diff --git a/.context/DESIGN.md b/.context/DESIGN.md index a60f2df1d..d8d976091 100644 --- a/.context/DESIGN.md +++ b/.context/DESIGN.md @@ -33,7 +33,11 @@ White system (Doop UI v2, canvas guideline `doop-ui-system`): neutral greys, no aliases). `--font-mono`: `'Geist Mono', ui-monospace, monospace` - values only (ids, sizes, numbers, key caps, code); the mono-uppercase caption voice is retired, captions and field labels are `text-caption` / `text-label` in sentence case. `--font-hero`: `'Hanken Grotesk'` Light - the - home greeting, and nothing else (loaded in `index.html`). There is no + home greeting, and nothing else (loaded in `index.html`). Every font stack lists `'Doop Keys'` + after its face: a 5 KB cut of the full Inter, inlined in `src/styles.css`, carrying only + the key symbols (⌘ ⌥ ⇧ ⌃ ⌫ ↩ ⇥ ⎋, arrows) the Google Fonts builds of Inter and Geist Mono drop, so + shortcut hints never fall back to the OS font's undersized glyphs. A new symbol in a hint goes + into its `unicode-range` and the subset (rebuild steps in `src/styles.css`). There is no serif: Instrument Serif was retired, and page-level headings outside the dashboard (sign-in, not-found, the desktop handoff) use `DashTitle` like every other page title. - **The scale** is named by role, as `--text-*` tokens in `src/styles.css` (each carries its line diff --git a/.context/RELEASE.md b/.context/RELEASE.md index 22b8794f7..c86b9ca8d 100644 --- a/.context/RELEASE.md +++ b/.context/RELEASE.md @@ -78,11 +78,15 @@ in `.github/actions/setup-desktop`: provider in the system browser and returns over a `doop://integration/` link; the app finishes it under its own session (`shared/desktopConnect.ts`). This is web-only: shells from 0.2.1 already deliver any `doop://` link, and older shells open Integrations in the browser. -- The macOS View menu (`desktop/src-tauri/src/view_menu.rs`) holds the canvas toggles (Rulers, - Show/Hide UI, Layers and Agents panels) and zoom. Items reach the page as `view-command` - events; the page mirrors its state back through `view_menu_state` (`src/lib/viewMenu.ts`, - gated on `window.__DOOP_VIEW_MENU__`), so checkmarks follow it and canvas items are disabled - off a canvas. Only ⌘ shortcuts are bound in the menu; ⇧R / ⇧1 / ⇧2 stay with the page. +- The macOS menu bar is the page's (`desktop/src-tauri/src/app_menu.rs`, `src/lib/appMenu.ts`, gated + on `window.__DOOP_APP_MENU__`, macOS only): the page sends File, Edit, View, Object, Text, Arrange + and Help from the action registry (`app_menu_set`, labels in its language, each chord as the key + equivalent) and then only changed enabled/checked state (`app_menu_state`); the shell keeps the + app menu, Close Tab, the system Undo/Cut/Copy/Paste/Select All that text fields need, Full Screen + and Window. A pick returns as `app-menu` `{ id, key }`; the webview sees a key before the menu, and + a key the menu does get keeps the canvas keyboard's rules (nothing while typing or presenting). + Until a page sets it the bar is the old fixed one, whose View menu (`view_menu.rs`, + `src/lib/viewMenu.ts`, `__DOOP_VIEW_MENU__`) an older page still drives. Needs a desktop release. - Server choice (`desktop/src-tauri/src/server.rs`, `src/components/ServerSettings.tsx`): the sign-in screen's cog (shells advertising `__DOOP_SERVER_CHOOSE__`) points an official build at a self-hosted server. `server_choose` normalizes the address to an origin (https, or http on loopback only), diff --git a/.context/TECHSTACK.md b/.context/TECHSTACK.md index 7665f3b53..df4e6482a 100644 --- a/.context/TECHSTACK.md +++ b/.context/TECHSTACK.md @@ -312,8 +312,8 @@ data-doop-webfonts>` for the roster families the frame names and does not load i - View options (`src/lib/viewOptions.ts`, per browser under `doop:view-options`): the zoom pill's menu opens on a field for a typed level (`150`, `150%`; `parseZoomPercent`) and switches the pixel grid (⇧'), other people's cursors (⌘⌥\ / Ctrl+Alt+\) and the comment pins (⇧C), each read - by `code` (`viewOptionForKey`). Hidden pins still show under the Comment tool and for a thread - that is open. Tests: `viewOptions.test.ts`, `zoomMenu.test.tsx`. + by `code` (registry actions `pixel-grid`, `comments`, `cursors`). Hidden pins still show under + the Comment tool and for a thread that is open. Tests: `viewOptions.test.ts`, `zoomMenu.test.tsx`. - Canvas panel layout (Settings → Appearance → Canvas panels, `src/lib/panelLayout.ts`, per browser under `doop:panel-layout`): `floating` (the default) keeps the islands over a full-window stage; `docked` makes Layers, the tool rail, the icon islands, the Inspector / @@ -359,6 +359,36 @@ data-doop-webfonts>` for the roster families the frame names and does not load i the brackets treat it as a frame, and ⌘A skips stack-locked shapes (`isStackLocked`). ↩ and Tab act only when no control has the keyboard (`isControlTarget`) and something is selected, so buttons, menus and the Layers tree keep theirs. The bracket chords are read by `code` too, since ⌥ changes the typed character on macOS. Tests: `selectionKeys.test.ts`. +- Canvas commands (`src/lib/actions/`): every editor command is one entry in `registry.ts` (id, + label key in the `actions` catalog, menu and section, chords, `edit`, `enabled`, `checked`, + `run`), and the keyboard (`dispatchActionKey`, called first by `CanvasPage`'s keydown), the ⌘K + palette (`CommandPalette.tsx`, cmdk through `ui/command.tsx`; text that names no command goes to + the agent's composer as a prompt), the main menu off the bar's Doop mark (`MainMenu.tsx`: File, + Edit, View, Object, Text, Arrange, Help) and the ⌃⇧? sheet (`ShortcutsSheet.tsx`) all read it. + `CanvasPage` lends the registry its modals and panels as the `ActionHost`. Chords (`chords.ts`) + are `mod` (⌘ on a Mac, Ctrl elsewhere), ⌥ chords by `code`, `macOnly` / `notMac` per platform (⌘Y + is outlines on a Mac, redo elsewhere), `global` for the two that act from fields (⌘K palette, ⌘/ + agent; a bare `/` opens the agent outside fields). A chord whose command is disabled or finds + nothing falls through to the browser. ⌫, Esc, ↩/Tab and the arrows stay in `CanvasPage`'s own + handler (their rules are shown, `hintOnly`). What the commands do lives in `edits.ts`: align / + distribute / tidy / pack (`arrange.ts`, pure geometry) move frames as one undo step + (`patchFrames`) and layers through the runtime's `move` geometry edit; ⌘G / ⌥⌘G wrap sibling + layers in a `div` (carrying a flex parent's flow; grid children are refused; a frame edited while + its layout is read is left alone) and ⇧⌘G / ⌘⌫ unwrap (`groupElements` / `ungroupElements` in + `layers.ts`); ⇧A makes a box a flex container, or wraps the pick in one, turning the space between + the layers into `gap` and dropping their flow margins so nothing moves; ⌥⌘C / ⌥⌘V copy and paste + computed looks (`doop:computed`), text styles only between text layers; ⇧⌘V / ⇧⌘R paste over or + replace the selection from the canvas clip (a frame goes only once all its replacements land; one + undo step, a single `transfer` (`replaceFramesTracked`), so undo never removes a replacement + before its original is back; tests in `replaceFrames.test.ts`); ⇧⌘U links (`setElementLink`: an + image or SVG is wrapped in the link, other layers' content is); ⌃C is the EyeDropper. ⌘F / ⌥⌘F is + the find bar (`FindBar.tsx`, `findText.ts`: text nodes only, locked layers found but never + replaced, replace-all is one undo step across frames). View toggles: ⇧' / ⇧C / ⌥⌘\ switch the view + options (pixel grid, comment pins, cursors), ⌘Y outline mode (an adopted sheet in each frame's + runtime, never saved or exported), ⌥L collapses the Layers tree. N / ⇧N zoom to the next frame in + reading order, Home / End bring it into view, PgUp / PgDn change page. Tests: + `actionRegistry.test.ts` (no chord bound twice per platform, nor over a tool key), + `actionChords.test.ts`, `arrange.test.ts`, `groupLayers.test.ts`, `findText.test.ts`. - `src/lib/tools.ts` defines bottom-toolbar tools and shortcuts. `Stage.tsx` delegates drawing gestures and world-space previews to `CanvasDrawing.tsx`; Space/middle-button panning takes precedence over drawing. diff --git a/bun.lock b/bun.lock index ace3901e8..cfb584ab6 100644 --- a/bun.lock +++ b/bun.lock @@ -25,6 +25,7 @@ "better-auth": "1.6.26", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", + "cmdk": "^1.1.1", "drizzle-orm": "^0.45.2", "envalid": "8.2.0", "express": "^4.19.2", @@ -971,6 +972,8 @@ "clsx": ["clsx@2.1.1", "", {}, "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA=="], + "cmdk": ["cmdk@1.1.1", "", { "dependencies": { "@radix-ui/react-compose-refs": "^1.1.1", "@radix-ui/react-dialog": "^1.1.6", "@radix-ui/react-id": "^1.1.0", "@radix-ui/react-primitive": "^2.0.2" }, "peerDependencies": { "react": "^18 || ^19 || ^19.0.0-rc", "react-dom": "^18 || ^19 || ^19.0.0-rc" } }, "sha512-Vsv7kFaXm+ptHDMZ7izaRsP70GgrW9NBNGswt9OZaVBLlE0SNpDq8eu/VGXyF9r7M0azK3Wy7OlYXsuyYLFzHg=="], + "code-block-writer": ["code-block-writer@13.0.3", "", {}, "sha512-Oofo0pq3IKnsFtuHqSF7TqBfr71aeyZDVJ0HpmqB7FBM2qEigL0iPONSCZSO9pE9dZTAxANe5XHG9Uy0YMv8cg=="], "color": ["color@4.2.3", "", { "dependencies": { "color-convert": "^2.0.1", "color-string": "^1.9.0" } }, "sha512-1rXeuUUiGGrykh+CeBdu5Ie7OJwinCgQY0bc7GCRxy5xVHy+moaqkpL/jqQq0MtQOeYcrqEz4abc5f0KtU7W4A=="], @@ -1967,6 +1970,8 @@ "cliui/string-width": ["string-width@7.2.0", "", { "dependencies": { "emoji-regex": "^10.3.0", "get-east-asian-width": "^1.0.0", "strip-ansi": "^7.1.0" } }, "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ=="], + "cmdk/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.2.0", "", { "dependencies": { "@radix-ui/react-slot": "1.5.0" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg=="], + "concurrently/yargs": ["yargs@17.7.3", "", { "dependencies": { "cliui": "^8.0.1", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "require-directory": "^2.1.1", "string-width": "^4.2.3", "y18n": "^5.0.5", "yargs-parser": "^21.1.1" } }, "sha512-GZtjxm/J/4TSxuL3FNYjCmLktBTnIw/rVmKSIyKeYAZpmJB2ig9VauCC5xsa82GNKVKDAqpOn3KVzNt0zmrU0g=="], "conf/ajv": ["ajv@8.20.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="], @@ -2187,6 +2192,8 @@ "cliui/string-width/emoji-regex": ["emoji-regex@10.6.0", "", {}, "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A=="], + "cmdk/@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.5.0", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.5" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ=="], + "concurrently/yargs/cliui": ["cliui@8.0.1", "", { "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.1", "wrap-ansi": "^7.0.0" } }, "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ=="], "concurrently/yargs/string-width": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="], diff --git a/desktop/src-tauri-chromium/Cargo.lock b/desktop/src-tauri-chromium/Cargo.lock index 718edc136..af8fc04c7 100644 --- a/desktop/src-tauri-chromium/Cargo.lock +++ b/desktop/src-tauri-chromium/Cargo.lock @@ -1221,6 +1221,7 @@ dependencies = [ "reqwest", "rfd", "rustls", + "serde", "serde_json", "tauri", "tauri-build", diff --git a/desktop/src-tauri-chromium/Cargo.toml b/desktop/src-tauri-chromium/Cargo.toml index 5f1358ca9..8a761cbde 100644 --- a/desktop/src-tauri-chromium/Cargo.toml +++ b/desktop/src-tauri-chromium/Cargo.toml @@ -33,6 +33,8 @@ tauri-plugin-opener = "=3.0.0-alpha.3" tauri-plugin-deep-link = "=3.0.0-alpha.3" tauri-plugin-single-instance = { version = "=3.0.0-alpha.3", features = ["deep-link"] } tauri-plugin-updater = "=3.0.0-alpha.3" +# the page's menu bar arrives typed (src/app_menu.rs) +serde = { version = "1", features = ["derive"] } serde_json = "1" toml_edit = "0.25" tempfile = "3" @@ -44,7 +46,7 @@ reqwest = { version = "0.13", default-features = false, features = ["json", "rus rustls = { version = "0.23", default-features = false, features = ["ring"] } [target.'cfg(target_os = "macos")'.dependencies] -objc2-app-kit = { version = "0.3", features = ["NSButton", "NSControl", "NSResponder", "NSView", "NSWindow"] } +objc2-app-kit = { version = "0.3", features = ["NSApplication", "NSButton", "NSControl", "NSEvent", "NSResponder", "NSView", "NSWindow"] } # reading the WebKit app's cookies and localStorage on the first launch (src/webkit_migration.rs) objc2 = "0.6" block2 = "0.6" diff --git a/desktop/src-tauri/Cargo.lock b/desktop/src-tauri/Cargo.lock index 7ddade6f7..a3b2c1c0d 100644 --- a/desktop/src-tauri/Cargo.lock +++ b/desktop/src-tauri/Cargo.lock @@ -936,10 +936,12 @@ dependencies = [ name = "doop-desktop" version = "0.13.0" dependencies = [ + "objc2", "objc2-app-kit", "reqwest", "rfd", "rustls", + "serde", "serde_json", "tauri", "tauri-build", diff --git a/desktop/src-tauri/Cargo.toml b/desktop/src-tauri/Cargo.toml index c2973538a..cb01e54a9 100644 --- a/desktop/src-tauri/Cargo.toml +++ b/desktop/src-tauri/Cargo.toml @@ -16,6 +16,8 @@ tauri-plugin-opener = "2" tauri-plugin-deep-link = "2" tauri-plugin-single-instance = { version = "2", features = ["deep-link"] } # generate_context! embeds the `plugins` section of tauri.conf.json through it +# the page's menu bar arrives typed (src/app_menu.rs) +serde = { version = "1", features = ["derive"] } serde_json = "1" toml_edit = "0.25" tempfile = "3" @@ -35,7 +37,9 @@ rustls = { version = "0.23", default-features = false, features = ["ring"] } # Repositioning the traffic lights over the web app's tab strip (main.rs); # AppKit resets them on window events, so the shell moves them itself. [target.'cfg(target_os = "macos")'.dependencies] -objc2-app-kit = { version = "0.3", features = ["NSButton", "NSControl", "NSResponder", "NSView", "NSWindow"] } +# MainThreadMarker, to read the event behind a menu pick (src/app_menu.rs) +objc2 = "0.6" +objc2-app-kit = { version = "0.3", features = ["NSApplication", "NSButton", "NSControl", "NSEvent", "NSResponder", "NSView", "NSWindow"] } [profile.release] strip = true diff --git a/desktop/src-tauri/build.rs b/desktop/src-tauri/build.rs index cbf8c543a..b77db6db4 100644 --- a/desktop/src-tauri/build.rs +++ b/desktop/src-tauri/build.rs @@ -25,6 +25,8 @@ fn main() { "server_status", "server_choose", "view_menu_state", + "app_menu_set", + "app_menu_state", "update_card_ready", "update_restart", ])); diff --git a/desktop/src-tauri/capabilities/default.json b/desktop/src-tauri/capabilities/default.json index c39e1b6ba..85a315e8c 100644 --- a/desktop/src-tauri/capabilities/default.json +++ b/desktop/src-tauri/capabilities/default.json @@ -37,6 +37,8 @@ "allow-server-status", "allow-server-choose", "allow-view-menu-state", + "allow-app-menu-set", + "allow-app-menu-state", "allow-update-card-ready", "allow-update-restart" ] diff --git a/desktop/src-tauri/permissions/autogenerated/app_menu_set.toml b/desktop/src-tauri/permissions/autogenerated/app_menu_set.toml new file mode 100644 index 000000000..5184bfaaa --- /dev/null +++ b/desktop/src-tauri/permissions/autogenerated/app_menu_set.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-app-menu-set" +description = "Enables the app_menu_set command without any pre-configured scope." +commands.allow = ["app_menu_set"] + +[[permission]] +identifier = "deny-app-menu-set" +description = "Denies the app_menu_set command without any pre-configured scope." +commands.deny = ["app_menu_set"] diff --git a/desktop/src-tauri/permissions/autogenerated/app_menu_state.toml b/desktop/src-tauri/permissions/autogenerated/app_menu_state.toml new file mode 100644 index 000000000..9a85a5fc1 --- /dev/null +++ b/desktop/src-tauri/permissions/autogenerated/app_menu_state.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-app-menu-state" +description = "Enables the app_menu_state command without any pre-configured scope." +commands.allow = ["app_menu_state"] + +[[permission]] +identifier = "deny-app-menu-state" +description = "Denies the app_menu_state command without any pre-configured scope." +commands.deny = ["app_menu_state"] diff --git a/desktop/src-tauri/src/app_menu.rs b/desktop/src-tauri/src/app_menu.rs new file mode 100644 index 000000000..d3b0e271c --- /dev/null +++ b/desktop/src-tauri/src/app_menu.rs @@ -0,0 +1,226 @@ +//! The macOS menu bar, built by the page from its action registry +//! (src/lib/appMenu.ts), as Figma's desktop app mirrors its menus: File, +//! Edit, View, Object, Text, Arrange and Help, each command with its label in +//! the page's language and its chord as the key equivalent. +//! +//! The page sends the menus through `app_menu_set` (on load, and again when +//! its language changes) and afterwards only the items whose enabled or +//! checked state moved, through `app_menu_state`. The shell keeps what is its +//! own around them: the app menu, Close Tab, the system's Undo / Redo / Cut / +//! Copy / Paste / Select All (what makes those keys reach a text field), Full +//! Screen and Window. A picked item is relayed as an `app-menu` event, +//! `{ id, key }`, `key` saying a key equivalent fired it rather than a click, +//! so the page can keep its keyboard's rules for it (nothing while typing in +//! a field, for one). +//! +//! The webview sees a key before the menu does: the menu only gets the key +//! equivalents the page left unhandled, so a chord the canvas takes runs +//! once, and a key typed into a field still types. +//! +//! Until the page calls `app_menu_set` the bar is `build_menu`'s, with the +//! fixed View menu (src/view_menu.rs) an older page still drives. Windows and +//! Linux have no menu bar; there the commands find nothing to do. + +#![cfg_attr(not(target_os = "macos"), allow(dead_code))] + +use std::collections::HashMap; +use std::sync::Mutex; + +use serde::{Deserialize, Serialize}; +use tauri::menu::{CheckMenuItem, MenuItem}; +#[cfg(target_os = "macos")] +use tauri::menu::{IsMenuItem, Menu, PredefinedMenuItem, Submenu}; +use tauri::{AppHandle, Emitter, Manager}; + +use crate::ShellRuntime; + +pub const EVENT: &str = "app-menu"; +const PREFIX: &str = "action:"; + +/// One menu as the page describes it; a `null` item is a separator. +#[derive(Deserialize)] +pub struct MenuSpec { + id: String, + label: String, + items: Vec>, +} + +#[derive(Deserialize)] +struct ItemSpec { + id: String, + label: String, + /// a Tauri accelerator such as "Alt+Cmd+KeyG" + accelerator: Option, + checkable: bool, +} + +/// An item's state as the page reports it: id, enabled, checked (null for an +/// item that is not a toggle). +type ItemState = (String, bool, Option); + +#[derive(Serialize, Clone)] +struct Picked<'a> { + id: &'a str, + key: bool, +} + +enum Item { + Plain(MenuItem), + Check(CheckMenuItem), +} + +/// The page's items in the bar, by action id. +#[derive(Default)] +pub struct AppMenu(Mutex>); + +/// An item the page asked for. An accelerator the menu cannot parse leaves +/// the item without one rather than the bar without the menu. +#[cfg(target_os = "macos")] +fn page_item( + app: &AppHandle, + spec: &ItemSpec, +) -> tauri::Result<(Box>, Item)> { + let id = format!("{PREFIX}{}", spec.id); + let id = id.as_str(); + let accelerator = spec.accelerator.as_deref(); + if spec.checkable { + let item = CheckMenuItem::with_id(app, id, &spec.label, false, false, accelerator) + .or_else(|_| { + CheckMenuItem::with_id(app, id, &spec.label, false, false, None::<&str>) + })?; + Ok((Box::new(item.clone()), Item::Check(item))) + } else { + let item = MenuItem::with_id(app, id, &spec.label, false, accelerator) + .or_else(|_| MenuItem::with_id(app, id, &spec.label, false, None::<&str>))?; + Ok((Box::new(item.clone()), Item::Plain(item))) + } +} + +/// One of the page's menus, with the shell's own rows where they belong. +#[cfg(target_os = "macos")] +fn submenu( + app: &AppHandle, + spec: &MenuSpec, + items: &mut HashMap, +) -> tauri::Result> { + let mut rows: Vec>> = Vec::new(); + if spec.id == "edit" { + rows.extend(crate::text_edit_items(app)?.0); + rows.push(Box::new(PredefinedMenuItem::separator(app)?)); + } + for entry in &spec.items { + match entry { + Some(item) => { + let (row, handle) = page_item(app, item)?; + rows.push(row); + items.insert(item.id.clone(), handle); + } + None => rows.push(Box::new(PredefinedMenuItem::separator(app)?)), + } + } + match spec.id.as_str() { + "file" => { + rows.push(Box::new(PredefinedMenuItem::separator(app)?)); + rows.push(Box::new(crate::close_tab_item(app)?)); + } + "view" => { + rows.push(Box::new(PredefinedMenuItem::separator(app)?)); + rows.push(Box::new(PredefinedMenuItem::fullscreen(app, None)?)); + } + _ => {} + } + let refs: Vec<&dyn IsMenuItem> = rows.iter().map(|row| row.as_ref()).collect(); + Submenu::with_items(app, &spec.label, true, &refs) +} + +/// The whole bar: the app menu, the page's menus, and Window before Help. +#[cfg(target_os = "macos")] +fn build( + app: &AppHandle, + menus: &[MenuSpec], +) -> tauri::Result<(Menu, HashMap)> { + let mut items = HashMap::new(); + let mut bar = vec![crate::app_submenu(app)?]; + let mut window = Some(crate::window_submenu(app)?); + for spec in menus { + let menu = submenu(app, spec, &mut items)?; + if spec.id == "help" { + bar.extend(window.take()); + menu.set_as_help_menu_for_nsapp()?; + } + bar.push(menu); + } + bar.extend(window); + let refs: Vec<&dyn IsMenuItem> = bar + .iter() + .map(|menu| menu as &dyn IsMenuItem) + .collect(); + Ok((Menu::with_items(app, &refs)?, items)) +} + +/// The page's menus become the bar. +#[tauri::command] +pub fn app_menu_set(app: AppHandle, menus: Vec) -> Result<(), String> { + #[cfg(target_os = "macos")] + { + let (menu, items) = build(&app, &menus).map_err(|e| e.to_string())?; + app.set_menu(menu).map_err(|e| e.to_string())?; + let state = app.state::(); + *state.0.lock().unwrap_or_else(|e| e.into_inner()) = items; + } + #[cfg(not(target_os = "macos"))] + let _ = (app, menus); + Ok(()) +} + +/// What the page's items show now; ids the bar does not hold are skipped. +#[tauri::command] +pub fn app_menu_state(app: AppHandle, items: Vec) { + let state = app.state::(); + let menu = state.0.lock().unwrap_or_else(|e| e.into_inner()); + for (id, enabled, checked) in items { + match menu.get(&id) { + Some(Item::Plain(item)) => { + let _ = item.set_enabled(enabled); + } + Some(Item::Check(item)) => { + let _ = item.set_enabled(enabled); + let _ = item.set_checked(checked.unwrap_or(false)); + } + None => {} + } + } +} + +/// Relays one of the page's items to it; any other menu id is ignored. +pub fn relay(app: &AppHandle, id: &str) { + if let Some(id) = id.strip_prefix(PREFIX) { + let _ = app.emit( + EVENT, + Picked { + id, + key: fired_by_key(), + }, + ); + } +} + +/// Whether the event AppKit is handling is a key press: a key equivalent +/// picked the item, not the pointer. +#[cfg(target_os = "macos")] +fn fired_by_key() -> bool { + use objc2::MainThreadMarker; + use objc2_app_kit::{NSApplication, NSEventType}; + + let Some(mtm) = MainThreadMarker::new() else { + return false; + }; + NSApplication::sharedApplication(mtm) + .currentEvent() + .is_some_and(|event| event.r#type() == NSEventType::KeyDown) +} + +#[cfg(not(target_os = "macos"))] +fn fired_by_key() -> bool { + false +} diff --git a/desktop/src-tauri/src/main.rs b/desktop/src-tauri/src/main.rs index 8653f40f7..14c8cde6d 100644 --- a/desktop/src-tauri/src/main.rs +++ b/desktop/src-tauri/src/main.rs @@ -42,9 +42,10 @@ #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] #[cfg(target_os = "macos")] -use tauri::menu::{AboutMetadata, Menu, MenuItem, PredefinedMenuItem, Submenu}; +use tauri::menu::{AboutMetadata, IsMenuItem, Menu, MenuItem, PredefinedMenuItem, Submenu}; #[cfg(target_os = "macos")] use tauri::Emitter; +mod app_menu; #[cfg(target_os = "linux")] mod appimage; mod claude; @@ -152,9 +153,29 @@ const CLOSE_TAB: &str = "close-tab"; /// by "Close Tab" in the File menu. Everything else stays: the app menu /// (with Check for Updates added below About), Edit (the predefined items /// are what make Cmd+C/V/Z reach the webview at all), View (the canvas's -/// view toggles and zoom, src/view_menu.rs) and Window. +/// view toggles and zoom, src/view_menu.rs) and Window. This is the bar until +/// the page builds its own from the action registry (src/app_menu.rs); a page +/// older than that keeps it. #[cfg(target_os = "macos")] fn build_menu(app: &AppHandle) -> tauri::Result> { + let file = Submenu::with_items(app, "File", true, &[&close_tab_item(app)?])?; + let edit = Submenu::with_items(app, "Edit", true, &text_edit_items(app)?.each())?; + let view = view_menu::submenu(app)?; + Menu::with_items( + app, + &[ + &app_submenu(app)?, + &file, + &edit, + &view, + &window_submenu(app)?, + ], + ) +} + +/// The app menu: About, Check for Updates, Services, Hide and Quit. +#[cfg(target_os = "macos")] +fn app_submenu(app: &AppHandle) -> tauri::Result> { let pkg = app.package_info(); let about = AboutMetadata { name: Some(pkg.name.clone()), @@ -169,15 +190,14 @@ fn build_menu(app: &AppHandle) -> tauri::Result> { let hide = PredefinedMenuItem::hide(app, None)?; let hide_others = PredefinedMenuItem::hide_others(app, None)?; let quit = PredefinedMenuItem::quit(app, None)?; - let mut app_items: Vec<&dyn tauri::menu::IsMenuItem> = - vec![&about, &check_updates]; + let mut app_items: Vec<&dyn IsMenuItem> = vec![&about, &check_updates]; // only while another server is chosen: the way back from one that no // longer loads (src/server.rs) if let Some(item) = &server_reset { app_items.push(item); } app_items.extend([ - &separator as &dyn tauri::menu::IsMenuItem, + &separator as &dyn IsMenuItem, &services, &separator, &hide, @@ -185,34 +205,33 @@ fn build_menu(app: &AppHandle) -> tauri::Result> { &separator, &quit, ]); - let app_menu = Submenu::with_items(app, pkg.name.clone(), true, &app_items)?; - let file = Submenu::with_items( - app, - "File", - true, - &[&MenuItem::with_id( - app, - CLOSE_TAB, - "Close Tab", - true, - Some("Cmd+W"), - )?], - )?; - let edit = Submenu::with_items( - app, - "Edit", - true, - &[ - &PredefinedMenuItem::undo(app, None)?, - &PredefinedMenuItem::redo(app, None)?, - &PredefinedMenuItem::separator(app)?, - &PredefinedMenuItem::cut(app, None)?, - &PredefinedMenuItem::copy(app, None)?, - &PredefinedMenuItem::paste(app, None)?, - &PredefinedMenuItem::select_all(app, None)?, - ], - )?; - let view = view_menu::submenu(app)?; + Submenu::with_items(app, pkg.name.clone(), true, &app_items) +} + +/// File's Close Tab (Cmd+W), relayed to the page as `close-tab`. +#[cfg(target_os = "macos")] +fn close_tab_item(app: &AppHandle) -> tauri::Result> { + MenuItem::with_id(app, CLOSE_TAB, "Close Tab", true, Some("Cmd+W")) +} + +/// The system's text editing commands: AppKit sends them to the focused +/// field, which is how Cmd+Z / X / C / V / A reach an input in the webview. +#[cfg(target_os = "macos")] +fn text_edit_items(app: &AppHandle) -> tauri::Result { + Ok(MenuEntries(vec![ + Box::new(PredefinedMenuItem::undo(app, None)?), + Box::new(PredefinedMenuItem::redo(app, None)?), + Box::new(PredefinedMenuItem::separator(app)?), + Box::new(PredefinedMenuItem::cut(app, None)?), + Box::new(PredefinedMenuItem::copy(app, None)?), + Box::new(PredefinedMenuItem::paste(app, None)?), + Box::new(PredefinedMenuItem::select_all(app, None)?), + ])) +} + +/// The Window menu, which AppKit fills with the open windows. +#[cfg(target_os = "macos")] +fn window_submenu(app: &AppHandle) -> tauri::Result> { let window = Submenu::with_items( app, "Window", @@ -222,7 +241,19 @@ fn build_menu(app: &AppHandle) -> tauri::Result> { &PredefinedMenuItem::maximize(app, None)?, ], )?; - Menu::with_items(app, &[&app_menu, &file, &edit, &view, &window]) + window.set_as_windows_menu_for_nsapp()?; + Ok(window) +} + +/// A submenu's rows, built in pieces and handed to `Submenu::with_items`. +#[cfg(target_os = "macos")] +struct MenuEntries(Vec>>); + +#[cfg(target_os = "macos")] +impl MenuEntries { + fn each(&self) -> Vec<&dyn IsMenuItem> { + self.0.iter().map(|entry| entry.as_ref()).collect() + } } /// The Chromium shell's runtime settings. Session cookies outlive a restart @@ -286,6 +317,7 @@ fn main() { let builder = builder .manage(claude::ClaudeState::default()) .manage(fonts::LocalFonts::default()) + .manage(app_menu::AppMenu::default()) .invoke_handler(tauri::generate_handler![ claude::claude_status, claude::claude_connect, @@ -302,6 +334,8 @@ fn main() { server::server_status, server::server_choose, view_menu::view_menu_state, + app_menu::app_menu_set, + app_menu::app_menu_state, updates::update_card_ready, updates::update_restart ]) @@ -321,6 +355,7 @@ fn main() { server::menu::reset(app); } else { view_menu::relay(app, event.id().as_ref()); + app_menu::relay(app, event.id().as_ref()); } }); builder @@ -386,10 +421,12 @@ fn main() { // (traffic-light inset arrived with the overlay title bar, 0.1.2) // and the platform tells it which window framing it lives under. let desktop_marker = format!( - "window.__DOOP_DESKTOP__ = '{}'; window.__DOOP_DESKTOP_PLATFORM__ = '{}'; window.__DOOP_CLAUDE_CLI__ = true; window.__DOOP_CLAUDE_INSTALL__ = true; window.__DOOP_CLAUDE_CHOOSE__ = true; window.__DOOP_CLAUDE_EXTENSION__ = {}; window.__DOOP_CODEX_SETUP__ = true; window.__DOOP_VIEW_MENU__ = true; window.__DOOP_LOCAL_FONTS__ = true; window.__DOOP_UPDATE_CARD__ = true; window.__DOOP_SERVER_CHOOSE__ = true;", + "window.__DOOP_DESKTOP__ = '{}'; window.__DOOP_DESKTOP_PLATFORM__ = '{}'; window.__DOOP_CLAUDE_CLI__ = true; window.__DOOP_CLAUDE_INSTALL__ = true; window.__DOOP_CLAUDE_CHOOSE__ = true; window.__DOOP_CLAUDE_EXTENSION__ = {}; window.__DOOP_CODEX_SETUP__ = true; window.__DOOP_VIEW_MENU__ = true; window.__DOOP_APP_MENU__ = {}; window.__DOOP_LOCAL_FONTS__ = true; window.__DOOP_UPDATE_CARD__ = true; window.__DOOP_SERVER_CHOOSE__ = true;", app.package_info().version, std::env::consts::OS, - cfg!(any(target_os = "macos", target_os = "windows")) + cfg!(any(target_os = "macos", target_os = "windows")), + // only macOS has a menu bar for the page to build (app_menu.rs) + cfg!(target_os = "macos") ); // macOS never reports the saved path on `Finished`, so remember // the destinations chosen on `Requested`, keyed by URL. The same diff --git a/package.json b/package.json index 9eab1150e..9c0f640c0 100644 --- a/package.json +++ b/package.json @@ -51,6 +51,7 @@ "better-auth": "1.6.26", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", + "cmdk": "^1.1.1", "drizzle-orm": "^0.45.2", "envalid": "8.2.0", "express": "^4.19.2", diff --git a/src/assets/fonts/inter-LICENSE.txt b/src/assets/fonts/inter-LICENSE.txt new file mode 100644 index 000000000..39830805d --- /dev/null +++ b/src/assets/fonts/inter-LICENSE.txt @@ -0,0 +1,92 @@ +Copyright (c) 2016-2018 The Inter Project Authors (me@rsms.me) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION AND CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/src/components/CommandPalette.tsx b/src/components/CommandPalette.tsx new file mode 100644 index 000000000..7badd2d5e --- /dev/null +++ b/src/components/CommandPalette.tsx @@ -0,0 +1,92 @@ +import { useMemo, useState } from 'react' +import { useT } from '../lib/i18n' +import { chordHint, firstChord } from '../lib/actions/chords' +import { ACTIONS, MENUS, isEnabled, runAction, type CanvasAction } from '../lib/actions/registry' +import { + Command, + CommandEmpty, + CommandGroup, + CommandInput, + CommandItem, + CommandList, + CommandShortcut, +} from './ui/command' +import { CheckIcon, SparkIcon } from './ui/icons' +import { Modal } from './ui/modal' + +/** + * ⌘K: every canvas command that can run right now, searchable by name and + * grouped by the menu it lives in, each with its chord. Text that names no + * command can go to the agent instead, as a prompt. + */ +export function CommandPalette({ onClose, onAsk }: { onClose: () => void; onAsk: ((prompt: string) => void) | null }) { + const t = useT() + const [query, setQuery] = useState('') + /* what can run is read once, as the palette opens: the selection does not change under it */ + const [groups] = useState(() => + MENUS.map((menu) => ({ + menu, + actions: ACTIONS.filter((a) => a.menu === menu.id && a.id !== 'palette' && isEnabled(a)), + })).filter((g) => g.actions.length), + ) + const ask = useMemo(() => (onAsk && query.trim() ? query.trim() : null), [onAsk, query]) + + function choose(action: CanvasAction) { + onClose() + /* after the modal lets go of focus, so a command that opens a field keeps it */ + window.setTimeout(() => runAction(action), 0) + } + + return ( + + + + + {t('actions.paletteEmpty')} + {groups.map(({ menu, actions }) => ( + + {actions.map((action) => { + const chord = firstChord(action.keys) + const on = action.checked?.() + return ( + choose(action)} + > + + {on && } + + {t(action.label)} + {chord && {chordHint(chord)}} + + ) + })} + + ))} + {ask && onAsk && ( + + { + onClose() + onAsk(ask) + }} + > + + {t('actions.paletteAsk', { query: ask })} + + + )} + + + + ) +} diff --git a/src/components/FindBar.tsx b/src/components/FindBar.tsx new file mode 100644 index 000000000..8e920e7ec --- /dev/null +++ b/src/components/FindBar.tsx @@ -0,0 +1,232 @@ +import { useEffect, useMemo, useRef, useState, type KeyboardEvent } from 'react' +import type { Frame } from '../../shared/types' +import { readingOrder } from '../../shared/frameOrder' +import { useT } from '../lib/i18n' +import { usePageCanvas } from '../lib/pages' +import { canEditOpenCanvas, useStore } from '../lib/store' +import { saveFrameHtml } from '../lib/layerEdits' +import { findInHtml, replaceInHtml, type TextMatch } from '../lib/actions/findText' +import { saveFramesHtml } from '../lib/actions/edits' +import { cn } from '@/lib/utils' +import { Button } from './ui/button' +import { IconButton } from './ui/icon-button' +import { ArrowDownIcon, ArrowUpIcon, ChevronRightIcon, XIcon } from './ui/icons' +import { Input } from './ui/input' +import { Pressable } from './ui/pressable' +import { SearchField } from './ui/search-field' + +interface Hit { + frame: Frame + /** the match's place among its frame's matches, which a single replace names */ + n: number + match: TextMatch +} + +/** + * ⌘F: find text across the page's frames, step through the matches (↩ / + * ⇧↩), each one picked and flown to; ⌥⌘F opens it with a replace line, + * replacing one match or all of them as one undo step. + */ +export function FindBar({ + mode, + step, + onClose, +}: { + mode: 'find' | 'replace' + /** a step asked for from outside (the Edit menu's Find next/previous) */ + step: { dir: 1 | -1; at: number } | null + onClose: () => void +}) { + const t = useT() + const page = usePageCanvas() + const canEdit = useStore((s) => canEditOpenCanvas(s)) + const [query, setQuery] = useState('') + const [replacement, setReplacement] = useState('') + const [matchCase, setMatchCase] = useState(false) + const [showReplace, setShowReplace] = useState(mode === 'replace') + const [cursor, setCursor] = useState(0) + const inputRef = useRef(null) + + /* ⌘F again (or ⌥⌘F) while open puts the keyboard back in the field */ + const [seenMode, setSeenMode] = useState(mode) + if (seenMode !== mode) { + setSeenMode(mode) + if (mode === 'replace') setShowReplace(true) + } + useEffect(() => { + inputRef.current?.focus() + inputRef.current?.select() + }, [mode]) + + const hits = useMemo(() => { + const frames = readingOrder((page?.frames ?? []).filter((f) => !f.hidden)) + return frames.flatMap((frame) => + findInHtml(frame.html, query, { matchCase }).map((match, n) => ({ frame, n, match })), + ) + }, [page?.frames, query, matchCase]) + const active = hits.length ? Math.min(cursor, hits.length - 1) : -1 + + function go(index: number) { + const hit = hits[index] + if (!hit) return + setCursor(index) + const s = useStore.getState() + s.select(hit.frame.id) + s.pickElement({ frameId: hit.frame.id, selector: hit.match.selector }, true) + s.requestFlyTo(hit.frame.id) + } + + function move(dir: 1 | -1) { + if (!hits.length) return + go(active === -1 ? 0 : (active + dir + hits.length) % hits.length) + } + + /* the menus' Find next / previous */ + const [seenStep, setSeenStep] = useState(step) + if (seenStep !== step) { + setSeenStep(step) + if (step) move(step.dir) + } + + function replaceOne() { + const hit = hits[active] + if (!hit || hit.frame.locked || hit.match.locked) return + const replaced = replaceInHtml(hit.frame.html, query, replacement, { matchCase, only: hit.n }) + if (replaced) saveFrameHtml(hit.frame, replaced.html) + } + + function replaceAll() { + const byFrame = new Map() + for (const hit of hits) if (!hit.frame.locked) byFrame.set(hit.frame.id, hit.frame) + let count = 0 + const changes = [...byFrame.values()].flatMap((frame) => { + const replaced = replaceInHtml(frame.html, query, replacement, { matchCase }) + if (!replaced) return [] + count += replaced.count + return [{ frame, html: replaced.html }] + }) + saveFramesHtml(changes) + if (count) useStore.getState().pushNotice(t('actions.replaced', { count })) + } + + function onKeyDown(e: KeyboardEvent) { + if (e.key === 'Escape') { + e.preventDefault() + onClose() + } else if (e.key === 'Enter' && !e.nativeEvent.isComposing) { + e.preventDefault() + move(e.shiftKey ? -1 : 1) + } + } + + const count = !query.trim() + ? '' + : hits.length + ? t('actions.findCount', { current: active + 1, total: hits.length }) + : t('actions.findNone') + + return ( +
+
+ {canEdit && ( + setShowReplace((v) => !v)} + > + + + )} + { + setQuery(e.target.value) + setCursor(0) + }} + onKeyDown={onKeyDown} + placeholder={t('actions.findPlaceholder')} + aria-label={t('actions.findPlaceholder')} + trailing={{count}} + /> + setMatchCase((v) => !v)} + > + Aa + + move(-1)}> + + + move(1)}> + + + + + +
+ {canEdit && showReplace && ( +
+ setReplacement(e.target.value)} + onKeyDown={(e) => { + if (e.key === 'Escape') onClose() + else if (e.key === 'Enter' && !e.nativeEvent.isComposing) { + e.preventDefault() + replaceOne() + } + }} + placeholder={t('actions.replacePlaceholder')} + aria-label={t('actions.replacePlaceholder')} + /> + + +
+ )} + {hits.length > 0 && ( +
    + {hits.slice(0, 200).map((hit, i) => ( +
  • + go(i)} + className={cn( + 'flex w-full flex-col items-start rounded-row px-2 py-1 text-left', + i === active ? 'bg-paper-deep' : 'hover:bg-sub', + )} + > + {hit.frame.name} + + {hit.match.before} + {hit.match.text} + {hit.match.after} + + +
  • + ))} +
+ )} +
+ ) +} diff --git a/src/components/LayersPanel.tsx b/src/components/LayersPanel.tsx index 0afd16dba..c9d4c8aae 100644 --- a/src/components/LayersPanel.tsx +++ b/src/components/LayersPanel.tsx @@ -285,6 +285,14 @@ export function LayersPanel({ } } + /* ⌥L (Collapse layers) folds every row */ + const collapseAt = useStore((s) => s.layersCollapseAt) + const [seenCollapse, setSeenCollapse] = useState(collapseAt) + if (seenCollapse !== collapseAt) { + setSeenCollapse(collapseAt) + setExpanded(new Set()) + } + function setOpen(key: string, open: boolean) { setExpanded((prev) => { if (prev.has(key) === open) return prev diff --git a/src/components/LinkDialog.tsx b/src/components/LinkDialog.tsx new file mode 100644 index 000000000..934ccc12c --- /dev/null +++ b/src/components/LinkDialog.tsx @@ -0,0 +1,62 @@ +import { useState, type FormEvent } from 'react' +import { useT } from '../lib/i18n' +import { linkSelection, pickedLink } from '../lib/actions/edits' +import { Button } from './ui/button' +import { Input } from './ui/input' +import { Modal, ModalActions, ModalLede, ModalSpacer, ModalTitle } from './ui/modal' + +/** A bare host gets https: what a person types as "doop.design" means the site. */ +function normalizeHref(value: string): string { + const v = value.trim() + if (!v || /^[a-z][a-z0-9+.-]*:/i.test(v) || v.startsWith('/') || v.startsWith('#')) return v + return `https://${v}` +} + +/** ⇧⌘U: link the picked layers, or take their link off. */ +export function LinkDialog({ onClose }: { onClose: () => void }) { + const t = useT() + const [existing] = useState(pickedLink) + const [href, setHref] = useState(existing ?? '') + + function submit(e: FormEvent) { + e.preventDefault() + const next = normalizeHref(href) + linkSelection(next || null) + onClose() + } + + return ( + +
+ {t('actions.linkTitle')} + {t('actions.linkLede')} + setHref(e.target.value)} + placeholder="https://" + aria-label={t('actions.linkUrl')} + /> + + {existing !== null && ( + + )} + + + +
+
+ ) +} diff --git a/src/components/MainMenu.tsx b/src/components/MainMenu.tsx new file mode 100644 index 000000000..19f1e2716 --- /dev/null +++ b/src/components/MainMenu.tsx @@ -0,0 +1,98 @@ +import { Fragment, type ReactNode } from 'react' +import { useT } from '../lib/i18n' +import { chordHint, firstChord } from '../lib/actions/chords' +import { ACTIONS, MENUS, isEnabled, runAction, type CanvasAction, type MenuId } from '../lib/actions/registry' +import { + DropdownMenu, + DropdownMenuCheckboxItem, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuSeparator, + DropdownMenuSub, + DropdownMenuSubContent, + DropdownMenuSubTrigger, + DropdownMenuTrigger, +} from './ui/dropdown-menu' +import { MenuHint } from './ui/menu' +import { SearchIcon, SparkIcon } from './ui/icons' + +/* The rows of one menu, a separator between each section. Rows are read as + the menu opens (Radix mounts the content then), so what is enabled or + checked is current. */ +function MenuRows({ menu }: { menu: MenuId }) { + const t = useT() + const actions = ACTIONS.filter((a) => a.menu === menu) + const sections = [...new Set(actions.map((a) => a.section))] + return sections.map((section, i) => ( + + {i > 0 && } + {actions + .filter((a) => a.section === section) + .map((action) => ( + + ))} + + )) +} + +function ActionRow({ action, label, icon }: { action: CanvasAction; label: string; icon?: ReactNode }) { + const chord = firstChord(action.keys) + const hint = chord && {chordHint(chord)} + const disabled = !isEnabled(action) + if (action.checked) { + return ( + runAction(action)}> + {label} + {hint} + + ) + } + return ( + runAction(action)}> + {icon} + {label} + {hint} + + ) +} + +/** + * The canvas's main menu, off a button at the bar's left: the action search + * first, then File, Edit, View, Object, Text, Arrange and Help, each a + * submenu of the registry's commands with their chords. + */ +export function MainMenu({ trigger }: { trigger: ReactNode }) { + const t = useT() + const general = (id: string) => ACTIONS.find((a) => a.id === id)! + return ( + + {trigger} + + } + /> + {isEnabled(general('ask-agent')) && ( + } + /> + )} + + {MENUS.map((menu) => ( + + {menu.id === 'help' && } + + {t(menu.label)} + + + + + + ))} + + + ) +} diff --git a/src/components/PromptBar.tsx b/src/components/PromptBar.tsx index 2320bcfbd..e45298302 100644 --- a/src/components/PromptBar.tsx +++ b/src/components/PromptBar.tsx @@ -36,7 +36,7 @@ const MAX_ATTACHMENTS = 4 const MAX_SCOPE_LABEL = 24 /** the field grows with the draft up to this many lines, then scrolls */ const MAX_COMPOSER_LINES = 6 -/** a ⌘K older than this is ignored by a composer that mounts later */ +/** a ⌘/ older than this is ignored by a composer that mounts later */ const FOCUS_REQUEST_TTL_MS = 2000 interface ScopeChip { @@ -248,7 +248,7 @@ export function PromptBar({ canvasId }: { canvasId: string }) { if (inputRef.current) autosize(inputRef.current) }, [text]) - /* ⌘K: the page has opened the panel on this tab — take the keyboard. The + /* ⌘/: the page has opened the panel on this tab — take the keyboard. The request is a timestamp so a composer mounted later (a tab switch some minutes on) does not re-run an old one. */ useEffect(() => { diff --git a/src/components/ShortcutsSheet.tsx b/src/components/ShortcutsSheet.tsx new file mode 100644 index 000000000..2b3b3d178 --- /dev/null +++ b/src/components/ShortcutsSheet.tsx @@ -0,0 +1,74 @@ +import { useState } from 'react' +import { useT } from '../lib/i18n' +import { TOOLS } from '../lib/tools' +import { boundOn, chordHint } from '../lib/actions/chords' +import { ACTIONS, MENUS } from '../lib/actions/registry' +import { Kbd } from './ui/kbd' +import { Modal, ModalTitle } from './ui/modal' +import { SearchField } from './ui/search-field' + +/** + * ⌃⇧?: every chord the canvas knows, the tools first and then each menu's + * commands, filtered as you type. Read from the registry, so it can never + * list a shortcut that does not work. + */ +export function ShortcutsSheet({ onClose }: { onClose: () => void }) { + const t = useT() + const [query, setQuery] = useState('') + const q = query.trim().toLowerCase() + const tools = TOOLS.map((tool) => ({ id: tool.id, label: t(tool.label), hints: [tool.key] })) + const groups = [ + { id: 'tools', label: t('stage.canvasTools'), rows: tools }, + ...MENUS.map((menu) => ({ + id: menu.id, + label: t(menu.label), + rows: ACTIONS.filter((a) => a.menu === menu.id && a.keys?.some((k) => boundOn(k))).map((a) => ({ + id: a.id, + label: t(a.label), + hints: a.keys!.filter((k) => boundOn(k)).map((k) => chordHint(k)), + })), + })), + ] + .map((g) => ({ ...g, rows: g.rows.filter((r) => !q || r.label.toLowerCase().includes(q)) })) + .filter((g) => g.rows.length) + + return ( + + {t('actions.keyboardShortcuts')} + setQuery(e.target.value)} + placeholder={t('actions.shortcutsSearch')} + aria-label={t('actions.shortcutsSearch')} + /> +
+ {groups.length === 0 && ( +

+ {t('actions.shortcutsEmpty', { query: query.trim() })} +

+ )} +
+ {groups.map((group) => ( +
+

{group.label}

+
    + {group.rows.map((row) => ( +
  • + {row.label} + {row.hints.map((hint) => ( + + {hint} + + ))} +
  • + ))} +
+
+ ))} +
+
+
+ ) +} diff --git a/src/components/Stage.tsx b/src/components/Stage.tsx index a770ffea0..cb23635b4 100644 --- a/src/components/Stage.tsx +++ b/src/components/Stage.tsx @@ -52,7 +52,6 @@ import { layoutZoomFor } from '../lib/layoutZoom' import { useT, type PlainMessageKey } from '../lib/i18n' import { NO_INSETS, fitBox, type StageInsets } from '../lib/viewFit' import { spaceWouldScroll } from '../lib/spaceScroll' -import { viewOptionForKey } from '../lib/viewOptions' import { ZOOM_DRAG_MIN, ZOOM_TOOL_STEP, zoomAtPoint, zoomToBox } from '../lib/zoomTool' const MIN_ZOOM = 0.08 @@ -716,51 +715,11 @@ export function Stage({ } }, []) - /* ⌘0 → 100%, ⌘+ / ⌘− → step zoom, all pivoting on the view center — - preventDefault keeps the browser's own page zoom out of it. ⇧1 / ⇧2 fit - everything / the selection and ⇧R shows or hides the rulers, as in Figma. - ⇧' / ⇧C / ⌘⌥\ switch the pixel grid, the comment pins and other people's - cursors (src/lib/viewOptions.ts). */ - useEffect(() => { - function onKey(e: KeyboardEvent) { - const t = e.target as HTMLElement - if (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable) return - const option = viewOptionForKey(e) - if (option) { - e.preventDefault() - if (!e.repeat) useStore.getState().toggleViewOption(option) - return - } - if (e.shiftKey && !e.metaKey && !e.ctrlKey && !e.altKey) { - if (e.key.toLowerCase() === 'r') { - e.preventDefault() - if (!e.repeat) useStore.getState().toggleRulers() - return - } - /* by code: ⇧1 types '!' on most layouts, so the key name is no use */ - if (e.code !== 'Digit1' && e.code !== 'Digit2') return - e.preventDefault() - if (e.code === 'Digit1') fit() - else fitSelection() - return - } - if (!(e.metaKey || e.ctrlKey) || e.altKey) return - if (e.key !== '0' && e.key !== '=' && e.key !== '+' && e.key !== '-') return - /* '+' arrives as ⇧= on most layouts; any other shifted combo isn't ours */ - if (e.shiftKey && e.key !== '+') return - const el = ref.current - if (!el) return - e.preventDefault() - const zoom = useStore.getState().viewport.zoom - if (e.key === '0') zoomCentered(el, 1) - else if (e.key === '-') zoomCentered(el, zoom / 1.25) - else zoomCentered(el, zoom * 1.25) - } - window.addEventListener('keydown', onKey) - return () => window.removeEventListener('keydown', onKey) - }, [fit, fitSelection]) - - /* the same zooms from the desktop shell's View menu */ + /* zooms by command: ⌘0 → 100%, ⌘+ / ⌘− step, ⇧1 / ⇧2 fit everything / the + selection, all pivoting on the view centre. (⇧R, ⇧' / ⇧C / ⌘⌥\ and the + other canvas chords live in the action registry.) The action registry sends the + keyboard's here (⌘ chords claimed so the browser's own page zoom stays out + of it), and the desktop shell's View menu its menu items. */ useEffect( () => onViewCommand((command) => { diff --git a/src/components/ui/command.tsx b/src/components/ui/command.tsx new file mode 100644 index 000000000..61f2b892e --- /dev/null +++ b/src/components/ui/command.tsx @@ -0,0 +1,95 @@ +import * as React from 'react' +import { Command as CommandPrimitive } from 'cmdk' + +import { cn } from '@/lib/utils' +import { SearchIcon } from './icons' + +/* The command list behind the ⌘K palette: cmdk does the fuzzy filtering, + the highlight that follows the arrow keys and Enter; these parts dress it + in the palette's look (the search modal's 48px bar, rows the menus' size, + captions over groups). */ + +function Command({ className, ...props }: React.ComponentProps) { + return ( + + ) +} + +/** The palette's top line: a glyph and a bare field, closed by a hairline. */ +function CommandInput({ className, ...props }: React.ComponentProps) { + return ( +
+ + +
+ ) +} + +function CommandList({ className, ...props }: React.ComponentProps) { + return ( + + ) +} + +function CommandEmpty({ className, ...props }: React.ComponentProps) { + return ( + + ) +} + +/** Rows under a caption ("Arrange"). */ +function CommandGroup({ className, ...props }: React.ComponentProps) { + return ( + + ) +} + +function CommandItem({ className, ...props }: React.ComponentProps) { + return ( + + ) +} + +/** The chord at a row's end, in mono caption type. */ +function CommandShortcut({ className, ...props }: React.ComponentProps<'span'>) { + return ( + + ) +} + +export { Command, CommandInput, CommandList, CommandEmpty, CommandGroup, CommandItem, CommandShortcut } diff --git a/src/components/ui/context-menu.tsx b/src/components/ui/context-menu.tsx index 1fb5d2a70..e8e856e49 100644 --- a/src/components/ui/context-menu.tsx +++ b/src/components/ui/context-menu.tsx @@ -59,7 +59,7 @@ function ContextMenuSeparator({ className, ...props }: React.ComponentProps ) diff --git a/src/components/ui/dropdown-menu.tsx b/src/components/ui/dropdown-menu.tsx index 848bcb424..a58d61946 100644 --- a/src/components/ui/dropdown-menu.tsx +++ b/src/components/ui/dropdown-menu.tsx @@ -3,7 +3,7 @@ import * as DropdownMenuPrimitive from '@radix-ui/react-dropdown-menu' import { cva, type VariantProps } from 'class-variance-authority' import { cn } from '@/lib/utils' -import { CheckIcon } from './icons' +import { CheckIcon, ChevronRightIcon } from './icons' import { menuItemVariants } from './menu' /* A menu hanging off a button. Radix handles what the hand-rolled version @@ -129,7 +129,7 @@ function DropdownMenuSeparator({ className, ...props }: React.ComponentProps ) @@ -151,6 +151,64 @@ function DropdownMenuCaption({ className, ...props }: React.ComponentProps) { + return ( + + + + + {children} + + ) +} + +const DropdownMenuSub = DropdownMenuPrimitive.Sub + +/** A row opening a menu of its own beside it (File, Edit…), with a chevron. */ +function DropdownMenuSubTrigger({ + className, + children, + ...props +}: React.ComponentProps) { + return ( + + {children} + + + ) +} + +function DropdownMenuSubContent({ + className, + width, + ...props +}: React.ComponentProps & VariantProps) { + return ( + + + + ) +} + export { DropdownMenu, DropdownMenuTrigger, @@ -161,4 +219,8 @@ export { DropdownMenuCaption, DropdownMenuRadioGroup, DropdownMenuRadioItem, + DropdownMenuCheckboxItem, + DropdownMenuSub, + DropdownMenuSubTrigger, + DropdownMenuSubContent, } diff --git a/src/lib/actions/arrange.ts b/src/lib/actions/arrange.ts new file mode 100644 index 000000000..ac1b96f6f --- /dev/null +++ b/src/lib/actions/arrange.ts @@ -0,0 +1,175 @@ +/* The Arrange menu as geometry: align, distribute, tidy up and pack a set + of boxes. Pure — every function takes the boxes in their current order and + returns where each one's top-left goes, in the same order, so the caller + decides whether they are frames on the canvas or layers in a frame. */ + +export interface Box { + x: number + y: number + width: number + height: number +} + +export interface Spot { + x: number + y: number +} + +export type AlignEdge = 'left' | 'hcenter' | 'right' | 'top' | 'vcenter' | 'bottom' +export type Axis = 'x' | 'y' +export type DistributeEdge = 'start' | 'center' | 'end' + +/** The box around every box. */ +export function boundsOf(boxes: readonly Box[]): Box { + const left = Math.min(...boxes.map((b) => b.x)) + const top = Math.min(...boxes.map((b) => b.y)) + const right = Math.max(...boxes.map((b) => b.x + b.width)) + const bottom = Math.max(...boxes.map((b) => b.y + b.height)) + return { x: left, y: top, width: right - left, height: bottom - top } +} + +/** Each box lined up on one edge (or centre line) of the boxes' bounds. */ +export function alignBoxes(boxes: readonly Box[], edge: AlignEdge, within: Box = boundsOf(boxes)): Spot[] { + return boxes.map((b) => { + switch (edge) { + case 'left': + return { x: within.x, y: b.y } + case 'hcenter': + return { x: within.x + (within.width - b.width) / 2, y: b.y } + case 'right': + return { x: within.x + within.width - b.width, y: b.y } + case 'top': + return { x: b.x, y: within.y } + case 'vcenter': + return { x: b.x, y: within.y + (within.height - b.height) / 2 } + case 'bottom': + return { x: b.x, y: within.y + within.height - b.height } + } + }) +} + +const start = (b: Box, axis: Axis) => (axis === 'x' ? b.x : b.y) +const size = (b: Box, axis: Axis) => (axis === 'x' ? b.width : b.height) +const moved = (b: Box, axis: Axis, at: number): Spot => (axis === 'x' ? { x: at, y: b.y } : { x: b.x, y: at }) + +/** The indexes of the boxes from first to last along the axis. */ +function orderAlong(boxes: readonly Box[], axis: Axis): number[] { + return boxes.map((_, i) => i).sort((a, b) => start(boxes[a]!, axis) - start(boxes[b]!, axis) || a - b) +} + +/** Equal gaps between neighbours along the axis; the first and last stay put. */ +export function distributeSpacing(boxes: readonly Box[], axis: Axis): Spot[] { + const out: Spot[] = boxes.map((b) => ({ x: b.x, y: b.y })) + if (boxes.length < 3) return out + const order = orderAlong(boxes, axis) + const bounds = boundsOf(boxes) + const used = boxes.reduce((sum, b) => sum + size(b, axis), 0) + const gap = (size(bounds, axis) - used) / (boxes.length - 1) + let at = start(bounds, axis) + for (const i of order) { + const b = boxes[i]! + out[i] = moved(b, axis, at) + at += size(b, axis) + gap + } + return out +} + +/** The boxes' left edges (or centres, or right edges) evenly spaced along + * the axis; the first and last stay put. */ +export function distributeEdges(boxes: readonly Box[], axis: Axis, edge: DistributeEdge): Spot[] { + const out: Spot[] = boxes.map((b) => ({ x: b.x, y: b.y })) + if (boxes.length < 3) return out + const order = orderAlong(boxes, axis) + const anchor = (b: Box) => + start(b, axis) + (edge === 'start' ? 0 : edge === 'center' ? size(b, axis) / 2 : size(b, axis)) + const first = anchor(boxes[order[0]!]!) + const last = anchor(boxes[order[order.length - 1]!]!) + const step = (last - first) / (boxes.length - 1) + order.forEach((i, n) => { + const b = boxes[i]! + out[i] = moved(b, axis, start(b, axis) + first + step * n - anchor(b)) + }) + return out +} + +/** The boxes side by side with no gap, in their order along the axis, + * starting where the first one is. */ +export function packBoxes(boxes: readonly Box[], axis: Axis): Spot[] { + const out: Spot[] = boxes.map((b) => ({ x: b.x, y: b.y })) + const order = orderAlong(boxes, axis) + if (!order.length) return out + let at = start(boxes[order[0]!]!, axis) + for (const i of order) { + const b = boxes[i]! + out[i] = moved(b, axis, at) + at += size(b, axis) + } + return out +} + +/** Rows as a person reads them: boxes whose vertical middles fall inside a + * row's band join it, rows top to bottom, each row left to right. */ +function rowsOf(boxes: readonly Box[]): number[][] { + const order = boxes.map((_, i) => i).sort((a, b) => boxes[a]!.y - boxes[b]!.y || boxes[a]!.x - boxes[b]!.x) + const rows: { top: number; bottom: number; items: number[] }[] = [] + for (const i of order) { + const b = boxes[i]! + const middle = b.y + b.height / 2 + const row = rows.find((r) => middle >= r.top && middle <= r.bottom) + if (row) { + row.items.push(i) + row.bottom = Math.max(row.bottom, b.y + b.height) + } else rows.push({ top: b.y, bottom: b.y + b.height, items: [i] }) + } + return rows.map((r) => r.items.sort((a, b) => boxes[a]!.x - boxes[b]!.x)) +} + +/** The gap a tidy-up keeps: the average space between neighbours as they + * are (rounded), or `fallback` when they overlap. */ +function averageGap(boxes: readonly Box[], rows: number[][], fallback: number): number { + const gaps: number[] = [] + for (const row of rows) { + for (let n = 1; n < row.length; n++) { + const a = boxes[row[n - 1]!]! + const b = boxes[row[n]!]! + gaps.push(b.x - (a.x + a.width)) + } + } + for (let n = 1; n < rows.length; n++) { + const above = Math.max(...rows[n - 1]!.map((i) => boxes[i]!.y + boxes[i]!.height)) + const below = Math.min(...rows[n]!.map((i) => boxes[i]!.y)) + gaps.push(below - above) + } + const mean = gaps.length ? gaps.reduce((s, g) => s + g, 0) / gaps.length : fallback + return mean > 0 ? Math.round(mean) : fallback +} + +/** Tidy up: the boxes on a grid of as many columns as their widest + * row has, every column as wide as its widest box and every row as tall as + * its tallest, an even gap between, from the boxes' top-left corner. */ +export function tidyUp(boxes: readonly Box[], fallbackGap = 40): Spot[] { + const out: Spot[] = boxes.map((b) => ({ x: b.x, y: b.y })) + if (boxes.length < 2) return out + const rows = rowsOf(boxes) + const gap = averageGap(boxes, rows, fallbackGap) + const columns = Math.max(...rows.map((r) => r.length)) + const order = rows.flat() + const cell = (n: number) => boxes[order[n]!]! + const colWidth = Array.from({ length: columns }, (_, c) => + Math.max(0, ...order.map((_, n) => (n % columns === c ? cell(n).width : 0))), + ) + const rowCount = Math.ceil(order.length / columns) + const rowHeight = Array.from({ length: rowCount }, (_, r) => + Math.max(0, ...order.map((_, n) => (Math.floor(n / columns) === r ? cell(n).height : 0))), + ) + const origin = boundsOf(boxes) + order.forEach((i, n) => { + const c = n % columns + const r = Math.floor(n / columns) + out[i] = { + x: origin.x + colWidth.slice(0, c).reduce((s, w) => s + w + gap, 0), + y: origin.y + rowHeight.slice(0, r).reduce((s, h) => s + h + gap, 0), + } + }) + return out +} diff --git a/src/lib/actions/chords.ts b/src/lib/actions/chords.ts new file mode 100644 index 000000000..36f430b03 --- /dev/null +++ b/src/lib/actions/chords.ts @@ -0,0 +1,98 @@ +/* A keyboard chord, as the action registry binds it. `mod` is ⌘ on a Mac and + Ctrl elsewhere; `ctrl` is the Control key itself, which only a Mac tells + apart from `mod`. Chords with ⌥ or ⇧ on a digit or punctuation key name the + physical key by `code`, since macOS types another character for ⌥ chords + and ⇧1 is '!' on most layouts. */ + +export interface Chord { + /** `KeyboardEvent.key`, compared case-insensitively */ + key?: string + /** `KeyboardEvent.code`, the physical key */ + code?: string + mod?: boolean + shift?: boolean + alt?: boolean + ctrl?: boolean + /** bound on a Mac only: elsewhere the chord belongs to the system (⌃C is copy) */ + macOnly?: boolean + /** bound everywhere but a Mac, where the chord means something else (⌘Y is outlines there) */ + notMac?: boolean + /** acts from inside text fields too (⌘K, ⌘/) */ + global?: boolean +} + +type KeyInput = Pick + +export const IS_MAC = typeof navigator !== 'undefined' && /mac/i.test(navigator.platform) + +/** Whether the event is this chord, modifiers exactly. */ +export function matchesChord(e: KeyInput, chord: Chord, mac = IS_MAC): boolean { + if ((chord.macOnly && !mac) || (chord.notMac && mac)) return false + if (mac) { + if (e.metaKey !== !!chord.mod || e.ctrlKey !== !!chord.ctrl) return false + } else if ((e.ctrlKey || e.metaKey) !== (!!chord.mod || !!chord.ctrl)) { + /* off a Mac either key is the modifier, as the canvas always read it: + Ctrl for people, the Meta key for a keyboard (or a driver) that sends it */ + return false + } + if (e.altKey !== !!chord.alt || e.shiftKey !== !!chord.shift) return false + if (chord.code) return e.code === chord.code + return !!chord.key && e.key.toLowerCase() === chord.key.toLowerCase() +} + +const KEY_GLYPHS: Record = { + Backspace: '⌫', + Delete: '⌦', + Enter: '↩', + Escape: 'Esc', + ArrowUp: '↑', + ArrowDown: '↓', + ArrowLeft: '←', + ArrowRight: '→', + PageUp: 'PgUp', + PageDown: 'PgDn', + Home: 'Home', + End: 'End', + Tab: '⇥', + Slash: '/', + Backslash: '\\', + BracketLeft: '[', + BracketRight: ']', + Period: '.', + Comma: ',', + Quote: "'", + Equal: '+', + Minus: '−', +} + +/** The key's face: a letter upper-cased, a code turned back into its key. */ +function keyFace(chord: Chord): string { + if (chord.code) { + if (chord.code.startsWith('Key')) return chord.code.slice(3) + if (chord.code.startsWith('Digit')) return chord.code.slice(5) + return KEY_GLYPHS[chord.code] ?? chord.code + } + const key = chord.key ?? '' + if (key === '?') return '?' + return KEY_GLYPHS[key] ?? (key.length === 1 ? key.toUpperCase() : key) +} + +/** The chord as a menu shows it: ⌃⌥⇧⌘K on a Mac, Ctrl+Alt+Shift+K elsewhere. */ +export function chordHint(chord: Chord, mac = IS_MAC): string { + const face = keyFace(chord) + if (mac) { + return `${chord.ctrl ? '⌃' : ''}${chord.alt ? '⌥' : ''}${chord.shift ? '⇧' : ''}${chord.mod ? '⌘' : ''}${face}` + } + const parts = [chord.mod || chord.ctrl ? 'Ctrl' : '', chord.alt ? 'Alt' : '', chord.shift ? 'Shift' : '', face] + return parts.filter(Boolean).join('+') +} + +/** The first chord bound on this platform, for a hint; null when none is. */ +export function firstChord(chords: readonly Chord[] | undefined, mac = IS_MAC): Chord | null { + return chords?.find((c) => boundOn(c, mac)) ?? null +} + +/** Whether the chord is bound on this system at all. */ +export function boundOn(chord: Chord, mac = IS_MAC): boolean { + return mac ? !chord.notMac : !chord.macOnly +} diff --git a/src/lib/actions/edits.ts b/src/lib/actions/edits.ts new file mode 100644 index 000000000..4d8558cbe --- /dev/null +++ b/src/lib/actions/edits.ts @@ -0,0 +1,733 @@ +/* What the action registry's entries do to the canvas: the Object, + Arrange, Text and Edit commands carried over to frames on the page and to + the HTML layers inside them. Frames move through the frame API (one undo + step per command); layers change through the frame runtime's live style + and geometry edits, or as a rewrite of the frame's HTML. */ + +import type { Frame } from '../../../shared/types' +import { canvasPages } from '../../../shared/pages' +import { readingOrder } from '../../../shared/frameOrder' +import { normalizeRotation } from '../../../shared/frameRotation' +import { api } from '../api' +import { t } from '../i18n' +import { canEditOpenCanvas, pickedSelectors, useStore } from '../store' +import { currentPageCanvas } from '../pages' +import { recordUpdates, trackSave } from '../history' +import { isCanvasElement } from '../drawing' +import { + computedStyles, + editElementGeometry, + inspectElement, + styleElement, + type ElementInfo, + type GeometryEdit, + type StylePatch, +} from '../frameBridge' +import { + ancestorsOf, + buildLayerTree, + elementPath, + findLayer, + groupElements, + isElementHidden, + setElementsLink, + elementLink, + ungroupElements, + type LayerNode, +} from '../layers' +import { isLayerLocked, saveFrameHtml, setFramesHidden, setLayersHidden, standaloneSelector } from '../layerEdits' +import { + alignBoxes, + distributeEdges, + distributeSpacing, + packBoxes, + tidyUp, + type AlignEdge, + type Axis, + type Box, + type DistributeEdge, + type Spot, +} from './arrange' + +/* ---- what is selected ---- */ + +export interface Picked { + frame: Frame + selectors: string[] + /** the frame's one shape is picked: the pick is a page-level object */ + standalone: boolean +} + +/** The picked layers and their frame, or null with no element picked. */ +export function pickedLayers(): Picked | null { + const s = useStore.getState() + const picked = s.selectedElement + const frame = picked ? s.canvas?.frames.find((f) => f.id === picked.frameId) : undefined + if (!picked || !frame) return null + const selectors = pickedSelectors(s) + return { frame, selectors, standalone: selectors.length === 1 && standaloneSelector(frame) === selectors[0] } +} + +/** Layers inside a frame (not a standalone shape) are picked. */ +export function hasInnerPick(): boolean { + const p = pickedLayers() + return !!p && !p.standalone +} + +/** Frames on the page that are selected, when no layer inside one is. A + * standalone shape picked as its own layer counts as its frame. */ +export function selectedFrames(): Frame[] { + const s = useStore.getState() + const p = pickedLayers() + if (p && !p.standalone) return [] + const frames = currentPageCanvas()?.frames ?? [] + return frames.filter((f) => s.selectedIds.includes(f.id)) +} + +export const canEdit = () => canEditOpenCanvas(useStore.getState()) +const notice = (text: string) => useStore.getState().pushNotice(text) + +/* ---- frames: moved, turned, rounded as one undo step ---- */ + +type FramePatch = Partial> + +/** Patch several frames as one undo step and one save each. */ +export function patchFrames(changes: { frame: Frame; patch: FramePatch }[]) { + const real = changes.filter(({ frame, patch }) => + (Object.keys(patch) as (keyof FramePatch)[]).some((k) => frame[k] !== patch[k]), + ) + if (!real.length) return + recordUpdates( + real.map(({ frame, patch }) => { + const before: FramePatch = {} + for (const k of Object.keys(patch) as (keyof FramePatch)[]) before[k] = frame[k] as never + return { frameId: frame.id, before, after: patch } + }), + ) + const store = useStore.getState() + for (const { frame, patch } of real) store.patchFrameLocal(frame.id, patch) + trackSave( + Promise.all( + real.map(({ frame, patch }) => + /* a straight frame keeps no rotation, which JSON would drop: send 0 */ + api.updateFrame(frame.id, 'rotation' in patch ? { ...patch, rotation: patch.rotation ?? 0 } : patch), + ), + ).catch(console.error), + ) +} + +const boxOf = (f: Frame): Box => ({ x: f.x, y: f.y, width: f.width, height: f.height }) + +function arrangeFrames(frames: Frame[], place: (boxes: Box[]) => Spot[]): boolean { + const movable = frames.filter((f) => !f.locked) + if (movable.length < 2) return false + const spots = place(movable.map(boxOf)) + patchFrames(movable.map((frame, i) => ({ frame, patch: { x: Math.round(spots[i]!.x), y: Math.round(spots[i]!.y) } }))) + return true +} + +/* ---- layers: placed through the runtime's geometry edits ---- */ + +async function infosOf(frame: Frame, selectors: string[]) { + const infos = await Promise.all(selectors.map((selector) => inspectElement(frame.id, selector))) + return selectors + .map((selector, i) => ({ selector, info: infos[i] })) + .filter((x): x is { selector: string; info: ElementInfo } => !!x.info && x.info.geometry.enabled) +} + +/** Move each picked layer to where `place` puts its box, in frame px. */ +async function arrangeLayers(p: Picked, place: (boxes: Box[]) => Spot[], min = 2): Promise { + if (p.frame.locked) return false + const items = await infosOf(p.frame, p.selectors) + if (items.length < min) return false + const spots = place(items.map(({ info }) => info.rect)) + await Promise.all( + items.map(({ selector, info }, i) => { + const dx = spots[i]!.x - info.rect.x + const dy = spots[i]!.y - info.rect.y + if (Math.abs(dx) < 0.01 && Math.abs(dy) < 0.01) return null + /* `move` places the layer's box in frame px, the space the boxes were read in */ + return editElementGeometry(p.frame.id, selector, { kind: 'move', x: spots[i]!.x, y: spots[i]!.y }) + }), + ) + return true +} + +const ALIGN_GEOMETRY: Record = { + left: { axis: 'x', edge: 'start' }, + hcenter: { axis: 'x', edge: 'center' }, + right: { axis: 'x', edge: 'end' }, + top: { axis: 'y', edge: 'start' }, + vcenter: { axis: 'y', edge: 'center' }, + bottom: { axis: 'y', edge: 'end' }, +} + +/** ⌥A and friends: frames line up with each other; one layer lines up in + * its parent (as the Design panel's align buttons do), several with each + * other. */ +export function align(edge: AlignEdge): boolean { + const p = pickedLayers() + if (p && !p.standalone) { + if (p.selectors.length === 1) { + const { axis, edge: to } = ALIGN_GEOMETRY[edge] + void editElementGeometry(p.frame.id, p.selectors[0]!, { kind: 'align', axis, edge: to }) + return true + } + void arrangeLayers(p, (boxes) => alignBoxes(boxes, edge)) + return true + } + return arrangeFrames(selectedFrames(), (boxes) => alignBoxes(boxes, edge)) +} + +/** The selection, frames or layers, laid out by `place`; `min` is how many + * it takes for the command to mean anything. */ +function arrange(place: (boxes: Box[]) => Spot[], min: number): boolean { + const p = pickedLayers() + if (p && !p.standalone) { + if (p.selectors.length < min) return false + void arrangeLayers(p, place, min) + return true + } + const frames = selectedFrames() + return frames.length >= min && arrangeFrames(frames, place) +} + +export const distributeSpacingOf = (axis: Axis) => arrange((boxes) => distributeSpacing(boxes, axis), 3) +export const distributeEdgesOf = (axis: Axis, edge: DistributeEdge) => + arrange((boxes) => distributeEdges(boxes, axis, edge), 3) +export const tidy = () => arrange((boxes) => tidyUp(boxes), 2) +export const pack = (axis: Axis) => arrange((boxes) => packBoxes(boxes, axis), 2) + +/** Arrange commands need two (align, pack, tidy) or three (distribute) things selected. */ +export function arrangeCount(): number { + const p = pickedLayers() + if (p && !p.standalone) return p.selectors.length + return selectedFrames().length +} + +/** Round to pixel: the selected frames' position and size to whole pixels. */ +export function roundFramesToPixel(): boolean { + const frames = selectedFrames().filter((f) => !f.locked) + if (!frames.length) return false + patchFrames( + frames.map((frame) => ({ + frame, + patch: { + x: Math.round(frame.x), + y: Math.round(frame.y), + width: Math.max(1, Math.round(frame.width)), + height: Math.max(1, Math.round(frame.height)), + }, + })), + ) + return true +} + +/* ---- turning and flipping ---- */ + +/** Flip the picked layers (frames do not flip). */ +export function flip(axis: 'x' | 'y'): boolean { + const p = pickedLayers() + if (!p || p.frame.locked) return false + for (const selector of p.selectors) void editElementGeometry(p.frame.id, selector, { kind: 'flip', axis }) + return true +} + +/** Turn the picked layers, else the selected frames, by `by` degrees clockwise. */ +export function rotateBy(by: number): boolean { + const p = pickedLayers() + if (p && !p.standalone) { + if (p.frame.locked) return false + void infosOf(p.frame, p.selectors).then((items) => { + for (const { selector, info } of items) { + if (info.geometry.rotation === null) continue + const edit: GeometryEdit = { kind: 'rotate', value: info.geometry.rotation + by } + void editElementGeometry(p.frame.id, selector, edit) + } + }) + return true + } + const frames = selectedFrames().filter((f) => !f.locked) + if (!frames.length) return false + patchFrames(frames.map((frame) => ({ frame, patch: { rotation: normalizeRotation((frame.rotation ?? 0) + by) } }))) + return true +} + +/* ---- grouping and auto layout ---- */ + +function pickAfterRewrite(frame: Frame, selectors: string[]) { + const store = useStore.getState() + store.select(frame.id) + store.pickElements(frame.id, selectors) +} + +/** ⌘G (and ⌥⌘G, "Frame selection"): the picked layers wrapped in one box. */ +export function groupSelection(kind: 'group' | 'frame'): boolean { + const p = pickedLayers() + if (!p || p.standalone || p.frame.locked) return false + if (p.selectors.some((s) => isLayerLocked(p.frame, s))) return false + void groupKeepingLayout(p, kind === 'group' ? t('actions.groupName') : t('actions.frameName')) + return true +} + +/** The frame as it is now, when it is still the document the pick was made + * in; null (with a notice) when an edit landed meanwhile, since positional + * layer paths may then name other layers. */ +function unchangedFrame(picked: Frame): Frame | null { + const live = useStore.getState().canvas?.frames.find((f) => f.id === picked.id) + if (live && live.html === picked.html && !live.locked) return live + notice(t('actions.frameChanged')) + return null +} + +/* the body's path, as the runtime's cssPath writes it */ +const BODY_PATH = 'body:nth-of-type(1)' + +/* Where the layer at `selector` sits: the row holding it (null for a root + layer) and the rows beside it, itself included. Walked on the tree rather + than read off the selector, since a path anchored on an #id says nothing + about the elements above that id. Null when the selector is not a layer. */ +function placeOf(tree: LayerNode[], selector: string): { parent: LayerNode | null; siblings: LayerNode[] } | null { + const above = ancestorsOf(tree, selector) + if (!above) return null + const parent = above.at(-1) ?? null + return { parent, siblings: parent ? parent.children : tree } +} + +/** How a new box must lay out what it takes from `parent` so nothing moves: + * a flex parent's flow, carried onto the box (the box itself becomes one + * flex item); none for a parent in normal flow. Null for a grid, whose + * tracks a wrapper cannot keep. */ +async function inheritedLayout(frameId: string, parent: string): Promise { + const cs = await computedStyles(frameId, parent, [ + 'display', + 'flex-direction', + 'flex-wrap', + 'align-items', + 'justify-content', + 'row-gap', + 'column-gap', + ]) + if (!cs) return undefined + if (/grid/.test(cs.display ?? '')) return null + if (!/flex/.test(cs.display ?? '')) return undefined + return [ + 'display: flex', + `flex-direction: ${cs['flex-direction']}`, + `flex-wrap: ${cs['flex-wrap']}`, + `align-items: ${cs['align-items']}`, + `justify-content: ${cs['justify-content']}`, + `gap: ${cs['row-gap']} ${cs['column-gap']}`, + ].join('; ') +} + +async function groupKeepingLayout(p: Picked, name: string) { + /* a root layer's box is the body, which the tree does not list */ + const parent = placeOf(buildLayerTree(p.frame.html), p.selectors[0]!)?.parent + const style = await inheritedLayout(p.frame.id, parent?.selector ?? BODY_PATH) + if (style === null) { + notice(t('actions.groupGridFailed')) + return + } + /* the picked paths are positions: if the frame changed while its layout + was read, they may name other layers now */ + const live = unchangedFrame(p.frame) + if (!live) return + const grouped = groupElements(live.html, p.selectors, { name, style }) + if (!grouped) { + notice(t('actions.groupFailed')) + return + } + saveFrameHtml(live, grouped.html) + pickAfterRewrite(live, [grouped.selector]) +} + +/** ⇧⌘G / ⌘⌫: each picked box gives way to what it holds. */ +export function ungroupSelection(): boolean { + const p = pickedLayers() + if (!p || p.standalone || p.frame.locked) return false + const freed = ungroupElements(p.frame.html, p.selectors) + if (!freed) { + notice(t('actions.ungroupFailed')) + return true + } + saveFrameHtml(p.frame, freed.html) + pickAfterRewrite(p.frame, freed.selectors) + return true +} + +/** Which way a run of boxes goes, and the space between the first two: + * in auto layout that space is the gap, as auto layout reads it. */ +function flowOf(rects: Box[]): { direction: 'row' | 'column'; gap: number } { + const [a, b] = [...rects].sort((m, n) => m.y - n.y || m.x - n.x) + if (!a || !b) return { direction: 'column', gap: 0 } + const sideBySide = b.x >= a.x + a.width - 1 || a.x >= b.x + b.width - 1 + const space = sideBySide ? b.x - (a.x + a.width) : b.y - (a.y + a.height) + return { direction: sideBySide ? 'row' : 'column', gap: Math.max(0, Math.round(space)) } +} + +/* the margins along the flow, which a gap replaces: flex margins do not + collapse, so left on, they would add to the gap */ +const flowMargins = (direction: 'row' | 'column') => + direction === 'row' ? (['margin-left', 'margin-right'] as const) : (['margin-top', 'margin-bottom'] as const) + +const childSelectors = (frame: Frame, selector: string): string[] => + (findLayer(buildLayerTree(frame.html), selector)?.children ?? []).map((n: LayerNode) => n.selector) + +async function rectsOf(frameId: string, selectors: string[]): Promise { + const infos = await Promise.all(selectors.map((s) => inspectElement(frameId, s))) + return infos.flatMap((info) => (info ? [info.rect] : [])) +} + +/** ⇧A: a box holding layers becomes a flex container laid out the way its + * children already run; anything else (a leaf, several siblings, a box + * already in auto layout) is wrapped in a new auto layout box. The space + * between the layers becomes the gap and their margins along the flow go, + * so nothing moves. */ +export async function addAutoLayout(): Promise { + const p = pickedLayers() + if (!p || p.standalone || p.frame.locked) return false + const { frame, selectors } = p + if (selectors.length === 1) { + const selector = selectors[0]! + const children = childSelectors(frame, selector) + const info = await inspectElement(frame.id, selector) + if (info && children.length && !/flex|grid/.test(info.display)) { + const { direction, gap } = flowOf(await rectsOf(frame.id, children.slice(0, 2))) + const [lead, trail] = flowMargins(direction) + await styleElement(frame.id, selector, { display: 'flex', 'flex-direction': direction, gap: `${gap}px` }) + /* only the margins between children: the gap takes their place, and the + first child's leading and the last one's trailing margin stay */ + const last = children.length - 1 + await Promise.all( + children.map((child, i) => { + const patch: StylePatch = {} + if (i > 0) patch[lead] = '0px' + if (i < last) patch[trail] = '0px' + return Object.keys(patch).length ? styleElement(frame.id, child, patch) : null + }), + ) + return true + } + } + const { direction, gap } = flowOf(await rectsOf(frame.id, selectors)) + const [lead, trail] = flowMargins(direction) + /* the run's outer margins move onto the new box, which takes its place */ + const first = selectors[0]! + const last = selectors[selectors.length - 1]! + const [outerLead, outerTrail] = await Promise.all([ + computedStyles(frame.id, first, [lead]), + computedStyles(frame.id, last, [trail]), + ]) + const live = unchangedFrame(frame) + if (!live) return true + const grouped = groupElements(live.html, selectors, { + name: t('actions.frameName'), + style: [ + `display: flex; flex-direction: ${direction}; gap: ${gap}px`, + outerLead?.[lead] ? `${lead}: ${outerLead[lead]}` : '', + outerTrail?.[trail] ? `${trail}: ${outerTrail[trail]}` : '', + ] + .filter(Boolean) + .join('; '), + childStyle: { [lead]: '0px', [trail]: '0px' }, + }) + if (!grouped) { + notice(t('actions.groupFailed')) + return true + } + saveFrameHtml(live, grouped.html) + pickAfterRewrite(live, [grouped.selector]) + return true +} + +/** ⌥⇧A: the picked boxes stop being flex containers. */ +export function removeAutoLayout(): boolean { + /* an explicit display, since a class may be what makes the box flex */ + return styleEach((info) => + /flex|grid/.test(info.display) + ? { display: info.display.startsWith('inline') ? 'inline-block' : 'block', 'flex-direction': null, gap: null } + : null, + ) +} + +/* ---- styles on the picked layers ---- */ + +/** The same inline styles on every picked layer, saved as one edit. */ +export function styleEach(styles: StylePatch | ((info: ElementInfo) => StylePatch | null)): boolean { + const p = pickedLayers() + if (!p || p.frame.locked) return false + for (const selector of p.selectors) { + if (typeof styles !== 'function') { + void styleElement(p.frame.id, selector, styles) + continue + } + void inspectElement(p.frame.id, selector).then((info) => { + const patch = info && styles(info) + if (patch) void styleElement(p.frame.id, selector, patch) + }) + } + return true +} + +/** ⌥/: no background on the picked layers. */ +export const removeFill = () => styleEach({ 'background-color': 'transparent', 'background-image': 'none' }) + +/** Text alignment, case and size on the picked layers. */ +export const textAlign = (value: 'left' | 'center' | 'right' | 'justify') => styleEach({ 'text-align': value }) +export const textCase = (value: 'uppercase' | 'lowercase' | 'capitalize' | 'none') => + styleEach({ 'text-transform': value === 'none' ? null : value }) +export const fontSizeBy = (step: number) => + styleEach((info) => (info.fontSize ? { 'font-size': `${Math.max(1, info.fontSize + step)}px` } : null)) + +/* ---- copy and paste properties: what a layer looks like, never where it is ---- */ + +const VISUAL_PROPERTIES = [ + 'background-color', + 'background-image', + 'background-size', + 'background-position', + 'background-repeat', + 'border-top-width', + 'border-right-width', + 'border-bottom-width', + 'border-left-width', + 'border-top-style', + 'border-right-style', + 'border-bottom-style', + 'border-left-style', + 'border-top-color', + 'border-right-color', + 'border-bottom-color', + 'border-left-color', + 'border-top-left-radius', + 'border-top-right-radius', + 'border-bottom-right-radius', + 'border-bottom-left-radius', + 'box-shadow', + 'opacity', + 'filter', + 'backdrop-filter', + 'mix-blend-mode', +] as const + +const TEXT_PROPERTIES = [ + 'color', + 'font-family', + 'font-size', + 'font-weight', + 'font-style', + 'line-height', + 'letter-spacing', + 'text-transform', + 'text-decoration-line', + 'text-align', +] as const + +const STYLE_CLIP_KEY = 'doop:style-clip' + +interface StyleClip { + visual: Record + /** only a layer with text of its own lends its type: on a box the same + * properties would cascade into every child */ + text: Record | null +} + +/** ⌥⌘C: the primary picked layer's look onto the style clipboard. */ +export async function copyProperties(): Promise { + const s = useStore.getState() + const picked = s.selectedElement + if (!picked) return false + const [visual, info] = await Promise.all([ + computedStyles(picked.frameId, picked.selector, [...VISUAL_PROPERTIES, ...TEXT_PROPERTIES]), + inspectElement(picked.frameId, picked.selector), + ]) + if (!visual || !info) return false + const text = info.hasText ? Object.fromEntries(TEXT_PROPERTIES.map((k) => [k, visual[k] ?? ''])) : null + const clip: StyleClip = { visual: Object.fromEntries(VISUAL_PROPERTIES.map((k) => [k, visual[k] ?? ''])), text } + try { + localStorage.setItem(STYLE_CLIP_KEY, JSON.stringify(clip)) + } catch { + return false + } + notice(t('actions.propertiesCopied')) + return true +} + +function styleClip(): StyleClip | null { + try { + const parsed: unknown = JSON.parse(localStorage.getItem(STYLE_CLIP_KEY) ?? 'null') + return parsed && typeof parsed === 'object' && 'visual' in parsed ? (parsed as StyleClip) : null + } catch { + return null + } +} + +export const hasStyleClip = () => !!styleClip() + +/** ⌥⌘V: the copied look onto every picked layer, type only onto text. */ +export function pasteProperties(): boolean { + const clip = styleClip() + if (!clip) return false + return styleEach((info) => ({ ...clip.visual, ...(clip.text && info.hasText ? clip.text : {}) })) +} + +/* ---- pick a colour from anywhere on screen ---- */ + +type EyeDropperCtor = new () => { open(): Promise<{ sRGBHex: string }> } + +export const canPickColor = () => typeof (window as { EyeDropper?: EyeDropperCtor }).EyeDropper === 'function' + +/** ⌃C: the eyedropper. The colour fills the picked layers (text layers take + * it as their ink) and lands on the clipboard either way. */ +export async function pickColor(): Promise { + const Dropper = (window as { EyeDropper?: EyeDropperCtor }).EyeDropper + if (!Dropper) return + let hex: string + try { + hex = (await new Dropper().open()).sRGBHex + } catch { + return // Esc + } + void navigator.clipboard?.writeText(hex).catch(() => {}) + if (canEdit() && pickedLayers()) { + styleEach((info): StylePatch => (info.hasText ? { color: hex } : { 'background-color': hex })) + } else notice(t('actions.colorCopied', { color: hex })) +} + +/* ---- links ---- */ + +/** The primary picked layer's link target, if it is, holds or sits in one. */ +export function pickedLink(): string | null { + const p = pickedLayers() + if (!p) return null + return elementLink(p.frame.html, p.selectors[p.selectors.length - 1]!) +} + +/** ⇧⌘U: link the picked layers to `href`, or unlink them with null. */ +export function linkSelection(href: string | null): boolean { + const p = pickedLayers() + if (!p || p.frame.locked) return false + const open = p.selectors.filter((selector) => !isLayerLocked(p.frame, selector)) + const linked = setElementsLink(p.frame.html, open, href) + if (!linked) return false + saveFrameHtml(p.frame, linked.html) + pickAfterRewrite(p.frame, linked.selectors) + return true +} + +/* ---- selecting ---- */ + +/** ⇧⌘A: everything beside the selection instead of it — the picked layers' + * other siblings, or the page's other frames. */ +export function selectInverse(): boolean { + const s = useStore.getState() + const p = pickedLayers() + if (p && !p.standalone) { + const primary = s.selectedElement!.selector + const place = placeOf(buildLayerTree(p.frame.html), primary) + if (!place) return false + const others = place.siblings.filter((n) => !n.locked && !p.selectors.includes(n.selector)).map((n) => n.selector) + /* everything was picked: its inverse is nothing */ + if (!others.length) s.select(null) + else s.pickElements(p.frame.id, others) + return true + } + const frames = currentPageCanvas()?.frames ?? [] + const others = frames.filter((f) => !s.selectedIds.includes(f.id) && !f.locked).map((f) => f.id) + s.pickElement(null) + if (!others.length) s.select(null) + else s.selectMany(others) + return true +} + +/** ⌥⌘A: every layer in the frame shaped like the picked one: the same tag + * and the same classes. */ +export function selectMatching(): boolean { + const s = useStore.getState() + const p = pickedLayers() + if (!p || p.standalone) return false + const doc = new DOMParser().parseFromString(p.frame.html, 'text/html') + let el: Element | null = null + try { + el = doc.querySelector(s.selectedElement!.selector) + } catch { + return false + } + if (!el) return false + const classes = (el.getAttribute('class') ?? '').trim().split(/\s+/).filter(Boolean).sort().join(' ') + const matches = [...doc.body.getElementsByTagName(el.tagName)].filter( + (m) => (m.getAttribute('class') ?? '').trim().split(/\s+/).filter(Boolean).sort().join(' ') === classes, + ) + if (matches.length < 2) return false + s.pickElements(p.frame.id, [...matches.filter((m) => m !== el).map(elementPath), s.selectedElement!.selector]) + return true +} + +/** Hide other layers: the picked layers' siblings, or the page's other frames. */ +export function hideOthers(): boolean { + const s = useStore.getState() + const p = pickedLayers() + if (p && !p.standalone) { + const place = placeOf(buildLayerTree(p.frame.html), s.selectedElement!.selector) + if (!place) return false + const others = place.siblings + .filter((n) => !p.selectors.includes(n.selector) && isElementHidden(p.frame.html, n.selector) === false) + .map((n) => n.selector) + return others.length > 0 && setLayersHidden(p.frame, others, true) + } + const frames = currentPageCanvas()?.frames ?? [] + const others = frames.filter((f) => !s.selectedIds.includes(f.id) && !f.hidden) + if (!others.length || !s.selectedIds.length) return false + setFramesHidden(others, true) + return true +} + +/* ---- moving around the canvas ---- */ + +/** The page's frames as a person reads them, top-level shapes left out. */ +function framesInOrder(): Frame[] { + const frames = (currentPageCanvas()?.frames ?? []).filter((f) => !f.hidden && !isCanvasElement(f.html)) + return readingOrder(frames) +} + +/** N / ⇧N (zoom to it) and End / Home (only bring it into view): the next or + * previous frame after the selected one, in reading order. */ +export function stepFrame(dir: 1 | -1, zoom: boolean): boolean { + const s = useStore.getState() + const frames = framesInOrder() + if (!frames.length) return false + const at = frames.findIndex((f) => f.id === s.selectedId) + const next = frames[at === -1 ? (dir === 1 ? 0 : frames.length - 1) : (at + dir + frames.length) % frames.length]! + s.select(next.id) + s.pickElement(null) + if (zoom) s.requestFlyTo(next.id) + else s.requestFlyToPoint(next.x + next.width / 2, next.y + next.height / 2) + return true +} + +/** PgUp / PgDn: the previous or next page. */ +export function stepPage(dir: 1 | -1): boolean { + const s = useStore.getState() + if (!s.canvas) return false + const pages = canvasPages(s.canvas) + if (pages.length < 2) return false + const at = Math.max( + 0, + pages.findIndex((p) => p.id === s.activePageId), + ) + const next = pages[at + dir] + if (!next) return false + s.setActivePage(next.id) + return true +} + +/** Rewrite several frames' HTML as one undo step (replace all). */ +export function saveFramesHtml(changes: { frame: Frame; html: string }[]) { + const real = changes.filter(({ frame, html }) => !frame.locked && frame.html !== html) + if (!real.length) return + recordUpdates(real.map(({ frame, html }) => ({ frameId: frame.id, before: { html: frame.html }, after: { html } }))) + const store = useStore.getState() + for (const { frame, html } of real) store.patchFrameLocal(frame.id, { html }) + trackSave(Promise.all(real.map(({ frame, html }) => api.updateFrame(frame.id, { html }))).catch(console.error)) +} diff --git a/src/lib/actions/findText.ts b/src/lib/actions/findText.ts new file mode 100644 index 000000000..222f93ec1 --- /dev/null +++ b/src/lib/actions/findText.ts @@ -0,0 +1,116 @@ +/* Find and replace over frame HTML: the text a person reads, never markup, + scripts or styles. A match lives inside one text node (as a browser's own + find does it across a styled run, it is two matches here, which is what a + replace can change safely). Pure: HTML in, matches or HTML out. */ + +import { elementPath, LOCK_ATTR } from '../layers' + +const SKIPPED = new Set(['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEMPLATE', 'TITLE', 'TEXTAREA']) + +export interface FindOptions { + matchCase?: boolean +} + +export interface TextMatch { + /** the element whose text holds the match, as the Layers panel paths it */ + selector: string + /** the text around the match, for the results list */ + before: string + text: string + after: string + /** inside a locked layer: found, never replaced */ + locked: boolean +} + +function parse(html: string): Document { + return new DOMParser().parseFromString(html, 'text/html') +} + +function textNodes(doc: Document): Text[] { + const out: Text[] = [] + const walker = doc.createTreeWalker(doc.body, NodeFilter.SHOW_TEXT, { + acceptNode: (node) => { + for (let el = node.parentElement; el; el = el.parentElement) { + if (SKIPPED.has(el.tagName)) return NodeFilter.FILTER_REJECT + } + return NodeFilter.FILTER_ACCEPT + }, + }) + for (let n = walker.nextNode(); n; n = walker.nextNode()) out.push(n as Text) + return out +} + +/* a locked layer, and everything inside it, takes no edits */ +const isLocked = (node: Text) => !!node.parentElement?.closest(`[${LOCK_ATTR}]`) + +/** Every match of `query` in `text`, left to right, never overlapping, as + * offsets and lengths in `text` itself. Matched by a case-insensitive + * regular expression rather than by lower-casing both sides: lower-casing + * can change a string's length (İ becomes i plus a dot), which would shift + * every offset after it. */ +function matchesIn(text: string, query: string, matchCase: boolean): { at: number; length: number }[] { + if (!query) return [] + const escaped = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + const pattern = new RegExp(escaped, matchCase ? 'gu' : 'giu') + return [...text.matchAll(pattern)].map((m) => ({ at: m.index, length: m[0].length })) +} + +const CONTEXT = 24 + +/** Every match of `query` in the frame's text, in reading order. */ +export function findInHtml(html: string, query: string, { matchCase = false }: FindOptions = {}): TextMatch[] { + if (!query.trim()) return [] + const out: TextMatch[] = [] + for (const node of textNodes(parse(html))) { + const text = node.data + const parent = node.parentElement + if (!parent) continue + for (const { at, length } of matchesIn(text, query, matchCase)) { + out.push({ + selector: elementPath(parent), + before: text.slice(Math.max(0, at - CONTEXT), at).trimStart(), + text: text.slice(at, at + length), + after: text.slice(at + length, at + length + CONTEXT).trimEnd(), + locked: isLocked(node), + }) + } + } + return out +} + +/** The frame's HTML with `query` replaced: every match, or only the + * `only`-th (0-based, in the order `findInHtml` lists them). Matches in + * locked layers are counted, so the numbering agrees with the search, and + * left as they are. Null when nothing was replaced. */ +export function replaceInHtml( + html: string, + query: string, + replacement: string, + { matchCase = false, only }: FindOptions & { only?: number } = {}, +): { html: string; count: number } | null { + if (!query.trim()) return null + const doc = parse(html) + let seen = 0 + let count = 0 + for (const node of textNodes(doc)) { + const offsets = matchesIn(node.data, query, matchCase) + if (!offsets.length) continue + /* right to left, so the earlier offsets still hold after each swap */ + const picked = offsets + .map(({ at, length }, i) => ({ at, length, n: seen + i })) + .filter(({ n }) => only === undefined || n === only) + .reverse() + seen += offsets.length + if (isLocked(node)) { + if (only !== undefined && seen > only) break + continue + } + for (const { at, length } of picked) { + node.replaceData(at, length, replacement) + count++ + } + if (only !== undefined && seen > only) break + } + if (!count) return null + return { html: '\n' + doc.documentElement.outerHTML, count } +} diff --git a/src/lib/actions/registry.ts b/src/lib/actions/registry.ts new file mode 100644 index 000000000..0e754f9e6 --- /dev/null +++ b/src/lib/actions/registry.ts @@ -0,0 +1,1085 @@ +/* Every command the canvas editor offers, in one list: the keyboard handler, + the ⌘K palette, the main menu and the shortcuts sheet all read it, so a + command, its name and its chord are written once. The canvas page lends + the registry what only it holds (its modals and panels) as the host. */ + +import type { PlainMessageKey } from '../i18n' +import { useStore } from '../store' +import { currentPageCanvas } from '../pages' +import { readingOrder } from '../../../shared/frameOrder' +import { redo, undo } from '../history' +import { runViewCommand } from '../viewMenu' +import { downloadFramesPdf } from '../frameExport' +import { duplicateFrames, hasFrameClip, pasteFramesOver, replaceFramesWithClip } from '../frameClipboard' +import { hasElementClip, pasteLayer, replaceWithClip } from '../elementClipboard' +import { + deleteSelection, + duplicateLayers, + formatSelectionText, + toggleLockSelection, + toggleSelectionHidden, +} from '../layerEdits' +import { reorderSelection, selectAll } from '../selectionKeys' +import type { Chord } from './chords' +import { IS_MAC, matchesChord } from './chords' +import { + addAutoLayout, + align, + arrangeCount, + canEdit, + canPickColor, + copyProperties, + distributeEdgesOf, + distributeSpacingOf, + flip, + fontSizeBy, + groupSelection, + hasInnerPick, + hasStyleClip, + hideOthers, + pack, + pasteProperties, + pickColor, + pickedLayers, + removeAutoLayout, + removeFill, + rotateBy, + roundFramesToPixel, + selectedFrames, + selectInverse, + selectMatching, + stepFrame, + stepPage, + textAlign, + textCase, + tidy, + ungroupSelection, +} from './edits' + +/** What the canvas page lends the registry: its own modals and panels. */ +export interface ActionHost { + canvasId: string + /** a person looking at the canvas, not an editor's account */ + guest: boolean + presenting: boolean + /** ⌘. has something to hide here (the canvas, not the board) */ + hideUiActive: boolean + agentsOpen: boolean + openPalette(): void + openAgent(): void + openShortcuts(): void + openFind(mode: 'find' | 'replace'): void + findStep(dir: 1 | -1): void + openExport(): void + openImport(): void + openVersionHistory(): void + openLink(): void + placeImage(): void + newCanvas(): void + duplicateCanvas(): void + present(): void + toggleHideUi(): void + toggleAgents(): void +} + +let host: ActionHost | null = null +const hostListeners = new Set<() => void>() + +/** The canvas page installs itself as the host while it is mounted. */ +export function setActionHost(next: ActionHost | null) { + host = next + for (const listener of hostListeners) listener() +} + +/** Called whenever the host is installed, replaced or removed (the desktop + * menu bar re-reads what is enabled then); returns the unsubscribe. */ +export function onActionHostChange(listener: () => void): () => void { + hostListeners.add(listener) + return () => hostListeners.delete(listener) +} + +export type MenuId = 'general' | 'file' | 'edit' | 'view' | 'object' | 'text' | 'arrange' | 'help' + +export const MENUS: { id: Exclude; label: PlainMessageKey }[] = [ + { id: 'file', label: 'actions.menuFile' }, + { id: 'edit', label: 'actions.menuEdit' }, + { id: 'view', label: 'actions.menuView' }, + { id: 'object', label: 'actions.menuObject' }, + { id: 'text', label: 'actions.menuText' }, + { id: 'arrange', label: 'actions.menuArrange' }, + { id: 'help', label: 'actions.menuHelp' }, +] + +export interface CanvasAction { + id: string + label: PlainMessageKey + menu: MenuId + /** rows sharing a section number sit between the same separators */ + section: number + /** the first chord bound on this platform is the one menus show */ + keys?: readonly Chord[] + /** changes the canvas: only an editor may run it */ + edit?: boolean + /** the chords are shown, but another handler owns them (⌫ and Esc, which + * the canvas page claims with rules of their own) */ + hintOnly?: boolean + enabled?: () => boolean + /** a toggle's state, for the check a menu row wears */ + checked?: () => boolean + /** false when there was nothing to act on: the key is left to the browser */ + run: () => boolean | void +} + +const store = () => useStore.getState() +const h = () => host +const hasSelection = () => store().selectedIds.length > 0 || !!store().selectedElement +const picked = () => !!pickedLayers() +const editing = () => canEdit() +const pasteable = () => hasFrameClip() || hasElementClip() + +/* the frames a PDF export takes: the selection, else the whole page, in reading order */ +function pdfFrames() { + const selected = selectedFrames() + return selected.length ? selected : readingOrder(currentPageCanvas()?.frames ?? []) +} + +function pasteOver(): boolean { + const p = pickedLayers() + if (p && hasElementClip()) return pasteLayer(p.frame, p.selectors[p.selectors.length - 1] ?? null) + const frames = selectedFrames() + const canvasId = h()?.canvasId + return !!canvasId && hasFrameClip() && pasteFramesOver(canvasId, frames) +} + +function pasteReplace(): boolean { + const p = pickedLayers() + if (p && !p.standalone && hasElementClip()) return replaceWithClip(p.frame, p.selectors) + const frames = selectedFrames() + const canvasId = h()?.canvasId + return !!canvasId && hasFrameClip() && frames.length > 0 && replaceFramesWithClip(canvasId, frames) +} + +function duplicate(): boolean { + const p = pickedLayers() + if (p) { + duplicateLayers(p.frame, p.selectors) + return true + } + const frames = selectedFrames() + if (!frames.length) return false + duplicateFrames(frames) + return true +} + +const mod = (key: string, extra: Partial = {}): Chord => ({ key, mod: true, ...extra }) +const code = (c: string, extra: Partial = {}): Chord => ({ code: c, ...extra }) + +export const ACTIONS: readonly CanvasAction[] = [ + /* ---- the palette's own line and the agent ---- */ + { + id: 'palette', + label: 'actions.palette', + menu: 'general', + section: 0, + keys: [mod('k', { global: true })], + run: () => h()?.openPalette(), + }, + { + id: 'ask-agent', + label: 'actions.askAgent', + menu: 'general', + section: 0, + keys: [mod('/', { global: true }), { key: '/' }], + enabled: () => !h()?.guest && editing(), + run: () => h()?.openAgent(), + }, + + /* ---- File ---- */ + { + id: 'new-canvas', + label: 'actions.newCanvas', + menu: 'file', + section: 0, + enabled: () => !h()?.guest, + run: () => h()?.newCanvas(), + }, + { + id: 'duplicate-canvas', + label: 'actions.duplicateCanvas', + menu: 'file', + section: 0, + enabled: () => !h()?.guest, + run: () => h()?.duplicateCanvas(), + }, + { + id: 'place-image', + label: 'actions.placeImage', + menu: 'file', + section: 1, + keys: [mod('k', { shift: true })], + edit: true, + run: () => h()?.placeImage(), + }, + { + id: 'import', + label: 'actions.import', + menu: 'file', + section: 1, + edit: true, + enabled: () => !h()?.guest, + run: () => h()?.openImport(), + }, + { + id: 'version-history', + label: 'actions.versionHistory', + menu: 'file', + section: 2, + enabled: () => store().selectedIds.length === 1, + run: () => h()?.openVersionHistory(), + }, + { + id: 'export', + label: 'actions.export', + menu: 'file', + section: 3, + keys: [mod('e', { shift: true })], + run: () => h()?.openExport(), + }, + { + id: 'export-pdf', + label: 'actions.exportPdf', + menu: 'file', + section: 3, + enabled: () => pdfFrames().length > 0, + run: () => { + const canvasId = h()?.canvasId + if (canvasId) void downloadFramesPdf(canvasId, pdfFrames()) + }, + }, + + /* ---- Edit ---- */ + { id: 'undo', label: 'actions.undo', menu: 'edit', section: 0, keys: [mod('z')], edit: true, run: () => void undo() }, + { + id: 'redo', + label: 'actions.redo', + menu: 'edit', + section: 0, + keys: [mod('z', { shift: true }), mod('y', { notMac: true })], + edit: true, + run: () => void redo(), + }, + { + id: 'paste-over', + label: 'actions.pasteOver', + menu: 'edit', + section: 1, + keys: [mod('v', { shift: true })], + edit: true, + enabled: () => pasteable() && hasSelection(), + run: pasteOver, + }, + { + id: 'paste-replace', + label: 'actions.pasteReplace', + menu: 'edit', + section: 1, + keys: [mod('r', { shift: true })], + edit: true, + enabled: () => pasteable() && hasSelection(), + run: pasteReplace, + }, + { + id: 'duplicate', + label: 'actions.duplicate', + menu: 'edit', + section: 1, + keys: [mod('d')], + edit: true, + enabled: hasSelection, + run: duplicate, + }, + { + id: 'delete', + label: 'actions.delete', + menu: 'edit', + section: 1, + keys: [{ key: 'Backspace' }, { key: 'Delete' }], + hintOnly: true, + edit: true, + enabled: hasSelection, + run: () => deleteSelection(), + }, + { id: 'find', label: 'actions.find', menu: 'edit', section: 2, keys: [mod('f')], run: () => h()?.openFind('find') }, + { id: 'find-next', label: 'actions.findNext', menu: 'edit', section: 2, run: () => h()?.findStep(1) }, + { id: 'find-previous', label: 'actions.findPrevious', menu: 'edit', section: 2, run: () => h()?.findStep(-1) }, + { + id: 'find-replace', + label: 'actions.findReplace', + menu: 'edit', + section: 2, + keys: [mod('f', { alt: true, code: 'KeyF' })], + edit: true, + run: () => h()?.openFind('replace'), + }, + { + id: 'copy-properties', + label: 'actions.copyProperties', + menu: 'edit', + section: 3, + keys: [mod('c', { alt: true, code: 'KeyC' })], + enabled: picked, + run: () => void copyProperties(), + }, + { + id: 'paste-properties', + label: 'actions.pasteProperties', + menu: 'edit', + section: 3, + keys: [mod('v', { alt: true, code: 'KeyV' })], + edit: true, + enabled: () => picked() && hasStyleClip(), + run: pasteProperties, + }, + { + id: 'pick-color', + label: 'actions.pickColor', + menu: 'edit', + section: 4, + keys: [{ key: 'c', ctrl: true, macOnly: true }], + enabled: canPickColor, + run: () => void pickColor(), + }, + { + id: 'select-all', + label: 'actions.selectAll', + menu: 'edit', + section: 5, + keys: [mod('a')], + /* claimed even when everything is already selected: left to the browser, + a second ⌘A would select the editor's own text and controls */ + run: () => void selectAll(), + }, + { + id: 'select-none', + label: 'actions.selectNone', + menu: 'edit', + section: 5, + keys: [{ key: 'Escape' }], + hintOnly: true, + enabled: hasSelection, + run: () => { + store().select(null) + }, + }, + { + id: 'select-inverse', + label: 'actions.selectInverse', + menu: 'edit', + section: 5, + keys: [mod('a', { shift: true })], + run: selectInverse, + }, + { + id: 'select-matching', + label: 'actions.selectMatching', + menu: 'edit', + section: 5, + keys: [mod('a', { alt: true, code: 'KeyA' })], + enabled: hasInnerPick, + run: selectMatching, + }, + + /* ---- View ---- */ + { + id: 'rulers', + label: 'actions.rulers', + menu: 'view', + section: 0, + keys: [{ key: 'r', shift: true }], + checked: () => store().rulers, + run: () => store().toggleRulers(), + }, + { + id: 'pixel-grid', + label: 'actions.pixelGrid', + menu: 'view', + section: 0, + keys: [{ code: 'Quote', shift: true }], + checked: () => store().viewOptions.pixelGrid, + run: () => store().toggleViewOption('pixelGrid'), + }, + { + id: 'comments', + label: 'actions.comments', + menu: 'view', + section: 0, + keys: [{ key: 'c', shift: true }], + checked: () => store().viewOptions.comments, + run: () => store().toggleViewOption('comments'), + }, + { + id: 'outlines', + label: 'actions.outlines', + menu: 'view', + section: 0, + keys: [mod('y', { macOnly: true })], + checked: () => store().outlines, + run: () => store().toggleOutlines(), + }, + { + id: 'ui', + label: 'actions.showUi', + menu: 'view', + section: 1, + keys: [mod('.'), mod('\\', { code: 'Backslash' })], + enabled: () => !!h()?.hideUiActive, + checked: () => !store().uiHidden, + run: () => h()?.toggleHideUi(), + }, + { + id: 'cursors', + label: 'actions.cursors', + menu: 'view', + section: 1, + keys: [mod('\\', { alt: true, code: 'Backslash' })], + checked: () => store().viewOptions.cursors, + run: () => store().toggleViewOption('cursors'), + }, + { + id: 'layers-panel', + label: 'actions.layersPanel', + menu: 'view', + section: 1, + checked: () => store().layersOpen, + run: () => store().setLayersOpen(!store().layersOpen), + }, + { + id: 'agents-panel', + label: 'actions.agentsPanel', + menu: 'view', + section: 1, + enabled: () => !h()?.guest, + checked: () => !!h()?.agentsOpen, + run: () => h()?.toggleAgents(), + }, + { + id: 'zoom-in', + label: 'actions.zoomIn', + menu: 'view', + section: 2, + keys: [mod('='), mod('+', { shift: true }), mod('+')], + run: () => runViewCommand('zoom-in'), + }, + { + id: 'zoom-out', + label: 'actions.zoomOut', + menu: 'view', + section: 2, + keys: [mod('-')], + run: () => runViewCommand('zoom-out'), + }, + { + id: 'zoom-reset', + label: 'actions.zoom100', + menu: 'view', + section: 2, + keys: [mod('0')], + run: () => runViewCommand('zoom-reset'), + }, + { + id: 'zoom-fit', + label: 'actions.zoomFit', + menu: 'view', + section: 2, + keys: [code('Digit1', { shift: true })], + run: () => runViewCommand('zoom-fit'), + }, + { + id: 'zoom-selection', + label: 'actions.zoomSelection', + menu: 'view', + section: 2, + keys: [code('Digit2', { shift: true })], + enabled: hasSelection, + run: () => runViewCommand('zoom-selection'), + }, + { + id: 'previous-page', + label: 'actions.previousPage', + menu: 'view', + section: 3, + keys: [{ key: 'PageUp' }], + run: () => stepPage(-1), + }, + { + id: 'next-page', + label: 'actions.nextPage', + menu: 'view', + section: 3, + keys: [{ key: 'PageDown' }], + run: () => stepPage(1), + }, + { + id: 'zoom-previous-frame', + label: 'actions.zoomPreviousFrame', + menu: 'view', + section: 3, + keys: [{ key: 'n', shift: true }], + run: () => stepFrame(-1, true), + }, + { + id: 'zoom-next-frame', + label: 'actions.zoomNextFrame', + menu: 'view', + section: 3, + keys: [{ key: 'n' }], + run: () => stepFrame(1, true), + }, + { + id: 'find-previous-frame', + label: 'actions.findPreviousFrame', + menu: 'view', + section: 3, + keys: [{ key: 'Home' }], + run: () => stepFrame(-1, false), + }, + { + id: 'find-next-frame', + label: 'actions.findNextFrame', + menu: 'view', + section: 3, + keys: [{ key: 'End' }], + run: () => stepFrame(1, false), + }, + { + id: 'present', + label: 'actions.present', + menu: 'view', + section: 4, + keys: [mod('Enter', { alt: true })], + run: () => h()?.present(), + }, + + /* ---- Object ---- */ + { + id: 'frame-selection', + label: 'actions.frameSelection', + menu: 'object', + section: 0, + keys: [mod('g', { alt: true, code: 'KeyG' })], + edit: true, + enabled: hasInnerPick, + run: () => groupSelection('frame'), + }, + { + id: 'group', + label: 'actions.group', + menu: 'object', + section: 0, + keys: [mod('g')], + edit: true, + enabled: hasInnerPick, + run: () => groupSelection('group'), + }, + { + id: 'ungroup', + label: 'actions.ungroup', + menu: 'object', + section: 0, + keys: [mod('g', { shift: true }), mod('Backspace')], + edit: true, + enabled: hasInnerPick, + run: ungroupSelection, + }, + { + id: 'auto-layout', + label: 'actions.addAutoLayout', + menu: 'object', + section: 1, + keys: [{ key: 'a', shift: true }], + edit: true, + enabled: hasInnerPick, + run: () => void addAutoLayout(), + }, + { + id: 'remove-auto-layout', + label: 'actions.removeAutoLayout', + menu: 'object', + section: 1, + keys: [{ code: 'KeyA', alt: true, shift: true }], + edit: true, + enabled: hasInnerPick, + run: removeAutoLayout, + }, + { + id: 'bring-to-front', + label: 'actions.bringToFront', + menu: 'object', + section: 2, + keys: [code('BracketRight'), mod(']', { alt: true, code: 'BracketRight' })], + edit: true, + enabled: hasSelection, + run: () => reorderSelection('front'), + }, + { + id: 'bring-forward', + label: 'actions.bringForward', + menu: 'object', + section: 2, + keys: [mod(']', { code: 'BracketRight' })], + edit: true, + enabled: hasSelection, + run: () => reorderSelection('forward'), + }, + { + id: 'send-backward', + label: 'actions.sendBackward', + menu: 'object', + section: 2, + keys: [mod('[', { code: 'BracketLeft' })], + edit: true, + enabled: hasSelection, + run: () => reorderSelection('backward'), + }, + { + id: 'send-to-back', + label: 'actions.sendToBack', + menu: 'object', + section: 2, + keys: [code('BracketLeft'), mod('[', { alt: true, code: 'BracketLeft' })], + edit: true, + enabled: hasSelection, + run: () => reorderSelection('back'), + }, + { + id: 'flip-horizontal', + label: 'actions.flipHorizontal', + menu: 'object', + section: 3, + keys: [{ key: 'h', shift: true }], + edit: true, + enabled: picked, + run: () => flip('x'), + }, + { + id: 'flip-vertical', + label: 'actions.flipVertical', + menu: 'object', + section: 3, + keys: [{ key: 'v', shift: true }], + edit: true, + enabled: picked, + run: () => flip('y'), + }, + { + id: 'rotate-180', + label: 'actions.rotate180', + menu: 'object', + section: 3, + edit: true, + enabled: hasSelection, + run: () => rotateBy(180), + }, + { + id: 'rotate-left', + label: 'actions.rotateLeft', + menu: 'object', + section: 3, + edit: true, + enabled: hasSelection, + run: () => rotateBy(-90), + }, + { + id: 'rotate-right', + label: 'actions.rotateRight', + menu: 'object', + section: 3, + edit: true, + enabled: hasSelection, + run: () => rotateBy(90), + }, + { + id: 'toggle-hidden', + label: 'actions.showHide', + menu: 'object', + section: 4, + keys: [mod('h', { shift: true })], + edit: true, + enabled: hasSelection, + run: () => toggleSelectionHidden(), + }, + { + id: 'toggle-locked', + label: 'actions.lockUnlock', + menu: 'object', + section: 4, + keys: [mod('l', { shift: true })], + edit: true, + enabled: hasSelection, + run: () => toggleLockSelection(), + }, + { + id: 'hide-others', + label: 'actions.hideOthers', + menu: 'object', + section: 4, + edit: true, + enabled: hasSelection, + run: hideOthers, + }, + { + id: 'collapse-layers', + label: 'actions.collapseLayers', + menu: 'object', + section: 4, + keys: [{ code: 'KeyL', alt: true }], + run: () => store().requestCollapseLayers(), + }, + { + id: 'remove-fill', + label: 'actions.removeFill', + menu: 'object', + section: 5, + keys: [{ code: 'Slash', alt: true }], + edit: true, + enabled: picked, + run: removeFill, + }, + + /* ---- Text ---- */ + { + id: 'bold', + label: 'actions.bold', + menu: 'text', + section: 0, + keys: [mod('b')], + edit: true, + enabled: picked, + run: () => formatSelectionText('bold'), + }, + { + id: 'italic', + label: 'actions.italic', + menu: 'text', + section: 0, + keys: [mod('i')], + edit: true, + enabled: picked, + run: () => formatSelectionText('italic'), + }, + { + id: 'underline', + label: 'actions.underline', + menu: 'text', + section: 0, + keys: [mod('u')], + edit: true, + enabled: picked, + run: () => formatSelectionText('underline'), + }, + { + id: 'strikethrough', + label: 'actions.strikethrough', + menu: 'text', + section: 0, + keys: [mod('x', { shift: true })], + edit: true, + enabled: picked, + run: () => formatSelectionText('strikeThrough'), + }, + { + id: 'link', + label: 'actions.createLink', + menu: 'text', + section: 0, + keys: [mod('u', { shift: true })], + edit: true, + enabled: hasInnerPick, + run: () => h()?.openLink(), + }, + { + id: 'bulleted-list', + label: 'actions.bulletedList', + menu: 'text', + section: 1, + keys: [mod('8', { shift: true, code: 'Digit8' })], + edit: true, + enabled: picked, + run: () => formatSelectionText('insertUnorderedList'), + }, + { + id: 'numbered-list', + label: 'actions.numberedList', + menu: 'text', + section: 1, + keys: [mod('7', { shift: true, code: 'Digit7' })], + edit: true, + enabled: picked, + run: () => formatSelectionText('insertOrderedList'), + }, + { + id: 'text-left', + label: 'actions.textAlignLeft', + menu: 'text', + section: 2, + keys: [mod('l', { alt: true, code: 'KeyL' })], + edit: true, + enabled: picked, + run: () => textAlign('left'), + }, + { + id: 'text-center', + label: 'actions.textAlignCenter', + menu: 'text', + section: 2, + keys: [mod('t', { alt: true, code: 'KeyT' })], + edit: true, + enabled: picked, + run: () => textAlign('center'), + }, + { + id: 'text-right', + label: 'actions.textAlignRight', + menu: 'text', + section: 2, + keys: [mod('r', { alt: true, code: 'KeyR' })], + edit: true, + enabled: picked, + run: () => textAlign('right'), + }, + { + id: 'text-justify', + label: 'actions.textAlignJustify', + menu: 'text', + section: 2, + keys: [mod('j', { alt: true, code: 'KeyJ' })], + edit: true, + enabled: picked, + run: () => textAlign('justify'), + }, + { + id: 'font-bigger', + label: 'actions.fontSizeUp', + menu: 'text', + section: 3, + keys: [mod('>', { shift: true, code: 'Period' })], + edit: true, + enabled: picked, + run: () => fontSizeBy(1), + }, + { + id: 'font-smaller', + label: 'actions.fontSizeDown', + menu: 'text', + section: 3, + keys: [mod('<', { shift: true, code: 'Comma' })], + edit: true, + enabled: picked, + run: () => fontSizeBy(-1), + }, + { + id: 'case-upper', + label: 'actions.caseUpper', + menu: 'text', + section: 4, + edit: true, + enabled: picked, + run: () => textCase('uppercase'), + }, + { + id: 'case-lower', + label: 'actions.caseLower', + menu: 'text', + section: 4, + edit: true, + enabled: picked, + run: () => textCase('lowercase'), + }, + { + id: 'case-title', + label: 'actions.caseTitle', + menu: 'text', + section: 4, + edit: true, + enabled: picked, + run: () => textCase('capitalize'), + }, + { + id: 'case-none', + label: 'actions.caseNone', + menu: 'text', + section: 4, + edit: true, + enabled: picked, + run: () => textCase('none'), + }, + + /* ---- Arrange ---- */ + { + id: 'round-to-pixel', + label: 'actions.roundToPixel', + menu: 'arrange', + section: 0, + edit: true, + enabled: () => selectedFrames().length > 0, + run: roundFramesToPixel, + }, + ...( + [ + ['align-left', 'actions.alignLeft', 'KeyA', 'left'], + ['align-hcenter', 'actions.alignHorizontalCenters', 'KeyH', 'hcenter'], + ['align-right', 'actions.alignRight', 'KeyD', 'right'], + ['align-top', 'actions.alignTop', 'KeyW', 'top'], + ['align-vcenter', 'actions.alignVerticalCenters', 'KeyV', 'vcenter'], + ['align-bottom', 'actions.alignBottom', 'KeyS', 'bottom'], + ] as const + ).map(([id, label, key, edge]): CanvasAction => ({ + id, + label, + menu: 'arrange', + section: 1, + keys: [{ code: key, alt: true }], + edit: true, + /* one layer aligns in its parent; frames need a second to align to */ + enabled: () => (hasInnerPick() ? true : arrangeCount() >= 2), + run: () => align(edge), + })), + { + id: 'tidy-up', + label: 'actions.tidyUp', + menu: 'arrange', + section: 2, + keys: [{ code: 'KeyT', alt: true, ctrl: true, macOnly: true }], + edit: true, + enabled: () => arrangeCount() >= 2, + run: tidy, + }, + { + id: 'pack-horizontal', + label: 'actions.packHorizontal', + menu: 'arrange', + section: 3, + edit: true, + enabled: () => arrangeCount() >= 2, + run: () => pack('x'), + }, + { + id: 'pack-vertical', + label: 'actions.packVertical', + menu: 'arrange', + section: 3, + edit: true, + enabled: () => arrangeCount() >= 2, + run: () => pack('y'), + }, + { + id: 'distribute-horizontal-spacing', + label: 'actions.distributeHorizontalSpacing', + menu: 'arrange', + section: 4, + keys: [{ code: 'KeyH', alt: true, ctrl: true, macOnly: true }], + edit: true, + enabled: () => arrangeCount() >= 3, + run: () => distributeSpacingOf('x'), + }, + { + id: 'distribute-vertical-spacing', + label: 'actions.distributeVerticalSpacing', + menu: 'arrange', + section: 4, + keys: [{ code: 'KeyV', alt: true, ctrl: true, macOnly: true }], + edit: true, + enabled: () => arrangeCount() >= 3, + run: () => distributeSpacingOf('y'), + }, + ...( + [ + ['distribute-left', 'actions.distributeLeft', 'x', 'start'], + ['distribute-hcenter', 'actions.distributeHorizontalCenters', 'x', 'center'], + ['distribute-right', 'actions.distributeRight', 'x', 'end'], + ['distribute-top', 'actions.distributeTop', 'y', 'start'], + ['distribute-vcenter', 'actions.distributeVerticalCenters', 'y', 'center'], + ['distribute-bottom', 'actions.distributeBottom', 'y', 'end'], + ] as const + ).map(([id, label, axis, edge]): CanvasAction => ({ + id, + label, + menu: 'arrange', + section: 5, + edit: true, + enabled: () => arrangeCount() >= 3, + run: () => distributeEdgesOf(axis, edge), + })), + + /* ---- Help ---- */ + { + id: 'shortcuts', + label: 'actions.keyboardShortcuts', + menu: 'help', + section: 0, + keys: [{ code: 'Slash', ctrl: true, shift: true }], + run: () => h()?.openShortcuts(), + }, +] + +/** Whether the action can run now: the canvas is open and editable when it + * needs to be, and its own test passes. */ +export function isEnabled(action: CanvasAction): boolean { + if (!host) return false + if (action.edit && !canEdit()) return false + return action.enabled ? action.enabled() : true +} + +/** Run the action from a menu or the palette. */ +export function runAction(action: CanvasAction) { + if (isEnabled(action)) action.run() +} + +/** Whether one of the action's chords, pressed with the focus in a field + * (`typing`) or not, is the canvas keyboard's to run: the rules + * `dispatchActionKey` applies, for a key that reached the desktop menu bar + * instead of the page. */ +export function takesKey(action: CanvasAction, typing: boolean): boolean { + if (!host || host.presenting || action.hintOnly) return false + return !typing || !!action.keys?.some((chord) => chord.global) +} + +type KeyEventLike = Pick< + KeyboardEvent, + 'key' | 'code' | 'metaKey' | 'ctrlKey' | 'altKey' | 'shiftKey' | 'repeat' | 'preventDefault' +> + +/** The canvas's keyboard: run the first enabled action bound to the chord. + * `typing` says the key landed in a field, where only global chords act. + * True when an action took the key. A chord whose action is disabled, or + * found nothing to act on, is left to the next binding and the browser. */ +export function dispatchActionKey(e: KeyEventLike, typing: boolean, mac = IS_MAC): boolean { + if (!host || host.presenting) return false + for (const action of ACTIONS) { + if (action.hintOnly) continue + if (!action.keys?.some((chord) => (!typing || chord.global) && matchesChord(e, chord, mac))) continue + if (!isEnabled(action)) continue + /* a held key repeats only what is safe to repeat */ + if (e.repeat && !REPEATABLE.has(action.id)) { + e.preventDefault() + return true + } + if (action.run() === false) continue + e.preventDefault() + return true + } + return false +} + +const REPEATABLE = new Set([ + 'undo', + 'redo', + 'zoom-in', + 'zoom-out', + 'font-bigger', + 'font-smaller', + 'zoom-next-frame', + 'zoom-previous-frame', + 'find-next-frame', + 'find-previous-frame', +]) diff --git a/src/lib/appMenu.ts b/src/lib/appMenu.ts new file mode 100644 index 000000000..8c3fb5d5e --- /dev/null +++ b/src/lib/appMenu.ts @@ -0,0 +1,216 @@ +/* The desktop shell's macOS menu bar (desktop/src-tauri/src/app_menu.rs), + built from the action registry the way the canvas's own main menu is: File, + Edit, View, Object, Text, Arrange and Help, every command with its label in + the page's language and its chord as the item's key equivalent, as Figma's + desktop app mirrors its menus. The shell adds what is its own (the app + menu, Close Tab, the system's Undo / Cut / Copy / Paste that text fields + need, Full Screen, Window). + + The page owns the state: it sends the menus once (`app_menu_set`, again + when the language changes) and then only the items whose enabled or + checked state moved (`app_menu_state`). A picked item comes back as an + `app-menu` event; `key` says a key equivalent fired it rather than a click, + and such a key keeps the canvas keyboard's rules (not in a field, not while + presenting, never a key another handler owns). Shells older than this + (no `__DOOP_APP_MENU__`) keep their fixed View menu (viewMenu.ts). */ + +import { firstChord, type Chord } from './actions/chords' +import { + ACTIONS, + MENUS, + isEnabled, + onActionHostChange, + runAction, + takesKey, + type CanvasAction, + type MenuId, +} from './actions/registry' +import { onLocaleChange, t } from './i18n' +import { isTypingTarget } from './keys' +import { useStore } from './store' + +/** One row of a native menu; `null` in a menu's items is a separator. */ +export interface NativeMenuItem { + id: string + label: string + /** a Tauri accelerator ("Alt+Cmd+KeyG"), or null for none */ + accelerator: string | null + checkable: boolean +} + +export interface NativeMenu { + id: Exclude + label: string + items: (NativeMenuItem | null)[] +} + +/** An item's state: id, enabled, and checked for a checkable one. */ +export type NativeItemState = [id: string, enabled: boolean, checked: boolean | null] + +/* the shell's predefined Undo and Redo stand for these: they are what makes + ⌘Z reach a text field, and the canvas takes the key before the menu does */ +const SHELL_OWNED = new Set(['undo', 'redo']) +/* the general rows (the ⌘K palette, the agent) open the Help menu, as the + canvas menu's search sits above its submenus */ +const HELP_LEAD = ['palette', 'ask-agent'] + +const PUNCTUATION: Record = { + '[': 'BracketLeft', + ']': 'BracketRight', + ',': 'Comma', + '.': 'Period', + '/': 'Slash', + '\\': 'Backslash', + "'": 'Quote', + '=': 'Equal', + '-': 'Minus', + ';': 'Semicolon', + '`': 'Backquote', +} +const NAMED = new Set([ + 'Enter', + 'Backspace', + 'Delete', + 'Escape', + 'Tab', + 'Home', + 'End', + 'PageUp', + 'PageDown', + 'ArrowUp', + 'ArrowDown', + 'ArrowLeft', + 'ArrowRight', +]) + +/* the physical key, as `KeyboardEvent.code` names it, which the shell's + accelerator parser reads; null for a key it has no name for */ +function keyCode(chord: Chord): string | null { + if (chord.code) return chord.code + const key = chord.key ?? '' + if (/^[a-z]$/i.test(key)) return `Key${key.toUpperCase()}` + if (/^\d$/.test(key)) return `Digit${key}` + return PUNCTUATION[key] ?? (NAMED.has(key) ? key : null) +} + +/** The chord as a macOS key equivalent: ⌃⌥⇧⌘ in the system's order, then + * the physical key. */ +export function nativeAccelerator(chord: Chord): string | null { + const code = keyCode(chord) + if (!code) return null + const modifiers = [chord.ctrl && 'Ctrl', chord.alt && 'Alt', chord.shift && 'Shift', chord.mod && 'Cmd'] + return [...modifiers.filter(Boolean), code].join('+') +} + +function item(action: CanvasAction): NativeMenuItem { + const chord = firstChord(action.keys, true) + return { + id: action.id, + label: t(action.label), + accelerator: chord && nativeAccelerator(chord), + checkable: !!action.checked, + } +} + +/* the registry's rows of one menu, a separator between sections */ +function rows(actions: readonly CanvasAction[]): (NativeMenuItem | null)[] { + const sections = [...new Set(actions.map((a) => a.section))] + return sections.flatMap((section, i) => [ + ...(i > 0 ? [null] : []), + ...actions.filter((a) => a.section === section).map(item), + ]) +} + +/** Every menu the page puts in the bar, in the registry's order. */ +export function nativeMenus(): NativeMenu[] { + return MENUS.map((menu) => { + const own = ACTIONS.filter((a) => a.menu === menu.id && !SHELL_OWNED.has(a.id)) + const lead = menu.id === 'help' ? ACTIONS.filter((a) => HELP_LEAD.includes(a.id)).map(item) : [] + return { id: menu.id, label: t(menu.label), items: lead.length ? [...lead, null, ...rows(own)] : rows(own) } + }) +} + +/** What each item in the bar shows now. */ +export function nativeStates(): NativeItemState[] { + const inBar = (a: CanvasAction) => !SHELL_OWNED.has(a.id) && (a.menu !== 'general' || HELP_LEAD.includes(a.id)) + return ACTIONS.filter(inBar).map((a) => { + const enabled = isEnabled(a) + return [a.id, enabled, a.checked ? enabled && a.checked() : null] + }) +} + +/** Run what the menu bar picked. A key equivalent keeps the canvas + * keyboard's rules; a field in a frame counts as typing, since the page + * never saw that key. */ +export function runNativeItem(id: string, key: boolean) { + const action = ACTIONS.find((a) => a.id === id) + if (!action) return + const focused = document.activeElement + if (key && !takesKey(action, isTypingTarget(focused) || focused instanceof HTMLIFrameElement)) return + runAction(action) +} + +type Invoke = (command: string, args: Record) => Promise +type Listen = (event: string, handler: (e: { payload: T }) => void) => Promise +type AppMenuBridge = { + __DOOP_APP_MENU__?: boolean + __TAURI__?: { core?: { invoke?: Invoke }; event?: { listen?: Listen } } +} + +const bridge = globalThis as AppMenuBridge + +/** Whether this shell builds its menu bar from the page. */ +export function hasAppMenu(): boolean { + return bridge.__DOOP_APP_MENU__ === true && !!bridge.__TAURI__?.core?.invoke +} + +const SYNC_DELAY_MS = 120 +/* what the shell shows, by item id, so only a change is sent */ +const shown = new Map() +let syncTimer: ReturnType | null = null + +function invoke(command: string, args: Record) { + bridge.__TAURI__?.core?.invoke?.(command, args).catch(console.error) +} + +/** Send the items whose state moved since the last send. */ +export function syncAppMenu() { + if (syncTimer) clearTimeout(syncTimer) + syncTimer = null + const items = nativeStates().filter(([id, enabled, checked]) => { + const state = `${enabled}:${checked}` + if (shown.get(id) === state) return false + shown.set(id, state) + return true + }) + if (items.length) invoke('app_menu_state', { items }) +} + +/* a store change, a host swap, a copy: the state is read again shortly + after, once, however many changes came in between (a drag moves the store + on every pointer move) */ +function scheduleSync() { + syncTimer ??= setTimeout(syncAppMenu, SYNC_DELAY_MS) +} + +function buildAppMenu() { + shown.clear() + invoke('app_menu_set', { menus: nativeMenus() }) + syncAppMenu() +} + +/** Hand the menu bar to the page; once, from the shell's start-up. */ +export function initAppMenu() { + if (!hasAppMenu()) return + buildAppMenu() + onLocaleChange(buildAppMenu) + onActionHostChange(scheduleSync) + useStore.subscribe(scheduleSync) + /* what Paste can take changes outside the store */ + for (const event of ['copy', 'cut', 'focus'] as const) window.addEventListener(event, scheduleSync) + bridge.__TAURI__?.event + ?.listen?.<{ id?: unknown; key?: unknown }>('app-menu', ({ payload }) => { + if (typeof payload?.id === 'string') runNativeItem(payload.id, payload.key === true) + }) + .catch(console.error) +} diff --git a/src/lib/desktop.ts b/src/lib/desktop.ts index 0044c9e3b..fe22355e0 100644 --- a/src/lib/desktop.ts +++ b/src/lib/desktop.ts @@ -23,6 +23,7 @@ import { codexSetupTarget } from './codexConnection' import { forgetPendingConnect, isPendingConnect, parseDesktopConnectLink } from './desktopConnect' import { safeRelativeTarget } from './safeTarget' import { NO_CANVAS, isViewCommand, runViewCommand, syncViewMenu } from './viewMenu' +import { initAppMenu } from './appMenu' export type CanvasTab = { id: string; name: string } @@ -299,8 +300,11 @@ export function initDesktopShell() { it as an event — the page never sees the keystroke. Windows has no menu bar, so Ctrl+W arrives as a plain keydown. Both close the active tab. */ shellWindow.__TAURI__?.event?.listen?.('close-tab', closeActiveTab).catch(console.error) - /* the macOS View menu (view_menu.rs): a reload leaves it showing the last - canvas until a canvas reports in again, so start it out closed */ + /* the macOS menu bar, built from the action registry (appMenu.ts); a shell + older than that has only the View menu (view_menu.rs), which a reload + leaves showing the last canvas until a canvas reports in again, so it + starts out closed */ + initAppMenu() syncViewMenu(NO_CANVAS) shellWindow.__TAURI__?.event ?.listen?.('view-command', (e) => { diff --git a/src/lib/elementClipboard.ts b/src/lib/elementClipboard.ts index 3a22f640f..3c6096f0b 100644 --- a/src/lib/elementClipboard.ts +++ b/src/lib/elementClipboard.ts @@ -1,5 +1,5 @@ import type { Frame } from '../../shared/types' -import { elementsHtml, insertElements, isElementLocked } from './layers' +import { elementsHtml, insertElements, isElementLocked, replaceElementsWith } from './layers' import { isStandalonePick, saveFrameHtml } from './layerEdits' import { copyFrames } from './frameClipboard' import { useStore } from './store' @@ -110,3 +110,22 @@ export function pasteLayer(frame: Frame, selector: string | null): boolean { for (const pasted of inserted.selectors) store.toggleElement({ frameId: frame.id, selector: pasted }) return true } + +/** ⇧⌘R on layers: the picked layers give way to the copied ones, which + * land where the first of them was and end up picked. */ +export function replaceWithClip(frame: Frame, selectors: string[]): boolean { + const live = useStore.getState().canvas?.frames.find((f) => f.id === frame.id) + const html = localStorage.getItem(ELEMENT_CLIP_KEY) + if (!live || live.locked || !html || !selectors.length) return false + const styles = clipStyles() + const fresh = new Map((styles?.scopes ?? []).map((old) => [old, newScope()])) + const rescope = (text: string) => [...fresh].reduce((t, [old, next]) => t.split(old).join(next), text) + const replaced = replaceElementsWith(live.html, selectors, rescope(html)) + if (!replaced) return false + const pasted = styles + ? withCarriedCss(replaced.html, renameInCss(rescope(styles.css), replaced.renamed), [...fresh.values()]) + : replaced.html + saveFrameHtml(live, pasted) + useStore.getState().pickElements(frame.id, replaced.selectors) + return true +} diff --git a/src/lib/frameBridge.ts b/src/lib/frameBridge.ts index 38a46306f..2212453c6 100644 --- a/src/lib/frameBridge.ts +++ b/src/lib/frameBridge.ts @@ -144,6 +144,8 @@ interface PendingAsk { const REPLY_TIMEOUT_MS = 2000 const windows = new Map() +/* ⌘Y outline mode, which a frame mounted later picks up when it registers */ +let outlines = false const changeListeners = new Map void>>() const selectionListeners = new Map void>>() const pending = new Map() @@ -174,6 +176,7 @@ function listen() { export function registerFrameWindow(frameId: string, win: Window) { windows.set(frameId, win) + if (outlines) win.postMessage({ type: 'doop:outlines', on: true }, '*') changeListeners.get(frameId)?.forEach((cb) => cb()) } @@ -347,3 +350,24 @@ export async function formatElementText( const reply = await requestFrame(frameId, 'doop:text-format', { selectors, command }) return Array.isArray(reply?.selectors) ? (reply.selectors as string[]) : null } + +/** The element's computed values for `properties`, or null when the selector + * no longer resolves or the frame is not mounted. */ +export async function computedStyles( + frameId: string, + selector: string, + properties: readonly string[], +): Promise | null> { + const reply = await requestFrame(frameId, 'doop:computed', { selector, properties: [...properties] }) + return reply && reply.values && typeof reply.values === 'object' ? (reply.values as Record) : null +} + +/** ⌘Y: draw every mounted frame (and any frame mounted later, through + * `outlinesOn`) as outlines. Nothing is saved. */ +export function setOutlines(on: boolean) { + outlines = on + for (const win of windows.values()) win.postMessage({ type: 'doop:outlines', on }, '*') +} +export function outlinesOn() { + return outlines +} diff --git a/src/lib/frameClipboard.ts b/src/lib/frameClipboard.ts index fe390cf73..c03e14e75 100644 --- a/src/lib/frameClipboard.ts +++ b/src/lib/frameClipboard.ts @@ -2,7 +2,7 @@ import type { Frame } from '../../shared/types' import { api } from './api' import { useStore } from './store' import { posthog } from './posthog' -import { recordCreates } from './history' +import { historyEpoch, recordCreates, replaceFramesTracked } from './history' import { ELEMENT_CLIP_KEY, FRAME_CLIP_KEY as CLIP_KEY } from './clipboardKeys' import { stageViewportSize } from './framePlacement' import { importSvgInBrowser, looksLikeSvg } from './svgImport' @@ -420,3 +420,94 @@ export function duplicateFrames(frames: Frame[]) { if (created.length) posthog.capture('frame_duplicated', { count: created.length }) }) } + +/** ⇧⌘V on frames: the copied frames centred over the selected ones. */ +export function pasteFramesOver(canvasId: string, over: Frame[]): boolean { + const frames = readClip() + if (!frames.length || !over.length) return false + const { width, height } = clipBounds(frames) + const left = Math.min(...over.map((f) => f.x)) + const top = Math.min(...over.map((f) => f.y)) + const right = Math.max(...over.map((f) => f.x + f.width)) + const bottom = Math.max(...over.map((f) => f.y + f.height)) + createFromClip(canvasId, (left + right) / 2 - width / 2, (top + bottom) / 2 - height / 2) + return true +} + +/* the frame as the canvas holds it now */ +function liveFrame(id: string): Frame | undefined { + return useStore.getState().canvas?.frames.find((f) => f.id === id) +} + +/** ⇧⌘R on frames: the copied frames land at each selected frame's top-left, + * and each selected frame goes once all of its replacements have landed. + * One whose replacements did not all land stays, and the copies that did + * are taken back; any that cannot be taken back stay in the undo step, so + * Undo still removes them. */ +export function replaceFramesWithClip(canvasId: string, targets: Frame[]): boolean { + const frames = readClip() + const replaceable = targets.filter((f) => !f.locked) + if (!frames.length || !replaceable.length) return false + /* the canvas and history this replacement belongs to: left behind, it + must not land in another canvas's history */ + const started = historyEpoch() + void Promise.all( + replaceable.map(async (target) => { + const results = await Promise.allSettled( + frames.map((f) => + api.createFrame(canvasId, { + name: f.name, + html: f.html, + width: f.width, + height: f.height, + x: Math.round(target.x + f.x), + y: Math.round(target.y + f.y), + ...(f.rotation ? { rotation: f.rotation } : {}), + }), + ), + ) + const created = results.flatMap((r) => (r.status === 'fulfilled' ? [r.value] : [])) + if (created.length === frames.length) return { target, created, leftovers: [] } + console.error(`replacing ${target.id}: ${frames.length - created.length} frame(s) failed`) + const removed = await Promise.allSettled(created.map((f) => api.deleteFrame(f.id))) + const leftovers = created.filter((_, i) => removed[i]?.status === 'rejected') + return { target, created: null, leftovers } + }), + ).then(async (outcomes) => { + const finished = outcomes.flatMap((o) => (o.created ? [{ target: o.target, created: o.created }] : [])) + const leftovers = outcomes.flatMap((o) => o.leftovers) + if (!finished.length && !leftovers.length) return + const movedOn = () => useStore.getState().canvas?.id !== canvasId || historyEpoch() !== started + /* the person moved on (another canvas, history cleared): no undo step + could take this back, so the replacements go and the originals stay */ + const dropAll = () => { + for (const f of finished.flatMap((o) => o.created)) api.deleteFrame(f.id).catch(console.error) + } + if (movedOn()) return dropAll() + /* a target a teammate edited while its replacements were made keeps that + edit, and its replacements go; a copy that cannot go stays in the undo + step, so Undo still takes it back */ + const stale = finished.filter(({ target }) => liveFrame(target.id)?.updatedAt !== target.updatedAt) + const ready = finished.filter((o) => !stale.includes(o)) + const staleCopies = stale.filter(({ target }) => liveFrame(target.id)).flatMap((o) => o.created) + const cleanup = await Promise.allSettled(staleCopies.map((f) => api.deleteFrame(f.id))) + leftovers.push(...staleCopies.filter((_, i) => cleanup[i]?.status === 'rejected')) + /* one deleted meanwhile has nothing left to remove: its copies stay */ + leftovers.push(...stale.filter(({ target }) => !liveFrame(target.id)).flatMap((o) => o.created)) + if (movedOn()) return dropAll() + /* read once more after the cleanup: a target edited during it keeps its + edit too, and its copies stay as plain copies */ + const done: { target: Frame; created: Frame[] }[] = [] + for (const { target, created } of ready) { + const now = liveFrame(target.id) + if (now?.updatedAt === target.updatedAt) done.push({ target: now, created }) + else leftovers.push(...created) + } + const created = [...done.flatMap((o) => o.created), ...leftovers] + if (!created.length) return + replaceFramesTracked(done, leftovers) + useStore.getState().selectMany(created.map((f) => f.id)) + posthog.capture('frame_pasted', { count: created.length }) + }) + return true +} diff --git a/src/lib/frameRuntime.ts b/src/lib/frameRuntime.ts index 850972cd5..70f4d1899 100644 --- a/src/lib/frameRuntime.ts +++ b/src/lib/frameRuntime.ts @@ -23,6 +23,18 @@ export const FRAME_BOOTSTRAP = ` vSheet.replaceSync('html,body{overscroll-behavior-x:none}[data-v-path-hidden]{visibility:hidden!important}') document.adoptedStyleSheets = document.adoptedStyleSheets.concat(vSheet) } catch (e) {} + /* ⌘Y outline mode: every box drawn as a hairline, fills and shadows off. + Adopted like the sheet above, so no save or export ever carries it. */ + var vOutlineSheet = null + try { + vOutlineSheet = new CSSStyleSheet() + vOutlineSheet.replaceSync('html,body{background:transparent!important}body *{outline:1px solid rgba(1,119,211,.6)!important;outline-offset:-1px!important;background:transparent!important;box-shadow:none!important;text-shadow:none!important}body img,body video,body canvas,body svg{opacity:.25!important}') + } catch (e) {} + function setOutlines(on) { + if (!vOutlineSheet) return + var rest = document.adoptedStyleSheets.filter(function (s) { return s !== vOutlineSheet }) + document.adoptedStyleSheets = on ? rest.concat(vOutlineSheet) : rest + } function syncAttrs(from, to) { for (var i = from.attributes.length - 1; i >= 0; i--) { var name = from.attributes[i].name @@ -350,7 +362,7 @@ export const FRAME_BOOTSTRAP = ` } var adopted = document.adoptedStyleSheets || [] for (var t = 0; t < adopted.length; t++) { - if (adopted[t] === vSheet) continue // the runtime's own + if (adopted[t] === vSheet || adopted[t] === vOutlineSheet) continue // the runtime's own var adoptedText = rulesText(adopted[t]) if (adoptedText === null) continue var adoptedStyle = document.createElement('style') @@ -1245,6 +1257,17 @@ export const FRAME_BOOTSTRAP = ` if (d.type === 'doop:inspect') { parent.postMessage({ type: 'doop:inspect-result', reqId: d.reqId, info: inspect(d.selector) }, '*') } + if (d.type === 'doop:outlines') setOutlines(d.on === true) + if (d.type === 'doop:computed' && Array.isArray(d.properties)) { + var computedEl = styleTarget(d.selector) + var values = null + if (computedEl) { + var cs = getComputedStyle(computedEl) + values = {} + d.properties.forEach(function (name) { values[name] = cs.getPropertyValue(name) }) + } + parent.postMessage({ type: 'doop:computed-result', reqId: d.reqId, values: values }, '*') + } if (d.type === 'doop:settle') { if (styleTimer) { clearTimeout(styleTimer) diff --git a/src/lib/history.ts b/src/lib/history.ts index ee3249a3c..8259ff45b 100644 --- a/src/lib/history.ts +++ b/src/lib/history.ts @@ -439,6 +439,37 @@ export function recordCreates(frames: Frame[]) { push(entries.length === 1 && first ? first : { type: 'group', entries }) } +/** Paste to replace, as one undo step: the replacements, already created, + * then the targets, deleted now, as a single transfer. A transfer runs its + * members in turn and stops where one fails, keeping the rest on the stack + * to retry, so undo brings every original back before it removes any + * replacement, however many frames were replaced. `leftovers` are copies + * that replace nothing (a failed replacement could not take them back, or + * their target was deleted meanwhile): undo removes them last. Each target + * goes only as it was checked: one edited since is refused by the server + * and stays, and the step then has no copy of it to bring back. */ +export function replaceFramesTracked(replacements: { target: Frame; created: Frame[] }[], leftovers: Frame[] = []) { + const created = [...leftovers, ...replacements.flatMap((r) => r.created)] + const removed = replacements.map((r) => r.target) + const first = removed[0] ?? created[0] + if (!first) return + const entry: Entry & { type: 'transfer' } = { + type: 'transfer', + canvasId: first.canvasId, + entries: [ + ...created.map((f): Entry => ({ type: 'create', frameId: f.id, snapshot: snapshot(f) })), + ...removed.map((f): Entry => ({ type: 'delete', frameId: f.id, snapshot: snapshot(f) })), + ], + } + push(entry) + for (const f of removed) { + api.deleteFrame(f.id, f.updatedAt).catch((err: unknown) => { + console.error(err) + entry.entries = entry.entries.filter((e) => e.type !== 'delete' || e.frameId !== f.id) + }) + } +} + /** Delete a frame through the API, remembering enough to bring it back. */ export function deleteFrameTracked(frame: Frame) { deleteFramesTracked([frame]) diff --git a/src/lib/i18n/en/actions.ts b/src/lib/i18n/en/actions.ts new file mode 100644 index 000000000..a2764e92d --- /dev/null +++ b/src/lib/i18n/en/actions.ts @@ -0,0 +1,165 @@ +/** The canvas editor's commands: the ⌘K palette, the main menu, the + * shortcuts sheet and the find bar. Labels follow common design-tool menus. */ +export const actions = { + /* menus */ + menuFile: 'File', + menuEdit: 'Edit', + menuView: 'View', + menuObject: 'Object', + menuText: 'Text', + menuArrange: 'Arrange', + menuHelp: 'Help', + mainMenu: 'Main menu', + + /* the palette */ + palette: 'Actions…', + palettePlaceholder: 'Search actions…', + paletteEmpty: 'No matching action', + paletteAsk: 'Ask the agent: “{query}”', + askAgent: 'Ask the agent', + + /* File */ + newCanvas: 'New canvas', + duplicateCanvas: 'Duplicate canvas', + placeImage: 'Place image…', + import: 'Import…', + versionHistory: 'Show version history', + export: 'Export…', + exportPdf: 'Export frames to PDF…', + + /* Edit */ + undo: 'Undo', + redo: 'Redo', + pasteOver: 'Paste over selection', + pasteReplace: 'Paste to replace', + duplicate: 'Duplicate', + delete: 'Delete', + find: 'Find…', + findNext: 'Find next', + findPrevious: 'Find previous', + findReplace: 'Find and replace…', + copyProperties: 'Copy properties', + pasteProperties: 'Paste properties', + propertiesCopied: 'Properties copied', + pickColor: 'Pick color', + colorCopied: 'Copied {color}', + selectAll: 'Select all', + selectNone: 'Select none', + selectInverse: 'Select inverse', + selectMatching: 'Select matching layers', + + /* View */ + rulers: 'Rulers', + pixelGrid: 'Pixel grid', + comments: 'Comments', + outlines: 'Outlines', + showUi: 'Show/Hide UI', + cursors: 'Multiplayer cursors', + layersPanel: 'Layers panel', + agentsPanel: 'Agents panel', + zoomIn: 'Zoom in', + zoomOut: 'Zoom out', + zoom100: 'Zoom to 100%', + zoomFit: 'Zoom to fit', + zoomSelection: 'Zoom to selection', + previousPage: 'Previous page', + nextPage: 'Next page', + zoomPreviousFrame: 'Zoom to previous frame', + zoomNextFrame: 'Zoom to next frame', + findPreviousFrame: 'Find previous frame', + findNextFrame: 'Find next frame', + present: 'Present', + + /* Object */ + frameSelection: 'Frame selection', + group: 'Group selection', + ungroup: 'Ungroup selection', + groupName: 'Group', + frameName: 'Frame', + groupFailed: 'Only layers side by side in one box can be grouped', + groupGridFailed: 'Layers in a grid can’t be grouped yet: the grid would lose their places', + frameChanged: 'The frame changed meanwhile. Pick the layers again and retry.', + ungroupFailed: 'Nothing to ungroup: pick a box that holds layers', + addAutoLayout: 'Add auto layout', + removeAutoLayout: 'Remove auto layout', + bringToFront: 'Bring to front', + bringForward: 'Bring forward', + sendBackward: 'Send backward', + sendToBack: 'Send to back', + flipHorizontal: 'Flip horizontal', + flipVertical: 'Flip vertical', + rotate180: 'Rotate 180°', + rotateLeft: 'Rotate 90° left', + rotateRight: 'Rotate 90° right', + showHide: 'Show/Hide selection', + lockUnlock: 'Lock/Unlock selection', + hideOthers: 'Hide other layers', + collapseLayers: 'Collapse layers', + removeFill: 'Remove fill', + + /* Text */ + bold: 'Bold', + italic: 'Italic', + underline: 'Underline', + strikethrough: 'Strikethrough', + createLink: 'Create link', + bulletedList: 'Bulleted list', + numberedList: 'Numbered list', + textAlignLeft: 'Text align left', + textAlignCenter: 'Text align center', + textAlignRight: 'Text align right', + textAlignJustify: 'Text align justified', + fontSizeUp: 'Increase font size', + fontSizeDown: 'Decrease font size', + caseUpper: 'Uppercase', + caseLower: 'Lowercase', + caseTitle: 'Title case', + caseNone: 'Original case', + + /* Arrange */ + roundToPixel: 'Round to pixel', + alignLeft: 'Align left', + alignHorizontalCenters: 'Align horizontal centers', + alignRight: 'Align right', + alignTop: 'Align top', + alignVerticalCenters: 'Align vertical centers', + alignBottom: 'Align bottom', + tidyUp: 'Tidy up', + packHorizontal: 'Pack horizontal', + packVertical: 'Pack vertical', + distributeHorizontalSpacing: 'Distribute horizontal spacing', + distributeVerticalSpacing: 'Distribute vertical spacing', + distributeLeft: 'Distribute left', + distributeHorizontalCenters: 'Distribute horizontal centers', + distributeRight: 'Distribute right', + distributeTop: 'Distribute top', + distributeVerticalCenters: 'Distribute vertical centers', + distributeBottom: 'Distribute bottom', + + /* Help */ + keyboardShortcuts: 'Keyboard shortcuts', + shortcutsSearch: 'Search shortcuts', + shortcutsEmpty: 'No shortcut matches “{query}”', + + /* the find bar */ + findLabel: 'Find in frames', + findPlaceholder: 'Find', + replacePlaceholder: 'Replace with', + findCount: '{current} of {total}', + findNone: 'No results', + matchCase: 'Match case', + previousMatch: 'Previous match', + nextMatch: 'Next match', + replaceOne: 'Replace', + replaceAll: 'Replace all', + showReplace: 'Show replace', + closeFind: 'Close find', + replaced: { one: 'Replaced {count} match', other: 'Replaced {count} matches' }, + + /* the link dialog */ + linkTitle: 'Create link', + linkLede: 'Where the picked layer should go when it is clicked.', + linkUrl: 'URL', + linkApply: 'Apply', + linkRemove: 'Remove link', +} as const diff --git a/src/lib/i18n/en/canvas.ts b/src/lib/i18n/en/canvas.ts index 56f521f93..cb46e5747 100644 --- a/src/lib/i18n/en/canvas.ts +++ b/src/lib/i18n/en/canvas.ts @@ -83,8 +83,8 @@ export const canvas = { contactSupport: 'Contact support', youAre: 'You are “{name}” — click to change your name', changeDisplayName: 'Change your display name', - agents: 'Agents · ⌘K to ask the Doop Agent', - agentsWorking: 'Agents · {working} working · ⌘K to ask the Doop Agent', + agents: 'Agents · ⌘/ to ask the Doop Agent', + agentsWorking: 'Agents · {working} working · ⌘/ to ask the Doop Agent', comments: 'Comments', commentsOpen: 'Comments · {open} open', activity: 'Activity', diff --git a/src/lib/i18n/en/index.ts b/src/lib/i18n/en/index.ts index 936a00e41..78c76a86e 100644 --- a/src/lib/i18n/en/index.ts +++ b/src/lib/i18n/en/index.ts @@ -19,6 +19,7 @@ import { workspace } from './workspace' import { community } from './community' import { admin } from './admin' import { ui } from './ui' +import { actions } from './actions' /** The source catalog, one namespace per area of the app. */ export const en = { @@ -43,4 +44,5 @@ export const en = { community, admin, ui, + actions, } diff --git a/src/lib/i18n/index.ts b/src/lib/i18n/index.ts index 8e1083671..d6ee6aec4 100644 --- a/src/lib/i18n/index.ts +++ b/src/lib/i18n/index.ts @@ -2,7 +2,17 @@ import { en } from './en' import { ptBR } from './pt-BR' import { getLocale, useLocale, type Locale } from './locale' -export { LOCALES, LOCALE_NAMES, isLocale, getLocale, setLocale, useLocale, initLocale, type Locale } from './locale' +export { + LOCALES, + LOCALE_NAMES, + isLocale, + getLocale, + setLocale, + useLocale, + initLocale, + subscribe as onLocaleChange, + type Locale, +} from './locale' /* English is the source catalog: its keys are the message keys, and its strings decide which {placeholders} a key takes. Every other language must diff --git a/src/lib/i18n/locale.ts b/src/lib/i18n/locale.ts index 60158c730..c033aab82 100644 --- a/src/lib/i18n/locale.ts +++ b/src/lib/i18n/locale.ts @@ -56,7 +56,8 @@ function notify(): void { listeners.forEach((listener) => listener()) } -function subscribe(listener: () => void): () => void { +/** Called whenever the language changes; returns the unsubscribe. */ +export function subscribe(listener: () => void): () => void { listeners.add(listener) return () => listeners.delete(listener) } diff --git a/src/lib/i18n/pt-BR/actions.ts b/src/lib/i18n/pt-BR/actions.ts new file mode 100644 index 000000000..beddbe0c5 --- /dev/null +++ b/src/lib/i18n/pt-BR/actions.ts @@ -0,0 +1,165 @@ +import type { Catalog } from '..' + +export const actions: Catalog['actions'] = { + /* menus */ + menuFile: 'Arquivo', + menuEdit: 'Editar', + menuView: 'Exibir', + menuObject: 'Objeto', + menuText: 'Texto', + menuArrange: 'Organizar', + menuHelp: 'Ajuda', + mainMenu: 'Menu principal', + + /* the palette */ + palette: 'Ações…', + palettePlaceholder: 'Buscar ações…', + paletteEmpty: 'Nenhuma ação encontrada', + paletteAsk: 'Perguntar ao agente: “{query}”', + askAgent: 'Perguntar ao agente', + + /* File */ + newCanvas: 'Novo canvas', + duplicateCanvas: 'Duplicar canvas', + placeImage: 'Inserir imagem…', + import: 'Importar…', + versionHistory: 'Mostrar histórico de versões', + export: 'Exportar…', + exportPdf: 'Exportar frames para PDF…', + + /* Edit */ + undo: 'Desfazer', + redo: 'Refazer', + pasteOver: 'Colar sobre a seleção', + pasteReplace: 'Colar substituindo', + duplicate: 'Duplicar', + delete: 'Excluir', + find: 'Localizar…', + findNext: 'Localizar próximo', + findPrevious: 'Localizar anterior', + findReplace: 'Localizar e substituir…', + copyProperties: 'Copiar propriedades', + pasteProperties: 'Colar propriedades', + propertiesCopied: 'Propriedades copiadas', + pickColor: 'Selecionar cor', + colorCopied: '{color} copiada', + selectAll: 'Selecionar tudo', + selectNone: 'Limpar seleção', + selectInverse: 'Inverter seleção', + selectMatching: 'Selecionar camadas semelhantes', + + /* View */ + rulers: 'Réguas', + pixelGrid: 'Grade de pixels', + comments: 'Comentários', + outlines: 'Contornos', + showUi: 'Mostrar/ocultar interface', + cursors: 'Cursores dos participantes', + layersPanel: 'Painel de camadas', + agentsPanel: 'Painel de agentes', + zoomIn: 'Aumentar zoom', + zoomOut: 'Diminuir zoom', + zoom100: 'Zoom em 100%', + zoomFit: 'Ajustar à tela', + zoomSelection: 'Zoom na seleção', + previousPage: 'Página anterior', + nextPage: 'Próxima página', + zoomPreviousFrame: 'Zoom no frame anterior', + zoomNextFrame: 'Zoom no próximo frame', + findPreviousFrame: 'Ir ao frame anterior', + findNextFrame: 'Ir ao próximo frame', + present: 'Apresentar', + + /* Object */ + frameSelection: 'Criar frame com a seleção', + group: 'Agrupar seleção', + ungroup: 'Desagrupar seleção', + groupName: 'Grupo', + frameName: 'Frame', + groupFailed: 'Só é possível agrupar camadas lado a lado na mesma caixa', + groupGridFailed: 'Ainda não é possível agrupar camadas de um grid: elas perderiam suas posições', + frameChanged: 'O frame mudou nesse meio-tempo. Escolha as camadas de novo e tente outra vez.', + ungroupFailed: 'Nada a desagrupar: escolha uma caixa que contenha camadas', + addAutoLayout: 'Adicionar auto layout', + removeAutoLayout: 'Remover auto layout', + bringToFront: 'Trazer para a frente', + bringForward: 'Avançar', + sendBackward: 'Recuar', + sendToBack: 'Enviar para trás', + flipHorizontal: 'Espelhar na horizontal', + flipVertical: 'Espelhar na vertical', + rotate180: 'Girar 180°', + rotateLeft: 'Girar 90° à esquerda', + rotateRight: 'Girar 90° à direita', + showHide: 'Mostrar/ocultar seleção', + lockUnlock: 'Bloquear/desbloquear seleção', + hideOthers: 'Ocultar outras camadas', + collapseLayers: 'Recolher camadas', + removeFill: 'Remover preenchimento', + + /* Text */ + bold: 'Negrito', + italic: 'Itálico', + underline: 'Sublinhado', + strikethrough: 'Tachado', + createLink: 'Criar link', + bulletedList: 'Lista com marcadores', + numberedList: 'Lista numerada', + textAlignLeft: 'Alinhar texto à esquerda', + textAlignCenter: 'Centralizar texto', + textAlignRight: 'Alinhar texto à direita', + textAlignJustify: 'Justificar texto', + fontSizeUp: 'Aumentar tamanho da fonte', + fontSizeDown: 'Diminuir tamanho da fonte', + caseUpper: 'Maiúsculas', + caseLower: 'Minúsculas', + caseTitle: 'Iniciais maiúsculas', + caseNone: 'Caixa original', + + /* Arrange */ + roundToPixel: 'Arredondar para pixel', + alignLeft: 'Alinhar à esquerda', + alignHorizontalCenters: 'Alinhar centros na horizontal', + alignRight: 'Alinhar à direita', + alignTop: 'Alinhar ao topo', + alignVerticalCenters: 'Alinhar centros na vertical', + alignBottom: 'Alinhar à base', + tidyUp: 'Organizar', + packHorizontal: 'Juntar na horizontal', + packVertical: 'Juntar na vertical', + distributeHorizontalSpacing: 'Distribuir espaçamento horizontal', + distributeVerticalSpacing: 'Distribuir espaçamento vertical', + distributeLeft: 'Distribuir pela esquerda', + distributeHorizontalCenters: 'Distribuir centros na horizontal', + distributeRight: 'Distribuir pela direita', + distributeTop: 'Distribuir pelo topo', + distributeVerticalCenters: 'Distribuir centros na vertical', + distributeBottom: 'Distribuir pela base', + + /* Help */ + keyboardShortcuts: 'Atalhos de teclado', + shortcutsSearch: 'Buscar atalhos', + shortcutsEmpty: 'Nenhum atalho corresponde a “{query}”', + + /* the find bar */ + findLabel: 'Localizar nos frames', + findPlaceholder: 'Localizar', + replacePlaceholder: 'Substituir por', + findCount: '{current} de {total}', + findNone: 'Nenhum resultado', + matchCase: 'Diferenciar maiúsculas', + previousMatch: 'Resultado anterior', + nextMatch: 'Próximo resultado', + replaceOne: 'Substituir', + replaceAll: 'Substituir tudo', + showReplace: 'Mostrar substituição', + closeFind: 'Fechar busca', + replaced: { one: '{count} ocorrência substituída', other: '{count} ocorrências substituídas' }, + + /* the link dialog */ + linkTitle: 'Criar link', + linkLede: 'Para onde a camada escolhida leva quando clicada.', + linkUrl: 'URL', + linkApply: 'Aplicar', + linkRemove: 'Remover link', +} diff --git a/src/lib/i18n/pt-BR/canvas.ts b/src/lib/i18n/pt-BR/canvas.ts index 23cc279ab..2c2710d31 100644 --- a/src/lib/i18n/pt-BR/canvas.ts +++ b/src/lib/i18n/pt-BR/canvas.ts @@ -83,8 +83,8 @@ export const canvas: Catalog['canvas'] = { contactSupport: 'Falar com o suporte', youAre: 'Você é “{name}” — clique para mudar seu nome', changeDisplayName: 'Mudar seu nome de exibição', - agents: 'Agentes · ⌘K para pedir ao Doop Agent', - agentsWorking: 'Agentes · {working} trabalhando · ⌘K para pedir ao Doop Agent', + agents: 'Agentes · ⌘/ para pedir ao Doop Agent', + agentsWorking: 'Agentes · {working} trabalhando · ⌘/ para pedir ao Doop Agent', comments: 'Comentários', commentsOpen: 'Comentários · {open} abertos', activity: 'Atividade', diff --git a/src/lib/i18n/pt-BR/index.ts b/src/lib/i18n/pt-BR/index.ts index b36b7b590..6ad9b8807 100644 --- a/src/lib/i18n/pt-BR/index.ts +++ b/src/lib/i18n/pt-BR/index.ts @@ -20,6 +20,7 @@ import { workspace } from './workspace' import { community } from './community' import { admin } from './admin' import { ui } from './ui' +import { actions } from './actions' export const ptBR: Catalog = { common, @@ -43,4 +44,5 @@ export const ptBR: Catalog = { community, admin, ui, + actions, } diff --git a/src/lib/layers.ts b/src/lib/layers.ts index fcee68e64..07fbfd147 100644 --- a/src/lib/layers.ts +++ b/src/lib/layers.ts @@ -751,3 +751,243 @@ function renameIds(doc: Document, copies: Element[], clashesOnly = false): Recor } return Object.fromEntries(renamed) } + +/* ---- grouping: ⌘G, ⌥⌘G and ⇧⌘G as markup ---- */ + +/* containers a wrapper may not go inside, nor be: their children are rows, + cells or options the parser keeps only directly under them */ +const UNWRAPPABLE_PARENTS = new Set([ + 'TABLE', + 'THEAD', + 'TBODY', + 'TFOOT', + 'TR', + 'SELECT', + 'OPTGROUP', + 'DATALIST', + 'UL', + 'OL', +]) + +export interface GroupOptions { + /** the wrapper's layer name, as the Layers panel shows it */ + name: string + /** inline styles for the wrapper (auto layout's flex), none for a plain group */ + style?: string + /** inline styles each wrapped element takes on (auto layout drops their margins) */ + childStyle?: Record +} + +/** The frame's HTML with the elements wrapped in one new `div`, placed where + * the first of them was, and the wrapper's path. The elements must share a + * parent (a group holds siblings); a wrapper in normal flow is static, so + * absolutely positioned children keep the box they were placed in. Null when + * they do not share one, sit in a table or list, or are locked. */ +export function groupElements( + html: string, + selectors: string[], + { name, style, childStyle }: GroupOptions, +): { html: string; selector: string } | null { + const doc = parse(html) + const found = findAll(doc, selectors) + if (!found?.length) return null + const els = inDocumentOrder(found) + const parent = els[0]!.parentElement + if (!parent || els.some((el) => el.parentElement !== parent)) return null + if (UNWRAPPABLE_PARENTS.has(parent.tagName) || parent.closest(`[${LOCK_ATTR}]`)) return null + if (els.some((el) => el.hasAttribute(LOCK_ATTR))) return null + const svg = parent.namespaceURI === 'http://www.w3.org/2000/svg' + const wrapper = svg ? doc.createElementNS(parent.namespaceURI, 'g') : doc.createElement('div') + wrapper.setAttribute(NAME_ATTR, name) + if (style && !svg) wrapper.setAttribute('style', style) + els[0]!.before(wrapper) + for (const el of els) { + wrapper.append(el) + if (!childStyle || svg) continue + for (const [prop, value] of Object.entries(childStyle)) (el as HTMLElement).style.setProperty(prop, value) + } + const next = serialize(doc) + const selector = elementPath(wrapper) + if (find(parse(next), selector)?.outerHTML !== wrapper.outerHTML) return null + return { html: next, selector } +} + +/** The frame's HTML with each element swapped for its children, and the + * children's paths: the group goes, what it held stays where it was. Only + * boxes holding elements unwrap (text would lose the box that styled it); + * null when none of them can. */ +export function ungroupElements(html: string, selectors: string[]): { html: string; selectors: string[] } | null { + const doc = parse(html) + const found = findAll(doc, selectors) + if (!found?.length) return null + const groups = outermost(found).filter( + (el) => + el !== doc.body && + el.children.length > 0 && + !ownText(el) && + !IMAGE_TAGS.has(el.tagName) && + !el.closest(`[${LOCK_ATTR}]`) && + !el.hasAttribute('data-doop-drawing') && + !(el.parentElement && UNWRAPPABLE_PARENTS.has(el.parentElement.tagName)), + ) + if (!groups.length) return null + const freed: Element[] = [] + for (const group of groups) { + const children = [...group.children] + group.replaceWith(...group.childNodes) + freed.push(...children) + } + const next = serialize(doc) + return { html: next, selectors: freed.map(elementPath) } +} + +/* elements that hold no content of their own: a link goes around them, not inside */ +const LINK_WRAPPED = new Set(['IMG', 'PICTURE', 'VIDEO', 'CANVAS', 'IFRAME', 'INPUT', 'HR', 'BR', 'EMBED', 'OBJECT']) + +/** The link an element is, holds alone, or sits alone inside. */ +function linkOf(el: Element): Element | null { + if (el.tagName === 'A') return el + if (el.childNodes.length === 1 && el.firstElementChild?.tagName === 'A') return el.firstElementChild + const parent = el.parentElement + if (parent?.tagName === 'A' && parent.childNodes.length === 1) return parent + return null +} + +/** The element's link target, or null when it has none. */ +export function elementLink(html: string, selector: string): string | null { + const el = find(parse(html), selector) + return el ? (linkOf(el)?.getAttribute('href') ?? null) : null +} + +/** Link `el` to `href` (null unlinks) in its document; false when there is + * nothing to unlink or the element cannot take a link. */ +/* what makes an element a link; everything else an inner link wears stays */ +const LINK_ONLY_ATTRS = [ + 'href', + 'xlink:href', + 'target', + 'rel', + 'download', + 'hreflang', + 'ping', + 'referrerpolicy', + 'type', +] +const SVG_NS = 'http://www.w3.org/2000/svg' + +/** A plain box in the link's place: a span (a `g` for a link inside SVG, + * which an HTML span would be thrown out of on load), with its content and + * every attribute but the ones that make it a link (class, style, id stay). */ +function demoteLink(doc: Document, link: Element): Element { + const box = link.namespaceURI === SVG_NS ? doc.createElementNS(SVG_NS, 'g') : doc.createElement('span') + for (const { name, value } of [...link.attributes]) { + if (!LINK_ONLY_ATTRS.includes(name)) box.setAttribute(name, value) + } + box.append(...link.childNodes) + link.replaceWith(box) + return box +} + +function linkElement(doc: Document, el: Element, href: string | null, swaps: Map): boolean { + const link = linkOf(el) + if (href === null) { + if (!link) return false + if (link === el) { + /* the link itself picked: keep the element, drop what made it a link */ + el.removeAttribute('href') + el.removeAttribute('target') + } else link.replaceWith(...link.childNodes) + return true + } + if (link) { + link.setAttribute('href', href) + return true + } + /* already inside a link (a picked parent linked a moment ago): retarget + that one, since a link inside a link is split apart on load */ + const around = el.parentElement?.closest('a') + if (around) { + around.setAttribute('href', href) + return true + } + const a = doc.createElement('a') + a.setAttribute('href', href) + if (LINK_WRAPPED.has(el.tagName) || el.namespaceURI === 'http://www.w3.org/2000/svg') { + if (el.parentElement?.namespaceURI === 'http://www.w3.org/2000/svg') return false + el.replaceWith(a) + a.append(el) + } else { + /* the links inside become plain spans under the one around them (a link + inside a link is split apart on load), keeping their looks and ids */ + for (const inner of [...el.querySelectorAll('a')]) swaps.set(inner, demoteLink(doc, inner)) + a.append(...el.childNodes) + el.append(a) + } + return true +} + +/** The frame's HTML with each element linked to `href`, and every element's + * path afterwards, in the order given: a link gets the new target, an image + * (or any element with no content of its own, and SVG) is wrapped in one, + * anything else has its content wrapped. Null `href` takes links off (the + * link element, or the one link wrapping the element or its content, gives + * way to its content). Every element is found before any changes, since + * wrapping one shifts its siblings' positions. Null when an element no + * longer resolves or none of them changed. */ +export function setElementsLink( + html: string, + selectors: string[], + href: string | null, +): { html: string; selectors: string[] } | null { + const doc = parse(html) + const els = selectors.map((selector) => find(doc, selector)) + if (els.some((el) => !el || el === doc.body)) return null + /* outermost first, so a picked child finds its picked parent's new link */ + const order = [...els].sort((a, b) => (a!.compareDocumentPosition(b!) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1)) + /* inner links a wrap turned into spans: a picked one is followed there */ + const swaps = new Map() + const current = (el: Element) => swaps.get(el) ?? el + const changed = order.map((el) => linkElement(doc, current(el!), href, swaps)) + if (!changed.includes(true)) return null + return { html: serialize(doc), selectors: els.map((el) => elementPath(current(el!))) } +} + +/** One element's `setElementsLink`. */ +export function setElementLink( + html: string, + selector: string, + href: string | null, +): { html: string; selector: string } | null { + const linked = setElementsLink(html, [selector], href) + return linked ? { html: linked.html, selector: linked.selectors[0]! } : null +} + +/** The frame's HTML with the elements swapped for the clipboard's layers, + * which land where the first of them was (paste to replace), and + * the pasted layers' paths. Null when an element is gone or locked, or the + * markup does not survive a round trip. */ +export function replaceElementsWith( + html: string, + selectors: string[], + outerHtml: string, +): { html: string; selectors: string[]; renamed: Record } | null { + const doc = parse(html) + const found = findAll(doc, selectors) + if (!found?.length) return null + const els = inDocumentOrder(found) + const first = els[0]! + if (els.some((el) => el === doc.body || el.closest(`[${LOCK_ATTR}]`))) return null + const source = (first.parentElement ?? doc.body).cloneNode(false) as Element + source.innerHTML = outerHtml + if (!source.children.length) return null + if ([...source.childNodes].some((node) => node.nodeType === Node.TEXT_NODE && node.textContent?.trim())) return null + const copies = [...source.children] + const renamed = renameIds(doc, copies) + first.before(...copies) + for (const el of els) el.remove() + const next = serialize(doc) + const paths = copies.map(elementPath) + const reparsed = parse(next) + if (copies.some((copy, i) => find(reparsed, paths[i]!)?.outerHTML !== copy.outerHTML)) return null + return { html: next, selectors: paths, renamed } +} diff --git a/src/lib/store.ts b/src/lib/store.ts index c7b7c39cd..b3bab9a44 100644 --- a/src/lib/store.ts +++ b/src/lib/store.ts @@ -20,6 +20,7 @@ import type { import { roleAllows, type CanvasRole } from '../../shared/canvasRole' import type { SnapGuide } from './snap' import { isDrawingTool, type Tool } from './tools' +import { setOutlines } from './frameBridge' import { readViewOptions, writeViewOptions, type ViewOption, type ViewOptions } from './viewOptions' export interface Viewport { @@ -122,6 +123,10 @@ interface State { viewOptions: ViewOptions /** the ruler guide clicked last, which Delete removes */ selectedGuideId: string | null + /** ⌘Y — frames drawn as outlines, fills off; nothing is saved */ + outlines: boolean + /** ⌥L asks the Layers panel to fold every row; it watches the stamp */ + layersCollapseAt: number connected: boolean /** the join for the current canvasId was refused: no such canvas (deleted, * or the id in the URL was never one) — CanvasPage shows a not-found @@ -153,7 +158,7 @@ interface State { * the Comments panel raises it; the FrameView that owns the root consumes it */ threadRequest: { id: string; at: number } | null /** when the "Design it" composer in the Agents tab was last asked to take - * focus (⌘K) — a timestamp, so a composer that mounts long after an old + * focus (⌘/) — a timestamp, so a composer that mounts long after an old * request does not grab the keyboard */ composerFocusAt: number /** the composer's unsent text per canvas — collapsing the panel or @@ -263,6 +268,8 @@ interface State { setSnapGuides(guides: SnapGuide[]): void toggleRulers(): void toggleViewOption(name: ViewOption): void + toggleOutlines(): void + requestCollapseLayers(): void selectGuide(id: string | null): void /** add or move (guide set) or remove (null) a ruler guide on the open canvas */ setGuideLocal(id: string, guide: CanvasGuide | null): void @@ -334,6 +341,8 @@ export const useStore = create((set, get) => ({ rulers: readRulers(), viewOptions: readViewOptions(), selectedGuideId: null, + outlines: false, + layersCollapseAt: 0, connected: false, canvasNotFound: false, signInRequired: false, @@ -733,6 +742,12 @@ export const useStore = create((set, get) => ({ } return { rulers: !s.rulers, ...(s.rulers ? { selectedGuideId: null } : {}) } }), + toggleOutlines: () => + set((s) => { + setOutlines(!s.outlines) + return { outlines: !s.outlines } + }), + requestCollapseLayers: () => set({ layersCollapseAt: Date.now() }), toggleViewOption: (name) => set((s) => { const viewOptions = { ...s.viewOptions, [name]: !s.viewOptions[name] } diff --git a/src/lib/viewMenu.ts b/src/lib/viewMenu.ts index cc7ec62fd..eccff8a03 100644 --- a/src/lib/viewMenu.ts +++ b/src/lib/viewMenu.ts @@ -46,6 +46,8 @@ export const NO_CANVAS: ViewMenuState = { type ViewMenuBridge = { __DOOP_VIEW_MENU__?: boolean + /** the shell builds its whole menu bar from the page (appMenu.ts) */ + __DOOP_APP_MENU__?: boolean __TAURI__?: { core?: { invoke: (command: string, args: ViewMenuState) => Promise } } } @@ -63,8 +65,10 @@ export function runViewCommand(command: ViewCommand) { for (const handler of handlers) handler(command) } -/** Mirror the page's view state into the shell's menu. */ +/** Mirror the page's view state into the shell's menu; a shell whose menu bar + * the page builds (appMenu.ts) has no fixed View menu to keep in step. */ export function syncViewMenu(state: ViewMenuState) { - const invoke = bridge.__DOOP_VIEW_MENU__ === true ? bridge.__TAURI__?.core?.invoke : undefined + const fixedMenu = bridge.__DOOP_VIEW_MENU__ === true && bridge.__DOOP_APP_MENU__ !== true + const invoke = fixedMenu ? bridge.__TAURI__?.core?.invoke : undefined invoke?.('view_menu_state', state).catch(console.error) } diff --git a/src/lib/viewOptions.ts b/src/lib/viewOptions.ts index dd5ccbbe5..4b0fa2a6d 100644 --- a/src/lib/viewOptions.ts +++ b/src/lib/viewOptions.ts @@ -1,5 +1,6 @@ /* What the canvas draws over the frames, each switched from the zoom pill's - menu or its shortcut, and remembered per browser: + menu or its shortcut (bound in the action registry), and remembered per + browser: - pixelGrid (⇧'): the hairline grid that fades in from 300% - cursors (⌘⌥\ / Ctrl+Alt+\): everyone else's pointer - comments (⇧C): the comment pins; the Comment tool still shows them */ @@ -39,21 +40,6 @@ export function writeViewOptions(options: ViewOptions) { } } -/** The option a key press toggles, or null. Read by `code`: ⇧ and ⌥ change - * the typed character (⇧' is `"`, ⌥\ is `«` on macOS). */ -export function viewOptionForKey( - e: Pick, -): ViewOption | null { - const mod = e.metaKey || e.ctrlKey - if (e.shiftKey && !mod && !e.altKey) { - if (e.code === 'Quote') return 'pixelGrid' - if (e.code === 'KeyC') return 'comments' - return null - } - if (mod && e.altKey && !e.shiftKey && e.code === 'Backslash') return 'cursors' - return null -} - /** A typed zoom level ("150", "150%", "33.3 %") as a zoom factor, or null * when it is not a positive number. */ export function parseZoomPercent(text: string): number | null { diff --git a/src/pages/CanvasPage.tsx b/src/pages/CanvasPage.tsx index 4c4e7afd6..25838ee71 100644 --- a/src/pages/CanvasPage.tsx +++ b/src/pages/CanvasPage.tsx @@ -1,17 +1,9 @@ import { CAPTURE_PREFIX, pasteWebCapture } from '../lib/webCapture' import { useEffect, useMemo, useRef, useState, type CSSProperties } from 'react' import { canEditOpenCanvas, pickedSelectors, roleOf, useStore } from '../lib/store' -import { - MOD_KEY, - PRESENT_SHORTCUT_HINT, - isControlTarget, - isHideUiShortcut, - isPresentShortcut, - isSelectAllShortcut, - isTypingTarget, - reorderShortcut, -} from '../lib/keys' -import { enterSelection, exitSelection, reorderSelection, selectAll, selectSibling } from '../lib/selectionKeys' +import { MOD_KEY, PRESENT_SHORTCUT_HINT, isControlTarget, isTypingTarget } from '../lib/keys' +import { enterSelection, exitSelection, selectSibling } from '../lib/selectionKeys' +import { dispatchActionKey, setActionHost, type ActionHost } from '../lib/actions/registry' import { presentStartFrame } from '../lib/present' import { canHideUi, hideUiHinted } from '../lib/hideUi' import { connect, disconnect, sendWs } from '../lib/ws' @@ -60,11 +52,16 @@ import type { Frame } from '../../shared/types' import { ImportStepFooter, ImportStepHeader, SourcePicker } from '../components/ImportSources' import { importSources } from '../components/importSourceList' import { PresentMode } from '../components/PresentMode' +import { CommandPalette } from '../components/CommandPalette' +import { MainMenu } from '../components/MainMenu' +import { ShortcutsSheet } from '../components/ShortcutsSheet' +import { FindBar } from '../components/FindBar' +import { LinkDialog } from '../components/LinkDialog' +import { FrameHistoryModal } from '../components/FrameHistoryModal' import { getIdentity, setName } from '../lib/identity' import { copyFrames, dropFiles, - duplicateFrames, hasFrameClip, hasIncoming, pasteFrameCentered, @@ -72,16 +69,8 @@ import { splitIncoming, svgMarkupOf, } from '../lib/frameClipboard' -import { clearHistory, redo, undo } from '../lib/history' -import { - deleteSelection, - duplicateLayers, - nudgeSelection, - toggleLockSelection, - toggleSelectionHidden, - formatSelectionText, -} from '../lib/layerEdits' -import type { TextFormatCommand } from '../lib/richText' +import { clearHistory } from '../lib/history' +import { deleteSelection, nudgeSelection } from '../lib/layerEdits' import { copyPicked, hasElementClip, pasteLayer } from '../lib/elementClipboard' import { isCanvasClipboard, writeCanvasClipboard } from '../lib/canvasClipboard' import { authClient } from '../lib/auth' @@ -156,14 +145,6 @@ const ARROW_NUDGE: Record = { ArrowUp: [0, -1], ArrowDown: [0, 1], } -const LETTER_FORMATS: Record = { b: 'bold', i: 'italic', u: 'underline' } - -/** The text format a canvas key chord names: letters without ⇧, the ⇧ digits by code (⇧7 is & on US keyboards). */ -function layerTextShortcut(e: KeyboardEvent): TextFormatCommand | null { - if (!e.shiftKey) return LETTER_FORMATS[e.key.toLowerCase()] ?? null - if (e.key.toLowerCase() === 'x') return 'strikeThrough' - return e.code === 'Digit7' ? 'insertOrderedList' : e.code === 'Digit8' ? 'insertUnorderedList' : null -} const LAYERS_W = 264 const RAIL_W = 40 const INSPECTOR_W = 244 @@ -343,6 +324,15 @@ export function CanvasPage({ const [showMobileLayers, setShowMobileLayers] = useState(false) const [renaming, setRenaming] = useState(false) const [toast, setToast] = useState(null) + /* the action registry's surfaces: ⌘K, the shortcuts sheet, the find bar, + the link dialog and a frame's version history */ + const [paletteOpen, setPaletteOpen] = useState(false) + const [shortcutsOpen, setShortcutsOpen] = useState(false) + const [find, setFind] = useState<'find' | 'replace' | null>(null) + const [findStep, setFindStep] = useState<{ dir: 1 | -1; at: number } | null>(null) + const [linkOpen, setLinkOpen] = useState(false) + const [historyFrame, setHistoryFrame] = useState(null) + const placeImageRef = useRef(null) const storeNotice = useStore((s) => s.notice) const updateReady = useStore((s) => s.updateReady) const limitWall = useStore((s) => s.limitWall) @@ -390,25 +380,14 @@ export function CanvasPage({ sendWs({ type: 'editing', frameId: selectedId }) }, [selectedId]) - /* frame keyboard shortcuts: delete, copy/paste/duplicate, undo/redo */ + /* the canvas's keyboard: every chord in the action registry (the ⌘K + palette's commands), then the keys with rules of their own — ⌫, the + selection walk on ↩ and Tab, the arrow nudge and Esc */ useEffect(() => { function onKey(e: KeyboardEvent) { - /* ⌘K from anywhere, fields included: open the side panel on the Agents - tab and put the keyboard in its "Design it" composer. Asking for the - composer ends ⌘. hide-UI — a field under `hidden` cannot take focus. */ - if ((e.metaKey || e.ctrlKey) && !e.altKey && !e.shiftKey && e.key.toLowerCase() === 'k') { - e.preventDefault() - /* the composer is an editor's: readers (and guests) have none */ - const state = useStore.getState() - if (guest || !state.canvas || !canEditOpenCanvas(state)) return - setShowActivity(true) - if (useStore.getState().uiHidden) useStore.getState().toggleUiHidden() - useStore.getState().setPanelTab('tasks') - useStore.getState().requestComposerFocus() - return - } - if (isTypingTarget(e.target)) return - const selectedIds = useStore.getState().selectedIds + const typing = isTypingTarget(e.target) + if (dispatchActionKey(e, typing)) return + if (typing) return /* a picked element (from the canvas or the layers tree) is what ⌫ removes — the frame it lives in only goes when nothing inside it is selected. Auto-repeat is ignored: a held key must not take the @@ -435,19 +414,6 @@ export function CanvasPage({ return } } - /* ⌘A: every frame on the page, or every sibling of the picked element */ - if (isSelectAllShortcut(e) && !presenting) { - e.preventDefault() - selectAll() - return - } - /* ⌘] / ⌘[ and ⌘⌥] / ⌘⌥[ restack what is selected */ - const reorder = reorderShortcut(e) - if (reorder && canEdit && !presenting) { - e.preventDefault() - reorderSelection(reorder) - return - } const nudge = ARROW_NUDGE[e.key] if (canEdit && nudge && !e.defaultPrevented && !e.metaKey && !e.ctrlKey && !e.altKey) { const step = e.shiftKey ? 10 : 1 @@ -458,66 +424,10 @@ export function CanvasPage({ select(null) useStore.getState().setFollowing(null) } - /* ⌘. hides every panel and toolbar; ⌘. again brings them back as they - were. Escape deliberately leaves the UI hidden, as in Figma. */ - if (isHideUiShortcut(e) && hideUiActive) { - e.preventDefault() - toggleHideUi() - return - } - /* ⌘⌥↩ presents from the selected frame (else the page's flow start), - as the Play button does; while presenting the player owns the keys */ - if (isPresentShortcut(e) && !presenting) { - e.preventDefault() - const state = useStore.getState() - const from = presentStartFrame(state.canvas, state.selectedId, state.activePageId) - if (from) setPresenting(from) - return - } - /* undo, redo, hide, lock and duplicate all change the canvas */ - if (canEdit && (e.metaKey || e.ctrlKey) && !e.altKey && e.key.toLowerCase() === 'z') { - e.preventDefault() - if (e.shiftKey) void redo() - else void undo() - return - } - if (canEdit && (e.metaKey || e.ctrlKey) && !e.altKey && !e.shiftKey && e.key.toLowerCase() === 'y') { - e.preventDefault() - void redo() - return - } - /* ⌘⇧H hides or shows what is selected — the picked element, else the - frames — as the eye in the Layers panel would */ - if (canEdit && (e.metaKey || e.ctrlKey) && e.shiftKey && !e.altKey && e.key.toLowerCase() === 'h') { - if (toggleSelectionHidden()) e.preventDefault() - return - } - /* ⌘B / ⌘I / ⌘U, ⌘⇧X and ⌘⇧7 / ⌘⇧8 format a picked text layer whole, as in Figma */ - const textFormat = canEdit && (e.metaKey || e.ctrlKey) && !e.altKey ? layerTextShortcut(e) : null - if (textFormat) { - if (formatSelectionText(textFormat)) e.preventDefault() - return - } - /* ⌘⇧L locks or unlocks what is selected: the picked layer, else the frames */ - if (canEdit && (e.metaKey || e.ctrlKey) && e.shiftKey && !e.altKey && e.key.toLowerCase() === 'l') { - if (toggleLockSelection()) e.preventDefault() - return - } - if ((e.metaKey || e.ctrlKey) && !e.shiftKey && !e.altKey) { - const state = useStore.getState() - const picked = state.selectedElement - const pickedFrame = state.canvas?.frames.find((f) => f.id === picked?.frameId) - const frames = state.canvas?.frames.filter((f) => selectedIds.includes(f.id)) ?? [] - if (canEdit && e.key.toLowerCase() === 'd' && frames.length) { - e.preventDefault() - if (picked && pickedFrame) duplicateLayers(pickedFrame, pickedSelectors(state)) - else if (!picked) duplicateFrames(frames) - } - } } window.addEventListener('keydown', onKey) return () => window.removeEventListener('keydown', onKey) - }, [canvasId, guest, hideUiActive, presenting]) // eslint-disable-line react-hooks/exhaustive-deps + }, [canvasId, presenting]) // eslint-disable-line react-hooks/exhaustive-deps /* Native copy/paste events let us write the selection's token and read clipboard images without asking for clipboard-read permission. */ @@ -655,6 +565,67 @@ export function CanvasPage({ setExporting({ frames, selected: s.selectedIds.filter((id) => frames.some((f) => f.id === id)) }) } + /* the agent's composer: ⌘/ (and / outside a field) opens the side panel on + the Agents tab and puts the keyboard there. Asking for the composer ends + ⌘. hide-UI — a field under `hidden` cannot take focus. */ + function openAgent() { + const state = useStore.getState() + /* the composer is an editor's: readers (and guests) have none */ + if (guest || !state.canvas || !canEditOpenCanvas(state)) return + setShowActivity(true) + if (state.uiHidden) state.toggleUiHidden() + state.setPanelTab('tasks') + state.requestComposerFocus() + } + + /* lend the action registry what only this page holds, fresh every render */ + useEffect(() => { + const host: ActionHost = { + canvasId, + guest, + presenting: !!presenting, + hideUiActive, + agentsOpen: showActivity, + openPalette: () => setPaletteOpen(true), + openAgent, + openShortcuts: () => setShortcutsOpen(true), + openFind: (mode) => setFind((open) => (open === 'replace' ? open : mode)), + findStep: (dir) => { + setFind((open) => open ?? 'find') + setFindStep({ dir, at: Date.now() }) + }, + openExport, + openImport: () => setShowImport(true), + openVersionHistory: () => { + const s = useStore.getState() + setHistoryFrame(s.canvas?.frames.find((f) => f.id === s.selectedId) ?? null) + }, + openLink: () => setLinkOpen(true), + placeImage: () => placeImageRef.current?.click(), + newCanvas: () => { + api + .createCanvas('Untitled canvas', useStore.getState().canvas?.workspaceId) + .then((made) => navigate(`/c/${made.id}`)) + .catch((err: Error) => showToast(err.message)) + }, + duplicateCanvas: () => { + api + .duplicateCanvas(canvasId) + .then((made) => navigate(`/c/${made.id}`)) + .catch((err: Error) => showToast(err.message)) + }, + present: () => { + const state = useStore.getState() + const from = presentStartFrame(state.canvas, state.selectedId, state.activePageId) + if (from) setPresenting(from) + }, + toggleHideUi, + toggleAgents: () => setShowActivity((open) => !open), + } + setActionHost(host) + }) + useEffect(() => () => setActionHost(null), []) + /* a pending Memory suggestion gets its own toast beside the side panel; clicking it jumps to the Memory tab, ✕ mutes it for this session */ const pendingProposal = useStore((s) => s.proposals.find((p) => p.status === 'pending')) @@ -849,6 +820,19 @@ export function CanvasPage({ >
+ + + + } + /> {!guest && (