@open-slide/core 2.0.0-beta.3 → 2.0.0-beta.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.
Files changed (51) hide show
  1. package/README.md +1 -1
  2. package/dist/{build-Bzy-qlGc.js → build-Cu5_qRyE.js} +1 -1
  3. package/dist/cli/bin.js +3 -3
  4. package/dist/{config-nbSvY7z_.js → config-BQ6rD2iE.js} +226 -27
  5. package/dist/{config-DjWifhaA.d.ts → config-GMR1QUlM.d.ts} +1 -1
  6. package/dist/{dev-MXa5Tod4.js → dev-BK641O5e.js} +1 -1
  7. package/dist/index.d.ts +2 -2
  8. package/dist/index.js +1 -1
  9. package/dist/locale/index.d.ts +1 -1
  10. package/dist/locale/index.js +1 -1
  11. package/dist/{preview-DEpQcKz3.js → preview-BuCI-RMW.js} +1 -1
  12. package/dist/{types-BWg-Dtbg.d.ts → types-BcbaKTNY.d.ts} +60 -0
  13. package/dist/vite/index.d.ts +1 -1
  14. package/dist/vite/index.js +1 -1
  15. package/dist/{zh-tw-DlKyeNX7.js → zh-tw-DlZoAc2-.js} +271 -35
  16. package/package.json +6 -6
  17. package/src/app/components/asset-view.tsx +448 -0
  18. package/src/app/components/history-provider.tsx +68 -44
  19. package/src/app/components/icon-switcher-indicator.tsx +10 -0
  20. package/src/app/components/inspector/arrange-panel.tsx +449 -0
  21. package/src/app/components/inspector/inline-text-editor.tsx +170 -284
  22. package/src/app/components/inspector/inspect-overlay.tsx +642 -295
  23. package/src/app/components/inspector/inspector-panel.tsx +434 -427
  24. package/src/app/components/inspector/inspector-provider.tsx +564 -293
  25. package/src/app/components/inspector/save-bar.tsx +36 -0
  26. package/src/app/components/note-markdown.test.tsx +42 -0
  27. package/src/app/components/note-markdown.tsx +85 -0
  28. package/src/app/components/panel/editor-sidebar.tsx +50 -0
  29. package/src/app/components/panel/panel-fields.tsx +204 -16
  30. package/src/app/components/panel/panel-shell.tsx +3 -18
  31. package/src/app/components/style-panel/style-panel.tsx +4 -69
  32. package/src/app/lib/assets.ts +33 -0
  33. package/src/app/lib/export-html.ts +48 -5
  34. package/src/app/lib/inspector/geometry.test.ts +324 -0
  35. package/src/app/lib/inspector/geometry.ts +207 -0
  36. package/src/app/lib/inspector/text-edit-timeline.test.ts +121 -0
  37. package/src/app/lib/inspector/text-edit-timeline.ts +12 -0
  38. package/src/app/lib/inspector/text-selection.ts +117 -0
  39. package/src/app/lib/inspector/use-editor.ts +1 -1
  40. package/src/app/lib/inspector/use-visual-editor.ts +429 -0
  41. package/src/app/lib/inspector/visual-dom.ts +255 -0
  42. package/src/app/lib/keys.ts +9 -0
  43. package/src/app/lib/note-markdown.test.ts +147 -0
  44. package/src/app/lib/note-markdown.ts +116 -0
  45. package/src/app/routes/presenter.tsx +3 -2
  46. package/src/app/routes/slide.tsx +34 -9
  47. package/src/locale/en.ts +71 -9
  48. package/src/locale/ja.ts +73 -8
  49. package/src/locale/types.ts +60 -0
  50. package/src/locale/zh-cn.ts +69 -9
  51. package/src/locale/zh-tw.ts +69 -9
