Compare commits

...

72 Commits

Author SHA1 Message Date
49be50aa99 chore: ignore local .gstack/ tooling dir 2026-10-23 05:14:12 +03:00
0b8a3a505e fix: ignore the project watcher's spurious self-notification on macOS
fs.watch's recursive FSEvents backend fires an extra "change" event whose
filename is just the watched project folder's own basename, both alongside
real file changes and once more asynchronously after the folder is removed
and the watcher closed. watchProject had no filter for it, so that bogus
event reached the renderer as a PROJECTS_CHANGED notification naming a path
that was never a real project file.

Reproduced deterministically outside vitest (plain fs.watch), then fixed by
skipping any event whose filename equals the watched directory's own name.
3 previously-flaky tests in projects.watch.test.ts (expecting an empty
`changed` array) now pass consistently across repeated runs; full desktop
suite is 111/111 green, tsc clean.
2026-10-21 04:00:58 +03:00
Konstantin Paulus
af570c164a
Merge pull request #104 from diffusionstudio/fix/auto-updater
feat: update version to 0.216.0 across all modules and implement auto…
2026-10-19 00:13:14 +02:00
konstantin-paulus
98ea0c986b feat: update version to 0.216.0 across all modules and implement auto-update notifications 2026-10-19 00:11:57 +02:00
Konstantin Paulus
68b633db3c
Merge pull request #102 from diffusionstudio/feat/alpha-mask
Feat/alpha mask
2026-10-17 17:40:32 +02:00
konstantin-paulus
a54e4152c3 feat: update package versions to 0.215.0 across all modules 2026-10-17 17:35:13 +02:00
konstantin-paulus
5aeb75118a feat: add credits display to node menu and update commands to include pricing logic 2026-10-17 17:26:44 +02:00
konstantin-paulus
744dbcb6b7 feat: update tool titles for clarity and consistency in toolbar 2026-10-17 17:18:54 +02:00
konstantin-paulus
b8869dd649 feat: add new icons for edit with prompt, remove background, and remove silences; update command icons 2026-10-17 17:09:21 +02:00
konstantin-paulus
e2d070f968 feat: add mask icon display in SubItemLayer component 2026-10-17 16:53:49 +02:00
konstantin-paulus
783edc2197 feat: add 'Use as mask' shortcut and implement mask application logic 2026-10-17 13:51:37 +02:00
konstantin-paulus
075732f237 feat: implement mask tool and replace clip path functionality with masks 2026-10-17 13:33:10 +02:00
konstantin-paulus
6a45d560d1 feat: add 'type' prop to mask for channel specification and update example usage 2026-10-16 16:38:37 +02:00
konstantin-paulus
0491460e1a Merge branch 'clip-mask-containers' into feat/alpha-mask 2026-10-16 16:16:05 +02:00
Konstantin Paulus
1ac2f5cc9a
Merge pull request #100 from diffusionstudio/feat/canvas-context-menu
Feat/canvas context menu
2026-10-16 11:23:22 +02:00
konstantin-paulus
f3d3a08cc2 feat: optimize canvas position handling by replacing ResizeObserver with computed effect 2026-10-16 11:19:50 +02:00
konstantin-paulus
f29396e13a feat: update package versions to 0.214.0 across all modules 2026-10-16 11:09:52 +02:00
konstantin-paulus
0cd29c91b8 feat: adjust submenu positioning by updating SUB_GUTTER constant 2026-10-16 10:52:06 +02:00
konstantin-paulus
efbc257512 feat: add clean-up command to arrange selected nodes in a grid layout 2026-10-16 10:41:59 +02:00
konstantin-paulus
78b0580c85 feat: update media actions in canvas context menu for enhanced functionality 2026-10-16 10:28:13 +02:00
konstantin-paulus
8107138490 feat: add keyboard shortcut for opening folder in context menu 2026-10-16 10:18:09 +02:00
konstantin-paulus
d68a336199 feat: add keyboard shortcut for delete action in folder context menu 2026-10-16 10:16:44 +02:00
konstantin-paulus
7b3e1fc5e1 feat: add media asset commands and integrate into canvas context menu 2026-10-16 10:14:37 +02:00
konstantin-paulus
b01a79a9e1 feat: refactor soundAsset function to use findGeometryAsset for improved asset retrieval 2026-10-16 00:32:49 +02:00
konstantin-paulus
a567775be1 feat: enhance FloatingProjectHeader with fullscreen detection and traffic light visibility 2026-10-16 00:26:22 +02:00
konstantin-paulus
53aa33ead9 feat: add folder rename cancellation functionality in asset management 2026-10-16 00:05:40 +02:00
konstantin-paulus
c897d7b4d0 feat: add folder move functionality to asset context menus 2026-10-15 23:56:33 +02:00
konstantin-paulus
41ea0e26ab feat: add palette option to command for better control over visibility in UI 2026-10-15 23:53:44 +02:00
konstantin-paulus
893eab6d02 feat: implement clipboard functionality for media import and enhance context menu options 2026-10-15 21:29:27 +02:00
konstantin-paulus
66bed78f88 feat: refactor auto-captions command and improve scene selection logic 2026-10-15 20:56:28 +02:00
konstantin-paulus
db9a6f668f feat: enhance context menus and commands with new shortcuts and improved structure 2026-10-15 15:42:33 +02:00
konstantin-paulus
5433beaebb feat: add keyboard shortcut for toggling prompt input with 'G' key 2026-10-15 14:53:37 +02:00
konstantin-paulus
250c4cc96f feat: update more-three-dots icon for improved clarity and consistency 2026-10-15 11:11:07 +02:00
konstantin-paulus
5681fd9bff feat: add icons for clipboard actions and chat functionality in shortcuts and window commands 2026-10-15 11:07:23 +02:00
konstantin-paulus
9d8327b48d feat: enhance context menu with improved layout and submenu offsets 2026-10-15 11:01:26 +02:00
konstantin-paulus
bbb2fad77a feat: enhance canvas behavior with dynamic panning on panel visibility changes 2026-10-15 10:57:59 +02:00
konstantin-paulus
9b3983d32a feat: add window commands for UI toggling and chat access 2026-10-15 10:52:01 +02:00
konstantin-paulus
6c6349a38f feat: add layer toggle commands and integrate context menus in timeline and canvas 2026-10-15 10:44:14 +02:00
konstantin-paulus
d3d2a0b468 feat: implement node context menu for right-click actions on canvas nodes 2026-10-15 10:37:18 +02:00
konstantin-paulus
3bf9f55067 fix: adjust padding in command palette list class for improved layout 2026-10-15 10:15:49 +02:00
konstantin-paulus
c530e9ca09 feat: adjust item and row height in command palette for improved UI 2026-10-15 10:13:23 +02:00
konstantin-paulus
56a8f09e53 Refactor command palette and action bar components
- Removed unused ActionBarMenu and related components from action-bar.tsx.
- Simplified ExportCurrentFrameCommand and ExportVideoCommand by removing ActionBar dependencies.
- Integrated LayeredCommand and LayerSection types into commands context for better structure.
- Enhanced CommandPalette to support layered commands with options.
- Deleted PresetMenu component as its functionality was integrated into the command handling.
- Improved overall code organization and readability across affected files.
2026-10-15 10:05:40 +02:00
konstantin-paulus
748f31ac45 feat: implement recent commands tracking in the command palette 2026-10-15 09:42:23 +02:00
konstantin-paulus
c413432d75 feat: implement focus handling for the composer on chat tab activation 2026-10-14 23:46:50 +02:00
konstantin-paulus
8d657e578e feat: refactor asset insertion logic to support new scene creation and improve handling of empty assets 2026-10-14 22:49:16 +02:00
konstantin-paulus
2609b28820 feat: enhance asset import functionality with selection management 2026-10-14 22:40:49 +02:00
konstantin-paulus
090669c999 feat: add label to context menu group for improved organization 2026-10-14 20:55:20 +02:00
konstantin-paulus
9ccaac43ce feat: enhance context and dropdown menus with grouping and improved item alignment 2026-10-14 20:51:36 +02:00
konstantin-paulus
e53775d581 feat: add "TRANSCRIPT" filter option to asset filtering 2026-10-14 20:33:27 +02:00
konstantin-paulus
82ebd30df7 feat: refactor context menu integration and add insert options for assets 2026-10-14 20:16:07 +02:00
konstantin-paulus
b8f06155ed feat: implement remove silence command and related functionality 2026-10-14 19:43:25 +02:00
konstantin-paulus
96d7242faa feat: add project folder commands and enhance command ordering in palette 2026-10-14 17:12:21 +02:00
konstantin-paulus
c95e6afc1d feat: update toolbar drag-and-drop functionality with slot anchoring 2026-10-14 16:42:06 +02:00
konstantin-paulus
d8ca02ae02 feat: implement dynamic toolbar slot positioning and update related components 2026-10-14 16:28:33 +02:00
konstantin-paulus
ec84c73d62 feat: enhance command structure with ready state and update execution logic 2026-10-14 14:38:02 +02:00
konstantin-paulus
9617d8adec feat: add export current frame and video commands with preset menus 2026-10-14 14:23:34 +02:00
konstantin-paulus
c21f56a705 feat: implement escape key functionality to close prompt input and update command section order 2026-10-14 12:54:23 +02:00
konstantin-paulus
2a54059ea8 feat: add timeline navigation shortcuts and corresponding icons 2026-10-14 12:32:33 +02:00
konstantin-paulus
f964e5c798 feat: add reload window command and keyboard shortcuts for asset management 2026-10-14 12:02:41 +02:00
konstantin-paulus
29f214bc39 feat: add generate command and update auto-captions command title 2026-10-14 11:47:03 +02:00
konstantin-paulus
bb4ac3bdd8 Refactor command handling and UI components
- Introduced a new CommandBar component to manage command actions and their UI.
- Replaced ActionBar in ClipPathBar and ObjectMaskBar with the new CommandBar.
- Added new command functionalities including AutoCaptions, EditWithPrompt, MakeVideo, RemoveBackground, Rerun, ReuseSettings, and Upscale.
- Implemented CommandPalette for command selection via keyboard shortcuts.
- Updated useAutoCaptions and useTransforms hooks for better scene management.
- Removed deprecated ActionBar component and adjusted related imports.
- Enhanced commands context management for better command registration and execution flow.
2026-10-14 11:32:21 +02:00
konstantin-paulus
17e09d1cc4 feat: bump version to 0.213.1 across all packages 2026-10-14 00:23:21 +02:00
Konstantin Paulus
5d93ffee9c
Merge pull request #99 from diffusionstudio/feat/multi-asset-selection
Feat/multi asset selection
2026-10-14 00:16:04 +02:00
konstantin-paulus
b9dcc6193e feat: bump version to 0.213.0 across all packages 2026-10-14 00:11:25 +02:00
konstantin-paulus
db5a4e90ad feat: update timeline colors to match engine constants for improved consistency 2026-10-13 23:58:37 +02:00
konstantin-paulus
a3cd943478 feat: refine asset attachment logic to handle file modification time more accurately 2026-10-13 23:44:40 +02:00
konstantin-paulus
5ac1c05eca feat: add SVG thumbnail support and improve getSvgDimensions function 2026-10-13 23:24:51 +02:00
konstantin-paulus
7760cb569d feat: enhance asset and folder item components to support multiple selections and context menu actions 2026-10-13 23:21:43 +02:00
konstantin-paulus
fb8a924a7a feat: add MiddleEllipsis component for improved text truncation and update asset and folder item components to utilize it 2026-10-13 21:04:33 +02:00
konstantin-paulus
e5a4024bdc feat: enhance createProjectList to support optional project record updates 2026-10-13 10:33:37 +02:00
Konstantin Paulus
ccf990a25b
Merge pull request #97 from diffusionstudio/feat/draft-projects
Feat/draft projects
2026-10-13 10:01:59 +02:00
konstantin-paulus
8a1313b777 Refactor clip path handling and enhance SVG support
- Updated the handling of clip paths in various components, replacing references to `isClipPath` with `isClipShape` for consistency.
- Enhanced the `ClipPathsSettings` component to correctly select and manage clip path shapes.
- Added support for `<mask>` and `<clipPath>` elements in the documentation, clarifying their usage and properties.
- Improved the handling of ambiguous SVG tags by including `<mask>` and `<clipPath>` in the relevant sets.
- Introduced a new `clip-path.tsx` file to manage clip path functionalities, ensuring better organization and maintainability of the codebase.
2026-10-11 11:47:17 +02:00
170 changed files with 6375 additions and 1547 deletions

3
.gitignore vendored
View File

@ -39,4 +39,5 @@ out/
# AI
skills-lock.json
.agents
.claude
.claude
.gstack/

View File

