RuneStone 1.0.0

This commit is contained in:
Knotty Wyvern
2026-11-16 04:21:21 -07:00
commit b52eeb14a1
827 changed files with 241421 additions and 0 deletions
+17
View File
@@ -0,0 +1,17 @@
import test from "node:test";
import assert from "node:assert/strict";
import { SearchQuery } from "@codemirror/search";
import { documentMatches } 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("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/);
});
+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-->');
});
+32
View File
@@ -0,0 +1,32 @@
import assert from "node:assert/strict";
import test from "node:test";
import { estimatedImageHeight, imageSize, rememberImageSize } from "../../../src/lib/workspace/imageSizes.ts";
import { renderMarkdownHtml } from "../../../src/lib/workspace/noteHtml.ts";
test("a rendered image has size attributes only when its size is known", () => {
const unknown = "data:image/png;base64,AAAA";
const known = "data:image/png;base64,BBBB";
rememberImageSize(known, 1400, 700);
const urls = new Map([["a.png", unknown], ["b.png", known]]);
assert.doesNotMatch(renderMarkdownHtml("![a](a.png)", urls), /width=/);
assert.match(renderMarkdownHtml("![b](b.png)", urls), /width="1400" height="700"/);
});
test("a large data URL keeps its size without the image data as the key", () => {
const url = `data:image/png;base64,${"A".repeat(5000)}${"B".repeat(100)}${"C".repeat(5000)}`;
const other = `data:image/png;base64,${"A".repeat(5000)}${"D".repeat(100)}${"C".repeat(5000)}`;
rememberImageSize(url, 10, 20);
assert.deepEqual(imageSize(url), { width: 10, height: 20 });
assert.equal(imageSize(other), undefined);
});
test("an image without a real size stays unknown", () => {
rememberImageSize("data:image/svg+xml;base64,AAAA", 0, 0);
assert.equal(imageSize("data:image/svg+xml;base64,AAAA"), undefined);
});
test("the estimate scales a wide image to the text column and keeps a small image", () => {
assert.equal(estimatedImageHeight('<img src="x" alt="">'), -1);
assert.equal(estimatedImageHeight('<img width="1480" height="740">'), 370 + 45);
assert.equal(estimatedImageHeight('<img width="100" height="50">'), 50 + 45);
});
+101
View File
@@ -0,0 +1,101 @@
import assert from "node:assert/strict";
import test from "node:test";
import { EditorState } from "@codemirror/state";
import { attachmentRel, dataUrlExtension, hasFileDrag, imageFiles, imageInsertion, mayAnimate, pastedImageSource, workspaceImageLink } from "../../../src/lib/workspace/media.ts";
import { copiedImage, keepCopiedImage } from "../../../src/lib/workspace/copiedImage.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("a copied web image names its original file in the clipboard HTML", () => {
const copy = (src: string) => `<html><body>\r\n<!--StartFragment--><img src="${src}"/><!--EndFragment-->\r\n</body>\r\n</html>`;
assert.equal(pastedImageSource(copy("https://media.example.com/cat.gif")), "https://media.example.com/cat.gif");
assert.equal(pastedImageSource(copy("https://cdn.example.com/a/b.WEBP?width=200&amp;ex=1")), "https://cdn.example.com/a/b.WEBP?width=200&ex=1");
assert.equal(pastedImageSource("<img alt='x' data-src='a.png' src='http://example.com/x.avif'>"), "http://example.com/x.avif");
assert.equal(pastedImageSource("<img src=https://example.com/x.gif>"), "https://example.com/x.gif");
assert.equal(pastedImageSource(copy("https://example.com/photo.jpg")), "https://example.com/photo.jpg");
// Firefox copies the element of the page with all of its attributes.
assert.equal(pastedImageSource('<img id="img" src="https://h.example.net/om/1/x.gif" style="width:640px" onload="update()">'), "https://h.example.net/om/1/x.gif");
// A missing address and other schemes keep the clipboard copy.
assert.equal(pastedImageSource(copy("data:image/gif;base64,R0lGODlh")), undefined);
assert.equal(pastedImageSource(copy("file:///C:/cat.gif")), undefined);
assert.equal(pastedImageSource(copy("cat.gif")), undefined);
assert.equal(pastedImageSource('<img srcset="https://example.com/x.gif 1x">'), undefined);
assert.equal(pastedImageSource(""), undefined);
// A copy of a page part with two images is not a copied image.
assert.equal(pastedImageSource(copy("https://example.com/a.gif") + copy("https://example.com/b.gif")), undefined);
});
test("only formats with frames get a download, and data URLs name their extension", () => {
assert.equal(mayAnimate("https://media.example.com/cat.gif"), true);
assert.equal(mayAnimate("https://cdn.example.com/a/b.WEBP?width=200"), true);
assert.equal(mayAnimate("http://example.com/x.avif"), true);
assert.equal(mayAnimate("https://example.com/photo.jpg"), false);
assert.equal(mayAnimate("https://example.com/image?format=gif"), false);
assert.equal(dataUrlExtension("data:image/gif;base64,R0lGODlh"), "gif");
assert.equal(dataUrlExtension("data:image/jpeg;base64,/9j/"), "jpg");
assert.equal(dataUrlExtension("data:image/webp;base64,UklG"), "webp");
assert.equal(dataUrlExtension("data:image/svg+xml;base64,PHN2Zz4="), undefined);
assert.equal(dataUrlExtension("data:text/html;base64,PGh0bWw+"), undefined);
});
test("a paste uses only the original of the image that the RuneStone browser copied last", async () => {
assert.equal(await copiedImage("https://example.com/a.gif"), undefined);
let finish: (value: string) => void = () => {};
keepCopiedImage("https://example.com/a.gif", new Promise(resolve => { finish = resolve; }));
const waiting = copiedImage("https://example.com/a.gif");
finish("data:image/gif;base64,R0lGODlh");
assert.equal(await waiting, "data:image/gif;base64,R0lGODlh");
assert.equal(await copiedImage("https://example.com/b.gif"), undefined);
keepCopiedImage("https://example.com/b.gif", Promise.reject(new Error("engine stopped")));
assert.equal(await copiedImage("https://example.com/b.gif"), undefined);
assert.equal(await copiedImage("https://example.com/a.gif"), undefined, "a newer copy replaces the older one");
});
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");
});
+90
View File
@@ -0,0 +1,90 @@
import assert from "node:assert/strict";
import test from "node:test";
import { EditorState } from "@codemirror/state";
import { indentUnit } from "@codemirror/language";
import { markdown, markdownLanguage } from "@codemirror/lang-markdown";
import { noteFormats } from "../../../src/lib/editor/noteFormats.ts";
import { indentListItems, listLabels, orderedLabel, outdentListItems } from "../../../src/lib/editor/markdownLists.ts";
const extensions = [markdown({ base: markdownLanguage, extensions: [noteFormats] }), indentUnit.of(" ")];
/** A document with `|` at the caret, or two `|` around a selection. */
function editor(marked: string) {
const anchor = marked.indexOf("|"), head = marked.indexOf("|", anchor + 1);
const doc = marked.replaceAll("|", "");
return EditorState.create({ doc, selection: { anchor, head: head < 0 ? anchor : head - 1 }, extensions });
}
function run(move: typeof indentListItems, marked: string) {
const state = editor(marked), specs = move(state);
if (!specs) return null;
const next = state.update(...specs).state;
const { from, to } = next.selection.main;
const doc = next.doc.toString();
return from === to ? doc.slice(0, from) + "|" + doc.slice(from) : doc.slice(0, from) + "|" + doc.slice(from, to) + "|" + doc.slice(to);
}
test("tab makes a nested list and renumbers the items after it", () => {
assert.equal(run(indentListItems, "1. Topic\n2. B|\n3. A"), "1. Topic\n 1. B|\n2. A");
});
test("tab on an empty item keeps the caret after its marker", () => {
assert.equal(run(indentListItems, "1. Topic\n2.|\n3. A"), "1. Topic\n 1.|\n2. A");
assert.equal(run(indentListItems, "1. Topic\n2. |\n3. A"), "1. Topic\n 1. |\n2. A");
});
test("tab adds the item to the nested list of the previous item", () => {
assert.equal(run(indentListItems, "1. A\n 1. x\n2. B|\n3. C"), "1. A\n 1. x\n 2. B|\n2. C");
});
test("tab moves the children of an item with it", () => {
assert.equal(run(indentListItems, "1. A\n2. B|\n 1. b\n3. C"), "1. A\n 1. B|\n 1. b\n2. C");
});
test("tab nests each selected item under the first unselected item", () => {
assert.equal(run(indentListItems, "1. A\n|2. B\n3. C|\n4. D"), "1. A\n| 1. B\n 2. C|\n2. D");
});
test("tab nests bullet items and keeps their marker", () => {
assert.equal(run(indentListItems, "- a\n- b|"), "- a\n - b|");
assert.equal(run(indentListItems, "- [ ] a\n- [x] b|"), "- [ ] a\n - [x] b|");
});
test("tab keeps the first item in place and ignores text outside lists", () => {
assert.deepEqual(indentListItems(editor("1. A|\n2. B")), []);
assert.equal(indentListItems(editor("Plain| text")), null);
assert.equal(indentListItems(editor("1. A\n\n ```\n co|de\n ```")), null);
});
test("shift+tab moves a nested item up and makes the later items its children", () => {
assert.equal(run(outdentListItems, "1. A\n 1. x\n 2. y|\n 3. z\n2. B"), "1. A\n 1. x\n2. y|\n 1. z\n3. B");
});
test("shift+tab gives the item the marker style of the outer list", () => {
assert.equal(run(outdentListItems, "1. A\n - x|\n2. B"), "1. A\n2. x|\n3. B");
assert.equal(run(outdentListItems, "- A\n 1. x|\n- B"), "- A\n- x|\n- B");
});
test("shift+tab keeps a top-level item in place", () => {
assert.deepEqual(outdentListItems(editor("1. A|\n2. B")), []);
assert.equal(outdentListItems(editor("Plain| text")), null);
});
test("ordered labels use numbers, letters, and Roman numerals by level", () => {
assert.equal(orderedLabel(1, 3), "3");
assert.equal(orderedLabel(2, 1), "a");
assert.equal(orderedLabel(2, 27), "aa");
assert.equal(orderedLabel(3, 4), "iv");
assert.equal(orderedLabel(4, 2), "2");
assert.equal(orderedLabel(2, 0), "0");
});
test("nested ordered markers get labels and the first level keeps its source", () => {
const state = editor("1. A\n 1. x\n 1. y\n 1. z\n2. B|");
assert.deepEqual(listLabels(state).map(label => [state.sliceDoc(label.from, label.to), label.label]), [["1.", "a."], ["1.", "b."], ["1.", "i."]]);
});
test("an empty nested marker gets its label before the item has text", () => {
const state = editor("1. Topic\n 1.\n2. A|");
assert.deepEqual(listLabels(state).map(label => label.label), ["a."]);
});
+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>/);
});