@pretty-chitty/core 2.0.0 → 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 (318) 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/ContextGalleryDisplay.d.ts.map +1 -1
  10. package/dist/components/ContextGalleryDisplay.js +1 -1
  11. package/dist/components/ContextGalleryDisplay.js.map +1 -1
  12. package/dist/components/DemoWrapper.d.ts +30 -2
  13. package/dist/components/DemoWrapper.d.ts.map +1 -1
  14. package/dist/components/DemoWrapper.js +79 -36
  15. package/dist/components/DemoWrapper.js.map +1 -1
  16. package/dist/components/FullScreenGalleryDisplay.d.ts.map +1 -1
  17. package/dist/components/FullScreenGalleryDisplay.js +2 -2
  18. package/dist/components/FullScreenGalleryDisplay.js.map +1 -1
  19. package/dist/components/Gallery/BuiltItem.d.ts +6 -2
  20. package/dist/components/Gallery/BuiltItem.d.ts.map +1 -1
  21. package/dist/components/Gallery/BuiltItem.js +28 -9
  22. package/dist/components/Gallery/BuiltItem.js.map +1 -1
  23. package/dist/components/Gallery/GalleryController.d.ts +18 -0
  24. package/dist/components/Gallery/GalleryController.d.ts.map +1 -1
  25. package/dist/components/Gallery/GalleryController.js +67 -0
  26. package/dist/components/Gallery/GalleryController.js.map +1 -1
  27. package/dist/components/Gallery/GalleryViewer.d.ts +6 -1
  28. package/dist/components/Gallery/GalleryViewer.d.ts.map +1 -1
  29. package/dist/components/Gallery/GalleryViewer.js +48 -10
  30. package/dist/components/Gallery/GalleryViewer.js.map +1 -1
  31. package/dist/components/Gallery/LayoutManager.d.ts +6 -0
  32. package/dist/components/Gallery/LayoutManager.d.ts.map +1 -1
  33. package/dist/components/Gallery/LayoutManager.js +23 -3
  34. package/dist/components/Gallery/LayoutManager.js.map +1 -1
  35. package/dist/components/Gallery/constants.d.ts +2 -0
  36. package/dist/components/Gallery/constants.d.ts.map +1 -1
  37. package/dist/components/Gallery/constants.js +2 -0
  38. package/dist/components/Gallery/constants.js.map +1 -1
  39. package/dist/components/Gallery/registry.d.ts +34 -0
  40. package/dist/components/Gallery/registry.d.ts.map +1 -0
  41. package/dist/components/Gallery/registry.js +17 -0
  42. package/dist/components/Gallery/registry.js.map +1 -0
  43. package/dist/components/GameDesigner.d.ts.map +1 -1
  44. package/dist/components/GameDesigner.js +42 -10
  45. package/dist/components/GameDesigner.js.map +1 -1
  46. package/dist/components/InlineGalleryDisplay.d.ts.map +1 -1
  47. package/dist/components/InlineGalleryDisplay.js +2 -2
  48. package/dist/components/InlineGalleryDisplay.js.map +1 -1
  49. package/dist/components/LiveButton.d.ts.map +1 -1
  50. package/dist/components/LiveButton.js +5 -2
  51. package/dist/components/LiveButton.js.map +1 -1
  52. package/dist/components/MatchViewer.d.ts +6 -1
  53. package/dist/components/MatchViewer.d.ts.map +1 -1
  54. package/dist/components/MatchViewer.js +9 -3
  55. package/dist/components/MatchViewer.js.map +1 -1
  56. package/dist/components/Panel/MultiPanel.d.ts.map +1 -1
  57. package/dist/components/Panel/MultiPanel.js +18 -0
  58. package/dist/components/Panel/MultiPanel.js.map +1 -1
  59. package/dist/components/Panel/PanelContents.d.ts.map +1 -1
  60. package/dist/components/Panel/PanelContents.js +92 -23
  61. package/dist/components/Panel/PanelContents.js.map +1 -1
  62. package/dist/components/Panel/PanelTabStack.d.ts.map +1 -1
  63. package/dist/components/Panel/PanelTabStack.js +1 -1
  64. package/dist/components/Panel/PanelTabStack.js.map +1 -1
  65. package/dist/components/PanelSpark.d.ts.map +1 -1
  66. package/dist/components/PanelSpark.js +3 -2
  67. package/dist/components/PanelSpark.js.map +1 -1
  68. package/dist/components/Playground.d.ts.map +1 -1
  69. package/dist/components/Playground.js +10 -4
  70. package/dist/components/Playground.js.map +1 -1
  71. package/dist/components/PromptControls.d.ts.map +1 -1
  72. package/dist/components/PromptControls.js +4 -2
  73. package/dist/components/PromptControls.js.map +1 -1
  74. package/dist/components/SparkLineChart.d.ts.map +1 -1
  75. package/dist/components/SparkLineChart.js +22 -26
  76. package/dist/components/SparkLineChart.js.map +1 -1
  77. package/dist/components/TimeControlBar.d.ts.map +1 -1
  78. package/dist/components/TimeControlBar.js +5 -3
  79. package/dist/components/TimeControlBar.js.map +1 -1
  80. package/dist/components/TokenizedMarkdown.d.ts +23 -0
  81. package/dist/components/TokenizedMarkdown.d.ts.map +1 -0
  82. package/dist/components/TokenizedMarkdown.js +144 -0
  83. package/dist/components/TokenizedMarkdown.js.map +1 -0
  84. package/dist/components/TokenizedMessage.d.ts +6 -0
  85. package/dist/components/TokenizedMessage.d.ts.map +1 -1
  86. package/dist/components/TokenizedMessage.js +20 -19
  87. package/dist/components/TokenizedMessage.js.map +1 -1
  88. package/dist/components/TopBarPlayers.d.ts.map +1 -1
  89. package/dist/components/TopBarPlayers.js +1 -1
  90. package/dist/components/TopBarPlayers.js.map +1 -1
  91. package/dist/components/Tutorial/BrowserNarration.d.ts +55 -0
  92. package/dist/components/Tutorial/BrowserNarration.d.ts.map +1 -0
  93. package/dist/components/Tutorial/BrowserNarration.js +240 -0
  94. package/dist/components/Tutorial/BrowserNarration.js.map +1 -0
  95. package/dist/components/Tutorial/TutorialBox.d.ts +26 -0
  96. package/dist/components/Tutorial/TutorialBox.d.ts.map +1 -0
  97. package/dist/components/Tutorial/TutorialBox.js +239 -0
  98. package/dist/components/Tutorial/TutorialBox.js.map +1 -0
  99. package/dist/components/Tutorial/TutorialDevPanel.d.ts +9 -0
  100. package/dist/components/Tutorial/TutorialDevPanel.d.ts.map +1 -0
  101. package/dist/components/Tutorial/TutorialDevPanel.js +92 -0
  102. package/dist/components/Tutorial/TutorialDevPanel.js.map +1 -0
  103. package/dist/components/Tutorial/TutorialOverlay.d.ts +7 -0
  104. package/dist/components/Tutorial/TutorialOverlay.d.ts.map +1 -0
  105. package/dist/components/Tutorial/TutorialOverlay.js +1132 -0
  106. package/dist/components/Tutorial/TutorialOverlay.js.map +1 -0
  107. package/dist/components/Tutorial/targetRects.d.ts +67 -0
  108. package/dist/components/Tutorial/targetRects.d.ts.map +1 -0
  109. package/dist/components/Tutorial/targetRects.js +241 -0
  110. package/dist/components/Tutorial/targetRects.js.map +1 -0
  111. package/dist/game/Chit.d.ts +7 -0
  112. package/dist/game/Chit.d.ts.map +1 -1
  113. package/dist/game/Chit.js +20 -5
  114. package/dist/game/Chit.js.map +1 -1
  115. package/dist/game/ClientTimeState.d.ts +14 -0
  116. package/dist/game/ClientTimeState.d.ts.map +1 -1
  117. package/dist/game/ClientTimeState.js +17 -0
  118. package/dist/game/ClientTimeState.js.map +1 -1
  119. package/dist/game/Game.d.ts +6 -0
  120. package/dist/game/Game.d.ts.map +1 -1
  121. package/dist/game/GameTheme.d.ts +3 -0
  122. package/dist/game/GameTheme.d.ts.map +1 -1
  123. package/dist/game/GameTheme.js +2 -0
  124. package/dist/game/GameTheme.js.map +1 -1
  125. package/dist/game/Match.d.ts +8 -2
  126. package/dist/game/Match.d.ts.map +1 -1
  127. package/dist/game/Match.js +4 -1
  128. package/dist/game/Match.js.map +1 -1
  129. package/dist/game/Pick.d.ts +2 -0
  130. package/dist/game/Pick.d.ts.map +1 -1
  131. package/dist/game/Pick.js +17 -1
  132. package/dist/game/Pick.js.map +1 -1
  133. package/dist/game/PlayerPromptStatusChit.d.ts +8 -0
  134. package/dist/game/PlayerPromptStatusChit.d.ts.map +1 -1
  135. package/dist/game/PlayerPromptStatusChit.js +5 -1
  136. package/dist/game/PlayerPromptStatusChit.js.map +1 -1
  137. package/dist/game/Prompt.d.ts +15 -0
  138. package/dist/game/Prompt.d.ts.map +1 -1
  139. package/dist/game/Prompt.js +16 -0
  140. package/dist/game/Prompt.js.map +1 -1
  141. package/dist/game/Turn.d.ts +15 -4
  142. package/dist/game/Turn.d.ts.map +1 -1
  143. package/dist/game/Turn.js +173 -60
  144. package/dist/game/Turn.js.map +1 -1
  145. package/dist/game/TurnState.d.ts +12 -1
  146. package/dist/game/TurnState.d.ts.map +1 -1
  147. package/dist/game/TurnState.js +15 -3
  148. package/dist/game/TurnState.js.map +1 -1
  149. package/dist/game/ai/AiClientPrompts.d.ts +20 -3
  150. package/dist/game/ai/AiClientPrompts.d.ts.map +1 -1
  151. package/dist/game/ai/AiClientPrompts.js +42 -6
  152. package/dist/game/ai/AiClientPrompts.js.map +1 -1
  153. package/dist/game/ai/AiPlayerView.js +2 -0
  154. package/dist/game/ai/AiPlayerView.js.map +1 -1
  155. package/dist/game/clientTransport/ClientPrompts.d.ts +20 -1
  156. package/dist/game/clientTransport/ClientPrompts.d.ts.map +1 -1
  157. package/dist/game/clientTransport/ClientPrompts.js +30 -1
  158. package/dist/game/clientTransport/ClientPrompts.js.map +1 -1
  159. package/dist/game/clientTransport/ClientTime.d.ts +13 -0
  160. package/dist/game/clientTransport/ClientTime.d.ts.map +1 -1
  161. package/dist/game/clientTransport/ClientTime.js +51 -11
  162. package/dist/game/clientTransport/ClientTime.js.map +1 -1
  163. package/dist/game/tutorial/TutorialController.d.ts +300 -0
  164. package/dist/game/tutorial/TutorialController.d.ts.map +1 -0
  165. package/dist/game/tutorial/TutorialController.js +1182 -0
  166. package/dist/game/tutorial/TutorialController.js.map +1 -0
  167. package/dist/game/tutorial/TutorialRuntime.d.ts +89 -0
  168. package/dist/game/tutorial/TutorialRuntime.d.ts.map +1 -0
  169. package/dist/game/tutorial/TutorialRuntime.js +261 -0
  170. package/dist/game/tutorial/TutorialRuntime.js.map +1 -0
  171. package/dist/game/tutorial/TutorialTheme.d.ts +28 -0
  172. package/dist/game/tutorial/TutorialTheme.d.ts.map +1 -0
  173. package/dist/game/tutorial/TutorialTheme.js +39 -0
  174. package/dist/game/tutorial/TutorialTheme.js.map +1 -0
  175. package/dist/game/tutorial/allowed.d.ts +2 -0
  176. package/dist/game/tutorial/allowed.d.ts.map +1 -0
  177. package/dist/game/tutorial/allowed.js +119 -0
  178. package/dist/game/tutorial/allowed.js.map +1 -0
  179. package/dist/game/tutorial/checks.d.ts +58 -0
  180. package/dist/game/tutorial/checks.d.ts.map +1 -0
  181. package/dist/game/tutorial/checks.js +144 -0
  182. package/dist/game/tutorial/checks.js.map +1 -0
  183. package/dist/game/tutorial/createDemoMatch.d.ts +47 -0
  184. package/dist/game/tutorial/createDemoMatch.d.ts.map +1 -0
  185. package/dist/game/tutorial/createDemoMatch.js +67 -0
  186. package/dist/game/tutorial/createDemoMatch.js.map +1 -0
  187. package/dist/game/tutorial/defineTutorial.d.ts +353 -0
  188. package/dist/game/tutorial/defineTutorial.d.ts.map +1 -0
  189. package/dist/game/tutorial/defineTutorial.js +86 -0
  190. package/dist/game/tutorial/defineTutorial.js.map +1 -0
  191. package/dist/game/tutorial/runTutorial.d.ts +63 -0
  192. package/dist/game/tutorial/runTutorial.d.ts.map +1 -0
  193. package/dist/game/tutorial/runTutorial.js +273 -0
  194. package/dist/game/tutorial/runTutorial.js.map +1 -0
  195. package/dist/hooks/usePanelNavigation.d.ts +28 -0
  196. package/dist/hooks/usePanelNavigation.d.ts.map +1 -0
  197. package/dist/hooks/usePanelNavigation.js +36 -0
  198. package/dist/hooks/usePanelNavigation.js.map +1 -0
  199. package/dist/hooks/useTimeController.d.ts +2 -1
  200. package/dist/hooks/useTimeController.d.ts.map +1 -1
  201. package/dist/hooks/useTimeController.js +6 -2
  202. package/dist/hooks/useTimeController.js.map +1 -1
  203. package/dist/hooks/useTutorial.d.ts +48 -0
  204. package/dist/hooks/useTutorial.d.ts.map +1 -0
  205. package/dist/hooks/useTutorial.js +16 -0
  206. package/dist/hooks/useTutorial.js.map +1 -0
  207. package/dist/index.d.ts +36 -0
  208. package/dist/index.d.ts.map +1 -1
  209. package/dist/index.html +12 -0
  210. package/dist/index.js +19 -2
  211. package/dist/index.js.map +1 -1
  212. package/dist/main.0792d734cde2c688d5f7.hot-update.js +16991 -0
  213. package/dist/main.0792d734cde2c688d5f7.hot-update.js.map +1 -0
  214. package/dist/main.0792d734cde2c688d5f7.hot-update.json +1 -0
  215. package/dist/pretty-chitty.js +204513 -0
  216. package/dist/pretty-chitty.js.map +1 -0
  217. package/dist/rendering/CameraWrapperPerspective.d.ts +5 -0
  218. package/dist/rendering/CameraWrapperPerspective.d.ts.map +1 -1
  219. package/dist/rendering/CameraWrapperPerspective.js +16 -0
  220. package/dist/rendering/CameraWrapperPerspective.js.map +1 -1
  221. package/dist/rendering/ChitGalleryItemInstance.d.ts +1 -0
  222. package/dist/rendering/ChitGalleryItemInstance.d.ts.map +1 -1
  223. package/dist/rendering/ChitGalleryItemInstance.js +12 -0
  224. package/dist/rendering/ChitGalleryItemInstance.js.map +1 -1
  225. package/dist/rendering/ChitRenderInstance.d.ts +9 -1
  226. package/dist/rendering/ChitRenderInstance.d.ts.map +1 -1
  227. package/dist/rendering/ChitRenderInstance.js +28 -0
  228. package/dist/rendering/ChitRenderInstance.js.map +1 -1
  229. package/dist/rendering/RootChitRenderInstance.d.ts +2 -0
  230. package/dist/rendering/RootChitRenderInstance.d.ts.map +1 -1
  231. package/dist/rendering/RootChitRenderInstance.js +29 -0
  232. package/dist/rendering/RootChitRenderInstance.js.map +1 -1
  233. package/dist/utilities/Annotations.d.ts +15 -0
  234. package/dist/utilities/Annotations.d.ts.map +1 -1
  235. package/dist/utilities/Annotations.js +31 -7
  236. package/dist/utilities/Annotations.js.map +1 -1
  237. package/dist/utilities/CanvasStack/CanvasStack.d.ts +2 -0
  238. package/dist/utilities/CanvasStack/CanvasStack.d.ts.map +1 -1
  239. package/dist/utilities/CanvasStack/CanvasStack.js +4 -0
  240. package/dist/utilities/CanvasStack/CanvasStack.js.map +1 -1
  241. package/dist/utilities/TokenizedText.d.ts +6 -0
  242. package/dist/utilities/TokenizedText.d.ts.map +1 -1
  243. package/dist/utilities/TokenizedText.js.map +1 -1
  244. package/dist/utilities/zIndex.d.ts +1 -0
  245. package/dist/utilities/zIndex.d.ts.map +1 -1
  246. package/dist/utilities/zIndex.js +1 -0
  247. package/dist/utilities/zIndex.js.map +1 -1
  248. package/package.json +3 -2
  249. package/src/library/components/ActionLogDisplay.tsx +1 -0
  250. package/src/library/components/BottomBarButton.tsx +5 -0
  251. package/src/library/components/ContextGalleryDisplay.tsx +2 -0
  252. package/src/library/components/DemoWrapper.tsx +147 -44
  253. package/src/library/components/FullScreenGalleryDisplay.tsx +3 -0
  254. package/src/library/components/Gallery/BuiltItem.ts +30 -9
  255. package/src/library/components/Gallery/GalleryController.ts +72 -1
  256. package/src/library/components/Gallery/GalleryViewer.tsx +54 -10
  257. package/src/library/components/Gallery/LayoutManager.ts +30 -6
  258. package/src/library/components/Gallery/constants.ts +2 -0
  259. package/src/library/components/Gallery/registry.ts +44 -0
  260. package/src/library/components/GameDesigner.tsx +121 -12
  261. package/src/library/components/InlineGalleryDisplay.tsx +5 -0
  262. package/src/library/components/LiveButton.tsx +8 -5
  263. package/src/library/components/MatchViewer.tsx +14 -3
  264. package/src/library/components/Panel/MultiPanel.tsx +21 -0
  265. package/src/library/components/Panel/PanelContents.tsx +70 -1
  266. package/src/library/components/Panel/PanelTabStack.tsx +1 -0
  267. package/src/library/components/PanelSpark.tsx +9 -4
  268. package/src/library/components/Playground.tsx +48 -21
  269. package/src/library/components/PromptControls.tsx +7 -3
  270. package/src/library/components/SparkLineChart.tsx +23 -27
  271. package/src/library/components/TimeControlBar.tsx +5 -3
  272. package/src/library/components/TokenizedMarkdown.tsx +224 -0
  273. package/src/library/components/TokenizedMessage.tsx +28 -32
  274. package/src/library/components/TopBarPlayers.tsx +12 -9
  275. package/src/library/components/Tutorial/BrowserNarration.ts +233 -0
  276. package/src/library/components/Tutorial/TutorialBox.tsx +506 -0
  277. package/src/library/components/Tutorial/TutorialDevPanel.tsx +297 -0
  278. package/src/library/components/Tutorial/TutorialOverlay.tsx +1301 -0
  279. package/src/library/components/Tutorial/targetRects.ts +273 -0
  280. package/src/library/game/Chit.ts +21 -5
  281. package/src/library/game/ClientTimeState.ts +18 -0
  282. package/src/library/game/Game.ts +7 -0
  283. package/src/library/game/GameTheme.ts +4 -0
  284. package/src/library/game/Match.ts +12 -2
  285. package/src/library/game/Pick.ts +16 -1
  286. package/src/library/game/PlayerPromptStatusChit.ts +5 -1
  287. package/src/library/game/Prompt.ts +20 -0
  288. package/src/library/game/Turn.ts +179 -61
  289. package/src/library/game/TurnState.ts +26 -3
  290. package/src/library/game/ai/AI_GUIDE.md +10 -0
  291. package/src/library/game/ai/AiClientPrompts.ts +60 -11
  292. package/src/library/game/ai/AiPlayerView.ts +2 -0
  293. package/src/library/game/clientTransport/ClientPrompts.ts +31 -1
  294. package/src/library/game/clientTransport/ClientTime.ts +54 -13
  295. package/src/library/game/serialize.test.ts +275 -0
  296. package/src/library/game/tutorial/TUTORIAL_GUIDE.md +411 -0
  297. package/src/library/game/tutorial/TutorialController.test.ts +731 -0
  298. package/src/library/game/tutorial/TutorialController.ts +1286 -0
  299. package/src/library/game/tutorial/TutorialRuntime.ts +311 -0
  300. package/src/library/game/tutorial/TutorialTheme.ts +67 -0
  301. package/src/library/game/tutorial/allowed.ts +145 -0
  302. package/src/library/game/tutorial/checks.ts +186 -0
  303. package/src/library/game/tutorial/createDemoMatch.ts +115 -0
  304. package/src/library/game/tutorial/defineTutorial.ts +414 -0
  305. package/src/library/game/tutorial/runTutorial.ts +331 -0
  306. package/src/library/game/undo.test.ts +282 -0
  307. package/src/library/hooks/usePanelNavigation.tsx +65 -0
  308. package/src/library/hooks/useTimeController.tsx +6 -2
  309. package/src/library/hooks/useTutorial.tsx +76 -0
  310. package/src/library/index.ts +57 -2
  311. package/src/library/rendering/CameraWrapperPerspective.ts +17 -0
  312. package/src/library/rendering/ChitGalleryItemInstance.ts +12 -0
  313. package/src/library/rendering/ChitRenderInstance.ts +34 -0
  314. package/src/library/rendering/RootChitRenderInstance.ts +30 -1
  315. package/src/library/utilities/Annotations.ts +35 -7
  316. package/src/library/utilities/CanvasStack/CanvasStack.ts +6 -1
  317. package/src/library/utilities/TokenizedText.ts +6 -0
  318. package/src/library/utilities/zIndex.ts +1 -0
