Skip to content

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

fix: lay out loaded text live and select nested layers as in Figma (#1664)

Danila Poyarkov9343a6781f26
diff --git a/changes/1664/fixed.md b/changes/1664/fixed.md
new file mode 100644
index 000000000..f316a1dd9
--- /dev/null
+++ b/changes/1664/fixed.md
@@ -0,0 +1,6 @@
+- Editing text that keeps Figma's saved glyphs draws it from the live layout while it is edited, so the caret and selection land where you click even when the loaded font is a different build than the file's; the saved glyphs return when the edit ends (#1664).
+- A single click inside a selected frame or group keeps it selected, each double-click goes one level down through frames and groups, and a nested text is selected first and edited by the next double-click, as in Figma; a top-level frame or section stays open while selected (#1664).
+- A group's empty area no longer takes clicks: a layer under a group, such as a chart line beneath its grouped dots, is selected through the gaps between the group's layers, as in Figma (#1664).
+- A quick run of clicks goes one level deeper on each click after the first, as in Figma, so a nested chart title is reached by clicking it a few times; a run that lands on a text selects it, and a double-click then edits it (#1664).
+- Entering an edit by double-click selects all of the text, and clicking another text while editing puts the caret where you clicked, as in Figma (#1664).
+- After reaching a nested layer by double-clicks, a click on a layer elsewhere selects what a click from nothing would, such as another row of swatches in the shadcn kit, instead of climbing out one container per click; a click on the page or a section's empty area with a selection deselects, as in Figma (#1664).
diff --git a/packages/core/src/canvas/renderer.ts b/packages/core/src/canvas/renderer.ts
index a8ea42bf6..111e1f889 100644
--- a/packages/core/src/canvas/renderer.ts
+++ b/packages/core/src/canvas/renderer.ts
@@ -207,6 +207,11 @@ export class SkiaRenderer {
* null for a canvas that draws only the document, such as an export.
*/
stickyPlaceholder: string | null = null
+ /**
+ * The text being edited on this canvas, drawn from the live layout its caret and selection
+ * come from rather than from its saved glyphs, which another font build may have shaped.
+ */
+ editingTextId: string | null = null
/** What an empty connector label shows while it is typed into; null draws nothing. */
connectorLabelPlaceholder: string | null = null
/** The marked layers staged in world space, placed anew each frame. */
@@ -413,10 +418,7 @@ export class SkiaRenderer {
flushDecodedPreviews(graph: SceneGraph): void {
if (this.images.decodedPreviewHashes.size === 0) return
for (const hash of this.images.decodedPreviewHashes) {
- for (const nodeId of this.images.fillUsers.get(hash) ?? []) {
- this.invalidateNodePicture(nodeId)
- this.tiledScene.invalidateNode(nodeId, graph)
- }
+ for (const nodeId of this.images.fillUsers.get(hash) ?? []) this.redrawNode(nodeId, graph)
}
this.images.decodedPreviewHashes.clear()
}
@@ -432,8 +434,7 @@ export class SkiaRenderer {
const node = graph.getNode(id)
if (!node) continue
if (node.type === 'TEXT') {
- this.invalidateNodePicture(id)
- this.tiledScene.invalidateNode(id, graph)
+ this.redrawNode(id, graph)
this.invalidateBooleanAncestors(graph, node)
}
pending.push(...node.childIds)
@@ -451,8 +452,7 @@ export class SkiaRenderer {
seen.add(parent.id)
if (parent.type === 'BOOLEAN_OPERATION') {
this.invalidateVectorPath(parent.id)
- this.invalidateNodePicture(parent.id)
- this.tiledScene.invalidateNode(parent.id, graph)
+ this.redrawNode(parent.id, graph)
}
parent = parent.parentId ? graph.getNode(parent.parentId) : undefined
}
@@ -488,10 +488,7 @@ export class SkiaRenderer {
const image = source && this.surface.makeImageFromTextureSource(textureSource(source))
if (image) this.images.live.set(hash, { image, surface: this.surface })
}
- for (const id of nodeIds) {
- this.invalidateNodePicture(id)
- this.tiledScene.invalidateNode(id)
- }
+ for (const id of nodeIds) this.redrawNode(id)
return this.images.live.has(hash)
}
@@ -519,6 +516,12 @@ export class SkiaRenderer {
RendererState.invalidateNodePicture(this, nodeId, changedKeys)
}
+ /** Draws `nodeId` afresh next frame: its picture and the tiles that hold it are dropped. */
+ redrawNode(nodeId: string, graph?: SceneGraph): void {
+ this.invalidateNodePicture(nodeId)
+ this.tiledScene.invalidateNode(nodeId, graph)
+ }
+
flashNode(nodeId: string): void {
RendererState.flashNode(this, nodeId)
}
diff --git a/packages/core/src/canvas/renderer/pipeline.ts b/packages/core/src/canvas/renderer/pipeline.ts
index 6062b6eb9..0ba282e70 100644
--- a/packages/core/src/canvas/renderer/pipeline.ts
+++ b/packages/core/src/canvas/renderer/pipeline.ts
@@ -16,7 +16,15 @@ import { drawChromePass, drawLabelPass, drawOverlayPass } from './overlay-pass'
import { hasTransientPreviews, renderPageWithPreviews } from './transient-previews'
export function renderSceneToCanvas(
- r: Pick<SkiaRenderer, 'worldViewport' | 'viewportImageRendering' | 'renderNode' | 'nodePaths'>,
+ r: Pick<
+ SkiaRenderer,
+ | 'worldViewport'
+ | 'viewportImageRendering'
+ | 'renderNode'
+ | 'nodePaths'
+ | 'editingTextId'
+ | 'invalidateNodePicture'
+ >,
canvas: Canvas,
graph: SceneGraph,
pageId: string
@@ -24,7 +32,12 @@ export function renderSceneToCanvas(
r.nodePaths.releaseUncached()
const prevViewport = r.worldViewport
const previewMode = r.viewportImageRendering
+ const editing = r.editingTextId
r.viewportImageRendering = false
+ // An export or thumbnail shows the document, saved glyphs included, whatever is being edited;
+ // the edited text's picture is of its live layout, so it is dropped on the way in and out.
+ r.editingTextId = null
+ if (editing) r.invalidateNodePicture(editing)
r.worldViewport = { x: -1e9, y: -1e9, w: 2e9, h: 2e9 }
try {
const pageNode = graph.getNode(pageId)
@@ -34,6 +47,8 @@ export function renderSceneToCanvas(
} finally {
r.worldViewport = prevViewport
r.viewportImageRendering = previewMode
+ r.editingTextId = editing
+ if (editing) r.invalidateNodePicture(editing)
}
}
@@ -246,6 +261,7 @@ export function render(
layer: RenderLayer = 'full',
interactive = false
): void {
+ r.editingTextId = overlays.editingTextId ?? null
emitNavigationTrace('render:start', {
layer,
sceneVersion,
diff --git a/packages/core/src/canvas/text/render.ts b/packages/core/src/canvas/text/render.ts
index 3e97bc4cb..c6ae03fa8 100644
--- a/packages/core/src/canvas/text/render.ts
+++ b/packages/core/src/canvas/text/render.ts
@@ -62,7 +62,9 @@ function drawResolvedPathText(
function drawsLaidOutText(r: SkiaRenderer, node: SceneNode): boolean {
if (!r.fontsLoaded || !r.fontProvider || node.textPathData !== null) return false
const readiness = r.nodeFontReadiness(node)
- return readiness !== 'pending' && readiness !== 'exhausted' && mayHoldEmoji(shownText(node))
+ // Edited text draws its paragraph even after its fonts gave up, so its emoji draw over it too.
+ const laidOut = readiness !== 'pending' && (readiness !== 'exhausted' || !drawsSaved(r, node))
+ return laidOut && mayHoldEmoji(shownText(node))
}
/**
@@ -70,7 +72,7 @@ function drawsLaidOutText(r: SkiaRenderer, node: SceneNode): boolean {
* over the blank squares the editor's layout gives them.
*/
export function drawTextEmoji(r: SkiaRenderer, canvas: Canvas, node: SceneNode): void {
- const saved = drawsSavedText(node)
+ const saved = drawsSaved(r, node) && drawsSavedText(node)
if (!saved && !drawsLaidOutText(r, node)) return
canvas.save()
if (saved) drawSavedEmoji(r, canvas, node)
@@ -86,8 +88,24 @@ export function drawTextEmoji(r: SkiaRenderer, canvas: Canvas, node: SceneNode):
canvas.restore()
}
+/**
+ * Whether the text draws from its saved glyphs. Text whose fonts are all loaded lays out live, as
+ * Figma lays text out with its own fonts, so an edit changes nothing but the characters; saved
+ * glyphs stand in for a missing or substituted font and keep path text on its path. Not while the
+ * text is edited either: the caret, selection, and hit testing follow the live layout.
+ */
+function drawsSaved(r: SkiaRenderer, node: SceneNode): boolean {
+ const readiness = r.nodeFontReadiness(node)
+ // Fonts still loading leave nothing else to draw, edited or not.
+ if (readiness === 'pending') return true
+ if (r.editingTextId === node.id) return false
+ return node.textPathData !== null || readiness !== 'ready'
+}
+
function drawSavedText(r: SkiaRenderer, canvas: Canvas, node: SceneNode, fill?: Fill): boolean {
- return canDrawSavedText(node, fill) && drawDerivedText(r, canvas, node, fill)
+ return (
+ drawsSaved(r, node) && canDrawSavedText(node, fill) && drawDerivedText(r, canvas, node, fill)
+ )
}
export function renderText(r: SkiaRenderer, canvas: Canvas, node: SceneNode, fill?: Fill): void {
@@ -109,7 +127,7 @@ export function renderText(r: SkiaRenderer, canvas: Canvas, node: SceneNode, fil
canvas.restore()
return
}
- if (fontReadiness === 'exhausted') {
+ if (fontReadiness === 'exhausted' && drawsSaved(r, node)) {
if (node.textPicture && r.isTextPictureCurrent(node)) {
const pic = r.ck.MakePicture(node.textPicture)
if (pic) {
diff --git a/packages/core/src/editor/read-only/actions.ts b/packages/core/src/editor/read-only/actions.ts
index 8a472487e..d16779554 100644
--- a/packages/core/src/editor/read-only/actions.ts
+++ b/packages/core/src/editor/read-only/actions.ts
@@ -57,7 +57,9 @@ export const READ_ONLY_ACTIONS: ReadonlySet<string> = new Set([
// Selection and hover
'clearSelection',
'enterContainer',
+ 'enterContainerOf',
'exitContainer',
+ 'exitContainers',
'select',
'selectAll',
'selectAtPoint',
diff --git a/packages/core/src/editor/selection.ts b/packages/core/src/editor/selection.ts
index 5904ec573..533cb056b 100644
--- a/packages/core/src/editor/selection.ts
+++ b/packages/core/src/editor/selection.ts
@@ -68,7 +68,12 @@ export function createSelectionActions(ctx: EditorContext) {
}
const containerActions = createSelectionContainerActions(ctx)
- const hitTestActions = createSelectionHitTestActions(ctx, select, clearSelection)
+ const hitTestActions = createSelectionHitTestActions(
+ ctx,
+ select,
+ clearSelection,
+ containerActions.enterContainerOf
+ )
const navigationActions = createSelectionNavigationActions(ctx, select)
const overlayActions = createSelectionOverlayActions(ctx)
const readActions = createSelectionReadActions(ctx)
diff --git a/packages/core/src/editor/selection/container.ts b/packages/core/src/editor/selection/container.ts
index 1dceafd64..2675fcc53 100644
--- a/packages/core/src/editor/selection/container.ts
+++ b/packages/core/src/editor/selection/container.ts
@@ -1,4 +1,5 @@
import type { EditorContext } from '#core/editor/types'
+import { resolveEditorProfile } from '#core/editor/views'
export function createSelectionContainerActions(ctx: EditorContext) {
function validateEnteredContainer() {
@@ -11,6 +12,21 @@ export function createSelectionContainerActions(ctx: EditorContext) {
ctx.state.enteredContainerId = id
}
+ /**
+ * Enters the container a click reached the layer through, as a double-click would have: its
+ * parent, unless that is the page or a container a click looks into by itself (a top-level
+ * frame in a design, a section, a component set), which is never entered.
+ */
+ function enterContainerOf(nodeId: string) {
+ const parentId = ctx.graph.getNode(nodeId)?.parentId ?? null
+ const { framesOpen } = resolveEditorProfile(ctx.state)
+ const entered =
+ parentId &&
+ parentId !== ctx.state.currentPageId &&
+ !ctx.graph.isOpenContainer(parentId, framesOpen)
+ ctx.state.enteredContainerId = entered ? parentId : null
+ }
+
function exitContainer() {
const entered = ctx.state.enteredContainerId
if (!entered) return
@@ -24,5 +40,16 @@ export function createSelectionContainerActions(ctx: EditorContext) {
ctx.setSelectedIds(new Set(entered ? [entered] : []))
}
- return { validateEnteredContainer, enterContainer, exitContainer }
+ /** Leaves every entered container; a press on nothing lands on the page, as in Figma. */
+ function exitContainers() {
+ ctx.state.enteredContainerId = null
+ }
+
+ return {
+ validateEnteredContainer,
+ enterContainer,
+ enterContainerOf,
+ exitContainer,
+ exitContainers
+ }
}
diff --git a/packages/core/src/editor/selection/hit-test.ts b/packages/core/src/editor/selection/hit-test.ts
index aad557c78..5b47a860e 100644
--- a/packages/core/src/editor/selection/hit-test.ts
+++ b/packages/core/src/editor/selection/hit-test.ts
@@ -7,36 +7,43 @@ import { resolveEditorProfile } from '#core/editor/views'
export function createSelectionHitTestActions(
ctx: EditorContext,
select: (ids: string[], additive?: boolean) => void,
- clearSelection: () => void
+ clearSelection: () => void,
+ enterContainerOf: (nodeId: string) => void
) {
+ /**
+ * The layer a click selects, found from the page: the selection and the entered container open
+ * their ancestors, so an entered container never limits where a click lands, as in Figma.
+ */
function hitTestAtPoint(cx: number, cy: number, deep = false): SceneNode | null {
const renderer = ctx.getRenderer()
if (!renderer) return null
const pad = LAYER_HIT_PAD / ctx.state.zoom
- const scopeId = ctx.state.enteredContainerId
- if (scopeId && !ctx.graph.getNode(scopeId)) ctx.state.enteredContainerId = null
- const scope = ctx.state.enteredContainerId ?? ctx.state.currentPageId
+ const scope = ctx.state.currentPageId
+ if (ctx.state.enteredContainerId && !ctx.graph.getNode(ctx.state.enteredContainerId)) {
+ ctx.state.enteredContainerId = null
+ }
return deep
? ctx.graph.hitTestDeep(cx, cy, scope, pad)
- : ctx.graph.hitTestSelectable(
- cx,
- cy,
- scope,
- ctx.state.selectedIds,
+ : ctx.graph.hitTestSelectable(cx, cy, scope, ctx.state.selectedIds, {
pad,
- resolveEditorProfile(ctx.state).framesOpen
- )
+ framesOpen: resolveEditorProfile(ctx.state).framesOpen,
+ enteredId: ctx.state.enteredContainerId
+ })
}
/**
* Selects what a right-click is over, as Figma does: the layer a click would select, or else the
- * frame or section whose empty area is under the point, which a click leaves for a marquee.
+ * frame or section whose empty area is under the point, which a click leaves for a marquee. The
+ * entered container follows the selection, as it does after a press.
*/
function selectAtPoint(cx: number, cy: number) {
- const scopeId = ctx.state.enteredContainerId ?? ctx.state.currentPageId
- const hit = hitTestAtPoint(cx, cy) ?? ctx.graph.hitTestOpenContainer(cx, cy, scopeId)
+ const hit =
+ hitTestAtPoint(cx, cy) ?? ctx.graph.hitTestOpenContainer(cx, cy, ctx.state.currentPageId)
if (hit) {
- if (!ctx.state.selectedIds.has(hit.id)) select([hit.id])
+ if (!ctx.state.selectedIds.has(hit.id)) {
+ select([hit.id])
+ enterContainerOf(hit.id)
+ }
} else {
clearSelection()
}
diff --git a/packages/core/src/editor/text.ts b/packages/core/src/editor/text.ts
index 7fdb30827..5973ee41c 100644
--- a/packages/core/src/editor/text.ts
+++ b/packages/core/src/editor/text.ts
@@ -130,6 +130,11 @@ export function createTextActions(ctx: EditorContext) {
if (node.width !== width || node.height !== height) ctx.runLayoutForNode(nodeId)
}
+ /** A text draws from its live layout while edited, so it is drawn afresh as the edit starts and ends. */
+ function redrawText(nodeId: string) {
+ for (const renderer of ctx.getRenderers()) renderer.redrawNode(nodeId, ctx.graph)
+ }
+
function startTextEditing(nodeId: string) {
const te = ctx.getTextEditor()
if (ctx.state.editingTextId) commitTextEdit()
@@ -139,6 +144,7 @@ export function createTextActions(ctx: EditorContext) {
if (!isPathTextEditable(node)) return
activeSession = createTextEditSession(node)
ctx.state.editingTextId = nodeId
+ redrawText(nodeId)
restoreEmptyLabel = fitEmptyLabelToPlaceholder(ctx, node)
if (te) {
te.setRenderer(ctx.getRenderer())
@@ -224,11 +230,16 @@ export function createTextActions(ctx: EditorContext) {
function commitTextEdit() {
const te = ctx.getTextEditor()
const restore = restoreEmptyLabel
+ const edited = ctx.state.editingTextId
restoreEmptyLabel = null
if (!te?.isActive) {
ctx.state.editingTextId = null
activeSession = null
restore?.()
+ if (edited) {
+ redrawText(edited)
+ ctx.requestRender()
+ }
return
}
const textState = te.state
@@ -237,6 +248,7 @@ export function createTextActions(ctx: EditorContext) {
ctx.state.editingTextId = null
activeSession = null
restore?.()
+ if (edited) redrawText(edited)
ctx.requestRender()
}
diff --git a/packages/core/tests/editor/selection/container.test.ts b/packages/core/tests/editor/selection/container.test.ts
new file mode 100644
index 000000000..2c824397a
--- /dev/null
+++ b/packages/core/tests/editor/selection/container.test.ts
@@ -0,0 +1,70 @@
+import { afterEach, describe, expect, test } from 'bun:test'
+
+import { createEditor, type Editor } from '@open-pencil/core'
+
+let editor: Editor
+
+afterEach(() => editor.dispose())
+
+/** A section holding a top-level auto layout frame of rows of cards, as the shadcn kit lays swatches out. */
+function swatchRows() {
+ editor = createEditor()
+ const pageId = editor.state.currentPageId
+ const section = editor.graph.createNode('SECTION', pageId, { width: 800, height: 300 })
+ const rows = editor.graph.createNode('FRAME', section.id, {
+ x: 40,
+ y: 40,
+ width: 700,
+ height: 200,
+ layoutMode: 'VERTICAL',
+ fills: []
+ })
+ const row = editor.graph.createNode('FRAME', rows.id, {
+ width: 700,
+ height: 80,
+ layoutMode: 'HORIZONTAL',
+ fills: []
+ })
+ const card = editor.graph.createNode('FRAME', row.id, {
+ width: 120,
+ height: 80,
+ layoutMode: 'VERTICAL',
+ fills: []
+ })
+ const swatch = editor.graph.createNode('RECTANGLE', card.id, { width: 120, height: 60 })
+ return { section, rows, row, card, swatch }
+}
+
+describe('enterContainerOf', () => {
+ test('enters the parent of a nested layer, as a double-click reached it', () => {
+ const { card, swatch, row } = swatchRows()
+ editor.enterContainerOf(swatch.id)
+ expect(editor.state.enteredContainerId).toBe(card.id)
+ editor.enterContainerOf(card.id)
+ expect(editor.state.enteredContainerId).toBe(row.id)
+ })
+
+ test('never enters a container a click looks into by itself, nor the page', () => {
+ const { rows, row, section } = swatchRows()
+ editor.enterContainerOf(row.id)
+ expect(editor.state.enteredContainerId).toBeNull()
+ editor.enterContainerOf(rows.id)
+ expect(editor.state.enteredContainerId).toBeNull()
+ editor.enterContainerOf(section.id)
+ expect(editor.state.enteredContainerId).toBeNull()
+ })
+
+ test('enters a top-level frame on a board, where frames stay closed', () => {
+ const { rows, row } = swatchRows()
+ editor.setDocumentKind('board')
+ editor.enterContainerOf(row.id)
+ expect(editor.state.enteredContainerId).toBe(rows.id)
+ })
+
+ test('exitContainers leaves every entered container', () => {
+ const { swatch } = swatchRows()
+ editor.enterContainerOf(swatch.id)
+ editor.exitContainers()
+ expect(editor.state.enteredContainerId).toBeNull()
+ })
+})
diff --git a/packages/core/tests/editor/selection/hit-test.test.ts b/packages/core/tests/editor/selection/hit-test.test.ts
index fd185253c..e54634193 100644
--- a/packages/core/tests/editor/selection/hit-test.test.ts
+++ b/packages/core/tests/editor/selection/hit-test.test.ts
@@ -2,8 +2,8 @@ import { describe, expect, test } from 'bun:test'
import { createEditor } from '@open-pencil/core'
-describe('editor scoped hit testing', () => {
- test('uses world coordinates inside entered containers', () => {
+describe('editor hit testing', () => {
+ test('finds layers from the page whatever container is entered', () => {
const editor = createEditor()
const pageId = editor.state.currentPageId
const frame = editor.graph.createNode('FRAME', pageId, {
@@ -70,5 +70,9 @@ describe('editor scoped hit testing', () => {
editor.state.enteredContainerId = frame.id
editor.selectAtPoint(130, 130)
expect([...editor.state.selectedIds]).toEqual([child.id])
+ // The entered container follows the selection, as after a press.
+ expect(editor.state.enteredContainerId).toBe(frame.id)
+ editor.selectAtPoint(500, 500)
+ expect([...editor.state.selectedIds]).toEqual([])
})
})
diff --git a/packages/scene-graph/src/graph.ts b/packages/scene-graph/src/graph.ts
index 2bafd1e80..4a6cc401b 100644
--- a/packages/scene-graph/src/graph.ts
+++ b/packages/scene-graph/src/graph.ts
@@ -711,18 +711,17 @@ export class SceneGraph {
py: number,
scopeId: string,
selectedIds: ReadonlySet<string>,
- pad = 0,
- framesOpen = true
+ options?: HitTest.SelectableHitOptions
): SceneNode | null {
- return HitTest.hitTestSelectable(this, px, py, scopeId, selectedIds, pad, framesOpen)
+ return HitTest.hitTestSelectable(this, px, py, scopeId, selectedIds, options)
}
hitTestOpenContainer(px: number, py: number, scopeId: string): SceneNode | null {
return HitTest.hitTestOpenContainer(this, px, py, scopeId)
}
- isOpenContainer(nodeId: string): boolean {
- return HitTest.isOpenContainer(this, nodeId)
+ isOpenContainer(nodeId: string, framesOpen = true): boolean {
+ return HitTest.isOpenContainer(this, nodeId, framesOpen)
}
isPointInNode(nodeId: string, px: number, py: number): boolean {
diff --git a/packages/scene-graph/src/hit-test.ts b/packages/scene-graph/src/hit-test.ts
index 53e195b4e..ca7b37943 100644
--- a/packages/scene-graph/src/hit-test.ts
+++ b/packages/scene-graph/src/hit-test.ts
@@ -110,9 +110,10 @@ function hitTestTransparentContainer(
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
+ // 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)
- if (childHit) return deep ? childHit : child
- return containsPoint(px, py, child, graph, transformCache) ? child : null
+ return childHit ? (deep ? childHit : child) : null
}
const childHit = hitTestChildren(graph, px, py, childId, deep, transformCache, pad)
@@ -241,17 +242,26 @@ function frameChildAt(
}
/**
- * The containers the selection opens: every ancestor of a selected layer inside the scope, and a
- * selected container itself, so a click inside it selects the layer under the point, as in Figma.
- * A selected group or boolean stays closed: clicking inside it keeps it selected.
+ * The containers the selection opens: every ancestor of a selected layer inside the scope, so a
+ * click reaches the siblings of selected layers, and a selected container itself, so hover and a
+ * read-only click reach the layer under the point. A plain press inside a selected frame still
+ * drags the frame, as in Figma, which `pressesSelection` in the Vue input decides. A selected group
+ * or boolean stays closed: clicking inside it keeps it selected.
*/
function openedBySelection(
graph: SceneGraph,
selectedIds: ReadonlySet<string>,
scopeId: string,
- framesOpen = true
+ framesOpen: boolean,
+ enteredId: string | null
): Set<string> {
const ancestors = new Set<string>()
+ // An entered container is open whatever its kind, so a double-click into a board's frame
+ // reaches its layers; its ancestors open with it.
+ for (let id = enteredId; id && id !== scopeId && !ancestors.has(id);) {
+ ancestors.add(id)
+ id = graph.nodes.get(id)?.parentId ?? null
+ }
for (const id of selectedIds) {
const node = graph.nodes.get(id)
if (
@@ -280,15 +290,24 @@ function openedBySelection(
* by the selection is selected, so is a top-level frame with auto layout, and a plain top-level
* frame or a section is not.
*/
+export interface SelectableHitOptions {
+ /** Canvas units a leaf layer's box grows by, as Figma takes a click a few pixels outside. */
+ pad?: number
+ /** Whether top-level frames are looked into (a design) or selected whole (a board). */
+ framesOpen?: boolean
+ /** The container a double-click entered, open along with its ancestors. */
+ enteredId?: string | null
+}
+
export function hitTestSelectable(
graph: SceneGraph,
px: number,
py: number,
scopeId: string,
selectedIds: ReadonlySet<string>,
- pad = 0,
- framesOpen = true
+ options: SelectableHitOptions = {}
): SceneNode | null {
+ const { pad = 0, framesOpen = true, enteredId = null } = options
const deepest = hitTestChildren(graph, px, py, scopeId, true, new Map(), pad)
if (!deepest) {
const scope = graph.nodes.get(scopeId)
@@ -301,7 +320,7 @@ export function hitTestSelectable(
node = node.parentId ? graph.nodes.get(node.parentId) : undefined
}
- const opened = openedBySelection(graph, selectedIds, scopeId, framesOpen)
+ const opened = openedBySelection(graph, selectedIds, scopeId, framesOpen, enteredId)
for (const node of chain) {
// A locked layer stands in for everything inside it.
@@ -317,9 +336,9 @@ export function hitTestSelectable(
}
/** Whether a click looks into this container rather than selecting it; see `hitTestSelectable`. */
-export function isOpenContainer(graph: SceneGraph, nodeId: string): boolean {
+export function isOpenContainer(graph: SceneGraph, nodeId: string, framesOpen = true): boolean {
const node = graph.nodes.get(nodeId)
- return node !== undefined && opensByItself(graph, node)
+ return node !== undefined && opensByItself(graph, node, framesOpen)
}
/**
diff --git a/packages/scene-graph/tests/basic/selectable-hit.test.ts b/packages/scene-graph/tests/basic/selectable-hit.test.ts
index 7469b8406..a10b127f3 100644
--- a/packages/scene-graph/tests/basic/selectable-hit.test.ts
+++ b/packages/scene-graph/tests/basic/selectable-hit.test.ts
@@ -283,7 +283,7 @@ describe('a click just outside a shape', () => {
fills: FILL
})
const hit = (x: number, y: number, zoom: number) =>
- graph.hitTestSelectable(x, y, page, new Set(), 3.5 / zoom)?.name ?? null
+ graph.hitTestSelectable(x, y, page, new Set(), { pad: 3.5 / zoom })?.name ?? null
for (const zoom of [0.5, 1, 4]) {
const inside = 3.4 / zoom
const outside = 3.6 / zoom
@@ -298,6 +298,26 @@ describe('a click just outside a shape', () => {
}
})
+ test('a group’s empty area takes no click, so a layer under the group shows through', () => {
+ const graph = new SceneGraph()
+ const page = pageId(graph)
+ const line = graph.createNode('RECTANGLE', page, {
+ name: 'Line',
+ x: 100,
+ y: 100,
+ width: 400,
+ height: 300,
+ fills: FILL
+ })
+ const group = graph.createNode('GROUP', page, { name: 'Dots', x: 150, y: 150, width: 300, height: 200 })
+ graph.createNode('ELLIPSE', group.id, { name: 'Dot', width: 20, height: 20, fills: FILL })
+ expect(graph.hitTestSelectable(160, 160, page, new Set())?.name).toBe('Dots')
+ expect(graph.hitTestSelectable(300, 250, page, new Set())?.id).toBe(line.id)
+ expect(graph.hitTestDeep(300, 250, page)?.id).toBe(line.id)
+ graph.updateNode(line.id, { visible: false })
+ expect(graph.hitTestSelectable(300, 250, page, new Set())).toBeNull()
+ })
+
test('reaches a shape at its group’s edge, and the group only through its shapes', () => {
const graph = new SceneGraph()
const page = pageId(graph)
@@ -309,28 +329,33 @@ describe('a click just outside a shape', () => {
height: 50
})
graph.createNode('RECTANGLE', group.id, { name: 'Box', width: 50, height: 50, fills: FILL })
- expect(graph.hitTestSelectable(152, 120, page, new Set(), 3.5)?.name).toBe('Group')
+ expect(graph.hitTestSelectable(152, 120, page, new Set(), { pad: 3.5 })?.name).toBe('Group')
expect(graph.hitTestDeep(152, 120, page, 3.5)?.name).toBe('Box')
- expect(graph.hitTestSelectable(155, 120, page, new Set(), 3.5)).toBeNull()
+ expect(graph.hitTestSelectable(155, 120, page, new Set(), { pad: 3.5 })).toBeNull()
})
test('leaves a frame’s edge exact, so the page around it starts a marquee', () => {
const graph = new SceneGraph()
const page = pageId(graph)
graph.createNode('FRAME', page, { name: 'Empty', width: 100, height: 100, fills: FILL })
- expect(graph.hitTestSelectable(102, 50, page, new Set(), 3.5)).toBeNull()
+ expect(graph.hitTestSelectable(102, 50, page, new Set(), { pad: 3.5 })).toBeNull()
})
// FigJam board, Figma desktop: a click on a layer inside a frame selects the frame.
test('selects a top-level frame whole when frames stay closed, as on a board', () => {
const { graph, page } = scene()
const click = (framesOpen: boolean) =>
- graph.hitTestSelectable(170, 170, page, new Set(), 0, framesOpen)?.name ?? null
+ graph.hitTestSelectable(170, 170, page, new Set(), { framesOpen })?.name ?? null
// In a design the click looks into the top-level frame and takes the frame inside it.
expect([click(true), click(false)]).toEqual(['Nested', 'Top'])
// Selected, it stays closed: another click inside keeps the frame.
const top = [...graph.nodes.values()].find((node) => node.name === 'Top')
if (!top) throw new Error('Missing Top')
- expect(graph.hitTestSelectable(170, 170, page, new Set([top.id]), 0, false)?.name).toBe('Top')
+ expect(graph.hitTestSelectable(170, 170, page, new Set([top.id]), { framesOpen: false })?.name).toBe('Top')
+ // Entered by a double-click, it is open from the page: the click reaches the frame inside.
+ const entered = { framesOpen: false, enteredId: top.id }
+ expect(graph.hitTestSelectable(170, 170, page, new Set(), entered)?.name).toBe('Nested')
+ // A click outside the entered frame still lands as a click from nothing does.
+ expect(graph.hitTestSelectable(850, 50, page, new Set(), entered)?.name).toBe('Component')
})
})
diff --git a/packages/vue/src/canvas/pointer/use.ts b/packages/vue/src/canvas/pointer/use.ts
index 06eefc20e..681a26a86 100644
--- a/packages/vue/src/canvas/pointer/use.ts
+++ b/packages/vue/src/canvas/pointer/use.ts
@@ -3,12 +3,7 @@ import type { Ref } from 'vue'
import type { Editor } from '@open-pencil/core'
import type { SceneNode } from '@open-pencil/scene-graph'
-import {
- canvasToLocalPoint,
- getPointerCoords,
- hitTestInEditorScope,
- isInsideEditorContainerBounds
-} from '#vue/shared/input/geometry'
+import { canvasToLocalPoint, getPointerCoords, hitTestLayerAt } from '#vue/shared/input/geometry'
import type { HitTestFns } from '#vue/shared/input/select'
export function createCanvasPointer(
@@ -20,14 +15,11 @@ export function createCanvasPointer(
) {
const canvasToLocal = (cx: number, cy: number, scopeId: string) =>
canvasToLocalPoint(cx, cy, scopeId, editor)
- const hitTestInScope = (cx: number, cy: number, deep: boolean) =>
- hitTestInEditorScope(cx, cy, deep, editor)
- const isInsideContainerBounds = (cx: number, cy: number, containerId: string) =>
- isInsideEditorContainerBounds(cx, cy, containerId, editor, canvasToLocal)
+ const hitTestLayer = (cx: number, cy: number, deep: boolean) =>
+ hitTestLayerAt(cx, cy, deep, editor)
const hitFns: HitTestFns = {
- hitTestInScope,
- isInsideContainerBounds,
+ hitTestLayer,
hitTestSectionTitle,
hitTestComponentLabel,
hitTestFrameTitle
@@ -36,8 +28,7 @@ export function createCanvasPointer(
return {
getCoords: (e: MouseEvent) => getPointerCoords(e, canvasRef.value, editor),
canvasToLocal,
- hitTestInScope,
- isInsideContainerBounds,
+ hitTestLayer,
hitFns
}
}
diff --git a/packages/vue/src/canvas/text-edit/input.ts b/packages/vue/src/canvas/text-edit/input.ts
index ef1e923b4..d94341056 100644
--- a/packages/vue/src/canvas/text-edit/input.ts
+++ b/packages/vue/src/canvas/text-edit/input.ts
@@ -13,12 +13,11 @@ type SetDrag = (drag: DragState) => void
type TextEditInputOptions = {
editor: Editor
getCoords: GetCoords
- hitTestInScope: HitTest
+ hitTestLayer: HitTest
hitTestSectionTitle: (cx: number, cy: number) => SceneNode | null
hitTestComponentLabel: (cx: number, cy: number) => SceneNode | null
hitTestFrameTitle: (cx: number, cy: number) => SceneNode | null
getClickCount: () => number
- wasSelectedBeforeClickSequence: (id: string) => boolean
onEditCanvasLabel?: (kind: CanvasLabelKind, node: SceneNode) => void
setDrag: SetDrag
}
@@ -27,12 +26,11 @@ export function createTextEditInput(options: TextEditInputOptions) {
const {
editor,
getCoords,
- hitTestInScope,
+ hitTestLayer,
hitTestSectionTitle,
hitTestComponentLabel,
hitTestFrameTitle,
getClickCount,
- wasSelectedBeforeClickSequence,
onEditCanvasLabel,
setDrag
} = options
@@ -51,9 +49,9 @@ export function createTextEditInput(options: TextEditInputOptions) {
const localY = cy - abs.y
if (localX < 0 || localY < 0 || localX > editNode.width || localY > editNode.height) {
editor.commitTextEdit()
- const hit = hitTestInScope(cx, cy, true)
+ const hit = hitTestLayer(cx, cy, true)
if (hit?.type === 'TEXT' && hit.id !== editNode.id) {
- startTextEditingAt(hit, cx, cy)
+ startTextEditingAt(hit, cx, cy, 'caret')
return true
}
return false
@@ -70,7 +68,16 @@ export function createTextEditInput(options: TextEditInputOptions) {
return true
}
- function startTextEditingAt(hit: SceneNode, cx: number, cy: number) {
+ /**
+ * Starts editing `hit` as Figma does: a double-click selects all of its text, a click on it
+ * while another text is edited puts the caret where the click landed.
+ */
+ function startTextEditingAt(
+ hit: SceneNode,
+ cx: number,
+ cy: number,
+ selection: 'all' | 'caret' = 'all'
+ ) {
editor.select([hit.id])
editor.startTextEditing(hit.id)
// Text the editor refuses, such as path text without its font, stays selected only.
@@ -78,7 +85,8 @@ export function createTextEditInput(options: TextEditInputOptions) {
const textEd = editor.textEditor
if (textEd) {
const abs = editor.graph.getAbsolutePosition(hit.id)
- textEd.selectWordAt(cx - abs.x, cy - abs.y)
+ if (selection === 'caret') textEd.setCursorAt(cx - abs.x, cy - abs.y, false)
+ else textEd.selectAll()
editor.textSelectionChanged()
}
}
@@ -143,14 +151,18 @@ export function createTextEditInput(options: TextEditInputOptions) {
}
const hit = getContainerDescendantHit(selectedId, cx, cy)
editor.enterContainer(selectedId)
- if (hit?.type === 'TEXT' && resolveEditorProfile(editor.state).edits)
- startTextEditingAt(hit, cx, cy)
- else if (hit) editor.select([hit.id])
+ // A text one level down is selected first; the next double-click edits it, as in Figma.
+ if (hit) editor.select([hit.id])
else editor.clearSelection()
return true
}
- function onDblClick(e: MouseEvent) {
+ /**
+ * The press of a run's second click or later: one level deeper, as a double-click goes in
+ * Figma. The third click on, `rapid`, goes a level deeper too but stops at a text: editing it
+ * takes a double-click.
+ */
+ function pressDeeper(e: MouseEvent, rapid = false) {
const nodeEditEditor = editor as Editor & NodeEditMethods
if (editor.state.editingTextId) return
@@ -162,7 +174,7 @@ export function createTextEditInput(options: TextEditInputOptions) {
editor.state.selectedIds.size === 1 ? [...editor.state.selectedIds][0] : undefined
if (handleContainerDoubleClick(selectedId, cx, cy)) return
- const found = hitTestInScope(cx, cy, true)
+ const found = hitTestLayer(cx, cy, true)
if (!found) return
// A generated frame's sublayers are edited through the frame.
const hit = generatedFrameOwner(editor.graph, found) ?? found
@@ -173,12 +185,9 @@ export function createTextEditInput(options: TextEditInputOptions) {
}
if (hit.type === 'TEXT') {
- const isTopLevelText = hit.parentId === editor.state.currentPageId
- if (!isTopLevelText && selectedId !== hit.id && !wasSelectedBeforeClickSequence(hit.id)) {
- editor.select([hit.id])
- return
- }
- startTextEditingAt(hit, cx, cy)
+ // The selected text is edited; a text reached by this click is selected first.
+ if (rapid || selectedId !== hit.id) editor.select([hit.id])
+ else startTextEditingAt(hit, cx, cy)
return
}
@@ -195,5 +204,5 @@ export function createTextEditInput(options: TextEditInputOptions) {
editor.select([hit.id])
}
- return { handleTextEditClick, onDblClick }
+ return { handleTextEditClick, pressDeeper }
}
diff --git a/packages/vue/src/canvas/transform/marquee.ts b/packages/vue/src/canvas/transform/marquee.ts
index ef9069c20..16ba00229 100644
--- a/packages/vue/src/canvas/transform/marquee.ts
+++ b/packages/vue/src/canvas/transform/marquee.ts
@@ -41,13 +41,16 @@ export function handleMarqueeMove(editor: Editor, d: DragMarquee, cx: number, cy
editor.setMarquee(marquee)
}
-/** Ends a marquee; a click on a section's empty area, without a drag, selects it, as in Figma. */
+/**
+ * Ends a marquee; a click on a section's empty area, without a drag, selects it when nothing was
+ * selected, as in Figma, where the same click with a selection only deselects.
+ */
export function finishMarquee(editor: Editor, d: DragMarquee) {
const container = d.containerId ? editor.graph.getNode(d.containerId) : undefined
const marquee = editor.state.marquee
const zoom = editor.state.zoom
const dragged =
!!marquee && isPastPointerDragThreshold(0, 0, marquee.width * zoom, marquee.height * zoom)
- if (!dragged && container?.type === 'SECTION') editor.select([container.id])
+ if (!dragged && d.selectsSection && container?.type === 'SECTION') editor.select([container.id])
editor.setMarquee(null)
}
diff --git a/packages/vue/src/canvas/useCanvasInput.ts b/packages/vue/src/canvas/useCanvasInput.ts
index 2c97b80cb..bdce06cc3 100644
--- a/packages/vue/src/canvas/useCanvasInput.ts
+++ b/packages/vue/src/canvas/useCanvasInput.ts
@@ -81,7 +81,6 @@ export function useCanvasInput(
const cursorOverride = ref<string | null>(null)
/** Whether the primary button is held on a preview control, such as a slider thumb. */
const valueEdit = createAutoLayoutValueEdit(editor)
- const selectedIdsBeforeClickSequence = ref<ReadonlySet<string>>(new Set())
const lastPointer = ref<{ cx: number; cy: number; sx: number; sy: number } | null>(null)
const pointerInside = ref(false)
let altHeld = false
@@ -90,7 +89,7 @@ export function useCanvasInput(
const spaceHeld = useSpaceHeld()
const { recordClick, getClickCount } = createClickCounter()
- const { getCoords, canvasToLocal, hitTestInScope, hitFns } = createCanvasPointer(
+ const { getCoords, canvasToLocal, hitTestLayer, hitFns } = createCanvasPointer(
canvasRef,
editor,
hitTestSectionTitle,
@@ -173,15 +172,14 @@ export function useCanvasInput(
}
})
- const { handleTextEditClick, onDblClick: onTextDblClick } = createTextEditInput({
+ const { handleTextEditClick, pressDeeper } = createTextEditInput({
editor,
getCoords,
- hitTestInScope,
+ hitTestLayer,
hitTestSectionTitle,
hitTestComponentLabel,
hitTestFrameTitle,
getClickCount,
- wasSelectedBeforeClickSequence: (id) => selectedIdsBeforeClickSequence.value.has(id),
onEditCanvasLabel: canvasLabelEdit.start,
setDrag
})
@@ -194,15 +192,39 @@ export function useCanvasInput(
handleMarqueeMove
} = createCanvasTransformInput(editor, setDrag)
- function onDblClick(e: MouseEvent) {
- if (profile().pointer === 'pan') return
+ /**
+ * Only a plain press of the select tool takes a double-click on its press: a drawing tool, a
+ * vector being edited, and a Shift-press that adds to the selection keep their own press.
+ */
+ function takesMultiClick(e: MouseEvent): boolean {
+ return (
+ e.button === 0 &&
+ !e.shiftKey &&
+ editor.state.activeTool === 'SELECT' &&
+ !editor.state.editingTextId &&
+ !editor.state.nodeEditState &&
+ profile().pointer !== 'pan'
+ )
+ }
+
+ /**
+ * The second click of a run and every one after it, on its press: one level deeper, or a value
+ * field, as in Figma. The press decides so that every click of a quick run counts; the browser
+ * fires its double-click event by its own count, which a click shortly before the run shifts.
+ */
+ function onMultiClickDown(e: MouseEvent, clickCount: number) {
const { cx, cy } = getCoords(e)
- if (profile().edits && valueEdit.start(cx, cy)) {
+ if (clickCount === 2 && profile().edits && valueEdit.start(cx, cy)) {
e.preventDefault()
e.stopPropagation()
return
}
- onTextDblClick(e)
+ pressDeeper(e, clickCount > 2)
+ }
+
+ function onDblClick(e: MouseEvent) {
+ // Handled on the press; the event only must not start a browser text selection.
+ e.preventDefault()
}
function hoverLayers({ event, cx, cy, sx, sy }: CanvasToolPointer) {
@@ -259,9 +281,11 @@ export function useCanvasInput(
}
editor.setSelectedGuide(null)
- const selectedIdsBeforeMouseDown = new Set(editor.state.selectedIds)
- const clickCount = recordClick(sx, sy)
- if (clickCount === 1) selectedIdsBeforeClickSequence.value = selectedIdsBeforeMouseDown
+ const clickCount = recordClick(sx, sy, e.detail)
+ if (clickCount >= 2 && takesMultiClick(e)) {
+ onMultiClickDown(e, clickCount)
+ return
+ }
pressCanvasTool({ event: e, cx, cy, sx, sy }, toolContext)
}
diff --git a/packages/vue/src/shared/input/click-count.ts b/packages/vue/src/shared/input/click-count.ts
index 826251aee..835cb797b 100644
--- a/packages/vue/src/shared/input/click-count.ts
+++ b/packages/vue/src/shared/input/click-count.ts
@@ -7,9 +7,16 @@ export function createClickCounter() {
let lastClickY = 0
let clickCount = 0
- function recordClick(sx: number, sy: number) {
+ /**
+ * Counts a press in a run of clicks. `detail`, the browser's own count for the press, is the
+ * count when the event carries one: the system times the run by its own double-click speed. A
+ * press without one, such as a dispatched event, is counted here by time and distance.
+ */
+ function recordClick(sx: number, sy: number, detail = 0) {
const now = performance.now()
- if (
+ if (detail > 0) {
+ clickCount = detail
+ } else if (
now - lastClickTime < MULTI_CLICK_DELAY &&
Math.abs(sx - lastClickX) < MULTI_CLICK_RADIUS &&
Math.abs(sy - lastClickY) < MULTI_CLICK_RADIUS
diff --git a/packages/vue/src/shared/input/geometry.ts b/packages/vue/src/shared/input/geometry.ts
index b70c8c145..135f02d2a 100644
--- a/packages/vue/src/shared/input/geometry.ts
+++ b/packages/vue/src/shared/input/geometry.ts
@@ -48,42 +48,31 @@ export function canvasToLocalPoint(
return { lx: point?.x ?? cx, ly: point?.y ?? cy }
}
-export function hitTestInEditorScope(
+/**
+ * The layer a press selects, or with `deep` (⌘ or Ctrl held) the deepest layer under the point.
+ * Always found from the page: the selection and the entered container open their ancestors, so
+ * an entered container never limits where a click lands, as in Figma.
+ */
+export function hitTestLayerAt(
cx: number,
cy: number,
deep: boolean,
editor: Editor
): SceneNode | null {
- const scopeId = editor.state.enteredContainerId
-
const renderer = editor.renderer
if (!renderer) return null
const pad = LAYER_HIT_PAD / renderer.zoom
- if (scopeId && !editor.graph.getNode(scopeId)) editor.state.enteredContainerId = null
- const scope = editor.state.enteredContainerId ?? editor.state.currentPageId
+ const scope = editor.state.currentPageId
+ if (editor.state.enteredContainerId && !editor.graph.getNode(editor.state.enteredContainerId)) {
+ editor.state.enteredContainerId = null
+ }
return deep
? editor.graph.hitTestDeep(cx, cy, scope, pad)
- : editor.graph.hitTestSelectable(
- cx,
- cy,
- scope,
- editor.state.selectedIds,
+ : editor.graph.hitTestSelectable(cx, cy, scope, editor.state.selectedIds, {
pad,
- resolveEditorProfile(editor.state).framesOpen
- )
-}
-
-export function isInsideEditorContainerBounds(
- cx: number,
- cy: number,
- containerId: string,
- editor: Editor,
- canvasToLocal: (cx: number, cy: number, scopeId: string) => { lx: number; ly: number }
-): boolean {
- const container = editor.graph.getNode(containerId)
- if (!container) return false
- const { lx, ly } = canvasToLocal(cx, cy, containerId)
- return lx >= 0 && lx <= container.width && ly >= 0 && ly <= container.height
+ framesOpen: resolveEditorProfile(editor.state).framesOpen,
+ enteredId: editor.state.enteredContainerId
+ })
}
export function getScreenRect(
diff --git a/packages/vue/src/shared/input/move/drag.ts b/packages/vue/src/shared/input/move/drag.ts
index 4c589ad53..5aff94365 100644
--- a/packages/vue/src/shared/input/move/drag.ts
+++ b/packages/vue/src/shared/input/move/drag.ts
@@ -342,7 +342,6 @@ export function handleMoveUp(d: DragMove, editor: Editor) {
editor.setLayoutInsertIndicator(null)
editor.setSnapGuides([])
editor.setDropTarget(null)
- if (d.selectOnClick) editor.select([d.selectOnClick])
return
}
diff --git a/packages/vue/src/shared/input/select.ts b/packages/vue/src/shared/input/select.ts
index 866e43db7..e78cc078c 100644
--- a/packages/vue/src/shared/input/select.ts
+++ b/packages/vue/src/shared/input/select.ts
@@ -12,8 +12,7 @@ import { tryStartLineEndDrag } from '#vue/shared/input/line/end'
import { tryStartResize } from '#vue/shared/input/resize'
import {
createSelectionMoveDrag,
- clickSelectsInside,
- pressesSelection,
+ pressSelects,
selectionIsLocked
} from '#vue/shared/input/select/move'
import { tryStartShapeHandleDrag } from '#vue/shared/input/shape-handles'
@@ -21,18 +20,23 @@ import { tryStartStickyScale } from '#vue/shared/input/sticky/scale'
import type { DragState } from '#vue/shared/input/types'
export interface HitTestFns {
- hitTestInScope: (cx: number, cy: number, deep: boolean) => SceneNode | null
- isInsideContainerBounds: (cx: number, cy: number, containerId: string) => boolean
+ hitTestLayer: (cx: number, cy: number, deep: boolean) => SceneNode | null
hitTestSectionTitle: (cx: number, cy: number) => SceneNode | null
hitTestComponentLabel: (cx: number, cy: number) => SceneNode | null
hitTestFrameTitle: (cx: number, cy: number) => SceneNode | null
}
-/** Clears the selection and starts a marquee in the open frame or section under the press. */
+/**
+ * A press on nothing: leaves any entered container, clears the selection, and starts a marquee in
+ * the open frame or section under the press. Without a drag it selects that section only when
+ * nothing was selected; with a selection it only deselects, as in Figma.
+ */
function startMarquee(cx: number, cy: number, editor: Editor, setDrag: (d: DragState) => void) {
+ const selectsSection = editor.state.selectedIds.size === 0
+ editor.exitContainers()
editor.clearSelection()
const container = editor.graph.hitTestOpenContainer(cx, cy, editor.state.currentPageId)
- setDrag({ type: 'marquee', startX: cx, startY: cy, containerId: container?.id })
+ setDrag({ type: 'marquee', startX: cx, startY: cy, containerId: container?.id, selectsSection })
}
/**
@@ -72,16 +76,18 @@ function tryStartHandleDrag(
return !hitTestLabel(cx, cy, fns) && tryStartRotation(cx, cy)
}
-/** Shift adds to the selection; a plain press selects the layer unless it keeps the selection. */
-function selectOnPress(hit: SceneNode, shiftKey: boolean, keepsSelection: boolean, editor: Editor) {
- if (shiftKey) editor.select([hit.id], true)
- else if (!editor.state.selectedIds.has(hit.id) && !keepsSelection) editor.select([hit.id])
-}
-
-/** A read-only document moves nothing, so a press selects a layer inside a selected frame at once. */
-function selectInsideOnPress(hit: SceneNode, keepsSelection: boolean, editor: Editor) {
- if (keepsSelection && !editor.state.selectedIds.has(hit.id) && clickSelectsInside(hit, editor))
- editor.select([hit.id])
+/**
+ * Shift adds to the selection; a plain press selects the layer when the press selects it and
+ * enters the container it was reached through, so Escape, pasting, and the marquee follow it.
+ */
+function selectOnPress(hit: SceneNode, shiftKey: boolean, selects: boolean, editor: Editor) {
+ if (shiftKey) {
+ editor.select([hit.id], true)
+ return
+ }
+ if (!selects) return
+ if (!editor.state.selectedIds.has(hit.id)) editor.select([hit.id])
+ editor.enterContainerOf(hit.id)
}
export function handleSelectDown(
@@ -108,26 +114,19 @@ export function handleSelectDown(
if (tryStartHandleDrag(cx, cy, sx, sy, e.altKey, editor, fns, tryStartRotation, setDrag)) return
- const hit =
- tinySelectionAt(cx, cy, editor) ?? resolveHit(cx, cy, editor, fns, e.metaKey || e.ctrlKey)
+ const deep = e.metaKey || e.ctrlKey
+ const hit = tinySelectionAt(cx, cy, editor) ?? resolveHit(cx, cy, fns, deep)
if (!hit) {
- if (!editor.state.enteredContainerId) startMarquee(cx, cy, editor, setDrag)
+ startMarquee(cx, cy, editor, setDrag)
return
}
- const keepsSelection = !e.shiftKey && pressesSelection(hit, cx, cy, editor)
- selectOnPress(hit, e.shiftKey, keepsSelection, editor)
+ selectOnPress(hit, e.shiftKey, pressSelects(hit, cx, cy, editor, deep), editor)
- if (!resolveEditorProfile(editor.state).edits) {
- selectInsideOnPress(hit, keepsSelection, editor)
- return
- }
+ // A read-only document moves nothing.
+ if (!resolveEditorProfile(editor.state).edits) return
if (selectionIsLocked(editor)) return
- const drag = createSelectionMoveDrag(cx, cy, sx, sy, editor, e.altKey)
- // A click without dragging still selects a layer inside a selected frame; groups need a double-click.
- if (drag.type === 'move' && keepsSelection && !editor.state.selectedIds.has(hit.id)) {
- drag.selectOnClick = clickSelectsInside(hit, editor) ? hit.id : undefined
- }
- setDrag(drag)
+ // A press inside the selection drags it; its layers are a double-click or ⌘-click away, as in Figma.
+ setDrag(createSelectionMoveDrag(cx, cy, sx, sy, editor, e.altKey))
}
diff --git a/packages/vue/src/shared/input/select/hit.ts b/packages/vue/src/shared/input/select/hit.ts
index 6cec9fc37..c8db9c774 100644
--- a/packages/vue/src/shared/input/select/hit.ts
+++ b/packages/vue/src/shared/input/select/hit.ts
@@ -33,34 +33,16 @@ export function tinySelectionAt(cx: number, cy: number, editor: Editor): SceneNo
return null
}
-/** The layer a press selects; `deep` (Cmd or Ctrl held) reaches the deepest layer, as in Figma. */
+/**
+ * The layer a press selects: a label under the point, or else the layer a click reaches from the
+ * page; `deep` (⌘ or Ctrl held) reaches the deepest layer, as in Figma. Null where nothing is
+ * under the point, however deep the selection was.
+ */
export function resolveHit(
cx: number,
cy: number,
- editor: Editor,
fns: HitTestFns,
deep = false
): SceneNode | null {
- const titleHit = hitTestLabel(cx, cy, fns)
- if (titleHit) return titleHit
-
- const hit = fns.hitTestInScope(cx, cy, deep)
- if (hit) return hit
-
- const scopeId = editor.state.enteredContainerId
- if (!scopeId) return null
-
- if (fns.isInsideContainerBounds(cx, cy, scopeId)) {
- editor.clearSelection()
- return null
- }
-
- editor.exitContainer()
- const afterExit = fns.hitTestInScope(cx, cy, deep)
- if (afterExit) return afterExit
-
- if (editor.state.enteredContainerId) {
- editor.exitContainer()
- }
- return null
+ return hitTestLabel(cx, cy, fns) ?? fns.hitTestLayer(cx, cy, deep)
}
diff --git a/packages/vue/src/shared/input/select/hover.ts b/packages/vue/src/shared/input/select/hover.ts
index eda106e4f..fcce9eb78 100644
--- a/packages/vue/src/shared/input/select/hover.ts
+++ b/packages/vue/src/shared/input/select/hover.ts
@@ -12,6 +12,7 @@ import {
import { lineEndAt } from '#vue/shared/input/line/end'
import type { HitTestFns } from '#vue/shared/input/select'
import { hitTestLabel } from '#vue/shared/input/select/hit'
+import { pressSelects } from '#vue/shared/input/select/move'
import { scalesByHandles } from '#vue/shared/input/sticky/scale'
import { getNodeEditState } from '#vue/shared/input/vector'
@@ -60,17 +61,20 @@ function updateHoveredNode(
editor: Editor,
fns: Pick<
HitTestFns,
- 'hitTestInScope' | 'hitTestFrameTitle' | 'hitTestSectionTitle' | 'hitTestComponentLabel'
+ 'hitTestLayer' | 'hitTestFrameTitle' | 'hitTestSectionTitle' | 'hitTestComponentLabel'
>,
deep: boolean
) {
- const hit = deep
- ? fns.hitTestInScope(cx, cy, true)
- : (hitTestLabel(cx, cy, fns) ?? fns.hitTestInScope(cx, cy, false))
+ // A label takes the hover before the layers under it, with or without ⌘, as it takes a press.
+ const hit = hitTestLabel(cx, cy, fns) ?? fns.hitTestLayer(cx, cy, deep)
const editNodeId = getNodeEditState(editor)?.nodeId
- editor.setHoveredNode(
- hit && !editor.state.selectedIds.has(hit.id) && hit.id !== editNodeId ? hit.id : null
- )
+ // No outline on a layer a press would not select.
+ const hovered =
+ hit &&
+ !editor.state.selectedIds.has(hit.id) &&
+ hit.id !== editNodeId &&
+ pressSelects(hit, cx, cy, editor, deep)
+ editor.setHoveredNode(hovered ? hit.id : null)
}
export function updateHoverCursor(
@@ -79,7 +83,7 @@ export function updateHoverCursor(
editor: Editor,
fns: Pick<
HitTestFns,
- 'hitTestInScope' | 'hitTestFrameTitle' | 'hitTestSectionTitle' | 'hitTestComponentLabel'
+ 'hitTestLayer' | 'hitTestFrameTitle' | 'hitTestSectionTitle' | 'hitTestComponentLabel'
>,
deep = false
): string | null {
diff --git a/packages/vue/src/shared/input/select/move.ts b/packages/vue/src/shared/input/select/move.ts
index 982b03e18..268f78096 100644
--- a/packages/vue/src/shared/input/select/move.ts
+++ b/packages/vue/src/shared/input/select/move.ts
@@ -1,4 +1,4 @@
-import type { Editor, MovePlace } from '@open-pencil/core'
+import { resolveEditorProfile, type Editor, type MovePlace } from '@open-pencil/core'
import type { SceneNode } from '@open-pencil/scene-graph'
import { duplicateAndDrag } from '#vue/shared/input/duplicate-drag'
@@ -23,18 +23,12 @@ export function selectionIsLocked(editor: Editor) {
/**
* Whether pressing `hit` should drag the current selection, as in Figma: the hit lies inside a
- * selected layer, or a selected layer under the point lies inside the hit group or boolean.
+ * selected layer that a click does not look into, or a selected layer under the point lies inside
+ * the hit group or boolean. A selected top-level frame or section stays open, so its layers are
+ * selected by the press as they are when it is not selected.
*/
-export function pressesSelection(hit: SceneNode, cx: number, cy: number, editor: Editor) {
- return [...editor.state.selectedIds].some((id) => {
- if (id === hit.id) return false
- if (editor.graph.isDescendant(hit.id, id)) return true
- return editor.graph.isDescendant(id, hit.id) && editor.graph.isPointInNode(id, cx, cy)
- })
-}
-
-/** Whether clicking `hit` inside the selection selects it: not when a selected group holds it. */
-export function clickSelectsInside(hit: SceneNode, editor: Editor) {
+/** Whether a selected frame, not a group or boolean, holds `hit`; a read-only press selects it then. */
+function insideSelectedFrame(hit: SceneNode, editor: Editor) {
for (let node = editor.graph.getNode(hit.parentId ?? ''); node;) {
if (editor.state.selectedIds.has(node.id)) {
return node.type !== 'GROUP' && node.type !== 'BOOLEAN_OPERATION'
@@ -44,6 +38,14 @@ export function clickSelectsInside(hit: SceneNode, editor: Editor) {
return false
}
+function pressesSelection(hit: SceneNode, cx: number, cy: number, editor: Editor) {
+ return [...editor.state.selectedIds].some((id) => {
+ if (id === hit.id) return false
+ if (editor.graph.isDescendant(hit.id, id)) return !editor.graph.isOpenContainer(id)
+ return editor.graph.isDescendant(id, hit.id) && editor.graph.isPointInNode(id, cx, cy)
+ })
+}
+
function autoLayoutMoveTarget(id: string, editor: Editor): string {
let current = editor.graph.getNode(id)
let target = current
@@ -135,3 +137,19 @@ export function createSelectionMoveDrag(
flows: collectFlowDrags(originals, editor)
}
}
+
+/**
+ * Whether a press on `hit` selects it rather than acting on the selection it lies in, as in
+ * Figma: a press inside a selected frame drags the frame, a deep (⌘) press selects what it hit,
+ * and a read-only document, where nothing drags, selects the layer inside a selected frame.
+ */
+export function pressSelects(
+ hit: SceneNode,
+ cx: number,
+ cy: number,
+ editor: Editor,
+ deep = false
+): boolean {
+ if (deep || !pressesSelection(hit, cx, cy, editor)) return true
+ return !resolveEditorProfile(editor.state).edits && insideSelectedFrame(hit, editor)
+}
diff --git a/packages/vue/src/shared/input/types.ts b/packages/vue/src/shared/input/types.ts
index b094e26cb..d41b6d73a 100644
--- a/packages/vue/src/shared/input/types.ts
+++ b/packages/vue/src/shared/input/types.ts
@@ -127,8 +127,6 @@ export interface DragMove {
keepParents?: boolean
/** Control is held: auto layout frames take the layers as absolute-positioned children. */
ignoreAutoLayout?: boolean
- /** Selected instead if the press ends as a click without dragging. */
- selectOnClick?: string
/** Where Control drops layers among an auto layout frame's children. */
absoluteInsertIndex?: number
}
@@ -176,6 +174,8 @@ export interface DragMarquee {
startY: number
/** The open frame or section the marquee started in, whose layers it selects. */
containerId?: string
+ /** Whether a press without a drag selects the section it started in: only from no selection. */
+ selectsSection: boolean
}
export interface DragRotate {
diff --git a/packages/vue/tests/canvas/transform/marquee.test.ts b/packages/vue/tests/canvas/transform/marquee.test.ts
index 982da70da..88d1672d6 100644
--- a/packages/vue/tests/canvas/transform/marquee.test.ts
+++ b/packages/vue/tests/canvas/transform/marquee.test.ts
@@ -12,7 +12,7 @@ function marquee(from: [number, number], to: [number, number], containerId?: str
editor.clearSelection()
handleMarqueeMove(
editor,
- { type: 'marquee', startX: from[0], startY: from[1], containerId },
+ { type: 'marquee', startX: from[0], startY: from[1], containerId, selectsSection: true },
...to
)
return [...editor.state.selectedIds]
diff --git a/packages/vue/tests/shared/input/move/containers.test.ts b/packages/vue/tests/shared/input/move/containers.test.ts
index bd7c16ed5..29ac0c4b1 100644
--- a/packages/vue/tests/shared/input/move/containers.test.ts
+++ b/packages/vue/tests/shared/input/move/containers.test.ts
@@ -2,11 +2,7 @@ import { afterEach, describe, expect, test } from 'bun:test'
import { autoLayoutInsertIndex } from '#vue/shared/input/auto-layout'
import { handleMoveMove, handleMoveUp } from '#vue/shared/input/move/drag'
-import {
- clickSelectsInside,
- createSelectionMoveDrag,
- pressesSelection
-} from '#vue/shared/input/select/move'
+import { createSelectionMoveDrag, pressSelects } from '#vue/shared/input/select/move'
import { createMoveHarness, type MoveHarness } from './harness'
@@ -160,25 +156,26 @@ describe('auto layout', () => {
})
describe('pressing inside the selection', () => {
- test('drags a selected container rather than the child under the cursor', () => {
+ test('drags a selected container rather than selecting the child under the cursor', () => {
const { node, page, editor } = setup()
const outer = node('FRAME', page, { width: 500, height: 500 })
const nested = node('FRAME', outer.id, { x: 50, y: 50, width: 300, height: 300 })
const child = node('RECTANGLE', nested.id, { x: 50, y: 50, width: 60, height: 60 })
editor.select([nested.id])
- expect(pressesSelection(child, 130, 130, editor)).toBe(true)
- // A click without dragging still selects the child of a frame.
- expect(clickSelectsInside(child, editor)).toBe(true)
+ expect(pressSelects(child, 130, 130, editor)).toBe(false)
+ // A deep press selects what it hit, as a ⌘-click does.
+ expect(pressSelects(child, 130, 130, editor, true)).toBe(true)
+ // A top-level frame stays open while selected, so a press reaches its layers.
+ editor.select([outer.id])
+ expect(pressSelects(nested, 130, 130, editor)).toBe(true)
})
- test('keeps a selected group child when the group is hit, and a selected group on click', () => {
+ test('keeps a selected group child when the group is hit', () => {
const { node, page, editor } = setup()
const group = node('GROUP', page, { width: 160, height: 160 })
const a = node('RECTANGLE', group.id, { width: 60, height: 60 })
editor.select([a.id])
- expect(pressesSelection(group, 20, 20, editor)).toBe(true)
- expect(pressesSelection(group, 120, 120, editor)).toBe(false)
- editor.select([group.id])
- expect(clickSelectsInside(a, editor)).toBe(false)
+ expect(pressSelects(group, 20, 20, editor)).toBe(false)
+ expect(pressSelects(group, 120, 120, editor)).toBe(true)
})
})
diff --git a/packages/vue/tests/shared/input/select/hit.test.ts b/packages/vue/tests/shared/input/select/hit.test.ts
index 4f5572d05..8c842f983 100644
--- a/packages/vue/tests/shared/input/select/hit.test.ts
+++ b/packages/vue/tests/shared/input/select/hit.test.ts
@@ -3,8 +3,9 @@ import { afterEach, describe, expect, test } from 'bun:test'
import { createEditor, type Editor } from '@open-pencil/core'
import type { SceneNode } from '@open-pencil/scene-graph'
-import type { HitTestFns } from '#vue/shared/input/select'
+import { handleSelectDown, type HitTestFns } from '#vue/shared/input/select'
import { resolveHit } from '#vue/shared/input/select/hit'
+import type { DragState } from '#vue/shared/input/types'
let editor: Editor
@@ -14,8 +15,7 @@ function labelHits(
hits: Partial<Record<'frame' | 'section' | 'component', SceneNode>>
): HitTestFns {
return {
- hitTestInScope: () => null,
- isInsideContainerBounds: () => false,
+ hitTestLayer: () => null,
hitTestFrameTitle: () => hits.frame ?? null,
hitTestSectionTitle: () => hits.section ?? null,
hitTestComponentLabel: () => hits.component ?? null
@@ -31,10 +31,135 @@ describe('label hits', () => {
const component = editor.graph.createNode('COMPONENT', pageId, { name: 'Button' })
// Labels are drawn frames, then sections, then components.
- expect(resolveHit(0, 0, editor, labelHits({ frame, section, component }))?.id).toBe(
- component.id
- )
- expect(resolveHit(0, 0, editor, labelHits({ frame, section }))?.id).toBe(section.id)
- expect(resolveHit(0, 0, editor, labelHits({ frame }))?.id).toBe(frame.id)
+ expect(resolveHit(0, 0, labelHits({ frame, section, component }))?.id).toBe(component.id)
+ expect(resolveHit(0, 0, labelHits({ frame, section }))?.id).toBe(section.id)
+ expect(resolveHit(0, 0, labelHits({ frame }))?.id).toBe(frame.id)
+ })
+})
+
+const press = { shiftKey: false, altKey: false, metaKey: false, ctrlKey: false } as MouseEvent
+
+/**
+ * A section holding a top-level auto layout frame of two rows of cards, each a swatch over a
+ * label, as the shadcn kit lays its colours out. Presses resolve against the graph from the page.
+ */
+function swatchRows() {
+ editor = createEditor()
+ const pageId = editor.state.currentPageId
+ const section = editor.graph.createNode('SECTION', pageId, {
+ name: 'Light',
+ width: 800,
+ height: 300
+ })
+ const rows = editor.graph.createNode('FRAME', section.id, {
+ name: 'Rows',
+ x: 40,
+ y: 40,
+ width: 700,
+ height: 180,
+ layoutMode: 'VERTICAL',
+ fills: []
+ })
+ const card = (row: SceneNode, index: number) => {
+ const frame = editor.graph.createNode('FRAME', row.id, {
+ name: `${row.name} card ${index}`,
+ x: index * 140,
+ width: 120,
+ height: 80,
+ layoutMode: 'VERTICAL',
+ fills: []
+ })
+ const swatch = editor.graph.createNode('RECTANGLE', frame.id, {
+ name: `${frame.name} swatch`,
+ width: 120,
+ height: 60
+ })
+ return { frame, swatch }
+ }
+ const row = (index: number) =>
+ editor.graph.createNode('FRAME', rows.id, {
+ name: `Row ${index}`,
+ y: (index - 1) * 100,
+ width: 700,
+ height: 80,
+ layoutMode: 'HORIZONTAL',
+ fills: []
+ })
+ const row1 = row(1)
+ const row2 = row(2)
+ const first = card(row1, 0)
+ const second = card(row1, 1)
+ const below = card(row2, 2)
+ const fns: HitTestFns = {
+ hitTestLayer: (cx, cy, deep) =>
+ deep
+ ? editor.graph.hitTestDeep(cx, cy, pageId)
+ : editor.graph.hitTestSelectable(cx, cy, pageId, editor.state.selectedIds),
+ hitTestFrameTitle: () => null,
+ hitTestSectionTitle: () => null,
+ hitTestComponentLabel: () => null
+ }
+ const pressAt = (x: number, y: number) => {
+ let drag: DragState | null = null
+ handleSelectDown(press, x, y, x, y, editor, fns, () => false, () => false, (next) => {
+ drag = next
+ })
+ return drag as DragState | null
+ }
+ const selected = () => [...editor.state.selectedIds].map((id) => editor.graph.getNode(id)?.name)
+ /** The centre of a layer, in canvas units. */
+ const center = (node: SceneNode) => {
+ const abs = editor.graph.getAbsolutePosition(node.id)
+ return { x: abs.x + node.width / 2, y: abs.y + node.height / 2 }
+ }
+ return { section, rows, row1, row2, first, second, below, pressAt, selected, center }
+}
+
+describe('presses after reaching a nested layer', () => {
+ // Each case repeats a click observed in Figma desktop 126 on the shadcn kit's swatches.
+ test('a press on a swatch in another row selects that row and leaves the entered card', () => {
+ const { first, below, row2, pressAt, selected, center } = swatchRows()
+ editor.select([first.swatch.id])
+ editor.enterContainerOf(first.swatch.id)
+ expect(editor.state.enteredContainerId).toBe(first.frame.id)
+
+ const at = center(below.swatch)
+ pressAt(at.x, at.y)
+ expect(selected()).toEqual([row2.name])
+ expect(editor.state.enteredContainerId).toBeNull()
+ })
+
+ test('a press on a swatch in a sibling card selects that card and enters the row', () => {
+ const { first, second, row1, pressAt, selected, center } = swatchRows()
+ editor.select([first.swatch.id])
+ editor.enterContainerOf(first.swatch.id)
+
+ const at = center(second.swatch)
+ pressAt(at.x, at.y)
+ expect(selected()).toEqual([second.frame.name])
+ expect(editor.state.enteredContainerId).toBe(row1.id)
+ })
+
+ test('a press on nothing deselects, leaves every entered container, and starts a marquee', () => {
+ const { first, pressAt, selected } = swatchRows()
+ editor.select([first.swatch.id])
+ editor.enterContainerOf(first.swatch.id)
+
+ // The section's padding, with a selection, deselects without selecting the section.
+ const drag = pressAt(10, 290)
+ expect(selected()).toEqual([])
+ expect(editor.state.enteredContainerId).toBeNull()
+ expect(drag).toMatchObject({ type: 'marquee', selectsSection: false })
+
+ // From nothing, the same press ends up selecting the section when it does not drag.
+ expect(pressAt(10, 290)).toMatchObject({ type: 'marquee', selectsSection: true })
+ })
+
+ test('a press from nothing selects the row, the direct child of the top-level frame', () => {
+ const { first, row1, pressAt, selected, center } = swatchRows()
+ const at = center(first.swatch)
+ pressAt(at.x, at.y)
+ expect(selected()).toEqual([row1.name])
+ expect(editor.state.enteredContainerId).toBeNull()
})
})
diff --git a/packages/vue/tests/shared/input/select/hover.test.ts b/packages/vue/tests/shared/input/select/hover.test.ts
index 7bd06e93d..cc0ad607d 100644
--- a/packages/vue/tests/shared/input/select/hover.test.ts
+++ b/packages/vue/tests/shared/input/select/hover.test.ts
@@ -26,7 +26,7 @@ function selectedFrame(labelled: boolean) {
})
editor.select([frame.id])
const fns = {
- hitTestInScope: () => null,
+ hitTestLayer: () => null,
hitTestFrameTitle: (): SceneNode | null => (labelled ? frame : null),
hitTestSectionTitle: () => null,
hitTestComponentLabel: () => null
@@ -51,7 +51,7 @@ test('a label does not take the press from a resize band', () => {
})
const NO_HITS = {
- hitTestInScope: () => null,
+ hitTestLayer: () => null,
hitTestFrameTitle: () => null,
hitTestSectionTitle: () => null,
hitTestComponentLabel: () => null
diff --git a/packages/vue/tests/shared/input/select/read-only.test.ts b/packages/vue/tests/shared/input/select/read-only.test.ts
index 38c76eae5..6359a156c 100644
--- a/packages/vue/tests/shared/input/select/read-only.test.ts
+++ b/packages/vue/tests/shared/input/select/read-only.test.ts
@@ -28,8 +28,7 @@ function setup() {
})
let under: SceneNode | null = rect
const fns: HitTestFns = {
- hitTestInScope: () => under,
- isInsideContainerBounds: () => false,
+ hitTestLayer: () => under,
hitTestFrameTitle: () => null,
hitTestSectionTitle: () => null,
hitTestComponentLabel: () => null
diff --git a/tests/e2e/canvas/section-clicks.spec.ts b/tests/e2e/canvas/section-clicks.spec.ts
index 3ae79e480..b9d9148fe 100644
--- a/tests/e2e/canvas/section-clicks.spec.ts
+++ b/tests/e2e/canvas/section-clicks.spec.ts
@@ -40,3 +40,53 @@ test('a right-click selects the frame or section whose empty area is under it',
await page.keyboard.press('Escape')
}
})
+
+test('a swatch reached by double-clicks, then clicks on other rows and sections, as in Figma', async () => {
+ const ids = await scene.buildSwatchRows()
+ await canvas.waitForRender()
+ const swatch = await scene.center(ids.lightSwatch)
+ const other = await scene.center(ids.lightRowTwoSwatch)
+ const dark = await scene.center(ids.darkSwatch)
+
+ // A click from nothing selects the row, the direct child of the section's top-level frame.
+ await canvas.click(swatch.x, swatch.y)
+ await expect.poll(() => scene.selection()).toEqual(['Light Row 1'])
+ await canvas.dblclick(swatch.x, swatch.y)
+ await expect.poll(() => scene.selection()).toEqual(['Card 2'])
+ await canvas.dblclick(swatch.x, swatch.y)
+ await expect.poll(() => scene.selection()).toEqual(['Light Row 1 Card 2'])
+ expect(await scene.entered()).toBe('Card 2')
+
+ // A swatch in another row selects that row, however deep the selection was.
+ await canvas.click(other.x, other.y)
+ await expect.poll(() => scene.selection()).toEqual(['Light Row 2'])
+ expect(await scene.entered()).toBeNull()
+ // A swatch in another section selects its row.
+ await canvas.click(dark.x, dark.y)
+ await expect.poll(() => scene.selection()).toEqual(['Dark Row 2'])
+ await canvas.dblclick(dark.x, dark.y)
+ await canvas.dblclick(dark.x, dark.y)
+ await expect.poll(() => scene.selection()).toEqual(['Dark Row 2 Card 1'])
+
+ // The page between the sections deselects and leaves every entered container.
+ await canvas.click(swatch.x, 330)
+ await expect.poll(() => scene.selection()).toEqual([])
+ expect(await scene.entered()).toBeNull()
+ canvas.assertNoErrors()
+})
+
+test('a section’s empty area deselects a selection and is selected only from nothing', async () => {
+ const ids = await scene.buildSwatchRows()
+ await canvas.waitForRender()
+ const swatch = await scene.center(ids.lightSwatch)
+ await canvas.click(swatch.x, swatch.y)
+ await canvas.dblclick(swatch.x, swatch.y)
+ await expect.poll(() => scene.selection()).toEqual(['Card 2'])
+
+ // The section's padding below its rows.
+ await canvas.click(70, 300)
+ await expect.poll(() => scene.selection()).toEqual([])
+ await canvas.click(70, 300)
+ await expect.poll(() => scene.selection()).toEqual(['Light'])
+ canvas.assertNoErrors()
+})
diff --git a/tests/e2e/canvas/top-level-frame-click.spec.ts b/tests/e2e/canvas/top-level-frame-click.spec.ts
index bc9a67b98..92f9e84f8 100644
--- a/tests/e2e/canvas/top-level-frame-click.spec.ts
+++ b/tests/e2e/canvas/top-level-frame-click.spec.ts
@@ -59,20 +59,44 @@ test('the empty area of a plain top-level frame stays background', async () => {
editor.canvas.assertNoErrors()
})
-test('repeated clicks at one point reach deeper layers, one level at a time', async () => {
+test('clicks keep the selected layer and double-clicks go one level deeper each', async () => {
const ids = await scene.nestedBoard()
await editor.canvas.waitForRender()
const point = await scene.at(ids.label, 20, 20)
- for (const expected of [ids.grid, ids.cell, ids.label]) {
+ // The board is top-level, so its child is one click away; a selected frame keeps its children
+ // a double-click away, as in Figma.
+ for (let i = 0; i < 2; i++) {
await editor.canvas.click(point.x, point.y)
+ await expect.poll(async () => (await scene.state()).selected).toEqual([ids.grid])
+ await editor.page.waitForTimeout(600)
+ }
+ for (const expected of [ids.cell, ids.label]) {
+ await editor.canvas.dblclick(point.x, point.y)
await expect.poll(async () => (await scene.state()).selected).toEqual([expected])
- // Apart enough not to count as a double-click, which goes one level deeper by itself.
await editor.page.waitForTimeout(600)
}
editor.canvas.assertNoErrors()
})
+test('a run of quick clicks goes one level deeper on each click after the first', async () => {
+ const ids = await scene.nestedBoard()
+ await editor.canvas.waitForRender()
+ const point = await scene.at(ids.label, 20, 20)
+ // Click, double-click, and a third click of the same run, each within the multi-click window.
+ const box = await editor.page.getByTestId('canvas-element').boundingBox()
+ if (!box) throw new Error('canvas bounds')
+ await editor.page.mouse.move(box.x + point.x, box.y + point.y)
+ await editor.page.mouse.down({ clickCount: 1 })
+ await editor.page.mouse.up({ clickCount: 1 })
+ await editor.page.mouse.down({ clickCount: 2 })
+ await editor.page.mouse.up({ clickCount: 2 })
+ await editor.page.mouse.down({ clickCount: 3 })
+ await editor.page.mouse.up({ clickCount: 3 })
+ await expect.poll(async () => (await scene.state()).selected).toEqual([ids.label])
+ editor.canvas.assertNoErrors()
+})
+
test('holding Cmd hovers the deepest layer, the one a Cmd-click selects', async () => {
const ids = await scene.nestedBoard()
await editor.canvas.waitForRender()
diff --git a/tests/e2e/editor/auto-layout/padding-editor.spec.ts b/tests/e2e/editor/auto-layout/padding-editor.spec.ts
index 00029dafd..8c425baa5 100644
--- a/tests/e2e/editor/auto-layout/padding-editor.spec.ts
+++ b/tests/e2e/editor/auto-layout/padding-editor.spec.ts
@@ -10,15 +10,9 @@ async function clickCanvas(page: Page, x: number, y: number) {
}
async function dblclickCanvas(page: Page, x: number, y: number) {
- const canvas = page.getByTestId('canvas-element')
- const box = await canvas.boundingBox()
+ const box = await page.getByTestId('canvas-element').boundingBox()
if (!box) throw new Error('Canvas has no bounding box')
- await canvas.dispatchEvent('dblclick', {
- clientX: box.x + x,
- clientY: box.y + y,
- bubbles: true,
- cancelable: true
- })
+ await page.mouse.dblclick(box.x + x, box.y + y)
}
async function setupAutoLayoutFrame(page: Page) {
diff --git a/tests/e2e/text/double-click-edit.spec.ts b/tests/e2e/text/double-click-edit.spec.ts
index 2a020a8c8..827cd756b 100644
--- a/tests/e2e/text/double-click-edit.spec.ts
+++ b/tests/e2e/text/double-click-edit.spec.ts
@@ -35,37 +35,115 @@ async function addTopLevelText(page: Page) {
})
}
-async function addFrameWithNestedText(page: Page) {
- return page.evaluate(() => {
+const WHITE = [
+ { type: 'SOLID' as const, color: { r: 1, g: 1, b: 1, a: 1 }, opacity: 1, visible: true }
+]
+
+/** A selected top-level card holding a text, directly or inside an inner frame. */
+async function addFrameWithNestedText(page: Page, inner = false) {
+ return page.evaluate(
+ ({ inner, white }) => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ store.state.zoom = 1
+ store.state.panX = 0
+ store.state.panY = 0
+ const pageId = store.state.currentPageId
+ const frame = store.graph.createNode('FRAME', pageId, {
+ name: 'Card',
+ x: 100,
+ y: 100,
+ width: 240,
+ height: 140,
+ fills: white
+ })
+ const holder = inner
+ ? store.graph.createNode('FRAME', frame.id, {
+ name: 'Inner',
+ x: 10,
+ y: 10,
+ width: 220,
+ height: 120,
+ fills: [
+ { type: 'SOLID', color: { r: 0.9, g: 0.9, b: 0.9, a: 1 }, opacity: 1, visible: true }
+ ]
+ })
+ : frame
+ const text = store.graph.createNode('TEXT', holder.id, {
+ name: 'Nested label',
+ text: 'Nested label',
+ x: 20,
+ y: 20,
+ width: 140,
+ height: 30,
+ fontSize: 18
+ })
+ store.select([frame.id])
+ store.requestRender()
+ return { frameId: frame.id, innerId: inner ? holder.id : null, textId: text.id }
+ },
+ { inner, white: WHITE }
+ )
+}
+
+const selectedIds = (page: Page) =>
+ page.evaluate(() => {
const store = window.openPencil?.getStore?.()
if (!store) throw new Error('OpenPencil store not initialized')
- store.state.zoom = 1
- store.state.panX = 0
- store.state.panY = 0
-
- const pageId = store.state.currentPageId
- const frame = store.graph.createNode('FRAME', pageId, {
- name: 'Card',
- x: 100,
- y: 100,
- width: 220,
- height: 120,
- fills: [{ type: 'SOLID', color: { r: 1, g: 1, b: 1, a: 1 }, opacity: 1, visible: true }]
- })
- const text = store.graph.createNode('TEXT', frame.id, {
- name: 'Nested label',
- text: 'Nested label',
- x: 20,
- y: 20,
- width: 140,
- height: 30,
- fontSize: 18
- })
- store.select([frame.id])
- store.requestRender()
- return { frameId: frame.id, textId: text.id }
+ return [...store.state.selectedIds]
})
-}
+
+test('double-clicks reach nested text one level at a time and edit it last', async ({ page }) => {
+ await page.goto('/?test')
+ const canvas = new CanvasHelper(page)
+ await canvas.waitForInit()
+ canvas.errors.length = 0
+ await canvas.clearCanvas()
+
+ const ids = await addFrameWithNestedText(page, true)
+ await canvas.waitForRender()
+
+ // Card is top-level, so a click reaches Inner; Inner's text takes a double-click to select and
+ // another to edit, as in Figma.
+ await canvas.click(145, 145)
+ await expect.poll(() => selectedIds(page)).toEqual([ids.innerId])
+ await page.waitForTimeout(600)
+ await canvas.dblclick(145, 145)
+ await expect.poll(() => selectedIds(page)).toEqual([ids.textId])
+ expect(await getEditingTextId(page)).toBeNull()
+ await page.waitForTimeout(600)
+ await canvas.dblclick(145, 145)
+ await expect.poll(() => getEditingTextId(page), { timeout: 3000 }).toBe(ids.textId)
+})
+
+test('quick clicks reach nested text and select it; a double-click then edits', async ({
+ page
+}) => {
+ await page.goto('/?test')
+ const canvas = new CanvasHelper(page)
+ await canvas.waitForInit()
+ canvas.errors.length = 0
+ await canvas.clearCanvas()
+
+ const ids = await addFrameWithNestedText(page, true)
+ await canvas.waitForRender()
+ await page.evaluate(() => window.openPencil?.getStore?.().clearSelection())
+
+ // Card is top-level: click one reaches Inner, click two the text, click three keeps it.
+ const box = await page.getByTestId('canvas-element').boundingBox()
+ if (!box) throw new Error('canvas bounds')
+ await page.mouse.move(box.x + 145, box.y + 145)
+ for (const [count, expected] of [ids.innerId, ids.textId, ids.textId].entries()) {
+ await page.mouse.down({ clickCount: count + 1 })
+ await page.mouse.up({ clickCount: count + 1 })
+ await expect.poll(() => selectedIds(page)).toEqual([expected])
+ await page.waitForTimeout(80)
+ }
+ expect(await getEditingTextId(page)).toBeNull()
+ await page.waitForTimeout(600)
+ await canvas.dblclick(145, 145)
+ await expect.poll(() => getEditingTextId(page), { timeout: 3000 }).toBe(ids.textId)
+})
test('double-clicking top-level text enters text edit mode', async ({ page }) => {
await page.goto('/?test')
@@ -111,13 +189,5 @@ test('double-click drill enters nested text edit mode', async ({ page }) => {
await canvas.dblclick(125, 125)
await expect.poll(() => getEditingTextId(page), { timeout: 3000 }).toBe(ids.textId)
- await expect
- .poll(() =>
- page.evaluate(() => {
- const store = window.openPencil?.getStore?.()
- if (!store) throw new Error('OpenPencil store not initialized')
- return [...store.state.selectedIds]
- })
- )
- .toEqual([ids.textId])
+ await expect.poll(() => selectedIds(page)).toEqual([ids.textId])
})
diff --git a/tests/engine/hit-test/scope.test.ts b/tests/engine/hit-test/scope.test.ts
index d02f2b272..703ff3796 100644
--- a/tests/engine/hit-test/scope.test.ts
+++ b/tests/engine/hit-test/scope.test.ts
@@ -93,16 +93,19 @@ describe('hitTest — nested groups', () => {
test('click from page scope returns GroupA', () => {
const { graph, page } = setup()
- const hit = graph.hitTest(100, 100, page)
+ // On the rectangle: a group has no area of its own, so its empty corner takes no click.
+ const hit = graph.hitTest(175, 175, page)
expect(hit).not.toBeNull()
expect(expectDefined(hit, 'hit node').name).toBe('GroupA')
+ expect(graph.hitTest(100, 100, page)).toBeNull()
})
test('click with scope=GroupA returns GroupB', () => {
const { graph, groupA } = setup()
- const hit = graph.hitTest(150, 150, groupA.id)
+ const hit = graph.hitTest(175, 175, groupA.id)
expect(hit).not.toBeNull()
expect(expectDefined(hit, 'hit node').name).toBe('GroupB')
+ expect(graph.hitTest(150, 150, groupA.id)).toBeNull()
})
test('click with scope=GroupB returns DeepRect', () => {
diff --git a/tests/engine/render/canvas/derived-text.test.ts b/tests/engine/render/canvas/derived-text.test.ts
index 0c1dd5958..abd42b7e1 100644
--- a/tests/engine/render/canvas/derived-text.test.ts
+++ b/tests/engine/render/canvas/derived-text.test.ts
@@ -83,9 +83,8 @@ describe('derived text rendering', () => {
})
const surface = expectDefined(ck.MakeSurface(1, 1), 'surface')
const renderer = new SkiaRenderer(ck, surface)
- renderer.nodeFontReadiness = () => {
- throw new Error('Saved text must not depend on font readiness')
- }
+ // Saved glyphs draw while the face is not the text's own; a loaded face lays the text out live.
+ renderer.nodeFontReadiness = () => 'substituted'
try {
const png = expectDefined(
renderNodesToImage(ck, renderer, graph, page.id, [text.id], {
diff --git a/tests/engine/render/canvas/raster-export.test.ts b/tests/engine/render/canvas/raster-export.test.ts
index 3fc9f21d2..92a2e8998 100644
--- a/tests/engine/render/canvas/raster-export.test.ts
+++ b/tests/engine/render/canvas/raster-export.test.ts
@@ -1,4 +1,4 @@
-import { beforeAll, describe, expect, test } from 'bun:test'
+import { beforeAll, describe, expect, mock, test } from 'bun:test'
import type { Canvas } from 'canvaskit-wasm'
@@ -50,6 +50,8 @@ describe('raster export', () => {
graph.createNode('RECTANGLE', page.id)
const viewport = { x: 1, y: 2, w: 3, h: 4 }
const renderer = {
+ editingTextId: null,
+ invalidateNodePicture: mock(() => undefined),
viewportImageRendering: true,
worldViewport: viewport,
nodePaths: new NodePathCaches(),
@@ -65,6 +67,30 @@ describe('raster export', () => {
expect(renderer.worldViewport).toBe(viewport)
})
+ test('draws the text being edited from its saved glyphs and drops its live picture', () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ graph.createNode('RECTANGLE', page.id)
+ const invalidated: string[] = []
+ const seen: Array<string | null> = []
+ const renderer = {
+ editingTextId: 'edited' as string | null,
+ invalidateNodePicture: mock((id: string) => {
+ invalidated.push(id)
+ }),
+ viewportImageRendering: false,
+ worldViewport: { x: 0, y: 0, w: 1, h: 1 },
+ nodePaths: new NodePathCaches(),
+ renderNode() {
+ seen.push(this.editingTextId)
+ }
+ }
+ renderSceneToCanvas(renderer, asDouble<Canvas>({}), graph, page.id)
+ expect(seen).toEqual([null])
+ expect(renderer.editingTextId).toBe('edited')
+ expect(invalidated).toEqual(['edited', 'edited'])
+ })
+
test('preserves transformed top-level nodes when preparing a page export', () => {
const graph = new SceneGraph()
const page = graph.getPages()[0]
diff --git a/tests/engine/render/canvas/text/render.test.ts b/tests/engine/render/canvas/text/render.test.ts
index a22393ba1..2947c72bc 100644
--- a/tests/engine/render/canvas/text/render.test.ts
+++ b/tests/engine/render/canvas/text/render.test.ts
@@ -221,6 +221,53 @@ describe('renderText', () => {
expect(canvas.saveLayer).not.toHaveBeenCalled()
})
+ test('lays text out live when its fonts are loaded, and draws saved glyphs for a substituted face', () => {
+ const node = textNode({
+ derivedTextGlyphs: [
+ { commandsBlob: new Uint8Array(), x: 0, y: 12, fontSize: 12, firstCharacter: 0, advance: 8 }
+ ]
+ })
+ const ready = createMockRenderer()
+ const readyCanvas = createMockCanvas()
+ renderText(ready, readyCanvas as never, node)
+ expect(ready.buildParagraph).toHaveBeenCalledTimes(1)
+ expect(readyCanvas.drawPath).not.toHaveBeenCalled()
+
+ const base = createMockRenderer()
+ const substituted = createMockRenderer({
+ nodeFontReadiness: mock(() => 'substituted'),
+ ck: { ...base.ck, FillType: { EvenOdd: 0, Winding: 1 } }
+ })
+ const substitutedCanvas = createMockCanvas()
+ renderText(substituted, substitutedCanvas as never, node)
+ expect(substituted.buildParagraph).not.toHaveBeenCalled()
+ expect(substitutedCanvas.drawPath).toHaveBeenCalled()
+ })
+
+ test('draws the text being edited from its live layout, not its saved glyphs', () => {
+ const node = textNode({
+ derivedTextGlyphs: [
+ { commandsBlob: new Uint8Array(), x: 0, y: 12, fontSize: 12, firstCharacter: 0, advance: 8 }
+ ]
+ })
+ const edited = createMockRenderer({ editingTextId: node.id })
+ const editedCanvas = createMockCanvas()
+ renderText(edited, editedCanvas as never, node)
+ expect(edited.buildParagraph).toHaveBeenCalledTimes(1)
+ expect(editedCanvas.drawPath).not.toHaveBeenCalled()
+
+ const base = createMockRenderer()
+ const other = createMockRenderer({
+ editingTextId: 'another',
+ nodeFontReadiness: mock(() => 'substituted'),
+ ck: { ...base.ck, FillType: { EvenOdd: 0, Winding: 1 } }
+ })
+ const otherCanvas = createMockCanvas()
+ renderText(other, otherCanvas as never, node)
+ expect(other.buildParagraph).not.toHaveBeenCalled()
+ expect(otherCanvas.drawPath).toHaveBeenCalled()
+ })
+
test('prefers resolved fonts over baked text pictures', () => {
const r = createMockRenderer()
const canvas = createMockCanvas()
diff --git a/tests/helpers/canvas/section-clicks/driver.ts b/tests/helpers/canvas/section-clicks/driver.ts
index c9669e331..ba32505bb 100644
--- a/tests/helpers/canvas/section-clicks/driver.ts
+++ b/tests/helpers/canvas/section-clicks/driver.ts
@@ -23,6 +23,46 @@ export function sectionClicksDriver(page: () => Page) {
}, PAN)
},
+ /** Builds the swatch rows and returns their ids. */
+ buildSwatchRows() {
+ return page().evaluate(async (pan) => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ const fixtureURL = '/tests/helpers/canvas/section-clicks/scene.ts'
+ const scene: typeof SectionScene = await import(fixtureURL)
+ const ids = scene.createSwatchRows(store.graph, store.state.currentPageId)
+ store.state.zoom = 1
+ store.state.panX = pan
+ store.state.panY = pan
+ store.clearSelection()
+ store.requestRender()
+ return ids
+ }, PAN)
+ },
+
+ /** The canvas point over a node's centre, for the canvas helper's clicks. */
+ center(id: string) {
+ return page().evaluate(
+ ({ id, pan }) => {
+ const store = window.openPencil?.getStore?.()
+ const node = store?.graph.getNode(id)
+ if (!store || !node) throw new Error('node not found')
+ const abs = store.graph.getAbsolutePosition(id)
+ return { x: pan + abs.x + node.width / 2, y: pan + abs.y + node.height / 2 }
+ },
+ { id, pan: PAN }
+ )
+ },
+
+ /** The entered container's name, or null on the page. */
+ entered() {
+ return page().evaluate(() => {
+ const store = window.openPencil?.getStore?.()
+ const id = store?.state.enteredContainerId
+ return id ? (store?.graph.getNode(id)?.name ?? null) : null
+ })
+ },
+
clearSelection() {
return page().evaluate(() => window.openPencil?.getStore?.().clearSelection())
},
diff --git a/tests/helpers/canvas/section-clicks/scene.ts b/tests/helpers/canvas/section-clicks/scene.ts
index 16d8b6493..1c3a58d1f 100644
--- a/tests/helpers/canvas/section-clicks/scene.ts
+++ b/tests/helpers/canvas/section-clicks/scene.ts
@@ -30,3 +30,84 @@ export function createSectionClickScene(graph: SceneGraph, pageId: string) {
})
graph.createNode('RECTANGLE', full.id, { name: 'Child', x: 10, y: 10, width: 40, height: 40 })
}
+
+const SWATCH: Fill[] = [
+ { type: 'SOLID', color: { r: 0.3, g: 0.5, b: 0.8, a: 1 }, opacity: 1, visible: true }
+]
+const LABEL: Fill[] = [
+ { type: 'SOLID', color: { r: 0.5, g: 0.5, b: 0.5, a: 1 }, opacity: 1, visible: true }
+]
+
+/**
+ * Two sections of swatch rows, as the shadcn kit's Foundations page lays them out and Figma
+ * desktop 126 was clicked on: section > unfilled auto layout frame > rows > cards > swatch. Rows
+ * are named `<section> Row <n>`, swatches `<row> Card <n>`.
+ */
+export function createSwatchRows(graph: SceneGraph, pageId: string) {
+ const build = (section: string, y: number) => {
+ const sectionNode = graph.createNode('SECTION', pageId, {
+ name: section,
+ y,
+ width: 760,
+ height: 260,
+ fills: WHITE
+ })
+ const rows = graph.createNode('FRAME', sectionNode.id, {
+ name: 'Rows',
+ x: 40,
+ y: 40,
+ width: 680,
+ height: 180,
+ fills: [],
+ layoutMode: 'VERTICAL',
+ itemSpacing: 20
+ })
+ const swatches: Record<string, string> = {}
+ for (const r of [1, 2]) {
+ const row = graph.createNode('FRAME', rows.id, {
+ name: `${section} Row ${r}`,
+ y: (r - 1) * 100,
+ width: 680,
+ height: 80,
+ fills: [],
+ layoutMode: 'HORIZONTAL',
+ itemSpacing: 20
+ })
+ for (const c of [1, 2, 3]) {
+ const card = graph.createNode('FRAME', row.id, {
+ name: `Card ${c}`,
+ x: (c - 1) * 140,
+ width: 120,
+ height: 80,
+ fills: [],
+ layoutMode: 'VERTICAL',
+ itemSpacing: 8
+ })
+ const swatch = graph.createNode('RECTANGLE', card.id, {
+ name: `${row.name} Card ${c}`,
+ width: 120,
+ height: 60,
+ fills: SWATCH
+ })
+ graph.createNode('RECTANGLE', card.id, {
+ name: 'Label',
+ y: 68,
+ width: 120,
+ height: 12,
+ fills: LABEL
+ })
+ swatches[swatch.name] = swatch.id
+ }
+ }
+ return { section: sectionNode.id, swatches }
+ }
+ const light = build('Light', 0)
+ const dark = build('Dark', 300)
+ return {
+ light: light.section,
+ lightSwatch: light.swatches['Light Row 1 Card 2'],
+ lightRowTwoSwatch: light.swatches['Light Row 2 Card 3'],
+ dark: dark.section,
+ darkSwatch: dark.swatches['Dark Row 2 Card 1']
+ }
+}