The open-source full-stack studio for Opus 5.5 motion video. Reverse engineering for any video. Code video with HTML: recreate, edit and render. BYOA + BYOK · Motion.md · Images, Video, Music & Voice.
TypeScript agent-skillsagentic-aiai-agentsai-videobyokclaude-codecodexdeepseek-harnessdsh-plugingenerative-ailocal-firstmcpmotionmotion-graphicsmultimodalopenmotionreverse-engineeringvideo-editingvideo-generationworkbuddy
feat(export): add Notion, Bilibili, Mastodon, Bluesky, Markdown round-trip targets (#19)
steve wu122b780e1a81
diff --git a/next/src/lib/export/__tests__/bilibili.test.ts b/next/src/lib/export/__tests__/bilibili.test.tsnew file mode 100644index 00000000..9d3be03f--- /dev/null+++ b/next/src/lib/export/__tests__/bilibili.test.ts@@ -0,0 +1,148 @@+/**+ * Tests for the Bilibili 专栏 HTML sanitizer. The sanitizer runs in a real+ * (happy-dom) browser-like environment so it exercises the actual DOMParser+ * + Element APIs the production code uses. Each test parses the cleaned+ * output back through DOMParser and asserts on the resulting tree shape.+ */+import { describe, it, expect } from "vitest";+import { toBilibiliHtml } from "../bilibili";++function parseFragment(html: string): HTMLBodyElement {+ return new DOMParser().parseFromString(`<body>${html}</body>`, "text/html")+ .body as HTMLBodyElement;+}++describe("toBilibiliHtml — whitelist enforcement", () => {+ it("strips <script>/<iframe>/<style> wrappers entirely", () => {+ const html = toBilibiliHtml(+ "<p>keep</p><script>alert(1)</script><iframe></iframe><style>p{}</style>",+ );+ const body = parseFragment(html);+ expect(body.querySelector("script")).toBeNull();+ expect(body.querySelector("iframe")).toBeNull();+ expect(body.querySelector("style")).toBeNull();+ expect(body.querySelector("p")?.textContent).toBe("keep");+ });++ it("unwraps <div>/<section> but keeps their children", () => {+ const html = toBilibiliHtml(+ "<div><section><p>a</p></section><p>b</p></div>",+ );+ const body = parseFragment(html);+ expect(body.querySelector("div")).toBeNull();+ expect(body.querySelector("section")).toBeNull();+ const ps = Array.from(body.querySelectorAll("p")).map((p) => p.textContent);+ expect(ps).toEqual(["a", "b"]);+ });++ it("preserves headings, lists, code, blockquotes, hr, br", () => {+ const html = toBilibiliHtml(+ "<h2>Title</h2><ul><li>x</li></ul><pre><code>k</code></pre><blockquote>q</blockquote><hr><br>",+ );+ const body = parseFragment(html);+ expect(body.querySelector("h2")?.textContent).toBe("Title");+ expect(body.querySelector("ul li")?.textContent).toBe("x");+ expect(body.querySelector("pre code")?.textContent).toBe("k");+ expect(body.querySelector("blockquote")?.textContent).toBe("q");+ expect(body.querySelector("hr")).not.toBeNull();+ expect(body.querySelector("br")).not.toBeNull();+ });+});++describe("toBilibiliHtml — attribute filtering", () => {+ it("drops all attributes except those in the allow-list", () => {+ const html = toBilibiliHtml(+ '<p class="foo" data-x="y" onclick="alert(1)" id="z">hi</p>',+ );+ const p = parseFragment(html).querySelector("p");+ expect(p?.getAttribute("class")).toBeNull();+ expect(p?.getAttribute("data-x")).toBeNull();+ expect(p?.getAttribute("onclick")).toBeNull();+ expect(p?.getAttribute("id")).toBeNull();+ expect(p?.textContent).toBe("hi");+ });++ it("keeps href and title on <a>, drops javascript: hrefs", () => {+ const html = toBilibiliHtml(+ '<p><a href="https://example.com" title="t">ok</a> ' ++ '<a href="javascript:alert(1)">bad</a></p>',+ );+ const anchors = Array.from(parseFragment(html).querySelectorAll("a"));+ expect(anchors[0].getAttribute("href")).toBe("https://example.com");+ expect(anchors[0].getAttribute("title")).toBe("t");+ expect(anchors[1].hasAttribute("href")).toBe(false);+ });++ it("keeps only language-* classes on <code>", () => {+ const html = toBilibiliHtml(+ '<pre><code class="hljs language-ts other">x</code></pre>',+ );+ const code = parseFragment(html).querySelector("code");+ // Whitespace allowed, but the only token retained is language-ts.+ const tokens = (code?.getAttribute("class") ?? "")+ .split(/\s+/)+ .filter(Boolean);+ expect(tokens).toEqual(["language-ts"]);+ });++ it("removes the class attribute entirely when no language-* token survives", () => {+ const html = toBilibiliHtml(+ '<pre><code class="hljs token-keyword">x</code></pre>',+ );+ const code = parseFragment(html).querySelector("code");+ expect(code?.hasAttribute("class")).toBe(false);+ });+});++describe("toBilibiliHtml — image rewriting", () => {+ it("leaves bilibili CDN images intact", () => {+ const html = toBilibiliHtml(+ '<p><img src="https://i0.hdslb.com/x.png" alt="a"></p>',+ );+ const img = parseFragment(html).querySelector("img");+ expect(img?.getAttribute("src")).toBe("https://i0.hdslb.com/x.png");+ expect(img?.getAttribute("alt")).toBe("a");+ expect(img?.hasAttribute("data-bili-placeholder")).toBe(false);+ });++ it("replaces non-CDN images with a placeholder SVG and stashes the original src", () => {+ const html = toBilibiliHtml(+ '<p><img src="https://imgur.com/foo.png" alt="ext"></p>',+ );+ const img = parseFragment(html).querySelector("img");+ expect(img?.getAttribute("data-original-src")).toBe(+ "https://imgur.com/foo.png",+ );+ expect(img?.getAttribute("data-bili-placeholder")).toBe("true");+ expect(img?.getAttribute("src")).toMatch(/^data:image\/svg\+xml/);+ expect(img?.getAttribute("alt")).toBe("ext");+ });++ it("rejects lookalike hostnames (no subdomain dot before the literal)", () => {+ // `evilhdslb.com` and `notbilibili.com` would slip past a `[^/]*` regex+ // and skip the placeholder swap — both must be treated as non-CDN.+ for (const src of [+ "https://evilhdslb.com/foo.png",+ "https://notbilibili.com/foo.png",+ ]) {+ const html = toBilibiliHtml(`<p><img src="${src}" alt="x"></p>`);+ const img = parseFragment(html).querySelector("img");+ expect(img?.getAttribute("data-bili-placeholder")).toBe("true");+ expect(img?.getAttribute("data-original-src")).toBe(src);+ }+ });++ it("accepts subdomains of the bilibili CDN", () => {+ for (const src of [+ "https://i0.hdslb.com/bfs/x.png",+ "https://album.bilibili.com/x.png",+ "https://hdslb.com/x.png", // bare apex+ "https://bilibili.com/foo.png", // bare apex+ ]) {+ const html = toBilibiliHtml(`<p><img src="${src}" alt="x"></p>`);+ const img = parseFragment(html).querySelector("img");+ expect(img?.hasAttribute("data-bili-placeholder")).toBe(false);+ expect(img?.getAttribute("src")).toBe(src);+ }+ });+});diff --git a/next/src/lib/export/__tests__/markdown-roundtrip.test.ts b/next/src/lib/export/__tests__/markdown-roundtrip.test.tsnew file mode 100644index 00000000..d2377f32--- /dev/null+++ b/next/src/lib/export/__tests__/markdown-roundtrip.test.ts@@ -0,0 +1,356 @@+/**+ * Tests for the HTML → Markdown emitter. Each case is verified two ways:+ * 1. The emitted Markdown matches expectations (substring / regex / exact).+ * 2. The emitted Markdown is fed through `marked` (a real CommonMark/GFM+ * parser, also a runtime dependency) and the resulting HTML is asserted+ * to round-trip the structural intent. This is the closest "simulate+ * real" check we can do without spinning up Hugo / 11ty / Obsidian.+ */+import { describe, it, expect, beforeAll } from "vitest";+import { marked } from "marked";++import { htmlToMarkdown } from "../markdown-roundtrip";++beforeAll(() => {+ marked.setOptions({ async: false, gfm: true, breaks: false });+});++function mdToDoc(md: string): Document {+ const html = marked.parse(md) as string;+ return new DOMParser().parseFromString(`<body>${html}</body>`, "text/html");+}++function roundtripTags(html: string): string[] {+ const md = htmlToMarkdown(html);+ const doc = mdToDoc(md);+ return Array.from(doc.body.children).map((c) => c.tagName.toLowerCase());+}++describe("htmlToMarkdown — headings", () => {+ it("emits ATX headings for h1–h6", () => {+ for (let lvl = 1; lvl <= 6; lvl++) {+ const md = htmlToMarkdown(`<h${lvl}>Title ${lvl}</h${lvl}>`);+ expect(md).toContain(`${"#".repeat(lvl)} Title ${lvl}`);+ const doc = mdToDoc(md);+ const h = doc.body.querySelector(`h${lvl}`);+ expect(h?.textContent).toBe(`Title ${lvl}`);+ }+ });+});++describe("htmlToMarkdown — paragraphs and inline marks", () => {+ it("renders **strong**, *em*, ~~del~~", () => {+ const md = htmlToMarkdown(+ "<p><strong>bold</strong> <em>it</em> <s>gone</s></p>",+ );+ expect(md).toMatch(/\*\*bold\*\*/);+ expect(md).toMatch(/\*it\*/);+ expect(md).toMatch(/~~gone~~/);+ const doc = mdToDoc(md);+ expect(doc.body.querySelector("strong")?.textContent).toBe("bold");+ expect(doc.body.querySelector("em")?.textContent).toBe("it");+ expect(doc.body.querySelector("del,s")?.textContent).toBe("gone");+ });++ it("escapes literal *, _, ~ in plain text so they don't become marks", () => {+ const md = htmlToMarkdown("<p>5 * 3 = 15 and _foo_ and ~~bar~~ literal</p>");+ // None of these should round-trip as <em>/<strong>/<del>.+ const doc = mdToDoc(md);+ expect(doc.body.querySelector("em")).toBeNull();+ expect(doc.body.querySelector("strong")).toBeNull();+ expect(doc.body.querySelector("del,s")).toBeNull();+ expect(doc.body.textContent).toContain("5 * 3 = 15");+ expect(doc.body.textContent).toContain("_foo_");+ expect(doc.body.textContent).toContain("~~bar~~");+ });+});++describe("htmlToMarkdown — inline code with backticks", () => {+ it("handles content containing a single backtick with a longer fence", () => {+ const md = htmlToMarkdown("<p>see <code>a `b` c</code> done</p>");+ const doc = mdToDoc(md);+ const code = doc.body.querySelector("code");+ expect(code).not.toBeNull();+ // The textContent must include the literal backticks, not be split by them.+ expect(code!.textContent).toContain("`b`");+ });++ it("handles content starting and ending with a backtick", () => {+ const md = htmlToMarkdown("<p><code>`tick`</code></p>");+ const doc = mdToDoc(md);+ const code = doc.body.querySelector("code");+ expect(code!.textContent?.trim()).toBe("`tick`");+ });+});++describe("htmlToMarkdown — fenced code blocks", () => {+ it("uses the language hint from class=language-*", () => {+ const md = htmlToMarkdown(+ '<pre><code class="language-ts">const x: number = 1;</code></pre>',+ );+ expect(md).toMatch(/```ts\nconst x: number = 1;\n```/);+ const doc = mdToDoc(md);+ expect(doc.body.querySelector("pre code")?.textContent?.trim()).toBe(+ "const x: number = 1;",+ );+ });++ it("uses a longer fence when the body contains triple backticks", () => {+ const md = htmlToMarkdown(+ "<pre><code>before\n```\nfake fence inside\n```\nafter</code></pre>",+ );+ // Body still has the original triple backticks; the outer fence is longer.+ expect(md).toContain("```\nfake fence inside\n```");+ // Outer fence is at least 4 backticks long.+ expect(md).toMatch(/````+\n[\s\S]*```\nfake fence inside\n```/);+ const doc = mdToDoc(md);+ const code = doc.body.querySelector("pre code");+ expect(code?.textContent).toContain("fake fence inside");+ expect(code?.textContent).toContain("before");+ expect(code?.textContent).toContain("after");+ });+});++describe("htmlToMarkdown — links and images", () => {+ it("emits a plain [text](url) for simple links", () => {+ const md = htmlToMarkdown(+ '<p><a href="https://example.com">site</a></p>',+ );+ expect(md).toMatch(/\[site\]\(https:\/\/example\.com\)/);+ const a = mdToDoc(md).body.querySelector("a");+ expect(a?.getAttribute("href")).toBe("https://example.com");+ expect(a?.textContent).toBe("site");+ });++ it("wraps URLs containing spaces or parens with <…>", () => {+ const md = htmlToMarkdown(+ '<p><a href="https://example.com/foo (bar)/baz">click</a></p>',+ );+ expect(md).toContain("(<https://example.com/foo (bar)/baz>)");+ // marked URL-encodes spaces during HTML rendering — verify the decoded+ // form so we're testing the source-of-truth (the markdown the user pastes+ // into Hugo/Obsidian preserves the unencoded URL).+ const a = mdToDoc(md).body.querySelector("a");+ expect(decodeURI(a?.getAttribute("href") ?? "")).toBe(+ "https://example.com/foo (bar)/baz",+ );+ });++ it("escapes quotes and backslashes inside the title", () => {+ const md = htmlToMarkdown(+ '<p><a href="https://x.com" title="say "hi" \\back">t</a></p>',+ );+ // Title quotes are backslash-escaped, so the link form remains valid.+ expect(md).toMatch(/"say \\"hi\\" \\\\back"/);+ const a = mdToDoc(md).body.querySelector("a");+ expect(a?.getAttribute("title")).toBe('say "hi" \\back');+ });++ it("escapes [ and ] inside link text", () => {+ const md = htmlToMarkdown(+ '<p><a href="https://x.com">[bracketed] text</a></p>',+ );+ expect(md).toMatch(/\\\[bracketed\\\] text/);+ const a = mdToDoc(md).body.querySelector("a");+ expect(a?.textContent).toBe("[bracketed] text");+ });++ it("renders images with alt, src and optional title", () => {+ const md = htmlToMarkdown(+ '<p><img src="https://x.com/a.png" alt="hello" title="t"></p>',+ );+ expect(md).toMatch(/!\[hello\]\(https:\/\/x\.com\/a\.png "t"\)/);+ const img = mdToDoc(md).body.querySelector("img");+ expect(img?.getAttribute("src")).toBe("https://x.com/a.png");+ expect(img?.getAttribute("alt")).toBe("hello");+ expect(img?.getAttribute("title")).toBe("t");+ });++ it("preserves <img> nested inside <a> (badge-style link)", () => {+ const md = htmlToMarkdown(+ '<p><a href="https://repo.example/owner/proj"><img src="https://shields.io/badge.svg" alt="badge"></a></p>',+ );+ const doc = mdToDoc(md);+ const a = doc.body.querySelector("a");+ expect(a?.getAttribute("href")).toBe(+ "https://repo.example/owner/proj",+ );+ // The image must still be a child of the <a>, not flattened to text.+ const img = a?.querySelector("img");+ expect(img).not.toBeNull();+ expect(img?.getAttribute("src")).toBe("https://shields.io/badge.svg");+ expect(img?.getAttribute("alt")).toBe("badge");+ });++ it("preserves <code> nested inside <a>", () => {+ const md = htmlToMarkdown(+ '<p><a href="https://example.com"><code>foo</code></a></p>',+ );+ const doc = mdToDoc(md);+ const a = doc.body.querySelector("a");+ const code = a?.querySelector("code");+ expect(code).not.toBeNull();+ expect(code?.textContent).toBe("foo");+ // No stray backslashes inside the code span.+ expect(code?.textContent).not.toContain("\\");+ });+});++describe("htmlToMarkdown — line-start block-marker escaping", () => {+ it("escapes a paragraph that starts with '1. ' so it stays a paragraph", () => {+ const tags = roundtripTags("<p>1. First item, not a list</p>");+ expect(tags).toEqual(["p"]);+ });++ it("escapes a paragraph starting with '# '", () => {+ const tags = roundtripTags("<p># Not a heading</p>");+ expect(tags).toEqual(["p"]);+ });++ it("escapes a paragraph starting with '> '", () => {+ const tags = roundtripTags("<p>> Not a quote</p>");+ expect(tags).toEqual(["p"]);+ });++ it("escapes a paragraph starting with '- '", () => {+ const tags = roundtripTags("<p>- Not a bullet</p>");+ expect(tags).toEqual(["p"]);+ });++ it("does NOT escape mid-text markers", () => {+ // "#hashtag" mid-text is not a heading and should not be escaped.+ const md = htmlToMarkdown("<p>see #hashtag here</p>");+ expect(md).not.toMatch(/\\#hashtag/);+ });+});++describe("htmlToMarkdown — lists", () => {+ it("renders a simple unordered list", () => {+ const md = htmlToMarkdown("<ul><li>a</li><li>b</li></ul>");+ const doc = mdToDoc(md);+ const items = Array.from(doc.body.querySelectorAll("ul > li")).map(+ (li) => li.textContent?.trim(),+ );+ expect(items).toEqual(["a", "b"]);+ });++ it("renders a nested list with correct indentation", () => {+ const md = htmlToMarkdown(+ "<ul><li>outer<ul><li>inner-a</li><li>inner-b</li></ul></li><li>other</li></ul>",+ );+ const doc = mdToDoc(md);+ const outer = doc.body.querySelector("ul");+ const innerLis = outer+ ?.querySelector("li > ul")+ ?.querySelectorAll(":scope > li");+ expect(innerLis?.length).toBe(2);+ expect(innerLis?.[0].textContent?.trim()).toBe("inner-a");+ });++ it("renders a list item with a paragraph and a code block inside", () => {+ const md = htmlToMarkdown(+ "<ol><li><p>step one</p><pre><code class=\"language-js\">x++;</code></pre></li><li>step two</li></ol>",+ );+ const doc = mdToDoc(md);+ const lis = doc.body.querySelectorAll("ol > li");+ expect(lis.length).toBe(2);+ // First <li> contains both a paragraph and a fenced code block.+ expect(lis[0].querySelector("p")?.textContent?.trim()).toBe("step one");+ expect(lis[0].querySelector("pre code")?.textContent?.trim()).toBe("x++;");+ expect(lis[1].textContent?.trim()).toBe("step two");+ });+});++describe("htmlToMarkdown — blockquotes, hr, tables, br", () => {+ it("renders blockquotes with > prefix", () => {+ const md = htmlToMarkdown(+ "<blockquote><p>line one</p><p>line two</p></blockquote>",+ );+ const doc = mdToDoc(md);+ const bq = doc.body.querySelector("blockquote");+ expect(bq).not.toBeNull();+ expect(bq?.textContent).toMatch(/line one/);+ expect(bq?.textContent).toMatch(/line two/);+ });++ it("renders a horizontal rule", () => {+ const md = htmlToMarkdown("<p>before</p><hr><p>after</p>");+ const doc = mdToDoc(md);+ expect(doc.body.querySelector("hr")).not.toBeNull();+ });++ it("renders a GFM table", () => {+ const md = htmlToMarkdown(+ "<table><thead><tr><th>A</th><th>B</th></tr></thead><tbody><tr><td>1</td><td>2</td></tr><tr><td>3</td><td>4</td></tr></tbody></table>",+ );+ const doc = mdToDoc(md);+ const headers = Array.from(doc.body.querySelectorAll("thead th")).map(+ (th) => th.textContent?.trim(),+ );+ expect(headers).toEqual(["A", "B"]);+ const rows = Array.from(doc.body.querySelectorAll("tbody tr")).map((tr) =>+ Array.from(tr.querySelectorAll("td")).map((td) => td.textContent?.trim()),+ );+ expect(rows).toEqual([+ ["1", "2"],+ ["3", "4"],+ ]);+ });++ it("escapes pipes inside table cells", () => {+ const md = htmlToMarkdown(+ "<table><tr><th>a|b</th></tr><tr><td>c|d</td></tr></table>",+ );+ expect(md).toMatch(/a\\\|b/);+ expect(md).toMatch(/c\\\|d/);+ });++ it("keeps a cell containing <br> on a single row (no smashed table)", () => {+ const md = htmlToMarkdown(+ "<table><tr><th>H</th></tr><tr><td>line1<br>line2</td></tr><tr><td>next</td></tr></table>",+ );+ const doc = mdToDoc(md);+ const trs = doc.body.querySelectorAll("table tr");+ // Header + 2 body rows = 3 total; if the <br> had injected a literal \n,+ // marked would see only the header and the table would collapse.+ expect(trs.length).toBe(3);+ const firstBodyCell = doc.body.querySelector("tbody tr:first-child td");+ expect(firstBodyCell?.textContent).toContain("line1");+ expect(firstBodyCell?.textContent).toContain("line2");+ expect(firstBodyCell?.querySelector("br")).not.toBeNull();+ });+});++describe("htmlToMarkdown — full document smoke", () => {+ it("round-trips a deck-style document end-to-end", () => {+ const html = `+ <body>+ <h1>Demo Deck</h1>+ <p>An intro paragraph with <strong>bold</strong> and a <a href="https://example.com/page (v2)">tricky link</a>.</p>+ <h2>Steps</h2>+ <ol>+ <li>Install+ <pre><code class="language-bash">npm i</code></pre>+ </li>+ <li>Run with a <code>foo \`bar\` baz</code> snippet</li>+ </ol>+ <blockquote><p>Quote with 1. literal numeric prefix.</p></blockquote>+ </body>`;+ const md = htmlToMarkdown(html);+ const doc = mdToDoc(md);+ expect(doc.body.querySelector("h1")?.textContent).toBe("Demo Deck");+ expect(doc.body.querySelector("h2")?.textContent).toBe("Steps");+ expect(doc.body.querySelector("ol > li pre code")?.textContent).toContain(+ "npm i",+ );+ expect(doc.body.querySelector("blockquote p")?.textContent).toMatch(+ /1\. literal numeric prefix/,+ );+ // Tricky-link href survives the angle-bracket wrap (decoded form,+ // since marked percent-encodes spaces in the rendered HTML).+ const a = doc.body.querySelector("a");+ expect(decodeURI(a?.getAttribute("href") ?? "")).toBe(+ "https://example.com/page (v2)",+ );+ });+});diff --git a/next/src/lib/export/__tests__/mastodon.test.ts b/next/src/lib/export/__tests__/mastodon.test.tsnew file mode 100644index 00000000..2cf71f54--- /dev/null+++ b/next/src/lib/export/__tests__/mastodon.test.ts@@ -0,0 +1,81 @@+/**+ * Tests for `truncateForPost` — shared by both Mastodon (500 cap) and+ * Bluesky (300 cap). Verifies that the function never splits a surrogate+ * pair and stays under the platform limit for compound emoji (ZWJ+ * sequences count as multiple code points, which is conservative).+ */+import { describe, it, expect } from "vitest";+import { truncateForPost } from "../mastodon";++describe("truncateForPost — basic length handling", () => {+ it("returns the trimmed input when under the limit", () => {+ expect(truncateForPost(" hello world ", 50)).toBe("hello world");+ });++ it("collapses internal whitespace runs", () => {+ expect(truncateForPost("a b\t\tc\n\nd", 50)).toBe("a b c d");+ });++ it("truncates a long ASCII string with an ellipsis", () => {+ const long = "abcdefghij".repeat(10); // 100 chars+ const out = truncateForPost(long, 30);+ expect(out.length).toBeLessThanOrEqual(30);+ expect(out.endsWith("…")).toBe(true);+ });+});++describe("truncateForPost — Unicode safety", () => {+ it("does not split a surrogate pair", () => {+ // 5 single-code-point emoji = 5 code points = 10 UTF-16 units.+ const s = "🎉🎉🎉🎉🎉";+ const out = truncateForPost(s, 3);+ // Output is at most 3 code points; ellipsis takes 1, so we keep 2 emoji.+ const points = Array.from(out);+ expect(points.length).toBeLessThanOrEqual(3);+ // No lone surrogate should appear in the output.+ for (const ch of out) {+ const code = ch.codePointAt(0)!;+ const isSurrogate = code >= 0xd800 && code <= 0xdfff;+ // `for…of` on a string iterates by code point, so any individual char+ // in this loop should already be a full code point, never a surrogate.+ expect(isSurrogate).toBe(false);+ }+ expect(out.endsWith("…")).toBe(true);+ });++ it("returns input unchanged when code-point count is within limit even if UTF-16 length exceeds it", () => {+ // 10 emoji = 10 code points but 20 UTF-16 units.+ const s = "🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉";+ expect(s.length).toBe(20); // UTF-16 units+ expect(Array.from(s).length).toBe(10); // code points+ // Limit 15: collapsed.length=20 > 15, but code points 10 <= 15, so the+ // fast path's second check returns the string unchanged.+ expect(truncateForPost(s, 15)).toBe(s);+ });++ it("counts ZWJ-joined emoji as multiple code points (documented conservative behavior)", () => {+ // 👨👩👧 = 5 code points (3 emoji + 2 zero-width joiners) but 1 grapheme.+ // The doc comment on truncateForPost calls this out — verify the behavior.+ const family = "👨👩👧";+ expect(Array.from(family).length).toBe(5);+ // With limit 3, the family alone (5 code points) exceeds it.+ const out = truncateForPost(family, 3);+ expect(Array.from(out).length).toBeLessThanOrEqual(3);+ });+});++describe("truncateForPost — boundary cases", () => {+ it("handles empty input", () => {+ expect(truncateForPost("", 10)).toBe("");+ });++ it("handles limit equal to length", () => {+ expect(truncateForPost("hello", 5)).toBe("hello");+ });++ it("handles limit exactly one less than length", () => {+ const out = truncateForPost("hello", 4);+ expect(out.endsWith("…")).toBe(true);+ expect(Array.from(out).length).toBeLessThanOrEqual(4);+ });+});diff --git a/next/src/lib/export/__tests__/notion.test.ts b/next/src/lib/export/__tests__/notion.test.tsnew file mode 100644index 00000000..2bad5156--- /dev/null+++ b/next/src/lib/export/__tests__/notion.test.ts@@ -0,0 +1,91 @@+/**+ * Tests for the Notion exporter. Notion's paste handler honors inline styles+ * (added by juice) but ignores classes and `<section>`/`<article>` wrappers,+ * so we verify the post-processing pipeline against real DOM parses.+ */+import { describe, it, expect } from "vitest";+import { toNotionHtml } from "../notion";++function parseFragment(html: string): HTMLBodyElement {+ return new DOMParser().parseFromString(`<body>${html}</body>`, "text/html")+ .body as HTMLBodyElement;+}++describe("toNotionHtml — wrapper unwrapping", () => {+ it("unwraps <section>/<article>/<header>/<footer>/<main>", () => {+ const html = toNotionHtml(+ "<section><article><header><h1>t</h1></header><main><p>body</p></main><footer><p>f</p></footer></article></section>",+ );+ const body = parseFragment(html);+ expect(body.querySelector("section")).toBeNull();+ expect(body.querySelector("article")).toBeNull();+ expect(body.querySelector("header")).toBeNull();+ expect(body.querySelector("main")).toBeNull();+ expect(body.querySelector("footer")).toBeNull();+ expect(body.querySelector("h1")?.textContent).toBe("t");+ expect(+ Array.from(body.querySelectorAll("p")).map((p) => p.textContent),+ ).toEqual(["body", "f"]);+ });+});++describe("toNotionHtml — noise attribute stripping", () => {+ it("strips data-* and class attributes from non-code elements", () => {+ const html = toNotionHtml(+ '<p class="prose" data-foo="bar">hello</p><span class="x" data-baz="qux">world</span>',+ );+ const body = parseFragment(html);+ const p = body.querySelector("p");+ expect(p?.getAttribute("class")).toBeNull();+ expect(p?.getAttribute("data-foo")).toBeNull();+ const span = body.querySelector("span");+ expect(span?.getAttribute("class")).toBeNull();+ expect(span?.getAttribute("data-baz")).toBeNull();+ });++ it("preserves inline styles (juice's output) so colors/weights survive paste", () => {+ const html = toNotionHtml(+ '<p style="color: red; font-weight: bold">styled</p>',+ );+ const p = parseFragment(html).querySelector("p");+ expect(p?.getAttribute("style")).toContain("color");+ });+});++describe("toNotionHtml — code block normalization", () => {+ it("keeps language-* class on <code> inside <pre>", () => {+ const html = toNotionHtml(+ '<pre><code class="language-ts">x</code></pre>',+ );+ const code = parseFragment(html).querySelector("pre code");+ expect(code?.getAttribute("class")).toMatch(/language-ts/);+ });++ it("strips non-language classes from <code>, keeping only language-*", () => {+ const html = toNotionHtml(+ '<pre><code class="hljs language-py extra">x</code></pre>',+ );+ const code = parseFragment(html).querySelector("pre code");+ const tokens = (code?.getAttribute("class") ?? "")+ .split(/\s+/)+ .filter(Boolean);+ // All language-* tokens are present; nothing else.+ expect(tokens.every((t) => /^language-/.test(t))).toBe(true);+ expect(tokens).toContain("language-py");+ });++ it("adds language-plaintext when <pre><code> has no language hint", () => {+ const html = toNotionHtml("<pre><code>raw</code></pre>");+ const code = parseFragment(html).querySelector("pre code");+ expect(code?.getAttribute("class")).toMatch(/language-plaintext/);+ });++ it("wraps a <pre> with no inner <code> in one, with a language hint", () => {+ const html = toNotionHtml("<pre>orphan</pre>");+ const body = parseFragment(html);+ const code = body.querySelector("pre > code");+ expect(code).not.toBeNull();+ expect(code?.textContent).toBe("orphan");+ expect(code?.getAttribute("class")).toMatch(/language-plaintext/);+ });+});diff --git a/next/src/lib/export/bilibili.ts b/next/src/lib/export/bilibili.tsnew file mode 100644index 00000000..c5aa0f0b--- /dev/null+++ b/next/src/lib/export/bilibili.ts@@ -0,0 +1,131 @@+"use client";++import { copyHtml } from "./clipboard";++/**+ * Bilibili 专栏 (column) editor accepts a narrow subset of HTML and rejects+ * everything else (drops the tag, sometimes drops the whole paste). Images+ * must be on a bili-hosted CDN — external src URLs are silently stripped at+ * publish time. We replace external images with a placeholder that the user+ * can re-upload through bilibili's image button, preserving alt + a hint+ * data attribute so the source URL isn't lost.+ */+const ALLOWED_TAGS = new Set([+ "p", "h1", "h2", "h3", "h4", "h5", "h6",+ "ul", "ol", "li", "blockquote", "pre", "code",+ "strong", "b", "em", "i", "u", "s", "del", "br", "hr",+ "a", "img", "figure", "figcaption", "span",+]);++const ALLOWED_ATTRS: Record<string, Set<string>> = {+ a: new Set(["href", "title"]),+ img: new Set(["src", "alt", "data-bili-placeholder", "data-original-src"]),+ span: new Set(["style"]),+ code: new Set(["class"]),+};++const PLACEHOLDER_SRC =+ "data:image/svg+xml;utf8," ++ encodeURIComponent(+ `<svg xmlns="http://www.w3.org/2000/svg" width="640" height="360">` ++ `<rect width="100%" height="100%" fill="#f1f2f3"/>` ++ `<text x="50%" y="50%" font-family="sans-serif" font-size="20" fill="#999" ` ++ `text-anchor="middle" dominant-baseline="middle">Re-upload to Bilibili CDN</text>` ++ `</svg>`,+ );++/** Whitelist HTML to the subset bilibili's column editor accepts. */+export function toBilibiliHtml(fullHtml: string): string {+ if (typeof window === "undefined") return fullHtml;++ const doc = new DOMParser().parseFromString(fullHtml, "text/html");+ const body = doc.body;+ if (!body) return fullHtml;++ const cleaned = sanitize(body);+ return cleaned.innerHTML;+}++export async function copyToBilibili(fullHtml: string): Promise<void> {+ const html = toBilibiliHtml(fullHtml);+ await copyHtml(html);+}++function sanitize(node: Element): HTMLElement {+ const out = document.createElement("div");+ for (const child of Array.from(node.childNodes)) {+ const c = sanitizeNode(child);+ if (c) out.appendChild(c);+ }+ return out;+}++function sanitizeNode(node: Node): Node | null {+ if (node.nodeType === Node.TEXT_NODE) {+ return document.createTextNode(node.textContent ?? "");+ }+ if (node.nodeType !== Node.ELEMENT_NODE) return null;++ const el = node as Element;+ const tag = el.tagName.toLowerCase();++ if (!ALLOWED_TAGS.has(tag)) {+ // Drop the wrapper but keep the children (e.g. unwrap divs, sections).+ const frag = document.createDocumentFragment();+ for (const child of Array.from(el.childNodes)) {+ const c = sanitizeNode(child);+ if (c) frag.appendChild(c);+ }+ return frag.childNodes.length ? frag : null;+ }++ const fresh = document.createElement(tag);+ const allowed = ALLOWED_ATTRS[tag];+ if (allowed) {+ for (const attr of Array.from(el.attributes)) {+ if (allowed.has(attr.name)) fresh.setAttribute(attr.name, attr.value);+ }+ }++ if (tag === "a") {+ const href = fresh.getAttribute("href") ?? "";+ // Bilibili scrubs javascript: schemes anyway, but strip defensively.+ if (/^javascript:/i.test(href)) fresh.removeAttribute("href");+ }++ if (tag === "code") {+ // Keep only `language-*` classes; bilibili strips arbitrary classes+ // server-side but the language hint can influence syntax styling.+ const cls = fresh.getAttribute("class") ?? "";+ const langOnly = cls+ .split(/\s+/)+ .filter((c) => /^language-[\w-]+$/.test(c))+ .join(" ");+ if (langOnly) fresh.setAttribute("class", langOnly);+ else fresh.removeAttribute("class");+ }++ if (tag === "img") {+ const src = fresh.getAttribute("src") ?? "";+ if (!isBilibiliCdn(src)) {+ fresh.setAttribute("data-original-src", src);+ fresh.setAttribute("data-bili-placeholder", "true");+ fresh.setAttribute("src", PLACEHOLDER_SRC);+ }+ }++ for (const child of Array.from(el.childNodes)) {+ const c = sanitizeNode(child);+ if (c) fresh.appendChild(c);+ }+ return fresh;+}++function isBilibiliCdn(src: string): boolean {+ // Require an exact host match or a subdomain dot — `[^/]*` would otherwise+ // admit `evilhdslb.com` / `notbilibili.com`, skipping the placeholder swap+ // and silently losing the image after bilibili's publish-time scrub.+ return /^https?:\/\/(?:[^/]+\.)?(?:hdslb\.com|bilibili\.com)(?:[/?#]|$)/i.test(+ src,+ );+}diff --git a/next/src/lib/export/bluesky.ts b/next/src/lib/export/bluesky.tsnew file mode 100644index 00000000..384140d7--- /dev/null+++ b/next/src/lib/export/bluesky.ts@@ -0,0 +1,37 @@+"use client";++import { copyImage, copyText } from "./clipboard";+import { iframeToBlob } from "./image";+import { truncateForPost } from "./mastodon";++/** Bluesky enforces a 300-grapheme post limit. */+export const BLUESKY_TEXT_LIMIT = 300;++export type BlueskyShare = {+ blob: Blob;+ text: string;+ filename: string;+};++/**+ * Build a Bluesky-friendly share bundle: a PNG screenshot plus a 300-char+ * caption. Bluesky's compose box accepts paste of the image directly, but+ * we keep image + text on separate clipboard calls to dodge browser quirks+ * around mixed mime clipboard writes.+ */+export async function buildBlueskyShare(+ iframe: HTMLIFrameElement,+ caption: string,+): Promise<BlueskyShare> {+ const blob = await iframeToBlob(iframe);+ const text = truncateForPost(caption, BLUESKY_TEXT_LIMIT);+ return { blob, text, filename: `bluesky-${Date.now()}.png` };+}++export async function copyBlueskyImage(share: BlueskyShare): Promise<void> {+ await copyImage(share.blob);+}++export async function copyBlueskyText(share: BlueskyShare): Promise<void> {+ await copyText(share.text);+}diff --git a/next/src/lib/export/markdown-roundtrip.ts b/next/src/lib/export/markdown-roundtrip.tsnew file mode 100644index 00000000..94e44e91--- /dev/null+++ b/next/src/lib/export/markdown-roundtrip.ts@@ -0,0 +1,317 @@+"use client";++import { copyText } from "./clipboard";+import { downloadMarkdown } from "./download";++/**+ * Reverse trip: take a rendered HTML document and emit clean GitHub-flavored+ * Markdown that hugo / 11ty / Obsidian users can drop into a `.md` file.+ *+ * We deliberately do NOT pull in turndown — its rules table is large and+ * its handling of nested lists / tables drifts from CommonMark. A focused+ * walker over the subset we actually produce (the HTML the editor renders)+ * gives a more predictable result for ~150 lines.+ *+ * Supported: headings, paragraphs, emphasis, inline + fenced code, links,+ * images, ordered/unordered lists (nested), blockquotes, hr, tables, br.+ * Anything we don't recognize falls back to plain text.+ */+export function htmlToMarkdown(fullHtml: string): string {+ if (typeof window === "undefined") return fullHtml;++ const doc = new DOMParser().parseFromString(fullHtml, "text/html");+ const body = doc.body;+ if (!body) return "";++ const out = renderBlock(body, { listDepth: 0 });+ return collapseBlankLines(out).trim() + "\n";+}++export async function copyAsMarkdown(fullHtml: string): Promise<void> {+ await copyText(htmlToMarkdown(fullHtml));+}++export function downloadAsMarkdown(fullHtml: string, basename = "html-anything"): void {+ downloadMarkdown(htmlToMarkdown(fullHtml), basename);+}++type Ctx = { listDepth: number };++function renderBlock(node: Node, ctx: Ctx): string {+ if (node.nodeType === Node.TEXT_NODE) {+ const t = node.textContent ?? "";+ return /\S/.test(t) ? t.replace(/\s+/g, " ") : "";+ }+ if (node.nodeType !== Node.ELEMENT_NODE) return "";++ const el = node as Element;+ const tag = el.tagName.toLowerCase();++ switch (tag) {+ case "h1": case "h2": case "h3": case "h4": case "h5": case "h6": {+ const level = Number(tag[1]);+ return `\n\n${"#".repeat(level)} ${renderInline(el)}\n\n`;+ }+ case "p":+ return `\n\n${escapeBlockStarts(renderInline(el))}\n\n`;+ case "blockquote": {+ const inner = childrenToBlocks(el, ctx).trim();+ return "\n\n" + inner.split("\n").map((l) => `> ${l}`).join("\n") + "\n\n";+ }+ case "hr":+ return "\n\n---\n\n";+ case "br":+ return " \n";+ case "pre":+ return renderPre(el);+ case "ul": case "ol":+ return renderList(el, ctx);+ case "table":+ return renderTable(el);+ case "figure":+ return childrenToBlocks(el, ctx);+ case "body": case "div": case "section": case "article":+ case "header": case "footer": case "main": case "aside":+ return childrenToBlocks(el, ctx);+ default:+ // Inline element at block position — wrap as paragraph if non-empty.+ return escapeBlockStarts(renderInline(el));+ }+}++function childrenToBlocks(el: Element, ctx: Ctx): string {+ let out = "";+ for (const child of Array.from(el.childNodes)) {+ out += renderBlock(child, ctx);+ }+ return out;+}++function renderInline(node: Node): string {+ if (node.nodeType === Node.TEXT_NODE) {+ return escapeMd(node.textContent ?? "");+ }+ if (node.nodeType !== Node.ELEMENT_NODE) return "";+ const el = node as Element;+ const tag = el.tagName.toLowerCase();+ const inner = () =>+ Array.from(el.childNodes).map((c) => renderInline(c)).join("");++ switch (tag) {+ case "strong": case "b":+ return `**${inner()}**`;+ case "em": case "i":+ return `*${inner()}*`;+ case "code":+ // Inline code only — fenced blocks come through renderPre.+ // CommonMark forbids backslash-escaping backticks inside inline code;+ // use a fence longer than the longest backtick run in the body.+ return wrapInlineCode(el.textContent ?? "");+ case "s": case "del": case "strike":+ return `~~${inner()}~~`;+ case "br":+ return " \n";+ case "a": {+ const rawHref = el.getAttribute("href") ?? "";+ const href = escapeHref(rawHref);+ const title = el.getAttribute("title");+ // `escapeMd` already backslash-escapes brackets in text nodes, so+ // `inner()` is safe to drop into the [text](url) form without further+ // wrapping. Nested rendered structure (, `code`) survives+ // intact this way.+ const text = inner() || escapeMd(rawHref);+ return title ? `[${text}](${href} "${escapeTitle(title)}")` : `[${text}](${href})`;+ }+ case "img": {+ const src = escapeHref(el.getAttribute("src") ?? "");+ const alt = escapeMd(el.getAttribute("alt") ?? "");+ const title = el.getAttribute("title");+ return title ? `}")` : ``;+ }+ case "span": case "u":+ return inner();+ default:+ // Unknown inline / block-ish element — recurse.+ return Array.from(el.childNodes).map((c) => renderInline(c)).join("");+ }+}++function renderPre(el: Element): string {+ const code = el.querySelector("code");+ const langCls = code?.getAttribute("class") ?? "";+ const langMatch = langCls.match(/language-([\w-]+)/);+ const lang = langMatch ? langMatch[1] : "";+ const raw = ((code ?? el).textContent ?? "").replace(/\n$/, "");+ // Fence must be longer than any backtick run in the body so the block+ // doesn't terminate early on embedded ```.+ const fence = backtickFence(raw, 3);+ return `\n\n${fence}${lang}\n${raw}\n${fence}\n\n`;+}++const LIST_BLOCK_TAGS = new Set([+ "p", "pre", "blockquote", "h1", "h2", "h3", "h4", "h5", "h6",+ "table", "figure", "div", "section", "article", "hr",+]);++function renderList(el: Element, ctx: Ctx): string {+ const ordered = el.tagName.toLowerCase() === "ol";+ const indent = " ".repeat(ctx.listDepth);+ const items: string[] = [];+ let n = 1;+ for (const li of Array.from(el.children)) {+ if (li.tagName.toLowerCase() !== "li") continue;+ const marker = ordered ? `${n}.` : "-";+ n++;+ const childCtx = { listDepth: ctx.listDepth + 1 };+ const contIndent = indent + " ".repeat(marker.length + 1);++ // Partition children: inline (rendered into the marker line),+ // nested lists, and other block elements (paragraphs, code blocks, etc.).+ const inlineFrag = document.createElement("div");+ type ChildBlock = { kind: "list" | "block"; el: Element };+ const blockChildren: ChildBlock[] = [];+ for (const c of Array.from(li.childNodes)) {+ if (c.nodeType === Node.ELEMENT_NODE) {+ const t = (c as Element).tagName.toLowerCase();+ if (t === "ul" || t === "ol") {+ blockChildren.push({ kind: "list", el: c as Element });+ continue;+ }+ if (LIST_BLOCK_TAGS.has(t)) {+ blockChildren.push({ kind: "block", el: c as Element });+ continue;+ }+ }+ inlineFrag.appendChild(c.cloneNode(true));+ }++ // If the marker line would be empty (li had no inline children), promote+ // the first <p>'s inline content onto the marker line. Otherwise marked+ // sees "1. \n\n text" and starts a new list from the next marker.+ if (!inlineFrag.childNodes.length && blockChildren.length) {+ const first = blockChildren[0];+ if (first.kind === "block" && first.el.tagName.toLowerCase() === "p") {+ for (const c of Array.from(first.el.childNodes)) {+ inlineFrag.appendChild(c.cloneNode(true));+ }+ blockChildren.shift();+ }+ }++ const inlineText = escapeBlockStarts(renderInline(inlineFrag)).trim();+ let block = `${indent}${marker} ${inlineText}`;+ for (const bc of blockChildren) {+ if (bc.kind === "list") {+ block += "\n" + renderList(bc.el, childCtx).replace(/\n+$/, "");+ } else {+ const rendered = renderBlock(bc.el, childCtx).replace(/^\n+/, "").replace(/\n+$/, "");+ if (!rendered) continue;+ const indented = rendered.split("\n").map((l) => (l ? contIndent + l : l)).join("\n");+ block += "\n\n" + indented;+ }+ }+ items.push(block);+ }+ return "\n" + items.join("\n") + "\n";+}++function renderTable(el: Element): string {+ const rows: string[][] = [];+ el.querySelectorAll("tr").forEach((tr) => {+ const cells: string[] = [];+ tr.querySelectorAll("th,td").forEach((cell) => {+ // GFM tables are strictly one row per source line: a literal \n inside+ // a cell (e.g. from <br> or a stray <p>) terminates the row early and+ // breaks every downstream row. Collapse intra-cell newlines to <br>+ // (inline HTML is permitted inside GFM cells) before pipe escaping.+ cells.push(+ renderInline(cell)+ .replace(/\r?\n+/g, "<br>")+ .replace(/\|/g, "\\|")+ .trim(),+ );+ });+ if (cells.length) rows.push(cells);+ });+ if (!rows.length) return "";+ const width = Math.max(...rows.map((r) => r.length));+ const norm = rows.map((r) => {+ while (r.length < width) r.push("");+ return r;+ });+ const header = norm[0];+ const sep = header.map(() => "---");+ const body = norm.slice(1);+ const fmt = (r: string[]) => `| ${r.join(" | ")} |`;+ return ["\n", fmt(header), fmt(sep), ...body.map(fmt), "\n"].join("\n");+}++function escapeMd(s: string): string {+ // Escape inline-marker characters in plain text. Brackets are escaped at+ // the text-node level (not at link composition) so nested `<img>` / `<code>`+ // inside `<a>` survives without their delimiters getting backslashed.+ // Parens are left alone — escaping them in prose looks worse than the rare+ // false link match. Line-starting block markers (#, >, -, +, digits.) are+ // handled separately in `escapeBlockStarts` so they only escape at the+ // position where they would actually trigger a block construct.+ return s.replace(/([\\`*_~[\]])/g, "\\$1");+}++/**+ * Escape characters at the start of a line that would otherwise be parsed+ * as the opening of a block-level Markdown construct (heading, blockquote,+ * unordered/ordered list, hr). Only matches when the marker is followed by+ * whitespace or end-of-line — `#bar` mid-text isn't a heading.+ */+function escapeBlockStarts(s: string): string {+ return s.replace(+ /(^|\n)([ \t]*)(#{1,6}|>|[-+*]|\d+\.)(?=\s|$)/g,+ (_m, lead: string, ws: string, marker: string) =>+ `${lead}${ws}\\${marker}`,+ );+}++function collapseBlankLines(s: string): string {+ return s.replace(/\n{3,}/g, "\n\n");+}++function backtickFence(body: string, min: number): string {+ let max = 0;+ const re = /`+/g;+ let m: RegExpExecArray | null;+ while ((m = re.exec(body)) !== null) {+ if (m[0].length > max) max = m[0].length;+ }+ return "`".repeat(Math.max(min, max + 1));+}++function wrapInlineCode(text: string): string {+ if (!text) return "``";+ const fence = backtickFence(text, 1);+ // CommonMark strips a single leading/trailing space if the content also+ // contains a non-space char — use that to allow the body to start or end+ // with a backtick (or only-spaces content) without parser ambiguity.+ const needsPad = text.startsWith("`") || text.endsWith("`");+ const pad = needsPad ? " " : "";+ return `${fence}${pad}${text}${pad}${fence}`;+}++/**+ * Render a URL safe for use inside the `(...)` of a Markdown link/image.+ * URLs containing spaces or parens are wrapped with angle brackets; any+ * embedded `<` / `>` are percent-encoded since they would close the bracket+ * form prematurely.+ */+function escapeHref(href: string): string {+ if (!href) return "";+ if (/[\s()<>]/.test(href)) {+ const encoded = href.replace(/[<>]/g, (c) => (c === "<" ? "%3C" : "%3E"));+ return `<${encoded}>`;+ }+ return href;+}++function escapeTitle(title: string): string {+ return title.replace(/\\/g, "\\\\").replace(/"/g, '\\"');+}+diff --git a/next/src/lib/export/mastodon.ts b/next/src/lib/export/mastodon.tsnew file mode 100644index 00000000..6e75ddf5--- /dev/null+++ b/next/src/lib/export/mastodon.ts@@ -0,0 +1,60 @@+"use client";++import { copyImage, copyText } from "./clipboard";+import { iframeToBlob } from "./image";++/** Default Mastodon instance post limit. Some instances raise this, but 500+ * is the canonical default — use as a safe ceiling. */+export const MASTODON_TEXT_LIMIT = 500;++export type MastodonShare = {+ /** Image to attach to the post. */+ blob: Blob;+ /** Caption trimmed to the platform limit. */+ text: string;+ /** Suggested filename if the caller wants to save the blob. */+ filename: string;+};++/**+ * Build a Mastodon-friendly share bundle: a PNG screenshot of the preview+ * plus a short caption. Most browsers refuse to put image + text on the+ * clipboard together — call `copyMastodonImage` to copy the image and+ * `copyMastodonText` to copy the caption.+ */+export async function buildMastodonShare(+ iframe: HTMLIFrameElement,+ caption: string,+): Promise<MastodonShare> {+ const blob = await iframeToBlob(iframe);+ const text = truncateForPost(caption, MASTODON_TEXT_LIMIT);+ return { blob, text, filename: `mastodon-${Date.now()}.png` };+}++export async function copyMastodonImage(share: MastodonShare): Promise<void> {+ await copyImage(share.blob);+}++export async function copyMastodonText(share: MastodonShare): Promise<void> {+ await copyText(share.text);+}++/**+ * Trim to a hard character ceiling without slicing a multi-byte glyph.+ *+ * Note: Mastodon and Bluesky both count *graphemes*, not code points, when+ * enforcing their limits. A ZWJ-joined emoji like 👨👩👧 is 1 grapheme but+ * 5 code points — counting by `Array.from` will count it as 5. This is+ * conservative (we'll never overshoot the platform's limit), but a caption+ * with many compound emoji may be truncated more aggressively than needed.+ */+export function truncateForPost(text: string, limit: number): string {+ const collapsed = text.replace(/\s+/g, " ").trim();+ if (collapsed.length <= limit) return collapsed;+ // Use Array.from to count by code point, not UTF-16 unit, so we don't+ // split a surrogate pair in half.+ const points = Array.from(collapsed);+ if (points.length <= limit) return collapsed;+ const ellipsis = "…";+ return points.slice(0, limit - ellipsis.length).join("") + ellipsis;+}diff --git a/next/src/lib/export/notion.ts b/next/src/lib/export/notion.tsnew file mode 100644index 00000000..7333ab78--- /dev/null+++ b/next/src/lib/export/notion.ts@@ -0,0 +1,109 @@+"use client";++import juice from "juice";+import { copyHtml } from "./clipboard";++/**+ * Notion's paste handler converts HTML to native blocks. It honors inline+ * styles for text decoration (color, background, font-weight) but ignores+ * classes and section wrappers — so we juice the CSS in, then flatten the+ * outer container that WeChat needs but Notion drops.+ *+ * Quirks worth knowing about:+ * - `<section>` / `<article>` wrappers around top-level blocks get unwrapped.+ * - `<pre><code class="language-xxx">` is required for code blocks to+ * land as Notion code blocks with the right language.+ * - `<img>` is accepted but Notion re-uploads only when src is reachable;+ * we leave the src as-is so the user can decide whether to host first.+ * - `data-*` and `class` attributes survive paste as noise; strip them.+ */+export function toNotionHtml(fullHtml: string): string {+ if (typeof window === "undefined") return fullHtml;++ const doc = new DOMParser().parseFromString(fullHtml, "text/html");++ const css = Array.from(doc.querySelectorAll("style"))+ .map((s) => s.textContent ?? "")+ .join("\n");++ const bodyHtml = doc.body?.innerHTML ?? fullHtml;++ let inlined: string;+ try {+ inlined = juice.inlineContent(bodyHtml, css, {+ inlinePseudoElements: true,+ preserveImportant: true,+ });+ } catch {+ inlined = bodyHtml;+ }++ // Post-process: unwrap section/article, strip class/data-*, normalize code blocks.+ const wrap = document.createElement("div");+ wrap.innerHTML = inlined;++ unwrapAll(wrap, ["section", "article", "header", "footer", "main"]);+ stripNoiseAttrs(wrap);+ normalizeCodeBlocks(wrap);++ return wrap.innerHTML;+}++export async function copyToNotion(fullHtml: string): Promise<void> {+ const html = toNotionHtml(fullHtml);+ await copyHtml(html);+}++function unwrapAll(root: HTMLElement, tags: string[]): void {+ for (const tag of tags) {+ const nodes = Array.from(root.querySelectorAll(tag));+ for (const node of nodes) {+ const parent = node.parentNode;+ if (!parent) continue;+ while (node.firstChild) parent.insertBefore(node.firstChild, node);+ parent.removeChild(node);+ }+ }+}++function stripNoiseAttrs(root: HTMLElement): void {+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT);+ let el = walker.nextNode() as Element | null;+ while (el) {+ // For <code>, keep only language-* tokens — Notion uses them to pick+ // the syntax mode and strips any other classes on paste anyway.+ if (el.tagName === "CODE" && el.hasAttribute("class")) {+ const langOnly = (el.getAttribute("class") ?? "")+ .split(/\s+/)+ .filter((c) => /^language-[\w-]+$/.test(c))+ .join(" ");+ if (langOnly) el.setAttribute("class", langOnly);+ else el.removeAttribute("class");+ }+ for (const attr of Array.from(el.attributes)) {+ if (el.tagName === "CODE" && attr.name === "class") continue;+ if (attr.name.startsWith("data-") || attr.name === "class") {+ el.removeAttribute(attr.name);+ }+ }+ el = walker.nextNode() as Element | null;+ }+}++function normalizeCodeBlocks(root: HTMLElement): void {+ // Ensure every <pre> has a <code> child with a language-* class; Notion+ // otherwise treats the block as plain text and you lose the code styling.+ root.querySelectorAll("pre").forEach((pre) => {+ let code = pre.querySelector(":scope > code");+ if (!code) {+ code = document.createElement("code");+ code.textContent = pre.textContent ?? "";+ pre.textContent = "";+ pre.appendChild(code);+ }+ const cls = code.getAttribute("class") ?? "";+ if (!/\blanguage-[\w-]+/.test(cls)) {+ code.setAttribute("class", `${cls} language-plaintext`.trim());+ }+ });+}