@open-slide/core 2.3.2 → 2.4.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 (85) hide show
  1. package/dist/{build-8lRsgsO4.js → build-D7GwYl8d.js} +1 -1
  2. package/dist/cli/bin.js +4 -4
  3. package/dist/{config-DJ8ZOe7C.d.ts → config-CfhtJxQH.d.ts} +1 -1
  4. package/dist/{config-D2Mq1vSW.js → config-D4uPk_tM.js} +383 -138
  5. package/dist/{dev-BvefEp1Q.js → dev-DyCDMbHB.js} +10 -10
  6. package/dist/index.d.ts +2 -2
  7. package/dist/index.js +9 -1
  8. package/dist/locale/index.d.ts +1 -1
  9. package/dist/locale/index.js +1 -1
  10. package/dist/{preview-D8ognobz.js → preview-DjIFvt0K.js} +1 -1
  11. package/dist/{types-tdaXSyah.d.ts → types-ZfArJF0d.d.ts} +20 -13
  12. package/dist/{update-BivdNgL3.js → update-BKhRM7o4.js} +30 -3
  13. package/dist/vite/index.d.ts +1 -1
  14. package/dist/vite/index.js +1 -1
  15. package/dist/{zh-tw-DXcqQTrA.js → zh-tw-D7LfGVmA.js} +215 -65
  16. package/package.json +4 -5
  17. package/src/agent/provider.ts +8 -1
  18. package/src/agent/types.ts +17 -2
  19. package/src/app/app.tsx +2 -0
  20. package/src/app/components/agent/agent-markdown.tsx +3 -6
  21. package/src/app/components/agent/agent-panel.tsx +36 -258
  22. package/src/app/components/agent/agent-presence.tsx +1 -1
  23. package/src/app/components/agent/composer.tsx +52 -24
  24. package/src/app/components/agent/effort-slider.tsx +172 -0
  25. package/src/app/components/agent/model-menu.tsx +170 -0
  26. package/src/app/components/agent/permission-menu.tsx +88 -0
  27. package/src/app/components/agent/transcript.tsx +23 -31
  28. package/src/app/components/command/home-command-menu.tsx +4 -1
  29. package/src/app/components/command/slide-command-menu.tsx +4 -1
  30. package/src/app/components/export-progress-toast.tsx +3 -1
  31. package/src/app/components/inspector/asset-picker-dialog.tsx +1 -1
  32. package/src/app/components/inspector/comment-layer.tsx +3 -3
  33. package/src/app/components/inspector/inline-text-editor.tsx +1 -12
  34. package/src/app/components/inspector/inspect-overlay.tsx +9 -1
  35. package/src/app/components/inspector/inspector-panel.tsx +8 -35
  36. package/src/app/components/inspector/inspector-provider.tsx +177 -36
  37. package/src/app/components/inspector/page-panel.tsx +270 -0
  38. package/src/app/components/language-toggle.tsx +13 -11
  39. package/src/app/components/note-markdown.test.tsx +12 -6
  40. package/src/app/components/note-markdown.tsx +16 -21
  41. package/src/app/components/overview-grid.tsx +3 -3
  42. package/src/app/components/panel/editor-sidebar.tsx +43 -8
  43. package/src/app/components/panel/panel-shell.tsx +9 -5
  44. package/src/app/components/panel/save-card.tsx +1 -1
  45. package/src/app/components/sidebar/folder-item.tsx +4 -1
  46. package/src/app/components/sidebar/sidebar.tsx +11 -8
  47. package/src/app/components/style-panel/design-provider.tsx +48 -11
  48. package/src/app/components/style-panel/use-design.ts +6 -1
  49. package/src/app/components/theme-toggle.tsx +16 -22
  50. package/src/app/components/thumbnail-rail.tsx +68 -49
  51. package/src/app/components/ui/context-menu.tsx +9 -10
  52. package/src/app/components/ui/dialog.tsx +2 -4
  53. package/src/app/components/ui/dropdown-menu.tsx +9 -10
  54. package/src/app/components/ui/popover.tsx +1 -1
  55. package/src/app/components/ui/select.tsx +2 -2
  56. package/src/app/components/ui/sonner.tsx +2 -2
  57. package/src/app/index.html +7 -0
  58. package/src/app/lib/agent/use-agent.ts +131 -37
  59. package/src/app/lib/desktop-host.ts +31 -0
  60. package/src/app/lib/desktop-routes.test.ts +54 -0
  61. package/src/app/lib/desktop-routes.ts +22 -0
  62. package/src/app/lib/desktop.ts +106 -0
  63. package/src/app/lib/export-pdf.ts +15 -7
  64. package/src/app/lib/inspector/color.ts +51 -0
  65. package/src/app/lib/inspector/fiber.ts +6 -0
  66. package/src/app/lib/inspector/use-editor.ts +2 -1
  67. package/src/app/lib/inspector/use-notes.test.ts +209 -0
  68. package/src/app/lib/inspector/use-notes.ts +331 -57
  69. package/src/app/lib/inspector/use-visual-editor.ts +9 -1
  70. package/src/app/lib/locale-store.ts +14 -2
  71. package/src/app/lib/note-markdown.test.ts +69 -5
  72. package/src/app/lib/note-markdown.ts +97 -22
  73. package/src/app/lib/transition.test.ts +84 -1
  74. package/src/app/lib/transition.ts +43 -0
  75. package/src/app/lib/unsaved.test.ts +253 -0
  76. package/src/app/lib/unsaved.ts +155 -0
  77. package/src/app/routes/home.tsx +1 -1
  78. package/src/app/routes/slide.tsx +114 -117
  79. package/src/app/styles.css +421 -1
  80. package/src/locale/en.ts +40 -15
  81. package/src/locale/es.ts +40 -17
  82. package/src/locale/ja.ts +40 -15
  83. package/src/locale/types.ts +19 -14
  84. package/src/locale/zh-cn.ts +40 -14
  85. package/src/locale/zh-tw.ts +40 -14
