castle-web-cli 0.4.142 → 0.4.145

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 (52) hide show
  1. package/dist/agent-prompts.d.ts +1 -0
  2. package/dist/agent-prompts.js +7 -2
  3. package/dist/agent.js +11 -9
  4. package/dist/imports.js +44 -4
  5. package/dist/init.d.ts +4 -0
  6. package/dist/init.js +63 -26
  7. package/dist/install.js +4 -0
  8. package/dist/platformDoc.d.ts +12 -0
  9. package/dist/platformDoc.js +236 -0
  10. package/dist/serve.d.ts +3 -0
  11. package/dist/serve.js +157 -13
  12. package/dist/serveSecurity.d.ts +5 -1
  13. package/dist/serveSecurity.js +27 -8
  14. package/dist/shell/assets/index-BaiRLZ8p.css +1 -0
  15. package/dist/shell/assets/{index-qbygvQIx.js → index-CbRAepsq.js} +68 -68
  16. package/dist/shell/index.html +2 -2
  17. package/kits/blank/CLAUDE.md +198 -0
  18. package/kits/blank/castle.json +8 -0
  19. package/kits/blank/index.html +42 -0
  20. package/kits/blank/package-lock.json +10 -0
  21. package/kits/blank/package.json +9 -0
  22. package/kits/physics-2d/CLAUDE.md +44 -4
  23. package/kits/physics-2d/behaviors/Collider.jsx +21 -0
  24. package/kits/physics-2d/behaviors/Draggable.jsx +9 -0
  25. package/kits/physics-2d/behaviors/Layout.jsx +7 -0
  26. package/kits/physics-2d/behaviors/RigidBody.jsx +6 -0
  27. package/kits/physics-2d/behaviors/Sprite.jsx +9 -4
  28. package/kits/physics-2d/editors/BlueprintLibrary.jsx +64 -32
  29. package/kits/physics-2d/editors/NewBlueprintModal.jsx +69 -0
  30. package/kits/physics-2d/editors/PlayOnly.jsx +1 -1
  31. package/kits/physics-2d/editors/SceneEditor.jsx +333 -108
  32. package/kits/physics-2d/editors/SelectionOverlay.jsx +6 -2
  33. package/kits/physics-2d/editors/behaviorRegistry.js +78 -5
  34. package/kits/physics-2d/engine/SceneUI.jsx +2 -2
  35. package/kits/physics-2d/engine/blueprint.js +212 -15
  36. package/kits/physics-2d/engine/editorFlags.js +50 -0
  37. package/kits/physics-2d/engine/files.js +9 -0
  38. package/kits/physics-2d/engine/liveReload.js +16 -4
  39. package/kits/physics-2d/engine/panelPrefs.js +78 -0
  40. package/kits/physics-2d/engine/panelSorting.jsx +84 -0
  41. package/kits/physics-2d/engine/physics/PhysicsSystem.js +5 -2
  42. package/kits/physics-2d/engine/physics/matterBridge.js +12 -2
  43. package/kits/physics-2d/engine/scene.js +94 -3
  44. package/kits/physics-2d/engine/ui.jsx +157 -4
  45. package/kits/physics-2d/engine/ui.module.css +615 -1
  46. package/kits/physics-2d/package-lock.json +78 -1
  47. package/kits/physics-2d/package.json +4 -0
  48. package/kits/physics-3d/CLAUDE.md +2 -3
  49. package/package.json +1 -1
  50. package/dist/commonInstructions.d.ts +0 -1
  51. package/dist/commonInstructions.js +0 -26
  52. package/dist/shell/assets/index-CcVJjnL3.css +0 -1
@@ -1,5 +1,6 @@
1
- // Discover every behavior class from `behaviors/**/*.jsx`. Vite HMR is off, so a
2
- // newly-added behavior file is picked up on the next reload/restart.
1
+ import { useEffect, useState } from 'react';
2
+ import { onFilesChanged } from 'castle-web-sdk';
3
+ // Discover every behavior class from `behaviors/**/*.jsx`.
3
4
  // Root-anchored so the kit finds the DECK's behaviors even when the kit is
4
5
  // itself an import (see engine/files.js). Imports are swept first and the deck's
5
6
  // own behaviors last: collectBehaviors keys by behaviorName, so a behavior the
@@ -7,6 +8,11 @@
7
8
  // `behaviors/` is the ONE place behaviors live -- the rest of the system (the
8
9
  // deck file map, the editor's visible paths, lint, the duplicate gate) keys off
9
10
  // that directory, so a behavior kept anywhere else is invisible to all of it.
