@lemonriver/core 0.4.0 → 0.6.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 (115) hide show
  1. package/README.md +14 -4
  2. package/dist/{build-Nl7EeJ6x.js → build-RlcGG-Ve.js} +1 -1
  3. package/dist/cli/bin.js +4 -4
  4. package/dist/{config-CpC0nM3r.js → config-BJT87wE9.js} +4756 -2012
  5. package/dist/{dev-BB3THd5I.js → dev-DR-j_xda.js} +2 -2
  6. package/dist/{preview-BGjgTg7H.js → preview-BTAhTb5B.js} +1 -1
  7. package/dist/{update-DsxZBtwv.js → update-CMRxtTc9.js} +18 -8
  8. package/dist/vite/index.js +1 -1
  9. package/package.json +2 -2
  10. package/src/agent/types.ts +14 -2
  11. package/src/app/components/agent/agent-panel.tsx +17 -5
  12. package/src/app/components/agent/connect-view.tsx +1 -1
  13. package/src/app/components/agent/provider-logo.tsx +10 -1
  14. package/src/app/lemonriver/agent/provider-marks.tsx +53 -0
  15. package/src/app/lemonriver/agent-providers/section.tsx +75 -0
  16. package/src/app/lemonriver/agent-providers/use-providers.ts +61 -0
  17. package/src/app/lemonriver/board/blocks/block-panel.tsx +666 -0
  18. package/src/app/lemonriver/board/blocks/cache.ts +28 -0
  19. package/src/app/lemonriver/board/blocks/change-list.tsx +189 -0
  20. package/src/app/lemonriver/board/blocks/classify.test.ts +209 -0
  21. package/src/app/lemonriver/board/blocks/classify.ts +152 -0
  22. package/src/app/lemonriver/board/blocks/snapshot.ts +116 -0
  23. package/src/app/lemonriver/board/board-canvas.tsx +627 -104
  24. package/src/app/lemonriver/board/board-page.tsx +1702 -91
  25. package/src/app/lemonriver/board/board.css +58 -7
  26. package/src/app/lemonriver/board/layout.test.ts +84 -0
  27. package/src/app/lemonriver/board/layout.ts +112 -11
  28. package/src/app/lemonriver/board/model/agent-tasks.test.ts +200 -0
  29. package/src/app/lemonriver/board/model/agent-tasks.ts +223 -0
  30. package/src/app/lemonriver/board/model/apply-prompt.test.ts +121 -0
  31. package/src/app/lemonriver/board/model/apply-prompt.ts +115 -0
  32. package/src/app/lemonriver/board/model/apply.ts +71 -0
  33. package/src/app/lemonriver/board/model/cards.test.ts +95 -2
  34. package/src/app/lemonriver/board/model/cards.ts +88 -20
  35. package/src/app/lemonriver/board/model/changes.test.ts +244 -0
  36. package/src/app/lemonriver/board/model/changes.ts +268 -0
  37. package/src/app/lemonriver/board/model/filter.test.ts +50 -0
  38. package/src/app/lemonriver/board/model/filter.ts +42 -0
  39. package/src/app/lemonriver/board/model/history.test.ts +71 -0
  40. package/src/app/lemonriver/board/model/history.ts +51 -0
  41. package/src/app/lemonriver/board/model/restructure.test.ts +205 -0
  42. package/src/app/lemonriver/board/model/restructure.ts +169 -0
  43. package/src/app/lemonriver/board/model/self-check.test.ts +329 -0
  44. package/src/app/lemonriver/board/model/self-check.ts +489 -0
  45. package/src/app/lemonriver/board/model/structure.test.ts +249 -0
  46. package/src/app/lemonriver/board/model/structure.ts +209 -0
  47. package/src/app/lemonriver/board/model/timing.test.ts +113 -0
  48. package/src/app/lemonriver/board/model/timing.ts +117 -0
  49. package/src/app/lemonriver/board/page-node.tsx +258 -55
  50. package/src/app/lemonriver/board/self-check-jump.ts +23 -0
  51. package/src/app/lemonriver/board/self-check-panel.tsx +272 -0
  52. package/src/app/lemonriver/board/self-check-runner.tsx +150 -0
  53. package/src/app/lemonriver/board/status-style.ts +25 -0
  54. package/src/app/lemonriver/board/use-board-apply.ts +206 -0
  55. package/src/app/lemonriver/board/use-board-cards.ts +108 -5
  56. package/src/app/lemonriver/board/use-board-changes.ts +108 -0
  57. package/src/app/lemonriver/board/use-board-columns.ts +37 -56
  58. package/src/app/lemonriver/board/use-board-comments.ts +36 -0
  59. package/src/app/lemonriver/board/use-board-restructures.ts +107 -0
  60. package/src/app/lemonriver/board/use-history.ts +86 -0
  61. package/src/app/lemonriver/board/use-page-order.ts +65 -38
  62. package/src/app/lemonriver/board/use-self-check.ts +117 -0
  63. package/src/app/lemonriver/board/use-target-minutes.ts +47 -0
  64. package/src/app/lemonriver/board/views/block-readings.tsx +46 -0
  65. package/src/app/lemonriver/board/views/list-view.tsx +356 -0
  66. package/src/app/lemonriver/board/views/progress.tsx +32 -0
  67. package/src/app/lemonriver/board/views/timeline-view.tsx +341 -0
  68. package/src/app/lemonriver/chrome/filter-pill.tsx +30 -0
  69. package/src/app/lemonriver/chrome/sidebar-extras.tsx +12 -1
  70. package/src/app/lemonriver/features.test.ts +5 -0
  71. package/src/app/lemonriver/features.ts +2 -1
  72. package/src/app/lemonriver/home/deck-card.tsx +10 -0
  73. package/src/app/lemonriver/home/home-page.tsx +55 -6
  74. package/src/app/lemonriver/home/use-deck-times.ts +4 -1
  75. package/src/app/lemonriver/outline/build-team.tsx +42 -0
  76. package/src/app/lemonriver/outline/describe-page.tsx +128 -27
  77. package/src/app/lemonriver/outline/draft.ts +38 -0
  78. package/src/app/lemonriver/outline/model.test.ts +118 -0
  79. package/src/app/lemonriver/outline/model.ts +92 -7
  80. package/src/app/lemonriver/outline/outline-page.tsx +90 -7
  81. package/src/app/lemonriver/outline/pick-style.tsx +282 -0
  82. package/src/app/lemonriver/routes.test.tsx +17 -5
  83. package/src/app/lemonriver/routes.tsx +28 -0
  84. package/src/app/lemonriver/settings/settings-page.tsx +3 -0
  85. package/src/app/lemonriver/slide-extensions.tsx +14 -2
  86. package/src/app/lemonriver/templates/client.ts +60 -0
  87. package/src/app/lemonriver/templates/demo-page.tsx +79 -0
  88. package/src/app/lemonriver/templates/knobs.test.ts +62 -0
  89. package/src/app/lemonriver/templates/knobs.ts +62 -0
  90. package/src/app/lemonriver/templates/library-page.tsx +292 -0
  91. package/src/app/lemonriver/templates/model.test.ts +175 -0
  92. package/src/app/lemonriver/templates/model.ts +339 -0
  93. package/src/app/lemonriver/templates/preview-content.test.ts +117 -0
  94. package/src/app/lemonriver/templates/preview-content.ts +149 -0
  95. package/src/app/lemonriver/templates/recommend.test.ts +71 -0
  96. package/src/app/lemonriver/templates/recommend.ts +72 -0
  97. package/src/app/lemonriver/templates/use-library.ts +58 -0
  98. package/src/app/lemonriver/templates/virtual.d.ts +28 -0
  99. package/src/app/lemonriver/text/en.ts +228 -0
  100. package/src/app/lemonriver/text/es.ts +220 -0
  101. package/src/app/lemonriver/text/ja.ts +220 -0
  102. package/src/app/lemonriver/text/types.ts +243 -0
  103. package/src/app/lemonriver/text/zh-cn.ts +218 -0
  104. package/src/app/lemonriver/text/zh-tw.ts +218 -0
  105. package/src/app/lemonriver/theme/lemon-icon.tsx +6 -0
  106. package/src/app/lemonriver/theme/pages.test.ts +4 -0
  107. package/src/app/lemonriver/theme/pages.ts +6 -1
  108. package/src/app/lemonriver/theme/theme-menu.tsx +3 -2
  109. package/src/app/lemonriver/theme/use-theme.tsx +2 -2
  110. package/src/app/lemonriver/update/prompt.ts +1 -1
  111. package/src/app/lib/agent/use-agent.ts +4 -3
  112. package/src/app/routes/slide.tsx +1 -1
  113. package/src/app/assets/open-slide.svg +0 -39
  114. package/src/app/favicon.ico +0 -0
  115. package/src/app/favicon.svg +0 -39
