Skip to content

The VS Code of video editing, built for agents.

TypeScript

Refactor command handling and UI components

konstantin-paulusbb4ac3bdd810
diff --git a/apps/web/src/app.tsx b/apps/web/src/app.tsx
index 7e6527b2..cc1b92f9 100644
--- a/apps/web/src/app.tsx
+++ b/apps/web/src/app.tsx
@@ -9,6 +9,8 @@ import { Toaster } from "@/components/ui/sonner";
import { AppContextMenu } from "@/components/app-context-menu";
import { AuthProvider, useAuth } from '@/context/auth';
+import { CommandsProvider } from '@/context/commands';
+import { CommandPalette } from '@/components/commands';
import { PersistRoute } from '@/lib/persist-route';
import { useColorMode } from "@kobalte/core";
import { mainBridge } from "@/lib/ipc";
@@ -97,11 +99,14 @@ function App() {
<ColorModeProvider initialColorMode="dark">
<AppContextMenu>
<AuthProvider>
- {props.children}
- <BootSplash />
- <UpgradeDialog />
- <PurchaseSuccess />
- <EditorApi />
+ <CommandsProvider>
+ {props.children}
+ <CommandPalette />
+ <BootSplash />
+ <UpgradeDialog />
+ <PurchaseSuccess />
+ <EditorApi />
+ </CommandsProvider>
</AuthProvider>
</AppContextMenu>
<Toaster />
diff --git a/apps/web/src/assets/icons/tool.actions-spotlight.svg b/apps/web/src/assets/icons/tool.actions-spotlight.svg
new file mode 100644
index 00000000..9c9ec2da
--- /dev/null
+++ b/apps/web/src/assets/icons/tool.actions-spotlight.svg
@@ -0,0 +1,6 @@
+<svg viewBox="0 0 25 25" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M5.7 7.3L7.3 5.7Q8.5 4.5 9.7 5.7L11.3 7.3Q12.5 8.5 11.3 9.7L9.7 11.3Q8.5 12.5 7.3 11.3L5.7 9.7Q4.5 8.5 5.7 7.3Z" stroke="currentColor"/>
+<path d="M16.5 6V11M14 8.5H19" stroke="currentColor" stroke-linecap="round"/>
+<rect x="5.5" y="14.5" width="6" height="6" rx="1.5" stroke="currentColor"/>
+<circle cx="16.5" cy="17.5" r="3" stroke="currentColor"/>
+</svg>
diff --git a/apps/web/src/components/canvas/action-bar.tsx b/apps/web/src/components/canvas/action-bar.tsx
new file mode 100644
index 00000000..01bba4a2
--- /dev/null
+++ b/apps/web/src/components/canvas/action-bar.tsx
@@ -0,0 +1,148 @@
+/* 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 bar over the canvas, above the toolbar, that a tool or a command puts
+// up while it works: what it applies to, and the way out. The pieces here are
+// what bars share; what goes between them is each bar's own.
+
+import { Match, Show, Switch, onCleanup, onMount } from "solid-js";
+import { useTrait, useWorld } from "@diffusionstudio/koota-solid";
+import { Name } from "@diffusionstudio/runtime";
+import { Button } from "@/components/ui/button";
+import { Icon } from "@/components/ui/icon";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import { getClipFallbackName } from "@/engine/timeline/style";
+import { cx } from "@/lib/cva";
+
+import type { Entity } from "koota";
+import type { JSX } from "solid-js";
+
+export function ActionBar(props: { class?: string; children: JSX.Element }) {
+ return (
+ <div
+ class={cx(
+ "absolute bottom-16 left-1/2 -translate-x-1/2 z-10 rounded-xl px-1.5 py-1 bg-background border border-border flex gap-1 items-center",
+ props.class,
+ )}
+ >
+ {props.children}
+ </div>
+ );
+}
+
+/**
+ * Whether a key press is the bar's to answer: not one typed into a field,
+ * nor one an open menu, popover or dialog has the focus for — Esc there
+ * closes that, not the bar.
+ */
+export function isBarKey(event: KeyboardEvent): boolean {
+ const target = event.target;
+ if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) return false;
+ if (!(target instanceof HTMLElement)) return true;
+ return !target.isContentEditable && !target.closest('[role="dialog"], [role="menu"], [role="listbox"]');
+}
+
+/**
+ * Calls `handler` on the key presses that `matches`, while the calling
+ * component is mounted, ahead of the editor's shortcuts, which then never
+ * see them: ⌘↵ and Esc mean something else there.
+ */
+export function useBarKey(matches: (event: KeyboardEvent) => boolean, handler: () => void): void {
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (!matches(event) || !isBarKey(event)) return;
+ event.preventDefault();
+ event.stopPropagation();
+ handler();
+ };
+
+ onMount(() => window.addEventListener("keydown", onKeyDown, true));
+ onCleanup(() => window.removeEventListener("keydown", onKeyDown, true));
+}
+
+type ActionBarTargetProps = {
+ /** What the action is applied to. */
+ nodes: Entity[];
+ /** What it does to them: "Upscale". */
+ verb: string;
+ /** Them, counted: "3 layers". */
+ plural?: string;
+ /** What to select, while nothing it applies to is. */
+ empty: string;
+};
+
+/** What the bar's action applies to: the node by name, or how many; what to select while there are none. */
+export function ActionBarTarget(props: ActionBarTargetProps) {
+ return (
+ <span class="px-2 text-xs text-muted-foreground whitespace-nowrap">
+ <Switch>
+ <Match when={props.nodes.length === 0}>{props.empty}</Match>
+ <Match when={props.nodes.length === 1}>
+ {props.verb} <NodeName node={props.nodes[0]!} />
+ </Match>
+ <Match when={props.nodes.length > 1}>
+ {props.verb} <span class="text-foreground">{props.nodes.length} {props.plural ?? "layers"}</span>
+ </Match>
+ </Switch>
+ </span>
+ );
+}
+
+function NodeName(props: { node: Entity }) {
+ const world = useWorld();
+ const name = useTrait(() => props.node, Name);
+ return <span class="text-foreground">{name()?.value || getClipFallbackName(world, props.node)}</span>;
+}
+
+/** What confirming costs, once that is known. */
+export function ActionBarCredits(props: { credits: number | undefined }) {
+ return (
+ <Show when={props.credits !== undefined}>
+ <span class="flex items-center pr-2 text-xs text-muted-foreground tabular-nums whitespace-nowrap">
+ <Icon name="ai-credits-small" />
+ {props.credits!.toLocaleString()}
+ </span>
+ </Show>
+ );
+}
+
+export function ActionBarCancel(props: { onCancel(): void }) {
+ return (
+ <Tooltip>
+ <TooltipTrigger as={Button} variant="ghost" class="text-muted-foreground" onClick={() => props.onCancel()}>
+ Cancel
+ </TooltipTrigger>
+ <TooltipContent shortcut="Esc">Cancel</TooltipContent>
+ </Tooltip>
+ );
+}
+
+type ActionBarConfirmProps = {
+ onConfirm(): void;
+ disabled?: boolean;
+ /** What confirming does, on hover. */
+ hint?: JSX.Element;
+ /** The button's label; "Confirm" when left out. */
+ children?: JSX.Element;
+};
+
+/** The bar's go-ahead, on ⌘↵ as well as on a click. */
+export function ActionBarConfirm(props: ActionBarConfirmProps) {
+ // ⌘↵ is the bar's while it has a Confirm, even a disabled one: the editor
+ // would wrap the selection in a scene.
+ useBarKey(
+ (event) => event.key === "Enter" && (event.metaKey || event.ctrlKey) && !event.shiftKey && !event.altKey,
+ () => {
+ if (!props.disabled) props.onConfirm();
+ },
+ );
+
+ return (
+ <Tooltip>
+ <TooltipTrigger as={Button} disabled={props.disabled} onClick={() => props.onConfirm()}>
+ {props.children ?? "Confirm"}
+ </TooltipTrigger>
+ <TooltipContent shortcut="⌘↵">{props.hint ?? "Confirm"}</TooltipContent>
+ </Tooltip>
+ );
+}
diff --git a/apps/web/src/components/canvas/canvas.tsx b/apps/web/src/components/canvas/canvas.tsx
index 5d2bdce9..92d7ee43 100644
--- a/apps/web/src/components/canvas/canvas.tsx
+++ b/apps/web/src/components/canvas/canvas.tsx
@@ -8,6 +8,7 @@ import { CameraController, EngineCanvas } from "@/engine";
import { insertAsset } from "@/engine/insert-asset";
import { droppedFiles, importFiles } from "@/engine/asset-actions";
import { Toolbar } from "./toolbar";
+import { CanvasCommands } from "@/components/commands";
import { DesktopAppBanner } from "./desktop-app-banner";
import { toast } from "somoto"
import { SceneInitOverlay } from "./scene-init-overlay";
@@ -75,6 +76,7 @@ export function Canvas() {
on:dragover={handleDragOver}
>
<Toolbar />
+ <CanvasCommands />
<DesktopAppBanner />
<SceneInitOverlay />
<EngineCanvas />
diff --git a/apps/web/src/components/canvas/clip-path-bar.tsx b/apps/web/src/components/canvas/clip-path-bar.tsx
index 50340330..6d1e1add 100644
--- a/apps/web/src/components/canvas/clip-path-bar.tsx
+++ b/apps/web/src/components/canvas/clip-path-bar.tsx
@@ -9,6 +9,7 @@ import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { useDerived } from "@/engine/hooks";
+import { ActionBar } from "./action-bar";
import { applyClipPaths, cancelClipPath, getClipPathPicks, getClipPathTarget } from "@/engine/clip-path";
import type { Entity } from "koota";
@@ -33,7 +34,7 @@ export function ClipPathBar() {
return (
<Show when={target()}>
{(node) => (
- <div class="absolute bottom-16 left-1/2 -translate-x-1/2 z-10 rounded-xl px-1.5 py-1 bg-background border border-border flex gap-1 items-center">
+ <ActionBar>
<span class="px-2 text-xs text-muted-foreground whitespace-nowrap">
{picks().length === 0
? "Pick a shape to use as the clipping source"
@@ -52,7 +53,7 @@ export function ClipPathBar() {
</TooltipTrigger>
<TooltipContent shortcut="⌘↵">Clip <TargetName target={node()} /></TooltipContent>
</Tooltip>
- </div>
+ </ActionBar>
)}
</Show>
);
diff --git a/apps/web/src/components/canvas/object-mask-bar.tsx b/apps/web/src/components/canvas/object-mask-bar.tsx
index ccd030e0..d4c57195 100644
--- a/apps/web/src/components/canvas/object-mask-bar.tsx
+++ b/apps/web/src/components/canvas/object-mask-bar.tsx
@@ -21,6 +21,7 @@ import {
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { cx } from "@/lib/cva";
+import { ActionBar } from "./action-bar";
import { useDerived, useObjectMaskTool } from "@/engine/hooks";
import {
cancelObjectMask,
@@ -113,7 +114,7 @@ export function ObjectMaskBar() {
};
return (
- <div class="absolute bottom-16 left-1/2 -translate-x-1/2 z-10 rounded-xl px-1.5 py-1 bg-background border border-border flex gap-1 items-center">
+ <ActionBar>
<ModelMenu disabled={busy()} />
<Separator orientation="vertical" class="min-h-5" />
<ModePopover />
@@ -131,7 +132,7 @@ export function ObjectMaskBar() {
</TooltipTrigger>
<TooltipContent shortcut="⌘↵"></TooltipContent>
</Tooltip>
- </div>
+ </ActionBar>
);
}
diff --git a/apps/web/src/components/canvas/toolbar.tsx b/apps/web/src/components/canvas/toolbar.tsx
index 0ee6de6d..5da15f62 100644
--- a/apps/web/src/components/canvas/toolbar.tsx
+++ b/apps/web/src/components/canvas/toolbar.tsx
@@ -15,14 +15,15 @@ import {
DropdownMenuShortcut,
} from "@/components/ui/dropdown-menu";
import { PromptInput } from "../genai/prompt-input";
-import { ActionBar } from "../genai/action-bar";
+import { CommandBar } from "../commands";
import { ObjectMaskBar } from "./object-mask-bar";
import { ClipPathBar } from "./clip-path-bar";
-import { For, Match, Show, Switch, createEffect, createMemo, createSignal } from "solid-js";
+import { For, Match, Show, Switch, createEffect, createMemo, createSignal, on } from "solid-js";
import { Tool, ToolType } from "@diffusionstudio/runtime";
import { useWorld } from "@diffusionstudio/koota-solid";
-import { clearClipPathTarget, useTool } from "@/engine";
+import { cancelClipPath, cancelObjectMask, clearClipPathTarget, useTool } from "@/engine";
import { usePromptInput } from "@/context/prompt-input";
+import { useCommands } from "@/context/commands";
const CURSOR_TOOLS = [
{ tool: ToolType.MOVE, label: 'Move', shortcut: 'V', icon: 'move', menuIcon: 'move-small' },
@@ -44,7 +45,8 @@ const [lastShapeTool, setLastShapeTool] = createSignal<ShapeTool>(SHAPE_TOOLS[0]
export function Toolbar() {
const world = useWorld();
- const { promptInputOpen, promptInputConfig, openPromptInput, setPromptInputOpen } = usePromptInput();
+ const { promptInputOpen, promptInputConfig, setPromptInputOpen } = usePromptInput();
+ const commands = useCommands();
const selectedTool = useTool();
const cursorTool = createMemo(() => CURSOR_TOOLS.find((cursor) => cursor.tool === selectedTool()));
const shapeTool = createMemo(() => SHAPE_TOOLS.find((shape) => shape.tool === selectedTool()));
@@ -62,6 +64,20 @@ export function Toolbar() {
}
});
+ // One bar over the canvas at a time, whichever came up last: a command's
+ // bar puts down the prompt box and the tools that have bars of their own,
+ // and either of those coming up takes the command's bar down.
+ createEffect(on(commands.active, (command) => {
+ if (!command) return;
+ setPromptInputOpen(false);
+ if (selectedTool() === ToolType.OBJECT_MASK) cancelObjectMask(world);
+ if (selectedTool() === ToolType.CLIP_PATH) cancelClipPath(world);
+ }));
+
+ createEffect(on([promptInputOpen, selectedTool], ([open, tool]) => {
+ if (open || tool === ToolType.OBJECT_MASK || tool === ToolType.CLIP_PATH) commands.close();
+ }));
+
const handleToolChange = (tool: ToolType) => {
world.set(Tool, { value: tool });
}
@@ -72,7 +88,7 @@ export function Toolbar() {
<PromptInput initialConfig={promptInputConfig()} />
</Show>
<Show when={!promptInputOpen()}>
- <Switch fallback={<ActionBar openPromptInput={openPromptInput} />}>
+ <Switch fallback={<CommandBar />}>
<Match when={selectedTool() === ToolType.OBJECT_MASK}>
<ObjectMaskBar />
</Match>
@@ -215,10 +231,6 @@ export function Toolbar() {
</TooltipTrigger>
<TooltipContent shortcut="T">Text</TooltipContent>
</Tooltip>
- <Separator
- orientation="vertical"
- class="data-[orientation=vertical]:h-5 rounded-md"
- />
<Tooltip>
<TooltipTrigger
as={Button}
@@ -231,6 +243,19 @@ export function Toolbar() {
</TooltipTrigger>
<TooltipContent>AI generate</TooltipContent>
</Tooltip>
+ <Separator orientation="vertical" class="min-h-5" />
+ <Tooltip>
+ <TooltipTrigger
+ as={Button}
+ size="icon-square"
+ variant="ghost"
+ class="text-muted-foreground"
+ onClick={() => commands.setPaletteOpen(true)}
+ >
+ <Icon name="tool.actions-spotlight" />
+ </TooltipTrigger>
+ <TooltipContent shortcut="⌘K">Actions</TooltipContent>
+ </Tooltip>
</div>
</>
);
diff --git a/apps/web/src/components/commands/auto-captions.tsx b/apps/web/src/components/commands/auto-captions.tsx
new file mode 100644
index 00000000..14b72231
--- /dev/null
+++ b/apps/web/src/components/commands/auto-captions.tsx
@@ -0,0 +1,41 @@
+/* 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 { Separator } from "@/components/ui/separator";
+import { useCommand, useCommands } from "@/context/commands";
+import { useAutoCaptions } from "@/components/genai/use-auto-captions";
+import { ActionBar, ActionBarCancel, ActionBarConfirm, ActionBarTarget } from "@/components/canvas/action-bar";
+
+export function AutoCaptionsCommand() {
+ useCommand({
+ id: "auto-captions",
+ title: "Auto-captions",
+ group: "Media",
+ icon: "captions",
+ keywords: ["subtitles", "transcribe"],
+ bar: AutoCaptionsBar,
+ });
+
+ return null;
+}
+
+/** The active scene, captioned from its audio on Confirm. */
+function AutoCaptionsBar() {
+ const { close } = useCommands();
+ const { scene, generate } = useAutoCaptions();
+
+ const confirm = () => {
+ generate();
+ close();
+ };
+
+ return (
+ <ActionBar>
+ <ActionBarTarget nodes={scene() ? [scene()!] : []} verb="Target:" empty="Open a scene to caption" />
+ <Separator orientation="vertical" class="min-h-5" />
+ <ActionBarCancel onCancel={close} />
+ <ActionBarConfirm disabled={!scene()} onConfirm={confirm} hint="Caption" />
+ </ActionBar>
+ );
+}
diff --git a/apps/web/src/components/commands/command-bar.tsx b/apps/web/src/components/commands/command-bar.tsx
new file mode 100644
index 00000000..2a15d651
--- /dev/null
+++ b/apps/web/src/components/commands/command-bar.tsx
@@ -0,0 +1,42 @@
+/* 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 { Show, createComponent, createRoot, onCleanup, runWithOwner } from "solid-js";
+import { useCommands } from "@/context/commands";
+import { useBarKey } from "@/components/canvas/action-bar";
+
+import type { RegisteredCommand } from "@/context/commands";
+
+/** Where the bar of the command that is up goes; Esc takes it down. */
+export function CommandBar() {
+ const commands = useCommands();
+
+ return (
+ <Show when={commands.active()} keyed>
+ {(command) => <BarOf command={command} />}
+ </Show>
+ );
+}
+
+/**
+ * `command`'s bar, rendered under the component that registered the
+ * command, so it sees that component's context rather than this one's; it
+ * goes when this does.
+ */
+function BarOf(props: { command: RegisteredCommand }) {
+ const { close } = useCommands();
+ useBarKey((event) => event.key === "Escape", close);
+
+ const { command } = props;
+ let dispose!: () => void;
+ const bar = runWithOwner(command.owner, () =>
+ createRoot((disposeBar) => {
+ dispose = disposeBar;
+ return createComponent(command.bar!, {});
+ }),
+ );
+ onCleanup(() => dispose());
+
+ return <>{bar}</>;
+}
diff --git a/apps/web/src/components/commands/edit-with-prompt.tsx b/apps/web/src/components/commands/edit-with-prompt.tsx
new file mode 100644
index 00000000..8df27f9c
--- /dev/null
+++ b/apps/web/src/components/commands/edit-with-prompt.tsx
@@ -0,0 +1,26 @@
+/* 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 { useCommand } from "@/context/commands";
+import { usePromptInput } from "@/context/prompt-input";
+import { useMediaSelection } from "@/components/genai/selection";
+import { restoreConfig } from "@/components/genai/saved-config";
+
+/** Opens the prompt box on the selected images. */
+export function EditWithPromptCommand() {
+ const { openPromptInput } = usePromptInput();
+ const { imageMedia } = useMediaSelection();
+
+ useCommand({
+ id: "edit-with-prompt",
+ title: "Edit with prompt",
+ group: "Generate",
+ icon: "ai-generate",
+ keywords: ["image", "prompt", "ai"],
+ available: () => imageMedia().length > 0,
+ run: () => openPromptInput(restoreConfig("IMAGE")),
+ });
+
+ return null;
+}
diff --git a/apps/web/src/components/commands/index.tsx b/apps/web/src/components/commands/index.tsx
new file mode 100644
index 00000000..84754225
--- /dev/null
+++ b/apps/web/src/components/commands/index.tsx
@@ -0,0 +1,29 @@
+/* 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 { AutoCaptionsCommand } from "./auto-captions";
+import { EditWithPromptCommand } from "./edit-with-prompt";
+import { MakeVideoCommand } from "./make-video";
+import { RemoveBackgroundCommand } from "./remove-background";
+import { RerunCommand } from "./rerun";
+import { ReuseSettingsCommand } from "./reuse-settings";
+import { UpscaleCommand } from "./upscale";
+
+export { CommandBar } from "./command-bar";
+export { CommandPalette } from "./palette";
+
+/** The commands on the selection in the canvas: what the media can be run through, and generated from. */
+export function CanvasCommands() {
+ return (
+ <>
+ <UpscaleCommand />
+ <RemoveBackgroundCommand />
+ <AutoCaptionsCommand />
+ <EditWithPromptCommand />
+ <MakeVideoCommand />
+ <RerunCommand />
+ <ReuseSettingsCommand />
+ </>
+ );
+}
diff --git a/apps/web/src/components/commands/make-video.tsx b/apps/web/src/components/commands/make-video.tsx
new file mode 100644
index 00000000..6da3bce6
--- /dev/null
+++ b/apps/web/src/components/commands/make-video.tsx
@@ -0,0 +1,26 @@
+/* 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 { useCommand } from "@/context/commands";
+import { usePromptInput } from "@/context/prompt-input";
+import { useMediaSelection } from "@/components/genai/selection";
+import { restoreConfig } from "@/components/genai/saved-config";
+
+/** Opens the prompt box for a video, from the selected generated images. */
+export function MakeVideoCommand() {
+ const { openPromptInput } = usePromptInput();
+ const { imageMedia } = useMediaSelection();
+
+ useCommand({
+ id: "make-video",
+ title: "Make video",
+ group: "Generate",
+ icon: "film-video-export",
+ keywords: ["animate", "image to video"],
+ available: () => imageMedia().some((entry) => entry.asset?.job !== undefined),
+ run: () => openPromptInput(restoreConfig("VIDEO")),
+ });
+
+ return null;
+}
diff --git a/apps/web/src/components/commands/palette.tsx b/apps/web/src/components/commands/palette.tsx
new file mode 100644
index 00000000..105981af
--- /dev/null
+++ b/apps/web/src/components/commands/palette.tsx
@@ -0,0 +1,154 @@
+/* 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 { For, Show, createMemo, createSignal, onCleanup, onMount } from "solid-js";
+import { Dialog } from "@kobalte/core/dialog";
+import { Command as CommandPrimitive, defaultFilter } from "cmdk-solid";
+import { Icon } from "@/components/ui/icon";
+import { Kbd, KbdGroup } from "@/components/ui/kbd";
+import { useCommands } from "@/context/commands";
+
+import type { RegisteredCommand } from "@/context/commands";
+
+const offered = (command: RegisteredCommand) => command.available?.() ?? true;
+
+/**
+ * The command palette, on ⌘K: the commands on offer, by section, found by
+ * typing; the arrows pick one, Enter carries it out.
+ */
+export function CommandPalette() {
+ const commands = useCommands();
+
+ // Picking a command can hand the focus to what it opens (the prompt box),
+ // which the dialog would otherwise take back on its way out.
+ let picked = false;
+
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (event.key.toLowerCase() !== "k" || !(event.metaKey || event.ctrlKey) || event.shiftKey || event.altKey) return;
+ // Nothing on offer outside the editor yet: ⌘K is left alone there.
+ if (!commands.paletteOpen() && !commands.commands().some(offered)) return;
+
+ // Ahead of the editor, which would record the K as held.
+ event.preventDefault();
+ event.stopPropagation();
+ commands.setPaletteOpen(!commands.paletteOpen());
+ };
+
+ onMount(() => window.addEventListener("keydown", onKeyDown, true));
+ onCleanup(() => window.removeEventListener("keydown", onKeyDown, true));
+
+ const pick = (command: RegisteredCommand) => {
+ picked = true;
+ commands.execute(command);
+ };
+
+ return (
+ <Dialog open={commands.paletteOpen()} onOpenChange={commands.setPaletteOpen}>
+ <Dialog.Portal>
+ <Dialog.Overlay class="fixed inset-0 z-50 bg-overlay-soft data-[expanded]:animate-in data-[closed]:animate-out data-[closed]:fade-out-0 data-[expanded]:fade-in-0" />
+ <Dialog.Content
+ class="fixed top-[20vh] left-1/2 z-50 w-full max-w-[calc(100%-2rem)] sm:max-w-180 -translate-x-1/2 overflow-hidden rounded-xl border border-border bg-popover text-popover-foreground outline-none shadow-[0px_0px_1px_2px_rgba(0,0,0,0.12),0px_4px_12px_8px_rgba(0,0,0,0.12),0px_12px_16px_0px_rgba(0,0,0,0.16)] data-[expanded]:animate-in data-[closed]:animate-out data-[closed]:fade-out-0 data-[expanded]:fade-in-0 data-[closed]:zoom-out-[0.98] data-[expanded]:zoom-in-[0.98] duration-100"
+ onCloseAutoFocus={(event: Event) => {
+ if (picked) event.preventDefault();
+ picked = false;
+ }}
+ >
+ <Dialog.Title class="sr-only">Commands</Dialog.Title>
+ <PaletteContent onPick={pick} />
+ </Dialog.Content>
+ </Dialog.Portal>
+ </Dialog>
+ );
+}
+
+type Section = { name: string; commands: RegisteredCommand[] };
+
+/**
+ * The commands on offer that match `search`, in sections. Without a search,
+ * in the order they were registered; with one, the best match first, and the
+ * section it is in. cmdk scores, but leaves the order alone under Solid.
+ */
+function rank(commands: RegisteredCommand[], search: string): Section[] {
+ const query = search.trim();
+ const matches = commands
+ .filter(offered)
+ .map((command) => ({
+ command,
+ score: query ? defaultFilter(command.title, query, [command.group, ...(command.keywords ?? [])]) : 1,
+ }))
+ .filter((match) => match.score > 0)
+ .sort((a, b) => b.score - a.score);
+
+ const byName = new Map<string, RegisteredCommand[]>();
+ for (const { command } of matches) {
+ const section = byName.get(command.group);
+ if (section) section.push(command);
+ else byName.set(command.group, [command]);
+ }
+ return [...byName].map(([name, list]) => ({ name, commands: list }));
+}
+
+function PaletteContent(props: { onPick(command: RegisteredCommand): void }) {
+ const commands = useCommands();
+ const [search, setSearch] = createSignal("");
+
+ const sections = createMemo(() => rank(commands.commands(), search()));
+
+ return (
+ <CommandPrimitive label="Commands" loop shouldFilter={false} class="flex flex-col">
+ {/* Inset like the items below, so the icon sits over theirs and the text over their titles. */}
+ <div class="mx-2 flex h-12 shrink-0 items-center gap-1.5 border-b border-border px-1.5">
+ <Icon name="search" class="text-muted-foreground" />
+ <CommandPrimitive.Input
+ value={search()}
+ onValueChange={setSearch}
+ placeholder="Type a command or search..."
+ class="h-full min-w-0 flex-1 bg-transparent text-sm outline-hidden placeholder:text-muted-foreground"
+ />
+ {/* Enter runs the highlighted command; with nothing listed it does nothing. */}
+ <Show when={sections().length > 0}>
+ <span class="flex shrink-0 items-center gap-1.5 text-xs text-muted-foreground select-none">
+ Run
+ <Kbd>↵</Kbd>
+ </span>
+ </Show>
+ </div>
+ <CommandPrimitive.List class="max-h-[min(400px,60vh)] scroll-py-2 overflow-y-auto overflow-x-hidden px-2 pt-1 pb-2">
+ <CommandPrimitive.Empty class="py-6 text-center text-xs text-muted-foreground">
+ No commands found
+ </CommandPrimitive.Empty>
+ <For each={sections()}>
+ {(section) => (
+ <CommandPrimitive.Group
+ heading={section.name}
+ class="[&_[cmdk-group-heading]]:flex [&_[cmdk-group-heading]]:h-8 [&_[cmdk-group-heading]]:items-center [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:text-muted-foreground"
+ >
+ <For each={section.commands}>
+ {(command) => (
+ <CommandPrimitive.Item
+ value={command.id}
+ onSelect={() => props.onPick(command)}
+ class="flex h-8 cursor-default items-center gap-1.5 rounded-lg px-1.5 text-sm text-foreground outline-hidden select-none data-[selected=true]:bg-input [&_svg]:text-muted-foreground data-[selected=true]:[&_svg]:text-foreground"
+ >
+ <Show when={command.icon} fallback={<span class="size-[25px] shrink-0" />}>
+ {(icon) => <Icon name={icon()} />}
+ </Show>
+ <span class="flex-1 truncate">{command.title}</span>
+ <Show when={command.shortcut}>
+ {(keys) => (
+ <KbdGroup class="pr-1">
+ <For each={keys()}>{(key) => <Kbd>{key}</Kbd>}</For>
+ </KbdGroup>
+ )}
+ </Show>
+ </CommandPrimitive.Item>
+ )}
+ </For>
+ </CommandPrimitive.Group>
+ )}
+ </For>
+ </CommandPrimitive.List>
+ </CommandPrimitive>
+ );
+}
diff --git a/apps/web/src/components/commands/remove-background.tsx b/apps/web/src/components/commands/remove-background.tsx
new file mode 100644
index 00000000..69da62d6
--- /dev/null
+++ b/apps/web/src/components/commands/remove-background.tsx
@@ -0,0 +1,21 @@
+/* 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 { useCommand } from "@/context/commands";
+import { TransformBar } from "./transform-bar";
+
+export function RemoveBackgroundCommand() {
+ useCommand({
+ id: "remove-background",
+ title: "Remove background",
+ group: "Media",
+ icon: "ai-generate",
+ keywords: ["cutout", "matte", "transparent"],
+ bar: () => (
+ <TransformBar type="removeBackground" verb="Remove the background of" empty="Select an image to cut out" />
+ ),
+ });
+
+ return null;
+}
diff --git a/apps/web/src/components/commands/rerun.tsx b/apps/web/src/components/commands/rerun.tsx
new file mode 100644
index 00000000..0ad8cf5f
--- /dev/null
+++ b/apps/web/src/components/commands/rerun.tsx
@@ -0,0 +1,62 @@
+/* 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 { createMemo } from "solid-js";
+import { Separator } from "@/components/ui/separator";
+import { useCommand, useCommands } from "@/context/commands";
+import { useGenerate } from "@/components/genai/use-generate";
+import { useGenerationRecords } from "@/components/genai/use-generation-records";
+import { useMediaSelection } from "@/components/genai/selection";
+import {
+ ActionBar,
+ ActionBarCancel,
+ ActionBarConfirm,
+ ActionBarCredits,
+ ActionBarTarget,
+} from "@/components/canvas/action-bar";
+
+export function RerunCommand() {
+ useCommand({
+ id: "rerun",
+ title: "Rerun generation",
+ group: "Generate",
+ icon: "rerun",
+ keywords: ["regenerate", "again", "retry"],
+ bar: RerunBar,
+ });
+
+ return null;
+}
+
+/** The first generated node of the selection, generated again from the same request on Confirm. */
+function RerunBar() {
+ const { close } = useCommands();
+ const { media } = useMediaSelection();
+ const { firstJob } = useGenerationRecords();
+ const { rerun } = useGenerate();
+
+ // The node whose job `firstJob` is, once that is fetched.
+ const generated = createMemo(() => media().find((entry) => entry.asset?.job !== undefined)?.node);
+
+ const confirm = () => {
+ const job = firstJob();
+ if (!job) return;
+ rerun(job.request);
+ close();
+ };
+
+ return (
+ <ActionBar>
+ <ActionBarTarget
+ nodes={generated() ? [generated()!] : []}
+ verb="Rerun"
+ empty="Select a generated image or video"
+ />
+ <ActionBarCredits credits={firstJob()?.credits} />
+ <Separator orientation="vertical" class="min-h-5" />
+ <ActionBarCancel onCancel={close} />
+ <ActionBarConfirm disabled={!firstJob()} onConfirm={confirm} hint="Rerun" />
+ </ActionBar>
+ );
+}
diff --git a/apps/web/src/components/commands/reuse-settings.tsx b/apps/web/src/components/commands/reuse-settings.tsx
new file mode 100644
index 00000000..77423507
--- /dev/null
+++ b/apps/web/src/components/commands/reuse-settings.tsx
@@ -0,0 +1,50 @@
+/* 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 { toast } from "somoto";
+import { api } from "@/lib/api";
+import { useCommand } from "@/context/commands";
+import { usePromptInput } from "@/context/prompt-input";
+import { useMediaSelection } from "@/components/genai/selection";
+import { toConfig } from "@/components/genai/requests";
+
+/**
+ * Opens the prompt box with the settings the first selected generated image
+ * was made with. The job is fetched on pick rather than kept up with the
+ * selection, which this command is mounted for the whole time.
+ */
+export function ReuseSettingsCommand() {
+ const { openPromptInput } = usePromptInput();
+ const { imageMedia } = useMediaSelection();
+
+ const jobId = () => imageMedia().find((entry) => entry.asset?.job !== undefined)?.asset?.job;
+
+ const reuse = async () => {
+ const id = jobId();
+ if (!id) return;
+
+ try {
+ const config = toConfig((await api.jobs.get.query({ id })).request);
+ if (!config) {
+ toast("No generation config found", { description: "This asset wasn't generated with a prompt." });
+ return;
+ }
+ openPromptInput(config);
+ } catch (error) {
+ toast("Failed to load the generation", { description: error instanceof Error ? error.message : "Unknown error" });
+ }
+ };
+
+ useCommand({
+ id: "reuse-settings",
+ title: "Reuse generation settings",
+ group: "Generate",
+ icon: "reuse-settings",
+ keywords: ["prompt", "config"],
+ available: () => jobId() !== undefined,
+ run: () => void reuse(),
+ });
+
+ return null;
+}
diff --git a/apps/web/src/components/commands/transform-bar.tsx b/apps/web/src/components/commands/transform-bar.tsx
new file mode 100644
index 00000000..b3781aea
--- /dev/null
+++ b/apps/web/src/components/commands/transform-bar.tsx
@@ -0,0 +1,53 @@
+/* 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 { createMemo } from "solid-js";
+import { Separator } from "@/components/ui/separator";
+import { useCommands } from "@/context/commands";
+import { useTransforms } from "@/components/genai/use-transforms";
+import {
+ ActionBar,
+ ActionBarCancel,
+ ActionBarConfirm,
+ ActionBarCredits,
+ ActionBarTarget,
+} from "@/components/canvas/action-bar";
+
+import type { Entity } from "koota";
+import type { TransformType } from "@/components/genai/types";
+
+type TransformBarProps = {
+ type: TransformType;
+ /** What the transform does: "Upscale". */
+ verb: string;
+ /** What to select, while nothing it runs over is. */
+ empty: string;
+};
+
+/** A transform's bar: the selected media it runs over and what that costs, run on Confirm. */
+export function TransformBar(props: TransformBarProps) {
+ const { close } = useCommands();
+ const { targets, run, price } = useTransforms();
+
+ const nodes = createMemo(() => targets(props.type).map((entry) => entry.node), [], { equals: sameEntities });
+
+ const confirm = () => {
+ run(props.type);
+ close();
+ };
+
+ return (
+ <ActionBar>
+ <ActionBarTarget nodes={nodes()} verb={props.verb} empty={props.empty} />
+ <ActionBarCredits credits={price(props.type)} />
+ <Separator orientation="vertical" class="min-h-5" />
+ <ActionBarCancel onCancel={close} />
+ <ActionBarConfirm disabled={nodes().length === 0} onConfirm={confirm} hint={props.verb} />
+ </ActionBar>
+ );
+}
+
+function sameEntities(a: Entity[], b: Entity[]): boolean {
+ return a.length === b.length && a.every((entity, i) => entity === b[i]);
+}
diff --git a/apps/web/src/components/commands/upscale.tsx b/apps/web/src/components/commands/upscale.tsx
new file mode 100644
index 00000000..45d1e310
--- /dev/null
+++ b/apps/web/src/components/commands/upscale.tsx
@@ -0,0 +1,19 @@
+/* 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 { useCommand } from "@/context/commands";
+import { TransformBar } from "./transform-bar";
+
+export function UpscaleCommand() {
+ useCommand({
+ id: "upscale",
+ title: "Upscale",
+ group: "Media",
+ icon: "arrow-scale",
+ keywords: ["resolution", "enhance", "sharpen"],
+ bar: () => <TransformBar type="upscale" verb="Upscale" empty="Select an image or video to upscale" />,
+ });
+
+ return null;
+}
diff --git a/apps/web/src/components/genai/action-bar.tsx b/apps/web/src/components/genai/action-bar.tsx
deleted file mode 100644
index 16d6f723..00000000
--- a/apps/web/src/components/genai/action-bar.tsx
+++ /dev/null
@@ -1,201 +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/. */
-
-import { Button } from "@/components/ui/button";
-import { Icon } from "@/components/ui/icon";
-import { Separator } from "@/components/ui/separator";
-import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuGroup,
- DropdownMenuItem,
- DropdownMenuPortal,
- DropdownMenuTrigger,
-} from "@/components/ui/dropdown-menu";
-import { createMemo, Show, type JSX } from "solid-js";
-import { useGenerationRecords } from "./use-generation-records";
-import { useGenerate } from "./use-generate";
-import { useAutoCaptions } from "./use-auto-captions";
-import { useMediaSelection } from "./selection";
-import { useTransforms } from "./use-transforms";
-import { formatCost } from "./use-estimate";
-import { restoreConfig } from "./saved-config";
-import { toast } from "somoto";
-
-import type { GenerationConfig } from "./types";
-
-interface ActionBarProps {
- openPromptInput?(config: GenerationConfig): void;
-}
-
-export function ActionBar(props: ActionBarProps) {
- const { imageMedia, videoMedia } = useMediaSelection();
- const { run: runTransform, price } = useTransforms();
-
- const { rerun } = useGenerate();
- const { generate: autoCaptions, hasScene } = useAutoCaptions();
- const { isGenerated, totalCredits, firstJob, firstConfig } = useGenerationRecords();
-
- const isImage = createMemo(() => imageMedia().length > 0);
- const isVideo = createMemo(() => videoMedia().length > 0);
-
- const visible = createMemo(() => {
- return isImage() || isVideo() || hasScene();
- })
-
- const handleRerun = () => {
- const job = firstJob();
- if (!job) {
- toast("No generation found", { description: "This asset wasn't generated with a prompt." });
- return;
- }
-
- rerun(job.request);
- };
-
- const handleEditWithPrompt = () => {
- props.openPromptInput?.(restoreConfig("IMAGE"));
- };
-
- const handleMakeVideo = () => {
- props.openPromptInput?.(restoreConfig("VIDEO"));
- };
-
- const handleReuse = () => {
- const config = firstConfig();
- if (!config) {
- toast("No generation config found", { description: "This asset wasn't generated with a prompt." });
- return;
- }
- props.openPromptInput?.(config);
- };
-
- return (
- <>
- <Show when={visible()}>
- <div class="absolute bottom-16 left-1/2 -translate-x-1/2 z-10 rounded-xl p-1 bg-background border border-border flex gap-1 items-center">
- <Show when={hasScene()}>
- <Button variant="ghost" class="gap-0 pl-0.5 text-muted-foreground" onClick={autoCaptions}>
- <Icon name="captions" />
- Auto-Captions
- </Button>
- </Show>
- <Show when={isImage()}>
- <div class="flex gap-1 items-center">
- <TransformButton icon="ai-generate" credits={price("removeBackground")} onClick={() => runTransform("removeBackground")}>
- Remove background
- </TransformButton>
- <TransformButton icon="arrow-scale" credits={price("upscale")} onClick={() => runTransform("upscale")}>
- Upscale
- </TransformButton>
- </div>
- <Separator orientation="vertical" class="min-h-5" />
- <div class="flex gap-1 items-center">
- <Button variant="ghost" class="gap-0 pl-0.5 text-muted-foreground" onClick={handleEditWithPrompt}>
- <Icon name="ai-generate" />
- Edit with prompt
- </Button>
- <Show when={isGenerated()}>
- <DropdownMenu placement="right">
- <DropdownMenuTrigger<typeof Button>
- as={(triggerProps) => (
- <Button {...triggerProps} variant="ghost" class="gap-0 pr-0.5 text-muted-foreground">
- More
- <Icon name="chevron-down" />
- </Button>
- )}
- />
- <DropdownMenuPortal>
- <DropdownMenuContent>
- <div class="flex items-center gap-1 px-0 pr-2 h-7">
- <Icon name="ai-credits" class="text-muted-foreground" />
- <span class="text-xs text-muted-foreground">{totalCredits()} AI credits used</span>
- </div>
- <Separator class="my-1" />
- <DropdownMenuGroup>
- <DropdownMenuItem onSelect={handleMakeVideo}>
- <Icon name="film-video-export" class="mr-2 text-foreground" />
- Make video
- </DropdownMenuItem>
- <DropdownMenuItem onSelect={handleRerun}>
- <Icon name="rerun" class="mr-2 text-foreground" />
- Rerun
- </DropdownMenuItem>
- <DropdownMenuItem onSelect={handleReuse}>
- <Icon name="reuse-settings" class="mr-2 text-foreground" />
- Reuse
- </DropdownMenuItem>
- </DropdownMenuGroup>
- </DropdownMenuContent>
- </DropdownMenuPortal>
- </DropdownMenu>
- </Show>
- </div>
- </Show>
- <Show when={isVideo()}>
- <div class="flex gap-1 items-center">
- <TransformButton icon="arrow-scale" credits={price("upscale")} onClick={() => runTransform("upscale")}>
- Upscale
- </TransformButton>
- <Show when={isGenerated()}>
- <Separator orientation="vertical" class="min-h-5" />
- <DropdownMenu placement="right">
- <DropdownMenuTrigger<typeof Button>
- as={(triggerProps) => (
- <Button {...triggerProps} variant="ghost" class="gap-0 pr-0.5 text-muted-foreground">
- More
- <Icon name="chevron-down" />
- </Button>
- )}
- />
- <DropdownMenuPortal>
- <DropdownMenuContent>
- <div class="flex items-center gap-1 px-0 pr-2 h-7">
- <Icon name="ai-credits" class="text-muted-foreground" />
- <span class="text-xs text-muted-foreground">{totalCredits()} AI credits used</span>
- </div>
- <Separator class="my-1" />
- <DropdownMenuGroup>
- <DropdownMenuItem onSelect={handleRerun}>
- <Icon name="rerun" class="mr-2 text-foreground" />
- Rerun
- </DropdownMenuItem>
- </DropdownMenuGroup>
- </DropdownMenuContent>
- </DropdownMenuPortal>
- </DropdownMenu>
- </Show>
- </div>
- </Show>
- </div>
- </Show>
- </>
- );
-}
-
-type TransformButtonProps = {
- icon: string;
- /** What running it costs; a blurred stand-in while that isn't known. */
- credits: number | undefined;
- onClick(): void;
- children: JSX.Element;
-};
-
-/** A paid action, its price on hover. */
-function TransformButton(props: TransformButtonProps) {
- return (
- <Tooltip>
- <TooltipTrigger as={Button} variant="ghost" class="gap-0 pl-0.5 text-muted-foreground" onClick={props.onClick}>
- <Icon name={props.icon} />
- {props.children}
- </TooltipTrigger>
- <TooltipContent class="h-6 py-0">
- <Show when={props.credits} fallback={<span class="blur-[3px] select-none">This will cost 000 credits</span>}>
- {(credits) => formatCost(credits())}
- </Show>
- </TooltipContent>
- </Tooltip>
- );
-}
diff --git a/apps/web/src/components/genai/index.ts b/apps/web/src/components/genai/index.ts
index 6021e1f4..c58e4942 100644
--- a/apps/web/src/components/genai/index.ts
+++ b/apps/web/src/components/genai/index.ts
@@ -2,5 +2,4 @@
* 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/. */
-export * from "./action-bar";
export * from "./prompt-input";
\ No newline at end of file
diff --git a/apps/web/src/components/genai/use-auto-captions.tsx b/apps/web/src/components/genai/use-auto-captions.tsx
index 025eaf25..85e2cfb2 100644
--- a/apps/web/src/components/genai/use-auto-captions.tsx
+++ b/apps/web/src/components/genai/use-auto-captions.tsx
@@ -2,26 +2,23 @@
* 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 { createMemo } from "solid-js";
import { useWorld } from "@diffusionstudio/koota-solid";
-import { isScene } from "@diffusionstudio/runtime";
import { useProject } from "@/context/project";
import { generateCaptions } from "@/engine/generate";
-import { useSelection } from "@/engine/hooks";
+import { useActiveScene } from "@/engine/hooks";
+/** Captions for the active scene, the one being edited: selecting a scene makes it active. */
export function useAutoCaptions() {
const world = useWorld();
const project = useProject();
- const { nodes } = useSelection();
-
- const scenes = createMemo(() => nodes().filter(isScene));
- const hasScene = createMemo(() => scenes().length > 0);
+ const scene = useActiveScene();
const generate = () => {
- for (const scene of scenes()) {
- generateCaptions(world, scene, project.dir());
+ const active = scene();
+ if (active) {
+ generateCaptions(world, active, project.dir());
}
};
- return { hasScene, generate };
+ return { scene, generate };
}
diff --git a/apps/web/src/components/genai/use-transforms.ts b/apps/web/src/components/genai/use-transforms.ts
index 7aeeead4..f9e0c9d7 100644
--- a/apps/web/src/components/genai/use-transforms.ts
+++ b/apps/web/src/components/genai/use-transforms.ts
@@ -70,5 +70,5 @@ export function useTransforms() {
return prices.reduce<number>((sum, credits) => sum + credits!, 0);
};
- return { run, price };
+ return { targets, run, price };
}
diff --git a/apps/web/src/context/commands.tsx b/apps/web/src/context/commands.tsx
new file mode 100644
index 00000000..fb818893
--- /dev/null
+++ b/apps/web/src/context/commands.tsx
@@ -0,0 +1,104 @@
+/* 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 commands the palette (⌘K) offers. A command is registered by the
+// component that knows how to carry it out (see `useCommand`), mounted where
+// the context it needs is: it is on offer for as long as that component is
+// up, and its handlers and its bar see that component's context.
+
+import { createContext, createSignal, getOwner, onCleanup, useContext } from "solid-js";
+
+import type { Accessor, Component, JSX, Owner } from "solid-js";
+
+type CommandAction =
+ | {
+ /** What picking it does. */
+ run(): void;
+ bar?: never;
+ }
+ | {
+ /**
+ * The action bar picking it puts up, over the canvas until the bar
+ * closes it (see `useCommands().close`) or Esc does. For commands
+ * that need a target picked, or a go-ahead, before they run.
+ */
+ bar: Component;
+ run?: never;
+ };
+
+export type Command = CommandAction & {
+ /** Unique among the commands registered at once. */
+ id: string;
+ title: string;
+ /** The palette section it is listed under; sections come in the order they were first registered. */
+ group: string;
+ icon?: string;
+ /** More words the palette finds it by. */
+ keywords?: string[];
+ /** The keys it is bound to, one cap each (["⌘", "K"]); shown, not bound. */
+ shortcut?: string[];
+ /** Whether it is offered right now; always, when left out. */
+ available?(): boolean;
+};
+
+/** A command as registered: with the owner of the component that registered it. */
+export type RegisteredCommand = Command & { owner: Owner | null };
+
+type CommandsContextValue = {
+ /** Every command registered right now, in the order they were registered. */
+ commands: Accessor<RegisteredCommand[]>;
+ paletteOpen: Accessor<boolean>;
+ setPaletteOpen(open: boolean): void;
+ /** The command whose bar is up. */
+ active: Accessor<RegisteredCommand | null>;
+ /** Carries `command` out: runs it, or puts its bar up. */
+ execute(command: RegisteredCommand): void;
+ /** Takes the bar down. */
+ close(): void;
+ register(command: RegisteredCommand): () => void;
+};
+
+const CommandsContext = createContext<CommandsContextValue>();
+
+export function CommandsProvider(props: { children: JSX.Element }) {
+ const [commands, setCommands] = createSignal<RegisteredCommand[]>([]);
+ const [paletteOpen, setPaletteOpen] = createSignal(false);
+ const [active, setActive] = createSignal<RegisteredCommand | null>(null);
+
+ const execute = (command: RegisteredCommand) => {
+ setPaletteOpen(false);
+ if (command.bar) setActive(command);
+ else command.run();
+ };
+
+ const register = (command: RegisteredCommand) => {
+ setCommands((list) => [...list, command]);
+
+ return () => {
+ setCommands((list) => list.filter((entry) => entry !== command));
+ // Its component is gone, and with it what the bar was working with.
+ if (active() === command) setActive(null);
+ };
+ };
+
+ return (
+ <CommandsContext.Provider
+ value={{ commands, paletteOpen, setPaletteOpen, active, execute, close: () => setActive(null), register }}
+ >
+ {props.children}
+ </CommandsContext.Provider>
+ );
+}
+
+export function useCommands() {
+ const context = useContext(CommandsContext);
+ if (!context) throw new Error("useCommands must be used within a CommandsProvider");
+ return context;
+}
+
+/** Offers `command` in the palette for as long as the calling component is mounted. */
+export function useCommand(command: Command): void {
+ const { register } = useCommands();
+ onCleanup(register({ ...command, owner: getOwner() }));
+}