Open History to see the last commit
1import type { LegendListRef } from "@legendapp/list/react";
2import { EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";
3import { afterEach, describe, expect, it, vi } from "vite-plus/test";
4
5import {
6 observeAssistantCitationCommentSource,
7 observeAssistantCitationSource,
8 type AssistantCitationTarget,
9} from "./AssistantCitationSource";
10
11const mocks = vi.hoisted(() => ({ resolveRange: vi.fn(), toast: vi.fn() }));
12vi.mock("~/lib/assistantTextSelection", () => ({
13 resolveAssistantCitationRange: mocks.resolveRange,
14}));
15vi.mock("../ui/toast", () => ({ toastManager: { add: mocks.toast } }));
16
17function rect(top: number, height = 20) {
18 return { top, bottom: top + height, height, width: 100 } as DOMRect;
19}
20
21class TestAnimation {
22 currentTime = 0;
23 id = "";
24 private resolveFinished!: () => void;
25 finished = new Promise<void>((resolve) => {
26 this.resolveFinished = resolve;
27 });
28 cancel = vi.fn();
29 finish() {
30 this.resolveFinished();
31 }
32}
33
34class TestElement {
35 parentNode: TestElement | null = null;
36 dataset: Record<string, string> = {};
37 focus = vi.fn();
38 animations: TestAnimation[] = [];
39 animate = vi.fn(() => {
40 const animation = new TestAnimation();
41 this.animations.push(animation);
42 return animation as unknown as Animation;
43 });
44 isConnected = true;
45 scrollTop = 8586;
46 scrollHeight = 9334;
47 clientHeight = 748;
48 getBoundingClientRect = () => rect(0, this.clientHeight);
49 ownerDocument = {
50 getSelection: () => null as TestSelection | null,
51 };
52
53 contains(node: TestElement | null): boolean {
54 return node === this || (node?.parentNode ? this.contains(node.parentNode) : false);
55 }
56}
57
58class TestRange {
59 startOffset = 0;
60 endOffset = 5;
61 collapsed = false;
62 endContainer: TestElement;
63
64 constructor(
65 public startContainer: TestElement,
66 readonly readRect: () => DOMRect,
67 ) {
68 this.endContainer = startContainer;
69 }
70
71 getBoundingClientRect() {
72 return this.collapsed ? rect(0, 0) : this.readRect();
73 }
74
75 cloneRange() {
76 const copy = new TestRange(this.startContainer, this.readRect);
77 copy.startOffset = this.startOffset;
78 copy.endOffset = this.endOffset;
79 return copy;
80 }
81
82 collapseTo(parent: TestElement) {
83 this.startContainer = this.endContainer = parent;
84 this.startOffset = this.endOffset = 0;
85 this.collapsed = true;
86 }
87
88 setStart(node: TestElement, offset: number) {
89 this.startContainer = node;
90 this.startOffset = offset;
91 this.collapsed =
92 this.startContainer === this.endContainer && this.startOffset === this.endOffset;
93 }
94
95 setEnd(node: TestElement, offset: number) {
96 this.endContainer = node;
97 this.endOffset = offset;
98 this.collapsed =
99 this.startContainer === this.endContainer && this.startOffset === this.endOffset;
100 }
101
102 toString() {
103 return this.collapsed ? "" : "quote";
104 }
105}
106
107class TestSelection {
108 ranges: TestRange[] = [];
109 get rangeCount() {
110 return this.ranges.length;
111 }
112 getRangeAt(index: number) {
113 return this.ranges[index]!;
114 }
115 addRange(range: TestRange) {
116 this.ranges.push(range);
117 }
118 removeRange(range: TestRange) {
119 this.ranges = this.ranges.filter((current) => current !== range);
120 }
121 removeAllRanges() {
122 this.ranges = [];
123 }
124}
125
126function createSource({ reducedMotion = false } = {}) {
127 vi.stubGlobal("window", { matchMedia: vi.fn(() => ({ matches: reducedMotion })) });
128 let now = 0;
129 vi.stubGlobal("performance", { now: () => now });
130 const frames = new Map<number, FrameRequestCallback>();
131 let nextFrame = 0;
132 vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {
133 frames.set(++nextFrame, callback);
134 return nextFrame;
135 });
136 vi.stubGlobal("cancelAnimationFrame", (frame: number) => frames.delete(frame));
137 const flushFrame = () => {
138 const callbacks = [...frames.values()];
139 frames.clear();
140 for (const callback of callbacks) callback(0);
141 };
142 const mutationCallbacks = new Set<MutationCallback>();
143 let resize: ResizeObserverCallback = () => {};
144 vi.stubGlobal(
145 "MutationObserver",
146 class {
147 constructor(readonly callback: MutationCallback) {}
148 observe() {
149 mutationCallbacks.add(this.callback);
150 }
151 disconnect() {
152 mutationCallbacks.delete(this.callback);
153 }
154 },
155 );
156 vi.stubGlobal(
157 "ResizeObserver",
158 class {
159 constructor(callback: ResizeObserverCallback) {
160 resize = callback;
161 }
162 observe() {}
163 disconnect() {
164 resize = () => {};
165 }
166 },
167 );
168 vi.stubGlobal("HTMLElement", TestElement);
169 const highlights = new Map<string, Set<TestRange>>();
170 vi.stubGlobal(
171 "Highlight",
172 class extends Set<TestRange> {
173 constructor(...ranges: TestRange[]) {
174 super(ranges);
175 }
176 },
177 );
178 vi.stubGlobal("CSS", { highlights });
179
180 const scrollNode = new TestElement();
181 const container = new TestElement();
182 container.parentNode = scrollNode;
183 const root = new TestElement();
184 root.parentNode = container;
185 const text = new TestElement();
186 text.parentNode = root;
187 let sourceTop = 200;
188 let measured = true;
189 let rangeHeight = 20;
190 root.getBoundingClientRect = () => rect(sourceTop - scrollNode.scrollTop, 300);
191 mocks.resolveRange.mockImplementation(
192 () => new TestRange(text, () => rect(sourceTop - scrollNode.scrollTop, rangeHeight)),
193 );
194 const listeners = new Set<() => void>();
195 const listen = (callback: () => void) => {
196 listeners.add(callback);
197 return () => listeners.delete(callback);
198 };
199 const layoutChanged = () => {
200 for (const listener of listeners) listener();
201 };
202 let pending: { options: { offset: number }; resolve: () => void } | null = null;
203 const scrollToOffset = vi.fn((options: { offset: number; animated?: boolean }) => {
204 pending?.resolve();
205 return new Promise<void>((resolve) => {
206 pending = { options, resolve };
207 });
208 });
209 const finishScroll = async () => {
210 const scroll = pending;
211 if (!scroll) throw new Error("No citation scroll is pending");
212 pending = null;
213 scrollNode.scrollTop = scroll.options.offset;
214 scroll.resolve();
215 await Promise.resolve();
216 flushFrame();
217 };
218 const list = {
219 getScrollableNode: () => scrollNode,
220 getState: () => ({
221 scroll: scrollNode.scrollTop,
222 indexByKey: () => 1,
223 sizeAtIndex: () => (measured ? 300 : undefined),
224 listenToPosition: (_key: string, callback: () => void) => listen(callback),
225 listen: (_signal: string, callback: () => void) => listen(callback),
226 }),
227 scrollToOffset,
228 } as unknown as LegendListRef;
229 const target: AssistantCitationTarget = {
230 key: "activation-one",
231 citation: {
232 version: 1,
233 environmentId: EnvironmentId.make("environment"),
234 threadId: ThreadId.make("thread"),
235 messageId: MessageId.make("source"),
236 text: "quote",
237 start: 0,
238 end: 5,
239 prefix: "",
240 suffix: "",
241 },
242 activationRef: { current: { scrolled: false, dismissed: false } },
243 onComplete: vi.fn(),
244 };
245 const cleanups: Array<() => void> = [];
246 const mount = (request = target) => {
247 const cleanup = observeAssistantCitationSource({
248 root: root as unknown as HTMLElement,
249 itemKey: "source-row",
250 request,
251 list,
252 });
253 if (cleanup) cleanups.push(cleanup);
254 return cleanup;
255 };
256 const mountComment = (
257 range = new TestRange(text, () => rect(sourceTop - scrollNode.scrollTop, rangeHeight)),
258 ) => {
259 const onUnavailable = vi.fn();
260 const cleanup = observeAssistantCitationCommentSource({
261 anchor: {
262 source: root as unknown as HTMLElement,
263 range: range as unknown as Range,
264 viewport: scrollNode as unknown as HTMLElement,
265 },
266 citation: target.citation,
267 onUnavailable,
268 });
269 cleanups.push(cleanup);
270 return { range, onUnavailable, cleanup };
271 };
272 const mutation = (changed: TestElement, removed: TestElement[] = []) => {
273 for (const callback of mutationCallbacks) {
274 callback(
275 [{ target: changed, addedNodes: [], removedNodes: removed }] as unknown as MutationRecord[],
276 {} as MutationObserver,
277 );
278 }
279 };
280 return {
281 target,
282 root,
283 text,
284 container,
285 scrollNode,
286 highlights,
287 scrollToOffset,
288 mount,
289 mountComment,
290 flushFrame,
291 finishScroll,
292 layoutChanged,
293 mutation,
294 advanceTime: (milliseconds: number) => {
295 now += milliseconds;
296 },
297 finishPulse: async () => {
298 root.animations.at(-1)?.finish();
299 await Promise.resolve();
300 },
301 resize: () => resize([], {} as ResizeObserver),
302 setMeasured: (value: boolean) => {
303 measured = value;
304 },
305 setRangeHeight: (value: number) => {
306 rangeHeight = value;
307 },
308 setSourceTop: (value: number) => {
309 sourceTop = value;
310 },
311 highlight: () => highlights.get("t3-assistant-citation")?.values().next().value,
312 commentHighlight: () => highlights.get("t3-assistant-citation-comment"),
313 cleanup: () => {
314 for (const cleanup of cleanups) cleanup();
315 },
316 };
317}
318
319afterEach(() => {
320 vi.unstubAllGlobals();
321 vi.clearAllMocks();
322});
323
324describe("assistant citation source lifecycle", () => {
325 it("waits for a mounted measurement and rechecks geometry after the list settles", async () => {
326 const source = createSource();
327 source.setMeasured(false);
328 source.mount();
329 source.flushFrame();
330 expect(source.scrollToOffset).not.toHaveBeenCalled();
331
332 source.setMeasured(true);
333 source.setRangeHeight(0);
334 source.resize();
335 source.flushFrame();
336 expect(source.target.activationRef.current.scrolled).toBe(false);
337 expect(source.scrollToOffset).not.toHaveBeenCalled();
338
339 source.setRangeHeight(20);
340 source.layoutChanged();
341 source.flushFrame();
342 expect(source.scrollToOffset).toHaveBeenCalledExactlyOnceWith({ offset: 80, animated: true });
343 expect(source.highlight()).toBeUndefined();
344 expect(source.root.animations).toHaveLength(0);
345
346 source.scrollNode.scrollTop = 4200;
347 source.advanceTime(700);
348 source.setSourceTop(260);
349 source.layoutChanged();
350 source.flushFrame();
351 expect(source.scrollToOffset).toHaveBeenCalledTimes(1);
352 expect(source.highlight()).toBeUndefined();
353 expect(source.target.onComplete).not.toHaveBeenCalled();
354 await source.finishScroll();
355 expect(source.target.onComplete).not.toHaveBeenCalled();
356 expect(source.scrollToOffset).toHaveBeenLastCalledWith({ offset: 140, animated: true });
357 await source.finishScroll();
358 expect(source.target.onComplete).toHaveBeenCalledOnce();
359 expect(source.highlight()?.getBoundingClientRect().top).toBe(120);
360 expect(source.root.animations).toHaveLength(1);
361 expect(source.root.focus).not.toHaveBeenCalled();
362 source.cleanup();
363 expect(source.highlight()).toBeUndefined();
364 });
365
366 it("completes a measured citation at the clamped beginning of the list", async () => {
367 const source = createSource();
368 source.setSourceTop(40);
369 source.mount();
370 source.flushFrame();
371 await source.finishScroll();
372 expect(source.scrollNode.scrollTop).toBe(0);
373 expect(source.highlight()?.toString()).toBe("quote");
374 expect(source.target.onComplete).toHaveBeenCalledOnce();
375 source.cleanup();
376 });
377
378 it("repairs collapsed ranges after an ancestor move without following the user's scroll", async () => {
379 const source = createSource();
380 const unmount = source.mount();
381 source.flushFrame();
382 await source.finishScroll();
383 const originalRange = source.highlight()!;
384 source.scrollNode.scrollTop = 4000;
385 originalRange.collapseTo(source.scrollNode);
386 source.mutation(source.scrollNode, [source.container]);
387 expect(source.highlight()).toBeUndefined();
388 expect(source.root.dataset.citationHighlighted).toBeUndefined();
389 source.flushFrame();
390 expect(source.highlight()?.toString()).toBe("quote");
391 expect(source.root.contains(source.highlight()!.startContainer)).toBe(true);
392 expect(source.scrollNode.scrollTop).toBe(4000);
393 expect(source.root.animations).toHaveLength(1);
394
395 const resolutions = mocks.resolveRange.mock.calls.length;
396 source.mutation(new TestElement());
397 source.flushFrame();
398 expect(mocks.resolveRange).toHaveBeenCalledTimes(resolutions);
399
400 unmount?.();
401 source.advanceTime(700);
402 source.mount();
403 source.flushFrame();
404 expect(source.highlight()?.toString()).toBe("quote");
405 expect(source.scrollToOffset).toHaveBeenCalledTimes(1);
406 expect(source.target.onComplete).toHaveBeenCalledOnce();
407 expect(source.root.animations).toHaveLength(2);
408 expect(source.root.animations[1]?.currentTime).toBe(700);
409 source.root.animations[0]?.finish();
410 await Promise.resolve();
411 expect(source.highlight()?.toString()).toBe("quote");
412 await source.finishPulse();
413 expect(source.highlight()).toBeUndefined();
414 source.cleanup();
415 });
416
417 it("removes the quote after the pulse and replays it only for a fresh citation activation", async () => {
418 const source = createSource();
419 const unmount = source.mount();
420 source.flushFrame();
421 await source.finishScroll();
422 await source.finishPulse();
423 expect(source.highlight()).toBeUndefined();
424 expect(source.root.dataset.citationHighlighted).toBeUndefined();
425 source.layoutChanged();
426 source.flushFrame();
427 expect(source.mount()).toBeUndefined();
428 expect(source.root.animations).toHaveLength(1);
429
430 unmount?.();
431 source.mount({
432 ...source.target,
433 key: "activation-two",
434 activationRef: { current: { scrolled: false, dismissed: false } },
435 });
436 source.flushFrame();
437 expect(source.highlight()?.toString()).toBe("quote");
438 expect(source.root.animations).toHaveLength(2);
439 expect(source.root.animations[1]?.currentTime).toBe(0);
440 source.cleanup();
441 });
442
443 it("uses instant navigation and removes the temporary quote highlight for reduced motion", async () => {
444 const source = createSource({ reducedMotion: true });
445 source.mount();
446 source.flushFrame();
447 expect(source.scrollToOffset).toHaveBeenCalledWith({ offset: 80, animated: false });
448 expect(source.highlight()).toBeUndefined();
449 await source.finishScroll();
450 expect(source.target.activationRef.current.pulse?.reducedMotion).toBe(true);
451 expect(source.highlight()?.toString()).toBe("quote");
452 await source.finishPulse();
453 expect(source.highlight()).toBeUndefined();
454 expect(source.root.focus).not.toHaveBeenCalled();
455 source.cleanup();
456 });
457
458 it("does not revive a quote when remounting after its original pulse deadline", async () => {
459 const source = createSource();
460 const unmount = source.mount();
461 source.flushFrame();
462 await source.finishScroll();
463 unmount?.();
464 source.advanceTime(3100);
465 source.mount();
466 source.flushFrame();
467 expect(source.highlight()).toBeUndefined();
468 expect(source.root.animations).toHaveLength(1);
469 expect(source.target.activationRef.current.dismissed).toBe(true);
470 source.cleanup();
471 });
472
473 it("dismisses an active text pulse without reviving it on remount", async () => {
474 const source = createSource();
475 source.mount();
476 source.flushFrame();
477 await source.finishScroll();
478 source.target.activationRef.current.dismissed = true;
479 source.cleanup();
480 expect(source.root.animations[0]?.cancel).toHaveBeenCalledOnce();
481 expect(source.highlight()).toBeUndefined();
482 expect(source.mount()).toBeUndefined();
483 source.flushFrame();
484 expect(source.root.animations).toHaveLength(1);
485 });
486
487 it("does not highlight a parent when the saved quote no longer matches", async () => {
488 const source = createSource();
489 mocks.resolveRange.mockReturnValue(null);
490 source.mount();
491 source.flushFrame();
492 await source.finishScroll();
493 expect(source.highlight()).toBeUndefined();
494 expect(source.root.animations).toHaveLength(0);
495 expect(source.root.focus).not.toHaveBeenCalled();
496 expect(source.target.onComplete).toHaveBeenCalledOnce();
497 source.cleanup();
498 });
499
500 it("cancels deferred positioning without capturing a pre-gesture offset or reviving dismissal", async () => {
501 const source = createSource();
502 source.mount();
503 source.flushFrame();
504 expect(source.scrollToOffset).toHaveBeenCalledWith({ offset: 80, animated: true });
505 source.target.activationRef.current.dismissed = true;
506 source.target.activationRef.current.cancelScroll?.();
507 source.scrollNode.scrollTop = 4300;
508 expect(source.scrollToOffset).toHaveBeenLastCalledWith({ offset: 4300, animated: false });
509 await source.finishScroll();
510 source.layoutChanged();
511 source.flushFrame();
512 expect(source.scrollNode.scrollTop).toBe(4300);
513 expect(source.target.activationRef.current.scrolled).toBe(false);
514 expect(source.target.onComplete).not.toHaveBeenCalled();
515 expect(source.highlight()).toBeUndefined();
516 expect(source.root.animations).toHaveLength(0);
517 source.cleanup();
518 expect(source.mount()).toBeUndefined();
519 source.flushFrame();
520 expect(source.scrollToOffset).toHaveBeenCalledTimes(2);
521 });
522
523 it("does not erase another highlight when its source unmounts", async () => {
524 const source = createSource();
525 source.mount();
526 source.flushFrame();
527 await source.finishScroll();
528 const replacement = new Set<TestRange>();
529 source.highlights.set("t3-assistant-citation", replacement);
530 source.cleanup();
531 expect(source.highlights.get("t3-assistant-citation")).toBe(replacement);
532 });
533
534 it("preserves a user's replacement selection in the native-selection fallback", async () => {
535 const source = createSource();
536 vi.stubGlobal("Highlight", undefined);
537 const selection = new TestSelection();
538 source.root.ownerDocument.getSelection = () => selection;
539 source.mount();
540 source.flushFrame();
541 await source.finishScroll();
542 expect(selection.ranges).toHaveLength(1);
543 expect(selection.ranges[0]?.startContainer).toBe(source.text);
544
545 const userRange = new TestRange(new TestElement(), () => rect(50));
546 selection.ranges = [userRange];
547 source.mutation(source.root);
548 source.flushFrame();
549 source.cleanup();
550 source.mount();
551 source.flushFrame();
552 expect(selection.ranges).toEqual([userRange]);
553 expect(source.scrollToOffset).toHaveBeenCalledTimes(1);
554 source.cleanup();
555 });
556
557 it("clears its own native-selection fallback when the pulse expires", async () => {
558 const source = createSource();
559 vi.stubGlobal("Highlight", undefined);
560 const selection = new TestSelection();
561 source.root.ownerDocument.getSelection = () => selection;
562 source.mount();
563 source.flushFrame();
564 await source.finishScroll();
565 expect(selection.ranges).toHaveLength(1);
566 await source.finishPulse();
567 expect(selection.ranges).toHaveLength(0);
568 source.cleanup();
569 });
570});
571
572describe("assistant citation comment source lifecycle", () => {
573 it("keeps the exact live range highlighted until cleanup without changing selection or navigation", () => {
574 const source = createSource();
575 const selection = new TestSelection();
576 const selectedRange = new TestRange(source.text, () => rect(40));
577 selection.addRange(selectedRange);
578 const getSelection = vi.fn(() => selection);
579 source.root.ownerDocument.getSelection = getSelection;
580 const navigationHighlight = new Set([new TestRange(source.text, () => rect(20))]);
581 source.highlights.set("t3-assistant-citation", navigationHighlight);
582 const comment = source.mountComment();
583
584 expect(source.commentHighlight()?.size).toBe(1);
585 expect(source.commentHighlight()?.values().next().value).toBe(comment.range);
586 expect(mocks.resolveRange).not.toHaveBeenCalled();
587 source.advanceTime(5000);
588 source.flushFrame();
589 expect(source.commentHighlight()?.has(comment.range)).toBe(true);
590 expect(source.root.animations).toHaveLength(0);
591 expect(source.scrollToOffset).not.toHaveBeenCalled();
592 expect(getSelection).not.toHaveBeenCalled();
593
594 comment.cleanup();
595 comment.cleanup();
596 expect(source.commentHighlight()).toBeUndefined();
597 expect(source.highlights.get("t3-assistant-citation")).toBe(navigationHighlight);
598 expect(selection.ranges).toEqual([selectedRange]);
599 expect(comment.onUnavailable).not.toHaveBeenCalled();
600 source.mutation(source.root);
601 expect(mocks.resolveRange).not.toHaveBeenCalled();
602 });
603
604 it("repairs changed source text in the same Range used by the popup anchor", () => {
605 const source = createSource();
606 const comment = source.mountComment();
607 const replacementText = new TestElement();
608 replacementText.parentNode = source.root;
609 const repaired = new TestRange(replacementText, () => rect(70));
610 repaired.startOffset = 7;
611 repaired.endOffset = 12;
612 mocks.resolveRange.mockReturnValue(repaired);
613
614 source.mutation(source.root);
615
616 expect(mocks.resolveRange).toHaveBeenCalledOnce();
617 expect(comment.range.startContainer).toBe(replacementText);
618 expect(comment.range.endContainer).toBe(replacementText);
619 expect(comment.range.startOffset).toBe(7);
620 expect(comment.range.endOffset).toBe(12);
621 expect(comment.range.collapsed).toBe(false);
622 expect(source.commentHighlight()?.size).toBe(1);
623 expect(source.commentHighlight()?.values().next().value).toBe(comment.range);
624 expect(source.commentHighlight()?.has(repaired)).toBe(false);
625 expect(comment.onUnavailable).not.toHaveBeenCalled();
626 source.cleanup();
627 });
628
629 it.each(["collapsed", "escaped"])("repairs a %s range after a virtual ancestor move", (state) => {
630 const source = createSource();
631 const comment = source.mountComment();
632 if (state === "collapsed") {
633 comment.range.collapseTo(source.scrollNode);
634 } else {
635 comment.range.startContainer = new TestElement();
636 }
637
638 source.mutation(source.scrollNode, [source.container]);
639
640 expect(comment.range.startContainer).toBe(source.text);
641 expect(comment.range.endContainer).toBe(source.text);
642 expect(comment.range.collapsed).toBe(false);
643 expect(source.commentHighlight()?.has(comment.range)).toBe(true);
644 expect(comment.onUnavailable).not.toHaveBeenCalled();
645 source.cleanup();
646 });
647
648 it("clears and disconnects once when the selected quote can no longer be repaired", () => {
649 const source = createSource();
650 const comment = source.mountComment();
651 mocks.resolveRange.mockReturnValue(null);
652
653 source.mutation(source.root);
654
655 expect(comment.onUnavailable).toHaveBeenCalledOnce();
656 expect(source.commentHighlight()).toBeUndefined();
657 source.mutation(source.root);
658 comment.cleanup();
659 expect(mocks.resolveRange).toHaveBeenCalledOnce();
660 expect(comment.onUnavailable).toHaveBeenCalledOnce();
661 });
662
663 it.each(["disconnected", "outside viewport"])("closes once when the source is %s", (state) => {
664 const source = createSource();
665 const comment = source.mountComment();
666 if (state === "disconnected") {
667 source.root.isConnected = false;
668 } else {
669 source.root.parentNode = new TestElement();
670 }
671
672 source.mutation(source.scrollNode, [source.container]);
673 source.mutation(source.scrollNode, [source.container]);
674 comment.cleanup();
675
676 expect(comment.onUnavailable).toHaveBeenCalledOnce();
677 expect(source.commentHighlight()).toBeUndefined();
678 expect(mocks.resolveRange).not.toHaveBeenCalled();
679 });
680
681 it("rejects an already detached source without registering a highlight", () => {
682 const source = createSource();
683 source.root.isConnected = false;
684 const comment = source.mountComment();
685
686 expect(comment.onUnavailable).toHaveBeenCalledOnce();
687 expect(source.commentHighlight()).toBeUndefined();
688 source.mutation(source.root);
689 comment.cleanup();
690 expect(comment.onUnavailable).toHaveBeenCalledOnce();
691 expect(mocks.resolveRange).not.toHaveBeenCalled();
692 });
693
694 it("keeps distinct editors' ranges independent through one shared highlight", () => {
695 const source = createSource();
696 const first = source.mountComment();
697 const second = source.mountComment();
698 expect(source.commentHighlight()?.size).toBe(2);
699
700 first.cleanup();
701 first.cleanup();
702
703 expect(source.commentHighlight()?.size).toBe(1);
704 expect(source.commentHighlight()?.has(second.range)).toBe(true);
705 expect(second.onUnavailable).not.toHaveBeenCalled();
706 second.cleanup();
707 expect(source.commentHighlight()).toBeUndefined();
708 });
709
710 it("does not delete a replacement highlight when an older editor closes", () => {
711 const source = createSource();
712 const comment = source.mountComment();
713 const original = source.commentHighlight();
714 const replacement = new Set([new TestRange(source.text, () => rect(90))]);
715 source.highlights.set("t3-assistant-citation-comment", replacement);
716
717 comment.cleanup();
718
719 expect(original?.size).toBe(0);
720 expect(source.commentHighlight()).toBe(replacement);
721 expect(replacement.size).toBe(1);
722 });
723
724 it("keeps native selection untouched when CSS highlights are unavailable", () => {
725 const source = createSource();
726 vi.stubGlobal("Highlight", undefined);
727 const selection = new TestSelection();
728 const selectedRange = new TestRange(source.text, () => rect(40));
729 selection.addRange(selectedRange);
730 const getSelection = vi.fn(() => selection);
731 source.root.ownerDocument.getSelection = getSelection;
732 const comment = source.mountComment();
733 source.mutation(source.root);
734
735 expect(source.commentHighlight()).toBeUndefined();
736 expect(getSelection).not.toHaveBeenCalled();
737 expect(selection.ranges).toEqual([selectedRange]);
738 expect(comment.onUnavailable).not.toHaveBeenCalled();
739 source.root.isConnected = false;
740 source.mutation(source.scrollNode, [source.container]);
741 expect(comment.onUnavailable).toHaveBeenCalledOnce();
742 source.cleanup();
743 });
744});