castle-web-cli 0.4.230 → 0.4.231

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 (69) hide show
  1. package/dist/castle-host/host.js +81 -0
  2. package/dist/devSaveStorage.d.ts +36 -0
  3. package/dist/devSaveStorage.js +469 -0
  4. package/dist/devSessionChild.js +22 -12
  5. package/dist/devSessionServer.js +8 -2
  6. package/dist/devSessionStorage.d.ts +9 -0
  7. package/dist/devSessionStorage.js +66 -1
  8. package/dist/init.js +1 -1
  9. package/dist/serve.js +5 -1
  10. package/kits/base/castle.json +1 -1
  11. package/kits/base/sdk/README.md +148 -1
  12. package/kits/base/sdk/castle.d.ts +4 -0
  13. package/kits/base/sdk/castle.js +2 -0
  14. package/kits/base/sdk/commands.d.ts +15 -0
  15. package/kits/base/sdk/multiplayer.js +52 -4
  16. package/kits/base/sdk/save.d.ts +197 -0
  17. package/kits/base/sdk/save.js +525 -0
  18. package/kits/base/sdk/saveCoordinator.d.ts +39 -0
  19. package/kits/base/sdk/saveCoordinator.js +252 -0
  20. package/kits/base/sdk/server/storage.d.ts +3 -2
  21. package/kits/base/sdk/server/storage.js +25 -5
  22. package/kits/base/sdk/server/wrapper.d.ts +4 -0
  23. package/kits/base/sdk/server/wrapper.js +2 -0
  24. package/kits/base/sdk/store.d.ts +3 -2
  25. package/kits/base/sdk/store.js +5 -0
  26. package/kits/hub-game/CLAUDE.md +4 -1
  27. package/kits/hub-game/code/client/chrome.js +43 -9
  28. package/kits/hub-game/code/client/grab.js +142 -7
  29. package/kits/hub-game/code/client/hookLayer.js +7 -1
  30. package/kits/hub-game/code/client/state.js +13 -1
  31. package/kits/hub-game/code/client/talk.js +10 -36
  32. package/kits/hub-game/code/client/tiers.js +480 -0
  33. package/kits/hub-game/code/client/together.js +78 -3
  34. package/kits/hub-game/code/server/grab.js +3 -2
  35. package/kits/hub-game/code/server/hub.js +99 -5
  36. package/kits/hub-game/code/server/manifest.js +34 -7
  37. package/kits/hub-game/code/server/npcs.js +21 -33
  38. package/kits/hub-game/code/server/party.js +64 -6
  39. package/kits/hub-game/code/systems/hub.js +133 -16
  40. package/kits/hub-game/docs/contract.md +84 -14
  41. package/kits/hub-game/package.json +1 -1
  42. package/kits/hub-game/scripts/test-grab-client.mjs +328 -0
  43. package/kits/hub-game/scripts/test-hub-trip.mjs +208 -0
  44. package/kits/hub-game/scripts/test-manifest.mjs +47 -1
  45. package/kits/hub-game/scripts/test-npcs.mjs +34 -24
  46. package/kits/hub-game/scripts/test-party.mjs +87 -4
  47. package/kits/hub-game/scripts/test-tiers.mjs +666 -0
  48. package/kits/hub-game/scripts/test-together.mjs +33 -1
  49. package/kits/physics-2d/CLAUDE.md +2 -0
  50. package/kits/physics-2d/castle.json +2 -2
  51. package/kits/physics-2d/engine/scene.js +92 -0
  52. package/kits/physics-2d/package.json +1 -1
  53. package/kits/physics-2d/scripts/test-skip-unchanged.mjs +254 -0
  54. package/kits/physics-3d/CLAUDE.md +279 -0
  55. package/kits/physics-3d/behaviors/Player.jsx +74 -1
  56. package/kits/physics-3d/castle.json +3 -3
  57. package/kits/physics-3d/engine3d/Scene3DPlayer.jsx +1 -1
  58. package/kits/physics-3d/engine3d/actornode.js +253 -0
  59. package/kits/physics-3d/engine3d/nearshadows.js +600 -0
  60. package/kits/physics-3d/engine3d/unchanged.js +153 -0
  61. package/kits/physics-3d/engine3d/world3d.js +465 -7
  62. package/kits/physics-3d/package.json +1 -1
  63. package/kits/physics-3d/scripts/test-camera-follow.mjs +533 -0
  64. package/kits/physics-3d/scripts/test-near-shadows.mjs +1073 -0
  65. package/kits/physics-3d/scripts/test-static-actors.mjs +662 -0
  66. package/kits/physics-3d/scripts/test-static-passes.mjs +459 -0
  67. package/kits/physics-3d/scripts/test-static-physics.mjs +128 -0
  68. package/kits/physics-3d/systems/physics3d.js +182 -3
  69. package/package.json +1 -1
