2026-08-06 09f01778d5a034e2af50ae05da8908f7b6a871c8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
/**
 * Pure helpers for live-mode insert UI (browser + tests).
 * Kept separate from live-browser.js so insert logic is unit-testable.
 */
 
export const PLACEHOLDER_DEFAULT_HEIGHT = 80;
export const PLACEHOLDER_MIN_HEIGHT = 48;
export const PLACEHOLDER_MIN_WIDTH = 120;
 
/** @typedef {'before' | 'after'} InsertPosition */
/** @typedef {'row' | 'column'} InsertAxis */
 
/**
 * Infer sibling flow axis from a container's computed layout styles.
 * @param {{ display?: string, flexDirection?: string, gridTemplateColumns?: string, gridAutoFlow?: string }} style
 * @returns {InsertAxis}
 */
export function detectInsertAxisFromStyle(style) {
  const display = style?.display || 'block';
  if (display.includes('flex')) {
    const dir = style.flexDirection || 'row';
    return dir.startsWith('row') ? 'row' : 'column';
  }
  if (display === 'grid' || display === 'inline-grid') {
    const flow = style.gridAutoFlow || 'row';
    if (flow.includes('column')) return 'column';
    const cols = (style.gridTemplateColumns || '').trim();
    if (cols && cols !== 'none') {
      const colCount = cols.split(/\s+/).filter(Boolean).length;
      if (colCount > 1) return 'row';
    }
    return 'row';
  }
  return 'column';
}
 
/**
 * Pick insertion side from pointer position against an anchor element box.
 * @param {number} clientX
 * @param {number} clientY
 * @param {{ top: number, left: number, width: number, height: number, bottom?: number, right?: number }} rect
 * @param {InsertAxis} [axis]
 * @returns {InsertPosition}
 */
export function computeInsertPosition(clientX, clientY, rect, axis = 'column') {
  if (!rect) return 'after';
  if (axis === 'row') {
    if (!Number.isFinite(rect.left) || !Number.isFinite(rect.width) || rect.width <= 0) return 'after';
    const mid = rect.left + rect.width / 2;
    return clientX < mid ? 'before' : 'after';
  }
  if (!Number.isFinite(rect.top) || !Number.isFinite(rect.height) || rect.height <= 0) return 'after';
  const mid = rect.top + rect.height / 2;
  return clientY < mid ? 'before' : 'after';
}
 
/**
 * Whether Create is allowed for an insert session.
 * Requires a non-empty prompt OR at least one annotation.
 */
export function canCreateInsert({ prompt, comments, strokes }) {
  const hasPrompt = typeof prompt === 'string' && prompt.trim().length > 0;
  const hasComments = Array.isArray(comments) && comments.length > 0;
  const hasStrokes = Array.isArray(strokes) && strokes.some(
    (s) => Array.isArray(s?.points) && s.points.length >= 2,
  );
  return hasPrompt || hasComments || hasStrokes;
}
 
/** Tooltip/title when Create is disabled. */
export function insertCreateDisabledReason({ prompt, comments, strokes }) {
  if (canCreateInsert({ prompt, comments, strokes })) return null;
  return 'Add a prompt or annotate the placeholder to create';
}
 
/**
 * Fixed-position insert line coordinates (viewport px).
 * @param {{ top: number, left: number, width: number, height: number, bottom?: number, right?: number }} rect
 * @param {InsertPosition} position
 * @param {InsertAxis} [axis]
 */
export function insertLineCoords(rect, position, axis = 'column') {
  if (axis === 'row') {
    const right = rect.right ?? rect.left + rect.width;
    const x = position === 'before' ? rect.left - 2 : right + 2;
    return { axis: 'row', top: rect.top, left: x, width: 0, height: rect.height };
  }
  const bottom = rect.bottom ?? rect.top + rect.height;
  const y = position === 'before' ? rect.top - 2 : bottom + 2;
  return { axis: 'column', top: y, left: rect.left, width: rect.width, height: 0 };
}
 
/** Cursor while hovering an insert boundary. */
export function cursorForInsertAxis(axis) {
  return axis === 'row' ? 'ew-resize' : 'ns-resize';
}
 
