@pretty-chitty/core 1.2.18 → 2.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 (378) hide show
  1. package/README.md +8 -0
  2. package/dist/components/ActionLogDisplay.d.ts.map +1 -1
  3. package/dist/components/ActionLogDisplay.js +1 -1
  4. package/dist/components/ActionLogDisplay.js.map +1 -1
  5. package/dist/components/BottomBarButton.d.ts +3 -1
  6. package/dist/components/BottomBarButton.d.ts.map +1 -1
  7. package/dist/components/BottomBarButton.js +3 -2
  8. package/dist/components/BottomBarButton.js.map +1 -1
  9. package/dist/components/ClientTrustMatchViewer.d.ts +14 -1
  10. package/dist/components/ClientTrustMatchViewer.d.ts.map +1 -1
  11. package/dist/components/ClientTrustMatchViewer.js +25 -2
  12. package/dist/components/ClientTrustMatchViewer.js.map +1 -1
  13. package/dist/components/ContextGalleryDisplay.d.ts.map +1 -1
  14. package/dist/components/ContextGalleryDisplay.js +1 -1
  15. package/dist/components/ContextGalleryDisplay.js.map +1 -1
  16. package/dist/components/DemoWrapper.d.ts +30 -2
  17. package/dist/components/DemoWrapper.d.ts.map +1 -1
  18. package/dist/components/DemoWrapper.js +79 -43
  19. package/dist/components/DemoWrapper.js.map +1 -1
  20. package/dist/components/FullScreenGalleryDisplay.d.ts.map +1 -1
  21. package/dist/components/FullScreenGalleryDisplay.js +2 -2
  22. package/dist/components/FullScreenGalleryDisplay.js.map +1 -1
  23. package/dist/components/Gallery/BuiltItem.d.ts +6 -2
  24. package/dist/components/Gallery/BuiltItem.d.ts.map +1 -1
  25. package/dist/components/Gallery/BuiltItem.js +31 -9
  26. package/dist/components/Gallery/BuiltItem.js.map +1 -1
  27. package/dist/components/Gallery/GalleryController.d.ts +18 -0
  28. package/dist/components/Gallery/GalleryController.d.ts.map +1 -1
  29. package/dist/components/Gallery/GalleryController.js +70 -1
  30. package/dist/components/Gallery/GalleryController.js.map +1 -1
  31. package/dist/components/Gallery/GalleryViewer.d.ts +6 -1
  32. package/dist/components/Gallery/GalleryViewer.d.ts.map +1 -1
  33. package/dist/components/Gallery/GalleryViewer.js +48 -10
  34. package/dist/components/Gallery/GalleryViewer.js.map +1 -1
  35. package/dist/components/Gallery/LayoutManager.d.ts +6 -0
  36. package/dist/components/Gallery/LayoutManager.d.ts.map +1 -1
  37. package/dist/components/Gallery/LayoutManager.js +23 -3
  38. package/dist/components/Gallery/LayoutManager.js.map +1 -1
  39. package/dist/components/Gallery/constants.d.ts +2 -0
  40. package/dist/components/Gallery/constants.d.ts.map +1 -1
  41. package/dist/components/Gallery/constants.js +2 -0
  42. package/dist/components/Gallery/constants.js.map +1 -1
  43. package/dist/components/Gallery/registry.d.ts +34 -0
  44. package/dist/components/Gallery/registry.d.ts.map +1 -0
  45. package/dist/components/Gallery/registry.js +17 -0
  46. package/dist/components/Gallery/registry.js.map +1 -0
  47. package/dist/components/GameDesigner.d.ts.map +1 -1
  48. package/dist/components/GameDesigner.js +42 -10
  49. package/dist/components/GameDesigner.js.map +1 -1
  50. package/dist/components/InlineGalleryDisplay.d.ts.map +1 -1
  51. package/dist/components/InlineGalleryDisplay.js +2 -2
  52. package/dist/components/InlineGalleryDisplay.js.map +1 -1
  53. package/dist/components/LiveButton.d.ts.map +1 -1
  54. package/dist/components/LiveButton.js +5 -2
  55. package/dist/components/LiveButton.js.map +1 -1
  56. package/dist/components/MatchViewer.d.ts +6 -1
  57. package/dist/components/MatchViewer.d.ts.map +1 -1
  58. package/dist/components/MatchViewer.js +9 -3
  59. package/dist/components/MatchViewer.js.map +1 -1
  60. package/dist/components/Panel/MultiPanel.d.ts.map +1 -1
  61. package/dist/components/Panel/MultiPanel.js +18 -0
  62. package/dist/components/Panel/MultiPanel.js.map +1 -1
  63. package/dist/components/Panel/PanelContents.d.ts.map +1 -1
  64. package/dist/components/Panel/PanelContents.js +92 -23
  65. package/dist/components/Panel/PanelContents.js.map +1 -1
  66. package/dist/components/Panel/PanelTabStack.d.ts.map +1 -1
  67. package/dist/components/Panel/PanelTabStack.js +1 -1
  68. package/dist/components/Panel/PanelTabStack.js.map +1 -1
  69. package/dist/components/PanelSpark.d.ts.map +1 -1
  70. package/dist/components/PanelSpark.js +3 -2
  71. package/dist/components/PanelSpark.js.map +1 -1
  72. package/dist/components/Playground.d.ts.map +1 -1
  73. package/dist/components/Playground.js +46 -14
  74. package/dist/components/Playground.js.map +1 -1
  75. package/dist/components/PromptControls.d.ts.map +1 -1
  76. package/dist/components/PromptControls.js +4 -2
  77. package/dist/components/PromptControls.js.map +1 -1
  78. package/dist/components/SparkLineChart.d.ts.map +1 -1
  79. package/dist/components/SparkLineChart.js +22 -26
  80. package/dist/components/SparkLineChart.js.map +1 -1
  81. package/dist/components/TimeControlBar.d.ts.map +1 -1
  82. package/dist/components/TimeControlBar.js +5 -3
  83. package/dist/components/TimeControlBar.js.map +1 -1
  84. package/dist/components/TokenizedMarkdown.d.ts +23 -0
  85. package/dist/components/TokenizedMarkdown.d.ts.map +1 -0
  86. package/dist/components/TokenizedMarkdown.js +144 -0
  87. package/dist/components/TokenizedMarkdown.js.map +1 -0
  88. package/dist/components/TokenizedMessage.d.ts +8 -6
  89. package/dist/components/TokenizedMessage.d.ts.map +1 -1
  90. package/dist/components/TokenizedMessage.js +21 -54
  91. package/dist/components/TokenizedMessage.js.map +1 -1
  92. package/dist/components/TopBarPlayers.d.ts.map +1 -1
  93. package/dist/components/TopBarPlayers.js +2 -2
  94. package/dist/components/TopBarPlayers.js.map +1 -1
  95. package/dist/components/Tutorial/BrowserNarration.d.ts +55 -0
  96. package/dist/components/Tutorial/BrowserNarration.d.ts.map +1 -0
  97. package/dist/components/Tutorial/BrowserNarration.js +240 -0
  98. package/dist/components/Tutorial/BrowserNarration.js.map +1 -0
  99. package/dist/components/Tutorial/TutorialBox.d.ts +26 -0
  100. package/dist/components/Tutorial/TutorialBox.d.ts.map +1 -0
  101. package/dist/components/Tutorial/TutorialBox.js +239 -0
  102. package/dist/components/Tutorial/TutorialBox.js.map +1 -0
  103. package/dist/components/Tutorial/TutorialDevPanel.d.ts +9 -0
  104. package/dist/components/Tutorial/TutorialDevPanel.d.ts.map +1 -0
  105. package/dist/components/Tutorial/TutorialDevPanel.js +92 -0
  106. package/dist/components/Tutorial/TutorialDevPanel.js.map +1 -0
  107. package/dist/components/Tutorial/TutorialOverlay.d.ts +7 -0
  108. package/dist/components/Tutorial/TutorialOverlay.d.ts.map +1 -0
  109. package/dist/components/Tutorial/TutorialOverlay.js +1132 -0
  110. package/dist/components/Tutorial/TutorialOverlay.js.map +1 -0
  111. package/dist/components/Tutorial/targetRects.d.ts +67 -0
  112. package/dist/components/Tutorial/targetRects.d.ts.map +1 -0
  113. package/dist/components/Tutorial/targetRects.js +241 -0
  114. package/dist/components/Tutorial/targetRects.js.map +1 -0
  115. package/dist/game/Chit.d.ts +7 -0
  116. package/dist/game/Chit.d.ts.map +1 -1
  117. package/dist/game/Chit.js +22 -7
  118. package/dist/game/Chit.js.map +1 -1
  119. package/dist/game/ClientTimeState.d.ts +14 -0
  120. package/dist/game/ClientTimeState.d.ts.map +1 -1
  121. package/dist/game/ClientTimeState.js +17 -0
  122. package/dist/game/ClientTimeState.js.map +1 -1
  123. package/dist/game/ConnectionTransport.d.ts +3 -0
  124. package/dist/game/ConnectionTransport.d.ts.map +1 -1
  125. package/dist/game/ConnectionTransport.js +13 -4
  126. package/dist/game/ConnectionTransport.js.map +1 -1
  127. package/dist/game/Game.d.ts +14 -1
  128. package/dist/game/Game.d.ts.map +1 -1
  129. package/dist/game/GameTheme.d.ts +3 -0
  130. package/dist/game/GameTheme.d.ts.map +1 -1
  131. package/dist/game/GameTheme.js +2 -0
  132. package/dist/game/GameTheme.js.map +1 -1
  133. package/dist/game/Match.d.ts +74 -2
  134. package/dist/game/Match.d.ts.map +1 -1
  135. package/dist/game/Match.js +155 -4
  136. package/dist/game/Match.js.map +1 -1
  137. package/dist/game/MatchStorage.d.ts +8 -1
  138. package/dist/game/MatchStorage.d.ts.map +1 -1
  139. package/dist/game/MatchStorage.js +11 -3
  140. package/dist/game/MatchStorage.js.map +1 -1
  141. package/dist/game/Pick.d.ts +16 -0
  142. package/dist/game/Pick.d.ts.map +1 -1
  143. package/dist/game/Pick.js +32 -1
  144. package/dist/game/Pick.js.map +1 -1
  145. package/dist/game/PlayerChit.d.ts +3 -0
  146. package/dist/game/PlayerChit.d.ts.map +1 -1
  147. package/dist/game/PlayerChit.js +3 -0
  148. package/dist/game/PlayerChit.js.map +1 -1
  149. package/dist/game/PlayerInfo.d.ts +8 -0
  150. package/dist/game/PlayerInfo.d.ts.map +1 -1
  151. package/dist/game/PlayerInfo.js +6 -3
  152. package/dist/game/PlayerInfo.js.map +1 -1
  153. package/dist/game/PlayerPromptStatusChit.d.ts +8 -0
  154. package/dist/game/PlayerPromptStatusChit.d.ts.map +1 -1
  155. package/dist/game/PlayerPromptStatusChit.js +8 -2
  156. package/dist/game/PlayerPromptStatusChit.js.map +1 -1
  157. package/dist/game/Prompt.d.ts +15 -0
  158. package/dist/game/Prompt.d.ts.map +1 -1
  159. package/dist/game/Prompt.js +16 -0
  160. package/dist/game/Prompt.js.map +1 -1
  161. package/dist/game/Turn.d.ts +20 -4
  162. package/dist/game/Turn.d.ts.map +1 -1
  163. package/dist/game/Turn.js +191 -67
  164. package/dist/game/Turn.js.map +1 -1
  165. package/dist/game/TurnState.d.ts +20 -1
  166. package/dist/game/TurnState.d.ts.map +1 -1
  167. package/dist/game/TurnState.js +22 -3
  168. package/dist/game/TurnState.js.map +1 -1
  169. package/dist/game/ai/AiClientPrompts.d.ts +177 -0
  170. package/dist/game/ai/AiClientPrompts.d.ts.map +1 -0
  171. package/dist/game/ai/AiClientPrompts.js +561 -0
  172. package/dist/game/ai/AiClientPrompts.js.map +1 -0
  173. package/dist/game/ai/AiLiveView.d.ts +2 -0
  174. package/dist/game/ai/AiLiveView.d.ts.map +1 -0
  175. package/dist/game/ai/AiLiveView.js +48 -0
  176. package/dist/game/ai/AiLiveView.js.map +1 -0
  177. package/dist/game/ai/AiPlayerView.d.ts +2 -0
  178. package/dist/game/ai/AiPlayerView.d.ts.map +1 -0
  179. package/dist/game/ai/AiPlayerView.js +91 -0
  180. package/dist/game/ai/AiPlayerView.js.map +1 -0
  181. package/dist/game/ai/connectAiPlayer.d.ts +43 -0
  182. package/dist/game/ai/connectAiPlayer.d.ts.map +1 -0
  183. package/dist/game/ai/connectAiPlayer.js +58 -0
  184. package/dist/game/ai/connectAiPlayer.js.map +1 -0
  185. package/dist/game/ai/defineAi.d.ts +119 -0
  186. package/dist/game/ai/defineAi.d.ts.map +1 -0
  187. package/dist/game/ai/defineAi.js +122 -0
  188. package/dist/game/ai/defineAi.js.map +1 -0
  189. package/dist/game/ai/simulateMatches.d.ts +62 -0
  190. package/dist/game/ai/simulateMatches.d.ts.map +1 -0
  191. package/dist/game/ai/simulateMatches.js +108 -0
  192. package/dist/game/ai/simulateMatches.js.map +1 -0
  193. package/dist/game/badAiTransport/BadAIClientPrompts.d.ts +3 -0
  194. package/dist/game/badAiTransport/BadAIClientPrompts.d.ts.map +1 -1
  195. package/dist/game/badAiTransport/BadAIClientPrompts.js +3 -0
  196. package/dist/game/badAiTransport/BadAIClientPrompts.js.map +1 -1
  197. package/dist/game/clientTransport/ClientPrompts.d.ts +20 -1
  198. package/dist/game/clientTransport/ClientPrompts.d.ts.map +1 -1
  199. package/dist/game/clientTransport/ClientPrompts.js +30 -1
  200. package/dist/game/clientTransport/ClientPrompts.js.map +1 -1
  201. package/dist/game/clientTransport/ClientTime.d.ts +13 -0
  202. package/dist/game/clientTransport/ClientTime.d.ts.map +1 -1
  203. package/dist/game/clientTransport/ClientTime.js +51 -11
  204. package/dist/game/clientTransport/ClientTime.js.map +1 -1
  205. package/dist/game/tutorial/TutorialController.d.ts +300 -0
  206. package/dist/game/tutorial/TutorialController.d.ts.map +1 -0
  207. package/dist/game/tutorial/TutorialController.js +1182 -0
  208. package/dist/game/tutorial/TutorialController.js.map +1 -0
  209. package/dist/game/tutorial/TutorialRuntime.d.ts +89 -0
  210. package/dist/game/tutorial/TutorialRuntime.d.ts.map +1 -0
  211. package/dist/game/tutorial/TutorialRuntime.js +261 -0
  212. package/dist/game/tutorial/TutorialRuntime.js.map +1 -0
  213. package/dist/game/tutorial/TutorialTheme.d.ts +28 -0
  214. package/dist/game/tutorial/TutorialTheme.d.ts.map +1 -0
  215. package/dist/game/tutorial/TutorialTheme.js +39 -0
  216. package/dist/game/tutorial/TutorialTheme.js.map +1 -0
  217. package/dist/game/tutorial/allowed.d.ts +2 -0
  218. package/dist/game/tutorial/allowed.d.ts.map +1 -0
  219. package/dist/game/tutorial/allowed.js +119 -0
  220. package/dist/game/tutorial/allowed.js.map +1 -0
  221. package/dist/game/tutorial/checks.d.ts +58 -0
  222. package/dist/game/tutorial/checks.d.ts.map +1 -0
  223. package/dist/game/tutorial/checks.js +144 -0
  224. package/dist/game/tutorial/checks.js.map +1 -0
  225. package/dist/game/tutorial/createDemoMatch.d.ts +47 -0
  226. package/dist/game/tutorial/createDemoMatch.d.ts.map +1 -0
  227. package/dist/game/tutorial/createDemoMatch.js +67 -0
  228. package/dist/game/tutorial/createDemoMatch.js.map +1 -0
  229. package/dist/game/tutorial/defineTutorial.d.ts +353 -0
  230. package/dist/game/tutorial/defineTutorial.d.ts.map +1 -0
  231. package/dist/game/tutorial/defineTutorial.js +86 -0
  232. package/dist/game/tutorial/defineTutorial.js.map +1 -0
  233. package/dist/game/tutorial/runTutorial.d.ts +63 -0
  234. package/dist/game/tutorial/runTutorial.d.ts.map +1 -0
  235. package/dist/game/tutorial/runTutorial.js +273 -0
  236. package/dist/game/tutorial/runTutorial.js.map +1 -0
  237. package/dist/hooks/usePanelNavigation.d.ts +28 -0
  238. package/dist/hooks/usePanelNavigation.d.ts.map +1 -0
  239. package/dist/hooks/usePanelNavigation.js +36 -0
  240. package/dist/hooks/usePanelNavigation.js.map +1 -0
  241. package/dist/hooks/useTimeController.d.ts +2 -1
  242. package/dist/hooks/useTimeController.d.ts.map +1 -1
  243. package/dist/hooks/useTimeController.js +6 -2
  244. package/dist/hooks/useTimeController.js.map +1 -1
  245. package/dist/hooks/useTokenMap.d.ts +2 -4
  246. package/dist/hooks/useTokenMap.d.ts.map +1 -1
  247. package/dist/hooks/useTokenMap.js +2 -5
  248. package/dist/hooks/useTokenMap.js.map +1 -1
  249. package/dist/hooks/useTutorial.d.ts +48 -0
  250. package/dist/hooks/useTutorial.d.ts.map +1 -0
  251. package/dist/hooks/useTutorial.js +16 -0
  252. package/dist/hooks/useTutorial.js.map +1 -0
  253. package/dist/index.d.ts +57 -1
  254. package/dist/index.d.ts.map +1 -1
  255. package/dist/index.html +12 -0
  256. package/dist/index.js +27 -3
  257. package/dist/index.js.map +1 -1
  258. package/dist/main.0792d734cde2c688d5f7.hot-update.js +16991 -0
  259. package/dist/main.0792d734cde2c688d5f7.hot-update.js.map +1 -0
  260. package/dist/main.0792d734cde2c688d5f7.hot-update.json +1 -0
  261. package/dist/pretty-chitty.js +204513 -0
  262. package/dist/pretty-chitty.js.map +1 -0
  263. package/dist/rendering/CameraWrapperPerspective.d.ts +5 -0
  264. package/dist/rendering/CameraWrapperPerspective.d.ts.map +1 -1
  265. package/dist/rendering/CameraWrapperPerspective.js +16 -0
  266. package/dist/rendering/CameraWrapperPerspective.js.map +1 -1
  267. package/dist/rendering/ChitGalleryItemInstance.d.ts +1 -0
  268. package/dist/rendering/ChitGalleryItemInstance.d.ts.map +1 -1
  269. package/dist/rendering/ChitGalleryItemInstance.js +12 -0
  270. package/dist/rendering/ChitGalleryItemInstance.js.map +1 -1
  271. package/dist/rendering/ChitRenderInstance.d.ts +9 -1
  272. package/dist/rendering/ChitRenderInstance.d.ts.map +1 -1
  273. package/dist/rendering/ChitRenderInstance.js +28 -0
  274. package/dist/rendering/ChitRenderInstance.js.map +1 -1
  275. package/dist/rendering/RootChitRenderInstance.d.ts +2 -0
  276. package/dist/rendering/RootChitRenderInstance.d.ts.map +1 -1
  277. package/dist/rendering/RootChitRenderInstance.js +29 -0
  278. package/dist/rendering/RootChitRenderInstance.js.map +1 -1
  279. package/dist/utilities/Annotations.d.ts +15 -0
  280. package/dist/utilities/Annotations.d.ts.map +1 -1
  281. package/dist/utilities/Annotations.js +31 -7
  282. package/dist/utilities/Annotations.js.map +1 -1
  283. package/dist/utilities/CanvasStack/CanvasStack.d.ts +13 -0
  284. package/dist/utilities/CanvasStack/CanvasStack.d.ts.map +1 -1
  285. package/dist/utilities/CanvasStack/CanvasStack.js +66 -15
  286. package/dist/utilities/CanvasStack/CanvasStack.js.map +1 -1
  287. package/dist/utilities/TokenizedText.d.ts +55 -0
  288. package/dist/utilities/TokenizedText.d.ts.map +1 -0
  289. package/dist/utilities/TokenizedText.js +47 -0
  290. package/dist/utilities/TokenizedText.js.map +1 -0
  291. package/dist/utilities/zIndex.d.ts +1 -0
  292. package/dist/utilities/zIndex.d.ts.map +1 -1
  293. package/dist/utilities/zIndex.js +1 -0
  294. package/dist/utilities/zIndex.js.map +1 -1
  295. package/package.json +3 -2
  296. package/src/library/components/ActionLogDisplay.tsx +1 -0
  297. package/src/library/components/BottomBarButton.tsx +5 -0
  298. package/src/library/components/ClientTrustMatchViewer.tsx +32 -2
  299. package/src/library/components/ContextGalleryDisplay.tsx +2 -0
  300. package/src/library/components/DemoWrapper.tsx +147 -52
  301. package/src/library/components/FullScreenGalleryDisplay.tsx +3 -0
  302. package/src/library/components/Gallery/BuiltItem.ts +34 -9
  303. package/src/library/components/Gallery/GalleryController.ts +75 -2
  304. package/src/library/components/Gallery/GalleryViewer.tsx +54 -10
  305. package/src/library/components/Gallery/LayoutManager.ts +30 -6
  306. package/src/library/components/Gallery/constants.ts +2 -0
  307. package/src/library/components/Gallery/registry.ts +44 -0
  308. package/src/library/components/GameDesigner.tsx +121 -12
  309. package/src/library/components/InlineGalleryDisplay.tsx +5 -0
  310. package/src/library/components/LiveButton.tsx +8 -5
  311. package/src/library/components/MatchViewer.tsx +14 -3
  312. package/src/library/components/Panel/MultiPanel.tsx +21 -0
  313. package/src/library/components/Panel/PanelContents.tsx +70 -1
  314. package/src/library/components/Panel/PanelTabStack.tsx +1 -0
  315. package/src/library/components/PanelSpark.tsx +9 -4
  316. package/src/library/components/Playground.tsx +125 -33
  317. package/src/library/components/PromptControls.tsx +7 -3
  318. package/src/library/components/SparkLineChart.tsx +23 -27
  319. package/src/library/components/TimeControlBar.tsx +5 -3
  320. package/src/library/components/TokenizedMarkdown.tsx +224 -0
  321. package/src/library/components/TokenizedMessage.tsx +30 -95
  322. package/src/library/components/TopBarPlayers.tsx +18 -10
  323. package/src/library/components/Tutorial/BrowserNarration.ts +233 -0
  324. package/src/library/components/Tutorial/TutorialBox.tsx +506 -0
  325. package/src/library/components/Tutorial/TutorialDevPanel.tsx +297 -0
  326. package/src/library/components/Tutorial/TutorialOverlay.tsx +1301 -0
  327. package/src/library/components/Tutorial/targetRects.ts +273 -0
  328. package/src/library/game/Chit.ts +23 -7
  329. package/src/library/game/ClientTimeState.ts +18 -0
  330. package/src/library/game/ConnectionTransport.ts +12 -3
  331. package/src/library/game/Game.ts +16 -1
  332. package/src/library/game/GameTheme.ts +4 -0
  333. package/src/library/game/Match.ts +174 -5
  334. package/src/library/game/MatchStorage.ts +14 -4
  335. package/src/library/game/Pick.ts +36 -1
  336. package/src/library/game/PlayerChit.ts +4 -1
  337. package/src/library/game/PlayerInfo.ts +13 -3
  338. package/src/library/game/PlayerPromptStatusChit.ts +8 -2
  339. package/src/library/game/Prompt.ts +20 -0
  340. package/src/library/game/Turn.ts +198 -68
  341. package/src/library/game/TurnState.ts +34 -3
  342. package/src/library/game/ai/AI_GUIDE.md +444 -0
  343. package/src/library/game/ai/AiClientPrompts.ts +730 -0
  344. package/src/library/game/ai/AiLiveView.ts +63 -0
  345. package/src/library/game/ai/AiPlayerView.ts +114 -0
  346. package/src/library/game/ai/ai.test.ts +475 -0
  347. package/src/library/game/ai/connectAiPlayer.ts +88 -0
  348. package/src/library/game/ai/defineAi.ts +230 -0
  349. package/src/library/game/ai/simulateMatches.ts +172 -0
  350. package/src/library/game/badAiTransport/BadAIClientPrompts.ts +3 -0
  351. package/src/library/game/clientTransport/ClientPrompts.ts +31 -1
  352. package/src/library/game/clientTransport/ClientTime.ts +54 -13
  353. package/src/library/game/serialize.test.ts +275 -0
  354. package/src/library/game/tutorial/TUTORIAL_GUIDE.md +411 -0
  355. package/src/library/game/tutorial/TutorialController.test.ts +731 -0
  356. package/src/library/game/tutorial/TutorialController.ts +1286 -0
  357. package/src/library/game/tutorial/TutorialRuntime.ts +311 -0
  358. package/src/library/game/tutorial/TutorialTheme.ts +67 -0
  359. package/src/library/game/tutorial/allowed.ts +145 -0
  360. package/src/library/game/tutorial/checks.ts +186 -0
  361. package/src/library/game/tutorial/createDemoMatch.ts +115 -0
  362. package/src/library/game/tutorial/defineTutorial.ts +414 -0
  363. package/src/library/game/tutorial/runTutorial.ts +331 -0
  364. package/src/library/game/undo.test.ts +282 -0
  365. package/src/library/hooks/usePanelNavigation.tsx +65 -0
  366. package/src/library/hooks/useTimeController.tsx +6 -2
  367. package/src/library/hooks/useTokenMap.ts +2 -6
  368. package/src/library/hooks/useTutorial.tsx +76 -0
  369. package/src/library/index.ts +91 -4
  370. package/src/library/rendering/CameraWrapperPerspective.ts +17 -0
  371. package/src/library/rendering/ChitGalleryItemInstance.ts +12 -0
  372. package/src/library/rendering/ChitRenderInstance.ts +34 -0
  373. package/src/library/rendering/RootChitRenderInstance.ts +30 -1
  374. package/src/library/utilities/Annotations.ts +35 -7
  375. package/src/library/utilities/CanvasStack/CanvasStack.ts +74 -29
  376. package/src/library/utilities/TokenizedText.test.ts +32 -0
  377. package/src/library/utilities/TokenizedText.ts +103 -0
  378. package/src/library/utilities/zIndex.ts +1 -0