@ -1,7 +1,7 @@
{
"name": "@diffusionstudio/cli",
"private": true,
"version": "0.212.0",
"version": "0.216.0",
"license": "MPL-2.0",
"bin": {
"diffusion": "./dist/index.js",

View File

@ -1,7 +1,7 @@
{
"name": "@diffusionstudio/desktop",
"private": true,
"version": "0.212.0",
"version": "0.216.0",
"license": "MPL-2.0",
"repository": {
"type": "git",

View File

@ -0,0 +1,47 @@
/* 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 files on the system clipboard: what a copy in Finder or Explorer (or
// of a recording in a screenshot app) leaves there. The renderer reads
// pictures itself, but the web clipboard API knows nothing of files, and
// outside a paste event this is the only way to them.
import { clipboard } from "electron";
import { fileURLToPath } from "node:url";
/** The files on the clipboard, by path, in the order they were copied. */
export function clipboardPaths(): string[] {
switch (process.platform) {
case "darwin": {
// Every file of a copy is in the filenames list, a plist of paths; the
// file URL type only holds the first.
const plist = clipboard.read("NSFilenamesPboardType");
const paths = [...plist.matchAll(/<string>([^<]*)<\/string>/g)].map((match) => unescapeXml(match[1]!));
if (paths.length) return paths;
const url = clipboard.read("public.file-url");
return url.startsWith("file:") ? [fileURLToPath(url)] : [];
}
case "win32": {
// Only the first file of a copy: the full list is in CF_HDROP, which
// Electron cannot read.
const path = clipboard.readBuffer("FileNameW").toString("utf16le").split("\0")[0];
return path ? [path] : [];
}
default:
return clipboard
.read("text/uri-list")
.split(/\r?\n/)
.filter((line) => line.startsWith("file:"))
.map((url) => fileURLToPath(url));
}
}
function unescapeXml(text: string): string {
return text
.replace(/&lt;/g, "<")
.replace(/&gt;/g, ">")
.replace(/&quot;/g, '"')
.replace(/&apos;/g, "'")
.replace(/&amp;/g, "&");
}

View File

@ -42,6 +42,7 @@ export const MAIN_CHANNELS = {
WINDOW_CAPTURE: "window:capture",
WINDOW_SET_BUSY: "window:set-busy",
WINDOW_SHOW: "window:show",
CLIPBOARD_PATHS: "clipboard:paths",
FILE_TRANSFER: "file:transfer",
FILE_WRITE_OPEN: "file:write-open",
FILE_WRITE_CHUNK: "file:write-chunk",
@ -208,6 +209,7 @@ export type MainRequestMap = {
[MAIN_CHANNELS.WINDOW_CAPTURE]: { request: void; response: ScreenshotResult };
[MAIN_CHANNELS.WINDOW_SET_BUSY]: { request: { busy: boolean }; response: void };
[MAIN_CHANNELS.WINDOW_SHOW]: { request: void; response: void };
[MAIN_CHANNELS.CLIPBOARD_PATHS]: { request: void; response: string[] };
[MAIN_CHANNELS.FILE_TRANSFER]: {
request: { selector: string; absolutePath: string };
response: void;

View File

@ -8,6 +8,7 @@ import { existsSync } from "node:fs";
import { mkdir, open, rename, unlink } from "node:fs/promises";
import { randomUUID } from "node:crypto";
import type { FileHandle } from "node:fs/promises";
import type { IUpdateInfo } from "update-electron-app";
import { makeUserNotifier, updateElectronApp } from "update-electron-app";
import { tempPathFor } from "./atomic";
import { DapiServer } from "./dapi/server";
@ -16,6 +17,7 @@ import { cliStatus, installCli, refreshCliShim, uninstallCli } from "./cli-insta
import { applyMcp, healMcpRegistrations, mcpStatus } from "./mcp-install";
import { configureAnalytics, countCanvasEdits, startAnalytics, track } from "./analytics";
import { setupAppMenu } from "./menu";
import { clipboardPaths } from "./clipboard";
import { installedEditors, openInEditor } from "./editors";
import { AppTray } from "./tray";
import { WindowHost } from "./window-host";
@ -110,14 +112,25 @@ function setColorMode(mode: "dark" | "light") {
mainWindow.setTitleBarOverlay({ ...WINDOWS_OVERLAY_COLORS[mode], height: WINDOWS_OVERLAY_HEIGHT });
}
// A downloaded update is offered while the user has the window out; one that
// lands while the app runs in the background waits for the next show, since
// the app rarely quits on its own to apply it.
const notifyUser = makeUserNotifier();
let pendingUpdate: IUpdateInfo | null = null;
function offerUpdate() {
if (!pendingUpdate || !windows.visible()) return;
const info = pendingUpdate;
pendingUpdate = null;
notifyUser(info);
}
if (app.isPackaged && !squirrelLaunch) {
const notifyUser = makeUserNotifier();
updateElectronApp({
repo: "diffusionstudio/editor",
onNotifyUser: function (info) {
if (windows.visible()) {
notifyUser(info);
}
pendingUpdate = info;
offerUpdate();
},
});
}
@ -130,7 +143,10 @@ let lastProject: string | null = null;
const windows = new WindowHost({
create: createWindow,
idleMs: WINDOW_IDLE_MS,
onChange: () => tray.refresh(),
onChange: () => {
tray.refresh();
offerUpdate();
},
});
const tray = new AppTray({
@ -380,6 +396,7 @@ if (squirrelLaunch) {
// A plain Uint8Array over the PNG, so the renderer sees bytes and not a Buffer.
return { png: new Uint8Array(png.buffer, png.byteOffset, png.byteLength), width, height };
});
mainBridge.handle(MAIN_CHANNELS.CLIPBOARD_PATHS, () => clipboardPaths());
mainBridge.handle(MAIN_CHANNELS.LOGS_GET, () => logBuffer);
mainBridge.handle(MAIN_CHANNELS.AGENT_CHAT_ENDPOINT, () => agentChatEndpoint());
mainBridge.handle(MAIN_CHANNELS.MCP_STATUS, () => mcpStatus());

View File

@ -1404,6 +1404,11 @@ export function watchProject(window: BrowserWindow | null, dir: string): void {
const watcher = watch(dir, { recursive: true }, (_event, filename) => {
if (!filename) return;
// macOS's recursive FSEvents watch fires an extra notification for the
// watched folder itself alongside the real one for whatever changed
// inside it — and again once more, asynchronously, after the folder is
// removed and the watcher closed. Neither names an actual project file.
if (filename === basename(dir)) return;
// Project-relative and `/`-separated; installs churn node_modules constantly.
const path = filename.split(sep).join("/");
if (path.startsWith("node_modules/") || path === "node_modules") return;

View File

@ -28,10 +28,12 @@ const COMPOSITION_COMPONENTS = new Map<string, string>(
// These composition names also exist in SVG. An SVG fragment is DOM content
// only while it has an SVG container in the same JSX tree; elsewhere the tag
// keeps its composition meaning.
const AMBIGUOUS_SVG_TAGS: ReadonlySet<string> = new Set(["rect", "ellipse", "polygon", "path", "text", "image"]);
// keeps its composition meaning. `<mask>` and `<clipPath>` are SVG containers
// too, but as such they only ever sit in an `<svg>`, so they are not counted
// as one: a composition `<mask>` keeps the shapes under it composition ones.
const AMBIGUOUS_SVG_TAGS: ReadonlySet<string> = new Set(["rect", "ellipse", "polygon", "path", "text", "image", "mask", "clipPath"]);
const SVG_CONTAINERS: ReadonlySet<string> = new Set([
"svg", "g", "defs", "symbol", "marker", "mask", "clipPath", "pattern",
"svg", "g", "defs", "symbol", "marker", "pattern",
"filter", "linearGradient", "radialGradient", "textPath", "tspan", "switch",
]);

View File

@ -6,10 +6,12 @@ import { EventEmitter } from "node:events";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const appEvents = new EventEmitter();
const updaterEvents = new EventEmitter();
const dock = { show: vi.fn(async () => { }), hide: vi.fn() };
vi.mock("electron", () => ({
app: { on: (event: string, listener: () => void) => appEvents.on(event, listener), dock, focus: () => { } },
autoUpdater: { on: (event: string, listener: () => void) => updaterEvents.on(event, listener) },
}));
const { WindowHost } = await import("./window-host");
@ -45,6 +47,7 @@ let host: InstanceType<typeof WindowHost>;
beforeEach(() => {
vi.useFakeTimers();
appEvents.removeAllListeners();
updaterEvents.removeAllListeners();
created = [];
host = new WindowHost({
create: () => {
@ -132,4 +135,11 @@ describe("WindowHost", () => {
expect(created[0]!.isDestroyed()).toBe(true);
expect(host.current()).toBeNull();
});
it("lets the window close when an update quits the app to install", async () => {
await host.show();
updaterEvents.emit("before-quit-for-update");
created[0]!.close();
expect(created[0]!.isDestroyed()).toBe(true);
});
});

View File

@ -12,7 +12,7 @@
// the Dock icon (macOS) follows whether the window is showing, and closing
// the window hides it rather than ending what the renderer is doing.
import { app } from "electron";
import { app, autoUpdater } from "electron";
import type { BrowserWindow } from "electron";
@ -47,6 +47,11 @@ export class WindowHost {
app.on("before-quit", () => {
this.quitting = true;
});
// quitAndInstall closes the windows before `before-quit`; a close turned
// into a hide there would leave the app running and the update unapplied.
autoUpdater.on("before-quit-for-update", () => {
this.quitting = true;
});
}
/** The window, if there is one. */

View File

@ -1,7 +1,7 @@
{
"name": "@diffusionstudio/web",
"private": true,
"version": "0.212.0",
"version": "0.216.0",
"license": "MPL-2.0",
"type": "module",
"scripts": {

View File

@ -55,6 +55,16 @@ export function Composer(props: ComposerProps) {
resize();
});
// The panel mounts whenever the Chat tab comes up: land in the box, ready
// to type. It may still be disabled while the host connects, and a disabled
// box can't take focus — so focus it the first time it is enabled.
let focused = false;
createEffect(() => {
if (focused || props.blocked !== null) return;
focused = true;
textarea?.focus();
});
// Enter sends, shift+enter breaks the line — and the editor's shortcuts
// have no business reading what is typed here. While a turn runs Enter
// does nothing: there is no queue.
@ -95,6 +105,7 @@ export function Composer(props: ComposerProps) {
<textarea
ref={textarea}
data-chat-composer
value={props.text}
onInput={(event) => props.onText(event.currentTarget.value)}
onKeyDown={handleKeyDown}

View File

@ -33,7 +33,7 @@ export function HeaderActions(props: HeaderActionsProps) {
>
<Icon name="plus-add" />
</TooltipTrigger>
<TooltipContent>New chat</TooltipContent>
<TooltipContent shortcut="⇧⌘L">New chat</TooltipContent>
</Tooltip>
</div>
);

View File

@ -6,9 +6,10 @@ import { Router, HashRouter, Route, useLocation } from '@solidjs/router';
import { ColorModeProvider } from '@kobalte/core';
import { Show, createEffect, createMemo, type JSX } from 'solid-js';
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, ReloadWindowCommand } from '@/components/commands';
import { PersistRoute } from '@/lib/persist-route';
import { useColorMode } from "@kobalte/core";
import { mainBridge } from "@/lib/ipc";
@ -95,15 +96,17 @@ function App() {
<RouterComponent
root={(props) => (
<ColorModeProvider initialColorMode="dark">
<AppContextMenu>
<AuthProvider>
<AuthProvider>
<CommandsProvider>
{props.children}
<CommandPalette />
<ReloadWindowCommand />
<BootSplash />
<UpgradeDialog />
<PurchaseSuccess />
<EditorApi />
</AuthProvider>
</AppContextMenu>
</CommandsProvider>
</AuthProvider>
<Toaster />
<EnvironmentOverlays />
<PersistRoute />

View File

@ -103,7 +103,7 @@ Save the file as `<name>.svg`, using the Figma name without `icon.24.` (`icon.24
A few icons stay on their own grid on purpose:
- **Brand logos** (`agent.*`, `claude`, `codex`, `social.*`, `diffusion-logo*`) are moved to the 25 frame without reshaping.
- **Brand logos** (`agent.*`, `editor.*`, `claude`, `codex`, `social.*`, `diffusion-logo*`) are moved to the 25 frame without reshaping.
- **The `large-*` provider logos** are left as exported.
- **`frame`** (20×20, shown at 20 px), **`folder-thumbnail`** (32×24) and **`vertical-knob-line`** are drawn for their own sizes.
- **`line-join-*`** use a 15×15 grid because they are shown at 14 px.

View File

@ -0,0 +1,4 @@
<svg viewBox="0 0 25 25" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M15.5 7.5L7.5 15.5V17.5H9.5L17.5 9.5A1.4142 1.4142 0 0 0 15.5 7.5ZM14.5 8.5L16.5 10.5M13.5 17.5H18.5M15.5 14.5H18.5" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M8.01 5.44C8.14 4.94 8.86 4.94 8.99 5.44L9.3 6.7L10.56 7.01C11.06 7.14 11.06 7.86 10.56 7.99L9.3 8.3L8.99 9.56C8.86 10.06 8.14 10.06 8.01 9.56L7.7 8.3L6.44 7.99C5.94 7.86 5.94 7.14 6.44 7.01L7.7 6.7Z" fill="currentColor"/>
</svg>

After

Width:  |  Height:  |  Size: 509 B

View File

@ -0,0 +1,5 @@
<svg viewBox="0 0 25 25" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M7.5 9.5V8.5A1 1 0 0 1 8.5 7.5H9.5M11.5 7.5H13.5M17.5 11.5V12.5M7.5 16V16.5A1 1 0 0 0 8.5 17.5H9.5M11.5 17.5H13.5M7.5 11.5V14.5L9.5 12.5L13 16M12.5 15.5L15.5 12.5L17.5 14.5V16.5A1 1 0 0 1 16.5 17.5H15.5" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/>
<circle cx="12.5" cy="10.5" r="1" stroke="currentColor"/>
<path d="M17.01 5.44C17.14 4.94 17.86 4.94 17.99 5.44L18.3 6.7L19.56 7.01C20.06 7.14 20.06 7.86 19.56 7.99L18.3 8.3L17.99 9.56C17.86 10.06 17.14 10.06 17.01 9.56L16.7 8.3L15.44 7.99C14.94 7.86 14.94 7.14 15.44 7.01L16.7 6.7Z" fill="currentColor"/>
</svg>

After

Width:  |  Height:  |  Size: 670 B

View File

@ -0,0 +1,4 @@
<svg viewBox="0 0 25 25" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M12.5 6.5V18.5M10.5 7.5H9A1.5 1.5 0 0 0 7.5 9V16A1.5 1.5 0 0 0 9 17.5H10.5M17.5 10.5V16A1.5 1.5 0 0 1 16 17.5H14.5M9.5 11.5V13.5M15.5 11.5V13.5" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M16.01 4.44C16.14 3.94 16.86 3.94 16.99 4.44L17.3 5.7L18.56 6.01C19.06 6.14 19.06 6.86 18.56 6.99L17.3 7.3L16.99 8.56C16.86 9.06 16.14 9.06 16.01 8.56L15.7 7.3L14.44 6.99C13.94 6.86 13.94 6.14 14.44 6.01L15.7 5.7Z" fill="currentColor"/>
</svg>

After

Width:  |  Height:  |  Size: 551 B

View File

@ -0,0 +1,3 @@
<svg viewBox="0 0 25 25" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M8.1464 13.1464C7.9512 13.3417 7.9512 13.6583 8.1464 13.8535L12.1465 17.8536C12.3417 18.0488 12.6583 18.0488 12.8536 17.8536L16.8536 13.8535C17.0488 13.6583 17.0488 13.3417 16.8536 13.1464C16.6583 12.9512 16.3417 12.9512 16.1464 13.1464L13 16.2929L13 7.5C13 7.2239 12.7761 7 12.5 7C12.2239 7 12 7.2239 12 7.5L12 16.2929L8.8536 13.1464C8.6583 12.9512 8.3417 12.9512 8.1464 13.1464Z" fill="currentColor"/>
</svg>

After

Width:  |  Height:  |  Size: 533 B

View File

@ -0,0 +1,3 @@
<svg viewBox="0 0 25 25" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M12.5 15.5H8A1.5 1.5 0 0 1 6.5 14V9A1.5 1.5 0 0 1 8 7.5H17A1.5 1.5 0 0 1 18.5 9V14A1.5 1.5 0 0 1 17 15.5H15.5V18.5L12.5 15.5Z" stroke="currentColor" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 264 B

View File

@ -0,0 +1,4 @@
<svg viewBox="0 0 25 25" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M9.5 15.5H6A0.5 0.5 0 0 1 5.5 15V6A0.5 0.5 0 0 1 6 5.5H15A0.5 0.5 0 0 1 15.5 6V9.5" stroke="currentColor"/>
<rect x="9.5" y="9.5" width="10" height="10" rx="0.5" stroke="currentColor"/>
</svg>

After

Width:  |  Height:  |  Size: 275 B

View File

@ -0,0 +1,5 @@
<svg viewBox="0 0 25 25" fill="none" xmlns="http://www.w3.org/2000/svg">
<circle cx="9.5" cy="16.5" r="2" stroke="currentColor"/>
<circle cx="15.5" cy="16.5" r="2" stroke="currentColor"/>
<path d="M10.53 14.79L15.5 6.5M14.47 14.79L9.5 6.5" stroke="currentColor" stroke-linecap="round"/>
</svg>

After

Width:  |  Height:  |  Size: 294 B

View File

@ -0,0 +1,5 @@
<svg viewBox="0 0 25 25" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M9.5 15.5H6A0.5 0.5 0 0 1 5.5 15V6A0.5 0.5 0 0 1 6 5.5H15A0.5 0.5 0 0 1 15.5 6V9.5" stroke="currentColor"/>
<rect x="9.5" y="9.5" width="10" height="10" rx="0.5" stroke="currentColor"/>
<path d="M14.5 12V17M12 14.5H17" stroke="currentColor" stroke-linecap="round"/>
</svg>

After

Width:  |  Height:  |  Size: 355 B

View File

@ -0,0 +1,3 @@
<svg viewBox="0 0 25 25" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M15.5322 19.651C15.7606 19.74 16.021 19.7343 16.2515 19.6233L19.2368 18.1869C19.5505 18.0359 19.75 17.7184 19.75 17.3701V7.6299C19.75 7.2816 19.5505 6.9642 19.2368 6.8132L16.2515 5.3767C15.949 5.2311 15.595 5.2668 15.3295 5.4598C15.2915 5.4874 15.2554 5.5182 15.2215 5.5521L9.5065 10.766L7.0171 8.8764C6.7854 8.7005 6.4613 8.7149 6.2461 8.9107L5.4476 9.637C5.1844 9.8764 5.1841 10.2906 5.447 10.5305L7.6058 12.5L5.447 14.4696C5.1841 14.7094 5.1844 15.1236 5.4476 15.3631L6.2461 16.0893C6.4613 16.2851 6.7854 16.2995 7.0171 16.1236L9.5065 14.234L15.2215 19.4479C15.3119 19.5384 15.4181 19.6065 15.5322 19.651ZM16.1272 9.2083L11.7908 12.5L16.1272 15.7917V9.2083Z" fill="currentColor" fill-opacity="0.64"/>
</svg>

After

Width:  |  Height:  |  Size: 833 B

View File

@ -0,0 +1,3 @@
<svg viewBox="0 0 25 25" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M7.2188 6.8125C6.9944 6.8125 6.8125 6.9944 6.8125 7.2188V16.1562H6V7.2188C6 6.5457 6.5457 6 7.2188 6H18.1034C18.6463 6 18.9181 6.6564 18.5343 7.0403L11.8304 13.7441H13.7188V12.9062H14.5312V13.9473C14.5312 14.2838 14.2584 14.5566 13.9219 14.5566H11.0179L9.6214 15.9531H15.9531V10.875H16.7656V15.9531C16.7656 16.4018 16.4018 16.7656 15.9531 16.7656H8.8089L7.387 18.1875H17.7812C18.0056 18.1875 18.1875 18.0056 18.1875 17.7812V8.8438H19V17.7812C19 18.4543 18.4543 19 17.7812 19H6.8966C6.3537 19 6.0819 18.3436 6.4657 17.9597L13.1442 11.2812H11.2812V12.0938H10.4688V11.0781C10.4688 10.7416 10.7416 10.4688 11.0781 10.4688H13.9567L15.3786 9.0469H9.0469V14.125H8.2344V9.0469C8.2344 8.5981 8.5981 8.2344 9.0469 8.2344H16.1911L17.613 6.8125H7.2188Z" fill="currentColor" fill-opacity="0.64"/>
</svg>

After

Width:  |  Height:  |  Size: 913 B

View File

@ -0,0 +1,4 @@
<svg viewBox="0 0 25 25" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M7.5 6.5H7C6.7239 6.5 6.5 6.7239 6.5 7V7.5M9.5 6.5H11.5M13.5 6.5H14C14.2761 6.5 14.5 6.7239 14.5 7V7.5M6.5 9.5V11.5M6.5 13.5V14C6.5 14.2761 6.7239 14.5 7 14.5H7.5M14.5 9.5V14C14.5 14.2761 14.2761 14.5 14 14.5H9.5" stroke="currentColor" stroke-linecap="round"/>
<circle cx="13.5" cy="13.5" r="4" stroke="currentColor"/>
</svg>

After

Width:  |  Height:  |  Size: 408 B

View File

@ -1,3 +1,3 @@
<svg viewBox="0 0 25 25" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M13 8C13 8.5523 12.5523 9 12 9C11.4477 9 11 8.5523 11 8C11 7.4477 11.4477 7 12 7C12.5523 7 13 7.4477 13 8ZM13 12C13 12.5523 12.5523 13 12 13C11.4477 13 11 12.5523 11 12C11 11.4477 11.4477 11 12 11C12.5523 11 13 11.4477 13 12ZM12 17C12.5523 17 13 16.5523 13 16C13 15.4477 12.5523 15 12 15C11.4477 15 11 15.4477 11 16C11 16.5523 11.4477 17 12 17Z" fill="currentColor"/>
<path d="M11 7H13V9H11V7ZM11 11H13V13H11V11ZM11 15H13V17H11V15Z" fill="currentColor"/>
</svg>

Before

Width:  |  Height:  |  Size: 497 B

After

Width:  |  Height:  |  Size: 167 B

View File

@ -0,0 +1,4 @@
<svg viewBox="0 0 25 25" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M10.5 6.5H8A0.5 0.5 0 0 0 7.5 7V19A0.5 0.5 0 0 0 8 19.5H17A0.5 0.5 0 0 0 17.5 19V7A0.5 0.5 0 0 0 17 6.5H14.5" stroke="currentColor"/>
<rect x="10.5" y="5.5" width="4" height="3" rx="0.5" stroke="currentColor"/>
</svg>

After

Width:  |  Height:  |  Size: 300 B

View File

@ -0,0 +1,3 @@
<svg viewBox="0 0 25 25" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M17.5 9.5H11.5A4 4 0 0 0 11.5 17.5H14.5M14.5 6.5L17.5 9.5L14.5 12.5" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 229 B

View File

@ -0,0 +1,3 @@
<svg viewBox="0 0 25 25" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M17.2817 8.462C15.3669 6.1957 12.0487 5.5535 9.3888 7.0891C6.3999 8.8148 5.3757 12.6362 7.1013 15.6252C8.8271 18.614 12.6494 19.6384 15.6383 17.9128C17.1682 17.0293 18.1838 15.5955 18.5785 14.0072C18.6425 13.7496 18.4849 13.4891 18.2273 13.425C17.9697 13.3612 17.7091 13.5177 17.6451 13.7753C17.3107 15.1208 16.4523 16.3332 15.1575 17.0808C12.6285 18.5409 9.3945 17.6733 7.9342 15.1444C6.4741 12.6153 7.3406 9.3813 9.8696 7.9211C12.1866 6.5838 15.0948 7.1993 16.6891 9.2565L15.0861 9.1175C14.8216 9.0944 14.5871 9.2906 14.564 9.5551C14.5411 9.8194 14.7374 10.053 15.0016 10.0763L17.5108 10.2951C17.826 10.3225 18.1039 10.0891 18.1315 9.7739L18.3513 7.2657C18.3744 7.0011 18.1782 6.7676 17.9137 6.7445C17.6492 6.7215 17.4166 6.9176 17.3934 7.1821L17.2817 8.462Z" fill="currentColor"/>
</svg>

After

Width:  |  Height:  |  Size: 873 B

View File

@ -0,0 +1,4 @@
<svg viewBox="0 0 25 25" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M6.5 9.5V6.5H9.5M15.5 6.5H18.5V9.5M18.5 15.5V18.5H15.5M9.5 18.5H6.5V15.5" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/>
<rect x="9.5" y="9.5" width="6" height="6" rx="0.5" stroke="currentColor"/>
</svg>

After

Width:  |  Height:  |  Size: 310 B

View File

@ -0,0 +1,3 @@
<svg viewBox="0 0 25 25" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M18.5 7.5V17.5M11.5 7.5V17.5L16.5 12.5L11.5 7.5ZM6.5 7.5V17.5L11.5 12.5L6.5 7.5Z" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 242 B

View File

@ -0,0 +1,3 @@
<svg viewBox="0 0 25 25" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M15.5 7.5H17.5V17.5H15.5M7.5 12.5H14.5M11.5 9.5L14.5 12.5L11.5 15.5" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 229 B

View File

@ -0,0 +1,3 @@
<svg viewBox="0 0 25 25" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M9.5 7.5H7.5V17.5H9.5M17.5 12.5H10.5M13.5 9.5L10.5 12.5L13.5 15.5" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 227 B

View File

@ -0,0 +1,3 @@
<svg viewBox="0 0 25 25" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M6.5 7.5V17.5M13.5 7.5V17.5L8.5 12.5L13.5 7.5ZM18.5 7.5V17.5L13.5 12.5L18.5 7.5Z" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 242 B

View File

@ -0,0 +1,3 @@
<svg viewBox="0 0 25 25" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M11.5 7.5V17.5L18.5 12.5L11.5 7.5ZM8.5 7.5V17.5" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 209 B

View File

@ -0,0 +1,3 @@
<svg viewBox="0 0 25 25" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M13.5 7.5V17.5L6.5 12.5L13.5 7.5ZM16.5 7.5V17.5" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 209 B

View File

@ -0,0 +1,3 @@
<svg viewBox="0 0 25 25" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M11.5 7.5V17.5L5.5 12.5L11.5 7.5ZM17.5 7.5V17.5L11.5 12.5L17.5 7.5Z" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 229 B

View File

@ -0,0 +1,3 @@
<svg viewBox="0 0 25 25" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M13.5 7.5V17.5L19.5 12.5L13.5 7.5ZM7.5 7.5V17.5L13.5 12.5L7.5 7.5Z" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 228 B

View File

@ -0,0 +1,3 @@
<svg viewBox="0 0 25 25" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M11.5 6.5A6 6 0 1 1 5.5 12.5M13.5 4.5L11.5 6.5L13.5 8.5M10.5 11.5L11.5 10.5V14.5" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 242 B

View File

@ -0,0 +1,3 @@
<svg viewBox="0 0 25 25" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M13.5 6.5A6 6 0 1 0 19.5 12.5M11.5 4.5L13.5 6.5L11.5 8.5M12.5 11.5L13.5 10.5V14.5" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 243 B

View File

@ -0,0 +1,3 @@
<svg viewBox="0 0 25 25" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect x="7.5" y="7.5" width="10" height="10" rx="1.5" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 205 B

View File

@ -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>

After

Width:  |  Height:  |  Size: 439 B

View File

@ -0,0 +1,3 @@
<svg viewBox="0 0 25 25" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M10.5 6.5H14.5M8.5 8.5H16.5M9.5 8.5V17C9.5 17.2761 9.7239 17.5 10 17.5H15C15.2761 17.5 15.5 17.2761 15.5 17V8.5" stroke="currentColor" stroke-linecap="round"/>
</svg>

After

Width:  |  Height:  |  Size: 249 B

View File

@ -0,0 +1,3 @@
<svg viewBox="0 0 25 25" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M7.5 9.5H13.5A4 4 0 0 1 13.5 17.5H10.5M10.5 6.5L7.5 9.5L10.5 12.5" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 227 B

View File

@ -1,105 +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 type { JSX } from "solid-js"
import {
ContextMenu,
ContextMenuContent,
ContextMenuItem,
ContextMenuPortal,
ContextMenuSeparator,
ContextMenuShortcut,
ContextMenuTrigger,
} from "@/components/ui/context-menu"
export function AppContextMenu(props: { children: JSX.Element }) {
const handleUndo = () => {
document.execCommand("undo")
}
const handleRedo = () => {
document.execCommand("redo")
}
const handleCut = () => {
document.execCommand("cut")
}
const handleCopy = () => {
document.execCommand("copy")
}
const handlePaste = async () => {
try {
const text = await navigator.clipboard.readText()
document.execCommand("insertText", false, text)
} catch {
document.execCommand("paste")
}
}
const handleSelectAll = () => {
document.execCommand("selectAll")
}
const handleFullscreen = () => {
if (document.fullscreenElement) {
void document.exitFullscreen()
} else {
void document.documentElement.requestFullscreen()
}
}
const handleReload = () => {
window.location.reload()
}
return (
<ContextMenu>
<ContextMenuTrigger class="contents">
{props.children}
</ContextMenuTrigger>
<ContextMenuPortal>
<ContextMenuContent class="w-[200px]">
<ContextMenuItem onSelect={handleUndo}>
Undo
<ContextMenuShortcut>⌘Z</ContextMenuShortcut>
</ContextMenuItem>
<ContextMenuItem onSelect={handleRedo}>
Redo
<ContextMenuShortcut>⇧⌘Z</ContextMenuShortcut>
</ContextMenuItem>
<ContextMenuSeparator />
<ContextMenuItem onSelect={handleCut}>
Cut
<ContextMenuShortcut>⌘X</ContextMenuShortcut>
</ContextMenuItem>
<ContextMenuItem onSelect={handleCopy}>
Copy
<ContextMenuShortcut>⌘C</ContextMenuShortcut>
</ContextMenuItem>
<ContextMenuItem onSelect={handlePaste}>
Paste
<ContextMenuShortcut>⌘V</ContextMenuShortcut>
</ContextMenuItem>
<ContextMenuItem onSelect={handleSelectAll}>
Select All
<ContextMenuShortcut>⌘A</ContextMenuShortcut>
</ContextMenuItem>
<ContextMenuSeparator />
<ContextMenuItem onSelect={handleFullscreen}>
{document.fullscreenElement ? "Exit Fullscreen" : "Fullscreen"}
<ContextMenuShortcut>F11</ContextMenuShortcut>
</ContextMenuItem>
<ContextMenuSeparator />
<ContextMenuItem onSelect={handleReload}>
Reload
<ContextMenuShortcut>⌘R</ContextMenuShortcut>
</ContextMenuItem>
</ContextMenuContent>
</ContextMenuPortal>
</ContextMenu>
)
}

View File

@ -0,0 +1,153 @@
/* 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, beside 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 { useLayout } from "@/context/layout";
import { BAR_SLOT_CLASS } from "./toolbar-slot";
import type { Entity } from "koota";
import type { JSX } from "solid-js";
export function ActionBar(props: { class?: string; children: JSX.Element }) {
const { toolbarSlot } = useLayout();
return (
<div
class={cx(
"absolute z-10 rounded-xl px-1.5 py-1 bg-background border border-border flex gap-1 items-center",
BAR_SLOT_CLASS[toolbarSlot()],
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>
);
}

View File

@ -2,12 +2,15 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import { createComputed, createEffect, on } from "solid-js";
import { useWorld } from "@diffusionstudio/koota-solid";
import { findSceneAt, screenToWorld, worldToLocal, Library, Root } from "@diffusionstudio/runtime";
import { CameraController, EngineCanvas } from "@/engine";
import { CameraController, EngineCanvas, nodesAt, panBy } from "@/engine";
import { useLayout } from "@/context/layout";
import { insertAsset } from "@/engine/insert-asset";
import { droppedFiles, importFiles } from "@/engine/asset-actions";
import { Toolbar } from "./toolbar";
import { CanvasCommands, NodeContextMenu } from "@/components/commands";
import { DesktopAppBanner } from "./desktop-app-banner";
import { toast } from "somoto"
import { SceneInitOverlay } from "./scene-init-overlay";
@ -17,6 +20,24 @@ import type { Asset } from "@diffusionstudio/assets";
export function Canvas() {
const world = useWorld();
const { uiVisible } = useLayout();
let container!: HTMLDivElement;
/**
* Showing or hiding the panels moves the canvas's corner across the
* screen; the camera moves back by as much, so what is drawn stays where it
* was. The computed runs before Solid applies the toggle to the DOM, so it
* reads where the canvas was; the effect runs after, and reads where it is
* now. The grid snaps rather than animates, so the new place is final.
*/
let before!: DOMRect;
createComputed(on(uiVisible, () => (before = container.getBoundingClientRect()), { defer: true }));
createEffect(on(uiVisible, () => {
const after = container.getBoundingClientRect();
const dx = after.left - before.left;
const dy = after.top - before.top;
if (dx || dy) panBy(world, dx, dy);
}, { defer: true }));
/**
* Drops onto the canvas: library assets (dragged from the panel) land where
@ -68,16 +89,19 @@ export function Canvas() {
}
return (
<div class="relative size-full bg-background">
<div ref={container} class="relative size-full bg-background">
<div
class="absolute inset-0"
on:drop={handleDropEvent}
on:dragover={handleDragOver}
>
<Toolbar />
<CanvasCommands />
<DesktopAppBanner />
<SceneInitOverlay />
<EngineCanvas />
<NodeContextMenu class="size-full" pick={(event) => nodesAt(world, event)}>
<EngineCanvas />
<SceneInitOverlay />
</NodeContextMenu>
<CameraController />
</div>
</div>

View File

@ -10,15 +10,18 @@ import { createStoredSignal } from "@/lib/store";
import { desktopAppDownloadLabel, downloadDesktopApp } from "@/lib/desktop-app";
import { track } from "@/lib/analytics";
import { store } from "@/init";
import { cx } from "@/lib/cva";
import { useLayout } from "@/context/layout";
const BANNER_IMAGE = new URL("@/assets/images/desktop-app-banner.png", import.meta.url).href;
/**
* Dismissible promo for the desktop app, pinned to the bottom left of the
* canvas. Hidden in the desktop build, which is the thing being advertised.
* canvas, or the bottom right while the toolbar is in that corner. Hidden in the desktop build, which is the thing being advertised.
*/
export function DesktopAppBanner() {
const { isDesktop } = useEditorApi();
const { toolbarSlot } = useLayout();
const [dismissed, setDismissed] = createStoredSignal(
store.define("canvas.desktop-app-banner-dismissed", false),
);
@ -32,7 +35,12 @@ export function DesktopAppBanner() {
return (
<Show when={!dismissed() && !isDesktop}>
<div class="absolute bottom-4 left-4 z-10 flex w-[220px] flex-col gap-1 rounded-md border border-border bg-background pb-3 shadow-[0px_0px_1px_2px_rgba(0,0,0,0.12),0px_4px_12px_8px_rgba(0,0,0,0.12)]">
<div
class={cx(
"absolute bottom-4 z-10 flex w-[220px] flex-col gap-1 rounded-md border border-border bg-background pb-3 shadow-[0px_0px_1px_2px_rgba(0,0,0,0.12),0px_4px_12px_8px_rgba(0,0,0,0.12)]",
toolbarSlot() === "bottom-left" ? "right-4" : "left-4",
)}
>
<div class="relative aspect-[220/122] w-full overflow-hidden rounded-t-md">
<img src={BANNER_IMAGE} alt="" class="pointer-events-none size-full object-cover" />
<button

View File

@ -9,50 +9,50 @@ 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 { applyClipPaths, cancelClipPath, getClipPathPicks, getClipPathTarget } from "@/engine/clip-path";
import { ActionBar } from "./action-bar";
import { applyMasks, cancelMask, getMaskPicks, getMaskTarget } from "@/engine/mask";
import type { Entity } from "koota";
/**
* The clip path tool's action bar, over the canvas while the tool is up: how
* many of the selected shapes would clip the target, and the way out —
* Cancel leaves the document as it was, Confirm makes them clip paths of the
* target.
* The mask tool's action bar, over the canvas while the tool is up: how many
* of the selected layers would mask the target, and the way out — Cancel
* leaves the document as it was, Confirm makes them a mask of the target.
*/
export function ClipPathBar() {
export function MaskBar() {
const world = useWorld();
const target = useDerived(getClipPathTarget);
const picks = useDerived(() => getClipPathPicks(world), sameEntities);
const target = useDerived(getMaskTarget);
const picks = useDerived(() => getMaskPicks(world), sameEntities);
// Nothing to aim at (the target was deleted, or undone away): the tool has no work left.
createEffect(() => {
if (!target()) cancelClipPath(world);
if (!target()) cancelMask(world);
});
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"
: `${picks().length} ${picks().length === 1 ? "shape" : "shapes"} selected`}
? "Pick a layer to use as the mask"
: `${picks().length} ${picks().length === 1 ? "layer" : "layers"} selected`}
</span>
<Separator orientation="vertical" class="min-h-5" />
<Tooltip>
<TooltipTrigger as={Button} variant="ghost" class="text-muted-foreground" onClick={() => cancelClipPath(world)}>
<TooltipTrigger as={Button} variant="ghost" class="text-muted-foreground" onClick={() => cancelMask(world)}>
Cancel
</TooltipTrigger>
<TooltipContent shortcut="Esc">Cancel</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger as={Button} disabled={picks().length === 0} onClick={() => applyClipPaths(world)}>
<TooltipTrigger as={Button} disabled={picks().length === 0} onClick={() => applyMasks(world)}>
Confirm
</TooltipTrigger>
<TooltipContent shortcut="⌘↵">Clip <TargetName target={node()} /></TooltipContent>
<TooltipContent shortcut="⌘↵">Mask <TargetName target={node()} /></TooltipContent>
</Tooltip>
</div>
</ActionBar>
)}
</Show>
);

View File

@ -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>
);
}

View File

@ -0,0 +1,39 @@
/* 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/. */
// Where the toolbar goes in each of its slots (see `useLayout().toolbarSlot`),
// and where the bars a tool or a command puts up go with it, on its inner side.
import type { ToolbarSlot } from "@/context/layout";
export const TOOLBAR_SLOT_CLASS: Record<ToolbarSlot, string> = {
"bottom": "bottom-4 left-1/2 -translate-x-1/2",
"top": "top-4 left-1/2 -translate-x-1/2",
"top-left": "top-4 left-4",
"top-right": "top-4 right-4",
"bottom-left": "bottom-4 left-4",
"bottom-right": "bottom-4 right-4",
};
/** Where a bar goes beside the toolbar in each slot: a step in from the edge it is on. */
export const BAR_SLOT_CLASS: Record<ToolbarSlot, string> = {
"bottom": "bottom-16 left-1/2 -translate-x-1/2",
"top": "top-16 left-1/2 -translate-x-1/2",
"top-left": "top-16 left-4",
"top-right": "top-16 right-4",
"bottom-left": "bottom-16 left-4",
"bottom-right": "bottom-16 right-4",
};
/** Where each slot is on the canvas, as fractions of its width and height: the slot nearest the pointer is the one a drag would drop the toolbar in. */
export const TOOLBAR_SLOT_ANCHOR: Record<ToolbarSlot, { x: number; y: number }> = {
"bottom": { x: 0.5, y: 1 },
"top": { x: 0.5, y: 0 },
"top-left": { x: 0, y: 0 },
"top-right": { x: 1, y: 0 },
"bottom-left": { x: 0, y: 1 },
"bottom-right": { x: 1, y: 1 },
};
export const isTopSlot = (slot: ToolbarSlot) => slot.startsWith("top");

View File

@ -15,14 +15,21 @@ 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 { MaskBar } from "./mask-bar";
import { For, Match, Show, Switch, createEffect, createMemo, createSignal, on, onCleanup, onMount } from "solid-js";
import { Tool, ToolType } from "@diffusionstudio/runtime";
import { useWorld } from "@diffusionstudio/koota-solid";
import { clearClipPathTarget, useTool } from "@/engine";
import { cancelMask, cancelObjectMask, clearMaskTarget, useTool } from "@/engine";
import { usePromptInput } from "@/context/prompt-input";
import { useCommands } from "@/context/commands";
import { TOOLBAR_SLOTS, useLayout } from "@/context/layout";
import { TOOLBAR_SLOT_ANCHOR, TOOLBAR_SLOT_CLASS, isTopSlot } from "./toolbar-slot";
import { cx } from "@/lib/cva";
import { isInputTarget } from "@/utils";
import type { ToolbarSlot } from "@/context/layout";
const CURSOR_TOOLS = [
{ tool: ToolType.MOVE, label: 'Move', shortcut: 'V', icon: 'move', menuIcon: 'move-small' },
@ -42,9 +49,14 @@ type ShapeTool = (typeof SHAPE_TOOLS)[number];
// Outlives the toolbar, which unmounts with the canvas.
const [lastShapeTool, setLastShapeTool] = createSignal<ShapeTool>(SHAPE_TOOLS[0]);
/** How far the pointer goes, pressed on the toolbar, before the press is a drag rather than a click. */
const DRAG_THRESHOLD = 4;
export function Toolbar() {
const world = useWorld();
const { promptInputOpen, promptInputConfig, openPromptInput, setPromptInputOpen } = usePromptInput();
const { promptInputOpen, promptInputConfig, setPromptInputOpen } = usePromptInput();
const commands = useCommands();
const { toolbarSlot, setToolbarSlot } = useLayout();
const selectedTool = useTool();
const cursorTool = createMemo(() => CURSOR_TOOLS.find((cursor) => cursor.tool === selectedTool()));
const shapeTool = createMemo(() => SHAPE_TOOLS.find((shape) => shape.tool === selectedTool()));
@ -57,31 +69,149 @@ export function Toolbar() {
});
createEffect(() => {
if (selectedTool() !== ToolType.CLIP_PATH) {
clearClipPathTarget();
if (selectedTool() !== ToolType.MASK) {
clearMaskTarget();
}
});
// 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.MASK) cancelMask(world);
}));
createEffect(on([promptInputOpen, selectedTool], ([open, tool]) => {
if (open || tool === ToolType.OBJECT_MASK || tool === ToolType.MASK) commands.close();
}));
const handleToolChange = (tool: ToolType) => {
world.set(Tool, { value: tool });
}
// G opens and closes the prompt box, as its button does. The box lives
// here rather than in the engine, so its key is bound here rather than in
// the engine's shortcut table.
const handleGenerateKey = (event: KeyboardEvent) => {
if (event.key.toLowerCase() !== "g" || event.repeat) return;
if (event.metaKey || event.ctrlKey || event.altKey || event.shiftKey) return;
if (isInputTarget(event)) return;
event.preventDefault();
setPromptInputOpen(!promptInputOpen());
};
onMount(() => window.addEventListener("keydown", handleGenerateKey));
onCleanup(() => window.removeEventListener("keydown", handleGenerateKey));
// Dragging the toolbar shows the other slots it can go to, the one nearest
// the pointer drawn wide; the toolbar stays put until it is let go of, and
// then moves there.
let toolbar!: HTMLDivElement;
const [dropSlot, setDropSlot] = createSignal<ToolbarSlot>();
const dragging = () => dropSlot() !== undefined;
let press: { x: number; y: number; pointerId: number } | undefined;
const nearestSlot = (x: number, y: number) => {
const canvas = toolbar.offsetParent!.getBoundingClientRect();
let nearest = toolbarSlot();
let nearestDistance = Infinity;
for (const slot of TOOLBAR_SLOTS) {
const anchor = TOOLBAR_SLOT_ANCHOR[slot];
const distance = Math.hypot(
x - (canvas.left + anchor.x * canvas.width),
y - (canvas.top + anchor.y * canvas.height),
);
if (distance < nearestDistance) {
nearest = slot;
nearestDistance = distance;
}
}
return nearest;
};
const handlePointerMove = (event: PointerEvent) => {
if (event.pointerId !== press?.pointerId) return;
if (!dragging()) {
if (Math.hypot(event.clientX - press.x, event.clientY - press.y) < DRAG_THRESHOLD) return;
// Captured, the press no longer ends in a click on the button it began on.
toolbar.setPointerCapture(event.pointerId);
}
setDropSlot(nearestSlot(event.clientX, event.clientY));
};
const handlePointerUp = (event: PointerEvent) => {
if (event.pointerId !== press?.pointerId) return;
press = undefined;
const slot = dropSlot();
if (slot) setToolbarSlot(slot);
setDropSlot(undefined);
window.removeEventListener("pointermove", handlePointerMove);
window.removeEventListener("pointerup", handlePointerUp);
window.removeEventListener("pointercancel", handlePointerUp);
};
const handlePointerDown = (event: PointerEvent) => {
// Menus open on the press: one begun on their trigger is theirs.
if (event.button !== 0 || (event.target as Element).closest("[aria-haspopup]")) return;
press = { x: event.clientX, y: event.clientY, pointerId: event.pointerId };
window.addEventListener("pointermove", handlePointerMove);
window.addEventListener("pointerup", handlePointerUp);
window.addEventListener("pointercancel", handlePointerUp);
};
onCleanup(() => {
window.removeEventListener("pointermove", handlePointerMove);
window.removeEventListener("pointerup", handlePointerUp);
window.removeEventListener("pointercancel", handlePointerUp);
});
// Up top, the menus open downwards, into the canvas.
const menuPlacement = () => (isTopSlot(toolbarSlot()) ? "bottom-start" : "top-start");
return (
<>
<Show when={promptInputOpen()}>
<PromptInput initialConfig={promptInputConfig()} />
</Show>
<Show when={!promptInputOpen()}>
<Switch fallback={<ActionBar openPromptInput={openPromptInput} />}>
<Switch fallback={<CommandBar />}>
<Match when={selectedTool() === ToolType.OBJECT_MASK}>
<ObjectMaskBar />
</Match>
<Match when={selectedTool() === ToolType.CLIP_PATH}>
<ClipPathBar />
<Match when={selectedTool() === ToolType.MASK}>
<MaskBar />
</Match>
</Switch>
</Show>
<div class="absolute bottom-4 left-1/2 -translate-x-1/2 rounded-xl p-1.5 bg-background border border-border-strong flex gap-2 items-center z-10">
<Show when={dragging()}>
<For each={TOOLBAR_SLOTS.filter((slot) => slot !== toolbarSlot())}>
{(slot) => (
// As tall as the toolbar: its buttons, padding and border.
<div
class={cx(
"absolute z-10 h-10.5 rounded-xl bg-foreground/6 pointer-events-none transition-all duration-150",
TOOLBAR_SLOT_CLASS[slot],
slot === dropSlot() ? "w-55" : "w-10.5",
)}
/>
)}
</For>
</Show>
{/* Up top, it sits over the desktop window's drag strip, which would take its clicks. */}
<div
ref={toolbar}
class={cx(
"absolute rounded-xl p-1.5 bg-background border border-border-strong flex gap-2 items-center z-30",
TOOLBAR_SLOT_CLASS[toolbarSlot()],
dragging() && "cursor-grabbing",
)}
style="-webkit-app-region: no-drag;"
onPointerDown={handlePointerDown}
>
<div class="flex gap-1">
<Tooltip>
<TooltipTrigger
@ -97,7 +227,7 @@ export function Toolbar() {
{(cursorTool() ?? CURSOR_TOOLS[0]!).label}
</TooltipContent>
</Tooltip>
<DropdownMenu placement="top-start">
<DropdownMenu placement={menuPlacement()}>
<Tooltip>
<TooltipTrigger<typeof DropdownMenuTrigger>
as={(triggerProps: object) => (
@ -142,7 +272,7 @@ export function Toolbar() {
>
<Icon name="frame" class="size-5" />
</TooltipTrigger>
<TooltipContent shortcut="F">Frame</TooltipContent>
<TooltipContent shortcut="F">Scene</TooltipContent>
</Tooltip>
<div class="flex gap-1">
<Tooltip>
@ -157,7 +287,7 @@ export function Toolbar() {
</TooltipTrigger>
<TooltipContent shortcut={lastShapeTool().shortcut}>{lastShapeTool().label}</TooltipContent>
</Tooltip>
<DropdownMenu placement="top-start">
<DropdownMenu placement={menuPlacement()}>
<Tooltip>
<TooltipTrigger<typeof DropdownMenuTrigger>
as={(triggerProps: object) => (
@ -215,10 +345,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}
@ -229,7 +355,20 @@ export function Toolbar() {
>
<Icon name="ai-generate" class="size-7" />
</TooltipTrigger>
<TooltipContent>AI generate</TooltipContent>
<TooltipContent shortcut="G">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>
</>

View File

@ -0,0 +1,22 @@
/* 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 { useAutoCaptions } from "@/components/genai/use-auto-captions";
export function AutoCaptionsCommand() {
const { scene, generate } = useAutoCaptions();
useCommand({
id: "auto-captions",
title: "Generate captions",
group: "Media",
icon: "captions",
keywords: ["auto-captions", "subtitles", "transcribe"],
available: () => !!scene(),
run: generate,
});
return null;
}

View File

@ -0,0 +1,25 @@
/* 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 { useWorld } from "@diffusionstudio/koota-solid";
import { useCommand } from "@/context/commands";
import { cleanUpSelection, getAlignableSelection, useSelection } from "@/engine";
/** Lays a selection of several out in a grid on the canvas (see `cleanUpSelection`). */
export function CleanUpCommand() {
const world = useWorld();
const { nodes } = useSelection();
useCommand({
id: "clean-up",
title: "Clean up",
group: "Object",
icon: "view-grid",
keywords: ["tidy", "grid", "arrange", "layout", "align", "distribute"],
available: () => nodes().length > 1 && getAlignableSelection(world).length > 1,
run: () => cleanUpSelection(world),
});
return null;
}

View File

@ -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}</>;
}

View File

@ -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.edit-with-prompt",
keywords: ["image", "prompt", "ai"],
available: () => imageMedia().length > 0,
run: () => openPromptInput(restoreConfig("IMAGE")),
});
return null;
}

View File

@ -0,0 +1,70 @@
/* 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 { 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 { store } from "@/init";
import type { LayerSection } from "@/context/commands";
/** 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. */
const PRESETS = [
{ id: "1080p", name: "Full HD", resolution: 1080 },
{ id: "1440p", name: "2k Quad HD", resolution: 1440 },
{ 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() {
const { exportFrame } = useExport();
const scene = useActiveScene();
const sections = (): LayerSection[] => {
const computed = scene()?.get(Computed);
const width = computed?.width || 1920;
const height = computed?.height || 1080;
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) => {
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);
};
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 null;
}

View File

@ -0,0 +1,107 @@
/* 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 { 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";
import { store } from "@/init";
import {
DEFAULT_EXPORT_TEMPLATE_ID,
EXPORT_TEMPLATE_GROUPS,
TEMPLATE_BY_ID,
} from "@/components/sidebar-right/inspector/export-templates";
import type { ExportConfig } from "@/components/sidebar-right/inspector/export-templates";
import type { LayerSection } from "@/context/commands";
/** 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";
/** "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";
const resolution = config.video?.resolution ?? 1080;
const size = resolution === 2160 ? "4K" : `${resolution}p`;
return config.format && config.format !== "mp4" ? `${size} · ${config.format.toUpperCase()}` : size;
}
/** 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;
});
// 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 own = sceneSettings();
return [
...(own ? [{
name: "Scene settings",
options: [{ id: SCENE_SETTINGS, title: describe(own), detail: pixels(own) }]
}] : []),
...EXPORT_TEMPLATE_GROUPS.map((group) => ({
name: group.label,
options: group.items.map((template) => ({
id: template.id,
title: template.name,
keywords: [describe(template)],
detail: pixels(template),
})),
})),
];
};
// 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 pick = (id: string) => {
const active = scene();
const settings = id === SCENE_SETTINGS ? sceneSettings() : TEMPLATE_BY_ID.get(id);
if (!active || !settings) return;
if (id !== SCENE_SETTINGS) store.set(LAST_PRESET_KEY, id);
void exportScene(active, { format: settings.format, video: settings.video, audio: settings.audio });
};
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;
}

View File

@ -0,0 +1,34 @@
/* 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 { PROMPT_INPUT_MODE_OPTIONS } from "@/components/genai/config";
import { restoreConfig } from "@/components/genai/saved-config";
import type { PromptMode } from "@/components/genai/config";
const KEYWORDS: Record<PromptMode, string[]> = {
IMAGE: ["picture", "photo", "text to image"],
VIDEO: ["clip", "animate", "text to video"],
VOICE: ["speech", "narration", "voiceover", "text to speech", "tts"],
AUDIO: ["sound", "music", "sound effect", "sfx"],
};
/** Opens the prompt box in `mode`, as it was last left in that mode. */
export function GenerateCommand(props: { mode: PromptMode }) {
const { openPromptInput } = usePromptInput();
const option = PROMPT_INPUT_MODE_OPTIONS.find((entry) => entry.value === props.mode)!;
useCommand({
id: `generate:${props.mode}`,
title: `Generate ${option.label.toLowerCase()}`,
group: "Generate",
icon: option.icon,
keywords: ["ai", "prompt", "create", ...KEYWORDS[props.mode]],
run: () => openPromptInput(restoreConfig(props.mode)),
});
return null;
}

View File

@ -0,0 +1,69 @@
/* 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 { ToolType } from "@diffusionstudio/runtime";
import { AutoCaptionsCommand } from "./auto-captions";
import { CleanUpCommand } from "./clean-up";
import { EditWithPromptCommand } from "./edit-with-prompt";
import { ExportCurrentFrameCommand } from "./export-current-frame";
import { ExportVideoCommand } from "./export-video";
import { GenerateCommand } from "./generate";
import { LayerToggleCommands } from "./layer-toggles";
import { MakeVideoCommand } from "./make-video";
import { MediaAssetCommands } from "./media-asset";
import { ProjectFolderCommands } from "./project-folder";
import { RemoveBackgroundCommand } from "./remove-background";
import { RemoveSilenceCommand } from "./remove-silence";
import { RerunCommand } from "./rerun";
import { ReuseSettingsCommand } from "./reuse-settings";
import { ShortcutCommands } from "./shortcuts";
import { ToolCommand } from "./tool";
import { UpscaleCommand } from "./upscale";
import { WindowCommands } from "./window";
export { CommandBar } from "./command-bar";
export { CommandPalette } from "./palette";
export { CANVAS_MENU, CommandContextMenu, NodeContextMenu, TIMELINE_HEADER_MENU, TIMELINE_MENU } from "./node-menu";
export { ReloadWindowCommand } from "./reload-window";
/**
* The canvas's commands: what to generate, what the selected media can be
* run through, the toolbar's tools, the keyboard shortcuts, where else
* the project folder can be opened, and the panels around the canvas.
*/
export function CanvasCommands() {
return (
<>
<GenerateCommand mode="IMAGE" />
<GenerateCommand mode="VIDEO" />
<GenerateCommand mode="VOICE" />
<GenerateCommand mode="AUDIO" />
<EditWithPromptCommand />
<MakeVideoCommand />
<RerunCommand />
<ReuseSettingsCommand />
<UpscaleCommand />
<RemoveBackgroundCommand />
<AutoCaptionsCommand />
<RemoveSilenceCommand />
<MediaAssetCommands />
<CleanUpCommand />
<ExportVideoCommand />
<ExportCurrentFrameCommand />
<ToolCommand tool={ToolType.MOVE} />
<ToolCommand tool={ToolType.HAND} />
<ToolCommand tool={ToolType.OBJECT_MASK} />
<ToolCommand tool={ToolType.SCENE} />
<ToolCommand tool={ToolType.RECT} />
<ToolCommand tool={ToolType.ELLIPSE} />
<ToolCommand tool={ToolType.POLYGON} />
<ToolCommand tool={ToolType.PEN} />
<ToolCommand tool={ToolType.TEXT} />
<ShortcutCommands />
<LayerToggleCommands />
<ProjectFolderCommands />
<WindowCommands />
</>
);
}

View File

@ -0,0 +1,35 @@
/* 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 { useWorld } from "@diffusionstudio/koota-solid";
import { useCommand } from "@/context/commands";
import { toggleSelectionMuted, toggleSelectionSoloed, useSelection } from "@/engine";
/** What the layer list's mute and solo buttons do, over the selection. */
export function LayerToggleCommands() {
const world = useWorld();
const { nodes } = useSelection();
useCommand({
id: "toggle-muted",
title: "Mute/Unmute",
group: "Object",
icon: "mute",
keywords: ["mute", "unmute", "audio", "sound", "silence"],
available: () => nodes().length > 0,
run: () => toggleSelectionMuted(world),
});
useCommand({
id: "toggle-soloed",
title: "Toggle solo",
group: "Object",
icon: "solo",
keywords: ["solo", "unsolo", "audio", "listen"],
available: () => nodes().length > 0,
run: () => toggleSelectionSoloed(world),
});
return null;
}

View File

@ -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;
}

View File

@ -0,0 +1,134 @@
/* 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, onCleanup, onMount } from "solid-js";
import { toast } from "somoto";
import { assetFolder, isUrlSource } from "@diffusionstudio/assets";
import { setSidebarTab } from "@/agent-chat";
import { useMediaSelection } from "@/components/genai/selection";
import { revealInAssets } from "@/components/sidebar-left/reveal";
import { useCommand } from "@/context/commands";
import { useLayout } from "@/context/layout";
import { useLibrary } from "@/engine/library";
import { revealPath } from "@/lib/shell";
import { isWindowsDesktop } from "@/projects";
import type { Asset } from "@diffusionstudio/assets";
/** The layer option for the library's root; no folder path starts with a slash. */
const ROOT = "/";
export function MediaAssetCommands() {
const library = useLibrary();
const layout = useLayout();
const { media } = useMediaSelection();
/** The assets the selected media shows, each once. */
const shown = createMemo(() => [
...new Set(media().map((entry) => entry.asset).filter((asset) => asset !== undefined)),
]);
/** Those of them in the library: what the panel lists and a folder holds. */
const listed = createMemo(() => shown().filter((asset) => !asset.transient));
/** The first of them that is a file here, rather than a download's URL. */
const file = () => (window.desktop ? shown().find((asset) => !isUrlSource(asset.source)) : undefined);
const folders = () => [...(library()?.folders() ?? [])].sort();
const moveTo = (id: string) => {
library()?.move(listed(), id === ROOT ? "" : id);
};
const showInAssets = () => {
const assets = listed();
if (!assets.length) return;
const folder = assetFolder(assets[0]!);
// Only what is in the folder that opens: the panel selects what it shows.
const ids = assets.filter((asset) => assetFolder(asset) === folder).map((asset) => asset.id);
if (!layout.uiVisible()) layout.toggleUI();
setSidebarTab("assets");
revealInAssets({ folder, ids });
};
const showInFinder = async (asset: Asset) => {
try {
await revealPath(library()?.fs.absolute?.(asset.source) ?? asset.source);
} catch (e) {
toast.error("Failed to show the file", { description: (e as Error).message });
}
};
useCommand({
id: "set-folder",
title: "Set folder",
group: "Assets",
icon: "navigation.folder",
keywords: ["move", "folder", "asset", "organize"],
available: () => listed().length > 0 && folders().length > 0,
layer: {
placeholder: "Search for folder",
sections: () => [{
name: "Folders",
options: [{ id: ROOT, title: "All assets" }, ...folders().map((folder) => ({ id: folder, title: folder }))],
}],
current: () => {
const asset = listed()[0];
return asset ? assetFolder(asset) || ROOT : undefined;
},
pick: moveTo,
},
});
useCommand({
id: "reveal-in-assets",
title: "Reveal in assets",
group: "Assets",
icon: "assets",
keywords: ["show", "find", "library", "asset"],
shortcut: ["⇧", "⌘", "O"],
available: () => listed().length > 0,
run: showInAssets,
});
useCommand({
id: "reveal-in-finder",
title: isWindowsDesktop() ? "Reveal in Explorer" : "Reveal in Finder",
group: "Assets",
icon: "external-link",
keywords: ["show", "file", "finder", "explorer", "folder"],
shortcut: ["⌥", "⌘", "O"],
available: () => file() !== undefined,
run: () => {
const asset = file();
if (asset) void showInFinder(asset);
},
});
// ⇧⌘O and ⌥⌘O, ahead of the editor, which would otherwise record the key
// as held. By code: ⌥ turns the O into another character on a Mac.
const onKeyDown = (event: KeyboardEvent) => {
if (!(event.metaKey || event.ctrlKey) || event.code !== "KeyO") return;
if (event.shiftKey && !event.altKey && listed().length > 0) {
event.preventDefault();
event.stopPropagation();
showInAssets();
return;
}
const asset = file();
if (event.altKey && !event.shiftKey && asset) {
event.preventDefault();
event.stopPropagation();
showInFinder(asset);
}
};
onMount(() => window.addEventListener("keydown", onKeyDown, true));
onCleanup(() => window.removeEventListener("keydown", onKeyDown, true));
return null;
}

View File

@ -0,0 +1,364 @@
/* 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 menu a right-click on nodes puts up, the way Figma's does: the click
// selects what it lands on first (unless that is selected already, so a
// selection of several survives it), and the menu lists what the palette
// offers for that selection. Every surface that shows nodes wraps itself in
// one, and says which nodes are under the pointer.
import { createSignal, For, Show, splitProps } from "solid-js";
import { useWorld } from "@diffusionstudio/koota-solid";
import {
ContextMenu,
ContextMenuContent,
ContextMenuGroup,
ContextMenuItem,
ContextMenuPortal,
ContextMenuSeparator,
ContextMenuShortcut,
ContextMenuSub,
ContextMenuSubContent,
ContextMenuSubTrigger,
ContextMenuTrigger,
} from "@/components/ui/context-menu";
import { Icon } from "@/components/ui/icon";
import { useCommands } from "@/context/commands";
import { getDocumentEditor, useSelection } from "@/engine";
import type { Entity } from "koota";
import type { JSX } from "solid-js";
import type { CommandLayer, RegisteredCommand } from "@/context/commands";
/**
* What a menu lists, a rule between sections: commands by id, and submenus
* of them. A command that has nothing in the selection to work on is left
* out, and a section or submenu left with none goes with it.
*/
export type MenuLayout = MenuEntry[][];
export type MenuEntry = string | { submenu: string; layout: MenuLayout };
/** What a menu lists over a selection, and over nothing. */
export type NodeMenuLayout = {
nodes: MenuLayout;
empty: MenuLayout;
};
const CLIPBOARD = ["shortcut:copy", "shortcut:cut", "shortcut:paste", "shortcut:duplicate", "shortcut:delete"];
const STRUCTURE = [
"shortcut:group",
"shortcut:ungroup",
"shortcut:use-as-mask",
"shortcut:wrap-in-scene",
"shortcut:wrap-in-sequence",
"shortcut:unwrap-sequence",
];
/** What works on the selected media, the transforms in a submenu of their own. */
const MEDIA: MenuEntry[] = [
{ submenu: "Media actions", layout: [["upscale", "remove-background", "remove-silence", "rerun", "make-video", "reuse-settings", "edit-with-prompt"]] },
"auto-captions",
];
const ASSET = ["set-folder", "reveal-in-assets", "reveal-in-finder"];
export const CANVAS_MENU: NodeMenuLayout = {
nodes: [
CLIPBOARD,
STRUCTURE,
["clean-up", "shortcut:bring-to-front", "shortcut:send-to-back", "shortcut:toggle-hidden"],
MEDIA,
ASSET,
],
empty: [["shortcut:paste", "shortcut:select-all"], ["toggle-ui", "toggle-timeline", "toggle-chat", "actions"]],
};
/**
* The timeline's: cuts at the playhead and the layer list's monitoring
* toggles besides. Select all would select what the stage holds rather than
* the clips in view, so it is not offered over nothing.
*/
export const TIMELINE_MENU: NodeMenuLayout = {
nodes: [
CLIPBOARD,
["shortcut:split"],
STRUCTURE,
["shortcut:bring-to-front", "shortcut:send-to-back", "shortcut:toggle-hidden", "toggle-muted", "toggle-soloed"],
MEDIA,
],
empty: [["shortcut:paste"]],
};
/**
* The timeline header's: what its buttons do, and putting the timeline away
* (or bringing it back), which a double-click on it does too.
*/
export const TIMELINE_HEADER_MENU: MenuLayout = [
["shortcut:toggle-playback", "shortcut:split"],
["toggle-timeline"],
];
/** Whether `command` would run over the selection rather than ask for a target. */
const offered = (command: RegisteredCommand) => (command.available?.() ?? true) && (command.ready?.() ?? true);
/** A menu entry as it is shown: a command on offer, or a submenu with some. */
type MenuItem = RegisteredCommand | Submenu;
type Submenu = { submenu: string; sections: MenuItem[][] };
const isSubmenu = (item: MenuItem): item is Submenu => "submenu" in item;
/** Each submenu entry as last resolved. */
const resolved = new WeakMap<object, Submenu>();
const sameSections = (a: MenuItem[][], b: MenuItem[][]) =>
a.length === b.length &&
a.every((section, i) => section.length === b[i]!.length && section.every((item, j) => item === b[i]![j]));
/** `layout`'s commands that are on offer, sections and submenus left with none left out. */
function resolve(commands: RegisteredCommand[], layout: MenuLayout): MenuItem[][] {
const byId = new Map(commands.map((command) => [command.id, command]));
const resolveLayout = (sections: MenuLayout): MenuItem[][] =>
sections
.map((entries) =>
entries
.map((entry): MenuItem | undefined => {
if (typeof entry !== "string") {
const sections = resolveLayout(entry.layout);
if (!sections.length) return undefined;
// The same one while what it lists is: a new one would be
// mounted afresh, closing the submenu under the pointer.
const last = resolved.get(entry);
if (last && sameSections(last.sections, sections)) return last;
const submenu = { submenu: entry.submenu, sections };
resolved.set(entry, submenu);
return submenu;
}
const command = byId.get(entry);
return command && offered(command) ? command : undefined;
})
.filter((item) => item !== undefined),
)
.filter((section) => section.length > 0);
return resolveLayout(layout);
}
export type NodeContextMenuProps = Omit<JSX.HTMLAttributes<HTMLDivElement>, "onContextMenu"> & {
/** The nodes a right-click at `event` is on; empty over nothing. */
pick(event: MouseEvent): Entity[];
/** `CANVAS_MENU` when left out. */
layout?: NodeMenuLayout;
};
/** The rest of the props go to the element that answers the right-click, which holds `children`. */
export function NodeContextMenu(props: NodeContextMenuProps) {
const [local, rest] = splitProps(props, ["pick", "layout", "children"]);
const world = useWorld();
const { commands } = useCommands();
const { nodes } = useSelection();
const select = (event: MouseEvent) => {
const editor = getDocumentEditor(world);
const picked = local.pick(event);
const selected = nodes();
if (!picked.length) editor.clearSelection();
else if (!picked.every((node) => selected.includes(node))) editor.select(picked);
// Nothing to offer (over nothing, with nothing to paste): no menu at all,
// rather than an empty one. Prevented, the trigger leaves it closed.
if (live().length === 0) event.preventDefault();
};
/**
* What is on offer for the selection. Followed while the menu is open:
* what the selected media is (which `upscale` and the other media commands
* look at) is read off the engine once per tick, so a selection the
* right-click just made shows up in it a frame after the menu opens.
*/
const live = () => {
const layout = local.layout ?? CANVAS_MENU;
return resolve(commands(), nodes().length ? layout.nodes : layout.empty);
};
return (
<CommandMenu {...rest} sections={live} onContextMenu={select}>
{local.children}
</CommandMenu>
);
}
export type CommandContextMenuProps = Omit<JSX.HTMLAttributes<HTMLDivElement>, "onContextMenu"> & {
/** What the menu lists, a rule between sections. */
layout: MenuLayout;
};
/**
* A right-click menu of commands that work on no selection — a panel's
* header's, say. Unlike `NodeContextMenu`, the click leaves the selection be.
*/
export function CommandContextMenu(props: CommandContextMenuProps) {
const [local, rest] = splitProps(props, ["layout", "children"]);
const { commands } = useCommands();
const live = () => resolve(commands(), local.layout);
const prevent = (event: MouseEvent) => {
if (live().length === 0) event.preventDefault();
};
return (
<CommandMenu {...rest} sections={live} onContextMenu={prevent}>
{local.children}
</CommandMenu>
);
}
type CommandMenuProps = JSX.HTMLAttributes<HTMLDivElement> & {
/** What is on offer, followed while the menu is open. */
sections(): MenuItem[][];
onContextMenu(event: MouseEvent): void;
};
function CommandMenu(props: CommandMenuProps) {
const [local, rest] = splitProps(props, ["sections", "children"]);
const [frozen, setFrozen] = createSignal<MenuItem[][] | null>(null);
/**
* Holds the list as it stands until the menu is open again: a command run
* from it changes the selection, and the menu should not change under the
* pointer while it fades out.
*/
const freeze = () => {
if (frozen() === null) setFrozen(local.sections());
};
const sections = () => frozen() ?? local.sections();
return (
<ContextMenu onOpenChange={(open) => (open ? setFrozen(null) : freeze())}>
<ContextMenuTrigger {...rest}>
{local.children}
</ContextMenuTrigger>
<ContextMenuPortal>
<ContextMenuContent class="w-[220px]">
<MenuSections sections={sections()} onPick={freeze} />
</ContextMenuContent>
</ContextMenuPortal>
</ContextMenu>
);
}
type MenuSectionsProps = {
sections: MenuItem[][];
/** Before the item picked is carried out. */
onPick(): void;
};
/** A menu's items, or a submenu's, a rule between sections. */
function MenuSections(props: MenuSectionsProps) {
const { execute } = useCommands();
const item = (entry: MenuItem) => {
if (isSubmenu(entry)) {
return (
<ContextMenuSub>
<ContextMenuSubTrigger>{entry.submenu}</ContextMenuSubTrigger>
<ContextMenuPortal>
<ContextMenuSubContent class="w-[220px]">
<MenuSections sections={entry.sections} onPick={props.onPick} />
</ContextMenuSubContent>
</ContextMenuPortal>
</ContextMenuSub>
);
}
const command = entry;
if (command.layer) return <LayerSubmenu title={command.title} layer={command.layer} onPick={props.onPick} />;
return (
<ContextMenuItem
onSelect={() => {
props.onPick();
execute(command);
}}
>
{command.title}
<Show when={command.shortcut}>
{(keys) => <ContextMenuShortcut>{keys().join("")}</ContextMenuShortcut>}
</Show>
<Show when={command.credits?.()}>
{(credits) => (
<ContextMenuShortcut class="flex items-center tracking-normal tabular-nums">
<Icon name="ai-credits-small" class="-my-1" />
{credits().toLocaleString()}
</ContextMenuShortcut>
)}
</Show>
</ContextMenuItem>
);
};
return (
<For each={props.sections}>
{(section, index) => (
<>
<Show when={index() > 0}>
<ContextMenuSeparator />
</Show>
<ContextMenuGroup>
<For each={section}>{item}</For>
</ContextMenuGroup>
</>
)}
</For>
);
}
type LayerSubmenuProps = {
title: string;
layer: CommandLayer;
/** Before the option is carried out. */
onPick(): void;
};
/** A command the palette lists options for, as a submenu of them: a rule between its sections. */
function LayerSubmenu(props: LayerSubmenuProps) {
return (
<ContextMenuSub>
<ContextMenuSubTrigger>{props.title}</ContextMenuSubTrigger>
<ContextMenuPortal>
<ContextMenuSubContent class="w-[220px]">
<For each={props.layer.sections()}>
{(section, index) => (
<>
<Show when={index() > 0}>
<ContextMenuSeparator />
</Show>
<ContextMenuGroup>
<For each={section.options}>
{(option) => (
<ContextMenuItem
onSelect={() => {
props.onPick();
props.layer.pick(option.id);
}}
>
<span class="min-w-0 flex-1 truncate">{option.title}</span>
<Show when={option.detail}>
{(detail) => <ContextMenuShortcut>{detail()}</ContextMenuShortcut>}
</Show>
</ContextMenuItem>
)}
</For>
</ContextMenuGroup>
</>
)}
</For>
</ContextMenuSubContent>
</ContextMenuPortal>
</ContextMenuSub>
);
}

View File

@ -0,0 +1,321 @@
/* 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, 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 { LayerSection, LayeredCommand, RegisteredCommand } from "@/context/commands";
const offered = (command: RegisteredCommand) => command.palette !== false && (command.available?.() ?? true);
/**
* The least score a match needs to be listed. cmdk matches letters anywhere
* in order, so "group" finds g…r…o…u…p across a command's keywords; such a
* match scores well under this, a word or prefix or initials well over.
*/
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. A command with options
* lists them in a layer of its own, which Esc goes back from.
*/
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;
// 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;
// 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, 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>
<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>
);
}
type ListedSection = {
name: string;
commands: RegisteredCommand[];
/** Tells its items from the same commands listed in another section. */
key?: string;
};
/**
* The commands on offer that match `search`, in sections. Without a search,
* sections in `SECTIONS` order and commands by `order`, then in the order
* they 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): ListedSection[] {
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 >= MIN_SCORE)
.sort(
(a, b) =>
b.score - a.score ||
SECTIONS.indexOf(a.command.group) - SECTIONS.indexOf(b.command.group) ||
(a.command.order ?? 0) - (b.command.order ?? 0),
);
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 }));
}
const LIST_CLASS =
"max-h-[min(400px,60vh)] scroll-pt-1 scroll-pb-2.5 overflow-y-auto overflow-x-hidden px-3 pt-1 pb-2.5 [&_[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-9 cursor-default items-center text-xs text-foreground outline-hidden select-none";
/** The highlight is a row inset in the item, 2px short of it top and bottom. */
const ROW_CLASS = "flex h-8 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("");
const sections = createMemo((): ListedSection[] => {
const listed = rank(commands.commands(), search());
if (search().trim()) return listed;
const recent = commands
.recents()
.map((id) => commands.commands().find((command) => command.id === id && offered(command)))
.filter((command) => command !== undefined)
.slice(0, RECENTS_LISTED);
return recent.length ? [{ name: "Recents", commands: recent, key: "recent" }, ...listed] : listed;
});
return (
<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={GROUP_CLASS}>
<For each={section.commands}>
{(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>
</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>
)}
</For>
</CommandPrimitive.Group>
)}
</For>
</CommandPrimitive.List>
</CommandPrimitive>
);
}

View File

@ -0,0 +1,74 @@
/* 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, createResource } from "solid-js";
import { toast } from "somoto";
import { useCommand } from "@/context/commands";
import { useProject } from "@/context/project";
import { listEditors, openInEditor, revealPath } from "@/lib/shell";
import { isWindowsDesktop } from "@/projects";
import type { EditorId, EditorInfo } from "@/lib/shell";
/** Each editor's logo. */
const EDITOR_ICONS: Record<EditorId, string> = {
vscode: "editor.vscode",
cursor: "agent.cursor",
zed: "editor.zed",
};
/**
* The project folder's commands, as the File menu has them: showing it in
* Finder (Explorer on Windows), and opening it in each code editor installed
* here. Desktop only; off it there is no folder to show.
*/
export function ProjectFolderCommands() {
const project = useProject();
const [editors] = createResource(listEditors, { initialValue: [] });
const handleReveal = async () => {
try {
await revealPath(project.dir());
} catch (e) {
toast.error("Failed to show the folder", { description: (e as Error).message });
}
};
useCommand({
id: "show-project-folder",
title: isWindowsDesktop() ? "Show in Explorer" : "Show in Finder",
group: "File",
icon: "navigation.folder",
keywords: ["reveal", "project folder", "files", "finder", "explorer"],
available: () => Boolean(window.desktop && project.dir()),
run: () => void handleReveal(),
});
return <For each={editors()}>{(editor) => <OpenInEditorCommand editor={editor} />}</For>;
}
function OpenInEditorCommand(props: { editor: EditorInfo }) {
const project = useProject();
const { editor } = props;
const handleOpen = async () => {
try {
await openInEditor(editor.id, project.dir());
} catch (e) {
toast.error(`Failed to open in ${editor.label}`, { description: (e as Error).message });
}
};
useCommand({
id: `open-in-editor:${editor.id}`,
title: `Open in ${editor.label}`,
group: "File",
icon: EDITOR_ICONS[editor.id],
keywords: ["code editor", "project folder", "jsx", "source", editor.id],
available: () => Boolean(project.dir()),
run: () => void handleOpen(),
});
return null;
}

View File

@ -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";
/** Loads the window again, for when it is stuck; the project reopens from disk. */
export function ReloadWindowCommand() {
useCommand({
id: "reload-window",
title: "Force reload app",
group: "View",
icon: "reload",
keywords: ["refresh", "restart"],
shortcut: ["⇧", "⌘", "R"],
order: 1,
run: () => window.location.reload(),
});
return null;
}

View File

@ -0,0 +1,27 @@
/* 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 { useTransforms } from "@/components/genai/use-transforms";
import { TransformBar } from "./transform-bar";
export function RemoveBackgroundCommand() {
const { targets, run, price } = useTransforms();
useCommand({
id: "remove-background",
title: "Remove background",
group: "Media",
icon: "ai.remove-background",
keywords: ["cutout", "matte", "transparent"],
ready: () => targets("removeBackground").length > 0,
run: () => run("removeBackground"),
credits: () => price("removeBackground"),
bar: () => (
<TransformBar type="removeBackground" verb="Remove the background of" empty="Select an image to cut out" />
),
});
return null;
}

View File

@ -0,0 +1,85 @@
/* 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 { toast } from "somoto";
import { useWorld } from "@diffusionstudio/koota-solid";
import { Separator } from "@/components/ui/separator";
import { useCommand, useCommands } from "@/context/commands";
import { useSelection } from "@/engine/hooks";
import { detectClipSilences, removeSilences, silenceTargets } from "@/engine/silence/remove";
import { ActionBar, ActionBarCancel, ActionBarConfirm, ActionBarTarget } from "@/components/canvas/action-bar";
import type { Entity } from "koota";
import type { ClipSilences } from "@/engine/silence/remove";
/** Cuts the silent parts out of the selected video and audio clips and closes the gaps. */
export function RemoveSilenceCommand() {
const { targets, run } = useRemoveSilence();
useCommand({
id: "remove-silence",
title: "Remove silence",
group: "Media",
icon: "ai.remove-silences",
keywords: ["silent parts", "pauses", "gaps", "jump cut", "trim", "dead air", "audio"],
ready: () => targets().length > 0,
run: () => void run(),
bar: RemoveSilenceBar,
});
return null;
}
/** The selected clips with sound, cut on Confirm. */
function RemoveSilenceBar() {
const { close } = useCommands();
const { targets, run } = useRemoveSilence();
const confirm = () => {
void run();
close();
};
return (
<ActionBar>
<ActionBarTarget nodes={targets()} verb="Remove silence from" plural="clips" empty="Select a video or audio clip" />
<Separator orientation="vertical" class="min-h-5" />
<ActionBarCancel onCancel={close} />
<ActionBarConfirm disabled={targets().length === 0} onConfirm={confirm} hint="Remove" />
</ActionBar>
);
}
function useRemoveSilence() {
const world = useWorld();
const { nodes } = useSelection();
// Tracks the selection; which of it has sound is read off the world.
const targets = createMemo(() => (nodes(), silenceTargets(world)), [], { equals: sameEntities });
const run = async () => {
const clips = targets();
if (clips.length === 0) return;
const found: ClipSilences[] = [];
try {
for (const clip of clips) {
found.push({ clip, silences: await detectClipSilences(world, clip) });
}
} catch (e) {
console.error("Silence detection failed:", e);
toast.error("Failed to remove silence", { description: (e as Error).message });
return;
}
removeSilences(world, found);
};
return { targets, run };
}
function sameEntities(a: Entity[], b: Entity[]): boolean {
return a.length === b.length && a.every((entity, i) => entity === b[i]);
}

View File

@ -0,0 +1,65 @@
/* 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() {
const { media } = useMediaSelection();
useCommand({
id: "rerun",
title: "Rerun generation",
group: "Generate",
icon: "rerun",
keywords: ["regenerate", "again", "retry"],
available: () => media().some((entry) => entry.asset?.job !== undefined),
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>
);
}

View File

@ -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;
}

View File

@ -0,0 +1,415 @@
/* 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 keyboard shortcuts worth finding by name, in the palette under the
// names the project menu gives them: each runs what its keys run, and shows
// the keys.
import { For } from "solid-js";
import { useWorld } from "@diffusionstudio/koota-solid";
import {
FrameRate,
getActiveEntity,
isGroupLike,
isSequence,
shuttlePlayback,
stopPlayback,
togglePlayback,
} from "@diffusionstudio/runtime";
import { useCommand } from "@/context/commands";
import { clipboardHasMedia } from "@/lib/clipboard";
import {
applySelectionAsMask,
copySelection,
cutSelection,
deleteSelection,
duplicateSelection,
getDocumentEditor,
getEditHistory,
getSelectionMask,
groupSelection,
pasteSelection,
redoEdit,
restackSelection,
seekBy,
seekToSelectionEdge,
seekToTimelineEdge,
selectAll,
splitAtPlayhead,
toggleSelectionHidden,
undoEdit,
ungroupSelection,
unwrapSequenceSelection,
useActiveScene,
useSelection,
wrapSelectionInScene,
wrapSelectionInSequence,
} from "@/engine";
import type { Entity, World } from "koota";
import type { Section } from "@/context/commands";
import type { DocumentEditor, EditHistory } from "@/engine";
/** What a shortcut needs to have something to work on. */
type ShortcutState = {
/** The selected nodes. */
nodes: Entity[];
history: EditHistory;
editor: DocumentEditor;
scene: Entity | null;
world: World;
};
type Shortcut = {
id: string;
title: string;
group: Section;
icon: string;
/** Its keys, one cap each. */
keys: string[];
keywords?: string[];
run(world: World): void;
/** Whether it has something to work on; always, when left out. */
available?(state: ShortcutState): boolean;
};
const selection = ({ nodes }: ShortcutState) => nodes.length > 0;
const activeScene = ({ scene }: ShortcutState) => scene !== null;
/** Clips to seek to the edges of: the active scene is where they are, not one of them. */
const selectedClips = ({ nodes, scene }: ShortcutState) => scene !== null && nodes.some((node) => node !== scene);
/** Runs `action` on the active scene, if there is one. */
const onActiveScene = (action: (world: World, scene: Entity) => void) => (world: World) => {
const scene = getActiveEntity(world);
if (scene) action(world, scene);
};
const seekSeconds = (seconds: number) => (world: World) =>
seekBy(world, Math.round(seconds * (world.get(FrameRate)?.value ?? 30)));
const SHORTCUTS: Shortcut[] = [
{
id: "group",
title: "Group",
group: "Object",
icon: "group",
keys: ["⌘", "G"],
run: groupSelection,
available: selection,
},
{
id: "ungroup",
title: "Ungroup",
group: "Object",
icon: "group",
keys: ["⇧", "⌘", "G"],
run: ungroupSelection,
available: ({ nodes }) => nodes.some((node) => isGroupLike(node) || isSequence(node)),
},
{
id: "use-as-mask",
title: "Use as mask",
group: "Object",
icon: "mask-small",
keys: ["⌃", "⌘", "M"],
keywords: ["matte", "clip"],
run: applySelectionAsMask,
available: ({ nodes, world }) => nodes.length === 2 && getSelectionMask(world) !== null,
},
{
id: "wrap-in-scene",
title: "Wrap in scene",
group: "Object",
icon: "scene-frame-small",
keys: ["⌘", "↩︎"],
keywords: ["frame"],
run: wrapSelectionInScene,
available: selection,
},
{
id: "wrap-in-sequence",
title: "Wrap in sequence",
group: "Object",
icon: "timeline-sequence-small",
keys: ["⌥", "⌘", "↩︎"],
run: wrapSelectionInSequence,
available: selection,
},
{
id: "unwrap-sequence",
title: "Unwrap sequence",
group: "Object",
icon: "timeline-sequence-small",
keys: ["⌥", "⇧", "⌘", "↩︎"],
run: unwrapSequenceSelection,
available: ({ nodes }) => nodes.some(isSequence),
},
{
id: "bring-to-front",
title: "Bring to front",
group: "Object",
icon: "arrow-top",
keys: ["]"],
keywords: ["arrange", "order"],
run: (world) => restackSelection(world, "front"),
available: selection,
},
{
id: "send-to-back",
title: "Send to back",
group: "Object",
icon: "arrow-bottom",
keys: ["["],
keywords: ["arrange", "order"],
run: (world) => restackSelection(world, "back"),
available: selection,
},
{
id: "toggle-hidden",
title: "Show/Hide",
group: "Object",
icon: "eye-on",
keys: ["⇧", "⌘", "H"],
keywords: ["hide", "show"],
run: toggleSelectionHidden,
available: selection,
},
{
id: "toggle-playback",
title: "Play or pause",
group: "Timeline",
icon: "play",
keys: ["Space"],
keywords: ["playback", "stop"],
run: onActiveScene(togglePlayback),
available: activeScene,
},
{
id: "play-forward",
title: "Play forward",
group: "Timeline",
icon: "timeline.shuttle-forward",
keys: ["L"],
keywords: ["shuttle", "faster"],
run: onActiveScene((world, scene) => shuttlePlayback(world, scene, 1)),
available: activeScene,
},
{
id: "play-backward",
title: "Play backward",
group: "Timeline",
icon: "timeline.shuttle-backward",
keys: ["J"],
keywords: ["shuttle", "reverse", "rewind"],
run: onActiveScene((world, scene) => shuttlePlayback(world, scene, -1)),
available: activeScene,
},
{
id: "stop-playback",
title: "Stop playback",
group: "Timeline",
icon: "timeline.stop",
keys: ["K"],
keywords: ["shuttle", "pause"],
run: onActiveScene(stopPlayback),
available: activeScene,
},
{
id: "next-frame",
title: "Go to next frame",
group: "Timeline",
icon: "timeline.next-frame",
keys: ["D"],
keywords: ["step", "jump", "forward"],
run: (world) => seekBy(world, 1),
available: activeScene,
},
{
id: "previous-frame",
title: "Go to previous frame",
group: "Timeline",
icon: "timeline.previous-frame",
keys: ["A"],
keywords: ["step", "jump", "back"],
run: (world) => seekBy(world, -1),
available: activeScene,
},
{
id: "skip-forward",
title: "Skip forward 1 second",
group: "Timeline",
icon: "timeline.skip-forward",
keys: ["W"],
keywords: ["jump", "seek"],
run: seekSeconds(1),
available: activeScene,
},
{
id: "skip-back",
title: "Skip back 1 second",
group: "Timeline",
icon: "timeline.skip-back",
keys: ["S"],
keywords: ["jump", "seek"],
run: seekSeconds(-1),
available: activeScene,
},
{
id: "go-to-start",
title: "Go to start",
group: "Timeline",
icon: "timeline.go-to-start",
keys: ["Home"],
keywords: ["jump", "beginning", "first frame"],
run: (world) => seekToTimelineEdge(world, "start"),
available: activeScene,
},
{
id: "go-to-end",
title: "Go to end",
group: "Timeline",
icon: "timeline.go-to-end",
keys: ["End"],
keywords: ["jump", "last frame"],
run: (world) => seekToTimelineEdge(world, "end"),
available: activeScene,
},
{
id: "go-to-selection-start",
title: "Go to selection start",
group: "Timeline",
icon: "timeline.go-to-selection-start",
keys: [";"],
keywords: ["jump", "clip", "in point"],
run: (world) => seekToSelectionEdge(world, "start"),
available: selectedClips,
},
{
id: "go-to-selection-end",
title: "Go to selection end",
group: "Timeline",
icon: "timeline.go-to-selection-end",
keys: ["'"],
keywords: ["jump", "clip", "out point"],
run: (world) => seekToSelectionEdge(world, "end"),
available: selectedClips,
},
{
id: "split",
title: "Split at playhead",
group: "Timeline",
icon: "split",
keys: ["⌘", "B"],
keywords: ["cut", "razor", "blade"],
run: splitAtPlayhead,
available: activeScene,
},
{
id: "undo",
title: "Undo",
group: "Edit",
icon: "undo",
keys: ["⌘", "Z"],
run: undoEdit,
available: ({ history }) => history.canUndo(),
},
{
id: "redo",
title: "Redo",
group: "Edit",
icon: "redo",
keys: ["⇧", "⌘", "Z"],
run: redoEdit,
available: ({ history }) => history.canRedo(),
},
{
id: "copy",
title: "Copy",
group: "Edit",
icon: "copy",
keys: ["⌘", "C"],
keywords: ["clipboard"],
run: copySelection,
available: selection,
},
{
id: "cut",
title: "Cut",
group: "Edit",
icon: "cut",
keys: ["⌘", "X"],
keywords: ["clipboard"],
run: cutSelection,
available: selection,
},
{
id: "paste",
title: "Paste",
group: "Edit",
icon: "paste",
keys: ["⌘", "V"],
keywords: ["clipboard"],
run: pasteSelection,
available: ({ editor }) => editor.canPaste() || clipboardHasMedia(),
},
{
id: "duplicate",
title: "Duplicate",
group: "Edit",
icon: "duplicate",
keys: ["⌘", "D"],
keywords: ["copy", "clone"],
run: duplicateSelection,
available: selection,
},
{
id: "delete",
title: "Delete",
group: "Edit",
icon: "trash",
keys: ["⌫"],
keywords: ["remove"],
run: deleteSelection,
available: selection,
},
{
id: "select-all",
title: "Select all",
group: "Edit",
icon: "select-all",
keys: ["⌘", "A"],
run: selectAll,
},
];
/** Every shortcut as a command, sharing one read of what they work on. */
export function ShortcutCommands() {
const world = useWorld();
const { nodes } = useSelection();
const scene = useActiveScene();
const history = getEditHistory(world);
const editor = getDocumentEditor(world);
const state = (): ShortcutState => ({ nodes: nodes(), history, editor, scene: scene(), world });
return <For each={SHORTCUTS}>{(shortcut) => <ShortcutCommand shortcut={shortcut} state={state} />}</For>;
}
function ShortcutCommand(props: { shortcut: Shortcut; state: () => ShortcutState }) {
const world = useWorld();
const { shortcut } = props;
useCommand({
id: `shortcut:${shortcut.id}`,
title: shortcut.title,
group: shortcut.group,
icon: shortcut.icon,
keywords: shortcut.keywords,
shortcut: shortcut.keys,
available: shortcut.available ? () => shortcut.available!(props.state()) : undefined,
run: () => shortcut.run(world),
});
return null;
}

View File

@ -0,0 +1,51 @@
/* 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 { useWorld } from "@diffusionstudio/koota-solid";
import { Tool, ToolType } from "@diffusionstudio/runtime";
import { useCommand } from "@/context/commands";
type ToolEntry = {
title: string;
icon: string;
/** The key that picks it outside the palette. */
key?: string;
keywords: string[];
};
/** The toolbar's tools, as the palette lists them. */
const TOOLS: Partial<Record<ToolType, ToolEntry>> = {
[ToolType.MOVE]: { title: "Move", icon: "move", key: "V", keywords: ["select", "pointer", "cursor"] },
[ToolType.HAND]: { title: "Hand", icon: "hand", key: "H", keywords: ["pan", "scroll"] },
[ToolType.OBJECT_MASK]: {
title: "Object Mask",
icon: "object-mask",
key: "M",
keywords: ["smart object mask", "segment", "track", "cutout", "sam", "rotoscope"],
},
[ToolType.SCENE]: { title: "Scene", icon: "scene-frame-small", key: "F", keywords: ["create", "frame", "artboard"] },
[ToolType.RECT]: { title: "Rectangle", icon: "tool.rectangle", key: "R", keywords: ["draw", "shape", "square", "box"] },
[ToolType.ELLIPSE]: { title: "Ellipse", icon: "tool.ellipse", key: "O", keywords: ["draw", "shape", "circle", "oval"] },
[ToolType.POLYGON]: { title: "Polygon", icon: "tool.polygon", keywords: ["draw", "shape", "triangle", "star"] },
[ToolType.PEN]: { title: "Pen", icon: "tool.pen", key: "P", keywords: ["draw", "path", "vector", "bezier", "curve"] },
[ToolType.TEXT]: { title: "Text", icon: "tool.text", key: "T", keywords: ["add", "type", "title", "label"] },
};
/** Picks `tool`, as its toolbar button does. */
export function ToolCommand(props: { tool: ToolType }) {
const world = useWorld();
const entry = TOOLS[props.tool]!;
useCommand({
id: `tool:${props.tool}`,
title: entry.title,
group: "Tools",
icon: entry.icon,
keywords: ["tool", ...entry.keywords],
shortcut: entry.key ? [entry.key] : undefined,
run: () => world.set(Tool, { value: props.tool }),
});
return null;
}

View File

@ -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]);
}

View File

@ -0,0 +1,25 @@
/* 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 { useTransforms } from "@/components/genai/use-transforms";
import { TransformBar } from "./transform-bar";
export function UpscaleCommand() {
const { targets, run, price } = useTransforms();
useCommand({
id: "upscale",
title: "Upscale",
group: "Media",
icon: "arrow-scale",
keywords: ["resolution", "enhance", "sharpen"],
ready: () => targets("upscale").length > 0,
run: () => run("upscale"),
credits: () => price("upscale"),
bar: () => <TransformBar type="upscale" verb="Upscale" empty="Select an image or video to upscale" />,
});
return null;
}

View File

@ -0,0 +1,141 @@
/* 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 { onCleanup, onMount } from "solid-js";
import { setActiveChat, setSidebarTab, sidebarTab } from "@/agent-chat/store";
import { useCommand, useCommands } from "@/context/commands";
import { useLayout } from "@/context/layout";
import { useProject } from "@/context/project";
/** Showing and hiding the panels around the canvas, the chat, and the palette itself. */
export function WindowCommands() {
const layout = useLayout();
const project = useProject();
const { setPaletteOpen } = useCommands();
useCommand({
id: "toggle-ui",
title: "Show/Hide UI",
group: "View",
icon: "sidebar",
keywords: ["panels", "sidebar", "focus", "fullscreen", "toggle ui"],
shortcut: ["⌘", "\\"],
run: layout.toggleUI,
});
const timelineShown = () => layout.uiVisible() && !layout.timelineMinimized();
// With the UI hidden the timeline is too, so showing it brings the UI back.
const toggleTimeline = () => {
if (timelineShown()) {
layout.toggleTimeline();
return;
}
if (!layout.uiVisible()) layout.toggleUI();
if (layout.timelineMinimized()) layout.toggleTimeline();
};
useCommand({
id: "toggle-timeline",
title: "Show/Hide timeline",
group: "View",
icon: "sidebar-timeline",
keywords: ["panel", "tracks", "layers", "minimize", "toggle timeline"],
shortcut: ["⌘", "J"],
run: toggleTimeline,
});
const chatShown = () => layout.uiVisible() && sidebarTab() === "chat";
const showChat = () => {
if (!layout.uiVisible()) layout.toggleUI();
setSidebarTab("chat");
// A composer that mounts with the tab focuses itself; one that was up
// already is focused here, once the menu that ran this has let go.
requestAnimationFrame(() => document.querySelector<HTMLTextAreaElement>("[data-chat-composer]")?.focus());
};
const toggleChat = () => {
if (chatShown()) setSidebarTab("assets");
else showChat();
};
// What the chat header's plus does, from wherever the chat is.
const newChat = () => {
setActiveChat(project.id(), null);
showChat();
};
useCommand({
id: "toggle-chat",
title: "Show/Hide chat",
group: "View",
icon: "ask-chat",
keywords: ["open chat", "agent", "assistant", "message", "claude"],
shortcut: ["⌘", "L"],
run: toggleChat,
});
useCommand({
id: "new-chat",
title: "New chat thread",
group: "View",
icon: "plus-add",
keywords: ["new thread", "conversation", "agent", "assistant", "claude"],
shortcut: ["⇧", "⌘", "L"],
palette: false,
run: newChat,
});
useCommand({
id: "actions",
title: "Actions…",
group: "View",
icon: "tool.actions-spotlight",
shortcut: ["⌘", "K"],
palette: false,
run: () => setPaletteOpen(true),
});
// ⌘\, ⌘J, ⌘L and ⇧⌘L wherever focus is, a field included, as ⌘K is:
// ahead of the editor, which would otherwise record the key as held.
const onKeyDown = (event: KeyboardEvent) => {
if (!(event.metaKey || event.ctrlKey) || event.altKey) return;
if (event.shiftKey) {
if (event.key.toLowerCase() !== "l" && event.code !== "KeyL") return;
event.preventDefault();
event.stopPropagation();
newChat();
return;
}
if (event.key === "\\" || event.code === "Backslash") {
event.preventDefault();
event.stopPropagation();
layout.toggleUI();
return;
}
if (event.key.toLowerCase() === "j" || event.code === "KeyJ") {
event.preventDefault();
event.stopPropagation();
toggleTimeline();
return;
}
if (event.key.toLowerCase() === "l" || event.code === "KeyL") {
event.preventDefault();
event.stopPropagation();
toggleChat();
}
};
onMount(() => window.addEventListener("keydown", onKeyDown, true));
onCleanup(() => window.removeEventListener("keydown", onKeyDown, true));
return null;
}

View File

@ -17,6 +17,7 @@ import {
createResource,
onCleanup,
type JSX,
type Signal,
} from "solid-js";
import { createStore, reconcile } from "solid-js/store";
import { Separator } from "../ui/separator";
@ -36,6 +37,7 @@ import {
projectsRevision,
relocateProject,
type ProjectInfo,
type ProjectRecord,
} from "@/projects";
@ -563,12 +565,12 @@ export function createProjectList() {
const [store, setStore] = createStore({ value: initial });
return [
() => store.value,
(next) => {
(next?: ProjectRecord[] | ((prev?: ProjectRecord[]) => ProjectRecord[] | undefined)) => {
const value = typeof next === "function" ? next(store.value) : next;
setStore("value", reconcile(value, { key: "dir" }));
return store.value;
},
];
] as Signal<ProjectRecord[] | undefined>;
},
});
}

View File

@ -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>
);
}

View File

@ -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";

View File

@ -106,7 +106,7 @@ export function PromptInputActions() {
<TransformItem name="upscale" icon="arrow-scale" label="Upscale" run={run} />
</Show>
<Show when={hasImageSelection()}>
<TransformItem name="removeBackground" icon="ai-generate" label="Remove background" run={run} />
<TransformItem name="removeBackground" icon="ai.remove-background" label="Remove background" run={run} />
</Show>
</DropdownMenuGroup>
</DropdownMenuContent>

View File

@ -59,6 +59,10 @@ import { useEditor } from "@/engine/hooks";
import { droppedFiles, importFiles, pickFiles } from "@/engine/asset-actions";
import { useMediaSelection } from "./selection";
import { ASSET_DRAG_TYPE } from "@/components/sidebar-left/folder-item";
import { useBarKey } from "@/components/canvas/action-bar";
import { isTopSlot } from "@/components/canvas/toolbar-slot";
import { useLayout } from "@/context/layout";
import { usePromptInput } from "@/context/prompt-input";
import type { ModelId, Resolution } from "@diffusionstudio/api-contract";
import type { AssetCache } from "@diffusionstudio/assets";
@ -80,6 +84,14 @@ export function PromptInput(props: PromptInputProps) {
const editor = useEditor();
const { images: selectedImages } = useMediaSelection();
const { generate } = useGenerate();
const { setPromptInputOpen } = usePromptInput();
const { toolbarSlot } = useLayout();
// Esc puts the box down, what was typed kept for next time: from the
// prompt, once the recent prompts are dismissed, and from anywhere else
// but an open menu or another field.
const close = () => setPromptInputOpen(false);
useBarKey((event) => event.key === "Escape", close);
let textareaRef!: HTMLTextAreaElement;
let dragCounter = 0;
@ -306,6 +318,9 @@ export function PromptInput(props: PromptInputProps) {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
handleSubmit();
} else if (e.key === "Escape") {
e.preventDefault();
close();
}
};
@ -388,7 +403,10 @@ export function PromptInput(props: PromptInputProps) {
return (
<div
class="absolute w-xl max-w-[calc(100%-2rem)] bottom-16 z-10 mx-auto left-1/2 -translate-x-1/2 flex flex-col gap-2 rounded-xl border border-border bg-background p-2"
class={cx(
"absolute w-xl max-w-[calc(100%-2rem)] z-10 mx-auto left-1/2 -translate-x-1/2 flex flex-col gap-2 rounded-xl border border-border bg-background p-2",
isTopSlot(toolbarSlot()) ? "bottom-4" : "bottom-16",
)}
onDragOver={handleDragOver}
onDragEnter={handleDragEnter}
onDragLeave={handleDragLeave}

View File

@ -2,26 +2,34 @@
* 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 { Scene } from "@diffusionstudio/runtime";
import { useProject } from "@/context/project";
import { generateCaptions } from "@/engine/generate";
import { useSelection } from "@/engine/hooks";
import { useActiveScene, useSelection } from "@/engine/hooks";
/**
* Captions for the selected scene, or the active one, the one being edited,
* when nothing is selected. A selection without a scene in it has none: other
* nodes are not captioned.
*/
export function useAutoCaptions() {
const world = useWorld();
const project = useProject();
const { nodes } = useSelection();
const active = useActiveScene();
const scenes = createMemo(() => nodes().filter(isScene));
const hasScene = createMemo(() => scenes().length > 0);
const scene = () => {
const selected = nodes();
return selected.length ? selected.find((node) => node.has(Scene)) ?? null : active();
};
const generate = () => {
for (const scene of scenes()) {
generateCaptions(world, scene, project.dir());
const target = scene();
if (target) {
generateCaptions(world, target, project.dir());
}
};
return { hasScene, generate };
return { scene, generate };
}

View File

@ -70,5 +70,5 @@ export function useTransforms() {
return prices.reduce<number>((sum, credits) => sum + credits!, 0);
};
return { run, price };
return { targets, run, price };
}

View File

@ -2,38 +2,53 @@
* 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, onMount, onCleanup, Show, createMemo } from "solid-js";
import { toast } from "somoto";
import { useWorld } from "@diffusionstudio/koota-solid";
import { assetName } from "@diffusionstudio/assets";
import { insertAssetAtPlayhead, replaceAssetSource, saveAssetAs } from "@/engine/asset-actions";
import { createSignal, onMount, onCleanup, For, Show, createMemo } from "solid-js";
import { assetFolder, assetName } from "@diffusionstudio/assets";
import { replaceAssetSource, saveAssetAs } from "@/engine/asset-actions";
import {
ContextMenu,
ContextMenuContent,
ContextMenuGroup,
ContextMenuItem,
ContextMenuPortal,
ContextMenuSeparator,
ContextMenuShortcut,
ContextMenuSub,
ContextMenuSubContent,
ContextMenuSubTrigger,
ContextMenuTrigger,
} from "../ui/context-menu";
import { AssetThumbnail } from "../ui/asset-thumbnail";
import { MiddleEllipsis } from "../ui/middle-ellipsis";
import { formatAssetDuration } from "@/utils";
import { useLibrary } from "@/engine/library";
import { ASSET_DRAG_TYPE } from "./folder-item";
import type { Asset } from "@diffusionstudio/assets";
export type LazyAssetItemProps = {
asset: Asset;
selected: boolean;
onSelect(): void;
/** Selected along with other items: the menu then acts on all of them. */
multiple: boolean;
onSelect(event: MouseEvent): void;
onContextSelect(): void;
onDragStart(event: DragEvent): void;
/** Inserts the selection at the start of the timeline. */
onInsertAtStart(): void;
/** Inserts the selection at the playhead. */
onInsertAtPlayhead(): void;
/** Every folder in the library, offered as move targets. */
folders: string[];
/** Moves the selection into a folder ('' = root). */
onMove(folder: string): void;
/** Deletes the selection. */
onDelete(): void;
};
/**
* A lazy loaded asset item. Clears the buffer when not visible.
*/
export function LazyAssetItem(props: LazyAssetItemProps) {
const world = useWorld();
const library = useLibrary();
const [isVisible, setIsVisible] = createSignal(false);
@ -55,18 +70,6 @@ export function LazyAssetItem(props: LazyAssetItemProps) {
onCleanup(() => observer.disconnect());
});
const handleDeleteAsset = async () => {
try {
await library()?.remove([props.asset]);
} catch (e) {
toast.error("Failed to delete", { description: (e as Error).message });
}
};
const handleDragStart = (event: DragEvent) => {
event.dataTransfer?.setData(ASSET_DRAG_TYPE, props.asset.id);
};
const commitRename = (nextName: string) => {
if (!isRenaming()) return;
setIsRenaming(false);
@ -99,7 +102,6 @@ export function LazyAssetItem(props: LazyAssetItemProps) {
};
const handleSaveAs = () => saveAssetAs(props.asset);
const handleInsertToTimeline = () => insertAssetAtPlayhead(world, props.asset);
return (
<ContextMenu>
@ -108,16 +110,16 @@ export function LazyAssetItem(props: LazyAssetItemProps) {
class="flex flex-col gap-1 text-left"
data-asset-id={props.asset.id}
draggable={true}
onDragStart={handleDragStart}
onClick={props.onSelect}
onContextMenu={props.onSelect}>
onDragStart={(event: DragEvent) => props.onDragStart(event)}
onClick={(event: MouseEvent) => props.onSelect(event)}
onContextMenu={() => props.onContextSelect()}>
<div
ref={ref}
data-selected={props.selected}
class="relative aspect-video w-full overflow-clip rounded bg-muted after:pointer-events-none after:absolute after:inset-0 after:rounded after:opacity-0 after:ring-2 after:ring-inset after:ring-ring after:z-10 data-[selected=true]:after:opacity-100"
class="relative aspect-video w-full rounded bg-muted after:pointer-events-none after:absolute after:-inset-px after:rounded-[5px] after:opacity-0 after:ring-2 after:ring-inset after:ring-ring after:z-10 data-[selected=true]:after:opacity-100"
>
<Show when={isVisible()}>
<AssetThumbnail asset={props.asset} class="absolute inset-0" cache={library()?.cache} />
<AssetThumbnail asset={props.asset} class="absolute inset-0 overflow-clip rounded" cache={library()?.cache} />
</Show>
<Show when={assetDuration()}>
{(duration) => (
@ -132,9 +134,12 @@ export function LazyAssetItem(props: LazyAssetItemProps) {
<Show
when={isRenaming()}
fallback={
<div class="text-xs text-foreground truncate select-none" title={props.asset.source}>
{name()}
</div>
<MiddleEllipsis
text={name()}
data-selected={props.selected}
class="text-xs text-muted-foreground select-none data-[selected=true]:text-foreground"
title={props.asset.source}
/>
}
>
<input
@ -154,21 +159,64 @@ export function LazyAssetItem(props: LazyAssetItemProps) {
</ContextMenuTrigger>
<ContextMenuPortal>
<ContextMenuContent class="w-[180px]">
<ContextMenuItem onSelect={handleInsertToTimeline}>
Insert at playhead
</ContextMenuItem>
<ContextMenuSub>
<ContextMenuSubTrigger>Insert...</ContextMenuSubTrigger>
<ContextMenuPortal>
<ContextMenuSubContent class="w-[180px]">
<ContextMenuGroup>
<ContextMenuItem onSelect={props.onInsertAtStart}>
Insert at start
<ContextMenuShortcut>⇧,</ContextMenuShortcut>
</ContextMenuItem>
<ContextMenuItem onSelect={props.onInsertAtPlayhead}>
Insert at playhead
<ContextMenuShortcut>,</ContextMenuShortcut>
</ContextMenuItem>
</ContextMenuGroup>
</ContextMenuSubContent>
</ContextMenuPortal>
</ContextMenuSub>
<Show when={props.folders.length > 0}>
<ContextMenuSub>
<ContextMenuSubTrigger>Move to...</ContextMenuSubTrigger>
<ContextMenuPortal>
<ContextMenuSubContent class="w-[220px]">
<ContextMenuGroup>
<ContextMenuItem
disabled={!props.multiple && assetFolder(props.asset) === ""}
onSelect={() => props.onMove("")}>
All assets
</ContextMenuItem>
<For each={props.folders}>
{(folder) => (
<ContextMenuItem
disabled={!props.multiple && assetFolder(props.asset) === folder}
onSelect={() => props.onMove(folder)}>
<MiddleEllipsis text={folder} title={folder} class="min-w-0 flex-1" />
</ContextMenuItem>
)}
</For>
</ContextMenuGroup>
</ContextMenuSubContent>
</ContextMenuPortal>
</ContextMenuSub>
</Show>
<Show when={!props.multiple}>
<ContextMenuSeparator />
<ContextMenuGroup>
<ContextMenuItem onSelect={() => setIsRenaming(true)}>
Rename
</ContextMenuItem>
<ContextMenuItem onSelect={handleReplaceMedia}>
Replace
</ContextMenuItem>
<ContextMenuItem onSelect={handleSaveAs}>
Save as
</ContextMenuItem>
</ContextMenuGroup>
</Show>
<ContextMenuSeparator />
<ContextMenuItem onSelect={() => setIsRenaming(true)}>
Rename
</ContextMenuItem>
<ContextMenuItem onSelect={handleReplaceMedia}>
Replace
</ContextMenuItem>
<ContextMenuItem onSelect={handleSaveAs}>
Save as
</ContextMenuItem>
<ContextMenuSeparator />
<ContextMenuItem onSelect={handleDeleteAsset}>
<ContextMenuItem onSelect={props.onDelete}>
Delete
<ContextMenuShortcut>⌫</ContextMenuShortcut>
</ContextMenuItem>

View File

@ -5,7 +5,8 @@
import { basename, dirname } from "@diffusionstudio/assets";
import { usePromptInput } from "@/context/prompt-input";
import { restoreConfig } from "@/components/genai/saved-config";
import { createEffect, createMemo, createSignal, For, onCleanup, onMount, Show } from "solid-js";
import { createEffect, createMemo, createSignal, For, onCleanup, onMount, Show, untrack } from "solid-js";
import { useWorld } from "@diffusionstudio/koota-solid";
import { SidebarTabs } from "@/agent-chat";
import { Button } from "../ui/button";
import { Icon } from "../ui/icon";
@ -14,9 +15,17 @@ import {
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuPortal,
DropdownMenuShortcut,
DropdownMenuTrigger,
} from "../ui/dropdown-menu";
import {
ContextMenu,
ContextMenuContent,
ContextMenuItem,
ContextMenuPortal,
ContextMenuSeparator,
ContextMenuShortcut,
ContextMenuTrigger,
} from "../ui/context-menu";
import { toast } from "somoto";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import {
@ -28,15 +37,27 @@ import {
BreadcrumbsSeparator,
} from "../ui/breadcrumbs";
import { LazyAssetItem } from "./asset-item";
import { clearRevealRequest, revealRequest } from "./reveal";
import { FolderItem, handleFolderDrop, isAssetOrFolderDrag, ASSET_DRAG_TYPE, FOLDER_DRAG_TYPE } from "./folder-item";
import { useLibrary } from "@/engine/library";
import { useAssetSelection } from "@/engine/hooks";
import { droppedFiles, importFiles, pickAndImport } from "@/engine/asset-actions";
import { droppedFiles, importClipboard, importFiles, insertAssetsAtPlayhead, insertAssetsAtStart, pickAndImport } from "@/engine/asset-actions";
import { clipboardHasMedia, hasMedia, pastedMedia, readClipboardMedia } from "@/lib/clipboard";
import { isInputTarget } from "@/utils";
import { useCommand } from "@/context/commands";
import type { AssetLibrary } from "@diffusionstudio/assets";
import type { Asset, AssetLibrary } from "@diffusionstudio/assets";
/** The ancestors of a folder path, root excluded, nearest last. */
/**
* A grid item's selection key: an asset id or a folder path, told apart by
* prefix so the two kinds can share one ordered list.
*/
const assetKey = (id: string) => `asset:${id}`;
const folderKey = (path: string) => `folder:${path}`;
const isAssetKey = (key: string) => key.startsWith("asset:");
const keyValue = (key: string) => key.slice(key.indexOf(":") + 1);
function ancestorsOf(path: string): string[] {
const chain: string[] = [];
for (let folder = path; folder; folder = dirname(folder)) chain.unshift(folder);
@ -45,15 +66,19 @@ function ancestorsOf(path: string): string[] {
export function Assets() {
let root: HTMLDivElement | undefined;
let scroller: HTMLDivElement | undefined;
let dragCounter = 0;
let createdFolder: string | null = null;
const world = useWorld();
const library = useLibrary();
const { id: selectedAssetId, select: setSelectedAssetId } = useAssetSelection();
const assetSelection = useAssetSelection();
const { openPromptInput } = usePromptInput();
const [query, setQuery] = createSignal("");
const [assetFilter, setAssetFilter] = createSignal<AssetFilter>("ALL");
const [isDragging, setIsDragging] = createSignal(false);
const [renamingFolder, setRenamingFolder] = createSignal<string | null>(null);
const [currentFolder, setCurrentFolder] = createSignal("");
const allAssets = createMemo(() => library()?.list().filter((asset) => asset.type !== "SCRIPT") ?? []);
@ -86,6 +111,199 @@ export function Assets() {
const itemCount = createMemo(() => visibleFolders().length + filteredAssets().length);
/** The items in the grid, in its order: folders first, then assets. */
const visibleKeys = createMemo(() => [
...visibleFolders().map(folderKey),
...filteredAssets().map((asset) => assetKey(asset.id)),
]);
const selectedKeys = createMemo(() => new Set([
...assetSelection.folders().map(folderKey),
...assetSelection.ids().map(assetKey),
]));
const setSelection = (keys: Iterable<string>) => {
const unique = [...new Set(keys)];
assetSelection.set({
ids: unique.filter(isAssetKey).map(keyValue),
folders: unique.filter((key) => !isAssetKey(key)).map(keyValue),
});
};
// Finder's selection, as the dashboard's project grid has it: where a
// Shift range starts, where Shift-arrows move from, and what was selected
// before the range — the range is added to that.
let anchor: string | null = null;
let lead: string | null = null;
let base: ReadonlySet<string> = new Set();
const selectOnly = (key: string) => {
setSelection([key]);
anchor = lead = key;
base = new Set();
};
const toggleSelected = (key: string) => {
const next = new Set(selectedKeys());
if (!next.delete(key)) next.add(key);
setSelection(next);
anchor = lead = key;
base = new Set([...next].filter((entry) => entry !== key));
};
/** Selects anchor through `key` on top of `base`, or just `key` when the anchor is off the grid. */
const selectRangeTo = (key: string) => {
const keys = visibleKeys();
const from = anchor === null ? -1 : keys.indexOf(anchor);
const to = keys.indexOf(key);
if (from < 0 || to < 0) return selectOnly(key);
setSelection([...base, ...keys.slice(Math.min(from, to), Math.max(from, to) + 1)]);
lead = key;
};
const selectAll = () => {
const keys = visibleKeys();
setSelection(keys);
anchor = keys[0] ?? null;
lead = keys.at(-1) ?? null;
base = new Set();
};
const clearSelection = () => {
setSelection([]);
anchor = lead = null;
base = new Set();
};
/** Selects what an import brought in; a dismissed picker or a refused drop keeps the selection. */
const selectImported = (assets: ReadonlyArray<Asset>) => {
if (!assets.length) return;
const keys = assets.map((asset) => assetKey(asset.id));
setSelection(keys);
anchor = keys[0];
lead = keys.at(-1)!;
base = new Set();
root?.focus();
};
// Items that leave the grid (another folder opened, filtered out, moved or
// deleted) leave the selection, so keys never act on what is not in view.
createEffect(() => {
const visible = new Set(visibleKeys());
const selected = untrack(selectedKeys);
const kept = [...selected].filter((key) => visible.has(key));
if (kept.length !== selected.size) setSelection(kept);
});
const handleItemClick = (key: string, event: MouseEvent) => {
if (event.shiftKey) selectRangeTo(key);
else if (event.metaKey || event.ctrlKey) toggleSelected(key);
else selectOnly(key);
root?.focus();
};
/** A right-click keeps a selection it lands in, like Finder; elsewhere it selects the item alone. */
const handleItemContextMenu = (key: string) => {
if (!selectedKeys().has(key)) selectOnly(key);
root?.focus();
};
/** Drags the whole selection when the item is part of it, the item alone otherwise. */
const handleItemDragStart = (key: string, event: DragEvent) => {
const keys = selectedKeys().has(key) ? [...selectedKeys()] : [key];
const assetIds = keys.filter(isAssetKey).map(keyValue);
const folders = keys.filter((entry) => !isAssetKey(entry)).map(keyValue);
if (assetIds.length) event.dataTransfer?.setData(ASSET_DRAG_TYPE, assetIds.join(","));
if (folders.length) event.dataTransfer?.setData(FOLDER_DRAG_TYPE, folders.join("\n"));
if (keys.length > 1) setSelectionDragImage(keys, event);
};
/**
* Shows every dragged item under the pointer, where it sits in the grid, as
* Finder does: copies of the items in view, laid out as they are, become the
* drag image. Items scrolled out of view are left out, their thumbnails are
* not loaded.
*/
const setSelectionDragImage = (keys: string[], event: DragEvent) => {
const viewport = scroller?.getBoundingClientRect();
if (!event.dataTransfer || !viewport) return;
const items = keys
.map((key) => itemElement(key))
.filter((element) => element !== null)
.map((element) => ({ element, rect: element.getBoundingClientRect() }))
.filter(({ rect }) => rect.bottom > viewport.top && rect.top < viewport.bottom);
if (items.length < 2) return;
const left = Math.min(...items.map(({ rect }) => rect.left));
const top = Math.min(...items.map(({ rect }) => rect.top));
// Off screen: the browser takes its picture of the element while it is in
// the document, and it can go once the drag has begun.
const image = document.createElement("div");
image.style.cssText = "position: fixed; left: -10000px; top: 0; pointer-events: none;";
for (const { element, rect } of items) {
const copy = element.cloneNode(true) as HTMLElement;
copy.removeAttribute("id");
copy.style.cssText = `position: absolute; left: ${rect.left - left}px; top: ${rect.top - top}px; width: ${rect.width}px; height: ${rect.height}px;`;
image.append(copy);
}
document.body.append(image);
event.dataTransfer.setDragImage(image, event.clientX - left, event.clientY - top);
setTimeout(() => image.remove());
};
const selectedAssets = () => {
const lib = library();
if (!lib) return [];
return assetSelection.ids().map((id) => lib.get(id)).filter((asset) => asset !== undefined);
};
const insertSelectionAtStart = () => insertAssetsAtStart(world, selectedAssets());
const insertSelectionAtPlayhead = () => insertAssetsAtPlayhead(world, selectedAssets());
/** Moves the selection into a folder ('' = root), as a drop onto it would. */
const moveSelectionTo = (target: string) => {
const lib = library();
if (!lib) return;
const assets = selectedAssets();
if (assets.length) lib.move(assets, target);
for (const folder of assetSelection.folders()) {
if (folder === target || dirname(folder) === target) continue;
if (target.startsWith(`${folder}/`)) {
toast("Cannot move a folder into itself");
} else {
lib.moveFolder(folder, target);
}
}
};
const deleteSelection = async () => {
const lib = library();
if (!lib) return;
const assets = selectedAssets();
const folders = assetSelection.folders();
try {
if (assets.length) await lib.remove(assets);
// A folder inside another selected folder is gone with it.
for (const folder of folders) {
if (lib.folders().has(folder)) await lib.deleteFolder(folder);
}
} catch (e) {
toast.error("Failed to delete", { description: (e as Error).message });
}
};
const itemElement = (key: string) => {
const attribute = isAssetKey(key) ? "data-asset-id" : "data-folder-path";
return root?.querySelector<HTMLElement>(`[${attribute}="${CSS.escape(keyValue(key))}"]`) ?? null;
};
const scrollToItem = (key: string) => {
itemElement(key)?.scrollIntoView({ block: "nearest" });
};
// Deep paths collapse like the breadcrumbs docs example:
// All assets / … / parent / current, with the hidden folders in a dropdown.
const folderPath = createMemo(() => ancestorsOf(currentFolder()));
@ -107,9 +325,9 @@ export function Assets() {
if (currentFolder()) openFolder(dirname(currentFolder()));
};
const getAssetIdFromTarget = (target: EventTarget | null) => {
const isItemTarget = (target: EventTarget | null) => {
const element = target instanceof Element ? target : null;
return element?.closest("[data-asset-id]")?.getAttribute("data-asset-id") ?? null;
return element?.closest("[data-asset-id], [data-folder-path]") != null;
};
// A folder that went away (deleted, moved) closes to the nearest one left.
@ -121,6 +339,27 @@ export function Assets() {
setCurrentFolder(folder);
});
// A reveal from elsewhere (the canvas menu's Reveal in assets): its folder
// opens, unfiltered, with its assets selected and the first scrolled to.
createEffect(() => {
const request = revealRequest();
if (!request) return;
clearRevealRequest();
untrack(() => {
setQuery("");
setAssetFilter("ALL");
setCurrentFolder(request.folder);
const keys = request.ids.map(assetKey);
setSelection(keys);
anchor = keys[0] ?? null;
lead = keys.at(-1) ?? null;
base = new Set();
root?.focus();
requestAnimationFrame(() => keys[0] && scrollToItem(keys[0]));
});
});
const withLibrary = (run: (library: AssetLibrary) => void | Promise<void>) => {
const lib = library();
if (!lib) {
@ -130,7 +369,26 @@ export function Assets() {
return run(lib);
};
const handleImportAssets = () => withLibrary((lib) => pickAndImport(lib, currentFolder()).then(() => {}));
const handleImportAssets = () => withLibrary(async (lib) => selectImported(await pickAndImport(lib, currentFolder())));
/** Media copied in another app, into the folder in view: from the menu. */
const handlePaste = () => withLibrary(async (lib) => {
selectImported(await importClipboard(lib, await readClipboardMedia(), currentFolder()));
});
/**
* ⌘V with the panel in focus. Without media copied in another app, the
* paste goes on to the stage, as it would with the panel out of focus.
*/
const handlePasteEvent = (event: ClipboardEvent) => {
if (isInputTarget(event)) return;
const media = pastedMedia(event);
const lib = library();
if (!hasMedia(media) || !lib) return;
event.preventDefault();
event.stopPropagation();
importClipboard(lib, media, currentFolder()).then(selectImported);
};
const handleDrop = async (event: DragEvent) => {
event.preventDefault();
@ -143,7 +401,7 @@ export function Assets() {
const lib = library();
if (!lib) return;
if (handleFolderDrop(lib, event, currentFolder())) return;
await importFiles(lib, droppedFiles(event), currentFolder());
selectImported(await importFiles(lib, droppedFiles(event), currentFolder()));
};
const handleDragOver = (event: DragEvent) => {
@ -180,35 +438,43 @@ export function Assets() {
};
const handleSelectAsset = (assetId: string) => {
setSelectedAssetId(assetId);
root?.focus();
};
const moveSelection = (delta: number) => {
const items = Array.from(
root?.querySelectorAll<HTMLElement>("[data-asset-id]") ?? []
);
if (items.length === 0) return;
const currentId = selectedAssetId();
const currentIndex = currentId
? items.findIndex(item => item.dataset.assetId === currentId)
: -1;
const baseIndex = currentIndex === -1 ? 0 : currentIndex;
const nextIndex = Math.min(
items.length - 1,
Math.max(0, baseIndex + delta)
);
const nextItem = items[nextIndex];
const nextId = nextItem?.dataset.assetId;
if (!nextId) return;
setSelectedAssetId(nextId);
nextItem.scrollIntoView({ block: "nearest" });
/** Moves the lead an item over, or a row up or down, as Finder's icon view does. */
const moveSelection = (arrow: string, extend: boolean) => {
const keys = visibleKeys();
if (keys.length === 0) return;
const columns = 2;
const count = keys.length;
const current = lead === null ? -1 : keys.indexOf(lead);
let index: number;
if (current < 0) {
index = 0;
} else {
if (arrow === "ArrowLeft") index = current - 1;
else if (arrow === "ArrowRight") index = current + 1;
else if (arrow === "ArrowUp") index = current - columns;
// Down from a row above a short last row lands on its last item.
else if (current + columns < count) index = current + columns;
else if (Math.floor(current / columns) < Math.floor((count - 1) / columns)) index = count - 1;
else return;
if (index < 0 || index >= count) return;
}
const key = keys[index];
if (extend && anchor !== null) selectRangeTo(key);
else selectOnly(key);
scrollToItem(key);
};
/**
* Finder's keys for the grid: arrows move the selection and Shift-arrows
* grow it, ⌘A selects every item in view and ⌥⌘A or Escape none, ⌘↓ opens
* the selected folder and ⌘↑ goes up, ⌫ deletes the selection, , inserts it
* at the playhead and ⇧, at the start of the timeline. Handled keys stop
* here, so the canvas does not act on them too.
*/
const handleKeyDown = (event: KeyboardEvent) => {
const target = event.target as HTMLElement | null;
if (
@ -219,13 +485,13 @@ export function Assets() {
return;
}
const command = event.metaKey || event.ctrlKey;
if (event.key === "Backspace" || event.key === "Delete") {
const selected = selectedAssetId();
const entry = selected ? library()?.get(selected) : undefined;
if (entry) {
if (selectedKeys().size > 0) {
event.preventDefault();
event.stopPropagation();
void library()?.remove([entry]);
void deleteSelection();
return;
}
@ -237,24 +503,48 @@ export function Assets() {
return;
}
const columns = 2;
const deltaByKey: Record<string, number> = {
ArrowUp: -columns,
ArrowDown: columns,
ArrowLeft: -1,
ArrowRight: 1,
};
const delta = deltaByKey[event.key];
if (delta === undefined) return;
// By code: ⇧ turns the comma of ⇧, into another character.
if (!command && !event.altKey && event.code === "Comma") {
if (assetSelection.ids().length === 0) return;
event.preventDefault();
event.stopPropagation();
if (event.shiftKey) insertSelectionAtStart();
else insertSelectionAtPlayhead();
return;
}
// By code: ⌥ turns the A of ⌥⌘A into another character on a Mac.
if (command && event.code === "KeyA") {
event.preventDefault();
event.stopPropagation();
if (event.altKey) clearSelection();
else selectAll();
return;
}
if (event.key === "Escape" && selectedKeys().size > 0) {
event.preventDefault();
event.stopPropagation();
clearSelection();
return;
}
if (!event.key.startsWith("Arrow")) return;
event.preventDefault();
moveSelection(delta);
event.stopPropagation();
if (command && event.key === "ArrowDown") {
const folders = assetSelection.folders();
if (folders.length === 1 && assetSelection.ids().length === 0) openFolder(folders[0]);
} else if (command && event.key === "ArrowUp") {
handleGoToParent();
} else if (!command && !event.altKey) {
moveSelection(event.key, event.shiftKey);
}
};
const handleBackgroundClick = (event: MouseEvent) => {
if (!getAssetIdFromTarget(event.target)) {
setSelectedAssetId(null);
}
if (!isItemTarget(event.target)) clearSelection();
};
const hasAssets = () => allAssets().length > 0;
@ -266,9 +556,39 @@ export function Assets() {
const parent = currentFolder();
const name = lib.uniqueFolderName(parent, "New folder");
const folder = lib.createFolder(parent ? `${parent}/${name}` : name);
createdFolder = folder;
setRenamingFolder(folder);
});
const handleRenameEnd = () => {
createdFolder = null;
setRenamingFolder(null);
};
// The open menu traps focus, so "Create folder" cannot focus the new folder's
// name field; focus it once the menu is gone, instead of the panel.
const handleMenuCloseAutoFocus = (event: Event) => {
const folder = renamingFolder();
if (!folder) return;
event.preventDefault();
const input = itemElement(folderKey(folder))?.querySelector("input");
input?.focus();
input?.select();
};
// Escape while naming a folder just created takes the folder back.
const handleRenameCancel = async (folder: string) => {
const created = createdFolder === folder;
handleRenameEnd();
const lib = library();
if (!created || !lib) return;
try {
await lib.deleteFolder(folder);
} catch (e) {
toast.error("Failed to delete", { description: (e as Error).message });
}
};
/**
* The panel's own keys, the ones its menu advertises. These commands are the
* library's rather than the stage's, so they are bound here and not in the
@ -296,6 +616,27 @@ export function Assets() {
onCleanup(() => window.removeEventListener("keydown", handleShortcut));
});
// The same two in the palette, into the folder the panel is showing.
useCommand({
id: "import-assets",
title: "Import media",
group: "Assets",
icon: "download",
keywords: ["assets", "files", "upload", "add"],
shortcut: ["⌘", "I"],
run: () => void handleImportAssets(),
});
useCommand({
id: "new-folder",
title: "Create folder",
group: "Assets",
icon: "navigation.folder",
keywords: ["new folder", "directory", "organize"],
shortcut: ["⇧", "⌘", "N"],
run: handleCreateFolder,
});
return (
<div
on:drop={handleDrop}
@ -306,6 +647,7 @@ export function Assets() {
tabIndex={0}
ref={root}
onKeyDown={handleKeyDown}
on:paste={handlePasteEvent}
>
<div class="h-12 shrink-0 flex items-center gap-2 px-4 border-y border-border [[data-platform=win32]_&]:border-t-0">
<div class="flex-1 min-w-0 flex items-center">
@ -335,7 +677,7 @@ export function Assets() {
<TooltipContent>Filter assets</TooltipContent>
</Tooltip>
<DropdownMenuPortal>
<DropdownMenuContent class="w-32">
<DropdownMenuContent class="w-36">
<For each={ASSET_FILTER_OPTIONS}>
{(option) => (
<DropdownMenuItem
@ -357,41 +699,19 @@ export function Assets() {
</DropdownMenuPortal>
</DropdownMenu>
</Show>
<DropdownMenu placement="bottom-start">
<Tooltip>
<TooltipTrigger<typeof DropdownMenuTrigger>
as={(triggerProps: object) => (
<DropdownMenuTrigger<typeof Button>
{...triggerProps}
as={(buttonProps) => (
<Button
{...buttonProps}
size="icon"
variant="ghost"
aria-label="Add assets"
class="text-muted-foreground data-expanded:bg-accent data-expanded:text-foreground"
>
<Icon name="plus-add" />
</Button>
)}
/>
)}
/>
<TooltipContent shortcut="⌘I">Import assets</TooltipContent>
</Tooltip>
<DropdownMenuPortal>
<DropdownMenuContent class="w-40">
<DropdownMenuItem tone="neutral" onSelect={handleImportAssets}>
Import assets
<DropdownMenuShortcut>⌘I</DropdownMenuShortcut>
</DropdownMenuItem>
<DropdownMenuItem tone="neutral" onSelect={handleCreateFolder}>
Create folder
<DropdownMenuShortcut>⇧⌘N</DropdownMenuShortcut>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenuPortal>
</DropdownMenu>
<Tooltip>
<TooltipTrigger
as={Button}
size="icon"
variant="ghost"
aria-label="Import assets"
class="text-muted-foreground"
onClick={handleImportAssets}
>
<Icon name="plus-add" />
</TooltipTrigger>
<TooltipContent shortcut="⌘I">Import assets</TooltipContent>
</Tooltip>
</div>
</div>
@ -477,68 +797,120 @@ export function Assets() {
</div>
</div>
</Show>
<div
class="flex-1 min-h-0 overflow-y-auto p-4 pt-3"
onClick={handleBackgroundClick}
>
<Show when={isEmptyView() && !isFiltering()}>
<div class="h-full flex flex-col items-center justify-center gap-4 px-6 pb-[88px] pt-4">
<div class="flex flex-col items-center gap-1">
<Icon name="navigation.folder" class="size-8 text-muted-foreground" />
<span class="text-xs font-450 text-muted-foreground">
Add media
</span>
<p class="text-xxs text-muted-foreground text-center">
Drag here, import from your computer,{"\n"}
or, generate something new with AI.
</p>
{/* The grid's own items open their own menus and stop the event,
so this one only answers a right-click on empty space. */}
<ContextMenu>
<ContextMenuTrigger
as="div"
ref={scroller}
class="flex-1 min-h-0 overflow-y-auto p-4 pt-3"
onClick={handleBackgroundClick}
>
<Show when={isEmptyView() && !isFiltering()}>
<div class="h-full flex flex-col items-center justify-center gap-4 px-6 pb-[88px] pt-4">
<div class="flex flex-col items-center gap-1">
<Icon name="navigation.folder" class="size-8 text-muted-foreground" />
<span class="text-xs font-450 text-muted-foreground">
Add media
</span>
<p class="text-xxs text-muted-foreground text-center">
Drag here, import from your computer,{"\n"}
or, generate something new with AI.
</p>
</div>
<div class="flex flex-col gap-2 w-full">
<Button variant="secondary" class="w-full" onClick={() => openPromptInput(restoreConfig("IMAGE"))}>
Generate with AI
</Button>
<Button variant="default" class="w-full" onClick={handleImportAssets}>
Import media
</Button>
</div>
</div>
<div class="flex flex-col gap-2 w-full">
<Button variant="secondary" class="w-full" onClick={() => openPromptInput(restoreConfig("IMAGE"))}>
Generate with AI
</Button>
<Button variant="default" class="w-full" onClick={handleImportAssets}>
Import media
</Button>
</Show>
<Show when={isEmptyView() && isFiltering()}>
<div class="h-full flex items-center justify-center text-xs text-muted-foreground">
No matching assets
</div>
</div>
</Show>
<Show when={isEmptyView() && isFiltering()}>
<div class="h-full flex items-center justify-center text-xs text-muted-foreground">
No matching assets
</div>
</Show>
<Show when={!isEmptyView()}>
<div class="grid grid-cols-2 gap-x-2 gap-y-4">
<For each={visibleFolders()}>
{(folder) => (
<FolderItem
path={folder}
renaming={renamingFolder() === folder}
onRenameStart={() => setRenamingFolder(folder)}
onRenameEnd={() => setRenamingFolder(null)}
onOpen={() => openFolder(folder)}
/>
)}
</For>
<For each={filteredAssets()}>
{(asset) => (
<LazyAssetItem
asset={asset}
selected={selectedAssetId() === asset.id}
onSelect={() => handleSelectAsset(asset.id)}
/>
)}
</For>
</div>
</Show>
</div>
</Show>
<Show when={!isEmptyView()}>
<div class="grid grid-cols-2 gap-x-2 gap-y-4">
<For each={visibleFolders()}>
{(folder) => (
<FolderItem
path={folder}
renaming={renamingFolder() === folder}
selected={selectedKeys().has(folderKey(folder))}
multiple={selectedKeys().size > 1 && selectedKeys().has(folderKey(folder))}
onSelect={(event) => handleItemClick(folderKey(folder), event)}
onContextSelect={() => handleItemContextMenu(folderKey(folder))}
onDragStart={(event) => handleItemDragStart(folderKey(folder), event)}
onRenameStart={() => setRenamingFolder(folder)}
onRenameEnd={handleRenameEnd}
onRenameCancel={() => void handleRenameCancel(folder)}
onOpen={() => openFolder(folder)}
onDelete={deleteSelection}
/>
)}
</For>
<For each={filteredAssets()}>
{(asset) => (
<LazyAssetItem
asset={asset}
selected={selectedKeys().has(assetKey(asset.id))}
multiple={selectedKeys().size > 1 && selectedKeys().has(assetKey(asset.id))}
onSelect={(event) => handleItemClick(assetKey(asset.id), event)}
onContextSelect={() => handleItemContextMenu(assetKey(asset.id))}
onDragStart={(event) => handleItemDragStart(assetKey(asset.id), event)}
onInsertAtStart={insertSelectionAtStart}
onInsertAtPlayhead={insertSelectionAtPlayhead}
folders={allFolders()}
onMove={moveSelectionTo}
onDelete={deleteSelection}
/>
)}
</For>
</div>
</Show>
</ContextMenuTrigger>
<ContextMenuPortal>
<ContextMenuContent class="w-52" onCloseAutoFocus={handleMenuCloseAutoFocus}>
<ContextMenuItem onSelect={handleImportAssets}>
Import assets
<ContextMenuShortcut>⌘I</ContextMenuShortcut>
</ContextMenuItem>
<ContextMenuItem onSelect={() => openPromptInput(restoreConfig("IMAGE"))}>
Generate with AI
</ContextMenuItem>
<ContextMenuItem disabled={!clipboardHasMedia()} onSelect={handlePaste}>
Paste
<ContextMenuShortcut>⌘V</ContextMenuShortcut>
</ContextMenuItem>
<ContextMenuSeparator />
<ContextMenuItem onSelect={handleCreateFolder}>
Create folder
<ContextMenuShortcut>⇧⌘N</ContextMenuShortcut>
</ContextMenuItem>
<ContextMenuSeparator />
<ContextMenuItem disabled={visibleKeys().length === 0} onSelect={selectAll}>
Select all
<ContextMenuShortcut>⌘A</ContextMenuShortcut>
</ContextMenuItem>
<Show when={currentFolder() !== ""}>
<ContextMenuItem onSelect={handleGoToParent}>
Go to parent folder
<ContextMenuShortcut>⌘↑</ContextMenuShortcut>
</ContextMenuItem>
</Show>
</ContextMenuContent>
</ContextMenuPortal>
</ContextMenu>
</div>
</div>
);
}
type AssetFilter = "ALL" | "VIDEO" | "IMAGE" | "AUDIO";
type AssetFilter = "ALL" | "VIDEO" | "IMAGE" | "AUDIO" | "TRANSCRIPT";
const ASSET_FILTER_OPTIONS: ReadonlyArray<{
value: AssetFilter;
@ -549,6 +921,7 @@ const ASSET_FILTER_OPTIONS: ReadonlyArray<{
{ value: "VIDEO", label: "Video", icon: "video" },
{ value: "IMAGE", label: "Image", icon: "media-image" },
{ value: "AUDIO", label: "Audio", icon: "media-audio" },
{ value: "TRANSCRIPT", label: "Captions", icon: "captions-small" },
];
type FilterIconStackProps = {

View File

@ -11,14 +11,16 @@ import {
ContextMenuItem,
ContextMenuPortal,
ContextMenuSeparator,
ContextMenuShortcut,
ContextMenuTrigger,
} from "../ui/context-menu";
import { Icon } from "../ui/icon";
import { MiddleEllipsis } from "../ui/middle-ellipsis";
import { useLibrary } from "@/engine/library";
import type { AssetLibrary } from "@diffusionstudio/assets";
/** Drag payloads: comma-separated asset ids, or one folder path. */
/** Drag payloads: comma-separated asset ids, and newline-separated folder paths. */
export const ASSET_DRAG_TYPE = "application/x-asset-id";
export const FOLDER_DRAG_TYPE = "application/x-folder-path";
@ -35,14 +37,16 @@ export function handleFolderDrop(library: AssetLibrary | undefined, event: DragE
if (!library) return false;
const assetIds = event.dataTransfer?.getData(ASSET_DRAG_TYPE)?.split(",").filter(Boolean) ?? [];
const folder = event.dataTransfer?.getData(FOLDER_DRAG_TYPE);
if (!assetIds.length && !folder) return false;
const folders = event.dataTransfer?.getData(FOLDER_DRAG_TYPE)?.split("\n").filter(Boolean) ?? [];
if (!assetIds.length && !folders.length) return false;
const assets = assetIds.map((id) => library.get(id)).filter((asset) => asset !== undefined);
if (assets.length) library.move(assets, target);
if (folder && folder !== target) {
if (target === folder || target.startsWith(`${folder}/`)) {
for (const folder of folders) {
// A selected folder dropped on itself stays put; the rest of the selection goes in.
if (folder === target) continue;
if (target.startsWith(`${folder}/`)) {
toast("Cannot move a folder into itself");
} else {
library.moveFolder(folder, target);
@ -55,9 +59,19 @@ export type FolderItemProps = {
/** The folder's library path. */
path: string;
renaming: boolean;
selected: boolean;
/** Selected along with other items: the menu then acts on all of them. */
multiple: boolean;
onSelect(event: MouseEvent): void;
onContextSelect(): void;
onDragStart(event: DragEvent): void;
onRenameStart(): void;
onRenameEnd(): void;
/** Escape in the name field: keeps the old name. */
onRenameCancel(): void;
onOpen(): void;
/** Deletes the selection. */
onDelete(): void;
};
export function FolderItem(props: FolderItemProps) {
@ -70,10 +84,6 @@ export function FolderItem(props: FolderItemProps) {
return children ? children.folders.length + children.assets.length : 0;
});
const handleDragStart = (event: DragEvent) => {
event.dataTransfer?.setData(FOLDER_DRAG_TYPE, props.path);
};
const handleDragOver = (event: DragEvent) => {
if (!isAssetOrFolderDrag(event)) return;
event.preventDefault();
@ -104,23 +114,27 @@ export function FolderItem(props: FolderItemProps) {
event.currentTarget.blur();
} else if (event.key === "Escape") {
event.preventDefault();
props.onRenameEnd();
props.onRenameCancel();
}
};
let input: HTMLInputElement | undefined;
const handleFocusElement = (el: HTMLInputElement) => {
input = el;
queueMicrotask(() => {
el.focus();
el.select();
});
};
const handleDelete = async () => {
try {
await library()?.deleteFolder(props.path);
} catch (e) {
toast.error("Failed to delete", { description: (e as Error).message });
}
// The open menu traps focus, so "Rename" cannot focus the field; focus it
// once the menu is gone, instead of handing focus back to the trigger.
const handleMenuCloseAutoFocus = (event: Event) => {
if (!props.renaming || !input) return;
event.preventDefault();
input.focus();
input.select();
};
return (
@ -130,15 +144,18 @@ export function FolderItem(props: FolderItemProps) {
class="flex flex-col gap-1 text-left"
data-folder-path={props.path}
draggable={true}
onDragStart={handleDragStart}
onDragStart={(event: DragEvent) => props.onDragStart(event)}
on:dragover={handleDragOver}
on:dragleave={() => setIsDropTarget(false)}
on:drop={handleDrop}
onClick={props.onOpen}
onClick={(event: MouseEvent) => props.onSelect(event)}
onDblClick={() => props.onOpen()}
onContextMenu={() => props.onContextSelect()}
>
<div
data-drop-target={isDropTarget()}
class="relative aspect-video w-full overflow-clip rounded bg-muted flex items-center justify-center after:pointer-events-none after:absolute after:inset-0 after:rounded after:opacity-0 after:ring-2 after:ring-inset after:ring-ring after:z-10 data-[drop-target=true]:after:opacity-100"
data-selected={props.selected}
class="relative aspect-video w-full rounded bg-muted flex items-center justify-center after:pointer-events-none after:absolute after:-inset-px after:rounded-[5px] after:opacity-0 after:ring-2 after:ring-inset after:ring-ring after:z-10 data-[drop-target=true]:after:opacity-100 data-[selected=true]:after:opacity-100"
>
<Icon name="folder-thumbnail" class="w-8 h-6 text-muted-foreground pointer-events-none" />
<Show when={childCount() > 0}>
@ -149,7 +166,13 @@ export function FolderItem(props: FolderItemProps) {
</div>
<Show
when={props.renaming}
fallback={<div class="text-xs text-foreground truncate select-none">{name()}</div>}
fallback={
<MiddleEllipsis
text={name()}
data-selected={props.selected}
class="text-xs text-muted-foreground select-none data-[selected=true]:text-foreground"
/>
}
>
<input
ref={handleFocusElement}
@ -167,12 +190,20 @@ export function FolderItem(props: FolderItemProps) {
</Show>
</ContextMenuTrigger>
<ContextMenuPortal>
<ContextMenuContent class="w-[220px]">
<ContextMenuItem onSelect={props.onOpen}>Open</ContextMenuItem>
<ContextMenuSeparator />
<ContextMenuItem onSelect={props.onRenameStart}>Rename</ContextMenuItem>
<ContextMenuSeparator />
<ContextMenuItem onSelect={handleDelete}>Delete</ContextMenuItem>
<ContextMenuContent class="w-[220px]" onCloseAutoFocus={handleMenuCloseAutoFocus}>
<Show when={!props.multiple}>
<ContextMenuItem onSelect={props.onOpen}>
Open
<ContextMenuShortcut>⌘↓</ContextMenuShortcut>
</ContextMenuItem>
<ContextMenuSeparator />
<ContextMenuItem onSelect={props.onRenameStart}>Rename</ContextMenuItem>
<ContextMenuSeparator />
</Show>
<ContextMenuItem onSelect={props.onDelete}>
Delete
<ContextMenuShortcut>⌫</ContextMenuShortcut>
</ContextMenuItem>
</ContextMenuContent>
</ContextMenuPortal>
</ContextMenu>

View File

@ -32,6 +32,7 @@ import { AssetId, ChildOf, Name, Root, Scene, getAssetFile, getActiveEntity, sor
import { assetName } from "@diffusionstudio/assets";
import { useQuery, useWorld } from "@diffusionstudio/koota-solid";
import { useLibrary } from "@/engine/library";
import { useAssetSelection } from "@/engine/hooks";
import { pickAndImport } from "@/engine/asset-actions";
import { projectRoute } from "@/hooks/use-project-route";
import { useProject } from "@/context/project";
@ -94,6 +95,7 @@ export function FileMenu() {
const navigate = useNavigate();
const project = useProject();
const library = useLibrary();
const assetSelection = useAssetSelection();
const commands = useFileCommands();
const [editors] = createResource(listEditors, { initialValue: [] });
@ -145,7 +147,14 @@ export function FileMenu() {
toast("No project open");
return;
}
await pickAndImport(lib, "");
const imported = await pickAndImport(lib, "");
if (imported.length) {
assetSelection.set({
ids: imported.map((asset) => asset.id),
folders: [],
});
}
};
return (

View File

@ -52,9 +52,11 @@ export function ViewMenu() {
<DropdownMenuGroup>
<DropdownMenuItem onSelect={layout.toggleUI}>
Toggle UI
<DropdownMenuShortcut>⌘\</DropdownMenuShortcut>
</DropdownMenuItem>
<DropdownMenuItem onSelect={layout.toggleTimeline}>
Toggle timeline
<DropdownMenuShortcut>⌘J</DropdownMenuShortcut>
</DropdownMenuItem>
</DropdownMenuGroup>
</>

View File

@ -0,0 +1,32 @@
/* 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/. */
// Showing assets in the assets panel from elsewhere: the panel opens the
// folder they are in, selects them and scrolls to them. Kept here rather than
// in the panel, which is not mounted while the UI is hidden: it takes up a
// request left for it as it comes up.
import { createSignal } from "solid-js";
export type RevealRequest = {
/** The folder to open ('' = the root). */
folder: string;
/** The assets in it to select. */
ids: string[];
};
const [revealRequest, setRevealRequest] = createSignal<RevealRequest | null>(null);
/** The reveal the assets panel has yet to carry out. */
export { revealRequest };
/** Asks the assets panel to show `ids` in `folder`. */
export function revealInAssets(request: RevealRequest): void {
setRevealRequest(request);
}
/** Marks the reveal done. */
export function clearRevealRequest(): void {
setRevealRequest(null);
}

View File

@ -208,11 +208,13 @@ export function ProjectHeader(props: ProjectHeaderProps) {
}
export function FloatingProjectHeader() {
const { isDesktop } = useEditorApi();
const { isDesktop, isFullscreen } = useEditorApi();
const { toggleUI } = useLayout();
const belowTrafficLights = () => isDesktop && !isWindowsDesktop() && !isFullscreen();
return (
<div data-desktop={isDesktop} class="h-10 rounded-lg border border-border shrink-0 flex items-center px-2 gap-1 fixed top-4 data-[desktop=true]:top-10 left-4 z-30 bg-background shadow-lg">
<div data-traffic-lights={belowTrafficLights()} class="h-10 rounded-lg border border-border shrink-0 flex items-center px-2 gap-1 fixed top-4 data-[traffic-lights=true]:top-10 left-4 z-30 bg-background shadow-lg">
<ProjectMenu />
<span class="text-xs text-muted-foreground font-450">Diffusion Studio</span>
<Button variant="ghost" size="icon" class="text-muted-foreground ml-2" onClick={toggleUI}>

View File

@ -20,10 +20,11 @@ import { LazyAssetItem } from "@/components/sidebar-left/asset-item";
import { usePromptInput } from "@/context/prompt-input";
import { restoreConfig } from "@/components/genai/saved-config";
import { assetName } from "@diffusionstudio/assets";
import { useTrait } from "@diffusionstudio/koota-solid";
import { useTrait, useWorld } from "@diffusionstudio/koota-solid";
import { AssetId, isScene } from "@diffusionstudio/runtime";
import { useLibrary } from "@/engine/library";
import { pickAndImport } from "@/engine/asset-actions";
import { insertAssetAtPlayhead, insertAssetsAtStart, pickAndImport } from "@/engine/asset-actions";
import { ASSET_DRAG_TYPE } from "@/components/sidebar-left/folder-item";
import type { Asset } from "@diffusionstudio/assets";
import type { Entity } from "koota";
@ -55,6 +56,7 @@ export type AssetFillPickerProps = {
*/
export function AssetFillPicker(props: AssetFillPickerProps) {
const { openPromptInput } = usePromptInput();
const world = useWorld();
const library = useLibrary();
const [query, setQuery] = createSignal("");
@ -92,6 +94,14 @@ export function AssetFillPicker(props: AssetFillPickerProps) {
}
};
const handleDeleteAsset = async (asset: Asset) => {
try {
await library()?.remove([asset]);
} catch (e) {
toast.error("Failed to delete", { description: (e as Error).message });
}
};
const selectedAssetId = useTrait(() => props.fill, AssetId);
return (
@ -166,7 +176,15 @@ export function AssetFillPicker(props: AssetFillPickerProps) {
<LazyAssetItem
asset={asset}
selected={selectedAssetId()?.value === asset.id}
multiple={false}
onSelect={() => props.onSelectAsset(asset)}
onContextSelect={() => props.onSelectAsset(asset)}
onDragStart={(event) => event.dataTransfer?.setData(ASSET_DRAG_TYPE, asset.id)}
onInsertAtStart={() => insertAssetsAtStart(world, [asset])}
onInsertAtPlayhead={() => insertAssetAtPlayhead(world, asset)}
folders={[...(library()?.folders() ?? [])].sort()}
onMove={(folder) => library()?.move([asset], folder)}
onDelete={() => void handleDeleteAsset(asset)}
/>
)}
</For>

View File

@ -2,16 +2,11 @@
* 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 } from "solid-js";
import { Button } from "@/components/ui/button";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { Icon } from "@/components/ui/icon";
import { ItemRow } from "@/components/ui/item-row";
import { For, Show } from "solid-js";
import { PanelSection } from "@/components/ui/panel-section";
import { useTrait, useWorld } from "@diffusionstudio/koota-solid";
import { Cache, Name } from "@diffusionstudio/runtime";
import { beginClipPathFor } from "@/engine/clip-path";
import { Cache } from "@diffusionstudio/runtime";
import { useDerived, useEditor } from "@/engine/hooks";
import { ContainerRow } from "./masks";
import type { Entity } from "koota";
@ -23,16 +18,12 @@ type ClipPathsSettingsProps = {
};
/**
* The clip path children of the selected node (`<rect clipPath>`,
* `<ellipse clipPath>`, `<polygon clipPath>`, `<path clipPath>`): the shapes it is clipped to
* (several intersect). A clip path is a shape like any other, so it
* has no inspector of its own — a row selects it and the transform, time and
* appearance panels are then its own. The plus picks up the clip path tool,
* whose bar over the canvas turns the shapes selected there into clip paths
* of this node.
* The `<clipPath>`s the selected node was given in its JSX, one row each.
* Clip paths are on their way out of the UI in favour of masks: nothing here
* adds or edits one, a row only removes it, and a node without any shows no
* section at all.
*/
export function ClipPathsSettings(props: ClipPathsSettingsProps) {
const world = useWorld();
const editor = useEditor();
const entity = () => props.selection[0]!;
@ -40,65 +31,18 @@ export function ClipPathsSettings(props: ClipPathsSettingsProps) {
const clipPaths = useDerived(() => entity().get(Cache)?.clipPaths ?? NO_CLIP_PATHS);
return (
<PanelSection
title="Clip Paths"
actions={
<Tooltip>
<TooltipTrigger
as={Button}
size="icon"
variant="ghost"
class="text-muted-foreground"
onClick={() => beginClipPathFor(world, entity())}
>
<Icon name="plus-add" />
</TooltipTrigger>
<TooltipContent>Add clip path</TooltipContent>
</Tooltip>
}
>
<For each={clipPaths()}>
{(clipPath) => (
<ClipPathRow
clipPath={clipPath}
onSelect={() => editor.select(clipPath)}
onRemove={() => editor.remove(clipPath)}
/>
)}
</For>
</PanelSection>
);
}
type ClipPathRowProps = {
clipPath: Entity;
onSelect(): void;
onRemove(): void;
};
function ClipPathRow(props: ClipPathRowProps) {
const name = useTrait(() => props.clipPath, Name);
return (
<ItemRow
label="Clip Path"
value={name()?.value || "Clip Path"}
icon={<Icon name="mask-small" />}
class="text-foreground"
onClick={props.onSelect}
>
<Tooltip>
<TooltipTrigger
as={Button}
size="icon"
variant="ghost"
class="text-muted-foreground"
onClick={props.onRemove}
>
<Icon name="close-remove-small" />
</TooltipTrigger>
<TooltipContent>Remove clip path</TooltipContent>
</Tooltip>
</ItemRow>
<Show when={clipPaths().length > 0}>
<PanelSection title="Clip Path">
<For each={clipPaths()}>
{(clipPath) => (
<ContainerRow
container={clipPath}
label="Shape"
onRemove={() => editor.remove(clipPath)}
/>
)}
</For>
</PanelSection>
</Show>
);
}

View File

@ -11,7 +11,7 @@ import {
isAudio,
isCaption,
isGroup,
isClipPath,
isClipShape,
isPath,
isScene,
isSequence,
@ -39,6 +39,7 @@ import { ShadowsSettings } from "./shadows";
import { EffectsSettings } from "./effects";
import { AnimationsSettings } from "./animations";
import { TransitionSettings } from "./transition";
import { MasksSettings } from "./masks";
import { ClipPathsSettings } from "./clip-paths";
import { AudioSettings } from "./audio";
import { InterpolationSettings } from "./interpolation";
@ -62,7 +63,7 @@ export type SelectionTarget =
function classifyNode(entity: Entity): SelectionTarget {
if (isScene(entity)) return "scene";
if (isClipPath(entity)) return "clip-path";
if (isClipShape(entity)) return "clip-path";
if (isSequence(entity)) return "sequence";
if (isCaption(entity)) return "caption";
if (isAudio(entity)) return "audio";
@ -182,6 +183,7 @@ export function Inspector() {
</Show>
<Show when={includesTarget("shape", "text", "caption", "group")}>
<MasksSettings selection={nodes()} />
<ClipPathsSettings selection={nodes()} />
</Show>

View File

@ -0,0 +1,110 @@
/* 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 } from "solid-js";
import { Button } from "@/components/ui/button";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { Icon } from "@/components/ui/icon";
import { ItemRow } from "@/components/ui/item-row";
import { PanelSection } from "@/components/ui/panel-section";
import { useTrait, useWorld } from "@diffusionstudio/koota-solid";
import { Cache, Name } from "@diffusionstudio/runtime";
import { beginMaskFor } from "@/engine/mask";
import { useDerived, useEditor } from "@/engine/hooks";
import type { Entity } from "koota";
// Stable identity, so a node without masks does not resample every tick.
const NO_MASKS: Entity[] = [];
type MasksSettingsProps = {
selection: Entity[];
};
/**
* The `<mask>`s of the selected node, one row each (several intersect). A
* mask is the layers under it and has no inspector of its own: a row selects
* its layers, whose transform, time and appearance panels are then the ones
* shown. The plus picks up the mask tool, whose bar over the canvas puts the
* layers selected there into a new mask of this node.
*/
export function MasksSettings(props: MasksSettingsProps) {
const world = useWorld();
const editor = useEditor();
const entity = () => props.selection[0]!;
// Cache is derived state, written without change events.
const masks = useDerived(() => entity().get(Cache)?.masks ?? NO_MASKS);
return (
<PanelSection
title="Masks"
actions={
<Tooltip>
<TooltipTrigger
as={Button}
size="icon"
variant="ghost"
class="text-muted-foreground"
onClick={() => beginMaskFor(world, entity())}
>
<Icon name="plus-add" />
</TooltipTrigger>
<TooltipContent>Add mask</TooltipContent>
</Tooltip>
}
>
<For each={masks()}>
{(mask) => (
<ContainerRow
container={mask}
label="Mask"
onSelect={() => {
// A mask drawn from a file has no layers to select.
const children = mask.get(Cache)?.children ?? [];
if (children.length) editor.select(children);
}}
onRemove={() => editor.remove(mask)}
/>
)}
</For>
</PanelSection>
);
}
type ContainerRowProps = {
/** The `<mask>` or `<clipPath>`. */
container: Entity;
label: string;
onSelect?(): void;
onRemove(): void;
};
/** One mask or clip path of a node: its name selects its layers (when it can), the × removes it with them. */
export function ContainerRow(props: ContainerRowProps) {
const name = useTrait(() => props.container, Name);
return (
<ItemRow
label={props.label}
value={name()?.value || props.label}
icon={<Icon name="mask-small" />}
class="text-foreground"
onClick={props.onSelect}
>
<Tooltip>
<TooltipTrigger
as={Button}
size="icon"
variant="ghost"
class="text-muted-foreground"
onClick={props.onRemove}
>
<Icon name="close-remove-small" />
</TooltipTrigger>
<TooltipContent>Remove {props.label.toLowerCase()}</TooltipContent>
</Tooltip>
</ItemRow>
);
}

View File

@ -4,7 +4,7 @@
import { createContext, createSignal, onCleanup, useContext, type JSX, type Signal } from "solid-js";
import { useWorld } from "@diffusionstudio/koota-solid";
import { Expanded, getEntityTree, isClipPath, isSequence } from "@diffusionstudio/runtime";
import { Expanded, getEntityTree, isSequence } from "@diffusionstudio/runtime";
import { useEditor, useTimelineIndex } from "@/engine/hooks";
import { useTimeline } from "@/context/timeline";
@ -51,7 +51,7 @@ export function LayerContextProvider(props: { children: JSX.Element }) {
const [target, setTarget] = createSignal<DropTarget | null>(null);
let pending: { entity: Entity; startX: number; startY: number } | null = null;
let active: { entity: Entity; forbidden: Set<Entity>; isClipPath: boolean } | null = null;
let active: { entity: Entity; forbidden: Set<Entity> } | null = null;
let dwell: { entity: Entity; since: number } | null = null;
let pointerX = 0;
let pointerY = 0;
@ -74,7 +74,6 @@ export function LayerContextProvider(props: { children: JSX.Element }) {
active = {
entity,
forbidden: new Set(getEntityTree(world, entity)),
isClipPath: isClipPath(entity),
};
dirty = true;
setDragging(entity);
@ -190,7 +189,6 @@ export function LayerContextProvider(props: { children: JSX.Element }) {
root,
dragged: active.entity,
forbidden: active.forbidden,
draggedIsClipPath: active.isClipPath,
containerRect,
listBottom: getListBottom(layersEl, containerRect),
};

View File

@ -13,7 +13,7 @@
* rect, depth and ancestor chain without the rows registering anything.
*/
import { isGroupLike, isClipPath, isSequence } from '@diffusionstudio/runtime';
import { isGroupLike, isSequence } from '@diffusionstudio/runtime';
import { NESTED_INDENT_PX } from './config';
import type { Accessor } from 'solid-js';
@ -70,8 +70,6 @@ export type GapContext = {
dragged: Entity;
/** The dragged subtree: nothing in it may become the parent of the drop. */
forbidden: Set<Entity>;
/** Clip paths stack apart from plain layers; anchors must stay in their bucket. */
draggedIsClipPath: boolean;
containerRect: DOMRect;
/** Client Y just below the last row of the whole list. */
listBottom: number;
@ -216,9 +214,7 @@ export function resolveGap(gapIndex: number, rows: FlatRow[], x: number, context
/**
* The document sibling to insert before: the nearest row above the gap at
* the chosen depth. Restricted to the dragged layer's stacking bucket —
* clip paths and plain layers render as separate runs, so an anchor from the
* other bucket would land the row somewhere the line never was.
* the chosen depth.
*/
function scanAnchor(
rows: FlatRow[],
@ -233,7 +229,7 @@ function scanAnchor(
if (row.depth > depth) continue;
if (row.parent !== parent) break;
if (row.node.entity === context.dragged) continue;
if (isClipPath(row.node.entity) === context.draggedIsClipPath) return row.node.entity;
return row.node.entity;
}
return undefined;

View File

@ -21,7 +21,10 @@ import {
DropdownMenu,
DropdownMenuCheckboxItem,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuGroupLabel,
DropdownMenuItem,
DropdownMenuItemDetail,
DropdownMenuPortal,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
@ -32,6 +35,7 @@ import {
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Tooltip, TooltipContent, TooltipPortal, TooltipTrigger } from '@/components/ui/tooltip';
import { CommandContextMenu, TIMELINE_HEADER_MENU } from '@/components/commands';
import { DEFAULT_CLIP_HEIGHT, RULER_HEIGHT } from '@/engine/timeline';
import { splitAtPlayhead } from '@/engine/split';
import { useDerived, useEditor, useTimelineIndex } from '@/engine/hooks';
@ -147,9 +151,10 @@ export function Layers() {
style={{ 'grid-template-rows': `${RULER_HEIGHT}px 1fr` }}
data-timeline-layers-container
>
<div
<CommandContextMenu
layout={TIMELINE_HEADER_MENU}
class="w-full z-10 flex flex-row gap-1 pl-2 pr-3 items-center text-muted-foreground select-none"
on:dblclick={handleHeaderDoubleClick}
onDblClick={handleHeaderDoubleClick}
>
<Tooltip placement="top">
<TooltipTrigger<typeof Button>
@ -218,47 +223,49 @@ export function Layers() {
<DropdownMenuContent class="w-[180px]">
<DropdownMenuItem onSelect={addLayer}>Add layer</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuSub>
<DropdownMenuSubTrigger>Layer height</DropdownMenuSubTrigger>
<DropdownMenuPortal>
<DropdownMenuSubContent class="w-[140px]">
<Index each={HEIGHT_PRESETS}>
{(preset) => (
<DropdownMenuCheckboxItem
onSelect={() => setCommonHeight(preset().height)}
checked={commonHeight() === preset().height}
>
{preset().label}
<span class="text-xxs text-muted-foreground ml-auto">{preset().height}</span>
</DropdownMenuCheckboxItem>
)}
</Index>
</DropdownMenuSubContent>
</DropdownMenuPortal>
</DropdownMenuSub>
<DropdownMenuSeparator />
<DropdownMenuSub>
<DropdownMenuSubTrigger>Time format</DropdownMenuSubTrigger>
<DropdownMenuPortal>
<DropdownMenuSubContent class="w-[200px]">
<DropdownMenuRadioGroup
value={timeFormat()}
onChange={(value) => setTimeFormat(value as TimeFormat)}
>
<Index each={TIME_FORMAT_OPTIONS}>
{(option) => (
<DropdownMenuRadioItem value={option().value}>
{option().label}
<span class="text-xxs text-muted-foreground ml-auto">
{option().example}
</span>
</DropdownMenuRadioItem>
)}
</Index>
</DropdownMenuRadioGroup>
</DropdownMenuSubContent>
</DropdownMenuPortal>
</DropdownMenuSub>
<DropdownMenuGroup>
<DropdownMenuGroupLabel>View</DropdownMenuGroupLabel>
<DropdownMenuSub>
<DropdownMenuSubTrigger>Layer height</DropdownMenuSubTrigger>
<DropdownMenuPortal>
<DropdownMenuSubContent class="w-[160px]">
<DropdownMenuGroup>
<Index each={HEIGHT_PRESETS}>
{(preset) => (
<DropdownMenuCheckboxItem
onSelect={() => setCommonHeight(preset().height)}
checked={commonHeight() === preset().height}
>
{preset().label}
<DropdownMenuItemDetail class="ml-auto">{preset().height}</DropdownMenuItemDetail>
</DropdownMenuCheckboxItem>
)}
</Index>
</DropdownMenuGroup>
</DropdownMenuSubContent>
</DropdownMenuPortal>
</DropdownMenuSub>
<DropdownMenuSub>
<DropdownMenuSubTrigger>Time format</DropdownMenuSubTrigger>
<DropdownMenuPortal>
<DropdownMenuSubContent class="w-[200px]">
<DropdownMenuRadioGroup
value={timeFormat()}
onChange={(value) => setTimeFormat(value as TimeFormat)}
>
<Index each={TIME_FORMAT_OPTIONS}>
{(option) => (
<DropdownMenuRadioItem value={option().value}>
{option().label}
<DropdownMenuItemDetail class="ml-auto">{option().example}</DropdownMenuItemDetail>
</DropdownMenuRadioItem>
)}
</Index>
</DropdownMenuRadioGroup>
</DropdownMenuSubContent>
</DropdownMenuPortal>
</DropdownMenuSub>
</DropdownMenuGroup>
</DropdownMenuContent>
</DropdownMenuPortal>
</DropdownMenu>
@ -266,7 +273,7 @@ export function Layers() {
<span class="text-xs font-mono font-thin ml-auto select-none">
{clock()}
</span>
</div>
</CommandContextMenu>
<div data-timeline-layers-viewport class="relative h-full z-0 overflow-hidden">
<div
data-timeline-layers

View File

@ -14,12 +14,10 @@ import {
Selected,
Soloed,
findGeometryAsset,
getEntityChildren,
getParentEntity,
isAdjustmentLayer,
isCaption,
isGroup,
isClipPath,
isClipShape,
isEllipse,
isPath,
isPolygon,
@ -29,15 +27,7 @@ import {
} from '@diffusionstudio/runtime';
import { Button } from '@/components/ui/button';
import { Icon } from '@/components/ui/icon';
import {
ContextMenu,
ContextMenuContent,
ContextMenuItem,
ContextMenuPortal,
ContextMenuSeparator,
ContextMenuShortcut,
ContextMenuTrigger,
} from '@/components/ui/context-menu';
import { NodeContextMenu, TIMELINE_MENU } from '@/components/commands';
import { Tooltip, TooltipContent, TooltipPortal, TooltipTrigger } from '@/components/ui/tooltip';
import { useEditor } from '@/engine/hooks';
import { DEFAULT_CLIP_HEIGHT, MAX_CLIP_HEIGHT, MIN_CLIP_HEIGHT, getClipFallbackName } from '@/engine/timeline';
@ -141,21 +131,6 @@ export function NodeLayer(props: LayerRowProps) {
document.addEventListener('pointerup', handleResizeEnd);
};
const handleRemove = () => editor.remove(entity());
/**
* The column reads top-down while the file reads bottom-up: the last child
* of an element is the one drawn on top, so "front" is the end of the file
* and "back" is the beginning.
*/
const handleReorder = (target: 'front' | 'back') => {
const parent = getParentEntity(entity());
if (!parent) return;
const siblings = getEntityChildren(world, parent).filter((sibling) => sibling !== entity());
editor.reparent(entity(), parent, target === 'back' ? siblings[0] : undefined);
};
const startEditing = () => {
originalName = name();
setEditing(true);
@ -193,168 +168,149 @@ export function NodeLayer(props: LayerRowProps) {
};
return (
<ContextMenu>
<ContextMenuTrigger
as="div"
data-layer-row
class="w-full text-muted-foreground group relative select-none"
onPointerEnter={() => setRowHover(world, entity())}
onPointerLeave={() => setRowHover(world, null)}
onPointerDown={handleRowPointerDown}
classList={{
'bg-accent': selected(),
'bg-accent/70': !selected() && hovering() && resized() === null && drag.dragging() === null,
'bg-accent/40': !selected() && !(hovering() && resized() === null) && props.ancestorSelected,
'opacity-60': drag.dragging() === entity(),
}}
style={{ height: height() + 'px' }}
>
<div class="w-full pl-0.5 pr-2 flex items-center justify-between h-full">
<div
data-layer-label
class="flex-1 min-w-0 overflow-hidden"
style={{
'mask-image': controlsVisible() && !editing() ? 'linear-gradient(to right, #000 calc(100% - 1.25rem), transparent)' : undefined,
'-webkit-mask-image': controlsVisible() && !editing() ? 'linear-gradient(to right, #000 calc(100% - 1.25rem), transparent)' : undefined,
}}
>
<div
class="flex items-center gap-0.5 w-max"
style={{
'padding-left': `${props.depth * NESTED_INDENT_PX}px`,
transform: editing() ? 'none' : 'translateX(calc(var(--layer-x, 0px) * -1))',
}}
>
<button
disabled={!props.layer.expandable}
onClick={toggleExpanded}
class="size-4 shrink-0 flex items-center justify-center overflow-clip invisible group-hover/layers:visible focus-ring rounded-sm"
>
<Show when={props.layer.expandable}>
<Icon name={props.expanded ? "chevron-down" : "chevron-right"} class="hover:text-foreground" />
</Show>
</button>
<div class="size-4 shrink-0 flex items-center justify-center overflow-clip mr-0.5">
<Icon name={icon()} />
</div>
<Show
when={editing()}
fallback={
<span class="text-xs px-0.5 shrink-0 whitespace-nowrap text-foreground" onDblClick={startEditing}>
{name()}
</span>
}
>
<input
ref={mountNameInput}
type="text"
class="text-xs bg-input border border-primary rounded-sm outline-none px-0.5 w-32 text-foreground"
value={name()}
onInput={handleNameInput}
onKeyDown={handleNameKeyDown}
onBlur={(e) => finishEditing(e.currentTarget)}
onPointerDown={(e) => e.stopPropagation()}
onDblClick={(e) => e.stopPropagation()}
/>
</Show>
</div>
</div>
<div
class="items-center flex gap-0.5 shrink-0 overflow-hidden group-hover:w-auto"
classList={{
'hidden': resized() !== null,
'w-0': !(muted() || soloed() || hidden()),
'w-auto': muted() || soloed() || hidden(),
}}
>
<Tooltip placement="bottom">
<TooltipTrigger
as={Button}
variant={muted() ? "on" : "ghost"}
size="icon"
class="invisible group-hover:visible"
style={{ visibility: muted() ? 'visible' : undefined }}
onClick={toggleMuted}
>
<Icon name="mute" />
</TooltipTrigger>
<TooltipPortal>
<TooltipContent>{muted() ? "Unmute" : "Mute"}</TooltipContent>
</TooltipPortal>
</Tooltip>
<Tooltip placement="bottom">
<TooltipTrigger
as={Button}
variant={soloed() ? "on" : "ghost"}
size="icon"
class="invisible group-hover:visible"
style={{ visibility: soloed() ? 'visible' : undefined }}
onClick={toggleSoloed}
>
<Icon name="solo" />
</TooltipTrigger>
<TooltipPortal>
<TooltipContent>{soloed() ? "Unsolo" : "Solo"}</TooltipContent>
</TooltipPortal>
</Tooltip>
<Tooltip placement="bottom">
<TooltipTrigger
as={Button}
variant="ghost"
size="icon"
class="invisible group-hover:visible"
onClick={toggleHidden}
style={{ visibility: hidden() ? 'visible' : undefined }}
>
<Show when={!hidden()} fallback={<Icon name="eye-off" />}>
<Icon name="eye-on" />
</Show>
</TooltipTrigger>
<TooltipPortal>
<TooltipContent>{hidden() ? "Show" : "Hide"}</TooltipContent>
</TooltipPortal>
</Tooltip>
</div>
</div>
{/* Drag the bottom edge to make the row taller. */}
<NodeContextMenu
layout={TIMELINE_MENU}
pick={() => [entity()]}
data-layer-row
class="w-full text-muted-foreground group relative select-none"
onPointerEnter={() => setRowHover(world, entity())}
onPointerLeave={() => setRowHover(world, null)}
onPointerDown={handleRowPointerDown}
classList={{
'bg-accent': selected(),
'bg-accent/70': !selected() && hovering() && resized() === null && drag.dragging() === null,
'bg-accent/40': !selected() && !(hovering() && resized() === null) && props.ancestorSelected,
'opacity-60': drag.dragging() === entity(),
}}
style={{ height: height() + 'px' }}
>
<div class="w-full pl-0.5 pr-2 flex items-center justify-between h-full">
<div
class="absolute bottom-0 left-0 right-0 h-[3px] cursor-ns-resize translate-y-0.5 z-20 group/resize"
onPointerDown={handleResizeStart}
data-layer-label
class="flex-1 min-w-0 overflow-hidden"
style={{
'mask-image': controlsVisible() && !editing() ? 'linear-gradient(to right, #000 calc(100% - 1.25rem), transparent)' : undefined,
'-webkit-mask-image': controlsVisible() && !editing() ? 'linear-gradient(to right, #000 calc(100% - 1.25rem), transparent)' : undefined,
}}
>
<div
class="absolute left-0 right-0 top-px h-px transition-colors group-hover/resize:bg-primary"
classList={{ 'bg-primary': resized() === entity() }}
/>
class="flex items-center gap-0.5 w-max"
style={{
'padding-left': `${props.depth * NESTED_INDENT_PX}px`,
transform: editing() ? 'none' : 'translateX(calc(var(--layer-x, 0px) * -1))',
}}
>
<button
disabled={!props.layer.expandable}
onClick={toggleExpanded}
class="size-4 shrink-0 flex items-center justify-center overflow-clip invisible group-hover/layers:visible focus-ring rounded-sm"
>
<Show when={props.layer.expandable}>
<Icon name={props.expanded ? "chevron-down" : "chevron-right"} class="hover:text-foreground" />
</Show>
</button>
<div class="size-4 shrink-0 flex items-center justify-center overflow-clip mr-0.5">
<Icon name={icon()} />
</div>
<Show
when={editing()}
fallback={
<span class="text-xs px-0.5 shrink-0 whitespace-nowrap text-foreground" onDblClick={startEditing}>
{name()}
</span>
}
>
<input
ref={mountNameInput}
type="text"
class="text-xs bg-input border border-primary rounded-sm outline-none px-0.5 w-32 text-foreground"
value={name()}
onInput={handleNameInput}
onKeyDown={handleNameKeyDown}
onBlur={(e) => finishEditing(e.currentTarget)}
onPointerDown={(e) => e.stopPropagation()}
onDblClick={(e) => e.stopPropagation()}
/>
</Show>
</div>
</div>
</ContextMenuTrigger>
<ContextMenuPortal>
<ContextMenuContent class="w-[160px]">
<ContextMenuItem onSelect={toggleMuted}>{muted() ? 'Unmute' : 'Mute'}</ContextMenuItem>
<ContextMenuItem onSelect={toggleSoloed}>{soloed() ? 'Unsolo' : 'Solo'}</ContextMenuItem>
<ContextMenuItem onSelect={toggleHidden}>{hidden() ? 'Unhide' : 'Hide'}</ContextMenuItem>
<ContextMenuSeparator />
<ContextMenuItem onSelect={() => handleReorder('front')}>
Bring to front
<ContextMenuShortcut>]</ContextMenuShortcut>
</ContextMenuItem>
<ContextMenuItem onSelect={() => handleReorder('back')}>
Send to back
<ContextMenuShortcut>[</ContextMenuShortcut>
</ContextMenuItem>
<ContextMenuSeparator />
<ContextMenuItem onSelect={handleRemove}>Remove</ContextMenuItem>
</ContextMenuContent>
</ContextMenuPortal>
</ContextMenu>
<div
class="items-center flex gap-0.5 shrink-0 overflow-hidden group-hover:w-auto"
classList={{
'hidden': resized() !== null,
'w-0': !(muted() || soloed() || hidden()),
'w-auto': muted() || soloed() || hidden(),
}}
>
<Tooltip placement="bottom">
<TooltipTrigger
as={Button}
variant={muted() ? "on" : "ghost"}
size="icon"
class="invisible group-hover:visible"
style={{ visibility: muted() ? 'visible' : undefined }}
onClick={toggleMuted}
>
<Icon name="mute" />
</TooltipTrigger>
<TooltipPortal>
<TooltipContent>{muted() ? "Unmute" : "Mute"}</TooltipContent>
</TooltipPortal>
</Tooltip>
<Tooltip placement="bottom">
<TooltipTrigger
as={Button}
variant={soloed() ? "on" : "ghost"}
size="icon"
class="invisible group-hover:visible"
style={{ visibility: soloed() ? 'visible' : undefined }}
onClick={toggleSoloed}
>
<Icon name="solo" />
</TooltipTrigger>
<TooltipPortal>
<TooltipContent>{soloed() ? "Unsolo" : "Solo"}</TooltipContent>
</TooltipPortal>
</Tooltip>
<Tooltip placement="bottom">
<TooltipTrigger
as={Button}
variant="ghost"
size="icon"
class="invisible group-hover:visible"
onClick={toggleHidden}
style={{ visibility: hidden() ? 'visible' : undefined }}
>
<Show when={!hidden()} fallback={<Icon name="eye-off" />}>
<Icon name="eye-on" />
</Show>
</TooltipTrigger>
<TooltipPortal>
<TooltipContent>{hidden() ? "Show" : "Hide"}</TooltipContent>
</TooltipPortal>
</Tooltip>
</div>
</div>
{/* Drag the bottom edge to make the row taller. */}
<div
class="absolute bottom-0 left-0 right-0 h-[3px] cursor-ns-resize translate-y-0.5 z-20 group/resize"
onPointerDown={handleResizeStart}
>
<div
class="absolute left-0 right-0 top-px h-px transition-colors group-hover/resize:bg-primary"
classList={{ 'bg-primary': resized() === entity() }}
/>
</div>
</NodeContextMenu>
)
}
function getLayerIcon(world: World, layer: TimelineNode) {
const entity = layer.entity;
if (isClipPath(entity)) return "mask-small";
if (isClipShape(entity)) return "mask-small";
if (isAdjustmentLayer(entity)) return "adjustment-layer";
if (isScene(entity)) return "scene-frame-small";
if (isSequence(entity)) return "timeline-sequence-small";

View File

@ -5,10 +5,12 @@
import { createMemo, Show } from 'solid-js';
import { useTag, useWorld } from '@diffusionstudio/koota-solid';
import {
ClipPath,
ColorStop,
Effect,
Expanded,
Hovering,
Mask,
Name,
Paint,
PaintType,
@ -40,9 +42,10 @@ const PAINT_NAMES: Partial<Record<PaintType, string>> = {
};
/**
* A row for one of a clip's parts — a fill, a stroke, a shadow, an effect —
* which is here only so the keyframe rows under it have something to hang
* from. It has no clip of its own on the canvas beside it.
* A row for one of a clip's parts — a fill, a stroke, a shadow, an effect, a
* clip path or mask — which is here only so the keyframe rows and layers
* under it have something to hang from. It has no clip of its own on the
* canvas beside it.
*/
export function SubItemLayer(props: LayerRowProps) {
const world = useWorld();
@ -88,6 +91,11 @@ export function SubItemLayer(props: LayerRowProps) {
<Icon name={props.expanded ? "chevron-down" : "chevron-right"} class="hover:text-foreground" />
</Show>
</button>
<Show when={entity().has(Mask)}>
<div class="size-4 shrink-0 flex items-center justify-center overflow-clip mr-0.5">
<Icon name="layer-mask-small" />
</div>
</Show>
<span class="text-xs px-0.5 shrink-0 whitespace-nowrap text-foreground">
{name()}
</span>
@ -105,6 +113,8 @@ function describe(entity: Entity): string {
if (entity.has(Stroke)) return 'Stroke';
if (entity.has(Shadow)) return 'Shadow';
if (entity.has(ColorStop)) return 'Stop';
if (entity.has(ClipPath)) return 'Clip Path';
if (entity.has(Mask)) return 'Mask';
if (entity.has(Paint)) {
return PAINT_NAMES[entity.get(Paint)!.value as PaintType] ?? 'Fill';

Some files were not shown because too many files have changed in this diff Show More