@motionscript/react 0.1.0-alpha.7 → 0.1.0-alpha.9

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.
@@ -1 +1 @@
1
- {"version":3,"file":"motionscript-react.js","names":[],"sources":["../src/ui/use-engine.ts","../src/ui/playhead.ts","../src/ui/use-motion-player.ts","../src/ui/stage.tsx"],"sourcesContent":["import { useEffect, useRef, useState, type DependencyList } from \"react\";\n\nimport type { Engine } from \"@motionscript/core\";\n\nexport interface UseEngineOptions {\n /**\n * Rebuild the engine when any of these change, compared the way\n * `useEffect` compares its own. The default, `[]`, builds it once.\n *\n * Not for the factory's closure: the latest `create` is always the one\n * called, so an inline arrow does not rebuild anything. List only what\n * makes a *different* engine, such as the node types or the wasm URL.\n */\n deps?: DependencyList;\n /** Called when `create` rejects or throws. Defaults to `console.error`. */\n onError?: (error: unknown) => void;\n}\n\nfunction logError(error: unknown) {\n console.error(\"Could not start the MotionScript engine.\", error);\n}\n\n/**\n * Builds an engine once, hands it to you when it is ready, and disposes it\n * when it is no longer wanted.\n *\n * ```tsx\n * const engine = useEngine(() => createBrowserEngine({ wasmUrl: \"/canvaskit.wasm\" }));\n * const player = useMotionPlayer({ engine, document: doc });\n * ```\n *\n * `null` until it arrives, which {@link useMotionPlayer} accepts. Nothing in\n * this package imports a platform, so what to build is the factory's job: the\n * browser's `createBrowserEngine`, a headless one, or a test double.\n *\n * Disposal covers the cases a hand-written effect gets wrong: an unmount while\n * the wasm was still loading (StrictMode does this on every mount in\n * development) frees the engine the moment it lands, and a change in `deps`\n * disposes the old one and returns `null` until the new one is ready.\n *\n * Call it once and hand the engine down. A second call is a second wasm module\n * and a second GL stack. Anything that must be true before a player sees the\n * engine, such as `setManifest`, belongs in `create`, not in an effect beside it.\n */\nexport function useEngine<E extends Engine = Engine>(\n create: () => E | Promise<E>,\n options: UseEngineOptions = {},\n): E | null {\n const { deps = [], onError } = options;\n const [engine, setEngine] = useState<E | null>(null);\n const createRef = useRef(create);\n const onErrorRef = useRef(onError);\n\n useEffect(() => {\n createRef.current = create;\n onErrorRef.current = onError;\n });\n\n useEffect(() => {\n let live = true;\n let built: E | null = null;\n\n new Promise<E>(resolve => resolve(createRef.current()))\n .then(next => {\n built = next;\n if (!live) {\n next.dispose();\n return;\n }\n setEngine(next);\n })\n .catch(error => {\n if (live) (onErrorRef.current ?? logError)(error);\n });\n\n return () => {\n live = false;\n built?.dispose();\n setEngine(null);\n };\n // The caller's list, not ours: it is what makes a different engine.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, deps);\n\n return engine;\n}\n","import { useSyncExternalStore } from \"react\";\r\n\r\n/**\r\n * The playhead, held outside React.\r\n *\r\n * A frame number written at clock rate through `useState` re-renders whoever\r\n * owns the player, and on a high-refresh display that is faster than the\r\n * project's own frame rate. Nothing in a render depends on it: the controller\r\n * paints straight onto the canvas and React is not involved. So the number\r\n * lives here, and only the components that actually display it subscribe.\r\n */\r\nexport interface PlayheadStore {\r\n subscribe(onChange: () => void): () => void;\r\n getSnapshot(): number;\r\n /** @internal — written by the player that owns this store. */\r\n set(frame: number): void;\r\n}\r\n\r\nexport function createPlayheadStore(): PlayheadStore {\r\n let frame = 0;\r\n const listeners = new Set<() => void>();\r\n return {\r\n subscribe(onChange) {\r\n listeners.add(onChange);\r\n return () => {\r\n listeners.delete(onChange);\r\n };\r\n },\r\n getSnapshot: () => frame,\r\n set(next) {\r\n if (next === frame) return;\r\n frame = next;\r\n for (const notify of listeners) notify();\r\n },\r\n };\r\n}\r\n\r\n/**\r\n * Subscribe *this* component to the playhead.\r\n *\r\n * Typed structurally rather than against `Player` so the store and the hook\r\n * that reads it don't import each other.\r\n */\r\nexport function usePlayhead(player: { playhead: PlayheadStore }): number {\r\n const { playhead } = player;\r\n return useSyncExternalStore(playhead.subscribe, playhead.getSnapshot, playhead.getSnapshot);\r\n}\r\n","import { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\r\n\r\nimport { clipTimeToFrame, DEFAULT_FPS, DEFAULT_VIEWPORT, isProjectDocument } from \"@motionscript/core\";\r\n\r\nimport type {\r\n BuildError,\r\n Engine,\r\n NodeBox,\r\n NodeHandle,\r\n Node3DFrame,\r\n NodeOverride,\r\n NodeState,\r\n NodeTextLayout,\r\n PlaybackController,\r\n AssetTimelineResult,\r\n ProjectDocument,\r\n ReparentPlacement,\r\n VisualDocument,\r\n Session,\r\n Size2D,\r\n TrackSpan,\r\n TreeState,\r\n Vector2,\r\n Vector3,\r\n} from \"@motionscript/core\";\r\n\r\nimport { createPlayheadStore, type PlayheadStore } from \"./playhead\";\r\n\r\n/**\r\n * How far background discovery has got. Only the tracks on frame 0 are\r\n * discovered before the player mounts; the rest stream in behind it (see\r\n * `AssetTimeline.runAsync`). The timeline's length never waits on it — every track\r\n * declares its own.\r\n */\r\nexport interface PrecompProgress {\r\n /** Tracks discovered so far. */\r\n discoveredTracks: number;\r\n /** Tracks in the project. */\r\n totalTracks: number;\r\n /** True once every track has been discovered. */\r\n complete: boolean;\r\n}\r\n\r\n/**\r\n * Sessions this hook has disposed. React can replay a child's effects with the\r\n * `session` it last rendered after this hook's cleanup has run — a suspended\r\n * boundary being revealed, StrictMode's dev replay — so a stage asks here\r\n * before binding to the one it was handed.\r\n */\r\nconst disposedSessions = new WeakSet<Session>();\r\n\r\n/** @internal Whether `session` was disposed by a player. Not exported from the package. */\r\nexport function isSessionDisposed(session: Session): boolean {\r\n return disposedSessions.has(session);\r\n}\r\n\r\nconst INITIAL_PRECOMP: PrecompProgress = { discoveredTracks: 0, totalTracks: 0, complete: false };\r\nconst NO_ERRORS: BuildError[] = [];\r\n\r\nfunction precompProgressOf(result: AssetTimelineResult): PrecompProgress {\r\n return {\r\n discoveredTracks: result.tracks.filter(track => track.discovered).length,\r\n totalTracks: result.tracks.length,\r\n complete: result.complete,\r\n };\r\n}\r\n\r\nfunction samePrecomp(a: PrecompProgress, b: PrecompProgress): boolean {\r\n return a.discoveredTracks === b.discoveredTracks && a.totalTracks === b.totalTracks && a.complete === b.complete;\r\n}\r\n\r\nfunction sameErrors(a: readonly BuildError[], b: readonly BuildError[]): boolean {\r\n return a.length === b.length && a.every((error, i) => {\r\n const other = b[i];\r\n return error.trackId === other.trackId && error.message === other.message\r\n && error.nodeId === other.nodeId && error.prop === other.prop && error.stack === other.stack;\r\n });\r\n}\r\n\r\n/** A state updater that keeps the held errors when the report says the same thing. */\r\nfunction errorsFrom(reported: readonly BuildError[]): (held: BuildError[]) => BuildError[] {\r\n const next = reported.length === 0 ? NO_ERRORS : reported.slice();\r\n return held => (sameErrors(held, next) ? held : next);\r\n}\r\n\r\nexport interface MotionPlayerOptions {\r\n /**\r\n * The engine this player opens its session on.\r\n *\r\n * Nullable on purpose: building one is asynchronous\r\n * (`await createBrowserEngine(...)`), so a host gets it from {@link useEngine}\r\n * and it is `null` for the first render or two. The player no-ops until it\r\n * arrives, which is what keeps the hook out of a conditional.\r\n *\r\n * **Create it once, and share it.** It holds CanvasKit and the exporter, so\r\n * a fresh one per render rebuilds the WebGL surface behind every player on\r\n * it. Identity-compared: a different engine is a different CanvasKit, and so\r\n * a full rebuild.\r\n */\r\n engine: Engine | null | undefined;\r\n /**\r\n * What to play. Nothing opens until there is one.\r\n *\r\n * A **project** document is the whole answer: it carries its own viewport,\r\n * fps, theme and tracks. A **scene** document (still or composition) is one\r\n * clip and carries none of that, so `viewport` and `fps` must come from here\r\n * or from the engine.\r\n *\r\n * Content-diffed, with identity as the fast path: a new document is reconciled\r\n * onto the running session, each track's built tree patched in place and\r\n * rebuilt only when its change cannot be patched. Treat documents as\r\n * immutable — an edit made in place to one the player already holds is not\r\n * seen.\r\n *\r\n * A new document keeps the player's place: the playhead stays where it was\r\n * (clamped when the timeline got shorter), and playback carries on if it was\r\n * running. Seek or pause yourself when a swap means \"start over\".\r\n */\r\n document?: ProjectDocument | VisualDocument;\r\n /** Overrides the engine's, for a source that carries none. */\r\n viewport?: Size2D;\r\n /** Overrides the engine's, for a source that carries none. */\r\n fps?: number;\r\n /** Initial playback rate. Change it later with {@link Player.setSpeed}. */\r\n speed?: number;\r\n /** Initial mute state. Change it later with {@link Player.setMuted}. */\r\n muted?: boolean;\r\n /** Initial loop state. Change it later with {@link Player.setLoop}. */\r\n loop?: boolean;\r\n /**\r\n * Called **synchronously**, on the same task as the draw, each time a frame\r\n * has been painted — whether by the clock, a seek, or a document swap.\r\n *\r\n * Not the playhead, which reports where the *clock* is. A seek is\r\n * asynchronous, so between the two there is a window in which the number has\r\n * moved and the canvas has not. Reach for this to keep an overlay — a\r\n * selection box, a caret, a handle — in step with the pixels, and keep the\r\n * listener cheap: it runs on the render loop, before the browser has had a\r\n * chance to composite.\r\n *\r\n * Read through a ref, so changing it costs nothing.\r\n */\r\n onFramePainted?: (frame: number) => void;\r\n}\r\n\r\n/**\r\n * One document, its transport, and the session driving it. No DOM.\r\n *\r\n * Hand it to a {@link MotionStage} to put pixels on screen. Two calls to\r\n * {@link useMotionPlayer} produce two of these with nothing shared but the\r\n * engine — separate playheads, clocks, audio devices and transports.\r\n */\r\nexport interface Player {\r\n /** The live session, or `null` before the engine and a document arrive. */\r\n readonly session: Session | null;\r\n /** The playhead, read with `usePlayhead(player)`. Stable for the hook's life. */\r\n readonly playhead: PlayheadStore;\r\n /** Resolved from the document, else the engine, else 1920×1080. */\r\n readonly viewport: Size2D;\r\n /** Resolved from the document, else the engine, else 60. */\r\n readonly fps: number;\r\n\r\n readonly isPlaying: boolean;\r\n readonly speed: number;\r\n readonly muted: boolean;\r\n readonly loop: boolean;\r\n /** True while a seek or a document swap is in flight. */\r\n readonly loading: boolean;\r\n /** The project's length, known from the document before any track is discovered. */\r\n readonly duration: number;\r\n /** {@link duration} in frames, floored at 1. */\r\n readonly totalFrames: number;\r\n readonly errors: BuildError[];\r\n readonly precomp: PrecompProgress;\r\n\r\n play(): void;\r\n pause(): void;\r\n toggle(): void;\r\n /** Seek while paused. Clamped to the timeline. */\r\n seek(frame: number): void;\r\n /** Seek relative to where the playhead is now. */\r\n step(delta: number): void;\r\n /** Seek without interrupting playback. */\r\n seekWhilePlaying(frame: number): void;\r\n setSpeed(speed: number): void;\r\n setMuted(muted: boolean): void;\r\n setLoop(loop: boolean): void;\r\n\r\n screenshot(): Promise<string | undefined>;\r\n /** Re-layout and repaint the current frame — no re-evaluation. */\r\n repaint(): void;\r\n\r\n getTreeState(): TreeState | null;\r\n getNodeProps(nodeId: string): NodeState | null;\r\n /** The node's props before any command has acted on it: the same at every frame, and answered while it is off screen. */\r\n getNodeInitialProps(nodeId: string): NodeState[\"properties\"] | null;\r\n /** Where each track sits on the timeline, in document order. */\r\n getTrackSpans(): readonly TrackSpan[];\r\n /**\r\n * Resolves once the paint a document swap scheduled has landed. The swap\r\n * does not paint before its assets have loaded, so await this before\r\n * screenshotting or reading the tree.\r\n */\r\n whenReplaced(): Promise<void>;\r\n\r\n // ---- Direct manipulation ----------------------------------------------\r\n // Points are in viewport space — origin at the viewport centre, y-up, in\r\n // this player's `viewport` pixels.\r\n\r\n getNodeBox(path: string): NodeBox | null;\r\n getNodePropsAt(path: string): NodeState[\"properties\"] | null;\r\n getNodeBoxes(): NodeBox[];\r\n projectNode3D(\r\n path: string,\r\n parentPoints: readonly Vector3[],\r\n localPoints: readonly Vector3[],\r\n ): Node3DFrame | null;\r\n /**\r\n * Where `point` lands on the plane the node at `path` is positioned in, in\r\n * that plane's own y-up frame. Two answers differ by the `x`/`y` change that\r\n * moves the node between them — which a screen delta no longer is once the\r\n * node sits in a 2.5D space.\r\n */\r\n parentPlanePoint(path: string, point: Vector2): Vector2 | null;\r\n /**\r\n * Where `point` lands in the coordinates the node at `path` positions its\r\n * children in (a graph's units), or `null` when those are pixels: the\r\n * `x`/`y` to give a node dropped or pasted there.\r\n */\r\n childPlanePoint(path: string, point: Vector2): Vector2 | null;\r\n /**\r\n * What keeps the node at `path` looking as it does once it moves under the\r\n * node at `parentPath`: `offsets` (`x`/`y` values it takes under its parent\r\n * now) as the ones that put it at the same place there, and the turn to add\r\n * and the factor to scale by. `null` when that parent arranges its children\r\n * itself.\r\n */\r\n reparentPlacement(path: string, parentPath: string, offsets: readonly Vector2[]): ReparentPlacement | null;\r\n /** The points an editor may drag on the node at `path` (an arrow's ends), in viewport space. */\r\n nodeHandles(path: string): NodeHandle[] | null;\r\n /** The value of `prop` that puts its handle under `point`, or `null`. */\r\n handleValue(path: string, prop: string, point: Vector2): Vector2 | null;\r\n getTextLayout(path: string): NodeTextLayout | null;\r\n /** `tolerance` is grab-slop in scene units. */\r\n pickNode(point: Vector2, tolerance?: number): NodeBox | null;\r\n /** Layer transient props over a node without rebuilding its track. */\r\n setNodeOverride(path: string, props: NodeOverride): void;\r\n clearNodeOverrides(path?: string): void;\r\n}\r\n\r\n/**\r\n * Opens a session on `engine` and gives you the transport for it.\r\n *\r\n * ```tsx\r\n * const player = useMotionPlayer({ engine, document: doc, loop: true });\r\n * <MotionStage player={player} />\r\n * ```\r\n */\r\nexport function useMotionPlayer(options: MotionPlayerOptions): Player {\r\n const { engine, document, onFramePainted } = options;\r\n\r\n // Read straight off the document where it says so, else the caller's, else\r\n // the engine's. All plain JSON, so this resolves during render, before any\r\n // session exists — which is what lets a stage size its canvas on the first\r\n // pass rather than after a mount.\r\n const projectDoc = document && isProjectDocument(document) ? document : undefined;\r\n const resolvedViewport = projectDoc?.viewport ?? options.viewport ?? engine?.viewport ?? DEFAULT_VIEWPORT;\r\n const fps = projectDoc?.fps ?? options.fps ?? engine?.fps ?? DEFAULT_FPS;\r\n\r\n // Held by size: a host that rebuilds its document per edit rebuilds this\r\n // object with it, and a new one would hand every consumer a new `Player`.\r\n const [viewport, setViewport] = useState(resolvedViewport);\r\n if (viewport.width !== resolvedViewport.width || viewport.height !== resolvedViewport.height) {\r\n setViewport(resolvedViewport);\r\n }\r\n const hasDocument = document !== undefined;\r\n\r\n const [session, setSession] = useState<Session | null>(null);\r\n /** Created once; stable for the hook's life, so `usePlayhead` never resubscribes. */\r\n const [playhead] = useState(createPlayheadStore);\r\n\r\n const [isPlaying, setIsPlaying] = useState(false);\r\n const [speed, setSpeedState] = useState(options.speed ?? 1);\r\n const [muted, setMutedState] = useState(options.muted ?? false);\r\n const [loop, setLoopState] = useState(options.loop ?? false);\r\n const [loading, setLoading] = useState(true);\r\n const [duration, setDuration] = useState(0);\r\n const [errors, setErrors] = useState<BuildError[]>(NO_ERRORS);\r\n const [precomp, setPrecomp] = useState<PrecompProgress>(INITIAL_PRECOMP);\r\n\r\n const totalFrames = Math.max(1, Math.round(duration * fps));\r\n\r\n // Stable across renders so the action callbacks below never need rebuilding.\r\n const controllerRef = useRef<PlaybackController | null>(null);\r\n const sessionRef = useRef<Session | null>(null);\r\n const documentRef = useRef(document);\r\n const onFramePaintedRef = useRef(onFramePainted);\r\n /** Monotonic seek id; only the latest may clear the loading flag. */\r\n const seekTokenRef = useRef(0);\r\n /** Read by the tick handler, which is installed once and must see the latest. */\r\n const loopRef = useRef(loop);\r\n const fpsRef = useRef(fps);\r\n const speedRef = useRef(speed);\r\n /**\r\n * What the transport has been told to do, ahead of the next render. State\r\n * only shows the last value a batch settled on, and the controller is\r\n * driven by the calls that were made, so the two can disagree inside one\r\n * batch (`seek` then `play`).\r\n */\r\n const playingRef = useRef(false);\r\n\r\n useEffect(() => {\r\n onFramePaintedRef.current = onFramePainted;\r\n loopRef.current = loop;\r\n fpsRef.current = fps;\r\n speedRef.current = speed;\r\n playingRef.current = isPlaying;\r\n });\r\n\r\n // An edit keeps the transport and its errors — the reconcile effect below\r\n // re-reads both off the session, so an error the edit did not fix never\r\n // blinks out for a commit. Only losing the document stops it, during render\r\n // so nothing draws against a timeline that is gone.\r\n const [prevDocument, setPrevDocument] = useState(document);\r\n if (document !== prevDocument) {\r\n setPrevDocument(document);\r\n if (document === undefined) {\r\n setIsPlaying(false);\r\n setDuration(0);\r\n if (errors.length > 0) setErrors(NO_ERRORS);\r\n }\r\n }\r\n\r\n /**\r\n * Pull what the controller now knows: timeline length, errors, progress.\r\n * Runs on every swap, so it keeps whatever did not change — a fresh array or\r\n * object here is a new `Player` for every consumer on every edit.\r\n */\r\n const sync = useCallback((pc: PlaybackController) => {\r\n setDuration(pc.totalDuration);\r\n setErrors(errorsFrom(pc.buildErrors));\r\n const progress = precompProgressOf(pc.precomp);\r\n setPrecomp(held => (samePrecomp(held, progress) ? held : progress));\r\n }, []);\r\n\r\n /**\r\n * Move the playhead and repaint, with the loading flag the UI paces off.\r\n *\r\n * Created once so every caller — the transport, the reconcile effect and\r\n * the first paint after a session opens — shares one seek discipline.\r\n */\r\n const [seekTo] = useState(() => (frame: number): Promise<boolean> => {\r\n const pc = controllerRef.current;\r\n if (!pc) return Promise.resolve(false);\r\n const last = Math.max(0, Math.round(pc.totalDuration * fpsRef.current) - 1);\r\n const clamped = Math.min(Math.max(0, Math.round(frame)), last);\r\n playhead.set(clamped);\r\n // Only the newest seek may report \"settled\". A superseded seek still\r\n // resolves — its generation guard bailed inside the controller — but it\r\n // never painted, so clearing the loading flag from it would tell the UI\r\n // a frame is ready while the newest is still in flight. Consumers pace\r\n // scrubbing off that edge.\r\n const token = ++seekTokenRef.current;\r\n setLoading(true);\r\n // Resolves `true` when this was still the newest seek as it landed.\r\n return pc.seek(clamped).then(() => {\r\n const newest = token === seekTokenRef.current;\r\n if (newest) setLoading(false);\r\n return newest;\r\n });\r\n });\r\n\r\n useEffect(() => {\r\n if (!engine || !document) return;\r\n\r\n // `target` is omitted: the session opens unmounted, and a `MotionStage`\r\n // binds a canvas to it afterwards. That is what lets this hook own the\r\n // session without owning any DOM.\r\n const opened = engine.open({\r\n document,\r\n viewport,\r\n fps,\r\n // A track landing can surface a build error it threw.\r\n onPrecompProgress: () => sync(opened.controller),\r\n });\r\n\r\n const pc = opened.controller;\r\n pc.onRenderError = errs => setErrors(errorsFrom(errs));\r\n pc.onFramePainted = frame => onFramePaintedRef.current?.(frame);\r\n\r\n pc.onTime((t: number) => {\r\n const frame = Math.floor(clipTimeToFrame(t, fpsRef.current));\r\n playhead.set(frame);\r\n\r\n // A document swap can change the timeline's length, so ask the\r\n // controller rather than trusting a duration captured when this\r\n // listener was installed.\r\n const last = Math.round(pc.totalDuration * fpsRef.current) - 1;\r\n if (frame < last) return;\r\n if (loopRef.current) pc.seekWhilePlaying(0);\r\n else {\r\n playingRef.current = false;\r\n setIsPlaying(false);\r\n }\r\n });\r\n\r\n controllerRef.current = pc;\r\n sessionRef.current = opened;\r\n documentRef.current = document;\r\n setSession(opened);\r\n sync(pc);\r\n setLoading(true);\r\n\r\n return () => {\r\n controllerRef.current = null;\r\n sessionRef.current = null;\r\n setSession(null);\r\n // Disposes the controller and the render context together — the\r\n // session owns both.\r\n disposedSessions.add(opened);\r\n opened.dispose();\r\n };\r\n // `document` is deliberately absent — only whether there is one: a new\r\n // document is reconciled onto the live session by the effect below\r\n // rather than rebuilt into a new one. What remains genuinely does need a\r\n // rebuild — a different engine is a different CanvasKit, and a live\r\n // surface cannot change its size or rate (`Session.replace` refuses both).\r\n // eslint-disable-next-line react-hooks/exhaustive-deps\r\n }, [engine, hasDocument, viewport.width, viewport.height, fps, sync]);\r\n\r\n // Reconcile a changed document onto the session already running. Skipped on\r\n // the pass that opens it, which was opened with this very document —\r\n // replacing it there would rediscover a timeline just discovered.\r\n useEffect(() => {\r\n if (documentRef.current === document) return;\r\n documentRef.current = document;\r\n const live = sessionRef.current;\r\n if (!live || !document) return;\r\n const pc = live.controller;\r\n live.replace(document);\r\n sync(pc);\r\n // No seek: `replace` already paints the current frame once its assets\r\n // load, clamped to the new length, and a running clock keeps ticking.\r\n const last = Math.max(0, Math.round(pc.totalDuration * fpsRef.current) - 1);\r\n playhead.set(Math.min(playhead.getSnapshot(), last));\r\n const token = ++seekTokenRef.current;\r\n setLoading(true);\r\n void pc.whenReplaced().then(() => {\r\n if (token === seekTokenRef.current) setLoading(false);\r\n });\r\n }, [document, sync, playhead]);\r\n\r\n useEffect(() => {\r\n const pc = controllerRef.current;\r\n if (!pc) return;\r\n if (isPlaying) pc.play(speed);\r\n else pc.pause();\r\n }, [session, isPlaying, speed]);\r\n\r\n useEffect(() => {\r\n controllerRef.current?.setMuted(muted);\r\n }, [session, muted]);\r\n\r\n // The one seek that isn't user-driven: park the new session on the frame\r\n // the playhead already holds, so a rebuild keeps its place.\r\n //\r\n // A seek pauses the clock, and the clock effect above has already started\r\n // this session, so a player that was playing resumes once the park lands\r\n // (with its assets loaded, so the first ticks draw rather than catch up). It\r\n // does not if the transport moved meanwhile: a newer seek, or a pause.\r\n useEffect(() => {\r\n const pc = controllerRef.current;\r\n if (!pc) return;\r\n const wasPlaying = playingRef.current;\r\n const parked = seekTo(playhead.getSnapshot());\r\n if (!wasPlaying) return;\r\n void parked.then(newest => {\r\n if (!newest || controllerRef.current !== pc || !playingRef.current || pc.isPlaying) return;\r\n pc.play(speedRef.current);\r\n });\r\n }, [session, playhead, seekTo]);\r\n\r\n // Built once and stable for the hook's life: every one reads the controller\r\n // through a ref, so a re-render never invalidates a handler a child holds —\r\n // which is what lets a transport subscribe its listeners a single time.\r\n const [actions] = useState<Omit<Player, keyof PlayerState>>(() => {\r\n // Scrubbing is a pause: a seek that left the clock running would be\r\n // overwritten by the next tick.\r\n const seek = (frame: number) => {\r\n playingRef.current = false;\r\n setIsPlaying(false);\r\n void seekTo(frame);\r\n };\r\n\r\n return {\r\n playhead,\r\n // Both drive the controller as well as the state. In one batch a\r\n // `seek` and a `play` cancel out in state (`true`, `false`, `true`\r\n // while playing), so the effect on `isPlaying` never re-runs, yet the\r\n // seek has already paused the clock; the state is the settled\r\n // answer and the controller is what was actually asked.\r\n play: () => {\r\n playingRef.current = true;\r\n setIsPlaying(true);\r\n const pc = controllerRef.current;\r\n if (pc && !pc.isPlaying) pc.play(speedRef.current);\r\n },\r\n pause: () => {\r\n playingRef.current = false;\r\n setIsPlaying(false);\r\n controllerRef.current?.pause();\r\n },\r\n toggle: () =>\r\n setIsPlaying(playing => {\r\n // Restarting from the end is what a play button means there.\r\n const pc = controllerRef.current;\r\n if (!playing && pc) {\r\n const last = Math.round(pc.totalDuration * fpsRef.current) - 1;\r\n if (playhead.getSnapshot() >= last) void pc.seek(0);\r\n }\r\n return !playing;\r\n }),\r\n seek,\r\n step: (delta: number) => seek(playhead.getSnapshot() + delta),\r\n seekWhilePlaying: (frame: number) => controllerRef.current?.seekWhilePlaying(frame),\r\n setSpeed: (next: number) => setSpeedState(next),\r\n setMuted: (next: boolean) => setMutedState(next),\r\n setLoop: (next: boolean) => setLoopState(next),\r\n\r\n screenshot: async () => controllerRef.current?.screenshot() ?? undefined,\r\n repaint: () => controllerRef.current?.repaint(),\r\n\r\n getTreeState: () => controllerRef.current?.getTreeState() ?? null,\r\n getNodeProps: (nodeId: string) => controllerRef.current?.getNodeState(nodeId) ?? null,\r\n getNodeInitialProps: (nodeId: string) => controllerRef.current?.getNodeInitialProps(nodeId) ?? null,\r\n getTrackSpans: () => controllerRef.current?.spans ?? [],\r\n whenReplaced: async () => {\r\n await controllerRef.current?.whenReplaced();\r\n },\r\n\r\n getNodeBox: (path: string) => controllerRef.current?.getNodeBox(path) ?? null,\r\n getNodePropsAt: (path: string) => controllerRef.current?.getNodePropsAt(path) ?? null,\r\n getNodeBoxes: () => controllerRef.current?.getNodeBoxes() ?? [],\r\n projectNode3D: (path, parentPoints, localPoints) =>\r\n controllerRef.current?.projectNode3D(path, parentPoints, localPoints) ?? null,\r\n parentPlanePoint: (path: string, point: Vector2) =>\r\n controllerRef.current?.parentPlanePoint(path, point) ?? null,\r\n childPlanePoint: (path: string, point: Vector2) =>\r\n controllerRef.current?.childPlanePoint(path, point) ?? null,\r\n reparentPlacement: (path: string, parentPath: string, offsets: readonly Vector2[]) =>\r\n controllerRef.current?.reparentPlacement(path, parentPath, offsets) ?? null,\r\n nodeHandles: (path: string) => controllerRef.current?.nodeHandles(path) ?? null,\r\n handleValue: (path: string, prop: string, point: Vector2) =>\r\n controllerRef.current?.handleValue(path, prop, point) ?? null,\r\n getTextLayout: (path: string) => controllerRef.current?.getTextLayout(path) ?? null,\r\n pickNode: (point: Vector2, tolerance?: number) =>\r\n controllerRef.current?.pickNode(point, tolerance) ?? null,\r\n setNodeOverride: (path: string, props: NodeOverride) =>\r\n controllerRef.current?.setNodeOverride(path, props),\r\n clearNodeOverrides: (path?: string) => controllerRef.current?.clearNodeOverrides(path),\r\n };\r\n });\r\n\r\n return useMemo(\r\n () => ({\r\n ...actions,\r\n session,\r\n viewport,\r\n fps,\r\n isPlaying,\r\n speed,\r\n muted,\r\n loop,\r\n loading,\r\n duration,\r\n totalFrames,\r\n errors,\r\n precomp,\r\n }),\r\n [\r\n actions,\r\n session,\r\n viewport,\r\n fps,\r\n isPlaying,\r\n speed,\r\n muted,\r\n loop,\r\n loading,\r\n duration,\r\n totalFrames,\r\n errors,\r\n precomp,\r\n ],\r\n );\r\n}\r\n\r\n/** The fields the memo above supplies; everything else on `Player` is an action. */\r\ntype PlayerState = Pick<\r\n Player,\r\n | \"session\"\r\n | \"viewport\"\r\n | \"fps\"\r\n | \"isPlaying\"\r\n | \"speed\"\r\n | \"muted\"\r\n | \"loop\"\r\n | \"loading\"\r\n | \"duration\"\r\n | \"totalFrames\"\r\n | \"errors\"\r\n | \"precomp\"\r\n>;\r\n","import { useEffect, useRef, type CSSProperties } from \"react\";\r\n\r\nimport type { EngineRenderContext, Size2D } from \"@motionscript/core\";\r\n\r\nimport { isSessionDisposed, type Player } from \"./use-motion-player\";\r\n\r\n/**\r\n * The session's surface, with `mount` narrowed to a canvas.\r\n *\r\n * `core` compiles without the DOM lib, so `RenderSurface.mount` takes `unknown`\r\n * there. This is the narrowing that seam always assumed: it happens here, in\r\n * the one layer that genuinely has `HTMLCanvasElement`.\r\n */\r\ntype StageRenderContext = Omit<EngineRenderContext, \"mount\"> & {\r\n mount(canvas: HTMLCanvasElement): void;\r\n};\r\n\r\n/**\r\n * What every stage that doesn't ask for a view gets: the whole frame, 1:1.\r\n *\r\n * A shared frozen object rather than a literal, so the view effect's dependency\r\n * on its fields is stable across renders for the overwhelming majority of\r\n * stages, which never pass `view` at all.\r\n */\r\nconst IDENTITY_VIEW = Object.freeze({ zoom: 1, x: 0, y: 0 });\r\n\r\nexport interface MotionStageProps {\r\n /** The player whose session this stage draws. */\r\n player: Player;\r\n /**\r\n * Device pixels to rasterize per viewport unit. Defaults to `1`.\r\n *\r\n * **Not a zoom and not a crop.** The viewport stays the scene's logical\r\n * coordinate space; this only changes how many real pixels that space is\r\n * drawn into, and CSS scales the canvas back up to fill its box.\r\n *\r\n * The lever exists because a preview is usually displayed far smaller than\r\n * the project's output size: a 1920×1080 project in a 700px-wide panel\r\n * rasterizes roughly seven times the pixels anyone can see. `0.5` there is a\r\n * quarter of the fill, the shader work and the effect offscreens.\r\n *\r\n * Two things to know before animating it:\r\n *\r\n * - **Every change re-creates the Skia surface**, which drops the storage\r\n * adapter's texture-backed images (decoded video frames, 3D composites;\r\n * still images survive) and asks for a fresh GL context. Quantize to a few\r\n * steps and let it settle — never drive it from a resize observer.\r\n * - **Prefer scales that keep both dimensions whole.** `pixelRatio` is one\r\n * uniform number, so a scale that rounds differently on each axis shifts\r\n * the frame's centre by up to half a device pixel.\r\n *\r\n * A snapshot from `player.screenshot()` comes back at the surface's size, so\r\n * it is scaled too — render at `1` if you need full resolution out of it.\r\n */\r\n renderScale?: number;\r\n /**\r\n * The canvas's own size in CSS pixels, when it is **not** the frame.\r\n *\r\n * Omitted — the default — the canvas is the frame: sized `viewport ×\r\n * renderScale` and stretched over its box by CSS, which is what every\r\n * export, thumbnail and plain player wants.\r\n *\r\n * Supplied, together with {@link view}, the canvas becomes a *window* onto\r\n * the frame: it takes the size of the area it is shown in, `renderScale`\r\n * stops meaning \"fraction of the project's resolution\" and starts meaning\r\n * device pixels per CSS pixel, and only what is on screen is rasterized.\r\n * That is what lets an editor zoom in without going soft or paying for the\r\n * whole frame at the zoomed resolution.\r\n *\r\n * It re-creates the surface exactly as `renderScale` does, and wants the\r\n * same treatment: quantize it and let it settle.\r\n */\r\n surfaceSize?: Size2D;\r\n /**\r\n * A pan and zoom applied to the render itself. Requires {@link surfaceSize}.\r\n *\r\n * `zoom` multiplies scene units; `x`/`y` offset the frame's centre in CSS\r\n * pixels, positive `y` downwards — the same sign convention as a CSS\r\n * translate, so a preview can hand over the pan it was already computing.\r\n *\r\n * Changing it costs a repaint and nothing else: no surface, no textures, no\r\n * precomp. That is the point of it living here rather than in a CSS\r\n * transform, which cannot add resolution it was not rasterized with.\r\n */\r\n view?: { zoom: number; x: number; y: number };\r\n /**\r\n * Whether the frame's edge bounds what draws, rather than only where its own\r\n * backdrop goes. Requires {@link surfaceSize} and {@link view}. Defaults to\r\n * `true`.\r\n *\r\n * Off lets a node parked past the frame's edge rasterize into the rest of\r\n * the surface instead of being discarded — for a host that wants to show,\r\n * faded, what a node placed there while animating in or out.\r\n */\r\n clipToFrame?: boolean;\r\n /**\r\n * What the frame's backdrop is painted with. Defaults to `\"black\"`.\r\n *\r\n * `\"transparent\"` leaves the frame unpainted where nothing was drawn, so\r\n * whatever the host renders behind the canvas shows through — a\r\n * checkerboard, for an editor that has to distinguish \"no scene covers this\"\r\n * from \"a scene covers it in black\". Requires {@link surfaceSize} and\r\n * {@link view}, the same way {@link clipToFrame} does.\r\n */\r\n frameBackground?: \"black\" | \"transparent\";\r\n className?: string;\r\n style?: CSSProperties;\r\n}\r\n\r\n/**\r\n * A canvas bound to a {@link Player}'s session.\r\n *\r\n * The stage owns how the frame is rasterized — resolution, view, clipping — and\r\n * nothing about what is in it or when. A session drives **one** surface, so one\r\n * stage per player: a second would take the surface from the first.\r\n */\r\nexport function MotionStage({\r\n player,\r\n renderScale = 1,\r\n surfaceSize,\r\n view,\r\n clipToFrame,\r\n frameBackground,\r\n className,\r\n style,\r\n}: MotionStageProps) {\r\n const canvasRef = useRef<HTMLCanvasElement>(null);\r\n const { session } = player;\r\n // The session's own size, not the player's: the player's moves a commit\r\n // ahead, in the commit whose cleanup disposes the old session, and a buffer\r\n // resized there would re-bind that disposed session.\r\n const viewport = session?.viewport ?? player.viewport;\r\n\r\n /**\r\n * The canvas's backing store, in device pixels. `viewport × renderScale` in\r\n * the default case, where the canvas *is* the frame; with `surfaceSize` it\r\n * is the viewing area instead.\r\n *\r\n * Floored at 1 so a degenerate scale can't ask CanvasKit for a zero-sized\r\n * surface, which fails the surface creation outright.\r\n */\r\n const bufferWidth = Math.max(1, Math.round((surfaceSize?.width ?? viewport.width) * renderScale));\r\n const bufferHeight = Math.max(1, Math.round((surfaceSize?.height ?? viewport.height) * renderScale));\r\n\r\n /**\r\n * The view transform to draw with, and the frame to clip and anchor against.\r\n * Only meaningful together, so they resolve in one place: no `surfaceSize`\r\n * means the canvas is the frame, and both revert to identity.\r\n */\r\n const activeView = surfaceSize && view ? view : IDENTITY_VIEW;\r\n const activeFrame = surfaceSize && view ? viewport : null;\r\n const activeClipToFrame = surfaceSize && view ? (clipToFrame ?? true) : true;\r\n const activeFrameBackground = surfaceSize && view ? (frameBackground ?? \"black\") : \"black\";\r\n\r\n const viewRef = useRef(activeView);\r\n const frameRectRef = useRef(activeFrame);\r\n const clipToFrameRef = useRef(activeClipToFrame);\r\n const frameBackgroundRef = useRef(activeFrameBackground);\r\n /**\r\n * The live render context.\r\n *\r\n * Held here rather than reached through `player.session` at each use because\r\n * it is mutable external state — a Skia context whose knobs are written, not\r\n * a value derived from a prop — and writing through the prop is what the\r\n * immutability lint is there to catch everywhere it *isn't* one of these.\r\n */\r\n const ctxRef = useRef<StageRenderContext | null>(null);\r\n useEffect(() => {\r\n viewRef.current = activeView;\r\n frameRectRef.current = activeFrame;\r\n clipToFrameRef.current = activeClipToFrame;\r\n frameBackgroundRef.current = activeFrameBackground;\r\n ctxRef.current = session ? (session.surface as StageRenderContext) : null;\r\n });\r\n\r\n /**\r\n * Bind the surface, and rebuild it when the backing store changes.\r\n *\r\n * The order matters and is why this is an effect rather than a callback:\r\n * React has already written the canvas's new `width`/`height` by the time\r\n * effects run, and CanvasKit reads exactly those when it builds the surface\r\n * (`MakeOnScreenGLSurface(ctx, canvas.width, canvas.height)`). Mounting\r\n * before the resize would produce a surface of the previous size.\r\n *\r\n * `repaint()` afterwards because a new surface starts blank and the clock is\r\n * not necessarily running to fill it — a paused editor would otherwise show\r\n * black until something else moved.\r\n */\r\n useEffect(() => {\r\n const canvas = canvasRef.current;\r\n const ctx = ctxRef.current;\r\n // A replayed effect can hold a session its player has since disposed.\r\n if (!session || !canvas || !ctx || isSessionDisposed(session)) return;\r\n ctx.pixelRatio = renderScale;\r\n ctx.view = viewRef.current;\r\n ctx.frame = frameRectRef.current;\r\n ctx.clipToFrame = clipToFrameRef.current;\r\n ctx.frameBackground = frameBackgroundRef.current;\r\n // `mount` detaches the old surface first, which also drops the storage\r\n // adapter's texture-backed images — they belong to the surface that made\r\n // them. Video frames and 3D composites are re-uploaded on demand;\r\n // decoded still images are raster-backed and survive.\r\n ctx.mount(canvas);\r\n session.controller.repaint();\r\n }, [session, renderScale, bufferWidth, bufferHeight]);\r\n\r\n /**\r\n * Apply {@link MotionStageProps.view} — a repaint and nothing more.\r\n *\r\n * Depends on the fields rather than the object so a caller passing a fresh\r\n * `{zoom, x, y}` each render — which is every caller, since it comes from a\r\n * gesture — doesn't repaint on renders where the view didn't move.\r\n */\r\n useEffect(() => {\r\n const ctx = ctxRef.current;\r\n if (!session || !ctx || isSessionDisposed(session)) return;\r\n ctx.view = { zoom: activeView.zoom, x: activeView.x, y: activeView.y };\r\n ctx.frame = activeFrame;\r\n ctx.clipToFrame = activeClipToFrame;\r\n ctx.frameBackground = activeFrameBackground;\r\n session.controller.repaint();\r\n // eslint-disable-next-line react-hooks/exhaustive-deps\r\n }, [\r\n session,\r\n activeView.zoom,\r\n activeView.x,\r\n activeView.y,\r\n activeFrame?.width,\r\n activeFrame?.height,\r\n activeClipToFrame,\r\n activeFrameBackground,\r\n ]);\r\n\r\n return (\r\n <div className={className} style={{ position: \"relative\", width: \"100%\", height: \"100%\", ...style }}>\r\n <canvas\r\n ref={canvasRef}\r\n // The backing store, in device pixels. CSS below stretches it\r\n // back over the whole box either way, so this is purely how much\r\n // gets rasterized.\r\n width={bufferWidth}\r\n height={bufferHeight}\r\n style={{\r\n display: session ? \"block\" : \"none\",\r\n ...(surfaceSize\r\n ? {\r\n // `surfaceSize` is the canvas's CSS size, so it is\r\n // honoured literally rather than stretched to the\r\n // box: it is quantized by its caller, which means\r\n // it is usually a little larger than the box and\r\n // rarely the same shape. Stretched, that\r\n // difference would land as a non-uniform scale — a\r\n // picture squashed on one axis, a far worse\r\n // artefact than the softness this arrangement\r\n // exists to remove.\r\n //\r\n // Centred, so the surface's midpoint is the box's\r\n // midpoint: `executePass` puts the scene origin at\r\n // the centre of the surface, so this is what makes\r\n // the frame land where the caller's layout says it\r\n // is. The spare pixels hang off all four edges and\r\n // are clipped by whatever is holding this.\r\n position: \"absolute\",\r\n left: \"50%\",\r\n top: \"50%\",\r\n width: `${surfaceSize.width}px`,\r\n height: `${surfaceSize.height}px`,\r\n transform: \"translate(-50%, -50%)\",\r\n }\r\n : { width: \"100%\", height: \"100%\" }),\r\n }}\r\n />\r\n </div>\r\n );\r\n}\r\n"],"mappings":";;;;AAkBA,SAAS,SAAS,OAAgB;CAC9B,QAAQ,MAAM,4CAA4C,KAAK;AACnE;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,UACZ,QACA,UAA4B,CAAC,GACrB;CACR,MAAM,EAAE,OAAO,CAAC,GAAG,YAAY;CAC/B,MAAM,CAAC,QAAQ,aAAa,SAAmB,IAAI;CACnD,MAAM,YAAY,OAAO,MAAM;CAC/B,MAAM,aAAa,OAAO,OAAO;CAEjC,gBAAgB;EACZ,UAAU,UAAU;EACpB,WAAW,UAAU;CACzB,CAAC;CAED,gBAAgB;EACZ,IAAI,OAAO;EACX,IAAI,QAAkB;EAEtB,IAAI,SAAW,YAAW,QAAQ,UAAU,QAAQ,CAAC,CAAC,EACjD,MAAK,SAAQ;GACV,QAAQ;GACR,IAAI,CAAC,MAAM;IACP,KAAK,QAAQ;IACb;GACJ;GACA,UAAU,IAAI;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,QAAQ;IAAO;GAC1C;EACH,CAAA;CACA,CAAA;AAEb"}
1
+ {"version":3,"file":"motionscript-react.js","names":[],"sources":["../src/ui/use-engine.ts","../src/ui/playhead.ts","../src/ui/use-motion-player.ts","../src/ui/stage.tsx"],"sourcesContent":["import { useEffect, useRef, useState, type DependencyList } from \"react\";\n\nimport type { Engine } from \"@motionscript/core\";\n\nexport interface UseEngineOptions {\n /**\n * Rebuild the engine when any of these change, compared the way\n * `useEffect` compares its own. The default, `[]`, builds it once.\n *\n * Not for the factory's closure: the latest `create` is always the one\n * called, so an inline arrow does not rebuild anything. List only what\n * makes a *different* engine, such as the node types or the wasm URL.\n */\n deps?: DependencyList;\n /** Called when `create` rejects or throws. Defaults to `console.error`. */\n onError?: (error: unknown) => void;\n}\n\nfunction logError(error: unknown) {\n console.error(\"Could not start the MotionScript engine.\", error);\n}\n\n/**\n * Builds an engine once, hands it to you when it is ready, and disposes it\n * when it is no longer wanted.\n *\n * ```tsx\n * const engine = useEngine(() => createBrowserEngine());\n * const player = useMotionPlayer({ engine, document: doc });\n * ```\n *\n * `null` until it arrives, which {@link useMotionPlayer} accepts. Nothing in\n * this package imports a platform, so what to build is the factory's job: the\n * browser's `createBrowserEngine`, a headless one, or a test double.\n *\n * Disposal covers the cases a hand-written effect gets wrong: an unmount while\n * the wasm was still loading (StrictMode does this on every mount in\n * development) frees the engine the moment it lands, and a change in `deps`\n * disposes the old one and returns `null` until the new one is ready.\n *\n * Call it once and hand the engine down. A second call is a second wasm module\n * and a second GL stack. Anything that must be true before a player sees the\n * engine, such as `setManifest`, belongs in `create`, not in an effect beside it.\n */\nexport function useEngine<E extends Engine = Engine>(\n create: () => E | Promise<E>,\n options: UseEngineOptions = {},\n): E | null {\n const { deps = [], onError } = options;\n const [engine, setEngine] = useState<E | null>(null);\n const createRef = useRef(create);\n const onErrorRef = useRef(onError);\n\n useEffect(() => {\n createRef.current = create;\n onErrorRef.current = onError;\n });\n\n useEffect(() => {\n let live = true;\n let built: E | null = null;\n\n new Promise<E>(resolve => resolve(createRef.current()))\n .then(next => {\n built = next;\n if (!live) {\n next.dispose();\n return;\n }\n setEngine(next);\n })\n .catch(error => {\n if (live) (onErrorRef.current ?? logError)(error);\n });\n\n return () => {\n live = false;\n built?.dispose();\n setEngine(null);\n };\n // The caller's list, not ours: it is what makes a different engine.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, deps);\n\n return engine;\n}\n","import { useSyncExternalStore } from \"react\";\n\n/**\n * The playhead, held outside React.\n *\n * A frame number written at clock rate through `useState` re-renders whoever\n * owns the player, and on a high-refresh display that is faster than the\n * project's own frame rate. Nothing in a render depends on it: the controller\n * paints straight onto the canvas and React is not involved. So the number\n * lives here, and only the components that actually display it subscribe.\n */\nexport interface PlayheadStore {\n subscribe(onChange: () => void): () => void;\n getSnapshot(): number;\n /** @internal — written by the player that owns this store. */\n set(frame: number): void;\n}\n\nexport function createPlayheadStore(): PlayheadStore {\n let frame = 0;\n const listeners = new Set<() => void>();\n return {\n subscribe(onChange) {\n listeners.add(onChange);\n return () => {\n listeners.delete(onChange);\n };\n },\n getSnapshot: () => frame,\n set(next) {\n if (next === frame) return;\n frame = next;\n for (const notify of listeners) notify();\n },\n };\n}\n\n/**\n * Subscribe *this* component to the playhead.\n *\n * Typed structurally rather than against `Player` so the store and the hook\n * that reads it don't import each other.\n */\nexport function usePlayhead(player: { playhead: PlayheadStore }): number {\n const { playhead } = player;\n return useSyncExternalStore(playhead.subscribe, playhead.getSnapshot, playhead.getSnapshot);\n}\n","import { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\n\nimport { clipTimeToFrame, DEFAULT_FPS, DEFAULT_VIEWPORT, isProjectDocument } from \"@motionscript/core\";\n\nimport type {\n BuildError,\n Engine,\n NodeBox,\n NodeHandle,\n Node3DFrame,\n NodeOverride,\n NodeState,\n NodeTextLayout,\n PlaybackController,\n AssetTimelineResult,\n ProjectDocument,\n ReparentPlacement,\n VisualDocument,\n Session,\n Size2D,\n TrackSpan,\n TreeState,\n Vector2,\n Vector3,\n} from \"@motionscript/core\";\n\nimport { createPlayheadStore, type PlayheadStore } from \"./playhead\";\n\n/**\n * How far background discovery has got. Only the tracks on frame 0 are\n * discovered before the player mounts; the rest stream in behind it (see\n * `AssetTimeline.runAsync`). The timeline's length never waits on it — every track\n * declares its own.\n */\nexport interface PrecompProgress {\n /** Tracks discovered so far. */\n discoveredTracks: number;\n /** Tracks in the project. */\n totalTracks: number;\n /** True once every track has been discovered. */\n complete: boolean;\n}\n\n/**\n * Sessions this hook has disposed. React can replay a child's effects with the\n * `session` it last rendered after this hook's cleanup has run — a suspended\n * boundary being revealed, StrictMode's dev replay — so a stage asks here\n * before binding to the one it was handed.\n */\nconst disposedSessions = new WeakSet<Session>();\n\n/** @internal Whether `session` was disposed by a player. Not exported from the package. */\nexport function isSessionDisposed(session: Session): boolean {\n return disposedSessions.has(session);\n}\n\nconst INITIAL_PRECOMP: PrecompProgress = { discoveredTracks: 0, totalTracks: 0, complete: false };\nconst NO_ERRORS: BuildError[] = [];\n\nfunction precompProgressOf(result: AssetTimelineResult): PrecompProgress {\n return {\n discoveredTracks: result.tracks.filter(track => track.discovered).length,\n totalTracks: result.tracks.length,\n complete: result.complete,\n };\n}\n\nfunction samePrecomp(a: PrecompProgress, b: PrecompProgress): boolean {\n return a.discoveredTracks === b.discoveredTracks && a.totalTracks === b.totalTracks && a.complete === b.complete;\n}\n\nfunction sameErrors(a: readonly BuildError[], b: readonly BuildError[]): boolean {\n return a.length === b.length && a.every((error, i) => {\n const other = b[i];\n return error.trackId === other.trackId && error.message === other.message\n && error.nodeId === other.nodeId && error.prop === other.prop && error.stack === other.stack;\n });\n}\n\n/** A state updater that keeps the held errors when the report says the same thing. */\nfunction errorsFrom(reported: readonly BuildError[]): (held: BuildError[]) => BuildError[] {\n const next = reported.length === 0 ? NO_ERRORS : reported.slice();\n return held => (sameErrors(held, next) ? held : next);\n}\n\nexport interface MotionPlayerOptions {\n /**\n * The engine this player opens its session on.\n *\n * Nullable on purpose: building one is asynchronous\n * (`await createBrowserEngine(...)`), so a host gets it from {@link useEngine}\n * and it is `null` for the first render or two. The player no-ops until it\n * arrives, which is what keeps the hook out of a conditional.\n *\n * **Create it once, and share it.** It holds the renderer and the exporter, so\n * a fresh one per render rebuilds the WebGL surface behind every player on\n * it. Identity-compared: a different engine is a different renderer, and so\n * a full rebuild.\n */\n engine: Engine | null | undefined;\n /**\n * What to play. Nothing opens until there is one.\n *\n * A **project** document is the whole answer: it carries its own viewport,\n * fps, theme and tracks. A **scene** document (still or composition) is one\n * clip and carries none of that, so `viewport` and `fps` must come from here\n * or from the engine.\n *\n * Content-diffed, with identity as the fast path: a new document is reconciled\n * onto the running session, each track's built tree patched in place and\n * rebuilt only when its change cannot be patched. Treat documents as\n * immutable — an edit made in place to one the player already holds is not\n * seen.\n *\n * A new document keeps the player's place: the playhead stays where it was\n * (clamped when the timeline got shorter), and playback carries on if it was\n * running. Seek or pause yourself when a swap means \"start over\".\n */\n document?: ProjectDocument | VisualDocument;\n /** Overrides the engine's, for a source that carries none. */\n viewport?: Size2D;\n /** Overrides the engine's, for a source that carries none. */\n fps?: number;\n /** Initial playback rate. Change it later with {@link Player.setSpeed}. */\n speed?: number;\n /** Initial mute state. Change it later with {@link Player.setMuted}. */\n muted?: boolean;\n /** Initial loop state. Change it later with {@link Player.setLoop}. */\n loop?: boolean;\n /**\n * Called **synchronously**, on the same task as the draw, each time a frame\n * has been painted — whether by the clock, a seek, or a document swap.\n *\n * Not the playhead, which reports where the *clock* is. A seek is\n * asynchronous, so between the two there is a window in which the number has\n * moved and the canvas has not. Reach for this to keep an overlay — a\n * selection box, a caret, a handle — in step with the pixels, and keep the\n * listener cheap: it runs on the render loop, before the browser has had a\n * chance to composite.\n *\n * Read through a ref, so changing it costs nothing.\n */\n onFramePainted?: (frame: number) => void;\n}\n\n/**\n * One document, its transport, and the session driving it. No DOM.\n *\n * Hand it to a {@link MotionStage} to put pixels on screen. Two calls to\n * {@link useMotionPlayer} produce two of these with nothing shared but the\n * engine — separate playheads, clocks, audio devices and transports.\n */\nexport interface Player {\n /** The live session, or `null` before the engine and a document arrive. */\n readonly session: Session | null;\n /** The playhead, read with `usePlayhead(player)`. Stable for the hook's life. */\n readonly playhead: PlayheadStore;\n /** Resolved from the document, else the engine, else 1920×1080. */\n readonly viewport: Size2D;\n /** Resolved from the document, else the engine, else 60. */\n readonly fps: number;\n\n readonly isPlaying: boolean;\n readonly speed: number;\n readonly muted: boolean;\n readonly loop: boolean;\n /** True while a seek or a document swap is in flight. */\n readonly loading: boolean;\n /** The project's length, known from the document before any track is discovered. */\n readonly duration: number;\n /** {@link duration} in frames, floored at 1. */\n readonly totalFrames: number;\n readonly errors: BuildError[];\n readonly precomp: PrecompProgress;\n\n play(): void;\n pause(): void;\n toggle(): void;\n /** Seek while paused. Clamped to the timeline. */\n seek(frame: number): void;\n /** Seek relative to where the playhead is now. */\n step(delta: number): void;\n /** Seek without interrupting playback. */\n seekWhilePlaying(frame: number): void;\n setSpeed(speed: number): void;\n setMuted(muted: boolean): void;\n setLoop(loop: boolean): void;\n\n screenshot(): Promise<string | undefined>;\n /** Re-layout and repaint the current frame — no re-evaluation. */\n repaint(): void;\n\n getTreeState(): TreeState | null;\n getNodeProps(nodeId: string): NodeState | null;\n /** The node's props before any command has acted on it: the same at every frame, and answered while it is off screen. */\n getNodeInitialProps(nodeId: string): NodeState[\"properties\"] | null;\n /** Where each track sits on the timeline, in document order. */\n getTrackSpans(): readonly TrackSpan[];\n /**\n * Resolves once the paint a document swap scheduled has landed. The swap\n * does not paint before its assets have loaded, so await this before\n * screenshotting or reading the tree.\n */\n whenReplaced(): Promise<void>;\n\n // ---- Direct manipulation ----------------------------------------------\n // Points are in viewport space — origin at the viewport centre, y-up, in\n // this player's `viewport` pixels.\n\n getNodeBox(path: string): NodeBox | null;\n getNodePropsAt(path: string): NodeState[\"properties\"] | null;\n getNodeBoxes(): NodeBox[];\n projectNode3D(\n path: string,\n parentPoints: readonly Vector3[],\n localPoints: readonly Vector3[],\n ): Node3DFrame | null;\n /**\n * Where `point` lands on the plane the node at `path` is positioned in, in\n * that plane's own y-up frame. Two answers differ by the `x`/`y` change that\n * moves the node between them — which a screen delta no longer is once the\n * node sits in a 2.5D space.\n */\n parentPlanePoint(path: string, point: Vector2): Vector2 | null;\n /**\n * Where `point` lands in the coordinates the node at `path` positions its\n * children in (a graph's units), or `null` when those are pixels: the\n * `x`/`y` to give a node dropped or pasted there.\n */\n childPlanePoint(path: string, point: Vector2): Vector2 | null;\n /**\n * What keeps the node at `path` looking as it does once it moves under the\n * node at `parentPath`: `offsets` (`x`/`y` values it takes under its parent\n * now) as the ones that put it at the same place there, and the turn to add\n * and the factor to scale by. `null` when that parent arranges its children\n * itself.\n */\n reparentPlacement(path: string, parentPath: string, offsets: readonly Vector2[]): ReparentPlacement | null;\n /** The points an editor may drag on the node at `path` (an arrow's ends), in viewport space. */\n nodeHandles(path: string): NodeHandle[] | null;\n /** The value of `prop` that puts its handle under `point`, or `null`. */\n handleValue(path: string, prop: string, point: Vector2): Vector2 | null;\n getTextLayout(path: string): NodeTextLayout | null;\n /** `tolerance` is grab-slop in scene units. */\n pickNode(point: Vector2, tolerance?: number): NodeBox | null;\n /** Layer transient props over a node without rebuilding its track. */\n setNodeOverride(path: string, props: NodeOverride): void;\n clearNodeOverrides(path?: string): void;\n}\n\n/**\n * Opens a session on `engine` and gives you the transport for it.\n *\n * ```tsx\n * const player = useMotionPlayer({ engine, document: doc, loop: true });\n * <MotionStage player={player} />\n * ```\n */\nexport function useMotionPlayer(options: MotionPlayerOptions): Player {\n const { engine, document, onFramePainted } = options;\n\n // Read straight off the document where it says so, else the caller's, else\n // the engine's. All plain JSON, so this resolves during render, before any\n // session exists — which is what lets a stage size its canvas on the first\n // pass rather than after a mount.\n const projectDoc = document && isProjectDocument(document) ? document : undefined;\n const resolvedViewport = projectDoc?.viewport ?? options.viewport ?? engine?.viewport ?? DEFAULT_VIEWPORT;\n const fps = projectDoc?.fps ?? options.fps ?? engine?.fps ?? DEFAULT_FPS;\n\n // Held by size: a host that rebuilds its document per edit rebuilds this\n // object with it, and a new one would hand every consumer a new `Player`.\n const [viewport, setViewport] = useState(resolvedViewport);\n if (viewport.width !== resolvedViewport.width || viewport.height !== resolvedViewport.height) {\n setViewport(resolvedViewport);\n }\n const hasDocument = document !== undefined;\n\n const [session, setSession] = useState<Session | null>(null);\n /** Created once; stable for the hook's life, so `usePlayhead` never resubscribes. */\n const [playhead] = useState(createPlayheadStore);\n\n const [isPlaying, setIsPlaying] = useState(false);\n const [speed, setSpeedState] = useState(options.speed ?? 1);\n const [muted, setMutedState] = useState(options.muted ?? false);\n const [loop, setLoopState] = useState(options.loop ?? false);\n const [loading, setLoading] = useState(true);\n const [duration, setDuration] = useState(0);\n const [errors, setErrors] = useState<BuildError[]>(NO_ERRORS);\n const [precomp, setPrecomp] = useState<PrecompProgress>(INITIAL_PRECOMP);\n\n const totalFrames = Math.max(1, Math.round(duration * fps));\n\n // Stable across renders so the action callbacks below never need rebuilding.\n const controllerRef = useRef<PlaybackController | null>(null);\n const sessionRef = useRef<Session | null>(null);\n const documentRef = useRef(document);\n const onFramePaintedRef = useRef(onFramePainted);\n /** Monotonic seek id; only the latest may clear the loading flag. */\n const seekTokenRef = useRef(0);\n /** Read by the tick handler, which is installed once and must see the latest. */\n const loopRef = useRef(loop);\n const fpsRef = useRef(fps);\n const speedRef = useRef(speed);\n /**\n * What the transport has been told to do, ahead of the next render. State\n * only shows the last value a batch settled on, and the controller is\n * driven by the calls that were made, so the two can disagree inside one\n * batch (`seek` then `play`).\n */\n const playingRef = useRef(false);\n\n useEffect(() => {\n onFramePaintedRef.current = onFramePainted;\n loopRef.current = loop;\n fpsRef.current = fps;\n speedRef.current = speed;\n playingRef.current = isPlaying;\n });\n\n // An edit keeps the transport and its errors — the reconcile effect below\n // re-reads both off the session, so an error the edit did not fix never\n // blinks out for a commit. Only losing the document stops it, during render\n // so nothing draws against a timeline that is gone.\n const [prevDocument, setPrevDocument] = useState(document);\n if (document !== prevDocument) {\n setPrevDocument(document);\n if (document === undefined) {\n setIsPlaying(false);\n setDuration(0);\n if (errors.length > 0) setErrors(NO_ERRORS);\n }\n }\n\n /**\n * Pull what the controller now knows: timeline length, errors, progress.\n * Runs on every swap, so it keeps whatever did not change — a fresh array or\n * object here is a new `Player` for every consumer on every edit.\n */\n const sync = useCallback((pc: PlaybackController) => {\n setDuration(pc.totalDuration);\n setErrors(errorsFrom(pc.buildErrors));\n const progress = precompProgressOf(pc.precomp);\n setPrecomp(held => (samePrecomp(held, progress) ? held : progress));\n }, []);\n\n /**\n * Move the playhead and repaint, with the loading flag the UI paces off.\n *\n * Created once so every caller — the transport, the reconcile effect and\n * the first paint after a session opens — shares one seek discipline.\n */\n const [seekTo] = useState(() => (frame: number): Promise<boolean> => {\n const pc = controllerRef.current;\n if (!pc) return Promise.resolve(false);\n const last = Math.max(0, Math.round(pc.totalDuration * fpsRef.current) - 1);\n const clamped = Math.min(Math.max(0, Math.round(frame)), last);\n playhead.set(clamped);\n // Only the newest seek may report \"settled\". A superseded seek still\n // resolves — its generation guard bailed inside the controller — but it\n // never painted, so clearing the loading flag from it would tell the UI\n // a frame is ready while the newest is still in flight. Consumers pace\n // scrubbing off that edge.\n const token = ++seekTokenRef.current;\n setLoading(true);\n // Resolves `true` when this was still the newest seek as it landed.\n return pc.seek(clamped).then(() => {\n const newest = token === seekTokenRef.current;\n if (newest) setLoading(false);\n return newest;\n });\n });\n\n useEffect(() => {\n if (!engine || !document) return;\n\n // `target` is omitted: the session opens unmounted, and a `MotionStage`\n // binds a canvas to it afterwards. That is what lets this hook own the\n // session without owning any DOM.\n const opened = engine.open({\n document,\n viewport,\n fps,\n // A track landing can surface a build error it threw.\n onPrecompProgress: () => sync(opened.controller),\n });\n\n const pc = opened.controller;\n pc.onRenderError = errs => setErrors(errorsFrom(errs));\n pc.onFramePainted = frame => onFramePaintedRef.current?.(frame);\n\n pc.onTime((t: number) => {\n const frame = Math.floor(clipTimeToFrame(t, fpsRef.current));\n playhead.set(frame);\n\n // A document swap can change the timeline's length, so ask the\n // controller rather than trusting a duration captured when this\n // listener was installed.\n const last = Math.round(pc.totalDuration * fpsRef.current) - 1;\n if (frame < last) return;\n if (loopRef.current) pc.seekWhilePlaying(0);\n else {\n playingRef.current = false;\n setIsPlaying(false);\n }\n });\n\n controllerRef.current = pc;\n sessionRef.current = opened;\n documentRef.current = document;\n setSession(opened);\n sync(pc);\n setLoading(true);\n\n return () => {\n controllerRef.current = null;\n sessionRef.current = null;\n setSession(null);\n // Disposes the controller and the render context together — the\n // session owns both.\n disposedSessions.add(opened);\n opened.dispose();\n };\n // `document` is deliberately absent — only whether there is one: a new\n // document is reconciled onto the live session by the effect below\n // rather than rebuilt into a new one. What remains genuinely does need a\n // rebuild — a different engine is a different renderer, and a live\n // surface cannot change its size or rate (`Session.replace` refuses both).\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [engine, hasDocument, viewport.width, viewport.height, fps, sync]);\n\n // Reconcile a changed document onto the session already running. Skipped on\n // the pass that opens it, which was opened with this very document —\n // replacing it there would rediscover a timeline just discovered.\n useEffect(() => {\n if (documentRef.current === document) return;\n documentRef.current = document;\n const live = sessionRef.current;\n if (!live || !document) return;\n const pc = live.controller;\n live.replace(document);\n sync(pc);\n // No seek: `replace` already paints the current frame once its assets\n // load, clamped to the new length, and a running clock keeps ticking.\n const last = Math.max(0, Math.round(pc.totalDuration * fpsRef.current) - 1);\n playhead.set(Math.min(playhead.getSnapshot(), last));\n const token = ++seekTokenRef.current;\n setLoading(true);\n void pc.whenReplaced().then(() => {\n if (token === seekTokenRef.current) setLoading(false);\n });\n }, [document, sync, playhead]);\n\n useEffect(() => {\n const pc = controllerRef.current;\n if (!pc) return;\n if (isPlaying) pc.play(speed);\n else pc.pause();\n }, [session, isPlaying, speed]);\n\n useEffect(() => {\n controllerRef.current?.setMuted(muted);\n }, [session, muted]);\n\n // The one seek that isn't user-driven: park the new session on the frame\n // the playhead already holds, so a rebuild keeps its place.\n //\n // A seek pauses the clock, and the clock effect above has already started\n // this session, so a player that was playing resumes once the park lands\n // (with its assets loaded, so the first ticks draw rather than catch up). It\n // does not if the transport moved meanwhile: a newer seek, or a pause.\n useEffect(() => {\n const pc = controllerRef.current;\n if (!pc) return;\n const wasPlaying = playingRef.current;\n const parked = seekTo(playhead.getSnapshot());\n if (!wasPlaying) return;\n void parked.then(newest => {\n if (!newest || controllerRef.current !== pc || !playingRef.current || pc.isPlaying) return;\n pc.play(speedRef.current);\n });\n }, [session, playhead, seekTo]);\n\n // Built once and stable for the hook's life: every one reads the controller\n // through a ref, so a re-render never invalidates a handler a child holds —\n // which is what lets a transport subscribe its listeners a single time.\n const [actions] = useState<Omit<Player, keyof PlayerState>>(() => {\n // Scrubbing is a pause: a seek that left the clock running would be\n // overwritten by the next tick.\n const seek = (frame: number) => {\n playingRef.current = false;\n setIsPlaying(false);\n void seekTo(frame);\n };\n\n return {\n playhead,\n // Both drive the controller as well as the state. In one batch a\n // `seek` and a `play` cancel out in state (`true`, `false`, `true`\n // while playing), so the effect on `isPlaying` never re-runs, yet the\n // seek has already paused the clock; the state is the settled\n // answer and the controller is what was actually asked.\n play: () => {\n playingRef.current = true;\n setIsPlaying(true);\n const pc = controllerRef.current;\n if (pc && !pc.isPlaying) pc.play(speedRef.current);\n },\n pause: () => {\n playingRef.current = false;\n setIsPlaying(false);\n controllerRef.current?.pause();\n },\n toggle: () =>\n setIsPlaying(playing => {\n // Restarting from the end is what a play button means there.\n const pc = controllerRef.current;\n if (!playing && pc) {\n const last = Math.round(pc.totalDuration * fpsRef.current) - 1;\n if (playhead.getSnapshot() >= last) void pc.seek(0);\n }\n return !playing;\n }),\n seek,\n step: (delta: number) => seek(playhead.getSnapshot() + delta),\n seekWhilePlaying: (frame: number) => controllerRef.current?.seekWhilePlaying(frame),\n setSpeed: (next: number) => setSpeedState(next),\n setMuted: (next: boolean) => setMutedState(next),\n setLoop: (next: boolean) => setLoopState(next),\n\n screenshot: async () => controllerRef.current?.screenshot() ?? undefined,\n repaint: () => controllerRef.current?.repaint(),\n\n getTreeState: () => controllerRef.current?.getTreeState() ?? null,\n getNodeProps: (nodeId: string) => controllerRef.current?.getNodeState(nodeId) ?? null,\n getNodeInitialProps: (nodeId: string) => controllerRef.current?.getNodeInitialProps(nodeId) ?? null,\n getTrackSpans: () => controllerRef.current?.spans ?? [],\n whenReplaced: async () => {\n await controllerRef.current?.whenReplaced();\n },\n\n getNodeBox: (path: string) => controllerRef.current?.getNodeBox(path) ?? null,\n getNodePropsAt: (path: string) => controllerRef.current?.getNodePropsAt(path) ?? null,\n getNodeBoxes: () => controllerRef.current?.getNodeBoxes() ?? [],\n projectNode3D: (path, parentPoints, localPoints) =>\n controllerRef.current?.projectNode3D(path, parentPoints, localPoints) ?? null,\n parentPlanePoint: (path: string, point: Vector2) =>\n controllerRef.current?.parentPlanePoint(path, point) ?? null,\n childPlanePoint: (path: string, point: Vector2) =>\n controllerRef.current?.childPlanePoint(path, point) ?? null,\n reparentPlacement: (path: string, parentPath: string, offsets: readonly Vector2[]) =>\n controllerRef.current?.reparentPlacement(path, parentPath, offsets) ?? null,\n nodeHandles: (path: string) => controllerRef.current?.nodeHandles(path) ?? null,\n handleValue: (path: string, prop: string, point: Vector2) =>\n controllerRef.current?.handleValue(path, prop, point) ?? null,\n getTextLayout: (path: string) => controllerRef.current?.getTextLayout(path) ?? null,\n pickNode: (point: Vector2, tolerance?: number) =>\n controllerRef.current?.pickNode(point, tolerance) ?? null,\n setNodeOverride: (path: string, props: NodeOverride) =>\n controllerRef.current?.setNodeOverride(path, props),\n clearNodeOverrides: (path?: string) => controllerRef.current?.clearNodeOverrides(path),\n };\n });\n\n return useMemo(\n () => ({\n ...actions,\n session,\n viewport,\n fps,\n isPlaying,\n speed,\n muted,\n loop,\n loading,\n duration,\n totalFrames,\n errors,\n precomp,\n }),\n [\n actions,\n session,\n viewport,\n fps,\n isPlaying,\n speed,\n muted,\n loop,\n loading,\n duration,\n totalFrames,\n errors,\n precomp,\n ],\n );\n}\n\n/** The fields the memo above supplies; everything else on `Player` is an action. */\ntype PlayerState = Pick<\n Player,\n | \"session\"\n | \"viewport\"\n | \"fps\"\n | \"isPlaying\"\n | \"speed\"\n | \"muted\"\n | \"loop\"\n | \"loading\"\n | \"duration\"\n | \"totalFrames\"\n | \"errors\"\n | \"precomp\"\n>;\n","import { useEffect, useRef, type CSSProperties } from \"react\";\n\nimport type { EngineRenderContext, Size2D } from \"@motionscript/core\";\n\nimport { isSessionDisposed, type Player } from \"./use-motion-player\";\n\n/**\n * The session's surface, with `mount` narrowed to a canvas.\n *\n * `core` compiles without the DOM lib, so `RenderSurface.mount` takes `unknown`\n * there. This is the narrowing that seam always assumed: it happens here, in\n * the one layer that genuinely has `HTMLCanvasElement`.\n */\ntype StageRenderContext = Omit<EngineRenderContext, \"mount\"> & {\n mount(canvas: HTMLCanvasElement): void;\n};\n\n/**\n * What every stage that doesn't ask for a view gets: the whole frame, 1:1.\n *\n * A shared frozen object rather than a literal, so the view effect's dependency\n * on its fields is stable across renders for the overwhelming majority of\n * stages, which never pass `view` at all.\n */\nconst IDENTITY_VIEW = Object.freeze({ zoom: 1, x: 0, y: 0 });\n\nexport interface MotionStageProps {\n /** The player whose session this stage draws. */\n player: Player;\n /**\n * Device pixels to rasterize per viewport unit. Defaults to `1`.\n *\n * **Not a zoom and not a crop.** The viewport stays the scene's logical\n * coordinate space; this only changes how many real pixels that space is\n * drawn into, and CSS scales the canvas back up to fill its box.\n *\n * The lever exists because a preview is usually displayed far smaller than\n * the project's output size: a 1920×1080 project in a 700px-wide panel\n * rasterizes roughly seven times the pixels anyone can see. `0.5` there is a\n * quarter of the fill, the shader work and the effect offscreens.\n *\n * Two things to know before animating it:\n *\n * - **Every change re-creates the GPU surface**, which drops the storage\n * adapter's texture-backed images (decoded video frames, 3D composites;\n * still images survive) and asks for a fresh GL context. Quantize to a few\n * steps and let it settle — never drive it from a resize observer.\n * - **Prefer scales that keep both dimensions whole.** `pixelRatio` is one\n * uniform number, so a scale that rounds differently on each axis shifts\n * the frame's centre by up to half a device pixel.\n *\n * A snapshot from `player.screenshot()` comes back at the surface's size, so\n * it is scaled too — render at `1` if you need full resolution out of it.\n */\n renderScale?: number;\n /**\n * The canvas's own size in CSS pixels, when it is **not** the frame.\n *\n * Omitted — the default — the canvas is the frame: sized `viewport ×\n * renderScale` and stretched over its box by CSS, which is what every\n * export, thumbnail and plain player wants.\n *\n * Supplied, together with {@link view}, the canvas becomes a *window* onto\n * the frame: it takes the size of the area it is shown in, `renderScale`\n * stops meaning \"fraction of the project's resolution\" and starts meaning\n * device pixels per CSS pixel, and only what is on screen is rasterized.\n * That is what lets an editor zoom in without going soft or paying for the\n * whole frame at the zoomed resolution.\n *\n * It re-creates the surface exactly as `renderScale` does, and wants the\n * same treatment: quantize it and let it settle.\n */\n surfaceSize?: Size2D;\n /**\n * A pan and zoom applied to the render itself. Requires {@link surfaceSize}.\n *\n * `zoom` multiplies scene units; `x`/`y` offset the frame's centre in CSS\n * pixels, positive `y` downwards — the same sign convention as a CSS\n * translate, so a preview can hand over the pan it was already computing.\n *\n * Changing it costs a repaint and nothing else: no surface, no textures, no\n * precomp. That is the point of it living here rather than in a CSS\n * transform, which cannot add resolution it was not rasterized with.\n */\n view?: { zoom: number; x: number; y: number };\n /**\n * Whether the frame's edge bounds what draws, rather than only where its own\n * backdrop goes. Requires {@link surfaceSize} and {@link view}. Defaults to\n * `true`.\n *\n * Off lets a node parked past the frame's edge rasterize into the rest of\n * the surface instead of being discarded — for a host that wants to show,\n * faded, what a node placed there while animating in or out.\n */\n clipToFrame?: boolean;\n /**\n * What the frame's backdrop is painted with. Defaults to `\"black\"`.\n *\n * `\"transparent\"` leaves the frame unpainted where nothing was drawn, so\n * whatever the host renders behind the canvas shows through — a\n * checkerboard, for an editor that has to distinguish \"no scene covers this\"\n * from \"a scene covers it in black\". Requires {@link surfaceSize} and\n * {@link view}, the same way {@link clipToFrame} does.\n */\n frameBackground?: \"black\" | \"transparent\";\n className?: string;\n style?: CSSProperties;\n}\n\n/**\n * A canvas bound to a {@link Player}'s session.\n *\n * The stage owns how the frame is rasterized — resolution, view, clipping — and\n * nothing about what is in it or when. A session drives **one** surface, so one\n * stage per player: a second would take the surface from the first.\n */\nexport function MotionStage({\n player,\n renderScale = 1,\n surfaceSize,\n view,\n clipToFrame,\n frameBackground,\n className,\n style,\n}: MotionStageProps) {\n const canvasRef = useRef<HTMLCanvasElement>(null);\n const { session } = player;\n // The session's own size, not the player's: the player's moves a commit\n // ahead, in the commit whose cleanup disposes the old session, and a buffer\n // resized there would re-bind that disposed session.\n const viewport = session?.viewport ?? player.viewport;\n\n /**\n * The canvas's backing store, in device pixels. `viewport × renderScale` in\n * the default case, where the canvas *is* the frame; with `surfaceSize` it\n * is the viewing area instead.\n *\n * Floored at 1 so a degenerate scale can't ask the renderer for a zero-sized\n * surface, which fails the surface creation outright.\n */\n const bufferWidth = Math.max(1, Math.round((surfaceSize?.width ?? viewport.width) * renderScale));\n const bufferHeight = Math.max(1, Math.round((surfaceSize?.height ?? viewport.height) * renderScale));\n\n /**\n * The view transform to draw with, and the frame to clip and anchor against.\n * Only meaningful together, so they resolve in one place: no `surfaceSize`\n * means the canvas is the frame, and both revert to identity.\n */\n const activeView = surfaceSize && view ? view : IDENTITY_VIEW;\n const activeFrame = surfaceSize && view ? viewport : null;\n const activeClipToFrame = surfaceSize && view ? (clipToFrame ?? true) : true;\n const activeFrameBackground = surfaceSize && view ? (frameBackground ?? \"black\") : \"black\";\n\n const viewRef = useRef(activeView);\n const frameRectRef = useRef(activeFrame);\n const clipToFrameRef = useRef(activeClipToFrame);\n const frameBackgroundRef = useRef(activeFrameBackground);\n /**\n * The live render context.\n *\n * Held here rather than reached through `player.session` at each use because\n * it is mutable external state — a GPU context whose knobs are written, not\n * a value derived from a prop — and writing through the prop is what the\n * immutability lint is there to catch everywhere it *isn't* one of these.\n */\n const ctxRef = useRef<StageRenderContext | null>(null);\n useEffect(() => {\n viewRef.current = activeView;\n frameRectRef.current = activeFrame;\n clipToFrameRef.current = activeClipToFrame;\n frameBackgroundRef.current = activeFrameBackground;\n ctxRef.current = session ? (session.surface as StageRenderContext) : null;\n });\n\n /**\n * Bind the surface, and rebuild it when the backing store changes.\n *\n * The order matters and is why this is an effect rather than a callback:\n * React has already written the canvas's new `width`/`height` by the time\n * effects run, and the renderer reads exactly those when it builds the surface\n * (`MakeOnScreenGLSurface(ctx, canvas.width, canvas.height)`). Mounting\n * before the resize would produce a surface of the previous size.\n *\n * `repaint()` afterwards because a new surface starts blank and the clock is\n * not necessarily running to fill it — a paused editor would otherwise show\n * black until something else moved.\n */\n useEffect(() => {\n const canvas = canvasRef.current;\n const ctx = ctxRef.current;\n // A replayed effect can hold a session its player has since disposed.\n if (!session || !canvas || !ctx || isSessionDisposed(session)) return;\n ctx.pixelRatio = renderScale;\n ctx.view = viewRef.current;\n ctx.frame = frameRectRef.current;\n ctx.clipToFrame = clipToFrameRef.current;\n ctx.frameBackground = frameBackgroundRef.current;\n // `mount` detaches the old surface first, which also drops the storage\n // adapter's texture-backed images — they belong to the surface that made\n // them. Video frames and 3D composites are re-uploaded on demand;\n // decoded still images are raster-backed and survive.\n ctx.mount(canvas);\n session.controller.repaint();\n }, [session, renderScale, bufferWidth, bufferHeight]);\n\n /**\n * Apply {@link MotionStageProps.view} — a repaint and nothing more.\n *\n * Depends on the fields rather than the object so a caller passing a fresh\n * `{zoom, x, y}` each render — which is every caller, since it comes from a\n * gesture — doesn't repaint on renders where the view didn't move.\n */\n useEffect(() => {\n const ctx = ctxRef.current;\n if (!session || !ctx || isSessionDisposed(session)) return;\n ctx.view = { zoom: activeView.zoom, x: activeView.x, y: activeView.y };\n ctx.frame = activeFrame;\n ctx.clipToFrame = activeClipToFrame;\n ctx.frameBackground = activeFrameBackground;\n session.controller.repaint();\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [\n session,\n activeView.zoom,\n activeView.x,\n activeView.y,\n activeFrame?.width,\n activeFrame?.height,\n activeClipToFrame,\n activeFrameBackground,\n ]);\n\n return (\n <div className={className} style={{ position: \"relative\", width: \"100%\", height: \"100%\", ...style }}>\n <canvas\n ref={canvasRef}\n // The backing store, in device pixels. CSS below stretches it\n // back over the whole box either way, so this is purely how much\n // gets rasterized.\n width={bufferWidth}\n height={bufferHeight}\n style={{\n display: session ? \"block\" : \"none\",\n ...(surfaceSize\n ? {\n // `surfaceSize` is the canvas's CSS size, so it is\n // honoured literally rather than stretched to the\n // box: it is quantized by its caller, which means\n // it is usually a little larger than the box and\n // rarely the same shape. Stretched, that\n // difference would land as a non-uniform scale — a\n // picture squashed on one axis, a far worse\n // artefact than the softness this arrangement\n // exists to remove.\n //\n // Centred, so the surface's midpoint is the box's\n // midpoint: `executePass` puts the scene origin at\n // the centre of the surface, so this is what makes\n // the frame land where the caller's layout says it\n // is. The spare pixels hang off all four edges and\n // are clipped by whatever is holding this.\n position: \"absolute\",\n left: \"50%\",\n top: \"50%\",\n width: `${surfaceSize.width}px`,\n height: `${surfaceSize.height}px`,\n transform: \"translate(-50%, -50%)\",\n }\n : { width: \"100%\", height: \"100%\" }),\n }}\n />\n </div>\n );\n}\n"],"mappings":";;;;AAkBA,SAAS,SAAS,OAAgB;CAC9B,QAAQ,MAAM,4CAA4C,KAAK;AACnE;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,UACZ,QACA,UAA4B,CAAC,GACrB;CACR,MAAM,EAAE,OAAO,CAAC,GAAG,YAAY;CAC/B,MAAM,CAAC,QAAQ,aAAa,SAAmB,IAAI;CACnD,MAAM,YAAY,OAAO,MAAM;CAC/B,MAAM,aAAa,OAAO,OAAO;CAEjC,gBAAgB;EACZ,UAAU,UAAU;EACpB,WAAW,UAAU;CACzB,CAAC;CAED,gBAAgB;EACZ,IAAI,OAAO;EACX,IAAI,QAAkB;EAEtB,IAAI,SAAW,YAAW,QAAQ,UAAU,QAAQ,CAAC,CAAC,EACjD,MAAK,S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G,YAAY,MAAM;KAC5B,QAAQ,GAAG,YAAY,OAAO;KAC9B,WAAW;IACf,IACA;KAAE,OAAO;KAAQ,QAAQ;IAAO;GAC1C;EACH,CAAA;CACA,CAAA;AAEb"}
@@ -18,7 +18,7 @@ export interface MotionStageProps {
18
18
  *
19
19
  * Two things to know before animating it:
20
20
  *
21
- * - **Every change re-creates the Skia surface**, which drops the storage
21
+ * - **Every change re-creates the GPU surface**, which drops the storage
22
22
  * adapter's texture-backed images (decoded video frames, 3D composites;
23
23
  * still images survive) and asks for a fresh GL context. Quantize to a few
