Skip to content

AI media harness for planning, generating, and editing locally

TypeScript

Use application Back for video scenes and image families

Bitticd1a3e7132a5
diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md
index 11cdb79..ef3c75d 100644
--- a/RELEASE_NOTES.md
+++ b/RELEASE_NOTES.md
@@ -23,6 +23,7 @@ Changes since 0.3.2.
## Fixes and improvements
- Video cards match Shot sizing, show the opening playback frame and open scenes on click; playback shares Timeline's prepared players. Returning to the Video tab restores the open video.
+- Application Back returns from scenes to Video and from image versions to their parent bar.
- Editing generated music creates a separate draft; cards distinguish drafts from playable songs.
- Single Shot uses previous latents only as its starting anchor, fresh noise for the middle and a generated ending anchor, avoiding repeated source imagery.
- Dependent scenes can queue behind active sources; cancelling any linked generation cancels the whole pending group.
diff --git a/src/components/ProjectWorkspace.tsx b/src/components/ProjectWorkspace.tsx
index ab06911..8e371c2 100644
--- a/src/components/ProjectWorkspace.tsx
+++ b/src/components/ProjectWorkspace.tsx
@@ -17,6 +17,7 @@ import { ExportView } from "./workspace/ExportView";
import { ImageExportView } from "./workspace/ImageExportView";
import { MusicExportView } from "./workspace/MusicExportView";
import { VideoLibraryView } from "./workspace/VideoLibraryView";
+import type { BackNavigation } from "./workspace/useBackNavigation";
import { ReferencesView } from "./workspace/ReferencesView";
import { TimelineView, type ConfigUpdate } from "./workspace/TimelineView";
import { UnsavedProjectDialog } from "./UnsavedProjectDialog";
@@ -153,6 +154,7 @@ export function ProjectWorkspace({ project, initialView, runtime = null, onBack,
const [selectedGenerationJobId, setSelectedGenerationJobId] = useState<string | undefined>(project.config.generationJobs[0]?.id);
const [videoNavigation, setVideoNavigation] = useState<{ id: string }>();
const [openVideoId, setOpenVideoId] = useState<string>();
+ const [backNavigation, setBackNavigation] = useState<BackNavigation | null>(null);
const [imageNavigation, setImageNavigation] = useState<{ id: string }>();
const [musicNavigation, setMusicNavigation] = useState<{ id: string }>();
const [referenceNavigation, setReferenceNavigation] = useState<{ id: string }>();
@@ -189,7 +191,7 @@ export function ProjectWorkspace({ project, initialView, runtime = null, onBack,
} catch { /* The session supplies the save error and keeps the dialog open. */ }
finally { setSavingToLeave(false); }
};
- const goBack = () => { if (dirty) setLeaving(true); else onBack(); };
+ const goBack = () => { if (backNavigation) backNavigation.run(); else if (dirty) setLeaving(true); else onBack(); };
/* Scene removal can come from the Generator or from Slop replacing the
project document. Keep derived disk caches honest at this shared boundary
@@ -254,7 +256,7 @@ export function ProjectWorkspace({ project, initialView, runtime = null, onBack,
<TitleBar
className="project-titlebar"
- leading={<button type="button" className="icon-button" onClick={goBack} aria-label="Back to project library" data-tooltip="Back to projects" data-tooltip-shortcut="Alt+Left" aria-keyshortcuts="Alt+ArrowLeft"><Back16 /></button>}
+ leading={<button type="button" className="icon-button" onClick={goBack} aria-label={backNavigation?.label ?? "Back to project library"} data-tooltip={backNavigation?.label ?? "Back to projects"} data-tooltip-shortcut="Alt+Left" aria-keyshortcuts="Alt+ArrowLeft"><Back16 /></button>}
title={<button type="button" className="project-title" aria-label={`Edit project settings for ${config.name}`} aria-haspopup="dialog" aria-expanded={editingProject} data-tooltip="Project settings" onClick={() => { session.dismissError(); setEditingProject(true); }}><span className="project-title__name">{config.name}</span><ChevronDown12 aria-hidden="true" /></button>}
/* Save, then Undo and Redo, right after the project's name: the commands
about the document sit with the document's title. */
@@ -303,9 +305,9 @@ export function ProjectWorkspace({ project, initialView, runtime = null, onBack,
{musicVisited && <div hidden={view !== "music"} style={{ height: "100%", display: view === "music" ? "block" : "none" }}>
<MusicView active={view === "music"} onPlayingChange={setMusicPlaying} openSong={musicNavigation} onSongOpened={() => setMusicNavigation(undefined)} config={config} folderPath={project.folderPath} onChange={changeConfig} onGenerate={(id, template) => queue.enqueueMusic(session, id, template)} onCancel={(id) => void queue.cancel(id)} workItems={projectItems.filter((item) => item.kind === "music")} />
</div>}
- {view === "editor" && <ImageEditor openImage={imageNavigation} onImageOpened={() => setImageNavigation(undefined)} config={config} folderPath={project.folderPath} onChange={changeConfig} onGenerate={(template, count) => queue.enqueueImage(session, template, count)} onGenerateCharacterSheet={(template, sourceId, options) => queue.enqueueCharacterSheet(session, template, sourceId, options)} onGenerateExtend={(template, sourceId, options) => queue.enqueueExtendImage(session, template, sourceId, options)} onCancel={(id) => queue.cancel(id)} workItems={projectItems.filter((item) => item.kind === "image")} onOpenGenerator={(jobId) => { setSelectedGenerationJobId(jobId); setVideoNavigation(jobId ? { id: jobId } : undefined); setView("generator"); }} onOpenReferences={() => setView("references")} />}
+ {view === "editor" && <ImageEditor onBackNavigationChange={setBackNavigation} openImage={imageNavigation} onImageOpened={() => setImageNavigation(undefined)} config={config} folderPath={project.folderPath} onChange={changeConfig} onGenerate={(template, count) => queue.enqueueImage(session, template, count)} onGenerateCharacterSheet={(template, sourceId, options) => queue.enqueueCharacterSheet(session, template, sourceId, options)} onGenerateExtend={(template, sourceId, options) => queue.enqueueExtendImage(session, template, sourceId, options)} onCancel={(id) => queue.cancel(id)} workItems={projectItems.filter((item) => item.kind === "image")} onOpenGenerator={(jobId) => { setSelectedGenerationJobId(jobId); setVideoNavigation(jobId ? { id: jobId } : undefined); setView("generator"); }} onOpenReferences={() => setView("references")} />}
{view === "timeline" && <TimelineView config={config} openSceneId={selectedGenerationJobId} folderPath={project.folderPath} generationCompletionTimes={generationCompletionTimes} onChange={changeConfig} onMeasured={recordMeasurement} onOpenGenerator={(jobId) => { setSelectedGenerationJobId(jobId); setVideoNavigation(jobId ? { id: jobId } : undefined); setView("generator"); }} />}
- {view === "generator" && <VideoLibraryView initialOpenVideoId={openVideoId} onOpenVideoChange={setOpenVideoId} openScene={videoNavigation} onSceneOpened={() => setVideoNavigation(undefined)} onGenerate={(submissions) => queue.enqueue(session, submissions)} onCancelGeneration={(ids) => queue.cancelScenes(session, ids)} cancellingJobIds={cancellingJobIds} config={config} folderPath={project.folderPath} generationCompletionTimes={generationCompletionTimes} runtime={runtime?.slopfab ?? null} onRuntimeChange={onGeneratorRuntimeChange} onChange={changeConfig} selectedJobId={selectedGenerationJobId} onSelectedJobChange={setSelectedGenerationJobId} onOpenTimeline={() => setView("timeline")} />}
+ {view === "generator" && <VideoLibraryView onBackNavigationChange={setBackNavigation} initialOpenVideoId={openVideoId} onOpenVideoChange={setOpenVideoId} openScene={videoNavigation} onSceneOpened={() => setVideoNavigation(undefined)} onGenerate={(submissions) => queue.enqueue(session, submissions)} onCancelGeneration={(ids) => queue.cancelScenes(session, ids)} cancellingJobIds={cancellingJobIds} config={config} folderPath={project.folderPath} generationCompletionTimes={generationCompletionTimes} runtime={runtime?.slopfab ?? null} onRuntimeChange={onGeneratorRuntimeChange} onChange={changeConfig} selectedJobId={selectedGenerationJobId} onSelectedJobChange={setSelectedGenerationJobId} onOpenTimeline={() => setView("timeline")} />}
{view === "references" && <ReferencesView openReference={referenceNavigation} onReferenceOpened={() => setReferenceNavigation(undefined)} config={config} folderPath={project.folderPath} onChange={changeConfig} onRegenerateIcon={(id) => queue.regenerateReferenceIcon(session, id)} onExportRefmod={(id, outputPath) => queue.exportReferenceRefmod(session, id, outputPath)} onGenerateBuiltinIcons={() => queue.generateBuiltinReferenceIcons(session)} onRegenerateBuiltinIcon={(id) => queue.regenerateBuiltinReferenceIcon(session, id)} pendingBuiltinIconIds={queue.pendingBuiltinIconIds()} pendingIconIds={new Set(config.references.filter((reference) => queue.isReferenceIconPending(session, reference.id)).map((reference) => reference.id))} onOpenGenerator={(jobId) => { setSelectedGenerationJobId(jobId); setVideoNavigation(jobId ? { id: jobId } : undefined); setView("generator"); }} />}
{view === "export" && <div className="project-export">
<SelectorBar aria-label="Export type" className="project-export__types" value={mediaMode} onChange={setMediaMode} items={[{ value: "video", label: "Video" }, { value: "image", label: "Image" }, { value: "music", label: "Music" }]} />
diff --git a/src/components/WorkspaceBackNavigation.integration.test.tsx b/src/components/WorkspaceBackNavigation.integration.test.tsx
new file mode 100644
index 0000000..1431bb7
--- /dev/null
+++ b/src/components/WorkspaceBackNavigation.integration.test.tsx
@@ -0,0 +1,60 @@
+// @vitest-environment jsdom
+import "@testing-library/jest-dom/vitest";
+import { cleanup, fireEvent, render, screen, within } from "@testing-library/react";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import { ProjectWorkspace } from "./ProjectWorkspace";
+import { createProjectConfig } from "../lib/project";
+import { createEmptyImage } from "../lib/imageHistory";
+import { newVideo } from "../lib/videoLibrary";
+
+vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn() }));
+vi.mock("@tauri-apps/api/event", () => ({ listen: vi.fn(async () => () => undefined) }));
+beforeEach(() => {
+ localStorage.clear();
+ vi.spyOn(HTMLMediaElement.prototype, "load").mockImplementation(() => undefined);
+});
+afterEach(() => { cleanup(); vi.restoreAllMocks(); });
+const project = () => createProjectConfig({ name: "Back navigation", prompt: "Walk", aspectRatio: "16:9", resolution: "416p", targetDurationSeconds: 30 });
+
+it("uses application Back and Alt+Left for scenes, clears the action on tab switches and preserves the project exit guard", () => {
+ const config = project(), onBack = vi.fn();
+ config.videos = [{ ...newVideo(null), title: "Film", sceneIds: config.generationJobs.map((scene) => scene.id) }];
+ const view = render(<ProjectWorkspace project={{ folderPath: "D:/Back", config }} initialView="generator" onBack={onBack} onSave={async () => {}} />);
+ fireEvent.change(screen.getByRole("textbox", { name: "Video title" }), { target: { value: "Renamed film" } });
+ fireEvent.click(screen.getByRole("button", { name: "Open Renamed film" }));
+ expect(within(view.container.querySelector(".video-scenes")!).queryByRole("button", { name: "Back to Video" })).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "Back to Video" }));
+ expect(screen.getByRole("button", { name: "Open Renamed film" })).toBeInTheDocument();
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument(); expect(onBack).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole("button", { name: "Open Renamed film" }));
+ fireEvent.click(screen.getByRole("tab", { name: "References" }));
+ expect(screen.getByRole("button", { name: "Back to project library" })).toBeInTheDocument();
+ fireEvent.click(screen.getByRole("tab", { name: "Video" }));
+ expect(screen.getByRole("button", { name: "Back to Video" })).toBeInTheDocument();
+ fireEvent.keyDown(document.body, { key: "ArrowLeft", code: "ArrowLeft", altKey: true });
+ expect(screen.getByRole("button", { name: "Open Renamed film" })).toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "Back to project library" }));
+ expect(screen.getByRole("dialog")).toBeInTheDocument(); expect(onBack).not.toHaveBeenCalled();
+});
+
+it("uses application Back to show parent images, then restores the project back action", () => {
+ let config = createEmptyImage(project());
+ const root = config.imageScene!.outputAssetId!;
+ config = createEmptyImage(config, undefined, root);
+ const child = config.imageScene!.outputAssetId!;
+ const onBack = vi.fn();
+ render(<ProjectWorkspace project={{ folderPath: "D:/Images", config }} initialView="editor" onBack={onBack} onSave={async () => {}} />);
+ const bar = screen.getByLabelText("Generated images");
+ expect(bar.querySelector(`[data-image-asset="${child}"]`)).toBeInTheDocument();
+ expect(within(bar).queryByRole("button", { name: "Back to all images" })).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "Back to all images" }));
+ expect(bar.querySelector(`[data-image-asset="${child}"]`)).not.toBeInTheDocument();
+ expect(bar.querySelector(`[data-image-asset="${root}"]`)).toHaveAttribute("aria-pressed", "true");
+ expect(onBack).not.toHaveBeenCalled();
+ // Opening the family again registers the keyboard action too.
+ fireEvent.click(bar.querySelector(`[data-image-asset="${root}"]`)!);
+ expect(screen.getByRole("button", { name: "Back to all images" })).toBeInTheDocument();
+ fireEvent.keyDown(document.body, { key: "ArrowLeft", code: "ArrowLeft", altKey: true });
+ expect(bar.querySelector(`[data-image-asset="${child}"]`)).not.toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Back to project library" })).toBeInTheDocument();
+});
diff --git a/src/components/workspace/ImageBar.tsx b/src/components/workspace/ImageBar.tsx
index 89f01df..9d4253d 100644
--- a/src/components/workspace/ImageBar.tsx
+++ b/src/components/workspace/ImageBar.tsx
@@ -4,6 +4,7 @@ import type { ProjectAsset } from "../../lib/project";
import { isWorkActive, type WorkItem } from "../../lib/workQueue";
import { ChevronLeft16, Edit11, Image24 } from "../ui/icons";
import { ReferenceImage } from "./ReferenceImage";
+import { useBackNavigation, type BackNavigationChange } from "./useBackNavigation";
import "../../styles/image-editor.css";
/* The strip of an image project's images along the foot of the Editor and the
@@ -15,8 +16,9 @@ import "../../styles/image-editor.css";
An image regenerated or edited from another joins that image's family. The
bar lists the primary images; while an image with a family is selected it
- shows just that family — the primary first, then the other versions — with
- a back button at its leading edge that returns to all primary images. */
+ shows just that family — the primary first, then the other versions.
+ The application back button returns to primaries; standalone bars keep a
+ local back button. */
export const ImageBar = forwardRef<HTMLDivElement | null, {
images: ProjectAsset[];
selectedId: string | null | undefined;
@@ -24,7 +26,8 @@ export const ImageBar = forwardRef<HTMLDivElement | null, {
workItems?: readonly WorkItem[];
onSelect: (id: string) => void;
onMenu?: (id: string | null, x: number, y: number, inFamily: boolean) => void;
-}>(function ImageBar({ images, selectedId, folderPath, workItems = [], onSelect, onMenu }, ref) {
+ onBackNavigationChange?: BackNavigationChange;
+}>(function ImageBar({ images, selectedId, folderPath, workItems = [], onSelect, onMenu, onBackNavigationChange }, ref) {
const bar = useRef<HTMLDivElement>(null);
useImperativeHandle(ref, () => bar.current as HTMLDivElement);
@@ -35,6 +38,8 @@ export const ImageBar = forwardRef<HTMLDivElement | null, {
const [showAll, setShowAll] = useState(false);
useEffect(() => setShowAll(false), [selectedId]);
const inFamily = !showAll && family.length > 1;
+ const goBack = () => { setShowAll(true); bar.current?.focus(); };
+ useBackNavigation(onBackNavigationChange, inFamily ? "Back to all images" : null, goBack);
const primaries = images.filter((asset) => imageFamilyRoot(images, asset.id) === asset.id);
const shown = inFamily ? family : primaries;
const pressed = inFamily ? selectedId : root;
@@ -113,8 +118,8 @@ export const ImageBar = forwardRef<HTMLDivElement | null, {
const bounds = event.currentTarget.getBoundingClientRect();
onMenu(null, bounds.left, bounds.top, inFamily);
}}>
- {inFamily && <button type="button" className="image-results__back" aria-label="Back to all images" data-tooltip="All images"
- onClick={() => { setShowAll(true); bar.current?.focus(); }}><ChevronLeft16 aria-hidden="true" /></button>}
+ {inFamily && !onBackNavigationChange && <button type="button" className="image-results__back" aria-label="Back to all images" data-tooltip="All images"
+ onClick={goBack}><ChevronLeft16 aria-hidden="true" /></button>}
{shown.map((asset) => <button key={asset.id} type="button" data-image-asset={asset.id} data-tooltip={asset.name}
aria-label={`View ${asset.name}${!inFamily && childCount(asset.id) ? `, ${childCount(asset.id) + 1} versions` : ""}`} aria-pressed={asset.id === pressed} aria-busy={pending.has(asset.id)}
onContextMenu={onMenu && ((event) => { event.preventDefault(); event.stopPropagation(); onMenu(asset.id, event.clientX, event.clientY, inFamily); })}
diff --git a/src/components/workspace/ImageEditor.tsx b/src/components/workspace/ImageEditor.tsx
index c2e6872..ccabfe3 100644
--- a/src/components/workspace/ImageEditor.tsx
+++ b/src/components/workspace/ImageEditor.tsx
@@ -22,6 +22,7 @@ import { ReferenceImage } from "./ReferenceImage";
import { PromptTextField } from "./PromptTextField";
import { ReferenceIcon } from "./ReferenceIcon";
import { ImageBar } from "./ImageBar";
+import type { BackNavigationChange } from "./useBackNavigation";
import { CharacterSheetSettings } from "./CharacterSheetSettings";
import { ExtendSettings } from "./ExtendSettings";
import { ExtendCanvas } from "./ExtendCanvas";
@@ -52,7 +53,7 @@ function UsedImageSeed({ id, seed, onError }: { id: string; seed: number | undef
</PropRow>;
}
-export function ImageEditor({ config, folderPath, onChange: changeConfig, onGenerate, onGenerateCharacterSheet, onGenerateExtend, onCancel, onOpenGenerator, onOpenReferences, workItems = [], openImage, onImageOpened }: {
+export function ImageEditor({ config, folderPath, onChange: changeConfig, onGenerate, onGenerateCharacterSheet, onGenerateExtend, onCancel, onOpenGenerator, onOpenReferences, workItems = [], openImage, onImageOpened, onBackNavigationChange }: {
config: ProjectConfig; folderPath: string; onChange: (update: ConfigUpdate) => void;
onGenerate: (template: GeneratorTemplate, count: number) => void; onCancel: (id: string) => Promise<void>; workItems?: readonly WorkItem[];
onGenerateCharacterSheet?: (template: GeneratorTemplate, sourceId: string, options: CharacterSheetOptions) => void;
@@ -61,6 +62,7 @@ export function ImageEditor({ config, folderPath, onChange: changeConfig, onGene
onOpenReferences?: () => void;
openImage?: { id: string };
onImageOpened?: () => void;
+ onBackNavigationChange?: BackNavigationChange;
}) {
const scene = useMemo(() => config.imageScene ?? { ...createImageScene(config.brief.prompt), steps: selectedImageGeneratorTemplate().defaultSteps }, [config.imageScene, config.brief.prompt]);
const settings = imageSettings(config);
@@ -777,7 +779,7 @@ export function ImageEditor({ config, folderPath, onChange: changeConfig, onGene
</div></div>}
{(error || work?.error) && <InfoBar className="image-error" severity="error" title="Couldn’t update the image" message={error ?? work?.error ?? ""} onClose={error ? () => setError(null) : undefined} />}
<div className="image-status" role="status">{active && <ProgressBar value={work.progress * 100} aria-label="Image generation progress" />}<span>{active ? work.detail : extendMode && extendOptions ? `Zoom: ${extendSize?.width ?? "-"} \u00d7 ${extendSize?.height ?? "-"} px` : templateSnapshot ? `${templateSnapshot.kind === "extend" ? "Zoom" : "Character sheet"} · ${width} × ${height} px` : imageRoot ? editingBlocked ?? editPlan?.error ?? `${width} × ${height} · ${editPlan?.edits.length} edits in hierarchy order` : inputBlocked ?? (!isTauri() ? "Image generation is available in the desktop app." : `${width} × ${height}${isMiniMaxH3 ? "" : " · Placement boxes guide the prompt"}`)}</span></div>
- <ImageBar ref={imageResults} workItems={workItems} images={images} selectedId={scene.outputAssetId} folderPath={folderPath} onSelect={selectImage}
+ <ImageBar ref={imageResults} onBackNavigationChange={onBackNavigationChange} workItems={workItems} images={images} selectedId={scene.outputAssetId} folderPath={folderPath} onSelect={selectImage}
onMenu={(id, x, y, inFamily) => { setContextMenu(null); setImageMenu({ id, x, y, inFamily, source: "bar" }); }} />
</section>
<Splitter {...inspectorPane.splitterProps} reverse aria-label="Resize inspector" />
diff --git a/src/components/workspace/VideoLibraryView.test.tsx b/src/components/workspace/VideoLibraryView.test.tsx
index 7f0070e..3f66d9f 100644
--- a/src/components/workspace/VideoLibraryView.test.tsx
+++ b/src/components/workspace/VideoLibraryView.test.tsx
@@ -9,6 +9,7 @@ import { PreviewSources } from "../../lib/exportPipeline";
import { shotPoster } from "./ShotThumbnail";
import { VideoLibraryView } from "./VideoLibraryView";
import { VideoPlayback } from "./VideoPlayback";
+import type { BackNavigation } from "./useBackNavigation";
import { choose } from "./comboTestUtils";
vi.mock("./ShotThumbnail", async (original) => ({ ...await original<typeof import("./ShotThumbnail")>(), shotPoster: vi.fn(async () => ({ poster: "data:image/jpeg;base64,preview", failed: false })) }));
@@ -29,7 +30,10 @@ afterEach(() => { cleanup(); vi.restoreAllMocks(); vi.clearAllMocks(); vi.unstub
const project = () => createProjectConfig({ name: "Library", prompt: "", resolution: "416p", aspectRatio: "16:9", targetDurationSeconds: 30 });
function mount(config = project(), openScene?: { id: string }) {
let latest = config;
- function Harness() { const [value, setValue] = useState(config); latest = value; return <VideoLibraryView config={value} folderPath="D:/Project" onChange={setValue} onOpenTimeline={() => {}} openScene={openScene} />; }
+ function Harness() {
+ const [value, setValue] = useState(config), [back, setBack] = useState<BackNavigation | null>(null); latest = value;
+ return <>{back && <button onClick={back.run}>{back.label}</button>}<VideoLibraryView onBackNavigationChange={setBack} config={value} folderPath="D:/Project" onChange={setValue} onOpenTimeline={() => {}} openScene={openScene} /></>;
+ }
return { ...render(<Harness />), config: () => latest };
}
@@ -70,9 +74,11 @@ it("restores the open video after leaving the tab, respects Back and lets scene
function Harness() {
const [visible, setVisible] = useState(true), [openId, setOpenId] = useState<string>();
const [openScene, setOpenScene] = useState<{ id: string }>();
+ const [back, setBack] = useState<BackNavigation | null>(null);
return <><button onClick={() => setVisible(!visible)}>Switch tab</button><button onClick={() => { setOpenScene({ id: "b" }); setVisible(true); }}>Open scene B</button>
+ {back && <button onClick={back.run}>{back.label}</button>}
{visible && <VideoLibraryView config={config} folderPath="D:/Project" onChange={() => {}} onOpenTimeline={() => {}}
- initialOpenVideoId={openId} onOpenVideoChange={setOpenId} openScene={openScene} onSceneOpened={() => setOpenScene(undefined)} />}</>;
+ onBackNavigationChange={setBack} initialOpenVideoId={openId} onOpenVideoChange={setOpenId} openScene={openScene} onSceneOpened={() => setOpenScene(undefined)} />}</>;
}
render(<Harness />);
const switchTab = () => fireEvent.click(screen.getByRole("button", { name: "Switch tab" }));
diff --git a/src/components/workspace/VideoLibraryView.tsx b/src/components/workspace/VideoLibraryView.tsx
index e39f90a..a32ed3f 100644
--- a/src/components/workspace/VideoLibraryView.tsx
+++ b/src/components/workspace/VideoLibraryView.tsx
@@ -11,12 +11,13 @@ import { GeneratorView } from "./GeneratorView";
import { VideoPlayback, videoPlaylist } from "./VideoPlayback";
import { VideoPoster } from "./VideoPoster";
import { PromptTextField } from "./PromptTextField";
+import { useBackNavigation, type BackNavigationChange } from "./useBackNavigation";
const VIDEO_DRAG = "application/x-slopus-video";
const sourceValue = (source: VideoSource | null | undefined) => source ? `${source.kind}:${source.id}` : "";
const parseSource = (value: string): VideoSource | null => value ? { kind: value.startsWith("asset:") ? "asset" : "reference", id: value.slice(value.indexOf(":") + 1) } : null;
-export function VideoLibraryView(props: ComponentProps<typeof GeneratorView> & { openScene?: { id: string }; onSceneOpened?: () => void; initialOpenVideoId?: string; onOpenVideoChange?: (id: string | undefined) => void }) {
+export function VideoLibraryView(props: ComponentProps<typeof GeneratorView> & { openScene?: { id: string }; onSceneOpened?: () => void; initialOpenVideoId?: string; onOpenVideoChange?: (id: string | undefined) => void; onBackNavigationChange?: BackNavigationChange }) {
const { config, onChange, folderPath } = props;
const latest = useRef(config); latest.current = config;
const videos = videoLibrary(config), folders = config.videoFolders ?? [];
@@ -32,6 +33,7 @@ export function VideoLibraryView(props: ComponentProps<typeof GeneratorView> & {
const visible = videos.filter((video) => (video.folderId ?? null) === currentFolderId);
const selected = visible.find((video) => video.id === selectedId) ?? visible[0];
const open = videos.find((video) => video.id === openId);
+ useBackNavigation(props.onBackNavigationChange, open ? "Back to Video" : null, () => setOpenId(undefined));
useEffect(() => { props.onOpenVideoChange?.(open?.id); }, [open?.id, props.onOpenVideoChange]);
const playing = videos.find((video) => video.id === playback?.id);
const breadcrumbs: { id: string | null; name: string }[] = [];
@@ -85,7 +87,7 @@ export function VideoLibraryView(props: ComponentProps<typeof GeneratorView> & {
];
if (open) return <div className="video-scenes">
<GeneratorView {...props} key={open.id} config={{ ...config, videos }} sceneIds={open.sceneIds} selectedJobId={open.sceneIds.includes(props.selectedJobId ?? "") ? props.selectedJobId : undefined}
- toolbarStart={<><button type="button" className="secondary-button" onClick={() => setOpenId(undefined)}>Back to Video</button><strong className="video-scenes__title" title={open.title}>{open.title}</strong></>}
+ toolbarStart={<strong className="video-scenes__title" title={open.title}>{open.title}</strong>}
onChange={(next, key) => onChange(mergeVideoScenes(latest.current, open.id, next), key)} />
</div>;
return <div className="video-library-view" style={pane.style}>
diff --git a/src/components/workspace/useBackNavigation.ts b/src/components/workspace/useBackNavigation.ts
new file mode 100644
index 0000000..52d25f8
--- /dev/null
+++ b/src/components/workspace/useBackNavigation.ts
@@ -0,0 +1,14 @@
+import { useEffect, useRef } from "react";
+
+export interface BackNavigation { label: string; run: () => void }
+export type BackNavigationChange = (navigation: BackNavigation | null) => void;
+
+/** A mounted view temporarily supplies the application back button's action. */
+export function useBackNavigation(onChange: BackNavigationChange | undefined, label: string | null, run: () => void) {
+ const action = useRef(run);
+ action.current = run;
+ useEffect(() => {
+ onChange?.(label ? { label, run: () => action.current() } : null);
+ return () => onChange?.(null);
+ }, [onChange, label]);
+}