@astronox/core 0.1.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 (259) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +66 -0
  3. package/package.json +77 -0
  4. package/src/client/clipboard.ts +7 -0
  5. package/src/client/focus.ts +17 -0
  6. package/src/client/index.ts +3 -0
  7. package/src/client/scroll.ts +15 -0
  8. package/src/components/actions/ActionListItem/ActionListItem.astro +78 -0
  9. package/src/components/actions/ActionListItem/ActionListItem.css +43 -0
  10. package/src/components/actions/Button/Button.astro +100 -0
  11. package/src/components/actions/Button/Button.css +165 -0
  12. package/src/components/actions/CardAction/CardAction.astro +97 -0
  13. package/src/components/actions/CardAction/CardAction.css +188 -0
  14. package/src/components/actions/MediaTrigger/MediaTrigger.astro +55 -0
  15. package/src/components/actions/MediaTrigger/MediaTrigger.css +175 -0
  16. package/src/components/actions/ScrollToTop/ScrollToTop.astro +36 -0
  17. package/src/components/actions/ScrollToTop/ScrollToTop.css +19 -0
  18. package/src/components/actions/ScrollToTop/scrollToTopController.ts +32 -0
  19. package/src/components/content/CardBody/CardBody.astro +31 -0
  20. package/src/components/content/CardBody/CardBody.css +74 -0
  21. package/src/components/content/CardFooter/CardFooter.astro +58 -0
  22. package/src/components/content/CardFooter/CardFooter.css +102 -0
  23. package/src/components/content/CardHeader/CardHeader.astro +96 -0
  24. package/src/components/content/CardHeader/CardHeader.css +164 -0
  25. package/src/components/content/CardLink/CardLink.astro +138 -0
  26. package/src/components/content/CardLink/CardLink.css +362 -0
  27. package/src/components/content/CodeBlock/CodeBlock.astro +102 -0
  28. package/src/components/content/CodeBlock/CodeBlock.css +85 -0
  29. package/src/components/content/CodeBlock/codeBlockController.ts +60 -0
  30. package/src/components/content/CodeBlock/contracts.ts +8 -0
  31. package/src/components/content/InlineDefinition/InlineDefinition.astro +31 -0
  32. package/src/components/content/InlineDefinition/InlineDefinition.css +9 -0
  33. package/src/components/content/MarkdownContent/MarkdownContent.astro +32 -0
  34. package/src/components/content/MarkdownContent/MarkdownContent.css +358 -0
  35. package/src/components/content/MarkdownContent/MarkdownInline.astro +44 -0
  36. package/src/components/content/MarkdownContent/MarkdownNode.astro +280 -0
  37. package/src/components/content/MarkdownContent/MarkdownSymbol.astro +47 -0
  38. package/src/components/content/MarkdownContent/contracts.ts +181 -0
  39. package/src/components/data-display/BadgeList/BadgeList.astro +54 -0
  40. package/src/components/data-display/BadgeList/BadgeList.css +29 -0
  41. package/src/components/data-display/IconList/IconList.astro +64 -0
  42. package/src/components/data-display/IconList/IconList.css +55 -0
  43. package/src/components/data-display/MetricTile/MetricTile.astro +68 -0
  44. package/src/components/data-display/MetricTile/MetricTile.css +103 -0
  45. package/src/components/data-display/MetricTile/MetricTileContent.astro +70 -0
  46. package/src/components/data-display/MetricTile/metricTileController.ts +9 -0
  47. package/src/components/data-display/Tag/Tag.astro +67 -0
  48. package/src/components/data-display/Tag/Tag.css +134 -0
  49. package/src/components/data-display/Tag/TagAffix.astro +33 -0
  50. package/src/components/data-display/TextPair/TextPair.astro +63 -0
  51. package/src/components/data-display/TextPair/TextPair.css +99 -0
  52. package/src/components/feedback/Spinner/Spinner.astro +32 -0
  53. package/src/components/feedback/Spinner/Spinner.css +37 -0
  54. package/src/components/feedback/Tooltip/Tooltip.astro +66 -0
  55. package/src/components/feedback/Tooltip/Tooltip.css +67 -0
  56. package/src/components/feedback/Tooltip/tooltipController.ts +371 -0
  57. package/src/components/forms/FieldError/FieldError.astro +31 -0
  58. package/src/components/forms/FieldError/FieldError.css +12 -0
  59. package/src/components/forms/FieldError/fieldErrorState.ts +21 -0
  60. package/src/components/forms/FieldLabel/FieldLabel.astro +32 -0
  61. package/src/components/forms/FieldLabel/FieldLabel.css +17 -0
  62. package/src/components/forms/TextInput/TextInput.astro +79 -0
  63. package/src/components/forms/TextInput/TextInput.css +121 -0
  64. package/src/components/forms/TextInput/textInputController.ts +53 -0
  65. package/src/components/icons/ArrowDownIcon.astro +26 -0
  66. package/src/components/icons/ArrowLeftIcon.astro +26 -0
  67. package/src/components/icons/ArrowRightIcon.astro +26 -0
  68. package/src/components/icons/ArrowUpDownIcon.astro +26 -0
  69. package/src/components/icons/ArrowUpIcon.astro +26 -0
  70. package/src/components/icons/BulletIcon.astro +21 -0
  71. package/src/components/icons/BurnIcon.astro +24 -0
  72. package/src/components/icons/CircleSymbolIcon.css +66 -0
  73. package/src/components/icons/ClearIcon.astro +28 -0
  74. package/src/components/icons/CloseIcon.astro +21 -0
  75. package/src/components/icons/CopyIcon.astro +30 -0
  76. package/src/components/icons/CurrencyIcon.css +9 -0
  77. package/src/components/icons/DayIcon.astro +33 -0
  78. package/src/components/icons/DollarIcon.astro +28 -0
  79. package/src/components/icons/DownloadIcon.astro +22 -0
  80. package/src/components/icons/EnterFullscreenIcon.astro +22 -0
  81. package/src/components/icons/EqualIcon.astro +25 -0
  82. package/src/components/icons/ExitFullscreenIcon.astro +22 -0
  83. package/src/components/icons/ExternalLinkIcon.astro +22 -0
  84. package/src/components/icons/FieldIcon.astro +28 -0
  85. package/src/components/icons/GrassIcon.astro +29 -0
  86. package/src/components/icons/InfoIcon.astro +24 -0
  87. package/src/components/icons/MinusIcon.astro +21 -0
  88. package/src/components/icons/MountainIcon.astro +31 -0
  89. package/src/components/icons/NightIcon.astro +32 -0
  90. package/src/components/icons/PlayIcon.astro +22 -0
  91. package/src/components/icons/PlusIcon.astro +21 -0
  92. package/src/components/icons/PoisonIcon.astro +24 -0
  93. package/src/components/icons/RibbonIcon.astro +25 -0
  94. package/src/components/icons/SlashIcon.astro +22 -0
  95. package/src/components/icons/SlowIcon.astro +25 -0
  96. package/src/components/icons/StarIcon.astro +28 -0
  97. package/src/components/icons/StunIcon.astro +22 -0
  98. package/src/components/icons/TableSortIcon.astro +34 -0
  99. package/src/components/icons/WaterIcon.astro +30 -0
  100. package/src/components/index.ts +83 -0
  101. package/src/components/media/CanvasFrame/CanvasFrame.astro +130 -0
  102. package/src/components/media/CanvasFrame/CanvasFrame.css +59 -0
  103. package/src/components/media/CanvasFrame/canvasFrameController.ts +104 -0
  104. package/src/components/media/EmbedFrame/EmbedFrame.astro +147 -0
  105. package/src/components/media/EmbedFrame/EmbedFrame.css +51 -0
  106. package/src/components/media/EmbedFrame/embedFrameController.ts +66 -0
  107. package/src/components/media/MediaFrame/MediaFrame.astro +34 -0
  108. package/src/components/media/MediaFrame/MediaFrame.css +66 -0
  109. package/src/components/navigation/Breadcrumbs/Breadcrumbs.astro +55 -0
  110. package/src/components/navigation/Breadcrumbs/Breadcrumbs.css +89 -0
  111. package/src/components/navigation/DesktopNavigation.astro +92 -0
  112. package/src/components/navigation/DesktopNavigation.css +99 -0
  113. package/src/components/navigation/Header.astro +73 -0
  114. package/src/components/navigation/Header.css +20 -0
  115. package/src/components/navigation/MobileNavigation.astro +124 -0
  116. package/src/components/navigation/MobileNavigation.css +177 -0
  117. package/src/components/navigation/NavigationBrand.astro +63 -0
  118. package/src/components/navigation/NavigationBrand.css +52 -0
  119. package/src/components/navigation/NavigationControl.css +166 -0
  120. package/src/components/navigation/NavigationItemContent.astro +24 -0
  121. package/src/components/navigation/NavigationLink.astro +121 -0
  122. package/src/components/navigation/NavigationLinks.astro +27 -0
  123. package/src/components/navigation/NavigationMenuList.astro +37 -0
  124. package/src/components/navigation/NavigationMenuList.css +6 -0
  125. package/src/components/navigation/SkipLink/SkipLink.astro +18 -0
  126. package/src/components/navigation/SkipLink/SkipLink.css +26 -0
  127. package/src/components/navigation/SubNavigation/SubNavigation.astro +124 -0
  128. package/src/components/navigation/SubNavigation/SubNavigation.css +211 -0
  129. package/src/components/navigation/mobileNavigationController.ts +122 -0
  130. package/src/components/navigation/navigationState.ts +35 -0
  131. package/src/components/navigation/navigationTypes.ts +18 -0
  132. package/src/components/seo/SeoHead.astro +194 -0
  133. package/src/components/widgetTypes.ts +3 -0
  134. package/src/composition/Grid/Grid.astro +82 -0
  135. package/src/composition/Grid/Grid.css +314 -0
  136. package/src/composition/GridItem/GridItem.astro +50 -0
  137. package/src/composition/GridItem/GridItem.css +95 -0
  138. package/src/composition/Inline/Inline.astro +48 -0
  139. package/src/composition/Inline/Inline.css +65 -0
  140. package/src/composition/Stack/Stack.astro +37 -0
  141. package/src/composition/Stack/Stack.css +31 -0
  142. package/src/composition/SurfaceGroup/SurfaceGroup.astro +44 -0
  143. package/src/composition/SurfaceGroup/SurfaceGroup.css +76 -0
  144. package/src/composition/SurfaceGroup/stickySurfaceGroupController.ts +89 -0
  145. package/src/composition/index.ts +6 -0
  146. package/src/config/index.ts +2 -0
  147. package/src/config/pageMeta.ts +55 -0
  148. package/src/config/siteConfig.ts +90 -0
  149. package/src/data/collectionValidation.ts +61 -0
  150. package/src/data/index.ts +1 -0
  151. package/src/display/contracts.ts +284 -0
  152. package/src/display/index.ts +1 -0
  153. package/src/index.ts +6 -0
  154. package/src/layouts/BaseLayout.astro +74 -0
  155. package/src/layouts/PageSurface.astro +15 -0
  156. package/src/layouts/PageSurface.css +24 -0
  157. package/src/layouts/index.ts +2 -0
  158. package/src/patterns/CircuitPuzzle/CircuitPuzzle.astro +93 -0
  159. package/src/patterns/CircuitPuzzle/CircuitPuzzle.css +118 -0
  160. package/src/patterns/CircuitPuzzle/circuitPuzzleController.ts +205 -0
  161. package/src/patterns/CircuitPuzzle/contracts.ts +42 -0
  162. package/src/patterns/Combobox/Combobox.astro +462 -0
  163. package/src/patterns/Combobox/Combobox.css +403 -0
  164. package/src/patterns/Combobox/comboboxController.ts +788 -0
  165. package/src/patterns/Combobox/contracts.ts +18 -0
  166. package/src/patterns/Dropdown/Dropdown.astro +127 -0
  167. package/src/patterns/Dropdown/Dropdown.css +100 -0
  168. package/src/patterns/Dropdown/dropdownController.ts +157 -0
  169. package/src/patterns/Fullscreen/FullscreenControl.astro +103 -0
  170. package/src/patterns/Fullscreen/FullscreenControl.css +49 -0
  171. package/src/patterns/Fullscreen/fullscreenController.ts +73 -0
  172. package/src/patterns/GlitchOverlay/GlitchOverlay.astro +50 -0
  173. package/src/patterns/GlitchOverlay/GlitchOverlay.css +234 -0
  174. package/src/patterns/GlitchOverlay/glitchOverlayController.ts +152 -0
  175. package/src/patterns/GuidedFlow/GuidedFlow.astro +60 -0
  176. package/src/patterns/GuidedFlow/GuidedFlow.css +82 -0
  177. package/src/patterns/GuidedFlow/contracts.ts +3 -0
  178. package/src/patterns/GuidedFlow/guidedFlowController.ts +49 -0
  179. package/src/patterns/MagneticFieldPuzzle/MagneticFieldPuzzle.astro +217 -0
  180. package/src/patterns/MagneticFieldPuzzle/MagneticFieldPuzzle.css +383 -0
  181. package/src/patterns/MagneticFieldPuzzle/contracts.ts +81 -0
  182. package/src/patterns/MagneticFieldPuzzle/magneticFieldPuzzleController.ts +802 -0
  183. package/src/patterns/MagneticFieldPuzzle/simulation.ts +244 -0
  184. package/src/patterns/MapViewport/MapViewport.astro +296 -0
  185. package/src/patterns/MapViewport/MapViewport.css +257 -0
  186. package/src/patterns/MapViewport/contracts.ts +79 -0
  187. package/src/patterns/MapViewport/geometry.ts +80 -0
  188. package/src/patterns/MapViewport/mapViewportController.ts +636 -0
  189. package/src/patterns/Modal/Modal.astro +64 -0
  190. package/src/patterns/Modal/Modal.css +87 -0
  191. package/src/patterns/Modal/ModalClose.astro +37 -0
  192. package/src/patterns/Modal/ModalOpen.astro +36 -0
  193. package/src/patterns/Modal/modalController.ts +118 -0
  194. package/src/patterns/PuzzleGrid/PuzzleGrid.astro +22 -0
  195. package/src/patterns/PuzzleGrid/PuzzleGrid.css +149 -0
  196. package/src/patterns/PuzzleGrid/contracts.ts +2 -0
  197. package/src/patterns/PuzzleGrid/selectionDismissal.ts +27 -0
  198. package/src/patterns/PuzzleGrid/state.ts +25 -0
  199. package/src/patterns/SpriteProjectilePreview/SpriteProjectilePreview.astro +65 -0
  200. package/src/patterns/SpriteProjectilePreview/SpriteProjectilePreview.css +35 -0
  201. package/src/patterns/SpriteProjectilePreview/contracts.ts +33 -0
  202. package/src/patterns/SpriteProjectilePreview/spriteProjectilePreviewController.ts +586 -0
  203. package/src/patterns/StageFlow/StageFlow.astro +57 -0
  204. package/src/patterns/StageFlow/StageFlow.css +54 -0
  205. package/src/patterns/StageFlow/StageFlowAlternative.astro +23 -0
  206. package/src/patterns/StageFlow/StageFlowArrow.astro +22 -0
  207. package/src/patterns/StageFlow/StageFlowConnector.astro +7 -0
  208. package/src/patterns/StageFlow/StageFlowConnector.css +4 -0
  209. package/src/patterns/StageFlow/StageFlowStage.astro +51 -0
  210. package/src/patterns/StageFlow/StageFlowStage.css +106 -0
  211. package/src/patterns/StageFlow/StageFlowStep.astro +24 -0
  212. package/src/patterns/StageFlow/StageFlowStep.css +19 -0
  213. package/src/patterns/StageFlow/StageFlowSymbol.css +28 -0
  214. package/src/patterns/Table/Table.astro +176 -0
  215. package/src/patterns/Table/Table.css +70 -0
  216. package/src/patterns/Table/TableBody.astro +185 -0
  217. package/src/patterns/Table/TableBody.css +262 -0
  218. package/src/patterns/Table/TableCell.astro +59 -0
  219. package/src/patterns/Table/TableCell.css +99 -0
  220. package/src/patterns/Table/TableCellValue.astro +86 -0
  221. package/src/patterns/Table/TableFooter.astro +32 -0
  222. package/src/patterns/Table/TableFooter.css +31 -0
  223. package/src/patterns/Table/TableHeader.astro +118 -0
  224. package/src/patterns/Table/TableHeader.css +209 -0
  225. package/src/patterns/Table/TablePagination.astro +70 -0
  226. package/src/patterns/Table/TablePagination.css +133 -0
  227. package/src/patterns/Table/TableSkeleton.astro +36 -0
  228. package/src/patterns/Table/TableSkeleton.css +81 -0
  229. package/src/patterns/Table/tableCellController.ts +11 -0
  230. package/src/patterns/Table/tableFilterController.ts +206 -0
  231. package/src/patterns/Table/tableHeaderOverflowController.ts +105 -0
  232. package/src/patterns/Table/tableLayout.ts +113 -0
  233. package/src/patterns/Table/tableProgressiveController.ts +319 -0
  234. package/src/patterns/Table/tableRowNavigationController.ts +91 -0
  235. package/src/patterns/Table/tableScrollController.ts +192 -0
  236. package/src/patterns/Table/tableSortController.ts +272 -0
  237. package/src/patterns/index.ts +46 -0
  238. package/src/primitives/index.ts +4 -0
  239. package/src/primitives/layout/Separator/Separator.astro +29 -0
  240. package/src/primitives/layout/Separator/Separator.css +20 -0
  241. package/src/primitives/media/AmbientAudio/AmbientAudio.astro +28 -0
  242. package/src/primitives/media/Media/Media.astro +122 -0
  243. package/src/primitives/media/Media/Media.css +161 -0
  244. package/src/primitives/text/TextBlock/TextBlock.astro +46 -0
  245. package/src/primitives/text/TextBlock/TextBlock.css +21 -0
  246. package/src/seo/StaticRedirect.astro +32 -0
  247. package/src/seo/index.ts +6 -0
  248. package/src/seo/pageSeo.ts +99 -0
  249. package/src/seo/robots.ts +16 -0
  250. package/src/seo/sitemap.ts +38 -0
  251. package/src/seo/structuredData.ts +133 -0
  252. package/src/seo/url.ts +64 -0
  253. package/src/styles/base.css +148 -0
  254. package/src/styles/interaction.css +108 -0
  255. package/src/styles/style.css +93 -0
  256. package/src/styles/tokens.css +256 -0
  257. package/src/theme/contracts.ts +7 -0
  258. package/src/theme/index.ts +1 -0
  259. package/tsconfig.json +20 -0