@@ -0,0 +1,252 @@
1
+ import { asSaveError, encodeSaveInput, matchSaveTarget, SaveError, saveTargetKey, } from "./save";
2
+ // The request is built when a save is first sent, from the revisions known then.
3
+ function buildRequest(intent, access, revisions, writers) {
4
+ const changes = intent.changes.map((change) => {
5
+ const key = saveTargetKey(change.target);
6
+ const expectedRevision = change.expectedRevision === undefined
7
+ ? revisions.get(key)
8
+ : change.expectedRevision;
9
+ if (expectedRevision === undefined) {
10
+ throw new SaveError({
11
+ code: "CAULDRON_STORAGE_INVALID_ARGUMENT",
12
+ message: "Load a target's revision before saving it.",
13
+ operationId: intent.operationId,
14
+ retryable: false,
15
+ committed: false,
16
+ target: change.target,
17
+ });
18
+ }
19
+ const writer = change.writer ?? writers.get(key);
20
+ return {
21
+ ...change,
22
+ expectedRevision,
23
+ ...(writer === undefined ? {} : { writer }),
24
+ };
25
+ });
26
+ return {
27
+ operationId: intent.operationId,
28
+ expectedAccess: access,
29
+ ...(intent.checks ? { checks: intent.checks } : {}),
30
+ changes,
31
+ };
32
+ }
33
+ // A committed error with its receipt is a repeat of a save that committed
34
+ // earlier, whose fresh reply failed for some other reason.
35
+ async function send(api, request) {
36
+ try {
37
+ return await api.transaction(request);
38
+ }
39
+ catch (failure) {
40
+ const error = asSaveError(failure, request.operationId);
41
+ if (error.committed === true && error.receipt)
42
+ return error.receipt;
43
+ throw error;
44
+ }
45
+ }
46
+ // An unknown outcome is not a cancellation: the first request may still
47
+ // arrive. So it is looked up, then sent again exactly as before.
48
+ async function settle(api, request) {
49
+ try {
50
+ return await send(api, request);
51
+ }
52
+ catch (error) {
53
+ if (error.committed !== "unknown")
54
+ throw error;
55
+ }
56
+ let found;
57
+ try {
58
+ found = await api.operation(request.operationId);
59
+ }
60
+ catch (failure) {
61
+ const error = asSaveError(failure, request.operationId);
62
+ throw new SaveError({
63
+ ...error.extensions,
64
+ code: error.code,
65
+ message: error.message,
66
+ operationId: request.operationId,
67
+ retryable: error.retryable,
68
+ committed: "unknown",
69
+ });
70
+ }
71
+ if (found.state === "committed")
72
+ return found.receipt;
73
+ return send(api, request);
74
+ }
75
+ /**
76
+ * Starts from a snapshot of the targets to be saved and the writers of any
77
+ * claimed ones. Keep the coordinator where it outlives a replaceable worker.
78
+ */
79
+ export function createSaveCoordinator(api, snapshot, writers = []) {
80
+ const access = snapshot.access;
81
+ const revisions = new Map(snapshot.targets.map((entry) => [
82
+ saveTargetKey(entry.target),
83
+ entry.revision,
84
+ ]));
85
+ const writerTokens = new Map(writers.map((entry) => [saveTargetKey(entry.target), entry.writer]));
86
+ const submittedIds = new Set();
87
+ const queue = [];
88
+ let flushes = [];
89
+ let blocked;
90
+ let running;
91
+ function apply(receipt, request) {
92
+ const targets = request.changes.map((change) => change.target);
93
+ for (const entry of receipt.revisions) {
94
+ const target = matchSaveTarget(entry.target, targets);
95
+ revisions.set(saveTargetKey(target), entry.revision);
96
+ }
97
+ }
98
+ function block(item, error) {
99
+ blocked = error;
100
+ if (error.committed === false && !error.retryable) {
101
+ item.failed = true;
102
+ item.reject(error);
103
+ }
104
+ for (const flush of flushes)
105
+ flush.reject(error);
106
+ flushes = [];
107
+ }
108
+ function commit(item, receipt) {
109
+ queue.shift();
110
+ item.resolve(receipt);
111
+ flushes = flushes.filter((flush) => {
112
+ if (flush.last !== item)
113
+ return true;
114
+ flush.resolve();
115
+ return false;
116
+ });
117
+ }
118
+ async function drain() {
119
+ while (queue.length > 0 && !blocked) {
120
+ const item = queue[0];
121
+ try {
122
+ item.request ??= buildRequest(item.intent, access, revisions, writerTokens);
123
+ const receipt = await settle(api, item.request);
124
+ apply(receipt, item.request);
125
+ commit(item, receipt);
126
+ }
127
+ catch (failure) {
128
+ block(item, asSaveError(failure, item.intent.operationId));
129
+ }
130
+ }
131
+ }
132
+ // A save submitted while the last drain was finishing finds it still running,
133
+ // so the drain looks again once it is done.
134
+ function start() {
135
+ running ??= drain().finally(() => {
136
+ running = undefined;
137
+ if (queue.length > 0 && !blocked)
138
+ void start();
139
+ });
140
+ return running;
141
+ }
142
+ return {
143
+ get status() {
144
+ if (blocked)
145
+ return "blocked";
146
+ return queue.length > 0 ? "pending" : "saved";
147
+ },
148
+ get error() {
149
+ return blocked;
150
+ },
151
+ get pendingOperationIds() {
152
+ return queue
153
+ .filter((item) => !item.failed)
154
+ .map((item) => item.intent.operationId);
155
+ },
156
+ revision: (target) => revisions.get(saveTargetKey(target)),
157
+ submit(input) {
158
+ if (submittedIds.has(input.operationId)) {
159
+ return Promise.reject(new SaveError({
160
+ code: "CAULDRON_STORAGE_OPERATION_MISMATCH",
161
+ message: "This coordinator already has that operation id.",
162
+ operationId: input.operationId,
163
+ retryable: false,
164
+ committed: false,
165
+ }));
166
+ }
167
+ // Encoding validates and copies the save, so later changes to the
168
+ // caller's objects do not reach it.
169
+ let intent;
170
+ try {
171
+ const encoded = encodeSaveInput("transaction", {
172
+ operationId: input.operationId,
173
+ expectedAccess: access,
174
+ ...(input.checks ? { checks: input.checks } : {}),
175
+ changes: input.changes.map((change) => ({
176
+ ...change,
177
+ expectedRevision: change.expectedRevision ?? null,
178
+ })),
179
+ });
180
+ intent = {
181
+ operationId: encoded.operationId,
182
+ ...(encoded.checks ? { checks: encoded.checks } : {}),
183
+ changes: encoded.changes.map((change, index) => ({
184
+ ...change,
185
+ expectedRevision: input.changes[index].expectedRevision,
186
+ })),
187
+ };
188
+ }
189
+ catch (error) {
190
+ return Promise.reject(asSaveError(error, input.operationId));
191
+ }
192
+ submittedIds.add(input.operationId);
193
+ const promise = new Promise((resolve, reject) => {
194
+ queue.push({ intent, failed: false, resolve, reject });
195
+ });
196
+ // A deck may watch status or flush() instead of every save's promise.
197
+ promise.catch(() => { });
198
+ void start();
199
+ return promise;
200
+ },
201
+ flush() {
202
+ const last = queue.at(-1);
203
+ if (!last)
204
+ return Promise.resolve();
205
+ if (blocked)
206
+ return Promise.reject(blocked);
207
+ return new Promise((resolve, reject) => {
208
+ flushes.push({ last, resolve, reject });
209
+ });
210
+ },
211
+ async retry() {
212
+ await running;
213
+ if (!blocked)
214
+ return;
215
+ if (queue[0]?.failed)
216
+ throw blocked;
217
+ if (blocked.retryAfterMs !== undefined && blocked.retryAfterMs > 0) {
218
+ const delay = blocked.retryAfterMs;
219
+ await new Promise((resolve) => setTimeout(resolve, delay));
220
+ }
221
+ blocked = undefined;
222
+ return start().then(() => {
223
+ if (blocked)
224
+ throw blocked;
225
+ });
226
+ },
227
+ discardUnsent() {
228
+ const error = new SaveError({
229
+ code: "CAULDRON_STORAGE_CANCELLED",
230
+ message: "The save was discarded before it was sent.",
231
+ retryable: false,
232
+ committed: false,
233
+ });
234
+ for (let index = queue.length - 1; index >= 0; index--) {
235
+ const item = queue[index];
236
+ if (item.request || item.failed)
237
+ continue;
238
+ queue.splice(index, 1);
239
+ item.reject(error);
240
+ }
241
+ // A flush still waits for the sent save ahead of what was dropped.
242
+ flushes = flushes.filter((flush) => {
243
+ if (!flush.last || !queue.includes(flush.last))
244
+ flush.last = queue[0];
245
+ if (flush.last)
246
+ return true;
247
+ flush.resolve();
248
+ return false;
249
+ });
250
+ },
251
+ };
252
+ }
@@ -1,6 +1,7 @@
1
1
  import type { Json } from "../types";
