@lemonriver/core 0.6.0 → 0.7.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 (44) hide show
  1. package/dist/{build-RlcGG-Ve.js → build-CKwrex8y.js} +1 -1
  2. package/dist/cli/bin.js +3 -3
  3. package/dist/{config-BJT87wE9.js → config-B1_gk0sy.js} +1641 -60
  4. package/dist/{dev-DR-j_xda.js → dev-DZ2Yzl2p.js} +1 -1
  5. package/dist/{preview-BTAhTb5B.js → preview-hMDcuHfP.js} +1 -1
  6. package/dist/vite/index.js +1 -1
  7. package/package.json +1 -1
  8. package/src/app/lemonriver/chrome/app-chrome.tsx +12 -1
  9. package/src/app/lemonriver/features.test.ts +5 -0
  10. package/src/app/lemonriver/features.ts +2 -1
  11. package/src/app/lemonriver/feedback/pending-toast.ts +7 -2
  12. package/src/app/lemonriver/home/deck-card.tsx +10 -1
  13. package/src/app/lemonriver/home/home-page.tsx +52 -1
  14. package/src/app/lemonriver/share/capture.ts +76 -0
  15. package/src/app/lemonriver/share/client.ts +162 -0
  16. package/src/app/lemonriver/share/codes.test.ts +49 -0
  17. package/src/app/lemonriver/share/codes.ts +30 -0
  18. package/src/app/lemonriver/share/compare.test.ts +199 -0
  19. package/src/app/lemonriver/share/compare.ts +367 -0
  20. package/src/app/lemonriver/share/drop.ts +84 -0
  21. package/src/app/lemonriver/share/folder.test.ts +42 -0
  22. package/src/app/lemonriver/share/folder.ts +29 -0
  23. package/src/app/lemonriver/share/freeze.ts +51 -0
  24. package/src/app/lemonriver/share/guide.test.ts +78 -0
  25. package/src/app/lemonriver/share/guide.ts +222 -0
  26. package/src/app/lemonriver/share/import-dialog.tsx +391 -0
  27. package/src/app/lemonriver/share/import-entry.tsx +106 -0
  28. package/src/app/lemonriver/share/model.ts +150 -0
  29. package/src/app/lemonriver/share/naming.test.ts +59 -0
  30. package/src/app/lemonriver/share/naming.ts +71 -0
  31. package/src/app/lemonriver/share/paths.test.ts +75 -0
  32. package/src/app/lemonriver/share/paths.ts +181 -0
  33. package/src/app/lemonriver/share/pdf.test.ts +79 -0
  34. package/src/app/lemonriver/share/pdf.ts +169 -0
  35. package/src/app/lemonriver/share/share-dialog.tsx +286 -0
  36. package/src/app/lemonriver/share/summary.ts +47 -0
  37. package/src/app/lemonriver/slide-extensions.tsx +69 -23
  38. package/src/app/lemonriver/templates/library-page.tsx +5 -2
  39. package/src/app/lemonriver/text/en.ts +67 -0
  40. package/src/app/lemonriver/text/es.ts +67 -0
  41. package/src/app/lemonriver/text/ja.ts +67 -0
  42. package/src/app/lemonriver/text/types.ts +78 -0
  43. package/src/app/lemonriver/text/zh-cn.ts +62 -0
  44. package/src/app/lemonriver/text/zh-tw.ts +62 -0
