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.

perf(fig): improve loading, rendering, and editor interactions (#7560)

Jacob Beckerman51de3d396f57
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 59b5310fb3..3f24211a56 100644
--- a/apps/web/src/features/block-fig/browser-test/README.md
+++ b/apps/web/src/features/block-fig/browser-test/README.md
@@ -110,6 +110,36 @@ the session, and an unreachable sync service.
`FIG_CORPUS_DIR` (with a trailing slash) serves another directory of
files; `--port` runs a second server beside the default one.
+`performance.browser.e2e.ts` checks that reopening a design fetches and
+compiles the engine only once per browser page, and that moving over layers
+does not re-composite unchanged page tiles. It also prints engine reopen
+and tile timings; compare those on the same hardware and browser.
+Set `FIG_PERF_FILE` to an absolute local `.fig` path to measure a cold import
+and a second import with cached compiled code, overview raster time, and
+hit-test latency while rendering. The file stays local and unchanged:
+
+```sh
+FIG_PERF_FILE='/absolute/path/design.fig' bunx playwright test --config src/features/block-fig/browser-test/playwright.config.ts performance.browser.e2e.ts --grep 'profiles a local'
+```
+
Set `PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH` when the bundled browser is not
installed. Failure traces and screenshots stay in the ignored `test-results/`
folder.
+
+For performance investigations, `?realFonts` uses the application's Google
+Fonts cache and local-font discovery instead of substituting Inter. In this
+mode `fontRequests()` does not record requests; use the browser network trace.
+For a production fixture build, set `FIG_CORPUS_URL=/corpus/` and place only
+the selected test files in the ignored `.dist/corpus/` after building. The
+default `/@fs` fixture URLs are development-server URLs and do not work in
+`vite preview`.
+
+The reported `visibleMs` measures the viewer shell, not a painted document.
+`firstTileFrameMs` measures from selecting the local file to a browser frame
+after the first actual tile draw, using the production font source. This is
+an initial overview, not a guarantee that every sharp tile or font has loaded.
+Neither it nor the engine-only raster timings establish a comparison with
+Figma's complete application. For that comparison, capture both applications
+in the same browser, viewport and cache state, include document retrieval and
+collaboration startup, and inspect the filmstrip for the first visible canvas.
+Keep private exports and browser traces out of Git.
diff --git a/apps/web/src/features/block-fig/browser-test/collab-fixture.tsx b/apps/web/src/features/block-fig/browser-test/collab-fixture.tsx
index 395d98c8f3..25e6823149 100644
--- a/apps/web/src/features/block-fig/browser-test/collab-fixture.tsx
+++ b/apps/web/src/features/block-fig/browser-test/collab-fixture.tsx
@@ -25,9 +25,9 @@ import {
type FigSharing,
FigViewerProvider,
} from '../context/fig-viewer-context';
-import { fileFingerprint } from '../core/collab-entries';
import { createDesignCollabSession } from '../queries/fig-collab';
import { shareFigEngine } from '../queries/fig-sharing';
+import { prepareFigEngine } from '../queries/prepare-engine';
import { FigViewer } from '../views/fig-viewer';
import { MemorySyncServer } from './memory-sync';
@@ -84,6 +84,8 @@ function Person(props: {
const [saves, setSaves] = createSignal(0);
const [failure, setFailure] = createSignal<string>();
const [replaced, setReplaced] = createSignal(false);
+ const opening = prepareFigEngine(props.server.stored());
+ onCleanup(() => void opening.dispose());
const session = createDesignCollabSession({
documentId,
userId: props.user,
@@ -123,16 +125,22 @@ function Person(props: {
let sharedEngine: FigSharing | undefined;
const open = async () => {
try {
- const bytes = props.server.stored();
- const fingerprint = await fileFingerprint(bytes);
- opened = await FigEngine.open(bytes);
- if (closed) return;
+ const ready = await opening.take((e) => setFailure(e.message));
+ opened = ready.engine;
+ const fingerprint = ready.fingerprint;
+ if (closed) {
+ opened.close();
+ return;
+ }
if (shared) {
sharedEngine = await shareFigEngine(opened, shared, {
fingerprint,
delivered: session.delivered,
});
- if (closed) return;
+ if (closed) {
+ sharedEngine.close();
+ return;
+ }
sharedEngine.onReplaced(() => setReplaced(true));
setSharing(sharedEngine);
}
diff --git a/apps/web/src/features/block-fig/browser-test/collaboration.browser.e2e.ts b/apps/web/src/features/block-fig/browser-test/collaboration.browser.e2e.ts
index 36900365b8..e8aaa49fb0 100644
--- a/apps/web/src/features/block-fig/browser-test/collaboration.browser.e2e.ts
+++ b/apps/web/src/features/block-fig/browser-test/collaboration.browser.e2e.ts
@@ -105,7 +105,7 @@ test('edits, selections, and pointers reach the other person', async ({
// Undo is Alice's own, and Bob sees it.
await alice.click({ position: { x: 10, y: 10 } });
- await page.keyboard.press('Control+z');
+ await page.keyboard.press('ControlOrMeta+z');
await expect.poll(() => layersNamed(page, 1, 'Rectangle 1')).toBe(0);
await expect.poll(() => pixel(bob, 0.25, 0.76)).not.toEqual([217, 217, 217]);
diff --git a/apps/web/src/features/block-fig/browser-test/drag-composite.browser.e2e.ts b/apps/web/src/features/block-fig/browser-test/drag-composite.browser.e2e.ts
new file mode 100644
index 0000000000..fe93e0c37a
--- /dev/null
+++ b/apps/web/src/features/block-fig/browser-test/drag-composite.browser.e2e.ts
@@ -0,0 +1,214 @@
+import { fileURLToPath } from 'node:url';
+import { expect, test } from '@playwright/test';
+
+test('dragging the synth layer uses preview frames and remains undoable', async ({
+ page,
+}) => {
+ const file = process.env.FIG_DRAG_FILE;
+ test.skip(!file, 'Set FIG_DRAG_FILE to the synth reproduction');
+ await page.goto('/?edit');
+ await page.getByTestId('fig-file-input').setInputFiles(file!);
+ await expect(page.getByTestId('fig-viewer')).toBeVisible();
+ await page.getByRole('button', { name: 'Find layers', exact: true }).click();
+ await page
+ .getByRole('searchbox', { name: 'Find layers' })
+ .fill('Rectangle 70');
+ await page
+ .getByTestId('fig-search-hit')
+ .filter({ hasText: /^Rectangle 70$/ })
+ .first()
+ .click();
+ const canvas = page.getByTestId('fig-canvas');
+ await expect(page.getByTestId('fig-field-x')).toBeVisible();
+ const zoom = page.getByRole('button', { name: 'Zoom and view options' });
+ const initialZoom = await zoom.innerText();
+ await zoom.click();
+ await page
+ .getByRole('menuitem', { name: 'Zoom to selection', exact: false })
+ .click();
+ await expect(zoom).not.toHaveText(initialZoom);
+ const initialX = await page.getByTestId('fig-field-x').inputValue();
+ await page.evaluate(() => {
+ const engine = window.figFixture.engine()!;
+ const render = engine.render.bind(engine);
+ const canvas = document.querySelector('[data-testid="fig-canvas"]')!;
+ canvas.setAttribute('data-preview-frames', '0');
+ engine.render = (request) => {
+ if (request.priority === -4_000_000)
+ canvas.setAttribute(
+ 'data-preview-frames',
+ String(Number(canvas.getAttribute('data-preview-frames')) + 1)
+ );
+ return render(request);
+ };
+ });
+ const box = (await canvas.boundingBox())!;
+ const x = box.x + box.width * 0.65;
+ const y = box.y + box.height * 0.25;
+ await page.mouse.move(x, y);
+ await page.mouse.down();
+ await page.mouse.move(x + 55, y + 25, { steps: 20 });
+ await expect
+ .poll(() => canvas.getAttribute('data-preview-frames').then(Number))
+ .toBeGreaterThan(1);
+ const screenshot = test.info().outputPath('during-drag.png');
+ await canvas.screenshot({ path: screenshot });
+ await test.info().attach('during-drag', {
+ path: screenshot,
+ contentType: 'image/png',
+ });
+ await page.mouse.up();
+ await expect(page.getByTestId('fig-field-x')).not.toHaveValue(initialX);
+ await canvas.focus();
+ await page.keyboard.press('ControlOrMeta+z');
+ await expect(page.getByTestId('fig-field-x')).toHaveValue(initialX);
+ expect(await page.evaluate(() => window.figFixture.errors())).toEqual([]);
+});
+
+test('an unliftable corpus layer drags as complete frames', async ({
+ page,
+}) => {
+ const file = process.env.FIG_DRAG_FILE;
+ test.skip(!file, 'Set FIG_DRAG_FILE to the synth reproduction');
+ await page.goto('/?edit');
+ await page.getByTestId('fig-file-input').setInputFiles(file!);
+ await expect(page.getByTestId('fig-viewer')).toBeVisible();
+ const source = `/@fs${fileURLToPath(new URL('../primitives/create-tile-compositor.ts', import.meta.url))}`;
+ const result = await page.evaluate(async (source) => {
+ const { createTileCompositor } = await import(source);
+ const engine = window.figFixture.engine()!;
+ const rows = await engine.search(0, 'Rectangle 70');
+ const row = rows.find((r) => r.name === 'Rectangle 70')!;
+ const plan = await engine.liftPlan(0, [row.id]);
+ if (!plan.refused) throw new Error('Expected a composited ancestor');
+ const [geometry] = await engine.geometry(0, [row.id]);
+ const bounds = geometry.bounds;
+ const layout = await engine.openPage(0);
+ const view = {
+ camera: { x: bounds.x - 300, y: bounds.y - 200, zoom: 0.78 },
+ viewport: { w: 900, h: 950 },
+ dpr: 1,
+ };
+ let pending = 0;
+ const frameTimes: number[] = [];
+ let dragging = false;
+ const compositor = createTileCompositor({
+ engine: {
+ render: (request: Parameters<typeof engine.render>[0]) => {
+ pending++;
+ const started = performance.now();
+ const job = engine.render(request);
+ return {
+ id: job.id,
+ promise: job.promise.finally(() => {
+ pending--;
+ if (dragging) frameTimes.push(performance.now() - started);
+ }),
+ };
+ },
+ cancel: (ids: number[]) => engine.cancel(ids),
+ },
+ onTile: () => {},
+ });
+ const canvas = document.createElement('canvas');
+ canvas.width = view.viewport.w;
+ canvas.height = view.viewport.h;
+ const ctx = canvas.getContext('2d')!;
+ const idle = async () => {
+ while (pending) await new Promise((r) => setTimeout(r, 20));
+ };
+ compositor.setPage({
+ page: 0,
+ outline: false,
+ content: layout.bounds,
+ background: `rgba(${engine.summary.pages[0].background
+ .slice(0, 3)
+ .map((c) => c * 255)
+ .join(',')},1)`,
+ });
+ compositor.update(view);
+ await idle();
+ dragging = true;
+ compositor.beginInteractive();
+ for (let step = 0; step < 12; step++) {
+ const edit = await engine.apply(0, [
+ { op: 'translate', ids: [row.id], dx: 12, dy: 6 },
+ ]);
+ if (edit.dirty) compositor.invalidate(edit.dirty);
+ await new Promise((resolve) => setTimeout(resolve, 16));
+ }
+ await idle();
+ compositor.draw(ctx, view);
+ const lifted = ctx.getImageData(0, 0, canvas.width, canvas.height).data;
+ const liftedImage = canvas.toDataURL();
+ dragging = false;
+ const rendered = await engine.render({
+ page: 0,
+ x: view.camera.x,
+ y: view.camera.y,
+ scale: 0.78,
+ width: canvas.width,
+ height: canvas.height,
+ outline: false,
+ priority: 0,
+ }).promise;
+ ctx.drawImage(rendered!.bitmap, 0, 0);
+ rendered!.bitmap.close();
+ const actual = ctx.getImageData(0, 0, canvas.width, canvas.height).data;
+ let mismatched = 0;
+ for (let i = 0; i < actual.length; i += 4)
+ if (
+ Math.max(
+ ...[0, 1, 2].map((c) => Math.abs(actual[i + c] - lifted[i + c]))
+ ) > 32
+ )
+ mismatched++;
+ const committedImage = canvas.toDataURL();
+ compositor.endInteractive();
+ await idle();
+ compositor.draw(ctx, view);
+ const finalPixels = ctx.getImageData(
+ 0,
+ 0,
+ canvas.width,
+ canvas.height
+ ).data;
+ let finalMismatch = 0;
+ for (let i = 0; i < actual.length; i += 4)
+ if (
+ Math.max(
+ ...[0, 1, 2].map((c) => Math.abs(actual[i + c] - finalPixels[i + c]))
+ ) > 32
+ )
+ finalMismatch++;
+ compositor.dispose();
+ return {
+ mismatched,
+ finalMismatch,
+ pixels: canvas.width * canvas.height,
+ frameTimes,
+ liftedImage,
+ committedImage,
+ };
+ }, source);
+ await test.info().attach('lifted', {
+ body: Buffer.from(result.liftedImage.split(',')[1], 'base64'),
+ contentType: 'image/png',
+ });
+ await test.info().attach('committed', {
+ body: Buffer.from(result.committedImage.split(',')[1], 'base64'),
+ contentType: 'image/png',
+ });
+ console.info(
+ 'drag-composite',
+ JSON.stringify({
+ mismatched: result.mismatched,
+ pixels: result.pixels,
+ frameTimes: result.frameTimes,
+ })
+ );
+ // The moving preview trades fine edge detail for latency, but must not
+ // introduce the large rectangular corruption seen with mixed tile ages.
+ expect(result.mismatched / result.pixels).toBeLessThan(0.04);
+ expect(result.finalMismatch / result.pixels).toBeLessThan(0.01);
+});
diff --git a/apps/web/src/features/block-fig/browser-test/fig-chrome.browser.e2e.ts b/apps/web/src/features/block-fig/browser-test/fig-chrome.browser.e2e.ts
new file mode 100644
index 0000000000..67fdf86c6e
--- /dev/null
+++ b/apps/web/src/features/block-fig/browser-test/fig-chrome.browser.e2e.ts
@@ -0,0 +1,754 @@
+import { expect, type Page, test } from '@playwright/test';
+
+async function open(page: Page) {
+ await page.goto('/?file=showcase.fig&edit');
+ await expect(page.getByTestId('fig-toolbar')).toBeVisible();
+ await expect(page.getByTestId('fig-layer-row')).toHaveCount(2);
+}
+
+async function selectHome(page: Page) {
+ await page.getByTestId('fig-layer-row').filter({ hasText: 'Home' }).click();
+ await expect(page.getByTestId('fig-name')).toHaveValue('Home');
+}
+
+test('groups drawing tools, remembers the chosen shape, and supports keyboard menus', async ({
+ page,
+}) => {
+ await open(page);
+ await expect(page.getByTestId('fig-tool-ellipse')).toHaveCount(0);
+ const shapeMenu = page.getByTestId('fig-tool-menu-rectangle');
+ await shapeMenu.focus();
+ await page.keyboard.press('ArrowDown');
+ await expect(page.getByRole('menu', { name: 'Shape tools' })).toBeVisible();
+ await page.keyboard.press('End');
+ await expect(page.getByTestId('fig-choose-ellipse')).toBeFocused();
+ await page.keyboard.press('Enter');
+ await expect(page.getByTestId('fig-tool-ellipse')).toHaveAttribute(
+ 'aria-pressed',
+ 'true'
+ );
+ await expect(shapeMenu).toBeFocused();
+ await page.getByTestId('fig-canvas').focus();
+ await page.keyboard.press('v');
+ await expect(page.getByTestId('fig-tool-ellipse')).toHaveAttribute(
+ 'aria-pressed',
+ 'false'
+ );
+ await page.getByTestId('fig-tool-ellipse').click();
+ await expect(page.getByTestId('fig-tool-ellipse')).toHaveAttribute(
+ 'aria-pressed',
+ 'true'
+ );
+ await shapeMenu.click();
+ await page.keyboard.press('Escape');
+ await expect(page.getByRole('menu', { name: 'Shape tools' })).toBeHidden();
+ await expect(shapeMenu).toBeFocused();
+});
+
+test('opens search from Assets with the find shortcut, then returns to layers', async ({
+ page,
+}) => {
+ await open(page);
+ await expect(page.getByTestId('fig-layer-search')).toHaveCount(0);
+ await page.getByTestId('fig-tab-assets').click();
+ await page.getByTestId('fig-canvas').focus();
+ await page.keyboard.press('ControlOrMeta+f');
+ const search = page.getByTestId('fig-layer-search');
+ await expect(search).toBeFocused();
+ await search.fill('Primary button');
+ await page.getByTestId('fig-search-hit').click();
+ await expect(page.getByTestId('fig-name')).toHaveValue('Primary button');
+ await search.press('Escape');
+ await expect(search).toHaveCount(0);
+ await expect(page.getByTestId('fig-search-toggle')).toBeFocused();
+ await expect(page.getByTestId('fig-layers-heading')).toHaveText('Layers');
+ await expect(page.getByTestId('fig-page')).toHaveCount(2);
+});
+
+test('keeps view controls in the inspector and drawing tools on one row', async ({
+ page,
+}) => {
+ await page.setViewportSize({ width: 1024, height: 768 });
+ await open(page);
+ const toolbar = page.getByTestId('fig-toolbar');
+ await expect(toolbar.getByTestId('fig-zoom-menu')).toHaveCount(0);
+ await expect(
+ page.getByTestId('fig-design-panel').getByTestId('fig-zoom-menu')
+ ).toBeVisible();
+ const [tools, canvas] = await Promise.all([
+ toolbar.boundingBox(),
+ page.getByTestId('fig-canvas').boundingBox(),
+ ]);
+ expect(tools).not.toBeNull();
+ expect(canvas).not.toBeNull();
+ expect(tools!.height).toBeLessThanOrEqual(52);
+ expect(tools!.x).toBeGreaterThanOrEqual(canvas!.x);
+ expect(tools!.x + tools!.width).toBeLessThanOrEqual(
+ canvas!.x + canvas!.width
+ );
+ await page.getByTestId('fig-zoom-menu').click();
+ await expect(
+ page.getByRole('menu', { name: 'Zoom and view options' })
+ ).toBeVisible();
+ await page.keyboard.press('Escape');
+ await expect(page.getByTestId('fig-zoom-menu')).toBeFocused();
+});
+
+test('edits position, dimensions and appearance, and undoes from the file menu', async ({
+ page,
+}) => {
+ await open(page);
+ await selectHome(page);
+ const position = page.getByTestId('fig-position-section');
+ const layout = page.getByTestId('fig-auto-layout-section');
+ await expect(position.getByTestId('fig-field-x')).toBeVisible();
+ await expect(position.getByTestId('fig-field-w')).toHaveCount(0);
+ await expect(layout.getByTestId('fig-field-w')).toBeVisible();
+ const radius = page.getByTestId('fig-field-radius');
+ await radius.fill('16');
+ await radius.press('Enter');
+ await expect(radius).toHaveValue('16');
+ await page.getByTestId('fig-main-menu').click();
+ await page.getByTestId('fig-main-edit').hover();
+ await page.getByTestId('fig-undo').click();
+ await expect(radius).toHaveValue('0');
+ await expect(page.getByTestId('fig-save-state')).toHaveAttribute(
+ 'data-state',
+ 'saved'
+ );
+});
+
+test('switches Dev Mode and prototype without losing inspector mode on selection', async ({
+ page,
+}) => {
+ await open(page);
+ await selectHome(page);
+ const dev = page.getByTestId('fig-panel-tab-code');
+ await dev.click();
+ await expect(dev).toHaveAttribute('aria-pressed', 'true');
+ await page
+ .getByTestId('fig-layer-row')
+ .filter({ hasText: 'Settings' })
+ .click();
+ await expect(dev).toHaveAttribute('aria-pressed', 'true');
+ await page.getByTestId('fig-panel-tab-prototype').click();
+ await expect(dev).toHaveAttribute('aria-pressed', 'false');
+ await page.getByTestId('fig-panel-tab-design').click();
+ await expect(page.getByTestId('fig-position-section')).toBeVisible();
+});
+
+test('uses light editor chrome when the app is in light mode', async ({
+ page,
+}) => {
+ await page.addInitScript(() =>
+ document.addEventListener('DOMContentLoaded', () => {
+ document.documentElement.dataset.themeLight = 'true';
+ })
+ );
+ await open(page);
+ const panel = page.getByTestId('fig-design-panel');
+ await expect
+ .poll(() =>
+ panel.evaluate((el) =>
+ getComputedStyle(el).getPropertyValue('--color-panel').trim()
+ )
+ )
+ .toBe('#ffffff');
+ await page.getByTestId('fig-tool-menu-rectangle').click();
+ await expect
+ .poll(() =>
+ page
+ .getByRole('menu', { name: 'Shape tools' })
+ .evaluate((el) => getComputedStyle(el).backgroundColor)
+ )
+ .toBe('rgb(255, 255, 255)');
+});
+
+test('resizes both panels and preserves their widths after hiding and showing them', async ({
+ page,
+}) => {
+ await open(page);
+ const left = page.getByTestId('fig-resize-left');
+ await left.press('ArrowRight');
+ await expect(left).toHaveAttribute('aria-valuenow', '288');
+ await page.getByRole('button', { name: 'Hide layers', exact: true }).click();
+ await expect(page.getByTestId('fig-layers-panel')).toBeHidden();
+ await page.getByRole('button', { name: 'Show layers', exact: true }).click();
+ await expect(left).toHaveAttribute('aria-valuenow', '288');
+ const right = page.getByTestId('fig-resize-right');
+ await right.press('ArrowLeft');
+ await expect(right).toHaveAttribute('aria-valuenow', '248');
+ await page
+ .getByRole('button', { name: 'Hide properties', exact: true })
+ .click();
+ await expect(page.getByTestId('fig-design-panel')).toBeHidden();
+ await expect(page.getByTestId('fig-zoom-menu')).toBeVisible();
+ await page
+ .getByRole('button', { name: 'Show properties', exact: true })
+ .click();
+ await expect(right).toHaveAttribute('aria-valuenow', '248');
+});
+
+test('edits independent auto-layout padding without changing the other sides', async ({
+ page,
+}) => {
+ await open(page);
+ await selectHome(page);
+ await page
+ .getByRole('button', { name: 'Add auto layout', exact: true })
+ .click();
+ await page.getByTestId('fig-field-padding-h').fill('12');
+ await page.getByTestId('fig-field-padding-h').press('Enter');
+ await page.getByTestId('fig-padding-independent').click();
+ await page.getByTestId('fig-field-padding-right').fill('28');
+ await page.getByTestId('fig-field-padding-right').press('Enter');
+ await expect(page.getByTestId('fig-field-padding-left')).toHaveValue('12');
+ await expect(page.getByTestId('fig-field-padding-top')).toHaveValue('0');
+ await expect(page.getByTestId('fig-field-padding-bottom')).toHaveValue('0');
+ await expect(page.getByTestId('fig-field-padding-right')).toHaveValue('28');
+ await page
+ .getByTestId('fig-layer-row')
+ .filter({ hasText: 'Settings' })
+ .click();
+ await selectHome(page);
+ await expect(page.getByTestId('fig-field-padding-right')).toHaveValue('28');
+});
+
+test('shows only the comment tool as active and exits comments when a drawing tool is chosen', async ({
+ page,
+}) => {
+ await open(page);
+ await page.getByTestId('fig-tool-comment').click();
+ await expect(page.getByTestId('fig-tool-comment')).toHaveAttribute(
+ 'aria-pressed',
+ 'true'
+ );
+ await expect(page.getByTestId('fig-tool-move')).toHaveAttribute(
+ 'aria-pressed',
+ 'false'
+ );
+ await page.getByTestId('fig-tool-rectangle').click();
+ await expect(page.getByTestId('fig-tool-comment')).toHaveAttribute(
+ 'aria-pressed',
+ 'false'
+ );
+ await expect(page.getByTestId('fig-tool-rectangle')).toHaveAttribute(
+ 'aria-pressed',
+ 'true'
+ );
+ await expect(page.getByTestId('fig-design-panel')).toBeVisible();
+});
+
+test('navigates inspector and file tabs without nudging selected layers', async ({
+ page,
+}) => {
+ await open(page);
+ await selectHome(page);
+ const x = await page.getByTestId('fig-field-x').inputValue();
+ await page.getByTestId('fig-panel-tab-design').press('ArrowRight');
+ await expect(page.getByTestId('fig-panel-tab-prototype')).toBeFocused();
+ await expect(page.getByTestId('fig-panel-tab-prototype')).toHaveAttribute(
+ 'aria-selected',
+ 'true'
+ );
+ await page.getByTestId('fig-panel-tab-prototype').press('Home');
+ await expect(page.getByTestId('fig-field-x')).toHaveValue(x);
+ await page.getByTestId('fig-tab-layers').press('ArrowRight');
+ await expect(page.getByTestId('fig-tab-assets')).toBeFocused();
+ await page.getByTestId('fig-tab-assets').press('Home');
+ await expect(page.getByTestId('fig-layers-panel')).toBeVisible();
+ await page.getByTestId('fig-resize-left').press('ArrowRight');
+ await expect(page.getByTestId('fig-resize-left')).toHaveAttribute(
+ 'aria-valuenow',
+ '288'
+ );
+ await expect(page.getByTestId('fig-field-x')).toHaveValue(x);
+});
+
+test('opens selection actions with the keyboard in the fixed inspector header', async ({
+ page,
+}) => {
+ await open(page);
+ await selectHome(page);
+ const actions = page.getByTestId('fig-boolean-menu');
+ await actions.press('ArrowDown');
+ await expect(page.getByTestId('fig-menu-boolean-union')).toBeFocused();
+ await page.keyboard.press('End');
+ await expect(page.getByTestId('fig-menu-flatten')).toBeFocused();
+ await page.keyboard.press('Escape');
+ await expect(actions).toBeFocused();
+});
+
+test('keeps sizing beside its dimension and rotates through the inspector', async ({
+ page,
+}) => {
+ await open(page);
+ await selectHome(page);
+ await page
+ .getByRole('button', { name: 'Add auto layout', exact: true })
+ .click();
+ const width = page.getByTestId('fig-field-w');
+ const sizing = page.getByTestId('fig-sizing-w');
+ await sizing.click();
+ await page.getByRole('option', { name: 'Hug', exact: true }).click();
+ await expect(sizing).toHaveText('Hug');
+ const [fieldBox, sizingBox] = await Promise.all([
+ width.boundingBox(),
+ sizing.boundingBox(),
+ ]);
+ expect(Math.abs(fieldBox!.y - sizingBox!.y)).toBeLessThanOrEqual(5);
+ expect(sizingBox!.x).toBeGreaterThan(fieldBox!.x);
+ await sizing.click();
+ await page.getByRole('option', { name: 'Fixed', exact: true }).click();
+ await width.fill('400');
+ await width.press('Enter');
+ await expect(width).toHaveValue('400');
+ await page.getByTestId('fig-rotate-90').click();
+ await expect(page.getByTestId('fig-field-rotation')).toHaveValue('90');
+ await page.getByTestId('fig-main-menu').click();
+ await page.getByTestId('fig-main-edit').hover();
+ await page.getByTestId('fig-undo').click();
+ await expect(page.getByTestId('fig-field-rotation')).toHaveValue('0');
+});
+
+test('toggles layer visibility in Appearance and keeps the layer selected', async ({
+ page,
+}) => {
+ await open(page);
+ await selectHome(page);
+ const visible = page.getByTestId('fig-appearance-visible');
+ await visible.click();
+ await expect(visible).toHaveAttribute('aria-label', 'Show layer');
+ await expect(page.getByTestId('fig-name')).toHaveValue('Home');
+ await page.getByTestId('fig-main-menu').click();
+ await page.getByTestId('fig-main-edit').hover();
+ await page.getByTestId('fig-undo').click();
+ await expect(visible).toHaveAttribute('aria-label', 'Hide layer');
+});
+
+test('keeps typography settings beside the inspector and applies text options', async ({
+ page,
+}) => {
+ await page.goto('/?file=design-system.fig&edit');
+ await page.getByTestId('fig-search-toggle').click();
+ await page.getByTestId('fig-layer-search').fill('Heading');
+ await page.getByTestId('fig-search-hit').click();
+ await expect(page.getByTestId('fig-name')).toHaveValue('Heading');
+ await expect(
+ page.getByTestId('fig-auto-layout-section').getByTestId('fig-text-resize')
+ ).toBeVisible();
+ await expect(
+ page.getByTestId('fig-type').getByTestId('fig-text-resize')
+ ).toHaveCount(0);
+ await page.getByTestId('fig-type-settings').click();
+ const dialog = page.getByRole('dialog', { name: 'Type settings' });
+ const [popup, inspector] = await Promise.all([
+ dialog.boundingBox(),
+ page.getByTestId('fig-design-panel').boundingBox(),
+ ]);
+ expect(popup!.x + popup!.width).toBeLessThanOrEqual(inspector!.x);
+ await page.getByTestId('fig-underline').click();
+ await expect(page.getByTestId('fig-underline')).toHaveAttribute(
+ 'aria-pressed',
+ 'true'
+ );
+ await page.getByTestId('fig-text-case').click();
+ await page.getByRole('option', { name: 'Uppercase', exact: true }).click();
+ await expect(page.getByTestId('fig-text-case')).toHaveText('Uppercase');
+ await page.getByTestId('fig-field-paragraph-spacing').fill('12');
+ await page.getByTestId('fig-field-paragraph-spacing').press('Enter');
+ await expect(page.getByTestId('fig-field-paragraph-spacing')).toHaveValue(
+ '12'
+ );
+ await page.getByRole('button', { name: 'Close type settings' }).click();
+ await expect(dialog).toBeHidden();
+ await expect(page.getByTestId('fig-type-settings')).toBeFocused();
+});
+
+test('browses local component previews, switches to a list, and inserts a searched component', async ({
+ page,
+}) => {
+ await page.goto('/?file=design-system.fig&edit');
+ await page.getByTestId('fig-tab-assets').click();
+ const assets = page.getByTestId('fig-asset');
+ await expect.poll(() => assets.count()).toBeGreaterThan(0);
+ const count = await assets.count();
+ await expect(assets.first().locator('img')).toBeVisible();
+ await expect
+ .poll(() =>
+ assets
+ .first()
+ .locator('img')
+ .evaluate((img: HTMLImageElement) => img.naturalWidth)
+ )
+ .toBeGreaterThan(0);
+ await page.getByTestId('fig-assets-list').click();
+ await expect(page.getByTestId('fig-asset-preview')).toHaveCount(0);
+ await page.getByTestId('fig-assets-search').fill('Card');
+ await expect(assets).toHaveCount(1);
+ await assets.click();
+ await expect(page.getByTestId('fig-main-component')).toHaveText('Card');
+ await page.getByTestId('fig-assets-grid').click();
+ await expect(assets.locator('img')).toBeVisible();
+ await page.getByRole('button', { name: 'Clear asset search' }).click();
+ await expect(assets).toHaveCount(count);
+});
+
+test('keeps the floating toolbar centered and usable in a narrow split', async ({
+ page,
+}) => {
+ await page.setViewportSize({ width: 760, height: 720 });
+ await open(page);
+ const root = await page.getByTestId('fig-viewer').boundingBox();
+ const toolbar = await page.getByTestId('fig-toolbar').boundingBox();
+ expect(root).not.toBeNull();
+ expect(toolbar).not.toBeNull();
+ expect(toolbar!.x + toolbar!.width / 2).toBeCloseTo(
+ root!.x + root!.width / 2,
+ 0
+ );
+ for (const button of await page
+ .getByTestId('fig-toolbar')
+ .getByRole('button')
+ .all()) {
+ const box = await button.boundingBox();
+ expect(box!.x).toBeGreaterThanOrEqual(root!.x);
+ expect(box!.x + box!.width).toBeLessThanOrEqual(root!.x + root!.width);
+ }
+ await page.getByTestId('fig-tool-menu-rectangle').click();
+ await page.getByTestId('fig-choose-ellipse').click();
+ await expect(page.getByTestId('fig-tool-ellipse')).toHaveAttribute(
+ 'aria-pressed',
+ 'true'
+ );
+});
+
+test('locks inspector dimensions proportionally and undoes both dimensions together', async ({
+ page,
+}) => {
+ await open(page);
+ await selectHome(page);
+ const width = page.getByTestId('fig-field-w');
+ const height = page.getByTestId('fig-field-h');
+ const originalWidth = Number(await width.inputValue());
+ const originalHeight = Number(await height.inputValue());
+ await page.getByTestId('fig-lock-aspect-ratio').click();
+ await width.fill(String(originalWidth * 2));
+ await width.press('Enter');
+ await expect(width).toHaveValue(String(originalWidth * 2));
+ await expect(height).toHaveValue(String(originalHeight * 2));
+ await page.getByTestId('fig-canvas').focus();
+ await page.keyboard.press('ControlOrMeta+z');
+ await expect(width).toHaveValue(String(originalWidth));
+ await expect(height).toHaveValue(String(originalHeight));
+ await page.getByTestId('fig-lock-aspect-ratio').click();
+ await width.fill(String(originalWidth + 20));
+ await width.press('Enter');
+ await expect(width).toHaveValue(String(originalWidth + 20));
+ await expect(height).toHaveValue(String(originalHeight));
+});
+
+test('closes paint settings and returns focus to the swatch', async ({
+ page,
+}) => {
+ await open(page);
+ await selectHome(page);
+ const swatch = page.getByTestId('fig-fill-0-swatch');
+ await swatch.click();
+ await expect(page.getByTestId('fig-color-picker')).toBeVisible();
+ await page
+ .getByRole('button', { name: 'Close edit fill', exact: true })
+ .click();
+ await expect(page.getByTestId('fig-color-picker')).toBeHidden();
+ await expect(swatch).toBeFocused();
+});
+
+test('navigates font search results with arrow keys without moving the layer', async ({
+ page,
+}) => {
+ await page.goto('/?file=design-system.fig&edit');
+ await page.getByTestId('fig-search-toggle').click();
+ await page.getByTestId('fig-layer-search').fill('Heading');
+ await page.getByTestId('fig-search-hit').click();
+ const x = await page.getByTestId('fig-field-x').inputValue();
+ const y = await page.getByTestId('fig-field-y').inputValue();
+ await page.getByTestId('fig-font-family').click();
+ const search = page.getByTestId('fig-font-search');
+ await search.fill('Roboto');
+ const options = page.getByTestId('fig-font-option');
+ await expect.poll(() => options.count()).toBeGreaterThan(1);
+ const second = await options.nth(1).getAttribute('data-family');
+ await search.press('ArrowDown');
+ await expect(options.first()).toHaveAttribute('data-active', 'true');
+ await search.press('ArrowDown');
+ await expect(options.nth(1)).toHaveAttribute('data-active', 'true');
+ await search.press('Enter');
+ await expect(page.getByTestId('fig-font-picker')).toBeHidden();
+ await expect(page.getByTestId('fig-font-family')).toHaveAttribute(
+ 'data-value',
+ second!
+ );
+ await expect(page.getByTestId('fig-field-x')).toHaveValue(x);
+ await expect(page.getByTestId('fig-field-y')).toHaveValue(y);
+});
+
+test('keeps effect settings open across edits and closes nested color settings independently', async ({
+ page,
+}) => {
+ await open(page);
+ await selectHome(page);
+ await page.getByRole('button', { name: 'Add effects', exact: true }).click();
+ await expect(page.getByTestId('fig-effect-0-y')).toBeHidden();
+ const settings = page.getByTestId('fig-effect-0-settings');
+ await settings.click();
+ const popup = page.getByTestId('fig-effect-0-popover');
+ await expect(popup).toBeVisible();
+ for (const [field, value] of [
+ ['y', '8'],
+ ['blur', '20'],
+ ['spread', '4'],
+ ] as const) {
+ const input = page.getByTestId(`fig-effect-0-${field}`);
+ await input.fill(value);
+ await input.press('Enter');
+ await expect(input).toHaveValue(value);
+ await expect(popup).toBeVisible();
+ }
+ await page.getByTestId('fig-effect-0-swatch').click();
+ await page.getByTestId('fig-color-field-0').fill('FF6600');
+ await page.getByTestId('fig-color-field-0').press('Enter');
+ await expect(page.getByTestId('fig-color-field-0')).toHaveValue('FF6600');
+ await page
+ .getByRole('button', { name: 'Close shadow color', exact: true })
+ .click();
+ await expect(popup).toBeVisible();
+ await expect(page.getByTestId('fig-color-picker')).toBeHidden();
+ await page
+ .getByRole('button', { name: 'Close effect settings', exact: true })
+ .click();
+ await expect(popup).toBeHidden();
+ await expect(settings).toBeFocused();
+});
+
+test('searches comment text, replies and authors, and keeps view controls in the comments header', async ({
+ page,
+}) => {
+ await open(page);
+ await page.evaluate(() => {
+ const fixture = window.figFixture;
+ const pageId = fixture.engine()!.summary.pages[0].id;
+ const anchor = { pageId, nodeId: null, x: 100, y: 100 };
+ const threadId = fixture.comments.arrive(
+ fixture.comments.people[1],
+ 'Review the spacing',
+ { anchor }
+ );
+ fixture.comments.arrive(fixture.comments.people[2], 'Typography is ready', {
+ threadId,
+ });
+ fixture.comments.arrive(fixture.comments.people[0], 'Update the icon', {
+ anchor: { ...anchor, x: 300 },
+ });
+ });
+ await page.getByTestId('fig-tool-comment').click();
+ const panel = page.getByTestId('fig-comments-panel');
+ await expect(panel.getByTestId('fig-zoom-menu')).toBeVisible();
+ await expect(panel.getByTestId('fig-present-button')).toBeVisible();
+ await expect(panel.getByTestId('fig-comment-row')).toHaveCount(2);
+ const search = panel.getByTestId('fig-comments-search');
+ await search.fill('typography');
+ await expect(panel.getByTestId('fig-comment-row')).toHaveCount(1);
+ await expect(panel.getByTestId('fig-comment-row')).toContainText(
+ 'Review the spacing'
+ );
+ await search.fill('casey');
+ await expect(panel.getByTestId('fig-comment-row')).toHaveCount(1);
+ await search.fill('not in this file');
+ await expect(panel.getByTestId('fig-comments-empty')).toHaveText(
+ 'No matching comments.'
+ );
+ await panel.getByRole('button', { name: 'Clear comment search' }).click();
+ await expect(panel.getByTestId('fig-comment-row')).toHaveCount(2);
+ await panel.getByTestId('fig-comments-filter').click();
+ await page.getByTestId('fig-comments-filter-resolved').click();
+ await expect(panel.getByTestId('fig-comments-empty')).toHaveText(
+ 'No resolved comments.'
+ );
+ await panel.getByRole('button', { name: 'Hide properties' }).click();
+ await expect(panel).toBeHidden();
+ await page.getByRole('button', { name: 'Show properties' }).click();
+ await expect(panel).toBeVisible();
+});
+
+test('uses the same inspector sections for multiple selected layers', async ({
+ page,
+}) => {
+ await open(page);
+ await selectHome(page);
+ await page
+ .getByTestId('fig-layer-row')
+ .filter({ hasText: 'Settings' })
+ .click({ modifiers: ['Shift'] });
+ const panel = page.getByTestId('fig-design-panel');
+ await expect(panel).toContainText('2 layers selected');
+ await expect(panel.getByTestId('fig-boolean-menu')).toBeVisible();
+ const position = panel.getByTestId('fig-position-section');
+ const layout = panel.getByTestId('fig-auto-layout-section');
+ await expect(position.getByTestId('fig-align-left')).toBeVisible();
+ await expect(position.getByTestId('fig-field-rotation')).toBeVisible();
+ await expect(position.getByTestId('fig-field-w')).toHaveCount(0);
+ await expect(layout.getByTestId('fig-field-w')).toBeVisible();
+ await panel.getByTestId('fig-boolean-menu').focus();
+ await page.keyboard.press('ArrowDown');
+ await expect(
+ page.getByRole('menu', { name: 'Boolean groups' })
+ ).toBeVisible();
+ await page.keyboard.press('Escape');
+});
+
+test('navigates main-menu categories by keyboard without moving the selection', async ({
+ page,
+}) => {
+ await open(page);
+ await selectHome(page);
+ const x = await page.getByTestId('fig-field-x').inputValue();
+ const menu = page.getByTestId('fig-main-menu');
+ await menu.focus();
+ await page.keyboard.press('ArrowDown');
+ await page.getByTestId('fig-main-edit').focus();
+ await page.keyboard.press('ArrowRight');
+ await expect(page.getByTestId('fig-main-copy')).toBeVisible();
+ await page.keyboard.press('ArrowLeft');
+ await expect(page.getByTestId('fig-main-edit')).toBeFocused();
+ await page.getByTestId('fig-main-view').focus();
+ await page.keyboard.press('ArrowRight');
+ await expect(page.getByTestId('fig-zoom-100')).toBeVisible();
+ await page.getByTestId('fig-zoom-100').focus();
+ await page.keyboard.press('Enter');
+ await expect(menu).toBeFocused();
+ await expect(page.getByTestId('fig-zoom-menu')).toContainText('100%');
+ await expect(page.getByTestId('fig-field-x')).toHaveValue(x);
+});
+
+test('runs a grouped object command from the main menu and undoes it', async ({
+ page,
+}) => {
+ await open(page);
+ await selectHome(page);
+ await page.getByTestId('fig-main-menu').click();
+ await page.getByTestId('fig-main-object').hover();
+ await page.getByTestId('fig-main-toggle-visible').click();
+ await expect(page.getByTestId('fig-appearance-visible')).toHaveAttribute(
+ 'aria-label',
+ 'Show layer'
+ );
+ await page.getByTestId('fig-main-menu').click();
+ await page.getByTestId('fig-main-edit').hover();
+ await page.getByTestId('fig-undo').click();
+ await expect(page.getByTestId('fig-appearance-visible')).toHaveAttribute(
+ 'aria-label',
+ 'Hide layer'
+ );
+});
+
+test('keeps prototype interaction rows compact and opens persistent settings beside the inspector', async ({
+ page,
+}) => {
+ await page.goto('/?file=prototype.fig&edit');
+ await expect(page.getByTestId('fig-toolbar')).toBeVisible();
+ await page.getByTestId('fig-search-toggle').click();
+ await page.getByTestId('fig-layer-search').fill('Next');
+ await page.getByTestId('fig-search-hit').click();
+ await page.getByTestId('fig-panel-tab-prototype').click();
+ const row = page.getByTestId('fig-proto-open');
+ const bounds = await row.boundingBox();
+ expect(bounds!.height).toBeLessThanOrEqual(32);
+ await expect(page.getByTestId('fig-proto-settings')).toHaveCount(0);
+ await row.press('Enter');
+ const settings = page.getByTestId('fig-proto-settings');
+ await expect(settings).toBeVisible();
+ const [popoverBounds, panelBounds] = await Promise.all([
+ settings.boundingBox(),
+ page.getByRole('complementary', { name: 'Properties' }).boundingBox(),
+ ]);
+ expect(popoverBounds!.x + popoverBounds!.width).toBeLessThanOrEqual(
+ panelBounds!.x
+ );
+ await page.getByTestId('fig-proto-destination').click();
+ await page.getByRole('option', { name: 'Done', exact: true }).click();
+ await expect(settings).toBeVisible();
+ await expect(row).toContainText('Done');
+ await page
+ .getByRole('button', { name: 'Close interaction settings' })
+ .click();
+ await expect(row).toBeFocused();
+ await expect(settings).toHaveCount(0);
+});
+
+test('creates a component from the selection header and undoes it', async ({
+ page,
+}) => {
+ await open(page);
+ await selectHome(page);
+ await page.getByTestId('fig-create-component').click();
+ await expect(page.getByTestId('fig-create-component')).toHaveCount(0);
+ await expect(page.getByTestId('fig-component-section')).toBeVisible();
+ await page.getByTestId('fig-main-menu').click();
+ await page.getByTestId('fig-main-edit').hover();
+ await page.getByTestId('fig-undo').click();
+ await expect(page.getByTestId('fig-create-component')).toBeVisible();
+ await expect(page.getByTestId('fig-name')).toHaveValue('Home');
+});
+
+test('disables selection commands when there is no selection', async ({
+ page,
+}) => {
+ await open(page);
+ await page.getByTestId('fig-main-menu').click();
+ await page.getByTestId('fig-main-edit').hover();
+ await expect(page.getByTestId('fig-main-copy')).toHaveAttribute(
+ 'aria-disabled',
+ 'true'
+ );
+ await expect(page.getByTestId('fig-main-paste')).not.toHaveAttribute(
+ 'aria-disabled',
+ 'true'
+ );
+ await page.keyboard.press('Escape');
+ await selectHome(page);
+ await page.getByTestId('fig-main-menu').click();
+ await page.getByTestId('fig-main-edit').hover();
+ await expect(page.getByTestId('fig-main-copy')).not.toHaveAttribute(
+ 'aria-disabled',
+ 'true'
+ );
+});
+
+test('drags panel edges without drawing or moving the selected layer', async ({
+ page,
+}) => {
+ await open(page);
+ await selectHome(page);
+ await page.getByTestId('fig-tool-rectangle').click();
+ const left = page.getByTestId('fig-resize-left');
+ const right = page.getByTestId('fig-resize-right');
+ for (const [edge, delta, expected] of [
+ [left, 64, '344'],
+ [right, -48, '288'],
+ ] as const) {
+ const box = await edge.boundingBox();
+ const x = box!.x + box!.width / 2;
+ const y = box!.y + 200;
+ await page.mouse.move(x, y);
+ await page.mouse.down();
+ await page.mouse.move(x + delta, y, { steps: 8 });
+ await page.mouse.up();
+ await expect(edge).toHaveAttribute('aria-valuenow', expected);
+ await page.mouse.move(720, 300);
+ await expect(edge).toHaveAttribute('aria-valuenow', expected);
+ }
+ await expect(page.getByTestId('fig-layer-row')).toHaveCount(2);
+ await expect(page.getByTestId('fig-name')).toHaveValue('Home');
+ await expect(page.getByTestId('fig-field-x')).toHaveValue('0');
+ await expect(page.getByTestId('fig-field-w')).toHaveValue('360');
+});
diff --git a/apps/web/src/features/block-fig/browser-test/fig-design-system.browser.e2e.ts b/apps/web/src/features/block-fig/browser-test/fig-design-system.browser.e2e.ts
index 6a9a6154fe..86b574929d 100644
--- a/apps/web/src/features/block-fig/browser-test/fig-design-system.browser.e2e.ts
+++ b/apps/web/src/features/block-fig/browser-test/fig-design-system.browser.e2e.ts
@@ -14,6 +14,8 @@ async function open(page: Page) {
/** Selects the layer named exactly `name` on the open page. */
async function select(page: Page, name: string) {
+ if (!(await page.getByTestId('fig-layer-search').isVisible()))
+ await page.getByTestId('fig-search-toggle').click();
await page.getByTestId('fig-layer-search').fill(name);
await page
.getByTestId('fig-search-hit')
@@ -88,7 +90,7 @@ test('sets an instance’s properties, swaps it, and resets it', async ({
.click();
await expect(page.getByTestId('fig-main-component')).toHaveText('Icon/Heart');
await page.getByTestId('fig-canvas').focus();
- await page.keyboard.press('Control+z');
+ await page.keyboard.press('ControlOrMeta+z');
await expect(page.getByTestId('fig-main-component')).toHaveText('Card');
// Go to main component.
@@ -102,16 +104,20 @@ test('switches variants of an instance', async ({ page }) => {
await open(page);
await select(page, 'Button');
const type = page.getByTestId('fig-variant-Type');
- await expect(type).toHaveValue('Primary');
- await expect(type.locator('option')).toHaveText(['Primary', 'Secondary']);
- await type.selectOption('Secondary');
- await expect(type).toHaveValue('Secondary');
+ await expect(type).toHaveText('Primary');
+ await type.click();
+ await expect(page.getByRole('option')).toHaveText(['Primary', 'Secondary']);
+ await page.keyboard.press('Escape');
+ await type.click();
+ await page.getByRole('option', { name: 'Secondary', exact: true }).click();
+ await expect(type).toHaveText('Secondary');
// The text property survives the switch.
const label = page.getByTestId('fig-prop-Label');
await label.fill('Go');
await label.press('Enter');
- await type.selectOption('Primary');
- await expect(type).toHaveValue('Primary');
+ await type.click();
+ await page.getByRole('option', { name: 'Primary', exact: true }).click();
+ await expect(type).toHaveText('Primary');
await expect(label).toHaveValue('Go');
await expectSavedCleanly(page);
});
@@ -140,7 +146,8 @@ test('edits a component set’s variants and properties', async ({ page }) => {
// Create a boolean property on the set.
await section.getByRole('button', { name: 'Add variant' }).first().click();
await expect(page.getByTestId('fig-new-property')).toBeVisible();
- await page.getByTestId('fig-new-property-kind').selectOption('BOOL');
+ await page.getByTestId('fig-new-property-kind').click();
+ await page.getByRole('option', { name: 'Boolean', exact: true }).click();
await page.getByTestId('fig-new-property-name').fill('Disabled');
await page.getByTestId('fig-new-property-create').click();
await expect(page.getByTestId('fig-property-name-Disabled')).toBeVisible();
@@ -156,14 +163,19 @@ test('binds layers of a main component to properties', async ({ page }) => {
const bindings = page.getByTestId('fig-bindings-section');
await expect(bindings).toBeVisible();
const visible = page.getByTestId('fig-bind-VISIBLE');
- await expect(visible).toHaveValue('');
+ await expect(visible).toHaveText('None');
// "Create boolean property…" makes one from the layer and binds it.
- await visible.selectOption({ label: 'Create boolean property…' });
- await expect(visible.locator('option:checked')).toHaveText('Show');
- await visible.selectOption({ label: 'Show icon' });
- await expect(visible.locator('option:checked')).toHaveText('Show icon');
- await visible.selectOption({ label: 'None' });
- await expect(visible).toHaveValue('');
+ await visible.click();
+ await page
+ .getByRole('option', { name: 'Create boolean property…', exact: true })
+ .click();
+ await expect(visible).toHaveText('Show');
+ await visible.click();
+ await page.getByRole('option', { name: 'Show icon', exact: true }).click();
+ await expect(visible).toHaveText('Show icon');
+ await visible.click();
+ await page.getByRole('option', { name: 'None', exact: true }).click();
+ await expect(visible).toHaveText('None');
await expectSavedCleanly(page);
});
@@ -225,7 +237,8 @@ test('lists variables, binds colors, and switches modes', async ({ page }) => {
await expect(page.getByTestId('fig-variable-FILL')).toHaveText('Surface');
await expect(page.getByTestId('fig-fill-0-hex')).toHaveValue('FFFFFF');
const mode = page.getByTestId('fig-variable-mode-Theme');
- await mode.selectOption({ label: 'Dark' });
+ await mode.click();
+ await page.getByRole('option', { name: 'Dark', exact: true }).click();
await expect(page.getByTestId('fig-fill-0-hex')).toHaveValue('000000');
// The logo's Brand color aliases Surface in the dark mode.
diff --git a/apps/web/src/features/block-fig/browser-test/fig-design-ui.browser.e2e.ts b/apps/web/src/features/block-fig/browser-test/fig-design-ui.browser.e2e.ts
index ca7ac683df..8ceb4479de 100644
--- a/apps/web/src/features/block-fig/browser-test/fig-design-ui.browser.e2e.ts
+++ b/apps/web/src/features/block-fig/browser-test/fig-design-ui.browser.e2e.ts
@@ -136,7 +136,7 @@ test('right-click menus act on layers and the canvas', async ({ page }) => {
await expect(page.getByTestId('fig-field-x')).toHaveValue('400');
await expect(page.getByTestId('fig-field-rotation')).toHaveValue('0');
await page.getByTestId('fig-canvas').focus();
- await page.keyboard.press('Control+z');
+ await page.keyboard.press('ControlOrMeta+z');
// A vertical flip reads as a half turn about the center.
await page.keyboard.press('Shift+V');
await expect(page.getByTestId('fig-field-rotation')).toHaveValue(/^-?180$/);
@@ -171,7 +171,8 @@ test('picks colors and edits gradients', async ({ page }) => {
await expect
.poll(async () => (await pixelAt(page, 20, 20)).join(','))
.toBe('255,0,0');
- await page.getByTestId('fig-color-format').selectOption('rgb');
+ await page.getByTestId('fig-color-format').click();
+ await page.getByRole('option', { name: 'RGB', exact: true }).click();
await expect(page.getByTestId('fig-color-field-1')).toHaveValue('0');
// A drag across the square is one undo step: top left is white.
@@ -180,12 +181,13 @@ test('picks colors and edits gradients', async ({ page }) => {
await page.keyboard.press('Escape');
await expect(picker).toBeHidden();
await page.getByTestId('fig-canvas').focus();
- await page.keyboard.press('Control+z');
+ await page.keyboard.press('ControlOrMeta+z');
await expect(page.getByTestId('fig-fill-0-hex')).toHaveValue('FF0000');
// Linear gradient: click the bar to add a stop, Delete removes it.
await page.getByTestId('fig-fill-0-swatch').click();
- await page.getByTestId('fig-paint-type').selectOption('GRADIENT_LINEAR');
+ await page.getByTestId('fig-paint-type').click();
+ await page.getByRole('option', { name: 'Linear', exact: true }).click();
await expect(page.getByTestId('fig-fill-0')).toContainText('Linear');
const stops = page.getByTestId('fig-gradient-stop');
await expect(stops).toHaveCount(2);
@@ -197,7 +199,8 @@ test('picks colors and edits gradients', async ({ page }) => {
await expect
.poll(async () => (await pixelAt(page, 5, 100))[0])
.toBeGreaterThan(240);
- await page.getByTestId('fig-paint-type').selectOption('GRADIENT_RADIAL');
+ await page.getByTestId('fig-paint-type').click();
+ await page.getByRole('option', { name: 'Radial', exact: true }).click();
await expect(page.getByTestId('fig-fill-0')).toContainText('Radial');
});
@@ -256,7 +259,7 @@ test('edits several layers at once, with mixed values', async ({ page }) => {
await rows(page)
.filter({ hasText: 'Rectangle 1' })
.click({ modifiers: ['Shift'] });
- await expect(page.getByTestId('fig-mixed')).toContainText(
+ await expect(page.getByTestId('fig-design-panel')).toContainText(
'3 layers selected'
);
await expect(page.getByTestId('fig-field-w')).toHaveValue('Mixed');
@@ -273,7 +276,7 @@ test('edits several layers at once, with mixed values', async ({ page }) => {
await rows(page)
.filter({ hasText: 'Rectangle 2' })
.click({ modifiers: ['ControlOrMeta'] });
- await expect(page.getByTestId('fig-mixed')).toContainText(
+ await expect(page.getByTestId('fig-design-panel')).toContainText(
'2 layers selected'
);
diff --git a/apps/web/src/features/block-fig/browser-test/fig-handoff.browser.e2e.ts b/apps/web/src/features/block-fig/browser-test/fig-handoff.browser.e2e.ts
index 84875f9c06..0ba8f59208 100644
--- a/apps/web/src/features/block-fig/browser-test/fig-handoff.browser.e2e.ts
+++ b/apps/web/src/features/block-fig/browser-test/fig-handoff.browser.e2e.ts
@@ -15,6 +15,8 @@ async function openNew(page: Page) {
}
async function selectLayer(page: Page, name: string) {
+ if (!(await page.getByTestId('fig-layer-search').isVisible()))
+ await page.getByTestId('fig-search-toggle').click();
await page.getByTestId('fig-layer-search').fill(name);
await page
.getByTestId('fig-search-hit')
@@ -90,11 +92,14 @@ test('stores export presets and exports them as a ZIP', async ({ page }) => {
await expect(page.getByTestId('fig-export-size-0')).toHaveValue('1x');
await add.click();
await expect(page.getByTestId('fig-export-size-1')).toHaveValue('2x');
- await page.getByTestId('fig-export-format-1').selectOption('JPEG');
+ await page.getByTestId('fig-export-format-1').click();
+ await page.getByRole('option', { name: 'JPEG', exact: true }).click();
+ await page.getByTestId('fig-export-options-0').click();
await page.getByTestId('fig-export-suffix-0').fill('-small');
await page.getByTestId('fig-export-suffix-0').press('Enter');
await add.click();
- await page.getByTestId('fig-export-format-2').selectOption('SVG');
+ await page.getByTestId('fig-export-format-2').click();
+ await page.getByRole('option', { name: 'SVG', exact: true }).click();
await page.getByTestId('fig-export-options-2').click();
await page.getByTestId('fig-export-include-id-2').check();
await expect(page.getByTestId('fig-export-row-2')).toBeVisible();
@@ -145,6 +150,7 @@ test('stores export presets and exports them as a ZIP', async ({ page }) => {
test('exports the page frames to PDF', async ({ page }) => {
await openShowcase(page);
await page.getByTestId('fig-main-menu').click();
+ await page.getByTestId('fig-main-file').hover();
await page.getByTestId('fig-menu-export-frames-pdf').click();
await expect
.poll(() => page.evaluate(() => window.figFixture.downloads()))
@@ -215,9 +221,10 @@ test('adds layout grids, toggles them, and saves them', async ({ page }) => {
await openNew(page);
const id = await drawFrame(page, [100, 100], [400, 300]);
const grids = page.getByTestId('fig-layout-grids');
- await grids.getByRole('button', { name: 'Add layout grid' }).click();
+ await grids.getByRole('button', { name: 'Add layout guide' }).click();
await expect(page.getByTestId('fig-grid-0')).toBeVisible();
- await page.getByTestId('fig-grid-type-0').selectOption('COLUMNS');
+ await page.getByTestId('fig-grid-type-0').click();
+ await page.getByRole('option', { name: 'Columns (5)', exact: true }).click();
await page.getByTestId('fig-grid-settings-0').click();
await page.getByTestId('fig-grid-count-0').fill('3');
await page.getByTestId('fig-grid-count-0').press('Enter');
@@ -233,11 +240,15 @@ test('adds layout grids, toggles them, and saves them', async ({ page }) => {
expect((await overlayPixel(page, 195, 200))[3]).toBe(0);
// Ctrl+⇧4 (⌃G on a Mac) hides them.
await page.getByTestId('fig-canvas').focus();
- await page.keyboard.press('Control+Shift+Digit4');
+ await page.keyboard.press(
+ process.platform === 'darwin' ? 'Control+g' : 'Control+Shift+Digit4'
+ );
await expect
.poll(async () => (await overlayPixel(page, 140, 200))[3])
.toBe(0);
- await page.keyboard.press('Control+Shift+Digit4');
+ await page.keyboard.press(
+ process.platform === 'darwin' ? 'Control+g' : 'Control+Shift+Digit4'
+ );
await expect
.poll(async () => (await overlayPixel(page, 140, 200))[3])
.toBeGreaterThan(0);
diff --git a/apps/web/src/features/block-fig/browser-test/fig-libraries.browser.e2e.ts b/apps/web/src/features/block-fig/browser-test/fig-libraries.browser.e2e.ts
index c8e0f8891c..879e7d7c89 100644
--- a/apps/web/src/features/block-fig/browser-test/fig-libraries.browser.e2e.ts
+++ b/apps/web/src/features/block-fig/browser-test/fig-libraries.browser.e2e.ts
@@ -124,6 +124,8 @@ test('publishes a library, uses it in another design, and updates it', async ({
await expect(
page.getByTestId('fig-layer-row').filter({ hasText: 'Card' })
).toBeVisible();
+ if (!(await page.getByTestId('fig-layer-search').isVisible()))
+ await page.getByTestId('fig-search-toggle').click();
await page.getByTestId('fig-layer-search').fill('Background');
await page
.getByTestId('fig-search-hit')
diff --git a/apps/web/src/features/block-fig/browser-test/fig-review.browser.e2e.ts b/apps/web/src/features/block-fig/browser-test/fig-review.browser.e2e.ts
index fc51371b62..b960562bce 100644
--- a/apps/web/src/features/block-fig/browser-test/fig-review.browser.e2e.ts
+++ b/apps/web/src/features/block-fig/browser-test/fig-review.browser.e2e.ts
@@ -37,6 +37,8 @@ async function presented(page: Page, frame: string) {
/** Selects a layer through the layer search. */
async function select(page: Page, name: string) {
+ if (!(await page.getByTestId('fig-layer-search').isVisible()))
+ await page.getByTestId('fig-search-toggle').click();
await page.getByTestId('fig-layer-search').fill(name);
await page
.getByTestId('fig-search-hit')
@@ -158,30 +160,34 @@ test('edits interactions and flows in the Prototype tab and saves them', async (
await page.getByTestId('fig-panel-tab-prototype').click();
const panel = page.getByTestId('fig-prototype-panel');
await expect(panel.getByTestId('fig-proto-interaction')).toHaveCount(1);
- await expect(panel.getByTestId('fig-proto-destination')).toHaveValue('1:20');
- await expect(panel.getByTestId('fig-proto-transition')).toHaveValue(
- 'DISSOLVE'
- );
+ await panel.getByTestId('fig-proto-open').click();
+ await expect(page.getByTestId('fig-proto-destination')).toHaveText('Details');
+ await expect(page.getByTestId('fig-proto-transition')).toHaveText('Dissolve');
// The selection's connection is drawn on the canvas.
await expect(
page.locator('[data-testid="fig-noodle"][data-from="1:11"]')
).toHaveAttribute('data-to', '1:20');
await expect(page.getByTestId('fig-flow-badge')).toHaveText(/Onboarding/);
- await panel.getByTestId('fig-proto-destination').selectOption('1:40');
+ await page.getByTestId('fig-proto-destination').click();
+ await page.getByRole('option', { name: 'Done', exact: true }).click();
await expect(
page.locator('[data-testid="fig-noodle"][data-from="1:11"]')
).toHaveAttribute('data-to', '1:40');
- await panel
- .getByTestId('fig-proto-transition')
- .selectOption('PUSH_FROM_RIGHT');
- await panel.getByTestId('fig-proto-duration').fill('450');
- await panel.getByTestId('fig-proto-duration').press('Enter');
+ await page.getByTestId('fig-proto-transition').click();
+ await page.getByRole('option', { name: 'Push', exact: true }).click();
+ await page.getByTestId('fig-proto-duration').fill('450');
+ await page.getByTestId('fig-proto-duration').press('Enter');
+ await page
+ .getByRole('button', { name: 'Close interaction settings' })
+ .click();
// A second interaction: open the menu as an overlay.
await panel.getByTestId('fig-proto-add').click();
await expect(panel.getByTestId('fig-proto-interaction')).toHaveCount(2);
- await panel.getByTestId('fig-proto-action').nth(1).selectOption('overlay');
- await panel.getByTestId('fig-proto-destination').nth(1).selectOption('1:30');
+ await page.getByTestId('fig-proto-action').click();
+ await page.getByRole('option', { name: 'Open overlay', exact: true }).click();
+ await page.getByTestId('fig-proto-destination').click();
+ await page.getByRole('option', { name: 'Menu', exact: true }).click();
const proto = () =>
page.evaluate(async () => {
@@ -200,6 +206,9 @@ test('edits interactions and flows in the Prototype tab and saves them', async (
{ navigation: 'OVERLAY', destination: '1:30' },
]);
+ await page
+ .getByRole('button', { name: 'Close interaction settings' })
+ .click();
// A flow starting point on another frame.
await select(page, 'Unlinked');
await panel.getByTestId('fig-flow-add').click();
@@ -210,6 +219,8 @@ test('edits interactions and flows in the Prototype tab and saves them', async (
await select(page, 'Next');
await panel.getByTestId('fig-proto-remove').nth(1).click();
await expect(panel.getByTestId('fig-proto-interaction')).toHaveCount(1);
+ await page.getByTestId('fig-main-menu').click();
+ await page.getByTestId('fig-main-edit').hover();
await page.getByTestId('fig-undo').click();
await expect(panel.getByTestId('fig-proto-interaction')).toHaveCount(2);
@@ -308,11 +319,13 @@ test('comments: pins, replies, mentions, unread, resolve, and moving with the fr
await page.keyboard.press('Escape');
await expect(pin).toHaveCount(0);
await expect(panel.getByTestId('fig-comment-row')).toHaveCount(0);
- await panel.getByTestId('fig-comments-filter-resolved').click();
+ await panel.getByTestId('fig-comments-filter').click();
+ await page.getByTestId('fig-comments-filter-resolved').click();
await expect(panel.getByTestId('fig-comment-row')).toHaveCount(1);
await panel.getByTestId('fig-comment-row').click();
await popover.getByTestId('fig-comment-reopen').click();
- await panel.getByTestId('fig-comments-filter-open').click();
+ await panel.getByTestId('fig-comments-filter').click();
+ await page.getByTestId('fig-comments-filter-open').click();
await expect(panel.getByTestId('fig-comment-row')).toHaveCount(1);
// The pin moves with its frame.
diff --git a/apps/web/src/features/block-fig/browser-test/fig-shapes.browser.e2e.ts b/apps/web/src/features/block-fig/browser-test/fig-shapes.browser.e2e.ts
index fc06664c75..7c6eb86757 100644
--- a/apps/web/src/features/block-fig/browser-test/fig-shapes.browser.e2e.ts
+++ b/apps/web/src/features/block-fig/browser-test/fig-shapes.browser.e2e.ts
@@ -97,7 +97,7 @@ test('combines shapes with boolean operations and flattens them', async ({
}) => {
await openNew(page);
await drawTwoShapes(page);
- await page.keyboard.press('Control+a');
+ await page.keyboard.press('ControlOrMeta+a');
await expect(page.getByTestId('fig-design-panel')).toContainText(
'2 layers selected'
);
@@ -121,10 +121,10 @@ test('combines shapes with boolean operations and flattens them', async ({
// Undo goes back to the subtraction.
await page.getByTestId('fig-canvas').focus();
- await page.keyboard.press('Control+z');
+ await page.keyboard.press('ControlOrMeta+z');
await expect.poll(() => isShape(page, 240, 200)).toBe(false);
- // The toolbar menu flattens it into one vector layer.
+ // The selection menu flattens it into one vector layer.
await page.getByTestId('fig-boolean-menu').click();
await page.getByTestId('fig-menu-flatten').click();
await expect(page.getByTestId('fig-design-panel')).toContainText('Vector');
@@ -171,7 +171,7 @@ test('draws with the pen and edits the points', async ({ page }) => {
await expect.poll(() => isDark(page, 250, 80)).toBe(true);
// Undo puts the point back.
await canvas.focus();
- await page.keyboard.press('Control+z');
+ await page.keyboard.press('ControlOrMeta+z');
await expect(page.getByTestId('fig-field-y')).toHaveValue('100');
// A double-click on the last point ends an open path (without adding
@@ -201,6 +201,8 @@ test('draws with the pen and edits the points', async ({ page }) => {
test('exports SVG that draws like the PNG', async ({ page }) => {
await page.goto('/?file=showcase.fig');
await expect(page.getByTestId('fig-layer-row').first()).toBeVisible();
+ if (!(await page.getByTestId('fig-layer-search').isVisible()))
+ await page.getByTestId('fig-search-toggle').click();
await page.getByTestId('fig-layer-search').fill('Home');
await page
.getByTestId('fig-search-hit')
@@ -209,7 +211,8 @@ test('exports SVG that draws like the PNG', async ({ page }) => {
.click();
const exports = page.getByTestId('fig-export');
await exports.getByRole('button', { name: 'Add export' }).click();
- await page.getByTestId('fig-export-format-0').selectOption('SVG');
+ await page.getByTestId('fig-export-format-0').click();
+ await page.getByRole('option', { name: 'SVG', exact: true }).click();
await page.getByTestId('fig-export-button').click();
await expect
.poll(() => page.evaluate(() => window.figFixture.downloads()))
@@ -259,6 +262,7 @@ test('exports SVG that draws like the PNG', async ({ page }) => {
// "Copy as SVG" puts the markup on the clipboard.
await page.context().grantPermissions(['clipboard-read', 'clipboard-write']);
+ await page.getByRole('button', { name: 'Copy as', exact: true }).click();
await page.getByTestId('fig-copy-svg').click();
await expect
.poll(() => page.evaluate(() => navigator.clipboard.readText()))
@@ -269,6 +273,8 @@ test('copies layers into another file', async ({ page, context }) => {
await context.grantPermissions(['clipboard-read', 'clipboard-write']);
await page.goto('/?file=showcase.fig&edit');
await expect(page.getByTestId('fig-layer-row').first()).toBeVisible();
+ if (!(await page.getByTestId('fig-layer-search').isVisible()))
+ await page.getByTestId('fig-search-toggle').click();
await page.getByTestId('fig-layer-search').fill('Primary button');
await page
.getByTestId('fig-search-hit')
@@ -277,7 +283,7 @@ test('copies layers into another file', async ({ page, context }) => {
.click();
await page.getByTestId('fig-layer-search').fill('');
await page.getByTestId('fig-canvas').focus();
- await page.keyboard.press('Control+c');
+ await page.keyboard.press('ControlOrMeta+c');
await expect
.poll(() =>
page.evaluate(async () => {
@@ -293,7 +299,7 @@ test('copies layers into another file', async ({ page, context }) => {
const other = await context.newPage();
await openNew(other);
await other.getByTestId('fig-canvas').focus();
- await other.keyboard.press('Control+v');
+ await other.keyboard.press('ControlOrMeta+v');
await expect(other.getByTestId('fig-layer-row')).toHaveText([
'Primary button',
]);
@@ -320,7 +326,7 @@ test('copies layers into another file', async ({ page, context }) => {
// Numbered after the pasted frame.
await expect(other.getByTestId('fig-name')).toHaveValue('Frame 2');
await other.getByTestId('fig-canvas').focus();
- await other.keyboard.press('Control+v');
+ await other.keyboard.press('ControlOrMeta+v');
await expect(other.getByTestId('fig-name')).toHaveValue('Primary button');
await other.getByTestId('fig-canvas').focus();
await other.keyboard.press('Shift+Enter');
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
index 99a2dd4988..102a687f66 100644
--- 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
@@ -118,7 +118,7 @@ test('runs actions from the actions menu (⌘P)', async ({ page }) => {
);
return seen;
});
- await page.keyboard.press('Control+p');
+ await page.keyboard.press('ControlOrMeta+p');
const palette = page.getByTestId('fig-actions');
await expect(palette).toBeVisible();
// The browser does not print.
@@ -139,13 +139,13 @@ test('runs actions from the actions menu (⌘P)', async ({ page }) => {
'true'
);
// Escape closes it; ⌘P again too.
- await page.keyboard.press('Control+p');
+ await page.keyboard.press('ControlOrMeta+p');
await expect(palette).toBeVisible();
await page.keyboard.press('Escape');
await expect(palette).toBeHidden();
- await page.keyboard.press('Control+p');
+ await page.keyboard.press('ControlOrMeta+p');
await expect(palette).toBeVisible();
- await page.keyboard.press('Control+p');
+ await page.keyboard.press('ControlOrMeta+p');
await expect(palette).toBeHidden();
});
@@ -153,9 +153,9 @@ 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 page.keyboard.press('ControlOrMeta+.');
await expect(page.getByTestId('fig-layers-panel')).toBeHidden();
- await page.keyboard.press('Control+.');
+ await page.keyboard.press('ControlOrMeta+.');
await expect(page.getByTestId('fig-layers-panel')).toBeVisible();
});
@@ -166,7 +166,7 @@ test('aligns, distributes, sets opacity, and swaps fill and stroke', async ({
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 page.keyboard.press('ControlOrMeta+a');
await expect(page.getByTestId('fig-design-panel')).toContainText(
'3 layers selected'
);
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 646c4114cc..c9a4e415c9 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
@@ -68,13 +68,16 @@ async function canvasCenter(page: Page) {
/** Selects a layer through the layer search, then zooms to it. */
async function focusLayer(page: Page, name: string) {
+ if (!(await page.getByTestId('fig-layer-search').isVisible()))
+ await page.getByTestId('fig-search-toggle').click();
await page.getByTestId('fig-layer-search').fill(name);
await page
.getByTestId('fig-search-hit')
.filter({ hasText: name })
.first()
.click();
- await page.getByTestId('fig-layer-search').fill('');
+ await page.getByRole('button', { name: 'Close search', exact: true }).click();
+ await expect(page.getByTestId('fig-design-panel')).toContainText(name);
await page.getByTestId('fig-canvas').focus();
await page.keyboard.press('Shift+2');
}
@@ -315,7 +318,7 @@ test('moves layers lifted off the page, one edit at the drop', async ({
await expect.poll(() => color(120, 150)).toBe('other');
// The move is one step.
await canvas.focus();
- await page.keyboard.press('Control+z');
+ await page.keyboard.press('ControlOrMeta+z');
await expect(page.getByTestId('fig-field-x')).toHaveValue('100');
await expect.poll(() => color(120, 150)).toBe('red');
await expect
@@ -385,15 +388,15 @@ test('undo and redo bring back the selection', async ({ page }) => {
)
);
await canvas.focus();
- await page.keyboard.press('Control+d');
+ await page.keyboard.press('ControlOrMeta+d');
await expect(rows).toHaveCount(2);
await expect.poll(selectedRows).toEqual([0]);
// As in Figma, undoing the duplicate selects the original again …
- await page.keyboard.press('Control+z');
+ await page.keyboard.press('ControlOrMeta+z');
await expect(rows).toHaveCount(1);
await expect.poll(selectedRows).toEqual([0]);
// … and redoing it, the copy.
- await page.keyboard.press('Control+Shift+z');
+ await page.keyboard.press('ControlOrMeta+Shift+z');
await expect(rows).toHaveCount(2);
await expect.poll(selectedRows).toEqual([0]);
// Undoing a nudge of a layer no longer selected selects it.
@@ -403,7 +406,7 @@ test('undo and redo bring back the selection', async ({ page }) => {
await page.keyboard.press('ArrowRight');
await page.keyboard.press('Escape');
await expect.poll(selectedRows).toEqual([]);
- await page.keyboard.press('Control+z');
+ await page.keyboard.press('ControlOrMeta+z');
await expect.poll(selectedRows).toEqual([1]);
});
@@ -418,18 +421,21 @@ test('lays out with auto layout', async ({ page }) => {
await dragOnCanvas(page, [200, 100], [260, 160]);
await expect(page.getByTestId('fig-name')).toHaveValue('Rectangle 2');
await canvas.focus();
- await page.keyboard.press('Control+a');
- await expect(page.getByText('2 layers selected')).toBeVisible();
+ await page.keyboard.press('ControlOrMeta+a');
+ await expect(page.getByTestId('fig-design-panel')).toContainText(
+ '2 layers selected'
+ );
await page.keyboard.press('Shift+A');
await expect(page.getByTestId('fig-layer-row').first()).toHaveText('Frame');
// Side by side with the 60 px gap between them, hugging both.
- await expect(page.getByTestId('fig-sizing-w')).toHaveValue('HUG');
- await expect(page.getByTestId('fig-sizing-h')).toHaveValue('HUG');
+ await expect(page.getByTestId('fig-sizing-w')).toHaveText('Hug');
+ await expect(page.getByTestId('fig-sizing-h')).toHaveText('Hug');
await expect(page.getByTestId('fig-field-w')).toHaveValue('160');
- // Dragging the first square past the second swaps them.
+ // Drop past the second square, inside the frame, to reorder. Dropping
+ // outside the frame now reparents the square onto the page.
await canvas.focus();
await page.keyboard.press('Escape');
- await dragOnCanvas(page, [120, 120], [262, 122]);
+ await dragOnCanvas(page, [120, 120], [252, 122]);
await expect(page.getByTestId('fig-name')).toHaveValue('Rectangle 1');
await expect(page.getByTestId('fig-field-x')).toHaveValue('120');
await expect(page.getByTestId('fig-field-y')).toHaveValue('0');
@@ -446,10 +452,10 @@ test('lays out with auto layout', async ({ page }) => {
// Fixing the width and filling it with a child.
await page.getByTestId('fig-field-w').fill('300');
await page.getByTestId('fig-field-w').press('Enter');
- await expect(page.getByTestId('fig-sizing-w')).toHaveValue('FIXED');
+ await expect(page.getByTestId('fig-sizing-w')).toHaveText('Fixed');
await canvas.focus();
- await page.keyboard.press('Control+z');
- await expect(page.getByTestId('fig-sizing-w')).toHaveValue('HUG');
+ await page.keyboard.press('ControlOrMeta+z');
+ await expect(page.getByTestId('fig-sizing-w')).toHaveText('Hug');
await expect(page.getByTestId('fig-field-w')).toHaveValue('150');
});
@@ -464,7 +470,8 @@ test('keeps layers pinned with constraints', async ({ page }) => {
await dragOnCanvas(page, [250, 100], [300, 150]);
await expect(page.getByTestId('fig-name')).toHaveValue('Rectangle 1');
await expect(page.getByTestId('fig-field-x')).toHaveValue('200');
- await page.getByTestId('fig-constraint-h').selectOption('MAX');
+ await page.getByTestId('fig-constraint-h').click();
+ await page.getByRole('option', { name: 'Right', exact: true }).click();
await canvas.focus();
await page.keyboard.press('Shift+Enter');
await expect(page.getByTestId('fig-name')).toHaveValue('Frame 1');
@@ -490,7 +497,7 @@ test('makes components, places instances, and detaches them', async ({
await canvas.focus();
await page.keyboard.press('Shift+Enter');
await expect(page.getByTestId('fig-name')).toHaveValue('Frame 1');
- await page.keyboard.press('Control+Alt+k');
+ await page.keyboard.press('ControlOrMeta+Alt+k');
await expect(page.getByTestId('fig-design-panel')).toContainText('Component');
await page.getByTestId('fig-tab-assets').click();
await page.getByTestId('fig-asset').filter({ hasText: 'Frame 1' }).click();
@@ -516,7 +523,7 @@ test('makes components, places instances, and detaches them', async ({
'Frame 1',
]);
await canvas.focus();
- await page.keyboard.press('Control+Alt+b');
+ await page.keyboard.press('ControlOrMeta+Alt+b');
await expect(page.getByTestId('fig-design-panel')).not.toContainText(
'of Frame 1'
);
@@ -529,11 +536,13 @@ test('adds and edits shadows', async ({ page }) => {
await dragOnCanvas(page, [100, 100], [200, 200]);
await expect(page.getByTestId('fig-name')).toHaveValue('Rectangle 1');
await page.getByRole('button', { name: 'Add effects' }).click();
+ await page.getByTestId('fig-effect-0-settings').click();
await expect(page.getByTestId('fig-effect-0-y')).toHaveValue('4');
await page.getByTestId('fig-effect-0-blur').fill('20');
await page.getByTestId('fig-effect-0-blur').press('Enter');
await expect(page.getByTestId('fig-effect-0-blur')).toHaveValue('20');
- await page.getByTestId('fig-effect-0-type').selectOption('LAYER_BLUR');
+ await page.getByTestId('fig-effect-0-type').click();
+ await page.getByRole('option', { name: 'Layer blur', exact: true }).click();
await expect(page.getByTestId('fig-effect-0-y')).toBeHidden();
});
@@ -548,8 +557,10 @@ test('resizes several layers and rotates one', async ({ page }) => {
await dragOnCanvas(page, [200, 100], [260, 160]);
await expect(page.getByTestId('fig-name')).toHaveValue('Rectangle 2');
await canvas.focus();
- await page.keyboard.press('Control+a');
- await expect(page.getByText('2 layers selected')).toBeVisible();
+ await page.keyboard.press('ControlOrMeta+a');
+ await expect(page.getByTestId('fig-design-panel')).toContainText(
+ '2 layers selected'
+ );
// The selection box spans 100–260 × 100–160; its corner doubles it.
await dragOnCanvas(page, [260, 160], [420, 220]);
await page
@@ -628,9 +639,9 @@ test('edits fills from the design panel and undoes', async ({ page }) => {
};
await expect.poll(red).toBe(true);
await page.getByTestId('fig-canvas').focus();
- await page.keyboard.press('Control+z');
+ await page.keyboard.press('ControlOrMeta+z');
await expect.poll(red).toBe(false);
- await page.keyboard.press('Control+Shift+z');
+ await page.keyboard.press('ControlOrMeta+Shift+z');
await expect.poll(red).toBe(true);
});
@@ -664,7 +675,8 @@ test('styles text from the design panel', async ({ page }) => {
await page.keyboard.press('Escape');
const width = page.getByTestId('fig-field-w');
const regular = Number(await width.inputValue());
- await page.getByTestId('fig-font-weight').selectOption('700');
+ await page.getByTestId('fig-font-weight').click();
+ await page.getByRole('option', { name: 'Bold', exact: true }).click();
await expect
.poll(async () => Number(await width.inputValue()))
.toBeGreaterThan(regular);
@@ -673,12 +685,14 @@ test('styles text from the design panel', async ({ page }) => {
await lineHeight.fill('200%');
await lineHeight.press('Enter');
await expect(page.getByTestId('fig-field-h')).toHaveValue('24');
+ await page.getByTestId('fig-type-settings').click();
await page.getByTestId('fig-underline').click();
await expect(page.getByTestId('fig-underline')).toHaveAttribute(
'aria-pressed',
'true'
);
- await page.getByTestId('fig-text-case').selectOption('UPPER');
+ await page.getByTestId('fig-text-case').click();
+ await page.getByRole('option', { name: 'Uppercase', exact: true }).click();
await expect(page.getByTestId('fig-text-content')).toHaveText('Type');
});
diff --git a/apps/web/src/features/block-fig/browser-test/fixture.tsx b/apps/web/src/features/block-fig/browser-test/fixture.tsx
index 5b28d9c222..4ac9f562b0 100644
--- a/apps/web/src/features/block-fig/browser-test/fixture.tsx
+++ b/apps/web/src/features/block-fig/browser-test/fixture.tsx
@@ -17,6 +17,7 @@ import { render } from 'solid-js/web';
import { FigOpening } from '../components/fig-opening';
import { FigViewerProvider } from '../context/fig-viewer-context';
import type { FigCommentAnchor, FigPerson } from '../core/comments';
+import { createFontSource } from '../queries/font-source';
import { FigViewer } from '../views/fig-viewer';
import { CollabFixture, type FixtureCollab } from './collab-fixture';
import { fixtureFontSource } from './font-source';
@@ -83,7 +84,8 @@ function Fixture() {
const [current, setCurrent] = createSignal<string>();
const comments = createMemoryComments();
- const fonts = fixtureFontSource();
+ const fixtureFonts = fixtureFontSource();
+ const fonts = params.has('realFonts') ? createFontSource() : fixtureFonts;
window.figFixture = {
engine,
errors,
@@ -96,7 +98,7 @@ function Fixture() {
notified: comments.notified,
people: FIXTURE_PEOPLE,
},
- fontRequests: fonts.requests,
+ fontRequests: fixtureFonts.requests,
};
// Several people on one design, side by side (`?collab&people=a,b`).
@@ -224,7 +226,7 @@ function Fixture() {
)}
</Show>
<Show when={opening()} keyed>
- {(bytes) => <FigOpening bytes={bytes} />}
+ <FigOpening />
</Show>
<Show when={engine()} keyed>
{(e) => {
diff --git a/apps/web/src/features/block-fig/browser-test/frame-drop.browser.e2e.ts b/apps/web/src/features/block-fig/browser-test/frame-drop.browser.e2e.ts
new file mode 100644
index 0000000000..78c8c0c98c
--- /dev/null
+++ b/apps/web/src/features/block-fig/browser-test/frame-drop.browser.e2e.ts
@@ -0,0 +1,184 @@
+import { expect, test } from '@playwright/test';
+
+for (const auto of [false, true]) {
+ test(`dragging into ${auto ? 'auto layout' : 'a frame'} reparents and undoes as one move`, async ({
+ page,
+ }) => {
+ await page.goto('/?new&edit');
+ await expect(page.getByTestId('fig-viewer')).toBeVisible();
+ const seed = await page.evaluate(async (auto) => {
+ const engine = window.figFixture.engine()!;
+ const parent = engine.summary.pages[0].id;
+ let sourceParent = parent;
+ if (auto) {
+ const container = await engine.apply(0, [
+ {
+ op: 'create',
+ parent,
+ node: {
+ type: 'FRAME',
+ name: 'Original parent',
+ x: 0,
+ y: 0,
+ width: 40,
+ height: 40,
+ props: { opacity: 0.5, clipContent: false },
+ },
+ },
+ ]);
+ sourceParent = container.created[0];
+ }
+ const source = await engine.apply(0, [
+ {
+ op: 'create',
+ parent: sourceParent,
+ node: {
+ type: 'RECTANGLE',
+ name: 'Moving rectangle',
+ x: 0,
+ y: 0,
+ width: 40,
+ height: 40,
+ props: { fills: [{ color: 'FF0000' }] },
+ },
+ },
+ ]);
+ const frame = await engine.apply(0, [
+ {
+ op: 'create',
+ parent,
+ node: {
+ type: 'FRAME',
+ name: 'Destination',
+ x: 180,
+ y: -40,
+ width: 220,
+ height: 160,
+ props: {
+ fills: [{ color: 'EEEEEE' }],
+ ...(auto
+ ? {
+ layoutMode: 'HORIZONTAL',
+ itemSpacing: 10,
+ paddingLeft: 10,
+ paddingTop: 10,
+ sizingHorizontal: 'FIXED',
+ sizingVertical: 'FIXED',
+ }
+ : {}),
+ },
+ },
+ },
+ ]);
+ const frameId = frame.created[0];
+ if (auto)
+ await engine.apply(
+ 0,
+ [0, 1].map((i) => ({
+ op: 'create',
+ parent: frameId,
+ node: {
+ type: 'RECTANGLE',
+ name: `Sibling ${i}`,
+ x: 0,
+ y: 0,
+ width: 40,
+ height: 40,
+ props: { fills: [{ color: '0000FF' }] },
+ },
+ }))
+ );
+ return {
+ bytes: Array.from(await engine.save()),
+ source: source.created[0],
+ frame: frameId,
+ };
+ }, auto);
+ await page.getByTestId('fig-file-input').setInputFiles({
+ name: 'drop-test.fig',
+ mimeType: 'application/octet-stream',
+ buffer: Buffer.from(seed.bytes),
+ });
+ await expect(page.getByRole('banner')).toContainText('drop-test');
+ await expect(page.getByTestId('fig-viewer')).toBeVisible();
+ await page
+ .getByRole('button', { name: 'Find layers', exact: true })
+ .click();
+ await page
+ .getByRole('searchbox', { name: 'Find layers' })
+ .fill('Moving rectangle');
+ await page
+ .getByTestId('fig-search-hit')
+ .filter({ hasText: /^Moving rectangle$/ })
+ .click();
+ await expect(page.getByTestId('fig-field-x')).toBeVisible();
+ const zoom = page.getByRole('button', { name: 'Zoom and view options' });
+ await zoom.click();
+ await page.getByRole('menuitem', { name: 'Zoom to selection' }).click();
+ await zoom.click();
+ await page.getByRole('menuitem', { name: 'Zoom to 100%' }).click();
+ await expect(zoom).toHaveText('100%');
+ const canvas = page.getByTestId('fig-canvas');
+ const box = (await canvas.boundingBox())!;
+ const start = { x: box.x + box.width / 2, y: box.y + box.height / 2 };
+ // Release between the two existing auto-layout children.
+ const dx = 235 - 20;
+ const dy = -10 - 20;
+ await page.mouse.move(start.x, start.y);
+ await page.mouse.down();
+ await page.mouse.move(start.x + dx, start.y + dy, { steps: 12 });
+ await page.mouse.up();
+ const ancestors = () =>
+ page.evaluate(
+ async (id) =>
+ (await window.figFixture.engine()!.ancestry(0, id)).map((r) => r.id),
+ seed.source
+ );
+ await expect.poll(ancestors).toContain(seed.frame);
+ if (auto) {
+ await expect
+ .poll(() =>
+ page.evaluate(
+ async (id) =>
+ (await window.figFixture.engine()!.layers(0, id))
+ .map((r) => r.name)
+ .reverse(),
+ seed.frame
+ )
+ )
+ .toEqual(['Sibling 0', 'Moving rectangle', 'Sibling 1']);
+ } else {
+ const info = await page.evaluate(
+ (id) => window.figFixture.engine()!.nodeInfo(0, id),
+ seed.source
+ );
+ expect(info.bounds.x).toBeCloseTo(dx, 0);
+ expect(info.bounds.y).toBeCloseTo(dy, 0);
+ }
+ await canvas.focus();
+ await page.keyboard.press('ControlOrMeta+z');
+ await expect.poll(ancestors).not.toContain(seed.frame);
+ const restored = await page.evaluate(
+ (id) => window.figFixture.engine()!.nodeInfo(0, id),
+ seed.source
+ );
+ expect(restored.bounds.x).toBeCloseTo(0, 0);
+ expect(restored.bounds.y).toBeCloseTo(0, 0);
+ await page.keyboard.press('ControlOrMeta+Shift+z');
+ await expect.poll(ancestors).toContain(seed.frame);
+ const placed = await page.evaluate(
+ (id) => window.figFixture.engine()!.nodeInfo(0, id),
+ seed.source
+ );
+ await page.mouse.move(
+ start.x + placed.bounds.x + placed.bounds.w / 2 - 20,
+ start.y + placed.bounds.y + placed.bounds.h / 2 - 20
+ );
+ await page.mouse.down();
+ await page.mouse.move(start.x - 100, start.y + 200, { steps: 12 });
+ await page.mouse.up();
+ await expect.poll(ancestors).toEqual([seed.source]);
+ await page.screenshot({ path: test.info().outputPath('after-drop.png') });
+ expect(await page.evaluate(() => window.figFixture.errors())).toEqual([]);
+ });
+}
diff --git a/apps/web/src/features/block-fig/browser-test/frame-labels.browser.e2e.ts b/apps/web/src/features/block-fig/browser-test/frame-labels.browser.e2e.ts
new file mode 100644
index 0000000000..cf840deb10
--- /dev/null
+++ b/apps/web/src/features/block-fig/browser-test/frame-labels.browser.e2e.ts
@@ -0,0 +1,107 @@
+import { expect, type Page, test } from '@playwright/test';
+import { fitRect, pageToScreen } from '../core/camera';
+
+async function drawFrame(page: Page) {
+ await page.goto('/?new');
+ const canvas = page.getByTestId('fig-canvas');
+ await expect(canvas).toBeVisible();
+ const box = await canvas.boundingBox();
+ if (!box) throw new Error('Canvas missing');
+ await canvas.focus();
+ await page.keyboard.press('f');
+ await page.mouse.move(box.x + 100, box.y + 100);
+ await page.mouse.down();
+ await page.mouse.move(box.x + 300, box.y + 300, { steps: 4 });
+ await page.mouse.up();
+ await expect(page.getByTestId('fig-name')).toHaveValue('Frame 1');
+ return { x: box.x + 110, y: box.y + 88 };
+}
+
+test('canvas frame labels select, rename, cancel and undo', async ({
+ page,
+}) => {
+ const label = await drawFrame(page);
+ await page.keyboard.press('Escape');
+ await page.mouse.click(label.x, label.y);
+ await expect(page.getByTestId('fig-name')).toHaveValue('Frame 1');
+ await page.mouse.dblclick(label.x, label.y);
+ const input = page.getByTestId('fig-frame-rename');
+ await expect(input).toBeFocused();
+ expect(
+ await input.evaluate((el: HTMLInputElement) => [
+ el.selectionStart,
+ el.selectionEnd,
+ ])
+ ).toEqual([0, 7]);
+ await input.fill('Inbox');
+ await input.press('Enter');
+ await expect(input).toBeHidden();
+ await expect(page.getByTestId('fig-name')).toHaveValue('Inbox');
+ await expect(
+ page.getByTestId('fig-layer-row').filter({ hasText: 'Inbox' })
+ ).toBeVisible();
+ await page.mouse.dblclick(label.x, label.y);
+ await input.fill('Cancelled name');
+ await input.press('Escape');
+ await expect(page.getByTestId('fig-name')).toHaveValue('Inbox');
+ await page.keyboard.press('ControlOrMeta+z');
+ await expect(page.getByTestId('fig-name')).toHaveValue('Frame 1');
+ await page.mouse.dblclick(label.x, label.y);
+ await input.fill('Saved on blur');
+ await page.getByTestId('fig-name').click();
+ await expect(
+ page.getByTestId('fig-layer-row').filter({ hasText: 'Saved on blur' })
+ ).toBeVisible();
+ expect(await page.evaluate(() => window.figFixture.errors())).toEqual([]);
+});
+
+test('read-only labels select frames without opening a name editor', async ({
+ page,
+}) => {
+ await page.goto('/?file=showcase.fig');
+ const canvas = page.getByTestId('fig-canvas');
+ await expect(canvas).toBeVisible();
+ await expect(page.getByTestId('fig-layer-row')).toHaveCount(2);
+ await canvas.focus();
+ await page.keyboard.press('Shift+1');
+ const box = await canvas.boundingBox();
+ if (!box) throw new Error('Canvas missing');
+ const layout = await page.evaluate(() =>
+ window.figFixture.engine()!.openPage(0)
+ );
+ const home = layout.frames.find((frame) => frame.name === 'Home')!;
+ const camera = fitRect(layout.bounds, { w: box.width, h: box.height }, 1);
+ const point = pageToScreen(camera, home.bounds);
+ await page.mouse.click(box.x + point.x + 10, box.y + point.y - 12);
+ const row = page.locator(`[data-layer-id="${home.id}"]`);
+ await expect(row).toHaveClass(/bg-accent\/20/);
+ await page.mouse.dblclick(box.x + point.x + 10, box.y + point.y - 12);
+ await expect(page.getByTestId('fig-frame-rename')).toHaveCount(0);
+ await expect(row).toHaveClass(/bg-accent\/20/);
+});
+
+test('dragging a frame label moves its frame', async ({ page }) => {
+ const label = await drawFrame(page);
+ const id = await page
+ .getByTestId('fig-layer-row')
+ .first()
+ .getAttribute('data-layer-id');
+ if (!id) throw new Error('Frame missing');
+ const before = await page.evaluate(
+ (id) => window.figFixture.engine()!.nodeInfo(0, id),
+ id
+ );
+ await page.mouse.move(label.x, label.y);
+ await page.mouse.down();
+ await page.mouse.move(label.x + 50, label.y + 50, { steps: 8 });
+ await page.mouse.up();
+ await expect
+ .poll(async () => {
+ const after = await page.evaluate(
+ (id) => window.figFixture.engine()!.nodeInfo(0, id),
+ id
+ );
+ return [after.x - before.x, after.y - before.y];
+ })
+ .toEqual([50, 50]);
+});
diff --git a/apps/web/src/features/block-fig/browser-test/layer-lock.browser.e2e.ts b/apps/web/src/features/block-fig/browser-test/layer-lock.browser.e2e.ts
new file mode 100644
index 0000000000..a1041dbd40
--- /dev/null
+++ b/apps/web/src/features/block-fig/browser-test/layer-lock.browser.e2e.ts
@@ -0,0 +1,194 @@
+import { expect, test } from '@playwright/test';
+
+test('shares a component lock and unlock between editors', async ({ page }) => {
+ await page.setViewportSize({ width: 2000, height: 900 });
+ await page.goto('/?collab&people=alice,bob&file=showcase.fig');
+ await expect
+ .poll(() =>
+ page.evaluate(() =>
+ window.figFixture?.collab
+ ?.people()
+ .every((person) => person.engine() && person.peers().length > 0)
+ )
+ )
+ .toBe(true);
+ for (const name of ['Alice', 'Bob']) {
+ const editor = page.getByTestId(`fig-person-${name}`);
+ await editor
+ .getByRole('button', { name: 'Find layers', exact: true })
+ .click();
+ await editor
+ .getByRole('searchbox', { name: 'Find layers' })
+ .fill('Primary button');
+ await editor
+ .getByTestId('fig-search-hit')
+ .filter({ hasText: /^Primary button$/ })
+ .click();
+ await editor.getByRole('button', { name: 'Close search' }).click();
+ }
+ const alice = page
+ .getByTestId('fig-person-Alice')
+ .getByTestId('fig-layer-row')
+ .filter({ hasText: /^Primary button$/ });
+ const bob = page
+ .getByTestId('fig-person-Bob')
+ .getByTestId('fig-layer-row')
+ .filter({ hasText: /^Primary button$/ });
+ await alice.hover();
+ await alice.getByRole('button', { name: 'Lock', exact: true }).click();
+ await expect(
+ bob.getByRole('button', { name: 'Unlock', exact: true })
+ ).toBeVisible();
+ await bob.getByRole('button', { name: 'Unlock', exact: true }).click();
+ await expect(
+ alice.getByRole('button', {
+ name: 'Lock',
+ exact: true,
+ includeHidden: true,
+ })
+ ).toBeAttached();
+ await expect(
+ bob.getByRole('button', { name: 'Lock', exact: true, includeHidden: true })
+ ).toBeAttached();
+ expect(await page.evaluate(() => window.figFixture.errors())).toEqual([]);
+});
+
+test('unlocks all selected layers with the shortcut and supports undo', async ({
+ page,
+}) => {
+ await page.goto('/?new');
+ await expect(page.getByTestId('fig-viewer')).toBeVisible();
+ const canvas = page.getByTestId('fig-canvas');
+ const box = await canvas.boundingBox();
+ if (!box) throw new Error('Canvas missing');
+ for (const x of [100, 300]) {
+ await canvas.focus();
+ await page.keyboard.press('r');
+ await page.mouse.move(box.x + x, box.y + 100);
+ await page.mouse.down();
+ await page.mouse.move(box.x + x + 100, box.y + 200, { steps: 4 });
+ await page.mouse.up();
+ }
+ const rows = page.getByTestId('fig-layer-row');
+ await expect(rows).toHaveCount(2);
+ await rows.nth(0).click();
+ await rows.nth(1).click({ modifiers: ['Shift'] });
+ await canvas.focus();
+ const locks = () =>
+ page.evaluate(async () => {
+ const engine = window.figFixture.engine()!;
+ const hits = await engine.search(0, 'Rectangle');
+ return (
+ await engine.rows(
+ 0,
+ hits.map((r) => r.id)
+ )
+ ).map((r) => r.locked);
+ });
+ await page.keyboard.press('ControlOrMeta+Shift+l');
+ await expect.poll(locks).toEqual([true, true]);
+ await page.keyboard.press('ControlOrMeta+Shift+l');
+ await expect.poll(locks).toEqual([false, false]);
+ await page.keyboard.press('ControlOrMeta+z');
+ await expect.poll(locks).toEqual([true, true]);
+ await page.keyboard.press('ControlOrMeta+Shift+z');
+ await expect.poll(locks).toEqual([false, false]);
+ expect(await page.evaluate(() => window.figFixture.errors())).toEqual([]);
+});
+
+test('unlocks an imported component instance and keeps its row in sync', async ({
+ page,
+}) => {
+ await page.goto('/?file=showcase.fig&edit');
+ await expect(page.getByTestId('fig-viewer')).toBeVisible();
+ const seed = await page.evaluate(async () => {
+ const engine = window.figFixture.engine()!;
+ const row = (await engine.search(0, 'Primary button')).find(
+ (r) => r.name === 'Primary button'
+ )!;
+ await engine.apply(0, [
+ { op: 'set', ids: [row.id], props: { locked: true } },
+ ]);
+ return { id: row.id, bytes: Array.from(await engine.save()) };
+ });
+ await page.getByTestId('fig-file-input').setInputFiles({
+ name: 'locked.fig',
+ mimeType: 'application/octet-stream',
+ buffer: Buffer.from(seed.bytes),
+ });
+ await expect(page.getByRole('banner')).toContainText('locked');
+ await expect(page.getByTestId('fig-viewer')).toBeVisible();
+ await page.getByRole('button', { name: 'Find layers', exact: true }).click();
+ await page
+ .getByRole('searchbox', { name: 'Find layers' })
+ .fill('Primary button');
+ await page
+ .getByTestId('fig-search-hit')
+ .filter({ hasText: /^Primary button$/ })
+ .click();
+ await page.getByRole('button', { name: 'Close search' }).click();
+ const row = page.locator(`[data-layer-id="${seed.id}"]`);
+ await row.getByRole('button', { name: 'Unlock', exact: true }).click();
+ await expect
+ .poll(() =>
+ page.evaluate(
+ (id) =>
+ window.figFixture
+ .engine()!
+ .nodeInfo(0, id)
+ .then((r) => r.locked),
+ seed.id
+ )
+ )
+ .toBe(false);
+ await expect(
+ row.getByRole('button', { name: 'Lock', exact: true })
+ ).toBeAttached();
+ await row.hover();
+ await row.getByRole('button', { name: 'Lock', exact: true }).click();
+ await expect(
+ row.getByRole('button', { name: 'Unlock', exact: true })
+ ).toBeVisible();
+ expect(await page.evaluate(() => window.figFixture.errors())).toEqual([]);
+});
+
+test('toggles the Mobile Interfaces Logotype with expanded instance children', async ({
+ page,
+}) => {
+ test.skip(!process.env.FIG_LOCK_CORPUS, 'Local reproduction corpus only');
+ await page.goto('/?edit');
+ await page
+ .getByTestId('fig-file-input')
+ .setInputFiles(`${process.env.FIG_LOCK_CORPUS}/Mobile.fig`);
+ await expect(page.getByTestId('fig-viewer')).toBeVisible();
+ await page.getByRole('button', { name: 'Find layers', exact: true }).click();
+ await page.getByRole('searchbox', { name: 'Find layers' }).fill('Logotype');
+ await page
+ .getByTestId('fig-search-hit')
+ .filter({ hasText: /^Logotype$/ })
+ .click();
+ await page.getByRole('button', { name: 'Close search' }).click();
+ const row = page.locator('[data-layer-id="3:838"]');
+ await row.getByRole('button', { name: 'Expand', exact: true }).click();
+ await row.hover();
+ await row.getByRole('button', { name: 'Lock', exact: true }).click();
+ await expect(
+ row.getByRole('button', { name: 'Unlock', exact: true })
+ ).toBeVisible();
+ await row.getByRole('button', { name: 'Unlock', exact: true }).click();
+ await expect
+ .poll(() =>
+ page.evaluate(
+ async () =>
+ (await window.figFixture.engine()!.nodeInfo(0, '3:838')).locked
+ )
+ )
+ .toBe(false);
+ await expect(
+ row.getByRole('button', { name: 'Lock', exact: true })
+ ).toBeAttached();
+ await page.screenshot({
+ path: test.info().outputPath('unlocked-logotype.png'),
+ });
+ expect(await page.evaluate(() => window.figFixture.errors())).toEqual([]);
+});
diff --git a/apps/web/src/features/block-fig/browser-test/loading.browser.e2e.ts b/apps/web/src/features/block-fig/browser-test/loading.browser.e2e.ts
new file mode 100644
index 0000000000..ac26f478fd
--- /dev/null
+++ b/apps/web/src/features/block-fig/browser-test/loading.browser.e2e.ts
@@ -0,0 +1,42 @@
+import { expect, test } from '@playwright/test';
+
+test('opening preserves canvas geometry without a thumbnail pop', async ({
+ page,
+}) => {
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ await page.route('**/fig_engine_bg.wasm*', async (route) => {
+ await gate;
+ await route.continue();
+ });
+ await page.goto('/?file=showcase.fig');
+ try {
+ const opening = page.getByTestId('fig-opening');
+ await expect(opening).toBeVisible();
+ await expect(opening.locator('img')).toHaveCount(0);
+ await expect(opening.getByRole('status')).toHaveText('Opening design…');
+ const before = await page.getByTestId('fig-opening-canvas').boundingBox();
+ expect(before).not.toBeNull();
+ release();
+ await expect(page.getByTestId('fig-viewer')).toBeVisible();
+ await expect(page.getByTestId('fig-loading-status')).toHaveCount(0);
+ const after = await page.getByTestId('fig-canvas').boundingBox();
+ expect(after).toEqual(before);
+ expect(await page.evaluate(() => window.figFixture.errors())).toEqual([]);
+ } finally {
+ release();
+ }
+});
+
+test('an empty design does not wait forever for a rendered tile', async ({
+ page,
+}) => {
+ await page.goto('/?new&edit');
+ await expect(page.getByTestId('fig-viewer')).toBeVisible();
+ await expect(page.getByTestId('fig-loading-status')).toHaveCount(0);
+ await expect(
+ page.getByRole('button', { name: 'Frame (F)', exact: true })
+ ).toBeEnabled();
+});
diff --git a/apps/web/src/features/block-fig/browser-test/performance.browser.e2e.ts b/apps/web/src/features/block-fig/browser-test/performance.browser.e2e.ts
new file mode 100644
index 0000000000..26bcc00538
--- /dev/null
+++ b/apps/web/src/features/block-fig/browser-test/performance.browser.e2e.ts
@@ -0,0 +1,214 @@
+import { expect, test } from '@playwright/test';
+
+test('profiles a local design without changing its contents', async ({
+ page,
+}) => {
+ const input = process.env.FIG_PERF_FILE;
+ test.skip(!input, 'Set FIG_PERF_FILE to benchmark a local .fig');
+ test.setTimeout(180_000);
+ await page.addInitScript(() => {
+ const drawn = new WeakSet<HTMLCanvasElement>();
+ const drawImage = CanvasRenderingContext2D.prototype.drawImage;
+ CanvasRenderingContext2D.prototype.drawImage = function (
+ ...args: unknown[]
+ ) {
+ Reflect.apply(drawImage, this, args);
+ if (
+ !drawn.has(this.canvas) &&
+ this.canvas ===
+ document.querySelector('[data-testid="fig-canvas"] canvas')
+ ) {
+ drawn.add(this.canvas);
+ // A paint opportunity after an actual tile, not just the viewer shell.
+ requestAnimationFrame(() =>
+ performance.mark('fig-test:first-tile-frame')
+ );
+ }
+ };
+ });
+ await page.goto('/?realFonts');
+ for (let run = 0; run < 2; run++) {
+ await page.getByTestId('fig-file-input').setInputFiles([]);
+ const previous = await page.evaluateHandle(() =>
+ window.figFixture.engine()
+ );
+ const started = Date.now();
+ await page.evaluate(() => {
+ performance.clearMarks('fig-test:first-tile-frame');
+ performance.mark('fig-test:upload-start');
+ });
+ await page.getByTestId('fig-file-input').setInputFiles(input!);
+ await page.waitForFunction(
+ (old) => window.figFixture.engine() && window.figFixture.engine() !== old,
+ previous,
+ { timeout: 120_000 }
+ );
+ await previous.dispose();
+ await expect(page.getByTestId('fig-viewer')).toBeVisible({
+ timeout: 120_000,
+ });
+ const visibleMs = Date.now() - started;
+ await page.waitForFunction(
+ () => performance.getEntriesByName('fig-test:first-tile-frame').length,
+ undefined,
+ { timeout: 120_000 }
+ );
+ const firstTileFrameMs = await page.evaluate(() => {
+ const tile = performance.getEntriesByName('fig-test:first-tile-frame')[0];
+ const starts = performance.getEntriesByName('fig-test:upload-start');
+ return tile.startTime - starts[starts.length - 1].startTime;
+ });
+ const measurements = await page.evaluate(async () => {
+ const engine = window.figFixture.engine();
+ if (!engine) throw new Error('No engine');
+ const layout = await engine.openPage(0);
+ const bounds = layout.bounds;
+ const scale = Math.min(512 / Math.max(bounds.w, bounds.h), 1);
+ const started = performance.now();
+ const pending = engine.render({
+ page: 0,
+ x: bounds.x,
+ y: bounds.y,
+ scale,
+ width: 512,
+ height: 512,
+ outline: false,
+ priority: 0,
+ });
+ const samples: number[] = [];
+ for (let i = 0; i < 20; i++) {
+ const before = performance.now();
+ await engine.hitTest(
+ 0,
+ bounds.x + (bounds.w * i) / 20,
+ bounds.y + bounds.h / 2,
+ 1
+ );
+ samples.push(performance.now() - before);
+ }
+ const tile = await pending.promise;
+ const renderWallMs = performance.now() - started;
+ tile?.bitmap.close();
+ samples.sort((a, b) => a - b);
+ return {
+ nodes: engine.summary.nodeCount,
+ renderWallMs,
+ rasterMs: tile?.millis,
+ hitTestP95Ms: samples[18],
+ errors: window.figFixture.errors(),
+ };
+ });
+ console.info(
+ '[fig-corpus]',
+ JSON.stringify({
+ input,
+ run,
+ visibleMs,
+ firstTileFrameMs,
+ ...measurements,
+ })
+ );
+ expect(measurements.errors).toEqual([]);
+ }
+});
+
+test('reuses compiled wasm when reopening a design', async ({ page }) => {
+ const wasmRequests: string[] = [];
+ page.on('request', (request) => {
+ if (request.url().includes('fig_engine_bg'))
+ wasmRequests.push(request.url());
+ });
+ await page.goto('/?file=showcase.fig');
+ await expect(page.getByTestId('fig-viewer')).toBeVisible();
+ const timings = await page.evaluate(async () => {
+ const source = window.figFixture.engine();
+ if (!source) throw new Error('No engine');
+ const Engine =
+ source.constructor as typeof import('@core/fig-engine/client').FigEngine;
+ const blank = await Engine.blank('Cache test');
+ const empty = await Engine.open(blank.buffer);
+ empty.close();
+ const bytes = await source.save();
+ const started = performance.now();
+ const reopened = await Engine.open(bytes.buffer as ArrayBuffer);
+ try {
+ const opened = performance.now() - started;
+ const layout = await reopened.openPage(0);
+ const b = layout.bounds;
+ const rendering = performance.now();
+ const tile = await reopened.render({
+ page: 0,
+ x: b?.x ?? 0,
+ y: b?.y ?? 0,
+ width: 512,
+ height: 512,
+ scale: 1,
+ outline: false,
+ priority: 0,
+ }).promise;
+ const raster = performance.now() - rendering;
+ tile?.bitmap.close();
+ return {
+ reopenMs: opened,
+ tileMs: raster,
+ nodes: reopened.summary.nodeCount,
+ };
+ } finally {
+ reopened.close();
+ }
+ });
+ console.info('[fig-performance]', JSON.stringify(timings));
+ expect(wasmRequests).toHaveLength(1);
+});
+
+test('hover repaints the overlay without recompositing the page', async ({
+ page,
+}) => {
+ await page.goto('/?file=showcase.fig');
+ const canvas = page.getByTestId('fig-canvas');
+ await expect(canvas).toBeVisible();
+ await page.evaluate(() => document.fonts.ready.then(() => undefined));
+ // Observe actual paint activity: a fixed delay can overlap a late tile
+ // or font load on a busy machine and count it as a hover repaint.
+ await canvas
+ .locator('canvas')
+ .first()
+ .evaluate((element) => {
+ const tile = element as HTMLCanvasElement;
+ const context = tile.getContext('2d');
+ if (!context) throw new Error('No canvas context');
+ const fill = context.fillRect.bind(context);
+ tile.dataset.pagePaints = '0';
+ tile.dataset.lastPagePaint = String(performance.now());
+ context.fillRect = (...args) => {
+ tile.dataset.pagePaints = String(Number(tile.dataset.pagePaints) + 1);
+ tile.dataset.lastPagePaint = String(performance.now());
+ fill(...args);
+ };
+ });
+ await page.waitForFunction(() => {
+ const tile = document.querySelector<HTMLCanvasElement>(
+ '[data-testid="fig-canvas"] canvas'
+ );
+ return (
+ tile && performance.now() - Number(tile.dataset.lastPagePaint) >= 1000
+ );
+ });
+ await canvas
+ .locator('canvas')
+ .first()
+ .evaluate((element) => {
+ (element as HTMLCanvasElement).dataset.pagePaints = '0';
+ });
+ const box = await canvas.boundingBox();
+ if (!box) throw new Error('No canvas bounds');
+ await page.mouse.move(box.x + 50, box.y + 50);
+ await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2, {
+ steps: 20,
+ });
+ await page.waitForTimeout(200);
+ await expect(canvas.locator('canvas').first()).toHaveAttribute(
+ 'data-page-paints',
+ '0'
+ );
+});
diff --git a/apps/web/src/features/block-fig/browser-test/text-editing.browser.e2e.ts b/apps/web/src/features/block-fig/browser-test/text-editing.browser.e2e.ts
index daa0b26581..ac2cec4c20 100644
--- a/apps/web/src/features/block-fig/browser-test/text-editing.browser.e2e.ts
+++ b/apps/web/src/features/block-fig/browser-test/text-editing.browser.e2e.ts
@@ -107,12 +107,12 @@ test('styles a range of characters', async ({ page }) => {
// Select "bold" and make it bold, underlined.
for (let k = 0; k < 4; k++) await page.keyboard.press('Shift+ArrowLeft');
await expect.poll(() => selection(page)).toEqual([6, 10]);
- await page.keyboard.press('Control+b');
+ await page.keyboard.press('ControlOrMeta+b');
await expect
.poll(async () => (await textInfo(page))?.runs.map((r) => r.fontStyle))
.toEqual(['Bold']);
- await expect(page.getByTestId('fig-font-weight')).toHaveValue('700');
- await page.keyboard.press('Control+u');
+ await expect(page.getByTestId('fig-font-weight')).toHaveText('Bold');
+ await page.keyboard.press('ControlOrMeta+u');
await expect
.poll(async () => (await textInfo(page))?.runs[0]?.decoration)
.toBe('UNDERLINE');
@@ -120,8 +120,8 @@ test('styles a range of characters', async ({ page }) => {
expect(info?.styleIds).toEqual([0, 0, 0, 0, 0, 0, 1, 1, 1, 1]);
expect(info?.fontStyle).toBe('Regular');
// Over both, the Type section shows the weight as mixed.
- await page.keyboard.press('Control+a');
- await expect(page.getByTestId('fig-font-weight')).toHaveValue('mixed');
+ await page.keyboard.press('ControlOrMeta+a');
+ await expect(page.getByTestId('fig-font-weight')).toHaveText('Mixed');
// A size from the panel applies to the selected characters only.
await page.keyboard.press('Shift+ArrowLeft');
await page.keyboard.press('Home');
@@ -148,7 +148,7 @@ test('styles a range of characters', async ({ page }) => {
test('bolds what is typed next at a caret', async ({ page }) => {
await openNew(page);
await typeNewText(page, 'a');
- await page.keyboard.press('Control+b');
+ await page.keyboard.press('ControlOrMeta+b');
await page.keyboard.type('b');
await expect
.poll(async () => (await textInfo(page))?.styleIds)
@@ -162,10 +162,10 @@ test('undoes typing in bursts and keeps editing', async ({ page }) => {
await page.keyboard.type(' two');
const editor = page.getByTestId('fig-text-editor');
await expect(editor).toHaveValue('one two');
- await page.keyboard.press('Control+z');
+ await page.keyboard.press('ControlOrMeta+z');
await expect(editor).toHaveValue('one');
await expect(editor).toBeFocused();
- await page.keyboard.press('Control+Shift+z');
+ await page.keyboard.press('ControlOrMeta+Shift+z');
await expect(editor).toHaveValue('one two');
});
diff --git a/apps/web/src/features/block-fig/browser-test/vite.config.ts b/apps/web/src/features/block-fig/browser-test/vite.config.ts
index b9d91cb83f..bdb5000e2f 100644
--- a/apps/web/src/features/block-fig/browser-test/vite.config.ts
+++ b/apps/web/src/features/block-fig/browser-test/vite.config.ts
@@ -26,7 +26,9 @@ const corpusDirectory =
export default defineConfig({
root: directory,
define: {
- __FIG_CORPUS_URL__: JSON.stringify(`/@fs${corpusDirectory}`),
+ __FIG_CORPUS_URL__: JSON.stringify(
+ process.env.FIG_CORPUS_URL ?? `/@fs${corpusDirectory}`
+ ),
// The font the fixture's stand-in font sources serve.
__FIG_FONT_URL__: JSON.stringify(
`/@fs${workspaceDirectory}crates/fig_engine/fonts/InterVariable.ttf`
diff --git a/apps/web/src/features/block-fig/components/auto-layout-controls.tsx b/apps/web/src/features/block-fig/components/auto-layout-controls.tsx
index 3b82700dc8..ad9c48eb10 100644
--- a/apps/web/src/features/block-fig/components/auto-layout-controls.tsx
+++ b/apps/web/src/features/block-fig/components/auto-layout-controls.tsx
@@ -1,3 +1,4 @@
+import { InspectorSelect } from './inspector-select';
/**
* Editing auto layout as Figma's design panel does: direction, gap (a
* number, or Auto to space children apart), horizontal and vertical
@@ -8,7 +9,8 @@
import type { AutoLayout, NodeInfo, Sizing } from '@core/fig-engine/types';
import ArrowDown from '@phosphor/arrow-down.svg';
import ArrowRight from '@phosphor/arrow-right.svg';
-import { For, Show } from 'solid-js';
+import CornersOut from '@phosphor/corners-out.svg';
+import { createSignal, For, type JSX, Show } from 'solid-js';
import type { Constraint, Patch } from '../primitives/create-fig-editor';
import { ChoiceRow, NumberField, ParsedField } from './design-fields';
@@ -43,10 +45,16 @@ function parseGap(text: string): number | 'AUTO' | null {
export function AutoLayoutControls(props: {
layout: AutoLayout;
+ children?: JSX.Element;
onPatch: (patch: Patch, live: boolean) => void;
}) {
const al = () => props.layout;
const horizontal = () => al().mode === 'HORIZONTAL';
+ const [paddingMode, setPaddingMode] = createSignal<boolean>();
+ const individual = () =>
+ paddingMode() ??
+ (al().paddingLeft !== al().paddingRight ||
+ al().paddingTop !== al().paddingBottom);
const primary = (): Spot =>
(SPOTS as readonly string[]).includes(al().primaryAlign ?? '')
? (al().primaryAlign as Spot)
@@ -69,51 +77,18 @@ export function AutoLayoutControls(props: {
return c === counter() && (isAuto(al()) || p === primary());
};
return (
- <div class="flex flex-col gap-1.5" data-testid="fig-auto-layout">
- <div class="grid grid-cols-[2fr_3fr] gap-1.5">
- <ChoiceRow
- value={al().mode}
- options={DIRECTIONS}
- testId="fig-layout-direction"
- onChange={(layoutMode) => props.onPatch({ layoutMode }, false)}
- />
- <ParsedField
- label="Gap"
- shown={isAuto(al()) ? 'Auto' : String(al().spacing)}
- parse={parseGap}
- testId="fig-field-gap"
- onChange={(gap) =>
- props.onPatch(
- gap === 'AUTO'
- ? { primaryAlign: 'SPACE_BETWEEN' }
- : {
- itemSpacing: gap,
- ...(isAuto(al()) ? { primaryAlign: 'MIN' as const } : {}),
- },
- false
- )
- }
- />
- </div>
- <div class="grid grid-cols-[1fr_1fr_auto] items-start gap-1.5">
- <NumberField
- label="↔"
- value={al().paddingLeft}
- min={0}
- testId="fig-field-padding-h"
- onChange={(v, live) =>
- props.onPatch({ paddingLeft: v, paddingRight: v }, live)
- }
- />
- <NumberField
- label="↕"
- value={al().paddingTop}
- min={0}
- testId="fig-field-padding-v"
- onChange={(v, live) =>
- props.onPatch({ paddingTop: v, paddingBottom: v }, live)
- }
- />
+ <div class="flex flex-col gap-2" data-testid="fig-auto-layout">
+ <span class="text-ink-muted text-[11px]">Flow</span>
+ <ChoiceRow
+ value={al().mode}
+ options={DIRECTIONS}
+ testId="fig-layout-direction"
+ onChange={(layoutMode) => props.onPatch({ layoutMode }, false)}
+ />
+ {props.children}
+ <div class="grid grid-cols-2 gap-2">
+ <span class="text-ink-muted text-[11px]">Alignment</span>
+ <span class="text-ink-muted text-[11px]">Gap</span>
<div
class="grid grid-cols-3 gap-0.5 rounded-md bg-inset p-1"
data-testid="fig-layout-align"
@@ -126,7 +101,7 @@ export function AutoLayoutControls(props: {
type="button"
aria-label={`Align ${row.toLowerCase()} ${column.toLowerCase()}`}
aria-pressed={active(row, column)}
- class="flex size-3.5 items-center justify-center rounded-sm hover:bg-hover"
+ class="flex h-4 items-center justify-center rounded-sm hover:bg-hover"
onClick={() => select(row, column)}
>
<span
@@ -142,6 +117,108 @@ export function AutoLayoutControls(props: {
)}
</For>
</div>
+ <div class="self-start">
+ <ParsedField
+ label="↔"
+ ariaLabel="Gap"
+ shown={isAuto(al()) ? 'Auto' : String(al().spacing)}
+ parse={parseGap}
+ testId="fig-field-gap"
+ onChange={(gap) =>
+ props.onPatch(
+ gap === 'AUTO'
+ ? { primaryAlign: 'SPACE_BETWEEN' }
+ : {
+ itemSpacing: gap,
+ ...(isAuto(al()) ? { primaryAlign: 'MIN' as const } : {}),
+ },
+ false
+ )
+ }
+ />
+ </div>
+ </div>
+ <div class="flex items-center justify-between">
+ <span class="text-ink-muted text-[11px]">Padding</span>
+ <button
+ type="button"
+ aria-label="Independent padding"
+ title="Independent padding"
+ aria-pressed={individual()}
+ data-testid="fig-padding-independent"
+ class="flex size-6 items-center justify-center rounded text-ink-muted hover:bg-hover aria-pressed:bg-accent/15 aria-pressed:text-accent"
+ onClick={() => setPaddingMode(!individual())}
+ >
+ <CornersOut class="size-3.5" />
+ </button>
+ </div>
+ <div class="grid grid-cols-2 gap-2">
+ <Show
+ when={individual()}
+ fallback={
+ <>
+ <NumberField
+ label="↔"
+ ariaLabel="Horizontal padding"
+ value={al().paddingLeft}
+ min={0}
+ testId="fig-field-padding-h"
+ onChange={(v, live) =>
+ props.onPatch({ paddingLeft: v, paddingRight: v }, live)
+ }
+ />
+ <NumberField
+ label="↕"
+ ariaLabel="Vertical padding"
+ value={al().paddingTop}
+ min={0}
+ testId="fig-field-padding-v"
+ onChange={(v, live) =>
+ props.onPatch({ paddingTop: v, paddingBottom: v }, live)
+ }
+ />
+ </>
+ }
+ >
+ <NumberField
+ label="←"
+ ariaLabel="Left padding"
+ value={al().paddingLeft}
+ min={0}
+ testId="fig-field-padding-left"
+ onChange={(paddingLeft, live) =>
+ props.onPatch({ paddingLeft }, live)
+ }
+ />
+ <NumberField
+ label="↑"
+ ariaLabel="Top padding"
+ value={al().paddingTop}
+ min={0}
+ testId="fig-field-padding-top"
+ onChange={(paddingTop, live) => props.onPatch({ paddingTop }, live)}
+ />
+ <NumberField
+ label="→"
+ ariaLabel="Right padding"
+ value={al().paddingRight}
+ min={0}
+ testId="fig-field-padding-right"
+ onChange={(paddingRight, live) =>
+ props.onPatch({ paddingRight }, live)
+ }
+ />
+ <NumberField
+ label="↓"
+ ariaLabel="Bottom padding"
+ value={al().paddingBottom}
+ min={0}
+ testId="fig-field-padding-bottom"
+ onChange={(paddingBottom, live) =>
+ props.onPatch({ paddingBottom }, live)
+ }
+ />
+ </Show>
</div>
</div>
);
@@ -154,8 +231,9 @@ const SIZING_LABEL: Record<Sizing, string> = {
};
/** Fixed / Hug / Fill for the width and height, where they apply. */
-export function SizingControls(props: {
+export function SizingControl(props: {
info: NodeInfo;
+ axis: 0 | 1;
onPatch: (patch: Patch, live: boolean) => void;
}) {
const choices = (): Sizing[] => {
@@ -166,36 +244,24 @@ export function SizingControls(props: {
};
return (
<Show when={props.info.sizing && choices().length > 1}>
- <div class="grid grid-cols-2 gap-1.5">
- <For each={[0, 1] as const}>
- {(axis) => (
- <select
- class="min-w-0 rounded-md bg-inset px-2 py-1 text-ink outline-none focus:outline focus:outline-1 focus:outline-accent"
- aria-label={axis === 0 ? 'Width sizing' : 'Height sizing'}
- data-testid={axis === 0 ? 'fig-sizing-w' : 'fig-sizing-h'}
- value={props.info.sizing?.[axis] ?? 'FIXED'}
- onChange={(e) => {
- const v = e.currentTarget.value as Sizing;
- props.onPatch(
- axis === 0 ? { sizingHorizontal: v } : { sizingVertical: v },
- false
- );
- }}
- >
- <For each={choices()}>
- {(c) => (
- <option
- value={c}
- selected={c === (props.info.sizing?.[axis] ?? 'FIXED')}
- >
- {axis === 0 ? 'W' : 'H'} · {SIZING_LABEL[c]}
- </option>
- )}
- </For>
- </select>
- )}
- </For>
- </div>
+ <InspectorSelect
+ class="w-10 shrink-0 [&_button]:px-1 [&_svg]:hidden"
+ label={props.axis === 0 ? 'Width sizing' : 'Height sizing'}
+ testId={props.axis === 0 ? 'fig-sizing-w' : 'fig-sizing-h'}
+ value={props.info.sizing?.[props.axis] ?? 'FIXED'}
+ options={choices().map((value) => ({
+ value,
+ label: SIZING_LABEL[value],
+ }))}
+ onChange={(value) =>
+ props.onPatch(
+ props.axis === 0
+ ? { sizingHorizontal: value as Sizing }
+ : { sizingVertical: value as Sizing },
+ false
+ )
+ }
+ />
</Show>
);
}
@@ -228,33 +294,24 @@ export function ConstraintControls(props: {
<div class="grid grid-cols-2 gap-1.5">
<For each={[0, 1] as const}>
{(axis) => (
- <select
- class="min-w-0 rounded-md bg-inset px-2 py-1 text-ink outline-none focus:outline focus:outline-1 focus:outline-accent"
- aria-label={
+ <InspectorSelect
+ label={
axis === 0 ? 'Horizontal constraint' : 'Vertical constraint'
}
- data-testid={axis === 0 ? 'fig-constraint-h' : 'fig-constraint-v'}
- onChange={(e) => {
- const v = e.currentTarget.value;
+ testId={axis === 0 ? 'fig-constraint-h' : 'fig-constraint-v'}
+ value={current(axis)}
+ options={(axis === 0
+ ? HORIZONTAL_CONSTRAINTS
+ : VERTICAL_CONSTRAINTS
+ ).map(([value, label]) => ({ value, label }))}
+ onChange={(value) =>
props.onPatch(
axis === 0
- ? { constraintHorizontal: v as Constraint }
- : { constraintVertical: v as Constraint }
- );
- }}
- >
- <For
- each={
- axis === 0 ? HORIZONTAL_CONSTRAINTS : VERTICAL_CONSTRAINTS
- }
- >
- {([value, label]) => (
- <option value={value} selected={value === current(axis)}>
- {label}
- </option>
- )}
- </For>
- </select>
+ ? { constraintHorizontal: value as Constraint }
+ : { constraintVertical: value as Constraint }
+ )
+ }
+ />
)}
</For>
</div>
diff --git a/apps/web/src/features/block-fig/components/bindings-section.tsx b/apps/web/src/features/block-fig/components/bindings-section.tsx
index c191a67f2d..8857c8b628 100644
--- a/apps/web/src/features/block-fig/components/bindings-section.tsx
+++ b/apps/web/src/features/block-fig/components/bindings-section.tsx
@@ -1,3 +1,4 @@
+import { InspectorSelect } from './inspector-select';
/**
* For a layer inside a main component: which component property drives
* its visibility, its text, or (for a nested instance) which component it
@@ -43,27 +44,27 @@ export function BindingsSection(props: {
<For each={b().fields}>
{(f) => (
<PropertyRow label={FIELD_LABELS[f.field]}>
- <select
- class="w-full rounded-md bg-inset px-1.5 py-0.5 text-ink outline-none disabled:opacity-60"
+ <InspectorSelect
+ label={FIELD_LABELS[f.field]}
value={f.property ?? ''}
disabled={!props.actions}
- data-testid={`fig-bind-${f.field}`}
- onChange={(e) => {
- const v = e.currentTarget.value;
- if (v === CREATE) {
- e.currentTarget.value = f.property ?? '';
- props.actions?.onCreate(f.field);
- } else props.actions?.onBind(f.field, v || undefined);
- }}
- >
- <option value="">None</option>
- <For each={b().properties.filter((p) => p.kind === f.kind)}>
- {(p) => <option value={p.id}>{p.name}</option>}
- </For>
- <option value={CREATE}>
- Create {PROPERTY_KIND_LABELS[f.kind].toLowerCase()} property…
- </option>
- </select>
+ testId={`fig-bind-${f.field}`}
+ options={[
+ { value: '', label: 'None' },
+ ...b()
+ .properties.filter((p) => p.kind === f.kind)
+ .map((p) => ({ value: p.id, label: p.name })),
+ {
+ value: CREATE,
+ label: `Create ${PROPERTY_KIND_LABELS[f.kind].toLowerCase()} property…`,
+ },
+ ]}
+ onChange={(value) =>
+ value === CREATE
+ ? props.actions?.onCreate(f.field)
+ : props.actions?.onBind(f.field, value || undefined)
+ }
+ />
</PropertyRow>
)}
</For>
diff --git a/apps/web/src/features/block-fig/components/boolean-controls.tsx b/apps/web/src/features/block-fig/components/boolean-controls.tsx
index 1186ea235a..aa271e210f 100644
--- a/apps/web/src/features/block-fig/components/boolean-controls.tsx
+++ b/apps/web/src/features/block-fig/components/boolean-controls.tsx
@@ -10,13 +10,14 @@ import Intersect from '@phosphor/intersect.svg';
import StackSimple from '@phosphor/stack-simple.svg';
import Subtract from '@phosphor/subtract.svg';
import Unite from '@phosphor/unite.svg';
-import { For, type JSX, Show } from 'solid-js';
+import { For } from 'solid-js';
import { match } from 'ts-pattern';
import {
BOOLEAN_ITEMS,
type BooleanItem,
type BooleanOperation,
} from '../core/boolean';
+import { EditorMenu } from './editor-menu';
export function BooleanIcon(props: { item: BooleanItem; class?: string }) {
return match(props.item.id)
@@ -30,6 +31,38 @@ export function BooleanIcon(props: { item: BooleanItem; class?: string }) {
const shortcut = (item: BooleanItem) => `⌥⇧${item.key}`;
const flattenShortcut = IS_MAC ? '⌘E' : 'Ctrl+E';
+/** Selection actions belong with the selected layer, not the drawing tools. */
+export function BooleanMenu(props: {
+ onBoolean: (operation: BooleanOperation) => void;
+ onFlatten: () => void;
+}) {
+ return (
+ <EditorMenu
+ label="Boolean groups"
+ testId="fig-boolean-menu"
+ items={[
+ ...BOOLEAN_ITEMS.map((item) => ({
+ label: item.label,
+ shortcut: shortcut(item),
+ icon: <BooleanIcon item={item} class="size-4" />,
+ testId: `fig-menu-boolean-${item.id}`,
+ onSelect: () => props.onBoolean(item.operation),
+ })),
+ 'divider',
+ {
+ label: 'Flatten',
+ shortcut: flattenShortcut,
+ icon: <StackSimple class="size-4" />,
+ testId: 'fig-menu-flatten',
+ onSelect: props.onFlatten,
+ },
+ ]}
+ >
+ <Unite class="size-4" />
+ </EditorMenu>
+ );
+}
+
/** The design panel's row: the four operations and Flatten. */
export function BooleanButtons(props: {
/** A selected boolean layer's operation, shown as chosen. */
@@ -39,7 +72,7 @@ export function BooleanButtons(props: {
}) {
return (
<div
- class="flex items-center gap-0.5 border-edge-muted border-b px-2 py-1.5"
+ class="flex items-center gap-0.5 border-edge-frame border-b px-2 py-1.5"
data-testid="fig-boolean-row"
>
<For each={BOOLEAN_ITEMS}>
@@ -60,7 +93,7 @@ export function BooleanButtons(props: {
</button>
)}
</For>
- <div aria-hidden="true" class="mx-1 h-4 w-px bg-edge-muted" />
+ <div aria-hidden="true" class="mx-1 h-4 w-px bg-edge-frame" />
<button
type="button"
aria-label="Flatten"
@@ -74,58 +107,3 @@ export function BooleanButtons(props: {
</div>
);
}
-
-/** The toolbar menu's items, as Figma lists them. */
-export function BooleanMenuItems(props: {
- onBoolean: (operation: BooleanOperation) => void;
- onFlatten: () => void;
- /** Closes the menu after a choice. */
- onDone: () => void;
-}) {
- const Item = (p: {
- label: string;
- shortcut: string;
- testId: string;
- icon: JSX.Element;
- onSelect: () => void;
- }) => (
- <button
- type="button"
- data-testid={p.testId}
- class="flex h-7 w-full items-center gap-2 rounded-md px-2 text-left text-ink hover:bg-hover"
- onClick={() => {
- p.onSelect();
- props.onDone();
- }}
- >
- {p.icon}
- <span class="flex-1">{p.label}</span>
- <Show when={p.shortcut}>
- <span class="text-ink-muted">{p.shortcut}</span>
- </Show>
- </button>
- );
- return (
- <>
- <For each={BOOLEAN_ITEMS}>
- {(item) => (
- <Item
- label={item.label}
- shortcut={shortcut(item)}
- testId={`fig-menu-boolean-${item.id}`}
- icon={<BooleanIcon item={item} class="size-4" />}
- onSelect={() => props.onBoolean(item.operation)}
- />
- )}
- </For>
- <div class="my-1 h-px bg-edge-muted" />
- <Item
- label="Flatten"
- shortcut={flattenShortcut}
- testId="fig-menu-flatten"
- icon={<StackSimple class="size-4" />}
- onSelect={props.onFlatten}
- />
- </>
- );
-}
diff --git a/apps/web/src/features/block-fig/components/color-picker.tsx b/apps/web/src/features/block-fig/components/color-picker.tsx
index 04b370affa..958c00b802 100644
--- a/apps/web/src/features/block-fig/components/color-picker.tsx
+++ b/apps/web/src/features/block-fig/components/color-picker.tsx
@@ -1,3 +1,4 @@
+import { InspectorSelect } from './inspector-select';
/**
* Figma's color picker: a saturation and brightness square, hue and
* opacity sliders, the eyedropper (where the browser has one), the value
@@ -269,17 +270,14 @@ export function ColorPicker(props: {
</div>
</div>
<div class="flex items-center gap-1">
- <select
- aria-label="Color format"
- data-testid="fig-color-format"
- class="w-14 shrink-0 rounded bg-transparent py-1 text-ink outline-none"
+ <InspectorSelect
+ label="Color format"
+ testId="fig-color-format"
+ class="w-18 shrink-0"
value={format()}
- onChange={(e) => setFormat(e.currentTarget.value as ColorFormat)}
- >
- <For each={COLOR_FORMATS}>
- {(f) => <option value={f.value}>{f.label}</option>}
- </For>
- </select>
+ options={COLOR_FORMATS}
+ onChange={setFormat}
+ />
<div class="flex min-w-0 flex-1 gap-1">
<Index each={fields()}>
{(value, i) => (
diff --git a/apps/web/src/features/block-fig/components/component-picker.tsx b/apps/web/src/features/block-fig/components/component-picker.tsx
index 32832f012a..60fb88a719 100644
--- a/apps/web/src/features/block-fig/components/component-picker.tsx
+++ b/apps/web/src/features/block-fig/components/component-picker.tsx
@@ -73,7 +73,7 @@ export function ComponentPicker(props: {
<Popover.Portal>
<Layer depth={3}>
<Popover.Content
- class="z-modal flex max-h-96 w-64 flex-col rounded-xl border border-edge-muted bg-menu p-2 text-xs shadow-xl outline-none"
+ class="fig-editor-theme z-modal flex max-h-96 w-64 flex-col rounded-xl border border-edge-muted bg-menu p-2 text-xs shadow-xl outline-none"
aria-label={props.label}
data-testid="fig-component-picker"
onKeyDown={(e: KeyboardEvent) => {
diff --git a/apps/web/src/features/block-fig/components/component-preview.tsx b/apps/web/src/features/block-fig/components/component-preview.tsx
new file mode 100644
index 0000000000..d3f46f4403
--- /dev/null
+++ b/apps/web/src/features/block-fig/components/component-preview.tsx
@@ -0,0 +1,54 @@
+/** Load a component thumbnail only when its card approaches the viewport. */
+import DiamondsFour from '@phosphor/diamonds-four.svg';
+import { createSignal, onCleanup, onMount, Show } from 'solid-js';
+
+export function ComponentPreview(props: { load: () => Promise<Blob> }) {
+ let host!: HTMLSpanElement;
+ let disposed = false;
+ const [url, setUrl] = createSignal<string>();
+ const load = async () => {
+ try {
+ const blob = await props.load();
+ if (!disposed) setUrl(URL.createObjectURL(blob));
+ } catch {
+ // A component without drawable content keeps its component icon.
+ }
+ };
+ onMount(() => {
+ const observer = new IntersectionObserver(
+ (entries) => {
+ if (!entries.some((entry) => entry.isIntersecting)) return;
+ observer.disconnect();
+ void load();
+ },
+ { rootMargin: '64px' }
+ );
+ observer.observe(host);
+ onCleanup(() => observer.disconnect());
+ });
+ onCleanup(() => {
+ disposed = true;
+ const current = url();
+ if (current) URL.revokeObjectURL(current);
+ });
+ return (
+ <span
+ ref={host}
+ data-testid="fig-asset-preview"
+ class="flex h-20 w-full items-center justify-center overflow-hidden rounded-md bg-inset p-3"
+ >
+ <Show
+ when={url()}
+ fallback={<DiamondsFour class="size-5 text-ink-muted" />}
+ >
+ {(src) => (
+ <img
+ src={src()}
+ alt=""
+ class="max-h-full max-w-full object-contain"
+ />
+ )}
+ </Show>
+ </span>
+ );
+}
diff --git a/apps/web/src/features/block-fig/components/component-section.tsx b/apps/web/src/features/block-fig/components/component-section.tsx
index 321d51f36d..7917d427cf 100644
--- a/apps/web/src/features/block-fig/components/component-section.tsx
+++ b/apps/web/src/features/block-fig/components/component-section.tsx
@@ -1,3 +1,4 @@
+import { InspectorSelect } from './inspector-select';
/**
* The design panel section for a main component, component set, or
* variant: its variant properties (renamed, removed, or, on a variant, its
@@ -72,27 +73,17 @@ function NewProperty(props: {
class="flex flex-col gap-1.5 rounded-md bg-inset p-2"
data-testid="fig-new-property"
>
- <select
- class="rounded-md bg-panel px-1.5 py-0.5 text-ink outline-none"
+ <InspectorSelect
+ label="Property type"
value={kind()}
- data-testid="fig-new-property-kind"
- onChange={(e) =>
- setKind(e.currentTarget.value as PropertyKind | 'VARIANT')
- }
- >
- <For
- each={
- (props.allowVariant
- ? ['VARIANT', 'BOOL', 'TEXT', 'INSTANCE_SWAP']
- : ['BOOL', 'TEXT', 'INSTANCE_SWAP']) as (
- | PropertyKind
- | 'VARIANT'
- )[]
- }
- >
- {(k) => <option value={k}>{PROPERTY_KIND_LABELS[k]}</option>}
- </For>
- </select>
+ testId="fig-new-property-kind"
+ options={(
+ (props.allowVariant
+ ? ['VARIANT', 'BOOL', 'TEXT', 'INSTANCE_SWAP']
+ : ['BOOL', 'TEXT', 'INSTANCE_SWAP']) as (PropertyKind | 'VARIANT')[]
+ ).map((value) => ({ value, label: PROPERTY_KIND_LABELS[value] }))}
+ onChange={setKind}
+ />
<input
class="rounded-md bg-panel px-1.5 py-0.5 text-ink outline-none"
value={shown()}
diff --git a/apps/web/src/features/block-fig/components/design-fields.tsx b/apps/web/src/features/block-fig/components/design-fields.tsx
index 1ed5510a58..88eb1f2077 100644
--- a/apps/web/src/features/block-fig/components/design-fields.tsx
+++ b/apps/web/src/features/block-fig/components/design-fields.tsx
@@ -9,15 +9,13 @@ import { evaluate } from '../core/arith';
import { formatMeasure } from '../core/measure';
import { isCommitKey } from '../core/shortcuts';
-const inputClass =
- 'min-w-0 flex-1 bg-transparent text-ink tabular-nums outline-none';
-
/**
* A number with a label. Typing commits on Enter or blur (Escape reverts);
* dragging the label scrubs the value, one unit per pixel (⇧: ten).
*/
export function NumberField(props: {
label: string | JSX.Element;
+ ariaLabel?: string;
value: number;
/** Shown and typed as a percentage of 1. */
percent?: boolean;
@@ -26,6 +24,8 @@ export function NumberField(props: {
testId?: string;
/** Layers in the selection differ: shows "Mixed" until typed into. */
mixed?: boolean;
+ /** Adjacent control, such as the width's Fixed / Hug / Fill selector. */
+ suffix?: JSX.Element;
/** `live` changes come from scrubbing (coalesce them); the release
* commits the last one. */
onChange: (value: number, live: boolean) => void;
@@ -77,44 +77,53 @@ export function NumberField(props: {
};
return (
- <label class="flex min-w-0 items-center gap-2 rounded-md bg-inset px-2 py-1 focus-within:outline focus-within:outline-1 focus-within:outline-accent">
- <span
- class="shrink-0 cursor-ew-resize select-none text-ink-muted"
- onPointerDown={onLabelDown}
- onPointerMove={onLabelMove}
- onPointerUp={onLabelUp}
+ <div class="flex min-w-0 items-center rounded-md bg-inset focus-within:outline focus-within:outline-1 focus-within:outline-accent">
+ <label
+ class={`flex h-6 min-w-0 flex-1 items-center ${props.suffix ? 'gap-1 pl-1 pr-0' : 'gap-2 px-2'}`}
>
- {props.label}
- </span>
- <input
- class={inputClass}
- data-testid={props.testId}
- value={draft() ?? shown()}
- onFocus={(e) => {
- setDraft(props.mixed ? '' : e.currentTarget.value);
- e.currentTarget.select();
- }}
- onInput={(e) => setDraft(e.currentTarget.value)}
- onBlur={commit}
- onKeyDown={(e) => {
- e.stopPropagation();
- if (isCommitKey(e)) e.currentTarget.blur();
- if (e.key === 'Escape') {
- setDraft(undefined);
- e.currentTarget.blur();
- }
- if ((e.key === 'ArrowUp' || e.key === 'ArrowDown') && !props.mixed) {
- e.preventDefault();
- const step = (e.shiftKey ? 10 : 1) * (props.percent ? 0.01 : 1);
- props.onChange(
- clamp(props.value + (e.key === 'ArrowUp' ? step : -step)),
- false
- );
- setDraft(undefined);
- }
- }}
- />
- </label>
+ <span
+ class="shrink-0 cursor-ew-resize select-none text-ink-muted"
+ onPointerDown={onLabelDown}
+ onPointerMove={onLabelMove}
+ onPointerUp={onLabelUp}
+ >
+ {props.label}
+ </span>
+ <input
+ class="min-w-0 flex-1 bg-transparent text-ink tabular-nums outline-none"
+ aria-label={props.ariaLabel}
+ data-testid={props.testId}
+ value={draft() ?? shown()}
+ onFocus={(e) => {
+ setDraft(props.mixed ? '' : e.currentTarget.value);
+ e.currentTarget.select();
+ }}
+ onInput={(e) => setDraft(e.currentTarget.value)}
+ onBlur={commit}
+ onKeyDown={(e) => {
+ e.stopPropagation();
+ if (isCommitKey(e)) e.currentTarget.blur();
+ if (e.key === 'Escape') {
+ setDraft(undefined);
+ e.currentTarget.blur();
+ }
+ if (
+ (e.key === 'ArrowUp' || e.key === 'ArrowDown') &&
+ !props.mixed
+ ) {
+ e.preventDefault();
+ const step = (e.shiftKey ? 10 : 1) * (props.percent ? 0.01 : 1);
+ props.onChange(
+ clamp(props.value + (e.key === 'ArrowUp' ? step : -step)),
+ false
+ );
+ setDraft(undefined);
+ }
+ }}
+ />
+ </label>
+ {props.suffix}
+ </div>
);
}
@@ -133,7 +142,7 @@ export function TextField(props: {
};
return (
<input
- class={`${inputClass} rounded-md px-1 py-0.5 hover:bg-inset focus:bg-inset ${props.class ?? ''}`}
+ class={`min-w-0 flex-1 bg-transparent text-ink tabular-nums outline-none rounded-md px-1 py-0.5 hover:bg-inset focus:bg-inset ${props.class ?? ''}`}
data-testid={props.testId}
value={draft() ?? props.value}
onFocus={(e) => setDraft(e.currentTarget.value)}
@@ -157,6 +166,7 @@ export function TextField(props: {
*/
export function ParsedField<T>(props: {
label: string | JSX.Element;
+ ariaLabel?: string;
shown: string;
parse: (text: string) => T | null;
testId?: string;
@@ -171,10 +181,11 @@ export function ParsedField<T>(props: {
if (v !== null) props.onChange(v);
};
return (
- <label class="flex min-w-0 items-center gap-2 rounded-md bg-inset px-2 py-1 focus-within:outline focus-within:outline-1 focus-within:outline-accent">
+ <label class="flex h-6 min-w-0 items-center gap-2 rounded-md bg-inset px-2 focus-within:outline focus-within:outline-1 focus-within:outline-accent">
<span class="shrink-0 select-none text-ink-muted">{props.label}</span>
<input
- class={inputClass}
+ class="min-w-0 flex-1 bg-transparent text-ink tabular-nums outline-none"
+ aria-label={props.ariaLabel}
data-testid={props.testId}
value={draft() ?? props.shown}
onFocus={(e) => {
diff --git a/apps/web/src/features/block-fig/components/design-panel.tsx b/apps/web/src/features/block-fig/components/design-panel.tsx
index 189d53589e..9285e904c6 100644
--- a/apps/web/src/features/block-fig/components/design-panel.tsx
+++ b/apps/web/src/features/block-fig/components/design-panel.tsx
@@ -1,3 +1,7 @@
+import CircleHalf from '@phosphor/circle-half.svg';
+import CornersOut from '@phosphor/corners-out.svg';
+import List from '@phosphor/list.svg';
+import { InspectorSelect } from './inspector-select';
/**
* The right panel: the selected layer's properties as Figma's design panel
* shows them (editable when `onPatch` is given), CSS as Dev Mode writes
@@ -11,13 +15,11 @@ import type {
PaintInfo,
TextInfo,
} from '@core/fig-engine/types';
-import AlignBottom from '@phosphor/align-bottom.svg';
-import AlignCenterHorizontal from '@phosphor/align-center-horizontal.svg';
-import AlignCenterVertical from '@phosphor/align-center-vertical.svg';
-import AlignLeft from '@phosphor/align-left.svg';
-import AlignRight from '@phosphor/align-right.svg';
-import AlignTop from '@phosphor/align-top.svg';
+import { Tabs } from '@kobalte/core/tabs';
import Copy from '@phosphor/copy.svg';
+import DiamondsFour from '@phosphor/diamonds-four.svg';
+import Eye from '@phosphor/eye.svg';
+import EyeSlash from '@phosphor/eye-slash.svg';
import { createSignal, For, type JSX, Show } from 'solid-js';
import type { Alignment } from '../core/align';
import type { BooleanOperation } from '../core/boolean';
@@ -29,21 +31,32 @@ import { formatDashes, parseDashes } from '../core/paint';
import type { MixedTextField } from '../core/rich-text';
import { formatLetterSpacing, formatLineHeight } from '../core/type';
import type { Patch } from '../primitives/create-fig-editor';
-import {
- AutoLayoutControls,
- ConstraintControls,
- SizingControls,
-} from './auto-layout-controls';
-import { BooleanButtons } from './boolean-controls';
+import { BooleanButtons, BooleanMenu } from './boolean-controls';
import { ColorPicker } from './color-picker';
import { NumberField, ParsedField, TextField } from './design-fields';
import { EffectList } from './effect-controls';
+import { LayoutSection, PositionSection } from './geometry-sections';
import { MixedFields } from './mixed-fields';
import { PaintList, paintLabel, paintSwatch } from './paint-controls';
import { Section } from './panel-section';
import { SwatchPopover } from './swatch-popover';
import { TypeControls } from './type-controls';
+function CreateComponentButton(props: { onCreate: () => void }) {
+ return (
+ <button
+ type="button"
+ aria-label="Create component"
+ title="Create component"
+ data-testid="fig-create-component"
+ class="flex size-7 shrink-0 items-center justify-center rounded text-ink-muted hover:bg-hover hover:text-ink focus-visible:ring-1 focus-visible:ring-accent"
+ onClick={props.onCreate}
+ >
+ <DiamondsFour class="size-4" />
+ </button>
+ );
+}
+
function Field(props: { label: string; value: string | number }) {
return (
<div class="flex min-w-0 items-center gap-2 rounded-md bg-inset px-2 py-1">
@@ -148,37 +161,6 @@ function EffectRow(props: { effect: EffectInfo }) {
);
}
-const canHaveAutoLayout = (type: string) => ['FRAME', 'SYMBOL'].includes(type);
-
-function AutoLayoutFields(props: { info: NodeInfo }) {
- return (
- <Show when={props.info.autoLayout}>
- {(al) => (
- <Section title="Auto layout">
- <div class="grid grid-cols-2 gap-1.5">
- <Field label="Direction" value={title(al().mode)} />
- <Field label="Gap" value={fmt(al().spacing)} />
- <Field
- label="Padding"
- value={[
- al().paddingTop,
- al().paddingRight,
- al().paddingBottom,
- al().paddingLeft,
- ]
- .map(fmt)
- .join(' ')}
- />
- <Show when={al().primaryAlign}>
- {(a) => <Field label="Align" value={title(a())} />}
- </Show>
- </div>
- </Section>
- )}
- </Show>
- );
-}
-
function TextFields(props: { text: TextInfo }) {
const t = () => props.text;
return (
@@ -225,12 +207,16 @@ export interface TypeOptions {
}
export function DesignPanel(props: {
+ tab?: PanelTab;
+ headerActions?: JSX.Element;
+ zoom?: JSX.Element;
info: NodeInfo | undefined;
selectionCount: number;
/** Edits the selection; absent when the file is read-only. */
onPatch?: (patch: Patch, live: boolean) => void;
/** Aligns the selection; absent when the file is read-only. */
onAlign?: (how: Alignment) => void;
+ onFlip?: (axis: 'horizontal' | 'vertical') => void;
page: PageSummary | undefined;
/** The Export section of the selected layer. */
exportSection?: JSX.Element;
@@ -241,6 +227,7 @@ export function DesignPanel(props: {
/** Boolean operations on the selection; absent when read-only. */
onBoolean?: (operation: BooleanOperation) => void;
onFlatten?: () => void;
+ onCreateComponent?: () => void;
onCopyText: (text: string) => void;
/** Font families the document uses. */
fontFamilies?: readonly string[];
@@ -268,56 +255,139 @@ export function DesignPanel(props: {
/** The shared style control of a fill, stroke, text, or effect section. */
styleControl?: (kind: StyleKind) => JSX.Element;
}) {
- const [tab, setTabSignal] = createSignal<PanelTab>('design');
+ const [localTab, setTabSignal] = createSignal<PanelTab>('design');
+ const tab = () => props.tab ?? localTab();
const setTab = (t: PanelTab) => {
setTabSignal(t);
props.onTabChange?.(t);
};
const tabs = (): PanelTab[] =>
- props.prototype === undefined
- ? ['design', 'code']
- : ['design', 'prototype', 'code'];
+ props.prototype === undefined ? ['design'] : ['design', 'prototype'];
return (
- <div
+ <Tabs
class="flex size-full min-h-0 flex-col text-ink text-xs"
data-testid="fig-design-panel"
+ value={tab() === 'code' ? 'design' : tab()}
+ onChange={(value) => setTab(value as PanelTab)}
>
- <div class="flex h-9 shrink-0 items-center gap-1 border-edge-muted border-b px-2">
- <For each={tabs()}>
- {(t) => (
- <button
- type="button"
- class="rounded-md px-2 py-1 font-medium"
- classList={{
- 'bg-hover text-ink': tab() === t,
- 'text-ink-muted': tab() !== t,
- }}
- data-testid={`fig-panel-tab-${t}`}
- onClick={() => setTab(t)}
- >
- {PANEL_TAB_LABELS[t]}
- </button>
- )}
- </For>
+ <div class="flex h-12 shrink-0 items-center justify-end px-3">
+ {props.headerActions}
+ </div>
+ <div class="flex h-10 shrink-0 items-center gap-1 border-edge-frame border-b px-3">
+ <Tabs.List
+ aria-label="Inspector"
+ class="flex min-w-0 flex-1 items-center gap-1"
+ >
+ <For each={tabs()}>
+ {(t) => (
+ <Tabs.Trigger
+ value={t}
+ class="rounded-md px-2 py-1 font-medium"
+ classList={{
+ 'bg-hover text-ink':
+ (tab() === 'code' ? 'design' : tab()) === t,
+ 'text-ink-muted': (tab() === 'code' ? 'design' : tab()) !== t,
+ }}
+ data-testid={`fig-panel-tab-${t}`}
+ onClick={() => setTab(t)}
+ >
+ {PANEL_TAB_LABELS[t]}
+ </Tabs.Trigger>
+ )}
+ </For>
+ </Tabs.List>
+ {props.zoom}
</div>
- <Show when={tab() === 'prototype'}>
- <div class="min-h-0 flex-1 overflow-y-auto">{props.prototype}</div>
+ <Show
+ when={tab() === 'design' && !props.info && props.selectionCount > 1}
+ >
+ <div class="flex h-14 shrink-0 items-center justify-between gap-2 border-edge-frame border-b px-3">
+ <span class="min-w-0 flex-1 truncate font-medium text-sm">
+ {props.selectionCount} layers selected
+ </span>
+ <Show when={props.onCreateComponent}>
+ {(create) => <CreateComponentButton onCreate={create()} />}
+ </Show>
+ <Show when={props.onBoolean}>
+ {(onBoolean) => (
+ <BooleanMenu
+ onBoolean={onBoolean()}
+ onFlatten={() => props.onFlatten?.()}
+ />
+ )}
+ </Show>
+ </div>
+ </Show>
+ <Show when={tab() === 'design' ? props.info : undefined}>
+ {(info) => (
+ <div class="shrink-0 border-edge-frame border-b px-3 py-3">
+ <div class="flex h-7 items-center justify-between gap-2">
+ <span class="min-w-0 flex-1 truncate font-medium text-sm">
+ {info().typeLabel}
+ </span>
+ <Show
+ when={
+ info().type !== 'SYMBOL' &&
+ info().type !== 'INSTANCE' &&
+ props.onCreateComponent
+ }
+ >
+ {(create) => <CreateComponentButton onCreate={create()} />}
+ </Show>
+ <Show when={props.onBoolean}>
+ {(onBoolean) => (
+ <BooleanMenu
+ onBoolean={onBoolean()}
+ onFlatten={() => props.onFlatten?.()}
+ />
+ )}
+ </Show>
+ </div>
+ <Show
+ when={props.onPatch}
+ fallback={
+ <div class="truncate text-ink-muted" title={info().name}>
+ {info().name}
+ </div>
+ }
+ >
+ {(patch) => (
+ <TextField
+ value={info().name}
+ class="-mx-1 text-ink-muted"
+ testId="fig-name"
+ onChange={(name) => patch()({ name }, false)}
+ />
+ )}
+ </Show>
+ <Show when={info().mainComponent}>
+ {(main) => <div class="text-ink-muted">Instance of {main()}</div>}
+ </Show>
+ <Show when={info().description}>
+ {(description) => (
+ <p class="mt-1 text-ink-muted">{description()}</p>
+ )}
+ </Show>
+ </div>
+ )}
</Show>
- <div
+ <Tabs.Content
+ value="prototype"
+ class="min-h-0 flex-1 overflow-y-auto outline-none"
+ >
+ {props.prototype}
+ </Tabs.Content>
+ <Tabs.Content
+ value="design"
+ forceMount
class="min-h-0 flex-1 overflow-y-auto"
classList={{ hidden: tab() === 'prototype' }}
>
- <Show
- when={props.onAlign && props.selectionCount > 0 && tab() === 'design'}
- >
- <AlignRow onAlign={(how) => props.onAlign?.(how)} />
- </Show>
<Show
when={
props.onBoolean &&
tab() === 'design' &&
- (props.selectionCount > 1 ||
- props.info?.type === 'BOOLEAN_OPERATION')
+ props.info?.type === 'BOOLEAN_OPERATION'
}
>
<BooleanButtons
@@ -386,6 +456,7 @@ export function DesignPanel(props: {
{(mixed) => (
<MixedFields
mixed={mixed()}
+ onAlign={props.onAlign}
onPatch={props.onPatch}
swatches={props.swatches}
onPickerOpen={props.onPickerOpen}
@@ -404,235 +475,49 @@ export function DesignPanel(props: {
)
}
>
- <div class="border-edge-muted border-b px-3 py-3">
- <Show
- when={props.onPatch}
- fallback={
- <div
- class="truncate font-semibold text-sm"
- title={info().name}
- >
- {info().name}
- </div>
- }
- >
- {(patch) => (
- <TextField
- value={info().name}
- class="-mx-1 font-semibold text-sm"
- testId="fig-name"
- onChange={(name) => patch()({ name }, false)}
- />
- )}
- </Show>
- <div class="text-ink-muted">
- {info().typeLabel}
- <Show when={info().mainComponent}>
- {(main) => <> of {main()}</>}
- </Show>
- </div>
- <Show when={info().description}>
- {(d) => <p class="mt-1 text-ink-muted">{d()}</p>}
- </Show>
- </div>
{props.designSections}
- <Section title="Layout">
- <Show
- when={props.onPatch && !info().id.startsWith('I')}
- fallback={
- <div class="grid grid-cols-2 gap-1.5">
- <Field label="X" value={fmt(info().x)} />
- <Field label="Y" value={fmt(info().y)} />
- <Field label="W" value={fmt(info().width)} />
- <Field label="H" value={fmt(info().height)} />
- <Show when={Math.abs(info().rotation) > 0.01}>
- <Field label="↻" value={`${fmt(info().rotation)}°`} />
- </Show>
- <Show when={info().cornerRadius}>
- {(r) => (
- <Field label="Radius" value={radiusLabel(r())} />
- )}
- </Show>
- </div>
- }
- >
- <div class="grid grid-cols-2 gap-1.5">
- <NumberField
- label="X"
- value={info().x}
- testId="fig-field-x"
- onChange={(x, live) => props.onPatch?.({ x }, live)}
- />
- <NumberField
- label="Y"
- value={info().y}
- testId="fig-field-y"
- onChange={(y, live) => props.onPatch?.({ y }, live)}
- />
- <NumberField
- label="W"
- value={info().width}
- min={0.01}
- testId="fig-field-w"
- onChange={(width, live) =>
- props.onPatch?.({ width }, live)
- }
- />
- <NumberField
- label="H"
- value={info().height}
- min={0.01}
- testId="fig-field-h"
- onChange={(height, live) =>
- props.onPatch?.({ height }, live)
- }
- />
- <NumberField
- label="↻"
- value={info().rotation}
- testId="fig-field-rotation"
- onChange={(rotation, live) =>
- props.onPatch?.({ rotation }, live)
- }
- />
- <Show when={info().cornerRadius || hasCorners(info().type)}>
- <NumberField
- label="◜"
- value={info().cornerRadius?.top_left ?? 0}
- min={0}
- testId="fig-field-radius"
- onChange={(cornerRadius, live) =>
- props.onPatch?.({ cornerRadius }, live)
- }
- />
- </Show>
- </div>
- <SizingControls
- info={info()}
- onPatch={(patch, live) => props.onPatch?.(patch, live)}
- />
- <Show when={info().layoutParent}>
- {(positioning) => (
- <label class="flex items-center gap-2 text-ink-muted">
- <input
- type="checkbox"
- checked={positioning() === 'ABSOLUTE'}
- data-testid="fig-absolute"
- onChange={(e) =>
- props.onPatch?.(
- {
- layoutPositioning: e.currentTarget.checked
- ? 'ABSOLUTE'
- : 'AUTO',
- },
- false
- )
- }
- />
- Absolute position
- </label>
- )}
- </Show>
- <Show when={info().type === 'FRAME'}>
- <label class="flex items-center gap-2 text-ink-muted">
- <input
- type="checkbox"
- checked={info().clipsContent}
- data-testid="fig-clip-content"
- onChange={(e) =>
- props.onPatch?.(
- { clipContent: e.currentTarget.checked },
- false
- )
- }
- />
- Clip content
- </label>
- </Show>
- </Show>
- <Show
- when={props.onPatch && info().constrained}
- fallback={
- <>
- <Show
- when={
- !props.onPatch &&
- info().clipsContent &&
- info().childCount > 0
- }
- >
- <span class="text-ink-muted">Clips content</span>
- </Show>
- <Show when={info().constraints}>
- {(c) => (
- <span class="text-ink-muted">
- Constraints: {title(c()[0])} · {title(c()[1])}
- </span>
- )}
- </Show>
- </>
- }
- >
- <ConstraintControls
- constraints={info().constraints}
- onPatch={(patch) => props.onPatch?.(patch, false)}
- />
- </Show>
- </Section>
- <Show
- when={props.onPatch && !info().id.startsWith('I')}
- fallback={<AutoLayoutFields info={info()} />}
- >
- <Show
- when={info().autoLayout}
- fallback={
- <Show when={canHaveAutoLayout(info().type)}>
- <Section
- title="Auto layout"
- testId="fig-auto-layout-section"
- onAdd={props.onAddAutoLayout}
- >
- <span class="text-ink-muted">⇧A adds auto layout</span>
- </Section>
- </Show>
- }
- >
- {(al) => (
- <Section
- title="Auto layout"
- testId="fig-auto-layout-section"
- onRemove={() =>
- props.onPatch?.({ layoutMode: 'NONE' }, false)
+ <PositionSection
+ info={info()}
+ onAlign={props.onAlign}
+ onFlip={props.onFlip}
+ onPatch={!info().id.startsWith('I') ? props.onPatch : undefined}
+ />
+ <LayoutSection
+ info={info()}
+ onPatch={!info().id.startsWith('I') ? props.onPatch : undefined}
+ onAddAutoLayout={props.onAddAutoLayout}
+ />
+ <Section
+ title="Appearance"
+ actions={
+ <Show when={props.onPatch}>
+ <button
+ type="button"
+ aria-label={info().visible ? 'Hide layer' : 'Show layer'}
+ title={info().visible ? 'Hide layer' : 'Show layer'}
+ data-testid="fig-appearance-visible"
+ class="flex size-6 items-center justify-center rounded text-ink-muted hover:bg-hover hover:text-ink"
+ onClick={() =>
+ props.onPatch?.({ visible: !info().visible }, false)
}
>
<Show
- when={
- (al().mode === 'HORIZONTAL' ||
- al().mode === 'VERTICAL') &&
- !al().wrap
- }
- fallback={
- <span class="text-ink-muted">
- {title(al().mode)}
- {al().wrap ? ' (wrap)' : ''}: kept as laid out in
- Figma
- </span>
- }
+ when={info().visible}
+ fallback={<EyeSlash class="size-3.5" />}
>
- <AutoLayoutControls
- layout={al()}
- onPatch={(patch, live) =>
- props.onPatch?.(patch, live)
- }
- />
+ <Eye class="size-3.5" />
</Show>
- </Section>
- )}
- </Show>
- </Show>
- {props.layoutGrids}
- <Section title="Appearance">
+ </button>
+ </Show>
+ }
+ >
<div class="grid grid-cols-2 gap-1.5">
+ <span class="text-ink-muted text-[11px]">Opacity</span>
+ <span class="text-ink-muted text-[11px]">
+ {info().cornerRadius || hasCorners(info().type)
+ ? 'Corner radius'
+ : ''}
+ </span>
<Show
when={props.onPatch}
fallback={
@@ -640,7 +525,8 @@ export function DesignPanel(props: {
}
>
<NumberField
- label="◐"
+ label={<CircleHalf class="size-3.5" />}
+ ariaLabel="Opacity"
value={info().opacity}
percent
min={0}
@@ -651,12 +537,53 @@ export function DesignPanel(props: {
}
/>
</Show>
- <Field label="Blend" value={title(info().blendMode)} />
+ <Show when={info().cornerRadius || hasCorners(info().type)}>
+ <Show
+ when={props.onPatch}
+ fallback={
+ <Field
+ label="Radius"
+ value={
+ info().cornerRadius
+ ? radiusLabel(info().cornerRadius!)
+ : '0'
+ }
+ />
+ }
+ >
+ <NumberField
+ label={<CornersOut class="size-3.5" />}
+ ariaLabel="Corner radius"
+ value={info().cornerRadius?.top_left ?? 0}
+ min={0}
+ mixed={
+ !!info().cornerRadius &&
+ radiusLabel(info().cornerRadius!).includes(',')
+ }
+ testId="fig-field-radius"
+ onChange={(cornerRadius, live) =>
+ props.onPatch?.({ cornerRadius }, live)
+ }
+ />
+ </Show>
+ </Show>
+ <Show
+ when={
+ !['PASS_THROUGH', 'NORMAL'].includes(info().blendMode)
+ }
+ >
+ <div class="col-span-2">
+ <Field label="Blend" value={title(info().blendMode)} />
+ </div>
+ </Show>
</div>
</Section>
<Show when={info().text}>
{(t) => (
- <Section title="Text" actions={props.styleControl?.('TEXT')}>
+ <Section
+ title="Typography"
+ actions={props.styleControl?.('TEXT')}
+ >
<Show
when={props.onPatch}
fallback={<TextFields text={t()} />}
@@ -677,23 +604,26 @@ export function DesignPanel(props: {
Also uses {t().fonts.join(', ')}
</span>
</Show>
- <div class="relative">
- <p
- class="max-h-40 select-text overflow-y-auto whitespace-pre-wrap break-words rounded-md bg-inset px-2 py-1.5 text-ink"
- data-testid="fig-text-content"
- >
- {t().characters}
- {t().truncated ? '…' : ''}
- </p>
- <button
- type="button"
- aria-label="Copy text"
- class="absolute top-1 right-1 rounded p-0.5 text-ink-muted hover:text-ink"
- onClick={() => props.onCopyText(t().characters)}
- >
- <Copy class="size-3" />
- </button>
- </div>
+ <details class="mt-1 text-ink-muted">
+ <summary class="py-1">Text content</summary>
+ <div class="relative">
+ <p
+ class="max-h-40 select-text overflow-y-auto whitespace-pre-wrap break-words rounded-md bg-inset px-2 py-1.5 text-ink"
+ data-testid="fig-text-content"
+ >
+ {t().characters}
+ {t().truncated ? '…' : ''}
+ </p>
+ <button
+ type="button"
+ aria-label="Copy text"
+ class="absolute top-1 right-1 rounded p-0.5 text-ink-muted hover:text-ink"
+ onClick={() => props.onCopyText(t().characters)}
+ >
+ <Copy class="size-3" />
+ </button>
+ </div>
+ </details>
</Section>
)}
</Show>
@@ -771,7 +701,7 @@ export function DesignPanel(props: {
<Show when={info().strokes.length > 0}>
<div class="grid grid-cols-2 gap-1.5">
<NumberField
- label="≡"
+ label={<List class="size-3.5" />}
value={info().strokeWeight ?? 1}
min={0}
testId="fig-field-stroke-weight"
@@ -779,23 +709,23 @@ export function DesignPanel(props: {
props.onPatch?.({ strokeWeight }, live)
}
/>
- <select
- class="rounded-md bg-inset px-2 py-1 text-ink outline-none"
+ <InspectorSelect
+ label="Stroke alignment"
value={info().strokeAlign ?? 'CENTER'}
- onChange={(e) =>
+ options={[
+ { value: 'INSIDE', label: 'Inside' },
+ { value: 'CENTER', label: 'Center' },
+ { value: 'OUTSIDE', label: 'Outside' },
+ ]}
+ onChange={(strokeAlign) =>
props.onPatch?.(
{
- strokeAlign: e.currentTarget
- .value as Patch['strokeAlign'],
+ strokeAlign: strokeAlign as Patch['strokeAlign'],
},
false
)
}
- >
- <option value="INSIDE">Inside</option>
- <option value="CENTER">Center</option>
- <option value="OUTSIDE">Outside</option>
- </select>
+ />
<div class="col-span-2">
<ParsedField
label="Dash"
@@ -883,6 +813,7 @@ export function DesignPanel(props: {
</For>
</Section>
</Show>
+ {props.layoutGrids}
{props.exportSection}
</Show>
)}
@@ -892,46 +823,8 @@ export function DesignPanel(props: {
>
{props.pageExtra}
</Show>
- </div>
- </div>
- );
-}
-
-const ALIGN_BUTTONS: {
- how: Alignment;
- label: string;
- icon: (props: { class?: string }) => JSX.Element;
-}[] = [
- { how: 'left', label: 'Align left', icon: AlignLeft },
- {
- how: 'center',
- label: 'Align horizontal centers',
- icon: AlignCenterHorizontal,
- },
- { how: 'right', label: 'Align right', icon: AlignRight },
- { how: 'top', label: 'Align top', icon: AlignTop },
- { how: 'middle', label: 'Align vertical centers', icon: AlignCenterVertical },
- { how: 'bottom', label: 'Align bottom', icon: AlignBottom },
-];
-
-function AlignRow(props: { onAlign: (how: Alignment) => void }) {
- return (
- <div class="flex items-center justify-between border-edge-muted border-b px-2 py-1.5">
- <For each={ALIGN_BUTTONS}>
- {(b) => (
- <button
- type="button"
- aria-label={b.label}
- title={b.label}
- data-testid={`fig-align-${b.how}`}
- class="rounded p-1 text-ink-muted hover:bg-hover hover:text-ink"
- onClick={() => props.onAlign(b.how)}
- >
- {b.icon({ class: 'size-4' })}
- </button>
- )}
- </For>
- </div>
+ </Tabs.Content>
+ </Tabs>
);
}
diff --git a/apps/web/src/features/block-fig/components/editor-menu.tsx b/apps/web/src/features/block-fig/components/editor-menu.tsx
new file mode 100644
index 0000000000..c58b23c7ed
--- /dev/null
+++ b/apps/web/src/features/block-fig/components/editor-menu.tsx
@@ -0,0 +1,117 @@
+/** Shared accessible menu surface for the editor's tool and view menus. */
+import { DropdownMenu } from '@kobalte/core/dropdown-menu';
+import CaretRight from '@phosphor/caret-right.svg';
+import Check from '@phosphor/check.svg';
+import { For, type JSX, Show } from 'solid-js';
+
+export interface EditorMenuItem {
+ label: string;
+ shortcut?: string;
+ checked?: boolean;
+ disabled?: boolean;
+ icon?: JSX.Element;
+ onSelect: () => void;
+ testId?: string;
+}
+
+export interface EditorMenuGroup {
+ label: string;
+ testId?: string;
+ items: (EditorMenuItem | 'divider')[];
+}
+
+export type EditorMenuEntry = EditorMenuItem | EditorMenuGroup | 'divider';
+
+function MenuItem(props: { item: EditorMenuItem | 'divider' }) {
+ const item = props.item;
+ return item === 'divider' ? (
+ <DropdownMenu.Separator class="my-1 h-px bg-edge-muted" />
+ ) : (
+ <DropdownMenu.Item
+ disabled={item.disabled}
+ data-testid={item.testId}
+ class="flex h-6 items-center gap-2 rounded-md px-2 outline-none data-[disabled]:opacity-40 data-[highlighted]:bg-accent data-[highlighted]:text-accent-contrast"
+ onSelect={item.onSelect}
+ >
+ <span class="flex size-4 shrink-0 items-center justify-center">
+ <Show when={item.checked} fallback={item.icon}>
+ <Check class="size-3.5" />
+ </Show>
+ </span>
+ <span class="flex-1">{item.label}</span>
+ <Show when={item.shortcut}>
+ <span class="pl-5 opacity-70">{item.shortcut}</span>
+ </Show>
+ </DropdownMenu.Item>
+ );
+}
+
+export function EditorMenu(props: {
+ label: string;
+ testId?: string;
+ children: JSX.Element;
+ items: EditorMenuEntry[];
+ above?: boolean;
+}) {
+ return (
+ <DropdownMenu
+ placement={props.above ? 'top-start' : 'bottom-end'}
+ gutter={8}
+ >
+ <DropdownMenu.Trigger
+ aria-label={props.label}
+ title={props.label}
+ data-testid={props.testId}
+ class="flex h-8 shrink-0 items-center justify-center gap-1 rounded-md px-1.5 text-ink-muted outline-none hover:bg-hover hover:text-ink focus-visible:ring-2 focus-visible:ring-accent data-[expanded]:bg-hover"
+ >
+ {props.children}
+ </DropdownMenu.Trigger>
+ <DropdownMenu.Portal>
+ <DropdownMenu.Content
+ class="fig-editor-theme z-modal min-w-52 rounded-xl border border-edge-muted bg-menu p-1 text-ink text-xs shadow-lg outline-none"
+ classList={{
+ // A submenu trigger must not live in a scroll container: Kobalte's
+ // trigger focus helper loops on that ancestor with overflow-hidden pages.
+ 'max-h-[min(70vh,32rem)] overflow-y-auto': !props.items.some(
+ (item) => item !== 'divider' && 'items' in item
+ ),
+ }}
+ onKeyDown={(e) => e.stopPropagation()}
+ onPointerDown={(e) => e.stopPropagation()}
+ onPointerUp={(e) => e.stopPropagation()}
+ onPointerMove={(e) => e.stopPropagation()}
+ >
+ <For each={props.items}>
+ {(item) =>
+ item !== 'divider' && 'items' in item ? (
+ <DropdownMenu.Sub gutter={4}>
+ <DropdownMenu.SubTrigger
+ data-testid={item.testId}
+ class="flex h-6 items-center justify-between gap-6 rounded-md pr-2 pl-8 outline-none data-[highlighted]:bg-accent data-[highlighted]:text-accent-contrast data-[expanded]:bg-hover"
+ >
+ {item.label}
+ <CaretRight class="size-3.5" />
+ </DropdownMenu.SubTrigger>
+ <DropdownMenu.Portal>
+ <DropdownMenu.SubContent
+ class="fig-editor-theme z-modal max-h-[min(70vh,32rem)] min-w-52 overflow-y-auto rounded-xl border border-edge-muted bg-menu p-1 text-ink text-xs shadow-lg outline-none"
+ onKeyDown={(e) => e.stopPropagation()}
+ onPointerDown={(e) => e.stopPropagation()}
+ onPointerUp={(e) => e.stopPropagation()}
+ >
+ <For each={item.items}>
+ {(entry) => <MenuItem item={entry} />}
+ </For>
+ </DropdownMenu.SubContent>
+ </DropdownMenu.Portal>
+ </DropdownMenu.Sub>
+ ) : (
+ <MenuItem item={item} />
+ )
+ }
+ </For>
+ </DropdownMenu.Content>
+ </DropdownMenu.Portal>
+ </DropdownMenu>
+ );
+}
diff --git a/apps/web/src/features/block-fig/components/editor-theme.css b/apps/web/src/features/block-fig/components/editor-theme.css
new file mode 100644
index 0000000000..1e8439360d
--- /dev/null
+++ b/apps/web/src/features/block-fig/components/editor-theme.css
@@ -0,0 +1,72 @@
+/* Editor-local semantic tokens: Figma's neutral chrome, with the app's
+ light/dark preference. Document and canvas colors remain document data. */
+.fig-editor-theme {
+ font-family: "Inter Variable", var(--font-sans);
+ --color-panel: #2c2c2c;
+ --color-menu: #2c2c2c;
+ --color-inset: #383838;
+ --color-input: #383838;
+ --color-accent-bg: #0d99ff26;
+ --color-hover: #383838;
+ --color-selected: #383838;
+ --color-edge: #444444;
+ --color-edge-muted: #444444;
+ --color-ink: #ffffff;
+ --color-ink-muted: #b3b3b3;
+ --color-ink-subtle: #999999;
+ --color-ink-placeholder: #808080;
+ --color-accent: #0d99ff;
+ --color-accent-contrast: #ffffff;
+}
+
+[data-theme-light='true'] .fig-editor-theme {
+ --color-panel: #ffffff;
+ --color-menu: #ffffff;
+ --color-inset: #f5f5f5;
+ --color-input: #f5f5f5;
+ --color-hover: #f0f0f0;
+ --color-selected: #e6e6e6;
+ --color-edge: #d9d9d9;
+ --color-edge-muted: #e6e6e6;
+ --color-ink: #1e1e1e;
+ --color-ink-muted: #767676;
+ --color-ink-subtle: #808080;
+ --color-ink-placeholder: #999999;
+}
+
+/* Shared app dialogs are portaled outside the editor's root. */
+.fig-editor-theme.elevated-surface {
+ border-radius: 12px;
+ background-color: var(--color-menu);
+}
+
+.fig-editor-theme.elevated-surface > [data-layer] > [data-surface] {
+ border-radius: 12px;
+}
+
+/* Empty sections are one 40px header; populated ones share an 8px rhythm. */
+.fig-inspector-section-body:has(> :not(datalist)) {
+ padding-top: 8px;
+ padding-bottom: 8px;
+}
+.fig-editor-theme input[type='checkbox'] {
+ appearance: none;
+ width: 16px;
+ height: 16px;
+ flex-shrink: 0;
+ margin: 0;
+ border: 1px solid var(--color-ink-subtle);
+ border-radius: 3px;
+ background: transparent;
+}
+.fig-editor-theme input[type='checkbox']:checked {
+ background-color: var(--color-inset);
+ background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath d='m3.5 8 3 3 6-6' fill='none' stroke='white' stroke-width='1.5'/%3E%3C/svg%3E");
+}
+.fig-editor-theme input[type='checkbox']:focus-visible {
+ outline: 2px solid var(--color-accent);
+ outline-offset: 2px;
+}
+[data-theme-light='true'] .fig-editor-theme input[type='checkbox']:checked {
+ background-color: var(--color-accent);
+}
diff --git a/apps/web/src/features/block-fig/components/effect-controls.tsx b/apps/web/src/features/block-fig/components/effect-controls.tsx
index 30fd14b011..50af988c88 100644
--- a/apps/web/src/features/block-fig/components/effect-controls.tsx
+++ b/apps/web/src/features/block-fig/components/effect-controls.tsx
@@ -1,18 +1,17 @@
-/**
- * Editable effects, as in Figma's design panel: each row picks the kind,
- * toggles visibility, and removes; shadows take offset, blur, spread, and
- * color, blurs a radius. Presentational.
- */
-
+/** Effects stay compact in the inspector; their settings open beside it. */
import type { EffectInfo } from '@core/fig-engine/types';
+import { Popover } from '@kobalte/core/popover';
import Eye from '@phosphor/eye.svg';
import EyeSlash from '@phosphor/eye-slash.svg';
import Minus from '@phosphor/minus.svg';
+import Square from '@phosphor/square.svg';
+import X from '@phosphor/x.svg';
import { For, Show } from 'solid-js';
import { cssHex, normalizeHex } from '../core/color';
import type { EffectSpec } from '../primitives/create-fig-editor';
import { ColorPicker } from './color-picker';
import { NumberField, TextField } from './design-fields';
+import { InspectorSelect } from './inspector-select';
import { SwatchPopover } from './swatch-popover';
const KINDS = [
@@ -22,17 +21,6 @@ const KINDS = [
['BACKGROUND_BLUR', 'Background blur'],
] as const;
-/** Specs keeping every effect, with `edit` applied to the one at `index`. */
-function specs(
- effects: EffectInfo[],
- index: number,
- edit: EffectSpec | null
-): EffectSpec[] {
- return effects.flatMap((_, keep) =>
- keep !== index ? [{ keep }] : edit ? [{ keep, ...edit }] : []
- );
-}
-
function hexWithAlpha(e: EffectInfo): string {
const a = Math.round(e.alpha * 255);
return a >= 255
@@ -40,129 +28,213 @@ function hexWithAlpha(e: EffectInfo): string {
: `${e.color}${a.toString(16).padStart(2, '0').toUpperCase()}`;
}
-export function EffectList(props: {
- effects: EffectInfo[];
- /** Colors the color picker offers (the page's). */
+function EffectSettings(props: {
+ effect: EffectInfo;
+ index: number;
swatches?: readonly string[];
- /** The color picker opened (to load the page's colors). */
onPickerOpen?: () => void;
- onChange: (effects: EffectSpec[], live: boolean) => void;
+ onChange: (edit: EffectSpec, live?: boolean) => void;
}) {
- const set = (k: number, edit: EffectSpec | null, live = false) =>
- props.onChange(specs(props.effects, k, edit), live);
+ const e = () => props.effect;
+ const shadow = () =>
+ e().type === 'DROP_SHADOW' || e().type === 'INNER_SHADOW';
return (
- <For each={props.effects}>
- {(e, k) => {
- const shadow = () =>
- e.type === 'DROP_SHADOW' || e.type === 'INNER_SHADOW';
- return (
- <div
- class="flex flex-col gap-1 rounded-md bg-inset p-1.5"
- classList={{ 'opacity-60': !e.visible }}
- data-testid={`fig-effect-${k()}`}
- >
- <div class="flex items-center gap-1">
- <select
- class="min-w-0 flex-1 rounded bg-transparent px-1 text-ink outline-none"
- aria-label="Effect"
- data-testid={`fig-effect-${k()}-type`}
- onChange={(ev) =>
- set(k(), {
- type: ev.currentTarget.value as EffectSpec['type'],
- })
- }
- >
- <For each={KINDS}>
- {([value, label]) => (
- <option value={value} selected={value === e.type}>
- {label}
- </option>
- )}
- </For>
- </select>
- <button
- type="button"
- aria-label={e.visible ? 'Hide' : 'Show'}
- class="rounded p-0.5 text-ink-muted hover:text-ink"
- onClick={() => set(k(), { visible: !e.visible })}
- >
- <Show when={e.visible} fallback={<EyeSlash class="size-3.5" />}>
- <Eye class="size-3.5" />
- </Show>
- </button>
- <button
- type="button"
- aria-label="Remove effect"
- class="rounded p-0.5 text-ink-muted hover:text-ink"
- onClick={() => set(k(), null)}
- >
- <Minus class="size-3.5" />
- </button>
- </div>
- <Show
- when={shadow()}
- fallback={
- <NumberField
- label="Blur"
- value={e.radius}
- min={0}
- onChange={(radius, live) => set(k(), { radius }, live)}
- />
+ <Popover placement="left-start" gutter={16}>
+ <Popover.Trigger
+ aria-label="Effect settings"
+ title="Effect settings"
+ data-testid={`fig-effect-${props.index}-settings`}
+ class="flex h-6 min-w-0 flex-1 items-center gap-2 rounded-md border border-edge bg-transparent px-1 text-left text-ink hover:bg-hover data-[expanded]:bg-accent-bg data-[expanded]:text-accent"
+ classList={{ 'opacity-50': !e().visible }}
+ >
+ <Square class="size-4 shrink-0" />
+ <span class="truncate">
+ {KINDS.find(([kind]) => kind === e().type)?.[1] ?? 'Effect'}
+ </span>
+ </Popover.Trigger>
+ <Popover.Portal>
+ <Popover.Content
+ class="fig-editor-theme z-modal flex w-60 flex-col rounded-xl border border-edge-muted bg-menu text-ink text-xs shadow-xl outline-none"
+ aria-label="Effect settings"
+ data-testid={`fig-effect-${props.index}-popover`}
+ onPointerDown={(event) => event.stopPropagation()}
+ onKeyDown={(event) => {
+ if (!event.metaKey && !event.ctrlKey) event.stopPropagation();
+ }}
+ >
+ <div class="flex items-center justify-between gap-2 border-b border-edge-frame px-2 py-2">
+ <Popover.Title class="sr-only">Effect settings</Popover.Title>
+ <InspectorSelect
+ label="Effect"
+ testId={`fig-effect-${props.index}-type`}
+ value={e().type}
+ options={KINDS.map(([value, label]) => ({ value, label }))}
+ onChange={(type) =>
+ props.onChange({ type: type as EffectSpec['type'] })
}
+ />
+ <Popover.CloseButton
+ aria-label="Close effect settings"
+ class="flex size-6 items-center justify-center rounded hover:bg-hover"
>
- <div class="grid grid-cols-2 gap-1">
- <NumberField
- label="X"
- value={e.x}
- onChange={(x, live) => set(k(), { x }, live)}
- />
- <NumberField
- label="Y"
- value={e.y}
- testId={`fig-effect-${k()}-y`}
- onChange={(y, live) => set(k(), { y }, live)}
+ <X class="size-3.5" />
+ </Popover.CloseButton>
+ </div>
+ <div class="grid grid-cols-[64px_minmax(0,1fr)] items-center gap-2 p-4">
+ <Show when={shadow()}>
+ <span class="self-start pt-1 text-ink-muted">Position</span>
+ <NumberField
+ label="X"
+ value={e().x}
+ ariaLabel="Shadow X"
+ testId={`fig-effect-${props.index}-x`}
+ onChange={(x, live) => props.onChange({ x }, live)}
+ />
+ <span />
+ <NumberField
+ label="Y"
+ value={e().y}
+ ariaLabel="Shadow Y"
+ testId={`fig-effect-${props.index}-y`}
+ onChange={(y, live) => props.onChange({ y }, live)}
+ />
+ </Show>
+ <span class="text-ink-muted">Blur</span>
+ <NumberField
+ label=""
+ ariaLabel="Blur"
+ value={e().radius}
+ min={0}
+ testId={`fig-effect-${props.index}-blur`}
+ onChange={(radius, live) => props.onChange({ radius }, live)}
+ />
+ <Show when={shadow()}>
+ <span class="text-ink-muted">Spread</span>
+ <NumberField
+ label=""
+ ariaLabel="Spread"
+ value={e().spread}
+ testId={`fig-effect-${props.index}-spread`}
+ onChange={(spread, live) => props.onChange({ spread }, live)}
+ />
+ </Show>
+ </div>
+ <Show when={shadow()}>
+ <span class="px-4 text-ink-muted">Color</span>
+ <div class="m-4 mt-2 flex h-6 items-center gap-1.5 rounded-md bg-inset px-2">
+ <SwatchPopover
+ swatch={cssHex(hexWithAlpha(e()))}
+ label="Shadow color"
+ testId={`fig-effect-${props.index}-swatch`}
+ onOpenChange={(open) => {
+ if (open) props.onPickerOpen?.();
+ }}
+ >
+ <ColorPicker
+ value={hexWithAlpha(e())}
+ swatches={props.swatches}
+ onChange={(color, live) => props.onChange({ color }, live)}
/>
+ </SwatchPopover>
+ <TextField
+ value={e().color}
+ onChange={(value) => {
+ const hex = normalizeHex(value);
+ if (hex)
+ props.onChange({
+ color:
+ hex.length === 6
+ ? `${hex}${Math.round(e().alpha * 255)
+ .toString(16)
+ .padStart(2, '0')}`
+ : hex,
+ });
+ }}
+ />
+ <div class="w-14 shrink-0 border-l border-edge-frame">
<NumberField
- label="Blur"
- value={e.radius}
+ label=""
+ ariaLabel="Shadow opacity"
+ percent
min={0}
- testId={`fig-effect-${k()}-blur`}
- onChange={(radius, live) => set(k(), { radius }, live)}
- />
- <NumberField
- label="Spread"
- value={e.spread}
- onChange={(spread, live) => set(k(), { spread }, live)}
- />
- </div>
- <div class="flex items-center gap-1.5 rounded-md bg-panel px-1.5 py-0.5">
- <SwatchPopover
- swatch={cssHex(hexWithAlpha(e))}
- label="Shadow color"
- testId={`fig-effect-${k()}-swatch`}
- onOpenChange={(open) => {
- if (open) props.onPickerOpen?.();
- }}
- >
- <ColorPicker
- value={hexWithAlpha(e)}
- swatches={props.swatches}
- onChange={(color, live) => set(k(), { color }, live)}
- />
- </SwatchPopover>
- <TextField
- value={hexWithAlpha(e)}
- class="font-mono"
- onChange={(v) => {
- const hex = normalizeHex(v);
- if (hex) set(k(), { color: hex });
- }}
+ max={1}
+ value={e().alpha}
+ onChange={(alpha, live) =>
+ props.onChange(
+ {
+ color: `${e().color}${Math.round(alpha * 255)
+ .toString(16)
+ .padStart(2, '0')}`,
+ },
+ live
+ )
+ }
/>
</div>
+ </div>
+ </Show>
+ </Popover.Content>
+ </Popover.Portal>
+ </Popover>
+ );
+}
+
+export function EffectList(props: {
+ effects: EffectInfo[];
+ swatches?: readonly string[];
+ onPickerOpen?: () => void;
+ onChange: (effects: EffectSpec[], live: boolean) => void;
+}) {
+ const set = (index: number, edit: EffectSpec | null, live = false) =>
+ props.onChange(
+ props.effects.flatMap((_, keep) =>
+ keep !== index ? [{ keep }] : edit ? [{ keep, ...edit }] : []
+ ),
+ live
+ );
+ return (
+ <For each={props.effects.map((_, index) => index).reverse()}>
+ {(index) => (
+ <div
+ class="flex items-center gap-1"
+ data-testid={`fig-effect-${index}`}
+ >
+ <EffectSettings
+ effect={props.effects[index]}
+ index={index}
+ swatches={props.swatches}
+ onPickerOpen={props.onPickerOpen}
+ onChange={(edit, live) => set(index, edit, live)}
+ />
+ <button
+ type="button"
+ aria-label={
+ props.effects[index].visible ? 'Hide effect' : 'Show effect'
+ }
+ title={props.effects[index].visible ? 'Hide effect' : 'Show effect'}
+ class="flex size-6 shrink-0 items-center justify-center rounded text-ink-muted hover:bg-hover hover:text-ink"
+ onClick={() =>
+ set(index, { visible: !props.effects[index].visible })
+ }
+ >
+ <Show
+ when={props.effects[index].visible}
+ fallback={<EyeSlash class="size-3.5" />}
+ >
+ <Eye class="size-3.5" />
</Show>
- </div>
- );
- }}
+ </button>
+ <button
+ type="button"
+ aria-label="Remove effect"
+ title="Remove effect"
+ class="flex size-6 shrink-0 items-center justify-center rounded text-ink-muted hover:bg-hover hover:text-ink"
+ onClick={() => set(index, null)}
+ >
+ <Minus class="size-3.5" />
+ </button>
+ </div>
+ )}
</For>
);
}
diff --git a/apps/web/src/features/block-fig/components/export-section.tsx b/apps/web/src/features/block-fig/components/export-section.tsx
index 27888c40bd..494cda6bd9 100644
--- a/apps/web/src/features/block-fig/components/export-section.tsx
+++ b/apps/web/src/features/block-fig/components/export-section.tsx
@@ -6,15 +6,11 @@
* Presentational.
*/
-import type {
- ExportFormat,
- ExportSetting,
-} from '@core/fig-engine/handoff-types';
+import type { ExportSetting } from '@core/fig-engine/handoff-types';
import CaretDown from '@phosphor/caret-down.svg';
import Copy from '@phosphor/copy.svg';
import DotsThree from '@phosphor/dots-three.svg';
import Minus from '@phosphor/minus.svg';
-import { Button } from '@ui/components/Button';
import { createSignal, For, Index, onCleanup, Show } from 'solid-js';
import {
EXPORT_FORMATS,
@@ -26,6 +22,8 @@ import {
sizeLabel,
} from '../core/export-settings';
import { isCommitKey } from '../core/shortcuts';
+import { EditorMenu } from './editor-menu';
+import { InspectorSelect } from './inspector-select';
import { Section } from './panel-section';
/** A text field that commits on Enter or blur (empty is a value). */
@@ -46,7 +44,7 @@ function DraftInput(props: {
};
return (
<input
- class={`min-w-0 rounded-md bg-inset px-1.5 py-1 text-ink outline-none focus:outline focus:outline-1 focus:outline-accent ${props.class ?? ''}`}
+ class={`h-6 min-w-0 rounded-md bg-inset px-2 text-ink outline-none focus:outline focus:outline-1 focus:outline-accent ${props.class ?? ''}`}
aria-label={props.ariaLabel}
placeholder={props.placeholder}
list={props.list}
@@ -82,7 +80,7 @@ function ExportRow(props: {
<Show
when={hasSize(s().format)}
fallback={
- <span class="min-w-0 rounded-md bg-inset px-1.5 py-1 text-ink outline-none focus:outline focus:outline-1 focus:outline-accent w-16 text-ink-muted">
+ <span class="h-6 min-w-0 rounded-md bg-inset px-2 text-ink outline-none focus:outline focus:outline-1 focus:outline-accent w-16 text-ink-muted">
1x
</span>
}
@@ -99,55 +97,57 @@ function ExportRow(props: {
}}
/>
</Show>
- <DraftInput
- class="w-0 flex-1"
- ariaLabel="Suffix"
- placeholder="Suffix"
- testId={`fig-export-suffix-${k()}`}
- value={s().suffix}
- onCommit={(suffix) => props.onChange({ ...s(), suffix })}
- />
- <select
- class="min-w-0 rounded-md bg-inset px-1.5 py-1 text-ink outline-none focus:outline focus:outline-1 focus:outline-accent w-16"
- aria-label="Format"
- data-testid={`fig-export-format-${k()}`}
+ <InspectorSelect
+ class="min-w-0 flex-1"
+ label="Export file type"
+ testId={`fig-export-format-${k()}`}
value={s().format}
- onChange={(e) => {
- const format = e.currentTarget.value as ExportFormat;
- // Vectors export at their own size.
+ options={EXPORT_FORMATS.map((f) => ({
+ value: f.format,
+ label: f.label,
+ }))}
+ onChange={(format) =>
props.onChange(
hasSize(format)
? { ...s(), format }
: { ...s(), format, constraint: 'CONTENT_SCALE', value: 1 }
- );
- }}
+ )
+ }
+ />
+
+ <button
+ type="button"
+ aria-label="Export settings"
+ aria-expanded={open()}
+ class="flex size-6 shrink-0 items-center justify-center rounded text-ink-muted hover:bg-hover hover:text-ink aria-expanded:bg-hover"
+ data-testid={`fig-export-options-${k()}`}
+ onClick={() => setOpen((o) => !o)}
>
- <For each={EXPORT_FORMATS}>
- {(f) => <option value={f.format}>{f.label}</option>}
- </For>
- </select>
- <Show when={s().format === 'SVG' || s().format === 'JPEG'}>
- <button
- type="button"
- aria-label="Export settings"
- aria-expanded={open()}
- class="rounded p-0.5 text-ink-muted hover:bg-hover hover:text-ink aria-expanded:bg-hover"
- data-testid={`fig-export-options-${k()}`}
- onClick={() => setOpen((o) => !o)}
- >
- <DotsThree class="size-3.5" />
- </button>
- </Show>
+ <DotsThree class="size-3.5" />
+ </button>
<button
type="button"
aria-label="Remove export setting"
- class="rounded p-0.5 text-ink-muted hover:bg-hover hover:text-ink"
+ class="flex size-6 shrink-0 items-center justify-center rounded text-ink-muted hover:bg-hover hover:text-ink"
data-testid={`fig-export-remove-${k()}`}
onClick={props.onRemove}
>
<Minus class="size-3.5" />
</button>
</div>
+ <Show when={open()}>
+ <label class="flex items-center gap-2 text-ink-muted">
+ Suffix
+ <DraftInput
+ class="w-0 flex-1"
+ ariaLabel="Suffix"
+ placeholder="Suffix"
+ testId={`fig-export-suffix-${k()}`}
+ value={s().suffix}
+ onCommit={(suffix) => props.onChange({ ...s(), suffix })}
+ />
+ </label>
+ </Show>
<Show when={open() && s().format === 'SVG'}>
<div class="flex flex-col gap-1 rounded-md bg-inset px-2 py-1.5 text-ink-muted">
<label class="flex items-center gap-2">
@@ -248,6 +248,26 @@ export function ExportSection(props: {
title="Export"
testId="fig-export"
onAdd={() => update([...settings(), nextSetting(settings())])}
+ actions={
+ <EditorMenu
+ label="Copy as"
+ items={[
+ {
+ label: 'Copy as PNG',
+ icon: <Copy class="size-3.5" />,
+ onSelect: props.onCopyPng,
+ },
+ {
+ label: 'Copy as SVG',
+ icon: <Copy class="size-3.5" />,
+ onSelect: props.onCopySvg,
+ testId: 'fig-copy-svg',
+ },
+ ]}
+ >
+ <Copy class="size-3.5" />
+ </EditorMenu>
+ }
>
<datalist id="fig-export-sizes">
<For each={EXPORT_SIZES}>{(s) => <option value={s} />}</For>
@@ -265,10 +285,9 @@ export function ExportSection(props: {
)}
</Index>
<Show when={settings().length > 0}>
- <Button
- variant="outline"
- size="sm"
- class="w-full truncate"
+ <button
+ type="button"
+ class="h-6 w-full truncate rounded-md border border-edge bg-transparent px-2 text-ink hover:bg-hover"
data-testid="fig-export-button"
title={
props.count === 1
@@ -280,7 +299,7 @@ export function ExportSection(props: {
onClick={() => props.onExport(settings())}
>
Export {label()}
- </Button>
+ </button>
<Show when={props.preview && props.count === 1}>
<button
type="button"
@@ -309,21 +328,6 @@ export function ExportSection(props: {
</Show>
</Show>
</Show>
- <div class="flex flex-wrap gap-1.5">
- <Button variant="outline" size="sm" onClick={props.onCopyPng}>
- <Copy />
- Copy as PNG
- </Button>
- <Button
- variant="outline"
- size="sm"
- data-testid="fig-copy-svg"
- onClick={props.onCopySvg}
- >
- <Copy />
- Copy as SVG
- </Button>
- </div>
</Section>
);
}
diff --git a/apps/web/src/features/block-fig/components/fig-context-menu.tsx b/apps/web/src/features/block-fig/components/fig-context-menu.tsx
index 65287c7862..b82634de78 100644
--- a/apps/web/src/features/block-fig/components/fig-context-menu.tsx
+++ b/apps/web/src/features/block-fig/components/fig-context-menu.tsx
@@ -51,7 +51,7 @@ export function FigContextMenu(props: {
<DropdownMenu.Portal>
<ContextMenuContent
contentComponent={DropdownMenu.Content}
- class="w-60 text-xs"
+ class="fig-editor-theme w-60 text-xs"
// The chosen action decides where focus goes (a rename field).
onCloseAutoFocus={(e) => e.preventDefault()}
>
diff --git a/apps/web/src/features/block-fig/components/fig-opening.tsx b/apps/web/src/features/block-fig/components/fig-opening.tsx
index 4a35ce13b8..9eea606055 100644
--- a/apps/web/src/features/block-fig/components/fig-opening.tsx
+++ b/apps/web/src/features/block-fig/components/fig-opening.tsx
@@ -1,35 +1,74 @@
-/**
- * What a design shows while the engine opens it: the preview Figma stored
- * in the file (large designs take seconds to decode), under a status line.
- */
+/** Keep the editor's geometry stable through download, sync and decoding. */
+import './editor-theme.css';
+import { For } from 'solid-js';
-import { figThumbnail } from '@core/fig-engine/thumbnail';
-import { onCleanup, Show } from 'solid-js';
-
-export function FigOpening(props: { bytes?: ArrayBuffer }) {
- const png = props.bytes ? figThumbnail(props.bytes) : null;
- const url = png
- ? URL.createObjectURL(new Blob([png.slice()], { type: 'image/png' }))
- : undefined;
- onCleanup(() => {
- if (url) URL.revokeObjectURL(url);
- });
+export function FigOpening() {
return (
<div
- class="relative flex size-full flex-col items-center justify-center gap-3 p-6 text-ink-muted text-sm"
+ class="fig-editor-theme relative flex size-full min-h-0 min-w-0 overflow-hidden bg-page text-ink-muted text-xs"
data-testid="fig-opening"
+ aria-busy="true"
+ >
+ <div
+ class="flex w-[280px] shrink-0 flex-col border-edge-frame border-r bg-page"
+ aria-hidden="true"
+ >
+ <div class="flex h-12 items-center px-4">
+ <div class="h-2 w-28 rounded bg-hover" />
+ </div>
+ <div class="flex h-10 items-center gap-4 border-edge-frame border-b px-4">
+ <span>File</span>
+ <span>Assets</span>
+ </div>
+ <div class="border-edge-frame border-b p-4">
+ Pages
+ <div class="mt-4 h-7 rounded bg-hover" />
+ </div>
+ <div class="p-4">
+ Layers
+ <For each={[128, 168, 112, 144, 96]}>
+ {(width) => (
+ <div
+ class="mt-5 h-2 rounded bg-hover"
+ style={{ width: `${width}px` }}
+ />
+ )}
+ </For>
+ </div>
+ </div>
+ <div class="relative min-w-0 flex-1" data-testid="fig-opening-canvas">
+ <FigLoadingStatus />
+ </div>
+ <div
+ class="w-[240px] shrink-0 border-edge-frame border-l bg-page"
+ aria-hidden="true"
+ >
+ <div class="h-12" />
+ <div class="flex h-10 items-center gap-4 border-edge-frame border-b px-4">
+ <span>Design</span>
+ <span>Prototype</span>
+ </div>
+ <div class="p-4">
+ <div class="h-2 w-12 rounded bg-hover" />
+ <div class="mt-5 h-7 rounded bg-hover" />
+ <div class="mt-3 h-7 rounded bg-hover" />
+ </div>
+ </div>
+ </div>
+ );
+}
+
+/** A quiet status in the canvas; never substitutes a differently scaled image. */
+export function FigLoadingStatus() {
+ return (
+ <div
+ role="status"
+ class="pointer-events-none absolute inset-0 flex items-center justify-center"
+ data-testid="fig-loading-status"
>
- <Show when={url}>
- {(src) => (
- <img
- src={src()}
- alt=""
- class="max-h-[60%] max-w-[80%] object-contain opacity-60"
- data-testid="fig-opening-preview"
- />
- )}
- </Show>
- Opening design…
+ <span class="rounded-md bg-panel px-3 py-2 text-ink-muted text-xs">
+ Opening design…
+ </span>
</div>
);
}
diff --git a/apps/web/src/features/block-fig/components/font-picker.tsx b/apps/web/src/features/block-fig/components/font-picker.tsx
index f78a2dde30..24b66cf061 100644
--- a/apps/web/src/features/block-fig/components/font-picker.tsx
+++ b/apps/web/src/features/block-fig/components/font-picker.tsx
@@ -12,6 +12,7 @@ import { Layer } from '@ui';
import {
createMemo,
createSignal,
+ createUniqueId,
For,
onCleanup,
onMount,
@@ -22,8 +23,11 @@ import {
const LIMIT = 150;
function Row(props: {
+ id: string;
family: string;
selected: boolean;
+ active: boolean;
+ onActive: () => void;
preview?: (family: string) => Promise<string | undefined>;
onSelect: () => void;
}) {
@@ -50,15 +54,19 @@ function Row(props: {
<button
ref={el}
type="button"
+ id={props.id}
+ tabIndex={-1}
role="option"
aria-selected={props.selected}
+ data-active={props.active ? 'true' : undefined}
data-testid="fig-font-option"
data-family={props.family}
- class="w-full truncate rounded px-2 py-1 text-left text-ink hover:bg-hover aria-selected:bg-hover"
+ class="w-full truncate rounded px-2 py-1.5 text-left text-ink hover:bg-hover aria-selected:font-medium data-[active=true]:bg-hover"
style={{
'font-family': face() ? `"${face()}", Inter, sans-serif` : undefined,
}}
onClick={() => props.onSelect()}
+ onPointerMove={props.onActive}
>
{props.family}
</button>
@@ -80,6 +88,9 @@ export function FontPicker(props: {
}) {
const [open, setOpen] = createSignal(false);
const [query, setQuery] = createSignal('');
+ const [active, setActive] = createSignal<string>();
+ const listId = createUniqueId();
+ let list!: HTMLDivElement;
const matches = (family: string) =>
family.toLowerCase().includes(query().trim().toLowerCase());
const documentRows = createMemo(() => props.documentFamilies.filter(matches));
@@ -97,6 +108,30 @@ export function FontPicker(props: {
setQuery('');
props.onSelect(family);
};
+ const rows = () => [...documentRows(), ...googleRows()];
+ const rowId = (family: string) => `${listId}-${encodeURIComponent(family)}`;
+ const navigate = (event: KeyboardEvent) => {
+ const families = rows();
+ if (families.length === 0) return;
+ if (event.key === 'Enter') {
+ event.preventDefault();
+ choose(active() ?? families[0]);
+ } else if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
+ event.preventDefault();
+ const current = families.indexOf(active() ?? '');
+ const direction = event.key === 'ArrowDown' ? 1 : -1;
+ const next =
+ current < 0
+ ? direction > 0
+ ? 0
+ : families.length - 1
+ : (current + direction + families.length) % families.length;
+ setActive(families[next]);
+ list
+ .querySelector('[data-active="true"]')
+ ?.scrollIntoView({ block: 'nearest' });
+ }
+ };
return (
<Popover
placement="left-start"
@@ -104,6 +139,7 @@ export function FontPicker(props: {
open={open()}
onOpenChange={(o) => {
setOpen(o);
+ setActive(undefined);
if (o) props.onOpen?.();
}}
>
@@ -127,7 +163,7 @@ export function FontPicker(props: {
<Popover.Portal>
<Layer depth={3}>
<Popover.Content
- class="z-modal flex max-h-96 w-64 flex-col rounded-xl border border-edge-muted bg-menu p-2 shadow-xl outline-none"
+ class="fig-editor-theme z-modal flex max-h-96 w-64 flex-col rounded-xl border border-edge-muted bg-menu p-2 text-xs shadow-xl outline-none"
aria-label="Fonts"
data-testid="fig-font-picker"
onKeyDown={(e: KeyboardEvent) => {
@@ -140,17 +176,26 @@ export function FontPicker(props: {
placeholder="Search fonts"
aria-label="Search fonts"
data-testid="fig-font-search"
+ role="combobox"
+ aria-autocomplete="list"
+ aria-expanded={open()}
+ aria-controls={listId}
+ aria-activedescendant={active() ? rowId(active()!) : undefined}
value={query()}
- onInput={(e) => setQuery(e.currentTarget.value)}
- onKeyDown={(e) => {
- if (e.key === 'Enter') {
- const first = documentRows()[0] ?? googleRows()[0];
- if (first) choose(first);
- }
+ onInput={(e) => {
+ setQuery(e.currentTarget.value);
+ setActive(undefined);
}}
+ onKeyDown={navigate}
autofocus
/>
- <div class="min-h-0 flex-1 overflow-y-auto" role="listbox">
+ <div
+ ref={list}
+ id={listId}
+ class="min-h-0 flex-1 overflow-y-auto"
+ role="listbox"
+ aria-label="Font families"
+ >
<Show when={documentRows().length > 0}>
<div class="px-2 pt-1 pb-0.5 text-ink-muted text-xs">
In this file
@@ -158,8 +203,11 @@ export function FontPicker(props: {
<For each={documentRows()}>
{(f) => (
<Row
+ id={rowId(f)}
family={f}
selected={f === props.value}
+ active={f === active()}
+ onActive={() => setActive(f)}
preview={props.preview}
onSelect={() => choose(f)}
/>
@@ -173,8 +221,11 @@ export function FontPicker(props: {
<For each={googleRows()}>
{(f) => (
<Row
+ id={rowId(f)}
family={f}
selected={f === props.value}
+ active={f === active()}
+ onActive={() => setActive(f)}
preview={props.preview}
onSelect={() => choose(f)}
/>
diff --git a/apps/web/src/features/block-fig/components/geometry-sections.tsx b/apps/web/src/features/block-fig/components/geometry-sections.tsx
new file mode 100644
index 0000000000..7b44047af7
--- /dev/null
+++ b/apps/web/src/features/block-fig/components/geometry-sections.tsx
@@ -0,0 +1,400 @@
+/** Position and layout controls in the same groups as the Figma inspector. */
+import type { NodeInfo } from '@core/fig-engine/types';
+import AlignBottom from '@phosphor/align-bottom.svg';
+import AlignCenterHorizontal from '@phosphor/align-center-horizontal.svg';
+import AlignCenterVertical from '@phosphor/align-center-vertical.svg';
+import AlignLeft from '@phosphor/align-left.svg';
+import AlignRight from '@phosphor/align-right.svg';
+import AlignTop from '@phosphor/align-top.svg';
+import Angle from '@phosphor/angle.svg';
+import ArrowClockwise from '@phosphor/arrow-clockwise.svg';
+import FlipHorizontal from '@phosphor/flip-horizontal.svg';
+import FlipVertical from '@phosphor/flip-vertical.svg';
+import LockKey from '@phosphor/lock-key.svg';
+import LockKeyOpen from '@phosphor/lock-key-open.svg';
+import { createSignal, For, type JSX, Show } from 'solid-js';
+import type { Alignment } from '../core/align';
+import { formatMeasure } from '../core/measure';
+import type { Patch } from '../primitives/create-fig-editor';
+import {
+ AutoLayoutControls,
+ ConstraintControls,
+ SizingControl,
+} from './auto-layout-controls';
+import { NumberField } from './design-fields';
+import { Section } from './panel-section';
+import { TextResizing } from './text-resizing';
+
+const ALIGNMENTS: {
+ how: Alignment;
+ label: string;
+ icon: (props: { class?: string }) => JSX.Element;
+}[] = [
+ { how: 'left', label: 'Align left', icon: AlignLeft },
+ {
+ how: 'center',
+ label: 'Align horizontal centers',
+ icon: AlignCenterHorizontal,
+ },
+ { how: 'right', label: 'Align right', icon: AlignRight },
+ { how: 'top', label: 'Align top', icon: AlignTop },
+ { how: 'middle', label: 'Align vertical centers', icon: AlignCenterVertical },
+ { how: 'bottom', label: 'Align bottom', icon: AlignBottom },
+];
+
+export function AlignRow(props: { onAlign: (how: Alignment) => void }) {
+ return (
+ <div class="grid grid-cols-2 gap-2">
+ <For each={[ALIGNMENTS.slice(0, 3), ALIGNMENTS.slice(3)]}>
+ {(group) => (
+ <div class="flex rounded-md bg-inset">
+ <For each={group}>
+ {(item) => (
+ <button
+ type="button"
+ aria-label={item.label}
+ title={item.label}
+ data-testid={`fig-align-${item.how}`}
+ class="flex h-6 min-w-0 flex-1 items-center justify-center rounded text-ink-muted hover:bg-hover hover:text-ink"
+ onClick={() => props.onAlign(item.how)}
+ >
+ {item.icon({ class: 'size-4' })}
+ </button>
+ )}
+ </For>
+ </div>
+ )}
+ </For>
+ </div>
+ );
+}
+
+function GeometryField(props: {
+ label: string | JSX.Element;
+ name: string;
+ value: number;
+ testId: string;
+ min?: number;
+ suffix?: JSX.Element;
+ onChange?: (value: number, live: boolean) => void;
+}) {
+ return (
+ <Show
+ when={props.onChange}
+ fallback={
+ <div
+ class="flex h-6 items-center gap-2 rounded bg-inset px-2"
+ title={props.name}
+ >
+ <span class="text-ink-muted">{props.label}</span>
+ <span>{formatMeasure(props.value)}</span>
+ </div>
+ }
+ >
+ {(change) => (
+ <NumberField
+ label={props.label}
+ ariaLabel={props.name}
+ value={props.value}
+ min={props.min}
+ suffix={props.suffix}
+ testId={props.testId}
+ onChange={change()}
+ />
+ )}
+ </Show>
+ );
+}
+
+export function PositionSection(props: {
+ info: NodeInfo;
+ onPatch?: (patch: Patch, live: boolean) => void;
+ onAlign?: (how: Alignment) => void;
+ onFlip?: (axis: 'horizontal' | 'vertical') => void;
+}) {
+ return (
+ <Section title="Position" testId="fig-position-section">
+ <Show when={props.onPatch && props.onAlign}>
+ {(align) => (
+ <>
+ <span class="text-ink-muted text-[11px]">Alignment</span>
+ <AlignRow onAlign={align()} />
+ </>
+ )}
+ </Show>
+ <span class="mt-1 text-ink-muted text-[11px]">Position</span>
+ <div class="grid grid-cols-2 gap-2">
+ <GeometryField
+ label="X"
+ name="X position"
+ value={props.info.x}
+ testId="fig-field-x"
+ onChange={
+ props.onPatch && ((x, live) => props.onPatch?.({ x }, live))
+ }
+ />
+ <GeometryField
+ label="Y"
+ name="Y position"
+ value={props.info.y}
+ testId="fig-field-y"
+ onChange={
+ props.onPatch && ((y, live) => props.onPatch?.({ y }, live))
+ }
+ />
+ <span class="col-span-2 text-ink-muted text-[11px]">Rotation</span>
+ <GeometryField
+ label={<Angle class="size-3.5" />}
+ name="Rotation"
+ value={props.info.rotation}
+ testId="fig-field-rotation"
+ onChange={
+ props.onPatch &&
+ ((rotation, live) => props.onPatch?.({ rotation }, live))
+ }
+ />
+ <Show when={props.onPatch && props.onFlip}>
+ <div class="flex items-center rounded-md bg-inset">
+ <button
+ type="button"
+ aria-label="Rotate 90 degrees"
+ title="Rotate 90 degrees"
+ data-testid="fig-rotate-90"
+ class="flex h-6 flex-1 items-center justify-center rounded hover:bg-hover"
+ onClick={() =>
+ props.onPatch?.(
+ { rotation: (props.info.rotation + 90) % 360 },
+ false
+ )
+ }
+ >
+ <ArrowClockwise class="size-4" />
+ </button>
+ <button
+ type="button"
+ aria-label="Flip horizontal"
+ title="Flip horizontal · ⇧H"
+ data-testid="fig-flip-horizontal"
+ class="flex h-6 flex-1 items-center justify-center rounded hover:bg-hover"
+ onClick={() => props.onFlip?.('horizontal')}
+ >
+ <FlipHorizontal class="size-4" />
+ </button>
+ <button
+ type="button"
+ aria-label="Flip vertical"
+ title="Flip vertical · ⇧V"
+ data-testid="fig-flip-vertical"
+ class="flex h-6 flex-1 items-center justify-center rounded hover:bg-hover"
+ onClick={() => props.onFlip?.('vertical')}
+ >
+ <FlipVertical class="size-4" />
+ </button>
+ </div>
+ </Show>
+ </div>
+ <Show when={props.onPatch && props.info.layoutParent}>
+ <label class="mt-1 flex items-center gap-2 text-ink-muted">
+ <input
+ type="checkbox"
+ checked={props.info.layoutParent === 'ABSOLUTE'}
+ data-testid="fig-absolute"
+ onChange={(e) =>
+ props.onPatch?.(
+ {
+ layoutPositioning: e.currentTarget.checked
+ ? 'ABSOLUTE'
+ : 'AUTO',
+ },
+ false
+ )
+ }
+ />
+ Ignore auto layout
+ </label>
+ </Show>
+ <Show when={!props.onPatch && props.info.constraints}>
+ {(constraints) => (
+ <div class="mt-1 text-ink-muted">
+ Constraints: {constraints()[0].toLowerCase()} ·{' '}
+ {constraints()[1].toLowerCase()}
+ </div>
+ )}
+ </Show>
+ <Show when={props.onPatch && props.info.constrained}>
+ <ConstraintControls
+ constraints={props.info.constraints}
+ onPatch={(patch) => props.onPatch?.(patch, false)}
+ />
+ </Show>
+ </Section>
+ );
+}
+
+function LayoutDimensions(props: {
+ info: NodeInfo;
+ onPatch?: (patch: Patch, live: boolean) => void;
+}) {
+ // This constrains inspector edits; it does not change the layer's layout mode.
+ const [locked, setLocked] = createSignal(false);
+ const resize = (axis: 'width' | 'height', value: number, live: boolean) => {
+ const patch: Patch = { [axis]: value };
+ if (locked() && props.info.width > 0 && props.info.height > 0) {
+ if (axis === 'width')
+ patch.height = (value * props.info.height) / props.info.width;
+ else patch.width = (value * props.info.width) / props.info.height;
+ }
+ props.onPatch?.(patch, live);
+ };
+ return (
+ <>
+ <Show when={props.info.text && props.onPatch}>
+ <span class="text-ink-muted text-[11px]">
+ {props.info.autoLayout ? 'Resizing' : 'Dimensions'}
+ </span>
+ <TextResizing text={props.info.text!} onPatch={props.onPatch!} />
+ </Show>
+ <div class="flex items-center justify-between text-ink-muted text-[11px]">
+ <span>{props.info.autoLayout ? 'Resizing' : 'Dimensions'}</span>
+ <Show when={props.onPatch && !props.info.text}>
+ <button
+ type="button"
+ aria-label="Lock aspect ratio"
+ aria-pressed={locked()}
+ title={locked() ? 'Unlock aspect ratio' : 'Lock aspect ratio'}
+ data-testid="fig-lock-aspect-ratio"
+ class="flex size-5 items-center justify-center rounded hover:bg-hover hover:text-ink aria-pressed:bg-hover aria-pressed:text-ink"
+ onClick={() => setLocked((value) => !value)}
+ >
+ <Show when={locked()} fallback={<LockKeyOpen class="size-3.5" />}>
+ <LockKey class="size-3.5" />
+ </Show>
+ </button>
+ </Show>
+ </div>
+ <div class="grid grid-cols-2 gap-2">
+ <GeometryField
+ label="W"
+ name="Width"
+ value={props.info.width}
+ min={0.01}
+ testId="fig-field-w"
+ suffix={
+ props.onPatch &&
+ (!props.info.text || props.info.layoutParent === 'AUTO') && (
+ <SizingControl
+ info={props.info}
+ axis={0}
+ onPatch={props.onPatch}
+ />
+ )
+ }
+ onChange={
+ props.onPatch && ((width, live) => resize('width', width, live))
+ }
+ />
+ <GeometryField
+ label="H"
+ name="Height"
+ value={props.info.height}
+ min={0.01}
+ testId="fig-field-h"
+ suffix={
+ props.onPatch &&
+ (!props.info.text || props.info.layoutParent === 'AUTO') && (
+ <SizingControl
+ info={props.info}
+ axis={1}
+ onPatch={props.onPatch}
+ />
+ )
+ }
+ onChange={
+ props.onPatch && ((height, live) => resize('height', height, live))
+ }
+ />
+ </div>
+ </>
+ );
+}
+
+export function LayoutSection(props: {
+ info: NodeInfo;
+ onPatch?: (patch: Patch, live: boolean) => void;
+ onAddAutoLayout?: () => void;
+}) {
+ const editableLayout = () => {
+ const layout = props.info.autoLayout;
+ return props.onPatch &&
+ layout &&
+ ['HORIZONTAL', 'VERTICAL'].includes(layout.mode) &&
+ !layout.wrap
+ ? layout
+ : undefined;
+ };
+ return (
+ <Section
+ title={props.info.autoLayout ? 'Auto layout' : 'Layout'}
+ testId="fig-auto-layout-section"
+ onAdd={
+ !props.info.autoLayout && ['FRAME', 'SYMBOL'].includes(props.info.type)
+ ? props.onAddAutoLayout
+ : undefined
+ }
+ addLabel="Add auto layout"
+ onRemove={
+ props.info.autoLayout && props.onPatch
+ ? () => props.onPatch?.({ layoutMode: 'NONE' }, false)
+ : undefined
+ }
+ >
+ <Show
+ when={editableLayout()}
+ fallback={
+ <>
+ <LayoutDimensions info={props.info} onPatch={props.onPatch} />
+ <Show when={props.info.autoLayout}>
+ {(layout) => (
+ <div class="text-ink-muted">
+ {layout().mode.toLowerCase()} · Gap{' '}
+ {formatMeasure(layout().spacing)} · Padding{' '}
+ {[
+ layout().paddingTop,
+ layout().paddingRight,
+ layout().paddingBottom,
+ layout().paddingLeft,
+ ]
+ .map(formatMeasure)
+ .join(' ')}
+ </div>
+ )}
+ </Show>
+ </>
+ }
+ >
+ {(layout) => (
+ <AutoLayoutControls
+ layout={layout()}
+ onPatch={(patch, live) => props.onPatch?.(patch, live)}
+ >
+ <LayoutDimensions info={props.info} onPatch={props.onPatch} />
+ </AutoLayoutControls>
+ )}
+ </Show>
+ <Show when={props.info.type === 'FRAME'}>
+ <label class="mt-1 flex items-center gap-2 text-ink-muted">
+ <input
+ type="checkbox"
+ checked={props.info.clipsContent}
+ disabled={!props.onPatch}
+ data-testid="fig-clip-content"
+ onChange={(e) =>
+ props.onPatch?.({ clipContent: e.currentTarget.checked }, false)
+ }
+ />
+ Clip content
+ </label>
+ </Show>
+ </Section>
+ );
+}
diff --git a/apps/web/src/features/block-fig/components/inspector-select.tsx b/apps/web/src/features/block-fig/components/inspector-select.tsx
new file mode 100644
index 0000000000..e730935e0f
--- /dev/null
+++ b/apps/web/src/features/block-fig/components/inspector-select.tsx
@@ -0,0 +1,75 @@
+/** Compact, keyboard-accessible choices shared by the inspector's fields. */
+import { Select } from '@kobalte/core/select';
+import CaretDown from '@phosphor/caret-down.svg';
+import Check from '@phosphor/check.svg';
+
+type Option<T extends string> = { value: T; label: string; disabled?: boolean };
+
+export function InspectorSelect<T extends string>(props: {
+ label: string;
+ value: T;
+ options: readonly Option<T>[];
+ onChange: (value: T) => void;
+ testId?: string;
+ disabled?: boolean;
+ class?: string;
+}) {
+ return (
+ <Select<Option<T>>
+ class={props.class ?? 'min-w-0 flex-1'}
+ options={[...props.options]}
+ optionValue={(option) => `value:${option.value}`}
+ optionTextValue="label"
+ optionDisabled="disabled"
+ value={props.options.find((option) => option.value === props.value)}
+ onChange={(option) => {
+ if (option && option.value !== props.value)
+ props.onChange(option.value);
+ }}
+ disabled={props.disabled}
+ disallowEmptySelection
+ placement="bottom-start"
+ gutter={4}
+ itemComponent={(item) => (
+ <Select.Item
+ item={item.item}
+ class="relative flex h-6 items-center gap-2 rounded px-2 text-ink outline-none data-[disabled]:opacity-40 data-[highlighted]:bg-accent data-[highlighted]:text-accent-contrast"
+ >
+ <span class="flex size-3 items-center justify-center">
+ <Select.ItemIndicator>
+ <Check class="size-3" />
+ </Select.ItemIndicator>
+ </span>
+ <Select.ItemLabel>{item.item.rawValue.label}</Select.ItemLabel>
+ </Select.Item>
+ )}
+ >
+ <Select.Trigger
+ onKeyDown={(event) => event.stopPropagation()}
+ aria-label={props.label}
+ data-testid={props.testId}
+ title={
+ props.options.find((option) => option.value === props.value)?.label
+ }
+ class="disabled:opacity-50 flex h-6 w-full min-w-0 items-center justify-between gap-1 rounded-md bg-inset px-2 text-left text-ink outline-none hover:shadow-[inset_0_0_0_1px_var(--color-edge)] focus-visible:outline focus-visible:outline-1 focus-visible:outline-accent"
+ >
+ <Select.Value<Option<T>> class="truncate">
+ {(state) => state.selectedOption().label}
+ </Select.Value>
+ <Select.Icon>
+ <CaretDown class="size-3 shrink-0" />
+ </Select.Icon>
+ </Select.Trigger>
+ <Select.Portal>
+ <Select.Content
+ class="fig-editor-theme z-modal min-w-32 max-w-72 rounded-xl border border-edge-muted bg-menu p-1.5 text-xs text-ink shadow-xl outline-none"
+ onKeyDown={(event) => event.stopPropagation()}
+ onPointerDown={(event) => event.stopPropagation()}
+ onPointerUp={(event) => event.stopPropagation()}
+ >
+ <Select.Listbox class="max-h-72 overflow-y-auto outline-none" />
+ </Select.Content>
+ </Select.Portal>
+ </Select>
+ );
+}
diff --git a/apps/web/src/features/block-fig/components/instance-section.tsx b/apps/web/src/features/block-fig/components/instance-section.tsx
index 3ad1653b07..94e2523b2d 100644
--- a/apps/web/src/features/block-fig/components/instance-section.tsx
+++ b/apps/web/src/features/block-fig/components/instance-section.tsx
@@ -1,3 +1,4 @@
+import { InspectorSelect } from './inspector-select';
/**
* The instance section of the design panel, as Figma shows it for a
* selected instance: its main component (with "Go to main component"),
@@ -44,19 +45,14 @@ function Properties(props: {
<For each={props.instance.variants}>
{(v) => (
<PropertyRow label={v.name}>
- <select
- class="w-full rounded-md bg-inset px-1.5 py-0.5 text-ink outline-none disabled:opacity-60"
+ <InspectorSelect
+ label={v.name}
value={v.value}
disabled={!set}
- data-testid={`fig-variant-${slug(v.name)}`}
- onChange={(e) =>
- set?.(id(), v.name, { variant: e.currentTarget.value })
- }
- >
- <For each={v.options}>
- {(o) => <option value={o}>{o}</option>}
- </For>
- </select>
+ testId={`fig-variant-${slug(v.name)}`}
+ options={v.options.map((value) => ({ value, label: value }))}
+ onChange={(value) => set?.(id(), v.name, { variant: value })}
+ />
</PropertyRow>
)}
</For>
@@ -165,7 +161,7 @@ export function InstanceSection(props: {
/>
<For each={i().nested}>
{(n) => (
- <div class="flex flex-col gap-1.5 border-edge-muted border-t pt-1.5">
+ <div class="flex flex-col gap-1.5 border-edge-frame border-t pt-1.5">
<span class="flex items-center gap-1 font-medium text-ink">
<DiamondsFour class="size-3 text-accent" />
{n.name}
diff --git a/apps/web/src/features/block-fig/components/layout-grid-section.tsx b/apps/web/src/features/block-fig/components/layout-grid-section.tsx
index 5d2f6da4e9..7e71ebf3af 100644
--- a/apps/web/src/features/block-fig/components/layout-grid-section.tsx
+++ b/apps/web/src/features/block-fig/components/layout-grid-section.tsx
@@ -1,3 +1,4 @@
+import { InspectorSelect } from './inspector-select';
/**
* The design panel's Layout grid section for frames, as in Figma: "+"
* adds a 10 px grid; each grid is a square grid, columns, or rows, with
@@ -97,27 +98,32 @@ function GridRow(props: {
}
/>
</SwatchPopover>
- <select
- class="min-w-0 flex-1 rounded-md bg-inset px-1.5 py-1 text-ink outline-none"
- aria-label="Grid type"
- data-testid={`fig-grid-type-${k()}`}
+ <InspectorSelect
+ label="Grid type"
+ testId={`fig-grid-type-${k()}`}
value={kindOf(g())}
- onChange={(e) => {
- const kind = e.currentTarget.value as GridKind;
+ options={[
+ { value: 'GRID', label: `Grid ${g().sectionSize}px` },
+ {
+ value: 'COLUMNS',
+ label: `Columns (${g().count === 0 ? 'Auto' : g().count})`,
+ },
+ {
+ value: 'ROWS',
+ label: `Rows (${g().count === 0 ? 'Auto' : g().count})`,
+ },
+ ]}
+ onChange={(kind) =>
props.onChange(
- { ...newGrid(kind), color: g().color, alpha: g().alpha },
+ {
+ ...newGrid(kind as GridKind),
+ color: g().color,
+ alpha: g().alpha,
+ },
false
- );
- }}
- >
- <option value="GRID">Grid {g().sectionSize}px</option>
- <option value="COLUMNS">
- Columns ({g().count === 0 ? 'Auto' : g().count})
- </option>
- <option value="ROWS">
- Rows ({g().count === 0 ? 'Auto' : g().count})
- </option>
- </select>
+ )
+ }
+ />
<button
type="button"
aria-label="Grid settings"
@@ -174,20 +180,20 @@ function GridRow(props: {
}}
onChange={(count) => set({ count })}
/>
- <select
- class="min-w-0 rounded-md bg-inset px-1.5 py-1 text-ink outline-none"
- aria-label="Type"
- data-testid={`fig-grid-align-${k()}`}
+ <InspectorSelect
+ label="Type"
+ testId={`fig-grid-align-${k()}`}
value={g().align}
- onChange={(e) =>
- set({ align: e.currentTarget.value as LayoutGridInfo['align'] })
+ options={[
+ { value: 'STRETCH', label: 'Stretch' },
+ { value: 'MIN', label: columns() ? 'Left' : 'Top' },
+ { value: 'CENTER', label: 'Center' },
+ { value: 'MAX', label: columns() ? 'Right' : 'Bottom' },
+ ]}
+ onChange={(align) =>
+ set({ align: align as LayoutGridInfo['align'] })
}
- >
- <option value="STRETCH">Stretch</option>
- <option value="MIN">{columns() ? 'Left' : 'Top'}</option>
- <option value="CENTER">Center</option>
- <option value="MAX">{columns() ? 'Right' : 'Bottom'}</option>
- </select>
+ />
<Show when={g().align !== 'STRETCH'}>
<NumberField
label={columns() ? 'Width' : 'Height'}
@@ -231,7 +237,7 @@ export function LayoutGridSection(props: {
props.onChange?.(grids, live);
return (
<Section
- title="Layout grid"
+ title="Layout guide"
testId="fig-layout-grids"
onAdd={
props.onChange ? () => update([...props.grids, newGrid()]) : undefined
diff --git a/apps/web/src/features/block-fig/components/libraries-dialog.tsx b/apps/web/src/features/block-fig/components/libraries-dialog.tsx
index 96235cf664..a6a7065c0e 100644
--- a/apps/web/src/features/block-fig/components/libraries-dialog.tsx
+++ b/apps/web/src/features/block-fig/components/libraries-dialog.tsx
@@ -69,7 +69,7 @@ export function LibrariesDialog(props: {
<Dialog
open
onOpenChange={(open) => !open && props.onClose()}
- class="w-120"
+ class="fig-editor-theme w-120"
>
<Panel depth={2} class="rounded-xl *:max-h-[80vh]">
<Panel.Body scroll>
diff --git a/apps/web/src/features/block-fig/components/library-assets.tsx b/apps/web/src/features/block-fig/components/library-assets.tsx
index 29ba036e79..05e39e420b 100644
--- a/apps/web/src/features/block-fig/components/library-assets.tsx
+++ b/apps/web/src/features/block-fig/components/library-assets.tsx
@@ -26,7 +26,7 @@ export function LibraryAssets(props: {
const [open, setOpen] = createSignal(true);
return (
<div
- class="border-edge-muted border-t py-1"
+ class="border-edge-frame border-t py-1"
data-testid="fig-library-assets"
data-library={props.library}
>
diff --git a/apps/web/src/features/block-fig/components/library-updates.tsx b/apps/web/src/features/block-fig/components/library-updates.tsx
index 6da07e8b2e..4377f5eee8 100644
--- a/apps/web/src/features/block-fig/components/library-updates.tsx
+++ b/apps/web/src/features/block-fig/components/library-updates.tsx
@@ -68,7 +68,7 @@ export function LibraryUpdatesDialog(props: {
<Dialog
open
onOpenChange={(open) => !open && props.onClose()}
- class="w-120"
+ class="fig-editor-theme w-120"
>
<Panel depth={2} class="rounded-xl *:max-h-[80vh]">
<Panel.Body scroll>
diff --git a/apps/web/src/features/block-fig/components/main-menu.tsx b/apps/web/src/features/block-fig/components/main-menu.tsx
index ab20367ef8..e75ac58e4d 100644
--- a/apps/web/src/features/block-fig/components/main-menu.tsx
+++ b/apps/web/src/features/block-fig/components/main-menu.tsx
@@ -1,61 +1,177 @@
-/**
- * The main menu at the left panel's top (Figma's menu): File items such
- * as "Export frames to PDF", and View toggles. Presentational.
- */
-
+/** File, edit, view, and layer commands grouped like Figma's main menu. */
+import { IS_MAC } from '@core/constant/isMac';
import List from '@phosphor/list.svg';
-import { Button } from '@ui/components/Button';
-import { createSignal, For, onCleanup, Show } from 'solid-js';
-import type { ZoomMenuItem } from './viewer-toolbar';
+import { paletteActions } from '../core/palette';
+import { EDIT_ACTIONS, type ViewerAction } from '../core/shortcuts';
+import { EditorMenu, type EditorMenuItem } from './editor-menu';
+
+const SELECTION_COMMANDS: ReadonlySet<ViewerAction> = new Set([
+ 'copy',
+ 'cut',
+ 'paste-replace',
+ 'duplicate',
+ 'delete',
+ 'group',
+ 'ungroup',
+ 'frame-selection',
+ 'add-auto-layout',
+ 'remove-auto-layout',
+ 'create-component',
+ 'detach-instance',
+ 'toggle-visible',
+ 'toggle-locked',
+ 'rename',
+ 'bring-to-front',
+ 'bring-forward',
+ 'send-backward',
+ 'send-to-back',
+ 'align-left',
+ 'align-center',
+ 'align-right',
+ 'align-top',
+ 'align-middle',
+ 'align-bottom',
+ 'distribute-horizontal',
+ 'distribute-vertical',
+ 'flip-horizontal',
+ 'flip-vertical',
+]);
-export function MainMenu(props: { items: (ZoomMenuItem | 'divider')[] }) {
- const [open, setOpen] = createSignal(false);
- let root!: HTMLDivElement;
- const onDocumentDown = (e: PointerEvent) => {
- if (!root.contains(e.target as Node)) setOpen(false);
+export function MainMenu(props: {
+ canEdit: boolean;
+ hasSelection: boolean;
+ canUndo: boolean;
+ canRedo: boolean;
+ zoomItems: (EditorMenuItem | 'divider')[];
+ onRun: (action: ViewerAction) => void;
+ onExportFramesPdf: () => void;
+}) {
+ const menuAction = (id: ViewerAction, label?: string): EditorMenuItem => {
+ const action = paletteActions('').find((item) => item.id === id);
+ const keys = !IS_MAC && action?.otherKeys ? action.otherKeys : action?.keys;
+ return {
+ label: label ?? action?.label ?? id,
+ shortcut: keys
+ ?.map((key) => (key === 'mod' ? (IS_MAC ? '⌘' : 'Ctrl') : key))
+ .join(IS_MAC ? '' : '+'),
+ disabled:
+ (EDIT_ACTIONS.has(id) && !props.canEdit) ||
+ (SELECTION_COMMANDS.has(id) && !props.hasSelection) ||
+ (id === 'undo' && !props.canUndo) ||
+ (id === 'redo' && !props.canRedo),
+ onSelect: () => props.onRun(id),
+ testId: id === 'undo' || id === 'redo' ? `fig-${id}` : `fig-main-${id}`,
+ };
};
- document.addEventListener('pointerdown', onDocumentDown);
- onCleanup(() => document.removeEventListener('pointerdown', onDocumentDown));
+
return (
- <div ref={root} class="relative">
- <Button
- variant="ghost"
- size="icon-md"
- label="Main menu"
- tooltip="Main menu"
- aria-expanded={open()}
- data-testid="fig-main-menu"
- onClick={() => setOpen((o) => !o)}
- >
- <List />
- </Button>
- <Show when={open()}>
- <div class="absolute top-full left-0 z-50 mt-1 w-60 rounded-lg border border-edge-muted bg-menu p-1 text-xs shadow-lg">
- <For each={props.items}>
- {(item) =>
- item === 'divider' ? (
- <div class="my-1 h-px bg-edge-muted" />
- ) : (
- <button
- type="button"
- data-testid={item.testId}
- class="flex h-7 w-full items-center gap-2 rounded-md px-2 text-left text-ink hover:bg-hover"
- onClick={() => {
- item.onSelect();
- setOpen(false);
- }}
- >
- <span class="w-3 text-accent">{item.checked ? '✓' : ''}</span>
- <span class="flex-1">{item.label}</span>
- <Show when={item.shortcut}>
- <span class="text-ink-muted">{item.shortcut}</span>
- </Show>
- </button>
- )
- }
- </For>
- </div>
- </Show>
- </div>
+ <EditorMenu
+ label="Main menu"
+ testId="fig-main-menu"
+ items={[
+ {
+ label: 'Actions…',
+ shortcut: IS_MAC ? '⌘P' : 'Ctrl+P',
+ onSelect: () => props.onRun('open-actions'),
+ },
+ 'divider',
+ {
+ label: 'File',
+ testId: 'fig-main-file',
+ items: [
+ menuAction('place-image', 'Place image…'),
+ 'divider',
+ {
+ label: 'Export frames to PDF…',
+ onSelect: () => props.onExportFramesPdf(),
+ testId: 'fig-menu-export-frames-pdf',
+ },
+ {
+ ...menuAction('export', 'Export selection…'),
+ testId: 'fig-menu-export-selection',
+ },
+ ],
+ },
+ {
+ label: 'Edit',
+ testId: 'fig-main-edit',
+ items: [
+ menuAction('undo'),
+ menuAction('redo'),
+ 'divider',
+ menuAction('copy'),
+ menuAction('cut'),
+ {
+ ...menuAction('paste', 'Paste'),
+ shortcut: IS_MAC ? '⌘V' : 'Ctrl+V',
+ },
+ menuAction('paste-replace'),
+ 'divider',
+ menuAction('duplicate'),
+ menuAction('delete'),
+ 'divider',
+ menuAction('select-all'),
+ menuAction('find'),
+ ],
+ },
+ {
+ label: 'View',
+ testId: 'fig-main-view',
+ items: [
+ ...props.zoomItems,
+ 'divider',
+ menuAction('toggle-layers'),
+ menuAction('toggle-assets'),
+ menuAction('toggle-design'),
+ ],
+ },
+ {
+ label: 'Object',
+ testId: 'fig-main-object',
+ items: [
+ menuAction('group', 'Group selection'),
+ menuAction('ungroup'),
+ menuAction('frame-selection'),
+ 'divider',
+ menuAction('add-auto-layout'),
+ menuAction('remove-auto-layout'),
+ 'divider',
+ menuAction('create-component'),
+ menuAction('detach-instance'),
+ 'divider',
+ menuAction('toggle-visible', 'Show/hide selection'),
+ menuAction('toggle-locked', 'Lock/unlock selection'),
+ menuAction('rename'),
+ ],
+ },
+ {
+ label: 'Arrange',
+ testId: 'fig-main-arrange',
+ items: [
+ menuAction('bring-to-front'),
+ menuAction('bring-forward'),
+ menuAction('send-backward'),
+ menuAction('send-to-back'),
+ 'divider',
+ menuAction('align-left'),
+ menuAction('align-center'),
+ menuAction('align-right'),
+ menuAction('align-top'),
+ menuAction('align-middle'),
+ menuAction('align-bottom'),
+ 'divider',
+ menuAction('distribute-horizontal'),
+ menuAction('distribute-vertical'),
+ 'divider',
+ menuAction('flip-horizontal'),
+ menuAction('flip-vertical'),
+ ],
+ },
+ 'divider',
+ menuAction('show-shortcuts'),
+ ]}
+ >
+ <List class="size-4" />
+ </EditorMenu>
);
}
diff --git a/apps/web/src/features/block-fig/components/mixed-fields.tsx b/apps/web/src/features/block-fig/components/mixed-fields.tsx
index 70ac6acc59..b0b4679c53 100644
--- a/apps/web/src/features/block-fig/components/mixed-fields.tsx
+++ b/apps/web/src/features/block-fig/components/mixed-fields.tsx
@@ -6,11 +6,13 @@
import type { PaintInfo } from '@core/fig-engine/types';
import { type JSX, Show } from 'solid-js';
+import type { Alignment } from '../core/align';
import { formatMeasure } from '../core/measure';
import { MIXED, type Mixed, type MixedInfo } from '../core/mixed';
import type { PaintEdit } from '../core/paint';
import type { Patch } from '../primitives/create-fig-editor';
import { NumberField } from './design-fields';
+import { AlignRow } from './geometry-sections';
import { PaintList } from './paint-controls';
import { Section } from './panel-section';
@@ -71,6 +73,7 @@ function MixedPaints(props: {
export function MixedFields(props: {
mixed: MixedInfo;
+ onAlign?: (how: Alignment) => void;
/** Edits all the selected layers; absent when read-only. */
onPatch?: (patch: Patch, live: boolean) => void;
swatches?: readonly string[];
@@ -82,9 +85,6 @@ export function MixedFields(props: {
v === MIXED ? 'Mixed' : v === undefined ? '' : formatMeasure(v);
return (
<div data-testid="fig-mixed">
- <div class="border-edge-muted border-b px-3 py-3">
- <div class="font-semibold text-sm">{m().count} layers selected</div>
- </div>
<Show
when={props.onPatch}
fallback={
@@ -101,8 +101,17 @@ export function MixedFields(props: {
{(patch) => (
<>
<Show when={!m().inInstance}>
- <Section title="Layout">
- <div class="grid grid-cols-2 gap-1.5">
+ <Section title="Position" testId="fig-position-section">
+ <Show when={props.onAlign}>
+ {(align) => (
+ <>
+ <span class="text-ink-muted text-[11px]">Alignment</span>
+ <AlignRow onAlign={align()} />
+ </>
+ )}
+ </Show>
+ <span class="mt-1 text-ink-muted text-[11px]">Position</span>
+ <div class="grid grid-cols-2 gap-2">
<NumberField
label="X"
value={value(m().x)}
@@ -117,6 +126,21 @@ export function MixedFields(props: {
testId="fig-field-y"
onChange={(y, live) => patch()({ y }, live)}
/>
+ <span class="col-span-2 text-ink-muted text-[11px]">
+ Rotation
+ </span>
+ <NumberField
+ label="↻"
+ value={value(m().rotation)}
+ mixed={m().rotation === MIXED}
+ testId="fig-field-rotation"
+ onChange={(rotation, live) => patch()({ rotation }, live)}
+ />
+ </div>
+ </Section>
+ <Section title="Layout" testId="fig-auto-layout-section">
+ <span class="text-ink-muted text-[11px]">Dimensions</span>
+ <div class="grid grid-cols-2 gap-2">
<NumberField
label="W"
value={value(m().width)}
@@ -133,30 +157,17 @@ export function MixedFields(props: {
testId="fig-field-h"
onChange={(height, live) => patch()({ height }, live)}
/>
- <NumberField
- label="↻"
- value={value(m().rotation)}
- mixed={m().rotation === MIXED}
- testId="fig-field-rotation"
- onChange={(rotation, live) => patch()({ rotation }, live)}
- />
- <Show when={m().radius !== undefined}>
- <NumberField
- label="◜"
- value={value(m().radius ?? 0)}
- mixed={m().radius === MIXED}
- min={0}
- testId="fig-field-radius"
- onChange={(cornerRadius, live) =>
- patch()({ cornerRadius }, live)
- }
- />
- </Show>
</div>
</Section>
</Show>
<Section title="Appearance">
<div class="grid grid-cols-2 gap-1.5">
+ <span class="text-ink-muted text-[11px]">Opacity</span>
+ <span class="text-ink-muted text-[11px]">
+ {!m().inInstance && m().radius !== undefined
+ ? 'Corner radius'
+ : ''}
+ </span>
<NumberField
label="◐"
value={value(m().opacity)}
@@ -167,6 +178,18 @@ export function MixedFields(props: {
testId="fig-field-opacity"
onChange={(opacity, live) => patch()({ opacity }, live)}
/>
+ <Show when={!m().inInstance && m().radius !== undefined}>
+ <NumberField
+ label="◜"
+ value={value(m().radius ?? 0)}
+ mixed={m().radius === MIXED}
+ min={0}
+ testId="fig-field-radius"
+ onChange={(cornerRadius, live) =>
+ patch()({ cornerRadius }, live)
+ }
+ />
+ </Show>
</div>
</Section>
<MixedPaints
@@ -188,7 +211,7 @@ export function MixedFields(props: {
onPatch={patch()}
/>
<Show when={m().strokeWeight !== undefined}>
- <div class="-mt-2 grid grid-cols-2 gap-1.5 border-edge-muted border-b px-3 pb-3">
+ <div class="-mt-2 grid grid-cols-2 gap-1.5 border-edge-frame border-b px-3 pb-3">
<NumberField
label="≡"
value={value(m().strokeWeight ?? 0)}
diff --git a/apps/web/src/features/block-fig/components/overlay.ts b/apps/web/src/features/block-fig/components/overlay.ts
index 34ac38c5d1..9660447139 100644
--- a/apps/web/src/features/block-fig/components/overlay.ts
+++ b/apps/web/src/features/block-fig/components/overlay.ts
@@ -76,6 +76,11 @@ export interface VectorOverlay {
const LABEL_TYPES = new Set(['FRAME', 'SYMBOL', 'SECTION', 'INSTANCE']);
+export interface FrameLabel {
+ frame: FrameRow;
+ rect: Rect;
+}
+
function pill(
ctx: CanvasRenderingContext2D,
text: string,
@@ -120,6 +125,7 @@ function drawPixelGrid(ctx: CanvasRenderingContext2D, m: OverlayModel) {
}
function drawFrameLabels(ctx: CanvasRenderingContext2D, m: OverlayModel) {
+ const labels: FrameLabel[] = [];
ctx.font = '11px Inter, system-ui, sans-serif';
ctx.textAlign = 'left';
ctx.textBaseline = 'bottom';
@@ -144,7 +150,17 @@ function drawFrameLabels(ctx: CanvasRenderingContext2D, m: OverlayModel) {
name = `${name.slice(0, -2)}…`;
}
ctx.fillText(name, Math.round(p.x), Math.round(p.y - 4));
+ labels.push({
+ frame: f,
+ rect: {
+ x: Math.round(p.x),
+ y: Math.round(p.y - 20),
+ w: ctx.measureText(name).width,
+ h: 18,
+ },
+ });
}
+ return labels;
}
function drawSelection(ctx: CanvasRenderingContext2D, m: OverlayModel) {
@@ -407,7 +423,7 @@ export function drawOverlay(ctx: CanvasRenderingContext2D, m: OverlayModel) {
ctx.setTransform(m.dpr, 0, 0, m.dpr, 0, 0);
drawPixelGrid(ctx, m);
if (m.layoutAids) drawLayoutGrids(ctx, m, m.layoutAids);
- drawFrameLabels(ctx, m);
+ const labels = drawFrameLabels(ctx, m);
drawHover(ctx, m);
if (m.layoutAids) drawSpacing(ctx, m, m.layoutAids);
drawSelection(ctx, m);
@@ -418,4 +434,5 @@ export function drawOverlay(ctx: CanvasRenderingContext2D, m: OverlayModel) {
drawPeers(ctx, m);
if (m.layoutAids?.guides) drawRulerGuides(ctx, m, m.layoutAids);
drawRulers(ctx, m);
+ return labels;
}
diff --git a/apps/web/src/features/block-fig/components/paint-controls.tsx b/apps/web/src/features/block-fig/components/paint-controls.tsx
index 3d10e9fe8b..11c1a61efd 100644
--- a/apps/web/src/features/block-fig/components/paint-controls.tsx
+++ b/apps/web/src/features/block-fig/components/paint-controls.tsx
@@ -31,6 +31,7 @@ import {
} from '../core/paint';
import { ColorPicker } from './color-picker';
import { NumberField, TextField } from './design-fields';
+import { InspectorSelect } from './inspector-select';
import { SwatchPopover } from './swatch-popover';
const title = (s: string) =>
@@ -209,33 +210,23 @@ function PaintEditor(props: {
return (
<div class="flex flex-col gap-3" data-testid="fig-paint-popover">
- <select
- aria-label="Paint type"
- data-testid="fig-paint-type"
- class="w-full rounded-md bg-inset px-2 py-1 text-ink text-xs outline-none"
+ <InspectorSelect
+ label="Paint type"
+ testId="fig-paint-type"
value={p().type}
- onChange={(e) => {
- const type = e.currentTarget.value as PaintType;
- if (type === 'IMAGE') {
+ options={PAINT_TYPES.map((type) => ({
+ ...type,
+ disabled: type.value === 'IMAGE' && !props.onAddImage,
+ }))}
+ onChange={(value) => {
+ if (value === 'IMAGE') {
fileInput.click();
- e.currentTarget.value = p().type;
return;
}
setActive(0);
- props.onEdit({ type }, false);
+ props.onEdit({ type: value as PaintType }, false);
}}
- >
- <For each={PAINT_TYPES}>
- {(t) => (
- <option
- value={t.value}
- disabled={t.value === 'IMAGE' && !props.onAddImage}
- >
- {t.label}
- </option>
- )}
- </For>
- </select>
+ />
<input
ref={fileInput}
type="file"
@@ -323,7 +314,7 @@ export function PaintList(props: {
const testId = () => `fig-${props.kind}-${index()}`;
return (
<div
- class="group relative flex items-center gap-1.5 rounded-md bg-inset py-1 pr-1.5 pl-0.5"
+ class="group relative flex h-6 items-center gap-2"
data-testid={testId()}
classList={{ 'opacity-60': !paint().visible }}
onDragOver={(e) => {
@@ -359,7 +350,7 @@ export function PaintList(props: {
<span
draggable={props.paints.length > 1}
aria-hidden="true"
- class="flex w-3 shrink-0 cursor-grab justify-center text-ink-muted opacity-0 group-hover:opacity-100"
+ class="absolute -left-3 flex w-3 shrink-0 cursor-grab justify-center text-ink-muted opacity-0 group-hover:opacity-100"
classList={{ invisible: props.paints.length < 2 }}
onDragStart={(e) => {
setDragged(index());
@@ -373,67 +364,69 @@ export function PaintList(props: {
>
<DotsSixVertical class="size-3" />
</span>
- <SwatchPopover
- swatch={paintSwatch(paint())}
- label={`Edit ${props.kind}`}
- testId={`${testId()}-swatch`}
- onOpenChange={(open) => {
- if (open) props.onPickerOpen?.();
- }}
- >
- <PaintEditor
- paint={paint()}
- swatches={props.swatches}
- onAddImage={props.onAddImage}
- onEdit={(edit, live) =>
- change(index(), (spec) => ({ ...spec, ...edit }), live)
- }
- />
- </SwatchPopover>
- <Show
- when={paint().type === 'SOLID'}
- fallback={
- <span class="min-w-0 flex-1 truncate text-ink">
- {paintLabel(paint())}
- </span>
- }
- >
- <TextField
- value={paint().color ?? ''}
- class="font-mono"
- testId={`${testId()}-hex`}
- onChange={(v) => {
- const hex = normalizeHex(v);
- if (!hex) return;
- // Six digits keep the paint's own alpha; eight set it.
- change(index(), (spec, p) => ({
- ...spec,
- color:
- hex.length === 6 && (p.alpha ?? 1) < 1
- ? rgbaToHex({ ...hexToRgba(hex), a: p.alpha ?? 1 })
- : hex,
- }));
+ <div class="flex h-6 min-w-0 flex-1 items-center gap-1 rounded-md bg-inset pl-1">
+ <SwatchPopover
+ swatch={paintSwatch(paint())}
+ label={`Edit ${props.kind}`}
+ testId={`${testId()}-swatch`}
+ onOpenChange={(open) => {
+ if (open) props.onPickerOpen?.();
}}
- />
- </Show>
- <div class="w-14 shrink-0">
- <NumberField
- label=""
- value={paint().opacity}
- percent
- min={0}
- max={1}
- testId={`${testId()}-opacity`}
- onChange={(opacity, live) =>
- change(index(), (spec) => ({ ...spec, opacity }), live)
+ >
+ <PaintEditor
+ paint={paint()}
+ swatches={props.swatches}
+ onAddImage={props.onAddImage}
+ onEdit={(edit, live) =>
+ change(index(), (spec) => ({ ...spec, ...edit }), live)
+ }
+ />
+ </SwatchPopover>
+ <Show
+ when={paint().type === 'SOLID'}
+ fallback={
+ <span class="min-w-0 flex-1 truncate text-ink">
+ {paintLabel(paint())}
+ </span>
}
- />
+ >
+ <TextField
+ value={paint().color ?? ''}
+ class="font-sans"
+ testId={`${testId()}-hex`}
+ onChange={(v) => {
+ const hex = normalizeHex(v);
+ if (!hex) return;
+ // Six digits keep the paint's own alpha; eight set it.
+ change(index(), (spec, p) => ({
+ ...spec,
+ color:
+ hex.length === 6 && (p.alpha ?? 1) < 1
+ ? rgbaToHex({ ...hexToRgba(hex), a: p.alpha ?? 1 })
+ : hex,
+ }));
+ }}
+ />
+ </Show>
+ <div class="w-14 shrink-0 border-l border-edge-frame">
+ <NumberField
+ label=""
+ value={paint().opacity}
+ percent
+ min={0}
+ max={1}
+ testId={`${testId()}-opacity`}
+ onChange={(opacity, live) =>
+ change(index(), (spec) => ({ ...spec, opacity }), live)
+ }
+ />
+ </div>
</div>
<button
type="button"
aria-label={paint().visible ? 'Hide' : 'Show'}
data-testid={`${testId()}-visibility`}
- class="rounded p-0.5 text-ink-muted hover:text-ink"
+ class="flex size-6 shrink-0 items-center justify-center rounded text-ink-muted hover:bg-hover hover:text-ink"
onClick={() =>
change(index(), (spec, p) => ({ ...spec, visible: !p.visible }))
}
@@ -449,7 +442,7 @@ export function PaintList(props: {
type="button"
aria-label="Remove"
data-testid={`${testId()}-remove`}
- class="rounded p-0.5 text-ink-muted hover:text-ink"
+ class="flex size-6 shrink-0 items-center justify-center rounded text-ink-muted hover:bg-hover hover:text-ink"
onClick={() => change(index(), () => null)}
>
<Minus class="size-3.5" />
diff --git a/apps/web/src/features/block-fig/components/panel-section.tsx b/apps/web/src/features/block-fig/components/panel-section.tsx
index 03a9949ada..41ce0b758c 100644
--- a/apps/web/src/features/block-fig/components/panel-section.tsx
+++ b/apps/web/src/features/block-fig/components/panel-section.tsx
@@ -9,6 +9,7 @@ export function Section(props: {
children: JSX.Element;
/** A "+" action in the header (add a fill, say). */
onAdd?: () => void;
+ addLabel?: string;
/** A "−" action in the header (remove auto layout, say). */
onRemove?: () => void;
/** More header controls, before "+" (a style picker, say). */
@@ -17,18 +18,18 @@ export function Section(props: {
}) {
return (
<section
- class="border-edge-muted border-b px-3 py-3"
+ class="fig-inspector-section border-edge-frame border-b px-4 py-2"
data-testid={props.testId}
>
- <div class="mb-2 flex items-center justify-between gap-1">
- <h3 class="mr-auto font-semibold text-ink text-xs">{props.title}</h3>
+ <div class="flex h-6 items-center justify-between gap-1">
+ <h3 class="mr-auto font-medium text-ink text-xs">{props.title}</h3>
{props.actions}
<Show when={props.onAdd}>
{(add) => (
<button
type="button"
- aria-label={`Add ${props.title.toLowerCase()}`}
- class="rounded p-0.5 text-ink-muted hover:bg-hover hover:text-ink"
+ aria-label={props.addLabel ?? `Add ${props.title.toLowerCase()}`}
+ class="flex size-6 shrink-0 items-center justify-center rounded text-ink-muted hover:bg-hover hover:text-ink"
onClick={() => add()()}
>
<Plus class="size-3.5" />
@@ -40,7 +41,7 @@ export function Section(props: {
<button
type="button"
aria-label={`Remove ${props.title.toLowerCase()}`}
- class="rounded p-0.5 text-ink-muted hover:bg-hover hover:text-ink"
+ class="flex size-6 shrink-0 items-center justify-center rounded text-ink-muted hover:bg-hover hover:text-ink"
onClick={() => remove()()}
>
<Minus class="size-3.5" />
@@ -48,7 +49,9 @@ export function Section(props: {
)}
</Show>
</div>
- <div class="flex flex-col gap-1.5">{props.children}</div>
+ <div class="fig-inspector-section-body flex flex-col gap-2">
+ {props.children}
+ </div>
</section>
);
}
diff --git a/apps/web/src/features/block-fig/components/panel-toggle.tsx b/apps/web/src/features/block-fig/components/panel-toggle.tsx
new file mode 100644
index 0000000000..d0d56bc6d4
--- /dev/null
+++ b/apps/web/src/features/block-fig/components/panel-toggle.tsx
@@ -0,0 +1,26 @@
+import SidebarSimple from '@phosphor/sidebar-simple.svg';
+
+export function PanelToggle(props: {
+ side: 'left' | 'right';
+ open: boolean;
+ onClick: () => void;
+}) {
+ const label = () =>
+ `${props.open ? 'Hide' : 'Show'} ${props.side === 'left' ? 'layers' : 'properties'}`;
+ return (
+ <button
+ type="button"
+ aria-label={label()}
+ title={label()}
+ data-testid={`fig-toggle-${props.side}`}
+ class="flex size-7 shrink-0 items-center justify-center rounded text-ink-muted hover:bg-hover hover:text-ink focus-visible:ring-2 focus-visible:ring-accent"
+ onPointerDown={(e) => e.stopPropagation()}
+ onClick={props.onClick}
+ >
+ <SidebarSimple
+ class="size-4"
+ classList={{ '-scale-x-100': props.side === 'right' }}
+ />
+ </button>
+ );
+}
diff --git a/apps/web/src/features/block-fig/components/prototype-panel.tsx b/apps/web/src/features/block-fig/components/prototype-panel.tsx
index ca9afc7710..97f1a5c34d 100644
--- a/apps/web/src/features/block-fig/components/prototype-panel.tsx
+++ b/apps/web/src/features/block-fig/components/prototype-panel.tsx
@@ -1,3 +1,4 @@
+import { InspectorSelect } from './inspector-select';
/**
* The Prototype tab: the page's flows, the selected frame's flow starting
* point, and the selected layer's interactions. Editors add, change, and
@@ -12,10 +13,22 @@ import type {
PrototypeInfo,
PrototypeInteraction,
} from '@core/fig-engine/prototype-types';
+import { Popover } from '@kobalte/core/popover';
+import ArrowRight from '@phosphor/arrow-right.svg';
+import Minus from '@phosphor/minus.svg';
import Play from '@phosphor/play.svg';
import Plus from '@phosphor/plus.svg';
import Trash from '@phosphor/trash.svg';
-import { createMemo, For, Show } from 'solid-js';
+import X from '@phosphor/x.svg';
+import {
+ createEffect,
+ createMemo,
+ createSignal,
+ For,
+ Index,
+ on,
+ Show,
+} from 'solid-js';
import {
type ActionKind,
actionKind,
@@ -45,7 +58,6 @@ const label = (value: string) =>
const control =
'min-w-0 rounded-md border border-edge-muted bg-input px-1.5 py-1 text-ink text-xs';
-const select = `w-full ${control}`;
export function PrototypePanel(props: {
info: PrototypeInfo | undefined;
@@ -60,6 +72,10 @@ export function PrototypePanel(props: {
onFlowStart?: (frameId: string, name: string | null) => void;
onPresent: (frameId?: string) => void;
}) {
+ const [openInteraction, setOpenInteraction] = createSignal<number>();
+ // Refreshed node metadata is still the same selection; keep its editor open.
+ const selectedId = createMemo(() => props.selected?.id);
+ createEffect(on(selectedId, () => setOpenInteraction(undefined)));
const frames = () => props.info?.frames ?? [];
const frameName = (id: string | null | undefined) =>
frames().find((f) => f.id === id)?.name ?? 'Unknown';
@@ -126,7 +142,7 @@ export function PrototypePanel(props: {
>
<Show when={selectedFrame()}>
{(frame) => (
- <section class="flex flex-col gap-2 border-edge-muted border-b px-3 py-3">
+ <section class="flex flex-col gap-2 border-edge-frame border-b px-3 py-3">
<div class="flex items-center">
<span class="font-semibold">Flow starting point</span>
<Show when={props.onFlowStart && !flowAt(frame().id)}>
@@ -154,7 +170,7 @@ export function PrototypePanel(props: {
fallback={<span class="flex-1">{flow().name}</span>}
>
<input
- class={select}
+ class={`w-full ${control}`}
value={flow().name}
aria-label="Flow name"
data-testid="fig-flow-name"
@@ -184,7 +200,7 @@ export function PrototypePanel(props: {
)}
</Show>
<Show when={props.selected}>
- <section class="flex flex-col gap-2 border-edge-muted border-b px-3 py-3">
+ <section class="flex flex-col gap-2 border-edge-frame border-b px-3 py-3">
<div class="flex items-center">
<span class="font-semibold">Interactions</span>
<Show when={editable() && frames().length > 0}>
@@ -196,6 +212,7 @@ export function PrototypePanel(props: {
onClick={() => {
const id = props.selected?.id;
if (!id) return;
+ setOpenInteraction(interactions().length);
props.onInteractions?.(id, interactions().length, {
kind: 'navigate',
destination: otherFrame()?.id,
@@ -216,132 +233,197 @@ export function PrototypePanel(props: {
</span>
}
>
- <For each={interactions()}>
- {(i, index) => {
- const a = () => i.actions[0];
+ <Index each={interactions()}>
+ {(interaction, index) => {
+ const i = interaction;
+ const a = () => i().actions[0];
const kind = () => actionKind(a());
const editsThis = () =>
- editable() && i.trigger === 'ON_CLICK' && !!kind();
+ editable() && i().trigger === 'ON_CLICK' && !!kind();
return (
<div
- class="flex flex-col gap-1.5 rounded-md bg-inset p-2"
+ class="flex items-center gap-1"
data-testid="fig-proto-interaction"
>
- <div class="flex items-center gap-1">
- <span class="font-medium">
- {TRIGGERS[i.trigger] ?? label(i.trigger)}
- </span>
- <Show when={editable()}>
- <button
- type="button"
- class="ml-auto rounded-md p-1 text-ink-muted hover:bg-hover hover:text-ink"
- aria-label="Remove interaction"
- data-testid="fig-proto-remove"
- onClick={() => {
- const id = props.selected?.id;
- if (id) props.onInteractions?.(id, index(), null);
- }}
- >
- <Trash class="size-3.5" />
- </button>
- </Show>
- </div>
- <Show
- when={editsThis()}
- fallback={
- <span
- class="text-ink-muted"
- data-testid="fig-proto-summary"
- >
- {summary(a())}
- </span>
+ <Popover
+ placement="left-start"
+ gutter={24}
+ open={openInteraction() === index}
+ onOpenChange={(open) =>
+ setOpenInteraction(open ? index : undefined)
}
>
- <select
- class={select}
- aria-label="Action"
- data-testid="fig-proto-action"
- value={kind()}
- onChange={(e) =>
- edit(index(), i, {
- kind: e.currentTarget.value as ActionKind,
- })
- }
+ <Popover.Trigger
+ class="flex h-8 min-w-0 flex-1 items-center gap-2 rounded-md bg-inset px-2 text-left hover:bg-hover focus-visible:ring-1 focus-visible:ring-accent"
+ data-testid="fig-proto-open"
+ aria-label={`${editsThis() ? 'Edit' : 'View'} interaction: ${TRIGGERS[i().trigger] ?? label(i().trigger)}, ${summary(a())}`}
>
- <option value="navigate">Navigate to</option>
- <option value="overlay">Open overlay</option>
- <option value="back">Back</option>
- </select>
- <Show when={kind() !== 'back'}>
- <select
- class={select}
- aria-label="Destination"
- data-testid="fig-proto-destination"
- value={a()?.destination ?? ''}
- onChange={(e) =>
- edit(index(), i, {
- destination: e.currentTarget.value,
- })
- }
- >
- <For each={frames()}>
- {(f) => <option value={f.id}>{f.name}</option>}
- </For>
- </select>
- </Show>
- <div class="flex gap-1">
- <select
- class={select}
- aria-label="Animation"
- data-testid="fig-proto-transition"
- value={a()?.transition ?? 'INSTANT_TRANSITION'}
- onChange={(e) =>
- edit(index(), i, {
- transition: e.currentTarget.value,
- })
- }
+ <span class="shrink-0">
+ {TRIGGERS[i().trigger] ?? label(i().trigger)}
+ </span>
+ <ArrowRight class="size-3 shrink-0 text-ink-muted" />
+ <span class="truncate text-ink-muted">
+ {summary(a())}
+ </span>
+ </Popover.Trigger>
+ <Popover.Portal>
+ <Popover.Content
+ class="fig-editor-theme z-modal w-64 rounded-xl border border-edge-muted bg-menu p-3 text-ink text-xs shadow-xl outline-none"
+ data-testid="fig-proto-settings"
+ onKeyDown={(e) => {
+ if (!e.metaKey && !e.ctrlKey) e.stopPropagation();
+ }}
+ onPointerDown={(e) => e.stopPropagation()}
>
- <Show
- when={TRANSITIONS.some(
- (t) => t.value === a()?.transition
- )}
- fallback={
- <option value={a()?.transition}>
- {label(a()?.transition ?? '')}
- </option>
- }
- >
- {null}
- </Show>
- <For each={TRANSITIONS}>
- {(t) => <option value={t.value}>{t.label}</option>}
- </For>
- </select>
- <Show when={a()?.transition !== 'INSTANT_TRANSITION'}>
- <input
- type="number"
- min="0"
- max="10000"
- step="50"
- class={`${control} w-16 shrink-0`}
- aria-label="Duration (ms)"
- title="Duration (ms)"
- data-testid="fig-proto-duration"
- value={Math.round((a()?.duration ?? 0.3) * 1000)}
- onKeyDown={(e) => e.stopPropagation()}
- onChange={(e) => {
- const ms = Number(e.currentTarget.value);
- if (Number.isFinite(ms) && ms >= 0)
- edit(index(), i, { duration: ms / 1000 });
- }}
- />
- </Show>
- </div>
+ <div class="mb-3 flex items-center justify-between">
+ <Popover.Title class="font-medium">
+ Interaction
+ </Popover.Title>
+ <Popover.CloseButton
+ class="rounded p-1 hover:bg-hover"
+ aria-label="Close interaction settings"
+ >
+ <X class="size-3.5" />
+ </Popover.CloseButton>
+ </div>
+ <div class="flex flex-col gap-2">
+ <span class="text-ink-muted">Trigger</span>
+ <div class="rounded-md bg-inset px-2 py-1.5">
+ {TRIGGERS[i().trigger] ?? label(i().trigger)}
+ </div>
+ <span class="mt-1 text-ink-muted">Action</span>
+ <Show
+ when={editsThis()}
+ fallback={
+ <span
+ class="text-ink-muted"
+ data-testid="fig-proto-summary"
+ >
+ {summary(a())}
+ </span>
+ }
+ >
+ <InspectorSelect
+ label="Action"
+ testId="fig-proto-action"
+ value={kind() ?? 'navigate'}
+ options={[
+ { value: 'navigate', label: 'Navigate to' },
+ { value: 'overlay', label: 'Open overlay' },
+ { value: 'back', label: 'Back' },
+ ]}
+ onChange={(value) =>
+ edit(index, i(), {
+ kind: value as ActionKind,
+ })
+ }
+ />
+ <Show when={kind() !== 'back'}>
+ <span class="mt-1 text-ink-muted">
+ Destination
+ </span>
+ <InspectorSelect
+ label="Destination"
+ testId="fig-proto-destination"
+ value={a()?.destination ?? ''}
+ options={frames().map((f) => ({
+ value: f.id,
+ label: f.name,
+ }))}
+ onChange={(destination) =>
+ edit(index, i(), { destination })
+ }
+ />
+ </Show>
+ <div class="mt-1 flex gap-1 text-ink-muted">
+ <span class="flex-1">Animation</span>
+ <Show
+ when={
+ a()?.transition !== 'INSTANT_TRANSITION'
+ }
+ >
+ <span class="w-20">Duration (ms)</span>
+ </Show>
+ </div>
+ <div class="flex gap-1">
+ <InspectorSelect
+ label="Animation"
+ testId="fig-proto-transition"
+ value={
+ a()?.transition ?? 'INSTANT_TRANSITION'
+ }
+ options={
+ TRANSITIONS.some(
+ (t) =>
+ t.value ===
+ (a()?.transition ??
+ 'INSTANT_TRANSITION')
+ )
+ ? TRANSITIONS
+ : [
+ {
+ value: a()?.transition ?? '',
+ label: label(a()?.transition ?? ''),
+ },
+ ...TRANSITIONS,
+ ]
+ }
+ onChange={(transition) =>
+ edit(index, i(), { transition })
+ }
+ />
+ <Show
+ when={
+ a()?.transition !== 'INSTANT_TRANSITION'
+ }
+ >
+ <input
+ type="number"
+ min="0"
+ max="10000"
+ step="50"
+ class={`${control} w-20 shrink-0`}
+ aria-label="Duration (ms)"
+ title="Duration (ms)"
+ data-testid="fig-proto-duration"
+ value={Math.round(
+ (a()?.duration ?? 0.3) * 1000
+ )}
+ onKeyDown={(e) => e.stopPropagation()}
+ onChange={(e) => {
+ const ms = Number(e.currentTarget.value);
+ if (Number.isFinite(ms) && ms >= 0)
+ edit(index, i(), {
+ duration: ms / 1000,
+ });
+ }}
+ />
+ </Show>
+ </div>
+ </Show>
+ </div>
+ </Popover.Content>
+ </Popover.Portal>
+ </Popover>
+ <Show when={editable()}>
+ <button
+ type="button"
+ class="rounded-md p-1 text-ink-muted hover:bg-hover hover:text-ink"
+ aria-label="Remove interaction"
+ data-testid="fig-proto-remove"
+ onClick={() => {
+ const id = props.selected?.id;
+ setOpenInteraction(undefined);
+ if (id) props.onInteractions?.(id, index, null);
+ }}
+ >
+ <Minus class="size-3.5" />
+ </button>
</Show>
</div>
);
}}
- </For>
+ </Index>
</Show>
</section>
</Show>
@@ -351,7 +433,11 @@ export function PrototypePanel(props: {
when={flows().length > 0}
fallback={
<span class="text-ink-muted">
- Select a top-level frame to add a starting point.
+ {!props.onFlowStart
+ ? 'No flow starting points.'
+ : selectedFrame()
+ ? 'Add a flow starting point above to present this frame.'
+ : 'Select a top-level frame to add a starting point.'}
</span>
}
>
diff --git a/apps/web/src/features/block-fig/components/publish-dialog.tsx b/apps/web/src/features/block-fig/components/publish-dialog.tsx
index a199f432db..bcd3c512cc 100644
--- a/apps/web/src/features/block-fig/components/publish-dialog.tsx
+++ b/apps/web/src/features/block-fig/components/publish-dialog.tsx
@@ -51,7 +51,7 @@ export function PublishDialog(props: {
<Dialog
open
onOpenChange={(open) => !open && props.onClose()}
- class="w-120"
+ class="fig-editor-theme w-120"
>
<Panel depth={2} class="rounded-xl *:max-h-[80vh]">
<Panel.Body scroll>
diff --git a/apps/web/src/features/block-fig/components/resizable-panel.tsx b/apps/web/src/features/block-fig/components/resizable-panel.tsx
new file mode 100644
index 0000000000..207dd02c00
--- /dev/null
+++ b/apps/web/src/features/block-fig/components/resizable-panel.tsx
@@ -0,0 +1,80 @@
+/** A panel edge that resizes with the pointer or arrow keys. */
+import type { JSX } from 'solid-js';
+
+export function ResizablePanel(props: {
+ side: 'left' | 'right';
+ label: string;
+ width: number;
+ onResize: (width: number) => void;
+ children: JSX.Element;
+ onContextMenu?: JSX.EventHandlerUnion<HTMLElement, MouseEvent>;
+}) {
+ const min = 224;
+ const max = 420;
+ const resize = (value: number) =>
+ props.onResize(Math.min(max, Math.max(min, value)));
+ let start: { x: number; width: number } | undefined;
+ const direction = () => (props.side === 'left' ? 1 : -1);
+ return (
+ <aside
+ class="relative flex shrink-0 flex-col border-edge-frame bg-page"
+ classList={{
+ 'border-r': props.side === 'left',
+ 'border-l': props.side === 'right',
+ }}
+ style={{ width: `${props.width}px` }}
+ aria-label={props.label}
+ onContextMenu={props.onContextMenu}
+ >
+ {props.children}
+ <div
+ role="separator"
+ tabIndex={0}
+ aria-label={`Resize ${props.label.toLowerCase()}`}
+ aria-orientation="vertical"
+ aria-valuemin={min}
+ aria-valuemax={max}
+ aria-valuenow={props.width}
+ data-testid={`fig-resize-${props.side}`}
+ class="absolute inset-y-0 z-20 w-1 touch-none cursor-col-resize outline-none hover:bg-accent focus-visible:bg-accent"
+ classList={{
+ 'right-0': props.side === 'left',
+ 'left-0': props.side === 'right',
+ }}
+ onPointerDown={(event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ event.currentTarget.setPointerCapture(event.pointerId);
+ start = { x: event.clientX, width: props.width };
+ }}
+ onPointerMove={(event) => {
+ if (start)
+ resize(start.width + (event.clientX - start.x) * direction());
+ }}
+ onPointerUp={() => {
+ start = undefined;
+ }}
+ onPointerCancel={() => {
+ start = undefined;
+ }}
+ onKeyDown={(event) => {
+ if (
+ event.key !== 'ArrowLeft' &&
+ event.key !== 'ArrowRight' &&
+ event.key !== 'Home' &&
+ event.key !== 'End'
+ )
+ return;
+ event.preventDefault();
+ event.stopPropagation();
+ if (event.key === 'Home') resize(min);
+ else if (event.key === 'End') resize(max);
+ else
+ resize(
+ props.width + (event.key === 'ArrowRight' ? 8 : -8) * direction()
+ );
+ }}
+ />
+ </aside>
+ );
+}
diff --git a/apps/web/src/features/block-fig/components/review-buttons.tsx b/apps/web/src/features/block-fig/components/review-buttons.tsx
index e25c882841..eb509b7d39 100644
--- a/apps/web/src/features/block-fig/components/review-buttons.tsx
+++ b/apps/web/src/features/block-fig/components/review-buttons.tsx
@@ -8,50 +8,55 @@ import Play from '@phosphor/play.svg';
import { Button } from '@ui/components/Button';
import { Show } from 'solid-js';
-export function ReviewButtons(props: {
- mac: boolean;
+export function CommentButton(props: {
/** Absent when the design has no comments. */
comments?: { active: boolean; unread: number; onToggle: () => void };
- onPresent: () => void;
}) {
return (
- <>
- <Show when={props.comments}>
- {(c) => (
- <div class="relative">
- <Button
- variant="ghost"
- size="icon-md"
- aria-pressed={c().active}
- class={c().active ? 'bg-accent/15 text-accent' : undefined}
- label="Comment (C)"
- tooltip="Comment · C"
- data-testid="fig-tool-comment"
- onClick={() => c().onToggle()}
+ <Show when={props.comments}>
+ {(c) => (
+ <div class="relative">
+ <Button
+ variant="ghost"
+ size="icon-md"
+ aria-pressed={c().active}
+ class={
+ c().active
+ ? 'rounded-lg bg-accent text-accent-contrast'
+ : 'rounded-lg'
+ }
+ label="Comment (C)"
+ tooltip="Comment · C"
+ data-testid="fig-tool-comment"
+ onClick={() => c().onToggle()}
+ >
+ <ChatCircle />
+ </Button>
+ <Show when={c().unread > 0}>
+ <span
+ class="pointer-events-none absolute top-0.5 right-0.5 flex h-3.5 min-w-3.5 items-center justify-center rounded-full bg-accent px-0.5 font-semibold text-[9px] text-accent-contrast"
+ data-testid="fig-comments-unread"
>
- <ChatCircle />
- </Button>
- <Show when={c().unread > 0}>
- <span
- class="pointer-events-none absolute top-0.5 right-0.5 flex h-3.5 min-w-3.5 items-center justify-center rounded-full bg-accent px-0.5 font-semibold text-[9px] text-accent-contrast"
- data-testid="fig-comments-unread"
- >
- {c().unread}
- </span>
- </Show>
- </div>
- )}
- </Show>
- <Button
- variant="ghost"
- size="icon-md"
- label="Present"
- tooltip={`Present · ${props.mac ? '⌥⌘↵' : 'Ctrl+Alt+Enter'}`}
- data-testid="fig-present-button"
- onClick={() => props.onPresent()}
- >
- <Play />
- </Button>
- </>
+ {c().unread}
+ </span>
+ </Show>
+ </div>
+ )}
+ </Show>
+ );
+}
+
+export function PresentButton(props: { mac: boolean; onPresent: () => void }) {
+ return (
+ <Button
+ variant="ghost"
+ size="icon-md"
+ label="Present"
+ tooltip={`Present · ${props.mac ? '⌥⌘↵' : 'Ctrl+Alt+Enter'}`}
+ data-testid="fig-present-button"
+ onClick={() => props.onPresent()}
+ >
+ <Play />
+ </Button>
);
}
diff --git a/apps/web/src/features/block-fig/components/save-indicator.tsx b/apps/web/src/features/block-fig/components/save-indicator.tsx
new file mode 100644
index 0000000000..b28ab9bab1
--- /dev/null
+++ b/apps/web/src/features/block-fig/components/save-indicator.tsx
@@ -0,0 +1,32 @@
+import CloudArrowUp from '@phosphor/cloud-arrow-up.svg';
+import CloudCheck from '@phosphor/cloud-check.svg';
+import WarningCircle from '@phosphor/warning-circle.svg';
+import { match } from 'ts-pattern';
+import type { SaveState } from '../primitives/create-fig-editor';
+
+export function SaveIndicator(props: { state: SaveState }) {
+ const label = () =>
+ match(props.state)
+ .with('saved', () => 'All changes saved')
+ .with('unsaved', () => 'Unsaved changes')
+ .with('saving', () => 'Saving…')
+ .with('error', () => 'Save failed')
+ .exhaustive();
+ return (
+ <span
+ class="flex size-6 shrink-0 items-center justify-center text-ink-muted"
+ role="status"
+ aria-label={label()}
+ title={label()}
+ data-testid="fig-save-state"
+ data-state={props.state}
+ >
+ {match(props.state)
+ .with('saved', () => <CloudCheck class="size-3.5" />)
+ .with('error', () => <WarningCircle class="size-3.5 text-failure" />)
+ .otherwise(() => (
+ <CloudArrowUp class="size-3.5 animate-pulse" />
+ ))}
+ </span>
+ );
+}
diff --git a/apps/web/src/features/block-fig/components/style-control.tsx b/apps/web/src/features/block-fig/components/style-control.tsx
index 5e56b6f5ea..01e06e79a1 100644
--- a/apps/web/src/features/block-fig/components/style-control.tsx
+++ b/apps/web/src/features/block-fig/components/style-control.tsx
@@ -123,7 +123,7 @@ export function StyleControl(props: {
<Popover.Portal>
<Layer depth={3}>
<Popover.Content
- class="z-modal flex max-h-96 w-60 flex-col rounded-xl border border-edge-muted bg-menu p-2 text-xs shadow-xl outline-none"
+ class="fig-editor-theme z-modal flex max-h-96 w-60 flex-col rounded-xl border border-edge-muted bg-menu p-2 text-xs shadow-xl outline-none"
aria-label={`${kind()} styles`}
data-testid="fig-style-popover"
onKeyDown={(e: KeyboardEvent) => {
diff --git a/apps/web/src/features/block-fig/components/swatch-popover.tsx b/apps/web/src/features/block-fig/components/swatch-popover.tsx
index f9157c3e4e..e267547d35 100644
--- a/apps/web/src/features/block-fig/components/swatch-popover.tsx
+++ b/apps/web/src/features/block-fig/components/swatch-popover.tsx
@@ -5,6 +5,7 @@
*/
import { Popover } from '@kobalte/core/popover';
+import X from '@phosphor/x.svg';
import { Layer } from '@ui';
import type { JSX } from 'solid-js';
@@ -41,13 +42,22 @@ export function SwatchPopover(props: {
<Popover.Portal>
<Layer depth={3}>
<Popover.Content
- class="z-modal rounded-xl border border-edge-muted bg-menu p-3 shadow-xl outline-none"
+ class="fig-editor-theme z-modal rounded-xl border border-edge-muted bg-menu p-3 shadow-xl outline-none"
aria-label={props.label}
onKeyDown={(e: KeyboardEvent) => {
if (!e.metaKey && !e.ctrlKey) e.stopPropagation();
}}
onPointerDown={(e: PointerEvent) => e.stopPropagation()}
>
+ <div class="mb-3 flex items-center justify-between gap-3 text-ink text-xs">
+ <Popover.Title class="font-medium">{props.label}</Popover.Title>
+ <Popover.CloseButton
+ aria-label={`Close ${props.label.toLowerCase()}`}
+ class="flex size-6 items-center justify-center rounded hover:bg-hover"
+ >
+ <X class="size-3.5" />
+ </Popover.CloseButton>
+ </div>
{props.children}
</Popover.Content>
</Layer>
diff --git a/apps/web/src/features/block-fig/components/text-resizing.tsx b/apps/web/src/features/block-fig/components/text-resizing.tsx
new file mode 100644
index 0000000000..8d7ccb473e
--- /dev/null
+++ b/apps/web/src/features/block-fig/components/text-resizing.tsx
@@ -0,0 +1,39 @@
+/** Text box resizing belongs with its dimensions in the Layout section. */
+import type { TextInfo } from '@core/fig-engine/types';
+import ArrowsOutLineHorizontal from '@phosphor/arrows-out-line-horizontal.svg';
+import ArrowsOutLineVertical from '@phosphor/arrows-out-line-vertical.svg';
+import FrameCorners from '@phosphor/frame-corners.svg';
+import type { Patch } from '../primitives/create-fig-editor';
+import { ChoiceRow } from './design-fields';
+
+const RESIZE = [
+ {
+ value: 'WIDTH_AND_HEIGHT',
+ label: 'Auto width',
+ icon: <ArrowsOutLineHorizontal class="size-3.5" />,
+ },
+ {
+ value: 'HEIGHT',
+ label: 'Auto height',
+ icon: <ArrowsOutLineVertical class="size-3.5" />,
+ },
+ {
+ value: 'NONE',
+ label: 'Fixed size',
+ icon: <FrameCorners class="size-3.5" />,
+ },
+] as const;
+
+export function TextResizing(props: {
+ text: TextInfo;
+ onPatch: (patch: Patch, live: boolean) => void;
+}) {
+ return (
+ <ChoiceRow
+ value={props.text.autoResize ?? 'NONE'}
+ options={RESIZE}
+ testId="fig-text-resize"
+ onChange={(textAutoResize) => props.onPatch({ textAutoResize }, false)}
+ />
+ );
+}
diff --git a/apps/web/src/features/block-fig/components/type-controls.tsx b/apps/web/src/features/block-fig/components/type-controls.tsx
index 85b10af600..38940b69c6 100644
--- a/apps/web/src/features/block-fig/components/type-controls.tsx
+++ b/apps/web/src/features/block-fig/components/type-controls.tsx
@@ -1,7 +1,7 @@
+import { InspectorSelect } from './inspector-select';
/**
* The editable Type section: family, weight and italic, size, line height,
- * letter spacing, paragraph spacing, alignment, resizing, decoration, and
- * case, laid out as Figma's design panel does. With characters selected in
+ * letter spacing and alignment, with less-used controls in Type settings. With characters selected in
* the text editor it shows (and sets) theirs, "Mixed" where they differ.
* Presentational.
*/
@@ -10,17 +10,11 @@ import type { TextInfo } from '@core/fig-engine/types';
import AlignBottomSimple from '@phosphor/align-bottom-simple.svg';
import AlignCenterVerticalSimple from '@phosphor/align-center-vertical-simple.svg';
import AlignTopSimple from '@phosphor/align-top-simple.svg';
-import ArrowsOutLineHorizontal from '@phosphor/arrows-out-line-horizontal.svg';
-import ArrowsOutLineVertical from '@phosphor/arrows-out-line-vertical.svg';
-import FrameCorners from '@phosphor/frame-corners.svg';
import TextAlignCenter from '@phosphor/text-align-center.svg';
import TextAlignJustify from '@phosphor/text-align-justify.svg';
import TextAlignLeft from '@phosphor/text-align-left.svg';
import TextAlignRight from '@phosphor/text-align-right.svg';
-import TextItalic from '@phosphor/text-italic.svg';
-import TextStrikethrough from '@phosphor/text-strikethrough.svg';
-import TextUnderline from '@phosphor/text-underline.svg';
-import { For, type JSX, Show } from 'solid-js';
+
import type { MixedTextField } from '../core/rich-text';
import {
formatLetterSpacing,
@@ -34,83 +28,49 @@ import {
import type { Patch } from '../primitives/create-fig-editor';
import { ChoiceRow, NumberField, ParsedField } from './design-fields';
import { FontPicker } from './font-picker';
-
-const icon = 'size-3.5';
+import { TypeSettings } from './type-settings';
const H_ALIGN = [
- { value: 'LEFT', label: 'Align left', icon: <TextAlignLeft class={icon} /> },
+ {
+ value: 'LEFT',
+ label: 'Align left',
+ icon: <TextAlignLeft class="size-3.5" />,
+ },
{
value: 'CENTER',
label: 'Align center',
- icon: <TextAlignCenter class={icon} />,
+ icon: <TextAlignCenter class="size-3.5" />,
},
{
value: 'RIGHT',
label: 'Align right',
- icon: <TextAlignRight class={icon} />,
+ icon: <TextAlignRight class="size-3.5" />,
},
{
value: 'JUSTIFIED',
label: 'Justify',
- icon: <TextAlignJustify class={icon} />,
+ icon: <TextAlignJustify class="size-3.5" />,
},
] as const;
const V_ALIGN = [
- { value: 'TOP', label: 'Align top', icon: <AlignTopSimple class={icon} /> },
+ {
+ value: 'TOP',
+ label: 'Align top',
+ icon: <AlignTopSimple class="size-3.5" />,
+ },
{
value: 'CENTER',
label: 'Align middle',
- icon: <AlignCenterVerticalSimple class={icon} />,
+ icon: <AlignCenterVerticalSimple class="size-3.5" />,
},
{
value: 'BOTTOM',
label: 'Align bottom',
- icon: <AlignBottomSimple class={icon} />,
+ icon: <AlignBottomSimple class="size-3.5" />,
},
] as const;
-const RESIZE = [
- {
- value: 'WIDTH_AND_HEIGHT',
- label: 'Auto width',
- icon: <ArrowsOutLineHorizontal class={icon} />,
- },
- {
- value: 'HEIGHT',
- label: 'Auto height',
- icon: <ArrowsOutLineVertical class={icon} />,
- },
- { value: 'NONE', label: 'Fixed size', icon: <FrameCorners class={icon} /> },
-] as const;
-
-const CASES = [
- ['ORIGINAL', 'As typed'],
- ['UPPER', 'Uppercase'],
- ['LOWER', 'Lowercase'],
- ['TITLE', 'Title Case'],
-] as const;
-
-function Select(props: {
- label: string;
- testId: string;
- value: string;
- onChange: (value: string) => void;
- children: JSX.Element;
-}) {
- return (
- <select
- class="min-w-0 rounded-md bg-inset px-2 py-1 text-ink outline-none focus:outline focus:outline-1 focus:outline-accent"
- aria-label={props.label}
- data-testid={props.testId}
- value={props.value}
- onChange={(e) => props.onChange(e.currentTarget.value)}
- >
- {props.children}
- </select>
- );
-}
-
export function TypeControls(props: {
text: TextInfo;
/** Fields the selected characters differ in. */
@@ -125,6 +85,7 @@ export function TypeControls(props: {
onFontsOpen?: () => void;
onPatch: (patch: Patch, live: boolean) => void;
}) {
+ let settingsAnchor: HTMLDivElement | undefined;
const t = () => props.text;
const isMixed = (field: MixedTextField) => props.mixed?.has(field) ?? false;
const style = () => parseStyle(t().fontStyle);
@@ -142,10 +103,6 @@ export function TypeControls(props: {
props.weights.includes(w) ||
w === style().weight
);
- const decoration = () =>
- isMixed('decoration') ? 'MIXED' : (t().decoration ?? 'NONE');
- const toggleDecoration = (d: 'UNDERLINE' | 'STRIKETHROUGH') =>
- props.onPatch({ textDecoration: decoration() === d ? 'NONE' : d }, false);
return (
<div class="flex flex-col gap-1.5" data-testid="fig-type">
<FontPicker
@@ -157,62 +114,43 @@ export function TypeControls(props: {
onOpen={props.onFontsOpen}
onSelect={(fontFamily) => props.onPatch({ fontFamily }, false)}
/>
- <div class="grid grid-cols-[1fr_auto] gap-1.5">
- <Select
- label="Font weight"
+ <div class="grid grid-cols-2 gap-2">
+ <InspectorSelect
+ label="Weight"
testId="fig-font-weight"
value={isMixed('fontStyle') ? 'mixed' : String(style().weight)}
- onChange={(w) =>
+ options={[
+ ...(isMixed('fontStyle')
+ ? [{ value: 'mixed', label: 'Mixed', disabled: true }]
+ : []),
+ ...weights().map(([weight, label]) => ({
+ value: String(weight),
+ label,
+ })),
+ ]}
+ onChange={(value) =>
props.onPatch(
- { fontStyle: styleName(Number(w), style().italic) },
+ { fontStyle: styleName(Number(value), style().italic) },
false
)
}
- >
- <Show when={isMixed('fontStyle')}>
- <option value="mixed" selected disabled>
- Mixed
- </option>
- </Show>
- <For each={weights()}>
- {([w, name]) => (
- <option
- value={String(w)}
- selected={!isMixed('fontStyle') && w === style().weight}
- >
- {name}
- </option>
- )}
- </For>
- </Select>
- <button
- type="button"
- aria-label="Italic"
- title="Italic"
- aria-pressed={!isMixed('fontStyle') && style().italic}
- data-testid="fig-italic"
- class="rounded-md bg-inset px-2 text-ink-muted hover:text-ink aria-pressed:bg-hover aria-pressed:text-ink"
- onClick={() =>
- props.onPatch(
- { fontStyle: styleName(style().weight, !style().italic) },
- false
- )
- }
- >
- <TextItalic class={icon} />
- </button>
- </div>
- <div class="grid grid-cols-2 gap-1.5">
+ />
<NumberField
- label="Size"
+ label="T"
+ ariaLabel="Font size"
value={t().fontSize ?? 12}
mixed={isMixed('fontSize')}
min={1}
testId="fig-field-font-size"
onChange={(fontSize, live) => props.onPatch({ fontSize }, live)}
/>
+ </div>
+ <div class="grid grid-cols-2 gap-2">
+ <span class="text-ink-muted text-[11px]">Line height</span>
+ <span class="text-ink-muted text-[11px]">Letter spacing</span>
<ParsedField
- label="Line"
+ label="↕"
+ ariaLabel="Line height"
shown={
isMixed('lineHeight') ? 'Mixed' : formatLineHeight(t().lineHeight)
}
@@ -221,7 +159,8 @@ export function TypeControls(props: {
onChange={(lineHeight) => props.onPatch({ lineHeight }, false)}
/>
<ParsedField
- label="Letter"
+ label="↔"
+ ariaLabel="Letter spacing"
shown={
isMixed('letterSpacing')
? 'Mixed'
@@ -231,14 +170,14 @@ export function TypeControls(props: {
testId="fig-field-letter-spacing"
onChange={(letterSpacing) => props.onPatch({ letterSpacing }, false)}
/>
- <NumberField
- label="¶"
- value={t().paragraphSpacing ?? 0}
- min={0}
- testId="fig-field-paragraph-spacing"
- onChange={(paragraphSpacing, live) =>
- props.onPatch({ paragraphSpacing }, live)
- }
+ </div>
+ <div ref={settingsAnchor} class="flex items-center justify-between">
+ <span class="text-ink-muted text-[11px]">Alignment</span>
+ <TypeSettings
+ anchor={() => settingsAnchor}
+ text={t()}
+ mixed={props.mixed}
+ onPatch={props.onPatch}
/>
</div>
<div class="grid grid-cols-[4fr_3fr] gap-1.5">
@@ -259,65 +198,6 @@ export function TypeControls(props: {
}
/>
</div>
- <div class="grid grid-cols-[3fr_2fr_3fr] gap-1.5">
- <ChoiceRow
- value={t().autoResize ?? 'NONE'}
- options={RESIZE}
- testId="fig-text-resize"
- onChange={(textAutoResize) =>
- props.onPatch({ textAutoResize }, false)
- }
- />
- <div class="flex items-center gap-0.5 rounded-md bg-inset p-0.5">
- <button
- type="button"
- aria-label="Underline"
- title="Underline"
- aria-pressed={decoration() === 'UNDERLINE'}
- data-testid="fig-underline"
- class="flex flex-1 items-center justify-center rounded p-1 text-ink-muted hover:text-ink aria-pressed:bg-hover aria-pressed:text-ink"
- onClick={() => toggleDecoration('UNDERLINE')}
- >
- <TextUnderline class={icon} />
- </button>
- <button
- type="button"
- aria-label="Strikethrough"
- title="Strikethrough"
- aria-pressed={decoration() === 'STRIKETHROUGH'}
- class="flex flex-1 items-center justify-center rounded p-1 text-ink-muted hover:text-ink aria-pressed:bg-hover aria-pressed:text-ink"
- onClick={() => toggleDecoration('STRIKETHROUGH')}
- >
- <TextStrikethrough class={icon} />
- </button>
- </div>
- <Select
- label="Case"
- testId="fig-text-case"
- value={isMixed('case') ? 'mixed' : (t().case ?? 'ORIGINAL')}
- onChange={(c) =>
- props.onPatch({ textCase: c as Patch['textCase'] }, false)
- }
- >
- <Show when={isMixed('case')}>
- <option value="mixed" selected disabled>
- Mixed
- </option>
- </Show>
- <For each={CASES}>
- {([value, label]) => (
- <option
- value={value}
- selected={
- !isMixed('case') && value === (t().case ?? 'ORIGINAL')
- }
- >
- {label}
- </option>
- )}
- </For>
- </Select>
- </div>
</div>
);
}
diff --git a/apps/web/src/features/block-fig/components/type-settings.tsx b/apps/web/src/features/block-fig/components/type-settings.tsx
new file mode 100644
index 0000000000..babb2519bb
--- /dev/null
+++ b/apps/web/src/features/block-fig/components/type-settings.tsx
@@ -0,0 +1,143 @@
+/** Less-used typography controls, opened beside the inspector. */
+import type { TextInfo } from '@core/fig-engine/types';
+import { Popover } from '@kobalte/core/popover';
+import SlidersHorizontal from '@phosphor/sliders-horizontal.svg';
+import TextItalic from '@phosphor/text-italic.svg';
+import TextStrikethrough from '@phosphor/text-strikethrough.svg';
+import TextUnderline from '@phosphor/text-underline.svg';
+import X from '@phosphor/x.svg';
+import type { MixedTextField } from '../core/rich-text';
+import { parseStyle, styleName } from '../core/type';
+import type { Patch } from '../primitives/create-fig-editor';
+import { NumberField } from './design-fields';
+import { InspectorSelect } from './inspector-select';
+
+const CASES = [
+ ['ORIGINAL', 'As typed'],
+ ['UPPER', 'Uppercase'],
+ ['LOWER', 'Lowercase'],
+ ['TITLE', 'Title Case'],
+] as const;
+
+export function TypeSettings(props: {
+ anchor: () => HTMLElement | undefined;
+ text: TextInfo;
+ mixed?: ReadonlySet<MixedTextField>;
+ onPatch: (patch: Patch, live: boolean) => void;
+}) {
+ const style = () => parseStyle(props.text.fontStyle);
+ const decoration = () =>
+ props.mixed?.has('decoration') ? 'MIXED' : props.text.decoration;
+ const toggleDecoration = (value: 'UNDERLINE' | 'STRIKETHROUGH') =>
+ props.onPatch(
+ { textDecoration: decoration() === value ? 'NONE' : value },
+ false
+ );
+ return (
+ <Popover placement="left-start" gutter={24} anchorRef={props.anchor}>
+ <Popover.Trigger
+ aria-label="Type settings"
+ title="Type settings"
+ data-testid="fig-type-settings"
+ class="flex size-7 items-center justify-center rounded text-ink-muted hover:bg-hover hover:text-ink"
+ >
+ <SlidersHorizontal class="size-4" />
+ </Popover.Trigger>
+ <Popover.Portal>
+ <Popover.Content
+ class="fig-editor-theme z-modal w-64 rounded-xl border border-edge-muted bg-menu p-3 text-ink text-xs shadow-xl outline-none"
+ aria-label="Type settings"
+ onKeyDown={(e) => {
+ if (!e.metaKey && !e.ctrlKey) e.stopPropagation();
+ }}
+ onPointerDown={(e) => e.stopPropagation()}
+ >
+ <div class="mb-3 flex items-center justify-between">
+ <Popover.Title class="font-medium">Type settings</Popover.Title>
+ <Popover.CloseButton
+ aria-label="Close type settings"
+ class="rounded p-1 hover:bg-hover"
+ >
+ <X class="size-3.5" />
+ </Popover.CloseButton>
+ </div>
+ <div class="flex flex-col gap-2">
+ <span class="text-ink-muted">Decoration</span>
+ <div class="flex gap-1 rounded-md bg-inset p-1">
+ <button
+ type="button"
+ aria-label="Italic"
+ title="Italic"
+ data-testid="fig-italic"
+ aria-pressed={!props.mixed?.has('fontStyle') && style().italic}
+ class="flex h-7 flex-1 items-center justify-center rounded text-ink-muted hover:text-ink aria-pressed:bg-hover aria-pressed:text-ink"
+ onClick={() =>
+ props.onPatch(
+ { fontStyle: styleName(style().weight, !style().italic) },
+ false
+ )
+ }
+ >
+ <TextItalic class="size-4" />
+ </button>
+ <button
+ type="button"
+ aria-label="Underline"
+ title="Underline"
+ data-testid="fig-underline"
+ aria-pressed={decoration() === 'UNDERLINE'}
+ class="flex h-7 flex-1 items-center justify-center rounded text-ink-muted hover:text-ink aria-pressed:bg-hover aria-pressed:text-ink"
+ onClick={() => toggleDecoration('UNDERLINE')}
+ >
+ <TextUnderline class="size-4" />
+ </button>
+ <button
+ type="button"
+ aria-label="Strikethrough"
+ title="Strikethrough"
+ data-testid="fig-strikethrough"
+ aria-pressed={decoration() === 'STRIKETHROUGH'}
+ class="flex h-7 flex-1 items-center justify-center rounded text-ink-muted hover:text-ink aria-pressed:bg-hover aria-pressed:text-ink"
+ onClick={() => toggleDecoration('STRIKETHROUGH')}
+ >
+ <TextStrikethrough class="size-4" />
+ </button>
+ </div>
+ <label class="flex flex-col gap-1">
+ <span class="text-ink-muted">Letter case</span>
+ <InspectorSelect
+ label="Case"
+ testId="fig-text-case"
+ value={
+ props.mixed?.has('case')
+ ? 'mixed'
+ : (props.text.case ?? 'ORIGINAL')
+ }
+ options={[
+ ...(props.mixed?.has('case')
+ ? [{ value: 'mixed', label: 'Mixed', disabled: true }]
+ : []),
+ ...CASES.map(([value, label]) => ({ value, label })),
+ ]}
+ onChange={(value) =>
+ props.onPatch({ textCase: value as Patch['textCase'] }, false)
+ }
+ />
+ </label>
+ <span class="text-ink-muted">Paragraph spacing</span>
+ <NumberField
+ label="¶"
+ ariaLabel="Paragraph spacing"
+ value={props.text.paragraphSpacing ?? 0}
+ min={0}
+ testId="fig-field-paragraph-spacing"
+ onChange={(paragraphSpacing, live) =>
+ props.onPatch({ paragraphSpacing }, live)
+ }
+ />
+ </div>
+ </Popover.Content>
+ </Popover.Portal>
+ </Popover>
+ );
+}
diff --git a/apps/web/src/features/block-fig/components/variable-controls.tsx b/apps/web/src/features/block-fig/components/variable-controls.tsx
index 744bc71941..ca7c9a2007 100644
--- a/apps/web/src/features/block-fig/components/variable-controls.tsx
+++ b/apps/web/src/features/block-fig/components/variable-controls.tsx
@@ -1,3 +1,4 @@
+import { InspectorSelect } from './inspector-select';
/**
* Variables in the design panel: the color variable a fill or stroke is
* bound to (with a picker of the file's color variables and "Detach
@@ -119,7 +120,7 @@ export function VariableControl(props: {
<Popover.Portal>
<Layer depth={3}>
<Popover.Content
- class="z-modal flex max-h-96 w-60 flex-col rounded-xl border border-edge-muted bg-menu p-2 text-xs shadow-xl outline-none"
+ class="fig-editor-theme z-modal flex max-h-96 w-60 flex-col rounded-xl border border-edge-muted bg-menu p-2 text-xs shadow-xl outline-none"
aria-label="Color variables"
onKeyDown={(e: KeyboardEvent) => {
if (!e.metaKey && !e.ctrlKey) e.stopPropagation();
@@ -193,23 +194,22 @@ export function VariableModes(props: {
<For each={props.modes}>
{(m) => (
<PropertyRow label={m.collection.name}>
- <select
- class="w-full rounded-md bg-inset px-1.5 py-0.5 text-ink outline-none disabled:opacity-60"
+ <InspectorSelect
+ label={m.collection.name}
value={m.mode ?? ''}
disabled={!props.onMode}
- data-testid={`fig-variable-mode-${m.collection.name.replace(/\s+/g, '-')}`}
- onChange={(e) =>
- props.onMode?.(
- m.collection.id,
- e.currentTarget.value || undefined
- )
+ testId={`fig-variable-mode-${m.collection.name.replace(/\s+/g, '-')}`}
+ options={[
+ { value: '', label: 'Auto' },
+ ...m.modes.map((mode) => ({
+ value: mode.id,
+ label: mode.name,
+ })),
+ ]}
+ onChange={(value) =>
+ props.onMode?.(m.collection.id, value || undefined)
}
- >
- <option value="">Auto</option>
- <For each={m.modes}>
- {(mode) => <option value={mode.id}>{mode.name}</option>}
- </For>
- </select>
+ />
</PropertyRow>
)}
</For>
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 632db8e56e..a18a897854 100644
--- a/apps/web/src/features/block-fig/components/viewer-toolbar.tsx
+++ b/apps/web/src/features/block-fig/components/viewer-toolbar.tsx
@@ -1,249 +1,160 @@
-/**
- * The floating toolbar at the bottom of the canvas (Figma UI3): tools,
- * undo and redo with the save state when editing, and the zoom menu with
- * its view toggles. Presentational.
- */
-
-import ArrowUUpLeft from '@phosphor/arrow-u-up-left.svg';
-import ArrowUUpRight from '@phosphor/arrow-u-up-right.svg';
+/** Figma's compact, grouped drawing tools in a single floating strip. */
import ArrowUpRight from '@phosphor/arrow-up-right.svg';
import CaretDown from '@phosphor/caret-down.svg';
import Circle from '@phosphor/circle.svg';
-import CloudArrowUp from '@phosphor/cloud-arrow-up.svg';
-import CloudCheck from '@phosphor/cloud-check.svg';
+import Code from '@phosphor/code.svg';
import Hand from '@phosphor/hand.svg';
import Hash from '@phosphor/hash.svg';
-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 Shapes from '@phosphor/shapes.svg';
import Square from '@phosphor/square.svg';
import TextT from '@phosphor/text-t.svg';
-import Unite from '@phosphor/unite.svg';
-import WarningCircle from '@phosphor/warning-circle.svg';
-import { Button } from '@ui/components/Button';
-import { createSignal, For, type JSX, onCleanup, Show } from 'solid-js';
-import { match } from 'ts-pattern';
-import type { BooleanOperation } from '../core/boolean';
-import type { SaveState } from '../primitives/create-fig-editor';
+import { createMemo, For, type JSX, Show } from 'solid-js';
import type { Tool } from '../primitives/create-fig-viewer';
-import { BooleanMenuItems } from './boolean-controls';
+import { EditorMenu } from './editor-menu';
+
+export type { EditorMenuItem as ZoomMenuItem } from './editor-menu';
interface ToolButton {
tool: Tool;
label: string;
key: string;
icon: (props: { class?: string }) => JSX.Element;
- /** Only when the file is editable. */
- edit: boolean;
}
-const TOOLS: ToolButton[] = [
- { tool: 'move', label: 'Move', key: 'V', icon: NavigationArrow, edit: false },
- { tool: 'frame', label: 'Frame', key: 'F', icon: Hash, edit: true },
- { tool: 'rectangle', label: 'Rectangle', key: 'R', icon: Square, edit: true },
- { tool: 'ellipse', label: 'Ellipse', key: 'O', icon: Circle, edit: true },
- { 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 },
+const GROUPS: { label: string; edit?: boolean; tools: ToolButton[] }[] = [
+ {
+ label: 'Move tools',
+ tools: [
+ { tool: 'move', label: 'Move', key: 'V', icon: NavigationArrow },
+ { tool: 'hand', label: 'Hand tool', key: 'H', icon: Hand },
+ ],
+ },
+ {
+ label: 'Frame tools',
+ edit: true,
+ tools: [{ tool: 'frame', label: 'Frame', key: 'F', icon: Hash }],
+ },
+ {
+ label: 'Shape tools',
+ edit: true,
+ tools: [
+ { tool: 'rectangle', label: 'Rectangle', key: 'R', icon: Square },
+ { tool: 'line', label: 'Line', key: 'L', icon: LineSegment },
+ { tool: 'arrow', label: 'Arrow', key: '⇧L', icon: ArrowUpRight },
+ { tool: 'ellipse', label: 'Ellipse', key: 'O', icon: Circle },
+ ],
+ },
+ {
+ label: 'Drawing tools',
+ edit: true,
+ tools: [
+ { tool: 'pen', label: 'Pen', key: 'P', icon: PenNib },
+ { tool: 'pencil', label: 'Pencil', key: '⇧P', icon: PencilSimple },
+ ],
+ },
{
- tool: 'pencil',
- label: 'Pencil',
- key: '⇧P',
- icon: PencilSimple,
+ label: 'Text tools',
edit: true,
+ tools: [{ tool: 'text', label: 'Text', key: 'T', icon: TextT }],
},
- { tool: 'text', label: 'Text', key: 'T', icon: TextT, edit: true },
- { tool: 'hand', label: 'Hand tool', key: 'H', icon: Hand, edit: false },
];
-export interface ZoomMenuItem {
+function ToolGroup(props: {
label: string;
- shortcut?: string;
- checked?: boolean;
- onSelect: () => void;
- testId?: string;
+ tools: ToolButton[];
+ tool: Tool | undefined;
+ onTool: (tool: Tool) => void;
+}) {
+ // Retain the last tool used in each group, including shortcut selections.
+ const current = createMemo<ToolButton>(
+ (previous) =>
+ props.tools.find((t) => t.tool === props.tool) ??
+ previous ??
+ props.tools[0]
+ );
+ return (
+ <div class="flex shrink-0 items-center gap-px">
+ <button
+ type="button"
+ aria-label={`${current().label} (${current().key})`}
+ title={`${current().label} · ${current().key}`}
+ aria-pressed={props.tool === current().tool}
+ data-testid={`fig-tool-${current().tool}`}
+ class="flex size-8 items-center justify-center rounded-lg text-ink-muted outline-none hover:bg-hover focus-visible:ring-2 focus-visible:ring-accent aria-pressed:bg-accent aria-pressed:text-accent-contrast"
+ onClick={() => props.onTool(current().tool)}
+ >
+ {current().icon({ class: 'size-4' })}
+ </button>
+ <Show when={props.tools.length > 1}>
+ <EditorMenu
+ label={props.label}
+ testId={`fig-tool-menu-${props.tools[0].tool}`}
+ above
+ items={props.tools.map((t) => ({
+ label: t.label,
+ shortcut: t.key,
+ icon: t.icon({ class: 'size-4' }),
+ checked: props.tool === t.tool,
+ testId: `fig-choose-${t.tool}`,
+ onSelect: () => props.onTool(t.tool),
+ }))}
+ >
+ <CaretDown class="size-2.5" />
+ </EditorMenu>
+ </Show>
+ </div>
+ );
}
export function ViewerToolbar(props: {
- tool: Tool;
+ tool: Tool | undefined;
onTool: (tool: Tool) => void;
- zoomLabel: string;
- zoomItems: (ZoomMenuItem | 'divider')[];
- onShortcuts: () => void;
editable?: boolean;
- saveState?: SaveState;
- canUndo?: boolean;
- canRedo?: boolean;
- onUndo?: () => void;
- onRedo?: () => void;
- /** Boolean operations on the selection (when editable and selected). */
- onBoolean?: (operation: BooleanOperation) => void;
- onFlatten?: () => void;
- /** Review tools after the drawing tools (comments, present). */
+ onActions: () => void;
+ devMode: boolean;
+ onDevMode: () => void;
review?: JSX.Element;
}) {
- const [open, setOpen] = createSignal(false);
- const [booleanOpen, setBooleanOpen] = createSignal(false);
- let menu!: HTMLDivElement;
- let booleanMenu: HTMLDivElement | undefined;
- const onDocumentDown = (e: PointerEvent) => {
- if (!menu.contains(e.target as Node)) setOpen(false);
- if (!booleanMenu?.contains(e.target as Node)) setBooleanOpen(false);
- };
- document.addEventListener('pointerdown', onDocumentDown);
- onCleanup(() => document.removeEventListener('pointerdown', onDocumentDown));
-
- const tools = () => TOOLS.filter((t) => props.editable || !t.edit);
-
return (
<div
- // A narrow canvas wraps the toolbar onto more rows rather than hiding
- // tools under the panels.
- class="-translate-x-1/2 absolute bottom-3 left-1/2 z-10 flex w-max max-w-[calc(100%-1rem)] flex-wrap items-center justify-center gap-0.5 rounded-xl border border-edge-muted bg-menu p-1 shadow-lg"
+ class="-translate-x-1/2 absolute bottom-4 left-1/2 z-10 flex w-max max-w-[calc(100%-1rem)] items-center gap-1 rounded-2xl border border-edge-muted bg-menu p-2 shadow-lg"
data-testid="fig-toolbar"
+ aria-label="Drawing tools"
+ role="toolbar"
onPointerDown={(e) => e.stopPropagation()}
>
- <For each={tools()}>
- {(t) => (
- <Button
- variant="ghost"
- size="icon-md"
- aria-pressed={props.tool === t.tool}
- class={
- props.tool === t.tool ? 'bg-accent/15 text-accent' : undefined
- }
- label={`${t.label} (${t.key})`}
- tooltip={`${t.label} · ${t.key}`}
- data-testid={`fig-tool-${t.tool}`}
- onClick={() => props.onTool(t.tool)}
- >
- {t.icon({ class: t.tool === 'move' ? '-scale-x-100' : undefined })}
- </Button>
+ <For each={GROUPS.filter((g) => props.editable || !g.edit)}>
+ {(group) => (
+ <ToolGroup {...group} tool={props.tool} onTool={props.onTool} />
)}
</For>
{props.review}
- <Show when={props.editable}>
- <div ref={booleanMenu} class="relative">
- <Button
- variant="ghost"
- size="sm"
- class="gap-0.5 px-1.5"
- label="Boolean groups"
- tooltip="Boolean groups"
- aria-expanded={booleanOpen()}
- disabled={!props.onBoolean}
- data-testid="fig-boolean-menu"
- onClick={() => setBooleanOpen((o) => !o)}
- >
- <Unite class="size-4" />
- <CaretDown class="size-3" />
- </Button>
- <Show when={booleanOpen() && props.onBoolean && props.onFlatten}>
- <div class="absolute bottom-full left-0 z-50 mb-2 w-48 rounded-lg border border-edge-muted bg-menu p-1 text-xs shadow-lg">
- <BooleanMenuItems
- onBoolean={(op) => props.onBoolean?.(op)}
- onFlatten={() => props.onFlatten?.()}
- onDone={() => setBooleanOpen(false)}
- />
- </div>
- </Show>
- </div>
- <div aria-hidden="true" class="mx-1 h-5 w-px bg-edge-muted" />
- <Button
- variant="ghost"
- size="icon-md"
- label="Undo"
- tooltip="Undo · ⌘Z"
- disabled={!props.canUndo}
- data-testid="fig-undo"
- onClick={() => props.onUndo?.()}
- >
- <ArrowUUpLeft />
- </Button>
- <Button
- variant="ghost"
- size="icon-md"
- label="Redo"
- tooltip="Redo · ⇧⌘Z"
- disabled={!props.canRedo}
- data-testid="fig-redo"
- onClick={() => props.onRedo?.()}
- >
- <ArrowUUpRight />
- </Button>
- <span
- class="flex size-8 items-center justify-center text-ink-muted"
- data-testid="fig-save-state"
- data-state={props.saveState}
- title={match(props.saveState ?? 'saved')
- .with('saved', () => 'All changes saved')
- .with('unsaved', () => 'Unsaved changes')
- .with('saving', () => 'Saving…')
- .with('error', () => 'Save failed')
- .exhaustive()}
- >
- {match(props.saveState ?? 'saved')
- .with('saved', () => <CloudCheck class="size-4" />)
- .with('error', () => <WarningCircle class="size-4 text-failure" />)
- .otherwise(() => (
- <CloudArrowUp class="size-4 animate-pulse" />
- ))}
- </span>
- </Show>
- <div aria-hidden="true" class="mx-1 h-5 w-px bg-edge-muted" />
- <div ref={menu} class="relative">
- <Button
- variant="ghost"
- size="sm"
- class="min-w-16 gap-0.5 tabular-nums"
- aria-expanded={open()}
- data-testid="fig-zoom-menu"
- onClick={() => setOpen((o) => !o)}
- >
- {props.zoomLabel}
- <CaretDown class="size-3" />
- </Button>
- <Show when={open()}>
- <div class="absolute right-0 bottom-full z-50 mb-2 w-56 rounded-lg border border-edge-muted bg-menu p-1 text-xs shadow-lg">
- <For each={props.zoomItems}>
- {(item) =>
- item === 'divider' ? (
- <div class="my-1 h-px bg-edge-muted" />
- ) : (
- <button
- type="button"
- data-testid={item.testId}
- class="flex h-7 w-full items-center gap-2 rounded-md px-2 text-left text-ink hover:bg-hover"
- onClick={() => {
- item.onSelect();
- setOpen(false);
- }}
- >
- <span class="w-3 text-accent">
- {item.checked ? '✓' : ''}
- </span>
- <span class="flex-1">{item.label}</span>
- <Show when={item.shortcut}>
- <span class="text-ink-muted">{item.shortcut}</span>
- </Show>
- </button>
- )
- }
- </For>
- </div>
- </Show>
- </div>
- <Button
- variant="ghost"
- size="icon-md"
- label="Keyboard shortcuts"
- tooltip="Keyboard shortcuts · Ctrl⇧?"
- onClick={props.onShortcuts}
+ <button
+ type="button"
+ class="flex size-8 shrink-0 items-center justify-center rounded-lg text-ink-muted hover:bg-hover focus-visible:ring-2 focus-visible:ring-accent"
+ aria-label="Actions"
+ title="Actions · ⌘/ / Ctrl+/"
+ data-testid="fig-actions-button"
+ onClick={props.onActions}
+ >
+ <Shapes class="size-4" />
+ </button>
+ <div aria-hidden="true" class="mx-1 h-5 w-px shrink-0 bg-edge-muted" />
+ <button
+ type="button"
+ aria-label="Dev Mode"
+ aria-pressed={props.devMode}
+ title="Dev Mode"
+ data-testid="fig-panel-tab-code"
+ class="flex h-8 shrink-0 items-center gap-1.5 rounded-lg bg-inset px-2 text-ink-muted hover:bg-hover focus-visible:ring-2 focus-visible:ring-accent aria-pressed:bg-success aria-pressed:text-accent-contrast"
+ onClick={props.onDevMode}
>
- <Keyboard />
- </Button>
+ <Code class="size-4" />
+ </button>
</div>
);
}
diff --git a/apps/web/src/features/block-fig/components/viewer-zoom.tsx b/apps/web/src/features/block-fig/components/viewer-zoom.tsx
new file mode 100644
index 0000000000..ce535fa225
--- /dev/null
+++ b/apps/web/src/features/block-fig/components/viewer-zoom.tsx
@@ -0,0 +1,18 @@
+import CaretDown from '@phosphor/caret-down.svg';
+import { EditorMenu, type EditorMenuItem } from './editor-menu';
+
+export function ViewerZoom(props: {
+ label: string;
+ items: (EditorMenuItem | 'divider')[];
+}) {
+ return (
+ <EditorMenu
+ label="Zoom and view options"
+ testId="fig-zoom-menu"
+ items={props.items}
+ >
+ <span class="min-w-8 text-right text-xs tabular-nums">{props.label}</span>
+ <CaretDown class="size-3" />
+ </EditorMenu>
+ );
+}
diff --git a/apps/web/src/features/block-fig/core/export-settings.ts b/apps/web/src/features/block-fig/core/export-settings.ts
index 39200b47bd..349145fc85 100644
--- a/apps/web/src/features/block-fig/core/export-settings.ts
+++ b/apps/web/src/features/block-fig/core/export-settings.ts
@@ -13,7 +13,7 @@ import { match } from 'ts-pattern';
/** The formats the format menu offers, as Figma labels them. */
export const EXPORT_FORMATS: { format: ExportFormat; label: string }[] = [
{ format: 'PNG', label: 'PNG' },
- { format: 'JPEG', label: 'JPG' },
+ { format: 'JPEG', label: 'JPEG' },
{ format: 'SVG', label: 'SVG' },
{ format: 'PDF', label: 'PDF' },
];
diff --git a/apps/web/src/features/block-fig/definition.ts b/apps/web/src/features/block-fig/definition.ts
index fcf896783e..15b5bd9770 100644
--- a/apps/web/src/features/block-fig/definition.ts
+++ b/apps/web/src/features/block-fig/definition.ts
@@ -5,13 +5,23 @@ import {
loadResult,
} from '@core/block';
import { enableFigViewer, isFeatureEnabled } from '@core/constant/featureFlags';
+import { compiledFigModule } from '@core/fig-engine/compiled-module';
import { fetchBinaryDocumentData } from '@queries/storage/binary-document';
import { fetchBinary } from '@service-storage/util/fetchBinary';
import { err, ok } from 'neverthrow';
import { lazy } from 'solid-js';
+import { FigOpening } from './components/fig-opening';
export const FIG_MIME = 'application/x-figma';
+async function warmEngine() {
+ try {
+ await compiledFigModule();
+ } catch {
+ // Opening the engine retries a failed warmup and reports the error.
+ }
+}
+
export const definition = defineBlock({
name: 'fig',
description: 'view Figma design files',
@@ -19,9 +29,14 @@ export const definition = defineBlock({
fig: FIG_MIME,
},
component: lazy(() => import('./fig-block')),
+ loading: FigOpening,
liveTrackingEnabled: true,
async load(source, intent) {
if (source.type !== 'dss') return LoadErrors.INVALID;
+ if (intent !== 'preload' && isFeatureEnabled(enableFigViewer)) {
+ // Fetch and compile while storage retrieves the document.
+ void warmEngine();
+ }
const maybeDocument = await loadResult(fetchBinaryDocumentData(source.id));
if (intent === 'preload') {
return ok({ type: 'preload', origin: source });
diff --git a/apps/web/src/features/block-fig/fig-block.tsx b/apps/web/src/features/block-fig/fig-block.tsx
index 15c01c6977..aff8613006 100644
--- a/apps/web/src/features/block-fig/fig-block.tsx
+++ b/apps/web/src/features/block-fig/fig-block.tsx
@@ -26,7 +26,7 @@ import {
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 type { FigEngine } from '@core/fig-engine/client';
import { blockDataSignal } from '@core/internal/BlockLoader';
import { blockMetadataSignal } from '@core/signal/load';
import {
@@ -63,7 +63,6 @@ import {
type FigSharing,
FigViewerProvider,
} from './context/fig-viewer-context';
-import { fileFingerprint } from './core/collab-entries';
import type { FigData } from './definition';
import { createDesignCollabSession } from './queries/fig-collab';
import { useFigComments } from './queries/fig-comments';
@@ -76,6 +75,7 @@ import {
initializeDesignSync,
} from './queries/fig-sync';
import { createFontSource } from './queries/font-source';
+import { openFigEngine, prepareFigEngine } from './queries/prepare-engine';
import { FigViewer } from './views/fig-viewer';
/**
@@ -108,6 +108,8 @@ function FigHost(props: {
collaboration?: FigCollaboration;
/** Whether every change made here reached the sync service. */
delivered?: () => Promise<boolean>;
+ /** Parsing already in progress while the shared session connects. */
+ opening?: ReturnType<typeof prepareFigEngine>;
/** Why the design is read-only, with the action that helps. */
notice?: { message: string; action: string; onAction: () => void };
comments?: FigCommentStore;
@@ -137,21 +139,24 @@ function FigHost(props: {
let shared: FigSharing | undefined;
const open = async () => {
try {
- // Before the engine takes the bytes.
- const fingerprint = props.shared
- ? await fileFingerprint(props.bytes)
- : undefined;
- const e = await FigEngine.open(props.bytes, {
- onFailure: (error) => setFailure(error.message),
- });
+ const onFailure = (error: Error) => setFailure(error.message);
+ const { engine: e, fingerprint } = props.opening
+ ? await props.opening.take(onFailure)
+ : await openFigEngine(props.bytes, onFailure);
opened = e;
- if (disposed) return;
+ if (disposed) {
+ e.close();
+ return;
+ }
if (props.shared && fingerprint) {
shared = await shareFigEngine(e, props.shared, {
fingerprint,
delivered: props.delivered,
});
- if (disposed) return;
+ if (disposed) {
+ shared.close();
+ return;
+ }
shared.onReplaced(() => setReplaced(true));
setSharing(shared);
}
@@ -169,7 +174,7 @@ function FigHost(props: {
});
return (
- <Switch fallback={<FigOpening bytes={props.bytes} />}>
+ <Switch fallback={<FigOpening />}>
<Match when={failure()}>
{(message) => (
<div class="flex size-full items-center justify-center p-6 text-center text-ink-muted text-sm">
@@ -260,6 +265,8 @@ function DesignSession(props: {
retry: () => void;
}) {
const userId = useUserId();
+ const opening = prepareFigEngine(props.bytes);
+ onCleanup(() => void opening.dispose());
const session = createDesignCollabSession({
documentId: props.documentId,
userId: userId(),
@@ -278,20 +285,15 @@ function DesignSession(props: {
return state.t === 'error' ? state.message : undefined;
};
return (
- <Switch
- fallback={
- <div class="flex size-full items-center justify-center text-ink-muted text-sm">
- Opening design…
- </div>
- }
- >
+ <Switch fallback={<FigOpening />}>
<Match when={session.state().t === 'unshared'}>
- <FigHost {...props} canEdit={() => false} />
+ <FigHost {...props} opening={opening} canEdit={() => false} />
</Match>
<Match when={failed()}>
{(message) => (
<FigHost
{...props}
+ opening={opening}
canEdit={() => false}
notice={
props.canEdit()
@@ -309,6 +311,7 @@ function DesignSession(props: {
{(doc) => (
<FigHost
{...props}
+ opening={opening}
shared={doc}
collaboration={session.collaboration}
delivered={session.delivered}
@@ -378,64 +381,66 @@ export default function FigBlock(props: { share?: string; present?: string }) {
};
return (
- <DocumentBlockContainer>
- <div class="flex size-full min-h-0 min-w-0 flex-col overflow-hidden">
- <SplitHeaderLeft>
- <BlockItemSplitLabel badges={<FileTypeChip />} />
- </SplitHeaderLeft>
- <SplitHeaderRight>
- <BlockLiveIndicators />
- </SplitHeaderRight>
- <ResponsivePermissionsBadge />
- <ResponsiveBlockToolbar
- id={documentId}
- itemType="document"
- name={name()}
- ops={[
- { op: 'rename' },
- { op: 'copy' },
- { op: 'moveToProject' },
- {
- group: 'file',
- label: 'Download',
- icon: DownloadSimple,
- action: () => void download(),
- },
- { op: 'delete' },
- ]}
- tools={[
- {
- group: 'sharing',
- label: 'Share',
- icon: IconShared,
- action: openShare,
- buttonComponent: () => <ShareTrigger onClick={openShare} />,
- focusTarget: getShareDrawerRecipientInput,
- },
- ]}
- />
- <div class="min-h-0 flex-1">
- <Show when={data()} keyed>
- {(d) => (
- <Show
- when={d.bytes}
- fallback={<DownloadOnly onDownload={() => void download()} />}
- >
- {(bytes) => (
- <CollaborativeFigHost
- bytes={bytes()}
- fileName={() => name() ?? 'Design'}
- documentId={documentId}
- canEdit={canEdit}
- comments={comments}
- present={props.present}
- />
- )}
- </Show>
- )}
- </Show>
+ <div class="size-full border-edge-frame border-t">
+ <DocumentBlockContainer loadingFallback={<FigOpening />}>
+ <div class="flex size-full min-h-0 min-w-0 flex-col overflow-hidden">
+ <SplitHeaderLeft>
+ <BlockItemSplitLabel badges={<FileTypeChip />} />
+ </SplitHeaderLeft>
+ <SplitHeaderRight>
+ <BlockLiveIndicators />
+ </SplitHeaderRight>
+ <ResponsivePermissionsBadge />
+ <ResponsiveBlockToolbar
+ id={documentId}
+ itemType="document"
+ name={name()}
+ ops={[
+ { op: 'rename' },
+ { op: 'copy' },
+ { op: 'moveToProject' },
+ {
+ group: 'file',
+ label: 'Download',
+ icon: DownloadSimple,
+ action: () => void download(),
+ },
+ { op: 'delete' },
+ ]}
+ tools={[
+ {
+ group: 'sharing',
+ label: 'Share',
+ icon: IconShared,
+ action: openShare,
+ buttonComponent: () => <ShareTrigger onClick={openShare} />,
+ focusTarget: getShareDrawerRecipientInput,
+ },
+ ]}
+ />
+ <div class="min-h-0 flex-1">
+ <Show when={data()} keyed>
+ {(d) => (
+ <Show
+ when={d.bytes}
+ fallback={<DownloadOnly onDownload={() => void download()} />}
+ >
+ {(bytes) => (
+ <CollaborativeFigHost
+ bytes={bytes()}
+ fileName={() => name() ?? 'Design'}
+ documentId={documentId}
+ canEdit={canEdit}
+ comments={comments}
+ present={props.present}
+ />
+ )}
+ </Show>
+ )}
+ </Show>
+ </div>
</div>
- </div>
- </DocumentBlockContainer>
+ </DocumentBlockContainer>
+ </div>
);
}
diff --git a/apps/web/src/features/block-fig/primitives/create-fig-context-menu.ts b/apps/web/src/features/block-fig/primitives/create-fig-context-menu.ts
index 14397c7221..449e198e27 100644
--- a/apps/web/src/features/block-fig/primitives/create-fig-context-menu.ts
+++ b/apps/web/src/features/block-fig/primitives/create-fig-context-menu.ts
@@ -155,7 +155,7 @@ export function createFigContextMenu(options: {
// Several layers: hide them all unless all are hidden already.
void editor.setProps({ visible: !open.facts.anyVisible });
} else if (action === 'toggle-locked' && open?.facts) {
- void editor.setProps({ locked: open.facts.anyUnlocked });
+ void editor.toggleLocked();
} else {
options.run(action);
}
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 703546e8a3..f9665b0dd4 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
@@ -41,6 +41,7 @@ import { resizedOrigin } from '../core/rotation';
import type { Measure } from '../core/type';
import { type PenPoint, pencilPoints, penNetwork } from '../core/vector';
import type { FigViewer, Selected } from './create-fig-viewer';
+import { resolveFrameDrop } from './resolve-frame-drop';
export type SaveState = 'saved' | 'unsaved' | 'saving' | 'error';
@@ -462,15 +463,22 @@ export function createFigEditor(options: FigEditorOptions) {
* `quiet` steps re-render and reload nothing (a lifted move's steps,
* which the canvas draws itself).
*/
- const apply = (ops: Op[], coalesce?: string, quiet = false) => {
- if (!enabled() || ops.length === 0) return Promise.resolve(undefined);
+ const apply = (
+ ops: Op[] | ((page: number) => Promise<Op[]>),
+ coalesce?: string,
+ quiet = false
+ ) => {
+ if (!enabled() || (Array.isArray(ops) && ops.length === 0))
+ return Promise.resolve(undefined);
const run = queue.then(async () => {
try {
// Other people's changes that arrived first apply first.
await pullShared();
const page = viewer.page();
+ const resolved = typeof ops === 'function' ? await ops(page) : ops;
+ if (resolved.length === 0) return undefined;
const before = viewer.selected();
- const result = await engine.apply(page, ops, coalesce);
+ const result = await engine.apply(page, resolved, coalesce);
// A drag's later steps coalesce into its first: keep that one's.
if (result.undoStep !== null && !stepSelections.has(result.undoStep)) {
stepSelections.set(result.undoStep, { page, before });
@@ -536,6 +544,24 @@ export function createFigEditor(options: FigEditorOptions) {
return apply([{ op: 'set', ids: targets, props: patch }], coalesce);
};
+ const toggleLocked = (targets = ids()) => {
+ const page = viewer.page();
+ return apply(async (currentPage) => {
+ if (currentPage !== page || targets.length === 0) return [];
+ // Read after queued and remote edits, never from the inspector or a
+ // cached layer row. Several layers unlock only when all are locked.
+ const rows = await engine.rows(page, targets);
+ if (rows.length === 0) return [];
+ return [
+ {
+ op: 'set',
+ ids: rows.map((row) => row.id),
+ props: { locked: rows.some((row) => !row.locked) },
+ },
+ ];
+ });
+ };
+
const deleteSelection = async () => {
const targets = editableIds();
if (targets.length === 0) return;
@@ -1007,17 +1033,22 @@ export function createFigEditor(options: FigEditorOptions) {
const key = `drag-${++dragKey}`;
let applied = { x: 0, y: 0 };
let wanted = { x: 0, y: 0 };
- let running = false;
+ let running: Promise<void> | undefined;
const pump = async () => {
- if (running) return;
- running = true;
- while (wanted.x !== applied.x || wanted.y !== applied.y) {
- const dx = wanted.x - applied.x;
- const dy = wanted.y - applied.y;
- applied = { ...wanted };
- await apply([{ op: 'translate', ids: targets, dx, dy }], key);
+ if (running) return running;
+ running = (async () => {
+ while (wanted.x !== applied.x || wanted.y !== applied.y) {
+ const dx = wanted.x - applied.x;
+ const dy = wanted.y - applied.y;
+ applied = { ...wanted };
+ await apply([{ op: 'translate', ids: targets, dx, dy }], key);
+ }
+ })();
+ try {
+ await running;
+ } finally {
+ running = undefined;
}
- running = false;
};
return {
/** Total page-space offset from the drag's start. */
@@ -1025,12 +1056,17 @@ export function createFigEditor(options: FigEditorOptions) {
wanted = { x: dx, y: dy };
void pump();
},
- async end() {
+ async end(at?: Point) {
await pump();
- // Settle what was dragged into its auto layout slot.
- if (applied.x !== 0 || applied.y !== 0)
- await apply([{ op: 'reflow', ids: targets }], key);
await queue;
+ if (applied.x !== 0 || applied.y !== 0) {
+ const ops = at
+ ? await resolveFrameDrop(engine, viewer.page(), targets, at)
+ : [];
+ ops.push({ op: 'reflow', ids: targets });
+ await apply(ops, key);
+ if (at) await viewer.selectIds(targets);
+ }
},
};
};
@@ -1048,15 +1084,19 @@ export function createFigEditor(options: FigEditorOptions) {
let applied = { x: 0, y: 0 };
let moved = { x: 0, y: 0 };
let timer: ReturnType<typeof setTimeout> | undefined;
- const step = async (last: boolean) => {
+ const step = async (last: boolean, at?: Point) => {
const dx = wanted.x - applied.x;
const dy = wanted.y - applied.y;
applied = { ...wanted };
const ops: Op[] =
dx !== 0 || dy !== 0 ? [{ op: 'translate', ids: targets, dx, dy }] : [];
- // Settle what was dragged into its auto layout slot.
- if (last && (applied.x !== 0 || applied.y !== 0))
+ if (last && (applied.x !== 0 || applied.y !== 0)) {
+ if (at)
+ ops.push(
+ ...(await resolveFrameDrop(engine, viewer.page(), targets, at))
+ );
ops.push({ op: 'reflow', ids: targets });
+ }
const result = await apply(ops, key, !last);
if (result) moved = { x: moved.x + dx, y: moved.y + dy };
};
@@ -1069,10 +1109,12 @@ export function createFigEditor(options: FigEditorOptions) {
void step(false);
}, GESTURE_PUSH_MS);
},
- async end() {
+ async end(at?: Point) {
clearTimeout(timer);
timer = undefined;
- await step(true);
+ await queue;
+ await step(true, at);
+ if (at) await viewer.selectIds(targets);
return moved;
},
};
@@ -1313,6 +1355,7 @@ export function createFigEditor(options: FigEditorOptions) {
undo: () => history('undo'),
redo: () => history('redo'),
setProps,
+ toggleLocked,
deleteSelection,
duplicateSelection,
group,
diff --git a/apps/web/src/features/block-fig/primitives/create-tile-compositor.test.ts b/apps/web/src/features/block-fig/primitives/create-tile-compositor.test.ts
index 84827e0bfd..210cf06150 100644
--- a/apps/web/src/features/block-fig/primitives/create-tile-compositor.test.ts
+++ b/apps/web/src/features/block-fig/primitives/create-tile-compositor.test.ts
@@ -38,6 +38,89 @@ function fakeEngine() {
}
describe('tile compositor', () => {
+ it('coalesces interactive edits and retains a complete frame until sharp tiles are ready', async () => {
+ const { engine, queued, finishAll } = fakeEngine();
+ const compositor = createTileCompositor({ engine, onTile: () => {} });
+ const view = {
+ camera: { x: 0, y: 0, zoom: 1 },
+ viewport: { w: 1200, h: 900 },
+ dpr: 2,
+ };
+ const content = { x: 0, y: 0, w: 1200, h: 900 };
+ compositor.setPage({
+ page: 0,
+ outline: false,
+ content,
+ background: '#fff',
+ });
+ compositor.update(view);
+ await finishAll();
+ compositor.beginInteractive();
+ expect(queued).toHaveLength(1);
+ expect(queued[0].tile.width).toBe(512);
+ expect(queued[0].tile.height).toBe(384);
+ for (let i = 0; i < 20; i++) compositor.invalidate(content);
+ // Pointer updates never build a queue of stale frames or sharp tiles.
+ expect(queued).toHaveLength(1);
+ await finishAll();
+ expect(queued).toHaveLength(1);
+ await finishAll();
+ const painted: unknown[][] = [];
+ const ctx = {
+ canvas: { width: 2400, height: 1800 },
+ fillRect() {},
+ drawImage(...args: unknown[]) {
+ painted.push(args);
+ },
+ } as unknown as CanvasRenderingContext2D;
+ compositor.draw(ctx, view);
+ expect(painted).toHaveLength(1);
+ expect(painted[0].slice(1)).toEqual([0, 0, 2400, 1800]);
+ compositor.endInteractive();
+ painted.length = 0;
+ compositor.draw(ctx, view);
+ expect(painted).toHaveLength(1);
+ await finishAll();
+ painted.length = 0;
+ compositor.draw(ctx, view);
+ expect(painted.length).toBeGreaterThan(1);
+ compositor.dispose();
+ });
+
+ it('reports readiness only after painting content, including empty pages', async () => {
+ const { engine, finishAll } = fakeEngine();
+ const compositor = createTileCompositor({ engine, onTile: () => {} });
+ const view = {
+ camera: { x: 0, y: 0, zoom: 1 },
+ viewport: { w: 512, h: 512 },
+ dpr: 1,
+ };
+ const ctx = {
+ canvas: { width: 512, height: 512 },
+ fillRect() {},
+ drawImage() {},
+ } as unknown as CanvasRenderingContext2D;
+ expect(compositor.draw(ctx, view)).toBe(false);
+ compositor.setPage({
+ page: 0,
+ outline: false,
+ content: { x: 0, y: 0, w: 512, h: 512 },
+ background: '#fff',
+ });
+ compositor.update(view);
+ expect(compositor.draw(ctx, view)).toBe(false);
+ await finishAll();
+ expect(compositor.draw(ctx, view)).toBe(true);
+ compositor.setPage({
+ page: 1,
+ outline: false,
+ content: undefined,
+ background: '#fff',
+ });
+ expect(compositor.draw(ctx, view)).toBe(true);
+ compositor.dispose();
+ });
+
it('re-renders the overview after the view when an edit changes it', async () => {
const { engine, queued, finishAll } = fakeEngine();
const compositor = createTileCompositor({ engine, onTile: () => {} });
@@ -52,12 +135,21 @@ describe('tile compositor', () => {
content: { x: 0, y: 0, w: 4096, h: 4096 },
background: '#fff',
});
- // Opening: the overview comes first.
+ // Opening: one coarse tile comes first, not sixteen detailed ones.
const overview = queued.filter((q) => q.tile.scale < 0.9);
- expect(overview.length).toBe(16);
+ expect(overview.length).toBe(1);
expect(overview.every((q) => q.tile.priority === -1)).toBe(true);
compositor.update(view);
await finishAll();
+ // Once settled, the detailed overview is queued behind the view.
+ await new Promise((r) => setTimeout(r, 150));
+ expect(queued.filter((q) => q.tile.scale === 0.5)).toHaveLength(16);
+ expect(
+ queued
+ .filter((q) => q.tile.scale === 0.5)
+ .every((q) => q.tile.priority === Number.MAX_SAFE_INTEGER)
+ ).toBe(true);
+ await finishAll();
compositor.invalidate({ x: 10, y: 10, w: 50, h: 50 });
// At once, only the changed tile in view (a drag's every step).
diff --git a/apps/web/src/features/block-fig/primitives/create-tile-compositor.ts b/apps/web/src/features/block-fig/primitives/create-tile-compositor.ts
index 8bc85db4cc..c9b3c312ff 100644
--- a/apps/web/src/features/block-fig/primitives/create-tile-compositor.ts
+++ b/apps/web/src/features/block-fig/primitives/create-tile-compositor.ts
@@ -93,6 +93,8 @@ export interface PageState {
/** Longest side of the overview, in device pixels. */
const OVERVIEW_SIDE = 2048;
+/** A quick first image, before rendering the visible area at full detail. */
+const FIRST_OVERVIEW_SIDE = 512;
/** Quiet time after which the view counts as settled. */
const SETTLE_MS = 100;
/** Quiet time after an edit before tiles out of view are re-rendered. */
@@ -157,6 +159,85 @@ export function createTileCompositor(options: TileCompositorOptions) {
let landTimer: ReturnType<typeof setTimeout> | undefined;
/** Render timings, for diagnostics. */
const stats = { rendered: 0, millis: 0 };
+ // Effects that cross layer boundaries cannot use a lifted sprite. During
+ // those gestures, replace complete viewport frames instead of mixing tiles
+ // from different edit positions. Keep only one render in flight.
+ let interactive = false;
+ let preview: { bitmap: ImageBitmap; view: ViewState } | undefined;
+ let previewPending: PendingTile | undefined;
+ let previewDirty = false;
+ let previewGeneration = 0;
+ let previewPixels = 512;
+
+ const clearPreview = () => {
+ previewGeneration++;
+ preview?.bitmap.close();
+ preview = undefined;
+ if (previewPending) engine.cancel([previewPending.id]);
+ previewPending = undefined;
+ previewDirty = false;
+ };
+
+ const renderPreview = async () => {
+ if (previewPending || !previewDirty || !lastView || !page) return;
+ const view = lastView;
+ const { w, h } = view.viewport;
+ if (w <= 0 || h <= 0) return;
+ previewDirty = false;
+ const epoch = previewGeneration;
+ const ratio = Math.min(view.dpr, previewPixels / Math.max(w, h));
+ const job = engine.render({
+ page: page.page,
+ x: view.camera.x,
+ y: view.camera.y,
+ scale: view.camera.zoom * ratio,
+ width: Math.max(1, Math.ceil(w * ratio)),
+ height: Math.max(1, Math.ceil(h * ratio)),
+ outline: page.outline,
+ priority: -4_000_000,
+ });
+ previewPending = job;
+ try {
+ const result = await job.promise;
+ if (!result) return;
+ if (disposed || epoch !== previewGeneration) {
+ result.bitmap.close();
+ return;
+ }
+ preview?.bitmap.close();
+ preview = { bitmap: result.bitmap, view };
+ // Keep expensive blur/shadow scenes near a 20ms raster budget while
+ // moving. Full-resolution tiles replace this preview after release.
+ const adjustment = Math.max(
+ 0.75,
+ Math.min(1.25, Math.sqrt(20 / Math.max(1, result.millis)))
+ );
+ previewPixels = Math.max(384, Math.min(768, previewPixels * adjustment));
+ options.onTile();
+ } finally {
+ if (previewPending?.id === job.id) {
+ previewPending = undefined;
+ if (previewDirty) void requestPreview();
+ }
+ }
+ };
+
+ const requestPreview = async () => {
+ try {
+ await renderPreview();
+ } catch {
+ /* Keep the last complete frame. */
+ }
+ };
+
+ const sharp = (view: ViewState) => {
+ const target = quantizeScale(view.camera.zoom * view.dpr);
+ return tilesFor(view.camera, view.viewport, target, 0).every((key) => {
+ if (page?.content && !tileTouches(key, page.content)) return true;
+ const entry = cache.get(tileId(key));
+ return !!entry?.bitmap && !entry.stale && !entry.pending;
+ });
+ };
const evict = () => {
const live = [...cache.values()].filter((e) => !e.pinned && e.bitmap);
@@ -255,15 +336,15 @@ export function createTileCompositor(options: TileCompositorOptions) {
render(entry, priority);
};
- const overviewScale = () => {
+ const overviewScale = (side: number) => {
const c = page?.content;
if (!c || !(c.w > 0 && c.h > 0)) return undefined;
- return quantizeScale(Math.min(OVERVIEW_SIDE / Math.max(c.w, c.h), 64));
+ return quantizeScale(Math.min(side / Math.max(c.w, c.h), 64));
};
/** The overview's tiles, first of all unless `priority` says otherwise. */
- const requestOverview = (priority = -1) => {
- const scale = overviewScale();
+ const requestOverview = (priority = -1, pixels = OVERVIEW_SIDE) => {
+ const scale = overviewScale(pixels);
const c = page?.content;
if (!scale || !c) return;
const side = TILE / scale;
@@ -324,6 +405,11 @@ export function createTileCompositor(options: TileCompositorOptions) {
* overview's once edits pause (behind the view's).
*/
const afterEdit = () => {
+ if (interactive) {
+ previewDirty = true;
+ void requestPreview();
+ return;
+ }
if (lastView) schedule(lastView, false);
clearTimeout(editTimer);
editTimer = setTimeout(() => {
@@ -554,8 +640,34 @@ export function createTileCompositor(options: TileCompositorOptions) {
return {
stats,
+ /** Whole-frame fallback for moves whose effects cannot be lifted. */
+ beginInteractive() {
+ interactive = true;
+ clearTimeout(settleTimer);
+ clearTimeout(editTimer);
+ const cancelled: number[] = [];
+ for (const [id, entry] of cache) {
+ if (entry.pending) cancelled.push(entry.pending.id);
+ entry.pending = undefined;
+ if (!entry.bitmap) cache.delete(id);
+ }
+ engine.cancel(cancelled);
+ previewDirty = true;
+ void requestPreview();
+ },
+
+ endInteractive() {
+ interactive = false;
+ // The complete preview stays visible until every final visible tile
+ // is ready; never reveal a checkerboard of old and new positions.
+ afterEdit();
+ options.onTile();
+ },
+
/** Starts over for a page (or after switching outline view). */
setPage(next: PageState) {
+ interactive = false;
+ clearPreview();
unlift();
for (const l of landing.splice(0)) discard(l);
for (const e of cache.values()) {
@@ -565,7 +677,7 @@ export function createTileCompositor(options: TileCompositorOptions) {
cache.clear();
generation++;
page = next;
- requestOverview();
+ requestOverview(-1, FIRST_OVERVIEW_SIDE);
if (lastView) schedule(lastView, true);
},
@@ -580,16 +692,43 @@ export function createTileCompositor(options: TileCompositorOptions) {
/** Call on every view change; fetches what the view needs. */
update(view: ViewState) {
lastView = view;
+ if (interactive) {
+ previewDirty = true;
+ void requestPreview();
+ return;
+ }
requestLift();
schedule(view, false);
clearTimeout(settleTimer);
settleTimer = setTimeout(() => {
- if (lastView && !disposed) schedule(lastView, true);
+ if (lastView && !disposed) {
+ schedule(lastView, true);
+ requestOverview(AFTER_VIEW);
+ }
}, SETTLE_MS);
},
- /** Draws the view from the tiles available now. */
+ /** Draws available tiles; returns whether content (or an empty page) is ready. */
draw(ctx: CanvasRenderingContext2D, view: ViewState) {
+ if (!interactive && (preview || previewPending) && sharp(view))
+ clearPreview();
+ if (preview) {
+ const { camera, viewport, dpr } = view;
+ const old = preview.view;
+ const scale = (camera.zoom / old.camera.zoom) * dpr;
+ ctx.fillStyle = page?.background ?? '#f5f5f5';
+ ctx.fillRect(0, 0, viewport.w * dpr, viewport.h * dpr);
+ ctx.imageSmoothingEnabled = true;
+ ctx.imageSmoothingQuality = 'low';
+ ctx.drawImage(
+ preview.bitmap,
+ (old.camera.x - camera.x) * camera.zoom * dpr,
+ (old.camera.y - camera.y) * camera.zoom * dpr,
+ old.viewport.w * scale,
+ old.viewport.h * scale
+ );
+ return true;
+ }
// In order: a newer drop may sit on top of an older one's parts.
while (landing.length > 0 && landed(landing[0], view)) {
const done = landing.shift();
@@ -600,7 +739,7 @@ export function createTileCompositor(options: TileCompositorOptions) {
const height = ctx.canvas.height;
ctx.fillStyle = page?.background ?? '#f5f5f5';
ctx.fillRect(0, 0, width, height);
- if (!page) return;
+ if (!page) return false;
const target = quantizeScale(camera.zoom * dpr);
const unit = camera.zoom * dpr;
// Coarse scales first, then sharper ones on top; far sharper tiles
@@ -683,6 +822,12 @@ export function createTileCompositor(options: TileCompositorOptions) {
}
for (const l of landing) drawLift(ctx, view, l);
if (lift) drawLift(ctx, view, lift);
+ return (
+ draws.length > 0 ||
+ !page.content ||
+ page.content.w <= 0 ||
+ page.content.h <= 0
+ );
},
/**
@@ -797,6 +942,7 @@ export function createTileCompositor(options: TileCompositorOptions) {
dispose() {
disposed = true;
+ clearPreview();
unlift();
for (const l of landing.splice(0)) discard(l);
clearTimeout(landTimer);
diff --git a/apps/web/src/features/block-fig/primitives/resolve-frame-drop.ts b/apps/web/src/features/block-fig/primitives/resolve-frame-drop.ts
new file mode 100644
index 0000000000..5cca0469b3
--- /dev/null
+++ b/apps/web/src/features/block-fig/primitives/resolve-frame-drop.ts
@@ -0,0 +1,97 @@
+import type { FigEngine } from '@core/fig-engine/client';
+import type { NodeGeometry } from '@core/fig-engine/types';
+import type { Point } from '../core/camera';
+import type { Op } from './create-fig-editor';
+
+function contains(geometry: NodeGeometry, point: Point) {
+ const cross = geometry.corners.map(({ x, y }, i, corners) => {
+ const next = corners[(i + 1) % corners.length];
+ return (next.x - x) * (point.y - y) - (next.y - y) * (point.x - x);
+ });
+ return (
+ cross.some((n) => Math.abs(n) > 0.001) &&
+ (cross.every((n) => n >= -0.001) || cross.every((n) => n <= 0.001))
+ );
+}
+
+/** Resolve a drop without letting the moving layers obscure its target. */
+export async function resolveFrameDrop(
+ engine: FigEngine,
+ page: number,
+ ids: string[],
+ point: Point
+): Promise<Op[]> {
+ const excluded = new Set(ids);
+ const find = async (parent?: string): Promise<string | undefined> => {
+ const rows = (await engine.layers(page, parent)).filter(
+ (r) =>
+ r.visible &&
+ !r.locked &&
+ !r.inInstance &&
+ !excluded.has(r.id) &&
+ ['FRAME', 'SYMBOL', 'SECTION', 'GROUP'].includes(r.type)
+ );
+ const geometry = await engine.geometry(
+ page,
+ rows.map((r) => r.id)
+ );
+ // Layer rows are in front-to-back paint order. Only visit the branch
+ // under the pointer, and never descend into the dragged subtree.
+ for (const row of rows) {
+ const bounds = geometry.find((g) => g.id === row.id);
+ if (!bounds || !contains(bounds, point)) continue;
+ const nested = row.childCount ? await find(row.id) : undefined;
+ if (nested) return nested;
+ if (row.type !== 'GROUP') return row.id;
+ }
+ };
+ const frame = await find();
+ const ancestry = await Promise.all(
+ ids.map((id) => engine.ancestry(page, id))
+ );
+ // Retain existing groups when moving inside their enclosing frame.
+ const moving = ids.filter((_, i) => {
+ const containers = ancestry[i]
+ .slice(0, -1)
+ .filter((r) => ['FRAME', 'SYMBOL', 'SECTION'].includes(r.type));
+ return containers.at(-1)?.id !== frame;
+ });
+ if (!moving.length) return [];
+ const parent = frame ?? (await engine.currentSummary()).pages[page].id;
+ const children = (await engine.layers(page, frame)).reverse();
+ const info = frame ? await engine.nodeInfo(page, frame) : undefined;
+ let index = children.length;
+ const auto = info?.autoLayout;
+ if (frame && auto && ['HORIZONTAL', 'VERTICAL'].includes(auto.mode)) {
+ const [geometry] = await engine.geometry(page, [frame]);
+ const origin = geometry.corners[0];
+ const end = geometry.corners[auto.mode === 'HORIZONTAL' ? 1 : 3];
+ const project = (x: number, y: number) =>
+ (x - origin.x) * (end.x - origin.x) + (y - origin.y) * (end.y - origin.y);
+ const at = project(point.x, point.y);
+ const candidates = children.filter((r) => r.visible && !excluded.has(r.id));
+ const details = await Promise.all(
+ candidates.map((r) => engine.nodeInfo(page, r.id))
+ );
+ const geometryRows = await engine.geometry(
+ page,
+ candidates.map((r) => r.id)
+ );
+ for (const child of details) {
+ if (child.layoutParent === 'ABSOLUTE') continue;
+ const g = geometryRows.find((g) => g.id === child.id)!;
+ const center = {
+ x: (g.corners[0].x + g.corners[2].x) / 2,
+ y: (g.corners[0].y + g.corners[2].y) / 2,
+ };
+ if (at < project(center.x, center.y)) {
+ index = children.findIndex((r) => r.id === child.id);
+ break;
+ }
+ }
+ }
+ const ops: Op[] = [{ op: 'reorder', ids: moving, parent, index }];
+ if (auto)
+ ops.push({ op: 'set', ids: moving, props: { layoutPositioning: 'AUTO' } });
+ return ops;
+}
diff --git a/apps/web/src/features/block-fig/queries/fig-sharing.test.ts b/apps/web/src/features/block-fig/queries/fig-sharing.test.ts
new file mode 100644
index 0000000000..7ab800f3bf
--- /dev/null
+++ b/apps/web/src/features/block-fig/queries/fig-sharing.test.ts
@@ -0,0 +1,44 @@
+import type { FigEngine } from '@core/fig-engine/client';
+import { LoroDoc } from 'loro-crdt';
+import { describe, expect, it, vi } from 'vitest';
+import { seedDesign } from '../core/collab-entries';
+import { shareFigEngine } from './fig-sharing';
+
+describe('joining a shared design', () => {
+ it('does not force a scene or full decode for metadata alone', async () => {
+ const doc = new LoroDoc();
+ seedDesign(doc);
+ const engine = {
+ enableCollab: vi.fn().mockResolvedValue([]),
+ applyRemote: vi.fn().mockResolvedValue({}),
+ };
+ const sharing = await shareFigEngine(engine as unknown as FigEngine, doc, {
+ fingerprint: 'file',
+ });
+ expect(engine.enableCollab).toHaveBeenCalledTimes(1);
+ expect(engine.applyRemote).not.toHaveBeenCalled();
+ sharing.close();
+ });
+
+ it('still replays existing edits before the design becomes editable', async () => {
+ const doc = new LoroDoc();
+ seedDesign(doc);
+ const engine = {
+ enableCollab: vi.fn().mockResolvedValue([]),
+ applyRemote: vi.fn().mockResolvedValue({}),
+ };
+ const first = await shareFigEngine(engine as unknown as FigEngine, doc, {
+ fingerprint: 'file',
+ });
+ first.close();
+ doc.getMap('figNodes').set('1:2', 'encoded-node');
+ doc.commit();
+ const sharing = await shareFigEngine(engine as unknown as FigEngine, doc, {
+ fingerprint: 'file',
+ });
+ expect(engine.applyRemote).toHaveBeenCalledWith(0, [
+ { container: 'figNodes', key: '1:2', value: 'encoded-node' },
+ ]);
+ sharing.close();
+ });
+});
diff --git a/apps/web/src/features/block-fig/queries/fig-sharing.ts b/apps/web/src/features/block-fig/queries/fig-sharing.ts
index fd08528d20..e95dd41ce0 100644
--- a/apps/web/src/features/block-fig/queries/fig-sharing.ts
+++ b/apps/web/src/features/block-fig/queries/fig-sharing.ts
@@ -111,7 +111,10 @@ export async function shareFigEngine(
});
// Everything shared before this person arrived.
- await engine.applyRemote(0, readEntries(doc));
+ const entries = readEntries(doc).filter(
+ (entry) => entry.container !== 'figMeta'
+ );
+ if (entries.length > 0) await engine.applyRemote(0, entries);
return {
pull: async (page: number): Promise<EditResult | null> => {
diff --git a/apps/web/src/features/block-fig/queries/prepare-engine.test.ts b/apps/web/src/features/block-fig/queries/prepare-engine.test.ts
new file mode 100644
index 0000000000..186a62a510
--- /dev/null
+++ b/apps/web/src/features/block-fig/queries/prepare-engine.test.ts
@@ -0,0 +1,62 @@
+import { FigEngine } from '@core/fig-engine/client';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { fileFingerprint } from '../core/collab-entries';
+import { prepareFigEngine } from './prepare-engine';
+
+vi.mock('@core/fig-engine/client', () => ({ FigEngine: { open: vi.fn() } }));
+vi.mock('../core/collab-entries', () => ({ fileFingerprint: vi.fn() }));
+
+afterEach(() => vi.resetAllMocks());
+
+function setup() {
+ const engine = { close: vi.fn() } as unknown as FigEngine;
+ vi.mocked(FigEngine.open).mockResolvedValue(engine);
+ vi.mocked(fileFingerprint).mockResolvedValue('fingerprint');
+ return engine;
+}
+
+describe('preparing a design while sync connects', () => {
+ it('opens immediately and transfers ownership only once', async () => {
+ const engine = setup();
+ const opening = prepareFigEngine(new ArrayBuffer(0));
+ expect(FigEngine.open).toHaveBeenCalledTimes(1);
+ expect(fileFingerprint).toHaveBeenCalledTimes(1);
+ expect((await opening.take(vi.fn())).engine).toBe(engine);
+ await opening.dispose();
+ expect(engine.close).not.toHaveBeenCalled();
+ });
+
+ it('releases an abandoned open after it finishes', async () => {
+ const engine = setup();
+ let finish!: (engine: FigEngine) => void;
+ vi.mocked(FigEngine.open).mockReturnValue(
+ new Promise((resolve) => {
+ finish = resolve;
+ })
+ );
+ const opening = prepareFigEngine(new ArrayBuffer(0));
+ const disposed = opening.dispose();
+ finish(engine);
+ await disposed;
+ expect(engine.close).toHaveBeenCalledTimes(1);
+ await expect(opening.take(vi.fn())).rejects.toThrow('closed');
+ });
+
+ it('opens a fresh engine when a replacement shared document mounts', async () => {
+ setup();
+ const opening = prepareFigEngine(new ArrayBuffer(0));
+ await opening.take(vi.fn());
+ await opening.take(vi.fn());
+ expect(FigEngine.open).toHaveBeenCalledTimes(2);
+ await opening.dispose();
+ });
+
+ it('closes the engine if fingerprinting fails', async () => {
+ const engine = setup();
+ vi.mocked(fileFingerprint).mockRejectedValue(new Error('hash failed'));
+ const opening = prepareFigEngine(new ArrayBuffer(0));
+ await expect(opening.take(vi.fn())).rejects.toThrow('hash failed');
+ expect(engine.close).toHaveBeenCalledTimes(1);
+ await opening.dispose();
+ });
+});
diff --git a/apps/web/src/features/block-fig/queries/prepare-engine.ts b/apps/web/src/features/block-fig/queries/prepare-engine.ts
new file mode 100644
index 0000000000..ee102ce7d7
--- /dev/null
+++ b/apps/web/src/features/block-fig/queries/prepare-engine.ts
@@ -0,0 +1,63 @@
+import { FigEngine } from '@core/fig-engine/client';
+import { fileFingerprint } from '../core/collab-entries';
+
+/** Open and fingerprint concurrently; the caller owns the resulting engine. */
+export async function openFigEngine(
+ bytes: ArrayBuffer,
+ onFailure: (error: Error) => void
+) {
+ const [opened, fingerprint] = await Promise.allSettled([
+ FigEngine.open(bytes, { onFailure }),
+ fileFingerprint(bytes),
+ ]);
+ if (opened.status === 'rejected') throw opened.reason;
+ if (fingerprint.status === 'rejected') {
+ opened.value.close();
+ throw fingerprint.reason;
+ }
+ return { engine: opened.value, fingerprint: fingerprint.value };
+}
+
+/**
+ * Start parsing while the collaboration transport connects. A host takes
+ * ownership once sync is ready. Recovery hosts always open a fresh engine,
+ * so a replaced Loro document never inherits edits from the old instance.
+ */
+export function prepareFigEngine(bytes: ArrayBuffer) {
+ let claimed = false;
+ let disposed = false;
+ let failure: Error | undefined;
+ let reportFailure: ((error: Error) => void) | undefined;
+ const pending = start();
+
+ async function start() {
+ try {
+ const opened = await openFigEngine(bytes, (error) => {
+ failure = error;
+ reportFailure?.(error);
+ });
+ return { opened };
+ } catch (error) {
+ // Keep an early failure handled until the host takes the result.
+ return { error };
+ }
+ }
+
+ return {
+ async take(onFailure: (error: Error) => void) {
+ if (disposed) throw new Error('The design was closed.');
+ if (claimed) return openFigEngine(bytes, onFailure);
+ claimed = true;
+ reportFailure = onFailure;
+ if (failure) onFailure(failure);
+ const result = await pending;
+ if (!result.opened) throw result.error;
+ return result.opened;
+ },
+ async dispose() {
+ disposed = true;
+ const result = await pending;
+ if (!claimed) result.opened?.engine.close();
+ },
+ };
+}
diff --git a/apps/web/src/features/block-fig/views/assets-panel.tsx b/apps/web/src/features/block-fig/views/assets-panel.tsx
index a02411e732..5bcb3786a8 100644
--- a/apps/web/src/features/block-fig/views/assets-panel.tsx
+++ b/apps/web/src/features/block-fig/views/assets-panel.tsx
@@ -4,12 +4,17 @@
* instance in the middle of the view; anyone can jump to a main component.
*/
+import { IS_MAC } from '@core/constant/isMac';
import type { FigEngine } from '@core/fig-engine/client';
import type { ComponentInfo } from '@core/fig-engine/types';
import ArrowSquareOut from '@phosphor/arrow-square-out.svg';
import DiamondsFour from '@phosphor/diamonds-four.svg';
+import List from '@phosphor/list.svg';
import MagnifyingGlass from '@phosphor/magnifying-glass.svg';
+import SquaresFour from '@phosphor/squares-four.svg';
+import X from '@phosphor/x.svg';
import { createMemo, createResource, createSignal, For, Show } from 'solid-js';
+import { ComponentPreview } from '../components/component-preview';
import type { FigEditor } from '../primitives/create-fig-editor';
import type { FigLibraries } from '../primitives/create-fig-libraries';
import type { FigViewer } from '../primitives/create-fig-viewer';
@@ -24,6 +29,25 @@ export function AssetsPanel(props: {
fileName?: string;
}) {
const [query, setQuery] = createSignal('');
+ const [grid, setGrid] = createSignal(true);
+ const previews = new Map<string, { revision: number; blob: Promise<Blob> }>();
+ const thumbnail = (component: ComponentInfo) => {
+ const revision = props.viewer.editsSettled();
+ const cached = previews.get(component.id);
+ if (cached?.revision === revision) return cached.blob;
+ const scale = Math.min(
+ 1,
+ 192 / Math.max(component.width, component.height, 1)
+ );
+ const blob = props.engine.exportPng(component.page, component.id, scale);
+ previews.set(component.id, { revision, blob });
+ // Browsing a large library should not retain every preview in memory.
+ if (previews.size > 64) {
+ const oldest = previews.keys().next().value;
+ if (oldest) previews.delete(oldest);
+ }
+ return blob;
+ };
// File-wide, so once per pause in a stream of edits (a drag's steps).
const [components] = createResource(
() => props.viewer.editsSettled(),
@@ -50,16 +74,8 @@ export function AssetsPanel(props: {
return (
<div class="flex min-h-0 flex-1 flex-col" data-testid="fig-assets">
- <label class="flex items-center gap-2 border-edge-muted border-b px-3 py-2 text-xs">
- <MagnifyingGlass class="size-3.5 text-ink-muted" />
- <input
- class="min-w-0 flex-1 bg-transparent text-ink outline-none placeholder:text-ink-placeholder"
- placeholder="Search components"
- data-testid="fig-assets-search"
- value={query()}
- onInput={(e) => setQuery(e.currentTarget.value)}
- onKeyDown={(e) => e.stopPropagation()}
- />
+ <div class="flex h-10 shrink-0 items-center justify-between px-3 text-xs">
+ <span class="font-medium">Assets</span>
<Show when={props.libraries}>
{(libraries) => (
<LibrariesButton
@@ -68,7 +84,58 @@ export function AssetsPanel(props: {
/>
)}
</Show>
- </label>
+ </div>
+ <div class="flex items-center gap-1 px-3 pb-3 text-xs">
+ <label class="flex min-w-0 flex-1 items-center gap-2 rounded-md bg-inset px-2 py-1.5 focus-within:ring-1 focus-within:ring-accent">
+ <MagnifyingGlass class="size-3.5 shrink-0 text-ink-muted" />
+ <input
+ class="min-w-0 flex-1 bg-transparent text-ink outline-none placeholder:text-ink-placeholder"
+ placeholder="Search all libraries"
+ aria-label="Search assets"
+ data-testid="fig-assets-search"
+ value={query()}
+ onInput={(e) => setQuery(e.currentTarget.value)}
+ onKeyDown={(e) => e.stopPropagation()}
+ />
+ </label>
+ <Show when={query()}>
+ <button
+ type="button"
+ aria-label="Clear asset search"
+ class="rounded p-1 text-ink-muted hover:bg-hover"
+ onClick={() => setQuery('')}
+ >
+ <X class="size-3.5" />
+ </button>
+ </Show>
+ </div>
+ <div class="flex items-center justify-between px-3 pb-2 text-xs">
+ <span class="font-medium">Created in this file</span>
+ <div class="flex items-center gap-0.5">
+ <button
+ type="button"
+ aria-label="Grid view"
+ title="Grid view"
+ aria-pressed={grid()}
+ data-testid="fig-assets-grid"
+ class="rounded p-1 text-ink-muted hover:bg-hover aria-pressed:bg-hover aria-pressed:text-ink"
+ onClick={() => setGrid(true)}
+ >
+ <SquaresFour class="size-3.5" />
+ </button>
+ <button
+ type="button"
+ aria-label="List view"
+ title="List view"
+ aria-pressed={!grid()}
+ data-testid="fig-assets-list"
+ class="rounded p-1 text-ink-muted hover:bg-hover aria-pressed:bg-hover aria-pressed:text-ink"
+ onClick={() => setGrid(false)}
+ >
+ <List class="size-3.5" />
+ </button>
+ </div>
+ </div>
<div class="min-h-0 flex-1 overflow-y-auto py-1 text-xs">
<Show
when={groups().length > 0}
@@ -76,7 +143,9 @@ export function AssetsPanel(props: {
<p class="px-3 py-2 text-ink-muted">
{query()
? 'No matching components.'
- : 'No components yet. Select layers and press ⌥⌘K.'}
+ : props.editor?.enabled()
+ ? `No components yet. Select layers and press ${IS_MAC ? '⌥⌘K' : 'Ctrl+Alt+K'}.`
+ : 'No components in this file.'}
</p>
}
>
@@ -88,40 +157,65 @@ export function AssetsPanel(props: {
{set}
</div>
</Show>
- <For each={list}>
- {(c) => (
- <div class="group flex items-center gap-2 px-3 py-1 hover:bg-hover">
- <button
- type="button"
- class="flex min-w-0 flex-1 items-center gap-2 text-left text-ink"
- data-testid="fig-asset"
- title={
- props.editor?.enabled()
- ? 'Place an instance'
- : 'Go to component'
- }
- onClick={() =>
- props.editor?.enabled()
- ? void props.editor.insertInstance(c)
- : void jump(c)
- }
+ <div classList={{ 'grid grid-cols-2 gap-2 px-3': grid() }}>
+ <For each={list}>
+ {(component) => (
+ <div
+ class="group relative min-w-0 rounded-md hover:bg-hover"
+ classList={{
+ 'flex items-center gap-2 px-3 py-2': !grid(),
+ 'p-1': grid(),
+ }}
>
- <DiamondsFour class="size-3.5 shrink-0 text-accent" />
- <span class="truncate">{c.name}</span>
- </button>
- <Show when={props.editor?.enabled()}>
<button
type="button"
- aria-label="Go to main component"
- class="rounded p-0.5 text-ink-muted opacity-0 hover:text-ink group-hover:opacity-100"
- onClick={() => void jump(c)}
+ data-testid="fig-asset"
+ aria-label={component.name}
+ class="flex min-w-0 flex-1 gap-2 text-left text-ink"
+ classList={{
+ 'w-full flex-col': grid(),
+ 'items-center': !grid(),
+ }}
+ title={
+ props.editor?.enabled()
+ ? `Place ${component.name}`
+ : `Go to ${component.name}`
+ }
+ onClick={() =>
+ props.editor?.enabled()
+ ? void props.editor.insertInstance(component)
+ : void jump(component)
+ }
>
- <ArrowSquareOut class="size-3.5" />
+ <Show
+ when={grid()}
+ fallback={
+ <DiamondsFour class="size-3.5 shrink-0 text-accent" />
+ }
+ >
+ <ComponentPreview
+ load={() => thumbnail(component)}
+ />
+ </Show>
+ <span class="w-full truncate text-[11px]">
+ {component.name}
+ </span>
</button>
- </Show>
- </div>
- )}
- </For>
+ <Show when={props.editor?.enabled()}>
+ <button
+ type="button"
+ aria-label="Go to main component"
+ class="rounded bg-panel p-1 text-ink-muted opacity-0 hover:text-ink focus-visible:opacity-100 group-hover:opacity-100"
+ classList={{ 'absolute top-2 right-2': grid() }}
+ onClick={() => void jump(component)}
+ >
+ <ArrowSquareOut class="size-3.5" />
+ </button>
+ </Show>
+ </div>
+ )}
+ </For>
+ </div>
</div>
)}
</For>
diff --git a/apps/web/src/features/block-fig/views/comments-panel.tsx b/apps/web/src/features/block-fig/views/comments-panel.tsx
index 7e81d9fb37..516cc21a08 100644
--- a/apps/web/src/features/block-fig/views/comments-panel.tsx
+++ b/apps/web/src/features/block-fig/views/comments-panel.tsx
@@ -1,127 +1,177 @@
-/**
- * The comments sidebar (the right panel while the comment tool is on):
- * every thread on the design, open or resolved, newest activity first,
- * with unread dots; a thread opens beside its pin, on its page.
- */
-
-import { For, Show } from 'solid-js';
+/** The comment tool's searchable thread list, alongside the canvas. */
+import FunnelSimple from '@phosphor/funnel-simple.svg';
+import MagnifyingGlass from '@phosphor/magnifying-glass.svg';
+import X from '@phosphor/x.svg';
+import { createMemo, createSignal, For, type JSX, Show } from 'solid-js';
import { CommentAvatar, CommentText } from '../components/comment-thread';
+import { EditorMenu } from '../components/editor-menu';
import { type CommentFilter, relativeTime } from '../core/comments';
import type { FigComments } from '../primitives/create-fig-comments';
const FILTERS: { value: CommentFilter; label: string }[] = [
- { value: 'open', label: 'Open' },
- { value: 'resolved', label: 'Resolved' },
- { value: 'all', label: 'All' },
+ { value: 'open', label: 'Open comments' },
+ { value: 'resolved', label: 'Resolved comments' },
+ { value: 'all', label: 'All comments' },
];
export function CommentsPanel(props: {
comments: FigComments;
- /** Page names by id, for threads on other pages. */
pageName: (id: string) => string | undefined;
- currentPage: string | undefined;
+ headerActions?: JSX.Element;
+ zoom?: JSX.Element;
}) {
const c = props.comments;
const now = Date.now();
+ const [query, setQuery] = createSignal('');
+ const threads = createMemo(() => {
+ const search = query().trim().toLowerCase();
+ return c
+ .listed()
+ .filter(
+ (thread) =>
+ !search ||
+ thread.comments.some((comment) =>
+ `${comment.author.name} ${comment.text}`
+ .toLowerCase()
+ .includes(search)
+ )
+ );
+ });
return (
<div
class="flex size-full min-h-0 flex-col text-ink text-xs"
data-testid="fig-comments-panel"
>
- <div class="flex h-9 shrink-0 items-center gap-1 border-edge-muted border-b px-2">
- <span class="px-1 font-medium">Comments</span>
- <div class="ml-auto flex items-center gap-0.5">
- <For each={FILTERS}>
- {(f) => (
- <button
- type="button"
- class="rounded-md px-1.5 py-1"
- classList={{
- 'bg-hover text-ink': c.filter() === f.value,
- 'text-ink-muted': c.filter() !== f.value,
- }}
- aria-pressed={c.filter() === f.value}
- data-testid={`fig-comments-filter-${f.value}`}
- onClick={() => c.setFilter(f.value)}
- >
- {f.label}
- </button>
- )}
- </For>
- </div>
+ <div class="flex h-12 shrink-0 items-center justify-end px-3">
+ {props.headerActions}
+ </div>
+ <div class="flex h-10 shrink-0 items-center justify-between border-edge-frame border-b px-3">
+ <h3 class="font-medium">Comments</h3>
+ {props.zoom}
+ </div>
+ <div class="flex shrink-0 items-center gap-1 border-edge-frame border-b px-3 py-2">
+ <label class="flex min-w-0 flex-1 items-center gap-1.5 rounded-md bg-inset px-2 py-1.5 focus-within:ring-1 focus-within:ring-accent">
+ <MagnifyingGlass class="size-3.5 shrink-0 text-ink-muted" />
+ <input
+ type="search"
+ aria-label="Search comments"
+ placeholder="Search"
+ data-testid="fig-comments-search"
+ class="min-w-0 flex-1 bg-transparent outline-none placeholder:text-ink-placeholder"
+ value={query()}
+ onInput={(e) => setQuery(e.currentTarget.value)}
+ onKeyDown={(e) => e.stopPropagation()}
+ />
+ </label>
+ <Show when={query()}>
+ <button
+ type="button"
+ aria-label="Clear comment search"
+ class="flex size-6 shrink-0 items-center justify-center rounded text-ink-muted hover:bg-hover"
+ onClick={() => setQuery('')}
+ >
+ <X class="size-3.5" />
+ </button>
+ </Show>
+ <EditorMenu
+ label="Filter comments"
+ testId="fig-comments-filter"
+ items={FILTERS.map((filter) => ({
+ label: filter.label,
+ checked: c.filter() === filter.value,
+ testId: `fig-comments-filter-${filter.value}`,
+ onSelect: () => c.setFilter(filter.value),
+ }))}
+ >
+ <FunnelSimple class="size-4" />
+ </EditorMenu>
</div>
<div class="min-h-0 flex-1 overflow-y-auto">
<Show
- when={c.listed().length > 0}
+ when={threads().length > 0}
fallback={
<p
class="px-3 py-4 text-ink-muted"
data-testid="fig-comments-empty"
>
- {c.filter() === 'resolved'
- ? 'No resolved comments.'
- : 'No comments yet. Click the canvas to add one.'}
+ {query()
+ ? 'No matching comments.'
+ : c.filter() === 'resolved'
+ ? 'No resolved comments.'
+ : c.store.canComment()
+ ? 'No comments yet. Click the canvas to add one.'
+ : 'No comments yet.'}
</p>
}
>
- <For each={c.listed()}>
+ <For each={threads()}>
{(thread) => {
const first = () => thread.comments[0];
const replies = () => thread.comments.length - 1;
- const unread = () => c.isUnread(thread);
+ const people = () =>
+ [
+ ...new Map(
+ thread.comments.map((comment) => [
+ comment.author.id,
+ comment.author,
+ ])
+ ).values(),
+ ].slice(0, 4);
const page = () =>
- thread.anchor && thread.anchor.pageId !== props.currentPage
+ thread.anchor
? props.pageName(thread.anchor.pageId)
: undefined;
return (
<button
type="button"
- class="flex w-full gap-2 border-edge-muted border-b px-3 py-2.5 text-left hover:bg-hover"
+ class="flex w-full flex-col gap-1.5 px-4 py-4 text-left hover:bg-hover"
classList={{ 'bg-hover': c.openThread() === thread.id }}
data-testid="fig-comment-row"
data-thread={thread.id}
- data-unread={unread() ? 'true' : 'false'}
+ data-unread={c.isUnread(thread) ? 'true' : 'false'}
onClick={() => void c.reveal(thread)}
>
+ <div class="mb-0.5 flex w-full items-center gap-1">
+ <For each={people()}>
+ {(person) => <CommentAvatar person={person} />}
+ </For>
+ <Show when={c.isUnread(thread)}>
+ <span
+ class="ml-auto size-1.5 rounded-full bg-accent"
+ aria-label="Unread"
+ />
+ </Show>
+ </div>
+ <Show when={page()}>
+ {(name) => <span class="text-ink-muted">{name()}</span>}
+ </Show>
+ <div class="flex w-full min-w-0 items-baseline gap-1.5">
+ <span class="truncate font-medium">
+ {first()?.author.name}
+ </span>
+ <span class="shrink-0 text-[11px] text-ink-muted">
+ {relativeTime(
+ thread.comments.at(-1)?.createdAt ?? 0,
+ now
+ )}
+ </span>
+ </div>
<Show when={first()}>
- {(f) => <CommentAvatar person={f().author} />}
+ {(comment) => (
+ <div class="line-clamp-3">
+ <CommentText comment={comment()} />
+ </div>
+ )}
</Show>
- <div class="min-w-0 flex-1">
- <div class="flex items-baseline gap-1.5">
- <span class="truncate font-medium">
- {first()?.author.name}
+ <div class="flex gap-2 text-[11px]">
+ <Show when={replies() > 0}>
+ <span class="text-accent">
+ {replies()} {replies() === 1 ? 'reply' : 'replies'}
</span>
- <span class="shrink-0 text-[11px] text-ink-muted">
- {relativeTime(
- thread.comments.at(-1)?.createdAt ?? 0,
- now
- )}
- </span>
- <Show when={unread()}>
- <span
- class="ml-auto size-2 shrink-0 rounded-full bg-accent"
- aria-label="Unread"
- />
- </Show>
- </div>
- <Show when={first()}>
- {(f) => (
- <div class="line-clamp-3">
- <CommentText comment={f()} />
- </div>
- )}
</Show>
- <div class="mt-1 flex gap-2 text-[11px] text-ink-muted">
- <Show when={replies() > 0}>
- <span>
- {replies()} {replies() === 1 ? 'reply' : 'replies'}
- </span>
- </Show>
- <Show when={thread.resolved}>
- <span>Resolved</span>
- </Show>
- <Show when={page()}>{(p) => <span>{p()}</span>}</Show>
- </div>
+ <Show when={thread.resolved}>
+ <span class="text-ink-muted">Resolved</span>
+ </Show>
</div>
</button>
);
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 40c918a8a2..5984ad0314 100644
--- a/apps/web/src/features/block-fig/views/fig-viewer.tsx
+++ b/apps/web/src/features/block-fig/views/fig-viewer.tsx
@@ -3,8 +3,10 @@
* design panel on the right, Figma's keyboard shortcuts throughout.
*/
+import '../components/editor-theme.css';
import { IS_MAC } from '@core/constant/isMac';
import type { NodeInfo, Rect } from '@core/fig-engine/types';
+import { Tabs } from '@kobalte/core/tabs';
import {
createEffect,
createSignal,
@@ -24,12 +26,16 @@ import { FigContextMenu } from '../components/fig-context-menu';
import { LayoutGridSection } from '../components/layout-grid-section';
import { MainMenu } from '../components/main-menu';
import { MissingFonts } from '../components/missing-fonts';
+import { PanelToggle } from '../components/panel-toggle';
import { FollowFrame, PeerAvatars } from '../components/peer-presence';
import { PrototypeNoodles } from '../components/prototype-noodles';
import { PrototypePanel } from '../components/prototype-panel';
-import { ReviewButtons } from '../components/review-buttons';
+import { ResizablePanel } from '../components/resizable-panel';
+import { CommentButton, PresentButton } from '../components/review-buttons';
+import { SaveIndicator } from '../components/save-indicator';
import { ShortcutsDialog } from '../components/shortcuts-dialog';
import { ViewerToolbar } from '../components/viewer-toolbar';
+import { ViewerZoom } from '../components/viewer-zoom';
import { useFigViewerContext } from '../context/fig-viewer-context';
import { type Point, zoomLabel } from '../core/camera';
import { LIBRARY_ASSET_MIME } from '../core/libraries';
@@ -115,6 +121,8 @@ export function FigViewer() {
const [deepHeld, setDeepHeld] = createSignal(false);
const [showShortcuts, setShowShortcuts] = createSignal(false);
const [showActions, setShowActions] = createSignal(false);
+ const [leftWidth, setLeftWidth] = createSignal(280);
+ const [rightWidth, setRightWidth] = createSignal(240);
const [leftTab, setLeftTab] = createSignal<'layers' | 'assets'>('layers');
const [info, setInfo] = createSignal<NodeInfo>();
const designSystem = createDesignSystem({ engine, viewer, editor });
@@ -143,7 +151,7 @@ export function FigViewer() {
devMode,
});
let root!: HTMLDivElement;
- let searchInput: HTMLInputElement | undefined;
+ let focusSearch: (() => void) | undefined;
onMount(() => {
void viewer.openPage(0);
@@ -470,7 +478,7 @@ export function FigViewer() {
viewer.setUiHidden(false);
viewer.setLayersOpen(true);
setLeftTab('layers');
- queueMicrotask(() => searchInput?.focus());
+ queueMicrotask(() => focusSearch?.());
})
.with('show-shortcuts', () => setShowShortcuts((s) => !s))
.with('open-actions', () => {
@@ -534,8 +542,7 @@ export function FigViewer() {
void editor.setProps({ visible: !visible });
})
.with('toggle-locked', () => {
- const locked = info()?.locked ?? false;
- void editor.setProps({ locked: !locked });
+ void editor.toggleLocked();
})
.with('flip-horizontal', () => void editor.flip(false))
.with('flip-vertical', () => void editor.flip(true))
@@ -710,6 +717,22 @@ export function FigViewer() {
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;
+ // Menus, tabs, and panel dividers use arrows without moving the selection.
+ if (
+ !mod &&
+ target.closest(
+ '[aria-haspopup="menu"], [aria-haspopup="true"], [role="tab"], [role="separator"]'
+ ) &&
+ [
+ 'ArrowUp',
+ 'ArrowDown',
+ 'ArrowLeft',
+ 'ArrowRight',
+ 'Home',
+ 'End',
+ ].includes(e.key)
+ )
+ return;
// A focused select or button keeps the keys it uses itself.
const control = target.closest('select, button, a[href]');
if (control && controlOwnsKey(control.tagName, e)) return;
@@ -877,59 +900,74 @@ export function FigViewer() {
<div
ref={root}
tabIndex={0}
- class="flex size-full min-h-0 bg-page outline-none"
+ class="fig-editor-theme relative flex size-full min-h-0 min-w-0 bg-page outline-none"
data-testid="fig-viewer"
onKeyDown={onPortaledKeyDown}
onKeyUp={onKeyUp}
onPaste={onPaste}
>
<Show when={showLayers()}>
- <aside
- class="flex w-60 shrink-0 flex-col border-edge-muted border-r bg-panel"
+ <ResizablePanel
+ side="left"
+ label="Pages and layers"
+ width={leftWidth()}
+ onResize={setLeftWidth}
onContextMenu={contextMenu.onLayers}
>
- <div class="flex h-9 shrink-0 items-center gap-1 border-edge-muted border-b px-2 text-xs">
- <MainMenu
- items={[
- {
- label: 'Export frames to PDF…',
- onSelect: () => void handoff.exportFramesPdf(),
- testId: 'fig-menu-export-frames-pdf',
- },
- {
- label: 'Export selection…',
- shortcut: IS_MAC ? '⇧⌘E' : 'Ctrl+⇧E',
- onSelect: () => void handoff.exportSelection(),
- testId: 'fig-menu-export-selection',
- },
- 'divider',
- ...zoomItems().filter(
- (item) =>
- item !== 'divider' &&
- (item.label === 'Layout grids' || item.label === 'Rulers')
- ),
- ]}
- />
- <For each={['layers', 'assets'] as const}>
- {(t) => (
- <button
- type="button"
- class="rounded-md px-2 py-1 font-medium"
- classList={{
- 'bg-hover text-ink': leftTab() === t,
- 'text-ink-muted': leftTab() !== t,
- }}
- data-testid={`fig-tab-${t}`}
- onClick={() => setLeftTab(t)}
- >
- {t === 'layers' ? 'Layers' : 'Assets'}
- </button>
- )}
- </For>
- </div>
- <Show
- when={leftTab() === 'layers'}
- fallback={
+ <Tabs
+ class="flex min-h-0 flex-1 flex-col"
+ value={leftTab()}
+ onChange={(value) => setLeftTab(value as 'layers' | 'assets')}
+ >
+ <div class="flex h-12 shrink-0 items-center gap-1 px-3 text-xs">
+ <MainMenu
+ canEdit={editor.enabled()}
+ hasSelection={viewer.selected().length > 0}
+ canUndo={editor.canUndo()}
+ canRedo={editor.canRedo()}
+ zoomItems={zoomItems()}
+ onRun={run}
+ onExportFramesPdf={() => void handoff.exportFramesPdf()}
+ />
+ <span
+ class="min-w-0 flex-1 truncate font-semibold"
+ title={context.fileName()}
+ >
+ {context.fileName()}
+ </span>
+ <Show when={editor.enabled()}>
+ <SaveIndicator state={editor.saveState()} />
+ </Show>
+ <PanelToggle
+ side="left"
+ open
+ onClick={() => viewer.setLayersOpen(false)}
+ />
+ </div>
+ <Tabs.List
+ class="flex h-10 shrink-0 items-center gap-1 border-edge-frame border-b px-3 text-xs"
+ aria-label="File navigation"
+ >
+ <For each={['layers', 'assets'] as const}>
+ {(t) => (
+ <Tabs.Trigger
+ value={t}
+ class="rounded-md px-2 py-1 font-medium"
+ classList={{
+ 'bg-hover text-ink': leftTab() === t,
+ 'text-ink-muted': leftTab() !== t,
+ }}
+ data-testid={`fig-tab-${t}`}
+ >
+ {t === 'layers' ? 'File' : 'Assets'}
+ </Tabs.Trigger>
+ )}
+ </For>
+ </Tabs.List>
+ <Tabs.Content
+ value="assets"
+ class="flex min-h-0 flex-1 flex-col outline-none"
+ >
<AssetsPanel
viewer={viewer}
engine={engine}
@@ -937,18 +975,22 @@ export function FigViewer() {
libraries={libraries}
fileName={context.fileName()}
/>
- }
- >
- <LayersPanel
- viewer={viewer}
- engine={engine}
- editor={editor}
- searchRef={(el) => {
- searchInput = el;
- }}
- />
- </Show>
- </aside>
+ </Tabs.Content>
+ <Tabs.Content
+ value="layers"
+ class="flex min-h-0 flex-1 flex-col outline-none"
+ >
+ <LayersPanel
+ viewer={viewer}
+ engine={engine}
+ editor={editor}
+ focusSearchRef={(focus) => {
+ focusSearch = focus;
+ }}
+ />
+ </Tabs.Content>
+ </Tabs>
+ </ResizablePanel>
</Show>
<div
class="relative min-w-0 flex-1"
@@ -1036,42 +1078,36 @@ export function FigViewer() {
Loading page…
</div>
</Show>
- <Show when={!viewer.uiHidden()}>
- <ViewerToolbar
- tool={viewer.tool()}
- onTool={(tool) => {
- if (editor.penPath()) void editor.penFinish();
- viewer.setTool(tool);
- }}
- onBoolean={
- editor.enabled() && editor.editableIds().length > 0
- ? (op) => void editor.booleanOp(op)
- : undefined
- }
- onFlatten={() => void editor.flatten()}
- editable={editor.enabled()}
- saveState={editor.saveState()}
- canUndo={editor.canUndo()}
- canRedo={editor.canRedo()}
- onUndo={() => editor.undo()}
- onRedo={() => editor.redo()}
- zoomLabel={zoomLabel(viewer.camera().zoom)}
- zoomItems={zoomItems()}
- onShortcuts={() => setShowShortcuts((s) => !s)}
- review={
- <ReviewButtons
- mac={IS_MAC}
- comments={
- review.comments && {
- active: review.comments.active(),
- unread: review.comments.unreadCount(),
- onToggle: review.toggleComments,
- }
- }
- onPresent={() => void review.present()}
+ <Show when={!viewer.uiHidden() && !showLayers()}>
+ <div class="absolute top-2 left-3 z-10 rounded-lg border border-edge-muted bg-panel p-1">
+ <PanelToggle
+ side="left"
+ open={false}
+ onClick={() => viewer.setLayersOpen(true)}
+ />
+ </div>
+ </Show>
+ <Show when={!viewer.uiHidden() && !showDesign()}>
+ <div
+ class="absolute top-2 right-3 z-10 flex items-center gap-1 rounded-lg border border-edge-muted bg-panel px-1"
+ onPointerDown={(e) => e.stopPropagation()}
+ >
+ <PresentButton
+ mac={IS_MAC}
+ onPresent={() => void review.present()}
+ />
+ <ViewerZoom
+ label={zoomLabel(viewer.camera().zoom)}
+ items={zoomItems()}
+ />
+ <Show when={!showDesign()}>
+ <PanelToggle
+ side="right"
+ open={false}
+ onClick={() => viewer.setDesignOpen(true)}
/>
- }
- />
+ </Show>
+ </div>
</Show>
<Show when={collab}>
{(c) => (
@@ -1132,18 +1168,66 @@ export function FigViewer() {
</div>
<Show when={showDesign() && review.comments?.active() && review.comments}>
{(c) => (
- <aside class="flex w-64 shrink-0 flex-col border-edge-muted border-l bg-panel">
+ <ResizablePanel
+ side="right"
+ label="Comments"
+ width={rightWidth()}
+ onResize={setRightWidth}
+ >
<CommentsPanel
comments={c()}
- currentPage={viewer.pages[viewer.page()]?.id}
+ headerActions={
+ <>
+ <PresentButton
+ mac={IS_MAC}
+ onPresent={() => void review.present()}
+ />
+ <PanelToggle
+ side="right"
+ open
+ onClick={() => viewer.setDesignOpen(false)}
+ />
+ </>
+ }
+ zoom={
+ <ViewerZoom
+ label={zoomLabel(viewer.camera().zoom)}
+ items={zoomItems()}
+ />
+ }
pageName={(id) => viewer.pages.find((p) => p.id === id)?.name}
/>
- </aside>
+ </ResizablePanel>
)}
</Show>
<Show when={showDesign() && !review.comments?.active()}>
- <aside class="flex w-64 shrink-0 flex-col border-edge-muted border-l bg-panel">
+ <ResizablePanel
+ side="right"
+ label="Properties"
+ width={rightWidth()}
+ onResize={setRightWidth}
+ >
<DesignPanel
+ tab={review.panelTab()}
+ headerActions={
+ <>
+ <PresentButton
+ mac={IS_MAC}
+ onPresent={() => void review.present()}
+ />
+ <PanelToggle
+ side="right"
+ open
+ onClick={() => viewer.setDesignOpen(false)}
+ />
+ </>
+ }
+ zoom={
+ <ViewerZoom
+ label={zoomLabel(viewer.camera().zoom)}
+ items={zoomItems()}
+ />
+ }
info={panel().info}
fontFamilies={[
...new Set([
@@ -1163,6 +1247,16 @@ export function FigViewer() {
onAlign={
editor.enabled() ? (how) => void editor.align(how) : undefined
}
+ onFlip={
+ editor.enabled()
+ ? (axis) =>
+ run(
+ axis === 'horizontal'
+ ? 'flip-horizontal'
+ : 'flip-vertical'
+ )
+ : undefined
+ }
onPatch={editor.enabled() ? patchSelection : undefined}
onPageColor={editor.enabled() ? setPageColor : undefined}
swatches={swatches()}
@@ -1235,6 +1329,12 @@ export function FigViewer() {
editor.enabled() ? (op) => void editor.booleanOp(op) : undefined
}
onFlatten={() => void editor.flatten()}
+ onCreateComponent={
+ editor.enabled() &&
+ !viewer.selected().some((node) => node.id.startsWith('I'))
+ ? () => void editor.createComponent()
+ : undefined
+ }
onCopyText={(text) => void copyText(text)}
onTabChange={review.setPanelTab}
prototype={
@@ -1266,7 +1366,36 @@ export function FigViewer() {
<LocalStylesView ds={designSystem} swatches={swatches()} />
}
/>
- </aside>
+ </ResizablePanel>
+ </Show>
+ <Show when={!viewer.uiHidden()}>
+ <ViewerToolbar
+ tool={review.comments?.active() ? undefined : viewer.tool()}
+ onTool={(tool) => {
+ review.comments?.setActive(false);
+ if (editor.penPath()) void editor.penFinish();
+ viewer.setTool(tool);
+ }}
+ editable={editor.enabled()}
+ onActions={() => setShowActions(true)}
+ devMode={review.panelTab() === 'code'}
+ onDevMode={() => {
+ viewer.setDesignOpen(true);
+ review.comments?.setActive(false);
+ review.setPanelTab((tab) => (tab === 'code' ? 'design' : 'code'));
+ }}
+ review={
+ <CommentButton
+ comments={
+ review.comments && {
+ active: review.comments.active(),
+ unread: review.comments.unreadCount(),
+ onToggle: review.toggleComments,
+ }
+ }
+ />
+ }
+ />
</Show>
<Show when={review.presenting()}>
{(p) => (
diff --git a/apps/web/src/features/block-fig/views/layers-panel.tsx b/apps/web/src/features/block-fig/views/layers-panel.tsx
index 1c9da8a858..e38f6039ab 100644
--- a/apps/web/src/features/block-fig/views/layers-panel.tsx
+++ b/apps/web/src/features/block-fig/views/layers-panel.tsx
@@ -33,7 +33,7 @@ import type { FigEditor } from '../primitives/create-fig-editor';
import type { FigViewer } from '../primitives/create-fig-viewer';
const ROOT = '';
-const ROW_HEIGHT = 28;
+const ROW_HEIGHT = 32;
interface FlatRow {
row: LayerRow;
@@ -54,7 +54,7 @@ export function LayersPanel(props: {
viewer: FigViewer;
engine: FigEngine;
/** Where ⌘F focuses. */
- searchRef?: (el: HTMLInputElement) => void;
+ focusSearchRef?: (focus: () => void) => void;
/** Renaming, visibility, locking, and reordering when editable. */
editor?: FigEditor;
}) {
@@ -62,6 +62,14 @@ export function LayersPanel(props: {
const [children, setChildren] = createSignal(new Map<string, LayerRow[]>());
const [expanded, setExpanded] = createSignal(new Set<string>());
const [query, setQuery] = createSignal('');
+ const [searchOpen, setSearchOpen] = createSignal(false);
+ let searchInput: HTMLInputElement | undefined;
+ let searchButton: HTMLButtonElement | undefined;
+ const focusSearch = () => {
+ setSearchOpen(true);
+ queueMicrotask(() => searchInput?.focus());
+ };
+ props.focusSearchRef?.(focusSearch);
const [results, setResults] = createSignal<SearchHit[]>([]);
const [pagesOpen, setPagesOpen] = createSignal(true);
let list: VListHandle | undefined;
@@ -232,17 +240,19 @@ export function LayersPanel(props: {
)
);
- const toggleFlag = (row: LayerRow, flag: 'visible' | 'locked') =>
+ const toggleFlag = (row: LayerRow, flag: 'visible' | 'locked') => {
+ if (flag === 'locked') {
+ void props.editor?.toggleLocked([row.id]);
+ return;
+ }
void props.editor?.apply([
{
op: 'set',
ids: [row.id],
- props:
- flag === 'visible'
- ? { visible: !row.visible }
- : { locked: !row.locked },
+ props: { visible: !row.visible },
},
]);
+ };
const [dragging, setDragging] = createSignal<string[]>();
const [drop, setDrop] = createSignal<{ id: string; zone: DropZone }>();
@@ -375,59 +385,78 @@ export function LayersPanel(props: {
class="flex size-full min-h-0 flex-col text-ink text-xs"
data-testid="fig-layers-panel"
>
- <div class="flex h-9 shrink-0 items-center gap-1.5 border-edge-muted border-b px-2">
- <MagnifyingGlass class="size-3.5 shrink-0 text-ink-muted" />
- <input
- ref={props.searchRef}
- type="search"
- placeholder="Find layers"
- aria-label="Find layers"
- data-testid="fig-layer-search"
- class="h-7 min-w-0 flex-1 bg-transparent text-ink outline-none placeholder:text-ink-placeholder"
- value={query()}
- onInput={(e) => void search(e.currentTarget.value)}
- onKeyDown={(e) => {
- e.stopPropagation();
- if (e.key === 'Escape') {
- void search('');
- e.currentTarget.blur();
- }
- }}
- />
- <Show when={query()}>
+ <Show when={searchOpen()}>
+ <div class="flex h-10 shrink-0 items-center gap-1.5 border-edge-frame border-b px-3">
+ <MagnifyingGlass class="size-3.5 shrink-0 text-ink-muted" />
+ <input
+ ref={searchInput}
+ type="search"
+ placeholder="Find layers"
+ aria-label="Find layers"
+ data-testid="fig-layer-search"
+ class="h-7 min-w-0 flex-1 bg-transparent text-ink outline-none placeholder:text-ink-placeholder"
+ value={query()}
+ onInput={(e) => void search(e.currentTarget.value)}
+ onKeyDown={(e) => {
+ e.stopPropagation();
+ if (e.key === 'Escape') {
+ void search('');
+ setSearchOpen(false);
+ searchButton?.focus();
+ }
+ }}
+ />
<button
type="button"
- aria-label="Clear search"
+ aria-label="Close search"
class="rounded p-0.5 text-ink-muted hover:text-ink"
- onClick={() => void search('')}
+ onClick={() => {
+ void search('');
+ setSearchOpen(false);
+ searchButton?.focus();
+ }}
>
<XIcon class="size-3" />
</button>
- </Show>
- </div>
+ </div>
+ </Show>
<Show when={!query()}>
- <div class="relative shrink-0 border-edge-muted border-b py-1">
- <button
- type="button"
- class="flex h-7 w-full items-center gap-1 px-2 font-medium"
- onClick={() => setPagesOpen((o) => !o)}
- >
- <Show when={pagesOpen()} fallback={<CaretRight class="size-3" />}>
- <CaretDown class="size-3" />
- </Show>
- <span class="flex-1 text-left">Pages</span>
- </button>
- <Show when={props.editor?.enabled()}>
+ <div class="shrink-0 border-edge-frame border-b px-2 pt-2 pb-3">
+ <div class="flex h-8 items-center gap-1 px-1">
<button
type="button"
- aria-label="Add page"
- data-testid="fig-page-add"
- class="absolute top-1.5 right-2 rounded p-0.5 text-ink-muted hover:bg-hover hover:text-ink"
- onClick={() => void addPage()}
+ class="flex h-7 min-w-0 flex-1 items-center gap-1 font-semibold"
+ aria-expanded={pagesOpen()}
+ onClick={() => setPagesOpen((o) => !o)}
>
- <Plus class="size-3.5" />
+ <Show when={pagesOpen()} fallback={<CaretRight class="size-3" />}>
+ <CaretDown class="size-3" />
+ </Show>
+ <span class="flex-1 text-left">Pages</span>
</button>
- </Show>
+ <button
+ ref={searchButton}
+ type="button"
+ aria-label="Find layers"
+ title="Find layers · ⌘F / Ctrl+F"
+ data-testid="fig-search-toggle"
+ class="flex size-6 items-center justify-center rounded text-ink-muted hover:bg-hover hover:text-ink"
+ onClick={focusSearch}
+ >
+ <MagnifyingGlass class="size-3.5" />
+ </button>
+ <Show when={props.editor?.enabled()}>
+ <button
+ type="button"
+ aria-label="Add page"
+ data-testid="fig-page-add"
+ class="flex size-6 items-center justify-center rounded text-ink-muted hover:bg-hover hover:text-ink"
+ onClick={() => void addPage()}
+ >
+ <Plus class="size-3.5" />
+ </button>
+ </Show>
+ </div>
<Show when={pagesOpen()}>
<div class="max-h-48 overflow-y-auto">
<For each={viewer.pages}>
@@ -436,7 +465,7 @@ export function LayersPanel(props: {
when={!isPageDivider(p.name)}
fallback={
<div class="flex h-3 items-center px-6" role="separator">
- <div class="h-px w-full bg-edge-muted" />
+ <div class="h-px w-full bg-edge-frame" />
</div>
}
>
@@ -444,10 +473,9 @@ export function LayersPanel(props: {
when={renamingPage() === p.id}
fallback={
<div
- class="group flex h-7 w-full items-center pr-2 pl-6 hover:bg-hover"
+ class="group flex h-8 w-full items-center rounded-md pr-2 pl-6 hover:bg-hover"
classList={{
- 'font-semibold bg-selected':
- p.index === viewer.page(),
+ 'font-medium bg-hover': p.index === viewer.page(),
}}
>
<button
@@ -506,6 +534,12 @@ export function LayersPanel(props: {
</Show>
</div>
</Show>
+ <div
+ class="flex h-10 shrink-0 items-center px-3 font-semibold"
+ data-testid="fig-layers-heading"
+ >
+ {query() ? 'Search results' : 'Layers'}
+ </div>
<div
ref={tree}
// Takes the keys after a row is clicked (see `onTreeKey`).
@@ -584,7 +618,7 @@ export function LayersPanel(props: {
}}
style={{
height: `${ROW_HEIGHT}px`,
- 'padding-left': `${8 + item.depth * 14}px`,
+ 'padding-left': `${12 + item.depth * 16}px`,
}}
draggable={editable(item.row) && renaming() !== item.row.id}
onDragStart={(e) => {
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 996369baea..45f41ec007 100644
--- a/apps/web/src/features/block-fig/views/viewer-canvas.tsx
+++ b/apps/web/src/features/block-fig/views/viewer-canvas.tsx
@@ -23,19 +23,22 @@ import type {
import {
createEffect,
createMemo,
+ createSignal,
type JSX,
on,
onCleanup,
onMount,
Show,
} from 'solid-js';
+import { FigLoadingStatus } from '../components/fig-opening';
import {
drawOverlay,
+ type FrameLabel,
type OverlayModel,
type VectorOverlay,
} from '../components/overlay';
import { PeerCursors } from '../components/peer-presence';
-import { type Point, screenToPage } from '../core/camera';
+import { type Point, pageToScreen, screenToPage } from '../core/camera';
import { type SnapLines, snapResize } from '../core/layout-grid';
import { offsetRect } from '../core/lift';
import { measure } from '../core/measure';
@@ -113,7 +116,7 @@ type Pressed = { row: LayerRow; wasSelected: boolean } | undefined;
/** A move drag: offsets from where the layers started, then the drop. */
interface Mover {
to(dx: number, dy: number): void;
- end(): Promise<void>;
+ end(at?: Point): Promise<void>;
}
/** Layers lifted when pressed, before a drag starts (see `startMove`). */
@@ -280,9 +283,42 @@ export function ViewerCanvas(props: {
children?: JSX.Element;
}) {
const viewer = props.viewer;
+ const [paintedPage, setPaintedPage] = createSignal<number>();
let host!: HTMLDivElement;
let tileCanvas!: HTMLCanvasElement;
let overlayCanvas!: HTMLCanvasElement;
+ let frameLabels: FrameLabel[] = [];
+ let labelsPage: number | undefined;
+ const [renamingFrame, setRenamingFrame] = createSignal<
+ FrameLabel & { page: number }
+ >();
+ const frameLabelAt = (p: Point) => {
+ if (labelsPage !== viewer.page()) return;
+ // Labels painted last take precedence where their text overlaps.
+ return frameLabels.findLast(
+ ({ rect }) =>
+ p.x >= rect.x &&
+ p.x <= rect.x + rect.w &&
+ p.y >= rect.y &&
+ p.y <= rect.y + rect.h
+ );
+ };
+ const finishFrameRename = (name?: string) => {
+ const label = renamingFrame();
+ setRenamingFrame(undefined);
+ const trimmed = name?.trim();
+ if (
+ !label ||
+ label.page !== viewer.page() ||
+ !trimmed ||
+ trimmed === label.frame.name ||
+ !props.editor?.enabled()
+ )
+ return;
+ void props.editor.apply([
+ { op: 'set', ids: [label.frame.id], props: { name: trimmed } },
+ ]);
+ };
const [dpr, setDpr] = (() => {
let value =
typeof window === 'undefined' ? 1 : window.devicePixelRatio || 1;
@@ -297,13 +333,18 @@ export function ViewerCanvas(props: {
})();
let frame: number | undefined;
- const requestDraw = () => {
+ let tilesDirty = true;
+ const requestOverlayDraw = () => {
if (frame !== undefined) return;
frame = requestAnimationFrame(() => {
frame = undefined;
draw();
});
};
+ const requestDraw = () => {
+ tilesDirty = true;
+ requestOverlayDraw();
+ };
const compositor = createTileCompositor({
engine: props.engine,
@@ -347,6 +388,7 @@ export function ViewerCanvas(props: {
compositor.setContent(viewer.contentBounds());
} else {
// A new page, view, or canvas color: render it afresh.
+ setPaintedPage(undefined);
shownPage = { page, outline, background: color };
compositor.setPage({
page,
@@ -511,17 +553,25 @@ export function ViewerCanvas(props: {
() => props.aids?.model(),
() => props.devMode?.(),
],
- requestDraw
+ requestOverlayDraw
)
);
function draw() {
const v = view();
if (v.viewport.w <= 0) return;
- const ctx = tileCanvas.getContext('2d', { alpha: false });
- if (ctx) compositor.draw(ctx, v);
+ // Hover, selection, guides and remote cursors live on the overlay.
+ // Keep the already-composited page when only those have changed.
+ if (tilesDirty) {
+ const ctx = tileCanvas.getContext('2d', { alpha: false });
+ if (ctx && compositor.draw(ctx, v)) setPaintedPage(viewer.page());
+ tilesDirty = false;
+ }
const octx = overlayCanvas.getContext('2d');
- if (octx) drawOverlay(octx, overlayModel());
+ if (octx) {
+ frameLabels = drawOverlay(octx, overlayModel());
+ labelsPage = viewer.page();
+ }
}
// ---- size --------------------------------------------------------------
@@ -719,7 +769,7 @@ export function ViewerCanvas(props: {
}
if (editing() && tool === 'pencil' && editor) {
drag = { kind: 'pencil', points: [pageAt(p)] };
- requestDraw();
+ requestOverlayDraw();
return;
}
const edit = editor?.vectorEdit();
@@ -747,7 +797,8 @@ export function ViewerCanvas(props: {
drag = { kind: 'create', tool, start: p, current: p };
return;
}
- const handle = handleAt(p);
+ const label = frameLabelAt(p);
+ const handle = label ? undefined : handleAt(p);
const info = props.info?.();
const bounds = viewer.selectionBounds();
if (handle && bounds && props.editor) {
@@ -764,7 +815,7 @@ export function ViewerCanvas(props: {
};
return;
}
- if (rotateAt(p) && info && bounds && props.editor) {
+ if (!label && rotateAt(p) && info && bounds && props.editor) {
const center = { x: bounds.x + bounds.w / 2, y: bounds.y + bounds.h / 2 };
const at = pageAt(p);
drag = {
@@ -777,10 +828,12 @@ export function ViewerCanvas(props: {
return;
}
const additive = e.shiftKey;
- const pressed = viewer.pressAt(p, {
- deep: IS_MAC ? e.metaKey : e.ctrlKey,
- additive,
- });
+ const pressed = label
+ ? pressFrameLabel(label, additive)
+ : viewer.pressAt(p, {
+ deep: IS_MAC ? e.metaKey : e.ctrlKey,
+ additive,
+ });
const press: Extract<Drag, { kind: 'press' }> = {
kind: 'press',
start: p,
@@ -802,6 +855,17 @@ export function ViewerCanvas(props: {
});
};
+ const pressFrameLabel = async (
+ label: FrameLabel,
+ additive: boolean
+ ): Promise<Pressed> => {
+ const id = label.frame.id;
+ const wasSelected = viewer.selected().some((row) => row.id === id);
+ if (!wasSelected || additive) await viewer.selectIds([id], additive);
+ const [row] = await props.engine.rows(viewer.page(), [id]);
+ return row ? { row, wasSelected } : undefined;
+ };
+
/**
* The last lifted drop's edit. A new lift waits for it, so its parts are
* rendered with the dropped layers where they landed.
@@ -875,6 +939,7 @@ export function ViewerCanvas(props: {
requestDraw();
return;
}
+ compositor.beginInteractive();
stepwise = editor.startMove(ids);
if (offset.x !== 0 || offset.y !== 0) stepwise.to(offset.x, offset.y);
})();
@@ -890,15 +955,23 @@ export function ViewerCanvas(props: {
requestDraw();
}
},
- end() {
+ end(at?: Point) {
const done = (async () => {
await decided;
- if (stepwise) return stepwise.end();
+ if (stepwise) {
+ try {
+ await stepwise.end(at);
+ } finally {
+ compositor.endInteractive();
+ requestDraw();
+ }
+ return;
+ }
if (!follower) return;
compositor.freezeLift();
let moved: Point | null = null;
try {
- moved = await follower.end();
+ moved = await follower.end(at);
} finally {
// Down once the page shows the move (at once if it did not
// apply); the selection box lands with the edit.
@@ -936,7 +1009,7 @@ export function ViewerCanvas(props: {
// The pointer came up while this was starting (a copy being made, or
// the press still resolving): the move ends where it got to.
if (drag !== press) {
- void press.mover.end();
+ void press.mover.end(pageAt(press.current));
return;
}
if (start) {
@@ -973,7 +1046,7 @@ export function ViewerCanvas(props: {
dx = constrain && dx === 0 ? 0 : Math.round(snapped.dx);
dy = constrain && dy === 0 ? 0 : Math.round(snapped.dy);
guides = snapped.guides;
- requestDraw();
+ requestOverlayDraw();
}
press.mover.to(dx, dy);
};
@@ -984,11 +1057,16 @@ export function ViewerCanvas(props: {
if (e.pointerType !== 'touch') props.onPointer?.(pageAt(p));
if (!drag && editing() && viewer.tool() === 'pen') {
penCursor = pageAt(p);
- requestDraw();
+ requestOverlayDraw();
return;
}
if (!drag) {
if (e.pointerType !== 'touch' && !panning()) {
+ if (frameLabelAt(p) && viewer.tool() === 'move') {
+ setCursorOverride('default');
+ hoverAt(undefined);
+ return;
+ }
const handle = handleAt(p);
setCursorOverride(
handle
@@ -1017,19 +1095,19 @@ export function ViewerCanvas(props: {
if (isLineTool(drag.tool))
linePreview = [drag.start, lineEnd(drag.start, p, e.shiftKey)];
else marquee = shapeRect(drag.start, p, e.shiftKey);
- requestDraw();
+ requestOverlayDraw();
} else if (drag.kind === 'pen') {
props.editor?.penHandle(
dragHandle(drag.start, pageAt(p), PEN_DRAG / viewer.camera().zoom)
);
- requestDraw();
+ requestOverlayDraw();
} 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();
+ requestOverlayDraw();
} else if (drag.kind === 'vector') {
const edit = props.editor?.vectorEdit();
if (edit) {
@@ -1083,7 +1161,7 @@ export function ViewerCanvas(props: {
w: Math.abs(p.x - press.start.x),
h: Math.abs(p.y - press.start.y),
};
- requestDraw();
+ requestOverlayDraw();
} else movePress(press, p, e.shiftKey);
}
};
@@ -1152,14 +1230,14 @@ export function ViewerCanvas(props: {
if (ended.kind === 'create') {
marquee = undefined;
linePreview = undefined;
- requestDraw();
+ requestOverlayDraw();
void finishCreate(ended, e.shiftKey);
} else if (ended.kind === 'vector') {
void ended.mover.end();
} else if (ended.kind === 'pen') {
- requestDraw();
+ requestOverlayDraw();
} else if (ended.kind === 'pencil') {
- requestDraw();
+ requestOverlayDraw();
void props.editor?.pencilFinish(
ended.points,
PENCIL_TOLERANCE / viewer.camera().zoom
@@ -1174,8 +1252,8 @@ export function ViewerCanvas(props: {
if (!ended.mover) dropPrepared(ended.prepared);
if (ended.mover) {
guides = [];
- requestDraw();
- void ended.mover.end();
+ requestOverlayDraw();
+ void ended.mover.end(pageAt(local(e)));
} else if (ended.marquee && marquee) {
const c = viewer.camera();
const a = screenToPage(c, { x: marquee.x, y: marquee.y });
@@ -1184,7 +1262,7 @@ export function ViewerCanvas(props: {
e.shiftKey
);
marquee = undefined;
- requestDraw();
+ requestOverlayDraw();
} else if (!ended.active) {
// A click on one layer of a multi-selection selects just it.
void ended.pressed.then((r) => {
@@ -1200,6 +1278,13 @@ export function ViewerCanvas(props: {
if (panning() || isShapeTool(tool) || tool === 'pen' || tool === 'pencil')
return;
if (props.editor?.vectorEdit()) return;
+ const label = frameLabelAt(local(e));
+ if (label) {
+ await viewer.selectIds([label.frame.id]);
+ if (editing() && !label.frame.id.startsWith('I'))
+ setRenamingFrame({ ...label, page: viewer.page() });
+ return;
+ }
const before = viewer.selected().map((s) => s.id);
await viewer.clickAt(local(e), {
deep: false,
@@ -1322,6 +1407,46 @@ export function ViewerCanvas(props: {
ref={overlayCanvas}
class="pointer-events-none absolute inset-0 size-full"
/>
+ <Show when={renamingFrame()} keyed>
+ {(label) => (
+ <input
+ ref={(el) =>
+ queueMicrotask(() => {
+ el.focus();
+ el.select();
+ })
+ }
+ aria-label="Frame name"
+ data-testid="fig-frame-rename"
+ class="absolute z-10 h-5 rounded-sm bg-input px-1 text-[11px] text-ink outline outline-1 outline-accent"
+ style={{
+ left: `${pageToScreen(viewer.camera(), label.frame.bounds).x - 4}px`,
+ top: `${pageToScreen(viewer.camera(), label.frame.bounds).y - 21}px`,
+ width: `${Math.max(80, label.rect.w + 16)}px`,
+ }}
+ value={label.frame.name}
+ onPointerDown={(e) => e.stopPropagation()}
+ onPointerMove={(e) => e.stopPropagation()}
+ onPointerUp={(e) => e.stopPropagation()}
+ onDblClick={(e) => e.stopPropagation()}
+ onBlur={(e) => finishFrameRename(e.currentTarget.value)}
+ onKeyDown={(e) => {
+ e.stopPropagation();
+ if (e.isComposing) return;
+ if (e.key === 'Enter' || e.key === 'Escape') {
+ e.preventDefault();
+ finishFrameRename(
+ e.key === 'Enter' ? e.currentTarget.value : undefined
+ );
+ host.focus({ preventScroll: true });
+ }
+ }}
+ />
+ )}
+ </Show>
+ <Show when={paintedPage() !== viewer.page()}>
+ <FigLoadingStatus />
+ </Show>
<Show when={props.peers}>
{(peers) => <PeerCursors peers={peers()()} camera={viewer.camera()} />}
</Show>
diff --git a/apps/web/src/lib/core/block.ts b/apps/web/src/lib/core/block.ts
index 53f4136f0b..2d04c38a6a 100644
--- a/apps/web/src/lib/core/block.ts
+++ b/apps/web/src/lib/core/block.ts
@@ -376,6 +376,9 @@ export type BlockDefinition<
/** The component for the block. */
component: BlockComponent<Name>;
+ /** Lightweight placeholder while the block's component or data loads. */
+ loading?: Component;
+
/** flag to indicate wether this block should enable collaborative features. */
liveTrackingEnabled?: boolean;
diff --git a/apps/web/src/lib/core/component/DocumentBlockContainer.tsx b/apps/web/src/lib/core/component/DocumentBlockContainer.tsx
index d962612a00..4d7e775a1a 100644
--- a/apps/web/src/lib/core/component/DocumentBlockContainer.tsx
+++ b/apps/web/src/lib/core/component/DocumentBlockContainer.tsx
@@ -2,7 +2,14 @@ import { BlockContainer } from '@core/component/BlockContainer';
import { blockDataSignal } from '@core/internal/BlockLoader';
import { nativeNetworkStatus } from '@core/mobile/native-network-status';
import { blockErrorSignal, blockLoadRetrySignal } from '@core/signal/load';
-import { type FlowProps, Match, Show, Switch, splitProps } from 'solid-js';
+import {
+ type FlowProps,
+ type JSX,
+ Match,
+ Show,
+ Switch,
+ splitProps,
+} from 'solid-js';
import Gone from './AccessErrorViews/Gone';
import NotFound from './AccessErrorViews/NotFound';
import Unauthorized from './AccessErrorViews/Unauthorized';
@@ -10,7 +17,11 @@ import { LoadErrorPanel } from './EntityLoadGate';
import { LoadingPanel } from './LoadingSpinner';
export function DocumentBlockContainer(
- props: FlowProps<{ usesCenterBar?: boolean; title?: string }>
+ props: FlowProps<{
+ usesCenterBar?: boolean;
+ title?: string;
+ loadingFallback?: JSX.Element;
+ }>
) {
const blockData = blockDataSignal.get;
const blockError = blockErrorSignal.get;
@@ -18,7 +29,10 @@ export function DocumentBlockContainer(
const retryLoad = () => setLoadRetry((count) => (count ?? 0) + 1);
const hasBlockData = () => blockData() != null;
- const [local, others] = splitProps(props, ['usesCenterBar']);
+ const [local, others] = splitProps(props, [
+ 'usesCenterBar',
+ 'loadingFallback',
+ ]);
const isLoading = () => !hasBlockData() && !blockError();
@@ -45,7 +59,7 @@ export function DocumentBlockContainer(
<LoadErrorPanel title="Unable to load this document" />
</Match>
<Match when={isLoading()}>
- <LoadingPanel />
+ {local.loadingFallback ?? <LoadingPanel />}
</Match>
<Match when={blockError() === 'UNAUTHORIZED'}>
<Unauthorized />
diff --git a/apps/web/src/lib/core/fig-engine/client.test.ts b/apps/web/src/lib/core/fig-engine/client.test.ts
new file mode 100644
index 0000000000..64d68f8413
--- /dev/null
+++ b/apps/web/src/lib/core/fig-engine/client.test.ts
@@ -0,0 +1,76 @@
+import { afterEach, expect, it, vi } from 'vitest';
+import { FigEngine } from './client';
+import type { FigRequest, FigResponse } from './protocol';
+
+vi.mock('./compiled-module', () => ({
+ compiledFigModule: async () => ({}),
+}));
+
+const workers: FakeWorker[] = [];
+class FakeWorker extends EventTarget {
+ requests: FigRequest[] = [];
+ terminate = vi.fn();
+ constructor() {
+ super();
+ workers.push(this);
+ }
+ postMessage(request: FigRequest) {
+ this.requests.push(request);
+ if (request.kind === 'open' && workers[0] === this)
+ queueMicrotask(() =>
+ this.reply({
+ id: request.id,
+ ok: true,
+ kind: 'open',
+ summary: {
+ rootId: '0:0',
+ fileName: null,
+ version: 1,
+ nodeCount: 1,
+ pages: [],
+ },
+ })
+ );
+ }
+ reply(response: FigResponse) {
+ this.dispatchEvent(new MessageEvent('message', { data: response }));
+ }
+}
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ workers.length = 0;
+});
+
+it('keeps pointer queries independent of raster helpers that are still opening', async () => {
+ vi.stubGlobal('Worker', FakeWorker);
+ const engine = await FigEngine.open(new ArrayBuffer(0), { helpers: 1 });
+ try {
+ const [primary, helper] = workers;
+ const tile = engine.render({
+ page: 0,
+ x: 0,
+ y: 0,
+ width: 512,
+ height: 512,
+ scale: 1,
+ outline: false,
+ priority: -1,
+ });
+ expect(helper.requests.map((r) => r.kind)).toEqual(['open', 'render']);
+ const hit = engine.hitTest(0, 10, 10, 1);
+ const query = primary.requests.at(-1)!;
+ expect(query.kind).toBe('query');
+ primary.reply({ id: query.id, ok: true, kind: 'query', json: '[]' });
+ await expect(hit).resolves.toEqual([]);
+ engine.cancel([tile.id]);
+ expect(helper.requests.at(-1)).toMatchObject({
+ kind: 'cancel',
+ ids: [tile.id],
+ });
+ helper.reply({ id: tile.id, ok: true, kind: 'cancelled' });
+ await expect(tile.promise).resolves.toBeNull();
+ } finally {
+ engine.close();
+ }
+});
diff --git a/apps/web/src/lib/core/fig-engine/client.ts b/apps/web/src/lib/core/fig-engine/client.ts
index b8dacc41af..4bdc959f71 100644
--- a/apps/web/src/lib/core/fig-engine/client.ts
+++ b/apps/web/src/lib/core/fig-engine/client.ts
@@ -2,12 +2,13 @@
* The `.fig` engine as the app calls it: async methods, workers behind them.
*
* Each open file gets a primary worker, which answers queries (layers, hit
- * tests, properties) and renders until helpers are ready, plus raster
+ * tests, properties), plus raster
* helpers that open the same file and rasterize tiles in parallel. Workers
* are terminated when the file is closed, which returns their memory (wasm
* memory never shrinks while a worker lives).
*/
+import { compiledFigModule } from './compiled-module';
import type { CollectionInfo, DesignInfo, StyleInfo } from './design-types';
import type {
Exportable,
@@ -192,7 +193,8 @@ export class FigEngine {
static async blank(name: string): Promise<Uint8Array<ArrayBuffer>> {
const worker = new EngineWorker(() => {});
try {
- const r = await worker.request({ kind: 'blank', name });
+ const module = await compiledFigModule();
+ const r = await worker.request({ kind: 'blank', name, module });
if (r.kind !== 'saved') throw new Error('unexpected response');
return new Uint8Array(r.bytes);
} finally {
@@ -208,15 +210,17 @@ export class FigEngine {
let engine: FigEngine | undefined;
const primary = new EngineWorker((e) => engine?.onFailure?.(e));
try {
+ const module = await compiledFigModule();
const copy = bytes.slice(0);
- const response = await primary.request({ kind: 'open', bytes: copy }, [
- copy,
- ]);
+ const response = await primary.request(
+ { kind: 'open', bytes: copy, module },
+ [copy]
+ );
if (response.kind !== 'open') throw new Error('unexpected response');
engine = new FigEngine(primary, response.summary);
engine.onFailure = options.onFailure;
const helpers = options.helpers ?? helperCount(bytes.byteLength);
- for (let i = 0; i < helpers; i++) engine.startHelper(bytes);
+ for (let i = 0; i < helpers; i++) engine.startHelper(bytes, module);
return engine;
} catch (error) {
primary.terminate();
@@ -224,7 +228,7 @@ export class FigEngine {
}
}
- private startHelper(bytes: ArrayBuffer) {
+ private startHelper(bytes: ArrayBuffer, module: WebAssembly.Module) {
const helper = new EngineWorker(() => {
const at = this.helpers.indexOf(helper);
if (at >= 0) this.helpers.splice(at, 1);
@@ -235,7 +239,7 @@ export class FigEngine {
this.starting.add(helper);
const copy = bytes.slice(0);
helper
- .request({ kind: 'open', bytes: copy }, [copy])
+ .request({ kind: 'open', bytes: copy, module }, [copy])
.then(() => {
this.starting.delete(helper);
if (this.closed) helper.terminate();
@@ -265,7 +269,11 @@ export class FigEngine {
/** Queues a tile render on the least busy worker. */
render(tile: TileRequest): PendingTile {
const live = this.helpers.filter((h) => !h.dead);
- const pool = live.length > 0 ? live : [this.primary];
+ // Helpers accept work behind their open request. Do not fill the primary
+ // with slow raster jobs while they start: it must answer pointer queries.
+ const opening = [...this.starting].filter((h) => !h.dead);
+ const pool =
+ live.length > 0 ? live : opening.length > 0 ? opening : [this.primary];
const worker = pool.reduce((a, b) => (b.renders < a.renders ? b : a));
const id = nextId++;
worker.renders++;
diff --git a/apps/web/src/lib/core/fig-engine/compiled-module.test.ts b/apps/web/src/lib/core/fig-engine/compiled-module.test.ts
new file mode 100644
index 0000000000..d9059b9ac7
--- /dev/null
+++ b/apps/web/src/lib/core/fig-engine/compiled-module.test.ts
@@ -0,0 +1,47 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ vi.resetModules();
+});
+
+describe('compiled design engine', () => {
+ it('shares one fetch and compilation across concurrent and later opens', async () => {
+ const module = {} as WebAssembly.Module;
+ const fetch = vi.fn().mockResolvedValue(
+ new Response('', {
+ headers: { 'content-type': 'application/wasm' },
+ })
+ );
+ vi.stubGlobal('fetch', fetch);
+ const compile = vi
+ .spyOn(WebAssembly, 'compileStreaming')
+ .mockResolvedValue(module);
+ const { compiledFigModule } = await import('./compiled-module');
+ const [a, b] = await Promise.all([
+ compiledFigModule(),
+ compiledFigModule(),
+ ]);
+ expect(a).toBe(module);
+ expect(b).toBe(module);
+ expect(await compiledFigModule()).toBe(module);
+ expect(fetch).toHaveBeenCalledTimes(1);
+ expect(compile).toHaveBeenCalledTimes(1);
+ });
+
+ it('retries after failure and supports hosts without a wasm MIME type', async () => {
+ const module = {} as WebAssembly.Module;
+ const fetch = vi
+ .fn()
+ .mockResolvedValueOnce(new Response('', { status: 503 }))
+ .mockResolvedValueOnce(new Response(new Uint8Array([0, 97, 115, 109])));
+ vi.stubGlobal('fetch', fetch);
+ const compile = vi.spyOn(WebAssembly, 'compile').mockResolvedValue(module);
+ const { compiledFigModule } = await import('./compiled-module');
+ await expect(compiledFigModule()).rejects.toThrow('503');
+ expect(await compiledFigModule()).toBe(module);
+ expect(fetch).toHaveBeenCalledTimes(2);
+ expect(compile).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/web/src/lib/core/fig-engine/compiled-module.ts b/apps/web/src/lib/core/fig-engine/compiled-module.ts
new file mode 100644
index 0000000000..a7c5136bba
--- /dev/null
+++ b/apps/web/src/lib/core/fig-engine/compiled-module.ts
@@ -0,0 +1,29 @@
+/**
+ * Share compiled code across file engines and raster workers. Each worker
+ * still gets its own instance and memory; closing a file releases its data.
+ */
+let compiled: Promise<WebAssembly.Module> | undefined;
+
+export function compiledFigModule(): Promise<WebAssembly.Module> {
+ if (!compiled) compiled = compile();
+ return compiled;
+}
+
+async function compile(): Promise<WebAssembly.Module> {
+ try {
+ const url = new URL('./wasm/fig_engine_bg.wasm', import.meta.url);
+ const response = await fetch(url);
+ if (!response.ok)
+ throw new Error(`Unable to load design engine (${response.status})`);
+ // Streaming starts compilation while the remaining bytes download.
+ // Some desktop protocols do not provide the application/wasm MIME type.
+ if (
+ response.headers.get('content-type')?.split(';')[0] === 'application/wasm'
+ )
+ return await WebAssembly.compileStreaming(response);
+ return await WebAssembly.compile(await response.arrayBuffer());
+ } catch (error) {
+ compiled = undefined;
+ throw error;
+ }
+}
diff --git a/apps/web/src/lib/core/fig-engine/fig.worker.ts b/apps/web/src/lib/core/fig-engine/fig.worker.ts
index e7478755c5..993bd9f079 100644
--- a/apps/web/src/lib/core/fig-engine/fig.worker.ts
+++ b/apps/web/src/lib/core/fig-engine/fig.worker.ts
@@ -32,8 +32,9 @@ const renders: Render[] = [];
let scheduled = false;
let busy = false;
-/** Nodes decoded per idle slice (some tens of milliseconds on large files). */
-const DECODE_SLICE = 2048;
+/** Bound background work so hit tests can run between decode slices. */
+const DECODE_BUDGET_MS = 8;
+let decodeSlice = 128;
/** Queries that read only a page, answered before the file is decoded. */
const PAGE_QUERIES = new Set<QueryMethod>([
@@ -114,7 +115,7 @@ function openFile(): WasmFigFile {
async function serve(request: FigRequest) {
switch (request.kind) {
case 'open': {
- const wasm = await loadFigEngineWasm();
+ const wasm = await loadFigEngineWasm(request.module);
file?.free();
file = new wasm.FigFile(new Uint8Array(request.bytes));
post({
@@ -404,7 +405,7 @@ async function serve(request: FigRequest) {
return;
}
case 'blank': {
- const wasm = await loadFigEngineWasm();
+ const wasm = await loadFigEngineWasm(request.module);
const bytes = wasm.FigFile.blank(request.name).slice().buffer;
post({ id: request.id, ok: true, kind: 'saved', bytes }, [bytes]);
return;
@@ -448,7 +449,16 @@ async function pump() {
if (!request) return;
if (request === 'decode') {
try {
- openFile().decodeSome(DECODE_SLICE);
+ const started = performance.now();
+ openFile().decodeSome(decodeSlice);
+ const elapsed = Math.max(1, performance.now() - started);
+ decodeSlice = Math.max(
+ 32,
+ Math.min(
+ 2048,
+ Math.round(decodeSlice * Math.min(2, DECODE_BUDGET_MS / elapsed))
+ )
+ );
} catch (error) {
// Decoding the rest failed: what needs it fails when served.
if (isWasmTrap(error)) trapped = true;
diff --git a/apps/web/src/lib/core/fig-engine/protocol.ts b/apps/web/src/lib/core/fig-engine/protocol.ts
index 0e9bdf8be2..bb3535ab44 100644
--- a/apps/web/src/lib/core/fig-engine/protocol.ts
+++ b/apps/web/src/lib/core/fig-engine/protocol.ts
@@ -39,7 +39,12 @@ export type QueryMethod =
| 'liftPlan';
export type FigRequest =
- | { id: number; kind: 'open'; bytes: ArrayBuffer }
+ | {
+ id: number;
+ kind: 'open';
+ bytes: ArrayBuffer;
+ module?: WebAssembly.Module;
+ }
| { id: number; kind: 'openPage'; page: number }
| {
id: number;
@@ -89,7 +94,7 @@ export type FigRequest =
}
| { id: number; kind: 'collabChanges' }
| { id: number; kind: 'save' }
- | { id: number; kind: 'blank'; name: string }
+ | { id: number; kind: 'blank'; name: string; module?: WebAssembly.Module }
| { id: number; kind: 'addImage'; hash: string; bytes: ArrayBuffer }
| {
id: number;
diff --git a/apps/web/src/lib/core/fig-engine/wasm-module.ts b/apps/web/src/lib/core/fig-engine/wasm-module.ts
index e5712f542b..5953cb3ee0 100644
--- a/apps/web/src/lib/core/fig-engine/wasm-module.ts
+++ b/apps/web/src/lib/core/fig-engine/wasm-module.ts
@@ -164,7 +164,9 @@ interface FigEngineWasmModule {
let modulePromise: Promise<FigEngineWasmModule> | undefined;
/** Loads and initializes the wasm module once per worker; a failed load is tried again. */
-export function loadFigEngineWasm(): Promise<FigEngineWasmModule> {
+export function loadFigEngineWasm(
+ module?: WebAssembly.Module
+): Promise<FigEngineWasmModule> {
if (!modulePromise) {
modulePromise = (async () => {
try {
@@ -175,7 +177,7 @@ export function loadFigEngineWasm(): Promise<FigEngineWasmModule> {
// The generated JS's own relative wasm URL 404s in production; a static
// `new URL` makes vite emit and rewrite the binary.
const wasmUrl = new URL('./wasm/fig_engine_bg.wasm', import.meta.url);
- await mod.default({ module_or_path: wasmUrl });
+ await mod.default({ module_or_path: module ?? wasmUrl });
return mod;
} catch (error) {
modulePromise = undefined;
diff --git a/apps/web/src/lib/core/orchestrator.tsx b/apps/web/src/lib/core/orchestrator.tsx
index 55ae672c58..62fc7f9326 100644
--- a/apps/web/src/lib/core/orchestrator.tsx
+++ b/apps/web/src/lib/core/orchestrator.tsx
@@ -219,7 +219,9 @@ function createBlockElement({
id={id}
handle={ownedHandle}
/>
- <Suspense fallback={<LoadingBlock />}>
+ <Suspense
+ fallback={<Dynamic component={definition.loading ?? LoadingBlock} />}
+ >
<Dynamic component={definition.component} {...opts?.params} />
</Suspense>
<BlockEffectRunner />
diff --git a/crates/fig_engine/src/collab/test.rs b/crates/fig_engine/src/collab/test.rs
index 331ef531e8..ddd7b54e24 100644
--- a/crates/fig_engine/src/collab/test.rs
+++ b/crates/fig_engine/src/collab/test.rs
@@ -6,6 +6,35 @@ use crate::scene::Scene;
use crate::testing::showcase_file;
use std::collections::BTreeMap;
+#[test]
+fn joining_a_lazy_file_keeps_other_pages_deferred() {
+ use crate::testing::{fig_file, node};
+
+ let bytes = Arc::new(fig_file(
+ vec![
+ node(0, None, "DOCUMENT", "Document", vec![]),
+ node(1, Some((0, "a")), "CANVAS", "Cover", vec![]),
+ node(2, Some((0, "b")), "CANVAS", "Screens", vec![]),
+ node(50, Some((2, "a")), "RECTANGLE", "Deferred", vec![]),
+ ],
+ vec![],
+ ));
+ let mut lazy = Document::open_lazy(&bytes).unwrap();
+ let mut full = Document::open_shared(&bytes).unwrap();
+ let session = lazy.props(lazy.root).guid.unwrap().session;
+ let (_, lazy_meta) = Collab::new(&mut lazy, session, None);
+ let (_, full_meta) = Collab::new(&mut full, session, None);
+ assert_eq!(lazy_meta, full_meta);
+ // A colliding session must still allocate after IDs on unopened pages.
+ assert_eq!(lazy.next_guid, full.next_guid);
+ assert_eq!(lazy.next_guid.local, 51);
+ assert!(!lazy.is_complete());
+ let deferred = lazy.node(lazy.pages[1]).children[0];
+ assert!(!lazy.is_decoded(deferred));
+ lazy.complete().unwrap();
+ assert_eq!(lazy.next_guid, full.next_guid);
+}
+
/// One person editing: a document, its undo history, and its collaboration
/// state, exchanging entries through a [`Hub`].
struct Peer {
diff --git a/crates/fig_engine/src/wasm.rs b/crates/fig_engine/src/wasm.rs
index 9032182955..a744352333 100644
--- a/crates/fig_engine/src/wasm.rs
+++ b/crates/fig_engine/src/wasm.rs
@@ -273,7 +273,9 @@ impl FigFile {
session: u32,
base_blobs: Option<u32>,
) -> Result<String, JsError> {
- self.complete()?;
+ // IDs, original blob count and image keys are present in the lazy
+ // skeleton. Joining an unedited design must not decode other pages.
+ // Applying remote changes and local edits still complete the file.
let (collab, changes) = Collab::new(&mut self.doc, session, base_blobs);
self.collab = Some(collab);
to_json(&changes)
diff --git a/docs/AGENT_GUIDE/documents.md b/docs/AGENT_GUIDE/documents.md
index 51b7a3627d..79a76e335d 100644
--- a/docs/AGENT_GUIDE/documents.md
+++ b/docs/AGENT_GUIDE/documents.md
@@ -986,6 +986,14 @@ flag off the block offers the file for download. The file is decoded,
rendered, and edited by the Rust `fig_engine` compiled to WebAssembly, in a
primary worker plus up to three tile-raster helpers. The canvas composites
512 px tiles; while zooming it shows the nearest cached scale, then sharpens.
+Opening shows the file's embedded preview (`fig-opening-preview`, when
+present) while the engine and live session start in parallel. A coarse
+page preview appears before detailed tiles; the visible area gets priority
+over refining the whole-page preview. Reopening a file shares the compiled
+engine code; a new open starts compiling it while the file downloads.
+Each file keeps its own worker memory. Hover and remote
+cursors update the overlay without redrawing an unchanged page canvas.
+The canvas becomes editable only after the shared changes have been applied.
People with edit access get an editor; others get the same view read-only
(no shape tools, no editing shortcuts). Edits save automatically 1.5 s after
@@ -1034,9 +1042,30 @@ chunk, so content search finds a design by the words on its canvas.
Layout and test hooks:
-- **Left panel tabs**: `fig-tab-layers` and `fig-tab-assets`. Assets
- (`fig-assets`) lists the file's components (`fig-asset`, searchable with
- `fig-assets-search`); editors click one to place an instance in the middle
+- **Opening a design**: download, collaboration connection, and decoding use
+ the same editor-shaped loading shell (`fig-opening`), without a floating
+ thumbnail or Macro spinner. Its canvas has the same bounds as the editor.
+ The canvas status (`fig-loading-status`) clears when content is first drawn
+ or an empty page is ready; the surrounding controls need not wait for tiles.
+- **Dragging layers with composited effects**: when a layer cannot be moved
+ as a cached sprite, the canvas updates in complete preview frames rather
+ than tiles from different drag positions. Full detail returns together
+ after release. Other collaborators still receive the movement as it happens.
+- **Editor chrome**: both sidebars use the app's page background color,
+ including the loading shell, so they follow the active theme. Horizontal
+ and vertical sidebar dividers use the same `edge-frame` color as the outer
+ navigation rail. The same divider spans the editor below the file header,
+ including while the design is loading.
+ Drag their inner edges (`fig-resize-left|right`) or focus an edge and use
+ Left/Right to resize. `fig-toggle-left|right` hides or shows a panel while
+ preserving its width. The file header shows save status (`fig-save-state`,
+ `data-state` is `saved`, `unsaved`, `saving`, or `error`).
+- **Left panel tabs**: File (`fig-tab-layers`) and Assets (`fig-tab-assets`);
+ arrow keys switch tabs. Assets
+ (`fig-assets`) shows component previews (`fig-asset`, searchable with
+ `fig-assets-search`). `fig-assets-grid|list` switches the local components
+ between thumbnail cards and compact rows; previews load near the visible
+ portion of the list. Editors click one to place an instance in the middle
of the view, and the arrow beside it (or a click, read-only) goes to the
main component. ⌥⌘K makes the selection a component (a frame becomes one;
other layers are wrapped), duplicating or pasting a main component places
@@ -1071,8 +1100,10 @@ Layout and test hooks:
`fig-library-update-one`, and `fig-library-update-all`. Updating keeps
instances' overrides; it is one undo step. Libraries are read when the
design opens and again when the Libraries dialog opens.
-- **Layers panel** (`fig-layers-panel`, toggled with ⌥1): layer search
- (`fig-layer-search`, ⌘/Ctrl+F; results are `fig-search-hit`), the pages list
+- **Layers panel** (`fig-layers-panel`, toggled with ⌥1): open layer search
+ with the magnifier (`fig-search-toggle`) or ⌘/Ctrl+F, including from Assets.
+ Search uses `fig-layer-search`; results are `fig-search-hit`. Escape closes
+ search and returns focus to its button. Below are the collapsible pages list
(`fig-page` buttons; pages named only with dashes are dividers; editors
get `fig-page-add`, double-click to rename in `fig-page-rename`, and a hover
`fig-page-delete`), and the layer tree (`fig-layer-row`, `data-layer-id` is
@@ -1090,13 +1121,18 @@ Layout and test hooks:
- **Canvas** (`fig-canvas`): click selects with Figma's rules (inside a
top-level frame the click selects the frame's child; sections are
transparent; ⌘/Ctrl-click selects the deepest layer; double-click goes one
- level deeper; Shift-click adds). Dragging empty canvas draws a selection
+ level deeper; Shift-click adds). Click a frame's canvas name label to select
+ that frame; Shift-click toggles it in the selection. Drag the label to move
+ the frame. In editable files, double-click the label to rename it in place
+ (`fig-frame-rename`): Enter or blur commits, Escape cancels, and undo restores
+ the previous name. Dragging empty canvas draws a selection
marquee. Hover outlines what a click would select; holding ⌥ measures from
the selection to the hovered layer. Scroll pans, ⌘/Ctrl+scroll or pinch
zooms, Space-drag or middle-drag pans. When editing: drag a layer to move it
(⌥ drags a copy, ⇧ constrains, edges and centers snap to siblings and the
- parent frame with red guides; in an auto layout frame the dragged layer
- takes the slot it is dropped over; the canvas draws the moving layers
+ parent frame with red guides; dropping inside another frame moves the layer
+ into that frame, and dropping outside frames moves it onto the page; in an
+ auto layout frame the dragged layer takes the slot it is dropped over; the canvas draws the moving layers
itself while they are dragged, the design panel's X and Y follow them, and
the move is one undo step, which the others in a live design see as it
goes), drag the selection's corners or edges to
@@ -1130,12 +1166,19 @@ Layout and test hooks:
cannot be moved, resized, or deleted, but their name, fills, strokes,
opacity, visibility, and text (typing included) are overridden on the
instance, as in Figma; text bound to a component text property sets the
- property.
+ property. A layer row's padlock toggles that layer. Lock/unlock selection
+ (⌘/Ctrl⇧L or the menus) unlocks when all selected layers are locked,
+ otherwise locks the selection. It reads current engine state after pending
+ local and remote edits; verify multi-selection, repeated toggles, and undo/redo.
- **Main menu, layout grids, and guides**: the menu at the top of the
- layers panel (`fig-main-menu`) has `fig-menu-export-frames-pdf` ("Export frames
+ layers panel (`fig-main-menu`) groups commands into File, Edit, View,
+ Object, and Arrange. Open Edit (`fig-main-edit`) for Undo/Redo
+ (`fig-undo`, `fig-redo`); open File (`fig-main-file`) for `fig-menu-export-frames-pdf` ("Export frames
to PDF": the page's top-level frames as a multi-page vector PDF),
- `fig-menu-export-selection`, and the Layout grids and Rulers toggles (also
- in the zoom menu, `fig-layout-grids-toggle`). Frames' layout grids draw
+ `fig-menu-export-selection`. View (`fig-main-view`) contains the Layout grids
+ and Rulers toggles (also in the zoom menu, `fig-layout-grids-toggle`).
+ Submenus open with hover or Right Arrow; Left Arrow returns to the parent.
+ Keyboard shortcuts remains a top-level menu command. Frames' layout grids draw
over the canvas (never in exports) until toggled off. With rulers shown
(⇧R), editors drag from the top ruler for a horizontal guide or the left
one for a vertical guide; a guide dropped on a top-level frame belongs to
@@ -1159,7 +1202,17 @@ Layout and test hooks:
undo step. Both paste what is on the system clipboard (layers from any
file or tab, as ⌘V does) when the browser lets the page read it, and
otherwise the layers copied in this design.
-- **Design panel** (`fig-design-panel`, toggled with ⌥8): alignment buttons
+- **Design panel** (`fig-design-panel`, toggled with ⌥8): the fixed selection
+ header offers Create component (`fig-create-component`) and Boolean operations
+ for editable selections. Design and Prototype
+ tabs support arrow-key navigation. Zoom and Present are in the top right;
+ the selected layer's heading stays visible while properties scroll.
+ Position groups alignment, X/Y, rotation, 90° rotation (`fig-rotate-90`),
+ and flip controls (`fig-flip-horizontal|vertical`). Layout groups dimensions,
+ resizing, auto layout, and clip content. The aspect-ratio lock
+ (`fig-lock-aspect-ratio`) constrains inspector width/height edits together.
+ Appearance groups opacity, radius, and visibility (`fig-appearance-visible`).
+ Alignment buttons
(`fig-align-<left|center|right|top|middle|bottom>`), name (`fig-name`),
position, size, rotation, radius, opacity (`fig-field-<x|y|w|h|rotation|
radius|opacity|font-size|stroke-weight>`; type a value or arithmetic, or
@@ -1171,30 +1224,35 @@ Layout and test hooks:
input `fig-fill-<n>-hex`, opacity `-opacity`, `-visibility`, and
`-remove`; "+" adds; drag a row's grip to reorder), stroke weight,
position, and dashes (`fig-field-dash`: `4, 2`, or `None`), clip
- content (`fig-clip-content`), the Text section for text layers (`fig-type`:
+ content (`fig-clip-content`), the Typography section for text layers (`fig-type`:
family `fig-font-family` (opens the font picker `fig-font-picker`: search
`fig-font-search`, options `fig-font-option` with `data-family`, the
- file's fonts first, then Google Fonts, each previewed in its face; a
+ file's fonts first, then Google Fonts, each previewed in its face; use
+ Up/Down to browse results and Enter to apply; a
missing font shows `fig-font-missing`), weight `fig-font-weight`,
- `fig-italic`, size,
+ and size on one row,
line height `fig-field-line-height` as `Auto`, a percentage, or pixels,
- letter spacing `fig-field-letter-spacing`, paragraph spacing, horizontal
- and vertical alignment, auto width / auto height / fixed size
- `fig-text-resize`, `fig-underline`, strikethrough, and case
- `fig-text-case`), auto layout (`fig-auto-layout-section`: "+" or ⇧A adds
+ letter spacing `fig-field-letter-spacing`, and horizontal/vertical alignment.
+ Open Type settings (`fig-type-settings`) for `fig-italic`, `fig-underline`,
+ strikethrough, paragraph spacing, and case (`fig-text-case`). Auto width /
+ auto height / fixed size (`fig-text-resize`) is in Layout; Text content is
+ a disclosure in Typography), auto layout (`fig-auto-layout-section`: "+" or ⇧A adds
it, wrapping other layers in a new frame; "−" or ⌥⇧A removes it;
direction `fig-layout-direction`, gap `fig-field-gap` as a number or
- `Auto`, padding `fig-field-padding-h|v`, and the alignment grid
- `fig-layout-align`), width and height sizing (`fig-sizing-w|h`: Fixed,
- Hug, Fill) and `fig-absolute` for layers in auto layout, constraints
+ `Auto`, padding `fig-field-padding-h|v` or independent sides via
+ `fig-padding-independent` (`fig-field-padding-left|top|right|bottom`), and the
+ alignment grid `fig-layout-align`), width and height sizing
+ (`fig-sizing-w|h`: Fixed, Hug, Fill, beside each dimension) and `fig-absolute`
+ ("Ignore auto layout") for layers in auto layout, constraints
(`fig-constraint-h|v`; children follow them when their frame is resized,
and groups scale theirs), effects (`fig-effects`: "+" adds a drop shadow;
- rows `fig-effect-<n>` pick the kind in `fig-effect-<n>-type` and take
- offset, blur `fig-effect-<n>-blur`, spread, and color), boolean
- operations (`fig-boolean-row`, shown for two or more layers or a boolean
- layer: `fig-boolean-<union|subtract|intersect|exclude>`, pressed for the
+ rows `fig-effect-<n>` open `fig-effect-<n>-settings`; inside that
+ popover, `fig-effect-<n>-type` picks the kind alongside offset, blur `fig-effect-<n>-blur`, spread,
+ and color in a popover beside the inspector), boolean
+ operations (the selected-layer header menu `fig-boolean-menu`; a boolean
+ layer also shows `fig-boolean-row`: `fig-boolean-<union|subtract|intersect|exclude>`, pressed for the
boolean's current operation, which a click changes, and `fig-flatten`),
- a Layout grid section for frames (`fig-layout-grids`: "+" adds a 10 px
+ a Layout guide section for frames (`fig-layout-grids`: "+" adds a 10 px
grid; rows `fig-grid-<n>` with color `fig-grid-color-<n>`, kind
`fig-grid-type-<n>` (`GRID`, `COLUMNS`, `ROWS`), `fig-grid-visible-<n>`,
`fig-grid-remove-<n>`, and `fig-grid-settings-<n>` opening count
@@ -1203,16 +1261,20 @@ Layout and test hooks:
or offset `fig-grid-offset-<n>`, and `fig-grid-gutter-<n>`), and the
Export section (`fig-export`): "+" adds a preset (1x PNG, then 2x, 3x…;
rows `fig-export-row-<n>` with size `fig-export-size-<n>` typed as `2x`,
- `0.5x`, `512w`, or `300h`, `fig-export-suffix-<n>`, format
- `fig-export-format-<n>` (`PNG`, `JPEG`, `SVG`, `PDF`), and for SVG and
- JPG `fig-export-options-<n>`: `fig-export-outline-text-<n>`,
+ `0.5x`, `512w`, or `300h`, format
+ `fig-export-format-<n>` (`PNG`, `JPEG`, `SVG`, `PDF`). Open
+ `fig-export-options-<n>` for `fig-export-suffix-<n>` and format-specific settings: `fig-export-outline-text-<n>`,
`fig-export-include-id-<n>`, or `fig-export-quality-<n>`; "−" is
`fig-export-remove-<n>`). Presets are saved in the file (read-only viewers
keep theirs for the session). `fig-export-button` ("Export <name>")
downloads one file named as Figma names it (`[email protected]`) or a ZIP of
several, `fig-export-preview-toggle` shows a preview
- (`fig-export-preview`), and `fig-copy-svg` is Copy as SVG; ⌘/Ctrl+⇧E
- exports the selection with its presets (1x PNG without). Read-only
+ (`fig-export-preview`), and the Export header’s "Copy as" menu contains
+ Copy as PNG and `fig-copy-svg` (Copy as SVG); ⌘/Ctrl+⇧E
+ exports the selection with its presets (1x PNG without). Inspector choices
+ use custom listboxes: click the trigger, then its named `option`; use
+ arrow keys/Enter to choose and Escape to dismiss with focus restored.
+ Read-only
viewers see the same values as text. The Code tab is Dev Mode's inspect
panel (`fig-dev-inspect`): size and position (`fig-dev-width`,
`fig-dev-height`), auto layout padding and gap (`fig-dev-padding`),
@@ -1287,17 +1349,22 @@ Layout and test hooks:
`fig-color-alpha-field`, and "On this page" swatches
(`fig-color-swatch`). Dragging previews live and is one undo step;
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),
- Pencil (⇧P), Text (T), Hand (H) as `fig-tool-<name>`, the boolean menu
+- **Toolbar** (`fig-toolbar`): one floating row centered across the editor at the bottom. Tool groups
+ retain their last-used tool: Move/Hand (`fig-tool-menu-move`), shapes
+ (`fig-tool-menu-rectangle`: Rectangle, Line, Arrow, Ellipse), and
+ Pen/Pencil (`fig-tool-menu-pen`). Menu choices are `fig-choose-<name>`;
+ the group's current button is `fig-tool-<name>`. Frame and Text have their
+ own buttons. Shortcuts remain V/H, F, R/L/⇧L/O, P/⇧P, and T; ⇧ while drawing
+ snaps lines to 45°. Arrow keys, Enter, and Escape operate the menus.
+ Comment (`fig-tool-comment`, C; `fig-comments-unread` counts unread threads)
+ is followed by Actions (`fig-actions-button`) and Dev Mode
+ (`fig-panel-tab-code`, a toggle). Selecting a drawing tool exits Comment.
+ The boolean menu is in the selected layer's inspector heading
(`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`,
- `unsaved`, `saving`, or `error`), the zoom menu (`fig-zoom-menu`), and the
- shortcuts dialog (`fig-shortcuts`, Ctrl+⇧+?). After the tools: Comment
- (`fig-tool-comment`, C; `fig-comments-unread` counts unread threads)
- where the design has comments, and Present (`fig-present-button`,
- ⌥⌘↵ / Ctrl+Alt+Enter).
+ and `fig-menu-flatten`). Zoom (`fig-zoom-menu`) and Present
+ (`fig-present-button`, ⌥⌘↵ / Ctrl+Alt+Enter) are in the inspector header,
+ or float at the canvas's top right while that panel is hidden. The
+ shortcuts dialog (`fig-shortcuts`, Ctrl+⇧+?) is also in the main menu.
- **Comments** (the comment tool, C): pins (`fig-comment-pin`,
`data-thread`, `data-unread`) at a constant size over the canvas; a click
places a comment on the top-level frame there (it moves with the frame)
@@ -1307,9 +1374,11 @@ Layout and test hooks:
`fig-comment-item`, mentions `fig-comment-mention`, `fig-comment-reply`
with `fig-comment-reply-post`, `fig-comment-resolve` /
`fig-comment-reopen`, and the author's `fig-comment-delete`). The right
- panel becomes the comments list (`fig-comments-panel`, filters
- `fig-comments-filter-<open|resolved|all>`, rows `fig-comment-row` with
- `data-unread`; a row opens the thread on its page). Escape closes the
+ panel becomes the comments list (`fig-comments-panel`), with Present and
+ Zoom in its header. Search (`fig-comments-search`) matches comment text,
+ replies, and author names. Open `fig-comments-filter` for
+ `fig-comments-filter-<open|resolved|all>`. Rows `fig-comment-row` have
+ `data-unread`; a row opens the thread on its page. Escape closes the
thread, then the tool. In the app, comments are document discussions
with a `fig` thread anchor, on wherever the viewer is; the fixture keeps
them in memory.
@@ -1328,11 +1397,13 @@ Layout and test hooks:
`fig-present-next`, Copy link to frame (`fig-present-copy-link`, a link
with `?present=<frame id>` that opens presenting it), and
`fig-present-exit`. Variant changes and Scroll to are not played.
-- **Prototype tab** (`fig-panel-tab-prototype`, beside Design and Code;
+- **Prototype tab** (`fig-panel-tab-prototype`, beside Design;
`fig-prototype-panel`): for a top-level frame, its flow starting point
(`fig-flow-add`, name `fig-flow-name`, `fig-flow-remove`); for a layer,
its interactions (`fig-proto-interaction`): editors add a click
- interaction (`fig-proto-add`), and set its action (`fig-proto-action`:
+ interaction (`fig-proto-add`). Click its compact row (`fig-proto-open`)
+ to open settings beside the inspector (`fig-proto-settings`); adding an
+ interaction opens its settings automatically. Set its action (`fig-proto-action`:
Navigate to, Open overlay, Back), destination frame
(`fig-proto-destination`), animation (`fig-proto-transition`), and
duration in ms (`fig-proto-duration`), or remove it (`fig-proto-remove`);