Recurring cleanup round over the code since round 6 (056a622), 105
commits. Behaviour is unchanged. Duplicated code in src went from 29
clones with 229 lines (0.32 %) to 14 clones with 109 lines (0.15 %),
measured with jscpd and the same settings as round 6.
- BehaviorSystem.ts shrinks from 941 to 589 lines. Collecting the
pulses (keys, timers, collisions, animations) moved to
behaviorPulses.ts. The NodeContext the nodes receive moved to
behaviorContext.ts. Imports from outside stay the same, TimeScaled
is still exported from BehaviorSystem.ts.
- PointKindButton and drawPointGrip replace the "Point:" button with
its menu and the point and handle drawing that the curve and the
vector art tab each had on their own.
- lerpVec, cubicAt and splitCubic in src/core/util/vec.ts replace four
copies of the cubic curve and two de Casteljau splits.
- mapNested in Properties.ts is the one walk over lists and structs
that liveObjects and objectRefs did separately. withFieldRenamed
and withoutField replace three copies of renaming a struct field
and two of removing one.
- jsonBody and staleRevision build the JSON body and turn a 409 into
StaleRevisionError for all stores. The auth store turns a 401 into
its error in one place.
- Smaller helpers: structAssetFrom for the two "Make struct type"
commands, shownObject in the inspector, selectedItem for the size
gizmo and the polygon corners, solidTiles in the tilemap collision,
requireVariablesAsset and requireBehaviorVariable.
- Left as is on purpose: the plain forwarding from the collision and
physics systems to Solids, the pointer wiring of the canvases and
the identical last lines of the two make commands.
- Removed unused code: tilemapTileIds and tilemapsUsing were never
called since #128 and #131. EditorState.runtimeProject became unused
with GameRun in #266. The assetId getter of the make commands was
read only by a test.
- 60 values used only in their own file lost their export. The shader
and particle node catalogues stay exported as in round 6.
- Five comments that told history now describe the current state. The
doc comment of BehaviorSystem sits on the class again.
- README lists the struct, clip area and curve assets and mentions the
game link from #266.
Findings:
- Deleting a tile that is painted on a tilemap leaves its cells in
place, and they draw nothing. The delete dialog does not mention the
tilemaps. That was probably the job of the unused tilemapsUsing.
Left as is, because fixing it changes behaviour.
- The solid filter for tile surfaces was untested. A bent filter
stayed green. A new test in tests/core/surface.test.ts now fails
against it.
Tests:
- ./check.sh: 195 files, 2815 tests, exit 0 (one test removed with
tilemapsUsing, one added for tile surfaces).
- Full e2e run: ALL PASSED, 1580 checks.
- Smokes jumprun, tetris, actor: 24, 19 and 21 checks, all passed.
The example project files were restored byte for byte afterwards.
- Counter-checks, 12, all fail as expected: 10 in unit tests (among
them mapNested, splitCubic, cubicAt, staleRevision, the stay pulse,
the late timer and the time scale), 2 in the browser (Point button
always enabled fails 47, selectedItem without a hit fails 29).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
226 lines
9.3 KiB
TypeScript
226 lines
9.3 KiB
TypeScript
import type { TaggedKind, ValueOf } from '../properties/kinds';
|
||
|
||
/** Lists and structs nest to any depth (#239): an item may be a list or a struct itself. */
|
||
export type ListValue = readonly PropertyValue[];
|
||
|
||
/** What a struct field or a list item holds – any value, since both nest to any depth. */
|
||
export type FieldValue = PropertyValue;
|
||
|
||
/** Several named values travelling as one, so a bundle needs one port instead of one per part. */
|
||
export type StructValue = { readonly [field: string]: PropertyValue };
|
||
|
||
/** Colors are stored as 0xRRGGBB numbers. */
|
||
export type PropertyValue = number | string | boolean | ListValue | StructValue;
|
||
|
||
export type PropertyBag = Record<string, PropertyValue>;
|
||
|
||
export const isList = (value: unknown): value is ListValue => Array.isArray(value);
|
||
|
||
/**
|
||
* A value of a kind JSON cannot show, under its kind's tag: `{ "$color": 16711680 }`,
|
||
* `{ "$texture": "walk-up" }`. Only a list needs it, where nothing is declared. A field name cannot
|
||
* start with `$` (`isValidFieldName`), so a tag never collides with a struct item of one field.
|
||
*/
|
||
export type TaggedItem = {
|
||
[K in TaggedKind]: { readonly [P in `$${K}`]: ValueOf<K> } & TaggedFields;
|
||
}[TaggedKind];
|
||
|
||
/** Indexable like any struct, so the one place that reads fields by name needs no special case. */
|
||
interface TaggedFields {
|
||
readonly [field: string]: FieldValue;
|
||
}
|
||
|
||
const TAG = '$';
|
||
|
||
/**
|
||
* The Struct asset a struct item follows (#254), kept in the item because a list declares at most
|
||
* one type for all of them – and a mixed list none. Model only: a run never sees it
|
||
* (`withoutItemTypes`), and no field can be called that, as no field name starts with `$`.
|
||
*/
|
||
export const ITEM_TYPE_KEY = '$struct';
|
||
|
||
/** The kind `value` wears as a tag, if it is a tagged item. */
|
||
export function tagOf(value: unknown): string | undefined {
|
||
if (!isStruct(value)) return undefined;
|
||
const keys = Object.keys(value);
|
||
const key = keys.length === 1 ? keys[0] : undefined;
|
||
return key?.startsWith(TAG) && key !== ITEM_TYPE_KEY ? key.slice(TAG.length) : undefined;
|
||
}
|
||
|
||
/** The Struct asset id a struct item is marked with, if any. */
|
||
export function itemTypeOf(value: PropertyValue | undefined): string | undefined {
|
||
if (!isStruct(value)) return undefined;
|
||
const id = value[ITEM_TYPE_KEY];
|
||
return typeof id === 'string' && id !== '' ? id : undefined;
|
||
}
|
||
|
||
/** The struct with its fields as they are, marked as `typeId` – or unmarked for `''`. */
|
||
export function withItemType(value: StructValue, typeId: string): StructValue {
|
||
const { [ITEM_TYPE_KEY]: _dropped, ...fields } = value;
|
||
return typeId ? { ...fields, [ITEM_TYPE_KEY]: typeId } : fields;
|
||
}
|
||
|
||
export function withoutField(value: StructValue, key: string): StructValue {
|
||
const { [key]: _dropped, ...rest } = value;
|
||
return rest;
|
||
}
|
||
|
||
/** Rebuilt rather than reassigned, so the field keeps its place in the value. */
|
||
export function withFieldRenamed(value: StructValue, from: string, to: string): StructValue {
|
||
const next: Record<string, FieldValue> = {};
|
||
for (const [key, item] of Object.entries(value)) next[key === from ? to : key] = item;
|
||
return next;
|
||
}
|
||
|
||
/**
|
||
* `value` with each part `swap` answers for replaced by the answer, through lists and untagged
|
||
* structs to any depth; `undefined` keeps a part and looks inside it. What is untouched keeps its
|
||
* identity, so a caller can tell whether anything changed.
|
||
*/
|
||
export function mapNested(value: unknown, swap: (part: unknown) => unknown): unknown {
|
||
const swapped = swap(value);
|
||
if (swapped !== undefined) return swapped;
|
||
if (isList(value)) {
|
||
const items = value.map((item) => mapNested(item, swap));
|
||
return items.some((item, i) => item !== value[i]) ? items : value;
|
||
}
|
||
if (isStruct(value) && tagOf(value) === undefined) {
|
||
const entries = Object.entries(value);
|
||
const mapped = entries.map(([key, field]) => [key, mapNested(field, swap)] as const);
|
||
return mapped.some(([, field], i) => field !== entries[i]![1]) ? Object.fromEntries(mapped) : value;
|
||
}
|
||
return value;
|
||
}
|
||
|
||
/** The value as a run holds it: every item-type mark taken out, at any depth. */
|
||
export function withoutItemTypes<T extends PropertyValue | undefined>(value: T): T {
|
||
if (isList(value)) return (value.some(holdsItemType) ? value.map(withoutItemTypes) : value) as T;
|
||
if (!isStruct(value) || !holdsItemType(value)) return value;
|
||
const out: Record<string, PropertyValue> = {};
|
||
for (const [key, item] of Object.entries(value))
|
||
if (key !== ITEM_TYPE_KEY) out[key] = withoutItemTypes(item);
|
||
return out as T;
|
||
}
|
||
|
||
export function bagWithoutItemTypes(bag: PropertyBag): PropertyBag {
|
||
if (!Object.values(bag).some(holdsItemType)) return bag;
|
||
const out: PropertyBag = {};
|
||
for (const [key, value] of Object.entries(bag)) out[key] = withoutItemTypes(value);
|
||
return out;
|
||
}
|
||
|
||
function holdsItemType(value: PropertyValue | undefined): boolean {
|
||
if (isList(value)) return value.some(holdsItemType);
|
||
if (!isStruct(value)) return false;
|
||
return ITEM_TYPE_KEY in value || Object.values(value).some(holdsItemType);
|
||
}
|
||
|
||
export function tagged(kind: TaggedKind, value: number | string): TaggedItem {
|
||
return { [TAG + kind]: value } as TaggedItem;
|
||
}
|
||
|
||
/**
|
||
* What an object's place holds at rest when it names no object – a variable, a struct field, a list
|
||
* item alike. Tagged, so a run tells the place apart from an empty text (`graph/liveObjects.ts`).
|
||
*/
|
||
export const NO_OBJECT: TaggedItem = tagged('object', '');
|
||
|
||
/**
|
||
* `value` as an object's place: the object of the same scene it names (#258, `model/objectRefs.ts`),
|
||
* or none – whatever else it was.
|
||
*/
|
||
export function objectPlace(value: PropertyValue | undefined): TaggedItem {
|
||
const id = tagOf(value) === 'object' ? (value as StructValue)[TAG + 'object'] : '';
|
||
return typeof id === 'string' && id ? tagged('object', id) : NO_OBJECT;
|
||
}
|
||
|
||
/** A tagged item as what it wraps; anything else as itself. */
|
||
export function untag(value: PropertyValue | undefined): PropertyValue | undefined {
|
||
const tag = tagOf(value);
|
||
return tag === undefined ? value : (value as StructValue)[TAG + tag];
|
||
}
|
||
|
||
/**
|
||
* Model-level only: a live entity handle is an object too, and the graph tells the two apart by
|
||
* the handle's brand (see `values.ts`). Nothing in a PropertyBag is ever a handle.
|
||
*/
|
||
export const isStruct = (value: unknown): value is StructValue =>
|
||
typeof value === 'object' && value !== null && !Array.isArray(value);
|
||
|
||
/**
|
||
* A property value as text. Nothing may hand a PropertyValue to `String()` directly: a struct would
|
||
* come out as "[object Object]" and a list without separators.
|
||
*/
|
||
export function textOf(value: PropertyValue | undefined): string {
|
||
if (value === undefined) return '';
|
||
if (isList(value)) return value.map((item) => textOf(item)).join(', ');
|
||
// A tagged value reads as what it wraps, the same as the matching property does.
|
||
if (tagOf(value) !== undefined) return textOf(untag(value));
|
||
if (isStruct(value))
|
||
return Object.entries(value)
|
||
.filter(([field]) => field !== ITEM_TYPE_KEY)
|
||
.map(([field, item]) => `${field}: ${textOf(item)}`)
|
||
.join(', ');
|
||
return String(value);
|
||
}
|
||
|
||
/** The spelling of a text counts: `Boolean('false')` would be true. */
|
||
export function booleanOf(value: unknown): boolean {
|
||
if (typeof value !== 'string') return Boolean(value);
|
||
const s = value.trim().toLowerCase();
|
||
return !(s === '' || s === 'false' || s === '0' || s === 'no');
|
||
}
|
||
|
||
/** A number, or a hex text with or without `#`, clamped to 0…0xffffff. */
|
||
export function colorOf(value: PropertyValue, fallback: number): number {
|
||
const n = typeof value === 'number' ? value : parseInt(textOf(value).replace('#', ''), 16);
|
||
return Number.isFinite(n) ? Math.max(0, Math.min(0xffffff, Math.floor(n))) : fallback;
|
||
}
|
||
|
||
/** Values are compared by content, because two equal lists (or structs) are never the same object. */
|
||
export function sameValue(a: PropertyValue | undefined, b: PropertyValue | undefined): boolean {
|
||
if (a === b) return true;
|
||
// A live handle (a run's bag may hold one, branded by a symbol) is only ever itself.
|
||
if (isBranded(a) || isBranded(b)) return false;
|
||
if (isList(a) || isList(b)) {
|
||
if (!isList(a) || !isList(b) || a.length !== b.length) return false;
|
||
return a.every((item, i) => sameValue(item, b[i]));
|
||
}
|
||
if (isStruct(a) || isStruct(b)) {
|
||
if (!isStruct(a) || !isStruct(b)) return false;
|
||
const keys = Object.keys(a);
|
||
return keys.length === Object.keys(b).length && keys.every((key) => sameValue(a[key], b[key]));
|
||
}
|
||
return a === b;
|
||
}
|
||
|
||
const isBranded = (value: unknown): boolean =>
|
||
isStruct(value) && Object.getOwnPropertySymbols(value).length > 0;
|
||
|
||
/** `undefined` removes the key, which is how an undo of "no value" works. */
|
||
export function setBagValue(bag: PropertyBag, key: string, value: PropertyValue | undefined): void {
|
||
if (value === undefined) delete bag[key];
|
||
else bag[key] = value;
|
||
}
|
||
|
||
export interface Vec2 {
|
||
x: number;
|
||
y: number;
|
||
}
|
||
|
||
/** `x`/`y` in world units; `z` is the draw order – higher is on top, ties keep hierarchy order. */
|
||
export interface Position extends Vec2 {
|
||
z: number;
|
||
}
|
||
|
||
export type Axis = keyof Position;
|
||
|
||
export function toPosition(point: Vec2 | Position): Position {
|
||
return { x: point.x, y: point.y, z: 'z' in point ? point.z : 0 };
|
||
}
|
||
|
||
/** Stable draw order: ascending `z`, ties keep the input (hierarchy) order. */
|
||
export function sortByZ<T extends { z: number }>(items: readonly T[]): T[] {
|
||
return [...items].sort((a, b) => a.z - b.z);
|
||
}
|