@@ -0,0 +1,1301 @@
1
+ import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
2
+ import { Box } from "@mui/material";
3
+ import useSize from "@react-hook/size";
4
+ import { useTutorial } from "../../hooks/useTutorial";
5
+ import { useClientPrompts, useTimeController, useTimeState } from "../../hooks/useTimeController";
6
+ import { usePlayerId } from "../../hooks/usePlayer";
7
+ import { useGameTheme } from "../../hooks/useGameTheme";
8
+ import { useTokenMap } from "../../hooks/useTokenMap";
9
+ import { usePanelNavigation } from "../../hooks/usePanelNavigation";
10
+ import { useEventChannelState } from "../../hooks/useEventChannelState";
11
+ import { TutorialController, TutorialStatus, TutorialView } from "../../game/tutorial/TutorialController";
12
+ import { EventChannel } from "../../utilities/EventChannel";
13
+ import { samePasses } from "../../game/ClockDetails";
14
+ import { resolveTutorialTheme } from "../../game/tutorial/TutorialTheme";
15
+ import { BoxAnchor, BoxPlacement, Focus, Target } from "../../game/tutorial/defineTutorial";
16
+ import { PickPrompt } from "../../game/Prompt";
17
+ import { Chit } from "../../game/Chit";
18
+ import { PlayerChit } from "../../game/PlayerChit";
19
+ import { RootChit } from "../../game/RootChit";
20
+ import { ZINDEX_TUTORIAL } from "../../utilities/zIndex";
21
+ import { requestSharedAnimationFrame } from "../../utilities/RequestSharedAnimationFrame";
22
+ import { BrowserNarration } from "./BrowserNarration";
23
+ import { PanelShown, Rect, rectCenter, resolveTarget, tableRects, toLocal, unionRects } from "./targetRects";
24
+ import type { RootChitRenderInstance } from "../../rendering/RootChitRenderInstance";
25
+ import { UI_ALIASES } from "../../game/tutorial/allowed";
26
+ import { BoxPosition, TutorialBox } from "./TutorialBox";
27
+ import { useModalState } from "../../hooks/useModalState";
28
+ import { ModalState } from "../../game/ModalState";
29
+ import { GalleryCommand, TutorialGalleryState, selectChits } from "../../game/tutorial/defineTutorial";
30
+ import { GalleryItemSource } from "../Gallery/types";
31
+ import { GalleryItemChitChildrenSource } from "../../game/GalleryItemChitChildrenSource";
32
+ import { GalleryItemRawSource } from "../../game/GalleryItemRawSource";
33
+ import { chitsToGalleryItems } from "../../utilities/GalleryItemConversion";
34
+ import { RegisteredGallery } from "../Gallery/registry";
35
+
36
+ type DrawnFocus = {
37
+ /** One union box, or one per chit with `separate` */
38
+ rings: Rect[];
39
+ shape: "rect" | "ellipse";
40
+ arrows: Rect[];
41
+ dim: boolean;
42
+ };
43
+
44
+ /** What the overlay draws, and for which step (placement must not mix two steps' targets) */
45
+ type Frame = { focus: DrawnFocus[]; debug: Rect[]; step: number };
46
+
47
+ const RING_PADDING = 8;
48
+ /** The box keeps this far from the screen's sides */
49
+ const BOX_MARGIN = 16;
50
+ /** A ringed thing smaller than this (its longer side, in pixels, with the whole table shown) gets zoomed in on */
51
+ const ZOOM_BELOW_PX = 28;
52
+ /** ...until its longer side is this share of its panel's shorter side, or this many pixels: enough to read it,
53
+ * with its surroundings still in view (a zoom that fills the panel loses where the thing is) */
54
+ const ZOOM_TO_SHARE = 0.3;
55
+ const ZOOM_TO_MAX_PX = 140;
56
+ /** Full screen hides every other panel, so it is used only when it buys something the camera cannot: a ringed thing
57
+ * smaller than FOCUS_TARGET_PX that zooming in its own panel cannot bring to READABLE_PX (the panel is too small, or the
58
+ * camera's max zoom too low), and whose panel full screen would grow at least FOCUS_GAIN times. A board overview, a
59
+ * badge, anything readable in place stays in the normal layout, beside the rest of the table (the developer: "it should
60
+ * only go full screen when it'd gain something meaningful. otherwise you're losing context") */
61
+ const FOCUS_TARGET_PX = 24;
62
+ const READABLE_PX = 40;
63
+ const FOCUS_GAIN = 1.5;
64
+ /** A zoom the step asks for outright (`zoom: 1.6`) applies on a screen smaller than this (its shorter side: a phone) */
65
+ const SMALL_SCREEN_PX = 500;
66
+ /** The dim stays this long after nothing asks for it (a ring hidden by a tab slide, a sentence with no ring), so the
67
+ * gaps between rings do not blink it off and on */
68
+ const DIM_HOLD_MS = 400;
69
+ /** How long a ring that leapt in one frame stays where it was (see the ring tick) */
70
+ const JUMP_HOLD_MS = 120;
71
+
72
+ function sameFrame(a: Frame, b: Frame) {
73
+ return JSON.stringify(a) === JSON.stringify(b);
74
+ }
75
+
76
+ function overlapArea(a: Rect, b: Rect) {
77
+ const w = Math.min(a.right, b.right) - Math.max(a.left, b.left);
78
+ const h = Math.min(a.bottom, b.bottom) - Math.max(a.top, b.top);
79
+ return w > 0 && h > 0 ? w * h : 0;
80
+ }
81
+
82
+ const RING_BREATHING_ROOM = 20;
83
+ /** Arrows need room to be seen, so their targets push the box further away */
84
+ const ARROW_BREATHING_ROOM = 44;
85
+
86
+ /** A target the box keeps clear of; `weight` makes sitting next to an arrow's tip count as covering it */
87
+ type Avoid = { rect: Rect; room: number; weight: number };
88
+
89
+ /**
90
+ * How badly `box` hides the targets: the sum over targets of the fraction of each target (plus its
91
+ * breathing room) that the box covers. A small counter fully under the box counts as 1, the same as
92
+ * a whole card; the box's own size does not matter.
93
+ */
94
+ function coverage(box: Rect, targets: Avoid[]) {
95
+ return targets.reduce((acc, { rect: t, room, weight }) => {
96
+ const padded: Rect = { left: t.left - room, top: t.top - room, right: t.right + room, bottom: t.bottom + room };
97
+ const area = Math.max(1, (padded.right - padded.left) * (padded.bottom - padded.top));
98
+ return acc + (overlapArea(box, padded) / area) * weight;
99
+ }, 0);
100
+ }
101
+
102
+ /** Every rect the overlay is drawing right now: the box must not sit on any of them */
103
+ function targetRects(frame: Frame): Avoid[] {
104
+ return frame.focus.flatMap((f) => [
105
+ ...f.rings.map((rect) => ({ rect, room: RING_BREATHING_ROOM, weight: 1 })),
106
+ ...f.arrows.map((rect) => ({ rect, room: ARROW_BREATHING_ROOM, weight: 3 })),
107
+ ]);
108
+ }
109
+
110
+ function sameAvoid(a: Avoid, b: Avoid) {
111
+ return (
112
+ a.room === b.room &&
113
+ Math.abs(a.rect.left - b.rect.left) < 2 &&
114
+ Math.abs(a.rect.top - b.rect.top) < 2 &&
115
+ Math.abs(a.rect.right - b.rect.right) < 2 &&
116
+ Math.abs(a.rect.bottom - b.rect.bottom) < 2
117
+ );
118
+ }
119
+
120
+ /**
121
+ * The 2D tutorial layer over the whole player: rings and arrows (SVG) that follow chits and UI, the
122
+ * draggable text box, and the controller that drives them. Renders nothing unless the match was
123
+ * started with a tutorial (see `TutorialProvider`).
124
+ */
125
+ export function TutorialOverlay() {
126
+ const tutorial = useTutorial();
127
+ if (!tutorial) return null;
128
+ return <InnerOverlay />;
129
+ }
130
+
131
+ function InnerOverlay() {
132
+ const tutorial = useTutorial()!;
133
+ const clientTime = useTimeController();
134
+ const clientPrompts = useClientPrompts();
135
+ const timeState = useTimeState();
136
+ const playerId = usePlayerId();
137
+ const gameTheme = useGameTheme();
138
+ const tokenMap = useTokenMap();
139
+ const navigation = usePanelNavigation();
140
+ const modalState = useModalState();
141
+ const theme = useMemo(
142
+ () => resolveTutorialTheme(gameTheme, tutorial.spec.theme, tutorial.themeOverrides),
143
+ [gameTheme, tutorial.spec.theme, tutorial.themeOverrides],
144
+ );
145
+
146
+ const ref = useRef<HTMLDivElement>(null);
147
+ const [width, height] = useSize(ref);
148
+ const [rootChit] = useEventChannelState(clientTime.rootChit);
149
+ const [isLoading] = useEventChannelState(timeState.isLoading);
150
+ const [live] = useEventChannelState(timeState.live);
151
+ const [controller, setController] = useState<TutorialController<any, any> | undefined>();
152
+ const [started, setStarted] = useState(tutorial.autoStart);
153
+ const [dev] = useEventChannelState(tutorial.dev);
154
+ const [muted] = useEventChannelState(tutorial.muted);
155
+
156
+ // ---- the controller, built once the board exists -------------------------------------------
157
+ useEffect(() => {
158
+ if (!rootChit || controller) return;
159
+ const view: TutorialView<PlayerChit, RootChit<PlayerChit>> = {
160
+ root: () => clientTime.rootChit.value,
161
+ me: () => clientTime.rootChit.value?.players.find((p) => p.id === playerId),
162
+ prompt: () => {
163
+ const p = clientPrompts.currentPrompt.value;
164
+ return p instanceof PickPrompt ? p : undefined;
165
+ },
166
+ clock: () => clientTime.currentClock.value.clock,
167
+ find: (id) => clientTime.findChitUnsafe(id),
168
+ latestLog: () => clientTime.activeLog.value,
169
+ live: () => timeState.live.value,
170
+ onChange: (cb) => {
171
+ const unsubs = [
172
+ clientTime.currentClock.on(cb, false),
173
+ clientTime.rootChit.on(cb, false),
174
+ clientTime.activeLog.on(cb, false),
175
+ clientPrompts.currentPrompt.on(cb, false),
176
+ timeState.live.on(cb, false),
177
+ modalState.gallerySource.on(cb, false),
178
+ modalState.inlineGallerySource.on(cb, false),
179
+ ];
180
+ return () => unsubs.forEach((u) => u());
181
+ },
182
+ setGuard: (guard) => {
183
+ clientPrompts.guard = guard ? (_prompt, action) => guard(action) : undefined;
184
+ },
185
+ setUndo: (undo) => {
186
+ clientPrompts.undoOverride.value = undo;
187
+ },
188
+ galleries: () => describeGalleries(modalState),
189
+ setGallery: (command) =>
190
+ applyGalleryCommand(
191
+ modalState,
192
+ command,
193
+ clientTime.rootChit.value,
194
+ clientTime.rootChit.value?.players.find((p) => p.id === playerId),
195
+ ),
196
+ onBlocked: (cb) => clientPrompts.blocked.on((b) => b && cb(b.action), false),
197
+ // Poses change this client's copy of a chit only; the match never hears of them
198
+ pose: (chit, change) => clientTime.poseChit(chit, change),
199
+ unpose: (chit) => clientTime.restoreChit(chit),
200
+ // Holds only how far this board plays; the match runs on behind it
201
+ timeline: {
202
+ at: () => Math.max(clientTime.currentClock.value.clock, timeState.targetClock.value),
203
+ hold: (clock) => {
204
+ timeState.timelineHold.value = clock;
205
+ },
206
+ },
207
+ pressUi: (name) => {
208
+ const el = (UI_ALIASES[name] ?? [name])
209
+ .map((n) => document.querySelector(`[data-tutorial-target="${CSS.escape(n)}"]`) as HTMLElement | null)
210
+ .find((e) => e && e.getBoundingClientRect().width > 0);
211
+ if (!el) return false;
212
+ // a target is often a wrapper around the actual control
213
+ const control = (el.matches("button, [role=button]") ? el : el.querySelector("button, [role=button]")) ?? el;
214
+ (control as HTMLElement).click();
215
+ return true;
216
+ },
217
+ settled: () =>
218
+ !timeState.isWaitingOnAnimations.value &&
219
+ clientTime.currentClock.value.clock >= clientTime.maxClock.value.clock,
220
+ setFastForward: (on) => {
221
+ timeState.animationSpeedOverrideMultiplier.value = on ? 0.05 : undefined;
222
+ },
223
+ };
224
+ const { snapshot, rewind, runtime } = tutorial;
225
+ const c = new TutorialController({
226
+ spec: tutorial.spec,
227
+ view,
228
+ runtime,
229
+ narration: new BrowserNarration(),
230
+ ai: tutorial.ai,
231
+ onEvent: tutorial.onEvent,
232
+ muted: tutorial.muted.value,
233
+ rate: readRate(),
234
+ history:
235
+ snapshot && rewind
236
+ ? {
237
+ save: (stepId) => runtime.saveSnapshot(stepId, snapshot()),
238
+ restore: async (stepId, index) => {
239
+ // Watch the history live, then wait for the rerun (a new clock pass) to reach this view
240
+ if (!timeState.live.value) timeState.live.value = true;
241
+ const before = clientTime.currentClock.value.pass;
242
+ // Skipping ahead shows the board as it is at that step, not each move on the way there:
243
+ // the view goes straight to the rerun's latest clock, with no time to animate
244
+ const ahead = index > (tutorial.controller.value?.frontier.value ?? -1);
245
+ const started = Date.now();
246
+ const unsubJump = ahead
247
+ ? clientTime.maxClock.on((max) => {
248
+ if (max.pass !== before) timeState.targetClock.value = max.clock;
249
+ }, false)
250
+ : undefined;
251
+ if (ahead) timeState.animationSpeedOverrideMultiplier.value = 0.001;
252
+ const done = (ok: boolean) => {
253
+ unsubJump?.();
254
+ if (ahead) {
255
+ timeState.animationSpeedOverrideMultiplier.value = undefined;
256
+ console.info(`[tutorial] skipped to step ${index + 1} in ${Date.now() - started} ms`);
257
+ }
258
+ return ok;
259
+ };
260
+ if (!(await rewind(stepId))) return done(false);
261
+ const deadline = Date.now() + 8000;
262
+ while (Date.now() < deadline) {
263
+ const current = clientTime.currentClock.value;
264
+ const max = clientTime.maxClock.value;
265
+ if (ahead) console.info("ZZTIME wait", Date.now() - started, current.clock, max.clock, current.pass === max.pass, [...((timeState as any).currentlyAnimating ?? [])].map((k: string) => k.replace(/\d{6,}/, "")).join(","));
266
+ if (
267
+ current.pass !== before &&
268
+ current.clock === max.clock &&
269
+ samePasses(current, max) &&
270
+ !timeState.isWaitingOnAnimations.value
271
+ ) {
272
+ break;
273
+ }
274
+ await new Promise((resolve) => setTimeout(resolve, ahead ? 5 : 50));
275
+ }
276
+ return done(true);
277
+ },
278
+ }
279
+ : undefined,
280
+ });
281
+ setController(c);
282
+ tutorial.controller.value = c;
283
+ c.rate.on((rate) => writeRate(rate), false);
284
+ if (tutorial.autoStart) {
285
+ // After a rewind or a dev restart: the board is already there and the player already tapped once
286
+ setStarted(true);
287
+ c.start(tutorial.startAt, { paused: tutorial.startPaused });
288
+ }
289
+ }, [rootChit, controller, clientTime, clientPrompts, timeState, playerId, tutorial, modalState]);
290
+
291
+ useEffect(() => {
292
+ return () => {
293
+ controller?.dispose();
294
+ if (tutorial.controller.value === controller) tutorial.controller.value = undefined;
295
+ };
296
+ }, [controller, tutorial]);
297
+
298
+ useEffect(() => {
299
+ controller?.setMuted(muted);
300
+ }, [controller, muted]);
301
+
302
+ // Tapping a control the next "do it" step asks for counts as moving on to that step. Listen in the
303
+ // capture phase so the step is entered (and its check baselined) before the control acts.
304
+ useEffect(() => {
305
+ if (!controller) return;
306
+ const onClick = (e: MouseEvent) => {
307
+ const el = (e.target as Element | null)?.closest?.("[data-tutorial-target]");
308
+ const name = el?.getAttribute("data-tutorial-target");
309
+ if (name) controller.usedUi(name);
310
+ };
311
+ document.addEventListener("click", onClick, true);
312
+ return () => document.removeEventListener("click", onClick, true);
313
+ }, [controller]);
314
+
315
+ // Keyboard: → next step (or, while a step waits for the player, makes its move for them), ← previous
316
+ // step, Space play/pause. Otherwise the same as the box's buttons. Before the start, → or Enter starts.
317
+ const startRef = useRef<() => void>(() => undefined);
318
+ useEffect(() => {
319
+ if (!controller) return;
320
+ const onKey = (e: KeyboardEvent) => {
321
+ if (e.defaultPrevented || e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) return;
322
+ const el = e.target as HTMLElement | null;
323
+ if (el && (el.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName))) return;
324
+ const status = controller.status.value;
325
+ if (status === "idle") {
326
+ if (e.key !== "ArrowRight" && e.key !== "Enter") return;
327
+ startRef.current();
328
+ e.preventDefault();
329
+ return;
330
+ }
331
+ if (status === "done") return;
332
+ if (e.key === "ArrowRight") controller.forward();
333
+ else if (e.key === "ArrowLeft") controller.back();
334
+ else if (e.key === " ") {
335
+ // a focused button would also take the space as a click
336
+ if (el?.tagName === "BUTTON") el.blur();
337
+ controller.toggleNarration();
338
+ } else return;
339
+ e.preventDefault();
340
+ };
341
+ window.addEventListener("keydown", onKey);
342
+ return () => window.removeEventListener("keydown", onKey);
343
+ }, [controller]);
344
+
345
+ const onStart = useCallback(() => {
346
+ if (!controller || controller.status.value !== "idle") return;
347
+ setStarted(true);
348
+ controller.start(tutorial.startAt);
349
+ }, [controller, tutorial.startAt]);
350
+ startRef.current = onStart;
351
+ // Skipping to a step (the dev panel) starts the tutorial too
352
+ useEffect(() => {
353
+ if (!controller) return;
354
+ const update = () => {
355
+ if (controller.status.value !== "idle" || controller.rewinding.value) setStarted(true);
356
+ };
357
+ const unsubs = [controller.status.on(update, false), controller.rewinding.on(update, false)];
358
+ return () => unsubs.forEach((u) => u());
359
+ }, [controller]);
360
+
361
+ // ---- per-frame target resolution ------------------------------------------------------------
362
+ const [focus] = useEventChannelState(controller?.focus ?? EMPTY_FOCUS);
363
+ const [status] = useEventChannelState(controller?.status ?? IDLE);
364
+ // Everything this step has pointed at so far: an earlier sentence's target stays relevant while
365
+ // the step is on screen, so the box keeps clear of it too. Keyed by the step the frame was drawn for.
366
+ const stepTargetsRef = useRef<{ step: number; targets: Avoid[] }>({ step: -1, targets: [] });
367
+ const [placement] = useEventChannelState(controller?.box ?? NO_BOX);
368
+ const [frame, setFrame] = useState<Frame>({ focus: [], debug: [], step: -1 });
369
+ const frameRef = useRef(frame);
370
+ /** Rings that leapt in one frame, per focus entry: since when (see the ring tick) */
371
+ const jumpRef = useRef<{ focus: unknown; since: (number | undefined)[] }>({ focus: undefined, since: [] });
372
+ const [boxSize, setBoxSize] = useState({ width: theme.boxWidth, height: 160 });
373
+ // Dragging a narrower box is still allowed; the drag is clamped to the viewer
374
+ const [boxPos, setBoxPos] = useState<BoxPosition>({ x: 16, y: 16 });
375
+ // The latest box rect, for the framing (an effect that outlives renders)
376
+ const boxPosRef = useRef(boxPos);
377
+ boxPosRef.current = boxPos;
378
+ const boxSizeRef = useRef(boxSize);
379
+ boxSizeRef.current = boxSize;
380
+ const userDraggedRef = useRef(false);
381
+ const targetRectRef = useRef<Rect | undefined>(undefined);
382
+
383
+ const active = started && status !== "done" && live;
384
+ // Keep the box off the top and bottom bars: the player needs the prompt buttons the script points at
385
+ const safeTop = gameTheme.topBarHeight + 12;
386
+ const safeBottom = gameTheme.bottomBarHeight + 12;
387
+ /** Where the box may sit: inside the screen, clear of the top and bottom bars */
388
+ const clampBox = useCallback(
389
+ (p: BoxPosition): BoxPosition => ({
390
+ x: Math.max(BOX_MARGIN, Math.min(width - boxSize.width - BOX_MARGIN, p.x)),
391
+ y: Math.max(safeTop, Math.min(height - boxSize.height - safeBottom, p.y)),
392
+ }),
393
+ [width, height, boxSize.width, boxSize.height, safeTop, safeBottom],
394
+ );
395
+ // A chit is on screen only if its panel is in front of its tab group: one behind still paints during
396
+ // a tab slide, from where it would be, and a ring drawn there points at the wrong panel
397
+ const shown = useCallback<PanelShown>(
398
+ (chit) => {
399
+ if (!navigation) return true;
400
+ const roots = new Set(navigation.panelRoots().map((c) => c.id));
401
+ let panel: Chit | undefined = chit;
402
+ while (panel && !roots.has(panel.id)) panel = panel.parent;
403
+ return !panel?.id || navigation.isFront(panel.id);
404
+ },
405
+ [navigation],
406
+ );
407
+ // The box floats on every screen size; on a narrow one it just gets narrower
408
+ const boxWidth = Math.max(220, Math.min(theme.boxWidth, width - 32));
409
+
410
+ // Bring hidden targets on screen, and keep doing so for as long as the step has one: the panel
411
+ // stack flips to wherever the bots act, and a target that is off screen explains nothing
412
+ useEffect(() => {
413
+ if (!active || !navigation || !controller) return;
414
+ let cancelled = false;
415
+ let revealing = false;
416
+ let revealedOnce = false;
417
+ const attempt = () => {
418
+ if (cancelled || revealing) return;
419
+ const container = ref.current;
420
+ if (!container) return;
421
+ const ctx = controller.context();
422
+ const root = ctx?.root;
423
+ const me = ctx?.me;
424
+ const hidden = new Set<Chit>();
425
+ const visible = new Set<Chit>();
426
+ const scroll: { gallery: RegisteredGallery; chit: Chit }[] = [];
427
+ focus.forEach((f: Focus<any, any>) => {
428
+ if (f.reveal === false) return;
429
+ const targets: Target<any, any>[] = [];
430
+ if (f.ring) targets.push(f.ring);
431
+ if (f.arrow && f.arrow !== true) targets.push(f.arrow);
432
+ targets.forEach((t) => {
433
+ const resolved = resolveTarget(t, root, me, container, shown, ctx?.find);
434
+ resolved.hidden.forEach((c) => hidden.add(c));
435
+ resolved.chits.forEach((c) => !resolved.hidden.includes(c) && visible.add(c));
436
+ scroll.push(...resolved.offscreenInGallery);
437
+ });
438
+ });
439
+ // Items scrolled out of an open gallery: bring the first one into view
440
+ if (scroll.length > 0) scroll[0].gallery.scrollTo(scroll[0].chit);
441
+ // What shows stays in front: its tab group would otherwise slide off to wherever a bot just moved
442
+ visible.forEach((c) => navigation.keepFront(c));
443
+ if (hidden.size === 0) return;
444
+ // Targets in two panels of one tab group cannot both show: switch once, not back and forth
445
+ if (visible.size > 0 && revealedOnce) return;
446
+ revealedOnce = true;
447
+ revealing = true;
448
+ void navigation.revealChit([...hidden][0]).finally(() => {
449
+ revealing = false;
450
+ });
451
+ };
452
+ const first = setTimeout(attempt, 50);
453
+ const interval = setInterval(attempt, 400);
454
+ return () => {
455
+ cancelled = true;
456
+ clearTimeout(first);
457
+ clearInterval(interval);
458
+ };
459
+ }, [focus, active, navigation, controller, shown]);
460
+
461
+ // Frame what the step is about. When everything it rings on the table sits in one panel and is too small
462
+ // to read even with that panel's camera zoomed (see FOCUS_TARGET_PX), show that panel full screen (as
463
+ // zooming in does, with every panel as a tab); anything readable in place stays beside the rest of the
464
+ // table. Rings in another panel go back
465
+ // to the normal layout first, and full screen comes back only if that one needs it too: switching
466
+ // tabs inside full screen, sentence after sentence, flips panels with no context. Then, if the thing
467
+ // is still tiny, zoom the camera in on it, and keep that zoom while the step's later rings still show
468
+ // in it. Both are undone when no longer needed (not if the player zoomed or focused meanwhile: that is
469
+ // theirs). Only what is ringed counts, and only on the table (a gallery shows things at a readable
470
+ // size already).
471
+ const zoomRef = useRef<{ panel: RootChitRenderInstance; zoom: number } | undefined>(undefined);
472
+ const focusedByUsRef = useRef<Chit | undefined>(undefined);
473
+ /** The step whose rings set the current framing */
474
+ const framedStepRef = useRef(-1);
475
+ // The framing moved the targets: the box's memory of where they were this step is out of date
476
+ const forgetTargets = () => {
477
+ stepTargetsRef.current.targets = [];
478
+ };
479
+ const unzoom = useCallback(() => {
480
+ const z = zoomRef.current;
481
+ zoomRef.current = undefined;
482
+ if (z && Math.abs(z.panel.cameraZoom - z.zoom) < 0.01) {
483
+ z.panel.focusCamera(z.panel.width / 2, z.panel.height / 2, 1);
484
+ forgetTargets();
485
+ }
486
+ // eslint-disable-next-line react-hooks/exhaustive-deps
487
+ }, []);
488
+ const unfocus = useCallback(() => {
489
+ const ours = focusedByUsRef.current;
490
+ focusedByUsRef.current = undefined;
491
+ if (ours && navigation?.focusedPanel()) void navigation.focusPanelOf(undefined);
492
+ }, [navigation]);
493
+ useEffect(() => {
494
+ if (!active || !controller) {
495
+ unzoom();
496
+ unfocus();
497
+ return;
498
+ }
499
+ let cancelled = false;
500
+ const ringed = () => {
501
+ const container = ref.current;
502
+ const ctx = controller.context();
503
+ const found: { rect: Rect; panel: RootChitRenderInstance }[] = [];
504
+ const panels = new Map<string, Chit>(); // panel root id → a ringed chit in it
505
+ let inGallery = false;
506
+ let asked: number | undefined; // a zoom the step asks for outright
507
+ if (!container || !navigation) return { found, panels, inGallery, asked };
508
+ const roots = new Set(navigation.panelRoots().map((c) => c.id));
509
+ focus.forEach((f: Focus<any, any>) => {
510
+ if (f.reveal === false || f.zoom === false || !f.ring) return;
511
+ const t = f.ring;
512
+ if (typeof t !== "function" && !("chit" in t)) return; // a UI or screen target
513
+ if (typeof f.zoom === "number") asked = Math.max(asked ?? 1, f.zoom);
514
+ const table = tableRects(t, ctx?.root, ctx?.me, container, shown);
515
+ inGallery ||= table.inGallery;
516
+ found.push(...table.rects);
517
+ for (const c of selectChits(typeof t === "function" ? t : t.chit, ctx?.root, ctx?.me)) {
518
+ let p: Chit | undefined = c;
519
+ while (p && !roots.has(p.id)) p = p.parent;
520
+ if (p?.id) panels.set(p.id, c);
521
+ }
522
+ });
523
+ return { found, panels, inGallery, asked };
524
+ };
525
+ const zoomIn = () => {
526
+ const { found, inGallery, asked, panels } = ringed();
527
+ // Nothing to frame in this cue (only rings that flash by, or UI): keep the step's framing; a new
528
+ // step starts zoomed out
529
+ if (panels.size === 0 && !inGallery) {
530
+ if (controller.index.value !== framedStepRef.current) unzoom();
531
+ return;
532
+ }
533
+ const sameStep = framedStepRef.current === controller.index.value;
534
+ framedStepRef.current = controller.index.value;
535
+ const panel = found[0]?.panel;
536
+ if (!panel || inGallery || found.some((f) => f.panel !== panel)) return unzoom();
537
+ // Only one panel is remembered as zoomed: moving the framing to another panel zooms the first back out, or
538
+ // it would stay zoomed in for good and its later rings land off-screen (Lisboa's Court card → Influence disc
539
+ // → Manuel's office)
540
+ if (zoomRef.current && zoomRef.current.panel !== panel) unzoom();
541
+ const union = unionRects(found.map((f) => f.rect))!;
542
+ const topLeft = panel.convertCameraSpaceToScreenSpace(-1, 1);
543
+ const bottomRight = panel.convertCameraSpaceToScreenSpace(1, -1);
544
+ if (!topLeft || !bottomRight) return;
545
+ // Later in the same step, a zoom whose view still shows every ring stays: re-framing each sentence is a
546
+ // camera that never stops moving
547
+ const inset = 8;
548
+ if (
549
+ sameStep &&
550
+ zoomRef.current?.panel === panel &&
551
+ union.left >= topLeft.x + inset &&
552
+ union.right <= bottomRight.x - inset &&
553
+ union.top >= topLeft.y + inset &&
554
+ union.bottom <= bottomRight.y - inset
555
+ )
556
+ return;
557
+ // its longer side with the whole table shown
558
+ const current = panel.cameraZoom;
559
+ const size = Math.max(union.right - union.left, union.bottom - union.top) / current;
560
+ // Where the thing should end up: the part of the panel the box leaves free (above or below it)
561
+ const bounds = ref.current!.getBoundingClientRect();
562
+ const box = {
563
+ left: bounds.left + boxPosRef.current.x,
564
+ top: bounds.top + boxPosRef.current.y,
565
+ right: bounds.left + boxPosRef.current.x + boxSizeRef.current.width,
566
+ bottom: bounds.top + boxPosRef.current.y + boxSizeRef.current.height,
567
+ };
568
+ let bandTop = topLeft.y;
569
+ let bandBottom = bottomRight.y;
570
+ if (box.right > topLeft.x && box.left < bottomRight.x && box.bottom > topLeft.y && box.top < bottomRight.y) {
571
+ if (box.top - topLeft.y >= bottomRight.y - box.bottom) bandBottom = Math.max(topLeft.y + 1, box.top);
572
+ else bandTop = Math.min(bottomRight.y - 1, box.bottom);
573
+ }
574
+ const panelShort = Math.min(bottomRight.x - topLeft.x, bottomRight.y - topLeft.y);
575
+ // a zoom the step asks for is for small screens, like the full-screen panel
576
+ const smallScreen = Math.min(width, height) < SMALL_SCREEN_PX;
577
+ const fits = Math.min(0.85 * (bandBottom - bandTop), 0.85 * (bottomRight.x - topLeft.x)) / size;
578
+ const wanted =
579
+ asked && smallScreen ? asked : size < ZOOM_BELOW_PX ? Math.min(Math.min(panelShort * ZOOM_TO_SHARE, ZOOM_TO_MAX_PX) / size, fits) : 1;
580
+ const zoom = Math.min(wanted, panel.cameraWrapper.cameraSpec.maxZoom);
581
+ if (zoom < 1.25) return unzoom();
582
+ // focusCamera brings a point to the middle: pick the point that puts the thing in the free band
583
+ const c = rectCenter(union);
584
+ const shift = ((bandTop + bandBottom) / 2 - (topLeft.y + bottomRight.y) / 2) * (current / zoom);
585
+ panel.focusCamera(c.x - topLeft.x, c.y - shift - topLeft.y, zoom);
586
+ zoomRef.current = { panel, zoom: panel.cameraZoom };
587
+ forgetTargets();
588
+ };
589
+ const frame = async () => {
590
+ if (cancelled || !navigation) return;
591
+ const { panels, inGallery } = ringed();
592
+ // A new step with nothing on the table (a button, the box alone): full screen we chose goes
593
+ if (
594
+ panels.size === 0 &&
595
+ !inGallery &&
596
+ focusedByUsRef.current &&
597
+ navigation.focusedPanel() &&
598
+ controller.index.value !== framedStepRef.current
599
+ ) {
600
+ unzoom();
601
+ focusedByUsRef.current = undefined;
602
+ await navigation.focusPanelOf(undefined);
603
+ forgetTargets();
604
+ }
605
+ if (!inGallery && panels.size > 1 && navigation.focusedPanel()) {
606
+ // the step needs more than one panel: the normal layout shows them side by side
607
+ unzoom();
608
+ focusedByUsRef.current = undefined;
609
+ await navigation.focusPanelOf(undefined);
610
+ forgetTargets();
611
+ } else if (!inGallery && panels.size === 1) {
612
+ const [[, chit]] = [...panels];
613
+ // Full screen we chose for another panel: back to the normal layout, then decide afresh from there
614
+ const ours = focusedByUsRef.current;
615
+ if (ours && navigation.focusedPanel() && ours.renderInstance?.rootRenderInstance !== chit.renderInstance?.rootRenderInstance) {
616
+ unzoom();
617
+ focusedByUsRef.current = undefined;
618
+ await navigation.focusPanelOf(undefined);
619
+ forgetTargets();
620
+ if (cancelled) return;
621
+ }
622
+ if (navigation.focusedPanel()) {
623
+ // full screen already (the player's, or ours for this panel): switch to its tab
624
+ await navigation.focusPanelOf(chit);
625
+ forgetTargets();
626
+ } else {
627
+ const panel = chit.renderInstance?.rootRenderInstance;
628
+ const union = unionRects(ringed().found.map((f) => f.rect));
629
+ if (panel && union && width && height) {
630
+ const size = Math.max(union.right - union.left, union.bottom - union.top) / panel.cameraZoom;
631
+ const zoomable = Math.min(Math.min(panel.width, panel.height) * ZOOM_TO_SHARE, size * panel.cameraWrapper.cameraSpec.maxZoom);
632
+ const gain = Math.min(width / panel.width, height / panel.height);
633
+ if (size < FOCUS_TARGET_PX && zoomable < READABLE_PX && gain >= FOCUS_GAIN) {
634
+ await navigation.focusPanelOf(chit);
635
+ focusedByUsRef.current = chit;
636
+ forgetTargets();
637
+ }
638
+ }
639
+ }
640
+ }
641
+ if (!cancelled) zoomIn();
642
+ };
643
+ // After a tab switch has slid in (see the reveal above), and the zoom once more in case it was slow
644
+ const first = setTimeout(() => void frame(), 450);
645
+ const again = setTimeout(() => !cancelled && zoomIn(), 1500);
646
+ return () => {
647
+ cancelled = true;
648
+ clearTimeout(first);
649
+ clearTimeout(again);
650
+ };
651
+ }, [focus, active, controller, shown, unzoom, unfocus, navigation, width, height]);
652
+
653
+ // While the player only watches, the prompt's own strip (the gallery its toggle button opens by
654
+ // itself) is put away, so the board gets the room; it comes back when it is the player's move or
655
+ // the step points into it. A strip the player opens themselves stays open.
656
+ const putAwayRef = useRef<{ source: GalleryItemSource; channel: EventChannel<GalleryItemSource | undefined> } | undefined>(undefined);
657
+ useEffect(() => {
658
+ if (!controller || !active) return;
659
+ const promptStrips = (): GalleryItemSource[] => {
660
+ const p = clientPrompts.currentPrompt.value;
661
+ if (!(p instanceof PickPrompt)) return [];
662
+ return p.picks.flatMap((k) => {
663
+ // a chit pick's toggle button (Hand, Actions...), when it opens its gallery by itself
664
+ const button = (k as { button?: { autoShow?: boolean; galleryItemSource?: GalleryItemSource } }).button;
665
+ return button?.autoShow && button.galleryItemSource ? [button.galleryItemSource] : [];
666
+ });
667
+ };
668
+ const playersMove = () => {
669
+ const allow = controller.step?.allow;
670
+ const list = allow === undefined ? [] : Array.isArray(allow) ? allow : [allow];
671
+ return controller.status.value === "waiting" && !controller.reviewing.value && list.length > 0;
672
+ };
673
+ const pointsInto = (source: GalleryItemSource) => {
674
+ const ids = new Set(describeSource(source, "inline").chitIds);
675
+ const ctx = controller.context();
676
+ return controller.focus.value.some((f: Focus<any, any>) =>
677
+ [f.ring, f.arrow].some((t) => {
678
+ if (!t || t === true) return false;
679
+ if (typeof t !== "function" && "ui" in t) {
680
+ const name = typeof t.ui === "function" ? (ctx ? t.ui(ctx.root, ctx.me) : "") : t.ui;
681
+ return typeof name === "string" && (name.startsWith("gallery:") || name.startsWith("button:"));
682
+ }
683
+ if (typeof t !== "function" && !("chit" in t)) return false;
684
+ const selector = typeof t === "function" ? t : t.chit;
685
+ return selectChits(selector, ctx?.root, ctx?.me).some((c) => ids.has(c.id ?? ""));
686
+ }),
687
+ );
688
+ };
689
+ // Inline or full screen, as the player prefers
690
+ const channels = [modalState.inlineGallerySource, modalState.gallerySource];
691
+ const update = () => {
692
+ const strips = promptStrips();
693
+ const away = putAwayRef.current;
694
+ if (away && !strips.includes(away.source)) putAwayRef.current = undefined; // its prompt is gone
695
+ for (const channel of channels) {
696
+ const open = channel.value;
697
+ if (open && strips.includes(open) && !playersMove() && !pointsInto(open)) {
698
+ putAwayRef.current = { source: open, channel };
699
+ channel.value = undefined;
700
+ }
701
+ }
702
+ const back = putAwayRef.current;
703
+ if (back && !channels.some((c) => c.value) && (playersMove() || pointsInto(back.source))) {
704
+ back.channel.value = back.source;
705
+ putAwayRef.current = undefined;
706
+ }
707
+ };
708
+ update();
709
+ const unsubs = [
710
+ controller.status.on(update, false),
711
+ controller.focus.on(update, false),
712
+ controller.index.on(update, false),
713
+ clientPrompts.currentPrompt.on(update, false),
714
+ ];
715
+ return () => unsubs.forEach((u) => u());
716
+ }, [controller, active, clientPrompts, modalState]);
717
+
718
+ // Project every target each frame while something is drawn; publish a new frame only when it changed
719
+ useEffect(() => {
720
+ if (!controller || (!active && !dev.showTargetRects)) {
721
+ if (frameRef.current.focus.length || frameRef.current.debug.length) {
722
+ frameRef.current = { focus: [], debug: [], step: -1 };
723
+ setFrame(frameRef.current);
724
+ }
725
+ return;
726
+ }
727
+ let cancelled = false;
728
+ const tick = () => {
729
+ if (cancelled) return;
730
+ requestSharedAnimationFrame(tick);
731
+ const container = ref.current;
732
+ if (!container) return;
733
+ const bounds = container.getBoundingClientRect();
734
+ const ctx = controller.context();
735
+ const root = ctx?.root;
736
+ const me = ctx?.me;
737
+ const drawn: DrawnFocus[] = [];
738
+ const debug: Rect[] = [];
739
+ let firstRing: Rect | undefined;
740
+ focus.forEach((f: Focus<any, any>) => {
741
+ let rings: Rect[] = [];
742
+ if (f.ring) {
743
+ const resolved = resolveTarget(f.ring, root, me, container, shown, ctx?.find);
744
+ const local = resolved.rects.map((r) => toLocal(r, bounds));
745
+ if (f.separate) {
746
+ rings = local;
747
+ } else {
748
+ const union = unionRects(local);
749
+ rings = union ? [union] : [];
750
+ }
751
+ debug.push(...local);
752
+ }
753
+ const ring = rings[0];
754
+ let arrows: Rect[] = [];
755
+ if (f.arrow === true) {
756
+ arrows = rings;
757
+ } else if (f.arrow) {
758
+ const resolved = resolveTarget(f.arrow, root, me, container, shown, ctx?.find);
759
+ arrows = resolved.rects.map((r) => toLocal(r, bounds));
760
+ debug.push(...arrows);
761
+ }
762
+ if (ring && !firstRing) firstRing = ring;
763
+ if (!firstRing && arrows[0]) firstRing = unionRects(arrows);
764
+ drawn.push({ rings, shape: f.shape ?? "rect", arrows, dim: !!f.dim });
765
+ });
766
+ // A ring that leaps across the screen in one frame, for the same focus, is the board mid-switch (a
767
+ // panel reporting where it is going a frame before it gets there): keep it where it was until
768
+ // the new place has lasted a moment. Zooms and slides move smoothly and are never held back.
769
+ const jumps = jumpRef.current;
770
+ if (jumps.focus !== focus) jumpRef.current = { focus, since: [] };
771
+ else {
772
+ const now = performance.now();
773
+ const far = 0.2 * Math.min(bounds.width, bounds.height);
774
+ drawn.forEach((d, i) => {
775
+ const before = frameRef.current.focus[i];
776
+ const moved =
777
+ before && before.rings.length === d.rings.length && d.rings.length > 0
778
+ ? Math.max(...d.rings.map((r, k) => {
779
+ const a = rectCenter(r), b = rectCenter(before.rings[k]);
780
+ return Math.hypot(a.x - b.x, a.y - b.y);
781
+ }))
782
+ : 0;
783
+ if (moved <= far) {
784
+ jumps.since[i] = undefined;
785
+ return;
786
+ }
787
+ jumps.since[i] ??= now;
788
+ if (now - jumps.since[i]! < JUMP_HOLD_MS) drawn[i] = before;
789
+ else jumps.since[i] = undefined;
790
+ });
791
+ }
792
+ targetRectRef.current = firstRing;
793
+ const next: Frame = { focus: drawn, debug: dev.showTargetRects ? debug : [], step: controller.index.value };
794
+ if (!sameFrame(next, frameRef.current)) {
795
+ frameRef.current = next;
796
+ setFrame(next);
797
+ }
798
+ };
799
+ tick();
800
+ return () => {
801
+ cancelled = true;
802
+ };
803
+ }, [controller, focus, active, dev.showTargetRects, shown]);
804
+
805
+ // ---- box placement --------------------------------------------------------------------------
806
+ useEffect(() => {
807
+ userDraggedRef.current = false;
808
+ }, [placement]);
809
+
810
+ useEffect(() => {
811
+ const container = ref.current;
812
+ if (!container || width === 0) return;
813
+ if (stepTargetsRef.current.step !== frame.step) {
814
+ stepTargetsRef.current = { step: frame.step, targets: [] };
815
+ }
816
+ const seen = stepTargetsRef.current.targets;
817
+ targetRects(frame).forEach((t) => {
818
+ if (!seen.some((s) => sameAvoid(s, t))) seen.push(t);
819
+ });
820
+ const targetsNow = seen;
821
+ const rectNow: Rect = {
822
+ left: boxPos.x,
823
+ top: boxPos.y,
824
+ right: boxPos.x + boxSize.width,
825
+ bottom: boxPos.y + boxSize.height,
826
+ };
827
+ const margin = BOX_MARGIN;
828
+ const bw = boxSize.width;
829
+ const bh = boxSize.height;
830
+ const clamp = clampBox;
831
+ // A dragged box stays put unless a target shows up underneath it (but stays on screen when it
832
+ // grows or the screen turns)
833
+ if (userDraggedRef.current && coverage(rectNow, targetsNow) <= 0.1) {
834
+ const kept = clamp(boxPos);
835
+ if (Math.abs(kept.x - boxPos.x) > 1 || Math.abs(kept.y - boxPos.y) > 1) setBoxPos(kept);
836
+ return;
837
+ }
838
+ const place = (p: BoxPlacement<any, any> | undefined): BoxPosition => {
839
+ const anchor = p?.anchor ?? "top-right";
840
+ switch (anchor) {
841
+ case "top-left":
842
+ return { x: margin, y: safeTop };
843
+ case "top":
844
+ return { x: (width - bw) / 2, y: safeTop };
845
+ case "top-right":
846
+ return { x: width - bw - margin, y: safeTop };
847
+ case "bottom-left":
848
+ return { x: margin, y: height - bh - safeBottom };
849
+ case "bottom":
850
+ return { x: (width - bw) / 2, y: height - bh - safeBottom };
851
+ case "bottom-right":
852
+ return { x: width - bw - margin, y: height - bh - safeBottom };
853
+ case "center":
854
+ return { x: (width - bw) / 2, y: (height - bh) / 2 };
855
+ case "keep":
856
+ return boxPos;
857
+ case "near": {
858
+ const bounds = container.getBoundingClientRect();
859
+ const ctx = controller?.context();
860
+ const resolved = resolveTarget((p as any).target, ctx?.root, ctx?.me, container, shown);
861
+ const target = unionRects(resolved.rects.map((r) => toLocal(r, bounds)));
862
+ if (!target) return boxPos;
863
+ const gap = 24;
864
+ const side =
865
+ (p as any).side ??
866
+ (target.bottom + gap + bh < height ? "below" : target.top - gap - bh > 0 ? "above" : "right");
867
+ const c = rectCenter(target);
868
+ switch (side) {
869
+ case "below":
870
+ return { x: c.x - bw / 2, y: target.bottom + gap };
871
+ case "above":
872
+ return { x: c.x - bw / 2, y: target.top - gap - bh };
873
+ case "left":
874
+ return { x: target.left - gap - bw, y: c.y - bh / 2 };
875
+ default:
876
+ return { x: target.right + gap, y: c.y - bh / 2 };
877
+ }
878
+ }
879
+ }
880
+ };
881
+ const targets = targetsNow;
882
+ const rectAt = (p: BoxPosition): Rect => ({ left: p.x, top: p.y, right: p.x + bw, bottom: p.y + bh });
883
+ // The start card sits in the middle of the darkened table
884
+ let next = clamp(place(started ? placement : { anchor: "center" }));
885
+ // Never sit on what the step is pointing at: if the requested spot covers a target, take the
886
+ // corner that covers the least (the current spot wins ties so the box does not wander)
887
+ if (coverage(rectAt(next), targets) > 0.1) {
888
+ const candidates: BoxAnchor[] = ["top-left", "top-right", "bottom-left", "bottom-right", "top", "bottom"];
889
+ let best = { pos: boxPos, cover: coverage(rectAt(boxPos), targets) };
890
+ for (const anchor of candidates) {
891
+ const pos = clamp(place({ anchor }));
892
+ const cover = coverage(rectAt(pos), targets);
893
+ if (cover < best.cover - 0.02) best = { pos, cover };
894
+ }
895
+ next = best.pos;
896
+ }
897
+ if (Math.abs(next.x - boxPos.x) > 1 || Math.abs(next.y - boxPos.y) > 1) {
898
+ setBoxPos(next);
899
+ }
900
+ // eslint-disable-next-line react-hooks/exhaustive-deps
901
+ }, [placement, width, height, boxSize.width, boxSize.height, frame, controller, safeTop, safeBottom, clampBox, shown, started]);
902
+
903
+ // Dragging keeps the box on screen too: a box dragged off it could not be dragged back
904
+ const clampRef = useRef(clampBox);
905
+ clampRef.current = clampBox;
906
+ const onDrag = useCallback((pos: BoxPosition) => {
907
+ userDraggedRef.current = true;
908
+ setBoxPos(clampRef.current(pos));
909
+ }, []);
910
+ const onMeasure = useCallback((size: { width: number; height: number }) => {
911
+ setBoxSize((prev) => (prev.width === size.width && prev.height === size.height ? prev : size));
912
+ }, []);
913
+
914
+ const wantDim = frame.focus.some((f) => f.dim) && frame.focus.some((f) => f.rings.length > 0 || f.arrows.length > 0);
915
+ const litNow = frame.focus.flatMap((f) => [
916
+ ...f.rings.map((rect) => ({ rect, shape: f.shape })),
917
+ ...f.arrows.map((rect) => ({ rect, shape: "rect" as const })),
918
+ ]);
919
+ const litRef = useRef(litNow);
920
+ if (wantDim) litRef.current = litNow;
921
+ const [anyDim, setAnyDim] = useState(false);
922
+ useEffect(() => {
923
+ if (wantDim) {
924
+ setAnyDim(true);
925
+ return;
926
+ }
927
+ const t = setTimeout(() => setAnyDim(false), DIM_HOLD_MS);
928
+ return () => clearTimeout(t);
929
+ }, [wantDim]);
930
+
931
+ if (!controller) {
932
+ return <Box ref={ref} sx={{ position: "absolute", inset: 0, pointerEvents: "none", zIndex: ZINDEX_TUTORIAL }} />;
933
+ }
934
+
935
+ const boxRect: Rect = {
936
+ left: boxPos.x,
937
+ top: boxPos.y,
938
+ right: boxPos.x + boxSize.width,
939
+ bottom: boxPos.y + boxSize.height,
940
+ };
941
+ const hasNarration = !!controller.step?.audio || controller.spec.steps.some((s) => !!s.audio);
942
+ // Once the tutorial is finished or skipped the box goes away and the match is just a game
943
+ const showBox = !isLoading && (live || !started) && status !== "done";
944
+ // A spotlight keeps everything the step highlights lit: every ring and every arrow target. Through a short
945
+ // gap (see DIM_HOLD_MS) the dim stays, with the holes it last had
946
+ const lit = anyDim && !wantDim ? litRef.current : litNow;
947
+
948
+ return (
949
+ <Box
950
+ ref={ref}
951
+ sx={{
952
+ position: "absolute",
953
+ inset: 0,
954
+ pointerEvents: "none",
955
+ zIndex: ZINDEX_TUTORIAL,
956
+ overflow: "hidden",
957
+ fontFamily: theme.fontFamily,
958
+ }}
959
+ >
960
+ {active && (
961
+ <svg width={width} height={height} style={{ position: "absolute", inset: 0, pointerEvents: "none" }}>
962
+ <defs>
963
+ <marker
964
+ id="tutorial-arrowhead"
965
+ viewBox="0 0 10 10"
966
+ refX="8"
967
+ refY="5"
968
+ markerWidth="7"
969
+ markerHeight="7"
970
+ orient="auto-start-reverse"
971
+ >
972
+ <path d="M 0 0 L 10 5 L 0 10 z" fill={theme.arrowColor} />
973
+ </marker>
974
+ {/* Sized to the overlay, not to each shape: a near-vertical arrow's own bounding box is a
975
+ few pixels wide and does not include its arrowhead, which then gets clipped */}
976
+ <filter id="tutorial-glow" filterUnits="userSpaceOnUse" x={0} y={0} width={width} height={height}>
977
+ <feGaussianBlur stdDeviation="4" result="blur" />
978
+ <feMerge>
979
+ <feMergeNode in="blur" />
980
+ <feMergeNode in="SourceGraphic" />
981
+ </feMerge>
982
+ </filter>
983
+ <mask id="tutorial-dim-mask">
984
+ <rect x={0} y={0} width={width} height={height} fill="white" />
985
+ {lit.map((l, i) => (
986
+ <RingShape key={i} rect={l.rect} shape={l.shape} pad={RING_PADDING + 4} fill="black" />
987
+ ))}
988
+ <rect
989
+ x={boxRect.left - 4}
990
+ y={boxRect.top - 4}
991
+ width={boxRect.right - boxRect.left + 8}
992
+ height={boxRect.bottom - boxRect.top + 8}
993
+ rx={theme.borderRadius}
994
+ fill="black"
995
+ />
996
+ </mask>
997
+ </defs>
998
+ {/* Always drawn, so it fades in and out rather than popping */}
999
+ <rect
1000
+ x={0}
1001
+ y={0}
1002
+ width={width}
1003
+ height={height}
1004
+ fill={theme.dimColor}
1005
+ opacity={anyDim ? theme.dimOpacity : 0}
1006
+ mask="url(#tutorial-dim-mask)"
1007
+ style={{ transition: "opacity 0.3s" }}
1008
+ />
1009
+ <style>{`
1010
+ @keyframes tutorialRingPulse { 0% { stroke-opacity: 0.55; } 50% { stroke-opacity: 1; } 100% { stroke-opacity: 0.55; } }
1011
+ @keyframes tutorialDash { to { stroke-dashoffset: -24; } }
1012
+ @keyframes tutorialArrowNudge { 0% { transform: translate(0,0); } 50% { transform: translate(var(--nx), var(--ny)); } 100% { transform: translate(0,0); } }
1013
+ `}</style>
1014
+ {frame.debug.map((r, i) => (
1015
+ <rect
1016
+ key={`d${i}`}
1017
+ x={r.left}
1018
+ y={r.top}
1019
+ width={r.right - r.left}
1020
+ height={r.bottom - r.top}
1021
+ fill="none"
1022
+ stroke="#ff00ff"
1023
+ strokeWidth={1}
1024
+ strokeDasharray="3 3"
1025
+ />
1026
+ ))}
1027
+ {frame.focus.map((f, i) => (
1028
+ <g key={i}>
1029
+ {f.rings.map((ring, j) => (
1030
+ <RingShape
1031
+ key={j}
1032
+ rect={ring}
1033
+ shape={f.shape}
1034
+ pad={ringPadding(ring, f.rings)}
1035
+ fill="none"
1036
+ stroke={theme.highlightColor}
1037
+ strokeWidth={3}
1038
+ filter="url(#tutorial-glow)"
1039
+ style={{ animation: "tutorialRingPulse 1.6s ease-in-out infinite" }}
1040
+ />
1041
+ ))}
1042
+ {f.arrows.map((target, j) => (
1043
+ <Arrow key={j} from={boxRect} to={target} color={theme.arrowColor} />
1044
+ ))}
1045
+ </g>
1046
+ ))}
1047
+ </svg>
1048
+ )}
1049
+
1050
+ {/* Until Start, the whole game sits dark behind the start card, and takes no taps */}
1051
+ {showBox && !started && (
1052
+ <Box
1053
+ sx={{ position: "absolute", inset: 0, pointerEvents: "auto", background: theme.dimColor, opacity: theme.dimOpacity }}
1054
+ />
1055
+ )}
1056
+ {showBox && (
1057
+ <TutorialBox
1058
+ controller={controller}
1059
+ theme={theme}
1060
+ tokenMap={tokenMap}
1061
+ position={boxPos}
1062
+ width={boxWidth}
1063
+ narrow={width < 600}
1064
+ onDrag={onDrag}
1065
+ onMeasure={onMeasure}
1066
+ started={started}
1067
+ onStart={onStart}
1068
+ hasNarration={hasNarration}
1069
+ />
1070
+ )}
1071
+ </Box>
1072
+ );
1073
+ }
1074
+
1075
+ // ---- galleries ---------------------------------------------------------------------------------
1076
+
1077
+ const DEFAULT_INLINE_GALLERY_SIZE = 125;
1078
+
1079
+ function describeSource(source: GalleryItemSource, mode: "inline" | "fullscreen"): TutorialGalleryState {
1080
+ const backing = source.backingObject;
1081
+ return {
1082
+ mode,
1083
+ of: backing instanceof Chit ? backing.id : undefined,
1084
+ chitIds: source.items.map((item) => ((item as any).chit instanceof Chit ? (item as any).chit.id : item.id)),
1085
+ };
1086
+ }
1087
+
1088
+ function describeGalleries(modal: ModalState): TutorialGalleryState[] {
1089
+ const result: TutorialGalleryState[] = [];
1090
+ if (modal.gallerySource.value) result.push(describeSource(modal.gallerySource.value, "fullscreen"));
1091
+ if (modal.inlineGallerySource.value) result.push(describeSource(modal.inlineGallerySource.value, "inline"));
1092
+ return result;
1093
+ }
1094
+
1095
+ /** The inline/full-screen choice the gallery buttons remember */
1096
+ function preferredGalleryMode(): "inline" | "fullscreen" {
1097
+ try {
1098
+ return window.localStorage.getItem("galleryFullScreen") === '"modal"' ? "fullscreen" : "inline";
1099
+ } catch {
1100
+ return "inline";
1101
+ }
1102
+ }
1103
+
1104
+ /**
1105
+ * Opens, switches or closes a gallery through the same modal state the gallery buttons use, so the
1106
+ * player can keep using those buttons. Returns true when it opened a new gallery.
1107
+ */
1108
+ function applyGalleryCommand(
1109
+ modal: ModalState,
1110
+ command: GalleryCommand<any, any>,
1111
+ root: RootChit<any> | undefined,
1112
+ me: PlayerChit | undefined,
1113
+ ): boolean {
1114
+ if (command === "close") {
1115
+ modal.gallerySource.value = undefined;
1116
+ modal.inlineGallerySource.value = undefined;
1117
+ return false;
1118
+ }
1119
+ const open = modal.gallerySource.value ?? modal.inlineGallerySource.value;
1120
+ let source: GalleryItemSource | undefined;
1121
+ let opened = false;
1122
+ if (command.of) {
1123
+ const container = selectChits(command.of, root, me)[0];
1124
+ if (container) {
1125
+ source = new GalleryItemChitChildrenSource(container);
1126
+ opened = true;
1127
+ }
1128
+ } else if (command.items) {
1129
+ const chits = selectChits(command.items, root, me);
1130
+ if (chits.length > 0) {
1131
+ source = new GalleryItemRawSource(chitsToGalleryItems(chits));
1132
+ opened = true;
1133
+ }
1134
+ } else if (open) {
1135
+ // Switching modes: a display closes the source it leaves, so hand the other one a fresh copy
1136
+ source = open.backingObject instanceof Chit ? new GalleryItemChitChildrenSource(open.backingObject) : open;
1137
+ source.inlineGallerySize = open.inlineGallerySize;
1138
+ }
1139
+ if (!source) return false;
1140
+ source.inlineGallerySize ??= DEFAULT_INLINE_GALLERY_SIZE;
1141
+ const mode =
1142
+ command.mode && command.mode !== "preferred"
1143
+ ? command.mode
1144
+ : opened
1145
+ ? preferredGalleryMode()
1146
+ : modal.gallerySource.value
1147
+ ? "fullscreen"
1148
+ : "inline";
1149
+ if (mode === "fullscreen") {
1150
+ modal.inlineGallerySource.value = undefined;
1151
+ modal.gallerySource.value = source;
1152
+ } else {
1153
+ modal.gallerySource.value = undefined;
1154
+ modal.inlineGallerySource.value = source;
1155
+ }
1156
+ return opened;
1157
+ }
1158
+
1159
+ const RATE_KEY = "tutorialPlaybackRate";
1160
+
1161
+ /** The narration speed this viewer chose last time (a per-device convenience; 1 when unavailable) */
1162
+ function readRate(): number {
1163
+ try {
1164
+ const value = parseFloat(window.localStorage.getItem(RATE_KEY) ?? "1");
1165
+ return value > 0 ? value : 1;
1166
+ } catch {
1167
+ return 1;
1168
+ }
1169
+ }
1170
+
1171
+ function writeRate(rate: number) {
1172
+ try {
1173
+ window.localStorage.setItem(RATE_KEY, String(rate));
1174
+ } catch {
1175
+ // private window or blocked storage: the speed just is not remembered
1176
+ }
1177
+ }
1178
+
1179
+ const EMPTY_FOCUS = new EventChannel<Focus<any, any>[]>([]);
1180
+ const IDLE = new EventChannel<TutorialStatus>("idle");
1181
+ const NO_BOX = new EventChannel<BoxPlacement<any, any> | undefined>(undefined);
1182
+
1183
+ /** A ring's padding: the usual breathing room, shrunk so neighbouring rings (with `separate`) never touch */
1184
+ function ringPadding(ring: Rect, all: Rect[]) {
1185
+ let pad = RING_PADDING;
1186
+ for (const other of all) {
1187
+ if (other === ring) continue;
1188
+ const gapX = Math.max(other.left - ring.right, ring.left - other.right);
1189
+ const gapY = Math.max(other.top - ring.bottom, ring.top - other.bottom);
1190
+ const gap = Math.max(gapX, gapY);
1191
+ pad = Math.min(pad, gap / 2 - 2);
1192
+ }
1193
+ return Math.max(1, pad);
1194
+ }
1195
+
1196
+ function RingShape({
1197
+ rect,
1198
+ shape,
1199
+ pad,
1200
+ ...rest
1201
+ }: { rect: Rect; shape: "rect" | "ellipse"; pad: number } & React.SVGProps<SVGRectElement> &
1202
+ React.SVGProps<SVGEllipseElement>) {
1203
+ const w = rect.right - rect.left + pad * 2;
1204
+ const h = rect.bottom - rect.top + pad * 2;
1205
+ if (shape === "ellipse") {
1206
+ return (
1207
+ <ellipse
1208
+ cx={rect.left - pad + w / 2}
1209
+ cy={rect.top - pad + h / 2}
1210
+ rx={w / 2}
1211
+ ry={h / 2}
1212
+ {...(rest as React.SVGProps<SVGEllipseElement>)}
1213
+ />
1214
+ );
1215
+ }
1216
+ return (
1217
+ <rect
1218
+ x={rect.left - pad}
1219
+ y={rect.top - pad}
1220
+ width={w}
1221
+ height={h}
1222
+ rx={Math.min(14, w / 4, h / 4)}
1223
+ {...(rest as React.SVGProps<SVGRectElement>)}
1224
+ />
1225
+ );
1226
+ }
1227
+
1228
+ /** A curved arrow from the nearest edge of the box to the nearest edge of the target. */
1229
+ function Arrow({ from, to, color }: { from: Rect; to: Rect; color: string }) {
1230
+ const tc = rectCenter(to);
1231
+ const fc = rectCenter(from);
1232
+ // Start on the box edge facing the target
1233
+ const dx = tc.x - fc.x;
1234
+ const dy = tc.y - fc.y;
1235
+ let start: { x: number; y: number };
1236
+ // ...as close to straight across from the target as the edge allows, so several arrows fan out
1237
+ // from their own points instead of one shared one
1238
+ const edgeMargin = 18;
1239
+ if (Math.abs(dx) * (from.bottom - from.top) > Math.abs(dy) * (from.right - from.left)) {
1240
+ start = {
1241
+ x: dx > 0 ? from.right : from.left,
1242
+ y: Math.max(from.top + edgeMargin, Math.min(from.bottom - edgeMargin, tc.y)),
1243
+ };
1244
+ } else {
1245
+ start = {
1246
+ x: Math.max(from.left + edgeMargin, Math.min(from.right - edgeMargin, tc.x)),
1247
+ y: dy > 0 ? from.bottom : from.top,
1248
+ };
1249
+ }
1250
+ // End on the target edge facing the box, a little outside it
1251
+ const pad = 10;
1252
+ const ex = tc.x - start.x;
1253
+ const ey = tc.y - start.y;
1254
+ let end: { x: number; y: number };
1255
+ if (Math.abs(ex) * (to.bottom - to.top) > Math.abs(ey) * (to.right - to.left)) {
1256
+ end = { x: ex > 0 ? to.left - pad : to.right + pad, y: tc.y };
1257
+ } else {
1258
+ end = { x: tc.x, y: ey > 0 ? to.top - pad : to.bottom + pad };
1259
+ }
1260
+ const len = Math.hypot(end.x - start.x, end.y - start.y);
1261
+ if (len < 24) return null;
1262
+ // Control point: perpendicular offset for a gentle curve
1263
+ const mx = (start.x + end.x) / 2;
1264
+ const my = (start.y + end.y) / 2;
1265
+ const nx = -(end.y - start.y) / len;
1266
+ const ny = (end.x - start.x) / len;
1267
+ const bend = Math.min(60, len * 0.2);
1268
+ const cx = mx + nx * bend;
1269
+ const cy = my + ny * bend;
1270
+ const ux = (end.x - start.x) / len;
1271
+ const uy = (end.y - start.y) / len;
1272
+ return (
1273
+ <g
1274
+ style={
1275
+ {
1276
+ "--nx": `${ux * 6}px`,
1277
+ "--ny": `${uy * 6}px`,
1278
+ animation: "tutorialArrowNudge 1.1s ease-in-out infinite",
1279
+ } as React.CSSProperties
1280
+ }
1281
+ >
1282
+ <path
1283
+ d={`M ${start.x} ${start.y} Q ${cx} ${cy} ${end.x} ${end.y}`}
1284
+ fill="none"
1285
+ stroke="rgba(0,0,0,0.35)"
1286
+ strokeWidth={6}
1287
+ strokeLinecap="round"
1288
+ />
1289
+ <path
1290
+ d={`M ${start.x} ${start.y} Q ${cx} ${cy} ${end.x} ${end.y}`}
1291
+ fill="none"
1292
+ stroke={color}
1293
+ strokeWidth={3}
1294
+ strokeLinecap="round"
1295
+ markerEnd="url(#tutorial-arrowhead)"
1296
+ filter="url(#tutorial-glow)"
1297
+ />
1298
+ <circle cx={start.x} cy={start.y} r={4} fill={color} />
1299
+ </g>
1300
+ );
1301
+ }