Move the tests from scripts/ to tests/ by feature

Unit tests go to tests/unit/<area>/, browser smoke tests to
tests/smoke/<area>/, and tests against a running desktop app to
tests/native/. Files named after dates, work passes, or Kanban cards get
feature names, for example editorOctober12 -> editor/footnotes.

scripts/ keeps the build, release, and package tools. Plugin repositories
import scripts/packagePlugin.mjs, and the Terminal smoke test imports
scripts/pluginMocks.mjs, which now re-exports the harness copy.

The unit tests get their own type check (tests/tsconfig.json) with Node
types. pnpm check runs it after the app check. Add @types/node and fix
the three test mocks that it reported.
This commit is contained in:
Knotty Wyvern
2026-10-27 19:47:39 -07:00
parent 90d1940c73
commit e433bed28e
154 changed files with 269 additions and 227 deletions
+23
View File
@@ -0,0 +1,23 @@
import test from "node:test";
import assert from "node:assert/strict";
import { SearchQuery } from "@codemirror/search";
import { documentMatches, replacementText } from "../../../src/lib/editor/findTarget.ts";
test("document search uses Writer word matching and normalized CRLF positions", () => {
const query = new SearchQuery({ search: "Alpha", wholeWord: true, caseSensitive: true });
const { state, matches } = documentMatches("Alpha alphabet\r\nalpha Alpha", query);
assert.deepEqual(matches.map(({ from, to }) => ({ from, to })), [{ from: 0, to: 5 }, { from: 21, to: 26 }]);
assert.equal(state.doc.lineAt(matches[1].from).number, 2);
assert.equal(state.doc.lineAt(matches[1].from).from, 15);
});
test("replacement keeps regex context, capture groups, dollars, and line breaks", () => {
const query = new SearchQuery({ search: "(?<=G)(amma)", regexp: true, replace: "$1-$12-$&-$$\\n" });
assert.equal(replacementText("Gamma", 1, query), "amma-amma2-amma-$\n");
assert.equal(replacementText("Alpha", 0, new SearchQuery({ search: "Alpha", replace: "$1\\t" })), "$1\t");
});
test("empty and invalid queries do not produce matches", () => {
assert.deepEqual(documentMatches("Alpha", new SearchQuery({ search: "" })).matches, []);
assert.deepEqual(documentMatches("Alpha", new SearchQuery({ search: "[", regexp: true })).matches, []);
});
+33
View File
@@ -0,0 +1,33 @@
import assert from "node:assert/strict";
import test from "node:test";
import MarkdownIt from "markdown-it";
import { footnotes, renderFootnotes } from "../../../src/lib/editor/footnotes.ts";
function render(source: string) {
const markdown = new MarkdownIt({ html: false }).use(footnotes);
const env = {};
return markdown.render(source, env) + renderFootnotes(markdown, env);
}
test("footnotes use first-reference order, repeated backlinks, and rich multiline definitions", () => {
const html = render("First[^b], then[^a], again[^b].\n\n[^a]: Second definition\n[^b]: **Bold** text\n continued\n\n Second paragraph.\n");
assert.match(html, /id="rs-fnref-1-1"/);
assert.match(html, /id="rs-fnref-1-2"/);
assert.match(html, /<strong>Bold<\/strong> text\ncontinued/);
assert.match(html, /<p>Second paragraph\.<\/p>/);
assert.ok(html.indexOf('<li id="rs-fn-1"') < html.indexOf('<li id="rs-fn-2"'));
assert.match(html, /href="#rs-fnref-1-2"/);
});
test("undefined, escaped, inline-code, fenced-code, and indented-code references stay literal", () => {
const html = render("Missing[^missing]. Escaped\\[^n]. `[^n]`\n\n```md\n[^n]\n```\n\n [^n]\n\n[^n]: Unused\n");
assert.doesNotMatch(html, /md-footnotes|md-footnote-ref/);
assert.match(html, /Missing\[\^missing\]/);
});
test("footnotes keep HTML escaped and support CRLF", () => {
const html = render("Body[^x]\r\n\r\n[^x]: <script>alert(1)</script>\r\n");
assert.match(html, /&lt;script&gt;/);
assert.doesNotMatch(html, /<script>/);
assert.match(html, /Footnote 1/);
});
+15
View File
@@ -0,0 +1,15 @@
import assert from "node:assert/strict";
import test from "node:test";
import { fenceOpenText, headingMarkText } from "../../../src/lib/editor/headingMarks.ts";
test("heading marks match the heading level", () => {
assert.equal(headingMarkText(1), "#");
assert.equal(headingMarkText(3), "###");
assert.equal(headingMarkText(6), "######");
});
test("fence open marks include the language", () => {
assert.equal(fenceOpenText(""), "```");
assert.equal(fenceOpenText("js"), "```js");
assert.equal(fenceOpenText(" pp "), "```pp");
});
+17
View File
@@ -0,0 +1,17 @@
import assert from "node:assert/strict";
import test from "node:test";
import { htmlToMarkdown } from "../../../src/lib/workspace/htmlToMarkdown.ts";
test("Windows HTML clipboard fragment comments do not become table content", () => {
const html = '<html><body><!--StartFragment--><table><tr><th>Ticker</th><th>Name</th></tr><tr><td>ADBE.US</td><td>Adobe</td></tr><tr><td>ADSK.US</td><td>Autodesk</td></tr></table><!--EndFragment--></body></html>';
assert.equal(htmlToMarkdown(html), '| Ticker | Name |\n| --- | --- |\n| ADBE.US | Adobe |\n| ADSK.US | Autodesk |');
});
test("comments inside cells preserve adjacent text and formatting", () => {
const html = '<table><tr><th>Notes</th></tr><tr><td>First<!-- multi-line\n <b>comment</b> --> part<br><strong>Second</strong></td></tr></table>';
assert.equal(htmlToMarkdown(html), '| Notes |\n| --- |\n| First part<br>**Second** |');
});
test("escaped comment text remains user content", () => {
assert.equal(htmlToMarkdown('<p>&lt;!--Example--&gt;</p>'), '<!--Example-->');
});
+55
View File
@@ -0,0 +1,55 @@
import assert from "node:assert/strict";
import test from "node:test";
import { EditorState } from "@codemirror/state";
import { attachmentRel, hasFileDrag, imageFiles, imageInsertion, workspaceImageLink } from "../../../src/lib/workspace/media.ts";
import { imageSource, editImageSource, imageSourceRanges } from "../../../src/lib/editor/imageSource.ts";
import { imageDrops, trackImageDrop } from "../../../src/lib/editor/imageDrop.ts";
test("same-name image imports receive distinct safe attachment paths", () => {
const paths = new Set(Array.from({ length: 100 }, () => attachmentRel("photo (1).PNG")));
assert.equal(paths.size, 100);
assert.ok([...paths].every(path => /^attachments\/[\w.-]+\.PNG$/.test(path)));
});
test("protected file drags and files without MIME metadata are recognized", () => {
assert.equal(hasFileDrag({ types: ["Files"], files: [] } as unknown as DataTransfer), true);
assert.equal(hasFileDrag({ types: ["text/plain"] } as unknown as DataTransfer), false);
const files = [{ name: "PHOTO.PNG", type: "" }, { name: "note.md", type: "text/plain" }];
assert.deepEqual(imageFiles({ files } as unknown as DataTransfer), [files[0]]);
});
test("image batches form independent Markdown blocks without extra blank lines", () => {
assert.equal(imageInsertion("beforeafter", 6, 6, ["![](a.png)", "![](b.png)"]), "\n\n![](a.png)\n\n![](b.png)\n\n");
assert.equal(imageInsertion("before\n\nafter", 8, 8, ["![](a.png)"]), "![](a.png)\n\n");
assert.equal(imageInsertion("before\r\n\r\nafter", 10, 10, ["![](a.png)"]), "![](a.png)\n\n");
});
test("pending image drops follow intervening edits instead of the current caret", () => {
let state = EditorState.create({ doc: "before\nafter", extensions: [imageDrops] });
const id = Symbol();
state = state.update({ effects: trackImageDrop.of({ id, from: 7, to: 7 }) }).state;
state = state.update({ changes: { from: 0, insert: "new\n" }, selection: { anchor: 0 } }).state;
assert.deepEqual(state.field(imageDrops).get(id), { from: 11, to: 11 });
});
test("navigator image links are relative and encode Markdown and URL punctuation", () => {
assert.equal(workspaceImageLink("notes/drafts/note.md", "images/a (#1).png"), "![](../../images/a%20%28%231%29.png)");
assert.equal(workspaceImageLink("notes/note.md", "notes/photo.png"), "![](photo.png)");
assert.equal(workspaceImageLink("note.md", "日本語/photo%.png"), "![](%E6%97%A5%E6%9C%AC%E8%AA%9E/photo%25.png)");
});
test("image source is explicitly activated, tracks edits, and hides on leaving", () => {
let state = EditorState.create({ doc: "![](a.png)\n\nText", extensions: [imageSource] });
state = state.update({ selection: { anchor: 0, head: 10 } }).state;
assert.equal(state.field(imageSource), null);
state = state.update({ effects: editImageSource.of({ from: 0, to: 10 }) }).state;
state = state.update({ changes: { from: 2, insert: "Alt" } }).state;
assert.deepEqual(state.field(imageSource), { from: 0, to: 13 });
state = state.update({ selection: { anchor: state.doc.length } }).state;
assert.equal(state.field(imageSource), null);
});
test("image ranges distinguish embeds from code and retain reference and wiki syntax", () => {
const source = "`![](code.png)`\n\nText ![alt](<a b.png>) and ![[a b.png|Photo]]\n\n![ref][photo]\n\n[photo]: x.png\n\n```\n![](code.png)\n```";
assert.deepEqual(imageSourceRanges(source).map(range => source.slice(range.from, range.to)), ["![alt](<a b.png>)", "![[a b.png|Photo]]", "![ref][photo]"]);
});
+56
View File
@@ -0,0 +1,56 @@
import assert from "node:assert/strict";
import test from "node:test";
import { markdown, markdownLanguage } from "@codemirror/lang-markdown";
import { noteFormats } from "../../../src/lib/editor/noteFormats.ts";
import { renderMarkdownHtml } from "../../../src/lib/workspace/noteHtml.ts";
const parser = markdown({ base: markdownLanguage, extensions: [noteFormats] }).language.parser;
const render = (source: string) => renderMarkdownHtml(source, new Map());
function mathNodes(source: string) {
const nodes: string[] = [];
parser.parse(source).iterate({ enter(node) {
if (node.name === "NoteMath") nodes.push(source.slice(node.from, node.to));
} });
return nodes;
}
test("dollar amounts stay literal in writing, reading, and table cells", () => {
for (const source of [
"$10", "$10 and $20", "$1,234.56 plus $78.90", "$10-$20", "$0.25-$.50",
"US$10 / CA$20", "$ 10 and $ 20", "$-10 and $-20", "($10) and ($20)",
"$10\n$20", "$10\r\n$20", "$10 **income**, $20 **cost**",
]) {
assert.deepEqual(mathNodes(source), [], source);
const html = render(source);
assert.doesNotMatch(html, /md-inline-math/, source);
assert.equal((html.match(/\$/g) || []).length, (source.match(/\$/g) || []).length, source);
assert.doesNotMatch(render(`| Amounts |\n| --- |\n| ${source.replace(/\r?\n/g, "<br>")} |`), /md-inline-math/, source);
}
});
test("inline math still works next to dollar amounts", () => {
for (const expression of ["$x^2$", "$2 + 2$", "$x + y$", String.raw`$\frac{1}{2}$`, String.raw`$x + \$5$`]) {
const source = `$10 and $20, then ${expression}, then $30 and $40.`;
assert.deepEqual(mathNodes(source), [expression], source);
assert.equal((render(source).match(/md-inline-math/g) || []).length, 1, source);
assert.match(render(source), /\$10 and \$20/);
assert.match(render(source), /\$30 and \$40/);
}
});
test("escaped, incomplete, spaced, multiline, and double delimiters do not create inline math", () => {
for (const source of [String.raw`\$x\$`, "$x", "$ x$", "$x $", "$x\ny$", "$$x$$", "$$\nx\n$$", "`$x$`", "```\n$x$\n```", "$x$2"]) {
assert.deepEqual(mathNodes(source), [], source);
assert.doesNotMatch(render(source), /md-inline-math/, source);
}
});
test("highlight and comment formats keep their existing behavior", () => {
const source = "==**highlight**== %%comment%%";
const tree = parser.parse(source).toString();
assert.match(tree, /NoteHighlight/);
assert.match(tree, /StrongEmphasis/);
assert.match(tree, /NoteComment/);
assert.match(render(source), /<mark><strong>highlight<\/strong><\/mark>/);
assert.match(render(source), /md-inline-comment/);
});
+18
View File
@@ -0,0 +1,18 @@
import assert from "node:assert/strict";
import test from "node:test";
import { languageFor } from "../../../src/lib/editor/languageFor.ts";
test("markdown files use the markdown language", () => {
assert.equal(languageFor("notes/inbox.md"), "markdown");
assert.equal(languageFor("README.markdown"), "markdown");
});
test("python and scripts use their languages", () => {
assert.equal(languageFor("src/hello.py"), "python");
assert.equal(languageFor("tools/setup.sh"), "shell");
});
test("unknown extensions are plaintext", () => {
assert.equal(languageFor("Makefile"), "plaintext");
assert.equal(languageFor("notes/data.bin"), "plaintext");
});
+56
View File
@@ -0,0 +1,56 @@
import assert from "node:assert/strict";
import test from "node:test";
import { markdownBlocks, markdownFences } from "../../../src/lib/workspace/markdownBlocks.ts";
test("fenced block with a language is one fence", () => {
assert.deepEqual(markdownBlocks("hi\n```js\nconst x = 1\n```\nbye"), [
{ type: "text", line: "hi" },
{ type: "fence", lang: "js", body: "const x = 1" },
{ type: "text", line: "bye" },
]);
});
test("fenced block without a language keeps an empty lang", () => {
assert.deepEqual(markdownBlocks("```\nHUGE\n```"), [
{ type: "fence", lang: "", body: "HUGE" },
]);
});
test("inline backticks stay on a text line", () => {
assert.deepEqual(markdownBlocks("say `HUGE` now"), [
{ type: "text", line: "say `HUGE` now" },
]);
});
test("a fence opened and closed on one line is a fence", () => {
assert.deepEqual(markdownBlocks("```this was a triumph```"), [
{ type: "fence", lang: "", body: "this was a triumph" },
]);
});
test("closed fence body is the copy payload", () => {
assert.deepEqual(markdownFences("```js\nconst x = 1\n```"), [
{ lang: "js", body: "const x = 1", openLine: 1, closeLine: 3 },
]);
});
test("one-line fence body excludes ticks", () => {
assert.deepEqual(markdownFences("```this was a triumph```"), [
{ lang: "", body: "this was a triumph", openLine: 1, closeLine: 1 },
]);
});
test("unclosed fence is not MdFence", () => {
assert.deepEqual(markdownFences("```js\nconst x = 1\n"), []);
});
test("markdownBlocks fence body matches markdownFences", () => {
const src = "hi\n```js\nconst x = 1\n```\nbye";
const block = markdownBlocks(src).find((row) => row.type === "fence");
const fence = markdownFences(src)[0];
assert.equal(block && block.type === "fence" ? block.body : null, "const x = 1");
assert.equal(fence.body, "const x = 1");
assert.equal(fence.lang, "js");
assert.equal(fence.openLine, 2);
assert.equal(fence.closeLine, 4);
});
@@ -0,0 +1,60 @@
import assert from "node:assert/strict";
import test from "node:test";
import { formatText, paragraphText, insertBlock, type MarkdownEdit, type InlineFormat } from "../../../src/lib/editor/markdownCommands.ts";
const apply = (source: string, edit: MarkdownEdit) => source.slice(0, edit.from) + edit.insert + source.slice(edit.to);
test("inline formatting toggles without losing surrounding prose or the selected text", () => {
for (const format of ["bold", "italic", "strike", "highlight", "code", "math", "comment"] as InlineFormat[]) {
const source = "before words after", selection = { from: 7, to: 12 };
const edit = formatText(source, selection, format), changed = apply(source, edit);
assert.equal(changed.slice(edit.anchor, edit.head), "words");
assert.equal(apply(changed, formatText(changed, { from: edit.anchor, to: edit.head }, format)), source, format);
assert.equal(apply(changed, formatText(changed, { from: edit.from, to: edit.from + edit.insert.length }, format)), source, format);
}
assert.equal(apply("word ", formatText("word ", { from: 0, to: 5 }, "bold")), "**word** ");
assert.equal(apply("**bold**", formatText("**bold**", { from: 0, to: 8 }, "italic")), "***bold***");
const empty = formatText("", { from: 0, to: 0 }, "bold");
assert.equal(empty.insert, "****"); assert.equal(empty.anchor, 2); assert.equal(empty.head, 2);
});
test("code delimiters survive backticks and clear formatting preserves literal punctuation and newlines", () => {
const source = "a ` b", edit = formatText(source, { from: 0, to: source.length }, "code");
assert.equal(edit.insert, "``a ` b``");
assert.equal(apply(edit.insert, formatText(edit.insert, { from: edit.anchor, to: edit.head }, "code")), source);
assert.equal(apply(edit.insert, formatText(edit.insert, { from: 0, to: edit.insert.length }, "code")), source);
const rich = "**bold**\r\n==mark== and \\*literal\\*";
assert.equal(formatText(rich, { from: 0, to: rich.length }, "clear").insert, "bold\r\nmark and \\*literal\\*");
assert.equal(apply("***bold***", formatText("***bold***", { from: 3, to: 7 }, "clear")), "bold");
});
test("paragraph commands cover selected lines, omit an unselected next line, and preserve indentation and CRLF", () => {
const source = "before\r\n - [x] first\r\n 2. second\r\nafter";
const selected = { from: source.indexOf("first"), to: source.indexOf("after") };
assert.equal(apply(source, paragraphText(source, selected, 3)), "before\r\n ### first\r\n ### second\r\nafter");
assert.equal(apply(source, paragraphText(source, selected, "body")), "before\r\n first\r\n second\r\nafter");
assert.equal(paragraphText("one\ntwo\n\nthree", { from: 0, to: 14 }, "number").insert, "1. one\n2. two\n\n1. three");
assert.equal(paragraphText("", { from: 0, to: 0 }, "task").insert, "- [ ] ");
assert.equal(apply("one\ntwo", paragraphText("one\ntwo", { from: 4, to: 4 }, "quote")), "one\n> two");
});
test("block inserts retain adjacent text, escape code fences, and select editable placeholders", () => {
const source = "left right", selection = { from: 5, to: 10 };
for (const kind of ["table", "rule"] as const) {
const result = apply(source, insertBlock(source, selection, kind));
assert.ok(result.startsWith(source + "\n\n"));
}
const code = insertBlock("```", { from: 0, to: 3 }, "code");
assert.equal(code.insert, "````\n```\n````\n\n");
const table = insertBlock("", { from: 0, to: 0 }, "table");
assert.equal(table.insert.slice(table.anchor, table.head), "Column 1");
assert.equal(insertBlock("a\r\nb", { from: 3, to: 4 }, "callout").insert, "\r\n> [!note]\r\n> b\r\n\r\n");
});
test("footnotes get unique references, retain the document tail, and select the definition", () => {
const source = "One[^1] and words.\n\n[^1]: existing\n";
const from = source.indexOf("words"), edit = insertBlock(source, { from, to: from + 5 }, "footnote");
const changed = apply(source, edit);
assert.equal(changed, "One[^1] and [^2].\n\n[^1]: existing\n\n[^2]: words\n");
assert.equal(changed.slice(edit.anchor, edit.head), "words");
});
+36
View File
@@ -0,0 +1,36 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
findMarkdownImages,
isImagePath,
isRemoteImage,
resolveImageRel,
} from "../../../src/lib/workspace/media.ts";
test("image paths are detected by extension", () => {
assert.equal(isImagePath("screenshot.png"), true);
assert.equal(isImagePath("notes/photo.JPEG"), true);
assert.equal(isImagePath("notes/inbox.md"), false);
});
test("markdown image syntax is parsed", () => {
const found = findMarkdownImages("See ![alt](../shot.png) and ![[screenshot.png|Hero]]");
assert.equal(found.length, 2);
assert.equal(found[0].src, "../shot.png");
assert.equal(found[0].kind, "md");
assert.equal(found[1].src, "screenshot.png");
assert.equal(found[1].alt, "Hero");
assert.equal(found[1].kind, "wiki");
});
test("image paths resolve from the note folder", () => {
assert.equal(resolveImageRel("notes/inbox.md", "pic.png"), "notes/pic.png");
assert.equal(resolveImageRel("notes/inbox.md", "../screenshot.png"), "screenshot.png");
assert.equal(resolveImageRel("notes/inbox.md", "screenshot.png"), "notes/screenshot.png");
assert.equal(resolveImageRel("notes/inbox.md", "/assets/pic.png"), "assets/pic.png");
});
test("remote images stay as URLs", () => {
assert.equal(isRemoteImage("https://example.com/a.png"), true);
assert.equal(isRemoteImage("screenshot.png"), false);
});
+60
View File
@@ -0,0 +1,60 @@
import assert from "node:assert/strict";
import test from "node:test";
import { htmlToMarkdown } from "../../../src/lib/workspace/htmlToMarkdown.ts";
test("headings and inline marks become markdown", () => {
const html =
"<h1>Heading 1</h1><h2>Heading 2</h2><p>hello <strong>bold</strong> and <code>code</code></p>";
assert.equal(htmlToMarkdown(html), "# Heading 1\n## Heading 2\nhello **bold** and `code`");
});
test("fences keep language and body", () => {
const html = '<pre class="md-code" data-lang="js"><code class="language-js">const x = 1</code></pre>';
assert.equal(htmlToMarkdown(html), "```js\nconst x = 1\n```");
});
test("wiki and markdown links become markdown", () => {
const html =
'<p>see <a class="wiki" href="projects/alpha" data-kind="wiki">projects/alpha</a> and <a href="notes/a.md" data-kind="md">label</a></p>';
assert.equal(htmlToMarkdown(html), "see [[projects/alpha]] and [label](notes/a.md)");
});
test("wiki image uses data-md-kind", () => {
const html =
'<p><img src="data:image/png;base64,xx" alt="screenshot.png" data-md-src="screenshot.png" data-md-kind="wiki" /></p>';
assert.equal(htmlToMarkdown(html), "![[screenshot.png]]");
});
test("strike super and sub become markdown", () => {
const html = "<p><s>old</s> x<sup>2</sup> a<sub>n</sub></p>";
assert.equal(htmlToMarkdown(html), "~~old~~ x^2^ a~n~");
});
test("gfm table becomes markdown", () => {
const html =
"<table><thead><tr><th>A</th><th>B</th></tr></thead><tbody><tr><td>1</td><td>2</td></tr></tbody></table>";
assert.equal(htmlToMarkdown(html), "| A | B |\n| --- | --- |\n| 1 | 2 |");
});
test("checked task item becomes a checkbox line", () => {
const html =
'<ul data-type="taskList"><li data-type="taskItem" data-checked="true"><p>done</p></li></ul>';
assert.equal(htmlToMarkdown(html), "- [x] done");
});
test("unchecked task item becomes an empty checkbox", () => {
const html =
'<ul data-type="taskList"><li data-type="taskItem" data-checked="false"><p>todo</p></li></ul>';
assert.equal(htmlToMarkdown(html), "- [ ] todo");
});
test("italic highlight math and comment become markdown", () => {
const html =
'<p><em>hi</em> <mark>glow</mark> <span data-math="1">x^2</span> <span data-comment="1">note</span></p>';
assert.equal(htmlToMarkdown(html), "*hi* ==glow== $x^2$ %%note%%");
});
test("blockquote and numbered list become markdown", () => {
const html = "<blockquote><p>said</p></blockquote><ol><li>one</li><li>two</li></ol>";
assert.equal(htmlToMarkdown(html), "> said\n1. one\n2. two");
});
+103
View File
@@ -0,0 +1,103 @@
import assert from "node:assert/strict";
import test from "node:test";
import { markdownImages, renderMarkdownHtml, renderMarkdownSections } from "../../../src/lib/workspace/noteHtml.ts";
const render = (text: string) => renderMarkdownHtml(text, new Map());
test("writing sections retain exact source ranges and document-wide references", () => {
const source = '\uFEFF---\r\ntitle: Draft\r\n---\r\n\r\n# Heading\r\n\r\n- Parent\r\n - Child\r\n\r\nA [reference][ref].\r\n\r\n[ref]: https://example.com\r\n';
const sections = renderMarkdownSections(source, new Map());
assert.equal(sections.map(section => source.slice(section.start, section.end)).join(""), source);
assert.equal(sections.length, 4);
assert.match(sections[2].html, /<ul>[\s\S]*<ul>/);
assert.match(sections[3].html, /href="https:\/\/example.com"/);
const paragraph = sections[3];
const edited = source.slice(0, paragraph.start) + 'Changed paragraph.\r\n' + source.slice(paragraph.end);
assert.equal(edited.slice(0, paragraph.start), source.slice(0, paragraph.start));
});
test("writing exposes empty and reference-only documents for editing", () => {
for (const source of ["", "\n\n", "[ref]: https://example.com\n"]) {
assert.deepEqual(renderMarkdownSections(source, new Map()), [{ start: 0, end: source.length, html: "" }]);
}
});
test("Mermaid fences render diagram containers with escaped, copyable source", () => {
const html = render('```mermaid\nflowchart LR\n A["<script>bad</script>"] --> B\n```');
assert.match(html, /class="md-mermaid"/);
assert.match(html, /aria-label="Mermaid diagram"/);
assert.match(html, /<summary>Diagram source<\/summary>/);
assert.match(html, /&lt;script&gt;bad&lt;\/script&gt;/);
assert.doesNotMatch(html, /<script>/);
assert.doesNotMatch(render('```js\nconst x = 1;\n```'), /md-mermaid/);
});
test("reader joins soft-wrapped lines and preserves paragraph boundaries", () => {
assert.equal(render("First line\ncontinues here.\n\nSecond paragraph."), "<p>First line\ncontinues here.</p>\n<p>Second paragraph.</p>\n");
assert.match(render("Hard break \nnext line"), /Hard break<br>\nnext line/);
});
test("reader preserves nested lists, ordered starts and multi-paragraph items", () => {
const html = render("7. Parent\n - Nested **item**\n - Other\n8. Next\n\n Another paragraph.\n");
assert.match(html, /<ol start="7">/);
assert.match(html, /<li>\n<p>Parent<\/p>\n<ul>\n<li>Nested <strong>item<\/strong><\/li>/);
assert.match(html, /<p>Next<\/p>\n<p>Another paragraph\.<\/p>/);
});
test("reader renders aligned tables and read-only nested tasks", () => {
const html = render("| Left | Right |\n| :--- | ---: |\n| **a** | 2 |\n\n- [x] Done\n - [ ] Nested\n");
assert.match(html, /class="md-table-scroll"><table>/);
assert.match(html, /<th style="text-align:right">Right<\/th>/);
assert.equal((html.match(/type="checkbox" disabled/g) || []).length, 2);
assert.equal((html.match(/ checked>/g) || []).length, 1);
assert.doesNotMatch(html, /\[x\]|\[ \]/);
});
test("reader keeps code literal and escapes embedded HTML", () => {
const html = render('```js\nconst text = "[[note]] **bold** <script>alert(1)</script>";\n```\n\n`[[literal]]`\n\n<img src=x onerror=alert(1)>');
assert.match(html, /aria-label="Copy code"/);
assert.match(html, /\[\[note\]\] \*\*bold\*\* &lt;script&gt;/);
assert.match(html, /<code>\[\[literal\]\]<\/code>/);
assert.doesNotMatch(html, /<script>|<img|class="wiki"|<strong>/);
});
test("table cell line breaks render without enabling arbitrary HTML", () => {
const html = render('| Notes |\n| --- |\n| First<br>Second<BR />Third<br/>Fourth |');
assert.match(html, /First<br>\nSecond<br>\nThird<br>\nFourth/);
assert.doesNotMatch(html, /&lt;br/i);
assert.match(render('`<br>`'), /<code>&lt;br&gt;<\/code>/);
assert.doesNotMatch(render('<br onclick="alert(1)">'), /<br /);
});
test("frontmatter is collapsed separately from document headings", () => {
const html = render("\uFEFF---\r\ntitle: Notes\r\ntags: [work]\r\n---\r\n# Document\n");
assert.match(html, /^<details class="md-properties"><summary>Properties<\/summary><pre>title: Notes/);
assert.match(html, /<h1>Document<\/h1>/);
assert.doesNotMatch(html, /<h2>|<hr>|details[^>]*open/);
assert.match(render("---\n\nOrdinary rule"), /^<hr>/);
});
test("wiki links, aliases and reference images retain their targets", () => {
const source = 'See [[notes/one|First note]] and [second](second.md).\n\n![A **diagram**][diagram]\n\n![[assets/screenshot.png|Screenshot]]\n\n[diagram]: assets/my%20diagram.png "Diagram"\n';
const urls = new Map([['assets/my%20diagram.png', 'data:image/png;base64,AA=='], ['assets/screenshot.png', 'data:image/png;base64,BB==']]);
const html = renderMarkdownHtml(source, urls);
assert.match(html, /href="notes\/one" data-kind="wiki" class="wiki">First note/);
assert.match(html, /href="second.md" data-kind="md"/);
assert.match(html, /alt="A diagram"/);
assert.match(html, /data-md-kind="wiki"/);
assert.deepEqual(markdownImages(source + '\n`![[ignored.png]]`\n\n```\n![also ignored](x.png)\n```'), ['assets/my%20diagram.png', 'assets/screenshot.png']);
});
test("reader rejects executable links and image URL injection", () => {
const html = render('[bad](javascript:alert%281%29) [[javascript:alert(1)]] ![bad](javascript:alert%281%29)');
assert.doesNotMatch(html, /<a |<img /);
const image = renderMarkdownHtml('![[safe.png]]', new Map([['safe.png', 'javascript:alert(1)']]));
assert.match(image, /Image unavailable/);
});
test("note callouts separate their title from the Markdown body", () => {
const html = render('> [!tip] Keep context close\n> Use **notes** beside code.\n>\n> A second paragraph.');
assert.match(html, /class="md-callout" data-callout="tip"/);
assert.match(html, /class="md-callout-title">Keep context close<\/strong>Use <strong>notes<\/strong>/);
assert.match(html, /<p>A second paragraph\.<\/p>/);
});
+244
View File
@@ -0,0 +1,244 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
copySelection,
cutSelection,
pasteClipboard,
writerContextItems,
} from "../../../src/lib/editor/writerMenu.ts";
type Harness = {
selected: string;
inTable: boolean;
deleted: boolean;
focused: boolean;
inserted: string | null;
dispatched: boolean;
};
function fakeEditor(init?: { selected?: string; inTable?: boolean }) {
const harness: Harness = {
selected: init?.selected ?? "",
inTable: init?.inTable ?? false,
deleted: false,
focused: false,
inserted: null,
dispatched: false,
};
const tr = {
insertText(text: string) {
harness.inserted = text;
return tr;
},
};
const chainApi = {
focus() {
harness.focused = true;
return chainApi;
},
deleteSelection() {
harness.deleted = true;
return chainApi;
},
run() {
return true;
},
};
const editor = {
isActive(name: string) {
return name === "table" && harness.inTable;
},
chain() {
return chainApi;
},
state: {
selection: { from: 0, to: harness.selected.length },
doc: {
textBetween() {
return harness.selected;
},
},
tr,
},
view: {
dispatch() {
harness.dispatched = true;
},
},
};
return { editor, harness };
}
function withClipboard(
impl: { writeText?: (text: string) => Promise<void>; readText?: () => Promise<string> },
run: () => Promise<void>,
): Promise<void> {
const previous = Object.getOwnPropertyDescriptor(globalThis, "navigator");
Object.defineProperty(globalThis, "navigator", {
configurable: true,
value: { clipboard: impl },
});
return run().finally(() => {
if (previous) {
Object.defineProperty(globalThis, "navigator", previous);
} else {
Reflect.deleteProperty(globalThis, "navigator");
}
});
}
function actionLabels(items: ReturnType<typeof writerContextItems>): string[] {
const labels: string[] = [];
for (const item of items) {
if (item.kind === "action") {
labels.push(item.label);
} else if (item.kind === "group") {
for (const sub of item.items) {
if (sub.kind === "action") {
labels.push(sub.label);
}
}
}
}
return labels;
}
test("paste inserts clipboard text without parsing tags", async () => {
const { editor, harness } = fakeEditor();
await withClipboard(
{ readText: async () => "<b>bold</b>" },
async () => {
await pasteClipboard(editor as never);
},
);
assert.equal(harness.focused, true);
assert.equal(harness.dispatched, true);
assert.equal(harness.inserted, "<b>bold</b>");
});
test("paste swallows clipboard errors", async () => {
const { editor, harness } = fakeEditor();
await withClipboard(
{
readText: async () => {
throw new Error("denied");
},
},
async () => {
await pasteClipboard(editor as never);
},
);
assert.equal(harness.dispatched, false);
assert.equal(harness.inserted, null);
});
test("cut keeps the selection when clipboard write fails", async () => {
const { editor, harness } = fakeEditor({ selected: "gone" });
await withClipboard(
{
writeText: async () => {
throw new Error("denied");
},
},
async () => {
await cutSelection(editor as never);
},
);
assert.equal(harness.deleted, false);
});
test("copy swallows clipboard errors", async () => {
const { editor } = fakeEditor({ selected: "keep" });
let attempted = false;
await withClipboard(
{
writeText: async () => {
attempted = true;
throw new Error("denied");
},
},
async () => {
await copySelection(editor as never);
},
);
assert.equal(attempted, true);
});
test("cut writes selected text then deletes it", async () => {
const { editor, harness } = fakeEditor({ selected: "clip" });
let written = "";
await withClipboard(
{
writeText: async (text) => {
written = text;
},
},
async () => {
await cutSelection(editor as never);
},
);
assert.equal(written, "clip");
assert.equal(harness.deleted, true);
});
test("table row and column actions disable outside a table", () => {
const { editor } = fakeEditor({ inTable: false });
const items = writerContextItems(editor as never);
const table = items.find((item) => item.kind === "group" && item.label === "Table");
assert.equal(table?.kind, "group");
if (table?.kind !== "group") {
return;
}
const byLabel = new Map(
table.items.filter((item) => item.kind === "action").map((item) => [item.label, item]),
);
assert.equal(byLabel.get("Insert table")?.disabled, undefined);
assert.equal(byLabel.get("Add row above")?.disabled, true);
assert.equal(byLabel.get("Delete table")?.disabled, true);
});
test("table row and column actions enable inside a table", () => {
const { editor } = fakeEditor({ inTable: true });
const items = writerContextItems(editor as never);
const table = items.find((item) => item.kind === "group" && item.label === "Table");
assert.equal(table?.kind, "group");
if (table?.kind !== "group") {
return;
}
const byLabel = new Map(
table.items.filter((item) => item.kind === "action").map((item) => [item.label, item]),
);
assert.equal(byLabel.get("Insert table")?.disabled, undefined);
assert.equal(byLabel.get("Add row above")?.disabled, false);
assert.equal(byLabel.get("Delete table")?.disabled, false);
});
test("style and format actions cover the requested commands", () => {
const { editor } = fakeEditor();
const labels = actionLabels(writerContextItems(editor as never));
for (const label of [
"Cut",
"Copy",
"Paste",
"Heading 1",
"Heading 6",
"Body",
"Quote",
"Bullet list",
"Numbered list",
"Task list",
"Bold",
"Italic",
"Strikethrough",
"Highlight",
"Code",
"Math",
"Comment",
"Clear formatting",
"Insert table",
]) {
assert.equal(labels.includes(label), true, label);
}
assert.equal(labels.includes("Superscript"), false);
assert.equal(labels.includes("Subscript"), false);
});