@open-slide/core 1.19.1 → 2.0.0-beta.1

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 (88) hide show
  1. package/dist/build-Bzy-qlGc.js +19 -0
  2. package/dist/cli/bin.d.ts +1 -1
  3. package/dist/cli/bin.js +331 -25
  4. package/dist/{config-CDHB8Oow.d.ts → config-AtA2Bqtn.d.ts} +4 -4
  5. package/dist/{config-GA6NMgs_.js → config-nbSvY7z_.js} +547 -778
  6. package/dist/{design-cpzS8aud.js → design-Cpqx7SJs.js} +1 -2
  7. package/dist/{dev-D57ui2yV.js → dev-MXa5Tod4.js} +39 -16
  8. package/dist/index.d.ts +7 -37
  9. package/dist/index.js +51 -54
  10. package/dist/locale/index.d.ts +2 -8
  11. package/dist/locale/index.js +13 -3
  12. package/dist/preview-DEpQcKz3.js +24 -0
  13. package/dist/{types-8HghULIe.d.ts → types-BzPSOxe-.d.ts} +5 -9
  14. package/dist/vite/index.d.ts +1 -4
  15. package/dist/vite/index.js +2 -4
  16. package/dist/{format-74A3B6zu.js → zh-tw-BxZ_pYqe.js} +13 -49
  17. package/package.json +12 -12
  18. package/skills/create-slide/SKILL.md +4 -1
  19. package/skills/slide-authoring/SKILL.md +25 -2
  20. package/src/app/app.tsx +1 -3
  21. package/src/app/assets/open-slide.png +0 -0
  22. package/src/app/components/asset-view.tsx +8 -16
  23. package/src/app/components/command/home-command-menu.tsx +6 -6
  24. package/src/app/components/export-progress-toast.tsx +80 -0
  25. package/src/app/components/history-provider.tsx +1 -5
  26. package/src/app/components/image-placeholder.tsx +4 -12
  27. package/src/app/components/inspector/asset-picker-dialog.tsx +6 -16
  28. package/src/app/components/inspector/image-crop-dialog.tsx +1 -4
  29. package/src/app/components/inspector/inline-text-editor.tsx +798 -0
  30. package/src/app/components/inspector/inspect-overlay.tsx +30 -72
  31. package/src/app/components/inspector/inspector-panel.tsx +17 -49
  32. package/src/app/components/inspector/inspector-provider.tsx +53 -36
  33. package/src/app/components/notes-drawer.tsx +2 -5
  34. package/src/app/components/overview-grid.tsx +5 -4
  35. package/src/app/components/panel/panel-shell.tsx +1 -3
  36. package/src/app/components/player.tsx +5 -6
  37. package/src/app/components/present/control-bar.tsx +4 -4
  38. package/src/app/components/present/jump-input.tsx +3 -2
  39. package/src/app/components/present/use-presenter-channel.ts +0 -1
  40. package/src/app/components/sidebar/folder-item.tsx +39 -16
  41. package/src/app/components/sidebar/sidebar-footer.tsx +7 -1
  42. package/src/app/components/sidebar/sidebar.tsx +91 -64
  43. package/src/app/components/slide-canvas.tsx +2 -6
  44. package/src/app/components/slide-transition-layer.tsx +48 -76
  45. package/src/app/components/style-panel/design-provider.tsx +1 -14
  46. package/src/app/components/style-panel/use-design.ts +1 -28
  47. package/src/app/components/themes/theme-detail.tsx +4 -4
  48. package/src/app/components/themes/themes-gallery.tsx +11 -6
  49. package/src/app/components/thumbnail-rail.tsx +7 -12
  50. package/src/app/lib/assets.ts +6 -7
  51. package/src/app/lib/dom.ts +42 -0
  52. package/src/app/lib/export-html.ts +10 -25
  53. package/src/app/lib/export-pdf.ts +11 -28
  54. package/src/app/lib/export-pptx.ts +6 -36
  55. package/src/app/lib/folders.ts +51 -46
  56. package/src/app/lib/inspector/inline-text.ts +31 -0
  57. package/src/app/lib/inspector/pick-target.ts +38 -0
  58. package/src/app/lib/inspector/use-comments.ts +1 -1
  59. package/src/app/lib/keys.ts +18 -0
  60. package/src/app/lib/last-home-location.ts +18 -0
  61. package/src/app/lib/print-ready.ts +2 -4
  62. package/src/app/lib/slides.ts +7 -4
  63. package/src/app/lib/text-diff.ts +19 -0
  64. package/src/app/lib/use-click-page-navigation.ts +2 -6
  65. package/src/app/lib/use-is-mobile.ts +2 -14
  66. package/src/app/lib/use-media-query.ts +20 -0
  67. package/src/app/lib/use-prefers-reduced-motion.ts +5 -13
  68. package/src/app/lib/use-slide-module.ts +1 -1
  69. package/src/app/lib/use-wheel-page-navigation.ts +1 -1
  70. package/src/app/lib/utils.test.ts +25 -1
  71. package/src/app/lib/utils.ts +8 -0
  72. package/src/app/routes/home-shell.tsx +71 -64
  73. package/src/app/routes/home.tsx +41 -52
  74. package/src/app/routes/presenter.tsx +10 -20
  75. package/src/app/routes/slide.tsx +84 -71
  76. package/src/app/routes/themes.tsx +7 -8
  77. package/src/app/styles.css +33 -44
  78. package/src/locale/en.ts +2 -7
  79. package/src/locale/ja.ts +2 -7
  80. package/src/locale/types.ts +2 -7
  81. package/src/locale/zh-cn.ts +2 -7
  82. package/src/locale/zh-tw.ts +2 -7
  83. package/dist/build-CaV_vhIw.js +0 -17
  84. package/dist/preview-D40Zw_o0.js +0 -18
  85. package/dist/sync-BCJDRIqo.js +0 -139
  86. package/dist/sync-j9_QPovT.js +0 -3
  87. package/src/app/components/pdf-progress-toast.tsx +0 -36
  88. package/src/app/components/pptx-progress-toast.tsx +0 -36