function groupSiblingRows(siblings, rowThreshold = 8) {
  const sorted = [...siblings].sort((a, b) => a.rect.top - b.rect.top || a.rect.left - b.rect.left);
  const rows = [];
  for (const entry of sorted) {
    let placed = false;
    for (const row of rows) {
      if (Math.abs(entry.rect.top - row[0].rect.top) <= rowThreshold) {
        row.push(entry);
        placed = true;
        break;
      }
    }
    if (!placed) rows.push([entry]);
  }
  return rows;
}
 
function horizontalOverlap(a, b) {
  const left = Math.max(a.left, b.left);
  const right = Math.min(a.right ?? a.left + a.width, b.right ?? b.left + b.width);
  return Math.max(0, right - left);
}
 
/**
 * Hit-test the gap between adjacent siblings (flex rows, grid columns, stacked blocks).
 * @param {number} clientX
 * @param {number} clientY
 * @param {Array<{ el: unknown, rect: { top: number, left: number, width: number, height: number, bottom?: number, right?: number } }>} siblings
 * @param {{ slop?: number, minOverlap?: number }} [opts]
 */
export function hitSiblingInsertGap(clientX, clientY, siblings, opts = {}) {
  if (!Array.isArray(siblings) || siblings.length < 2) return null;
  const slop = opts.slop ?? 12;
  const minOverlap = opts.minOverlap ?? 0.25;
 
  for (const row of groupSiblingRows(siblings)) {
    if (row.length < 2) continue;
    const sorted = [...row].sort((a, b) => a.rect.left - b.rect.left);
    for (let i = 0; i < sorted.length - 1; i++) {
      const a = sorted[i];
      const b = sorted[i + 1];
      const aRight = a.rect.right ?? a.rect.left + a.rect.width;
      const bLeft = b.rect.left;
      if (bLeft <= aRight) continue;
      const top = Math.max(a.rect.top, b.rect.top);
      const aBottom = a.rect.bottom ?? a.rect.top + a.rect.height;
      const bBottom = b.rect.bottom ?? b.rect.top + b.rect.height;
      const bottom = Math.min(aBottom, bBottom);
      const span = bottom - top;
      const minH = Math.min(a.rect.height, b.rect.height);
      if (span < minH * minOverlap) continue;
 
      const inX = clientX >= aRight - slop && clientX <= bLeft + slop;
      const inY = clientY >= top - slop && clientY <= bottom + slop;
      if (!inX || !inY) continue;
 
      const midX = (aRight + bLeft) / 2;
      return {
        anchor: b.el,
        position: 'before',
        axis: 'row',
        line: { axis: 'row', left: midX, top, width: 0, height: span },
      };
    }
  }
 
  const sortedCol = [...siblings].sort((a, b) => a.rect.top - b.rect.top || a.rect.left - b.rect.left);
  for (let i = 0; i < sortedCol.length - 1; i++) {
    const a = sortedCol[i];
    const b = sortedCol[i + 1];
    const overlap = horizontalOverlap(a.rect, b.rect);
    const minW = Math.min(a.rect.width, b.rect.width);
    if (overlap < minW * minOverlap) continue;
 
    const aBottom = a.rect.bottom ?? a.rect.top + a.rect.height;
    const gapTop = aBottom;
    const gapBottom = b.rect.top;
    if (gapBottom <= gapTop) continue;
 
    const overlapLeft = Math.max(a.rect.left, b.rect.left);
    const overlapRight = Math.min(
      a.rect.right ?? a.rect.left + a.rect.width,
      b.rect.right ?? b.rect.left + b.rect.width,
    );
    const inY = clientY >= gapTop - slop && clientY <= gapBottom + slop;
    const inX = clientX >= overlapLeft - slop && clientX <= overlapRight + slop;
    if (!inY || !inX) continue;
 
    const midY = (gapTop + gapBottom) / 2;
    return {
      anchor: b.el,
      position: 'before',
      axis: 'column',
      line: { axis: 'column', top: midY, left: overlapLeft, width: overlap, height: 0 },
    };
  }
 
  return null;
}
 
/**
 * Resolve insert hover target, side, axis, and indicator line for the pointer.
 */
export function resolveInsertHover({ clientX, clientY, target, rect, axis, siblings }) {
  const gap = hitSiblingInsertGap(clientX, clientY, siblings);
  if (gap) return gap;
 
  const position = computeInsertPosition(clientX, clientY, rect, axis);
  const line = insertLineCoords(rect, position, axis);
  return { anchor: target, position, axis, line };
}
 
