@open-slide/core 2.0.1 → 2.2.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.
Files changed (57) hide show
  1. package/dist/{build-DOgOEZZA.js → build-DTmKJyjX.js} +1 -1
  2. package/dist/cli/bin.js +4 -4
  3. package/dist/{config-hT1o6Jct.js → config-Ces2X_3T.js} +159 -17
  4. package/dist/{config-GMR1QUlM.d.ts → config-CpmGqpQi.d.ts} +1 -1
  5. package/dist/{dev-_YkLNJRt.js → dev-ldYag-pR.js} +1 -1
  6. package/dist/index.d.ts +2 -2
  7. package/dist/index.js +4 -3
  8. package/dist/locale/index.d.ts +5 -2
  9. package/dist/locale/index.js +2 -2
  10. package/dist/{preview-pABcGTQh.js → preview-GYMbZvvk.js} +1 -1
  11. package/dist/{types-BcbaKTNY.d.ts → types-CvAqFqsY.d.ts} +10 -5
  12. package/dist/{update-moCkSyvg.js → update-CPBitJQq.js} +24 -14
  13. package/dist/vite/index.d.ts +1 -1
  14. package/dist/vite/index.js +1 -1
  15. package/dist/{zh-tw-DlZoAc2-.js → zh-tw-B7_Oqv2q.js} +550 -17
  16. package/package.json +3 -3
  17. package/skills/apply-comments/SKILL.md +10 -6
  18. package/skills/create-slide/SKILL.md +2 -0
  19. package/skills/current-slide/SKILL.md +1 -0
  20. package/skills/slide-authoring/SKILL.md +31 -1
  21. package/src/app/app.tsx +2 -0
  22. package/src/app/assets/open-slide.svg +39 -0
  23. package/src/app/components/command/command-menu.tsx +1 -3
  24. package/src/app/components/history-provider.tsx +25 -3
  25. package/src/app/components/icon-switcher-indicator.tsx +1 -1
  26. package/src/app/components/inspector/comment-layer.tsx +992 -0
  27. package/src/app/components/inspector/inspect-overlay.tsx +2 -39
  28. package/src/app/components/inspector/inspector-panel.tsx +9 -92
  29. package/src/app/components/inspector/inspector-provider.tsx +299 -67
  30. package/src/app/components/panel/editor-sidebar.tsx +1 -1
  31. package/src/app/components/panel/save-card.tsx +6 -2
  32. package/src/app/components/preview-step-host.tsx +16 -0
  33. package/src/app/components/sidebar/sidebar.tsx +2 -2
  34. package/src/app/components/slide-transition-layer.tsx +1 -1
  35. package/src/app/components/style-panel/style-panel.tsx +3 -2
  36. package/src/app/components/thumbnail-rail.tsx +76 -1
  37. package/src/app/favicon.ico +0 -0
  38. package/src/app/favicon.svg +39 -0
  39. package/src/app/index.html +2 -1
  40. package/src/app/lib/inspector/freeze-motion.ts +61 -0
  41. package/src/app/lib/inspector/use-comments.ts +32 -3
  42. package/src/app/lib/keys.ts +3 -0
  43. package/src/app/lib/locale-store.ts +6 -1
  44. package/src/app/lib/print-ready.ts +9 -6
  45. package/src/app/routes/presenter.tsx +1 -16
  46. package/src/app/routes/preview.tsx +169 -0
  47. package/src/app/routes/slide.tsx +119 -70
  48. package/src/app/styles.css +64 -80
  49. package/src/locale/en.ts +7 -4
  50. package/src/locale/es.ts +550 -0
  51. package/src/locale/index.ts +1 -0
  52. package/src/locale/ja.ts +7 -5
  53. package/src/locale/types.ts +10 -5
  54. package/src/locale/zh-cn.ts +7 -4
  55. package/src/locale/zh-tw.ts +7 -4
  56. package/src/app/assets/open-slide.png +0 -0
  57. package/src/app/components/inspector/comment-widget.tsx +0 -119
