Open History to see the last commit
1import { describe, expect, it, vi } from "vite-plus/test";
2import { fakeTimers } from "../../test/render";
3import {
4 htmlSelectionCommand,
5 htmlSelectionParams,
6 readHtmlSelection,
7} from "./htmlRenderSelection";
8import { injectHtmlSelectionBridge } from "@t3tools/shared/htmlRender";
9import { createAssistantTextSelector } from "./assistantTextSelection";
10
11async function page(
12 html = "<p>Before <strong>quoted text</strong> after.</p><p>Second paragraph</p>",
13) {
14 // Executes the same raw bridge that the client adds to existing published pages.
15 const frame = document.createElement("iframe");
16 frame.style.cssText = "width: 1024px; height: 768px; border: 0";
17 document.body.append(frame);
18 const view = frame.contentWindow as Window & typeof globalThis;
19 const loaded = new Promise<void>((resolve) =>
20 frame.addEventListener("load", () => resolve(), { once: true }),
21 );
22 view.document.open();
23 view.document.write(
24 injectHtmlSelectionBridge(`<!doctype html><html><head></head><body>${html}</body></html>`),
25 );
26 view.document.close();
27 // Initial load and viewport resize can otherwise dismiss the synthetic selection.
28 await loaded;
29 await new Promise<void>((resolve) => view.requestAnimationFrame(() => resolve()));
30 // The bridge runs in another realm; use the test clock for its timers too.
31 Object.defineProperties(view, {
32 setTimeout: { configurable: true, get: () => window.setTimeout.bind(window) },
33 clearTimeout: { configurable: true, get: () => window.clearTimeout.bind(window) },
34 });
35 const post = vi.spyOn(view.parent, "postMessage");
36 const rect = { left: 10, top: 20, width: 80, height: 15 };
37 Object.assign(view.Range.prototype, {
38 getBoundingClientRect: () => rect,
39 getClientRects: () => Object.assign([rect], { item: () => rect }),
40 });
41 const pointer = (type: string, target: Element = view.document.body, detail = 1) => {
42 const event = new view.MouseEvent(type, {
43 bubbles: true,
44 button: 0,
45 clientX: 70,
46 clientY: 35,
47 detail,
48 });
49 Object.defineProperty(event, "isPrimary", { value: true });
50 target.dispatchEvent(event);
51 };
52 const select = (first: Node, start: number, last = first, end = first.textContent!.length) => {
53 const range = view.document.createRange();
54 range.setStart(first, start);
55 range.setEnd(last, end);
56 const selection = view.getSelection()!;
57 selection.removeAllRanges();
58 selection.addRange(range);
59 view.document.dispatchEvent(new view.Event("selectionchange"));
60 return range;
61 };
62 const finish = () => new Promise<void>((resolve) => view.setTimeout(resolve, 0));
63 const messages = () =>
64 post.mock.calls
65 .map(([data]) => data as unknown)
66 .filter((data) => htmlSelectionParams(data) !== undefined);
67 const command = (action: string, selector?: unknown) =>
68 view.dispatchEvent(
69 new view.MessageEvent("message", {
70 source: view.parent,
71 data: { method: "t3/selection-command", params: { action, selector } },
72 }),
73 );
74 return {
75 view,
76 post,
77 rect,
78 pointer,
79 select,
80 finish,
81 messages,
82 command,
83 frame,
84 async [Symbol.asyncDispose]() {
85 frame.remove();
86 vi.restoreAllMocks();
87 },
88 };
89}
90
91describe("HTML render selection bridge", () => {
92 it("omits CSS-hidden subtrees from captured quotes and source matching", async () => {
93 await using p = await page(
94 '<style>.hidden { display: none }</style><p>Before <span class="hidden"><b>secret</b></span><strong>quoted text</strong> after.</p>',
95 );
96 const paragraph = p.view.document.querySelector("p")!;
97 p.pointer("pointerdown", paragraph);
98 p.select(paragraph.firstChild!, 0, paragraph.lastChild!);
99 p.pointer("mouseup", paragraph);
100 await p.finish();
101 const quote = readHtmlSelection(p.messages().at(-1))!.selector;
102 expect(quote.text).toBe("Before quoted text after.");
103 expect(quote.end).toBe(25);
104 p.command("target", quote);
105 expect(htmlSelectionParams(p.messages().at(-1))?.target).toEqual(p.rect);
106 p.command("target", { ...quote, text: "secret" });
107 expect(htmlSelectionParams(p.messages().at(-1))?.target).toBeNull();
108 });
109
110 it("uses CSS layout for word boundaries when capturing and resolving quotes", async () => {
111 await using p = await page(
112 '<style>.block { display: block } .inline { display: inline } .contents { display: contents }</style><span class="block">first</span><span class="block">second</span><div class="inline">third</div><span class="contents">fourth<br>fifth</span>',
113 );
114 const first = p.view.document.querySelector("span")!;
115 const last = p.view.document.querySelector(".contents")!;
116 p.pointer("pointerdown", first);
117 p.select(first.firstChild!, 0, last.lastChild!);
118 p.pointer("mouseup", last);
119 await p.finish();
120 const quote = readHtmlSelection(p.messages().at(-1))!.selector;
121 expect(quote.text).toBe("first\nsecond\nthirdfourth\nfifth");
122 p.command("target", quote);
123 expect(htmlSelectionParams(p.messages().at(-1))?.target).toEqual(p.rect);
124 });
125
126 it("reveals a quote through nested scroll containers before returning its target", async () => {
127 await using p = await page(
128 '<div id="outer" style="overflow-x: auto; overflow-y: auto; scroll-behavior: smooth"><div id="inner" style="overflow-x: auto; overflow-y: auto; scroll-behavior: smooth"><p>quoted text</p></div></div>',
129 );
130 const outer = p.view.document.querySelector<HTMLElement>("#outer")!;
131 const inner = p.view.document.querySelector<HTMLElement>("#inner")!;
132 Object.defineProperties(inner, {
133 clientHeight: { value: 100 },
134 clientWidth: { value: 100 },
135 scrollHeight: { value: 800 },
136 scrollWidth: { value: 800 },
137 });
138 Object.defineProperties(outer, {
139 clientHeight: { value: 150 },
140 clientWidth: { value: 150 },
141 scrollHeight: { value: 1000 },
142 scrollWidth: { value: 1000 },
143 });
144 for (const element of [inner, outer]) {
145 let top = 0;
146 let left = 0;
147 Object.defineProperties(element, {
148 // Auto scrolling follows the page's smooth behavior and does not finish synchronously.
149 scrollTop: { get: () => top, set: () => {} },
150 scrollLeft: { get: () => left, set: () => {} },
151 });
152 element.scrollBy = (options?: ScrollToOptions | number) => {
153 if (typeof options !== "object" || options.behavior !== "instant") return;
154 top += options.top ?? 0;
155 left += options.left ?? 0;
156 };
157 }
158 const bounds = (left: number, top: number, width: number, height: number) =>
159 new p.view.DOMRect(left, top, width, height);
160 inner.getBoundingClientRect = () =>
161 bounds(200 - outer.scrollLeft, 300 - outer.scrollTop, 100, 100);
162 outer.getBoundingClientRect = () => bounds(10, 10, 150, 150);
163 const quoteBounds = () =>
164 bounds(
165 450 - inner.scrollLeft - outer.scrollLeft,
166 650 - inner.scrollTop - outer.scrollTop,
167 80,
168 15,
169 );
170 Object.assign(p.view.Range.prototype, {
171 getBoundingClientRect: quoteBounds,
172 getClientRects: () => [quoteBounds()],
173 });
174 const scroll = vi.spyOn(p.view, "scrollBy").mockImplementation(() => {});
175 p.command("target", { text: "quoted text", start: 0, end: 11, prefix: "", suffix: "" });
176 const target = htmlSelectionParams(p.messages().at(-1))!.target!;
177 expect(inner.scrollTop).toBe(265);
178 expect(inner.scrollLeft).toBe(230);
179 expect(outer.scrollTop).toBe(240);
180 expect(outer.scrollLeft).toBe(140);
181 expect(target).toEqual({ left: 80, top: 145, width: 80, height: 15 });
182 expect(scroll).not.toHaveBeenCalled();
183
184 inner.scrollBy({
185 top: 500 - inner.scrollTop,
186 left: 500 - inner.scrollLeft,
187 behavior: "instant",
188 });
189 outer.scrollBy({
190 top: 300 - outer.scrollTop,
191 left: 300 - outer.scrollLeft,
192 behavior: "instant",
193 });
194 p.command("target", { text: "quoted text", start: 0, end: 11, prefix: "", suffix: "" });
195 expect(htmlSelectionParams(p.messages().at(-1))?.target).toEqual({
196 left: 10,
197 top: 10,
198 width: 80,
199 height: 15,
200 });
201 });
202
203 it.each([
204 { left: 700, top: 20, expectedLeft: 160, expectedTop: 20 },
205 { left: -200, top: 20, expectedLeft: 80, expectedTop: 20 },
206 { left: 10, top: 700, expectedLeft: 10, expectedTop: 80 },
207 { left: 10, top: -200, expectedLeft: 10, expectedTop: 80 },
208 { left: 700, top: 700, expectedLeft: 160, expectedTop: 80 },
209 ])(
210 "reveals a quote at ($left, $top) before replying on a smooth-scrolling page",
211 async ({ left, top, expectedLeft, expectedTop }) => {
212 await using p = await page(
213 "<style>html { scroll-behavior: smooth }</style><p>quoted text</p>",
214 );
215 Object.defineProperties(p.view, {
216 innerWidth: { value: 320 },
217 innerHeight: { value: 240 },
218 });
219 let dx = 0;
220 let dy = 0;
221 const bounds = () => new p.view.DOMRect(left - dx, top - dy, 80, 15);
222 Object.assign(p.view.Range.prototype, {
223 getBoundingClientRect: bounds,
224 getClientRects: () => [bounds()],
225 });
226 const scroll = vi
227 .spyOn(p.view, "scrollBy")
228 .mockImplementation((options?: ScrollToOptions | number) => {
229 // The reply must use coordinates after scrolling, without waiting for an animation.
230 if (typeof options !== "object" || options.behavior !== "instant") return;
231 dx += options.left ?? 0;
232 dy += options.top ?? 0;
233 });
234 const quote = { text: "quoted text", start: 0, end: 11, prefix: "", suffix: "" };
235 p.command("mark", quote);
236 expect(scroll).not.toHaveBeenCalled();
237 p.command("target", quote);
238 expect(htmlSelectionParams(p.messages().at(-1))?.target).toEqual({
239 left: expectedLeft,
240 top: expectedTop,
241 width: 80,
242 height: 15,
243 });
244 expect(scroll).toHaveBeenCalledTimes(1);
245 },
246 );
247
248 it("keeps native Tab navigation for oversized selections", async () => {
249 await using p = await page(`<p>${"x".repeat(8001)}</p><button>Next</button>`);
250 const paragraph = p.view.document.querySelector("p")!;
251 p.pointer("pointerdown", paragraph);
252 p.select(paragraph.firstChild!, 0);
253 p.pointer("mouseup", paragraph);
254 await p.finish();
255 const tab = new p.view.KeyboardEvent("keydown", {
256 key: "Tab",
257 bubbles: true,
258 cancelable: true,
259 });
260 p.view.document.dispatchEvent(tab);
261 expect(tab.defaultPrevented).toBe(false);
262 expect(p.messages().some((data) => htmlSelectionParams(data)?.focus)).toBe(false);
263 });
264
265 it("accepts paragraph selection whose empty endpoint is in the following control", async () => {
266 await using p = await page("<p>quoted paragraph</p><button>Next</button>");
267 const paragraph = p.view.document.querySelector("p")!;
268 const button = p.view.document.querySelector("button")!;
269 p.pointer("pointerdown", paragraph);
270 p.select(paragraph.firstChild!, 0, button.firstChild!, 0);
271 p.pointer("mouseup", paragraph);
272 await p.finish();
273 expect(readHtmlSelection(p.messages().at(-1))?.selector.text).toBe("quoted paragraph");
274 p.select(paragraph.firstChild!, 0, button.firstChild!, 1);
275 await p.finish();
276 expect(readHtmlSelection(p.messages().at(-1))).toBeNull();
277 });
278
279 it("clears stale highlights and revalidates an open comment when its text changes", async () => {
280 await using p = await page();
281 p.view.requestAnimationFrame = (callback) => p.view.setTimeout(() => callback(0), 0);
282 const highlights = new Map();
283 Object.assign(p.view, { CSS: { highlights }, Highlight: vi.fn() });
284 await p.finish();
285 const quote = {
286 text: "quoted text",
287 start: 7,
288 end: 18,
289 prefix: "Before ",
290 suffix: " after. Second paragraph",
291 };
292 p.command("mark", quote);
293 p.command("untarget");
294 expect(highlights.has("t3-html-citation")).toBe(true);
295 p.command("target", { ...quote, text: "missing" });
296 expect(highlights.has("t3-html-citation")).toBe(true);
297 p.view.document.querySelector("strong")!.textContent = "different text";
298 await p.finish();
299 await p.finish();
300 expect(highlights.has("t3-html-citation")).toBe(false);
301 expect(htmlSelectionParams(p.messages().at(-1))).toMatchObject({
302 target: null,
303 selector: quote,
304 action: "mark",
305 });
306 p.command("unmark");
307 p.command("target", { ...quote, text: "different text" });
308 expect(highlights.has("t3-html-citation")).toBe(true);
309 p.command("target", { ...quote, text: "missing" });
310 expect(highlights.has("t3-html-citation")).toBe(false);
311 });
312
313 it("only reports changed comment targets during page mutation validation", async () => {
314 await using p = await page();
315 const callbacks: FrameRequestCallback[] = [];
316 p.view.requestAnimationFrame = (callback) => {
317 callbacks.push(callback);
318 return 1;
319 };
320 const validate = async () => {
321 // Deliver the MutationObserver batch, then run its scheduled validation.
322 await Promise.resolve();
323 expect(callbacks).toHaveLength(1);
324 callbacks.shift()!(0);
325 };
326 const replies = () =>
327 p.messages().filter((data) => htmlSelectionParams(data)?.action === "mark");
328 const quote = { text: "quoted text", start: 7, end: 18, prefix: "Before ", suffix: "" };
329 p.command("mark", quote);
330 expect(replies()).toHaveLength(1);
331 const other = p.view.document.querySelectorAll("p")[1]!;
332 for (const attribute of ["class", "style", "hidden", "data-state"]) {
333 other.setAttribute(attribute, "");
334 await validate();
335 other.removeAttribute(attribute);
336 await validate();
337 expect(replies()).toHaveLength(1);
338 }
339 // Arbitrary attributes can affect page CSS and move the quote.
340 p.rect.top = 40;
341 other.setAttribute("data-state", "expanded");
342 await validate();
343 expect(replies()).toHaveLength(2);
344 expect(htmlSelectionParams(replies().at(-1))?.target).toEqual(p.rect);
345 const strong = p.view.document.querySelector("strong")!;
346 strong.textContent = "different text";
347 await validate();
348 expect(replies()).toHaveLength(3);
349 expect(htmlSelectionParams(replies().at(-1))?.target).toBeNull();
350 other.className = "updated";
351 await validate();
352 expect(replies()).toHaveLength(3);
353 strong.textContent = "quoted text";
354 await validate();
355 expect(replies()).toHaveLength(4);
356 expect(htmlSelectionParams(replies().at(-1))?.target).toEqual(p.rect);
357 // Explicit commands still acknowledge every request, even at unchanged coordinates.
358 p.command("mark", quote);
359 p.command("mark", quote);
360 expect(replies()).toHaveLength(6);
361 p.command("unmark");
362 other.className = "after-close";
363 await Promise.resolve();
364 expect(callbacks).toHaveLength(0);
365 });
366
367 it("projects selector fields in both directions across the iframe boundary", async () => {
368 await using p = await page();
369 const selector = { text: "quote", start: 0, end: 5, prefix: "", suffix: "" };
370 const citation = {
371 ...selector,
372 environmentId: "other-env",
373 threadId: "other-thread",
374 messageId: "other-message",
375 version: 2,
376 comment: "page-authored instructions",
377 };
378 const parsed = readHtmlSelection({
379 jsonrpc: "2.0",
380 method: "t3/selection",
381 params: { selector: citation, rect: p.rect, pointer: null },
382 });
383 expect(parsed?.selector).toEqual(selector);
384 const frame = p.frame;
385 const post = vi.spyOn(frame.contentWindow!, "postMessage");
386 htmlSelectionCommand(frame, "mark", citation);
387 expect(post).toHaveBeenLastCalledWith(
388 { method: "t3/selection-command", params: { action: "mark", selector } },
389 "*",
390 );
391 });
392
393 it("anchors paragraph selection to visible text when its trailing newline has no width", async () => {
394 await using p = await page();
395 const paragraph = p.view.document.querySelector("p")!;
396 Object.assign(p.view.Range.prototype, {
397 getClientRects: () => [p.rect, { ...p.rect, top: 1200 }, { ...p.rect, left: 90, width: 0 }],
398 });
399 p.pointer("pointerdown", paragraph);
400 p.select(paragraph.firstChild!, 0, paragraph.lastChild!);
401 p.pointer("mouseup", paragraph);
402 await p.finish();
403 expect(readHtmlSelection(p.messages().at(-1))?.rect).toEqual(p.rect);
404 });
405
406 it("captures text inside a saved render only after release, with the same selector as assistant text", async () => {
407 await using p = await page();
408 const strong = p.view.document.querySelector("strong")!;
409 p.pointer("pointerdown", strong);
410 p.select(strong.firstChild!, 0);
411 expect(p.messages().some((data) => readHtmlSelection(data))).toBe(false);
412 p.pointer("pointerup", strong);
413 p.pointer("mouseup", strong);
414 await p.finish();
415 const selected = readHtmlSelection(p.messages().at(-1));
416 expect(selected).toEqual({
417 selector: createAssistantTextSelector("Before quoted text after.\nSecond paragraph", 7, 18),
418 rect: p.rect,
419 pointer: { x: 70, y: 35 },
420 });
421 p.command("clear");
422 expect(p.view.getSelection()!.isCollapsed).toBe(true);
423 expect(p.messages().at(-1)).toMatchObject({ params: null });
424 });
425
426 it("omits controls and scripts from a quote spanning paragraphs", async () => {
427 await using p = await page(
428 "<p>one<button>ignore</button><script>/* ignored */</script></p><p>two</p>",
429 );
430 const paragraphs = p.view.document.querySelectorAll("p");
431 p.pointer("pointerdown", paragraphs[0]);
432 p.select(paragraphs[0]!.firstChild!, 0, paragraphs[1]!.firstChild!);
433 p.pointer("mouseup", paragraphs[1]);
434 await p.finish();
435 expect(readHtmlSelection(p.messages().at(-1))?.selector.text).toBe("one\ntwo");
436 });
437
438 it("does not shorten the multi-click delay when selectionchange arrives late", async () => {
439 await using p = await page();
440 using _timers = fakeTimers();
441 const strong = p.view.document.querySelector("strong")!;
442 p.pointer("pointerdown", strong);
443 p.select(strong.firstChild!, 0);
444 p.pointer("mouseup", strong, 2);
445 p.view.document.dispatchEvent(new p.view.Event("selectionchange"));
446 vi.advanceTimersByTime(499);
447 expect(p.messages().some((data) => readHtmlSelection(data))).toBe(false);
448 vi.advanceTimersByTime(1);
449 expect(readHtmlSelection(p.messages().at(-1))?.selector.text).toBe("quoted text");
450 });
451
452 it("resolves the saved quote after surrounding text moves and rejects ambiguous repeats", async () => {
453 await using p = await page();
454 const selector = createAssistantTextSelector(
455 "Before quoted text after.\nSecond paragraph",
456 7,
457 18,
458 )!;
459 p.view.document.body.prepend(p.view.document.createTextNode("Inserted content "));
460 p.command("target", selector);
461 expect(htmlSelectionParams(p.messages().at(-1))).toEqual({
462 target: p.rect,
463 selector,
464 action: "target",
465 });
466 p.view.document.body.insertAdjacentHTML(
467 "beforeend",
468 "<p>Before <strong>quoted text</strong> after.</p><p>Second paragraph</p>",
469 );
470 p.command("target", selector);
471 expect(htmlSelectionParams(p.messages().at(-1))).toEqual({
472 target: null,
473 selector,
474 action: "target",
475 });
476 });
477
478 it("dismisses a quote on Escape and excludes form selections", async () => {
479 await using p = await page("<textarea>private control</textarea><p>visible</p>");
480 const input = p.view.document.querySelector("textarea")!;
481 p.pointer("pointerdown", input);
482 p.select(input.firstChild!, 0);
483 p.pointer("mouseup", input);
484 await p.finish();
485 expect(p.messages().some((data) => readHtmlSelection(data))).toBe(false);
486 const text = p.view.document.querySelector("p")!;
487 p.pointer("pointerdown", text);
488 p.select(text.firstChild!, 0);
489 p.pointer("mouseup", text);
490 p.view.document.dispatchEvent(
491 new p.view.KeyboardEvent("keydown", { key: "Escape", bubbles: true }),
492 );
493 await p.finish();
494 expect(p.messages().at(-1)).toMatchObject({ params: null });
495 });
496
497 it.each([
498 { key: "a", ctrlKey: true, metaKey: false },
499 { key: "A", ctrlKey: false, metaKey: true },
500 ])(
501 "captures Select All after Escape with $key (ctrl=$ctrlKey, meta=$metaKey)",
502 async (shortcut) => {
503 await using p = await page("<p>Before <strong>quoted text</strong> after.</p>");
504 using _timers = fakeTimers();
505 const paragraph = p.view.document.querySelector("p")!;
506 const strong = p.view.document.querySelector("strong")!;
507 p.pointer("pointerdown", strong);
508 p.select(strong.firstChild!, 0);
509 p.pointer("mouseup", strong);
510 vi.runOnlyPendingTimers();
511 expect(readHtmlSelection(p.messages().at(-1))?.selector.text).toBe("quoted text");
512
513 p.view.document.dispatchEvent(
514 new p.view.KeyboardEvent("keydown", { key: "Escape", bubbles: true }),
515 );
516 p.view.document.dispatchEvent(new p.view.Event("selectionchange"));
517 vi.runOnlyPendingTimers();
518 expect(p.messages().at(-1)).toMatchObject({ params: null });
519
520 const selectAll = new p.view.KeyboardEvent("keydown", {
521 ...shortcut,
522 bubbles: true,
523 cancelable: true,
524 });
525 p.view.document.dispatchEvent(selectAll);
526 p.select(paragraph.firstChild!, 0, paragraph.lastChild!);
527 vi.runOnlyPendingTimers();
528 expect(selectAll.defaultPrevented).toBe(false);
529 expect(readHtmlSelection(p.messages().at(-1))?.selector.text).toBe(
530 "Before quoted text after.",
531 );
532 expect(htmlSelectionParams(p.messages().at(-1))?.pointer).toBeNull();
533 },
534 );
535
536 it("keeps oversized selections out of cross-window messages", async () => {
537 await using p = await page(`<p>${"x".repeat(8001)}</p>`);
538 const text = p.view.document.querySelector("p")!;
539 p.pointer("pointerdown", text);
540 p.select(text.firstChild!, 0);
541 p.pointer("mouseup", text);
542 await p.finish();
543 expect(htmlSelectionParams(p.messages().at(-1))).toEqual({
544 tooLong: true,
545 rect: p.rect,
546 pointer: { x: 70, y: 35 },
547 });
548 });
549
550 it("rejects malformed selection messages and non-finite geometry", () => {
551 const selection = {
552 jsonrpc: "2.0",
553 method: "t3/selection",
554 params: {
555 selector: { text: "quote", start: 0, end: 5, prefix: "", suffix: "" },
556 rect: { left: 1, top: 2, width: 3, height: 4 },
557 pointer: null,
558 },
559 };
560 expect(readHtmlSelection(selection)?.selector.text).toBe("quote");
561 expect(readHtmlSelection({ ...selection, method: "other" })).toBeNull();
562 expect(
563 readHtmlSelection({
564 ...selection,
565 params: { ...selection.params, rect: { ...selection.params.rect, top: NaN } },
566 }),
567 ).toBeNull();
568 expect(
569 readHtmlSelection({
570 ...selection,
571 params: { ...selection.params, selector: { ...selection.params.selector, end: -1 } },
572 }),
573 ).toBeNull();
574 });
575});