@@ -0,0 +1,209 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2
+ import { settleUnsaved, unsavedStatus } from '@/lib/unsaved';
3
+ import { cachedNotes, changeNotesPages, detachNotes } from './use-notes';
4
+
5
+ type Call = {
6
+ url: string;
7
+ body: { index?: number; text?: string; layout?: string } | undefined;
8
+ reply: (ok: boolean | Response) => void;
9
+ };
10
+
11
+ let calls: Call[] = [];
12
+ let slide = 0;
13
+ let slideId = '';
14
+ let layout = 'L0';
15
+
16
+ const tick = () => new Promise((resolve) => setTimeout(resolve, 0));
17
+ const noteCalls = () => calls.filter((call) => call.url === '/__notes');
18
+
19
+ beforeEach(() => {
20
+ calls = [];
21
+ slideId = `deck-${++slide}`;
22
+ layout = 'L0';
23
+ vi.stubGlobal('fetch', (url: string, init?: RequestInit) => {
24
+ if (url.startsWith('/__notes?')) {
25
+ return Promise.resolve(new Response(JSON.stringify({ layout }), { status: 200 }));
26
+ }
27
+ return new Promise<Response>((resolve, reject) => {
28
+ init?.signal?.addEventListener('abort', () =>
29
+ reject(Object.assign(new Error('aborted'), { name: 'AbortError' })),
30
+ );
31
+ calls.push({
32
+ url,
33
+ body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined,
34
+ reply: (ok) =>
35
+ resolve(
36
+ ok instanceof Response
37
+ ? ok
38
+ : new Response(JSON.stringify(ok ? { ok: true } : { error: 'boom' }), {
39
+ status: ok ? 200 : 500,
40
+ }),
41
+ ),
42
+ });
43
+ });
44
+ });
45
+ });
46
+
47
+ afterEach(async () => {
48
+ await settleUnsaved('abandon');
49
+ vi.unstubAllGlobals();
50
+ });
51
+
52
+ async function failDetached(index: number, text: string) {
53
+ detachNotes({ slideId, index }, text);
54
+ await tick();
55
+ noteCalls().at(-1)?.reply(false);
56
+ await tick();
57
+ }
58
+
59
+ function change(order: number[], outcome: 'ok' | 'failed' | 'lost' = 'ok') {
60
+ return changeNotesPages(slideId, () => ({
61
+ order,
62
+ apply: async () => {
63
+ if (outcome !== 'failed') layout = 'L1';
64
+ if (outcome !== 'ok') throw new Error('page op failed');
65
+ return layout;
66
+ },
67
+ revert: () => {},
68
+ }));
69
+ }
70
+
71
+ async function retry() {
72
+ const before = noteCalls().length;
73
+ const settled = settleUnsaved('save');
74
+ await tick();
75
+ const sent = noteCalls().slice(before);
76
+ for (const call of sent) call.reply(true);
77
+ await settled;
78
+ return sent.map((call) => call.body);
79
+ }
80
+
81
+ describe('notes across page changes', () => {
82
+ it('retries a failed write on the page it was left on after a reorder', async () => {
83
+ await failDetached(1, 'second');
84
+ await change([1, 0]);
85
+ expect(cachedNotes(slideId, 0)).toBe('second');
86
+ expect(cachedNotes(slideId, 1)).toBeUndefined();
87
+ expect(await retry()).toEqual([{ slideId, index: 0, text: 'second', layout: 'L1' }]);
88
+ });
89
+
90
+ it('drops a failed write whose page was deleted', async () => {
91
+ await failDetached(1, 'gone');
92
+ await change([0, 2]);
93
+ expect(cachedNotes(slideId, 1)).toBeUndefined();
94
+ expect(unsavedStatus().pending).toBe(false);
95
+ expect(await retry()).toEqual([]);
96
+ });
97
+
98
+ it('shifts later pages down after a delete', async () => {
99
+ await failDetached(2, 'third');
100
+ await change([0, 2]);
101
+ expect(await retry()).toEqual([{ slideId, index: 1, text: 'third', layout: 'L1' }]);
102
+ });
103
+
104
+ it('copies saved notes to a duplicated page and shifts later retries', async () => {
105
+ detachNotes({ slideId, index: 0 }, 'first');
106
+ await tick();
107
+ noteCalls()[0].reply(true);
108
+ await tick();
109
+ await failDetached(1, 'second');
110
+
111
+ await change([0, 0, 1]);
112
+ expect(cachedNotes(slideId, 0)).toBe('first');
113
+ expect(cachedNotes(slideId, 1)).toBe('first');
114
+ expect(cachedNotes(slideId, 2)).toBe('second');
115
+ expect(await retry()).toEqual([{ slideId, index: 2, text: 'second', layout: 'L1' }]);
116
+ });
117
+
118
+ it('restores retries and cached notes when the page change fails', async () => {
119
+ detachNotes({ slideId, index: 0 }, 'kept');
120
+ await tick();
121
+ noteCalls()[0].reply(true);
122
+ await tick();
123
+ await failDetached(1, 'second');
124
+
125
+ await expect(change([0], 'failed')).rejects.toThrow('page op failed');
126
+ expect(cachedNotes(slideId, 0)).toBe('kept');
127
+ expect(cachedNotes(slideId, 1)).toBe('second');
128
+ expect(await retry()).toEqual([{ slideId, index: 1, text: 'second', layout: 'L0' }]);
129
+ });
130
+
131
+ it('keeps retries on the moved pages when a failed page change landed anyway', async () => {
132
+ await failDetached(1, 'second');
133
+ expect(await change([1, 0], 'lost')).toBe(true);
134
+ expect(cachedNotes(slideId, 0)).toBe('second');
135
+ expect(await retry()).toEqual([{ slideId, index: 0, text: 'second', layout: 'L1' }]);
136
+ });
137
+
138
+ it('sends a write held by a page change against the changed page list', async () => {
139
+ detachNotes({ slideId, index: 0 }, 'first');
140
+ await tick();
141
+ const stale = noteCalls()[0];
142
+ expect(stale.body?.layout).toBe('L0');
143
+ stale.reply(true);
144
+ await change([1, 0]);
145
+ detachNotes({ slideId, index: 1 }, 'again');
146
+ await tick();
147
+ expect(noteCalls()[1].body).toEqual({ slideId, index: 1, text: 'again', layout: 'L1' });
148
+ });
149
+
150
+ it('keeps text unsaved when the server refuses it for a changed page list', async () => {
151
+ detachNotes({ slideId, index: 0 }, 'typed');
152
+ await tick();
153
+ noteCalls()
154
+ .at(-1)
155
+ ?.reply(
156
+ new Response(JSON.stringify({ error: 'pages changed', layout: 'L9' }), { status: 409 }),
157
+ );
158
+ await tick();
159
+ expect(unsavedStatus().pending).toBe(true);
160
+ expect(await retry()).toEqual([{ slideId, index: 0, text: 'typed', layout: 'L9' }]);
161
+ });
162
+
163
+ it('waits for a write in flight before planning the change', async () => {
164
+ detachNotes({ slideId, index: 1 }, 'landing');
165
+ await tick();
166
+ const plan = vi.fn(() => ({ order: [1, 0], apply: async () => layout, revert: () => {} }));
167
+ const changed = changeNotesPages(slideId, plan);
168
+ await tick();
169
+ expect(plan).not.toHaveBeenCalled();
170
+
171
+ noteCalls()[0].reply(true);
172
+ expect(await changed).toBe(true);
173
+ expect(plan).toHaveBeenCalledOnce();
174
+ expect(cachedNotes(slideId, 0)).toBe('landing');
175
+ });
176
+
177
+ it('holds a write made during a page change until it settles', async () => {
178
+ let finish = () => {};
179
+ const first = changeNotesPages(slideId, () => ({
180
+ order: [1, 0],
181
+ apply: () =>
182
+ new Promise<string>((resolve) => {
183
+ finish = () => {
184
+ layout = 'L1';
185
+ resolve(layout);
186
+ };
187
+ }),
188
+ revert: () => {},
189
+ }));
190
+ await tick();
191
+ detachNotes({ slideId, index: 1 }, 'typed');
192
+ const plan = vi.fn(() => ({ order: [1, 0], apply: async () => layout, revert: () => {} }));
193
+ const second = changeNotesPages(slideId, plan);
194
+ await tick();
195
+ expect(noteCalls()).toEqual([]);
196
+
197
+ finish();
198
+ await first;
199
+ await tick();
200
+ expect(noteCalls().map((call) => call.body)).toEqual([
201
+ { slideId, index: 1, text: 'typed', layout: 'L1' },
202
+ ]);
203
+ expect(plan).not.toHaveBeenCalled();
204
+
205
+ noteCalls()[0].reply(true);
206
+ await second;
207
+ expect(cachedNotes(slideId, 0)).toBe('typed');
208
+ });
209
+ });
@@ -1,4 +1,5 @@
1
1
  import { useCallback, useEffect, useRef, useState } from 'react';
