Skip to content

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

fix: clear the selection on Escape and take container bodies by Figma's fill rules (#1697)

Danila Poyarkovb470077c2be7
diff --git a/changes/1697/fixed.md b/changes/1697/fixed.md
new file mode 100644
index 000000000..23bd47db3
--- /dev/null
+++ b/changes/1697/fixed.md
@@ -0,0 +1 @@
+- Escape clears the selection at any depth and Enter keeps layers without children selected, as in Figma; a click takes the empty area of a component or instance whatever its fill, while a ⌘-click passes through a frame or instance whose fill does not show (#1697).
diff --git a/packages/core/src/editor/read-only/actions.ts b/packages/core/src/editor/read-only/actions.ts
index d16779554..6c7eb052b 100644
--- a/packages/core/src/editor/read-only/actions.ts
+++ b/packages/core/src/editor/read-only/actions.ts
@@ -58,7 +58,6 @@ export const READ_ONLY_ACTIONS: ReadonlySet<string> = new Set([
'clearSelection',
'enterContainer',
'enterContainerOf',
- 'exitContainer',
'exitContainers',
'select',
'selectAll',
diff --git a/packages/core/src/editor/selection/container.ts b/packages/core/src/editor/selection/container.ts
index 2675fcc53..6c8eeec0f 100644
--- a/packages/core/src/editor/selection/container.ts
+++ b/packages/core/src/editor/selection/container.ts
@@ -27,19 +27,6 @@ export function createSelectionContainerActions(ctx: EditorContext) {
ctx.state.enteredContainerId = entered ? parentId : null
}
- function exitContainer() {
- const entered = ctx.state.enteredContainerId
- if (!entered) return
- const node = ctx.graph.getNode(entered)
- const parentId = node?.parentId
- if (parentId && parentId !== ctx.state.currentPageId) {
- ctx.state.enteredContainerId = parentId
- } else {
- ctx.state.enteredContainerId = null
- }
- ctx.setSelectedIds(new Set(entered ? [entered] : []))
- }
-
/** Leaves every entered container; a press on nothing lands on the page, as in Figma. */
function exitContainers() {
ctx.state.enteredContainerId = null
@@ -49,7 +36,6 @@ export function createSelectionContainerActions(ctx: EditorContext) {
validateEnteredContainer,
enterContainer,
enterContainerOf,
- exitContainer,
exitContainers
}
}
diff --git a/packages/core/src/editor/selection/navigation.ts b/packages/core/src/editor/selection/navigation.ts
index 5dab2833c..f859714af 100644
--- a/packages/core/src/editor/selection/navigation.ts
+++ b/packages/core/src/editor/selection/navigation.ts
@@ -14,14 +14,16 @@ export function createSelectionNavigationActions(ctx: EditorContext, select: Sel
}
/**
- * Selects the children of every selected layer that has any; a selection without any stays.
- * A generated frame, such as a sticky note, has none to offer: its template owns its layers.
+ * Replaces each selected layer that has children with its children, as Figma's Enter does, and
+ * keeps the others selected; a selection where none has children stays. A generated frame, such
+ * as a sticky note, has none to offer: its template owns its layers.
*/
function selectChildren() {
- const children = selectedNodes().flatMap((node) =>
- isGeneratedFrame(node) ? [] : node.childIds
- )
- if (children.length > 0) select(children)
+ const nodes = selectedNodes()
+ const opens = (node: (typeof nodes)[number]) =>
+ !isGeneratedFrame(node) && node.childIds.length > 0
+ if (!nodes.some(opens)) return
+ select(nodes.flatMap((node) => (opens(node) ? node.childIds : [node.id])))
}
/** Selects the parents of the selected layers; layers directly on the page stay selected. */
diff --git a/packages/core/tests/editor/selection/navigation.test.ts b/packages/core/tests/editor/selection/navigation.test.ts
index 674e701ce..ed24822e9 100644
--- a/packages/core/tests/editor/selection/navigation.test.ts
+++ b/packages/core/tests/editor/selection/navigation.test.ts
@@ -34,6 +34,19 @@ describe('keyboard layer navigation', () => {
expect(editor.state.selectedIds).toEqual(new Set([middle.id]))
})
+ // Measured in Figma 126 (scratch/pr-oracle/nav-keys.ts): Enter on a frame's children selects a
+ // group's children in the group's place and keeps the layers without children.
+ test('selectChildren opens the layers that have children and keeps the others', () => {
+ const { editor, frame, bottom, top } = layerTree()
+ const group = editor.graph.createNode('GROUP', frame.id, { name: 'Group' })
+ const inside = editor.graph.createNode('RECTANGLE', group.id, { name: 'Inside' })
+ editor.select([bottom.id, group.id, top.id])
+
+ editor.selectChildren()
+
+ expect(editor.state.selectedIds).toEqual(new Set([bottom.id, inside.id, top.id]))
+ })
+
test('selectParent selects the parent and stops at the page', () => {
const { editor, frame, middle } = layerTree()
editor.select([middle.id])
diff --git a/packages/scene-graph/src/hit-test.ts b/packages/scene-graph/src/hit-test.ts
index 3d6950f1f..ac726084c 100644
--- a/packages/scene-graph/src/hit-test.ts
+++ b/packages/scene-graph/src/hit-test.ts
@@ -2,7 +2,7 @@ import { hitsConnectorLine } from './connectors/hit'
import { getWorldMatrix } from './coordinate'
import type { SceneGraph } from './graph'
import Matrix from './matrix'
-import { hitsShape, strokeReach } from './outline/hit'
+import { hitsShape, isHitPaint, strokeReach } from './outline/hit'
import type { SceneNode, NodeType } from './types'
const CONTAINER_TYPES = new Set<NodeType>([
@@ -16,8 +16,9 @@ const CONTAINER_TYPES = new Set<NodeType>([
])
const OPAQUE_CONTAINER_TYPES = new Set<NodeType>(['COMPONENT', 'INSTANCE'])
-function hasVisibleFillOrStroke(node: SceneNode): boolean {
- return node.fills.some((f) => f.visible) || node.strokes.some((s) => s.visible)
+/** Whether a container's own paints show, so its empty area is drawn (see `isHitPaint`). */
+function showsPaint(node: SceneNode): boolean {
+ return node.fills.some(isHitPaint) || node.strokes.some(isHitPaint)
}
function isTopLevel(graph: SceneGraph, node: SceneNode): boolean {
@@ -82,96 +83,88 @@ function containsPoint(
)
}
-function hitTestOpaqueContainer(
- graph: SceneGraph,
- px: number,
- py: number,
- child: SceneNode,
- childId: string,
- deep: boolean,
- transformCache: Map<string, boolean>,
+/**
+ * How a walk down the layers takes a click. `deep` reaches past containers to the deepest layer;
+ * `pad`, in canvas units, grows each leaf layer's box, as Figma takes a click a few screen pixels
+ * outside a shape; `instanceBodies` lets a deep walk take an instance's empty area whatever its
+ * fill, as a plain click does, where a ⌘-click counts only a fill that shows.
+ */
+interface HitWalk {
+ deep: boolean
pad: number
-): SceneNode | null {
- if (!containsPoint(px, py, child, graph, transformCache)) return null
- const childHit = hitTestChildren(graph, px, py, childId, deep, transformCache, pad)
- if (childHit) return child
- if (hasVisibleFillOrStroke(child)) return child
- return null
+ instanceBodies: boolean
+ transformCache: Map<string, boolean>
+}
+
+function walkOf(deep: boolean, pad = 0, instanceBodies = false): HitWalk {
+ return { deep, pad, instanceBodies, transformCache: new Map() }
}
+
+/** Whether a container's empty area under the point takes a click reaching past containers. */
+function takesEmptyArea(graph: SceneGraph, node: SceneNode, walk: HitWalk): boolean {
+ // Figma counts an empty area only where a paint shows, except a main component's, which always
+ // counts, and an instance's when the click is a plain one.
+ if (node.type === 'COMPONENT' || showsPaint(node) || ownsItsEmptyArea(graph, node)) return true
+ return walk.instanceBodies && node.type === 'INSTANCE'
+}
+
function hitTestTransparentContainer(
graph: SceneGraph,
px: number,
py: number,
child: SceneNode,
- childId: string,
- deep: boolean,
- transformCache: Map<string, boolean>,
- pad: number
+ walk: HitWalk
): SceneNode | null {
if (child.type === 'GROUP') {
// A group fits its layers, so a padded click on one at its edge falls just outside it.
- if (!containsPoint(px, py, child, graph, transformCache, pad)) return null
+ if (!containsPoint(px, py, child, graph, walk.transformCache, walk.pad)) return null
// A group has no area of its own, as in Figma: between its layers the click falls through to
// whatever lies under the group.
- const childHit = hitTestChildren(graph, px, py, childId, deep, transformCache, pad)
- return childHit ? (deep ? childHit : child) : null
+ const childHit = hitTestChildren(graph, px, py, child.id, walk)
+ return childHit ? (walk.deep ? childHit : child) : null
}
- const childHit = hitTestChildren(graph, px, py, childId, deep, transformCache, pad)
+ const childHit = hitTestChildren(graph, px, py, child.id, walk)
if (childHit) {
if (child.locked) return child
return childHit
}
if (
- containsPoint(px, py, child, graph, transformCache) &&
- (hasVisibleFillOrStroke(child) || ownsItsEmptyArea(graph, child))
+ containsPoint(px, py, child, graph, walk.transformCache) &&
+ takesEmptyArea(graph, child, walk)
)
return child
return null
}
-/**
- * The topmost layer under the point among a container's children. `pad`, in canvas units, grows
- * each leaf layer's box, as Figma takes a click a few screen pixels outside a shape.
- */
+/** The topmost layer under the point among a container's children. */
function hitTestChildren(
graph: SceneGraph,
px: number,
py: number,
parentId: string,
- deep = false,
- transformCache = new Map<string, boolean>(),
- pad = 0
+ walk: HitWalk
): SceneNode | null {
const parent = graph.nodes.get(parentId)
if (!parent) return null
+ const { transformCache, pad } = walk
if (parent.clipsContent) {
if (!containsPoint(px, py, parent, graph, transformCache)) return null
}
for (let i = parent.childIds.length - 1; i >= 0; i--) {
- const childId = parent.childIds[i]
- const child = graph.nodes.get(childId)
+ const child = graph.nodes.get(parent.childIds[i])
if (!child || child.internalOnly || !child.visible) continue
if (CONTAINER_TYPES.has(child.type)) {
- if (OPAQUE_CONTAINER_TYPES.has(child.type) && !deep) {
- const hit = hitTestOpaqueContainer(graph, px, py, child, childId, deep, transformCache, pad)
- if (hit) return hit
+ if (OPAQUE_CONTAINER_TYPES.has(child.type) && !walk.deep) {
+ // A plain click takes an instance or component anywhere in its box, with a fill or
+ // without, as in Figma.
+ if (containsPoint(px, py, child, graph, transformCache)) return child
continue
}
-
- const hit = hitTestTransparentContainer(
- graph,
- px,
- py,
- child,
- childId,
- deep,
- transformCache,
- pad
- )
+ const hit = hitTestTransparentContainer(graph, px, py, child, walk)
if (hit) return hit
continue
}
@@ -211,7 +204,7 @@ export function hitTest(
scopeId?: string
): SceneNode | null {
const scope = scopeId ?? graph.rootId
- return hitTestChildren(graph, px, py, scope, false)
+ return hitTestChildren(graph, px, py, scope, walkOf(false))
}
export function hitTestDeep(
@@ -222,7 +215,7 @@ export function hitTestDeep(
pad = 0
): SceneNode | null {
const scope = scopeId ?? graph.rootId
- return hitTestChildren(graph, px, py, scope, true, new Map(), pad)
+ return hitTestChildren(graph, px, py, scope, walkOf(true, pad))
}
/**
@@ -327,7 +320,8 @@ export function hitTestSelectable(
options: SelectableHitOptions = {}
): SceneNode | null {
const { pad = 0, framesOpen = true, enteredId = null } = options
- const deepest = hitTestChildren(graph, px, py, scopeId, true, new Map(), pad)
+ // A plain click: the walk takes an instance's empty area whatever its fill.
+ const deepest = hitTestChildren(graph, px, py, scopeId, walkOf(true, pad, true))
if (!deepest) {
const scope = graph.nodes.get(scopeId)
return scope ? frameChildAt(graph, scope, px, py, framesOpen) : null
@@ -370,7 +364,7 @@ export function hitTestOpenContainer(
py: number,
scopeId: string
): SceneNode | null {
- const deepest = hitTestChildren(graph, px, py, scopeId, true)
+ const deepest = hitTestChildren(graph, px, py, scopeId, walkOf(true))
for (let node: SceneNode | undefined = deepest ?? undefined; node && node.id !== scopeId;) {
if (!opensByItself(graph, node) || ownsItsEmptyArea(graph, node)) return null
node = node.parentId ? graph.nodes.get(node.parentId) : undefined
diff --git a/packages/scene-graph/tests/basic/hit-test.test.ts b/packages/scene-graph/tests/basic/hit-test.test.ts
index 61232e410..56a9f3794 100644
--- a/packages/scene-graph/tests/basic/hit-test.test.ts
+++ b/packages/scene-graph/tests/basic/hit-test.test.ts
@@ -100,7 +100,7 @@ describe('hitTest', () => {
expect(graph.hitTest(150, 150, pageId(graph))).toBeNull()
})
- test('instance without fills is click-through in empty area', () => {
+ test('instance and component bodies take clicks whatever their fill', () => {
const graph = new SceneGraph()
const compId = graph.createNode('COMPONENT', pageId(graph), {
name: 'Comp',
@@ -124,8 +124,12 @@ describe('hitTest', () => {
).id
// Hit on instance's child area — returns instance (opaque container)
expect(graph.hitTest(320, 20, pageId(graph))?.id).toBe(instId)
- // Miss on instance's empty area (no fills)
- expect(graph.hitTest(450, 150, pageId(graph))).toBeNull()
+ // A plain click takes its empty area too, with no fill, as in Figma.
+ expect(graph.hitTest(450, 150, pageId(graph))?.id).toBe(instId)
+ // Reaching past containers, its empty area shows no paint and is passed through.
+ expect(graph.hitTestDeep(450, 150, pageId(graph))).toBeNull()
+ // A main component's empty area always counts.
+ expect(graph.hitTestDeep(150, 150, pageId(graph))?.id).toBe(compId)
})
test('hidden node is not hittable', () => {
@@ -178,6 +182,29 @@ describe('hitTest', () => {
})
})
+describe('reaching past containers', () => {
+ test('a nested frame whose fill is at 0% passes the click to its parent', () => {
+ const graph = new SceneGraph()
+ const top = graph.createNode('FRAME', pageId(graph), {
+ name: 'Top',
+ width: 300,
+ height: 300,
+ fills: [SOLID_FILL]
+ })
+ const nested = graph.createNode('FRAME', top.id, {
+ name: 'Nested',
+ x: 20,
+ y: 20,
+ width: 200,
+ height: 200,
+ fills: [{ ...SOLID_FILL, opacity: 0 }]
+ })
+ expect(graph.hitTestDeep(150, 150, pageId(graph))?.id).toBe(top.id)
+ graph.updateNode(nested.id, { fills: [{ ...SOLID_FILL, opacity: 0.01 }] })
+ expect(graph.hitTestDeep(150, 150, pageId(graph))?.id).toBe(nested.id)
+ })
+})
+
describe('hitTest on drawn shapes', () => {
test('a click inside an unfilled line reaches the layer under it', () => {
const graph = new SceneGraph()
diff --git a/src/app/shell/keyboard/actions.ts b/src/app/shell/keyboard/actions.ts
index 44da22bd3..2ada5f7d1 100644
--- a/src/app/shell/keyboard/actions.ts
+++ b/src/app/shell/keyboard/actions.ts
@@ -91,11 +91,9 @@ export function createKeyboardActions({
else store.penCancel()
return
}
- if (store.state.enteredContainerId) {
- store.exitContainer()
- return
- }
if (useComments().closeCard()) return
+ // Figma's Escape clears the selection at any depth; Shift+Enter is the way up a level.
+ store.exitContainers()
store.clearSelection()
store.setTool('SELECT')
}
diff --git a/tests/e2e/canvas/selection-keys.spec.ts b/tests/e2e/canvas/selection-keys.spec.ts
new file mode 100644
index 000000000..c16869242
--- /dev/null
+++ b/tests/e2e/canvas/selection-keys.spec.ts
@@ -0,0 +1,37 @@
+import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'
+import { clickDepthDriver } from '#tests/helpers/canvas/click-depth/driver'
+
+// Measured in Figma desktop 126 (scratch/pr-oracle/nav-keys.ts): Escape clears the selection at
+// any depth, and Shift+Enter is the way up a level.
+
+const editor = useEditorSetupWithClear('/?test&no-chrome&no-rulers')
+
+const scene = clickDepthDriver(() => editor.page)
+
+test('Escape inside an entered container clears the selection', async () => {
+ const { grid, cell, label } = await scene.nestedBoard()
+ await editor.canvas.waitForRender()
+ const point = await scene.at(label, 20, 20)
+
+ await editor.canvas.click(point.x, point.y)
+ await expect.poll(async () => (await scene.state()).selected).toEqual([grid])
+ await editor.canvas.dblclick(point.x, point.y)
+ await expect.poll(async () => (await scene.state()).selected).toEqual([cell])
+ expect((await scene.state()).entered).toBe(grid)
+
+ await editor.page.keyboard.press('Escape')
+ await expect.poll(async () => (await scene.state()).selected).toEqual([])
+ expect((await scene.state()).entered).toBeNull()
+ editor.canvas.assertNoErrors()
+})
+
+test('Shift+Enter after a click on a nested layer selects its parent', async () => {
+ const { plain } = await scene.cards()
+ await editor.canvas.waitForRender()
+ const button = await scene.at(plain, 100, 108)
+
+ await editor.canvas.click(button.x, button.y)
+ await editor.page.keyboard.press('Shift+Enter')
+ await expect.poll(async () => (await scene.state()).selected).toEqual([plain])
+ editor.canvas.assertNoErrors()
+})
diff --git a/tests/helpers/canvas/click-depth/driver.ts b/tests/helpers/canvas/click-depth/driver.ts
index fa4380be5..1c509eb1d 100644
--- a/tests/helpers/canvas/click-depth/driver.ts
+++ b/tests/helpers/canvas/click-depth/driver.ts
@@ -55,7 +55,11 @@ export function clickDepthDriver(page: () => Page) {
return page().evaluate(() => {
const store = window.openPencil?.getStore?.()
if (!store) throw new Error('OpenPencil store not initialized')
- return { selected: [...store.state.selectedIds], hovered: store.state.hoveredNodeId }
+ return {
+ selected: [...store.state.selectedIds],
+ hovered: store.state.hoveredNodeId,
+ entered: store.state.enteredContainerId
+ }
})
},