@@ -10,15 +10,19 @@ import {
10
10
  type CardPatch,
11
11
  carryCards,
12
12
  entriesAfter,
13
+ hasLink,
13
14
  isSettledKey,
15
+ type LinkKind,
14
16
  linkCards,
15
17
  linkedPairs,
16
18
  originAfter,
17
19
  type PageOp,
18
20
  pageKeys,
19
21
  patchCard,
22
+ patchCards,
20
23
  sanitizeCards,
21
24
  sanitizeLinks,
25
+ setLinkKind,
22
26
  unlinkCards,
23
27
  } from './model/cards';
24
28
 
@@ -32,8 +36,22 @@ type BoardState = {
32
36
 
33
37
  const INITIAL: BoardState = { cards: {}, links: [], entries: undefined, loaded: false };
34
38
 
35
- const countAfter = (op: PageOp, count: number) =>
36
- op.kind === 'move' ? count : op.kind === 'delete' ? count - 1 : count + 1;
39
+ export const countAfter = (op: PageOp, count: number) => {
40
+ switch (op.kind) {
41
+ case 'delete':
42
+ return count - 1;
43
+ case 'deleteMany':
44
+ return count - op.indices.length;
45
+ case 'move':
46
+ case 'moveMany':
47
+ case 'reorder':
48
+ return count;
49
+ case 'restore':
50
+ return count + 1;
51
+ default:
52
+ return count + 1;
53
+ }
54
+ };
37
55
 
38
56
  /**
39
57
  * Titles, statuses, work memos and links: board-only data that never reaches
@@ -132,15 +150,33 @@ export function useBoardCards(slideId: string, modulePages: Page[], count: numbe
132
150
  if (modulePages.length > 0) void refreshEntries();
133
151
  }, [modulePages, refreshEntries]);
134
152
 
153
+ /** Cards and links as the server has them; a task may have written titles. */
154
+ const refreshCards = useCallback(async () => {
155
+ try {
156
+ const res = await fetch(`/__board/cards?slideId=${encodeURIComponent(slideId)}`);
157
+ if (!res.ok) return;
158
+ const body = (await res.json()) as { cards?: unknown; links?: unknown };
159
+ const current = boardRef.current;
160
+ commit(
161
+ {
162
+ ...current,
163
+ cards: sanitizeCards(body.cards),
164
+ links: sanitizeLinks(body.links),
165
+ },
166
+ false,
167
+ );
168
+ } catch {}
169
+ }, [slideId, commit]);
170
+
135
171
  /**
136
172
  * Moves the board's data along with a page operation, before the deck itself
137
173
  * changes. Call the returned function once the deck write settles; a refused
138
174
  * write puts the cards back as they were.
139
175
  */
140
176
  const beginOp = useCallback(
141
- (op: PageOp) => {
177
+ (op: PageOp, countOverride?: number) => {
142
178
  const snapshot = boardRef.current;
143
- const count = countRef.current;
179
+ const count = countOverride ?? countRef.current;
144
180
  opsInFlight.current += 1;
145
181
  entrySeq.current += 1;
146
182
 
@@ -149,6 +185,9 @@ export function useBoardCards(slideId: string, modulePages: Page[], count: numbe
149
185
  if (before.every(isSettledKey)) {
150
186
  const after = pageKeys(entries, countAfter(op, count));
151
187
  const carried = carryCards(snapshot, before, after, originAfter(op, count));
188
+ // A restored page brings its card back in the same write: written later,
189
+ // it could be wiped by the deck reload the restore itself triggers.
190
+ if (op.kind === 'restore' && op.card) carried.cards[op.entry] = op.card;
152
191
  commit({ ...snapshot, ...carried, entries }, true);
153
192
  } else {
154
193
  commit({ ...snapshot, entries }, false);
@@ -181,6 +220,39 @@ export function useBoardCards(slideId: string, modulePages: Page[], count: numbe
181
220
  [keyAt, commit],
182
221
  );
183
222
 
223
+ /** One change across several cards, written once. */
224
+ const patchMany = useCallback(
225
+ (indices: number[], change: CardPatch) => {
226
+ const keys = indices
227
+ .map((index) => keyAt(index))
228
+ .filter((key): key is string => key !== null);
229
+ if (keys.length === 0) return;
230
+ const current = boardRef.current;
231
+ commit({ ...current, cards: patchCards(current.cards, keys, change) }, true);
232
+ },
233
+ [keyAt, commit],
234
+ );
235
+
236
+ /** Puts links back, ignoring any that are already there. */
237
+ const addLinks = useCallback(
238
+ (pairs: BoardLink[]) => {
239
+ if (pairs.length === 0) return;
240
+ const current = boardRef.current;
241
+ if (!current.loaded) return;
242
+ const links = [...current.links];
243
+ for (const pair of pairs) if (!hasLink(links, pair.a, pair.b)) links.push(pair);
244
+ if (links.length !== current.links.length) commit({ ...current, links }, true);
245
+ },
246
+ [commit],
247
+ );
248
+
249
+ /** The deck source a page is written as, for putting the page back later. */
250
+ const entryAt = useCallback((index: number): string | null => {
251
+ const entries = boardRef.current.entries;
252
+ if (!entries || entries.length !== countRef.current) return null;
253
+ return entries[index] ?? null;
254
+ }, []);
255
+
184
256
  const setLink = useCallback(
185
257
  (a: number, b: number, linked: boolean) => {
186
258
  const from = keyAt(a);
@@ -198,6 +270,19 @@ export function useBoardCards(slideId: string, modulePages: Page[], count: numbe
198
270
  const link = useCallback((a: number, b: number) => setLink(a, b, true), [setLink]);
199
271
  const unlink = useCallback((a: number, b: number) => setLink(a, b, false), [setLink]);
200
272
 
273
+ /** Names what links two pages, or clears it back to a plain association. */
274
+ const kindLink = useCallback(
275
+ (a: number, b: number, kind: LinkKind | null) => {
276
+ const from = keyAt(a);
277
+ const to = keyAt(b);
278
+ if (!from || !to) return;
279
+ const current = boardRef.current;
280
+ const links = setLinkKind(current.links, from, to, kind);
281
+ if (links !== current.links) commit({ ...current, links }, true);
282
+ },
283
+ [keyAt, commit],
284
+ );
285
+
201
286
  const keys = useMemo(() => pageKeys(board.entries, count), [board.entries, count]);
202
287
  const ready = board.loaded && keys.every(isSettledKey);
203
288
  const cards = useMemo<(BoardCard | undefined)[]>(
@@ -206,5 +291,23 @@ export function useBoardCards(slideId: string, modulePages: Page[], count: numbe
206
291
  );
207
292
  const pairs = useMemo(() => linkedPairs(keys, board.links), [keys, board.links]);
208
293
 
209
- return { ready, cards, pairs, patch, link, unlink, beginOp };
294
+ return {
295
+ ready,
296
+ keys,
297
+ entries: board.entries,
298
+ cards,
299
+ /** The same cards as a record, for code that looks a page up by its key. */
300
+ byKey: board.cards,
301
+ pairs,
302
+ links: board.links,
303
+ patch,
304
+ patchMany,
305
+ link,
306
+ unlink,
307
+ kindLink,
308
+ beginOp,
309
+ entryAt,
310
+ addLinks,
311
+ refreshCards,
312
+ };
210
313
  }
@@ -0,0 +1,108 @@
1
+ import { useCallback, useEffect, useRef, useState } from 'react';
2
+ import { toast } from 'sonner';
3
+ import { useLrText } from '../text';
4
+ import { type Placement, sanitizeChanges } from './model/changes';
5
+
6
+ const SAVE_DELAY = 150;
7
+
8
+ /**
9
+ * The list of blocks waiting to be moved. It belongs to the board, not the
10
+ * deck: nothing here is applied until the change list is handed to the agent.
11
+ */
12
+ export function useBoardChanges(slideId: string) {
13
+ const lr = useLrText();
14
+ const [changes, setChanges] = useState<Placement[]>([]);
15
+ const [ready, setReady] = useState(false);
16
+ const changesRef = useRef(changes);
17
+ changesRef.current = changes;
18
+ const readyRef = useRef(false);
19
+ const timer = useRef<number | null>(null);
20
+ const queue = useRef<Promise<void>>(Promise.resolve());
21
+
22
+ const save = useCallback(
23
+ (next: Placement[]) => {
24
+ const body = JSON.stringify({ slideId, changes: next });
25
+ queue.current = queue.current.then(async () => {
26
+ try {
27
+ const res = await fetch('/__board/changes', {
28
+ method: 'PUT',
29
+ headers: { 'content-type': 'application/json' },
30
+ body,
31
+ });
32
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
33
+ } catch (err) {
34
+ toast.error(`${lr.board.saveFailed}: ${String((err as Error).message ?? err)}`);
35
+ }
36
+ });
37
+ },
38
+ [slideId, lr.board],
39
+ );
40
+
41
+ const flush = useCallback(() => {
42
+ if (timer.current === null) return;
43
+ window.clearTimeout(timer.current);
44
+ timer.current = null;
45
+ save(changesRef.current);
46
+ }, [save]);
47
+
48
+ const commit = useCallback(
49
+ (next: Placement[]) => {
50
+ changesRef.current = next;
51
+ setChanges(next);
52
+ if (!readyRef.current) return;
53
+ if (timer.current !== null) window.clearTimeout(timer.current);
54
+ timer.current = window.setTimeout(() => {
55
+ timer.current = null;
56
+ save(changesRef.current);
57
+ }, SAVE_DELAY);
58
+ },
59
+ [save],
60
+ );
61
+
62
+ /** Takes what the server already holds, without writing it back. */
63
+ const replace = useCallback((next: Placement[]) => {
64
+ changesRef.current = next;
65
+ setChanges(next);
66
+ }, []);
67
+
68
+ useEffect(() => {
69
+ let cancelled = false;
70
+ readyRef.current = false;
71
+ setReady(false);
72
+ setChanges([]);
73
+ changesRef.current = [];
74
+ (async () => {
75
+ try {
76
+ const res = await fetch(`/__board/changes?slideId=${encodeURIComponent(slideId)}`);
77
+ if (!res.ok || cancelled) return;
78
+ const body = (await res.json()) as { changes?: unknown };
79
+ if (cancelled) return;
80
+ const next = sanitizeChanges(body.changes);
81
+ changesRef.current = next;
82
+ setChanges(next);
83
+ readyRef.current = true;
84
+ setReady(true);
85
+ } catch {
86
+ // Left unloaded, so nothing written from here can overwrite changes
87
+ // that were never read.
88
+ }
89
+ })();
90
+ return () => {
91
+ cancelled = true;
92
+ flush();
93
+ };
94
+ }, [slideId, flush]);
95
+
96
+ // A reload during the debounce window would otherwise drop the last move.
97
+ useEffect(() => {
98
+ const onLeave = () => flush();
99
+ window.addEventListener('pagehide', onLeave);
100
+ window.addEventListener('beforeunload', onLeave);
101
+ return () => {
102
+ window.removeEventListener('pagehide', onLeave);
103
+ window.removeEventListener('beforeunload', onLeave);
104
+ };
105
+ }, [flush]);
106
+
107
+ return { changes, ready, setChanges: commit, replace };
108
+ }
@@ -3,17 +3,16 @@ import { toast } from 'sonner';
3
3
  import type { Page } from '../../lib/sdk';
4
4
  import { useLrText } from '../text';
5
5
  import { seedColumns } from './layout';
6
- import {
7
- type BoardColumn,
8
- columnOfPosition,
9
- columnsAfterMove,
10
- reconcileColumns,
11
- } from './model/structure';
6
+ import { type BoardColumn, reconcileColumns } from './model/structure';
12
7
 
13
8
  /**
14
9
  * The board's columns live beside the project, never in the deck file. The deck
15
10
  * only ever seeds them: from then on a chapter page is an ordinary card, so
16
11
  * moving it cannot re-group the pages it used to head.
12
+ *
13
+ * Every change to the structure is worked out as a whole new list by a pure
14
+ * function and handed here, so an undo can replay the list it took away instead
15
+ * of re-deriving it from a board that has already moved on.
17
16
  */
18
17
  export function useBoardColumns(
19
18
  slideId: string,
@@ -28,6 +27,9 @@ export function useBoardColumns(
28
27
  });
29
28
  seedRef.current = { pages, title: columnTitle };
30
29
 
30
+ /** Chapters a task just wrote, waiting for the deck to reload with them. */
31
+ const waiting = useRef<{ columns: BoardColumn[]; count: number } | null>(null);
32
+
31
33
  const save = useCallback(
32
34
  async (next: BoardColumn[]) => {
33
35
  try {
@@ -79,6 +81,15 @@ export function useBoardColumns(
79
81
  // A deck edited outside the board (or by the agent) changes the page count;
80
82
  // the structure follows so the board never renders half a deck.
81
83
  useEffect(() => {
84
+ const pending = waiting.current;
85
+ if (pending) {
86
+ // The chapters belong to a deck that has not reloaded yet; reconciling
87
+ // now would spread the new pages into the wrong chapter.
88
+ if (pages.length !== pending.count) return;
89
+ waiting.current = null;
90
+ setColumns(pending.columns);
91
+ return;
92
+ }
82
93
  setColumns((current) => {
83
94
  if (!current) return current;
84
95
  const total = current.reduce((sum, column) => sum + column.size, 0);
@@ -89,61 +100,31 @@ export function useBoardColumns(
89
100
  });
90
101
  }, [pages.length, save]);
91
102
 
92
- /** A card crossing a column boundary hands one page over; nothing else moves. */
93
- const moveBetweenColumns = useCallback(
94
- (from: number, to: number) => {
95
- setColumns((current) => {
96
- if (!current) return current;
97
- const next = columnsAfterMove(current, from, to);
98
- if (next !== current) void save(next);
99
- return next;
100
- });
101
- },
102
- [save],
103
- );
104
-
105
- /** A page added or removed at `index` grows or shrinks the column holding it. */
106
- const resizeColumnAt = useCallback(
107
- (index: number, delta: number) => {
108
- setColumns((current) => {
109
- if (!current) return current;
110
- const column = columnOfPosition(current, index);
111
- const next = current.map((c, i) =>
112
- i === column ? { ...c, size: Math.max(0, c.size + delta) } : c,
113
- );
114
- void save(next);
115
- return next;
116
- });
117
- },
118
- [save],
119
- );
120
-
121
- /** Grows one column by `delta`, for a page added straight into that column. */
122
- const growColumn = useCallback(
123
- (index: number, delta: number) => {
124
- setColumns((current) => {
125
- if (!current?.[index]) return current;
126
- const next = current.map((column, i) =>
127
- i === index ? { ...column, size: Math.max(0, column.size + delta) } : column,
128
- );
129
- void save(next);
130
- return next;
131
- });
103
+ const applyColumns = useCallback(
104
+ (next: BoardColumn[]) => {
105
+ waiting.current = null;
106
+ setColumns(next);
107
+ void save(next);
132
108
  },
133
109
  [save],
134
110
  );
135
111
 
136
- const renameColumn = useCallback(
137
- (index: number, title: string) => {
138
- setColumns((current) => {
139
- if (!current?.[index]) return current;
140
- const next = current.map((column, i) => (i === index ? { ...column, title } : column));
141
- void save(next);
142
- return next;
143
- });
112
+ /** Chapters the server just wrote; held until the deck has that many pages. */
113
+ const adoptColumns = useCallback(
114
+ (next: BoardColumn[]) => {
115
+ const count = next.reduce((sum, column) => sum + column.size, 0);
116
+ // Fewer pages than the deck has: this is the record from before the task,
117
+ // and the deck's own reconcile already knows better.
118
+ if (count === 0 || count < pages.length) return;
119
+ if (pages.length === count) {
120
+ waiting.current = null;
121
+ setColumns(next);
122
+ return;
123
+ }
124
+ waiting.current = { columns: next, count };
144
125
  },
145
- [save],
126
+ [pages.length],
146
127
  );
147
128
 
148
- return { columns, moveBetweenColumns, resizeColumnAt, growColumn, renameColumn };
129
+ return { columns, applyColumns, adoptColumns };
149
130
  }
@@ -0,0 +1,36 @@
1
+ import { useEffect, useState } from 'react';
2
+
3
+ /**
4
+ * Which pages carry a comment. Comments are read-only here: the board only
5
+ * needs to know that a page has one, so a filter can pick those pages out.
6
+ */
7
+ export function useBoardComments(slideId: string, count: number): boolean[] {
8
+ const [pages, setPages] = useState<boolean[]>([]);
9
+
10
+ useEffect(() => {
11
+ let cancelled = false;
12
+ setPages([]);
13
+ if (!slideId) return;
14
+ (async () => {
15
+ try {
16
+ const res = await fetch(`/__comments?slideId=${encodeURIComponent(slideId)}`);
17
+ if (!res.ok) return;
18
+ const body = (await res.json()) as { comments?: { page?: unknown }[] };
19
+ if (cancelled) return;
20
+ const next = Array.from({ length: count }, () => false);
21
+ for (const comment of body.comments ?? []) {
22
+ const page = comment?.page;
23
+ if (typeof page === 'number' && page >= 0 && page < next.length) next[page] = true;
24
+ }
25
+ setPages(next);
26
+ } catch {
27
+ // No comments read: every card reads as having none.
28
+ }
29
+ })();
30
+ return () => {
31
+ cancelled = true;
32
+ };
33
+ }, [slideId, count]);
34
+
35
+ return pages;
36
+ }
@@ -0,0 +1,107 @@
1
+ import { useCallback, useEffect, useRef, useState } from 'react';
2
+ import { toast } from 'sonner';
3
+ import { useLrText } from '../text';
4
+ import { type Restructure, sanitizeRestructures } from './model/restructure';
5
+
6
+ const SAVE_DELAY = 150;
7
+
8
+ /**
9
+ * The pages waiting to be split or merged. Like the block moves it is board
10
+ * data: the deck is only touched when the list is handed to the agent.
11
+ */
12
+ export function useBoardRestructures(slideId: string) {
13
+ const lr = useLrText();
14
+ const [restructures, setRestructures] = useState<Restructure[]>([]);
15
+ const [ready, setReady] = useState(false);
16
+ const listRef = useRef(restructures);
17
+ listRef.current = restructures;
18
+ const readyRef = useRef(false);
19
+ const timer = useRef<number | null>(null);
20
+ const queue = useRef<Promise<void>>(Promise.resolve());
21
+
22
+ const save = useCallback(
23
+ (next: Restructure[]) => {
24
+ const body = JSON.stringify({ slideId, restructures: next });
25
+ queue.current = queue.current.then(async () => {
26
+ try {
27
+ const res = await fetch('/__board/restructures', {
28
+ method: 'PUT',
29
+ headers: { 'content-type': 'application/json' },
30
+ body,
31
+ });
32
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
33
+ } catch (err) {
34
+ toast.error(`${lr.board.saveFailed}: ${String((err as Error).message ?? err)}`);
35
+ }
36
+ });
37
+ },
38
+ [slideId, lr.board],
39
+ );
40
+
41
+ const flush = useCallback(() => {
42
+ if (timer.current === null) return;
43
+ window.clearTimeout(timer.current);
44
+ timer.current = null;
45
+ save(listRef.current);
46
+ }, [save]);
47
+
48
+ const commit = useCallback(
49
+ (next: Restructure[]) => {
50
+ listRef.current = next;
51
+ setRestructures(next);
52
+ if (!readyRef.current) return;
53
+ if (timer.current !== null) window.clearTimeout(timer.current);
54
+ timer.current = window.setTimeout(() => {
55
+ timer.current = null;
56
+ save(listRef.current);
57
+ }, SAVE_DELAY);
58
+ },
59
+ [save],
60
+ );
61
+
62
+ /** Takes what the server already holds, without writing it back. */
63
+ const replace = useCallback((next: Restructure[]) => {
64
+ listRef.current = next;
65
+ setRestructures(next);
66
+ }, []);
67
+
68
+ useEffect(() => {
69
+ let cancelled = false;
70
+ readyRef.current = false;
71
+ setReady(false);
72
+ setRestructures([]);
73
+ listRef.current = [];
74
+ (async () => {
75
+ try {
76
+ const res = await fetch(`/__board/restructures?slideId=${encodeURIComponent(slideId)}`);
77
+ if (!res.ok || cancelled) return;
78
+ const body = (await res.json()) as { restructures?: unknown };
79
+ if (cancelled) return;
80
+ const next = sanitizeRestructures(body.restructures);
81
+ listRef.current = next;
82
+ setRestructures(next);
83
+ readyRef.current = true;
84
+ setReady(true);
85
+ } catch {
86
+ // Left unloaded, so nothing written from here can overwrite a list
87
+ // that was never read.
88
+ }
89
+ })();
90
+ return () => {
91
+ cancelled = true;
92
+ flush();
93
+ };
94
+ }, [slideId, flush]);
95
+
96
+ useEffect(() => {
97
+ const onLeave = () => flush();
98
+ window.addEventListener('pagehide', onLeave);
99
+ window.addEventListener('beforeunload', onLeave);
100
+ return () => {
101
+ window.removeEventListener('pagehide', onLeave);
102
+ window.removeEventListener('beforeunload', onLeave);
103
+ };
104
+ }, [flush]);
105
+
106
+ return { restructures, ready, setRestructures: commit, replace };
107
+ }
@@ -0,0 +1,86 @@
1
+ import { useCallback, useEffect, useRef, useState } from 'react';
2
+ import { toast } from 'sonner';
3
+ import { useLrText } from '../text';
4
+ import {
5
+ canRedo,
6
+ canUndo,
7
+ dropStep,
8
+ emptyHistory,
9
+ type History,
10
+ type HistoryStep,
11
+ nextUndo,
12
+ recordStep,
13
+ redoStep,
14
+ undoStep,
15
+ } from './model/history';
16
+
17
+ /**
18
+ * Undo and redo over the board's operations. Each step is a pair of closures
19
+ * that replay the operation and its opposite; the stack itself is plain data.
20
+ */
21
+ export function useHistory(slideId: string) {
22
+ const [history, setHistory] = useState<History>(emptyHistory);
23
+ const historyRef = useRef(history);
24
+ historyRef.current = history;
25
+ const busy = useRef(false);
26
+ const lr = useLrText();
27
+
28
+ // A different deck starts with nothing to undo: a step recorded against the
29
+ // previous deck would run its writes against this one.
30
+ useEffect(() => {
31
+ if (!slideId) return;
32
+ const cleared = emptyHistory();
33
+ historyRef.current = cleared;
34
+ setHistory(cleared);
35
+ }, [slideId]);
36
+
37
+ const record = useCallback((step: HistoryStep) => {
38
+ const next = recordStep(historyRef.current, step);
39
+ historyRef.current = next;
40
+ setHistory(next);
41
+ }, []);
42
+
43
+ const run = useCallback(
44
+ async (direction: 'undo' | 'redo') => {
45
+ if (busy.current) return false;
46
+ const current = historyRef.current;
47
+ const taken = direction === 'undo' ? undoStep(current) : redoStep(current);
48
+ if (!taken) return false;
49
+
50
+ if (direction === 'undo' && !taken.step.undo) {
51
+ // The step cannot be taken back; drop it so the next press reaches a
52
+ // step that can be, and say why.
53
+ const dropped = dropStep(current);
54
+ historyRef.current = dropped;
55
+ setHistory(dropped);
56
+ toast.error(lr.board.undoUnavailable);
57
+ return false;
58
+ }
59
+
60
+ busy.current = true;
61
+ historyRef.current = taken.history;
62
+ setHistory(taken.history);
63
+ try {
64
+ await (direction === 'undo' ? taken.step.undo?.() : taken.step.redo());
65
+ return true;
66
+ } finally {
67
+ busy.current = false;
68
+ }
69
+ },
70
+ [lr.board.undoUnavailable],
71
+ );
72
+
73
+ const undo = useCallback(() => run('undo'), [run]);
74
+ const redo = useCallback(() => run('redo'), [run]);
75
+ const newest = nextUndo(history);
76
+
77
+ return {
78
+ record,
79
+ undo,
80
+ redo,
81
+ canUndo: canUndo(history),
82
+ canRedo: canRedo(history),
83
+ /** True when the newest step removed a page that cannot be put back. */
84
+ undoBlocked: newest !== null && newest.undo === null,
85
+ };
86
+ }