@storystick/preview 0.2.0-rc.5 → 0.2.0-rc.6

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.
@@ -1,10 +1,10 @@
1
1
  import { isPreviewTargetRendered, scrollPreviewTargetIntoView } from "../reveal-target.js";
2
2
  import { getPreviewOverlayRegistryTuple, getPreviewOverlayTarget, } from "./preview-overlay-sidecar.js";
3
3
  import { installPreviewInteractionPolicy } from "./preview-interaction-policy.js";
4
- import { getInteractionMode } from "../interaction-mode.js";
4
+ import { getInteractionMode, subscribeInteractionMode } from "../interaction-mode.js";
5
5
  import { parsePublicSidecar, readPreviewProvenanceSidecarStore, } from "../provenance/index.js";
6
6
  import { isPreviewPerfEnabled, recordPreviewPerfMetric, previewPerfNow, } from "./perf-metrics.js";
7
- import { applyPreviewOverlayLabelVisualStyle, PREVIEW_OVERLAY_LABEL_GAP_PX, PREVIEW_OVERLAY_LABEL_HEIGHT_PX, PREVIEW_OVERLAY_VISUAL_STYLES, resolvePreviewOverlayLabelHorizontalPosition, } from "../overlay-label.js";
7
+ import { applyPreviewOverlayLabelVisualStyle, commentMarkerVisualStyle, commentMarkerAnchorCorner, commentMarkerWidth, COMMENT_MARKER_SIZE_PX, commentAvatarVisualStyle, placeCommentMarker, previewOverlayActionVisualStyle, PREVIEW_OVERLAY_LABEL_GAP_PX, PREVIEW_OVERLAY_LABEL_HEIGHT_PX, PREVIEW_OVERLAY_VISUAL_STYLES, resolvePreviewOverlayLabelHorizontalPosition, } from "../overlay-label.js";
8
8
  const STYLE_ID = "storystick-preview-field-overlays-style";
9
9
  const ATTR = "data-ss-preview-field-overlay";
10
10
  const KEY_ATTR = "data-ss-preview-field-overlay-key";
@@ -42,7 +42,7 @@ function buildSyntheticOverlayStateTokens(tone) {
42
42
  degraded: { color: visual.color, fill: "transparent" },
43
43
  };
44
44
  }
45
- let decorated = [];
45
+ const decorated = new Map();
46
46
  let interactiveTargets = new WeakMap();
47
47
  let activeWindow = null;
48
48
  let activeClickHandler = null;
@@ -54,15 +54,19 @@ let activeRevealFlashes = [];
54
54
  let cancelRevealScroll;
55
55
  let syntheticOverlayState = null;
