Skip to content

The VS Code of video editing, built for agents.

TypeScript

Add project config read/write channels and implement config handling

konstantin-paulus97b829edcb5e
diff --git a/apps/desktop/src/main-channels.ts b/apps/desktop/src/main-channels.ts
index 2ae4b316..91f351b6 100644
--- a/apps/desktop/src/main-channels.ts
+++ b/apps/desktop/src/main-channels.ts
@@ -52,6 +52,8 @@ export const MAIN_CHANNELS = {
PROJECTS_UNWATCH: "projects:unwatch",
PROJECTS_MANIFEST_READ: "projects:manifest-read",
PROJECTS_MANIFEST_WRITE: "projects:manifest-write",
+ PROJECTS_CONFIG_READ: "projects:config-read",
+ PROJECTS_CONFIG_WRITE: "projects:config-write",
PROJECTS_FS_LIST: "projects:fs-list",
PROJECTS_FS_STAT: "projects:fs-stat",
PROJECTS_FS_REMOVE: "projects:fs-remove",
@@ -149,6 +151,11 @@ export type MainRequestMap = {
// The asset manifest (`assets.yml`) as plain data; null when there is none.
[MAIN_CHANNELS.PROJECTS_MANIFEST_READ]: { request: { dir: string }; response: unknown };
[MAIN_CHANNELS.PROJECTS_MANIFEST_WRITE]: { request: { dir: string; manifest: unknown }; response: void };
+ // The project's config: the `diffusion` field of its package.json, as
+ // parsed (null when absent). The renderer owns its shape; see
+ // `projects/config` in the web app.
+ [MAIN_CHANNELS.PROJECTS_CONFIG_READ]: { request: { dir: string }; response: unknown };
+ [MAIN_CHANNELS.PROJECTS_CONFIG_WRITE]: { request: { dir: string; config: unknown }; response: void };
// Project file system, for the asset library. `source` is project-relative
// or absolute; `path` is always project-relative. Writes stream through the
// FILE_WRITE_* channels (which create parent directories).
diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts
index 19dc8a0b..e5e1772b 100644
--- a/apps/desktop/src/main.ts
+++ b/apps/desktop/src/main.ts
@@ -25,11 +25,13 @@ import {
unwatchAll,
listEntries,
markSelfWriteAbsolute,
+ readConfig,
readManifest,
removeEntry,
statEntry,
unwatchProject,
watchProject,
+ writeConfig,
writeManifest,
writeProject,
} from "./projects";
@@ -283,6 +285,8 @@ if (app.requestSingleInstanceLock()) {
mainBridge.handle(MAIN_CHANNELS.PROJECTS_UNWATCH, ({ dir }) => unwatchProject(dir));
mainBridge.handle(MAIN_CHANNELS.PROJECTS_MANIFEST_READ, ({ dir }) => readManifest(dir));
mainBridge.handle(MAIN_CHANNELS.PROJECTS_MANIFEST_WRITE, ({ dir, manifest }) => writeManifest(dir, manifest));
+ mainBridge.handle(MAIN_CHANNELS.PROJECTS_CONFIG_READ, ({ dir }) => readConfig(dir));
+ mainBridge.handle(MAIN_CHANNELS.PROJECTS_CONFIG_WRITE, ({ dir, config }) => writeConfig(dir, config));
mainBridge.handle(MAIN_CHANNELS.PROJECTS_FS_LIST, ({ dir, source }) => listEntries(dir, source));
mainBridge.handle(MAIN_CHANNELS.PROJECTS_FS_STAT, ({ dir, source }) => statEntry(dir, source));
mainBridge.handle(MAIN_CHANNELS.PROJECTS_FS_REMOVE, ({ dir, path }) => removeEntry(dir, path));
diff --git a/apps/desktop/src/projects.ts b/apps/desktop/src/projects.ts
index 818bce17..a85134e6 100644
--- a/apps/desktop/src/projects.ts
+++ b/apps/desktop/src/projects.ts
@@ -424,6 +424,32 @@ ${text}`, "utf8");
await rename(temp, path);
}
+// ---------------------------------------------------------------------------
+// Config
+
+/** The package.json field the project's config lives under. */
+const CONFIG_FIELD = "diffusion";
+
+/** The project's config (package.json `diffusion`), or null when there is none. */
+export async function readConfig(dir: string): Promise<unknown> {
+ const pkg = await readPackage(dir);
+ return pkg?.[CONFIG_FIELD] ?? null;
+}
+
+/**
+ * Replaces the project's config in its package.json (removes the field for
+ * null), leaving the rest of the record alone. The watcher is told to keep
+ * quiet about it, like the manifest: the app already shows these values.
+ */
+export async function writeConfig(dir: string, config: unknown): Promise<void> {
+ const pkg = (await readPackage(dir)) ?? packageJson(basename(dir), basename(dir));
+ const next: PackageJson = { ...pkg };
+ if (config === null || config === undefined) delete next[CONFIG_FIELD];
+ else next[CONFIG_FIELD] = config;
+ markSelfWrite(dir, "package.json");
+ await writePackage(dir, next);
+}
+
/** Entries of a directory; [] when it is missing or not a directory. */
export async function listEntries(dir: string, source: string): Promise<FsEntry[]> {
const path = sourcePath(dir, source);
diff --git a/apps/web/src/components/sidebar-right/inspector/export-templates.ts b/apps/web/src/components/sidebar-right/inspector/export-templates.ts
index fa26a9a1..56f96473 100644
--- a/apps/web/src/components/sidebar-right/inspector/export-templates.ts
+++ b/apps/web/src/components/sidebar-right/inspector/export-templates.ts
@@ -3,8 +3,10 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import type { VideoCodec, AudioCodec } from "mediabunny";
-import type { ContainerFormat } from "@/components/engine/encode/types";
-import type { ExportConfig } from "./export-progress";
+import type { ContainerFormat, ExportConfig as ProjectExportConfig } from "@/engine/project-config";
+
+/** What an export is made with: the project's export config less the template label. */
+export type ExportConfig = Omit<ProjectExportConfig, "template">;
export type ExportTemplate = {
id: string;
diff --git a/apps/web/src/components/sidebar-right/inspector/export.tsx b/apps/web/src/components/sidebar-right/inspector/export.tsx
index 2dbd157f..a80bae74 100644
--- a/apps/web/src/components/sidebar-right/inspector/export.tsx
+++ b/apps/web/src/components/sidebar-right/inspector/export.tsx
@@ -2,23 +2,13 @@
* 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 { For, Show, createEffect, createMemo, createSignal } from "solid-js";
+import { Show, createMemo, createSignal } from "solid-js";
+import { toast } from "somoto";
import { PanelSection } from "@/components/ui/panel-section";
import { Button } from "@/components/ui/button";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { ItemRow } from "@/components/ui/item-row";
import { ControlRow } from "@/components/ui/control-group";
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuGroup,
- DropdownMenuGroupLabel,
- DropdownMenuItem,
- DropdownMenuItemDetail,
- DropdownMenuPortal,
- DropdownMenuSeparator,
- DropdownMenuTrigger,
-} from "@/components/ui/dropdown-menu";
import {
FloatingInspector,
FloatingInspectorContent,
@@ -35,16 +25,15 @@ import {
SelectValue,
} from "@/components/ui/select";
import { Switch, SwitchControl, SwitchInput, SwitchThumb } from "@/components/ui/switch";
-
import { Separator } from "@/components/ui/separator";
import { SliderInput } from "@/components/ui/slider-input";
import { formatBytes, formatDuration } from "@/utils/formatters";
-import { useEntityState, useEntityTag, setComponent, removeComponent } from "@/components/engine";
-import { useEngine } from "@/context/engine";
-import { useExport } from "@/context/export";
-import { type ExportConfig } from "./export-progress";
+import { useTrait, useWorld } from "@diffusionstudio/koota-solid";
+import { Computed, FrameRate } from "@diffusionstudio/runtime";
+import { useDerived } from "@/engine/hooks";
+import { useProjectConfig } from "@/engine/project-config";
import {
- EXPORT_TEMPLATE_GROUPS,
+ DEFAULT_EXPORT_TEMPLATE_ID,
TEMPLATE_BY_ID,
RESOLUTION_OPTIONS,
VIDEO_CODEC_OPTIONS,
@@ -54,134 +43,100 @@ import {
SAMPLE_RATE_OPTIONS,
} from "./export-templates";
-import type { EngineWorld } from "@/components/engine";
-import type { ContainerFormat } from "@/components/engine/encode/types";
+import type { Entity } from "koota";
import type { VideoCodec, AudioCodec } from "mediabunny";
+import type { ContainerFormat, ExportConfig as ProjectExportConfig } from "@/engine/project-config";
+import type { ExportConfig } from "./export-templates";
type ExportPanelProps = {
- selection: Set<number>;
-};
-
-export type ExportSettingsData = {
- templateId?: string | null;
- format?: ContainerFormat;
- videoEnabled?: boolean;
- videoCodec?: VideoCodec;
- videoBitrate?: number;
- videoFps?: number;
- videoResolution?: number;
- audioEnabled?: boolean;
- audioCodec?: AudioCodec;
- audioSampleRate?: number;
+ selection: Entity[];
};
-// Build the full export template payload — every field, so switching templates
-// fully replaces the prior config (the observer clears fields a template omits).
-function templatePayload(id: string): ExportSettingsData | null {
+/** The whole settings a template stands for: every field, so it replaces what was there. */
+function templateSettings(id: string): ProjectExportConfig | null {
const template = TEMPLATE_BY_ID.get(id);
if (!template) return null;
return {
- templateId: id,
+ template: id,
format: template.format,
- videoEnabled: template.video?.enabled,
- videoCodec: template.video?.codec,
- videoBitrate: template.video?.bitrate,
- videoFps: template.video?.fps,
- videoResolution: template.video?.resolution,
- audioEnabled: template.audio?.enabled,
- audioCodec: template.audio?.codec,
- audioSampleRate: template.audio?.sampleRate,
- };
-}
-
-// Read the export settings off the scene entity imperatively (no subscription).
-function readConfig(world: EngineWorld, eid: number): ExportConfig | undefined {
- const s = world.components.ExportSettings;
- if (s.templateId[eid] == null) return undefined;
- return {
- format: s.format[eid],
- video: {
- enabled: s.videoEnabled[eid],
- codec: s.videoCodec[eid],
- bitrate: s.videoBitrate[eid],
- fps: s.videoFps[eid],
- resolution: s.videoResolution[eid],
- },
- audio: {
- enabled: s.audioEnabled[eid],
- codec: s.audioCodec[eid],
- sampleRate: s.audioSampleRate[eid],
- },
+ video: template.video && { ...template.video },
+ audio: template.audio && { ...template.audio },
};
}
+/**
+ * How the project is exported. Project configuration rather than part of
+ * the composition: read from and written through the project config
+ * (package.json, see `@/engine/project-config`). Shown on the scene since
+ * that is what gets exported; per-scene settings would come as a per-scene
+ * accessor on the config, falling back to the project's. The row and the
+ * floating inspector both read the same accessor, so they never disagree.
+ */
export function ExportPanel(props: ExportPanelProps) {
- const { world } = useEngine();
- const { exportScene: runExport } = useExport();
+ const world = useWorld();
+ const config = useProjectConfig();
+ const entity = () => props.selection[0]!;
- const c = world.components;
-
- const [search, setSearch] = createSignal("");
- const [config, setConfig] = createSignal<ExportConfig | undefined>();
const [isInspectorOpen, setIsInspectorOpen] = createSignal(false);
- const eid = () => props.selection.values().next().value!;
- const duration = useEntityState(c.Computed.duration, eid, 0);
- const durationInSeconds = createMemo(() => duration() / world.frameRate);
- // Gate on component presence: removing a template removes the whole component,
- // but the SoA arrays aren't cleared, so the value subscription alone would
- // still report the old id.
- const hasSettings = useEntityTag(c.ExportSettings, eid);
- const templateId = useEntityState(c.ExportSettings.templateId, eid, null);
- const selectedTemplateId = () => (hasSettings() ? templateId() ?? null : null);
-
- const selectedTemplate = createMemo(() => {
- const id = selectedTemplateId();
- if (!id) return null;
- return TEMPLATE_BY_ID.get(id) ?? null;
+ const settings = () => config()?.export() ?? undefined;
+ const frameRate = useTrait(world, FrameRate);
+ const duration = useDerived(() => entity().get(Computed)?.duration ?? 0);
+ const durationInSeconds = createMemo(() => duration() / (frameRate()?.value ?? 30));
+
+ const template = createMemo(() => {
+ const id = settings()?.template;
+ return id ? TEMPLATE_BY_ID.get(id) ?? null : null;
});
- createEffect(() => {
- setConfig(selectedTemplateId() ? readConfig(world, eid()) : undefined);
+ // What the row says: the preset's name, or "Custom" for settings authored
+ // without one, and the resolution the export actually uses (a preset's
+ // resolution can be changed in the inspector without leaving the preset).
+ const label = createMemo(() => {
+ const current = settings();
+ if (!current) return "";
+ const name = template()?.name ?? "Custom";
+ const resolution = current.video?.resolution ?? template()?.video?.resolution;
+ return resolution ? `${name} · ${resolution}p` : name;
});
- const writeSettings = (data: ExportSettingsData) => {
- setComponent(world, eid(), c.ExportSettings, data, false);
+ const write = (value: ProjectExportConfig | null) => {
+ void config()?.setExport(value);
};
- const setInspectorTemplate = (id?: string | null) => {
- if (!id) return;
- const payload = templatePayload(id);
- if (payload) writeSettings(payload);
+ // Replaces the settings with a preset's, wholesale.
+ const applyTemplate = (id: string) => {
+ const next = templateSettings(id);
+ if (next) write(next);
};
- const filteredTemplateGroups = createMemo(() => {
- const query = search().trim().toLowerCase();
-
- return EXPORT_TEMPLATE_GROUPS
- .map((group) => ({
- id: group.id,
- label: group.label,
- items: group.items.filter((item) => {
- if (!query) return true;
- return `${item.name} ${item.video?.resolution} ${group.label}`
- .toLowerCase()
- .includes(query);
- }),
- }))
- .filter((group) => group.items.length > 0);
- });
+ // Changes some fields, keeping the rest (and the preset label) as they are.
+ const patchSettings = (patch: ExportConfig) => {
+ const current = settings();
+ if (!current) return;
+ write({
+ ...current,
+ ...patch,
+ video: patch.video ? { ...current.video, ...patch.video } : current.video,
+ audio: patch.audio ? { ...current.audio, ...patch.audio } : current.audio,
+ });
+ };
- const exportScene = async () => {
- const template = selectedTemplate();
- if (!template) return;
+ const removeSettings = () => {
+ write(null);
+ setIsInspectorOpen(false);
+ };
- await runExport(eid(), readConfig(world, eid()) ?? template);
+ const exportScene = () => {
+ // TODO(koota): render through @diffusionstudio/encoder with
+ // `{ ...settings(), scene: entity() }` once the export path is on the
+ // koota world; the settings are already in its shape.
+ toast("Export is not available yet", {
+ description: "Exporting is not wired to the new engine yet.",
+ });
};
- const estimatedFileSize = createMemo(() => {
- return estimateFileSize(config(), durationInSeconds());
- });
+ const estimatedFileSize = createMemo(() => estimateFileSize(settings(), durationInSeconds()));
let inspectorAnchorRef: HTMLDivElement | undefined;
@@ -190,206 +145,92 @@ export function ExportPanel(props: ExportPanelProps) {
title="Export"
ref={inspectorAnchorRef}
actions={
- <DropdownMenu
- placement="bottom-end"
- onOpenChange={(open) => {
- if (!open) setSearch("");
- }}
- >
+ <Show when={!settings()}>
<Tooltip>
- <TooltipTrigger<typeof DropdownMenuTrigger>
- as={(triggerProps: object) => (
- <DropdownMenuTrigger<typeof Button>
- {...triggerProps}
- as={(buttonProps) => (
- <Button
- size="icon"
- variant="ghost"
- class="text-muted-foreground"
- {...buttonProps}
- >
- <Icon name="plus-add" />
- </Button>
- )}
- />
- )}
- />
- <TooltipContent>Add template</TooltipContent>
+ <TooltipTrigger
+ as={Button}
+ size="icon"
+ variant="ghost"
+ class="text-muted-foreground"
+ onClick={() => applyTemplate(DEFAULT_EXPORT_TEMPLATE_ID)}
+ >
+ <Icon name="plus-add" />
+ </TooltipTrigger>
+ <TooltipContent>Add export</TooltipContent>
</Tooltip>
- <DropdownMenuPortal>
- <DropdownMenuContent class="w-[208px]">
- <div class="flex h-7 w-full items-center rounded-md overflow-hidden">
- <div class="h-7 w-6 shrink-0 flex items-center justify-center text-muted-foreground">
- <Icon name="search" class="size-6" />
- </div>
- <input
- type="text"
- placeholder="Search"
- value={search()}
- onInput={(event) => setSearch(event.currentTarget.value)}
- onKeyDown={(event) => {
- if (event.key === "Escape") return;
- event.stopPropagation();
- }}
- class="flex-1 min-w-0 bg-transparent pl-2 text-xs text-foreground placeholder:text-muted-foreground outline-none"
- />
- </div>
- <DropdownMenuSeparator />
- <For each={filteredTemplateGroups()}>
- {(group, index) => (
- <>
- <Show when={index() > 0}>
- <DropdownMenuSeparator />
- </Show>
- <DropdownMenuGroup>
- <DropdownMenuGroupLabel>
- {group.label}
- </DropdownMenuGroupLabel>
- <For each={group.items}>
- {(item) => (
- <DropdownMenuItem
- tone="neutral"
- disabled={item.id === selectedTemplateId()}
- onSelect={() => setInspectorTemplate(item.id)}
- >
- <span class="flex-1 min-w-0 overflow-hidden text-ellipsis whitespace-nowrap">
- {item.name}
- </span>
- <DropdownMenuItemDetail>
- {item.video?.resolution}p
- </DropdownMenuItemDetail>
- </DropdownMenuItem>
- )}
- </For>
- </DropdownMenuGroup>
- </>
- )}
- </For>
- <Show when={filteredTemplateGroups().length === 0}>
- <div class="px-2 py-1.5 text-xs text-muted-foreground">
- No template found
- </div>
- </Show>
- </DropdownMenuContent>
- </DropdownMenuPortal>
- </DropdownMenu>
+ </Show>
}
>
- <Show when={selectedTemplate()}>
- {(template) => (
- <>
- <ItemRow
- value={`${template().name} · ${template().video?.resolution}p`}
- icon={<Icon name="film-video-export" />}
- onClick={() => setIsInspectorOpen(true)}
+ <Show when={settings()}>
+ <ItemRow
+ value={label()}
+ icon={<Icon name="film-video-export" />}
+ onClick={() => setIsInspectorOpen(true)}
+ >
+ <Tooltip>
+ <TooltipTrigger
+ as={Button}
+ size="icon"
+ variant="ghost"
+ class="text-muted-foreground"
+ onClick={removeSettings}
>
- <Tooltip>
- <TooltipTrigger
- as={Button}
- size="icon"
- variant="ghost"
- class="text-muted-foreground"
- onClick={() => {
- removeComponent(world, eid(), c.ExportSettings, false);
- setIsInspectorOpen(false);
- }}
- >
- <Icon name="close-remove-small" />
- </TooltipTrigger>
- <TooltipContent>Remove template</TooltipContent>
- </Tooltip>
- </ItemRow>
- <Button class="w-full" onClick={exportScene}>
- Export
- </Button>
- <div class="flex justify-between items-center h-7">
- <span class="text-base text-muted-foreground">
- Duration {formatDuration(durationInSeconds())}
- </span>
- <span class="text-base text-muted-foreground">
- File size {formatBytes(estimatedFileSize())}
- </span>
- </div>
- </>
- )}
+ <Icon name="close-remove-small" />
+ </TooltipTrigger>
+ <TooltipContent>Remove export</TooltipContent>
+ </Tooltip>
+ </ItemRow>
+ <Button class="w-full" onClick={exportScene}>
+ Export
+ </Button>
+ <div class="flex justify-between items-center h-7">
+ <span class="text-base text-muted-foreground">
+ Duration {formatDuration(durationInSeconds())}
+ </span>
+ <span class="text-base text-muted-foreground">
+ File size {formatBytes(estimatedFileSize())}
+ </span>
+ </div>
</Show>
- <Show when={isInspectorOpen()}>
- <ExportInspector
- eid={eid}
- anchorRef={inspectorAnchorRef}
- onClose={() => setIsInspectorOpen(false)}
- onConfigChange={setConfig}
- onSelectTemplate={setInspectorTemplate}
- />
+ <Show when={isInspectorOpen() && settings()}>
+ {(current) => (
+ <ExportInspector
+ settings={current()}
+ anchorRef={inspectorAnchorRef}
+ onClose={() => setIsInspectorOpen(false)}
+ onSelectTemplate={applyTemplate}
+ onPatch={patchSettings}
+ />
+ )}
</Show>
</PanelSection>
);
}
type ExportInspectorProps = {
- eid: () => number;
+ settings: ProjectExportConfig;
anchorRef: HTMLDivElement | undefined;
onClose: () => void;
- onConfigChange: (config: ExportConfig | undefined) => void;
onSelectTemplate: (id: string) => void;
+ onPatch: (patch: ExportConfig) => void;
};
-// The floating export-settings dialog. Kept as its own component so the per-field
-// value subscriptions below only exist while the dialog is mounted (i.e. open).
+/**
+ * The floating export-settings dialog. Reads the settings the panel hands it
+ * and writes through the panel, so there is one place they are written from.
+ */
function ExportInspector(props: ExportInspectorProps) {
- const { world } = useEngine();
- const c = world.components;
-
- const templateId = useEntityState(c.ExportSettings.templateId, props.eid, null);
- const format = useEntityState(c.ExportSettings.format, props.eid, undefined);
- const videoEnabled = useEntityState(c.ExportSettings.videoEnabled, props.eid, undefined);
- const videoCodec = useEntityState(c.ExportSettings.videoCodec, props.eid, undefined);
- const videoBitrate = useEntityState(c.ExportSettings.videoBitrate, props.eid, undefined);
- const videoFps = useEntityState(c.ExportSettings.videoFps, props.eid, undefined);
- const videoResolution = useEntityState(c.ExportSettings.videoResolution, props.eid, undefined);
- const audioEnabled = useEntityState(c.ExportSettings.audioEnabled, props.eid, undefined);
- const audioCodec = useEntityState(c.ExportSettings.audioCodec, props.eid, undefined);
- const audioSampleRate = useEntityState(c.ExportSettings.audioSampleRate, props.eid, undefined);
-
- const selectedTemplate = createMemo(() => {
- const id = templateId();
- if (!id) return null;
- return TEMPLATE_BY_ID.get(id) ?? null;
- });
-
- const config = createMemo<ExportConfig | undefined>(() => {
- if (templateId() == null) return undefined;
- return {
- format: format(),
- video: {
- enabled: videoEnabled(),
- codec: videoCodec(),
- bitrate: videoBitrate(),
- fps: videoFps(),
- resolution: videoResolution(),
- },
- audio: {
- enabled: audioEnabled(),
- codec: audioCodec(),
- sampleRate: audioSampleRate(),
- },
- };
- });
+ const config = () => props.settings;
+ const templateId = () => props.settings.template ?? "";
- // Keep the panel's file-size estimate in sync while the dialog is open; the
- // last value stays frozen in the panel once this component unmounts.
- createEffect(() => props.onConfigChange(config()));
-
- const writeSettings = (data: ExportSettingsData) => {
- setComponent(world, props.eid(), c.ExportSettings, data, false);
- };
+ const write = props.onPatch;
return (
<FloatingInspector open anchorRef={props.anchorRef} width={272}>
<FloatingInspectorHeader class="items-center justify-between px-2">
<Select
- value={selectedTemplate()?.id ?? ""}
- options={Array.from(TEMPLATE_BY_ID.values()).map((template) => template.id)}
+ value={templateId()}
+ options={Array.from(TEMPLATE_BY_ID.keys())}
onChange={(value) => value && props.onSelectTemplate(value)}
itemComponent={(itemProps) => {
const template = TEMPLATE_BY_ID.get(itemProps.item.rawValue);
@@ -398,7 +239,7 @@ function ExportInspector(props: ExportInspectorProps) {
>
<SelectTrigger>
<SelectValue>
- {selectedTemplate()?.name}
+ {TEMPLATE_BY_ID.get(templateId())?.name ?? "Custom"}
</SelectValue>
</SelectTrigger>
<SelectPortal>
@@ -423,8 +264,8 @@ function ExportInspector(props: ExportInspectorProps) {
<div class="flex flex-col gap-2">
<ControlRow label="Video">
<Switch
- checked={config()?.video?.enabled != false}
- onChange={(checked) => writeSettings({ videoEnabled: checked })}
+ checked={config().video?.enabled != false}
+ onChange={(checked) => write({ video: { enabled: checked } })}
>
<SwitchInput />
<SwitchControl variant="compact">
@@ -435,21 +276,21 @@ function ExportInspector(props: ExportInspectorProps) {
<div
class="flex flex-col gap-2 transition-opacity"
classList={{
- "opacity-50": config()?.video?.enabled == false,
- "pointer-events-none": config()?.video?.enabled == false,
+ "opacity-50": config().video?.enabled == false,
+ "pointer-events-none": config().video?.enabled == false,
}}
>
<ControlRow label="Resolution">
<Select
- value={config()?.video?.resolution}
+ value={config().video?.resolution ?? 1080}
options={[...RESOLUTION_OPTIONS]}
- onChange={(value) => writeSettings({ videoResolution: value ?? undefined })}
+ onChange={(value) => value && write({ video: { resolution: value } })}
itemComponent={(itemProps) => (
<SelectItem item={itemProps.item}>{itemProps.item.rawValue}p</SelectItem>
)}
>
<SelectTrigger>
- <SelectValue>{config()?.video?.resolution + 'p'}</SelectValue>
+ <SelectValue>{config().video?.resolution ?? 1080}p</SelectValue>
</SelectTrigger>
<SelectPortal>
<SelectContent />
@@ -458,8 +299,8 @@ function ExportInspector(props: ExportInspectorProps) {
</ControlRow>
<ControlRow label="Bitrate">
<SliderInput
- value={((config()?.video?.bitrate ?? 10e6) / 1e6)}
- onChange={(value) => writeSettings({ videoBitrate: value * 1e6 })}
+ value={(config().video?.bitrate ?? 10e6) / 1e6}
+ onChange={(value) => write({ video: { bitrate: value * 1e6 } })}
min={0.1}
max={120}
step={1}
@@ -467,15 +308,15 @@ function ExportInspector(props: ExportInspectorProps) {
</ControlRow>
<ControlRow label="Codec">
<Select
- value={config()?.video?.codec ?? 'avc'}
+ value={config().video?.codec ?? "avc"}
options={[...VIDEO_CODEC_OPTIONS]}
- onChange={(value) => writeSettings({ videoCodec: value ?? undefined })}
+ onChange={(value) => value && write({ video: { codec: value } })}
itemComponent={(itemProps) => (
<SelectItem item={itemProps.item}>{itemProps.item.rawValue.toUpperCase()}</SelectItem>
)}
>
<SelectTrigger>
- <SelectValue>{config()?.video?.codec?.toUpperCase() ?? 'AVC'}</SelectValue>
+ <SelectValue>{(config().video?.codec ?? "avc").toUpperCase()}</SelectValue>
</SelectTrigger>
<SelectPortal>
<SelectContent />
@@ -484,15 +325,15 @@ function ExportInspector(props: ExportInspectorProps) {
</ControlRow>
<ControlRow label="Format">
<Select
- value={config()?.format ?? 'mp4'}
+ value={config().format ?? "mp4"}
options={[...VIDEO_FORMAT_OPTIONS]}
- onChange={(value) => writeSettings({ format: value ?? undefined })}
+ onChange={(value) => value && write({ format: value })}
itemComponent={(itemProps) => (
<SelectItem item={itemProps.item}>{itemProps.item.rawValue.toUpperCase()}</SelectItem>
)}
>
<SelectTrigger>
- <SelectValue>{config()?.format?.toUpperCase() ?? 'MP4'}</SelectValue>
+ <SelectValue>{(config().format ?? "mp4").toUpperCase()}</SelectValue>
</SelectTrigger>
<SelectPortal>
<SelectContent />
@@ -501,15 +342,15 @@ function ExportInspector(props: ExportInspectorProps) {
</ControlRow>
<ControlRow label="Frame rate">
<Select
- value={config()?.video?.fps ?? 30}
+ value={config().video?.fps ?? 30}
options={[...FRAME_RATE_OPTIONS]}
- onChange={(value) => writeSettings({ videoFps: value ?? undefined })}
+ onChange={(value) => value && write({ video: { fps: value } })}
itemComponent={(itemProps) => (
<SelectItem item={itemProps.item}>{itemProps.item.rawValue} FPS</SelectItem>
)}
>
<SelectTrigger>
- <SelectValue>{config()?.video?.fps ?? 30} FPS</SelectValue>
+ <SelectValue>{config().video?.fps ?? 30} FPS</SelectValue>
</SelectTrigger>
<SelectPortal>
<SelectContent />
@@ -524,8 +365,8 @@ function ExportInspector(props: ExportInspectorProps) {
<div class="flex flex-col gap-2">
<ControlRow label="Audio">
<Switch
- checked={config()?.audio?.enabled != false}
- onChange={(checked) => writeSettings({ audioEnabled: checked })}
+ checked={config().audio?.enabled != false}
+ onChange={(checked) => write({ audio: { enabled: checked } })}
>
<SwitchInput />
<SwitchControl variant="compact">
@@ -536,21 +377,21 @@ function ExportInspector(props: ExportInspectorProps) {
<div
class="flex flex-col gap-2 transition-opacity"
classList={{
- "opacity-50": config()?.audio?.enabled == false,
- "pointer-events-none": config()?.audio?.enabled == false,
+ "opacity-50": config().audio?.enabled == false,
+ "pointer-events-none": config().audio?.enabled == false,
}}
>
<ControlRow label="Codec">
<Select
- value={config()?.audio?.codec ?? 'aac'}
+ value={config().audio?.codec ?? "aac"}
options={[...AUDIO_CODEC_OPTIONS]}
- onChange={(value) => writeSettings({ audioCodec: value ?? undefined })}
+ onChange={(value) => value && write({ audio: { codec: value } })}
itemComponent={(itemProps) => (
<SelectItem item={itemProps.item}>{itemProps.item.rawValue.toUpperCase()}</SelectItem>
)}
>
<SelectTrigger>
- <SelectValue>{config()?.audio?.codec?.toUpperCase() ?? 'AAC'}</SelectValue>
+ <SelectValue>{(config().audio?.codec ?? "aac").toUpperCase()}</SelectValue>
</SelectTrigger>
<SelectPortal>
<SelectContent />
@@ -559,15 +400,15 @@ function ExportInspector(props: ExportInspectorProps) {
</ControlRow>
<ControlRow label="Sample rate">
<Select
- value={config()?.audio?.sampleRate ?? 48000}
+ value={config().audio?.sampleRate ?? 48000}
options={[...SAMPLE_RATE_OPTIONS]}
- onChange={(value) => writeSettings({ audioSampleRate: value ?? undefined })}
+ onChange={(value) => value && write({ audio: { sampleRate: value } })}
itemComponent={(itemProps) => (
<SelectItem item={itemProps.item}>{itemProps.item.rawValue / 1000} kHz</SelectItem>
)}
>
<SelectTrigger>
- <SelectValue>{(config()?.audio?.sampleRate ?? 48000) / 1000} kHz</SelectValue>
+ <SelectValue>{(config().audio?.sampleRate ?? 48000) / 1000} kHz</SelectValue>
</SelectTrigger>
<SelectPortal>
<SelectContent />
@@ -581,7 +422,6 @@ function ExportInspector(props: ExportInspectorProps) {
);
}
-
const DEFAULT_ESTIMATE_VIDEO_BITRATE = 10e6;
const DEFAULT_ESTIMATE_AUDIO_BITRATE = 128e3;
const DEFAULT_ESTIMATE_RESOLUTION = 1080;
diff --git a/apps/web/src/components/sidebar-right/inspector/inspector.tsx b/apps/web/src/components/sidebar-right/inspector/inspector.tsx
index 48f40cfe..698f5499 100644
--- a/apps/web/src/components/sidebar-right/inspector/inspector.tsx
+++ b/apps/web/src/components/sidebar-right/inspector/inspector.tsx
@@ -6,7 +6,7 @@ import { ControlScrollArea } from "@/components/ui/control-scrollarea";
import { Show, createMemo } from "solid-js";
import {
ToolType,
- // getParentNode,
+ getParentNode,
isAdjustmentLayer,
isAudio,
isCaption,
@@ -25,7 +25,7 @@ import { AssetInfoPanel } from "./asset-info";
import { TimeSettings } from "./time";
import { AppearanceSettings } from "./appearance";
import { Alignment } from "./alignment";
-// import { ExportPanel } from "./export";
+import { ExportPanel } from "./export";
// import { TransformSettings } from "./transform";
// import { LayoutPanel } from "./layout";
// import { CaptionSettings } from "./caption-settings";
@@ -78,8 +78,8 @@ export function Inspector() {
const { asset } = useAssetSelection();
// For ExportPanel (root scenes only) and TransitionSettings (sequence items).
- // const parent = createMemo(() => getParentNode(first()));
- // const isNested = createMemo(() => parent() !== null);
+ const parent = createMemo(() => getParentNode(first()));
+ const isNested = createMemo(() => parent() !== null);
// const isSequenceChild = createMemo(() => {
// const entity = parent();
// return entity !== null && isSequence(entity);
@@ -117,9 +117,9 @@ export function Inspector() {
<Alignment />
</Show>
- {/* <Show when={includesTarget("scene") && !isNested()}>
+ <Show when={includesTarget("scene") && !isNested()}>
<ExportPanel selection={nodes()} />
- </Show> */}
+ </Show>
<Show when={includesTarget("stage")}>
<BackgroundSettings />
diff --git a/apps/web/src/engine/project-config.ts b/apps/web/src/engine/project-config.ts
new file mode 100644
index 00000000..dc025326
--- /dev/null
+++ b/apps/web/src/engine/project-config.ts
@@ -0,0 +1,203 @@
+/* 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/. */
+
+// The project's config in the app: what is about the project rather than the
+// composition (how it is exported, for a start), kept in the `diffusion`
+// field of its package.json — the project record — rather than in the JSX,
+// which says what the composition is. Attached to the world for the project
+// on disk, like the library: the world holds the handle, the handle holds
+// the values as signals for the panels to read, and writes go to the file.
+// Nothing here is the runtime's business (a headless world is not exported
+// by its own settings; the encoder is handed its config), so no trait.
+//
+// Project-wide today. Per-scene settings would come as a further key here
+// (e.g. `scenes: { [name]: { export } }`) and a per-scene accessor, falling
+// back to the project's.
+
+import { createSignal } from 'solid-js';
+import { useTrait, useWorld } from '@diffusionstudio/koota-solid';
+
+import { readProjectConfig, writeProjectConfig } from '@/projects/host';
+import { ProjectConfig as ProjectConfigTrait } from './traits';
+
+import type { VideoCodec, AudioCodec } from 'mediabunny';
+import type { World } from 'koota';
+import type { Accessor } from 'solid-js';
+
+/** The file the config lives in, relative to the project. */
+export const PROJECT_CONFIG_FILE = 'package.json';
+
+export type ContainerFormat = 'mp4' | 'webm' | 'ogg' | 'mov';
+
+export type ExportVideoSettings = {
+ enabled?: boolean;
+ codec?: VideoCodec;
+ bitrate?: number;
+ fps?: number;
+ resolution?: number;
+};
+
+export type ExportAudioSettings = {
+ enabled?: boolean;
+ codec?: AudioCodec;
+ sampleRate?: number;
+ bitrate?: number;
+};
+
+/**
+ * How the project is exported, in the shape the encoder takes its config
+ * (format + video + audio), so the value goes to it as it is. `template`
+ * names the editor preset the values came from — only a label, the fields
+ * are what the export reads.
+ */
+export type ExportConfig = {
+ template?: string;
+ format?: ContainerFormat;
+ video?: ExportVideoSettings;
+ audio?: ExportAudioSettings;
+};
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+const string = (value: unknown): string | undefined => (typeof value === 'string' && value ? value : undefined);
+const number = (value: unknown): number | undefined => (typeof value === 'number' && Number.isFinite(value) ? value : undefined);
+const boolean = (value: unknown): boolean | undefined => (typeof value === 'boolean' ? value : undefined);
+
+/** An object without its `undefined` entries, so the file does not spell them. */
+function compact<T extends object>(value: T): T {
+ return Object.fromEntries(Object.entries(value).filter(([, v]) => v !== undefined)) as T;
+}
+
+/**
+ * The export field as read from the file: the same shape, with anything of
+ * the wrong type left out rather than trusted. Undefined when it is not an
+ * object, i.e. no export is set up.
+ */
+export function parseExportConfig(value: unknown): ExportConfig | undefined {
+ if (!isRecord(value)) return undefined;
+
+ let video: ExportVideoSettings | undefined;
+ if (isRecord(value.video)) {
+ video = compact({
+ enabled: boolean(value.video.enabled),
+ codec: string(value.video.codec) as ExportVideoSettings['codec'],
+ bitrate: number(value.video.bitrate),
+ fps: number(value.video.fps),
+ resolution: number(value.video.resolution),
+ });
+ }
+
+ let audio: ExportAudioSettings | undefined;
+ if (isRecord(value.audio)) {
+ audio = compact({
+ enabled: boolean(value.audio.enabled),
+ codec: string(value.audio.codec) as ExportAudioSettings['codec'],
+ sampleRate: number(value.audio.sampleRate),
+ bitrate: number(value.audio.bitrate),
+ });
+ }
+
+ return compact({
+ template: string(value.template),
+ format: string(value.format) as ContainerFormat | undefined,
+ video,
+ audio,
+ });
+}
+
+/**
+ * The config of the project at `dir`. `load` reads the file; the setters
+ * update the signal first and write the file after, so a panel sees its
+ * change at once. Fields the app does not know are carried through a write
+ * untouched.
+ */
+export class ProjectConfig {
+ private readonly world: World;
+ private readonly dir: string;
+ private raw: Record<string, unknown> = {};
+ private disposed = false;
+ private readonly exportSignal = createSignal<ExportConfig | null>(null);
+
+ public constructor(world: World, dir: string) {
+ this.world = world;
+ this.dir = dir;
+ }
+
+ /** How the project is exported, or null until it is set up. Reactive. */
+ public get export(): Accessor<ExportConfig | null> {
+ return this.exportSignal[0];
+ }
+
+ /** Reads the config from the project. */
+ public async load(): Promise<void> {
+ let value: unknown = null;
+ try {
+ value = await readProjectConfig(this.dir);
+ } catch (error) {
+ console.warn('Failed to read the project config', error);
+ }
+ if (this.disposed) return;
+
+ this.raw = isRecord(value) ? value : {};
+ this.exportSignal[1](parseExportConfig(this.raw.export) ?? null);
+ }
+
+ /** Sets how the project is exported (null for none): here now, in the file after. */
+ public async setExport(settings: ExportConfig | null): Promise<void> {
+ const next = { ...this.raw };
+ if (settings) next.export = exportToJson(settings);
+ else delete next.export;
+ this.raw = next;
+ this.exportSignal[1](settings && exportToJson(settings));
+
+ try {
+ await writeProjectConfig(this.dir, Object.keys(next).length ? next : null);
+ } catch (error) {
+ console.warn('Failed to write the project config', error);
+ }
+ }
+
+ /** Detaches the config from the world. */
+ public dispose(): void {
+ this.disposed = true;
+ if (this.world.get(ProjectConfigTrait) === this) this.world.remove(ProjectConfigTrait);
+ }
+}
+
+/** The export settings as they are spelled in the file: no `undefined`s, no empty sections. */
+function exportToJson(settings: ExportConfig): ExportConfig {
+ const video = settings.video && compact({ ...settings.video });
+ const audio = settings.audio && compact({ ...settings.audio });
+ return compact({
+ template: settings.template,
+ format: settings.format,
+ video: video && Object.keys(video).length ? video : undefined,
+ audio: audio && Object.keys(audio).length ? audio : undefined,
+ });
+}
+
+/**
+ * Creates the config of the project at `dir`, attaches it to the world and
+ * starts loading it. Returns it; `dispose` detaches it.
+ */
+export function attachProjectConfig(world: World, dir: string): ProjectConfig {
+ const config = new ProjectConfig(world, dir);
+ world.set(ProjectConfigTrait, config);
+ void config.load();
+ return config;
+}
+
+/** Whether a changed project file holds the config. */
+export function isProjectConfigFile(path: string): boolean {
+ return path === PROJECT_CONFIG_FILE;
+}
+
+/** The world's project config, or undefined until a project attaches one. */
+export function useProjectConfig(): Accessor<ProjectConfig | undefined> {
+ const world = useWorld();
+ const attached = useTrait(world, ProjectConfigTrait);
+ return () => attached() ?? undefined;
+}
diff --git a/apps/web/src/engine/traits.ts b/apps/web/src/engine/traits.ts
index ab4a182b..45ae13c1 100644
--- a/apps/web/src/engine/traits.ts
+++ b/apps/web/src/engine/traits.ts
@@ -12,6 +12,7 @@
import { trait } from 'koota';
import type { CanvasPointerEvent, Point } from '@diffusionstudio/runtime';
+import type { ProjectConfig as ProjectConfigStore } from './project-config';
export type PointerPhase = 'pressed' | 'lifted';
@@ -70,3 +71,10 @@ export const PointerEvents = trait({ queue: () => [] as CanvasPointerEvent[] });
* being looked at is editor state, not something the JSX says.
*/
export const AssetSelection = trait({ id: null as string | null });
+
+/**
+ * The config of the project on disk (its package.json `diffusion` field),
+ * attached while a project is open; see `./project-config`. The handle only,
+ * like Library: the values are its own reactive state.
+ */
+export const ProjectConfig = trait(() => null as ProjectConfigStore | null);
diff --git a/apps/web/src/pages/editor.tsx b/apps/web/src/pages/editor.tsx
index 1c23464e..d954d231 100644
--- a/apps/web/src/pages/editor.tsx
+++ b/apps/web/src/pages/editor.tsx
@@ -16,6 +16,7 @@ import { useWorld } from '@diffusionstudio/koota-solid';
import { mount } from '@diffusionstudio/reconciler';
import { getDocumentEditor } from '@/engine/editor';
import { attachLibrary, isLibraryFile } from '@/engine/library';
+import { attachProjectConfig, isProjectConfigFile } from '@/engine/project-config';
import { isCacheFile } from '@diffusionstudio/assets';
import { createEditWriter } from '@/projects/edits';
import { compileProject, watchProject, projectDir } from '@/projects/host';
@@ -45,6 +46,8 @@ export function EditorPage() {
// The library first: a mounted project's `src` values name its assets.
const library = attachLibrary(world, dir);
+ // The project's own settings (package.json `diffusion`), next to the scene.
+ const config = attachProjectConfig(world, dir);
const unmount = (): void => {
// Before the entities go: what the editor changed is still owed to the
@@ -89,6 +92,10 @@ export function EditorPage() {
if (isLibraryFile(path)) {
library.load();
} else {
+ // package.json is the config and the record (`main`) in one, so a
+ // hand edit to it reloads both; the app's own config writes never
+ // reach here (main keeps them from the watcher).
+ if (isProjectConfigFile(path)) config.load();
loadProject();
}
});
@@ -97,6 +104,7 @@ export function EditorPage() {
disposed = true;
unwatch();
unmount();
+ config.dispose();
library.dispose();
});
});
diff --git a/apps/web/src/projects/host.ts b/apps/web/src/projects/host.ts
index 0a73ec39..030a77b7 100644
--- a/apps/web/src/projects/host.ts
+++ b/apps/web/src/projects/host.ts
@@ -101,6 +101,16 @@ export function writeProject(dir: string, edits: SourceEdit[]): Promise<WriteRes
return mainBridge.call(MAIN_CHANNELS.PROJECTS_WRITE, { dir, edits });
}
+/** The project's config (the `diffusion` field of its package.json), unparsed; null when absent. */
+export function readProjectConfig(dir: string): Promise<unknown> {
+ return mainBridge.call(MAIN_CHANNELS.PROJECTS_CONFIG_READ, { dir });
+}
+
+/** Replaces the project's config (null removes the field). Kept from the watcher like `writeProject`. */
+export function writeProjectConfig(dir: string, config: unknown): Promise<void> {
+ return mainBridge.call(MAIN_CHANNELS.PROJECTS_CONFIG_WRITE, { dir, config });
+}
+
/**
* Watches a project folder and calls `onChange` (debounced) when a file
* inside it changes. Returns the unwatch function.
diff --git a/packages/encoder/src/types.ts b/packages/encoder/src/types.ts
index e584cd8b..974d49ce 100644
--- a/packages/encoder/src/types.ts
+++ b/packages/encoder/src/types.ts
@@ -4,9 +4,8 @@
import type { StreamTargetChunk } from 'mediabunny';
-// The container format is part of the persisted document model (the
-// ExportSettings trait), so the runtime owns the type.
-export type { ContainerFormat } from '@diffusionstudio/runtime';
+/** Container format of the output file. */
+export type ContainerFormat = 'mp4' | 'webm' | 'ogg' | 'mov';
// Minimal FileSystemFileHandle-shaped target
export interface WritableFileTarget {
diff --git a/packages/runtime/src/capture/format.ts b/packages/runtime/src/capture/format.ts
deleted file mode 100644
index 9127dd0c..00000000
--- a/packages/runtime/src/capture/format.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-/* 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/. */
-
-// Container format for export. Lives in the runtime (not the encoder
-// package) because the ExportSettings trait persists it; the encoder
-// imports it from here.
-
-export type ContainerFormat = 'mp4' | 'webm' | 'ogg' | 'mov';
diff --git a/packages/runtime/src/capture/index.ts b/packages/runtime/src/capture/index.ts
deleted file mode 100644
index af486a5b..00000000
--- a/packages/runtime/src/capture/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-// Persisted capture model. The encoders themselves live in
-// @diffusionstudio/encoder; only what the document format needs stays here.
-export * from './format';
diff --git a/packages/runtime/src/index.ts b/packages/runtime/src/index.ts
index 21ba3118..2a3827d2 100644
--- a/packages/runtime/src/index.ts
+++ b/packages/runtime/src/index.ts
@@ -9,6 +9,5 @@ export * from './actions';
export * from './systems';
export * from './math';
export * from './media';
-export * from './capture';
export * from './fonts';
export * from './utils';
diff --git a/packages/runtime/src/traits/node.ts b/packages/runtime/src/traits/node.ts
index d4b5e73e..f0101095 100644
--- a/packages/runtime/src/traits/node.ts
+++ b/packages/runtime/src/traits/node.ts
@@ -6,9 +6,6 @@ import { trait } from 'koota';
import { GeometryType, PaintType, CaptionType, CaptionAlign } from '../constants';
-import type { VideoCodec, AudioCodec } from 'mediabunny';
-import type { ContainerFormat } from '../capture/format';
-
// Geometric primitive: RECT or TEXT (see GeometryType). Other node-like roles
// (group, audio, scene, caption) are layered on top via tag traits.
export const Geometry = trait({ value: GeometryType.RECT as GeometryType });
@@ -94,16 +91,3 @@ export const Caption = trait({
colors: () => [] as number[],
verticalAlign: undefined as CaptionAlign | undefined, // unset = the preset's default
});
-
-export const ExportSettings = trait({
- templateId: null as string | null,
- format: undefined as ContainerFormat | undefined,
- videoEnabled: undefined as boolean | undefined,
- videoCodec: undefined as VideoCodec | undefined,
- videoBitrate: undefined as number | undefined,
- videoFps: undefined as number | undefined,
- videoResolution: undefined as number | undefined,
- audioEnabled: undefined as boolean | undefined,
- audioCodec: undefined as AudioCodec | undefined,
- audioSampleRate: undefined as number | undefined,
-});