Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
a composition's controls in the SDK, sdk/video's registry and systems/tweak's values
shinyobjectzbd9f7b73b87a
diff --git a/sdk/guides/craft/motion/compositions.md b/sdk/guides/craft/motion/compositions.mdindex 3ce2824e..8fc8942c 100644--- a/sdk/guides/craft/motion/compositions.md+++ b/sdk/guides/craft/motion/compositions.md@@ -8,6 +8,7 @@- `id` uses letters, digits and hyphens only (no spaces, no underscores) and is unique in the root.- `width`, `height` and `durationInFrames` are positive whole numbers, and `fps` is a positive number.- `defaultProps` (optional) is a plain object of JSON values, which the component receives as its props.+ - `controls` (optional) says which of those props a person may tune: see "Controls" below.- Size the composition from the shape the brief asks for: 1080x1920 (9:16), 1080x1350 (4:5), 1080x1080 (1:1) or1920x1080 (16:9). Use 30 fps unless the footage or brief says otherwise. Set the length as`Math.round(seconds * fps)`.@@ -22,6 +23,36 @@7. the main component, which places the clips, parts and sounds in `Sequence`s;8. `Root` and `registerRoot(Root)`.+## Controls: anything a person might tune++Anything a person might tune goes in `controls`: a colour, a warmth, a speed, a size, a title's words, which model+or take is used, whether it rains. Make it a prop with its value in `defaultProps`, read it in the component (as a+prop, or with `useControl("name")` in a part deep in the tree), and declare it in `controls` by the same key. The+feed's Controls panel lists them beside the timeline, and moving one changes the live picture at once, then the+render around it; a value written in the middle of the code is one the person can only ask you to change.++- Each control names a `defaultProps` key, and its `kind` fits that value: `number` (with `min`, `max`, `step` and+ `unit` when it has a range), `switch` (true or false), `choice` (one of `options`), `colour` (a hex string,+ `"#rgb"` to `"#rrggbbaa"`) or `text` (`maxLength`, `multiline`). The registry refuses one that doesn't fit, naming+ the control.+- `group` puts related controls together ("Grade", "Camera", "Words"); `label` and `about` are what the panel shows.+- `cost` says how a change reaches the picture. `live` (the default) is drawn at once, for values the running world+ takes frame by frame: a place, a turn, a size, a colour, roughness and metalness, a glow, opacity, a light's+ strength, the camera, any 2D style or text. `reopen` is for what a 3D world keeps from its first frame: a shape's+ geometry, a model's file, an instance count, a picture map, a shader. `resim` is for state carried from frame to+ frame: physics, particles, a game's fold.++```tsx+<Composition id="mayor" component={Film} width={1920} height={1080} fps={30} durationInFrames={2700}+ controls={{+ warmth: { kind: "number", min: -1, max: 1, step: 0.05, group: "Grade" },+ model: { kind: "choice", options: ["goose", "mayor"], cost: "reopen" },+ rain: { kind: "switch", cost: "resim" },+ title: { kind: "text", maxLength: 40, group: "Words" },+ }}+ defaultProps={{ warmth: 0.2, model: "goose", rain: false, title: "Swamp-Side Mayor" }} />+```+## WhyThe renderer finds compositions by walking the root's element tree without rendering it. It never calls a@@ -40,6 +71,10 @@ anyway, because a guessed size or length is how a 16:9 brief comes out vertical.- Calling `registerRoot` twice, or once per composition. Register one root that returns several `<Composition>`s.- A `Root` that calls `useCurrentFrame()` or `useVideoConfig()`. Hooks belong in the composition's component.- `defaultProps` holding a function, a Date or a class instance. Only JSON values are allowed.+- A tunable value as a literal in a part (`const WARMTH = 0.2`, `color="#d04a3a"` in a mesh): the person can't move+ it. Make it a prop in `defaultProps` and a control.+- A control for a key `defaultProps` doesn't have, or a `number` control whose value is outside its `min` and `max`:+ registering fails, naming the control.- Writing a second file for "the parts" and importing it. That works (modules resolve from the importing file), butone self-contained file is easier for the next pass to read and is how the approved pieces are written.@@ -67,11 +102,14 @@ export default function EndCard({ line }: { line: string }) {);}+/** What a person may tune: the line's words. */+const controls = { line: { kind: "text", maxLength: 32, group: "Words" } } as const;+function Root() {return (<>- <Composition id="end-9x16" component={EndCard} width={1080} height={1920} fps={30} durationInFrames={90} defaultProps={{ line: "Try it free" }} />- <Composition id="end-16x9" component={EndCard} width={1920} height={1080} fps={30} durationInFrames={90} defaultProps={{ line: "Try it free" }} />+ <Composition id="end-9x16" component={EndCard} width={1080} height={1920} fps={30} durationInFrames={90} defaultProps={{ line: "Try it free" }} controls={controls} />+ <Composition id="end-16x9" component={EndCard} width={1920} height={1080} fps={30} durationInFrames={90} defaultProps={{ line: "Try it free" }} controls={controls} /></>);}diff --git a/sdk/raea/conformance/controls.test.tsx b/sdk/raea/conformance/controls.test.tsxnew file mode 100644index 00000000..25c71d88--- /dev/null+++ b/sdk/raea/conformance/controls.test.tsx@@ -0,0 +1,99 @@+// A composition's controls (docs/realtime.feature RT4a, RT4c): each names a defaultProps key and fits its kind, the+// registry hands them on with their cost said, and useControl reads the value the frame is drawn with.+import { beforeEach, expect, test } from "bun:test";+import { Composition, Sequence, getCompositions, registerRoot, useControl, useCurrentFrame } from "../src";+import { renderFrame, resetRegistry } from "../src/test";++beforeEach(() => resetRegistry());+function Card() { useCurrentFrame(); return null; }+const base = { id: "card", component: Card, width: 640, height: 360, fps: 30, durationInFrames: 60 } as const;+const register = (props: Record<string, unknown>) => registerRoot(() => <Composition {...base} {...(props as object)} />);++test("each kind of control is registered with its cost, in the order declared", () => {+ register({+ defaultProps: { warmth: 0.2, rain: false, model: "goose", tint: "#ff8800", title: "Swamp", size: 2 },+ controls: {+ warmth: { kind: "number", min: -1, max: 1, step: 0.05, group: "Grade" },+ rain: { kind: "switch", cost: "resim" },+ model: { kind: "choice", options: ["goose", "mayor"], cost: "reopen" },+ tint: { kind: "colour", label: "Tint" },+ title: { kind: "text", maxLength: 40 },+ },+ });+ const c = getCompositions()[0];+ expect(Object.keys(c.controls)).toEqual(["warmth", "rain", "model", "tint", "title"]);+ expect(c.controls.warmth).toEqual({ kind: "number", min: -1, max: 1, step: 0.05, group: "Grade", cost: "live" });+ expect(c.controls.rain.cost).toBe("resim");+ expect(c.controls.model).toMatchObject({ kind: "choice", options: ["goose", "mayor"], cost: "reopen" });+ expect(c.controls.tint).toMatchObject({ kind: "colour", label: "Tint", cost: "live" });+ // a prop with no control stays a prop+ expect(c.controls.size).toBeUndefined();+});++test("a composition with no controls registers none", () => {+ register({ defaultProps: { hue: 210 } });+ expect(getCompositions()[0].controls).toEqual({});+ resetRegistry();+ registerRoot(() => <Card />);+ expect(getCompositions()[0].controls).toEqual({});+});++test("a control names a defaultProps key", () => {+ expect(() => register({ defaultProps: { hue: 210 }, controls: { warmth: { kind: "number" } } })).toThrow(+ 'Composition "card": controls.warmth names no defaultProps key: a control tunes a prop the composition has a value for (defaultProps has hue)',+ );+ expect(() => register({ controls: { warmth: { kind: "number" } } })).toThrow(/defaultProps has none/);+});++// each kind and the values that don't fit it, with what the error says+const misfits: [string, Record<string, unknown>, unknown, RegExp][] = [+ ["kind", { kind: "slider" }, 1, /controls.v.kind must be one of number, switch, choice, colour, text, got "slider"/],+ ["cost", { kind: "number", cost: "later" }, 1, /controls.v.cost must be one of live, reopen, resim/],+ ["number", { kind: "number" }, "1", /controls.v is a number, but defaultProps.v is "1"/],+ ["number range", { kind: "number", min: 0, max: 1 }, 2, /controls.v is 0 to 1, but defaultProps.v is 2/],+ ["min above max", { kind: "number", min: 2, max: 1 }, 1.5, /has min 2 above max 1/],+ ["step", { kind: "number", step: 0 }, 1, /controls.v.step must be above 0/],+ ["switch", { kind: "switch" }, 0, /controls.v is a switch, but defaultProps.v is 0/],+ ["choice options", { kind: "choice", options: [] }, "a", /controls.v.options must be a non-empty list/],+ ["choice twice", { kind: "choice", options: ["a", "a"] }, "a", /lists "a" twice/],+ ["choice value", { kind: "choice", options: ["a", "b"] }, "c", /controls.v is one of "a", "b", but defaultProps.v is "c"/],+ ["colour", { kind: "colour" }, "orange", /controls.v is a colour, but defaultProps.v is "orange"/],+ ["colour length", { kind: "colour" }, "#ff888", /is a colour/],+ ["text", { kind: "text" }, 3, /controls.v is text, but defaultProps.v is 3/],+ ["text length", { kind: "text", maxLength: 3 }, "four", /holds at most 3 characters, but defaultProps.v has 4/],+ ["label", { kind: "text", label: 3 }, "a", /controls.v.label must be a string/],+];+for (const [what, spec, value, why] of misfits) {+ test(`a control's value must fit its kind: ${what}`, () => {+ resetRegistry();+ expect(() => register({ defaultProps: { v: value }, controls: { v: spec } })).toThrow(why);+ });+}++test("colours take three, four, six or eight hex digits", () => {+ for (const tint of ["#f80", "#f80c", "#ff8800", "#FF8800cc"]) {+ resetRegistry();+ register({ defaultProps: { tint }, controls: { tint: { kind: "colour" } } });+ expect(getCompositions()[0].controls.tint.kind).toBe("colour");+ }+});++test("controls must be an object", () => {+ expect(() => register({ defaultProps: { v: 1 }, controls: [{ kind: "number" }] })).toThrow(/controls must be an object of controls by defaultProps key/);+});++test("useControl reads the value the frame is drawn with, inside a Sequence too", () => {+ const seen: unknown[] = [];+ function Deep() { seen.push(useControl("warmth")); return null; }+ const opts = { frame: 10, fps: 30, width: 640, height: 360, durationInFrames: 60 };+ renderFrame(<Sequence from={5}><Deep /></Sequence>, { ...opts, defaultProps: { warmth: 0.2 } });+ renderFrame(<Deep />, { ...opts, defaultProps: { warmth: 0.7 } });+ expect(seen).toEqual([0.2, 0.7]);+});++test("useControl names a prop the composition has", () => {+ function Wrong() { useControl("warmth"); return null; }+ expect(() => renderFrame(<Wrong />, { frame: 0, fps: 30, width: 64, height: 64, durationInFrames: 1, defaultProps: { hue: 1 } })).toThrow(+ 'useControl("warmth"): the composition has no prop "warmth" (its defaultProps has hue)',+ );+});diff --git a/sdk/raea/src/index.tsx b/sdk/raea/src/index.tsxindex 63007bc4..d93df9a3 100644--- a/sdk/raea/src/index.tsx+++ b/sdk/raea/src/index.tsx@@ -50,9 +50,19 @@ export {Composition,getCompositions,registerRoot,+ useControl,type CompositionProps,type Edit,type RegisteredComposition,+ type Control,+ type Controls,+ type ControlCost,+ type RegisteredControl,+ type NumberControl,+ type SwitchControl,+ type ChoiceControl,+ type ColourControl,+ type TextControl,} from "@raea/video/registry";export { Effect, effectAt, type EffectProps } from "@raea/video/effect";diff --git a/sdk/video/src/registry.tsx b/sdk/video/src/registry.tsxindex 3bd23068..925045b1 100644--- a/sdk/video/src/registry.tsx+++ b/sdk/video/src/registry.tsx@@ -1,6 +1,7 @@// Composition and registerRoot: record what's registered so a renderer can list compositions// (spec: "Declaring and registering", "The clock renderers use").import { Children, isValidElement, type ComponentType, type ReactElement, type ReactNode } from "react";+import { useVideoConfig } from "@raea/app/clock";import { Audio, Video } from "./media";import { Region } from "./region";import { Freeze, Loop, Sequence, Series } from "./timeline";@@ -20,10 +21,78 @@ export interface CompositionProps<P extends Record<string, unknown> = Record<strdurationInFrames: number;/** the props it's rendered with (JSON-like values only) */defaultProps?: P;+ /** the composition's controls: which of its defaultProps a person may tune, and how (docs/realtime.feature RT4).+ * Each names a defaultProps key, whose value is the control's; the feed's Controls panel shows them on the+ * timeline and a change reaches the live picture as that prop */+ controls?: Controls<P>;/** a hand edit laid over the composition (docs/craft-system.md, L): written back by the app's timeline */edit?: Edit;}+/** How a change to a control reaches the picture. `live` (the default): the running stage draws it at once, as a+ * prop. `reopen`: the stage opens the file again first, for what a running 3D world keeps from its first frame (a+ * shape, a model's file, an instance count, a picture map, a shader). `resim`: everything from the frame it changes+ * on is worked out again, for state carried from frame to frame (physics, particles, a game's fold). */+export type ControlCost = "live" | "reopen" | "resim";++interface ControlBase {+ /** what the panel calls it (the key when left out) */+ label?: string;+ /** the panel's group it sits in ("Grade", "Camera"); ungrouped controls come first */+ group?: string;+ /** how a change reaches the picture: "live" unless said */+ cost?: ControlCost;+ /** one line on what it changes, for the panel's tooltip and an agent reading the code */+ about?: string;+}++/** A number, dragged on a slider when it has both ends. */+export interface NumberControl extends ControlBase {+ kind: "number";+ /** the least it may be */+ min?: number;+ /** the most it may be */+ max?: number;+ /** what one step of the slider or an arrow key moves it by (above 0) */+ step?: number;+ /** its unit, shown after it ("px", "°", "s") */+ unit?: string;+}++/** On or off: a boolean. */+export interface SwitchControl extends ControlBase {+ kind: "switch";+}++/** One of a list: a string or a number from `options`. */+export interface ChoiceControl extends ControlBase {+ kind: "choice";+ /** what it may be, in the order the panel lists them (at least one, none twice) */+ options: readonly (string | number)[];+}++/** A colour: a hex string, "#rgb", "#rgba", "#rrggbb" or "#rrggbbaa". */+export interface ColourControl extends ControlBase {+ kind: "colour";+}++/** A string: a title, a caption, a name. */+export interface TextControl extends ControlBase {+ kind: "text";+ /** a box of several lines rather than one */+ multiline?: boolean;+ /** the most characters it may hold */+ maxLength?: number;+}++export type Control = NumberControl | SwitchControl | ChoiceControl | ColourControl | TextControl;++/** A composition's controls, by the defaultProps key each one tunes. */+export type Controls<P = Record<string, unknown>> = { readonly [K in keyof P & string]?: Control };++/** A control as a registered composition holds it: its cost said. */+export type RegisteredControl = Control & { cost: ControlCost };+/** A hand edit: `segments` are the composition's own frame ranges, [from, to), played one after another, so a trim,* a split, a cut word or a moved span is a change to this list; the length becomes their sum. */export interface Edit {@@ -51,9 +120,80 @@ export interface RegisteredComposition {durationInFrames: number;/** the props it's rendered with (JSON-like values only) */defaultProps: Record<string, unknown>;+ /** its controls, by defaultProps key, in the order they're declared ({} when it has none) */+ controls: Readonly<Record<string, RegisteredControl>>;}const ID_PATTERN = /^[A-Za-z0-9-]+$/;+const KINDS: readonly Control["kind"][] = ["number", "switch", "choice", "colour", "text"];+const COSTS: readonly ControlCost[] = ["live", "reopen", "resim"];+const HEX = /^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;++/** The controls checked against the defaultProps they tune: each names one of its keys, says a kind and a cost+ * raea knows, and its value fits that kind. `fail(field, why)` throws. */+function validControls(given: unknown, props: Record<string, unknown>, fail: (field: string, why: string) => never): Record<string, RegisteredControl> {+ if (given === undefined) return {};+ if (given === null || typeof given !== "object" || Array.isArray(given) || Object.getPrototypeOf(given) !== Object.prototype) {+ fail("controls", "must be an object of controls by defaultProps key");+ }+ const out: Record<string, RegisteredControl> = {};+ for (const [key, c] of Object.entries(given as Record<string, unknown>)) {+ const at = `controls.${key}`;+ if (!Object.prototype.hasOwnProperty.call(props, key)) {+ const keys = Object.keys(props);+ fail(at, `names no defaultProps key: a control tunes a prop the composition has a value for (defaultProps has ${keys.length ? keys.join(", ") : "none"})`);+ }+ if (c === null || typeof c !== "object" || Array.isArray(c)) fail(at, `must be an object with a kind (${KINDS.join(", ")})`);+ const spec = c as Record<string, unknown>;+ if (!KINDS.includes(spec.kind as Control["kind"])) fail(`${at}.kind`, `must be one of ${KINDS.join(", ")}, got ${JSON.stringify(spec.kind)}`);+ if (spec.cost !== undefined && !COSTS.includes(spec.cost as ControlCost)) fail(`${at}.cost`, `must be one of ${COSTS.join(", ")}, got ${JSON.stringify(spec.cost)}`);+ for (const f of ["label", "group", "about", "unit"] as const) {+ if (spec[f] !== undefined && typeof spec[f] !== "string") fail(`${at}.${f}`, `must be a string, got ${JSON.stringify(spec[f])}`);+ }+ const v = props[key];+ const got = JSON.stringify(v);+ switch (spec.kind as Control["kind"]) {+ case "number": {+ for (const f of ["min", "max", "step"] as const) {+ if (spec[f] !== undefined && !(typeof spec[f] === "number" && Number.isFinite(spec[f]))) fail(`${at}.${f}`, `must be a finite number, got ${JSON.stringify(spec[f])}`);+ }+ const { min, max, step } = spec as { min?: number; max?: number; step?: number };+ if (min !== undefined && max !== undefined && min > max) fail(at, `has min ${min} above max ${max}`);+ if (step !== undefined && !(step > 0)) fail(`${at}.step`, `must be above 0, got ${step}`);+ if (typeof v !== "number" || !Number.isFinite(v)) fail(at, `is a number, but defaultProps.${key} is ${got}`);+ if ((min !== undefined && (v as number) < min) || (max !== undefined && (v as number) > max)) fail(at, `is ${min ?? "-∞"} to ${max ?? "∞"}, but defaultProps.${key} is ${got}`);+ break;+ }+ case "switch":+ if (typeof v !== "boolean") fail(at, `is a switch, but defaultProps.${key} is ${got} (it takes true or false)`);+ break;+ case "choice": {+ const options = spec.options;+ if (!Array.isArray(options) || options.length === 0 || !options.every((o) => typeof o === "string" || (typeof o === "number" && Number.isFinite(o)))) {+ fail(`${at}.options`, "must be a non-empty list of strings or numbers");+ }+ const opts = options as (string | number)[];+ const twice = opts.find((o, i) => opts.indexOf(o) !== i);+ if (twice !== undefined) fail(`${at}.options`, `lists ${JSON.stringify(twice)} twice`);+ if (!opts.includes(v as string | number)) fail(at, `is one of ${opts.map((o) => JSON.stringify(o)).join(", ")}, but defaultProps.${key} is ${got}`);+ break;+ }+ case "colour":+ if (typeof v !== "string" || !HEX.test(v)) fail(at, `is a colour, but defaultProps.${key} is ${got} (it takes "#rgb", "#rgba", "#rrggbb" or "#rrggbbaa")`);+ break;+ case "text": {+ const { maxLength } = spec as { maxLength?: unknown };+ if (maxLength !== undefined && !(Number.isInteger(maxLength) && (maxLength as number) > 0)) fail(`${at}.maxLength`, `must be a positive integer, got ${JSON.stringify(maxLength)}`);+ if (spec.multiline !== undefined && typeof spec.multiline !== "boolean") fail(`${at}.multiline`, `must be true or false, got ${JSON.stringify(spec.multiline)}`);+ if (typeof v !== "string") fail(at, `is text, but defaultProps.${key} is ${got}`);+ if (maxLength !== undefined && (v as string).length > (maxLength as number)) fail(at, `holds at most ${maxLength} characters, but defaultProps.${key} has ${(v as string).length}`);+ break;+ }+ }+ out[key] = { ...(spec as unknown as Control), cost: (spec.cost as ControlCost | undefined) ?? "live" };+ }+ return out;+}function isJsonLike(v: unknown, seen: Set<unknown>): boolean {if (v === null || typeof v === "string" || typeof v === "boolean") return true;@@ -102,6 +242,7 @@ function validate(props: CompositionProps<any>, taken: readonly RegisteredComposconst scale = props.edit?.scale;if (scale !== undefined && !(typeof scale === "number" && scale > 0 && scale <= 1)) fail("edit.scale", `must be a number above 0 and at most 1, got ${scale}`);const [w, h] = scale === undefined || scale === 1 ? [props.width, props.height] : [Math.max(1, Math.round(props.width * scale)), Math.max(1, Math.round(props.height * scale))];+ const controls = validControls(props.controls, defaultProps as Record<string, unknown>, fail);const cut = segments ? edited(props.component, segments) : props.component;return {id: props.id,@@ -111,6 +252,7 @@ function validate(props: CompositionProps<any>, taken: readonly RegisteredComposfps: props.fps,durationInFrames: segments ? segments.reduce((n, [a, b]) => n + b - a, 0) : props.durationInFrames,defaultProps,+ controls,};}@@ -153,6 +295,18 @@ function scaled(Component: ComponentType<any>, width: number, height: number, w:return Scaled;}+/** A control's value as the frame is drawn (docs/realtime.feature RT4c): the composition's prop of that name, the+ * value a person set on the live stage or, in a render, its defaultProps. For a part deep in the tree, so the value+ * needn't be passed down as a prop; the root component can read its props as any component does. */+export function useControl<T = unknown>(name: string): T {+ const { defaultProps } = useVideoConfig();+ if (!Object.prototype.hasOwnProperty.call(defaultProps, name)) {+ const keys = Object.keys(defaultProps);+ throw new Error(`useControl("${name}"): the composition has no prop "${name}" (its defaultProps has ${keys.length ? keys.join(", ") : "none"})`);+ }+ return defaultProps[name] as T;+}+/** Declares a composition inside the root. It draws nothing itself; a renderer finds it through registerRoot. */export function Composition<P extends Record<string, unknown>>(_props: CompositionProps<P>) {return null;@@ -413,6 +567,7 @@ export function registerRoot(given: ComponentType | ReactElement): void {durationInFrames: walk.latestEnd > 0 ? Math.ceil(walk.latestEnd) : IMPLICIT.durationInFrames,component: Root,defaultProps: {},+ controls: {},});}root = Root;diff --git a/systems/tweak/src/lib.rs b/systems/tweak/src/lib.rsindex 5b4853b8..0de07b48 100644--- a/systems/tweak/src/lib.rs+++ b/systems/tweak/src/lib.rs@@ -8,6 +8,9 @@use std::path::{Path, PathBuf};+mod values;+pub use values::values_only;+use oxc::allocator::Allocator;use oxc::ast::ast::*;use oxc::ast_visit::{Visit, walk};diff --git a/systems/tweak/src/values.rs b/systems/tweak/src/values.rsnew file mode 100644index 00000000..95796810--- /dev/null+++ b/systems/tweak/src/values.rs@@ -0,0 +1,152 @@+//! Two versions of a composition that differ only in the values of its `<Composition defaultProps>` (docs/realtime.feature+//! RT4f): a control's value written into the file, as the app writes one on release. The stage takes such a version in+//! place of opening it again (its props laid over the running world), so writing a value costs no reopen.++use oxc::allocator::Allocator;+use oxc::ast::ast::*;+use oxc::ast_visit::{Visit, walk};+use oxc::parser::Parser;+use oxc::span::{GetSpan, SourceType, Span};+use serde_json::{Map, Number, Value};++/// The `defaultProps={...}` of each `<Composition>` element: its span, and its values when it is an object written out.+#[derive(Default)]+struct Defaults {+ found: Vec<(Span, Option<Map<String, Value>>)>,+}++impl<'a> Visit<'a> for Defaults {+ fn visit_jsx_opening_element(&mut self, it: &JSXOpeningElement<'a>) {+ // a capitalised name is a reference to the component (`Composition`, imported from raea)+ if matches!(&it.name, JSXElementName::IdentifierReference(n) if n.name == "Composition") {+ for a in &it.attributes {+ if let JSXAttributeItem::Attribute(a) = a+ && matches!(&a.name, JSXAttributeName::Identifier(n) if n.name == "defaultProps")+ && let Some(JSXAttributeValue::ExpressionContainer(c)) = &a.value+ && let Some(e) = c.expression.as_expression()+ {+ self.found.push((e.span(), match e.without_parentheses() {+ Expression::ObjectExpression(o) => object(o),+ _ => None,+ }));+ }+ }+ }+ walk::walk_jsx_opening_element(self, it);+ }+}++/// A value written out in the file as JSON: a string, number, true/false, null, or an array or object of them. None for+/// anything worked out (a name, a call, a spread, a computed key).+fn value(e: &Expression) -> Option<Value> {+ Some(match e.without_parentheses() {+ Expression::StringLiteral(s) => Value::String(s.value.to_string()),+ Expression::TemplateLiteral(t) if t.expressions.is_empty() => Value::String(t.quasis.iter().map(|q| q.value.cooked.as_ref().map_or(q.value.raw.as_str(), |c| c.as_str())).collect()),+ Expression::NumericLiteral(n) => number(n.value)?,+ Expression::UnaryExpression(u) if u.operator == UnaryOperator::UnaryNegation => match &u.argument {+ Expression::NumericLiteral(n) => number(-n.value)?,+ _ => return None,+ },+ Expression::BooleanLiteral(b) => Value::Bool(b.value),+ Expression::NullLiteral(_) => Value::Null,+ Expression::ArrayExpression(a) => Value::Array(a.elements.iter().map(|el| el.as_expression().and_then(value)).collect::<Option<_>>()?),+ Expression::ObjectExpression(o) => Value::Object(object(o)?),+ Expression::TSAsExpression(t) => value(&t.expression)?,+ Expression::TSSatisfiesExpression(t) => value(&t.expression)?,+ _ => return None,+ })+}++/// A number as JSON.stringify writes it (35, not 35.0), so the values compare with what the composition's JS reports.+fn number(v: f64) -> Option<Value> {+ if v.fract() == 0.0 && v.abs() < 9_007_199_254_740_992.0 {+ return Some(Value::Number(Number::from(v as i64)));+ }+ Number::from_f64(v).map(Value::Number)+}++fn object(o: &ObjectExpression) -> Option<Map<String, Value>> {+ let mut out = Map::new();+ for p in &o.properties {+ let ObjectPropertyKind::ObjectProperty(p) = p else { return None };+ if p.computed || p.method || p.kind != PropertyKind::Init {+ return None;+ }+ out.insert(p.key.static_name()?.to_string(), value(&p.value)?);+ }+ Some(out)+}++/// The one `<Composition defaultProps>` literal of a source, its span and its values; None when it has none, several, or+/// one that isn't written out as values, or doesn't parse.+fn defaults(src: &str) -> Option<(Span, Map<String, Value>)> {+ let alloc = Allocator::default();+ let ret = Parser::new(&alloc, src, SourceType::tsx()).parse();+ if ret.diagnostics.errors().next().is_some() {+ return None;+ }+ let mut d = Defaults::default();+ d.visit_program(&ret.program);+ match d.found.pop() {+ Some((span, Some(values))) if d.found.is_empty() => Some((span, values)),+ _ => None,+ }+}++/// `new`'s defaultProps when it is `old` with only the values of its one `<Composition defaultProps={{ ... }}>` changed:+/// the same text around them, the same keys, each value written out (no name or call). None for any other change, which+/// the stage opens again.+pub fn values_only(old: &str, new: &str) -> Option<Map<String, Value>> {+ let (a, was) = defaults(old)?;+ let (b, now) = defaults(new)?;+ let around = |s: &str, sp: Span| (s[..sp.start as usize].to_string(), s[sp.end as usize..].to_string());+ if around(old, a) != around(new, b) || was.len() != now.len() || !was.keys().all(|k| now.contains_key(k)) {+ return None;+ }+ Some(now)+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ const FILM: &str = r##"import { Composition, registerRoot } from "raea";+import { Film } from "./film";+const W = 1920;+registerRoot(() => (+ <Composition id="mayor" component={Film} width={W} height={1080} fps={30} durationInFrames={2700}+ controls={{ warmth: { kind: "number", min: -1, max: 1 } }}+ defaultProps={{ warmth: 0.2, model: "goose", rain: false, tint: "#ff8800", shots: [1, 2], cam: { fov: 40 } }} />+));+"##;++ #[test]+ fn a_value_written_into_the_defaults_is_values_only() {+ let new = FILM.replace("warmth: 0.2", "warmth: -0.5").replace(r##""#ff8800""##, r##""#00ff88""##).replace("fov: 40", "fov: 35");+ let v = values_only(FILM, &new).unwrap();+ assert_eq!(Value::Object(v), json!({"warmth": -0.5, "model": "goose", "rain": false, "tint": "#00ff88", "shots": [1, 2], "cam": {"fov": 35}}));+ // the same file is values only too, its values as they are+ assert_eq!(values_only(FILM, FILM).unwrap()["model"], json!("goose"));+ }++ #[test]+ fn anything_else_changed_is_not() {+ // code outside the defaults+ assert!(values_only(FILM, &FILM.replace("height={1080}", "height={720}")).is_none());+ // a control's spec+ assert!(values_only(FILM, &FILM.replace("max: 1 }", "max: 2 }")).is_none());+ // a key added or taken away+ assert!(values_only(FILM, &FILM.replace("rain: false, ", "")).is_none());+ assert!(values_only(FILM, &FILM.replace("rain: false,", "rain: false, wind: 1,")).is_none());+ // a value worked out, or named+ assert!(values_only(FILM, &FILM.replace("warmth: 0.2", "warmth: W / 10")).is_none());+ assert!(values_only(FILM, &FILM.replace("warmth: 0.2", "warmth: W")).is_none());+ // a file that doesn't parse, or has no literal defaults, or two compositions with them+ assert!(values_only(FILM, &FILM.replace("registerRoot(() => (", "registerRoot(() => ((")).is_none());+ let named = FILM.replace(r###"defaultProps={{ warmth: 0.2, model: "goose", rain: false, tint: "#ff8800", shots: [1, 2], cam: { fov: 40 } }}"###, "defaultProps={PROPS}");+ assert!(values_only(&named, &named).is_none());+ let two = FILM.replace("/>\n));", "/>\n));\nconst Two = () => <Composition id=\"b\" component={Film} width={1} height={1} fps={30} durationInFrames={1} defaultProps={{ a: 1 }} />;");+ assert!(values_only(&two, &two).is_none());+ }+}