diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml
index 75e9e36..cc6d97b 100644
--- a/.github/ISSUE_TEMPLATE/bug_report.yml
+++ b/.github/ISSUE_TEMPLATE/bug_report.yml
@@ -41,6 +41,7 @@ body:
- QR Code
- Lorem Ipsum
- Regex Tester
+ - Markdown Preview
- The site itself (⌘K palette, sidebar, shortcuts, saved state)
validations:
required: true
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 9367a42..d725c8c 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -62,7 +62,7 @@ jobs:
set -euo pipefail
pnpm pack --pack-destination "$RUNNER_TEMP" >/dev/null
LIST=$(tar -tzf "$RUNNER_TEMP"/fadeltd-devtools-core-*.tgz)
- for sub in base64 color cron css csv diff env escape hash html-text id-gen json json-types jwt list lorem number qr random regex share slug sql text text-bytes text-stats timestamp unicode url yaml-toml; do
+ for sub in base64 color cron css csv diff env escape hash html-text id-gen json json-types jwt list lorem markdown number qr random regex share slug sql text text-bytes text-stats timestamp unicode url yaml-toml; do
# A here-string, not `echo | grep -q`: grep -q stops reading at the
# first match, and under pipefail the writer's SIGPIPE fails the step.
grep -qx "package/dist/$sub/index.d.ts" <<< "$LIST" || { echo "::error::Missing dist/$sub/index.d.ts"; exit 1; }
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2e8add3..90c5820 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,7 +6,12 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and
## [Unreleased]
-Nothing yet.
+### Added
+- Markdown Preview: write or paste GitHub-flavoured Markdown beside a live preview. Copy formatted puts the rendered HTML and the Markdown source on the clipboard together, so a paste into Slack, Google Docs or Gmail keeps tables (with column alignment, escaped pipes, and links and ` ` line breaks inside cells), lists, links and monospace code, where a plain copy arrives as pipes and dashes. Copy Markdown copies just the source. Raw HTML in the source is shown as text, never run; links are limited to `http`, `https`, `mailto` and `tel`; remote images are not loaded, since the site makes no network requests. Rendering runs in a background worker, and the preview of a very long document shows its start while the copy carries all of it. (#28)
+- CSV to Table: Copy formatted, in the Table and Markdown views, copies the data as a real table (rich text, with TSV as the plain-text half), so it pastes into Slack, Docs, Gmail and spreadsheets as a table. Number columns are right-aligned and line breaks inside cells are kept. Offered up to 10,000 cells.
+
+### Fixed
+- CSV to Table: Ctrl/Cmd+Shift+C in the Table view copied nothing. It now copies the table.
## [0.16.0] — 2026-10-30
diff --git a/README.md b/README.md
index 2413241..134830a 100644
--- a/README.md
+++ b/README.md
@@ -36,6 +36,7 @@ It also does what the free sites usually don't: reports **every** JSON error wit
- **[Diff Checker](https://devtools.fadeltd.dev/diff)** — side-by-side or unified, word-level highlights, ignore whitespace or case, compare as sorted lines or key-sorted JSON, unified patch, share by link
- **[Regex Tester](https://devtools.fadeltd.dev/regex)** — JavaScript regex with every match, line and column, named and numbered groups, replace preview; runaway patterns can be cancelled
+- **[Markdown Preview](https://devtools.fadeltd.dev/markdown)** — GitHub-flavoured Markdown with a live preview; copy it as rich text and tables stay tables in Slack, Docs and Gmail
- **[List Tools](https://devtools.fadeltd.dev/list)** — sort, natural sort, dedupe, shuffle, filter and 11 more steps chained into a shareable pipeline
- **[Word Counter & Text Statistics](https://devtools.fadeltd.dev/text-stats)** — characters four ways, words, sentences, reading time, word frequency
- **[Unicode Inspector](https://devtools.fadeltd.dev/unicode)** — finds zero-width, bidi (Trojan Source) and other invisible characters, one-click clean
diff --git a/packages/core/CHANGELOG.md b/packages/core/CHANGELOG.md
index 5e58896..449b95a 100644
--- a/packages/core/CHANGELOG.md
+++ b/packages/core/CHANGELOG.md
@@ -6,7 +6,9 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and
## [Unreleased]
-Nothing yet.
+### Added
+- `/markdown`: `parseMarkdown(src)` turns GitHub-flavoured Markdown into a plain-data tree (`MdDoc`) that survives `structuredClone`, never throwing. Raw HTML comes back as the text it is, except ` `; character references are decoded once; link and image destinations pass `safeHref` / `safeImageSrc` or the node degrades to its text. `toHtml(doc)` serialises a tree to escaped HTML with a fixed tag set and the inline styles a rich-text paste needs (table borders, column alignment, monospace code). `limitDoc(doc, budget)` cuts a tree to a node budget for renderers that build real DOM, inside a long list or table if need be. Adds `marked` as a dependency, for its tokenizer only.
+- `/csv`: `toHtmlTable(table, types)` writes an HTML `
` for the clipboard, with cells escaped, line breaks as ` ` and number columns right-aligned.
## [0.8.0] — 2026-10-30
diff --git a/packages/core/README.md b/packages/core/README.md
index f67bb22..3e14b65 100644
--- a/packages/core/README.md
+++ b/packages/core/README.md
@@ -149,6 +149,7 @@ await formatSql('select a from t where b = 1', { dialect: 'postgresql', keywordC
| `/color` | CSS color parsing with positioned errors; sRGB ↔ HSL ↔ OKLCH; gamut detection and clipping; WCAG contrast and nearest passing foreground |
| `/qr` | QR payloads for text, URLs and Wi-Fi, encoded to a module matrix, plus a single-path SVG |
| `/regex` | Flag checks, readable compile errors, `/pattern/flags` literals, every match with line, column and named group spans (JavaScript semantics, capped), and `replace` with a count and warnings for references that silently do nothing |
+| `/markdown` | GitHub-flavoured Markdown to a plain-data tree (via `marked`'s tokenizer) and to escaped HTML for the clipboard, with raw HTML kept as text, a link-scheme allowlist, and a node budget for renderers |
| `/lorem` | Lorem ipsum by exact word, sentence or paragraph count, as text, HTML or Markdown, seedable |
| `/text` | Line/column offsets, character counts, UTF-8 size without encoding and long-line detection, shared by the tools |
| `/share` | Versioned, URL-safe compact encoding of any JSON value (deflate-raw + base64url) with a decode cap, for links that keep their content in the URL fragment |
diff --git a/packages/core/package.json b/packages/core/package.json
index 6537600..9ead30b 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -1,7 +1,7 @@
{
"name": "@fadeltd/devtools-core",
"version": "0.8.0",
- "description": "The engines behind devtools.fadeltd.dev: list pipelines, JSON errors and fixes, JSON to TypeScript, Zod and Go types, diff, base64, IDs and UUIDs, timestamps, JWT decoding and verification, URL encoding, hashes and HMAC, slugs, text bytes, number bases, Unicode inspection, YAML/JSON/TOML, SQL and CSS formatting, CSV, .env, cron, string escaping, colors and contrast, QR codes and lorem ipsum. Pure functions, no DOM, no network.",
+ "description": "The engines behind devtools.fadeltd.dev: list pipelines, JSON errors and fixes, JSON to TypeScript, Zod and Go types, diff, base64, IDs and UUIDs, timestamps, JWT decoding and verification, URL encoding, hashes and HMAC, slugs, text bytes, number bases, Unicode inspection, YAML/JSON/TOML, SQL and CSS formatting, CSV, .env, cron, string escaping, colors and contrast, QR codes, lorem ipsum and Markdown to HTML. Pure functions, no DOM, no network.",
"license": "MIT",
"type": "module",
"sideEffects": false,
@@ -70,6 +70,10 @@
"types": "./dist/lorem/index.d.ts",
"default": "./dist/lorem/index.js"
},
+ "./markdown": {
+ "types": "./dist/markdown/index.d.ts",
+ "default": "./dist/markdown/index.js"
+ },
"./number": {
"types": "./dist/number/index.d.ts",
"default": "./dist/number/index.js"
@@ -151,6 +155,7 @@
"cronstrue": "3.32.0",
"diff": "9.0.0",
"jsonc-parser": "3.3.1",
+ "marked": "18.1.2",
"smol-toml": "1.9.1",
"uqr": "0.1.3",
"yaml": "2.9.1"
@@ -218,7 +223,9 @@
"oklch",
"wcag contrast",
"qr code",
- "lorem ipsum"
+ "lorem ipsum",
+ "markdown",
+ "markdown to html"
],
"publishConfig": {
"access": "public"
diff --git a/packages/core/src/csv/serialize.test.ts b/packages/core/src/csv/serialize.test.ts
index 587078e..20763fb 100644
--- a/packages/core/src/csv/serialize.test.ts
+++ b/packages/core/src/csv/serialize.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
import { inferColumnTypes, valueType } from './infer.ts'
-import { formatTable, jsonKeys, quoteField, toDelimited, toJson, toMarkdown } from './serialize.ts'
+import { formatTable, jsonKeys, quoteField, toDelimited, toHtmlTable, toJson, toMarkdown } from './serialize.ts'
describe('quoteField', () => {
it('quotes only when needed', () => {
@@ -109,6 +109,54 @@ describe('toMarkdown', () => {
})
})
+describe('toHtmlTable', () => {
+ const CELL = 'border:1px solid #d0d7de;padding:4px 8px'
+
+ it('writes a header row and a body', () => {
+ expect(toHtmlTable({ header: ['a', 'b'], rows: [['1', '2']] })).toBe(
+ '
' +
+ `
a
b
` +
+ `
1
2
` +
+ '
',
+ )
+ })
+
+ it('has no header row when the header is off', () => {
+ const html = toHtmlTable({ header: null, rows: [['1', '2']] })
+ expect(html).not.toContain('')
+ expect(html).toContain(`
')).toThrow()
+ })
+
+ it('never throws, and writes only its own tags, attributes and schemes', () => {
+ fc.assert(
+ fc.property(fc.oneof(noisy, fc.string()), (src) => {
+ const { tags, attrs, schemes } = audit(html(src))
+ for (const t of tags) expect(TAGS.has(t)).toBe(true)
+ for (const a of attrs) expect(ATTRS.has(a)).toBe(true)
+ for (const s of schemes) expect(['http', 'https', 'mailto', 'tel', 'data']).toContain(s)
+ }),
+ { numRuns: 2000 },
+ )
+ })
+})
diff --git a/packages/core/src/markdown/html.ts b/packages/core/src/markdown/html.ts
new file mode 100644
index 0000000..91493e5
--- /dev/null
+++ b/packages/core/src/markdown/html.ts
@@ -0,0 +1,115 @@
+import { escapeHtml } from '../escape/html.ts'
+import type { MdAlign, MdBlock, MdDoc, MdInline, MdListItem } from './types.ts'
+
+// Inline styles, because a paste target keeps no stylesheet. Slack reads the
+// tags alone; Google Docs and Gmail need the borders and the font spelled out.
+const MONO = 'font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace'
+const CELL = 'border:1px solid #d0d7de;padding:4px 8px'
+const HEAD_CELL = `${CELL};font-weight:600`
+
+/** What a task-list item starts with. Characters, because a paste target drops ``. */
+export const TASK_OPEN = '☐ '
+export const TASK_DONE = '☑ '
+
+function inline(nodes: readonly MdInline[]): string {
+ let out = ''
+ for (const n of nodes) {
+ switch (n.type) {
+ case 'text':
+ out += escapeHtml(n.value)
+ break
+ case 'strong':
+ out += `${inline(n.children)}`
+ break
+ case 'em':
+ out += `${inline(n.children)}`
+ break
+ case 'del':
+ out += `${inline(n.children)}`
+ break
+ case 'code':
+ out += `${escapeHtml(n.value)}`
+ break
+ case 'link':
+ out +=
+ `${inline(n.children)}`
+ break
+ case 'image':
+ out +=
+ `'
+ break
+ case 'br':
+ out += ' '
+ break
+ }
+ }
+ return out
+}
+
+function cellStyle(base: string, align: MdAlign): string {
+ return align === null ? base : `${base};text-align:${align}`
+}
+
+function row(tag: 'th' | 'td', cells: readonly (readonly MdInline[])[], align: readonly MdAlign[], columns: number): string {
+ const base = tag === 'th' ? HEAD_CELL : CELL
+ let out = '
'
+ for (let c = 0; c < columns; c++) {
+ out += `<${tag} style="${cellStyle(base, align[c] ?? null)}">${inline(cells[c] ?? [])}${tag}>`
+ }
+ return out + '
'
+}
+
+function item(it: MdListItem): string {
+ const mark = it.task ? (it.checked ? TASK_DONE : TASK_OPEN) : ''
+ const [first, ...rest] = it.children
+ // The mark belongs on the first line of the item, so it goes inside the
+ // paragraph that opens it rather than in front of it.
+ if (mark !== '' && first !== undefined && (first.type === 'paragraph' || first.type === 'plain')) {
+ const head = first.type === 'paragraph' ? `
')],
+ },
+ ])
+ })
+})
+
+describe('parseMarkdown: links and images', () => {
+ it('reads inline, reference and automatic links', () => {
+ expect(para('[a](https://a.example "T") [b][r] https://d.example/x_y\n\n[r]: https://b.example')).toEqual([
+ { type: 'link', href: 'https://a.example', title: 'T', children: [text('a')] },
+ text(' '),
+ { type: 'link', href: 'https://b.example', title: null, children: [text('b')] },
+ text(' '),
+ { type: 'link', href: 'https://c.example', title: null, children: [text('https://c.example')] },
+ text(' '),
+ { type: 'link', href: 'https://d.example/x_y', title: null, children: [text('https://d.example/x_y')] },
+ ])
+ })
+
+ it('resolves references in a destination, but not in an autolink', () => {
+ expect(para('[a](https://x.example/?a&b)')).toMatchObject([{ href: 'https://x.example/?a&b' }])
+ expect(para('')).toMatchObject([{ href: 'https://x.example/?a&b' }])
+ })
+
+ it('keeps the text of a link it will not link', () => {
+ expect(para('[js](javascript:alert(1)) [d](data:text/html,x) [rel](/path) [h](#frag)')).toEqual([text('js d rel h')])
+ expect(para('[**b**](JaVaScRiPt:alert(1))')).toEqual([{ type: 'strong', children: [text('b')] }])
+ })
+
+ it('reads images, with alt text as plain text', () => {
+ expect(para('')).toEqual([
+ { type: 'image', src: 'https://i.example/x.png', alt: 'an alt', title: 'T' },
+ ])
+ expect(para('')).toEqual([
+ { type: 'image', src: 'data:image/png;base64,AAAA', alt: 'd', title: null },
+ ])
+ })
+
+ it('shows the alt text of an image it will not load', () => {
+ expect(para(')  ')).toEqual([text('alt rel h')])
+ })
+})
+
+describe('safeHref and safeImageSrc', () => {
+ it('allows only the listed schemes', () => {
+ expect(safeHref('https://a.example')).toBe('https://a.example')
+ expect(safeHref(' HTTP://a.example ')).toBe('HTTP://a.example')
+ expect(safeHref('mailto:a@b.example')).toBe('mailto:a@b.example')
+ expect(safeHref('tel:+15550100')).toBe('tel:+15550100')
+ for (const bad of ['javascript:alert(1)', 'java\nscript:alert(1)', 'data:text/html,x', 'vbscript:x', '//a.example', '/a', 'a', '#a', '']) {
+ expect(safeHref(bad)).toBeNull()
+ }
+ })
+
+ it('allows http(s) and inline image data', () => {
+ expect(safeImageSrc('https://i.example/x.png')).not.toBeNull()
+ expect(safeImageSrc('data:image/svg+xml;base64,AAAA')).not.toBeNull()
+ for (const bad of ['data:text/html,x', 'data:image/pngx,AA', 'javascript:x', 'x.png', 'blob:https://a/b']) {
+ expect(safeImageSrc(bad)).toBeNull()
+ }
+ })
+})
+
+function depthOf(bs: readonly MdBlock[]): number {
+ return bs.reduce((d, b) => Math.max(d, b.type === 'blockquote' ? 1 + depthOf(b.children) : 1), 0)
+}
+
+describe('parseMarkdown: hostile input', () => {
+ it('stops nesting at MAX_DEPTH instead of growing a tree as deep as the input', () => {
+ const doc = parseMarkdown(`${'> '.repeat(MAX_DEPTH * 4)}deep`)
+ expect(depthOf(doc.blocks)).toBeLessThanOrEqual(MAX_DEPTH + 2)
+ expect(JSON.stringify(doc)).toContain('deep')
+ })
+
+ it('does not throw on nesting far past what the tokenizer can take', () => {
+ expect(() => parseMarkdown('> '.repeat(20000) + 'x')).not.toThrow()
+ expect(() => parseMarkdown('['.repeat(20000))).not.toThrow()
+ // Emphasis delimiters are quadratic in the tokenizer: 50,000 take ~15 s,
+ // which is why the app only ever parses in a worker it can terminate.
+ expect(() => parseMarkdown('*'.repeat(3000) + 'a')).not.toThrow()
+ })
+})
diff --git a/packages/core/src/markdown/parse.ts b/packages/core/src/markdown/parse.ts
new file mode 100644
index 0000000..f29d8d1
--- /dev/null
+++ b/packages/core/src/markdown/parse.ts
@@ -0,0 +1,250 @@
+import { Lexer, type Token, type Tokens } from 'marked'
+import { decodeEntities } from '../html-text/entities.ts'
+import type { MdAlign, MdBlock, MdDoc, MdInline, MdListItem } from './types.ts'
+
+/**
+ * Past this depth a block is kept as its source text. Renderers recurse, so a
+ * paste of ten thousand nested `>` must not become ten thousand stack frames.
+ */
+export const MAX_DEPTH = 48
+
+const SAFE_HREF = /^(?:https?:\/\/|mailto:|tel:)/i
+
+/**
+ * The link schemes a rendered document may carry. Everything else comes back
+ * null: `javascript:` and `data:` because they run or smuggle content, and
+ * relative paths because they would resolve against whatever page shows the
+ * document, not the one the author meant.
+ */
+export function safeHref(href: string): string | null {
+ const h = href.trim()
+ return SAFE_HREF.test(h) ? h : null
+}
+
+const SAFE_IMAGE = /^(?:https?:\/\/|data:image\/(?:png|jpeg|gif|webp|avif|svg\+xml)[;,])/i
+
+/** `http(s)` and inline `data:image/…` only. An `` runs no script in either. */
+export function safeImageSrc(src: string): string | null {
+ const s = src.trim()
+ return SAFE_IMAGE.test(s) ? s : null
+}
+
+const BR_TAG = /^ $/i
+
+function pushText(out: MdInline[], value: string): void {
+ if (value === '') return
+ const last = out.at(-1)
+ if (last?.type === 'text') last.value += value
+ else out.push({ type: 'text', value })
+}
+
+/** The words of an inline run with the markup dropped: an image's alt text. */
+function plainText(nodes: readonly MdInline[]): string {
+ let out = ''
+ for (const n of nodes) {
+ switch (n.type) {
+ case 'text':
+ case 'code':
+ out += n.value
+ break
+ case 'image':
+ out += n.alt
+ break
+ case 'br':
+ out += ' '
+ break
+ default:
+ out += plainText(n.children)
+ }
+ }
+ return out
+}
+
+function inlines(tokens: readonly Token[] | undefined, depth: number): MdInline[] {
+ const out: MdInline[] = []
+ if (tokens === undefined) return out
+ for (const raw of tokens) {
+ if (depth > MAX_DEPTH) {
+ pushText(out, raw.raw)
+ continue
+ }
+ const t = raw as Tokens.Generic
+ switch (t.type) {
+ case 'text': {
+ const tok = t as Tokens.Text
+ if (tok.tokens !== undefined) {
+ for (const n of inlines(tok.tokens, depth + 1)) {
+ if (n.type === 'text') pushText(out, n.value)
+ else out.push(n)
+ }
+ } else {
+ // marked leaves named references in place for its HTML renderer to
+ // pass through; `escaped` marks text it took verbatim from raw HTML.
+ pushText(out, tok.escaped === true ? tok.text : decodeEntities(tok.text))
+ }
+ break
+ }
+ case 'escape':
+ pushText(out, (t as Tokens.Escape).text)
+ break
+ case 'html': {
+ // Raw HTML is never rendered: it is shown as the text it is. The one
+ // exception is , the only way to break a line inside a table cell.
+ const text = (t as Tokens.Tag).text
+ if (BR_TAG.test(text.trim())) out.push({ type: 'br' })
+ else pushText(out, text)
+ break
+ }
+ case 'br':
+ out.push({ type: 'br' })
+ break
+ case 'codespan':
+ out.push({ type: 'code', value: (t as Tokens.Codespan).text })
+ break
+ case 'strong':
+ case 'em':
+ case 'del':
+ out.push({ type: t.type, children: inlines(t.tokens, depth + 1) })
+ break
+ case 'link': {
+ const tok = t as Tokens.Link
+ const children = inlines(tok.tokens, depth + 1)
+ // An autolink's destination is literal; any other has references to resolve.
+ const href = safeHref(tok.autolink === true ? tok.href : decodeEntities(tok.href))
+ if (href === null) {
+ for (const n of children) {
+ if (n.type === 'text') pushText(out, n.value)
+ else out.push(n)
+ }
+ } else {
+ const title = tok.title == null || tok.title === '' ? null : decodeEntities(tok.title)
+ out.push({ type: 'link', href, title, children })
+ }
+ break
+ }
+ case 'image': {
+ const tok = t as Tokens.Image
+ const alt = plainText(inlines(tok.tokens, depth + 1))
+ const src = safeImageSrc(decodeEntities(tok.href))
+ if (src === null) pushText(out, alt)
+ else out.push({ type: 'image', src, alt, title: tok.title == null || tok.title === '' ? null : decodeEntities(tok.title) })
+ break
+ }
+ case 'checkbox':
+ // Carried by the list item's `task` and `checked`.
+ break
+ default:
+ pushText(out, t.raw)
+ }
+ }
+ return out
+}
+
+/** Text with its line breaks kept: a raw HTML block, shown as written. */
+function literalLines(text: string): MdInline[] {
+ const out: MdInline[] = []
+ const lines = text.replace(/\n+$/, '').split('\n')
+ lines.forEach((line, i) => {
+ if (i > 0) out.push({ type: 'br' })
+ pushText(out, line)
+ })
+ return out
+}
+
+function listItem(item: Tokens.ListItem, depth: number): MdListItem {
+ return { task: item.task, checked: item.checked === true, children: blocks(item.tokens, depth + 1) }
+}
+
+function clampDepth(depth: number): 1 | 2 | 3 | 4 | 5 | 6 {
+ return Math.min(6, Math.max(1, Math.trunc(depth))) as 1 | 2 | 3 | 4 | 5 | 6
+}
+
+function blocks(tokens: readonly Token[] | undefined, depth: number): MdBlock[] {
+ const out: MdBlock[] = []
+ if (tokens === undefined) return out
+ for (const raw of tokens) {
+ const t = raw as Tokens.Generic
+ if (t.type === 'space' || t.type === 'def' || t.type === 'checkbox') continue
+ if (depth > MAX_DEPTH) {
+ const children = literalLines(t.raw)
+ if (children.length > 0) out.push({ type: 'paragraph', children })
+ continue
+ }
+ switch (t.type) {
+ case 'heading':
+ out.push({ type: 'heading', depth: clampDepth((t as Tokens.Heading).depth), children: inlines(t.tokens, depth + 1) })
+ break
+ case 'paragraph':
+ out.push({ type: 'paragraph', children: inlines(t.tokens, depth + 1) })
+ break
+ case 'text': {
+ // A block-level text token is the body of a tight list item.
+ const tok = t as Tokens.Text
+ const children = tok.tokens === undefined ? inlines([tok], depth + 1) : inlines(tok.tokens, depth + 1)
+ const last = out.at(-1)
+ if (last?.type === 'plain') last.children.push({ type: 'text', value: '\n' }, ...children)
+ else out.push({ type: 'plain', children })
+ break
+ }
+ case 'blockquote':
+ out.push({ type: 'blockquote', children: blocks(t.tokens, depth + 1) })
+ break
+ case 'list': {
+ const tok = t as Tokens.List
+ out.push({
+ type: 'list',
+ ordered: tok.ordered,
+ start: typeof tok.start === 'number' ? tok.start : 1,
+ items: tok.items.map((item) => listItem(item, depth)),
+ })
+ break
+ }
+ case 'code': {
+ const tok = t as Tokens.Code
+ out.push({ type: 'code', lang: (tok.lang ?? '').trim().split(/\s+/)[0] ?? '', value: tok.text })
+ break
+ }
+ case 'table': {
+ const tok = t as Tokens.Table
+ const cell = (c: Tokens.TableCell) => inlines(c.tokens, depth + 1)
+ out.push({
+ type: 'table',
+ align: tok.align.map((a): MdAlign => a),
+ header: tok.header.map(cell),
+ rows: tok.rows.map((r) => r.map(cell)),
+ })
+ break
+ }
+ case 'hr':
+ out.push({ type: 'hr' })
+ break
+ case 'html': {
+ const children = literalLines((t as Tokens.HTML).text)
+ if (children.length > 0) out.push({ type: 'paragraph', children })
+ break
+ }
+ default: {
+ const children = literalLines(t.raw)
+ if (children.length > 0) out.push({ type: 'paragraph', children })
+ }
+ }
+ }
+ return out
+}
+
+/**
+ * Parse GitHub-flavoured Markdown into a tree. Never throws: input the
+ * tokenizer gives up on (pathological nesting) comes back as one code block
+ * holding the source, which is at least what was pasted.
+ *
+ * Raw HTML is not interpreted. Tags come back as the text they are, except
+ * ` `, which is a line break. Footnotes are not supported.
+ */
+export function parseMarkdown(src: string): MdDoc {
+ if (src === '') return { blocks: [] }
+ try {
+ return { blocks: blocks(Lexer.lex(src, { gfm: true }), 0) }
+ } catch {
+ return { blocks: [{ type: 'code', lang: '', value: src }] }
+ }
+}
diff --git a/packages/core/src/markdown/types.ts b/packages/core/src/markdown/types.ts
new file mode 100644
index 0000000..e52ab92
--- /dev/null
+++ b/packages/core/src/markdown/types.ts
@@ -0,0 +1,44 @@
+/**
+ * The document tree. Plain data: it survives `structuredClone`, so a worker
+ * can post it, and it carries nothing of the parser that produced it.
+ *
+ * Every string in it is plain text, already decoded. Nothing is HTML, so a
+ * renderer must escape (or hand it to something that does, like React).
+ */
+
+export type MdAlign = 'left' | 'center' | 'right' | null
+
+export type MdInline =
+ | { type: 'text'; value: string }
+ | { type: 'strong'; children: MdInline[] }
+ | { type: 'em'; children: MdInline[] }
+ | { type: 'del'; children: MdInline[] }
+ | { type: 'code'; value: string }
+ /** `href` has passed `safeHref`: a link that failed it is not a link node. */
+ | { type: 'link'; href: string; title: string | null; children: MdInline[] }
+ /** `src` has passed `safeImageSrc`. */
+ | { type: 'image'; src: string; alt: string; title: string | null }
+ | { type: 'br' }
+
+export interface MdListItem {
+ task: boolean
+ /** Meaningful only when `task` is true. */
+ checked: boolean
+ children: MdBlock[]
+}
+
+export type MdBlock =
+ | { type: 'heading'; depth: 1 | 2 | 3 | 4 | 5 | 6; children: MdInline[] }
+ | { type: 'paragraph'; children: MdInline[] }
+ /** Inline content with no paragraph around it: the body of a tight list item. */
+ | { type: 'plain'; children: MdInline[] }
+ | { type: 'blockquote'; children: MdBlock[] }
+ | { type: 'list'; ordered: boolean; start: number; items: MdListItem[] }
+ | { type: 'code'; lang: string; value: string }
+ /** `header` is empty for a table with no header row (CSV with the header off). */
+ | { type: 'table'; align: MdAlign[]; header: MdInline[][]; rows: MdInline[][][] }
+ | { type: 'hr' }
+
+export interface MdDoc {
+ blocks: MdBlock[]
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 3a3054e..d65550b 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -129,6 +129,9 @@ importers:
jsonc-parser:
specifier: 3.3.1
version: 3.3.1
+ marked:
+ specifier: 18.1.2
+ version: 18.1.2
smol-toml:
specifier: 1.9.1
version: 1.9.1
@@ -2741,6 +2744,11 @@ packages:
magic-string@1.4.1:
resolution: {integrity: sha512-8lyCu36ErXR0J9uaGKlKQoiLZKmtI63YGLE8G2o9jyRPdr4X47LusSOwgOJOzcVtp81fTAAjxR7BwKz682Jhow==}
+ marked@18.1.2:
+ resolution: {integrity: sha512-DfOnvLAQ6WYeWxWO1u4RyFOeqyHup6dks5PPqnoFiooU7ipRvidO/2j8plhAHIiZg574E9ZlzSjUiPMLAzFkgg==}
+ engines: {node: '>= 20'}
+ hasBin: true
+
math-intrinsics@1.1.0:
resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==}
engines: {node: '>= 0.4'}
@@ -5810,6 +5818,8 @@ snapshots:
dependencies:
'@jridgewell/sourcemap-codec': 1.6.0
+ marked@18.1.2: {}
+
math-intrinsics@1.1.0: {}
miniflare@5.20260921.0-alpha(@types/node@24.9.2):
diff --git a/src/components/ui/CopyButton.tsx b/src/components/ui/CopyButton.tsx
index 41ce28f..735cde3 100644
--- a/src/components/ui/CopyButton.tsx
+++ b/src/components/ui/CopyButton.tsx
@@ -1,34 +1,84 @@
import { useState } from 'react'
import { Check, Copy } from 'lucide-react'
-import { copyText } from '@/lib/util/clipboard'
+import { copyRich, copyText } from '@/lib/util/clipboard'
import { Button } from './Button'
-export function CopyButton({
- value,
- label = 'Copy',
+function CopyFace({
+ label,
disabled,
+ title,
+ copy,
}: {
- value: string
- label?: string
- disabled?: boolean
+ label: string
+ disabled: boolean
+ title: string
+ copy: () => Promise
}) {
const [copied, setCopied] = useState(false)
return (
)
}
+
+export function CopyButton({
+ value,
+ label = 'Copy',
+ disabled,
+}: {
+ value: string
+ label?: string
+ disabled?: boolean
+}) {
+ return (
+ copyText(value)}
+ />
+ )
+}
+
+/**
+ * Copies rich text with a plain-text twin, so a paste into Slack, Google Docs
+ * or Gmail keeps tables and formatting. `html` must already be built when the
+ * button is clicked: the clipboard write has to happen in the click itself.
+ */
+export function RichCopyButton({
+ html,
+ text,
+ label = 'Copy formatted',
+ title,
+ disabled,
+}: {
+ html: string
+ text: string
+ label?: string
+ /** Say why when the button is disabled; a tooltip is all a disabled button has. */
+ title?: string | undefined
+ disabled?: boolean
+}) {
+ return (
+ copyRich(html, text)}
+ />
+ )
+}
diff --git a/src/lib/registry/about.ts b/src/lib/registry/about.ts
index 666cf6b..560106f 100644
--- a/src/lib/registry/about.ts
+++ b/src/lib/registry/about.ts
@@ -36,4 +36,5 @@ export const ABOUT: Record = {
'sql': 'Formatting uses sql-formatter across 12 dialects, from standard SQL and PostgreSQL to BigQuery, T-SQL, Spark and Trino, and a parse or lexer error is reported at its line and column. Minifying is separate and dialect-aware: string literals, quoted identifiers and dollar-quoted bodies are left untouched, backslash escapes are read only where the dialect has them, # starts a comment only in MySQL-like dialects, and BigQuery triple-quoted strings are understood. Comments are kept by default and can be stripped, except optimizer hints and MySQL versioned comments.',
'css': 'Pretty-printing uses Prettier with its PostCSS parser, so CSS, SCSS and Less are all handled, and a syntax error or an unclosed block is reported at its line and column. The CSS minifier keeps /*! licence comments, the spaces calc() needs around + and -, the space that makes a descendant pseudo-class, and the space that ends a hex escape, and it leaves strings and unquoted url(data:...) bodies verbatim. It is idempotent, even on malformed input, and it drops the last semicolon in each block and any empty declarations.',
'regex': 'Patterns run on your browser’s own JavaScript engine in a background worker, so one that backtracks without end, like (a+)+$, can be cancelled instead of freezing the tab. Matching follows JavaScript exactly: every match with g, only the first without it, and an empty match steps forward a whole code point under u or v. Each match lists its line, column and every capture group by number and name, and a group that did not take part is shown as such, not as an empty string. Replace mode expands $1, $ and $& as String.replace does, and warns when $3 names a missing group or $0 was meant as the whole match.',
+ 'markdown': 'GitHub-flavoured Markdown is parsed in a background worker with the marked tokenizer and drawn as real elements, never as an HTML string, so nothing you paste can run. Copy formatted puts the rendered HTML and the Markdown source on the clipboard together: pasted into Slack, Google Docs or Gmail a table stays a table, with column alignment, escaped pipes, links and line breaks inside cells kept, and code staying monospace. Raw HTML in the source is shown as the text it is rather than interpreted, apart from . Links are limited to http, https, mailto and tel, so a javascript: link becomes plain text. Remote images are not loaded, because this site makes no network requests; the copied HTML still points at them. Footnotes and syntax highlighting are not supported, and the preview of a very long document shows only its start, while the copy carries all of it.',
}
diff --git a/src/lib/registry/index.ts b/src/lib/registry/index.ts
index a6982c3..5849102 100644
--- a/src/lib/registry/index.ts
+++ b/src/lib/registry/index.ts
@@ -10,6 +10,7 @@ import {
FileDigit,
FileType,
FileKey2,
+ FileText,
Fingerprint,
GitCompare,
KeyRound,
@@ -495,6 +496,18 @@ const RAW_TOOLS = [
stateVersion: 1,
status: 'beta',
},
+ {
+ slug: 'markdown',
+ title: 'Markdown Preview',
+ blurb: 'Write Markdown beside a live preview, and copy it as rich text that keeps its tables in Slack, Docs and Gmail.',
+ keywords: ['markdown', 'md', 'markdown preview', 'markdown editor', 'gfm', 'markdown table', 'markdown to html', 'rich text', 'copy formatted', 'slack table', 'paste table'],
+ category: 'text',
+ icon: FileText,
+ load: () => import('@/tools/markdown/MarkdownTool'),
+ store: { kind: 'idb' },
+ stateVersion: 1,
+ status: 'beta',
+ },
] as const satisfies readonly ToolDef[]
/** The literal union that keeps persistence keys, links and pins honest. */
diff --git a/src/lib/util/clipboard.ts b/src/lib/util/clipboard.ts
index 8f0fe16..bf91e29 100644
--- a/src/lib/util/clipboard.ts
+++ b/src/lib/util/clipboard.ts
@@ -1,9 +1,3 @@
-/**
- * Copy text to the clipboard.
- *
- * MUST be called directly inside a click/keydown handler. Safari rejects a
- * clipboard write that happens after an await or from an effect, silently.
- */
export async function copyText(text: string): Promise {
try {
await navigator.clipboard.writeText(text)
@@ -12,3 +6,81 @@ export async function copyText(text: string): Promise {
return false
}
}
+
+/**
+ * The route for browsers with no `ClipboardItem` (Firefox before 127) and for
+ * pages not served over HTTPS, where `navigator.clipboard` does not exist.
+ * `execCommand('copy')` fires a `copy` event whose data we replace, so both
+ * flavours land on the clipboard without the HTML ever entering the DOM.
+ * Safari only fires the event when something is selected, hence the probe.
+ */
+function copyRichLegacy(html: string, text: string): boolean {
+ const selection = document.getSelection()
+ const saved: Range[] = []
+ if (selection !== null) {
+ for (let i = 0; i < selection.rangeCount; i++) saved.push(selection.getRangeAt(i))
+ }
+ const active = document.activeElement
+
+ const probe = document.createElement('span')
+ probe.textContent = ' '
+ probe.setAttribute('aria-hidden', 'true')
+ probe.style.cssText = 'position:fixed;top:0;left:0;opacity:0;pointer-events:none;user-select:text'
+ document.body.append(probe)
+
+ let handled = false
+ const onCopy = (e: ClipboardEvent) => {
+ if (e.clipboardData === null) return
+ e.clipboardData.setData('text/html', html)
+ e.clipboardData.setData('text/plain', text)
+ e.preventDefault()
+ handled = true
+ }
+ document.addEventListener('copy', onCopy, true)
+ try {
+ const range = document.createRange()
+ range.selectNodeContents(probe)
+ selection?.removeAllRanges()
+ selection?.addRange(range)
+ // Deprecated, and still the only synchronous way to reach the clipboard.
+ return document.execCommand('copy') && handled
+ } catch {
+ return false
+ } finally {
+ document.removeEventListener('copy', onCopy, true)
+ probe.remove()
+ selection?.removeAllRanges()
+ for (const r of saved) selection?.addRange(r)
+ if (active instanceof HTMLElement) active.focus({ preventScroll: true })
+ }
+}
+
+/**
+ * Put rich text on the clipboard, with a plain-text twin. A paste into Slack,
+ * Google Docs or Gmail takes `text/html` and keeps tables and formatting; a
+ * paste into a terminal or a code editor takes `text/plain`.
+ *
+ * Call it straight from the click handler, as with `copyText`: both routes
+ * need the user gesture, and the legacy one is synchronous by nature.
+ */
+export async function copyRich(html: string, text: string): Promise {
+ if (typeof ClipboardItem !== 'undefined' && typeof navigator.clipboard?.write === 'function') {
+ try {
+ await navigator.clipboard.write([
+ new ClipboardItem({
+ 'text/html': new Blob([html], { type: 'text/html' }),
+ 'text/plain': new Blob([text], { type: 'text/plain' }),
+ }),
+ ])
+ return true
+ } catch {
+ // Permission denied or an unsupported type. The gesture may be spent by
+ // now, in which case the legacy route fails too and we report that.
+ }
+ }
+ try {
+ return copyRichLegacy(html, text)
+ } catch {
+ return false
+ }
+}
diff --git a/src/tools/csv/CsvTool.tsx b/src/tools/csv/CsvTool.tsx
index c4061bf..0492beb 100644
--- a/src/tools/csv/CsvTool.tsx
+++ b/src/tools/csv/CsvTool.tsx
@@ -5,17 +5,18 @@ import { TwoPane } from '@/components/layout/TwoPane'
import { Badge } from '@/components/ui/Badge'
import { Button } from '@/components/ui/Button'
import { CodeArea } from '@/components/ui/CodeArea'
-import { CopyButton } from '@/components/ui/CopyButton'
+import { CopyButton, RichCopyButton } from '@/components/ui/CopyButton'
import { Select, Toggle } from '@/components/ui/Select'
import { useToolState } from '@/lib/persist/useToolState'
import { useShortcuts } from '@/lib/keys/useShortcuts'
import { useToolUsageTracker } from '@/lib/prefs'
-import { copyText } from '@/lib/util/clipboard'
+import { copyRich, copyText } from '@/lib/util/clipboard'
import { formatCount } from '@/lib/util/bytes'
import { useWorkerJob, type JobStatus } from '@/lib/worker/useWorkerJob'
import type { CsvIssue, Delimiter } from '@fadeltd/devtools-core/csv'
import { CsvGrid } from './CsvGrid'
import type { CsvApi, CsvFormat, CsvRunInput, CsvRunResult } from './csv.worker'
+import { RICH_CELL_LIMIT } from './limits'
type DelimiterChoice = Delimiter | 'auto'
@@ -110,6 +111,9 @@ export default function CsvTool() {
// in flight, so draw what the result holds, not what the control says.
const shownFormat = result?.format ?? state.format
const output = result?.output ?? ''
+ const rich = result?.rich ?? null
+ // Offered where the output is a table to look at or to paste as one.
+ const offersRich = state.format === 'table' || state.format === 'markdown'
const current = job.status === 'done' && deferredText === state.text
const inputRef = useRef(null)
@@ -136,7 +140,12 @@ export default function CsvTool() {
scope: 'tool',
whileTyping: true,
run: () => {
- if (output !== '') void copyText(output)
+ // The table view has no text output: what it copies is the table.
+ if (shownFormat === 'table') {
+ if (rich !== null) void copyRich(rich.html, rich.text)
+ } else if (output !== '') {
+ void copyText(output)
+ }
},
},
])
@@ -200,6 +209,17 @@ export default function CsvTool() {
))}
+ {offersRich && (
+ RICH_CELL_LIMIT
+ ? `Too large to copy as a table (over ${formatCount(RICH_CELL_LIMIT)} cells). Copy it as CSV or TSV instead`
+ : undefined
+ }
+ />
+ )}
{state.format !== 'table' && }