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