@connectorvol/tree 2.1.2 → 4.0.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 (52) hide show
  1. package/dist/(classes)/chessTree.svelte.d.ts +83 -0
  2. package/dist/(classes)/chessTree.svelte.js +198 -0
  3. package/dist/(components)/DrillBreadcrumbs.svelte +135 -0
  4. package/dist/(components)/DrillBreadcrumbs.svelte.d.ts +20 -0
  5. package/dist/(components)/DrillForkSanLabel.svelte +26 -0
  6. package/dist/(components)/DrillForkSanLabel.svelte.d.ts +11 -0
  7. package/dist/(components)/DrillVariationList.svelte +65 -0
  8. package/dist/(components)/DrillVariationList.svelte.d.ts +15 -0
  9. package/dist/(components)/Move.svelte +247 -171
  10. package/dist/(components)/Move.svelte.d.ts +11 -5
  11. package/dist/(components)/MoveComment.svelte +32 -0
  12. package/dist/(components)/MoveComment.svelte.d.ts +11 -0
  13. package/dist/(components)/MoveContextMenu.svelte +73 -0
  14. package/dist/(components)/MoveContextMenu.svelte.d.ts +17 -0
  15. package/dist/(components)/MoveSanWithMenu.svelte +158 -0
  16. package/dist/(components)/MoveSanWithMenu.svelte.d.ts +42 -0
  17. package/dist/(components)/NagBadges.svelte +37 -0
  18. package/dist/(components)/NagBadges.svelte.d.ts +9 -0
  19. package/dist/(components)/TreeViewer.svelte +843 -42
  20. package/dist/(components)/TreeViewer.svelte.d.ts +29 -3
  21. package/dist/(components)/TreeViewerPanelManager.svelte +18 -155
  22. package/dist/(components)/VariantDropdownNavigator.svelte +173 -0
  23. package/dist/(components)/VariantDropdownNavigator.svelte.d.ts +16 -0
  24. package/dist/(components)/VariationGroup.svelte +100 -0
  25. package/dist/(components)/VariationGroup.svelte.d.ts +21 -0
  26. package/dist/(constants)/png.d.ts +1 -1
  27. package/dist/(constants)/png.js +2 -4
  28. package/dist/(models)/nagCatalog.d.ts +36 -0
  29. package/dist/(models)/nagCatalog.js +97 -0
  30. package/dist/(models)/pgnNodeCustomData.d.ts +3 -0
  31. package/dist/(utils)/context.d.ts +10 -3
  32. package/dist/(utils)/context.js +3 -14
  33. package/dist/(utils)/createPreviewHover.d.ts +19 -0
  34. package/dist/(utils)/createPreviewHover.js +37 -0
  35. package/dist/(utils)/nagBadgeStyle.d.ts +1 -0
  36. package/dist/(utils)/nagBadgeStyle.js +1 -0
  37. package/dist/(utils)/scrollToActiveMove.js +6 -5
  38. package/dist/(utils)/transformNag.d.ts +1 -1
  39. package/dist/(utils)/transformNag.js +1 -34
  40. package/dist/(utils)/transformPgnToChessNode.js +13 -0
  41. package/dist/(utils)/treeViewerPanelNavigation.svelte.d.ts +39 -0
  42. package/dist/(utils)/treeViewerPanelNavigation.svelte.js +257 -0
  43. package/dist/components/ui/button/button-variants.d.ts +65 -0
  44. package/dist/components/ui/button/button-variants.js +28 -0
  45. package/dist/components/ui/button/button.svelte +3 -43
  46. package/dist/components/ui/button/button.svelte.d.ts +1 -61
  47. package/dist/components/ui/button/index.d.ts +3 -2
  48. package/dist/components/ui/button/index.js +3 -4
  49. package/dist/components/ui/button-group/button-group-separator.svelte.d.ts +1 -1
  50. package/dist/index.d.ts +2 -1
  51. package/dist/index.js +2 -1
  52. package/package.json +4 -4
@@ -1,82 +1,883 @@
1
1
  <script lang="ts">
2
2
  import type { ClassValue } from "svelte/elements";
3
3
  import { ChessTree } from "../(classes)/chessTree.svelte.js";
4
+ import type { ChessTreeNode } from "../(models)/chessTreeNode.js";
4
5
 
5
6
  import Move from "./Move.svelte";
6
- import { initGameContext } from "../(utils)/context.js";
7
- import type { PieceSet } from "@connectorvol/shared";
7
+ import DrillBreadcrumbs from "./DrillBreadcrumbs.svelte";
8
+ import DrillVariationList from "./DrillVariationList.svelte";
9
+ import VariantDropdownNavigator from "./VariantDropdownNavigator.svelte";
10
+ import MoveComment from "./MoveComment.svelte";
11
+ import {
12
+ CHESS_TREE_CONTEXT_KEY,
13
+ type GameContext,
14
+ } from "../(utils)/context.js";
15
+ import {
16
+ type Comment,
17
+ makeComment,
18
+ parseComment,
19
+ } from "@connectorvol/chessops/pgn";
20
+ import type { Move as TSharedMove, PieceSet } from "@connectorvol/shared";
21
+ import {
22
+ isMoveEvaluationNag,
23
+ isPuzzleBranchNag,
24
+ NOVELTY_NAG_ID,
25
+ nagBadgeBackground,
26
+ transformNag as transformNagId,
27
+ } from "@connectorvol/shared";
28
+ import {
29
+ isPositionEvaluationNag,
30
+ nagDescription,
31
+ SELECTABLE_NAG_IDS_ORDERED,
32
+ } from "../(models)/nagCatalog.js";
33
+ import { setContext } from "svelte";
34
+ import type { Attachment } from "svelte/attachments";
35
+ import {
36
+ ACTIVE_MOVE_CLASS,
37
+ scrollToActiveMoveIfNeeded,
38
+ } from "../(utils)/scrollToActiveMove.js";
39
+ import {
40
+ getOrCreateTreeViewerPanelNavigation,
41
+ type TVariantNavigatorHandle,
42
+ } from "../(utils)/treeViewerPanelNavigation.svelte.js";
43
+ import { createPgnFromTree } from "../(utils)/createPgnFromTree.js";
44
+ import { transformPgnToChessNode } from "../(utils)/transformPgnToChessNode.js";
45
+ import Redo2Icon from "@lucide/svelte/icons/redo-2";
46
+ import Undo2Icon from "@lucide/svelte/icons/undo-2";
8
47
 
