@lemonriver/core 0.2.0 → 0.3.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 (120) hide show
  1. package/dist/{build-Df_xwIpg.js → build-Bqo69DWP.js} +1 -1
  2. package/dist/cli/bin.js +4 -4
  3. package/dist/{config-BjWCLoMQ.js → config-DJ5rkMMg.js} +1594 -974
  4. package/dist/{config-rMGCkz6i.d.ts → config-teo3kWz7.d.ts} +1 -1
  5. package/dist/{dev-Ctsx9IeO.js → dev-B2FJD5bJ.js} +2 -2
  6. package/dist/index.d.ts +2 -2
  7. package/dist/index.js +1 -1
  8. package/dist/locale/index.d.ts +1 -1
  9. package/dist/locale/index.js +1 -1
  10. package/dist/{preview-CJgcqsPk.js → preview-C93BOZL1.js} +1 -1
  11. package/dist/{types-8VUyA2bu.d.ts → types-DFK02XVv.d.ts} +0 -35
  12. package/dist/{update-BKOA3Z6o.js → update-DsxZBtwv.js} +2 -70
  13. package/dist/vite/index.d.ts +1 -1
  14. package/dist/vite/index.js +1 -1
  15. package/dist/{zh-tw-CeLrYwRE.js → zh-tw-DwTAZKa6.js} +6 -172
  16. package/package.json +1 -1
  17. package/src/app/app.tsx +5 -18
  18. package/src/app/components/agent/agent-panel.tsx +3 -0
  19. package/src/app/components/agent/agent-presence.tsx +2 -2
  20. package/src/app/components/agent/history-view.tsx +3 -2
  21. package/src/app/components/agent/transcript.tsx +15 -4
  22. package/src/app/components/asset-view.tsx +6 -6
  23. package/src/app/components/command/command-menu.tsx +2 -1
  24. package/src/app/components/inspector/asset-picker-dialog.tsx +7 -5
  25. package/src/app/components/inspector/comment-layer.tsx +2 -1
  26. package/src/app/components/inspector/inspector-panel.tsx +2 -2
  27. package/src/app/components/sidebar/sidebar-footer.tsx +1 -1
  28. package/src/app/components/sidebar/sidebar.tsx +3 -2
  29. package/src/app/components/themes/theme-detail.tsx +4 -2
  30. package/src/app/components/thumbnail-rail.tsx +1 -28
  31. package/src/app/index.html +2 -2
  32. package/src/app/lemonriver/agent/lemon.tsx +64 -0
  33. package/src/app/{components → lemonriver}/board/board-canvas.tsx +17 -17
  34. package/src/app/{routes/board.tsx → lemonriver/board/board-page.tsx} +16 -15
  35. package/src/app/{components → lemonriver}/board/layout.ts +1 -1
  36. package/src/app/lemonriver/board/model/cards.test.ts +239 -0
  37. package/src/app/lemonriver/board/model/cards.ts +234 -0
  38. package/src/app/lemonriver/board/model/structure.test.ts +101 -0
  39. package/src/app/lemonriver/board/model/structure.ts +82 -0
  40. package/src/app/{components → lemonriver}/board/page-node.tsx +34 -31
  41. package/src/app/{components → lemonriver}/board/use-board-cards.ts +6 -6
  42. package/src/app/{components → lemonriver}/board/use-board-columns.ts +7 -7
  43. package/src/app/{components → lemonriver}/board/use-page-order.ts +10 -6
  44. package/src/app/lemonriver/brand/app-icon.svg +44 -0
  45. package/src/app/lemonriver/brand/apple-touch-icon.png +0 -0
  46. package/src/app/lemonriver/brand/favicon-32.png +0 -0
  47. package/src/app/lemonriver/brand/mascot.tsx +59 -0
  48. package/src/app/lemonriver/brand/mascots/lemon-done.png +0 -0
  49. package/src/app/lemonriver/brand/mascots/lemon-idle.png +0 -0
  50. package/src/app/lemonriver/brand/mascots/lemon-needs-you.png +0 -0
  51. package/src/app/lemonriver/brand/mascots/lemon-thinking.png +0 -0
  52. package/src/app/lemonriver/brand/mascots/lemon-working.png +0 -0
  53. package/src/app/lemonriver/chrome/app-chrome.tsx +99 -0
  54. package/src/app/lemonriver/chrome/nav-row.tsx +34 -0
  55. package/src/app/lemonriver/chrome/not-found.tsx +34 -0
  56. package/src/app/lemonriver/chrome/sidebar-extras.tsx +57 -0
  57. package/src/app/lemonriver/chrome/use-slot.ts +23 -0
  58. package/src/app/lemonriver/features.test.ts +29 -0
  59. package/src/app/lemonriver/features.ts +26 -0
  60. package/src/app/lemonriver/feedback/export.ts +7 -0
  61. package/src/app/lemonriver/feedback/lemon-empty.tsx +54 -0
  62. package/src/app/lemonriver/feedback/offline-banner.tsx +41 -0
  63. package/src/app/lemonriver/feedback/pending-toast.test.ts +44 -0
  64. package/src/app/lemonriver/feedback/pending-toast.ts +39 -0
  65. package/src/app/lemonriver/feedback/toaster.tsx +34 -0
  66. package/src/app/lemonriver/feedback/upload.test.ts +26 -0
  67. package/src/app/lemonriver/feedback/upload.ts +19 -0
  68. package/src/app/lemonriver/home/brief-card.tsx +63 -0
  69. package/src/app/lemonriver/home/brief.test.ts +38 -0
  70. package/src/app/lemonriver/home/brief.ts +34 -0
  71. package/src/app/lemonriver/home/controls.tsx +93 -0
  72. package/src/app/lemonriver/home/deck-card.tsx +183 -0
  73. package/src/app/lemonriver/home/dialogs.tsx +292 -0
  74. package/src/app/lemonriver/home/home-page.tsx +335 -0
  75. package/src/app/lemonriver/home/sorting.test.ts +24 -0
  76. package/src/app/lemonriver/home/sorting.ts +59 -0
  77. package/src/app/lemonriver/home/time.test.ts +33 -0
  78. package/src/app/lemonriver/home/time.ts +33 -0
  79. package/src/app/lemonriver/home/use-deck-times.ts +27 -0
  80. package/src/app/lemonriver/home/use-delayed.ts +15 -0
  81. package/src/app/lemonriver/routes.test.tsx +37 -0
  82. package/src/app/lemonriver/routes.tsx +38 -0
  83. package/src/app/lemonriver/settings/settings-page.tsx +103 -0
  84. package/src/app/lemonriver/slide-extensions.tsx +73 -0
  85. package/src/app/lemonriver/text/all.ts +19 -0
  86. package/src/app/lemonriver/text/en.ts +106 -0
  87. package/src/app/lemonriver/text/es.ts +108 -0
  88. package/src/app/lemonriver/text/index.ts +9 -0
  89. package/src/app/lemonriver/text/ja.ts +106 -0
  90. package/src/app/lemonriver/text/text.test.ts +57 -0
  91. package/src/app/lemonriver/text/types.ts +111 -0
  92. package/src/app/lemonriver/text/zh-cn.ts +101 -0
  93. package/src/app/lemonriver/text/zh-tw.ts +101 -0
  94. package/src/app/lemonriver/theme/app.css +288 -0
  95. package/src/app/lemonriver/theme/controls.css +463 -0
  96. package/src/app/lemonriver/theme/index.css +3 -0
  97. package/src/app/lemonriver/theme/motion.ts +52 -0
  98. package/src/app/lemonriver/theme/pages.test.ts +66 -0
  99. package/src/app/lemonriver/theme/pages.ts +56 -0
  100. package/src/app/lemonriver/theme/theme-menu.tsx +64 -0
  101. package/src/app/lemonriver/theme/themes.test.ts +18 -0
  102. package/src/app/lemonriver/theme/themes.ts +16 -0
  103. package/src/app/lemonriver/theme/tokens.css +226 -0
  104. package/src/app/lemonriver/theme/use-theme.tsx +49 -0
  105. package/src/app/lemonriver/trash/api.test.ts +19 -0
  106. package/src/app/lemonriver/trash/api.ts +77 -0
  107. package/src/app/lemonriver/trash/trash-page.tsx +131 -0
  108. package/src/app/lib/pptx/raster.ts +1 -1
  109. package/src/app/main.tsx +8 -1
  110. package/src/app/routes/home-shell.tsx +4 -2
  111. package/src/app/routes/slide.tsx +12 -16
  112. package/src/app/styles.css +1 -0
  113. package/src/locale/en.ts +0 -35
  114. package/src/locale/es.ts +0 -34
  115. package/src/locale/ja.ts +0 -34
  116. package/src/locale/types.ts +0 -36
  117. package/src/locale/zh-cn.ts +3 -37
  118. package/src/locale/zh-tw.ts +3 -37
  119. /package/src/app/{components → lemonriver}/board/board.css +0 -0
  120. /package/src/app/{components → lemonriver}/board/layout.test.ts +0 -0
