From b2cd1f4a628f3b7acdedcda5365726b65d995074 Mon Sep 17 00:00:00 2001 From: Kevin Goedecke Date: Sat, 7 Nov 2026 19:28:17 -0800 Subject: [PATCH 01/14] =?UTF-8?q?feat(canvas):=20action=20registry=20with?= =?UTF-8?q?=20=E2=8C=98K=20palette,=20main=20menu=20and=20editor=20shortcu?= =?UTF-8?q?ts?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit One registry of canvas commands drives the keyboard, the ⌘K action palette, the main menu off the Doop mark and the ⌃⇧? shortcuts sheet. Adds arrange (align, distribute, tidy up, pack), group / ungroup, auto layout, flip and rotate, copy and paste properties, paste over / replace, find and replace across frames, links, text alignment, case and size, outline mode, comment pin and cursor toggles, and frame and page stepping. The agent composer moves from ⌘K to ⌘/ (and / outside fields). Co-Authored-By: Claude Opus 5.5 (1M context) --- .context/TECHSTACK.md | 26 + bun.lock | 7 + package.json | 1 + src/components/CanvasComments.tsx | 3 + src/components/CommandPalette.tsx | 92 +++ src/components/Cursors.tsx | 3 + src/components/FindBar.tsx | 232 ++++++ src/components/FrameView.tsx | 3 + src/components/LayersPanel.tsx | 8 + src/components/LinkDialog.tsx | 62 ++ src/components/MainMenu.tsx | 98 +++ src/components/PromptBar.tsx | 4 +- src/components/ShortcutsSheet.tsx | 74 ++ src/components/Stage.tsx | 41 +- src/components/ui/command.tsx | 95 +++ src/components/ui/dropdown-menu.tsx | 64 +- src/lib/actions/arrange.ts | 175 +++++ src/lib/actions/chords.ts | 94 +++ src/lib/actions/edits.ts | 673 +++++++++++++++++ src/lib/actions/findText.ts | 103 +++ src/lib/actions/registry.ts | 1049 +++++++++++++++++++++++++++ src/lib/elementClipboard.ts | 21 +- src/lib/frameBridge.ts | 24 + src/lib/frameClipboard.ts | 42 +- src/lib/frameRuntime.ts | 25 +- src/lib/i18n/en/actions.ts | 162 +++++ src/lib/i18n/en/canvas.ts | 4 +- src/lib/i18n/en/index.ts | 2 + src/lib/i18n/pt-BR/actions.ts | 162 +++++ src/lib/i18n/pt-BR/canvas.ts | 4 +- src/lib/i18n/pt-BR/index.ts | 2 + src/lib/layers.ts | 149 ++++ src/lib/store.ts | 27 +- src/pages/CanvasPage.tsx | 253 ++++--- src/stories/Overlays.stories.tsx | 87 +++ tests/actionChords.test.ts | 49 ++ tests/actionRegistry.test.ts | 127 ++++ tests/arrange.test.ts | 57 ++ tests/findText.test.ts | 46 ++ tests/fixtures/rulers.html | 27 + tests/groupLayers.test.ts | 96 +++ tests/promptComposer.test.tsx | 2 +- 42 files changed, 4109 insertions(+), 166 deletions(-) create mode 100644 src/components/CommandPalette.tsx create mode 100644 src/components/FindBar.tsx create mode 100644 src/components/LinkDialog.tsx create mode 100644 src/components/MainMenu.tsx create mode 100644 src/components/ShortcutsSheet.tsx create mode 100644 src/components/ui/command.tsx create mode 100644 src/lib/actions/arrange.ts create mode 100644 src/lib/actions/chords.ts create mode 100644 src/lib/actions/edits.ts create mode 100644 src/lib/actions/findText.ts create mode 100644 src/lib/actions/registry.ts create mode 100644 src/lib/i18n/en/actions.ts create mode 100644 src/lib/i18n/pt-BR/actions.ts create mode 100644 tests/actionChords.test.ts create mode 100644 tests/actionRegistry.test.ts create mode 100644 tests/arrange.test.ts create mode 100644 tests/findText.test.ts create mode 100644 tests/groupLayers.test.ts diff --git a/.context/TECHSTACK.md b/.context/TECHSTACK.md index 76e7b8e3e..a30a88d1a 100644 --- a/.context/TECHSTACK.md +++ b/.context/TECHSTACK.md @@ -344,6 +344,32 @@ 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` 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; ⇧⌘U links (`setElementLink`); ⌃C is + the EyeDropper. ⌘F / ⌥⌘F is the find bar (`FindBar.tsx`, `findText.ts`: text nodes only, + replace-all is one undo step across frames). View toggles live in the store: ⇧C hides comment + pins, ⌥⌘\ other people's 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/package.json b/package.json index 4b474cce6..0fab0ac4c 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/components/CanvasComments.tsx b/src/components/CanvasComments.tsx index 3337661de..20482df04 100644 --- a/src/components/CanvasComments.tsx +++ b/src/components/CanvasComments.tsx @@ -52,6 +52,8 @@ export function CanvasComments({ const canvasId = useStore((s) => s.canvas?.id) const pageId = useStore((s) => (s.canvas ? (s.activePageId ?? canvasPages(s.canvas)[0]!.id) : null)) const all = useStore((s) => s.comments) + /* ⇧C hides the pins; an open thread stays */ + const commentsHidden = useStore((s) => s.commentsHidden) /* only thread roots get a pin; replies live inside the root's popover */ const roots = all.filter( (c): c is CanvasComment => isCanvasComment(c) && c.pageId === pageId && !c.parentId && !c.resolvedAt, @@ -126,6 +128,7 @@ export function CanvasComments({ const replies = all.filter((r) => r.parentId === c.id).sort((a, b) => a.at - b.at) const thread: [ElementComment, ...ElementComment[]] = [c, ...replies] const open = openThread === c.id + if (commentsHidden && !open) return null return ( 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/Cursors.tsx b/src/components/Cursors.tsx index 255bd9888..c4be33918 100644 --- a/src/components/Cursors.tsx +++ b/src/components/Cursors.tsx @@ -11,6 +11,9 @@ export const Cursors = memo(function Cursors() { const peerViewports = useStore((s) => s.peerViewports) const activePageId = useStore((s) => s.activePageId) const me = getIdentity().clientId + /* ⌥⌘\ hides everyone else's pointer */ + const hidden = useStore((s) => s.cursorsHidden) + if (hidden) return null return ( <> diff --git a/src/components/FindBar.tsx b/src/components/FindBar.tsx new file mode 100644 index 000000000..f0c698ed9 --- /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) 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/FrameView.tsx b/src/components/FrameView.tsx index 84f827c32..36fffcde4 100644 --- a/src/components/FrameView.tsx +++ b/src/components/FrameView.tsx @@ -783,6 +783,8 @@ export const FrameView = memo(function FrameView({ /* ---- element comments ---- */ const frameComments = useStore((s) => s.comments).filter((c) => c.frameId === frame.id) + /* ⇧C hides the pins; an open thread stays */ + const commentsHidden = useStore((s) => s.commentsHidden) /* only thread roots get a pin; replies live inside the root's popover */ const comments = frameComments.filter((c) => !c.parentId && !c.resolvedAt) const [probe, setProbe] = useState(null) @@ -1904,6 +1906,7 @@ export const FrameView = memo(function FrameView({ const pos = isFrameComment(c) ? { x: c.x, y: c.y } : elementCommentPosition(c, pinPos[c.id]) if (!pos) return null const open = openThread === c.id + if (commentsHidden && !open) return null const replies = frameComments.filter((r) => r.parentId === c.id).reverse() // store is newest-first const thread: [ElementComment, ...ElementComment[]] = [c, ...replies.sort((a, b) => a.at - b.at)] return ( 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..dcd9f224d --- /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 9d4ead855..f202e58f3 100644 --- a/src/components/Stage.tsx +++ b/src/components/Stage.tsx @@ -696,43 +696,10 @@ 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. */ - useEffect(() => { - function onKey(e: KeyboardEvent) { - const t = e.target as HTMLElement - if (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable) 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. 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/dropdown-menu.tsx b/src/components/ui/dropdown-menu.tsx index 848bcb424..1f092f36d 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 @@ -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..35550db36 --- /dev/null +++ b/src/lib/actions/chords.ts @@ -0,0 +1,94 @@ +/* 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 + const wantMeta = mac ? !!chord.mod : false + const wantCtrl = mac ? !!chord.ctrl : !!chord.mod || !!chord.ctrl + if (e.metaKey !== wantMeta || e.ctrlKey !== wantCtrl) 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..3d0dd58f1 --- /dev/null +++ b/src/lib/actions/edits.ts @@ -0,0 +1,673 @@ +/* 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 { + buildLayerTree, + elementPath, + findLayer, + groupElements, + isElementHidden, + setElementLink, + 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 + return editElementGeometry(p.frame.id, selector, { + kind: 'move', + x: info.geometry.x + dx, + y: info.geometry.y + dy, + }) + }), + ) + 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 + const name = kind === 'group' ? t('actions.groupName') : t('actions.frameName') + const grouped = groupElements(p.frame.html, p.selectors, { name }) + if (!grouped) { + notice(t('actions.groupFailed')) + return true + } + saveFrameHtml(p.frame, grouped.html) + pickAfterRewrite(p.frame, [grouped.selector]) + return true +} + +/** ⇧⌘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` }) + await Promise.all(children.map((child) => styleElement(frame.id, child, { [lead]: '0px', [trail]: '0px' }))) + 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 = useStore.getState().canvas?.frames.find((f) => f.id === frame.id) ?? frame + 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 { + return styleEach({ display: null, 'flex-direction': null, gap: 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 (or wraps) one. */ +export function pickedLink(): string | null { + const p = pickedLayers() + if (!p) return null + const doc = new DOMParser().parseFromString(p.frame.html, 'text/html') + let el: Element | null = null + try { + el = doc.querySelector(p.selectors[p.selectors.length - 1]!) + } catch { + return null + } + const a = + el?.tagName === 'A' + ? el + : el?.children.length === 1 && el.firstElementChild?.tagName === 'A' + ? el.firstElementChild + : null + return a?.getAttribute('href') ?? null +} + +/** ⇧⌘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 + let html = p.frame.html + for (const selector of p.selectors) { + if (isLayerLocked(p.frame, selector)) continue + html = setElementLink(html, selector, href) ?? html + } + if (html === p.frame.html) return false + saveFrameHtml(p.frame, html) + pickAfterRewrite(p.frame, p.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 tree = buildLayerTree(p.frame.html) + const node = findLayer(tree, primary) + if (!node) return false + const parentPath = primary.includes(' > ') ? primary.slice(0, primary.lastIndexOf(' > ')) : null + const siblings = parentPath ? (findLayer(tree, parentPath)?.children ?? tree) : tree + const others = siblings.filter((n) => !n.locked && !p.selectors.includes(n.selector)).map((n) => n.selector) + if (!others.length) return false + 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) + if (!others.length) return false + s.pickElement(null) + s.selectMany(others) + return true +} + +/** ⌥⌘A: every layer in the frame shaped like the picked one — the same tag + * and the same classes — the matching layers. */ +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 tree = buildLayerTree(p.frame.html) + const primary = s.selectedElement!.selector + const parentPath = primary.includes(' > ') ? primary.slice(0, primary.lastIndexOf(' > ')) : null + const siblings = parentPath ? (findLayer(tree, parentPath)?.children ?? tree) : tree + const others = 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..60b7140f8 --- /dev/null +++ b/src/lib/actions/findText.ts @@ -0,0 +1,103 @@ +/* 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 } 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 +} + +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 +} + +/** Every offset of `query` in `text`, left to right, never overlapping. */ +function offsetsIn(text: string, query: string, matchCase: boolean): number[] { + if (!query) return [] + const hay = matchCase ? text : text.toLowerCase() + const needle = matchCase ? query : query.toLowerCase() + const out: number[] = [] + for (let at = hay.indexOf(needle); at !== -1; at = hay.indexOf(needle, at + needle.length)) out.push(at) + return out +} + +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 of offsetsIn(text, query, matchCase)) { + out.push({ + selector: elementPath(parent), + before: text.slice(Math.max(0, at - CONTEXT), at).trimStart(), + text: text.slice(at, at + query.length), + after: text.slice(at + query.length, at + query.length + CONTEXT).trimEnd(), + }) + } + } + return out +} + +/** The frame's HTML with `query` replaced: every match, or only the + * `only`-th (0-based, in the order `findInHtml` lists them). 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 = offsetsIn(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, i) => ({ at, n: seen + i })) + .filter(({ n }) => only === undefined || n === only) + .reverse() + seen += offsets.length + for (const { at } of picked) { + node.replaceData(at, query.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..7b4164c34 --- /dev/null +++ b/src/lib/actions/registry.ts @@ -0,0 +1,1049 @@ +/* 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 + +/** The canvas page installs itself as the host while it is mounted. */ +export function setActionHost(next: ActionHost | null) { + host = next +} + +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')], run: () => 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: 'comments', + label: 'actions.comments', + menu: 'view', + section: 0, + keys: [{ key: 'c', shift: true }], + checked: () => !store().commentsHidden, + run: () => store().toggleCommentsHidden(), + }, + { + 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().cursorsHidden, + run: () => store().toggleCursorsHidden(), + }, + { + 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() +} + +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/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..d416a7ae8 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 { deleteFramesTracked, recordCreates } 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,43 @@ 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 +} + +/** ⇧⌘R on frames: the copied frames land at each selected frame's top-left, + * and the selected frames go once they have. */ +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 + void createFrames( + replaceable.flatMap((target) => + frames.map((f) => ({ + canvasId, + frame: { + 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 } : {}), + }, + })), + ), + ).then((created) => { + if (created.length) deleteFramesTracked(replaceable) + }) + 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/i18n/en/actions.ts b/src/lib/i18n/en/actions.ts new file mode 100644 index 000000000..c96b21fe1 --- /dev/null +++ b/src/lib/i18n/en/actions.ts @@ -0,0 +1,162 @@ +/** 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', + 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', + 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 6b96a7014..dd2a05e18 100644 --- a/src/lib/i18n/en/canvas.ts +++ b/src/lib/i18n/en/canvas.ts @@ -82,8 +82,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/pt-BR/actions.ts b/src/lib/i18n/pt-BR/actions.ts new file mode 100644 index 000000000..59815ea46 --- /dev/null +++ b/src/lib/i18n/pt-BR/actions.ts @@ -0,0 +1,162 @@ +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', + 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', + 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 35fccc127..427823a0a 100644 --- a/src/lib/i18n/pt-BR/canvas.ts +++ b/src/lib/i18n/pt-BR/canvas.ts @@ -82,8 +82,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 c69bcbe96..ae61490bf 100644 --- a/src/lib/layers.ts +++ b/src/lib/layers.ts @@ -745,3 +745,152 @@ 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) } +} + +/** The frame's HTML with the element linked to `href`: a link gets the new + * target, anything else has its content wrapped in one. Null `href` takes a + * link off (the link element, or the one link wrapping the element's + * content, gives way to its content). Null when the selector no longer + * resolves or there is nothing to unlink. */ +export function setElementLink(html: string, selector: string, href: string | null): string | null { + const doc = parse(html) + const el = find(doc, selector) + if (!el || el === doc.body) return null + const only = el.childNodes.length === 1 && el.firstElementChild?.tagName === 'A' ? el.firstElementChild : null + const link = el.tagName === 'A' ? el : only + if (href === null) { + if (!link) return null + 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 serialize(doc) + } + if (link) link.setAttribute('href', href) + else { + const a = doc.createElement('a') + a.setAttribute('href', href) + a.append(...el.childNodes) + el.append(a) + } + return serialize(doc) +} + +/** 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 390cd34a2..8a829e667 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' export interface Viewport { x: number @@ -119,6 +120,14 @@ interface State { rulers: boolean /** the ruler guide clicked last, which Delete removes */ selectedGuideId: string | null + /** ⇧C — comment pins hidden on the canvas (the Comments tab still lists them) */ + commentsHidden: boolean + /** ⌥⌘\ — other people's cursors hidden */ + cursorsHidden: boolean + /** ⌘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 @@ -150,7 +159,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 @@ -259,6 +268,10 @@ interface State { setViewport(v: Viewport): void setSnapGuides(guides: SnapGuide[]): void toggleRulers(): void + toggleCommentsHidden(): void + toggleCursorsHidden(): 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 @@ -329,6 +342,10 @@ export const useStore = create((set, get) => ({ snapGuides: [], rulers: readRulers(), selectedGuideId: null, + commentsHidden: false, + cursorsHidden: false, + outlines: false, + layersCollapseAt: 0, connected: false, canvasNotFound: false, signInRequired: false, @@ -728,6 +745,14 @@ export const useStore = create((set, get) => ({ } return { rulers: !s.rulers, ...(s.rulers ? { selectedGuideId: null } : {}) } }), + toggleCommentsHidden: () => set((s) => ({ commentsHidden: !s.commentsHidden })), + toggleCursorsHidden: () => set((s) => ({ cursorsHidden: !s.cursorsHidden })), + toggleOutlines: () => + set((s) => { + setOutlines(!s.outlines) + return { outlines: !s.outlines } + }), + requestCollapseLayers: () => set({ layersCollapseAt: Date.now() }), selectGuide: (selectedGuideId) => set((s) => (s.selectedGuideId === selectedGuideId ? s : { selectedGuideId })), setGuideLocal: (id, guide) => set((s) => { 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 && (