@@ -0,0 +1,199 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { compareDeck } from './compare';
3
+
4
+ const encoder = new TextEncoder();
5
+ const bytes = (text: string) => encoder.encode(text);
6
+
7
+ const BASE = `import type { Page } from '@lemonriver/core';
8
+
9
+ export const meta = { title: 'Q3' };
10
+
11
+ const Cover: Page = () => <div>Cover</div>;
12
+ const Body: Page = () => <div>Body</div>;
13
+
14
+ export const notes = ['first', 'second'];
15
+
16
+ export default [Cover, Body] satisfies Page[];
17
+ `;
18
+
19
+ function deck(source: string, extra: Record<string, string | Uint8Array> = {}) {
20
+ const files: Record<string, Uint8Array> = { 'index.tsx': bytes(source) };
21
+ for (const [path, data] of Object.entries(extra)) {
22
+ files[path] = typeof data === 'string' ? bytes(data) : data;
23
+ }
24
+ return files;
25
+ }
26
+
27
+ const statuses = (changes: ReturnType<typeof compareDeck>) =>
28
+ changes.pages.map((page) => [page.n, page.status]);
29
+
30
+ describe('compareDeck', () => {
31
+ it('reports nothing when the two copies are identical, reformatting included', () => {
32
+ const reformatted = BASE.replace(/\n\n/g, '\n\n\n')
33
+ .replace('<div>Cover</div>', '<div> Cover </div>')
34
+ .replace("title: 'Q3'", "title: 'Q3'");
35
+ const changes = compareDeck(deck(BASE), deck(reformatted));
36
+ expect(changes.readable).toBe(true);
37
+ expect(statuses(changes)).toEqual([
38
+ [1, 'same'],
39
+ [2, 'same'],
40
+ ]);
41
+ expect(changes.shared).toBe(false);
42
+ expect(changes.assets).toEqual({ added: [], changed: [], removed: [] });
43
+ });
44
+
45
+ it('marks a page whose code changed', () => {
46
+ const changes = compareDeck(deck(BASE), deck(BASE.replace('Body</div>', 'Body, v2</div>')));
47
+ expect(statuses(changes)).toEqual([
48
+ [1, 'same'],
49
+ [2, 'changed'],
50
+ ]);
51
+ expect(changes.pages[1]?.name).toBe('Body');
52
+ expect(changes.shared).toBe(false);
53
+ });
54
+
55
+ it('marks a page that only moved', () => {
56
+ const moved = BASE.replace('export default [Cover, Body]', 'export default [Body, Cover]');
57
+ const changes = compareDeck(deck(BASE), deck(moved));
58
+ expect(statuses(changes)).toEqual([
59
+ [1, 'moved'],
60
+ [2, 'moved'],
61
+ ]);
62
+ });
63
+
64
+ it('marks an added page with its place in the package', () => {
65
+ const extra = BASE.replace(
66
+ 'const Body: Page = () => <div>Body</div>;',
67
+ 'const Body: Page = () => <div>Body</div>;\nconst More: Page = () => <div>More</div>;',
68
+ ).replace('[Cover, Body]', '[Cover, Body, More]');
69
+ const changes = compareDeck(deck(BASE), deck(extra));
70
+ expect(statuses(changes)).toEqual([
71
+ [1, 'same'],
72
+ [2, 'same'],
73
+ [3, 'added'],
74
+ ]);
75
+ expect(changes.pages[2]?.name).toBe('More');
76
+ });
77
+
78
+ it('marks a page this machine has and the package does not', () => {
79
+ const fewer = BASE.replace('const Body: Page = () => <div>Body</div>;\n', '').replace(
80
+ '[Cover, Body]',
81
+ '[Cover]',
82
+ );
83
+ const changes = compareDeck(deck(BASE), deck(fewer));
84
+ expect(statuses(changes)).toEqual([
85
+ [1, 'same'],
86
+ [2, 'removed'],
87
+ ]);
88
+ });
89
+
90
+ it('counts a page whose only change is its speaker note', () => {
91
+ const changes = compareDeck(
92
+ deck(BASE),
93
+ deck(BASE.replace("['first', 'second']", "['first', 'second, rewritten']")),
94
+ );
95
+ expect(statuses(changes)).toEqual([
96
+ [1, 'same'],
97
+ [2, 'changed'],
98
+ ]);
99
+ expect(changes.pages[1]?.notes).toBe(true);
100
+ expect(changes.pages[0]?.notes).toBe(false);
101
+ expect(changes.shared).toBe(false);
102
+ });
103
+
104
+ it('does not treat a title change as shared code', () => {
105
+ const changes = compareDeck(deck(BASE), deck(BASE.replace("title: 'Q3'", "title: 'Q3 FY26'")));
106
+ expect(changes.shared).toBe(false);
107
+ expect(statuses(changes)).toEqual([
108
+ [1, 'same'],
109
+ [2, 'same'],
110
+ ]);
111
+ });
112
+
113
+ it('keeps exported pages out of the shared check', () => {
114
+ const exported = BASE.replace('const Cover: Page', 'export const Cover: Page').replace(
115
+ 'const Body: Page',
116
+ 'export const Body: Page',
117
+ );
118
+ const changes = compareDeck(
119
+ deck(exported),
120
+ deck(exported.replace('Body</div>', 'Body v2</div>')),
121
+ );
122
+ expect(statuses(changes)).toEqual([
123
+ [1, 'same'],
124
+ [2, 'changed'],
125
+ ]);
126
+ expect(changes.shared).toBe(false);
127
+ });
128
+
129
+ it('flags a component both pages use as shared', () => {
130
+ const source = `import type { Page } from '@lemonriver/core';
131
+
132
+ export const meta = { title: 'Q3' };
133
+
134
+ const Card = () => <p>card</p>;
135
+
136
+ const Cover: Page = () => <div><Card />Cover</div>;
137
+ const Body: Page = () => <div><Card />Body</div>;
138
+
139
+ export const notes = ['first', 'second'];
140
+
141
+ export default [Cover, Body] satisfies Page[];
142
+ `;
143
+ const changes = compareDeck(deck(source), deck(source.replace('card</p>', 'card v2</p>')));
144
+ expect(changes.shared).toBe(true);
145
+ expect(statuses(changes)).toEqual([
146
+ [1, 'same'],
147
+ [2, 'same'],
148
+ ]);
149
+ });
150
+
151
+ it('ignores how packing rewrote an asset reference', () => {
152
+ const local = deck(
153
+ BASE.replace('Cover</div>', 'Cover<Logo /></div>').replace(
154
+ 'const Cover',
155
+ "import logo from '@assets/logo.png';\n\nconst Cover",
156
+ ),
157
+ );
158
+ const packaged = deck(
159
+ BASE.replace('Cover</div>', 'Cover<Logo /></div>').replace(
160
+ 'const Cover',
161
+ "import logo from './assets/logo.png';\n\nconst Cover",
162
+ ),
163
+ { 'assets/logo.png': bytes('PNG') },
164
+ );
165
+ const changes = compareDeck(local, packaged);
166
+ expect(statuses(changes)).toEqual([
167
+ [1, 'same'],
168
+ [2, 'same'],
169
+ ]);
170
+ expect(changes.shared).toBe(false);
171
+ expect(changes.assets.added).toEqual(['logo.png']);
172
+ });
173
+
174
+ it('lists assets that were added, changed and removed', () => {
175
+ const local = deck(BASE, { 'assets/a.png': 'old', 'assets/gone.png': 'x' });
176
+ const packaged = deck(BASE, { 'assets/a.png': 'new', 'assets/b.png': 'y' });
177
+ const changes = compareDeck(local, packaged);
178
+ expect(changes.assets).toEqual({ added: ['b.png'], changed: ['a.png'], removed: ['gone.png'] });
179
+ });
180
+
181
+ it('pairs inline pages by position', () => {
182
+ const inline = (b: string) =>
183
+ `import type { Page } from '@lemonriver/core';\n\nexport default [() => <div>${b}</div>, () => <div>Y</div>] satisfies Page[];\n`;
184
+ const changes = compareDeck(deck(inline('X')), deck(inline('X2')));
185
+ expect(statuses(changes)).toEqual([
186
+ [1, 'changed'],
187
+ [2, 'same'],
188
+ ]);
189
+ expect(changes.pages[0]?.name).toBeNull();
190
+ });
191
+
192
+ it('says when the file cannot be read page by page', () => {
193
+ const spread = `import type { Page } from '@lemonriver/core';\nconst rest: Page[] = [];\nexport default [() => <div>X</div>, ...rest];\n`;
194
+ const changes = compareDeck(deck(BASE), deck(spread));
195
+ expect(changes.readable).toBe(false);
196
+ expect(changes.pages).toEqual([]);
197
+ expect(changes.shared).toBe(true);
198
+ });
199
+ });
@@ -0,0 +1,367 @@
1
+ import { parse } from '@babel/parser';
2
+ import type { Node } from '@babel/types';
3
+
4
+ /** What changed between the deck this machine has and the one in a package. */
5
+
6
+ export type PageStatus = 'same' | 'changed' | 'added' | 'removed' | 'moved';
7
+
8
+ export type PageChange = {
9
+ /** The page's number in the package, or in this machine's copy when the package dropped it. */
10
+ n: number;
11
+ status: PageStatus;
12
+ name: string | null;
13
+ notes: boolean;
14
+ /** The code is the same and only the speaker note moved. */
15
+ notesOnly: boolean;
16
+ };
17
+
18
+ export type DeckChanges = {
19
+ pages: PageChange[];
20
+ shared: boolean;
21
+ assets: { added: string[]; changed: string[]; removed: string[] };
22
+ readable: boolean;
23
+ };
24
+
25
+ export type DeckFiles = Map<string, Uint8Array> | Record<string, Uint8Array>;
26
+
27
+ const ENTRY_NAMES = ['index.tsx', 'index.jsx', 'index.ts', 'index.js'];
28
+ const ASSETS = 'assets/';
29
+
30
+ type ParsedPage = {
31
+ name: string | null;
32
+ index: number;
33
+ inlineIndex: number;
34
+ source: string;
35
+ };
36
+
37
+ type ParsedDeck = {
38
+ ok: boolean;
39
+ pages: ParsedPage[];
40
+ notes: string[] | null;
41
+ shared: string;
42
+ };
43
+
44
+ function toMap(files: DeckFiles): Map<string, Uint8Array> {
45
+ return files instanceof Map ? files : new Map(Object.entries(files));
46
+ }
47
+
48
+ /**
49
+ * Packing rewrites `@assets/x` to a path relative to each file; comparing raw
50
+ * text would then report every page that uses an asset as changed.
51
+ */
52
+ export function normalizeAssets(source: string): string {
53
+ return source.replace(/(?:\.{1,2}\/)+assets\//g, '@assets/');
54
+ }
55
+
56
+ function compress(source: string): string {
57
+ return normalizeAssets(source).replace(/\s+/g, '');
58
+ }
59
+
60
+ function slice(source: string, node: Node): string {
61
+ if (node.start == null || node.end == null) return '';
62
+ return source.slice(node.start, node.end);
63
+ }
64
+
65
+ function unwrapExport(node: Node): Node {
66
+ return node.type === 'ExportNamedDeclaration' && node.declaration ? node.declaration : node;
67
+ }
68
+
69
+ /** Pages are compared one by one, and `notes`/`meta` ride with the deck rather than its layout. */
70
+ function excludedFromShared(name: string | null, pages: Set<string>): boolean {
71
+ return name === 'notes' || name === 'meta' || (name !== null && pages.has(name));
72
+ }
73
+
74
+ function parseDeck(source: string): ParsedDeck {
75
+ let body: Node[];
76
+ try {
77
+ body = parse(source, {
78
+ sourceType: 'module',
79
+ plugins: ['typescript', 'jsx'],
80
+ errorRecovery: true,
81
+ }).program.body;
82
+ } catch {
83
+ return { ok: false, pages: [], notes: null, shared: '' };
84
+ }
85
+
86
+ const declarations = new Map<string, string>();
87
+ for (const raw of body) {
88
+ const node = unwrapExport(raw);
89
+ if (node.type === 'VariableDeclaration') {
90
+ for (const item of node.declarations) {
91
+ if (item.id.type === 'Identifier' && item.init) {
92
+ declarations.set(item.id.name, compress(slice(source, item)));
93
+ }
94
+ }
95
+ } else if (node.type === 'FunctionDeclaration' && node.id) {
96
+ declarations.set(node.id.name, compress(slice(source, node)));
97
+ }
98
+ }
99
+
100
+ let array: Node | null = null;
101
+ let notes: string[] | null = null;
102
+ const named = new Set<string>();
103
+ for (const node of body) {
104
+ if (node.type === 'ExportDefaultDeclaration') {
105
+ let inner = node.declaration as Node;
106
+ while (inner.type === 'TSAsExpression' || inner.type === 'TSSatisfiesExpression') {
107
+ inner = inner.expression as Node;
108
+ }
109
+ array = inner.type === 'ArrayExpression' ? inner : null;
110
+ continue;
111
+ }
112
+ const declaration =
113
+ node.type === 'ExportNamedDeclaration' || node.type === 'VariableDeclaration'
114
+ ? node.type === 'ExportNamedDeclaration'
115
+ ? (node.declaration as Node | null)
116
+ : node
117
+ : null;
118
+ if (declaration?.type !== 'VariableDeclaration') continue;
119
+ for (const item of declaration.declarations) {
120
+ if (item.id.type !== 'Identifier' || item.id.name !== 'notes') continue;
121
+ if (item.init?.type === 'ArrayExpression') {
122
+ notes = item.init.elements.map((element) =>
123
+ element && element.type !== 'SpreadElement' ? compress(slice(source, element)) : '',
124
+ );
125
+ }
126
+ }
127
+ }
128
+
129
+ if (array?.type !== 'ArrayExpression') {
130
+ return { ok: false, pages: [], notes, shared: '' };
131
+ }
132
+
133
+ const pages: ParsedPage[] = [];
134
+ let inlineIndex = 0;
135
+ for (let index = 0; index < array.elements.length; index++) {
136
+ const element = array.elements[index];
137
+ if (!element || element.type === 'SpreadElement') {
138
+ return { ok: false, pages: [], notes, shared: '' };
139
+ }
140
+ if (element.type === 'Identifier') {
141
+ named.add(element.name);
142
+ pages.push({
143
+ name: element.name,
144
+ index,
145
+ inlineIndex: -1,
146
+ source: declarations.get(element.name) ?? compress(slice(source, element)),
147
+ });
148
+ continue;
149
+ }
150
+ pages.push({
151
+ name: null,
152
+ index,
153
+ inlineIndex: inlineIndex++,
154
+ source: compress(slice(source, element)),
155
+ });
156
+ }
157
+
158
+ const shared: string[] = [];
159
+ for (const raw of body) {
160
+ if (raw.type === 'ExportDefaultDeclaration') continue;
161
+ const node = unwrapExport(raw);
162
+ if (node.type === 'VariableDeclaration') {
163
+ for (const item of node.declarations) {
164
+ const name = item.id.type === 'Identifier' ? item.id.name : null;
165
+ if (excludedFromShared(name, named)) continue;
166
+ shared.push(compress(slice(source, item)));
167
+ }
168
+ continue;
169
+ }
170
+ if (
171
+ (node.type === 'FunctionDeclaration' || node.type === 'ClassDeclaration') &&
172
+ node.id &&
173
+ excludedFromShared(node.id.name, named)
174
+ )
175
+ continue;
176
+ shared.push(compress(slice(source, node)));
177
+ }
178
+
179
+ return { ok: true, pages, notes, shared: shared.join('\u0000') };
180
+ }
181
+
182
+ function entryKey(files: Map<string, Uint8Array>): string | null {
183
+ for (const name of ENTRY_NAMES) if (files.has(name)) return name;
184
+ return null;
185
+ }
186
+
187
+ function assetName(path: string): string | null {
188
+ return path.startsWith(ASSETS) && path.length > ASSETS.length ? path.slice(ASSETS.length) : null;
189
+ }
190
+
191
+ function sameBytes(a: Uint8Array | undefined, b: Uint8Array | undefined): boolean {
192
+ if (!a || !b) return a === b;
193
+ if (a.length !== b.length) return false;
194
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
195
+ return true;
196
+ }
197
+
198
+ function compareAssets(
199
+ local: Map<string, Uint8Array>,
200
+ packaged: Map<string, Uint8Array>,
201
+ ): DeckChanges['assets'] {
202
+ const added: string[] = [];
203
+ const changed: string[] = [];
204
+ const removed: string[] = [];
205
+ const names = new Set<string>();
206
+ for (const path of local.keys()) {
207
+ const name = assetName(path);
208
+ if (name) names.add(name);
209
+ }
210
+ for (const path of packaged.keys()) {
211
+ const name = assetName(path);
212
+ if (name) names.add(name);
213
+ }
214
+ for (const name of [...names].sort()) {
215
+ const a = local.get(`${ASSETS}${name}`);
216
+ const b = packaged.get(`${ASSETS}${name}`);
217
+ if (a && !b) removed.push(name);
218
+ else if (!a && b) added.push(name);
219
+ else if (!sameBytes(a, b)) changed.push(name);
220
+ }
221
+ return { added, changed, removed };
222
+ }
223
+
224
+ function compareOtherFiles(
225
+ local: Map<string, Uint8Array>,
226
+ packaged: Map<string, Uint8Array>,
227
+ entry: string | null,
228
+ ): boolean {
229
+ const paths = new Set<string>();
230
+ for (const path of local.keys()) paths.add(path);
231
+ for (const path of packaged.keys()) paths.add(path);
232
+ for (const path of paths) {
233
+ if (path === entry || assetName(path) !== null) continue;
234
+ if (!sameBytes(local.get(path), packaged.get(path))) return true;
235
+ }
236
+ return false;
237
+ }
238
+
239
+ function statusFor(
240
+ local: ParsedPage,
241
+ packaged: ParsedPage,
242
+ ): { status: PageStatus; notes: boolean } {
243
+ const moved = local.index !== packaged.index;
244
+ if (local.source !== packaged.source) return { status: 'changed', notes: false };
245
+ return { status: moved ? 'moved' : 'same', notes: false };
246
+ }
247
+
248
+ function notesChanged(
249
+ local: string[] | null,
250
+ localIndex: number,
251
+ packaged: string[] | null,
252
+ packagedIndex: number,
253
+ ): boolean {
254
+ return (local?.[localIndex] ?? '') !== (packaged?.[packagedIndex] ?? '');
255
+ }
256
+
257
+ function comparePages(local: ParsedDeck, packaged: ParsedDeck): PageChange[] {
258
+ const out: PageChange[] = [];
259
+ const named = new Map<string, { local: ParsedPage[]; packaged: ParsedPage[] }>();
260
+ const localInline: ParsedPage[] = [];
261
+ const packagedInline: ParsedPage[] = [];
262
+
263
+ for (const page of local.pages) {
264
+ if (page.name === null) {
265
+ localInline.push(page);
266
+ continue;
267
+ }
268
+ const entry = named.get(page.name) ?? { local: [], packaged: [] };
269
+ entry.local.push(page);
270
+ named.set(page.name, entry);
271
+ }
272
+ for (const page of packaged.pages) {
273
+ if (page.name === null) {
274
+ packagedInline.push(page);
275
+ continue;
276
+ }
277
+ const entry = named.get(page.name) ?? { local: [], packaged: [] };
278
+ entry.packaged.push(page);
279
+ named.set(page.name, entry);
280
+ }
281
+
282
+ for (const [name, entry] of named) {
283
+ const count = Math.max(entry.local.length, entry.packaged.length);
284
+ for (let k = 0; k < count; k++) {
285
+ const a = entry.local[k];
286
+ const b = entry.packaged[k];
287
+ if (a && b) {
288
+ const { status } = statusFor(a, b);
289
+ const notes = notesChanged(local.notes, a.index, packaged.notes, b.index);
290
+ out.push({
291
+ n: b.index + 1,
292
+ status: status === 'same' && notes ? 'changed' : status,
293
+ name,
294
+ notes,
295
+ notesOnly: a.source === b.source && notes,
296
+ });
297
+ continue;
298
+ }
299
+ if (b) out.push({ n: b.index + 1, status: 'added', name, notes: false, notesOnly: false });
300
+ else if (a)
301
+ out.push({ n: a.index + 1, status: 'removed', name, notes: false, notesOnly: false });
302
+ }
303
+ }
304
+
305
+ const inlineCount = Math.max(localInline.length, packagedInline.length);
306
+ for (let k = 0; k < inlineCount; k++) {
307
+ const a = localInline[k];
308
+ const b = packagedInline[k];
309
+ if (a && b) {
310
+ const { status } = statusFor(a, b);
311
+ const notes = notesChanged(local.notes, a.index, packaged.notes, b.index);
312
+ out.push({
313
+ n: b.index + 1,
314
+ status: status === 'same' && notes ? 'changed' : status,
315
+ name: null,
316
+ notes,
317
+ notesOnly: a.source === b.source && notes,
318
+ });
319
+ continue;
320
+ }
321
+ if (b)
322
+ out.push({ n: b.index + 1, status: 'added', name: null, notes: false, notesOnly: false });
323
+ else if (a)
324
+ out.push({ n: a.index + 1, status: 'removed', name: null, notes: false, notesOnly: false });
325
+ }
326
+
327
+ return out.sort((a, b) => a.n - b.n);
328
+ }
329
+
330
+ export function compareDeck(localFiles: DeckFiles, packagedFiles: DeckFiles): DeckChanges {
331
+ const local = toMap(localFiles);
332
+ const packaged = toMap(packagedFiles);
333
+ const entry = entryKey(local) ?? entryKey(packaged);
334
+ const assets = compareAssets(local, packaged);
335
+
336
+ if (entry === null) {
337
+ return {
338
+ pages: [],
339
+ shared: compareOtherFiles(local, packaged, entry),
340
+ assets,
341
+ readable: false,
342
+ };
343
+ }
344
+
345
+ const decoder = new TextDecoder();
346
+ const localDeck = parseDeck(decoder.decode(local.get(entry) ?? new Uint8Array()));
347
+ const packagedDeck = parseDeck(decoder.decode(packaged.get(entry) ?? new Uint8Array()));
348
+ const otherFilesChanged = compareOtherFiles(local, packaged, entry);
349
+
350
+ if (!localDeck.ok || !packagedDeck.ok) {
351
+ // Only the whole file can be compared: any entry or file difference counts.
352
+ const entryChanged = !sameBytes(local.get(entry), packaged.get(entry));
353
+ return {
354
+ pages: [],
355
+ shared: otherFilesChanged || entryChanged,
356
+ assets,
357
+ readable: false,
358
+ };
359
+ }
360
+
361
+ return {
362
+ pages: comparePages(localDeck, packagedDeck),
363
+ shared: localDeck.shared !== packagedDeck.shared || otherFilesChanged,
364
+ assets,
365
+ readable: true,
366
+ };
367
+ }
@@ -0,0 +1,84 @@
1
+ import { type DroppedFile, zipDroppedFolder } from './folder';
2
+
3
+ type Entry = {
4
+ isFile: boolean;
5
+ isDirectory: boolean;
6
+ name: string;
7
+ file?: (ok: (file: File) => void, fail?: (error: unknown) => void) => void;
8
+ createReader?: () => {
9
+ readEntries: (ok: (entries: Entry[]) => void, fail?: (error: unknown) => void) => void;
10
+ };
11
+ };
12
+
13
+ export type DroppedPackage = { kind: 'zip' | 'folder'; bytes: Uint8Array };
14
+
15
+ function readFile(file: File): Promise<Uint8Array> {
16
+ return file.arrayBuffer().then((buffer) => new Uint8Array(buffer));
17
+ }
18
+
19
+ function entryFile(entry: Entry): Promise<File> {
20
+ return new Promise((resolve, reject) => {
21
+ entry.file?.(resolve, reject) ?? reject(new Error('no file handle'));
22
+ });
23
+ }
24
+
25
+ async function readDirectory(entry: Entry): Promise<Entry[]> {
26
+ const reader = entry.createReader?.();
27
+ if (!reader) return [];
28
+ const all: Entry[] = [];
29
+ for (;;) {
30
+ const batch = await new Promise<Entry[]>((resolve, reject) =>
31
+ reader.readEntries(resolve, reject),
32
+ );
33
+ if (batch.length === 0) break;
34
+ all.push(...batch);
35
+ }
36
+ return all;
37
+ }
38
+
39
+ async function walk(entry: Entry, prefix: string, out: DroppedFile[]): Promise<void> {
40
+ const path = prefix === '' ? entry.name : `${prefix}/${entry.name}`;
41
+ if (entry.isFile) {
42
+ out.push({ path, bytes: await readFile(await entryFile(entry)) });
43
+ return;
44
+ }
45
+ if (!entry.isDirectory) return;
46
+ for (const child of await readDirectory(entry)) await walk(child, path, out);
47
+ }
48
+
49
+ function isZipName(name: string): boolean {
50
+ return name.toLowerCase().endsWith('.zip');
51
+ }
52
+
53
+ /**
54
+ * A drop can be the zip itself or, when Safari already unpacked it, the folder.
55
+ * Folders are read file by file and zipped again so both take the same route.
56
+ */
57
+ export async function readDropped(dataTransfer: DataTransfer): Promise<DroppedPackage | null> {
58
+ const items = Array.from(dataTransfer.items ?? []);
59
+ const entries: Entry[] = [];
60
+ for (const item of items) {
61
+ if (item.kind !== 'file') continue;
62
+ const entry = (
63
+ item as DataTransferItem & { webkitGetAsEntry?: () => Entry | null }
64
+ ).webkitGetAsEntry?.();
65
+ if (entry) entries.push(entry);
66
+ }
67
+
68
+ if (entries.length === 0) {
69
+ const files = Array.from(dataTransfer.files ?? []);
70
+ const zip = files.find((file) => isZipName(file.name));
71
+ return zip ? { kind: 'zip', bytes: await readFile(zip) } : null;
72
+ }
73
+
74
+ const zipEntry = entries.find((entry) => entry.isFile && isZipName(entry.name));
75
+ if (zipEntry) return { kind: 'zip', bytes: await readFile(await entryFile(zipEntry)) };
76
+
77
+ if (entries.some((entry) => entry.isDirectory)) {
78
+ const files: DroppedFile[] = [];
79
+ for (const entry of entries) await walk(entry, '', files);
80
+ return { kind: 'folder', bytes: await zipDroppedFolder(files) };
81
+ }
82
+
83
+ return null;
84
+ }
@@ -0,0 +1,42 @@
1
+ import { unzipSync } from 'fflate';
2
+ import { describe, expect, it } from 'vitest';
3
+ import { zipDroppedFolder } from './folder';
4
+
5
+ const bytes = (text: string) => new TextEncoder().encode(text);
6
+
7
+ function names(zip: Uint8Array): string[] {
8
+ return Object.keys(unzipSync(zip)).sort();
9
+ }
10
+
11
+ describe('zipDroppedFolder', () => {
12
+ it('keeps the folder paths exactly as they were', async () => {
13
+ const zip = await zipDroppedFolder([
14
+ { path: 'LemonRiver-files/manifest.json', bytes: bytes('{}') },
15
+ { path: 'LemonRiver-files/slides/alpha/index.tsx', bytes: bytes('export default [];') },
16
+ ]);
17
+ expect(names(zip)).toEqual([
18
+ 'LemonRiver-files/manifest.json',
19
+ 'LemonRiver-files/slides/alpha/index.tsx',
20
+ ]);
21
+ });
22
+
23
+ it('drops what Safari and Finder leave behind', async () => {
24
+ const zip = await zipDroppedFolder([
25
+ { path: 'LemonRiver-files/manifest.json', bytes: bytes('{}') },
26
+ { path: 'LemonRiver-files/.DS_Store', bytes: bytes('junk') },
27
+ { path: 'LemonRiver-files/slides/alpha/.DS_Store', bytes: bytes('junk') },
28
+ { path: '__MACOSX/LemonRiver-files/manifest.json', bytes: bytes('junk') },
29
+ { path: 'LemonRiver-files/__MACOSX/._index.tsx', bytes: bytes('junk') },
30
+ ]);
31
+ expect(names(zip)).toEqual(['LemonRiver-files/manifest.json']);
32
+ });
33
+
34
+ it('ignores paths that climb out or are empty', async () => {
35
+ const zip = await zipDroppedFolder([
36
+ { path: '../outside.txt', bytes: bytes('x') },
37
+ { path: '', bytes: bytes('x') },
38
+ { path: './LemonRiver-files/manifest.json', bytes: bytes('{}') },
39
+ ]);
40
+ expect(names(zip)).toEqual(['LemonRiver-files/manifest.json']);
41
+ });
42
+ });