Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(fig): Figma shortcut parity, design palette, and no blank canvas on resize (#7509)

Jacob Beckermand4f140448725
diff --git a/apps/web/src/features/block-fig/browser-test/README.md b/apps/web/src/features/block-fig/browser-test/README.md
index 994e1f4968..10454d76af 100644
--- a/apps/web/src/features/block-fig/browser-test/README.md
+++ b/apps/web/src/features/block-fig/browser-test/README.md
@@ -52,7 +52,10 @@ constraints, resizing several layers and rotating one, components
detaching), adding pages, and read-only access. `fig-shapes` covers
boolean operations and flattening, drawing with the pen and editing
points, SVG export (compared with the PNG) and Copy as SVG, and copying
-layers into another file through the system clipboard. `fig-design-ui` covers
+layers into another file through the system clipboard. `fig-shortcuts`
+covers the pencil (⇧P), the design palette (⌘P, which never prints), ⌘. for
+the UI, aligning and distributing, opacity digits, and swapping fill and
+stroke. `fig-design-ui` covers
the right-click menus, the color and paint pickers (gradients, dashes,
reordering paints), mixed values for several layers, and the layers
panel's range selection and arrow keys. `text-editing` covers the caret
diff --git a/apps/web/src/features/block-fig/browser-test/fig-shortcuts.browser.e2e.ts b/apps/web/src/features/block-fig/browser-test/fig-shortcuts.browser.e2e.ts
new file mode 100644
index 0000000000..99a2dd4988
--- /dev/null
+++ b/apps/web/src/features/block-fig/browser-test/fig-shortcuts.browser.e2e.ts
@@ -0,0 +1,220 @@
+import { expect, type Page, test } from '@playwright/test';
+
+// Figma's shortcuts beyond the basics: the pencil, the actions menu (⌘P),
+// ⌘. for the UI, aligning and distributing, opacity digits, and swapping
+// fill and stroke. The fixture runs on Linux, so ⌘ is Ctrl here. New
+// designs open at 100% with the page origin at the canvas's top left.
+
+async function openNew(page: Page) {
+ await page.goto('/?new&reload');
+ await expect(page.getByTestId('fig-viewer')).toBeVisible();
+ await expect(page.getByTestId('fig-tool-rectangle')).toBeVisible();
+}
+
+async function canvasBox(page: Page) {
+ const box = await page.getByTestId('fig-canvas').boundingBox();
+ if (!box) throw new Error('The canvas is not visible.');
+ return box;
+}
+
+async function dragOnCanvas(
+ page: Page,
+ from: [number, number],
+ to: [number, number]
+) {
+ const box = await canvasBox(page);
+ await page.mouse.move(box.x + from[0], box.y + from[1]);
+ await page.mouse.down();
+ await page.mouse.move(box.x + to[0], box.y + to[1], { steps: 8 });
+ await page.mouse.up();
+}
+
+/** A rectangle from `x`, 100 px down, `w` wide and 50 tall. */
+async function drawRectangle(page: Page, x: number, w: number, name: string) {
+ const canvas = page.getByTestId('fig-canvas');
+ await canvas.focus();
+ await page.keyboard.press('r');
+ await dragOnCanvas(page, [x, 100], [x + w, 150]);
+ await expect(page.getByTestId('fig-name')).toHaveValue(name);
+ await canvas.focus();
+}
+
+/** The selected layer's properties, from the engine. */
+const selectedInfo = (page: Page, name: string) =>
+ page.evaluate(async (n) => {
+ const engine = window.figFixture.engine();
+ const [hit] = (await engine?.search(0, n)) ?? [];
+ return hit ? engine?.nodeInfo(0, hit.id) : undefined;
+ }, name);
+
+const errors = (page: Page) => page.evaluate(() => window.figFixture.errors());
+
+test('draws freehand with the pencil (⇧P)', async ({ page }) => {
+ await openNew(page);
+ const canvas = page.getByTestId('fig-canvas');
+ await canvas.focus();
+ await page.keyboard.press('Shift+P');
+ await expect(page.getByTestId('fig-tool-pencil')).toHaveAttribute(
+ 'aria-pressed',
+ 'true'
+ );
+ // A curve: down, across, and up again.
+ const box = await canvasBox(page);
+ await page.mouse.move(box.x + 100, box.y + 100);
+ await page.mouse.down();
+ for (let i = 1; i <= 40; i++) {
+ const t = i / 40;
+ await page.mouse.move(
+ box.x + 100 + t * 200,
+ box.y + 100 + Math.sin(t * Math.PI) * 120
+ );
+ }
+ await page.mouse.up();
+ await expect(page.getByTestId('fig-layer-row')).toHaveText(['Vector 1']);
+ await expect(page.getByTestId('fig-field-x')).toHaveValue('100');
+ // Simplified: far fewer points than were drawn, still a curve.
+ const network = await page.evaluate(async () => {
+ const engine = window.figFixture.engine();
+ const [hit] = (await engine?.search(0, 'Vector 1')) ?? [];
+ return hit && engine?.vectorNetwork(0, hit.id);
+ });
+ expect(network?.vertices.length).toBeGreaterThan(2);
+ expect(network?.vertices.length).toBeLessThan(20);
+ expect(network?.regions).toEqual([]);
+ // The pencil stays chosen, as in Figma; Escape goes back to Move.
+ await expect(page.getByTestId('fig-tool-pencil')).toHaveAttribute(
+ 'aria-pressed',
+ 'true'
+ );
+ await canvas.focus();
+ await page.keyboard.press('Escape');
+ await expect(page.getByTestId('fig-tool-move')).toHaveAttribute(
+ 'aria-pressed',
+ 'true'
+ );
+ // P is still the pen.
+ await page.keyboard.press('p');
+ await expect(page.getByTestId('fig-tool-pen')).toHaveAttribute(
+ 'aria-pressed',
+ 'true'
+ );
+ await expect.poll(() => errors(page)).toEqual([]);
+});
+
+test('runs actions from the actions menu (⌘P)', async ({ page }) => {
+ await openNew(page);
+ const canvas = page.getByTestId('fig-canvas');
+ await canvas.focus();
+ const printed = await page.evaluateHandle(() => {
+ const seen = { prevented: [] as boolean[] };
+ // After the viewer's own listener (capturing on the window too, it
+ // stops the event going further).
+ window.addEventListener(
+ 'keydown',
+ (e) => {
+ if (e.code === 'KeyP') seen.prevented.push(e.defaultPrevented);
+ },
+ true
+ );
+ return seen;
+ });
+ await page.keyboard.press('Control+p');
+ const palette = page.getByTestId('fig-actions');
+ await expect(palette).toBeVisible();
+ // The browser does not print.
+ expect(await printed.evaluate((s) => s.prevented)).toEqual([true]);
+ await expect(page.getByTestId('fig-actions-input')).toBeFocused();
+ await page.keyboard.type('ellip');
+ await expect(page.getByTestId('fig-action-tool-ellipse')).toBeVisible();
+ await page.keyboard.press('Enter');
+ await expect(palette).toBeHidden();
+ await expect(page.getByTestId('fig-tool-ellipse')).toHaveAttribute(
+ 'aria-pressed',
+ 'true'
+ );
+ // Back on the canvas: its keys work again.
+ await page.keyboard.press('v');
+ await expect(page.getByTestId('fig-tool-move')).toHaveAttribute(
+ 'aria-pressed',
+ 'true'
+ );
+ // Escape closes it; ⌘P again too.
+ await page.keyboard.press('Control+p');
+ await expect(palette).toBeVisible();
+ await page.keyboard.press('Escape');
+ await expect(palette).toBeHidden();
+ await page.keyboard.press('Control+p');
+ await expect(palette).toBeVisible();
+ await page.keyboard.press('Control+p');
+ await expect(palette).toBeHidden();
+});
+
+test('hides and shows the UI with ⌘.', async ({ page }) => {
+ await openNew(page);
+ await page.getByTestId('fig-canvas').focus();
+ await expect(page.getByTestId('fig-layers-panel')).toBeVisible();
+ await page.keyboard.press('Control+.');
+ await expect(page.getByTestId('fig-layers-panel')).toBeHidden();
+ await page.keyboard.press('Control+.');
+ await expect(page.getByTestId('fig-layers-panel')).toBeVisible();
+});
+
+test('aligns, distributes, sets opacity, and swaps fill and stroke', async ({
+ page,
+}) => {
+ await openNew(page);
+ await drawRectangle(page, 100, 40, 'Rectangle 1');
+ await drawRectangle(page, 160, 60, 'Rectangle 2');
+ await drawRectangle(page, 400, 20, 'Rectangle 3');
+ await page.keyboard.press('Control+a');
+ await expect(page.getByTestId('fig-design-panel')).toContainText(
+ '3 layers selected'
+ );
+ // Spans 100–420 with 120 of width: 100 between each.
+ await page.keyboard.press('Control+Alt+h');
+ await expect
+ .poll(async () => (await selectedInfo(page, 'Rectangle 2'))?.x)
+ .toBe(240);
+ // ⌥A lines up their left edges.
+ await page.keyboard.press('Alt+a');
+ await expect
+ .poll(async () => (await selectedInfo(page, 'Rectangle 3'))?.x)
+ .toBe(100);
+
+ // One layer: digits set its opacity, two quick ones exactly.
+ await page
+ .getByTestId('fig-layer-row')
+ .filter({ hasText: 'Rectangle 1' })
+ .click();
+ await expect(page.getByTestId('fig-name')).toHaveValue('Rectangle 1');
+ await page.getByTestId('fig-canvas').focus();
+ await page.keyboard.press('5');
+ await expect
+ .poll(async () => (await selectedInfo(page, 'Rectangle 1'))?.opacity)
+ .toBeCloseTo(0.5);
+ // A digit typed later starts over (one soon after would make 54%).
+ await page.waitForTimeout(800);
+ await page.keyboard.press('4');
+ await page.keyboard.press('5');
+ await expect
+ .poll(async () => (await selectedInfo(page, 'Rectangle 1'))?.opacity)
+ .toBeCloseTo(0.45);
+ await page.waitForTimeout(800);
+ await page.keyboard.press('0');
+ await expect
+ .poll(async () => (await selectedInfo(page, 'Rectangle 1'))?.opacity)
+ .toBe(1);
+
+ // ⇧X: the gray fill becomes the stroke.
+ await page.keyboard.press('Shift+X');
+ await expect
+ .poll(async () => {
+ const info = await selectedInfo(page, 'Rectangle 1');
+ return {
+ fills: info?.fills.length,
+ stroke: info?.strokes[0]?.color,
+ };
+ })
+ .toEqual({ fills: 0, stroke: 'D9D9D9' });
+ await expect.poll(() => errors(page)).toEqual([]);
+});
diff --git a/apps/web/src/features/block-fig/browser-test/fig-viewer.browser.e2e.ts b/apps/web/src/features/block-fig/browser-test/fig-viewer.browser.e2e.ts
index 69719abcc5..c48d95d42c 100644
--- a/apps/web/src/features/block-fig/browser-test/fig-viewer.browser.e2e.ts
+++ b/apps/web/src/features/block-fig/browser-test/fig-viewer.browser.e2e.ts
@@ -576,3 +576,39 @@ test('is read-only without edit access', async ({ page }) => {
await page.keyboard.press('ArrowDown');
await expect(page.getByTestId('fig-design-panel')).toContainText('Home');
});
+
+test('stays drawn while its split resizes', async ({ page }) => {
+ await open(page);
+ // As when the app's sidebar opens or closes: the viewer narrows, then
+ // widens again. The canvas is read right after each frame is painted.
+ const painted = await page.evaluate(async () => {
+ const viewer = document.querySelector<HTMLElement>(
+ '[data-testid="fig-viewer"]'
+ );
+ const canvas = document.querySelector<HTMLCanvasElement>(
+ '[data-testid="fig-canvas"] canvas'
+ );
+ const host = viewer?.parentElement;
+ if (!host || !canvas) return [];
+ const corner = () => {
+ const ctx = canvas.getContext('2d');
+ const at = ctx?.getImageData(1, 1, 1, 1).data;
+ return at ? [at[0], at[1], at[2]] : [];
+ };
+ const afterPaint = () =>
+ new Promise<void>((resolve) =>
+ requestAnimationFrame(() => setTimeout(resolve, 0))
+ );
+ const out: number[][] = [];
+ const width = host.getBoundingClientRect().width;
+ for (const w of [width - 200, width - 120, width]) {
+ host.style.width = `${w}px`;
+ await afterPaint();
+ out.push(corner());
+ }
+ return out;
+ });
+ expect(painted).toHaveLength(3);
+ // Never cleared to black: the page's light background shows.
+ for (const [r, g, b] of painted) expect(r + g + b).toBeGreaterThan(600);
+});
diff --git a/apps/web/src/features/block-fig/components/actions-palette.tsx b/apps/web/src/features/block-fig/components/actions-palette.tsx
new file mode 100644
index 0000000000..46e00eee61
--- /dev/null
+++ b/apps/web/src/features/block-fig/components/actions-palette.tsx
@@ -0,0 +1,146 @@
+/**
+ * The actions menu (⌘P, as Figma's quick actions): every action with a
+ * shortcut, searched by name, run with Enter. It opens above the toolbar.
+ */
+
+import MagnifyingGlass from '@phosphor/magnifying-glass.svg';
+import { createSignal, For, onMount, Show } from 'solid-js';
+import { paletteActions } from '../core/palette';
+import type { ViewerAction } from '../core/shortcuts';
+
+export function ActionsPalette(props: {
+ mac: boolean;
+ /** Whether an action can run now (edits need an editable file). */
+ available: (action: ViewerAction) => boolean;
+ onRun: (action: ViewerAction) => void;
+ /** `refocus`: closed from the menu itself (not by focus leaving it). */
+ onClose: (refocus: boolean) => void;
+}) {
+ const [query, setQuery] = createSignal('');
+ const [active, setActive] = createSignal(0);
+ let input!: HTMLInputElement;
+ let list!: HTMLDivElement;
+
+ const results = () =>
+ paletteActions(query()).filter((a) => props.available(a.id));
+ const keysFor = (keys: string[], other?: string[]) =>
+ (!props.mac && other ? other : keys).map((k) =>
+ k === 'mod' ? (props.mac ? '⌘' : 'Ctrl') : k
+ );
+
+ const search = (text: string) => {
+ setQuery(text);
+ setActive(0);
+ };
+ const move = (step: number) => {
+ const count = results().length;
+ if (count === 0) return;
+ const next = (active() + step + count) % count;
+ setActive(next);
+ list
+ .querySelector(`[data-index="${next}"]`)
+ ?.scrollIntoView({ block: 'nearest' });
+ };
+ const choose = (action: ViewerAction | undefined) => {
+ if (!action) return;
+ props.onClose(true);
+ props.onRun(action);
+ };
+
+ const onKeyDown = (e: KeyboardEvent) => {
+ if (e.isComposing) return;
+ const handled = () => {
+ e.preventDefault();
+ e.stopPropagation();
+ };
+ if (e.key === 'ArrowDown') {
+ handled();
+ move(1);
+ } else if (e.key === 'ArrowUp') {
+ handled();
+ move(-1);
+ } else if (e.key === 'Enter') {
+ handled();
+ choose(results()[active()]?.id);
+ } else if (e.key === 'Escape') {
+ handled();
+ props.onClose(true);
+ }
+ };
+
+ onMount(() => input.focus({ preventScroll: true }));
+
+ return (
+ <div
+ role="dialog"
+ aria-label="Actions"
+ data-testid="fig-actions"
+ class="absolute inset-x-4 bottom-16 z-20 mx-auto flex max-h-[60%] max-w-md flex-col overflow-hidden rounded-xl border border-edge-muted bg-menu text-ink text-xs shadow-xl"
+ onPointerDown={(e) => e.stopPropagation()}
+ onFocusOut={(e) => {
+ const next = e.relatedTarget as Node | null;
+ if (!next || !e.currentTarget.contains(next)) props.onClose(false);
+ }}
+ >
+ <div class="flex items-center gap-2 border-edge-muted border-b px-3 py-2">
+ <MagnifyingGlass class="size-3.5 shrink-0 text-ink-muted" />
+ <input
+ ref={input}
+ type="text"
+ role="combobox"
+ aria-expanded="true"
+ aria-controls="fig-actions-list"
+ aria-activedescendant={`fig-action-${active()}`}
+ placeholder="Search actions"
+ class="min-w-0 flex-1 bg-transparent text-ink outline-none placeholder:text-ink-placeholder"
+ data-testid="fig-actions-input"
+ value={query()}
+ onInput={(e) => search(e.currentTarget.value)}
+ onKeyDown={onKeyDown}
+ />
+ </div>
+ <div
+ ref={list}
+ id="fig-actions-list"
+ role="listbox"
+ class="min-h-0 flex-1 overflow-y-auto p-1"
+ >
+ <For each={results()}>
+ {(item, index) => (
+ <div
+ id={`fig-action-${index()}`}
+ role="option"
+ aria-selected={index() === active()}
+ data-index={index()}
+ data-testid={`fig-action-${item.id}`}
+ class="flex items-center justify-between gap-3 rounded-md px-2 py-1.5"
+ classList={{ 'bg-hover': index() === active() }}
+ onPointerMove={() => setActive(index())}
+ onPointerDown={(e) => e.preventDefault()}
+ onClick={() => choose(item.id)}
+ >
+ <span class="min-w-0 truncate">
+ {item.label}
+ <span class="ml-2 text-ink-muted">{item.group}</span>
+ </span>
+ <span class="flex shrink-0 gap-0.5">
+ <For each={keysFor(item.keys, item.otherKeys)}>
+ {(k) => (
+ <kbd class="rounded border border-edge-muted bg-inset px-1 font-sans">
+ {k}
+ </kbd>
+ )}
+ </For>
+ </span>
+ </div>
+ )}
+ </For>
+ <Show when={results().length === 0}>
+ <div class="px-2 py-3 text-center text-ink-muted">
+ No matching actions
+ </div>
+ </Show>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/block-fig/components/overlay.ts b/apps/web/src/features/block-fig/components/overlay.ts
index a3f10d5c70..34ac38c5d1 100644
--- a/apps/web/src/features/block-fig/components/overlay.ts
+++ b/apps/web/src/features/block-fig/components/overlay.ts
@@ -70,6 +70,8 @@ export interface VectorOverlay {
pending?: boolean;
/** A press would close the path on its first point. */
closing?: boolean;
+ /** A pencil stroke being drawn: the path only, no points. */
+ stroke?: boolean;
}
const LABEL_TYPES = new Set(['FRAME', 'SYMBOL', 'SECTION', 'INSTANCE']);
@@ -346,6 +348,7 @@ function drawVector(ctx: CanvasRenderingContext2D, m: OverlayModel) {
ctx.bezierCurveTo(c1.x, c1.y, c2.x, c2.y, b.x, b.y);
}
ctx.stroke();
+ if (v.stroke) return;
const dot = (p: { x: number; y: number }, r: number, fill: string) => {
const q = screen(p);
ctx.beginPath();
diff --git a/apps/web/src/features/block-fig/components/shortcuts-dialog.tsx b/apps/web/src/features/block-fig/components/shortcuts-dialog.tsx
index 7e68c4328e..6355450cbe 100644
--- a/apps/web/src/features/block-fig/components/shortcuts-dialog.tsx
+++ b/apps/web/src/features/block-fig/components/shortcuts-dialog.tsx
@@ -35,7 +35,13 @@ export function ShortcutsDialog(props: { mac: boolean; onClose: () => void }) {
<div class="flex items-center justify-between gap-2 py-0.5">
<span>{item.action}</span>
<span class="flex gap-0.5">
- <For each={item.keys}>
+ <For
+ each={
+ !props.mac && item.otherKeys
+ ? item.otherKeys
+ : item.keys
+ }
+ >
{(k) => (
<kbd class="rounded border border-edge-muted bg-inset px-1 font-sans">
{cap(k)}
diff --git a/apps/web/src/features/block-fig/components/viewer-toolbar.tsx b/apps/web/src/features/block-fig/components/viewer-toolbar.tsx
index 0e75644141..632db8e56e 100644
--- a/apps/web/src/features/block-fig/components/viewer-toolbar.tsx
+++ b/apps/web/src/features/block-fig/components/viewer-toolbar.tsx
@@ -17,6 +17,7 @@ import Keyboard from '@phosphor/keyboard.svg';
import LineSegment from '@phosphor/line-segment.svg';
import NavigationArrow from '@phosphor/navigation-arrow.svg';
import PenNib from '@phosphor/pen-nib.svg';
+import PencilSimple from '@phosphor/pencil-simple.svg';
import Square from '@phosphor/square.svg';
import TextT from '@phosphor/text-t.svg';
import Unite from '@phosphor/unite.svg';
@@ -46,6 +47,13 @@ const TOOLS: ToolButton[] = [
{ tool: 'line', label: 'Line', key: 'L', icon: LineSegment, edit: true },
{ tool: 'arrow', label: 'Arrow', key: '⇧L', icon: ArrowUpRight, edit: true },
{ tool: 'pen', label: 'Pen', key: 'P', icon: PenNib, edit: true },
+ {
+ tool: 'pencil',
+ label: 'Pencil',
+ key: '⇧P',
+ icon: PencilSimple,
+ edit: true,
+ },
{ tool: 'text', label: 'Text', key: 'T', icon: TextT, edit: true },
{ tool: 'hand', label: 'Hand tool', key: 'H', icon: Hand, edit: false },
];
diff --git a/apps/web/src/features/block-fig/context/fig-viewer-context.tsx b/apps/web/src/features/block-fig/context/fig-viewer-context.tsx
index e31a74b102..1d210ca66d 100644
--- a/apps/web/src/features/block-fig/context/fig-viewer-context.tsx
+++ b/apps/web/src/features/block-fig/context/fig-viewer-context.tsx
@@ -102,6 +102,11 @@ export interface FigViewerContext {
fonts?: FigFontSource;
/** Other designs to use as team libraries; absent where there are none. */
libraries?: FigLibrarySource;
+ /**
+ * ⌘K on the canvas opens the app's command menu (not Figma's actions):
+ * offer the design's own actions menu (⌘P) there.
+ */
+ suggestActions?: (openActions: () => void) => void;
}
const Context = createContext<FigViewerContext>();
diff --git a/apps/web/src/features/block-fig/core/align.test.ts b/apps/web/src/features/block-fig/core/align.test.ts
index 97b51add0d..cc49999880 100644
--- a/apps/web/src/features/block-fig/core/align.test.ts
+++ b/apps/web/src/features/block-fig/core/align.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
-import { alignOffset } from './align';
+import { alignOffset, distributeOffsets } from './align';
const box = { x: 10, y: 20, w: 30, h: 40 };
const to = { x: 0, y: 0, w: 100, h: 200 };
@@ -14,3 +14,30 @@ describe('alignment', () => {
expect(alignOffset(box, to, 'bottom')).toEqual({ dx: 0, dy: 140 });
});
});
+
+describe('distributing', () => {
+ const at = (id: string, x: number, w: number) => ({
+ id,
+ bounds: { x, y: 0, w, h: 10 },
+ });
+
+ it('spaces layers evenly between the outermost two', () => {
+ // Spans 0–100 with 60 of width: 20 between each.
+ expect(
+ distributeOffsets(
+ [at('c', 90, 10), at('a', 0, 20), at('b', 25, 30)],
+ 'horizontal'
+ )
+ ).toEqual([
+ { id: 'a', dx: 0, dy: 0 },
+ { id: 'b', dx: 15, dy: 0 },
+ { id: 'c', dx: 0, dy: 0 },
+ ]);
+ });
+
+ it('needs three layers', () => {
+ expect(
+ distributeOffsets([at('a', 0, 10), at('b', 50, 10)], 'vertical')
+ ).toEqual([]);
+ });
+});
diff --git a/apps/web/src/features/block-fig/core/align.ts b/apps/web/src/features/block-fig/core/align.ts
index 98b9b2cf92..228ee637ac 100644
--- a/apps/web/src/features/block-fig/core/align.ts
+++ b/apps/web/src/features/block-fig/core/align.ts
@@ -34,3 +34,28 @@ export function alignOffset(
return { dx: 0, dy: to.y + to.h - (box.y + box.h) };
}
}
+
+/**
+ * Offsets spacing layers evenly between the outermost two along an axis,
+ * as Figma's distribute: three layers at least, ordered by their start.
+ */
+export function distributeOffsets(
+ boxes: { id: string; bounds: Rect }[],
+ axis: 'horizontal' | 'vertical'
+): { id: string; dx: number; dy: number }[] {
+ if (boxes.length < 3) return [];
+ const h = axis === 'horizontal';
+ const start = (r: Rect) => (h ? r.x : r.y);
+ const size = (r: Rect) => (h ? r.w : r.h);
+ const sorted = [...boxes].sort((a, b) => start(a.bounds) - start(b.bounds));
+ const first = sorted[0].bounds;
+ const end = Math.max(...sorted.map((b) => start(b.bounds) + size(b.bounds)));
+ const total = sorted.reduce((sum, b) => sum + size(b.bounds), 0);
+ const gap = (end - start(first) - total) / (sorted.length - 1);
+ let at = start(first);
+ return sorted.map((b) => {
+ const d = at - start(b.bounds);
+ at += size(b.bounds) + gap;
+ return { id: b.id, dx: h ? d : 0, dy: h ? 0 : d };
+ });
+}
diff --git a/apps/web/src/features/block-fig/core/paint.test.ts b/apps/web/src/features/block-fig/core/paint.test.ts
index e4a72e9b07..84b3781d58 100644
--- a/apps/web/src/features/block-fig/core/paint.test.ts
+++ b/apps/web/src/features/block-fig/core/paint.test.ts
@@ -3,6 +3,7 @@ import { describe, expect, it } from 'vitest';
import {
addStop,
colorAt,
+ copyPaint,
editPaint,
movePaint,
moveStop,
@@ -100,3 +101,26 @@ describe('dashes', () => {
expect(parseDashes('-1')).toBeNull();
});
});
+
+describe('copying paints between fills and strokes', () => {
+ it('copies solids with their alpha, gradients with stops, and images', () => {
+ expect(copyPaint({ ...paint('FF0000'), alpha: 0.5, opacity: 0.8 })).toEqual(
+ { type: 'SOLID', color: 'FF000080', opacity: 0.8, visible: true }
+ );
+ expect(
+ copyPaint({ ...paint('000000'), type: 'GRADIENT_LINEAR', stops })
+ ).toEqual({
+ type: 'GRADIENT_LINEAR',
+ stops: [
+ { color: 'FF0000', position: 0 },
+ { color: '0000FF00', position: 1 },
+ ],
+ opacity: 1,
+ visible: true,
+ });
+ expect(
+ copyPaint({ ...paint('000000'), type: 'IMAGE', imageHash: 'abc' })
+ ).toEqual({ image: 'abc', opacity: 1, visible: true });
+ expect(copyPaint({ ...paint('000000'), type: 'VIDEO' })).toBeNull();
+ });
+});
diff --git a/apps/web/src/features/block-fig/core/paint.ts b/apps/web/src/features/block-fig/core/paint.ts
index 7432f7d135..06a3f0dd79 100644
--- a/apps/web/src/features/block-fig/core/paint.ts
+++ b/apps/web/src/features/block-fig/core/paint.ts
@@ -162,3 +162,22 @@ export function parseDashes(text: string): number[] | null {
if (parts.every((n) => n === 0)) return [];
return parts.length === 1 ? [parts[0], parts[0]] : parts;
}
+
+/**
+ * A new paint like `p`, for moving it to the other list (Figma's swap fill
+ * and stroke). Gradients keep their stops; unknown kinds are dropped.
+ */
+export function copyPaint(p: PaintInfo): PaintEdit | null {
+ const common = { opacity: p.opacity, visible: p.visible };
+ if (p.type === 'SOLID' && p.color)
+ return {
+ ...common,
+ type: 'SOLID',
+ color: rgbaToHex({ ...hexToRgba(p.color), a: p.alpha ?? 1 }),
+ };
+ if (isGradient(p.type) && p.stops)
+ return { ...common, type: p.type as PaintType, stops: stopSpecs(p.stops) };
+ if (p.type === 'IMAGE' && p.imageHash)
+ return { ...common, image: p.imageHash };
+ return null;
+}
diff --git a/apps/web/src/features/block-fig/core/palette.test.ts b/apps/web/src/features/block-fig/core/palette.test.ts
new file mode 100644
index 0000000000..023133c82d
--- /dev/null
+++ b/apps/web/src/features/block-fig/core/palette.test.ts
@@ -0,0 +1,31 @@
+import { describe, expect, it } from 'vitest';
+import { paletteActions } from './palette';
+import { SHORTCUT_GROUPS } from './shortcuts';
+
+describe('actions menu', () => {
+ it('lists every action with a shortcut, but not itself', () => {
+ const all = paletteActions('');
+ const ids = all.map((a) => a.id);
+ expect(ids).toContain('tool-pencil');
+ expect(ids).toContain('align-left');
+ expect(ids).not.toContain('open-actions');
+ expect(new Set(ids).size).toBe(ids.length);
+ const withIds = SHORTCUT_GROUPS.flatMap((g) => g.items).filter(
+ (i) => i.id && i.id !== 'open-actions'
+ );
+ expect(all).toHaveLength(withIds.length);
+ });
+
+ it('finds actions by the starts of words in their names and groups', () => {
+ expect(paletteActions('penc').map((a) => a.id)).toEqual(['tool-pencil']);
+ expect(paletteActions('align bot').map((a) => a.id)).toEqual([
+ 'align-bottom',
+ ]);
+ expect(paletteActions('zoom').every((a) => a.group === 'Zoom')).toBe(true);
+ expect(paletteActions('xyzzy')).toEqual([]);
+ });
+
+ it('puts names starting with the query first', () => {
+ expect(paletteActions('flip')[0]?.label.startsWith('Flip')).toBe(true);
+ });
+});
diff --git a/apps/web/src/features/block-fig/core/palette.ts b/apps/web/src/features/block-fig/core/palette.ts
new file mode 100644
index 0000000000..61a1490faa
--- /dev/null
+++ b/apps/web/src/features/block-fig/core/palette.ts
@@ -0,0 +1,51 @@
+/**
+ * The actions menu's entries: the shortcut panel's actions, found by the
+ * words of their names (and their group's).
+ */
+
+import { SHORTCUT_GROUPS, type ViewerAction } from './shortcuts';
+
+export interface PaletteAction {
+ id: ViewerAction;
+ label: string;
+ group: string;
+ keys: string[];
+ otherKeys?: string[];
+}
+
+/** The actions menu itself is not one of its entries. */
+const ALL: PaletteAction[] = SHORTCUT_GROUPS.flatMap((g) =>
+ g.items.flatMap((item) =>
+ item.id && item.id !== 'open-actions'
+ ? [
+ {
+ id: item.id,
+ label: item.action,
+ group: g.title,
+ keys: item.keys,
+ otherKeys: item.otherKeys,
+ },
+ ]
+ : []
+ )
+);
+
+/**
+ * The entries matching `query`: every word starts a word of the name or
+ * the group. Names starting with the query come first.
+ */
+export function paletteActions(query: string): PaletteAction[] {
+ const words = query.toLowerCase().split(/\s+/).filter(Boolean);
+ if (words.length === 0) return ALL;
+ const matches = ALL.filter((a) => {
+ const haystack = `${a.label} ${a.group}`
+ .toLowerCase()
+ .split(/[^a-z0-9%]+/)
+ .filter(Boolean);
+ return words.every((w) => haystack.some((h) => h.startsWith(w)));
+ });
+ const q = query.trim().toLowerCase();
+ const leading = (a: PaletteAction) =>
+ a.label.toLowerCase().startsWith(q) ? 0 : 1;
+ return [...matches].sort((a, b) => leading(a) - leading(b));
+}
diff --git a/apps/web/src/features/block-fig/core/shortcuts.test.ts b/apps/web/src/features/block-fig/core/shortcuts.test.ts
index c9d9732887..986728b335 100644
--- a/apps/web/src/features/block-fig/core/shortcuts.test.ts
+++ b/apps/web/src/features/block-fig/core/shortcuts.test.ts
@@ -238,3 +238,94 @@ describe('focused controls and text fields', () => {
expect(controlOwnsKey('SELECT', k('z', true))).toBe(false);
});
});
+
+describe('Figma shortcuts added for parity', () => {
+ it('opens the actions menu with ⌘P and ⌘/ (never printing)', () => {
+ expect(shortcutAction(key('p', 'KeyP', { metaKey: true }), true)).toBe(
+ 'open-actions'
+ );
+ expect(shortcutAction(key('p', 'KeyP', { ctrlKey: true }), false)).toBe(
+ 'open-actions'
+ );
+ expect(shortcutAction(key('/', 'Slash', { metaKey: true }), true)).toBe(
+ 'open-actions'
+ );
+ });
+
+ it('leaves ⌘K to the app’s command menu', () => {
+ expect(
+ shortcutAction(key('k', 'KeyK', { metaKey: true }), true)
+ ).toBeUndefined();
+ expect(
+ shortcutAction(key('k', 'KeyK', { metaKey: true, altKey: true }), true)
+ ).toBe('create-component');
+ });
+
+ it('shows and hides the UI with ⌘. as well as ⌘\\', () => {
+ expect(shortcutAction(key('.', 'Period', { metaKey: true }), true)).toBe(
+ 'toggle-ui'
+ );
+ expect(
+ shortcutAction(key('\\', 'Backslash', { metaKey: true }), true)
+ ).toBe('toggle-ui');
+ });
+
+ it('picks the pencil with ⇧P and the pen with P', () => {
+ expect(shortcutAction(key('P', 'KeyP', { shiftKey: true }), true)).toBe(
+ 'tool-pencil'
+ );
+ expect(shortcutAction(key('p', 'KeyP'), true)).toBe('tool-pen');
+ });
+
+ it('aligns with ⌥ letters, and ⌥ letters on macOS whatever they type', () => {
+ const alt = (k: string, code: string) =>
+ shortcutAction(key(k, code, { altKey: true }), true);
+ expect(alt('å', 'KeyA')).toBe('align-left');
+ expect(alt('˙', 'KeyH')).toBe('align-center');
+ expect(alt('∂', 'KeyD')).toBe('align-right');
+ expect(alt('∑', 'KeyW')).toBe('align-top');
+ expect(alt('√', 'KeyV')).toBe('align-middle');
+ expect(alt('ß', 'KeyS')).toBe('align-bottom');
+ expect(alt('¬', 'KeyL')).toBe('collapse-layers');
+ expect(alt('™', 'Digit2')).toBe('toggle-assets');
+ });
+
+ it('distributes with ⌃⌥H and ⌃⌥V', () => {
+ expect(
+ shortcutAction(key('h', 'KeyH', { ctrlKey: true, altKey: true }), true)
+ ).toBe('distribute-horizontal');
+ expect(
+ shortcutAction(key('v', 'KeyV', { ctrlKey: true, altKey: true }), false)
+ ).toBe('distribute-vertical');
+ });
+
+ it('excludes with ⌥⇧E (and ⌥⇧X)', () => {
+ const mods = { altKey: true, shiftKey: true };
+ expect(shortcutAction(key('E', 'KeyE', mods), true)).toBe(
+ 'boolean-exclude'
+ );
+ expect(shortcutAction(key('X', 'KeyX', mods), true)).toBe(
+ 'boolean-exclude'
+ );
+ });
+
+ it('sets opacity with digits, leaving ⇧digits to zoom', () => {
+ expect(shortcutAction(key('5', 'Digit5'), true)).toBe('opacity-5');
+ expect(shortcutAction(key('0', 'Digit0'), true)).toBe('opacity-0');
+ expect(shortcutAction(key('!', 'Digit1', { shiftKey: true }), true)).toBe(
+ 'zoom-fit'
+ );
+ });
+
+ it('maps swap fill and stroke, place image, and paste to replace', () => {
+ expect(shortcutAction(key('X', 'KeyX', { shiftKey: true }), true)).toBe(
+ 'swap-fill-stroke'
+ );
+ expect(
+ shortcutAction(key('k', 'KeyK', { metaKey: true, shiftKey: true }), true)
+ ).toBe('place-image');
+ expect(
+ shortcutAction(key('r', 'KeyR', { metaKey: true, shiftKey: true }), true)
+ ).toBe('paste-replace');
+ });
+});
diff --git a/apps/web/src/features/block-fig/core/shortcuts.ts b/apps/web/src/features/block-fig/core/shortcuts.ts
index b64f4c6649..85cc5e42bd 100644
--- a/apps/web/src/features/block-fig/core/shortcuts.ts
+++ b/apps/web/src/features/block-fig/core/shortcuts.ts
@@ -35,6 +35,8 @@ export type ViewerAction =
| 'export'
| 'find'
| 'show-shortcuts'
+ | 'open-actions'
+ | 'toggle-assets'
| 'tool-frame'
| 'tool-rectangle'
| 'tool-ellipse'
@@ -42,6 +44,8 @@ export type ViewerAction =
| 'tool-line'
| 'tool-arrow'
| 'tool-pen'
+ | 'tool-pencil'
+ | 'place-image'
| 'undo'
| 'redo'
| 'delete'
@@ -49,6 +53,7 @@ export type ViewerAction =
| 'copy'
| 'cut'
| 'paste'
+ | 'paste-replace'
| 'group'
| 'ungroup'
| 'frame-selection'
@@ -70,6 +75,16 @@ export type ViewerAction =
| 'flip-horizontal'
| 'flip-vertical'
| 'rename'
+ | 'align-left'
+ | 'align-center'
+ | 'align-right'
+ | 'align-top'
+ | 'align-middle'
+ | 'align-bottom'
+ | 'distribute-horizontal'
+ | 'distribute-vertical'
+ | 'swap-fill-stroke'
+ | OpacityAction
| 'nudge-left'
| 'nudge-right'
| 'nudge-up'
@@ -79,6 +94,11 @@ export type ViewerAction =
| 'nudge-up-10'
| 'nudge-down-10';
+type Digit = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9';
+
+/** Figma's opacity keys: 1 is 10%, 0 is 100%; two quick digits, 45%. */
+export type OpacityAction = `opacity-${Digit}`;
+
export interface KeyInput {
key: string;
code: string;
@@ -111,15 +131,32 @@ export function shortcutAction(
)
return 'toggle-layout-grids';
+ // Distribute: ⌃⌥H / ⌃⌥V (Ctrl+Alt elsewhere, where Ctrl is the modifier).
+ if (e.ctrlKey && e.altKey && !e.metaKey && !e.shiftKey) {
+ if (e.code === 'KeyH') return 'distribute-horizontal';
+ if (e.code === 'KeyV') return 'distribute-vertical';
+ }
+
if (e.altKey && !mod && !otherMod) {
- if (e.shiftKey && e.code === 'KeyA') return 'remove-auto-layout';
- if (e.shiftKey && e.code === 'KeyU') return 'boolean-union';
- if (e.shiftKey && e.code === 'KeyS') return 'boolean-subtract';
- if (e.shiftKey && e.code === 'KeyI') return 'boolean-intersect';
- if (e.shiftKey && e.code === 'KeyX') return 'boolean-exclude';
+ if (e.shiftKey) {
+ if (e.code === 'KeyA') return 'remove-auto-layout';
+ if (e.code === 'KeyU') return 'boolean-union';
+ if (e.code === 'KeyS') return 'boolean-subtract';
+ if (e.code === 'KeyI') return 'boolean-intersect';
+ // ⌥⇧E is Figma's; ⌥⇧X is kept for those used to it here.
+ if (e.code === 'KeyE' || e.code === 'KeyX') return 'boolean-exclude';
+ return undefined;
+ }
if (e.code === 'Digit1') return 'toggle-layers';
+ if (e.code === 'Digit2') return 'toggle-assets';
if (e.code === 'Digit8') return 'toggle-design';
if (e.code === 'KeyL') return 'collapse-layers';
+ if (e.code === 'KeyA') return 'align-left';
+ if (e.code === 'KeyH') return 'align-center';
+ if (e.code === 'KeyD') return 'align-right';
+ if (e.code === 'KeyW') return 'align-top';
+ if (e.code === 'KeyV') return 'align-middle';
+ if (e.code === 'KeyS') return 'align-bottom';
return undefined;
}
@@ -140,6 +177,8 @@ export function shortcutAction(
if (e.code === 'KeyG') return 'ungroup';
if (e.code === 'KeyH') return 'toggle-visible';
if (e.code === 'KeyL') return 'toggle-locked';
+ if (e.code === 'KeyK') return 'place-image';
+ if (e.code === 'KeyR') return 'paste-replace';
return undefined;
}
if (e.code === 'KeyZ') return 'undo';
@@ -157,7 +196,10 @@ export function shortcutAction(
if (e.code === 'Minus' || e.code === 'NumpadSubtract') return 'zoom-out';
if (e.code === 'Digit0' || e.code === 'Numpad0') return 'zoom-100';
if (e.code === 'KeyA') return 'select-all';
- if (e.code === 'Backslash') return 'toggle-ui';
+ // Figma takes both ⌘\ and ⌘. for showing and hiding the UI.
+ if (e.code === 'Backslash' || e.code === 'Period') return 'toggle-ui';
+ // The actions menu (the browser's print is not used here).
+ if (e.code === 'KeyP' || e.code === 'Slash') return 'open-actions';
if (e.code === 'KeyY') return 'toggle-outline';
if (e.code === 'KeyF') return 'find';
return undefined;
@@ -165,6 +207,9 @@ export function shortcutAction(
if (!plain) return undefined;
+ if (!e.shiftKey && /^Digit[0-9]$/.test(e.code))
+ return `opacity-${e.code.slice(5) as Digit}`;
+
if (e.shiftKey) {
switch (e.code) {
case 'Digit0':
@@ -183,6 +228,10 @@ export function shortcutAction(
return 'flip-vertical';
case 'KeyL':
return 'tool-arrow';
+ case 'KeyP':
+ return 'tool-pencil';
+ case 'KeyX':
+ return 'swap-fill-stroke';
case 'KeyR':
return 'toggle-rulers';
case 'Quote':
@@ -270,12 +319,15 @@ export const EDIT_ACTIONS: ReadonlySet<ViewerAction> = new Set<ViewerAction>([
'tool-line',
'tool-arrow',
'tool-pen',
+ 'tool-pencil',
+ 'place-image',
'undo',
'redo',
'delete',
'duplicate',
'cut',
'paste',
+ 'paste-replace',
'group',
'ungroup',
'frame-selection',
@@ -297,6 +349,25 @@ export const EDIT_ACTIONS: ReadonlySet<ViewerAction> = new Set<ViewerAction>([
'flip-horizontal',
'flip-vertical',
'rename',
+ 'align-left',
+ 'align-center',
+ 'align-right',
+ 'align-top',
+ 'align-middle',
+ 'align-bottom',
+ 'distribute-horizontal',
+ 'distribute-vertical',
+ 'swap-fill-stroke',
+ 'opacity-0',
+ 'opacity-1',
+ 'opacity-2',
+ 'opacity-3',
+ 'opacity-4',
+ 'opacity-5',
+ 'opacity-6',
+ 'opacity-7',
+ 'opacity-8',
+ 'opacity-9',
'nudge-left',
'nudge-right',
'nudge-up',
@@ -307,103 +378,203 @@ export const EDIT_ACTIONS: ReadonlySet<ViewerAction> = new Set<ViewerAction>([
'nudge-down-10',
]);
+/**
+ * Actions that do nothing without a selection: their keys then go on to
+ * the app (⇧←/⇧→ focus the next split, ⇧⌘C copies the item's link).
+ */
+export const SELECTION_ACTIONS: ReadonlySet<ViewerAction> =
+ new Set<ViewerAction>([
+ 'flip-horizontal',
+ 'flip-vertical',
+ 'copy-png',
+ 'nudge-left',
+ 'nudge-right',
+ 'nudge-up',
+ 'nudge-down',
+ 'nudge-left-10',
+ 'nudge-right-10',
+ 'nudge-up-10',
+ 'nudge-down-10',
+ ]);
+
export interface ShortcutHelp {
action: string;
/** Key caps; `mod` is ⌘ on macOS and Ctrl elsewhere. */
keys: string[];
+ /** Keys elsewhere, when they differ by more than ⌘ for Ctrl. */
+ otherKeys?: string[];
+ /** What it runs, for the actions menu (absent for gestures). */
+ id?: ViewerAction;
}
-/** The shortcuts panel, grouped. */
+/** The shortcuts panel, grouped; the actions menu lists the same. */
export const SHORTCUT_GROUPS: { title: string; items: ShortcutHelp[] }[] = [
{
title: 'Tools',
items: [
- { action: 'Move', keys: ['V'] },
- { action: 'Frame', keys: ['F'] },
- { action: 'Rectangle', keys: ['R'] },
- { action: 'Ellipse', keys: ['O'] },
- { action: 'Line', keys: ['L'] },
- { action: 'Arrow', keys: ['⇧', 'L'] },
- { action: 'Text', keys: ['T'] },
- { action: 'Pen', keys: ['P'] },
- { action: 'Hand (pan)', keys: ['H'] },
+ { action: 'Move', keys: ['V'], id: 'tool-move' },
+ { action: 'Frame', keys: ['F'], id: 'tool-frame' },
+ { action: 'Rectangle', keys: ['R'], id: 'tool-rectangle' },
+ { action: 'Ellipse', keys: ['O'], id: 'tool-ellipse' },
+ { action: 'Line', keys: ['L'], id: 'tool-line' },
+ { action: 'Arrow', keys: ['⇧', 'L'], id: 'tool-arrow' },
+ { action: 'Text', keys: ['T'], id: 'tool-text' },
+ { action: 'Pen', keys: ['P'], id: 'tool-pen' },
+ { action: 'Pencil', keys: ['⇧', 'P'], id: 'tool-pencil' },
+ { action: 'Place image', keys: ['mod', '⇧', 'K'], id: 'place-image' },
+ { action: 'Hand (pan)', keys: ['H'], id: 'tool-hand' },
{ action: 'Pan while held', keys: ['Space'] },
],
},
{
title: 'Edit',
items: [
- { action: 'Undo', keys: ['mod', 'Z'] },
- { action: 'Redo', keys: ['mod', '⇧', 'Z'] },
- { action: 'Duplicate', keys: ['mod', 'D'] },
- { action: 'Copy / paste (across files)', keys: ['mod', 'C / V'] },
- { action: 'Delete', keys: ['⌫'] },
+ { action: 'Undo', keys: ['mod', 'Z'], id: 'undo' },
+ { action: 'Redo', keys: ['mod', '⇧', 'Z'], id: 'redo' },
+ { action: 'Duplicate', keys: ['mod', 'D'], id: 'duplicate' },
+ { action: 'Copy', keys: ['mod', 'C'], id: 'copy' },
+ { action: 'Cut', keys: ['mod', 'X'], id: 'cut' },
+ { action: 'Paste (across files)', keys: ['mod', 'V'] },
+ {
+ action: 'Paste to replace',
+ keys: ['mod', '⇧', 'R'],
+ id: 'paste-replace',
+ },
+ { action: 'Delete', keys: ['⌫'], id: 'delete' },
{ action: 'Nudge', keys: ['←↑→↓'] },
{ action: 'Nudge 10', keys: ['⇧', '←↑→↓'] },
- { action: 'Rename', keys: ['mod', 'R'] },
+ { action: 'Rename', keys: ['mod', 'R'], id: 'rename' },
],
},
{
title: 'Arrange',
items: [
- { action: 'Group', keys: ['mod', 'G'] },
- { action: 'Ungroup', keys: ['mod', '⇧', 'G'] },
- { action: 'Frame selection', keys: ['mod', '⌥', 'G'] },
- { action: 'Add auto layout', keys: ['⇧', 'A'] },
- { action: 'Remove auto layout', keys: ['⌥', '⇧', 'A'] },
- { action: 'Create component', keys: ['mod', '⌥', 'K'] },
- { action: 'Detach instance', keys: ['mod', '⌥', 'B'] },
- { action: 'Bring forward', keys: ['mod', ']'] },
- { action: 'Send backward', keys: ['mod', '['] },
- { action: 'Bring to front', keys: ['mod', '⌥', ']'] },
- { action: 'Send to back', keys: ['mod', '⌥', '['] },
- { action: 'Show/hide', keys: ['mod', '⇧', 'H'] },
- { action: 'Lock/unlock', keys: ['mod', '⇧', 'L'] },
- { action: 'Flip horizontal', keys: ['⇧', 'H'] },
- { action: 'Flip vertical', keys: ['⇧', 'V'] },
+ { action: 'Group', keys: ['mod', 'G'], id: 'group' },
+ { action: 'Ungroup', keys: ['mod', '⇧', 'G'], id: 'ungroup' },
+ {
+ action: 'Frame selection',
+ keys: ['mod', '⌥', 'G'],
+ id: 'frame-selection',
+ },
+ { action: 'Add auto layout', keys: ['⇧', 'A'], id: 'add-auto-layout' },
+ {
+ action: 'Remove auto layout',
+ keys: ['⌥', '⇧', 'A'],
+ id: 'remove-auto-layout',
+ },
+ {
+ action: 'Create component',
+ keys: ['mod', '⌥', 'K'],
+ id: 'create-component',
+ },
+ {
+ action: 'Detach instance',
+ keys: ['mod', '⌥', 'B'],
+ id: 'detach-instance',
+ },
+ { action: 'Bring forward', keys: ['mod', ']'], id: 'bring-forward' },
+ { action: 'Send backward', keys: ['mod', '['], id: 'send-backward' },
+ {
+ action: 'Bring to front',
+ keys: ['mod', '⌥', ']'],
+ id: 'bring-to-front',
+ },
+ { action: 'Send to back', keys: ['mod', '⌥', '['], id: 'send-to-back' },
+ { action: 'Show/hide', keys: ['mod', '⇧', 'H'], id: 'toggle-visible' },
+ { action: 'Lock/unlock', keys: ['mod', '⇧', 'L'], id: 'toggle-locked' },
+ { action: 'Flip horizontal', keys: ['⇧', 'H'], id: 'flip-horizontal' },
+ { action: 'Flip vertical', keys: ['⇧', 'V'], id: 'flip-vertical' },
+ ],
+ },
+ {
+ title: 'Align',
+ items: [
+ { action: 'Align left', keys: ['⌥', 'A'], id: 'align-left' },
+ {
+ action: 'Align horizontal centers',
+ keys: ['⌥', 'H'],
+ id: 'align-center',
+ },
+ { action: 'Align right', keys: ['⌥', 'D'], id: 'align-right' },
+ { action: 'Align top', keys: ['⌥', 'W'], id: 'align-top' },
+ {
+ action: 'Align vertical centers',
+ keys: ['⌥', 'V'],
+ id: 'align-middle',
+ },
+ { action: 'Align bottom', keys: ['⌥', 'S'], id: 'align-bottom' },
+ {
+ action: 'Distribute horizontal spacing',
+ keys: ['⌃', '⌥', 'H'],
+ otherKeys: ['Ctrl', 'Alt', 'H'],
+ id: 'distribute-horizontal',
+ },
+ {
+ action: 'Distribute vertical spacing',
+ keys: ['⌃', '⌥', 'V'],
+ otherKeys: ['Ctrl', 'Alt', 'V'],
+ id: 'distribute-vertical',
+ },
],
},
{
title: 'Shapes',
items: [
- { action: 'Union', keys: ['⌥', '⇧', 'U'] },
- { action: 'Subtract', keys: ['⌥', '⇧', 'S'] },
- { action: 'Intersect', keys: ['⌥', '⇧', 'I'] },
- { action: 'Exclude', keys: ['⌥', '⇧', 'X'] },
- { action: 'Flatten', keys: ['mod', 'E'] },
+ { action: 'Union', keys: ['⌥', '⇧', 'U'], id: 'boolean-union' },
+ { action: 'Subtract', keys: ['⌥', '⇧', 'S'], id: 'boolean-subtract' },
+ { action: 'Intersect', keys: ['⌥', '⇧', 'I'], id: 'boolean-intersect' },
+ { action: 'Exclude', keys: ['⌥', '⇧', 'E'], id: 'boolean-exclude' },
+ { action: 'Flatten', keys: ['mod', 'E'], id: 'flatten' },
{ action: 'Edit points', keys: ['Enter'] },
],
},
+ {
+ title: 'Fill and stroke',
+ items: [
+ { action: 'Opacity 10%–90%', keys: ['1…9'] },
+ { action: 'Opacity 100%', keys: ['0'], id: 'opacity-0' },
+ { action: 'Opacity, exact (e.g. 45%)', keys: ['4', '5'] },
+ {
+ action: 'Swap fill and stroke',
+ keys: ['⇧', 'X'],
+ id: 'swap-fill-stroke',
+ },
+ ],
+ },
{
title: 'Zoom',
items: [
- { action: 'Zoom in', keys: ['mod', '+'] },
- { action: 'Zoom out', keys: ['mod', '-'] },
- { action: 'Zoom to 100%', keys: ['⇧', '0'] },
- { action: 'Zoom to fit', keys: ['⇧', '1'] },
- { action: 'Zoom to selection', keys: ['⇧', '2'] },
+ { action: 'Zoom in', keys: ['mod', '+'], id: 'zoom-in' },
+ { action: 'Zoom out', keys: ['mod', '-'], id: 'zoom-out' },
+ { action: 'Zoom to 100%', keys: ['⇧', '0'], id: 'zoom-100' },
+ { action: 'Zoom to fit', keys: ['⇧', '1'], id: 'zoom-fit' },
+ { action: 'Zoom to selection', keys: ['⇧', '2'], id: 'zoom-selection' },
{ action: 'Zoom with scroll', keys: ['mod', 'Scroll'] },
],
},
{
title: 'Navigate',
items: [
- { action: 'Next frame', keys: ['N'] },
- { action: 'Previous frame', keys: ['⇧', 'N'] },
- { action: 'Next page', keys: ['PgDn'] },
- { action: 'Previous page', keys: ['PgUp'] },
- { action: 'Find layers', keys: ['mod', 'F'] },
+ { action: 'Next frame', keys: ['N'], id: 'next-frame' },
+ { action: 'Previous frame', keys: ['⇧', 'N'], id: 'previous-frame' },
+ { action: 'Next page', keys: ['PgDn'], id: 'next-page' },
+ { action: 'Previous page', keys: ['PgUp'], id: 'previous-page' },
+ { action: 'Find layers', keys: ['mod', 'F'], id: 'find' },
],
},
{
title: 'Selection',
items: [
- { action: 'Select all', keys: ['mod', 'A'] },
+ { action: 'Select all', keys: ['mod', 'A'], id: 'select-all' },
{ action: 'Deep select', keys: ['mod', 'Click'] },
- { action: 'Select children', keys: ['Enter'] },
- { action: 'Select parent', keys: ['⇧', 'Enter'] },
- { action: 'Next sibling', keys: ['Tab'] },
- { action: 'Previous sibling', keys: ['⇧', 'Tab'] },
+ { action: 'Select children', keys: ['Enter'], id: 'select-children' },
+ { action: 'Select parent', keys: ['⇧', 'Enter'], id: 'select-parent' },
+ { action: 'Next sibling', keys: ['Tab'], id: 'next-sibling' },
+ {
+ action: 'Previous sibling',
+ keys: ['⇧', 'Tab'],
+ id: 'previous-sibling',
+ },
{ action: 'Deselect / parent', keys: ['Esc'] },
{ action: 'Measure to layer', keys: ['⌥', 'Hover'] },
],
@@ -411,14 +582,21 @@ export const SHORTCUT_GROUPS: { title: string; items: ShortcutHelp[] }[] = [
{
title: 'View',
items: [
- { action: 'Show/hide UI', keys: ['mod', '\\'] },
- { action: 'Outline view', keys: ['mod', 'Y'] },
- { action: 'Rulers', keys: ['⇧', 'R'] },
- { action: 'Pixel grid', keys: ['⇧', "'"] },
- { action: 'Layout grids (Ctrl+⇧4 off macOS)', keys: ['⌃', 'G'] },
- { action: 'Layers panel', keys: ['⌥', '1'] },
- { action: 'Design panel', keys: ['⌥', '8'] },
- { action: 'Collapse layers', keys: ['⌥', 'L'] },
+ { action: 'Actions', keys: ['mod', 'P'], id: 'open-actions' },
+ { action: 'Show/hide UI', keys: ['mod', '.'], id: 'toggle-ui' },
+ { action: 'Outline view', keys: ['mod', 'Y'], id: 'toggle-outline' },
+ { action: 'Rulers', keys: ['⇧', 'R'], id: 'toggle-rulers' },
+ { action: 'Pixel grid', keys: ['⇧', "'"], id: 'toggle-pixel-grid' },
+ {
+ action: 'Layout grids',
+ keys: ['⌃', 'G'],
+ otherKeys: ['Ctrl', '⇧', '4'],
+ id: 'toggle-layout-grids',
+ },
+ { action: 'Layers panel', keys: ['⌥', '1'], id: 'toggle-layers' },
+ { action: 'Assets panel', keys: ['⌥', '2'], id: 'toggle-assets' },
+ { action: 'Design panel', keys: ['⌥', '8'], id: 'toggle-design' },
+ { action: 'Collapse layers', keys: ['⌥', 'L'], id: 'collapse-layers' },
],
},
{
@@ -431,9 +609,13 @@ export const SHORTCUT_GROUPS: { title: string; items: ShortcutHelp[] }[] = [
{
title: 'Export',
items: [
- { action: 'Copy as PNG', keys: ['mod', '⇧', 'C'] },
- { action: 'Export selection', keys: ['mod', '⇧', 'E'] },
- { action: 'Keyboard shortcuts', keys: ['Ctrl', '⇧', '?'] },
+ { action: 'Copy as PNG', keys: ['mod', '⇧', 'C'], id: 'copy-png' },
+ { action: 'Export selection', keys: ['mod', '⇧', 'E'], id: 'export' },
+ {
+ action: 'Keyboard shortcuts',
+ keys: ['Ctrl', '⇧', '?'],
+ id: 'show-shortcuts',
+ },
],
},
];
diff --git a/apps/web/src/features/block-fig/core/vector.test.ts b/apps/web/src/features/block-fig/core/vector.test.ts
index c474212575..3ede630d64 100644
--- a/apps/web/src/features/block-fig/core/vector.test.ts
+++ b/apps/web/src/features/block-fig/core/vector.test.ts
@@ -8,6 +8,7 @@ import {
moveHandle,
moveVertex,
type PenPoint,
+ pencilPoints,
penNetwork,
segmentCurve,
vertexHandles,
@@ -136,3 +137,31 @@ describe('editing points', () => {
expect(left.regions).toEqual([]);
});
});
+
+describe('pencil strokes', () => {
+ it('keeps the ends and drops points along straight runs', () => {
+ const line = Array.from({ length: 50 }, (_, i) => ({ x: i, y: i }));
+ const points = pencilPoints(line, 1);
+ expect(points.map(({ x, y }) => ({ x, y }))).toEqual([
+ { x: 0, y: 0 },
+ { x: 49, y: 49 },
+ ]);
+ expect(points.every((p) => p.handle.x === 0 && p.handle.y === 0)).toBe(
+ true
+ );
+ });
+
+ it('keeps corners and smooths through middle points', () => {
+ const corner = [
+ ...Array.from({ length: 20 }, (_, i) => ({ x: i, y: 0 })),
+ ...Array.from({ length: 20 }, (_, i) => ({ x: 20, y: i + 1 })),
+ ];
+ const points = pencilPoints(corner, 1);
+ expect(points).toHaveLength(3);
+ // The middle point's handle is a sixth of its neighbors' chord.
+ expect(points[1].handle).toEqual({ x: 3.33, y: 3.33 });
+ const net = penNetwork(points, false);
+ expect(net.segments).toHaveLength(2);
+ expect(net.regions).toEqual([]);
+ });
+});
diff --git a/apps/web/src/features/block-fig/core/vector.ts b/apps/web/src/features/block-fig/core/vector.ts
index dbfd1427f3..5784526b13 100644
--- a/apps/web/src/features/block-fig/core/vector.ts
+++ b/apps/web/src/features/block-fig/core/vector.ts
@@ -248,3 +248,65 @@ export function deleteVertex(net: VectorNetwork, i: number): VectorNetwork {
.filter((r) => r.loops.length > 0),
};
}
+
+/** Distance from `p` to the segment `a`–`b`. */
+function segmentDistance(p: Vec2, a: Vec2, b: Vec2): number {
+ const dx = b.x - a.x;
+ const dy = b.y - a.y;
+ const length = dx * dx + dy * dy;
+ const t =
+ length === 0
+ ? 0
+ : Math.max(
+ 0,
+ Math.min(1, ((p.x - a.x) * dx + (p.y - a.y) * dy) / length)
+ );
+ return dist(p, { x: a.x + t * dx, y: a.y + t * dy });
+}
+
+/** The points a stroke keeps within `tolerance` (Douglas–Peucker). */
+function simplify(points: Vec2[], tolerance: number): Vec2[] {
+ if (points.length < 3) return points;
+ const keep = new Array<boolean>(points.length).fill(false);
+ keep[0] = true;
+ keep[points.length - 1] = true;
+ const stack: [number, number][] = [[0, points.length - 1]];
+ while (stack.length > 0) {
+ const [from, to] = stack.pop() as [number, number];
+ let farthest = -1;
+ let distance = tolerance;
+ for (let i = from + 1; i < to; i++) {
+ const d = segmentDistance(points[i], points[from], points[to]);
+ if (d > distance) {
+ distance = d;
+ farthest = i;
+ }
+ }
+ if (farthest < 0) continue;
+ keep[farthest] = true;
+ stack.push([from, farthest], [farthest, to]);
+ }
+ return points.filter((_, i) => keep[i]);
+}
+
+/**
+ * A pencil stroke as pen points: the points it passes through, fewer where
+ * it runs straight, joined by smooth curves (the ends are corners).
+ */
+export function pencilPoints(stroke: Vec2[], tolerance: number): PenPoint[] {
+ const points = simplify(stroke, tolerance);
+ return points.map((p, i) => {
+ const before = points[i - 1];
+ const after = points[i + 1];
+ const handle =
+ before && after
+ ? { x: (after.x - before.x) / 6, y: (after.y - before.y) / 6 }
+ : ZERO;
+ const round = (v: number) => Math.round(v * 100) / 100;
+ return {
+ x: round(p.x),
+ y: round(p.y),
+ handle: { x: round(handle.x), y: round(handle.y) },
+ };
+ });
+}
diff --git a/apps/web/src/features/block-fig/fig-block.tsx b/apps/web/src/features/block-fig/fig-block.tsx
index 09102bfa8a..15c01c6977 100644
--- a/apps/web/src/features/block-fig/fig-block.tsx
+++ b/apps/web/src/features/block-fig/fig-block.tsx
@@ -3,6 +3,7 @@
* viewer, wired to the worker engine and document storage.
*/
+import { CommandState } from '@app/features/command';
import { useBlockEntityCommands } from '@app/features/next-soup/actions';
import {
ResponsiveBlockToolbar,
@@ -23,6 +24,7 @@ import {
ShareTrigger,
} from '@core/component/TopBar/ShareButton';
import { useShareModal } from '@core/component/TopBar/shareModal';
+import { IS_MAC } from '@core/constant/isMac';
import { useUserId } from '@core/context/user';
import { FigEngine } from '@core/fig-engine/client';
import { blockDataSignal } from '@core/internal/BlockLoader';
@@ -76,6 +78,22 @@ import {
import { createFontSource } from './queries/font-source';
import { FigViewer } from './views/fig-viewer';
+/**
+ * ⌘K on a design opens the command menu, which then offers the design
+ * palette (Figma's actions menu, ⌘P here).
+ */
+const suggestActions = (openActions: () => void) =>
+ CommandState.setHint({
+ message: 'Did you mean to open the design palette?',
+ shortcut: IS_MAC ? '⌘P' : 'Ctrl+P',
+ matches: (e) =>
+ (IS_MAC ? e.metaKey : e.ctrlKey) &&
+ !e.altKey &&
+ !e.shiftKey &&
+ e.code === 'KeyP',
+ run: openActions,
+ });
+
/**
* Opens the file in the engine (and, for a shared design, applies what
* other people changed) and mounts the viewer once ready.
@@ -185,6 +203,7 @@ function FigHost(props: {
presentAt: props.present,
fonts: createFontSource(),
libraries,
+ suggestActions,
}}
>
<FigViewer />
diff --git a/apps/web/src/features/block-fig/primitives/create-fig-editor.ts b/apps/web/src/features/block-fig/primitives/create-fig-editor.ts
index 62b0370e67..52da9f6800 100644
--- a/apps/web/src/features/block-fig/primitives/create-fig-editor.ts
+++ b/apps/web/src/features/block-fig/primitives/create-fig-editor.ts
@@ -23,7 +23,7 @@ import type {
} from '@core/fig-engine/types';
import { createSignal, onCleanup } from 'solid-js';
import type { FigSharing } from '../context/fig-viewer-context';
-import { type Alignment, alignOffset } from '../core/align';
+import { type Alignment, alignOffset, distributeOffsets } from '../core/align';
import type { BooleanOperation } from '../core/boolean';
import type { Point } from '../core/camera';
import {
@@ -35,11 +35,11 @@ import {
import type { DesignOp } from '../core/design-system';
import type { HandoffOp } from '../core/handoff-ops';
import type { LibraryOp } from '../core/libraries';
-import type { PaintType, StopSpec } from '../core/paint';
+import { copyPaint, type PaintType, type StopSpec } from '../core/paint';
import type { InteractionSpec } from '../core/prototype';
import { resizedOrigin } from '../core/rotation';
import type { Measure } from '../core/type';
-import { type PenPoint, penNetwork } from '../core/vector';
+import { type PenPoint, pencilPoints, penNetwork } from '../core/vector';
import type { FigViewer, Selected } from './create-fig-viewer';
export type SaveState = 'saved' | 'unsaved' | 'saving' | 'error';
@@ -675,6 +675,39 @@ export function createFigEditor(options: FigEditorOptions) {
await apply(ops);
};
+ /** Spaces three or more layers evenly (Figma's distribute spacing). */
+ const distribute = async (axis: 'horizontal' | 'vertical') => {
+ const boxes = viewer
+ .selectionGeometry()
+ .filter((g) => !g.id.startsWith('I'))
+ .map((g) => ({ id: g.id, bounds: g.bounds }));
+ const ops: Op[] = distributeOffsets(boxes, axis)
+ .filter((o) => Math.abs(o.dx) > 1e-6 || Math.abs(o.dy) > 1e-6)
+ .map((o) => ({
+ op: 'translate' as const,
+ ids: [o.id],
+ dx: Math.round(o.dx * 100) / 100,
+ dy: Math.round(o.dy * 100) / 100,
+ }));
+ if (ops.length > 0) await apply(ops);
+ };
+
+ /** Figma's ⇧X: a layer's fills become its strokes and the other way. */
+ const swapFillStroke = async (info: NodeInfo) => {
+ const copies = (paints: NodeInfo['fills']) =>
+ paints.map(copyPaint).filter((p): p is PaintSpec => p !== null);
+ const fills = copies(info.strokes);
+ const strokes = copies(info.fills);
+ if (fills.length === 0 && strokes.length === 0) return;
+ // A layer without a stroke weight shows none: give it Figma's 1.
+ const weight = strokes.length > 0 && !info.strokeWeight ? 1 : undefined;
+ await setProps({
+ fills,
+ strokes,
+ ...(weight ? { strokeWeight: weight } : {}),
+ });
+ };
+
/**
* ⌘C: the selected layers go on the system clipboard as Figma puts them
* there (they paste into other files and tabs), and are remembered for
@@ -878,6 +911,26 @@ export function createFigEditor(options: FigEditorOptions) {
return result?.created[0];
};
+ /**
+ * Ends a pencil stroke (page points): a smoothed open path, made in the
+ * frame under where it started and selected. The pencil stays chosen.
+ */
+ const pencilFinish = async (stroke: Point[], tolerance: number) => {
+ if (!enabled() || stroke.length < 2) return undefined;
+ const points = pencilPoints(stroke, tolerance);
+ if (points.length < 2) return undefined;
+ const parent = await viewer.containerAt(points[0]);
+ const result = await apply([
+ {
+ op: 'createVector',
+ parent,
+ network: penNetwork(points, false),
+ },
+ ]);
+ await selectCreated(result);
+ return result?.created[0];
+ };
+
/** Starts editing a layer's points (double-click or Enter, as in Figma). */
const editVector = async (id: string) => {
if (!enabled() || id.startsWith('I')) return false;
@@ -1195,6 +1248,7 @@ export function createFigEditor(options: FigEditorOptions) {
penAdd,
penHandle,
penFinish,
+ pencilFinish,
vectorEdit,
editVector,
endVectorEdit,
@@ -1218,6 +1272,8 @@ export function createFigEditor(options: FigEditorOptions) {
ungroup,
arrange,
align,
+ distribute,
+ swapFillStroke,
nudge,
copy,
paste,
diff --git a/apps/web/src/features/block-fig/primitives/create-fig-viewer.ts b/apps/web/src/features/block-fig/primitives/create-fig-viewer.ts
index a1d8a74bb5..0b9ed7432c 100644
--- a/apps/web/src/features/block-fig/primitives/create-fig-viewer.ts
+++ b/apps/web/src/features/block-fig/primitives/create-fig-viewer.ts
@@ -36,6 +36,7 @@ export type Tool =
| 'line'
| 'arrow'
| 'pen'
+ | 'pencil'
| 'text';
export interface Selected {
diff --git a/apps/web/src/features/block-fig/views/fig-viewer.tsx b/apps/web/src/features/block-fig/views/fig-viewer.tsx
index 3db8c3548f..8423ccb839 100644
--- a/apps/web/src/features/block-fig/views/fig-viewer.tsx
+++ b/apps/web/src/features/block-fig/views/fig-viewer.tsx
@@ -15,6 +15,7 @@ import {
Show,
} from 'solid-js';
import { match } from 'ts-pattern';
+import { ActionsPalette } from '../components/actions-palette';
import { CommentPins } from '../components/comment-pins';
import { DesignPanel } from '../components/design-panel';
import { DevInspect } from '../components/dev-inspect';
@@ -39,6 +40,7 @@ import { rangeFills, rangeStyle, textInfoForRange } from '../core/rich-text';
import {
controlOwnsKey,
EDIT_ACTIONS,
+ SELECTION_ACTIONS,
shortcutAction,
type ViewerAction,
} from '../core/shortcuts';
@@ -66,6 +68,9 @@ import { PresentMode } from './present-mode';
import { TextEditor } from './text-editor';
import { ViewerCanvas } from './viewer-canvas';
+/** How soon a second digit must follow the first to make an exact opacity. */
+const OPACITY_TYPING_MS = 600;
+
const safeName = (name: string) =>
name.replace(/[\\/:*?"<>|]+/g, '-').trim() || 'export';
@@ -109,6 +114,7 @@ export function FigViewer() {
const [altHeld, setAltHeld] = createSignal(false);
const [deepHeld, setDeepHeld] = createSignal(false);
const [showShortcuts, setShowShortcuts] = createSignal(false);
+ const [showActions, setShowActions] = createSignal(false);
const [leftTab, setLeftTab] = createSignal<'layers' | 'assets'>('layers');
const [info, setInfo] = createSignal<NodeInfo>();
const designSystem = createDesignSystem({ engine, viewer, editor });
@@ -348,6 +354,47 @@ export function FigViewer() {
if (next !== undefined) void viewer.openPage(next);
};
+ /**
+ * Figma's opacity keys: a digit sets tens of percent (0 is 100%); a
+ * second one typed quickly makes it exact (4 then 5 is 45%).
+ */
+ let typedOpacity: { digit: number; at: number; key: string } | undefined;
+ let opacitySteps = 0;
+ const typeOpacity = (digit: number) => {
+ const now = performance.now();
+ const first = typedOpacity;
+ if (first && now - first.at < OPACITY_TYPING_MS) {
+ typedOpacity = undefined;
+ void editor.setProps(
+ { opacity: (first.digit * 10 + digit) / 100 },
+ first.key
+ );
+ return;
+ }
+ const key = `opacity-keys-${++opacitySteps}`;
+ typedOpacity = { digit, at: now, key };
+ void editor.setProps({ opacity: digit === 0 ? 1 : digit / 10 }, key);
+ };
+
+ /** Figma's place image (⇧⌘K): picked images go in the middle of the view. */
+ const placeImage = () => {
+ const input = document.createElement('input');
+ input.type = 'file';
+ input.accept = 'image/*';
+ input.multiple = true;
+ input.onchange = () => {
+ const files = [...(input.files ?? [])];
+ if (files.length === 0) return;
+ const c = viewer.camera();
+ const v = viewer.viewport();
+ const at = { x: c.x + v.w / 2 / c.zoom, y: c.y + v.h / 2 / c.zoom };
+ void viewer
+ .containerAt(at)
+ .then((parent) => editor.importImages(files, at, parent));
+ };
+ input.click();
+ };
+
const run = (action: ViewerAction) =>
match(action)
.with('tool-move', () => viewer.setTool('move'))
@@ -364,6 +411,8 @@ export function FigViewer() {
.with('select-all', () => void viewer.selectAll())
.with('escape', () => {
if (showShortcuts()) setShowShortcuts(false);
+ else if (viewer.tool() !== 'move' && viewer.tool() !== 'hand')
+ viewer.setTool('move');
else viewer.escapeSelection();
})
.with('select-parent', () => viewer.selectParent())
@@ -393,6 +442,23 @@ export function FigViewer() {
queueMicrotask(() => searchInput?.focus());
})
.with('show-shortcuts', () => setShowShortcuts((s) => !s))
+ .with('open-actions', () => {
+ if (!showActions()) {
+ setShowActions(true);
+ return;
+ }
+ setShowActions(false);
+ root.focus({ preventScroll: true });
+ })
+ .with('toggle-assets', () => {
+ viewer.setUiHidden(false);
+ if (viewer.layersOpen() && leftTab() === 'assets') {
+ viewer.setLayersOpen(false);
+ return;
+ }
+ viewer.setLayersOpen(true);
+ setLeftTab('assets');
+ })
.with('tool-frame', () => viewer.setTool('frame'))
.with('tool-rectangle', () => viewer.setTool('rectangle'))
.with('tool-ellipse', () => viewer.setTool('ellipse'))
@@ -400,6 +466,8 @@ export function FigViewer() {
.with('tool-line', () => viewer.setTool('line'))
.with('tool-arrow', () => viewer.setTool('arrow'))
.with('tool-pen', () => viewer.setTool('pen'))
+ .with('tool-pencil', () => viewer.setTool('pencil'))
+ .with('place-image', () => placeImage())
.with('undo', () => {
editor.endVectorEdit();
editor.undo();
@@ -413,6 +481,7 @@ export function FigViewer() {
.with('copy', () => editor.copy())
.with('cut', () => void editor.cut())
.with('paste', () => void editor.paste())
+ .with('paste-replace', () => void editor.pasteToReplace())
.with('group', () => void editor.group())
.with('ungroup', () => void editor.ungroup())
.with('frame-selection', () => void editor.group(true))
@@ -440,6 +509,31 @@ export function FigViewer() {
.with('flip-horizontal', () => void editor.flip(false))
.with('flip-vertical', () => void editor.flip(true))
.with('rename', () => viewer.requestRename())
+ .with('align-left', () => void editor.align('left'))
+ .with('align-center', () => void editor.align('center'))
+ .with('align-right', () => void editor.align('right'))
+ .with('align-top', () => void editor.align('top'))
+ .with('align-middle', () => void editor.align('middle'))
+ .with('align-bottom', () => void editor.align('bottom'))
+ .with('distribute-horizontal', () => void editor.distribute('horizontal'))
+ .with('distribute-vertical', () => void editor.distribute('vertical'))
+ .with('swap-fill-stroke', () => {
+ const i = info();
+ if (i) void editor.swapFillStroke(i);
+ })
+ .with(
+ 'opacity-0',
+ 'opacity-1',
+ 'opacity-2',
+ 'opacity-3',
+ 'opacity-4',
+ 'opacity-5',
+ 'opacity-6',
+ 'opacity-7',
+ 'opacity-8',
+ 'opacity-9',
+ (a) => typeOpacity(Number(a.slice('opacity-'.length)))
+ )
.with('nudge-left', () => void editor.nudge(-1, 0))
.with('nudge-right', () => void editor.nudge(1, 0))
.with('nudge-up', () => void editor.nudge(0, -1))
@@ -559,8 +653,29 @@ export function FigViewer() {
focus: () => root.focus({ preventScroll: true }),
});
+ /** Nothing to deselect, no tool to leave, no panel to close. */
+ const escapeIdle = () =>
+ !showShortcuts() &&
+ (viewer.tool() === 'move' || viewer.tool() === 'hand') &&
+ viewer.selected().length === 0;
+
const onKeyDown = (e: KeyboardEvent) => {
const target = e.target as HTMLElement;
+ // Presenting takes its own keys.
+ if (review.presenting()) return;
+ const mod = IS_MAC ? e.metaKey : e.ctrlKey;
+ // ⌘P is the actions menu anywhere in the design, never the browser's
+ // print (Figma's quick actions; Figma's ⌘K is the app's command menu).
+ if (mod && !e.altKey && !e.shiftKey && e.code === 'KeyP') {
+ e.preventDefault();
+ e.stopPropagation();
+ run('open-actions');
+ return;
+ }
+ if (mod && !e.altKey && !e.shiftKey && e.code === 'KeyK') {
+ context.suggestActions?.(() => setShowActions(true));
+ return;
+ }
if (target.closest('input, textarea, [contenteditable="true"]')) return;
// Menus (portaled, so their events bubble here) handle their own keys.
if (target.closest('[role="menu"]')) return;
@@ -570,6 +685,7 @@ export function FigViewer() {
if (review.onKey(e)) return;
if (e.key === ' ') {
e.preventDefault();
+ e.stopPropagation();
setSpaceHeld(true);
return;
}
@@ -585,6 +701,10 @@ export function FigViewer() {
if (EDIT_ACTIONS.has(action) && !editor.enabled()) return;
// ⌘V goes through the paste event, which carries pasted image files.
if (action === 'paste') return;
+ // With nothing to act on, the key is the app's (⇧← focuses the split
+ // to the left, Escape leaves a spotlighted split, ⇧⌘C copies the link).
+ if (SELECTION_ACTIONS.has(action) && viewer.selected().length === 0) return;
+ if (action === 'escape' && escapeIdle()) return;
e.preventDefault();
e.stopPropagation();
const resolved = enterAction(action);
@@ -595,6 +715,29 @@ export function FigViewer() {
} else run(resolved);
};
+ /**
+ * Keys pressed in the design reach it before the app's hotkeys (which
+ * listen on the document while capturing), so where they overlap the
+ * design's shortcuts win, as in Figma: R, T, O, H, \, ⌘\, ⌘Z and others.
+ * Keys it does not use go on to the app (⌘K, ⌘S, G, /…).
+ */
+ const handledEarly = new WeakSet<Event>();
+ onMount(() => {
+ const onWindowKeyDown = (e: KeyboardEvent) => {
+ if (!(e.target instanceof Node) || !root.contains(e.target)) return;
+ handledEarly.add(e);
+ onKeyDown(e);
+ };
+ window.addEventListener('keydown', onWindowKeyDown, true);
+ onCleanup(() =>
+ window.removeEventListener('keydown', onWindowKeyDown, true)
+ );
+ });
+ /** Keys from the design's portaled popovers, which bubble here. */
+ const onPortaledKeyDown = (e: KeyboardEvent) => {
+ if (!handledEarly.has(e)) onKeyDown(e);
+ };
+
const onKeyUp = (e: KeyboardEvent) => {
if (e.key === ' ') setSpaceHeld(false);
if (e.key === 'Alt') setAltHeld(false);
@@ -705,7 +848,7 @@ export function FigViewer() {
tabIndex={0}
class="flex size-full min-h-0 bg-page outline-none"
data-testid="fig-viewer"
- onKeyDown={onKeyDown}
+ onKeyDown={onPortaledKeyDown}
onKeyUp={onKeyUp}
onPaste={onPaste}
>
@@ -932,6 +1075,20 @@ export function FigViewer() {
onClose={() => setShowShortcuts(false)}
/>
</Show>
+ <Show when={showActions()}>
+ <ActionsPalette
+ mac={IS_MAC}
+ available={(action) =>
+ !EDIT_ACTIONS.has(action) || editor.enabled()
+ }
+ onRun={run}
+ onClose={(refocus) => {
+ setShowActions(false);
+ // Back to the canvas, so its shortcuts work again.
+ if (refocus) root.focus({ preventScroll: true });
+ }}
+ />
+ </Show>
<FigContextMenu
at={contextMenu.menu()?.at}
entries={contextMenu.menu()?.entries ?? []}
diff --git a/apps/web/src/features/block-fig/views/viewer-canvas.tsx b/apps/web/src/features/block-fig/views/viewer-canvas.tsx
index 7629bb9aba..027096d95e 100644
--- a/apps/web/src/features/block-fig/views/viewer-canvas.tsx
+++ b/apps/web/src/features/block-fig/views/viewer-canvas.tsx
@@ -83,6 +83,8 @@ const HANDLE_SLOP = 6;
/** How far beyond a corner (CSS px) a press rotates instead. */
const ROTATE_REACH = 18;
+/** How far (CSS px) a smoothed pencil stroke may stray from the drawn one. */
+const PENCIL_TOLERANCE = 1.5;
/** Distance (CSS px) from the first point within which the pen closes. */
const PEN_CLOSE = 8;
@@ -139,6 +141,8 @@ type Drag =
}
/** The pen placed a point; dragging pulls out its handle. */
| { kind: 'pen'; start: Point }
+ /** The pencil drawing a stroke (page points). */
+ | { kind: 'pencil'; points: Point[] }
/** A ruler guide dragged out of a ruler, or moved. */
| { kind: 'guide'; guide: GuideDrag }
/** A point or handle of the layer being edited. */
@@ -372,6 +376,14 @@ export function ViewerCanvas(props: {
const vectorOverlay = (): VectorOverlay | undefined => {
const editor = props.editor;
if (!editor) return undefined;
+ if (drag?.kind === 'pencil')
+ return {
+ network: penNetwork(
+ drag.points.map((p) => ({ ...p, handle: { x: 0, y: 0 } })),
+ false
+ ),
+ stroke: true,
+ };
const points = editor.penPath();
if (points && points.length > 0) {
const z = viewer.camera().zoom;
@@ -458,12 +470,26 @@ export function ViewerCanvas(props: {
const r = entry.contentRect;
const ratio = window.devicePixelRatio || 1;
setDpr(ratio);
+ const width = Math.max(1, Math.round(r.width * ratio));
+ const height = Math.max(1, Math.round(r.height * ratio));
+ viewer.resize({ w: r.width, h: r.height });
+ // Sizing a canvas clears it, so it is drawn again before this frame
+ // is painted: waiting for the next frame would show it blank (black)
+ // for a frame each time the split resizes, as when the app's sidebar
+ // opens or closes.
+ if (tileCanvas.width === width && tileCanvas.height === height) {
+ requestDraw();
+ return;
+ }
for (const canvas of [tileCanvas, overlayCanvas]) {
- canvas.width = Math.max(1, Math.round(r.width * ratio));
- canvas.height = Math.max(1, Math.round(r.height * ratio));
+ canvas.width = width;
+ canvas.height = height;
}
- viewer.resize({ w: r.width, h: r.height });
- requestDraw();
+ if (frame !== undefined) {
+ cancelAnimationFrame(frame);
+ frame = undefined;
+ }
+ draw();
});
observer.observe(host);
onCleanup(() => observer.disconnect());
@@ -630,6 +656,11 @@ export function ViewerCanvas(props: {
drag = { kind: 'pen', start: point };
return;
}
+ if (editing() && tool === 'pencil' && editor) {
+ drag = { kind: 'pencil', points: [pageAt(p)] };
+ requestDraw();
+ return;
+ }
const edit = editor?.vectorEdit();
if (editing() && edit && editor) {
const hit = hitVector(
@@ -775,7 +806,8 @@ export function ViewerCanvas(props: {
? ROTATE_CURSOR
: props.aids?.cursorAt(p)
);
- if (!isShapeTool(viewer.tool())) hoverAt(p);
+ if (!isShapeTool(viewer.tool()) && viewer.tool() !== 'pencil')
+ hoverAt(p);
}
return;
}
@@ -800,6 +832,13 @@ export function ViewerCanvas(props: {
dragHandle(drag.start, pageAt(p), PEN_DRAG / viewer.camera().zoom)
);
requestDraw();
+ } else if (drag.kind === 'pencil') {
+ const at = pageAt(p);
+ const last = drag.points[drag.points.length - 1];
+ // A point per screen pixel or so is plenty to smooth.
+ if (Math.hypot(at.x - last.x, at.y - last.y) * viewer.camera().zoom >= 1)
+ drag.points.push(at);
+ requestDraw();
} else if (drag.kind === 'vector') {
const edit = props.editor?.vectorEdit();
if (edit) {
@@ -928,6 +967,12 @@ export function ViewerCanvas(props: {
void ended.mover.end();
} else if (ended.kind === 'pen') {
requestDraw();
+ } else if (ended.kind === 'pencil') {
+ requestDraw();
+ void props.editor?.pencilFinish(
+ ended.points,
+ PENCIL_TOLERANCE / viewer.camera().zoom
+ );
} else if (ended.kind === 'guide') {
void props.aids?.drop(ended.guide, local(e));
} else if (ended.kind === 'resize') {
@@ -960,7 +1005,8 @@ export function ViewerCanvas(props: {
const onDoubleClick = async (e: MouseEvent) => {
const tool = viewer.tool();
- if (panning() || isShapeTool(tool) || tool === 'pen') return;
+ if (panning() || isShapeTool(tool) || tool === 'pen' || tool === 'pencil')
+ return;
if (props.editor?.vectorEdit()) return;
const before = viewer.selected().map((s) => s.id);
await viewer.clickAt(local(e), {
@@ -1027,6 +1073,7 @@ export function ViewerCanvas(props: {
if (panning()) return 'grab';
if (editing() && viewer.tool() === 'text') return 'text';
if (editing() && viewer.tool() === 'pen') return 'crosshair';
+ if (editing() && viewer.tool() === 'pencil') return 'crosshair';
if (editing() && isShapeTool(viewer.tool())) return 'crosshair';
return cursorOverride() ?? 'default';
};
diff --git a/apps/web/src/features/command/CommandMenu.tsx b/apps/web/src/features/command/CommandMenu.tsx
index da50b8b35b..83c94a95fe 100644
--- a/apps/web/src/features/command/CommandMenu.tsx
+++ b/apps/web/src/features/command/CommandMenu.tsx
@@ -124,7 +124,13 @@ export function CommandMenu() {
}}
open={CommandState.isOpen()}
>
- <CommandMenuInner depth={2} onSelect={handleSelect} />
+ <CommandMenuInner
+ depth={2}
+ onSelect={handleSelect}
+ onHint={() => {
+ suppressCloseAutoFocus = true;
+ }}
+ />
</Dialog>
);
}
@@ -134,6 +140,8 @@ export function CommandMenuInner(props: {
items?: () => CommandMenuItem[];
/** Called when the user selects an item from the menu */
onSelect?: (item: CommandMenuItem) => void;
+ /** Called when the user takes the menu's hint (it moves focus itself). */
+ onHint?: () => void;
/**
* When true, selecting an item only fires `onSelect` — no navigation,
* command, or search is run. Used by the onboarding sandbox so selecting a
@@ -586,6 +594,26 @@ export function CommandMenuInner(props: {
}
});
+ const runHint = () => {
+ const hint = CommandState.hint();
+ if (!hint) return;
+ props.onHint?.();
+ CommandState.close();
+ // After the dialog has gone, so its focus trap lets the hint move focus.
+ setTimeout(hint.run);
+ };
+ // The hint's own key (e.g. ⌘P) works while the menu is open.
+ onMount(() => {
+ const onKeyDown = (e: KeyboardEvent) => {
+ if (!CommandState.hint()?.matches(e)) return;
+ e.preventDefault();
+ e.stopPropagation();
+ runHint();
+ };
+ document.addEventListener('keydown', onKeyDown);
+ onCleanup(() => document.removeEventListener('keydown', onKeyDown));
+ });
+
const isInCommandScope = createMemo(
() => CommandState.commandScopeCommands().length > 0
);
@@ -656,6 +684,26 @@ export function CommandMenuInner(props: {
/>
</CommandMenuShell.Header>
+ <Show
+ when={
+ !isInCommandScope() && !isEntityActionMode() && CommandState.hint()
+ }
+ >
+ {(hint) => (
+ <button
+ type="button"
+ class="mx-2 mt-2 flex items-center justify-between gap-2 rounded-md border border-edge-muted bg-inset px-2.5 py-1.5 text-left text-ink-muted text-xs hover:bg-hover hover:text-ink"
+ data-testid="command-menu-hint"
+ onClick={runHint}
+ >
+ <span class="truncate">{hint().message}</span>
+ <kbd class="shrink-0 rounded border border-edge-muted px-1 font-sans text-ink">
+ {hint().shortcut}
+ </kbd>
+ </button>
+ )}
+ </Show>
+
<Show when={isEntityActionMode() || !isInCommandScope()}>
<CommandMenuShell.Toolbar
class={cn(
diff --git a/apps/web/src/features/command/state.test.ts b/apps/web/src/features/command/state.test.ts
new file mode 100644
index 0000000000..c3f1cb3bc6
--- /dev/null
+++ b/apps/web/src/features/command/state.test.ts
@@ -0,0 +1,19 @@
+import { describe, expect, it, vi } from 'vitest';
+import { CommandState } from './state';
+
+describe('command menu hint', () => {
+ it('lasts until the menu closes', () => {
+ const run = vi.fn();
+ CommandState.setHint({
+ message: 'Did you mean to open the design palette?',
+ shortcut: '⌘P',
+ matches: (e) => e.metaKey && e.code === 'KeyP',
+ run,
+ });
+ CommandState.onMenuOpen();
+ expect(CommandState.hint()?.shortcut).toBe('⌘P');
+ CommandState.onMenuClose();
+ expect(CommandState.hint()).toBeUndefined();
+ expect(run).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/src/features/command/state.ts b/apps/web/src/features/command/state.ts
index 69198cf65e..b5d52bc37b 100644
--- a/apps/web/src/features/command/state.ts
+++ b/apps/web/src/features/command/state.ts
@@ -7,6 +7,19 @@ import type { CategoryFilter } from './types';
/** timestamp threshold for resetting state after menu close */
const STATE_RESET_THRESHOLD_MS = 2_000;
+/**
+ * A suggestion shown above the results for the place the menu was opened
+ * from, e.g. a design's own actions menu. Cleared when the menu closes.
+ */
+export interface CommandMenuHint {
+ message: string;
+ /** The key that runs it, as shown (`⌘P`). */
+ shortcut: string;
+ /** Whether a key press in the menu is that key. */
+ matches: (e: KeyboardEvent) => boolean;
+ run: () => void;
+}
+
interface ICommandState {
/** visibility */
isOpen: Accessor<boolean>;
@@ -51,6 +64,10 @@ interface ICommandState {
isEntityActionMode: Accessor<boolean>;
openForEntityAction: (entities: EntityData[]) => void;
+ /** a suggestion for where the menu was opened */
+ hint: Accessor<CommandMenuHint | undefined>;
+ setHint: Setter<CommandMenuHint | undefined>;
+
/** lifecycle */
maybeResetState: () => void;
forceReset: () => void;
@@ -79,6 +96,8 @@ function createCommandState(): ICommandState {
const [commandScopePlaceholder, setCommandScopePlaceholder] =
createSignal<string>();
+ const [hint, setHint] = createSignal<CommandMenuHint>();
+
function registerCommandScopePlaceholder(
scopeId: string,
placeholder: string
@@ -156,6 +175,7 @@ function createCommandState(): ICommandState {
function onMenuClose() {
setLastClosedTime(Date.now());
+ setHint(undefined);
clearCommandScopeCommands();
clearEntityActionEntities();
}
@@ -199,6 +219,9 @@ function createCommandState(): ICommandState {
isEntityActionMode,
openForEntityAction,
+ hint,
+ setHint,
+
maybeResetState,
forceReset,
onMenuClose,
diff --git a/docs/AGENT_GUIDE/documents.md b/docs/AGENT_GUIDE/documents.md
index 095a80aa50..255720084c 100644
--- a/docs/AGENT_GUIDE/documents.md
+++ b/docs/AGENT_GUIDE/documents.md
@@ -1080,7 +1080,9 @@ Layout and test hooks:
paste image files to place image-filled layers. The pen (P) draws a path:
click places a corner, drag pulls out a curve's handles, clicking the first
point closes the path, and Enter or Escape ends an open one; the result is
- a Vector layer with a 1 px black stroke. Double-clicking a selected shape
+ a Vector layer with a 1 px black stroke. The pencil (⇧P) draws freehand:
+ a drag becomes a smoothed open Vector layer, and the pencil stays chosen
+ until Escape or another tool. Double-clicking a selected shape
or vector (or Enter) edits its points: drag points and handles (⌥ breaks
a handle's mirroring), Delete removes the selected point, and Escape or a
click elsewhere ends editing; rectangles, ellipses, and the like become
@@ -1259,7 +1261,7 @@ Layout and test hooks:
Escape closes the picker.
- **Toolbar** (`fig-toolbar`): Move (V), Frame (F), Rectangle (R), Ellipse
(O), Line (L), Arrow (⇧L; ⇧ while drawing snaps lines to 45°), Pen (P),
- Text (T), Hand (H) as `fig-tool-<name>`, the boolean menu
+ Pencil (⇧P), Text (T), Hand (H) as `fig-tool-<name>`, the boolean menu
(`fig-boolean-menu`: `fig-menu-boolean-<union|subtract|intersect|exclude>`
and `fig-menu-flatten`), undo/redo (`fig-undo`,
`fig-redo`), the save state (`fig-save-state`, `data-state` is `saved`,
@@ -1338,17 +1340,35 @@ Layout and test hooks:
⇧N next/previous frame, PageDown/PageUp pages, Enter children, ⇧Enter and
Esc parent, Tab/⇧Tab siblings, ⌘/Ctrl+A select all, ⇧R rulers, ⇧' pixel
grid, ⌃G (Ctrl+⇧4 off macOS) layout grids, ⌘/Ctrl+Y outline view,
- ⌘/Ctrl+\\ hide UI, ⌘/Ctrl+⇧C copy as PNG, ⌘/Ctrl+⇧E export. Editing:
+ ⌘/Ctrl+\\ or ⌘/Ctrl+. hide UI, ⌥1 / ⌥2 / ⌥8 layers, assets, and design
+ panels, ⌘/Ctrl+⇧C copy as PNG, ⌘/Ctrl+⇧E export. ⌘/Ctrl+P (or ⌘/) opens
+ the design palette (`fig-actions`, Figma's actions menu, never the
+ browser's print): type in `fig-actions-input`, arrows and Enter run an
+ action (`fig-action-<action>`), Escape closes it. ⌘K stays the app's
+ command menu; opened from a design it offers the palette in a hint row
+ (`command-menu-hint`, "Did you mean to open the design palette?"), which
+ ⌘P or a click opens. Editing:
⌘Z/⇧⌘Z undo and redo (each brings back what was selected around the
step), ⌘D duplicate, ⌘C/⌘X/⌘V, Delete, arrows nudge (⇧ by 10), ⌘G
group, ⇧⌘G ungroup, ⌥⌘G frame selection (like ⇧A's wrapping frame, it
does not clip its layers), ⌘] / ⌘[ forward/backward, ⌥⌘] / ⌥⌘[
front/back, ⇧⌘H hide,
⇧⌘L lock, ⇧H / ⇧V flip, ⌘R rename, ⌥⇧U union, ⌥⇧S subtract (the top layers from the
- bottom one), ⌥⇧I intersect, ⌥⇧X exclude, and ⌘E flatten (booleans and
- shapes into one vector layer). A boolean keeps its layers as children and
+ bottom one), ⌥⇧I intersect, ⌥⇧E (or ⌥⇧X) exclude, and ⌘E flatten
+ (booleans and shapes into one vector layer). ⌥A / ⌥H / ⌥D align left,
+ center, right and ⌥W / ⌥V / ⌥S top, middle, bottom; ⌃⌥H / ⌃⌥V (Ctrl+Alt
+ off macOS) distribute three or more layers; digits set opacity (1 is 10%,
+ 0 is 100%, two quick digits such as 4 5 make 45%); ⇧X swaps fill and
+ stroke; ⇧⌘K places images; ⇧⌘R pastes to replace. A boolean keeps its layers as children and
recomputes its shape when they change, and takes the bottom layer's fills
and strokes.
+- **App hotkeys over a design**: while the design has focus its own keys
+ come first, so R, T, O, H, C, \\, ⌘\\, ⇧H/⇧L, ⌘Z and the others act on
+ the design rather than the app's rename, tag, leader keys, or new split.
+ Keys the design does not use stay the app's (⌘K, ⌘S, ⌘;, G, /, E, M), and
+ so do ⇧←/⇧→, ⇧H, ⇧⌘C, and Escape when there is no selection to act on
+ (focus the next split, copy the link, leave a spotlighted split). A
+ read-only design leaves the editing keys (R, T, O…) to the app.
The viewer has a browser fixture that needs no backend. From `apps/web`
(build the engine first with `just ensure-fig-engine-wasm`):