Skip to content

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

fix(svg): respect display and visibility during import (#1189)

PAVEL TKACHEV38dfc27bf21d
diff --git a/changes/1189/fixed.md b/changes/1189/fixed.md
new file mode 100644
index 000000000..4930781f3
--- /dev/null
+++ b/changes/1189/fixed.md
@@ -0,0 +1,2 @@
+- SVG import keeps content hidden by `visibility` or `display` as hidden layers, as Figma does, instead of painting it, and icons, inline SVG in design JSX, and image vectorization leave it out (#1166).
+- Groups span only their visible layers and refit when a layer inside is hidden or shown, as in Figma.
diff --git a/packages/core/src/editor/components/authoring/visibility-edit.ts b/packages/core/src/editor/components/authoring/visibility-edit.ts
index d3679eef3..6dc5b4d47 100644
--- a/packages/core/src/editor/components/authoring/visibility-edit.ts
+++ b/packages/core/src/editor/components/authoring/visibility-edit.ts
@@ -8,6 +8,7 @@ import {
} from '@open-pencil/scene-graph/components'
import { cloneInstanceOverrideState } from '@open-pencil/scene-graph/instances/overrides'
+import { refitGroupsAroundLayers } from '#core/editor/structure/group/bounds'
import type { EditorContext } from '#core/editor/types'
/** Whether a boolean property drives the layer's visibility. */
@@ -57,12 +58,14 @@ export function applyBoundVisibilityEdit(
const after = snapshot()
// The property already had the value, as when another layer it drives was just shown.
if (isEqual(before, after)) return true
+ refitGroupsAroundLayers(ctx, layers)
const apply = (values: typeof before) => {
ctx.graph.updateNode(instance.id, {
componentPropertyAssignments: { ...values.componentPropertyAssignments },
instanceOverrides: cloneInstanceOverrideState(values.instanceOverrides)
})
for (const [id, shown] of values.layers) ctx.graph.updateNode(id, { visible: shown })
+ refitGroupsAroundLayers(ctx, layers)
ctx.runLayoutForNode(instance.id)
ctx.requestRender()
}
diff --git a/packages/core/src/editor/nodes.ts b/packages/core/src/editor/nodes.ts
index b0081d698..e1cd39382 100644
--- a/packages/core/src/editor/nodes.ts
+++ b/packages/core/src/editor/nodes.ts
@@ -12,6 +12,7 @@ import { applyBoundVisibilityEdit, bindsVisibility } from './components/authorin
import { createLayoutModeActions } from './layout-mode'
import { createNodePreviewActions } from './node-preview'
import { createNudgeActions } from './nudge'
+import { refitGroupsAroundLayers } from './structure/group/bounds'
import { pathTextEditChanges } from './text/path-edit'
import type { EditorContext } from './types'
import { createVariableBindingActions } from './variable-bindings'
@@ -35,6 +36,7 @@ export function createNodeActions(ctx: EditorContext) {
function runChangedLayout(id: string, changes: Partial<SceneNode>) {
// A layer's modes reach the layers inside it.
if (changes.variableModes) reconcileVariableLayouts(ctx.graph, { subtrees: [id] })
+ if (changes.visible !== undefined) refitGroupsAroundLayers(ctx, [id])
ctx.runLayoutForNode(id)
}
diff --git a/packages/core/src/editor/structure/container-wrap.ts b/packages/core/src/editor/structure/container-wrap.ts
index ef9ed10bb..4e0e94174 100644
--- a/packages/core/src/editor/structure/container-wrap.ts
+++ b/packages/core/src/editor/structure/container-wrap.ts
@@ -1,5 +1,6 @@
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import { getAxisAlignedBoundsInParent } from '@open-pencil/scene-graph/coordinate'
+import { groupBounds } from '@open-pencil/scene-graph/group-bounds'
import { prepareSlotEdits } from '#core/editor/components/slots'
import { nextNumberedName } from '#core/editor/structure/rename'
@@ -52,7 +53,11 @@ export function wrapNodes(
index: number | undefined,
props: Partial<SceneNode> = {}
): SceneNode {
- const bounds = getAxisAlignedBoundsInParent(nodes, parentId, graph)
+ // A group spans only the layers it shows, as Figma's does; other containers span them all.
+ const bounds =
+ type === 'GROUP'
+ ? groupBounds(graph, inStackOrder(graph, nodes, parentId), parentId, { x: 0, y: 0 })
+ : getAxisAlignedBoundsInParent(nodes, parentId, graph)
const container = graph.createNode(type, parentId, {
name: CONTAINER_NAMES[type],
...bounds,
diff --git a/packages/core/src/editor/structure/group/bounds.ts b/packages/core/src/editor/structure/group/bounds.ts
index a8cb3c660..17decbb21 100644
--- a/packages/core/src/editor/structure/group/bounds.ts
+++ b/packages/core/src/editor/structure/group/bounds.ts
@@ -1,3 +1,5 @@
+import { compact } from 'es-toolkit/array'
+
import {
fitEnclosingGroups,
redoGroupFit,
@@ -24,3 +26,13 @@ export function fitEnclosingGroupsWithUndo(ctx: EditorContext, parentIds: Iterab
inverse: () => undoGroupFit(ctx.graph, fit)
})
}
+
+/**
+ * Refits the groups around layers that were shown or hidden, since a group spans only the layers
+ * it shows. The fit follows from what the layers show, so an edit that replays on undo and redo
+ * refits again and needs no undo step of its own.
+ */
+export function refitGroupsAroundLayers(ctx: EditorContext, layerIds: Iterable<string>) {
+ const parentIds = compact([...layerIds].map((id) => ctx.graph.getNode(id)?.parentId))
+ fitEnclosingGroups(ctx.graph, parentIds, groupFitOptions(ctx.getRenderer(), ctx.graph))
+}
diff --git a/packages/core/src/editor/structure/state.ts b/packages/core/src/editor/structure/state.ts
index 0a6391514..0f1d7ab3b 100644
--- a/packages/core/src/editor/structure/state.ts
+++ b/packages/core/src/editor/structure/state.ts
@@ -9,11 +9,12 @@ import {
applyBoundVisibilityEdit,
bindsVisibility
} from '#core/editor/components/authoring/visibility-edit'
+import { refitGroupsAroundLayers } from '#core/editor/structure/group/bounds'
import type { EditorContext } from '#core/editor/types'
export function createStructureStateActions(ctx: EditorContext) {
/** Shows or hides a layer; one a boolean property drives sets the property, as in Figma. */
- function setNodeVisibility(id: string, visible: boolean) {
+ function applyNodeVisibility(id: string, visible: boolean) {
const node = ctx.graph.getNode(id)
if (!node) return
const owner = findInstanceAncestor(ctx.graph, id)
@@ -24,7 +25,9 @@ export function createStructureStateActions(ctx: EditorContext) {
const show = (shown: boolean) => {
ctx.graph.updateNode(id, { visible: shown })
const parentId = ctx.graph.getNode(id)?.parentId
- if (parentId) ctx.runLayoutForNode(parentId)
+ if (!parentId) return
+ ctx.runLayoutForNode(parentId)
+ refitGroupsAroundLayers(ctx, [id])
}
const forward = () => {
const instance = findInstanceAncestor(ctx.graph, id)
@@ -46,10 +49,15 @@ export function createStructureStateActions(ctx: EditorContext) {
})
}
+ function setNodeVisibility(id: string, visible: boolean) {
+ assertNodeEditable(ctx.graph, id)
+ applyNodeVisibility(id, visible)
+ }
+
function toggleNodeVisibility(id: string) {
assertNodeEditable(ctx.graph, id)
const node = ctx.graph.getNode(id)
- if (node) setNodeVisibility(id, !node.visible)
+ if (node) applyNodeVisibility(id, !node.visible)
}
function toggleNodeLock(id: string) {
@@ -74,7 +82,7 @@ export function createStructureStateActions(ctx: EditorContext) {
return node ? [[id, !node.visible] as const] : []
})
ctx.undo.runBatch('Toggle visibility', () => {
- for (const [id, visible] of targets) setNodeVisibility(id, visible)
+ for (const [id, visible] of targets) applyNodeVisibility(id, visible)
})
}
@@ -85,5 +93,5 @@ export function createStructureStateActions(ctx: EditorContext) {
})
}
- return { toggleNodeVisibility, toggleNodeLock, toggleVisibility, toggleLock }
+ return { setNodeVisibility, toggleNodeVisibility, toggleNodeLock, toggleVisibility, toggleLock }
}
diff --git a/packages/core/src/figma-api/accessor-utils.ts b/packages/core/src/figma-api/accessor-utils.ts
index 4fa251480..8884510c7 100644
--- a/packages/core/src/figma-api/accessor-utils.ts
+++ b/packages/core/src/figma-api/accessor-utils.ts
@@ -82,8 +82,9 @@ export function prepareFollowedFieldEdit(
if (scope.kind === 'slot') claimSlotContent(scene, scope)
}
-/** Fields whose change can move a node's bounds, so the groups around it refit. */
+/** Fields whose change can move a node's bounds or drop it from its group's, so groups refit. */
const GEOMETRY_FIELDS: ReadonlySet<string> = new Set([
+ 'visible',
'x',
'y',
'width',
diff --git a/packages/core/src/figma-api/proxy.ts b/packages/core/src/figma-api/proxy.ts
index 12956ab92..680018ff9 100644
--- a/packages/core/src/figma-api/proxy.ts
+++ b/packages/core/src/figma-api/proxy.ts
@@ -307,6 +307,8 @@ export class FigmaNodeProxy {
set isMask(v: boolean) {
prepareFollowedFieldEdit(this[INTERNAL_GRAPH], this._raw(), 'isMask', 'is-mask')
this._update({ isMask: v })
+ // A mask limits what its group spans.
+ fitGroupsAround(this[INTERNAL_GRAPH], this._raw().parentId, this[INTERNAL_API].groupFitOptions)
}
get maskType(): string {
diff --git a/packages/core/src/icons/svg.ts b/packages/core/src/icons/svg.ts
index 3fac97502..d30edefd7 100644
--- a/packages/core/src/icons/svg.ts
+++ b/packages/core/src/icons/svg.ts
@@ -14,7 +14,8 @@ import {
normalizeSVGPaint,
num,
opacityValue,
- presentationFor
+ presentationFor,
+ presentationVisible
} from './svg/presentation'
import { elementLayer, type Scope, type Traversal } from './svg/scope'
import { textInfo } from './svg/text'
@@ -193,8 +194,14 @@ function collectClipPath(
)
return {
id: match[1],
- paths: paths.map(({ d, fillRule, transform }) => ({ d, fillRule, transform })),
- units
+ paths: paths.map((path) => ({
+ d: path.d,
+ fillRule: path.fillRule,
+ transform: path.transform,
+ visible: isSVGPathShown(path)
+ })),
+ units,
+ visible: presentationVisible(presentationFor(target, DEFAULT_PRESENTATION))
}
}
@@ -305,7 +312,7 @@ export function extractPathsFromElements(
const root = svgDocument.documentElement
if (!root) return []
appendSVGElement(svgDocument, root, { type: 'svg', props: rootProps, children: elements })
- return collectDocument(root).paths
+ return collectDocument(root).paths.filter(isSVGPathShown)
}
export function extractSVGContent(svgBody: string): SVGContent {
@@ -313,8 +320,14 @@ export function extractSVGContent(svgBody: string): SVGContent {
return root ? collectDocument(root) : { paths: [], texts: [] }
}
+/** Whether a shape shows: a hidden element hides everything in it, as a hidden layer does. */
+export function isSVGPathShown(path: Pick<IconPathInfo, 'elements'>): boolean {
+ return path.elements.every((element) => element.visible)
+}
+
+/** The shapes an SVG shows, for drawing it as one icon rather than importing its layers. */
export function extractPaths(svgBody: string): IconPathInfo[] {
- return extractSVGContent(svgBody).paths
+ return extractSVGContent(svgBody).paths.filter(isSVGPathShown)
}
export function buildIconData(
diff --git a/packages/core/src/icons/svg/presentation.ts b/packages/core/src/icons/svg/presentation.ts
index 131f9d630..f46bd0247 100644
--- a/packages/core/src/icons/svg/presentation.ts
+++ b/packages/core/src/icons/svg/presentation.ts
@@ -17,6 +17,8 @@ export interface PresentationAttributes {
textAnchor: string
letterSpacing: string
textDecoration: string
+ visibility: string
+ display: string
}
export const DEFAULT_PRESENTATION: PresentationAttributes = {
@@ -34,7 +36,9 @@ export const DEFAULT_PRESENTATION: PresentationAttributes = {
fontStyle: 'normal',
textAnchor: 'start',
letterSpacing: 'normal',
- textDecoration: 'none'
+ textDecoration: 'none',
+ visibility: 'visible',
+ display: 'inline'
}
export function isElement(node: Node): node is Element {
@@ -87,10 +91,20 @@ export function presentationFor(
fontStyle: attribute('font-style', inherited.fontStyle),
textAnchor: attribute('text-anchor', inherited.textAnchor),
letterSpacing: attribute('letter-spacing', inherited.letterSpacing),
- textDecoration: attribute('text-decoration', inherited.textDecoration)
+ textDecoration: attribute('text-decoration', inherited.textDecoration),
+ // As Figma reads them: both inherit, unlike CSS `display`; any visibility but `visible`
+ // hides, `inherit` included, and any display but `none` shows.
+ visibility:
+ attribute('visibility', inherited.visibility).trim() === 'visible' ? 'visible' : 'hidden',
+ display: attribute('display', inherited.display).trim() === 'none' ? 'none' : 'inline'
}
}
+/** Whether an element with these attributes shows: `visibility: visible`, not `display: none`. */
+export function presentationVisible(presentation: PresentationAttributes): boolean {
+ return presentation.visibility === 'visible' && presentation.display !== 'none'
+}
+
/** An SVG opacity, a number or a percentage, clamped to 0–1. */
export function opacityValue(value: string | null | undefined): number {
if (!value) return 1
diff --git a/packages/core/src/icons/svg/scope.ts b/packages/core/src/icons/svg/scope.ts
index 08b63db7b..3dd8dbff8 100644
--- a/packages/core/src/icons/svg/scope.ts
+++ b/packages/core/src/icons/svg/scope.ts
@@ -2,7 +2,12 @@ import type { Element } from '@xmldom/xmldom'
import type { SVGClipPathRegion, SVGElementLayer, SVGTextInfo } from '#core/icons/types'
-import { inlineStyles, opacityValue, type PresentationAttributes } from './presentation'
+import {
+ inlineStyles,
+ opacityValue,
+ presentationVisible,
+ type PresentationAttributes
+} from './presentation'
export interface Traversal {
root: Element
@@ -27,7 +32,7 @@ export function elementLayer(
traversal: Traversal,
element: Element,
kind: SVGElementLayer['kind'],
- scope: Pick<Scope, 'referenced'>,
+ scope: Pick<Scope, 'presentation' | 'referenced'>,
clip: number | null
): SVGElementLayer {
return {
@@ -35,6 +40,7 @@ export function elementLayer(
kind,
name: scope.referenced ? null : element.getAttribute('id') || null,
opacity: opacityValue(inlineStyles(element).get('opacity') ?? element.getAttribute('opacity')),
+ visible: presentationVisible(scope.presentation),
clip
}
}
diff --git a/packages/core/src/icons/types.ts b/packages/core/src/icons/types.ts
index 7d01612e3..1e34c93b4 100644
--- a/packages/core/src/icons/types.ts
+++ b/packages/core/src/icons/types.ts
@@ -76,6 +76,8 @@ export interface SVGElementLayer {
/** The element's `id`, when it is drawn directly rather than through `<use>`. */
name: string | null
opacity: number
+ /** False when `visibility` or `display` hides it; Figma imports it as a hidden layer. */
+ visible: boolean
/** The clip region this element adds to `clipPaths`, by index. */
clip: number | null
}
@@ -113,11 +115,16 @@ export interface SVGTextInfo {
pathIndex: number
}
-export type SVGClipPathInfo = Pick<IconPathInfo, 'd' | 'fillRule' | 'transform'>
+export type SVGClipPathInfo = Pick<IconPathInfo, 'd' | 'fillRule' | 'transform'> & {
+ /** False when `visibility` or `display` hides the shape, which Figma keeps as a hidden layer. */
+ visible: boolean
+}
export interface SVGClipPathRegion {
/** The `<clipPath>` element's `id`. */
id: string
paths: SVGClipPathInfo[]
units: 'userSpaceOnUse' | 'objectBoundingBox'
+ /** False when the `<clipPath>` itself is hidden: Figma's mask is then hidden and clips nothing. */
+ visible: boolean
}
diff --git a/packages/core/src/io/formats/svg/import.ts b/packages/core/src/io/formats/svg/import.ts
index 3825af2f3..eeef41e73 100644
--- a/packages/core/src/io/formats/svg/import.ts
+++ b/packages/core/src/io/formats/svg/import.ts
@@ -68,10 +68,16 @@ function createClipGroup(
parentIds: Set<string>
): string {
const groupId = createGroup(graph, parentId, { name: 'Clip path group' })
- const maskId = createGroup(graph, groupId, { name: clip.id, isMask: true, maskType: 'VECTOR' })
+ const maskId = createGroup(graph, groupId, {
+ name: clip.id,
+ isMask: true,
+ maskType: 'VECTOR',
+ visible: clip.visible
+ })
for (const shape of clip.shapes) {
- createPlacedVector(graph, maskId, shape, {
+ createPlacedVector(graph, maskId, shape.network, {
name: 'Vector',
+ visible: shape.visible,
fills: [{ type: 'SOLID', color: BLACK, opacity: 1, visible: true }]
})
}
@@ -103,6 +109,7 @@ function drawables(graph: SceneGraph, data: SVGImportData, parentIds: Set<string
const vector = createPlacedVector(graph, parentId, path.vectorNetwork, {
name: element.name ?? 'Vector',
opacity: element.opacity,
+ visible: element.visible,
...vectorizedPathPaints(path)
})
if (vector) parentIds.add(parentId)
@@ -151,7 +158,8 @@ function createSVGLayers(graph: SceneGraph, rootId: string, data: SVGImportData)
if (clip) parentId = createClipGroup(graph, parentId, clip, parentIds)
parentId = createGroup(graph, parentId, {
name: element.name ?? 'Group',
- opacity: element.opacity
+ opacity: element.opacity,
+ visible: element.visible
})
open.push({ key: element.key, parentId })
}
diff --git a/packages/core/src/io/formats/svg/text/import.ts b/packages/core/src/io/formats/svg/text/import.ts
index 703d97d29..93f703a36 100644
--- a/packages/core/src/io/formats/svg/text/import.ts
+++ b/packages/core/src/io/formats/svg/text/import.ts
@@ -120,13 +120,15 @@ export function createSVGText(
if (text.pieces.length === 1) {
createTextPiece(graph, parentId, text.pieces[0], text.matrix, {
...(element.name ? { name: element.name } : {}),
- opacity: element.opacity
+ opacity: element.opacity,
+ visible: element.visible
})
return
}
const groupId = createGroup(parentId, {
name: element.name ?? 'Group',
- opacity: element.opacity
+ opacity: element.opacity,
+ visible: element.visible
})
for (const piece of text.pieces) createTextPiece(graph, groupId, piece, text.matrix, {})
}
diff --git a/packages/core/src/vector/vectorize/placement.ts b/packages/core/src/vector/vectorize/placement.ts
index 8cb7ba56c..41777ce1e 100644
--- a/packages/core/src/vector/vectorize/placement.ts
+++ b/packages/core/src/vector/vectorize/placement.ts
@@ -2,6 +2,7 @@ import type { SceneGraph, SceneNode, VectorNetwork } from '@open-pencil/scene-gr
import type { Rect } from '@open-pencil/scene-graph/primitives'
import { pathStrokeLineStyle } from '#core/icons/path-style'
+import { isSVGPathShown } from '#core/icons/svg'
import { computeAccurateBounds } from '#core/vector/curve-math'
import type { SVGVectorizeResult, VectorizedPath } from './svg/to-vectors'
@@ -127,7 +128,7 @@ export function createVectorFrameChildren(
vectorized: SVGVectorizeResult,
placement: VectorFramePlacement
): void {
- for (const [index, path] of vectorized.paths.entries()) {
+ for (const [index, path] of vectorized.paths.filter(isSVGPathShown).entries()) {
createPlacedVector(
graph,
frameId,
diff --git a/packages/core/src/vector/vectorize/svg/to-vectors.ts b/packages/core/src/vector/vectorize/svg/to-vectors.ts
index c2191f88d..91463b45c 100644
--- a/packages/core/src/vector/vectorize/svg/to-vectors.ts
+++ b/packages/core/src/vector/vectorize/svg/to-vectors.ts
@@ -15,8 +15,15 @@ import { parseSVGPath } from '@open-pencil/scene-graph/parse-path'
import type { Rect, Size, Vector } from '@open-pencil/scene-graph/primitives'
import { createPathStroke } from '#core/icons/path-style'
-import { extractSVGContent } from '#core/icons/svg'
-import type { IconPathInfo, SVGElementLayer, SVGTextPiece, SVGTextRun } from '#core/icons/types'
+import { extractSVGContent, isSVGPathShown } from '#core/icons/svg'
+import type {
+ IconPathInfo,
+ SVGClipPathInfo,
+ SVGClipPathRegion,
+ SVGElementLayer,
+ SVGTextPiece,
+ SVGTextRun
+} from '#core/icons/types'
import { parseSVGSize, parseSVGViewBox } from '#core/io/formats/svg/metadata'
import { computeAccurateBounds } from '#core/vector/curve-math'
@@ -68,8 +75,10 @@ function resolveStrokes(path: IconPathInfo, defaultColor: string, strokeScale =
export interface VectorizedClip {
/** The `<clipPath>` element's `id`. */
id: string
- /** One network per clip shape. */
- shapes: VectorNetwork[]
+ /** False when the `<clipPath>` itself is hidden, so it clips nothing. */
+ visible: boolean
+ /** One network per clip shape, hidden ones included, as Figma keeps them. */
+ shapes: Array<{ network: VectorNetwork; visible: boolean }>
}
export interface VectorizedPath {
@@ -98,7 +107,7 @@ export interface VectorizedText {
export interface SVGVectorizeResult {
paths: VectorizedPath[]
texts: VectorizedText[]
- /** Tight bounds of path geometry in the target coordinate space. */
+ /** Tight bounds of the shown paths' geometry in the target coordinate space. */
contentBounds: Rect
}
@@ -169,7 +178,7 @@ export function svgToVectorPaths(
elements: text.elements,
pathIndex: text.pathIndex
})),
- contentBounds: unionPathBounds(vectorized)
+ contentBounds: unionPathBounds(vectorized.filter(isSVGPathShown))
}
}
@@ -190,27 +199,38 @@ function vectorizeClips(
if (cached) return cached
const clips = clipPaths.map((clipRegion) => ({
id: clipRegion.id,
+ visible: clipRegion.visible,
shapes:
clipRegion.units === 'objectBoundingBox' && !objectBounds
? []
- : clipRegion.paths.map((clipPath) => {
- let clipData = applySVGTransformToPath(clipPath.d, clipPath.transform ?? null)
- if (clipRegion.units === 'objectBoundingBox' && objectBounds) {
- clipData = svgpath(clipData)
- .scale(objectBounds.width, objectBounds.height)
- .translate(objectBounds.x, objectBounds.y)
- .toString()
- return parseSVGPath(clipData, clipPath.fillRule, { includeOpenRegions: true })
- }
- return parseSVGPath(mapSVGPathToViewport(clipData, viewport), clipPath.fillRule, {
- includeOpenRegions: true
- })
- })
+ : clipRegion.paths.map((clipPath) => ({
+ network: clipNetwork(clipPath, clipRegion.units, viewport, objectBounds),
+ visible: clipPath.visible
+ }))
}))
if (!hasObjectBoundingBoxClip) cache.set(clipPaths, clips)
return clips
}
+function clipNetwork(
+ clipPath: SVGClipPathInfo,
+ units: SVGClipPathRegion['units'],
+ viewport: SVGViewportMapping,
+ objectBounds: Rect | null
+): VectorNetwork {
+ let clipData = applySVGTransformToPath(clipPath.d, clipPath.transform ?? null)
+ if (units === 'objectBoundingBox' && objectBounds) {
+ clipData = svgpath(clipData)
+ .scale(objectBounds.width, objectBounds.height)
+ .translate(objectBounds.x, objectBounds.y)
+ .toString()
+ return parseSVGPath(clipData, clipPath.fillRule, { includeOpenRegions: true })
+ }
+ return parseSVGPath(mapSVGPathToViewport(clipData, viewport), clipPath.fillRule, {
+ includeOpenRegions: true
+ })
+}
+
/** The matrix taking an element's own coordinates, under `transform`, into the target space. */
function transformMatrix(transform: string | null, viewport: SVGViewportMapping): Mat3 {
const points: Vector[] = []
diff --git a/packages/core/tests/editor/components/properties.test.ts b/packages/core/tests/editor/components/properties.test.ts
index 6f7cd9f3c..4698cf8b1 100644
--- a/packages/core/tests/editor/components/properties.test.ts
+++ b/packages/core/tests/editor/components/properties.test.ts
@@ -41,6 +41,52 @@ function setupComponentProperties() {
}
describe('component property actions', () => {
+ test('a layer a boolean property hides leaves its group, which refits, and undo restores it', () => {
+ const editor = createEditor()
+ const pageId = editor.state.currentPageId
+ const component = editor.graph.createNode('COMPONENT', pageId, {
+ name: 'Card',
+ width: 200,
+ height: 200,
+ componentPropertyDefinitions: [
+ { id: '10:2', name: 'Show icon', type: 'BOOLEAN', defaultValue: 'true' }
+ ]
+ })
+ const group = editor.graph.createNode('GROUP', component.id, {
+ name: 'Content',
+ width: 130,
+ height: 130
+ })
+ editor.graph.createNode('RECTANGLE', group.id, { name: 'Body', width: 50, height: 50 })
+ editor.graph.createNode('RECTANGLE', group.id, {
+ name: 'Icon',
+ x: 100,
+ y: 100,
+ width: 30,
+ height: 30,
+ componentPropertyReferences: [{ propertyId: '10:2', field: 'VISIBLE' }]
+ })
+ const instance = editor.graph.createInstance(component.id, pageId)
+ if (!instance) throw new Error('Expected card instance')
+ const content = childByName(editor, instance.id, 'Content')
+ const icon = content && childByName(editor, content.id, 'Icon')
+ if (!content || !icon) throw new Error('Expected group copy')
+ const size = () => {
+ const node = editor.graph.getNode(content.id)
+ return [node?.width, node?.height]
+ }
+
+ editor.toggleNodeVisibility(icon.id)
+ expect(size()).toEqual([50, 50])
+ editor.undo.undo()
+ expect(size()).toEqual([130, 130])
+
+ editor.updateNodeWithUndo(icon.id, { visible: false }, 'Hide')
+ expect(size()).toEqual([50, 50])
+ editor.undo.undo()
+ expect(size()).toEqual([130, 130])
+ })
+
test('hiding a layer a boolean property shows sets the property, as Figma does', () => {
const { editor, component, instance } = setupComponentProperties()
editor.graph.createNode('FRAME', component.id, {
diff --git a/packages/core/tests/editor/structure/state.test.ts b/packages/core/tests/editor/structure/state.test.ts
index ae97e2e4a..5480b0a38 100644
--- a/packages/core/tests/editor/structure/state.test.ts
+++ b/packages/core/tests/editor/structure/state.test.ts
@@ -7,6 +7,31 @@ import { createEditor } from '@open-pencil/core'
import { computeAllLayouts } from '@open-pencil/core/layout'
describe('structure state actions', () => {
+ test('hiding a layer refits its group, and undo puts the group back', () => {
+ const editor = createEditor()
+ const page = editor.state.currentPageId
+ const a = rect(editor.graph, page, 50, 50)
+ const b = rect(editor.graph, page, 30, 30, { x: 100, y: 100 })
+ editor.select([a.id, b.id])
+ editor.groupSelected()
+ const group = getNodeOrThrow(editor.graph, [...editor.state.selectedIds][0])
+ const box = () => {
+ const { x, y, width, height } = getNodeOrThrow(editor.graph, group.id)
+ return [x, y, width, height]
+ }
+ expect(box()).toEqual([0, 0, 130, 130])
+
+ editor.toggleNodeVisibility(b.id)
+ expect(box()).toEqual([0, 0, 50, 50])
+ editor.setNodeVisibility(a.id, false)
+ expect(box()).toEqual([0, 0, 0, 0])
+
+ editor.undo.undo()
+ editor.undo.undo()
+ expect(box()).toEqual([0, 0, 130, 130])
+ expect(getNodeOrThrow(editor.graph, b.id)).toMatchObject({ x: 100, y: 100, visible: true })
+ })
+
test('toggleNodeVisibility reflows HUG auto-layout instance slots', async () => {
const editor = createEditor()
const page = editor.state.currentPageId
diff --git a/packages/core/tests/editor/vectorize.test.ts b/packages/core/tests/editor/vectorize.test.ts
index 74411dea5..cfcbb5478 100644
--- a/packages/core/tests/editor/vectorize.test.ts
+++ b/packages/core/tests/editor/vectorize.test.ts
@@ -70,6 +70,30 @@ describe('replaceNodeWithVectorFrame', () => {
expect(editor.graph.getNode(source.id)).toBeUndefined()
})
+ test('leaves out paths the SVG hides', () => {
+ const editor = createEditor()
+ const page = expectDefined(editor.graph.getPages()[0], 'page')
+ const source = editor.graph.createNode('RECTANGLE', page.id, { width: 100, height: 100 })
+ const vectorized = expectDefined(
+ svgToVectorPaths(
+ `<svg viewBox="0 0 100 100">
+ <path d="M0 0 H100 V100 H0 Z" visibility="hidden"/>
+ <path d="M25 25 H75 V75 H25 Z" fill="#336699"/>
+ </svg>`,
+ { width: 100, height: 100 }
+ ),
+ 'vectorized SVG'
+ )
+
+ const frameId = expectDefined(
+ editor.replaceNodeWithVectorFrame(source.id, vectorized),
+ 'replacement frame'
+ )
+ const frame = getNodeOrThrow(editor.graph, frameId)
+ expect(frame).toMatchObject({ x: 25, y: 25, width: 50, height: 50 })
+ expect(frame.childIds).toHaveLength(1)
+ })
+
test('preserves the coordinate box and rotation of rotated images', () => {
const editor = createEditor()
const page = expectDefined(editor.graph.getPages()[0], 'page')
diff --git a/packages/core/tests/figma-api/group-coordinates.test.ts b/packages/core/tests/figma-api/group-coordinates.test.ts
index a8192276d..87e5bd2f7 100644
--- a/packages/core/tests/figma-api/group-coordinates.test.ts
+++ b/packages/core/tests/figma-api/group-coordinates.test.ts
@@ -75,3 +75,66 @@ describe('group children in the plugin API', () => {
expect(group.removed).toBe(true)
})
})
+
+// Recorded in Figma desktop 126 on the page: a group spans only the layers it shows.
+describe('hidden group children in the plugin API', () => {
+ function pageRects(...boxes: Array<[number, number, number, number]>) {
+ const figma = new FigmaAPI(new SceneGraph())
+ const nodes = boxes.map(([x, y, width, height]) => {
+ const node = figma.createRectangle()
+ node.resize(width, height)
+ node.x = x
+ node.y = y
+ return node
+ })
+ return { figma, nodes }
+ }
+
+ test('hiding and showing a child refits the group; with none shown it is empty in place', () => {
+ const { figma, nodes } = pageRects([200, 200, 50, 50], [300, 300, 30, 30])
+ const [a, b] = nodes
+ const group = figma.group(nodes, figma.currentPage)
+ a.visible = false
+ expect(box(group)).toEqual([300, 300, 30, 30])
+ b.visible = false
+ expect(box(group)).toEqual([300, 300, 0, 0])
+ expect([box(a), box(b)]).toEqual([
+ [200, 200, 50, 50],
+ [300, 300, 30, 30]
+ ])
+ a.visible = true
+ expect(box(group)).toEqual([200, 200, 50, 50])
+ })
+
+ test('a hidden child of a nested group leaves both groups', () => {
+ const { figma, nodes } = pageRects([0, 0, 50, 50], [100, 100, 30, 30], [200, 0, 10, 10])
+ const [a, b, c] = nodes
+ const inner = figma.group([a, b], figma.currentPage)
+ const outer = figma.group([inner, c], figma.currentPage)
+ b.visible = false
+ expect(box(inner)).toEqual([0, 0, 50, 50])
+ expect(box(outer)).toEqual([0, 0, 210, 50])
+ inner.visible = false
+ expect(box(outer)).toEqual([200, 0, 10, 10])
+ })
+
+ test('a hidden mask stops limiting the group', () => {
+ const { figma, nodes } = pageRects([0, 0, 40, 40], [20, 20, 100, 100])
+ const [mask] = nodes
+ const group = figma.group(nodes, figma.currentPage)
+ mask.isMask = true
+ expect(box(group)).toEqual([0, 0, 40, 40])
+ mask.visible = false
+ expect(box(group)).toEqual([20, 20, 100, 100])
+ })
+
+ test('grouping spans the shown layers, or none at the origin', () => {
+ const { figma, nodes } = pageRects([500, 500, 50, 50], [600, 600, 30, 30])
+ nodes[0].visible = false
+ expect(box(figma.group(nodes, figma.currentPage))).toEqual([600, 600, 30, 30])
+
+ const hidden = pageRects([500, 500, 50, 50], [600, 600, 30, 30])
+ for (const node of hidden.nodes) node.visible = false
+ expect(box(hidden.figma.group(hidden.nodes, hidden.figma.currentPage))).toEqual([0, 0, 0, 0])
+ })
+})
diff --git a/packages/core/tests/icons/render.test.ts b/packages/core/tests/icons/render.test.ts
index 32a6792f8..39221e4fb 100644
--- a/packages/core/tests/icons/render.test.ts
+++ b/packages/core/tests/icons/render.test.ts
@@ -22,6 +22,15 @@ function insertIcon(graph: SceneGraph, body: string, viewBox = 24, size = 24) {
}
describe('placeIcon', () => {
+ test('leaves out shapes the SVG hides', () => {
+ const body = (hidden: string, none: string) =>
+ `<g ${hidden}><path d="M2 2h8v8H2z"/></g><path ${none} d="M14 2h8v8h-8z"/><path d="M2 14h8v8H2z"/>`
+ expect(insertIcon(new SceneGraph(), body('', '')).vectors).toHaveLength(3)
+ expect(
+ insertIcon(new SceneGraph(), body('visibility="hidden"', 'display="none"')).vectors
+ ).toHaveLength(1)
+ })
+
test('keeps round stroke caps and joins after a .fig round trip', async () => {
const graph = new SceneGraph()
insertIcon(
diff --git a/packages/core/tests/io/formats/svg/visibility.test.ts b/packages/core/tests/io/formats/svg/visibility.test.ts
new file mode 100644
index 000000000..f277b891e
--- /dev/null
+++ b/packages/core/tests/io/formats/svg/visibility.test.ts
@@ -0,0 +1,188 @@
+import { describe, expect, test } from 'bun:test'
+
+import { FigmaAPI } from '@open-pencil/core/figma-api'
+import { createSVGNodes } from '@open-pencil/core/io/formats/svg'
+import { importSVG } from '@open-pencil/core/tools'
+import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
+
+/**
+ * Each tree is what `figma.createNodeFromSvg` built in Figma 126 from the same markup, with
+ * positions relative to the imported frame. Figma keeps hidden content as hidden layers, and a
+ * group spans only the layers it shows.
+ */
+function layerTree(graph: SceneGraph, root: SceneNode): string[] {
+ const lines: string[] = []
+ const walk = (node: SceneNode, depth: number, originX: number, originY: number) => {
+ const x = depth === 0 ? 0 : originX + node.x
+ const y = depth === 0 ? 0 : originY + node.y
+ const flags = `${node.visible ? '' : ' hidden'}${node.isMask ? ' mask' : ''}`
+ lines.push(
+ `${' '.repeat(depth)}${node.type} "${node.name}" ${Math.round(x)},${Math.round(y)} ` +
+ `${Math.round(node.width)}x${Math.round(node.height)}${flags}`
+ )
+ for (const child of graph.getChildren(node.id)) walk(child, depth + 1, x, y)
+ }
+ walk(root, 0, 0, 0)
+ return lines
+}
+
+function importedTree(body: string, rootAttributes = ''): string[] {
+ const graph = new SceneGraph()
+ const root = createSVGNodes(graph, graph.getPages()[0].id, svg(body, rootAttributes))
+ if (!root) throw new Error('Nothing imported')
+ return layerTree(graph, root)
+}
+
+const svg = (body: string, rootAttributes = '') =>
+ `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="100" height="100" ${rootAttributes}>${body}</svg>`
+
+const rect = (attributes: string) => `<rect width="10" height="10" ${attributes}/>`
+
+describe('SVG import keeps hidden content as hidden layers', () => {
+ test('import_svg keeps groups hidden by visibility or display (#1166)', async () => {
+ const graph = new SceneGraph()
+ await importSVG.execute(new FigmaAPI(graph), {
+ svg: svg(`<g visibility="hidden"><path d="M0 0 L50 0 L50 50 Z" fill="#ff0000"/></g>
+ <g display="none"><path d="M60 0 L90 0 L90 30 Z" fill="#00ff00"/></g>
+ <path d="M0 60 L30 60 L30 90 Z" fill="#0000ff"/>`)
+ })
+ const [root] = graph.getChildren(graph.getPages()[0].id)
+ expect(layerTree(graph, root)).toEqual([
+ 'FRAME "Frame" 0,0 100x100',
+ ' GROUP "Group" 0,0 0x0 hidden',
+ ' VECTOR "Vector" 0,0 50x50 hidden',
+ ' GROUP "Group" 0,0 0x0 hidden',
+ ' VECTOR "Vector" 60,0 30x30 hidden',
+ ' VECTOR "Vector" 0,60 30x30'
+ ])
+ })
+
+ test('reads the properties on shapes and from a style attribute, which wins', () => {
+ expect(
+ importedTree(`<path id="none" display="none" d="M60 0 L90 0 L90 30 Z"/>
+ <path id="collapsed" visibility="collapse" d="M0 60 L30 60 L30 90 Z"/>
+ <g visibility="visible" style="visibility: hidden">
+ <rect id="hidden" width="10" height="10"/>
+ <rect id="shown" x="20" width="10" height="10" visibility="hidden" style="visibility:visible"/>
+ </g>
+ <g display="inline" style="display: none"><rect width="10" height="10"/></g>
+ <rect id="displayed" width="10" height="10" display="none" style="display:inline"/>`)
+ ).toEqual([
+ 'FRAME "Frame" 0,0 100x100',
+ ' VECTOR "none" 60,0 30x30 hidden',
+ ' VECTOR "collapsed" 0,60 30x30 hidden',
+ ' GROUP "Group" 20,0 10x10 hidden',
+ ' VECTOR "hidden" 0,0 10x10 hidden',
+ ' VECTOR "shown" 20,0 10x10',
+ ' GROUP "Group" 0,0 0x0 hidden',
+ ' VECTOR "Vector" 0,0 10x10 hidden',
+ ' VECTOR "displayed" 0,0 10x10'
+ ])
+ })
+
+ test('both properties inherit until a child sets its own', () => {
+ expect(
+ importedTree(`<g visibility="hidden"><g>
+ <rect id="hidden" width="10" height="10"/>
+ <g visibility="visible"><circle id="shown" cx="20" cy="20" r="5"/></g>
+ </g></g>
+ <g display="none"><g display="inline"><rect width="10" height="10"/></g></g>`)
+ ).toEqual([
+ 'FRAME "Frame" 0,0 100x100',
+ ' GROUP "Group" 0,0 0x0 hidden',
+ ' GROUP "Group" 15,15 10x10 hidden',
+ ' VECTOR "hidden" 0,0 10x10 hidden',
+ ' GROUP "Group" 15,15 10x10',
+ ' VECTOR "shown" 15,15 10x10',
+ ' GROUP "Group" 0,0 10x10 hidden',
+ ' GROUP "Group" 0,0 10x10',
+ ' VECTOR "Vector" 0,0 10x10'
+ ])
+ })
+
+ test('any visibility but visible hides, and any display but none shows', () => {
+ const shown = ['inherit', 'initial', 'unset', 'block', 'NONE'].map((value) =>
+ rect(`display="${value}"`)
+ )
+ expect(
+ importedTree(`<g visibility="hidden">${rect('visibility="inherit"')}${rect('style="visibility:unset"')}
+ ${rect('visibility="initial"')}${rect('visibility="VISIBLE"')}${rect('visibility=" visible "')}</g>
+ <g display="none">${shown.join('')}</g>${rect('display=" none "')}`)
+ ).toEqual([
+ 'FRAME "Frame" 0,0 100x100',
+ ' GROUP "Group" 0,0 10x10 hidden',
+ ...Array.from({ length: 4 }, () => ' VECTOR "Vector" 0,0 10x10 hidden'),
+ ' VECTOR "Vector" 0,0 10x10',
+ ' GROUP "Group" 0,0 10x10 hidden',
+ ...Array.from({ length: 5 }, () => ' VECTOR "Vector" 0,0 10x10'),
+ ' VECTOR "Vector" 0,0 10x10 hidden'
+ ])
+ })
+
+ test('the root element passes its properties to the drawing', () => {
+ for (const attribute of ['visibility="hidden"', 'display="none"']) {
+ expect(importedTree(rect(''), attribute)).toEqual([
+ 'FRAME "Frame" 0,0 100x100',
+ ' VECTOR "Vector" 0,0 10x10 hidden'
+ ])
+ }
+ })
+
+ test('a hidden <use> hides the copy it draws', () => {
+ expect(
+ importedTree(`<defs><path id="tri" d="M0 0 L50 0 L50 50 Z"/></defs>
+ <use href="#tri" visibility="hidden"/><use href="#tri" display="none" x="40"/>
+ <use href="#tri" y="50"/>`)
+ ).toEqual([
+ 'FRAME "Frame" 0,0 100x100',
+ ' VECTOR "Vector" 0,0 50x50 hidden',
+ ' VECTOR "Vector" 40,0 50x50 hidden',
+ ' VECTOR "Vector" 0,50 50x50'
+ ])
+ })
+
+ test('hidden clip shapes stay in the mask, and a hidden clip path masks nothing', () => {
+ expect(
+ importedTree(`<defs><clipPath id="c">
+ <rect width="20" height="20" visibility="hidden"/>
+ <rect x="30" width="20" height="20" display="none"/>
+ <rect x="60" width="20" height="20"/>
+ </clipPath></defs><rect width="100" height="100" clip-path="url(#c)"/>`)
+ ).toEqual([
+ 'FRAME "Frame" 0,0 100x100',
+ ' GROUP "Clip path group" 60,0 20x20',
+ ' GROUP "c" 60,0 20x20 mask',
+ ' VECTOR "Vector" 0,0 20x20 hidden',
+ ' VECTOR "Vector" 30,0 20x20 hidden',
+ ' VECTOR "Vector" 60,0 20x20',
+ ' VECTOR "Vector" 0,0 100x100'
+ ])
+ expect(
+ importedTree(`<defs><clipPath id="c" display="none"><rect width="20" height="20"/></clipPath></defs>
+ <rect width="100" height="100" clip-path="url(#c)"/>`)
+ ).toEqual([
+ 'FRAME "Frame" 0,0 100x100',
+ ' GROUP "Clip path group" 0,0 100x100',
+ ' GROUP "c" 0,0 0x0 hidden mask',
+ ' VECTOR "Vector" 0,0 20x20 hidden',
+ ' VECTOR "Vector" 0,0 100x100'
+ ])
+ })
+
+ test('hidden text imports as hidden text layers with its characters', () => {
+ const graph = new SceneGraph()
+ createSVGNodes(
+ graph,
+ graph.getPages()[0].id,
+ svg(`<g visibility="hidden"><text x="0" y="20">Hidden</text></g>
+ <text x="0" y="40" display="none">Absent</text>
+ <text x="0" y="60">Shown</text>`)
+ )
+ const texts = [...graph.getAllNodes()].filter((node) => node.type === 'TEXT')
+ expect(texts.map(({ text, visible }) => ({ text, visible }))).toEqual([
+ { text: 'Hidden', visible: false },
+ { text: 'Absent', visible: false },
+ { text: 'Shown', visible: true }
+ ])
+ })
+})
diff --git a/packages/scene-graph/src/group-bounds.ts b/packages/scene-graph/src/group-bounds.ts
index 652a0a8f6..6b503d80a 100644
--- a/packages/scene-graph/src/group-bounds.ts
+++ b/packages/scene-graph/src/group-bounds.ts
@@ -1,7 +1,7 @@
import { getAxisAlignedBoundsInParent } from './coordinate'
import type { SceneGraph } from './graph'
import { FITTED_CONTAINER_TYPES } from './node-defaults'
-import type { Rect } from './primitives'
+import type { Rect, Vector } from './primitives'
import type { SceneNode } from './types'
type Placement = Pick<SceneNode, 'x' | 'y' | 'width' | 'height'>
@@ -46,13 +46,31 @@ function fittedAncestors(graph: SceneGraph, parentIds: Iterable<string>): SceneN
}
/**
- * The layers a group's box covers. A mask hides the layers above it outside its shape, so, as in
- * Figma, they count only through the mask: the box is the layers below it and the masks.
+ * The layers a group's box covers, bottom to top. Hidden layers do not count, as in Figma. A mask
+ * hides the layers above it outside its shape, so they count only through the mask: the box is
+ * the layers below it and the masks.
*/
-function boundingChildren(children: SceneNode[]): SceneNode[] {
- const firstMask = children.findIndex((child) => child.isMask)
- if (firstMask === -1) return children
- return [...children.slice(0, firstMask), ...children.slice(firstMask).filter((c) => c.isMask)]
+function groupBoundingLayers(children: readonly SceneNode[]): SceneNode[] {
+ const shown = children.filter((child) => child.visible)
+ const firstMask = shown.findIndex((child) => child.isMask)
+ if (firstMask === -1) return shown
+ return [...shown.slice(0, firstMask), ...shown.slice(firstMask).filter((c) => c.isMask)]
+}
+
+/**
+ * A group's box in its parent's space: around the layers it shows, or, with every layer hidden,
+ * empty at `origin`, where Figma leaves it.
+ */
+export function groupBounds(
+ graph: SceneGraph,
+ children: readonly SceneNode[],
+ parentId: string,
+ origin: Vector
+): Rect {
+ const layers = groupBoundingLayers(children)
+ return layers.length > 0
+ ? getAxisAlignedBoundsInParent(layers, parentId, graph)
+ : { x: origin.x, y: origin.y, width: 0, height: 0 }
}
/** Moves the group to its children's bounds, shifting them back so they stay put. */
@@ -66,7 +84,7 @@ function fitGroup(
if (!group.parentId || group.rotation !== 0 || group.flipX || group.flipY) return
const bounds =
(group.type === 'BOOLEAN_OPERATION' ? options.booleanBounds?.(group) : null) ??
- getAxisAlignedBoundsInParent(boundingChildren(children), group.parentId, graph)
+ groupBounds(graph, children, group.parentId, group)
const dx = bounds.x - group.x
const dy = bounds.y - group.y
if (dx === 0 && dy === 0 && bounds.width === group.width && bounds.height === group.height) {
diff --git a/packages/vue/src/controls/appearance/helpers.ts b/packages/vue/src/controls/appearance/helpers.ts
index d151dc4b3..4c7878f6e 100644
--- a/packages/vue/src/controls/appearance/helpers.ts
+++ b/packages/vue/src/controls/appearance/helpers.ts
@@ -241,9 +241,7 @@ export function createAppearanceActions({
if (liveNodes.length === 0) return
const allVisible = liveNodes.every((n) => n.visible)
editor.undo.runBatch('Toggle visibility', () => {
- for (const n of liveNodes) {
- editor.updateNodeWithUndo(n.id, { visible: !allVisible }, 'Toggle visibility')
- }
+ for (const n of liveNodes) editor.setNodeVisibility(n.id, !allVisible)
})
return
}
@@ -252,7 +250,7 @@ export function createAppearanceActions({
if (!selected) return
const liveNode = editor.getNode(selected.id)
if (!liveNode) return
- editor.updateNodeWithUndo(liveNode.id, { visible: !liveNode.visible }, 'Toggle visibility')
+ editor.setNodeVisibility(liveNode.id, !liveNode.visible)
}
function toggleIndependentCorners() {