@@ -1,4 +1,4 @@
1
- import { Crosshair } from 'lucide-react';
1
+ import { Eye, PanelRight, Pencil } from 'lucide-react';
2
2
  import {
3
3
  createContext,
4
4
  type ReactNode,
@@ -11,10 +11,19 @@ import {
11
11
  } from 'react';
12
12
  import { toast } from 'sonner';
13
13
  import { useHistory } from '@/components/history-provider';
14
+ import { IconSwitcherIndicator } from '@/components/icon-switcher-indicator';
14
15
  import { Button } from '@/components/ui/button';
16
+ import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';
17
+ import { findSlideSource } from '@/lib/inspector/fiber';
18
+ import {
19
+ appendTextEdit,
20
+ type TextEditOp,
21
+ type TextEditStep,
22
+ } from '@/lib/inspector/text-edit-timeline';
15
23
  import { type SlideComment, useComments } from '@/lib/inspector/use-comments';
16
24
  import { type Edit, type EditOp, useEditor } from '@/lib/inspector/use-editor';
17
- import { isTypingTarget } from '@/lib/keys';
25
+ import { useVisualEditor, type VisualEdit } from '@/lib/inspector/use-visual-editor';
26
+ import { isShortcutControlTarget, isTypingTarget } from '@/lib/keys';
18
27
  import { textDiff } from '@/lib/text-diff';
19
28
  import { useLocale } from '@/lib/use-locale';
20
29
  import { round2 } from '@/lib/utils';
@@ -25,8 +34,28 @@ export type SelectedTarget = {
25
34
  line: number;
26
35
  column: number;
27
36
  anchor: HTMLElement;
37
+ canvasPath?: number[];
28
38
  };
29
39
 
40
+ function rememberTarget(target: SelectedTarget): SelectedTarget {
41
+ const root = target.anchor.closest('[data-osd-canvas]');
42
+ if (!root) return target;
43
+ const path: number[] = [];
44
+ for (let node: Element | null = target.anchor; node && node !== root; node = node.parentElement) {
45
+ const parent: Element | null = node.parentElement;
46
+ if (!parent) return target;
47
+ path.unshift(Array.from(parent.children).indexOf(node));
48
+ }
49
+ return { ...target, canvasPath: path };
50
+ }
51
+
52
+ function findRememberedTarget(root: HTMLElement, path?: number[]): HTMLElement | null {
53
+ let node = root.querySelector('[data-osd-canvas]');
54
+ if (!path) return null;
55
+ for (const index of path) node = node?.children[index] ?? null;
56
+ return node instanceof HTMLElement ? node : null;
57
+ }
58
+
30
59
  export type InlineEditTarget = SelectedTarget & {
31
60
  point?: { x: number; y: number };
32
61
  // Double-click entry selects the word under the caret; a single-click
@@ -37,44 +66,62 @@ export type InlineEditTarget = SelectedTarget & {
37
66
  session?: number;
38
67
  };
39
68
 
69
+ export type InlineTextSelection = { start: number; end: number };
70
+ type InlineStyleHandler = (ops: EditOp[]) => boolean;
71
+
40
72
  type AssetAttrOp = { assetPath: string; previewUrl: string };
41
73
  type Sequenced<T> = T & { seq: number };
42
74
  type StyleOp = { value: string | null; prevText?: string };
43
- type TextRangeStyleOp = {
44
- instanceId: string;
45
- start: number;
46
- end: number;
47
- key: string;
48
- value: string | null;
49
- prevText?: string;
50
- };
51
75
 
52
76
  type Bucket = {
53
77
  line: number;
54
78
  column: number;
55
79
  styleOps: Map<string, Sequenced<StyleOp>>;
56
- rangeStyleOps: Map<string, Sequenced<TextRangeStyleOp>>;
57
80
  // Text edits are scoped per DOM instance: a reused component renders
58
81
  // the same JSX `<h2>{title}</h2>` at multiple call sites with the same
59
82
  // `data-slide-loc`, but each call site's prop literal is independent.
60
83
  // Style/attr ops stay shared because they edit the JSX definition.
61
- textOps: Map<string /* instanceId */, Sequenced<{ value: string }>>;
84
+ textEdits: Map<string, TextEditStep[]>;
85
+ textTargets: Map<string, SelectedTarget & { pageIndex: number }>;
62
86
  attrOps: Map<string, Sequenced<AssetAttrOp>>;
63
87
  // Pre-edit snapshot of the DOM, captured the first time we touch
64
88
  // each style key / text / attribute. Used by `cancelEdits` to revert.
65
89
  origStyle: Map<string, string>;
66
90
  origTexts: Map<string /* instanceId */, { value: string }>;
67
- origHtmls: Map<string /* instanceId */, string>;
91
+ origHtmls: Map<string /* instanceId */, TextDomSnapshot>;
68
92
  origAttrs: Map<string, string | null>;
69
93
  };
70
94
 
95
+ function createBucket(line: number, column: number): Bucket {
96
+ return {
97
+ line,
98
+ column,
99
+ styleOps: new Map(),
100
+ textEdits: new Map(),
101
+ textTargets: new Map(),
102
+ attrOps: new Map(),
103
+ origStyle: new Map(),
104
+ origTexts: new Map(),
105
+ origHtmls: new Map(),
106
+ origAttrs: new Map(),
107
+ };
108
+ }
109
+
71
110
  const INSTANCE_ID_ATTR = 'data-slide-instance-id';
72
111
 
73
- function readInstanceId(el: HTMLElement): string | null {
74
- return el.getAttribute(INSTANCE_ID_ATTR);
75
- }
112
+ export type DomTextPart = {
113
+ node: Text | HTMLBRElement;
114
+ current: string;
115
+ preserveWhitespace?: boolean;
116
+ };
117
+ type WhiteSpaceResolver = (element: HTMLElement) => string;
118
+ type TextDomSnapshot = { html: string; whiteSpaces: string[] };
119
+
120
+ const computedWhiteSpace: WhiteSpaceResolver = (element) => getComputedStyle(element).whiteSpace;
76
121
 
77
- export type DomTextPart = { node: Text | HTMLBRElement; current: string };
122
+ function preservesWhitespace(whiteSpace: string): boolean {
123
+ return whiteSpace === 'pre' || whiteSpace === 'pre-wrap' || whiteSpace === 'break-spaces';
124
+ }
78
125
 
79
126
  export function readEditableText(el: HTMLElement): string {
80
127
  const parts: DomTextPart[] = [];
@@ -82,28 +129,39 @@ export function readEditableText(el: HTMLElement): string {
82
129
  return parts.map((part) => part.current).join('');
83
130
  }
84
131
 
85
- export function collectDomTextParts(node: Node, out: DomTextPart[]): void {
132
+ export function collectDomTextParts(
133
+ node: Node,
134
+ out: DomTextPart[],
135
+ whiteSpace: WhiteSpaceResolver = computedWhiteSpace,
136
+ ): void {
86
137
  const parts: DomTextPart[] = [];
87
- collectDomTextPartsRaw(node, parts);
138
+ collectDomTextPartsRaw(node, parts, whiteSpace);
88
139
  out.push(...normalizeDomTextParts(parts));
89
140
  }
90
141
 
91
- function collectDomTextPartsRaw(node: Node, out: DomTextPart[]): void {
142
+ function collectDomTextPartsRaw(
143
+ node: Node,
144
+ out: DomTextPart[],
145
+ whiteSpace: WhiteSpaceResolver,
146
+ ): void {
92
147
  for (const child of Array.from(node.childNodes)) {
93
148
  if (child instanceof Text) {
94
- const current = renderedTextNodeValue(child);
95
- if (current) out.push({ node: child, current });
149
+ const preserveWhitespace = preservesWhitespace(
150
+ child.parentElement ? whiteSpace(child.parentElement) : '',
151
+ );
152
+ const current = preserveWhitespace ? child.data : child.data.replace(/\s+/g, ' ');
153
+ if (current) out.push({ node: child, current, preserveWhitespace });
96
154
  } else if (child instanceof HTMLBRElement) {
97
155
  out.push({ node: child, current: '\n' });
98
156
  } else if (child instanceof HTMLElement) {
99
- collectDomTextPartsRaw(child, out);
157
+ collectDomTextPartsRaw(child, out, whiteSpace);
100
158
  }
101
159
  }
102
160
  }
103
161
 
104
162
  function normalizeDomTextParts(parts: DomTextPart[]): DomTextPart[] {
105
163
  return parts.flatMap((part, index) => {
106
- if (part.current === '\n') return [part];
164
+ if (part.preserveWhitespace || part.current === '\n') return [part];
107
165
  let current = part.current;
108
166
  if (parts[index - 1]?.current === '\n') current = current.replace(/^\s+/, '');
109
167
  if (parts[index + 1]?.current === '\n') current = current.replace(/\s+$/, '');
@@ -111,14 +169,6 @@ function normalizeDomTextParts(parts: DomTextPart[]): DomTextPart[] {
111
169
  });
112
170
  }
113
171
 
114
- function renderedTextNodeValue(node: Text): string {
115
- const whiteSpace = node.parentElement ? getComputedStyle(node.parentElement).whiteSpace : '';
116
- if (whiteSpace === 'pre' || whiteSpace === 'pre-wrap' || whiteSpace === 'break-spaces') {
117
- return node.data;
118
- }
119
- return node.data.replace(/\s+/g, ' ');
120
- }
121
-
122
172
  function textFragment(value: string): DocumentFragment {
123
173
  const fragment = document.createDocumentFragment();
124
174
  const lines = value.split('\n');
@@ -138,9 +188,13 @@ function replaceDomTextPart(part: DomTextPart, value: string) {
138
188
  part.node.replaceWith(fragment);
139
189
  }
140
190
 
141
- function setEditableText(el: HTMLElement, value: string) {
191
+ function setEditableText(
192
+ el: HTMLElement,
193
+ value: string,
194
+ whiteSpace: WhiteSpaceResolver = computedWhiteSpace,
195
+ ) {
142
196
  const parts: DomTextPart[] = [];
143
- collectDomTextParts(el, parts);
197
+ collectDomTextParts(el, parts, whiteSpace);
144
198
  const current = parts.map((part) => part.current).join('');
145
199
  if (current === value) return;
146
200
  if (parts.length === 0) {
@@ -184,21 +238,15 @@ function setEditableText(el: HTMLElement, value: string) {
184
238
  }
185
239
  }
186
240
 
187
- function rangeStyleKey(
188
- instanceId: string,
189
- op: { start: number; end: number; key: string },
190
- ): string {
191
- return `${instanceId}:${op.start}:${op.end}:${op.key}`;
192
- }
193
-
194
241
  function applyDomTextRangeStyle(
195
242
  el: HTMLElement,
196
- op: Pick<TextRangeStyleOp, 'start' | 'end' | 'key' | 'value'>,
243
+ op: Extract<TextEditOp, { kind: 'set-text-range-style' }>,
244
+ whiteSpace: WhiteSpaceResolver,
197
245
  ) {
198
246
  const value = op.value ?? resetValueForRangeStyle(op.key);
199
247
  if (value === null) return;
200
248
  const parts: DomTextPart[] = [];
201
- collectDomTextParts(el, parts);
249
+ collectDomTextParts(el, parts, whiteSpace);
202
250
  let offset = 0;
203
251
  for (const part of parts) {
204
252
  const partStart = offset;
@@ -227,25 +275,68 @@ function resetValueForRangeStyle(key: string): string | null {
227
275
  return null;
228
276
  }
229
277
 
230
- function replayDomTextRangeStyles(el: HTMLElement, html: string, ops: TextRangeStyleOp[]) {
278
+ function textSnapshotElements(el: HTMLElement): HTMLElement[] {
279
+ return [
280
+ el,
281
+ ...Array.from(el.querySelectorAll('*')).filter((node) => node instanceof HTMLElement),
282
+ ];
283
+ }
284
+
285
+ function captureTextDom(
286
+ el: HTMLElement,
287
+ whiteSpace: WhiteSpaceResolver = computedWhiteSpace,
288
+ ): TextDomSnapshot {
289
+ return { html: el.innerHTML, whiteSpaces: textSnapshotElements(el).map(whiteSpace) };
290
+ }
291
+
292
+ function textEditHtml(snapshot: TextDomSnapshot, steps: TextEditStep[]): TextDomSnapshot {
231
293
  const preview = document.createElement('span');
232
- preview.innerHTML = html;
233
- for (const op of ops) applyDomTextRangeStyle(preview, op);
234
- if (el.innerHTML !== preview.innerHTML) el.innerHTML = preview.innerHTML;
294
+ preview.innerHTML = snapshot.html;
295
+ const contexts = new Map(
296
+ textSnapshotElements(preview).map((element, index) => [element, snapshot.whiteSpaces[index]]),
297
+ );
298
+ const whiteSpace: WhiteSpaceResolver = (element) => {
299
+ for (let node: HTMLElement | null = element; node; node = node.parentElement) {
300
+ const value = contexts.get(node);
301
+ if (value !== undefined) return value;
302
+ }
303
+ return 'normal';
304
+ };
305
+ for (const { op } of steps) {
306
+ if (op.kind === 'set-text') setEditableText(preview, op.value, whiteSpace);
307
+ else applyDomTextRangeStyle(preview, op, whiteSpace);
308
+ }
309
+ return captureTextDom(preview, whiteSpace);
310
+ }
311
+
312
+ function replayDomTextEdits(el: HTMLElement, snapshot: TextDomSnapshot, steps: TextEditStep[]) {
313
+ const next = textEditHtml(snapshot, steps).html;
314
+ if (el.innerHTML !== next) el.innerHTML = next;
235
315
  }
236
316
 
237
317
  type InspectorCtx = {
238
318
  slideId: string;
239
319
  active: boolean;
240
320
  toggle: () => void;
321
+ panelOpen: boolean;
322
+ panelHidden: boolean;
323
+ togglePanel: () => void;
241
324
  cancel: () => void;
242
325
  comments: SlideComment[];
243
326
  error: string | null;
244
327
  add: (line: number, column: number, text: string) => Promise<void>;
245
328
  remove: (id: string) => Promise<void>;
329
+ selection: SelectedTarget[];
330
+ setSelection: (targets: SelectedTarget[]) => void;
331
+ bufferBatch: (edits: VisualEdit[], coalesceKey?: string) => void;
332
+ visual: ReturnType<typeof useVisualEditor>;
246
333
  selected: SelectedTarget | null;
247
334
  setSelected: (s: SelectedTarget | null) => void;
248
335
  inlineEdit: InlineEditTarget | null;
336
+ inlineSelection: InlineTextSelection | null;
337
+ setInlineSelection: (selection: InlineTextSelection | null) => void;
338
+ registerInlineStyle: (handler: InlineStyleHandler) => () => void;
339
+ applyInlineStyle: InlineStyleHandler;
249
340
  startInlineEdit: (target: InlineEditTarget) => void;
250
341
  stopInlineEdit: () => void;
251
342
  // Bumped on every buffered-op mutation (including undo/redo restores) so
@@ -275,21 +366,66 @@ export function useInspector(): InspectorCtx {
275
366
  export function InspectorProvider({
276
367
  slideId,
277
368
  pageIndex,
369
+ panelHidden = false,
370
+ onPanelOpen,
278
371
  children,
279
372
  }: {
280
373
  slideId: string;
281
374
  pageIndex: number;
375
+ panelHidden?: boolean;
376
+ onPanelOpen?: () => void;
282
377
  children: ReactNode;
283
378
  }) {
284
- const [active, setActive] = useState(false);
285
- const [selected, setSelected] = useState<SelectedTarget | null>(null);
379
+ const [active, setActive] = useState(import.meta.env.DEV);
380
+ const [panelOpen, setPanelOpen] = useState(
381
+ () => typeof window !== 'undefined' && window.innerWidth >= 1024,
382
+ );
383
+ const [selection, setSelectionState] = useState<SelectedTarget[]>([]);
384
+ const selected = selection.at(-1) ?? null;
385
+ const setSelection = useCallback((targets: SelectedTarget[]) => {
386
+ setSelectionState(targets.map(rememberTarget));
387
+ }, []);
388
+ const setSelected = useCallback((target: SelectedTarget | null) => {
389
+ setSelectionState((previous) => {
390
+ if (!target) return [];
391
+ const primary = previous.at(-1);
392
+ if (
393
+ primary?.anchor === target.anchor &&
394
+ primary.line === target.line &&
395
+ primary.column === target.column
396
+ )
397
+ return previous;
398
+ if (
399
+ primary?.anchor === target.anchor ||
400
+ (primary?.line === target.line && primary.column === target.column)
401
+ ) {
402
+ return [...previous.slice(0, -1), rememberTarget(target)];
403
+ }
404
+ return [rememberTarget(target)];
405
+ });
406
+ }, []);
286
407
  const [inlineEdit, setInlineEdit] = useState<InlineEditTarget | null>(null);
408
+ const [inlineSelection, setInlineSelection] = useState<InlineTextSelection | null>(null);
409
+ const inlineStyleRef = useRef<InlineStyleHandler | null>(null);
410
+ const registerInlineStyle = useCallback((handler: InlineStyleHandler) => {
411
+ inlineStyleRef.current = handler;
412
+ return () => {
413
+ if (inlineStyleRef.current === handler) inlineStyleRef.current = null;
414
+ };
415
+ }, []);
416
+ const applyInlineStyle = useCallback(
417
+ (ops: EditOp[]) => inlineStyleRef.current?.(ops) ?? false,
418
+ [],
419
+ );
287
420
  const [opsVersion, setOpsVersion] = useState(0);
288
421
  const { comments, error, add, remove } = useComments(slideId);
289
422
  const { applyEdit, applyEdits } = useEditor(slideId);
290
423
  const history = useHistory();
291
424
 
292
425
  const pendingRef = useRef<Map<string, Bucket>>(new Map());
426
+ const inlineBaselinesRef = useRef(
427
+ new WeakMap<HTMLElement, { text: string; html: TextDomSnapshot }>(),
428
+ );
293
429
  const instanceCounterRef = useRef(0);
294
430
  const pendingSeqRef = useRef(0);
295
431
  const [pendingCount, setPendingCount] = useState(0);
@@ -323,12 +459,7 @@ export function InspectorProvider({
323
459
  const refreshCount = useCallback(() => {
324
460
  let n = 0;
325
461
  for (const b of pendingRef.current.values()) {
326
- if (
327
- b.styleOps.size > 0 ||
328
- b.rangeStyleOps.size > 0 ||
329
- b.textOps.size > 0 ||
330
- b.attrOps.size > 0
331
- ) {
462
+ if (b.styleOps.size > 0 || b.textEdits.size > 0 || b.attrOps.size > 0) {
332
463
  n++;
333
464
  }
334
465
  }
@@ -357,18 +488,7 @@ export function InspectorProvider({
357
488
  const key = `${line}:${column}`;
358
489
  let bucket = pendingRef.current.get(key);
359
490
  if (!bucket) {
360
- bucket = {
361
- line,
362
- column,
363
- styleOps: new Map(),
364
- rangeStyleOps: new Map(),
365
- textOps: new Map(),
366
- attrOps: new Map(),
367
- origStyle: new Map(),
368
- origTexts: new Map(),
369
- origHtmls: new Map(),
370
- origAttrs: new Map(),
371
- };
491
+ bucket = createBucket(line, column);
372
492
  pendingRef.current.set(key, bucket);
373
493
  }
374
494
  const style = (anchor?.style ?? {}) as unknown as Record<string, string>;
@@ -380,40 +500,43 @@ export function InspectorProvider({
380
500
  }
381
501
  bucket.styleOps.set(op.key, { value: op.value, prevText: op.prevText, seq });
382
502
  if (anchor?.isConnected) style[op.key] = op.value ?? '';
383
- } else if (op.kind === 'set-text-range-style') {
503
+ } else if (op.kind === 'set-text-range-style' || op.kind === 'set-text') {
384
504
  if (!anchor) continue;
385
505
  const instanceId = ensureInstanceId(anchor);
386
- if (!bucket.origHtmls.has(instanceId)) bucket.origHtmls.set(instanceId, anchor.innerHTML);
387
- const nextOp: Sequenced<TextRangeStyleOp> = {
388
- instanceId,
389
- start: op.start,
390
- end: op.end,
391
- key: op.key,
392
- value: op.value,
393
- prevText: op.prevText ?? readEditableText(anchor),
394
- seq,
395
- };
396
- bucket.rangeStyleOps.set(rangeStyleKey(instanceId, op), nextOp);
397
- if (anchor.isConnected) {
398
- replayDomTextRangeStyles(
399
- anchor,
400
- bucket.origHtmls.get(instanceId) ?? anchor.innerHTML,
401
- Array.from(bucket.rangeStyleOps.values()).filter(
402
- (item) => item.instanceId === instanceId,
403
- ),
506
+ bucket.textTargets.set(instanceId, {
507
+ ...rememberTarget({ line, column, anchor }),
508
+ pageIndex,
509
+ });
510
+ const prevText = op.prevText ?? readEditableText(anchor);
511
+ if (!bucket.origTexts.has(instanceId)) {
512
+ bucket.origTexts.set(instanceId, { value: prevText });
513
+ }
514
+ if (!bucket.origHtmls.has(instanceId)) {
515
+ const baseline = inlineBaselinesRef.current.get(anchor);
516
+ bucket.origHtmls.set(
517
+ instanceId,
518
+ baseline?.text === prevText
519
+ ? baseline.html
520
+ : textEditHtml(captureTextDom(anchor), [
521
+ { seq, op: { kind: 'set-text', value: prevText } },
522
+ ]),
404
523
  );
405
524
  }
406
- } else if (op.kind === 'set-text') {
407
- // Reused JSX renders multiple DOM nodes with the same
408
- // `data-slide-loc` but distinct call-site literals; without an
409
- // anchor we can't tell which instance to route to, so skip.
410
- if (!anchor) continue;
411
- const instanceId = ensureInstanceId(anchor);
412
- if (!bucket.origTexts.has(instanceId)) {
413
- bucket.origTexts.set(instanceId, { value: readEditableText(anchor) });
525
+ const steps = appendTextEdit(
526
+ bucket.textEdits.get(instanceId) ?? [],
527
+ { ...op, prevText },
528
+ seq,
529
+ );
530
+ bucket.textEdits.set(instanceId, steps);
531
+ if (anchor.isConnected) {
532
+ if (op.kind === 'set-text') setEditableText(anchor, op.value);
533
+ else
534
+ replayDomTextEdits(
535
+ anchor,
536
+ bucket.origHtmls.get(instanceId) ?? captureTextDom(anchor),
537
+ steps,
538
+ );
414
539
  }
415
- bucket.textOps.set(instanceId, { value: op.value, seq });
416
- if (anchor.isConnected) setEditableText(anchor, op.value);
417
540
  } else if (op.kind === 'set-attr-asset') {
418
541
  if (anchor && !bucket.origAttrs.has(op.attr)) {
419
542
  bucket.origAttrs.set(
@@ -431,7 +554,7 @@ export function InspectorProvider({
431
554
  }
432
555
  refreshCount();
433
556
  },
434
- [refreshCount, ensureInstanceId],
557
+ [refreshCount, ensureInstanceId, pageIndex],
435
558
  );
436
559
 
437
560
  // Pre-edit snapshot for history: capture the *currently effective* value of
@@ -440,21 +563,14 @@ export function InspectorProvider({
440
563
  type StyleSnap = {
441
564
  kind: 'style';
442
565
  key: string;
443
- value: Sequenced<StyleOp> | string | null;
444
- existed: boolean;
445
- };
446
- type RangeStyleSnap = {
447
- kind: 'range-style';
448
- id: string;
449
- instanceId: string;
450
- value: Sequenced<TextRangeStyleOp> | null;
451
- existed: boolean;
452
- };
566
+ } & ({ value: Sequenced<StyleOp>; existed: true } | { value: string | null; existed: false });
453
567
  type TextSnap = {
454
568
  kind: 'text';
455
569
  instanceId: string;
456
- value: string | null;
457
- existed: boolean;
570
+ target?: SelectedTarget & { pageIndex: number };
571
+ steps: TextEditStep[];
572
+ html?: TextDomSnapshot;
573
+ text?: string;
458
574
  };
459
575
  type AttrSnap = {
460
576
  kind: 'attr';
@@ -462,7 +578,7 @@ export function InspectorProvider({
462
578
  value: Sequenced<AssetAttrOp> | string | null;
463
579
  source: 'op' | 'orig' | 'dom-missing' | 'dom-present';
464
580
  };
465
- type Snap = StyleSnap | RangeStyleSnap | TextSnap | AttrSnap;
581
+ type Snap = StyleSnap | TextSnap | AttrSnap;
466
582
 
467
583
  const snapshotForOps = useCallback(
468
584
  (line: number, column: number, anchor: HTMLElement, ops: EditOp[]): Snap[] => {
@@ -488,30 +604,16 @@ export function InspectorProvider({
488
604
  existed: false,
489
605
  });
490
606
  }
491
- } else if (op.kind === 'set-text-range-style') {
607
+ } else if (op.kind === 'set-text-range-style' || op.kind === 'set-text') {
492
608
  const instanceId = ensureInstanceId(anchor);
493
- const id = rangeStyleKey(instanceId, op);
494
- const existing = bucket?.rangeStyleOps.get(id);
495
609
  snaps.push({
496
- kind: 'range-style',
497
- id,
610
+ kind: 'text',
498
611
  instanceId,
499
- value: existing ? { ...existing } : null,
500
- existed: !!existing,
612
+ target: bucket?.textTargets.get(instanceId),
613
+ steps: bucket?.textEdits.get(instanceId) ?? [],
614
+ html: bucket?.origHtmls.get(instanceId),
615
+ text: bucket?.origTexts.get(instanceId)?.value,
501
616
  });
502
- } else if (op.kind === 'set-text') {
503
- const instanceId = ensureInstanceId(anchor);
504
- const existing = bucket?.textOps.get(instanceId);
505
- if (existing) {
506
- snaps.push({ kind: 'text', instanceId, value: existing.value, existed: true });
507
- } else {
508
- snaps.push({
509
- kind: 'text',
510
- instanceId,
511
- value: readEditableText(anchor),
512
- existed: false,
513
- });
514
- }
515
617
  } else if (op.kind === 'set-attr-asset') {
516
618
  const prev = bucket?.attrOps.get(op.attr);
517
619
  if (prev) {
@@ -543,9 +645,13 @@ export function InspectorProvider({
543
645
  // Restore the snapshotted values to bucket + DOM. Mirrors the bucket-empty
544
646
  // logic of `cancelEdits` so an undo back to the absolute baseline cleans up.
545
647
  const restoreSnapshot = useCallback(
546
- (line: number, column: number, snaps: Snap[]) => {
648
+ (line: number, column: number, snaps: Snap[], recreate = false) => {
547
649
  const key = `${line}:${column}`;
548
- const bucket = pendingRef.current.get(key);
650
+ let bucket = pendingRef.current.get(key);
651
+ if (!bucket && recreate) {
652
+ bucket = createBucket(line, column);
653
+ pendingRef.current.set(key, bucket);
654
+ }
549
655
  if (!bucket) return;
550
656
  // Style/attr snaps share the loc-level anchor (first match);
551
657
  // text snaps look up their per-instance node below.
@@ -554,47 +660,26 @@ export function InspectorProvider({
554
660
  for (const snap of snaps) {
555
661
  if (snap.kind === 'style') {
556
662
  if (snap.existed) {
557
- const prev =
558
- typeof snap.value === 'object' && snap.value !== null
559
- ? snap.value
560
- : { value: snap.value };
663
+ const prev = snap.value;
561
664
  const v = prev.value ?? '';
562
- bucket.styleOps.set(snap.key, { ...prev, seq: ++pendingSeqRef.current });
665
+ // Undo restores the edit's original position in the text timeline.
666
+ bucket.styleOps.set(snap.key, { ...prev });
563
667
  if (sharedAnchor?.isConnected) sharedStyle[snap.key] = v;
564
668
  } else {
565
669
  bucket.styleOps.delete(snap.key);
566
670
  const orig = bucket.origStyle.get(snap.key);
567
671
  if (sharedAnchor?.isConnected) sharedStyle[snap.key] = orig ?? '';
568
672
  }
569
- } else if (snap.kind === 'range-style') {
673
+ } else if (snap.kind === 'text') {
570
674
  const textAnchor = findAnchor(line, column, snap.instanceId);
571
- if (snap.existed && snap.value) {
572
- bucket.rangeStyleOps.set(snap.id, { ...snap.value, seq: ++pendingSeqRef.current });
573
- } else {
574
- bucket.rangeStyleOps.delete(snap.id);
575
- }
675
+ if (snap.target) bucket.textTargets.set(snap.instanceId, snap.target);
676
+ if (snap.html !== undefined) bucket.origHtmls.set(snap.instanceId, snap.html);
677
+ if (snap.text !== undefined) bucket.origTexts.set(snap.instanceId, { value: snap.text });
678
+ if (snap.steps.length) bucket.textEdits.set(snap.instanceId, snap.steps);
679
+ else bucket.textEdits.delete(snap.instanceId);
576
680
  const html = bucket.origHtmls.get(snap.instanceId);
577
681
  if (textAnchor?.isConnected && html !== undefined) {
578
- replayDomTextRangeStyles(
579
- textAnchor,
580
- html,
581
- Array.from(bucket.rangeStyleOps.values()).filter(
582
- (op) => op.instanceId === snap.instanceId,
583
- ),
584
- );
585
- }
586
- } else if (snap.kind === 'text') {
587
- const textAnchor = findAnchor(line, column, snap.instanceId);
588
- if (snap.existed) {
589
- bucket.textOps.set(snap.instanceId, {
590
- value: snap.value ?? '',
591
- seq: ++pendingSeqRef.current,
592
- });
593
- if (textAnchor?.isConnected) setEditableText(textAnchor, snap.value ?? '');
594
- } else {
595
- bucket.textOps.delete(snap.instanceId);
596
- const orig = bucket.origTexts.get(snap.instanceId);
597
- if (textAnchor?.isConnected) setEditableText(textAnchor, orig?.value ?? '');
682
+ replayDomTextEdits(textAnchor, html, snap.steps);
598
683
  }
599
684
  } else if (snap.kind === 'attr') {
600
685
  if (snap.source === 'op') {
@@ -611,12 +696,7 @@ export function InspectorProvider({
611
696
  }
612
697
  }
613
698
  }
614
- if (
615
- bucket.styleOps.size === 0 &&
616
- bucket.rangeStyleOps.size === 0 &&
617
- bucket.textOps.size === 0 &&
618
- bucket.attrOps.size === 0
619
- ) {
699
+ if (bucket.styleOps.size === 0 && bucket.textEdits.size === 0 && bucket.attrOps.size === 0) {
620
700
  pendingRef.current.delete(key);
621
701
  }
622
702
  refreshCount();
@@ -626,13 +706,24 @@ export function InspectorProvider({
626
706
 
627
707
  const bufferOps = useCallback(
628
708
  (line: number, column: number, anchor: HTMLElement, ops: EditOp[]) => {
709
+ const target = findSlideSource(anchor, slideId, { hostOnly: true }) ?? {
710
+ line,
711
+ column,
712
+ anchor,
713
+ };
629
714
  const instanceId = ops.some(
630
715
  (op) => op.kind === 'set-text' || op.kind === 'set-text-range-style',
631
716
  )
632
- ? ensureInstanceId(anchor)
717
+ ? ensureInstanceId(target.anchor)
633
718
  : undefined;
634
- const snaps = snapshotForOps(line, column, anchor, ops);
635
- applyOpsRaw(line, column, anchor, ops);
719
+ const snaps = snapshotForOps(target.line, target.column, target.anchor, ops);
720
+ applyOpsRaw(target.line, target.column, target.anchor, ops);
721
+ const textAfter = snapshotForOps(target.line, target.column, target.anchor, ops).filter(
722
+ (snap) => snap.kind === 'text',
723
+ );
724
+ const sharedOps = ops.filter(
725
+ (op) => op.kind !== 'set-text' && op.kind !== 'set-text-range-style',
726
+ );
636
727
  const first = ops[0];
637
728
  const opKey = first
638
729
  ? first.kind === 'set-style'
@@ -641,31 +732,80 @@ export function InspectorProvider({
641
732
  ? first.attr
642
733
  : 'text'
643
734
  : 'noop';
644
- const coalesceKey = `inspector:${line}:${column}:${first?.kind ?? 'noop'}:${opKey}`;
735
+ const coalesceKey = `inspector:${target.line}:${target.column}:${first?.kind ?? 'noop'}:${opKey}`;
736
+ history.record({
737
+ coalesceKey,
738
+ undo: () => restoreSnapshot(target.line, target.column, snaps),
739
+ redo: () => {
740
+ if (sharedOps.length) {
741
+ applyOpsRaw(
742
+ target.line,
743
+ target.column,
744
+ findAnchor(target.line, target.column, instanceId),
745
+ sharedOps,
746
+ );
747
+ }
748
+ if (textAfter.length) restoreSnapshot(target.line, target.column, textAfter, true);
749
+ },
750
+ });
751
+ },
752
+ [applyOpsRaw, snapshotForOps, restoreSnapshot, findAnchor, history, ensureInstanceId, slideId],
753
+ );
754
+
755
+ const bufferBatch = useCallback(
756
+ (input: VisualEdit[], coalesceKey?: string) => {
757
+ if (input.length === 0 || committing) return;
758
+ const edits = input.map((edit) => ({
759
+ ...edit,
760
+ ...findSlideSource(edit.anchor, slideId, { hostOnly: true }),
761
+ }));
762
+ const snapshots = edits.map((edit) =>
763
+ snapshotForOps(edit.line, edit.column, edit.anchor, edit.ops),
764
+ );
765
+ for (const edit of edits) applyOpsRaw(edit.line, edit.column, edit.anchor, edit.ops);
645
766
  history.record({
646
767
  coalesceKey,
647
- undo: () => restoreSnapshot(line, column, snaps),
648
- redo: () => applyOpsRaw(line, column, findAnchor(line, column, instanceId), ops),
768
+ undo: () => {
769
+ for (let index = edits.length - 1; index >= 0; index--) {
770
+ const edit = edits[index];
771
+ restoreSnapshot(edit.line, edit.column, snapshots[index]);
772
+ }
773
+ },
774
+ redo: () => {
775
+ for (const edit of edits)
776
+ applyOpsRaw(edit.line, edit.column, findAnchor(edit.line, edit.column), edit.ops);
777
+ },
649
778
  });
650
779
  },
651
- [applyOpsRaw, snapshotForOps, restoreSnapshot, findAnchor, history, ensureInstanceId],
780
+ [applyOpsRaw, snapshotForOps, restoreSnapshot, findAnchor, history, committing, slideId],
652
781
  );
653
782
 
783
+ const visual = useVisualEditor({
784
+ active,
785
+ inlineEditing: !!inlineEdit,
786
+ committing,
787
+ slideId,
788
+ selection,
789
+ setSelection,
790
+ bufferBatch,
791
+ });
792
+
654
793
  const commitEdits = useCallback(async () => {
655
794
  const buckets = pendingRef.current;
656
795
  if (buckets.size === 0) return;
657
796
  type PendingItem = {
658
- key: string;
797
+ bucket: Bucket;
659
798
  seq: number;
799
+ instanceId?: string;
660
800
  edit: Edit;
661
801
  onSuccess: (bucket: Bucket) => void;
662
802
  };
663
803
  const pending: PendingItem[] = [];
664
- for (const [key, bucket] of buckets) {
665
- const { line, column, styleOps, rangeStyleOps, textOps, attrOps, origTexts } = bucket;
804
+ for (const bucket of buckets.values()) {
805
+ const { line, column, styleOps, textEdits, attrOps } = bucket;
666
806
  for (const [k, op] of styleOps) {
667
807
  pending.push({
668
- key,
808
+ bucket,
669
809
  seq: op.seq,
670
810
  edit: {
671
811
  line,
@@ -674,12 +814,13 @@ export function InspectorProvider({
674
814
  },
675
815
  onSuccess: (b) => {
676
816
  b.styleOps.delete(k);
817
+ b.origStyle.delete(k);
677
818
  },
678
819
  });
679
820
  }
680
821
  for (const [attr, op] of attrOps) {
681
822
  pending.push({
682
- key,
823
+ bucket,
683
824
  seq: op.seq,
684
825
  edit: {
685
826
  line,
@@ -695,51 +836,44 @@ export function InspectorProvider({
695
836
  },
696
837
  onSuccess: (b) => {
697
838
  b.attrOps.delete(attr);
839
+ b.origAttrs.delete(attr);
698
840
  },
699
841
  });
700
842
  }
701
- for (const [id, op] of rangeStyleOps) {
702
- pending.push({
703
- key,
704
- seq: op.seq,
705
- edit: {
706
- line,
707
- column,
708
- ops: [
709
- {
710
- kind: 'set-text-range-style',
711
- start: op.start,
712
- end: op.end,
713
- key: op.key,
714
- value: op.value,
715
- prevText: op.prevText,
716
- },
717
- ],
718
- },
719
- onSuccess: (b) => {
720
- b.rangeStyleOps.delete(id);
721
- },
722
- });
723
- }
724
- // Per-instance text edits — one Edit per call site, each with its
725
- // own prevText so the server can disambiguate among siblings.
726
- for (const [instanceId, textOp] of textOps) {
727
- const orig = origTexts.get(instanceId);
728
- pending.push({
729
- key,
730
- seq: textOp.seq,
731
- edit: {
732
- line,
733
- column,
734
- ops: [{ kind: 'set-text', value: textOp.value, prevText: orig?.value }],
735
- },
736
- onSuccess: (b) => {
737
- b.textOps.delete(instanceId);
738
- },
739
- });
843
+ for (const [instanceId, steps] of textEdits) {
844
+ const target = bucket.textTargets.get(instanceId);
845
+ for (const step of steps) {
846
+ pending.push({
847
+ bucket,
848
+ seq: step.seq,
849
+ instanceId,
850
+ edit: {
851
+ line: target?.line ?? line,
852
+ column: target?.column ?? column,
853
+ ops: [step.op],
854
+ },
855
+ onSuccess: (b) => {
856
+ const html = b.origHtmls.get(instanceId);
857
+ if (html !== undefined) b.origHtmls.set(instanceId, textEditHtml(html, [step]));
858
+ if (step.op.kind === 'set-text')
859
+ b.origTexts.set(instanceId, { value: step.op.value });
860
+ const remaining = (b.textEdits.get(instanceId) ?? []).filter(
861
+ (item) => item.seq !== step.seq,
862
+ );
863
+ if (remaining.length) b.textEdits.set(instanceId, remaining);
864
+ else b.textEdits.delete(instanceId);
865
+ },
866
+ });
867
+ }
740
868
  }
741
869
  }
742
870
  pending.sort((a, b) => a.seq - b.seq);
871
+ const lastTextEdit = new Map<string, number>();
872
+ for (const [index, item] of pending.entries()) {
873
+ if (!item.instanceId) continue;
874
+ item.edit.dependsOn = lastTextEdit.get(item.instanceId);
875
+ lastTextEdit.set(item.instanceId, index);
876
+ }
743
877
  if (pending.length === 0) {
744
878
  pendingRef.current = new Map();
745
879
  setPendingCount(0);
@@ -753,17 +887,16 @@ export function InspectorProvider({
753
887
  for (let i = 0; i < results.length; i++) {
754
888
  const item = pending[i];
755
889
  const r = results[i];
756
- const bucket = pendingRef.current.get(item.key);
890
+ const bucket = item.bucket;
757
891
  if (r.ok) {
758
- if (bucket) {
759
- item.onSuccess(bucket);
760
- if (
761
- bucket.styleOps.size === 0 &&
762
- bucket.rangeStyleOps.size === 0 &&
763
- bucket.textOps.size === 0 &&
764
- bucket.attrOps.size === 0
765
- ) {
766
- pendingRef.current.delete(item.key);
892
+ item.onSuccess(bucket);
893
+ if (
894
+ bucket.styleOps.size === 0 &&
895
+ bucket.textEdits.size === 0 &&
896
+ bucket.attrOps.size === 0
897
+ ) {
898
+ for (const [key, pendingBucket] of pendingRef.current) {
899
+ if (pendingBucket === bucket) pendingRef.current.delete(key);
767
900
  }
768
901
  }
769
902
  } else {
@@ -802,7 +935,7 @@ export function InspectorProvider({
802
935
  for (const [instanceId, html] of b.origHtmls) {
803
936
  const textEl =
804
937
  root?.querySelector<HTMLElement>(`[${INSTANCE_ID_ATTR}="${instanceId}"]`) ?? null;
805
- if (textEl?.isConnected) textEl.innerHTML = html;
938
+ if (textEl?.isConnected) textEl.innerHTML = html.html;
806
939
  }
807
940
  for (const [instanceId, orig] of b.origTexts) {
808
941
  const textEl =
@@ -812,6 +945,7 @@ export function InspectorProvider({
812
945
  }
813
946
  pendingRef.current = new Map();
814
947
  setPendingCount(0);
948
+ setOpsVersion((version) => version + 1);
815
949
  history.clear();
816
950
  }, [history]);
817
951
 
@@ -849,24 +983,6 @@ export function InspectorProvider({
849
983
  const v = op.value ?? '';
850
984
  if (style[key] !== v) style[key] = v;
851
985
  }
852
- // Text replays per-instance: only the originally clicked DOM node
853
- // (stamped with its `data-slide-instance-id`) gets the buffered
854
- // value, so siblings of a reused component aren't clobbered.
855
- const instanceId = readInstanceId(el);
856
- if (instanceId) {
857
- const html = bucket.origHtmls.get(instanceId);
858
- if (html !== undefined) {
859
- replayDomTextRangeStyles(
860
- el,
861
- html,
862
- Array.from(bucket.rangeStyleOps.values()).filter((op) => op.instanceId === instanceId),
863
- );
864
- }
865
- const textOp = bucket.textOps.get(instanceId);
866
- if (textOp && readEditableText(el) !== textOp.value) {
867
- setEditableText(el, textOp.value);
868
- }
869
- }
870
986
  for (const [attr, op] of bucket.attrOps) {
871
987
  if (el.getAttribute(attr) !== op.previewUrl) el.setAttribute(attr, op.previewUrl);
872
988
  }
@@ -876,73 +992,151 @@ export function InspectorProvider({
876
992
  const replayAll = () => {
877
993
  if (pendingRef.current.size === 0) return;
878
994
  observer?.disconnect();
995
+ const relocations: { key: string; nextKey: string; bucket: Bucket }[] = [];
996
+ for (const [key, bucket] of pendingRef.current) {
997
+ for (const [instanceId, target] of bucket.textTargets) {
998
+ if (target.pageIndex !== pageIndex) continue;
999
+ const stamped = root.querySelector<HTMLElement>(`[${INSTANCE_ID_ATTR}="${instanceId}"]`);
1000
+ const anchor = stamped ?? findRememberedTarget(root, target.canvasPath);
1001
+ if (!anchor || anchor.tagName !== target.anchor.tagName) continue;
1002
+ const steps = bucket.textEdits.get(instanceId) ?? [];
1003
+ const html = bucket.origHtmls.get(instanceId);
1004
+ if (!html) continue;
1005
+ if (!stamped) {
1006
+ const text = readEditableText(anchor);
1007
+ const matchesBaseline = bucket.origTexts.get(instanceId)?.value === text;
1008
+ if (
1009
+ !matchesBaseline &&
1010
+ !steps.some((step) => step.op.kind === 'set-text' && step.op.value === text)
1011
+ )
1012
+ continue;
1013
+ }
1014
+ const hit = findSlideSource(anchor, slideId, { hostOnly: true });
1015
+ if (!hit || hit.anchor !== anchor) continue;
1016
+ anchor.setAttribute(INSTANCE_ID_ATTR, instanceId);
1017
+ bucket.textTargets.set(instanceId, { ...rememberTarget(hit), pageIndex });
1018
+ bucket.line = hit.line;
1019
+ bucket.column = hit.column;
1020
+ // Native editing can mutate child nodes before its input event updates the buffer.
1021
+ if (!anchor.isContentEditable) replayDomTextEdits(anchor, html, steps);
1022
+ }
1023
+ const nextKey = `${bucket.line}:${bucket.column}`;
1024
+ if (nextKey !== key) relocations.push({ key, nextKey, bucket });
1025
+ }
1026
+ let moved = true;
1027
+ while (moved) {
1028
+ moved = false;
1029
+ for (let index = relocations.length - 1; index >= 0; index--) {
1030
+ const { key, nextKey, bucket } = relocations[index];
1031
+ if (pendingRef.current.has(nextKey)) continue;
1032
+ pendingRef.current.delete(key);
1033
+ pendingRef.current.set(nextKey, bucket);
1034
+ relocations.splice(index, 1);
1035
+ moved = true;
1036
+ }
1037
+ }
879
1038
  root.querySelectorAll<HTMLElement>('[data-slide-loc]').forEach(applyBuffered);
880
- observer?.observe(root, { childList: true, subtree: true });
1039
+ observer?.observe(root, {
1040
+ childList: true,
1041
+ subtree: true,
1042
+ attributes: true,
1043
+ attributeFilter: ['data-slide-loc'],
1044
+ });
881
1045
  };
882
1046
 
883
1047
  replayAll();
884
1048
  observer = new MutationObserver(replayAll);
885
- observer.observe(root, { childList: true, subtree: true });
1049
+ observer.observe(root, {
1050
+ childList: true,
1051
+ subtree: true,
1052
+ attributes: true,
1053
+ attributeFilter: ['data-slide-loc'],
1054
+ });
886
1055
  return () => observer?.disconnect();
887
- }, []);
1056
+ }, [pageIndex, slideId]);
888
1057
 
889
1058
  useEffect(() => {
890
1059
  void pageIndex;
891
1060
  setSelected(null);
892
- }, [pageIndex]);
1061
+ }, [pageIndex, setSelected]);
893
1062
 
894
- // Never clear `selected` on a miss: the observer can fire between an
895
- // "old removed" and "new added" mutation batch, and clearing then would
896
- // drop a selection that's about to reattach on the next fire.
897
1063
  useEffect(() => {
898
- if (!selected) return;
1064
+ if (!selection.length) return;
899
1065
  const root = document.querySelector<HTMLElement>('[data-inspector-root]');
900
1066
  if (!root) return;
901
-
902
1067
  const revalidate = () => {
903
- if (selected.anchor.isConnected) return;
904
- const next = root.querySelector<HTMLElement>(
905
- `[data-slide-loc="${selected.line}:${selected.column}"]`,
906
- );
907
- if (next && next !== selected.anchor) {
908
- setSelected({ ...selected, anchor: next });
909
- }
1068
+ let changed = false;
1069
+ const next = selection.map((target) => {
1070
+ const anchor = target.anchor.isConnected
1071
+ ? target.anchor
1072
+ : (findRememberedTarget(root, target.canvasPath) ??
1073
+ root.querySelector<HTMLElement>(`[data-slide-loc="${target.line}:${target.column}"]`));
1074
+ if (!anchor) return target;
1075
+ const hit = findSlideSource(anchor, slideId, { hostOnly: true });
1076
+ if (
1077
+ !hit ||
1078
+ (hit.anchor === target.anchor && hit.line === target.line && hit.column === target.column)
1079
+ )
1080
+ return target;
1081
+ changed = true;
1082
+ return rememberTarget(hit);
1083
+ });
1084
+ if (changed) setSelection(next);
910
1085
  };
911
-
912
1086
  revalidate();
913
1087
  const observer = new MutationObserver(revalidate);
914
- observer.observe(root, { childList: true, subtree: true });
1088
+ observer.observe(root, {
1089
+ childList: true,
1090
+ subtree: true,
1091
+ attributes: true,
1092
+ attributeFilter: ['data-slide-loc'],
1093
+ });
915
1094
  return () => observer.disconnect();
916
- }, [selected]);
1095
+ }, [selection, setSelection, slideId]);
917
1096
 
918
1097
  const toggle = useCallback(() => {
919
- setActive((a) => {
920
- if (a) setSelected(null);
921
- return !a;
922
- });
923
- }, []);
1098
+ if (active) {
1099
+ setSelected(null);
1100
+ setInlineEdit(null);
1101
+ }
1102
+ setActive(!active);
1103
+ }, [active, setSelected]);
1104
+
1105
+ const togglePanel = useCallback(() => {
1106
+ setPanelOpen(!active || panelHidden || !panelOpen);
1107
+ setActive(true);
1108
+ onPanelOpen?.();
1109
+ }, [active, panelHidden, panelOpen, onPanelOpen]);
924
1110
 
925
1111
  const cancel = useCallback(() => {
926
- setActive(false);
927
1112
  setSelected(null);
928
- }, []);
1113
+ }, [setSelected]);
929
1114
 
930
1115
  const inlineEditSessionRef = useRef(0);
931
- const startInlineEdit = useCallback((target: InlineEditTarget) => {
932
- setSelected({ line: target.line, column: target.column, anchor: target.anchor });
933
- setInlineEdit({ ...target, session: ++inlineEditSessionRef.current });
934
- }, []);
1116
+ const startInlineEdit = useCallback(
1117
+ (target: InlineEditTarget) => {
1118
+ inlineBaselinesRef.current.set(target.anchor, {
1119
+ text: readEditableText(target.anchor),
1120
+ html: captureTextDom(target.anchor),
1121
+ });
1122
+ setInlineSelection(null);
1123
+ setSelection([{ line: target.line, column: target.column, anchor: target.anchor }]);
1124
+ setInlineEdit({ ...target, session: ++inlineEditSessionRef.current });
1125
+ },
1126
+ [setSelection],
1127
+ );
935
1128
 
936
1129
  const stopInlineEdit = useCallback(() => {
937
1130
  setInlineEdit(null);
1131
+ setInlineSelection(null);
938
1132
  }, []);
939
1133
 
940
1134
  // Deselecting, selecting another element, or an HMR anchor swap all end
941
1135
  // the inline session — the contenteditable node is gone or no longer the
942
1136
  // selection's anchor.
943
1137
  useEffect(() => {
944
- if (inlineEdit && selected?.anchor !== inlineEdit.anchor) setInlineEdit(null);
945
- }, [selected, inlineEdit]);
1138
+ if (inlineEdit && selected?.anchor !== inlineEdit.anchor) stopInlineEdit();
1139
+ }, [selected, inlineEdit, stopInlineEdit]);
946
1140
 
947
1141
  const openReplace = useCallback((anchor: HTMLElement) => {
948
1142
  const loc = anchor.dataset.slideLoc;
@@ -957,13 +1151,24 @@ export function InspectorProvider({
957
1151
  useEffect(() => {
958
1152
  if (import.meta.env.PROD) return;
959
1153
  const onKey = (e: KeyboardEvent) => {
960
- if (isTypingTarget(e.target)) return;
1154
+ if (
1155
+ e.defaultPrevented ||
1156
+ isShortcutControlTarget(e.target) ||
1157
+ isTypingTarget(e.target) ||
1158
+ e.isComposing ||
1159
+ e.keyCode === 229 ||
1160
+ e.metaKey ||
1161
+ e.ctrlKey ||
1162
+ e.altKey
1163
+ )
1164
+ return;
961
1165
  if (e.key !== 'i' && e.key !== 'I') return;
962
- toggle();
1166
+ e.preventDefault();
1167
+ togglePanel();
963
1168
  };
964
1169
  window.addEventListener('keydown', onKey);
965
1170
  return () => window.removeEventListener('keydown', onKey);
966
- }, [toggle]);
1171
+ }, [togglePanel]);
967
1172
 
968
1173
  const openCrop = useCallback((anchor: HTMLImageElement) => {
969
1174
  const loc = anchor.dataset.slideLoc;
@@ -991,14 +1196,25 @@ export function InspectorProvider({
991
1196
  slideId,
992
1197
  active,
993
1198
  toggle,
1199
+ panelOpen,
1200
+ panelHidden,
1201
+ togglePanel,
994
1202
  cancel,
995
1203
  comments,
996
1204
  error,
997
1205
  add,
998
1206
  remove,
1207
+ selection,
1208
+ setSelection,
1209
+ bufferBatch,
1210
+ visual,
999
1211
  selected,
1000
1212
  setSelected,
1001
1213
  inlineEdit,
1214
+ inlineSelection,
1215
+ setInlineSelection,
1216
+ registerInlineStyle,
1217
+ applyInlineStyle,
1002
1218
  startInlineEdit,
1003
1219
  stopInlineEdit,
1004
1220
  opsVersion,
@@ -1015,13 +1231,24 @@ export function InspectorProvider({
1015
1231
  slideId,
1016
1232
  active,
1017
1233
  toggle,
1234
+ panelOpen,
1235
+ panelHidden,
1236
+ togglePanel,
1018
1237
  cancel,
1019
1238
  comments,
1020
1239
  error,
1021
1240
  add,
1022
1241
  remove,
1242
+ selection,
1243
+ setSelection,
1244
+ setSelected,
1245
+ bufferBatch,
1246
+ visual,
1023
1247
  selected,
1024
1248
  inlineEdit,
1249
+ inlineSelection,
1250
+ registerInlineStyle,
1251
+ applyInlineStyle,
1025
1252
  startInlineEdit,
1026
1253
  stopInlineEdit,
1027
1254
  opsVersion,
@@ -1165,23 +1392,67 @@ function parsePercent(s: string, fallback: number): number {
1165
1392
  return fallback;
1166
1393
  }
1167
1394
 
1168
- export function InspectToggleButton() {
1395
+ export function InspectModeSwitcher() {
1169
1396
  const t = useLocale();
1170
1397
  const { active, toggle } = useInspector();
1171
1398
  if (import.meta.env.PROD) return null;
1399
+ return (
1400
+ <ToggleGroup
1401
+ size="sm"
1402
+ spacing={1}
1403
+ value={[active ? 'edit' : 'preview']}
1404
+ onValueChange={(value) => {
1405
+ const next = value[0];
1406
+ if (next && (next === 'edit') !== active) toggle();
1407
+ }}
1408
+ aria-label={`${t.inspector.previewMode} / ${t.inspector.editMode}`}
1409
+ data-inspector-ui
1410
+ className="relative isolate h-8 gap-0 rounded-lg border border-border/70 bg-muted/70 p-0.5"
1411
+ >
1412
+ <IconSwitcherIndicator index={active ? 1 : 0} />
1413
+ <ToggleGroupItem
1414
+ value="preview"
1415
+ title={t.inspector.previewMode}
1416
+ aria-label={t.inspector.previewMode}
1417
+ onClick={(event) => {
1418
+ if (event.detail > 0) event.currentTarget.blur();
1419
+ }}
1420
+ className="relative z-10 h-full w-8 rounded-md px-0 text-muted-foreground hover:bg-transparent data-pressed:bg-transparent data-pressed:text-foreground data-pressed:shadow-none"
1421
+ >
1422
+ <Eye />
1423
+ </ToggleGroupItem>
1424
+ <ToggleGroupItem
1425
+ value="edit"
1426
+ title={t.inspector.editMode}
1427
+ aria-label={t.inspector.editMode}
1428
+ onClick={(event) => {
1429
+ if (event.detail > 0) event.currentTarget.blur();
1430
+ }}
1431
+ className="relative z-10 h-full w-8 rounded-md px-0 text-muted-foreground hover:bg-transparent data-pressed:bg-transparent data-pressed:text-foreground data-pressed:shadow-none"
1432
+ >
1433
+ <Pencil />
1434
+ </ToggleGroupItem>
1435
+ </ToggleGroup>
1436
+ );
1437
+ }
1438
+
1439
+ export function InspectPanelButton() {
1440
+ const t = useLocale();
1441
+ const { active, panelOpen, panelHidden, togglePanel } = useInspector();
1442
+ if (import.meta.env.PROD) return null;
1443
+ const pressed = active && panelOpen && !panelHidden;
1172
1444
  return (
1173
1445
  <Button
1174
1446
  size="sm"
1175
- variant={active ? 'default' : 'ghost'}
1176
- onClick={toggle}
1447
+ variant={pressed ? 'secondary' : 'ghost'}
1448
+ onClick={togglePanel}
1449
+ aria-pressed={pressed}
1450
+ title={t.inspector.format}
1451
+ aria-label={t.inspector.format}
1177
1452
  data-inspector-ui
1178
- title={t.inspector.inspect}
1179
1453
  >
1180
- <Crosshair className="size-3.5" />
1181
- <span className="hidden md:inline">{t.inspector.inspect}</span>
1182
- <kbd className="ml-1 hidden rounded-[3px] bg-foreground/10 px-1 font-mono text-[9.5px] tracking-[0.04em] md:inline">
1183
- I
1184
- </kbd>
1454
+ <PanelRight className="size-3.5" />
1455
+ <span className="hidden md:inline">{t.inspector.format}</span>
1185
1456
  </Button>
1186
1457
  );
1187
1458
  }