The VS Code of video editing, built for agents.
TypeScript
Refactor export logic to utilize unified rendering approach and improve state management
konstantin-paulusf0b650d1bdbc
diff --git a/apps/web/src/context/editor-api/node.ts b/apps/web/src/context/editor-api/node.tsindex b910a0cf..682a433f 100644--- a/apps/web/src/context/editor-api/node.ts+++ b/apps/web/src/context/editor-api/node.ts@@ -4,9 +4,9 @@import { entityExists, hasComponent, query, Not } from "bitecs";-import { createEncoder } from "@/components/engine/encode/encoder";import { createImageEncoder } from "@/components/engine/encode/image-encoder";import { ElectronWritableFileHandle } from "@/lib/electron-file-writable";+import { renderScene } from "@/context/render";import {AnimationPhase,@@ -329,24 +329,17 @@ export function handleNodeRender(engine: Accessor<Engine>) {}const target = new ElectronWritableFileHandle(output);- e.stop();- let result;- try {- const encoder = await createEncoder(w, {- ...(config as Partial<EncoderConfig>),- scene: sceneEid,- target,- });- result = await encoder.render();- } finally {- e.start();- }+ const result = await renderScene(e, {+ scene: sceneEid,+ target,+ config: config as Partial<EncoderConfig>,+ });if (result.type !== "success") {// Clean up the partial file on cancel / error.await target.dispose().catch(() => { });if (result.type === "canceled") throw new Error("Export canceled");- throw new Error(result.error?.message || "Export failed");+ throw new Error(result.error.message || "Export failed");}return { path: output };diff --git a/apps/web/src/context/export.tsx b/apps/web/src/context/export.tsxindex 901270c1..30ee712c 100644--- a/apps/web/src/context/export.tsx+++ b/apps/web/src/context/export.tsx@@ -2,15 +2,15 @@* License, v. 2.0. If a copy of the MPL was not distributed with this* file, You can obtain one at http://mozilla.org/MPL/2.0/. */-import { createContext, useContext, createSignal, batch, onCleanup, onMount } from "solid-js";+import { createContext, useContext, onCleanup, onMount } from "solid-js";import { toast } from "somoto";import { assert, downloadObject } from "@/utils";import { useEngine } from "@/context/engine";import { useProjectId } from "@/hooks/use-project-id";import { getProjectName } from "@/components/engine/db/global-db";-import { createEncoder } from "@/components/engine/encode/encoder";import { track } from "@/lib/analytics";import { ExportProgress, type ExportConfig } from "@/components/sidebar-right/inspector/export-progress";+import { renderScene, renderOverlay, cancelRender } from "@/context/render";import {MIME_TYPES,getDefaultExportTemplate,@@ -31,13 +31,10 @@ export function ExportProvider(props: { children: JSX.Element }) {const { world } = engine;const projectId = useProjectId();- const [exporting, setExporting] = createSignal(false);- const [progress, setProgress] = createSignal(0);- const [remaining, setRemaining] = createSignal<{ minutes: number; seconds: number }>();- const [activeConfig, setActiveConfig] = createSignal<ExportConfig>();- const [duration, setDuration] = createSignal(0);+ const exporting = () => !!renderOverlay();- let cancelExport: (() => void) | undefined;+ const sceneDurationSeconds = (sceneEid: number) =>+ world.components.Computed.duration[sceneEid] / world.frameRate;const exportScene: ExportContextValue["exportScene"] = async (sceneEid, config) => {if (!sceneEid) return;@@ -70,65 +67,30 @@ export function ExportProvider(props: { children: JSX.Element }) {return;}- engine.stop();-- const sceneDuration = () => {- const frameRate = world.frameRate;- const Computed = world.components.Computed;- return Computed.duration[sceneEid] / frameRate;- };-- batch(() => {- setExporting(true);- setProgress(0);- setRemaining(undefined);- setActiveConfig(config);- setDuration(sceneDuration());- });-track('export_started', {format,resolution: config.video?.resolution,fps: config.video?.fps,video_codec: config.video?.codec,audio_codec: config.audio?.codec,- scene_duration_s: Math.round(sceneDuration()),+ scene_duration_s: Math.round(sceneDurationSeconds(sceneEid)),});const startedAt = performance.now();try {- const encoder = await createEncoder(world, {- ...config,- target,- scene: sceneEid,- onProgress(p) {- const percent = Math.round((p.progress / p.total) * 100);- const r = p.remaining;- batch(() => {- setProgress(percent);- setRemaining({- minutes: r.getUTCMinutes(),- seconds: r.getUTCSeconds(),- });- });- },- });-- cancelExport = encoder.cancel;-- const result = await encoder.render();+ const result = await renderScene(engine, { scene: sceneEid, target, config });if (result.type === "error") {console.error("Export failed:", result.error);toast.error("Export failed", {- description: (result.error as Error | undefined)?.message,+ description: result.error.message,});track('export_failed', {format,duration_ms: Math.round(performance.now() - startedAt),- error: (result.error as Error | undefined)?.message?.slice(0, 200) ?? 'unknown',+ error: result.error.message?.slice(0, 200) ?? 'unknown',});- } else {+ } else if (result.type === "success") {toast("Export complete", {description: "Your video has been successfully exported",});@@ -136,7 +98,7 @@ export function ExportProvider(props: { children: JSX.Element }) {format,resolution: config.video?.resolution,fps: config.video?.fps,- scene_duration_s: Math.round(sceneDuration()),+ scene_duration_s: Math.round(sceneDurationSeconds(sceneEid)),duration_ms: Math.round(performance.now() - startedAt),});}@@ -150,10 +112,6 @@ export function ExportProvider(props: { children: JSX.Element }) {duration_ms: Math.round(performance.now() - startedAt),error: (e as Error).message?.slice(0, 200) ?? 'unknown',});- } finally {- cancelExport = undefined;- setExporting(false);- engine.start();}};@@ -204,12 +162,12 @@ export function ExportProvider(props: { children: JSX.Element }) {<ExportContext.Provider value={{ exportScene, exportCurrentFrame, exporting }}>{props.children}<ExportProgress- open={exporting()}- progress={progress()}- remaining={remaining()}- config={activeConfig()}- duration={duration()}- onCancel={() => cancelExport?.()}+ open={!!renderOverlay()}+ progress={renderOverlay()?.progress ?? 0}+ remaining={renderOverlay()?.remaining}+ config={renderOverlay()?.config as ExportConfig | undefined}+ duration={renderOverlay()?.duration ?? 0}+ onCancel={cancelRender}/></ExportContext.Provider>);diff --git a/apps/web/src/context/render.ts b/apps/web/src/context/render.tsnew file mode 100644index 00000000..24c7618c--- /dev/null+++ b/apps/web/src/context/render.ts@@ -0,0 +1,92 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++import { createSignal } from "solid-js";++import { createEncoder } from "@/components/engine/encode/encoder";++import type { Engine } from "@/components/engine";+import type { EncoderConfig } from "@/components/engine/encode/interfaces";+import type { ExportResult } from "@/components/engine/encode/types";+import type { ExportConfig } from "@/components/sidebar-right/inspector/export-progress";++/**+ * Unified scene render path.+ *+ * Both the UI export (`ExportProvider.exportScene`) and the headless CLI render+ * (`handleNodeRender` for `dapi node render`) funnel through {@link renderScene}+ * so they share one implementation of: the "Exporting Composition" overlay, the+ * engine stop/start lifecycle, encoder creation, progress reporting, and cancel+ * wiring. Callers only supply what differs (where the file comes from, and any+ * analytics/toasts/cleanup around the result).+ */++export type RenderOverlayState = {+ config?: Partial<ExportConfig>;+ duration: number;+ progress: number;+ remaining?: { minutes: number; seconds: number };+};++const [overlay, setOverlay] = createSignal<RenderOverlayState | null>(null);+let cancelActive: (() => void) | undefined;++/** Reactive overlay state; `null` when no render is in flight. Read by `<ExportProgress>`. */+export const renderOverlay = overlay;++/** Cancel the render currently in flight, if any. Wired to the overlay's Cancel button. */+export function cancelRender() {+ cancelActive?.();+}++export type RenderSceneOptions = {+ /** Scene entity to encode. */+ scene: number;+ /** Where to write the output (a save-picker handle in the UI, a file path handle from the CLI). */+ target: NonNullable<EncoderConfig["target"]>;+ /** Encoder settings (resolution, codecs, format, ...). */+ config?: Partial<EncoderConfig>;+};++export async function renderScene(+ engine: Engine,+ { scene, target, config }: RenderSceneOptions,+): Promise<ExportResult> {+ const w = engine.world;+ const duration = w.components.Computed.duration[scene] / w.frameRate;++ cancelActive = undefined;+ setOverlay({ config, duration, progress: 0, remaining: undefined });+ engine.stop();++ try {+ const encoder = await createEncoder(w, {+ ...config,+ scene,+ target,+ onProgress(p) {+ const percent = Math.round((p.progress / p.total) * 100);+ setOverlay((prev) =>+ prev+ ? {+ ...prev,+ progress: percent,+ remaining: {+ minutes: p.remaining.getUTCMinutes(),+ seconds: p.remaining.getUTCSeconds(),+ },+ }+ : prev,+ );+ },+ });++ cancelActive = encoder.cancel;+ return await encoder.render();+ } finally {+ cancelActive = undefined;+ setOverlay(null);+ engine.start();+ }+}