2
+ import { forgetWrite, onAbandon, trackWrite, useUnsavedSource } from '@/lib/unsaved';
2
3
 
3
4
  export type NoteSaveStatus =
4
5
  | { kind: 'idle' }
@@ -9,39 +10,279 @@ export type NoteSaveStatus =
9
10
  const DEBOUNCE_MS = 600;
10
11
 
11
12
  type Target = { slideId: string; index: number };
13
+ type Detached = Target & { text: string; seq: number };
14
+ type Editor = { target: { current: Target }; drop: () => void };
15
+ type WriteResult = { kind: 'saved' } | { kind: 'skipped' } | { kind: 'error'; message: string };
12
16
 
13
17
  // HMR is suppressed for our writes, so the cached slide module's `notes`
14
18
  // stays stale across navigation. Cache last-saved text per target so
15
19
  // switching slides and back doesn't surface the old value.
16
20
  const sessionCache = new Map<string, string>();
21
+ // Text left on a page whose write is still landing or failed, shown on return
22
+ // instead of the older text on disk. Each entry is also its tracked write's key,
23
+ // so a retry follows its page when pages move.
24
+ const detached = new Set<Detached>();
25
+ onAbandon(() => detached.clear());
26
+ // Shared by every editor, so a newer write cancels an older one to the same
27
+ // notes even when the editor that started it has unmounted.
28
+ const inflight = new Map<string, { ctl: AbortController }>();
29
+ // Every write from its start, including ones still waiting to send, so a page
30
+ // change can wait for those not held back by another page change.
31
+ const pending = new Set<{ slideId: string; settled: Promise<unknown> }>();
32
+ // Targets of writes held back by a page change; moved with the pages before they send.
33
+ const waiting = new Set<Target>();
34
+ const editors = new Set<Editor>();
35
+ const pageChanges = new Map<string, Promise<void>>();
36
+ // The server's fingerprint of each deck's page list that note indices currently
37
+ // refer to. Saves carry it, so one that reaches the server after the pages
38
+ // moved, such as an aborted request, is refused instead of hitting another page.
39
+ const layouts = new Map<string, string>();
40
+ let pageChangeCount = 0;
41
+ let seq = 0;
42
+
17
43
  const cacheKey = (slideId: string, index: number) => `${slideId}:${index}`;
