Skip to content

A tiny friend in your Mac's notch and on your iPhone that keeps an eye on your AI coding agents: Claude Code, Codex, Cursor, Gemini CLI, Antigravity and more. Approve from the notch or your Lock Screen.

Chat: Markdown in the answers, with a copy button on code blocks

Claude5b4ee6188e2c
diff --git a/windows/src/style.css b/windows/src/style.css
index b2cf6756..12f19066 100644
--- a/windows/src/style.css
+++ b/windows/src/style.css
@@ -827,6 +827,127 @@ input[type="range"]::-webkit-slider-thumb {
white-space: pre-wrap;
padding-right: 8px;
user-select: text;
+ /* Answers are Markdown blocks (views/markdown.ts), spaced as ChatMarkdownView. */
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ min-width: 0;
+}
+
+/* ── Markdown in the answers ─────────────────────────────────────────────── */
+
+.md-p {
+ font: 400 12.5px var(--font);
+ color: #b0b5be;
+ white-space: pre-wrap;
+ overflow-wrap: anywhere;
+}
+
+.md-h {
+ font: 600 13px var(--font);
+ color: var(--ink-2);
+ overflow-wrap: anywhere;
+}
+
+.md-h1 {
+ font-weight: 700;
+ font-size: 14px;
+}
+
+.reply strong {
+ color: #e8e9ec;
+ font-weight: 600;
+}
+
+.md-code {
+ padding: 1px 4px;
+ border-radius: 4px;
+ background: rgba(255, 255, 255, 0.08);
+ font: 400 11.5px var(--mono);
+ color: #c8cdd4;
+}
+
+.md-link {
+ color: #60a5fa;
+ text-decoration: underline;
+ cursor: pointer;
+}
+
+.md-pre {
+ display: flex;
+ align-items: flex-start;
+ gap: 8px;
+ padding: 10px;
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ border-radius: 8px;
+ background: #0d0e12;
+}
+
+.md-pre pre {
+ flex: 1 1 auto;
+ min-width: 0;
+ font: 400 11px var(--mono);
+ color: #c8cdd4;
+ white-space: pre-wrap;
+ overflow-wrap: anywhere;
+}
+
+.md-copy {
+ flex: 0 0 22px;
+ display: grid;
+ place-items: center;
+ width: 22px;
+ height: 22px;
+ padding: 0;
+ border: 0;
+ border-radius: 4px;
+ background: rgba(255, 255, 255, 0.06);
+ color: var(--dim-3);
+ cursor: default;
+}
+
+.md-copy:hover {
+ color: var(--dim);
+}
+
+.md-copy.done {
+ color: var(--green);
+}
+
+.md-item {
+ display: flex;
+ align-items: flex-start;
+ gap: 6px;
+}
+
+.md-bullet {
+ flex: 0 0 auto;
+ min-width: 10px;
+ font: 400 12.5px var(--font);
+ color: var(--dim-3);
+}
+
+.md-quote {
+ display: flex;
+ align-items: stretch;
+ gap: 8px;
+}
+
+.md-quote i {
+ flex: 0 0 2px;
+ border-radius: 1px;
+ background: var(--dim-5);
+}
+
+.md-quote .md-p {
+ color: #8a8f98;
+}
+
+.md-rule {
+ width: 100%;
+ border: 0;
+ border-top: 1px solid rgba(255, 255, 255, 0.3);
+ opacity: 0.3;
}
.typing {
diff --git a/windows/src/views/chat.ts b/windows/src/views/chat.ts
index 2cd253f7..6b28965d 100644
--- a/windows/src/views/chat.ts
+++ b/windows/src/views/chat.ts
@@ -1,8 +1,9 @@
// Chat view — DOM port of PromptView / ChatBubble / TypingDotsView from
-// IslandViewContent.swift.
+// IslandViewContent.swift. Answers are rendered as Markdown (markdown.ts).
import { h, svg, clear } from "./dom";
import { ICONS } from "./icons";
+import { renderMarkdown } from "./markdown";
import { Bridge, type ChatContext } from "../core/bridge";
import { Sound } from "../core/sound";
import { State, type ChatMessage } from "../core/state";
@@ -18,7 +19,9 @@ function bubble(message: ChatMessage): HTMLElement {
h("div", { class: "bubble", text: message.content }),
);
}
- return h("div", { class: "chat-row" }, h("div", { class: "reply", text: message.content }));
+ const reply = h("div", { class: "reply" });
+ renderMarkdown(reply, message.content);
+ return h("div", { class: "chat-row" }, reply);
}
function typingDots(): HTMLElement {
diff --git a/windows/src/views/icons.ts b/windows/src/views/icons.ts
index d2ff8247..e2fc64e5 100644
--- a/windows/src/views/icons.ts
+++ b/windows/src/views/icons.ts
@@ -36,6 +36,10 @@ export const ICONS = {
star: "M12 3.2l2.6 5.55 5.9.82-4.3 4.3 1.05 6.13L12 17.1l-5.25 2.9L7.8 13.87 3.5 9.57l5.9-.82L12 3.2z",
// square.stack.fill
stack: "M5 8h14v11.5H5V8zm1.8-3h10.4v1.6H6.8V5zm1.6-2.6h7.2V4H8.4V2.4z",
+ // doc.on.doc (copy)
+ copy: "M9 3.5h8.5L21 7v10.5H9v-14zm1.8 1.8v10.4h8.4V7.8l-2.5-2.5h-5.9zM3 7.5h4.2v1.8H4.8v10.4h8.4v-2.2H15v4H3v-14z",
+ // chevron.up.chevron.down
+ chevronUpDown: "M8 9.5 12 5.5l4 4M8 14.5l4 4 4-4",
// doc.text
doc: "M6.5 2.6h7l4 4v14.8h-11V2.6zm6.6 1.6v3.3h3.3l-3.3-3.3zM8.6 11h6.8v1.5H8.6V11zm0 3.4h6.8v1.5H8.6v-1.5z",
} as const;
diff --git a/windows/src/views/markdown.ts b/windows/src/views/markdown.ts
new file mode 100644
index 00000000..0501af19
--- /dev/null
+++ b/windows/src/views/markdown.ts
@@ -0,0 +1,265 @@
+// Markdown in the chat's answers, as on the Mac (ChatMarkdown.swift and
+// ChatMarkdownView.swift): headings, paragraphs, fenced code with a copy button,
+// bullet and numbered lists, quotes and rules, with bold, italic, `code` and
+// links inside the text.
+//
+// Everything is built as DOM nodes with textContent, never as HTML, so nothing
+// a model writes can inject markup. Links open only when they are http(s), and
+// even then through Rust, which checks the scheme again.
+
+import { Bridge } from "../core/bridge";
+import { h, svg } from "./dom";
+import { ICONS } from "./icons";
+
+const STRINGS = {
+ copy: "Copy",
+ copied: "Copied",
+};
+
+export type Block =
+ | { kind: "heading"; level: number; text: string }
+ | { kind: "paragraph"; text: string }
+ | { kind: "code"; lang: string; code: string }
+ /** `prefix` is "•" or "1."; `indent` the nesting level, from 0. */
+ | { kind: "item"; prefix: string; text: string; indent: number }
+ | { kind: "quote"; text: string }
+ | { kind: "rule" };
+
+const isRule = (s: string) => s === "---" || s === "***" || s === "___";
+const isBullet = (s: string) => /^[-*+] /.test(s);
+const ordered = (s: string) => /^(\d+)\.\s+/.exec(s);
+const isQuote = (s: string) => s.startsWith("> ") || s === ">";
+
+/** Same rules as the Mac's parser, line by line. */
+export function parseMarkdown(input: string): Block[] {
+ const blocks: Block[] = [];
+ const lines = input.replace(/\r\n?/g, "\n").split("\n");
+ let i = 0;
+ while (i < lines.length) {
+ const line = lines[i];
+
+ if (line.startsWith("```")) {
+ const lang = line.slice(3).trim();
+ const code: string[] = [];
+ for (i++; i < lines.length && !lines[i].startsWith("```"); i++) code.push(lines[i]);
+ blocks.push({ kind: "code", lang, code: code.join("\n") });
+ i++;
+ continue;
+ }
+
+ // A heading needs a space after the #s; "#hashtag" stays a paragraph.
+ const hashes = /^#+/.exec(line)?.[0].length ?? 0;
+ if (hashes && (line.length === hashes || line[hashes] === " ")) {
+ const text = line.slice(hashes).trim();
+ if (text) blocks.push({ kind: "heading", level: Math.min(hashes, 6), text });
+ i++;
+ continue;
+ }
+
+ const stripped = line.trim();
+ if (isRule(stripped)) {
+ blocks.push({ kind: "rule" });
+ i++;
+ continue;
+ }
+ if (isQuote(stripped)) {
+ blocks.push({ kind: "quote", text: stripped.startsWith("> ") ? stripped.slice(2) : "" });
+ i++;
+ continue;
+ }
+
+ const indent = Math.floor((line.length - line.trimStart().length) / 2);
+ if (isBullet(stripped)) {
+ blocks.push({ kind: "item", prefix: "•", text: stripped.slice(2), indent });
+ i++;
+ continue;
+ }
+ const number = ordered(stripped);
+ if (number) {
+ blocks.push({ kind: "item", prefix: `${number[1]}.`, text: stripped.slice(number[0].length), indent });
+ i++;
+ continue;
+ }
+ if (!stripped) {
+ i++;
+ continue;
+ }
+
+ // A paragraph runs until a blank line or the start of another block.
+ const para = [line];
+ for (i++; i < lines.length; i++) {
+ const next = lines[i];
+ const s = next.trim();
+ if (!s || next.startsWith("#") || next.startsWith("```") || isQuote(s) || isBullet(s) || isRule(s) || ordered(s)) break;
+ para.push(next);
+ }
+ blocks.push({ kind: "paragraph", text: para.join("\n") });
+ }
+ return blocks;
+}
+
+// ── Inline ────────────────────────────────────────────────────────────────────
+
+export type Inline =
+ | { kind: "text"; text: string }
+ | { kind: "code"; text: string }
+ | { kind: "strong"; children: Inline[] }
+ | { kind: "em"; children: Inline[] }
+ /** `url` is null when the target is not a web address: the text stays, the link goes. */
+ | { kind: "link"; url: string | null; children: Inline[] };
+
+/**
+ * `code`, **bold**, __bold__, *italic*, _italic_ and [text](url), whichever
+ * comes first. No lookbehind: older WebKitGTK builds reject it, and one bad
+ * regex literal would take the whole island down with it.
+ */
+const INLINE = /`([^`\n]+)`|\*\*([^*]+?)\*\*|__([^_]+?)__|\*([^*\s][^*]*?)\*|_([^_\s][^_]*?)_(?!\w)|\[([^\]\n]+)\]\(([^)\s]+)\)/g;
+
+const isWordChar = (c: string | undefined) => c != null && /\w/.test(c);
+
+/** The address if it is an http(s) one; anything else (javascript:, file:, data:…) is not a link. */
+export function safeWebUrl(raw: string): string | null {
+ try {
+ const url = new URL(raw.trim());
+ return url.protocol === "http:" || url.protocol === "https:" ? url.href : null;
+ } catch {
+ return null;
+ }
+}
+
+export function parseInline(text: string): Inline[] {
+ const out: Inline[] = [];
+ const pushText = (t: string) => {
+ if (!t) return;
+ const last = out[out.length - 1];
+ if (last?.kind === "text") last.text += t;
+ else out.push({ kind: "text", text: t });
+ };
+ const re = new RegExp(INLINE.source, "g");
+ let at = 0;
+ let m: RegExpExecArray | null;
+ while ((m = re.exec(text))) {
+ // snake_case_words are not italics: an opening _ must not follow a letter.
+ if (m[5] != null && isWordChar(text[m.index - 1])) {
+ re.lastIndex = m.index + 1;
+ continue;
+ }
+ pushText(text.slice(at, m.index));
+ at = m.index + m[0].length;
+ if (m[1] != null) out.push({ kind: "code", text: m[1] });
+ else if (m[6] != null) out.push({ kind: "link", url: safeWebUrl(m[7]), children: parseInline(m[6]) });
+ else if (m[2] != null || m[3] != null) out.push({ kind: "strong", children: parseInline(m[2] ?? m[3]) });
+ else out.push({ kind: "em", children: parseInline(m[4] ?? m[5]) });
+ }
+ pushText(text.slice(at));
+ return out;
+}
+
+function appendInline(into: HTMLElement, nodes: Inline[]) {
+ for (const node of nodes) {
+ switch (node.kind) {
+ case "text":
+ into.append(document.createTextNode(node.text));
+ break;
+ case "code":
+ into.append(h("code", { class: "md-code", text: node.text }));
+ break;
+ case "strong":
+ case "em": {
+ const el = h(node.kind === "strong" ? "strong" : "em");
+ appendInline(el, node.children);
+ into.append(el);
+ break;
+ }
+ case "link": {
+ if (!node.url) {
+ appendInline(into, node.children);
+ break;
+ }
+ const url = node.url;
+ const a = h("a", { class: "md-link", href: url, title: url });
+ a.addEventListener("click", (e) => {
+ e.preventDefault();
+ void Bridge.openUrl(url);
+ });
+ appendInline(a, node.children);
+ into.append(a);
+ break;
+ }
+ }
+ }
+}
+
+function inline(text: string, into: HTMLElement) {
+ appendInline(into, parseInline(text));
+}
+
+// ── Blocks ────────────────────────────────────────────────────────────────────
+
+async function writeClipboard(text: string) {
+ try {
+ await navigator.clipboard.writeText(text);
+ } catch {
+ // No clipboard API (or no permission): the old way, through a hidden field.
+ const area = h("textarea", { style: "position:fixed;opacity:0" }) as HTMLTextAreaElement;
+ area.value = text;
+ document.body.append(area);
+ area.select();
+ document.execCommand("copy");
+ area.remove();
+ }
+}
+
+/** Puts the code on the clipboard; the check mark shows for a moment. */
+function copyButton(text: string): HTMLElement {
+ const btn = h("button", { class: "md-copy", title: STRINGS.copy, "aria-label": STRINGS.copy }, svg(ICONS.copy, 11));
+ btn.addEventListener("click", async (e) => {
+ e.stopPropagation();
+ await writeClipboard(text);
+ btn.replaceChildren(svg(ICONS.check, 11, { stroke: 2.2 }));
+ btn.classList.add("done");
+ btn.title = STRINGS.copied;
+ window.setTimeout(() => {
+ btn.replaceChildren(svg(ICONS.copy, 11));
+ btn.classList.remove("done");
+ btn.title = STRINGS.copy;
+ }, 1500);
+ });
+ return btn;
+}
+
+function render(block: Block): HTMLElement {
+ switch (block.kind) {
+ case "heading": {
+ const el = h("div", { class: block.level <= 2 ? "md-h md-h1" : "md-h" });
+ inline(block.text, el);
+ return el;
+ }
+ case "paragraph": {
+ const el = h("div", { class: "md-p" });
+ inline(block.text, el);
+ return el;
+ }
+ case "code":
+ return h("div", { class: "md-pre" }, h("pre", { text: block.code }), copyButton(block.code));
+ case "item": {
+ const text = h("span", { class: "md-p" });
+ inline(block.text, text);
+ const item = h("div", { class: "md-item" }, h("span", { class: "md-bullet", text: block.prefix }), text);
+ if (block.indent) item.style.paddingLeft = `${block.indent * 12}px`;
+ return item;
+ }
+ case "quote": {
+ const text = h("span", { class: "md-p" });
+ inline(block.text, text);
+ return h("div", { class: "md-quote" }, h("i"), text);
+ }
+ case "rule":
+ return h("hr", { class: "md-rule" });
+ }
+}
+
+/** Replaces what `into` shows with the Markdown rendered. */
+export function renderMarkdown(into: HTMLElement, markdown: string) {
+ into.replaceChildren(...parseMarkdown(markdown).map(render));
+}
diff --git a/windows/tests/fakedom.mjs b/windows/tests/fakedom.mjs
new file mode 100644
index 00000000..a8869b44
--- /dev/null
+++ b/windows/tests/fakedom.mjs
@@ -0,0 +1,133 @@
+// Just enough of a DOM for the views' helpers (views/dom.ts) to build nodes in
+// Node. Writing `innerHTML` throws: a view that renders untrusted text must
+// never parse it as markup, and a test that reaches for it fails loudly.
+
+class FakeText {
+ constructor(text) {
+ this.nodeType = 3;
+ this.data = String(text);
+ this.parentNode = null;
+ }
+ get textContent() {
+ return this.data;
+ }
+}
+
+class FakeElement {
+ constructor(tag, ns = null) {
+ this.nodeType = 1;
+ this.tagName = String(tag).toUpperCase();
+ this.namespaceURI = ns;
+ this.childNodes = [];
+ this.parentNode = null;
+ this.attributes = new Map();
+ this.listeners = new Map();
+ this.className = "";
+ this.title = "";
+ this.dataset = {};
+ this.scrollTop = 0;
+ this.scrollHeight = 0;
+ this.style = { setProperty: (k, v) => (this.style[k] = v) };
+ const el = this;
+ this.classList = {
+ add: (c) => (el.className = [...new Set([...el.className.split(" ").filter(Boolean), c])].join(" ")),
+ remove: (c) => (el.className = el.className.split(" ").filter((x) => x && x !== c).join(" ")),
+ contains: (c) => el.className.split(" ").includes(c),
+ toggle: (c, on) => ((on ?? !el.classList.contains(c)) ? el.classList.add(c) : el.classList.remove(c)),
+ };
+ }
+ set innerHTML(_) {
+ throw new Error("innerHTML must never be used");
+ }
+ get innerHTML() {
+ throw new Error("innerHTML must never be used");
+ }
+ set outerHTML(_) {
+ throw new Error("outerHTML must never be used");
+ }
+ insertAdjacentHTML() {
+ throw new Error("insertAdjacentHTML must never be used");
+ }
+ get parentElement() {
+ return this.parentNode?.nodeType === 1 ? this.parentNode : null;
+ }
+ get children() {
+ return this.childNodes.filter((n) => n.nodeType === 1);
+ }
+ get firstChild() {
+ return this.childNodes[0] ?? null;
+ }
+ get textContent() {
+ return this.childNodes.map((n) => n.textContent).join("");
+ }
+ set textContent(text) {
+ this.childNodes = [];
+ if (text !== "") this.append(new FakeText(text));
+ }
+ setAttribute(k, v) {
+ this.attributes.set(k, String(v));
+ }
+ getAttribute(k) {
+ return this.attributes.get(k) ?? null;
+ }
+ addEventListener(type, fn) {
+ this.listeners.set(type, [...(this.listeners.get(type) ?? []), fn]);
+ }
+ /** Calls the listeners of `type` with a minimal event. */
+ fire(type) {
+ const event = { type, defaultPrevented: false, preventDefault() { this.defaultPrevented = true; }, stopPropagation() {} };
+ for (const fn of this.listeners.get(type) ?? []) fn(event);
+ return event;
+ }
+ append(...nodes) {
+ for (const n of nodes) {
+ const node = typeof n === "string" ? new FakeText(n) : n;
+ node.parentNode = this;
+ this.childNodes.push(node);
+ }
+ }
+ replaceChildren(...nodes) {
+ this.childNodes = [];
+ this.append(...nodes);
+ }
+ removeChild(node) {
+ this.childNodes = this.childNodes.filter((n) => n !== node);
+ return node;
+ }
+ remove() {
+ this.parentNode?.removeChild(this);
+ }
+ /** `.a.b` class selectors only: the first descendant carrying every class. */
+ querySelector(selector) {
+ const wanted = selector.split(".").filter(Boolean);
+ return [...this.walk()].find((e) => wanted.every((c) => e.classList.contains(c))) ?? null;
+ }
+ scrollIntoView() {}
+ focus() {}
+ select() {}
+ /** Every descendant element, depth first. */
+ *walk() {
+ for (const c of this.children) {
+ yield c;
+ yield* c.walk();
+ }
+ }
+ /** Descendants by tag name ("A") or class (".md-p"). */
+ find(selector) {
+ const match = selector.startsWith(".")
+ ? (e) => e.classList.contains(selector.slice(1))
+ : (e) => e.tagName === selector.toUpperCase();
+ return [...this.walk()].filter(match);
+ }
+}
+
+export function installFakeDom() {
+ globalThis.requestAnimationFrame = (fn) => fn();
+ globalThis.document = {
+ createElement: (tag) => new FakeElement(tag),
+ createElementNS: (ns, tag) => new FakeElement(tag, ns),
+ createTextNode: (text) => new FakeText(text),
+ body: new FakeElement("body"),
+ };
+ return { root: () => new FakeElement("div") };
+}
diff --git a/windows/tests/markdown.test.mjs b/windows/tests/markdown.test.mjs
new file mode 100644
index 00000000..5fc3d08e
--- /dev/null
+++ b/windows/tests/markdown.test.mjs
@@ -0,0 +1,137 @@
+// Markdown in the chat's answers (src/views/markdown.ts): the block parser
+// follows ChatMarkdown.swift, inline syntax is parsed to a tree, and rendering
+// builds DOM nodes from text only — never HTML — with http(s)-only links.
+
+import { beforeEach, test } from "node:test";
+import assert from "node:assert/strict";
+import { installFakeDom } from "./fakedom.mjs";
+import { calls, sent } from "./tauri.mjs";
+
+const dom = installFakeDom();
+const { parseMarkdown, parseInline, renderMarkdown, safeWebUrl } = await import("../src/views/markdown.ts");
+
+beforeEach(() => {
+ calls.length = 0;
+});
+
+// ── Blocks ────────────────────────────────────────────────────────────────────
+
+test("headings need a space after the hashes", () => {
+ assert.deepEqual(parseMarkdown("# Title\n## Sub\n####### Deep"), [
+ { kind: "heading", level: 1, text: "Title" },
+ { kind: "heading", level: 2, text: "Sub" },
+ { kind: "heading", level: 6, text: "Deep" },
+ ]);
+ assert.deepEqual(parseMarkdown("#hashtag"), [{ kind: "paragraph", text: "#hashtag" }]);
+});
+
+test("a fenced code block keeps its lines as they are, language apart", () => {
+ const md = "Before\n```python\nprint('hi')\n indented\n\n# not a heading\n```\nAfter";
+ assert.deepEqual(parseMarkdown(md), [
+ { kind: "paragraph", text: "Before" },
+ { kind: "code", lang: "python", code: "print('hi')\n indented\n\n# not a heading" },
+ { kind: "paragraph", text: "After" },
+ ]);
+ // An unclosed fence runs to the end, as while an answer is still streaming.
+ assert.deepEqual(parseMarkdown("```\nlet x"), [{ kind: "code", lang: "", code: "let x" }]);
+});
+
+test("lists keep their markers and nesting", () => {
+ assert.deepEqual(parseMarkdown("- one\n* two\n + nested\n1. first\n12. twelfth"), [
+ { kind: "item", prefix: "•", text: "one", indent: 0 },
+ { kind: "item", prefix: "•", text: "two", indent: 0 },
+ { kind: "item", prefix: "•", text: "nested", indent: 1 },
+ { kind: "item", prefix: "1.", text: "first", indent: 0 },
+ { kind: "item", prefix: "12.", text: "twelfth", indent: 0 },
+ ]);
+});
+
+test("quotes, rules and paragraphs that stop at the next block", () => {
+ assert.deepEqual(parseMarkdown("> quoted\n>\n---\nline one\nline two\n- item\n\npara"), [
+ { kind: "quote", text: "quoted" },
+ { kind: "quote", text: "" },
+ { kind: "rule" },
+ { kind: "paragraph", text: "line one\nline two" },
+ { kind: "item", prefix: "•", text: "item", indent: 0 },
+ { kind: "paragraph", text: "para" },
+ ]);
+ assert.deepEqual(parseMarkdown("a\r\nb"), [{ kind: "paragraph", text: "a\nb" }]);
+ assert.deepEqual(parseMarkdown(""), []);
+});
+
+// ── Inline ────────────────────────────────────────────────────────────────────
+
+test("inline code, bold, italic and links nest as a tree", () => {
+ assert.deepEqual(parseInline("Use `npm ci` **now**, *really* or __not__ _ever_."), [
+ { kind: "text", text: "Use " },
+ { kind: "code", text: "npm ci" },
+ { kind: "text", text: " " },
+ { kind: "strong", children: [{ kind: "text", text: "now" }] },
+ { kind: "text", text: ", " },
+ { kind: "em", children: [{ kind: "text", text: "really" }] },
+ { kind: "text", text: " or " },
+ { kind: "strong", children: [{ kind: "text", text: "not" }] },
+ { kind: "text", text: " " },
+ { kind: "em", children: [{ kind: "text", text: "ever" }] },
+ { kind: "text", text: "." },
+ ]);
+ assert.deepEqual(parseInline("[**Docs**](https://example.com/a?b=1)"), [
+ { kind: "link", url: "https://example.com/a?b=1", children: [{ kind: "strong", children: [{ kind: "text", text: "Docs" }] }] },
+ ]);
+});
+
+test("snake_case words and code spans are not italics", () => {
+ assert.deepEqual(parseInline("call my_long_name now"), [{ kind: "text", text: "call my_long_name now" }]);
+ assert.deepEqual(parseInline("`a *b* c`"), [{ kind: "code", text: "a *b* c" }]);
+ assert.deepEqual(parseInline("2 * 3 * 4"), [{ kind: "text", text: "2 * 3 * 4" }]);
+});
+
+test("only http and https addresses become links", () => {
+ assert.equal(safeWebUrl("https://example.com"), "https://example.com/");
+ assert.equal(safeWebUrl("http://localhost:3000/x"), "http://localhost:3000/x");
+ for (const bad of ["javascript:alert(1)", "JaVaScRiPt:alert(1)", "file:///etc/passwd", "data:text/html,<b>x</b>", "vbscript:x", "/relative", "mailto:[email protected]", "not a url"]) {
+ assert.equal(safeWebUrl(bad), null, bad);
+ }
+ assert.deepEqual(parseInline("[click](javascript:alert(1))"), [
+ { kind: "link", url: null, children: [{ kind: "text", text: "click" }] },
+ { kind: "text", text: ")" },
+ ]);
+});
+
+// ── Rendering ─────────────────────────────────────────────────────────────────
+
+test("markup in an answer is shown as text, never parsed", () => {
+ const root = dom.root();
+ const evil = '<img src=x onerror="alert(1)"> **<script>alert(2)</script>**\n```\n<b>code</b>\n```';
+ renderMarkdown(root, evil); // fakedom throws if anything touches innerHTML
+ assert.equal(root.find("IMG").length, 0);
+ assert.equal(root.find("SCRIPT").length, 0);
+ assert.equal(root.find("B").length, 0);
+ assert.match(root.textContent, /<img src=x onerror="alert\(1\)">/);
+ assert.equal(root.find("STRONG")[0].textContent, "<script>alert(2)</script>");
+ assert.equal(root.find("PRE")[0].textContent, "<b>code</b>");
+});
+
+test("each block becomes its own element", () => {
+ const root = dom.root();
+ renderMarkdown(root, "## Answer\n\nHere:\n\n- **item 1**\n- item 2\n\n> note\n\n---\n\n```js\nx()\n```");
+ const classes = root.children.map((c) => c.className);
+ assert.deepEqual(classes, ["md-h md-h1", "md-p", "md-item", "md-item", "md-quote", "md-rule", "md-pre"]);
+ assert.equal(root.find(".md-bullet")[0].textContent, "•");
+ assert.equal(root.find(".md-copy").length, 1);
+ // Rendering again replaces, it never appends.
+ renderMarkdown(root, "plain");
+ assert.equal(root.children.length, 1);
+});
+
+test("a web link opens through Rust; anything else is plain text", () => {
+ const root = dom.root();
+ renderMarkdown(root, "See [the docs](https://example.com/docs) or [this](file:///etc/passwd).");
+ const links = root.find("A");
+ assert.equal(links.length, 1);
+ assert.equal(links[0].getAttribute("href"), "https://example.com/docs");
+ const event = links[0].fire("click");
+ assert.equal(event.defaultPrevented, true);
+ assert.deepEqual(sent("open_url"), [{ url: "https://example.com/docs" }]);
+ assert.match(root.textContent, /or this\.$/);
+});