@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
@@ -1,17 +1,127 @@
1
- import { ChevronLeft } from 'lucide-react';
2
- import { lazy, Suspense, useCallback, useEffect, useState } from 'react';
1
+ import {
2
+ ChevronDown,
3
+ ChevronLeft,
4
+ ChevronUp,
5
+ Columns3,
6
+ Combine,
7
+ Copy,
8
+ Filter,
9
+ GanttChart,
10
+ Grid2X2,
11
+ Image as ImageIcon,
12
+ LayoutGrid,
13
+ List,
14
+ ListOrdered,
15
+ Plus,
16
+ Redo2,
17
+ Rows3,
18
+ Trash2,
19
+ Undo2,
20
+ X,
21
+ } from 'lucide-react';
22
+ import { lazy, Suspense, useCallback, useEffect, useMemo, useRef, useState } from 'react';
3
23
  import { useNavigate, useParams } from 'react-router-dom';
4
- import { Button } from '@/components/ui/button';
24
+ import { toast } from 'sonner';
25
+ import { Button, buttonVariants } from '@/components/ui/button';
26
+ import {
27
+ Dialog,
28
+ DialogContent,
29
+ DialogDescription,
30
+ DialogFooter,
31
+ DialogHeader,
32
+ DialogTitle,
33
+ } from '@/components/ui/dialog';
34
+ import {
35
+ DropdownMenu,
36
+ DropdownMenuCheckboxItem,
37
+ DropdownMenuContent,
38
+ DropdownMenuGroup,
39
+ DropdownMenuItem,
40
+ DropdownMenuLabel,
41
+ DropdownMenuSeparator,
42
+ DropdownMenuTrigger,
43
+ } from '@/components/ui/dropdown-menu';
44
+ import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
45
+ import { setDockOpen } from '@/lib/agent/use-agent';
46
+ import { isTypingTarget } from '@/lib/keys';
5
47
  import { useDocumentTitle } from '@/lib/use-document-title';
6
- import { format } from '@/lib/use-locale';
7
- import { pad2 } from '@/lib/utils';
48
+ import { format, useLocale } from '@/lib/use-locale';
49
+ import { cn, pad2 } from '@/lib/utils';
8
50
  import type { Page } from '../../lib/sdk';
9
51
  import { useSlideModule } from '../../lib/use-slide-module';
10
52
  import { useLrText } from '../text';
11
- import { columnStarts } from './model/structure';
12
- import { useBoardCards } from './use-board-cards';
53
+ import { BlockPanel } from './blocks/block-panel';
54
+ import { pageReadOf } from './blocks/cache';
55
+ import { ChangeList } from './blocks/change-list';
56
+ import type { Block } from './blocks/classify';
57
+ import { type CardSize, orderAfterMoveMany } from './layout';
58
+ import type { PageAction } from './model/agent-tasks';
59
+ import {
60
+ type BoardApplying,
61
+ type BoardLastApply,
62
+ type ChapterPlan,
63
+ sanitizeChapterPlan,
64
+ } from './model/apply';
65
+ import {
66
+ type BoardCard,
67
+ CARD_STATUSES,
68
+ type CardPatch,
69
+ type CardStatus,
70
+ entriesAfter,
71
+ isSettledKey,
72
+ type LinkKind,
73
+ originAfter,
74
+ type PageOp,
75
+ pageKeys,
76
+ } from './model/cards';
77
+ import { carryChanges, type Placement, sanitizeChanges, staleChanges } from './model/changes';
78
+ import {
79
+ type BoardFilter,
80
+ EMPTY_FILTER,
81
+ isFilterActive,
82
+ matchesFilter,
83
+ toggleStatus,
84
+ } from './model/filter';
85
+ import type { HistoryStep } from './model/history';
86
+ import {
87
+ addMerge,
88
+ addSplit,
89
+ carryRestructures,
90
+ type Restructure,
91
+ restructureReplaced,
92
+ type SplitBlock,
93
+ sanitizeRestructures,
94
+ } from './model/restructure';
95
+ import {
96
+ addColumnAfter,
97
+ type BoardColumn,
98
+ chapterProgress,
99
+ columnStarts,
100
+ columnsAfterInsert,
101
+ columnsAfterMoveMany,
102
+ columnsAfterRemove,
103
+ deleteColumnAt,
104
+ insertPageColumn,
105
+ moveColumnBlock,
106
+ orderAfterColumnMove,
107
+ renameColumnAt,
108
+ } from './model/structure';
109
+ import { useStatusLabels } from './page-node';
110
+ import { publishFindings, SelfCheckButton } from './self-check-panel';
111
+ import { SelfCheckRunner } from './self-check-runner';
112
+ import { useBoardApply } from './use-board-apply';
113
+ import { countAfter, useBoardCards } from './use-board-cards';
114
+ import { useBoardChanges } from './use-board-changes';
13
115
  import { useBoardColumns } from './use-board-columns';
116
+ import { useBoardComments } from './use-board-comments';
117
+ import { useBoardRestructures } from './use-board-restructures';
118
+ import { useHistory } from './use-history';
14
119
  import { usePageOrder } from './use-page-order';
120
+ import { useSelfCheck } from './use-self-check';
121
+ import { useTargetMinutes } from './use-target-minutes';
122
+ import { BlockReadings } from './views/block-readings';
123
+ import { ListView } from './views/list-view';
124
+ import { TimelineView } from './views/timeline-view';
15
125
 
16
126
  const BoardCanvas = lazy(() => import('./board-canvas'));
17
127
 
@@ -20,6 +130,39 @@ const BoardCanvas = lazy(() => import('./board-canvas'));
20
130
  const NO_PAGES: Page[] = [];
21
131
 
22
132
  const LINKS_KEY = 'open-slide:board-links-visible';
133
+ const SIZE_KEY = 'open-slide:board-card-size';
134
+ const VIEW_KEY = 'open-slide:board-view';
135
+ const BLOCKS_KEY = 'open-slide:board-blocks-visible';
136
+ const collapsedKey = (slideId: string) => `open-slide:board-collapsed:${slideId}`;
137
+
138
+ const BOARD_VIEWS = ['cards', 'list', 'timeline'] as const;
139
+ export type BoardViewKind = (typeof BOARD_VIEWS)[number];
140
+
141
+ /** Which of the three ways the deck is being read. A preference, so it outlives the visit. */
142
+ function useBoardView(): [BoardViewKind, (view: BoardViewKind) => void] {
143
+ const [view, setView] = useState<BoardViewKind>(() => {
144
+ if (typeof window === 'undefined') return 'cards';
145
+ const stored = window.localStorage.getItem(VIEW_KEY);
146
+ return stored === 'list' || stored === 'timeline' ? stored : 'cards';
147
+ });
148
+ const choose = useCallback((next: BoardViewKind) => {
149
+ setView(next);
150
+ window.localStorage.setItem(VIEW_KEY, next);
151
+ }, []);
152
+ return [view, choose];
153
+ }
154
+
155
+ function useBlocksVisible() {
156
+ const [visible, setVisible] = useState(() => {
157
+ if (typeof window === 'undefined') return false;
158
+ return window.localStorage.getItem(BLOCKS_KEY) === '1';
159
+ });
160
+ useEffect(() => {
161
+ window.localStorage.setItem(BLOCKS_KEY, visible ? '1' : '0');
162
+ }, [visible]);
163
+ const toggle = useCallback(() => setVisible((v) => !v), []);
164
+ return [visible, toggle] as const;
165
+ }
23
166
 