@@ -0,0 +1,992 @@
1
+ import { ArrowUp, Check, MessageSquare, Trash2 } from 'lucide-react';
2
+ import {
3
+ type ComponentProps,
4
+ type CSSProperties,
5
+ type ReactNode,
6
+ type RefObject,
7
+ useCallback,
8
+ useEffect,
9
+ useLayoutEffect,
10
+ useRef,
11
+ useState,
12
+ } from 'react';
13
+ import { toast } from 'sonner';
14
+ import { findSlideSource } from '@/lib/inspector/fiber';
15
+ import { useFreezeSlideMotion } from '@/lib/inspector/freeze-motion';
16
+ import { type Point, type Rect, rectContains } from '@/lib/inspector/geometry';
17
+ import {
18
+ isInspectableEventTarget,
19
+ pickElement,
20
+ pickInspectorTarget,
21
+ } from '@/lib/inspector/pick-target';
22
+ import type { CommentRect, SlideComment } from '@/lib/inspector/use-comments';
23
+ import { type Canvas, readCanvas, readFrame } from '@/lib/inspector/visual-dom';
24
+ import { IS_APPLE, isTypingTarget } from '@/lib/keys';
25
+ import { format, plural, useLocale } from '@/lib/use-locale';
26
+ import { cn } from '@/lib/utils';
27
+ import { type SelectedTarget, useInspector } from './inspector-provider';
28
+
29
+ type ScreenRect = { left: number; top: number; width: number; height: number };
30
+ type Size = { width: number; height: number };
31
+
32
+ type Draft =
33
+ | { kind: 'element'; target: SelectedTarget }
34
+ | { kind: 'region'; rect: Rect; target: SelectedTarget };
35
+
36
+ type Gesture = {
37
+ pointerId: number;
38
+ start: Point;
39
+ hit: SelectedTarget | null;
40
+ canvas: Canvas;
41
+ moved: boolean;
42
+ };
43
+
44
+ type PinLayout = { frame: ScreenRect; region: boolean };
45
+
46
+ type Layout = {
47
+ width: number;
48
+ height: number;
49
+ canvas: ScreenRect | null;
50
+ scale: number;
51
+ pins: Record<string, PinLayout>;
52
+ hoverFrame: ScreenRect | null;
53
+ draftFrame: ScreenRect | null;
54
+ };
55
+
56
+ const EMPTY_LAYOUT: Layout = {
57
+ width: 0,
58
+ height: 0,
59
+ canvas: null,
60
+ scale: 1,
61
+ pins: {},
62
+ hoverFrame: null,
63
+ draftFrame: null,
64
+ };
65
+
66
+ // A freshly written marker shifts source lines, so a comment's `target`
67
+ // can point at a loc the canvas only picks up once HMR re-renders — and
68
+ // that reload can remount this layer. Remember each pin's last frame
69
+ // across mounts so it doesn't jump to the fallback corner in between.
70
+ const rememberedFrames = new Map<string, PinLayout>();
71
+
72
+ const PIN = 24;
73
+ const GAP = 8;
74
+ const MIN_REGION = 6;
75
+
76
+ function pinRect(frame: ScreenRect): ScreenRect {
77
+ return { left: frame.left + frame.width - 3, top: frame.top - PIN + 3, width: PIN, height: PIN };
78
+ }
79
+
80
+ function placeBeside(anchor: ScreenRect, size: Size, bounds: Size): { left: number; top: number } {
81
+ let left = anchor.left + anchor.width + GAP;
82
+ if (left + size.width > bounds.width - GAP) left = anchor.left - size.width - GAP;
83
+ if (left < GAP) left = Math.max(GAP, Math.min(anchor.left, bounds.width - size.width - GAP));
84
+ const top = Math.max(GAP, Math.min(anchor.top, bounds.height - size.height - GAP));
85
+ return { left, top };
86
+ }
87
+
88
+ function fallbackFrame(canvas: Canvas): Rect {
89
+ return { x: canvas.width - 72, y: 24, width: 48, height: 48 };
90
+ }
91
+
92
+ // Deepest host element whose box fully contains the drawn region; falls
93
+ // back to the largest host element (usually the page wrapper) so the
94
+ // marker always has a JSX container to live in.
95
+ function containerFor(rect: Rect, canvas: Canvas, slideId: string): SelectedTarget | null {
96
+ const tolerance = {
97
+ x: rect.x - 1,
98
+ y: rect.y - 1,
99
+ width: rect.width + 2,
100
+ height: rect.height + 2,
101
+ };
102
+ let best: { target: SelectedTarget; area: number } | null = null;
103
+ let largest: { target: SelectedTarget; area: number } | null = null;
104
+ const seen = new Set<HTMLElement>();
105
+ for (const element of canvas.root.querySelectorAll<HTMLElement>('[data-slide-loc]')) {
106
+ const hit = findSlideSource(element, slideId, { hostOnly: true });
107
+ if (!hit || seen.has(hit.anchor)) continue;
108
+ seen.add(hit.anchor);
109
+ const frame = readFrame(hit.anchor, canvas);
110
+ const area = frame.width * frame.height;
111
+ if (!area) continue;
112
+ if (!largest || area > largest.area) largest = { target: hit, area };
113
+ if (rectContains(frame, tolerance) && (!best || area < best.area)) best = { target: hit, area };
114
+ }
115
+ return best?.target ?? largest?.target ?? null;
116
+ }
117
+
118
+ export function CommentLayer() {
119
+ const { commentMode, exitCommentMode, slideId, pageIndex, comments, add, update, remove, error } =
120
+ useInspector();
121
+ const t = useLocale();
122
+ useFreezeSlideMotion(commentMode ? 'comment' : null);
123
+ const overlayRef = useRef<HTMLDivElement>(null);
124
+ const gestureRef = useRef<Gesture | null>(null);
125
+ const [hover, setHover] = useState<HTMLElement | null>(null);
126
+ const [marquee, setMarquee] = useState<Rect | null>(null);
127
+ const [draft, setDraft] = useState<Draft | null>(null);
128
+ const [openId, setOpenId] = useState<string | null>(null);
129
+ const [hoverId, setHoverId] = useState<string | null>(null);
130
+ const [layout, setLayout] = useState<Layout>(EMPTY_LAYOUT);
131
+
132
+ useEffect(() => {
133
+ if (commentMode) return;
134
+ gestureRef.current = null;
135
+ setHover(null);
136
+ setMarquee(null);
137
+ setDraft(null);
138
+ setOpenId(null);
139
+ setHoverId(null);
140
+ }, [commentMode]);
141
+
142
+ useEffect(() => {
143
+ void pageIndex;
144
+ setDraft(null);
145
+ setOpenId(null);
146
+ }, [pageIndex]);
147
+
148
+ useLayoutEffect(() => {
149
+ if (!commentMode) return;
150
+ const root = document.querySelector<HTMLElement>('[data-inspector-root]');
151
+ let raf = 0;
152
+ const measure = () => {
153
+ const overlay = overlayRef.current;
154
+ const canvas = readCanvas();
155
+ if (!overlay || !canvas) return;
156
+ const origin = overlay.getBoundingClientRect();
157
+ const screen = (rect: Rect): ScreenRect => ({
158
+ left: canvas.rect.left - origin.left + rect.x * canvas.scale,
159
+ top: canvas.rect.top - origin.top + rect.y * canvas.scale,
160
+ width: rect.width * canvas.scale,
161
+ height: rect.height * canvas.scale,
162
+ });
163
+ const element = (anchor: HTMLElement): ScreenRect => {
164
+ const box = anchor.getBoundingClientRect();
165
+ return {
166
+ left: box.left - origin.left,
167
+ top: box.top - origin.top,
168
+ width: box.width,
169
+ height: box.height,
170
+ };
171
+ };
172
+ const region = (rect: CommentRect): ScreenRect =>
173
+ screen({ x: rect.x, y: rect.y, width: rect.w, height: rect.h });
174
+ const pins: Record<string, PinLayout> = {};
175
+ for (const comment of comments) {
176
+ const memoryKey = `${slideId}:${comment.id}`;
177
+ // Pages often share a wrapper component, so the target loc alone
178
+ // would match on every page; the stored page index decides.
179
+ if (comment.page !== undefined && comment.page !== pageIndex) continue;
180
+ const anchor = comment.target
181
+ ? canvas.root.querySelector<HTMLElement>(
182
+ `[data-slide-loc="${comment.target.line}:${comment.target.column}"]`,
183
+ )
184
+ : null;
185
+ if (anchor) {
186
+ pins[comment.id] = {
187
+ frame: comment.rect ? region(comment.rect) : element(anchor),
188
+ region: !!comment.rect,
189
+ };
190
+ rememberedFrames.set(memoryKey, pins[comment.id]);
191
+ } else if (comment.page === pageIndex) {
192
+ pins[comment.id] = comment.rect
193
+ ? { frame: region(comment.rect), region: true }
194
+ : (rememberedFrames.get(memoryKey) ?? {
195
+ frame: screen(fallbackFrame(canvas)),
196
+ region: false,
197
+ });
198
+ }
199
+ }
200
+ const draftFrame = !draft
201
+ ? null
202
+ : draft.kind === 'region'
203
+ ? screen(draft.rect)
204
+ : draft.target.anchor.isConnected
205
+ ? element(draft.target.anchor)
206
+ : null;
207
+ const next: Layout = {
208
+ width: origin.width,
209
+ height: origin.height,
210
+ canvas: screen({ x: 0, y: 0, width: canvas.width, height: canvas.height }),
211
+ scale: canvas.scale,
212
+ pins,
213
+ hoverFrame: hover?.isConnected ? element(hover) : null,
214
+ draftFrame,
215
+ };
216
+ setLayout((previous) =>
217
+ JSON.stringify(previous) === JSON.stringify(next) ? previous : next,
218
+ );
219
+ };
220
+ const schedule = () => {
221
+ if (raf) return;
222
+ raf = requestAnimationFrame(() => {
223
+ raf = 0;
224
+ measure();
225
+ });
226
+ };
227
+ const stopAt = performance.now() + 420;
228
+ const track = () => {
229
+ measure();
230
+ if (performance.now() < stopAt) raf = requestAnimationFrame(track);
231
+ else raf = 0;
232
+ };
233
+ track();
234
+ const resize = new ResizeObserver(schedule);
235
+ if (overlayRef.current) resize.observe(overlayRef.current);
236
+ const mutations = root ? new MutationObserver(schedule) : null;
237
+ mutations?.observe(root as HTMLElement, {
238
+ childList: true,
239
+ subtree: true,
240
+ attributes: true,
241
+ attributeFilter: ['data-slide-loc', 'style', 'class'],
242
+ });
243
+ window.addEventListener('resize', schedule);
244
+ window.addEventListener('scroll', schedule, true);
245
+ return () => {
246
+ cancelAnimationFrame(raf);
247
+ resize.disconnect();
248
+ mutations?.disconnect();
249
+ window.removeEventListener('resize', schedule);
250
+ window.removeEventListener('scroll', schedule, true);
251
+ };
252
+ }, [commentMode, comments, pageIndex, hover, draft, slideId]);
253
+
254
+ useEffect(() => {
255
+ if (!commentMode) return;
256
+ const targetAt = (event: PointerEvent): SelectedTarget | null => {
257
+ const element = pickInspectorTarget(pickElement(event.clientX, event.clientY));
258
+ return element ? findSlideSource(element, slideId, { hostOnly: true }) : null;
259
+ };
260
+ const point = (event: PointerEvent, canvas: Canvas): Point => ({
261
+ x: (event.clientX - canvas.rect.left) / canvas.scale,
262
+ y: (event.clientY - canvas.rect.top) / canvas.scale,
263
+ });
264
+ const onDown = (event: PointerEvent) => {
265
+ if (event.button !== 0 || !event.isPrimary || gestureRef.current) return;
266
+ if (!isInspectableEventTarget(event.target)) return;
267
+ const canvas = readCanvas();
268
+ if (!canvas) return;
269
+ if (document.activeElement instanceof HTMLElement) document.activeElement.blur();
270
+ setDraft(null);
271
+ setOpenId(null);
272
+ gestureRef.current = {
273
+ pointerId: event.pointerId,
274
+ start: point(event, canvas),
275
+ hit: targetAt(event),
276
+ canvas,
277
+ moved: false,
278
+ };
279
+ event.preventDefault();
280
+ event.stopPropagation();
281
+ };
282
+ const onMove = (event: PointerEvent) => {
283
+ const gesture = gestureRef.current;
284
+ if (gesture) {
285
+ if (gesture.pointerId !== event.pointerId) return;
286
+ const current = point(event, gesture.canvas);
287
+ const delta = { x: current.x - gesture.start.x, y: current.y - gesture.start.y };
288
+ if (!gesture.moved && Math.hypot(delta.x, delta.y) * gesture.canvas.scale < 3) return;
289
+ gesture.moved = true;
290
+ setHover(null);
291
+ setMarquee({
292
+ x: Math.min(gesture.start.x, current.x),
293
+ y: Math.min(gesture.start.y, current.y),
294
+ width: Math.abs(delta.x),
295
+ height: Math.abs(delta.y),
296
+ });
297
+ return;
298
+ }
299
+ if (!isInspectableEventTarget(event.target)) {
300
+ setHover(null);
301
+ return;
302
+ }
303
+ setHover(targetAt(event)?.anchor ?? null);
304
+ };
305
+ const finish = (event: PointerEvent, cancelled: boolean) => {
306
+ const gesture = gestureRef.current;
307
+ if (!gesture || gesture.pointerId !== event.pointerId) return;
308
+ gestureRef.current = null;
309
+ setMarquee(null);
310
+ if (cancelled) return;
311
+ if (gesture.moved) {
312
+ const current = point(event, gesture.canvas);
313
+ const rect = {
314
+ x: Math.min(gesture.start.x, current.x),
315
+ y: Math.min(gesture.start.y, current.y),
316
+ width: Math.abs(current.x - gesture.start.x),
317
+ height: Math.abs(current.y - gesture.start.y),
318
+ };
319
+ if (
320
+ rect.width * gesture.canvas.scale < MIN_REGION ||
321
+ rect.height * gesture.canvas.scale < MIN_REGION
322
+ )
323
+ return;
324
+ const target = containerFor(rect, gesture.canvas, slideId);
325
+ if (!target) {
326
+ toast.error(t.inspector.commentRegionNoTarget);
327
+ return;
328
+ }
329
+ setDraft({ kind: 'region', rect, target });
330
+ return;
331
+ }
332
+ if (gesture.hit) setDraft({ kind: 'element', target: gesture.hit });
333
+ };
334
+ const onUp = (event: PointerEvent) => finish(event, false);
335
+ const onCancel = (event: Event) => {
336
+ if (event instanceof PointerEvent) finish(event, true);
337
+ else {
338
+ gestureRef.current = null;
339
+ setMarquee(null);
340
+ }
341
+ };
342
+ const onClick = (event: MouseEvent) => {
343
+ if (!isInspectableEventTarget(event.target)) return;
344
+ event.preventDefault();
345
+ event.stopImmediatePropagation();
346
+ };
347
+ const onKey = (event: KeyboardEvent) => {
348
+ if (event.key !== 'Escape' || event.isComposing || event.keyCode === 229) return;
349
+ if (isTypingTarget(event.target) && !overlayRef.current?.contains(event.target as Node))
350
+ return;
351
+ if (
352
+ event.target instanceof Element &&
353
+ event.target.closest('[role="dialog"], [role="menu"], [role="listbox"]')
354
+ )
355
+ return;
356
+ event.preventDefault();
357
+ event.stopImmediatePropagation();
358
+ if (gestureRef.current) {
359
+ gestureRef.current = null;
360
+ setMarquee(null);
361
+ } else if (draft) setDraft(null);
362
+ else if (openId) setOpenId(null);
363
+ else exitCommentMode();
364
+ };
365
+ window.addEventListener('pointerdown', onDown, true);
366
+ window.addEventListener('pointermove', onMove, true);
367
+ window.addEventListener('pointerup', onUp, true);
368
+ window.addEventListener('pointercancel', onCancel, true);
369
+ window.addEventListener('blur', onCancel);
370
+ window.addEventListener('click', onClick, true);
371
+ window.addEventListener('keydown', onKey, true);
372
+ return () => {
373
+ window.removeEventListener('pointerdown', onDown, true);
374
+ window.removeEventListener('pointermove', onMove, true);
375
+ window.removeEventListener('pointerup', onUp, true);
376
+ window.removeEventListener('pointercancel', onCancel, true);
377
+ window.removeEventListener('blur', onCancel);
378
+ window.removeEventListener('click', onClick, true);
379
+ window.removeEventListener('keydown', onKey, true);
380
+ };
381
+ }, [commentMode, slideId, draft, openId, exitCommentMode, t]);
382
+
383
+ const submit = useCallback(
384
+ async (text: string) => {
385
+ if (!draft) return;
386
+ const { target } = draft;
387
+ const rect =
388
+ draft.kind === 'region'
389
+ ? {
390
+ x: Math.round(draft.rect.x),
391
+ y: Math.round(draft.rect.y),
392
+ w: Math.round(draft.rect.width),
393
+ h: Math.round(draft.rect.height),
394
+ }
395
+ : undefined;
396
+ try {
397
+ await add({ line: target.line, column: target.column, text, rect, page: pageIndex });
398
+ setDraft(null);
399
+ } catch (err) {
400
+ toast.error(`${t.inspector.commentAddFailed} ${String((err as Error).message ?? err)}`);
401
+ }
402
+ },
403
+ [draft, add, pageIndex, t],
404
+ );
405
+
406
+ const handleUpdate = useCallback(
407
+ async (id: string, text: string) => {
408
+ try {
409
+ await update(id, text);
410
+ setOpenId(null);
411
+ } catch (err) {
412
+ toast.error(`${t.inspector.commentUpdateFailed} ${String((err as Error).message ?? err)}`);
413
+ }
414
+ },
415
+ [update, t],
416
+ );
417
+
418
+ const handleRemove = useCallback(
419
+ async (id: string) => {
420
+ try {
421
+ await remove(id);
422
+ setOpenId((current) => (current === id ? null : current));
423
+ } catch (err) {
424
+ toast.error(String((err as Error).message ?? err));
425
+ }
426
+ },
427
+ [remove],
428
+ );
429
+
430
+ if (!commentMode) return null;
431
+
432
+ const bounds = { width: layout.width, height: layout.height };
433
+ const toScreen = (rect: Rect): ScreenRect => ({
434
+ left: (layout.canvas?.left ?? 0) + rect.x * layout.scale,
435
+ top: (layout.canvas?.top ?? 0) + rect.y * layout.scale,
436
+ width: rect.width * layout.scale,
437
+ height: rect.height * layout.scale,
438
+ });
439
+ const count = comments.length;
440
+
441
+ return (
442
+ <div
443
+ ref={overlayRef}
444
+ data-inspector-ui
445
+ data-comment-layer
446
+ className="pointer-events-none absolute inset-0 z-30 select-none"
447
+ >
448
+ {layout.hoverFrame && !gestureRef.current && !draft && (
449
+ <div className="absolute border border-dashed border-brand/70" style={layout.hoverFrame} />
450
+ )}
451
+ {marquee && (
452
+ <div className="absolute border border-brand bg-brand/10" style={toScreen(marquee)} />
453
+ )}
454
+ {comments.map((comment) => {
455
+ const pin = layout.pins[comment.id];
456
+ if (!pin) return null;
457
+ const open = openId === comment.id;
458
+ return (
459
+ <CommentPin
460
+ key={comment.id}
461
+ comment={comment}
462
+ frame={pin.frame}
463
+ region={pin.region}
464
+ anchor={pinRect(pin.frame)}
465
+ bounds={bounds}
466
+ open={open}
467
+ hovered={hoverId === comment.id}
468
+ onToggle={() => {
469
+ setDraft(null);
470
+ setOpenId(open ? null : comment.id);
471
+ }}
472
+ onHover={(hovering) => setHoverId(hovering ? comment.id : null)}
473
+ onSave={(text) => handleUpdate(comment.id, text)}
474
+ onRemove={() => handleRemove(comment.id)}
475
+ />
476
+ );
477
+ })}
478
+ {draft && layout.draftFrame && (
479
+ <Composer
480
+ frame={layout.draftFrame}
481
+ region={draft.kind === 'region'}
482
+ anchor={pinRect(layout.draftFrame)}
483
+ bounds={bounds}
484
+ onSubmit={submit}
485
+ />
486
+ )}
487
+ <div className="absolute inset-x-0 bottom-3 flex justify-center">
488
+ <IslandHint
489
+ contentKey={error ? 'error' : count === 0 ? 'empty' : 'count'}
490
+ tone={error ? 'error' : 'default'}
491
+ >
492
+ {error ? (
493
+ error
494
+ ) : count === 0 ? (
495
+ t.inspector.commentEmptyHint
496
+ ) : (
497
+ <>
498
+ <CommentCountLabel count={count} />
499
+ <span aria-hidden className="mx-1.5">
500
+ ·
501
+ </span>
502
+ {t.inspector.commentsApplyHintPrefix}
503
+ <code className="rounded bg-muted px-1 py-0.5 font-mono text-foreground">
504
+ /apply-comments
505
+ </code>
506
+ {t.inspector.commentsApplyHintSuffix}
507
+ </>
508
+ )}
509
+ </IslandHint>
510
+ </div>
511
+ </div>
512
+ );
513
+ }
514
+
515
+ const ISLAND_SWAP_MS = 320;
516
+ const SUBMIT_SHORTCUT = IS_APPLE ? '⌘↵' : 'Ctrl ↵';
517
+
518
+ // Only the digits roll when the count changes; the surrounding words
519
+ // stay put so the pill reads as a counter ticking, not a text swap.
520
+ function CommentCountLabel({ count }: { count: number }) {
521
+ const t = useLocale();
522
+ const [prefix, suffix] = plural(count, t.inspector.commentsCount).split('{count}');
523
+ return (
524
+ <span className="font-medium text-foreground nums">
525
+ {prefix}
526
+ <RollingNumber value={count} />
527
+ {suffix}
528
+ </span>
529
+ );
530
+ }
531
+
532
+ function RollingNumber({ value }: { value: number }) {
533
+ const [outgoing, setOutgoing] = useState<number | null>(null);
534
+ const lastRef = useRef(value);
535
+ useLayoutEffect(() => {
536
+ const previous = lastRef.current;
537
+ if (previous === value) return;
538
+ lastRef.current = value;
539
+ setOutgoing(previous);
540
+ const timer = setTimeout(() => setOutgoing(null), ISLAND_SWAP_MS);
541
+ return () => clearTimeout(timer);
542
+ }, [value]);
543
+ const direction = outgoing !== null && value < outgoing ? -1 : 1;
544
+ return (
545
+ <span
546
+ className="inline-grid overflow-hidden align-bottom"
547
+ style={{ '--roll': direction } as CSSProperties}
548
+ >
549
+ {outgoing !== null && (
550
+ <span key={`out-${outgoing}`} aria-hidden className="roll-leave col-start-1 row-start-1">
551
+ {outgoing}
552
+ </span>
553
+ )}
554
+ <span
555
+ key={`in-${value}`}
556
+ className={cn('col-start-1 row-start-1', outgoing !== null && 'roll-arrive')}
557
+ >
558
+ {value}
559
+ </span>
560
+ </span>
561
+ );
562
+ }
563
+
564
+ // The pill resizes to whatever it says, Dynamic Island style: the shell
565
+ // animates its width while the outgoing text blurs out and the new text
566
+ // blurs in. The shell's width is driven by the incoming content alone so
567
+ // it never waits for the old text to unmount.
568
+ function IslandHint({
569
+ contentKey,
570
+ tone,
571
+ children,
572
+ }: {
573
+ contentKey: string;
574
+ tone: 'default' | 'error';
575
+ children: ReactNode;
576
+ }) {
577
+ const contentRef = useRef<HTMLSpanElement>(null);
578
+ const [width, setWidth] = useState<number | null>(null);
579
+ const [outgoing, setOutgoing] = useState<{ key: string; node: ReactNode } | null>(null);
580
+ const lastRef = useRef<{ key: string; node: ReactNode }>({ key: contentKey, node: children });
581
+
582
+ useLayoutEffect(() => {
583
+ const previous = lastRef.current;
584
+ lastRef.current = { key: contentKey, node: children };
585
+ if (previous.key === contentKey) return;
586
+ setOutgoing(previous);
587
+ const timer = setTimeout(() => setOutgoing(null), ISLAND_SWAP_MS);
588
+ return () => clearTimeout(timer);
589
+ }, [contentKey, children]);
590
+
591
+ // The content span remounts per key, and its entrance scales it, so
592
+ // re-attach per key and read the unscaled layout width.
593
+ // biome-ignore lint/correctness/useExhaustiveDependencies: re-observe the remounted span
594
+ useLayoutEffect(() => {
595
+ const node = contentRef.current;
596
+ if (!node) return;
597
+ const update = () => setWidth(node.offsetWidth);
598
+ update();
599
+ const observer = new ResizeObserver(update);
600
+ observer.observe(node);
601
+ return () => observer.disconnect();
602
+ }, [contentKey]);
603
+
604
+ return (
605
+ <div
606
+ data-comment-hint
607
+ className={cn(
608
+ 'island-enter grid max-w-[calc(100%-2rem)] justify-items-start overflow-hidden rounded-full border bg-card/95 px-3 py-1.5 text-[11px] text-muted-foreground shadow-floating backdrop-blur',
609
+ 'motion-safe:transition-[width] motion-safe:duration-500 motion-safe:ease-[cubic-bezier(0.32,0.72,0,1)]',
610
+ tone === 'error' && 'text-destructive',
611
+ )}
612
+ style={width === null ? undefined : { width: width + 26 }}
613
+ >
614
+ {outgoing && (
615
+ <span
616
+ key={outgoing.key}
617
+ aria-hidden
618
+ className="island-leave col-start-1 row-start-1 truncate whitespace-nowrap"
619
+ >
620
+ {outgoing.node}
621
+ </span>
622
+ )}
623
+ <span
624
+ key={contentKey}
625
+ ref={contentRef}
626
+ className={cn(
627
+ 'col-start-1 row-start-1 w-max whitespace-nowrap',
628
+ outgoing && 'island-arrive',
629
+ )}
630
+ >
631
+ {children}
632
+ </span>
633
+ </div>
634
+ );
635
+ }
636
+
637
+ // `mountKey` re-attaches the observer when the measured card mounts later
638
+ // than the hook's owner (the pin's cards only exist while open or hovered).
639
+ function useMeasuredSize(
640
+ fallback: Size,
641
+ mountKey: unknown = null,
642
+ ): [RefObject<HTMLDivElement | null>, Size] {
643
+ const ref = useRef<HTMLDivElement>(null);
644
+ const [size, setSize] = useState<Size>(fallback);
645
+ // biome-ignore lint/correctness/useExhaustiveDependencies: mountKey only triggers re-observation
646
+ useLayoutEffect(() => {
647
+ const node = ref.current;
648
+ if (!node) return;
649
+ const update = () => {
650
+ const next = { width: node.offsetWidth, height: node.offsetHeight };
651
+ setSize((previous) =>
652
+ previous.width === next.width && previous.height === next.height ? previous : next,
653
+ );
654
+ };
655
+ update();
656
+ const observer = new ResizeObserver(update);
657
+ observer.observe(node);
658
+ return () => observer.disconnect();
659
+ }, [mountKey]);
660
+ return [ref, size];
661
+ }
662
+
663
+ function Pin({
664
+ anchor,
665
+ lit,
666
+ children,
667
+ ...props
668
+ }: ComponentProps<'button'> & { anchor: ScreenRect; lit: boolean }) {
669
+ return (
670
+ <button
671
+ type="button"
672
+ {...props}
673
+ className={cn(
674
+ 'pointer-events-auto absolute flex size-6 items-center justify-center rounded-full rounded-bl-[3px] bg-brand font-mono text-[10px] font-semibold text-brand-foreground ring-2 ring-background shadow-floating nums',
675
+ 'transition-[scale,box-shadow] duration-150 ease-swift hover:scale-110 focus-visible:outline-none focus-visible:ring-ring/60',
676
+ lit && 'scale-110',
677
+ props.className,
678
+ )}
679
+ style={{ left: anchor.left, top: anchor.top }}
680
+ >
681
+ {children}
682
+ </button>
683
+ );
684
+ }
685
+
686
+ function CommentPin({
687
+ comment,
688
+ frame,
689
+ region,
690
+ anchor,
691
+ bounds,
692
+ open,
693
+ hovered,
694
+ onToggle,
695
+ onHover,
696
+ onSave,
697
+ onRemove,
698
+ }: {
699
+ comment: SlideComment;
700
+ frame: ScreenRect;
701
+ region: boolean;
702
+ anchor: ScreenRect;
703
+ bounds: Size;
704
+ open: boolean;
705
+ hovered: boolean;
706
+ onToggle: () => void;
707
+ onHover: (hovering: boolean) => void;
708
+ onSave: (text: string) => Promise<void>;
709
+ onRemove: () => void;
710
+ }) {
711
+ const t = useLocale();
712
+ const lit = open || hovered;
713
+ const [cardRef, cardSize] = useMeasuredSize(
714
+ { width: 288, height: 120 },
715
+ open ? 'editor' : hovered ? 'preview' : null,
716
+ );
717
+ const card = placeBeside(anchor, cardSize, bounds);
718
+ const meta = `${format(t.inspector.commentLineLabel, { n: comment.line })}${
719
+ region ? ` · ${t.inspector.commentRegionLabel}` : ''
720
+ }`;
721
+ return (
722
+ <>
723
+ {(lit || region) && (
724
+ <div
725
+ className={cn(
726
+ 'absolute border border-brand',
727
+ region && !lit && 'border-dashed border-brand/50',
728
+ )}
729
+ style={frame}
730
+ />
731
+ )}
732
+ <Pin
733
+ anchor={anchor}
734
+ lit={lit}
735
+ aria-label={comment.note}
736
+ aria-expanded={open}
737
+ onClick={onToggle}
738
+ onPointerEnter={() => onHover(true)}
739
+ onPointerLeave={() => onHover(false)}
740
+ onFocus={() => onHover(true)}
741
+ onBlur={() => onHover(false)}
742
+ >
743
+ <MessageSquare className="size-3" />
744
+ </Pin>
745
+ {open ? (
746
+ <CommentEditor
747
+ key={comment.id}
748
+ cardRef={cardRef}
749
+ style={card}
750
+ meta={meta}
751
+ note={comment.note}
752
+ onSave={onSave}
753
+ onRemove={onRemove}
754
+ />
755
+ ) : (
756
+ hovered && (
757
+ <div
758
+ ref={cardRef}
759
+ data-comment-preview
760
+ className="island-arrive pointer-events-none absolute w-72 origin-top-left rounded-[10px] border border-border/80 bg-card text-[12.5px] shadow-overlay"
761
+ style={card}
762
+ >
763
+ <div className="truncate px-3 pt-2 font-mono text-[10px] text-muted-foreground">
764
+ {meta}
765
+ </div>
766
+ <p className="px-3 pt-1 pb-3 leading-relaxed break-words whitespace-pre-wrap">
767
+ {comment.note}
768
+ </p>
769
+ </div>
770
+ )
771
+ )}
772
+ </>
773
+ );
774
+ }
775
+
776
+ function CommentEditor({
777
+ cardRef,
778
+ style,
779
+ meta,
780
+ note,
781
+ onSave,
782
+ onRemove,
783
+ }: {
784
+ cardRef: RefObject<HTMLDivElement | null>;
785
+ style: { left: number; top: number };
786
+ meta: string;
787
+ note: string;
788
+ onSave: (text: string) => Promise<void>;
789
+ onRemove: () => void;
790
+ }) {
791
+ const t = useLocale();
792
+ const [text, setText] = useState(note);
793
+ const [saving, setSaving] = useState(false);
794
+ const textareaRef = useRef<HTMLTextAreaElement>(null);
795
+ const dirty = text.trim() !== note && text.trim() !== '';
796
+
797
+ useEffect(() => {
798
+ const node = textareaRef.current;
799
+ if (!node) return;
800
+ node.focus({ preventScroll: true });
801
+ node.setSelectionRange(node.value.length, node.value.length);
802
+ }, []);
803
+
804
+ const save = async () => {
805
+ if (!dirty || saving) return;
806
+ setSaving(true);
807
+ try {
808
+ await onSave(text.trim());
809
+ } finally {
810
+ setSaving(false);
811
+ }
812
+ };
813
+
814
+ return (
815
+ <CommentCard ref={cardRef} style={style} data-comment-editor>
816
+ <div className="flex h-8 items-center justify-between gap-2 pr-1.5 pl-3">
817
+ <span className="truncate font-mono text-[10px] text-muted-foreground">{meta}</span>
818
+ <button
819
+ type="button"
820
+ onClick={onRemove}
821
+ disabled={saving}
822
+ className="flex size-6 shrink-0 items-center justify-center rounded-[5px] text-muted-foreground transition-[color,background-color,scale] duration-150 hover:bg-muted hover:text-destructive active:scale-90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40"
823
+ aria-label={t.inspector.commentDeleteAria}
824
+ title={t.inspector.commentDeleteAria}
825
+ >
826
+ <Trash2 className="size-3.5" />
827
+ </button>
828
+ </div>
829
+ <CommentTextarea
830
+ ref={textareaRef}
831
+ value={text}
832
+ disabled={saving}
833
+ onChange={(event) => setText(event.target.value)}
834
+ onSubmit={save}
835
+ className="pt-0"
836
+ />
837
+ <CommentCardFooter>
838
+ <SendButton icon={Check} label={t.common.save} onClick={save} disabled={saving || !dirty} />
839
+ </CommentCardFooter>
840
+ </CommentCard>
841
+ );
842
+ }
843
+
844
+ function Composer({
845
+ frame,
846
+ region,
847
+ anchor,
848
+ bounds,
849
+ onSubmit,
850
+ }: {
851
+ frame: ScreenRect;
852
+ region: boolean;
853
+ anchor: ScreenRect;
854
+ bounds: Size;
855
+ onSubmit: (text: string) => Promise<void>;
856
+ }) {
857
+ const t = useLocale();
858
+ const [text, setText] = useState('');
859
+ const [submitting, setSubmitting] = useState(false);
860
+ const textareaRef = useRef<HTMLTextAreaElement>(null);
861
+ const [cardRef, cardSize] = useMeasuredSize({ width: 288, height: 112 });
862
+ const card = placeBeside(anchor, cardSize, bounds);
863
+
864
+ useEffect(() => {
865
+ textareaRef.current?.focus({ preventScroll: true });
866
+ }, []);
867
+
868
+ const post = async () => {
869
+ const trimmed = text.trim();
870
+ if (!trimmed || submitting) return;
871
+ setSubmitting(true);
872
+ try {
873
+ await onSubmit(trimmed);
874
+ } finally {
875
+ setSubmitting(false);
876
+ }
877
+ };
878
+
879
+ return (
880
+ <>
881
+ <div className={cn('absolute border border-brand', region && 'bg-brand/5')} style={frame} />
882
+ <Pin anchor={anchor} lit aria-hidden tabIndex={-1}>
883
+ <MessageSquare className="size-3" />
884
+ </Pin>
885
+ <CommentCard ref={cardRef} style={card} data-comment-composer>
886
+ <CommentTextarea
887
+ ref={textareaRef}
888
+ value={text}
889
+ disabled={submitting}
890
+ onChange={(event) => setText(event.target.value)}
891
+ onSubmit={post}
892
+ placeholder={t.inspector.commentPlaceholder}
893
+ />
894
+ <CommentCardFooter>
895
+ <SendButton
896
+ icon={ArrowUp}
897
+ label={t.inspector.commentPost}
898
+ onClick={post}
899
+ disabled={submitting || !text.trim()}
900
+ />
901
+ </CommentCardFooter>
902
+ </CommentCard>
903
+ </>
904
+ );
905
+ }
906
+
907
+ // One quiet surface: the text sits directly on the card instead of inside
908
+ // a second framed box, and the only strong element is the send button.
909
+ function CommentCard({
910
+ className,
911
+ ...props
912
+ }: ComponentProps<'div'> & { ref: RefObject<HTMLDivElement | null> }) {
913
+ return (
914
+ <div
915
+ {...props}
916
+ className={cn(
917
+ 'island-arrive pointer-events-auto absolute w-72 origin-top-left rounded-[10px] border border-border/80 bg-card shadow-overlay',
918
+ className,
919
+ )}
920
+ />
921
+ );
922
+ }
923
+
924
+ function CommentTextarea({
925
+ onSubmit,
926
+ className,
927
+ ...props
928
+ }: Omit<ComponentProps<'textarea'>, 'onSubmit'> & {
929
+ ref: RefObject<HTMLTextAreaElement | null>;
930
+ onSubmit: () => void;
931
+ }) {
932
+ return (
933
+ <textarea
934
+ rows={2}
935
+ {...props}
936
+ onKeyDown={(event) => {
937
+ if (event.nativeEvent.isComposing) return;
938
+ if (event.key === 'Enter' && (event.metaKey || event.ctrlKey)) {
939
+ event.preventDefault();
940
+ onSubmit();
941
+ }
942
+ }}
943
+ className={cn(
944
+ 'field-sizing-content block max-h-40 min-h-[3.25rem] w-full resize-none bg-transparent px-3 pt-2.5 pb-1 text-[12.5px] leading-[1.5] text-foreground outline-none',
945
+ 'placeholder:text-muted-foreground/60 disabled:opacity-60',
946
+ className,
947
+ )}
948
+ />
949
+ );
950
+ }
951
+
952
+ function CommentCardFooter({ children }: { children: ReactNode }) {
953
+ return (
954
+ <div className="flex items-center justify-between gap-2 px-2 pt-0.5 pb-2 pl-3">
955
+ <kbd className="rounded-[4px] border border-border/70 bg-muted/60 px-1.5 py-0.5 font-mono text-[9.5px] tracking-[0.04em] text-muted-foreground">
956
+ {SUBMIT_SHORTCUT}
957
+ </kbd>
958
+ {children}
959
+ </div>
960
+ );
961
+ }
962
+
963
+ function SendButton({
964
+ icon: Icon,
965
+ label,
966
+ onClick,
967
+ disabled,
968
+ }: {
969
+ icon: typeof ArrowUp;
970
+ label: string;
971
+ onClick: () => void;
972
+ disabled: boolean;
973
+ }) {
974
+ return (
975
+ <button
976
+ type="button"
977
+ onClick={onClick}
978
+ disabled={disabled}
979
+ aria-label={label}
980
+ title={label}
981
+ className={cn(
982
+ 'flex size-7 shrink-0 items-center justify-center rounded-full transition-[background-color,color,scale,opacity] duration-150 ease-swift',
983
+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40',
984
+ disabled
985
+ ? 'bg-muted text-muted-foreground/50'
986
+ : 'bg-brand text-brand-foreground shadow-[inset_0_1px_0_oklch(1_0_0/0.18),0_1px_0_oklch(0_0_0/0.16)] hover:brightness-105 active:scale-90',
987
+ )}
988
+ >
989
+ <Icon className="size-3.5" strokeWidth={2.5} />
990
+ </button>
991
+ );
992
+ }