Merge branch 'feat/composer-markdown' into main
28 files changed,
+1,855
−50
internal/browsertest/paste_test.go+221 −0internal/browsertest/testdata/paste.json+92 −0internal/look/static/app.css+7 −4internal/look/static/ask.js+295 −14internal/web/ask_cards.go+66 −4internal/web/rich_internal_test.go+28 −1internal/web/templates/partials/chat.html+1 −1internal/web/testdata/person.json+66 −0internal/webtest/ask_test.go+25 −0native/apple/Sources/BaseKit/Ask/Composer.swift+83 −7native/apple/Sources/BaseKit/Ask/Markdown/BaseMarkdownView.swift+37 −4native/apple/Sources/BaseKit/Ask/Markdown/ChatMarkdown.swift+9 −3native/apple/Sources/BaseKit/Ask/Markdown/MarkdownPresentation.swift+2 −2native/apple/Sources/BaseKit/Ask/Markdown/PersonMarkdown.swift+127 −0native/apple/Sources/BaseKit/Ask/PasteMarkdown.swift+516 −0native/apple/Sources/BaseKit/Ask/Thread.swift+5 −1native/apple/Sources/BaseKit/Look/Type.swift+17 −9native/apple/Tests/BaseKitTests/AskViewTests.swift+48 −0native/apple/Tests/BaseKitTests/ComposerTests.swift+93 −0native/apple/Tests/BaseKitTests/PasteMarkdownTests.swift+100 −0native/apple/Tests/BaseKitTests/TypeTests.swift+3 −0native/apple/Tests/BaseSnapshots/AskSnapshots.swift+14 −0native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/person-markdown-dark-ax3.pngbinarynative/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/person-markdown-dark-default.pngbinarynative/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/person-markdown-light-ax3.pngbinarynative/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/person-markdown-light-default.pngbinarynative/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/mac/person-markdown-dark-default.pngbinarynative/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/mac/person-markdown-light-default.pngbinary
CI passed — run details
CI log
=== build === CGO_ENABLED=0 go build ./... === vet === go vet ./... === fmt-check === === staticcheck === go run honnef.co/go/tools/cmd/staticcheck@v0.7.0 ./... === govulncheck === go run golang.org/x/vuln/cmd/govulncheck@v1.8.0 ./... No vulnerabilities found. === gitleaks === [90m1:46PM[0m [32mINF[0m [1mUnknown SCM platform. Use --platform to include links in findings.[0m [36mhost=[0mamadan.net [90m1:46PM[0m [32mINF[0m [1m1 commits scanned.[0m [90m1:46PM[0m [32mINF[0m [1mscanned ~2492254 bytes (2.49 MB) in 241ms[0m [90m1:46PM[0m [32mINF[0m [1mno leaks found[0m === budget === go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget size budget size: 22 directories within budget === script-test === scripts/prepare-apps_test.sh ok releases lookup failure stops before ship ok app owned elsewhere stops the script ok apps listing failure stops before create ok ambiguous release dir is refused ok explicit version resolves the ambiguity ok releases match is exact, not substring ok shipped version is only promoted, existing app not created ok fresh account creates, ships, promotes to edge, enables ok failing promote stops the script ok ship is retried while uploads are rate limited all passed hack/fonts_test.sh fonts_test: ok === test === go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -count=1 ./... receipt: test step 7.289s against a 60s target (the gate's other steps are not in this figure) receipt: 16 packages ran, 0 cached, 6 without tests, 0 failed receipt: slow package 6.148s amadan.net/oficina/base/internal/webtest receipt: slow package 950ms amadan.net/oficina/base/internal/issuer receipt: slow package 586ms amadan.net/oficina/base/internal/operations receipt: slow package 243ms amadan.net/oficina/base/internal/consumer receipt: slow package 160ms amadan.net/oficina/base/internal/web receipt: slow test 1.52s amadan.net/oficina/base/internal/webtest TestHomeDoesNotWaitOnAStalledSnapshot receipt: slow test 1.08s amadan.net/oficina/base/internal/webtest TestAskZoneIsToldOnce receipt: slow test 710ms amadan.net/oficina/base/internal/issuer TestAuthorizeSignsForInstalledApp receipt: slow test 510ms amadan.net/oficina/base/internal/operations TestOperationsRefusals receipt: slow test 220ms amadan.net/oficina/base/internal/webtest TestAskZoneAgainOnANewConnection === native === strings: copy review's strings.json is not here (git-ignored); its comparison skipped strings: 119 in the catalog, 116 used worktree-lib_test: ok
diff --git a/internal/browsertest/paste_test.go b/internal/browsertest/paste_test.go| new file mode 100644 |
| index 0000000..4aa9e01 |
| --- /dev/null |
| +++ b/internal/browsertest/paste_test.go |
| @@ -0,0 +1,221 @@ |
| +//go:build browser |
| + |
| +package browsertest |
| + |
| +import ( |
| + "encoding/json" |
| + "os" |
| + "strconv" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/chromedp/chromedp" |
| + |
| + "amadan.net/rastrillo/rastrillo/harness" |
| +) |
| + |
| +// pasteSample is one of testdata/paste.json's clipboards: its HTML and the |
| +// Markdown it pastes as (null: the plain text, left to the browser). The |
| +// app's PasteMarkdownTests check the same samples. |
| +type pasteSample struct { |
| + Name string `json:"name"` |
| + HTML string `json:"html"` // "" for the app's RTF samples |
| + Markdown *string `json:"markdown"` |
| +} |
| + |
| +// A rich paste into the composer becomes the Markdown the chat draws (Paul, |
| +// 2026-11-26), and Undo takes it back; a paste whose HTML formats nothing |
| +// is the browser's own. |
| +func TestAskPasteMarkdown(t *testing.T) { |
| + raw, err := os.ReadFile("testdata/paste.json") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var samples []pasteSample |
| + if err := json.Unmarshal(raw, &samples); err != nil { |
| + t.Fatal(err) |
| + } |
| + rig, _ := askBase(t) |
| + openPanel(t, rig) |
| + type result struct { |
| + Prevented bool `json:"prevented"` |
| + Value string `json:"value"` |
| + } |
| + paste := func(before, html string) result { |
| + t.Helper() |
| + js := `(() => { |
| + const f = document.querySelector("#ask-text"); |
| + f.focus(); f.value = ` + strconv.Quote(before) + `; f.setSelectionRange(f.value.length, f.value.length); |
| + const data = new DataTransfer(); |
| + data.setData("text/html", ` + strconv.Quote(html) + `); |
| + data.setData("text/plain", "plain"); |
| + const e = new ClipboardEvent("paste", { clipboardData: data, bubbles: true, cancelable: true }); |
| + f.dispatchEvent(e); |
| + return JSON.stringify({ prevented: e.defaultPrevented, value: f.value }); |
| + })()` |
| + var r result |
| + if err := json.Unmarshal([]byte(harness.Evaluate[string](rig, js)), &r); err != nil { |
| + t.Fatal(err) |
| + } |
| + return r |
| + } |
| + for _, s := range samples { |
| + if s.HTML == "" { |
| + continue |
| + } |
| + got := paste("", s.HTML) |
| + switch { |
| + case s.Markdown == nil && (got.Prevented || got.Value != ""): |
| + t.Errorf("%s: pasted %q, want the browser's own paste", s.Name, got.Value) |
| + case s.Markdown != nil && (!got.Prevented || got.Value != *s.Markdown): |
| + t.Errorf("%s:\n got %q\nwant %q", s.Name, got.Value, *s.Markdown) |
| + } |
| + } |
| + // At the cursor, after what is there; and Undo takes the paste back. |
| + if got := paste("Note: ", samples[0].HTML); got.Value != "Note: "+*samples[0].Markdown { |
| + t.Errorf("pasted after text: %q", got.Value) |
| + } |
| + if got := harness.Evaluate[string](rig, `(document.execCommand("undo"), document.querySelector("#ask-text").value)`); got != "Note: " { |
| + t.Errorf("after Undo: %q", got) |
| + } |
| +} |
| + |
| +// Fable's S5 and S6: a big or hostile paste never freezes the tab. The |
| +// walk is linear and stops once the Markdown passes the field's 16,000 |
| +// characters; nesting past 32 levels is flattened. |
| +func TestAskPasteIsBounded(t *testing.T) { |
| + rig, _ := askBase(t) |
| + openPanel(t, rig) |
| + // The whole paste, the field's own insert included. |
| + got := harness.Evaluate[string](rig, `(() => { |
| + const f = document.querySelector("#ask-text"); |
| + const run = (html) => { |
| + f.focus(); f.value = ""; |
| + const data = new DataTransfer(); |
| + data.setData("text/html", html); |
| + const e = new ClipboardEvent("paste", { clipboardData: data, bubbles: true, cancelable: true }); |
| + const t0 = performance.now(); |
| + f.dispatchEvent(e); |
| + return { ms: performance.now() - t0, value: f.value }; |
| + }; |
| + const out = []; |
| + { |
| + const items = run("<ul>" + "<li><b>item</b></li>".repeat(50000) + "</ul>"); |
| + if (items.ms > 200) out.push("50,000 items took " + Math.round(items.ms) + " ms"); |
| + if (!items.value.startsWith("- **item**\n- **item**") || items.value.length > 16100) out.push("items pasted " + items.value.length + " characters"); |
| + const deep = run("<div><b>".repeat(5000) + "deep" + "</b></div>".repeat(5000)); |
| + if (deep.ms > 500) out.push("5,000 levels took " + Math.round(deep.ms) + " ms"); |
| + if (deep.value !== "**deep**") out.push("deep pasted " + JSON.stringify(deep.value.slice(0, 40))); |
| + } |
| + return out.join("; "); |
| + })()`) |
| + if got != "" { |
| + t.Error(got) |
| + } |
| +} |
| + |
| +// Fable's R1: the whole paste of about 4,000 lines, the field's own |
| +// insert included (nothing stubbed), is quick, and the field holds all of |
| +// it, with the panel's listeners told. |
| +func TestAskLongPasteIsQuick(t *testing.T) { |
| + rig, _ := askBase(t) |
| + openPanel(t, rig) |
| + var r struct { |
| + MS float64 `json:"ms"` |
| + Value string `json:"value"` |
| + Input bool `json:"input"` |
| + } |
| + raw := harness.Evaluate[string](rig, `(() => { |
| + const f = document.querySelector("#ask-text"); |
| + f.focus(); f.value = ""; |
| + let input = false; |
| + f.addEventListener("input", () => { input = true; }, { once: true }); |
| + const data = new DataTransfer(); |
| + data.setData("text/html", "<p><b>Rows</b></p>" + Array.from({ length: 4000 }, (_, i) => "<div>r" + (i % 10) + "</div>").join("")); |
| + const e = new ClipboardEvent("paste", { clipboardData: data, bubbles: true, cancelable: true }); |
| + const t0 = performance.now(); |
| + f.dispatchEvent(e); |
| + return JSON.stringify({ ms: performance.now() - t0, value: f.value, input }); |
| + })()`) |
| + if err := json.Unmarshal([]byte(raw), &r); err != nil { |
| + t.Fatal(err) |
| + } |
| + var want strings.Builder |
| + want.WriteString("**Rows**\n") |
| + for i := range 4000 { |
| + want.WriteString("\nr" + strconv.Itoa(i%10)) |
| + } |
| + if r.Value != want.String() { |
| + t.Errorf("pasted %d characters, want %d", len(r.Value), want.Len()) |
| + } |
| + if r.MS > 500 { |
| + t.Errorf("4,000 lines took %.0f ms", r.MS) |
| + } |
| + if !r.Input { |
| + t.Error("no input event: the panel's listeners weren't told") |
| + } |
| +} |
| + |
| +// The person's own messages are drawn in the Assistant's little Markdown, |
| +// with emphasis only at word boundaries, by the script and the server |
| +// alike (internal/web/testdata/person.json, which the server's and the |
| +// app's tests check too); plain words stay plain text, and unsafe links |
| +// stay text. |
| +func TestAskPersonMarkdown(t *testing.T) { |
| + raw, err := os.ReadFile("../web/testdata/person.json") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var cases []struct{ Text, HTML string } |
| + if err := json.Unmarshal(raw, &cases); err != nil { |
| + t.Fatal(err) |
| + } |
| + said := make([]string, len(cases)) |
| + for i, c := range cases { |
| + said[i] = c.Text |
| + } |
| + rig, _ := askBase(t) |
| + openPanel(t, rig) |
| + for i, s := range said { |
| + drive(t, rig, chromedp.Evaluate[chromedp.Void](`(() => { const f = document.querySelector("#ask-text"); f.value = `+strconv.Quote(s)+`; |
| + f.dispatchEvent(new Event("input", { bubbles: true })); document.querySelector("#ask-panel form.composer").requestSubmit() })()`)) |
| + n := strconv.Itoa(i + 1) |
| + drive(t, rig, chromedp.Poll[chromedp.Void](`document.querySelectorAll("#ask-panel .msg.person").length === `+n+ |
| + ` && document.querySelectorAll("#ask-panel .msg.coordinator").length === `+n+` && document.querySelector("#ask-panel button.stop").hidden`, |
| + chromedp.WithPollingTimeout(10*time.Second))) |
| + } |
| + got := harness.Evaluate[string](rig, `(async () => { |
| + const page = new DOMParser().parseFromString(await (await fetch("/ask")).text(), "text/html"); |
| + const out = []; |
| + for (const m of document.querySelectorAll("#ask-panel .msg.person")) { |
| + const s = page.querySelector('.msg.person[data-id="' + CSS.escape(m.dataset.id) + '"]'); |
| + if (!s) out.push(m.dataset.id + ": not on /ask"); |
| + else if (s.innerHTML !== m.innerHTML) out.push(JSON.stringify(m.textContent) + "\n script " + m.innerHTML + "\n server " + s.innerHTML); |
| + } |
| + return out.join("\n"); |
| + })()`, chromedp.EvalAwaitPromise) |
| + if got != "" { |
| + t.Errorf("the script and the server draw differently:\n%s", got) |
| + } |
| + var drawn []string |
| + if err := json.Unmarshal([]byte(harness.Evaluate[string](rig, `JSON.stringify([...document.querySelectorAll("#ask-panel .msg.person")].map(m => m.innerHTML))`)), &drawn); err != nil { |
| + t.Fatal(err) |
| + } |
| + for i, c := range cases { |
| + if i < len(drawn) && drawn[i] != c.HTML { |
| + t.Errorf("%q drawn\n %s\nwant %s", c.Text, drawn[i], c.HTML) |
| + } |
| + } |
| + // Their links keep the bubble's ink; their lists have markers. |
| + if got := harness.Evaluate[string](rig, `(() => { |
| + const a = document.querySelector("#ask-panel .msg.person a"), p = []; |
| + if (getComputedStyle(a).color !== getComputedStyle(a.closest(".msg")).color) p.push("link colour " + getComputedStyle(a).color); |
| + for (const l of document.querySelectorAll("#ask-panel .msg.person ul, #ask-panel .msg.person ol")) |
| + if (!/^(disc|decimal)$/.test(getComputedStyle(l).listStyleType)) p.push(l.tagName + " " + getComputedStyle(l).listStyleType); |
| + return p.join("; "); |
| + })()`); got != "" { |
| + t.Errorf("person styles: %s", got) |
| + } |
| + rig.Screen("#ask-panel", "the person's messages in simple Markdown") |
| +} |
diff --git a/internal/browsertest/testdata/paste.json b/internal/browsertest/testdata/paste.json| new file mode 100644 |
| index 0000000..080abda |
| --- /dev/null |
| +++ b/internal/browsertest/testdata/paste.json |
| @@ -0,0 +1,92 @@ |
| +[ |
| + { |
| + "name": "Google Docs: spans, a link and a list", |
| + "html": "<meta charset=\"utf-8\"><b style=\"font-weight:normal;\" id=\"docs-internal-guid-1a2b3c4d-7fff-1234-5678-9abcdef01234\"><p dir=\"ltr\" style=\"line-height:1.38;margin-top:0pt;margin-bottom:0pt;\"><span style=\"font-size:11pt;font-family:Arial,sans-serif;color:#000000;background-color:transparent;font-variant:normal;text-decoration:none;vertical-align:baseline;white-space:pre;white-space:pre-wrap;font-weight:700;font-style:normal;\">Christmas menu</span><span style=\"font-size:11pt;font-family:Arial,sans-serif;color:#000000;background-color:transparent;font-variant:normal;text-decoration:none;vertical-align:baseline;white-space:pre;white-space:pre-wrap;font-weight:400;font-style:normal;\"> for the bakery, </span><span style=\"font-size:11pt;font-family:Arial,sans-serif;color:#000000;background-color:transparent;font-variant:normal;text-decoration:none;vertical-align:baseline;white-space:pre;white-space:pre-wrap;font-weight:400;font-style:italic;\">draft two</span></p><br><ul style=\"margin-top:0;margin-bottom:0;padding-inline-start:48px;\"><li dir=\"ltr\" style=\"list-style-type:disc;font-size:11pt;font-family:Arial,sans-serif;color:#000000;background-color:transparent;font-weight:400;font-style:normal;font-variant:normal;text-decoration:none;vertical-align:baseline;white-space:pre;\" aria-level=\"1\"><p dir=\"ltr\" style=\"line-height:1.38;margin-top:0pt;margin-bottom:0pt;\" role=\"presentation\"><span style=\"font-size:11pt;font-family:Arial,sans-serif;color:#000000;background-color:transparent;font-variant:normal;text-decoration:none;vertical-align:baseline;white-space:pre;white-space:pre-wrap;font-weight:400;font-style:normal;\">Mince pies, </span><a href=\"https://fennel.example/menu/pies\" style=\"text-decoration:none;\"><span style=\"font-size:11pt;font-family:Arial,sans-serif;color:#1155cc;background-color:transparent;font-variant:normal;text-decoration:underline;vertical-align:baseline;white-space:pre;white-space:pre-wrap;font-weight:400;font-style:normal;\">see the recipe</span></a></p></li><li dir=\"ltr\" style=\"list-style-type:disc;font-size:11pt;font-family:Arial,sans-serif;color:#000000;background-color:transparent;font-weight:400;font-style:normal;font-variant:normal;text-decoration:none;vertical-align:baseline;white-space:pre;\" aria-level=\"1\"><p dir=\"ltr\" style=\"line-height:1.38;margin-top:0pt;margin-bottom:0pt;\" role=\"presentation\"><span style=\"font-size:11pt;font-family:Arial,sans-serif;color:#000000;background-color:transparent;font-variant:normal;text-decoration:none;vertical-align:baseline;white-space:pre;white-space:pre-wrap;font-weight:700;font-style:normal;\">Stollen</span></p></li></ul><br><p dir=\"ltr\" style=\"line-height:1.38;margin-top:0pt;margin-bottom:0pt;\"><span style=\"font-size:11pt;font-family:Arial,sans-serif;color:#000000;background-color:transparent;font-variant:normal;text-decoration:none;vertical-align:baseline;white-space:pre;white-space:pre-wrap;font-weight:400;font-style:normal;\">Ana signs it off on Friday.</span></p></b><br class=\"Apple-interchange-newline\">", |
| + "markdown": "**Christmas menu** for the bakery, *draft two*\n\n- Mince pies, [see the recipe](https://fennel.example/menu/pies)\n- **Stollen**\n\nAna signs it off on Friday." |
| + }, |
| + { |
| + "name": "Google Docs: a nested list, flat as Docs writes it", |
| + "html": "<meta charset=\"utf-8\"><b style=\"font-weight:normal;\" id=\"docs-internal-guid-2b\"><ul style=\"margin-top:0;margin-bottom:0;\"><li dir=\"ltr\" style=\"list-style-type:disc;font-size:11pt;font-family:Arial,sans-serif;color:#000000;background-color:transparent;font-weight:400;font-style:normal;font-variant:normal;text-decoration:none;vertical-align:baseline;white-space:pre;\" aria-level=\"1\"><p dir=\"ltr\" style=\"line-height:1.38;margin-top:0pt;margin-bottom:0pt;\" role=\"presentation\"><span style=\"font-size:11pt;font-family:Arial,sans-serif;color:#000000;background-color:transparent;font-variant:normal;text-decoration:none;vertical-align:baseline;white-space:pre;white-space:pre-wrap;font-weight:400;\">Bread</span></p></li><ul style=\"margin-top:0;margin-bottom:0;\"><li dir=\"ltr\" style=\"list-style-type:circle;\" aria-level=\"2\"><p dir=\"ltr\" style=\"line-height:1.38;margin-top:0pt;margin-bottom:0pt;\" role=\"presentation\"><span style=\"font-size:11pt;font-family:Arial,sans-serif;color:#000000;background-color:transparent;font-variant:normal;text-decoration:none;vertical-align:baseline;white-space:pre;white-space:pre-wrap;font-weight:400;\">Rye</span></p></li></ul><li dir=\"ltr\" style=\"list-style-type:disc;font-size:11pt;font-family:Arial,sans-serif;color:#000000;background-color:transparent;font-weight:400;font-style:normal;font-variant:normal;text-decoration:none;vertical-align:baseline;white-space:pre;\" aria-level=\"1\"><p dir=\"ltr\" style=\"line-height:1.38;margin-top:0pt;margin-bottom:0pt;\" role=\"presentation\"><span style=\"font-size:11pt;font-family:Arial,sans-serif;color:#000000;background-color:transparent;font-variant:normal;text-decoration:none;vertical-align:baseline;white-space:pre;white-space:pre-wrap;font-weight:400;\">Cakes</span></p></li></ul></b>", |
| + "markdown": "- Bread\n - Rye\n- Cakes" |
| + }, |
| + { |
| + "name": "A web page: a heading, links (one relative, one mailto) and a list from 3", |
| + "html": "<meta charset='utf-8'><h2 style=\"font-family: Georgia; color: rgb(30, 36, 64);\">Opening hours</h2><p style=\"margin: 0px 0px 1em;\">We bake every day from <strong>7am</strong>. See <a href=\"https://fennel.example/hours\" style=\"color: blue;\">our hours page</a> or <a href=\"/contact\">contact us</a>.</p>\n<ol start=\"3\">\n <li>Order by noon</li>\n <li>Collect after 4pm</li>\n</ol>\n<p>Questions? Email <a href=\"mailto:hello@fennel.example\">hello@fennel.example</a>.</p>", |
| + "markdown": "## Opening hours\n\nWe bake every day from **7am**. See [our hours page](https://fennel.example/hours) or contact us.\n\n3. Order by noon\n4. Collect after 4pm\n\nQuestions? Email hello@fennel.example." |
| + }, |
| + { |
| + "name": "Apple Mail: lines, a blank line, bold, italics and a numbered list", |
| + "html": "<html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\"></head><body style=\"overflow-wrap: break-word; -webkit-nbsp-mode: space; line-break: after-white-space;\"><div>Hi Ana,</div><div><br></div><div>The <b>flour delivery</b> moves to <i>Thursday</i>.<br>Can you check the order?</div><div><br></div><div><ol class=\"MailOutline\"><li>Two sacks of rye</li><li>One of spelt</li></ol><div>Thanks,</div></div><div>Paul</div></body></html>", |
| + "markdown": "Hi Ana,\n\nThe **flour delivery** moves to *Thursday*.\nCan you check the order?\n\n1. Two sacks of rye\n2. One of spelt\n\nThanks,\nPaul" |
| + }, |
| + { |
| + "name": "Nested lists, bullets in bullets in numbers", |
| + "html": "<ul><li>Bread<ul><li>Sourdough</li><li>Rye<ol><li>Light</li><li>Dark</li></ol></li></ul></li><li>Cakes</li></ul>", |
| + "markdown": "- Bread\n - Sourdough\n - Rye\n 1. Light\n 2. Dark\n- Cakes" |
| + }, |
| + { |
| + "name": "A javascript: link and one with a password are text; scripts and images go", |
| + "html": "<p>Click <a href=\"javascript:alert(1)\">here</a> or <a href=\"https://user:pw@fennel.example/x\">there</a> for <b>details</b>.</p><script>alert(2)</script><img src=\"https://tracker.example/p.gif\" alt=\"pixel\"><style>p { color: red }</style>", |
| + "markdown": "Click here or there for **details**." |
| + }, |
| + { |
| + "name": "Headings, emphasis inside them dropped", |
| + "html": "<h1 dir=\"ltr\"><span style=\"font-weight:700\">Weekly plan</span></h1><h3>Monday</h3><p><span style=\"font-style:italic\">Bake</span> only.</p>", |
| + "markdown": "# Weekly plan\n\n### Monday\n\n*Bake* only." |
| + }, |
| + { |
| + "name": "Spaces stand outside the marks, one between words", |
| + "html": "<p><b>Bold </b>then <i> spaced </i>words, and a link: <a href=\"https://fennel.example/a_(b)\">the [menu]</a></p>", |
| + "markdown": "**Bold** then *spaced* words, and a link: [the menu](https://fennel.example/a_%28b%29)" |
| + }, |
| + { |
| + "name": "Code from an editor formats nothing: the plain text is pasted", |
| + "html": "<meta charset=\"utf-8\"><div style=\"color: #d4d4d4;background-color: #1e1e1e;font-family: Menlo, Monaco, monospace;white-space: pre;\"><div><span style=\"color: #569cd6;\">let</span><span style=\"color: #d4d4d4;\"> x = 2*3</span></div></div>", |
| + "markdown": null |
| + }, |
| + { |
| + "name": "A link whose text is its address", |
| + "html": "<a href=\"https://fennel.example/menu\">https://fennel.example/menu</a>", |
| + "markdown": "https://fennel.example/menu" |
| + }, |
| + { |
| + "name": "Fable's S2: VS Code, with an italic comment, is code: the plain text is pasted", |
| + "html": "<meta charset=\"utf-8\"><div style=\"color: #cccccc;background-color: #1f1f1f;font-family: Menlo, Monaco, 'Courier New', monospace;font-weight: normal;font-size: 12px;line-height: 18px;white-space: pre;\"><div><span style=\"color: #569cd6;\">func</span><span style=\"color: #cccccc;\"> </span><span style=\"color: #dcdcaa;\">greet</span><span style=\"color: #cccccc;\">() {</span></div><div><span style=\"color: #cccccc;\"> </span><span style=\"color: #6a9955;font-style: italic;\">// say *hi*</span></div><div><span style=\"color: #cccccc;\"> </span><span style=\"color: #c586c0;\">return</span><span style=\"color: #cccccc;\"> </span><span style=\"color: #b5cea8;\">2</span><span style=\"color: #d4d4d4;\">*</span><span style=\"color: #b5cea8;\">3</span></div><div><span style=\"color: #cccccc;\">}</span></div></div>", |
| + "markdown": null |
| + }, |
| + { |
| + "name": "A little inline code in prose stays text", |
| + "html": "<p>Run <code>make ci</code> then <b>push</b>.</p>", |
| + "markdown": "Run make ci then **push**." |
| + }, |
| + { |
| + "name": "Fable's S3: Word's mso-bidi-* and other prefixed weights are not font-weight", |
| + "html": "<html xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:w=\"urn:schemas-microsoft-com:office:word\" xmlns=\"http://www.w3.org/TR/REC-html40\"><head><meta http-equiv=Content-Type content=\"text/html; charset=utf-8\"><meta name=Generator content=\"Microsoft Word 15\"><style><!-- p.MsoNormal {margin:0cm; font-size:12.0pt; font-family:\"Aptos\",sans-serif;} --></style></head><body lang=EN-IE style='tab-interval:36.0pt;word-wrap:break-word'><!--StartFragment--><p class=MsoNormal><b style='mso-bidi-font-weight:normal'>Bold</b> and <i style='mso-bidi-font-style:normal'>italic</i>, <span style='mso-bidi-font-weight:bold'>plain in Latin</span>, <span style='--tw-font-weight:700'>plain too</span>, and <a href=\"https://fennel.example/word\">a link</a><o:p></o:p></p><p class=MsoListParagraphCxSpFirst style='text-indent:-18.0pt;mso-list:l0 level1 lfo1'><![if !supportLists]><span style='font-family:Symbol'>·<span style='font:7.0pt \"Times New Roman\"'> </span></span><![endif]>Rye<o:p></o:p></p><!--EndFragment--></body></html>", |
| + "markdown": "**Bold** and *italic*, plain in Latin, plain too, and [a link](https://fennel.example/word)\n\n· Rye" |
| + }, |
| + { |
| + "name": "Fable's S2: Xcode's RTF (bold keywords in Menlo) is code (the app only: the web has no RTF)", |
| + "rtf": "{\\rtf1\\ansi\\ansicpg1252\\cocoartf2822\n\\cocoatextscaling0\\cocoaplatform0{\\fonttbl\\f0\\fnil\\fcharset0 Menlo-Bold;\\f1\\fnil\\fcharset0 Menlo-Regular;}\n{\\colortbl;\\red255\\green255\\blue255;\\red155\\green35\\blue147;}\n\\pard\\tx593\\pardeftab593\\pardirnatural\\partightenfactor0\n\n\\f0\\b\\fs24 \\cf2 func\n\\f1\\b0 \\cf0 greet() \\{\\\n \n\\f0\\b \\cf2 let\n\\f1\\b0 \\cf0 x = 2*3\\\n \n\\f0\\b \\cf2 return\n\\f1\\b0 \\cf0 x\\\n\\}}", |
| + "markdown": null |
| + }, |
| + { |
| + "name": "Fable's R2: a <pre> in prose keeps its indentation, as a fenced block", |
| + "html": "<p><b>Do this:</b></p><pre> x = 1\n y = 2</pre>", |
| + "markdown": "**Do this:**\n\n```\n x = 1\n y = 2\n```" |
| + }, |
| + { |
| + "name": "A <pre> keeps its blank lines and backticks; the line break after <pre> goes", |
| + "html": "<p>Then <b>restart</b> the service and check the log for errors:</p><pre>\nsystemctl restart base\n\n journalctl -u base # ```tail```</pre><p>That's all.</p>", |
| + "markdown": "Then **restart** the service and check the log for errors:\n\n````\nsystemctl restart base\n\n journalctl -u base # ```tail```\n````\n\nThat's all." |
| + }, |
| + { |
| + "name": "Fable's R3: past 32 levels a block is still a line and a cell a space; a button is still skipped", |
| + "html": "<p><b>Thread</b></p><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><p>one</p><p>two</p><div>three</div><table><tr><td>a</td><td>b</td></tr></table><button>Btn</button>tail</div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div>", |
| + "markdown": "**Thread**\n\none\ntwo\nthree\na b\ntail" |
| + }, |
| + { |
| + "name": "font-weight with !important is bold", |
| + "html": "<span style=\"font-weight: bold !important\">Bold</span> words", |
| + "markdown": "**Bold** words" |
| + } |
| +] |
diff --git a/internal/look/static/app.css b/internal/look/static/app.css| index 0db5708..34e5135 100644 |
| --- a/internal/look/static/app.css |
| +++ b/internal/look/static/app.css |
| @@ -557,10 +557,11 @@ aside.ask-panel { position: absolute; top: 16px; right: 16px; bottom: 16px; widt |
| .msg { max-width: 86%; padding: 10px 14px; border-radius: 14px; white-space: pre-wrap; overflow-wrap: anywhere; font-size: 15px; line-height: 1.5; } |
| .msg.person { align-self: flex-end; background: var(--mine); box-shadow: inset 0 0 0 1px var(--mine-edge); border-bottom-right-radius: 4px; } |
| .msg.coordinator { align-self: flex-start; background: var(--theirs); box-shadow: inset 0 0 0 1px var(--theirs-edge); border-bottom-left-radius: 4px; } |
| -/* The Assistant's simple lists: the thread's own list-style is none. */ |
| -.msg.coordinator ul, .msg.coordinator ol { margin: 4px 0; padding-left: 20px; } |
| -.msg.coordinator ul { list-style: disc; } |
| -.msg.coordinator ol { list-style: decimal; } |
| +/* The simple lists in a message, the Assistant's or the person's: the |
| + thread's own list-style is none. */ |
| +.msg ul, .msg ol { margin: 4px 0; padding-left: 20px; } |
| +.msg ul { list-style: disc; } |
| +.msg ol { list-style: decimal; } |
| .msg.draft::after { content: ""; display: inline-block; width: 7px; height: 1em; margin-left: 3px; vertical-align: -2px; background: var(--signal); animation: caret 1s steps(2) infinite; } |
| @keyframes caret { 50% { opacity: 0; } } |
| .msg.card { align-self: stretch; max-width: none; background: var(--card); box-shadow: inset 0 0 0 1px var(--card-edge); } |
| @@ -568,6 +569,8 @@ aside.ask-panel { position: absolute; top: 16px; right: 16px; bottom: 16px; widt |
| .choices { display: flex; flex-wrap: wrap; gap: 8px; } |
| .msg.card p + p { margin-top: -4px; } |
| .card-link, .msg.coordinator a { color: var(--focus); text-decoration: underline; text-underline-offset: 3px; overflow-wrap: anywhere; } |
| +/* The person's links keep their bubble's ink, underlined. */ |
| +.msg.person a { color: inherit; text-decoration: underline; text-underline-offset: 3px; overflow-wrap: anywhere; } |
| .card-link { display: inline-flex; align-items: center; min-height: 44px; font-weight: 500; } |
| .msg.card .card-state { margin: 0; color: var(--haze); font-size: 14px; } |
| .msg.card .choices + .card-state { margin-top: 10px; } |
diff --git a/internal/look/static/ask.js b/internal/look/static/ask.js| index 4b2c735..141ef04 100644 |
| --- a/internal/look/static/ask.js |
| +++ b/internal/look/static/ask.js |
| @@ -109,8 +109,10 @@ function start(root) { |
| li.className = "msg " + (m.role === "person" ? "person" : "coordinator"); |
| li.dataset.id = m.id; |
| if (m.role !== "person" && m.turn_id) li.dataset.turn = m.turn_id; |
| - if (m.role === "person") li.textContent = m.text; |
| - else rich(li, m.text); |
| + // The person's own words take the same little Markdown as the |
| + // Assistant's (rich), with emphasis only at word boundaries |
| + // (strictEmphasis). |
| + rich(li, m.text, m.role === "person"); |
| const draft = m.role !== "person" && (item("data-draft", m.turn_id) || bubbles.get(m.turn_id)); |
| if (draft && draft.querySelector(":scope > .think-line")) become(draft, li); |
| else if (draft) draft.replaceWith(li); |
| @@ -279,7 +281,7 @@ function start(root) { |
| } |
| // Line breaks are read as a page reads them (\r\n and \r are \n, and a |
| // NUL goes), so the server's HTML and this draw the same. |
| - function rich(el, text) { |
| + function rich(el, text, strict = false) { |
| el.replaceChildren(); |
| const lines = text.replace(/\r\n?/g, "\n").replaceAll("\0", "").split("\n"); |
| for (let i = 0; i < lines.length; ) { |
| @@ -287,7 +289,7 @@ function start(root) { |
| if (!first) { |
| let j = i + 1; |
| while (j < lines.length && !listLine(lines[j])) j++; |
| - inline(el, lines.slice(i, j).join("\n")); |
| + inline(el, lines.slice(i, j).join("\n"), strict); |
| i = j; |
| continue; |
| } |
| @@ -295,7 +297,7 @@ function start(root) { |
| if (first.kind === "ol" && first.n !== 1) list.start = first.n; |
| for (let l; i < lines.length && (l = listLine(lines[i])) && l.kind === first.kind; i++) { |
| const li = document.createElement("li"); |
| - inline(li, l.item); |
| + inline(li, l.item, strict); |
| list.append(li); |
| } |
| el.append(list); |
| @@ -303,7 +305,8 @@ function start(root) { |
| } |
| // inline appends text with its safe links, and bold and italics between |
| // them. |
| - function inline(el, text) { |
| + function inline(el, text, strict) { |
| + const emphasis = strict ? strictEmphasis : looseEmphasis; |
| let last = 0; |
| for (const m of text.matchAll(linkRE)) { |
| let end = m.index + m[0].length, label = m[1], target = m[2]; |
| @@ -324,7 +327,7 @@ function start(root) { |
| // x is the text up to the next same marker, not empty, on one line, and |
| // neither starting nor ending with a space; an _ also needs no word |
| // character just outside it. Nothing nests (emphasis in ask_cards.go). |
| - function emphasis(el, text) { |
| + function looseEmphasis(el, text) { |
| let last = 0; |
| const put = (tag, at, x, next) => { |
| if (at > last) el.append(text.slice(last, at)); |
| @@ -354,6 +357,36 @@ function start(root) { |
| } |
| if (text.length > last) el.append(text.slice(last)); |
| } |
| + // strictEmphasis is emphasis for the person's words: a run of markers |
| + // opens only at the start or after a character that is no word's, closes |
| + // only at the end or before one, and is exactly one * or _, or two *, so |
| + // 2*3*4, x**2 + y**2 and __init__.py stay as written (strictEmphasis in |
| + // ask_cards.go). Linear: each run looks only to the next of its marker. |
| + function strictEmphasis(el, text) { |
| + let last = 0; |
| + const run = (at) => { let n = 1; while (text[at + n] === text[at]) n++; return n; }; |
| + for (let i = 0; i < text.length; ) { |
| + const c = text[i]; |
| + if (c !== "*" && c !== "_") { i++; continue; } |
| + const n = run(i); |
| + if ((i === 0 || !wordUnit(text.charCodeAt(i - 1))) && (n === 1 || (n === 2 && c === "*"))) { |
| + const j = text.indexOf(c, i + n); |
| + if (j >= 0) { |
| + const end = j + run(j), x = text.slice(i + n, j); |
| + if (end - j === n && emphasized(x) && (end === text.length || !wordUnit(text.charCodeAt(end)))) { |
| + if (i > last) el.append(text.slice(last, i)); |
| + const e = document.createElement(n === 2 ? "strong" : "em"); |
| + e.textContent = x; |
| + el.append(e); |
| + i = last = end; |
| + continue; |
| + } |
| + } |
| + } |
| + i += n; |
| + } |
| + if (text.length > last) el.append(text.slice(last)); |
| + } |
| const space = (c) => c === " " || c === "\t"; |
| const emphasized = (x) => x !== "" && !x.includes("\n") && !space(x[0]) && !space(x[x.length - 1]); |
| // A word's code unit: an ASCII letter, digit or _, or anything beyond |
| @@ -1637,14 +1670,262 @@ function start(root) { |
| field.addEventListener("keydown", (e) => { |
| if (e.key !== "Enter" || e.isComposing || e.keyCode === 229 || e.shiftKey) return; |
| e.preventDefault(); |
| - if (!e.altKey) { |
| - composer.requestSubmit(); |
| - } else if (!document.execCommand("insertText", false, "\n")) { |
| - // Where insertText isn't offered: at the cursor, without undo. |
| - field.setRangeText("\n", field.selectionStart, field.selectionEnd, "end"); |
| - field.dispatchEvent(new Event("input", { bubbles: true })); |
| - } |
| + if (!e.altKey) composer.requestSubmit(); |
| + else typeIn("\n"); |
| + }); |
| + // A rich paste (a web page, Docs, Mail) comes in as the Markdown the |
| + // chat draws (pasteMarkdown); a plain one, or one whose HTML carries no |
| + // formatting, is left to the browser. |
| + field.addEventListener("paste", (e) => { |
| + const html = e.clipboardData && e.clipboardData.getData("text/html"); |
| + const md = html ? pasteMarkdown(html) : null; |
| + if (md === null) return; |
| + e.preventDefault(); |
| + typeIn(md); |
| }); |
| + // typeIn puts text in place of the field's selection as typing would, |
| + // so Undo takes it back. A text of many lines goes in at once instead |
| + // (insertText grows with the square of the lines: 4,000 take seconds), |
| + // without Undo, and so does any where insertText isn't offered; the |
| + // field's limit holds either way. |
| + function typeIn(text) { |
| + if (text.split("\n", 301).length <= 300 && document.execCommand("insertText", false, text)) return; |
| + const start = field.selectionStart, end = field.selectionEnd; |
| + const room = field.maxLength >= 0 ? field.maxLength - (field.value.length - (end - start)) : text.length; |
| + field.setRangeText(text.slice(0, Math.max(0, room)), start, end, "end"); |
| + field.dispatchEvent(new Event("input", { bubbles: true })); |
| + } |
| + |
| + // pasteMarkdown is a clipboard's HTML as the chat's Markdown: bold |
| + // (**x**), italics (*x*), links ([text](url), http(s) only, as webURL), |
| + // bullet and numbered lists (nested by indent), headings (# x), and line |
| + // breaks and paragraphs. Everything else is its text. It is null when the |
| + // HTML formats nothing, or is mostly code (a monospace font, or pre, |
| + // code, tt, samp, kbd), so a plain paste or code stays exactly as |
| + // copied. The HTML is parsed into an inert document (nothing runs or |
| + // loads) and walked once: elements deeper than 32 are flattened, the |
| + // walk stops once the Markdown passes the field's 16,000 characters, and |
| + // more than 2 MB of HTML is left plain. The app's PasteMarkdown does the |
| + // same (keep them in step: the samples in |
| + // internal/browsertest/testdata/paste.json check both). |
| + function pasteMarkdown(html) { |
| + if (html.length > 2000000) return null; |
| + const doc = new DOMParser().parseFromString(html, "text/html"); |
| + const maxDepth = 32, maxOut = 16000; |
| + const skip = new Set(["SCRIPT", "STYLE", "HEAD", "TITLE", "TEMPLATE", "NOSCRIPT", "IFRAME", "OBJECT", "EMBED", "SVG", "MATH", "CANVAS", "VIDEO", "AUDIO", "PICTURE", "IMG", "BUTTON", "SELECT", "INPUT", "TEXTAREA"]); |
| + const raw = new Set(["SCRIPT", "STYLE", "TEXTAREA", "TITLE", "TEMPLATE", "NOSCRIPT", "IFRAME"]); |
| + const lines = new Set(["DIV", "SECTION", "ARTICLE", "HEADER", "FOOTER", "MAIN", "NAV", "ASIDE", "BLOCKQUOTE", "FIGURE", "FIGCAPTION", "ADDRESS", "CENTER", "DETAILS", "SUMMARY", "FORM", "FIELDSET", "TABLE", "THEAD", "TBODY", "TFOOT", "TR", "CAPTION", "DL", "DT", "DD", "HR"]); |
| + const code = new Set(["CODE", "TT", "SAMP", "KBD"]); |
| + const blocks = new Set([...lines, "P", "LI", "UL", "OL", "H1", "H2", "H3", "H4", "H5", "H6", "PRE"]); |
| + const monoFont = /monospace|menlo|monaco|consolas|courier|sf ?mono|fira (code|mono)|jetbrains|source code|cascadia|ubuntu mono|dejavu sans mono|roboto mono|plex mono|andale mono|lucida console/i; |
| + // The output, built once: its pieces, its length, and how many line |
| + // breaks it ends with. |
| + const out = []; |
| + // A <pre>'s text, kept out of the clean-up at the end: its spaces and |
| + // blank lines are the code's. Each stands in the output as NUL, its |
| + // number, NUL (the parser never leaves a NUL in text). |
| + const verbatim = []; |
| + let length = 0, breaks = 0; |
| + const put = (s) => { |
| + if (!s) return; |
| + out.push(s); |
| + length += s.length; |
| + const m = /\n*$/.exec(s)[0].length; |
| + breaks = m === s.length ? breaks + m : m; |
| + }; |
| + let runs = [], open = false, marker = null, indent = "", formatted = false, chars = 0, mono = 0; |
| + const lists = []; |
| + const flush = () => { |
| + const s = inline(runs).replace(/^ +/, ""); |
| + runs = []; |
| + if (!s) return; |
| + put(open ? s : (marker !== null ? marker : indent) + s); |
| + if (!open && marker !== null) formatted = true; |
| + marker = null; |
| + open = true; |
| + }; |
| + const ensure = (n) => { |
| + flush(); |
| + open = false; |
| + if (!length) return; |
| + for (let have = breaks; have < n; have++) put("\n"); |
| + }; |
| + const lineBreak = () => { |
| + flush(); |
| + if (length) { put("\n"); open = false; } |
| + }; |
| + // A declaration's value in a style attribute (never mso-bidi-font-weight |
| + // and the like). |
| + const declared = (style, name) => { |
| + const m = new RegExp("(?:^|;)\\s*" + name + "\\s*:\\s*([^;]*)", "i").exec(style); |
| + return m ? m[1].replace(/!\s*important\s*$/i, "").trim() : null; |
| + }; |
| + const walk = (node, st, depth) => { |
| + if (length > maxOut) return; |
| + if (node.nodeType === 3) { |
| + const counted = node.data.replace(/\s+/g, "").length; |
| + chars += counted; |
| + if (st.mono) mono += counted; |
| + let t = node.data.replace(/[ \t\n\r\f\u00a0]+/g, " "); |
| + // One space between words, whichever side of a tag it was. |
| + if (t[0] === " " && runs.length && runs[runs.length - 1].text.endsWith(" ")) t = t.slice(1); |
| + if (t) runs.push({ text: t, bold: st.heading ? false : st.bold, italic: st.heading ? false : st.italic, href: st.href }); |
| + return; |
| + } |
| + if (node.nodeType !== 1) return; |
| + const tag = node.tagName.toUpperCase(); |
| + if (tag === "BR") return lineBreak(); |
| + if (skip.has(tag)) return; |
| + // Too deep: its text, a block a line of its own and a cell a space, |
| + // as the app's tree has it. |
| + if (depth >= maxDepth) { |
| + const block = blocks.has(tag); |
| + if (block) ensure(1); |
| + for (const c of node.childNodes) walk(c, st, depth); |
| + if (block) ensure(1); |
| + if (tag === "TD" || tag === "TH") runs.push({ text: " ", bold: false, italic: false, href: "" }); |
| + return; |
| + } |
| + const next = { ...st }; |
| + if (tag === "B" || tag === "STRONG") next.bold = true; |
| + if (tag === "I" || tag === "EM") next.italic = true; |
| + if (code.has(tag)) next.mono = true; |
| + const style = node.getAttribute("style") || ""; |
| + const weight = declared(style, "font-weight"); |
| + if (weight !== null) next.bold = /^(bold|bolder|[6-9]00)$/i.test(weight); |
| + const slant = declared(style, "font-style"); |
| + if (slant !== null) next.italic = /^(italic|oblique)/i.test(slant); |
| + const family = declared(style, "font-family"); |
| + if (family !== null) next.mono = monoFont.test(family); |
| + if (tag === "A" && !st.href) next.href = webURL((node.getAttribute("href") || "").trim()); |
| + const children = () => { for (const c of node.childNodes) walk(c, next, depth + 1); }; |
| + const level = /^H([1-6])$/.exec(tag); |
| + if (level) { |
| + ensure(2); |
| + marker = "#".repeat(Number(level[1])) + " "; |
| + next.heading = true; |
| + const before = formatted; |
| + children(); |
| + flush(); |
| + if (marker !== null) { marker = null; formatted = before; } |
| + ensure(2); |
| + return; |
| + } |
| + if (tag === "UL" || tag === "OL") { |
| + const top = lists.length === 0; |
| + const parent = lists[lists.length - 1]; |
| + ensure(top ? 2 : 1); |
| + const start = parseInt(node.getAttribute("start"), 10); |
| + lists.push({ ordered: tag === "OL", n: Number.isNaN(start) ? 1 : Math.max(0, start), |
| + indent: parent ? parent.inner : indent, inner: parent ? parent.inner : indent }); |
| + const saved = indent; |
| + children(); |
| + lists.pop(); |
| + indent = saved; |
| + ensure(top ? 2 : 1); |
| + return; |
| + } |
| + if (tag === "LI") { |
| + ensure(1); |
| + const list = lists[lists.length - 1] || { ordered: false, n: 0, indent: "", inner: "" }; |
| + const m = list.ordered ? list.n++ + ". " : "- "; |
| + marker = list.indent + m; |
| + list.inner = list.indent + " ".repeat(m.length); |
| + const saved = indent; |
| + indent = list.inner; |
| + children(); |
| + flush(); |
| + marker = null; |
| + indent = saved; |
| + ensure(1); |
| + return; |
| + } |
| + if (tag === "P") { |
| + if (lists.length) { |
| + flush(); |
| + if (open) { put("\n"); open = false; } |
| + children(); |
| + return; |
| + } |
| + ensure(2); |
| + children(); |
| + ensure(2); |
| + return; |
| + } |
| + if (tag === "PRE") { |
| + // Verbatim, as a fenced code block longer than any run of |
| + // backticks in it. |
| + let code = ""; |
| + const read = (n) => { |
| + if (n.nodeType === 3) code += n.data; |
| + else if (n.nodeType === 1 && n.tagName.toUpperCase() === "BR") code += "\n"; |
| + else if (n.nodeType === 1 && !skip.has(n.tagName.toUpperCase())) for (const c of n.childNodes) read(c); |
| + }; |
| + read(node); |
| + code = code.replace(/\r\n?/g, "\n").replace(/\n$/, ""); |
| + const counted = code.replace(/\s+/g, "").length; |
| + chars += counted; |
| + mono += counted; |
| + if (!code.trim()) return; |
| + const fence = "`".repeat(Math.max(3, ...(code.match(/`+/g) || []).map((r) => r.length + 1))); |
| + ensure(2); |
| + put(fence + "\n\0" + verbatim.length + "\0\n" + fence); |
| + verbatim.push(code); |
| + formatted = true; |
| + ensure(2); |
| + return; |
| + } |
| + if (lines.has(tag)) { |
| + ensure(1); |
| + children(); |
| + ensure(1); |
| + return; |
| + } |
| + if (tag === "TD" || tag === "TH") { |
| + children(); |
| + runs.push({ text: " ", bold: false, italic: false, href: "" }); |
| + return; |
| + } |
| + children(); |
| + }; |
| + // inline is a line's runs as Markdown: neighbours alike are one run, |
| + // and a run's outer spaces stand outside its marks. A label the chat |
| + // can't draw as a link (over 300 characters) is text with its address. |
| + const inline = (rs) => { |
| + const merged = []; |
| + for (const r of rs) { |
| + const last = merged[merged.length - 1]; |
| + if (last && last.href === r.href && (r.href || (last.bold === r.bold && last.italic === r.italic))) last.text += r.text; |
| + else merged.push({ ...r }); |
| + } |
| + let s = ""; |
| + for (const r of merged) { |
| + const lead = /^ */.exec(r.text)[0], trail = / *$/.exec(r.text)[0]; |
| + const core = r.text.slice(lead.length, r.text.length - trail.length); |
| + if (!core) { s += r.text; continue; } |
| + if (r.href) { |
| + const label = core.replace(/[\[\]]/g, ""); |
| + const href = r.href.replace(/\(/g, "%28").replace(/\)/g, "%29"); |
| + s += lead + (label === r.href ? href : label.length > 300 ? label + " (" + href + ")" : "[" + label + "](" + href + ")") + trail; |
| + formatted = true; |
| + } else if (r.bold || r.italic) { |
| + const mark = r.bold ? "**" : "*"; |
| + s += lead + mark + core + mark + trail; |
| + formatted = true; |
| + } else { |
| + s += r.text; |
| + } |
| + } |
| + return s.replace(/ +$/, ""); |
| + }; |
| + // The body is depth -1: 32 levels under it are kept, as in the app. |
| + walk(doc.body, { bold: false, italic: false, href: "", heading: false, mono: false }, -1); |
| + flush(); |
| + if (!formatted || mono * 2 > chars) return null; |
| + return out.join("").split("\n").map((l) => l.replace(/[ \t]+$/, "")).join("\n").replace(/\n{3,}/g, "\n\n").replace(/^\n+|\n+$/g, "") |
| + .replace(/\0(\d+)\0/g, (_, n) => verbatim[Number(n)]); |
| + } |
| + |
| cancel.addEventListener("submit", (e) => { |
| e.preventDefault(); |
| post(cancel); |
diff --git a/internal/web/ask_cards.go b/internal/web/ask_cards.go| index 03d7f77..e20f534 100644 |
| --- a/internal/web/ask_cards.go |
| +++ b/internal/web/ask_cards.go |
| @@ -23,7 +23,16 @@ var linkRE = regexp.MustCompile(`\[([^\[\]\n]{1,300})\]\(([^()\s]{1,1000})\)|htt |
| // relative paths and any other Markdown stay text. The panel's script does |
| // the same (ask.js, rich). Its line breaks are read as a page reads them |
| // (\r\n and \r are \n, and a NUL goes), so the two draw the same. |
| -func richText(text string) template.HTML { |
| +func richText(text string) template.HTML { return richMarkdown(text, false) } |
| + |
| +// personText is the person's own message as HTML: richText's little |
| +// Markdown, but stricter about emphasis (strictEmphasis), since people |
| +// write arithmetic, file names and code: 2*3*4, x**2 and __init__.py stay |
| +// as written. ask.js (rich, strict) and the app (PersonMarkdown) do the |
| +// same. |
| +func personText(text string) template.HTML { return richMarkdown(text, true) } |
| + |
| +func richMarkdown(text string, strict bool) template.HTML { |
| var b strings.Builder |
| lines := strings.Split(asPageReads.Replace(text), "\n") |
| for i := 0; i < len(lines); { |
| @@ -33,7 +42,7 @@ func richText(text string) template.HTML { |
| for j < len(lines) && !isListLine(lines[j]) { |
| j++ |
| } |
| - inline(&b, strings.Join(lines[i:j], "\n")) |
| + inline(&b, strings.Join(lines[i:j], "\n"), strict) |
| i = j |
| continue |
| } |
| @@ -48,7 +57,7 @@ func richText(text string) template.HTML { |
| break |
| } |
| b.WriteString("<li>") |
| - inline(&b, item) |
| + inline(&b, item, strict) |
| b.WriteString("</li>") |
| } |
| b.WriteString("</" + kind + ">") |
| @@ -79,7 +88,11 @@ func isListLine(line string) bool { k, _, _ := listLine(line); return k != "" } |
| // inline writes text with its safe links, and bold and italics between |
| // them. |
| -func inline(b *strings.Builder, text string) { |
| +func inline(b *strings.Builder, text string, strict bool) { |
| + emphasis := emphasis |
| + if strict { |
| + emphasis = strictEmphasis |
| + } |
| last := 0 |
| for _, m := range linkRE.FindAllStringSubmatchIndex(text, -1) { |
| end, label, target := m[1], "", "" |
| @@ -130,6 +143,52 @@ func emphasis(b *strings.Builder, text string) { |
| b.WriteString(html.EscapeString(text[last:])) |
| } |
| +// strictEmphasis is emphasis for the person's words: **x** and *x* or _x_ |
| +// only at word boundaries. A run of markers opens only at the start or |
| +// after a character that is no word's (a space, punctuation), closes only |
| +// at the end or before one, and is exactly one * or _, or two *: so |
| +// 2*3*4, a*b + c*d, x**2 + y**2 and __init__.py stay as written. x is as |
| +// in emphasis. Each run looks only as far as the next of its marker, so it |
| +// is linear. |
| +func strictEmphasis(b *strings.Builder, text string) { |
| + last := 0 |
| + for i := 0; i < len(text); { |
| + c := text[i] |
| + if c != '*' && c != '_' { |
| + i++ |
| + continue |
| + } |
| + run := markerRun(text, i) |
| + if (i == 0 || !wordByte(text[i-1])) && (run == 1 || run == 2 && c == '*') { |
| + from := i + run |
| + if k := strings.IndexByte(text[from:], c); k >= 0 { |
| + j := from + k |
| + end := j + markerRun(text, j) |
| + if x := text[from:j]; end-j == run && emphasized(x) && (end == len(text) || !wordByte(text[end])) { |
| + tag := "em" |
| + if run == 2 { |
| + tag = "strong" |
| + } |
| + b.WriteString(html.EscapeString(text[last:i]) + "<" + tag + ">" + html.EscapeString(x) + "</" + tag + ">") |
| + i, last = end, end |
| + continue |
| + } |
| + } |
| + } |
| + i += run |
| + } |
| + b.WriteString(html.EscapeString(text[last:])) |
| +} |
| + |
| +// markerRun is how many of text[i] follow one another from i. |
| +func markerRun(text string, i int) int { |
| + n := 1 |
| + for i+n < len(text) && text[i+n] == text[i] { |
| + n++ |
| + } |
| + return n |
| +} |
| + |
| // emphasized is whether x may be bold or italic: not empty, on one line, |
| // with no space at either end. |
| func emphasized(x string) bool { |
| @@ -146,3 +205,6 @@ func wordByte(c byte) bool { |
| // Rich is an Assistant's line with its links (richText), for templates. |
| func (v askView) Rich(text string) template.HTML { return richText(text) } |
| + |
| +// RichPerson is the person's own message (personText), for templates. |
| +func (v askView) RichPerson(text string) template.HTML { return personText(text) } |
diff --git a/internal/web/rich_internal_test.go b/internal/web/rich_internal_test.go| index 78fe013..e7b1cbb 100644 |
| --- a/internal/web/rich_internal_test.go |
| +++ b/internal/web/rich_internal_test.go |
| @@ -1,6 +1,10 @@ |
| package web |
| -import "testing" |
| +import ( |
| + "encoding/json" |
| + "os" |
| + "testing" |
| +) |
| // Equipo's lines may carry Markdown links. Base links only web addresses; |
| // everything else, raw HTML included, stays text. |
| @@ -64,3 +68,26 @@ func TestRichTextMarkdown(t *testing.T) { |
| } |
| } |
| } |
| + |
| +// The person's own words (Paul, 2026-11-26; Fable's S4): the Assistant's |
| +// little Markdown, with emphasis only at word boundaries. The samples are |
| +// the app's too (PersonMarkdownTests) and the script's (TestAskPersonMarkdown). |
| +func TestPersonText(t *testing.T) { |
| + raw, err := os.ReadFile("testdata/person.json") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var cases []struct{ Text, HTML string } |
| + if err := json.Unmarshal(raw, &cases); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, c := range cases { |
| + if got := string(personText(c.Text)); got != c.HTML { |
| + t.Errorf("personText(%q)\n got %s\nwant %s", c.Text, got, c.HTML) |
| + } |
| + } |
| + // The Assistant's replies keep their rules. |
| + if got := string(richText("2*3*4")); got != "2<em>3</em>4" { |
| + t.Errorf("richText changed: %s", got) |
| + } |
| +} |
diff --git a/internal/web/templates/partials/chat.html b/internal/web/templates/partials/chat.html| index 117c7b9..5bc96d1 100644 |
| --- a/internal/web/templates/partials/chat.html |
| +++ b/internal/web/templates/partials/chat.html |
| @@ -43,7 +43,7 @@ |
| </div> |
| <div class="ask-chat" data-when="ready norunner oldrunner"{{if not (.Shows "ready norunner oldrunner")}} hidden{{end}}> |
| <div class="log"><ol class="thread" role="log" aria-label="Conversation"{{with .Zone}} data-zone="{{.}}"{{end}} data-mark="{{asset "static/oficina/equipo.svg"}}"> |
| -{{range .Messages}}{{if eq .Role "person"}}<li class="msg person" data-id="{{.ID}}">{{.Text}}</li>{{else}}<li class="msg coordinator" data-id="{{.ID}}">{{$.Rich .Text}}{{range $.OffersAt .ID}}<div class="connect-offer" data-card="{{.ID}}" data-revision="{{.Revision}}">{{template "ask-offer" .}}</div>{{end}}</li>{{end}} |
| +{{range .Messages}}{{if eq .Role "person"}}<li class="msg person" data-id="{{.ID}}">{{$.RichPerson .Text}}</li>{{else}}<li class="msg coordinator" data-id="{{.ID}}">{{$.Rich .Text}}{{range $.OffersAt .ID}}<div class="connect-offer" data-card="{{.ID}}" data-revision="{{.Revision}}">{{template "ask-offer" .}}</div>{{end}}</li>{{end}} |
| {{end}}{{with .Notice}}<li class="ask-notice" data-after="{{$.NoticeAfter}}">{{.}}</li> |
| {{end}}{{range .Jobs}}{{template "ask-job" .}} |
| {{end}}{{range .LooseCards}}{{template "ask-card" .}} |
diff --git a/internal/web/testdata/person.json b/internal/web/testdata/person.json| new file mode 100644 |
| index 0000000..b55cf2d |
| --- /dev/null |
| +++ b/internal/web/testdata/person.json |
| @@ -0,0 +1,66 @@ |
| +[ |
| + { |
| + "text": "**Bold** and *it*", |
| + "html": "<strong>Bold</strong> and <em>it</em>" |
| + }, |
| + { |
| + "text": "*soon*, _later_ and **now**!", |
| + "html": "<em>soon</em>, <em>later</em> and <strong>now</strong>!" |
| + }, |
| + { |
| + "text": "Two lines\nhere, 2*3 and a_b_c", |
| + "html": "Two lines\nhere, 2*3 and a_b_c" |
| + }, |
| + { |
| + "text": "2*3*4", |
| + "html": "2*3*4" |
| + }, |
| + { |
| + "text": "2*3 and 4*5, a*b + c*d", |
| + "html": "2*3 and 4*5, a*b + c*d" |
| + }, |
| + { |
| + "text": "x**2 + y**2", |
| + "html": "x**2 + y**2" |
| + }, |
| + { |
| + "text": "__init__.py and my_file_name.txt", |
| + "html": "__init__.py and my_file_name.txt" |
| + }, |
| + { |
| + "text": "f(*args) and g(*rest)", |
| + "html": "f(*args) and g(*rest)" |
| + }, |
| + { |
| + "text": "word*not*emphasis and *also*not", |
| + "html": "word*not*emphasis and *also*not" |
| + }, |
| + { |
| + "text": "_private_ var and **kwargs", |
| + "html": "<em>private</em> var and **kwargs" |
| + }, |
| + { |
| + "text": "1986. A great year", |
| + "html": "1986. A great year" |
| + }, |
| + { |
| + "text": "3. Third\n4. Fourth", |
| + "html": "<ol start=\"3\"><li>Third</li><li>Fourth</li></ol>" |
| + }, |
| + { |
| + "text": "Not code:\n indented four\n\tand a tab", |
| + "html": "Not code:\n indented four\n\tand a tab" |
| + }, |
| + { |
| + "text": "# Not a heading\n> not a quote\n---\n+ not a bullet\nAT&T <b>x</b>", |
| + "html": "# Not a heading\n> not a quote\n---\n+ not a bullet\nAT&amp;T <b>x</b>" |
| + }, |
| + { |
| + "text": "Shopping:\n- [Menu](https://fennel.example/menu)\n- [x](javascript:alert(1))", |
| + "html": "Shopping:<ul><li><a href=\"https://fennel.example/menu\" target=\"_blank\" rel=\"noopener\">Menu</a></li><li>[x](javascript:alert(1))</li></ul>" |
| + }, |
| + { |
| + "text": "See https://fennel.example/menu.", |
| + "html": "See <a href=\"https://fennel.example/menu\" target=\"_blank\" rel=\"noopener\">https://fennel.example/menu</a>." |
| + } |
| +] |
diff --git a/internal/webtest/ask_test.go b/internal/webtest/ask_test.go| index 4e77482..6cf608f 100644 |
| --- a/internal/webtest/ask_test.go |
| +++ b/internal/webtest/ask_test.go |
| @@ -2011,3 +2011,28 @@ func TestAskTeamUpdateTurnIsQuiet(t *testing.T) { |
| page = a.get("/ask").Body |
| expect(t, "/ask with the person's turn", page, `<p class="ask-status" role="status">(.*?)</p>`, "Thinking…") |
| } |
| + |
| +// The person's own messages are drawn in the Assistant's little Markdown, |
| +// under its rules (Paul, 2026-11-26): bold, lists and safe links; raw HTML |
| +// and unsafe links stay text, and plain words are exactly as written. |
| +func TestAskPersonMessagesAreMarkdown(t *testing.T) { |
| + a, f := newAskApp(t) |
| + a.connectEquipo(f) |
| + for _, text := range []string{ |
| + "**Bold** and <b>x</b>:\n- [Menu](https://fennel.example/menu)\n- [x](javascript:alert(1))", |
| + "Two lines\nhere, 2*3 and a_b_c", |
| + } { |
| + a.post("/ask/messages", url.Values{"text": {text}}) |
| + } |
| + page := a.get("/ask").Body |
| + person := regexp.MustCompile(`(?s)<li class="msg person" data-id="[^"]+">(.*?)</li>\n`).FindAllStringSubmatch(page, -1) |
| + if len(person) != 2 { |
| + t.Fatalf("person messages: %d\n%s", len(person), page) |
| + } |
| + if want := `<strong>Bold</strong> and <b>x</b>:<ul><li><a href="https://fennel.example/menu" target="_blank" rel="noopener">Menu</a></li><li>[x](javascript:alert(1))</li></ul>`; person[0][1] != want { |
| + t.Errorf("Markdown:\n got %s\nwant %s", person[0][1], want) |
| + } |
| + if want := "Two lines\nhere, 2*3 and a_b_c"; person[1][1] != want { |
| + t.Errorf("plain words:\n got %q\nwant %q", person[1][1], want) |
| + } |
| +} |
diff --git a/native/apple/Sources/BaseKit/Ask/Composer.swift b/native/apple/Sources/BaseKit/Ask/Composer.swift| index fc647b2..62d393b 100644 |
| --- a/native/apple/Sources/BaseKit/Ask/Composer.swift |
| +++ b/native/apple/Sources/BaseKit/Ask/Composer.swift |
| @@ -3,6 +3,7 @@ import SwiftUI |
| import AppKit |
| #elseif os(iOS) |
| import UIKit |
| +import UniformTypeIdentifiers |
| #endif |
| /// The composer (chat.html `.composer`): one field that grows to a few |
| @@ -100,28 +101,42 @@ enum ComposerReturn: Equatable { |
| /// first responder of the window the anchor is in, while the field has the |
| /// keyboard (as it does whenever its key handler runs). |
| @MainActor final class ComposerInput { |
| - /// Whether the field has the keyboard (its FocusState). |
| - var focused = false |
| weak var model: AskModel? |
| #if os(macOS) |
| + /// Whether the field has the keyboard (its FocusState). |
| + var focused = false |
| weak var anchor: NSView? |
| /// A Mac field's editor. |
| var editor: NSTextView? { anchor?.window?.firstResponder as? NSTextView } |
| var composing: Bool { editor?.hasMarkedText() ?? false } |
| + /// Where pastes come from (tests give their own). |
| + static var pasteboard = NSPasteboard.general |
| private var observers: [NSObjectProtocol] = [] |
| + /// A menu's Paste (by its key or a click) is being sent. |
| + private var pasting = false |
| + private var converting = false |
| /// Starts watching the field, once its anchor is in a view (never in |
| /// an init: SwiftUI makes a ComposerInput on every pass of a parent's |
| /// body and keeps only the first). |
| func start() { |
| guard observers.isEmpty else { return } |
| - for name in [Notification.Name.NSUndoManagerDidUndoChange, .NSUndoManagerDidRedoChange] { |
| - observers.append(NotificationCenter.default.addObserver(forName: name, object: nil, queue: nil) { [weak self] note in |
| - // Undo and Redo post on the main thread. |
| - nonisolated(unsafe) let manager = note.object as AnyObject? |
| - MainActor.assumeIsolated { self?.undone(by: manager) } |
| + let center = NotificationCenter.default |
| + // Undo, Redo, text changes and menu actions all post on the main |
| + // thread. |
| + func watch(_ name: Notification.Name, _ act: @escaping @MainActor (ComposerInput, Notification) -> Void) { |
| + observers.append(center.addObserver(forName: name, object: nil, queue: nil) { [weak self] note in |
| + nonisolated(unsafe) let note = note |
| + MainActor.assumeIsolated { if let self { act(self, note) } } |
| }) |
| } |
| + watch(.NSUndoManagerDidUndoChange) { $0.undone(by: $1.object as AnyObject?) } |
| + watch(.NSUndoManagerDidRedoChange) { $0.undone(by: $1.object as AnyObject?) } |
| + watch(NSText.didChangeNotification) { $0.richPaste(in: $1.object as AnyObject?) } |
| + watch(NSMenu.willSendActionNotification) { input, note in |
| + input.pasting = (note.userInfo?["MenuItem"] as? NSMenuItem)?.action == #selector(NSText.paste(_:)) |
| + } |
| + watch(NSMenu.didSendActionNotification) { input, _ in input.pasting = false } |
| } |
| isolated deinit { observers.forEach(NotificationCenter.default.removeObserver) } |
| @@ -135,6 +150,35 @@ enum ComposerReturn: Equatable { |
| guard focused, let editor, let manager, manager === editor.undoManager, model?.text != editor.string else { return } |
| editor.didChangeText() |
| } |
| + |
| + /// A rich paste (HTML, or RTF without HTML) as Markdown. The Mac field |
| + /// pastes the plain text itself and has no hook before it, so this |
| + /// follows, inside the Paste menu action (its key or a click): the |
| + /// plain text just pasted, ending at the cursor, is put back as one |
| + /// edit with the paste (one Undo takes both). Paste and Match Style, |
| + /// typing, an input method, dictation, drops and Undo are never a |
| + /// Paste, and are left alone. |
| + func richPaste(in changed: AnyObject?) { |
| + guard pasting, focused, !converting, let editor, changed === editor, !editor.hasMarkedText() else { return } |
| + let board = Self.pasteboard |
| + guard let rich = board.availableType(from: [.html, .rtf]), |
| + let plain = board.string(forType: .string), !plain.isEmpty else { return } |
| + let markdown = rich == .html ? board.string(forType: .html).flatMap(PasteMarkdown.fromHTML) |
| + : board.data(forType: .rtf).flatMap(PasteMarkdown.fromRTF) |
| + guard let markdown else { return } |
| + let text = editor.string as NSString, length = (plain as NSString).length |
| + let selection = editor.selectedRange() |
| + let pasted = NSRange(location: selection.location - length, length: length) |
| + guard selection.length == 0, pasted.location >= 0, text.substring(with: pasted) == plain, |
| + editor.shouldChangeText(in: pasted, replacementString: markdown) else { return } |
| + converting = true |
| + defer { converting = false } |
| + editor.replaceCharacters(in: pasted, with: markdown) |
| + editor.setSelectedRange(NSRange(location: pasted.location + (markdown as NSString).length, length: 0)) |
| + editor.didChangeText() |
| + editor.breakUndoCoalescing() |
| + } |
| + |
| /// A new line in place of the selection, as Option Return in any Mac |
| /// field: one undoable edit, the cursor after it. |
| func insertNewline() -> Bool { |
| @@ -145,6 +189,18 @@ enum ComposerReturn: Equatable { |
| #elseif os(iOS) |
| weak var anchor: UIView? |
| var editor: (UIView & UITextInput)? { anchor?.window.flatMap(Self.firstResponder) } |
| + private let paste = ComposerPaste() |
| + /// Whether the field has the keyboard; once it has, its text view |
| + /// takes rich pastes as Markdown (ComposerPaste). |
| + var focused = false { |
| + didSet { |
| + guard focused else { return } |
| + Task { @MainActor [weak self] in |
| + guard let self, let view = self.editor as? UITextView, view.pasteDelegate !== self.paste else { return } |
| + view.pasteDelegate = self.paste |
| + } |
| + } |
| + } |
| var composing: Bool { editor?.markedTextRange != nil } |
| func insertNewline() -> Bool { |
| guard let editor, let range = editor.selectedTextRange else { return false } |
| @@ -157,11 +213,31 @@ enum ComposerReturn: Equatable { |
| return nil |
| } |
| #else |
| + var focused = false |
| var composing: Bool { false } |
| func insertNewline() -> Bool { false } |
| #endif |
| } |
| +#if os(iOS) |
| +/// The iPhone and iPad field's paste: HTML or RTF becomes Markdown, in |
| +/// place of the selection as any paste; anything else is pasted as is. |
| +final class ComposerPaste: NSObject, UITextPasteDelegate { |
| + func textPasteConfigurationSupporting(_ textPasteConfigurationSupporting: any UITextPasteConfigurationSupporting, transform item: UITextPasteItem) { |
| + let provider = item.itemProvider |
| + nonisolated(unsafe) let item = item |
| + for (type, convert) in [(UTType.html, { (data: Data) in PasteMarkdown.html(data).flatMap(PasteMarkdown.fromHTML) }), |
| + (UTType.rtf, PasteMarkdown.fromRTF)] where provider.hasItemConformingToTypeIdentifier(type.identifier) { |
| + provider.loadDataRepresentation(forTypeIdentifier: type.identifier) { data, _ in |
| + if let markdown = data.flatMap(convert) { item.setResult(string: markdown) } else { item.setDefaultResult() } |
| + } |
| + return |
| + } |
| + item.setDefaultResult() |
| + } |
| +} |
| +#endif |
| + |
| /// An empty view behind the field, so the composer knows its window. |
| #if os(macOS) |
| struct ComposerAnchor: NSViewRepresentable { |
diff --git a/native/apple/Sources/BaseKit/Ask/Markdown/BaseMarkdownView.swift b/native/apple/Sources/BaseKit/Ask/Markdown/BaseMarkdownView.swift| index a512933..e279fc9 100644 |
| --- a/native/apple/Sources/BaseKit/Ask/Markdown/BaseMarkdownView.swift |
| +++ b/native/apple/Sources/BaseKit/Ask/Markdown/BaseMarkdownView.swift |
| @@ -12,8 +12,11 @@ import UIKit |
| /// The Assistant's prose: the little Markdown it writes (lists, links, |
| /// bold, italics), parsed off the main thread as it streams. The source is |
| /// untrusted text; only absolute http(s) links are actionable. |
| +/// Base: the person's own messages too (`person`), which keep each line |
| +/// they typed and whose links keep the bubble's ink, as on the web. |
| struct BaseMarkdownView: View { |
| private let draft: Bool |
| + private let person: Bool |
| private let stream: MarkdownStreamRenderer |
| private let request: MarkdownRenderCache.Request |
| private let initial: MarkdownRenderCache.Result |
| @@ -26,20 +29,32 @@ struct BaseMarkdownView: View { |
| init(_ text: String, draft: Bool, id: String, transcript: MarkdownTranscript) { |
| self.draft = draft |
| + person = false |
| request = MarkdownRenderCache.Request(messageID: id, text: text, draft: draft) |
| initial = MarkdownRenderCache.shared.initial(request) |
| stream = transcript.renderer(for: id) |
| } |
| + /// Base: the person's own message, already in the web's little subset |
| + /// (PersonMarkdown), never streamed. |
| + init(person nodes: [ChatMarkdownNode], id: String, transcript: MarkdownTranscript) { |
| + draft = false |
| + person = true |
| + request = MarkdownRenderCache.Request(messageID: "person:" + id, text: "", draft: false) |
| + initial = MarkdownRenderCache.Result(tree: nodes, complete: true) |
| + stream = transcript.renderer(for: "person:" + id) |
| + } |
| + |
| var body: some View { |
| let p = Palette(scheme) |
| MarkdownRows(nodes: nodes) |
| .font(BaseFont.body(15)) |
| .foregroundStyle(p[.frost]) |
| - .tint(p[.focus]) |
| + .tint(person ? p[.frost] : p[.focus]) |
| + .environment(\.markdownKeepsLines, person) |
| .textSelection(.enabled) |
| - .onAppear { stream.submit(request, needsParsing: !initial.complete) } |
| - .onChange(of: request) { stream.submit(request, needsParsing: !initial.complete) } |
| + .onAppear { if !person { stream.submit(request, needsParsing: !initial.complete) } } |
| + .onChange(of: request) { if !person { stream.submit(request, needsParsing: !initial.complete) } } |
| .environment(\.openURL, OpenURLAction { url in |
| guard let original = MarkdownActions.originalTarget(url, in: nodes), |
| case .external(let target)? = MarkdownActions.destination(original, origin: url) else { return .discarded } |
| @@ -65,8 +80,16 @@ private struct MarkdownRows: View { |
| } |
| } |
| +extension EnvironmentValues { |
| + /// Base: the text is as typed (the person's messages), where the |
| + /// Assistant's runs of space and line breaks are one space, as |
| + /// Markdown's are. |
| + @Entry var markdownKeepsLines = false |
| +} |
| + |
| private struct MarkdownBlock: View { |
| let node: ChatMarkdownNode |
| + @Environment(\.markdownKeepsLines) private var keepsLines |
| var body: some View { |
| switch node.kind { |
| case "paragraph", "inlineGroup": Text(inline(node.children)).fixedSize(horizontal: false, vertical: true) |
| @@ -78,7 +101,10 @@ private struct MarkdownBlock: View { |
| } |
| private func prose(_ text: String) -> String { |
| - text.replacingOccurrences(of: #"[ \t\r\n\f]+"#, with: " ", options: .regularExpression) |
| + // Base: the person's words are as typed, spaces and lines and all, |
| + // as the web's pre-wrap draws them. |
| + if keepsLines { return text } |
| + return text.replacingOccurrences(of: #"[ \t\r\n\f]+"#, with: " ", options: .regularExpression) |
| } |
| private func inline(_ nodes: [ChatMarkdownNode]) -> AttributedString { |
| @@ -100,6 +126,13 @@ private struct MarkdownBlock: View { |
| if work.bold { intent.insert(.stronglyEmphasized) } |
| if work.italic { intent.insert(.emphasized) } |
| part.inlinePresentationIntent = intent |
| + // Base: italics by the face's italic instance, which the |
| + // emphasized intent can't find (it lands on another cut), so |
| + // the run is set in that font alone (BaseFont.body). |
| + if work.italic, node.kind != "code" { |
| + part.font = BaseFont.body(15, work.bold ? .bold : .regular, italic: true) |
| + part.inlinePresentationIntent = nil |
| + } |
| if let target = work.link, ChatMarkdown.allowsLink(target) { |
| part.link = MarkdownActions.linkURL(target) |
| part.underlineStyle = .single |
diff --git a/native/apple/Sources/BaseKit/Ask/Markdown/ChatMarkdown.swift b/native/apple/Sources/BaseKit/Ask/Markdown/ChatMarkdown.swift| index b51346c..3a99710 100644 |
| --- a/native/apple/Sources/BaseKit/Ask/Markdown/ChatMarkdown.swift |
| +++ b/native/apple/Sources/BaseKit/Ask/Markdown/ChatMarkdown.swift |
| @@ -8,9 +8,9 @@ import cmark_gfm |
| struct ChatMarkdownNode: Codable, Equatable, Sendable { |
| // Source anchors survive appended chunks and a fence's closing line. |
| var sourceOffset = 0 |
| - enum CodingKeys: String, CodingKey { case kind, text, target, label, copy, copied, wrap, copyEnabled, children } |
| + enum CodingKeys: String, CodingKey { case kind, text, target, label, copy, copied, wrap, copyEnabled, start, children } |
| static func == (lhs: Self, rhs: Self) -> Bool { |
| - lhs.kind == rhs.kind && lhs.text == rhs.text && lhs.target == rhs.target && lhs.label == rhs.label && lhs.copy == rhs.copy && lhs.copied == rhs.copied && lhs.wrap == rhs.wrap && lhs.copyEnabled == rhs.copyEnabled && lhs.children == rhs.children |
| + lhs.kind == rhs.kind && lhs.text == rhs.text && lhs.target == rhs.target && lhs.label == rhs.label && lhs.copy == rhs.copy && lhs.copied == rhs.copied && lhs.wrap == rhs.wrap && lhs.copyEnabled == rhs.copyEnabled && lhs.start == rhs.start && lhs.children == rhs.children |
| } |
| var kind: String |
| var text: String? |
| @@ -20,6 +20,8 @@ struct ChatMarkdownNode: Codable, Equatable, Sendable { |
| var copied: String? |
| var wrap: Bool? |
| var copyEnabled: Bool? |
| + /// Base: an ordered list's first number, when it isn't 1. |
| + var start: Int? |
| var children: [ChatMarkdownNode] = [] |
| } |
| @@ -368,7 +370,11 @@ private struct MarkdownProjection { |
| case "heading": return [ChatMarkdownNode(kind: "paragraph", children: children(node))] |
| case "emph": return [ChatMarkdownNode(kind: "emphasis", children: children(node))] |
| case "strong": return [ChatMarkdownNode(kind: "strong", children: children(node))] |
| - case "list": return [ChatMarkdownNode(kind: cmark_node_get_list_type(node) == CMARK_ORDERED_LIST ? "ordered" : "unordered", children: children(node))] |
| + case "list": |
| + // Base: an ordered list keeps its first number. |
| + let ordered = cmark_node_get_list_type(node) == CMARK_ORDERED_LIST |
| + let start = Int(cmark_node_get_list_start(node)) |
| + return [ChatMarkdownNode(kind: ordered ? "ordered" : "unordered", start: ordered && start != 1 ? start : nil, children: children(node))] |
| case "item": return [ChatMarkdownNode(kind: "item", children: children(node))] |
| case "link": |
| // Goldmark's AutoLink is outside Render's vocabulary. |
diff --git a/native/apple/Sources/BaseKit/Ask/Markdown/MarkdownPresentation.swift b/native/apple/Sources/BaseKit/Ask/Markdown/MarkdownPresentation.swift| index 98f51e3..0b3146e 100644 |
| --- a/native/apple/Sources/BaseKit/Ask/Markdown/MarkdownPresentation.swift |
| +++ b/native/apple/Sources/BaseKit/Ask/Markdown/MarkdownPresentation.swift |
| @@ -3,7 +3,7 @@ |
| // marked "Base:"; keep the rest in step with Equipo's. |
| import Foundation |
| -/// A flat list of layout rows. Depth changes indentation, never view nesting. |
| +/// A flat list of layout rows. Base: an ordered list counts from its start. Depth changes indentation, never view nesting. |
| /// Indentation stops at four levels so deeply nested replies remain readable |
| /// at phone width; every item and all of its content are still present. |
| enum MarkdownPresentation { |
| @@ -33,7 +33,7 @@ enum MarkdownPresentation { |
| let children = groups(item.children) |
| for (offset, child) in children.enumerated().reversed() { |
| stack.append(Row(node: child, indentation: row.indentation + 1, |
| - marker: offset == 0 ? (row.node.kind == "ordered" ? "\(index + 1)." : "•") : nil)) |
| + marker: offset == 0 ? (row.node.kind == "ordered" ? "\((row.node.start ?? 1) + index)." : "•") : nil)) |
| } |
| } |
| } else { |
diff --git a/native/apple/Sources/BaseKit/Ask/Markdown/PersonMarkdown.swift b/native/apple/Sources/BaseKit/Ask/Markdown/PersonMarkdown.swift| new file mode 100644 |
| index 0000000..e9db975 |
| --- /dev/null |
| +++ b/native/apple/Sources/BaseKit/Ask/Markdown/PersonMarkdown.swift |
| @@ -0,0 +1,127 @@ |
| +import Foundation |
| + |
| +/// Base: the person's own message as the chat's Markdown tree, in the web's |
| +/// little subset (richText and personText in ask_cards.go, rich and |
| +/// strictEmphasis in ask.js), not CommonMark: runs of "- " or "* " lines |
| +/// are a bulleted list, runs of "1. " or "1) " lines (1 to 3 digits) a |
| +/// numbered one from its first number, and every other line is text with |
| +/// its newlines (the one next to a list goes). In text and list items a |
| +/// Markdown link or bare URL is a link only to an http(s) address, and |
| +/// between links **x** is bold and *x* or _x_ italic, only at word |
| +/// boundaries. Nothing else is Markdown: headings, quotes, rules, escapes, |
| +/// entities and indented code are text as typed. The samples in |
| +/// internal/web/testdata/person.json check the three agree. |
| +enum PersonMarkdown { |
| + static func parse(_ text: String) -> [ChatMarkdownNode] { |
| + var builder = Builder() |
| + let lines = text.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n") |
| + .replacingOccurrences(of: "\0", with: "").components(separatedBy: "\n") |
| + var out: [ChatMarkdownNode] = [] |
| + var i = 0 |
| + while i < lines.count { |
| + guard let first = listLine(lines[i]) else { |
| + var j = i + 1 |
| + while j < lines.count, listLine(lines[j]) == nil { j += 1 } |
| + let inline = builder.inline(lines[i..<j].joined(separator: "\n")) |
| + if !inline.isEmpty { out.append(builder.node("paragraph", children: inline)) } |
| + i = j |
| + continue |
| + } |
| + var items: [ChatMarkdownNode] = [] |
| + while i < lines.count, let line = listLine(lines[i]), line.ordered == first.ordered { |
| + items.append(builder.node("item", children: builder.inline(line.item))) |
| + i += 1 |
| + } |
| + var list = builder.node(first.ordered ? "ordered" : "unordered", children: items) |
| + if first.ordered, first.n != 1 { list.start = first.n } |
| + out.append(list) |
| + } |
| + return out |
| + } |
| + |
| + /// Whether a tree is only words: the message is then drawn exactly as |
| + /// written. |
| + static func isPlain(_ nodes: [ChatMarkdownNode]) -> Bool { |
| + nodes.allSatisfy { $0.kind == "paragraph" && $0.children.allSatisfy { $0.kind == "text" } } |
| + } |
| + |
| + private static let number = try! NSRegularExpression(pattern: #"^([0-9]{1,3})[.)] "#) |
| + |
| + /// A line's list (numbered or not, its number) and the item after the |
| + /// marker, which is never empty. |
| + static func listLine(_ line: String) -> (ordered: Bool, n: Int, item: String)? { |
| + let u = Array(line.utf8) |
| + if u.count > 2, u[0] == UInt8(ascii: "-") || u[0] == UInt8(ascii: "*"), u[1] == UInt8(ascii: " ") { |
| + return (false, 0, String(decoding: u[2...], as: UTF8.self)) |
| + } |
| + if let m = number.firstMatch(in: line, range: NSRange(line.startIndex..., in: line)), |
| + let whole = Range(m.range, in: line), let digits = Range(m.range(at: 1), in: line), whole.upperBound < line.endIndex { |
| + return (true, Int(line[digits]) ?? 1, String(line[whole.upperBound...])) |
| + } |
| + return nil |
| + } |
| + |
| + private static let link = try! NSRegularExpression(pattern: #"\[([^\[\]\n]{1,300})\]\(([^()\s]{1,1000})\)|https?://[^\s<>()\[\]"']+"#) |
| + |
| + private struct Builder { |
| + var offset = 0 |
| + /// Every node its own offset: the rows are told apart by it. |
| + mutating func node(_ kind: String, text: String? = nil, target: String? = nil, children: [ChatMarkdownNode] = []) -> ChatMarkdownNode { |
| + offset += 1 |
| + return ChatMarkdownNode(sourceOffset: offset, kind: kind, text: text, target: target, children: children) |
| + } |
| + |
| + mutating func inline(_ text: String) -> [ChatMarkdownNode] { |
| + var out: [ChatMarkdownNode] = [] |
| + let ns = text as NSString |
| + var last = 0 |
| + for m in PersonMarkdown.link.matches(in: text, range: NSRange(location: 0, length: ns.length)) { |
| + var end = NSMaxRange(m.range), label: String, target: String |
| + if m.range(at: 1).location != NSNotFound { |
| + label = ns.substring(with: m.range(at: 1)); target = ns.substring(with: m.range(at: 2)) |
| + } else { |
| + var bare = ns.substring(with: m.range) |
| + while let c = bare.last, ".,;:!?".contains(c) { bare.removeLast() } |
| + target = bare; label = bare; end = m.range.location + (bare as NSString).length |
| + } |
| + guard ChatMarkdown.allowsLink(target) else { continue } |
| + out += emphasis(ns.substring(with: NSRange(location: last, length: m.range.location - last))) |
| + out.append(node("link", target: target, children: [node("text", text: label)])) |
| + last = end |
| + } |
| + out += emphasis(ns.substring(from: last)) |
| + return out |
| + } |
| + |
| + /// strictEmphasis in ask_cards.go, over Unicode scalars (a scalar |
| + /// beyond ASCII is a word's, as any byte of one is there). |
| + mutating func emphasis(_ text: String) -> [ChatMarkdownNode] { |
| + let s = Array(text.unicodeScalars) |
| + var out: [ChatMarkdownNode] = [] |
| + func str(_ r: Range<Int>) -> String { String(String.UnicodeScalarView(s[r])) } |
| + func word(_ c: Unicode.Scalar) -> Bool { c.value >= 0x80 || c == "_" || ("0"..."9").contains(c) || ("a"..."z").contains(c) || ("A"..."Z").contains(c) } |
| + func run(_ at: Int) -> Int { var n = 1; while at + n < s.count, s[at + n] == s[at] { n += 1 }; return n } |
| + func emphasized(_ r: Range<Int>) -> Bool { |
| + !r.isEmpty && !s[r].contains("\n") && s[r.lowerBound] != " " && s[r.lowerBound] != "\t" && s[r.upperBound - 1] != " " && s[r.upperBound - 1] != "\t" |
| + } |
| + var last = 0, i = 0 |
| + while i < s.count { |
| + let c = s[i] |
| + guard c == "*" || c == "_" else { i += 1; continue } |
| + let n = run(i) |
| + if i == 0 || !word(s[i - 1]), n == 1 || (n == 2 && c == "*"), let j = s[(i + n)...].firstIndex(of: c) { |
| + let end = j + run(j) |
| + if end - j == n, emphasized((i + n)..<j), end == s.count || !word(s[end]) { |
| + if i > last { out.append(node("text", text: str(last..<i))) } |
| + out.append(node(n == 2 ? "strong" : "emphasis", children: [node("text", text: str((i + n)..<j))])) |
| + i = end; last = end |
| + continue |
| + } |
| + } |
| + i += n |
| + } |
| + if s.count > last { out.append(node("text", text: str(last..<s.count))) } |
| + return out |
| + } |
| + } |
| +} |
diff --git a/native/apple/Sources/BaseKit/Ask/PasteMarkdown.swift b/native/apple/Sources/BaseKit/Ask/PasteMarkdown.swift| new file mode 100644 |
| index 0000000..cd2cdab |
| --- /dev/null |
| +++ b/native/apple/Sources/BaseKit/Ask/PasteMarkdown.swift |
| @@ -0,0 +1,516 @@ |
| +import Foundation |
| +#if os(macOS) |
| +import AppKit |
| +#elseif os(iOS) |
| +import UIKit |
| +#endif |
| + |
| +/// A rich paste (a web page, Docs, Mail) as the Markdown the chat draws: |
| +/// bold (**x**), italics (*x*), links ([text](url), http(s) only, as |
| +/// BaseJSON.webURL), bullet and numbered lists (nested by indent), headings |
| +/// (# x), and line breaks and paragraphs. Everything else is its text. Nil |
| +/// when the paste formats nothing, or is mostly code (a monospace font, or |
| +/// pre, code, tt, samp, kbd; RTF in a fixed-pitch font), so a plain paste |
| +/// or code stays exactly as copied. HTML is only tokenised here and walked |
| +/// (nothing loads or runs): elements deeper than 32 are flattened, the |
| +/// walk stops once the Markdown passes the composer's 16,000 characters, |
| +/// and more than 2 MB of HTML is left plain. RTF is read by Foundation, |
| +/// which loads nothing either. ask.js's pasteMarkdown is the same walk |
| +/// (keep them in step: the samples in |
| +/// internal/browsertest/testdata/paste.json check both). |
| +enum PasteMarkdown { |
| + static let maxDepth = 32, maxOut = 16_000, maxHTML = 2_000_000 |
| + |
| + static func fromHTML(_ html: String) -> String? { |
| + guard html.utf16.count <= maxHTML else { return nil } |
| + var walker = Walker() |
| + // (A NUL marks a <pre>'s place in the walk's output, as a page's |
| + // parser never leaves one in text.) |
| + return walker.markdown(HTMLTree.parse(html.replacingOccurrences(of: "\0", with: ""))) |
| + } |
| + |
| + /// A clipboard's HTML bytes as text: UTF-8, or UTF-16 with its mark. |
| + static func html(_ data: Data) -> String? { |
| + if data.starts(with: [0xFF, 0xFE]) || data.starts(with: [0xFE, 0xFF]) { return String(data: data, encoding: .utf16) } |
| + return String(data: data, encoding: .utf8) |
| + } |
| + |
| + static func fromRTF(_ data: Data) -> String? { |
| + guard let text = try? NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.rtf], documentAttributes: nil) else { return nil } |
| + return fromAttributed(text) |
| + } |
| + |
| + /// An attributed string's paragraphs as lines (lists by their text |
| + /// lists), its runs bold, italic or linked by their attributes: the |
| + /// same tree HTML makes, so the same walk. |
| + static func fromAttributed(_ text: NSAttributedString) -> String? { |
| + var walker = Walker() |
| + return walker.markdown(HTMLTree.from(text)) |
| + } |
| +} |
| + |
| +/// Just enough HTML: elements with their attributes, and text. Tags that |
| +/// are never closed close with their parent; a stray end tag is dropped. |
| +struct HTMLTree: Equatable { |
| + var tag = "" // "" is text |
| + var attributes: [String: String] = [:] |
| + var text = "" |
| + var children: [HTMLTree] = [] |
| + |
| + static let void: Set<String> = ["br", "img", "hr", "input", "meta", "link", "area", "base", "col", "embed", "source", "track", "wbr", "param"] |
| + static let raw: Set<String> = ["script", "style", "textarea", "title", "template", "noscript", "iframe", "xmp", "plaintext"] |
| + /// What a new block closes when it opens, as a page would. |
| + static let closesP: Set<String> = ["p", "div", "ul", "ol", "li", "h1", "h2", "h3", "h4", "h5", "h6", "pre", "table", "blockquote", "section", "article", "header", "footer", "hr", "dl", "form"] |
| + |
| + static func parse(_ html: String) -> HTMLTree { |
| + let s = Array(html.unicodeScalars) |
| + var stack = [HTMLTree(tag: "body")] |
| + // Elements opened past the depth cap: not in the tree (their text |
| + // and line breaks go to the deepest one that is; a block is a line |
| + // of its own, a cell a space, and what the walk skips is skipped), |
| + // but their end tags still match them. |
| + enum Drop { case inline, block, cell, skip } |
| + var dropped: [(name: String, kind: Drop)] = [] |
| + var skipping = 0 |
| + func mark(_ tag: String) { stack[stack.count - 1].children.append(HTMLTree(tag: tag)) } |
| + var at = 0 |
| + func appendText(_ t: String) { |
| + guard !t.isEmpty, skipping == 0 else { return } |
| + stack[stack.count - 1].children.append(HTMLTree(text: MarkdownEntities.link(t))) |
| + } |
| + func close(_ index: Int) { |
| + while stack.count > index { |
| + let done = stack.removeLast() |
| + stack[stack.count - 1].children.append(done) |
| + } |
| + } |
| + func open(_ name: String) -> Int? { stack.lastIndex { $0.tag == name } } |
| + var text = "" |
| + while at < s.count { |
| + guard s[at] == "<" else { text.unicodeScalars.append(s[at]); at += 1; continue } |
| + // A comment, doctype or processing instruction: skipped. |
| + if at + 3 < s.count, s[at + 1] == "!", s[at + 2] == "-", s[at + 3] == "-" { |
| + appendText(text); text = "" |
| + var end = at + 4 |
| + while end + 2 < s.count, !(s[end] == "-" && s[end + 1] == "-" && s[end + 2] == ">") { end += 1 } |
| + at = min(s.count, end + 3) |
| + continue |
| + } |
| + if at + 1 < s.count, s[at + 1] == "!" || s[at + 1] == "?" { |
| + appendText(text); text = "" |
| + while at < s.count, s[at] != ">" { at += 1 } |
| + at += 1 |
| + continue |
| + } |
| + let closing = at + 1 < s.count && s[at + 1] == "/" |
| + var cursor = at + (closing ? 2 : 1) |
| + var name = "" |
| + while cursor < s.count, s[cursor].properties.isAlphabetic || ("0"..."9").contains(s[cursor]) || s[cursor] == "-" || s[cursor] == ":" { |
| + name.unicodeScalars.append(s[cursor]); cursor += 1 |
| + } |
| + guard !name.isEmpty else { text.unicodeScalars.append(s[at]); at += 1; continue } |
| + name = name.lowercased() |
| + // The attributes, to the tag's end. |
| + var attributes: [String: String] = [:] |
| + var selfClosing = false |
| + while cursor < s.count, s[cursor] != ">" { |
| + if s[cursor] == "/" { selfClosing = true; cursor += 1; continue } |
| + if s[cursor].properties.isWhitespace { cursor += 1; continue } |
| + selfClosing = false |
| + var key = "" |
| + while cursor < s.count, !s[cursor].properties.isWhitespace, !"=>/".unicodeScalars.contains(s[cursor]) { |
| + key.unicodeScalars.append(s[cursor]); cursor += 1 |
| + } |
| + while cursor < s.count, s[cursor].properties.isWhitespace { cursor += 1 } |
| + var value = "" |
| + if cursor < s.count, s[cursor] == "=" { |
| + cursor += 1 |
| + while cursor < s.count, s[cursor].properties.isWhitespace { cursor += 1 } |
| + if cursor < s.count, s[cursor] == "\"" || s[cursor] == "'" { |
| + let quote = s[cursor]; cursor += 1 |
| + while cursor < s.count, s[cursor] != quote { value.unicodeScalars.append(s[cursor]); cursor += 1 } |
| + cursor += 1 |
| + } else { |
| + while cursor < s.count, !s[cursor].properties.isWhitespace, s[cursor] != ">" { value.unicodeScalars.append(s[cursor]); cursor += 1 } |
| + } |
| + } |
| + if key.isEmpty { cursor += 1; continue } |
| + let k = key.lowercased() |
| + if attributes[k] == nil { attributes[k] = MarkdownEntities.link(value) } |
| + } |
| + at = min(s.count, cursor + 1) |
| + appendText(text); text = "" |
| + if closing { |
| + if dropped.last?.name == name { |
| + switch dropped.removeLast().kind { |
| + case .skip: skipping -= 1 |
| + case .block: mark(Walker.line) |
| + case .cell: mark(Walker.cell) |
| + case .inline: break |
| + } |
| + } else if let index = open(name), index > 0 { close(index) } |
| + continue |
| + } |
| + if closesP.contains(name), let p = open("p"), !(stack[(p + 1)...].contains { $0.tag == "li" || $0.tag == "td" || $0.tag == "th" }) { close(p) } |
| + if name == "li", let li = open("li"), !stack[(li + 1)...].contains(where: { $0.tag == "ul" || $0.tag == "ol" }) { close(li) } |
| + let element = HTMLTree(tag: name, attributes: attributes) |
| + if raw.contains(name) { |
| + // Its content is text to its end tag; none of it is kept |
| + // (the walk skips all of these). |
| + var end = at |
| + let closer = Array("</\(name)".unicodeScalars) |
| + while end < s.count { |
| + if s[end] == "<", end + closer.count <= s.count, |
| + String(String.UnicodeScalarView(s[end..<end + closer.count])).lowercased() == "</\(name)" { break } |
| + end += 1 |
| + } |
| + stack[stack.count - 1].children.append(element) |
| + at = end |
| + while at < s.count, s[at] != ">" { at += 1 } |
| + at += 1 |
| + continue |
| + } |
| + if skipping > 0 { |
| + if !void.contains(name), !selfClosing { dropped.append((name, .skip)); skipping += 1 } |
| + } else if void.contains(name) || selfClosing { |
| + stack[stack.count - 1].children.append(element) |
| + } else if stack.count > PasteMarkdown.maxDepth { |
| + let kind: Drop = Walker.skip.contains(name) ? .skip : Walker.blocks.contains(name) ? .block : name == "td" || name == "th" ? .cell : .inline |
| + if kind == .skip { skipping += 1 } |
| + if kind == .block { mark(Walker.line) } |
| + dropped.append((name, kind)) |
| + } else { |
| + stack.append(element) |
| + } |
| + } |
| + appendText(text) |
| + close(1) |
| + return stack[0] |
| + } |
| + |
| + /// The tree an attributed string's paragraphs and runs make. |
| + static func from(_ text: NSAttributedString) -> HTMLTree { |
| + var body = HTMLTree(tag: "body") |
| + // The open lists: each the list node path from body. |
| + var lists: [(ordered: Bool, node: HTMLTree)] = [] |
| + func closeLists(to depth: Int) { |
| + while lists.count > depth { |
| + let done = lists.removeLast().node |
| + if lists.isEmpty { |
| + body.children.append(done) |
| + } else { |
| + lists[lists.count - 1].node.children.append(done) |
| + } |
| + } |
| + } |
| + let string = text.string as NSString |
| + string.enumerateSubstrings(in: NSRange(location: 0, length: string.length), options: [.byParagraphs, .substringNotRequired]) { _, content, _, _ in |
| + let style = content.length > 0 ? text.attribute(.paragraphStyle, at: content.location, effectiveRange: nil) as? NSParagraphStyle : nil |
| + let textLists = style?.textLists ?? [] |
| + var line = HTMLTree(tag: textLists.isEmpty ? "div" : "li") |
| + var runsFrom = content.location |
| + if !textLists.isEmpty, let marker = Self.listMarker.firstMatch(in: text.string, range: content) { |
| + // A list's marker is in the text ("\t•\t", "\t1.\t"): it goes. |
| + runsFrom += marker.range.length |
| + } |
| + if runsFrom < NSMaxRange(content) { |
| + text.enumerateAttributes(in: NSRange(location: runsFrom, length: NSMaxRange(content) - runsFrom)) { attributes, run, _ in |
| + var node = HTMLTree(text: string.substring(with: run).replacingOccurrences(of: "\0", with: "")) |
| + if let link = attributes[.link] { |
| + let href = (link as? URL)?.absoluteString ?? (link as? String) ?? "" |
| + node = HTMLTree(tag: "a", attributes: ["href": href], children: [node]) |
| + } |
| + let (bold, italic, mono) = traits(attributes) |
| + if italic { node = HTMLTree(tag: "i", children: [node]) } |
| + if bold { node = HTMLTree(tag: "b", children: [node]) } |
| + if mono { node = HTMLTree(tag: "code", children: [node]) } |
| + line.children.append(node) |
| + } |
| + } else if textLists.isEmpty { |
| + line.children.append(HTMLTree(tag: "br")) |
| + } |
| + // The paragraph's lists, outermost first. |
| + let depth = textLists.count |
| + var shared = 0 |
| + while shared < min(depth, lists.count), lists[shared].ordered == ordered(textLists[shared]) { shared += 1 } |
| + closeLists(to: shared) |
| + while lists.count < depth { |
| + let ordered = ordered(textLists[lists.count]) |
| + lists.append((ordered, HTMLTree(tag: ordered ? "ol" : "ul"))) |
| + } |
| + if depth == 0 { body.children.append(line) } else { lists[lists.count - 1].node.children.append(line) } |
| + } |
| + closeLists(to: 0) |
| + return body |
| + } |
| + |
| + private static let listMarker = try! NSRegularExpression(pattern: #"\G\t?[^\t\n]{0,12}\t"#) |
| + |
| + private static func ordered(_ list: NSTextList) -> Bool { |
| + !["disc", "circle", "square", "box", "check", "diamond", "hyphen"].contains { list.markerFormat.rawValue.contains($0) } |
| + } |
| + |
| + private static func traits(_ attributes: [NSAttributedString.Key: Any]) -> (bold: Bool, italic: Bool, mono: Bool) { |
| + #if os(macOS) |
| + guard let font = attributes[.font] as? NSFont else { return (false, false, false) } |
| + let t = font.fontDescriptor.symbolicTraits |
| + return (t.contains(.bold), t.contains(.italic), t.contains(.monoSpace) || font.isFixedPitch) |
| + #elseif os(iOS) |
| + guard let font = attributes[.font] as? UIFont else { return (false, false, false) } |
| + let t = font.fontDescriptor.symbolicTraits |
| + return (t.contains(.traitBold), t.contains(.traitItalic), t.contains(.traitMonoSpace)) |
| + #else |
| + return (false, false, false) |
| + #endif |
| + } |
| +} |
| + |
| +/// ask.js's pasteMarkdown walk, line for line. |
| +private struct Walker { |
| + struct Run { var text: String; var bold: Bool; var italic: Bool; var href: String } |
| + struct Style { var bold = false, italic = false, href = "", heading = false, mono = false } |
| + static let code: Set<String> = ["code", "tt", "samp", "kbd"] |
| + static let blocks = lines.union(["p", "li", "ul", "ol", "h1", "h2", "h3", "h4", "h5", "h6", "pre"]) |
| + /// Marks HTMLTree.parse leaves for blocks and cells past the depth |
| + /// cap (no tag a page can write starts with "_"). |
| + static let line = "_line", cell = "_cell" |
| + static let raw: Set<String> = ["script", "style", "textarea", "title", "template", "noscript", "iframe"] |
| + static let monoFont = try! NSRegularExpression(pattern: "monospace|menlo|monaco|consolas|courier|sf ?mono|fira (code|mono)|jetbrains|source code|cascadia|ubuntu mono|dejavu sans mono|roboto mono|plex mono|andale mono|lucida console", options: .caseInsensitive) |
| + final class List { let ordered: Bool; var n: Int; let indent: String; var inner: String |
| + init(ordered: Bool, n: Int, indent: String) { self.ordered = ordered; self.n = n; self.indent = indent; inner = indent } |
| + } |
| + static let skip: Set<String> = ["script", "style", "head", "title", "template", "noscript", "iframe", "object", "embed", "svg", "math", "canvas", "video", "audio", "picture", "img", "button", "select", "input", "textarea"] |
| + static let lines: Set<String> = ["div", "section", "article", "header", "footer", "main", "nav", "aside", "blockquote", "figure", "figcaption", "address", "center", "details", "summary", "form", "fieldset", "table", "thead", "tbody", "tfoot", "tr", "caption", "dl", "dt", "dd", "hr"] |
| + |
| + var out = "" |
| + var runs: [Run] = [] |
| + var open = false |
| + var marker: String? |
| + var indent = "" |
| + var formatted = false |
| + var lists: [List] = [] |
| + /// Characters of text (not spaces), and how many of them are code's. |
| + var chars = 0, mono = 0 |
| + /// Each <pre>'s text, standing in the output as NUL, its number, NUL |
| + /// until the clean-up is done: its spaces and blank lines are the |
| + /// code's. |
| + var verbatim: [String] = [] |
| + |
| + mutating func markdown(_ tree: HTMLTree) -> String? { |
| + walk(tree, Style(), depth: -1) |
| + flush() |
| + guard formatted, mono * 2 <= chars else { return nil } |
| + let trimmed = out.components(separatedBy: "\n").map { line in |
| + var line = line |
| + while line.last == " " || line.last == "\t" { line.removeLast() } |
| + return line |
| + }.joined(separator: "\n") |
| + var result = trimmed.replacingOccurrences(of: #"\n{3,}"#, with: "\n\n", options: .regularExpression) |
| + while result.first == "\n" { result.removeFirst() } |
| + while result.last == "\n" { result.removeLast() } |
| + for (n, code) in verbatim.enumerated().reversed() { result = result.replacingOccurrences(of: "\0\(n)\0", with: code) } |
| + return result |
| + } |
| + |
| + mutating func flush() { |
| + var s = inline(runs) |
| + runs = [] |
| + while s.first == " " { s.removeFirst() } |
| + guard !s.isEmpty else { return } |
| + if open { out += s } else { |
| + out += (marker ?? indent) + s |
| + if marker != nil { formatted = true } |
| + } |
| + marker = nil |
| + open = true |
| + } |
| + |
| + mutating func ensure(_ n: Int) { |
| + flush() |
| + open = false |
| + guard !out.isEmpty else { return } |
| + var have = 0 |
| + for c in out.reversed() { if c == "\n" { have += 1 } else { break } } |
| + while have < n { out += "\n"; have += 1 } |
| + } |
| + |
| + mutating func walk(_ node: HTMLTree, _ st: Style, depth: Int) { |
| + if out.utf16.count > PasteMarkdown.maxOut { return } |
| + if node.tag.isEmpty { |
| + let counted = node.text.unicodeScalars.reduce(0) { $0 + ($1.properties.isWhitespace ? 0 : $1.utf16.count) } |
| + chars += counted |
| + if st.mono { mono += counted } |
| + var t = node.text.replacingOccurrences(of: "[ \\t\\n\\r\\f\u{00a0}]+", with: " ", options: .regularExpression) |
| + // One space between words, whichever side of a tag it was. |
| + if t.first == " ", runs.last?.text.last == " " { t.removeFirst() } |
| + if !t.isEmpty { runs.append(Run(text: t, bold: st.heading ? false : st.bold, italic: st.heading ? false : st.italic, href: st.href)) } |
| + return |
| + } |
| + let tag = node.tag |
| + if tag == "br" { |
| + flush() |
| + if !out.isEmpty { out += "\n"; open = false } |
| + return |
| + } |
| + // (The body is depth -1; its children 0. HTMLTree.parse never makes |
| + // anything deeper than the cap, and marks what it flattened.) |
| + if tag == Self.line { ensure(1); return } |
| + if tag == Self.cell { runs.append(Run(text: " ", bold: false, italic: false, href: "")); return } |
| + if Self.skip.contains(tag) { return } |
| + var next = st |
| + if tag == "b" || tag == "strong" { next.bold = true } |
| + if tag == "i" || tag == "em" { next.italic = true } |
| + if Self.code.contains(tag) { next.mono = true } |
| + let style = node.attributes["style"] ?? "" |
| + if let weight = Self.declared(style, "font-weight") { |
| + next.bold = weight.range(of: "^(bold|bolder|[6-9]00)$", options: [.regularExpression, .caseInsensitive]) != nil |
| + } |
| + if let slant = Self.declared(style, "font-style") { |
| + next.italic = slant.range(of: "^(italic|oblique)", options: [.regularExpression, .caseInsensitive]) != nil |
| + } |
| + if let family = Self.declared(style, "font-family") { |
| + next.mono = Self.monoFont.firstMatch(in: family, range: NSRange(family.startIndex..., in: family)) != nil |
| + } |
| + if tag == "a", st.href.isEmpty { next.href = Self.link(node.attributes["href"] ?? "") } |
| + func children(_ w: inout Walker) { for c in node.children { w.walk(c, next, depth: depth + 1) } } |
| + |
| + if tag.count == 2, tag.first == "h", let level = Int(String(tag.last!)), (1...6).contains(level) { |
| + ensure(2) |
| + marker = String(repeating: "#", count: level) + " " |
| + next.heading = true |
| + let before = formatted |
| + children(&self) |
| + flush() |
| + if marker != nil { marker = nil; formatted = before } |
| + ensure(2) |
| + return |
| + } |
| + if tag == "ul" || tag == "ol" { |
| + let top = lists.isEmpty |
| + let parent = lists.last |
| + ensure(top ? 2 : 1) |
| + let start = Int(node.attributes["start"]?.trimmingCharacters(in: .whitespaces) ?? "") |
| + lists.append(List(ordered: tag == "ol", n: tag == "ol" ? max(0, start ?? 1) : 0, indent: parent?.inner ?? indent)) |
| + let saved = indent |
| + children(&self) |
| + lists.removeLast() |
| + indent = saved |
| + ensure(top ? 2 : 1) |
| + return |
| + } |
| + if tag == "li" { |
| + ensure(1) |
| + let list = lists.last ?? List(ordered: false, n: 0, indent: "") |
| + let m = list.ordered ? "\(list.n). " : "- " |
| + if list.ordered { list.n += 1 } |
| + marker = list.indent + m |
| + list.inner = list.indent + String(repeating: " ", count: m.count) |
| + let saved = indent |
| + indent = list.inner |
| + children(&self) |
| + flush() |
| + marker = nil |
| + indent = saved |
| + ensure(1) |
| + return |
| + } |
| + if tag == "p" { |
| + if !lists.isEmpty { |
| + flush() |
| + if open { out += "\n"; open = false } |
| + children(&self) |
| + return |
| + } |
| + ensure(2); children(&self); ensure(2) |
| + return |
| + } |
| + if tag == "pre" { |
| + // Verbatim, as a fenced code block longer than any run of |
| + // backticks in it. |
| + var code = "" |
| + func read(_ n: HTMLTree) { |
| + if n.tag.isEmpty { code += n.text } else if n.tag == "br" { code += "\n" } else if !Self.skip.contains(n.tag) { n.children.forEach(read) } |
| + } |
| + read(node) |
| + code = code.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n") |
| + // A page drops the line break just after <pre>. |
| + if code.hasPrefix("\n") { code.removeFirst() } |
| + if code.hasSuffix("\n") { code.removeLast() } |
| + let counted = code.unicodeScalars.reduce(0) { $0 + ($1.properties.isWhitespace ? 0 : $1.utf16.count) } |
| + chars += counted |
| + mono += counted |
| + guard !code.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return } |
| + var longest = 0, run = 0 |
| + for c in code { run = c == "`" ? run + 1 : 0; longest = max(longest, run) } |
| + let fence = String(repeating: "`", count: max(3, longest + 1)) |
| + ensure(2) |
| + out += fence + "\n\0\(verbatim.count)\0\n" + fence |
| + verbatim.append(code) |
| + formatted = true |
| + ensure(2) |
| + return |
| + } |
| + if Self.lines.contains(tag) { |
| + ensure(1); children(&self); ensure(1) |
| + return |
| + } |
| + if tag == "td" || tag == "th" { |
| + children(&self) |
| + runs.append(Run(text: " ", bold: false, italic: false, href: "")) |
| + return |
| + } |
| + children(&self) |
| + } |
| + |
| + /// A line's runs as Markdown: neighbours alike are one run, and a run's |
| + /// outer spaces stand outside its marks. |
| + mutating func inline(_ rs: [Run]) -> String { |
| + var merged: [Run] = [] |
| + for r in rs { |
| + if let last = merged.last, last.href == r.href, !r.href.isEmpty || (last.bold == r.bold && last.italic == r.italic) { |
| + merged[merged.count - 1].text += r.text |
| + } else { |
| + merged.append(r) |
| + } |
| + } |
| + var s = "" |
| + for r in merged { |
| + let lead = String(r.text.prefix { $0 == " " }) |
| + let rest = r.text.dropFirst(lead.count) |
| + let trail = String(rest.reversed().prefix { $0 == " " }) |
| + let core = String(rest.dropLast(trail.count)) |
| + if core.isEmpty { s += r.text; continue } |
| + if !r.href.isEmpty { |
| + let label = core.replacingOccurrences(of: "[", with: "").replacingOccurrences(of: "]", with: "") |
| + let href = r.href.replacingOccurrences(of: "(", with: "%28").replacingOccurrences(of: ")", with: "%29") |
| + s += lead + (label == r.href ? href : label.utf16.count > 300 ? "\(label) (\(href))" : "[\(label)](\(href))") + trail |
| + formatted = true |
| + } else if r.bold || r.italic { |
| + let mark = r.bold ? "**" : "*" |
| + s += lead + mark + core + mark + trail |
| + formatted = true |
| + } else { |
| + s += r.text |
| + } |
| + } |
| + while s.last == " " { s.removeLast() } |
| + return s |
| + } |
| + |
| + /// A declaration's value in a style attribute (never |
| + /// mso-bidi-font-weight and the like). |
| + static func declared(_ style: String, _ name: String) -> String? { |
| + guard let re = try? NSRegularExpression(pattern: "(?:^|;)\\s*\(name)\\s*:\\s*([^;]*)", options: .caseInsensitive), |
| + let m = re.firstMatch(in: style, range: NSRange(style.startIndex..., in: style)), |
| + let r = Range(m.range(at: 1), in: style) else { return nil } |
| + return style[r].replacingOccurrences(of: #"!\s*important\s*$"#, with: "", options: [.regularExpression, .caseInsensitive]).trimmingCharacters(in: .whitespaces) |
| + } |
| + |
| + /// An href as a page reads it (spaces at its ends go, tabs and line |
| + /// breaks in it go, other spaces are escaped), if it is http(s). |
| + static func link(_ href: String) -> String { |
| + let cleaned = href.trimmingCharacters(in: .whitespacesAndNewlines).filter { $0 != "\t" && $0 != "\n" && $0 != "\r" } |
| + guard let url = URL(string: cleaned, encodingInvalidCharacters: true) else { return "" } |
| + return BaseJSON.webURL(url.absoluteString)?.absoluteString ?? "" |
| + } |
| +} |
diff --git a/native/apple/Sources/BaseKit/Ask/Thread.swift b/native/apple/Sources/BaseKit/Ask/Thread.swift| index 0c6fcd3..4d8d9d1 100644 |
| --- a/native/apple/Sources/BaseKit/Ask/Thread.swift |
| +++ b/native/apple/Sources/BaseKit/Ask/Thread.swift |
| @@ -87,7 +87,11 @@ struct AskThread: View { |
| switch entry { |
| case .message(let m): |
| Bubble(person: m.isPerson, maxWidth: bubbleWidth) { |
| - if m.isPerson { |
| + // The person's own words take the web's little Markdown |
| + // (PersonMarkdown); with none, they are exactly as written. |
| + if m.isPerson, case let nodes = PersonMarkdown.parse(m.text), !PersonMarkdown.isPlain(nodes) { |
| + BaseMarkdownView(person: nodes, id: m.id, transcript: transcript) |
| + } else if m.isPerson { |
| Text(verbatim: m.text).font(BaseFont.body(15)).fixedSize(horizontal: false, vertical: true) |
| } else { |
| BaseMarkdownView(m.text, draft: false, id: m.id, transcript: transcript) |
diff --git a/native/apple/Sources/BaseKit/Look/Type.swift b/native/apple/Sources/BaseKit/Look/Type.swift| index c97d903..c37c162 100644 |
| --- a/native/apple/Sources/BaseKit/Look/Type.swift |
| +++ b/native/apple/Sources/BaseKit/Look/Type.swift |
| @@ -55,9 +55,12 @@ public enum BaseFonts { |
| /// The PostScript name of a named instance: Timeless Sans's cuts and |
| /// weights, or DM Sans's. |
| - static func postScriptName(grotesk: Bool, weight: BaseFont.Weight, face: Face) -> String? { |
| + static func postScriptName(grotesk: Bool, weight: BaseFont.Weight, face: Face, italic: Bool = false) -> String? { |
| switch face { |
| - case .timeless: return "TimelessSans-\(grotesk ? "Grotesk" : "Sans")\(weight.timeless)" |
| + // Timeless Sans's italics are named instances on its ital axis |
| + // (TimelessSans-SansRegularItalic and its siblings); none carries |
| + // the italic trait, so SwiftUI's own italic never finds them. |
| + case .timeless: return "TimelessSans-\(grotesk ? "Grotesk" : "Sans")\(weight.timeless)\(italic ? "Italic" : "")" |
| case .dmSans: return "DMSans-9ptRegular_\(weight.dmSans)" |
| case .system: return nil |
| } |
| @@ -85,15 +88,20 @@ public enum BaseFont { |
| font(size, weight, grotesk: true, style) |
| } |
| - /// The Sans cut: everything else. |
| - public static func body(_ size: CGFloat, _ weight: Weight = .regular, relativeTo style: Font.TextStyle = .body) -> Font { |
| - font(size, weight, grotesk: false, style) |
| + /// The Sans cut: everything else. `italic`: Timeless Sans's own |
| + /// italic instance; DM Sans, which has none bundled, and the system |
| + /// face slant as SwiftUI's italic does. |
| + public static func body(_ size: CGFloat, _ weight: Weight = .regular, italic: Bool = false, relativeTo style: Font.TextStyle = .body) -> Font { |
| + font(size, weight, grotesk: false, style, italic: italic) |
| } |
| - static func font(_ size: CGFloat, _ weight: Weight, grotesk: Bool, _ style: Font.TextStyle) -> Font { |
| - guard let name = BaseFonts.postScriptName(grotesk: grotesk, weight: weight, face: BaseFonts.face) else { |
| - return .system(size: size, weight: weight.system) |
| + static func font(_ size: CGFloat, _ weight: Weight, grotesk: Bool, _ style: Font.TextStyle, italic: Bool = false) -> Font { |
| + let face = BaseFonts.face |
| + guard let name = BaseFonts.postScriptName(grotesk: grotesk, weight: weight, face: face, italic: italic) else { |
| + let system = Font.system(size: size, weight: weight.system) |
| + return italic ? system.italic() : system |
| } |
| - return .custom(name, size: size, relativeTo: style) |
| + let font = Font.custom(name, size: size, relativeTo: style) |
| + return italic && face != .timeless ? font.italic() : font |
| } |
| } |
diff --git a/native/apple/Tests/BaseKitTests/AskViewTests.swift b/native/apple/Tests/BaseKitTests/AskViewTests.swift| index 6acfb8e..b061b0b 100644 |
| --- a/native/apple/Tests/BaseKitTests/AskViewTests.swift |
| +++ b/native/apple/Tests/BaseKitTests/AskViewTests.swift |
| @@ -76,3 +76,51 @@ extension AskViewTests { |
| } |
| } |
| } |
| + |
| +extension AskViewTests { |
| + /// The person's messages take the web's little Markdown (2026-11-26); |
| + /// words with none are drawn exactly as written (Fable's S4). |
| + func testThePersonsPlainWordsStayPlain() { |
| + for plain in ["What's on tomorrow?", "2*3 and a_b_c", "2*3*4", "a*b + c*d", "x**2 + y**2", "__init__.py", "f(*args) and g(*rest)", |
| + "Two lines\nhere", "# Not a heading", "> not a quote", "Gap\n\nbetween", " indented", "1986. A great year", "+ item", "AT&T \\*x"] { |
| + XCTAssertTrue(PersonMarkdown.isPlain(PersonMarkdown.parse(plain)), plain) |
| + } |
| + for rich in ["**Bold**", "*it*", "_it_", "- a\n- b", "1. One", "[Menu](https://fennel.example/menu)", "https://fennel.example/menu"] { |
| + XCTAssertFalse(PersonMarkdown.isPlain(PersonMarkdown.parse(rich)), rich) |
| + } |
| + } |
| + |
| + /// The web's server draws each of these (TestPersonText); the app's |
| + /// tree, written out the same way, must be the same. |
| + func testThePersonsMarkdownMatchesTheWeb() throws { |
| + struct Case: Decodable { let text: String; let html: String } |
| + let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() |
| + .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() |
| + let cases = try JSONDecoder().decode([Case].self, from: Data(contentsOf: root.appendingPathComponent("internal/web/testdata/person.json"))) |
| + XCTAssertGreaterThan(cases.count, 10) |
| + func escape(_ s: String) -> String { |
| + s.replacingOccurrences(of: "&", with: "&").replacingOccurrences(of: "<", with: "<").replacingOccurrences(of: ">", with: ">") |
| + .replacingOccurrences(of: "'", with: "'").replacingOccurrences(of: "\"", with: """) |
| + } |
| + func html(_ nodes: [ChatMarkdownNode]) -> String { |
| + nodes.map { n in |
| + switch n.kind { |
| + case "text": escape(n.text ?? "") |
| + case "strong": "<strong>\(html(n.children))</strong>" |
| + case "emphasis": "<em>\(html(n.children))</em>" |
| + case "link": "<a href=\"\(escape(n.target ?? ""))\" target=\"_blank\" rel=\"noopener\">\(html(n.children))</a>" |
| + case "unordered": "<ul>\(html(n.children))</ul>" |
| + case "ordered": (n.start.map { "<ol start=\"\($0)\">" } ?? "<ol>") + html(n.children) + "</ol>" |
| + case "item": "<li>\(html(n.children))</li>" |
| + default: html(n.children) |
| + } |
| + }.joined() |
| + } |
| + for c in cases { |
| + XCTAssertEqual(html(PersonMarkdown.parse(c.text)), c.html, c.text) |
| + } |
| + // A numbered list counts from its first number, the Assistant's too. |
| + XCTAssertEqual(MarkdownPresentation.rows(PersonMarkdown.parse("3. Third\n4. Fourth")).map(\.marker), ["3.", "4."]) |
| + XCTAssertEqual(MarkdownPresentation.rows(ChatMarkdown.parse("3. Third\n4. Fourth", draft: false)).map(\.marker), ["3.", "4."]) |
| + } |
| +} |
diff --git a/native/apple/Tests/BaseKitTests/ComposerTests.swift b/native/apple/Tests/BaseKitTests/ComposerTests.swift| index 220d46e..1bc8228 100644 |
| --- a/native/apple/Tests/BaseKitTests/ComposerTests.swift |
| +++ b/native/apple/Tests/BaseKitTests/ComposerTests.swift |
| @@ -127,6 +127,99 @@ import AppKit |
| } |
| extension ComposerKeyTests { |
| + /// The menu's Paste (or Paste and Match Style) as AppKit sends it: |
| + /// the item's will- and did-send around the field reading `board`. |
| + private func paste(from board: NSPasteboard, action: Selector = #selector(NSText.paste(_:))) throws { |
| + let editor = try XCTUnwrap(editor) |
| + let item = NSMenuItem(title: "Paste", action: action, keyEquivalent: "v") |
| + let menu = NSMenu(title: "Edit") |
| + menu.addItem(item) |
| + NotificationCenter.default.post(name: NSMenu.willSendActionNotification, object: menu, userInfo: ["MenuItem": item]) |
| + XCTAssertTrue(editor.readSelection(from: board)) |
| + NotificationCenter.default.post(name: NSMenu.didSendActionNotification, object: menu, userInfo: ["MenuItem": item]) |
| + settle() |
| + } |
| + |
| + private func richBoard() -> NSPasteboard { |
| + let board = NSPasteboard(name: .init("BaseKitTests.\(UUID().uuidString)")) |
| + board.clearContents() |
| + board.setString("<p>The <b>flour</b> comes <i>Thursday</i>:</p><ul><li>Rye</li><li><a href=\"https://fennel.example/order\">The order</a></li></ul>", forType: .html) |
| + board.setString("The flour comes Thursday:\nRye\nThe order", forType: .string) |
| + return board |
| + } |
| + |
| + /// A rich paste comes in as Markdown at the cursor (2026-11-26), and |
| + /// one Undo takes it all back, in the model too (S1); a plain one is |
| + /// pasted as it is. A pasteboard of the test's own, never the person's. |
| + func testARichPasteIsMarkdown() throws { |
| + let board = richBoard() |
| + defer { board.releaseGlobally(); ComposerInput.pasteboard = .general } |
| + ComposerInput.pasteboard = board |
| + try type("Note: ") |
| + try paste(from: board) |
| + XCTAssertEqual(model.text, "Note: The **flour** comes *Thursday*:\n\n- Rye\n- [The order](https://fennel.example/order)") |
| + XCTAssertEqual(editor?.selectedRange().location, (model.text as NSString).length, "the cursor after the paste") |
| + XCTAssertFalse(sent) |
| + editor?.undoManager?.undo() |
| + settle() |
| + XCTAssertEqual(model.text, "Note: ", "one Undo takes the paste back") |
| + editor?.undoManager?.redo() |
| + settle() |
| + XCTAssertTrue(model.text.contains("**flour**"), "and Redo brings it back") |
| + editor?.undoManager?.undo() |
| + settle() |
| + try press() |
| + XCTAssertEqual(sentText, "Note:", "Return after Undo sends what the field shows") |
| + } |
| + |
| + func testAPlainPasteIsAsCopied() throws { |
| + let board = NSPasteboard(name: .init("BaseKitTests.\(UUID().uuidString)")) |
| + defer { board.releaseGlobally(); ComposerInput.pasteboard = .general } |
| + ComposerInput.pasteboard = board |
| + board.clearContents() |
| + board.setString("plain *as* copied", forType: .string) |
| + try type("Note: ") |
| + try paste(from: board) |
| + XCTAssertEqual(model.text, "Note: plain *as* copied") |
| + } |
| + |
| + /// Fable's N1: Paste and Match Style, and an insert that is no Paste |
| + /// (dictation, a drop, an input method's word) of the very same text, |
| + /// stay as they are. |
| + func testOnlyPasteIsConverted() throws { |
| + let board = richBoard() |
| + defer { board.releaseGlobally(); ComposerInput.pasteboard = .general } |
| + ComposerInput.pasteboard = board |
| + try type("") |
| + try paste(from: board, action: #selector(NSTextView.pasteAsPlainText(_:))) |
| + XCTAssertEqual(model.text, "The flour comes Thursday:\nRye\nThe order", "Paste and Match Style") |
| + let editor = try XCTUnwrap(editor) |
| + editor.insertText("\nThe flour comes Thursday:\nRye\nThe order", replacementRange: editor.selectedRange()) |
| + settle() |
| + XCTAssertFalse(model.text.contains("**"), model.text) |
| + } |
| + |
| + /// The Paste key is the Edit menu's: it sends the item's will-send, |
| + /// which is what lets a paste be told from other inserts. |
| + func testThePasteKeyIsTheMenus() throws { |
| + final class Target: NSObject { var pasted = false; @objc func paste(_ sender: Any?) { pasted = true } } |
| + let target = Target() |
| + let item = NSMenuItem(title: "Paste", action: #selector(NSText.paste(_:)), keyEquivalent: "v") |
| + item.target = target |
| + let menu = NSMenu(title: "Edit") |
| + menu.addItem(item) |
| + var told: Selector? |
| + let watch = NotificationCenter.default.addObserver(forName: NSMenu.willSendActionNotification, object: menu, queue: nil) { note in |
| + told = (note.userInfo?["MenuItem"] as? NSMenuItem)?.action |
| + } |
| + defer { NotificationCenter.default.removeObserver(watch) } |
| + let key = try XCTUnwrap(NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: .command, timestamp: 0, windowNumber: window.windowNumber, |
| + context: nil, characters: "v", charactersIgnoringModifiers: "v", isARepeat: false, keyCode: 9)) |
| + XCTAssertTrue(menu.performKeyEquivalent(with: key)) |
| + XCTAssertTrue(target.pasted) |
| + XCTAssertEqual(told, #selector(NSText.paste(_:))) |
| + } |
| + |
| private var sentText: String? { |
| transport.bodies("/ask/messages").last.flatMap { $0 }.flatMap { URLComponents(string: "?" + String(decoding: $0, as: UTF8.self))?.queryItems?.first { $0.name == "text" }?.value } |
| } |
diff --git a/native/apple/Tests/BaseKitTests/PasteMarkdownTests.swift b/native/apple/Tests/BaseKitTests/PasteMarkdownTests.swift| new file mode 100644 |
| index 0000000..7a9446d |
| --- /dev/null |
| +++ b/native/apple/Tests/BaseKitTests/PasteMarkdownTests.swift |
| @@ -0,0 +1,100 @@ |
| +@testable import BaseKit |
| +import Foundation |
| +import XCTest |
| +#if os(macOS) |
| +import AppKit |
| +#elseif os(iOS) |
| +import UIKit |
| +#endif |
| + |
| +/// A rich paste becomes the chat's Markdown (Paul, 2026-11-26). The HTML |
| +/// samples are the web's too (internal/browsertest/testdata/paste.json, |
| +/// TestAskPasteMarkdown): both converters must agree on every one. |
| +final class PasteMarkdownTests: XCTestCase { |
| + struct Sample: Decodable { let name: String; let html: String?; let rtf: String?; let markdown: String? } |
| + |
| + func testTheSharedSamples() throws { |
| + let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() |
| + .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() |
| + let data = try Data(contentsOf: root.appendingPathComponent("internal/browsertest/testdata/paste.json")) |
| + let samples = try JSONDecoder().decode([Sample].self, from: data) |
| + XCTAssertGreaterThan(samples.count, 5) |
| + for sample in samples { |
| + if let html = sample.html { XCTAssertEqual(PasteMarkdown.fromHTML(html), sample.markdown, sample.name) } |
| + if let rtf = sample.rtf { XCTAssertEqual(PasteMarkdown.fromRTF(Data(rtf.utf8)), sample.markdown, sample.name) } |
| + } |
| + } |
| + |
| + /// Fable's S5: a hostile clipboard (a page's copy handler can put any |
| + /// HTML there) never crashes or stalls the paste, even on the iPhone's |
| + /// 512 KB item-provider thread: nesting is flattened past 32 levels |
| + /// and the walk stops at the field's 16,000 characters. |
| + func testHostileClipboardsOnASmallStack() { |
| + func onSmallStack(_ work: @escaping @Sendable () -> Void) { |
| + let done = DispatchSemaphore(value: 0) |
| + let thread = Thread { work(); done.signal() } |
| + thread.stackSize = 512 * 1024 |
| + thread.start() |
| + XCTAssertEqual(done.wait(timeout: .now() + 20), .success, "the paste stalled") |
| + } |
| + onSmallStack { |
| + let deep = String(repeating: "<div><b>", count: 100_000) + "deep" + String(repeating: "</b></div>", count: 100_000) |
| + XCTAssertEqual(PasteMarkdown.fromHTML(deep), "**deep**") |
| + } |
| + onSmallStack { |
| + let lists = String(repeating: "<ul><li>item", count: 2_000) |
| + let out = PasteMarkdown.fromHTML(lists) ?? "" |
| + XCTAssertTrue(out.hasPrefix("- item\n - item"), String(out.prefix(40))) |
| + XCTAssertLessThan(out.utf16.count, 16_000 + 200, "bounded") |
| + } |
| + onSmallStack { |
| + let start = Date() |
| + let stray = String(repeating: "<b>", count: 20_000) + "x" + String(repeating: "</i>", count: 20_000) |
| + XCTAssertEqual(PasteMarkdown.fromHTML(stray), "**x**") |
| + XCTAssertLessThan(Date().timeIntervalSince(start), 2) |
| + } |
| + let huge = "<b>x</b>" + String(repeating: "y", count: PasteMarkdown.maxHTML) |
| + XCTAssertNil(PasteMarkdown.fromHTML(huge), "over 2 MB of HTML is pasted plain") |
| + } |
| + |
| + func testPlainHTMLIsLeftAlone() { |
| + XCTAssertNil(PasteMarkdown.fromHTML("<p>Just words, 2*3 and *stars*</p><p>Two lines</p>")) |
| + XCTAssertNil(PasteMarkdown.fromHTML("")) |
| + XCTAssertNil(PasteMarkdown.fromHTML("<b style=\"font-weight:normal\">not bold</b>")) |
| + } |
| + |
| + /// RTF (Mail, TextEdit, Notes, Safari): bold and italic faces, links, |
| + /// and text lists. |
| + func testRTF() throws { |
| + #if os(macOS) |
| + let body = NSFont(name: "Helvetica", size: 13)! |
| + let bold = NSFontManager.shared.convert(body, toHaveTrait: .boldFontMask) |
| + let italic = NSFontManager.shared.convert(body, toHaveTrait: .italicFontMask) |
| + #else |
| + let body = UIFont(name: "Helvetica", size: 13)! |
| + let bold = UIFont(descriptor: body.fontDescriptor.withSymbolicTraits(.traitBold)!, size: 13) |
| + let italic = UIFont(descriptor: body.fontDescriptor.withSymbolicTraits(.traitItalic)!, size: 13) |
| + #endif |
| + let text = NSMutableAttributedString() |
| + func add(_ s: String, _ font: Any = body, link: String? = nil, list: NSTextList? = nil) { |
| + var attributes: [NSAttributedString.Key: Any] = [.font: font] |
| + if let link { attributes[.link] = URL(string: link)! } |
| + if let list { |
| + let style = NSMutableParagraphStyle() |
| + style.textLists = [list] |
| + attributes[.paragraphStyle] = style |
| + } |
| + text.append(NSAttributedString(string: s, attributes: attributes)) |
| + } |
| + add("The "); add("flour", bold); add(" comes "); add("Thursday", italic); add(", see "); add("the order", link: "https://fennel.example/order"); add(".\n") |
| + add("\n") |
| + let bullets = NSTextList(markerFormat: .disc, options: 0) |
| + add("\t•\tRye\n", list: bullets) |
| + add("\t•\tSpelt\n", list: bullets) |
| + add("Thanks") |
| + let rtf = try text.data(from: NSRange(location: 0, length: text.length), documentAttributes: [.documentType: NSAttributedString.DocumentType.rtf]) |
| + XCTAssertEqual(PasteMarkdown.fromRTF(rtf), "The **flour** comes *Thursday*, see [the order](https://fennel.example/order).\n\n- Rye\n- Spelt\n\nThanks") |
| + XCTAssertNil(PasteMarkdown.fromRTF(try NSAttributedString(string: "Plain\nlines", attributes: [.font: body]) |
| + .data(from: NSRange(location: 0, length: 11), documentAttributes: [.documentType: NSAttributedString.DocumentType.rtf]))) |
| + } |
| +} |
diff --git a/native/apple/Tests/BaseKitTests/TypeTests.swift b/native/apple/Tests/BaseKitTests/TypeTests.swift| index 3fdf35a..538f63b 100644 |
| --- a/native/apple/Tests/BaseKitTests/TypeTests.swift |
| +++ b/native/apple/Tests/BaseKitTests/TypeTests.swift |
| @@ -30,6 +30,9 @@ final class TypeTests: XCTestCase { |
| XCTAssertEqual(CTFontCopyFamilyName(font) as String, "Timeless Sans") |
| // Grotesk is STYL 0, Sans STYL 100 (app.css's font-variation-settings). |
| if let value = axis(name, styl) { XCTAssertEqual(value, grotesk ? 0 : 100, name) } |
| + // Fable's N4: each has its italic, by name. |
| + let italic = try XCTUnwrap(BaseFonts.postScriptName(grotesk: grotesk, weight: weight, face: .timeless, italic: true)) |
| + XCTAssertEqual(CTFontCopyPostScriptName(CTFontCreateWithName(italic as CFString, 16, nil)) as String, italic, "\(italic) does not resolve") |
| } |
| } |
| } |
diff --git a/native/apple/Tests/BaseSnapshots/AskSnapshots.swift b/native/apple/Tests/BaseSnapshots/AskSnapshots.swift| index cedbd47..365d5f2 100644 |
| --- a/native/apple/Tests/BaseSnapshots/AskSnapshots.swift |
| +++ b/native/apple/Tests/BaseSnapshots/AskSnapshots.swift |
| @@ -47,6 +47,12 @@ final class AskSnapshots: XCTestCase { |
| JobView(job: AskFixtures.pausedJob, timeZone: AskFixtures.zone, close: {}, now: SnapshotSettings.now, |
| carryOnError: BaseText.text("ask.not_sent")) |
| }, |
| + // The person's own words in the Assistant's little Markdown |
| + // (2026-11-26): bold, italics, a list with a link, lines kept; |
| + // and a plain message, exactly as written. |
| + SnapshotScreen("person-markdown", mac: .fixed(width: 640, height: 520), iphone: .fixed(width: 402, height: 620)) { |
| + AskFrame { AskView(model: AskFixtures.personMarkdown(), layout: frameLayout, timeZone: AskFixtures.zone, actions: AskActions {}) } |
| + }, |
| SnapshotScreen("norunner", mac: .fixed(width: 640, height: 420), iphone: .fixed(width: 402, height: 520)) { |
| AskFrame { AskView(model: AskFixtures.model(state: "norunner", extra: AskFixtures.shortThread), layout: frameLayout, timeZone: AskFixtures.zone, actions: AskActions {}) } |
| }, |
| @@ -149,6 +155,14 @@ struct AskFrame<Content: View>: View { |
| return m |
| } |
| + static func personMarkdown() -> AskModel { |
| + model(state: "ready", extra: #""" |
| + {"id":"m1","role":"person","text":"**Christmas menu** for the bakery, *draft two*:\n- Mince pies, [see the recipe](https://fennel.example/menu/pies)\n- **Stollen**\n\nAna signs it off\non Friday.","turn_id":"t1"}, |
| + {"id":"m2","role":"assistant","text":"Got it. I'll add **both** to the *Christmas* menu.","turn_id":"t1"}, |
| + {"id":"m3","role":"person","text":"Two lines,\n2*3 and a_b_c stay as typed.","turn_id":"t2"} |
| + """#) |
| + } |
| + |
| /// A paused job that offers Carry on now, a stopped one and one working. |
| static func paused() -> AskModel { |
| let m = model(state: "ready", extra: #"{"id":"m1","role":"person","text":"Can you put together a simple website for the bakery?","turn_id":"t1"}"#) |
diff --git a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/person-markdown-dark-ax3.png b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/person-markdown-dark-ax3.png| new file mode 100644 |
| index 0000000..c7dcefc |
| Binary files /dev/null and b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/person-markdown-dark-ax3.png differ |
diff --git a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/person-markdown-dark-default.png b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/person-markdown-dark-default.png| new file mode 100644 |
| index 0000000..457261b |
| Binary files /dev/null and b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/person-markdown-dark-default.png differ |
diff --git a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/person-markdown-light-ax3.png b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/person-markdown-light-ax3.png| new file mode 100644 |
| index 0000000..d4868e1 |
| Binary files /dev/null and b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/person-markdown-light-ax3.png differ |
diff --git a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/person-markdown-light-default.png b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/person-markdown-light-default.png| new file mode 100644 |
| index 0000000..31b9ef1 |
| Binary files /dev/null and b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/person-markdown-light-default.png differ |
diff --git a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/mac/person-markdown-dark-default.png b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/mac/person-markdown-dark-default.png| new file mode 100644 |
| index 0000000..b3539c1 |
| Binary files /dev/null and b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/mac/person-markdown-dark-default.png differ |
diff --git a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/mac/person-markdown-light-default.png b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/mac/person-markdown-light-default.png| new file mode 100644 |
| index 0000000..60058eb |
| Binary files /dev/null and b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/mac/person-markdown-light-default.png differ |