Skip to content

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

Phase 4-5: LayerTree and EditorMenu headless primitives

Danila Poyarkov72876f8a3e0e
diff --git a/packages/vue/src/EditorMenu/EditorMenuRoot.vue b/packages/vue/src/EditorMenu/EditorMenuRoot.vue
new file mode 100644
index 000000000..d4df3ab3b
--- /dev/null
+++ b/packages/vue/src/EditorMenu/EditorMenuRoot.vue
@@ -0,0 +1,76 @@
+<script setup lang="ts">
+import { computed } from 'vue'
+
+import { useEditor } from '../context'
+
+import type { SceneNode } from '@open-pencil/core'
+
+const editor = useEditor()
+
+const selectedIds = computed(() => {
+ void editor.state.sceneVersion
+ return editor.state.selectedIds
+})
+
+const hasSelection = computed(() => selectedIds.value.size > 0)
+const selectedCount = computed(() => selectedIds.value.size)
+
+const selectedNode = computed<SceneNode | null>(() => {
+ void editor.state.sceneVersion
+ return editor.getSelectedNode() ?? null
+})
+
+const selectedType = computed(() => selectedNode.value?.type ?? null)
+const isInstance = computed(() => selectedType.value === 'INSTANCE')
+const isComponent = computed(() => selectedType.value === 'COMPONENT')
+const isGroup = computed(() => selectedType.value === 'GROUP')
+const isVisible = computed(() => selectedNode.value?.visible ?? true)
+const isLocked = computed(() => selectedNode.value?.locked ?? false)
+
+const canCreateComponentSet = computed(() => {
+ if (selectedIds.value.size < 2) return false
+ for (const id of selectedIds.value) {
+ if (editor.graph.getNode(id)?.type !== 'COMPONENT') return false
+ }
+ return true
+})
+
+const otherPages = computed(() =>
+ editor.graph.getPages().filter((p) => p.id !== editor.state.currentPageId)
+)
+
+function ids() {
+ return [...selectedIds.value]
+}
+
+function copyAsText() {
+ return editor.copySelectionAsText(ids())
+}
+
+function copyAsSVG() {
+ return editor.copySelectionAsSVG(ids())
+}
+
+function copyAsJSX() {
+ return editor.copySelectionAsJSX(ids())
+}
+</script>
+
+<template>
+ <slot
+ :editor="editor"
+ :has-selection="hasSelection"
+ :selected-count="selectedCount"
+ :selected-node="selectedNode"
+ :is-instance="isInstance"
+ :is-component="isComponent"
+ :is-group="isGroup"
+ :is-visible="isVisible"
+ :is-locked="isLocked"
+ :can-create-component-set="canCreateComponentSet"
+ :other-pages="otherPages"
+ :copy-as-text="copyAsText"
+ :copy-as-s-v-g="copyAsSVG"
+ :copy-as-j-s-x="copyAsJSX"
+ />
+</template>
diff --git a/packages/vue/src/EditorMenu/index.ts b/packages/vue/src/EditorMenu/index.ts
new file mode 100644
index 000000000..602f2605d
--- /dev/null
+++ b/packages/vue/src/EditorMenu/index.ts
@@ -0,0 +1 @@
+export { default as EditorMenuRoot } from './EditorMenuRoot.vue'
diff --git a/packages/vue/src/LayerTree/LayerTreeItem.vue b/packages/vue/src/LayerTree/LayerTreeItem.vue
new file mode 100644
index 000000000..26f972fb5
--- /dev/null
+++ b/packages/vue/src/LayerTree/LayerTreeItem.vue
@@ -0,0 +1,47 @@
+<script setup lang="ts">
+import { computed, ref } from 'vue'
+
+import { useLayerTree } from './context'
+
+import type { LayerNode } from './context'
+
+const { node, level, hasChildren } = defineProps<{
+ node: LayerNode
+ level: number
+ hasChildren: boolean
+}>()
+
+const ctx = useLayerTree()
+
+const isSelected = computed(() => ctx.selectedIds.value.has(node.id))
+const isDragging = computed(() => false)
+const padLeft = computed(() => `${8 + (level - 1) * ctx.indentPerLevel}px`)
+
+const rowEl = ref<HTMLElement | null>(null)
+
+function onRef(el: unknown) {
+ const htmlEl = el as HTMLElement | null
+ rowEl.value = htmlEl
+ ctx.setRowRef(node.id, htmlEl)
+}
+
+defineExpose({ rowEl })
+</script>
+
+<template>
+ <div :ref="onRef" :data-node-id="node.id">
+ <slot
+ :node="node"
+ :level="level"
+ :has-children="hasChildren"
+ :is-selected="isSelected"
+ :is-dragging="isDragging"
+ :pad-left="padLeft"
+ :select="(additive: boolean) => ctx.select(node.id, additive)"
+ :toggle-expand="() => ctx.toggleExpand(node.id)"
+ :toggle-visibility="() => ctx.toggleVisibility(node.id)"
+ :toggle-lock="() => ctx.toggleLock(node.id)"
+ :rename="(name: string) => ctx.rename(node.id, name)"
+ />
+ </div>
+</template>
diff --git a/packages/vue/src/LayerTree/LayerTreeRoot.vue b/packages/vue/src/LayerTree/LayerTreeRoot.vue
new file mode 100644
index 000000000..795e34fab
--- /dev/null
+++ b/packages/vue/src/LayerTree/LayerTreeRoot.vue
@@ -0,0 +1,125 @@
+<script setup lang="ts">
+import { computed, nextTick, ref, watch } from 'vue'
+
+import { useEditor } from '../context'
+import { provideLayerTree } from './context'
+
+import type { LayerNode } from './context'
+
+const { indentPerLevel = 16 } = defineProps<{
+ indentPerLevel?: number
+}>()
+
+const editor = useEditor()
+
+function buildTree(parentId: string): LayerNode[] {
+ const parent = editor.graph.getNode(parentId)
+ if (!parent) return []
+ return parent.childIds
+ .map((cid) => editor.graph.getNode(cid))
+ .filter((n): n is NonNullable<typeof n> => !!n)
+ .map((node) => ({
+ id: node.id,
+ name: node.name,
+ type: node.type,
+ layoutMode: node.layoutMode,
+ visible: node.visible,
+ locked: node.locked,
+ children: node.childIds.length > 0 ? buildTree(node.id) : undefined
+ }))
+}
+
+const items = ref(buildTree(editor.state.currentPageId))
+const treeKey = ref(0)
+const expanded = ref<string[]>([])
+const selectedIds = computed(() => editor.state.selectedIds)
+
+watch([() => editor.state.sceneVersion, () => editor.state.currentPageId], () => {
+ items.value = buildTree(editor.state.currentPageId)
+ treeKey.value++
+})
+
+const rowRefs = new Map<string, HTMLElement>()
+
+function setRowRef(id: string, el: HTMLElement | null) {
+ if (el) rowRefs.set(id, el)
+ else rowRefs.delete(id)
+}
+
+watch(
+ () => editor.state.selectedIds,
+ (ids) => {
+ const toExpand = new Set(expanded.value)
+ for (const id of ids) {
+ let node = editor.graph.getNode(id)
+ while (node?.parentId && node.parentId !== editor.state.currentPageId) {
+ toExpand.add(node.parentId)
+ node = editor.graph.getNode(node.parentId)
+ }
+ }
+ if (toExpand.size > expanded.value.length) expanded.value = [...toExpand]
+ nextTick(() => {
+ const first = [...ids][0]
+ if (first) rowRefs.get(first)?.scrollIntoView({ block: 'nearest' })
+ })
+ }
+)
+
+function syncCanvasScope(nodeId: string) {
+ const node = editor.graph.getNode(nodeId)
+ if (!node) return
+ let parentId = node.parentId
+ while (parentId && parentId !== editor.state.currentPageId) {
+ if (editor.graph.isContainer(parentId)) {
+ editor.enterContainer(parentId)
+ return
+ }
+ const parent = editor.graph.getNode(parentId)
+ parentId = parent?.parentId ?? null
+ }
+ editor.state.enteredContainerId = null
+}
+
+function select(id: string, additive: boolean) {
+ if (additive) {
+ editor.select([id], true)
+ } else {
+ editor.select([id])
+ syncCanvasScope(id)
+ }
+}
+
+function toggleExpand(id: string) {
+ const idx = expanded.value.indexOf(id)
+ if (idx !== -1) expanded.value = expanded.value.filter((e) => e !== id)
+ else expanded.value = [...expanded.value, id]
+}
+
+provideLayerTree({
+ editor,
+ items,
+ expanded,
+ treeKey,
+ selectedIds,
+ indentPerLevel,
+ select,
+ toggleExpand,
+ toggleVisibility: (id: string) => editor.toggleNodeVisibility(id),
+ toggleLock: (id: string) => editor.toggleNodeLock(id),
+ rename: (id: string, name: string) => editor.renameNode(id, name),
+ setRowRef
+})
+</script>
+
+<template>
+ <slot
+ :items="items"
+ :expanded="expanded"
+ :tree-key="treeKey"
+ :selected-ids="selectedIds"
+ :select="select"
+ :toggle-expand="toggleExpand"
+ :get-key="(v: LayerNode) => v.id"
+ :get-children="(v: LayerNode) => v.children"
+ />
+</template>
diff --git a/packages/vue/src/LayerTree/context.ts b/packages/vue/src/LayerTree/context.ts
new file mode 100644
index 000000000..e4995632c
--- /dev/null
+++ b/packages/vue/src/LayerTree/context.ts
@@ -0,0 +1,41 @@
+import { type InjectionKey, inject, provide } from 'vue'
+
+import type { Editor } from '@open-pencil/core/editor'
+import type { ComputedRef, Ref } from 'vue'
+
+export interface LayerNode {
+ id: string
+ name: string
+ type: string
+ layoutMode: string
+ visible: boolean
+ locked: boolean
+ children?: LayerNode[]
+}
+
+export interface LayerTreeContext {
+ editor: Editor
+ items: Ref<LayerNode[]>
+ expanded: Ref<string[]>
+ treeKey: Ref<number>
+ selectedIds: ComputedRef<Set<string>>
+ indentPerLevel: number
+ select: (id: string, additive: boolean) => void
+ toggleExpand: (id: string) => void
+ toggleVisibility: (id: string) => void
+ toggleLock: (id: string) => void
+ rename: (id: string, name: string) => void
+ setRowRef: (id: string, el: HTMLElement | null) => void
+}
+
+export const LAYER_TREE_KEY: InjectionKey<LayerTreeContext> = Symbol('layer-tree')
+
+export function provideLayerTree(ctx: LayerTreeContext) {
+ provide(LAYER_TREE_KEY, ctx)
+}
+
+export function useLayerTree(): LayerTreeContext {
+ const ctx = inject(LAYER_TREE_KEY)
+ if (!ctx) throw new Error('[open-pencil] useLayerTree() called outside <LayerTreeRoot>')
+ return ctx
+}
diff --git a/packages/vue/src/LayerTree/index.ts b/packages/vue/src/LayerTree/index.ts
new file mode 100644
index 000000000..9024f61a7
--- /dev/null
+++ b/packages/vue/src/LayerTree/index.ts
@@ -0,0 +1,4 @@
+export { default as LayerTreeRoot } from './LayerTreeRoot.vue'
+export { default as LayerTreeItem } from './LayerTreeItem.vue'
+export { useLayerTree } from './context'
+export type { LayerTreeContext, LayerNode } from './context'
diff --git a/packages/vue/src/index.ts b/packages/vue/src/index.ts
index 5eb4d84d5..70b466a0a 100644
--- a/packages/vue/src/index.ts
+++ b/packages/vue/src/index.ts
@@ -32,6 +32,11 @@ export { PropertyListRoot, PropertyListItem, usePropertyList } from './PropertyL
export type { PropertyListContext } from './PropertyList'
export { PositionControlsRoot } from './PositionControls'
+
+export { LayerTreeRoot, LayerTreeItem, useLayerTree } from './LayerTree'
+
+export { EditorMenuRoot } from './EditorMenu'
+export type { LayerTreeContext, LayerNode } from './LayerTree'
export type { CanvasContext } from './Canvas'
export { ToolbarRoot, ToolbarItem, useToolbar } from './Toolbar'
diff --git a/src/components/CanvasMenu.vue b/src/components/CanvasMenu.vue
index 3b7b9b584..fa4b89ff8 100644
--- a/src/components/CanvasMenu.vue
+++ b/src/components/CanvasMenu.vue
@@ -8,41 +8,21 @@ import {
ContextMenuSubContent,
ContextMenuPortal
} from 'reka-ui'
-import { useSelectionState, toast } from '@open-pencil/vue'
-import { computed } from 'vue'
+import { EditorMenuRoot, toast } from '@open-pencil/vue'
import { useEditorStore } from '@/stores/editor'
import { menuContent, menuItem, menuSeparator } from '@/components/ui/menu'
const store = useEditorStore()
-const {
- hasSelection,
- selectedNode,
- selectedCount,
- isInstance,
- isComponent,
- isGroup,
- canCreateComponentSet
-} = useSelectionState()
-
-const otherPages = computed(() =>
- store.graph.getPages().filter((p) => p.id !== store.state.currentPageId)
-)
-
-const isVisible = computed(() => selectedNode.value?.visible ?? true)
-const isLocked = computed(() => selectedNode.value?.locked ?? false)
-
-async function copyAsText() {
- const text = store.copySelectionAsText([...store.state.selectedIds])
- await navigator.clipboard.writeText(text)
- toast.show('Copied as text')
+
+function execCommand(cmd: string) {
+ window.document.execCommand(cmd)
}
-async function copyAsSVG() {
- const svg = store.copySelectionAsSVG([...store.state.selectedIds])
- if (!svg) return
- await navigator.clipboard.writeText(svg)
- toast.show('Copied as SVG')
+async function clipboardWrite(text: string | null, label: string) {
+ if (!text) return
+ await navigator.clipboard.writeText(text)
+ toast.show(`Copied as ${label}`)
}
async function copyAsPNG() {
@@ -53,17 +33,6 @@ async function copyAsPNG() {
toast.show('Copied as PNG')
}
-async function copyAsJSX() {
- const jsx = store.copySelectionAsJSX([...store.state.selectedIds])
- if (!jsx) return
- await navigator.clipboard.writeText(jsx)
- toast.show('Copied as JSX')
-}
-
-function execCommand(cmd: string) {
- window.document.execCommand(cmd)
-}
-
const cls = {
menu: menuContent({
class: 'min-w-56 shadow-[0_8px_30px_rgb(0_0_0/0.4)] animate-in fade-in zoom-in-95'
@@ -75,129 +44,162 @@ const cls = {
</script>
<template>
- <ContextMenuContent :class="cls.menu" :side-offset="2" align="start">
- <ContextMenuItem :class="cls.item" :disabled="!hasSelection" @select="execCommand('copy')">
- <span>Copy</span><span class="text-[11px] text-muted">⌘C</span>
- </ContextMenuItem>
- <ContextMenuItem :class="cls.item" :disabled="!hasSelection" @select="execCommand('cut')">
- <span>Cut</span><span class="text-[11px] text-muted">⌘X</span>
- </ContextMenuItem>
- <ContextMenuItem :class="cls.item" @select="execCommand('paste')">
- <span>Paste here</span><span class="text-[11px] text-muted">⌘V</span>
- </ContextMenuItem>
- <ContextMenuItem
- :class="cls.item"
- :disabled="!hasSelection"
- @select="store.duplicateSelected()"
- >
- <span>Duplicate</span><span class="text-[11px] text-muted">⌘D</span>
- </ContextMenuItem>
- <ContextMenuItem :class="cls.item" :disabled="!hasSelection" @select="store.deleteSelected()">
- <span>Delete</span><span class="text-[11px] text-muted">⌫</span>
- </ContextMenuItem>
-
- <ContextMenuSeparator :class="cls.sep" />
-
- <ContextMenuSub v-if="otherPages.length > 0 && hasSelection">
- <ContextMenuSubTrigger :class="cls.item">
- <span>Move to page</span><span class="text-sm text-muted">›</span>
- </ContextMenuSubTrigger>
- <ContextMenuPortal>
- <ContextMenuSubContent :class="cls.menu">
- <ContextMenuItem
- v-for="page in otherPages"
- :key="page.id"
- :class="cls.item"
- @select="store.moveToPage(page.id)"
- >
- {{ page.name }}
- </ContextMenuItem>
- </ContextMenuSubContent>
- </ContextMenuPortal>
- </ContextMenuSub>
-
- <ContextMenuItem :class="cls.item" :disabled="!hasSelection" @select="store.bringToFront()">
- <span>Bring to front</span><span class="text-[11px] text-muted">]</span>
- </ContextMenuItem>
- <ContextMenuItem :class="cls.item" :disabled="!hasSelection" @select="store.sendToBack()">
- <span>Send to back</span><span class="text-[11px] text-muted">[</span>
- </ContextMenuItem>
-
- <ContextMenuSeparator :class="cls.sep" />
-
- <ContextMenuItem
- :class="cls.item"
- :disabled="selectedCount < 2"
- @select="store.groupSelected()"
- >
- <span>Group</span><span class="text-[11px] text-muted">⌘G</span>
- </ContextMenuItem>
- <ContextMenuItem v-if="isGroup" :class="cls.item" @select="store.ungroupSelected()">
- <span>Ungroup</span><span class="text-[11px] text-muted">⇧⌘G</span>
- </ContextMenuItem>
- <ContextMenuItem v-if="hasSelection" :class="cls.item" @select="store.wrapInAutoLayout()">
- <span>Add auto layout</span><span class="text-[11px] text-muted">⇧A</span>
- </ContextMenuItem>
-
- <ContextMenuSeparator :class="cls.sep" />
-
- <ContextMenuItem
- :class="cls.component"
- :disabled="!hasSelection"
- @select="store.createComponentFromSelection()"
- >
- <span>Create component</span><span class="text-[11px] text-component/60">⌥⌘K</span>
- </ContextMenuItem>
- <ContextMenuItem
- v-if="canCreateComponentSet"
- :class="cls.component"
- @select="store.createComponentSetFromComponents()"
- >
- <span>Create component set</span><span class="text-[11px] text-component/60">⇧⌘K</span>
- </ContextMenuItem>
- <ContextMenuItem
- v-if="isComponent && selectedNode"
- :class="cls.component"
- @select="store.createInstanceFromComponent(selectedNode.id)"
- >
- <span>Create instance</span>
- </ContextMenuItem>
- <ContextMenuItem v-if="isInstance" :class="cls.component" @select="store.goToMainComponent()">
- <span>Go to main component</span>
- </ContextMenuItem>
- <ContextMenuItem v-if="isInstance" :class="cls.item" @select="store.detachInstance()">
- <span>Detach instance</span><span class="text-[11px] text-muted">⌥⌘B</span>
- </ContextMenuItem>
-
- <template v-if="hasSelection">
- <ContextMenuSeparator :class="cls.sep" />
-
- <ContextMenuItem :class="cls.item" @select="store.toggleVisibility()">
- <span>{{ isVisible ? 'Hide' : 'Show' }}</span
- ><span class="text-[11px] text-muted">⇧⌘H</span>
+ <EditorMenuRoot
+ v-slot="{
+ editor,
+ hasSelection,
+ selectedCount,
+ selectedNode,
+ isInstance,
+ isComponent,
+ isGroup,
+ isVisible,
+ isLocked,
+ canCreateComponentSet,
+ otherPages,
+ copyAsText,
+ copyAsSVG,
+ copyAsJSX
+ }"
+ >
+ <ContextMenuContent :class="cls.menu" :side-offset="2" align="start">
+ <ContextMenuItem :class="cls.item" :disabled="!hasSelection" @select="execCommand('copy')">
+ <span>Copy</span><span class="text-[11px] text-muted">⌘C</span>
</ContextMenuItem>
- <ContextMenuItem :class="cls.item" @select="store.toggleLock()">
- <span>{{ isLocked ? 'Unlock' : 'Lock' }}</span
- ><span class="text-[11px] text-muted">⇧⌘L</span>
+ <ContextMenuItem :class="cls.item" :disabled="!hasSelection" @select="execCommand('cut')">
+ <span>Cut</span><span class="text-[11px] text-muted">⌘X</span>
+ </ContextMenuItem>
+ <ContextMenuItem :class="cls.item" @select="execCommand('paste')">
+ <span>Paste here</span><span class="text-[11px] text-muted">⌘V</span>
+ </ContextMenuItem>
+ <ContextMenuItem
+ :class="cls.item"
+ :disabled="!hasSelection"
+ @select="editor.duplicateSelected()"
+ >
+ <span>Duplicate</span><span class="text-[11px] text-muted">⌘D</span>
+ </ContextMenuItem>
+ <ContextMenuItem
+ :class="cls.item"
+ :disabled="!hasSelection"
+ @select="editor.deleteSelected()"
+ >
+ <span>Delete</span><span class="text-[11px] text-muted">⌫</span>
</ContextMenuItem>
<ContextMenuSeparator :class="cls.sep" />
- <ContextMenuSub>
+ <ContextMenuSub v-if="otherPages.length > 0 && hasSelection">
<ContextMenuSubTrigger :class="cls.item">
- <span>Copy/Paste as</span><span class="text-sm text-muted">›</span>
+ <span>Move to page</span><span class="text-sm text-muted">›</span>
</ContextMenuSubTrigger>
<ContextMenuPortal>
<ContextMenuSubContent :class="cls.menu">
- <ContextMenuItem :class="cls.item" @select="copyAsText">Copy as text</ContextMenuItem>
- <ContextMenuItem :class="cls.item" @select="copyAsSVG">Copy as SVG</ContextMenuItem>
- <ContextMenuItem :class="cls.item" @select="copyAsPNG">
- <span>Copy as PNG</span><span class="text-[11px] text-muted">⇧⌘C</span>
+ <ContextMenuItem
+ v-for="page in otherPages"
+ :key="page.id"
+ :class="cls.item"
+ @select="editor.moveToPage(page.id)"
+ >
+ {{ page.name }}
</ContextMenuItem>
- <ContextMenuItem :class="cls.item" @select="copyAsJSX">Copy as JSX</ContextMenuItem>
</ContextMenuSubContent>
</ContextMenuPortal>
</ContextMenuSub>
- </template>
- </ContextMenuContent>
+
+ <ContextMenuItem :class="cls.item" :disabled="!hasSelection" @select="editor.bringToFront()">
+ <span>Bring to front</span><span class="text-[11px] text-muted">]</span>
+ </ContextMenuItem>
+ <ContextMenuItem :class="cls.item" :disabled="!hasSelection" @select="editor.sendToBack()">
+ <span>Send to back</span><span class="text-[11px] text-muted">[</span>
+ </ContextMenuItem>
+
+ <ContextMenuSeparator :class="cls.sep" />
+
+ <ContextMenuItem
+ :class="cls.item"
+ :disabled="selectedCount < 2"
+ @select="editor.groupSelected()"
+ >
+ <span>Group</span><span class="text-[11px] text-muted">⌘G</span>
+ </ContextMenuItem>
+ <ContextMenuItem v-if="isGroup" :class="cls.item" @select="editor.ungroupSelected()">
+ <span>Ungroup</span><span class="text-[11px] text-muted">⇧⌘G</span>
+ </ContextMenuItem>
+ <ContextMenuItem v-if="hasSelection" :class="cls.item" @select="editor.wrapInAutoLayout()">
+ <span>Add auto layout</span><span class="text-[11px] text-muted">⇧A</span>
+ </ContextMenuItem>
+
+ <ContextMenuSeparator :class="cls.sep" />
+
+ <ContextMenuItem
+ :class="cls.component"
+ :disabled="!hasSelection"
+ @select="editor.createComponentFromSelection()"
+ >
+ <span>Create component</span><span class="text-[11px] text-component/60">⌥⌘K</span>
+ </ContextMenuItem>
+ <ContextMenuItem
+ v-if="canCreateComponentSet"
+ :class="cls.component"
+ @select="editor.createComponentSetFromComponents()"
+ >
+ <span>Create component set</span><span class="text-[11px] text-component/60">⇧⌘K</span>
+ </ContextMenuItem>
+ <ContextMenuItem
+ v-if="isComponent && selectedNode"
+ :class="cls.component"
+ @select="editor.createInstanceFromComponent(selectedNode.id)"
+ >
+ <span>Create instance</span>
+ </ContextMenuItem>
+ <ContextMenuItem
+ v-if="isInstance"
+ :class="cls.component"
+ @select="editor.goToMainComponent()"
+ >
+ <span>Go to main component</span>
+ </ContextMenuItem>
+ <ContextMenuItem v-if="isInstance" :class="cls.item" @select="editor.detachInstance()">
+ <span>Detach instance</span><span class="text-[11px] text-muted">⌥⌘B</span>
+ </ContextMenuItem>
+
+ <template v-if="hasSelection">
+ <ContextMenuSeparator :class="cls.sep" />
+
+ <ContextMenuItem :class="cls.item" @select="editor.toggleVisibility()">
+ <span>{{ isVisible ? 'Hide' : 'Show' }}</span
+ ><span class="text-[11px] text-muted">⇧⌘H</span>
+ </ContextMenuItem>
+ <ContextMenuItem :class="cls.item" @select="editor.toggleLock()">
+ <span>{{ isLocked ? 'Unlock' : 'Lock' }}</span
+ ><span class="text-[11px] text-muted">⇧⌘L</span>
+ </ContextMenuItem>
+
+ <ContextMenuSeparator :class="cls.sep" />
+
+ <ContextMenuSub>
+ <ContextMenuSubTrigger :class="cls.item">
+ <span>Copy/Paste as</span><span class="text-sm text-muted">›</span>
+ </ContextMenuSubTrigger>
+ <ContextMenuPortal>
+ <ContextMenuSubContent :class="cls.menu">
+ <ContextMenuItem :class="cls.item" @select="clipboardWrite(copyAsText(), 'text')"
+ >Copy as text</ContextMenuItem
+ >
+ <ContextMenuItem :class="cls.item" @select="clipboardWrite(copyAsSVG(), 'SVG')"
+ >Copy as SVG</ContextMenuItem
+ >
+ <ContextMenuItem :class="cls.item" @select="copyAsPNG">
+ <span>Copy as PNG</span><span class="text-[11px] text-muted">⇧⌘C</span>
+ </ContextMenuItem>
+ <ContextMenuItem :class="cls.item" @select="clipboardWrite(copyAsJSX(), 'JSX')"
+ >Copy as JSX</ContextMenuItem
+ >
+ </ContextMenuSubContent>
+ </ContextMenuPortal>
+ </ContextMenuSub>
+ </template>
+ </ContextMenuContent>
+ </EditorMenuRoot>
</template>
diff --git a/src/components/LayerRow.vue b/src/components/LayerRow.vue
deleted file mode 100644
index 40a86b442..000000000
--- a/src/components/LayerRow.vue
+++ /dev/null
@@ -1,220 +0,0 @@
-<script setup lang="ts">
-import { ref, type Component, type Ref } from 'vue'
-import { TreeItem } from 'reka-ui'
-
-import { nodeIcon, COMPONENT_TYPES } from '@/utils/layer-icons'
-import type { EditorStore } from '@/stores/editor'
-import type { Instruction } from '@atlaskit/pragmatic-drag-and-drop-hitbox/tree-item'
-
-interface LayerNode {
- id: string
- name: string
- type: string
- layoutMode: string
- visible: boolean
- locked: boolean
-}
-
-type TreeInstruction = Extract<
- Instruction,
- { type: 'reorder-above' | 'reorder-below' | 'make-child' }
->
-
-const {
- itemValue,
- level,
- hasChildren,
- rename,
- store,
- draggingId,
- instruction,
- instructionTargetId,
- indentPerLevel,
- setupItem
-} = defineProps<{
- itemValue: LayerNode
- level: number
- hasChildren: boolean
- rename: {
- editingId: Ref<string | null>
- focusInput: (el: HTMLInputElement | null) => void
- start: (id: string, name: string) => void
- commit: (id: string, el: HTMLInputElement) => void
- onKeydown: (e: KeyboardEvent) => void
- }
- store: EditorStore
- draggingId: string | null
- instruction: TreeInstruction | null
- instructionTargetId: string | null
- indentPerLevel: number
- setupItem: (
- el: Ref<HTMLElement | null>,
- item: () => { id: string; level: number; hasChildren: boolean; parentId: string | null }
- ) => void
-}>()
-
-const emit = defineEmits<{
- select: [ev: CustomEvent]
- toggleExpand: [id: string]
-}>()
-
-const rowEl = ref<HTMLElement | null>(null)
-
-setupItem(rowEl, () => ({
- id: itemValue.id,
- level,
- hasChildren,
- parentId: store.graph.getNode(itemValue.id)?.parentId ?? null
-}))
-
-defineExpose({ rowEl })
-
-const icon = nodeIcon(itemValue) as Component
-const isComponent = COMPONENT_TYPES.has(itemValue.type)
-const isTarget = () => instructionTargetId === itemValue.id
-const padLeft = `${8 + (level - 1) * indentPerLevel}px`
-</script>
-
-<template>
- <div ref="rowEl" :data-node-id="itemValue.id">
- <TreeItem
- v-slot="{ isExpanded }"
- :value="itemValue"
- :level="level"
- as-child
- @select="emit('select', $event)"
- @toggle="
- (e: CustomEvent) => {
- if (e.detail.originalEvent?.type === 'click') e.preventDefault()
- }
- "
- >
- <!-- Rename input -->
- <div
- v-if="rename.editingId.value === itemValue.id"
- class="flex w-full items-center gap-1 py-1"
- :style="{ paddingLeft: padLeft }"
- >
- <span
- v-if="hasChildren"
- class="flex w-4 shrink-0 cursor-pointer items-center justify-center text-muted transition-transform hover:text-surface"
- :class="isExpanded ? 'rotate-90' : 'rotate-0'"
- @click.stop="emit('toggleExpand', itemValue.id)"
- >
- <icon-lucide-chevron-right class="size-3" />
- </span>
- <span v-else class="w-4 shrink-0" />
- <component :is="icon" class="size-3 shrink-0 opacity-70" />
- <input
- :ref="
- (el) => {
- if (el) rename.focusInput(el as HTMLInputElement)
- }
- "
- data-layer-edit
- data-test-id="layers-item-input"
- class="min-w-0 flex-1 rounded border border-accent bg-input px-1 py-0 text-xs text-surface outline-none"
- :value="itemValue.name"
- @blur="rename.commit(itemValue.id, $event.target as HTMLInputElement)"
- @keydown="rename.onKeydown"
- />
- </div>
-
- <!-- Normal row -->
- <button
- v-else
- data-test-id="layers-item"
- class="group/row relative flex w-full cursor-pointer items-center gap-1 rounded border-none py-1 pr-1 text-left text-xs"
- :class="[
- store.state.selectedIds.has(itemValue.id)
- ? 'bg-accent text-white'
- : 'bg-transparent text-surface hover:bg-hover',
- draggingId === itemValue.id ? 'opacity-30' : '',
- isTarget() && instruction?.type === 'make-child' ? 'ring-2 ring-accent ring-inset' : '',
- !itemValue.visible ? 'opacity-50' : ''
- ]"
- :style="{ paddingLeft: padLeft }"
- @dblclick="rename.start(itemValue.id, itemValue.name)"
- >
- <span
- v-if="hasChildren"
- class="flex w-4 shrink-0 cursor-pointer items-center justify-center text-muted transition-transform hover:text-surface"
- :class="isExpanded ? 'rotate-90' : 'rotate-0'"
- @click.stop="emit('toggleExpand', itemValue.id)"
- >
- <icon-lucide-chevron-right class="size-3" />
- </span>
- <span v-else class="w-4 shrink-0" />
-
- <component
- :is="icon"
- class="size-3 shrink-0"
- :class="isComponent ? 'text-component opacity-100' : 'opacity-70'"
- />
-
- <span class="min-w-0 flex-1 truncate">{{ itemValue.name }}</span>
-
- <!-- Lock + visibility -->
- <span
- class="flex shrink-0 items-center gap-0.5"
- :class="
- !itemValue.locked && itemValue.visible ? 'opacity-0 group-hover/row:opacity-100' : ''
- "
- >
- <span
- class="flex size-4 items-center justify-center rounded hover:bg-white/15"
- :title="itemValue.locked ? 'Unlock' : 'Lock'"
- @pointerdown.stop
- @click.stop="store.toggleNodeLock(itemValue.id)"
- >
- <icon-lucide-lock
- v-if="itemValue.locked"
- class="size-3"
- :class="store.state.selectedIds.has(itemValue.id) ? 'text-white' : 'text-surface'"
- />
- <icon-lucide-unlock
- v-else
- class="size-3 opacity-0 group-hover/row:opacity-100"
- :class="
- store.state.selectedIds.has(itemValue.id) ? 'text-white/80' : 'text-surface/70'
- "
- />
- </span>
- <span
- class="flex size-4 items-center justify-center rounded hover:bg-white/15"
- :title="itemValue.visible ? 'Hide' : 'Show'"
- @pointerdown.stop
- @click.stop="store.toggleNodeVisibility(itemValue.id)"
- >
- <icon-lucide-eye-off
- v-if="!itemValue.visible"
- class="size-3"
- :class="store.state.selectedIds.has(itemValue.id) ? 'text-white' : 'text-surface'"
- />
- <icon-lucide-eye
- v-else
- class="size-3 opacity-0 group-hover/row:opacity-100"
- :class="
- store.state.selectedIds.has(itemValue.id) ? 'text-white/80' : 'text-surface/70'
- "
- />
- </span>
- </span>
-
- <!-- Drop indicators -->
- <div
- v-if="isTarget() && instruction && instruction.type !== 'make-child'"
- class="pointer-events-none absolute h-0.5 bg-accent"
- :class="{
- 'bottom-0': instruction.type === 'reorder-below',
- 'top-0': instruction.type === 'reorder-above'
- }"
- :style="{
- left: `${(level - 1) * indentPerLevel}px`,
- width: `calc(100% - ${(level - 1) * indentPerLevel}px)`
- }"
- />
- </button>
- </TreeItem>
- </div>
-</template>
diff --git a/src/components/LayerTree.vue b/src/components/LayerTree.vue
index ca8421d51..c6ca86cc8 100644
--- a/src/components/LayerTree.vue
+++ b/src/components/LayerTree.vue
@@ -1,166 +1,209 @@
<script setup lang="ts">
-import { nextTick, ref, watch } from 'vue'
-import { TreeRoot, ContextMenuRoot, ContextMenuTrigger, ContextMenuPortal } from 'reka-ui'
+import { TreeRoot, TreeItem, ContextMenuRoot, ContextMenuTrigger, ContextMenuPortal } from 'reka-ui'
-import { useInlineRename, useLayerDrag } from '@open-pencil/vue'
+import { LayerTreeRoot, LayerTreeItem, useInlineRename, useLayerDrag } from '@open-pencil/vue'
import { useEditorStore } from '@/stores/editor'
-import LayerRow from './LayerRow.vue'
+import { nodeIcon, COMPONENT_TYPES } from '@/utils/layer-icons'
import CanvasMenu from './CanvasMenu.vue'
-const INDENT_PER_LEVEL = 16
-
+const INDENT = 16
const store = useEditorStore()
const rename = useInlineRename((id, name) => store.renameNode(id, name))
-
-const { draggingId, instruction, instructionTargetId, setupItem } = useLayerDrag(
- store,
- INDENT_PER_LEVEL
-)
-
-// ─── Layer node type ────────────────────────────────────────
-
-interface LayerNode {
- id: string
- name: string
- type: string
- layoutMode: string
- visible: boolean
- locked: boolean
- children?: LayerNode[]
-}
-
-// ─── Tree data ──────────────────────────────────────────────
-
-function buildTree(parentId: string): LayerNode[] {
- const parent = store.graph.getNode(parentId)
- if (!parent) return []
- return parent.childIds
- .map((cid) => store.graph.getNode(cid))
- .filter((n): n is NonNullable<typeof n> => !!n)
- .map((node) => ({
- id: node.id,
- name: node.name,
- type: node.type,
- layoutMode: node.layoutMode,
- visible: node.visible,
- locked: node.locked,
- children: node.childIds.length > 0 ? buildTree(node.id) : undefined
- }))
-}
-
-const items = ref(buildTree(store.state.currentPageId))
-const treeKey = ref(0)
-const expanded = ref<string[]>([])
-
-watch([() => store.state.sceneVersion, () => store.state.currentPageId], () => {
- items.value = buildTree(store.state.currentPageId)
- treeKey.value++
-})
-
-const rowRefs = new Map<string, HTMLElement>()
-
-function setRowRef(id: string, el: HTMLElement | null) {
- if (el) rowRefs.set(id, el)
- else rowRefs.delete(id)
-}
-
-watch(
- () => store.state.selectedIds,
- (ids) => {
- const toExpand = new Set(expanded.value)
- for (const id of ids) {
- let node = store.graph.getNode(id)
- while (node?.parentId && node.parentId !== store.state.currentPageId) {
- toExpand.add(node.parentId)
- node = store.graph.getNode(node.parentId)
- }
- }
- if (toExpand.size > expanded.value.length) expanded.value = [...toExpand]
- nextTick(() => {
- const first = [...ids][0]
- if (first) rowRefs.get(first)?.scrollIntoView({ block: 'nearest' })
- })
- }
-)
-
-// ─── Selection ──────────────────────────────────────────────
-
-function onSelect(ev: CustomEvent) {
- ev.preventDefault()
- const node = ev.detail.value as LayerNode
- if (ev.detail.originalEvent?.shiftKey) {
- store.select([node.id], true)
- } else {
- store.select([node.id])
- syncCanvasScope(node.id)
- }
-}
-
-function syncCanvasScope(nodeId: string) {
- const node = store.graph.getNode(nodeId)
- if (!node) return
- let parentId = node.parentId
- while (parentId && parentId !== store.state.currentPageId) {
- if (store.graph.isContainer(parentId)) {
- store.enterContainer(parentId)
- return
- }
- const parent = store.graph.getNode(parentId)
- parentId = parent?.parentId ?? null
- }
- store.state.enteredContainerId = null
-}
+const { draggingId, instruction, instructionTargetId } = useLayerDrag(store, INDENT)
function onLayerRightClick(e: MouseEvent) {
const row = (e.target as HTMLElement).closest<HTMLElement>('[data-node-id]')
if (!row?.dataset.nodeId) return
- if (!store.state.selectedIds.has(row.dataset.nodeId)) {
- store.select([row.dataset.nodeId])
- }
-}
-
-function toggleExpand(id: string) {
- const idx = expanded.value.indexOf(id)
- if (idx !== -1) expanded.value = expanded.value.filter((e) => e !== id)
- else expanded.value = [...expanded.value, id]
+ if (!store.state.selectedIds.has(row.dataset.nodeId)) store.select([row.dataset.nodeId])
}
</script>
<template>
- <ContextMenuRoot :modal="false">
- <ContextMenuTrigger as-child @contextmenu="onLayerRightClick">
- <div class="relative scrollbar-thin flex-1 overflow-y-auto px-1">
- <TreeRoot
- :key="treeKey"
- v-slot="{ flattenItems }"
- v-model:expanded="expanded"
- :items="items"
- :get-key="(v: LayerNode) => v.id"
- :get-children="(v: LayerNode) => v.children"
- >
- <LayerRow
- v-for="item in flattenItems"
- :key="item._id"
- :ref="(comp: any) => setRowRef(item.value.id, comp?.rowEl ?? null)"
- :item-value="item.value"
- :level="item.level"
- :has-children="item.hasChildren"
- :rename="rename"
- :store="store"
- :dragging-id="draggingId"
- :instruction="instruction"
- :instruction-target-id="instructionTargetId"
- :indent-per-level="INDENT_PER_LEVEL"
- :setup-item="setupItem"
- @select="onSelect"
- @toggle-expand="toggleExpand"
- />
- </TreeRoot>
- </div>
- </ContextMenuTrigger>
- <ContextMenuPortal>
- <CanvasMenu />
- </ContextMenuPortal>
- </ContextMenuRoot>
+ <LayerTreeRoot
+ v-slot="{ items, expanded, treeKey, getKey, getChildren }"
+ :indent-per-level="INDENT"
+ >
+ <ContextMenuRoot :modal="false">
+ <ContextMenuTrigger as-child @contextmenu="onLayerRightClick">
+ <div class="relative scrollbar-thin flex-1 overflow-y-auto px-1">
+ <TreeRoot
+ :key="treeKey"
+ v-slot="{ flattenItems }"
+ v-model:expanded="expanded"
+ :items="items"
+ :get-key="getKey"
+ :get-children="getChildren"
+ >
+ <LayerTreeItem
+ v-for="item in flattenItems"
+ :key="item._id"
+ v-slot="{
+ node,
+ isSelected,
+ padLeft,
+ select: selectNode,
+ toggleExpand,
+ toggleVisibility,
+ toggleLock
+ }"
+ :node="item.value"
+ :level="item.level"
+ :has-children="item.hasChildren"
+ >
+ <TreeItem
+ v-slot="{ isExpanded }"
+ :value="item.value"
+ :level="item.level"
+ as-child
+ @select="
+ (e: CustomEvent) => {
+ e.preventDefault()
+ selectNode(!!e.detail.originalEvent?.shiftKey)
+ }
+ "
+ @toggle="
+ (e: CustomEvent) => {
+ if (e.detail.originalEvent?.type === 'click') e.preventDefault()
+ }
+ "
+ >
+ <!-- Rename mode -->
+ <div
+ v-if="rename.editingId.value === node.id"
+ class="flex w-full items-center gap-1 py-1"
+ :style="{ paddingLeft: padLeft }"
+ >
+ <span
+ v-if="item.hasChildren"
+ class="flex w-4 shrink-0 cursor-pointer items-center justify-center text-muted transition-transform hover:text-surface"
+ :class="isExpanded ? 'rotate-90' : 'rotate-0'"
+ @click.stop="toggleExpand"
+ >
+ <icon-lucide-chevron-right class="size-3" />
+ </span>
+ <span v-else class="w-4 shrink-0" />
+ <component :is="nodeIcon(node)" class="size-3 shrink-0 opacity-70" />
+ <input
+ :ref="
+ (el) => {
+ if (el) rename.focusInput(el as HTMLInputElement)
+ }
+ "
+ data-layer-edit
+ data-test-id="layers-item-input"
+ class="min-w-0 flex-1 rounded border border-accent bg-input px-1 py-0 text-xs text-surface outline-none"
+ :value="node.name"
+ @blur="rename.commit(node.id, $event.target as HTMLInputElement)"
+ @keydown="rename.onKeydown"
+ />
+ </div>
+
+ <!-- Normal row -->
+ <button
+ v-else
+ data-test-id="layers-item"
+ class="group/row relative flex w-full cursor-pointer items-center gap-1 rounded border-none py-1 pr-1 text-left text-xs"
+ :class="[
+ isSelected
+ ? 'bg-accent text-white'
+ : 'bg-transparent text-surface hover:bg-hover',
+ draggingId === node.id ? 'opacity-30' : '',
+ instructionTargetId === node.id && instruction?.type === 'make-child'
+ ? 'ring-2 ring-accent ring-inset'
+ : '',
+ !node.visible ? 'opacity-50' : ''
+ ]"
+ :style="{ paddingLeft: padLeft }"
+ @dblclick="rename.start(node.id, node.name)"
+ >
+ <span
+ v-if="item.hasChildren"
+ class="flex w-4 shrink-0 cursor-pointer items-center justify-center text-muted transition-transform hover:text-surface"
+ :class="isExpanded ? 'rotate-90' : 'rotate-0'"
+ @click.stop="toggleExpand"
+ >
+ <icon-lucide-chevron-right class="size-3" />
+ </span>
+ <span v-else class="w-4 shrink-0" />
+
+ <component
+ :is="nodeIcon(node)"
+ class="size-3 shrink-0"
+ :class="
+ COMPONENT_TYPES.has(node.type) ? 'text-component opacity-100' : 'opacity-70'
+ "
+ />
+ <span class="min-w-0 flex-1 truncate">{{ node.name }}</span>
+
+ <span
+ class="flex shrink-0 items-center gap-0.5"
+ :class="
+ !node.locked && node.visible ? 'opacity-0 group-hover/row:opacity-100' : ''
+ "
+ >
+ <span
+ class="flex size-4 items-center justify-center rounded hover:bg-white/15"
+ :title="node.locked ? 'Unlock' : 'Lock'"
+ @pointerdown.stop
+ @click.stop="toggleLock"
+ >
+ <icon-lucide-lock
+ v-if="node.locked"
+ class="size-3"
+ :class="isSelected ? 'text-white' : 'text-surface'"
+ />
+ <icon-lucide-unlock
+ v-else
+ class="size-3 opacity-0 group-hover/row:opacity-100"
+ :class="isSelected ? 'text-white/80' : 'text-surface/70'"
+ />
+ </span>
+ <span
+ class="flex size-4 items-center justify-center rounded hover:bg-white/15"
+ :title="node.visible ? 'Hide' : 'Show'"
+ @pointerdown.stop
+ @click.stop="toggleVisibility"
+ >
+ <icon-lucide-eye-off
+ v-if="!node.visible"
+ class="size-3"
+ :class="isSelected ? 'text-white' : 'text-surface'"
+ />
+ <icon-lucide-eye
+ v-else
+ class="size-3 opacity-0 group-hover/row:opacity-100"
+ :class="isSelected ? 'text-white/80' : 'text-surface/70'"
+ />
+ </span>
+ </span>
+
+ <!-- DnD indicator -->
+ <div
+ v-if="
+ instructionTargetId === node.id &&
+ instruction &&
+ instruction.type !== 'make-child'
+ "
+ class="pointer-events-none absolute h-0.5 bg-accent"
+ :class="{
+ 'bottom-0': instruction.type === 'reorder-below',
+ 'top-0': instruction.type === 'reorder-above'
+ }"
+ :style="{
+ left: `${(item.level - 1) * INDENT}px`,
+ width: `calc(100% - ${(item.level - 1) * INDENT}px)`
+ }"
+ />
+ </button>
+ </TreeItem>
+ </LayerTreeItem>
+ </TreeRoot>
+ </div>
+ </ContextMenuTrigger>
+ <ContextMenuPortal>
+ <CanvasMenu />
+ </ContextMenuPortal>
+ </ContextMenuRoot>
+ </LayerTreeRoot>
</template>