Skip to content

The VS Code of video editing, built for agents.

TypeScript

Refactor command palette and action bar components

konstantin-paulus56a8f09e5312
diff --git a/apps/web/src/components/canvas/action-bar.tsx b/apps/web/src/components/canvas/action-bar.tsx
index 8c7b88ec..5305b99f 100644
--- a/apps/web/src/components/canvas/action-bar.tsx
+++ b/apps/web/src/components/canvas/action-bar.tsx
@@ -6,11 +6,10 @@
// 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, splitProps } from "solid-js";
+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 { DropdownMenuItem } from "@/components/ui/dropdown-menu";
import { Icon } from "@/components/ui/icon";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { getClipFallbackName } from "@/engine/timeline/style";
@@ -152,47 +151,3 @@ export function ActionBarConfirm(props: ActionBarConfirmProps) {
</Tooltip>
);
}
-
-/** The menus a bar opens: headed lists, laid out like the toolbar's own. */
-export const ACTION_BAR_MENU_CLASS =
- "rounded-xl border-border bg-background px-2 pt-0 pb-2 gap-0 shadow-[0px_12px_24px_0px_rgba(0,0,0,0.24)]";
-
-export function ActionBarMenuHeader(props: { children: JSX.Element }) {
- return <div class="flex h-8 items-center px-1 text-xs text-muted-foreground">{props.children}</div>;
-}
-
-type ActionBarMenuItemProps = {
- checked: boolean;
- onSelect(): void;
- onHover?(row: HTMLElement | null): void;
- children: JSX.Element;
-};
-
-/** A menu row that is the current pick: raised, with a check at its end. */
-export function ActionBarMenuItem(props: ActionBarMenuItemProps) {
- const [local, rest] = splitProps(props, ["checked", "onHover", "children"]);
-
- return (
- <DropdownMenuItem
- {...rest}
- onPointerEnter={(event: PointerEvent) => local.onHover?.(event.currentTarget as HTMLElement)}
- onPointerLeave={() => local.onHover?.(null)}
- onFocus={(event: FocusEvent) => local.onHover?.(event.currentTarget as HTMLElement)}
- onBlur={() => local.onHover?.(null)}
- tone="neutral"
- class={cx("pr-0", local.checked ? "bg-accent text-foreground" : "text-muted-foreground")}
- >
- <span class="min-w-0 flex-1 truncate">{local.children}</span>
- <span class="flex size-7 items-center justify-center">
- <Show when={local.checked}>
- <Icon name="confirm-check" class="text-foreground" />
- </Show>
- </span>
- </DropdownMenuItem>
- );
-}
-
-/** Esc closes an open menu; it goes no further, where it would take the bar or the selection down. */
-export function keepMenuEscape(event: KeyboardEvent) {
- event.stopPropagation();
-}
diff --git a/apps/web/src/components/canvas/object-mask-bar.tsx b/apps/web/src/components/canvas/object-mask-bar.tsx
index 008e12d7..d4c57195 100644
--- a/apps/web/src/components/canvas/object-mask-bar.tsx
+++ b/apps/web/src/components/canvas/object-mask-bar.tsx
@@ -2,7 +2,7 @@
* 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, createResource, createSignal, onMount } from "solid-js";
+import { For, Show, createResource, createSignal, onMount, splitProps } from "solid-js";
import { Portal } from "solid-js/web";
import { SAM2_MODELS, downloadSize, sam2Model } from "@diffusionstudio/sam2/models";
import { useWorld } from "@diffusionstudio/koota-solid";
@@ -16,11 +16,12 @@ import { Popover, PopoverContent, PopoverPortal, PopoverTrigger } from "@/compon
import {
DropdownMenu,
DropdownMenuContent,
+ DropdownMenuItem,
DropdownMenuPortal,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { cx } from "@/lib/cva";
-import { ACTION_BAR_MENU_CLASS, ActionBar, ActionBarMenuHeader, ActionBarMenuItem, keepMenuEscape } from "./action-bar";
+import { ActionBar } from "./action-bar";
import { useDerived, useObjectMaskTool } from "@/engine/hooks";
import {
cancelObjectMask,
@@ -62,6 +63,9 @@ const MODEL_NOTES: Record<Sam2ModelId, string> = {
/** The brush's size on its slider: its diameter, in percent of the frame's height. */
const BRUSH_SIZE = { min: 1, max: 30 };
+/** The menus the bar opens: headed lists, laid out like the toolbar's own. */
+const MENU_CLASS = "rounded-xl border-border bg-background px-2 pt-0 pb-2 gap-0 shadow-[0px_12px_24px_0px_rgba(0,0,0,0.24)]";
+
type SessionState = {
status: ObjectTrackStatus | null;
completed: number;
@@ -191,18 +195,18 @@ function ModelMenu(props: { disabled: boolean }) {
<TooltipContent>{load() ? describeModelLoad(load()!) : "Segmentation model"}</TooltipContent>
</Tooltip>
<DropdownMenuPortal>
- <DropdownMenuContent class={cx(ACTION_BAR_MENU_CLASS, "min-w-40")} onEscapeKeyDown={keepMenuEscape}>
- <ActionBarMenuHeader>Model</ActionBarMenuHeader>
+ <DropdownMenuContent class={cx(MENU_CLASS, "min-w-40")} onEscapeKeyDown={keepEscape}>
+ <MenuHeader>Model</MenuHeader>
<div class="flex flex-col gap-1 py-0.5">
<For each={SAM2_MODELS}>
{(model) => (
- <ActionBarMenuItem
+ <CheckedItem
checked={model.id === objectMaskModel()}
onSelect={() => pickObjectMaskModel(model.id)}
onHover={(row) => setHovered(row ? { model, row } : null)}
>
{model.label}
- </ActionBarMenuItem>
+ </CheckedItem>
)}
</For>
</div>
@@ -262,11 +266,11 @@ function ModePopover() {
</Tooltip>
<PopoverPortal>
<PopoverContent
- class={cx(ACTION_BAR_MENU_CLASS, "w-44")}
- onEscapeKeyDown={keepMenuEscape}
+ class={cx(MENU_CLASS, "w-44")}
+ onEscapeKeyDown={keepEscape}
onOpenAutoFocus={(event) => event.preventDefault()}
>
- <ActionBarMenuHeader>Tool</ActionBarMenuHeader>
+ <MenuHeader>Tool</MenuHeader>
<SegmentedIconTabs value={tool.mode} onChange={(mode) => tool.set({ mode })} items={MODE_TABS} class="my-0.5" />
<Show when={mode().value === "brush"}>
<div class="pt-2 pb-0.5">
@@ -312,14 +316,14 @@ function OpMenu(props: { disabled: boolean }) {
<TooltipContent shortcut="Hold ⌥ to swap">{op().hint}</TooltipContent>
</Tooltip>
<DropdownMenuPortal>
- <DropdownMenuContent class={cx(ACTION_BAR_MENU_CLASS, "min-w-40")} onEscapeKeyDown={keepMenuEscape}>
- <ActionBarMenuHeader>Mode</ActionBarMenuHeader>
+ <DropdownMenuContent class={cx(MENU_CLASS, "min-w-40")} onEscapeKeyDown={keepEscape}>
+ <MenuHeader>Mode</MenuHeader>
<div class="flex flex-col gap-1 py-0.5">
<For each={OPS}>
{(entry) => (
- <ActionBarMenuItem checked={entry.value === tool.op()} onSelect={() => tool.set({ op: entry.value })}>
+ <CheckedItem checked={entry.value === tool.op()} onSelect={() => tool.set({ op: entry.value })}>
{entry.label}
- </ActionBarMenuItem>
+ </CheckedItem>
)}
</For>
</div>
@@ -329,6 +333,46 @@ function OpMenu(props: { disabled: boolean }) {
);
}
+function MenuHeader(props: { children: JSX.Element }) {
+ return <div class="flex h-8 items-center px-1 text-xs text-muted-foreground">{props.children}</div>;
+}
+
+type CheckedItemProps = {
+ checked: boolean;
+ onSelect(): void;
+ onHover?(row: HTMLElement | null): void;
+ children: JSX.Element;
+};
+
+/** A menu row that is the current pick: raised, with a check at its end. */
+function CheckedItem(props: CheckedItemProps) {
+ const [local, rest] = splitProps(props, ["checked", "onHover", "children"]);
+
+ return (
+ <DropdownMenuItem
+ {...rest}
+ onPointerEnter={(event: PointerEvent) => local.onHover?.(event.currentTarget as HTMLElement)}
+ onPointerLeave={() => local.onHover?.(null)}
+ onFocus={(event: FocusEvent) => local.onHover?.(event.currentTarget as HTMLElement)}
+ onBlur={() => local.onHover?.(null)}
+ tone="neutral"
+ class={cx("pr-0", local.checked ? "bg-accent text-foreground" : "text-muted-foreground")}
+ >
+ <span class="min-w-0 flex-1 truncate">{local.children}</span>
+ <span class="flex size-7 items-center justify-center">
+ <Show when={local.checked}>
+ <Icon name="confirm-check" class="text-foreground" />
+ </Show>
+ </span>
+ </DropdownMenuItem>
+ );
+}
+
+/** Esc closes an open menu; it goes no further, where it would put the tool down. */
+function keepEscape(event: KeyboardEvent) {
+ event.stopPropagation();
+}
+
/**
* Content as wide as `widest` whatever it says, centered in that width: the
* button around it holds still as a number in it counts up.
diff --git a/apps/web/src/components/commands/export-current-frame.tsx b/apps/web/src/components/commands/export-current-frame.tsx
index fe5810f5..e50ef256 100644
--- a/apps/web/src/components/commands/export-current-frame.tsx
+++ b/apps/web/src/components/commands/export-current-frame.tsx
@@ -2,20 +2,16 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-import { createSignal } from "solid-js";
import { computeOutputSize } from "@diffusionstudio/encoder";
import { Computed } from "@diffusionstudio/runtime";
-import { Separator } from "@/components/ui/separator";
-import { useCommand, useCommands } from "@/context/commands";
+import { useCommand } from "@/context/commands";
import { useExport } from "@/context/export";
-import { useActiveScene, useDerived } from "@/engine/hooks";
+import { useActiveScene } from "@/engine/hooks";
import { store } from "@/init";
-import { ActionBar, ActionBarCancel, ActionBarConfirm, ActionBarTarget } from "@/components/canvas/action-bar";
-import { PresetMenu } from "./preset-menu";
-import type { PresetGroup } from "./preset-menu";
+import type { LayerSection } from "@/context/commands";
-/** The preset the bar opened on last, kept across sessions. */
+/** The size picked last, highlighted when the sizes come up; kept across sessions. */
const LAST_PRESET_KEY = "commands.export-current-frame.preset";
/** The sizes an image is offered at, named as the video presets name them; each is the shorter side. */
@@ -25,66 +21,50 @@ const PRESETS = [
{ id: "2160p", name: "4K Ultra HD", resolution: 2160 },
];
+/** The frame at the active scene's playhead, exported as a PNG at the size picked from the palette's layer. */
export function ExportCurrentFrameCommand() {
- useCommand({
- id: "export-current-frame",
- title: "Export current frame",
- group: "Export",
- icon: "image",
- keywords: ["image", "still", "png", "screenshot", "1080p", "1440p", "4k"],
- shortcut: ["⇧", "⌘", "E"],
- bar: ExportCurrentFrameBar,
- });
-
- return null;
-}
-
-/** The frame at the active scene's playhead, exported as a PNG at the size picked. */
-function ExportCurrentFrameBar() {
- const { close } = useCommands();
const { exportFrame } = useExport();
const scene = useActiveScene();
- const size = useDerived(
- () => {
- const computed = scene()?.get(Computed);
- return { width: computed?.width || 1920, height: computed?.height || 1080 };
- },
- (a, b) => a.width === b.width && a.height === b.height,
- );
- const [picked, setPicked] = createSignal(store.get<string>(LAST_PRESET_KEY));
- const preset = () => PRESETS.find((entry) => entry.id === picked()) ?? PRESETS[0]!;
+ const sections = (): LayerSection[] => {
+ const computed = scene()?.get(Computed);
+ const width = computed?.width || 1920;
+ const height = computed?.height || 1080;
- // Each preset with the pixel size it makes of this scene.
- const groups = (): PresetGroup[] => [
- {
- label: "Size",
- presets: PRESETS.map((entry) => {
- const output = computeOutputSize(size().width, size().height, entry.resolution);
- return { id: entry.id, name: entry.name, detail: `${output.width}×${output.height}` };
- }),
- },
- ];
+ return [
+ {
+ name: "Size",
+ options: PRESETS.map((entry) => {
+ const output = computeOutputSize(width, height, entry.resolution);
+ return { id: entry.id, title: entry.name, detail: `${output.width}×${output.height}` };
+ }),
+ },
+ ];
+ };
const pick = (id: string) => {
- setPicked(id);
+ const active = scene();
+ const preset = PRESETS.find((entry) => entry.id === id);
+ if (!active || !preset) return;
store.set(LAST_PRESET_KEY, id);
+ exportFrame(active, preset.resolution);
};
- const confirm = () => {
- const active = scene();
- if (!active) return;
- close();
- void exportFrame(active, preset().resolution);
- };
+ useCommand({
+ id: "export-current-frame",
+ title: "Export current frame",
+ group: "Export",
+ icon: "image",
+ keywords: ["image", "still", "png", "screenshot", "1080p", "1440p", "4k"],
+ shortcut: ["⇧", "⌘", "E"],
+ available: () => scene() !== null,
+ layer: {
+ placeholder: "Search for image size",
+ sections,
+ current: () => store.get<string>(LAST_PRESET_KEY) ?? PRESETS[0]!.id,
+ pick,
+ },
+ });
- return (
- <ActionBar>
- <ActionBarTarget nodes={scene() ? [scene()!] : []} verb="Export frame of" empty="Open a scene to export" />
- <PresetMenu groups={groups()} value={preset().id} onChange={pick} tooltip="Image size" />
- <Separator orientation="vertical" class="min-h-5" />
- <ActionBarCancel onCancel={close} />
- <ActionBarConfirm disabled={!scene()} onConfirm={confirm} hint="Export current frame" />
- </ActionBar>
- );
+ return null;
}
diff --git a/apps/web/src/components/commands/export-video.tsx b/apps/web/src/components/commands/export-video.tsx
index 7867acf3..9a1ed884 100644
--- a/apps/web/src/components/commands/export-video.tsx
+++ b/apps/web/src/components/commands/export-video.tsx
@@ -2,9 +2,10 @@
* 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, createSignal } from "solid-js";
-import { Separator } from "@/components/ui/separator";
-import { useCommand, useCommands } from "@/context/commands";
+import { createMemo } from "solid-js";
+import { computeOutputSize } from "@diffusionstudio/encoder";
+import { Computed } from "@diffusionstudio/runtime";
+import { useCommand } from "@/context/commands";
import { useExport } from "@/context/export";
import { useActiveScene } from "@/engine/hooks";
import { useProjectConfig } from "@/engine/project-config";
@@ -14,32 +15,16 @@ import {
EXPORT_TEMPLATE_GROUPS,
TEMPLATE_BY_ID,
} from "@/components/sidebar-right/inspector/export-templates";
-import { ActionBar, ActionBarCancel, ActionBarConfirm, ActionBarTarget } from "@/components/canvas/action-bar";
-import { PresetMenu } from "./preset-menu";
import type { ExportConfig } from "@/components/sidebar-right/inspector/export-templates";
-import type { PresetGroup } from "./preset-menu";
+import type { LayerSection } from "@/context/commands";
-/** The preset the bar opened on last, kept across sessions. */
+/** The preset picked last, highlighted when the presets come up; kept across sessions. */
const LAST_PRESET_KEY = "commands.export-video.preset";
/** The scene's own settings, from the inspector's Export panel, as a pick. */
const SCENE_SETTINGS = "scene";
-export function ExportVideoCommand() {
- useCommand({
- id: "export-video",
- title: "Export video",
- group: "Export",
- icon: "film-video-export",
- keywords: ["render", "mp4", "webm", "720p", "1080p", "1440p", "4k", "youtube", "tiktok", "instagram"],
- shortcut: ["⌘", "E"],
- bar: ExportVideoBar,
- });
-
- return null;
-}
-
/** "1080p", "4K", with the container when it is not MP4: what a preset comes out as. */
function describe(config: ExportConfig): string {
if (config.format === "ogg" || config.video?.enabled === false) return "Audio only";
@@ -48,61 +33,75 @@ function describe(config: ExportConfig): string {
return config.format && config.format !== "mp4" ? `${size} · ${config.format.toUpperCase()}` : size;
}
-/** The active scene, exported as a video with the preset picked. */
-function ExportVideoBar() {
- const { close } = useCommands();
+/** The active scene, exported as a video with the preset picked from the palette's layer. */
+export function ExportVideoCommand() {
const { exportScene } = useExport();
const scene = useActiveScene();
const config = useProjectConfig();
-
const sceneSettings = createMemo(() => {
const active = scene();
return active ? config()?.exportOf(active) ?? null : null;
});
- // The scene's own settings when it has them, else the last preset used.
- const [picked, setPicked] = createSignal<string | null>(null);
- const preset = () => {
- const id = picked();
- if (id === SCENE_SETTINGS && sceneSettings()) return id;
- if (id !== null && TEMPLATE_BY_ID.has(id)) return id;
- if (sceneSettings()) return SCENE_SETTINGS;
- const last = store.get<string>(LAST_PRESET_KEY);
- return last && TEMPLATE_BY_ID.has(last) ? last : DEFAULT_EXPORT_TEMPLATE_ID;
- };
+ // Read as the layer comes up: the scene is not resized while it is.
+ const sections = (): LayerSection[] => {
+ const computed = scene()?.get(Computed);
+ const width = computed?.width || 1920;
+ const height = computed?.height || 1080;
+
+ // The pixel size a preset makes of this scene; none for audio.
+ const pixels = (config: ExportConfig) => {
+ if (config.format === "ogg" || config.video?.enabled === false) {
+ return undefined;
+ }
+
+ const output = computeOutputSize(width, height, config.video?.resolution ?? 1080);
+ return `${output.width}×${output.height}`;
+ };
- const groups = (): PresetGroup[] => {
const own = sceneSettings();
return [
- ...(own ? [{ label: "Scene", presets: [{ id: SCENE_SETTINGS, name: "Scene settings", detail: describe(own) }] }] : []),
+ ...(own ? [{
+ name: "Scene settings",
+ options: [{ id: SCENE_SETTINGS, title: describe(own), detail: pixels(own) }]
+ }] : []),
...EXPORT_TEMPLATE_GROUPS.map((group) => ({
- label: group.label,
- presets: group.items.map((template) => ({ id: template.id, name: template.name, detail: describe(template) })),
+ name: group.label,
+ options: group.items.map((template) => ({
+ id: template.id,
+ title: template.name,
+ keywords: [describe(template)],
+ detail: pixels(template),
+ })),
})),
];
};
- const pick = (id: string) => {
- setPicked(id);
- if (id !== SCENE_SETTINGS) store.set(LAST_PRESET_KEY, id);
+ // The scene's own settings when it has them, else the last preset used.
+ const current = () => {
+ if (sceneSettings()) return SCENE_SETTINGS;
+ const last = store.get<string>(LAST_PRESET_KEY);
+ return last && TEMPLATE_BY_ID.has(last) ? last : DEFAULT_EXPORT_TEMPLATE_ID;
};
- const confirm = () => {
+ const pick = (id: string) => {
const active = scene();
- const id = preset();
const settings = id === SCENE_SETTINGS ? sceneSettings() : TEMPLATE_BY_ID.get(id);
if (!active || !settings) return;
- close();
+ if (id !== SCENE_SETTINGS) store.set(LAST_PRESET_KEY, id);
void exportScene(active, { format: settings.format, video: settings.video, audio: settings.audio });
};
- return (
- <ActionBar>
- <ActionBarTarget nodes={scene() ? [scene()!] : []} verb="Export" empty="Open a scene to export" />
- <PresetMenu groups={groups()} value={preset()} onChange={pick} tooltip="Export preset" />
- <Separator orientation="vertical" class="min-h-5" />
- <ActionBarCancel onCancel={close} />
- <ActionBarConfirm disabled={!scene()} onConfirm={confirm} hint="Export video" />
- </ActionBar>
- );
+ useCommand({
+ id: "export-video",
+ title: "Export video",
+ group: "Export",
+ icon: "film-video-export",
+ keywords: ["render", "mp4", "webm", "720p", "1080p", "1440p", "4k", "youtube", "tiktok", "instagram"],
+ shortcut: ["⌘", "E"],
+ available: () => scene() !== null,
+ layer: { placeholder: "Search for export preset", sections, current, pick },
+ });
+
+ return null;
}
diff --git a/apps/web/src/components/commands/palette.tsx b/apps/web/src/components/commands/palette.tsx
index 27092aac..dbf8d7d1 100644
--- a/apps/web/src/components/commands/palette.tsx
+++ b/apps/web/src/components/commands/palette.tsx
@@ -2,13 +2,14 @@
* 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 { For, Show, createEffect, createMemo, createSignal, on, 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 { cx } from "@/lib/cva";
import { SECTIONS, useCommands } from "@/context/commands";
-import type { RegisteredCommand } from "@/context/commands";
+import type { LayerSection, LayeredCommand, RegisteredCommand } from "@/context/commands";
const offered = (command: RegisteredCommand) => command.available?.() ?? true;
@@ -22,9 +23,13 @@ const MIN_SCORE = 0.05;
/** How many of the commands last carried out the palette lists over the rest. */
const RECENTS_LISTED = 4;
+/** The bump the palette gives when it goes into a layer or back: down, then up again. */
+const LAYER_BUMP: Keyframe[] = [{ scale: "1" }, { scale: "0.98" }, { scale: "1" }];
+
/**
* The command palette, on ⌘K: the commands on offer, by section, found by
- * typing; the arrows pick one, Enter carries it out.
+ * typing; the arrows pick one, Enter carries it out. A command with options
+ * lists them in a layer of its own, which Esc goes back from.
*/
export function CommandPalette() {
const commands = useCommands();
@@ -32,6 +37,9 @@ export function CommandPalette() {
// 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;
+ // What was highlighted when a layer came up, highlighted again on the way back.
+ let returnTo: string | undefined;
+ let content: HTMLDivElement | undefined;
const onKeyDown = (event: KeyboardEvent) => {
if (event.key.toLowerCase() !== "k" || !(event.metaKey || event.ctrlKey) || event.shiftKey || event.altKey) return;
@@ -47,24 +55,51 @@ export function CommandPalette() {
onMount(() => window.addEventListener("keydown", onKeyDown, true));
onCleanup(() => window.removeEventListener("keydown", onKeyDown, true));
- const pick = (command: RegisteredCommand) => {
- picked = true;
+ const pick = (command: RegisteredCommand, value: string) => {
+ if (command.layer) returnTo = value;
+ else picked = true;
commands.execute(command);
};
+ const pickOption = (command: LayeredCommand, id: string) => {
+ commands.setPaletteOpen(false);
+ command.layer.pick(id);
+ };
+
+ // Not on the way out: closing takes the layer down too.
+ createEffect(
+ on(commands.layer,
+ () => {
+ if (commands.paletteOpen()) {
+ content?.animate(LAYER_BUMP, { duration: 200, easing: "ease-out" });
+ }
+ },
+ { defer: true },
+ ),
+ );
+
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
+ ref={content}
class="fixed top-[20vh] left-1/2 z-50 w-full max-w-[calc(100%-2rem)] sm:max-w-xl -translate-x-1/2 overflow-hidden rounded-xl border border-border bg-popover text-popover-foreground outline-none shadow-[0px_12px_24px_0px_rgba(0,0,0,0.24)] 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"
+ onEscapeKeyDown={(event: KeyboardEvent) => {
+ if (!commands.layer()) return;
+ event.preventDefault();
+ commands.back();
+ }}
onCloseAutoFocus={(event: Event) => {
if (picked) event.preventDefault();
picked = false;
+ returnTo = undefined;
}}
>
<Dialog.Title class="sr-only">Commands</Dialog.Title>
- <PaletteContent onPick={pick} />
+ <Show when={commands.layer()} keyed fallback={<PaletteContent initial={returnTo} onPick={pick} />}>
+ {(command) => <LayerContent command={command} onPick={(id) => pickOption(command, id)} />}
+ </Show>
</Dialog.Content>
</Dialog.Portal>
</Dialog>
@@ -110,7 +145,55 @@ function rank(commands: RegisteredCommand[], search: string): ListedSection[] {
return [...byName].map(([name, list]) => ({ name, commands: list }));
}
-function PaletteContent(props: { onPick(command: RegisteredCommand): void }) {
+const LIST_CLASS =
+ "max-h-[min(400px,60vh)] scroll-py-1 overflow-y-auto overflow-x-hidden px-3 py-1 [&_[cmdk-list-sizer]]:flex [&_[cmdk-list-sizer]]:flex-col [&_[cmdk-list-sizer]]:gap-2";
+
+const GROUP_CLASS =
+ "[&_[cmdk-group-heading]]:flex [&_[cmdk-group-heading]]:h-8 [&_[cmdk-group-heading]]:items-center [&_[cmdk-group-heading]]:px-1 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group-heading]]:select-none";
+
+const ITEM_CLASS = "group flex h-8 cursor-default items-center text-xs text-foreground outline-hidden select-none";
+
+/** The highlight is a row inset in the item, as tall as a menu item. */
+const ROW_CLASS = "flex h-7 min-w-0 flex-1 items-center gap-1 rounded-md pr-1 group-data-[selected=true]:bg-accent";
+
+type SearchRowProps = {
+ value: string;
+ onValueChange(value: string): void;
+ placeholder: string;
+ onKeyDown?(event: KeyboardEvent): void;
+};
+
+/** The search box over a layer's list, focused as the layer comes up. */
+function SearchRow(props: SearchRowProps) {
+ let input: HTMLInputElement | undefined;
+ onMount(() => input?.focus());
+
+ return (
+ <div class="flex h-11 shrink-0 px-2">
+ <div class="flex min-w-0 flex-1 items-center border-b border-border">
+ <span class="flex size-7 shrink-0 items-center justify-center">
+ <Icon name="search" class="text-muted-foreground" />
+ </span>
+ <CommandPrimitive.Input
+ ref={input}
+ value={props.value}
+ onValueChange={props.onValueChange}
+ onKeyDown={props.onKeyDown}
+ placeholder={props.placeholder}
+ class="h-full min-w-0 flex-1 bg-transparent text-xs text-foreground outline-hidden placeholder:text-muted-foreground"
+ />
+ </div>
+ </div>
+ );
+}
+
+type PaletteContentProps = {
+ /** The item highlighted at first; the first one when left out. */
+ initial?: string;
+ onPick(command: RegisteredCommand, value: string): void;
+};
+
+function PaletteContent(props: PaletteContentProps) {
const commands = useCommands();
const [search, setSearch] = createSignal("");
@@ -127,44 +210,103 @@ function PaletteContent(props: { onPick(command: RegisteredCommand): void }) {
});
return (
- <CommandPrimitive label="Commands" loop shouldFilter={false} class="flex flex-col">
- <div class="flex h-11 shrink-0 px-2">
- <div class="flex min-w-0 flex-1 items-center border-b border-border">
- <span class="flex size-7 shrink-0 items-center justify-center">
- <Icon name="search" class="text-muted-foreground" />
- </span>
- <CommandPrimitive.Input
- value={search()}
- onValueChange={setSearch}
- placeholder="Search or type a command"
- class="h-full min-w-0 flex-1 bg-transparent text-xs text-foreground outline-hidden placeholder:text-muted-foreground"
- />
- </div>
- </div>
- <CommandPrimitive.List class="max-h-[min(400px,60vh)] scroll-py-1 overflow-y-auto overflow-x-hidden px-3 py-1 [&_[cmdk-list-sizer]]:flex [&_[cmdk-list-sizer]]:flex-col [&_[cmdk-list-sizer]]:gap-2">
+ <CommandPrimitive label="Commands" loop shouldFilter={false} defaultValue={props.initial} class="flex flex-col">
+ <SearchRow value={search()} onValueChange={setSearch} placeholder="Search or type a command" />
+ <CommandPrimitive.List class={LIST_CLASS}>
<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-1 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group-heading]]:select-none"
- >
+ <CommandPrimitive.Group heading={section.name} class={GROUP_CLASS}>
<For each={section.commands}>
- {(command) => (
- <CommandPrimitive.Item
- value={section.key ? `${section.key}:${command.id}` : command.id}
- onSelect={() => props.onPick(command)}
- class="group flex h-8 cursor-default items-center text-xs text-foreground outline-hidden select-none"
- >
- <span class="flex h-7 min-w-0 flex-1 items-center gap-1 rounded-md pr-1 group-data-[selected=true]:bg-accent [&_svg]:text-muted-foreground group-data-[selected=true]:[&_svg]:text-foreground">
- <span class="flex size-7 shrink-0 items-center justify-center">
- <Show when={command.icon}>{(icon) => <Icon name={icon()} />}</Show>
+ {(command) => {
+ const value = section.key ? `${section.key}:${command.id}` : command.id;
+ return (
+ <CommandPrimitive.Item value={value} onSelect={() => props.onPick(command, value)} class={ITEM_CLASS}>
+ <span class={cx(ROW_CLASS, "[&_svg]:text-muted-foreground group-data-[selected=true]:[&_svg]:text-foreground")}>
+ <span class="flex size-7 shrink-0 items-center justify-center">
+ <Show when={command.icon}>{(icon) => <Icon name={icon()} />}</Show>
+ </span>
+ <span class="flex-1 truncate">{command.title}</span>
+ <Show when={command.shortcut}>
+ {(keys) => <span class="shrink-0 px-2 text-xxs text-muted-foreground">{keys().join("")}</span>}
+ </Show>
</span>
- <span class="flex-1 truncate">{command.title}</span>
- <Show when={command.shortcut}>
- {(keys) => <span class="shrink-0 px-2 text-xxs text-muted-foreground">{keys().join("")}</span>}
+ </CommandPrimitive.Item>
+ );
+ }}
+ </For>
+ </CommandPrimitive.Group>
+ )}
+ </For>
+ </CommandPrimitive.List>
+ </CommandPrimitive>
+ );
+}
+
+/** A layer's options that match `search`, in its sections and its order. */
+function filterLayer(sections: LayerSection[], search: string): LayerSection[] {
+ const query = search.trim();
+ if (!query) return sections;
+
+ return sections
+ .map((section) => ({
+ name: section.name,
+ options: section.options.filter((option) => {
+ const keywords = [section.name, option.detail, ...(option.keywords ?? [])];
+ return defaultFilter(option.title, query, keywords.filter((word) => word !== undefined)) >= MIN_SCORE;
+ }),
+ }))
+ .filter((section) => section.options.length > 0);
+}
+
+type LayerContentProps = {
+ command: LayeredCommand;
+ onPick(id: string): void;
+};
+
+/** A command's options, in place of the commands; Backspace in an empty search goes back. */
+function LayerContent(props: LayerContentProps) {
+ const commands = useCommands();
+ const [search, setSearch] = createSignal("");
+
+ const sections = createMemo(() => filterLayer(props.command.layer.sections(), search()));
+
+ // The option highlighted at first, when it is listed.
+ const current = props.command.layer.current?.();
+ const initial = sections().some((section) => section.options.some((option) => option.id === current))
+ ? current
+ : undefined;
+
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (event.key !== "Backspace" || search()) return;
+ event.preventDefault();
+ commands.back();
+ };
+
+ return (
+ <CommandPrimitive label={props.command.title} loop shouldFilter={false} defaultValue={initial} class="flex flex-col">
+ <SearchRow
+ value={search()}
+ onValueChange={setSearch}
+ placeholder={props.command.layer.placeholder}
+ onKeyDown={onKeyDown}
+ />
+ <CommandPrimitive.List class={LIST_CLASS}>
+ <CommandPrimitive.Empty class="py-6 text-center text-xs text-muted-foreground">
+ No options found
+ </CommandPrimitive.Empty>
+ <For each={sections()}>
+ {(section) => (
+ <CommandPrimitive.Group heading={section.name} class={GROUP_CLASS}>
+ <For each={section.options}>
+ {(option) => (
+ <CommandPrimitive.Item value={option.id} onSelect={() => props.onPick(option.id)} class={ITEM_CLASS}>
+ <span class={cx(ROW_CLASS, "pl-2")}>
+ <span class="flex-1 truncate">{option.title}</span>
+ <Show when={option.detail}>
+ <span class="shrink-0 px-2 text-xxs text-muted-foreground">{option.detail}</span>
</Show>
</span>
</CommandPrimitive.Item>
diff --git a/apps/web/src/components/commands/preset-menu.tsx b/apps/web/src/components/commands/preset-menu.tsx
deleted file mode 100644
index 6523c7de..00000000
--- a/apps/web/src/components/commands/preset-menu.tsx
+++ /dev/null
@@ -1,94 +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 { For, Show } from "solid-js";
-import { Button } from "@/components/ui/button";
-import { Icon } from "@/components/ui/icon";
-import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuGroup,
- DropdownMenuGroupLabel,
- DropdownMenuItem,
- DropdownMenuItemDetail,
- DropdownMenuPortal,
- DropdownMenuSeparator,
- DropdownMenuTrigger,
-} from "@/components/ui/dropdown-menu";
-import { keepMenuEscape } from "@/components/canvas/action-bar";
-
-export type Preset = {
- id: string;
- name: string;
- /** What it comes out as, at the row's end: "1080p", "1920×1080". */
- detail?: string;
-};
-
-export type PresetGroup = { label: string; presets: Preset[] };
-
-type PresetMenuProps = {
- groups: PresetGroup[];
- value: string;
- onChange(id: string): void;
- /** What the presets set, on hover. */
- tooltip: string;
-};
-
-/** A bar's preset picker: the pick on the button, the presets by group in its menu. */
-export function PresetMenu(props: PresetMenuProps) {
- const selected = () =>
- props.groups.flatMap((group) => group.presets).find((preset) => preset.id === props.value);
-
- return (
- <DropdownMenu placement="top-start" gutter={8}>
- <Tooltip>
- <TooltipTrigger<typeof DropdownMenuTrigger>
- as={(triggerProps: object) => (
- <DropdownMenuTrigger<typeof Button>
- {...triggerProps}
- as={(buttonProps) => (
- <Button {...buttonProps} variant="ghost" class="gap-1 pr-0.5 text-muted-foreground">
- <span class="text-foreground">{selected()?.name}</span>
- {selected()?.detail}
- <Icon name="chevron-down" />
- </Button>
- )}
- />
- )}
- />
- <TooltipContent>{props.tooltip}</TooltipContent>
- </Tooltip>
- <DropdownMenuPortal>
- <DropdownMenuContent class="min-w-60" onEscapeKeyDown={keepMenuEscape}>
- <For each={props.groups}>
- {(group, index) => (
- <>
- <Show when={index() > 0}>
- <DropdownMenuSeparator />
- </Show>
- <DropdownMenuGroup>
- <DropdownMenuGroupLabel>{group.label}</DropdownMenuGroupLabel>
- <For each={group.presets}>
- {(preset) => (
- <DropdownMenuItem class="px-0 pr-2 gap-0.5" onSelect={() => props.onChange(preset.id)}>
- <div classList={{ visible: preset.id === props.value }} class="invisible">
- <Icon name="confirm-check" class="text-foreground" />
- </div>
- <span class="mx-1 min-w-0 flex-1 truncate">{preset.name}</span>
- <Show when={preset.detail}>
- <DropdownMenuItemDetail class="pl-6 whitespace-nowrap">{preset.detail}</DropdownMenuItemDetail>
- </Show>
- </DropdownMenuItem>
- )}
- </For>
- </DropdownMenuGroup>
- </>
- )}
- </For>
- </DropdownMenuContent>
- </DropdownMenuPortal>
- </DropdownMenu>
- );
-}
diff --git a/apps/web/src/context/commands.tsx b/apps/web/src/context/commands.tsx
index 32345648..989e54f2 100644
--- a/apps/web/src/context/commands.tsx
+++ b/apps/web/src/context/commands.tsx
@@ -29,12 +29,40 @@ export type Section = (typeof SECTIONS)[number];
*/
const RECENTS_KEPT = 6;
+/** One of the options a command's layer lists. */
+export type LayerOption = {
+ /** Unique within the layer. */
+ id: string;
+ title: string;
+ /** At the row's end: "1920×1080". */
+ detail?: string;
+ /** More words it is found by. */
+ keywords?: string[];
+};
+
+export type LayerSection = { name: string; options: LayerOption[] };
+
+/**
+ * A second layer of the palette: the options a command is carried out
+ * with, listed in place of the commands until one is picked.
+ */
+export type CommandLayer = {
+ /** The search box's placeholder while the layer is up. */
+ placeholder: string;
+ sections(): LayerSection[];
+ /** The option highlighted when the layer comes up, as the last one picked; the first when left out. */
+ current?(): string | undefined;
+ /** Carries the command out with the option `id`; the palette is closed by then. */
+ pick(id: string): void;
+};
+
type CommandAction =
| {
/** What picking it does. */
run(): void;
bar?: never;
ready?: never;
+ layer?: never;
}
| {
/**
@@ -45,6 +73,14 @@ type CommandAction =
bar: Component;
run?: never;
ready?: never;
+ layer?: never;
+ }
+ | {
+ /** The options picking it lists in the palette, one of which carries it out. */
+ layer: CommandLayer;
+ run?: never;
+ bar?: never;
+ ready?: never;
}
| {
/** What picking it does while `ready`: what the bar would ask for is settled already. */
@@ -53,6 +89,7 @@ type CommandAction =
bar: Component;
/** Whether it can run without the bar (what it runs over is selected). */
ready(): boolean;
+ layer?: never;
};
export type Command = CommandAction & {
@@ -78,16 +115,24 @@ export type Command = CommandAction & {
/** A command as registered: with the owner of the component that registered it. */
export type RegisteredCommand = Command & { owner: Owner | null };
+/** A command whose options the palette lists in a layer of their own. */
+export type LayeredCommand = RegisteredCommand & { layer: CommandLayer };
+
type CommandsContextValue = {
/** Every command registered right now, in the order they were registered. */
commands: Accessor<RegisteredCommand[]>;
paletteOpen: Accessor<boolean>;
+ /** Closing it takes its layer down too. */
setPaletteOpen(open: boolean): void;
+ /** The command whose options the palette lists in place of the commands. */
+ layer: Accessor<LayeredCommand | null>;
+ /** Back from a layer to the commands. */
+ back(): void;
/** The ids of the commands last carried out, most recent first; kept across sessions. */
recents: Accessor<string[]>;
/** The command whose bar is up. */
active: Accessor<RegisteredCommand | null>;
- /** Carries `command` out: runs it, or puts its bar up. */
+ /** Carries `command` out: runs it, puts its bar up, or lists its options in the palette. */
execute(command: RegisteredCommand): void;
/** Takes the bar down. */
close(): void;
@@ -98,13 +143,23 @@ const CommandsContext = createContext<CommandsContextValue>();
export function CommandsProvider(props: { children: JSX.Element }) {
const [commands, setCommands] = createSignal<RegisteredCommand[]>([]);
- const [paletteOpen, setPaletteOpen] = createSignal(false);
+ const [paletteOpen, setOpen] = createSignal(false);
+ const [layer, setLayer] = createSignal<LayeredCommand | null>(null);
const [active, setActive] = createSignal<RegisteredCommand | null>(null);
const [recents, setRecents] = createStoredSignal(store.define<string[]>("commands.recents", []));
+ const setPaletteOpen = (open: boolean) => {
+ setOpen(open);
+ if (!open) setLayer(null);
+ };
+
const execute = (command: RegisteredCommand) => {
- setPaletteOpen(false);
setRecents([command.id, ...recents().filter((id) => id !== command.id)].slice(0, RECENTS_KEPT));
+ if (command.layer) {
+ setLayer({ ...command, layer: command.layer });
+ return;
+ }
+ setPaletteOpen(false);
if (!command.bar || command.ready?.()) {
command.run?.();
} else {
@@ -117,14 +172,15 @@ export function CommandsProvider(props: { children: JSX.Element }) {
return () => {
setCommands((list) => list.filter((entry) => entry !== command));
- // Its component is gone, and with it what the bar was working with.
+ // Its component is gone, and with it what the bar or the layer was working with.
if (active() === command) setActive(null);
+ if (layer()?.id === command.id) setLayer(null);
};
};
return (
<CommandsContext.Provider
- value={{ commands, paletteOpen, setPaletteOpen, recents, active, execute, close: () => setActive(null), register }}
+ value={{ commands, paletteOpen, setPaletteOpen, layer, back: () => setLayer(null), recents, active, execute, close: () => setActive(null), register }}
>
{props.children}
</CommandsContext.Provider>