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.

fix(fig): restore import and export fidelity for real Figma files (#7480)

Jacob Beckermaned30acb82492
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 80e6daddd9..994e1f4968 100644
--- a/apps/web/src/features/block-fig/browser-test/README.md
+++ b/apps/web/src/features/block-fig/browser-test/README.md
@@ -96,11 +96,14 @@ App's copy, keeping the instance.
(`&people=alice,bob` by default), each with the real shared-design session
(Loro document, WAL, awareness), engine, and viewer, connected through an
in-page sync server (`memory-sync.ts`, the `LiveSyncSource` contract the sync
-service's transport implements); `window.figFixture.collab.people()` exposes
-each person's engine, saves, status, and peers.
-`collaboration.browser.e2e.ts` covers edits and undo reaching the other
-person, remote pointers, selections and avatars, one person storing the
-merged file, and following someone's view.
+service's transport implements), which also holds the stored file;
+`window.figFixture.collab.people()` exposes each person's engine, saves,
+status, and peers, and `storeOutside()`, `reopen(name)`, and
+`setReachable(bool)` replace the stored file, reopen a person, and take the
+server down. `collaboration.browser.e2e.ts` covers edits and undo reaching
+the other person, remote pointers, selections and avatars, one person
+storing the merged file, following someone's view, a file stored outside
+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.
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 e12753edef..395d98c8f3 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
@@ -2,8 +2,9 @@
* Several people editing one design side by side (`?collab&file=…`): each
* runs the real design session (Loro document, WAL, awareness), engine,
* sharing, and viewer, connected through an in-page sync server
- * (`memory-sync.ts`). `window.figFixture.collab` exposes each person's
- * engine, saves, and status.
+ * (`memory-sync.ts`), which also holds the stored file. `window.figFixture
+ * .collab` exposes each person's engine, saves, and status, and can store a
+ * file outside the session, reopen a person, or take the server down.
*/
import { FigEngine } from '@core/fig-engine/client';
@@ -19,10 +20,12 @@ import {
Show,
Switch,
} from 'solid-js';
+import { SessionNotice } from '../components/session-notice';
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 { FigViewer } from '../views/fig-viewer';
@@ -52,6 +55,17 @@ export interface FixturePerson {
peers: () => string[];
}
+/** The fixture's controls, for tests. */
+export interface FixtureCollab {
+ people: () => FixturePerson[];
+ /** Stores a new blank design outside the session (an upload, say). */
+ storeOutside: () => Promise<void>;
+ /** Closes a person's design and opens the stored file again. */
+ reopen: (name: string) => void;
+ /** Takes the sync server down (`false`) or brings it back. */
+ setReachable: (reachable: boolean) => void;
+}
+
const shortName = (id: string | undefined) =>
(id ?? '')
.replace(/^macro\|/, '')
@@ -60,15 +74,16 @@ const shortName = (id: string | undefined) =>
function Person(props: {
user: string;
- bytes: Promise<ArrayBuffer>;
server: MemorySyncServer;
onPerson: (person: FixturePerson) => void;
+ retry: () => void;
}) {
const documentId = 'fixture-design';
const [engine, setEngine] = createSignal<FigEngine>();
const [sharing, setSharing] = createSignal<FigSharing>();
const [saves, setSaves] = createSignal(0);
const [failure, setFailure] = createSignal<string>();
+ const [replaced, setReplaced] = createSignal(false);
const session = createDesignCollabSession({
documentId,
userId: props.user,
@@ -88,15 +103,79 @@ function Person(props: {
const state = session.state();
return state.t === 'ready' ? state.doc : undefined;
};
+ const failed = () => {
+ const state = session.state();
+ return state.t === 'error' ? state.message : undefined;
+ };
props.onPerson({
name: shortName(props.user),
engine,
saves,
status: () =>
- `${session.state().t} ${session.collaboration.status()}${failure() ? ` ${failure()}` : ''}`,
+ `${session.state().t} ${session.collaboration.status()}${replaced() ? ' replaced' : ''}${failure() ? ` ${failure()}` : ''}`,
peers: () => session.collaboration.peers().map((p) => p.name),
});
+ /** Opens the stored file, shared through `shared` when given. */
+ const openDesign = (shared?: Parameters<typeof shareFigEngine>[1]) => {
+ let closed = false;
+ let opened: FigEngine | undefined;
+ 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;
+ if (shared) {
+ sharedEngine = await shareFigEngine(opened, shared, {
+ fingerprint,
+ delivered: session.delivered,
+ });
+ if (closed) return;
+ sharedEngine.onReplaced(() => setReplaced(true));
+ setSharing(sharedEngine);
+ }
+ setEngine(opened);
+ } catch (e) {
+ setFailure(String(e));
+ }
+ };
+ void open();
+ onCleanup(() => {
+ closed = true;
+ sharedEngine?.close();
+ opened?.close();
+ setEngine(undefined);
+ setSharing(undefined);
+ });
+ };
+
+ const viewer = (editable: () => boolean, live: boolean) => (
+ <Show when={engine()} keyed>
+ {(e) => (
+ <FigViewerProvider
+ context={{
+ engine: e,
+ fileName: () => 'Design',
+ download: () => {},
+ notifyError: (m) => setFailure(m),
+ notifyInfo: () => {},
+ canEdit: editable,
+ save: async (bytes) => {
+ props.server.store(bytes);
+ setSaves((n) => n + 1);
+ },
+ collaboration: live ? session.collaboration : undefined,
+ sharing: sharing(),
+ }}
+ >
+ <FigViewer />
+ </FigViewerProvider>
+ )}
+ </Show>
+ );
+
return (
<section class="flex min-w-0 flex-1 flex-col border-edge-muted border-r">
<header class="flex h-8 shrink-0 items-center gap-2 border-edge-muted border-b px-3 text-xs">
@@ -106,61 +185,44 @@ function Person(props: {
</span>
</header>
<div
- class="min-h-0 flex-1"
+ class="flex min-h-0 flex-1 flex-col"
data-testid={`fig-person-${shortName(props.user)}`}
>
<Switch>
<Match when={failure()}>
{(message) => <div class="p-4 text-failure">{message()}</div>}
</Match>
+ <Match when={failed()}>
+ {(message) => {
+ onMount(() => openDesign());
+ return (
+ <>
+ <SessionNotice
+ message={`${message()} The design is open read-only.`}
+ action="Retry"
+ onAction={props.retry}
+ />
+ <div class="min-h-0 flex-1">{viewer(() => false, false)}</div>
+ </>
+ );
+ }}
+ </Match>
<Match when={doc()} keyed>
{(ready) => {
- onMount(() => {
- let closed = false;
- let opened: FigEngine | undefined;
- let shared: FigSharing | undefined;
- const open = async () => {
- try {
- opened = await FigEngine.open(await props.bytes);
- if (closed) return;
- shared = await shareFigEngine(opened, ready);
- if (closed) return;
- setSharing(shared);
- setEngine(opened);
- } catch (e) {
- setFailure(String(e));
- }
- };
- void open();
- onCleanup(() => {
- closed = true;
- shared?.close();
- opened?.close();
- setEngine(undefined);
- });
- });
+ onMount(() => openDesign(ready));
return (
- <Show when={engine()} keyed>
- {(e) => (
- <FigViewerProvider
- context={{
- engine: e,
- fileName: () => 'Design',
- download: () => {},
- notifyError: (m) => setFailure(m),
- notifyInfo: () => {},
- canEdit: () => true,
- save: async () => {
- setSaves((n) => n + 1);
- },
- collaboration: session.collaboration,
- sharing: sharing(),
- }}
- >
- <FigViewer />
- </FigViewerProvider>
- )}
- </Show>
+ <>
+ <Show when={replaced()}>
+ <SessionNotice
+ message="This design was replaced by a newer file. Reload to edit the latest version."
+ action="Reload"
+ onAction={props.retry}
+ />
+ </Show>
+ <div class="min-h-0 flex-1">
+ {viewer(() => !replaced(), true)}
+ </div>
+ </>
);
}}
</Match>
@@ -172,24 +234,55 @@ function Person(props: {
export function CollabFixture(props: { fileUrl: string; users: string[] }) {
const server = new MemorySyncServer();
- const bytes = fetch(props.fileUrl).then((r) => {
+ const [stored, setStored] = createSignal(false);
+ const load = async () => {
+ const r = await fetch(props.fileUrl);
if (!r.ok) throw new Error(`${props.fileUrl}: ${r.status}`);
- return r.arrayBuffer();
- });
- const people: FixturePerson[] = [];
- window.figFixture.collab = { people: () => people };
+ server.store(new Uint8Array(await r.arrayBuffer()));
+ setStored(true);
+ };
+ void load();
+ const people = new Map<string, FixturePerson>();
+ const [opened, setOpened] = createSignal<Record<string, number>>({});
+ const reopen = (user: string) =>
+ setOpened((o) => ({ ...o, [user]: (o[user] ?? 0) + 1 }));
+ const controls: FixtureCollab = {
+ people: () =>
+ props.users.flatMap((u) => {
+ const p = people.get(u);
+ return p ? [p] : [];
+ }),
+ storeOutside: async () => {
+ server.store(await FigEngine.blank('Replaced'));
+ },
+ reopen: (name) => {
+ const user = props.users.find((u) => shortName(u) === name);
+ if (user) reopen(user);
+ },
+ setReachable: (reachable) => {
+ server.reachable = reachable;
+ },
+ };
+ window.figFixture.collab = controls;
return (
<div class="flex min-h-0 flex-1">
- <For each={props.users}>
- {(user) => (
- <Person
- user={user}
- bytes={bytes}
- server={server}
- onPerson={(p) => people.push(p)}
- />
- )}
- </For>
+ <Show when={stored()}>
+ <For each={props.users}>
+ {(user) => (
+ // The child's parameter makes Show call it again for each key.
+ <Show when={(opened()[user] ?? 0) + 1} keyed>
+ {(_opening) => (
+ <Person
+ user={user}
+ server={server}
+ onPerson={(p) => people.set(user, p)}
+ retry={() => reopen(user)}
+ />
+ )}
+ </Show>
+ )}
+ </For>
+ </Show>
</div>
);
}
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 e7e71c1b13..d5b669555e 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
@@ -148,3 +148,65 @@ test('both people’s layers appear on both sides, and following shows the other
await bob.click({ position: { x: 10, y: 10 } });
await expect(person(page, 'Bob').getByTestId('fig-following')).toHaveCount(0);
});
+
+test('a file stored outside the design starts it over, and the others reload', async ({
+ page,
+}) => {
+ await open(page);
+ const alice = person(page, 'Alice').getByTestId('fig-canvas');
+ await drawRectangle(page, alice, [0.1, 0.72], [0.4, 0.8]);
+ await expect.poll(() => layersNamed(page, 1, 'Rectangle 1')).toBe(1);
+ // The merged file is stored, and reopening it keeps the rectangle once.
+ await expect
+ .poll(() =>
+ page.evaluate(() =>
+ window.figFixture.collab?.people().some((p) => p.saves() > 0)
+ )
+ )
+ .toBe(true);
+ await page.evaluate(() => window.figFixture.collab?.reopen('Bob'));
+ await expect.poll(() => layersNamed(page, 1, 'Rectangle 1')).toBe(1);
+
+ // A new upload replaces the stored file; whoever opens it next gets it
+ // without the changes made on the old one.
+ await page.evaluate(() => window.figFixture.collab?.storeOutside());
+ await page.evaluate(() => window.figFixture.collab?.reopen('Bob'));
+ await expect(person(page, 'Bob').getByTestId('fig-page')).toHaveText([
+ 'Page 1',
+ ]);
+ await expect.poll(() => layersNamed(page, 1, 'Rectangle 1')).toBe(0);
+ // Alice's copy is out of date: read-only, with a way to reload.
+ const notice = person(page, 'Alice').getByTestId('fig-session-notice');
+ await expect(notice).toContainText('replaced');
+ await expect(
+ person(page, 'Alice').getByTestId('fig-tool-rectangle')
+ ).toBeHidden();
+ await notice.getByTestId('fig-session-action').click();
+ await expect(person(page, 'Alice').getByTestId('fig-page')).toHaveText([
+ 'Page 1',
+ ]);
+ await expect(
+ person(page, 'Alice').getByTestId('fig-tool-rectangle')
+ ).toBeVisible();
+ await expect.poll(() => layersNamed(page, 0, 'Rectangle 1')).toBe(0);
+});
+
+test('an unreachable sync service opens the design read-only, with retry', async ({
+ page,
+}) => {
+ await open(page);
+ await page.evaluate(() => {
+ window.figFixture.collab?.setReachable(false);
+ window.figFixture.collab?.reopen('Bob');
+ });
+ const bob = person(page, 'Bob');
+ await expect(bob.getByTestId('fig-session-notice')).toContainText(
+ 'read-only'
+ );
+ await expect(bob.getByTestId('fig-layer-row').first()).toBeVisible();
+ await expect(bob.getByTestId('fig-tool-rectangle')).toBeHidden();
+ await page.evaluate(() => window.figFixture.collab?.setReachable(true));
+ await bob.getByTestId('fig-session-action').click();
+ await expect(bob.getByTestId('fig-tool-rectangle')).toBeVisible();
+ await expect(bob.getByTestId('fig-session-notice')).toHaveCount(0);
+});
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 3796eec324..ca7ac683df 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
@@ -129,14 +129,17 @@ 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-y')).toHaveValue('300');
- // Flip about the center: the origin moves to the right edge; undo.
+ // Flip about the center: as in Figma, the panel keeps the flip apart
+ // from position and rotation; undo.
await rightClick(page, 450, 350);
await page.getByTestId('fig-menu-flip-horizontal').click();
- await expect(page.getByTestId('fig-field-x')).toHaveValue('500');
+ 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 expect(page.getByTestId('fig-field-x')).toHaveValue('400');
+ // 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$/);
await expect(page.getByTestId('fig-field-y')).toHaveValue('400');
// The same menu on a layers panel row.
@@ -274,16 +277,13 @@ test('edits several layers at once, with mixed values', async ({ page }) => {
'2 layers selected'
);
- // Arrow keys move through the layer tree after a row is clicked.
+ // As in Figma, arrow keys nudge the layer after its row is clicked.
await rows(page).filter({ hasText: 'Rectangle 3' }).click();
await page.keyboard.press('ArrowDown');
- await expect(page.getByTestId('fig-name')).toHaveValue('Rectangle 2');
- await page.keyboard.press('ArrowDown');
- await expect(page.getByTestId('fig-name')).toHaveValue('Rectangle 1');
- await page.keyboard.press('ArrowUp');
- await expect(page.getByTestId('fig-name')).toHaveValue('Rectangle 2');
- // It did not move the layer.
- await expect(page.getByTestId('fig-field-y')).toHaveValue('100');
+ await expect(page.getByTestId('fig-field-y')).toHaveValue('101');
+ await page.keyboard.press('Shift+ArrowUp');
+ await expect(page.getByTestId('fig-field-y')).toHaveValue('91');
+ await expect(page.getByTestId('fig-name')).toHaveValue('Rectangle 3');
});
test('sets the canvas color from the picker', async ({ page }) => {
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 b7a980d2f6..69719abcc5 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
@@ -161,7 +161,7 @@ test('zooms with Figma’s shortcuts', async ({ page }) => {
await page.getByTestId('fig-canvas').focus();
await page.keyboard.press('Shift+0');
await expect(zoom).toHaveText(/100%/);
- await page.keyboard.press('Control+=');
+ await page.keyboard.press('ControlOrMeta+=');
await expect(zoom).toHaveText(/200%/);
await page.keyboard.press('Shift+1');
await expect(zoom).not.toHaveText(/200%/);
@@ -236,6 +236,44 @@ test('draws, moves, and saves shapes', async ({ page }) => {
.toEqual([]);
});
+test('undo and redo bring back the selection', async ({ page }) => {
+ await openNew(page);
+ const canvas = page.getByTestId('fig-canvas');
+ await canvas.focus();
+ await page.keyboard.press('r');
+ await dragOnCanvas(page, [100, 100], [140, 140]);
+ await expect(page.getByTestId('fig-name')).toHaveValue('Rectangle 1');
+ const rows = page.getByTestId('fig-layer-row');
+ // Top-most first: the copy is the first row.
+ const selectedRows = () =>
+ rows.evaluateAll((all) =>
+ all.flatMap((r, i) =>
+ r.getAttribute('aria-selected') === 'true' ? [i] : []
+ )
+ );
+ await canvas.focus();
+ await page.keyboard.press('Control+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 expect(rows).toHaveCount(1);
+ await expect.poll(selectedRows).toEqual([0]);
+ // … and redoing it, the copy.
+ await page.keyboard.press('Control+Shift+z');
+ await expect(rows).toHaveCount(2);
+ await expect.poll(selectedRows).toEqual([0]);
+ // Undoing a nudge of a layer no longer selected selects it.
+ await page.keyboard.press('Escape');
+ await rows.nth(1).click();
+ await canvas.focus();
+ await page.keyboard.press('ArrowRight');
+ await page.keyboard.press('Escape');
+ await expect.poll(selectedRows).toEqual([]);
+ await page.keyboard.press('Control+z');
+ await expect.poll(selectedRows).toEqual([1]);
+});
+
test('lays out with auto layout', async ({ page }) => {
await openNew(page);
const canvas = page.getByTestId('fig-canvas');
@@ -397,6 +435,36 @@ test('resizes several layers and rotates one', async ({ page }) => {
await expect(page.getByTestId('fig-field-rotation')).not.toHaveValue('0');
});
+test('keeps a flip apart from rotation and position', async ({ page }) => {
+ await openNew(page);
+ const canvas = page.getByTestId('fig-canvas');
+ await canvas.focus();
+ await page.keyboard.press('r');
+ await dragOnCanvas(page, [100, 100], [220, 180]);
+ await canvas.focus();
+ await page.keyboard.press('Shift+h');
+ // As in Figma, a horizontal flip keeps the angle and the top left corner.
+ await expect(page.getByTestId('fig-field-rotation')).toHaveValue('0');
+ await expect(page.getByTestId('fig-field-x')).toHaveValue('100');
+ const rotation = page.getByTestId('fig-field-rotation');
+ await rotation.fill('90');
+ await rotation.press('Enter');
+ await rotation.fill('0');
+ await rotation.press('Enter');
+ await expect(page.getByTestId('fig-field-x')).toHaveValue('100');
+ // Unflipped again, a vertical flip reads as a half turn; its corners
+ // still resize it.
+ await canvas.focus();
+ await page.keyboard.press('Shift+h');
+ await page.keyboard.press('Shift+v');
+ await expect(page.getByTestId('fig-field-rotation')).toHaveValue(/^-?180$/);
+ await dragOnCanvas(page, [220, 180], [260, 200]);
+ await expect(page.getByTestId('fig-field-w')).toHaveValue('160');
+ await expect(page.getByTestId('fig-field-h')).toHaveValue('100');
+ await expect(page.getByTestId('fig-field-x')).toHaveValue('260');
+ await expect(page.getByTestId('fig-field-y')).toHaveValue('200');
+});
+
test('draws lines and arrows', async ({ page }) => {
await openNew(page);
const canvas = page.getByTestId('fig-canvas');
@@ -500,4 +568,11 @@ test('is read-only without edit access', async ({ page }) => {
'Settings',
'Home',
]);
+ // With nothing to nudge, arrow keys move through the layer tree.
+ await page
+ .getByTestId('fig-layer-row')
+ .filter({ hasText: 'Settings' })
+ .click();
+ await page.keyboard.press('ArrowDown');
+ await expect(page.getByTestId('fig-design-panel')).toContainText('Home');
});
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 6f325bb5be..5b28d9c222 100644
--- a/apps/web/src/features/block-fig/browser-test/fixture.tsx
+++ b/apps/web/src/features/block-fig/browser-test/fixture.tsx
@@ -18,7 +18,7 @@ import { FigOpening } from '../components/fig-opening';
import { FigViewerProvider } from '../context/fig-viewer-context';
import type { FigCommentAnchor, FigPerson } from '../core/comments';
import { FigViewer } from '../views/fig-viewer';
-import { CollabFixture, type FixturePerson } from './collab-fixture';
+import { CollabFixture, type FixtureCollab } from './collab-fixture';
import { fixtureFontSource } from './font-source';
import { createMemoryComments, FIXTURE_PEOPLE } from './memory-comments';
import {
@@ -40,7 +40,7 @@ declare global {
/** Font stylesheets and files the viewer asked for. */
fontRequests: () => string[];
/** With `?collab`: the people editing together. */
- collab?: { people: () => FixturePerson[] };
+ collab?: FixtureCollab;
/** With `?libraries`: the designs in memory, and opening one. */
libraries?: {
open: (id: string) => Promise<void>;
diff --git a/apps/web/src/features/block-fig/browser-test/memory-sync.ts b/apps/web/src/features/block-fig/browser-test/memory-sync.ts
index bbff4c038f..1f6d8506ad 100644
--- a/apps/web/src/features/block-fig/browser-test/memory-sync.ts
+++ b/apps/web/src/features/block-fig/browser-test/memory-sync.ts
@@ -23,16 +23,34 @@ export class MemorySyncServer {
private readonly awareness = new EphemeralStore(10_000);
private readonly clients = new Set<(event: SyncSourceEvent) => void>();
private initialized = false;
+ private file = new Uint8Array();
+ /** While `false`, people opening the design cannot reach the server. */
+ reachable = true;
constructor() {
this.doc.setPeerId(99n);
}
+ /** The stored `.fig` (document storage, which people open), a copy. */
+ stored(): ArrayBuffer {
+ return this.file.slice().buffer;
+ }
+
+ store(bytes: Uint8Array): void {
+ this.file = bytes.slice();
+ }
+
+ private ensureReachable() {
+ if (!this.reachable) throw new Error('The sync service is unreachable.');
+ }
+
async exists(): Promise<boolean> {
+ this.ensureReachable();
return this.initialized;
}
async initialize(snapshot: Uint8Array): Promise<void> {
+ this.ensureReachable();
if (this.initialized) throw new Error('already initialized');
this.doc.import(snapshot);
this.initialized = true;
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 92d4238d5c..daa0b26581 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
@@ -182,9 +182,15 @@ test('switches fonts, loading them first', async ({ page }) => {
'data-value',
'Roboto Mono'
);
- const requests = await page.evaluate(() => window.figFixture.fontRequests());
- expect(requests.some((r) => r.includes('family=Roboto+Mono'))).toBe(true);
- expect(requests.some((r) => r.endsWith('InterVariable.ttf'))).toBe(true);
+ // The panel shows the family as soon as it is picked; its files load after.
+ const requested = async (match: (r: string) => boolean) =>
+ (await page.evaluate(() => window.figFixture.fontRequests())).some(match);
+ await expect
+ .poll(() => requested((r) => r.includes('family=Roboto+Mono')))
+ .toBe(true);
+ await expect
+ .poll(() => requested((r) => r.endsWith('InterVariable.ttf')))
+ .toBe(true);
await expect
.poll(async () => (await textInfo(page))?.fontStatus)
.toBe('AVAILABLE');
diff --git a/apps/web/src/features/block-fig/components/session-notice.tsx b/apps/web/src/features/block-fig/components/session-notice.tsx
new file mode 100644
index 0000000000..e9db5cdad6
--- /dev/null
+++ b/apps/web/src/features/block-fig/components/session-notice.tsx
@@ -0,0 +1,33 @@
+/**
+ * A bar above the design explaining why it is open read-only (the sync
+ * service is unreachable, or the file was replaced), with the one action
+ * that helps. Presentational.
+ */
+
+import WarningCircle from '@phosphor/warning-circle.svg';
+import { Button } from '@ui/components/Button';
+
+export function SessionNotice(props: {
+ message: string;
+ action: string;
+ onAction: () => void;
+}) {
+ return (
+ <div
+ role="status"
+ class="flex shrink-0 items-center gap-2 border-edge-muted border-b bg-inset px-3 py-1.5 text-ink text-xs"
+ data-testid="fig-session-notice"
+ >
+ <WarningCircle class="size-3.5 shrink-0 text-warning" />
+ <span class="min-w-0 flex-1">{props.message}</span>
+ <Button
+ variant="outline"
+ size="sm"
+ data-testid="fig-session-action"
+ onClick={() => props.onAction()}
+ >
+ {props.action}
+ </Button>
+ </div>
+ );
+}
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 9450e9cf67..0e75644141 100644
--- a/apps/web/src/features/block-fig/components/viewer-toolbar.tsx
+++ b/apps/web/src/features/block-fig/components/viewer-toolbar.tsx
@@ -91,7 +91,9 @@ export function ViewerToolbar(props: {
return (
<div
- class="-translate-x-1/2 absolute bottom-3 left-1/2 z-10 flex items-center gap-0.5 rounded-xl border border-edge-muted bg-menu p-1 shadow-lg"
+ // 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"
data-testid="fig-toolbar"
onPointerDown={(e) => e.stopPropagation()}
>
diff --git a/apps/web/src/features/block-fig/context/fig-viewer-context.tsx b/apps/web/src/features/block-fig/context/fig-viewer-context.tsx
index 92f1591cf2..e31a74b102 100644
--- a/apps/web/src/features/block-fig/context/fig-viewer-context.tsx
+++ b/apps/web/src/features/block-fig/context/fig-viewer-context.tsx
@@ -35,10 +35,21 @@ export interface FigSharing {
onIncoming: (listener: () => void) => () => void;
/** The shared version the engine holds, recorded with a stored file. */
appliedVersion: () => Version;
+ /**
+ * Records that `bytes` are about to be stored, so whoever opens them
+ * applies the shared changes to them. `false` when that could not reach
+ * the sync service (offline): the file is then not stored.
+ */
+ willStore: (bytes: Uint8Array<ArrayBuffer>) => Promise<boolean>;
/** Tells everyone a file holding `version` was stored. */
markStored: (version: Version) => void;
/** Calls `listener` when someone else stored everything seen here. */
onStoredElsewhere: (listener: () => void) => () => void;
+ /**
+ * Calls `listener` when the shared design started over on a file stored
+ * outside it (a new upload, an AI edit): this copy is out of date.
+ */
+ onReplaced: (listener: () => void) => () => void;
close: () => void;
}
diff --git a/apps/web/src/features/block-fig/core/collab-entries.test.ts b/apps/web/src/features/block-fig/core/collab-entries.test.ts
index ac1cc34b45..18376a7032 100644
--- a/apps/web/src/features/block-fig/core/collab-entries.test.ts
+++ b/apps/web/src/features/block-fig/core/collab-entries.test.ts
@@ -3,10 +3,15 @@ import { describe, expect, it } from 'vitest';
import {
baseBlobs,
changedKeys,
+ designBase,
designFormat,
type EntryKey,
+ entriesApplyTo,
+ fileFingerprint,
readEntries,
readValues,
+ recordStoredFile,
+ restartOnFile,
seedDesign,
writeEntryChanges,
} from './collab-entries';
@@ -86,3 +91,55 @@ describe('collab entries', () => {
expect(value(alice)).toBe(value(bob));
});
});
+
+describe('stored files', () => {
+ it('applies entries to the file they began on and files stored from it', () => {
+ const doc = new LoroDoc();
+ seedDesign(doc);
+ // Shared before files were recorded: the first file opened begins it.
+ expect(entriesApplyTo(doc, 'first')).toBe(true);
+ expect(recordStoredFile(doc, 'first')).toBe(true);
+ expect(designBase(doc)).toBe('first');
+ expect(recordStoredFile(doc, 'first')).toBe(false);
+ // Someone stores the merged file; it is listed before it is stored.
+ recordStoredFile(doc, 'saved');
+ expect(entriesApplyTo(doc, 'first')).toBe(true);
+ expect(entriesApplyTo(doc, 'saved')).toBe(true);
+ // A file stored outside the design is not.
+ expect(entriesApplyTo(doc, 'uploaded')).toBe(false);
+ });
+
+ it('starts over on a replaced file, dropping the entries', () => {
+ const alice = new LoroDoc();
+ seedDesign(alice);
+ recordStoredFile(alice, 'first');
+ writeEntryChanges(alice, [
+ { container: 'figNodes', key: '1:2', value: 'AQID' },
+ { container: 'figBlobs', key: 'abc', value: 'BAUG' },
+ { container: 'figMeta', key: 'baseBlobs', value: '3' },
+ ]);
+ const bob = new LoroDoc();
+ sync(alice, bob);
+ restartOnFile(bob, 'uploaded');
+ sync(bob, alice);
+ for (const doc of [alice, bob]) {
+ expect(readEntries(doc)).toEqual(
+ expect.not.arrayContaining([
+ expect.objectContaining({ container: 'figNodes' }),
+ ])
+ );
+ expect(designFormat(doc)).toBe(1);
+ expect(designBase(doc)).toBe('uploaded');
+ expect(baseBlobs(doc)).toBeNull();
+ expect(entriesApplyTo(doc, 'uploaded')).toBe(true);
+ expect(entriesApplyTo(doc, 'first')).toBe(false);
+ }
+ });
+
+ it('fingerprints file bytes', async () => {
+ const a = await fileFingerprint(new Uint8Array([1, 2, 3]));
+ expect(a).toMatch(/^[0-9a-f]{32}$/);
+ expect(await fileFingerprint(new Uint8Array([1, 2, 3]))).toBe(a);
+ expect(await fileFingerprint(new Uint8Array([1, 2, 4]))).not.toBe(a);
+ });
+});
diff --git a/apps/web/src/features/block-fig/core/collab-entries.ts b/apps/web/src/features/block-fig/core/collab-entries.ts
index d2bc78f3d7..598c8f1bb4 100644
--- a/apps/web/src/features/block-fig/core/collab-entries.ts
+++ b/apps/web/src/features/block-fig/core/collab-entries.ts
@@ -52,6 +52,87 @@ export function seedDesign(doc: LoroDoc): void {
doc.commit({ origin: 'fig-seed' });
}
+// The stored files the entries apply to. Entries hold what changed since
+// the collaboration began, so they only apply to a file the collaboration
+// produced: the one it began on, or one stored from it. `figMeta.base` is
+// the fingerprint of the file the current entries began on, and
+// `figMeta["file:<fingerprint>"]` names, for every file opened or stored
+// since, the base it belongs to. A file stored outside the collaboration
+// (a new upload, an AI edit) is not listed: its opener starts the shared
+// design over on it, dropping the entries made on the file it replaced.
+
+/** `figMeta` key of the fingerprint of the file the entries began on. */
+export const BASE_KEY = 'base';
+
+const fileKey = (fingerprint: string) => `file:${fingerprint}`;
+
+/** Commit origin of changes to the stored files' record. */
+export const STORED_FILE_ORIGIN = 'fig-stored-file';
+
+/** The fingerprint of the file the shared entries began on, if recorded. */
+export function designBase(doc: LoroDoc): string | undefined {
+ const value = doc.getMap(META).get(BASE_KEY);
+ return typeof value === 'string' ? value : undefined;
+}
+
+/**
+ * Whether the shared entries apply to the stored file with `fingerprint`:
+ * it is the file they began on or one stored from it, or the design was
+ * shared before files were recorded.
+ */
+export function entriesApplyTo(doc: LoroDoc, fingerprint: string): boolean {
+ const base = designBase(doc);
+ return (
+ base === undefined || doc.getMap(META).get(fileKey(fingerprint)) === base
+ );
+}
+
+/**
+ * Records that the file with `fingerprint` holds the shared entries (it
+ * was opened, or is about to be stored); a design shared before files were
+ * recorded begins on it. Returns whether anything was written.
+ */
+export function recordStoredFile(doc: LoroDoc, fingerprint: string): boolean {
+ const meta = doc.getMap(META);
+ let base = designBase(doc);
+ if (base !== undefined && meta.get(fileKey(fingerprint)) === base)
+ return false;
+ if (base === undefined) {
+ base = fingerprint;
+ meta.set(BASE_KEY, base);
+ }
+ meta.set(fileKey(fingerprint), base);
+ doc.commit({ origin: STORED_FILE_ORIGIN });
+ return true;
+}
+
+/**
+ * Starts the shared design over on a file stored outside it: drops every
+ * entry (they were made on the file it replaced) and the facts about that
+ * file, and begins on this one.
+ */
+export function restartOnFile(doc: LoroDoc, fingerprint: string): void {
+ const meta = doc.getMap(META);
+ for (const container of FIG_CONTAINERS) {
+ if (container === META) continue;
+ const map = doc.getMap(container);
+ for (const key of map.keys()) map.delete(key);
+ }
+ // The format stays; what was known about the replaced file goes.
+ for (const key of meta.keys()) if (key !== 'format') meta.delete(key);
+ meta.set(BASE_KEY, fingerprint);
+ meta.set(fileKey(fingerprint), fingerprint);
+ doc.commit({ origin: STORED_FILE_ORIGIN });
+}
+
+/** A short, stable fingerprint of a stored file's bytes (SHA-256, hex). */
+export async function fileFingerprint(bytes: BufferSource): Promise<string> {
+ const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', bytes));
+ return [...digest.slice(0, 16)]
+ .map((b) => b.toString(16).padStart(2, '0'))
+ .join('');
+}
+
/** The current values of some entries, as changes to apply. */
export function readValues(
doc: LoroDoc,
diff --git a/apps/web/src/features/block-fig/core/rotation.test.ts b/apps/web/src/features/block-fig/core/rotation.test.ts
index 047ba5226e..012bc6bd83 100644
--- a/apps/web/src/features/block-fig/core/rotation.test.ts
+++ b/apps/web/src/features/block-fig/core/rotation.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
-import { rotationFor } from './rotation';
+import { isAxisAligned, resizedOrigin, rotationFor } from './rotation';
describe('rotation drags', () => {
it('turns counter-clockwise for positive degrees, as Figma shows them', () => {
@@ -13,3 +13,27 @@ describe('rotation drags', () => {
expect(rotationFor(0, 0, -0.2, true)).toBe(15);
});
});
+
+describe('resizing axis-aligned layers', () => {
+ it('treats half turns (vertical flips) as axis-aligned', () => {
+ expect(isAxisAligned(0)).toBe(true);
+ expect(isAxisAligned(-180)).toBe(true);
+ expect(isAxisAligned(180)).toBe(true);
+ expect(isAxisAligned(30)).toBe(false);
+ });
+
+ it('moves the panel point with the corner it sits on', () => {
+ const from = { x: 10, y: 20, w: 100, h: 50 };
+ const to = { x: 10, y: 20, w: 150, h: 80 };
+ // Unrotated: the top left corner stays.
+ expect(resizedOrigin({ x: 10, y: 20, rotation: 0 }, from, to)).toEqual({
+ x: 10,
+ y: 20,
+ });
+ // Half turned: the panel point is the bottom right corner, which moves.
+ expect(resizedOrigin({ x: 110, y: 70, rotation: 180 }, from, to)).toEqual({
+ x: 160,
+ y: 100,
+ });
+ });
+});
diff --git a/apps/web/src/features/block-fig/core/rotation.ts b/apps/web/src/features/block-fig/core/rotation.ts
index 1d358601eb..718efaaf59 100644
--- a/apps/web/src/features/block-fig/core/rotation.ts
+++ b/apps/web/src/features/block-fig/core/rotation.ts
@@ -13,3 +13,35 @@ export function rotationFor(
if (snap) r = Math.round(r / 15) * 15;
return Math.round(r * 100) / 100;
}
+
+const isHalfTurn = (rotation: number) =>
+ Math.abs(Math.abs(rotation) - 180) < 0.01;
+
+/**
+ * Whether a layer at `rotation` (as the panel shows it) lies along the
+ * page's axes, so its selection box is the layer itself: unrotated, or
+ * turned half way (which is also how a vertically flipped layer reads).
+ */
+export function isAxisAligned(rotation: number): boolean {
+ return Math.abs(rotation) < 0.01 || isHalfTurn(rotation);
+}
+
+type Box = { x: number; y: number; w: number; h: number };
+
+/**
+ * The panel X and Y of an axis-aligned layer whose page bounds `from`
+ * become `to`: the panel point is the top left corner, or the bottom right
+ * one when the layer is turned half way.
+ */
+export function resizedOrigin(
+ info: { x: number; y: number; rotation: number },
+ from: Box,
+ to: Box
+): { x: number; y: number } {
+ if (isHalfTurn(info.rotation))
+ return {
+ x: info.x + (to.x + to.w - (from.x + from.w)),
+ y: info.y + (to.y + to.h - (from.y + from.h)),
+ };
+ return { x: info.x + (to.x - from.x), y: info.y + (to.y - from.y) };
+}
diff --git a/apps/web/src/features/block-fig/core/shortcuts.ts b/apps/web/src/features/block-fig/core/shortcuts.ts
index bdca90b12e..b64f4c6649 100644
--- a/apps/web/src/features/block-fig/core/shortcuts.ts
+++ b/apps/web/src/features/block-fig/core/shortcuts.ts
@@ -421,6 +421,13 @@ export const SHORTCUT_GROUPS: { title: string; items: ShortcutHelp[] }[] = [
{ action: 'Collapse layers', keys: ['⌥', 'L'] },
],
},
+ {
+ title: 'Review',
+ items: [
+ { action: 'Comment', keys: ['C'] },
+ { action: 'Present', keys: ['mod', '⌥', '↵'] },
+ ],
+ },
{
title: 'Export',
items: [
diff --git a/apps/web/src/features/block-fig/fig-block.tsx b/apps/web/src/features/block-fig/fig-block.tsx
index 2f58d49214..09102bfa8a 100644
--- a/apps/web/src/features/block-fig/fig-block.tsx
+++ b/apps/web/src/features/block-fig/fig-block.tsx
@@ -54,12 +54,14 @@ import {
Switch,
} from 'solid-js';
import { FigOpening } from './components/fig-opening';
+import { SessionNotice } from './components/session-notice';
import type { FigCommentStore } from './context/fig-comments';
import {
type FigCollaboration,
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';
@@ -86,6 +88,10 @@ function FigHost(props: {
/** The shared document, when the design is edited live. */
shared?: LoroDoc;
collaboration?: FigCollaboration;
+ /** Whether every change made here reached the sync service. */
+ delivered?: () => Promise<boolean>;
+ /** Why the design is read-only, with the action that helps. */
+ notice?: { message: string; action: string; onAction: () => void };
comments?: FigCommentStore;
/** A frame to present on opening (from a frame link). */
present?: string;
@@ -94,20 +100,41 @@ function FigHost(props: {
const [sharing, setSharing] = createSignal<FigSharing>();
const libraries = useFigLibrarySource(props.documentId);
const [failure, setFailure] = createSignal<string>();
+ // Someone opened a file stored outside the shared design and started over
+ // on it: this copy is out of date.
+ const [replaced, setReplaced] = createSignal(false);
+ const canEdit = () => props.canEdit() && !replaced();
+ const notice = () =>
+ replaced()
+ ? {
+ message:
+ 'This design was replaced by a newer file (an upload or an AI edit). Reload to edit the latest version.',
+ action: 'Reload',
+ onAction: () => window.location.reload(),
+ }
+ : props.notice;
onMount(() => {
let disposed = false;
let opened: FigEngine | undefined;
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),
});
opened = e;
if (disposed) return;
- if (props.shared) {
- shared = await shareFigEngine(e, props.shared);
+ if (props.shared && fingerprint) {
+ shared = await shareFigEngine(e, props.shared, {
+ fingerprint,
+ delivered: props.delivered,
+ });
if (disposed) return;
+ shared.onReplaced(() => setReplaced(true));
setSharing(shared);
}
setEngine(e);
@@ -134,31 +161,36 @@ function FigHost(props: {
</Match>
<Match when={engine()}>
{(e) => (
- <FigViewerProvider
- context={{
- engine: e(),
- fileName: props.fileName,
- download: (blob, name) => void downloadFile(blob, name),
- notifyError: (message) => toast.failure(message),
- notifyInfo: (message) => toast.success(message),
- canEdit: props.canEdit,
- save: (bytes) => saveFigFile(props.documentId, bytes),
- fileKey: props.documentId,
- collaboration: props.collaboration,
- sharing: sharing(),
- comments: props.comments,
- frameLink: (frame) =>
- buildSimpleEntityUrl(
- { type: 'fig', id: props.documentId },
- { present: frame }
- ),
- presentAt: props.present,
- fonts: createFontSource(),
- libraries,
- }}
- >
- <FigViewer />
- </FigViewerProvider>
+ <div class="flex size-full min-h-0 flex-col">
+ <Show when={notice()}>{(n) => <SessionNotice {...n()} />}</Show>
+ <div class="min-h-0 flex-1">
+ <FigViewerProvider
+ context={{
+ engine: e(),
+ fileName: props.fileName,
+ download: (blob, name) => void downloadFile(blob, name),
+ notifyError: (message) => toast.failure(message),
+ notifyInfo: (message) => toast.success(message),
+ canEdit,
+ save: (bytes) => saveFigFile(props.documentId, bytes),
+ fileKey: props.documentId,
+ collaboration: props.collaboration,
+ sharing: sharing(),
+ comments: props.comments,
+ frameLink: (frame) =>
+ buildSimpleEntityUrl(
+ { type: 'fig', id: props.documentId },
+ { present: frame }
+ ),
+ presentAt: props.present,
+ fonts: createFontSource(),
+ libraries,
+ }}
+ >
+ <FigViewer />
+ </FigViewerProvider>
+ </div>
+ </div>
)}
</Match>
</Switch>
@@ -182,6 +214,31 @@ function CollaborativeFigHost(props: {
canEdit: () => boolean;
comments?: FigCommentStore;
present?: string;
+}) {
+ // Retrying starts a new session (and opens the file again). The child's
+ // parameter makes Show call it again for each attempt.
+ const [attempt, setAttempt] = createSignal(0);
+ return (
+ <Show when={attempt() + 1} keyed>
+ {(_attempt) => (
+ <DesignSession {...props} retry={() => setAttempt((n) => n + 1)} />
+ )}
+ </Show>
+ );
+}
+
+/** Why a session that failed leaves the design read-only. */
+const unavailable = (message: string) =>
+ `${message} Live editing is unavailable, so the design is open read-only; editing offline could overwrite other people's changes.`;
+
+function DesignSession(props: {
+ bytes: ArrayBuffer;
+ fileName: () => string;
+ documentId: string;
+ canEdit: () => boolean;
+ comments?: FigCommentStore;
+ present?: string;
+ retry: () => void;
}) {
const userId = useUserId();
const session = createDesignCollabSession({
@@ -197,6 +254,10 @@ function CollaborativeFigHost(props: {
const state = session.state();
return state.t === 'ready' ? state.doc : undefined;
};
+ const failed = () => {
+ const state = session.state();
+ return state.t === 'error' ? state.message : undefined;
+ };
return (
<Switch
fallback={
@@ -205,17 +266,33 @@ function CollaborativeFigHost(props: {
</div>
}
>
- <Match
- when={session.state().t === 'unshared' || session.state().t === 'error'}
- >
+ <Match when={session.state().t === 'unshared'}>
<FigHost {...props} canEdit={() => false} />
</Match>
+ <Match when={failed()}>
+ {(message) => (
+ <FigHost
+ {...props}
+ canEdit={() => false}
+ notice={
+ props.canEdit()
+ ? {
+ message: unavailable(message()),
+ action: 'Retry',
+ onAction: props.retry,
+ }
+ : undefined
+ }
+ />
+ )}
+ </Match>
<Match when={ready()} keyed>
{(doc) => (
<FigHost
{...props}
shared={doc}
collaboration={session.collaboration}
+ delivered={session.delivered}
/>
)}
</Match>
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 7531c4b188..62b0370e67 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
@@ -37,6 +37,7 @@ import type { HandoffOp } from '../core/handoff-ops';
import type { LibraryOp } from '../core/libraries';
import type { PaintType, StopSpec } from '../core/paint';
import type { InteractionSpec } from '../core/prototype';
+import { resizedOrigin } from '../core/rotation';
import type { Measure } from '../core/type';
import { type PenPoint, penNetwork } from '../core/vector';
import type { FigViewer, Selected } from './create-fig-viewer';
@@ -219,8 +220,16 @@ export interface FigEditorOptions {
* editing does). Defaults to always.
*/
stores?: () => boolean;
+ /**
+ * Whether the sync service of a shared design is reachable; storing
+ * waits for it (see `FigSharing.willStore`). Defaults to always.
+ */
+ online?: () => boolean;
}
+/** Undo steps whose selections are remembered (the engine keeps 200). */
+const MAX_REMEMBERED_STEPS = 256;
+
/** Quiet time after the last edit before saving. */
const SAVE_DELAY_MS = 1500;
@@ -289,7 +298,13 @@ export function createFigEditor(options: FigEditorOptions) {
const saveNow = async (): Promise<void> => {
clearTimeout(saveTimer);
saveTimer = undefined;
- if (!options.save || !dirtySinceSave || !stores()) return;
+ if (!options.save || !dirtySinceSave || !stores() || !enabled()) return;
+ if (options.online?.() === false) {
+ // The changes wait in the sync log, and are stored once it is
+ // reachable (see `takeOver`).
+ setSaveState('unsaved');
+ return;
+ }
if (saving) {
await saving;
if (!dirtySinceSave) return;
@@ -300,6 +315,11 @@ export function createFigEditor(options: FigEditorOptions) {
try {
const version = sharing?.appliedVersion();
const bytes = await engine.save();
+ if (sharing && !(await sharing.willStore(bytes))) {
+ dirtySinceSave = true;
+ setSaveState('unsaved');
+ return;
+ }
await options.save?.(bytes);
if (version) sharing?.markStored(version);
setSaveState(dirtySinceSave ? 'unsaved' : 'saved');
@@ -355,9 +375,34 @@ export function createFigEditor(options: FigEditorOptions) {
let queue: Promise<unknown> = Promise.resolve();
+ // What was selected around each undo step, so undo and redo bring the
+ // selection back as Figma does (undoing a duplicate selects the original).
+ const stepSelections = new Map<
+ number,
+ { page: number; before: Selected[]; after?: Selected[] }
+ >();
+ let undoStep: number | null = null;
+ let redoStep: number | null = null;
+
+ /** Selects what was selected, as far as those layers still exist. */
+ const restoreSelection = async (page: number, wanted: Selected[]) => {
+ if (viewer.page() !== page) return;
+ const rows =
+ wanted.length > 0
+ ? await engine.rows(
+ page,
+ wanted.map((s) => s.id)
+ )
+ : [];
+ const alive = new Set(rows.map((r) => r.id));
+ viewer.select(wanted.filter((s) => alive.has(s.id)));
+ };
+
const settle = async (result: EditResult) => {
setCanUndo(result.canUndo);
setCanRedo(result.canRedo);
+ undoStep = result.undoStep;
+ redoStep = result.redoStep;
if (result.dirty) options.onDirty(result.dirty);
scheduleSave();
await viewer.afterEdit();
@@ -419,7 +464,18 @@ export function createFigEditor(options: FigEditorOptions) {
try {
// Other people's changes that arrived first apply first.
await pullShared();
- const result = await engine.apply(viewer.page(), ops, coalesce);
+ const page = viewer.page();
+ const before = viewer.selected();
+ const result = await engine.apply(page, ops, 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 });
+ // The engine keeps 200 steps; forget the oldest beyond that.
+ for (const id of stepSelections.keys()) {
+ if (stepSelections.size <= MAX_REMEMBERED_STEPS) break;
+ stepSelections.delete(id);
+ }
+ }
if (coalesce) pushSoon();
else await pushNow();
await settle(result);
@@ -438,6 +494,10 @@ export function createFigEditor(options: FigEditorOptions) {
queue = queue.then(async () => {
try {
await pullShared();
+ const step = action === 'undo' ? undoStep : redoStep;
+ const remembered = step === null ? undefined : stepSelections.get(step);
+ if (remembered && action === 'undo')
+ remembered.after = viewer.selected();
const result =
action === 'undo'
? await engine.undo(viewer.page())
@@ -445,7 +505,11 @@ export function createFigEditor(options: FigEditorOptions) {
// Undo is local: what it restores is shared as a new change.
await pushNow();
await settle(result);
- await viewer.pruneSelection();
+ const wanted =
+ action === 'undo' ? remembered?.before : remembered?.after;
+ if (remembered && wanted)
+ await restoreSelection(remembered.page, wanted);
+ else await viewer.pruneSelection();
} catch (e) {
options.notifyError(e instanceof Error ? e.message : String(e));
}
@@ -943,12 +1007,18 @@ export function createFigEditor(options: FigEditorOptions) {
const b = info.bounds;
const nx = r.x + (b.x - start.x) * sx;
const ny = r.y + (b.y - start.y) * sy;
+ const origin = resizedOrigin(info, b, {
+ x: nx,
+ y: ny,
+ w: b.w * sx,
+ h: b.h * sy,
+ });
return {
op: 'set' as const,
ids: [info.id],
props: {
- x: round(info.x + (nx - b.x)),
- y: round(info.y + (ny - b.y)),
+ x: round(origin.x),
+ y: round(origin.y),
width: Math.max(1, round(info.width * sx)),
height: Math.max(1, round(info.height * sy)),
},
diff --git a/apps/web/src/features/block-fig/queries/fig-collab.ts b/apps/web/src/features/block-fig/queries/fig-collab.ts
index e79cd34629..749dc89630 100644
--- a/apps/web/src/features/block-fig/queries/fig-collab.ts
+++ b/apps/web/src/features/block-fig/queries/fig-collab.ts
@@ -101,8 +101,30 @@ export interface DesignCollabOptions {
export interface DesignCollabSession {
state: Accessor<DesignCollabState>;
collaboration: FigCollaboration;
+ /**
+ * Resolves once every change made here so far reached the sync service;
+ * `false` when it could not be reached in time.
+ */
+ delivered: () => Promise<boolean>;
}
+/** How long storing a file waits for the sync service to have every change. */
+const DELIVERY_TIMEOUT_MS = 5_000;
+
+/** A write-ahead log that knows when the last local change was logged. */
+class TrackedWALSyncer extends WALSyncer<Uint8Array> {
+ /** Settles once the latest appended change is in the log. */
+ lastAppend: Promise<void> = Promise.resolve();
+
+ override append(update: Uint8Array): Promise<void> {
+ const appended = super.append(update);
+ this.lastAppend = appended.catch(() => {});
+ return appended;
+ }
+}
+
+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
+
/** The first shared snapshot: the format version and nothing changed yet. */
export function buildDesignSeed(): Uint8Array {
const doc = new LoroDoc();
@@ -129,7 +151,7 @@ export function createDesignCollabSession(
let disposed = false;
let started = false;
- const wal = new WALSyncer(
+ const wal = new TrackedWALSyncer(
walStore,
(updates) =>
connection()?.source.pushUpdate(updates) ?? Promise.resolve(false),
@@ -338,8 +360,24 @@ export function createDesignCollabSession(
: []
);
+ async function delivered(): Promise<boolean> {
+ const deadline = Date.now() + DELIVERY_TIMEOUT_MS;
+ // A commit logs its change at once; the log writes it asynchronously.
+ await wal.lastAppend;
+ while (!disposed) {
+ if (connection()?.source.status() === SyncSourceStatus.Connected) {
+ await wal.flush();
+ if ((await wal.summary()).dirty === 0) return true;
+ }
+ if (Date.now() >= deadline) return false;
+ await sleep(200);
+ }
+ return false;
+ }
+
return {
state,
+ delivered,
collaboration: {
peerId: manager.peerIdStr,
color: () => awareness.local().user.color,
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 dbd534ff38..fd08528d20 100644
--- a/apps/web/src/features/block-fig/queries/fig-sharing.ts
+++ b/apps/web/src/features/block-fig/queries/fig-sharing.ts
@@ -10,12 +10,18 @@ import type { EntryChange } from '@core/fig-engine/types';
import type { LoroDoc } from 'loro-crdt';
import type { FigSharing } from '../context/fig-viewer-context';
import {
+ BASE_KEY,
baseBlobs,
changedKeys,
+ designBase,
type EntryKey,
+ entriesApplyTo,
+ fileFingerprint,
LOCAL_EDIT_ORIGIN,
readEntries,
readValues,
+ recordStoredFile,
+ restartOnFile,
writeEntryChanges,
} from '../core/collab-entries';
import { newGuidSession, type Version, versionCovers } from '../core/presence';
@@ -26,15 +32,34 @@ const STORED_ORIGIN = 'fig-stored';
const versionOf = (doc: LoroDoc): Version =>
Object.fromEntries(doc.version().toJSON()) as Version;
+export interface ShareOptions {
+ /** `fileFingerprint` of the stored file the engine opened. */
+ fingerprint: string;
+ /**
+ * Resolves once this person's changes so far reached the sync service,
+ * or `false` when they could not (offline). Without it, they are taken
+ * to have.
+ */
+ delivered?: () => Promise<boolean>;
+}
+
/**
* Starts sharing an open engine through `doc`: new layers get ids in a
* session of this visit, and everything other people changed so far is
- * applied before the design is shown.
+ * applied before the design is shown. When the stored file was replaced
+ * outside the shared design (see `entriesApplyTo`), the design starts over
+ * on it instead.
*/
export async function shareFigEngine(
engine: FigEngine,
- doc: LoroDoc
+ doc: LoroDoc,
+ options: ShareOptions
): Promise<FigSharing> {
+ if (entriesApplyTo(doc, options.fingerprint))
+ recordStoredFile(doc, options.fingerprint);
+ else restartOnFile(doc, options.fingerprint);
+ /** The file the entries this engine holds began on. */
+ const base = designBase(doc);
const meta = await engine.enableCollab(newGuidSession(), baseBlobs(doc));
writeEntryChanges(doc, meta);
@@ -46,6 +71,8 @@ export async function shareFigEngine(
let lastChange: Version = applied;
const incoming = new Set<() => void>();
const storedElsewhere = new Set<() => void>();
+ const replacedListeners = new Set<() => void>();
+ let replaced = false;
let closed = false;
const isEntry = (k: EntryKey) => k.container !== 'figMeta';
@@ -53,6 +80,17 @@ export async function shareFigEngine(
const unsubscribe = doc.subscribe((batch) => {
if (batch.by === 'local' && batch.origin === LOCAL_EDIT_ORIGIN) return;
const keys = changedKeys(doc, batch);
+ if (
+ !replaced &&
+ batch.by !== 'local' &&
+ keys.some((k) => k.container === 'figMeta' && k.key === BASE_KEY) &&
+ designBase(doc) !== base
+ ) {
+ // Someone opened a file stored outside the design and started over
+ // on it: what this engine holds no longer matches anyone's.
+ replaced = true;
+ for (const listener of replacedListeners) listener();
+ }
if (keys.some(isEntry)) lastChange = versionOf(doc);
const stored = keys.some(
(k) => k.container === 'figMeta' && k.key === 'saved'
@@ -98,6 +136,13 @@ export async function shareFigEngine(
return () => incoming.delete(listener);
},
appliedVersion: () => applied,
+ willStore: async (bytes) => {
+ if (closed || replaced) return false;
+ // Listed before it is stored, and known to the sync service, so
+ // whoever opens the stored file finds it is the design's own.
+ recordStoredFile(doc, await fileFingerprint(bytes));
+ return (await options.delivered?.()) ?? true;
+ },
markStored: (version) => {
// The last save can finish after the design closed.
if (closed) return;
@@ -108,11 +153,16 @@ export async function shareFigEngine(
storedElsewhere.add(listener);
return () => storedElsewhere.delete(listener);
},
+ onReplaced: (listener) => {
+ replacedListeners.add(listener);
+ return () => replacedListeners.delete(listener);
+ },
close: () => {
closed = true;
unsubscribe();
incoming.clear();
storedElsewhere.clear();
+ replacedListeners.clear();
},
};
}
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 678d3e5419..3db8c3548f 100644
--- a/apps/web/src/features/block-fig/views/fig-viewer.tsx
+++ b/apps/web/src/features/block-fig/views/fig-viewer.tsx
@@ -94,6 +94,7 @@ export function FigViewer() {
collab.peers()
)
: undefined,
+ online: collab ? () => collab.status() === 'connected' : undefined,
});
const review = createFigReview({
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 202f9aecff..1c9da8a858 100644
--- a/apps/web/src/features/block-fig/views/layers-panel.tsx
+++ b/apps/web/src/features/block-fig/views/layers-panel.tsx
@@ -329,9 +329,15 @@ export function LayersPanel(props: {
);
};
- /** Arrow keys move through the rows shown, and expand or collapse. */
+ /**
+ * Read-only, arrow keys move through the rows shown, and expand or
+ * collapse. Editing, they nudge the selection, as in Figma, whose layers
+ * list leaves the arrows to the canvas (Tab, Enter, and ⇧Enter move
+ * through the layers there).
+ */
const onTreeKey = (e: KeyboardEvent) => {
if (
+ props.editor?.enabled() ||
e.metaKey ||
e.ctrlKey ||
e.altKey ||
@@ -502,7 +508,7 @@ export function LayersPanel(props: {
</Show>
<div
ref={tree}
- // Takes the keys after a row is clicked (arrows move in the tree).
+ // Takes the keys after a row is clicked (see `onTreeKey`).
tabIndex={-1}
aria-label="Layers"
data-testid="fig-layer-tree"
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 94659d8f2a..7629bb9aba 100644
--- a/apps/web/src/features/block-fig/views/viewer-canvas.tsx
+++ b/apps/web/src/features/block-fig/views/viewer-canvas.tsx
@@ -31,7 +31,7 @@ import { type Point, screenToPage } from '../core/camera';
import { type SnapLines, snapResize } from '../core/layout-grid';
import { measure } from '../core/measure';
import type { PeerOverlay } from '../core/presence';
-import { rotationFor } from '../core/rotation';
+import { isAxisAligned, rotationFor } from '../core/rotation';
import { type Guide, snapMove } from '../core/snap';
import {
closesPath,
@@ -524,7 +524,7 @@ export function ViewerCanvas(props: {
const handleAt = (p: Point): Handle | undefined => {
if (!transformable()) return undefined;
const info = props.info?.();
- if (viewer.selected().length === 1 && Math.abs(info?.rotation ?? 0) > 0.01)
+ if (viewer.selected().length === 1 && !isAxisAligned(info?.rotation ?? 0))
return undefined;
const box = screenBox();
if (!box) return undefined;
diff --git a/apps/web/src/lib/core/fig-engine/client.ts b/apps/web/src/lib/core/fig-engine/client.ts
index a5ba81ba5b..a714660fec 100644
--- a/apps/web/src/lib/core/fig-engine/client.ts
+++ b/apps/web/src/lib/core/fig-engine/client.ts
@@ -70,6 +70,12 @@ export interface EditResult {
dirty: Rect | null;
canUndo: boolean;
canRedo: boolean;
+ /**
+ * The steps undo and redo would act on next; a step keeps its id while
+ * it coalesces and across undo and redo.
+ */
+ undoStep: number | null;
+ redoStep: number | null;
/** Layers were added, removed, or moved between parents. */
structure: boolean;
}
diff --git a/crates/fig_engine/README.md b/crates/fig_engine/README.md
index ff3525c102..e9eb63658c 100644
--- a/crates/fig_engine/README.md
+++ b/crates/fig_engine/README.md
@@ -141,6 +141,11 @@ geometry, gradients and image patterns (with embedded PNGs), masks, clips,
shadows and layer blur as filters, and text as outlines. `fig_render svg`
writes SVGs (with matching PNGs) for the first page's top-level layers.
+Pattern paints repeat another layer as a transparent tile, including
+rectangular and horizontal hexagonal layouts, spacing, alignment, and
+opacity. SVG embeds the same rendered tile; PDF rasterizes patterned layers.
+Pattern values and source references survive saving and collaboration.
+
Text the editor changes is laid out again in its own fonts when they are
registered at run time (`FigFile.registerFont`: TTF, OTF, collections, WOFF,
or WOFF2, optionally under a family name), else in Inter (`fonts/`, SIL Open
diff --git a/crates/fig_engine/src/collab.rs b/crates/fig_engine/src/collab.rs
index a38faa9814..fddfb1321e 100644
--- a/crates/fig_engine/src/collab.rs
+++ b/crates/fig_engine/src/collab.rs
@@ -6,6 +6,7 @@
//! | container | key | value |
//! | --- | --- | --- |
//! | `figMeta` | `format`, `baseBlobs` | entry layout version; blobs every peer's file starts with |
+//! | `figMeta` | `base`, `file:<fingerprint>` | the stored files the entries apply to (written by the web app's `core/collab-entries.ts`) |
//! | `figNodes` | node id (`12:34`) | the node's whole state ([`codec::NodeState`], base64) |
//! | `figBlobs` | content key | geometry or glyph blob (base64) |
//! | `figImages` | SHA-1 | image file (base64) |
diff --git a/crates/fig_engine/src/collab/codec.rs b/crates/fig_engine/src/collab/codec.rs
index 374bae1bf2..45f6397aaf 100644
--- a/crates/fig_engine/src/collab/codec.rs
+++ b/crates/fig_engine/src/collab/codec.rs
@@ -21,7 +21,7 @@ pub use read::Reader;
pub use write::Writer;
/// Layout version of a node entry (its first byte).
-pub(super) const ENTRY_VERSION: u8 = 1;
+pub(super) const ENTRY_VERSION: u8 = 2;
/// A node as the shared maps hold it.
#[derive(Clone, Debug, PartialEq)]
diff --git a/crates/fig_engine/src/collab/codec/read.rs b/crates/fig_engine/src/collab/codec/read.rs
index 6a6e9c0e62..392affe6ad 100644
--- a/crates/fig_engine/src/collab/codec/read.rs
+++ b/crates/fig_engine/src/collab/codec/read.rs
@@ -19,6 +19,7 @@ use std::sync::Arc;
pub struct Reader<'a> {
data: &'a [u8],
at: usize,
+ version: u8,
keys: Vec<Arc<str>>,
blob: &'a dyn Fn(&BlobRef) -> Option<u32>,
}
@@ -28,6 +29,7 @@ impl<'a> Reader<'a> {
Self {
data,
at: 0,
+ version: ENTRY_VERSION,
keys: Vec::new(),
blob,
}
@@ -217,6 +219,18 @@ impl<'a> Reader<'a> {
.unwrap_or("paint"),
)
}
+ 4 => PaintKind::Pattern(crate::model::PatternPaint {
+ source: self.guid()?,
+ layout: match self.string()?.as_str() {
+ "RECTANGULAR" => crate::model::PatternLayout::Rectangular,
+ "HORIZONTAL_HEXAGONAL" => crate::model::PatternLayout::HorizontalHexagonal,
+ _ => return Err(DecodeError::Invalid),
+ },
+ scale: self.f32()?,
+ spacing: self.vec2()?,
+ horizontal: crate::model::PatternAlign::parse(&self.string()?),
+ vertical: crate::model::PatternAlign::parse(&self.string()?),
+ }),
_ => return Err(DecodeError::Invalid),
};
Ok(Paint {
@@ -632,12 +646,18 @@ impl<'a> Reader<'a> {
})?,
macro_data: self.opt(|r| r.arc_list(|r| Ok((r.arc_str()?, r.arc_str()?))))?,
recomputed: self.bool()?,
+ arc_data: if self.version >= 2 {
+ self.opt(|r| Ok([r.f32()?, r.f32()?, r.f32()?]))?
+ } else {
+ None
+ },
})
}
/// Reads a whole entry written by [`Writer::node`].
pub fn node(mut self) -> Decoded<NodeState> {
- if self.u8()? != ENTRY_VERSION {
+ self.version = self.u8()?;
+ if !(1..=ENTRY_VERSION).contains(&self.version) {
return Err(DecodeError::Invalid);
}
self.keys = self.list(Self::arc_str)?;
diff --git a/crates/fig_engine/src/collab/codec/write.rs b/crates/fig_engine/src/collab/codec/write.rs
index 759e7561fa..dd8c7beeff 100644
--- a/crates/fig_engine/src/collab/codec/write.rs
+++ b/crates/fig_engine/src/collab/codec/write.rs
@@ -203,6 +203,15 @@ impl<'a> Writer<'a> {
}
self.opt(original_size, |w, s| w.vec2(s));
}
+ PaintKind::Pattern(pattern) => {
+ self.u8(4);
+ self.guid(&pattern.source);
+ self.str(pattern.layout.name());
+ self.f32(pattern.scale);
+ self.vec2(&pattern.spacing);
+ self.str(pattern.horizontal.name());
+ self.str(pattern.vertical.name());
+ }
PaintKind::Unsupported(name) => {
self.u8(3);
self.str(name);
@@ -625,6 +634,7 @@ impl<'a> Writer<'a> {
corner_radius,
corner_radii,
corner_smoothing,
+ arc_data,
clip_disabled,
background_color,
internal_only,
@@ -872,6 +882,11 @@ impl<'a> Writer<'a> {
});
});
self.bool(*recomputed);
+ self.opt(arc_data, |w, values| {
+ for value in values {
+ w.f32(*value);
+ }
+ });
}
/// The finished entry: version, the shared blob keys it uses, and the
diff --git a/crates/fig_engine/src/collab/test.rs b/crates/fig_engine/src/collab/test.rs
index 69b297483d..331ef531e8 100644
--- a/crates/fig_engine/src/collab/test.rs
+++ b/crates/fig_engine/src/collab/test.rs
@@ -319,6 +319,7 @@ fn entries_round_trip_every_property() {
}),
}));
props.macro_data = Some(Arc::from([(Arc::from("libraries"), Arc::from("[]"))]));
+ props.arc_data = Some([0.25, 4.5, 0.75]);
let state = NodeState {
props,
removed: node.removed,
@@ -465,6 +466,18 @@ fn set_design_system_fields(props: &mut crate::model::Props) {
name: "Light".into(),
}]));
props.mode_by_set = Some(Arc::from([(g(20), g(21))]));
+ let mut pattern = crate::model::Paint::solid(Color::BLACK);
+ pattern.kind = crate::model::PaintKind::Pattern(crate::model::PatternPaint {
+ layout: crate::model::PatternLayout::HorizontalHexagonal,
+ source: g(28),
+ scale: 1.5,
+ spacing: crate::model::Vec2::new(-0.2, 3.0),
+ horizontal: crate::model::PatternAlign::Center,
+ vertical: crate::model::PatternAlign::End,
+ });
+ let mut fills = props.fills().to_vec();
+ fills.push(pattern);
+ props.fills = Some(fills.into());
if let Some(fills) = &props.fills {
let mut list = fills.to_vec();
for p in &mut list {
@@ -994,3 +1007,23 @@ fn prototype_edits_reach_other_people_and_their_saves() {
let c = Peer::open(3, &saved, &mut hub);
assert_same(&a.doc, &c.doc);
}
+
+#[test]
+fn reads_entries_before_arc_metadata_was_added() {
+ use codec::{BlobRef, NodeState, Reader, Writer};
+ let state = NodeState {
+ props: crate::model::Props::default(),
+ removed: false,
+ listed: true,
+ edits: 0,
+ source: None,
+ };
+ let mut blobs = |index| BlobRef::Base(index);
+ let mut bytes = Writer::new(&mut blobs).node(&state);
+ // Version 1 ended Props after `recomputed`; version 2 appends arc_data.
+ // The four final bytes are NodeState's booleans, zero edits, and no source.
+ assert_eq!(bytes.remove(bytes.len() - 5), 0);
+ bytes[0] = 1;
+ let resolve = |_: &BlobRef| None;
+ assert_eq!(Reader::new(&bytes, &resolve).node().unwrap(), state);
+}
diff --git a/crates/fig_engine/src/decode.rs b/crates/fig_engine/src/decode.rs
index 4e3c21feaf..03f3d5b929 100644
--- a/crates/fig_engine/src/decode.rs
+++ b/crates/fig_engine/src/decode.rs
@@ -9,12 +9,14 @@ use crate::model::text::{StyleRun, TextContent};
use crate::model::*;
use std::sync::Arc;
+pub(crate) mod assets;
mod handoff;
mod prototype;
/// The `NodeChange` fields the engine reads. Everything else is skipped while
/// decoding, which keeps memory proportional to what is drawn.
const NODE_FIELDS: &[&str] = &[
+ "arcData",
"guid",
"phase",
"parentIndex",
@@ -47,6 +49,7 @@ const NODE_FIELDS: &[&str] = &[
"rectangleCornerRadiiIndependent",
"cornerSmoothing",
"frameMaskDisabled",
+ "resizeToFit",
"backgroundColor",
"internalOnly",
"textData",
@@ -157,6 +160,12 @@ const PAINT_FIELDS: &[&str] = &[
"originalImageWidth",
"originalImageHeight",
"colorVar",
+ "sourceNodeId",
+ "patternSpacing",
+ "spacing",
+ "patternTileType",
+ "horizontalAlignment",
+ "verticalAlignment",
];
const EFFECT_FIELDS: &[&str] = &[
@@ -329,6 +338,10 @@ fn hex(bytes: &[u8]) -> String {
}
pub fn paint(m: MsgRef) -> Paint {
+ paint_with_assets(m, &assets::AssetIds::default())
+}
+
+fn paint_with_assets(m: MsgRef, assets: &assets::AssetIds) -> Paint {
let kind_name = m.enum_name("type").unwrap_or("SOLID");
let gradient = |kind| PaintKind::Gradient {
kind,
@@ -386,6 +399,34 @@ pub fn paint(m: MsgRef) -> Paint {
}
"EMOJI" => PaintKind::Unsupported("emoji"),
"VIDEO" => PaintKind::Unsupported("video"),
+ "PATTERN"
+ if m.enum_name("patternTileType")
+ .is_none_or(|t| matches!(t, "RECTANGULAR" | "HORIZONTAL_HEXAGONAL"))
+ && (m.has("patternSpacing") || m.f32("spacing").is_none_or(|s| s == 0.0)) =>
+ {
+ match m.msg("sourceNodeId").and_then(guid) {
+ Some(source) => PaintKind::Pattern(PatternPaint {
+ layout: if m.enum_name("patternTileType") == Some("HORIZONTAL_HEXAGONAL") {
+ PatternLayout::HorizontalHexagonal
+ } else {
+ PatternLayout::Rectangular
+ },
+ source,
+ scale: m.f32("scale").unwrap_or(1.0),
+ spacing: m.msg("patternSpacing").map(vec2).unwrap_or_else(|| {
+ let spacing = f64::from(m.f32("spacing").unwrap_or(0.0));
+ Vec2::new(spacing, spacing)
+ }),
+ horizontal: PatternAlign::parse(
+ m.enum_name("horizontalAlignment").unwrap_or("START"),
+ ),
+ vertical: PatternAlign::parse(
+ m.enum_name("verticalAlignment").unwrap_or("START"),
+ ),
+ }),
+ None => PaintKind::Unsupported("pattern"),
+ }
+ }
"PATTERN" => PaintKind::Unsupported("pattern"),
"NOISE" => PaintKind::Unsupported("noise"),
_ => PaintKind::Unsupported("paint"),
@@ -398,22 +439,19 @@ pub fn paint(m: MsgRef) -> Paint {
.enum_name("blendMode")
.map(BlendMode::parse)
.unwrap_or(BlendMode::Normal),
- color_var: m.msg("colorVar").and_then(variable_alias),
+ color_var: m.msg("colorVar").and_then(|v| variable_alias(v, assets)),
}
}
/// The variable a `VariableData` aliases.
-fn variable_alias(v: MsgRef) -> Option<Guid> {
- v.msg("value")?.msg("alias")?.msg("guid").and_then(guid)
+fn variable_alias(v: MsgRef, assets: &assets::AssetIds) -> Option<Guid> {
+ assets.resolve(v.msg("value")?.msg("alias")?)
}
-fn variable(m: &MsgRef) -> Option<Variable> {
+fn variable(m: &MsgRef, assets: &assets::AssetIds) -> Option<Variable> {
let values = m.msg("variableDataValues")?;
Some(Variable {
- set: m
- .msg("variableSetID")
- .and_then(|s| s.msg("guid"))
- .and_then(guid),
+ set: m.msg("variableSetID").and_then(|s| assets.resolve(s)),
resolved_type: m
.enum_name("variableResolvedType")
.map(VariableType::parse)
@@ -426,8 +464,7 @@ fn variable(m: &MsgRef) -> Option<Variable> {
let value = match data.msg("value") {
Some(v) if data.enum_name("dataType") == Some("ALIAS") => v
.msg("alias")
- .and_then(|a| a.msg("guid"))
- .and_then(guid)
+ .and_then(|a| assets.resolve(a))
.map_or(VariableValue::Other, VariableValue::Alias),
Some(v) => {
if let Some(c) = v.msg("colorValue") {
@@ -490,7 +527,7 @@ fn path_refs<'a>(items: impl Iterator<Item = MsgRef<'a>>) -> Arc<[PathRef]> {
.collect()
}
-fn text_content(m: MsgRef) -> TextContent {
+fn text_content(m: MsgRef, assets: &assets::AssetIds) -> TextContent {
let styles = m
.msgs("styleOverrideTable")
.filter_map(|s| {
@@ -500,7 +537,7 @@ fn text_content(m: MsgRef) -> TextContent {
id,
fills: s
.has("fillPaints")
- .then(|| s.collect_msgs("fillPaints", paint)),
+ .then(|| s.collect_msgs("fillPaints", |m| paint_with_assets(m, assets))),
font_family: font.and_then(|f| f.str("family")).map(Into::into),
font_style: font.and_then(|f| f.str("style")).map(Into::into),
font_size: s.f32("fontSize"),
@@ -694,8 +731,22 @@ pub const SKELETON_FIELDS: &[&str] = &[
"phase",
"internalOnly",
"overrideKey",
+ "resizeToFit",
];
+fn node_type(m: &MsgRef) -> Option<NodeType> {
+ let kind = NodeType::parse(m.enum_name("type").or_else(|| m.str("type"))?);
+ // Figma stores groups as frames that resize to fit their children. Their
+ // saved frameMaskDisabled value does not make them clipping frames.
+ Some(
+ if kind == NodeType::Frame && m.bool("resizeToFit") == Some(true) {
+ NodeType::Group
+ } else {
+ kind
+ },
+ )
+}
+
/// The [`SKELETON_FIELDS`] of a node change, read as [`props`] reads them.
pub fn skeleton(m: MsgRef) -> Props {
let mut p = Props {
@@ -709,10 +760,7 @@ pub fn skeleton(m: MsgRef) -> Props {
.map(Into::into)
.or_else(|| parent.u32("position").map(|n| format!("{n:010}").into()));
}
- p.node_type = m
- .enum_name("type")
- .or_else(|| m.str("type"))
- .map(NodeType::parse);
+ p.node_type = node_type(&m);
p.internal_only = m.bool("internalOnly");
p.override_key = m.msg("overrideKey").and_then(guid);
p
@@ -720,6 +768,10 @@ pub fn skeleton(m: MsgRef) -> Props {
/// Reads one `NodeChange` (a node, an override, or derived layout).
pub fn props(m: MsgRef) -> Props {
+ props_with_assets(m, &assets::AssetIds::default())
+}
+
+pub(crate) fn props_with_assets(m: MsgRef, assets: &assets::AssetIds) -> Props {
let mut p = Props {
guid: m.msg("guid").and_then(guid),
..Props::default()
@@ -731,10 +783,7 @@ pub fn props(m: MsgRef) -> Props {
.map(Into::into)
.or_else(|| parent.u32("position").map(|n| format!("{n:010}").into()));
}
- p.node_type = m
- .enum_name("type")
- .or_else(|| m.str("type"))
- .map(NodeType::parse);
+ p.node_type = node_type(&m);
p.name = m
.shared("name", || m.str("name").map(Arc::<str>::from))
.flatten();
@@ -758,15 +807,19 @@ pub fn props(m: MsgRef) -> Props {
}),
};
if m.has("fillPaints") {
- p.fills = m.shared("fillPaints", || m.collect_msgs("fillPaints", paint));
+ p.fills = m.shared("fillPaints", || {
+ m.collect_msgs("fillPaints", |m| paint_with_assets(m, assets))
+ });
} else if m.has("backgroundPaints") && m.bool("backgroundEnabled") != Some(false) {
// Frames in older files keep their fill as a background.
p.fills = m.shared("backgroundPaints", || {
- m.collect_msgs("backgroundPaints", paint)
+ m.collect_msgs("backgroundPaints", |m| paint_with_assets(m, assets))
});
}
if m.has("strokePaints") {
- p.strokes = m.shared("strokePaints", || m.collect_msgs("strokePaints", paint));
+ p.strokes = m.shared("strokePaints", || {
+ m.collect_msgs("strokePaints", |m| paint_with_assets(m, assets))
+ });
}
p.stroke_weight = m.f32("strokeWeight");
if m.bool("borderStrokeWeightsIndependent") == Some(true) {
@@ -796,6 +849,13 @@ pub fn props(m: MsgRef) -> Props {
p.effects = m.shared("effects", || m.collect_msgs("effects", effect));
}
p.corner_radius = m.f32("cornerRadius");
+ p.arc_data = m.msg("arcData").map(|arc| {
+ [
+ arc.f32("startingAngle").unwrap_or(0.0),
+ arc.f32("endingAngle").unwrap_or(std::f32::consts::TAU),
+ arc.f32("innerRadius").unwrap_or(0.0),
+ ]
+ });
if m.bool("rectangleCornerRadiiIndependent") == Some(true)
|| m.has("rectangleTopLeftCornerRadius")
{
@@ -820,7 +880,7 @@ pub fn props(m: MsgRef) -> Props {
.shared("textData", || {
let text = m.msg("textData")?;
Some((
- Arc::new(text_content(text)),
+ Arc::new(text_content(text, assets)),
text_layout(text).map(Arc::new),
))
})
@@ -847,13 +907,13 @@ pub fn props(m: MsgRef) -> Props {
let symbol = m.msg("symbolData")?;
Some(Arc::new(SymbolData {
symbol_id: symbol.msg("symbolID").and_then(guid),
- overrides: symbol.collect_msgs("symbolOverrides", props),
+ overrides: symbol.collect_msgs("symbolOverrides", |m| props_with_assets(m, assets)),
uniform_scale: symbol.f32("uniformScaleFactor"),
}))
})
.flatten();
p.derived = m.shared("derivedSymbolData", || {
- m.collect_msgs("derivedSymbolData", props)
+ m.collect_msgs("derivedSymbolData", |m| props_with_assets(m, assets))
});
p.swapped_symbol = m.msg("overriddenSymbolID").and_then(guid);
if m.has("componentPropAssignments") {
@@ -929,8 +989,7 @@ pub fn props(m: MsgRef) -> Props {
p.is_state_group = m.bool("isStateGroup");
let style = |new: &'static str, legacy: &'static str| {
m.msg(new)
- .and_then(|s| s.msg("guid"))
- .and_then(guid)
+ .and_then(|s| assets.resolve(s))
.or_else(|| m.msg(legacy).and_then(guid))
.filter(|g| *g != Guid::default() && g.session != u32::MAX)
};
@@ -977,7 +1036,7 @@ pub fn props(m: MsgRef) -> Props {
);
}
p.props_bubbled = m.bool("propsAreBubbled");
- p.variable = variable(&m).map(Arc::new);
+ p.variable = variable(&m, assets).map(Arc::new);
if m.has("variableSetModes") {
p.variable_modes = Some(
m.msgs("variableSetModes")
@@ -995,7 +1054,7 @@ pub fn props(m: MsgRef) -> Props {
.msgs("entries")
.filter_map(|e| {
Some((
- e.msg("variableSetID")?.msg("guid").and_then(guid)?,
+ assets.resolve(e.msg("variableSetID")?)?,
e.msg("variableModeID").and_then(guid)?,
))
})
@@ -1004,7 +1063,7 @@ pub fn props(m: MsgRef) -> Props {
p.mode_by_set = Some(entries);
}
}
- p.generated = generated_layers(&m);
+ p.generated = generated_layers(&m, assets);
p.vector_styles = m.msg("vectorData").and_then(|v| {
let styles: Arc<[StyleRun]> = v
.msgs("styleOverrideTable")
@@ -1012,7 +1071,7 @@ pub fn props(m: MsgRef) -> Props {
.filter_map(|s| {
Some(StyleRun {
id: s.u32("styleID")?,
- fills: Some(s.collect_msgs("fillPaints", paint)),
+ fills: Some(s.collect_msgs("fillPaints", |m| paint_with_assets(m, assets))),
..StyleRun::default()
})
})
@@ -1056,15 +1115,19 @@ fn macro_data(m: &MsgRef) -> Option<library::MacroData> {
/// guid path. Layers with text are text layers, drawn above the others
/// (shapes drawn from their geometry: a connector's label background goes
/// under its label).
-fn generated_layers(m: &MsgRef) -> Option<Arc<[Props]>> {
+fn generated_layers(m: &MsgRef, assets: &assets::AssetIds) -> Option<Arc<[Props]>> {
let layout = m.msg("derivedImmutableFrameData")?;
let generation: Vec<Props> = m
.msg("nodeGenerationData")
- .map(|g| g.msgs("overrides").map(props).collect())
+ .map(|g| {
+ g.msgs("overrides")
+ .map(|m| props_with_assets(m, assets))
+ .collect()
+ })
.unwrap_or_default();
let mut layers: Vec<Props> = layout
.msgs("overrides")
- .map(props)
+ .map(|m| props_with_assets(m, assets))
.filter_map(|derived| {
let path = derived.guid_path.clone().filter(|p| !p.is_empty())?;
let mut layer = generation
diff --git a/crates/fig_engine/src/decode/assets.rs b/crates/fig_engine/src/decode/assets.rs
new file mode 100644
index 0000000000..bb0daf2fb1
--- /dev/null
+++ b/crates/fig_engine/src/decode/assets.rs
@@ -0,0 +1,63 @@
+//! Resolves library variable references to the copies embedded in this file.
+
+use crate::error::{Result, corrupt};
+use crate::kiwi::{Decoder, Flat, MsgRef, Reader, Schema, Ty};
+use crate::model::Guid;
+use std::collections::HashMap;
+
+#[cfg(test)]
+mod test;
+
+#[derive(Default)]
+pub(crate) struct AssetIds(HashMap<String, Guid>);
+
+impl AssetIds {
+ /// Read only identity and library keys, before decoding any references.
+ /// This also works when a referenced asset occurs after its consumer.
+ pub(crate) fn read(schema_bytes: &[u8], data: &[u8]) -> Result<Self> {
+ let mut schema = Schema::decode(schema_bytes)?;
+ schema.keep_only("NodeChange", &["guid", "key", "phase"]);
+ let root = schema
+ .def_index("Message")
+ .ok_or_else(|| corrupt("the schema has no Message type"))?;
+ let decoder = Decoder::new(&schema);
+ let mut reader = Reader::new(data);
+ let mut flat = Flat::new(data);
+ let mut ids = Self::default();
+ loop {
+ let id = reader.var_uint()?;
+ if id == 0 {
+ break;
+ }
+ let field = schema
+ .def(root)
+ .field_by_id(id)
+ .ok_or_else(|| corrupt(format!("kiwi: Message has no field {id}")))?;
+ if let ("nodeChanges", Ty::Def(def), true) =
+ (field.name.as_str(), field.ty, field.array)
+ {
+ for _ in 0..reader.var_uint()? {
+ flat.clear();
+ let slot = flat.decode(&schema, &mut reader, def)?;
+ let m = MsgRef::flat(&schema, &flat, slot);
+ if !super::is_removed(&m)
+ && let Some(key) = m.str("key")
+ && let Some(guid) = m.msg("guid").and_then(super::guid)
+ {
+ ids.0.insert(key.to_owned(), guid);
+ }
+ }
+ } else {
+ decoder.skip_field(&mut reader, field, 0)?;
+ }
+ }
+ Ok(ids)
+ }
+
+ pub(crate) fn resolve(&self, reference: MsgRef) -> Option<Guid> {
+ reference.msg("guid").and_then(super::guid).or_else(|| {
+ let key = reference.msg("assetRef")?.str("key")?;
+ self.0.get(key).copied()
+ })
+ }
+}
diff --git a/crates/fig_engine/src/decode/assets/test.rs b/crates/fig_engine/src/decode/assets/test.rs
new file mode 100644
index 0000000000..e1897a4b1f
--- /dev/null
+++ b/crates/fig_engine/src/decode/assets/test.rs
@@ -0,0 +1,108 @@
+use crate::images::ImageStore;
+use crate::model::{EffectKind, Guid};
+use crate::render::{RenderOptions, Viewport, render};
+use crate::testing::{SCHEMA, V, color, fig_file_with, node, size, solid, translate};
+use crate::{Document, Scene};
+use std::sync::Arc;
+
+#[test]
+fn imported_effect_style_draws_its_glow_in_eager_and_lazy_documents() {
+ let schema = SCHEMA.replace(
+ "message NodeChange guid:GUID",
+ "message AssetRef key:string\nmessage StyleId guid:GUID assetRef:AssetRef\nmessage NodeChange key:string styleIdForEffect:StyleId guid:GUID",
+ );
+ let bytes = Arc::new(fig_file_with(
+ &schema,
+ vec![
+ node(0, None, "DOCUMENT", "Document", vec![]),
+ node(
+ 1,
+ Some((0, "!")),
+ "CANVAS",
+ "Page",
+ vec![("backgroundColor", color(0.0, 0.0, 0.0, 1.0))],
+ ),
+ node(
+ 2,
+ Some((1, "!")),
+ "RECTANGLE",
+ "Button",
+ vec![
+ ("size", size(40.0, 20.0)),
+ ("transform", translate(30.0, 30.0)),
+ ("fillPaints", V::List(vec![solid(0.0, 1.0, 0.0)])),
+ (
+ "styleIdForEffect",
+ V::Msg(vec![(
+ "assetRef",
+ V::Msg(vec![("key", V::Str("library-glow".into()))]),
+ )]),
+ ),
+ ],
+ ),
+ // The imported style occurs after the layer that references it.
+ node(
+ 3,
+ Some((0, "~")),
+ "RECTANGLE",
+ "Glow",
+ vec![
+ ("key", V::Str("library-glow".into())),
+ ("visible", V::Bool(false)),
+ (
+ "effects",
+ V::List(vec![V::Msg(vec![
+ ("type", V::Enum("DROP_SHADOW")),
+ ("color", color(0.0, 1.0, 0.0, 1.0)),
+ ("radius", V::Float(12.0)),
+ ])]),
+ ),
+ ],
+ ),
+ ],
+ vec![],
+ ));
+ for doc in [
+ Document::open(&bytes).unwrap(),
+ Document::open_lazy(&bytes).unwrap(),
+ ] {
+ let button = doc
+ .find(Guid {
+ session: 1,
+ local: 2,
+ })
+ .unwrap();
+ let props = doc.props(button);
+ assert_eq!(
+ props.effect_style,
+ Some(Guid {
+ session: 1,
+ local: 3
+ })
+ );
+ assert_eq!(props.effects().len(), 1);
+ assert_eq!(props.effects()[0].kind, EffectKind::DropShadow);
+ let scene = Scene::build(&doc, doc.pages[0]);
+ let pixmap = render(
+ &doc,
+ &scene,
+ &mut ImageStore::default(),
+ &Viewport {
+ x: 0.0,
+ y: 0.0,
+ scale: 1.0,
+ width: 100,
+ height: 80,
+ },
+ RenderOptions {
+ outline: false,
+ background: Some(doc.page_background(doc.pages[0])),
+ },
+ )
+ .unwrap();
+ let glow = pixmap.pixel(25, 40).unwrap().demultiply();
+ assert!(glow.green() > 20, "the style draws outside the button");
+ assert_eq!(glow.red(), 0);
+ assert_eq!(glow.blue(), 0);
+ }
+}
diff --git a/crates/fig_engine/src/document.rs b/crates/fig_engine/src/document.rs
index db390bf1b7..9a1842ad8f 100644
--- a/crates/fig_engine/src/document.rs
+++ b/crates/fig_engine/src/document.rs
@@ -131,6 +131,13 @@ impl Document {
pub fn open_lazy(bytes: &Arc<Vec<u8>>) -> Result<Document> {
let container = Container::open_shared(bytes)?;
let mut doc = Self::decode_container(container, true)?;
+ // The page picker needs every page's name and canvas color even
+ // before its layers are decoded. These seeds do not expand children.
+ doc.decode_closure(
+ std::iter::once(doc.root)
+ .chain(doc.pages.iter().copied())
+ .collect(),
+ )?;
if let Some(&first) = doc.pages.first() {
doc.decode_page(first)?;
}
@@ -148,12 +155,19 @@ impl Document {
} else {
None
};
+ let assets = decode::assets::AssetIds::read(&container.schema, &container.message)?;
let mut table = NodeTable::default();
let MessageParts {
blobs: ranges,
images: embedded,
node_def,
- } = read_message(&schema, skeleton.as_ref(), &container.message, &mut table)?;
+ } = read_message(
+ &schema,
+ skeleton.as_ref(),
+ &container.message,
+ &mut table,
+ &assets,
+ )?;
let NodeTable {
mut nodes,
by_guid,
@@ -261,6 +275,7 @@ impl Document {
remaining,
cursor: 0,
shared: FlatShared::default(),
+ assets,
}))
}
_ => {
@@ -379,6 +394,7 @@ impl Document {
expanded,
remaining,
shared,
+ assets,
..
} = pending;
let mut flat = Flat::with_shared(message, std::mem::take(shared));
@@ -414,7 +430,7 @@ impl Document {
};
let m = MsgRef::flat(schema, &flat, slot);
decode::embedded_images(&m, &mut embedded);
- let p = decode::props(m);
+ let p = decode::props_with_assets(m, assets);
match &mut props {
Some(first) => first.merge(&p),
None => props = Some(p),
@@ -631,6 +647,7 @@ struct Pending {
cursor: usize,
/// What decoded node changes share ([`MsgRef::shared`]).
shared: FlatShared,
+ assets: decode::assets::AssetIds,
}
/// The nodes `p` draws from besides its subtree: the components its
@@ -638,6 +655,60 @@ struct Pending {
/// `seen` skips lists shared by many nodes after the first.
fn references(p: &Props, out: &mut Vec<Guid>, seen: &mut HashSet<usize>) {
out.extend(p.swapped_symbol);
+ for paint in p
+ .fills()
+ .iter()
+ .chain(p.strokes())
+ .chain(
+ p.text_content
+ .iter()
+ .flat_map(|t| t.styles.iter())
+ .flat_map(|s| s.fills.iter().flat_map(|p| p.iter())),
+ )
+ .chain(
+ p.vector_styles
+ .iter()
+ .flat_map(|s| s.iter())
+ .flat_map(|s| s.fills.iter().flat_map(|p| p.iter())),
+ )
+ {
+ if let crate::model::PaintKind::Pattern(pattern) = &paint.kind {
+ out.push(pattern.source);
+ }
+ }
+ out.extend(
+ p.fills()
+ .iter()
+ .chain(p.strokes())
+ .filter_map(|p| p.color_var),
+ );
+ for style in p
+ .text_content
+ .iter()
+ .flat_map(|t| t.styles.iter())
+ .chain(p.vector_styles.iter().flat_map(|s| s.iter()))
+ {
+ out.extend(
+ style
+ .fills
+ .iter()
+ .flat_map(|f| f.iter())
+ .filter_map(|p| p.color_var),
+ );
+ }
+ if let Some(variable) = &p.variable {
+ out.extend(variable.set);
+ out.extend(variable.values.iter().filter_map(|(_, value)| match value {
+ crate::model::VariableValue::Alias(id) => Some(*id),
+ _ => None,
+ }));
+ }
+ out.extend(
+ p.mode_by_set
+ .iter()
+ .flat_map(|m| m.iter())
+ .map(|(set, _)| *set),
+ );
out.extend(
[
p.fill_style,
@@ -747,6 +818,7 @@ fn read_message(
skeleton: Option<&Schema>,
data: &[u8],
table: &mut NodeTable,
+ assets: &decode::assets::AssetIds,
) -> Result<MessageParts> {
let root = schema
.def_index("Message")
@@ -786,7 +858,7 @@ fn read_message(
table.add(decode::skeleton(m), Some(start));
} else {
decode::embedded_images(&m, &mut images);
- table.add(decode::props(m), None);
+ table.add(decode::props_with_assets(m, assets), None);
}
}
}
diff --git a/crates/fig_engine/src/document/test.rs b/crates/fig_engine/src/document/test.rs
index 36e7ea0b9a..e465e872d8 100644
--- a/crates/fig_engine/src/document/test.rs
+++ b/crates/fig_engine/src/document/test.rs
@@ -244,6 +244,32 @@ fn opens_lazily_with_what_the_first_page_shows() {
assert_eq!(snapshot(&lazy), snapshot(&full));
}
+#[test]
+fn lazy_open_keeps_unvisited_page_metadata() {
+ 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![("backgroundColor", crate::testing::color(0.1, 0.2, 0.3, 1.0))],
+ ),
+ node(3, Some((2, "a")), "RECTANGLE", "Deferred", vec![]),
+ ],
+ vec![],
+ ));
+ let lazy = Document::open_lazy(&bytes).unwrap();
+ let page = lazy.pages[1];
+ assert_eq!(lazy.props(page).name(), "Screens");
+ assert_eq!(lazy.page_background(page).hex(), "1A334D");
+ assert!(lazy.is_decoded(lazy.root));
+ assert!(lazy.is_decoded(page));
+ assert!(!lazy.is_decoded(lazy.node(page).children[0]));
+}
+
#[test]
fn completes_a_lazy_open_as_a_full_one() {
for bytes in [
diff --git a/crates/fig_engine/src/edit.rs b/crates/fig_engine/src/edit.rs
index 3f0de16fad..f4e77bc41f 100644
--- a/crates/fig_engine/src/edit.rs
+++ b/crates/fig_engine/src/edit.rs
@@ -667,6 +667,9 @@ pub struct Applied {
}
struct Step {
+ /// Identifies the step while it is on either stack (see
+ /// [`History::undo_step`]).
+ id: u64,
before: Vec<(NodeIdx, Node)>,
after: Vec<(NodeIdx, Node)>,
coalesce: Option<String>,
@@ -677,6 +680,7 @@ struct Step {
pub struct History {
undo: Vec<Step>,
redo: Vec<Step>,
+ next_id: u64,
}
const MAX_UNDO: usize = 200;
@@ -877,7 +881,8 @@ impl<'a> Txn<'a> {
}
fn set_position(&mut self, i: NodeIdx, x: Option<f64>, y: Option<f64>) {
- let origin = self.doc.world(i).apply(Vec2::default());
+ // The point the panel shows (flip-aware, as `inspect::node_info`).
+ let origin = self.doc.world(i).panel_origin(self.doc.props(i).size());
let space = self
.coordinate_parent(i)
.map(|p| self.doc.world(p))
@@ -887,14 +892,28 @@ impl<'a> Txn<'a> {
self.translate(i, target.x - origin.x, target.y - origin.y);
}
+ /// Turns `i` about its center to `degrees` on the page, as the panel
+ /// shows it (`Affine::panel_rotation_degrees`): a flipped layer stays
+ /// flipped, and a layer in a rotated group reads its page angle.
fn set_rotation(&mut self, i: NodeIdx, degrees: f64) {
let props = self.doc.props(i);
let size = props.size();
let t = props.transform();
let center = t.apply(Vec2::new(size.x / 2.0, size.y / 2.0));
+ let parent = self
+ .doc
+ .node(i)
+ .parent
+ .map(|p| self.doc.world(p))
+ .unwrap_or_default();
// Figma's rotation is counter-clockwise in a y-down space.
- let r = Affine::rotate(-degrees.to_radians());
- let mut next = r;
+ let mut world = Affine::rotate(-degrees.to_radians());
+ if parent.mul(&t).is_mirrored() {
+ world = world.mul(&Affine::MIRROR_X);
+ }
+ let mut next = parent.invert().unwrap_or_default().mul(&world);
+ next.m02 = 0.0;
+ next.m12 = 0.0;
let c = next.apply(Vec2::new(size.x / 2.0, size.y / 2.0));
next.m02 = center.x - c.x;
next.m12 = center.y - c.y;
@@ -1605,8 +1624,12 @@ impl<'a> Txn<'a> {
.into_iter()
.filter(|&i| self.doc.node(i).parent == parent)
.collect();
- if let Some(g) = self.group(&same, *frame)? {
- let _ = g;
+ if let Some(g) = self.group(&same, *frame)?
+ && *frame
+ {
+ // As in Figma, a frame around a selection does not clip
+ // it (shadows and overhangs stay visible).
+ self.edit(g, flags::CLIP).clip_disabled = Some(true);
}
}
Op::Ungroup { ids } => {
@@ -1725,6 +1748,18 @@ impl History {
!self.redo.is_empty()
}
+ /// The step undo would take back next. Steps keep their id while
+ /// coalescing and across undo and redo, so the editor can remember
+ /// what was selected around each one.
+ pub fn undo_step(&self) -> Option<u64> {
+ self.undo.last().map(|s| s.id)
+ }
+
+ /// The step redo would apply next.
+ pub fn redo_step(&self) -> Option<u64> {
+ self.redo.last().map(|s| s.id)
+ }
+
/// Applies `ops` as one undoable step. Consecutive steps with the same
/// `coalesce` key (a drag, say) undo as one. On error nothing changes.
pub fn apply(
@@ -1814,7 +1849,9 @@ impl History {
}
last.after = after_map.into_iter().collect();
} else {
+ self.next_id += 1;
self.undo.push(Step {
+ id: self.next_id,
before,
after,
coalesce: coalesce.map(str::to_owned),
diff --git a/crates/fig_engine/src/edit/design/variables.rs b/crates/fig_engine/src/edit/design/variables.rs
index ed43f3243f..2dccf9b8ea 100644
--- a/crates/fig_engine/src/edit/design/variables.rs
+++ b/crates/fig_engine/src/edit/design/variables.rs
@@ -17,47 +17,7 @@ use std::sync::Arc;
/// An instance layer's new fills and strokes, by guid path.
type Recolored = (Vec<Guid>, Option<Arc<[Paint]>>, Option<Arc<[Paint]>>);
-/// Aliases followed at most this deep (guards against cycles).
-const MAX_ALIAS_DEPTH: usize = 16;
-
-/// The value of variable `var` where `modes` (nearest first: each a
-/// layer's `(collection, mode)` choices) apply; a collection no layer
-/// picks a mode for uses its first mode.
-pub(super) fn resolve(
- doc: &Document,
- var: Guid,
- modes: &[&[(Guid, Guid)]],
-) -> Option<VariableValue> {
- let mut var = var;
- for _ in 0..MAX_ALIAS_DEPTH {
- let v = doc.props(doc.find(var)?).variable.clone()?;
- let set = v.set;
- let mode = set
- .and_then(|s| {
- modes
- .iter()
- .find_map(|m| m.iter().find(|(c, _)| *c == s).map(|(_, mode)| *mode))
- })
- .or_else(|| {
- let first = doc
- .props(doc.find(set?)?)
- .variable_modes
- .as_ref()?
- .first()?
- .id;
- Some(first)
- });
- let value = mode
- .and_then(|m| v.values.iter().find(|(id, _)| *id == m))
- .or_else(|| v.values.first())
- .map(|(_, value)| value.clone())?;
- match value {
- VariableValue::Alias(next) => var = next,
- other => return Some(other),
- }
- }
- None
-}
+pub(super) use crate::variables::resolve;
/// The modes that apply to document node `i`: its own and its ancestors'.
fn doc_modes(doc: &Document, mut i: NodeIdx) -> Vec<Arc<[(Guid, Guid)]>> {
diff --git a/crates/fig_engine/src/edit/flip/test.rs b/crates/fig_engine/src/edit/flip/test.rs
index b3213ba7e8..f214b3f554 100644
--- a/crates/fig_engine/src/edit/flip/test.rs
+++ b/crates/fig_engine/src/edit/flip/test.rs
@@ -52,3 +52,72 @@ fn flipping_twice_restores_the_layer() {
}
assert_eq!(doc.props(i).transform(), start);
}
+
+/// The panel's rotation, X, and Y of `id`.
+fn panel(doc: &Document, id: &str) -> (f64, f64, f64) {
+ let scene = crate::scene::Scene::build(doc, doc.pages[0]);
+ let info = crate::inspect::node_info(doc, &scene, scene.find(doc, id).unwrap());
+ let round = |v: f64| (v * 1000.0).round() / 1000.0 + 0.0;
+ (round(info.rotation), round(info.x), round(info.y))
+}
+
+#[test]
+fn the_panel_keeps_a_flip_apart_from_rotation() {
+ let mut doc = Document::open(&simple_file()).unwrap();
+ let mut h = History::default();
+ apply(&mut doc, &mut h, r#"[{"op":"flip","ids":["1:3"]}]"#);
+ // A horizontal flip keeps the angle and the top left corner.
+ assert_eq!(panel(&doc, "1:3"), (0.0, 10.0, 20.0));
+ // Typing a rotation turns the flipped layer about its center.
+ let (before, _) = frame(&doc, "1:3");
+ apply(
+ &mut doc,
+ &mut h,
+ r#"[{"op":"set","ids":["1:3"],"props":{"rotation":90}}]"#,
+ );
+ let i = doc.find(Guid::parse("1:3").unwrap()).unwrap();
+ assert!(doc.world(i).is_mirrored(), "it stays flipped");
+ assert_eq!(panel(&doc, "1:3").0, 90.0);
+ let center = |r: Rect| ((r.x + r.w / 2.0).round(), (r.y + r.h / 2.0).round());
+ assert_eq!(center(frame(&doc, "1:3").0), center(before));
+ apply(
+ &mut doc,
+ &mut h,
+ r#"[{"op":"set","ids":["1:3"],"props":{"rotation":0}}]"#,
+ );
+ assert_eq!(panel(&doc, "1:3"), (0.0, 10.0, 20.0), "back where it was");
+ // Typing X and Y moves the flipped layer's top left corner there.
+ apply(
+ &mut doc,
+ &mut h,
+ r#"[{"op":"set","ids":["1:3"],"props":{"x":30,"y":40}}]"#,
+ );
+ assert_eq!(panel(&doc, "1:3"), (0.0, 30.0, 40.0));
+ assert_eq!(frame(&doc, "1:3").0, Rect::new(30.0, 40.0, 100.0, 50.0));
+ // A vertical flip reads as a half turn of the horizontally flipped layer.
+ apply(
+ &mut doc,
+ &mut h,
+ r#"[{"op":"flip","ids":["1:3"]},{"op":"flip","ids":["1:3"],"vertical":true}]"#,
+ );
+ assert_eq!(panel(&doc, "1:3").0.abs(), 180.0);
+}
+
+#[test]
+fn rotation_in_a_rotated_group_is_the_page_angle() {
+ let mut doc = Document::open(&simple_file()).unwrap();
+ let mut h = History::default();
+ // Turning the frame turns its rectangle with it.
+ apply(
+ &mut doc,
+ &mut h,
+ r#"[{"op":"set","ids":["1:2"],"props":{"rotation":30}}]"#,
+ );
+ assert_eq!(panel(&doc, "1:3").0, 30.0);
+ apply(
+ &mut doc,
+ &mut h,
+ r#"[{"op":"set","ids":["1:3"],"props":{"rotation":45}}]"#,
+ );
+ assert_eq!(panel(&doc, "1:3").0, 45.0, "what was typed, not 75°");
+}
diff --git a/crates/fig_engine/src/edit/layout/settings.rs b/crates/fig_engine/src/edit/layout/settings.rs
index 93d05d3449..47c3e917a8 100644
--- a/crates/fig_engine/src/edit/layout/settings.rs
+++ b/crates/fig_engine/src/edit/layout/settings.rs
@@ -271,6 +271,9 @@ impl Txn<'_> {
match self.group(&same, true)? {
Some(g) => {
self.edit(g, flags::NAME).name = Some("Frame".into());
+ // As in Figma, the new frame does not clip what it
+ // wraps (shadows and overhangs stay visible).
+ self.edit(g, flags::CLIP).clip_disabled = Some(true);
g
}
None => return Ok(None),
diff --git a/crates/fig_engine/src/edit/layout/test.rs b/crates/fig_engine/src/edit/layout/test.rs
index 347acdc99d..086929c82b 100644
--- a/crates/fig_engine/src/edit/layout/test.rs
+++ b/crates/fig_engine/src/edit/layout/test.rs
@@ -261,6 +261,24 @@ fn wraps_layers_in_a_hugging_stack() {
assert_eq!(doc.node(frame).children.len(), 2);
// 40 + 40 gap + 60 wide, as tall as the taller one.
assert_eq!(doc.props(frame).size(), Vec2::new(140.0, 30.0));
+ // As in Figma, the wrapping frame does not clip (shadows show).
+ assert!(!doc.props(frame).clips_content());
+}
+
+#[test]
+fn a_frame_around_a_selection_does_not_clip_it() {
+ let mut doc = Document::open(&blank("x")).unwrap();
+ let mut h = History::default();
+ let (_, kids) = row(&mut doc, &mut h);
+ let created = apply(
+ &mut doc,
+ &mut h,
+ &format!(
+ r#"[{{"op":"group","ids":["{}","{}"],"frame":true}}]"#,
+ kids[0], kids[1]
+ ),
+ );
+ assert!(!doc.props(idx(&doc, &created[0])).clips_content());
}
#[test]
diff --git a/crates/fig_engine/src/edit/library/import.rs b/crates/fig_engine/src/edit/library/import.rs
index 1a204cac83..64fceede46 100644
--- a/crates/fig_engine/src/edit/library/import.rs
+++ b/crates/fig_engine/src/edit/library/import.rs
@@ -87,13 +87,18 @@ impl Ids {
fn map_paints(paints: &mut Option<Arc<[Paint]>>, ids: &mut Ids) {
if let Some(list) = paints
- && list.iter().any(|p| p.color_var.is_some())
+ && list
+ .iter()
+ .any(|p| p.color_var.is_some() || matches!(p.kind, crate::model::PaintKind::Pattern(_)))
{
*list = list
.iter()
.map(|p| {
let mut p = p.clone();
p.color_var = p.color_var.map(|g| ids.map(g));
+ if let crate::model::PaintKind::Pattern(pattern) = &mut p.kind {
+ pattern.source = ids.map(pattern.source);
+ }
p
})
.collect();
diff --git a/crates/fig_engine/src/edit/test.rs b/crates/fig_engine/src/edit/test.rs
index 460b9f5983..4c714fa493 100644
--- a/crates/fig_engine/src/edit/test.rs
+++ b/crates/fig_engine/src/edit/test.rs
@@ -411,3 +411,22 @@ fn edits_effects() {
let r = reopened.find(Guid::parse("1:3").unwrap()).unwrap();
assert_eq!(reopened.props(r).effects().len(), 2);
}
+
+#[test]
+fn steps_keep_their_ids_through_coalescing_undo_and_redo() {
+ let (mut doc, mut h) = open();
+ let nudge = ops(r#"[{"op":"translate","ids":["1:3"],"dx":1,"dy":0}]"#);
+ assert_eq!(h.undo_step(), None);
+ h.apply(&mut doc, &nudge, None).unwrap();
+ let first = h.undo_step().unwrap();
+ // A drag's steps are one step, with one id.
+ h.apply(&mut doc, &nudge, Some("drag")).unwrap();
+ let drag = h.undo_step().unwrap();
+ assert_ne!(drag, first);
+ h.apply(&mut doc, &nudge, Some("drag")).unwrap();
+ assert_eq!(h.undo_step(), Some(drag));
+ h.undo(&mut doc).unwrap();
+ assert_eq!((h.undo_step(), h.redo_step()), (Some(first), Some(drag)));
+ h.redo(&mut doc).unwrap();
+ assert_eq!((h.undo_step(), h.redo_step()), (Some(drag), None));
+}
diff --git a/crates/fig_engine/src/export/pdf.rs b/crates/fig_engine/src/export/pdf.rs
index 54668c7bc8..a4429e90a0 100644
--- a/crates/fig_engine/src/export/pdf.rs
+++ b/crates/fig_engine/src/export/pdf.rs
@@ -158,6 +158,7 @@ fn vector_paint(paint: &Paint) -> bool {
PaintKind::Image(img) => {
img.scale_mode != ImageScaleMode::Tile && img.filters == ImageFilters::default()
}
+ PaintKind::Pattern(_) => false,
PaintKind::Unsupported(_) => true,
}
}
@@ -506,7 +507,7 @@ impl Page<'_> {
matrix(&world.mul(&to_node).mul(&unit))
);
}
- PaintKind::Unsupported(_) => {}
+ PaintKind::Pattern(_) | PaintKind::Unsupported(_) => {}
}
}
@@ -574,6 +575,11 @@ impl Page<'_> {
}
}
}
+ let container_stroke =
+ self.props(i).node_type().is_frame_like() && !self.props(i).clips_content();
+ if container_stroke && self.props(i).has_visible_strokes() {
+ self.strokes(i, alpha);
+ }
let p = self.props(i);
let children = self.scene.node(i).children.clone();
if p.node_type().draws_children() && !children.is_empty() {
@@ -596,7 +602,7 @@ impl Page<'_> {
self.ops.push_str("Q\n");
}
}
- if self.props(i).has_visible_strokes() {
+ if self.props(i).has_visible_strokes() && !container_stroke {
self.strokes(i, alpha);
}
}
diff --git a/crates/fig_engine/src/inspect.rs b/crates/fig_engine/src/inspect.rs
index 26a4a0f7f6..32ff78bf42 100644
--- a/crates/fig_engine/src/inspect.rs
+++ b/crates/fig_engine/src/inspect.rs
@@ -258,6 +258,7 @@ fn paint_info(p: &Paint, size: Vec2) -> PaintInfo {
info.scale_mode = Some(enum_name(&img.scale_mode));
info.image_hash = img.hash.as_deref().map(str::to_owned);
}
+ PaintKind::Pattern(_) => info.kind = "PATTERN".into(),
PaintKind::Unsupported(kind) => info.kind = kind.to_ascii_uppercase(),
}
info
@@ -297,7 +298,7 @@ pub fn node_info(doc: &Document, scene: &Scene, i: SceneIdx) -> NodeInfo {
let props = scene.props(doc, i);
let node = scene.node(i);
let size = props.size();
- let origin = node.world.apply(Vec2::default());
+ let origin = node.world.panel_origin(size);
let (x, y) = match coordinate_parent(scene, doc, i) {
Some(p) => {
let inv = scene.node(p).world.invert().unwrap_or_default();
@@ -402,7 +403,7 @@ pub fn node_info(doc: &Document, scene: &Scene, i: SceneIdx) -> NodeInfo {
y,
width: size.x,
height: size.y,
- rotation: node.world.rotation_degrees(),
+ rotation: node.world.panel_rotation_degrees(),
bounds: scene.frame_bounds(doc, i),
opacity: props.opacity(),
blend_mode: enum_name(&props.blend_mode()),
diff --git a/crates/fig_engine/src/lib.rs b/crates/fig_engine/src/lib.rs
index dc13bac9ac..0cda5c6e52 100644
--- a/crates/fig_engine/src/lib.rs
+++ b/crates/fig_engine/src/lib.rs
@@ -24,6 +24,7 @@ pub mod svg;
#[cfg(test)]
pub(crate) mod testing;
pub mod text;
+mod variables;
pub mod vector;
#[cfg(target_arch = "wasm32")]
pub mod wasm;
diff --git a/crates/fig_engine/src/library.rs b/crates/fig_engine/src/library.rs
index d8fc90f840..d6ad073746 100644
--- a/crates/fig_engine/src/library.rs
+++ b/crates/fig_engine/src/library.rs
@@ -519,6 +519,9 @@ pub(crate) fn dependencies(p: &Props, out: &mut Vec<Guid>) {
add(p.text_style_id);
for paint in p.fills().iter().chain(p.strokes()) {
add(paint.color_var);
+ if let crate::model::PaintKind::Pattern(pattern) = &paint.kind {
+ add(Some(pattern.source));
+ }
}
for a in p.prop_assignments.iter().flat_map(|a| a.iter()) {
if let PropValue::Symbol(g) = a.value {
diff --git a/crates/fig_engine/src/model.rs b/crates/fig_engine/src/model.rs
index e82c53ef31..96bbd5c29e 100644
--- a/crates/fig_engine/src/model.rs
+++ b/crates/fig_engine/src/model.rs
@@ -25,7 +25,7 @@ pub use handoff::{
pub use library::LibraryLink;
pub use paint::{
BlendMode, Color, ColorStop, Effect, EffectKind, GradientKind, ImageFilters, ImagePaint,
- ImageScaleMode, Paint, PaintKind,
+ ImageScaleMode, Paint, PaintKind, PatternAlign, PatternLayout, PatternPaint,
};
pub use prototype::{Action, FlowStart, Interaction, OverlaySettings};
pub use text::{Baseline, Decoration, Glyph, StyleRun, TextContent, TextLayout, TextStyle};
@@ -494,6 +494,8 @@ pub struct Props {
pub corner_radius: Option<f32>,
pub corner_radii: Option<CornerRadii>,
pub corner_smoothing: Option<f32>,
+ /// Ellipse start angle, end angle (radians), and inner radius ratio.
+ pub arc_data: Option<[f32; 3]>,
/// `frameMaskDisabled`: frames clip their content unless this is set.
pub clip_disabled: Option<bool>,
pub background_color: Option<Color>,
@@ -597,7 +599,7 @@ impl Props {
mask_type, fills, strokes, stroke_weight, stroke_sides, stroke_align, stroke_cap,
stroke_join,
dash_pattern, fill_geometry, stroke_geometry, effects, corner_radius, corner_radii,
- corner_smoothing, clip_disabled, background_color, internal_only, text_content,
+ corner_smoothing, arc_data, clip_disabled, background_color, internal_only, text_content,
text_layout, text_style,
symbol, derived, swapped_symbol, prop_assignments, prop_refs, prop_defs,
override_key, auto_layout, layout_child, export_settings, boolean_operation, vector_data, constraints,
@@ -686,6 +688,21 @@ impl Props {
self.fills().iter().any(Paint::is_visible)
}
+ /// Figma ignores stored shadow spread on open arcs and arbitrary paths.
+ /// Containers support it only when their filled shape clips the contents.
+ pub fn supports_shadow_spread(&self) -> bool {
+ match self.node_type() {
+ NodeType::Rectangle | NodeType::RoundedRectangle => true,
+ NodeType::Ellipse => self.arc_data.is_none_or(|[start, end, inner]| {
+ inner == 0.0 && (end - start).abs() >= std::f32::consts::TAU - 1e-5
+ }),
+ NodeType::Frame | NodeType::Symbol | NodeType::Instance => {
+ self.clips_content() && self.has_visible_fills()
+ }
+ _ => false,
+ }
+ }
+
/// The library this node is a copy of an asset from.
pub fn library_source(&self) -> Option<&str> {
self.library.as_ref()?.source.as_deref()
diff --git a/crates/fig_engine/src/model/geom.rs b/crates/fig_engine/src/model/geom.rs
index 5c32b1c4c7..d440eb9add 100644
--- a/crates/fig_engine/src/model/geom.rs
+++ b/crates/fig_engine/src/model/geom.rs
@@ -43,6 +43,12 @@ impl Affine {
m12: 0.0,
};
+ /// A mirror across the y axis (x ↦ −x).
+ pub const MIRROR_X: Affine = Affine {
+ m00: -1.0,
+ ..Self::IDENTITY
+ };
+
pub fn translate(x: f64, y: f64) -> Self {
Affine {
m02: x,
@@ -137,6 +143,33 @@ impl Affine {
-self.m10.atan2(self.m00).to_degrees()
}
+ /// Whether the transform mirrors its layer (a flipped layer).
+ pub fn is_mirrored(&self) -> bool {
+ self.determinant() < 0.0
+ }
+
+ /// The rotation the design panel shows. A mirrored transform reads as a
+ /// horizontal flip followed by this rotation, as in Figma, so flipping a
+ /// layer horizontally keeps its angle (and a vertical flip reads 180°).
+ pub fn panel_rotation_degrees(&self) -> f64 {
+ if self.is_mirrored() {
+ self.mul(&Affine::MIRROR_X).rotation_degrees()
+ } else {
+ self.rotation_degrees()
+ }
+ }
+
+ /// Where the design panel's X and Y point of a `size` layer with this
+ /// transform is: its origin, or for a mirrored layer the origin of the
+ /// unflipped layer it reads as (see `panel_rotation_degrees`).
+ pub fn panel_origin(&self, size: Vec2) -> Vec2 {
+ if self.is_mirrored() {
+ self.apply(Vec2::new(size.x, 0.0))
+ } else {
+ self.apply(Vec2::default())
+ }
+ }
+
pub fn to_skia(&self) -> tiny_skia::Transform {
tiny_skia::Transform::from_row(
self.m00 as f32,
diff --git a/crates/fig_engine/src/model/paint.rs b/crates/fig_engine/src/model/paint.rs
index 24eb6e1119..6af10150d0 100644
--- a/crates/fig_engine/src/model/paint.rs
+++ b/crates/fig_engine/src/model/paint.rs
@@ -186,6 +186,61 @@ pub struct ImagePaint {
pub original_size: Option<Vec2>,
}
+/// Alignment of a repeated source tile within its painted layer.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub enum PatternAlign {
+ #[default]
+ Start,
+ Center,
+ End,
+}
+
+impl PatternAlign {
+ pub fn parse(value: &str) -> Self {
+ match value {
+ "CENTER" => Self::Center,
+ "END" => Self::End,
+ _ => Self::Start,
+ }
+ }
+ pub fn name(self) -> &'static str {
+ match self {
+ Self::Start => "START",
+ Self::Center => "CENTER",
+ Self::End => "END",
+ }
+ }
+}
+
+/// Supported layouts for repeating a pattern source.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub enum PatternLayout {
+ #[default]
+ Rectangular,
+ HorizontalHexagonal,
+}
+
+impl PatternLayout {
+ pub fn name(self) -> &'static str {
+ match self {
+ Self::Rectangular => "RECTANGULAR",
+ Self::HorizontalHexagonal => "HORIZONTAL_HEXAGONAL",
+ }
+ }
+}
+
+/// A rectangular pattern whose tile is another node in the same document.
+#[derive(Clone, Debug, PartialEq)]
+pub struct PatternPaint {
+ pub layout: PatternLayout,
+ pub source: super::Guid,
+ pub scale: f32,
+ /// Gaps as fractions of the source width/height; negative values overlap.
+ pub spacing: Vec2,
+ pub horizontal: PatternAlign,
+ pub vertical: PatternAlign,
+}
+
#[derive(Clone, Debug, PartialEq)]
pub enum PaintKind {
Solid(Color),
@@ -196,7 +251,8 @@ pub enum PaintKind {
transform: Affine,
},
Image(ImagePaint),
- /// Emoji, video, pattern, noise: drawn as nothing.
+ Pattern(PatternPaint),
+ /// Emoji, video, unsupported pattern layouts, noise: drawn as nothing.
Unsupported(&'static str),
}
diff --git a/crates/fig_engine/src/render.rs b/crates/fig_engine/src/render.rs
index cf84a4fc22..06d968827a 100644
--- a/crates/fig_engine/src/render.rs
+++ b/crates/fig_engine/src/render.rs
@@ -12,6 +12,7 @@
mod effects;
pub(crate) mod paint;
+pub(crate) mod pattern;
mod text;
use crate::document::Document;
@@ -92,6 +93,8 @@ pub(crate) struct Painter<'a> {
reach: f64,
/// Cleared masks to reuse (see [`AreaMask`]).
masks: Vec<Mask>,
+ /// Sources currently being rendered, to stop cyclic patterns.
+ active_patterns: Vec<crate::model::Guid>,
}
/// Renders a viewport of a scene into a premultiplied RGBA pixmap.
@@ -115,6 +118,7 @@ pub fn render(
margin: 0.0,
reach: 0.0,
masks: Vec::new(),
+ active_patterns: Vec::new(),
};
// Effects sample beyond what they cover: render with a margin so blurs
// and shadows from just outside the region are complete inside it.
@@ -169,6 +173,7 @@ pub fn render_node(
margin: 0.0,
reach: 0.0,
masks: Vec::new(),
+ active_patterns: Vec::new(),
};
let mut surface = Surface::new(0, 0, vp.width, vp.height)?;
if let Some(bg) = opts.background {
@@ -231,7 +236,11 @@ impl<'a> Painter<'a> {
let r = match e.kind {
EffectKind::DropShadow => {
f64::from(e.radius) * 1.5
- + f64::from(e.spread.abs())
+ + if self.props(i).supports_shadow_spread() {
+ f64::from(e.spread.abs())
+ } else {
+ 0.0
+ }
+ e.offset.x.abs().max(e.offset.y.abs())
}
EffectKind::LayerBlur if e.radius > 0.0 => f64::from(e.radius) * 1.5,
@@ -262,7 +271,11 @@ impl<'a> Painter<'a> {
let reach = match e.kind {
EffectKind::InnerShadow => {
f64::from(e.radius) * 1.5
- + f64::from(e.spread.abs())
+ + if props.supports_shadow_spread() {
+ f64::from(e.spread.abs())
+ } else {
+ 0.0
+ }
+ e.offset.x.abs().max(e.offset.y.abs())
}
EffectKind::BackgroundBlur => f64::from(e.radius) * 1.5,
@@ -463,8 +476,12 @@ impl<'a> Painter<'a> {
.iter()
.filter(|e| e.is_visible() && e.kind == EffectKind::DropShadow)
{
+ let mut e = e.clone();
+ if !props.supports_shadow_spread() {
+ e.spread = 0.0;
+ }
let offset = self.device_vector(i, e.offset);
- effects::drop_shadow(&mut with_shadows.pixmap, &layer.pixmap, e, offset, scale);
+ effects::drop_shadow(&mut with_shadows.pixmap, &layer.pixmap, &e, offset, scale);
}
with_shadows.pixmap.draw_pixmap(
0,
@@ -527,7 +544,7 @@ impl<'a> Painter<'a> {
self.draw_node_content_with_opacity(i, surface, clip, as_mask, 1.0);
}
- /// Fills, inner shadows, children, strokes.
+ /// Fills, inner shadows, container strokes, children, shape strokes.
fn draw_node_content_with_opacity(
&mut self,
i: SceneIdx,
@@ -564,6 +581,13 @@ impl<'a> Painter<'a> {
self.inner_shadows(i, &inner, surface, clip);
}
+ // A nonclipping container's border belongs below its contents: a tab can
+ // cover a parent's border with its own underline or background.
+ let container_stroke = node_type.is_frame_like() && !props.clips_content();
+ if container_stroke && props.has_visible_strokes() {
+ self.draw_strokes(i, props, &ts, surface, clip, opacity);
+ }
+
let generated = &self.scene.node(i).generated;
if !generated.is_empty() {
for g in generated.clone() {
@@ -592,7 +616,7 @@ impl<'a> Painter<'a> {
}
// Text draws its own strokes, clipped to its glyphs.
- if props.has_visible_strokes() && !node_type.is_text() {
+ if props.has_visible_strokes() && !node_type.is_text() && !container_stroke {
self.draw_strokes(i, props, &ts, surface, clip, opacity);
}
}
diff --git a/crates/fig_engine/src/render/effects.rs b/crates/fig_engine/src/render/effects.rs
index 14abbad11e..f6d0ae608b 100644
--- a/crates/fig_engine/src/render/effects.rs
+++ b/crates/fig_engine/src/render/effects.rs
@@ -379,7 +379,11 @@ impl Painter<'_> {
&mut plane,
w as usize,
h as usize,
- (f64::from(e.spread) * scale).round() as i32,
+ if self.props(i).supports_shadow_spread() {
+ (f64::from(e.spread) * scale).round() as i32
+ } else {
+ 0
+ },
);
let (dx, dy) = self.device_vector(i, e.offset);
let mut plane = shifted(
diff --git a/crates/fig_engine/src/render/paint.rs b/crates/fig_engine/src/render/paint.rs
index a8cf0f9803..086aa6d5c9 100644
--- a/crates/fig_engine/src/render/paint.rs
+++ b/crates/fig_engine/src/render/paint.rs
@@ -96,6 +96,9 @@ impl Painter<'_> {
PaintKind::Image(image) => {
self.fill_image(surface, shape, ts, image, size, alpha, blend, clip);
}
+ PaintKind::Pattern(pattern) => {
+ self.fill_pattern(surface, shape, ts, pattern, size, alpha, blend, clip);
+ }
PaintKind::Unsupported(_) => {}
}
}
diff --git a/crates/fig_engine/src/render/pattern.rs b/crates/fig_engine/src/render/pattern.rs
new file mode 100644
index 0000000000..2c99cc2b97
--- /dev/null
+++ b/crates/fig_engine/src/render/pattern.rs
@@ -0,0 +1,174 @@
+//! Rectangular patterns render their source as a reusable transparent tile.
+
+use super::{Painter, RenderOptions, Shape, Surface};
+use crate::document::Document;
+use crate::images::ImageStore;
+use crate::model::{Affine, Guid, PatternAlign, PatternLayout, PatternPaint, Rect, Vec2};
+use crate::scene::Scene;
+use tiny_skia::{FilterQuality, Mask, Pattern, Pixmap, SpreadMode};
+
+const MAX_PATTERN_DEPTH: usize = 8;
+const MAX_TILE_SIDE: u32 = 2048;
+const MAX_OVERLAP: i32 = 8;
+
+/// One transparent, repeatable cell, also used by SVG export.
+pub(crate) struct Tile {
+ pub pixmap: Pixmap,
+ pub step: Vec2,
+ pub source_size: Vec2,
+}
+
+impl Tile {
+ pub(crate) fn transform(&self, pattern: &PatternPaint, size: Vec2) -> Affine {
+ let scale = f64::from(pattern.scale);
+ let offset = |alignment, layer, source| match alignment {
+ PatternAlign::Start => 0.0,
+ PatternAlign::Center => (layer - source * scale) / 2.0,
+ PatternAlign::End => layer - source * scale,
+ };
+ Affine::translate(
+ offset(pattern.horizontal, size.x, self.source_size.x),
+ offset(pattern.vertical, size.y, self.source_size.y),
+ )
+ .mul(&Affine::scale(
+ self.step.x * scale / f64::from(self.pixmap.width()),
+ self.step.y * scale / f64::from(self.pixmap.height()),
+ ))
+ }
+}
+
+pub(crate) fn render_tile(
+ doc: &Document,
+ images: &mut ImageStore,
+ pattern: &PatternPaint,
+ density: f64,
+ active: &[Guid],
+) -> Option<Tile> {
+ if active.len() >= MAX_PATTERN_DEPTH
+ || active.contains(&pattern.source)
+ || !pattern.scale.is_finite()
+ || pattern.scale <= 0.0
+ {
+ return None;
+ }
+ let source = doc.find(pattern.source)?;
+ let source_size = doc.props(source).size();
+ let step = Vec2::new(
+ source_size.x * (1.0 + pattern.spacing.x),
+ source_size.y * (1.0 + pattern.spacing.y),
+ );
+ if !step.x.is_finite() || !step.y.is_finite() || step.x <= 0.0 || step.y <= 0.0 {
+ return None;
+ }
+ let pitch = step;
+ let rows: i32 = match pattern.layout {
+ PatternLayout::Rectangular => 1,
+ PatternLayout::HorizontalHexagonal => 2,
+ };
+ let step = Vec2::new(step.x, step.y * f64::from(rows));
+ // Supersample small vector tiles so fractional (including negative)
+ // spacing does not snap to whole pixels at ordinary canvas zoom.
+ let density = density.max(4.0);
+ let w = (step.x * density)
+ .ceil()
+ .clamp(1.0, f64::from(MAX_TILE_SIDE)) as u32;
+ let h = (step.y * density)
+ .ceil()
+ .clamp(1.0, f64::from(MAX_TILE_SIDE)) as u32;
+ let mut tile = Surface::new(0, 0, w, h)?;
+ let scene = Scene::build_instance(doc, source);
+ let &source_node = scene.node(scene.root()).children.first()?;
+ let to_local = scene.node(source_node).world.invert()?;
+ let raster = Affine::scale(f64::from(w) / step.x, f64::from(h) / step.y);
+ let overlap_x = (source_size.x / step.x).ceil() as i32;
+ let overlap_y = (source_size.y / pitch.y).ceil() as i32;
+ if overlap_x > MAX_OVERLAP || overlap_y > MAX_OVERLAP {
+ return None;
+ }
+ let mut active_patterns = active.to_vec();
+ active_patterns.push(pattern.source);
+ let mut painter = Painter {
+ doc,
+ scene: &scene,
+ images,
+ opts: RenderOptions::default(),
+ base: Affine::IDENTITY,
+ scale: raster.scale_factor(),
+ region: Rect::new(0.0, 0.0, f64::from(w), f64::from(h)),
+ margin: 0.0,
+ reach: 0.0,
+ masks: Vec::new(),
+ active_patterns,
+ };
+ // Neighboring copies contribute when spacing is negative. Rendering
+ // them into one period makes the shader repeat seamlessly.
+ for y in -overlap_y..=rows {
+ for x in -overlap_x..=1 {
+ let stagger =
+ if pattern.layout == PatternLayout::HorizontalHexagonal && y.rem_euclid(2) == 1 {
+ pitch.x / 2.0
+ } else {
+ 0.0
+ };
+ painter.base = raster
+ .mul(&Affine::translate(
+ f64::from(x) * pitch.x + stagger,
+ f64::from(y) * pitch.y,
+ ))
+ .mul(&to_local);
+ painter.draw_node(source_node, &mut tile, None);
+ }
+ }
+ Some(Tile {
+ pixmap: tile.pixmap,
+ step,
+ source_size,
+ })
+}
+
+impl Painter<'_> {
+ #[expect(
+ clippy::too_many_arguments,
+ reason = "matches the paint renderer's fill interface"
+ )]
+ pub(super) fn fill_pattern(
+ &mut self,
+ surface: &mut Surface,
+ shape: &Shape,
+ ts: &Affine,
+ pattern: &PatternPaint,
+ size: Vec2,
+ alpha: f32,
+ blend: tiny_skia::BlendMode,
+ clip: Option<&Mask>,
+ ) {
+ let density = ts.scale_factor() * f64::from(pattern.scale);
+ let Some(tile) = render_tile(
+ self.doc,
+ self.images,
+ pattern,
+ density,
+ &self.active_patterns,
+ ) else {
+ return;
+ };
+ let paint = tiny_skia::Paint {
+ shader: Pattern::new(
+ tile.pixmap.as_ref(),
+ SpreadMode::Repeat,
+ FilterQuality::Bilinear,
+ alpha,
+ tile.transform(pattern, size).to_skia(),
+ ),
+ blend_mode: blend,
+ anti_alias: true,
+ force_hq_pipeline: false,
+ };
+ surface
+ .pixmap
+ .fill_path(shape.path(), &paint, shape.rule(), ts.to_skia(), clip);
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/fig_engine/src/render/pattern/test.rs b/crates/fig_engine/src/render/pattern/test.rs
new file mode 100644
index 0000000000..f99daca95f
--- /dev/null
+++ b/crates/fig_engine/src/render/pattern/test.rs
@@ -0,0 +1,192 @@
+use crate::document::Document;
+use crate::images::ImageStore;
+use crate::model::{PaintKind, PatternAlign};
+use crate::render::{RenderOptions, Viewport, render};
+use crate::scene::Scene;
+use crate::testing::{V, fig_file_with, guid, node, size, solid, translate};
+use std::sync::Arc;
+
+fn fixture(spacing: f32, scale: f32, cyclic: bool) -> Vec<u8> {
+ fixture_layout(spacing, scale, cyclic, "RECTANGULAR")
+}
+
+fn fixture_layout(spacing: f32, scale: f32, cyclic: bool, layout: &'static str) -> Vec<u8> {
+ let schema = crate::testing::SCHEMA
+ .replace("GRADIENT_DIAMOND IMAGE", "GRADIENT_DIAMOND IMAGE PATTERN")
+ .replace("message Paint type:PaintType", "enum PatternTileType RECTANGULAR HORIZONTAL_HEXAGONAL VERTICAL_HEXAGONAL\nenum PatternAlignment START CENTER END\nmessage Paint sourceNodeId:GUID scale:float patternSpacing:Vector patternTileType:PatternTileType horizontalAlignment:PatternAlignment verticalAlignment:PatternAlignment type:PaintType");
+ let pattern = || {
+ V::List(vec![V::Msg(vec![
+ ("type", V::Enum("PATTERN")),
+ ("sourceNodeId", guid(3)),
+ ("scale", V::Float(scale)),
+ ("patternSpacing", size(spacing, 0.0)),
+ ("patternTileType", V::Enum(layout)),
+ ])])
+ };
+ fig_file_with(
+ &schema,
+ vec![
+ node(0, None, "DOCUMENT", "Document", vec![]),
+ node(1, Some((0, "!")), "CANVAS", "Destination", vec![]),
+ node(2, Some((0, "#")), "CANVAS", "Source page", vec![]),
+ node(
+ 3,
+ Some((2, "!")),
+ "RECTANGLE",
+ "Tile",
+ vec![
+ ("size", size(4.0, 4.0)),
+ ("transform", translate(100.0, 100.0)),
+ (
+ "fillPaints",
+ if cyclic {
+ pattern()
+ } else {
+ V::List(vec![solid(1.0, 0.0, 0.0)])
+ },
+ ),
+ ],
+ ),
+ node(
+ 4,
+ Some((1, "!")),
+ "RECTANGLE",
+ "Pattern",
+ vec![
+ ("size", size(20.0, 8.0)),
+ ("transform", translate(0.0, 0.0)),
+ ("fillPaints", pattern()),
+ ],
+ ),
+ ],
+ vec![],
+ )
+}
+
+fn draw(doc: &Document) -> tiny_skia::Pixmap {
+ let scene = Scene::build(doc, doc.pages[0]);
+ render(
+ doc,
+ &scene,
+ &mut ImageStore::default(),
+ &Viewport {
+ x: 0.0,
+ y: 0.0,
+ scale: 1.0,
+ width: 24,
+ height: 12,
+ },
+ RenderOptions::default(),
+ )
+ .unwrap()
+}
+
+#[test]
+fn rectangular_pattern_loads_its_source_and_tiles_with_spacing() {
+ let bytes = Arc::new(fixture(0.5, 1.0, false));
+ for doc in [
+ Document::open(&bytes).unwrap(),
+ Document::open_lazy(&bytes).unwrap(),
+ ] {
+ let pixels = draw(&doc);
+ for x in [1, 7, 13, 19] {
+ assert_eq!(pixels.pixel(x, 1).unwrap().red(), 255);
+ }
+ for x in [4, 5, 10, 11, 16, 17, 20] {
+ assert_eq!(pixels.pixel(x, 1).unwrap().alpha(), 0);
+ }
+ assert_eq!(
+ pixels.pixel(1, 8).unwrap().alpha(),
+ 0,
+ "clip to destination"
+ );
+ }
+}
+
+#[test]
+fn pattern_negative_spacing_and_scale_render_without_gaps() {
+ let doc = Document::open(&fixture(-0.2, 2.0, false)).unwrap();
+ let pixels = draw(&doc);
+ for x in 0..20 {
+ assert_eq!(pixels.pixel(x, 1).unwrap().alpha(), 255, "x={x}");
+ }
+}
+
+#[test]
+fn pattern_alignment_and_opacity_are_applied_to_the_repeated_source() {
+ let mut doc = Document::open(&fixture(0.5, 1.0, false)).unwrap();
+ let target = doc
+ .find(crate::model::Guid {
+ session: 1,
+ local: 4,
+ })
+ .unwrap();
+ let paints = Arc::make_mut(doc.nodes[target as usize].props.fills.as_mut().unwrap());
+ let PaintKind::Pattern(pattern) = &mut paints[0].kind else {
+ panic!("pattern")
+ };
+ pattern.horizontal = PatternAlign::End;
+ paints[0].opacity = 0.5;
+ let pixels = draw(&doc);
+ assert_eq!(pixels.pixel(13, 1).unwrap().alpha(), 128);
+ assert_eq!(pixels.pixel(14, 1).unwrap().alpha(), 0);
+ assert_eq!(pixels.pixel(17, 1).unwrap().alpha(), 128);
+}
+
+#[test]
+fn cyclic_patterns_are_transparent_and_terminate() {
+ let doc = Document::open(&fixture(0.0, 1.0, true)).unwrap();
+ assert!(draw(&doc).pixels().iter().all(|p| p.alpha() == 0));
+}
+
+#[test]
+fn saving_an_edited_pattern_keeps_the_source_and_tile_settings() {
+ let bytes = fixture_layout(-0.2, 1.5, false, "HORIZONTAL_HEXAGONAL");
+ let mut doc = Document::open(&bytes).unwrap();
+ let target = doc
+ .find(crate::model::Guid {
+ session: 1,
+ local: 4,
+ })
+ .unwrap();
+ let paints = Arc::make_mut(doc.nodes[target as usize].props.fills.as_mut().unwrap());
+ paints[0].opacity = 0.5;
+ let PaintKind::Pattern(pattern) = &mut paints[0].kind else {
+ panic!("pattern")
+ };
+ pattern.horizontal = PatternAlign::End;
+ pattern.vertical = PatternAlign::Center;
+ doc.nodes[target as usize].edits |= crate::edit::flags::FILLS;
+ let saved = crate::save::save(&doc, &bytes).unwrap();
+ let reopened = Document::open(&saved).unwrap();
+ assert_eq!(doc.props(target).fills(), reopened.props(target).fills());
+ assert_eq!(draw(&doc).data(), draw(&reopened).data());
+}
+
+#[test]
+fn svg_embeds_a_repeating_pattern_tile() {
+ let doc = Document::open(&fixture_layout(0.5, 1.5, false, "HORIZONTAL_HEXAGONAL")).unwrap();
+ let scene = Scene::build(&doc, doc.pages[0]);
+ let node = scene.find(&doc, "1:4").unwrap();
+ let svg = crate::svg::export(&doc, &scene, node).unwrap();
+ assert!(svg.contains("<pattern "));
+ assert!(svg.contains("data:image/png;base64,"));
+ assert!(svg.contains("fill=\"url(#pattern"));
+}
+
+#[test]
+fn horizontal_hex_patterns_stagger_alternate_rows_by_half_a_cell() {
+ let bytes = Arc::new(fixture_layout(0.5, 1.0, false, "HORIZONTAL_HEXAGONAL"));
+ for doc in [
+ Document::open(&bytes).unwrap(),
+ Document::open_lazy(&bytes).unwrap(),
+ ] {
+ let pixels = draw(&doc);
+ assert_eq!(pixels.pixel(2, 1).unwrap().alpha(), 255);
+ assert_eq!(pixels.pixel(4, 1).unwrap().alpha(), 0);
+ assert_eq!(pixels.pixel(2, 5).unwrap().alpha(), 0);
+ assert_eq!(pixels.pixel(4, 5).unwrap().alpha(), 255);
+ assert_eq!(pixels.pixel(8, 5).unwrap().alpha(), 0);
+ assert_eq!(pixels.pixel(10, 5).unwrap().alpha(), 255);
+ }
+}
diff --git a/crates/fig_engine/src/render/test.rs b/crates/fig_engine/src/render/test.rs
index 4066076562..f9fb86fd48 100644
--- a/crates/fig_engine/src/render/test.rs
+++ b/crates/fig_engine/src/render/test.rs
@@ -2,6 +2,8 @@ use super::*;
use crate::testing::{V, fig_file, node, simple_file, size, solid, translate};
mod fidelity;
+mod groups;
+mod stroke_order;
fn rgba(p: &Pixmap, x: u32, y: u32) -> [u8; 4] {
let c = p.pixel(x, y).unwrap().demultiply();
@@ -151,6 +153,32 @@ fn exports_one_node_on_transparency() {
assert_eq!(rgba(&p, 100, 50), [255, 0, 0, 255]);
}
+#[test]
+fn exports_children_with_their_shadows() {
+ // Showcase: "Home" holds a white "Card" (24, 260, 312 × 120) with a drop
+ // shadow (y 4, blur 12) on the frame's white.
+ let bytes = crate::testing::showcase_file();
+ let doc = Document::open(&bytes).unwrap();
+ let scene = Scene::build(&doc, doc.pages[0]);
+ let home = (0..scene.nodes.len() as SceneIdx)
+ .find(|&i| scene.props(&doc, i).name() == "Home")
+ .unwrap();
+ for scale in [1.0, 2.0] {
+ let p = render_node(
+ &doc,
+ &scene,
+ &mut ImageStore::default(),
+ home,
+ scale,
+ RenderOptions::default(),
+ )
+ .unwrap();
+ let at = |v: f64| (v * scale) as u32;
+ let [r, ..] = rgba(&p, at(180.0), at(384.0));
+ assert!(r < 250, "the shadow shows below the card at {scale}× ({r})");
+ }
+}
+
#[test]
fn draws_outlines() {
let doc = Document::open(&simple_file()).unwrap();
diff --git a/crates/fig_engine/src/render/test/fidelity.rs b/crates/fig_engine/src/render/test/fidelity.rs
index 620142c31e..8774213d1d 100644
--- a/crates/fig_engine/src/render/test/fidelity.rs
+++ b/crates/fig_engine/src/render/test/fidelity.rs
@@ -12,7 +12,7 @@ use tiny_skia::Pixmap;
/// The common test schema plus FigJam's generated layers and derived text.
const SCHEMA: &str = "
-enum NodeType DOCUMENT CANVAS GROUP FRAME RECTANGLE ROUNDED_RECTANGLE ELLIPSE VECTOR TEXT SYMBOL INSTANCE SECTION STICKY SHAPE_WITH_TEXT CONNECTOR TEXT_PATH
+enum NodeType DOCUMENT CANVAS GROUP FRAME RECTANGLE ROUNDED_RECTANGLE ELLIPSE VECTOR TEXT SYMBOL INSTANCE SECTION STICKY SHAPE_WITH_TEXT CONNECTOR TEXT_PATH LINE
enum NodePhase CREATED REMOVED
enum PaintType SOLID GRADIENT_LINEAR GRADIENT_RADIAL GRADIENT_ANGULAR GRADIENT_DIAMOND IMAGE
enum BlendMode PASS_THROUGH NORMAL MULTIPLY SCREEN
@@ -39,7 +39,8 @@ message VectorData styleOverrideTable:NodeChange[]
message DerivedTextData layoutSize:Vector glyphs:Glyph[] truncationStartIndex:int
message NodeGenerationData overrides:NodeChange[]
message DerivedImmutableFrameData overrides:NodeChange[]
-message NodeChange guid:GUID phase:NodePhase parentIndex:ParentIndex type:NodeType name:string visible:bool locked:bool opacity:float size:Vector transform:Matrix fillPaints:Paint[] strokePaints:Paint[] strokeWeight:float strokeAlign:StrokeAlign fillGeometry:Path[] strokeGeometry:Path[] effects:Effect[] cornerRadius:float backgroundColor:Color symbolData:SymbolData guidPath:GUIDPath overrideKey:GUID internalOnly:bool derivedTextData:DerivedTextData nodeGenerationData:NodeGenerationData derivedImmutableFrameData:DerivedImmutableFrameData vectorData:VectorData styleID:uint styleIdForFill:StyleId
+message ArcData startingAngle:float endingAngle:float innerRadius:float
+message NodeChange guid:GUID phase:NodePhase parentIndex:ParentIndex type:NodeType name:string visible:bool locked:bool opacity:float size:Vector transform:Matrix fillPaints:Paint[] strokePaints:Paint[] strokeWeight:float strokeAlign:StrokeAlign fillGeometry:Path[] strokeGeometry:Path[] effects:Effect[] cornerRadius:float backgroundColor:Color symbolData:SymbolData guidPath:GUIDPath overrideKey:GUID internalOnly:bool derivedTextData:DerivedTextData nodeGenerationData:NodeGenerationData derivedImmutableFrameData:DerivedImmutableFrameData vectorData:VectorData styleID:uint styleIdForFill:StyleId arcData:ArcData
message Blob bytes:byte[]
message Message nodeChanges:NodeChange[] blobs:Blob[]
";
@@ -530,3 +531,62 @@ fn overrides_take_their_shared_styles() {
let p = draw(&bytes, viewport(0.0, 0.0, 1.0, 40, 20));
assert_eq!(rgba(&p, 10, 10), [0, 255, 0, 255]);
}
+
+#[test]
+fn shadow_spread_respects_the_shape_that_figma_supports() {
+ fn sample(kind: &'static str, arc: Option<[f32; 3]>, spread: f32) -> Vec<u8> {
+ let mut fields = vec![
+ ("size", size(40.0, 40.0)),
+ ("transform", translate(40.0, 40.0)),
+ ("fillPaints", V::List(vec![solid(0.4, 0.4, 0.4)])),
+ (
+ "effects",
+ V::List(vec![V::Msg(vec![
+ ("type", V::Enum("DROP_SHADOW")),
+ ("color", color(0.0, 0.0, 0.0, 1.0)),
+ ("radius", V::Float(4.0)),
+ ("spread", V::Float(spread)),
+ ])]),
+ ),
+ ];
+ if let Some([start, end, inner]) = arc {
+ fields.push((
+ "arcData",
+ V::Msg(vec![
+ ("startingAngle", V::Float(start)),
+ ("endingAngle", V::Float(end)),
+ ("innerRadius", V::Float(inner)),
+ ]),
+ ));
+ }
+ file(vec![node(2, Some((1, "!")), kind, "Shape", fields)], vec![])
+ }
+ let tau = std::f32::consts::TAU;
+ for (kind, arc, supported) in [
+ ("RECTANGLE", None, true),
+ ("ELLIPSE", None, true),
+ ("ELLIPSE", Some([0.0, tau, 0.0]), true),
+ ("ELLIPSE", Some([0.0, tau / 2.0, 0.0]), false),
+ ("ELLIPSE", Some([0.0, tau, 1.0]), false),
+ ("LINE", None, false),
+ ("VECTOR", None, false),
+ ] {
+ let base = sample(kind, arc, 0.0);
+ let expanded = sample(kind, arc, 20.0);
+ let a = draw(&base, viewport(0.0, 0.0, 1.0, 120, 120));
+ let b = draw(&expanded, viewport(0.0, 0.0, 1.0, 120, 120));
+ assert_eq!(a.data() != b.data(), supported, "{kind} {arc:?}");
+ let doc = Document::open(&expanded).unwrap();
+ let scene = Scene::build(&doc, doc.pages[0]);
+ let shape = scene.find(&doc, "1:2").unwrap();
+ let svg = crate::svg::export(&doc, &scene, shape).unwrap();
+ assert_eq!(
+ svg.contains("feMorphology"),
+ supported,
+ "SVG {kind} {arc:?}"
+ );
+ let props = scene.props(&doc, shape);
+ assert_eq!(props.arc_data, arc);
+ assert_eq!(props.effects()[0].spread, 20.0, "retain the authored value");
+ }
+}
diff --git a/crates/fig_engine/src/render/test/groups.rs b/crates/fig_engine/src/render/test/groups.rs
new file mode 100644
index 0000000000..7eb3a53f8e
--- /dev/null
+++ b/crates/fig_engine/src/render/test/groups.rs
@@ -0,0 +1,83 @@
+use super::{rgba, viewport};
+use crate::images::ImageStore;
+use crate::model::{Guid, NodeType};
+use crate::render::{RenderOptions, render};
+use crate::testing::{SCHEMA, V, fig_file_with, node, size, solid, translate};
+use crate::{Document, Scene};
+use std::sync::Arc;
+
+#[test]
+fn resize_to_fit_groups_do_not_clip_children_to_the_stored_frame_box() {
+ let schema = SCHEMA.replace(
+ "message NodeChange guid:GUID",
+ "message NodeChange resizeToFit:bool frameMaskDisabled:bool guid:GUID",
+ );
+ let container = |id, x, group| {
+ node(
+ id,
+ Some((1, "!")),
+ "FRAME",
+ "Container",
+ vec![
+ ("size", size(20.0, 20.0)),
+ ("transform", translate(x, 20.0)),
+ ("resizeToFit", V::Bool(group)),
+ ("frameMaskDisabled", V::Bool(false)),
+ ],
+ )
+ };
+ let child = |id, parent| {
+ node(
+ id,
+ Some((parent, "!")),
+ "RECTANGLE",
+ "Content beyond the stored box",
+ vec![
+ ("size", size(10.0, 40.0)),
+ ("transform", translate(5.0, -10.0)),
+ ("fillPaints", V::List(vec![solid(0.0, 1.0, 0.0)])),
+ ],
+ )
+ };
+ let bytes = Arc::new(fig_file_with(
+ &schema,
+ vec![
+ node(0, None, "DOCUMENT", "Document", vec![]),
+ node(1, Some((0, "!")), "CANVAS", "Page", vec![]),
+ container(2, 10.0, true),
+ child(3, 2),
+ container(4, 50.0, false),
+ child(5, 4),
+ ],
+ vec![],
+ ));
+ for doc in [
+ Document::open(&bytes).unwrap(),
+ Document::open_lazy(&bytes).unwrap(),
+ ] {
+ let group = doc
+ .find(Guid {
+ session: 1,
+ local: 2,
+ })
+ .unwrap();
+ assert_eq!(doc.props(group).node_type(), NodeType::Group);
+ let scene = Scene::build(&doc, doc.pages[0]);
+ let pixmap = render(
+ &doc,
+ &scene,
+ &mut ImageStore::default(),
+ &viewport(0.0, 0.0, 1.0, 90, 60),
+ RenderOptions {
+ outline: false,
+ background: Some(crate::model::Color::BLACK),
+ },
+ )
+ .unwrap();
+ assert_eq!(rgba(&pixmap, 20, 15), [0, 255, 0, 255]);
+ assert_eq!(rgba(&pixmap, 20, 45), [0, 255, 0, 255]);
+ assert_eq!(rgba(&pixmap, 60, 15), [0, 0, 0, 255]);
+ assert_eq!(rgba(&pixmap, 60, 45), [0, 0, 0, 255]);
+ assert_eq!(rgba(&pixmap, 60, 30), [0, 255, 0, 255]);
+ }
+}
diff --git a/crates/fig_engine/src/render/test/stroke_order.rs b/crates/fig_engine/src/render/test/stroke_order.rs
new file mode 100644
index 0000000000..3ff987e503
--- /dev/null
+++ b/crates/fig_engine/src/render/test/stroke_order.rs
@@ -0,0 +1,77 @@
+use super::{draw, rgba, viewport};
+use crate::testing::{V, fig_file, node, size, solid, translate};
+use crate::{Document, Scene};
+
+#[test]
+fn child_tabs_cover_the_container_border() {
+ let bytes = fig_file(
+ vec![
+ node(0, None, "DOCUMENT", "Document", vec![]),
+ node(1, Some((0, "!")), "CANVAS", "Page", vec![]),
+ node(
+ 2,
+ Some((1, "!")),
+ "FRAME",
+ "Tab bar",
+ vec![
+ ("size", size(80.0, 30.0)),
+ ("transform", translate(10.0, 10.0)),
+ ("fillPaints", V::List(vec![solid(0.0, 0.0, 0.0)])),
+ ("strokePaints", V::List(vec![solid(0.5, 0.5, 0.5)])),
+ ("strokeWeight", V::Float(1.0)),
+ ("strokeAlign", V::Enum("INSIDE")),
+ ],
+ ),
+ node(
+ 3,
+ Some((2, "!")),
+ "RECTANGLE",
+ "Active underline",
+ vec![
+ ("size", size(20.0, 1.0)),
+ ("transform", translate(10.0, 29.0)),
+ ("fillPaints", V::List(vec![solid(0.0, 1.0, 0.0)])),
+ ],
+ ),
+ node(
+ 4,
+ Some((2, "#")),
+ "RECTANGLE",
+ "Open tab edge",
+ vec![
+ ("size", size(20.0, 1.0)),
+ ("transform", translate(40.0, 29.0)),
+ ("fillPaints", V::List(vec![solid(0.0, 0.0, 0.0)])),
+ ],
+ ),
+ ],
+ vec![],
+ );
+ for scale in [1.0, 2.0] {
+ let mut doc = Document::open(&bytes).unwrap();
+ let frame = doc.find(crate::model::Guid::parse("1:2").unwrap()).unwrap();
+ doc.nodes[frame as usize].props.clip_disabled = Some(true);
+ let scene = Scene::build(&doc, doc.pages[0]);
+ let p = crate::render::render(
+ &doc,
+ &scene,
+ &mut crate::images::ImageStore::default(),
+ &viewport(0.0, 0.0, scale, 200, 100),
+ crate::render::RenderOptions::default(),
+ )
+ .unwrap();
+ let sample = |x, y| rgba(&p, (x * scale) as u32, (y * scale) as u32);
+ assert_eq!(sample(25.0, 39.0), [0, 255, 0, 255]);
+ assert_eq!(sample(55.0, 39.0), [0, 0, 0, 255]);
+ assert_eq!(sample(80.0, 39.0), [128, 128, 128, 255]);
+ }
+ let clipped = draw(&bytes, viewport(0.0, 0.0, 1.0, 100, 50));
+ assert_eq!(rgba(&clipped, 25, 39), [128, 128, 128, 255]);
+ assert_eq!(rgba(&clipped, 55, 39), [128, 128, 128, 255]);
+ let mut doc = Document::open(&bytes).unwrap();
+ let frame = doc.find(crate::model::Guid::parse("1:2").unwrap()).unwrap();
+ doc.nodes[frame as usize].props.clip_disabled = Some(true);
+ let scene = Scene::build(&doc, doc.pages[0]);
+ let svg = crate::svg::export(&doc, &scene, 0).unwrap();
+ assert!(svg.find("#808080").unwrap() < svg.find("#00FF00").unwrap());
+}
diff --git a/crates/fig_engine/src/save.rs b/crates/fig_engine/src/save.rs
index e035f5e3b1..f053e2e8f3 100644
--- a/crates/fig_engine/src/save.rs
+++ b/crates/fig_engine/src/save.rs
@@ -35,7 +35,9 @@ enum MessageType JOIN_START NODE_CHANGES USER_CHANGES JOIN_END SIGNAL STYLE STYL
enum NodePhase CREATED REMOVED
enum NodeType NONE DOCUMENT CANVAS GROUP FRAME BOOLEAN_OPERATION VECTOR STAR LINE ELLIPSE RECTANGLE REGULAR_POLYGON ROUNDED_RECTANGLE TEXT SLICE SYMBOL INSTANCE STICKY SHAPE_WITH_TEXT CONNECTOR CODE_BLOCK WIDGET STAMP MEDIA HIGHLIGHT SECTION SECTION_OVERLAY WASHI_TAPE VARIABLE TABLE TABLE_CELL
enum BlendMode PASS_THROUGH NORMAL DARKEN MULTIPLY LINEAR_BURN COLOR_BURN LIGHTEN SCREEN LINEAR_DODGE COLOR_DODGE OVERLAY SOFT_LIGHT HARD_LIGHT DIFFERENCE EXCLUSION HUE SATURATION COLOR LUMINOSITY
-enum PaintType SOLID GRADIENT_LINEAR GRADIENT_RADIAL GRADIENT_ANGULAR GRADIENT_DIAMOND IMAGE EMOJI VIDEO
+enum PaintType SOLID GRADIENT_LINEAR GRADIENT_RADIAL GRADIENT_ANGULAR GRADIENT_DIAMOND IMAGE EMOJI VIDEO PATTERN
+enum PatternTileType RECTANGULAR HORIZONTAL_HEXAGONAL VERTICAL_HEXAGONAL
+enum PatternAlignment START CENTER END
enum ImageScaleMode STRETCH FIT FILL TILE
enum EffectType INNER_SHADOW DROP_SHADOW FOREGROUND_BLUR BACKGROUND_BLUR
enum StrokeAlign CENTER INSIDE OUTSIDE
@@ -67,7 +69,7 @@ message Number value:float units:NumberUnits
message FontName family:string style:string postscript:string
message ColorStop color:Color position:float
message Image hash:byte[] name:string
-message Paint type:PaintType color:Color opacity:float visible:bool blendMode:BlendMode stops:ColorStop[] transform:Matrix image:Image imageScaleMode:ImageScaleMode rotation:float scale:float originalImageWidth:uint originalImageHeight:uint
+message Paint type:PaintType color:Color opacity:float visible:bool blendMode:BlendMode stops:ColorStop[] transform:Matrix image:Image imageScaleMode:ImageScaleMode rotation:float scale:float originalImageWidth:uint originalImageHeight:uint sourceNodeId:GUID patternSpacing:Vector patternTileType:PatternTileType horizontalAlignment:PatternAlignment verticalAlignment:PatternAlignment
message Effect type:EffectType color:Color offset:Vector radius:float visible:bool blendMode:BlendMode spread:float showShadowBehindNode:bool
message Path windingRule:WindingRule commandsBlob:uint styleID:uint
message Glyph commandsBlob:uint position:Vector styleID:uint fontSize:float firstCharacter:uint advance:float
@@ -102,7 +104,8 @@ struct ExportConstraint type:ExportConstraintType value:float
message ExportSettings suffix:string imageType:ImageType constraint:ExportConstraint svgIDMode:ExportSVGIDMode svgOutlineText:bool contentsOnly:bool useAbsoluteBounds:bool quality:float
message LayoutGrid type:LayoutGridType axis:Axis visible:bool numSections:int offset:float sectionSize:float gutterSize:float color:Color pattern:LayoutGridPattern
message Guide axis:Axis offset:float guid:GUID
-message NodeChange guid:GUID phase:NodePhase parentIndex:ParentIndex type:NodeType name:string visible:bool locked:bool opacity:float blendMode:BlendMode size:Vector transform:Matrix mask:bool fillPaints:Paint[] strokePaints:Paint[] strokeWeight:float strokeAlign:StrokeAlign strokeCap:StrokeCap strokeJoin:StrokeJoin dashPattern:float[] fillGeometry:Path[] strokeGeometry:Path[] effects:Effect[] cornerRadius:float rectangleTopLeftCornerRadius:float rectangleTopRightCornerRadius:float rectangleBottomLeftCornerRadius:float rectangleBottomRightCornerRadius:float rectangleCornerRadiiIndependent:bool cornerSmoothing:float frameMaskDisabled:bool backgroundColor:Color backgroundOpacity:float backgroundEnabled:bool internalOnly:bool textData:TextData derivedTextData:DerivedTextData fontSize:float fontName:FontName lineHeight:Number letterSpacing:Number textAlignHorizontal:TextAlignHorizontal textAlignVertical:TextAlignVertical textAutoResize:TextAutoResize paragraphSpacing:float textDecoration:TextDecoration textCase:TextCase derivedSymbolData:NodeChange[] stackMode:StackMode stackSpacing:float stackHorizontalPadding:float stackVerticalPadding:float stackPaddingRight:float stackPaddingBottom:float stackPrimaryAlignItems:StackJustify stackCounterAlignItems:StackAlign stackPrimarySizing:StackSize stackCounterSizing:StackSize stackWrap:StackWrap stackChildPrimaryGrow:float stackChildAlignSelf:StackCounterAlign stackPositioning:StackPositioning horizontalConstraint:ConstraintType verticalConstraint:ConstraintType symbolData:SymbolData overriddenSymbolID:GUID guidPath:GUIDPath overrideKey:GUID booleanOperation:BooleanOperation vectorData:VectorData componentPropDefs:ComponentPropDef[] componentPropRefs:ComponentPropRef[] componentPropAssignments:ComponentPropAssignment[] variantPropSpecs:VariantPropSpec[] stateGroupPropertyValueOrders:StateGroupPropertyValueOrder[] isStateGroup:bool propsAreBubbled:bool description:string key:string styleType:StyleType sortPosition:string isSoftDeleted:bool styleIdForFill:StyleId styleIdForStrokeFill:StyleId styleIdForEffect:StyleId styleIdForText:StyleId styleID:uint exportSettings:ExportSettings[] layoutGrids:LayoutGrid[] guides:Guide[]
+message ArcData startingAngle:float endingAngle:float innerRadius:float
+message NodeChange arcData:ArcData guid:GUID phase:NodePhase parentIndex:ParentIndex type:NodeType name:string visible:bool locked:bool opacity:float blendMode:BlendMode size:Vector transform:Matrix mask:bool fillPaints:Paint[] strokePaints:Paint[] strokeWeight:float strokeAlign:StrokeAlign strokeCap:StrokeCap strokeJoin:StrokeJoin dashPattern:float[] fillGeometry:Path[] strokeGeometry:Path[] effects:Effect[] cornerRadius:float rectangleTopLeftCornerRadius:float rectangleTopRightCornerRadius:float rectangleBottomLeftCornerRadius:float rectangleBottomRightCornerRadius:float rectangleCornerRadiiIndependent:bool cornerSmoothing:float frameMaskDisabled:bool backgroundColor:Color backgroundOpacity:float backgroundEnabled:bool internalOnly:bool textData:TextData derivedTextData:DerivedTextData fontSize:float fontName:FontName lineHeight:Number letterSpacing:Number textAlignHorizontal:TextAlignHorizontal textAlignVertical:TextAlignVertical textAutoResize:TextAutoResize paragraphSpacing:float textDecoration:TextDecoration textCase:TextCase derivedSymbolData:NodeChange[] stackMode:StackMode stackSpacing:float stackHorizontalPadding:float stackVerticalPadding:float stackPaddingRight:float stackPaddingBottom:float stackPrimaryAlignItems:StackJustify stackCounterAlignItems:StackAlign stackPrimarySizing:StackSize stackCounterSizing:StackSize stackWrap:StackWrap stackChildPrimaryGrow:float stackChildAlignSelf:StackCounterAlign stackPositioning:StackPositioning horizontalConstraint:ConstraintType verticalConstraint:ConstraintType symbolData:SymbolData overriddenSymbolID:GUID guidPath:GUIDPath overrideKey:GUID booleanOperation:BooleanOperation vectorData:VectorData componentPropDefs:ComponentPropDef[] componentPropRefs:ComponentPropRef[] componentPropAssignments:ComponentPropAssignment[] variantPropSpecs:VariantPropSpec[] stateGroupPropertyValueOrders:StateGroupPropertyValueOrder[] isStateGroup:bool propsAreBubbled:bool description:string key:string styleType:StyleType sortPosition:string isSoftDeleted:bool styleIdForFill:StyleId styleIdForStrokeFill:StyleId styleIdForEffect:StyleId styleIdForText:StyleId styleID:uint exportSettings:ExportSettings[] layoutGrids:LayoutGrid[] guides:Guide[]
message Blob bytes:byte[]
message Message type:MessageType sessionID:uint ackID:uint nodeChanges:NodeChange[] blobs:Blob[]
";
@@ -260,6 +263,15 @@ impl<'s> Build<'s> {
}
"IMAGE"
}
+ PaintKind::Pattern(pattern) => {
+ self.guid_field(&mut m, "sourceNodeId", pattern.source);
+ m.set(self.schema, "scale", Value::Float(pattern.scale));
+ self.vector(&mut m, "patternSpacing", pattern.spacing);
+ self.set_enum(&mut m, "patternTileType", pattern.layout.name());
+ self.set_enum(&mut m, "horizontalAlignment", pattern.horizontal.name());
+ self.set_enum(&mut m, "verticalAlignment", pattern.vertical.name());
+ "PATTERN"
+ }
PaintKind::Unsupported(_) => return None,
};
self.set_enum(&mut m, "type", kind);
@@ -726,6 +738,13 @@ impl<'s> Build<'s> {
if edits & flags::GEOMETRY != 0 {
self.geometry(m, "fillGeometry", p.fill_geometry.as_deref());
self.geometry(m, "strokeGeometry", p.stroke_geometry.as_deref());
+ if let Some([start, end, inner]) = p.arc_data {
+ self.msg_field(m, "arcData", |b, arc| {
+ arc.set(b.schema, "startingAngle", Value::Float(start));
+ arc.set(b.schema, "endingAngle", Value::Float(end));
+ arc.set(b.schema, "innerRadius", Value::Float(inner));
+ });
+ }
}
if edits & flags::TEXT != 0 {
self.text(m, p);
@@ -1105,7 +1124,7 @@ impl<'s> Build<'s> {
};
self.set_enum(&mut m, "type", t);
let mut edits = !flags::GEOMETRY;
- if p.fill_geometry.is_some() || p.stroke_geometry.is_some() {
+ if p.fill_geometry.is_some() || p.stroke_geometry.is_some() || p.arc_data.is_some() {
edits |= flags::GEOMETRY;
}
if p.node_type() != NodeType::Text {
diff --git a/crates/fig_engine/src/save/test.rs b/crates/fig_engine/src/save/test.rs
index be0b42326f..32a3353199 100644
--- a/crates/fig_engine/src/save/test.rs
+++ b/crates/fig_engine/src/save/test.rs
@@ -45,6 +45,23 @@ fn saves_edits_and_reopens() {
assert_eq!(scene.nodes.len(), 4);
}
+#[test]
+fn saves_arc_metadata_for_new_ellipses() {
+ let original = blank("Arc");
+ let mut doc = Document::open(&original).unwrap();
+ let created = apply(
+ &mut doc,
+ r#"[{"op":"create","parent":"0:1","node":{"type":"ELLIPSE","name":"Arc","x":0,"y":0,"width":40,"height":40}}]"#,
+ );
+ let id = doc.find(Guid::parse(&created[0]).unwrap()).unwrap();
+ let arc = [0.25, 4.5, 1.0];
+ doc.nodes[id as usize].props.arc_data = Some(arc);
+ let reopened = Document::open(&save(&doc, &original).unwrap()).unwrap();
+ let props = find(&reopened, &created[0]);
+ assert_eq!(props.arc_data, Some(arc));
+ assert!(!props.supports_shadow_spread());
+}
+
#[test]
fn drops_deleted_nodes() {
let original = simple_file();
diff --git a/crates/fig_engine/src/scene.rs b/crates/fig_engine/src/scene.rs
index 993028d1a3..966ed64a64 100644
--- a/crates/fig_engine/src/scene.rs
+++ b/crates/fig_engine/src/scene.rs
@@ -14,6 +14,8 @@ use crate::model::{Affine, EffectKind, Guid, NodeType, PropField, PropValue, Pro
use std::collections::HashMap;
use std::sync::Arc;
+mod variables;
+
pub type SceneIdx = u32;
/// Where a scene node's properties live.
@@ -44,6 +46,8 @@ pub struct SceneNode {
/// For instances: what their sublayers were built from (see
/// [`instance_feed`]), to tell a move from a change in what they show.
feed: u64,
+ /// Collection modes at build time, including an explicit empty selection.
+ modes: Option<Arc<[(Guid, Guid)]>>,
}
impl SceneNode {
@@ -112,6 +116,7 @@ impl Scene {
nodes: b.nodes,
by_guid: b.by_guid,
};
+ variables::resolve(doc, &mut scene);
scene.compute_world(doc);
scene.compute_bounds(doc);
scene
@@ -134,7 +139,9 @@ impl Scene {
nodes: b.nodes,
by_guid: b.by_guid,
};
+ variables::resolve(doc, &mut scene);
scene.compute_world(doc);
+ scene.compute_bounds(doc);
scene
}
@@ -298,10 +305,16 @@ impl Scene {
let mut starts = Vec::new();
for &t in touched {
let node = doc.node(t);
+ if node.props.variable.is_some() || node.props.variable_modes.is_some() {
+ return false;
+ }
if node.removed || node.props.node_type() == NodeType::Canvas && t != self.page {
return false;
}
if t == self.page {
+ if self.nodes[0].modes != node.props.mode_by_set {
+ return false;
+ }
continue;
}
let Some(&i) = node.props.guid.and_then(|g| self.by_guid.get(&g)) else {
@@ -316,7 +329,8 @@ impl Scene {
// component itself does not: instances keep their own root
// properties); an instance whose sources changed shows other
// layers.
- if !matches!(sn.props, PropSource::Doc(_))
+ if sn.modes != node.props.mode_by_set
+ || !matches!(sn.props, PropSource::Doc(_))
|| sn.path.is_some()
|| (node.props.node_type() == NodeType::Instance
&& sn.feed != instance_feed(&node.props))
@@ -556,7 +570,11 @@ fn effect_outset(props: &Props, world: &Affine) -> f64 {
let reach = match e.kind {
EffectKind::DropShadow => {
f64::from(e.radius) * 1.5
- + f64::from(e.spread.max(0.0))
+ + if props.supports_shadow_spread() {
+ f64::from(e.spread.max(0.0))
+ } else {
+ 0.0
+ }
+ e.offset.x.abs().max(e.offset.y.abs())
}
EffectKind::LayerBlur => f64::from(e.radius) * 1.5,
@@ -595,6 +613,7 @@ impl<'a> Builder<'a> {
bounds: Rect::EMPTY,
path,
feed: 0,
+ modes: self.doc.props(src).mode_by_set.clone(),
});
if let Some(p) = parent {
self.nodes[p as usize].children.push(i);
@@ -631,6 +650,7 @@ impl<'a> Builder<'a> {
bounds: Rect::EMPTY,
path: Some((root, path.into())),
feed: 0,
+ modes: self.doc.props(src).mode_by_set.clone(),
});
self.nodes[at as usize].generated.push(i);
}
@@ -654,25 +674,68 @@ impl<'a> Builder<'a> {
}
}
- fn normalize(&self, path: &[Guid]) -> Vec<Guid> {
+ fn normalize(&self, path: &[Guid], mut symbol: NodeIdx) -> Vec<Guid> {
path.iter()
.map(|g| {
- if self.doc.by_guid.contains_key(g) {
- *g
- } else {
- self.doc.by_override_key.get(g).copied().unwrap_or(*g)
+ // Imported components keep their original ids as override
+ // keys. Those ids can also name unrelated nodes in this file;
+ // resolve each segment inside its component first.
+ let direct = self.doc.find(*g);
+ let imported = self
+ .doc
+ .by_override_key
+ .get(g)
+ .and_then(|g| self.doc.find(*g));
+ let within = |mut node| loop {
+ if node == symbol {
+ return true;
+ }
+ let Some(parent) = self.doc.node(node).parent else {
+ return false;
+ };
+ node = parent;
+ };
+ let node = direct.filter(|&n| within(n)).or_else(|| {
+ imported.filter(|&n| within(n)).or_else(|| {
+ // More than one imported component can reuse a key,
+ // so the document-wide index need not hold this copy.
+ let mut pending = vec![symbol];
+ while let Some(n) = pending.pop() {
+ if self.doc.props(n).override_key == Some(*g) {
+ return Some(n);
+ }
+ pending.extend(&self.doc.node(n).children);
+ }
+ None
+ })
+ });
+ // A swapped nested instance can reference another component's
+ // nodes. Keep accepting those globally unique paths too.
+ let Some(node) = node.or(direct).or(imported) else {
+ return *g;
+ };
+ let props = self.doc.props(node);
+ if let Some(next) = props
+ .swapped_symbol
+ .or_else(|| props.symbol.as_ref().and_then(|s| s.symbol_id))
+ .and_then(|g| self.doc.find(g))
+ {
+ symbol = next;
}
+ props.guid.unwrap_or(*g)
})
.collect()
}
- fn override_map(&self, list: &[Props]) -> OverrideMap {
+ fn override_map(&self, list: &[Props], symbol: NodeIdx) -> OverrideMap {
let mut map: OverrideMap = HashMap::new();
for (i, p) in list.iter().enumerate() {
if let Some(path) = &p.guid_path
&& !path.is_empty()
{
- map.entry(self.normalize(path)).or_default().push(i as u32);
+ map.entry(self.normalize(path, symbol))
+ .or_default()
+ .push(i as u32);
}
}
map
@@ -708,9 +771,9 @@ impl<'a> Builder<'a> {
let derived = props.derived.clone().unwrap_or_else(empty);
levels.push(Level {
prefix_len: path.len(),
- override_map: self.override_map(&overrides),
+ override_map: self.override_map(&overrides, symbol),
overrides,
- derived_map: self.override_map(&derived),
+ derived_map: self.override_map(&derived, symbol),
derived,
assignments: props.prop_assignments.clone(),
symbol,
diff --git a/crates/fig_engine/src/scene/test.rs b/crates/fig_engine/src/scene/test.rs
index f086f39e9d..6a855b0308 100644
--- a/crates/fig_engine/src/scene/test.rs
+++ b/crates/fig_engine/src/scene/test.rs
@@ -93,6 +93,100 @@ fn expands_instances_with_overrides() {
assert!(matches!(fill.kind, crate::model::PaintKind::Solid(c) if c.b == 1.0));
}
+#[test]
+fn resolves_imported_override_paths_inside_each_component() {
+ use crate::testing::{SCHEMA, fig_file_with};
+
+ // Both original-library keys collide with unrelated document ids. A
+ // second import also reuses the leaf key, replacing the global index.
+ let path = || V::Msg(vec![("guids", V::List(vec![guid(42), guid(21)]))]);
+ let schema = SCHEMA.replace(
+ "unusedField:string",
+ "unusedField:string derivedSymbolData:NodeChange[]",
+ );
+ let bytes = fig_file_with(
+ &schema,
+ vec![
+ node(0, None, "DOCUMENT", "Document", vec![]),
+ node(1, Some((0, "!")), "CANVAS", "Page", vec![]),
+ node(10, Some((1, "a")), "SYMBOL", "Imported", vec![]),
+ node(
+ 11,
+ Some((10, "a")),
+ "RECTANGLE",
+ "Leaf",
+ vec![
+ ("overrideKey", guid(21)),
+ ("size", size(10.0, 10.0)),
+ ("fillPaints", V::List(vec![solid(0.0, 0.0, 1.0)])),
+ ],
+ ),
+ node(21, Some((1, "b")), "FRAME", "Unrelated", vec![]),
+ node(30, Some((1, "c")), "SYMBOL", "Other import", vec![]),
+ node(
+ 31,
+ Some((30, "a")),
+ "RECTANGLE",
+ "Other leaf",
+ vec![("overrideKey", guid(21))],
+ ),
+ node(40, Some((1, "d")), "SYMBOL", "Outer", vec![]),
+ node(
+ 41,
+ Some((40, "a")),
+ "INSTANCE",
+ "Nested",
+ vec![
+ ("overrideKey", guid(42)),
+ ("symbolData", V::Msg(vec![("symbolID", guid(10))])),
+ ],
+ ),
+ node(42, Some((1, "e")), "FRAME", "Also unrelated", vec![]),
+ node(
+ 50,
+ Some((1, "f")),
+ "INSTANCE",
+ "Placed",
+ vec![
+ (
+ "symbolData",
+ V::Msg(vec![
+ ("symbolID", guid(40)),
+ (
+ "symbolOverrides",
+ V::List(vec![V::Msg(vec![
+ ("guidPath", path()),
+ ("fillPaints", V::List(vec![solid(0.0, 1.0, 0.0)])),
+ ])]),
+ ),
+ ]),
+ ),
+ (
+ "derivedSymbolData",
+ V::List(vec![V::Msg(vec![
+ ("guidPath", path()),
+ ("size", size(60.0, 20.0)),
+ ("transform", translate(7.0, 9.0)),
+ ])]),
+ ),
+ ],
+ ),
+ ],
+ vec![],
+ );
+ let doc = Document::open(&bytes).unwrap();
+ let scene = Scene::build(&doc, doc.pages[0]);
+ let leaf = scene.find(&doc, "I1:50;1:41;1:11").unwrap();
+ let props = scene.props(&doc, leaf);
+ assert_eq!(props.size(), Vec2::new(60.0, 20.0));
+ assert_eq!(props.transform(), Affine::translate(7.0, 9.0));
+ assert!(
+ matches!(props.fills()[0].kind, crate::model::PaintKind::Solid(c) if c.g == 1.0 && c.b == 0.0)
+ );
+ let original = scene.find(&doc, "1:11").unwrap();
+ assert_eq!(scene.props(&doc, original).size(), Vec2::new(10.0, 10.0));
+}
+
#[test]
fn survives_an_instance_of_itself() {
// A component containing an instance of itself must not recurse forever.
diff --git a/crates/fig_engine/src/scene/variables.rs b/crates/fig_engine/src/scene/variables.rs
new file mode 100644
index 0000000000..d86d1a2cd2
--- /dev/null
+++ b/crates/fig_engine/src/scene/variables.rs
@@ -0,0 +1,88 @@
+//! Apply inherited collection modes after instance overrides have been merged.
+
+use super::{PropSource, Scene, SceneIdx};
+use crate::document::Document;
+use crate::model::{Guid, Paint, PaintKind, VariableValue};
+use std::sync::Arc;
+
+pub(super) fn resolve(doc: &Document, scene: &mut Scene) {
+ for i in 0..scene.nodes.len() {
+ let p = scene.props(doc, i as SceneIdx);
+ let bound = p
+ .fills()
+ .iter()
+ .chain(p.strokes())
+ .any(|p| p.color_var.is_some())
+ || p.text_content.as_ref().is_some_and(|t| {
+ t.styles.iter().any(|s| {
+ s.fills
+ .as_ref()
+ .is_some_and(|f| f.iter().any(|p| p.color_var.is_some()))
+ })
+ })
+ || p.vector_styles.as_ref().is_some_and(|s| {
+ s.iter().any(|s| {
+ s.fills
+ .as_ref()
+ .is_some_and(|f| f.iter().any(|p| p.color_var.is_some()))
+ })
+ });
+ if !bound {
+ continue;
+ }
+ let mut modes: Vec<&[(Guid, Guid)]> = Vec::new();
+ let mut at = Some(i as SceneIdx);
+ while let Some(n) = at {
+ if let Some(m) = &scene.props(doc, n).mode_by_set {
+ modes.push(m);
+ }
+ at = scene.nodes[n as usize].parent;
+ }
+ // A standalone instance scene starts at its immediate parent; its
+ // remaining document ancestors still contribute inherited modes.
+ let mut at = doc.node(scene.nodes[0].src).parent;
+ while let Some(n) = at {
+ if let Some(m) = &doc.props(n).mode_by_set {
+ modes.push(m);
+ }
+ at = doc.node(n).parent;
+ }
+ let mut next = p.clone();
+ let mut changed = paints(doc, &mut next.fills, &modes);
+ changed |= paints(doc, &mut next.strokes, &modes);
+ if let Some(content) = &mut next.text_content {
+ let content = Arc::make_mut(content);
+ for style in Arc::make_mut(&mut content.styles) {
+ changed |= paints(doc, &mut style.fills, &modes);
+ }
+ }
+ if let Some(styles) = &mut next.vector_styles {
+ for style in Arc::make_mut(styles) {
+ changed |= paints(doc, &mut style.fills, &modes);
+ }
+ }
+ if changed {
+ scene.nodes[i].props = PropSource::Owned(Box::new(next));
+ }
+ }
+}
+
+fn paints(doc: &Document, paints: &mut Option<Arc<[Paint]>>, modes: &[&[(Guid, Guid)]]) -> bool {
+ let Some(paints) = paints else {
+ return false;
+ };
+ let mut changed = false;
+ for i in 0..paints.len() {
+ if let Some(var) = paints[i].color_var
+ && let Some(VariableValue::Color(color)) = crate::variables::resolve(doc, var, modes)
+ && paints[i].kind != PaintKind::Solid(color)
+ {
+ Arc::make_mut(paints)[i].kind = PaintKind::Solid(color);
+ changed = true;
+ }
+ }
+ changed
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/fig_engine/src/scene/variables/test.rs b/crates/fig_engine/src/scene/variables/test.rs
new file mode 100644
index 0000000000..df97cc9b87
--- /dev/null
+++ b/crates/fig_engine/src/scene/variables/test.rs
@@ -0,0 +1,85 @@
+use super::*;
+use crate::model::Color;
+use crate::testing::design_system::variables_file_with_remote;
+
+#[test]
+fn remote_variables_follow_inherited_modes_in_eager_and_lazy_scenes() {
+ let bytes = Arc::new(variables_file_with_remote(true));
+ for doc in [
+ Document::open(&bytes).unwrap(),
+ Document::open_lazy(&bytes).unwrap(),
+ ] {
+ let scene = Scene::build(&doc, doc.pages[0]);
+ // The screen inherits Dark; Brand aliases Surface in this mode.
+ // The component instance must inherit the screen's mode as well.
+ for id in ["1:10", "1:11", "I1:30;1:21"] {
+ let i = scene.find(&doc, id).unwrap();
+ assert_eq!(
+ scene.props(&doc, i).fills()[0].kind,
+ PaintKind::Solid(Color::BLACK),
+ "{id}"
+ );
+ }
+ // The original component, outside the screen, uses the default Light.
+ let i = scene.find(&doc, "1:21").unwrap();
+ assert_eq!(
+ scene.props(&doc, i).fills()[0].kind,
+ PaintKind::Solid(Color::WHITE)
+ );
+ // Rendering must not rewrite the original fallback color in the file.
+ let frame = doc.find(Guid::parse("1:10").unwrap()).unwrap();
+ assert_eq!(
+ doc.props(frame).fills()[0].kind,
+ PaintKind::Solid(Color::WHITE)
+ );
+ let isolated = Scene::build_instance(&doc, doc.find(Guid::parse("1:30").unwrap()).unwrap());
+ let i = isolated.find(&doc, "I1:30;1:21").unwrap();
+ assert_eq!(
+ isolated.props(&doc, i).fills()[0].kind,
+ PaintKind::Solid(Color::BLACK)
+ );
+ }
+}
+
+#[test]
+fn missing_and_cyclic_variables_keep_the_stored_color() {
+ let bytes = variables_file_with_remote(true);
+ let mut doc = Document::open(&bytes).unwrap();
+ let surface = doc.find(Guid::parse("1:51").unwrap()).unwrap();
+ let original = doc.nodes[surface as usize].props.variable.clone();
+ doc.nodes[surface as usize].props.variable = None;
+ let scene = Scene::build(&doc, doc.pages[0]);
+ let frame = scene.find(&doc, "1:10").unwrap();
+ assert_eq!(
+ scene.props(&doc, frame).fills()[0].kind,
+ PaintKind::Solid(Color::WHITE)
+ );
+ let mut variable = (*original.unwrap()).clone();
+ variable.values = Arc::from([(
+ Guid::parse("1:61").unwrap(),
+ VariableValue::Alias(Guid::parse("1:51").unwrap()),
+ )]);
+ doc.nodes[surface as usize].props.variable = Some(Arc::new(variable));
+ let scene = Scene::build(&doc, doc.pages[0]);
+ let frame = scene.find(&doc, "1:10").unwrap();
+ assert_eq!(
+ scene.props(&doc, frame).fills()[0].kind,
+ PaintKind::Solid(Color::WHITE)
+ );
+}
+
+#[test]
+fn removing_a_mode_on_an_unpainted_ancestor_requires_rebuilding() {
+ let mut doc = Document::open(&variables_file_with_remote(true)).unwrap();
+ let frame = doc.find(Guid::parse("1:10").unwrap()).unwrap();
+ doc.nodes[frame as usize].props.fills = None;
+ let mut scene = Scene::build(&doc, doc.pages[0]);
+ doc.nodes[frame as usize].props.mode_by_set = None;
+ assert!(!scene.refresh(&doc, &[frame]));
+ let scene = Scene::build(&doc, doc.pages[0]);
+ let instance = scene.find(&doc, "I1:30;1:21").unwrap();
+ assert_eq!(
+ scene.props(&doc, instance).fills()[0].kind,
+ PaintKind::Solid(Color::WHITE)
+ );
+}
diff --git a/crates/fig_engine/src/svg.rs b/crates/fig_engine/src/svg.rs
index 1250d7a1ae..3f91d386b4 100644
--- a/crates/fig_engine/src/svg.rs
+++ b/crates/fig_engine/src/svg.rs
@@ -339,7 +339,7 @@ impl Writer<'_> {
}
}
- /// Fills, children, and strokes.
+ /// Fills, container strokes, children, and shape strokes.
fn content(&mut self, i: SceneIdx, out: &mut String) {
let p = self.props(i);
let world = self.world(i);
@@ -362,6 +362,11 @@ impl Writer<'_> {
}
}
}
+ let container_stroke =
+ self.props(i).node_type().is_frame_like() && !self.props(i).clips_content();
+ if container_stroke && self.props(i).has_visible_strokes() {
+ self.strokes(i, out);
+ }
let p = self.props(i);
if p.node_type().draws_children() && !self.scene.node(i).children.is_empty() {
let mut inner = String::new();
@@ -379,7 +384,7 @@ impl Writer<'_> {
out.push_str(&inner);
}
}
- if self.props(i).has_visible_strokes() {
+ if self.props(i).has_visible_strokes() && !container_stroke {
self.strokes(i, out);
}
}
@@ -527,6 +532,28 @@ impl Writer<'_> {
});
let _ = write!(s, " {attr}=\"url(#{id})\"");
}
+ PaintKind::Pattern(pattern) => {
+ let tile = crate::render::pattern::render_tile(
+ self.doc,
+ &mut crate::images::ImageStore::default(),
+ pattern,
+ 4.0,
+ &[],
+ )?;
+ let id = self.id("pattern");
+ let data = base64(&crate::images::encode_png(&tile.pixmap));
+ let (w, h) = (tile.pixmap.width(), tile.pixmap.height());
+ let _ = writeln!(
+ self.defs,
+ "<pattern id=\"{id}\" patternUnits=\"userSpaceOnUse\" width=\"{w}\" height=\"{h}\" patternTransform=\"{}\"><image width=\"{w}\" height=\"{h}\" href=\"data:image/png;base64,{data}\"/></pattern>",
+ matrix(&tile.transform(pattern, size))
+ );
+ let _ = write!(
+ s,
+ " {attr}=\"url(#{id})\" {attr}-opacity=\"{}\"",
+ num(f64::from(paint.opacity))
+ );
+ }
PaintKind::Image(_) | PaintKind::Unsupported(_) => return None,
}
if let Some(css) = blend_css(paint.blend_mode) {
@@ -898,7 +925,7 @@ impl Writer<'_> {
for e in effects.iter().filter(|e| e.kind == EffectKind::DropShadow) {
k += 1;
f.push_str(HARD_ALPHA);
- if e.spread != 0.0 {
+ if e.spread != 0.0 && self.scene.props(self.doc, i).supports_shadow_spread() {
let _ = writeln!(
f,
"<feMorphology radius=\"{}\" operator=\"{}\" in=\"SourceAlpha\" result=\"spread{k}\"/>",
diff --git a/crates/fig_engine/src/testing/design_system.rs b/crates/fig_engine/src/testing/design_system.rs
index 432cc48dff..bc3b9bd9a0 100644
--- a/crates/fig_engine/src/testing/design_system.rs
+++ b/crates/fig_engine/src/testing/design_system.rs
@@ -226,6 +226,10 @@ fn write_design_system_fixture() {
/// rectangle in it bound to them, and an instance of a component whose
/// layer is bound to `Surface`.
pub fn variables_file() -> Vec<u8> {
+ variables_file_with_remote(false)
+}
+
+pub(crate) fn variables_file_with_remote(remote: bool) -> Vec<u8> {
use crate::kiwi::{Schema, schema_from_text};
use crate::testing::{V, color, encode, guid, node, size, translate};
let text = crate::save::MACRO_SCHEMA
@@ -240,6 +244,16 @@ pub fn variables_file() -> Vec<u8> {
);
let schema_bytes = schema_from_text(&text);
let schema = Schema::decode(&schema_bytes).unwrap();
+ let reference = |id: u32| {
+ if remote {
+ V::Msg(vec![(
+ "assetRef",
+ V::Msg(vec![("key", V::Str(format!("asset-{id}")))]),
+ )])
+ } else {
+ V::Msg(vec![("guid", guid(id))])
+ }
+ };
let c = |r: f32, g: f32, b: f32| color(r, g, b, 1.0);
let bound = |rgb: V, var: u32| {
V::List(vec![V::Msg(vec![
@@ -250,10 +264,7 @@ pub fn variables_file() -> Vec<u8> {
(
"colorVar",
V::Msg(vec![
- (
- "value",
- V::Msg(vec![("alias", V::Msg(vec![("guid", guid(var))]))]),
- ),
+ ("value", V::Msg(vec![("alias", reference(var))])),
("dataType", V::Enum("ALIAS")),
("resolvedDataType", V::Enum("COLOR")),
]),
@@ -270,10 +281,7 @@ pub fn variables_file() -> Vec<u8> {
};
let alias = |var: u32| {
V::Msg(vec![
- (
- "value",
- V::Msg(vec![("alias", V::Msg(vec![("guid", guid(var))]))]),
- ),
+ ("value", V::Msg(vec![("alias", reference(var))])),
("dataType", V::Enum("ALIAS")),
("resolvedDataType", V::Enum("COLOR")),
])
@@ -285,7 +293,7 @@ pub fn variables_file() -> Vec<u8> {
"VARIABLE",
name,
vec![
- ("variableSetID", V::Msg(vec![("guid", guid(50))])),
+ ("variableSetID", reference(50)),
("variableResolvedType", V::Enum("COLOR")),
(
"variableDataValues",
@@ -294,7 +302,7 @@ pub fn variables_file() -> Vec<u8> {
],
)
};
- let nodes = vec![
+ let mut nodes = vec![
node(0, None, "DOCUMENT", "Document", vec![]),
node(
1,
@@ -394,6 +402,42 @@ pub fn variables_file() -> Vec<u8> {
],
),
];
+ if remote {
+ for node in &mut nodes {
+ let V::Msg(fields) = node else {
+ continue;
+ };
+ let id = fields
+ .iter()
+ .find(|(name, _)| *name == "guid")
+ .map(|(_, v)| v);
+ let Some(V::Msg(id)) = id else {
+ continue;
+ };
+ let id = id
+ .iter()
+ .find_map(|(name, v)| match (*name, v) {
+ ("localID", V::Uint(id)) => Some(*id),
+ _ => None,
+ })
+ .unwrap();
+ if [50, 51, 52].contains(&id) {
+ fields.push(("key", V::Str(format!("asset-{id}"))));
+ }
+ if id == 10 {
+ fields.push((
+ "variableModeBySetMap",
+ V::Msg(vec![(
+ "entries",
+ V::List(vec![V::Msg(vec![
+ ("variableSetID", reference(50)),
+ ("variableModeID", guid(61)),
+ ])]),
+ )]),
+ ));
+ }
+ }
+ }
let message = encode(
&schema,
"Message",
diff --git a/crates/fig_engine/src/variables.rs b/crates/fig_engine/src/variables.rs
new file mode 100644
index 0000000000..a867d4aa45
--- /dev/null
+++ b/crates/fig_engine/src/variables.rs
@@ -0,0 +1,46 @@
+//! Resolves variable values for both scene rendering and editing.
+
+use crate::document::Document;
+use crate::model::{Guid, VariableValue};
+
+/// Aliases followed at most this deep (guards against cycles).
+const MAX_ALIAS_DEPTH: usize = 16;
+
+/// The value of variable `var` where `modes` (nearest first: each a
+/// layer's `(collection, mode)` choices) apply; a collection no layer
+/// picks a mode for uses its first mode.
+pub(crate) fn resolve(
+ doc: &Document,
+ var: Guid,
+ modes: &[&[(Guid, Guid)]],
+) -> Option<VariableValue> {
+ let mut var = var;
+ for _ in 0..MAX_ALIAS_DEPTH {
+ let v = doc.props(doc.find(var)?).variable.clone()?;
+ let set = v.set;
+ let mode = set
+ .and_then(|s| {
+ modes
+ .iter()
+ .find_map(|m| m.iter().find(|(c, _)| *c == s).map(|(_, mode)| *mode))
+ })
+ .or_else(|| {
+ let first = doc
+ .props(doc.find(set?)?)
+ .variable_modes
+ .as_ref()?
+ .first()?
+ .id;
+ Some(first)
+ });
+ let value = mode
+ .and_then(|m| v.values.iter().find(|(id, _)| *id == m))
+ .or_else(|| v.values.first())
+ .map(|(_, value)| value.clone())?;
+ match value {
+ VariableValue::Alias(next) => var = next,
+ other => return Some(other),
+ }
+ }
+ None
+}
diff --git a/crates/fig_engine/src/wasm.rs b/crates/fig_engine/src/wasm.rs
index 701c139497..401b8c0a28 100644
--- a/crates/fig_engine/src/wasm.rs
+++ b/crates/fig_engine/src/wasm.rs
@@ -77,6 +77,9 @@ struct EditResult {
dirty: Option<Rect>,
can_undo: bool,
can_redo: bool,
+ /// The steps undo and redo would act on next (`History::undo_step`).
+ undo_step: Option<u64>,
+ redo_step: Option<u64>,
/// The page's layer count changed or layers moved between parents.
structure: bool,
}
@@ -194,6 +197,8 @@ impl FigFile {
dirty: (!dirty.is_empty()).then_some(dirty),
can_undo: self.history.can_undo(),
can_redo: self.history.can_redo(),
+ undo_step: self.history.undo_step(),
+ redo_step: self.history.redo_step(),
structure,
})
}
diff --git a/crates/fig_engine/tests/fixtures/design-system.fig b/crates/fig_engine/tests/fixtures/design-system.fig
index 47723d62b7..f4c1b3c161 100644
Binary files a/crates/fig_engine/tests/fixtures/design-system.fig and b/crates/fig_engine/tests/fixtures/design-system.fig differ
diff --git a/crates/fig_engine/tests/fixtures/variables.fig b/crates/fig_engine/tests/fixtures/variables.fig
index 945c526d59..152d8351b2 100644
Binary files a/crates/fig_engine/tests/fixtures/variables.fig and b/crates/fig_engine/tests/fixtures/variables.fig differ
diff --git a/docs/AGENT_GUIDE/documents.md b/docs/AGENT_GUIDE/documents.md
index 6d2d24de31..be6f0ad5e3 100644
--- a/docs/AGENT_GUIDE/documents.md
+++ b/docs/AGENT_GUIDE/documents.md
@@ -979,7 +979,16 @@ person, `data-peer="<name>"`). Clicking an avatar follows that person: their
page and view, inside a colored frame (`fig-following`) until you click,
scroll, or press **Stop**. A viewer who opens a design nobody has shared yet,
or anyone when the sync service is unreachable, gets the stored file
-read-only.
+read-only; for editors a bar above the design (`fig-session-notice`) says
+why, with **Retry** (`fig-session-action`). Editing offline is not offered:
+without the sync service's changes, storing would overwrite other people's.
+The shared changes apply only to files the session produced (each stored
+file is listed in the shared metadata before it is stored, and only once
+the sync service has that record; offline, storing waits). Whoever opens a
+file stored outside the session (a new upload, an AI edit, a restored
+version from before such a replacement) starts the shared design over on
+it, dropping the changes made on the file it replaced; people still in the
+design get a **Reload** bar and their copy turns read-only.
Macro AI reads designs with `ReadDesign` (`ReadContent` returns the same
description; attaching a design points the agent at it): the pages, numbered
@@ -1040,9 +1049,10 @@ Layout and test hooks:
the Figma node id such as `12:34`, or `I12:34;56:78` inside instances).
Rows list top-most first, as Figma does; instance and component rows are
purple. A click selects a row, Shift-click the rows between it and the
- selection, ⌘/Ctrl-click toggles a row; after a click the arrow keys move
- through the tree (`fig-layer-tree`; Left and Right collapse and expand),
- ⌥L collapses everything, and the list scrolls to the selection. Editors
+ selection, ⌘/Ctrl-click toggles a row. After a click, editors' arrow keys
+ nudge the selection as in Figma (Tab, Enter, and ⇧Enter move through the
+ layers); read-only, they move through the tree (`fig-layer-tree`; Left
+ and Right collapse and expand). ⌥L collapses everything, and the list scrolls to the selection. Editors
can double-click a row (or ⌘R) to rename it (`fig-layer-rename`), toggle
visibility and lock on hover (`fig-layer-visibility`), and drag rows to
reorder or move them into frames and groups. Right-click a row for the
@@ -1075,7 +1085,10 @@ Layout and test hooks:
layers paste into other designs and tabs, and layers copied in Figma paste
here (their images arrive as gray placeholders, since Figma's clipboard
does not carry them). Pasted instances whose component is not in the file
- are detached. Paste places layers by Figma's rules: into a selected frame
+ are detached. In a live design, the others receive pasted layers as the
+ properties Macro models, so fields it does not model (prototype links,
+ plugin data, and the like) survive only while the person who pasted is
+ the one storing the file. Paste places layers by Figma's rules: into a selected frame
(where they were if that is inside it, else centered), beside a selected
layer, or on the page where they were when that is in view and in the
middle of the view otherwise. Layers inside instances
@@ -1115,7 +1128,10 @@ Layout and test hooks:
(`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
- drag the label to scrub), fills and strokes (`fig-fills`, `fig-strokes`,
+ drag the label to scrub; a flip is kept apart from rotation: after ⇧H
+ the angle and X/Y read as before, a vertical flip reads as 180°, and
+ typing a rotation or position keeps the flip), fills and strokes
+ (`fig-fills`, `fig-strokes`,
rows `fig-fill-<n>` / `fig-stroke-<n>`, top paint first, with a hex
input `fig-fill-<n>-hex`, opacity `-opacity`, `-visibility`, and
`-remove`; "+" adds; drag a row's grip to reorder), stroke weight,
@@ -1316,10 +1332,13 @@ Layout and test hooks:
- **Keyboard**, as in Figma: ⇧0 100%, ⇧1 fit, ⇧2 selection, ⌘/Ctrl +/−, N and
⇧N next/previous frame, PageDown/PageUp pages, Enter children, ⇧Enter and
Esc parent, Tab/⇧Tab siblings, ⌘/Ctrl+A select all, ⇧R rulers, ⇧' pixel
- grid, ⌃G (Ctrl+⇧4 off macOS) layout grids, ⌘/Ctrl+Y outline view, ⌘/Ctrl+\\ hide UI, ⌘/Ctrl+⇧C copy as PNG,
- ⌘/Ctrl+⇧E export. Editing: ⌘Z/⇧⌘Z undo and redo, ⌘D duplicate, ⌘C/⌘X/⌘V,
- Delete, arrows nudge (⇧ by 10), ⌘G group, ⇧⌘G ungroup, ⌥⌘G frame
- selection, ⌘] / ⌘[ forward/backward, ⌥⌘] / ⌥⌘[ front/back, ⇧⌘H hide,
+ grid, ⌃G (Ctrl+⇧4 off macOS) layout grids, ⌘/Ctrl+Y outline view,
+ ⌘/Ctrl+\\ hide UI, ⌘/Ctrl+⇧C copy as PNG, ⌘/Ctrl+⇧E export. Editing:
+ ⌘Z/⇧⌘Z undo and redo (each brings back what was selected around the
+ step), ⌘D duplicate, ⌘C/⌘X/⌘V, Delete, arrows nudge (⇧ by 10), ⌘G
+ group, ⇧⌘G ungroup, ⌥⌘G frame selection (like ⇧A's wrapping frame, it
+ does not clip its layers), ⌘] / ⌘[ forward/backward, ⌥⌘] / ⌥⌘[
+ front/back, ⇧⌘H hide,
⇧⌘L lock, ⇧H / ⇧V flip, ⌘R rename, ⌥⇧U union, ⌥⇧S subtract (the top layers from the
bottom one), ⌥⇧I intersect, ⌥⇧X exclude, and ⌘E flatten (booleans and
shapes into one vector layer). A boolean keeps its layers as children and
@@ -1360,6 +1379,17 @@ stored design, and `window.figFixture.libraries` has `open(id)`,
installed). The sections above were verified on this fixture; the `/app/fig`
route itself needs a backend with an uploaded `.fig`.
+For import fidelity checks, save a local copy from Figma and open that same
+file in the fixture. Check the page names before switching pages, then use
+**Find layers** and **⇧2** to compare the same frame at a useful zoom in both
+apps. Include nested component logos, colors inherited from the page's
+variable mode, effects supplied by library styles, repeated pattern fills,
+and text that extends beyond a group's stored bounds. Compare exports as
+well as the canvas; an overview thumbnail can hide missing letters, wrong
+colors, or absent glows. Wait for the tiles to sharpen after zooming. The
+fixture preserves imported text outlines, but
+its substitute fonts do not verify the appearance of newly edited text.
+
## Create and type
Pasting a Macro `/app/agents/<uuid>` session URL into a Markdown editor converts