@sentropic/design-system-svelte 0.42.0 → 0.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1621 @@
1
+ <script lang="ts" module>
2
+ import type { Snippet } from "svelte";
3
+ import type { HTMLAttributes } from "svelte/elements";
4
+ import type {
5
+ AnchorPayload,
6
+ CollaborationActor,
7
+ CommentTarget,
8
+ ReviewComment,
9
+ ReviewThread,
10
+ ThreadFilter,
11
+ ThreadReadState,
12
+ } from "@sentropic/design-system-review-core";
13
+
14
+ export type ReviewMode = "view" | "review";
15
+
16
+ export interface CommentLayerCreatePayload {
17
+ target: CommentTarget;
18
+ sectionKey: string;
19
+ body: string;
20
+ }
21
+
22
+ export interface CommentLayerComposerContext {
23
+ anchor: AnchorPayload;
24
+ sectionKey: string | null;
25
+ error: string | null;
26
+ submit: (body: string) => Promise<void>;
27
+ cancel: () => void;
28
+ }
29
+
30
+ export type CommentLayerProps = Omit<HTMLAttributes<HTMLDivElement>, "class"> & {
31
+ /** Artifact root element (e.g. bearing `data-review-root`). Optional when wrapping slotted `children`. */
32
+ rootEl?: HTMLElement | null;
33
+ /** Host-controlled review mode (`"view"` leaves artifact untouched; `"review"` overlays pins & picking). */
34
+ mode?: ReviewMode;
35
+ /** Target identity (`kind` + `id`) used to mint new comment targets even when `comments` is empty. */
36
+ target: Pick<CommentTarget, "kind" | "id">;
37
+ /** Current rendered artifact version stamped into new anchors as `v` and passed to `resolveAnchor`. */
38
+ artifactVersion: string;
39
+ /** Flat comments for this artifact. */
40
+ comments: readonly ReviewComment[];
41
+ currentUser: CollaborationActor;
42
+ activeThreadId?: string | null;
43
+ readState?: ThreadReadState | null;
44
+ canModerate?: boolean;
45
+ /** Explicit visibility control for the integrated `ThreadPanel` (auto-opens in review mode when panel callbacks are bound). */
46
+ panelOpen?: boolean;
47
+ /** Active filter forwarded to the integrated `ThreadPanel`. */
48
+ panelFilter?: ThreadFilter;
49
+ /** Explicit `<48rem` bottom-sheet override forwarded to the integrated `ThreadPanel`. */
50
+ panelCompact?: boolean;
51
+ /** Debounce before showing the floating "Add comment" trigger after text selection (default 150ms). */
52
+ selectionSettleMs?: number;
53
+ class?: string;
54
+ onCreate?: (payload: CommentLayerCreatePayload) => void | Promise<void>;
55
+ onSelect?: (threadId: string | null) => void;
56
+ onMarkRead?: (threadId: string) => void;
57
+ onModeChange?: (mode: ReviewMode) => void;
58
+ /** Called whenever resolved vs orphaned thread partition changes against the live DOM. */
59
+ onOrphansChange?: (orphaned: ReviewThread[]) => void;
60
+ onPanelFilterChange?: (filter: ThreadFilter) => void;
61
+ onPanelClose?: () => void;
62
+ /** Forwarded panel/thread mutation callbacks wired into the integrated `ThreadPanel`. */
63
+ onReply?: (threadId: string, body: string) => void | Promise<void>;
64
+ onResolve?: (threadId: string) => void | Promise<void>;
65
+ onReopen?: (threadId: string) => void | Promise<void>;
66
+ onEditComment?: (commentId: string, body: string) => void | Promise<void>;
67
+ onDeleteComment?: (commentId: string) => void | Promise<void>;
68
+ onReanchor?: (threadId: string) => void | Promise<void>;
69
+ /** Optional slotted artifact content (used when `rootEl` is not supplied externally). */
70
+ children?: Snippet;
71
+ /** Optional custom composer slot `{ anchor, sectionKey, error, submit, cancel }`. */
72
+ composer?: Snippet<[CommentLayerComposerContext]>;
73
+ };
74
+ </script>
75
+
76
+ <script lang="ts">
77
+ import { tick, untrack } from "svelte";
78
+ import {
79
+ countUnreadComments,
80
+ createAnchorFromElement,
81
+ createAnchorFromSelection,
82
+ groupCommentsIntoThreads,
83
+ isUnread,
84
+ layoutPins,
85
+ resolveAnchor,
86
+ tryEncodeAnchor,
87
+ type PositionedPin,
88
+ } from "@sentropic/design-system-review-core";
89
+ import Button from "./Button.svelte";
90
+ import CommentComposer from "./CommentComposer.svelte";
91
+ import CommentPin from "./CommentPin.svelte";
92
+ import ThreadPanel from "./ThreadPanel.svelte";
93
+ import {
94
+ formatAnchorLabel,
95
+ formatPinAriaLabel,
96
+ getFocusableElements,
97
+ handleFocusTrapKeydown,
98
+ } from "./review-markdown.js";
99
+
100
+ interface OverlayBox {
101
+ top: number;
102
+ left: number;
103
+ width: number;
104
+ height: number;
105
+ }
106
+
107
+ interface ResolvedEntry {
108
+ thread: ReviewThread;
109
+ anchorKind: "text" | "element" | "region";
110
+ element: Element;
111
+ range: Range | null;
112
+ box: OverlayBox;
113
+ index: number;
114
+ }
115
+
116
+ interface PinCluster {
117
+ id: string;
118
+ entries: ResolvedEntry[];
119
+ box: OverlayBox;
120
+ primaryIndex: number;
121
+ totalComments: number;
122
+ unreadCount: number;
123
+ allResolved: boolean;
124
+ anyActive: boolean;
125
+ variant: "inline" | "element" | "cluster";
126
+ ariaLabel: string;
127
+ }
128
+
129
+ interface PendingSelection {
130
+ anchor: AnchorPayload;
131
+ top: number;
132
+ left: number;
133
+ }
134
+
135
+ interface ComposerSession {
136
+ anchor: AnchorPayload;
137
+ sectionKey: string | null;
138
+ error: string | null;
139
+ top: number;
140
+ left: number;
141
+ invoker: HTMLElement | null;
142
+ }
143
+
144
+ const COMMENTABLE_FALLBACK_SELECTOR =
145
+ "p, h1, h2, h3, h4, h5, h6, li, figure, table, blockquote, pre, [data-anchor-id]";
146
+ const INTERACTIVE_SUPPRESSED_SELECTOR =
147
+ 'a, button, input, select, textarea, summary, [role="button"], [role="link"]';
148
+ const HIGHLIGHT_OPEN = "st-review-text";
149
+ const HIGHLIGHT_ACTIVE = "st-review-text-active";
150
+ const HIGHLIGHT_RESOLVED = "st-review-text-resolved";
151
+
152
+ let {
153
+ rootEl = null,
154
+ mode = "view",
155
+ target,
156
+ artifactVersion,
157
+ comments,
158
+ currentUser,
159
+ activeThreadId,
160
+ readState = null,
161
+ canModerate = false,
162
+ panelOpen,
163
+ panelFilter,
164
+ panelCompact,
165
+ selectionSettleMs = 150,
166
+ class: className,
167
+ onCreate,
168
+ onSelect,
169
+ onMarkRead,
170
+ onModeChange,
171
+ onOrphansChange,
172
+ onPanelFilterChange,
173
+ onPanelClose,
174
+ onReply,
175
+ onResolve,
176
+ onReopen,
177
+ onEditComment,
178
+ onDeleteComment,
179
+ onReanchor,
180
+ children,
181
+ composer,
182
+ ...rest
183
+ }: CommentLayerProps = $props();
184
+
185
+ let layerEl: HTMLElement | undefined = $state();
186
+ let slotHostEl: HTMLElement | undefined = $state();
187
+ let overlayEl: HTMLElement | undefined = $state();
188
+ let panelHostEl: HTMLElement | undefined = $state();
189
+ let clusterPopoverEl: HTMLElement | undefined = $state();
190
+ let selectionTriggerEl: HTMLElement | undefined = $state();
191
+ let confirmDialogEl: HTMLElement | undefined = $state();
192
+
193
+ let domRevision = $state(0);
194
+ let hoverBox = $state<OverlayBox | null>(null);
195
+ let flashBox = $state<OverlayBox | null>(null);
196
+ let pendingSelection = $state<PendingSelection | null>(null);
197
+ let composerSession = $state<ComposerSession | null>(null);
198
+ let draftBody = $state("");
199
+ let confirmDiscardOpen = $state(false);
200
+ let openClusterId = $state<string | null>(null);
201
+ let liveAnnouncement = $state("");
202
+ let internalActiveThreadId = $state<string | null>(null);
203
+ let panelDismissed = $state(false);
204
+
205
+ const effectiveActiveThreadId = $derived(
206
+ activeThreadId !== undefined ? activeThreadId : internalActiveThreadId,
207
+ );
208
+ const hasPanelCallbacks = $derived(
209
+ onReply !== undefined ||
210
+ onResolve !== undefined ||
211
+ onReopen !== undefined ||
212
+ onEditComment !== undefined ||
213
+ onDeleteComment !== undefined ||
214
+ onReanchor !== undefined,
215
+ );
216
+ const panelMounted = $derived(panelOpen !== undefined || hasPanelCallbacks);
217
+ const effectivePanelOpen = $derived(
218
+ panelOpen !== undefined ? panelOpen : mode === "review" && hasPanelCallbacks && !panelDismissed,
219
+ );
220
+
221
+ let prevMode: ReviewMode = untrack(() => mode);
222
+ let prevOrphanIds = new Set<string>();
223
+ let mutationQueued = false;
224
+ let flashTimer: ReturnType<typeof setTimeout> | undefined;
225
+ let selectionTimer: ReturnType<typeof setTimeout> | undefined;
226
+ let selectionTriggerReleaseTimer: ReturnType<typeof setTimeout> | undefined;
227
+ let selectionTriggerPressed = false;
228
+ let clusterInvoker: HTMLElement | null = null;
229
+ let confirmReturnFocus: HTMLElement | null = null;
230
+
231
+ const effectiveRoot = $derived.by<HTMLElement | null>(() => {
232
+ // Re-read domRevision only for anchor resolution; root lookup tracks rootEl/slotHostEl.
233
+ if (rootEl) return rootEl;
234
+ if (!slotHostEl) return null;
235
+ const explicit = slotHostEl.querySelector<HTMLElement>("[data-review-root]");
236
+ return explicit ?? slotHostEl;
237
+ });
238
+
239
+ const threads = $derived(groupCommentsIntoThreads(comments));
240
+
241
+ function relativeBox(
242
+ rootRect: DOMRect,
243
+ rect: { top: number; left: number; width: number; height: number },
244
+ ): OverlayBox {
245
+ return {
246
+ top: rect.top - rootRect.top,
247
+ left: rect.left - rootRect.left,
248
+ width: rect.width,
249
+ height: rect.height,
250
+ };
251
+ }
252
+
253
+ function safeRangeRect(range: Range, fallbackEl: Element): DOMRect {
254
+ if (typeof range.getBoundingClientRect === "function") {
255
+ const rect = range.getBoundingClientRect();
256
+ if (rect.width > 0 || rect.height > 0) {
257
+ return rect;
258
+ }
259
+ }
260
+ return fallbackEl.getBoundingClientRect();
261
+ }
262
+
263
+ function compareDomOrder(a: ResolvedEntry, b: ResolvedEntry): number {
264
+ if (a.element !== b.element) {
265
+ const pos = a.element.compareDocumentPosition(b.element);
266
+ if (pos & Node.DOCUMENT_POSITION_FOLLOWING) return -1;
267
+ if (pos & Node.DOCUMENT_POSITION_PRECEDING) return 1;
268
+ }
269
+ if (a.range && b.range) {
270
+ try {
271
+ const cmp = a.range.compareBoundaryPoints(Range.START_TO_START, b.range);
272
+ if (cmp !== 0) return cmp;
273
+ } catch {
274
+ // Detached ranges fall through to geometric comparison.
275
+ }
276
+ }
277
+ if (a.box.top !== b.box.top) return a.box.top - b.box.top;
278
+ const aTime = a.thread.comments[0]?.createdAt ?? "";
279
+ const bTime = b.thread.comments[0]?.createdAt ?? "";
280
+ return aTime < bTime ? -1 : aTime > bTime ? 1 : 0;
281
+ }
282
+
283
+ const resolution = $derived.by(() => {
284
+ // Depend on domRevision and mode so observer/scroll/resize updates and mode toggles
285
+ // re-measure rootEl vs layerEl and re-resolve anchors.
286
+ void domRevision;
287
+ void mode;
288
+ const root = effectiveRoot;
289
+ const layer = layerEl;
290
+ const resolved: ResolvedEntry[] = [];
291
+ const orphaned: ReviewThread[] = [];
292
+
293
+ if (!root) {
294
+ return { resolved, orphaned, rootHeight: 0, overlayBox: null as OverlayBox | null };
295
+ }
296
+
297
+ const rootRect = root.getBoundingClientRect();
298
+ const overlayBox: OverlayBox | null = layer
299
+ ? (() => {
300
+ const layerRect = layer.getBoundingClientRect();
301
+ return {
302
+ top: rootRect.top - layerRect.top,
303
+ left: rootRect.left - layerRect.left,
304
+ width: rootRect.width,
305
+ height: rootRect.height,
306
+ };
307
+ })()
308
+ : null;
309
+
310
+ for (const thread of threads) {
311
+ if (thread.anchor === null) {
312
+ orphaned.push(thread);
313
+ continue;
314
+ }
315
+
316
+ const match = resolveAnchor(root, thread.anchor, { artifactVersion });
317
+ if (match.status === "orphan") {
318
+ orphaned.push(thread);
319
+ continue;
320
+ }
321
+
322
+ let targetRect: { top: number; left: number; width: number; height: number };
323
+ if (match.kind === "region") {
324
+ targetRect = {
325
+ top: rootRect.top + match.rect.y * rootRect.height,
326
+ left: rootRect.left + match.rect.x * rootRect.width,
327
+ width: match.rect.width * rootRect.width,
328
+ height: match.rect.height * rootRect.height,
329
+ };
330
+ } else if (match.kind === "text" && match.range) {
331
+ targetRect = safeRangeRect(match.range, match.element);
332
+ } else {
333
+ targetRect = match.element.getBoundingClientRect();
334
+ }
335
+
336
+ resolved.push({
337
+ thread,
338
+ anchorKind: match.kind,
339
+ element: match.element,
340
+ range: match.range,
341
+ box: relativeBox(rootRect, targetRect),
342
+ index: 0,
343
+ });
344
+ }
345
+
346
+ resolved.sort(compareDomOrder);
347
+ resolved.forEach((entry, idx) => {
348
+ entry.index = idx + 1;
349
+ });
350
+
351
+ return { resolved, orphaned, rootHeight: rootRect.height, overlayBox };
352
+ });
353
+
354
+ const clusters = $derived.by<PinCluster[]>(() => {
355
+ const groups: ResolvedEntry[][] = [];
356
+ const elementGroups = new Map<Element, ResolvedEntry[]>();
357
+ const sectionGroups = new Map<string, ResolvedEntry[]>();
358
+
359
+ for (const entry of resolution.resolved) {
360
+ if (entry.anchorKind === "element" || (entry.anchorKind === "text" && entry.range === null)) {
361
+ const existing = elementGroups.get(entry.element);
362
+ if (existing) {
363
+ existing.push(entry);
364
+ } else {
365
+ const bucket = [entry];
366
+ elementGroups.set(entry.element, bucket);
367
+ groups.push(bucket);
368
+ }
369
+ } else if (entry.thread.sectionKey) {
370
+ const existing = sectionGroups.get(entry.thread.sectionKey);
371
+ if (existing) {
372
+ existing.push(entry);
373
+ } else {
374
+ const bucket = [entry];
375
+ sectionGroups.set(entry.thread.sectionKey, bucket);
376
+ groups.push(bucket);
377
+ }
378
+ } else {
379
+ groups.push([entry]);
380
+ }
381
+ }
382
+
383
+ return groups.map((entries) => {
384
+ const first = entries[0]!;
385
+ const totalComments = entries.reduce((sum, e) => sum + e.thread.comments.length, 0);
386
+ const unreadCount = entries.reduce(
387
+ (sum, e) => sum + countUnreadComments(e.thread, currentUser, readState),
388
+ 0,
389
+ );
390
+ const allResolved = entries.every((e) => e.thread.state === "closed");
391
+ const anyActive = entries.some((e) => e.thread.threadId === effectiveActiveThreadId);
392
+ const isCluster = entries.length > 1;
393
+ const excerpt = formatAnchorLabel(first.thread.anchor, 60);
394
+ const ariaLabel = isCluster
395
+ ? `${entries.length} threads clustered, ${totalComments} comments${unreadCount > 0 ? `, ${unreadCount} unread` : ""}, on '${excerpt}'`
396
+ : formatPinAriaLabel({
397
+ index: first.index,
398
+ count: totalComments,
399
+ unreadCount,
400
+ resolved: allResolved,
401
+ excerpt,
402
+ });
403
+
404
+ return {
405
+ id: entries.map((e) => e.thread.threadId).join("+"),
406
+ entries,
407
+ box: first.box,
408
+ primaryIndex: first.index,
409
+ totalComments,
410
+ unreadCount,
411
+ allResolved,
412
+ anyActive,
413
+ variant: isCluster ? "cluster" : first.anchorKind === "element" ? "element" : "inline",
414
+ ariaLabel,
415
+ };
416
+ });
417
+ });
418
+
419
+ const gutterPins = $derived.by<Array<{ cluster: PinCluster; positioned: PositionedPin }>>(() => {
420
+ if (clusters.length === 0) return [];
421
+ const byId = new Map(clusters.map((cluster) => [cluster.id, cluster]));
422
+ const positioned = layoutPins(
423
+ clusters.map((cluster) => ({ id: cluster.id, targetY: cluster.box.top })),
424
+ {
425
+ gap: 28,
426
+ minY: 0,
427
+ maxY: resolution.rootHeight > 0 ? Math.max(0, resolution.rootHeight - 24) : undefined,
428
+ },
429
+ );
430
+ return positioned
431
+ .map((item) => {
432
+ const cluster = byId.get(item.id);
433
+ return cluster ? { cluster, positioned: item } : null;
434
+ })
435
+ .filter((entry): entry is { cluster: PinCluster; positioned: PositionedPin } => entry !== null);
436
+ });
437
+
438
+ const openCluster = $derived(
439
+ openClusterId ? clusters.find((cluster) => cluster.id === openClusterId) ?? null : null,
440
+ );
441
+
442
+ // Notify host of orphan partition changes and politely announce newly orphaned threads.
443
+ $effect(() => {
444
+ const orphans = resolution.orphaned;
445
+ onOrphansChange?.(orphans);
446
+
447
+ const nextIds = new Set(orphans.map((t) => t.threadId));
448
+ let newlyOrphaned = 0;
449
+ for (const id of nextIds) {
450
+ if (!prevOrphanIds.has(id)) {
451
+ newlyOrphaned += 1;
452
+ }
453
+ }
454
+ if (newlyOrphaned > 0 && mode === "review") {
455
+ liveAnnouncement =
456
+ newlyOrphaned === 1
457
+ ? "1 comment thread is now unattached (orphan)."
458
+ : `${newlyOrphaned} comment threads are now unattached (orphans).`;
459
+ }
460
+ prevOrphanIds = nextIds;
461
+ });
462
+
463
+ // Guard review -> view exit when an unsaved draft is open.
464
+ $effect(() => {
465
+ const current = mode;
466
+ if (prevMode === "review" && current === "view") {
467
+ if (composerSession !== null && draftBody.trim().length > 0) {
468
+ const active = typeof document !== "undefined" ? document.activeElement : null;
469
+ confirmReturnFocus =
470
+ active instanceof HTMLElement && !(overlayEl && overlayEl.contains(active))
471
+ ? active
472
+ : composerSession.invoker;
473
+ confirmDiscardOpen = true;
474
+ } else {
475
+ clearTransientState();
476
+ }
477
+ } else if (current === "review") {
478
+ confirmDiscardOpen = false;
479
+ confirmReturnFocus = null;
480
+ panelDismissed = false;
481
+ }
482
+ prevMode = current;
483
+ });
484
+
485
+ // Sync CSS Custom Highlight API when supported (pin-only fallback otherwise).
486
+ $effect(() => {
487
+ const isReview = mode === "review";
488
+ const entries = resolution.resolved;
489
+ const currentActiveId = effectiveActiveThreadId;
490
+
491
+ const applyHighlights = (active: boolean) => {
492
+ if (
493
+ typeof CSS === "undefined" ||
494
+ CSS === null ||
495
+ !("highlights" in CSS) ||
496
+ typeof Highlight === "undefined"
497
+ ) {
498
+ return;
499
+ }
500
+ const registry = (CSS as unknown as { highlights: Map<string, unknown> }).highlights;
501
+ registry.delete(HIGHLIGHT_OPEN);
502
+ registry.delete(HIGHLIGHT_ACTIVE);
503
+ registry.delete(HIGHLIGHT_RESOLVED);
504
+ if (!active) return;
505
+
506
+ const openRanges: Range[] = [];
507
+ const activeRanges: Range[] = [];
508
+ const resolvedRanges: Range[] = [];
509
+
510
+ for (const entry of entries) {
511
+ if (!entry.range) continue;
512
+ if (entry.thread.threadId === currentActiveId) {
513
+ activeRanges.push(entry.range);
514
+ } else if (entry.thread.state === "closed") {
515
+ resolvedRanges.push(entry.range);
516
+ } else {
517
+ openRanges.push(entry.range);
518
+ }
519
+ }
520
+
521
+ if (openRanges.length > 0) registry.set(HIGHLIGHT_OPEN, new Highlight(...openRanges));
522
+ if (activeRanges.length > 0) registry.set(HIGHLIGHT_ACTIVE, new Highlight(...activeRanges));
523
+ if (resolvedRanges.length > 0) {
524
+ registry.set(HIGHLIGHT_RESOLVED, new Highlight(...resolvedRanges));
525
+ }
526
+ };
527
+
528
+ applyHighlights(isReview);
529
+ return () => applyHighlights(false);
530
+ });
531
+
532
+ // Observe artifact DOM mutations & resizes while in review mode so anchors re-attach after re-render.
533
+ $effect(() => {
534
+ const root = effectiveRoot;
535
+ if (mode !== "review" || !root) return;
536
+
537
+ const scheduleRefresh = () => {
538
+ if (mutationQueued) return;
539
+ mutationQueued = true;
540
+ queueMicrotask(() => {
541
+ mutationQueued = false;
542
+ domRevision += 1;
543
+ });
544
+ };
545
+
546
+ const observer =
547
+ typeof MutationObserver !== "undefined"
548
+ ? new MutationObserver((records) => {
549
+ // Ignore mutations originating exclusively inside our own overlay if nested.
550
+ const relevant = records.some(
551
+ (rec) => !overlayEl || !overlayEl.contains(rec.target),
552
+ );
553
+ if (relevant) {
554
+ scheduleRefresh();
555
+ }
556
+ })
557
+ : null;
558
+
559
+ observer?.observe(root, {
560
+ childList: true,
561
+ subtree: true,
562
+ characterData: true,
563
+ attributes: true,
564
+ attributeFilter: ["data-anchor-id", "data-commentable"],
565
+ });
566
+
567
+ const resizeObserver =
568
+ typeof ResizeObserver !== "undefined" ? new ResizeObserver(scheduleRefresh) : null;
569
+ resizeObserver?.observe(root);
570
+ if (layerEl && layerEl !== root) {
571
+ resizeObserver?.observe(layerEl);
572
+ }
573
+
574
+ window.addEventListener("resize", scheduleRefresh, { passive: true });
575
+ window.addEventListener("scroll", scheduleRefresh, { capture: true, passive: true });
576
+
577
+ return () => {
578
+ observer?.disconnect();
579
+ resizeObserver?.disconnect();
580
+ window.removeEventListener("resize", scheduleRefresh);
581
+ window.removeEventListener("scroll", scheduleRefresh, { capture: true });
582
+ };
583
+ });
584
+
585
+ // Picking listeners (click, hover/focus outline, 150ms text selection settle, Alt+Shift+C).
586
+ $effect(() => {
587
+ const root = effectiveRoot;
588
+ if (mode !== "review" || !root) {
589
+ hoverBox = null;
590
+ return;
591
+ }
592
+
593
+ const doc = root.ownerDocument;
594
+
595
+ const isInsideOverlay = (node: Node | null): boolean =>
596
+ node !== null &&
597
+ ((overlayEl !== undefined && overlayEl.contains(node)) ||
598
+ (panelHostEl !== undefined && panelHostEl.contains(node)));
599
+
600
+ const isEditableElement = (el: EventTarget | null): boolean => {
601
+ if (!el || typeof (el as Element).tagName !== "string") return false;
602
+ const tag = (el as Element).tagName.toUpperCase();
603
+ if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT") return true;
604
+ return (el as HTMLElement).isContentEditable === true;
605
+ };
606
+
607
+ const isPassthrough = (el: Element): boolean => {
608
+ const match = el.closest("[data-review-passthrough]");
609
+ return match !== null && root.contains(match);
610
+ };
611
+
612
+ const findCommentable = (el: Element): HTMLElement | null => {
613
+ if (!root.contains(el) || isInsideOverlay(el)) return null;
614
+ const explicit = el.closest("[data-commentable]");
615
+ if (explicit && root.contains(explicit)) {
616
+ return explicit as HTMLElement;
617
+ }
618
+ const fallback = el.closest(COMMENTABLE_FALLBACK_SELECTOR);
619
+ if (fallback && root.contains(fallback)) {
620
+ return fallback as HTMLElement;
621
+ }
622
+ return null;
623
+ };
624
+
625
+ const handleRootClick = (event: MouseEvent) => {
626
+ const targetNode = event.target as Element | null;
627
+ if (!targetNode || isInsideOverlay(targetNode)) return;
628
+ if (isPassthrough(targetNode)) return;
629
+
630
+ // Suppress clicks on links/buttons inside the artifact during review mode.
631
+ const interactive = targetNode.closest(INTERACTIVE_SUPPRESSED_SELECTOR);
632
+ if (interactive && root.contains(interactive) && !interactive.hasAttribute("data-commentable")) {
633
+ event.preventDefault();
634
+ event.stopPropagation();
635
+ return;
636
+ }
637
+
638
+ // If the user just dragged a non-collapsed text selection inside root, let selection flow own it.
639
+ const selection = doc.defaultView?.getSelection();
640
+ if (
641
+ selection &&
642
+ selection.rangeCount > 0 &&
643
+ !selection.getRangeAt(0).collapsed &&
644
+ root.contains(selection.getRangeAt(0).commonAncestorContainer)
645
+ ) {
646
+ return;
647
+ }
648
+
649
+ const commentable = findCommentable(targetNode);
650
+ if (!commentable) return;
651
+
652
+ const anchor = createAnchorFromElement(root, commentable, artifactVersion);
653
+ if (!anchor) return;
654
+ const box = relativeBox(root.getBoundingClientRect(), commentable.getBoundingClientRect());
655
+ pendingSelection = null;
656
+ openClusterId = null;
657
+ openComposerForAnchor(anchor, commentable, box.top + box.height, box.left);
658
+ };
659
+
660
+ const updateHover = (targetNode: Element | null) => {
661
+ if (!targetNode || isInsideOverlay(targetNode) || isPassthrough(targetNode)) {
662
+ hoverBox = null;
663
+ return;
664
+ }
665
+ const interactive = targetNode.closest(INTERACTIVE_SUPPRESSED_SELECTOR);
666
+ if (interactive && root.contains(interactive) && !interactive.hasAttribute("data-commentable")) {
667
+ hoverBox = null;
668
+ return;
669
+ }
670
+ const commentable = findCommentable(targetNode);
671
+ if (!commentable) {
672
+ hoverBox = null;
673
+ return;
674
+ }
675
+ hoverBox = relativeBox(root.getBoundingClientRect(), commentable.getBoundingClientRect());
676
+ };
677
+
678
+ const handlePointerOver = (event: Event) => updateHover(event.target as Element | null);
679
+ const handlePointerLeave = () => {
680
+ hoverBox = null;
681
+ };
682
+ const handleFocusIn = (event: FocusEvent) => updateHover(event.target as Element | null);
683
+ const handleFocusOut = (event: FocusEvent) => {
684
+ const related = event.relatedTarget as Node | null;
685
+ if (!related || !root.contains(related)) {
686
+ hoverBox = null;
687
+ }
688
+ };
689
+
690
+ const isTriggerEngaged = (): boolean =>
691
+ selectionTriggerPressed ||
692
+ (selectionTriggerEl !== undefined &&
693
+ doc.activeElement !== null &&
694
+ selectionTriggerEl.contains(doc.activeElement));
695
+
696
+ const hasValidRootSelection = (): boolean => {
697
+ const selection = doc.defaultView?.getSelection();
698
+ if (!selection || selection.rangeCount === 0) return false;
699
+ const range = selection.getRangeAt(0);
700
+ return (
701
+ !range.collapsed &&
702
+ range.toString().trim().length > 0 &&
703
+ root.contains(range.commonAncestorContainer) &&
704
+ !isInsideOverlay(range.commonAncestorContainer) &&
705
+ !isEditableElement(doc.activeElement)
706
+ );
707
+ };
708
+
709
+ const handleSelectionChange = () => {
710
+ if (selectionTimer !== undefined) {
711
+ clearTimeout(selectionTimer);
712
+ selectionTimer = undefined;
713
+ }
714
+ const selection = doc.defaultView?.getSelection();
715
+ if (!selection || selection.rangeCount === 0) {
716
+ if (!isTriggerEngaged()) {
717
+ pendingSelection = null;
718
+ }
719
+ return;
720
+ }
721
+ const range = selection.getRangeAt(0);
722
+ if (
723
+ range.collapsed ||
724
+ range.toString().trim().length === 0 ||
725
+ !root.contains(range.commonAncestorContainer) ||
726
+ isInsideOverlay(range.commonAncestorContainer) ||
727
+ isEditableElement(doc.activeElement)
728
+ ) {
729
+ if (!isTriggerEngaged()) {
730
+ pendingSelection = null;
731
+ }
732
+ return;
733
+ }
734
+
735
+ const cloned = range.cloneRange();
736
+ selectionTimer = setTimeout(() => {
737
+ selectionTimer = undefined;
738
+ if (!root.contains(cloned.commonAncestorContainer)) {
739
+ pendingSelection = null;
740
+ return;
741
+ }
742
+ const anchor = createAnchorFromSelection(root, cloned, artifactVersion);
743
+ if (!anchor) {
744
+ pendingSelection = null;
745
+ return;
746
+ }
747
+ const rootRect = root.getBoundingClientRect();
748
+ const fallbackEl =
749
+ cloned.endContainer.nodeType === Node.ELEMENT_NODE
750
+ ? (cloned.endContainer as Element)
751
+ : cloned.endContainer.parentElement ?? root;
752
+ const rect = safeRangeRect(cloned, fallbackEl);
753
+ pendingSelection = {
754
+ anchor,
755
+ top: rect.bottom - rootRect.top,
756
+ left: Math.max(0, rect.right - rootRect.left),
757
+ };
758
+ }, selectionSettleMs);
759
+ };
760
+
761
+ const handleSelectionTriggerPointerRelease = () => {
762
+ if (!selectionTriggerPressed) return;
763
+ if (selectionTriggerReleaseTimer !== undefined) {
764
+ clearTimeout(selectionTriggerReleaseTimer);
765
+ }
766
+ // Keep the trigger mounted past mouseup/pointerup until click fires.
767
+ selectionTriggerReleaseTimer = setTimeout(() => {
768
+ selectionTriggerReleaseTimer = undefined;
769
+ selectionTriggerPressed = false;
770
+ if (!pendingSelection || composerSession) return;
771
+ if (!isTriggerEngaged() && !hasValidRootSelection()) {
772
+ pendingSelection = null;
773
+ }
774
+ }, 0);
775
+ };
776
+
777
+ const handleGlobalKeydown = (event: KeyboardEvent) => {
778
+ if (event.key === "Escape") {
779
+ if (confirmDiscardOpen) {
780
+ return;
781
+ }
782
+ if (openClusterId && !composerSession) {
783
+ const activeEl = doc.activeElement;
784
+ const onInvoker =
785
+ clusterInvoker !== null &&
786
+ activeEl !== null &&
787
+ (activeEl === clusterInvoker || clusterInvoker.contains(activeEl));
788
+ const inPopover =
789
+ clusterPopoverEl !== undefined &&
790
+ activeEl !== null &&
791
+ clusterPopoverEl.contains(activeEl);
792
+ if (onInvoker || inPopover) {
793
+ event.preventDefault();
794
+ event.stopPropagation();
795
+ const invoker = clusterInvoker;
796
+ openClusterId = null;
797
+ clusterInvoker = null;
798
+ invoker?.focus();
799
+ return;
800
+ }
801
+ }
802
+ if (pendingSelection && !composerSession && !openClusterId) {
803
+ event.preventDefault();
804
+ event.stopPropagation();
805
+ pendingSelection = null;
806
+ return;
807
+ }
808
+ }
809
+
810
+ // Alt+Shift+C comments the selection or focused commentable element (Review only, never while typing).
811
+ if (event.altKey && event.shiftKey && event.key.toLowerCase() === "c") {
812
+ const activeEl = doc.activeElement;
813
+ const targetEl = event.target as Element | null;
814
+ if (isEditableElement(activeEl) || isEditableElement(targetEl)) {
815
+ return;
816
+ }
817
+
818
+ const selection = doc.defaultView?.getSelection();
819
+ if (
820
+ selection &&
821
+ selection.rangeCount > 0 &&
822
+ !selection.getRangeAt(0).collapsed &&
823
+ root.contains(selection.getRangeAt(0).commonAncestorContainer)
824
+ ) {
825
+ const range = selection.getRangeAt(0);
826
+ const anchor = createAnchorFromSelection(root, range, artifactVersion);
827
+ if (anchor) {
828
+ event.preventDefault();
829
+ event.stopPropagation();
830
+ const rootRect = root.getBoundingClientRect();
831
+ const fallbackEl =
832
+ range.endContainer.nodeType === Node.ELEMENT_NODE
833
+ ? (range.endContainer as Element)
834
+ : range.endContainer.parentElement ?? root;
835
+ const rangeRect = safeRangeRect(range, fallbackEl);
836
+ pendingSelection = null;
837
+ openComposerForAnchor(
838
+ anchor,
839
+ activeEl as HTMLElement | null,
840
+ rangeRect.bottom - rootRect.top,
841
+ Math.max(0, rangeRect.left - rootRect.left),
842
+ );
843
+ return;
844
+ }
845
+ }
846
+
847
+ if (activeEl && root.contains(activeEl)) {
848
+ const commentable = findCommentable(activeEl);
849
+ if (commentable) {
850
+ const anchor = createAnchorFromElement(root, commentable, artifactVersion);
851
+ if (anchor) {
852
+ event.preventDefault();
853
+ event.stopPropagation();
854
+ const box = relativeBox(root.getBoundingClientRect(), commentable.getBoundingClientRect());
855
+ openComposerForAnchor(anchor, commentable, box.top + box.height, box.left);
856
+ }
857
+ }
858
+ }
859
+ }
860
+ };
861
+
862
+ root.addEventListener("click", handleRootClick, true);
863
+ root.addEventListener("pointerover", handlePointerOver);
864
+ root.addEventListener("pointerleave", handlePointerLeave);
865
+ root.addEventListener("focusin", handleFocusIn);
866
+ root.addEventListener("focusout", handleFocusOut);
867
+ doc.addEventListener("selectionchange", handleSelectionChange);
868
+ doc.addEventListener("keydown", handleGlobalKeydown);
869
+ doc.addEventListener("mouseup", handleSelectionTriggerPointerRelease);
870
+ doc.addEventListener("pointerup", handleSelectionTriggerPointerRelease);
871
+ doc.addEventListener("pointercancel", handleSelectionTriggerPointerRelease);
872
+
873
+ return () => {
874
+ if (selectionTimer !== undefined) {
875
+ clearTimeout(selectionTimer);
876
+ selectionTimer = undefined;
877
+ }
878
+ if (selectionTriggerReleaseTimer !== undefined) {
879
+ clearTimeout(selectionTriggerReleaseTimer);
880
+ selectionTriggerReleaseTimer = undefined;
881
+ }
882
+ selectionTriggerPressed = false;
883
+ if (flashTimer !== undefined) {
884
+ clearTimeout(flashTimer);
885
+ flashTimer = undefined;
886
+ }
887
+ root.removeEventListener("click", handleRootClick, true);
888
+ root.removeEventListener("pointerover", handlePointerOver);
889
+ root.removeEventListener("pointerleave", handlePointerLeave);
890
+ root.removeEventListener("focusin", handleFocusIn);
891
+ root.removeEventListener("focusout", handleFocusOut);
892
+ doc.removeEventListener("selectionchange", handleSelectionChange);
893
+ doc.removeEventListener("keydown", handleGlobalKeydown);
894
+ doc.removeEventListener("mouseup", handleSelectionTriggerPointerRelease);
895
+ doc.removeEventListener("pointerup", handleSelectionTriggerPointerRelease);
896
+ doc.removeEventListener("pointercancel", handleSelectionTriggerPointerRelease);
897
+ };
898
+ });
899
+
900
+ // Focus the first item on cluster popover open and handle Escape directly on the popover
901
+ // so Escape closes the popover only and restores focus to the invoker pin.
902
+ $effect(() => {
903
+ const node = clusterPopoverEl;
904
+ if (!node) return;
905
+ const firstItem = node.querySelector<HTMLElement>(".st-review-layer__cluster-item");
906
+ (firstItem ?? node).focus();
907
+ const onKeydown = (event: KeyboardEvent) => {
908
+ if (event.key === "Escape") {
909
+ event.preventDefault();
910
+ event.stopPropagation();
911
+ const invoker = clusterInvoker;
912
+ openClusterId = null;
913
+ clusterInvoker = null;
914
+ invoker?.focus();
915
+ }
916
+ };
917
+ node.addEventListener("keydown", onKeydown);
918
+ return () => node.removeEventListener("keydown", onKeydown);
919
+ });
920
+
921
+ // Modal exit alertdialog: move focus inside on open, trap Tab/Shift+Tab, and wire Escape
922
+ // to Keep editing so Escape closes ONLY the topmost alertdialog layer.
923
+ $effect(() => {
924
+ const node = confirmDialogEl;
925
+ if (!confirmDiscardOpen || !node) return;
926
+ const doc = node.ownerDocument;
927
+ const focusables = getFocusableElements(node);
928
+ (focusables[0] ?? node).focus();
929
+
930
+ const onDialogKeydown = (event: KeyboardEvent) => {
931
+ if (event.key === "Escape") {
932
+ event.preventDefault();
933
+ event.stopPropagation();
934
+ handleKeepEditing();
935
+ return;
936
+ }
937
+ if (event.key === "Tab") {
938
+ event.stopPropagation();
939
+ handleFocusTrapKeydown(event, node);
940
+ }
941
+ };
942
+ const onDocumentKeydown = (event: KeyboardEvent) => {
943
+ if (event.key === "Escape") {
944
+ event.preventDefault();
945
+ event.stopPropagation();
946
+ handleKeepEditing();
947
+ } else if (event.key === "Tab" && !node.contains(doc.activeElement)) {
948
+ event.stopPropagation();
949
+ handleFocusTrapKeydown(event, node);
950
+ }
951
+ };
952
+ node.addEventListener("keydown", onDialogKeydown);
953
+ doc.addEventListener("keydown", onDocumentKeydown);
954
+ return () => {
955
+ node.removeEventListener("keydown", onDialogKeydown);
956
+ doc.removeEventListener("keydown", onDocumentKeydown);
957
+ };
958
+ });
959
+
960
+ function clearTransientState() {
961
+ hoverBox = null;
962
+ flashBox = null;
963
+ pendingSelection = null;
964
+ selectionTriggerPressed = false;
965
+ if (selectionTriggerReleaseTimer !== undefined) {
966
+ clearTimeout(selectionTriggerReleaseTimer);
967
+ selectionTriggerReleaseTimer = undefined;
968
+ }
969
+ composerSession = null;
970
+ draftBody = "";
971
+ openClusterId = null;
972
+ confirmDiscardOpen = false;
973
+ }
974
+
975
+ function openComposerForAnchor(
976
+ anchor: AnchorPayload,
977
+ invoker: HTMLElement | null,
978
+ top: number,
979
+ left: number,
980
+ ) {
981
+ const encoded = tryEncodeAnchor(anchor);
982
+ draftBody = "";
983
+ composerSession = encoded.ok
984
+ ? {
985
+ anchor: encoded.payload,
986
+ sectionKey: encoded.sectionKey,
987
+ error: null,
988
+ top,
989
+ left,
990
+ invoker,
991
+ }
992
+ : {
993
+ anchor,
994
+ sectionKey: null,
995
+ error: encoded.message,
996
+ top,
997
+ left,
998
+ invoker,
999
+ };
1000
+ }
1001
+
1002
+ function handleSelectionTriggerPointerDown(event: PointerEvent | MouseEvent) {
1003
+ event.preventDefault();
1004
+ selectionTriggerPressed = true;
1005
+ if (selectionTriggerReleaseTimer !== undefined) {
1006
+ clearTimeout(selectionTriggerReleaseTimer);
1007
+ selectionTriggerReleaseTimer = undefined;
1008
+ }
1009
+ }
1010
+
1011
+ function handleSelectionTriggerFocusOut(event: FocusEvent) {
1012
+ if (selectionTriggerPressed) return;
1013
+ const related = event.relatedTarget as Node | null;
1014
+ if (related && selectionTriggerEl?.contains(related)) return;
1015
+ const root = effectiveRoot;
1016
+ if (!root) {
1017
+ pendingSelection = null;
1018
+ return;
1019
+ }
1020
+ const selection = root.ownerDocument.defaultView?.getSelection();
1021
+ if (
1022
+ !selection ||
1023
+ selection.rangeCount === 0 ||
1024
+ selection.getRangeAt(0).collapsed ||
1025
+ !root.contains(selection.getRangeAt(0).commonAncestorContainer)
1026
+ ) {
1027
+ pendingSelection = null;
1028
+ }
1029
+ }
1030
+
1031
+ function handleSelectionTriggerClick(event: MouseEvent) {
1032
+ selectionTriggerPressed = false;
1033
+ if (selectionTriggerReleaseTimer !== undefined) {
1034
+ clearTimeout(selectionTriggerReleaseTimer);
1035
+ selectionTriggerReleaseTimer = undefined;
1036
+ }
1037
+ if (!pendingSelection) return;
1038
+ const { anchor, top, left } = pendingSelection;
1039
+ pendingSelection = null;
1040
+ openComposerForAnchor(anchor, event.currentTarget as HTMLElement | null, top, left);
1041
+ }
1042
+
1043
+ function restoreFocusFallback(preferred: HTMLElement | null) {
1044
+ if (preferred?.isConnected && preferred.tabIndex >= 0) {
1045
+ preferred.focus();
1046
+ return;
1047
+ }
1048
+ layerEl?.focus();
1049
+ }
1050
+
1051
+ async function handleComposerSubmit(body: string) {
1052
+ const session = composerSession;
1053
+ if (!session || session.sectionKey === null) {
1054
+ throw new Error(session?.error ?? "Unable to encode anchor for this selection.");
1055
+ }
1056
+ const createdSectionKey = session.sectionKey;
1057
+ const invoker = session.invoker;
1058
+ const fullTarget: CommentTarget = {
1059
+ kind: target.kind,
1060
+ id: target.id,
1061
+ sectionKey: createdSectionKey,
1062
+ };
1063
+ await onCreate?.({
1064
+ target: fullTarget,
1065
+ sectionKey: createdSectionKey,
1066
+ body,
1067
+ });
1068
+ composerSession = null;
1069
+ draftBody = "";
1070
+ liveAnnouncement = "Comment thread created.";
1071
+
1072
+ // Preserve focus after submit: keep any host-assigned focus, otherwise move focus
1073
+ // to the integrated ThreadPanel heading (SPEC-r6 §3), then the created pin, invoker, or layer.
1074
+ await tick();
1075
+ const doc = layerEl?.ownerDocument ?? (typeof document !== "undefined" ? document : null);
1076
+ const active = doc?.activeElement ?? null;
1077
+ if (active === null || active === doc?.body) {
1078
+ const panelHeading = effectivePanelOpen
1079
+ ? panelHostEl?.querySelector<HTMLElement>(".st-review-panel__heading, .st-drawer__title") ?? null
1080
+ : null;
1081
+ if (panelHeading) {
1082
+ panelHeading.focus();
1083
+ } else {
1084
+ const matchingPin = overlayEl?.querySelector<HTMLElement>(
1085
+ `.st-review-layer__pins [data-pin-section-key="${createdSectionKey.replace(/"/g, '\\"')}"] button.st-review-pin`,
1086
+ );
1087
+ if (matchingPin) {
1088
+ matchingPin.focus();
1089
+ } else {
1090
+ restoreFocusFallback(invoker);
1091
+ }
1092
+ }
1093
+ }
1094
+ }
1095
+
1096
+ function handleComposerCancel() {
1097
+ const invoker = composerSession?.invoker ?? null;
1098
+ composerSession = null;
1099
+ draftBody = "";
1100
+ void tick().then(() => {
1101
+ restoreFocusFallback(invoker);
1102
+ });
1103
+ }
1104
+
1105
+ function handleSelectThread(threadId: string | null) {
1106
+ if (activeThreadId === undefined) {
1107
+ internalActiveThreadId = threadId;
1108
+ }
1109
+ if (threadId !== null) {
1110
+ panelDismissed = false;
1111
+ }
1112
+ onSelect?.(threadId);
1113
+ }
1114
+
1115
+ function handlePanelClose() {
1116
+ if (panelOpen === undefined) {
1117
+ panelDismissed = true;
1118
+ }
1119
+ onPanelClose?.();
1120
+ }
1121
+
1122
+ function activateEntry(entry: ResolvedEntry) {
1123
+ openClusterId = null;
1124
+ handleSelectThread(entry.thread.threadId);
1125
+ onMarkRead?.(entry.thread.threadId);
1126
+ if (typeof (entry.element as HTMLElement).scrollIntoView === "function") {
1127
+ (entry.element as HTMLElement).scrollIntoView({ behavior: "smooth", block: "center" });
1128
+ }
1129
+ flashBox = entry.box;
1130
+ if (flashTimer !== undefined) clearTimeout(flashTimer);
1131
+ flashTimer = setTimeout(() => {
1132
+ flashBox = null;
1133
+ flashTimer = undefined;
1134
+ }, 900);
1135
+ }
1136
+
1137
+ function handleClusterPinActivate(cluster: PinCluster, event?: MouseEvent) {
1138
+ if (cluster.entries.length === 1) {
1139
+ activateEntry(cluster.entries[0]!);
1140
+ return;
1141
+ }
1142
+ if (openClusterId === cluster.id) {
1143
+ openClusterId = null;
1144
+ } else {
1145
+ clusterInvoker = (event?.currentTarget as HTMLElement | null) ?? null;
1146
+ openClusterId = cluster.id;
1147
+ }
1148
+ }
1149
+
1150
+ function handleKeepEditing() {
1151
+ const returnTarget = confirmReturnFocus;
1152
+ confirmDiscardOpen = false;
1153
+ onModeChange?.("review");
1154
+ void tick().then(() => {
1155
+ if (mode !== "review") {
1156
+ confirmReturnFocus = null;
1157
+ restoreFocusFallback(returnTarget);
1158
+ }
1159
+ });
1160
+ }
1161
+
1162
+ function handleDiscardDraft() {
1163
+ const returnTarget = confirmReturnFocus ?? composerSession?.invoker ?? null;
1164
+ confirmReturnFocus = null;
1165
+ clearTransientState();
1166
+ void tick().then(() => {
1167
+ restoreFocusFallback(returnTarget);
1168
+ });
1169
+ }
1170
+
1171
+ const classes = $derived(
1172
+ ["st-review-layer", `st-review-layer--${mode}`, className].filter(Boolean).join(" "),
1173
+ );
1174
+ </script>
1175
+
1176
+ <div {...rest} bind:this={layerEl} class={classes} data-review-mode={mode} tabindex="-1">
1177
+ {#if children}
1178
+ <div bind:this={slotHostEl} class="st-review-layer__content">
1179
+ {@render children()}
1180
+ </div>
1181
+ {/if}
1182
+
1183
+ <div
1184
+ bind:this={overlayEl}
1185
+ class="st-review-layer__overlay"
1186
+ data-review-overlay="true"
1187
+ style:top={resolution.overlayBox ? `${resolution.overlayBox.top}px` : undefined}
1188
+ style:left={resolution.overlayBox ? `${resolution.overlayBox.left}px` : undefined}
1189
+ style:width={resolution.overlayBox ? `${resolution.overlayBox.width}px` : undefined}
1190
+ style:height={resolution.overlayBox ? `${resolution.overlayBox.height}px` : undefined}
1191
+ >
1192
+ {#if mode === "review"}
1193
+ {#if hoverBox}
1194
+ <div
1195
+ class="st-review-layer__hover-outline"
1196
+ aria-hidden="true"
1197
+ style:top={`${hoverBox.top}px`}
1198
+ style:left={`${hoverBox.left}px`}
1199
+ style:width={`${hoverBox.width}px`}
1200
+ style:height={`${hoverBox.height}px`}
1201
+ ></div>
1202
+ {/if}
1203
+
1204
+ {#if flashBox}
1205
+ <div
1206
+ class="st-review-layer__flash"
1207
+ aria-hidden="true"
1208
+ style:top={`${flashBox.top}px`}
1209
+ style:left={`${flashBox.left}px`}
1210
+ style:width={`${flashBox.width}px`}
1211
+ style:height={`${flashBox.height}px`}
1212
+ ></div>
1213
+ {/if}
1214
+
1215
+ <div class="st-review-layer__pins" role="group" aria-label="Comment pins">
1216
+ {#each clusters as cluster (cluster.id)}
1217
+ <div
1218
+ class="st-review-layer__pin-anchor"
1219
+ data-pin-section-key={cluster.entries[0]?.thread.sectionKey ?? undefined}
1220
+ style:top={`${cluster.box.top}px`}
1221
+ style:left={`${cluster.box.left + cluster.box.width}px`}
1222
+ >
1223
+ <CommentPin
1224
+ index={cluster.primaryIndex}
1225
+ count={cluster.totalComments}
1226
+ unread={cluster.unreadCount > 0}
1227
+ resolved={cluster.allResolved}
1228
+ active={cluster.anyActive}
1229
+ label={cluster.ariaLabel}
1230
+ variant={cluster.variant}
1231
+ onclick={(event) => handleClusterPinActivate(cluster, event)}
1232
+ />
1233
+ </div>
1234
+ {/each}
1235
+ </div>
1236
+
1237
+ {#if gutterPins.length > 0}
1238
+ <div class="st-review-layer__gutter" aria-hidden="false">
1239
+ {#each gutterPins as item (item.cluster.id)}
1240
+ <div
1241
+ class="st-review-layer__gutter-pin"
1242
+ style:top={`${item.positioned.y}px`}
1243
+ >
1244
+ <CommentPin
1245
+ index={item.cluster.primaryIndex}
1246
+ count={item.cluster.totalComments}
1247
+ unread={item.cluster.unreadCount > 0}
1248
+ resolved={item.cluster.allResolved}
1249
+ active={item.cluster.anyActive}
1250
+ label={item.cluster.ariaLabel}
1251
+ variant="margin"
1252
+ tabindex={-1}
1253
+ onclick={(event) => handleClusterPinActivate(item.cluster, event)}
1254
+ />
1255
+ </div>
1256
+ {/each}
1257
+ </div>
1258
+ {/if}
1259
+
1260
+ {#if openCluster}
1261
+ <div
1262
+ bind:this={clusterPopoverEl}
1263
+ class="st-review-layer__cluster-popover"
1264
+ role="dialog"
1265
+ aria-label="Clustered comment threads"
1266
+ tabindex="-1"
1267
+ style:top={`${openCluster.box.top + 28}px`}
1268
+ style:left={`${Math.max(0, openCluster.box.left)}px`}
1269
+ >
1270
+ <ul class="st-review-layer__cluster-list">
1271
+ {#each openCluster.entries as entry (entry.thread.threadId)}
1272
+ {@const preview = entry.thread.comments[0]?.body ?? ""}
1273
+ {@const threadUnread = isUnread(entry.thread, currentUser, readState)}
1274
+ <li>
1275
+ <button
1276
+ type="button"
1277
+ class="st-review-layer__cluster-item"
1278
+ data-unread={threadUnread ? "true" : "false"}
1279
+ onclick={() => activateEntry(entry)}
1280
+ >
1281
+ <span class="st-review-layer__cluster-index">#{entry.index}</span>
1282
+ <span class="st-review-layer__cluster-preview">{preview}</span>
1283
+ </button>
1284
+ </li>
1285
+ {/each}
1286
+ </ul>
1287
+ </div>
1288
+ {/if}
1289
+
1290
+ {#if pendingSelection && !composerSession}
1291
+ <div
1292
+ bind:this={selectionTriggerEl}
1293
+ class="st-review-layer__selection-trigger"
1294
+ style:top={`${pendingSelection.top}px`}
1295
+ style:left={`${pendingSelection.left}px`}
1296
+ >
1297
+ <Button
1298
+ type="button"
1299
+ variant="primary"
1300
+ size="sm"
1301
+ onpointerdown={handleSelectionTriggerPointerDown}
1302
+ onmousedown={handleSelectionTriggerPointerDown}
1303
+ onfocusout={handleSelectionTriggerFocusOut}
1304
+ onclick={handleSelectionTriggerClick}
1305
+ >
1306
+ Add comment
1307
+ </Button>
1308
+ </div>
1309
+ {/if}
1310
+
1311
+ {#if composerSession}
1312
+ <div
1313
+ class="st-review-layer__composer"
1314
+ role="dialog"
1315
+ aria-label="Add comment"
1316
+ style:top={`${composerSession.top}px`}
1317
+ style:left={`${composerSession.left}px`}
1318
+ >
1319
+ {#if composer}
1320
+ {@render composer({
1321
+ anchor: composerSession.anchor,
1322
+ sectionKey: composerSession.sectionKey,
1323
+ error: composerSession.error,
1324
+ submit: handleComposerSubmit,
1325
+ cancel: handleComposerCancel,
1326
+ })}
1327
+ {:else}
1328
+ <CommentComposer
1329
+ author={currentUser}
1330
+ initialBody={draftBody}
1331
+ quotePreview={formatAnchorLabel(composerSession.anchor, 140)}
1332
+ anchorError={composerSession.error}
1333
+ autofocus={true}
1334
+ trapFocus={true}
1335
+ onSubmit={handleComposerSubmit}
1336
+ onCancel={handleComposerCancel}
1337
+ onDraftChange={(next) => {
1338
+ draftBody = next;
1339
+ }}
1340
+ />
1341
+ {/if}
1342
+ </div>
1343
+ {/if}
1344
+ {/if}
1345
+
1346
+ {#if confirmDiscardOpen}
1347
+ <div
1348
+ bind:this={confirmDialogEl}
1349
+ class="st-review-layer__confirm"
1350
+ role="alertdialog"
1351
+ aria-modal="true"
1352
+ aria-label="Discard unsaved comment draft"
1353
+ tabindex="-1"
1354
+ >
1355
+ <p class="st-review-layer__confirm-text">
1356
+ You have an unsaved comment draft. Discard it and exit review mode?
1357
+ </p>
1358
+ <div class="st-review-layer__confirm-actions">
1359
+ <Button type="button" variant="secondary" size="sm" onclick={handleKeepEditing}>
1360
+ Keep editing
1361
+ </Button>
1362
+ <Button type="button" variant="danger" size="sm" onclick={handleDiscardDraft}>
1363
+ Discard draft
1364
+ </Button>
1365
+ </div>
1366
+ </div>
1367
+ {/if}
1368
+
1369
+ <div class="st-review-layer__sr-live" aria-live="polite" aria-atomic="true">
1370
+ {liveAnnouncement}
1371
+ </div>
1372
+ </div>
1373
+
1374
+ {#if panelMounted}
1375
+ <div bind:this={panelHostEl} class="st-review-layer__panel">
1376
+ <ThreadPanel
1377
+ threads={resolution.resolved.map((entry) => entry.thread)}
1378
+ orphaned={resolution.orphaned}
1379
+ {currentUser}
1380
+ activeThreadId={effectiveActiveThreadId}
1381
+ filter={panelFilter}
1382
+ open={effectivePanelOpen}
1383
+ {readState}
1384
+ {canModerate}
1385
+ compact={panelCompact}
1386
+ onSelect={handleSelectThread}
1387
+ onFilterChange={onPanelFilterChange}
1388
+ onClose={handlePanelClose}
1389
+ {onReply}
1390
+ {onResolve}
1391
+ {onReopen}
1392
+ {onEditComment}
1393
+ {onDeleteComment}
1394
+ {onReanchor}
1395
+ {onMarkRead}
1396
+ />
1397
+ </div>
1398
+ {/if}
1399
+ </div>
1400
+
1401
+ <style>
1402
+ .st-review-layer {
1403
+ position: relative;
1404
+ }
1405
+
1406
+ .st-review-layer__content {
1407
+ position: relative;
1408
+ }
1409
+
1410
+ .st-review-layer__overlay {
1411
+ left: 0;
1412
+ pointer-events: none;
1413
+ position: absolute;
1414
+ top: 0;
1415
+ z-index: var(--st-component-review-layer-zIndex, 40);
1416
+ }
1417
+
1418
+ .st-review-layer__hover-outline {
1419
+ border: 1.5px dashed
1420
+ var(--st-component-review-hoverOutline, var(--st-semantic-border-interactive, #2563eb));
1421
+ border-radius: var(--st-radius-sm, 0.375rem);
1422
+ box-sizing: border-box;
1423
+ pointer-events: none;
1424
+ position: absolute;
1425
+ }
1426
+
1427
+ .st-review-layer__flash {
1428
+ background: color-mix(
1429
+ in srgb,
1430
+ var(--st-component-review-flash, var(--st-semantic-feedback-info, #2563eb)) 18%,
1431
+ transparent
1432
+ );
1433
+ border: 2px solid var(--st-semantic-border-interactive, #2563eb);
1434
+ border-radius: var(--st-radius-sm, 0.375rem);
1435
+ box-sizing: border-box;
1436
+ pointer-events: none;
1437
+ position: absolute;
1438
+ animation: st-review-flash 900ms ease-out forwards;
1439
+ }
1440
+
1441
+ @keyframes st-review-flash {
1442
+ from {
1443
+ opacity: 1;
1444
+ }
1445
+ to {
1446
+ opacity: 0;
1447
+ }
1448
+ }
1449
+
1450
+ @media (prefers-reduced-motion: reduce) {
1451
+ .st-review-layer__flash {
1452
+ animation: none;
1453
+ }
1454
+ }
1455
+
1456
+ .st-review-layer__pins {
1457
+ inset: 0;
1458
+ pointer-events: none;
1459
+ position: absolute;
1460
+ }
1461
+
1462
+ .st-review-layer__pin-anchor {
1463
+ pointer-events: auto;
1464
+ position: absolute;
1465
+ transform: translate(-50%, -25%);
1466
+ }
1467
+
1468
+ .st-review-layer__gutter {
1469
+ bottom: 0;
1470
+ pointer-events: none;
1471
+ position: absolute;
1472
+ right: calc(-1 * var(--st-component-review-gutter-offset, 2.5rem));
1473
+ top: 0;
1474
+ width: var(--st-component-review-gutter-width, 2rem);
1475
+ }
1476
+
1477
+ .st-review-layer__gutter-pin {
1478
+ pointer-events: auto;
1479
+ position: absolute;
1480
+ right: 0;
1481
+ }
1482
+
1483
+ @media (max-width: 47.999rem) {
1484
+ .st-review-layer__gutter {
1485
+ display: none;
1486
+ }
1487
+ }
1488
+
1489
+ .st-review-layer__cluster-popover {
1490
+ background: var(--st-semantic-surface-raised, #ffffff);
1491
+ border: 1px solid var(--st-semantic-border-subtle);
1492
+ border-radius: var(--st-radius-md, 0.5rem);
1493
+ box-shadow: 0 12px 32px rgb(15 23 42 / 0.16);
1494
+ max-width: 20rem;
1495
+ padding: var(--st-spacing-2, 0.5rem);
1496
+ pointer-events: auto;
1497
+ position: absolute;
1498
+ z-index: 60;
1499
+ }
1500
+
1501
+ .st-review-layer__cluster-list {
1502
+ display: grid;
1503
+ gap: var(--st-spacing-1, 0.25rem);
1504
+ list-style: none;
1505
+ margin: 0;
1506
+ padding: 0;
1507
+ }
1508
+
1509
+ .st-review-layer__cluster-item {
1510
+ align-items: center;
1511
+ background: transparent;
1512
+ border: 1px solid transparent;
1513
+ border-radius: var(--st-radius-sm, 0.375rem);
1514
+ color: var(--st-semantic-text-primary);
1515
+ cursor: pointer;
1516
+ display: flex;
1517
+ font: inherit;
1518
+ font-size: 0.8125rem;
1519
+ gap: var(--st-spacing-2, 0.5rem);
1520
+ padding: var(--st-spacing-1, 0.25rem) var(--st-spacing-2, 0.5rem);
1521
+ text-align: start;
1522
+ width: 100%;
1523
+ }
1524
+
1525
+ .st-review-layer__cluster-item:hover {
1526
+ background: var(--st-semantic-surface-subtle, #f1f5f9);
1527
+ }
1528
+
1529
+ .st-review-layer__cluster-item:focus-visible {
1530
+ outline: 2px solid var(--st-semantic-border-interactive, #2563eb);
1531
+ outline-offset: 1px;
1532
+ }
1533
+
1534
+ .st-review-layer__cluster-index {
1535
+ color: var(--st-semantic-text-secondary);
1536
+ font-weight: 700;
1537
+ }
1538
+
1539
+ .st-review-layer__cluster-preview {
1540
+ overflow: hidden;
1541
+ text-overflow: ellipsis;
1542
+ white-space: nowrap;
1543
+ }
1544
+
1545
+ .st-review-layer__selection-trigger {
1546
+ pointer-events: auto;
1547
+ position: absolute;
1548
+ transform: translateY(0.25rem);
1549
+ z-index: 65;
1550
+ }
1551
+
1552
+ .st-review-layer__composer {
1553
+ max-width: min(24rem, 92vw);
1554
+ min-width: 18rem;
1555
+ pointer-events: auto;
1556
+ position: absolute;
1557
+ z-index: 70;
1558
+ }
1559
+
1560
+ .st-review-layer__confirm {
1561
+ background: var(--st-semantic-surface-raised, #ffffff);
1562
+ border: 1px solid var(--st-semantic-border-strong, #cbd5e1);
1563
+ border-radius: var(--st-radius-md, 0.5rem);
1564
+ box-shadow: 0 18px 40px rgb(15 23 42 / 0.2);
1565
+ display: grid;
1566
+ gap: var(--st-spacing-3, 0.75rem);
1567
+ left: 50%;
1568
+ max-width: 24rem;
1569
+ padding: var(--st-spacing-4, 1rem);
1570
+ pointer-events: auto;
1571
+ position: fixed;
1572
+ top: 20%;
1573
+ transform: translateX(-50%);
1574
+ z-index: 100;
1575
+ }
1576
+
1577
+ .st-review-layer__confirm-text {
1578
+ color: var(--st-semantic-text-primary);
1579
+ font-size: 0.875rem;
1580
+ margin: 0;
1581
+ }
1582
+
1583
+ .st-review-layer__confirm-actions {
1584
+ display: flex;
1585
+ gap: var(--st-spacing-2, 0.5rem);
1586
+ justify-content: flex-end;
1587
+ }
1588
+
1589
+ .st-review-layer__sr-live {
1590
+ border: 0;
1591
+ clip: rect(0 0 0 0);
1592
+ clip-path: inset(50%);
1593
+ height: 1px;
1594
+ overflow: hidden;
1595
+ padding: 0;
1596
+ position: absolute;
1597
+ white-space: nowrap;
1598
+ width: 1px;
1599
+ }
1600
+
1601
+ :global(::highlight(st-review-text)) {
1602
+ background-color: var(
1603
+ --st-component-review-highlight-background,
1604
+ rgb(250 204 21 / 0.35)
1605
+ );
1606
+ }
1607
+
1608
+ :global(::highlight(st-review-text-active)) {
1609
+ background-color: var(
1610
+ --st-component-review-highlight-activeBackground,
1611
+ rgb(37 99 235 / 0.25)
1612
+ );
1613
+ }
1614
+
1615
+ :global(::highlight(st-review-text-resolved)) {
1616
+ background-color: var(
1617
+ --st-component-review-highlight-resolvedBackground,
1618
+ rgb(21 128 61 / 0.16)
1619
+ );
1620
+ }
1621
+ </style>