Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(chat): copy only the selected Markdown fragment (#2429)

Call White03d91ab6b5af
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml
index 97da5efbb..6d6e9caaa 100644
--- a/.github/workflows/lint.yml
+++ b/.github/workflows/lint.yml
@@ -91,6 +91,7 @@ jobs:
npm run test:workbench-general -- sidebar-floating.spec.ts desktop-window-chrome.spec.ts
npm run test:voice-shortcut
npm run test:chat-interactions
+ npm run test:chat-selection
show-router-integration:
runs-on: ubuntu-latest
diff --git a/docs/plans/chat-selection-fragments.md b/docs/plans/chat-selection-fragments.md
new file mode 100644
index 000000000..dbe963a5c
--- /dev/null
+++ b/docs/plans/chat-selection-fragments.md
@@ -0,0 +1,100 @@
+# Range-bounded Markdown copy
+
+## Decision
+
+The selection toolbar must not silently widen Copy to whole paragraphs, lists,
+code blocks, tables, or bubbles. Selection extent takes priority over preserving
+formatting. This replaces the whole-block partial-copy policy from PR #2371.
+
+The user explicitly accepts dropping formatting cut by either selection edge;
+we must not complete wrappers or import surrounding text to make the fragment
+self-contained. Drop incomplete **formatting**, never selected content.
+
+For `Before **bold words** after`:
+
+| Selected visible content | Clipboard |
+| --- | --- |
+| `bold words` (entire emphasis content) | `**bold words**` |
+| `old wor` (inside emphasis) | `old wor` |
+| `words after` (starts inside emphasis) | `words after` |
+| `Before bold words` | `Before **bold words**` |
+
+## Invariants
+
+- No unselected visible text is copied. Touching every block is not equivalent
+ to selecting the whole bubble.
+- Preserve original Markdown for formatting constructs entirely covered by the
+ selection. If a construct is clipped, omit its own syntax and process only
+ its selected contents; a complete nested construct may retain its formatting.
+- Do not synthesize missing open/close delimiters, enclosing containers, or
+ unselected list items/table cells/code lines. Plain selected text is the safe
+ fallback for a clipped/unsupported construct.
+- Preserve selected whitespace, non-ASCII, emoji, and line breaks appropriately;
+ do not use rendered-text substring searches to guess source offsets.
+- Link labels partially selected remain just the selected label text; a complete
+ inline link may retain its Markdown destination. Do not append unselected
+ footnote bodies or other visible definition text to a partial selection.
+- A genuine full-bubble selection (including Select all) retains byte-exact full
+ Markdown source. Copy across bubbles takes only each selected fragment.
+- Images/rules completely selected retain their Markdown. Selection endpoints at
+ the next block/bubble's start must not pull that block/bubble into the copy.
+- Quote/Ask semantics and toolbar gesture/placement behavior remain unchanged.
+
+## Architecture direction
+
+Reuse the renderer/parser's existing source spans. Prefer a conservative tree
+walk: retain source for fully selected supported subtrees, recurse into clipped
+ones, and use only the selected text for clipped leaves. Do not reintroduce the
+old heuristic character alignment, indentation reconstruction, or arbitrary
+Markdown grammar repair that made PR #2371 repeatedly fail review. If the current
+marks cannot establish a safe mapping, improve the owning renderer annotation
+or fall back locally to plain selected text, not whole-block expansion.
+
+## Verification and scope
+
+- Rework the existing markdownSource table-driven tests around the new policy;
+ demonstrate the partial-selection regression fails on the old implementation.
+- Include formatting edges, nested inline formatting, links, CJK/emoji, escapes,
+ multiline selection, list/table/code slices, definitions, mention chips,
+ textless selections, multiple bubbles, and genuine whole-bubble byte identity.
+- Toolbar tests must consume the fragment through the real clipboard boundary.
+- Use hermetic browser validation for browser Range behavior that jsdom misses;
+ no production service restart or real user state/profile writes.
+- Ship independently from PR #2426 (notice layout and touchend handling), based
+ on default-branch interfaces. No stacking or cherry-picking that PR.
+
+## Implemented boundary
+
+`ui/src/lib/markdownSource.ts` walks the rendered DOM of each bubble the
+selection reaches, reading the `data-md-start` / `data-md-end` spans the
+renderer already writes. It adds no source-offset alignment and no Markdown
+repair:
+
+- An element whose whole content lies inside the selection copies its source
+ span, mapped back through the mention/secret rewrite passes. Content is every
+ character, whitespace included (code indentation is content), plus images,
+ rules and hard breaks; only renderer layout is excluded: blank text between
+ blocks, the newline after a hard break, and the newline ending a code block.
+ The bubble root is the first such element, which is what makes a
+ whole-bubble selection byte-exact.
+- Any other element is walked into. Its text copies as the selected DOM
+ characters, selected edge whitespace included, so an escape or entity in a
+ cut run copies as the character it shows. A hard break the selection holds
+ copies its own source (two trailing spaces or a backslash, then the
+ newline); a newline the renderer draws as a line break without a source span
+ (soft-break bubbles) copies as a plain newline.
+- Table rows and cells never copy their own span (a cell's span starts at its
+ pipe); cut cells are separated by a tab and rows by a line break. A whole
+ table copies its source.
+- Inside a cut quote or list item, a covered element whose source spans
+ several lines is walked into instead, because those lines carry the
+ container's `>` or indentation. Single-line sources still copy as written.
+- Parts from different blocks are joined by one line break or a blank line,
+ following the newline count written between the two blocks.
+- Renderer-only text outside every source construct (the footnote section's
+ label) and the blank layout text between blocks are never copied.
+- A covered reference link appends its `[id]: url` definition, which renders
+ nowhere. Footnote bodies are never appended.
+
+Browser Range behavior (double-click, triple-click, hit-tested drags, Select
+all) is covered by the hermetic `npm run test:chat-selection` harness.
diff --git a/ui/e2e/chat-selection/README.md b/ui/e2e/chat-selection/README.md
new file mode 100644
index 000000000..de43f4e17
--- /dev/null
+++ b/ui/e2e/chat-selection/README.md
@@ -0,0 +1,21 @@
+# Chat Selection Copy Regression
+
+Run `npm run test:chat-selection` from `ui/` after installing Chromium and WebKit
+with `npx playwright install --with-deps chromium webkit`.
+
+The fixture renders two transcript bubbles with the production `Markdown`
+renderer under the production `SelectionQuoteToolbar`, with real CSS and the
+shipped i18n bundles. No Avibe service is used, and the clipboard is a page-local
+recorder. Checks run on desktop Chromium and desktop WebKit.
+
+They cover the Ranges only a browser makes: a double-clicked word inside an
+emphasis or a code span, a triple-click that ends at the start of the next
+paragraph or list item, a drag resolved by hit-testing that starts inside an
+emphasis, a drag across two bubbles and the timestamp between them, and Select
+all. Each asserts what Copy writes: formatting the selection covers keeps its
+Markdown, formatting it cuts is dropped, and nothing unselected is copied.
+Screenshots and failure traces go under `e2e/.artifacts/chat-selection/`.
+
+The extraction rules themselves are covered table-driven in
+`src/lib/markdownSource.test.tsx`. Touch selection on native devices remains
+separate manual validation.
diff --git a/ui/e2e/chat-selection/chat-selection.spec.ts b/ui/e2e/chat-selection/chat-selection.spec.ts
new file mode 100644
index 000000000..aa425ab25
--- /dev/null
+++ b/ui/e2e/chat-selection/chat-selection.spec.ts
@@ -0,0 +1,103 @@
+import { expect, test, type Page } from '@playwright/test';
+import { copy } from '../support/copy';
+
+// What a browser has to answer that jsdom cannot: the Range a real double-click,
+// triple-click, or drag makes — word boundaries, a triple-click ending at the
+// start of the next block, a drag resolved by hit-testing — and what the toolbar
+// copies from it. The clipboard is a page-local recorder, so nothing reaches the
+// machine's real clipboard.
+const FIRST_BUBBLE = [
+ 'Before **bold words** after.',
+ '',
+ 'Second paragraph with `code`.',
+ '',
+ '- first item',
+ '- second item',
+].join('\n');
+
+test.beforeEach(async ({ page }) => {
+ await page.addInitScript(() => {
+ const written: string[] = [];
+ Object.assign(window, { __written: written });
+ Object.defineProperty(navigator, 'clipboard', {
+ configurable: true,
+ value: { writeText: async (text: string) => { written.push(text); } },
+ });
+ });
+ await page.goto('/e2e/chat-selection/fixture.html');
+});
+
+// A point inside the transcript text where the caret lands just before
+// `needle[at]` (or just after the needle when `at` is its length): a quarter
+// into the character it precedes, or three quarters into the one it follows.
+async function caret(page: Page, needle: string, at: number): Promise<{ x: number; y: number }> {
+ return page.evaluate(([needle, at]) => {
+ const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
+ const start = node.textContent!.indexOf(needle);
+ if (start < 0) continue;
+ const char = document.createRange();
+ const index = start + Math.min(at, needle.length - 1);
+ char.setStart(node, index);
+ char.setEnd(node, index + 1);
+ const rect = char.getBoundingClientRect();
+ const fraction = at < needle.length ? 0.25 : 0.75;
+ return { x: rect.left + rect.width * fraction, y: rect.top + rect.height / 2 };
+ }
+ throw new Error(`no text node holds ${needle}`);
+ }, [needle, at] as const);
+}
+
+async function copied(page: Page): Promise<string> {
+ await page.getByRole('button', { name: copy('chat.selection.copy'), exact: true }).click();
+ await expect.poll(() => page.evaluate(() => (window as unknown as { __written: string[] }).__written.length)).toBe(1);
+ return page.evaluate(() => (window as unknown as { __written: string[] }).__written[0]);
+}
+
+async function drag(page: Page, from: { x: number; y: number }, to: { x: number; y: number }) {
+ await page.mouse.move(from.x, from.y);
+ await page.mouse.down();
+ await page.mouse.move(to.x, to.y, { steps: 8 });
+ await page.mouse.up();
+}
+
+test('a double-clicked word inside an emphasis copies as the word alone', async ({ page }) => {
+ const { x, y } = await caret(page, 'words', 2);
+ await page.mouse.dblclick(x, y);
+ expect(await copied(page)).toBe('words');
+});
+
+test('a double-clicked code span copies as its Markdown', async ({ page }) => {
+ const { x, y } = await caret(page, 'code', 2);
+ await page.mouse.dblclick(x, y);
+ expect(await copied(page)).toBe('`code`');
+});
+
+test('a triple-clicked paragraph copies that paragraph and nothing after it', async ({ page }) => {
+ const { x, y } = await caret(page, 'Second paragraph', 3);
+ await page.mouse.click(x, y, { clickCount: 3 });
+ expect(await copied(page)).toBe('Second paragraph with `code`.');
+});
+
+test('a triple-clicked list item copies that item and not the next one', async ({ page }) => {
+ const { x, y } = await caret(page, 'first item', 3);
+ await page.mouse.click(x, y, { clickCount: 3 });
+ expect(await copied(page)).toBe('- first item');
+});
+
+test('a drag from inside an emphasis copies only the characters it crosses', async ({ page }) => {
+ await drag(page, await caret(page, 'bold', 1), await caret(page, 'after', 3));
+ expect(await copied(page)).toBe('old words aft');
+});
+
+test('a drag across bubbles copies each selected fragment and skips the timestamp', async ({ page }) => {
+ await drag(page, await caret(page, 'second item', 7), await caret(page, '加粗文字', 4));
+ expect(await copied(page)).toBe('item\n\n前面 **加粗文字**');
+});
+
+test('Select all copies the bubble byte for byte', async ({ page }) => {
+ const { x, y } = await caret(page, 'words', 2);
+ await page.mouse.dblclick(x, y);
+ await page.getByRole('button', { name: copy('chat.selection.selectAll'), exact: true }).click();
+ expect(await copied(page)).toBe(FIRST_BUBBLE);
+});
diff --git a/ui/e2e/chat-selection/fixture.html b/ui/e2e/chat-selection/fixture.html
new file mode 100644
index 000000000..cd41b7179
--- /dev/null
+++ b/ui/e2e/chat-selection/fixture.html
@@ -0,0 +1,12 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>Chat Selection Copy Regression</title>
+ </head>
+ <body>
+ <div id="root"></div>
+ <script type="module" src="./fixture.tsx"></script>
+ </body>
+</html>
diff --git a/ui/e2e/chat-selection/fixture.tsx b/ui/e2e/chat-selection/fixture.tsx
new file mode 100644
index 000000000..7494b8af2
--- /dev/null
+++ b/ui/e2e/chat-selection/fixture.tsx
@@ -0,0 +1,40 @@
+import { StrictMode, useRef } from 'react';
+import { createRoot } from 'react-dom/client';
+import { Markdown } from '../../src/components/ui/markdown';
+import { SelectionQuoteToolbar } from '../../src/components/workbench/SelectionQuoteToolbar';
+import '../../src/i18n';
+import '../../src/index.css';
+
+// Two transcript bubbles rendered by the production Markdown renderer under the
+// production selection toolbar, with a timestamp between them that is not
+// Markdown. What this fixture exists to check is the Range a real browser makes
+// for a double-click, a triple-click, or a drag, which jsdom cannot produce.
+const BUBBLES = [
+ [
+ 'Before **bold words** after.',
+ '',
+ 'Second paragraph with `code`.',
+ '',
+ '- first item',
+ '- second item',
+ ].join('\n'),
+ '前面 **加粗文字** 后面',
+];
+
+export function Fixture() {
+ const containerRef = useRef<HTMLDivElement>(null);
+ return (
+ <div ref={containerRef} className="min-h-dvh space-y-4 bg-background p-4 text-[15px] text-foreground">
+ <div className="max-w-xl rounded-2xl border border-border bg-surface p-3">
+ <Markdown content={BUBBLES[0]} />
+ </div>
+ <span className="text-muted">12:00</span>
+ <div className="max-w-xl rounded-2xl border border-border bg-surface p-3">
+ <Markdown content={BUBBLES[1]} />
+ </div>
+ <SelectionQuoteToolbar containerRef={containerRef} onQuote={() => undefined} />
+ </div>
+ );
+}
+
+createRoot(document.getElementById('root')!).render(<StrictMode><Fixture /></StrictMode>);
diff --git a/ui/e2e/chat-selection/tsconfig.json b/ui/e2e/chat-selection/tsconfig.json
new file mode 100644
index 000000000..d9bbc7a8b
--- /dev/null
+++ b/ui/e2e/chat-selection/tsconfig.json
@@ -0,0 +1,6 @@
+{
+ "extends": "../../tsconfig.app.json",
+ "compilerOptions": { "types": ["vite/client", "node"] },
+ "include": ["*.ts", "*.tsx", "../../playwright.chat-selection.config.ts", "../../agentation.d.ts"],
+ "exclude": []
+}
diff --git a/ui/package.json b/ui/package.json
index 49c2a6ccf..e32a349e8 100644
--- a/ui/package.json
+++ b/ui/package.json
@@ -22,6 +22,7 @@
"test:chat-interactions": "tsc -p e2e/chat-interactions/tsconfig.json --noEmit && playwright test --config playwright.chat-interactions.config.ts",
"test:chat-paging": "tsc -p e2e/chat-paging/tsconfig.json --noEmit && playwright test --config playwright.chat-paging.config.ts",
"test:citations": "tsc -p e2e/citations/tsconfig.json --noEmit && playwright test --config playwright.citations.config.ts",
+ "test:chat-selection": "tsc -p e2e/chat-selection/tsconfig.json --noEmit && playwright test --config playwright.chat-selection.config.ts",
"test:inbox-return": "tsc -p e2e/inbox-return/tsconfig.json --noEmit && playwright test --config playwright.inbox-return.config.ts",
"test:badge-triggers": "tsc -p e2e/badge-triggers/tsconfig.json --noEmit && playwright test --config playwright.badge-triggers.config.ts",
"test:project-order": "tsc -p e2e/project-order/tsconfig.json --noEmit && playwright test --config playwright.project-order.config.ts",
diff --git a/ui/playwright.chat-selection.config.ts b/ui/playwright.chat-selection.config.ts
new file mode 100644
index 000000000..a79b881aa
--- /dev/null
+++ b/ui/playwright.chat-selection.config.ts
@@ -0,0 +1,18 @@
+import { defineConfig, devices } from '@playwright/test';
+
+export default defineConfig({
+ testDir: './e2e/chat-selection',
+ outputDir: './e2e/.artifacts/chat-selection',
+ workers: 1,
+ retries: 0,
+ use: { baseURL: 'http://127.0.0.1:5219', locale: 'en-US', trace: 'retain-on-failure' },
+ webServer: {
+ command: 'npm run dev -- --host 127.0.0.1 --port 5219 --strictPort',
+ env: { VIBE_UI_BACKEND: 'http://127.0.0.1:9' },
+ url: 'http://127.0.0.1:5219/e2e/chat-selection/fixture.html',
+ },
+ projects: [
+ { name: 'desktop', use: { ...devices['Desktop Chrome'] } },
+ { name: 'desktop-webkit', use: { ...devices['Desktop Safari'] } },
+ ],
+});
diff --git a/ui/src/components/workbench/SelectionQuoteToolbar.test.tsx b/ui/src/components/workbench/SelectionQuoteToolbar.test.tsx
index 83f0788a8..7bb4e1819 100644
--- a/ui/src/components/workbench/SelectionQuoteToolbar.test.tsx
+++ b/ui/src/components/workbench/SelectionQuoteToolbar.test.tsx
@@ -198,6 +198,25 @@ describe('chat selection action gesture lifetime', () => {
expect(writeText).toHaveBeenCalledExactlyOnceWith(BUBBLE);
});
+ it('copies no more of a bubble than is selected', async () => {
+ const container = mountBubble();
+ const strong = container.querySelector('strong')!;
+ const range = document.createRange();
+ range.setStart(strong.firstChild!, 0);
+ range.setEnd(strong.nextSibling!, ' no'.length);
+ window.getSelection()!.addRange(range);
+ settle();
+
+ await act(async () => {
+ const button = screen.getByRole('button', { name: 'chat.selection.copy' });
+ fireEvent.pointerDown(button, press);
+ fireEvent.pointerUp(button, press);
+ await Promise.resolve();
+ });
+
+ expect(writeText).toHaveBeenCalledExactlyOnceWith('**bold** no');
+ });
+
it('offers Copy for an image alone, which has Markdown but no text', async () => {
const containerRef = createRef<HTMLDivElement>();
const image = '![chart](/api/media/abc123)';
diff --git a/ui/src/lib/markdownSource.test.tsx b/ui/src/lib/markdownSource.test.tsx
index a290d6af5..9d170e8b3 100644
--- a/ui/src/lib/markdownSource.test.tsx
+++ b/ui/src/lib/markdownSource.test.tsx
@@ -60,10 +60,14 @@ function renderDoc(content = DOC, references?: MentionReference[]) {
return container;
}
-const PARAGRAPH = 'Intro with **bold text** and a [link](https://example.com/a) here.';
-const LIST = '- first item\n- second `code` item';
+const BOLD = 'Before **bold words** after';
+const CJK = '前面 **加粗文字** 后面';
const CODE = '```ts\nconst a = 1;\nconst b = 2;\n```';
-const TABLE = '| key | val |\n|---|---|\n| x | yes |';
+const LIST = '- first item\n- second `code` item';
+const QUOTE = '> q1\n> q2\n>\n> p2\n\nafter';
+const TABLE = '| key | val |\n|---|---|\n| x | yes |\n| z | **w** |';
+const REFERENCE = '见[文档][docs]和[接口][api]。\n\n[docs]: https://example.com/docs\n[api]: https://example.com/api';
+const NOTE = 'A claim[^1] here.\n\n[^1]: First part.\n\n Second part.\n\nNext.';
describe('selectedMarkdown', () => {
it.each([
@@ -79,69 +83,100 @@ describe('selectedMarkdown', () => {
expect(selectedMarkdown(range, container)).toBe(content);
});
- it('copies the whole bubble once a selection touches every block of it', () => {
+ it('copies a whole bubble byte for byte once a selection reaches all it shows', () => {
const content = 'Only **one** paragraph.\n';
const container = renderDoc(content);
- expect(selectedMarkdown(rangeOver(container, ['one', 'before'], ['one', 'after']), container)).toBe(content);
- });
-
- // Each block a selection touches is copied whole, however little of it is selected.
- it.each<[string, Edge, Edge, string]>([
- ['a few words of a paragraph', ['bold', 'before'], ['and', 'after'], PARAGRAPH],
- ['two characters of a link', ['in', 'before'], ['in', 'after'], PARAGRAPH],
- ['a heading', ['Plan', 'before'], ['Plan', 'after'], '## Plan **now**'],
- ['one list item', ['second', 'before'], ['second', 'after'], LIST],
- ['a line of a code block', ['const b', 'before'], ['const b', 'after'], CODE],
- ['one table cell', ['yes', 'before'], ['yes', 'after'], TABLE],
- ['a paragraph and the list after it', ['here', 'before'], ['first', 'after'], `${PARAGRAPH}\n\n${LIST}`],
- ['a code block and the table after it', ['const a', 'before'], ['key', 'after'], `${CODE}\n\n${TABLE}`],
- ])('copies the blocks under %s', (_case, start, end, expected) => {
- const container = renderDoc();
- expect(selectedMarkdown(rangeOver(container, start, end), container)).toBe(expected);
- });
-
- it('brings along the definition of a reference in the copy', () => {
- const container = renderDoc();
- expect(selectedMarkdown(rangeOver(container, ['重点', 'before'], ['内容', 'after']), container))
- .toBe('这是**重点**内容。见[文档][docs]。\n\n[docs]: https://example.com/docs');
- });
-
- it('brings along definitions an appended definition needs', () => {
- const container = renderDoc('A claim[^1] here.\n\nNext.\n\n[^1]: See [docs][ref].\n\n[ref]: https://example.com/docs');
- expect(selectedMarkdown(rangeOver(container, ['claim', 'before'], ['here', 'after']), container))
- .toBe('A claim[^1] here.\n\n[^1]: See [docs][ref].\n\n[ref]: https://example.com/docs');
+ expect(selectedMarkdown(rangeOver(container, ['Only', 'before'], ['paragraph.', 'after']), container))
+ .toBe(content);
});
- it('copies a footnote definition selected in the rendered footnotes once', () => {
- // A two-paragraph footnote is one block, wherever it is written.
- const content = 'A claim[^1] here.\n\n[^1]: First part.\n\n Second part.\n\nNext.';
+ // A construct the selection covers keeps its Markdown; one it cuts through
+ // drops its own syntax and copies what is selected inside it. Nothing that
+ // was not selected is copied.
+ it.each<[string, string, Edge, Edge, string]>([
+ ['a whole emphasis', BOLD, ['bold words', 'before'], ['bold words', 'after'], '**bold words**'],
+ ['the inside of an emphasis', BOLD, ['old wor', 'before'], ['old wor', 'after'], 'old wor'],
+ ['text starting inside an emphasis', BOLD, ['words', 'before'], ['after', 'after'], 'words after'],
+ ['text ending after a whole emphasis', BOLD, ['Before', 'before'], ['words', 'after'], 'Before **bold words**'],
+ ['a whole CJK emphasis', CJK, ['加粗文字', 'before'], ['加粗文字', 'after'], '**加粗文字**'],
+ ['the inside of a CJK emphasis', CJK, ['粗文', 'before'], ['粗文', 'after'], '粗文'],
+ ['CJK text starting inside an emphasis', CJK, ['文字', 'before'], ['后面', 'after'], '文字 后面'],
+ ['an emphasis whole inside a cut one', '**bold *it* text** end', ['it', 'before'], ['text', 'after'], '*it* text'],
+ ['a cut emphasis around a whole one', '**bold *it* text** end', ['old', 'before'], ['it', 'after'], 'old *it*'],
+ ['a whole inline link', 'See [link](https://example.com/a) here.', ['See', 'before'], ['link', 'after'], 'See [link](https://example.com/a)'],
+ ['part of a link label', 'See [link](https://example.com/a) here.', ['in', 'before'], ['in', 'after'], 'in'],
+ ['a whole code span', 'Run `npm test` now.', ['npm test', 'before'], ['npm test', 'after'], '`npm test`'],
+ ['part of a code span', 'Run `npm test` now.', ['test', 'before'], ['now', 'after'], 'test now'],
+ // Text in a cut construct copies as it reads; a covered one keeps what was written.
+ ['escapes and entities in cut text', 'Keep \\*this\\* &amp; **that** too.', ['*this', 'before'], ['that', 'after'], '*this* & **that**'],
+ ['escapes and entities in a whole paragraph', 'Keep \\*this\\* &amp; that.\n\nNext.', ['Keep', 'before'], ['that.', 'after'], 'Keep \\*this\\* &amp; that.'],
+ // Every selected character copies, whitespace included; code whitespace is content.
+ ['the spaces selected around an emphasis', BOLD, [' ', 'before'], [' ', 'after', 2], ' **bold words** '],
+ ['a code line without its indentation', 'Intro\n\n```\n a\n```\n\nNext', ['a', 'before'], ['a', 'after'], 'a'],
+ ['the only code block without its indentation', '```\n a\n```', ['a', 'before'], ['a', 'after'], 'a'],
+ ['the only code block with its indentation', '```\n a\n```', [' a', 'before'], [' a', 'after'], '```\n a\n```'],
+ ['an indented code block line', ' x = 1\n y', [' y', 'before'], [' y', 'after'], ' y'],
+ // A hard break the selection holds keeps the source that makes it one.
+ ['a hard break', 'Prefix one \ntwo end', ['one', 'before'], ['two', 'after'], 'one \ntwo'],
+ ['a backslash hard break', 'Prefix one\\\ntwo end', ['one', 'before'], ['two', 'after'], 'one\\\ntwo'],
+ ['a hard break between emphases', 'Prefix **one** \n*two* end', ['one', 'before'], ['two', 'after'], '**one** \n*two*'],
+ ['the line before a hard break', 'Prefix one \ntwo end', ['one', 'before'], ['one', 'after'], 'one'],
+ ['the line after a hard break', 'Prefix one \ntwo end', ['two', 'before'], ['end', 'after'], 'two end'],
+ ['emoji and the whitespace between them', 'Grow 🌱 **green** 🌳 tall', ['🌱', 'before'], ['🌳', 'after'], '🌱 **green** 🌳'],
+ ['a soft line break', 'line one\nline **two** here', ['one', 'before'], ['two', 'after'], 'one\nline **two**'],
+ ['part of a heading', '## Plan **now**\n\nBody.', ['Plan', 'before'], ['Plan', 'after'], 'Plan'],
+ ['a whole heading and part of the paragraph after it', '## Plan **now**\n\nBody.', ['Plan', 'before'], ['Bo', 'after'], '## Plan **now**\n\nBo'],
+ ['a line of a code block', CODE, ['const b', 'before'], ['const b', 'after'], 'const b'],
+ ['the end of a code block and the paragraph after it', `${CODE}\n\nafter`, ['const b', 'before'], ['after', 'after'], 'const b = 2;\n\nafter'],
+ ['a whole code block and the paragraph after it', `${CODE}\n\nafter`, ['const a', 'before'], ['after', 'after'], `${CODE}\n\nafter`],
+ ['the end of one list item and the start of the next', LIST, ['item', 'before'], ['second', 'after'], 'item\nsecond'],
+ ['a whole list item and part of the next', LIST, ['first', 'before'], ['second', 'after'], '- first item\nsecond'],
+ ['the items of a nested list', '- top\n - inner one\n - inner two\n- next', ['inner one', 'before'], ['inner two', 'after'], '- inner one\n- inner two'],
+ ['a code block in a list item', '- step:\n ```sh\n npm i\n ```\n- next', ['npm', 'before'], ['next', 'after'], 'npm i\n- next'],
+ // A source over several lines of a quote carries the quote's `>` on each.
+ ['a multi-line paragraph of a quote', QUOTE, ['q1', 'before'], ['q2', 'after'], 'q1\nq2'],
+ ['two paragraphs of a quote', QUOTE, ['q2', 'before'], ['p2', 'after'], 'q2\n\np2'],
+ ['a whole quote', QUOTE, ['q1', 'before'], ['p2', 'after'], '> q1\n> q2\n>\n> p2'],
+ ['cells across table rows', TABLE, ['val', 'before'], ['w', 'after'], 'val\nx\tyes\nz\t**w**'],
+ ['a whole table and the paragraph after it', `Intro.\n\n${TABLE}\n\nend`, ['key', 'before'], ['end', 'after'], `${TABLE}\n\nend`],
+ // A covered reference link brings its definition, which renders nowhere.
+ ['a whole reference link', REFERENCE, ['文档', 'before'], ['文档', 'after'], '[文档][docs]\n\n[docs]: https://example.com/docs'],
+ ['two reference links', REFERENCE, ['文档', 'before'], ['接口', 'after'], '[文档][docs]和[接口][api]\n\n[docs]: https://example.com/docs\n[api]: https://example.com/api'],
+ ['part of a reference link label', REFERENCE, ['文', 'before'], ['文', 'after'], '文'],
+ // A footnote body is visible text of its own, so a reference never brings it.
+ ['a footnote reference', NOTE, ['claim', 'before'], ['here', 'after'], 'claim[^1] here'],
+ ['part of a footnote body', NOTE, ['First', 'before'], ['part', 'after'], 'First part'],
+ ['a paragraph and the footnotes rendered after it', NOTE, ['Next', 'before'], ['First', 'after'], 'Next.\n\nFirst'],
+ ])('copies only %s', (_case, content, start, end, expected) => {
const container = renderDoc(content);
- expect(selectedMarkdown(rangeOver(container, ['Next', 'before'], ['First', 'after']), container))
- .toBe('[^1]: First part.\n\n Second part.\n\nNext.');
+ expect(selectedMarkdown(rangeOver(container, start, end), container)).toBe(expected);
});
- it('leaves out a block written between two copied ones but not selected', () => {
- // The footnote is written mid-document but rendered after "Third".
- const container = renderDoc('First.\n\n[^1]: Note.\n\nSecond[^1].\n\nThird.');
- expect(selectedMarkdown(rangeOver(container, ['Third', 'before'], ['Note', 'after']), container))
- .toBe('[^1]: Note.\n\nThird.');
+ it('copies a line break of a bubble that renders every newline as one', () => {
+ const { container } = render(<Markdown content={'one\ntwo **three**\nfour'} softBreaks />);
+ expect(selectedMarkdown(rangeOver(container, ['two', 'before'], ['four', 'after']), container))
+ .toBe('two **three**\nfour');
});
- it('copies a mention chip as the marker that was typed', () => {
+ // A whole chip copies as the marker that was typed; part of one is part of its label.
+ it.each<[string, Edge, Edge, string]>([
+ ['a whole chip', ['#Release plan', 'before'], ['#Release plan', 'after'], '#<ses_1a2b>'],
+ ['text and a whole chip', ['or', 'before'], ['plan', 'after'], 'or see #<ses_1a2b>'],
+ ['part of a chip', ['lease', 'before'], ['pla', 'after'], 'lease pla'],
+ ])('copies %s', (_case, start, end, expected) => {
const content = 'ask @<claude> or see #<ses_1a2b>\n\nNext.';
const container = renderDoc(content, [
{ kind: 'agent', name: 'claude' },
{ kind: 'session', session_id: 'ses_1a2b', title: 'Release plan' },
]);
- expect(selectedMarkdown(rangeOver(container, ['lease', 'before'], ['pla', 'after']), container))
- .toBe('ask @<claude> or see #<ses_1a2b>');
+ expect(selectedMarkdown(rangeOver(container, start, end), container)).toBe(expected);
});
// An endpoint resting on an element's edge or in whitespace touches nothing there.
it.each<[string, string, Edge, (container: Element) => [Node, number], string]>([
- ['the next paragraph', 'Intro with **bold** here.\n\nNext para.', ['here', 'before'], (c) => [c.querySelectorAll('p')[1], 0], 'Intro with **bold** here.'],
- ['the next list item', '- alpha\n- beta\n\nAfter.', ['alpha', 'before'], (c) => [c.querySelectorAll('li')[1], 0], '- alpha\n- beta'],
- ['the paragraph after a code block', '```\nabc\n```\n\nafter\n\nend', ['bc', 'before'], (c) => [c.querySelectorAll('p')[0], 0], '```\nabc\n```'],
+ ['the next paragraph', 'Intro with **bold** here.\n\nNext para.', ['here', 'before'], (c) => [c.querySelectorAll('p')[1], 0], 'here.'],
+ ['the next list item', '- alpha\n- beta\n\nAfter.', ['alpha', 'before'], (c) => [c.querySelectorAll('li')[1], 0], '- alpha'],
+ ['the paragraph after a code block', '```\nabc\n```\n\nafter\n\nend', ['bc', 'before'], (c) => [c.querySelectorAll('p')[0], 0], 'bc'],
])('ends a selection before %s', (_case, content, start, end, expected) => {
const container = renderDoc(content);
const range = document.createRange();
@@ -151,7 +186,16 @@ describe('selectedMarkdown', () => {
expect(selectedMarkdown(range, container)).toBe(expected);
});
- // An image or a rule shows content without text, and selecting it touches its block.
+ it('starts a selection after the end of the paragraph before it', () => {
+ const container = renderDoc('First **one**.\n\nSecond para.');
+ const range = document.createRange();
+ range.setStart(...pointAt(container, ['.', 'after']));
+ range.setEnd(...pointAt(container, ['Second', 'after']));
+
+ expect(selectedMarkdown(range, container)).toBe('Second');
+ });
+
+ // An image or a rule shows content without text, and selecting it selects all of it.
it.each<[string, string, Edge, (container: Element) => [Node, number], string]>([
['an image block', 'Here:\n\n![chart](/api/media/abc123)\n\nNext para.', ['Here', 'before'], (c) => [c.querySelectorAll('p')[2], 0], 'Here:\n\n![chart](/api/media/abc123)'],
['a rule', 'Above\n\n---\n\nBelow', ['Above', 'before'], (c) => [c.querySelectorAll('p')[1], 0], 'Above\n\n---'],
@@ -164,7 +208,10 @@ describe('selectedMarkdown', () => {
expect(selectedMarkdown(range, container)).toBe(expected);
});
- it('copies each bubble a selection crosses, separated by a blank line', () => {
+ it.each<[string, Edge, string]>([
+ ['part of each bubble', ['bubble', 'before'], '**bubble** text\n\n- second'],
+ ['one bubble byte for byte and part of the next', ['Intro', 'before'], 'Intro.\n\nfirst **bubble** text\n\n- second'],
+ ])('copies %s a selection crosses, separated by a blank line', (_case, start, expected) => {
const { container } = render(
<>
<Markdown content={'Intro.\n\nfirst **bubble** text'} />
@@ -172,9 +219,9 @@ describe('selectedMarkdown', () => {
<Markdown content={'- second\n- bubble\n\nOutro.'} />
</>,
);
- const range = rangeOver(container, ['bubble', 'before'], ['second', 'after']);
+ const range = rangeOver(container, start, ['second', 'after']);
- expect(selectedMarkdown(range, container)).toBe('first **bubble** text\n\n- second\n- bubble');
+ expect(selectedMarkdown(range, container)).toBe(expected);
});
it('reports no Markdown for a selection outside every bubble', () => {
diff --git a/ui/src/lib/markdownSource.ts b/ui/src/lib/markdownSource.ts
index 959b6c4ef..94157cc70 100644
--- a/ui/src/lib/markdownSource.ts
+++ b/ui/src/lib/markdownSource.ts
@@ -1,31 +1,39 @@
import type { TextEdit } from '@/lib/citations';
-// Selection → the Markdown that was written.
+// Selection → the Markdown that was written, bounded by the selection.
//
// The transcript shows rendered Markdown, but a reader copying from it wants
-// the source the bubble was rendered from: `**b**`, not `b`. Copying works in
-// whole blocks, because a whole block is self-contained Markdown and a cut
-// through one is not (half a list item, half a table, half a link):
+// the source the bubble was rendered from: `**b**`, not `b`. A copy never
+// reaches past what was selected; where the two conflict, the selection wins
+// and formatting is what gets dropped. For `Before **bold words** after`:
//
-// - A selection that touches every block of a bubble copies the bubble's
-// source byte for byte. Select all does exactly that.
-// - Otherwise it copies the source of each top-level block it touches — a
-// paragraph, heading, list, quote, code block, table, rule or footnote — whole.
-// A selection inside one paragraph copies that paragraph.
-// - A reference-style link or footnote in the copy brings its definition along
-// when the definition is not in the copy itself.
+// - `bold words` covers the emphasis and copies `**bold words**`.
+// - `old wor` cuts through it and copies `old wor`; `words after` copies
+// `words after`. A cut construct drops its own syntax and copies what is
+// selected inside it, where whatever it holds whole keeps its own Markdown.
+// - A selection of everything in a bubble copies the bubble's source byte for
+// byte. Select all does exactly that.
+//
+// Text in a cut construct copies as it reads, whitespace included, so an
+// escape or an entity there copies as the character it shows. Whitespace is
+// content (code indentation especially): a construct is covered only when the
+// selection holds all of it. A hard break the selection holds keeps its source.
+// A construct whose source would carry its container's syntax onto later lines
+// (a quote's `>`, an item's indent) copies as a cut one unless that container
+// is selected whole too. A complete reference link brings along its
+// definition, which renders nowhere; a footnote's body is visible text and is
+// never brought along.
//
// The renderer marks every element with the source range it came from
// (`data-md-start` / `data-md-end`, UTF-16 offsets into the text ReactMarkdown
-// parsed), marks each reference with its definition's range, and binds each
-// rendered root to that text.
+// parsed), marks each reference link with its definition's range, and binds
+// each rendered root to that text.
const START = 'data-md-start';
const END = 'data-md-end';
const DEF_START = 'data-md-def-start';
const DEF_END = 'data-md-def-end';
const ROOT = 'data-md-root';
-const MARKED = `[${START}]`;
// What shows content without text.
const TEXTLESS = new Set(['IMG', 'HR']);
@@ -79,29 +87,21 @@ function eachNode<T extends { children?: T[] }>(node: T, visit: (node: T) => voi
node.children?.forEach((child) => eachNode(child, visit));
}
-/** Point each reference at the definition it needs, which renders nowhere near it. */
+/** Point each reference link at its definition, which renders nowhere. */
export function remarkDefinitionSpans() {
return (tree: unknown) => {
- const kind = (type?: string) => {
- if (type === 'definition' || type === 'linkReference' || type === 'imageReference') return 'link';
- if (type === 'footnoteDefinition' || type === 'footnoteReference') return 'note';
- return null;
- };
const definitions = new Map<string, [number, number]>();
eachNode(tree as MdastNode, (node) => {
const start = node.position?.start?.offset;
const end = node.position?.end?.offset;
- if (node.type !== 'definition' && node.type !== 'footnoteDefinition') return;
+ if (node.type !== 'definition') return;
if (typeof node.identifier !== 'string' || typeof start !== 'number' || typeof end !== 'number') return;
// The first definition of an identifier is the one a reference resolves to.
- const key = `${kind(node.type)}:${node.identifier}`;
- if (!definitions.has(key)) definitions.set(key, [start, end]);
+ if (!definitions.has(node.identifier)) definitions.set(node.identifier, [start, end]);
});
eachNode(tree as MdastNode, (node) => {
- if (node.type === 'definition' || node.type === 'footnoteDefinition') return;
- const type = kind(node.type);
- if (!type || typeof node.identifier !== 'string') return;
- const span = definitions.get(`${type}:${node.identifier}`);
+ if (node.type !== 'linkReference' && node.type !== 'imageReference') return;
+ const span = typeof node.identifier === 'string' ? definitions.get(node.identifier) : undefined;
if (!span) return;
const properties = ((node.data ??= {}).hProperties ??= {});
properties.dataMdDefStart = span[0];
@@ -138,6 +138,68 @@ export function sourceSpanProps(node: unknown): Record<string, number> {
const spanStart = (el: Element) => Number(el.getAttribute(START));
const spanEnd = (el: Element) => Number(el.getAttribute(END));
+// Elements laid out as blocks. A copy separates the parts of two blocks itself;
+// the blank text the renderer puts between them is only its line layout.
+const BLOCKS = new Set([
+ 'P', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'UL', 'OL', 'LI', 'BLOCKQUOTE', 'PRE', 'DIV', 'HR',
+ 'TABLE', 'THEAD', 'TBODY', 'TR', 'TH', 'TD', 'SECTION',
+]);
+// A table's parts are not Markdown without the table: a cell's range starts at its pipe.
+const TABLE_PARTS = new Set(['THEAD', 'TBODY', 'TR', 'TH', 'TD']);
+const CELLS = new Set(['TH', 'TD']);
+// Containers that repeat their syntax on every line they hold: a quote's `>`, an item's indent.
+const LINE_PREFIXED = new Set(['BLOCKQUOTE', 'LI']);
+
+const isBlock = (node: Node | null) => node?.nodeType === Node.ELEMENT_NODE && BLOCKS.has((node as Element).tagName);
+const isMarkedBreak = (node: Node | null) => node?.nodeType === Node.ELEMENT_NODE
+ && (node as Element).tagName === 'BR' && (node as Element).hasAttribute(START);
+
+// How much of a text node is content. Every character is, whitespace included,
+// except what the renderer adds for layout: blank text between blocks, the
+// newline after a hard break (whose own source holds it), and the newline that
+// ends a code block.
+function contentLength(text: Text): number {
+ if (text.data.trim() === '' && isBlock(text.parentNode)
+ && (!text.previousSibling || isBlock(text.previousSibling))
+ && (!text.nextSibling || isBlock(text.nextSibling))) return 0;
+ if (text.data === '\n' && isMarkedBreak(text.previousSibling)) return 0;
+ const code = text.parentElement;
+ const endsBlockCode = code?.tagName === 'CODE' && code.parentElement?.tagName === 'PRE'
+ && !text.nextSibling && text.data.endsWith('\n');
+ return text.data.length - (endsBlockCode ? 1 : 0);
+}
+
+type Point = [Node, number];
+const before = (node: Node): Point => [node.parentNode!, Array.prototype.indexOf.call(node.parentNode!.childNodes, node)];
+const after = (node: Node): Point => [node.parentNode!, before(node)[1] + 1];
+
+// Where what `el` shows begins and ends: its first and last character of
+// content, image or rule. A hard break shows a line break, and is all of itself.
+function contentBounds(el: Element): [Point, Point] | null {
+ if (isTextless(el) || isMarkedBreak(el)) return [before(el), after(el)];
+ let first: Point | null = null;
+ let last: Point | null = null;
+ const walker = el.ownerDocument.createTreeWalker(el, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT);
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
+ if (node.nodeType === Node.TEXT_NODE) {
+ const length = contentLength(node as Text);
+ if (!length) continue;
+ first ??= [node, 0];
+ last = [node, length];
+ } else if (isTextless(node)) {
+ first ??= before(node);
+ last = after(node);
+ }
+ }
+ return first && last ? [first, last] : null;
+}
+
+// Whether `range` selects everything `el` shows.
+function covers(range: Range, el: Element): boolean {
+ const bounds = contentBounds(el);
+ return !!bounds && bounds.every(([node, offset]) => range.comparePoint(node, offset) === 0);
+}
+
// The selection narrowed to what it selects: characters, images and rules. An
// endpoint resting on an element's edge, between blocks, or in whitespace at
// either end touches nothing there — a triple-click ends at the start of the
@@ -168,25 +230,17 @@ function selectedContent(range: Range): Range | null {
const head = selected(first as Text);
narrowed.setStart(first, head.from + head.text.search(/\S/));
} else {
- narrowed.setStart(first, 0);
+ narrowed.setStartBefore(first);
}
if (last.nodeType === Node.TEXT_NODE) {
const tail = selected(last as Text);
narrowed.setEnd(last, tail.from + tail.text.search(/\s*$/));
} else {
- narrowed.setEnd(last, 0);
+ narrowed.setEndAfter(last);
}
return narrowed;
}
-// A root's top-level blocks: its outermost marked elements. Footnote
-// definitions render inside an unmarked section, and are blocks of their own.
-function blocksOf(root: Element): Element[] {
- return Array.from(root.querySelectorAll(MARKED)).filter(
- (el) => el.parentElement?.closest(MARKED) === root,
- );
-}
-
// An offset in the parsed text, carried back through the rewrite passes into
// `content`. An offset inside a rewritten span widens to cover the whole of
// what was rewritten: a mention chip copies as the `@<name>` that was typed.
@@ -212,45 +266,75 @@ function toContent(source: MarkdownSource, offset: number, side: 'start' | 'end'
function copyFromRoot(range: Range, root: Element): string {
const source = sources.get(root)!;
- const blocks = blocksOf(root);
- const touched = new Set(blocks.filter((block) => range.intersectsNode(block)));
- if (!touched.size) return '';
- if (touched.size === blocks.length) return source.content;
+ if (covers(range, root)) return source.content;
+ const slice = (start: number, end: number) =>
+ source.content.slice(toContent(source, start, 'start'), toContent(source, end, 'end'));
+
+ // What goes between the parts of two blocks: a tab between cells of a row, a
+ // line break between rows, otherwise the line break or blank line written
+ // between the blocks.
+ const separator = (from: Element, to: Element) => {
+ if (CELLS.has(from.tagName) && CELLS.has(to.tagName)) return from.parentElement === to.parentElement ? '\t' : '\n';
+ if (from.contains(to) || to.contains(from)) return '\n';
+ const between = spanEnd(from) <= spanStart(to) ? source.text.slice(spanEnd(from), spanStart(to)) : '';
+ return between.split('\n').length === 2 ? '\n' : '\n\n';
+ };
- // Touched blocks next to each other in the source are copied as one stretch,
- // with what was written between them; a block left out splits the stretch.
- const ordered = [...blocks].sort((left, right) => spanStart(left) - spanStart(right));
- const stretches: Array<[number, number]> = [];
- let open = false;
- for (const block of ordered) {
- if (!touched.has(block)) {
- open = false;
- } else if (open) {
- stretches[stretches.length - 1][1] = spanEnd(block);
- } else {
- stretches.push([spanStart(block), spanEnd(block)]);
- open = true;
+ let copied = '';
+ let block: Element | null = null;
+ const kept: Element[] = [];
+ const write = (text: string, within: Element) => {
+ if (!text) return;
+ if (block && block !== within) copied = copied.replace(/\n+$/, '') + separator(block, within);
+ copied += text;
+ block = within;
+ };
+ // A construct the selection covers copies its source; one it cuts through
+ // copies what it selects inside. `within` is the block around `node`, and
+ // `prefixed` says a container around it repeats its syntax on every line, so
+ // a source that runs over several lines would carry that syntax along.
+ const visit = (node: Node, within: Element, prefixed: boolean) => {
+ if (!range.intersectsNode(node)) return;
+ if (node.nodeType === Node.TEXT_NODE) {
+ const text = node as Text;
+ // Text no construct holds is the renderer's own, like a footnote section's label.
+ if (within === root) return;
+ const from = text === range.startContainer ? range.startOffset : 0;
+ const to = text === range.endContainer ? range.endOffset : text.data.length;
+ write(text.data.slice(from, Math.min(to, contentLength(text))), within);
+ return;
}
- }
+ if (node.nodeType !== Node.ELEMENT_NODE) return;
+ const el = node as Element;
+ const marked = el.hasAttribute(START);
+ const own = marked && BLOCKS.has(el.tagName) ? el : within;
+ if (marked && !TABLE_PARTS.has(el.tagName) && covers(range, el)) {
+ const markdown = slice(spanStart(el), spanEnd(el));
+ if (!prefixed || !markdown.includes('\n')) {
+ write(markdown, own);
+ kept.push(el);
+ return;
+ }
+ }
+ const inner = prefixed || (marked && LINE_PREFIXED.has(el.tagName));
+ el.childNodes.forEach((child) => visit(child, own, inner));
+ };
+ root.childNodes.forEach((child) => visit(child, root, false));
- // A definition brought along can itself hold references (a footnote citing a
- // reference link), so collect until nothing copied needs anything more.
- const copied = [...stretches];
- const holds = (start: number, end: number) => copied.some(([left, right]) => start >= left && end <= right);
- const references = Array.from(root.querySelectorAll(`[${DEF_START}]`)).filter((el) => el.hasAttribute(START));
- for (let grew = true; grew;) {
- grew = false;
- for (const el of references) {
- const definition: [number, number] = [Number(el.getAttribute(DEF_START)), Number(el.getAttribute(DEF_END))];
- if (!holds(spanStart(el), spanEnd(el)) || holds(...definition)) continue;
- copied.push(definition);
- grew = true;
+ // A kept reference link brings along its definition, unless that was kept too.
+ const holds = (start: number, end: number) => kept.some((el) => start >= spanStart(el) && end <= spanEnd(el));
+ const definitions = new Map<number, number>();
+ for (const el of kept) {
+ for (const reference of [el, ...Array.from(el.querySelectorAll(`[${DEF_START}]`))]) {
+ if (!reference.hasAttribute(DEF_START)) continue;
+ const start = Number(reference.getAttribute(DEF_START));
+ const end = Number(reference.getAttribute(DEF_END));
+ if (!holds(start, end)) definitions.set(start, end);
}
}
- const definitions = copied.slice(stretches.length).sort(([left], [right]) => left - right);
- return [...stretches, ...definitions]
- .map(([start, end]) => source.content.slice(toContent(source, start, 'start'), toContent(source, end, 'end')))
- .join('\n\n');
+ if (!definitions.size) return copied;
+ const appended = [...definitions].sort(([left], [right]) => left - right).map(([start, end]) => slice(start, end));
+ return `${copied}\n\n${appended.join('\n')}`;
}
// The rendered Markdown roots `range` reaches inside `container`, in document order.
@@ -267,9 +351,11 @@ function markdownRoots(range: Range, container: Element): Element[] {
* timestamps) is not Markdown and is left out.
*/
export function selectedMarkdown(range: Range, container: Element): string | null {
+ // The narrowed selection decides which bubbles are reached at all; within
+ // them, every character the selection holds is copied, whitespace included.
const selected = selectedContent(range);
if (!selected) return null;
- const parts = markdownRoots(selected, container).map((root) => copyFromRoot(selected, root));
+ const parts = markdownRoots(selected, container).map((root) => copyFromRoot(range, root));
return parts.filter((part) => part.trim() !== '').join('\n\n') || null;
}