@@ -0,0 +1,802 @@
1
+ import {
2
+ setPuzzleGridCellState,
3
+ setPuzzleGridState,
4
+ } from '../PuzzleGrid/state';
5
+ import { initPuzzleSelectionDismissal } from '../PuzzleGrid/selectionDismissal';
6
+ import type {
7
+ MagneticFieldDirection,
8
+ MagneticFieldMovement,
9
+ MagneticFieldPolarity,
10
+ MagneticFieldPupilPosition,
11
+ MagneticFieldPuzzleChangeDetail,
12
+ MagneticFieldPuzzleModel,
13
+ MagneticFieldPuzzleState,
14
+ MagneticFieldPuzzleStatus,
15
+ } from './contracts';
16
+ import {
17
+ createMagneticFieldInitialState,
18
+ getMagneticFieldMoves,
19
+ isMagneticFieldPuzzleComplete,
20
+ simulateMagneticFieldMove,
21
+ } from './simulation';
22
+
23
+ type MagneticFieldDrag = {
24
+ pointerId: number;
25
+ pieceId: string;
26
+ startX: number;
27
+ startY: number;
28
+ currentX: number;
29
+ currentY: number;
30
+ frameId: number | null;
31
+ element: HTMLButtonElement;
32
+ originCellBounds: DOMRect;
33
+ originCenterX: number;
34
+ originCenterY: number;
35
+ destinations: readonly HTMLButtonElement[] | null;
36
+ moved: boolean;
37
+ };
38
+
39
+ type MagneticFieldInstance = {
40
+ activeIndex: number;
41
+ selectedPieceId: string | null;
42
+ drag: MagneticFieldDrag | null;
43
+ ignoreNextClick: boolean;
44
+ };
45
+
46
+ const dragThreshold = 12;
47
+ const pathChevronsPerCell = 3;
48
+ const pathDurationPerCellMs = 2100;
49
+ const instances = new WeakMap<HTMLElement, MagneticFieldInstance>();
50
+
51
+ export function initMagneticFieldPuzzle(root: HTMLElement): void {
52
+ if (instances.has(root)) return;
53
+ instances.set(root, {
54
+ activeIndex: 0,
55
+ selectedPieceId: null,
56
+ drag: null,
57
+ ignoreNextClick: false,
58
+ });
59
+ initPuzzleSelectionDismissal(root, {
60
+ dismiss: () => selectPiece(root, null),
61
+ isSelectionTarget: (target) => {
62
+ const panel = getActivePanel(root);
63
+ if (!panel || panel.dataset.puzzleStatus === 'valid') return false;
64
+
65
+ const piece = target.closest<HTMLElement>('[data-field-piece]');
66
+ if (piece && panel.contains(piece)) return true;
67
+
68
+ const destination = target.closest<HTMLButtonElement>(
69
+ '[data-field-destination]',
70
+ );
71
+ return Boolean(
72
+ destination && panel.contains(destination) && !destination.disabled,
73
+ );
74
+ },
75
+ });
76
+
77
+ root.addEventListener('click', (event) => {
78
+ const target = event.target;
79
+ const instance = instances.get(root);
80
+ if (!(target instanceof Element) || !instance) return;
81
+
82
+ const piece = target.closest<HTMLButtonElement>('[data-field-piece]');
83
+ if (piece) {
84
+ if (instance.ignoreNextClick) {
85
+ instance.ignoreNextClick = false;
86
+ return;
87
+ }
88
+ togglePieceSelection(root, piece.dataset.fieldPiece ?? null);
89
+ return;
90
+ }
91
+
92
+ const destination = target.closest<HTMLButtonElement>(
93
+ '[data-field-destination]',
94
+ );
95
+ if (destination && !destination.disabled) {
96
+ const pieceId = destination.dataset.destinationPiece;
97
+ const direction = destination.dataset.destinationDirection as
98
+ MagneticFieldDirection | undefined;
99
+ if (pieceId && direction) movePiece(root, pieceId, direction);
100
+ return;
101
+ }
102
+
103
+ if (target.closest('[data-field-board]')) selectPiece(root, null);
104
+ });
105
+
106
+ root.addEventListener('pointerdown', (event) => {
107
+ if (!event.isPrimary || event.button !== 0) return;
108
+ const target = event.target;
109
+ if (!(target instanceof Element)) return;
110
+ const piece = target.closest<HTMLButtonElement>('[data-field-piece]');
111
+ const instance = instances.get(root);
112
+ const pieceId = piece?.dataset.fieldPiece;
113
+ if (!piece || !pieceId || !instance) return;
114
+ const panel = getActivePanel(root);
115
+ const originCell = panel
116
+ ? findCell(panel, {
117
+ row: Number(piece.dataset.pieceRow),
118
+ column: Number(piece.dataset.pieceColumn),
119
+ })
120
+ : null;
121
+ if (!originCell) return;
122
+ const pieceBounds = piece.getBoundingClientRect();
123
+
124
+ piece.setPointerCapture(event.pointerId);
125
+ instance.drag = {
126
+ pointerId: event.pointerId,
127
+ pieceId,
128
+ startX: event.clientX,
129
+ startY: event.clientY,
130
+ currentX: event.clientX,
131
+ currentY: event.clientY,
132
+ frameId: null,
133
+ element: piece,
134
+ originCellBounds: originCell.getBoundingClientRect(),
135
+ originCenterX: (pieceBounds.left + pieceBounds.right) / 2,
136
+ originCenterY: (pieceBounds.top + pieceBounds.bottom) / 2,
137
+ destinations: null,
138
+ moved: false,
139
+ };
140
+ });
141
+
142
+ root.addEventListener('pointermove', (event) => {
143
+ const drag = instances.get(root)?.drag;
144
+ if (!drag || drag.pointerId !== event.pointerId) return;
145
+ const deltaX = event.clientX - drag.startX;
146
+ const deltaY = event.clientY - drag.startY;
147
+ if (!drag.moved) {
148
+ drag.moved = Math.hypot(deltaX, deltaY) >= dragThreshold;
149
+ if (!drag.moved) return;
150
+ drag.element.setAttribute('data-piece-dragging', '');
151
+ selectPiece(root, drag.pieceId);
152
+ }
153
+
154
+ event.preventDefault();
155
+ drag.destinations ??= getDropDestinations(root);
156
+ drag.currentX = event.clientX;
157
+ drag.currentY = event.clientY;
158
+ scheduleDragFrame(root, drag);
159
+ });
160
+
161
+ root.addEventListener('pointerup', (event) => {
162
+ finishDrag(root, event, true);
163
+ });
164
+ root.addEventListener('pointercancel', (event) => {
165
+ finishDrag(root, event, false);
166
+ });
167
+
168
+ root.addEventListener('keydown', (event) => {
169
+ if (event.altKey || event.ctrlKey || event.metaKey) return;
170
+ const direction = arrowDirections[event.key.toLowerCase()];
171
+ if (!direction) {
172
+ if (event.key === 'Escape') selectPiece(root, null);
173
+ return;
174
+ }
175
+
176
+ const piece = (event.target as Element | null)?.closest<HTMLElement>(
177
+ '[data-field-piece]',
178
+ );
179
+ const pieceId =
180
+ piece?.dataset.fieldPiece ??
181
+ instances.get(root)?.selectedPieceId ??
182
+ undefined;
183
+ if (!pieceId) return;
184
+ event.preventDefault();
185
+ movePiece(root, pieceId, direction);
186
+ });
187
+ }
188
+
189
+ export function selectMagneticFieldPuzzle(
190
+ root: HTMLElement,
191
+ index: number,
192
+ ): void {
193
+ initMagneticFieldPuzzle(root);
194
+ const panels = getPanels(root);
195
+ const selectedIndex = Math.max(0, Math.min(index, panels.length - 1));
196
+ const instance = instances.get(root);
197
+ if (instance) instance.activeIndex = selectedIndex;
198
+
199
+ panels.forEach((panel, panelIndex) => {
200
+ panel.hidden = panelIndex !== selectedIndex;
201
+ });
202
+ initializeActivePuzzle(root);
203
+ }
204
+
205
+ export function setMagneticFieldPuzzleStatus(
206
+ root: HTMLElement,
207
+ puzzleId: string,
208
+ status: MagneticFieldPuzzleStatus,
209
+ ): void {
210
+ const panel = getPanels(root).find(
211
+ (candidate) => candidate.dataset.puzzleId === puzzleId,
212
+ );
213
+ if (!panel) return;
214
+
215
+ const previous = panel.dataset.puzzleStatus;
216
+ if (status === 'valid') {
217
+ const instance = instances.get(root);
218
+ if (instance && panel === getActivePanel(root)) {
219
+ instance.selectedPieceId = null;
220
+ }
221
+ for (const piece of panel.querySelectorAll<HTMLElement>(
222
+ '[data-field-piece]',
223
+ )) {
224
+ piece.removeAttribute('data-piece-selected');
225
+ piece.setAttribute('aria-pressed', 'false');
226
+ }
227
+ hideMovePreviews(panel);
228
+ }
229
+ panel.dataset.puzzleStatus = status;
230
+ const grid = panel.querySelector<HTMLElement>('[data-puzzle-grid]');
231
+ if (grid) setPuzzleGridState(grid, status === 'valid' ? 'valid' : null);
232
+
233
+ if (status === 'valid' && previous !== 'valid') {
234
+ root.dispatchEvent(
235
+ new CustomEvent('puzzle:complete', {
236
+ bubbles: true,
237
+ detail: {
238
+ kind: 'magnetic-field',
239
+ puzzleId,
240
+ },
241
+ }),
242
+ );
243
+ }
244
+ }
245
+
246
+ export function resetMagneticFieldPuzzle(root: HTMLElement): void {
247
+ initMagneticFieldPuzzle(root);
248
+ initializeActivePuzzle(root);
249
+ }
250
+
251
+ function selectPiece(root: HTMLElement, pieceId: string | null): void {
252
+ const panel = getActivePanel(root);
253
+ const instance = instances.get(root);
254
+ if (!panel || !instance || panel.dataset.puzzleStatus === 'valid') return;
255
+ if (instance.selectedPieceId === pieceId) return;
256
+
257
+ instance.selectedPieceId = pieceId;
258
+ syncPieceSelection(panel, pieceId);
259
+ updateDestinations(root);
260
+ }
261
+
262
+ function togglePieceSelection(root: HTMLElement, pieceId: string | null): void {
263
+ const instance = instances.get(root);
264
+ if (!instance || !pieceId) {
265
+ selectPiece(root, null);
266
+ return;
267
+ }
268
+
269
+ selectPiece(root, instance.selectedPieceId === pieceId ? null : pieceId);
270
+ }
271
+
272
+ function syncPieceSelection(panel: HTMLElement, pieceId: string | null): void {
273
+ for (const piece of panel.querySelectorAll<HTMLElement>(
274
+ '[data-field-piece]',
275
+ )) {
276
+ const selected = piece.dataset.fieldPiece === pieceId;
277
+ piece.toggleAttribute('data-piece-selected', selected);
278
+ piece.setAttribute('aria-pressed', String(selected));
279
+ }
280
+ }
281
+
282
+ function updateDestinations(root: HTMLElement): void {
283
+ const panel = getActivePanel(root);
284
+ const instance = instances.get(root);
285
+ if (!panel || !instance) return;
286
+ hideMovePreviews(panel);
287
+ const pieceId = instance.selectedPieceId;
288
+ if (!pieceId) return;
289
+
290
+ const puzzle = readPuzzle(panel);
291
+ const state = readState(panel, puzzle);
292
+ const labels = panel.querySelector<HTMLElement>('[data-move-template]');
293
+ const piece = puzzle.pieces.find((candidate) => candidate.id === pieceId);
294
+ if (!piece) return;
295
+
296
+ for (const movement of getMagneticFieldMoves(puzzle, state, pieceId)) {
297
+ const directionLabel = readDirectionLabel(labels, movement.direction);
298
+ renderPathStream(panel, movement);
299
+
300
+ const destination = findCell(panel, movement.to);
301
+ if (!destination) continue;
302
+ destination.removeAttribute('tabindex');
303
+ destination.setAttribute('data-field-destination', '');
304
+ destination.setAttribute('data-puzzle-cell-interactive', '');
305
+ destination.dataset.destinationPiece = pieceId;
306
+ destination.dataset.destinationDirection = movement.direction;
307
+ destination.setAttribute(
308
+ 'aria-label',
309
+ formatTemplate(labels?.dataset.moveTemplate ?? '', {
310
+ piece: piece.label,
311
+ direction: directionLabel,
312
+ }),
313
+ );
314
+ }
315
+ }
316
+
317
+ function movePiece(
318
+ root: HTMLElement,
319
+ pieceId: string,
320
+ direction: MagneticFieldDirection,
321
+ retainSelection = true,
322
+ ): void {
323
+ const panel = getActivePanel(root);
324
+ if (!panel || panel.dataset.puzzleStatus === 'valid') return;
325
+ const puzzle = readPuzzle(panel);
326
+ const current = readState(panel, puzzle);
327
+ const simulation = simulateMagneticFieldMove(puzzle, current, {
328
+ pieceId,
329
+ direction,
330
+ });
331
+ if (!simulation.movement) return;
332
+
333
+ const movingElement = panel.querySelector<HTMLButtonElement>(
334
+ `[data-field-piece="${CSS.escape(pieceId)}"]`,
335
+ );
336
+ const initialBounds = movingElement?.getBoundingClientRect();
337
+ renderState(panel, puzzle, simulation.state);
338
+ if (movingElement && initialBounds) {
339
+ animatePieceMovement(movingElement, initialBounds);
340
+ }
341
+ const complete = isMagneticFieldPuzzleComplete(puzzle, simulation.state);
342
+ const selectedPieceId = retainSelection && !complete ? pieceId : null;
343
+ const instance = instances.get(root);
344
+ if (instance) instance.selectedPieceId = selectedPieceId;
345
+ syncPieceSelection(panel, selectedPieceId);
346
+ if (selectedPieceId) {
347
+ updateDestinations(root);
348
+ } else {
349
+ hideMovePreviews(panel);
350
+ }
351
+ emitChange(root, puzzle.id, simulation.state);
352
+ }
353
+
354
+ function initializeActivePuzzle(root: HTMLElement): void {
355
+ const panel = getActivePanel(root);
356
+ const instance = instances.get(root);
357
+ if (!panel || !instance) return;
358
+ const puzzle = readPuzzle(panel);
359
+ const initial = createMagneticFieldInitialState(puzzle);
360
+
361
+ instance.selectedPieceId = null;
362
+ instance.drag = null;
363
+ instance.ignoreNextClick = false;
364
+ panel.dataset.puzzleStatus = 'incomplete';
365
+ const grid = panel.querySelector<HTMLElement>('[data-puzzle-grid]');
366
+ if (grid) setPuzzleGridState(grid, null);
367
+ renderState(panel, puzzle, initial);
368
+ hideMovePreviews(panel);
369
+ emitChange(root, puzzle.id, initial);
370
+ }
371
+
372
+ function renderState(
373
+ panel: HTMLElement,
374
+ puzzle: MagneticFieldPuzzleModel,
375
+ state: MagneticFieldPuzzleState,
376
+ ): void {
377
+ for (const target of panel.querySelectorAll<HTMLElement>(
378
+ '[data-field-target-cell]',
379
+ )) {
380
+ const targetState = target.dataset.puzzleCellState;
381
+ if (targetState === 'valid' || targetState === 'invalid') {
382
+ setPuzzleGridCellState(target, null);
383
+ }
384
+ }
385
+
386
+ for (const target of puzzle.targets) {
387
+ const targetElement = panel.querySelector<HTMLElement>(
388
+ `[data-field-target-cell="${CSS.escape(target.id)}"]`,
389
+ );
390
+ const occupant = puzzle.pieces.find((piece) => {
391
+ const position = state[piece.id];
392
+ return position?.row === target.row && position.column === target.column;
393
+ });
394
+ if (!targetElement || !occupant) continue;
395
+
396
+ const occupantState = state[occupant.id];
397
+ const valid =
398
+ occupant.id === target.pieceId &&
399
+ occupantState?.polarity === target.polarity;
400
+ setPuzzleGridCellState(targetElement, valid ? 'valid' : 'invalid');
401
+ }
402
+
403
+ for (const piece of puzzle.pieces) {
404
+ const current = state[piece.id];
405
+ const element = panel.querySelector<HTMLButtonElement>(
406
+ `[data-field-piece="${CSS.escape(piece.id)}"]`,
407
+ );
408
+ if (!current || !element) continue;
409
+
410
+ element.getAnimations().forEach((animation) => animation.cancel());
411
+ element.dataset.pieceRow = String(current.row);
412
+ element.dataset.pieceColumn = String(current.column);
413
+ element.dataset.piecePolarity = current.polarity;
414
+ element.style.setProperty('--piece-row', String(current.row + 1));
415
+ element.style.setProperty('--piece-column', String(current.column + 1));
416
+ const occupiedTarget = puzzle.targets.find(
417
+ (target) =>
418
+ target.row === current.row && target.column === current.column,
419
+ );
420
+ const pieceState = occupiedTarget
421
+ ? isPiecePlaced(puzzle, piece.id, current)
422
+ ? 'valid'
423
+ : 'invalid'
424
+ : null;
425
+ if (pieceState) {
426
+ element.dataset.pieceState = pieceState;
427
+ } else {
428
+ delete element.dataset.pieceState;
429
+ }
430
+ if (pieceState === 'invalid') {
431
+ element.setAttribute('aria-invalid', 'true');
432
+ } else {
433
+ element.removeAttribute('aria-invalid');
434
+ }
435
+
436
+ const polarityIdentity = element.querySelector<HTMLElement>(
437
+ '[data-piece-polarity-identity]',
438
+ );
439
+ if (polarityIdentity) {
440
+ polarityIdentity.dataset.polarity = current.polarity;
441
+ }
442
+ const polarityLabel =
443
+ current.polarity === 'north'
444
+ ? element.dataset.polarityLabelNorth
445
+ : element.dataset.polarityLabelSouth;
446
+ element.setAttribute(
447
+ 'aria-label',
448
+ `${piece.label} — ${polarityLabel ?? current.polarity}`,
449
+ );
450
+
451
+ element.removeAttribute('data-piece-moved');
452
+ }
453
+ }
454
+
455
+ function animatePieceMovement(
456
+ element: HTMLButtonElement,
457
+ initialBounds: DOMRect,
458
+ ): void {
459
+ const finalBounds = element.getBoundingClientRect();
460
+ element.style.setProperty(
461
+ '--piece-move-inline-distance',
462
+ `${initialBounds.left - finalBounds.left}px`,
463
+ );
464
+ element.style.setProperty(
465
+ '--piece-move-block-distance',
466
+ `${initialBounds.top - finalBounds.top}px`,
467
+ );
468
+ element.setAttribute('data-piece-moved', '');
469
+ }
470
+
471
+ function finishDrag(
472
+ root: HTMLElement,
473
+ event: PointerEvent,
474
+ commit: boolean,
475
+ ): void {
476
+ const instance = instances.get(root);
477
+ const drag = instance?.drag;
478
+ if (!instance || !drag || drag.pointerId !== event.pointerId) return;
479
+ const deltaX = event.clientX - drag.startX;
480
+ const deltaY = event.clientY - drag.startY;
481
+ const destination =
482
+ commit && drag.moved && hasLeftOriginCell(drag, deltaX, deltaY)
483
+ ? findDirectionalDropDestination(drag, deltaX, deltaY)
484
+ : null;
485
+
486
+ cancelDragFrame(drag);
487
+ drag.element.removeAttribute('data-piece-dragging');
488
+ drag.element.style.removeProperty('--piece-drag-x');
489
+ drag.element.style.removeProperty('--piece-drag-y');
490
+ if (drag.element.hasPointerCapture(event.pointerId)) {
491
+ drag.element.releasePointerCapture(event.pointerId);
492
+ }
493
+ instance.drag = null;
494
+
495
+ if (commit && drag.moved) {
496
+ instance.ignoreNextClick = true;
497
+ window.setTimeout(() => {
498
+ const current = instances.get(root);
499
+ if (current === instance) current.ignoreNextClick = false;
500
+ }, 0);
501
+ const destinationPiece = destination?.dataset.destinationPiece;
502
+ const direction = destination?.dataset.destinationDirection as
503
+ MagneticFieldDirection | undefined;
504
+ if (destinationPiece === drag.pieceId && direction) {
505
+ movePiece(root, drag.pieceId, direction, false);
506
+ }
507
+ }
508
+ if (drag.moved) selectPiece(root, null);
509
+ }
510
+
511
+ function hasLeftOriginCell(
512
+ drag: MagneticFieldDrag,
513
+ deltaX: number,
514
+ deltaY: number,
515
+ ): boolean {
516
+ const centerX = drag.originCenterX + deltaX;
517
+ const centerY = drag.originCenterY + deltaY;
518
+ const { bottom, left, right, top } = drag.originCellBounds;
519
+
520
+ return centerX < left || centerX > right || centerY < top || centerY > bottom;
521
+ }
522
+
523
+ function scheduleDragFrame(root: HTMLElement, drag: MagneticFieldDrag): void {
524
+ if (drag.frameId !== null) return;
525
+ drag.frameId = window.requestAnimationFrame(() => {
526
+ drag.frameId = null;
527
+ if (instances.get(root)?.drag !== drag) return;
528
+
529
+ drag.element.style.setProperty(
530
+ '--piece-drag-x',
531
+ `${drag.currentX - drag.startX}px`,
532
+ );
533
+ drag.element.style.setProperty(
534
+ '--piece-drag-y',
535
+ `${drag.currentY - drag.startY}px`,
536
+ );
537
+ });
538
+ }
539
+
540
+ function cancelDragFrame(drag: MagneticFieldDrag): void {
541
+ if (drag.frameId === null) return;
542
+ window.cancelAnimationFrame(drag.frameId);
543
+ drag.frameId = null;
544
+ }
545
+
546
+ function getDropDestinations(root: HTMLElement): HTMLButtonElement[] {
547
+ const panel = getActivePanel(root);
548
+ if (!panel) return [];
549
+
550
+ return [
551
+ ...panel.querySelectorAll<HTMLButtonElement>('[data-field-destination]'),
552
+ ];
553
+ }
554
+
555
+ function findDirectionalDropDestination(
556
+ drag: MagneticFieldDrag,
557
+ deltaX: number,
558
+ deltaY: number,
559
+ ): HTMLButtonElement | null {
560
+ let direction: MagneticFieldDirection;
561
+ if (Math.abs(deltaX) >= Math.abs(deltaY)) {
562
+ direction = deltaX >= 0 ? 'east' : 'west';
563
+ } else {
564
+ direction = deltaY >= 0 ? 'south' : 'north';
565
+ }
566
+
567
+ return (
568
+ (drag.destinations ?? []).find(
569
+ (destination) =>
570
+ destination.dataset.destinationDirection === direction &&
571
+ destination.dataset.destinationPiece === drag.pieceId,
572
+ ) ?? null
573
+ );
574
+ }
575
+
576
+ function hideMovePreviews(panel: HTMLElement): void {
577
+ for (const stream of panel.querySelectorAll<HTMLElement>(
578
+ '[data-field-path-stream]',
579
+ )) {
580
+ stream.remove();
581
+ }
582
+
583
+ for (const destination of panel.querySelectorAll<HTMLButtonElement>(
584
+ '[data-field-destination]',
585
+ )) {
586
+ destination.tabIndex = -1;
587
+ destination.removeAttribute('data-field-destination');
588
+ destination.removeAttribute('data-puzzle-cell-interactive');
589
+ destination.removeAttribute('data-destination-piece');
590
+ destination.removeAttribute('data-destination-direction');
591
+ const cellLabel = destination.dataset.cellLabel;
592
+ if (cellLabel) {
593
+ destination.setAttribute('aria-label', cellLabel);
594
+ } else {
595
+ destination.removeAttribute('aria-label');
596
+ }
597
+ }
598
+ }
599
+
600
+ function renderPathStream(
601
+ panel: HTMLElement,
602
+ movement: MagneticFieldMovement,
603
+ ): void {
604
+ const board = panel.querySelector<HTMLElement>('[data-field-board]');
605
+ if (!board) return;
606
+
607
+ const rowDistance = movement.to.row - movement.from.row;
608
+ const columnDistance = movement.to.column - movement.from.column;
609
+ const cellDistance = Math.abs(rowDistance) + Math.abs(columnDistance);
610
+ const chevronCount = pathChevronsPerCell * cellDistance;
611
+ const stream = document.createElement('span');
612
+ stream.className = 'magnetic-field-puzzle__path-stream';
613
+ stream.dataset.fieldPathStream = '';
614
+ stream.dataset.fieldPathDirection = movement.direction;
615
+ stream.setAttribute('aria-hidden', 'true');
616
+ stream.style.setProperty('--field-path-row', String(movement.from.row + 1));
617
+ stream.style.setProperty(
618
+ '--field-path-column',
619
+ String(movement.from.column + 1),
620
+ );
621
+ stream.style.setProperty(
622
+ '--field-path-target-inline',
623
+ `${50 + columnDistance * 100}%`,
624
+ );
625
+ stream.style.setProperty(
626
+ '--field-path-target-block',
627
+ `${50 + rowDistance * 100}%`,
628
+ );
629
+ stream.style.setProperty(
630
+ '--field-path-duration',
631
+ `${pathDurationPerCellMs * cellDistance}ms`,
632
+ );
633
+
634
+ for (let index = 0; index < chevronCount; index += 1) {
635
+ const progress = (index + 0.5) / chevronCount;
636
+ const chevron = document.createElement('span');
637
+ chevron.className = 'magnetic-field-puzzle__path-chevron';
638
+ chevron.style.setProperty('--field-path-chevron-index', String(index));
639
+ chevron.style.setProperty(
640
+ '--field-path-static-inline',
641
+ `${50 + columnDistance * progress * 100}%`,
642
+ );
643
+ chevron.style.setProperty(
644
+ '--field-path-static-block',
645
+ `${50 + rowDistance * progress * 100}%`,
646
+ );
647
+ stream.append(chevron);
648
+ }
649
+
650
+ board.append(stream);
651
+ }
652
+
653
+ function findCell(
654
+ panel: HTMLElement,
655
+ position: { row: number; column: number },
656
+ ): HTMLButtonElement | null {
657
+ return panel.querySelector<HTMLButtonElement>(
658
+ `[data-field-cell][data-cell-row="${position.row}"][data-cell-column="${position.column}"]`,
659
+ );
660
+ }
661
+
662
+ function readPuzzle(panel: HTMLElement): MagneticFieldPuzzleModel {
663
+ const board = panel.querySelector<HTMLElement>('[data-field-board]');
664
+ const pieces = [...panel.querySelectorAll<HTMLElement>('[data-field-piece]')];
665
+ return {
666
+ id: panel.dataset.puzzleId ?? '',
667
+ label: board?.getAttribute('aria-label') ?? '',
668
+ rows: Number(board?.dataset.fieldRows),
669
+ columns: Number(board?.dataset.fieldColumns),
670
+ pieces: pieces.map((piece) => ({
671
+ id: piece.dataset.fieldPiece ?? '',
672
+ label: piece.dataset.pieceLabel ?? '',
673
+ shortLabel: piece.dataset.pieceShortLabel ?? '',
674
+ row: Number(piece.dataset.initialRow),
675
+ column: Number(piece.dataset.initialColumn),
676
+ polarity: piece.dataset.initialPolarity as MagneticFieldPolarity,
677
+ pupilPosition: piece.dataset
678
+ .piecePupilPosition as MagneticFieldPupilPosition,
679
+ })),
680
+ targets: [
681
+ ...panel.querySelectorAll<HTMLElement>('[data-field-target]'),
682
+ ].map((target) => ({
683
+ id: target.dataset.fieldTarget ?? '',
684
+ label: target.dataset.targetLabel ?? '',
685
+ pieceId: target.dataset.targetPiece ?? '',
686
+ row: Number(target.dataset.targetRow),
687
+ column: Number(target.dataset.targetColumn),
688
+ polarity: target.dataset.targetPolarity as MagneticFieldPolarity,
689
+ })),
690
+ blockedCells: [
691
+ ...panel.querySelectorAll<HTMLElement>('[data-field-blocked-cell]'),
692
+ ].map((cell) => ({
693
+ id: cell.dataset.fieldBlockedCell ?? '',
694
+ label: cell.getAttribute('aria-label') ?? '',
695
+ row: Number(cell.dataset.cellRow),
696
+ column: Number(cell.dataset.cellColumn),
697
+ })),
698
+ inverters: [
699
+ ...panel.querySelectorAll<HTMLElement>('[data-field-inverter]'),
700
+ ].map((inverter) => ({
701
+ id: inverter.dataset.fieldInverter ?? '',
702
+ label: inverter.dataset.inverterLabel ?? '',
703
+ row: Number(inverter.dataset.inverterRow),
704
+ column: Number(inverter.dataset.inverterColumn),
705
+ })),
706
+ };
707
+ }
708
+
709
+ function readState(
710
+ panel: HTMLElement,
711
+ puzzle: MagneticFieldPuzzleModel,
712
+ ): MagneticFieldPuzzleState {
713
+ return Object.fromEntries(
714
+ puzzle.pieces.map((piece) => {
715
+ const element = panel.querySelector<HTMLElement>(
716
+ `[data-field-piece="${CSS.escape(piece.id)}"]`,
717
+ );
718
+ return [
719
+ piece.id,
720
+ {
721
+ row: Number(element?.dataset.pieceRow),
722
+ column: Number(element?.dataset.pieceColumn),
723
+ polarity: element?.dataset.piecePolarity as MagneticFieldPolarity,
724
+ },
725
+ ];
726
+ }),
727
+ );
728
+ }
729
+
730
+ function isPiecePlaced(
731
+ puzzle: MagneticFieldPuzzleModel,
732
+ pieceId: string,
733
+ state: MagneticFieldPuzzleState[string],
734
+ ): boolean {
735
+ const target = puzzle.targets.find(
736
+ (candidate) => candidate.pieceId === pieceId,
737
+ );
738
+ return (
739
+ target !== undefined &&
740
+ target.row === state.row &&
741
+ target.column === state.column &&
742
+ target.polarity === state.polarity
743
+ );
744
+ }
745
+
746
+ function emitChange(
747
+ root: HTMLElement,
748
+ puzzleId: string,
749
+ state: MagneticFieldPuzzleState,
750
+ ): void {
751
+ const detail: MagneticFieldPuzzleChangeDetail = {
752
+ kind: 'magnetic-field',
753
+ puzzleId,
754
+ state,
755
+ };
756
+ root.dispatchEvent(
757
+ new CustomEvent<MagneticFieldPuzzleChangeDetail>('puzzle:change', {
758
+ bubbles: true,
759
+ detail,
760
+ }),
761
+ );
762
+ }
763
+
764
+ function getPanels(root: HTMLElement): HTMLElement[] {
765
+ return [...root.querySelectorAll<HTMLElement>(':scope > [data-puzzle-id]')];
766
+ }
767
+
768
+ function getActivePanel(root: HTMLElement): HTMLElement | undefined {
769
+ const index = instances.get(root)?.activeIndex ?? 0;
770
+ return getPanels(root)[index];
771
+ }
772
+
773
+ function readDirectionLabel(
774
+ element: HTMLElement | null,
775
+ direction: MagneticFieldDirection,
776
+ ): string {
777
+ const key = `directionLabel${capitalize(direction)}` as keyof DOMStringMap;
778
+ return element?.dataset[key] ?? direction;
779
+ }
780
+
781
+ function formatTemplate(
782
+ template: string,
783
+ values: Readonly<Record<string, string>>,
784
+ ): string {
785
+ return Object.entries(values).reduce(
786
+ (result, [key, value]) => result.replaceAll(`{${key}}`, value),
787
+ template,
788
+ );
789
+ }
790
+
791
+ function capitalize(value: string): string {
792
+ return `${value.charAt(0).toUpperCase()}${value.slice(1)}`;
793
+ }
794
+
795
+ const arrowDirections: Readonly<
796
+ Partial<Record<string, MagneticFieldDirection>>
797
+ > = {
798
+ arrowup: 'north',
799
+ arrowright: 'east',
800
+ arrowdown: 'south',
801
+ arrowleft: 'west',
802
+ };