Skip to content

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

feat(editor): add flatten selection command

Danila Poyarkovdc93ec54c559
diff --git a/desktop/generated/menu.json b/desktop/generated/menu.json
index b16890255..88528c70a 100644
--- a/desktop/generated/menu.json
+++ b/desktop/generated/menu.json
@@ -210,6 +210,10 @@
"id": "selection.booleanExclude",
"label": "Exclude selection"
},
+ {
+ "id": "selection.flatten",
+ "label": "Flatten"
+ },
{
"type": "separator"
},
diff --git a/packages/core/src/canvas/boolean.ts b/packages/core/src/canvas/boolean.ts
index bc4dde07a..c9d5ff38d 100644
--- a/packages/core/src/canvas/boolean.ts
+++ b/packages/core/src/canvas/boolean.ts
@@ -16,14 +16,21 @@ const BOOLEAN_PATH_OP: Record<
EXCLUDE: 'XOR'
}
-function childTransform(r: SkiaRenderer, child: SceneNode): number[] {
+export function nodePathTransform(r: SkiaRenderer, child: SceneNode): number[] {
const transforms = [r.ck.Matrix.translated(child.x, child.y)]
if (child.rotation !== 0) {
- transforms.push(r.ck.Matrix.rotated((child.rotation * Math.PI) / 180, child.width / 2, child.height / 2))
+ transforms.push(
+ r.ck.Matrix.rotated((child.rotation * Math.PI) / 180, child.width / 2, child.height / 2)
+ )
}
if (child.flipX || child.flipY) {
transforms.push(
- r.ck.Matrix.scaled(child.flipX ? -1 : 1, child.flipY ? -1 : 1, child.width / 2, child.height / 2)
+ r.ck.Matrix.scaled(
+ child.flipX ? -1 : 1,
+ child.flipY ? -1 : 1,
+ child.width / 2,
+ child.height / 2
+ )
)
}
if (transforms.length === 1) return transforms[0]
@@ -38,7 +45,11 @@ function lineStrokePath(r: SkiaRenderer, node: SceneNode): Path | null {
return path.stroke({ width: stroke?.weight ?? 1 })
}
-function shapePath(r: SkiaRenderer, node: SceneNode, graph: SceneGraph): Path | null {
+export function makeBooleanSourcePath(
+ r: SkiaRenderer,
+ node: SceneNode,
+ graph: SceneGraph
+): Path | null {
if (node.type === 'BOOLEAN_OPERATION') return makeBooleanOperationPath(r, node, graph)
if (node.type === 'TEXT' || node.type === 'SECTION' || node.type === 'COMPONENT_SET') return null
if (node.type === 'LINE') return lineStrokePath(r, node)
@@ -48,14 +59,10 @@ function shapePath(r: SkiaRenderer, node: SceneNode, graph: SceneGraph): Path |
return r.makeNodeShapePath(node, rect, nodeHasRadius(node))
}
-function transformedShapePath(
- r: SkiaRenderer,
- child: SceneNode,
- graph: SceneGraph
-): Path | null {
- const path = shapePath(r, child, graph)
+function transformedShapePath(r: SkiaRenderer, child: SceneNode, graph: SceneGraph): Path | null {
+ const path = makeBooleanSourcePath(r, child, graph)
if (!path) return null
- path.transform(childTransform(r, child))
+ path.transform(nodePathTransform(r, child))
return path
}
diff --git a/packages/core/src/editor/bridges/structure.ts b/packages/core/src/editor/bridges/structure.ts
index ab4a5b09b..d64fd8877 100644
--- a/packages/core/src/editor/bridges/structure.ts
+++ b/packages/core/src/editor/bridges/structure.ts
@@ -11,6 +11,7 @@ export function createStructureBridge(structure: StructureActions, selection: Se
frameSelection: () => structure.frameSelection(selection.getSelectedNodes()),
booleanOperationSelected: (operation: 'UNION' | 'SUBTRACT' | 'INTERSECT' | 'EXCLUDE') =>
structure.booleanOperationSelected(selection.getSelectedNodes(), operation),
+ flattenSelected: () => structure.flattenSelected(selection.getSelectedNodes()),
ungroupSelected: () => structure.ungroupSelected(selection.getSelectedNode())
}
}
diff --git a/packages/core/src/editor/structure.ts b/packages/core/src/editor/structure.ts
index f8a37f6f5..887826be0 100644
--- a/packages/core/src/editor/structure.ts
+++ b/packages/core/src/editor/structure.ts
@@ -1,12 +1,13 @@
import { DEFAULT_FRAME_FILL } from '#core/constants'
import type { NodeType, SceneNode } from '#core/scene-graph'
+import { wrapInAutoLayout as wrapInAutoLayoutImpl } from './structure/auto-layout-wrap'
import {
booleanOperationSelected as booleanOperationSelectedImpl,
type BooleanOperation
} from './structure/boolean'
-import { wrapInAutoLayout as wrapInAutoLayoutImpl } from './structure/auto-layout-wrap'
import { wrapSelectionInContainer as wrapSelectionInContainerImpl } from './structure/container-wrap'
+import { flattenSelected as flattenSelectedImpl } from './structure/flatten'
import { ungroupSelected as ungroupImpl } from './structure/group'
import { createStructureReorderActions } from './structure/reorder'
import { createStructureStateActions } from './structure/state'
@@ -68,6 +69,10 @@ export function createStructureActions(ctx: EditorContext) {
ungroupImpl(ctx, selectedNode)
}
+ function flattenSelected(selectedNodes: SceneNode[]) {
+ return flattenSelectedImpl(ctx, selectedNodes)
+ }
+
function moveToPage(pageId: string) {
const targetPage = ctx.graph.getNode(pageId)
if (targetPage?.type !== 'CANVAS') return
@@ -95,6 +100,7 @@ export function createStructureActions(ctx: EditorContext) {
frameSelection,
booleanOperationSelected,
ungroupSelected,
+ flattenSelected,
...stateActions,
moveToPage,
renameNode
diff --git a/packages/core/src/editor/structure/boolean.ts b/packages/core/src/editor/structure/boolean.ts
index 71cd56e13..b96e065ee 100644
--- a/packages/core/src/editor/structure/boolean.ts
+++ b/packages/core/src/editor/structure/boolean.ts
@@ -1,8 +1,9 @@
+import { restoreSubtree, snapshotSubtree } from '#core/editor/clipboard/subtree-history'
import type { EditorContext } from '#core/editor/types'
import { computeAbsoluteBounds } from '#core/geometry'
import type { SceneNode } from '#core/scene-graph'
-import { restoreSubtree, snapshotSubtree } from '#core/editor/clipboard/subtree-history'
+import { selectedNodesInSharedParent } from './selection'
export type BooleanOperation = 'UNION' | 'SUBTRACT' | 'INTERSECT' | 'EXCLUDE'
@@ -12,15 +13,9 @@ export function booleanOperationSelected(
selectedNodes: SceneNode[],
operation: BooleanOperation
) {
- const selectedSet = new Set(selectedNodes.map((node) => node.id))
- const topLevel = selectedNodes.filter((node) => !node.parentId || !selectedSet.has(node.parentId))
- if (topLevel.length < 2 || topLevel.some((node) => node.locked)) return null
-
- const parentId = topLevel[0].parentId ?? ctx.state.currentPageId
- if (!topLevel.every((node) => (node.parentId ?? ctx.state.currentPageId) === parentId)) return null
-
- const parent = ctx.graph.getNode(parentId)
- if (!parent) return null
+ const selection = selectedNodesInSharedParent(ctx, selectedNodes)
+ if (!selection || selection.topLevel.length < 2) return null
+ const { topLevel, parentId, parent } = selection
const prevSelection = new Set(ctx.state.selectedIds)
const childIds = topLevel.map((node) => node.id)
diff --git a/packages/core/src/editor/structure/flatten.ts b/packages/core/src/editor/structure/flatten.ts
new file mode 100644
index 000000000..4d642bd04
--- /dev/null
+++ b/packages/core/src/editor/structure/flatten.ts
@@ -0,0 +1,80 @@
+import { makeBooleanSourcePath, nodePathTransform } from '#core/canvas/boolean'
+import { restoreSubtree, snapshotSubtree } from '#core/editor/clipboard/subtree-history'
+import type { EditorContext } from '#core/editor/types'
+import { parseSVGPath } from '#core/io/formats/svg/parse-path'
+import type { SceneNode } from '#core/scene-graph'
+import { copyFills } from '#core/scene-graph/copy'
+
+import { selectedNodesInSharedParent } from './selection'
+
+export function flattenSelected(ctx: EditorContext, selectedNodes: SceneNode[]) {
+ const renderer = ctx.getRenderer()
+ if (!renderer) return null
+
+ const selection = selectedNodesInSharedParent(ctx, selectedNodes)
+ if (!selection) return null
+ const { topLevel, parentId, parent } = selection
+
+ const childIds = topLevel.map((node) => node.id)
+ const childSnapshots = childIds.map((id) => ({ id, subtree: snapshotSubtree(ctx.graph, id) }))
+ const prevSelection = new Set(ctx.state.selectedIds)
+ const firstIndex = Math.min(...childIds.map((id) => parent.childIds.indexOf(id)))
+ const path = new renderer.ck.Path()
+
+ for (const node of topLevel) {
+ const childPath = makeBooleanSourcePath(renderer, node, ctx.graph)
+ if (!childPath) continue
+ childPath.transform(nodePathTransform(renderer, node))
+ path.addPath(childPath)
+ childPath.delete()
+ }
+
+ const bounds = path.getBounds()
+ if (bounds[2] <= bounds[0] || bounds[3] <= bounds[1]) {
+ path.delete()
+ return null
+ }
+
+ path.transform(renderer.ck.Matrix.translated(-bounds[0], -bounds[1]))
+ const svgPath = path.toSVGString()
+ path.delete()
+
+ const first = topLevel[0]
+ const vector = ctx.graph.createNode('VECTOR', parentId, {
+ name: 'Flatten',
+ x: bounds[0],
+ y: bounds[1],
+ width: bounds[2] - bounds[0],
+ height: bounds[3] - bounds[1],
+ fills: copyFills(first.fills),
+ strokes: [],
+ vectorNetwork: parseSVGPath(svgPath)
+ })
+ const vectorSnapshot = structuredClone(vector)
+ ctx.graph.insertChildAt(vector.id, parentId, firstIndex)
+ for (const id of childIds) ctx.graph.deleteNode(id)
+ ctx.setSelectedIds(new Set([vector.id]))
+
+ ctx.undo.push({
+ label: 'Flatten',
+ forward: () => {
+ const restored = ctx.graph.createNode('VECTOR', parentId, vectorSnapshot)
+ ctx.graph.insertChildAt(restored.id, parentId, firstIndex)
+ for (const id of childIds) ctx.graph.deleteNode(id)
+ ctx.setSelectedIds(new Set([restored.id]))
+ },
+ inverse: () => {
+ ctx.graph.deleteNode(vector.id)
+ for (let i = 0; i < childSnapshots.length; i++) {
+ const { id, subtree } = childSnapshots[i]
+ const root = subtree.get(id)
+ if (!root) continue
+ restoreSubtree(ctx.graph, root, parentId, subtree)
+ ctx.graph.insertChildAt(id, parentId, firstIndex + i)
+ }
+ ctx.setSelectedIds(prevSelection)
+ }
+ })
+
+ return vector.id
+}
diff --git a/packages/core/src/editor/structure/selection.ts b/packages/core/src/editor/structure/selection.ts
new file mode 100644
index 000000000..451aeb560
--- /dev/null
+++ b/packages/core/src/editor/structure/selection.ts
@@ -0,0 +1,18 @@
+import type { EditorContext } from '#core/editor/types'
+import type { SceneNode } from '#core/scene-graph'
+
+export function topLevelSelectedNodes(selectedNodes: SceneNode[]): SceneNode[] {
+ const selectedSet = new Set(selectedNodes.map((node) => node.id))
+ return selectedNodes.filter((node) => !node.parentId || !selectedSet.has(node.parentId))
+}
+
+export function selectedNodesInSharedParent(ctx: EditorContext, selectedNodes: SceneNode[]) {
+ const topLevel = topLevelSelectedNodes(selectedNodes)
+ if (topLevel.length === 0 || topLevel.some((node) => node.locked)) return null
+
+ const parentId = topLevel[0].parentId ?? ctx.state.currentPageId
+ if (!topLevel.every((node) => (node.parentId ?? ctx.state.currentPageId) === parentId)) return null
+
+ const parent = ctx.graph.getNode(parentId)
+ return parent ? { topLevel, parentId, parent } : null
+}
diff --git a/packages/vue/src/editor/commands/registry.ts b/packages/vue/src/editor/commands/registry.ts
index b73443525..3211c3ffe 100644
--- a/packages/vue/src/editor/commands/registry.ts
+++ b/packages/vue/src/editor/commands/registry.ts
@@ -63,10 +63,31 @@ export const EDITOR_COMMAND_METADATA = {
keybinding: 'Shift+KeyV',
contextTestId: 'context-flip-vertical'
},
- 'selection.booleanUnion': { contextTestId: 'context-boolean-union' },
- 'selection.booleanSubtract': { contextTestId: 'context-boolean-subtract' },
- 'selection.booleanIntersect': { contextTestId: 'context-boolean-intersect' },
- 'selection.booleanExclude': { contextTestId: 'context-boolean-exclude' },
+ 'selection.booleanUnion': {
+ shortcut: 'ALT+SHIFT+U',
+ keybinding: 'Alt+Shift+KeyU',
+ contextTestId: 'context-boolean-union'
+ },
+ 'selection.booleanSubtract': {
+ shortcut: 'ALT+SHIFT+S',
+ keybinding: 'Alt+Shift+KeyS',
+ contextTestId: 'context-boolean-subtract'
+ },
+ 'selection.booleanIntersect': {
+ shortcut: 'ALT+SHIFT+I',
+ keybinding: 'Alt+Shift+KeyI',
+ contextTestId: 'context-boolean-intersect'
+ },
+ 'selection.booleanExclude': {
+ shortcut: 'ALT+SHIFT+E',
+ keybinding: 'Alt+Shift+KeyE',
+ contextTestId: 'context-boolean-exclude'
+ },
+ 'selection.flatten': {
+ shortcut: 'ALT+SHIFT+F',
+ keybinding: 'Alt+Shift+KeyF',
+ contextTestId: 'context-flatten'
+ },
'selection.moveToPage': {},
'view.zoom100': { keybinding: '$mod+Digit0' },
'view.zoomFit': { keybinding: ['$mod+Digit1', 'Shift+Digit1'] },
diff --git a/packages/vue/src/editor/commands/selection.ts b/packages/vue/src/editor/commands/selection.ts
index 58c803f09..4df4a05e6 100644
--- a/packages/vue/src/editor/commands/selection.ts
+++ b/packages/vue/src/editor/commands/selection.ts
@@ -191,6 +191,14 @@ export function createSelectionCommands({
enabled: capabilities.canBooleanOperation,
run: () => editor.booleanOperationSelected('EXCLUDE')
},
+ 'selection.flatten': {
+ id: 'selection.flatten',
+ get label() {
+ return t.value.flattenSelection
+ },
+ enabled: capabilities.canFlatten,
+ run: () => editor.flattenSelected()
+ },
'selection.moveToPage': {
id: 'selection.moveToPage',
get label() {
diff --git a/packages/vue/src/editor/commands/types.ts b/packages/vue/src/editor/commands/types.ts
index 684308c9d..94931a1e5 100644
--- a/packages/vue/src/editor/commands/types.ts
+++ b/packages/vue/src/editor/commands/types.ts
@@ -25,6 +25,7 @@ export type EditorCommandId =
| 'selection.booleanSubtract'
| 'selection.booleanIntersect'
| 'selection.booleanExclude'
+ | 'selection.flatten'
| 'selection.moveToPage'
| 'view.zoom100'
| 'view.zoomFit'
diff --git a/packages/vue/src/editor/menu-model/canvas.ts b/packages/vue/src/editor/menu-model/canvas.ts
index adfedb579..f99e0f795 100644
--- a/packages/vue/src/editor/menu-model/canvas.ts
+++ b/packages/vue/src/editor/menu-model/canvas.ts
@@ -31,7 +31,13 @@ export type CanvasMenuOptions = {
const CANVAS_MENU_GROUPS = [
['selection.duplicate', 'selection.delete'],
['selection.moveToPageWhenAvailable', 'selection.bringToFront', 'selection.sendToBack'],
- ['selection.group', 'selection.frameSelection', 'selection.ungroupWhenGroup', 'selection.wrapInAutoLayout'],
+ [
+ 'selection.group',
+ 'selection.frameSelection',
+ 'selection.ungroupWhenGroup',
+ 'selection.wrapInAutoLayout',
+ 'selection.flatten'
+ ],
['selection.componentAction', 'selection.componentSetAction', 'selection.instanceActions'],
['selection.toggleVisibility', 'selection.toggleLock'],
['selection.flipHorizontal', 'selection.flipVertical']
diff --git a/packages/vue/src/editor/selection-capabilities/use.ts b/packages/vue/src/editor/selection-capabilities/use.ts
index b16750cd9..a1e181e40 100644
--- a/packages/vue/src/editor/selection-capabilities/use.ts
+++ b/packages/vue/src/editor/selection-capabilities/use.ts
@@ -36,6 +36,7 @@ export function useSelectionCapabilities() {
canToggleLock: computed(() => hasSelection.value),
canFlip: computed(() => hasSelection.value),
canBooleanOperation: computed(() => selectedCount.value >= 2),
+ canFlatten: computed(() => hasSelection.value),
canGoToMainComponent: computed(() => selection.isInstance.value),
canCreateInstance: computed(() => selectedNode.value?.type === 'COMPONENT'),
canMoveToPage: useSceneComputed(() => hasSelection.value && editor.graph.getPages().length > 1),
diff --git a/packages/vue/src/i18n/messages.ts b/packages/vue/src/i18n/messages.ts
index 4b1a24be9..a01e6cb03 100644
--- a/packages/vue/src/i18n/messages.ts
+++ b/packages/vue/src/i18n/messages.ts
@@ -98,6 +98,7 @@ export const commandMessages = i18n('commands', {
subtractSelection: 'Subtract selection',
intersectSelection: 'Intersect selection',
excludeSelection: 'Exclude selection',
+ flattenSelection: 'Flatten',
booleanOperations: 'Boolean operations',
flipHorizontal: 'Flip horizontal',
flipVertical: 'Flip vertical',
diff --git a/packages/vue/src/locales/de.json b/packages/vue/src/locales/de.json
index d7ff09dd4..c34bdfbdd 100644
--- a/packages/vue/src/locales/de.json
+++ b/packages/vue/src/locales/de.json
@@ -73,7 +73,8 @@
"excludeSelection": "Exclude selection",
"booleanOperations": "Boolean operations",
"flipHorizontal": "Horizontal spiegeln",
- "flipVertical": "Vertikal spiegeln"
+ "flipVertical": "Vertikal spiegeln",
+ "flattenSelection": "Flatten"
},
"tools": {
"move": "Verschieben",
diff --git a/packages/vue/src/locales/es.json b/packages/vue/src/locales/es.json
index f5101f091..ac6dca8e4 100644
--- a/packages/vue/src/locales/es.json
+++ b/packages/vue/src/locales/es.json
@@ -73,7 +73,8 @@
"excludeSelection": "Exclude selection",
"booleanOperations": "Boolean operations",
"flipHorizontal": "Voltear horizontalmente",
- "flipVertical": "Voltear verticalmente"
+ "flipVertical": "Voltear verticalmente",
+ "flattenSelection": "Flatten"
},
"tools": {
"move": "Mover",
diff --git a/packages/vue/src/locales/fr.json b/packages/vue/src/locales/fr.json
index edca09929..c6933ee35 100644
--- a/packages/vue/src/locales/fr.json
+++ b/packages/vue/src/locales/fr.json
@@ -73,7 +73,8 @@
"excludeSelection": "Exclude selection",
"booleanOperations": "Boolean operations",
"flipHorizontal": "Retourner horizontalement",
- "flipVertical": "Retourner verticalement"
+ "flipVertical": "Retourner verticalement",
+ "flattenSelection": "Flatten"
},
"tools": {
"move": "Déplacer",
diff --git a/packages/vue/src/locales/it.json b/packages/vue/src/locales/it.json
index e732b1bac..305ec6aec 100644
--- a/packages/vue/src/locales/it.json
+++ b/packages/vue/src/locales/it.json
@@ -73,7 +73,8 @@
"excludeSelection": "Exclude selection",
"booleanOperations": "Boolean operations",
"flipHorizontal": "Rifletti orizzontalmente",
- "flipVertical": "Rifletti verticalmente"
+ "flipVertical": "Rifletti verticalmente",
+ "flattenSelection": "Flatten"
},
"tools": {
"move": "Sposta",
diff --git a/packages/vue/src/locales/pl.json b/packages/vue/src/locales/pl.json
index b8ba8e028..fa50bb66c 100644
--- a/packages/vue/src/locales/pl.json
+++ b/packages/vue/src/locales/pl.json
@@ -73,7 +73,8 @@
"excludeSelection": "Exclude selection",
"booleanOperations": "Boolean operations",
"flipHorizontal": "Odbij poziomo",
- "flipVertical": "Odbij pionowo"
+ "flipVertical": "Odbij pionowo",
+ "flattenSelection": "Flatten"
},
"tools": {
"move": "Przesuń",
diff --git a/packages/vue/src/locales/ru.json b/packages/vue/src/locales/ru.json
index dc6370c12..cee5c0062 100644
--- a/packages/vue/src/locales/ru.json
+++ b/packages/vue/src/locales/ru.json
@@ -73,7 +73,8 @@
"excludeSelection": "Exclude selection",
"booleanOperations": "Boolean operations",
"flipHorizontal": "Отразить по горизонтали",
- "flipVertical": "Отразить по вертикали"
+ "flipVertical": "Отразить по вертикали",
+ "flattenSelection": "Flatten"
},
"tools": {
"move": "Перемещение",
diff --git a/packages/vue/src/locales/zh-CN.json b/packages/vue/src/locales/zh-CN.json
index 1563f0699..c2e1b583f 100644
--- a/packages/vue/src/locales/zh-CN.json
+++ b/packages/vue/src/locales/zh-CN.json
@@ -73,7 +73,8 @@
"excludeSelection": "Exclude selection",
"booleanOperations": "Boolean operations",
"flipHorizontal": "水平翻转",
- "flipVertical": "垂直翻转"
+ "flipVertical": "垂直翻转",
+ "flattenSelection": "Flatten"
},
"tools": {
"move": "移动",
diff --git a/src/app/shell/menu/schema.ts b/src/app/shell/menu/schema.ts
index 7ab66a3bb..385ea4b81 100644
--- a/src/app/shell/menu/schema.ts
+++ b/src/app/shell/menu/schema.ts
@@ -169,6 +169,11 @@ export const APP_MENU_SCHEMA = [
label: 'Exclude selection',
command: 'selection.booleanExclude'
},
+ {
+ id: 'selection.flatten',
+ label: 'Flatten',
+ command: 'selection.flatten'
+ },
{ type: 'separator' },
{
id: 'selection.createComponent',
diff --git a/src/app/shell/menu/use.ts b/src/app/shell/menu/use.ts
index cd3f15495..c1a266ba2 100644
--- a/src/app/shell/menu/use.ts
+++ b/src/app/shell/menu/use.ts
@@ -29,6 +29,7 @@ const COMMAND_MENU_IDS = new Set<string>([
'selection.booleanSubtract',
'selection.booleanIntersect',
'selection.booleanExclude',
+ 'selection.flatten',
'selection.bringToFront',
'selection.sendToBack',
'view.zoom100',
diff --git a/src/components/CanvasMenu.vue b/src/components/CanvasMenu.vue
index e713cb1b4..5e6fb4c0e 100644
--- a/src/components/CanvasMenu.vue
+++ b/src/components/CanvasMenu.vue
@@ -11,6 +11,7 @@ import {
import IconCombine from '~icons/lucide/combine'
import IconCopyMinus from '~icons/lucide/copy-minus'
import IconCopyX from '~icons/lucide/copy-x'
+import IconListCollapse from '~icons/lucide/list-collapse'
import IconSquaresIntersect from '~icons/lucide/squares-intersect'
import {
vTestId,
@@ -60,7 +61,8 @@ const booleanCommandIcons = {
'selection.booleanUnion': IconCombine,
'selection.booleanSubtract': IconCopyMinus,
'selection.booleanIntersect': IconSquaresIntersect,
- 'selection.booleanExclude': IconCopyX
+ 'selection.booleanExclude': IconCopyX,
+ 'selection.flatten': IconListCollapse
} satisfies Partial<Record<EditorCommandId, Component>>
function contextCommandTestId(id: EditorCommandId | undefined): string | undefined {
@@ -183,6 +185,5 @@ function contextCommandIcon(id: EditorCommandId | undefined): Component | undefi
>
</ContextMenuItem>
</template>
-
</ContextMenuContent>
</template>
diff --git a/src/components/properties/BooleanOperationsControl.vue b/src/components/properties/BooleanOperationsControl.vue
index 6923bf0c1..d578e7f98 100644
--- a/src/components/properties/BooleanOperationsControl.vue
+++ b/src/components/properties/BooleanOperationsControl.vue
@@ -10,9 +10,10 @@ import IconChevronDown from '~icons/lucide/chevron-down'
import IconCombine from '~icons/lucide/combine'
import IconCopyMinus from '~icons/lucide/copy-minus'
import IconCopyX from '~icons/lucide/copy-x'
+import IconListCollapse from '~icons/lucide/list-collapse'
import IconSquaresIntersect from '~icons/lucide/squares-intersect'
-import { useEditorCommands, useI18n } from '@open-pencil/vue'
+import { editorCommandMetadata, formatShortcut, useEditorCommands, useI18n } from '@open-pencil/vue'
import type { EditorCommandId } from '@open-pencil/vue'
import { menuItem, useMenuUI } from '@/components/ui/menu'
@@ -24,11 +25,12 @@ const operations = [
{ id: 'selection.booleanUnion', icon: IconCombine },
{ id: 'selection.booleanSubtract', icon: IconCopyMinus },
{ id: 'selection.booleanIntersect', icon: IconSquaresIntersect },
- { id: 'selection.booleanExclude', icon: IconCopyX }
+ { id: 'selection.booleanExclude', icon: IconCopyX },
+ { id: 'selection.flatten', icon: IconListCollapse }
] satisfies Array<{ id: EditorCommandId; icon: unknown }>
const menuCls = useMenuUI({ content: 'min-w-44' })
-const itemCls = menuItem({ justify: 'start' })
+const itemCls = menuItem({ justify: 'between' })
</script>
<template>
@@ -44,12 +46,7 @@ const itemCls = menuItem({ justify: 'start' })
</button>
</DropdownMenuTrigger>
<DropdownMenuPortal>
- <DropdownMenuContent
- align="end"
- side="bottom"
- :side-offset="4"
- :class="menuCls.content"
- >
+ <DropdownMenuContent align="end" side="bottom" :side-offset="4" :class="menuCls.content">
<DropdownMenuItem
v-for="operation in operations"
:key="operation.id"
@@ -57,8 +54,13 @@ const itemCls = menuItem({ justify: 'start' })
:disabled="!getCommand(operation.id).enabled.value"
@select="runCommand(operation.id)"
>
- <component :is="operation.icon" class="size-3.5 text-muted" />
- <span>{{ getCommand(operation.id).label }}</span>
+ <div class="flex min-w-0 items-center gap-2">
+ <component :is="operation.icon" class="size-3.5 shrink-0 text-muted" />
+ <span>{{ getCommand(operation.id).label }}</span>
+ </div>
+ <span class="ml-6 text-[11px] text-muted">{{
+ formatShortcut(editorCommandMetadata(operation.id).shortcut)
+ }}</span>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenuPortal>
diff --git a/tests/engine/editor/structure/flatten.test.ts b/tests/engine/editor/structure/flatten.test.ts
new file mode 100644
index 000000000..eca84a4d7
--- /dev/null
+++ b/tests/engine/editor/structure/flatten.test.ts
@@ -0,0 +1,62 @@
+import { describe, expect, test } from 'bun:test'
+
+import { initCanvasKit } from '#cli/headless'
+import { SkiaRenderer } from '#core/canvas'
+import { createEditor } from '#core/editor'
+
+async function createEditorWithRenderer() {
+ const ck = await initCanvasKit()
+ const surface = ck.MakeSurface(200, 200)
+ if (!surface) throw new Error('Could not create CanvasKit surface')
+ const renderer = new SkiaRenderer(ck, surface)
+ const editor = createEditor()
+ editor.setCanvasKit(ck, renderer)
+ return { editor, surface }
+}
+
+describe('flattenSelected', () => {
+ test('converts selected shapes into a vector path', async () => {
+ const { editor, surface } = await createEditorWithRenderer()
+ const pageId = editor.state.currentPageId
+ const first = editor.graph.createNode('RECTANGLE', pageId, { x: 10, y: 20, width: 50, height: 40 })
+ const second = editor.graph.createNode('ELLIPSE', pageId, { x: 40, y: 30, width: 50, height: 40 })
+
+ editor.select([first.id, second.id])
+ editor.flattenSelected()
+
+ const [vectorId] = [...editor.state.selectedIds]
+ const vector = editor.graph.getNode(vectorId)
+ expect(vector?.type).toBe('VECTOR')
+ expect(vector?.x).toBe(10)
+ expect(vector?.y).toBe(20)
+ expect(vector?.width).toBe(80)
+ expect(vector?.height).toBe(50)
+ expect(vector?.vectorNetwork?.vertices.length).toBeGreaterThan(0)
+ expect(editor.graph.getNode(first.id)).toBeUndefined()
+ expect(editor.graph.getNode(second.id)).toBeUndefined()
+ surface.delete()
+ })
+
+ test('undo and redo restore flattened children and vector', async () => {
+ const { editor, surface } = await createEditorWithRenderer()
+ const pageId = editor.state.currentPageId
+ const before = editor.graph.createNode('RECTANGLE', pageId, { name: 'Before' })
+ const first = editor.graph.createNode('RECTANGLE', pageId, { name: 'First' })
+ const second = editor.graph.createNode('ELLIPSE', pageId, { name: 'Second', x: 50 })
+ const after = editor.graph.createNode('RECTANGLE', pageId, { name: 'After' })
+
+ editor.select([first.id, second.id])
+ editor.flattenSelected()
+ const [vectorId] = [...editor.state.selectedIds]
+ expect(editor.graph.getNode(pageId)?.childIds).toEqual([before.id, vectorId, after.id])
+
+ editor.undo.undo()
+ expect(editor.graph.getNode(pageId)?.childIds).toEqual([before.id, first.id, second.id, after.id])
+ expect(editor.state.selectedIds).toEqual(new Set([first.id, second.id]))
+
+ editor.undo.redo()
+ expect(editor.graph.getNode(pageId)?.childIds).toEqual([before.id, vectorId, after.id])
+ expect(editor.graph.getNode(vectorId)?.type).toBe('VECTOR')
+ surface.delete()
+ })
+})
diff --git a/tests/engine/vue/editor/menu-model/canvas.test.ts b/tests/engine/vue/editor/menu-model/canvas.test.ts
index d28e1cd38..dbcc3036f 100644
--- a/tests/engine/vue/editor/menu-model/canvas.test.ts
+++ b/tests/engine/vue/editor/menu-model/canvas.test.ts
@@ -1,7 +1,9 @@
import { describe, expect, test } from 'bun:test'
+
import { computed, ref } from 'vue'
import type { EditorCommandId } from '@open-pencil/vue'
+
import { buildCanvasContextMenu } from '#vue/editor/menu-model/canvas'
import type { CanvasMenuOptions } from '#vue/editor/menu-model/canvas'
@@ -30,7 +32,7 @@ function options(overrides: Partial<CanvasMenuOptions> = {}): CanvasMenuOptions
}
function itemIds(menu: ReturnType<typeof buildCanvasContextMenu>) {
- return menu.map((item) => (item.separator ? '---' : item.id ?? item.label))
+ return menu.map((item) => (item.separator ? '---' : (item.id ?? item.label)))
}
describe('buildCanvasContextMenu', () => {
@@ -45,6 +47,7 @@ describe('buildCanvasContextMenu', () => {
'selection.group',
'selection.frameSelection',
'selection.wrapInAutoLayout',
+ 'selection.flatten',
'---',
'selection.createComponent',
'---',