/**
 * How the in-flow placeholder should participate in layout.
 * Prefer implicit sizing (flex / %) so row inserts don't inherit the full parent width in px.
 * @returns {{ kind: 'flex', flex: string, minWidth: number } | { kind: 'percent' } | { kind: 'auto' } | { kind: 'explicit', width: number }}
 */
export function placeholderSizing({ axis, parentDisplay, parentWidth, anchorFlex }) {
  const display = parentDisplay || 'block';
  const w = Number.isFinite(parentWidth) ? parentWidth : 0;
 
  if (axis === 'row') {
    if (display.includes('flex')) {
      const flex = anchorFlex && anchorFlex !== 'none' && anchorFlex !== '0 1 auto'
        ? anchorFlex
        : '1 1 0';
      return { kind: 'flex', flex, minWidth: 0 };
    }
    if (display === 'grid' || display === 'inline-grid') {
      return { kind: 'auto' };
    }
  }
 
  if (w >= PLACEHOLDER_MIN_WIDTH) {
    return { kind: 'percent' };
  }
 
  return {
    kind: 'explicit',
    width: Math.max(PLACEHOLDER_MIN_WIDTH, w || PLACEHOLDER_MIN_WIDTH),
  };
}
 
/** Width kinds that need materializing to px before edge-resize. */
export function placeholderWidthIsImplicit(kind) {
  return kind === 'flex' || kind === 'percent' || kind === 'auto';
}
 
/**
 * Clamp user-resized placeholder dimensions.
 */
export function clampPlaceholderSize(width, height, parentWidth, opts = {}) {
  const minW = opts.minWidth ?? PLACEHOLDER_MIN_WIDTH;
  const minH = opts.minHeight ?? PLACEHOLDER_MIN_HEIGHT;
  const maxW = opts.maxWidth ?? Math.max(minW, parentWidth || minW);
  return {
    width: Math.min(maxW, Math.max(minW, Math.round(width))),
    height: Math.max(minH, Math.round(height)),
  };
}
 
/** CSS cursor for a placeholder edge resize handle. */
export function cursorForPlaceholderEdge(edge) {
  if (edge === 'n' || edge === 's') return 'ns-resize';
  if (edge === 'e' || edge === 'w') return 'ew-resize';
  return 'default';
}
 
/**
 * Compute placeholder box after dragging one edge (in-flow margins shift for n/w).
 * @param {{ width: number, height: number, marginLeft?: number, marginTop?: number }} start
 * @param {'n'|'e'|'s'|'w'} edge
 * @param {number} dx pointer delta X since drag start
 * @param {number} dy pointer delta Y since drag start
 * @param {number} parentWidth
 */
export function resizePlaceholderFromEdge(start, edge, dx, dy, parentWidth, opts = {}) {
  const base = {
    width: start.width,
    height: start.height,
    marginLeft: start.marginLeft ?? 0,
    marginTop: start.marginTop ?? 0,
  };
  if (edge === 'e') base.width = start.width + dx;
  else if (edge === 'w') {
    base.width = start.width - dx;
    base.marginLeft = start.marginLeft + dx;
  } else if (edge === 's') base.height = start.height + dy;
  else if (edge === 'n') {
    base.height = start.height - dy;
    base.marginTop = start.marginTop + dy;
  }
 
  const clamped = clampPlaceholderSize(base.width, base.height, parentWidth, opts);
  if (edge === 'w') {
    base.marginLeft = start.marginLeft + start.width - clamped.width;
  } else if (edge === 'n') {
    base.marginTop = start.marginTop + start.height - clamped.height;
  }
 
  return {
    width: clamped.width,
    height: clamped.height,
    marginLeft: Math.round(base.marginLeft),
    marginTop: Math.round(base.marginTop),
  };
}
 
/** Pick and insert toggles are independent but turning one ON turns the other OFF. */
export function applyPickToggle(pickActive, insertActive) {
  const nextPick = !pickActive;
  return {
    pickActive: nextPick,
    insertActive: nextPick ? false : insertActive,
  };
}
 
export function applyInsertToggle(pickActive, insertActive) {
  const nextInsert = !insertActive;
  return {
    pickActive: nextInsert ? false : pickActive,
    insertActive: nextInsert,
  };
}
 
/**
 * Build the browser generate payload for insert mode.
 */