@@ -0,0 +1,1182 @@
1
+ import { EventChannel } from "../../utilities/EventChannel";
2
+ import { allowsUi, isAllowed, scriptedAnswer, shapeOfPromptAction } from "./allowed";
3
+ import { selectChits, splitSentences, } from "./defineTutorial";
4
+ const DEFAULT_HINT_AFTER = 8;
5
+ /**
6
+ * Runs a tutorial script against a game the player can see: steps, narration and cues, "do it" checks,
7
+ * hints and the end-of-tutorial handoff. UI-free, so it runs headlessly in tests; the overlay reads
8
+ * its channels and calls `next`/`back`/`skip`.
9
+ *
10
+ * @group Tutorials
11
+ */
12
+ /** The pause between steps while fast-forwarding */
13
+ const FAST_BEAT_MS = 60;
14
+ /** How long the board must stay settled before a fast-forward moves on */
15
+ const FAST_SETTLE_MS = 150;
16
+ /** A fast-forward stuck this long on one step stops there */
17
+ const FAST_GIVE_UP_MS = 20000;
18
+ export class TutorialController {
19
+ constructor(options) {
20
+ this.spec = undefined;
21
+ this.index = new EventChannel(-1);
22
+ this.status = new EventChannel("idle");
23
+ this.focus = new EventChannel([]);
24
+ this.box = new EventChannel(undefined);
25
+ this.hint = new EventChannel(undefined);
26
+ /** Index of the sentence being narrated, for emphasis */
27
+ this.sentence = new EventChannel(-1);
28
+ this.narrationTime = new EventChannel(0);
29
+ this.narrating = new EventChannel(false);
30
+ /**
31
+ * The player stopped the flow (Pause, or Back): narration holds where it is, nothing advances by
32
+ * itself, the bots hold their moves, and moving between steps with Back/Next stays silent until
33
+ * `play()`. A "do it" step can still be completed while paused; doing it counts as resuming.
34
+ */
35
+ this.paused = new EventChannel(false);
36
+ /** A Back is putting the game back; input and Next are held until it lands */
37
+ this.rewinding = new EventChannel(false);
38
+ this.muted = undefined;
39
+ /** Narration speed (1 = normal) */
40
+ this.rate = undefined;
41
+ /** Result of the current step's `waitFor` at the last evaluation */
42
+ this.check = new EventChannel(undefined);
43
+ /**
44
+ * True while looking at a step behind the furthest one reached (after Back). A reviewed step
45
+ * narrates and highlights but does not check, pause the bots or auto-advance; Next walks forward
46
+ * until the live step resumes with its state intact.
47
+ */
48
+ this.reviewing = new EventChannel(false);
49
+ /** Index of the furthest step reached live */
50
+ this.frontier = new EventChannel(-1);
51
+ /** Bumps each time the player tries a move the current step does not allow */
52
+ this.blocked = new EventChannel(0);
53
+ /** The clock the script is holding the board at, or undefined while the board plays freely */
54
+ this.timelineHold = new EventChannel(undefined);
55
+ /** The clock the board shows, for the workbench (counting moments for `{ advance: n }`) */
56
+ this.boardClock = new EventChannel(0);
57
+ /** The step a fast-forward is playing through to, or undefined */
58
+ this.fastForwardTarget = new EventChannel(undefined);
59
+ this.view = undefined;
60
+ this.runtime = undefined;
61
+ this.narration = undefined;
62
+ this.ai = undefined;
63
+ this.history = undefined;
64
+ this.onEvent = undefined;
65
+ this.satisfiedDelayMs = undefined;
66
+ this.autoAdvanceDelayMs = undefined;
67
+ this.readingSpeed = undefined;
68
+ this._setTimeout = undefined;
69
+ this._clearTimeout = undefined;
70
+ this._now = undefined;
71
+ this.unsubs = [];
72
+ this.stepUnsubs = [];
73
+ this.stepStartClock = 0;
74
+ this.recentLog = [];
75
+ this.lastLog = undefined;
76
+ this.aiEnabledBeforePause = undefined;
77
+ this.satisfiedTimer = undefined;
78
+ /** A step entered by acting ahead narrates after all if its check has not passed by then */
79
+ this.aheadTimer = undefined;
80
+ this.readingActive = false;
81
+ this.advanceTimer = undefined;
82
+ this.hintTimer = undefined;
83
+ this.readingTimer = undefined;
84
+ this.readingStartedAt = 0;
85
+ this.readingPausedAt = undefined;
86
+ this.appliedCues = new Set();
87
+ this.sentences = [];
88
+ this.disposed = false;
89
+ this.narrationEnded = false;
90
+ /** Steps whose `waitFor` baseline was taken; a live re-entry (after a review) keeps it */
91
+ this.baselined = new Set();
92
+ this.began = false;
93
+ this.rewindTarget = undefined;
94
+ this.rewindRunning = false;
95
+ /** A "do it" step whose check passed while it was still narrating */
96
+ this.advanceWhenNarrationEnds = false;
97
+ /** Whether a gallery the script opened may still be showing (Back closes it) */
98
+ this.scriptOpenedGallery = false;
99
+ this.fastTimer = undefined;
100
+ this.fastWatchdog = undefined;
101
+ // ---- poses -------------------------------------------------------------------------------------
102
+ /** Chits the script changed in the player's view, with the step that changed them */
103
+ this.posed = new Map();
104
+ // ---- the board's timeline ----------------------------------------------------------------------
105
+ /** A `{ until }` command still playing toward its moment, and where its log lines start */
106
+ this.timelineUntil = undefined;
107
+ this.spec = options.spec;
108
+ this.view = options.view;
109
+ this.runtime = options.runtime;
110
+ this.narration = options.narration;
111
+ this.ai = options.ai;
112
+ this.history = options.history;
113
+ this.onEvent = options.onEvent;
114
+ this.satisfiedDelayMs = options.satisfiedDelayMs ?? 900;
115
+ this.autoAdvanceDelayMs = options.autoAdvanceDelayMs ?? 700;
116
+ this.readingSpeed = options.readingSpeed ?? 3;
117
+ this.muted = new EventChannel(options.muted ?? false);
118
+ this.rate = new EventChannel(options.rate ?? 1);
119
+ this.narration?.setRate?.(this.rate.value);
120
+ this._setTimeout = options.setTimeout ?? ((cb, ms) => setTimeout(cb, ms));
121
+ this._clearTimeout = options.clearTimeout ?? ((h) => clearTimeout(h));
122
+ this._now = options.now ?? (() => Date.now());
123
+ // Guard from the start: before Start is pressed the board is a picture, not a game
124
+ this.view.setGuard?.((action) => {
125
+ // The game's Undo is the tutorial's Back while the tutorial runs
126
+ if (action.type === "undo" && this.status.value !== "done") {
127
+ this.back();
128
+ return "handled";
129
+ }
130
+ if (this.allows(action))
131
+ return true;
132
+ // A move the next "do it" step asks for counts as moving on to that step
133
+ const ahead = this.aheadFor(action);
134
+ if (ahead === undefined)
135
+ return false;
136
+ this.actAhead(ahead);
137
+ return true;
138
+ });
139
+ const unsubBlocked = this.view.onBlocked?.(() => {
140
+ this.blocked.value = this.blocked.value + 1;
141
+ });
142
+ if (unsubBlocked)
143
+ this.unsubs.push(unsubBlocked);
144
+ // The first recording loads while the start card is up
145
+ this.preloadStep(0);
146
+ }
147
+ /** Lets the narration player start loading step `index`'s recording ahead of time */
148
+ preloadStep(index) {
149
+ const audio = this.spec.steps[index]?.audio;
150
+ if (audio && audio !== "tts")
151
+ this.narration?.preload?.(audio);
152
+ }
153
+ get step() {
154
+ return this.spec.steps[this.index.value];
155
+ }
156
+ get steps() {
157
+ return this.spec.steps;
158
+ }
159
+ get isLast() {
160
+ return this.index.value >= this.spec.steps.length - 1;
161
+ }
162
+ /** Whether Next is allowed right now */
163
+ get canAdvance() {
164
+ if (this.rewinding.value)
165
+ return false;
166
+ if (this.reviewing.value)
167
+ return true;
168
+ const s = this.status.value;
169
+ return s === "narrating" || s === "satisfied" || (s === "waiting" && this.check.value === true);
170
+ }
171
+ /** Builds the context the checks and callbacks see. Undefined until the board exists. */
172
+ context() {
173
+ const root = this.view.root();
174
+ const me = this.view.me();
175
+ if (!root || !me)
176
+ return undefined;
177
+ return {
178
+ root,
179
+ me,
180
+ prompt: this.view.prompt(),
181
+ clock: this.view.clock(),
182
+ find: (id) => this.view.find(id),
183
+ stepStartClock: this.stepStartClock,
184
+ recentLog: this.recentLog,
185
+ galleries: this.view.galleries?.() ?? [],
186
+ };
187
+ }
188
+ /** Starts at the first step (or the given one). Call once the board has loaded. */
189
+ start(at = 0, options = {}) {
190
+ if (!this.begin(options))
191
+ return;
192
+ this.enter(at);
193
+ }
194
+ /** Starts watching the board (once): what `start` does before entering its first step */
195
+ begin(options = {}) {
196
+ if (this.disposed || this.began)
197
+ return false;
198
+ this.began = true;
199
+ this.paused.value = !!options.paused;
200
+ this.unsubs.push(this.view.onChange(() => this.onViewChange()));
201
+ this.onEvent?.({ type: "started" });
202
+ this.lastLog = this.view.latestLog();
203
+ return true;
204
+ }
205
+ next() {
206
+ if (this.disposed || this.index.value < 0 || this.rewinding.value)
207
+ return;
208
+ if (!this.canAdvance)
209
+ return;
210
+ if (this.isLast) {
211
+ this.finish(this.step?.end ?? "continue");
212
+ }
213
+ else {
214
+ this.enter(this.index.value + 1);
215
+ }
216
+ }
217
+ /**
218
+ * Previous step. With a history this rewinds the game to that step; otherwise it reviews its text.
219
+ * Either way the tutorial pauses there until the player presses Play, so pressing Back again goes
220
+ * further back instead of racing the narration. Presses during a rewind queue up.
221
+ */
222
+ back() {
223
+ if (this.disposed || this.index.value <= 0)
224
+ return;
225
+ const index = this.index.value - 1;
226
+ this.holdFlow();
227
+ if (this.history) {
228
+ this.requestRewind(index);
229
+ return;
230
+ }
231
+ this.enter(index);
232
+ }
233
+ /** Show the target step straight away and put the game back to it; presses during a rewind queue up */
234
+ requestRewind(index) {
235
+ if (!this.rewinding.value) {
236
+ this.leaveStep();
237
+ // the board is going back: a gallery the script opened would show the wrong moment
238
+ if (this.scriptOpenedGallery)
239
+ this.applyGallery("close");
240
+ // and so would a chit the script changed; the step landed on poses its own again
241
+ this.releasePoses(true);
242
+ // the rewind waits for the board to catch up with the rerun; the step it lands on holds again
243
+ this.releaseTimeline();
244
+ this.rewinding.value = true;
245
+ // bots wait while the board goes back; entering the step decides whether they play
246
+ this.applyAi();
247
+ }
248
+ this.rewindTarget = index;
249
+ this.index.value = index;
250
+ this.publishUndo();
251
+ this.reviewing.value = false;
252
+ this.focus.value = [];
253
+ this.hint.value = undefined;
254
+ this.check.value = undefined;
255
+ this.narrating.value = false;
256
+ this.sentence.value = -1;
257
+ if (!this.rewindRunning)
258
+ void this.runRewinds();
259
+ }
260
+ async runRewinds() {
261
+ this.rewindRunning = true;
262
+ try {
263
+ while (this.rewindTarget !== undefined && !this.disposed) {
264
+ const index = this.rewindTarget;
265
+ this.rewindTarget = undefined;
266
+ let ok = false;
267
+ try {
268
+ ok = (await this.history?.restore(this.spec.steps[index].id, index)) ?? false;
269
+ }
270
+ catch (e) {
271
+ console.error(`[tutorial ${this.spec.id}] rewind to step ${index + 1} failed`, e);
272
+ }
273
+ if (this.disposed)
274
+ return;
275
+ if (this.rewindTarget !== undefined)
276
+ continue; // Back was pressed again meanwhile
277
+ if (ok) {
278
+ // The game is back where this step started: it is the live step again, and it and every
279
+ // later step will take fresh baselines when entered
280
+ this.frontier.value = index;
281
+ this.spec.steps.slice(index).forEach((s) => this.baselined.delete(s.id));
282
+ }
283
+ this.rewinding.value = false;
284
+ this.enter(index);
285
+ }
286
+ }
287
+ finally {
288
+ this.rewindRunning = false;
289
+ if (this.rewinding.value && this.rewindTarget === undefined && !this.disposed) {
290
+ this.rewinding.value = false;
291
+ }
292
+ }
293
+ }
294
+ /** Whether Back rewinds the game (true) or only reviews text (false) */
295
+ get rewinds() {
296
+ return !!this.history;
297
+ }
298
+ /** Jump to any step (the dev panel). Forward jumps become the live step; the game is left as it is. */
299
+ jumpTo(index) {
300
+ if (this.disposed || index < 0 || index >= this.spec.steps.length)
301
+ return;
302
+ this.stopFastForward();
303
+ if (index < this.frontier.value && this.history) {
304
+ this.holdFlow();
305
+ this.requestRewind(index);
306
+ return;
307
+ }
308
+ if (index > this.frontier.value)
309
+ this.frontier.value = index;
310
+ this.enter(index);
311
+ }
312
+ /**
313
+ * Go straight to any step with the game as it was when that step went live, and play on from there
314
+ * (the dev panel's step list). A step not played yet is played headlessly first (see `history`),
315
+ * so this works before Start too. Without a game history it is `jumpTo`.
316
+ */
317
+ skipTo(index) {
318
+ if (this.disposed || index < 0 || index >= this.spec.steps.length || this.status.value === "done")
319
+ return;
320
+ if (!this.history) {
321
+ if (!this.began)
322
+ this.start(index);
323
+ else
324
+ this.jumpTo(index);
325
+ return;
326
+ }
327
+ this.begin();
328
+ this.stopFastForward();
329
+ this.paused.value = false;
330
+ this.requestRewind(index);
331
+ }
332
+ /** Leave a review and return to the live step */
333
+ resume() {
334
+ if (this.reviewing.value)
335
+ this.enter(this.frontier.value);
336
+ }
337
+ skip() {
338
+ if (this.disposed)
339
+ return;
340
+ this.onEvent?.({ type: "skipped" });
341
+ this.finish("continue", true);
342
+ }
343
+ /** While the tutorial runs, the game's Undo button (shown as usual) does the tutorial's Back */
344
+ publishUndo() {
345
+ if (this.disposed || this.status.value === "done") {
346
+ this.view.setUndo?.(undefined);
347
+ return;
348
+ }
349
+ this.view.setUndo?.({ undo: () => this.back() });
350
+ }
351
+ /** Stop the flow: the narration holds where it is and nothing advances until `play()`. */
352
+ pause() {
353
+ if (this.disposed || this.status.value === "done" || this.paused.value)
354
+ return;
355
+ this.holdFlow();
356
+ // A step that was only finishing its narration moves on when the player presses Play again
357
+ if (this.narration?.playing && !this.narration.paused)
358
+ this.narration.pause();
359
+ if (this.readingActive && this.readingPausedAt === undefined)
360
+ this.readingPausedAt = this._now();
361
+ this.narrating.value = false;
362
+ }
363
+ /** Resume: continue a held narration, or play the step's narration from the top. */
364
+ play() {
365
+ if (this.disposed || this.status.value === "done" || !this.step)
366
+ return;
367
+ this.paused.value = false;
368
+ this.applyAi();
369
+ if (this.narration?.paused) {
370
+ this.narration.resume();
371
+ this.narrating.value = true;
372
+ return;
373
+ }
374
+ if (this.readingActive && this.readingPausedAt !== undefined) {
375
+ this.readingStartedAt += this._now() - this.readingPausedAt;
376
+ this.readingPausedAt = undefined;
377
+ this.narrating.value = true;
378
+ return;
379
+ }
380
+ this.startNarration();
381
+ }
382
+ /** The box's play/pause button */
383
+ toggleNarration() {
384
+ if (this.paused.value || !this.narrating.value)
385
+ this.play();
386
+ else
387
+ this.pause();
388
+ }
389
+ holdFlow() {
390
+ this.stopFastForward();
391
+ this.paused.value = true;
392
+ this._clearTimeout(this.advanceTimer);
393
+ this.advanceTimer = undefined;
394
+ this.applyAi();
395
+ }
396
+ /**
397
+ * Whether the bots may move: not while the flow is held (paused or going back), and not during a
398
+ * live step with `pauseAi`. Otherwise they play.
399
+ */
400
+ applyAi() {
401
+ if (!this.ai || this.status.value === "done")
402
+ return;
403
+ const step = this.step;
404
+ const hold = this.paused.value || this.rewinding.value || (!!step?.pauseAi && !this.reviewing.value);
405
+ if (hold) {
406
+ if (this.aiEnabledBeforePause === undefined)
407
+ this.aiEnabledBeforePause = this.ai.enabled;
408
+ this.ai.enabled = false;
409
+ }
410
+ else {
411
+ this.restoreAi();
412
+ }
413
+ }
414
+ /** Narration for a step just entered: plays unless the flow is held, then it only shows the opening cues */
415
+ beginNarration() {
416
+ if (this.paused.value) {
417
+ this.narrating.value = false;
418
+ this.appliedCues = new Set();
419
+ this.applyCuesAt(0);
420
+ return;
421
+ }
422
+ this.startNarration();
423
+ }
424
+ /** Speeds the narration up or down, from where it is; the reading clock follows */
425
+ setRate(rate) {
426
+ if (!(rate > 0) || rate === this.rate.value)
427
+ return;
428
+ if (this.readingActive) {
429
+ // keep the reading clock's position, change only how fast it moves from here
430
+ const at = this.readingPausedAt ?? this._now();
431
+ const t = ((at - this.readingStartedAt) / 1000) * this.rate.value;
432
+ this.readingStartedAt = at - (t * 1000) / rate;
433
+ }
434
+ this.rate.value = rate;
435
+ this.narration?.setRate?.(rate);
436
+ }
437
+ setMuted(muted) {
438
+ if (this.muted.value === muted)
439
+ return;
440
+ this.muted.value = muted;
441
+ this.narration?.stop();
442
+ this.narrating.value = false;
443
+ // Re-run the step's narration/clock from the top so cues stay consistent
444
+ if (this.step && this.status.value !== "done") {
445
+ this.beginNarration();
446
+ }
447
+ }
448
+ dispose() {
449
+ this.disposed = true;
450
+ this.stopFastForward();
451
+ this.leaveStep();
452
+ this.releasePoses(true);
453
+ this.releaseTimeline();
454
+ this.view.setGuard?.(undefined);
455
+ this.view.setUndo?.(undefined);
456
+ this.unsubs.forEach((u) => u());
457
+ this.unsubs = [];
458
+ this.narration?.stop();
459
+ this.restoreAi();
460
+ }
461
+ // ---- what the player may do ---------------------------------------------------------------------
462
+ /**
463
+ * Whether the game should accept this action right now. Only a live "do it" step that is still
464
+ * waiting lets anything through, and then only what it lists in `allow` (the game's Undo never
465
+ * gets here: it is the tutorial's Back). Nothing is allowed before it starts; once it is over
466
+ * everything is allowed again.
467
+ */
468
+ allows(action) {
469
+ if (this.status.value === "done")
470
+ return true;
471
+ if (this.rewinding.value)
472
+ return false;
473
+ const step = this.step;
474
+ if (!step || this.reviewing.value || this.status.value !== "waiting")
475
+ return false;
476
+ if (action.type === "undo")
477
+ return false; // handled as Back before this is asked
478
+ const move = shapeOfPromptAction(action);
479
+ if (!move)
480
+ return false;
481
+ return isAllowed(step.allow, move, this.view.root(), this.view.me());
482
+ }
483
+ /**
484
+ * The "do it" step the player may act ahead into: the first later step that waits for something,
485
+ * reached only through steps that just talk. Only while the live step is talking (or already done).
486
+ */
487
+ aheadStep() {
488
+ if (this.status.value === "done" || this.rewinding.value || this.reviewing.value)
489
+ return undefined;
490
+ if (this.status.value !== "narrating" && this.status.value !== "satisfied")
491
+ return undefined;
492
+ for (let i = this.index.value + 1; i < this.spec.steps.length; i++) {
493
+ if (this.spec.steps[i].waitFor)
494
+ return i;
495
+ }
496
+ return undefined;
497
+ }
498
+ /** The step a game move acts ahead into, if the next "do it" step allows it */
499
+ aheadFor(action) {
500
+ if (action.type === "undo")
501
+ return undefined;
502
+ const ahead = this.aheadStep();
503
+ if (ahead === undefined)
504
+ return undefined;
505
+ const move = shapeOfPromptAction(action);
506
+ if (!move)
507
+ return undefined;
508
+ return isAllowed(this.spec.steps[ahead].allow, move, this.view.root(), this.view.me()) ? ahead : undefined;
509
+ }
510
+ /**
511
+ * The player used a UI control (by its `data-tutorial-target`). If the next "do it" step lists it in
512
+ * `allow`, that counts as moving on to that step, as a game move it allows does. Call it before the
513
+ * control acts, so the step's check takes its baseline from the board as it was.
514
+ */
515
+ usedUi(name) {
516
+ if (this.disposed)
517
+ return;
518
+ const ahead = this.aheadStep();
519
+ if (ahead !== undefined && allowsUi(this.spec.steps[ahead].allow, name))
520
+ this.actAhead(ahead);
521
+ }
522
+ /**
523
+ * The player did what a later "do it" step asks for while an earlier step was still talking: move
524
+ * straight on to that step. The steps in between count as seen (snapshots for Back, their hooks and
525
+ * events), and the step itself stays quiet, since it would only ask for what was just done; it moves
526
+ * on after the usual short beat once its check passes, and narrates as usual if the check does not.
527
+ */
528
+ actAhead(index) {
529
+ this.leaveStep();
530
+ const ctx = this.context();
531
+ for (let i = this.index.value + 1; i < index; i++) {
532
+ const step = this.spec.steps[i];
533
+ if (i > this.frontier.value)
534
+ this.frontier.value = i;
535
+ if (this.markSeen(step))
536
+ this.baselined.add(step.id);
537
+ if (ctx) {
538
+ step.onEnter?.(ctx);
539
+ step.onExit?.(ctx);
540
+ }
541
+ this.onEvent?.({ type: "step", stepId: step.id, index: i });
542
+ }
543
+ // Acting is as explicit as pressing Play
544
+ this.paused.value = false;
545
+ this.enter(index, { ahead: true });
546
+ }
547
+ /** First visit to a live step: its snapshot for Back and the baselines its check measures from */
548
+ markSeen(step) {
549
+ if (this.baselined.has(step.id))
550
+ return false;
551
+ this.stepStartClock = this.view.clock();
552
+ this.recentLog = [];
553
+ this.lastLog = this.view.latestLog();
554
+ this.history?.save(step.id);
555
+ return true;
556
+ }
557
+ // ---- steps -------------------------------------------------------------------------------------
558
+ /** `ahead`: entered by acting ahead (see `actAhead`), after the previous step was already left */
559
+ enter(index, options = {}) {
560
+ if (!options.ahead)
561
+ this.leaveStep();
562
+ // A fast-forward ends on its step, which then plays as usual
563
+ if (this.fastForwardTarget.value !== undefined && index >= this.fastForwardTarget.value)
564
+ this.stopFastForward();
565
+ const step = this.spec.steps[index];
566
+ if (!step)
567
+ return;
568
+ const review = index < this.frontier.value;
569
+ if (!review && index > this.frontier.value)
570
+ this.frontier.value = index;
571
+ this.index.value = index;
572
+ this.reviewing.value = review;
573
+ this.hint.value = undefined;
574
+ this.check.value = undefined;
575
+ this.appliedCues = new Set();
576
+ this.sentences = splitSentences(step.text);
577
+ this.sentence.value = -1;
578
+ this.narrationTime.value = 0;
579
+ if (step.box) {
580
+ this.box.value = step.box.anchor === "keep" ? this.box.value : step.box;
581
+ }
582
+ this.focus.value = step.focus ?? [];
583
+ if (step.gallery)
584
+ this.applyGallery(step.gallery);
585
+ if (step.pose)
586
+ this.applyPoses(step.pose);
587
+ this.releasePoses(false);
588
+ if (review) {
589
+ // Looking back: narrate and highlight, but leave the game, the bots and the checks alone
590
+ this.status.value = "narrating";
591
+ this.beginNarration();
592
+ this.publishUndo();
593
+ return;
594
+ }
595
+ this.runtime && (this.runtime.activeStep.value = step.id);
596
+ const firstTime = this.markSeen(step);
597
+ if (step.timeline)
598
+ this.applyTimeline(step.timeline);
599
+ if (step.waitFor && this.timelineHold.value !== undefined && !step.timeline) {
600
+ console.warn(`[tutorial ${this.spec.id}] step "${step.id}" waits with the board's timeline held at clock ` +
601
+ `${this.timelineHold.value}; if it needs the board to catch up, give it timeline: "play"`);
602
+ }
603
+ this.applyAi();
604
+ const ctx = this.context();
605
+ if (ctx) {
606
+ if (firstTime) {
607
+ step.waitFor?.reset?.(ctx);
608
+ this.baselined.add(step.id);
609
+ }
610
+ step.onEnter?.(ctx);
611
+ }
612
+ this.status.value = step.waitFor ? "waiting" : "narrating";
613
+ this.onEvent?.({ type: "step", stepId: step.id, index });
614
+ if (this.fastForwardTarget.value !== undefined) {
615
+ // Passing through: no narration, but the galleries end up as the cues would leave them
616
+ this.narrating.value = false;
617
+ this.sentence.value = -1;
618
+ step.cues?.forEach((cue) => cue.gallery && this.applyGallery(cue.gallery));
619
+ this.scheduleFastBeat();
620
+ }
621
+ else if (options.ahead) {
622
+ // The move that brought us here has not landed yet. Once it does the check passes and the step
623
+ // moves on; if it does not pass soon after, narrate after all.
624
+ this.narrating.value = false;
625
+ this.sentence.value = -1;
626
+ this.aheadTimer = this._setTimeout(() => {
627
+ this.aheadTimer = undefined;
628
+ if (this.step === step && this.status.value === "waiting")
629
+ this.beginNarration();
630
+ }, this.satisfiedDelayMs);
631
+ }
632
+ else {
633
+ this.beginNarration();
634
+ }
635
+ this.evaluate();
636
+ if (step.waitFor) {
637
+ const after = typeof step.hint === "object" ? step.hint.after : DEFAULT_HINT_AFTER;
638
+ this.hintTimer = this._setTimeout(() => this.showHint(), after * 1000);
639
+ }
640
+ this.publishUndo();
641
+ }
642
+ leaveStep() {
643
+ const step = this.step;
644
+ if (step && !this.reviewing.value) {
645
+ const ctx = this.context();
646
+ if (ctx)
647
+ step.onExit?.(ctx);
648
+ }
649
+ this.stepUnsubs.forEach((u) => u());
650
+ this.stepUnsubs = [];
651
+ this._clearTimeout(this.satisfiedTimer);
652
+ this._clearTimeout(this.advanceTimer);
653
+ this._clearTimeout(this.hintTimer);
654
+ this._clearTimeout(this.readingTimer);
655
+ this._clearTimeout(this.aheadTimer);
656
+ this.satisfiedTimer = this.advanceTimer = this.hintTimer = this.readingTimer = this.aheadTimer = undefined;
657
+ this.advanceWhenNarrationEnds = false;
658
+ this.readingActive = false;
659
+ this.readingPausedAt = undefined;
660
+ this.narration?.stop();
661
+ this.narrating.value = false;
662
+ }
663
+ restoreAi() {
664
+ if (this.ai && this.aiEnabledBeforePause !== undefined) {
665
+ this.ai.enabled = this.aiEnabledBeforePause;
666
+ this.aiEnabledBeforePause = undefined;
667
+ }
668
+ }
669
+ finish(end, skipped = false) {
670
+ this.leaveStep();
671
+ this.stopFastForward();
672
+ // The game is the player's now: show it as it is
673
+ this.releasePoses(true);
674
+ this.releaseTimeline();
675
+ this.restoreAi();
676
+ this.view.setGuard?.(undefined);
677
+ this.view.setUndo?.(undefined);
678
+ this.runtime && (this.runtime.activeStep.value = "done");
679
+ this.focus.value = [];
680
+ this.hint.value = undefined;
681
+ this.status.value = "done";
682
+ if (!skipped) {
683
+ this.onEvent?.({ type: "completed", end });
684
+ }
685
+ }
686
+ // ---- narration and cues ------------------------------------------------------------------------
687
+ startNarration() {
688
+ const step = this.step;
689
+ if (!step)
690
+ return;
691
+ // Emphasise the first sentence from the start, not once the audio reports its first position
692
+ this.sentence.value = this.sentences.length > 0 ? 0 : -1;
693
+ this._clearTimeout(this.readingTimer);
694
+ this.readingActive = false;
695
+ this.readingPausedAt = undefined;
696
+ this.narration?.stop();
697
+ this.appliedCues = new Set();
698
+ this.narrationEnded = false;
699
+ this.applyCuesAt(0);
700
+ const useAudio = !!step.audio && !!this.narration && !this.muted.value;
701
+ // While this step talks, the next one's recording loads
702
+ if (useAudio)
703
+ this.preloadStep(this.index.value + 1);
704
+ if (useAudio && this.narration) {
705
+ const narration = this.narration;
706
+ this.stepUnsubs.push(narration.onTime((t) => this.onNarrationTime(t)));
707
+ this.stepUnsubs.push(narration.onSentence((i) => this.onSentence(i)));
708
+ this.stepUnsubs.push(narration.onEnd(() => {
709
+ this.narrationEnded = true;
710
+ this.narrating.value = false;
711
+ this.applyCuesAt(Number.POSITIVE_INFINITY);
712
+ this.sentence.value = this.emphasisAfterNarration();
713
+ this.afterNarration();
714
+ }));
715
+ this.narrating.value = true;
716
+ narration.play({ audio: step.audio, text: step.text, sentences: this.sentences }).catch(() => {
717
+ this.narrating.value = false;
718
+ this.startReadingClock();
719
+ });
720
+ }
721
+ else {
722
+ this.startReadingClock();
723
+ }
724
+ }
725
+ /** Without audio, time flows at the reading speed so `at` cues and emphasis still happen. */
726
+ startReadingClock() {
727
+ const step = this.step;
728
+ if (!step)
729
+ return;
730
+ const words = step.text.split(/\s+/).filter((w) => w).length;
731
+ // In "reading seconds" (normal speed); the clock below advances `rate` of them per real second
732
+ const duration = Number.isFinite(this.readingSpeed) ? Math.max(1, words / this.readingSpeed) : 0;
733
+ this.readingStartedAt = this._now();
734
+ this.readingPausedAt = undefined;
735
+ this.readingActive = true;
736
+ this.narrating.value = true;
737
+ const tick = () => {
738
+ if (this.readingPausedAt !== undefined) {
739
+ this.readingTimer = this._setTimeout(tick, 100);
740
+ return;
741
+ }
742
+ const t = ((this._now() - this.readingStartedAt) / 1000) * this.rate.value;
743
+ this.onNarrationTime(t, duration);
744
+ if (t >= duration) {
745
+ this.readingActive = false;
746
+ this.narrating.value = false;
747
+ this.sentence.value = this.emphasisAfterNarration();
748
+ this.narrationEnded = true;
749
+ this.applyCuesAt(Number.POSITIVE_INFINITY);
750
+ this.afterNarration();
751
+ return;
752
+ }
753
+ this.readingTimer = this._setTimeout(tick, 100);
754
+ };
755
+ tick();
756
+ }
757
+ scheduleSatisfiedAdvance() {
758
+ this._clearTimeout(this.satisfiedTimer);
759
+ if (this.fastForwardTarget.value !== undefined) {
760
+ // Fast-forwarding moves on once the board settles, so a check that passed in passing is re-read
761
+ this.scheduleFastBeat();
762
+ return;
763
+ }
764
+ this.satisfiedTimer = this._setTimeout(() => {
765
+ // The player just did what the step asked: that is as explicit as pressing Play
766
+ this.paused.value = false;
767
+ this.next();
768
+ }, this.satisfiedDelayMs);
769
+ }
770
+ /**
771
+ * Which sentence stays emphasised once the narration ends. A step about to move on by itself keeps
772
+ * its last sentence lit through the short beat before the next step, rather than flashing the whole
773
+ * paragraph back to full strength; a step that stays on screen shows the whole paragraph to read.
774
+ */
775
+ emphasisAfterNarration() {
776
+ const step = this.step;
777
+ if (!step || this.paused.value || this.status.value === "done")
778
+ return -1;
779
+ const movesOn = (this.advanceWhenNarrationEnds && this.status.value === "satisfied") ||
780
+ (!step.waitFor && !step.pause && !this.isLast);
781
+ return movesOn ? this.sentences.length - 1 : -1;
782
+ }
783
+ /** The step's narration (or reading clock) just ended */
784
+ afterNarration() {
785
+ this.scheduleAutoAdvance();
786
+ if (this.advanceWhenNarrationEnds && this.status.value === "satisfied") {
787
+ this.advanceWhenNarrationEnds = false;
788
+ this.scheduleSatisfiedAdvance();
789
+ }
790
+ }
791
+ /**
792
+ * A narration step moves on by itself once its narration (or reading clock) ends, unless it sets
793
+ * `pause`. "Do it" steps wait for their check and the last step waits for Finish.
794
+ */
795
+ scheduleAutoAdvance() {
796
+ const step = this.step;
797
+ // Reviewing (Back without a game to rewind) flows too once the player presses Play
798
+ if (!step || step.waitFor || step.pause || this.isLast || this.status.value === "done")
799
+ return;
800
+ if (this.paused.value)
801
+ return;
802
+ this._clearTimeout(this.advanceTimer);
803
+ this.advanceTimer = this._setTimeout(() => {
804
+ if (this.step === step && this.status.value === "narrating" && !this.paused.value)
805
+ this.next();
806
+ }, this.autoAdvanceDelayMs);
807
+ }
808
+ onNarrationTime(t, estimatedDuration) {
809
+ this.narrationTime.value = t;
810
+ this.applyCuesAt(t);
811
+ // Sentence emphasis: explicit times, else proportional to the (estimated) duration
812
+ const step = this.step;
813
+ if (!step || this.sentences.length === 0)
814
+ return;
815
+ const times = step.sentenceTimes;
816
+ if (times && times.length > 0) {
817
+ let i = 0;
818
+ while (i + 1 < times.length && times[i + 1] <= t)
819
+ i++;
820
+ this.sentence.value = i;
821
+ }
822
+ else if (!this.narration?.onSentence || this.muted.value || !step.audio) {
823
+ const duration = estimatedDuration ?? this.narration?.duration;
824
+ if (duration && duration > 0) {
825
+ const total = this.sentences.reduce((a, s) => a + s.length, 0);
826
+ let acc = 0;
827
+ let i = 0;
828
+ for (; i < this.sentences.length; i++) {
829
+ acc += this.sentences[i].length;
830
+ if ((t / duration) * total < acc)
831
+ break;
832
+ }
833
+ this.sentence.value = Math.min(i, this.sentences.length - 1);
834
+ }
835
+ }
836
+ }
837
+ onSentence(i) {
838
+ this.sentence.value = i;
839
+ this.applySentenceCues(i);
840
+ }
841
+ cueTime(cue) {
842
+ if (typeof cue.at === "number")
843
+ return cue.at;
844
+ const step = this.step;
845
+ const times = step?.sentenceTimes;
846
+ if (times && times[cue.at.sentence] !== undefined)
847
+ return times[cue.at.sentence];
848
+ // Proportional estimate when the narration has a known or estimated duration
849
+ const duration = this.narration?.duration;
850
+ if (step && duration && this.sentences.length) {
851
+ const total = this.sentences.reduce((a, s) => a + s.length, 0);
852
+ const before = this.sentences.slice(0, cue.at.sentence).reduce((a, s) => a + s.length, 0);
853
+ return (before / total) * duration;
854
+ }
855
+ return undefined;
856
+ }
857
+ applyCue(i, cue) {
858
+ if (this.appliedCues.has(i))
859
+ return;
860
+ this.appliedCues.add(i);
861
+ if (cue.focus)
862
+ this.focus.value = cue.focus;
863
+ if (cue.box && cue.box.anchor !== "keep")
864
+ this.box.value = cue.box;
865
+ if (cue.gallery)
866
+ this.applyGallery(cue.gallery);
867
+ if (cue.pose)
868
+ this.applyPoses(cue.pose);
869
+ if (cue.timeline)
870
+ this.applyTimeline(cue.timeline);
871
+ }
872
+ applyGallery(command) {
873
+ if (!this.view.setGallery)
874
+ return;
875
+ const opened = this.view.setGallery(command);
876
+ if (command === "close")
877
+ this.scriptOpenedGallery = false;
878
+ else if (opened)
879
+ this.scriptOpenedGallery = true;
880
+ }
881
+ applyCuesAt(t) {
882
+ const step = this.step;
883
+ if (!step?.cues)
884
+ return;
885
+ step.cues.forEach((cue, i) => {
886
+ if (typeof cue.at === "number") {
887
+ if (cue.at <= t)
888
+ this.applyCue(i, cue);
889
+ }
890
+ else if (t === Number.POSITIVE_INFINITY) {
891
+ this.applyCue(i, cue);
892
+ }
893
+ else {
894
+ const at = this.cueTime(cue);
895
+ if (at !== undefined && at <= t)
896
+ this.applyCue(i, cue);
897
+ else if (at === undefined && this.readingTimer && this.sentences.length) {
898
+ // reading clock, no durations: use sentence index from emphasis
899
+ if (this.sentence.value >= cue.at.sentence)
900
+ this.applyCue(i, cue);
901
+ }
902
+ }
903
+ });
904
+ }
905
+ applySentenceCues(sentence) {
906
+ const step = this.step;
907
+ step?.cues?.forEach((cue, i) => {
908
+ if (typeof cue.at !== "number" && cue.at.sentence <= sentence)
909
+ this.applyCue(i, cue);
910
+ });
911
+ }
912
+ // ---- doing it for the player --------------------------------------------------------------------
913
+ /**
914
+ * Makes the move the live "do it" step is waiting for, as if the player had: the first entry of its
915
+ * `allow` (in the order written) that the prompt can take, or the UI control an entry names. For
916
+ * watching and testing a tutorial without playing it every time. Returns whether it did anything.
917
+ */
918
+ doItForMe() {
919
+ if (this.disposed || this.rewinding.value || this.reviewing.value)
920
+ return false;
921
+ const step = this.step;
922
+ if (!step?.waitFor || this.status.value !== "waiting")
923
+ return false;
924
+ const prompt = this.view.prompt();
925
+ const answer = scriptedAnswer(step.allow, prompt, this.view.root(), this.view.me());
926
+ if (!answer)
927
+ return false;
928
+ if ("ui" in answer)
929
+ return this.view.pressUi?.(answer.ui) ?? false;
930
+ if (!prompt)
931
+ return false;
932
+ prompt.resolvePick(answer.move.pick, answer.move.value);
933
+ return true;
934
+ }
935
+ /** The → key: Next when the step can move on, otherwise the step's move made for the player */
936
+ forward() {
937
+ if (this.canAdvance)
938
+ this.next();
939
+ else
940
+ this.doItForMe();
941
+ }
942
+ /**
943
+ * Plays on to a later step as fast as it can: narration skipped, the board's animations rushed, the
944
+ * player's moves made for them (see `doItForMe`) and the bots playing as scripted. The step it lands
945
+ * on plays as usual. Back, Pause or jumping elsewhere stops it.
946
+ */
947
+ fastForwardTo(index) {
948
+ if (this.disposed || this.rewinding.value || this.status.value === "done")
949
+ return;
950
+ if (index <= this.index.value || index >= this.spec.steps.length)
951
+ return;
952
+ if (this.reviewing.value) {
953
+ // From a review (Back without a game history): carry on from the live step
954
+ this.enter(this.frontier.value);
955
+ if (index <= this.index.value)
956
+ return;
957
+ }
958
+ this.fastForwardTarget.value = index;
959
+ this.view.setFastForward?.(true);
960
+ this.releaseTimeline();
961
+ this.paused.value = false;
962
+ this.applyAi();
963
+ // The step on screen stops talking and moves on (or gets its move made)
964
+ this.narration?.stop();
965
+ this._clearTimeout(this.readingTimer);
966
+ this.readingActive = false;
967
+ this.narrating.value = false;
968
+ this.advanceWhenNarrationEnds = false;
969
+ if (this.status.value === "satisfied")
970
+ this.scheduleSatisfiedAdvance();
971
+ this.scheduleFastBeat();
972
+ }
973
+ /** The next beat of a fast-forward: move on from a talking step, or make a waiting step's move */
974
+ scheduleFastBeat() {
975
+ this._clearTimeout(this.fastTimer);
976
+ this._clearTimeout(this.fastWatchdog);
977
+ let settledSince;
978
+ const beat = () => {
979
+ this.fastTimer = undefined;
980
+ if (this.fastForwardTarget.value === undefined)
981
+ return;
982
+ // Wait for the board to catch up and stay caught up: a prompt can arrive just after its clock
983
+ if (this.view.settled?.() === false)
984
+ settledSince = undefined;
985
+ else
986
+ settledSince ?? (settledSince = this._now());
987
+ if (settledSince === undefined || this._now() - settledSince < FAST_SETTLE_MS) {
988
+ this.fastTimer = this._setTimeout(beat, FAST_BEAT_MS);
989
+ return;
990
+ }
991
+ this.evaluate();
992
+ if (this.status.value === "narrating" || this.status.value === "satisfied")
993
+ this.next();
994
+ else if (this.status.value === "waiting")
995
+ this.doItForMe();
996
+ };
997
+ this.fastTimer = this._setTimeout(beat, FAST_BEAT_MS);
998
+ // A step that never gets anywhere (its move is not on offer, the bots never finish) ends it
999
+ this.fastWatchdog = this._setTimeout(() => {
1000
+ const step = this.step;
1001
+ console.warn(`[tutorial ${this.spec.id}] fast-forward gave up on step "${step?.id}"`);
1002
+ this.stopFastForward();
1003
+ if (step)
1004
+ this.beginNarration();
1005
+ }, FAST_GIVE_UP_MS);
1006
+ }
1007
+ stopFastForward() {
1008
+ this._clearTimeout(this.fastTimer);
1009
+ this._clearTimeout(this.fastWatchdog);
1010
+ this.fastTimer = this.fastWatchdog = undefined;
1011
+ if (this.fastForwardTarget.value === undefined)
1012
+ return;
1013
+ this.fastForwardTarget.value = undefined;
1014
+ this.view.setFastForward?.(false);
1015
+ }
1016
+ applyPoses(poses) {
1017
+ const root = this.view.root();
1018
+ const me = this.view.me();
1019
+ // Passing through on a fast-forward: the next step would only put them back
1020
+ if (!root || !me || !this.view.pose || this.fastForwardTarget.value !== undefined)
1021
+ return;
1022
+ for (const pose of poses) {
1023
+ for (const chit of selectChits(pose.chit, root, me)) {
1024
+ const set = pose.set;
1025
+ if (!set) {
1026
+ this.releasePose(chit);
1027
+ continue;
1028
+ }
1029
+ try {
1030
+ this.view.pose(chit, (c) => (typeof set === "function" ? set(c) : Object.assign(c, set)));
1031
+ }
1032
+ catch (e) {
1033
+ console.error(`[tutorial ${this.spec.id}] a pose in step "${this.step?.id}" threw`, e);
1034
+ }
1035
+ this.posed.set(chit, { keep: !!pose.keep, step: this.index.value });
1036
+ }
1037
+ }
1038
+ }
1039
+ releasePose(chit) {
1040
+ if (!this.posed.delete(chit))
1041
+ return;
1042
+ try {
1043
+ this.view.unpose?.(chit);
1044
+ }
1045
+ catch (e) {
1046
+ console.error(`[tutorial ${this.spec.id}] putting a posed chit back threw`, e);
1047
+ }
1048
+ }
1049
+ /**
1050
+ * Puts posed chits back: all of them, or (on entering a step) those an earlier step posed for its
1051
+ * own length. A step that poses the same chit again keeps it posed without a flicker in between.
1052
+ */
1053
+ releasePoses(all) {
1054
+ for (const [chit, p] of [...this.posed]) {
1055
+ if (all || (!p.keep && p.step !== this.index.value))
1056
+ this.releasePose(chit);
1057
+ }
1058
+ }
1059
+ applyTimeline(command) {
1060
+ const timeline = this.view.timeline;
1061
+ // Looking back at a step's text leaves the board alone, as it does the game and the bots
1062
+ // A fast-forward lets the board play; the step it lands on holds it again
1063
+ if (!timeline || this.reviewing.value || this.fastForwardTarget.value !== undefined)
1064
+ return;
1065
+ this.timelineUntil = undefined;
1066
+ if (command === "play") {
1067
+ this.holdTimeline(undefined);
1068
+ }
1069
+ else if (command === "hold") {
1070
+ this.holdTimeline(timeline.at());
1071
+ }
1072
+ else if ("advance" in command) {
1073
+ this.holdTimeline(timeline.at() + Math.max(0, Math.floor(command.advance)));
1074
+ }
1075
+ else {
1076
+ const ctx = this.context();
1077
+ if (ctx)
1078
+ command.until.reset?.(ctx);
1079
+ this.timelineUntil = { check: command.until, logFrom: this.recentLog.length };
1080
+ this.holdTimeline(undefined);
1081
+ this.checkTimelineUntil();
1082
+ }
1083
+ }
1084
+ /** Stops the board at the first moment that passes a pending `{ until }` command */
1085
+ checkTimelineUntil() {
1086
+ const until = this.timelineUntil;
1087
+ if (!until || !this.view.timeline)
1088
+ return;
1089
+ const ctx = this.context();
1090
+ if (!ctx)
1091
+ return;
1092
+ let passed = false;
1093
+ try {
1094
+ passed = until.check({ ...ctx, recentLog: this.recentLog.slice(until.logFrom) }) === true;
1095
+ }
1096
+ catch (e) {
1097
+ console.error(`[tutorial ${this.spec.id}] a timeline "until" check in step "${this.step?.id}" threw`, e);
1098
+ }
1099
+ if (!passed)
1100
+ return;
1101
+ this.timelineUntil = undefined;
1102
+ // Change events arrive once the moment has loaded and before the board moves on from it
1103
+ this.holdTimeline(this.view.clock());
1104
+ }
1105
+ holdTimeline(clock) {
1106
+ this.timelineHold.value = clock;
1107
+ this.view.timeline?.hold(clock);
1108
+ }
1109
+ releaseTimeline() {
1110
+ this.timelineUntil = undefined;
1111
+ if (this.timelineHold.value !== undefined)
1112
+ this.holdTimeline(undefined);
1113
+ }
1114
+ // ---- checks ------------------------------------------------------------------------------------
1115
+ onViewChange() {
1116
+ if (this.disposed)
1117
+ return;
1118
+ const latest = this.view.latestLog();
1119
+ if (latest !== undefined && latest !== this.lastLog) {
1120
+ this.recentLog.push(latest);
1121
+ this.lastLog = latest;
1122
+ }
1123
+ this.boardClock.value = this.view.clock();
1124
+ this.checkTimelineUntil();
1125
+ this.evaluate();
1126
+ // Fast-forwarding through a "do it" step: make the move as soon as the prompt offers it
1127
+ if (this.fastForwardTarget.value !== undefined && this.status.value === "waiting")
1128
+ this.doItForMe();
1129
+ }
1130
+ evaluate() {
1131
+ const step = this.step;
1132
+ if (!step || this.status.value === "done" || this.reviewing.value)
1133
+ return;
1134
+ if (!step.waitFor) {
1135
+ this.check.value = undefined;
1136
+ return;
1137
+ }
1138
+ const ctx = this.context();
1139
+ if (!ctx)
1140
+ return;
1141
+ let result;
1142
+ try {
1143
+ result = step.waitFor(ctx);
1144
+ }
1145
+ catch (e) {
1146
+ console.error(`[tutorial ${this.spec.id}] waitFor of step "${step.id}" threw`, e);
1147
+ result = false;
1148
+ }
1149
+ this.check.value = result;
1150
+ if (result === true) {
1151
+ if (this.status.value !== "satisfied") {
1152
+ this.status.value = "satisfied";
1153
+ this.hint.value = undefined;
1154
+ this._clearTimeout(this.hintTimer);
1155
+ this._clearTimeout(this.satisfiedTimer);
1156
+ this.onEvent?.({ type: "satisfied", stepId: step.id });
1157
+ // Let the step finish what it is saying first; Next still moves on straight away
1158
+ if (this.narrating.value)
1159
+ this.advanceWhenNarrationEnds = true;
1160
+ else
1161
+ this.scheduleSatisfiedAdvance();
1162
+ }
1163
+ }
1164
+ else if (this.status.value === "satisfied") {
1165
+ // Un-satisfied again (an undo): keep waiting
1166
+ this._clearTimeout(this.satisfiedTimer);
1167
+ this.advanceWhenNarrationEnds = false;
1168
+ this.status.value = "waiting";
1169
+ }
1170
+ }
1171
+ showHint() {
1172
+ const step = this.step;
1173
+ if (!step || this.status.value !== "waiting")
1174
+ return;
1175
+ const configured = typeof step.hint === "object" ? step.hint.text : step.hint;
1176
+ const fromCheck = typeof this.check.value === "string" ? this.check.value : undefined;
1177
+ this.hint.value = fromCheck ?? configured;
1178
+ // keep the hint fresh as the check's reason changes
1179
+ this.hintTimer = this._setTimeout(() => this.showHint(), 1000);
1180
+ }
1181
+ }
1182
+ //# sourceMappingURL=TutorialController.js.map