24
167
  function useLinksVisible() {
25
168
  const [visible, setVisible] = useState(() => {
@@ -33,94 +176,973 @@ function useLinksVisible() {
33
176
  return [visible, toggle] as const;
34
177
  }
35
178
 
179
+ /** How much of a page the cards show. A preference, so it outlives the visit. */
180
+ function useCardSize(): [CardSize, (size: CardSize) => void] {
181
+ const [size, setSize] = useState<CardSize>(() => {
182
+ if (typeof window === 'undefined') return 'large';
183
+ const stored = window.localStorage.getItem(SIZE_KEY);
184
+ return stored === 'small' || stored === 'title' ? stored : 'large';
185
+ });
186
+ const choose = useCallback((next: CardSize) => {
187
+ setSize(next);
188
+ window.localStorage.setItem(SIZE_KEY, next);
189
+ }, []);
190
+ return [size, choose];
191
+ }
192
+
193
+ /** Folded chapters, by index. A view state, kept per deck in the browser. */
194
+ function useFolded(slideId: string): [boolean[], (index: number) => void, (count: number) => void] {
195
+ const read = useCallback((): number[] => {
196
+ if (typeof window === 'undefined') return [];
197
+ try {
198
+ const parsed: unknown = JSON.parse(
199
+ window.localStorage.getItem(collapsedKey(slideId)) ?? '[]',
200
+ );
201
+ return Array.isArray(parsed)
202
+ ? parsed.filter((value): value is number => typeof value === 'number' && value >= 0)
203
+ : [];
204
+ } catch {
205
+ return [];
206
+ }
207
+ }, [slideId]);
208
+
209
+ const [folded, setFolded] = useState<number[]>(read);
210
+ useEffect(() => setFolded(read()), [read]);
211
+
212
+ const toggle = useCallback(
213
+ (index: number) => {
214
+ setFolded((current) => {
215
+ const next = current.includes(index)
216
+ ? current.filter((value) => value !== index)
217
+ : [...current, index];
218
+ window.localStorage.setItem(collapsedKey(slideId), JSON.stringify(next));
219
+ return next;
220
+ });
221
+ },
222
+ [slideId],
223
+ );
224
+
225
+ // A chapter that went away takes its folded state with it, so a chapter that
226
+ // later lands on that index does not open folded for no reason.
227
+ const trim = useCallback(
228
+ (count: number) =>
229
+ setFolded((current) => {
230
+ const next = current.filter((index) => index < count);
231
+ return next.length === current.length ? current : next;
232
+ }),
233
+ [],
234
+ );
235
+
236
+ const collapsed = useMemo(() => {
237
+ const flags: boolean[] = [];
238
+ for (const index of folded) flags[index] = true;
239
+ return flags;
240
+ }, [folded]);
241
+
242
+ return [collapsed, toggle, trim];
243
+ }
244
+
245
+ /** The inverse of a page permutation, both expressed as `next[index] = previous[?]`. */
246
+ function invertOrder(order: number[]): number[] {
247
+ const inverse = new Array<number>(order.length);
248
+ order.forEach((from, to) => {
249
+ inverse[from] = to;
250
+ });
251
+ return inverse;
252
+ }
253
+
254
+ const isIdentity = (order: number[]) => order.every((value, index) => value === index);
255
+
36
256
  export function Board() {
37
257
  const { slideId = '' } = useParams();
38
258
  const navigate = useNavigate();
39
259
  const { slide, error } = useSlideModule(slideId);
40
260
  const lr = useLrText();
261
+ const t = useLocale();
262
+ const labels = useStatusLabels();
41
263
  useDocumentTitle(slide?.meta?.title);
42
264
 
265
+ const selfCheck = useSelfCheck(slideId);
266
+ useEffect(() => {
267
+ publishFindings(slideId, selfCheck.record?.findings ?? [], selfCheck.record?.unread ?? []);
268
+ }, [selfCheck.record, slideId]);
269
+
43
270
  const modulePages = slide?.default ?? NO_PAGES;
44
- const { pages, reorder, duplicate, insert, remove } = usePageOrder(slideId, modulePages);
271
+ const { pages, reorderAll, duplicate, insert, restore, remove } = usePageOrder(
272
+ slideId,
273
+ modulePages,
274
+ );
45
275
 
46
276
  const columnTitle = useCallback(
47
277
  (n: number) => format(lr.board.columnFallback, { n }),
48
278
  [lr.board.columnFallback],
49
279
  );
50
- const { columns, moveBetweenColumns, resizeColumnAt, growColumn, renameColumn } = useBoardColumns(
51
- slideId,
52
- pages,
53
- columnTitle,
280
+ const { columns, applyColumns, adoptColumns } = useBoardColumns(slideId, pages, columnTitle);
281
+ const {
282
+ ready,
283
+ keys,
284
+ entries,
285
+ cards,
286
+ byKey,
287
+ pairs,
288
+ links,
289
+ patch,
290
+ link,
291
+ unlink,
292
+ kindLink,
293
+ beginOp,
294
+ entryAt,
295
+ addLinks,
296
+ refreshCards,
297
+ } = useBoardCards(slideId, modulePages, pages.length);
298
+ const comments = useBoardComments(slideId, pages.length);
299
+ const history = useHistory(slideId);
300
+ const { changes, setChanges, replace: replaceChanges } = useBoardChanges(slideId);
301
+ const {
302
+ restructures,
303
+ setRestructures,
304
+ replace: replaceRestructures,
305
+ } = useBoardRestructures(slideId);
306
+ const [showLinks, toggleLinks] = useLinksVisible();
307
+ const [showBlocks, toggleBlocks] = useBlocksVisible();
308
+ const [size, chooseSize] = useCardSize();
309
+ const [view, chooseView] = useBoardView();
310
+ const [target, chooseTarget] = useTargetMinutes(slideId);
311
+ const [collapsed, toggleCollapse, trimFolded] = useFolded(slideId);
312
+ const [filter, setFilter] = useState<BoardFilter>(EMPTY_FILTER);
313
+ const [selected, setSelected] = useState<number[]>([]);
314
+ const [pendingDelete, setPendingDelete] = useState<number[] | null>(null);
315
+ const [jumpTo, setJumpTo] = useState<{ index: number; seq: number } | null>(null);
316
+ const jumpSeq = useRef(0);
317
+
318
+ const pageCount = useRef(pages.length);
319
+ pageCount.current = pages.length;
320
+
321
+ const changesRef = useRef(changes);
322
+ changesRef.current = changes;
323
+
324
+ const restructuresRef = useRef(restructures);
325
+ restructuresRef.current = restructures;
326
+
327
+ /** A page operation carries the block moves and the splits along with it. */
328
+ const beginPageOp = useCallback(
329
+ (op: PageOp, count: number) => {
330
+ const snapshot = changesRef.current;
331
+ const savedRestructures = restructuresRef.current;
332
+ const before = pageKeys(entries, count);
333
+ if (before.every(isSettledKey)) {
334
+ const after = pageKeys(entriesAfter(op, entries, count), countAfter(op, count));
335
+ setChanges(carryChanges(snapshot, before, after, originAfter(op, count)));
336
+ setRestructures(
337
+ carryRestructures(savedRestructures, before, after, originAfter(op, count)),
338
+ );
339
+ }
340
+ const settle = beginOp(op, count);
341
+ return (ok: boolean) => {
342
+ if (!ok) {
343
+ setChanges(snapshot);
344
+ setRestructures(savedRestructures);
345
+ }
346
+ settle(ok);
347
+ };
348
+ },
349
+ [entries, setChanges, setRestructures, beginOp],
54
350
  );
55
- const { ready, cards, pairs, patch, link, unlink, beginOp } = useBoardCards(
56
- slideId,
57
- modulePages,
58
- pages.length,
351
+
352
+ const applyChanges = useCallback(
353
+ (next: Placement[]) => {
354
+ const previous = changesRef.current;
355
+ setChanges(next);
356
+ history.record({ undo: () => setChanges(previous), redo: () => setChanges(next) });
357
+ },
358
+ [setChanges, history],
59
359
  );
60
- const [showLinks, toggleLinks] = useLinksVisible();
61
360
 
62
- // Order, structure and the board's own card data move together: every path
63
- // that changes the deck's pages goes through here, so none of them can drift
64
- // out of step with the pages.
65
- const movePage = useCallback(
66
- (from: number, to: number) => {
67
- if (from === to) return;
68
- const settle = beginOp({ kind: 'move', from, to });
69
- moveBetweenColumns(from, to);
70
- void reorder(from, to).then(settle);
361
+ const removeChanges = useCallback(
362
+ (indices: number[]) => {
363
+ const drop = new Set(indices);
364
+ applyChanges(changesRef.current.filter((_, index) => !drop.has(index)));
71
365
  },
72
- [beginOp, moveBetweenColumns, reorder],
366
+ [applyChanges],
73
367
  );
74
368
 
75
- const openPage = useCallback(
76
- (index: number) => {
77
- navigate(`/s/${encodeURIComponent(slideId)}?p=${index + 1}`);
369
+ const applyRestructures = useCallback(
370
+ (next: Restructure[]) => {
371
+ const previous = restructuresRef.current;
372
+ setRestructures(next);
373
+ history.record({ undo: () => setRestructures(previous), redo: () => setRestructures(next) });
78
374
  },
79
- [navigate, slideId],
375
+ [setRestructures, history],
80
376
  );
81
377
 
82
- const duplicatePage = useCallback(
83
- (index: number) => {
84
- const settle = beginOp({ kind: 'duplicate', index });
85
- resizeColumnAt(index, 1);
86
- void duplicate(index).then(settle);
378
+ const removeRestructures = useCallback(
379
+ (indices: number[]) => {
380
+ const drop = new Set(indices);
381
+ applyRestructures(restructuresRef.current.filter((_, index) => !drop.has(index)));
382
+ },
383
+ [applyRestructures],
384
+ );
385
+
386
+ /** Splitting the same page again replaces what the board already recorded. */
387
+ const splitPage = useCallback(
388
+ (page: string, blocks: SplitBlock[]) => {
389
+ const entry: Restructure = { kind: 'split', page, blocks: blocks.map((block) => block.id) };
390
+ if (restructureReplaced(restructuresRef.current, entry)) {
391
+ toast.info(lr.board.restructureReplaced);
392
+ }
393
+ applyRestructures(addSplit(restructuresRef.current, page, blocks));
394
+ },
395
+ [applyRestructures, lr.board.restructureReplaced],
396
+ );
397
+
398
+ const mergeSelected = useCallback(() => {
399
+ if (selected.length !== 2) return;
400
+ const [a, b] = [...selected].sort((one, other) => one - other);
401
+ const first = keys[a];
402
+ const second = keys[b];
403
+ if (!first || !second) return;
404
+ if (restructureReplaced(restructuresRef.current, { kind: 'merge', pages: [first, second] })) {
405
+ toast.info(lr.board.restructureReplaced);
406
+ }
407
+ applyRestructures(addMerge(restructuresRef.current, first, second));
408
+ }, [applyRestructures, keys, lr.board.restructureReplaced, selected]);
409
+
410
+ useEffect(() => {
411
+ setSelected((current) => current.filter((index) => index < pages.length));
412
+ }, [pages.length]);
413
+
414
+ useEffect(() => {
415
+ if (columns) trimFolded(columns.length);
416
+ }, [columns, trimFolded]);
417
+
418
+ const filterActive = isFilterActive(filter);
419
+
420
+ const dimmed = useMemo(
421
+ () => cards.map((card, index) => !matchesFilter(card, comments[index] === true, filter)),
422
+ [cards, comments, filter],
423
+ );
424
+
425
+ const changeCounts = useMemo(() => {
426
+ const counts = new Array<number>(pages.length).fill(0);
427
+ const at = new Map(keys.map((key, index) => [key, index]));
428
+ for (const item of changes) {
429
+ const from = at.get(item.origin.page);
430
+ if (from !== undefined) counts[from] += 1;
431
+ if (item.to === 'parked') continue;
432
+ const to = at.get(item.to.page);
433
+ if (to !== undefined && to !== from) counts[to] += 1;
434
+ }
435
+ for (const entry of restructures) {
436
+ const touched = entry.kind === 'split' ? [entry.page] : entry.pages;
437
+ for (const key of touched) {
438
+ const index = at.get(key);
439
+ if (index !== undefined) counts[index] += 1;
440
+ }
441
+ }
442
+ return counts;
443
+ }, [changes, restructures, keys, pages.length]);
444
+
445
+ const blocksOfPage = useCallback(
446
+ (key: string): Block[] | null => {
447
+ const index = keys.indexOf(key);
448
+ const page = index >= 0 ? pages[index] : undefined;
449
+ if (!page) return null;
450
+ const read = pageReadOf(page);
451
+ return read && 'blocks' in read ? read.blocks : null;
452
+ },
453
+ [keys, pages],
454
+ );
455
+
456
+ /** How far along each chapter is, for the chapter's own header. */
457
+ const columnProgress = useMemo(() => {
458
+ if (!columns) return [];
459
+ const starts = columnStarts(columns);
460
+ return columns.map((column, index) =>
461
+ chapterProgress(byKey, keys.slice(starts[index] ?? 0, (starts[index] ?? 0) + column.size)),
462
+ );
463
+ }, [columns, byKey, keys]);
464
+
465
+ // ----- handing the list to the agent -----
466
+
467
+ const [flashed, setFlashed] = useState<string[]>([]);
468
+ const [undoOpen, setUndoOpen] = useState(false);
469
+ const [listOpen, setListOpen] = useState(false);
470
+ const [building, setBuilding] = useState(false);
471
+ const [chapterAt, setChapterAt] = useState<number | null>(null);
472
+ const [chapterBrief, setChapterBrief] = useState('');
473
+ const [chapterCount, setChapterCount] = useState(3);
474
+ const [planItems, setPlanItems] = useState<ChapterPlan['items']>([]);
475
+ const [syncedPlan, setSyncedPlan] = useState<string | null>(null);
476
+
477
+ const refreshLists = useCallback(async () => {
478
+ try {
479
+ const [found, splits] = await Promise.all([
480
+ fetch(`/__board/changes?slideId=${encodeURIComponent(slideId)}`),
481
+ fetch(`/__board/restructures?slideId=${encodeURIComponent(slideId)}`),
482
+ ]);
483
+ if (found.ok) {
484
+ const body = (await found.json()) as { changes?: unknown };
485
+ replaceChanges(sanitizeChanges(body.changes));
486
+ }
487
+ if (splits.ok) {
488
+ const body = (await splits.json()) as { restructures?: unknown };
489
+ replaceRestructures(sanitizeRestructures(body.restructures));
490
+ }
491
+ } catch {}
492
+ }, [replaceChanges, replaceRestructures, slideId]);
493
+
494
+ const askUndo = useCallback(() => setUndoOpen(true), []);
495
+
496
+ /** A hand-over that has just ended: say how it went, and light up what changed. */
497
+ const onSettled = useCallback(
498
+ (last: BoardLastApply | null, was: BoardApplying | null) => {
499
+ void refreshLists();
500
+ // The task may have named the pages it added; those titles are the
501
+ // server's, not anything this board knows.
502
+ void refreshCards();
503
+ if (!last) return;
504
+ if (!last.ok) {
505
+ toast.error(format(lr.board.applyFailed, { reason: last.error ?? '' }), {
506
+ duration: 10_000,
507
+ action: { label: lr.outline.openAgent, onClick: () => setDockOpen(true) },
508
+ });
509
+ return;
510
+ }
511
+ setFlashed(last.pages);
512
+ const undo = { label: lr.board.undoTask, onClick: askUndo };
513
+ const task = was?.task;
514
+ if (task?.kind === 'page') {
515
+ const n = keys.indexOf(task.page) + 1;
516
+ toast.success(
517
+ task.action === 'expand'
518
+ ? format(lr.board.askExpanded, { n })
519
+ : format(lr.board.askDone, { n }),
520
+ { duration: 10_000, action: undo },
521
+ );
522
+ return;
523
+ }
524
+ if (task?.kind === 'chapter-write') {
525
+ toast.success(
526
+ format(lr.board.chapterWritten, { n: task.chapter + 1, k: last.pages.length }),
527
+ {
528
+ duration: 10_000,
529
+ action: undo,
530
+ },
531
+ );
532
+ return;
533
+ }
534
+ toast.success(lr.board.applyDone, {
535
+ duration: 10_000,
536
+ action: { label: lr.board.applyUndo, onClick: askUndo },
537
+ });
538
+ },
539
+ [
540
+ askUndo,
541
+ keys,
542
+ lr.board.applyDone,
543
+ lr.board.applyFailed,
544
+ lr.board.applyUndo,
545
+ lr.board.askDone,
546
+ lr.board.askExpanded,
547
+ lr.board.chapterWritten,
548
+ lr.board.undoTask,
549
+ lr.outline.openAgent,
550
+ refreshCards,
551
+ refreshLists,
552
+ ],
553
+ );
554
+
555
+ const boardApply = useBoardApply(slideId, onSettled);
556
+ const applying = boardApply.applying !== null;
557
+
558
+ // A task that adds or removes pages rewrites the chapters on the server; the
559
+ // board takes them as they are instead of sharing the new pages out itself.
560
+ useEffect(() => {
561
+ if (boardApply.columns) adoptColumns(boardApply.columns);
562
+ }, [adoptColumns, boardApply.columns]);
563
+
564
+ /** Why "ask the agent" is off for every page, before a page's own reasons. */
565
+ const agentHint = applying
566
+ ? lr.board.askBusy
567
+ : !boardApply.connected
568
+ ? lr.board.askNeedsAgent
569
+ : building
570
+ ? lr.board.askBuilding
571
+ : null;
572
+
573
+ const startPageTask = useCallback(
574
+ (index: number, action: PageAction) => {
575
+ const key = keys[index];
576
+ if (!key || agentHint || changeCounts[index] > 0) return;
577
+ if (action === 'memo' && !cards[index]?.memo?.trim()) return;
578
+ void boardApply.start({ kind: 'page', page: key, action });
579
+ },
580
+ [agentHint, boardApply, cards, changeCounts, keys],
581
+ );
582
+
583
+ const applyingLabel = useMemo(() => {
584
+ const task = boardApply.applying?.task;
585
+ if (!task) return lr.board.applying;
586
+ if (task.kind === 'page') {
587
+ return format(lr.board.askingPage[task.action], { n: keys.indexOf(task.page) + 1 });
588
+ }
589
+ if (task.kind === 'chapter-plan') {
590
+ return format(lr.board.planningChapter, { n: task.chapter + 1 });
591
+ }
592
+ if (task.kind === 'chapter-write') {
593
+ return format(lr.board.writingChapter, { n: task.chapter + 1 });
594
+ }
595
+ return lr.board.applying;
596
+ }, [boardApply.applying, keys, lr.board]);
597
+
598
+ const planFor = useCallback(
599
+ (column: number): 'planning' | number | null => {
600
+ const task = boardApply.applying?.task;
601
+ if (task?.kind === 'chapter-plan' && task.chapter === column) return 'planning';
602
+ const plan = boardApply.chapterPlan;
603
+ if (plan && plan.chapter === column && plan.state === 'ready') return plan.items.length;
604
+ return null;
605
+ },
606
+ [boardApply.applying, boardApply.chapterPlan],
607
+ );
608
+
609
+ const openChapter = useCallback((column: number) => {
610
+ setChapterAt(column);
611
+ setChapterBrief('');
612
+ setChapterCount(3);
613
+ setPlanItems([]);
614
+ setSyncedPlan(null);
615
+ }, []);
616
+
617
+ const planAt =
618
+ boardApply.chapterPlan && chapterAt !== null && boardApply.chapterPlan.chapter === chapterAt
619
+ ? boardApply.chapterPlan
620
+ : null;
621
+ const planningHere =
622
+ boardApply.applying?.task.kind === 'chapter-plan' &&
623
+ chapterAt !== null &&
624
+ boardApply.applying.task.chapter === chapterAt;
625
+ const writingHere =
626
+ boardApply.applying?.task.kind === 'chapter-write' &&
627
+ chapterAt !== null &&
628
+ boardApply.applying.task.chapter === chapterAt;
629
+
630
+ // The titles arrive once; a later read of the same record must not wipe what
631
+ // the user has typed into them since.
632
+ const planKey = planAt
633
+ ? `${planAt.chapter}|${planAt.state}|${planAt.items.map((item) => item.title).join('\u0001')}`
634
+ : null;
635
+ useEffect(() => {
636
+ if (planAt?.state !== 'ready' || planKey === null || syncedPlan === planKey) return;
637
+ setPlanItems(planAt.items);
638
+ setChapterBrief(planAt.brief);
639
+ setSyncedPlan(planKey);
640
+ }, [planAt, planKey, syncedPlan]);
641
+
642
+ const startChapterPlan = useCallback(() => {
643
+ if (chapterAt === null || !chapterBrief.trim()) return;
644
+ const brief = planAt?.brief || chapterBrief.trim();
645
+ void boardApply.start({
646
+ kind: 'chapter-plan',
647
+ chapter: chapterAt,
648
+ title: columns?.[chapterAt]?.title ?? '',
649
+ brief,
650
+ count: chapterCount,
651
+ });
652
+ }, [boardApply, chapterAt, chapterBrief, chapterCount, columns, planAt]);
653
+
654
+ const dropChapterPlan = useCallback(() => {
655
+ void boardApply.savePlan(null);
656
+ setChapterAt(null);
657
+ }, [boardApply]);
658
+
659
+ const writeChapter = useCallback(async () => {
660
+ if (chapterAt === null) return;
661
+ const title = columns?.[chapterAt]?.title ?? planAt?.title ?? '';
662
+ const saved = sanitizeChapterPlan({
663
+ chapter: chapterAt,
664
+ title,
665
+ brief: planAt?.brief ?? chapterBrief,
666
+ items: planItems,
667
+ state: 'ready',
668
+ });
669
+ if (!saved) return;
670
+ await boardApply.savePlan(saved);
671
+ setChapterAt(null);
672
+ void boardApply.start({ kind: 'chapter-write', chapter: chapterAt, title });
673
+ }, [boardApply, chapterAt, chapterBrief, columns, planAt, planItems]);
674
+
675
+ const movePlanItem = useCallback((from: number, to: number) => {
676
+ setPlanItems((items) => {
677
+ if (to < 0 || to >= items.length || from === to) return items;
678
+ const next = items.slice();
679
+ const [moved] = next.splice(from, 1);
680
+ next.splice(to, 0, moved);
681
+ return next;
682
+ });
683
+ }, []);
684
+
685
+ const editPlanItem = useCallback((at: number, title: string) => {
686
+ setPlanItems((items) => items.map((item, i) => (i === at ? { ...item, title } : item)));
687
+ }, []);
688
+
689
+ const addPlanItem = useCallback(() => {
690
+ setPlanItems((items) =>
691
+ items.length >= 8
692
+ ? items
693
+ : [
694
+ ...items,
695
+ { id: `plan-${Date.now().toString(36)}-${items.length}`, title: '', kind: 'page' },
696
+ ],
697
+ );
698
+ }, []);
699
+
700
+ useEffect(() => {
701
+ if (flashed.length === 0) return;
702
+ const timer = window.setTimeout(() => setFlashed([]), 1600);
703
+ return () => window.clearTimeout(timer);
704
+ }, [flashed]);
705
+
706
+ // The outline lays the deck out page by page; a change list applied on top
707
+ // of that would fight it.
708
+ useEffect(() => {
709
+ let cancelled = false;
710
+ const read = async () => {
711
+ try {
712
+ const res = await fetch(`/__lr/outline?slideId=${encodeURIComponent(slideId)}`);
713
+ if (!res.ok) return;
714
+ const body = (await res.json()) as { outline?: { state?: string } | null };
715
+ if (!cancelled) setBuilding(body.outline?.state === 'building');
716
+ } catch {}
717
+ };
718
+ void read();
719
+ const timer = window.setInterval(() => void read(), 3000);
720
+ return () => {
721
+ cancelled = true;
722
+ window.clearInterval(timer);
723
+ };
724
+ }, [slideId]);
725
+
726
+ const undoLastApply = useCallback(async () => {
727
+ const ok = await boardApply.undoLast();
728
+ setUndoOpen(false);
729
+ if (ok) {
730
+ toast.success(lr.board.applyUndone);
731
+ void refreshLists();
732
+ } else {
733
+ toast.error(lr.board.undoFailed);
734
+ }
735
+ }, [boardApply, lr.board.applyUndone, lr.board.undoFailed, refreshLists]);
736
+
737
+ const staleCount = useMemo(
738
+ () => staleChanges(changes, blocksOfPage).size,
739
+ [changes, blocksOfPage],
740
+ );
741
+
742
+ const applyHint = applying
743
+ ? null
744
+ : !boardApply.connected
745
+ ? lr.board.applyNeedsAgent
746
+ : building
747
+ ? lr.board.applyBuilding
748
+ : staleCount > 0
749
+ ? lr.board.applyStale
750
+ : null;
751
+
752
+ const totalChanges = changes.length + restructures.length;
753
+ const flashedPages = useMemo(
754
+ () => flashed.map((key) => keys.indexOf(key)).filter((index) => index >= 0),
755
+ [flashed, keys],
756
+ );
757
+
758
+ // ----- deck operations, each with the step that takes it back -----
759
+
760
+ /** Applies a whole new page order together with the chapters it implies. */
761
+ const performOrder = useCallback(
762
+ async (order: number[], nextColumns: BoardColumn[], count: number) => {
763
+ const settle = beginPageOp({ kind: 'reorder', order }, count);
764
+ applyColumns(nextColumns);
765
+ await reorderAll(order).then(settle);
766
+ },
767
+ [beginPageOp, applyColumns, reorderAll],
768
+ );
769
+
770
+ const performDuplicate = useCallback(
771
+ async (indices: number[], startCount: number, nextColumns: BoardColumn[]) => {
772
+ const sorted = [...new Set(indices)].sort((a, b) => b - a);
773
+ applyColumns(nextColumns);
774
+ let total = startCount;
775
+ for (const index of sorted) {
776
+ const settle = beginPageOp({ kind: 'duplicate', index }, total);
777
+ const ok = await duplicate(index);
778
+ settle(ok);
779
+ if (!ok) return false;
780
+ total += 1;
781
+ }
782
+ return true;
783
+ },
784
+ [applyColumns, beginPageOp, duplicate],
785
+ );
786
+
787
+ /** Removes pages from the highest index down. */
788
+ const performDelete = useCallback(
789
+ async (indices: number[], startCount: number, nextColumns: BoardColumn[]) => {
790
+ const sorted = [...new Set(indices)].sort((a, b) => b - a);
791
+ applyColumns(nextColumns);
792
+ let total = startCount;
793
+ for (const index of sorted) {
794
+ const settle = beginPageOp({ kind: 'delete', index }, total);
795
+ const ok = await remove(index);
796
+ settle(ok);
797
+ if (!ok) return false;
798
+ total -= 1;
799
+ }
800
+ return true;
801
+ },
802
+ [applyColumns, beginPageOp, remove],
803
+ );
804
+
805
+ const performRestore = useCallback(
806
+ async (
807
+ restores: { index: number; entry: string; card?: BoardCard | null }[],
808
+ startCount: number,
809
+ nextColumns: BoardColumn[],
810
+ ) => {
811
+ const sorted = [...restores].sort((a, b) => a.index - b.index);
812
+ applyColumns(nextColumns);
813
+ let total = startCount;
814
+ for (const { index, entry, card } of sorted) {
815
+ const settle = beginPageOp({ kind: 'restore', index, entry, card }, total);
816
+ const ok = await restore(index, entry);
817
+ settle(ok);
818
+ if (!ok) return false;
819
+ total += 1;
820
+ }
821
+ return true;
822
+ },
823
+ [applyColumns, beginPageOp, restore],
824
+ );
825
+
826
+ const movePages = useCallback(
827
+ (moving: number[], to: number) => {
828
+ if (!columns) return;
829
+ const order = orderAfterMoveMany(pageCount.current, moving, to);
830
+ if (isIdentity(order)) return;
831
+ const nextColumns = columnsAfterMoveMany(columns, moving, to);
832
+ const inverse = invertOrder(order);
833
+ const count = pageCount.current;
834
+ void performOrder(order, nextColumns, count);
835
+ history.record({
836
+ undo: () => performOrder(inverse, columns, count),
837
+ redo: () => performOrder(order, nextColumns, count),
838
+ });
839
+ },
840
+ [columns, performOrder, history],
841
+ );
842
+
843
+ const duplicatePages = useCallback(
844
+ (indices: number[]) => {
845
+ if (!columns) return;
846
+ const count = pageCount.current;
847
+ const sorted = [...new Set(indices)].sort((a, b) => b - a);
848
+ const after = (done: number) => columnsAfterInsert(columns, sorted.slice(0, done));
849
+ const steps: HistoryStep[] = sorted.map((index, at) => ({
850
+ undo: async () => {
851
+ await performDelete([index + 1], count + 1 + at, after(at));
852
+ },
853
+ redo: async () => {
854
+ await performDuplicate([index], count + at, after(at));
855
+ },
856
+ }));
857
+ void performDuplicate(sorted, count, after(sorted.length));
858
+ history.record(groupSteps(steps));
87
859
  },
88
- [beginOp, duplicate, resizeColumnAt],
860
+ [columns, performDelete, performDuplicate, history],
89
861
  );
90
862
 
91
- // A new page lands at the end of the column whose + was clicked.
92
- const addPage = useCallback(
863
+ const deletePages = useCallback(
864
+ (indices: number[]) => {
865
+ if (!columns) return;
866
+ const count = pageCount.current;
867
+ const sorted = [...new Set(indices)].sort((a, b) => b - a);
868
+ if (sorted.length === 0 || count - sorted.length < 1) return;
869
+ // What the page carried lives beside the deck, so it has to be held here
870
+ // while the page is gone or the undo would bring back an empty card.
871
+ const saved = sorted.map((index) => {
872
+ const entry = entryAt(index);
873
+ return {
874
+ index,
875
+ entry,
876
+ card: cards[index] ?? null,
877
+ linked: entry ? links.filter((link) => link.a === entry || link.b === entry) : [],
878
+ };
879
+ });
880
+ // Block moves that involve a removed page go with it, and come back with
881
+ // it: the page lands on the same entry, so the whole list is restored.
882
+ const changesBefore = changesRef.current;
883
+ const restructuresBefore = restructuresRef.current;
884
+ const before = (done: number) => columnsAfterRemove(columns, sorted.slice(0, done));
885
+ const steps: HistoryStep[] = saved.map(({ index, entry, card, linked }, at) => ({
886
+ undo: entry
887
+ ? async () => {
888
+ await performRestore([{ index, entry, card }], count - 1 - at, before(at));
889
+ addLinks(linked);
890
+ setChanges(changesBefore);
891
+ setRestructures(restructuresBefore);
892
+ }
893
+ : null,
894
+ redo: async () => {
895
+ await performDelete([index], count - at, before(at + 1));
896
+ },
897
+ }));
898
+ void performDelete(sorted, count, before(sorted.length));
899
+ history.record(groupSteps(steps));
900
+ setSelected([]);
901
+ },
902
+ [
903
+ columns,
904
+ performDelete,
905
+ performRestore,
906
+ entryAt,
907
+ cards,
908
+ links,
909
+ addLinks,
910
+ history,
911
+ setChanges,
912
+ setRestructures,
913
+ ],
914
+ );
915
+
916
+ const insertPage = useCallback(
917
+ (at: number, columnIndex: number) => {
918
+ if (!columns) return;
919
+ const count = pageCount.current;
920
+ const previous = columns;
921
+ const nextColumns = columns.map((column, i) =>
922
+ i === columnIndex ? { ...column, size: column.size + 1 } : column,
923
+ );
924
+ const run = async () => {
925
+ applyColumns(nextColumns);
926
+ const settle = beginPageOp({ kind: 'insert', index: at }, count);
927
+ const ok = await insert(at);
928
+ settle(ok);
929
+ };
930
+ void run();
931
+ history.record({
932
+ undo: async () => {
933
+ await performDelete([at], count + 1, previous);
934
+ },
935
+ redo: run,
936
+ });
937
+ },
938
+ [columns, applyColumns, beginPageOp, insert, performDelete, history],
939
+ );
940
+
941
+ const addPageToColumn = useCallback(
93
942
  (columnIndex: number) => {
94
943
  if (!columns?.[columnIndex]) return;
95
944
  const starts = columnStarts(columns);
96
945
  const start = starts[columnIndex];
97
946
  const size = columns[columnIndex].size;
98
- const at = size > 0 ? start + size : start;
99
- const settle = beginOp({ kind: 'insert', index: at });
100
- growColumn(columnIndex, 1);
101
- void insert(at).then(settle);
947
+ insertPage(size > 0 ? start + size : start, columnIndex);
102
948
  },
103
- [beginOp, columns, growColumn, insert],
949
+ [columns, insertPage],
104
950
  );
105
951
 
106
- const moveToEnd = useCallback(
107
- (index: number) => movePage(index, pages.length - 1),
108
- [movePage, pages.length],
952
+ const moveToNewChapter = useCallback(
953
+ (from: number, boundary: number) => {
954
+ if (!columns) return;
955
+ const result = insertPageColumn(columns, from, boundary, lr.board.newChapterTitle);
956
+ if (!result) return;
957
+ const inverse = invertOrder(result.order);
958
+ const count = pageCount.current;
959
+ void performOrder(result.order, result.columns, count);
960
+ history.record({
961
+ undo: () => performOrder(inverse, columns, count),
962
+ redo: () => performOrder(result.order, result.columns, count),
963
+ });
964
+ },
965
+ [columns, performOrder, history, lr.board.newChapterTitle],
966
+ );
967
+
968
+ const moveChapter = useCallback(
969
+ (from: number, to: number) => {
970
+ if (!columns) return;
971
+ const nextColumns = moveColumnBlock(columns, from, to);
972
+ if (!nextColumns) return;
973
+ const order = orderAfterColumnMove(columns, from, to);
974
+ const inverse = invertOrder(order);
975
+ const count = pageCount.current;
976
+ void performOrder(order, nextColumns, count);
977
+ history.record({
978
+ undo: () => performOrder(inverse, columns, count),
979
+ redo: () => performOrder(order, nextColumns, count),
980
+ });
981
+ },
982
+ [columns, performOrder, history],
109
983
  );
110
984
 
111
- const deletePage = useCallback(
985
+ const addChapter = useCallback(
986
+ (after: number) => {
987
+ if (!columns) return;
988
+ const previous = columns;
989
+ const next = addColumnAfter(previous, after, lr.board.newChapterTitle);
990
+ applyColumns(next);
991
+ history.record({
992
+ undo: () => applyColumns(previous),
993
+ redo: () => applyColumns(next),
994
+ });
995
+ },
996
+ [columns, applyColumns, history, lr.board.newChapterTitle],
997
+ );
998
+
999
+ const deleteChapter = useCallback(
1000
+ (index: number) => {
1001
+ if (!columns) return;
1002
+ const previous = columns;
1003
+ const next = deleteColumnAt(previous, index);
1004
+ if (!next) return;
1005
+ applyColumns(next);
1006
+ history.record({
1007
+ undo: () => applyColumns(previous),
1008
+ redo: () => applyColumns(next),
1009
+ });
1010
+ },
1011
+ [columns, applyColumns, history],
1012
+ );
1013
+
1014
+ const renameChapter = useCallback(
1015
+ (index: number, title: string) => {
1016
+ if (!columns?.[index]) return;
1017
+ const previous = columns;
1018
+ const next = renameColumnAt(previous, index, title);
1019
+ applyColumns(next);
1020
+ history.record({
1021
+ undo: () => applyColumns(previous),
1022
+ redo: () => applyColumns(next),
1023
+ });
1024
+ },
1025
+ [columns, applyColumns, history],
1026
+ );
1027
+
1028
+ const setStatusFor = useCallback(
1029
+ (indices: number[], status: CardStatus | null) => {
1030
+ if (indices.length === 0) return;
1031
+ const before = indices.map((index) => cards[index]?.status ?? null);
1032
+ for (const index of indices) patch(index, { status });
1033
+ history.record({
1034
+ undo: () => {
1035
+ for (const [at, index] of indices.entries()) patch(index, { status: before[at] });
1036
+ },
1037
+ redo: () => {
1038
+ for (const index of indices) patch(index, { status });
1039
+ },
1040
+ });
1041
+ },
1042
+ [cards, patch, history],
1043
+ );
1044
+
1045
+ const patchCard = useCallback(
1046
+ (index: number, change: CardPatch) => {
1047
+ const card = cards[index];
1048
+ const before: CardPatch = {};
1049
+ if ('title' in change) before.title = card?.title ?? null;
1050
+ if ('status' in change) before.status = card?.status ?? null;
1051
+ if ('memo' in change) before.memo = card?.memo ?? null;
1052
+ patch(index, change);
1053
+ history.record({
1054
+ undo: () => patch(index, before),
1055
+ redo: () => patch(index, change),
1056
+ });
1057
+ },
1058
+ [cards, patch, history],
1059
+ );
1060
+
1061
+ const setLink = useCallback(
1062
+ (a: number, b: number, linked: boolean) => {
1063
+ if (linked) link(a, b);
1064
+ else unlink(a, b);
1065
+ history.record({
1066
+ undo: () => (linked ? unlink(a, b) : link(a, b)),
1067
+ redo: () => (linked ? link(a, b) : unlink(a, b)),
1068
+ });
1069
+ },
1070
+ [link, unlink, history],
1071
+ );
1072
+
1073
+ const setLinkKindAt = useCallback(
1074
+ (a: number, b: number, kind: LinkKind | null) => {
1075
+ const before = pairs.find((pair) => pair.a === a && pair.b === b)?.kind ?? null;
1076
+ kindLink(a, b, kind);
1077
+ history.record({
1078
+ undo: () => kindLink(a, b, before),
1079
+ redo: () => kindLink(a, b, kind),
1080
+ });
1081
+ },
1082
+ [pairs, kindLink, history],
1083
+ );
1084
+
1085
+ /** Brings a page into view and lights it up, wherever it is being read. */
1086
+ const jumpToPage = useCallback(
1087
+ (index: number) => {
1088
+ jumpSeq.current += 1;
1089
+ setJumpTo({ index, seq: jumpSeq.current });
1090
+ setSelected([index]);
1091
+ const key = keys[index];
1092
+ if (key) setFlashed([key]);
1093
+ },
1094
+ [keys],
1095
+ );
1096
+
1097
+ const openPage = useCallback(
112
1098
  (index: number) => {
113
- if (pages.length <= 1) return;
114
- const settle = beginOp({ kind: 'delete', index });
115
- resizeColumnAt(index, -1);
116
- void remove(index).then(settle);
1099
+ navigate(`/s/${encodeURIComponent(slideId)}?p=${index + 1}`);
117
1100
  },
118
- [beginOp, pages.length, remove, resizeColumnAt],
1101
+ [navigate, slideId],
119
1102
  );
120
1103
 
1104
+ const moveToEnd = useCallback(
1105
+ (index: number) => movePages([index], pageCount.current - 1),
1106
+ [movePages],
1107
+ );
1108
+
1109
+ useEffect(() => {
1110
+ const onKey = (event: KeyboardEvent) => {
1111
+ if (isTypingTarget(event.target)) return;
1112
+ const mod = event.metaKey || event.ctrlKey;
1113
+ const undoKey = mod && (event.key === 'z' || event.key === 'Z');
1114
+ // Keys pressed inside the block panel are the panel's, not the board's;
1115
+ // undo is the one shortcut that still carries across.
1116
+ if (!undoKey && (event.target as Element | null)?.closest?.('[data-lr-block-panel]')) {
1117
+ return;
1118
+ }
1119
+ if (undoKey) {
1120
+ event.preventDefault();
1121
+ void (event.shiftKey ? history.redo() : history.undo());
1122
+ return;
1123
+ }
1124
+ if (event.key === 'Escape') {
1125
+ setSelected([]);
1126
+ return;
1127
+ }
1128
+ if ((event.key === 'Delete' || event.key === 'Backspace') && selected.length > 0) {
1129
+ event.preventDefault();
1130
+ setPendingDelete([...selected]);
1131
+ }
1132
+ };
1133
+ window.addEventListener('keydown', onKey);
1134
+ return () => window.removeEventListener('keydown', onKey);
1135
+ }, [history, selected]);
1136
+
1137
+ const confirmDelete = useCallback(() => {
1138
+ if (!pendingDelete) return;
1139
+ deletePages(pendingDelete);
1140
+ setPendingDelete(null);
1141
+ }, [pendingDelete, deletePages]);
1142
+
121
1143
  return (
122
- <div className="flex h-screen flex-col bg-background text-foreground">
123
- <header className="flex h-11 shrink-0 items-center gap-3 border-b border-hairline px-3">
1144
+ <div className="flex h-screen flex-col bg-background text-foreground" data-lr-board-view={view}>
1145
+ <header className="flex h-11 shrink-0 items-center gap-2 border-b border-hairline px-3">
124
1146
  <Button
125
1147
  variant="ghost"
126
1148
  size="icon-sm"
@@ -133,47 +1155,636 @@ export function Board() {
133
1155
  <span className="truncate text-[13px] text-muted-foreground">
134
1156
  {slide?.meta?.title ?? slideId}
135
1157
  </span>
136
- <span className="folio ml-auto">{pad2(pages.length)}</span>
137
- <span className="hidden text-[11.5px] text-muted-foreground/70 sm:inline">
1158
+ <span className="hidden truncate text-[11.5px] text-muted-foreground/70 xl:inline">
138
1159
  {lr.board.hint}
139
1160
  </span>
1161
+
1162
+ <div className="ml-auto flex items-center gap-1">
1163
+ <Button
1164
+ variant="ghost"
1165
+ size="icon-sm"
1166
+ aria-label={lr.board.undo}
1167
+ title={history.undoBlocked ? lr.board.undoUnavailable : lr.board.undo}
1168
+ disabled={!history.canUndo}
1169
+ onClick={() => void history.undo()}
1170
+ >
1171
+ <Undo2 />
1172
+ </Button>
1173
+ <Button
1174
+ variant="ghost"
1175
+ size="icon-sm"
1176
+ aria-label={lr.board.redo}
1177
+ title={lr.board.redo}
1178
+ disabled={!history.canRedo}
1179
+ onClick={() => void history.redo()}
1180
+ >
1181
+ <Redo2 />
1182
+ </Button>
1183
+ <span className="mx-1 h-5 w-px bg-hairline" aria-hidden />
1184
+ <SelfCheckButton
1185
+ record={selfCheck.record}
1186
+ running={selfCheck.running}
1187
+ onRun={() => void selfCheck.run()}
1188
+ />
1189
+ <Button
1190
+ variant="ghost"
1191
+ size="icon-sm"
1192
+ aria-label={lr.board.addChapter}
1193
+ title={lr.board.addChapter}
1194
+ disabled={!columns}
1195
+ onClick={() => addChapter((columns?.length ?? 1) - 1)}
1196
+ >
1197
+ <Columns3 />
1198
+ </Button>
1199
+ <div
1200
+ className="flex items-center rounded-[6px] border border-hairline p-0.5"
1201
+ data-lr-view-switch
1202
+ >
1203
+ {(
1204
+ [
1205
+ ['cards', LayoutGrid, lr.board.viewCards],
1206
+ ['list', ListOrdered, lr.board.viewList],
1207
+ ['timeline', GanttChart, lr.board.viewTimeline],
1208
+ ] as const
1209
+ ).map(([value, Icon, label]) => (
1210
+ <button
1211
+ key={value}
1212
+ type="button"
1213
+ aria-label={label}
1214
+ title={label}
1215
+ aria-pressed={view === value}
1216
+ data-lr-view={value}
1217
+ onClick={() => chooseView(value)}
1218
+ className={cn(
1219
+ 'flex size-6 items-center justify-center rounded-[4px] motion-safe:transition-colors',
1220
+ view === value
1221
+ ? 'bg-muted text-foreground'
1222
+ : 'text-muted-foreground/60 hover:text-foreground',
1223
+ )}
1224
+ >
1225
+ <Icon className="size-3.5" strokeWidth={1.8} />
1226
+ </button>
1227
+ ))}
1228
+ </div>
1229
+ {view === 'cards' && (
1230
+ <div className="flex items-center rounded-[6px] border border-hairline p-0.5">
1231
+ {(
1232
+ [
1233
+ ['large', ImageIcon, lr.board.sizeLarge],
1234
+ ['small', Grid2X2, lr.board.sizeSmall],
1235
+ ['title', List, lr.board.sizeTitle],
1236
+ ] as const
1237
+ ).map(([value, Icon, label]) => (
1238
+ <button
1239
+ key={value}
1240
+ type="button"
1241
+ aria-label={label}
1242
+ title={label}
1243
+ aria-pressed={size === value}
1244
+ onClick={() => chooseSize(value)}
1245
+ className={cn(
1246
+ 'flex size-6 items-center justify-center rounded-[4px] motion-safe:transition-colors',
1247
+ size === value
1248
+ ? 'bg-muted text-foreground'
1249
+ : 'text-muted-foreground/60 hover:text-foreground',
1250
+ )}
1251
+ >
1252
+ <Icon className="size-3.5" strokeWidth={1.8} />
1253
+ </button>
1254
+ ))}
1255
+ </div>
1256
+ )}
1257
+ <Button
1258
+ variant="ghost"
1259
+ size="icon-sm"
1260
+ aria-label={lr.board.blockPanel}
1261
+ title={lr.board.blockPanel}
1262
+ aria-pressed={showBlocks}
1263
+ onClick={toggleBlocks}
1264
+ className={cn(showBlocks && 'text-foreground')}
1265
+ >
1266
+ <Rows3 />
1267
+ </Button>
1268
+ {applying ? (
1269
+ boardApply.stalled ? (
1270
+ <span className="flex items-center gap-1">
1271
+ <span className="text-[12px] text-destructive" data-lr-apply-stalled>
1272
+ {lr.board.applyStalled}
1273
+ </span>
1274
+ <Button
1275
+ variant="ghost"
1276
+ size="sm"
1277
+ onClick={() => void boardApply.cancel()}
1278
+ data-lr-apply-cancel
1279
+ >
1280
+ {lr.board.applyCancel}
1281
+ </Button>
1282
+ </span>
1283
+ ) : (
1284
+ <span
1285
+ className="flex items-center gap-1.5 text-[12px] text-muted-foreground"
1286
+ data-lr-applying
1287
+ >
1288
+ <span className="size-1.5 rounded-full bg-[var(--lr-accent)]" />
1289
+ {applyingLabel}
1290
+ </span>
1291
+ )
1292
+ ) : (
1293
+ <>
1294
+ {totalChanges > 0 && (
1295
+ <Popover open={listOpen} onOpenChange={setListOpen}>
1296
+ <PopoverTrigger
1297
+ type="button"
1298
+ className={cn(buttonVariants({ variant: 'ghost', size: 'sm' }), 'tabular-nums')}
1299
+ >
1300
+ {format(lr.board.changes, { n: totalChanges })}
1301
+ </PopoverTrigger>
1302
+ <PopoverContent align="end" className="w-[360px] p-0">
1303
+ <ChangeList
1304
+ changes={changes}
1305
+ restructures={restructures}
1306
+ pageKeys={keys}
1307
+ readOf={blocksOfPage}
1308
+ onRemove={removeChanges}
1309
+ onRemoveRestructure={(index) => removeRestructures([index])}
1310
+ readOnly={applying}
1311
+ apply={{
1312
+ onApply: () => {
1313
+ setListOpen(false);
1314
+ void boardApply.start({ kind: 'changes' });
1315
+ },
1316
+ disabled: applyHint !== null,
1317
+ hint: applyHint,
1318
+ starting: boardApply.starting,
1319
+ }}
1320
+ />
1321
+ </PopoverContent>
1322
+ </Popover>
1323
+ )}
1324
+ {boardApply.lastApply?.ok && (
1325
+ <Button variant="ghost" size="sm" data-lr-undo-last onClick={askUndo}>
1326
+ {lr.board.applyUndoLast}
1327
+ </Button>
1328
+ )}
1329
+ </>
1330
+ )}
1331
+ <DropdownMenu>
1332
+ <DropdownMenuTrigger
1333
+ type="button"
1334
+ aria-label={lr.board.filter}
1335
+ title={lr.board.filter}
1336
+ className={cn(
1337
+ buttonVariants({ variant: 'ghost', size: 'icon-sm' }),
1338
+ filterActive && 'text-foreground',
1339
+ )}
1340
+ >
1341
+ <Filter />
1342
+ </DropdownMenuTrigger>
1343
+ <DropdownMenuContent align="end" className="min-w-[190px]">
1344
+ <DropdownMenuGroup>
1345
+ <DropdownMenuLabel>{lr.board.filterStatus}</DropdownMenuLabel>
1346
+ {CARD_STATUSES.map((value) => (
1347
+ <DropdownMenuCheckboxItem
1348
+ key={value}
1349
+ checked={filter.statuses.includes(value)}
1350
+ onCheckedChange={() => setFilter((current) => toggleStatus(current, value))}
1351
+ >
1352
+ {labels[value]}
1353
+ </DropdownMenuCheckboxItem>
1354
+ ))}
1355
+ </DropdownMenuGroup>
1356
+ <DropdownMenuSeparator />
1357
+ <DropdownMenuGroup>
1358
+ <DropdownMenuCheckboxItem
1359
+ checked={filter.memo}
1360
+ onCheckedChange={() =>
1361
+ setFilter((current) => ({ ...current, memo: !current.memo }))
1362
+ }
1363
+ >
1364
+ {lr.board.filterMemo}
1365
+ </DropdownMenuCheckboxItem>
1366
+ <DropdownMenuCheckboxItem
1367
+ checked={filter.comments}
1368
+ onCheckedChange={() =>
1369
+ setFilter((current) => ({ ...current, comments: !current.comments }))
1370
+ }
1371
+ >
1372
+ {lr.board.filterComments}
1373
+ </DropdownMenuCheckboxItem>
1374
+ </DropdownMenuGroup>
1375
+ <DropdownMenuSeparator />
1376
+ <DropdownMenuItem onClick={() => setFilter(EMPTY_FILTER)}>
1377
+ {lr.board.filterClear}
1378
+ </DropdownMenuItem>
1379
+ </DropdownMenuContent>
1380
+ </DropdownMenu>
1381
+ </div>
1382
+ <span className="folio">{pad2(pages.length)}</span>
140
1383
  </header>
141
- <div className="relative min-h-0 flex-1">
142
- {error ? (
143
- <p className="grid h-full place-items-center px-6 text-center text-[13px] text-destructive">
144
- {error}
145
- </p>
146
- ) : pages.length === 0 || !columns ? (
147
- <p className="grid h-full place-items-center text-[13px] text-muted-foreground">
148
- {lr.board.loading}
149
- </p>
150
- ) : (
151
- <Suspense fallback={null}>
152
- <BoardCanvas
153
- slideId={slideId}
154
- pages={pages}
155
- notes={slide?.notes}
156
- cards={cards}
157
- cardsReady={ready}
158
- links={pairs}
159
- showLinks={showLinks}
160
- columns={columns}
161
- design={slide?.design}
162
- onOpenPage={openPage}
163
- onMovePage={movePage}
164
- onRenameColumn={renameColumn}
165
- onAddPage={addPage}
166
- onDuplicate={duplicatePage}
167
- onDelete={deletePage}
168
- onMoveToEnd={moveToEnd}
169
- onPatchCard={patch}
170
- onLink={link}
171
- onUnlink={unlink}
172
- onToggleLinks={toggleLinks}
173
- />
174
- </Suspense>
1384
+
1385
+ {selfCheck.runner && <SelfCheckRunner {...selfCheck.runner} />}
1386
+
1387
+ <div className="flex min-h-0 flex-1">
1388
+ <div className="relative min-h-0 min-w-0 flex-1">
1389
+ {error ? (
1390
+ <p className="grid h-full place-items-center px-6 text-center text-[13px] text-destructive">
1391
+ {error}
1392
+ </p>
1393
+ ) : pages.length === 0 || !columns ? (
1394
+ <p className="grid h-full place-items-center text-[13px] text-muted-foreground">
1395
+ {lr.board.loading}
1396
+ </p>
1397
+ ) : (
1398
+ <>
1399
+ {selected.length > 0 && (
1400
+ <div className="pointer-events-auto absolute left-1/2 top-3 z-10 flex -translate-x-1/2 items-center gap-1 rounded-[8px] border border-hairline bg-card px-2 py-1 shadow-edge">
1401
+ <span className="px-1 text-[12px] text-muted-foreground">
1402
+ {format(lr.board.selected, { n: selected.length })}
1403
+ </span>
1404
+ <DropdownMenu>
1405
+ <DropdownMenuTrigger
1406
+ type="button"
1407
+ className={buttonVariants({ variant: 'ghost', size: 'sm' })}
1408
+ >
1409
+ {lr.board.status}
1410
+ </DropdownMenuTrigger>
1411
+ <DropdownMenuContent align="center" className="min-w-[150px]">
1412
+ {CARD_STATUSES.map((value) => (
1413
+ <DropdownMenuItem key={value} onClick={() => setStatusFor(selected, value)}>
1414
+ {labels[value]}
1415
+ </DropdownMenuItem>
1416
+ ))}
1417
+ <DropdownMenuSeparator />
1418
+ <DropdownMenuItem onClick={() => setStatusFor(selected, null)}>
1419
+ {lr.board.statusNone}
1420
+ </DropdownMenuItem>
1421
+ </DropdownMenuContent>
1422
+ </DropdownMenu>
1423
+ {selected.length === 2 && (
1424
+ <Button
1425
+ variant="ghost"
1426
+ size="icon-sm"
1427
+ aria-label={lr.board.mergePages}
1428
+ title={lr.board.mergePages}
1429
+ data-lr-merge-pages
1430
+ onClick={mergeSelected}
1431
+ >
1432
+ <Combine />
1433
+ </Button>
1434
+ )}
1435
+ <Button
1436
+ variant="ghost"
1437
+ size="icon-sm"
1438
+ aria-label={t.thumbnailRail.duplicatePage}
1439
+ title={t.thumbnailRail.duplicatePage}
1440
+ onClick={() => duplicatePages(selected)}
1441
+ >
1442
+ <Copy />
1443
+ </Button>
1444
+ <Button
1445
+ variant="ghost"
1446
+ size="icon-sm"
1447
+ aria-label={t.thumbnailRail.deletePage}
1448
+ title={t.thumbnailRail.deletePage}
1449
+ onClick={() => setPendingDelete([...selected])}
1450
+ >
1451
+ <Trash2 />
1452
+ </Button>
1453
+ <Button
1454
+ variant="ghost"
1455
+ size="icon-sm"
1456
+ aria-label={lr.board.clearSelection}
1457
+ title={lr.board.clearSelection}
1458
+ onClick={() => setSelected([])}
1459
+ >
1460
+ <X />
1461
+ </Button>
1462
+ </div>
1463
+ )}
1464
+ {view !== 'cards' && <BlockReadings pages={pages} design={slide?.design} />}
1465
+ {view === 'cards' ? (
1466
+ <Suspense fallback={null}>
1467
+ <BoardCanvas
1468
+ slideId={slideId}
1469
+ pages={pages}
1470
+ notes={slide?.notes}
1471
+ cards={cards}
1472
+ cardsReady={ready}
1473
+ links={pairs}
1474
+ showLinks={showLinks}
1475
+ columns={columns}
1476
+ progress={columnProgress}
1477
+ design={slide?.design}
1478
+ size={size}
1479
+ collapsed={collapsed}
1480
+ dimmed={dimmed}
1481
+ changeCounts={changeCounts}
1482
+ selected={selected}
1483
+ onSelect={setSelected}
1484
+ onOpenPage={openPage}
1485
+ onMovePages={movePages}
1486
+ onMoveToNewChapter={moveToNewChapter}
1487
+ onRenameColumn={renameChapter}
1488
+ onAddPage={addPageToColumn}
1489
+ onAddChapter={addChapter}
1490
+ onDeleteChapter={deleteChapter}
1491
+ onToggleCollapse={toggleCollapse}
1492
+ onMoveChapter={moveChapter}
1493
+ onDuplicate={(index) => duplicatePages([index])}
1494
+ onDelete={(index) => deletePages([index])}
1495
+ onMoveToEnd={moveToEnd}
1496
+ onPatchCard={patchCard}
1497
+ onLink={(a, b) => setLink(a, b, true)}
1498
+ onUnlink={(a, b) => setLink(a, b, false)}
1499
+ onSetLinkKind={setLinkKindAt}
1500
+ onJump={jumpToPage}
1501
+ onToggleLinks={toggleLinks}
1502
+ flashed={flashedPages}
1503
+ agentHint={agentHint}
1504
+ onPageTask={startPageTask}
1505
+ planFor={planFor}
1506
+ onFillChapter={openChapter}
1507
+ onViewPlan={openChapter}
1508
+ />
1509
+ </Suspense>
1510
+ ) : view === 'list' ? (
1511
+ <ListView
1512
+ pages={pages}
1513
+ keys={keys}
1514
+ cards={cards}
1515
+ byKey={byKey}
1516
+ columns={columns}
1517
+ notes={slide?.notes}
1518
+ comments={comments}
1519
+ dimmed={dimmed}
1520
+ changeCounts={changeCounts}
1521
+ selected={selected}
1522
+ jumpTo={jumpTo}
1523
+ onSelect={setSelected}
1524
+ onOpenPage={openPage}
1525
+ onPatchCard={patchCard}
1526
+ onMovePages={movePages}
1527
+ blocksOfPage={blocksOfPage}
1528
+ />
1529
+ ) : (
1530
+ <TimelineView
1531
+ pages={pages}
1532
+ keys={keys}
1533
+ cards={cards}
1534
+ columns={columns}
1535
+ notes={slide?.notes}
1536
+ dimmed={dimmed}
1537
+ selected={selected}
1538
+ target={target}
1539
+ targetFor={chooseTarget}
1540
+ onSelect={setSelected}
1541
+ onOpenPage={openPage}
1542
+ onMovePages={movePages}
1543
+ blocksOfPage={blocksOfPage}
1544
+ />
1545
+ )}
1546
+ </>
1547
+ )}
1548
+ </div>
1549
+ {showBlocks && (
1550
+ <BlockPanel
1551
+ slideId={slideId}
1552
+ pages={pages}
1553
+ pageKeys={keys}
1554
+ design={slide?.design}
1555
+ selected={selected.length > 0 ? selected[selected.length - 1] : null}
1556
+ changes={changes}
1557
+ onChanges={applyChanges}
1558
+ cardTitle={(index) => cards[index]?.title ?? ''}
1559
+ cardMemo={(index) => cards[index]?.memo ?? ''}
1560
+ agent={{
1561
+ hint:
1562
+ agentHint ??
1563
+ (selected.length > 0 && changeCounts[selected[selected.length - 1]] > 0
1564
+ ? lr.board.askHasChanges
1565
+ : null),
1566
+ onTask: (action) => {
1567
+ const at = selected[selected.length - 1];
1568
+ if (at !== undefined) startPageTask(at, action);
1569
+ },
1570
+ }}
1571
+ readOnly={applying}
1572
+ onSplit={splitPage}
1573
+ />
175
1574
  )}
176
1575
  </div>
1576
+
1577
+ <Dialog
1578
+ open={pendingDelete !== null}
1579
+ onOpenChange={(open) => {
1580
+ if (!open) setPendingDelete(null);
1581
+ }}
1582
+ >
1583
+ <DialogContent>
1584
+ <DialogHeader>
1585
+ <DialogTitle>
1586
+ {format(lr.board.deleteSelectedTitle, { n: pendingDelete?.length ?? 0 })}
1587
+ </DialogTitle>
1588
+ <DialogDescription>{lr.board.deleteSelectedHint}</DialogDescription>
1589
+ </DialogHeader>
1590
+ <DialogFooter>
1591
+ <Button variant="outline" size="sm" onClick={() => setPendingDelete(null)}>
1592
+ {t.common.cancel}
1593
+ </Button>
1594
+ <Button variant="destructive" size="sm" onClick={confirmDelete}>
1595
+ {t.common.delete}
1596
+ </Button>
1597
+ </DialogFooter>
1598
+ </DialogContent>
1599
+ </Dialog>
1600
+ <Dialog open={undoOpen} onOpenChange={setUndoOpen}>
1601
+ <DialogContent>
1602
+ <DialogHeader>
1603
+ <DialogTitle>{lr.board.applyUndoConfirm.title}</DialogTitle>
1604
+ <DialogDescription>{lr.board.applyUndoConfirm.body}</DialogDescription>
1605
+ </DialogHeader>
1606
+ <DialogFooter>
1607
+ <Button variant="outline" size="sm" onClick={() => setUndoOpen(false)}>
1608
+ {t.common.cancel}
1609
+ </Button>
1610
+ <Button variant="destructive" size="sm" onClick={() => void undoLastApply()}>
1611
+ {lr.board.applyUndoConfirm.confirm}
1612
+ </Button>
1613
+ </DialogFooter>
1614
+ </DialogContent>
1615
+ </Dialog>
1616
+ <Dialog
1617
+ open={chapterAt !== null}
1618
+ onOpenChange={(open) => {
1619
+ if (!open) setChapterAt(null);
1620
+ }}
1621
+ >
1622
+ <DialogContent data-lr-chapter-dialog>
1623
+ <DialogHeader>
1624
+ <DialogTitle>{lr.board.fillChapter}</DialogTitle>
1625
+ <DialogDescription>
1626
+ {chapterAt === null
1627
+ ? ''
1628
+ : columns?.[chapterAt]?.title ||
1629
+ format(lr.board.columnFallback, { n: chapterAt + 1 })}
1630
+ </DialogDescription>
1631
+ </DialogHeader>
1632
+
1633
+ {planAt?.state === 'ready' ? (
1634
+ <div className="flex flex-col gap-1.5" data-lr-plan-list>
1635
+ {planItems.map((item, at) => (
1636
+ <div key={item.id} className="flex items-center gap-1" data-lr-plan-item>
1637
+ <input
1638
+ value={item.title}
1639
+ aria-label={`${lr.board.writeChapter} ${at + 1}`}
1640
+ onChange={(event) => editPlanItem(at, event.currentTarget.value)}
1641
+ className="min-w-0 flex-1 rounded-[4px] border border-hairline bg-background px-2 py-1 text-[12.5px] outline-none focus:ring-1 focus:ring-brand/50"
1642
+ />
1643
+ <Button
1644
+ type="button"
1645
+ variant="ghost"
1646
+ size="icon-sm"
1647
+ aria-label={lr.board.planMoveUp}
1648
+ disabled={at === 0}
1649
+ onClick={() => movePlanItem(at, at - 1)}
1650
+ >
1651
+ <ChevronUp />
1652
+ </Button>
1653
+ <Button
1654
+ type="button"
1655
+ variant="ghost"
1656
+ size="icon-sm"
1657
+ aria-label={lr.board.planMoveDown}
1658
+ disabled={at === planItems.length - 1}
1659
+ onClick={() => movePlanItem(at, at + 1)}
1660
+ >
1661
+ <ChevronDown />
1662
+ </Button>
1663
+ <Button
1664
+ type="button"
1665
+ variant="ghost"
1666
+ size="icon-sm"
1667
+ aria-label={lr.board.planRemove}
1668
+ onClick={() => setPlanItems((items) => items.filter((_, i) => i !== at))}
1669
+ >
1670
+ <X />
1671
+ </Button>
1672
+ </div>
1673
+ ))}
1674
+ <Button
1675
+ type="button"
1676
+ variant="ghost"
1677
+ size="sm"
1678
+ className="self-start"
1679
+ data-lr-add-plan-item
1680
+ disabled={planItems.length >= 8}
1681
+ onClick={addPlanItem}
1682
+ >
1683
+ <Plus />
1684
+ {lr.board.addPlanItem}
1685
+ </Button>
1686
+ </div>
1687
+ ) : planAt?.state === 'failed' ? (
1688
+ <p className="text-[12.5px] text-destructive" data-lr-plan-error>
1689
+ {planAt.error || lr.board.planFailed}
1690
+ </p>
1691
+ ) : (
1692
+ <div className="flex flex-col gap-3">
1693
+ <label className="flex flex-col gap-1 text-[12.5px]">
1694
+ <span>{lr.board.chapterBrief}</span>
1695
+ <textarea
1696
+ value={chapterBrief}
1697
+ maxLength={500}
1698
+ rows={4}
1699
+ data-lr-chapter-brief
1700
+ onChange={(event) => setChapterBrief(event.currentTarget.value)}
1701
+ className="resize-none rounded-[4px] border border-hairline bg-background px-2 py-1.5 text-[12.5px] outline-none focus:ring-1 focus:ring-brand/50"
1702
+ />
1703
+ </label>
1704
+ <label className="flex items-center gap-2 text-[12.5px]">
1705
+ <span>{lr.board.chapterCount}</span>
1706
+ <input
1707
+ type="number"
1708
+ min={1}
1709
+ max={8}
1710
+ value={chapterCount}
1711
+ data-lr-chapter-count
1712
+ onChange={(event) =>
1713
+ setChapterCount(
1714
+ Math.min(8, Math.max(1, Math.trunc(Number(event.currentTarget.value) || 1))),
1715
+ )
1716
+ }
1717
+ className="w-16 rounded-[4px] border border-hairline bg-background px-2 py-1 text-[12.5px] tabular-nums outline-none focus:ring-1 focus:ring-brand/50"
1718
+ />
1719
+ </label>
1720
+ </div>
1721
+ )}
1722
+
1723
+ {planningHere && (
1724
+ <p className="text-[12px] text-muted-foreground" data-lr-planning-dialog>
1725
+ {lr.board.planning}
1726
+ </p>
1727
+ )}
1728
+
1729
+ <DialogFooter>
1730
+ {planAt?.state === 'ready' ? (
1731
+ <>
1732
+ <Button variant="outline" size="sm" onClick={dropChapterPlan}>
1733
+ {lr.board.dropPlan}
1734
+ </Button>
1735
+ <Button
1736
+ size="sm"
1737
+ data-lr-write-chapter
1738
+ disabled={writingHere || planItems.length === 0}
1739
+ onClick={() => void writeChapter()}
1740
+ >
1741
+ {format(lr.board.writeChapter, { n: planItems.length })}
1742
+ </Button>
1743
+ </>
1744
+ ) : planAt?.state === 'failed' ? (
1745
+ <>
1746
+ <Button variant="outline" size="sm" onClick={dropChapterPlan}>
1747
+ {lr.board.dropPlan}
1748
+ </Button>
1749
+ <Button
1750
+ size="sm"
1751
+ data-lr-retry-plan
1752
+ disabled={planningHere || agentHint !== null}
1753
+ onClick={startChapterPlan}
1754
+ >
1755
+ {lr.board.retryPlan}
1756
+ </Button>
1757
+ </>
1758
+ ) : (
1759
+ <>
1760
+ <Button variant="outline" size="sm" onClick={() => setChapterAt(null)}>
1761
+ {t.common.cancel}
1762
+ </Button>
1763
+ <Button
1764
+ size="sm"
1765
+ data-lr-plan-chapter
1766
+ disabled={!chapterBrief.trim() || planningHere || agentHint !== null}
1767
+ onClick={startChapterPlan}
1768
+ >
1769
+ {lr.board.planChapter}
1770
+ </Button>
1771
+ </>
1772
+ )}
1773
+ </DialogFooter>
1774
+ </DialogContent>
1775
+ </Dialog>
177
1776
  </div>
178
1777
  );
179
1778
  }
1779
+
1780
+ /** Several steps taken as one, so a single undo takes back the whole batch. */
1781
+ function groupSteps(steps: HistoryStep[]): HistoryStep {
1782
+ return {
1783
+ undo: async () => {
1784
+ for (const step of [...steps].reverse()) if (step.undo) await step.undo();
1785
+ },
1786
+ redo: async () => {
1787
+ for (const step of steps) await step.redo();
1788
+ },
1789
+ };
1790
+ }