@@ -0,0 +1,798 @@
1
+ import { AlignCenter, AlignLeft, AlignRight, Bold, Italic, Minus, Plus } from 'lucide-react';
2
+ import { type RefObject, useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
3
+ import { findSlideSource } from '@/lib/inspector/fiber';
4
+ import {
5
+ isEditableTextContainer,
6
+ isInspectableEventTarget,
7
+ pickElement,
8
+ pickInspectorTarget,
9
+ } from '@/lib/inspector/pick-target';
10
+ import { useLocale } from '@/lib/use-locale';
11
+ import { cn } from '@/lib/utils';
12
+ import {
13
+ collectDomTextParts,
14
+ type DomTextPart,
15
+ type InlineEditTarget,
16
+ readEditableText,
17
+ useInspector,
18
+ } from './inspector-provider';
19
+
20
+ type RelRect = { left: number; top: number; width: number; height: number };
21
+ type TextRange = { start: number; end: number };
22
+
23
+ const RANGE_STYLE_KEYS = new Set(['fontSize', 'fontWeight', 'fontStyle', 'color']);
24
+ const TOOLBAR_GAP = 8;
25
+ const TOOLBAR_HEIGHT = 36;
26
+
27
+ function pickEditableAnchor(
28
+ x: number,
29
+ y: number,
30
+ slideId: string,
31
+ ): { line: number; column: number; anchor: HTMLElement } | null {
32
+ const el = pickInspectorTarget(pickElement(x, y));
33
+ if (!el) return null;
34
+ const hit = findSlideSource(el, slideId, { hostOnly: true });
35
+ if (!hit) return null;
36
+ // Images keep their double-click behavior (crop, in inspect mode).
37
+ if (hit.anchor instanceof HTMLImageElement) return null;
38
+ if (!isEditableTextContainer(hit.anchor)) return null;
39
+ return hit;
40
+ }
41
+
42
+ // Click-to-edit lives outside the inspector: it works in the plain slide
43
+ // view, without activating inspect mode or opening the panel.
44
+ export function InlineEditLayer() {
45
+ const { slideId, active, inlineEdit, startInlineEdit, stopInlineEdit } = useInspector();
46
+ const layerRef = useRef<HTMLDivElement>(null);
47
+
48
+ // Plain view: a single click on a text run starts editing with the caret
49
+ // at the click point. A double-click's second click lands on the
50
+ // now-contenteditable element, so native word selection still happens.
51
+ useEffect(() => {
52
+ if (import.meta.env.PROD || active) return;
53
+ const onClick = (e: MouseEvent) => {
54
+ if (inlineEdit?.anchor.contains(e.target as Node)) return;
55
+ if (!isInspectableEventTarget(e.target)) return;
56
+ const hit = pickEditableAnchor(e.clientX, e.clientY, slideId);
57
+ if (!hit) return;
58
+ e.preventDefault();
59
+ e.stopPropagation();
60
+ startInlineEdit({
61
+ line: hit.line,
62
+ column: hit.column,
63
+ anchor: hit.anchor,
64
+ point: { x: e.clientX, y: e.clientY },
65
+ selectWord: false,
66
+ });
67
+ };
68
+ window.addEventListener('click', onClick, true);
69
+ return () => window.removeEventListener('click', onClick, true);
70
+ }, [active, slideId, inlineEdit, startInlineEdit]);
71
+
72
+ // Inspect mode keeps double-click entry — a single click there means
73
+ // "select the element for the panel".
74
+ useEffect(() => {
75
+ if (import.meta.env.PROD || !active) return;
76
+ const onDblClick = (e: MouseEvent) => {
77
+ if (inlineEdit?.anchor.contains(e.target as Node)) return;
78
+ if (!isInspectableEventTarget(e.target)) return;
79
+ const hit = pickEditableAnchor(e.clientX, e.clientY, slideId);
80
+ if (!hit) return;
81
+ e.preventDefault();
82
+ e.stopPropagation();
83
+ startInlineEdit({
84
+ line: hit.line,
85
+ column: hit.column,
86
+ anchor: hit.anchor,
87
+ point: { x: e.clientX, y: e.clientY },
88
+ selectWord: true,
89
+ });
90
+ };
91
+ window.addEventListener('dblclick', onDblClick, true);
92
+ return () => window.removeEventListener('dblclick', onDblClick, true);
93
+ }, [active, slideId, inlineEdit, startInlineEdit]);
94
+
95
+ useEffect(() => {
96
+ if (!inlineEdit) return;
97
+ const { anchor } = inlineEdit;
98
+ const onPointerDown = (e: PointerEvent) => {
99
+ if (anchor.contains(e.target as Node)) return;
100
+ if (e.target instanceof Element && e.target.closest('[data-inspector-ui]')) return;
101
+ // In the plain view a single click on another text run switches the
102
+ // session to it; in inspect mode a click means "select", so just exit.
103
+ if (!active && isInspectableEventTarget(e.target)) {
104
+ const hit = pickEditableAnchor(e.clientX, e.clientY, slideId);
105
+ if (hit) {
106
+ e.preventDefault();
107
+ startInlineEdit({
108
+ line: hit.line,
109
+ column: hit.column,
110
+ anchor: hit.anchor,
111
+ point: { x: e.clientX, y: e.clientY },
112
+ selectWord: false,
113
+ });
114
+ return;
115
+ }
116
+ }
117
+ stopInlineEdit();
118
+ };
119
+ const onKey = (e: KeyboardEvent) => {
120
+ if (e.key !== 'Escape') return;
121
+ e.preventDefault();
122
+ e.stopPropagation();
123
+ stopInlineEdit();
124
+ };
125
+ window.addEventListener('pointerdown', onPointerDown, true);
126
+ window.addEventListener('keydown', onKey, true);
127
+ return () => {
128
+ window.removeEventListener('pointerdown', onPointerDown, true);
129
+ window.removeEventListener('keydown', onKey, true);
130
+ };
131
+ }, [inlineEdit, active, slideId, startInlineEdit, stopInlineEdit]);
132
+
133
+ // Hovering an editable text run in the plain view shows a text cursor and
134
+ // a light outline — the discoverability cue for click-to-edit.
135
+ useEffect(() => {
136
+ if (import.meta.env.PROD || active) return;
137
+ const styleEl = document.createElement('style');
138
+ styleEl.textContent = HOVER_HINT_CSS;
139
+ document.head.appendChild(styleEl);
140
+ let hovered: HTMLElement | null = null;
141
+ let raf = 0;
142
+ const clear = () => {
143
+ const el = hovered;
144
+ hovered = null;
145
+ if (!el) return;
146
+ if (el.getAttribute(TEXT_HOVER_ATTR) !== 'true') {
147
+ el.removeAttribute(TEXT_HOVER_ATTR);
148
+ return;
149
+ }
150
+ el.setAttribute(TEXT_HOVER_ATTR, 'out');
151
+ window.setTimeout(() => {
152
+ // Re-entering the element mid-fade flips the value back to 'true'.
153
+ if (el.getAttribute(TEXT_HOVER_ATTR) === 'out') el.removeAttribute(TEXT_HOVER_ATTR);
154
+ }, HOVER_FADE_MS + 40);
155
+ };
156
+ const onMove = (e: PointerEvent) => {
157
+ const { clientX, clientY, target } = e;
158
+ cancelAnimationFrame(raf);
159
+ raf = requestAnimationFrame(() => {
160
+ const hit = isInspectableEventTarget(target)
161
+ ? pickEditableAnchor(clientX, clientY, slideId)
162
+ : null;
163
+ const anchor =
164
+ hit && hit.anchor.getAttribute('contenteditable') !== 'true' ? hit.anchor : null;
165
+ if (anchor === hovered) return;
166
+ clear();
167
+ if (anchor) {
168
+ hovered = anchor;
169
+ if (anchor.hasAttribute(TEXT_HOVER_ATTR)) {
170
+ // Mid-fade-out re-entry: transition straight back to visible.
171
+ anchor.setAttribute(TEXT_HOVER_ATTR, 'true');
172
+ } else {
173
+ anchor.setAttribute(TEXT_HOVER_ATTR, 'in');
174
+ requestAnimationFrame(() => {
175
+ if (hovered === anchor && anchor.getAttribute(TEXT_HOVER_ATTR) === 'in') {
176
+ anchor.setAttribute(TEXT_HOVER_ATTR, 'true');
177
+ }
178
+ });
179
+ }
180
+ }
181
+ });
182
+ };
183
+ window.addEventListener('pointermove', onMove, true);
184
+ return () => {
185
+ window.removeEventListener('pointermove', onMove, true);
186
+ cancelAnimationFrame(raf);
187
+ hovered = null;
188
+ for (const el of document.querySelectorAll(`[${TEXT_HOVER_ATTR}]`)) {
189
+ el.removeAttribute(TEXT_HOVER_ATTR);
190
+ }
191
+ styleEl.remove();
192
+ };
193
+ }, [active, slideId]);
194
+
195
+ if (import.meta.env.PROD) return null;
196
+ return (
197
+ <div ref={layerRef} data-inspector-ui className="pointer-events-none absolute inset-0 z-30">
198
+ {inlineEdit && (
199
+ <ActiveInlineEditor
200
+ key={inlineEdit.session ?? `${inlineEdit.line}:${inlineEdit.column}`}
201
+ target={inlineEdit}
202
+ layerRef={layerRef}
203
+ showOutline={!active}
204
+ />
205
+ )}
206
+ </div>
207
+ );
208
+ }
209
+
210
+ const TEXT_HOVER_ATTR = 'data-slide-text-hover';
211
+ const HOVER_FADE_MS = 160;
212
+
213
+ // The outline fades by transitioning outline-color through transient
214
+ // attribute values: 'in' (transparent) → 'true' (visible) on enter, and
215
+ // 'true' → 'out' (transparent) before removal on leave.
216
+ const HOVER_HINT_CSS = `
217
+ [data-inspector-root] [${TEXT_HOVER_ATTR}],
218
+ [data-inspector-root] [${TEXT_HOVER_ATTR}] * {
219
+ cursor: text !important;
220
+ }
221
+ [data-inspector-root] [${TEXT_HOVER_ATTR}] {
222
+ outline: 2px solid rgba(59, 130, 246, 0.5) !important;
223
+ outline-offset: 2px !important;
224
+ }
225
+ [data-inspector-root] [${TEXT_HOVER_ATTR}='in'],
226
+ [data-inspector-root] [${TEXT_HOVER_ATTR}='out'] {
227
+ outline-color: rgba(59, 130, 246, 0) !important;
228
+ }
229
+ @media (prefers-reduced-motion: no-preference) {
230
+ [data-inspector-root] [${TEXT_HOVER_ATTR}] {
231
+ transition: outline-color ${HOVER_FADE_MS}ms ease !important;
232
+ }
233
+ /* The 'in' frame must land on transparent instantly; with the transition
234
+ active it would itself animate away from the pre-hover outline-color. */
235
+ [data-inspector-root] [${TEXT_HOVER_ATTR}='in'] {
236
+ transition: none !important;
237
+ }
238
+ @keyframes osd-inline-outline-in {
239
+ from {
240
+ opacity: 0;
241
+ }
242
+ to {
243
+ opacity: 1;
244
+ }
245
+ }
246
+ }
247
+ `;
248
+
249
+ const INLINE_EDITING_CSS = `
250
+ [data-inspector-root] [data-slide-editing][data-slide-editing],
251
+ [data-inspector-root] [data-slide-editing][data-slide-editing] * {
252
+ cursor: text !important;
253
+ -webkit-user-select: text !important;
254
+ user-select: text !important;
255
+ }
256
+ [data-inspector-root] [data-slide-editing][data-slide-editing] {
257
+ outline: none !important;
258
+ }
259
+ `;
260
+
261
+ function ActiveInlineEditor({
262
+ target,
263
+ layerRef,
264
+ showOutline,
265
+ }: {
266
+ target: InlineEditTarget;
267
+ layerRef: RefObject<HTMLDivElement | null>;
268
+ showOutline: boolean;
269
+ }) {
270
+ const { bufferOps, stopInlineEdit } = useInspector();
271
+ const [sel, setSel] = useState<TextRange | null>(null);
272
+ const { anchor } = target;
273
+ const rect = useAnchorRect(anchor, layerRef);
274
+
275
+ const commit = useCallback(() => {
276
+ if (!anchor.isConnected) return;
277
+ bufferOps(target.line, target.column, anchor, [
278
+ { kind: 'set-text', value: readEditableText(anchor) },
279
+ ]);
280
+ }, [anchor, target.line, target.column, bufferOps]);
281
+
282
+ const applyTextStyle = useCallback(
283
+ (key: string, value: string | null) => {
284
+ if (!anchor.isConnected) return;
285
+ if (sel && sel.end > sel.start && RANGE_STYLE_KEYS.has(key)) {
286
+ bufferOps(target.line, target.column, anchor, [
287
+ { kind: 'set-text-range-style', start: sel.start, end: sel.end, key, value },
288
+ ]);
289
+ return;
290
+ }
291
+ bufferOps(target.line, target.column, anchor, [
292
+ { kind: 'set-style', key, value, prevText: readEditableText(anchor) },
293
+ ]);
294
+ },
295
+ [anchor, sel, target.line, target.column, bufferOps],
296
+ );
297
+
298
+ const toggleBold = useCallback(() => {
299
+ const bold = parseInt(getComputedStyle(styleContext(anchor, sel)).fontWeight, 10) >= 600;
300
+ applyTextStyle('fontWeight', bold ? null : '700');
301
+ }, [anchor, sel, applyTextStyle]);
302
+
303
+ const toggleItalic = useCallback(() => {
304
+ const italic = getComputedStyle(styleContext(anchor, sel)).fontStyle === 'italic';
305
+ applyTextStyle('fontStyle', italic ? null : 'italic');
306
+ }, [anchor, sel, applyTextStyle]);
307
+
308
+ // The setup effect must run exactly once per anchor — re-running it would
309
+ // re-place the caret and clobber the user's live selection — so everything
310
+ // with an unstable identity is reached through latest-refs.
311
+ const latestRef = useRef({ commit, toggleBold, toggleItalic });
312
+ latestRef.current = { commit, toggleBold, toggleItalic };
313
+ const initialCaretRef = useRef({ point: target.point, selectWord: target.selectWord ?? false });
314
+
315
+ useEffect(() => {
316
+ anchor.setAttribute('contenteditable', 'true');
317
+ anchor.setAttribute('spellcheck', 'false');
318
+ anchor.setAttribute('data-slide-editing', 'true');
319
+ const styleEl = document.createElement('style');
320
+ styleEl.textContent = INLINE_EDITING_CSS;
321
+ document.head.appendChild(styleEl);
322
+ focusAndPlaceCaret(anchor, initialCaretRef.current.point, initialCaretRef.current.selectWord);
323
+
324
+ const onBeforeInput = (e: Event) => {
325
+ const ev = e as InputEvent;
326
+ const type = ev.inputType;
327
+ if (type === 'insertParagraph' || type === 'insertLineBreak') {
328
+ ev.preventDefault();
329
+ document.execCommand('insertLineBreak');
330
+ } else if (type === 'insertFromPaste' || type === 'insertFromDrop') {
331
+ ev.preventDefault();
332
+ const text = ev.dataTransfer?.getData('text/plain') ?? ev.data;
333
+ if (text) document.execCommand('insertText', false, text);
334
+ } else if (type === 'formatBold') {
335
+ ev.preventDefault();
336
+ latestRef.current.toggleBold();
337
+ } else if (type === 'formatItalic') {
338
+ ev.preventDefault();
339
+ latestRef.current.toggleItalic();
340
+ } else if (type.startsWith('format')) {
341
+ ev.preventDefault();
342
+ }
343
+ };
344
+ const onInput = (e: Event) => {
345
+ if ((e as InputEvent).isComposing) return;
346
+ latestRef.current.commit();
347
+ };
348
+ const onCompositionEnd = () => latestRef.current.commit();
349
+ const onKeyDown = (e: KeyboardEvent) => {
350
+ if ((e.metaKey || e.ctrlKey) && !e.altKey) {
351
+ const key = e.key.toLowerCase();
352
+ if (key === 'b') {
353
+ e.preventDefault();
354
+ latestRef.current.toggleBold();
355
+ } else if (key === 'i') {
356
+ e.preventDefault();
357
+ latestRef.current.toggleItalic();
358
+ }
359
+ }
360
+ };
361
+ const onSelectionChange = () => {
362
+ const offsets = selectionTextOffsets(anchor);
363
+ if (offsets === null) return;
364
+ setSel(offsets.end > offsets.start ? offsets : null);
365
+ };
366
+
367
+ anchor.addEventListener('beforeinput', onBeforeInput);
368
+ anchor.addEventListener('input', onInput);
369
+ anchor.addEventListener('compositionend', onCompositionEnd);
370
+ anchor.addEventListener('keydown', onKeyDown);
371
+ document.addEventListener('selectionchange', onSelectionChange);
372
+ return () => {
373
+ anchor.removeEventListener('beforeinput', onBeforeInput);
374
+ anchor.removeEventListener('input', onInput);
375
+ anchor.removeEventListener('compositionend', onCompositionEnd);
376
+ anchor.removeEventListener('keydown', onKeyDown);
377
+ document.removeEventListener('selectionchange', onSelectionChange);
378
+ styleEl.remove();
379
+ if (anchor.isConnected) {
380
+ anchor.removeAttribute('contenteditable');
381
+ anchor.removeAttribute('spellcheck');
382
+ anchor.removeAttribute('data-slide-editing');
383
+ }
384
+ };
385
+ }, [anchor]);
386
+
387
+ // An HMR remount replaces the anchor node (taking its contenteditable
388
+ // attribute with it), so a disconnected anchor ends the session.
389
+ useEffect(() => {
390
+ const root = document.querySelector<HTMLElement>('[data-inspector-root]');
391
+ if (!root) return;
392
+ const check = () => {
393
+ if (!anchor.isConnected) stopInlineEdit();
394
+ };
395
+ const observer = new MutationObserver(check);
396
+ observer.observe(root, { childList: true, subtree: true });
397
+ return () => observer.disconnect();
398
+ }, [anchor, stopInlineEdit]);
399
+
400
+ if (!rect) return null;
401
+ return (
402
+ <>
403
+ {showOutline && (
404
+ <div
405
+ className="absolute"
406
+ style={{
407
+ left: rect.left,
408
+ top: rect.top,
409
+ width: rect.width,
410
+ height: rect.height,
411
+ outline: '2px solid #3b82f6',
412
+ animation: 'osd-inline-outline-in 160ms ease-out',
413
+ }}
414
+ />
415
+ )}
416
+ <TextToolbar
417
+ anchor={anchor}
418
+ layerRef={layerRef}
419
+ rect={rect}
420
+ sel={sel}
421
+ applyStyle={applyTextStyle}
422
+ />
423
+ </>
424
+ );
425
+ }
426
+
427
+ function useAnchorRect(
428
+ anchor: HTMLElement,
429
+ layerRef: RefObject<HTMLDivElement | null>,
430
+ ): RelRect | null {
431
+ const [rect, setRect] = useState<RelRect | null>(null);
432
+
433
+ const measure = useCallback(() => {
434
+ const layer = layerRef.current;
435
+ if (!anchor.isConnected || !layer) return;
436
+ const a = anchor.getBoundingClientRect();
437
+ const o = layer.getBoundingClientRect();
438
+ const next = { left: a.left - o.left, top: a.top - o.top, width: a.width, height: a.height };
439
+ setRect((prev) =>
440
+ prev &&
441
+ Math.abs(prev.left - next.left) < 0.5 &&
442
+ Math.abs(prev.top - next.top) < 0.5 &&
443
+ Math.abs(prev.width - next.width) < 0.5 &&
444
+ Math.abs(prev.height - next.height) < 0.5
445
+ ? prev
446
+ : next,
447
+ );
448
+ }, [anchor, layerRef]);
449
+
450
+ useLayoutEffect(() => {
451
+ measure();
452
+ }, [measure]);
453
+
454
+ useEffect(() => {
455
+ let scheduled = 0;
456
+ const scheduleMeasure = () => {
457
+ cancelAnimationFrame(scheduled);
458
+ scheduled = requestAnimationFrame(measure);
459
+ };
460
+ const resizeObserver = new ResizeObserver(scheduleMeasure);
461
+ resizeObserver.observe(anchor);
462
+ if (layerRef.current) resizeObserver.observe(layerRef.current);
463
+ window.addEventListener('resize', scheduleMeasure, true);
464
+ window.addEventListener('scroll', scheduleMeasure, true);
465
+ return () => {
466
+ resizeObserver.disconnect();
467
+ cancelAnimationFrame(scheduled);
468
+ window.removeEventListener('resize', scheduleMeasure, true);
469
+ window.removeEventListener('scroll', scheduleMeasure, true);
470
+ };
471
+ }, [measure, anchor, layerRef]);
472
+
473
+ return rect;
474
+ }
475
+
476
+ function TextToolbar({
477
+ anchor,
478
+ layerRef,
479
+ rect,
480
+ sel,
481
+ applyStyle,
482
+ }: {
483
+ anchor: HTMLElement;
484
+ layerRef: RefObject<HTMLDivElement | null>;
485
+ rect: RelRect;
486
+ sel: TextRange | null;
487
+ applyStyle: (key: string, value: string | null) => void;
488
+ }) {
489
+ const { opsVersion } = useInspector();
490
+ const t = useLocale();
491
+ const toolbarRef = useRef<HTMLDivElement>(null);
492
+
493
+ void opsVersion;
494
+ const contextEl = styleContext(anchor, sel);
495
+ const cs = anchor.isConnected ? getComputedStyle(contextEl) : null;
496
+ const fontSize = cs ? Math.round(parseFloat(cs.fontSize) || 16) : 16;
497
+ const bold = cs ? parseInt(cs.fontWeight, 10) >= 600 : false;
498
+ const italic = cs ? cs.fontStyle === 'italic' : false;
499
+ const color = cs ? (rgbToHex(cs.color) ?? '#000000') : '#000000';
500
+ const anchorAlign = anchor.isConnected ? getComputedStyle(anchor).textAlign : 'left';
501
+ const align =
502
+ anchorAlign === 'center' || anchorAlign === 'right' || anchorAlign === 'justify'
503
+ ? anchorAlign
504
+ : 'left';
505
+
506
+ const layerWidth = layerRef.current?.clientWidth ?? 0;
507
+ const barWidth = toolbarRef.current?.offsetWidth ?? 0;
508
+ const centerX = rect.left + rect.width / 2;
509
+ const clampedX =
510
+ barWidth > 0 && layerWidth > 0
511
+ ? Math.min(Math.max(centerX, barWidth / 2 + 4), layerWidth - barWidth / 2 - 4)
512
+ : centerX;
513
+ const above = rect.top - TOOLBAR_HEIGHT - TOOLBAR_GAP >= 0;
514
+ const top = above ? rect.top - TOOLBAR_GAP : rect.top + rect.height + TOOLBAR_GAP;
515
+
516
+ const setFontSize = (px: number) => {
517
+ if (!Number.isFinite(px)) return;
518
+ applyStyle('fontSize', `${Math.min(Math.max(Math.round(px), 4), 400)}px`);
519
+ };
520
+
521
+ return (
522
+ <div
523
+ ref={toolbarRef}
524
+ data-inspector-ui
525
+ className="pointer-events-auto absolute z-10 flex items-center gap-0.5 rounded-[8px] border border-border bg-popover p-1 text-popover-foreground shadow-floating"
526
+ style={{
527
+ left: clampedX,
528
+ top,
529
+ transform: above ? 'translate(-50%, -100%)' : 'translateX(-50%)',
530
+ }}
531
+ onPointerDown={(e) => {
532
+ // Keep focus (and the text selection) inside the contenteditable.
533
+ e.preventDefault();
534
+ }}
535
+ >
536
+ <ToolbarIconButton
537
+ label={t.inspector.decreaseFontSize}
538
+ onClick={() => setFontSize(fontSize - 1)}
539
+ >
540
+ <Minus className="size-3.5" />
541
+ </ToolbarIconButton>
542
+ <FontSizeInput value={fontSize} onCommit={setFontSize} label={t.inspector.sizeLabel} />
543
+ <ToolbarIconButton
544
+ label={t.inspector.increaseFontSize}
545
+ onClick={() => setFontSize(fontSize + 1)}
546
+ >
547
+ <Plus className="size-3.5" />
548
+ </ToolbarIconButton>
549
+ <span aria-hidden className="mx-0.5 h-4 w-px bg-hairline" />
550
+ <ToolbarIconButton
551
+ label={t.inspector.boldAria}
552
+ pressed={bold}
553
+ onClick={() => applyStyle('fontWeight', bold ? null : '700')}
554
+ >
555
+ <Bold className="size-3.5" />
556
+ </ToolbarIconButton>
557
+ <ToolbarIconButton
558
+ label={t.inspector.italicAria}
559
+ pressed={italic}
560
+ onClick={() => applyStyle('fontStyle', italic ? null : 'italic')}
561
+ >
562
+ <Italic className="size-3.5" />
563
+ </ToolbarIconButton>
564
+ <label
565
+ className="relative ml-0.5 inline-flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-[5px] transition-colors duration-150 hover:bg-muted"
566
+ aria-label={t.inspector.textColor}
567
+ onPointerDown={(e) => e.stopPropagation()}
568
+ >
569
+ <span
570
+ className="size-4 rounded-[3px] border border-foreground/15"
571
+ style={{ backgroundColor: color }}
572
+ />
573
+ <input
574
+ type="color"
575
+ value={color}
576
+ onChange={(e) => applyStyle('color', e.target.value)}
577
+ className="absolute inset-0 size-full cursor-pointer opacity-0"
578
+ />
579
+ </label>
580
+ <span aria-hidden className="mx-0.5 h-4 w-px bg-hairline" />
581
+ {(
582
+ [
583
+ ['left', AlignLeft],
584
+ ['center', AlignCenter],
585
+ ['right', AlignRight],
586
+ ] as const
587
+ ).map(([value, Icon]) => (
588
+ <ToolbarIconButton
589
+ key={value}
590
+ label={value}
591
+ pressed={align === value}
592
+ onClick={() => applyStyle('textAlign', value === 'left' ? null : value)}
593
+ >
594
+ <Icon className="size-3.5" />
595
+ </ToolbarIconButton>
596
+ ))}
597
+ </div>
598
+ );
599
+ }
600
+
601
+ function ToolbarIconButton({
602
+ label,
603
+ pressed,
604
+ onClick,
605
+ children,
606
+ }: {
607
+ label: string;
608
+ pressed?: boolean;
609
+ onClick: () => void;
610
+ children: React.ReactNode;
611
+ }) {
612
+ return (
613
+ <button
614
+ type="button"
615
+ aria-label={label}
616
+ aria-pressed={pressed}
617
+ title={label}
618
+ onClick={onClick}
619
+ className={cn(
620
+ 'inline-flex size-7 items-center justify-center rounded-[5px] transition-[background-color,color,scale] duration-150 active:scale-[0.94] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40',
621
+ pressed
622
+ ? 'bg-muted text-foreground'
623
+ : 'text-foreground/85 hover:bg-muted hover:text-foreground',
624
+ )}
625
+ >
626
+ {children}
627
+ </button>
628
+ );
629
+ }
630
+
631
+ function FontSizeInput({
632
+ value,
633
+ onCommit,
634
+ label,
635
+ }: {
636
+ value: number;
637
+ onCommit: (px: number) => void;
638
+ label: string;
639
+ }) {
640
+ const [draft, setDraft] = useState(String(value));
641
+ useEffect(() => setDraft(String(value)), [value]);
642
+ const commit = () => {
643
+ const n = parseFloat(draft);
644
+ if (Number.isFinite(n)) onCommit(n);
645
+ else setDraft(String(value));
646
+ };
647
+ return (
648
+ <input
649
+ type="text"
650
+ inputMode="numeric"
651
+ value={draft}
652
+ aria-label={label}
653
+ onPointerDown={(e) => e.stopPropagation()}
654
+ onChange={(e) => setDraft(e.target.value)}
655
+ onBlur={commit}
656
+ onKeyDown={(e) => {
657
+ if (e.key === 'Enter') {
658
+ e.preventDefault();
659
+ commit();
660
+ } else if (e.key === 'ArrowUp') {
661
+ e.preventDefault();
662
+ onCommit(value + 1);
663
+ } else if (e.key === 'ArrowDown') {
664
+ e.preventDefault();
665
+ onCommit(value - 1);
666
+ }
667
+ e.stopPropagation();
668
+ }}
669
+ className="nums h-7 w-9 rounded-[5px] border border-transparent bg-transparent text-center font-mono text-[11px] text-foreground outline-none transition-colors duration-150 hover:border-hairline focus:border-ring/50"
670
+ />
671
+ );
672
+ }
673
+
674
+ function styleContext(anchor: HTMLElement, sel: TextRange | null): HTMLElement {
675
+ if (!sel) return anchor;
676
+ const node = window.getSelection()?.anchorNode;
677
+ const el = node instanceof HTMLElement ? node : (node?.parentElement ?? null);
678
+ return el && anchor.contains(el) ? el : anchor;
679
+ }
680
+
681
+ function focusAndPlaceCaret(
682
+ anchor: HTMLElement,
683
+ point: { x: number; y: number } | undefined,
684
+ selectWord: boolean,
685
+ ) {
686
+ anchor.focus({ preventScroll: true });
687
+ const selection = window.getSelection();
688
+ if (!selection) return;
689
+ if (point) {
690
+ const range = caretRangeAtPoint(point.x, point.y);
691
+ if (range && anchor.contains(range.startContainer)) {
692
+ selection.removeAllRanges();
693
+ selection.addRange(range);
694
+ const modifiable = selection as Selection & {
695
+ modify?: (alter: string, direction: string, granularity: string) => void;
696
+ };
697
+ if (
698
+ selectWord &&
699
+ typeof modifiable.modify === 'function' &&
700
+ range.startContainer instanceof Text
701
+ ) {
702
+ modifiable.modify('move', 'backward', 'word');
703
+ modifiable.modify('extend', 'forward', 'word');
704
+ }
705
+ return;
706
+ }
707
+ }
708
+ const range = document.createRange();
709
+ range.selectNodeContents(anchor);
710
+ range.collapse(false);
711
+ selection.removeAllRanges();
712
+ selection.addRange(range);
713
+ }
714
+
715
+ function caretRangeAtPoint(x: number, y: number): Range | null {
716
+ const doc = document as Document & {
717
+ caretRangeFromPoint?: (x: number, y: number) => Range | null;
718
+ caretPositionFromPoint?: (x: number, y: number) => { offsetNode: Node; offset: number } | null;
719
+ };
720
+ if (typeof doc.caretRangeFromPoint === 'function') return doc.caretRangeFromPoint(x, y);
721
+ const pos = doc.caretPositionFromPoint?.(x, y);
722
+ if (!pos) return null;
723
+ const range = document.createRange();
724
+ try {
725
+ range.setStart(pos.offsetNode, pos.offset);
726
+ } catch {
727
+ return null;
728
+ }
729
+ range.collapse(true);
730
+ return range;
731
+ }
732
+
733
+ // Map the live DOM selection to offsets in the normalized editable text —
734
+ // the same coordinate space `set-text-range-style` ops use.
735
+ export function selectionTextOffsets(root: HTMLElement): TextRange | null {
736
+ const selection = window.getSelection();
737
+ if (!selection || selection.rangeCount === 0) return null;
738
+ const range = selection.getRangeAt(0);
739
+ if (!root.contains(range.startContainer) || !root.contains(range.endContainer)) return null;
740
+ const parts: DomTextPart[] = [];
741
+ collectDomTextParts(root, parts);
742
+ const start = pointToTextOffset(parts, range.startContainer, range.startOffset);
743
+ const end = pointToTextOffset(parts, range.endContainer, range.endOffset);
744
+ if (start === null || end === null) return null;
745
+ return start <= end ? { start, end } : { start: end, end: start };
746
+ }
747
+
748
+ function pointToTextOffset(parts: DomTextPart[], container: Node, offset: number): number | null {
749
+ const probe = document.createRange();
750
+ try {
751
+ probe.setStart(container, offset);
752
+ } catch {
753
+ return null;
754
+ }
755
+ probe.collapse(true);
756
+ let total = 0;
757
+ for (const part of parts) {
758
+ if (part.node === container && part.node instanceof Text) {
759
+ const full = collapsedTextSlice(part.node, part.node.data);
760
+ const prefix = collapsedTextSlice(part.node, part.node.data.slice(0, offset));
761
+ const leading = Math.max(0, full.indexOf(part.current));
762
+ return total + Math.min(Math.max(prefix.length - leading, 0), part.current.length);
763
+ }
764
+ let cmp: number;
765
+ try {
766
+ cmp = probe.comparePoint(part.node, 0);
767
+ } catch {
768
+ return null;
769
+ }
770
+ if (cmp > 0) break;
771
+ if (cmp < 0) {
772
+ total += part.current.length;
773
+ continue;
774
+ }
775
+ break;
776
+ }
777
+ return total;
778
+ }
779
+
780
+ function collapsedTextSlice(node: Text, value: string): string {
781
+ const whiteSpace = node.parentElement ? getComputedStyle(node.parentElement).whiteSpace : '';
782
+ if (whiteSpace === 'pre' || whiteSpace === 'pre-wrap' || whiteSpace === 'break-spaces') {
783
+ return value;
784
+ }
785
+ return value.replace(/\s+/g, ' ');
786
+ }
787
+
788
+ function rgbToHex(value: string): string | null {
789
+ const m = value.match(/^rgba?\(([^)]+)\)$/);
790
+ if (!m) return null;
791
+ const parts = m[1].split(',').map((s) => s.trim());
792
+ if (parts.length < 3) return null;
793
+ const bytes = parts.slice(0, 3).map((p) => {
794
+ const n = Math.round(Number(p));
795
+ return Math.max(0, Math.min(255, Number.isFinite(n) ? n : 0));
796
+ });
797
+ return `#${bytes.map((n) => n.toString(16).padStart(2, '0')).join('')}`;
798
+ }