AI-native design editor. Open-source Figma alternative.
feat: pin the top-level layer at the top of the layers panel, as in Figma (#1196)
rcoenen4557c7ed68ac
diff --git a/changes/1196/added.md b/changes/1196/added.mdnew file mode 100644index 000000000..cba5bb278--- /dev/null+++ b/changes/1196/added.md@@ -0,0 +1 @@+- While you scroll through a top-level frame's layers, its row stays pinned at the top of the layers panel, as in Figma, until the next top-level layer pushes it out.diff --git a/packages/vue/src/index.ts b/packages/vue/src/index.tsindex 8d951e74c..5353a34dc 100644--- a/packages/vue/src/index.ts+++ b/packages/vue/src/index.ts@@ -244,6 +244,7 @@ export {LayerTreeItem,LayerTreeRoot,patchLayerNode,+ stickyTopLevelRow,useLayerTree,visibleLayerRows} from '#vue/primitives/LayerTree'@@ -251,6 +252,7 @@ export type {LayerDragInstruction,LayerNode,LayerRow,+ StickyLayerRow,LayerSelectionMode,LayerTreeContext,LayerOutline,diff --git a/packages/vue/src/primitives/LayerTree/index.ts b/packages/vue/src/primitives/LayerTree/index.tsindex e6a3defa9..537f5d962 100644--- a/packages/vue/src/primitives/LayerTree/index.ts+++ b/packages/vue/src/primitives/LayerTree/index.ts@@ -17,3 +17,4 @@ export {patchLayerNode,visibleLayerRows} from '#vue/primitives/LayerTree/model'+export { stickyTopLevelRow, type StickyLayerRow } from '#vue/primitives/LayerTree/sticky'diff --git a/packages/vue/src/primitives/LayerTree/sticky.ts b/packages/vue/src/primitives/LayerTree/sticky.tsnew file mode 100644index 000000000..5e8cb9f56--- /dev/null+++ b/packages/vue/src/primitives/LayerTree/sticky.ts@@ -0,0 +1,44 @@+import type { LayerRow } from '#vue/primitives/LayerTree/context'++export interface StickyLayerRow {+ /** The pinned row's index among the visible rows. */+ index: number+ /** How far up, in pixels, the next top-level row pushes it; 0 or less. */+ offset: number+}++/**+ * The top-level row the layers panel pins while you scroll through its children, as Figma's+ * does: one row at a time, the last top-level row at or above the first visible one, and only+ * while it is expanded with its children showing and its own row has scrolled off the top. The+ * next top-level row pushes it up as it arrives. Null when nothing is pinned.+ */+export function stickyTopLevelRow(+ rows: readonly LayerRow[],+ scrollTop: number,+ rowHeight: number+): StickyLayerRow | null {+ if (rows.length === 0 || scrollTop <= 0 || rowHeight <= 0) return null+ const firstVisible = Math.min(Math.floor(scrollTop / rowHeight), rows.length - 1)+ let index = -1+ for (let i = firstVisible; i >= 0; i--) {+ if (rows[i].level === 1) {+ index = i+ break+ }+ }+ if (index === -1) return null+ const expanded = rows[index].hasChildren && (rows[index + 1]?.level ?? 1) > 1+ // Still in full view at the top: nothing to pin yet.+ if (!expanded || index * rowHeight >= scrollTop) return null++ let next = -1+ for (let i = index + 1; i < rows.length; i++) {+ if (rows[i].level === 1) {+ next = i+ break+ }+ }+ const offset = next === -1 ? 0 : Math.min(0, (next - 1) * rowHeight - scrollTop)+ return { index, offset }+}diff --git a/packages/vue/tests/primitives/LayerTree/sticky.test.ts b/packages/vue/tests/primitives/LayerTree/sticky.test.tsnew file mode 100644index 000000000..59a89edf8--- /dev/null+++ b/packages/vue/tests/primitives/LayerTree/sticky.test.ts@@ -0,0 +1,48 @@+import { describe, expect, test } from 'bun:test'++import type { LayerRow } from '#vue/primitives/LayerTree/context'+import { stickyTopLevelRow } from '#vue/primitives/LayerTree/sticky'++const H = 24++/** Rows at the given levels; a row has children when the next row is deeper. */+function rows(levels: number[]): LayerRow[] {+ return levels.map((level, index) => ({+ node: {+ id: `n${index}`,+ name: `n${index}`,+ type: 'FRAME',+ layoutMode: 'NONE',+ visible: true,+ locked: false+ },+ level,+ hasChildren: (levels[index + 1] ?? 0) > level+ }))+}++describe('the pinned top-level layer', () => {+ // A frame with five children, then a second frame with two.+ const list = rows([1, 2, 2, 2, 2, 2, 1, 2, 2])++ test('pins nothing before the list scrolls or while the row is still in view', () => {+ expect(stickyTopLevelRow(list, 0, H)).toBeNull()+ })++ test('pins the frame whose children are scrolling beneath it', () => {+ expect(stickyTopLevelRow(list, 2 * H, H)).toEqual({ index: 0, offset: 0 })+ })++ test('is pushed up by the next top-level row, then replaced by it', () => {+ // Still 10 px below the pinned row: not touching it yet.+ expect(stickyTopLevelRow(list, 5 * H - 10, H)).toEqual({ index: 0, offset: 0 })+ // 10 px into the pinned row's slot: it is pushed 10 px up.+ expect(stickyTopLevelRow(list, 5 * H + 10, H)).toEqual({ index: 0, offset: -10 })+ expect(stickyTopLevelRow(list, 6 * H + 5, H)).toEqual({ index: 6, offset: 0 })+ })++ test('pins only an expanded top-level layer with children', () => {+ // Top-level rows with no children showing: nothing to pin.+ expect(stickyTopLevelRow(rows([1, 1, 1, 1, 1]), 2 * H, H)).toBeNull()+ })+})diff --git a/src/components/LayerTree/LayerTree.vue b/src/components/LayerTree/LayerTree.vueindex f098aec48..3b219988f 100644--- a/src/components/LayerTree/LayerTree.vue+++ b/src/components/LayerTree/LayerTree.vue@@ -1,4 +1,5 @@<script setup lang="ts">+import { useScroll } from '@vueuse/core'import {TreeItem,TreeVirtualizer,@@ -7,12 +8,13 @@ import {ContextMenuPortal} from 'reka-ui'import { tv } from 'tailwind-variants'-import { computed, useAttrs, watch } from 'vue'+import { computed, nextTick, useAttrs, useTemplateRef, watch } from 'vue'-import { LayerTreeRoot, LayerTreeItem, useInlineRename } from '@open-pencil/vue'+import { LayerTreeRoot, LayerTreeItem, stickyTopLevelRow, useInlineRename } from '@open-pencil/vue'import type {LayerDragInstruction,LayerNode,+ LayerRow,LayerSelectionMode,LayerTreeVirtualizer} from '@open-pencil/vue'@@ -26,6 +28,7 @@ import CanvasMenu from '../canvas/CanvasMenu.vue'import { LAYER_TREE_ROW_HEIGHT } from './geometry'import LayerTreeNodeRow from './LayerTreeNodeRow.vue'import LayerTreeRenameRow from './LayerTreeRenameRow.vue'+import LayerTreeStickyRow from './LayerTreeStickyRow.vue'import { provideLayerTreeUI } from './ui'import type { LayerTreeUI } from './ui'@@ -53,6 +56,9 @@ const attrs = useAttrs()const styles = tv(layerTreeTheme)()provideLayerTreeUI(() => ui)const store = useEditorStore()+const viewport = useTemplateRef<HTMLElement>('viewport')+/** How far the rows are scrolled, for the pinned top-level row. */+const { y: scrollTop } = useScroll(viewport)const rename = useInlineRename((id, name) => store.renameNode(id, name))/** Issue marks follow the canvas markers' View → Design issues toggle. */@@ -79,6 +85,13 @@ watch({ immediate: true })+/** Rename the pinned layer on its own row: scroll the list back to it, then start. */+async function renamePinned(id: string, name: string, index: number) {+ if (viewport.value) viewport.value.scrollTop = index * LAYER_TREE_ROW_HEIGHT+ await nextTick()+ rename.start(id, name)+}+function onLayerRightClick(e: MouseEvent) {const row = (e.target as HTMLElement).closest<HTMLElement>('[data-node-id]')if (!row?.dataset.nodeId) return@@ -140,11 +153,36 @@ function chrome(scope: Omit<LayerTreeSlotScope, 'actions'>) {}}+/**+ * Bring a row into view. A nested row stops below the top-level row pinned over the top of the+ * list, so the pin never covers it; rows are one height, so their place is exact.+ */+function revealRow(rows: readonly LayerRow[], index: number) {+ const el = viewport.value+ const row = rows.at(index)+ if (!el || !row) return+ // A layer showing as the pinned row is in view already, so selecting it keeps the list still.+ if (stickyTopLevelRow(rows, el.scrollTop, LAYER_TREE_ROW_HEIGHT)?.index === index) return+ const top = index * LAYER_TREE_ROW_HEIGHT+ const pinned = row.level > 1 ? LAYER_TREE_ROW_HEIGHT : 0+ if (top - pinned < el.scrollTop) {+ el.scrollTop = Math.max(0, top - pinned)+ } else if (top + LAYER_TREE_ROW_HEIGHT > el.scrollTop + el.clientHeight) {+ el.scrollTop = top + LAYER_TREE_ROW_HEIGHT - el.clientHeight+ }+}+function registerVirtualizer(actions: LayerTreeRootActions,- virtualizer: LayerTreeVirtualizer+ virtualizer: LayerTreeVirtualizer,+ rows: () => readonly LayerRow[]): boolean {- actions.setVirtualizer(virtualizer)+ actions.setVirtualizer({+ scrollToIndex: (index, options) => {+ if ((options?.align ?? 'auto') === 'auto') revealRow(rows(), index)+ else virtualizer.scrollToIndex(index, options)+ }+ })return true}@@ -164,14 +202,16 @@ function onFocusOut(event: FocusEvent, actions: LayerTreeRootActions) {<template><LayerTreeRoot v-slot="scope" :indent-per-level="INDENT"><ContextMenuRoot :modal="false">- <div- v-bind="attrs"- class="relative min-h-0 flex-1 overflow-hidden"- @focusin="scope.actions.setFocused(true)"- @focusout="onFocusOut($event, scope.actions)"- >- <ContextMenuTrigger as-child @contextmenu="onLayerRightClick">+ <!-- The trigger covers the pinned row too, so right-clicking it opens the layer menu. -->+ <ContextMenuTrigger as-child @contextmenu="onLayerRightClick">+ <div+ v-bind="attrs"+ class="relative min-h-0 flex-1 overflow-hidden"+ @focusin="scope.actions.setFocused(true)"+ @focusout="onFocusOut($event, scope.actions)"+ ><div+ ref="viewport"data-test-id="layers-scroll"data-slot="viewport":class="styles.viewport({ class: ui?.viewport })"@@ -181,7 +221,9 @@ function onFocusOut(event: FocusEvent, actions: LayerTreeRootActions) {:estimate-size="LAYER_TREE_ROW_HEIGHT":text-content="layerTextContent">- <template v-if="registerVirtualizer(scope.actions, virtualizer)">+ <template+ v-if="registerVirtualizer(scope.actions, virtualizer, () => scope.visibleRows)"+ ><TreeItemv-slot="{ isExpanded }"v-bind="item.bind"@@ -243,8 +285,13 @@ function onFocusOut(event: FocusEvent, actions: LayerTreeRootActions) {</template></TreeVirtualizer></div>- </ContextMenuTrigger>- </div>+ <LayerTreeStickyRow+ :scroll-top="scrollTop"+ :chrome="chrome({ ...scope, instruction: null, instructionTargetId: null })"+ @rename-start="renamePinned"+ />+ </div>+ </ContextMenuTrigger><ContextMenuPortal><CanvasMenu /></ContextMenuPortal>diff --git a/src/components/LayerTree/LayerTreeStickyRow.vue b/src/components/LayerTree/LayerTreeStickyRow.vuenew file mode 100644index 000000000..65bd6b3d3--- /dev/null+++ b/src/components/LayerTree/LayerTreeStickyRow.vue@@ -0,0 +1,80 @@+<script setup lang="ts">+import { computed } from 'vue'++import { stickyTopLevelRow, useLayerTree } from '@open-pencil/vue'++import type { LayerIssueMark } from '@/app/editor/design-check/layers'++import { LAYER_TREE_ROW_HEIGHT } from './geometry'+import LayerTreeNodeRow from './LayerTreeNodeRow.vue'+import type { LayerTreeChrome, LayerTreeItemActions } from './types'++/**+ * The top-level layer pinned at the top of the panel while its children scroll beneath it, as in+ * Figma (its layers panel pins `stickyTopLevelLayersPanelChildren` one at a time). It is the+ * row itself, so clicking, expanding, hiding and locking work as on the row in the list.+ */+const { scrollTop, chrome, issueMarks } = defineProps<{+ scrollTop: number+ chrome: LayerTreeChrome+ /** Design issues by layer, so the pinned row keeps its mark as the list row does. */+ issueMarks?: ReadonlyMap<string, LayerIssueMark> | null+}>()++const emit = defineEmits<{+ /** Renaming happens on the layer's own row, which the list scrolls back to at `index`. */+ renameStart: [id: string, name: string, index: number]+}>()++const tree = useLayerTree()++const pinned = computed(() => {+ const rows = tree.visibleRows.value+ const sticky = stickyTopLevelRow(rows, scrollTop, LAYER_TREE_ROW_HEIGHT)+ if (!sticky) return null+ return { row: rows[sticky.index], index: sticky.index, offset: sticky.offset }+})++const actions = computed<LayerTreeItemActions | null>(() => {+ const id = pinned.value?.row.node.id+ if (!id) return null+ return {+ select: (additive) => tree.select(id, additive),+ toggleExpand: () => tree.toggleExpand(id),+ toggleVisibility: () => tree.toggleVisibility(id),+ toggleLock: () => tree.toggleLock(id),+ rename: (name) => tree.rename(id, name)+ }+})++function select(event: MouseEvent) {+ const id = pinned.value?.row.node.id+ if (!id) return+ tree.select(id, { additive: event.metaKey || event.ctrlKey, range: event.shiftKey })+}+</script>++<template>+ <div+ v-if="pinned && actions"+ data-test-id="layers-sticky-row"+ :data-node-id="pinned.row.node.id"+ :data-pushing-away="pinned.offset < 0 || undefined"+ class="absolute inset-x-1 top-0 z-10 border-b border-border bg-panel"+ :style="{ transform: `translateY(${pinned.offset}px)` }"+ @click="select"+ >+ <LayerTreeNodeRow+ :node="pinned.row.node"+ :level="pinned.row.level"+ :has-children="pinned.row.hasChildren"+ :selected="tree.selectedIds.value.has(pinned.row.node.id)"+ pad-left="0px"+ :expanded="true"+ :actions="actions"+ :chrome="chrome"+ :issue="issueMarks?.get(pinned.row.node.id) ?? null"+ @rename-start="(id, name) => pinned && emit('renameStart', id, name, pinned.index)"+ />+ </div>+</template>diff --git a/tests/e2e/layers/sticky.spec.ts b/tests/e2e/layers/sticky.spec.tsnew file mode 100644index 000000000..c16aa74ef--- /dev/null+++ b/tests/e2e/layers/sticky.spec.ts@@ -0,0 +1,81 @@+import { expect, test, type Page } from '@playwright/test'++import { CanvasHelper } from '#tests/helpers/canvas'+import { layerDriver } from '#tests/helpers/canvas/layers'++/** A frame with enough children to scroll past its own row, expanded in the layers panel. */+async function scrolledFrame(page: Page) {+ await page.goto('/')+ const canvas = new CanvasHelper(page)+ await canvas.waitForInit()+ canvas.errors.length = 0+ await canvas.clearCanvas()++ const layers = layerDriver(() => page)+ const ids = await layers.frameWithChildren('Pinned frame', 60)+ // Selecting a child expands the frame in the layers panel.+ await layers.select([ids.children[0]])+ await canvas.waitForRender()++ await page.getByTestId('layers-scroll').evaluate((el) => {+ el.scrollTop = 600+ })+ const pinned = page.getByTestId('layers-sticky-row')+ await expect(pinned).toContainText('Pinned frame')+ return { canvas, layers, children: ids.children, pinned }+}++test('right-clicking the pinned frame row opens the layer menu for it', async ({ page }) => {+ const { canvas, pinned } = await scrolledFrame(page)++ await pinned.click({ button: 'right' })+ await expect(page.getByRole('menu')).toBeVisible()+ // The pinned row stays put and shows the frame selected.+ await expect(pinned.locator('[data-slot="row"]')).toHaveAttribute('data-selected', 'true')+ canvas.assertNoErrors()+})++test('clicking the pinned frame row selects it without moving the list', async ({ page }) => {+ const { canvas, pinned } = await scrolledFrame(page)+ const scroller = page.getByTestId('layers-scroll')+ const before = await scroller.evaluate((el) => el.scrollTop)++ await pinned.click()+ await expect(pinned.locator('[data-slot="row"]')).toHaveAttribute('data-selected', 'true')+ expect(await scroller.evaluate((el) => el.scrollTop)).toBe(before)+ canvas.assertNoErrors()+})++test('double-clicking the pinned frame row renames it on its own row', async ({ page }) => {+ const { canvas, pinned } = await scrolledFrame(page)++ await pinned.dblclick()+ const input = page.getByTestId('layers-item-input')+ await expect(input).toBeFocused()+ await expect(input).toHaveValue('Pinned frame')+ // The list scrolled back to the frame's row, so nothing is pinned while it is renamed.+ await expect(pinned).toHaveCount(0)+ canvas.assertNoErrors()+})++test("selecting a pinned frame's child scrolls its row into view below the pin", async ({+ page+}) => {+ const { canvas, layers, children, pinned } = await scrolledFrame(page)+ const scroller = page.getByTestId('layers-scroll')+ // Scroll to the end of the list, then select a child further up from outside the panel, as on+ // the canvas: the list scrolls back to it with the frame row pinned above.+ await scroller.evaluate((el) => {+ el.scrollTop = el.scrollHeight+ })+ const target = children[30]+ await layers.select([target])++ const row = page.locator(`[data-node-id="${target}"]`).getByTestId('layers-item')+ await expect(row).toBeVisible()+ await expect(pinned).toBeVisible()+ const pinBox = await pinned.boundingBox()+ const rowBox = await row.boundingBox()+ expect(rowBox?.y ?? 0).toBeGreaterThanOrEqual((pinBox?.y ?? 0) + (pinBox?.height ?? 0) - 1)+ canvas.assertNoErrors()+})diff --git a/tests/helpers/canvas/layers.ts b/tests/helpers/canvas/layers.tsindex de7ca8979..ce508f097 100644--- a/tests/helpers/canvas/layers.ts+++ b/tests/helpers/canvas/layers.ts@@ -57,6 +57,39 @@ export function layerDriver(page: () => Page) {)},+ /** Driver: a frame on the current page with `count` rectangles named `Child 1` and on. */+ frameWithChildren(name: string, count: number): Promise<{ frame: string; children: string[] }> {+ return page().evaluate(+ ({ frameName, childCount }) => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ const frame = store.graph.createNode('FRAME', store.state.currentPageId, {+ name: frameName,+ width: 400,+ height: 400+ })+ const children = Array.from(+ { length: childCount },+ (_, i) =>+ store.graph.createNode('RECTANGLE', frame.id, { name: `Child ${i + 1}`, x: i, y: i })+ .id+ )+ store.requestRender()+ return { frame: frame.id, children }+ },+ { frameName: name, childCount: count }+ )+ },++ /** Driver: selects layers by id, as a click on the canvas does, revealing them in the panel. */+ select(ids: readonly string[]): Promise<void> {+ return page().evaluate((layerIds) => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ store.select([...layerIds])+ }, ids)+ },+/** Driver: clears the selection, so a screenshot shows no handles. */clearSelection(): Promise<void> {return page().evaluate(() => {