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