9
- type Props = {
48
+ /** Представляет снимок PGN и пути варианта к выбранной ноде для undo/redo. */
49
+ type TPgnHistoryEntry = {
50
+ /** Возвращает полную строку PGN партии. */
51
+ pgn: string;
52
+ /** Возвращает индексы детей от `rootNode.moves` к текущей ноде (пустой — узел начала партии). */
53
+ variationPath: number[];
54
+ };
55
+
56
+ type TPreviewOnHoverChessNodeSettings = {
57
+ /** Возвращает функцию для установки FEN превью при наведении (null скрывает); второй аргумент — подсветка последнего хода. */
58
+ setPreviewFen?: (fen: string | null, lastMove?: TSharedMove | null) => void;
59
+ /** Возвращает задержку (мс) до показа превью-позиции при наведении на ноду, либо `off` для отключения. */
60
+ delayMs?: number | "off";
61
+ };
62
+
63
+ type TTreeViewerProps = {
64
+ /** Возвращает дерево партии. */
10
65
  chessTree: ChessTree;
66
+ /** Возвращает дополнительные классы корневого контейнера. */
11
67
  className?: ClassValue;
68
+ /** Возвращает колбэк после выбора узла в дереве. */
12
69
  onSelectNode: () => void;
70
+ /** Возвращает колбэк после удаления варианта. */
13
71
  onDeleteVariant: () => void;
72
+ /** Возвращает колбэк после выбора узла (после `onSelectNode`), передаётся актуальный `currentNode`. */
73
+ onChessNodeSelected?: (node: ChessTreeNode) => void;
74
+ /** Возвращает функцию установки FEN основной партии. */
14
75
  setChessFen: (fen: string) => void;
76
+ /** Возвращает функцию обновления доски. */
15
77
  setChessboardFen: (animationTime?: number) => void;
78
+ /** Возвращает набор фигур для иконок SAN. */
16
79
  pieceSet: PieceSet;
17
80
  /** Возвращает true, если клик по ходу переключает текущий узел и доску. По умолчанию true. */
18
81
  selectable?: boolean;
82
+ /** Возвращает настройки превью-доски при наведении на ноду. */
83
+ previewOnHoverChessNodeSettings?: TPreviewOnHoverChessNodeSettings;
84
+ /** Возвращает функцию для установки FEN превью при наведении (null скрывает); второй аргумент — подсветка последнего хода. */
85
+ setPreviewFen?: (fen: string | null, lastMove?: TSharedMove | null) => void;
86
+ /** Возвращает задержку (мс) до показа превью-позиции при наведении на ноду, либо `off` для отключения. */
87
+ previewHoverDelayMs?: number | "off";
88
+ /** Возвращает true, если под деревом показываются комментарий и выбор NAG для текущей ноды. */
89
+ editMode?: boolean;
90
+ /** Возвращает функцию для установки признака несохранённости дерева. */
91
+ onChangeDirty?: (setIsDirty: (value: boolean) => void) => void;
19
92
  };
20
93
 
21
- const {
94
+ let {
22
95
  className,
23
96
  onSelectNode,
24
97
  onDeleteVariant,
98
+ onChessNodeSelected,
25
99
  setChessFen,
26
100
  setChessboardFen,
27
101
  chessTree,
28
102
  pieceSet,
29
103
  selectable = true,
30
- }: Props = $props();
104
+ previewOnHoverChessNodeSettings,
105
+ setPreviewFen,
106
+ previewHoverDelayMs = 700,
107
+ editMode = false,
108
+ onChangeDirty
109
+ }: TTreeViewerProps = $props();
31
110
 
32
- initGameContext(
33
- chessTree,
34
- onSelectNode,
35
- onDeleteVariant,
36
- setChessFen,
37
- setChessboardFen,
38
- selectable
111
+ const previewSettings = $derived(previewOnHoverChessNodeSettings);
112
+ const previewFenSetter = $derived(
113
+ previewSettings?.setPreviewFen ?? setPreviewFen,
114
+ );
115
+ const previewDelayMs = $derived(
116
+ previewSettings?.delayMs ?? previewHoverDelayMs,
39
117
  );
40
- </script>
41
118
 
42
- {#snippet comment(text: string)}
43
- <div
44
- class={{
45
- "col-span-3 flex flex-col p-8 select-text": true,
46
- }}
47
- >
48
- {#each text.split("\n") as line, index}
49
- {#if index > 0}<br />{/if}{line}
50
- {/each}
51
- </div>
52
- {/snippet}
119
+ setContext<GameContext>(CHESS_TREE_CONTEXT_KEY, {
120
+ chessTree: (() => chessTree)(),
121
+ onSelectNode: (() => onSelectNode)(),
122
+ onDeleteVariant: (() => onDeleteVariant)(),
123
+ onChessNodeSelected: (() => onChessNodeSelected)(),
124
+ setChessFen: (() => setChessFen)(),
125
+ setChessboardFen: (() => setChessboardFen)(),
126
+ setPreviewFen: (() =>
127
+ previewFenSetter
128
+ ? (fen, lastMove) => previewFenSetter(fen, lastMove)
129
+ : undefined)(),
130
+ previewHoverDelayMs: (() => previewDelayMs)(),
131
+ selectable: (() => selectable)(),
132
+ });
133
+
134
+ const panelNav = $derived.by(() =>
135
+ getOrCreateTreeViewerPanelNavigation(chessTree),
136
+ );
137
+
138
+ let variantDropdownNavigator = $state<TVariantNavigatorHandle | null>(null);
139
+
140
+ $effect(() => {
141
+ panelNav.bindCallbacks(setChessFen, setChessboardFen);
142
+ });
143
+
144
+ $effect(() => {
145
+ const nav = panelNav;
146
+ nav.setVariantNavigator(variantDropdownNavigator);
147
+ return () => {
148
+ nav.setVariantNavigator(null);
149
+ };
150
+ });
151
+
152
+ $effect(() => {
153
+ const nav = panelNav;
154
+ return () => {
155
+ nav.dispose();
156
+ };
157
+ });
158
+
159
+ /** Представляет true, если доступно редактирование комментария и NAG (есть интерактивный выбор ноды). */
160
+ const canEditAnnotations = $derived(editMode && selectable);
161
+
162
+ /** Представляет актуальную строку PGN, восстановленную из дерева (для отслеживания изменений). */
163
+ const serializedPgn = $derived.by(() => createPgnFromTree(chessTree.rootNode));
164
+
165
+ /** Представляет признак: текущий PGN отличается от снимка при монтировании дерева в просмотрщике. */
166
+ let isDirty = $state(false);
167
+
168
+ /** Представляет строку PGN при первом отслеживании (эталон «несохранённости»). */
169
+ let initialPgnSnapshot = $state<string | null>(null);
170
+
171
+ /** Представляет предыдущее значение `serializedPgn` для обнаружения мутаций. */
172
+ let previousSerializedPgn = $state<string | null>(null);
173
+
174
+ /** Представляет максимум сохранённых полных PGN в истории undo для режима правки. */
175
+ const MAX_PGN_EDIT_HISTORY = 20;
176
+
177
+ /** Представляет стек предыдущих состояний PGN и выбора ноды (до текущего). */
178
+ let pastPgnEntries = $state<TPgnHistoryEntry[]>([]);
179
+
180
+ /** Представляет стек отменённых состояний для redo. */
181
+ let redoPgnEntries = $state<TPgnHistoryEntry[]>([]);
182
+
183
+ /** Представляет путь варианта, соответствующий последнему зафиксированному `serializedPgn`. */
184
+ let variationPathSyncedWithPreviousSerializedPgn = $state<number[]>([]);
185
+
186
+ /** Представляет true, пока к дереву применяется PGN из истории (без добавления записи в стек). */
187
+ let suppressPgnHistoryPush = $state(false);
188
+
189
+ /** Представляет true, пока фокус в поле комментария (не пишем историю PGN на каждый символ). */
190
+ let commentTextareaHasFocus = $state(false);
191
+
192
+ /** Представляет снимок PGN и выбора до начала текущей сессии правки комментария (фиксируется при фокусе). */
193
+ let pendingCommentUndoEntry = $state<TPgnHistoryEntry | null>(null);
194
+
195
+ /** Представляет проверку: целевая нода лежит в поддереве предка (включая совпадение). */
196
+ function treeBranchContainsNode(
197
+ ancestor: ChessTreeNode,
198
+ target: ChessTreeNode,
199
+ ): boolean {
200
+ if (ancestor.id === target.id) return true;
201
+ return ancestor.children.some((c) => treeBranchContainsNode(c, target));
202
+ }
203
+
204
+ /** Представляет индексы детей от корня ходов до указанной ноды. */
205
+ function variationPathFromRootToNode(
206
+ rootMoves: ChessTreeNode,
207
+ target: ChessTreeNode,
208
+ ): number[] {
209
+ const path: number[] = [];
210
+ let node = rootMoves;
211
+ while (node.id !== target.id) {
212
+ const idx = node.children.findIndex((c) =>
213
+ treeBranchContainsNode(c, target),
214
+ );
215
+ if (idx === -1) break;
216
+ path.push(idx);
217
+ node = node.children[idx]!;
218
+ }
219
+ return path;
220
+ }
221
+
222
+ /** Представляет узел по пути варианта от корня ходов (устойчив к новым id после парсинга). */
223
+ function nodeAtVariationPathFromRoot(
224
+ rootMoves: ChessTreeNode,
225
+ variationPath: number[],
226
+ ): ChessTreeNode {
227
+ let node = rootMoves;
228
+ for (const idx of variationPath) {
229
+ const next = node.children[idx];
230
+ if (!next) break;
231
+ node = next;
232
+ }
233
+ return node;
234
+ }
235
+
236
+ /** Представляет актуальный путь варианта к текущей ноде в дереве. */
237
+ function variationPathForChessTreeSelection(tree: ChessTree): number[] {
238
+ return variationPathFromRootToNode(tree.rootNode.moves, tree.currentNode);
239
+ }
240
+
241
+ /** Представляет запись истории: текущий PGN и выбор ноды. */
242
+ function capturePgnHistoryEntry(tree: ChessTree): TPgnHistoryEntry {
243
+ return {
244
+ pgn: createPgnFromTree(tree.rootNode),
245
+ variationPath: variationPathForChessTreeSelection(tree),
246
+ };
247
+ }
248
+
249
+ const setIsDirty = (value: boolean) => {
250
+ isDirty = value;
251
+ };
252
+
253
+ $effect(() => {
254
+ if (!editMode) {
255
+ pastPgnEntries = [];
256
+ redoPgnEntries = [];
257
+ pendingCommentUndoEntry = null;
258
+ commentTextareaHasFocus = false;
259
+ }
260
+ });
261
+
262
+ /** Представляет одну запись undo для завершённой сессии правки комментария (до правки vs после). */
263
+ function flushPendingCommentUndoEntry(): void {
264
+ if (pendingCommentUndoEntry === null) return;
265
+ const pending = pendingCommentUndoEntry;
266
+ pendingCommentUndoEntry = null;
267
+ const nowPgn = createPgnFromTree(chessTree.rootNode);
268
+ if (pending.pgn === nowPgn) return;
269
+ const last = pastPgnEntries[pastPgnEntries.length - 1];
270
+ if (
271
+ last !== undefined &&
272
+ last.pgn === pending.pgn &&
273
+ JSON.stringify(last.variationPath) ===
274
+ JSON.stringify(pending.variationPath)
275
+ ) {
276
+ return;
277
+ }
278
+ pastPgnEntries = [...pastPgnEntries, pending].slice(-MAX_PGN_EDIT_HISTORY);
279
+ redoPgnEntries = [];
280
+ }
281
+
282
+ $effect(() => {
283
+ const next = serializedPgn;
284
+ const pathNow = variationPathForChessTreeSelection(chessTree);
285
+ const skipPushForInFlightCommentEdit =
286
+ editMode &&
287
+ commentTextareaHasFocus &&
288
+ pendingCommentUndoEntry !== null;
289
+ if (previousSerializedPgn === null) {
290
+ initialPgnSnapshot = next;
291
+ previousSerializedPgn = next;
292
+ variationPathSyncedWithPreviousSerializedPgn = pathNow;
293
+ isDirty = false;
294
+ return;
295
+ }
296
+ if (next !== previousSerializedPgn) {
297
+ if (
298
+ editMode &&
299
+ !suppressPgnHistoryPush &&
300
+ !skipPushForInFlightCommentEdit
301
+ ) {
302
+ pastPgnEntries = [
303
+ ...pastPgnEntries,
304
+ {
305
+ pgn: previousSerializedPgn,
306
+ variationPath: variationPathSyncedWithPreviousSerializedPgn,
307
+ },
308
+ ].slice(-MAX_PGN_EDIT_HISTORY);
309
+ redoPgnEntries = [];
310
+ }
311
+ previousSerializedPgn = next;
312
+ onChangeDirty?.(setIsDirty);
313
+ }
314
+ variationPathSyncedWithPreviousSerializedPgn = pathNow;
315
+ isDirty = next !== initialPgnSnapshot;
316
+ });
317
+
318
+ /** Представляет применение сохранённого PGN и восстановление активной ноды по пути варианта. */
319
+ function applyPgnHistoryEntry(entry: TPgnHistoryEntry): void {
320
+ pendingCommentUndoEntry = null;
321
+ commentTextareaHasFocus = false;
322
+ suppressPgnHistoryPush = true;
323
+ try {
324
+ const { rootNode } = transformPgnToChessNode(entry.pgn);
325
+ chessTree.replaceRootTree(rootNode);
326
+ chessTree.currentNode = nodeAtVariationPathFromRoot(
327
+ chessTree.rootNode.moves,
328
+ entry.variationPath,
329
+ );
330
+ onSelectNode();
331
+ onChessNodeSelected?.(chessTree.currentNode);
332
+ setTimeout(() => scrollToActiveMoveIfNeeded(), 50);
333
+ } finally {
334
+ setTimeout(() => {
335
+ suppressPgnHistoryPush = false;
336
+ }, 0);
337
+ }
338
+ }
339
+
340
+ /** Представляет откат к предыдущему сохранённому состоянию PGN и выбору ноды. */
341
+ function undoPgnEdit(): void {
342
+ if (pastPgnEntries.length === 0) return;
343
+ const prev = pastPgnEntries[pastPgnEntries.length - 1]!;
344
+ pastPgnEntries = pastPgnEntries.slice(0, -1);
345
+ redoPgnEntries = [
346
+ ...redoPgnEntries,
347
+ capturePgnHistoryEntry(chessTree),
348
+ ].slice(-MAX_PGN_EDIT_HISTORY);
349
+ applyPgnHistoryEntry(prev);
350
+ }
351
+
352
+ /** Представляет повтор последнего отменённого состояния PGN и выбор ноды. */
353
+ function redoPgnEdit(): void {
354
+ if (redoPgnEntries.length === 0) return;
355
+ const nextEntry = redoPgnEntries[redoPgnEntries.length - 1]!;
356
+ redoPgnEntries = redoPgnEntries.slice(0, -1);
357
+ pastPgnEntries = [
358
+ ...pastPgnEntries,
359
+ capturePgnHistoryEntry(chessTree),
360
+ ].slice(-MAX_PGN_EDIT_HISTORY);
361
+ applyPgnHistoryEntry(nextEntry);
362
+ }
363
+
364
+ /** Представляет доступность undo по истории PGN. */
365
+ const canUndoPgnEdit = $derived(editMode && pastPgnEntries.length > 0);
366
+
367
+ /** Представляет доступность redo по истории PGN. */
368
+ const canRedoPgnEdit = $derived(editMode && redoPgnEntries.length > 0);
369
+
370
+ /** Представляет глобальную обработку Ctrl/Cmd+Z и Shift+Ctrl/Cmd+Z для undo/redo PGN в режиме правки. */
371
+ function onTreeViewerWindowKeyDown(e: KeyboardEvent): void {
372
+ if (
373
+ editMode &&
374
+ (e.ctrlKey || e.metaKey) &&
375
+ !e.altKey &&
376
+ e.key.toLowerCase() === "z"
377
+ ) {
378
+ if (e.shiftKey) {
379
+ if (canRedoPgnEdit) {
380
+ e.preventDefault();
381
+ redoPgnEdit();
382
+ return;
383
+ }
384
+ } else if (canUndoPgnEdit) {
385
+ e.preventDefault();
386
+ undoPgnEdit();
387
+ return;
388
+ }
389
+ }
390
+ panelNav.onWindowKeyDown(e);
391
+ }
392
+
393
+ /** Представляет true, если выбран главный первый ход партии — комментарий партии до дерева ходов (`rootNode.comments`). */
394
+ const isAtMoveTreeRoot = $derived(
395
+ chessTree.currentNode.id === chessTree.rootNode.moves.id,
396
+ );
397
+
398
+ const drillForkCrumbs = $derived(chessTree.drillForkBreadcrumbs);
399
+ let isTreeViewerContainerOverflowing = $state(false);
400
+
401
+ /** Представляет черновой редактируемый текст первого PGN-комментария без блоков `[%…]` (часы, eval, стрелки и т.д.). */
402
+ let commentDraft = $state("");
403
+ /** Представляет id ноды, для которой загружен `commentDraft` (без затирания во время набора). */
404
+ let commentDraftSyncedNodeId = $state<string | null>(null);
405
+ $effect(() => {
406
+ if (!editMode) return;
407
+ const id = chessTree.currentNode.id;
408
+ if (
409
+ commentDraftSyncedNodeId !== null &&
410
+ commentDraftSyncedNodeId !== id
411
+ ) {
412
+ if (pendingCommentUndoEntry !== null) {
413
+ flushPendingCommentUndoEntry();
414
+ }
415
+ persistCommentDraftForNodeId(commentDraftSyncedNodeId);
416
+ }
417
+ if (commentDraftSyncedNodeId !== id) {
418
+ commentDraftSyncedNodeId = id;
419
+ const rawFirst =
420
+ id === chessTree.rootNode.moves.id
421
+ ? chessTree.rootNode.comments?.[0]
422
+ : chessTree.currentNode.data.comments?.[0];
423
+ commentDraft =
424
+ rawFirst !== undefined ? parseComment(rawFirst).text : "";
425
+ }
426
+ });
427
+
428
+ /** Представляет объединение строки из textarea с неизменной мета-разметкой первого сегмента (`[%clk]`, `[%eval]`, `[%csl]` …). */
429
+ function mergeEditableCommentWithPreservedMeta(
430
+ editableText: string,
431
+ rawFirstSegment: string | undefined,
432
+ ): string {
433
+ const base: Comment =
434
+ rawFirstSegment !== undefined
435
+ ? parseComment(rawFirstSegment)
436
+ : { text: "", shapes: [] };
437
+ return makeComment({ ...base, text: editableText });
438
+ }
439
+
440
+ /** Представляет нормализацию текста комментария для сравнения «набрано vs уже в дереве». */
441
+ function normalizeCommentTextForCompare(text: string): string {
442
+ return text.replace(/\r\n/g, "\n");
443
+ }
444
+
445
+ /** Представляет проверку совпадения массивов PGN-комментариев поэлементно (включая оба undefined). */
446
+ function commentStringArraysEqual(
447
+ nextComments: string[] | undefined,
448
+ currentComments: string[] | undefined,
449
+ ): boolean {
450
+ if (nextComments === undefined && currentComments === undefined) {
451
+ return true;
452
+ }
453
+ if (nextComments === undefined || currentComments === undefined) {
454
+ return false;
455
+ }
456
+ if (nextComments.length !== currentComments.length) return false;
457
+ for (let i = 0; i < nextComments.length; i++) {
458
+ if (nextComments[i] !== currentComments[i]) return false;
459
+ }
460
+ return true;
461
+ }
462
+
463
+ /** Представляет запись черновика в первый сегмент для узла с указанным id или вступления у корня партии. */
464
+ function persistCommentDraftForNodeId(targetNodeId: string): void {
465
+ if (!canEditAnnotations) return;
466
+ const isIntroComment =
467
+ targetNodeId === chessTree.rootNode.moves.id;
468
+
469
+ let tail: string[];
470
+ let rawFirst: string | undefined;
471
+ let targetMoveNode: ChessTreeNode | null = null;
472
+
473
+ if (isIntroComment) {
474
+ tail = chessTree.rootNode.comments?.slice(1) ?? [];
475
+ rawFirst = chessTree.rootNode.comments?.[0];
476
+ } else {
477
+ const node = chessTree.getNodeById(targetNodeId);
478
+ if (!node) return;
479
+ targetMoveNode = node;
480
+ tail = node.data.comments?.slice(1) ?? [];
481
+ rawFirst = node.data.comments?.[0];
482
+ }
483
+
484
+ const storedEditable =
485
+ rawFirst !== undefined ? parseComment(rawFirst).text : "";
486
+ if (
487
+ normalizeCommentTextForCompare(storedEditable) ===
488
+ normalizeCommentTextForCompare(commentDraft)
489
+ ) {
490
+ return;
491
+ }
492
+
493
+ const rebuiltFirst = mergeEditableCommentWithPreservedMeta(
494
+ commentDraft,
495
+ rawFirst,
496
+ );
497
+ const nextComments =
498
+ rebuiltFirst.trim() === ""
499
+ ? tail.length === 0
500
+ ? undefined
501
+ : tail
502
+ : [rebuiltFirst, ...tail];
503
+
504
+ if (isIntroComment) {
505
+ if (
506
+ commentStringArraysEqual(nextComments, chessTree.rootNode.comments)
507
+ ) {
508
+ return;
509
+ }
510
+ chessTree.rootNode.comments = nextComments;
511
+ return;
512
+ }
513
+
514
+ if (targetMoveNode === null) return;
515
+ if (commentStringArraysEqual(nextComments, targetMoveNode.data.comments)) {
516
+ return;
517
+ }
518
+ targetMoveNode.data.comments = nextComments;
519
+ }
520
+
521
+ /** Представляет запись черновика в первый сегмент `{...}` текущего узла или вступления партии у корня, сохраняя хвост и `[%…]` метаданные. */
522
+ function persistCommentDraftToCurrentNode(): void {
523
+ if (!canEditAnnotations) return;
524
+ persistCommentDraftForNodeId(chessTree.currentNode.id);
525
+ }
526
+
527
+ /** Представляет символы «оценки хода» с взаимоисключением (новинка `NOVELTY_NAG_ID` не входит). */
528
+ function isExclusiveMoveEvaluationGlyph(nag: number): boolean {
529
+ return isMoveEvaluationNag(nag) && nag !== NOVELTY_NAG_ID;
530
+ }
531
+
532
+ /** Представляет переключение NAG: для !/?/… — не более одного; новинка независима; для позиции — не более одного. */
533
+ function toggleNagAtCurrentNode(nagId: number): void {
534
+ if (!canEditAnnotations) return;
535
+ const node = chessTree.currentNode;
536
+ let next = [...(node.data.nags ?? [])];
537
+ const idx = next.indexOf(nagId);
538
+
539
+ if (nagId === NOVELTY_NAG_ID) {
540
+ if (idx !== -1) next.splice(idx, 1);
541
+ else next.push(nagId);
542
+ } else if (isExclusiveMoveEvaluationGlyph(nagId)) {
543
+ if (idx !== -1) next.splice(idx, 1);
544
+ else {
545
+ next = next.filter((n) => !isExclusiveMoveEvaluationGlyph(n));
546
+ next.push(nagId);
547
+ }
548
+ } else if (isPositionEvaluationNag(nagId)) {
549
+ if (idx !== -1) next.splice(idx, 1);
550
+ else {
551
+ next = next.filter((n) => !isPositionEvaluationNag(n));
552
+ next.push(nagId);
553
+ }
554
+ } else if (isPuzzleBranchNag(nagId)) {
555
+ if (idx !== -1) next.splice(idx, 1);
556
+ else {
557
+ next = next.filter((n) => !isPuzzleBranchNag(n));
558
+ next.push(nagId);
559
+ }
560
+ } else if (idx !== -1) next.splice(idx, 1);
561
+ else next.push(nagId);
562
+
563
+ node.data.nags = next.length > 0 ? next : undefined;
564
+ }
565
+
566
+ /** Представляет обновление признака вертикального переполнения дерева ходов. */
567
+ function updateTreeViewerContainerOverflow(element: HTMLDivElement): void {
568
+ isTreeViewerContainerOverflowing =
569
+ element.scrollHeight > element.clientHeight + 1;
570
+ }
571
+
572
+ /** Представляет последний узел главной линии от указанного узла. */
573
+ function getMainLineTailNode(node: ChessTreeNode): ChessTreeNode {
574
+ let currentNode = node;
575
+
576
+ while (currentNode.children[0]) {
577
+ currentNode = currentNode.children[0];
578
+ }
579
+
580
+ return currentNode;
581
+ }
582
+
583
+ const treeViewerOverflowAttachment: Attachment<HTMLDivElement> = (
584
+ element,
585
+ ) => {
586
+ const updateOverflow = () => updateTreeViewerContainerOverflow(element);
587
+ const contentElement = element.firstElementChild;
588
+
589
+ updateOverflow();
590
+
591
+ const resizeObserver = new ResizeObserver(updateOverflow);
592
+ const mutationObserver = new MutationObserver(updateOverflow);
593
+
594
+ resizeObserver.observe(element);
595
+ if (contentElement) {
596
+ resizeObserver.observe(contentElement);
597
+ }
598
+ mutationObserver.observe(element, {
599
+ childList: true,
600
+ characterData: true,
601
+ subtree: true,
602
+ });
603
+
604
+ return () => {
605
+ resizeObserver.disconnect();
606
+ mutationObserver.disconnect();
607
+ };
608
+ };
609
+
610
+ /**
611
+ * Представляет признак: развилка drill-down совпадает с развилкой для акцентных направляющих
612
+ * при текущем выборе; тогда в боковой панели рисуются акцентные линии.
613
+ */
614
+ const isDrillForkGuideForSelection = $derived(
615
+ chessTree.drillForkParent !== null &&
616
+ chessTree.drillForkParent.children.length > 1 &&
617
+ chessTree.currentGuideHighlightForkParent?.id ===
618
+ chessTree.drillForkParent.id,
619
+ );
620
+
621
+ /**
622
+ * Представляет true, когда последняя строка основного варианта заполнена двумя полуходами
623
+ * и ей нужна общая нижняя граница без риска нарисовать линию под пустой чёрной ячейкой.
624
+ */
625
+ const isFullMainLineTailRow = $derived.by(() => {
626
+ if (
627
+ chessTree.drillForkParent &&
628
+ chessTree.drillForkParent.children.length > 0
629
+ ) {
630
+ return false;
631
+ }
632
+
633
+ return getMainLineTailNode(chessTree.rootNode.moves).data.ply % 2 === 0;
634
+ });
635
+
636
+ /** Представляет выход на уровень выше по drill-down относительно активной крошки. */
637
+ function navigateToParentFromHeaderIndex(currentIndex: number): void {
638
+ const crumbs = drillForkCrumbs;
639
+ const currentCrumb = crumbs[currentIndex];
640
+ if (!currentCrumb) return;
641
+
642
+ const parent = chessTree.getNodeParent(currentCrumb);
643
+ if (!parent) return;
644
+
645
+ if (currentIndex <= 0) {
646
+ chessTree.exitDrillToFullTreeWithoutSelectingNode();
647
+ } else {
648
+ chessTree.navigateDrillBreadcrumb(currentIndex - 1);
649
+ }
650
+
651
+ chessTree.currentNode = parent;
652
+ onSelectNode();
653
+ onChessNodeSelected?.(chessTree.currentNode);
654
+ scrollToActiveMoveIfNeeded();
655
+ }
656
+
657
+ /** Представляет переход по «крошке» drill-down и синхронизацию доски. */
658
+ function navigateDrillCrumb(targetForkIndex: number): void {
659
+ chessTree.navigateDrillBreadcrumb(targetForkIndex);
660
+ onSelectNode();
661
+ onChessNodeSelected?.(chessTree.currentNode);
662
+ scrollToActiveMoveIfNeeded();
663
+ }
664
+
665
+ /** Представляет выход к полному дереву по домику без смены текущего узла и без синхронизации доски. */
666
+ function exitDrillViaHome(): void {
667
+ chessTree.exitDrillToFullTreeWithoutSelectingNode();
668
+ scrollToActiveMoveIfNeeded();
669
+ }
670
+
671
+ const ROOT_COMMENT_BLOCK_CLASS = "px-3 py-2 !bg-gray-50/95";
672
+ </script>
53
673
 
54
674
  <div
55
- id="tree-viewer-container"
56
675
  class={[
57
- "flex-1 relative overflow-auto border border-gray-300 rounded-l-sm shadow-sm ",
676
+ "relative flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden rounded-l-sm border-x border-t border-gray-300",
58
677
  className,
59
678
  ]}
60
- role="region"
61
- aria-label="Chess move tree"
62
- oncontextmenu={(e) => e.preventDefault()}
63
679
  >
64
680
  <div
681
+ id="tree-viewer-container"
65
682
  class={{
66
- "grid flex-1 grid-cols-[60px_1fr_1fr] divide-x divide-y divide-gray-300 select-none ": true,
683
+ "min-h-0 flex-1 overflow-x-hidden overflow-y-auto border-b border-gray-300": true,
684
+ "tree-viewer-container--overflowing": isTreeViewerContainerOverflowing,
67
685
  }}
686
+ role="region"
687
+ aria-label="Chess move tree"
688
+ oncontextmenu={(e) => e.preventDefault()}
689
+ {@attach treeViewerOverflowAttachment}
68
690
  >
69
- {#if chessTree.rootNode.comments}
70
- {#each chessTree.rootNode.comments as firstComment}
71
- {@render comment(firstComment)}
72
- {/each}
73
- {/if}
74
- <Move
75
- chessNode={chessTree.rootNode.moves}
76
- depth={1}
77
- needSpace={false}
78
- parentNode={null}
79
- {pieceSet}
80
- />
691
+ <div
692
+ class={{
693
+ "grid min-w-0 grid-cols-[60px_1fr_1fr] gap-px bg-gray-300 select-none [&>*]:min-w-0 [&>*]:bg-white": true,
694
+ "border-b border-gray-300":
695
+ !isTreeViewerContainerOverflowing && isFullMainLineTailRow,
696
+ "border-r border-gray-300": isTreeViewerContainerOverflowing,
697
+ }}
698
+ >
699
+ {#if chessTree.drillForkParent && chessTree.drillForkParent.children.length > 0}
700
+ <DrillBreadcrumbs
701
+ {chessTree}
702
+ {drillForkCrumbs}
703
+ {pieceSet}
704
+ onNavigateCrumb={navigateDrillCrumb}
705
+ onNavigateToParentFromCrumb={navigateToParentFromHeaderIndex}
706
+ onExitToFullTree={exitDrillViaHome}
707
+ />
708
+ <DrillVariationList
709
+ drillForkParent={chessTree.drillForkParent}
710
+ {pieceSet}
711
+ {isDrillForkGuideForSelection}
712
+ isBranchOnCurrentPath={(n) => chessTree.isCurrentOnPathFromNode(n)}
713
+ />
714
+ {:else}
715
+ {#if chessTree.rootNode.comments}
716
+ {#each chessTree.rootNode.comments as firstComment, commentIndex (`root-${commentIndex}`)}
717
+ <MoveComment
718
+ text={parseComment(firstComment).text}
719
+ isHighestLevel={true}
720
+ spaceBlockClass={ROOT_COMMENT_BLOCK_CLASS}
721
+ />
722
+ {/each}
723
+ {/if}
724
+ <Move
725
+ chessNode={chessTree.rootNode.moves}
726
+ depth={1}
727
+ shouldReserveEmptyMoveCell={false}
728
+ parentNode={null}
729
+ {pieceSet}
730
+ />
731
+ {/if}
732
+ </div>
81
733
  </div>
734
+ {#if editMode}
735
+ <div
736
+ class="flex shrink-0 flex-col gap-2 border-b border-gray-300 bg-gray-50/95 p-3"
737
+ >
738
+ <div
739
+ class="flex justify-center"
740
+ role="toolbar"
741
+ aria-label="Отмена и повтор правок PGN"
742
+ >
743
+ <div class="flex items-center gap-1">
744
+ <button
745
+ type="button"
746
+ disabled={!canUndoPgnEdit}
747
+ onclick={() => undoPgnEdit()}
748
+ title="Отменить"
749
+ class={{
750
+ "inline-flex size-8 shrink-0 items-center justify-center rounded-md border border-gray-300 bg-white text-gray-700 shadow-sm outline-none hover:bg-gray-50 focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-40":
751
+ true,
752
+ }}
753
+ aria-label="Отменить изменение PGN"
754
+ >
755
+ <Undo2Icon class="size-4" aria-hidden="true" />
756
+ </button>
757
+ <button
758
+ type="button"
759
+ disabled={!canRedoPgnEdit}
760
+ onclick={() => redoPgnEdit()}
761
+ title="Повторить"
762
+ class={{
763
+ "inline-flex size-8 shrink-0 items-center justify-center rounded-md border border-gray-300 bg-white text-gray-700 shadow-sm outline-none hover:bg-gray-50 focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-40":
764
+ true,
765
+ }}
766
+ aria-label="Повторить изменение PGN"
767
+ >
768
+ <Redo2Icon class="size-4" aria-hidden="true" />
769
+ </button>
770
+ </div>
771
+ </div>
772
+ <label class="flex flex-col gap-1">
773
+ <span class="sr-only">Комментарий к текущей ноде</span>
774
+ <textarea
775
+ class="min-h-[4.5rem] w-full resize-y rounded-md border border-gray-300 bg-white px-3 py-2 font-sans text-sm text-gray-900 shadow-sm outline-none placeholder:text-gray-400 focus-visible:ring-2 focus-visible:ring-gray-400 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:bg-gray-200 disabled:text-gray-500"
776
+ placeholder={isAtMoveTreeRoot
777
+ ? "Комментарий перед первым ходом"
778
+ : "Комментарий первого блока после хода"}
779
+ autocomplete="off"
780
+ disabled={!canEditAnnotations}
781
+ bind:value={commentDraft}
782
+ oninput={() => persistCommentDraftToCurrentNode()}
783
+ onfocusin={() => {
784
+ if (!canEditAnnotations) return;
785
+ commentTextareaHasFocus = true;
786
+ pendingCommentUndoEntry = capturePgnHistoryEntry(chessTree);
787
+ }}
788
+ onfocusout={() => {
789
+ commentTextareaHasFocus = false;
790
+ flushPendingCommentUndoEntry();
791
+ const syncId = commentDraftSyncedNodeId;
792
+ if (syncId !== null) {
793
+ persistCommentDraftForNodeId(syncId);
794
+ }
795
+ }}
796
+ onkeydown={(e) => {
797
+ if (
798
+ editMode &&
799
+ (e.ctrlKey || e.metaKey) &&
800
+ !e.altKey &&
801
+ e.key.toLowerCase() === "z"
802
+ ) {
803
+ return;
804
+ }
805
+ e.stopPropagation();
806
+ }}
807
+ ></textarea>
808
+ </label>
809
+ <div
810
+ class="relative flex flex-wrap gap-1.5 pb-0.5 pr-0.5"
811
+ role="group"
812
+ aria-label="Символы NAG"
813
+ >
814
+ {#each SELECTABLE_NAG_IDS_ORDERED as nagId (nagId)}
815
+ {@const label = transformNagId(nagId)}
816
+ {@const nagOnNode =
817
+ chessTree.currentNode.data.nags?.includes(nagId) ?? false}
818
+ {@const shadedActive = canEditAnnotations && nagOnNode}
819
+ {#if label}
820
+ <button
821
+ type="button"
822
+ disabled={!canEditAnnotations}
823
+ title={nagDescription(nagId)}
824
+ class={{
825
+ "inline-flex min-h-[1.5rem] min-w-[1.5rem] shrink-0 items-center justify-center rounded-full border px-2 py-0.5 text-center font-serif text-[0.625rem] font-semibold leading-none text-white shadow-[0_1px_2px_rgba(0,0,0,0.25)]": true,
826
+ "cursor-pointer": canEditAnnotations,
827
+ "cursor-not-allowed border-gray-300 bg-gray-300 text-gray-600 shadow-none":
828
+ !canEditAnnotations,
829
+ "border-white/25": canEditAnnotations,
830
+ }}
831
+ style:background={canEditAnnotations
832
+ ? shadedActive
833
+ ? nagBadgeBackground(nagId)
834
+ : "rgb(243 244 246)"
835
+ : undefined}
836
+ style:color={canEditAnnotations && !shadedActive
837
+ ? "#374151"
838
+ : undefined}
839
+ aria-pressed={nagOnNode}
840
+ onclick={() => toggleNagAtCurrentNode(nagId)}
841
+ >
842
+ {label}
843
+ </button>
844
+ {/if}
845
+ {/each}
846
+ {#if canEditAnnotations}
847
+ <span
848
+ class={{
849
+ "pointer-events-none absolute bottom-0 right-0 size-2 rounded-full shadow-sm ring-1": true,
850
+ "bg-red-600 ring-red-900/25": isDirty,
851
+ "bg-green-600 ring-green-900/25": !isDirty,
852
+ }}
853
+ aria-label={isDirty
854
+ ? "Несохранённые изменения PGN"
855
+ : "Изменения сохранены"}
856
+ title={isDirty
857
+ ? "Дерево партии изменено"
858
+ : "Несохранённых изменений нет"}
859
+ ></span>
860
+ {/if}
861
+ </div>
862
+ </div>
863
+ {/if}
82
864
  </div>
865
+
866
+ <VariantDropdownNavigator
867
+ bind:this={variantDropdownNavigator}
868
+ variants={chessTree.currentNode?.children ?? []}
869
+ anchorSelector={`.${ACTIVE_MOVE_CLASS}`}
870
+ onActivateVariant={(node) => {
871
+ panelNav.selectChildNode(node);
872
+ panelNav.highlightButton("next");
873
+ }}
874
+ />
875
+
876
+ <svelte:window onkeydown={onTreeViewerWindowKeyDown} />
877
+
878
+ <style>
879
+ .tree-viewer-container--overflowing
880
+ :global(.tree-viewer-overflow-tail-border) {
881
+ border-bottom-width: 0;
882
+ }
883
+ </style>