56
56
  export function applyPreviewOverlayMap(payload, win, options = {}) {
57
+ closeCommentTooltip?.();
57
58
  const tupleMatches = matchesPreviewOverlayRegistryTuple(payload);
58
- if (!tupleMatches) {
59
+ const provenanceContext = resolvePreviewProvenanceOverlayContext(payload, win.document);
60
+ // Authority is revalidated on every map. Renderer reuse is a separate
61
+ // decision: native provenance does not require a legacy slice snapshot.
62
+ if (!matchesSyntheticOverlayIdentity(payload, win) ||
63
+ (!tupleMatches && provenanceContext === null)) {
59
64
  clearPreviewOverlayPaint();
60
65
  }
61
66
  ensureStyle(win.document);
62
67
  activeWindow = win;
63
68
  activeClickHandler =
64
69
  typeof options === "function" ? options : (options.onClick ?? null);
65
- const provenanceContext = resolvePreviewProvenanceOverlayContext(payload, win.document);
66
70
  if (!tupleMatches && provenanceContext === null) {
67
71
  return {
68
72
  generation: payload.generation,
@@ -76,6 +80,7 @@ export function applyPreviewOverlayMap(payload, win, options = {}) {
76
80
  const syntheticTargets = [];
77
81
  const syntheticElements = new Map();
78
82
  let provenanceTargets = null;
83
+ const resolvePaintTarget = createPreviewPaintTargetResolver(win.document);
79
84
  const hostDomMutationSafe = isPreviewPaintTargetDomMutationSafe(win);
80
85
  for (const item of payload.items) {
81
86
  const registryTarget = tupleMatches
@@ -86,7 +91,7 @@ export function applyPreviewOverlayMap(payload, win, options = {}) {
86
91
  : getPreviewProvenanceItemTargets(item, win.document, provenanceContext, () => {
87
92
  provenanceTargets ??= collectProvenanceMarkerTargets(win.document, provenanceContext);
88
93
  return provenanceTargets;
89
- });
94
+ }, resolvePaintTarget);
90
95
  const connectedTargets = targetElements.filter((element) => win.document.contains(element));
91
96
  if (connectedTargets.length === 0) {
92
97
  missingSnapshotItemKeys.push(item.snapshotItemKey);
@@ -94,6 +99,7 @@ export function applyPreviewOverlayMap(payload, win, options = {}) {
94
99
  }
95
100
  for (const element of connectedTargets) {
96
101
  const interaction = {
102
+ tone: item.tone,
97
103
  generation: payload.generation,
98
104
  snapshotItemKey: item.snapshotItemKey,
99
105
  paintKey: item.paintKey,
@@ -123,7 +129,7 @@ export function applyPreviewOverlayMap(payload, win, options = {}) {
123
129
  for (const target of syntheticTargets)
124
130
  decorateElement(target.element, target.item, payload);
125
131
  }
126
- if (tupleMatches && syntheticOverlayState !== null) {
132
+ if (syntheticOverlayState !== null) {
127
133
  reconcileSyntheticOverlayRenderer(syntheticTargets, payload, win);
128
134
  }
129
135
  else {
@@ -133,6 +139,7 @@ export function applyPreviewOverlayMap(payload, win, options = {}) {
133
139
  overlayDelegationActive = true;
134
140
  installEventDelegation(win);
135
141
  }
142
+ activeCommentMenu?.reconcile();
136
143
  // Synchronous target association, not a browser paint timestamp. Synthetic
137
144
  // geometry is committed by the scheduled renderer below.
138
145
  if (typeof win !== 'undefined') {
@@ -154,22 +161,27 @@ export function applyPreviewOverlayMap(payload, win, options = {}) {
154
161
  };
155
162
  }
156
163
  export function clearPreviewOverlayPaint() {
164
+ activeCommentMenu?.close();
165
+ closeCommentTooltip?.();
157
166
  clearSyntheticOverlayRenderer();
158
167
  clearActiveRevealFlashes(activeWindow?.document);
159
- for (const entry of decorated) {
160
- for (const [name, previous] of entry.attrs) {
168
+ for (const [element, attrs] of decorated) {
169
+ for (const [name, previous] of attrs) {
161
170
  if (previous === null)
162
- entry.element.removeAttribute(name);
171
+ element.removeAttribute(name);
163
172
  else
164
- entry.element.setAttribute(name, previous);
173
+ element.setAttribute(name, previous);
165
174
  }
166
175
  }
167
- decorated = [];
176
+ decorated.clear();
168
177
  interactiveTargets = new WeakMap();
169
178
  overlayDelegationActive = false;
170
179
  activeClickHandler = null;
171
180
  maybeUninstallEventDelegation();
172
181
  }
182
+ export function dismissPreviewOverlayMenu() {
183
+ activeCommentMenu?.close();
184
+ }
173
185
  export function installPreviewEditInteractionGuard(win, options = {}) {
174
186
  if (activeWindow !== null && activeWindow !== win) {
175
187
  clearPreviewOverlayPaint();
@@ -213,8 +225,9 @@ export function revealPreviewV2SourceInIframe(payload, win) {
213
225
  let hiddenCount = 0;
214
226
  let mountedCount = 0;
215
227
  const revealed = [];
228
+ const resolvePaintTarget = createPreviewPaintTargetResolver(win.document);
216
229
  for (const target of payload.targets) {
217
- const element = getPreviewV2RevealTargetElement(target.renderTargetId, target.markerId, win.document, context);
230
+ const element = getPreviewV2RevealTargetElement(target.renderTargetId, target.markerId, context, resolvePaintTarget);
218
231
  if (element === null || !win.document.contains(element))
219
232
  continue;
220
233
  mountedCount += 1;
@@ -258,6 +271,14 @@ function matchesPreviewOverlayRegistryTuple(payload) {
258
271
  tuple.cacheVersion === payload.cacheVersion &&
259
272
  tuple.renderId === payload.renderId);
260
273
  }
274
+ function matchesSyntheticOverlayIdentity(payload, win) {
275
+ const state = syntheticOverlayState;
276
+ return (state !== null && state.win === win && state.root.isConnected &&
277
+ state.paintIdentity.routeHash === payload.routeHash &&
278
+ state.paintIdentity.codeVersion === payload.codeVersion &&
279
+ state.paintIdentity.renderId === payload.renderId &&
280
+ state.paintIdentity.cacheVersion === payload.cacheVersion);
281
+ }
261
282
  function resolvePreviewProvenanceOverlayContext(payload, doc) {
262
283
  let routeFrameMatches = false;
263
284
  const markerIds = new Set();
@@ -301,41 +322,49 @@ function resolvePreviewProvenanceOverlayContext(payload, doc) {
301
322
  multiMarkerIds,
302
323
  };
303
324
  }
304
- function getPreviewV2RevealTargetElement(renderTargetId, markerId, doc, context) {
325
+ function getPreviewV2RevealTargetElement(renderTargetId, markerId, context, resolvePaintTarget) {
305
326
  if (!markerId.startsWith("p_"))
306
327
  return null;
307
328
  if (!context.markerIds.has(markerId))
308
329
  return null;
309
- const resolved = getUniquePreviewPaintTarget(renderTargetId, doc);
330
+ const resolved = resolvePaintTarget(renderTargetId);
310
331
  if (resolved === null)
311
332
  return null;
312
333
  return resolved.markerId === markerId ? resolved.element : null;
313
334
  }
314
- function getUniquePreviewPaintTarget(renderTargetId, doc) {
315
- const runtimeTarget = resolvePreviewPaintTargetFromRegistry(renderTargetId, doc);
316
- let stamped = null;
317
- for (const element of doc.querySelectorAll("[data-ss-preview-paint-id]")) {
318
- if (element.getAttribute("data-ss-preview-paint-id") !== renderTargetId) {
319
- continue;
335
+ function createPreviewPaintTargetResolver(doc) {
336
+ // One lazy index per application/reveal, never across DOM updates. `null`
337
+ // records a duplicate so memory-registry hits cannot bypass ambiguity.
338
+ let stampedTargets = null;
339
+ return (renderTargetId) => {
340
+ if (stampedTargets === null) {
341
+ stampedTargets = new Map();
342
+ for (const element of doc.querySelectorAll("[data-ss-preview-paint-id]")) {
343
+ const id = element.getAttribute("data-ss-preview-paint-id");
344
+ if (id === null)
345
+ continue;
346
+ stampedTargets.set(id, stampedTargets.has(id) ? null : element);
347
+ }
320
348
  }
321
- if (stamped !== null)
322
- return null;
323
- stamped = element;
324
- }
325
- if (runtimeTarget !== null) {
326
- if (runtimeTarget.element.ownerDocument !== doc ||
327
- !doc.contains(runtimeTarget.element) ||
328
- (stamped !== null && stamped !== runtimeTarget.element)) {
349
+ const stamped = stampedTargets.get(renderTargetId);
350
+ if (stamped === null)
329
351
  return null;
352
+ const runtimeTarget = resolvePreviewPaintTargetFromRegistry(renderTargetId, doc);
353
+ if (runtimeTarget !== null) {
354
+ if (runtimeTarget.element.ownerDocument !== doc ||
355
+ !doc.contains(runtimeTarget.element) ||
356
+ (stamped !== undefined && stamped !== runtimeTarget.element)) {
357
+ return null;
358
+ }
359
+ return runtimeTarget;
330
360
  }
331
- return runtimeTarget;
332
- }
333
- if (stamped === null)
334
- return null;
335
- const markerId = stamped.getAttribute("data-ss-e") ?? stamped.getAttribute("data-ss-p");
336
- return markerId === null || markerId.length === 0
337
- ? null
338
- : { element: stamped, markerId };
361
+ if (stamped === undefined || !doc.contains(stamped))
362
+ return null;
363
+ const markerId = stamped.getAttribute("data-ss-e") ?? stamped.getAttribute("data-ss-p");
364
+ return markerId === null || markerId.length === 0
365
+ ? null
366
+ : { element: stamped, markerId };
367
+ };
339
368
  }
340
369
  function resolvePreviewPaintTargetFromRegistry(renderTargetId, doc) {
341
370
  const registry = readPreviewPaintTargetRegistry(doc);
@@ -388,12 +417,12 @@ function getPreviewProvenanceMarkerTargets(markerId, doc, context, targetsRef) {
388
417
  const targets = targetsRef();
389
418
  return targets.get(markerId) ?? [];
390
419
  }
391
- function getPreviewProvenanceItemTargets(item, doc, context, targetsRef) {
420
+ function getPreviewProvenanceItemTargets(item, doc, context, targetsRef, resolvePaintTarget) {
392
421
  const markerId = item.markerId ?? item.snapshotItemKey;
393
422
  const targets = getPreviewProvenanceMarkerTargets(markerId, doc, context, targetsRef);
394
423
  if (item.renderTargetId === undefined)
395
424
  return targets;
396
- const target = getUniquePreviewPaintTarget(item.renderTargetId, doc);
425
+ const target = resolvePaintTarget(item.renderTargetId);
397
426
  return target === null || target.markerId !== markerId
398
427
  ? []
399
428
  : [target.element];
@@ -456,28 +485,28 @@ function clearActiveRevealFlashes(doc) {
456
485
  }
457
486
  }
458
487
  function decorateElement(element, item, payload) {
459
- if (decorated.every((entry) => entry.element !== element)) {
460
- decorated.push({
461
- element,
462
- attrs: new Map([
463
- [ATTR, element.getAttribute(ATTR)],
464
- [KEY_ATTR, element.getAttribute(KEY_ATTR)],
465
- [DISPLAY_ATTR, element.getAttribute(DISPLAY_ATTR)],
466
- ]),
467
- });
488
+ if (!decorated.has(element)) {
489
+ decorated.set(element, new Map([
490
+ [ATTR, element.getAttribute(ATTR)],
491
+ [KEY_ATTR, element.getAttribute(KEY_ATTR)],
492
+ [DISPLAY_ATTR, element.getAttribute(DISPLAY_ATTR)],
493
+ ]));
494
+ }
495
+ if (element.getAttribute(ATTR) !== "field")
496
+ element.setAttribute(ATTR, "field");
497
+ if (element.getAttribute(KEY_ATTR) !== item.paintKey) {
498
+ element.setAttribute(KEY_ATTR, item.paintKey);
499
+ }
500
+ if (element.getAttribute(DISPLAY_ATTR) !== payload.display) {
501
+ element.setAttribute(DISPLAY_ATTR, payload.display);
468
502
  }
469
- element.setAttribute(ATTR, "field");
470
- element.setAttribute(KEY_ATTR, item.paintKey);
471
- element.setAttribute(DISPLAY_ATTR, payload.display);
472
503
  }
473
504
  function restoreDecoratedElement(element) {
474
- const index = decorated.findIndex((entry) => entry.element === element);
475
- if (index === -1)
476
- return;
477
- const [entry] = decorated.splice(index, 1);
478
- if (entry === undefined)
505
+ const attrs = decorated.get(element);
506
+ if (attrs === undefined)
479
507
  return;
480
- for (const [name, previous] of entry.attrs) {
508
+ decorated.delete(element);
509
+ for (const [name, previous] of attrs) {
481
510
  if (previous === null)
482
511
  element.removeAttribute(name);
483
512
  else
@@ -634,6 +663,7 @@ function installSyntheticOverlayRenderer(targets, payload, win) {
634
663
  const mutationObserver = createSyntheticMutationObserver(win, (records) => {
635
664
  if (records.every(isSyntheticOverlayMutationRecord))
636
665
  return;
666
+ activeCommentMenu?.reconcile();
637
667
  onResize();
638
668
  });
639
669
  if (mutationObserver !== null) {
@@ -671,6 +701,12 @@ function installSyntheticOverlayRenderer(targets, payload, win) {
671
701
  }
672
702
  syntheticOverlayState = {
673
703
  win,
704
+ paintIdentity: {
705
+ routeHash: payload.routeHash,
706
+ codeVersion: payload.codeVersion,
707
+ renderId: payload.renderId,
708
+ cacheVersion: payload.cacheVersion,
709
+ },
674
710
  root,
675
711
  entries,
676
712
  targetElements,
@@ -771,6 +807,9 @@ function createSyntheticOverlayEntries(targets, previousByIdentity = new Map())
771
807
  crossDoc: item.crossDoc === true,
772
808
  label: item.crossDoc === true && item.label !== undefined ? item.label : null,
773
809
  boxes: previous?.boxes ?? [],
810
+ commentCount: item.commentCount ?? 0,
811
+ commentUnread: item.commentUnread ?? false,
812
+ commentAvatars: item.commentAvatars ?? [],
774
813
  labelWidth: previous?.label === item.label &&
775
814
  previous?.tone === (item.tone === "model" ? "model" : "default")
776
815
  ? previous.labelWidth
@@ -1016,6 +1055,7 @@ function updateSyntheticOverlayGeometry(state, targetElements = null) {
1016
1055
  }
1017
1056
  entry.lastRects = rects;
1018
1057
  }
1058
+ positionSyntheticCommentMarkers(state);
1019
1059
  const committedGeneration = state.pendingCommitMetricGeneration;
1020
1060
  const committedBoxCount = state.entries.reduce((count, entry) => count + entry.boxes.length, 0);
1021
1061
  if (committedGeneration !== null && committedBoxCount > 0) {
@@ -1060,6 +1100,7 @@ function updateSyntheticOverlayPresentation(state) {
1060
1100
  }
1061
1101
  }
1062
1102
  }
1103
+ positionSyntheticCommentMarkers(state);
1063
1104
  if (perfEnabled) {
1064
1105
  recordPreviewPerfMetric(state.win, {
1065
1106
  name: "preview.overlayPresentationPass",
@@ -1121,11 +1162,98 @@ function ensureSyntheticOverlayEntryBoxes(root, entry, count) {
1121
1162
  box.style.pointerEvents = "none";
1122
1163
  box.style.cursor = "inherit";
1123
1164
  box.style.transformOrigin = "0 0";
1165
+ const comment = root.ownerDocument.createElement("button");
1166
+ comment.type = "button";
1167
+ comment.setAttribute("data-ss-comment-control", "");
1168
+ comment.setAttribute("data-ss-comment-marker", "");
1169
+ comment.setAttribute(PREVIEW_CONTROLS_ATTR, "");
1170
+ comment.setAttribute("aria-label", "Add comment");
1171
+ installCommentTooltip(comment);
1172
+ box.appendChild(comment);
1173
+ const menuTrigger = root.ownerDocument.createElement("button");
1174
+ menuTrigger.type = "button";
1175
+ menuTrigger.setAttribute("data-ss-comment-control", "");
1176
+ menuTrigger.setAttribute("data-ss-comment-menu-trigger", "");
1177
+ menuTrigger.setAttribute(PREVIEW_CONTROLS_ATTR, "");
1178
+ menuTrigger.setAttribute("aria-label", "Content actions");
1179
+ menuTrigger.setAttribute("aria-haspopup", "menu");
1180
+ menuTrigger.setAttribute("aria-expanded", "false");
1181
+ menuTrigger.innerHTML = CONTENT_ACTIONS_ICON;
1182
+ menuTrigger.onclick = event => {
1183
+ event.stopPropagation();
1184
+ if (menuTrigger.getAttribute("aria-expanded") === "true") {
1185
+ activeCommentMenu?.close();
1186
+ }
1187
+ else {
1188
+ openCommentMenu(entry.element, menuTrigger);
1189
+ }
1190
+ };
1191
+ box.appendChild(menuTrigger);
1124
1192
  ensureSyntheticOverlayBoxPill(box, entry);
1125
1193
  root.appendChild(box);
1126
1194
  entry.boxes.push(box);
1127
1195
  }
1128
1196
  for (const box of entry.boxes) {
1197
+ const menuTrigger = box.querySelector('[data-ss-comment-menu-trigger]');
1198
+ if (menuTrigger) {
1199
+ menuTrigger.hidden = entry.tone === "model" || activeClickHandler === null;
1200
+ Object.assign(menuTrigger.style, previewOverlayActionVisualStyle(entry.tone));
1201
+ }
1202
+ const comment = box.querySelector('[data-ss-comment-marker]');
1203
+ if (comment) {
1204
+ const label = entry.commentCount
1205
+ ? `${entry.commentCount} open ${entry.commentCount === 1 ? "discussion" : "discussions"}${entry.commentUnread ? ', unread comments' : ''}`
1206
+ : "View discussions";
1207
+ comment.setAttribute("aria-label", `${label}${entry.commentAvatars.length ? ` — ${entry.commentAvatars.map(person => person.name).join(', ')}` : ''}`);
1208
+ comment.hidden = entry.commentCount === 0 || entry.tone === "model" || activeClickHandler === null;
1209
+ comment.style.visibility = comment.hidden ? "hidden" : "visible";
1210
+ comment.toggleAttribute("data-unread", entry.commentUnread && entry.commentCount > 0);
1211
+ const anchorCorner = comment.dataset.anchorCorner === 'bottom-right' ? 'bottom-right' : 'top-left';
1212
+ Object.assign(comment.style, { width: `${commentMarkerWidth(entry.commentAvatars.length)}px`, height: `${COMMENT_MARKER_SIZE_PX}px`, minWidth: '0', border: '0', borderRadius: '0', background: 'transparent', boxShadow: 'none' });
1213
+ let count = comment.querySelector('[data-ss-comment-count]');
1214
+ if (!count) {
1215
+ count = box.ownerDocument.createElement('span');
1216
+ count.setAttribute("data-ss-comment-count", "");
1217
+ count.setAttribute("aria-hidden", "true");
1218
+ comment.appendChild(count);
1219
+ }
1220
+ count.textContent = entry.commentCount > 99 ? '99+' : entry.commentCount ? String(entry.commentCount) : '';
1221
+ Object.assign(count.style, commentMarkerVisualStyle(entry.commentUnread, anchorCorner), {
1222
+ position: 'absolute', top: '0', zIndex: '4', display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
1223
+ });
1224
+ const avatarKey = JSON.stringify(entry.commentAvatars);
1225
+ if (comment.dataset.avatarKey !== avatarKey) {
1226
+ comment.dataset.avatarKey = avatarKey;
1227
+ comment.querySelectorAll('[data-ss-comment-avatar]').forEach(avatar => avatar.remove());
1228
+ entry.commentAvatars.forEach((person, index) => {
1229
+ const avatar = box.ownerDocument.createElement('span');
1230
+ avatar.setAttribute('data-ss-comment-avatar', '');
1231
+ avatar.setAttribute('aria-hidden', 'true');
1232
+ avatar.textContent = person.initials;
1233
+ Object.assign(avatar.style, commentAvatarVisualStyle(index, person.hue, anchorCorner));
1234
+ if (person.avatarUrl) {
1235
+ const image = box.ownerDocument.createElement('img');
1236
+ image.alt = '';
1237
+ image.referrerPolicy = 'no-referrer';
1238
+ image.draggable = false;
1239
+ Object.assign(image.style, { position: 'absolute', inset: '0', width: '100%', height: '100%', objectFit: 'cover' });
1240
+ image.onerror = () => image.remove();
1241
+ image.src = person.avatarUrl;
1242
+ avatar.appendChild(image);
1243
+ }
1244
+ comment.appendChild(avatar);
1245
+ });
1246
+ }
1247
+ // Resolve from the current paint map, never retain an old generation.
1248
+ comment.onclick = event => {
1249
+ event.stopPropagation();
1250
+ closeCommentTooltip?.();
1251
+ const target = interactiveTargets.get(entry.element);
1252
+ if (target) {
1253
+ emitOverlayClick(target, 0, "view-comments");
1254
+ }
1255
+ };
1256
+ }
1129
1257
  if (box.getAttribute(SYNTHETIC_BOX_TONE_ATTR) !== entry.tone) {
1130
1258
  box.setAttribute(SYNTHETIC_BOX_TONE_ATTR, entry.tone);
1131
1259
  const pill = box.querySelector('[data-slot="ss-preview-cross-doc-pill"]');
@@ -1136,6 +1264,48 @@ function ensureSyntheticOverlayEntryBoxes(root, entry, count) {
1136
1264
  }
1137
1265
  }
1138
1266
  }
1267
+ function positionSyntheticCommentMarkers(state) {
1268
+ const viewport = {
1269
+ width: state.win.document.documentElement.clientWidth || state.win.innerWidth,
1270
+ height: state.win.document.documentElement.clientHeight || state.win.innerHeight,
1271
+ };
1272
+ const occupied = [];
1273
+ for (const entry of state.entries) {
1274
+ let placed = false;
1275
+ entry.boxes.forEach((box, index) => {
1276
+ const marker = box.querySelector('[data-ss-comment-marker]');
1277
+ if (!marker)
1278
+ return;
1279
+ const rect = entry.lastRects[index]?.viewport;
1280
+ const visible = !placed && entry.commentCount > 0 && entry.tone !== 'model' && activeClickHandler !== null &&
1281
+ rect && rect.bottom > 0 && rect.top < viewport.height && rect.right > 0 && rect.left < viewport.width &&
1282
+ box.getAttribute(SYNTHETIC_BOX_STATE_ATTR) !== 'degraded';
1283
+ marker.hidden = !visible;
1284
+ box.setAttribute('data-comment-count', visible ? String(entry.commentCount) : '0');
1285
+ if (!visible || !rect)
1286
+ return;
1287
+ const width = commentMarkerWidth(entry.commentAvatars.length);
1288
+ const position = placeCommentMarker(rect, viewport, occupied, width);
1289
+ const anchorCorner = commentMarkerAnchorCorner(rect, position);
1290
+ if (marker.dataset.anchorCorner !== anchorCorner) {
1291
+ marker.dataset.anchorCorner = anchorCorner;
1292
+ const count = marker.querySelector('[data-ss-comment-count]');
1293
+ if (count)
1294
+ Object.assign(count.style, commentMarkerVisualStyle(entry.commentUnread, anchorCorner));
1295
+ marker.querySelectorAll('[data-ss-comment-avatar]').forEach((avatar, index) => {
1296
+ const person = entry.commentAvatars[index];
1297
+ if (person)
1298
+ Object.assign(avatar.style, commentAvatarVisualStyle(index, person.hue, anchorCorner));
1299
+ });
1300
+ }
1301
+ occupied.push({ ...position, width });
1302
+ marker.style.left = `${position.x - rect.left}px`;
1303
+ marker.style.top = `${position.y - rect.top}px`;
1304
+ marker.style.right = 'auto';
1305
+ placed = true;
1306
+ });
1307
+ }
1308
+ }
1139
1309
  function ensureSyntheticOverlayBoxPill(box, entry) {
1140
1310
  let pill = box.querySelector('[data-slot="ss-preview-cross-doc-pill"]');
1141
1311
  if (!entry.crossDoc || entry.label === null) {
@@ -1311,6 +1481,9 @@ function resolveSyntheticOverlayBoxState(state, element, rect) {
1311
1481
  }
1312
1482
  if (element.getAttribute(REVEAL_ATTR) === "active")
1313
1483
  return "reveal";
1484
+ if (activeCommentMenu !== null) {
1485
+ return activeCommentMenu.element === element ? "focus" : "idle";
1486
+ }
1314
1487
  if (state.focusedTarget === element)
1315
1488
  return "focus";
1316
1489
  if (state.hoveredTargets.has(element))
@@ -1544,7 +1717,7 @@ function installEventDelegation(win) {
1544
1717
  win.document.addEventListener("click", onOverlayClick, true);
1545
1718
  win.document.addEventListener("dblclick", onOverlaySuppressOnly, true);
1546
1719
  win.document.addEventListener("auxclick", onOverlaySuppressOnly, true);
1547
- win.document.addEventListener("contextmenu", onOverlaySuppressOnly, true);
1720
+ win.document.addEventListener("contextmenu", onOverlayContextMenu, true);
1548
1721
  win.document.addEventListener("submit", onOverlaySuppressOnly, true);
1549
1722
  }
1550
1723
  function maybeUninstallEventDelegation() {
@@ -1568,7 +1741,7 @@ function uninstallEventDelegation() {
1568
1741
  doc.removeEventListener("click", onOverlayClick, true);
1569
1742
  doc.removeEventListener("dblclick", onOverlaySuppressOnly, true);
1570
1743
  doc.removeEventListener("auxclick", onOverlaySuppressOnly, true);
1571
- doc.removeEventListener("contextmenu", onOverlaySuppressOnly, true);
1744
+ doc.removeEventListener("contextmenu", onOverlayContextMenu, true);
1572
1745
  doc.removeEventListener("submit", onOverlaySuppressOnly, true);
1573
1746
  }
1574
1747
  function onOverlayPointerDown(event) {
@@ -1611,6 +1784,187 @@ function onOverlayKeyDown(event) {
1611
1784
  return;
1612
1785
  emitOverlayClick(target, 0);
1613
1786
  }
1787
+ const COMMENT_ICON = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>';
1788
+ const CONTENT_ACTIONS_ICON = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="1"/><circle cx="19" cy="12" r="1"/><circle cx="5" cy="12" r="1"/></svg>';
1789
+ let activeCommentMenu = null;
1790
+ let closeCommentTooltip = null;
1791
+ let commentTooltipId = 0;
1792
+ function installCommentTooltip(button) {
1793
+ const doc = button.ownerDocument;
1794
+ const win = doc.defaultView;
1795
+ const hide = () => closeCommentTooltip?.();
1796
+ const show = (delay) => {
1797
+ hide();
1798
+ let tooltip = null;
1799
+ const timer = win.setTimeout(() => {
1800
+ if (!button.isConnected || button.hidden)
1801
+ return;
1802
+ tooltip = doc.createElement("span");
1803
+ tooltip.setAttribute(PREVIEW_CONTROLS_ATTR, "");
1804
+ tooltip.setAttribute("data-ss-comment-tooltip", "");
1805
+ tooltip.setAttribute("role", "tooltip");
1806
+ tooltip.id = `ss-comment-tooltip-${++commentTooltipId}`;
1807
+ tooltip.textContent = button.getAttribute("aria-label");
1808
+ doc.body.appendChild(tooltip);
1809
+ const anchor = button.getBoundingClientRect();
1810
+ const bounds = tooltip.getBoundingClientRect();
1811
+ const left = Math.max(8, Math.min(anchor.right - bounds.width, win.innerWidth - bounds.width - 8));
1812
+ const top = anchor.top >= bounds.height + 16
1813
+ ? anchor.top - bounds.height - 8
1814
+ : anchor.bottom + 8;
1815
+ tooltip.style.left = `${left}px`;
1816
+ tooltip.style.top = `${Math.max(8, Math.min(top, win.innerHeight - bounds.height - 8))}px`;
1817
+ button.setAttribute("aria-describedby", tooltip.id);
1818
+ }, delay);
1819
+ win.addEventListener("scroll", hide, { capture: true, passive: true });
1820
+ win.addEventListener("resize", hide);
1821
+ closeCommentTooltip = () => {
1822
+ win.removeEventListener("scroll", hide, true);
1823
+ win.removeEventListener("resize", hide);
1824
+ win.clearTimeout(timer);
1825
+ tooltip?.remove();
1826
+ button.removeAttribute("aria-describedby");
1827
+ closeCommentTooltip = null;
1828
+ };
1829
+ };
1830
+ button.addEventListener("pointerenter", () => show(200));
1831
+ button.addEventListener("pointerleave", hide);
1832
+ button.addEventListener("focus", () => show(0));
1833
+ button.addEventListener("blur", hide);
1834
+ button.addEventListener("pointerdown", hide);
1835
+ button.addEventListener("keydown", (event) => {
1836
+ if (event.key === "Escape")
1837
+ hide();
1838
+ });
1839
+ }
1840
+ function onOverlayContextMenu(event) {
1841
+ if (!shouldBlockNativeInteraction() || isPreviewControlsEvent(event))
1842
+ return;
1843
+ const element = getInteractiveElement(event);
1844
+ suppressNativeEvent(event);
1845
+ openCommentMenu(element, null, event);
1846
+ }
1847
+ function openCommentMenu(element, triggerButton, pointer) {
1848
+ activeCommentMenu?.close();
1849
+ closeCommentTooltip?.();
1850
+ const target = element === null ? null : interactiveTargets.get(element);
1851
+ if (!element || !target || !activeWindow || !activeClickHandler ||
1852
+ target.tone === "model" || getInteractionMode() !== "edit")
1853
+ return;
1854
+ emitIframeInteraction(pointer?.button === 2 ? 2 : 0, "preview-control");
1855
+ const win = activeWindow;
1856
+ const doc = win.document;
1857
+ const trigger = triggerButton ?? doc.activeElement;
1858
+ const menu = doc.createElement("div");
1859
+ menu.setAttribute(PREVIEW_CONTROLS_ATTR, "");
1860
+ menu.setAttribute("role", "menu");
1861
+ menu.setAttribute("aria-label", "Content actions");
1862
+ menu.setAttribute("data-ss-comment-menu", "");
1863
+ menu.id = "ss-preview-content-actions";
1864
+ triggerButton?.setAttribute("aria-controls", menu.id);
1865
+ triggerButton?.setAttribute("aria-expanded", "true");
1866
+ const button = doc.createElement("button");
1867
+ button.type = "button";
1868
+ button.setAttribute("data-ss-comment-menu-item", "");
1869
+ button.setAttribute("role", "menuitem");
1870
+ button.innerHTML = `${COMMENT_ICON}<span>Add comment</span>`;
1871
+ let closed = false;
1872
+ let unsubscribeMode = null;
1873
+ // Every paint generation remints paintKey. Keep the menu bound to its
1874
+ // source identity and dispatch through the latest approved paint instead.
1875
+ const currentTarget = () => {
1876
+ const current = interactiveTargets.get(element);
1877
+ return element.isConnected && activeClickHandler && current &&
1878
+ current.snapshotItemKey === target.snapshotItemKey &&
1879
+ current.routeHash === target.routeHash &&
1880
+ current.codeVersion === target.codeVersion &&
1881
+ current.renderId === target.renderId && current.tone !== "model" &&
1882
+ getInteractionMode() === "edit" ? current : null;
1883
+ };
1884
+ const dismiss = (restore = false) => {
1885
+ if (closed)
1886
+ return;
1887
+ closed = true;
1888
+ win.removeEventListener("pointerdown", outside, true);
1889
+ win.removeEventListener("keydown", keyboard, true);
1890
+ win.removeEventListener("blur", dismissOnBlur);
1891
+ win.removeEventListener("scroll", viewportChanged, true);
1892
+ win.removeEventListener("resize", viewportChanged);
1893
+ doc.removeEventListener("visibilitychange", visibilityChanged);
1894
+ unsubscribeMode?.();
1895
+ activeCommentMenu = null;
1896
+ menu.remove();
1897
+ triggerButton?.removeAttribute("aria-controls");
1898
+ triggerButton?.setAttribute("aria-expanded", "false");
1899
+ if (restore && trigger instanceof win.HTMLElement && trigger.isConnected) {
1900
+ trigger.focus();
1901
+ }
1902
+ scheduleSyntheticOverlayUpdate("presentation");
1903
+ };
1904
+ const outside = (event) => {
1905
+ const path = event.composedPath();
1906
+ if (!path.includes(menu) && (!triggerButton || !path.includes(triggerButton)))
1907
+ dismiss();
1908
+ };
1909
+ const keyboard = (event) => {
1910
+ if (event.key === "Escape") {
1911
+ event.preventDefault();
1912
+ event.stopPropagation();
1913
+ dismiss(true);
1914
+ }
1915
+ else if (event.key === "Tab") {
1916
+ dismiss(true);
1917
+ }
1918
+ else if (["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) {
1919
+ event.preventDefault();
1920
+ button.focus();
1921
+ }
1922
+ };
1923
+ const dismissOnBlur = () => dismiss();
1924
+ const viewportChanged = (event) => {
1925
+ if (!event.composedPath().includes(menu))
1926
+ dismiss();
1927
+ };
1928
+ const visibilityChanged = () => {
1929
+ if (doc.visibilityState === "hidden")
1930
+ dismiss();
1931
+ };
1932
+ button.onclick = () => {
1933
+ if (closed)
1934
+ return;
1935
+ const current = currentTarget();
1936
+ dismiss();
1937
+ if (current)
1938
+ emitOverlayClick(current, 0, "comment");
1939
+ };
1940
+ menu.appendChild(button);
1941
+ doc.body.appendChild(menu);
1942
+ const bounds = menu.getBoundingClientRect();
1943
+ const anchor = triggerButton?.getBoundingClientRect();
1944
+ const left = anchor ? anchor.right - Math.max(180, bounds.width) : pointer.clientX;
1945
+ const top = anchor ? anchor.bottom + 4 : pointer.clientY;
1946
+ menu.style.left = `${Math.max(8, Math.min(left, win.innerWidth - Math.max(180, bounds.width) - 8))}px`;
1947
+ menu.style.top = `${Math.max(8, Math.min(top, win.innerHeight - Math.max(38, bounds.height) - 8))}px`;
1948
+ activeCommentMenu = {
1949
+ element,
1950
+ close: dismiss,
1951
+ reconcile: () => {
1952
+ if (!currentTarget())
1953
+ dismiss();
1954
+ },
1955
+ };
1956
+ // Window capture runs before the document's edit interception can suppress it.
1957
+ win.addEventListener("pointerdown", outside, true);
1958
+ win.addEventListener("keydown", keyboard, true);
1959
+ win.addEventListener("blur", dismissOnBlur);
1960
+ win.addEventListener("scroll", viewportChanged, { capture: true, passive: true });
1961
+ win.addEventListener("resize", viewportChanged);
1962
+ doc.addEventListener("visibilitychange", visibilityChanged);
1963
+ unsubscribeMode = subscribeInteractionMode(mode => { if (mode !== "edit")
1964
+ dismiss(); });
1965
+ button.focus();
1966
+ scheduleSyntheticOverlayUpdate("presentation");
1967
+ }
1614
1968
  function onOverlaySuppressOnly(event) {
1615
1969
  if (!shouldBlockNativeInteraction() || isPreviewControlsEvent(event))
1616
1970
  return;
@@ -1628,20 +1982,24 @@ function isPreviewControlsEvent(event) {
1628
1982
  return path.some((node) => isElementNode(node) && node.hasAttribute(PREVIEW_CONTROLS_ATTR));
1629
1983
  }
1630
1984
  function getInteractiveTarget(event) {
1985
+ const element = getInteractiveElement(event);
1986
+ return element === null ? null : interactiveTargets.get(element) ?? null;
1987
+ }
1988
+ function getInteractiveElement(event) {
1631
1989
  const path = typeof event.composedPath === "function" ? event.composedPath() : [];
1632
1990
  for (const node of path) {
1633
1991
  if (!isElementNode(node))
1634
1992
  continue;
1635
1993
  const target = interactiveTargets.get(node);
1636
1994
  if (target !== undefined)
1637
- return target;
1995
+ return node;
1638
1996
  }
1639
1997
  let node = event.target;
1640
1998
  while (node !== null) {
1641
1999
  if (isElementNode(node)) {
1642
2000
  const target = interactiveTargets.get(node);
1643
2001
  if (target !== undefined)
1644
- return target;
2002
+ return node;
1645
2003
  }
1646
2004
  node = isNode(node) ? node.parentNode : null;
1647
2005
  }
@@ -1649,7 +2007,7 @@ function getInteractiveTarget(event) {
1649
2007
  ? null
1650
2008
  : findSyntheticOverlayTargetAtEventPoint(syntheticOverlayState, event);
1651
2009
  if (syntheticTarget !== null) {
1652
- return interactiveTargets.get(syntheticTarget) ?? null;
2010
+ return syntheticTarget;
1653
2011
  }
1654
2012
  return null;
1655
2013
  }
@@ -1676,8 +2034,9 @@ function normalizeMouseButton(event) {
1676
2034
  const button = event.button;
1677
2035
  return button === 0 || button === 1 || button === 2 ? button : null;
1678
2036
  }
1679
- function emitOverlayClick(target, button) {
2037
+ function emitOverlayClick(target, button, action) {
1680
2038
  activeClickHandler?.({
2039
+ ...(action ? { action } : {}),
1681
2040
  generation: target.generation,
1682
2041
  snapshotItemKey: target.snapshotItemKey,
1683
2042
  paintKey: target.paintKey,
@@ -1687,10 +2046,11 @@ function emitOverlayClick(target, button) {
1687
2046
  button,
1688
2047
  });
1689
2048
  }
1690
- function emitIframeInteraction(button) {
2049
+ function emitIframeInteraction(button, source) {
1691
2050
  activeInteractionHandler?.({
1692
2051
  kind: "pointerdown",
1693
2052
  button,
2053
+ ...(source ? { source } : {}),
1694
2054
  });
1695
2055
  }
1696
2056
  function ensureStyle(doc) {
@@ -1706,6 +2066,41 @@ function ensureStyle(doc) {
1706
2066
  display: none;
1707
2067
  transition: border-color 120ms ease, background-color 120ms ease;
1708
2068
  }
2069
+ [data-ss-comment-control] {
2070
+ all: initial; box-sizing: border-box; position: absolute; right: 0; top: 0;
2071
+ display: inline-flex; align-items: center; justify-content: center; gap: 6px;
2072
+ min-width: 32px; height: 32px; padding: 0; border: 0; border-radius: 999px;
2073
+ background: var(--ss-surface-card, #fff); color: var(--ss-text-primary, oklch(0.2 0.007 258.364));
2074
+ box-shadow: var(--ss-shadow-control, inset 0 0 0 1px rgb(0 0 0 / .085), 0 1px 2px -1px rgb(0 0 0 / .035), 0 3px 8px -5px rgb(0 0 0 / .045));
2075
+ cursor: pointer; pointer-events: auto; user-select: none; font: 500 12px/16px "Inter Variable", ui-sans-serif, system-ui, sans-serif;
2076
+ font-variant-numeric: tabular-nums; transition: background-color 120ms ease;
2077
+ }
2078
+ [data-ss-comment-control][hidden] { display: none; }
2079
+ [data-ss-comment-marker]:hover { filter: brightness(.95); }
2080
+ [data-ss-comment-menu-trigger]:hover, [data-ss-comment-menu-trigger][aria-expanded="true"] { opacity: .9; }
2081
+ [data-ss-comment-menu-trigger] svg { width: 14px; height: 14px; }
2082
+ [data-ss-comment-control]:hover, [data-ss-comment-menu-item]:hover { background: var(--ss-surface-interaction, oklch(0.946 0.001 250)); }
2083
+ [data-ss-comment-control] svg, [data-ss-comment-menu-item] svg { width: 16px; height: 16px; flex: none; pointer-events: none; }
2084
+ [data-ss-comment-count]:empty { display: none; }
2085
+ [data-ss-comment-menu] {
2086
+ all: initial; box-sizing: border-box; position: fixed; z-index: 2147483647;
2087
+ min-width: min(180px, calc(100vw - 16px)); max-width: calc(100vw - 16px); padding: 5px; border-radius: 14px;
2088
+ background: var(--ss-surface-card, #fff); color: var(--ss-text-primary, oklch(0.2 0.007 258.364));
2089
+ box-shadow: var(--ss-shadow-popover, 0 0 0 1px rgb(0 0 0 / .085), 0 2px 6px -4px rgb(0 0 0 / .12), 0 10px 24px -12px rgb(0 0 0 / .18)); pointer-events: auto;
2090
+ }
2091
+ [data-ss-comment-menu-item] {
2092
+ all: initial; box-sizing: border-box; display: flex; align-items: center; gap: 8px; width: 100%; min-height: 28px;
2093
+ padding: 5px 10px; border-radius: 7px; color: inherit; cursor: pointer; user-select: none; font: 400 14px/18px "Inter Variable", ui-sans-serif, system-ui, sans-serif;
2094
+ }
2095
+ [data-ss-comment-control]:focus-visible, [data-ss-comment-menu-item]:focus-visible { outline: 2px solid var(--ss-focus-color, oklch(0.614 0.194 257)); outline-offset: 2px; }
2096
+ [data-ss-comment-tooltip] {
2097
+ all: initial; box-sizing: border-box; position: fixed; z-index: 2147483647; max-width: min(260px, calc(100vw - 16px));
2098
+ padding: 6px 10px; border-radius: 12px; color: var(--ss-text-inverse, #fff); background: var(--ss-text-primary, oklch(0.2 0.007 258.364));
2099
+ font: 500 13px/17px "Inter Variable", ui-sans-serif, system-ui, sans-serif; pointer-events: none;
2100
+ box-shadow: var(--ss-shadow-floating-dark, 0 0 0 1px rgb(255 255 255 / .1), 0 12px 24px -12px rgb(0 0 0 / .5));
2101
+ }
2102
+ @media (prefers-reduced-motion: reduce) { [data-ss-comment-control] { transition: none; } }
2103
+ [${SYNTHETIC_BOX_ATTR}][data-comment-count]:not([data-comment-count="0"]),
1709
2104
  [${SYNTHETIC_ROOT_ATTR}][${DISPLAY_ATTR}="always"] [${SYNTHETIC_BOX_ATTR}],
1710
2105
  [${SYNTHETIC_BOX_ATTR}][${SYNTHETIC_BOX_STATE_ATTR}="hover"],
1711
2106
  [${SYNTHETIC_BOX_ATTR}][${SYNTHETIC_BOX_STATE_ATTR}="focus"],
@@ -1713,6 +2108,12 @@ function ensureStyle(doc) {
1713
2108
  display: block;
1714
2109
  }
1715
2110
  ${buildSyntheticOverlayStateCss()}
2111
+ [${SYNTHETIC_ROOT_ATTR}][${DISPLAY_ATTR}="hover"] [${SYNTHETIC_BOX_ATTR}][${SYNTHETIC_BOX_STATE_ATTR}="idle"] {
2112
+ border-color: transparent !important; background-color: transparent !important;
2113
+ }
2114
+ [${SYNTHETIC_ROOT_ATTR}][${DISPLAY_ATTR}="hover"] [${SYNTHETIC_BOX_ATTR}][${SYNTHETIC_BOX_STATE_ATTR}="idle"] [data-ss-comment-menu-trigger] {
2115
+ visibility: hidden;
2116
+ }
1716
2117
  `;
1717
2118
  const existing = doc.getElementById(STYLE_ID);
1718
2119
  if (existing !== null) {