@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
@@ -59,12 +59,24 @@ function getSnapshot(): Locale {
59
59
  return current;
60
60
  }
61
61
 
62
+ function apply(next: Locale): void {
63
+ if (next === current) return;
64
+ current = next;
65
+ for (const listener of listeners) listener();
66
+ }
67
+
62
68
  export function setLocale(id: LocaleId): void {
63
- current = LOCALES[id];
64
69
  try {
65
70
  localStorage.setItem(STORAGE_KEY, id);
66
71
  } catch {}
67
- for (const listener of listeners) listener();
72
+ apply(LOCALES[id]);
73
+ }
74
+
75
+ // Desktop tabs are separate pages on one origin; a pick in one reaches the others through storage.
76
+ if (typeof window !== 'undefined') {
77
+ window.addEventListener('storage', (e) => {
78
+ if (e.key === STORAGE_KEY || e.key === null) apply(readStored());
79
+ });
68
80
  }
69
81
 
70
82
  export function useLocaleValue(): Locale {
@@ -1,7 +1,13 @@
1
1
  import { describe, expect, it } from 'vitest';
2
- import { type NoteInline, parseInline, parseNoteMarkdown } from './note-markdown.ts';
2
+ import {
3
+ type NoteBlock,
4
+ type NoteInline,
5
+ parseInline,
6
+ parseNoteMarkdown,
7
+ } from './note-markdown.ts';
3
8
 
4
9
  const text = (t: string): NoteInline => ({ type: 'text', text: t });
10
+ const item = (content: NoteInline[], children: NoteBlock[] = []) => ({ content, children });
5
11
 
6
12
  describe('parseInline', () => {
7
13
  it('returns plain text untouched', () => {
@@ -90,7 +96,8 @@ describe('parseNoteMarkdown', () => {
90
96
  {
91
97
  type: 'list',
92
98
  ordered: false,
93
- items: [[text('a')], [{ type: 'strong', children: [text('b')] }]],
99
+ start: 1,
100
+ items: [item([text('a')]), item([{ type: 'strong', children: [text('b')] }])],
94
101
  },
95
102
  { type: 'paragraph', lines: [[text('tail')]] },
96
103
  ]);
@@ -98,14 +105,71 @@ describe('parseNoteMarkdown', () => {
98
105
 
99
106
  it('parses ordered lists with dot or paren markers', () => {
100
107
  expect(parseNoteMarkdown('1. a\n2) b')).toEqual([
101
- { type: 'list', ordered: true, items: [[text('a')], [text('b')]] },
108
+ { type: 'list', ordered: true, start: 1, items: [item([text('a')]), item([text('b')])] },
109
+ ]);
110
+ });
111
+
112
+ it('nests indented items under their parent so numbering continues', () => {
113
+ expect(parseNoteMarkdown('1. **A**\n - a1\n - a2\n2. B\n - b1')).toEqual([
114
+ {
115
+ type: 'list',
116
+ ordered: true,
117
+ start: 1,
118
+ items: [
119
+ item(
120
+ [{ type: 'strong', children: [text('A')] }],
121
+ [
122
+ {
123
+ type: 'list',
124
+ ordered: false,
125
+ start: 1,
126
+ items: [item([text('a1')]), item([text('a2')])],
127
+ },
128
+ ],
129
+ ),
130
+ item(
131
+ [text('B')],
132
+ [{ type: 'list', ordered: false, start: 1, items: [item([text('b1')])] }],
133
+ ),
134
+ ],
135
+ },
136
+ ]);
137
+ });
138
+
139
+ it('keeps a list together across blank lines between items', () => {
140
+ expect(parseNoteMarkdown('1. a\n\n2. b\n\n more\n\nafter')).toEqual([
141
+ {
142
+ type: 'list',
143
+ ordered: true,
144
+ start: 1,
145
+ items: [
146
+ item([text('a')]),
147
+ item([text('b')], [{ type: 'paragraph', lines: [[text('more')]] }]),
148
+ ],
149
+ },
150
+ { type: 'paragraph', lines: [[text('after')]] },
151
+ ]);
152
+ });
153
+
154
+ it('records the starting number of an ordered list', () => {
155
+ expect(parseNoteMarkdown('3. c\n4. d')).toEqual([
156
+ { type: 'list', ordered: true, start: 3, items: [item([text('c')]), item([text('d')])] },
157
+ ]);
158
+ });
159
+
160
+ it('parses thematic breaks', () => {
161
+ expect(parseNoteMarkdown('a\n---\nb\n\n* * *')).toEqual([
162
+ { type: 'paragraph', lines: [[text('a')]] },
163
+ { type: 'rule' },
164
+ { type: 'paragraph', lines: [[text('b')]] },
165
+ { type: 'rule' },
102
166
  ]);
103
167
  });
104
168
 
105
169
  it('keeps unordered and ordered runs as separate lists', () => {
106
170
  expect(parseNoteMarkdown('- a\n1. b')).toEqual([
107
- { type: 'list', ordered: false, items: [[text('a')]] },
108
- { type: 'list', ordered: true, items: [[text('b')]] },
171
+ { type: 'list', ordered: false, start: 1, items: [item([text('a')])] },
172
+ { type: 'list', ordered: true, start: 1, items: [item([text('b')])] },
109
173
  ]);
110
174
  });
111
175
 
@@ -4,12 +4,16 @@ export type NoteInline =
4
4
  | { type: 'em'; children: NoteInline[] }
5
5
  | { type: 'code'; text: string };
6
6
 
7
+ export type NoteListItem = { content: NoteInline[]; children: NoteBlock[] };
8
+
7
9
  export type NoteBlock =
8
10
  | { type: 'paragraph'; lines: NoteInline[][] }
9
11
  | { type: 'heading'; level: 1 | 2 | 3; children: NoteInline[] }
10
- | { type: 'list'; ordered: boolean; items: NoteInline[][] };
12
+ | { type: 'list'; ordered: boolean; start: number; items: NoteListItem[] }
13
+ | { type: 'rule' };
11
14
 
12
15
  const HEADING = /^(#{1,3})\s+(.*)$/;
16
+ const RULE = /^(?:-[ \t]*){3,}$|^(?:\*[ \t]*){3,}$|^(?:_[ \t]*){3,}$/;
13
17
  // Ordered before the single-star branch so `**bold**` never parses as
14
18
  // empty italics. Emphasis content must start and end with non-whitespace
15
19
  // (CommonMark) so spaced stars like `2 * 3 … 5 * 4` never pair up, and `_`
@@ -38,14 +42,40 @@ function restoreEscapes(text: string, keepBackslash: boolean): string {
38
42
  });
39
43
  }
40
44
 
41
- function matchListItem(line: string): { ordered: boolean; content: string } | null {
45
+ type ListMarker = { ordered: boolean; start: number; indent: number; content: string };
46
+
47
+ function indentOf(line: string): number {
48
+ let width = 0;
49
+ for (const ch of line) {
50
+ if (ch === ' ') width++;
51
+ else if (ch === '\t') width += 4 - (width % 4);
52
+ else break;
53
+ }
54
+ return width;
55
+ }
56
+
57
+ function matchListItem(line: string): ListMarker | null {
58
+ const indent = indentOf(line);
42
59
  const unordered = /^\s*[-*]\s+(.*)$/.exec(line);
43
- if (unordered) return { ordered: false, content: unordered[1] };
44
- const ordered = /^\s*\d{1,3}[.)]\s+(.*)$/.exec(line);
45
- if (ordered) return { ordered: true, content: ordered[1] };
60
+ if (unordered) return { ordered: false, start: 1, indent, content: unordered[1] };
61
+ const ordered = /^\s*(\d{1,3})[.)]\s+(.*)$/.exec(line);
62
+ if (ordered) return { ordered: true, start: Number(ordered[1]), indent, content: ordered[2] };
46
63
  return null;
47
64
  }
48
65
 
66
+ function isBlank(line: string | undefined): boolean {
67
+ return line === undefined || line.trim() === '';
68
+ }
69
+
70
+ function dedent(lines: string[]): string[] {
71
+ const depth = Math.min(...lines.filter((l) => !isBlank(l)).map(indentOf));
72
+ return lines.map((l) => {
73
+ let cut = 0;
74
+ while (/[ \t]/.test(l[cut] ?? '') && indentOf(l.slice(0, cut + 1)) <= depth) cut++;
75
+ return l.slice(cut);
76
+ });
77
+ }
78
+
49
79
  function parseInlineHidden(text: string): NoteInline[] {
50
80
  const out: NoteInline[] = [];
51
81
  const pushText = (raw: string) => {
@@ -67,8 +97,53 @@ export function parseInline(text: string): NoteInline[] {
67
97
  return parseInlineHidden(hideEscapes(text));
68
98
  }
69
99
 
70
- export function parseNoteMarkdown(text: string): NoteBlock[] {
71
- const lines = hideEscapes(text).split('\n');
100
+ function parseList(lines: string[], from: number): { block: NoteBlock; next: number } {
101
+ const first = matchListItem(lines[from]) as ListMarker;
102
+ const items: NoteListItem[] = [];
103
+ let i = from;
104
+ while (i < lines.length) {
105
+ const marker = matchListItem(lines[i]);
106
+ if (!marker || marker.ordered !== first.ordered || marker.indent > first.indent) break;
107
+ i++;
108
+ // Anything indented past the marker belongs to the item, so loosely
109
+ // indented agent output (two spaces under `1.`) still nests.
110
+ const body: string[] = [];
111
+ while (i < lines.length) {
112
+ if (isBlank(lines[i])) {
113
+ let peek = i;
114
+ while (isBlank(lines[peek]) && peek < lines.length) peek++;
115
+ if (peek < lines.length && indentOf(lines[peek]) > marker.indent) {
116
+ body.push(...lines.slice(i, peek));
117
+ i = peek;
118
+ continue;
119
+ }
120
+ break;
121
+ }
122
+ if (indentOf(lines[i]) <= marker.indent) break;
123
+ body.push(lines[i]);
124
+ i++;
125
+ }
126
+ items.push({
127
+ content: parseInlineHidden(marker.content.trim()),
128
+ children: body.length ? parseBlocks(dedent(body)) : [],
129
+ });
130
+ let peek = i;
131
+ while (isBlank(lines[peek]) && peek < lines.length) peek++;
132
+ const sibling = peek < lines.length ? matchListItem(lines[peek]) : null;
133
+ if (sibling && sibling.ordered === first.ordered && sibling.indent <= first.indent) i = peek;
134
+ }
135
+ return {
136
+ block: { type: 'list', ordered: first.ordered, start: first.start, items },
137
+ next: i,
138
+ };
139
+ }
140
+
141
+ function startsBlock(line: string): boolean {
142
+ const trimmed = line.trim();
143
+ return trimmed === '' || HEADING.test(trimmed) || RULE.test(trimmed) || !!matchListItem(line);
144
+ }
145
+
146
+ function parseBlocks(lines: string[]): NoteBlock[] {
72
147
  const blocks: NoteBlock[] = [];
73
148
  let i = 0;
74
149
  while (i < lines.length) {
@@ -87,30 +162,30 @@ export function parseNoteMarkdown(text: string): NoteBlock[] {
87
162
  i++;
88
163
  continue;
89
164
  }
90
- const item = matchListItem(lines[i]);
91
- if (item) {
92
- const items: NoteInline[][] = [];
93
- while (i < lines.length) {
94
- const next = matchListItem(lines[i]);
95
- if (!next || next.ordered !== item.ordered) break;
96
- items.push(parseInlineHidden(next.content.trim()));
97
- i++;
98
- }
99
- blocks.push({ type: 'list', ordered: item.ordered, items });
165
+ if (RULE.test(trimmed)) {
166
+ blocks.push({ type: 'rule' });
167
+ i++;
168
+ continue;
169
+ }
170
+ if (matchListItem(lines[i])) {
171
+ const { block, next } = parseList(lines, i);
172
+ blocks.push(block);
173
+ i = next;
100
174
  continue;
101
175
  }
102
176
  // Paragraph lines keep leading whitespace (rendered with pre-wrap) so
103
177
  // plain-text notes don't lose manual indentation or spacing.
104
178
  const paragraph = [parseInlineHidden(lines[i].trimEnd())];
105
179
  i++;
106
- while (i < lines.length) {
107
- const next = lines[i];
108
- const nextTrimmed = next.trim();
109
- if (nextTrimmed === '' || HEADING.test(nextTrimmed) || matchListItem(next)) break;
110
- paragraph.push(parseInlineHidden(next.trimEnd()));
180
+ while (i < lines.length && !startsBlock(lines[i])) {
181
+ paragraph.push(parseInlineHidden(lines[i].trimEnd()));
111
182
  i++;
112
183
  }
113
184
  blocks.push({ type: 'paragraph', lines: paragraph });
114
185
  }
115
186
  return blocks;
116
187
  }
188
+
189
+ export function parseNoteMarkdown(text: string): NoteBlock[] {
190
+ return parseBlocks(hideEscapes(text).split('\n'));
191
+ }
@@ -1,5 +1,5 @@
1
1
  import { describe, expect, it } from 'vitest';
2
- import { holdOpacity } from './transition';
2
+ import { describeTransition, holdOpacity } from './transition';
3
3
 
4
4
  describe('holdOpacity', () => {
5
5
  it('drops opacity from array keyframes and keeps everything else', () => {
@@ -29,3 +29,86 @@ describe('holdOpacity', () => {
29
29
  expect(holdOpacity(undefined)).toBeUndefined();
30
30
  });
31
31
  });
32
+
33
+ describe('describeTransition', () => {
34
+ it('names a cross-fade and reports its longest phase', () => {
35
+ expect(
36
+ describeTransition({
37
+ duration: 200,
38
+ enter: { duration: 320, keyframes: [{ opacity: 0 }, { opacity: 1 }] },
39
+ exit: { duration: 240, keyframes: [{ opacity: 1 }, { opacity: 0 }] },
40
+ }),
41
+ ).toEqual({ kind: 'fade', duration: 320 });
42
+ });
43
+
44
+ it('adds a phase delay to the duration it inherits', () => {
45
+ expect(
46
+ describeTransition({
47
+ duration: 300,
48
+ enter: { delay: 80, keyframes: [{ opacity: 0 }, { opacity: 1 }] },
49
+ }).duration,
50
+ ).toBe(380);
51
+ expect(describeTransition({ duration: 300, morph: { delay: 50 } }).duration).toBe(350);
52
+ });
53
+
54
+ it('calls a translating entrance a slide', () => {
55
+ expect(
56
+ describeTransition({
57
+ duration: 240,
58
+ enter: {
59
+ keyframes: [
60
+ { opacity: 0, transform: 'translateX(10px)' },
61
+ { opacity: 1, transform: 'translateX(0)' },
62
+ ],
63
+ },
64
+ }).kind,
65
+ ).toBe('slide');
66
+ });
67
+
68
+ it('reads property-indexed keyframes', () => {
69
+ expect(
70
+ describeTransition({
71
+ duration: 300,
72
+ enter: { keyframes: { opacity: [0, 1], transform: ['scale(0.96)', 'scale(1)'] } },
73
+ }).kind,
74
+ ).toBe('zoom');
75
+ });
76
+
77
+ it('prefers morph and counts its duration', () => {
78
+ expect(
79
+ describeTransition({
80
+ duration: 300,
81
+ enter: { duration: 320, keyframes: [{ opacity: 0 }, { opacity: 1 }] },
82
+ morph: { duration: 600, delay: 40 },
83
+ }),
84
+ ).toEqual({ kind: 'morph', duration: 640 });
85
+ });
86
+
87
+ it('ignores the base duration when explicit phase durations set the length', () => {
88
+ expect(
89
+ describeTransition({
90
+ duration: 600,
91
+ enter: { duration: 200, keyframes: [{ opacity: 0 }, { opacity: 1 }] },
92
+ }).duration,
93
+ ).toBe(200);
94
+ });
95
+
96
+ it('uses the base duration for a bare morph', () => {
97
+ expect(
98
+ describeTransition({
99
+ duration: 500,
100
+ enter: { duration: 200, keyframes: [{ opacity: 0 }, { opacity: 1 }] },
101
+ morph: true,
102
+ }),
103
+ ).toEqual({ kind: 'morph', duration: 500 });
104
+ });
105
+
106
+ it('falls back to custom for anything else', () => {
107
+ expect(
108
+ describeTransition({
109
+ duration: 300,
110
+ enter: { keyframes: [{ filter: 'blur(8px)' }, { filter: 'blur(0)' }] },
111
+ }).kind,
112
+ ).toBe('custom');
113
+ });
114
+ });
@@ -41,3 +41,46 @@ export function holdOpacity(phase: TransitionPhase | undefined): TransitionPhase
41
41
  const { opacity: _opacity, ...keyframes } = phase.keyframes;
42
42
  return { ...phase, keyframes };
43
43
  }
44
+
45
+ export type TransitionKind = 'morph' | 'fade' | 'slide' | 'zoom' | 'wipe' | 'custom';
46
+
47
+ export function describeTransition(transition: SlideTransition): {
48
+ kind: TransitionKind;
49
+ duration: number;
50
+ } {
51
+ const duration = Math.max(
52
+ phaseLength(transition.enter, transition.duration),
53
+ phaseLength(transition.exit, transition.duration),
54
+ transition.morph === true
55
+ ? transition.duration
56
+ : phaseLength(transition.morph || undefined, transition.duration),
57
+ );
58
+ if (transition.morph) return { kind: 'morph', duration };
59
+ const frames = keyframeList(transition.enter?.keyframes ?? transition.exit?.keyframes);
60
+ const props = new Set(frames.flatMap((frame) => Object.keys(frame)));
61
+ for (const meta of ['offset', 'easing', 'composite']) props.delete(meta);
62
+ const transforms = frames.map((frame) => String(frame.transform ?? '')).join(' ');
63
+ let kind: TransitionKind = 'custom';
64
+ if (props.has('clipPath')) kind = 'wipe';
65
+ else if (/scale/.test(transforms)) kind = 'zoom';
66
+ else if (/translate/.test(transforms)) kind = 'slide';
67
+ else if (props.size === 1 && props.has('opacity')) kind = 'fade';
68
+ return { kind, duration };
69
+ }
70
+
71
+ function phaseLength(
72
+ phase: { duration?: number; delay?: number } | undefined,
73
+ fallbackDuration: number,
74
+ ): number {
75
+ return phase ? (phase.duration ?? fallbackDuration) + (phase.delay ?? 0) : 0;
76
+ }
77
+
78
+ function keyframeList(keyframes: TransitionPhase['keyframes'] | undefined): Keyframe[] {
79
+ if (!keyframes) return [];
80
+ if (Array.isArray(keyframes)) return keyframes;
81
+ const frame: Keyframe = {};
82
+ for (const [key, value] of Object.entries(keyframes)) {
83
+ frame[key] = Array.isArray(value) ? value.join(' ') : value;
84
+ }
85
+ return [frame];
86
+ }
@@ -0,0 +1,253 @@
1
+ import { afterEach, describe, expect, it, vi } from 'vitest';
2
+ import {
3
+ createSaveQueue,
4
+ createWriteLedger,
5
+ forgetWrite,
6
+ onAbandon,
7
+ registerUnsaved,
8
+ settleUnsaved,
9
+ trackWrite,
10
+ type UnsavedSource,
11
+ unsavedStatus,
12
+ } from './unsaved';
13
+
14
+ const cleanups: (() => void)[] = [];
15
+
16
+ function source(kind: UnsavedSource['kind'], opts: { fail?: string } = {}) {
17
+ const state = { dirty: true };
18
+ const entry = {
19
+ kind,
20
+ dirty: () => state.dirty,
21
+ save: vi.fn(async () => {
22
+ if (opts.fail) throw new Error(opts.fail);
23
+ state.dirty = false;
24
+ }),
25
+ discard: vi.fn(() => {
26
+ state.dirty = false;
27
+ }),
28
+ };
29
+ cleanups.push(registerUnsaved(entry));
30
+ return Object.assign(entry, { state });
31
+ }
32
+
33
+ afterEach(async () => {
34
+ for (const cleanup of cleanups.splice(0)) cleanup();
35
+ await settleUnsaved('abandon');
36
+ });
37
+
38
+ const settled = () => new Promise((resolve) => setTimeout(resolve));
39
+
40
+ describe('unsaved work registry', () => {
41
+ it('reports drafts apart from autosaved work that is still landing', () => {
42
+ expect(unsavedStatus()).toEqual({ drafts: false, pending: false });
43
+ const notes = source('autosave');
44
+ expect(unsavedStatus()).toEqual({ drafts: false, pending: true });
45
+ source('draft');
46
+ expect(unsavedStatus()).toEqual({ drafts: true, pending: true });
47
+ notes.state.dirty = false;
48
+ expect(unsavedStatus()).toEqual({ drafts: true, pending: false });
49
+ });
50
+
51
+ it('saves every dirty source and leaves clean ones alone', async () => {
52
+ const draft = source('draft');
53
+ const notes = source('autosave');
54
+ const clean = source('draft');
55
+ clean.state.dirty = false;
56
+
57
+ expect(await settleUnsaved('save')).toEqual({ ok: true });
58
+ expect(draft.save).toHaveBeenCalledOnce();
59
+ expect(notes.save).toHaveBeenCalledOnce();
60
+ expect(clean.save).not.toHaveBeenCalled();
61
+ expect(unsavedStatus()).toEqual({ drafts: false, pending: false });
62
+ });
63
+
64
+ it('discards drafts but still lets autosaved work land', async () => {
65
+ const draft = source('draft');
66
+ const notes = source('autosave');
67
+
68
+ expect(await settleUnsaved('discard')).toEqual({ ok: true });
69
+ expect(draft.discard).toHaveBeenCalledOnce();
70
+ expect(draft.save).not.toHaveBeenCalled();
71
+ expect(notes.save).toHaveBeenCalledOnce();
72
+ expect(notes.discard).not.toHaveBeenCalled();
73
+ });
74
+
75
+ it('reports a failed save and keeps the work dirty', async () => {
76
+ const draft = source('draft', { fail: 'disk is full' });
77
+
78
+ expect(await settleUnsaved('save')).toEqual({ ok: false, error: 'disk is full' });
79
+ expect(draft.state.dirty).toBe(true);
80
+ expect(unsavedStatus().drafts).toBe(true);
81
+ });
82
+
83
+ it('abandons everything without writing', async () => {
84
+ const draft = source('draft', { fail: 'disk is full' });
85
+ const notes = source('autosave', { fail: 'disk is full' });
86
+
87
+ expect(await settleUnsaved('abandon')).toEqual({ ok: true });
88
+ expect(draft.save).not.toHaveBeenCalled();
89
+ expect(notes.save).not.toHaveBeenCalled();
90
+ expect(unsavedStatus()).toEqual({ drafts: false, pending: false });
91
+ });
92
+
93
+ it('tells abandon listeners only when the work is abandoned', async () => {
94
+ const listener = vi.fn();
95
+ cleanups.push(onAbandon(listener));
96
+
97
+ await settleUnsaved('save');
98
+ await settleUnsaved('discard');
99
+ expect(listener).not.toHaveBeenCalled();
100
+
101
+ await settleUnsaved('abandon');
102
+ expect(listener).toHaveBeenCalledOnce();
103
+ });
104
+
105
+ it('refuses to report success when more work appeared while saving', async () => {
106
+ const draft = source('draft');
107
+ draft.save.mockImplementation(async () => {});
108
+
109
+ expect(await settleUnsaved('save')).toEqual({
110
+ ok: false,
111
+ error: 'More changes were made while saving.',
112
+ });
113
+ });
114
+
115
+ it('waits for a write that outlived the component that started it', async () => {
116
+ let land: () => void = () => {};
117
+ const write = new Promise<void>((resolve) => {
118
+ land = resolve;
119
+ });
120
+ trackWrite('notes', () => write);
121
+ expect(unsavedStatus()).toEqual({ drafts: false, pending: true });
122
+
123
+ let done = false;
124
+ const outcome = settleUnsaved('save').then((result) => {
125
+ done = true;
126
+ return result;
127
+ });
128
+ await Promise.resolve();
129
+ expect(done).toBe(false);
130
+ land();
131
+ expect(await outcome).toEqual({ ok: true });
132
+ expect(unsavedStatus().pending).toBe(false);
133
+ });
134
+
135
+ it('reports a detached write that failed', async () => {
136
+ trackWrite('notes', () => Promise.reject(new Error('server went away')));
137
+
138
+ expect(await settleUnsaved('save')).toEqual({ ok: false, error: 'server went away' });
139
+ });
140
+
141
+ it('keeps a failed detached write unsaved and retries it on the next save', async () => {
142
+ const write = vi
143
+ .fn<() => Promise<void>>()
144
+ .mockRejectedValueOnce(new Error('server went away'))
145
+ .mockResolvedValue();
146
+ trackWrite('notes', write);
147
+ await settled();
148
+ expect(unsavedStatus()).toEqual({ drafts: false, pending: true });
149
+
150
+ expect(await settleUnsaved('save')).toEqual({ ok: true });
151
+ expect(write).toHaveBeenCalledTimes(2);
152
+ expect(unsavedStatus().pending).toBe(false);
153
+ });
154
+
155
+ it('keeps failing until the work is abandoned', async () => {
156
+ const write = vi.fn(() => Promise.reject(new Error('server went away')));
157
+ trackWrite('notes', write);
158
+ await settled();
159
+
160
+ expect(await settleUnsaved('save')).toEqual({ ok: false, error: 'server went away' });
161
+ expect(unsavedStatus().pending).toBe(true);
162
+ expect(await settleUnsaved('abandon')).toEqual({ ok: true });
163
+ expect(unsavedStatus().pending).toBe(false);
164
+ expect(write).toHaveBeenCalledTimes(2);
165
+ });
166
+
167
+ it('forgets a write abandoned in flight, even if it fails afterwards', async () => {
168
+ let fail: (error: Error) => void = () => {};
169
+ const write = vi.fn(
170
+ () =>
171
+ new Promise<void>((_resolve, reject) => {
172
+ fail = reject;
173
+ }),
174
+ );
175
+ trackWrite('notes', write);
176
+
177
+ expect(await settleUnsaved('abandon')).toEqual({ ok: true });
178
+ expect(unsavedStatus().pending).toBe(false);
179
+ fail(new Error('server went away'));
180
+ await settled();
181
+ expect(unsavedStatus().pending).toBe(false);
182
+ expect(await settleUnsaved('save')).toEqual({ ok: true });
183
+ expect(write).toHaveBeenCalledOnce();
184
+ });
185
+
186
+ it('drops a failed write once newer work for the same key has landed', async () => {
187
+ const stale = vi.fn(() => Promise.reject(new Error('server went away')));
188
+ trackWrite('notes', stale);
189
+ await settled();
190
+
191
+ forgetWrite('notes');
192
+ expect(unsavedStatus().pending).toBe(false);
193
+ expect(await settleUnsaved('save')).toEqual({ ok: true });
194
+ expect(stale).toHaveBeenCalledOnce();
195
+ });
196
+ });
197
+
198
+ describe('createSaveQueue', () => {
199
+ it('runs one task at a time and reports idle once all settle', async () => {
200
+ const queue = createSaveQueue();
201
+ const order: string[] = [];
202
+ let release!: () => void;
203
+ const onIdle = vi.fn();
204
+ const first = queue.run(
205
+ () =>
206
+ new Promise<void>((resolve) => {
207
+ order.push('first:start');
208
+ release = () => {
209
+ order.push('first:end');
210
+ resolve();
211
+ };
212
+ }),
213
+ onIdle,
214
+ );
215
+ const second = queue.run(async () => {
216
+ order.push('second');
217
+ throw new Error('boom');
218
+ }, onIdle);
219
+ await Promise.resolve();
220
+ expect(queue.busy()).toBe(true);
221
+ release();
222
+ await first;
223
+ await expect(second).rejects.toThrow('boom');
224
+ expect(order).toEqual(['first:start', 'first:end', 'second']);
225
+ expect(queue.busy()).toBe(false);
226
+ expect(onIdle).toHaveBeenCalledOnce();
227
+ await expect(queue.run(async () => 'next')).resolves.toBe('next');
228
+ });
229
+ });
230
+
231
+ describe('createWriteLedger', () => {
232
+ it('marks an older write superseded once a newer one for the same key lands', () => {
233
+ const ledger = createWriteLedger();
234
+ const stale = ledger.next();
235
+ const fresh = ledger.next();
236
+
237
+ expect(ledger.superseded('fontSize', stale)).toBe(false);
238
+ ledger.record('fontSize', fresh);
239
+ expect(ledger.superseded('fontSize', stale)).toBe(true);
240
+ expect(ledger.superseded('fontSize', fresh)).toBe(false);
241
+ expect(ledger.superseded('color', stale)).toBe(false);
242
+ });
243
+
244
+ it('keeps the newest record when an older write lands late', () => {
245
+ const ledger = createWriteLedger();
246
+ const stale = ledger.next();
247
+ const fresh = ledger.next();
248
+ ledger.record('fontSize', fresh);
249
+ ledger.record('fontSize', stale);
250
+
251
+ expect(ledger.superseded('fontSize', stale)).toBe(true);
252
+ });
253
+ });