44
+ const sameTarget = (a: Target, b: Target) => a.slideId === b.slideId && a.index === b.index;
45
+
46
+ function findDetached(target: Target): Detached | undefined {
47
+ for (const entry of detached) if (sameTarget(entry, target)) return entry;
48
+ return undefined;
49
+ }
50
+
51
+ function writing(target: Target): boolean {
52
+ if (inflight.has(cacheKey(target.slideId, target.index))) return true;
53
+ for (const slot of waiting) if (sameTarget(slot, target)) return true;
54
+ return false;
55
+ }
56
+
57
+ export function cachedNotes(slideId: string, index: number): string | undefined {
58
+ return findDetached({ slideId, index })?.text ?? sessionCache.get(cacheKey(slideId, index));
59
+ }
60
+
61
+ const errorMessage = (err: unknown) => String((err as Error).message ?? err);
62
+
63
+ async function fetchLayout(slideId: string): Promise<string> {
64
+ const res = await fetch(`/__notes?slideId=${encodeURIComponent(slideId)}`);
65
+ const body = (await res.json().catch(() => ({}))) as { layout?: unknown; error?: string };
66
+ if (!res.ok || typeof body.layout !== 'string') {
67
+ throw new Error(body.error ?? `GET /__notes → ${res.status}`);
68
+ }
69
+ return body.layout;
70
+ }
71
+
72
+ async function settledLayout(slideId: string): Promise<string> {
73
+ for (;;) {
74
+ const change = pageChanges.get(slideId);
75
+ if (change) {
76
+ await change;
77
+ continue;
78
+ }
79
+ const known = layouts.get(slideId);
80
+ if (known !== undefined) return known;
81
+ const count = pageChangeCount;
82
+ const layout = await fetchLayout(slideId);
83
+ if (pageChangeCount === count) layouts.set(slideId, layout);
84
+ }
85
+ }
86
+
87
+ // Resolves to the failure, or a skip once a newer write to the same notes took
88
+ // over or the page was deleted; writes to other notes are never cut off.
89
+ function writeNotes(target: Target, text: string): Promise<WriteResult> {
90
+ const write = { slideId: target.slideId, settled: sendNotes(target, text) };
91
+ pending.add(write);
92
+ void write.settled.then(() => pending.delete(write));
93
+ return write.settled;
94
+ }
95
+
96
+ async function sendNotes(target: Target, text: string): Promise<WriteResult> {
97
+ const slot = { ...target };
98
+ waiting.add(slot);
99
+ let layout: string;
100
+ try {
101
+ layout = await settledLayout(slot.slideId);
102
+ } catch (err) {
103
+ return { kind: 'error', message: errorMessage(err) };
104
+ } finally {
105
+ waiting.delete(slot);
106
+ }
107
+ if (slot.index < 0) return { kind: 'skipped' };
108
+
109
+ const key = cacheKey(slot.slideId, slot.index);
110
+ const startSeq = seq;
111
+ inflight.get(key)?.ctl.abort();
112
+ const ctl = new AbortController();
113
+ const entry = { ctl };
114
+ inflight.set(key, entry);
115
+ try {
116
+ const res = await fetch('/__notes', {
117
+ method: 'PUT',
118
+ headers: { 'content-type': 'application/json' },
119
+ body: JSON.stringify({ slideId: slot.slideId, index: slot.index, text, layout }),
120
+ signal: ctl.signal,
121
+ });
122
+ const body = (await res.json().catch(() => ({}))) as { error?: string; layout?: unknown };
123
+ if (inflight.get(key) !== entry) return { kind: 'skipped' };
124
+ // Refused because the page list changed on disk outside a page change made
125
+ // here; the text stays unsaved and its next save targets the list now on disk.
126
+ if (res.status === 409 && typeof body.layout === 'string') {
127
+ if (layouts.get(slot.slideId) === layout) layouts.set(slot.slideId, body.layout);
128
+ }
129
+ if (!res.ok) throw new Error(body.error ?? `PUT /__notes → ${res.status}`);
130
+ sessionCache.set(key, text);
131
+ for (const left of detached) {
132
+ if (!sameTarget(left, slot) || left.seq > startSeq) continue;
133
+ detached.delete(left);
134
+ forgetWrite(left);
135
+ }
136
+ return { kind: 'saved' };
137
+ } catch (err) {
138
+ if ((err as { name?: string }).name === 'AbortError') return { kind: 'skipped' };
139
+ return { kind: 'error', message: errorMessage(err) };
140
+ } finally {
141
+ if (inflight.get(key) === entry) inflight.delete(key);
142
+ }
143
+ }
144
+
145
+ // For text whose editor has moved on; a failed write is retried until it lands.
146
+ export function detachNotes(target: Target, text: string): void {
147
+ let entry = findDetached(target);
148
+ if (entry) {
149
+ entry.text = text;
150
+ entry.seq = ++seq;
151
+ } else {
152
+ entry = { ...target, text, seq: ++seq };
153
+ detached.add(entry);
154
+ }
155
+ const owned = entry;
156
+ trackWrite(owned, async () => {
157
+ const result = await writeNotes(owned, owned.text);
158
+ if (result.kind === 'error') throw new Error(result.message);
159
+ });
160
+ }
161
+
162
+ // `order[i]` is the original page index that lands at new position `i`; a
163
+ // duplicated page appears twice and a deleted one not at all.
164
+ function movePages(slideId: string, order: number[]) {
165
+ const moved = new Map<number, number>();
166
+ order.forEach((from, to) => {
167
+ if (!moved.has(from)) moved.set(from, to);
168
+ });
169
+
170
+ for (const editor of editors) {
171
+ const target = editor.target.current;
172
+ if (target.slideId === slideId && !moved.has(target.index)) editor.drop();
173
+ }
174
+
175
+ const prefix = `${slideId}:`;
176
+ const cached = new Map<number, string>();
177
+ for (const [key, text] of sessionCache) {
178
+ if (!key.startsWith(prefix)) continue;
179
+ cached.set(Number(key.slice(prefix.length)), text);
180
+ sessionCache.delete(key);
181
+ }
182
+ order.forEach((from, to) => {
183
+ const text = cached.get(from);
184
+ if (text !== undefined) sessionCache.set(cacheKey(slideId, to), text);
185
+ });
186
+
187
+ const targets = [...[...editors].map((editor) => editor.target.current), ...detached, ...waiting];
188
+ const removed: [Target, number][] = [];
189
+ for (const target of targets) {
190
+ if (target.slideId !== slideId || target.index < 0) continue;
191
+ const to = moved.get(target.index);
192
+ if (to === undefined) removed.push([target, target.index]);
193
+ target.index = to ?? -1;
194
+ }
195
+
196
+ return {
197
+ commit() {
198
+ for (const entry of detached) {
199
+ if (entry.slideId !== slideId || entry.index >= 0) continue;
200
+ detached.delete(entry);
201
+ forgetWrite(entry);
202
+ }
203
+ },
204
+ rollback() {
205
+ for (const [key] of sessionCache) if (key.startsWith(prefix)) sessionCache.delete(key);
206
+ for (const [index, text] of cached) sessionCache.set(cacheKey(slideId, index), text);
207
+ const current = [
208
+ ...[...editors].map((editor) => editor.target.current),
209
+ ...detached,
210
+ ...waiting,
211
+ ];
212
+ for (const target of current) {
213
+ if (target.slideId === slideId && target.index >= 0) target.index = order[target.index];
214
+ }
215
+ for (const [target, index] of removed) target.index = index;
216
+ },
217
+ };
218
+ }
219
+
220
+ export type NotesPageChange = {
221
+ order: number[];
222
+ // Resolves to the server's page-list fingerprint after the change.
223
+ apply: () => Promise<string | undefined>;
224
+ revert: () => void;
225
+ };
18
226
 
