@pretty-chitty/core 1.2.10 → 1.2.15

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 (158) hide show
  1. package/README.md +17 -3
  2. package/dist/components/FullScreenGalleryDisplay.d.ts.map +1 -1
  3. package/dist/components/FullScreenGalleryDisplay.js +5 -1
  4. package/dist/components/FullScreenGalleryDisplay.js.map +1 -1
  5. package/dist/components/Gallery/AnimationController.d.ts +1 -0
  6. package/dist/components/Gallery/AnimationController.d.ts.map +1 -1
  7. package/dist/components/Gallery/AnimationController.js +9 -0
  8. package/dist/components/Gallery/AnimationController.js.map +1 -1
  9. package/dist/components/Gallery/BuiltItem.d.ts +2 -1
  10. package/dist/components/Gallery/BuiltItem.d.ts.map +1 -1
  11. package/dist/components/Gallery/BuiltItem.js +15 -3
  12. package/dist/components/Gallery/BuiltItem.js.map +1 -1
  13. package/dist/components/Gallery/GalleryController.d.ts +1 -0
  14. package/dist/components/Gallery/GalleryController.d.ts.map +1 -1
  15. package/dist/components/Gallery/GalleryController.js +15 -4
  16. package/dist/components/Gallery/GalleryController.js.map +1 -1
  17. package/dist/components/Gallery/GalleryViewer.d.ts +2 -1
  18. package/dist/components/Gallery/GalleryViewer.d.ts.map +1 -1
  19. package/dist/components/Gallery/GalleryViewer.js +13 -4
  20. package/dist/components/Gallery/GalleryViewer.js.map +1 -1
  21. package/dist/components/InlineGalleryDisplay.d.ts.map +1 -1
  22. package/dist/components/InlineGalleryDisplay.js +5 -1
  23. package/dist/components/InlineGalleryDisplay.js.map +1 -1
  24. package/dist/components/Playground.d.ts.map +1 -1
  25. package/dist/components/Playground.js +59 -21
  26. package/dist/components/Playground.js.map +1 -1
  27. package/dist/components/ServerTrustMatchViewer.d.ts.map +1 -1
  28. package/dist/components/ServerTrustMatchViewer.js +10 -2
  29. package/dist/components/ServerTrustMatchViewer.js.map +1 -1
  30. package/dist/components/SparkLineChart.d.ts.map +1 -1
  31. package/dist/components/SparkLineChart.js +62 -22
  32. package/dist/components/SparkLineChart.js.map +1 -1
  33. package/dist/components/Viewer.d.ts.map +1 -1
  34. package/dist/components/Viewer.js +15 -6
  35. package/dist/components/Viewer.js.map +1 -1
  36. package/dist/game/Chit.d.ts +10 -1
  37. package/dist/game/Chit.d.ts.map +1 -1
  38. package/dist/game/Chit.js +125 -4
  39. package/dist/game/Chit.js.map +1 -1
  40. package/dist/game/Connection.d.ts +1 -0
  41. package/dist/game/Connection.d.ts.map +1 -1
  42. package/dist/game/Connection.js +27 -8
  43. package/dist/game/Connection.js.map +1 -1
  44. package/dist/game/ConnectionTransport.d.ts +5 -0
  45. package/dist/game/ConnectionTransport.d.ts.map +1 -1
  46. package/dist/game/ConnectionTransport.js +32 -0
  47. package/dist/game/ConnectionTransport.js.map +1 -1
  48. package/dist/game/GalleryItemChitChildrenSource.d.ts.map +1 -1
  49. package/dist/game/GalleryItemChitChildrenSource.js +9 -1
  50. package/dist/game/GalleryItemChitChildrenSource.js.map +1 -1
  51. package/dist/game/OrderedOutlet.d.ts +4 -1
  52. package/dist/game/OrderedOutlet.d.ts.map +1 -1
  53. package/dist/game/OrderedOutlet.js +25 -4
  54. package/dist/game/OrderedOutlet.js.map +1 -1
  55. package/dist/game/Pick.d.ts +1 -0
  56. package/dist/game/Pick.d.ts.map +1 -1
  57. package/dist/game/Pick.js +40 -1
  58. package/dist/game/Pick.js.map +1 -1
  59. package/dist/game/Prompt.d.ts +11 -1
  60. package/dist/game/Prompt.d.ts.map +1 -1
  61. package/dist/game/Prompt.js +34 -1
  62. package/dist/game/Prompt.js.map +1 -1
  63. package/dist/game/Turn.d.ts +17 -0
  64. package/dist/game/Turn.d.ts.map +1 -1
  65. package/dist/game/Turn.js +114 -63
  66. package/dist/game/Turn.js.map +1 -1
  67. package/dist/game/badAiTransport/BadAIClientPrompts.d.ts.map +1 -1
  68. package/dist/game/badAiTransport/BadAIClientPrompts.js +24 -4
  69. package/dist/game/badAiTransport/BadAIClientPrompts.js.map +1 -1
  70. package/dist/game/clientTransport/ClientPrompts.d.ts +2 -0
  71. package/dist/game/clientTransport/ClientPrompts.d.ts.map +1 -1
  72. package/dist/game/clientTransport/ClientPrompts.js +48 -16
  73. package/dist/game/clientTransport/ClientPrompts.js.map +1 -1
  74. package/dist/game/clientTransport/ClientTime.d.ts.map +1 -1
  75. package/dist/game/clientTransport/ClientTime.js +58 -52
  76. package/dist/game/clientTransport/ClientTime.js.map +1 -1
  77. package/dist/game/serverTransport/ServerPrompts.d.ts +1 -1
  78. package/dist/game/serverTransport/ServerPrompts.d.ts.map +1 -1
  79. package/dist/game/serverTransport/ServerPrompts.js +14 -3
  80. package/dist/game/serverTransport/ServerPrompts.js.map +1 -1
  81. package/dist/game/serverTransport/ServerStatus.d.ts.map +1 -1
  82. package/dist/game/serverTransport/ServerStatus.js +6 -2
  83. package/dist/game/serverTransport/ServerStatus.js.map +1 -1
  84. package/dist/game/serverTransport/ServerTime.d.ts.map +1 -1
  85. package/dist/game/serverTransport/ServerTime.js +6 -2
  86. package/dist/game/serverTransport/ServerTime.js.map +1 -1
  87. package/dist/hooks/useTimeController.d.ts.map +1 -1
  88. package/dist/hooks/useTimeController.js +3 -0
  89. package/dist/hooks/useTimeController.js.map +1 -1
  90. package/dist/hooks/useWebGlRenderer.d.ts +27 -1
  91. package/dist/hooks/useWebGlRenderer.d.ts.map +1 -1
  92. package/dist/hooks/useWebGlRenderer.js +179 -6
  93. package/dist/hooks/useWebGlRenderer.js.map +1 -1
  94. package/dist/index.d.ts +1 -1
  95. package/dist/index.d.ts.map +1 -1
  96. package/dist/index.js +1 -1
  97. package/dist/index.js.map +1 -1
  98. package/dist/rendering/ChitGalleryItemInstance.js +1 -1
  99. package/dist/rendering/ChitGalleryItemInstance.js.map +1 -1
  100. package/dist/rendering/ChitRenderInstance.d.ts.map +1 -1
  101. package/dist/rendering/ChitRenderInstance.js +30 -9
  102. package/dist/rendering/ChitRenderInstance.js.map +1 -1
  103. package/dist/rendering/ChitRenderSpec.js +1 -1
  104. package/dist/rendering/ChitRenderSpec.js.map +1 -1
  105. package/dist/rendering/outline/IDBasedOutlinePass.d.ts.map +1 -1
  106. package/dist/rendering/outline/IDBasedOutlinePass.js +6 -2
  107. package/dist/rendering/outline/IDBasedOutlinePass.js.map +1 -1
  108. package/dist/rendering/outline/passes/InterMeshEdgeDetectionPass.d.ts.map +1 -1
  109. package/dist/rendering/outline/passes/InterMeshEdgeDetectionPass.js +7 -3
  110. package/dist/rendering/outline/passes/InterMeshEdgeDetectionPass.js.map +1 -1
  111. package/dist/utilities/CanvasStack/CanvasOperations.d.ts.map +1 -1
  112. package/dist/utilities/CanvasStack/CanvasOperations.js +34 -13
  113. package/dist/utilities/CanvasStack/CanvasOperations.js.map +1 -1
  114. package/dist/utilities/CanvasStack/CanvasStack.d.ts +9 -0
  115. package/dist/utilities/CanvasStack/CanvasStack.d.ts.map +1 -1
  116. package/dist/utilities/CanvasStack/CanvasStack.js +37 -2
  117. package/dist/utilities/CanvasStack/CanvasStack.js.map +1 -1
  118. package/dist/utilities/CanvasStack/RichTextRenderer.d.ts +2 -0
  119. package/dist/utilities/CanvasStack/RichTextRenderer.d.ts.map +1 -1
  120. package/dist/utilities/CanvasStack/RichTextRenderer.js +47 -4
  121. package/dist/utilities/CanvasStack/RichTextRenderer.js.map +1 -1
  122. package/package.json +1 -1
  123. package/src/library/components/FullScreenGalleryDisplay.tsx +5 -0
  124. package/src/library/components/Gallery/AnimationController.ts +10 -0
  125. package/src/library/components/Gallery/BuiltItem.ts +16 -3
  126. package/src/library/components/Gallery/GalleryController.ts +15 -4
  127. package/src/library/components/Gallery/GalleryViewer.tsx +17 -3
  128. package/src/library/components/InlineGalleryDisplay.tsx +5 -0
  129. package/src/library/components/Playground.tsx +76 -20
  130. package/src/library/components/ServerTrustMatchViewer.tsx +10 -2
  131. package/src/library/components/SparkLineChart.tsx +85 -24
  132. package/src/library/components/Viewer.tsx +15 -6
  133. package/src/library/game/Chit.test.ts +91 -0
  134. package/src/library/game/Chit.ts +122 -9
  135. package/src/library/game/Connection.ts +27 -8
  136. package/src/library/game/ConnectionTransport.ts +38 -0
  137. package/src/library/game/GalleryItemChitChildrenSource.ts +9 -1
  138. package/src/library/game/OrderedOutlet.ts +27 -4
  139. package/src/library/game/Pick.ts +46 -4
  140. package/src/library/game/Prompt.ts +43 -3
  141. package/src/library/game/Turn.ts +127 -78
  142. package/src/library/game/badAiTransport/BadAIClientPrompts.ts +21 -4
  143. package/src/library/game/clientTransport/ClientPrompts.ts +50 -16
  144. package/src/library/game/clientTransport/ClientTime.ts +61 -56
  145. package/src/library/game/serverTransport/ServerPrompts.ts +25 -7
  146. package/src/library/game/serverTransport/ServerStatus.ts +6 -2
  147. package/src/library/game/serverTransport/ServerTime.ts +6 -2
  148. package/src/library/hooks/useTimeController.tsx +3 -0
  149. package/src/library/hooks/useWebGlRenderer.tsx +212 -6
  150. package/src/library/index.ts +1 -1
  151. package/src/library/rendering/ChitGalleryItemInstance.ts +1 -1
  152. package/src/library/rendering/ChitRenderInstance.ts +32 -9
  153. package/src/library/rendering/ChitRenderSpec.ts +1 -1
  154. package/src/library/rendering/outline/IDBasedOutlinePass.ts +6 -2
  155. package/src/library/rendering/outline/passes/InterMeshEdgeDetectionPass.ts +7 -3
  156. package/src/library/utilities/CanvasStack/CanvasOperations.tsx +44 -13
  157. package/src/library/utilities/CanvasStack/CanvasStack.ts +38 -1
  158. package/src/library/utilities/CanvasStack/RichTextRenderer.ts +66 -5
