@motionscript/react 0.1.0 → 0.1.1-alpha.1
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.
- package/CHANGELOG.md +11 -0
- package/README.md +1 -1
- package/dist/browser/index.js.map +2 -2
- package/dist/browser/manifest.json +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/motionscript-react.js +20 -92
- package/dist/motionscript-react.js.map +1 -1
- package/dist/ui/playhead.d.ts +5 -13
- package/dist/ui/playhead.d.ts.map +1 -1
- package/dist/ui/stage.d.ts +27 -62
- package/dist/ui/stage.d.ts.map +1 -1
- package/dist/ui/use-engine.d.ts +13 -19
- package/dist/ui/use-engine.d.ts.map +1 -1
- package/dist/ui/use-motion-player.d.ts +25 -49
- package/dist/ui/use-motion-player.d.ts.map +1 -1
- package/package.json +4 -4
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,16 @@
|
|
|
1
1
|
# @motionscript/react
|
|
2
2
|
|
|
3
|
+
## 0.1.1-alpha.1
|
|
4
|
+
|
|
5
|
+
## 0.1.1-alpha.0
|
|
6
|
+
|
|
7
|
+
### Patch Changes
|
|
8
|
+
|
|
9
|
+
- Updated dependencies [3630b74]
|
|
10
|
+
- Updated dependencies [1c43a37]
|
|
11
|
+
- Updated dependencies [e279864]
|
|
12
|
+
- @motionscript/core@0.1.1-alpha.0
|
|
13
|
+
|
|
3
14
|
## 0.1.0
|
|
4
15
|
|
|
5
16
|
## 0.1.0-alpha.10
|
package/README.md
CHANGED
|
@@ -84,7 +84,7 @@ it returns in — which is also why nothing in this package imports a platform,
|
|
|
84
84
|
it works with `@motionscript/browser`'s engine, a headless one, or a test double.
|
|
85
85
|
|
|
86
86
|
**Create it once and share it.** It holds the renderer and the exporter, so a
|
|
87
|
-
second engine is a second wasm module and a second
|
|
87
|
+
second engine is a second wasm module and a second renderer. `engine` is
|
|
88
88
|
nullable precisely because building one is async: the player no-ops until it
|
|
89
89
|
arrives, which keeps the hook out of a conditional.
|
|
90
90
|
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/ui/use-engine.ts", "../../src/ui/playhead.ts", "../../src/ui/use-motion-player.ts", "../../src/ui/stage.tsx"],
|
|
4
|
-
"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"],
|
|
5
|
-
"mappings": "
|
|
4
|
+
"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 as `useEffect` does.\n * The default, `[]`, builds it once. List only what makes a *different*\n * engine (node types, the wasm URL): the latest `create` is always the one\n * called, so its closure is not a dependency.\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, `null` until it arrives, and disposes it when it is no\n * longer wanted. What to build is the factory's job: nothing here imports a\n * platform.\n *\n * ```tsx\n * const engine = useEngine(() => createBrowserEngine());\n * const player = useMotionPlayer({ engine, document: doc });\n * ```\n *\n * An unmount while the factory was still pending (StrictMode does this on every\n * dev mount) frees the engine the moment it lands; a change in `deps` disposes\n * 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 renderer. Anything that must hold before a player sees the engine, such as\n * `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: a frame written at clock rate through\n * `useState` would re-render the player's owner faster than the project's frame\n * rate, and nothing in a render depends on it (the controller paints straight\n * onto the canvas). Only components that 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/** Subscribe *this* component to the playhead. Takes `{ playhead }` rather than `Player` to avoid an import cycle with `use-motion-player`. */\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/** Background asset discovery: only frame-0 tracks are discovered before mount, the rest stream in. The timeline's length never waits on it. */\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 ran (a suspended\n * boundary revealed, StrictMode), so a stage asks here before binding.\n */\nconst disposedSessions = new WeakSet<Session>();\n\n/** @internal 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. Nullable because building one\n * is async ({@link useEngine}): the player no-ops until it arrives.\n *\n * Create it once and share it: it holds the renderer and the exporter, so a\n * fresh one per render rebuilds the renderer behind every player on it.\n * Compared by identity; a different engine is a full rebuild.\n */\n engine: Engine | null | undefined;\n /**\n * What to play; nothing opens until there is one. A project document carries\n * its own viewport, fps, theme and tracks; a scene document (still or\n * composition) carries none, so `viewport` and `fps` come from here or the\n * engine.\n *\n * Content-diffed, identity first: a new document is reconciled onto the\n * running session, each track patched in place and rebuilt only when it\n * cannot be. Treat documents as immutable: an in-place edit is not seen.\n *\n * A new document keeps the player's place (the playhead is clamped to a\n * shorter timeline, playback carries on). Seek or pause yourself when a swap\n * 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 has\n * been painted (clock, seek or document swap).\n *\n * Not the playhead, which reports where the clock is: a seek is async, so the\n * number can move before the canvas does. Use it to keep an overlay in step\n * with the pixels, and keep it cheap: it runs on the render loop. Read through\n * a ref, so changing it costs nothing.\n */\n onFramePainted?: (frame: number) => void;\n}\n\n/** A document's transport and its session, with no DOM. Two calls to {@link useMotionPlayer} share only the engine. */\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 /** Pauses, then seeks. 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 // Points below 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 // Document, then options, then engine. Resolved during render, before any\n // session exists, so a stage can size its canvas on the first pass.\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 would otherwise\n // 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 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 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 was told to do, ahead of the next render. State shows\n * only the last value a batch settled on, so it can disagree with the\n * controller inside one 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 errors (the reconcile effect re-reads both,\n // so an unfixed error never blinks out); only losing the document stops it,\n // during render 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 /** Pulls duration, errors and progress off the controller, keeping what did not change: a fresh array or object is a new `Player` on every edit. */\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 /** One instance, so the transport, the reconcile effect and a session's first paint share one seek discipline. */\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 // A superseded seek still resolves (its generation guard bailed in the\n // controller) but never painted, so only the newest may clear `loading`:\n // consumers pace scrubbing off that edge.\n const token = ++seekTokenRef.current;\n setLoading(true);\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 afterwards, so this hook owns no 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 // Asks the controller: a swap can change the length after 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 disposedSessions.add(opened);\n opened.dispose();\n };\n // `document` is deliberately absent (only whether there is one): the effect\n // below reconciles a new one onto the live session. Everything listed\n // needs a rebuild: a different engine is a different renderer, and a live\n // surface cannot change 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 running session. Skipped on the pass\n // that opened it, which already holds this document.\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` paints the current frame once its assets load, and a\n // 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 // Parks a new session on the frame the playhead holds, so a rebuild keeps its\n // place. The seek pauses the clock the effect above just started, so a player\n // that was playing resumes once the park lands (assets loaded, so the first\n // ticks draw rather than catch up), unless a newer seek or a pause moved the\n // transport meanwhile.\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: every action reads the controller through a ref, so a re-render\n // never invalidates a handler a child holds.\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 state: in one batch a `seek` and\n // a `play` cancel out in state, so the `isPlaying` effect never re-runs\n // though the seek already paused the clock.\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/** Core compiles without the DOM lib, so `RenderSurface.mount` takes `unknown`; narrowed here, where `HTMLCanvasElement` exists. */\ntype StageRenderContext = Omit<EngineRenderContext, \"mount\"> & {\n mount(canvas: HTMLCanvasElement): void;\n};\n\nconst IDENTITY_VIEW = Object.freeze({ zoom: 1, x: 0, y: 0 });\n\nexport interface MotionStageProps {\n player: Player;\n /**\n * Device pixels rasterized per viewport unit. Defaults to `1`. Not a zoom or\n * a crop: the scene's coordinate space is unchanged and CSS scales the canvas\n * back to its box. `<1` suits a preview shown far smaller than the output size.\n *\n * Every change re-creates the GPU surface, dropping texture-backed images\n * (decoded video frames, 3D composites; they re-upload on demand), so quantize\n * to a few steps and never drive it from a resize observer. Prefer scales that\n * keep both dimensions whole: `pixelRatio` is one number, so uneven rounding\n * shifts the frame's centre by up to half a device pixel.\n *\n * `player.screenshot()` returns the surface's size, so it is scaled too.\n */\n renderScale?: number;\n /**\n * The canvas's own size in CSS pixels, when it is not the frame. Omitted, the\n * canvas is the frame: `viewport × renderScale`, stretched over its box.\n *\n * Supplied together with {@link view}, the canvas becomes a window onto the\n * frame: it takes the size of the area shown, `renderScale` means device\n * pixels per CSS pixel, and only what is on screen is rasterized, so zooming\n * in stays sharp. It re-creates the surface like `renderScale`: quantize it.\n */\n surfaceSize?: Size2D;\n /**\n * Pan and zoom applied to the render itself; requires {@link surfaceSize}.\n * `zoom` multiplies scene units; `x`/`y` offset the frame's centre in CSS\n * pixels, positive `y` downwards (a CSS translate).\n *\n * A change costs a repaint and nothing else. A CSS transform could not add\n * 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. Requires {@link surfaceSize} and\n * {@link view}. Defaults to `true`; off lets a node parked past the edge\n * rasterize into the rest of the surface.\n */\n clipToFrame?: boolean;\n /**\n * Defaults to `\"black\"`. `\"transparent\"` leaves undrawn frame pixels\n * unpainted so the host's backdrop (a checkerboard) shows through. Requires\n * {@link surfaceSize} and {@link view}.\n */\n frameBackground?: \"black\" | \"transparent\";\n className?: string;\n style?: CSSProperties;\n}\n\n/**\n * A canvas bound to a {@link Player}'s session. One stage per player: a session\n * drives one surface, and a second stage would take it 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 // Floored at 1: a zero-sized surface fails creation outright.\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 // Without both `surfaceSize` and `view` the canvas is the frame, so all four revert to defaults.\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 // A ref because the context is mutable external state whose knobs are\n // written; writing through the `player` prop trips the immutability lint.\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 // Bind the surface and rebuild it when the backing store changes. An effect,\n // not a callback, because React has written the canvas's new `width`/`height`\n // by the time effects run and the renderer reads them when it builds the\n // surface: mounting before the resize would build the previous size.\n // `repaint()` because a new surface starts blank and a paused clock would not\n // fill it.\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 // Detaches the old surface first, which drops the texture-backed images\n // that belong to it.\n ctx.mount(canvas);\n session.controller.repaint();\n }, [session, renderScale, bufferWidth, bufferHeight]);\n\n // Keyed on the view's fields, not the object: callers pass a fresh\n // `{zoom, x, y}` every render, which would repaint every render.\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 width={bufferWidth}\n height={bufferHeight}\n style={{\n display: session ? \"block\" : \"none\",\n ...(surfaceSize\n ? {\n // `surfaceSize` is honoured literally, not stretched\n // to the box: it is quantized, so it is usually a\n // little larger than the box and a different shape,\n // and stretching would squash one axis.\n //\n // Centred because `executePass` puts the scene origin\n // at the surface's centre, so this lands the frame\n // where the layout says; the spare pixels hang off\n // all four edges and the parent clips them.\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"],
|
|
5
|
+
"mappings": "sRAgBA,SAASA,GAASC,EAAgB,CAC9B,QAAQ,MAAM,2CAA4CA,CAAK,CACnE,CAoBA,SAAgBC,GACZC,EACAC,EAA4B,CAAC,EACrB,CACR,GAAM,CAAE,KAAAC,EAAO,CAAC,EAAG,QAAAC,CAAA,EAAYF,EACzB,CAACG,EAAQC,CAAA,EAAaC,EAAmB,IAAI,EAC7CC,EAAYC,EAAOR,CAAM,EACzBS,EAAaD,EAAOL,CAAO,EAEjC,OAAAO,E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ps", "onError", "engine", "setEngine", "useState", "createRef", "useRef", "onErrorRef", "useEffect", "live", "built", "resolve", "next", "createPlayheadStore", "frame", "listeners", "onChange", "notify", "usePlayhead", "player", "playhead", "useSyncExternalStore", "disposedSessions", "isSessionDisposed", "session", "INITIAL_PRECOMP", "NO_ERRORS", "precompProgressOf", "result", "track", "samePrecomp", "a", "b", "sameErrors", "i", "other", "errorsFrom", "reported", "held", "useMotionPlayer", "document", "onFramePainted", "projectDoc", "isProjectDocument", "resolvedViewport", "DEFAULT_VIEWPORT", "fps", "DEFAULT_FPS", "viewport", "setViewport", "hasDocument", "setSession", "isPlaying", "setIsPlaying", "speed", "setSpeedState", "muted", "setMutedState", "loop", "setLoopState", "loading", "setLoading", "duration", "setDuration", "errors", "setErrors", "precomp", "setPrecomp", "totalFrames", "controllerRef", "sessionRef", "documentRef", "onFramePaintedRef", "seekTokenRef", "loopRef", "fpsRef", "speedRef", "playingRef", "prevDocument", "setPrevDocument", "sync", "useCallback", "pc", "progress", "seekTo", "last", "clamped", "token", "newest", "opened", "errs", "t", "clipTimeToFrame", "wasPlaying", "parked", "actions", "seek", "playing", "delta", "nodeId", "path", "parentPoints", "localPoints", "point", "parentPath", "offsets", "prop", "tolerance", "props", "useMemo", "IDENTITY_VIEW", "MotionStage", "renderScale", "surfaceSize", "view", "clipToFrame", "frameBackground", "className", "style", "canvasRef", "bufferWidth", "bufferHeight", "activeView", "activeFrame", "activeClipToFrame", "activeFrameBackground", "viewRef", "frameRectRef", "clipToFrameRef", "frameBackgroundRef", "ctxRef", "canvas", "ctx", "jsx"]
|
|
7
7
|
}
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,YAAY,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACzD,YAAY,EAAE,mBAAmB,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAC3F,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AACzC,YAAY,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AACnD,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,YAAY,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AACnD,YAAY,EAAE,UAAU,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAC"}
|
|
@@ -6,26 +6,22 @@ function logError(error) {
|
|
|
6
6
|
console.error("Could not start the MotionScript engine.", error);
|
|
7
7
|
}
|
|
8
8
|
/**
|
|
9
|
-
* Builds an engine once,
|
|
10
|
-
*
|
|
9
|
+
* Builds an engine once, `null` until it arrives, and disposes it when it is no
|
|
10
|
+
* longer wanted. What to build is the factory's job: nothing here imports a
|
|
11
|
+
* platform.
|
|
11
12
|
*
|
|
12
13
|
* ```tsx
|
|
13
14
|
* const engine = useEngine(() => createBrowserEngine());
|
|
14
15
|
* const player = useMotionPlayer({ engine, document: doc });
|
|
15
16
|
* ```
|
|
16
17
|
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
18
|
+
* An unmount while the factory was still pending (StrictMode does this on every
|
|
19
|
+
* dev mount) frees the engine the moment it lands; a change in `deps` disposes
|
|
20
|
+
* the old one and returns `null` until the new one is ready.
|
|
20
21
|
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
* disposes the old one and returns `null` until the new one is ready.
|
|
25
|
-
*
|
|
26
|
-
* Call it once and hand the engine down. A second call is a second wasm module
|
|
27
|
-
* and a second GL stack. Anything that must be true before a player sees the
|
|
28
|
-
* engine, such as `setManifest`, belongs in `create`, not in an effect beside it.
|
|
22
|
+
* Call it once and hand the engine down: a second call is a second wasm module
|
|
23
|
+
* and renderer. Anything that must hold before a player sees the engine, such as
|
|
24
|
+
* `setManifest`, belongs in `create`, not in an effect beside it.
|
|
29
25
|
*/
|
|
30
26
|
function useEngine(create, options = {}) {
|
|
31
27
|
const { deps = [], onError } = options;
|
|
@@ -77,12 +73,7 @@ function createPlayheadStore() {
|
|
|
77
73
|
}
|
|
78
74
|
};
|
|
79
75
|
}
|
|
80
|
-
/**
|
|
81
|
-
* Subscribe *this* component to the playhead.
|
|
82
|
-
*
|
|
83
|
-
* Typed structurally rather than against `Player` so the store and the hook
|
|
84
|
-
* that reads it don't import each other.
|
|
85
|
-
*/
|
|
76
|
+
/** Subscribe *this* component to the playhead. Takes `{ playhead }` rather than `Player` to avoid an import cycle with `use-motion-player`. */
|
|
86
77
|
function usePlayhead(player) {
|
|
87
78
|
const { playhead } = player;
|
|
88
79
|
return useSyncExternalStore(playhead.subscribe, playhead.getSnapshot, playhead.getSnapshot);
|
|
@@ -91,12 +82,11 @@ function usePlayhead(player) {
|
|
|
91
82
|
//#region src/ui/use-motion-player.ts
|
|
92
83
|
/**
|
|
93
84
|
* Sessions this hook has disposed. React can replay a child's effects with the
|
|
94
|
-
* `session` it last rendered after this hook's cleanup
|
|
95
|
-
* boundary
|
|
96
|
-
* before binding to the one it was handed.
|
|
85
|
+
* `session` it last rendered after this hook's cleanup ran (a suspended
|
|
86
|
+
* boundary revealed, StrictMode), so a stage asks here before binding.
|
|
97
87
|
*/
|
|
98
88
|
var disposedSessions = /* @__PURE__ */ new WeakSet();
|
|
99
|
-
/** @internal
|
|
89
|
+
/** @internal Not exported from the package. */
|
|
100
90
|
function isSessionDisposed(session) {
|
|
101
91
|
return disposedSessions.has(session);
|
|
102
92
|
}
|
|
@@ -144,7 +134,6 @@ function useMotionPlayer(options) {
|
|
|
144
134
|
if (viewport.width !== resolvedViewport.width || viewport.height !== resolvedViewport.height) setViewport(resolvedViewport);
|
|
145
135
|
const hasDocument = document !== void 0;
|
|
146
136
|
const [session, setSession] = useState(null);
|
|
147
|
-
/** Created once; stable for the hook's life, so `usePlayhead` never resubscribes. */
|
|
148
137
|
const [playhead] = useState(createPlayheadStore);
|
|
149
138
|
const [isPlaying, setIsPlaying] = useState(false);
|
|
150
139
|
const [speed, setSpeedState] = useState(options.speed ?? 1);
|
|
@@ -166,10 +155,9 @@ function useMotionPlayer(options) {
|
|
|
166
155
|
const fpsRef = useRef(fps);
|
|
167
156
|
const speedRef = useRef(speed);
|
|
168
157
|
/**
|
|
169
|
-
* What the transport
|
|
170
|
-
* only
|
|
171
|
-
*
|
|
172
|
-
* batch (`seek` then `play`).
|
|
158
|
+
* What the transport was told to do, ahead of the next render. State shows
|
|
159
|
+
* only the last value a batch settled on, so it can disagree with the
|
|
160
|
+
* controller inside one batch (`seek` then `play`).
|
|
173
161
|
*/
|
|
174
162
|
const playingRef = useRef(false);
|
|
175
163
|
useEffect(() => {
|
|
@@ -188,23 +176,14 @@ function useMotionPlayer(options) {
|
|
|
188
176
|
if (errors.length > 0) setErrors(NO_ERRORS);
|
|
189
177
|
}
|
|
190
178
|
}
|
|
191
|
-
/**
|
|
192
|
-
* Pull what the controller now knows: timeline length, errors, progress.
|
|
193
|
-
* Runs on every swap, so it keeps whatever did not change — a fresh array or
|
|
194
|
-
* object here is a new `Player` for every consumer on every edit.
|
|
195
|
-
*/
|
|
179
|
+
/** Pulls duration, errors and progress off the controller, keeping what did not change: a fresh array or object is a new `Player` on every edit. */
|
|
196
180
|
const sync = useCallback((pc) => {
|
|
197
181
|
setDuration(pc.totalDuration);
|
|
198
182
|
setErrors(errorsFrom(pc.buildErrors));
|
|
199
183
|
const progress = precompProgressOf(pc.precomp);
|
|
200
184
|
setPrecomp((held) => samePrecomp(held, progress) ? held : progress);
|
|
201
185
|
}, []);
|
|
202
|
-
/**
|
|
203
|
-
* Move the playhead and repaint, with the loading flag the UI paces off.
|
|
204
|
-
*
|
|
205
|
-
* Created once so every caller — the transport, the reconcile effect and
|
|
206
|
-
* the first paint after a session opens — shares one seek discipline.
|
|
207
|
-
*/
|
|
186
|
+
/** One instance, so the transport, the reconcile effect and a session's first paint share one seek discipline. */
|
|
208
187
|
const [seekTo] = useState(() => (frame) => {
|
|
209
188
|
const pc = controllerRef.current;
|
|
210
189
|
if (!pc) return Promise.resolve(false);
|
|
@@ -398,44 +377,21 @@ function useMotionPlayer(options) {
|
|
|
398
377
|
}
|
|
399
378
|
//#endregion
|
|
400
379
|
//#region src/ui/stage.tsx
|
|
401
|
-
/**
|
|
402
|
-
* What every stage that doesn't ask for a view gets: the whole frame, 1:1.
|
|
403
|
-
*
|
|
404
|
-
* A shared frozen object rather than a literal, so the view effect's dependency
|
|
405
|
-
* on its fields is stable across renders for the overwhelming majority of
|
|
406
|
-
* stages, which never pass `view` at all.
|
|
407
|
-
*/
|
|
408
380
|
var IDENTITY_VIEW = Object.freeze({
|
|
409
381
|
zoom: 1,
|
|
410
382
|
x: 0,
|
|
411
383
|
y: 0
|
|
412
384
|
});
|
|
413
385
|
/**
|
|
414
|
-
* A canvas bound to a {@link Player}'s session.
|
|
415
|
-
*
|
|
416
|
-
* The stage owns how the frame is rasterized — resolution, view, clipping — and
|
|
417
|
-
* nothing about what is in it or when. A session drives **one** surface, so one
|
|
418
|
-
* stage per player: a second would take the surface from the first.
|
|
386
|
+
* A canvas bound to a {@link Player}'s session. One stage per player: a session
|
|
387
|
+
* drives one surface, and a second stage would take it from the first.
|
|
419
388
|
*/
|
|
420
389
|
function MotionStage({ player, renderScale = 1, surfaceSize, view, clipToFrame, frameBackground, className, style }) {
|
|
421
390
|
const canvasRef = useRef(null);
|
|
422
391
|
const { session } = player;
|
|
423
392
|
const viewport = session?.viewport ?? player.viewport;
|
|
424
|
-
/**
|
|
425
|
-
* The canvas's backing store, in device pixels. `viewport × renderScale` in
|
|
426
|
-
* the default case, where the canvas *is* the frame; with `surfaceSize` it
|
|
427
|
-
* is the viewing area instead.
|
|
428
|
-
*
|
|
429
|
-
* Floored at 1 so a degenerate scale can't ask the renderer for a zero-sized
|
|
430
|
-
* surface, which fails the surface creation outright.
|
|
431
|
-
*/
|
|
432
393
|
const bufferWidth = Math.max(1, Math.round((surfaceSize?.width ?? viewport.width) * renderScale));
|
|
433
394
|
const bufferHeight = Math.max(1, Math.round((surfaceSize?.height ?? viewport.height) * renderScale));
|
|
434
|
-
/**
|
|
435
|
-
* The view transform to draw with, and the frame to clip and anchor against.
|
|
436
|
-
* Only meaningful together, so they resolve in one place: no `surfaceSize`
|
|
437
|
-
* means the canvas is the frame, and both revert to identity.
|
|
438
|
-
*/
|
|
439
395
|
const activeView = surfaceSize && view ? view : IDENTITY_VIEW;
|
|
440
396
|
const activeFrame = surfaceSize && view ? viewport : null;
|
|
441
397
|
const activeClipToFrame = surfaceSize && view ? clipToFrame ?? true : true;
|
|
@@ -444,14 +400,6 @@ function MotionStage({ player, renderScale = 1, surfaceSize, view, clipToFrame,
|
|
|
444
400
|
const frameRectRef = useRef(activeFrame);
|
|
445
401
|
const clipToFrameRef = useRef(activeClipToFrame);
|
|
446
402
|
const frameBackgroundRef = useRef(activeFrameBackground);
|
|
447
|
-
/**
|
|
448
|
-
* The live render context.
|
|
449
|
-
*
|
|
450
|
-
* Held here rather than reached through `player.session` at each use because
|
|
451
|
-
* it is mutable external state — a GPU context whose knobs are written, not
|
|
452
|
-
* a value derived from a prop — and writing through the prop is what the
|
|
453
|
-
* immutability lint is there to catch everywhere it *isn't* one of these.
|
|
454
|
-
*/
|
|
455
403
|
const ctxRef = useRef(null);
|
|
456
404
|
useEffect(() => {
|
|
457
405
|
viewRef.current = activeView;
|
|
@@ -460,19 +408,6 @@ function MotionStage({ player, renderScale = 1, surfaceSize, view, clipToFrame,
|
|
|
460
408
|
frameBackgroundRef.current = activeFrameBackground;
|
|
461
409
|
ctxRef.current = session ? session.surface : null;
|
|
462
410
|
});
|
|
463
|
-
/**
|
|
464
|
-
* Bind the surface, and rebuild it when the backing store changes.
|
|
465
|
-
*
|
|
466
|
-
* The order matters and is why this is an effect rather than a callback:
|
|
467
|
-
* React has already written the canvas's new `width`/`height` by the time
|
|
468
|
-
* effects run, and the renderer reads exactly those when it builds the surface
|
|
469
|
-
* (`MakeOnScreenGLSurface(ctx, canvas.width, canvas.height)`). Mounting
|
|
470
|
-
* before the resize would produce a surface of the previous size.
|
|
471
|
-
*
|
|
472
|
-
* `repaint()` afterwards because a new surface starts blank and the clock is
|
|
473
|
-
* not necessarily running to fill it — a paused editor would otherwise show
|
|
474
|
-
* black until something else moved.
|
|
475
|
-
*/
|
|
476
411
|
useEffect(() => {
|
|
477
412
|
const canvas = canvasRef.current;
|
|
478
413
|
const ctx = ctxRef.current;
|
|
@@ -490,13 +425,6 @@ function MotionStage({ player, renderScale = 1, surfaceSize, view, clipToFrame,
|
|
|
490
425
|
bufferWidth,
|
|
491
426
|
bufferHeight
|
|
492
427
|
]);
|
|
493
|
-
/**
|
|
494
|
-
* Apply {@link MotionStageProps.view} — a repaint and nothing more.
|
|
495
|
-
*
|
|
496
|
-
* Depends on the fields rather than the object so a caller passing a fresh
|
|
497
|
-
* `{zoom, x, y}` each render — which is every caller, since it comes from a
|
|
498
|
-
* gesture — doesn't repaint on renders where the view didn't move.
|
|
499
|
-
*/
|
|
500
428
|
useEffect(() => {
|
|
501
429
|
const ctx = ctxRef.current;
|
|
502
430
|
if (!session || !ctx || isSessionDisposed(session)) return;
|
|
@@ -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());\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,SAAQ;GACV,QAAQ;GACR,IAAI,CAAC,MAAM;IACP,KAAK,QAAQ;IACb;GACJ;GACA,UAAU,IAAI;EAClB,CAAC,EACA,OAAM,UAAS;GACZ,IAAI,MAAM,CAAC,WAAW,WAAW,UAAU,KAAK;EACpD,CAAC;EAEL,aAAa;GACT,OAAO;GACP,OAAO,QAAQ;GACf,UAAU,IAAI;EAClB;CAGJ,GAAG,IAAI;CAEP,OAAO;AACX;;;ACnEA,SAAgB,sBAAqC;CACjD,IAAI,QAAQ;CACZ,MAAM,4BAAY,IAAI,IAAgB;CACtC,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,CAAC,OAAO,kBAAkB,OAAO,GAAG;EAC/D,IAAI,aAAa;EACjB,IAAI,OAAO,QAAQ;EACnB,IAAI,QAAQ,aAAa;EACzB,IAAI,cAAc,eAAe;EACjC,IAAI,kBAAkB,mBAAmB;EAKzC,IAAI,MAAM,MAAM;EAChB,QAAQ,WAAW,QAAQ;CAC/B,GAAG;EAAC;EAAS;EAAa;EAAa;CAAY,CAAC;;;;;;;;CASpD,gBAAgB;EACZ,MAAM,MAAM,OAAO;EACnB,IAAI,CAAC,WAAW,CAAC,OAAO,kBAAkB,OAAO,GAAG;EACpD,IAAI,OAAO;GAAE,MAAM,WAAW;GAAM,GAAG,WAAW;GAAG,GAAG,WAAW;EAAE;EACrE,IAAI,QAAQ;EACZ,IAAI,cAAc;EAClB,IAAI,kBAAkB;EACtB,QAAQ,WAAW,QAAQ;CAE/B,GAAG;EACC;EACA,WAAW;EACX,WAAW;EACX,WAAW;EACX,aAAa;EACb,aAAa;EACb;EACA;CACJ,CAAC;CAED,OACI,oBAAC,OAAD;EAAgB;EAAW,OAAO;GAAE,UAAU;GAAY,OAAO;GAAQ,QAAQ;GAAQ,GAAG;EAAM;YAC9F,oBAAC,UAAD;GACI,KAAK;GAIL,OAAO;GACP,QAAQ;GACR,OAAO;IACH,SAAS,UAAU,UAAU;IAC7B,GAAI,cACE;KAiBI,UAAU;KACV,MAAM;KACN,KAAK;KACL,OAAO,GAAG,YAAY,MAAM;KAC5B,QAAQ,GAAG,YAAY,OAAO;KAC9B,WAAW;IACf,IACA;KAAE,OAAO;KAAQ,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 as `useEffect` does.\n * The default, `[]`, builds it once. List only what makes a *different*\n * engine (node types, the wasm URL): the latest `create` is always the one\n * called, so its closure is not a dependency.\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, `null` until it arrives, and disposes it when it is no\n * longer wanted. What to build is the factory's job: nothing here imports a\n * platform.\n *\n * ```tsx\n * const engine = useEngine(() => createBrowserEngine());\n * const player = useMotionPlayer({ engine, document: doc });\n * ```\n *\n * An unmount while the factory was still pending (StrictMode does this on every\n * dev mount) frees the engine the moment it lands; a change in `deps` disposes\n * 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 renderer. Anything that must hold before a player sees the engine, such as\n * `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: a frame written at clock rate through\n * `useState` would re-render the player's owner faster than the project's frame\n * rate, and nothing in a render depends on it (the controller paints straight\n * onto the canvas). Only components that 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/** Subscribe *this* component to the playhead. Takes `{ playhead }` rather than `Player` to avoid an import cycle with `use-motion-player`. */\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/** Background asset discovery: only frame-0 tracks are discovered before mount, the rest stream in. The timeline's length never waits on it. */\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 ran (a suspended\n * boundary revealed, StrictMode), so a stage asks here before binding.\n */\nconst disposedSessions = new WeakSet<Session>();\n\n/** @internal 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. Nullable because building one\n * is async ({@link useEngine}): the player no-ops until it arrives.\n *\n * Create it once and share it: it holds the renderer and the exporter, so a\n * fresh one per render rebuilds the renderer behind every player on it.\n * Compared by identity; a different engine is a full rebuild.\n */\n engine: Engine | null | undefined;\n /**\n * What to play; nothing opens until there is one. A project document carries\n * its own viewport, fps, theme and tracks; a scene document (still or\n * composition) carries none, so `viewport` and `fps` come from here or the\n * engine.\n *\n * Content-diffed, identity first: a new document is reconciled onto the\n * running session, each track patched in place and rebuilt only when it\n * cannot be. Treat documents as immutable: an in-place edit is not seen.\n *\n * A new document keeps the player's place (the playhead is clamped to a\n * shorter timeline, playback carries on). Seek or pause yourself when a swap\n * 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 has\n * been painted (clock, seek or document swap).\n *\n * Not the playhead, which reports where the clock is: a seek is async, so the\n * number can move before the canvas does. Use it to keep an overlay in step\n * with the pixels, and keep it cheap: it runs on the render loop. Read through\n * a ref, so changing it costs nothing.\n */\n onFramePainted?: (frame: number) => void;\n}\n\n/** A document's transport and its session, with no DOM. Two calls to {@link useMotionPlayer} share only the engine. */\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 /** Pauses, then seeks. 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 // Points below 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 // Document, then options, then engine. Resolved during render, before any\n // session exists, so a stage can size its canvas on the first pass.\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 would otherwise\n // 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 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 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 was told to do, ahead of the next render. State shows\n * only the last value a batch settled on, so it can disagree with the\n * controller inside one 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 errors (the reconcile effect re-reads both,\n // so an unfixed error never blinks out); only losing the document stops it,\n // during render 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 /** Pulls duration, errors and progress off the controller, keeping what did not change: a fresh array or object is a new `Player` on every edit. */\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 /** One instance, so the transport, the reconcile effect and a session's first paint share one seek discipline. */\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 // A superseded seek still resolves (its generation guard bailed in the\n // controller) but never painted, so only the newest may clear `loading`:\n // consumers pace scrubbing off that edge.\n const token = ++seekTokenRef.current;\n setLoading(true);\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 afterwards, so this hook owns no 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 // Asks the controller: a swap can change the length after 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 disposedSessions.add(opened);\n opened.dispose();\n };\n // `document` is deliberately absent (only whether there is one): the effect\n // below reconciles a new one onto the live session. Everything listed\n // needs a rebuild: a different engine is a different renderer, and a live\n // surface cannot change 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 running session. Skipped on the pass\n // that opened it, which already holds this document.\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` paints the current frame once its assets load, and a\n // 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 // Parks a new session on the frame the playhead holds, so a rebuild keeps its\n // place. The seek pauses the clock the effect above just started, so a player\n // that was playing resumes once the park lands (assets loaded, so the first\n // ticks draw rather than catch up), unless a newer seek or a pause moved the\n // transport meanwhile.\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: every action reads the controller through a ref, so a re-render\n // never invalidates a handler a child holds.\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 state: in one batch a `seek` and\n // a `play` cancel out in state, so the `isPlaying` effect never re-runs\n // though the seek already paused the clock.\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/** Core compiles without the DOM lib, so `RenderSurface.mount` takes `unknown`; narrowed here, where `HTMLCanvasElement` exists. */\ntype StageRenderContext = Omit<EngineRenderContext, \"mount\"> & {\n mount(canvas: HTMLCanvasElement): void;\n};\n\nconst IDENTITY_VIEW = Object.freeze({ zoom: 1, x: 0, y: 0 });\n\nexport interface MotionStageProps {\n player: Player;\n /**\n * Device pixels rasterized per viewport unit. Defaults to `1`. Not a zoom or\n * a crop: the scene's coordinate space is unchanged and CSS scales the canvas\n * back to its box. `<1` suits a preview shown far smaller than the output size.\n *\n * Every change re-creates the GPU surface, dropping texture-backed images\n * (decoded video frames, 3D composites; they re-upload on demand), so quantize\n * to a few steps and never drive it from a resize observer. Prefer scales that\n * keep both dimensions whole: `pixelRatio` is one number, so uneven rounding\n * shifts the frame's centre by up to half a device pixel.\n *\n * `player.screenshot()` returns the surface's size, so it is scaled too.\n */\n renderScale?: number;\n /**\n * The canvas's own size in CSS pixels, when it is not the frame. Omitted, the\n * canvas is the frame: `viewport × renderScale`, stretched over its box.\n *\n * Supplied together with {@link view}, the canvas becomes a window onto the\n * frame: it takes the size of the area shown, `renderScale` means device\n * pixels per CSS pixel, and only what is on screen is rasterized, so zooming\n * in stays sharp. It re-creates the surface like `renderScale`: quantize it.\n */\n surfaceSize?: Size2D;\n /**\n * Pan and zoom applied to the render itself; requires {@link surfaceSize}.\n * `zoom` multiplies scene units; `x`/`y` offset the frame's centre in CSS\n * pixels, positive `y` downwards (a CSS translate).\n *\n * A change costs a repaint and nothing else. A CSS transform could not add\n * 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. Requires {@link surfaceSize} and\n * {@link view}. Defaults to `true`; off lets a node parked past the edge\n * rasterize into the rest of the surface.\n */\n clipToFrame?: boolean;\n /**\n * Defaults to `\"black\"`. `\"transparent\"` leaves undrawn frame pixels\n * unpainted so the host's backdrop (a checkerboard) shows through. Requires\n * {@link surfaceSize} and {@link view}.\n */\n frameBackground?: \"black\" | \"transparent\";\n className?: string;\n style?: CSSProperties;\n}\n\n/**\n * A canvas bound to a {@link Player}'s session. One stage per player: a session\n * drives one surface, and a second stage would take it 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 // Floored at 1: a zero-sized surface fails creation outright.\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 // Without both `surfaceSize` and `view` the canvas is the frame, so all four revert to defaults.\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 // A ref because the context is mutable external state whose knobs are\n // written; writing through the `player` prop trips the immutability lint.\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 // Bind the surface and rebuild it when the backing store changes. An effect,\n // not a callback, because React has written the canvas's new `width`/`height`\n // by the time effects run and the renderer reads them when it builds the\n // surface: mounting before the resize would build the previous size.\n // `repaint()` because a new surface starts blank and a paused clock would not\n // fill it.\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 // Detaches the old surface first, which drops the texture-backed images\n // that belong to it.\n ctx.mount(canvas);\n session.controller.repaint();\n }, [session, renderScale, bufferWidth, bufferHeight]);\n\n // Keyed on the view's fields, not the object: callers pass a fresh\n // `{zoom, x, y}` every render, which would repaint every render.\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 width={bufferWidth}\n height={bufferHeight}\n style={{\n display: session ? \"block\" : \"none\",\n ...(surfaceSize\n ? {\n // `surfaceSize` is honoured literally, not stretched\n // to the box: it is quantized, so it is usually a\n // little larger than the box and a different shape,\n // and stretching would squash one axis.\n //\n // Centred because `executePass` puts the scene origin\n // at the surface's centre, so this lands the frame\n // where the layout says; the spare pixels hang off\n // all four edges and the parent clips them.\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":";;;;A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AAkB;EACtB,QAAQ,WAAW,QAAQ;CAE/B,GAAG;EACC;EACA,WAAW;EACX,WAAW;EACX,WAAW;EACX,aAAa;EACb,aAAa;EACb;EACA;CACJ,CAAC;CAED,OACI,oBAAC,OAAD;EAAgB;EAAW,OAAO;GAAE,UAAU;GAAY,OAAO;GAAQ,QAAQ;GAAQ,GAAG;EAAM;YAC9F,oBAAC,UAAD;GACI,KAAK;GACL,OAAO;GACP,QAAQ;GACR,OAAO;IACH,SAAS,UAAU,UAAU;IAC7B,GAAI,cACE;KAUI,UAAU;KACV,MAAM;KACN,KAAK;KACL,OAAO,GAAG,YAAY,MAAM;KAC5B,QAAQ,GAAG,YAAY,OAAO;KAC9B,WAAW;IACf,IACA;KAAE,OAAO;KAAQ,QAAQ;IAAO;GAC1C;EACH,CAAA;CACA,CAAA;AAEb"}
|
package/dist/ui/playhead.d.ts
CHANGED
|
@@ -1,11 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The playhead, held outside React
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
* project's own frame rate. Nothing in a render depends on it: the controller
|
|
7
|
-
* paints straight onto the canvas and React is not involved. So the number
|
|
8
|
-
* lives here, and only the components that actually display it subscribe.
|
|
2
|
+
* The playhead, held outside React: a frame written at clock rate through
|
|
3
|
+
* `useState` would re-render the player's owner faster than the project's frame
|
|
4
|
+
* rate, and nothing in a render depends on it (the controller paints straight
|
|
5
|
+
* onto the canvas). Only components that display it subscribe.
|
|
9
6
|
*/
|
|
10
7
|
export interface PlayheadStore {
|
|
11
8
|
subscribe(onChange: () => void): () => void;
|
|
@@ -14,12 +11,7 @@ export interface PlayheadStore {
|
|
|
14
11
|
set(frame: number): void;
|
|
15
12
|
}
|
|
16
13
|
export declare function createPlayheadStore(): PlayheadStore;
|
|
17
|
-
/**
|
|
18
|
-
* Subscribe *this* component to the playhead.
|
|
19
|
-
*
|
|
20
|
-
* Typed structurally rather than against `Player` so the store and the hook
|
|
21
|
-
* that reads it don't import each other.
|
|
22
|
-
*/
|
|
14
|
+
/** Subscribe *this* component to the playhead. Takes `{ playhead }` rather than `Player` to avoid an import cycle with `use-motion-player`. */
|
|
23
15
|
export declare function usePlayhead(player: {
|
|
24
16
|
playhead: PlayheadStore;
|
|
25
17
|
}): number;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"playhead.d.ts","sourceRoot":"","sources":["../../src/ui/playhead.ts"],"names":[],"mappings":"AAEA
|
|
1
|
+
{"version":3,"file":"playhead.d.ts","sourceRoot":"","sources":["../../src/ui/playhead.ts"],"names":[],"mappings":"AAEA;;;;;GAKG;AACH,MAAM,WAAW,aAAa;IAC1B,SAAS,CAAC,QAAQ,EAAE,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC;IAC5C,WAAW,IAAI,MAAM,CAAC;IACtB,8DAA8D;IAC9D,GAAG,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;CAC5B;AAED,wBAAgB,mBAAmB,IAAI,aAAa,CAiBnD;AAED,+IAA+I;AAC/I,wBAAgB,WAAW,CAAC,MAAM,EAAE;IAAE,QAAQ,EAAE,aAAa,CAAA;CAAE,GAAG,MAAM,CAGvE"}
|
package/dist/ui/stage.d.ts
CHANGED
|
@@ -2,62 +2,38 @@ import { CSSProperties } from 'react';
|
|
|
2
2
|
import { Size2D } from '@motionscript/core';
|
|
3
3
|
import { Player } from './use-motion-player';
|
|
4
4
|
export interface MotionStageProps {
|
|
5
|
-
/** The player whose session this stage draws. */
|
|
6
5
|
player: Player;
|
|
7
6
|
/**
|
|
8
|
-
* Device pixels
|
|
7
|
+
* Device pixels rasterized per viewport unit. Defaults to `1`. Not a zoom or
|
|
8
|
+
* a crop: the scene's coordinate space is unchanged and CSS scales the canvas
|
|
9
|
+
* back to its box. `<1` suits a preview shown far smaller than the output size.
|
|
9
10
|
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
11
|
+
* Every change re-creates the GPU surface, dropping texture-backed images
|
|
12
|
+
* (decoded video frames, 3D composites; they re-upload on demand), so quantize
|
|
13
|
+
* to a few steps and never drive it from a resize observer. Prefer scales that
|
|
14
|
+
* keep both dimensions whole: `pixelRatio` is one number, so uneven rounding
|
|
15
|
+
* shifts the frame's centre by up to half a device pixel.
|
|
13
16
|
*
|
|
14
|
-
*
|
|
15
|
-
* the project's output size: a 1920×1080 project in a 700px-wide panel
|
|
16
|
-
* rasterizes roughly seven times the pixels anyone can see. `0.5` there is a
|
|
17
|
-
* quarter of the fill, the shader work and the effect offscreens.
|
|
18
|
-
*
|
|
19
|
-
* Two things to know before animating it:
|
|
20
|
-
*
|
|
21
|
-
* - **Every change re-creates the GPU surface**, which drops the storage
|
|
22
|
-
* adapter's texture-backed images (decoded video frames, 3D composites;
|
|
23
|
-
* still images survive) and asks for a fresh GL context. Quantize to a few
|
|
24
|
-
* steps and let it settle — never drive it from a resize observer.
|
|
25
|
-
* - **Prefer scales that keep both dimensions whole.** `pixelRatio` is one
|
|
26
|
-
* uniform number, so a scale that rounds differently on each axis shifts
|
|
27
|
-
* the frame's centre by up to half a device pixel.
|
|
28
|
-
*
|
|
29
|
-
* A snapshot from `player.screenshot()` comes back at the surface's size, so
|
|
30
|
-
* it is scaled too — render at `1` if you need full resolution out of it.
|
|
17
|
+
* `player.screenshot()` returns the surface's size, so it is scaled too.
|
|
31
18
|
*/
|
|
32
19
|
renderScale?: number;
|
|
33
20
|
/**
|
|
34
|
-
* The canvas's own size in CSS pixels, when it is
|
|
35
|
-
*
|
|
36
|
-
* Omitted — the default — the canvas is the frame: sized `viewport ×
|
|
37
|
-
* renderScale` and stretched over its box by CSS, which is what every
|
|
38
|
-
* export, thumbnail and plain player wants.
|
|
21
|
+
* The canvas's own size in CSS pixels, when it is not the frame. Omitted, the
|
|
22
|
+
* canvas is the frame: `viewport × renderScale`, stretched over its box.
|
|
39
23
|
*
|
|
40
|
-
* Supplied
|
|
41
|
-
*
|
|
42
|
-
*
|
|
43
|
-
*
|
|
44
|
-
* That is what lets an editor zoom in without going soft or paying for the
|
|
45
|
-
* whole frame at the zoomed resolution.
|
|
46
|
-
*
|
|
47
|
-
* It re-creates the surface exactly as `renderScale` does, and wants the
|
|
48
|
-
* same treatment: quantize it and let it settle.
|
|
24
|
+
* Supplied together with {@link view}, the canvas becomes a window onto the
|
|
25
|
+
* frame: it takes the size of the area shown, `renderScale` means device
|
|
26
|
+
* pixels per CSS pixel, and only what is on screen is rasterized, so zooming
|
|
27
|
+
* in stays sharp. It re-creates the surface like `renderScale`: quantize it.
|
|
49
28
|
*/
|
|
50
29
|
surfaceSize?: Size2D;
|
|
51
30
|
/**
|
|
52
|
-
*
|
|
53
|
-
*
|
|
31
|
+
* Pan and zoom applied to the render itself; requires {@link surfaceSize}.
|
|
54
32
|
* `zoom` multiplies scene units; `x`/`y` offset the frame's centre in CSS
|
|
55
|
-
* pixels, positive `y` downwards
|
|
56
|
-
* translate, so a preview can hand over the pan it was already computing.
|
|
33
|
+
* pixels, positive `y` downwards (a CSS translate).
|
|
57
34
|
*
|
|
58
|
-
*
|
|
59
|
-
*
|
|
60
|
-
* transform, which cannot add resolution it was not rasterized with.
|
|
35
|
+
* A change costs a repaint and nothing else. A CSS transform could not add
|
|
36
|
+
* resolution it was not rasterized with.
|
|
61
37
|
*/
|
|
62
38
|
view?: {
|
|
63
39
|
zoom: number;
|
|
@@ -65,34 +41,23 @@ export interface MotionStageProps {
|
|
|
65
41
|
y: number;
|
|
66
42
|
};
|
|
67
43
|
/**
|
|
68
|
-
* Whether the frame's edge bounds what draws
|
|
69
|
-
*
|
|
70
|
-
*
|
|
71
|
-
*
|
|
72
|
-
* Off lets a node parked past the frame's edge rasterize into the rest of
|
|
73
|
-
* the surface instead of being discarded — for a host that wants to show,
|
|
74
|
-
* faded, what a node placed there while animating in or out.
|
|
44
|
+
* Whether the frame's edge bounds what draws. Requires {@link surfaceSize} and
|
|
45
|
+
* {@link view}. Defaults to `true`; off lets a node parked past the edge
|
|
46
|
+
* rasterize into the rest of the surface.
|
|
75
47
|
*/
|
|
76
48
|
clipToFrame?: boolean;
|
|
77
49
|
/**
|
|
78
|
-
*
|
|
79
|
-
*
|
|
80
|
-
*
|
|
81
|
-
* whatever the host renders behind the canvas shows through — a
|
|
82
|
-
* checkerboard, for an editor that has to distinguish "no scene covers this"
|
|
83
|
-
* from "a scene covers it in black". Requires {@link surfaceSize} and
|
|
84
|
-
* {@link view}, the same way {@link clipToFrame} does.
|
|
50
|
+
* Defaults to `"black"`. `"transparent"` leaves undrawn frame pixels
|
|
51
|
+
* unpainted so the host's backdrop (a checkerboard) shows through. Requires
|
|
52
|
+
* {@link surfaceSize} and {@link view}.
|
|
85
53
|
*/
|
|
86
54
|
frameBackground?: "black" | "transparent";
|
|
87
55
|
className?: string;
|
|
88
56
|
style?: CSSProperties;
|
|
89
57
|
}
|
|
90
58
|
/**
|
|
91
|
-
* A canvas bound to a {@link Player}'s session.
|
|
92
|
-
*
|
|
93
|
-
* The stage owns how the frame is rasterized — resolution, view, clipping — and
|
|
94
|
-
* nothing about what is in it or when. A session drives **one** surface, so one
|
|
95
|
-
* stage per player: a second would take the surface from the first.
|
|
59
|
+
* A canvas bound to a {@link Player}'s session. One stage per player: a session
|
|
60
|
+
* drives one surface, and a second stage would take it from the first.
|
|
96
61
|
*/
|
|
97
62
|
export declare function MotionStage({ player, renderScale, surfaceSize, view, clipToFrame, frameBackground, className, style, }: MotionStageProps): import("react").JSX.Element;
|
|
98
63
|
//# sourceMappingURL=stage.d.ts.map
|
package/dist/ui/stage.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stage.d.ts","sourceRoot":"","sources":["../../src/ui/stage.tsx"],"names":[],"mappings":"AAAA,OAAO,EAAqB,KAAK,aAAa,EAAE,MAAM,OAAO,CAAC;AAE9D,OAAO,KAAK,EAAuB,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAEtE,OAAO,EAAqB,KAAK,MAAM,EAAE,MAAM,qBAAqB,CAAC;
|
|
1
|
+
{"version":3,"file":"stage.d.ts","sourceRoot":"","sources":["../../src/ui/stage.tsx"],"names":[],"mappings":"AAAA,OAAO,EAAqB,KAAK,aAAa,EAAE,MAAM,OAAO,CAAC;AAE9D,OAAO,KAAK,EAAuB,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAEtE,OAAO,EAAqB,KAAK,MAAM,EAAE,MAAM,qBAAqB,CAAC;AASrE,MAAM,WAAW,gBAAgB;IAC7B,MAAM,EAAE,MAAM,CAAC;IACf;;;;;;;;;;;;OAYG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;;;;;;OAQG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;;;;;OAOG;IACH,IAAI,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,CAAC,EAAE,MAAM,CAAC;QAAC,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;IAC9C;;;;OAIG;IACH,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB;;;;OAIG;IACH,eAAe,CAAC,EAAE,OAAO,GAAG,aAAa,CAAC;IAC1C,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,aAAa,CAAC;CACzB;AAED;;;GAGG;AACH,wBAAgB,WAAW,CAAC,EACxB,MAAM,EACN,WAAe,EACf,WAAW,EACX,IAAI,EACJ,WAAW,EACX,eAAe,EACf,SAAS,EACT,KAAK,GACR,EAAE,gBAAgB,+BA4GlB"}
|
package/dist/ui/use-engine.d.ts
CHANGED
|
@@ -2,38 +2,32 @@ import { DependencyList } from 'react';
|
|
|
2
2
|
import { Engine } from '@motionscript/core';
|
|
3
3
|
export interface UseEngineOptions {
|
|
4
4
|
/**
|
|
5
|
-
* Rebuild the engine when any of these change, compared
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
* called, so an inline arrow does not rebuild anything. List only what
|
|
10
|
-
* makes a *different* engine, such as the node types or the wasm URL.
|
|
5
|
+
* Rebuild the engine when any of these change, compared as `useEffect` does.
|
|
6
|
+
* The default, `[]`, builds it once. List only what makes a *different*
|
|
7
|
+
* engine (node types, the wasm URL): the latest `create` is always the one
|
|
8
|
+
* called, so its closure is not a dependency.
|
|
11
9
|
*/
|
|
12
10
|
deps?: DependencyList;
|
|
13
11
|
/** Called when `create` rejects or throws. Defaults to `console.error`. */
|
|
14
12
|
onError?: (error: unknown) => void;
|
|
15
13
|
}
|
|
16
14
|
/**
|
|
17
|
-
* Builds an engine once,
|
|
18
|
-
*
|
|
15
|
+
* Builds an engine once, `null` until it arrives, and disposes it when it is no
|
|
16
|
+
* longer wanted. What to build is the factory's job: nothing here imports a
|
|
17
|
+
* platform.
|
|
19
18
|
*
|
|
20
19
|
* ```tsx
|
|
21
20
|
* const engine = useEngine(() => createBrowserEngine());
|
|
22
21
|
* const player = useMotionPlayer({ engine, document: doc });
|
|
23
22
|
* ```
|
|
24
23
|
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
*
|
|
24
|
+
* An unmount while the factory was still pending (StrictMode does this on every
|
|
25
|
+
* dev mount) frees the engine the moment it lands; a change in `deps` disposes
|
|
26
|
+
* the old one and returns `null` until the new one is ready.
|
|
28
27
|
*
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
* disposes the old one and returns `null` until the new one is ready.
|
|
33
|
-
*
|
|
34
|
-
* Call it once and hand the engine down. A second call is a second wasm module
|
|
35
|
-
* and a second GL stack. Anything that must be true before a player sees the
|
|
36
|
-
* engine, such as `setManifest`, belongs in `create`, not in an effect beside it.
|
|
28
|
+
* Call it once and hand the engine down: a second call is a second wasm module
|
|
29
|
+
* and renderer. Anything that must hold before a player sees the engine, such as
|
|
30
|
+
* `setManifest`, belongs in `create`, not in an effect beside it.
|
|
37
31
|
*/
|
|
38
32
|
export declare function useEngine<E extends Engine = Engine>(create: () => E | Promise<E>, options?: UseEngineOptions): E | null;
|
|
39
33
|
//# sourceMappingURL=use-engine.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-engine.d.ts","sourceRoot":"","sources":["../../src/ui/use-engine.ts"],"names":[],"mappings":"AAAA,OAAO,EAA+B,KAAK,cAAc,EAAE,MAAM,OAAO,CAAC;AAEzE,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAEjD,MAAM,WAAW,gBAAgB;IAC7B
|
|
1
|
+
{"version":3,"file":"use-engine.d.ts","sourceRoot":"","sources":["../../src/ui/use-engine.ts"],"names":[],"mappings":"AAAA,OAAO,EAA+B,KAAK,cAAc,EAAE,MAAM,OAAO,CAAC;AAEzE,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAEjD,MAAM,WAAW,gBAAgB;IAC7B;;;;;OAKG;IACH,IAAI,CAAC,EAAE,cAAc,CAAC;IACtB,2EAA2E;IAC3E,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,CAAC;CACtC;AAMD;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,SAAS,CAAC,CAAC,SAAS,MAAM,GAAG,MAAM,EAC/C,MAAM,EAAE,MAAM,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,EAC5B,OAAO,GAAE,gBAAqB,GAC/B,CAAC,GAAG,IAAI,CAsCV"}
|
|
@@ -1,11 +1,6 @@
|
|
|
1
1
|
import { BuildError, Engine, NodeBox, NodeHandle, Node3DFrame, NodeOverride, NodeState, NodeTextLayout, ProjectDocument, ReparentPlacement, VisualDocument, Session, Size2D, TrackSpan, TreeState, Vector2, Vector3 } from '@motionscript/core';
|
|
2
2
|
import { PlayheadStore } from './playhead';
|
|
3
|
-
/**
|
|
4
|
-
* How far background discovery has got. Only the tracks on frame 0 are
|
|
5
|
-
* discovered before the player mounts; the rest stream in behind it (see
|
|
6
|
-
* `AssetTimeline.runAsync`). The timeline's length never waits on it — every track
|
|
7
|
-
* declares its own.
|
|
8
|
-
*/
|
|
3
|
+
/** Background asset discovery: only frame-0 tracks are discovered before mount, the rest stream in. The timeline's length never waits on it. */
|
|
9
4
|
export interface PrecompProgress {
|
|
10
5
|
/** Tracks discovered so far. */
|
|
11
6
|
discoveredTracks: number;
|
|
@@ -14,40 +9,31 @@ export interface PrecompProgress {
|
|
|
14
9
|
/** True once every track has been discovered. */
|
|
15
10
|
complete: boolean;
|
|
16
11
|
}
|
|
17
|
-
/** @internal
|
|
12
|
+
/** @internal Not exported from the package. */
|
|
18
13
|
export declare function isSessionDisposed(session: Session): boolean;
|
|
19
14
|
export interface MotionPlayerOptions {
|
|
20
15
|
/**
|
|
21
|
-
* The engine this player opens its session on.
|
|
16
|
+
* The engine this player opens its session on. Nullable because building one
|
|
17
|
+
* is async ({@link useEngine}): the player no-ops until it arrives.
|
|
22
18
|
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
* arrives, which is what keeps the hook out of a conditional.
|
|
27
|
-
*
|
|
28
|
-
* **Create it once, and share it.** It holds the renderer and the exporter, so
|
|
29
|
-
* a fresh one per render rebuilds the WebGL surface behind every player on
|
|
30
|
-
* it. Identity-compared: a different engine is a different renderer, and so
|
|
31
|
-
* a full rebuild.
|
|
19
|
+
* Create it once and share it: it holds the renderer and the exporter, so a
|
|
20
|
+
* fresh one per render rebuilds the renderer behind every player on it.
|
|
21
|
+
* Compared by identity; a different engine is a full rebuild.
|
|
32
22
|
*/
|
|
33
23
|
engine: Engine | null | undefined;
|
|
34
24
|
/**
|
|
35
|
-
* What to play
|
|
36
|
-
*
|
|
37
|
-
*
|
|
38
|
-
*
|
|
39
|
-
* clip and carries none of that, so `viewport` and `fps` must come from here
|
|
40
|
-
* or from the engine.
|
|
25
|
+
* What to play; nothing opens until there is one. A project document carries
|
|
26
|
+
* its own viewport, fps, theme and tracks; a scene document (still or
|
|
27
|
+
* composition) carries none, so `viewport` and `fps` come from here or the
|
|
28
|
+
* engine.
|
|
41
29
|
*
|
|
42
|
-
* Content-diffed,
|
|
43
|
-
*
|
|
44
|
-
*
|
|
45
|
-
* immutable — an edit made in place to one the player already holds is not
|
|
46
|
-
* seen.
|
|
30
|
+
* Content-diffed, identity first: a new document is reconciled onto the
|
|
31
|
+
* running session, each track patched in place and rebuilt only when it
|
|
32
|
+
* cannot be. Treat documents as immutable: an in-place edit is not seen.
|
|
47
33
|
*
|
|
48
|
-
* A new document keeps the player's place
|
|
49
|
-
*
|
|
50
|
-
*
|
|
34
|
+
* A new document keeps the player's place (the playhead is clamped to a
|
|
35
|
+
* shorter timeline, playback carries on). Seek or pause yourself when a swap
|
|
36
|
+
* means "start over".
|
|
51
37
|
*/
|
|
52
38
|
document?: ProjectDocument | VisualDocument;
|
|
53
39
|
/** Overrides the engine's, for a source that carries none. */
|
|
@@ -61,27 +47,17 @@ export interface MotionPlayerOptions {
|
|
|
61
47
|
/** Initial loop state. Change it later with {@link Player.setLoop}. */
|
|
62
48
|
loop?: boolean;
|
|
63
49
|
/**
|
|
64
|
-
* Called
|
|
65
|
-
*
|
|
50
|
+
* Called synchronously, on the same task as the draw, each time a frame has
|
|
51
|
+
* been painted (clock, seek or document swap).
|
|
66
52
|
*
|
|
67
|
-
* Not the playhead, which reports where the
|
|
68
|
-
*
|
|
69
|
-
*
|
|
70
|
-
*
|
|
71
|
-
* listener cheap: it runs on the render loop, before the browser has had a
|
|
72
|
-
* chance to composite.
|
|
73
|
-
*
|
|
74
|
-
* Read through a ref, so changing it costs nothing.
|
|
53
|
+
* Not the playhead, which reports where the clock is: a seek is async, so the
|
|
54
|
+
* number can move before the canvas does. Use it to keep an overlay in step
|
|
55
|
+
* with the pixels, and keep it cheap: it runs on the render loop. Read through
|
|
56
|
+
* a ref, so changing it costs nothing.
|
|
75
57
|
*/
|
|
76
58
|
onFramePainted?: (frame: number) => void;
|
|
77
59
|
}
|
|
78
|
-
/**
|
|
79
|
-
* One document, its transport, and the session driving it. No DOM.
|
|
80
|
-
*
|
|
81
|
-
* Hand it to a {@link MotionStage} to put pixels on screen. Two calls to
|
|
82
|
-
* {@link useMotionPlayer} produce two of these with nothing shared but the
|
|
83
|
-
* engine — separate playheads, clocks, audio devices and transports.
|
|
84
|
-
*/
|
|
60
|
+
/** A document's transport and its session, with no DOM. Two calls to {@link useMotionPlayer} share only the engine. */
|
|
85
61
|
export interface Player {
|
|
86
62
|
/** The live session, or `null` before the engine and a document arrive. */
|
|
87
63
|
readonly session: Session | null;
|
|
@@ -106,7 +82,7 @@ export interface Player {
|
|
|
106
82
|
play(): void;
|
|
107
83
|
pause(): void;
|
|
108
84
|
toggle(): void;
|
|
109
|
-
/**
|
|
85
|
+
/** Pauses, then seeks. Clamped to the timeline. */
|
|
110
86
|
seek(frame: number): void;
|
|
111
87
|
/** Seek relative to where the playhead is now. */
|
|
112
88
|
step(delta: number): void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-motion-player.d.ts","sourceRoot":"","sources":["../../src/ui/use-motion-player.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EACR,UAAU,EACV,MAAM,EACN,OAAO,EACP,UAAU,EACV,WAAW,EACX,YAAY,EACZ,SAAS,EACT,cAAc,EAGd,eAAe,EACf,iBAAiB,EACjB,cAAc,EACd,OAAO,EACP,MAAM,EACN,SAAS,EACT,SAAS,EACT,OAAO,EACP,OAAO,EACV,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EAAuB,KAAK,aAAa,EAAE,MAAM,YAAY,CAAC;AAErE
|
|
1
|
+
{"version":3,"file":"use-motion-player.d.ts","sourceRoot":"","sources":["../../src/ui/use-motion-player.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EACR,UAAU,EACV,MAAM,EACN,OAAO,EACP,UAAU,EACV,WAAW,EACX,YAAY,EACZ,SAAS,EACT,cAAc,EAGd,eAAe,EACf,iBAAiB,EACjB,cAAc,EACd,OAAO,EACP,MAAM,EACN,SAAS,EACT,SAAS,EACT,OAA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CAAC;IACzD,kBAAkB,CAAC,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC3C;AAED;;;;;;;GAOG;AACH,wBAAgB,eAAe,CAAC,OAAO,EAAE,mBAAmB,GAAG,MAAM,CAoTpE"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@motionscript/react",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.1-alpha.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "React bindings for Motion Script.",
|
|
6
6
|
"repository": {
|
|
@@ -35,7 +35,7 @@
|
|
|
35
35
|
"peerDependencies": {
|
|
36
36
|
"react": "^18.2.0 || ^19.0.0",
|
|
37
37
|
"react-dom": "^18.2.0 || ^19.0.0",
|
|
38
|
-
"@motionscript/core": "^0.1.
|
|
38
|
+
"@motionscript/core": "^0.1.1-alpha.1"
|
|
39
39
|
},
|
|
40
40
|
"devDependencies": {
|
|
41
41
|
"@eslint/js": "^9.39.1",
|
|
@@ -57,8 +57,8 @@
|
|
|
57
57
|
"vite": "^8.0.11",
|
|
58
58
|
"vite-plugin-dts": "5.0.0",
|
|
59
59
|
"vitest": "^4.1.5",
|
|
60
|
-
"@motionscript/core": "0.1.
|
|
61
|
-
"@motionscript/browser": "0.1.
|
|
60
|
+
"@motionscript/core": "0.1.1-alpha.1",
|
|
61
|
+
"@motionscript/browser": "0.1.1-alpha.1"
|
|
62
62
|
},
|
|
63
63
|
"scripts": {
|
|
64
64
|
"dev": "vite",
|