@@ -0,0 +1,239 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import {
3
+ adoptEntries,
4
+ type CardState,
5
+ carryCards,
6
+ entriesAfter,
7
+ isSettledKey,
8
+ linkCards,
9
+ linkedPairs,
10
+ originAfter,
11
+ type PageOp,
12
+ pageKeys,
13
+ patchCard,
14
+ sanitizeCards,
15
+ sanitizeLinks,
16
+ unlinkCards,
17
+ } from './cards.ts';
18
+
19
+ /** Runs one board operation the way the board does, entries and all. */
20
+ function run(state: CardState, entries: string[], op: PageOp) {
21
+ const count = entries.length;
22
+ const next = entriesAfter(op, entries, count);
23
+ const nextCount = op.kind === 'move' ? count : op.kind === 'delete' ? count - 1 : count + 1;
24
+ const carried = carryCards(
25
+ state,
26
+ pageKeys(entries, count),
27
+ pageKeys(next, nextCount),
28
+ originAfter(op, count),
29
+ );
30
+ return { state: carried, entries: next };
31
+ }
32
+
33
+ /** The memo each position shows, which is what a user actually sees. */
34
+ const memos = (state: CardState, entries: string[] | null | undefined, count: number) =>
35
+ pageKeys(entries, count).map((key) => state.cards[key]?.memo ?? null);
36
+
37
+ const deck = ['Cover', 'Agenda', 'Q3', 'Close'];
38
+
39
+ describe('pageKeys', () => {
40
+ it('keys pages by their entry in the deck', () => {
41
+ expect(pageKeys(deck, 4)).toEqual(deck);
42
+ });
43
+
44
+ it('tells repeated entries apart, so a duplicated page gets its own card', () => {
45
+ expect(pageKeys(['A', 'B', 'A', 'A'], 4)).toEqual(['A', 'B', 'A#2', 'A#3']);
46
+ });
47
+
48
+ it('falls back to positions when the entries cannot be read one per page', () => {
49
+ expect(pageKeys(null, 3)).toEqual(['@0', '@1', '@2']);
50
+ });
51
+
52
+ it('gives a deck caught mid-reload keys that match no card', () => {
53
+ const keys = pageKeys(['A', 'B'], 3);
54
+ expect(keys.every(isSettledKey)).toBe(false);
55
+ expect(pageKeys(undefined, 2).some(isSettledKey)).toBe(false);
56
+ });
57
+ });
58
+
59
+ describe('carryCards', () => {
60
+ const withMemo: CardState = { cards: { Q3: { memo: 'Q3 numbers missing' } }, links: [] };
61
+
62
+ it('keeps a memo on its page when the page moves', () => {
63
+ const after = run(withMemo, deck, { kind: 'move', from: 2, to: 0 });
64
+ expect(memos(after.state, after.entries, 4)).toEqual(['Q3 numbers missing', null, null, null]);
65
+ });
66
+
67
+ it('keeps a memo on its page when the deck is reordered outside the board', () => {
68
+ // No operation runs: the thumbnail rail rewrote the file and the entries reload.
69
+ expect(memos(withMemo, ['Q3', 'Cover', 'Agenda', 'Close'], 4)[0]).toBe('Q3 numbers missing');
70
+ });
71
+
72
+ it('never shifts a memo onto the neighbour when a page is added before it', () => {
73
+ const after = run(withMemo, deck, { kind: 'insert', index: 1 });
74
+ expect(memos(after.state, after.entries, 5)).toEqual([
75
+ null,
76
+ null,
77
+ null,
78
+ 'Q3 numbers missing',
79
+ null,
80
+ ]);
81
+ });
82
+
83
+ it('starts a duplicated page with a card of its own', () => {
84
+ const after = run(withMemo, deck, { kind: 'duplicate', index: 2 });
85
+ expect(memos(after.state, after.entries, 5)).toEqual([
86
+ null,
87
+ null,
88
+ 'Q3 numbers missing',
89
+ null,
90
+ null,
91
+ ]);
92
+ });
93
+
94
+ it('lets the copy keep its own memo while the original moves around it', () => {
95
+ let state: CardState = {
96
+ cards: { A: { memo: 'first' }, 'A#2': { memo: 'second' } },
97
+ links: [],
98
+ };
99
+ let entries = ['A', 'B', 'A'];
100
+ ({ state, entries } = run(state, entries, { kind: 'move', from: 0, to: 2 }));
101
+ expect(memos(state, entries, 3)).toEqual([null, 'second', 'first']);
102
+ });
103
+
104
+ it('takes a deleted page’s card and links with it', () => {
105
+ const state: CardState = {
106
+ cards: { Q3: { memo: 'gone' }, Close: { memo: 'kept' } },
107
+ links: [{ a: 'Q3', b: 'Cover' }],
108
+ };
109
+ const after = run(state, deck, { kind: 'delete', index: 2 });
110
+ expect(after.state.cards).toEqual({ Close: { memo: 'kept' } });
111
+ expect(after.state.links).toEqual([]);
112
+ });
113
+
114
+ it('does not hand a deleted copy’s memo to the original', () => {
115
+ const state: CardState = { cards: { 'A#2': { memo: 'copy only' } }, links: [] };
116
+ const after = run(state, ['A', 'A'], { kind: 'delete', index: 1 });
117
+ expect(memos(after.state, after.entries, 1)).toEqual([null]);
118
+ });
119
+
120
+ it('re-keys every page when the deck is keyed by position', () => {
121
+ const state: CardState = { cards: { '@2': { memo: 'third page' } }, links: [] };
122
+ const op: PageOp = { kind: 'move', from: 2, to: 0 };
123
+ const carried = carryCards(state, pageKeys(null, 4), pageKeys(null, 4), originAfter(op, 4));
124
+ expect(memos(carried, null, 4)).toEqual(['third page', null, null, null]);
125
+ });
126
+
127
+ it('leaves data for a page the deck does not have right now where it is', () => {
128
+ const state: CardState = { cards: { Gone: { memo: 'parked' } }, links: [] };
129
+ const after = run(state, deck, { kind: 'move', from: 0, to: 3 });
130
+ expect(after.state.cards.Gone).toEqual({ memo: 'parked' });
131
+ });
132
+
133
+ it('starts a new copy clean even when an earlier copy left data under the same key', () => {
134
+ // The first copy was deleted from the thumbnail rail, so its card was never cleared.
135
+ const state: CardState = {
136
+ cards: { 'A#2': { memo: 'old copy' } },
137
+ links: [{ a: 'A#2', b: 'B' }],
138
+ };
139
+ const after = run(state, ['A', 'B'], { kind: 'duplicate', index: 0 });
140
+ expect(memos(after.state, after.entries, 3)).toEqual([null, null, null]);
141
+ expect(after.state.links).toEqual([]);
142
+ });
143
+
144
+ it('keeps a page’s own card when it is pushed onto a position that holds leftover data', () => {
145
+ // A deck keyed by position that once had five pages: "@4" is left over.
146
+ const state: CardState = {
147
+ cards: { '@3': { memo: 'last page' }, '@4': { memo: 'leftover' } },
148
+ links: [],
149
+ };
150
+ const op: PageOp = { kind: 'insert', index: 1 };
151
+ const carried = carryCards(state, pageKeys(null, 4), pageKeys(null, 5), originAfter(op, 4));
152
+ expect(memos(carried, null, 5)).toEqual([null, null, null, null, 'last page']);
153
+ });
154
+ });
155
+
156
+ describe('adoptEntries', () => {
157
+ it('moves a blank page’s memo onto the name the deck gave it', () => {
158
+ let state: CardState = { cards: {}, links: [] };
159
+ let entries: string[] = ['Cover', 'Close'];
160
+ ({ state, entries } = run(state, entries, { kind: 'insert', index: 1 }));
161
+ const blankKey = pageKeys(entries, 3)[1];
162
+ state = { ...state, cards: { [blankKey]: { memo: 'draft me' } } };
163
+
164
+ const named = ['Cover', 'NewPage1', 'Close'];
165
+ const adopted = adoptEntries(state, entries, named);
166
+ expect(memos(adopted, named, 3)).toEqual([null, 'draft me', null]);
167
+ });
168
+
169
+ it('clears leftovers from an older page that used the same name', () => {
170
+ const state: CardState = {
171
+ cards: { NewPage1: { memo: 'stale' } },
172
+ links: [{ a: 'NewPage1', b: 'Cover' }],
173
+ };
174
+ const { entries } = run(state, ['Cover', 'Close'], { kind: 'insert', index: 1 });
175
+ const adopted = adoptEntries(state, entries, ['Cover', 'NewPage1', 'Close']);
176
+ expect(adopted.cards).toEqual({});
177
+ expect(adopted.links).toEqual([]);
178
+ });
179
+
180
+ it('changes nothing when no blank page is waiting for a name', () => {
181
+ const state: CardState = { cards: { Cover: { memo: 'x' } }, links: [] };
182
+ expect(adoptEntries(state, deck, deck)).toBe(state);
183
+ });
184
+ });
185
+
186
+ describe('links', () => {
187
+ it('records a link once, whichever way it is drawn', () => {
188
+ const links = linkCards(linkCards([], 'A', 'B'), 'B', 'A');
189
+ expect(links).toEqual([{ a: 'A', b: 'B' }]);
190
+ });
191
+
192
+ it('never links a card to itself', () => {
193
+ expect(linkCards([], 'A', 'A')).toEqual([]);
194
+ });
195
+
196
+ it('removes a link drawn the other way round', () => {
197
+ expect(unlinkCards([{ a: 'A', b: 'B' }], 'B', 'A')).toEqual([]);
198
+ });
199
+
200
+ it('follows both pages when the deck is reordered', () => {
201
+ const keys = ['Close', 'Cover', 'Q3', 'Agenda'];
202
+ expect(linkedPairs(keys, [{ a: 'Cover', b: 'Close' }])).toEqual([[1, 0]]);
203
+ });
204
+
205
+ it('hides a link whose page is not in the deck', () => {
206
+ expect(linkedPairs(deck, [{ a: 'Cover', b: 'Gone' }])).toEqual([]);
207
+ });
208
+ });
209
+
210
+ describe('patchCard', () => {
211
+ it('sets and clears fields one at a time', () => {
212
+ let cards = patchCard({}, 'A', { title: 'Market', status: 'doing' });
213
+ expect(cards).toEqual({ A: { title: 'Market', status: 'doing' } });
214
+ cards = patchCard(cards, 'A', { status: null });
215
+ expect(cards).toEqual({ A: { title: 'Market' } });
216
+ });
217
+
218
+ it('drops a card once nothing is left on it', () => {
219
+ expect(patchCard({ A: { memo: 'x' } }, 'A', { memo: '' })).toEqual({});
220
+ });
221
+ });
222
+
223
+ describe('sanitize', () => {
224
+ it('keeps only the fields and statuses the board knows', () => {
225
+ expect(
226
+ sanitizeCards({
227
+ A: { title: ' Intro ', status: 'doing', extra: 1 },
228
+ B: { status: 'bogus' },
229
+ C: 'nope',
230
+ }),
231
+ ).toEqual({ A: { title: 'Intro', status: 'doing' } });
232
+ });
233
+
234
+ it('drops malformed and duplicate links', () => {
235
+ expect(sanitizeLinks([{ a: 'A', b: 'B' }, { a: 'B', b: 'A' }, { a: 'A' }, null])).toEqual([
236
+ { a: 'A', b: 'B' },
237
+ ]);
238
+ });
239
+ });
@@ -0,0 +1,234 @@
1
+ export const CARD_STATUSES = ['todo', 'doing', 'review', 'done'] as const;
2
+ export type CardStatus = (typeof CARD_STATUSES)[number];
3
+
4
+ /** What the board knows about a page that the deck never sees. */
5
+ export type BoardCard = { title?: string; status?: CardStatus; memo?: string };
6
+ export type BoardCards = Record<string, BoardCard>;
7
+ /** No direction, and no say in the deck's order. */
8
+ export type BoardLink = { a: string; b: string };
9
+ export type CardState = { cards: BoardCards; links: BoardLink[] };
10
+ /** `null` or an empty string clears a field. */
11
+ export type CardPatch = { title?: string | null; status?: CardStatus | null; memo?: string | null };
12
+
13
+ const TITLE_MAX = 80;
14
+ const MEMO_MAX = 2000;
15
+ const PENDING = '\u0000pending:';
16
+ /** Holds a blank page's slot until the deck reloads with the name the server gave it. */
17
+ const BLANK_ENTRY = '\u0000blank';
18
+
19
+ /** A key that names a page for good, so the board may store data under it. */
20
+ export const isSettledKey = (key: string) => !key.startsWith(PENDING);
21
+
22
+ export function isCardStatus(value: unknown): value is CardStatus {
23
+ return typeof value === 'string' && (CARD_STATUSES as readonly string[]).includes(value);
24
+ }
25
+
26
+ function cleanCard(raw: unknown): BoardCard | null {
27
+ if (!raw || typeof raw !== 'object') return null;
28
+ const { title, status, memo } = raw as Record<string, unknown>;
29
+ const card: BoardCard = {};
30
+ if (typeof title === 'string' && title.trim()) card.title = title.trim().slice(0, TITLE_MAX);
31
+ if (isCardStatus(status)) card.status = status;
32
+ if (typeof memo === 'string' && memo.trim()) card.memo = memo.trim().slice(0, MEMO_MAX);
33
+ return Object.keys(card).length > 0 ? card : null;
34
+ }
35
+
36
+ export function sanitizeCards(raw: unknown): BoardCards {
37
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {};
38
+ const cards: BoardCards = {};
39
+ for (const [key, value] of Object.entries(raw)) {
40
+ const card = cleanCard(value);
41
+ if (key && card) cards[key] = card;
42
+ }
43
+ return cards;
44
+ }
45
+
46
+ const sameLink = (link: BoardLink, a: string, b: string) =>
47
+ (link.a === a && link.b === b) || (link.a === b && link.b === a);
48
+
49
+ export function linkCards(links: BoardLink[], a: string, b: string): BoardLink[] {
50
+ if (!a || !b || a === b || links.some((link) => sameLink(link, a, b))) return links;
51
+ return [...links, { a, b }];
52
+ }
53
+
54
+ export function unlinkCards(links: BoardLink[], a: string, b: string): BoardLink[] {
55
+ const kept = links.filter((link) => !sameLink(link, a, b));
56
+ return kept.length === links.length ? links : kept;
57
+ }
58
+
59
+ export function sanitizeLinks(raw: unknown): BoardLink[] {
60
+ if (!Array.isArray(raw)) return [];
61
+ return raw.reduce<BoardLink[]>((links, item) => {
62
+ const { a, b } = (item ?? {}) as { a?: unknown; b?: unknown };
63
+ return typeof a === 'string' && typeof b === 'string' ? linkCards(links, a, b) : links;
64
+ }, []);
65
+ }
66
+
67
+ export function patchCard(cards: BoardCards, key: string, patch: CardPatch): BoardCards {
68
+ const merged: Record<string, unknown> = { ...cards[key] };
69
+ for (const field of ['title', 'status', 'memo'] as const) {
70
+ if (!(field in patch)) continue;
71
+ const value = patch[field];
72
+ if (value == null || value === '') delete merged[field];
73
+ else merged[field] = value;
74
+ }
75
+ const card = cleanCard(merged);
76
+ const next = { ...cards };
77
+ if (card) next[key] = card;
78
+ else delete next[key];
79
+ return next;
80
+ }
81
+
82
+ /**
83
+ * Keys a page by its entry in the page array, so its card follows it through a
84
+ * reorder made anywhere — the thumbnail rail, or an agent editing the file —
85
+ * and a page added elsewhere never shifts a memo onto its neighbour. A repeated
86
+ * entry, which is what duplicating a page produces, is told apart by
87
+ * occurrence, so the copy starts with a card of its own.
88
+ *
89
+ * `null` entries mean the array cannot be read one entry per page (a spread
90
+ * stands for any number of pages), so pages fall back to their positions.
91
+ * Entries not loaded yet, or disagreeing with the page count while the deck
92
+ * reloads, give keys that match no card, so a memo never flashes onto the
93
+ * wrong page.
94
+ */
95
+ export function pageKeys(entries: string[] | null | undefined, count: number): string[] {
96
+ if (entries === null) return Array.from({ length: count }, (_, i) => `@${i}`);
97
+ if (entries === undefined || entries.length !== count) {
98
+ return Array.from({ length: count }, (_, i) => `${PENDING}${i}`);
99
+ }
100
+ const seen = new Map<string, number>();
101
+ return entries.map((entry) => {
102
+ const n = (seen.get(entry) ?? 0) + 1;
103
+ seen.set(entry, n);
104
+ return n === 1 ? entry : `${entry}#${n}`;
105
+ });
106
+ }
107
+
108
+ /** Position pairs for the links whose pages are both in the deck. */
109
+ export function linkedPairs(keys: string[], links: BoardLink[]): [number, number][] {
110
+ const at = new Map(keys.map((key, i) => [key, i]));
111
+ return links.flatMap((link) => {
112
+ const a = at.get(link.a);
113
+ const b = at.get(link.b);
114
+ return a === undefined || b === undefined ? [] : [[a, b] as [number, number]];
115
+ });
116
+ }
117
+
118
+ export type PageOp =
119
+ | { kind: 'move'; from: number; to: number }
120
+ | { kind: 'duplicate'; index: number }
121
+ | { kind: 'insert'; index: number }
122
+ | { kind: 'delete'; index: number };
123
+
124
+ /** Where each page sat before `op`; -1 marks the page `op` created. */
125
+ export function originAfter(op: PageOp, total: number): number[] {
126
+ const order = Array.from({ length: total }, (_, i) => i);
127
+ switch (op.kind) {
128
+ case 'move': {
129
+ const [moved] = order.splice(op.from, 1);
130
+ order.splice(op.to, 0, moved);
131
+ return order;
132
+ }
133
+ case 'duplicate':
134
+ order.splice(op.index + 1, 0, -1);
135
+ return order;
136
+ case 'insert':
137
+ order.splice(op.index, 0, -1);
138
+ return order;
139
+ case 'delete':
140
+ order.splice(op.index, 1);
141
+ return order;
142
+ }
143
+ }
144
+
145
+ export function entriesAfter<E extends string[] | null | undefined>(
146
+ op: PageOp,
147
+ entries: E,
148
+ count: number,
149
+ ): E {
150
+ if (!entries || entries.length !== count) return entries;
151
+ return originAfter(op, count).map((from) => {
152
+ if (from >= 0) return entries[from];
153
+ return op.kind === 'duplicate' ? entries[op.index] : BLANK_ENTRY;
154
+ }) as E;
155
+ }
156
+
157
+ /**
158
+ * Carries cards and links through a page operation the board made. Only pages
159
+ * whose key the operation changed are re-keyed — the copies of a duplicated
160
+ * page, or every page when the deck is keyed by position — and a deleted page
161
+ * takes its card and links with it. Data under a key the deck does not have
162
+ * right now stays put, so a page whose entry comes back finds its card again;
163
+ * it only gives way to a page this operation created under the same key.
164
+ */
165
+ export function carryCards(
166
+ state: CardState,
167
+ before: string[],
168
+ after: string[],
169
+ origin: number[],
170
+ ): CardState {
171
+ const rename = new Map<string, string>();
172
+ const created = new Set<string>();
173
+ origin.forEach((from, i) => {
174
+ if (from >= 0 && from < before.length) rename.set(before[from], after[i]);
175
+ else created.add(after[i]);
176
+ });
177
+ const live = new Set(before);
178
+ const resolve = (key: string): string | null => {
179
+ const next = live.has(key) ? (rename.get(key) ?? null) : key;
180
+ return next !== null && !created.has(next) ? next : null;
181
+ };
182
+
183
+ const cards: BoardCards = {};
184
+ // Live pages go last, so a page renumbered onto a key that also holds
185
+ // leftover data keeps its own card.
186
+ for (const livePass of [false, true]) {
187
+ for (const [key, card] of Object.entries(state.cards)) {
188
+ if (live.has(key) !== livePass) continue;
189
+ const next = resolve(key);
190
+ if (next !== null) cards[next] = card;
191
+ }
192
+ }
193
+ const links = state.links.reduce<BoardLink[]>((kept, link) => {
194
+ const a = resolve(link.a);
195
+ const b = resolve(link.b);
196
+ return a !== null && b !== null ? linkCards(kept, a, b) : kept;
197
+ }, []);
198
+ return { cards, links };
199
+ }
200
+
201
+ /**
202
+ * Once the deck reloads, a blank page added on the board learns its real name.
203
+ * Whatever it collected in the meantime moves onto that name, and anything left
204
+ * over under the name from an older page goes: the blank page is new.
205
+ */
206
+ export function adoptEntries(
207
+ state: CardState,
208
+ before: string[] | null | undefined,
209
+ after: string[] | null | undefined,
210
+ ): CardState {
211
+ if (!before || !after || before.length !== after.length) return state;
212
+ const from = pageKeys(before, before.length);
213
+ const to = pageKeys(after, after.length);
214
+ const rename = new Map<string, string>();
215
+ before.forEach((entry, i) => {
216
+ if (entry === BLANK_ENTRY && from[i] !== to[i]) rename.set(from[i], to[i]);
217
+ });
218
+ if (rename.size === 0) return state;
219
+
220
+ const targets = new Set(rename.values());
221
+ const cards = { ...state.cards };
222
+ for (const [blank, named] of rename) {
223
+ if (cards[blank]) cards[named] = cards[blank];
224
+ else delete cards[named];
225
+ delete cards[blank];
226
+ }
227
+ const links = state.links
228
+ .filter((link) => !targets.has(link.a) && !targets.has(link.b))
229
+ .reduce<BoardLink[]>(
230
+ (kept, link) => linkCards(kept, rename.get(link.a) ?? link.a, rename.get(link.b) ?? link.b),
231
+ [],
232
+ );
233
+ return { cards, links };
234
+ }
@@ -0,0 +1,101 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import {
3
+ type BoardColumn,
4
+ columnOfPosition,
5
+ columnsAfterMove,
6
+ reconcileColumns,
7
+ sanitizeStructure,
8
+ } from './structure.ts';
9
+
10
+ const deck = (): BoardColumn[] => [
11
+ { title: 'Cover', size: 2 },
12
+ { title: 'Chapter 1', size: 6 },
13
+ { title: 'Chapter 2', size: 8 },
14
+ ];
15
+
16
+ describe('columnOfPosition', () => {
17
+ it('maps a deck position to the column holding it', () => {
18
+ const columns = deck();
19
+ expect([0, 1, 2, 7, 8, 15].map((p) => columnOfPosition(columns, p))).toEqual([
20
+ 0, 0, 1, 1, 2, 2,
21
+ ]);
22
+ });
23
+
24
+ it('skips empty columns instead of claiming a position for them', () => {
25
+ const columns = [
26
+ { title: 'A', size: 1 },
27
+ { title: 'B', size: 0 },
28
+ { title: 'C', size: 1 },
29
+ ];
30
+ expect(columnOfPosition(columns, 1)).toBe(2);
31
+ });
32
+ });
33
+
34
+ describe('columnsAfterMove', () => {
35
+ it('hands exactly one page over when a card crosses a boundary', () => {
36
+ expect(columnsAfterMove(deck(), 2, 10).map((c) => c.size)).toEqual([2, 5, 9]);
37
+ });
38
+
39
+ it('leaves the structure alone when a card moves inside its own column', () => {
40
+ const columns = deck();
41
+ expect(columnsAfterMove(columns, 3, 6)).toBe(columns);
42
+ });
43
+
44
+ it('keeps a chapter together when the page that heads it moves away', () => {
45
+ // The reported defect: dragging a chapter page into another chapter used to
46
+ // re-group the deck, so the five pages it headed jumped column with it. The
47
+ // structure is the board's own now, so only the dragged page changes column.
48
+ const after = columnsAfterMove(deck(), 2, 12);
49
+ expect(after.map((c) => c.size)).toEqual([2, 5, 9]);
50
+ expect(after.map((c) => c.title)).toEqual(['Cover', 'Chapter 1', 'Chapter 2']);
51
+ });
52
+ });
53
+
54
+ describe('reconcileColumns', () => {
55
+ it('leaves a structure that already matches the deck', () => {
56
+ expect(reconcileColumns(deck(), 16).map((c) => c.size)).toEqual([2, 6, 8]);
57
+ });
58
+
59
+ it('gives pages added outside the board to the last column', () => {
60
+ expect(reconcileColumns(deck(), 18).map((c) => c.size)).toEqual([2, 6, 10]);
61
+ });
62
+
63
+ it('takes pages deleted outside the board off the end', () => {
64
+ expect(reconcileColumns(deck(), 12).map((c) => c.size)).toEqual([2, 6, 4]);
65
+ });
66
+
67
+ it('drops trailing columns a deletion emptied rather than leaving dead labels', () => {
68
+ expect(reconcileColumns(deck(), 8).map((c) => c.title)).toEqual(['Cover', 'Chapter 1']);
69
+ });
70
+
71
+ it('always leaves one column for a deck that still has pages', () => {
72
+ expect(reconcileColumns([], 4)).toEqual([{ title: '', size: 4 }]);
73
+ expect(reconcileColumns(deck(), 1).map((c) => c.size)).toEqual([1]);
74
+ });
75
+
76
+ it('reports no columns for an empty deck', () => {
77
+ expect(reconcileColumns(deck(), 0)).toEqual([]);
78
+ });
79
+ });
80
+
81
+ describe('sanitizeStructure', () => {
82
+ it('accepts a stored structure', () => {
83
+ expect(sanitizeStructure({ columns: [{ title: 'A', size: 2 }] })).toEqual({
84
+ columns: [{ title: 'A', size: 2 }],
85
+ });
86
+ });
87
+
88
+ it('refuses anything that is not a column list', () => {
89
+ expect(sanitizeStructure(null)).toBeNull();
90
+ expect(sanitizeStructure({})).toBeNull();
91
+ expect(sanitizeStructure({ columns: 'nope' })).toBeNull();
92
+ expect(sanitizeStructure({ columns: [{ title: 'A', size: -1 }] })).toBeNull();
93
+ expect(sanitizeStructure({ columns: [{ title: 'A', size: 1.5 }] })).toBeNull();
94
+ });
95
+
96
+ it('fills in a missing title rather than dropping the column', () => {
97
+ expect(sanitizeStructure({ columns: [{ size: 3 }] })).toEqual({
98
+ columns: [{ title: '', size: 3 }],
99
+ });
100
+ });
101
+ });
@@ -0,0 +1,82 @@
1
+ /**
2
+ * The board's own structure, stored outside the deck: a deck file never learns
3
+ * that a board exists. Columns hold a count rather than page ids, so reordering
4
+ * a deck can never strand the structure — only the page count has to agree.
5
+ */
6
+ export type BoardColumn = { title: string; size: number };
7
+ export type BoardStructure = { columns: BoardColumn[] };
8
+
9
+ export function sanitizeStructure(parsed: unknown): BoardStructure | null {
10
+ if (!parsed || typeof parsed !== 'object') return null;
11
+ const columns = (parsed as { columns?: unknown }).columns;
12
+ if (!Array.isArray(columns)) return null;
13
+ const cleaned = columns.flatMap((column) => {
14
+ if (!column || typeof column !== 'object') return [];
15
+ const { title, size } = column as { title?: unknown; size?: unknown };
16
+ if (typeof size !== 'number' || !Number.isInteger(size) || size < 0) return [];
17
+ return [{ title: typeof title === 'string' ? title : '', size }];
18
+ });
19
+ return cleaned.length > 0 ? { columns: cleaned } : null;
20
+ }
21
+
22
+ /**
23
+ * Keeps a stored structure usable after the deck changed behind the board's
24
+ * back: pages added outside the board join the last column, and pages deleted
25
+ * outside it come off the end.
26
+ */
27
+ export function reconcileColumns(columns: BoardColumn[], pageCount: number): BoardColumn[] {
28
+ if (pageCount <= 0) return [];
29
+ const kept = columns.map((column) => ({ ...column }));
30
+ if (kept.length === 0) return [{ title: '', size: pageCount }];
31
+
32
+ let total = kept.reduce((sum, column) => sum + column.size, 0);
33
+ if (total === pageCount) return kept;
34
+
35
+ if (total < pageCount) {
36
+ kept[kept.length - 1].size += pageCount - total;
37
+ return kept;
38
+ }
39
+ for (let i = kept.length - 1; i >= 0 && total > pageCount; i--) {
40
+ const drop = Math.min(kept[i].size, total - pageCount);
41
+ kept[i].size -= drop;
42
+ total -= drop;
43
+ }
44
+ // A column emptied by deletions keeps its title; only trailing empties go, so
45
+ // the board does not accumulate labels for chapters that no longer exist.
46
+ while (kept.length > 1 && kept[kept.length - 1].size === 0) kept.pop();
47
+ return kept;
48
+ }
49
+
50
+ /** Column index that owns a position, and where each column starts. */
51
+ export function columnStarts(columns: BoardColumn[]): number[] {
52
+ const starts: number[] = [];
53
+ let at = 0;
54
+ for (const column of columns) {
55
+ starts.push(at);
56
+ at += column.size;
57
+ }
58
+ return starts;
59
+ }
60
+
61
+ export function columnOfPosition(columns: BoardColumn[], position: number): number {
62
+ const starts = columnStarts(columns);
63
+ for (let i = starts.length - 1; i >= 0; i--) {
64
+ if (position >= starts[i]) return i;
65
+ }
66
+ return 0;
67
+ }
68
+
69
+ /**
70
+ * Moving a card across a column boundary hands one page from one column to the
71
+ * other. Nothing else about the structure moves — a chapter divider is an
72
+ * ordinary card, so the pages it used to head keep their own column.
73
+ */
74
+ export function columnsAfterMove(columns: BoardColumn[], from: number, to: number): BoardColumn[] {
75
+ const source = columnOfPosition(columns, from);
76
+ const target = columnOfPosition(columns, to);
77
+ if (source === target) return columns;
78
+ const next = columns.map((column) => ({ ...column }));
79
+ next[source].size -= 1;
80
+ next[target].size += 1;
81
+ return next;
82
+ }