@@ -28,6 +28,8 @@ type ChitHistoryResponse = {
28
28
  [id: string]: ChitHistoryItem[];
29
29
  };
30
30
 
31
+ export type ConfirmContext = "turn_end" | "roll" | "switch_player";
32
+
31
33
  type ValidPick = undefined | false | Pick | Pick[] | ButtonPick | ButtonPick[] | GameButton | GameButton[];
32
34
  export type Picks = ValidPick | ValidPick[];
33
35
 
@@ -89,6 +91,38 @@ export class Turn<T, P extends PlayerChit, R extends RootChit<P>> {
89
91
  private chitLookup: ChitLookup = {};
90
92
  private lockedChitStates: ChitStateLookup = {};
91
93
  private lastChitStates: ChitStateLookup = {};
94
+ private dirtyChitIds = new Set<string>();
95
+ private pendingNewChits = new Set<Chit>();
96
+ private _statePool?: Map<string, string>;
97
+
98
+ private get statePool(): Map<string, string> {
99
+ if (this.parent) return this.parent.statePool;
100
+ if (!this._statePool) this._statePool = new Map();
101
+ return this._statePool;
102
+ }
103
+
104
+ /**
105
+ * Intern a serialized state string. If `hint` is provided (e.g. the last known state),
106
+ * a cheap content comparison is done first to avoid the Map lookup entirely — which matters
107
+ * because Map.get with large string keys is O(n) on string length.
108
+ */
109
+ private internState(s: string, hint?: string): string {
110
+ if (hint !== undefined && s === hint) return hint;
111
+ const pool = this.statePool;
112
+ const existing = pool.get(s);
113
+ if (existing !== undefined) return existing;
114
+ pool.set(s, s);
115
+ return s;
116
+ }
117
+
118
+ /** @internal */
119
+ public notifyChitDirty(chit: Chit) {
120
+ if (chit.id) {
121
+ this.dirtyChitIds.add(chit.id);
122
+ } else {
123
+ this.pendingNewChits.add(chit);
124
+ }
125
+ }
92
126
 
93
127
  /**
94
128
  * Locates a chit by its ID. If not found, will throw.
@@ -160,7 +194,7 @@ export class Turn<T, P extends PlayerChit, R extends RootChit<P>> {
160
194
  if (!c.id) {
161
195
  throw new Error("Cannot serialize a chit without an id");
162
196
  }
163
- this.lastChitStates[c.id] = this.lockedChitStates[c.id] = c.serialize(this._playerIds);
197
+ this.lastChitStates[c.id] = this.lockedChitStates[c.id] = this.internState(c.serialize(this._playerIds));
164
198
  });
165
199
  }
166
200
 
@@ -245,6 +279,8 @@ export class Turn<T, P extends PlayerChit, R extends RootChit<P>> {
245
279
  step.log = message;
246
280
  }
247
281
 
282
+ _zipStartPoint = 0;
283
+
248
284
  /**
249
285
  * Compress the history in the timeline such that a user with maybe many moves (and changing their minds) won't
250
286
  * clock up the replay timeline. Basically takes all of the flushes and smushes them together into a single flush.
@@ -256,7 +292,7 @@ export class Turn<T, P extends PlayerChit, R extends RootChit<P>> {
256
292
  zip() {
257
293
  this.flush();
258
294
  let hasChange = false;
259
- while (this.clockSteps.length >= 2) {
295
+ while (this.clockSteps.length >= this._zipStartPoint + 2) {
260
296
  const lastStep = this.clockSteps[this.clockSteps.length - 1];
261
297
  const previousStep = this.clockSteps[this.clockSteps.length - 2];
262
298
  if (!(lastStep instanceof FlushClockStep) || !(previousStep instanceof FlushClockStep)) {
@@ -270,101 +306,107 @@ export class Turn<T, P extends PlayerChit, R extends RootChit<P>> {
270
306
 
271
307
  if (hasChange) {
272
308
  this.pass++;
273
- this.flush();
309
+ this.flush(true);
274
310
  }
275
311
  }
276
312
 
313
+ /**
314
+ * Marks the current point in the clock steps as a "zip start point". This does nothing by itself, but when you later call zip(),
315
+ * it will not zip past this point
316
+ */
317
+ markZipStartPoint() {
318
+ this._zipStartPoint = this.clockSteps.length;
319
+ }
320
+
277
321
  /**
278
322
  * Scan all of the chits managed by this turn. If any of them have changed, group them together into a
279
323
  * "ClockStep". If any new chits appear, then add them to our lookup. If any chits are deleted (orphaned),
280
324
  * then we have to identify those as well.
281
325
  */
282
326
  flush(force = false) {
283
- const seenIds = new Set<string>();
284
327
  const newStates: ChitStateLookup = {};
285
328
  let sawChange = force;
286
329
 
287
- // first ensure they all are locked and all have ids
288
- const chitsToAddIdsTo: Chit[] = [];
289
- Chit.walk(this.chitsToLock, (c) => {
290
- if (!c.id) {
291
- chitsToAddIdsTo.push(c);
330
+ // 1. Assign IDs to pending new chits and their children
331
+ if (this.pendingNewChits.size > 0) {
332
+ // collect all chits needing IDs by walking each new chit's subtree
333
+ const chitsToAddIdsTo: Chit[] = [];
334
+ for (const c of this.pendingNewChits) {
335
+ if (!c.parent) continue; // created then deleted before flush — skip
336
+ c.walk((child) => {
337
+ if (!child.id) {
338
+ chitsToAddIdsTo.push(child);
339
+ }
340
+ });
292
341
  }
293
- });
294
-
295
- chitsToAddIdsTo.sort((a, b) => a.createdOrder - b.createdOrder);
296
- chitsToAddIdsTo.forEach((c) => {
297
- const type = c.chitTypeName();
298
- const counter = (this.newChitCounter[type] || 0) + 1;
299
- this.newChitCounter[type] = counter;
300
- c.id = `${this.id}.${type}.${counter}`;
301
- c.lock(this);
302
-
303
- const existing = this.chitLookup[c.id];
304
- this.chitLookup[c.id] = c; // it's possible that this is kicking out an "old" version of this chit from a previous pass
305
- if (existing) {
306
- existing.removeFromParent(); // do not want to leave stray references to this cloned chit around!
307
- existing.unlock(this);
342
+ this.pendingNewChits.clear();
343
+
344
+ chitsToAddIdsTo.sort((a, b) => a.createdOrder - b.createdOrder);
345
+ for (const c of chitsToAddIdsTo) {
346
+ if (c.id) continue; // may have been assigned by a prior iteration
347
+ const type = c.chitTypeName();
348
+ const counter = (this.newChitCounter[type] || 0) + 1;
349
+ this.newChitCounter[type] = counter;
350
+ c.id = `${this.id}.${type}.${counter}`;
351
+ c.lock(this);
352
+
353
+ const existing = this.chitLookup[c.id];
354
+ this.chitLookup[c.id] = c;
355
+ if (existing) {
356
+ existing.removeFromParent();
357
+ existing.unlock(this);
358
+ }
359
+ this.dirtyChitIds.add(c.id);
308
360
  }
309
- });
361
+ }
310
362
 
311
- // now (once per chit) we serialize the state if it changed
312
- Chit.walk(this.chitsToLock, (c) => {
313
- if (!c.id) {
314
- throw new Error("Should not be possible unless Chit.walk is misbehaving");
315
- }
316
- if (!seenIds.has(c.id)) {
317
- seenIds.add(c.id);
318
- const serialized = c.serialize(this._playerIds);
319
- const lastState = this.lastChitStates[c.id];
320
- if (serialized !== lastState) {
321
- this.lastChitStates[c.id] = newStates[c.id] = serialized;
322
- sawChange = true;
323
- } else {
324
- newStates[c.id] = serialized;
325
- }
363
+ // 2. Serialize only dirty chits
364
+ for (const id of this.dirtyChitIds) {
365
+ const chit = this.chitLookup[id];
366
+ if (!chit) continue;
367
+ const lastState = this.lastChitStates[id];
368
+ const serialized = this.internState(chit.serialize(this._playerIds), lastState);
369
+ if (serialized !== lastState) {
370
+ this.lastChitStates[id] = newStates[id] = serialized;
371
+ sawChange = true;
326
372
  } else {
327
- return false; // already saw this - no need to keep digging into children
373
+ newStates[id] = serialized;
328
374
  }
329
- });
375
+ }
376
+ this.dirtyChitIds.clear();
330
377
 
331
- // find any chits that we previously serialized that we no longer see
332
- // these should be marked as deleted now
333
- const chitsToDelete = Object.keys(this.lastChitStates)
334
- .filter((id) => !seenIds.has(id) && this.lastChitStates[id] !== Chit.deletedIfSerialized())
335
- .map((id) => this.findChit(id));
336
-
337
- // make sure any missing items that were previously also missing are still deleted
338
- Object.keys(this.lastChitStates)
339
- .filter((id) => !seenIds.has(id) && this.lastChitStates[id] == Chit.deletedIfSerialized())
340
- .forEach((id) => {
341
- newStates[id] = Chit.deletedIfSerialized();
342
- });
343
-
344
- // find all chits without parents - all of their descendants are safe to be purged
345
- chitsToDelete
346
- .filter((chit) => !chit.parent)
347
- .forEach((chit) => {
348
- if (chit.id) {
349
- sawChange = true;
350
- chit.unlock(this);
351
- newStates[chit.id] = Chit.deletedIfSerialized();
352
- // do not store this new state in lastChitStates, but rather delete this record from it altogether
353
- chit.walk((c) => {
354
- if (c.id) {
355
- seenIds.add(c.id);
356
- this.lastChitStates[c.id] = Chit.deletedIfSerialized();
357
- newStates[c.id] = Chit.deletedIfSerialized();
358
- chit.unlock(this);
359
- }
360
- });
361
- }
362
- });
378
+ // 4. Carry forward all non-dirty chit states
379
+ for (const id of Object.keys(this.lastChitStates)) {
380
+ if (newStates[id] === undefined) {
381
+ newStates[id] = this.lastChitStates[id];
382
+ }
383
+ }
384
+
385
+ // 5. Detect deleted chits — orphans in lastChitStates that weren't serialized above
386
+ const deletedRoots: Chit[] = [];
387
+ for (const id of Object.keys(this.lastChitStates)) {
388
+ if (this.lastChitStates[id] === Chit.deletedIfSerialized()) continue;
389
+ const chit = this.chitLookup[id];
390
+ if (chit && !chit.parent && !this.chitsToLock.includes(chit)) {
391
+ deletedRoots.push(chit);
392
+ }
393
+ }
363
394
 
364
- // any chits remaining that we haven't seen are bad news - they have likely been reparented to some other Turn, which
365
- // is against the rules. They need to remain under this turns control.
366
- if (chitsToDelete.find((c) => c.id && !seenIds.has(c.id))) {
367
- throw new Error("Chit has been reparented to another Turn which will corrupt control");
395
+ for (const chit of deletedRoots) {
396
+ if (chit.id) {
397
+ sawChange = true;
398
+ chit.unlock(this);
399
+ newStates[chit.id] = Chit.deletedIfSerialized();
400
+ this.lastChitStates[chit.id] = Chit.deletedIfSerialized();
401
+ // walk only the deleted subtree to mark descendants as deleted
402
+ chit.walk((c) => {
403
+ if (c.id) {
404
+ this.lastChitStates[c.id] = Chit.deletedIfSerialized();
405
+ newStates[c.id] = Chit.deletedIfSerialized();
406
+ chit.unlock(this);
407
+ }
408
+ });
409
+ }
368
410
  }
369
411
 
370
412
  if (sawChange) {
@@ -1147,6 +1189,13 @@ export class Turn<T, P extends PlayerChit, R extends RootChit<P>> {
1147
1189
  });
1148
1190
 
1149
1191
  this.lastChitStates = { ...this.lockedChitStates }; // reset our known chit states
1192
+ this.dirtyChitIds.clear();
1193
+ this.pendingNewChits.clear();
1194
+ // chits were deserialized back to locked state — mark them clean so future
1195
+ // modifications correctly trigger markDirty() → notifyChitDirty()
1196
+ Chit.walk(this.chitsToLock, (c) => {
1197
+ c._dirty = false;
1198
+ });
1150
1199
  this.clockSteps = [];
1151
1200
  this.decisionIndex = 0;
1152
1201
  this.newChitCounter = {};
@@ -24,26 +24,43 @@ export class BadAIClientPrompts<P extends PlayerChit, R extends RootChit<P>> ext
24
24
  if (prompt && playerId === this.playerId) {
25
25
  if (prompt.type === "PickPrompt") {
26
26
  const picks = prompt.details.picks;
27
- const pickIndex = Math.floor(Math.random() * picks.length);
27
+ const weights = picks.map((p: any) => {
28
+ switch (p.type as PickType) {
29
+ case "ButtonPick": return 1;
30
+ case "ChitPick": return p.details.c.length;
31
+ case "DragPick": return (p.details.d as any[][]).reduce((sum: number, targets: any[]) => sum + targets.length, 0);
32
+ default: return 1;
33
+ }
34
+ });
35
+ const totalWeight = weights.reduce((sum: number, w: number) => sum + w, 0);
36
+ let roll = Math.random() * totalWeight;
37
+ let pickIndex = 0;
38
+ for (let i = 0; i < weights.length; i++) {
39
+ roll -= weights[i];
40
+ if (roll <= 0) { pickIndex = i; break; }
41
+ }
28
42
  const pick = picks[pickIndex];
29
43
  switch (pick.type as PickType) {
30
44
  case "ButtonPick": {
31
- await this.serverPrompts.resolvePrompt({
45
+ await this.serverPrompts.resolvePrompt(prompt.id, {
32
46
  idx: pickIndex,
47
+ pickType: "ButtonPick",
33
48
  });
34
49
  break;
35
50
  }
36
51
  case "ChitPick": {
37
- await this.serverPrompts.resolvePrompt({
52
+ await this.serverPrompts.resolvePrompt(prompt.id, {
38
53
  idx: pickIndex,
54
+ pickType: "ChitPick",
39
55
  value: pick.details.c[Math.floor(Math.random() * pick.details.c.length)],
40
56
  });
41
57
  break;
42
58
  }
43
59
  case "DragPick": {
44
60
  const target = pick.details.d[Math.floor(Math.random() * pick.details.d.length)];
45
- await this.serverPrompts.resolvePrompt({
61
+ await this.serverPrompts.resolvePrompt(prompt.id, {
46
62
  idx: pickIndex,
63
+ pickType: "DragPick",
47
64
  value: {
48
65
  chitId: pick.details.c[Math.floor(Math.random() * pick.details.c.length)],
49
66
  targetChitId: target[Math.floor(Math.random() * target.length)],
@@ -37,6 +37,30 @@ export class ClientPrompts<P extends PlayerChit, R extends RootChit<P>> extends
37
37
  }
38
38
  }
39
39
 
40
+ private stageInPrompt(promptSpec: PromptSerialization) {
41
+ this._currentPromptSpec = promptSpec;
42
+ const prompt = Prompt.deserialize(promptSpec, this.clientTime.findChit, this.clientTime.game.buttonLibrary);
43
+ prompt.onResolve(async (success) => {
44
+ try {
45
+ this.fixActiveLog();
46
+ if (success) {
47
+ const newPromptSpec = await this.serverPrompts.resolvePrompt(prompt.id, prompt.response);
48
+ this.getPromptEventChannelForPlayer(this.playerId).value = newPromptSpec ?? undefined;
49
+ } else if (prompt.shouldStepBack) {
50
+ this.getPromptEventChannelForPlayer(this.playerId).value = undefined;
51
+ await this.serverPrompts.stepBackPrompt(prompt.shouldReset ?? false);
52
+ }
53
+ } catch (e) {
54
+ prompt.stageOut();
55
+ this.currentPrompt.value = undefined;
56
+ }
57
+ });
58
+ prompt.stageIn();
59
+
60
+ this.currentPrompt.value = prompt;
61
+ this.fixActiveLog();
62
+ }
63
+
40
64
  private checkIfPromptCanBeInflated() {
41
65
  const isLive = this.clientTime.clientTimeState.live.value;
42
66
  const currentTime = this.clientTime.currentClock.value.clock;
@@ -59,22 +83,23 @@ export class ClientPrompts<P extends PlayerChit, R extends RootChit<P>> extends
59
83
  this.currentPrompt.value.stageOut();
60
84
  }
61
85
 
62
- this._currentPromptSpec = promptSpec;
63
- const prompt = Prompt.deserialize(promptSpec, this.clientTime.findChit, this.clientTime.game.buttonLibrary);
64
- prompt.onResolve(async (success) => {
65
- this.fixActiveLog();
66
- if (success) {
67
- const newPromptSpec = await this.serverPrompts.resolvePrompt(prompt.response);
68
- this.getPromptEventChannelForPlayer(this.playerId).value = newPromptSpec ?? undefined;
69
- } else if (prompt.shouldStepBack) {
70
- this.getPromptEventChannelForPlayer(this.playerId).value = undefined;
71
- await this.serverPrompts.stepBackPrompt(prompt.shouldReset ?? false);
72
- }
73
- });
74
- prompt.stageIn();
75
-
76
- this.currentPrompt.value = prompt;
77
- this.fixActiveLog();
86
+ this.stageInPrompt(promptSpec);
87
+ } else if (
88
+ isLive &&
89
+ promptSpec &&
90
+ currentTime > 0 &&
91
+ promptSpec.canStageInEarly > 0 &&
92
+ currentTime >= maxTime - promptSpec.canStageInEarly &&
93
+ samePasses(this.clientTime.currentClock.value, this.clientTime.maxClock.value)
94
+ ) {
95
+ // if we are live and have a prompt spec, but our current time is greater than our max time, then we should stage in the prompt, but not mark it as the current prompt spec, so that if we go back in time we can stage out the prompt and stage it back in when we return to the current time
96
+ if (this.currentPrompt.value && this.currentPrompt.value.isSameSerialization(promptSpec)) {
97
+ return;
98
+ }
99
+ if (this.currentPrompt.value) {
100
+ this.currentPrompt.value.stageOut();
101
+ }
102
+ this.stageInPrompt(promptSpec);
78
103
  } else {
79
104
  this._currentPromptSpec = undefined;
80
105
  if (this.currentPrompt.value) {
@@ -85,6 +110,15 @@ export class ClientPrompts<P extends PlayerChit, R extends RootChit<P>> extends
85
110
  }
86
111
  }
87
112
 
113
+ disconnect() {
114
+ this._currentPromptSpec = undefined;
115
+ if (this.currentPrompt.value) {
116
+ this.currentPrompt.value.stageOut();
117
+ }
118
+ this.currentPrompt.value = undefined;
119
+ this.fixActiveLog();
120
+ }
121
+
88
122
  public async setPromptForPlayer(playerId: string, prompt?: PromptSerialization, clockDetails?: ClockDetails) {
89
123
  this.getPromptEventChannelForPlayer(playerId).value = prompt;
90
124
  if (clockDetails) {
@@ -148,74 +148,79 @@ export class ClientTime extends ConnectionObject {
148
148
  const animationKey = `minimumAnimationDuration${Date.now()}`;
149
149
  this.clientTimeState.setAnimationState(animationKey, true);
150
150
 
151
- const response = await this.serverTime.serializeDelta(this.clientTimeState.targetClock.value);
152
- const serializedChits = this.inflateSerializedResponse(response.newStates, response.chits);
153
-
154
- // make sure nothing changed while we were waiting...
155
- if (this.clientTimeState.targetClock.value === newTargetClock && currentClock === this.currentClock.value) {
156
- if (newTargetClock >= this.startTime) {
157
- this.clientTimeState.isLoading.value = false;
158
- }
151
+ try {
152
+ const response = await this.serverTime.serializeDelta(this.clientTimeState.targetClock.value);
153
+ const serializedChits = this.inflateSerializedResponse(response.newStates, response.chits);
154
+
155
+ // make sure nothing changed while we were waiting...
156
+ if (this.clientTimeState.targetClock.value === newTargetClock && currentClock === this.currentClock.value) {
157
+ if (newTargetClock >= this.startTime) {
158
+ this.clientTimeState.isLoading.value = false;
159
+ }
159
160
 
160
- // track the active log message
161
- this.activeLog.value = response.log?.message;
162
- this.clientPrompt?.fixActiveLog();
163
-
164
- // first make sure all chits exist (because they may link to each other)
165
- Object.entries(serializedChits).forEach(([id, value]) => {
166
- let chit = this.chitLookup[id];
167
- if (!chit) {
168
- const c = Chit.deflate(value, this.game);
169
- if (c) {
170
- chit = this.chitLookup[id] = c;
161
+ // track the active log message
162
+ this.activeLog.value = response.log?.message;
163
+ this.clientPrompt?.fixActiveLog();
164
+
165
+ // first make sure all chits exist (because they may link to each other)
166
+ Object.entries(serializedChits).forEach(([id, value]) => {
167
+ let chit = this.chitLookup[id];
168
+ if (!chit) {
169
+ const c = Chit.deflate(value, this.game);
170
+ if (c) {
171
+ chit = this.chitLookup[id] = c;
172
+ }
171
173
  }
172
- }
173
- });
174
+ });
174
175
 
175
- Object.values(this.chitLookup).forEach((chit) => {
176
- if (chit.id && !serializedChits[chit.id]) {
177
- if (chit.parentFallback) {
178
- chit.beginDeserializing();
179
- chit.setParent(chit.parentFallback, chit.parentOutlet ?? "graveyard");
180
- chit.doneDeserializing();
181
- } else {
182
- chit.removeFromParent();
176
+ Object.values(this.chitLookup).forEach((chit) => {
177
+ if (chit.id && !serializedChits[chit.id]) {
178
+ if (chit.parentFallback) {
179
+ chit.beginDeserializing();
180
+ chit.setParent(chit.parentFallback, chit.parentOutlet ?? "graveyard");
181
+ chit.doneDeserializing();
182
+ } else {
183
+ chit.removeFromParent();
184
+ }
185
+ delete this.lastSerializedState[chit.id];
183
186
  }
184
- delete this.lastSerializedState[chit.id];
185
- }
186
- });
187
+ });
187
188
 
188
- this.currentClock.value = response.clockDetails;
189
+ this.currentClock.value = response.clockDetails;
189
190
 
190
- // now actually load the new state
191
- const changedIds = new Set(
192
- Object.entries(serializedChits)
193
- .filter(([id, value]) => this.chitLookup[id] && this.lastSerializedState[id] !== value)
194
- .map(([id]) => id),
195
- );
191
+ // now actually load the new state
192
+ const changedIds = new Set(
193
+ Object.entries(serializedChits)
194
+ .filter(([id, value]) => this.chitLookup[id] && this.lastSerializedState[id] !== value)
195
+ .map(([id]) => id),
196
+ );
196
197
 
197
- const chits: Chit[] = Object.entries(serializedChits)
198
- .filter(([id, value]) => this.chitLookup[id] && this.lastSerializedState[id] !== value)
199
- .map(([id]) => this.chitLookup[id]);
198
+ const chits: Chit[] = Object.entries(serializedChits)
199
+ .filter(([id, value]) => this.chitLookup[id] && this.lastSerializedState[id] !== value)
200
+ .map(([id]) => this.chitLookup[id]);
200
201
 
201
- chits.forEach((chit) => chit.beginDeserializing());
202
+ chits.forEach((chit) => chit.beginDeserializing());
202
203
 
203
- Object.entries(serializedChits)
204
- .filter(([id]) => changedIds.has(id))
205
- .forEach(([id, value]) => {
206
- const chit = this.chitLookup[id];
207
- chit.deserialize(value, this.findChit);
208
- this.lastSerializedState[id] = value;
209
- });
204
+ Object.entries(serializedChits)
205
+ .filter(([id]) => changedIds.has(id))
206
+ .forEach(([id, value]) => {
207
+ const chit = this.chitLookup[id];
208
+ chit.deserialize(value, this.findChit);
209
+ this.lastSerializedState[id] = value;
210
+ });
210
211
 
211
- chits.forEach((chit) => chit.doneDeserializing());
212
+ chits.forEach((chit) => chit.doneDeserializing());
212
213
 
213
- this.rootChit.value = this.findChit("root") as RootChit<any>;
214
+ this.rootChit.value = this.findChit("root") as RootChit<any>;
214
215
 
215
- // sometimes deserializing chits does not result in animations (maybe a pure texture change?)
216
- // in that case, we need to make sure that the clock moves forward
217
- setTimeout(() => this.clientTimeState.setAnimationState(animationKey, false), 100);
218
- } else {
216
+ // sometimes deserializing chits does not result in animations (maybe a pure texture change?)
217
+ // in that case, we need to make sure that the clock moves forward
218
+ setTimeout(() => this.clientTimeState.setAnimationState(animationKey, false), 100);
219
+ } else {
220
+ this.clientTimeState.setAnimationState(animationKey, false);
221
+ }
222
+ } catch (e) {
223
+ console.error(e);
219
224
  this.clientTimeState.setAnimationState(animationKey, false);
220
225
  }
221
226
  }
@@ -29,11 +29,13 @@ export class ServerPrompts<P extends PlayerChit, R extends RootChit<P>> extends
29
29
  if (newTurn) {
30
30
  unsubs = newTurn.rootChit.players.map((player) =>
31
31
  player.promptStatus.latestPrompt.on((latestPrompt: any) =>
32
- this.clientPrompts.setPromptForPlayer(
33
- player.playerId,
34
- latestPrompt?.serialize(),
35
- this.match.turn.value?.clockDetails(playerId),
36
- ),
32
+ this.clientPrompts
33
+ .setPromptForPlayer(
34
+ player.playerId,
35
+ latestPrompt?.serialize(),
36
+ this.match.turn.value?.clockDetails(playerId),
37
+ )
38
+ .catch((e: any) => console.error("Failed to send prompt to client:", e)),
37
39
  ),
38
40
  );
39
41
  }
@@ -51,14 +53,30 @@ export class ServerPrompts<P extends PlayerChit, R extends RootChit<P>> extends
51
53
  return this.match.turn.value?.rootChit.players;
52
54
  }
53
55
 
54
- async resolvePrompt(response: any): Promise<void | PromptSerialization> {
56
+ async resolvePrompt(promptId: string, response: any): Promise<void | PromptSerialization> {
55
57
  const player = this.playerChits?.find((p) => p.playerId === this.playerId);
56
58
  if (player && player.promptStatus.latestPrompt.value) {
59
+ const currentPrompt = player.promptStatus.latestPrompt.value;
60
+
61
+ if (currentPrompt.id !== promptId) {
62
+ console.warn(
63
+ `[ServerPrompts] Prompt ID mismatch for player ${this.playerId}: received "${promptId}", expected "${currentPrompt.id}". Ignoring resolution.`,
64
+ );
65
+ return currentPrompt.serialize();
66
+ }
67
+
68
+ if (!currentPrompt.canResolveResponse(response)) {
69
+ console.warn(
70
+ `[ServerPrompts] Prompt "${currentPrompt.id}" for player ${this.playerId} cannot resolve response (type=${currentPrompt.type}). Ignoring resolution.`,
71
+ );
72
+ return currentPrompt.serialize();
73
+ }
74
+
57
75
  let cb: (() => void) | undefined;
58
76
  const p = new Promise((resolve) => {
59
77
  cb = this.match.onChange(() => resolve(0), false);
60
78
  });
61
- player.promptStatus.latestPrompt.value.resolve(response);
79
+ currentPrompt.resolve(response);
62
80
  await p;
63
81
  if (cb) {
64
82
  cb();
@@ -18,13 +18,17 @@ export class ServerStatus<P extends PlayerChit, R extends RootChit<P>> extends C
18
18
 
19
19
  this.register(
20
20
  this.match.errorState.on((errorMessage) => {
21
- this.clientStatus.setErrorMessage(errorMessage);
21
+ this.clientStatus
22
+ .setErrorMessage(errorMessage)
23
+ .catch((e: any) => console.error("Failed to send error message to client:", e));
22
24
  }),
23
25
  );
24
26
 
25
27
  this.register(
26
28
  this.match.result.on((result) => {
27
- this.clientStatus.setMatchResult(result?.winners?.map((winner) => winner.id ?? ""));
29
+ this.clientStatus
30
+ .setMatchResult(result?.winners?.map((winner) => winner.id ?? ""))
31
+ .catch((e: any) => console.error("Failed to send match result to client:", e));
28
32
  }),
29
33
  );
30
34
  }
@@ -20,7 +20,9 @@ export class ServerTime<P extends PlayerChit, R extends RootChit<P>> extends Con
20
20
  this.register(
21
21
  match.onChange(() => {
22
22
  if (match.turn.value) {
23
- this.clientTime.newMaxClock(match.turn.value.clockDetails(this.playerId));
23
+ this.clientTime
24
+ .newMaxClock(match.turn.value.clockDetails(this.playerId))
25
+ .catch((e: any) => console.error("Failed to send newMaxClock to client:", e));
24
26
  }
25
27
 
26
28
  if (!this.hasSentLastActionTime) {
@@ -28,7 +30,9 @@ export class ServerTime<P extends PlayerChit, R extends RootChit<P>> extends Con
28
30
 
29
31
  const player = match.turn.value?.rootChit.players.find((p) => p.id === playerId);
30
32
  if (player) {
31
- this.clientTime.setStartTime(player.promptStatus.latestPromptResponseTime);
33
+ this.clientTime
34
+ .setStartTime(player.promptStatus.latestPromptResponseTime)
35
+ .catch((e: any) => console.error("Failed to send setStartTime to client:", e));
32
36
  }
33
37
  }
34
38
  }),
@@ -76,6 +76,9 @@ export function TimeControllerProvider({ children }: { children: ReactNode }) {
76
76
 
77
77
  if (!clientTime || clientTime.connection !== connection) {
78
78
  clientTime?.dispose();
79
+ if (clientTime?.clientPrompt) {
80
+ clientTime.clientPrompt.disconnect();
81
+ }
79
82
 
80
83
  const newClientTime = new ClientTime(connection, game, clientTimeState);
81
84
  connection.register(newClientTime);