Skip to content

AI-native design editor. Open-source Figma alternative.

fix: undo in pickers, frame names on sections, and Figma text units (#1044)

Danila Poyarkovf61a611f9a94
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 00da15439..ae445635d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -156,6 +156,9 @@
### Fixed
+- Cmd+Z and Shift+Cmd+Z undo and redo while a fill, stroke, or colour picker is open, as in Figma, and undo reverts the picker's latest change rather than the edit before it.
+- A frame's name reads on the section it sits in: on a dark page, frames in a white section had white names on white. Names now fade more on light backgrounds than on dark ones, as Figma's do.
+- `lineHeight` and `letterSpacing` in the plugin API and `eval` scripts read and write Figma's `{ unit, value }`, including percent of the font size and `{ unit: 'AUTO' }`; assigning those objects used to leave the text undrawn.
- Gradients from Figma files and Figma pastes draw as they do in Figma: they ran backwards or sat in the wrong place unless they were symmetric, because the canvas applied Figma's gradient transform the wrong way round. SVG export and import keep a gradient exactly, and a new gradient starts as Figma's does, top to bottom from the fill colour to a darker shade, keeping its transform when switched between linear, radial, angular, and diamond.
- Changing stroke position, per-side stroke weights, or an effect with several layers selected changes all of them, not only the first.
- Draw layer blur, drop and inner shadows, and background blur with Figma's falloff. They spread about 15% too far, with a long faint edge Figma does not draw; SVG export keeps Figma's own `stdDeviation` of half the radius.
diff --git a/packages/core/src/canvas/labels/draw.ts b/packages/core/src/canvas/labels/draw.ts
index 498d8802c..244712f00 100644
--- a/packages/core/src/canvas/labels/draw.ts
+++ b/packages/core/src/canvas/labels/draw.ts
@@ -201,7 +201,7 @@ export function drawFrameTitles(
node.name,
layout.fontSize,
layout.maxTextWidth,
- frameTitleColor(r, highlighted),
+ frameTitleColor(r, graph, node, layout, highlighted, overlays?.rotationPreview),
r.fontGeneration,
layout.text.x,
layout.text.y,
diff --git a/packages/core/src/canvas/labels/style.ts b/packages/core/src/canvas/labels/style.ts
index 5a50ce37f..cfc3fc200 100644
--- a/packages/core/src/canvas/labels/style.ts
+++ b/packages/core/src/canvas/labels/style.ts
@@ -1,12 +1,15 @@
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
-import type { Color } from '@open-pencil/scene-graph/primitives'
+import { compositeOver } from '@open-pencil/scene-graph/color'
+import Matrix from '@open-pencil/scene-graph/matrix'
+import type { Color, Vector } from '@open-pencil/scene-graph/primitives'
import type { SkiaRenderer } from '#core/canvas/renderer'
-import type { RotationPreview } from '#core/geometry'
+import { createSceneGeometry, type RotationPreview } from '#core/geometry'
import { canvasLabelForeground } from './color'
import type { LabelHitOptions } from './hit-test'
import type { LabelLayout, LabelTextMetrics } from './layout'
+import { frameLabelPlacement } from './transform'
export function sectionLabelColors(r: SkiaRenderer, graph: SceneGraph, node: SceneNode) {
const background: Color =
@@ -22,17 +25,94 @@ export function sectionLabelColors(r: SkiaRenderer, graph: SceneGraph, node: Sce
}
}
-/** How far a frame's name fades into the canvas while the frame is not selected or hovered. */
-const FRAME_TITLE_MUTED_ALPHA = 0.5
+/**
+ * How strongly a frame's name shows while the frame is not selected or hovered. Figma desktop 126
+ * fades it further on light backgrounds: dark text at 23% and light text at 50% come within ten
+ * levels of its labels on light and dark pages and on white and dark sections.
+ */
+const FRAME_TITLE_ALPHA = { dark: 0.23, light: 0.5 } as const
+
+/** A point inside a frame's drawn name, in world space. */
+function frameTitlePoint(
+ r: SkiaRenderer,
+ graph: SceneGraph,
+ node: SceneNode,
+ layout: LabelLayout,
+ preview?: RotationPreview | null
+): Vector {
+ const placement = frameLabelPlacement(node, graph, preview)
+ const angle = (placement.rotation * Math.PI) / 180
+ const inside = {
+ x: layout.text.x / r.zoom + 1 / r.zoom,
+ y: (layout.text.y + layout.fontSize / 2) / r.zoom
+ }
+ return {
+ x: placement.x + inside.x * Math.cos(angle) - inside.y * Math.sin(angle),
+ y: placement.y + inside.x * Math.sin(angle) + inside.y * Math.cos(angle)
+ }
+}
+
+function sectionContains(
+ geometry: ReturnType<typeof createSceneGeometry>,
+ section: SceneNode,
+ point: Vector
+): boolean {
+ const inverse = Matrix.invert(geometry.worldMatrix(section))
+ if (!inverse) return false
+ const local = Matrix.mapPoint(inverse, point)
+ return local.x >= 0 && local.y >= 0 && local.x <= section.width && local.y <= section.height
+}
/**
- * A top-level frame's name: the selection color while the frame is selected or hovered, otherwise
- * the canvas's own text color, faded, so names read on light and dark canvases alike.
+ * What a frame's name is drawn over: the page, under every section around the frame that the name
+ * falls inside, each section's visible fills stacked in order. A frame at a section's top edge has
+ * its name above the section, over the page.
*/
-export function frameTitleColor(r: SkiaRenderer, highlighted: boolean) {
+function frameTitleBackground(
+ r: SkiaRenderer,
+ graph: SceneGraph,
+ node: SceneNode,
+ layout: LabelLayout,
+ preview?: RotationPreview | null
+): Color {
+ const point = frameTitlePoint(r, graph, node, layout, preview)
+ const geometry = createSceneGeometry(graph, preview)
+ const sections: SceneNode[] = []
+ for (
+ let ancestor = node.parentId ? graph.getNode(node.parentId) : undefined;
+ ancestor;
+ ancestor = ancestor.parentId ? graph.getNode(ancestor.parentId) : undefined
+ ) {
+ if (ancestor.type === 'SECTION' && sectionContains(geometry, ancestor, point))
+ sections.unshift(ancestor)
+ }
+ let background = r.pageColor
+ for (const section of sections) {
+ for (const [index, fill] of section.fills.entries()) {
+ if (fill.visible)
+ background = compositeOver(r.resolveFillColor(fill, index, section, graph), background)
+ }
+ }
+ return background
+}
+
+/**
+ * A frame's name: the selection color while the frame is selected or hovered, otherwise the text
+ * color of what it sits on, faded, so names read on light and dark pages and sections alike, as
+ * Figma draws them on a white section of a dark page.
+ */
+export function frameTitleColor(
+ r: SkiaRenderer,
+ graph: SceneGraph,
+ node: SceneNode,
+ layout: LabelLayout,
+ highlighted: boolean,
+ preview?: RotationPreview | null
+) {
if (highlighted) return r.selColor()
- const foreground = canvasLabelForeground(r.pageColor)
- return r.ck.Color4f(foreground.r, foreground.g, foreground.b, FRAME_TITLE_MUTED_ALPHA)
+ const foreground = canvasLabelForeground(frameTitleBackground(r, graph, node, layout, preview))
+ const alpha = foreground.r < 0.5 ? FRAME_TITLE_ALPHA.dark : FRAME_TITLE_ALPHA.light
+ return r.ck.Color4f(foreground.r, foreground.g, foreground.b, alpha)
}
/** Hit-testing reuses the same shaped paragraphs, constraints and paint keys as drawing. */
@@ -44,7 +124,7 @@ export function measureLabel(
): LabelTextMetrics | null {
const provider = r.fontProvider
if (!provider) return null
- let color = frameTitleColor(r, false)
+ let color = frameTitleColor(r, graph, node, layout, false)
if (layout.kind === 'section') color = sectionLabelColors(r, graph, node).foreground
else if (layout.kind === 'component') color = r.compColor()
return r.labelParagraphCache.measure(
diff --git a/packages/core/src/figma-api/accessors/text.ts b/packages/core/src/figma-api/accessors/text.ts
index 391f35f74..9c917078f 100644
--- a/packages/core/src/figma-api/accessors/text.ts
+++ b/packages/core/src/figma-api/accessors/text.ts
@@ -8,7 +8,16 @@ import {
type ProxyThis
} from '#core/figma-api/accessor-utils'
import type { FigmaFontName } from '#core/figma-api/fonts'
-import { getFontName, setFontName } from '#core/figma-api/text'
+import {
+ getFontName,
+ getLetterSpacing,
+ getLineHeight,
+ letterSpacingValue,
+ lineHeightValue,
+ setFontName,
+ type FigmaLetterSpacing,
+ type FigmaLineHeight
+} from '#core/figma-api/text'
function graph(target: ProxyThis, internals: NodeProxyInternals): SceneGraph {
return target[internals.graph] as SceneGraph
@@ -61,8 +70,26 @@ export function installTextNodeProxyAccessors(
textAlignVertical: field(internals, 'textAlignVertical'),
textDirection: field(internals, 'textDirection'),
textAutoResize: field(internals, 'textAutoResize'),
- letterSpacing: field(internals, 'letterSpacing'),
- lineHeight: field(internals, 'lineHeight'),
+ // Figma's plugin API reads and writes these as { unit, value }; a bare object stored on the
+ // node instead of pixels would leave the text unmeasurable.
+ letterSpacing: {
+ get(this: ProxyThis): FigmaLetterSpacing {
+ return getLetterSpacing(raw(this, internals))
+ },
+ set(this: ProxyThis, value: FigmaLetterSpacing | number) {
+ updateNode(this, internals, {
+ letterSpacing: letterSpacingValue(raw(this, internals), value)
+ })
+ }
+ },
+ lineHeight: {
+ get(this: ProxyThis): FigmaLineHeight {
+ return getLineHeight(raw(this, internals))
+ },
+ set(this: ProxyThis, value: FigmaLineHeight | number | null) {
+ updateNode(this, internals, { lineHeight: lineHeightValue(raw(this, internals), value) })
+ }
+ },
textCase: field(internals, 'textCase'),
textDecoration: field(internals, 'textDecoration'),
maxLines: field(internals, 'maxLines'),
diff --git a/packages/core/src/figma-api/proxy.ts b/packages/core/src/figma-api/proxy.ts
index 64ee4d28a..a6750b29d 100644
--- a/packages/core/src/figma-api/proxy.ts
+++ b/packages/core/src/figma-api/proxy.ts
@@ -39,6 +39,7 @@ import { getPageBackgrounds, setPageBackgrounds } from './page-backgrounds'
import * as PluginData from './plugin-data'
import { nodeProxyToJSON } from './serialization'
import { installSlotAccessors, prepareSlotMove, prepareSlotRemoval } from './slots'
+import type { FigmaLetterSpacing, FigmaLineHeight } from './text'
import * as TextProxy from './text'
import { containerTransform, setContainerTransform } from './transform'
import * as Traversal from './traversal'
@@ -151,8 +152,8 @@ export class FigmaNodeProxy {
declare textAlignVertical: string
declare textDirection: string
declare textAutoResize: string
- declare letterSpacing: number
- declare lineHeight: number | null
+ declare letterSpacing: FigmaLetterSpacing
+ declare lineHeight: FigmaLineHeight
declare textCase: string
declare textDecoration: string
declare maxLines: number | null
diff --git a/packages/core/src/figma-api/text.ts b/packages/core/src/figma-api/text.ts
index fc6ca988e..50785751a 100644
--- a/packages/core/src/figma-api/text.ts
+++ b/packages/core/src/figma-api/text.ts
@@ -17,6 +17,44 @@ export function setFontName(graph: SceneGraph, nodeId: string, fontName: FigmaFo
recordInstanceOverride(graph, nodeId, ['fontFamily', 'fontWeight'])
}
+/** Figma's plugin API line height: automatic, or a size in pixels or percent of the font size. */
+export type FigmaLineHeight = { unit: 'AUTO' } | { unit: 'PIXELS' | 'PERCENT'; value: number }
+/** Figma's plugin API letter spacing, in pixels or percent of the font size. */
+export interface FigmaLetterSpacing {
+ unit: 'PIXELS' | 'PERCENT'
+ value: number
+}
+
+/** The node keeps sizes in pixels; a percent is of its font size when set, as Figma resolves it. */
+function pixels(value: { unit: 'PIXELS' | 'PERCENT'; value: number }, fontSize: number) {
+ return value.unit === 'PERCENT' ? (value.value / 100) * fontSize : value.value
+}
+
+export function getLineHeight(node: SceneNode): FigmaLineHeight {
+ return node.lineHeight == null ? { unit: 'AUTO' } : { unit: 'PIXELS', value: node.lineHeight }
+}
+
+/**
+ * Accepts Figma's object, or a bare number of pixels or `null` for automatic, as earlier
+ * OpenPencil scripts wrote it.
+ */
+export function lineHeightValue(
+ node: SceneNode,
+ value: FigmaLineHeight | number | null
+): number | null {
+ if (value === null || typeof value === 'number') return value
+ return value.unit === 'AUTO' ? null : pixels(value, node.fontSize)
+}
+
+export function getLetterSpacing(node: SceneNode): FigmaLetterSpacing {
+ return { unit: 'PIXELS', value: node.letterSpacing }
+}
+
+/** Accepts Figma's object, or a bare number of pixels as earlier OpenPencil scripts wrote it. */
+export function letterSpacingValue(node: SceneNode, value: FigmaLetterSpacing | number): number {
+ return typeof value === 'number' ? value : pixels(value, node.fontSize)
+}
+
export function insertCharacters(
graph: SceneGraph,
node: SceneNode,
diff --git a/packages/core/tests/figma-api/text-units.test.ts b/packages/core/tests/figma-api/text-units.test.ts
new file mode 100644
index 000000000..277432652
--- /dev/null
+++ b/packages/core/tests/figma-api/text-units.test.ts
@@ -0,0 +1,50 @@
+import { describe, expect, test } from 'bun:test'
+
+import { FigmaAPI } from '@open-pencil/core/figma-api'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import { expectDefined } from '#core-tests/helpers/assert'
+
+function text() {
+ const graph = new SceneGraph()
+ const node = new FigmaAPI(graph).createText()
+ node.fontSize = 20
+ return { graph, node }
+}
+
+// Figma's plugin API reads and writes line height and letter spacing as { unit, value }. Scripts
+// written for Figma assigned those objects straight onto the node, which left the text
+// unmeasured and undrawn.
+describe('text units in the plugin API', () => {
+ test('line height takes pixels, percent of the font size, and auto', () => {
+ const { graph, node } = text()
+ node.lineHeight = { unit: 'PIXELS', value: 22 }
+ expect(expectDefined(graph.getNode(node.id)).lineHeight).toBe(22)
+ expect(node.lineHeight).toEqual({ unit: 'PIXELS', value: 22 })
+
+ node.lineHeight = { unit: 'PERCENT', value: 150 }
+ expect(expectDefined(graph.getNode(node.id)).lineHeight).toBe(30)
+
+ node.lineHeight = { unit: 'AUTO' }
+ expect(expectDefined(graph.getNode(node.id)).lineHeight).toBeNull()
+ expect(node.lineHeight).toEqual({ unit: 'AUTO' })
+ })
+
+ test('letter spacing takes pixels and percent of the font size', () => {
+ const { graph, node } = text()
+ node.letterSpacing = { unit: 'PERCENT', value: 10 }
+ expect(expectDefined(graph.getNode(node.id)).letterSpacing).toBe(2)
+ expect(node.letterSpacing).toEqual({ unit: 'PIXELS', value: 2 })
+ })
+
+ // Plugin typings allow only the object; untyped eval scripts may still pass a number.
+ test('a bare number still sets pixels and null automatic, as earlier OpenPencil scripts wrote them', () => {
+ const { graph, node } = text()
+ Reflect.set(node, 'lineHeight', 18)
+ Reflect.set(node, 'letterSpacing', 1)
+ expect(expectDefined(graph.getNode(node.id))).toMatchObject({
+ lineHeight: 18,
+ letterSpacing: 1
+ })
+ })
+})
diff --git a/packages/scene-graph/src/undo.ts b/packages/scene-graph/src/undo.ts
index 8297a3174..c49cf6481 100644
--- a/packages/scene-graph/src/undo.ts
+++ b/packages/scene-graph/src/undo.ts
@@ -23,6 +23,7 @@ export class UndoManager {
private undoStack: UndoEntry[] = []
private redoStack: UndoEntry[] = []
private batches: UndoBatch[] = []
+ private readonly settlers = new Set<() => void>()
private readonly limit: number
private readonly onChange: (() => void) | undefined
@@ -53,7 +54,21 @@ export class UndoManager {
this.pushUndoEntry(entry)
}
+ /**
+ * Registers a hook that commits an edit still being coalesced, such as a run of picker changes.
+ * Undo and redo run every hook first, so they act on the newest change.
+ */
+ onBeforeHistory(settle: () => void): () => void {
+ this.settlers.add(settle)
+ return () => this.settlers.delete(settle)
+ }
+
+ private settle() {
+ for (const settle of this.settlers) settle()
+ }
+
undo(): string | null {
+ this.settle()
const entry = this.undoStack.pop()
if (!entry) return null
entry.inverse()
@@ -63,6 +78,7 @@ export class UndoManager {
}
redo(): string | null {
+ this.settle()
const entry = this.redoStack.pop()
if (!entry) return null
entry.forward()
@@ -119,8 +135,10 @@ export class UndoManager {
return this.batches.length > 0
}
+ /** Committed history, or changes in an open batch that a settling hook commits first. */
get canUndo(): boolean {
- return this.undoStack.length > 0
+ if (this.undoStack.length > 0) return true
+ return this.settlers.size > 0 && this.batches.some((batch) => batch.entries.length > 0)
}
get canRedo(): boolean {
diff --git a/packages/scene-graph/tests/undo/batch.test.ts b/packages/scene-graph/tests/undo/batch.test.ts
index bbaa28cd1..c191b2255 100644
--- a/packages/scene-graph/tests/undo/batch.test.ts
+++ b/packages/scene-graph/tests/undo/batch.test.ts
@@ -36,3 +36,40 @@ test('discarding nested batches preserves committed undo/redo without replay or
undo.commitBatch()
expect(undo.redo()).toBe('Second')
})
+
+// A picker coalesces its changes into one batch until it goes idle; ⌘Z pressed before that must
+// undo those changes, not the edit before them.
+test('undo commits an edit still being coalesced and undoes it first', () => {
+ const undo = new UndoManager()
+ const values: string[] = []
+ const entry = (label: string) => ({
+ label,
+ forward: () => values.push(`redo ${label}`),
+ inverse: () => values.push(`undo ${label}`)
+ })
+ undo.push(entry('Earlier'))
+ undo.beginBatch('Change fill')
+ undo.push(entry('Picker'))
+ const stop = undo.onBeforeHistory(() => {
+ if (undo.isBatching) undo.commitBatch()
+ })
+
+ expect(undo.undo()).toBe('Change fill')
+ expect(values).toEqual(['undo Picker'])
+ stop()
+ expect(undo.undo()).toBe('Earlier')
+})
+
+// The picker's first change in a document with no history yet must still be undoable.
+test('a pending batch that will settle counts as undoable', () => {
+ const undo = new UndoManager()
+ const noop = () => undefined
+ undo.beginBatch('Change fill')
+ undo.push({ label: 'Picker', forward: noop, inverse: noop })
+ expect(undo.canUndo).toBe(false)
+ undo.onBeforeHistory(() => {
+ if (undo.isBatching) undo.commitBatch()
+ })
+ expect(undo.canUndo).toBe(true)
+ expect(undo.undo()).toBe('Change fill')
+})
diff --git a/packages/vue/src/controls/binding-provider/open-pencil.ts b/packages/vue/src/controls/binding-provider/open-pencil.ts
index 8d7d179af..263f3a080 100644
--- a/packages/vue/src/controls/binding-provider/open-pencil.ts
+++ b/packages/vue/src/controls/binding-provider/open-pencil.ts
@@ -33,14 +33,29 @@ export function createOpenPencilBindingProvider<V>(
): BindingProvider<V> {
const { contains } = useFilter({ sensitivity: 'base' })
const variables = () => editor.getVariablesByType(options.type)
- const interactiveEdits: Array<() => void> = []
+ const interactiveEdits: Array<{ end: () => void; stopSettling: () => void }> = []
+
+ /**
+ * A picker keeps one batch open while it is used. Undo and redo commit it first and reopen it,
+ * so they act on the picker's changes and later changes still form one step.
+ */
+ function beginBatch(label: string) {
+ editor.undo.beginBatch(label)
+ const stopSettling = editor.undo.onBeforeHistory(() => {
+ editor.undo.commitBatch()
+ editor.undo.beginBatch(label)
+ })
+ interactiveEdits.push({ end: editor.beginInteractiveEdit(), stopSettling })
+ }
function finishBatch(commit: boolean) {
+ const edit = interactiveEdits.pop()
+ edit?.stopSettling()
try {
if (commit) editor.undo.commitBatch()
else editor.undo.rollbackBatch()
} finally {
- interactiveEdits.pop()?.()
+ edit?.end()
}
}
@@ -101,10 +116,7 @@ export function createOpenPencilBindingProvider<V>(
? (variableId, target) => options.prepareEdit?.(editor, variableId, target)
: undefined,
runBatch: (label, action) => editor.undo.runBatch(label, action),
- beginBatch: (label) => {
- editor.undo.beginBatch(label)
- interactiveEdits.push(editor.beginInteractiveEdit())
- },
+ beginBatch,
commitBatch: () => finishBatch(true),
rollbackBatch: () => finishBatch(false)
}
diff --git a/packages/vue/src/controls/undo-batch/use.ts b/packages/vue/src/controls/undo-batch/use.ts
index 6f4c243e6..fbba55cf0 100644
--- a/packages/vue/src/controls/undo-batch/use.ts
+++ b/packages/vue/src/controls/undo-batch/use.ts
@@ -43,7 +43,12 @@ export function useUndoBatch(undo: UndoManager, beginInteractiveEdit?: () => ()
scheduleFlush()
}
- tryOnScopeDispose(flush)
+ // Undo and redo commit the coalesced edit first, so they never step past it.
+ const stopSettling = undo.onBeforeHistory(flush)
+ tryOnScopeDispose(() => {
+ flush()
+ stopSettling()
+ })
// These are applied property-list edits, not owned previews. Preserve the
// normal unmount behavior; preview owners cancel unfinished interactions.
if (getCurrentInstance()) onDeactivated(flush)
diff --git a/src/app/shell/keyboard/registry.ts b/src/app/shell/keyboard/registry.ts
index c7c884212..fc78ce870 100644
--- a/src/app/shell/keyboard/registry.ts
+++ b/src/app/shell/keyboard/registry.ts
@@ -65,23 +65,40 @@ function opacityBindings(): ShortcutDefinition[] {
const EDITOR_SHORTCUT_OVERLAY_SELECTOR =
'[data-picker-content], [role="dialog"], [role="listbox"], [role="menu"]'
+const PICKER_SELECTOR = '[data-picker-content]'
+const OPEN_LAYER_SELECTOR = '[data-dismissable-layer]:not([data-state="closed"])'
-function originatedInOverlay(event: KeyboardEvent) {
+function originatedInOverlay(event: KeyboardEvent, allowPickers = false) {
return event
.composedPath()
- .some((target) => target instanceof Element && target.matches(EDITOR_SHORTCUT_OVERLAY_SELECTOR))
+ .some(
+ (target) =>
+ target instanceof Element &&
+ target.matches(EDITOR_SHORTCUT_OVERLAY_SELECTOR) &&
+ !(allowPickers && target.closest(PICKER_SELECTOR))
+ )
}
/** A popover, menu, or dialog that is open; one fading out after closing no longer counts. */
-function hasOpenDismissableLayer() {
- return document.querySelector('[data-dismissable-layer]:not([data-state="closed"])') !== null
+function hasOpenDismissableLayer(allowPickers = false) {
+ return [...document.querySelectorAll(OPEN_LAYER_SELECTOR)].some(
+ (layer) => !(allowPickers && layer.closest(PICKER_SELECTOR))
+ )
}
-function shouldIgnoreShortcut(event: KeyboardEvent, options: KeyboardShortcutOptions) {
+/**
+ * Other shortcuts wait for open popovers to close, but undo and redo work while a fill, stroke,
+ * or colour picker is open, as in Figma; a text field in it keeps its own undo.
+ */
+function shouldIgnoreShortcut(
+ event: KeyboardEvent,
+ options: KeyboardShortcutOptions,
+ history = false
+) {
return (
isButtonActivation(event) ||
- hasOpenDismissableLayer() ||
- originatedInOverlay(event) ||
+ hasOpenDismissableLayer(history) ||
+ originatedInOverlay(event, history) ||
isEditing(event) ||
options.inputFocused.value ||
!!options.store.state.editingTextId ||
@@ -270,6 +287,11 @@ export function registerKeyboardShortcuts(options: KeyboardShortcutOptions) {
const previewKeys = new Set(
shortcuts.filter((shortcut) => shortcut.preview).flatMap((shortcut) => [shortcut.keys].flat())
)
+ const historyKeys = new Set(
+ shortcuts
+ .filter((shortcut) => shortcut.id === 'edit.undo' || shortcut.id === 'edit.redo')
+ .flatMap((shortcut) => [shortcut.keys].flat())
+ )
bindToolShortcuts(bindings, runOptions(new KeyboardEvent('keydown')))
for (const shortcut of shortcuts) {
@@ -285,7 +307,7 @@ export function registerKeyboardShortcuts(options: KeyboardShortcutOptions) {
Object.entries(bindings).map(([keys, handler]) => [
keys,
(event: KeyboardEvent) => {
- if (shouldIgnoreShortcut(event, options)) return
+ if (shouldIgnoreShortcut(event, options, historyKeys.has(keys))) return
if (options.store.state.play && !previewKeys.has(keys)) return
handler(event)
}
diff --git a/tests/e2e/canvas/labels/frame-title-color.spec.ts b/tests/e2e/canvas/labels/frame-title-color.spec.ts
new file mode 100644
index 000000000..b5f8a5521
--- /dev/null
+++ b/tests/e2e/canvas/labels/frame-title-color.spec.ts
@@ -0,0 +1,182 @@
+import { expect, test, type Page } from '@playwright/test'
+import { fromUint8Array } from 'js-base64'
+
+import { CanvasHelper } from '#tests/helpers/canvas'
+
+// Figma desktop 126 draws a frame's name against what it sits on: a white section's frame names
+// stay dark on a dark page, and names fade more on light backgrounds than on dark ones.
+
+let page: Page
+let canvas: CanvasHelper
+
+test.describe.configure({ mode: 'serial' })
+
+test.beforeAll(async ({ browser }) => {
+ page = await browser.newPage({ deviceScaleFactor: 2 })
+ await page.goto('/?test&no-chrome&no-rulers')
+ canvas = new CanvasHelper(page)
+ await canvas.waitForInit()
+})
+
+test.afterAll(async () => {
+ await page.close()
+})
+
+async function showSections(shade: number) {
+ await canvas.clearCanvas()
+ await page.evaluate((shade) => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ store.setPageColor({ r: shade / 255, g: shade / 255, b: shade / 255, a: 1 })
+ const pageId = store.state.currentPageId
+ const solid = (v: number) => [
+ { type: 'SOLID' as const, color: { r: v, g: v, b: v, a: 1 }, opacity: 1, visible: true }
+ ]
+ const section = (name: string, x: number, v: number) => {
+ const s = store.graph.createNode('SECTION', pageId, {
+ name,
+ x,
+ y: 0,
+ width: 360,
+ height: 260,
+ fills: solid(v)
+ })
+ store.graph.createNode('FRAME', s.id, {
+ name: 'Frame inside',
+ x: 80,
+ y: 100,
+ width: 200,
+ height: 120,
+ fills: solid(0.9)
+ })
+ }
+ section('White', 0, 1)
+ section('Dark', 420, 0.267)
+ store.graph.createNode('FRAME', pageId, {
+ name: 'Loose frame',
+ x: 880,
+ y: 100,
+ width: 200,
+ height: 120,
+ fills: solid(1)
+ })
+ store.state.zoom = 1
+ store.state.panX = 40
+ store.state.panY = 60
+ store.clearSelection()
+ store.requestRender()
+ }, shade)
+ await page.mouse.move(2, 2)
+ await canvas.waitForRender()
+}
+
+/** The darkest and brightest red channel in a region of the canvas, read from a screenshot. */
+async function regionRange(x: number, y: number, width = 70, height = 16) {
+ const box = await canvas.canvas.boundingBox()
+ if (!box) throw new Error('No canvas')
+ const shot = await page.screenshot({ clip: { x: box.x + x, y: box.y + y, width, height } })
+ return page.evaluate(async (data) => {
+ const image = new Image()
+ image.src = `data:image/png;base64,${data}`
+ await image.decode()
+ const copy = document.createElement('canvas')
+ copy.width = image.width
+ copy.height = image.height
+ const context = copy.getContext('2d')
+ if (!context) throw new Error('No 2D context')
+ context.drawImage(image, 0, 0)
+ const pixels = context.getImageData(0, 0, image.width, image.height).data
+ let darkest = 255
+ let brightest = 0
+ for (let i = 0; i < pixels.length; i += 4) {
+ darkest = Math.min(darkest, pixels[i])
+ brightest = Math.max(brightest, pixels[i])
+ }
+ return { darkest, brightest }
+ }, fromUint8Array(shot))
+}
+
+/** The white section's frame name sits just above the frame at (80, 100), panned to (40, 60). */
+async function whiteSectionLabelDarkest() {
+ return (await regionRange(118, 140)).darkest
+}
+
+async function expectReadableNames(name: 'dark' | 'light', shade: number) {
+ await showSections(shade)
+ // Dark text on the white section, faded as Figma fades it (its darkest pixel is about 204).
+ const darkest = await whiteSectionLabelDarkest()
+ expect(darkest).toBeLessThan(220)
+ expect(darkest).toBeGreaterThan(180)
+ expect(await canvas.screenshotCanvasRegion(1100, 260)).toMatchSnapshot(
+ `frame-title-colors-${name}.png`
+ )
+}
+
+test('frame names on a dark page read on white and dark sections', async () => {
+ await expectReadableNames('dark', 30)
+})
+
+test('frame names on a light page read on white and dark sections', async () => {
+ await expectReadableNames('light', 245)
+})
+
+// Names drawn above a section's top edge sit on the page, and a section's hidden fill does not
+// count, so these stay readable too.
+test('a name above a section sits on the page, and a hidden fill does not count', async () => {
+ await canvas.clearCanvas()
+ await page.evaluate(() => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ store.setPageColor({ r: 30 / 255, g: 30 / 255, b: 30 / 255, a: 1 })
+ const pageId = store.state.currentPageId
+ const solid = (v: number, visible = true) => ({
+ type: 'SOLID' as const,
+ color: { r: v, g: v, b: v, a: 1 },
+ opacity: 1,
+ visible
+ })
+ const edge = store.graph.createNode('SECTION', pageId, {
+ name: 'Edge',
+ x: 0,
+ y: 0,
+ width: 360,
+ height: 260,
+ fills: [solid(1)]
+ })
+ store.graph.createNode('FRAME', edge.id, {
+ name: 'At the top edge',
+ x: 80,
+ y: 0,
+ width: 200,
+ height: 120,
+ fills: [solid(0.9)]
+ })
+ const hidden = store.graph.createNode('SECTION', pageId, {
+ name: 'Hidden first fill',
+ x: 420,
+ y: 0,
+ width: 360,
+ height: 260,
+ fills: [solid(0.1, false), solid(1)]
+ })
+ store.graph.createNode('FRAME', hidden.id, {
+ name: 'Frame inside',
+ x: 80,
+ y: 100,
+ width: 200,
+ height: 120,
+ fills: [solid(0.9)]
+ })
+ store.state.zoom = 1
+ store.state.panX = 40
+ store.state.panY = 60
+ store.clearSelection()
+ store.requestRender()
+ })
+ await page.mouse.move(2, 2)
+ await canvas.waitForRender()
+ // Over the dark page: light text, brighter than the page.
+ expect((await regionRange(118, 40)).brightest).toBeGreaterThan(90)
+ // On the hidden fill's section, whose visible fill is white: dark text.
+ expect((await regionRange(538, 140)).darkest).toBeLessThan(220)
+})
diff --git a/tests/e2e/canvas/labels/frame-title-color.spec.ts-snapshots/frame-title-colors-dark-openpencil-darwin.png b/tests/e2e/canvas/labels/frame-title-color.spec.ts-snapshots/frame-title-colors-dark-openpencil-darwin.png
new file mode 100644
index 000000000..c9c717e63
Binary files /dev/null and b/tests/e2e/canvas/labels/frame-title-color.spec.ts-snapshots/frame-title-colors-dark-openpencil-darwin.png differ
diff --git a/tests/e2e/canvas/labels/frame-title-color.spec.ts-snapshots/frame-title-colors-light-openpencil-darwin.png b/tests/e2e/canvas/labels/frame-title-color.spec.ts-snapshots/frame-title-colors-light-openpencil-darwin.png
new file mode 100644
index 000000000..b4e84d90a
Binary files /dev/null and b/tests/e2e/canvas/labels/frame-title-color.spec.ts-snapshots/frame-title-colors-light-openpencil-darwin.png differ
diff --git a/tests/e2e/canvas/layout-outlines.spec.ts-snapshots/layout-outlines-hovered-card-openpencil-darwin.png b/tests/e2e/canvas/layout-outlines.spec.ts-snapshots/layout-outlines-hovered-card-openpencil-darwin.png
index 1ff930e29..eb8c864ad 100644
Binary files a/tests/e2e/canvas/layout-outlines.spec.ts-snapshots/layout-outlines-hovered-card-openpencil-darwin.png and b/tests/e2e/canvas/layout-outlines.spec.ts-snapshots/layout-outlines-hovered-card-openpencil-darwin.png differ
diff --git a/tests/e2e/canvas/layout-outlines.spec.ts-snapshots/layout-outlines-hovered-plain-openpencil-darwin.png b/tests/e2e/canvas/layout-outlines.spec.ts-snapshots/layout-outlines-hovered-plain-openpencil-darwin.png
index 7a180d3ae..3a547e21a 100644
Binary files a/tests/e2e/canvas/layout-outlines.spec.ts-snapshots/layout-outlines-hovered-plain-openpencil-darwin.png and b/tests/e2e/canvas/layout-outlines.spec.ts-snapshots/layout-outlines-hovered-plain-openpencil-darwin.png differ
diff --git a/tests/e2e/canvas/layout-outlines.spec.ts-snapshots/layout-outlines-hovered-row-openpencil-darwin.png b/tests/e2e/canvas/layout-outlines.spec.ts-snapshots/layout-outlines-hovered-row-openpencil-darwin.png
index 47b555ca6..182b3bd09 100644
Binary files a/tests/e2e/canvas/layout-outlines.spec.ts-snapshots/layout-outlines-hovered-row-openpencil-darwin.png and b/tests/e2e/canvas/layout-outlines.spec.ts-snapshots/layout-outlines-hovered-row-openpencil-darwin.png differ
diff --git a/tests/e2e/canvas/layout-outlines.spec.ts-snapshots/layout-outlines-moving-child-openpencil-darwin.png b/tests/e2e/canvas/layout-outlines.spec.ts-snapshots/layout-outlines-moving-child-openpencil-darwin.png
index 4172b9ab1..d0fbe0fe1 100644
Binary files a/tests/e2e/canvas/layout-outlines.spec.ts-snapshots/layout-outlines-moving-child-openpencil-darwin.png and b/tests/e2e/canvas/layout-outlines.spec.ts-snapshots/layout-outlines-moving-child-openpencil-darwin.png differ
diff --git a/tests/e2e/canvas/layout-outlines.spec.ts-snapshots/layout-outlines-selected-child-openpencil-darwin.png b/tests/e2e/canvas/layout-outlines.spec.ts-snapshots/layout-outlines-selected-child-openpencil-darwin.png
index ff372c373..e99676fc5 100644
Binary files a/tests/e2e/canvas/layout-outlines.spec.ts-snapshots/layout-outlines-selected-child-openpencil-darwin.png and b/tests/e2e/canvas/layout-outlines.spec.ts-snapshots/layout-outlines-selected-child-openpencil-darwin.png differ
diff --git a/tests/e2e/color-picker/history.spec.ts b/tests/e2e/color-picker/history.spec.ts
new file mode 100644
index 000000000..9fa19fce0
--- /dev/null
+++ b/tests/e2e/color-picker/history.spec.ts
@@ -0,0 +1,70 @@
+import { expect, test, type Page } from '@playwright/test'
+
+import { CanvasHelper } from '#tests/helpers/canvas'
+import { fillDriver } from '#tests/helpers/canvas/fill-driver'
+
+// Figma desktop 126 undoes with a colour picker open; other shortcuts still wait for it to close.
+
+let page: Page
+let canvas: CanvasHelper
+
+test.describe.configure({ mode: 'serial' })
+
+test.beforeAll(async ({ browser }) => {
+ page = await browser.newPage()
+ await page.goto('/')
+ canvas = new CanvasHelper(page)
+ await canvas.waitForInit()
+})
+
+test.afterAll(async () => {
+ await page.close()
+})
+
+const fill = fillDriver(() => page)
+const selectedFillColor = () => fill.selectedColor()
+
+async function changeHue() {
+ const slider = page
+ .getByTestId('color-slider-hue')
+ .locator(':scope > [data-orientation="horizontal"]')
+ const box = await slider.boundingBox()
+ if (!box) throw new Error('Missing hue slider')
+ await slider.click({ position: { x: box.width * 0.65, y: box.height / 2 } })
+ await canvas.waitForRender()
+}
+
+async function openPickerOnNewRect() {
+ await canvas.clearCanvas()
+ await canvas.drawRect(100, 100, 160, 120)
+ await canvas.waitForRender()
+ await page.getByTestId('fill-picker-swatch').first().click()
+ await expect(page.getByTestId('fill-picker-tab-solid')).toBeVisible()
+}
+
+test('Cmd+Z undoes a colour change while the picker stays open', async () => {
+ await openPickerOnNewRect()
+
+ const before = await selectedFillColor()
+ await changeHue()
+ expect(await selectedFillColor()).not.toEqual(before)
+
+ // Pressed at once, before the picker's changes settle into one undo step.
+ await page.keyboard.press('ControlOrMeta+z')
+ await expect.poll(selectedFillColor).toEqual(before)
+ await expect(page.getByTestId('fill-picker-tab-solid')).toBeVisible()
+
+ await page.keyboard.press('ControlOrMeta+Shift+z')
+ await expect.poll(selectedFillColor).not.toEqual(before)
+ await expect(page.getByTestId('fill-picker-tab-solid')).toBeVisible()
+ canvas.assertNoErrors()
+})
+
+test('Cmd+Z undoes the first change of a document with no history', async () => {
+ await openPickerOnNewRect()
+ await fill.clearHistory()
+ const before = await selectedFillColor()
+ await changeHue()
+ await page.keyboard.press('ControlOrMeta+z')
+ await expect.poll(selectedFillColor).toEqual(before)
+})
diff --git a/tests/engine/figma/api/layout/plugin-compat.test.ts b/tests/engine/figma/api/layout/plugin-compat.test.ts
index b809c331a..314c77899 100644
--- a/tests/engine/figma/api/layout/plugin-compat.test.ts
+++ b/tests/engine/figma/api/layout/plugin-compat.test.ts
@@ -41,8 +41,8 @@ describe('Figma Plugin API layout compatibility', () => {
const text: FigmaNodeProxy = api.createText()
text.characters = 'Hi'
text.fontSize = 10
- text.letterSpacing = 2
- text.lineHeight = 14
+ text.letterSpacing = { unit: 'PIXELS', value: 2 }
+ text.lineHeight = { unit: 'PIXELS', value: 14 }
frame.appendChild(text)
text.x = 11
text.y = 13
@@ -70,8 +70,8 @@ describe('Figma Plugin API layout compatibility', () => {
expect(text.x).toBe(22)
expect(text.y).toBe(26)
expect(text.fontSize).toBe(20)
- expect(text.letterSpacing).toBe(4)
- expect(text.lineHeight).toBe(28)
+ expect(text.letterSpacing).toEqual({ unit: 'PIXELS', value: 4 })
+ expect(text.lineHeight).toEqual({ unit: 'PIXELS', value: 28 })
expect(graph.getNode(text.id)?.width).toBe(textWidth * 2)
})
diff --git a/tests/helpers/canvas/fill-driver.ts b/tests/helpers/canvas/fill-driver.ts
new file mode 100644
index 000000000..1194a0ba3
--- /dev/null
+++ b/tests/helpers/canvas/fill-driver.ts
@@ -0,0 +1,19 @@
+import type { Page } from '@playwright/test'
+
+/** Reads the selected layer's first fill and resets the editor's undo history. */
+export function fillDriver(page: () => Page) {
+ return {
+ selectedColor() {
+ return page().evaluate(() => {
+ const store = window.openPencil?.getStore?.()
+ const id = store ? [...store.state.selectedIds][0] : undefined
+ return id ? (store?.graph.getNode(id)?.fills[0]?.color ?? null) : null
+ })
+ },
+
+ /** As in a freshly opened document: nothing to undo yet. */
+ clearHistory() {
+ return page().evaluate(() => window.openPencil?.getStore?.().undo.clear())
+ }
+ }
+}