11
+ //
12
+ // The glob seeds the registry; after that a behavior file can be re-imported in
13
+ // place -- see `swapBehaviorModule` at the bottom. Key ORDER is the precedence
14
+ // rule (imports first, the deck last), and re-assigning an existing key keeps
15
+ // its position, so a hot swap can't quietly change which definition wins.
10
16
  const modules = {
11
17
  ...import.meta.glob('/imports/*/behaviors/**/*.jsx', { eager: true }),
12
18
  ...import.meta.glob('/behaviors/**/*.jsx', { eager: true }),
@@ -14,11 +20,28 @@ const modules = {
14
20
  function isBehaviorClass(value) {
15
21
  return typeof value === 'function' && typeof value.behaviorName === 'string';
16
22
  }
23
+ // Where each behavior was found, by behaviorName. The glob keys already carry
24
+ // it -- `/behaviors/Ball.jsx`, or `/imports/<alias>/behaviors/Ball.jsx` for one
25
+ // a dependency contributes -- and collecting the classes threw it away. Keeping
26
+ // it is what lets the inspector offer "view source" on a behavior without the
27
+ // editor guessing at a path from the name (which would be wrong for every
28
+ // behavior in a subfolder, and for every behavior an import provides).
29
+ const sources = new Map();
30
+
31
+ export function behaviorSourcePath(behaviorName) {
32
+ return sources.get(behaviorName) ?? null;
33
+ }
34
+
17
35
  function collectBehaviors() {
18
36
  const found = new Map();
19
- for (const mod of Object.values(modules)) {
37
+ sources.clear();
38
+ for (const [modulePath, mod] of Object.entries(modules)) {
20
39
  for (const exported of Object.values(mod)) {
21
- if (isBehaviorClass(exported)) found.set(exported.behaviorName, exported);
40
+ if (isBehaviorClass(exported)) {
41
+ found.set(exported.behaviorName, exported);
42
+ // Deck-relative, matching every other path the editor handles.
43
+ sources.set(exported.behaviorName, modulePath.replace(/^\//, ''));
44
+ }
22
45
  }
23
46
  }
24
47
  // Layout first (every actor needs it), then alphabetical.
@@ -28,7 +51,57 @@ function collectBehaviors() {
28
51
  return a.behaviorName.localeCompare(b.behaviorName);
29
52
  });
30
53
  }
31
- export const behaviorClasses = collectBehaviors();
54
+ // `let`, not `const`: an ES module export is a LIVE binding, so re-assigning
55
+ // here updates every importer without any of them changing.
56
+ export let behaviorClasses = collectBehaviors();
32
57
  export function findBehaviorClass(behaviorName) {
33
58
  return behaviorClasses.find((candidate) => candidate.behaviorName === behaviorName);
34
59
  }
60
+
61
+ // A live binding updates the value importers see, but tells React nothing.
62
+ const listeners = new Set();
63
+
64
+ export function subscribeBehaviors(listener) {
65
+ listeners.add(listener);
66
+ return () => listeners.delete(listener);
67
+ }
68
+
69
+ // Only `behaviors/**`: `engine/` and `editors/` are imported statically all over
70
+ // the runtime and still need a reload.
71
+ function isBehaviorModulePath(path) {
72
+ return /(^|\/)behaviors\/[^/]*\.jsx$/.test(path) && !path.startsWith('editors/');
73
+ }
74
+
75
+ // The serve runs with `hmr: false`, so a cache-busting query is what gets a
76
+ // fresh module rather than the one already in the browser's map.
77
+ //
78
+ // Behavior INSTANCES need nothing -- they are rebuilt per frame from whatever
79
+ // class the registry holds. Only class-level reads need the re-render.
80
+ async function swapBehaviorModule(deckPath) {
81
+ const key = `/${deckPath}`;
82
+ try {
83
+ const mod = await import(/* @vite-ignore */ `${key}?t=${Date.now()}`);
84
+ modules[key] = mod;
85
+ } catch {
86
+ // A file mid-edit may not parse. Keep the last good definition and wait for
87
+ // the next save rather than emptying the registry under the editor.
88
+ return;
89
+ }
90
+ behaviorClasses = collectBehaviors();
91
+ for (const listener of [...listeners]) listener();
92
+ }
93
+
94
+ // Subscribed once at module scope; every panel runs its own copy of the registry.
95
+ onFilesChanged((event) => {
96
+ const touched = new Set();
97
+ for (const change of event.changes ?? []) {
98
+ if (change.event !== 'delete' && isBehaviorModulePath(change.path)) touched.add(change.path);
99
+ }
100
+ for (const path of touched) void swapBehaviorModule(path);
101
+ });
102
+
103
+ // Re-render when a behavior's code changes; read `behaviorClasses` directly.
104
+ export function useBehaviorReload() {
105
+ const [, bump] = useState(0);
106
+ useEffect(() => subscribeBehaviors(() => bump((n) => n + 1)), []);
107
+ }
@@ -1,7 +1,7 @@
1
1
  import React, { useEffect, useRef, useState } from 'react';
2
2
  import styles from './ui.module.css';
3
3
  import { useElementSize } from './ui';
4
- import { cardSize } from './scene';
4
+ import { cardSize, isBehaviorEnabled } from './scene';
5
5
  // Game-time UI overlay.
6
6
  //
7
7
  // Behaviors expose a `ui(actor, scene)` handler -- the React counterpart of
@@ -45,7 +45,7 @@ function collectUiNodes(runtime) {
45
45
  const nodes = [];
46
46
  for (const actor of runtime.getActors()) {
47
47
  for (const [behaviorName, props] of Object.entries(actor.components)) {
48
- if (!props) continue;
48
+ if (!isBehaviorEnabled(props)) continue;
49
49
  const Behavior = runtime.behaviors.get(behaviorName);
50
50
  if (!Behavior) continue;
51
51
  const instance = new Behavior(props);
@@ -161,13 +161,19 @@ function countMatches(text, regex) {
161
161
  return m ? Number(m[1]) : max;
162
162
  }
163
163
 
164
- // "Blueprint N" -- N is one more than the highest existing "Blueprint <n>"
165
- // name (not just existing.length + 1, so a gap left by a deleted blueprint
166
- // doesn't get reused and collide with intent elsewhere).
164
+ // "New Blueprint (N)" -- one past the highest existing, so a gap left by a
165
+ // deletion isn't reused. The older bare "Blueprint N" form still counts toward
166
+ // N, so a deck holding both can't collide.
167
167
  function mintBlueprintName(existingNames) {
168
168
  let max = 0;
169
- for (const name of existingNames) max = Math.max(max, countMatches(name, /^Blueprint (\d+)$/));
170
- return `Blueprint ${max + 1}`;
169
+ for (const name of existingNames) {
170
+ max = Math.max(
171
+ max,
172
+ countMatches(name, /^New Blueprint \((\d+)\)$/),
173
+ countMatches(name, /^Blueprint (\d+)$/)
174
+ );
175
+ }
176
+ return `New Blueprint (${max + 1})`;
171
177
  }
172
178
 
173
179
  // `blueprints/blueprint-N.scene` -- the filename is a stable slug minted once
@@ -350,7 +356,11 @@ export function applyComponentPatch(files, behaviors, actor, behaviorName, nextP
350
356
  const defaultProps = Behavior?.defaultProps ?? {};
351
357
  const overrides = { ...(actor.components[behaviorName] ?? {}) };
352
358
  for (const [prop, value] of Object.entries(nextProps)) {
353
- const baseline = prop in templateProps ? templateProps[prop] : defaultProps[prop];
359
+ // `$enabled` is in neither the template nor defaultProps when a behavior is
360
+ // simply on, so without this, switching an instance back ON would store
361
+ // `$enabled: true` forever instead of returning to inheritance.
362
+ const raw = prop in templateProps ? templateProps[prop] : defaultProps[prop];
363
+ const baseline = prop === '$enabled' ? (raw ?? true) : raw;
354
364
  // Deep-equal, not Object.is: object/array props (e.g. Collider `shapes`,
355
365
  // Joints `list`) reset to the blueprint value are a fresh reference with
356
366
  // identical content, so a reference check would never drop the override.
@@ -390,6 +400,10 @@ export function blankPxArtText() {
390
400
  return serializeCompact({ palette: {}, grid });
391
401
  }
392
402
 
403
+ // `.pxart` is the legacy spelling and still reads; new art is `.sprite`.
404
+ const DRAWING_EXT = '.sprite';
405
+ const DRAWING_EXT_RE = '\\.(?:pxart|sprite)';
406
+
393
407
  // `drawings/drawing-N.sprite` -- next free numbered slug, so repeated adds don't
394
408
  // collide and a deleted drawing's number isn't reused.
395
409
  function mintDrawingPath(files) {
@@ -416,15 +430,11 @@ function topZ(actors, files) {
416
430
  return max === -Infinity ? 0 : max + 1;
417
431
  }
418
432
 
419
- export function addActorWithBlueprint(sceneData, files) {
420
- const width = 50;
421
- const height = 50;
422
- const drawingFile = { path: mintDrawingPath(files), text: blankPxArtText() };
423
- const components = {
424
- Layout: { width, height, z: 0 },
425
- Sprite: { file: drawingFile.path },
426
- };
427
- const blueprintFile = mintBlueprintFile(files, components);
433
+ // A freshly minted blueprint's first instance, at the card centre and on top.
434
+ function appendCenteredInstance(sceneData, files, blueprintFile) {
435
+ const layout = blueprintFile.components?.Layout ?? {};
436
+ const width = layout.width ?? 50;
437
+ const height = layout.height ?? 50;
428
438
  const next = structuredClone(sceneData);
429
439
  const existingIds = new Set(next.actors.map((actor) => actor.id));
430
440
  const newId = mintActorIdFromName(existingIds, blueprintFile.name);
@@ -433,9 +443,113 @@ export function addActorWithBlueprint(sceneData, files) {
433
443
  // Guarantee the new actor renders on top of whatever's already there.
434
444
  const z = topZ(next.actors, files);
435
445
  next.actors.push({ id: newId, blueprint: blueprintFile.path, components: { Layout: { x, y, z } } });
446
+ return { sceneData: next, newId };
447
+ }
448
+
449
+ export function addActorWithBlueprint(sceneData, files) {
450
+ const drawingFile = { path: mintDrawingPath(files), text: blankPxArtText() };
451
+ const components = {
452
+ Layout: { width: 50, height: 50, z: 0 },
453
+ Sprite: { file: drawingFile.path },
454
+ };
455
+ const minted = mintBlueprintFile(files, components);
456
+ const blueprintFile = { ...minted, components };
457
+ const { sceneData: next, newId } = appendCenteredInstance(sceneData, files, blueprintFile);
436
458
  return { sceneData: next, newId, blueprintFile, drawingFile };
437
459
  }
438
460
 
461
+ // `blueprints/wall.scene` from a display name: slugified, then suffix-deduped.
462
+ function mintPathFromName(existingPaths, name, dir, ext) {
463
+ const base = slugifyActorId(typeof name === 'string' ? name : '') || 'blueprint';
464
+ const MAX_ATTEMPTS = 1000;
465
+ for (let suffix = 1; suffix <= MAX_ATTEMPTS; suffix += 1) {
466
+ const slug = suffix === 1 ? base : `${base}-${suffix}`;
467
+ const path = `${dir}/${slug}${ext}`;
468
+ if (!existingPaths.has(path)) return path;
469
+ }
470
+ // Callers treat null as "couldn't name it" and fall back to the counter.
471
+ return null;
472
+ }
473
+
474
+ // The creation modal's starting points: whatever blueprints the deck's imports
475
+ // contribute. Deck-owned ones are excluded -- drag-to-place already copies those.
476
+ export function listBuiltinBlueprints(files) {
477
+ return listBlueprints(files).filter((blueprint) => isImportedPath(blueprint.path));
478
+ }
479
+
480
+ // A built-in's components, with its art COPIED into the deck: an import's files
481
+ // are read-only, so a referenced sprite could never be edited. Only
482
+ // `Sprite.file` -- other file refs (a joint's rope art) stay with the import.
483
+ function adoptBuiltinArt(files, components, existingPaths, name) {
484
+ const source = components.Sprite?.file;
485
+ const text = source ? files?.[resolveDeckFile(source)] : undefined;
486
+ if (typeof text !== 'string') return null;
487
+ const ext = source.endsWith('.pxart') ? '.pxart' : DRAWING_EXT;
488
+ const path = mintPathFromName(existingPaths, name, DRAWINGS_DIR, ext) ?? mintDrawingPath(files);
489
+ components.Sprite.file = path;
490
+ return { path, text };
491
+ }
492
+
493
+ // "Ball", then "Ball 2", "Ball 3" as the deck accumulates them. Same shape as
494
+ // the migration path's dedup (`deriveBlueprintName`) rather than the "New
495
+ // Blueprint (N)" placeholder form -- the parentheses are there to mark a name
496
+ // as a stand-in, and a name taken from a preset isn't one.
497
+ function mintNameFromBase(existingNames, base) {
498
+ const taken = new Set(existingNames);
499
+ if (!taken.has(base)) return base;
500
+ const MAX_ATTEMPTS = 1000;
501
+ for (let suffix = 2; suffix <= MAX_ATTEMPTS; suffix += 1) {
502
+ const name = `${base} ${suffix}`;
503
+ if (!taken.has(name)) return name;
504
+ }
505
+ return base;
506
+ }
507
+
508
+ // Create a blueprint and place its first instance -- the modal's whole job, as
509
+ // one operation. `spec.builtin` is the path of a built-in to copy, or absent
510
+ // for a blank drawing (an empty canvas to draw into, which is the other thing
511
+ // somebody starting a new actor wants).
512
+ //
513
+ // The name is minted, never asked for. A preset lends its own ("Ball"), which
514
+ // is both a better starting point than a placeholder and a truthful
515
+ // description of what you get; a blank drawing has nothing to lend, so it
516
+ // falls back to "New Blueprint (N)". Either way the creator renames it in the
517
+ // blueprint inspector, where they can see the actor they are naming.
518
+ //
519
+ // Returns the same shape as `addActorWithBlueprint` so the caller's write +
520
+ // commit + select sequence is identical for every path.
521
+ export function createBlueprint(sceneData, files, spec) {
522
+ const existingPaths = new Set(Object.keys(files ?? {}));
523
+ // Deck-owned names only. An import's blueprints are a separate namespace --
524
+ // they collide on neither path nor identity -- and counting them would mean
525
+ // picking the Ball preset in a fresh deck yields "Ball 2", named around a
526
+ // conflict the creator can't see and doesn't have.
527
+ const existingNames = listBlueprints(files)
528
+ .filter((blueprint) => !isImportedPath(blueprint.path))
529
+ .map((blueprint) => blueprint.name);
530
+ const builtin = spec?.builtin ? getBlueprintTemplate(files, spec.builtin) : null;
531
+ const name = builtin?.name
532
+ ? mintNameFromBase(existingNames, builtin.name)
533
+ : mintBlueprintName(existingNames);
534
+ const path =
535
+ mintPathFromName(existingPaths, name, BLUEPRINTS_DIR, '.scene') ??
536
+ mintBlueprintPath([...existingPaths]);
537
+ let components;
538
+ let drawingFile;
539
+ if (builtin) {
540
+ components = structuredClone(builtin.components ?? {});
541
+ drawingFile = adoptBuiltinArt(files, components, existingPaths, name);
542
+ } else {
543
+ const drawingPath =
544
+ mintPathFromName(existingPaths, name, DRAWINGS_DIR, DRAWING_EXT) ?? mintDrawingPath(files);
545
+ drawingFile = { path: drawingPath, text: blankPxArtText() };
546
+ components = { Layout: { width: 50, height: 50, z: 0 }, Sprite: { file: drawingPath } };
547
+ }
548
+ const blueprintFile = { path, name, components, text: formatBlueprintFileText(name, components) };
549
+ const { sceneData: next, newId } = appendCenteredInstance(sceneData, files, blueprintFile);
550
+ return { sceneData: next, newId, blueprintFile, drawingFile: drawingFile ?? null };
551
+ }
552
+
439
553
  // Centered, grid-snapped Layout x/y for a blueprint's template at a
440
554
  // card-space point. Shared by initial drag-in placement and the subsequent
441
555
  // moves while the drag is still in progress, so both snap identically.
@@ -550,6 +664,89 @@ export function cascadeDeleteBlueprint(files, blueprintPath) {
550
664
  return writes;
551
665
  }
552
666
 
667
+ // How many blueprints point a Sprite at `drawingPath`. Guards the rename
668
+ // below: a drawing two blueprints share is nobody's to rename.
669
+ function countSpriteRefs(files, drawingPath) {
670
+ let count = 0;
671
+ for (const path of Object.keys(files ?? {})) {
672
+ if (!isBlueprintPath(path) || isImportedPath(path)) continue;
673
+ const template = parseBlueprintText(files[path]);
674
+ if (template?.components?.Sprite?.file === drawingPath) count += 1;
675
+ }
676
+ return count;
677
+ }
678
+
679
+ // Is `drawingPath` this blueprint's OWN auto-minted art -- the blank we made
680
+ // for it at creation, under either the anonymous counter (`drawing-3.sprite`,
681
+ // the zero-prompt path) or the blueprint's own slug (`wall.sprite`, the modal
682
+ // pairing a name with its drawing)? Those two shapes are ours to keep in sync
683
+ // with the name. A drawing the creator picked from the grid, or drew and named
684
+ // themselves, is not: it may be shared, and its name means something to them.
685
+ // Both spellings match, so a blueprint made before the `.sprite` rename still
686
+ // carries its drawing along.
687
+ function isOwnMintedDrawing(drawingPath, blueprintPath) {
688
+ if (typeof drawingPath !== 'string') return false;
689
+ if (new RegExp(`^${DRAWINGS_DIR}/drawing-\\d+${DRAWING_EXT_RE}$`).test(drawingPath)) return true;
690
+ // Compared literally rather than by regex: a hand-authored blueprint path
691
+ // can hold characters (`.`, `+`) that would match far too much as a pattern.
692
+ const slug = blueprintPath.slice(BLUEPRINTS_DIR.length + 1, -'.scene'.length);
693
+ return (
694
+ drawingPath === `${DRAWINGS_DIR}/${slug}.sprite` ||
695
+ drawingPath === `${DRAWINGS_DIR}/${slug}.pxart`
696
+ );
697
+ }
698
+
699
+ // Renaming a blueprint means renaming the FILE, not just editing `name` --
700
+ // that's the whole complaint. Returns the physical moves and the content
701
+ // writes to apply (renames first, then writes, so a write never lands on a
702
+ // path that's about to move):
703
+ //
704
+ // { path, name, fileRenames: [{from, to}], writes: [{path, text}] }
705
+ //
706
+ // or null when the blueprint is missing/unparseable. What moves:
707
+ // - the blueprint file, to its new name-derived slug
708
+ // - its auto-minted drawing, when no other blueprint shares it
709
+ // - every `"blueprint"` ref in every `scenes/*.scene`
710
+ //
711
+ // Actor ids are deliberately left alone. They're referenced by `Joints.target`,
712
+ // `Camera.target` and any behavior calling `scene.getActor('...')` -- that last
713
+ // one we cannot rewrite, so renaming ids would silently break working games.
714
+ // A-1's modal is the real fix there: the first id is right to begin with.
715
+ export function renameBlueprintCascade(files, blueprintPath, nextName) {
716
+ const template = parseBlueprintText(files?.[blueprintPath]);
717
+ if (!template) return null;
718
+ const name = typeof nextName === 'string' && nextName.trim() ? nextName.trim() : 'Blueprint';
719
+ const taken = new Set(Object.keys(files ?? {}));
720
+ taken.delete(blueprintPath);
721
+ const nextPath = mintPathFromName(taken, name, BLUEPRINTS_DIR, '.scene') ?? blueprintPath;
722
+ const fileRenames = [];
723
+ const components = structuredClone(template.components ?? {});
724
+ const drawingPath = components.Sprite?.file;
725
+ if (isOwnMintedDrawing(drawingPath, blueprintPath) && countSpriteRefs(files, drawingPath) === 1) {
726
+ taken.delete(drawingPath);
727
+ // Keep the drawing's OWN extension: a deck made before the `.sprite`
728
+ // rename holds `.pxart` files, and a rename is no place to migrate a
729
+ // format out from under the creator.
730
+ const ext = drawingPath.endsWith('.pxart') ? '.pxart' : DRAWING_EXT;
731
+ const nextDrawing = mintPathFromName(taken, name, DRAWINGS_DIR, ext);
732
+ if (nextDrawing && nextDrawing !== drawingPath) {
733
+ fileRenames.push({ from: drawingPath, to: nextDrawing });
734
+ components.Sprite.file = nextDrawing;
735
+ }
736
+ }
737
+ if (nextPath !== blueprintPath) fileRenames.push({ from: blueprintPath, to: nextPath });
738
+ const writes = [{ path: nextPath, text: formatBlueprintFileText(name, components) }];
739
+ for (const { path, data } of parseSceneFiles(files)) {
740
+ const actors = data.actors ?? [];
741
+ if (!actors.some((actor) => actor?.blueprint === blueprintPath)) continue;
742
+ const rewritten = actors.map((actor) =>
743
+ actor?.blueprint === blueprintPath ? { ...actor, blueprint: nextPath } : actor
744
+ );
745
+ writes.push({ path, text: formatJson({ ...data, actors: rewritten }) });
746
+ }
747
+ return { path: nextPath, name, fileRenames, writes };
748
+ }
749
+
553
750
  // Auto-migrate a scene's orphan actors (no `blueprint` field -- the pre-v1
554
751
  // shape) into blueprint instances: mint one blueprint per orphan (its
555
752
  // authored components split by propertyMeta, same as fork), rewrite the actor
@@ -0,0 +1,50 @@
1
+ // Per-feature kill switches for editor changes that ship in a kit publish.
2
+ //
3
+ // One boolean per feature, not one "new editor" flag: a kit publish reaches
4
+ // every deck at its next serve start and is roll-forward only, so the unit of
5
+ // rollback has to be smaller than the unit of release.
6
+ //
7
+ // `?castle-flags=-newBlueprintModal` overrides one for a session -- faster than
8
+ // a publish while something is being tested. Never persisted.
9
+
10
+ const DEFAULTS = {
11
+ // A-1/A-3: the `+` opens the New-blueprint modal (pick a preset or a blank
12
+ // drawing) instead of creating one outright.
13
+ //
14
+ // OFF: pressing `+` means "I want an actor", so it makes a blank-drawing
15
+ // blueprint and puts the cursor in its name. Kept behind a flag so presets
16
+ // can come back without rebuilding them.
17
+ newBlueprintModal: false,
18
+ // A-4: committing a blueprint rename moves the file and repoints every
19
+ // instance, rather than only editing the file's `name`. Off leaves the old
20
+ // name-only behavior, which is inert rather than wrong -- worth having a
21
+ // switch for, since this one writes across every scene in the deck.
22
+ renameBlueprintFiles: true,
23
+ };
24
+
25
+ // `?castle-flags=+one,-two` -- a leading `-` forces off, `+` or a bare name
26
+ // forces on. An unknown name is ignored rather than added, so a typo can't
27
+ // invent a flag that nothing reads.
28
+ function readOverrides() {
29
+ const flags = { ...DEFAULTS };
30
+ if (typeof window === 'undefined') return flags;
31
+ let raw = null;
32
+ try {
33
+ raw = new URLSearchParams(window.location.search).get('castle-flags');
34
+ } catch {
35
+ return flags;
36
+ }
37
+ if (!raw) return flags;
38
+ for (const entry of raw.split(',')) {
39
+ const token = entry.trim();
40
+ if (!token) continue;
41
+ const off = token.startsWith('-');
42
+ const name = off || token.startsWith('+') ? token.slice(1) : token;
43
+ if (name in flags) flags[name] = !off;
44
+ }
45
+ return flags;
46
+ }
47
+
48
+ // Resolved once at module load: flags are read during render, and a value that
49
+ // changed mid-session would leave the editor half in each world.
50
+ export const editorFlags = readOverrides();
@@ -44,12 +44,21 @@ export const initialFiles = Object.fromEntries(
44
44
  // upload and lands wherever the person uploading put it, so the pattern is the
45
45
  // whole deck minus what is never deck content. (Both patterns and options must
46
46
  // be literals -- import.meta.glob is a compile-time transform.)
47
+ //
48
+ // `/preview.png` is excluded because it is OUTPUT, not content: the deck's
49
+ // cover, rewritten automatically as the creator plays. Including it cost twice.
50
+ // It showed up as pickable art everywhere a sprite is chosen, which it never
51
+ // is. And being in this glob made it a source module, so each automatic cover
52
+ // write invalidated the module graph and full-reloaded every deck iframe --
53
+ // which re-fired the on-load capture, which wrote the cover again. A visible
54
+ // flash of every open panel, on a loop, with nobody touching the keyboard.
47
55
  const mediaModules = import.meta.glob(
48
56
  [
49
57
  '/**/*.{png,jpg,jpeg,gif,webp,svg,mp3,wav,m4a,mp4}',
50
58
  '!/node_modules/**',
51
59
  '!/dist/**',
52
60
  '!/.castle/**',
61
+ '!/preview.png',
53
62
  ],
54
63
  { eager: true, import: 'default' }
55
64
  );
@@ -132,9 +132,14 @@ export async function hydrateDeclaredFiles({ knownExts, knownFiles, ensurePath }
132
132
  // `shouldSkipPath` lets an editor keep its own in-flight edits from being
133
133
  // clobbered by the fs echo of a stale write. `ensurePath` names the file this
134
134
  // consumer actually opened, so a declared type outside the curated listing is
135
- // still read. `live: false` takes the hydration without the subscription --
136
- // what Play wants, since it never folds a change into a run in progress.
137
- export function useLiveDeckFiles({ shouldSkipPath, ensurePath, live = true } = {}) {
135
+ // still read. Play disables both live updates and declared-type hydration: its
136
+ // build-time snapshot is complete, and its isolated origin cannot read source.
137
+ export function useLiveDeckFiles({
138
+ shouldSkipPath,
139
+ ensurePath,
140
+ live = true,
141
+ hydrateDeclared = true,
142
+ } = {}) {
138
143
  const [files, setFiles] = useState(initialFiles);
139
144
  // False until the declared-type read above has settled. An editor mounted
140
145
  // before then would be handed '' for a file that exists, and an edit made in
@@ -145,6 +150,13 @@ export function useLiveDeckFiles({ shouldSkipPath, ensurePath, live = true } = {
145
150
  skipRef.current = shouldSkipPath;
146
151
 
147
152
  useEffect(() => {
153
+ // Play runs on a source-blind origin. Its build-time glob already contains
154
+ // every file type the engine consumes, so editor-only declared-type
155
+ // hydration would only make forbidden file API requests.
156
+ if (!hydrateDeclared) {
157
+ setHydrated(true);
158
+ return undefined;
159
+ }
148
160
  let alive = true;
149
161
  void hydrateDeclaredFiles({
150
162
  knownExts: DATA_EXTS,
@@ -165,7 +177,7 @@ export function useLiveDeckFiles({ shouldSkipPath, ensurePath, live = true } = {
165
177
  return () => {
166
178
  alive = false;
167
179
  };
168
- }, [ensurePath]);
180
+ }, [ensurePath, hydrateDeclared]);
169
181
 
170
182
  useEffect(() => {
171
183
  if (!live) return undefined;
@@ -0,0 +1,78 @@
1
+ // Which behavior panels are collapsed, and what order they sit in, per OWNER --
2
+ // a blueprint by path, a placed actor by scene + id.
3
+ //
4
+ // Editor state, never deck data: panel order is how one person likes to read an
5
+ // inspector, so it stays out of the .scene files and out of version control.
6
+
7
+ const KEY = 'castle-panel-prefs';
8
+ // Bounded so a deck edited for months doesn't grow this without limit; the
9
+ // oldest owners fall off, and their panels return to the defaults.
10
+ const MAX_OWNERS = 300;
11
+
12
+ function readAll() {
13
+ try {
14
+ const raw = localStorage.getItem(KEY);
15
+ const data = raw ? JSON.parse(raw) : null;
16
+ return data && typeof data === 'object' ? data : {};
17
+ } catch {
18
+ return {};
19
+ }
20
+ }
21
+
22
+ function writeAll(data) {
23
+ try {
24
+ const keys = Object.keys(data);
25
+ if (keys.length > MAX_OWNERS) {
26
+ for (const stale of keys.slice(0, keys.length - MAX_OWNERS)) delete data[stale];
27
+ }
28
+ localStorage.setItem(KEY, JSON.stringify(data));
29
+ } catch {
30
+ /* storage disabled -- preferences just don't persist */
31
+ }
32
+ }
33
+
34
+ function ownerEntry(owner) {
35
+ const all = readAll();
36
+ const entry = all[owner];
37
+ return entry && typeof entry === 'object' ? entry : {};
38
+ }
39
+
40
+ // Behaviors start COLLAPSED: the whole stack is then visible at once, and each
41
+ // summary says whether a panel is worth opening.
42
+ export function isCollapsed(owner, title) {
43
+ const open = ownerEntry(owner).open;
44
+ return !(Array.isArray(open) && open.includes(title));
45
+ }
46
+
47
+ // Stored as the OPEN list, so "nothing recorded" means the collapsed default.
48
+ export function setCollapsed(owner, title, collapsed) {
49
+ const all = readAll();
50
+ const entry = all[owner] && typeof all[owner] === 'object' ? all[owner] : {};
51
+ const open = new Set(Array.isArray(entry.open) ? entry.open : []);
52
+ if (collapsed) open.delete(title);
53
+ else open.add(title);
54
+ // Re-inserting the owner moves it to the end, which is what makes the
55
+ // trim above drop the least recently touched.
56
+ delete all[owner];
57
+ all[owner] = { ...entry, open: [...open] };
58
+ writeAll(all);
59
+ }
60
+
61
+ // Saved order first, then anything unsaved in its natural order -- so a behavior
62
+ // added after the order was saved appears at the bottom rather than vanishing.
63
+ export function applyOrder(owner, names) {
64
+ const saved = ownerEntry(owner).order;
65
+ if (!Array.isArray(saved) || saved.length === 0) return names;
66
+ const known = new Set(names);
67
+ const ordered = saved.filter((name) => known.has(name));
68
+ const seen = new Set(ordered);
69
+ return [...ordered, ...names.filter((name) => !seen.has(name))];
70
+ }
71
+
72
+ export function setOrder(owner, names) {
73
+ const all = readAll();
74
+ const entry = all[owner] && typeof all[owner] === 'object' ? all[owner] : {};
75
+ delete all[owner];
76
+ all[owner] = { ...entry, order: [...names] };
77
+ writeAll(all);
78
+ }