export function buildInsertGeneratePayload({
  id,
  count,
  pageUrl,
  anchorContext,
  position,
  placeholder,
  freeformPrompt,
  comments,
  strokes,
  screenshotPath,
}) {
  const payload = {
    type: 'generate',
    mode: 'insert',
    id,
    count,
    pageUrl,
    insert: {
      position,
      anchor: anchorContext,
    },
    placeholder,
    freeformPrompt: freeformPrompt?.trim() || undefined,
  };
  if (comments?.length) payload.comments = comments;
  if (strokes?.length) payload.strokes = strokes;
  if (screenshotPath) payload.screenshotPath = screenshotPath;
  return payload;
}
 
/**
 * Whether a variant wrapper is currently shown (handles `hidden` and display:none).
 * @param {{ hidden?: boolean, style?: { display?: string } } | null | undefined} el
 */
export function isVariantShown(el) {
  if (!el) return false;
  if (el.hidden) return false;
  if (el.style?.display === 'none') return false;
  return true;
}
 
/**
 * Show or hide a variant wrapper for cycling.
 * @param {{ hidden?: boolean, style?: { display?: string }, removeAttribute?: (name: string) => void, setAttribute?: (name: string, value?: string) => void } | null | undefined} el
 * @param {boolean} shown
 */
export function setVariantShown(el, shown) {
  if (!el) return;
  if (shown) {
    el.removeAttribute?.('hidden');
    if (el.style) el.style.display = '';
  } else {
    el.setAttribute?.('hidden', '');
    if (el.style) el.style.display = 'none';
  }
}
 
/**
 * Pick the best live anchor during an insert session (placeholder until variants land).
 * @param {{
 *   wrapper?: unknown,
 *   variantCount?: number,
 *   visibleVariant?: number,
 *   placeholder?: unknown,
 *   insertAnchor?: unknown,
 *   pickVariantContent?: (wrapper: unknown, index: number) => unknown,
 * }} opts
 */
export function resolveInsertSessionAnchor(opts) {
  const {
    wrapper,
    variantCount = 0,
    visibleVariant = 0,
    placeholder,
    insertAnchor,
    pickVariantContent,
  } = opts || {};
  if (wrapper && variantCount > 0 && visibleVariant > 0 && pickVariantContent) {
    const vis = pickVariantContent(wrapper, visibleVariant);
    if (vis) return vis;
  }
  return placeholder || insertAnchor || null;
}
 
/**
 * Snapshot placeholder geometry + anchor fingerprint so HMR can recreate the box.
 * @param {{
 *   tagName?: string,
 *   className?: string,
 *   textContent?: string,
 * }} anchor
 * @param {{
 *   offsetWidth?: number,
 *   offsetHeight?: number,
 *   style?: { marginLeft?: string, marginTop?: string },
 * }} placeholder
 * @param {{ position: 'before' | 'after', layoutAxis?: 'row' | 'column' }} meta
 */
export function buildInsertPlaceholderSnapshot(anchor, placeholder, { position, layoutAxis }) {
  return {
    width: Math.round(placeholder.offsetWidth || 0),
    height: Math.round(placeholder.offsetHeight || PLACEHOLDER_DEFAULT_HEIGHT),
    marginLeft: parseFloat(placeholder.style?.marginLeft || '') || 0,
    marginTop: parseFloat(placeholder.style?.marginTop || '') || 0,
    position,
    layoutAxis: layoutAxis || 'column',
    anchorTag: anchor.tagName || 'DIV',
    anchorClasses: anchor.className || '',
    anchorText: (anchor.textContent || '').trim().slice(0, 120),
  };
}
 
/**
 * Re-find an insert anchor after framework HMR replaced the live DOM node.
 * @param {Pick<Document, 'body' | 'querySelectorAll'>} doc
 * @param {ReturnType<typeof buildInsertPlaceholderSnapshot> | null | undefined} snapshot
 * @param {Element | null | undefined} liveAnchor
 */
export function findInsertAnchorInDom(doc, snapshot, liveAnchor = null) {
  if (liveAnchor && doc.body.contains(liveAnchor)) return liveAnchor;
  if (!snapshot) return null;
  const tag = (snapshot.anchorTag || 'div').toLowerCase();
  const cls = (snapshot.anchorClasses || '').split(/\s+/).filter(Boolean)[0];
  const needle = snapshot.anchorText || '';
  const sel = cls ? `${tag}.${cls}` : tag;
  const candidates = doc.querySelectorAll(sel);
  for (const candidate of candidates) {
    if (needle && !(candidate.textContent || '').includes(needle.slice(0, 40))) continue;
    return candidate;
  }
  return null;
}