24
24
  * steps and let it settle — never drive it from a resize observer.
@@ -18,7 +18,7 @@ export interface UseEngineOptions {
18
18
  * when it is no longer wanted.
19
19
  *
20
20
  * ```tsx
21
- * const engine = useEngine(() => createBrowserEngine({ wasmUrl: "/canvaskit.wasm" }));
21
+ * const engine = useEngine(() => createBrowserEngine());
22
22
  * const player = useMotionPlayer({ engine, document: doc });
23
23
  * ```
24
24
  *
@@ -25,9 +25,9 @@ export interface MotionPlayerOptions {
25
25
  * and it is `null` for the first render or two. The player no-ops until it
26
26
  * arrives, which is what keeps the hook out of a conditional.
27
27
  *
28
- * **Create it once, and share it.** It holds CanvasKit and the exporter, so
28
+ * **Create it once, and share it.** It holds the renderer and the exporter, so
29
29
  * a fresh one per render rebuilds the WebGL surface behind every player on
30
- * it. Identity-compared: a different engine is a different CanvasKit, and so
30
+ * it. Identity-compared: a different engine is a different renderer, and so
31
31
  * a full rebuild.
32
32
  */
33
33
  engine: Engine | null | undefined;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@motionscript/react",
3
- "version": "0.1.0-alpha.7",
3
+ "version": "0.1.0-alpha.9",
4
4
  "type": "module",
5
5
  "description": "React bindings for Motion Script.",
6
6
  "repository": {
@@ -13,6 +13,7 @@
13
13
  "url": "https://github.com/motionscript-dev/motionscript/issues"
14
14
  },
15
15
  "license": "Apache-2.0",
16
+ "author": "Motionscript",
16
17
  "sideEffects": false,
17
18
  "publishConfig": {
18
19
  "access": "public"
@@ -34,7 +35,7 @@
34
35
  "peerDependencies": {
35
36
  "react": "^18.2.0 || ^19.0.0",
36
37
  "react-dom": "^18.2.0 || ^19.0.0",
37
- "@motionscript/core": "^0.1.0-alpha.7"
38
+ "@motionscript/core": "^0.1.0-alpha.9"
38
39
  },
39
40
  "devDependencies": {
40
41
  "@eslint/js": "^9.39.1",
@@ -56,9 +57,8 @@
56
57
  "vite": "^8.0.11",
57
58
  "vite-plugin-dts": "5.0.0",
58
59
  "vitest": "^4.1.5",
59
- "@motionscript/core": "0.1.0-alpha.7",
60
- "@motionscript/canvaskit": "0.1.0-alpha.7",
61
- "@motionscript/browser": "0.1.0-alpha.7"
60
+ "@motionscript/core": "0.1.0-alpha.9",
61
+ "@motionscript/browser": "0.1.0-alpha.9"
62
62
  },
63
63
  "scripts": {
64
64
  "dev": "vite",