@pretty-chitty/core 2.3.5 → 2.3.6

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pretty-chitty/core",
3
- "version": "2.3.5",
3
+ "version": "2.3.6",
4
4
  "license": "SEE LICENSE IN LICENSE.md",
5
5
  "description": "A TypeScript framework for building high-quality async or realtime 3D strategy board games",
6
6
  "author": "Pretty Chitty, LLC",
@@ -8,6 +8,7 @@ import { Vector2 } from "three";
8
8
  import { OrderedOutlet } from "./OrderedOutlet";
9
9
  import { SparkChit } from "./SparkChit";
10
10
  import StaticChitTypeRegistry from "./StaticChitTypeRegistry";
11
+ import { typeNameOfInstance } from "./typeName";
11
12
  import type { Game } from "./Game";
12
13
  import { IUpdatingCanvas } from "../utilities/IUpdatingCanvas";
13
14
  import { ImageSpec } from "../utilities/CanvasStack/CanvasOperations";
@@ -183,7 +184,7 @@ export class Chit extends ObjectWithProps {
183
184
 
184
185
  /** @internal */
185
186
  chitTypeName() {
186
- const result = Object.getPrototypeOf(this).constructor.name;
187
+ const result = typeNameOfInstance(this);
187
188
  if (this.parentFallback) {
188
189
  return `${result}-${this.parentFallback.id}-`;
189
190
  }
@@ -634,7 +635,7 @@ export class Chit extends ObjectWithProps {
634
635
  return acc;
635
636
  },
636
637
  {
637
- __chitType: Object.getPrototypeOf(this).constructor.name,
638
+ __chitType: typeNameOfInstance(this),
638
639
  __hiddenProps: playerIds ? this.hiddenPropertiesForSerialization(playerIds) : undefined,
639
640
  } as { [key: string]: any },
640
641
  ),
@@ -7,6 +7,7 @@ import { GalleryItemSource } from "../components/GalleryViewer";
7
7
  import { GalleryItemChitChildrenSource } from "./GalleryItemChitChildrenSource";
8
8
  import { GalleryItemRawSource } from "./GalleryItemRawSource";
9
9
  import { chitsToGalleryItems } from "../utilities/GalleryItemConversion";
10
+ import { setTypeName } from "./typeName";
10
11
 
11
12
  export type ButtonCallback = () => void | Promise<void>;
12
13
 
@@ -140,3 +141,4 @@ export class Confirm extends GameButton {
140
141
  /** @internal */
141
142
  canAutoResolve = false;
142
143
  }
144
+ setTypeName(Confirm, "Confirm");
@@ -3,6 +3,7 @@ import { GalleryItemChitChildrenSource } from "./GalleryItemChitChildrenSource";
3
3
  import { IButtonLibrary } from "./Game";
4
4
  import { Confirm, GameButton, ToggleGalleryButton } from "./GameButton";
5
5
  import { OrderedOutlet } from "./OrderedOutlet";
6
+ import { typeNameOfInstance } from "./typeName";
6
7
  import { PickPrompt } from "./Prompt";
7
8
  import { MismatchError, Turn } from "./Turn";
8
9
 
@@ -187,7 +188,7 @@ export class ChitPick<T extends Chit> extends Pick {
187
188
 
188
189
  if (this.button) {
189
190
  result.b = this.button.serialize();
190
- result.b.__buttonType = Object.getPrototypeOf(this.button).constructor.name;
191
+ result.b.__buttonType = typeNameOfInstance(this.button);
191
192
  }
192
193
 
193
194
  return result;
@@ -436,7 +437,7 @@ export class ButtonPick extends Pick {
436
437
  }
437
438
 
438
439
  const details = this.button.serialize();
439
- details.__buttonType = Object.getPrototypeOf(this.button).constructor.name;
440
+ details.__buttonType = typeNameOfInstance(this.button);
440
441
  details.__f = this.focusChits.map((chit) => chit.id);
441
442
  return details;
442
443
  }
@@ -3,6 +3,7 @@ import { EventChannel } from "../utilities/EventChannel";
3
3
  import { Chit } from "./Chit";
4
4
  import { Prompt } from "./Prompt";
5
5
  import StaticChitTypeRegistry from "./StaticChitTypeRegistry";
6
+ import { setTypeName } from "./typeName";
6
7
 
7
8
  export class PlayerPromptStatusChit extends Chit {
8
9
  /** Plain text of the prompt the player is currently being asked to answer (`:token:` markup resolved). @internal */
@@ -21,4 +22,5 @@ export class PlayerPromptStatusChit extends Chit {
21
22
  }
22
23
  }
23
24
 
25
+ setTypeName(PlayerPromptStatusChit, "PlayerPromptStatusChit");
24
26
  StaticChitTypeRegistry["PlayerPromptStatusChit"] = PlayerPromptStatusChit;
@@ -4,6 +4,7 @@ import { Vector2 } from "three";
4
4
  import { NonEditable } from "../utilities/Annotations";
5
5
  import { PlayerChit } from "./PlayerChit";
6
6
  import StaticChitTypeRegistry from "./StaticChitTypeRegistry";
7
+ import { setTypeName } from "./typeName";
7
8
  import { IUpdatingCanvas } from "../utilities/IUpdatingCanvas";
8
9
 
9
10
  export class SparkChit extends Chit {
@@ -82,6 +83,7 @@ export class SparkChit extends Chit {
82
83
  }
83
84
  }
84
85
 
86
+ setTypeName(SparkChit, "SparkChit");
85
87
  StaticChitTypeRegistry["SparkChit"] = SparkChit;
86
88
 
87
89
  export abstract class BagSparkChit<T extends Chit> extends SparkChit {
@@ -0,0 +1,51 @@
1
+ import { describe, expect, test } from "vitest";
2
+
3
+ import { Chit } from "./Chit";
4
+ import { Game } from "./Game";
5
+ import { Confirm } from "./GameButton";
6
+ import { SparkChit } from "./SparkChit";
7
+ import { setTypeName, typeNameOf, typeNameOfInstance } from "./typeName";
8
+
9
+ /** Simulate a bundler renaming a class (`Card` → `Card2`). */
10
+ function renamed<T extends abstract new () => unknown>(ctor: T, name: string): T {
11
+ Object.defineProperty(ctor, "name", { value: name, configurable: true });
12
+ return ctor;
13
+ }
14
+
15
+ describe("typeName", () => {
16
+ test("falls back to constructor.name", () => {
17
+ class Plain extends Chit {}
18
+ expect(typeNameOf(Plain)).toBe("Plain");
19
+ });
20
+
21
+ test("pinned name wins over a renamed constructor", () => {
22
+ const Card = renamed(class Card extends Chit {}, "Card2");
23
+ setTypeName(Card, "Card");
24
+ expect(typeNameOf(Card)).toBe("Card");
25
+ expect(typeNameOfInstance(new Card())).toBe("Card");
26
+ });
27
+
28
+ test("subclasses do not inherit a parent's pinned name", () => {
29
+ class Card extends Chit {}
30
+ setTypeName(Card, "Card");
31
+ class SpecialCard extends Card {}
32
+ expect(typeNameOf(SpecialCard)).toBe("SpecialCard");
33
+ });
34
+
35
+ test("engine built-ins are pinned", () => {
36
+ expect(typeNameOf(SparkChit)).toBe("SparkChit");
37
+ expect(typeNameOf(Confirm)).toBe("Confirm");
38
+ });
39
+
40
+ test("serialize/deflate round-trips through a renamed class", () => {
41
+ const Card = renamed(class Card extends Chit {}, "Card2");
42
+ setTypeName(Card, "Card");
43
+ const game = { chitLibrary: { Card } } as unknown as Game<any, any>;
44
+
45
+ const card = new Card();
46
+ card.id = "c1";
47
+ const serialized = card.serialize();
48
+ expect(JSON.parse(serialized).__chitType).toBe("Card");
49
+ expect(Chit.deflate(serialized, game)).toBeInstanceOf(Card);
50
+ });
51
+ });
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Static property holding a class's serialized type name (`__chitType` / `__buttonType`).
3
+ *
4
+ * Bundlers may rename classes (minification, or `Card` → `Card2` to avoid collisions), so
5
+ * `constructor.name` is not stable across builds. Setting this on a class pins the name that
6
+ * gets written to saved state, and it must match that class's key in `chitLibrary` / `buttonLibrary`.
7
+ */
8
+ export const TYPE_NAME_KEY = "__typeName";
9
+
10
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
11
+ type AnyClass = abstract new (...args: any[]) => unknown;
12
+
13
+ /**
14
+ * Pin the serialized type name for a chit or button class.
15
+ *
16
+ * ```ts
17
+ * setTypeName(Card, "Card");
18
+ * ```
19
+ */
20
+ export function setTypeName(ctor: AnyClass, name: string) {
21
+ Object.defineProperty(ctor, TYPE_NAME_KEY, { value: name, writable: true, configurable: true, enumerable: false });
22
+ }
23
+
24
+ /**
25
+ * The serialized type name for a class: its own pinned `__typeName`, else `constructor.name`.
26
+ *
27
+ * Only an *own* property counts. Statics are inherited, so a subclass that wasn't stamped
28
+ * must not report its parent's name.
29
+ */
30
+ export function typeNameOf(ctor: AnyClass): string {
31
+ if (Object.prototype.hasOwnProperty.call(ctor, TYPE_NAME_KEY)) {
32
+ return (ctor as any)[TYPE_NAME_KEY];
33
+ }
34
+ return ctor.name;
35
+ }
36
+
37
+ /** `typeNameOf` for an instance. */
38
+ export function typeNameOfInstance(instance: object): string {
39
+ return typeNameOf(Object.getPrototypeOf(instance).constructor);
40
+ }
@@ -6,6 +6,7 @@ export type { GameMetaData } from "./game/GameMetaData";
6
6
  // NOTE: must be before Turn! or circular dependency!
7
7
  /** @group Chits */
8
8
  export { Chit } from "./game/Chit";
9
+ export { setTypeName, typeNameOf } from "./game/typeName";
9
10
 
10
11
  /** @group Core Game Elements */
11
12
  export { Turn } from "./game/Turn";
@@ -159,22 +159,59 @@ export class CanvasStack implements IUpdatingCanvas {
159
159
  private static _pendingFontRedraws = new Set<CanvasStack>();
160
160
  private static _fontRedrawScheduled = false;
161
161
 
162
+ // Records the font as it was *set*, not as ctx.font reads back: WebKit's getter drops the weight ("700 27px X"
163
+ // reads "27px X"), so tracking the read-back only ever checked the regular face. Once that had loaded, bold text
164
+ // drawn in the fallback while its own face was still downloading looked loaded and never redrew (the ghosted
165
+ // titles and re-wrapped bodies on iPhone). save/restore carry the set value the way the context carries its font.
162
166
  private _trackFonts(ctx: CanvasRenderingContext2D) {
167
+ const fontProp = Object.getOwnPropertyDescriptor(CanvasRenderingContext2D.prototype, "font");
168
+ let current = ctx.font;
169
+ if (fontProp?.get && fontProp.set) {
170
+ const { get, set } = fontProp;
171
+ const saved: string[] = [];
172
+ Object.defineProperty(ctx, "font", {
173
+ configurable: true,
174
+ get: () => get.call(ctx),
175
+ set: (value: string) => {
176
+ set.call(ctx, value);
177
+ current = value;
178
+ },
179
+ });
180
+ const save = ctx.save;
181
+ const restore = ctx.restore;
182
+ ctx.save = () => {
183
+ saved.push(current);
184
+ save.call(ctx);
185
+ };
186
+ ctx.restore = () => {
187
+ if (saved.length > 0) current = saved.pop()!;
188
+ restore.call(ctx);
189
+ };
190
+ }
163
191
  for (const name of ["fillText", "strokeText", "measureText"] as const) {
164
192
  const original = ctx[name] as (...args: unknown[]) => unknown;
165
193
  (ctx as any)[name] = (...args: unknown[]) => {
166
- this._fontsUsed.add(ctx.font);
194
+ this._fontsUsed.add(current);
167
195
  return original.apply(ctx, args);
168
196
  };
169
197
  }
170
198
  }
171
199
 
200
+ /** check() throws on a string that isn't a valid font (the context ignored that assignment); treat it as loaded. */
201
+ private static fontLoaded(font: string): boolean {
202
+ try {
203
+ return document.fonts.check(font);
204
+ } catch {
205
+ return true;
206
+ }
207
+ }
208
+
172
209
  private _noteUnloadedFonts() {
173
210
  this._unloadedFonts.clear();
174
211
  const fonts = typeof document !== "undefined" ? document.fonts : undefined;
175
212
  if (!fonts) return;
176
213
  for (const font of this._fontsUsed) {
177
- if (fonts.check(font)) continue;
214
+ if (CanvasStack.fontLoaded(font)) continue;
178
215
  this._unloadedFonts.add(font);
179
216
  CanvasStack.whenFontLoads(font);
180
217
  }
@@ -182,7 +219,7 @@ export class CanvasStack implements IUpdatingCanvas {
182
219
 
183
220
  /** A font this stack drew with before it loaded has loaded since: its pixels are stale. */
184
221
  private _fontsArrived(): boolean {
185
- for (const font of this._unloadedFonts) if (document.fonts.check(font)) return true;
222
+ for (const font of this._unloadedFonts) if (CanvasStack.fontLoaded(font)) return true;
186
223
  return false;
187
224
  }
188
225