2
2
  import type { CharacterHistory, CharacterOperation } from "../commands";
3
3
  import type { PlatformHandle } from "./platformHandle";
4
+ import { type SaveApi, type SaveBucketApi } from "../save";
4
5
  export interface ServerStorageListOptions {
5
6
  prefix?: string;
6
7
  limit?: number;
@@ -15,7 +16,7 @@ export interface ServerStorageListPage<T extends Json = Json> {
15
16
  /** Null means there is nothing left. A short page alone does not mean that. */
16
17
  cursor: string | null;
17
18
  }
18
- export interface ServerStorageScope {
19
+ export interface ServerStorageScope extends SaveBucketApi {
19
20
  get<T extends Json = Json>(keys: string[]): Promise<Record<string, T>>;
20
21
  set(values: Record<string, Json>): Promise<void>;
21
22
  remove(keys: string[]): Promise<void>;
@@ -257,7 +258,7 @@ export interface ServerCharacterHistoryOptions {
257
258
  limit?: number;
258
259
  cursor?: string | null;
259
260
  }
260
- export interface ServerStorage {
261
+ export interface ServerStorage extends SaveApi {
261
262
  /** Shared by everyone playing the deck, and owned by this server. */
262
263
  readonly deck: ServerStorageScope;
263
264
  /** One player's public data. Readable by anyone; writable by them or by this server. */
@@ -1,5 +1,6 @@
1
1
  import { chunked } from "../chunk";
2
2
  import { decodeStorageValue, encodeStorageValue, storageError, } from "../storageJson";
3
+ import { createSaveApi, createSaveBucket, preflightSaveRequest, SaveError, } from "../save";
3
4
  // Deck storage for an author's session server.
4
5
  //
5
6
  // The same store the deck's clients use, reached over the platform channel instead of
@@ -56,8 +57,26 @@ export function createServerStorage(platformHandle) {
56
57
  const result = await platformHandle.storage(op, JSON.stringify(args));
57
58
  return JSON.parse(result);
58
59
  };
60
+ // The host forwards these args to the platform's storage route unchanged,
61
+ // which takes a save's request as `input` and a lookup as `operationId`.
62
+ const saveApi = createSaveApi(async (verb, input) => {
63
+ if (typeof platformHandle.storage !== "function" ||
64
+ platformHandle.storageEnabled === false) {
65
+ throw new SaveError({
66
+ code: "CAULDRON_STORAGE_UNAVAILABLE",
67
+ message: "Storage is not available to this session.",
68
+ operationId: input.operationId,
69
+ retryable: false,
70
+ committed: false,
71
+ });
72
+ }
73
+ const args = verb === "operation" ? input : { input };
74
+ preflightSaveRequest(verb, args, MAX_REQUEST_BYTES);
75
+ return call(verb, args);
76
+ }, true);
59
77
  return {
60
- deck: createScope(call, "DECK", null),
78
+ ...saveApi,
79
+ deck: createScope(call, "DECK", null, saveApi),
61
80
  user(userId) {
62
81
  // A bad id poisons the scope rather than throwing here, so the failure arrives
63
82
  // the same way every other failure does -- as a rejection the author can await.
@@ -65,12 +84,12 @@ export function createServerStorage(platformHandle) {
65
84
  // resolved by the platform to the deck's creator, quietly writing the wrong
66
85
  // player's bucket, so nothing is sent either.
67
86
  if (typeof userId !== "string" || userId.length === 0) {
68
- return createScope(rejectMissingSubject, "USER", null);
87
+ return createScope(rejectMissingSubject, "USER", null, saveApi);
69
88
  }
70
89
  if (utf8Length(userId) > MAX_SUBJECT_BYTES) {
71
- return createScope(rejectOversizeSubject, "USER", null);
90
+ return createScope(rejectOversizeSubject, "USER", userId, saveApi);
72
91
  }
73
- return createScope(call, "USER", userId);
92
+ return createScope(call, "USER", userId, saveApi);
74
93
  },
75
94
  board(name) {
76
95
  return createBoard(call, name);
@@ -224,8 +243,9 @@ function createPlaythrough(call, subject, generation) {
224
243
  },
225
244
  });
226
245
  }
227
- function createScope(call, scope, subject) {
246
+ function createScope(call, scope, subject, saveApi) {
228
247
  return {
248
+ ...createSaveBucket(saveApi, scope === "DECK" ? "deck" : "user", subject ?? undefined),
229
249
  async get(keys) {
230
250
  // A bare array, not a wrapper: the platform hands back exactly what the
231
251
  // storage verb returns, and `get` returns its entries directly.
@@ -4,6 +4,10 @@ import type { MultiplayerWorldCharacterCommand, MultiplayerWorldCharacterCommand
4
4
  import { type ServerStorage } from "./storage";
5
5
  import { type MultiplayerHubArrival, type MultiplayerServerHub } from "./hub";
6
6
  export type { MultiplayerSessionMode, PlatformHandle, PlatformSessionConfig, PlatformWorldCheckpoint, PlatformWorldSnapshot, PlatformWorldTimeConfig, PlayerIdentity, } from "./platformHandle";
7
+ export { createSaveCoordinator } from "../saveCoordinator";
8
+ export type { CoordinatedChange, CoordinatedSave, SaveCoordinator, SaveStatus, } from "../saveCoordinator";
9
+ export { SaveError } from "../save";
10
+ export type { SaveApi, SaveBucketApi, SaveBucketRead, SaveChange, SaveCheck, SaveClaimed, SaveClaimInput, SaveErrorEnvelope, SaveInitial, SaveInitializeInput, SaveOpened, SaveOperation, SaveReadTarget, SaveReceipt, SaveRevision, SaveRows, SaveScope, SaveSelection, SaveSnapshot, SaveTarget, SaveTransactionInput, SaveWriter, } from "../save";
7
11
  export type { MultiplayerHubArrival, MultiplayerHubBoard, MultiplayerHubOutcome, MultiplayerHubPadUpdateInput, MultiplayerHubPadUpdateResult, MultiplayerHubPlayerResults, MultiplayerHubRecord, MultiplayerHubReportReceipt, MultiplayerHubResultInput, MultiplayerHubResultRow, MultiplayerHubResultShape, MultiplayerHubResultsRead, MultiplayerHubResultsReadInput, MultiplayerHubWearable, MultiplayerHubWearReceipt, MultiplayerServerHub, } from "./hub";
8
12
  export type { CharacterActionNotice, CharacterGameStateOperation, CharacterGameStateResult, CharacterKnowledgeDeliveryOperation, CharacterKnowledgeDeliveryResult, CharacterKnowledgeSource, CompleteCharacterBeatInput, DeliverCharacterKnowledgeInput, RecordCharacterEventInput, SetCharacterGameStateInput, ShareCharacterClaimInput, ServerStorage, ServerStorageBoard, ServerStorageBoardScore, ServerStorageListEntry, ServerStorageListOptions, ServerStorageListPage, ServerPlaythrough, ServerPlaythroughCharacters, ServerCharacterHistoryOptions, ServerStorageScope, } from "./storage";
9
13
  export interface MultiplayerServerPlayer extends PlayerIdentity {
@@ -2,6 +2,8 @@ import { isBinaryPayload, toUint8Array, } from "../multiplayerProtocol";
2
2
  import { encodeStorageValue, storageError } from "../storageJson";
3
3
  import { createServerStorage } from "./storage";
4
4
  import { createServerHub, hubArrival, recordHiddenUserIds, } from "./hub";
5
+ export { createSaveCoordinator } from "../saveCoordinator";
6
+ export { SaveError } from "../save";
5
7
  // The publish bundler binds the author's default callbacks export once and
6
8
  // exports the returned one-argument function as `__castleBootSession`.
7
9
  export function createCastleSessionBoot(callbacks) {
@@ -1,5 +1,6 @@
1
1
  import type { StoreAllowance } from "./commands";
2
2
  import type { Json } from "./types";
3
+ import { type SaveApi, type SaveBucketApi } from "./save";
3
4
  export interface StoreListOptions {
4
5
  /** Only keys beginning with this. Omit for every key in the scope. */
5
6
  prefix?: string;
@@ -21,7 +22,7 @@ export interface StoreListPage<T extends Json = Json> {
21
22
  */
22
23
  cursor: string | null;
23
24
  }
24
- export interface StoreScopeApi {
25
+ export interface StoreScopeApi extends SaveBucketApi {
25
26
  /** Reads keys. Keys with no value are absent from the result. */
26
27
  get<T extends Json = Json>(keys: string[]): Promise<Record<string, T>>;
27
28
  /**
@@ -63,7 +64,7 @@ export interface StoreUsage {
63
64
  /** `Store.deck`: one allowance shared by every player of the deck. */
64
65
  shared: StoreAllowance;
65
66
  }
66
- export interface CastleStoreApi {
67
+ export interface CastleStoreApi extends SaveApi {
67
68
  /** Shared by everyone playing the deck. */
68
69
  readonly deck: StoreScopeApi;
69
70
  /** The current player's data, which other players can read. */
@@ -2,6 +2,7 @@ import { chunked } from "./chunk";
2
2
  import { decodeStorageValue, encodeStorageValue, storageError } from "./storageJson";
3
3
  import { hostRequest } from "./transport";
4
4
  import { onUnloadFlush } from "./unloadFlush";
5
+ import { createSaveApi, createSaveBucket, } from "./save";
5
6
  // Per-key deck storage for Cauldron decks.
6
7
  //
7
8
  // The older Storage/SharedStorage keep one document per bucket and rewrite the
@@ -212,6 +213,7 @@ function assertKeys(keys, operation) {
212
213
  }
213
214
  function createScope(scope, subject) {
214
215
  return {
216
+ ...createSaveBucket(saveApi, scope, subject ?? undefined),
215
217
  async get(keys) {
216
218
  const { entries } = await hostRequest("cauldronStorage.get", {
217
219
  scope,
@@ -309,7 +311,10 @@ async function usage() {
309
311
  const { usage: allowances } = await hostRequest("cauldronStorage.usage", {});
310
312
  return { player: allowances.player, shared: allowances.shared };
311
313
  }
314
+ // Saves skip the write coalescing above: each is one request, sent at once.
315
+ const saveApi = createSaveApi((verb, input) => hostRequest(`cauldronStorage.${verb}`, input));
312
316
  export const Store = {
317
+ ...saveApi,
313
318
  deck: createScope("deck", null),
314
319
  me: createScope("user", null),
315
320
  user(userId) {
@@ -72,7 +72,10 @@ it is what every published hub game depends on.
72
72
  optional hook `grab(hub, playerId, actorId, op)` hears each `'grab'` and
73
73
  `'throw'` and refuses a grab by returning `false`; `hub.drop(playerId?)`
74
74
  makes holders let go (a goal, a whistle), `hub.holding(playerId)` says what
75
- someone holds. Never a player, one object at a time.
75
+ someone holds. Never a player, one object at a time. `reach` (1.6-3 m) and
76
+ `steady: true` (contract v1.22) offer objects from farther away and keep
77
+ the button up through a moment at the reach, the cone or a shared owner --
78
+ for places played on phones.
76
79
  - **Idle play** (contract v1.6): `"idle": true` in the `hub` block (or
77
80
  `{ emotes, seats, sounds: ["sounds/x.mp3"] }`) gives players an emote picker
78
81
  (wave, dance, cheer, bow, spin, drawn on their avatar) and Sit on scene
@@ -1,8 +1,8 @@
1
1
  // The hub's own chrome: DOM drawn by the place, never by a game's content, so a
2
2
  // game cannot hide or fake it (contract: "Hub-owned UI"). The door cover, the
3
3
  // Back control, the declared HUD, actor labels and speech, the result ribbon,
4
- // the avatar picker, the NPC talk button and panel, a town's door list (jump
5
- // to a door), the people here and the player's friends, each friend with
4
+ // the avatar picker (with a Graphics row in a deck with device tiers), the NPC
5
+ // talk button and panel, a town's door list (jump to a door), the people here and the player's friends, each friend with
6
6
  // where they are and Join, each player with Report (where the host takes
7
7
  // reports), the pointers to friends out of sight,
8
8
  // the Grab / Throw button (a place with `grab`, v1.3), the emote picker and
@@ -174,6 +174,26 @@ export function makeChrome({ onBack, onAvatar, avatarCount, onPerson = () => {},
174
174
  }
175
175
  const pickerToggle = el('button', { padding: '8px 14px', borderRadius: '18px', border: '1px solid rgba(255,255,255,0.4)', background: 'rgba(20,16,12,0.72)', color: '#fff', font: 'inherit', cursor: 'pointer' }, picker);
176
176
  pickerToggle.textContent = 'Character';
177
+ // Graphics: Auto / Low / High, under the characters, in a deck that has
178
+ // device tiers (`tiers.js`). Built on the first `setGraphics`, so a deck
179
+ // without them draws the card as it always was.
180
+ let graphics = null;
181
+ function buildGraphics() {
182
+ const row = el('div', { display: 'flex', alignItems: 'center', gap: '6px', marginTop: '2px' }, pickerCard);
183
+ el('div', { fontSize: '12px', opacity: '0.8', flex: '1' }, row).textContent = 'Graphics';
184
+ const buttons = new Map();
185
+ for (const [mode, text] of [['auto', 'Auto'], ['low', 'Low'], ['high', 'High']]) {
186
+ const button = el('button', { padding: '4px 9px', borderRadius: '12px', border: '1px solid rgba(255,255,255,0.4)', background: 'rgba(20,16,12,0.7)', color: '#fff', font: '600 12px system-ui, sans-serif', cursor: 'pointer' }, row);
187
+ button.textContent = text;
188
+ button.setAttribute('aria-label', `Graphics: ${text}`);
189
+ button.addEventListener('pointerdown', (event) => {
190
+ event.stopPropagation();
191
+ graphics.onPick(mode);
192
+ });
193
+ buttons.set(mode, button);
194
+ }
195
+ return { buttons, onPick: () => {} };
196
+ }
177
197
  pickerToggle.addEventListener('pointerdown', (event) => {
178
198
  event.stopPropagation();
179
199
  setPickerOpen(!pickerOpen);
@@ -196,7 +216,6 @@ export function makeChrome({ onBack, onAvatar, avatarCount, onPerson = () => {},
196
216
  event.stopPropagation();
197
217
  talkHandlers.end();
198
218
  });
199
- const panelNote = el('div', { fontSize: '11px', opacity: '0.65', fontWeight: '500' }, panel);
200
219
  const panelLog = el('div', { maxHeight: '28vh', overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: '4px', fontSize: '14px', fontWeight: '500' }, panel);
201
220
  // Not a <form>: castle.xyz plays a deck in a frame sandboxed without
202
221
  // `allow-forms`, where a form's submission (Enter, or a submit button) is
@@ -597,6 +616,15 @@ export function makeChrome({ onBack, onAvatar, avatarCount, onPerson = () => {},
597
616
  button.style.borderColor = i === selected ? '#f2c94c' : 'rgba(255,255,255,0.4)';
598
617
  });
599
618
  },
619
+ // The Graphics row: `mode` is the one picked ('auto', 'low' or 'high').
620
+ setGraphics(mode, onPick) {
621
+ graphics ??= buildGraphics();
622
+ graphics.onPick = onPick;
623
+ for (const [m, button] of graphics.buttons) {
624
+ button.style.borderColor = m === mode ? '#f2c94c' : 'rgba(255,255,255,0.4)';
625
+ button.setAttribute('aria-pressed', String(m === mode));
626
+ }
627
+ },
600
628
  onTalk(handlers) {
601
629
  talkHandlers = handlers;
602
630
  },
@@ -795,10 +823,9 @@ export function makeChrome({ onBack, onAvatar, avatarCount, onPerson = () => {},
795
823
  talkButton.textContent = text;
796
824
  }
797
825
  },
798
- openTalk(name, note) {
826
+ openTalk(name) {
799
827
  talkOpen = true;
800
828
  panelName.textContent = name;
801
- panelNote.textContent = note;
802
829
  panelLog.replaceChildren();
803
830
  panel.style.display = 'flex';
804
831
  talkButton.style.display = 'none';
@@ -848,16 +875,20 @@ export function makeChrome({ onBack, onAvatar, avatarCount, onPerson = () => {},
848
875
  doorsList.replaceChildren();
849
876
  for (const door of doors) {
850
877
  const row = el('div', { display: 'flex', alignItems: 'center', gap: '8px' }, doorsList);
851
- const name = el('div', { flex: '1', minWidth: '0', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }, row);
878
+ // The title on a line of its own, with one short word under it on what
879
+ // the door takes (a solo game, how many it needs): beside the button
880
+ // they squeezed the title to a few letters.
881
+ const words = el('div', { flex: '1', minWidth: '0' }, row);
882
+ const name = el('div', { overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }, words);
852
883
  name.textContent = `${door.featured ? '★ ' : ''}${door.title ?? door.id}`;
853
- // One short word on what the door takes: a solo game, or how many it needs.
854
884
  const takes = door.solo ? 'solo' : door.need ? `needs ${door.need}` : '';
855
885
  if (takes) {
856
- el('div', { flex: 'none', fontSize: '11px', fontWeight: '500', opacity: '0.7' }, row).textContent = takes;
886
+ el('div', { fontSize: '11px', fontWeight: '500', opacity: '0.7' }, words).textContent = takes;
857
887
  }
858
888
  const go = el('button', { padding: '5px 12px', borderRadius: '12px', border: 'none', background: '#e9c48f', color: '#2b2118', font: '700 13px system-ui, sans-serif', cursor: 'pointer' }, row);
859
889
  // A party cannot go together through a door that takes one player.
860
890
  go.textContent = door.solo ? 'Go' : goText;
891
+ go.style.flex = 'none';
861
892
  go.addEventListener('pointerdown', (event) => {
862
893
  event.stopPropagation();
863
894
  closeDoors();
@@ -878,7 +909,10 @@ export function makeChrome({ onBack, onAvatar, avatarCount, onPerson = () => {},
878
909
  peopleKey = '';
879
910
  return;
880
911
  }
881
- const label = `People · ${people.length}`;
912
+ // Everyone in this place, the player too: a count of the others read as
913
+ // one short beside the avatars on screen. Friends elsewhere are rows of
914
+ // the list, not people here.
915
+ const label = `People · ${people.filter((p) => p.playerId).length + 1}`;
882
916
  if (peopleButton.textContent !== label) {
883
917
  peopleButton.textContent = label;
884
918
  }