19
- // Remap the per-target cache after a reorder. `order[i]` is the original
20
- // page index that lands at new position `i`, matching the contract used by
21
- // the `/__slides/:id/reorder` endpoint.
22
- export function remapNotesSessionCacheAfterReorder(slideId: string, order: number[]): void {
23
- const prev = new Map<number, string>();
24
- for (let i = 0; i < order.length; i++) {
25
- const cached = sessionCache.get(cacheKey(slideId, i));
26
- if (cached !== undefined) prev.set(i, cached);
27
- sessionCache.delete(cacheKey(slideId, i));
227
+ // Note writes are bound to a page index, so a page change waits for the ones in
228
+ // flight, holds back new ones until it settles, and moves cached text, unsaved
229
+ // editors and failed retries along with their pages. `plan` runs once nothing is
230
+ // in flight; its `apply` makes the change, and if it throws, the notes and
231
+ // `revert` roll back unless the server's page list shows the change landed.
232
+ export async function changeNotesPages(
233
+ slideId: string,
234
+ plan: () => NotesPageChange | null,
235
+ ): Promise<boolean> {
236
+ for (;;) {
237
+ const change = pageChanges.get(slideId);
238
+ if (change) {
239
+ await change;
240
+ continue;
241
+ }
242
+ const writes = [...pending].filter((write) => write.slideId === slideId);
243
+ if (writes.length === 0) break;
244
+ await Promise.all(writes.map((write) => write.settled));
28
245
  }
29
- for (let newIdx = 0; newIdx < order.length; newIdx++) {
30
- const oldIdx = order[newIdx];
31
- const text = prev.get(oldIdx);
32
- if (text !== undefined) sessionCache.set(cacheKey(slideId, newIdx), text);
246
+
247
+ let done = () => {};
248
+ pageChanges.set(slideId, new Promise<void>((resolve) => (done = resolve)));
249
+ pageChangeCount++;
250
+ try {
251
+ const before = await fetchLayout(slideId);
252
+ layouts.set(slideId, before);
253
+ const next = plan();
254
+ if (!next) return false;
255
+ const moved = movePages(slideId, next.order);
256
+ let after: string | undefined;
257
+ try {
258
+ after = await next.apply();
259
+ } catch (err) {
260
+ after = await fetchLayout(slideId).catch(() => before);
261
+ if (after === before) {
262
+ moved.rollback();
263
+ next.revert();
264
+ throw err;
265
+ }
266
+ }
267
+ moved.commit();
268
+ if (after === undefined) layouts.delete(slideId);
269
+ else layouts.set(slideId, after);
270
+ return true;
271
+ } finally {
272
+ pageChanges.delete(slideId);
273
+ done();
33
274
  }
34
275
  }
35
276
 
36
277
  export function useNotes(slideId: string, index: number, initial: string | undefined) {
37
- const initialText = sessionCache.get(cacheKey(slideId, index)) ?? initial ?? '';
278
+ const initialText = cachedNotes(slideId, index) ?? initial ?? '';
38
279
  const [value, setValueState] = useState(initialText);
39
280
  const [status, setStatus] = useState<NoteSaveStatus>({ kind: 'idle' });
281
+ const [dropped, setDropped] = useState(0);
40
282
 
41
283
  const lastSavedRef = useRef(initialText);
42
284
  const dirtyRef = useRef(false);
43
285
  const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
44
- const inflightRef = useRef<AbortController | null>(null);
45
286
  const targetRef = useRef<Target>({ slideId, index });
46
287
  const valueRef = useRef(value);
47
288
  valueRef.current = value;
@@ -53,69 +294,102 @@ export function useNotes(slideId: string, index: number, initial: string | undef
53
294
  }
54
295
  }, []);
55
296
 
56
- const persist = useCallback(async (target: Target, text: string) => {
57
- inflightRef.current?.abort();
58
- const ctl = new AbortController();
59
- inflightRef.current = ctl;
60
- setStatus({ kind: 'saving' });
61
- try {
62
- const res = await fetch('/__notes', {
63
- method: 'PUT',
64
- headers: { 'content-type': 'application/json' },
65
- body: JSON.stringify({ slideId: target.slideId, index: target.index, text }),
66
- signal: ctl.signal,
67
- });
68
- const body = (await res.json().catch(() => ({}))) as { error?: string };
69
- if (!res.ok) throw new Error(body.error ?? `PUT /__notes → ${res.status}`);
70
- sessionCache.set(cacheKey(target.slideId, target.index), text);
71
- if (inflightRef.current !== ctl) return;
72
- lastSavedRef.current = text;
73
- dirtyRef.current = false;
74
- setStatus({ kind: 'saved' });
75
- } catch (err) {
76
- if ((err as { name?: string }).name === 'AbortError') return;
77
- setStatus({ kind: 'error', message: String((err as Error).message ?? err) });
78
- } finally {
79
- if (inflightRef.current === ctl) inflightRef.current = null;
297
+ const persist = useCallback(async (target: Target, text: string): Promise<string | null> => {
298
+ const showing = () => sameTarget(targetRef.current, target);
299
+ if (showing()) setStatus({ kind: 'saving' });
300
+ const result = await writeNotes(target, text);
301
+ if (result.kind === 'skipped') return null;
302
+ if (result.kind === 'error') {
303
+ if (showing()) setStatus({ kind: 'error', message: result.message });
304
+ return result.message;
80
305
  }
306
+ if (!showing()) return null;
307
+ lastSavedRef.current = text;
308
+ // Text typed while this was in flight still waits on its own save.
309
+ dirtyRef.current = valueRef.current !== text;
310
+ setStatus({ kind: 'saved' });
311
+ return null;
81
312
  }, []);
82
313
 
83
- const flush = useCallback(async () => {
314
+ const persistOrThrow = useCallback(
315
+ async (target: Target, text: string) => {
316
+ const error = await persist(target, text);
317
+ if (error) throw new Error(error);
318
+ },
319
+ [persist],
320
+ );
321
+
322
+ // Even text put back to the last save goes out, since a write still in flight may
323
+ // land something else.
324
+ const detachDirty = useCallback(() => {
84
325
  cancelTimer();
85
326
  if (!dirtyRef.current) return;
86
- const target = targetRef.current;
87
- await persist(target, valueRef.current);
88
- }, [cancelTimer, persist]);
327
+ dirtyRef.current = false;
328
+ detachNotes(targetRef.current, valueRef.current);
329
+ }, [cancelTimer]);
89
330
 
90
- // When the (slideId, index) target changes, flush pending edits for the
91
- // previous target before adopting the new initial text.
331
+ // biome-ignore lint/correctness/useExhaustiveDependencies: `dropped` re-runs this when the page under this editor is deleted, since its props may not change
92
332
  useEffect(() => {
93
- const prev = targetRef.current;
94
- const targetChanged = prev.slideId !== slideId || prev.index !== index;
95
- if (targetChanged && dirtyRef.current) {
96
- cancelTimer();
97
- const pending = valueRef.current;
98
- if (lastSavedRef.current !== pending) void persist(prev, pending);
333
+ const targetChanged = !sameTarget(targetRef.current, { slideId, index });
334
+ if (targetChanged) {
335
+ detachDirty();
336
+ targetRef.current = { slideId, index };
337
+ } else if (initialText === lastSavedRef.current) {
338
+ // A save updates the cache `initialText` reads; adopting that echo would
339
+ // drop text typed while the save was in flight.
340
+ return;
99
341
  }
100
- targetRef.current = { slideId, index };
101
342
  cancelTimer();
102
343
  setValueState(initialText);
103
344
  lastSavedRef.current = initialText;
104
345
  dirtyRef.current = false;
105
346
  setStatus({ kind: 'idle' });
106
- }, [slideId, index, initialText, persist, cancelTimer]);
347
+ }, [slideId, index, initialText, dropped, detachDirty, cancelTimer]);
107
348
 
108
349
  useEffect(() => {
350
+ const editor: Editor = {
351
+ target: targetRef,
352
+ drop: () => {
353
+ detachDirty();
354
+ setDropped((n) => n + 1);
355
+ },
356
+ };
357
+ editors.add(editor);
109
358
  return () => {
110
- cancelTimer();
111
- inflightRef.current?.abort();
359
+ editors.delete(editor);
360
+ detachDirty();
112
361
  };
113
- }, [cancelTimer]);
362
+ }, [detachDirty]);
363
+
364
+ const flush = useCallback(async () => {
365
+ cancelTimer();
366
+ if (!dirtyRef.current) return;
367
+ await persist(targetRef.current, valueRef.current);
368
+ }, [cancelTimer, persist]);
369
+
370
+ useUnsavedSource({
371
+ kind: 'autosave',
372
+ dirty: () => dirtyRef.current || writing(targetRef.current),
373
+ save: () => {
374
+ cancelTimer();
375
+ return persistOrThrow(targetRef.current, valueRef.current);
376
+ },
377
+ discard: () => {
378
+ cancelTimer();
379
+ const { slideId: id, index: at } = targetRef.current;
380
+ inflight.get(cacheKey(id, at))?.ctl.abort();
381
+ dirtyRef.current = false;
382
+ setValueState(lastSavedRef.current);
383
+ setStatus({ kind: 'idle' });
384
+ },
385
+ });
114
386
 
115
387
  const setValue = useCallback(
116
388
  (next: string) => {
117
389
  setValueState(next);
118
- dirtyRef.current = next !== lastSavedRef.current;
390
+ valueRef.current = next;
391
+ // Text put back to the last save still goes out after a write in flight lands.
392
+ dirtyRef.current = next !== lastSavedRef.current || writing(targetRef.current);
119
393
  cancelTimer();
120
394
  if (!dirtyRef.current) {
121
395
  setStatus({ kind: 'idle' });
@@ -138,6 +138,7 @@ type Options = {
138
138
  selection: SelectedTarget[];
139
139
  setSelection: (targets: SelectedTarget[]) => void;
140
140
  bufferBatch: (edits: VisualEdit[], coalesceKey?: string) => void;
141
+ removeElements: (targets: SelectedTarget[]) => void;
141
142
  };
142
143
 
143
144
  export function useVisualEditor({
@@ -148,6 +149,7 @@ export function useVisualEditor({
148
149
  selection,
149
150
  setSelection,
150
151
  bufferBatch,
152
+ removeElements,
151
153
  }: Options) {
152
154
  const [snapping, setSnapping] = useState(true);
153
155
  const t = useLocale();
@@ -393,6 +395,12 @@ export function useVisualEditor({
393
395
  return;
394
396
  }
395
397
  if (!selection.length || event.metaKey || event.ctrlKey || event.altKey) return;
398
+ if (event.key === 'Delete' || event.key === 'Backspace') {
399
+ event.preventDefault();
400
+ event.stopImmediatePropagation();
401
+ removeElements(selection);
402
+ return;
403
+ }
396
404
  const vectors: Record<string, { x: number; y: number }> = {
397
405
  ArrowLeft: { x: -1, y: 0 },
398
406
  ArrowRight: { x: 1, y: 0 },
@@ -411,7 +419,7 @@ export function useVisualEditor({
411
419
  };
412
420
  window.addEventListener('keydown', onKey, true);
413
421
  return () => window.removeEventListener('keydown', onKey, true);
414
- }, [active, inlineEditing, committing, selection, move, selectAll]);
422
+ }, [active, inlineEditing, committing, selection, move, selectAll, removeElements]);
415
423
 
416
424
  return useMemo(
417
425
  () => ({