AI-native design editor. Open-source Figma alternative.
feat(panel): edit multi-selections as Figma does (#1038)
Danila Poyarkov5c0d015abf11
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 957716abf..9d7ce591b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,7 @@### Breaking changes+- `useStrokeControls` from `@open-pencil/vue` acts on the whole selection: `updateAlign`, `selectSide`, and `updateBorderWeight` no longer take a node, and `currentAlign()` and `borderWeight(side)` read the selection and return `MIXED` when it differs. `useEffectsControls().scrubEffect` and `commitEffect` no longer take a node. `useTypography` edits every selected text layer and adds `nodes`, `merged`, and `fontFeature`. The `panels.layersCount` message is now `panels.selectedCount`.- The app renders `render` JSX itself and no longer accepts the pre-rendered tree that earlier versions of `openpencil-mcp` send, so an older `openpencil-mcp` fails to render into this app version; update it with the app.- `VectorizedPath` from `@open-pencil/core/vector` replaces `clipNetworks` with `clips`, each the clip path's `id` and one network per clip shape, and adds `elements`, the groups and shape a path was drawn from. `SVGVectorizeResult` adds `texts`, the SVG's text placed in the target space, and `SVGImportData` from `@open-pencil/core/io` adds the root `name` and whether the SVG is `sized`.- `VectorizedPath` from `@open-pencil/core/vector` replaces `clipNetworks` with `clips`, each the clip path's `id` and one network per clip shape, and adds `elements`, the groups and shape a path was drawn from. `SVGImportData` from `@open-pencil/core/io` adds the root `name` and whether the SVG is `sized`.@@ -43,6 +44,7 @@### Added+- Edit several layers at once as in Figma: the properties panel gives a multi-selection a Layout section with sizes, text resizing, flow, clip content, and a Spacing field that spaces a row or column evenly; Typography for the text among it; corner radius for the layers that have one; the stroke of the layers that have strokes; and Selection colors, which lists every fill and stroke colour in the selection and its children and recolours one everywhere it is used. The panel's header reads "N selected".- Edit gradients on the canvas, as in Figma: while a fill or stroke gradient's picker is open, the layer shows the gradient's line or ellipse with its end dots and stop squares. Dragging a dot moves it, <kbd>Shift</kbd> turns it in 15° steps, and dragging a square slides its stop; the stop selected on the canvas is the one selected in the picker.- Paste SVG markup copied as text, such as from a code editor or Figma's Copy as SVG, as layers.- Show the pixel grid when zoomed in, as in Figma: from 800% on a standard display and 400% on a Retina one, toggled with **View → Pixel Grid** or <kbd>⇧</kbd><kbd>'</kbd>. <kbd>⇧</kbd><kbd>⌘</kbd><kbd>'</kbd> toggles **Snap to Pixel Grid**. The zoom menu in the properties panel lists both, with Figma's shortcuts, and labels its shortcuts for zoom to fit (<kbd>⇧</kbd><kbd>1</kbd>) and 100% (<kbd>⌘</kbd><kbd>0</kbd>); <kbd>⇧</kbd><kbd>R</kbd> toggles rulers and <kbd>⌥</kbd><kbd>⌘</kbd><kbd>\\</kbd> multiplayer cursors.@@ -149,6 +151,7 @@### Fixed+- Changing stroke position, per-side stroke weights, or an effect with several layers selected changes all of them, not only the first.- Draw layer blur, drop and inner shadows, and background blur with Figma's falloff. They spread about 15% too far, with a long faint edge Figma does not draw; SVG export keeps Figma's own `stdDeviation` of half the radius.- Load the fonts of SVG text before placing it from `import_svg`, so centred and right-aligned text sits where Figma puts it; `figma.loadFontAsync` in scripts now loads the font instead of doing nothing.- Gradient stops in the fill picker show their full position and opacity, such as 100%, instead of cutting them off; each stop's colour, hex, and opacity share one field as in the properties panel.diff --git a/packages/core/src/editor/alignment.ts b/packages/core/src/editor/alignment.tsindex 800e145cd..8fa348260 100644--- a/packages/core/src/editor/alignment.ts+++ b/packages/core/src/editor/alignment.ts@@ -120,7 +120,99 @@ function distributeMultipleNodes(}}+type Axis = 'horizontal' | 'vertical'++/** The layers as one row or column, or null when they are not, as Figma's Spacing field reads them. */+export interface SelectionSpacing {+ axis: Axis+ /** The gaps between neighbours, in order along the axis. */+ gaps: number[]+}++function axisSpans(ctx: EditorContext, nodes: SceneNode[], axis: Axis) {+ const start = axis === 'horizontal' ? 'boundX' : 'boundY'+ const crossStart = axis === 'horizontal' ? 'boundY' : 'boundX'+ const size = axis === 'horizontal' ? 'width' : 'height'+ const crossSize = axis === 'horizontal' ? 'height' : 'width'+ return nodes+ .map((node) => {+ const bounds = getAbsolutePositionFull(node, ctx.graph)+ return {+ node,+ min: bounds[start],+ max: bounds[start] + bounds[size],+ crossMin: bounds[crossStart],+ crossMax: bounds[crossStart] + bounds[crossSize]+ }+ })+ .sort((a, b) => a.min - b.min || a.node.id.localeCompare(b.node.id))+}++/**+ * Layers form a row when none overlap along it and each overlaps its neighbour across it; layers+ * apart on both axes, like a grid or a diagonal, have no spacing in Figma.+ */+function rowAlong(ctx: EditorContext, nodes: SceneNode[], axis: Axis) {+ const spans = axisSpans(ctx, nodes, axis)+ for (let index = 1; index < spans.length; index++) {+ const previous = spans[index - 1]+ const current = spans[index]+ if (current.min < previous.max) return null+ if (current.crossMin > previous.crossMax || current.crossMax < previous.crossMin) return null+ }+ return spans+}+export function createAlignmentActions(ctx: EditorContext) {+ function positionableNodes(nodeIds: readonly string[]) {+ const nodes = nodeIds+ .map((id) => ctx.graph.getNode(id))+ .filter((node): node is SceneNode => node != null)+ return nodes.length >= 2 && nodes.every((node) => canPositionNode(ctx, node)) ? nodes : null+ }++ function selectionSpacing(nodeIds: readonly string[]): SelectionSpacing | null {+ const nodes = positionableNodes(nodeIds)+ if (!nodes) return null+ for (const axis of ['horizontal', 'vertical'] as const) {+ const spans = rowAlong(ctx, nodes, axis)+ if (spans)+ return { axis, gaps: spans.slice(1).map((span, index) => span.min - spans[index].max) }+ }+ return null+ }++ /** Spaces the row or column evenly by `gap`, keeping its first layer in place, as Figma does. */+ function setSelectionSpacing(nodeIds: readonly string[], gap: number) {+ const spacing = selectionSpacing(nodeIds)+ const nodes = positionableNodes(nodeIds)+ if (!spacing || !nodes) return+ const spans = rowAlong(ctx, nodes, spacing.axis)+ if (!spans) return+ const originals = collectNodePositions(+ ctx,+ nodes.map((node) => node.id)+ )+ let cursor = spans[0].max + gap+ for (const span of spans.slice(1)) {+ const distance = cursor - span.min+ const delta = parentLocalDelta(+ ctx,+ span.node,+ spacing.axis === 'horizontal' ? { x: distance, y: 0 } : { x: 0, y: distance }+ )+ if (delta)+ ctx.graph.updateNode(span.node.id, {+ x: span.node.x + delta.x,+ y: span.node.y + delta.y+ })+ cursor += span.max - span.min + gap+ }+ pushPositionUndo(ctx, 'Change spacing', originals, collectNodePositions(ctx, originals.keys()))+ for (const node of nodes) ctx.runLayoutForNode(node.id)+ ctx.requestRender()+ }+function canDistributeNodes(nodeIds: string[]): boolean {const nodes = nodeIds.map((id) => ctx.graph.getNode(id))@@ -178,5 +270,13 @@ export function createAlignmentActions(ctx: EditorContext) {const { flipNodes, rotateNodes } = createFlipRotateActions(ctx)- return { alignNodes, canDistributeNodes, distributeNodes, flipNodes, rotateNodes }+ return {+ alignNodes,+ canDistributeNodes,+ distributeNodes,+ selectionSpacing,+ setSelectionSpacing,+ flipNodes,+ rotateNodes+ }}diff --git a/packages/core/src/editor/index.ts b/packages/core/src/editor/index.tsindex ec4a3475a..5244822c1 100644--- a/packages/core/src/editor/index.ts+++ b/packages/core/src/editor/index.ts@@ -8,6 +8,13 @@ export { DEFAULT_SNAPPING_PREFERENCES } from './preferences'export type { SnappingPreferences } from './preferences'export { createDefaultEditorSharedState } from './state/shared'export { editedGradient, editedGradientLayout } from './gradient-edit'+export type { SelectionSpacing } from './alignment'+export {+ replaceSelectionColor,+ selectionColors,+ selectionColorsShown,+ type SelectionColor+} from './selection/colors'export {copyEditorViewState,createDefaultEditorViewState,diff --git a/packages/core/src/editor/selection/colors.ts b/packages/core/src/editor/selection/colors.tsnew file mode 100644index 000000000..b366fe9bd--- /dev/null+++ b/packages/core/src/editor/selection/colors.ts@@ -0,0 +1,119 @@+import type { Color, Fill, SceneGraph, SceneNode } from '@open-pencil/scene-graph'++/**+ * Figma's Selection colors: every solid fill and stroke colour of the selected layers and their+ * descendants, most used first. Effect colours and colours bound to a variable are left out.+ */++export interface SelectionColor {+ /** The colour without alpha; its alpha is in `opacity`. */+ color: Color+ /** The paint's opacity, multiplied by the colour's own alpha. */+ opacity: number+ /** How many paints use it. */+ count: number+}++type PaintKind = 'fills' | 'strokes'+const PAINT_KINDS: readonly PaintKind[] = ['fills', 'strokes']++function paintOpacity(paint: Fill) {+ return paint.opacity * paint.color.a+}++// Integer channels instead of a formatted hex: this runs for every paint in a selection that can+// hold thousands of layers, on each change while the panel is open.+function colorKey(color: Color, opacity: number) {+ const channel = (value: number) => Math.round(value * 255)+ return (+ ((channel(color.r) << 16) | (channel(color.g) << 8) | channel(color.b)) * 101 ++ Math.round(opacity * 100)+ )+}++function listed(node: SceneNode, kind: PaintKind, index: number, paint: Fill) {+ return paint.type === 'SOLID' && paint.visible && !node.boundVariables[`${kind}/${index}/color`]+}++function eachNode(graph: SceneGraph, ids: readonly string[], visit: (node: SceneNode) => void) {+ const seen = new Set<string>()+ const walk = (id: string) => {+ if (seen.has(id)) return+ seen.add(id)+ const node = graph.getNode(id)+ if (!node) return+ visit(node)+ for (const childId of node.childIds) walk(childId)+ }+ for (const id of ids) walk(id)+}++export function selectionColors(graph: SceneGraph, ids: readonly string[]): SelectionColor[] {+ const colors = new Map<number, SelectionColor>()+ eachNode(graph, ids, (node) => {+ for (const kind of PAINT_KINDS) {+ node[kind].forEach((paint, index) => {+ if (!listed(node, kind, index, paint)) return+ const opacity = paintOpacity(paint)+ const key = colorKey(paint.color, opacity)+ const existing = colors.get(key)+ if (existing) existing.count+++ else colors.set(key, { color: { ...paint.color, a: 1 }, opacity, count: 1 })+ })+ }+ })+ // Most used first; ties in hex order, as Figma lists them.+ return [...colors.entries()]+ .sort(([keyA, a], [keyB, b]) => b.count - a.count || keyA - keyB)+ .map(([, color]) => color)+}++/**+ * The paint changes that turn one selection colour into another on every layer that uses it.+ * Each change replaces that layer's whole `fills` or `strokes` list.+ */+export function replaceSelectionColor(+ graph: SceneGraph,+ ids: readonly string[],+ from: Pick<SelectionColor, 'color' | 'opacity'>,+ to: Pick<SelectionColor, 'color' | 'opacity'>+): Array<{ id: string; changes: Partial<SceneNode> }> {+ const key = colorKey(from.color, from.opacity)+ const updates: Array<{ id: string; changes: Partial<SceneNode> }> = []+ eachNode(graph, ids, (node) => {+ const recolor = <T extends Fill>(kind: PaintKind, paints: readonly T[]): T[] | undefined => {+ const next = paints.map((paint, index) =>+ listed(node, kind, index, paint) && colorKey(paint.color, paintOpacity(paint)) === key+ ? { ...paint, color: { ...to.color, a: 1 }, opacity: to.opacity }+ : paint+ )+ return next.some((paint, index) => paint !== paints[index]) ? next : undefined+ }+ const changes: Partial<Pick<SceneNode, PaintKind>> = {}+ const fills = recolor('fills', node.fills)+ const strokes = recolor('strokes', node.strokes)+ if (fills) changes.fills = fills+ if (strokes) changes.strokes = strokes+ if (changes.fills || changes.strokes) updates.push({ id: node.id, changes })+ })+ return updates+}++/** Whether the Fill and Stroke sections already show every colour, so Figma hides the list. */+export function selectionColorsShown(graph: SceneGraph, ids: readonly string[]): boolean {+ const nodes = ids.map((id) => graph.getNode(id)).filter((node) => node !== undefined)+ if (nodes.some((node) => node.childIds.length > 0)) return true+ if (nodes.length < 2) return false+ const signature = (paints: readonly Fill[]) =>+ paints+ .map((paint) =>+ paint.type === 'SOLID' ? colorKey(paint.color, paintOpacity(paint)) : paint.type+ )+ .join('|')+ const fills = new Set(nodes.map((node) => signature(node.fills)))+ // Layers without strokes don't make strokes differ, as in the Stroke section.+ const strokes = new Set(+ nodes.filter((node) => node.strokes.length > 0).map((node) => signature(node.strokes))+ )+ return fills.size > 1 || strokes.size > 1+}diff --git a/packages/core/tests/editor/selection/colors.test.ts b/packages/core/tests/editor/selection/colors.test.tsnew file mode 100644index 000000000..15e14faf0--- /dev/null+++ b/packages/core/tests/editor/selection/colors.test.ts@@ -0,0 +1,95 @@+import { describe, expect, test } from 'bun:test'++import {+ createEditor,+ replaceSelectionColor,+ selectionColors,+ selectionColorsShown+} from '@open-pencil/core/editor'+import type { Color, Fill } from '@open-pencil/scene-graph'++const RED = { r: 1, g: 0.3, b: 0.2, a: 1 }+const BLUE = { r: 0.2, g: 0.4, b: 1, a: 1 }+const BLACK = { r: 0, g: 0, b: 0, a: 1 }+const GREY = { r: 0.85, g: 0.85, b: 0.85, a: 1 }++function solid(color: Color, opacity = 1): Fill {+ return { type: 'SOLID', color, opacity, visible: true }+}++// The layers Figma desktop 126 was probed with.+function setup() {+ const editor = createEditor()+ const { graph } = editor+ const pageId = graph.getPages()[0].id+ const frame = graph.createNode('FRAME', pageId, { fills: [solid(BLUE)] })+ graph.createNode('RECTANGLE', frame.id, { fills: [solid(GREY)] })+ const rectA = graph.createNode('RECTANGLE', pageId, {+ fills: [solid(RED)],+ strokes: [{ ...solid(BLACK), weight: 2, align: 'INSIDE' }]+ })+ const rectB = graph.createNode('RECTANGLE', pageId, {+ fills: [solid(RED)],+ effects: [+ {+ type: 'DROP_SHADOW',+ color: { r: 0, g: 0, b: 0, a: 0.25 },+ offset: { x: 0, y: 4 },+ radius: 8,+ spread: 0,+ visible: true+ }+ ]+ })+ const ellipse = graph.createNode('ELLIPSE', pageId, { fills: [solid(BLUE)] })+ const text = graph.createNode('TEXT', pageId, { fills: [solid(BLACK)] })+ return { graph, frame: frame.id, rectA: rectA.id, rectB: rectB.id, ellipse: ellipse.id, text: text.id }+}++const hex = (color: Color) =>+ [color.r, color.g, color.b]+ .map((channel) => Math.round(channel * 255).toString(16).padStart(2, '0'))+ .join('')+ .toUpperCase()++describe('selection colors', () => {+ // Figma desktop 126 lists text + rect A as 000000 then FF4D33: black fills the text and strokes+ // the rectangle, so it is used twice.+ test('lists fills and strokes, most used first', () => {+ const { graph, text, rectA } = setup()+ expect(selectionColors(graph, [text, rectA]).map((entry) => [hex(entry.color), entry.count])).toEqual([+ ['000000', 2],+ ['FF4D33', 1]+ ])+ })++ test('takes descendants and leaves out effect colours', () => {+ const { graph, frame, rectB } = setup()+ expect(selectionColors(graph, [frame, rectB]).map((entry) => hex(entry.color))).toEqual([+ '3366FF',+ 'D9D9D9',+ 'FF4D33'+ ])+ })++ test('replaces a colour on every layer that uses it, in one change per layer', () => {+ const { graph, frame, ellipse } = setup()+ const updates = replaceSelectionColor(+ graph,+ [frame, ellipse],+ { color: BLUE, opacity: 1 },+ { color: { r: 0, g: 1, b: 0, a: 1 }, opacity: 0.5 }+ )+ expect(updates.map((update) => update.id)).toEqual([frame, ellipse])+ expect(updates[0]?.changes.fills?.[0]).toMatchObject({ color: { r: 0, g: 1, b: 0 }, opacity: 0.5 })+ })++ // Figma desktop 126 hides the list when the Fill and Stroke sections already show every colour.+ test('shows when fills differ or a layer has children', () => {+ const { graph, frame, rectA, rectB, ellipse } = setup()+ expect(selectionColorsShown(graph, [rectA])).toBe(false)+ expect(selectionColorsShown(graph, [rectA, rectB])).toBe(false)+ expect(selectionColorsShown(graph, [rectA, ellipse])).toBe(true)+ expect(selectionColorsShown(graph, [frame])).toBe(true)+ })+})diff --git a/packages/core/tests/editor/selection/distribution.test.ts b/packages/core/tests/editor/selection/distribution.test.tsindex 0e4de3e04..52091ba6b 100644--- a/packages/core/tests/editor/selection/distribution.test.ts+++ b/packages/core/tests/editor/selection/distribution.test.ts@@ -115,3 +115,45 @@ describe('distribute nodes', () => {expect(positions(editor, ids, 'x')).toEqual([0, 60, 130])})})++// Figma desktop 126: Spacing reads the gaps of a row or column and typing a value spaces it from+// its first layer; layers apart on both axes have no spacing.+describe('selection spacing', () => {+ function row() {+ const editor = createEditor()+ const pageId = editor.state.currentPageId+ const a = editor.graph.createNode('RECTANGLE', pageId, { x: 0, y: 180, width: 100, height: 80 })+ const b = editor.graph.createNode('RECTANGLE', pageId, { x: 140, y: 180, width: 120, height: 80 })+ const c = editor.graph.createNode('ELLIPSE', pageId, { x: 320, y: 180, width: 80, height: 80 })+ return { editor, ids: [c.id, a.id, b.id], a, b, c }+ }++ test('reads the gaps along a row in order', () => {+ const { editor, ids } = row()+ expect(editor.selectionSpacing(ids)).toEqual({ axis: 'horizontal', gaps: [40, 60] })+ })++ test('spaces the row from its first layer', () => {+ const { editor, ids, a, b, c } = row()+ editor.setSelectionSpacing(ids, 10)+ expect(positions(editor, [a.id, b.id, c.id], 'x')).toEqual([0, 110, 240])+ editor.undo.undo()+ expect(positions(editor, [a.id, b.id, c.id], 'x')).toEqual([0, 140, 320])+ })++ test('reads a column when the layers overlap across it', () => {+ const editor = createEditor()+ const pageId = editor.state.currentPageId+ const rect = editor.graph.createNode('RECTANGLE', pageId, { x: 0, y: 180, width: 100, height: 80 })+ const text = editor.graph.createNode('TEXT', pageId, { x: 0, y: 300, width: 39, height: 19 })+ expect(editor.selectionSpacing([text.id, rect.id])).toEqual({ axis: 'vertical', gaps: [40] })+ })++ test('has no spacing for layers apart on both axes', () => {+ const editor = createEditor()+ const pageId = editor.state.currentPageId+ const rect = editor.graph.createNode('RECTANGLE', pageId, { x: 110, y: 180, width: 120, height: 80 })+ const text = editor.graph.createNode('TEXT', pageId, { x: 0, y: 300, width: 39, height: 19 })+ expect(editor.selectionSpacing([text.id, rect.id])).toBeNull()+ })+})diff --git a/packages/docs/.vitepress/sdk-sidebar.ts b/packages/docs/.vitepress/sdk-sidebar.tsindex 4452050b9..15ae50e15 100644--- a/packages/docs/.vitepress/sdk-sidebar.ts+++ b/packages/docs/.vitepress/sdk-sidebar.ts@@ -53,6 +53,8 @@ const SDK_COMPOSABLE_PAGES = [{ text: 'useFillControls', slug: 'use-fill-controls' },{ text: 'useStrokeControls', slug: 'use-stroke-controls' },{ text: 'useEffectsControls', slug: 'use-effects-controls' },+ { text: 'useSelectionLayout', slug: 'use-selection-layout', canonical: true },+ { text: 'useSelectionColors', slug: 'use-selection-colors', canonical: true },{ text: 'useMask', slug: 'use-mask', canonical: true },{ text: 'useDocumentWorkspace', slug: 'use-document-workspace', canonical: true },{ text: 'usePageList', slug: 'use-page-list' },diff --git a/packages/docs/de/programmable/sdk/api/composables/use-stroke-controls.md b/packages/docs/de/programmable/sdk/api/composables/use-stroke-controls.mdindex a17c5f67b..6fe6dbba1 100644--- a/packages/docs/de/programmable/sdk/api/composables/use-stroke-controls.md+++ b/packages/docs/de/programmable/sdk/api/composables/use-stroke-controls.md@@ -9,8 +9,8 @@ description: Ausrichtung, Seiten und Stärke von Konturen im Eigenschaften-Panel```tsconst { alignOptions, sideOptions, currentAlign, currentSides, selectSide } = useStrokeControls()-strokes.updateAlign('INSIDE', activeNode)-strokes.selectSide('TOP', activeNode)+strokes.updateAlign('INSIDE')+strokes.selectSide('TOP')```## Siehe auchdiff --git a/packages/docs/pl/programmable/sdk/api/composables/use-stroke-controls.md b/packages/docs/pl/programmable/sdk/api/composables/use-stroke-controls.mdindex eb86651b4..d1be68765 100644--- a/packages/docs/pl/programmable/sdk/api/composables/use-stroke-controls.md+++ b/packages/docs/pl/programmable/sdk/api/composables/use-stroke-controls.md@@ -10,8 +10,8 @@ description: Zarządzanie wyrównaniem, bokami i grubością obwiedni w panelu w```tsconst { alignOptions, sideOptions, currentAlign, currentSides, selectSide } = useStrokeControls()-strokes.updateAlign('INSIDE', activeNode)-strokes.selectSide('TOP', activeNode)+strokes.updateAlign('INSIDE')+strokes.selectSide('TOP')```## Zobacz teżdiff --git a/packages/docs/programmable/sdk/api/composables/index.md b/packages/docs/programmable/sdk/api/composables/index.mdindex 9c169fec9..1b2ebdfa5 100644--- a/packages/docs/programmable/sdk/api/composables/index.md+++ b/packages/docs/programmable/sdk/api/composables/index.md@@ -37,6 +37,8 @@ These are the main composables most `@open-pencil/vue` consumers will use.- [useFillControls](./use-fill-controls)- [useStrokeControls](./use-stroke-controls)- [useEffectsControls](./use-effects-controls)+- [useSelectionLayout](./use-selection-layout)+- [useSelectionColors](./use-selection-colors)## Document workspacesdiff --git a/packages/docs/programmable/sdk/api/composables/use-selection-colors.md b/packages/docs/programmable/sdk/api/composables/use-selection-colors.mdnew file mode 100644index 000000000..69cf99e20--- /dev/null+++ b/packages/docs/programmable/sdk/api/composables/use-selection-colors.md@@ -0,0 +1,31 @@+---+title: useSelectionColors+description: Figma's Selection colors list for the current selection, with an edit that recolours every paint using a colour.+---++# useSelectionColors++`useSelectionColors()` lists each solid fill and stroke colour of the selected layers and their+descendants, most used first. Effect colours and colours bound to a variable are left out. `shown`+is true when Figma shows the list: the Fill and Stroke sections can't already show every colour,+because they differ across the selection or a selected layer has children.++## Usage++```ts+import { useSelectionColors } from '@open-pencil/vue'++const selection = useSelectionColors()++// Recolour every paint that uses the first colour.+selection.replace(0, { color: { r: 0, g: 0.5, b: 1, a: 1 }, opacity: 1 })+```++Edits made in quick succession, such as dragging in a colour picker, become one undo step. Call+`begin()` when a row's picker opens and `finish()` when it closes to keep the list's order steady+while the colour changes.++## Related APIs++- [useSelectionLayout](./use-selection-layout)+- [useFillControls](./use-fill-controls)diff --git a/packages/docs/programmable/sdk/api/composables/use-selection-layout.md b/packages/docs/programmable/sdk/api/composables/use-selection-layout.mdnew file mode 100644index 000000000..a7d944288--- /dev/null+++ b/packages/docs/programmable/sdk/api/composables/use-selection-layout.md@@ -0,0 +1,37 @@+---+title: useSelectionLayout+description: Layout of a multi-selection as Figma shows it, with text resizing, flow, clip content, and spacing.+---++# useSelectionLayout++`useSelectionLayout()` reads and edits the layout of the selected layers the way Figma's panel does+for several layers. Each value is the one the relevant layers share, `MIXED` when they differ, or+`undefined` when no selected layer has it:++- `textResize` — resizing of the selected text layers+- `layoutMode` — flow, when every selected layer can hold an auto layout+- `clipsContent` — clip content of the layers that can clip+- `spacing` and `spacingAxis` — the gap between neighbours when the layers form one row or column++Each action changes only the layers it applies to, in one undo step.++## Usage++```ts+import { useSelectionLayout } from '@open-pencil/vue'++const layout = useSelectionLayout()++layout.setTextResize('AUTO_HEIGHT')+layout.setLayoutMode('VERTICAL')+layout.toggleClipsContent()+layout.setSpacing(16)+```++`setSpacing` keeps the first layer of the row in place and spaces the rest after it.++## Related APIs++- [useLayout](./use-layout)+- [useSelectionColors](./use-selection-colors)diff --git a/packages/docs/programmable/sdk/api/composables/use-stroke-controls.md b/packages/docs/programmable/sdk/api/composables/use-stroke-controls.mdindex 770eb4af0..bb70a3722 100644--- a/packages/docs/programmable/sdk/api/composables/use-stroke-controls.md+++ b/packages/docs/programmable/sdk/api/composables/use-stroke-controls.md@@ -36,13 +36,13 @@ const { alignOptions, sideOptions, currentAlign, currentSides, selectSide } = us### Set stroke alignment```ts-strokes.updateAlign('INSIDE', activeNode)+strokes.updateAlign('INSIDE')```### Limit a stroke to one side```ts-strokes.selectSide('TOP', activeNode)+strokes.selectSide('TOP')```### Edit stroke geometry@@ -58,6 +58,10 @@ strokes.commitMiterLimit(8)`advancedActive` is true only when every selected node has at least one stroke. `cap`, `join`, and`miterLimit` return the shared value or `MIXED` for a mixed selection.+Alignment, sides, and border weights act on every selected node in one undo step. `currentAlign()`+and `borderWeight(side)` return the shared value or `MIXED`; a node without strokes counts with the+alignment it keeps for new strokes.+## Related APIs- [PropertyListRoot](../components/property-list-root)diff --git a/packages/docs/programmable/sdk/api/composables/use-typography.md b/packages/docs/programmable/sdk/api/composables/use-typography.mdindex 27604c0e0..fd599e007 100644--- a/packages/docs/programmable/sdk/api/composables/use-typography.md+++ b/packages/docs/programmable/sdk/api/composables/use-typography.md@@ -5,7 +5,9 @@ description: Read and update font, alignment, case, truncation, and OpenType fea# useTypography-`useTypography()` is the text-property control composable for text editing panels.+`useTypography()` is the text-property control composable for text editing panels. It works on the+text layers in the selection: `nodes` holds them, `node` is the first, and every action changes all+of them in one undo step, so a selection of text and other layers edits only the text.It exposes:@@ -19,6 +21,7 @@ It exposes:- ending truncation and maximum lines- OpenType feature toggles- helpers for changing family, weight, alignment, and decorations+- `merged(key)` and `fontFeature(tag)`, which return the shared value or `MIXED`## Usagediff --git a/packages/docs/ru/programmable/sdk/api/composables/use-stroke-controls.md b/packages/docs/ru/programmable/sdk/api/composables/use-stroke-controls.mdindex 66466e4b0..2339df74e 100644--- a/packages/docs/ru/programmable/sdk/api/composables/use-stroke-controls.md+++ b/packages/docs/ru/programmable/sdk/api/composables/use-stroke-controls.md@@ -31,13 +31,13 @@ const { alignOptions, sideOptions, currentAlign, currentSides, selectSide } = us### Разместить обводку внутри границы объекта```ts-strokes.updateAlign('INSIDE', activeNode)+strokes.updateAlign('INSIDE')```### Ограничить обводку одной стороной```ts-strokes.selectSide('TOP', activeNode)+strokes.selectSide('TOP')```## Связанные APIdiff --git a/packages/docs/user-guide/selection-and-manipulation.md b/packages/docs/user-guide/selection-and-manipulation.mdindex ae012dba3..a2e650bb1 100644--- a/packages/docs/user-guide/selection-and-manipulation.md+++ b/packages/docs/user-guide/selection-and-manipulation.md@@ -77,6 +77,15 @@ Change the stacking order of nodes within their parent:Move selected nodes to a different page via the [context menu](./context-menu). The nodes are reparented under the target page's canvas.+## Editing several layers++With several layers selected, the properties panel shows what they have in common and reads **Mixed** where they differ; an edit changes all of them in one undo step.++- **Layout** shows their sizes, text resizing when text is selected, flow when every layer is a frame, and clip content for the frames among them. When the layers form one row or column, **Spacing** shows the gap between them; typing a value spaces them evenly from the first layer.+- **Typography** appears whenever text is selected and changes only the text.+- **Stroke** shows the stroke of the layers that have one; editing it strokes every selected layer.+- **Selection colors** lists every fill and stroke colour in the selection, including inside frames and groups, most used first. Changing one recolours it everywhere it is used.+## SectionsA section takes in the sibling nodes it fully covers when you draw it, move it, or resize it over them.diff --git a/packages/vue/src/controls/appearance/helpers.ts b/packages/vue/src/controls/appearance/helpers.tsindex 4695de183..2daab6cbd 100644--- a/packages/vue/src/controls/appearance/helpers.ts+++ b/packages/vue/src/controls/appearance/helpers.ts@@ -34,6 +34,17 @@ type AppearanceActionOptions = AppearanceStateOptions & {editor: Editor}+function supportsCornerRadius(node: SceneNode) {+ return CORNER_RADIUS_TYPES.has(node.type)+}++/** The value shared by every node, MIXED when they differ, or `empty` when there are none. */+function sharedValue<T>(values: readonly T[], empty: T): MixedValue<T> {+ if (values.length === 0) return empty+ const [first] = values+ return values.every((value) => value === first) ? first : MIXED+}+function cornersHaveEquivalentBindings(node: SceneNode): boolean {const first = node.boundVariables.topLeftRadiusif (!first) return false@@ -59,13 +70,21 @@ export function createAppearanceState({merged,expandedCornerNodeId}: AppearanceStateOptions) {+ // Figma shows the radius for any multi-selection and edits only the layers that have one; with+ // none among them the field is disabled.+ const cornerNodes = computed(() => nodes.value.filter(supportsCornerRadius))const hasCornerRadius = computed(() => {- if (isMulti.value) return nodes.value.every((n) => CORNER_RADIUS_TYPES.has(n.type))- return node.value ? CORNER_RADIUS_TYPES.has(node.value.type) : false+ if (isMulti.value) return true+ return node.value ? supportsCornerRadius(node.value) : false})+ const cornerRadiusDisabled = computed(() => isMulti.value && cornerNodes.value.length === 0)const independentCorners = computed(() => {- if (isMulti.value) return merged('independentCorners')+ if (isMulti.value)+ return sharedValue(+ cornerNodes.value.map((n) => n.independentCorners),+ false+ )return node.value?.independentCorners ?? false})@@ -80,7 +99,11 @@ export function createAppearanceState({})const cornerRadiusValue = computed(() => {- if (isMulti.value) return merged('cornerRadius')+ if (isMulti.value)+ return sharedValue(+ cornerNodes.value.map((n) => n.cornerRadius),+ 0+ )const selected = node.valuereturn selected && cornersHaveEquivalentBindings(selected) && !hasUnequalCorners(selected)? selected.topLeftRadius@@ -95,7 +118,12 @@ export function createAppearanceState({})const cornerSmoothingPercent = computed(() => {- const value = merged('cornerSmoothing')+ const value = isMulti.value+ ? sharedValue(+ cornerNodes.value.map((n) => n.cornerSmoothing),+ 0+ )+ : merged('cornerSmoothing')return value === MIXED ? MIXED : Math.round(Math.max(0, Math.min(value, 1)) * 100)})@@ -117,6 +145,7 @@ export function createAppearanceState({return {hasCornerRadius,+ cornerRadiusDisabled,independentCorners,showIndependentCorners,cornerRadiusValue,@@ -185,8 +214,7 @@ export function createAppearanceActions({expandedCornerNodeId.value = expandedCornerNodeId.value === selected.id ? null : selected.idreturn}- const targets = isMulti.value ? [...nodes.value] : []- if (!isMulti.value && selected) targets.push(selected)+ const targets = cornerTargets()if (targets.length === 0) returnconst makeIndependent = !targets.every((target) => target.independentCorners || hasUnequalCorners(target)@@ -230,7 +258,7 @@ export function createAppearanceActions({}function cornerTargets() {- if (isMulti.value) return nodes.value+ if (isMulti.value) return nodes.value.filter(supportsCornerRadius)const selected = node.valuereturn selected ? [selected] : []}diff --git a/packages/vue/src/controls/effects/helpers.ts b/packages/vue/src/controls/effects/helpers.tsindex 76e354235..6d151b955 100644--- a/packages/vue/src/controls/effects/helpers.ts+++ b/packages/vue/src/controls/effects/helpers.ts@@ -1,7 +1,7 @@import type { Ref } from 'vue'import type { Editor } from '@open-pencil/core/editor'-import type { Effect, SceneNode } from '@open-pencil/scene-graph'+import { copyEffects, type Effect, type SceneNode } from '@open-pencil/scene-graph'import type { Color } from '@open-pencil/scene-graph/primitives'import { useI18n } from '#vue/i18n/useI18n.js'@@ -44,43 +44,50 @@ export interface EffectEditSnapshot {effectStyleId: string | null}+/** Effects scrubbed on every selected node, each committed from its own value before the scrub. */export function createEffectEditActions(editor: Editor,- effectsBeforeScrub: Ref<EffectEditSnapshot | null>+ effectsBeforeScrub: Ref<Map<string, EffectEditSnapshot> | null>) {- function scrubEffect(node: SceneNode | null, index: number, changes: Partial<Effect>) {- if (!node) return- if (!effectsBeforeScrub.value) {- effectsBeforeScrub.value = {- effects: node.effects.map((e) => ({- ...e,- color: { ...e.color },- offset: { ...e.offset }- })),- effectStyleId: node.effectStyleId- }+ function apply(nodes: readonly SceneNode[], index: number, changes: Partial<Effect>) {+ for (const node of nodes) {+ const effects = [...node.effects]+ const current = effects.at(index)+ if (!current) continue+ effects[index] = { ...current, ...changes }+ editor.updateNode(node.id, { effects })}- const effects = [...node.effects]- effects[index] = { ...effects[index], ...changes }- editor.updateNode(node.id, { effects })editor.requestRender()}- function commitEffect(node: SceneNode | null, index: number, changes: Partial<Effect>) {- if (!node) return+ function scrubEffect(nodes: readonly SceneNode[], index: number, changes: Partial<Effect>) {+ if (nodes.length === 0) return+ effectsBeforeScrub.value ??= new Map(+ nodes.map((node) => [+ node.id,+ { effects: copyEffects(node.effects), effectStyleId: node.effectStyleId }+ ])+ )+ apply(nodes, index, changes)+ }++ function commitEffect(nodes: readonly SceneNode[], index: number, changes: Partial<Effect>) {+ if (nodes.length === 0) returnconst previous = effectsBeforeScrub.valueeffectsBeforeScrub.value = null- const effects = [...node.effects]- effects[index] = { ...effects[index], ...changes }- editor.updateNode(node.id, { effects })- editor.requestRender()- if (previous) {- editor.commitNodeUpdate(- node.id,- { effects: previous.effects, effectStyleId: previous.effectStyleId },- 'Change effect'- )- }+ apply(nodes, index, changes)+ if (!previous) return+ editor.undo.runBatch('Change effect', () => {+ for (const node of nodes) {+ const before = previous.get(node.id)+ if (!before) continue+ editor.commitNodeUpdate(+ node.id,+ { effects: before.effects, effectStyleId: before.effectStyleId },+ 'Change effect'+ )+ }+ })}return { scrubEffect, commitEffect }diff --git a/packages/vue/src/controls/effects/use.ts b/packages/vue/src/controls/effects/use.tsindex 159852f47..f7c1e6833 100644--- a/packages/vue/src/controls/effects/use.ts+++ b/packages/vue/src/controls/effects/use.ts@@ -1,5 +1,7 @@import { ref, shallowRef } from 'vue'+import type { Effect } from '@open-pencil/scene-graph'+import {EFFECT_OPTIONS,createDefaultEffect,@@ -8,6 +10,7 @@ import {isShadow,type EffectEditSnapshot} from '#vue/controls/effects/helpers'+import { useNodeProps } from '#vue/controls/node-props/use'import { useEditor } from '#vue/editor/context'/**@@ -20,7 +23,8 @@ export function useEffectsControls() {const editor = useEditor()const expandedIndex = ref<number | null>(null)- const effectsBeforeScrub = shallowRef<EffectEditSnapshot | null>(null)+ const { nodes } = useNodeProps()+ const effectsBeforeScrub = shallowRef<Map<string, EffectEditSnapshot> | null>(null)const editActions = createEffectEditActions(editor, effectsBeforeScrub)const controlActions = createEffectControlActions(expandedIndex)@@ -29,7 +33,12 @@ export function useEffectsControls() {effectOptions: EFFECT_OPTIONS,createDefaultEffect,isShadow,- ...editActions,+ /** Previews a change to one effect on every selected layer. */+ scrubEffect: (index: number, changes: Partial<Effect>) =>+ editActions.scrubEffect(nodes.value, index, changes),+ /** Applies a change to one effect on every selected layer in one undo step. */+ commitEffect: (index: number, changes: Partial<Effect>) =>+ editActions.commitEffect(nodes.value, index, changes),...controlActions}}diff --git a/packages/vue/src/controls/property-list/use.ts b/packages/vue/src/controls/property-list/use.tsindex 46352da38..7c28e4f40 100644--- a/packages/vue/src/controls/property-list/use.ts+++ b/packages/vue/src/controls/property-list/use.ts@@ -2,6 +2,7 @@ import { computed } from 'vue'import type { SceneNode } from '@open-pencil/scene-graph'+import { isNodeArrayMixed } from '#vue/controls/node-props/helpers'import { useNodeProps } from '#vue/controls/node-props/use'import { useUndoBatch } from '#vue/controls/undo-batch/use'import { useEditor } from '#vue/editor/context'@@ -23,15 +24,23 @@ function moveItem<T>(items: T[], fromIndex: number, toIndex: number): T[] {export function useEditorPropertyList<K extends PropertyListKey>(propKey: K) {const editor = useEditor()- const { isArrayMixed, nodes: selectedNodes, activeNode } = useNodeProps()+ const { nodes: selectedNodes, activeNode } = useNodeProps()const batch = useUndoBatch(editor.undo, editor.beginInteractiveEdit)const selectedNodeIds = computed(() => selectedNodes.value.map((node) => node.id))const isMulti = computed(() => selectedNodes.value.length > 1)const active = computed(() => selectedNodes.value.length > 0)- const isMixed = computed(() => isArrayMixed(propKey))+ // Figma leaves layers without strokes out when it compares strokes, so a stroke on some of the+ // selection shows as theirs; fills and effects still differ when a layer has none.+ const shownNodes = computed(() => {+ if (propKey !== 'strokes') return selectedNodes.value+ const stroked = selectedNodes.value.filter((node) => node.strokes.length > 0)+ return stroked.length > 0 ? stroked : selectedNodes.value+ })+ const isMixed = computed(() => isNodeArrayMixed(shownNodes.value, propKey))const items = computed<PropertyListItemFor<K>[]>(() => {if (isMixed.value) return []- return (activeNode.value?.[propKey] ?? []) as PropertyListItemFor<K>[]+ const shown = shownNodes.value.at(0)+ return (shown?.[propKey] ?? []) as PropertyListItemFor<K>[]})function targetNodes(): SceneNode[] {@@ -39,8 +48,10 @@ export function useEditorPropertyList<K extends PropertyListKey>(propKey: K) {return activeNode.value ? [activeNode.value] : []}+ /** A layer without strokes takes the shown ones when they are edited, as in Figma. */function propArray(node: SceneNode): PropertyListItemFor<K>[] {- return node[propKey] as PropertyListItemFor<K>[]+ const own = node[propKey] as PropertyListItemFor<K>[]+ return own.length === 0 && !isMixed.value ? items.value : own}function updateArray(node: SceneNode, value: PropertyListItemFor<K>[], label: string) {diff --git a/packages/vue/src/controls/selection-colors/use.ts b/packages/vue/src/controls/selection-colors/use.tsnew file mode 100644index 000000000..f4ddb5d49--- /dev/null+++ b/packages/vue/src/controls/selection-colors/use.ts@@ -0,0 +1,59 @@+import { computed, shallowRef } from 'vue'++import {+ replaceSelectionColor,+ selectionColors,+ selectionColorsShown,+ type SelectionColor+} from '@open-pencil/core/editor'++import { useUndoBatch } from '#vue/controls/undo-batch/use'+import { useEditor } from '#vue/editor/context'+import { useSceneComputed } from '#vue/internal/scene-computed/use'++/**+ * Figma's Selection colors for the current selection: each colour its layers and their+ * descendants fill or stroke with, and an edit that recolours every paint using it. While a row's+ * picker is open the list keeps its order, so the row under the picker stays put.+ */+export function useSelectionColors() {+ const editor = useEditor()+ const batch = useUndoBatch(editor.undo, editor.beginInteractiveEdit)+ const ids = useSceneComputed(() => [...editor.state.selectedIds])+ // A move, resize, or rotation changes no colour, so the list is not walked again mid-drag.+ let last: SelectionColor[] = []+ const live = useSceneComputed(() => {+ if (!editor.state.transforming) last = selectionColors(editor.graph, ids.value)+ return last+ })+ const frozen = shallowRef<SelectionColor[] | null>(null)+ const colors = computed(() => frozen.value ?? live.value)+ const shown = useSceneComputed(+ () => live.value.length > 0 && selectionColorsShown(editor.graph, ids.value)+ )++ /** Recolours every paint using the colour in row `index`. */+ function replace(index: number, to: Pick<SelectionColor, 'color' | 'opacity'>) {+ const list = colors.value+ const from = list.at(index)+ if (!from) return+ batch.ensure(`selection-color:${index}`, 'Change selection color')+ for (const { id, changes } of replaceSelectionColor(editor.graph, ids.value, from, to))+ editor.updateNodeWithUndo(id, changes, 'Change selection color')+ if (frozen.value)+ frozen.value = list.map((entry, row) => (row === index ? { ...entry, ...to } : entry))+ }++ /** Starts editing a row in its picker: the list keeps its order until `finish`. */+ function begin() {+ frozen.value = [...live.value]+ }++ /** Ends an edit: commits it as one undo step and lets the list re-sort. */+ function finish() {+ batch.flush()+ frozen.value = null+ }++ return { colors, shown, replace, begin, finish }+}diff --git a/packages/vue/src/controls/selection-layout/use.ts b/packages/vue/src/controls/selection-layout/use.tsnew file mode 100644index 000000000..0182a396d--- /dev/null+++ b/packages/vue/src/controls/selection-layout/use.ts@@ -0,0 +1,123 @@+import { computed } from 'vue'++import type { LayoutMode, NodeType, SceneNode } from '@open-pencil/scene-graph'++import { MIXED, useNodeProps, type MixedValue } from '#vue/controls/node-props/use'+import { useUndoBatch } from '#vue/controls/undo-batch/use'+import { useEditor } from '#vue/editor/context'+import { useSceneComputed } from '#vue/internal/scene-computed/use'++/** Layers that can hold an auto layout and clip their content. */+export const LAYOUT_CONTAINER_TYPES: ReadonlySet<NodeType> = new Set<NodeType>([+ 'FRAME',+ 'COMPONENT',+ 'COMPONENT_SET',+ 'INSTANCE'+])++export type TextResizeMode = 'AUTO_WIDTH' | 'AUTO_HEIGHT' | 'FIXED'++const TEXT_AUTO_RESIZE: Record<TextResizeMode, SceneNode['textAutoResize']> = {+ AUTO_WIDTH: 'WIDTH_AND_HEIGHT',+ AUTO_HEIGHT: 'HEIGHT',+ FIXED: 'NONE'+}++export function textResizeMode(node: SceneNode): TextResizeMode {+ if (node.textAutoResize === 'WIDTH_AND_HEIGHT') return 'AUTO_WIDTH'+ if (node.textAutoResize === 'HEIGHT' || node.textAutoResize === 'TRUNCATE') return 'AUTO_HEIGHT'+ return 'FIXED'+}++function shared<T>(values: readonly T[]): MixedValue<T> | undefined {+ if (values.length === 0) return undefined+ const [first] = values+ return values.every((value) => value === first) ? first : MIXED+}++/**+ * Layout of a multi-selection, as Figma's panel shows it: text resizing for its text layers,+ * flow when every layer can hold an auto layout, clip content for those that can clip, and the+ * spacing of a row or column. Each edit changes the layers it applies to in one undo step.+ */+export function useSelectionLayout() {+ const editor = useEditor()+ const { nodes } = useNodeProps()+ const batch = useUndoBatch(editor.undo, editor.beginInteractiveEdit)++ const texts = computed(() => nodes.value.filter((node) => node.type === 'TEXT'))+ const containers = computed(() =>+ nodes.value.filter((node) => LAYOUT_CONTAINER_TYPES.has(node.type))+ )+ const allContainers = computed(+ () => nodes.value.length > 0 && containers.value.length === nodes.value.length+ )++ /** Undefined when no text is selected. */+ const textResize = computed(() => shared(texts.value.map(textResizeMode)))+ /** Undefined unless every selected layer can hold an auto layout. */+ const layoutMode = computed(() =>+ allContainers.value ? shared(containers.value.map((node) => node.layoutMode)) : undefined+ )+ const rowSpacing = useSceneComputed(() =>+ editor.selectionSpacing(nodes.value.map((node) => node.id))+ )+ /** The axis of a row or column, or undefined when the layers are not one. */+ const spacingAxis = computed(() => rowSpacing.value?.axis)+ /** The gap between neighbours, MIXED when they differ. */+ const spacing = computed<MixedValue<number>>(() => {+ const gaps = rowSpacing.value?.gaps.map((gap) => Math.round(gap * 100) / 100) ?? []+ return shared(gaps) ?? MIXED+ })++ /** Spaces the row evenly from its first layer; a scrub is one undo step. */+ function setSpacing(gap: number) {+ batch.ensure('selection-spacing', 'Change spacing')+ editor.setSelectionSpacing(+ nodes.value.map((node) => node.id),+ gap+ )+ }++ /** Undefined when nothing selected can clip. */+ const clipsContent = computed(() => shared(containers.value.map((node) => node.clipsContent)))++ function setTextResize(mode: TextResizeMode) {+ editor.undo.runBatch('Set text resizing', () => {+ for (const node of texts.value)+ editor.updateNodeWithUndo(node.id, { textAutoResize: TEXT_AUTO_RESIZE[mode] })+ })+ }++ function setLayoutMode(mode: LayoutMode) {+ editor.undo.runBatch('Set layout', () => {+ for (const node of containers.value) editor.setLayoutMode(node.id, mode)+ })+ }++ /** A mixed checkbox turns clipping on, as Figma's does. */+ function toggleClipsContent() {+ const clips = clipsContent.value !== true+ editor.undo.runBatch('Toggle clip content', () => {+ for (const node of containers.value)+ editor.updateNodeWithUndo(node.id, { clipsContent: clips })+ })+ }++ return {+ editor,+ nodes,+ texts,+ containers,+ textResize,+ layoutMode,+ clipsContent,+ spacingAxis,+ spacing,+ setSpacing,+ flushSpacing: batch.flush,+ setTextResize,+ setLayoutMode,+ toggleClipsContent+ }+}diff --git a/packages/vue/src/controls/stroke/helpers.ts b/packages/vue/src/controls/stroke/helpers.tsindex f42871c73..a353dd828 100644--- a/packages/vue/src/controls/stroke/helpers.ts+++ b/packages/vue/src/controls/stroke/helpers.ts@@ -134,15 +134,26 @@ export function createStrokeGeometryActions(return { setCap, setJoin, updateMiterLimit, commitMiterLimit }}-export function updateAlign(editor: Editor, align: Stroke['align'], activeNode: SceneNode | null) {- if (!activeNode) return- const strokes = activeNode.strokes.map((s) => ({ ...s, align }))- editor.updateNodeWithUndo(activeNode.id, { strokes }, 'Change stroke align')+function alignOf(node: SceneNode): Stroke['align'] {+ return node.strokes.at(0)?.align ?? node.strokeAlign}-export function currentAlign(activeNode: SceneNode | null): Stroke['align'] {- if (!activeNode || activeNode.strokes.length === 0) return 'CENTER'- return activeNode.strokes[0].align+/** Changes every node's stroke alignment, including the one a node without strokes keeps. */+export function updateAlign(editor: Editor, nodes: readonly SceneNode[], align: Stroke['align']) {+ editor.undo.runBatch('Change stroke align', () => {+ for (const node of nodes) {+ const strokes = node.strokes.map((stroke) => ({ ...stroke, align }))+ editor.updateNodeWithUndo(node.id, { strokes, strokeAlign: align }, 'Change stroke align')+ }+ })+}++/** The alignment the nodes share, MIXED when they differ, as Figma's Position field shows. */+export function currentAlign(nodes: readonly SceneNode[]): MixedValue<Stroke['align']> {+ const first = nodes.at(0)+ if (!first) return 'CENTER'+ const align = alignOf(first)+ return nodes.every((node) => alignOf(node) === align) ? align : MIXED}export function currentSides(activeNode: SceneNode | null): StrokeSides {@@ -187,77 +198,80 @@ export function setGap(stroke: Stroke | undefined, value: number): Partial<Strokreturn { dashPattern: [dash, Math.max(1, value)] }}-export function borderWeight(activeNode: SceneNode | null, side: (typeof BORDER_SIDES)[number]) {- if (!activeNode) return 0- const key = `border${side[0].toUpperCase()}${side.slice(1)}Weight` as keyof SceneNode- const value = activeNode[key]- return typeof value === 'number' ? value : 0+const BORDER_KEYS = {+ top: 'borderTopWeight',+ right: 'borderRightWeight',+ bottom: 'borderBottomWeight',+ left: 'borderLeftWeight'+} as const++function borderKey(side: (typeof BORDER_SIDES)[number]) {+ return BORDER_KEYS[side]+}++export function borderWeight(+ nodes: readonly SceneNode[],+ side: (typeof BORDER_SIDES)[number]+): MixedValue<number> {+ const first = nodes.at(0)+ if (!first) return 0+ const key = borderKey(side)+ return nodes.every((node) => node[key] === first[key]) ? first[key] : MIXED}export function createStrokeSideActions(editor: Editor, sideMenuOpen: Ref<boolean>) {- function selectSide(side: StrokeSides, activeNode: SceneNode | null) {- if (!activeNode) return- const weight = activeNode.strokes.length > 0 ? activeNode.strokes[0].weight : 1+ function sideChanges(side: StrokeSides, node: SceneNode): Partial<SceneNode> {+ const weight = node.strokes.at(0)?.weight ?? 1if (side === 'ALL') {- editor.updateNodeWithUndo(- activeNode.id,- {- independentStrokeWeights: false,- borderTopWeight: 0,- borderRightWeight: 0,- borderBottomWeight: 0,- borderLeftWeight: 0- } as Partial<SceneNode>,- 'Stroke all sides'- )- } else if (side === 'CUSTOM') {- const w = activeNode.independentStrokeWeights- ? {- top: activeNode.borderTopWeight,- right: activeNode.borderRightWeight,- bottom: activeNode.borderBottomWeight,- left: activeNode.borderLeftWeight- }- : { top: weight, right: weight, bottom: weight, left: weight }- editor.updateNodeWithUndo(- activeNode.id,- {- independentStrokeWeights: true,- borderTopWeight: w.top,- borderRightWeight: w.right,- borderBottomWeight: w.bottom,- borderLeftWeight: w.left- } as Partial<SceneNode>,- 'Custom stroke sides'- )- } else {- editor.updateNodeWithUndo(- activeNode.id,- {- independentStrokeWeights: true,- borderTopWeight: side === 'TOP' ? weight : 0,- borderRightWeight: side === 'RIGHT' ? weight : 0,- borderBottomWeight: side === 'BOTTOM' ? weight : 0,- borderLeftWeight: side === 'LEFT' ? weight : 0- } as Partial<SceneNode>,- `Stroke ${side.toLowerCase()} only`- )+ return {+ independentStrokeWeights: false,+ borderTopWeight: 0,+ borderRightWeight: 0,+ borderBottomWeight: 0,+ borderLeftWeight: 0+ }+ }+ if (side === 'CUSTOM') {+ const independent = node.independentStrokeWeights+ return {+ independentStrokeWeights: true,+ borderTopWeight: independent ? node.borderTopWeight : weight,+ borderRightWeight: independent ? node.borderRightWeight : weight,+ borderBottomWeight: independent ? node.borderBottomWeight : weight,+ borderLeftWeight: independent ? node.borderLeftWeight : weight+ }+ }+ return {+ independentStrokeWeights: true,+ borderTopWeight: side === 'TOP' ? weight : 0,+ borderRightWeight: side === 'RIGHT' ? weight : 0,+ borderBottomWeight: side === 'BOTTOM' ? weight : 0,+ borderLeftWeight: side === 'LEFT' ? weight : 0}+ }++ function selectSide(side: StrokeSides, nodes: readonly SceneNode[]) {+ const labels: Partial<Record<StrokeSides, string>> = {+ ALL: 'Stroke all sides',+ CUSTOM: 'Custom stroke sides'+ }+ const label = labels[side] ?? `Stroke ${side.toLowerCase()} only`+ editor.undo.runBatch(label, () => {+ for (const node of nodes) editor.updateNodeWithUndo(node.id, sideChanges(side, node), label)+ })sideMenuOpen.value = false}function updateBorderWeight(side: (typeof BORDER_SIDES)[number],value: number,- activeNode: SceneNode | null+ nodes: readonly SceneNode[]) {- if (!activeNode) return- const key = `border${side[0].toUpperCase()}${side.slice(1)}Weight` as keyof SceneNode- editor.updateNodeWithUndo(- activeNode.id,- { [key]: value } as Partial<SceneNode>,- 'Change stroke weight'- )+ const key = borderKey(side)+ editor.undo.runBatch('Change stroke weight', () => {+ for (const node of nodes)+ editor.updateNodeWithUndo(node.id, { [key]: value }, 'Change stroke weight')+ })}return { selectSide, updateBorderWeight }diff --git a/packages/vue/src/controls/stroke/use.ts b/packages/vue/src/controls/stroke/use.tsindex 767568cf9..e0b9d78ad 100644--- a/packages/vue/src/controls/stroke/use.ts+++ b/packages/vue/src/controls/stroke/use.ts@@ -17,7 +17,8 @@ import {setDash,setGap,toggleDash,- updateAlign+ updateAlign,+ type StrokeSides} from '#vue/controls/stroke/helpers'import { useEditor } from '#vue/editor/context'import { useI18n } from '#vue/i18n'@@ -68,15 +69,21 @@ export function useStrokeControls() {const first = nodes.value.at(0)return { ...DEFAULT_STROKE, ...(first ? newStrokeGeometry(first) : {}) }},- updateAlign: updateAlign.bind(null, store),- currentAlign,+ /** Aligns the strokes of every selected node. */+ updateAlign: (align: Stroke['align']) => updateAlign(store, nodes.value, align),+ /** The alignment the selected nodes share, or MIXED. */+ currentAlign: () => currentAlign(nodes.value),currentSides,dashState,toggleDash,setDash,setGap,- borderWeight,- selectSide,- updateBorderWeight+ /** One side's weight across the selection, or MIXED. */+ borderWeight: (side: (typeof BORDER_SIDES)[number]) => borderWeight(nodes.value, side),+ /** Strokes the chosen sides of every selected node. */+ selectSide: (side: StrokeSides) => selectSide(side, nodes.value),+ /** Changes one side's weight on every selected node. */+ updateBorderWeight: (side: (typeof BORDER_SIDES)[number], value: number) =>+ updateBorderWeight(side, value, nodes.value)}}diff --git a/packages/vue/src/controls/typography/actions.ts b/packages/vue/src/controls/typography/actions.tsindex 18f6185cf..7628604c5 100644--- a/packages/vue/src/controls/typography/actions.ts+++ b/packages/vue/src/controls/typography/actions.ts@@ -5,6 +5,7 @@ import type { Editor } from '@open-pencil/core/editor'import { FONT_WEIGHT_NAMES, weightToStyle } from '@open-pencil/core/text'import type { SceneNode, TextDecoration } from '@open-pencil/scene-graph'+import { MIXED, type MixedValue } from '#vue/controls/node-props/use'import type { UseTypographyOptions } from '#vue/controls/typography/use'import { useSceneComputed } from '#vue/internal/scene-computed/use'import { useNodeFontStatus } from '#vue/shared/font-status/use'@@ -20,8 +21,31 @@ export const TYPOGRAPHY_WEIGHTS = Object.entries(FONT_WEIGHT_NAMES).map(([value,label}))+function sharedValue<T>(values: readonly T[]): MixedValue<T> {+ const [first] = values+ return values.every((value) => value === first) ? first : MIXED+}++/** The formatting every node has, so a mixed toggle reads as off. */+function sharedFormatting(nodes: readonly SceneNode[]) {+ if (nodes.length === 0) return []+ const result: string[] = []+ if (nodes.every((n) => n.fontWeight >= 700)) result.push('bold')+ if (nodes.every((n) => n.italic)) result.push('italic')+ if (nodes.every((n) => n.textDecoration === 'UNDERLINE')) result.push('underline')+ if (nodes.every((n) => n.textDecoration === 'STRIKETHROUGH')) result.push('strikethrough')+ return result+}++/**+ * Typography of the selected text layers. With other layers selected too, Figma shows the text's+ * typography and edits only the text, so `nodes` holds just the text layers.+ */export function createTypographyState(editor: Editor) {- const node = useSceneComputed<SceneNode | null>(() => editor.getSelectedNode() ?? null)+ const nodes = useSceneComputed<SceneNode[]>(() =>+ editor.getSelectedNodes().filter((n) => n.type === 'TEXT')+ )+ const node = computed<SceneNode | null>(() => nodes.value.at(0) ?? null)const { missingFonts, hasMissingFonts } = useNodeFontStatus(() => node.value)const fontFamily = computed(() => node.value?.fontFamily ?? '')const fontWeight = computed(() => node.value?.fontWeight ?? 400)@@ -29,19 +53,25 @@ export function createTypographyState(editor: Editor) {const currentWeightLabel = computed(() => FONT_WEIGHT_NAMES[node.value?.fontWeight ?? 400] ?? 'Regular')- const activeFormatting = computed(() => {- const n = node.value- if (!n) return []- const result: string[] = []- if (n.fontWeight >= 700) result.push('bold')- if (n.italic) result.push('italic')- if (n.textDecoration === 'UNDERLINE') result.push('underline')- if (n.textDecoration === 'STRIKETHROUGH') result.push('strikethrough')- return result- })+ const activeFormatting = computed(() => sharedFormatting(nodes.value))++ /** The value every selected text layer shares, or MIXED when they differ. */+ function merged<K extends keyof SceneNode>(key: K): MixedValue<SceneNode[K]> {+ return sharedValue(nodes.value.map((n) => n[key]))+ }++ /** Whether one OpenType feature is on for every text layer, MIXED when they differ. */+ function fontFeature(tag: string): MixedValue<boolean> {+ return sharedValue(+ nodes.value.map((n) => n.fontFeatures.find((feature) => feature.tag === tag)?.enabled ?? true)+ )+ }return {node,+ nodes,+ merged,+ fontFeature,fontFamily,fontWeight,fontSize,@@ -54,103 +84,100 @@ export function createTypographyState(editor: Editor) {type TypographyActionOptions = {editor: Editor- node: ComputedRef<SceneNode | null>- currentWeightLabel: ComputedRef<string>+ nodes: ComputedRef<SceneNode[]>activeFormatting: ComputedRef<string[]>options: UseTypographyOptions}export function createTypographyActions({editor,- node,- currentWeightLabel,+ nodes,activeFormatting,options}: TypographyActionOptions) {- let propBeforePreview:- | { key: keyof SceneNode; value: SceneNode[keyof SceneNode]; textStyleId: string | null }- | undefined+ type Preview = { value: SceneNode[keyof SceneNode]; textStyleId: string | null }+ let previewKey: keyof SceneNode | undefined+ const beforePreview = new Map<string, Preview>()- async function doLoadFont(family: string, style: string) {- await options.fontLoader?.load(family, style)+ /** Applies one change per text layer in one undo step. */+ function updateEach(label: string, changes: (node: SceneNode) => Partial<SceneNode>) {+ const targets = nodes.value+ if (targets.length === 0) return+ editor.undo.runBatch(label, () => {+ for (const target of targets) editor.updateNodeWithUndo(target.id, changes(target), label)+ })+ }++ function update(label: string, changes: Partial<SceneNode>) {+ updateEach(label, () => changes)}async function setFamily(family: string) {- if (!node.value) return- await doLoadFont(family, currentWeightLabel.value)- editor.updateNodeWithUndo(node.value.id, { fontFamily: family }, 'Change font')+ const targets = nodes.value+ if (targets.length === 0) return+ await Promise.all(+ targets.map((target) =>+ options.fontLoader?.load(family, FONT_WEIGHT_NAMES[target.fontWeight] ?? 'Regular')+ )+ )+ update('Change font', { fontFamily: family })}async function setWeight(weight: number) {- if (!node.value) return- const { id, fontFamily } = node.value+ const targets = nodes.value+ if (targets.length === 0) return+ update('Change font weight', { fontWeight: weight })const style = weightToStyle(weight)- editor.updateNodeWithUndo(id, { fontWeight: weight }, 'Change font weight')- await doLoadFont(fontFamily, style)+ await Promise.all(targets.map((target) => options.fontLoader?.load(target.fontFamily, style)))}function setAlign(align: TextAlign) {- if (!node.value) return- editor.updateNodeWithUndo(- node.value.id,- { textAlignHorizontal: align },- 'Change text alignment'- )+ update('Change text alignment', { textAlignHorizontal: align })}function setDirection(direction: TextDirection) {- if (!node.value) return- editor.updateNodeWithUndo(node.value.id, { textDirection: direction }, 'Change text direction')+ update('Change text direction', { textDirection: direction })}function setVerticalAlign(align: TextVerticalAlign) {- if (!node.value) return- editor.updateNodeWithUndo(- node.value.id,- { textAlignVertical: align },- 'Change vertical text alignment'- )+ update('Change vertical text alignment', { textAlignVertical: align })}function setTextCase(textCase: TextCase) {- if (!node.value) return- editor.updateNodeWithUndo(node.value.id, { textCase }, 'Change text case')+ update('Change text case', { textCase })}function setTruncation(textTruncation: TextTruncation) {- if (!node.value) return- editor.updateNodeWithUndo(node.value.id, { textTruncation }, 'Change text truncation')+ update('Change text truncation', { textTruncation })}function setFontFeature(tag: string, enabled: boolean) {- if (!node.value) return- const fontFeatures = node.value.fontFeatures.filter((feature) => feature.tag !== tag)- fontFeatures.push({ tag, enabled })- editor.updateNodeWithUndo(node.value.id, { fontFeatures }, `Change ${tag} feature`)+ updateEach(`Change ${tag} feature`, (target) => ({+ fontFeatures: [+ ...target.fontFeatures.filter((feature) => feature.tag !== tag),+ { tag, enabled }+ ]+ }))}+ /** Bold unless every text layer already is, as Figma's toggle does for a mixed selection. */function toggleBold() {- if (!node.value) return- void setWeight(node.value.fontWeight >= 700 ? 400 : 700)+ const bold = activeFormatting.value.includes('bold')+ void setWeight(bold ? 400 : 700)}function toggleItalic() {- if (!node.value) return- editor.updateNodeWithUndo(node.value.id, { italic: !node.value.italic }, 'Toggle italic')+ update('Toggle italic', { italic: !activeFormatting.value.includes('italic') })}function toggleDecoration(deco: 'UNDERLINE' | 'STRIKETHROUGH') {- if (!node.value) return- const current = node.value.textDecoration- editor.updateNodeWithUndo(- node.value.id,- { textDecoration: (current === deco ? 'NONE' : deco) as TextDecoration },- `Toggle ${deco.toLowerCase()}`- )+ const on = activeFormatting.value.includes(deco.toLowerCase())+ update(`Toggle ${deco.toLowerCase()}`, {+ textDecoration: (on ? 'NONE' : deco) as TextDecoration+ })}function onFormattingChange(values: string[]) {- if (!node.value) returnconst prev = activeFormatting.valueconst added = values.filter((v) => !prev.includes(v))const removed = prev.filter((v) => !values.includes(v))@@ -163,15 +190,15 @@ export function createTypographyActions({}function updateProp(key: keyof SceneNode, value: number | string | null) {- if (!node.value) return- if (!propBeforePreview || propBeforePreview.key !== key) {- propBeforePreview = {- key,- value: node.value[key],- textStyleId: node.value.textStyleId- }+ if (previewKey !== key) {+ previewKey = key+ beforePreview.clear()+ }+ for (const target of nodes.value) {+ if (!beforePreview.has(target.id))+ beforePreview.set(target.id, { value: target[key], textStyleId: target.textStyleId })+ editor.updateNode(target.id, { [key]: value } as Partial<SceneNode>)}- editor.updateNode(node.value.id, { [key]: value } as Partial<SceneNode>)}function commitProp(@@ -179,17 +206,24 @@ export function createTypographyActions({_value: number | string | null,previous: number | string | null) {- if (!node.value) return- const snapshot = propBeforePreview?.key === key ? propBeforePreview : undefined- editor.commitNodeUpdate(- node.value.id,- {- [key]: snapshot ? snapshot.value : previous,- ...(snapshot ? { textStyleId: snapshot.textStyleId } : {})- } as Partial<SceneNode>,- `Change ${String(key)}`- )- propBeforePreview = undefined+ const targets = nodes.value+ if (targets.length === 0) return+ const snapshots = previewKey === key ? beforePreview : new Map<string, Preview>()+ editor.undo.runBatch(`Change ${String(key)}`, () => {+ for (const target of targets) {+ const snapshot = snapshots.get(target.id)+ editor.commitNodeUpdate(+ target.id,+ {+ [key]: snapshot ? snapshot.value : previous,+ ...(snapshot ? { textStyleId: snapshot.textStyleId } : {})+ } as Partial<SceneNode>,+ `Change ${String(key)}`+ )+ }+ })+ previewKey = undefined+ beforePreview.clear()}return {diff --git a/packages/vue/src/i18n/locales/de/panels.json b/packages/vue/src/i18n/locales/de/panels.jsonindex 10b202810..7264588ac 100644--- a/packages/vue/src/i18n/locales/de/panels.json+++ b/packages/vue/src/i18n/locales/de/panels.json@@ -6,6 +6,7 @@"ai": "KI","assets": "Elemente","page": "Seite",+ "selectionColors": "Auswahlfarben","frame": "Frame","framePreset": "Frame-Voreinstellung","framePresetCustom": "Benutzerdefiniert",@@ -91,7 +92,7 @@"effectStyle": "Effektstil","gridStyle": "Rasterstil","missingStyle": "Fehlender Stil ({id})",- "layersCount": "{count} Ebenen",+ "selectedCount": "{count} ausgewählt","goToMainComponent": "Zur Hauptkomponente","solid": "Vollton","linearGradient": "Linear",@@ -129,6 +130,7 @@"flow": "Fluss","freeform": "Freiform","dimensions": "Abmessungen",+ "spacing": "Abstand","layoutHorizontal": "Horizontales Layout","layoutVertical": "Vertikales Layout","layoutGrid": "Rasterlayout",diff --git a/packages/vue/src/i18n/locales/es/panels.json b/packages/vue/src/i18n/locales/es/panels.jsonindex 582d8da51..ca07aeb1b 100644--- a/packages/vue/src/i18n/locales/es/panels.json+++ b/packages/vue/src/i18n/locales/es/panels.json@@ -7,6 +7,7 @@"ai": "IA","assets": "Recursos","page": "Página",+ "selectionColors": "Colores de la selección","frame": "Marco","framePreset": "Preajuste de marco","framePresetCustom": "Personalizado",@@ -104,7 +105,7 @@"effectStyle": "Estilo de efecto","gridStyle": "Estilo de cuadrícula","missingStyle": "Estilo no disponible ({id})",- "layersCount": "{count} capas",+ "selectedCount": "{count} seleccionados","goToMainComponent": "Ir al componente principal","solid": "Sólido","linearGradient": "Lineal",@@ -142,6 +143,7 @@"flow": "Flujo","freeform": "Forma libre","dimensions": "Dimensiones",+ "spacing": "Espaciado","layoutHorizontal": "Diseño horizontal","layoutVertical": "Diseño vertical","layoutGrid": "Diseño de cuadrícula",diff --git a/packages/vue/src/i18n/locales/fr/panels.json b/packages/vue/src/i18n/locales/fr/panels.jsonindex 82094138c..55bca6350 100644--- a/packages/vue/src/i18n/locales/fr/panels.json+++ b/packages/vue/src/i18n/locales/fr/panels.json@@ -6,6 +6,7 @@"ai": "IA","assets": "Ressources","page": "Page",+ "selectionColors": "Couleurs de la sélection","frame": "Cadre","framePreset": "Préréglage de cadre","framePresetCustom": "Personnalisé",@@ -91,7 +92,7 @@"effectStyle": "Style d’effet","gridStyle": "Style de grille","missingStyle": "Style manquant ({id})",- "layersCount": "{count} calques",+ "selectedCount": "{count} sélectionnés","goToMainComponent": "Aller au composant principal","solid": "Uni","linearGradient": "Linéaire",@@ -129,6 +130,7 @@"flow": "Flux","freeform": "Forme libre","dimensions": "Dimensions",+ "spacing": "Espacement","layoutHorizontal": "Disposition horizontale","layoutVertical": "Disposition verticale","layoutGrid": "Disposition en grille",diff --git a/packages/vue/src/i18n/locales/it/panels.json b/packages/vue/src/i18n/locales/it/panels.jsonindex dc4483d87..e16abed6d 100644--- a/packages/vue/src/i18n/locales/it/panels.json+++ b/packages/vue/src/i18n/locales/it/panels.json@@ -6,6 +6,7 @@"ai": "AI","assets": "Risorse","page": "Pagina",+ "selectionColors": "Colori della selezione","frame": "Cornice","framePreset": "Preimpostazione cornice","framePresetCustom": "Personalizzata",@@ -91,7 +92,7 @@"effectStyle": "Stile effetto","gridStyle": "Stile griglia","missingStyle": "Stile mancante ({id})",- "layersCount": "{count} livelli",+ "selectedCount": "{count} selezionati","goToMainComponent": "Vai al componente principale","solid": "Pieno","linearGradient": "Lineare",@@ -129,6 +130,7 @@"flow": "Flusso","freeform": "Forma libera","dimensions": "Dimensioni",+ "spacing": "Spaziatura","layoutHorizontal": "Layout orizzontale","layoutVertical": "Layout verticale","layoutGrid": "Layout a griglia",diff --git a/packages/vue/src/i18n/locales/ja/panels.json b/packages/vue/src/i18n/locales/ja/panels.jsonindex 30b7b0642..d1b32031b 100644--- a/packages/vue/src/i18n/locales/ja/panels.json+++ b/packages/vue/src/i18n/locales/ja/panels.json@@ -7,6 +7,7 @@"ai": "AI","assets": "アセット","page": "ページ",+ "selectionColors": "選択範囲の色","frame": "フレーム","framePreset": "フレームプリセット","framePresetCustom": "カスタム",@@ -104,7 +105,7 @@"effectStyle": "エフェクトスタイル","gridStyle": "グリッドスタイル","missingStyle": "不明なスタイル ({id})",- "layersCount": "{count} 個のレイヤー",+ "selectedCount": "{count} 個を選択","goToMainComponent": "メインコンポーネントに移動","solid": "ソリッド (単色)","linearGradient": "線形グラデーション",@@ -142,6 +143,7 @@"flow": "フロー","freeform": "フリーフォーム","dimensions": "寸法",+ "spacing": "間隔","layoutHorizontal": "横方向レイアウト","layoutVertical": "縦方向レイアウト","layoutGrid": "グリッドレイアウト",diff --git a/packages/vue/src/i18n/locales/pl/panels.json b/packages/vue/src/i18n/locales/pl/panels.jsonindex b25deabb2..18aed632c 100644--- a/packages/vue/src/i18n/locales/pl/panels.json+++ b/packages/vue/src/i18n/locales/pl/panels.json@@ -6,6 +6,7 @@"ai": "AI","assets": "Zasoby","page": "Strona",+ "selectionColors": "Kolory zaznaczenia","frame": "Ramka","framePreset": "Ustawienie ramki","framePresetCustom": "Niestandardowe",@@ -91,7 +92,7 @@"effectStyle": "Styl efektu","gridStyle": "Styl siatki","missingStyle": "Brakujący styl ({id})",- "layersCount": "{count} warstw",+ "selectedCount": "Zaznaczono: {count}","goToMainComponent": "Przejdź do głównego komponentu","solid": "Jednolity","linearGradient": "Liniowy",@@ -129,6 +130,7 @@"flow": "Przepływ","freeform": "Swobodny","dimensions": "Wymiary",+ "spacing": "Odstęp","layoutHorizontal": "Układ poziomy","layoutVertical": "Układ pionowy","layoutGrid": "Układ siatki",diff --git a/packages/vue/src/i18n/locales/ru/panels.json b/packages/vue/src/i18n/locales/ru/panels.jsonindex 6b39a6431..a3cc95e6c 100644--- a/packages/vue/src/i18n/locales/ru/panels.json+++ b/packages/vue/src/i18n/locales/ru/panels.json@@ -6,6 +6,7 @@"ai": "AI","assets": "Ассеты","page": "Страница",+ "selectionColors": "Цвета выделения","frame": "Фрейм","framePreset": "Размер фрейма","framePresetCustom": "Пользовательский",@@ -104,7 +105,7 @@"effectStyle": "Стиль эффекта","gridStyle": "Стиль сетки","missingStyle": "Недоступный стиль ({id})",- "layersCount": "{count} слоёв",+ "selectedCount": "Выбрано: {count}","goToMainComponent": "Перейти к главному компоненту","solid": "Сплошной","linearGradient": "Линейный",@@ -129,6 +130,7 @@"flow": "Поток","freeform": "Свободная","dimensions": "Размеры",+ "spacing": "Интервал","layoutHorizontal": "Горизонтальная раскладка","layoutVertical": "Вертикальная раскладка","layoutGrid": "Сетка",diff --git a/packages/vue/src/i18n/locales/zh-cn/panels.json b/packages/vue/src/i18n/locales/zh-cn/panels.jsonindex cf2f3dc61..b4cc0480a 100644--- a/packages/vue/src/i18n/locales/zh-cn/panels.json+++ b/packages/vue/src/i18n/locales/zh-cn/panels.json@@ -6,6 +6,7 @@"ai": "AI","assets": "资源","page": "页面",+ "selectionColors": "所选颜色","frame": "画框","framePreset": "画框预设","framePresetCustom": "自定义",@@ -104,7 +105,7 @@"effectStyle": "效果样式","gridStyle": "网格样式","missingStyle": "缺失样式 ({id})",- "layersCount": "{count} 个图层",+ "selectedCount": "已选择 {count} 个","goToMainComponent": "转到主组件","solid": "纯色","linearGradient": "线性",@@ -129,6 +130,7 @@"flow": "流向","freeform": "自由布局","dimensions": "尺寸",+ "spacing": "间距","layoutHorizontal": "水平布局","layoutVertical": "垂直布局","layoutGrid": "网格布局",diff --git a/packages/vue/src/i18n/messages/panels.ts b/packages/vue/src/i18n/messages/panels.tsindex ee5e909cb..00d89b82f 100644--- a/packages/vue/src/i18n/messages/panels.ts+++ b/packages/vue/src/i18n/messages/panels.ts@@ -131,6 +131,7 @@ export const panelMessageDefaults = {spread: 'Spread',page: 'Page',+ selectionColors: 'Selection colors',frame: 'Frame',framePreset: 'Frame preset',framePresetCustom: 'Custom',@@ -428,7 +429,7 @@ export const panelMessageDefaults = {effectStyle: 'Effect style',gridStyle: 'Grid style',missingStyle: params('Missing style ({id})'),- layersCount: params('{count} layers'),+ selectedCount: params('{count} selected'),goToMainComponent: 'Go to main component',gap: 'Gap',@@ -457,6 +458,7 @@ export const panelMessageDefaults = {flow: 'Flow',freeform: 'Freeform',dimensions: 'Dimensions',+ spacing: 'Spacing',layoutHorizontal: 'Horizontal layout',layoutVertical: 'Vertical layout',layoutGrid: 'Grid layout',diff --git a/packages/vue/src/index.ts b/packages/vue/src/index.tsindex f44e95d0b..a6b647678 100644--- a/packages/vue/src/index.ts+++ b/packages/vue/src/index.ts@@ -102,6 +102,13 @@ export type { TestId } from '#vue/testing/test-id'/** Property-panel composables. */export { usePosition } from '#vue/controls/position/use'export { useLayout } from '#vue/controls/layout/use'+export { useSelectionColors } from '#vue/controls/selection-colors/use'+export {+ LAYOUT_CONTAINER_TYPES,+ textResizeMode,+ useSelectionLayout+} from '#vue/controls/selection-layout/use'+export type { TextResizeMode } from '#vue/controls/selection-layout/use'export type { LayoutAxis, SizeLimitProp } from '#vue/controls/layout/helpers'export { useAppearance } from '#vue/controls/appearance/use'export { useMask } from '#vue/controls/mask/use'diff --git a/packages/vue/src/primitives/AppearanceControls/AppearanceControlsRoot.vue b/packages/vue/src/primitives/AppearanceControls/AppearanceControlsRoot.vueindex 40391f4f3..78703f64e 100644--- a/packages/vue/src/primitives/AppearanceControls/AppearanceControlsRoot.vue+++ b/packages/vue/src/primitives/AppearanceControls/AppearanceControlsRoot.vue@@ -23,6 +23,7 @@ const actions = {:is-multi="ctx.isMulti.value":active="ctx.active.value":has-corner-radius="ctx.hasCornerRadius.value"+ :corner-radius-disabled="ctx.cornerRadiusDisabled.value":independent-corners="ctx.independentCorners.value":show-independent-corners="ctx.showIndependentCorners.value":corner-radius-value="ctx.cornerRadiusValue.value"diff --git a/packages/vue/src/primitives/AppearanceControls/types.ts b/packages/vue/src/primitives/AppearanceControls/types.tsindex 57b183e66..26ceb3395 100644--- a/packages/vue/src/primitives/AppearanceControls/types.ts+++ b/packages/vue/src/primitives/AppearanceControls/types.ts@@ -22,6 +22,8 @@ export interface AppearanceControlsRootSlotProps {isMulti: booleanactive: booleanhasCornerRadius: boolean+ /** A multi-selection with no layer that has corners shows the radius disabled, as Figma does. */+ cornerRadiusDisabled: booleanindependentCorners: MixedValue<boolean>showIndependentCorners: booleancornerRadiusValue: MixedValue<number>diff --git a/packages/vue/src/primitives/TypographyControls/TypographyControlsRoot.vue b/packages/vue/src/primitives/TypographyControls/TypographyControlsRoot.vueindex b19ee244e..5c443b366 100644--- a/packages/vue/src/primitives/TypographyControls/TypographyControlsRoot.vue+++ b/packages/vue/src/primitives/TypographyControls/TypographyControlsRoot.vue@@ -39,6 +39,9 @@ const actions = {<template><slot:node="ctx.node"+ :nodes="ctx.nodes"+ :merged="ctx.merged"+ :font-feature="ctx.fontFeature":weights="ctx.weights":missing-fonts="ctx.missingFonts":has-missing-fonts="ctx.hasMissingFonts"diff --git a/src/components/DesignPanel.vue b/src/components/DesignPanel.vueindex d7a735ab0..d306ecc45 100644--- a/src/components/DesignPanel.vue+++ b/src/components/DesignPanel.vue@@ -36,6 +36,8 @@ import MaskSection from './properties/MaskSection.vue'import PageSection from './properties/PageSection.vue'import RetainedPanel from './properties/panel/RetainedPanel.vue'import PositionSection from './properties/PositionSection.vue'+import SelectionColorsSection from './properties/selection/SelectionColorsSection.vue'+import SelectionLayoutSection from './properties/selection/SelectionLayoutSection.vue'import SelectionActionsControl from './properties/SelectionActionsControl.vue'import StrokeSection from './properties/stroke/StrokeSection.vue'import TypographySection from './properties/TypographySection.vue'@@ -100,7 +102,7 @@ const { panels } = useI18n()<icon-lucide-layers-3 class="size-3.5" aria-hidden="true" /></template><span role="heading" aria-level="2">- {{ panels.layersCount({ count: String(multiCount) }) }}+ {{ panels.selectedCount({ count: String(multiCount) }) }}</span><template #actions><SelectionActionsControl :show-boolean-operations="showBooleanOperations" />@@ -109,10 +111,13 @@ const { panels } = useI18n()<ComponentPropertiesSection /><PositionSection /><ConstraintsSection />+ <SelectionLayoutSection /><AppearanceSection />+ <TypographySection /><FillSection /><StrokeSection /><EffectsSection />+ <SelectionColorsSection /><ExportSection /></div>@@ -202,6 +207,7 @@ const { panels } = useI18n()<StrokeSection /><LayoutGridSection v-if="supportsLayoutGuides" /><EffectsSection />+ <SelectionColorsSection /><ExportSection /></div>diff --git a/src/components/font-picker/FontPicker.vue b/src/components/font-picker/FontPicker.vueindex 29784addf..15eb51ae1 100644--- a/src/components/font-picker/FontPicker.vue+++ b/src/components/font-picker/FontPicker.vue@@ -15,7 +15,8 @@ import { usePopoverUI } from '@/components/ui/overlay/popover'import { useSelectUI } from '@/components/ui/select/select'const { panels } = useI18n()-const { label: labelProp } = defineProps<{ label?: string }>()+/** The placeholder shows while no family is set, such as Mixed for texts in different fonts. */+const { label: labelProp, placeholder } = defineProps<{ label?: string; placeholder?: string }>()const label = computed(() => labelProp ?? panels.value.fontFamily)const modelValue = defineModel<string>({ required: true })const emit = defineEmits<{ select: [family: string] }>()@@ -73,7 +74,9 @@ function loadPreviewFont(family: string, source: string) {:aria-label="label":class="selectCls.trigger">- <span class="truncate">{{ modelValue }}</span>+ <span class="truncate" :class="{ 'text-muted': !modelValue }">{{+ modelValue || placeholder+ }}</span><icon-lucide-chevron-down class="size-3 shrink-0 text-muted" /></button></template>diff --git a/src/components/properties/AppearanceSection.vue b/src/components/properties/AppearanceSection.vueindex e26217520..85f2800fe 100644--- a/src/components/properties/AppearanceSection.vue+++ b/src/components/properties/AppearanceSection.vue@@ -33,6 +33,7 @@ function blendModeOptions(value: BlendMode | typeof MIXED) {isMulti,active,hasCornerRadius,+ cornerRadiusDisabled,showIndependentCorners,cornerRadiusValue,cornerRadiusBindingPaths,@@ -128,6 +129,7 @@ function blendModeOptions(value: BlendMode | typeof MIXED) {data-property="cornerRadius":aria-label="panels.radius":model-value="cornerRadiusValue"+ :disabled="cornerRadiusDisabled":min="0"@update:model-value="actions.updateUniformRadius"@commit="actions.commitUniformRadius"@@ -142,6 +144,7 @@ function blendModeOptions(value: BlendMode | typeof MIXED) {:label="panels.independentCornerRadii"size="xs":active="showIndependentCorners"+ :disabled="cornerRadiusDisabled"@click="actions.toggleIndependentCorners"><icon-lucide-square-round-corner class="size-3" />@@ -203,7 +206,7 @@ function blendModeOptions(value: BlendMode | typeof MIXED) {</template></PanelGrid>- <PanelGrid v-if="hasCornerRadius" :columns="2" class="mt-1.5">+ <PanelGrid v-if="hasCornerRadius && !cornerRadiusDisabled" :columns="2" class="mt-1.5"><PanelFieldGroup :label="panels.cornerSmoothing"><NumberFieldsuffix="%"diff --git a/src/components/properties/EffectsSection.vue b/src/components/properties/EffectsSection.vueindex 7d2ed983b..2964567b7 100644--- a/src/components/properties/EffectsSection.vue+++ b/src/components/properties/EffectsSection.vue@@ -162,12 +162,12 @@ function effectPreview(effect: Effect): Fill {:model-value="effect.offset.x"data-property="effect-offset-x"@update:model-value="- effectsCtx.scrubEffect(activeNode, index, {+ effectsCtx.scrubEffect(index, {offset: { ...effect.offset, x: $event }})"@commit="- effectsCtx.commitEffect(activeNode, index, {+ effectsCtx.commitEffect(index, {offset: { ...effect.offset, x: $event }})"@@ -179,12 +179,12 @@ function effectPreview(effect: Effect): Fill {:model-value="effect.offset.y"data-property="effect-offset-y"@update:model-value="- effectsCtx.scrubEffect(activeNode, index, {+ effectsCtx.scrubEffect(index, {offset: { ...effect.offset, y: $event }})"@commit="- effectsCtx.commitEffect(activeNode, index, {+ effectsCtx.commitEffect(index, {offset: { ...effect.offset, y: $event }})"@@ -199,10 +199,8 @@ function effectPreview(effect: Effect): Fill {:model-value="effect.radius":min="0"data-property="effect-radius"- @update:model-value="- effectsCtx.scrubEffect(activeNode, index, { radius: $event })- "- @commit="effectsCtx.commitEffect(activeNode, index, { radius: $event })"+ @update:model-value="effectsCtx.scrubEffect(index, { radius: $event })"+ @commit="effectsCtx.commitEffect(index, { radius: $event })"/></Tip><Tip :label="panels.spread">@@ -210,10 +208,8 @@ function effectPreview(effect: Effect): Fill {icon="S":model-value="effect.spread"data-property="effect-spread"- @update:model-value="- effectsCtx.scrubEffect(activeNode, index, { spread: $event })- "- @commit="effectsCtx.commitEffect(activeNode, index, { spread: $event })"+ @update:model-value="effectsCtx.scrubEffect(index, { spread: $event })"+ @commit="effectsCtx.commitEffect(index, { spread: $event })"/></Tip></div>@@ -234,12 +230,12 @@ function effectPreview(effect: Effect): Fill {:max="100"data-property="effect-opacity"@update:model-value="- effectsCtx.scrubEffect(activeNode, index, {+ effectsCtx.scrubEffect(index, {color: { ...effect.color, a: Math.max(0, Math.min(1, $event / 100)) }})"@commit="- effectsCtx.commitEffect(activeNode, index, {+ effectsCtx.commitEffect(index, {color: { ...effect.color, a: Math.max(0, Math.min(1, $event / 100)) }})"@@ -255,8 +251,8 @@ function effectPreview(effect: Effect): Fill {:model-value="effect.radius":min="0"data-property="effect-radius"- @update:model-value="effectsCtx.scrubEffect(activeNode, index, { radius: $event })"- @commit="effectsCtx.commitEffect(activeNode, index, { radius: $event })"+ @update:model-value="effectsCtx.scrubEffect(index, { radius: $event })"+ @commit="effectsCtx.commitEffect(index, { radius: $event })"/></div></div>diff --git a/src/components/properties/PositionSection.vue b/src/components/properties/PositionSection.vueindex 4dc1b57da..759f3a664 100644--- a/src/components/properties/PositionSection.vue+++ b/src/components/properties/PositionSection.vue@@ -26,9 +26,7 @@ function handleAlign(</script><template>- <PositionControlsRoot- v-slot="{ active, isMulti, xValue, yValue, wValue, hValue, rotationValue, actions }"- >+ <PositionControlsRoot v-slot="{ active, xValue, yValue, rotationValue, actions }"><PanelSection v-if="active" :label="panels.position"><div role="toolbar" :aria-label="panels.position" class="mb-1.5 flex justify-between"><div class="flex gap-0.5">@@ -104,33 +102,6 @@ function handleAlign(</Tip></PanelGrid>- <PanelGrid v-if="isMulti" :columns="2" class="mt-1.5">- <Tip :label="panels.width">- <NumberField- icon="W"- data-property="width"- :aria-label="panels.width"- :model-value="wValue"- :min="1"- @update:model-value="actions.updateProp('width', $event)"- @commit="(v: number, p: number) => actions.commitProp('width', v, p)"- @cancel="actions.cancelProp('width')"- />- </Tip>- <Tip :label="panels.height">- <NumberField- icon="H"- data-property="height"- :aria-label="panels.height"- :model-value="hValue"- :min="1"- @update:model-value="actions.updateProp('height', $event)"- @commit="(v: number, p: number) => actions.commitProp('height', v, p)"- @cancel="actions.cancelProp('height')"- />- </Tip>- </PanelGrid>-<PanelGrid :columns="2" class="mt-1.5"><Tip :label="panels.rotation"><NumberFielddiff --git a/src/components/properties/TypographySection.vue b/src/components/properties/TypographySection.vueindex cbafb1b1d..3638e30c5 100644--- a/src/components/properties/TypographySection.vue+++ b/src/components/properties/TypographySection.vue@@ -1,7 +1,7 @@<script setup lang="ts">import { computed } from 'vue'-import { TypographyControlsRoot, useI18n } from '@open-pencil/vue'+import { MIXED, TypographyControlsRoot, useI18n, type MixedValue } from '@open-pencil/vue'import { loadFont } from '@/app/editor/fonts'import { appMenuShortcutLabel } from '@/app/shell/menu/shortcut'@@ -52,25 +52,31 @@ const commonFeatures = computed(() => [{ tag: 'KERN', label: panels.value.kerning }])-function featureEnabled(features: Array<{ tag: string; enabled: boolean }>, tag: string) {- return features.find((feature) => feature.tag === tag)?.enabled ?? true+/** Empty when the text layers differ, so selects and segmented controls show no choice. */+function picked<T>(value: MixedValue<T>): T | '' {+ return value === MIXED ? '' : value}</script><template><TypographyControlsRoot v-slot="ctx" :font-loader="fontLoader">- <PanelSection v-if="ctx.node.value" :label="panels.typography">- <template #actions>+ <PanelSection v-if="ctx.node.value" :label="panels.typography" data-test-id="typography">+ <template v-if="ctx.nodes.value.length === 1" #actions><PropertyBindButton field="TEXT" /></template>- <PropertyBoundField field="TEXT" :label="panels.content" />+ <PropertyBoundField+ v-if="ctx.nodes.value.length === 1"+ field="TEXT"+ :label="panels.content"+ /><SharedStyleField kind="text" :label="panels.textStyle" /><div class="mb-1.5 flex min-w-0 items-center gap-1.5"><FontPickerclass="min-w-0 flex-1"- :model-value="ctx.node.value.fontFamily"+ :model-value="picked(ctx.merged('fontFamily'))":label="panels.fontFamily"+ :placeholder="panels.mixed"@select="ctx.actions.setFamily"/><FontSettingsPopover />@@ -100,18 +106,20 @@ function featureEnabled(features: Array<{ tag: string; enabled: boolean }>, tag:<PanelFieldGroup :label="panels.fontWeight"><AppSelect:label="panels.fontWeight"- :model-value="ctx.node.value.fontWeight"+ :model-value="picked(ctx.merged('fontWeight'))":options="ctx.weights"+ :placeholder="panels.mixed"@update:model-value="ctx.actions.setWeight(+$event)"/></PanelFieldGroup><PanelFieldGroup :label="panels.fontSize"><VariableNumberField- :model-value="ctx.node.value.fontSize"+ :model-value="ctx.merged('fontSize')":aria-label="panels.fontSize":min="1":max="1000":node-id="ctx.node.value.id"+ :node-ids="ctx.nodes.value.map((text) => text.id)"binding-path="fontSize"@update:model-value="ctx.actions.updateProp('fontSize', $event)"@commit="(v: number, p: number) => ctx.actions.commitProp('fontSize', v, p)"@@ -122,7 +130,7 @@ function featureEnabled(features: Array<{ tag: string; enabled: boolean }>, tag:<PanelGrid :columns="2" class="mb-3"><PanelFieldGroup :label="panels.lineHeight"><LineHeightField- :node="ctx.node.value"+ :nodes="ctx.nodes.value"@update="ctx.actions.updateProp('lineHeight', $event)"@commit="(v, p) => ctx.actions.commitProp('lineHeight', v, p)"/>@@ -130,9 +138,10 @@ function featureEnabled(features: Array<{ tag: string; enabled: boolean }>, tag:<PanelFieldGroup :label="panels.letterSpacing"><VariableNumberFieldsuffix="px"- :model-value="ctx.node.value.letterSpacing"+ :model-value="ctx.merged('letterSpacing')":aria-label="panels.letterSpacing":node-id="ctx.node.value.id"+ :node-ids="ctx.nodes.value.map((text) => text.id)"binding-path="letterSpacing"@update:model-value="ctx.actions.updateProp('letterSpacing', $event)"@commit="(v: number, p: number) => ctx.actions.commitProp('letterSpacing', v, p)"@@ -148,7 +157,8 @@ function featureEnabled(features: Array<{ tag: string; enabled: boolean }>, tag:<PanelFieldGroup :label="panels.direction" class="mb-3"><AppSelect:label="panels.direction"- :model-value="ctx.node.value.textDirection"+ :model-value="picked(ctx.merged('textDirection'))"+ :placeholder="panels.mixed":options="[{ value: 'AUTO', label: panels.auto },{ value: 'LTR', label: 'LTR' },@@ -160,7 +170,7 @@ function featureEnabled(features: Array<{ tag: string; enabled: boolean }>, tag:<PanelFieldGroup :label="panels.textAlignment" class="mb-3"><SegmentedControl- :model-value="ctx.node.value.textAlignHorizontal"+ :model-value="picked(ctx.merged('textAlignHorizontal'))":options="alignmentOptions":label="panels.textAlignment"@change="ctx.actions.align($event as 'LEFT' | 'CENTER' | 'RIGHT' | 'JUSTIFIED')"@@ -176,7 +186,7 @@ function featureEnabled(features: Array<{ tag: string; enabled: boolean }>, tag:<PanelFieldGroup :label="panels.verticalTextAlignment" class="mb-3"><SegmentedControl- :model-value="ctx.node.value.textAlignVertical"+ :model-value="picked(ctx.merged('textAlignVertical'))":options="verticalAlignmentOptions":label="panels.verticalTextAlignment"@change="ctx.actions.setVerticalAlign($event as 'TOP' | 'CENTER' | 'BOTTOM')"@@ -246,7 +256,8 @@ function featureEnabled(features: Array<{ tag: string; enabled: boolean }>, tag:<PanelFieldGroup :label="panels.textCase"><AppSelect:label="panels.textCase"- :model-value="ctx.node.value.textCase"+ :model-value="picked(ctx.merged('textCase'))"+ :placeholder="panels.mixed":options="textCaseOptions"@update:model-value="ctx.actions.setTextCase($event as 'ORIGINAL' | 'UPPER' | 'LOWER' | 'TITLE')@@ -256,7 +267,8 @@ function featureEnabled(features: Array<{ tag: string; enabled: boolean }>, tag:<PanelFieldGroup :label="panels.truncation"><AppSelect:label="panels.truncation"- :model-value="ctx.node.value.textTruncation"+ :model-value="picked(ctx.merged('textTruncation'))"+ :placeholder="panels.mixed":options="truncationOptions"@update:model-value="ctx.actions.setTruncation($event as 'DISABLED' | 'ENDING')"/>@@ -264,12 +276,12 @@ function featureEnabled(features: Array<{ tag: string; enabled: boolean }>, tag:</PanelGrid><PanelFieldGroup- v-if="ctx.node.value.textTruncation === 'ENDING'"+ v-if="ctx.merged('textTruncation') === 'ENDING'":label="panels.maxLines"class="mb-3"><NumberField- :model-value="ctx.node.value.maxLines ?? 1"+ :model-value="ctx.merged('maxLines') ?? 1":aria-label="panels.maxLines":min="1":step="1"@@ -293,7 +305,7 @@ function featureEnabled(features: Array<{ tag: string; enabled: boolean }>, tag:><span>{{ feature.label }}</span><AppSwitch- :model-value="featureEnabled(ctx.node.value.fontFeatures, feature.tag)"+ :model-value="ctx.fontFeature(feature.tag) === true":label="feature.label":data-property="`font-feature-${feature.tag.toLowerCase()}`"@update:model-value="ctx.actions.setFontFeature(feature.tag, $event)"diff --git a/src/components/properties/VariableNumberField.vue b/src/components/properties/VariableNumberField.vueindex a4179afd4..31e977d46 100644--- a/src/components/properties/VariableNumberField.vue+++ b/src/components/properties/VariableNumberField.vue@@ -19,6 +19,7 @@ const {sensitivity,placeholder,nodeId,+ nodeIds,bindingPath,bindingPaths} = defineProps<{@@ -32,6 +33,8 @@ const {sensitivity?: numberplaceholder?: stringnodeId: string+ /** Every layer the field edits, when it is more than `nodeId`; a variable binds to all. */+ nodeIds?: readonly string[]bindingPath: NumberBindingPathbindingPaths?: readonly NumberBindingPath[]}>()@@ -46,7 +49,9 @@ const { panels, common } = useI18n()const provider = useNumberBindingProvider()const attrs = useAttrs()const targets = computed<BindingTarget[]>(() =>- (bindingPaths ?? [bindingPath]).map((path) => ({ nodeId, path }))+ (nodeIds ?? [nodeId]).flatMap((id) =>+ (bindingPaths ?? [bindingPath]).map((path) => ({ nodeId: id, path }))+ ))const accessibleLabel = computed(() => {const ariaLabel = attrs['aria-label']diff --git a/src/components/properties/layout/ClipContentControl.vue b/src/components/properties/layout/ClipContentControl.vueindex 7f54888cd..902a2903a 100644--- a/src/components/properties/layout/ClipContentControl.vue+++ b/src/components/properties/layout/ClipContentControl.vue@@ -1,8 +1,7 @@<script setup lang="ts">-import { useI18n, useLayoutControlsContext } from '@open-pencil/vue'--const ctx = useLayoutControlsContext()+import { MIXED, useI18n, useSelectionLayout } from '@open-pencil/vue'+const layout = useSelectionLayout()const { panels } = useI18n()</script>@@ -12,14 +11,9 @@ const { panels } = useI18n()type="checkbox"data-test-id="clip-content-checkbox"class="accent-accent"- :checked="ctx.node.clipsContent"- @change="- ctx.editor.updateNodeWithUndo(- ctx.node.id,- { clipsContent: !ctx.node.clipsContent },- 'Toggle clip content'- )- "+ :checked="layout.clipsContent.value === true"+ :indeterminate="layout.clipsContent.value === MIXED"+ @change="layout.toggleClipsContent()"/>{{ panels.clipContent }}</label>diff --git a/src/components/properties/layout/LayoutFlowControl.vue b/src/components/properties/layout/LayoutFlowControl.vueindex 5edfaed27..1df6bbad1 100644--- a/src/components/properties/layout/LayoutFlowControl.vue+++ b/src/components/properties/layout/LayoutFlowControl.vue@@ -1,14 +1,16 @@<script setup lang="ts">import { computed } from 'vue'+import type { VNode } from 'vue'import type { LayoutMode } from '@open-pencil/scene-graph'-import { useI18n, useLayoutControlsContext } from '@open-pencil/vue'+import { MIXED, useI18n, useSelectionLayout } from '@open-pencil/vue'-import IconButton from '@/components/ui/button/IconButton.vue'import Tip from '@/components/ui/overlay/Tip.vue'import SegmentedControl from '@/components/ui/select/SegmentedControl.vue'-const ctx = useLayoutControlsContext()+defineSlots<{ default?(): VNode[] }>()++const layout = useSelectionLayout()const { panels } = useI18n()const layoutModes = computed<Array<{ value: LayoutMode; label: string }>>(() => [@@ -18,23 +20,11 @@ const layoutModes = computed<Array<{ value: LayoutMode; label: string }>>(() =>{ value: 'GRID', label: panels.value.layoutGrid }])-function toggleWrap() {- const node = ctx.node- const enabling = node.layoutWrap !== 'WRAP'- ctx.editor.updateNodeWithUndo(- node.id,- {- layoutWrap: enabling ? 'WRAP' : 'NO_WRAP',- primaryAxisAlign:- enabling && node.primaryAxisAlign === 'SPACE_BETWEEN' ? 'MIN' : node.primaryAxisAlign- },- 'Toggle layout wrap'- )-}--function setLayoutMode(mode: string) {- ctx.editor.setLayoutMode(ctx.node.id, mode as LayoutMode)-}+// Layers with different flows leave every option off.+const mode = computed(() => {+ const value = layout.layoutMode.value+ return value === MIXED || value === undefined ? '' : value+})</script><template>@@ -42,11 +32,11 @@ function setLayoutMode(mode: string) {<label class="mb-1 block text-[11px] text-muted">{{ panels.flow }}</label><div class="flex items-center gap-1.5"><SegmentedControl- :model-value="ctx.node.layoutMode"+ :model-value="mode":options="layoutModes":label="panels.flow":ui="{ root: 'flex min-w-0 flex-1' }"- @change="setLayoutMode"+ @change="layout.setLayoutMode($event as LayoutMode)"><template #option="{ option }"><Tip :label="option.label">@@ -59,16 +49,7 @@ function setLayoutMode(mode: string) {</Tip></template></SegmentedControl>-- <IconButton- v-if="ctx.isFlex"- :label="panels.layoutWrap"- size="xs"- :active="ctx.node.layoutWrap === 'WRAP'"- @click="toggleWrap"- >- <icon-lucide-wrap-text class="size-3.5" />- </IconButton>+ <slot /></div></div></template>diff --git a/src/components/properties/layout/LayoutSection.vue b/src/components/properties/layout/LayoutSection.vueindex 8ec07bf60..9587a2c43 100644--- a/src/components/properties/layout/LayoutSection.vue+++ b/src/components/properties/layout/LayoutSection.vue@@ -1,10 +1,11 @@<script setup lang="ts">-import { LayoutControlsRoot, useI18n } from '@open-pencil/vue'+import { LAYOUT_CONTAINER_TYPES, LayoutControlsRoot, useI18n } from '@open-pencil/vue'import ClipContentControl from '@/components/properties/layout/ClipContentControl.vue'import FlexControls from '@/components/properties/layout/flex/FlexControls.vue'import GridControls from '@/components/properties/layout/grid/GridControls.vue'import LayoutFlowControl from '@/components/properties/layout/LayoutFlowControl.vue'+import LayoutWrapToggle from '@/components/properties/layout/LayoutWrapToggle.vue'import PaddingControls from '@/components/properties/layout/padding/PaddingControls.vue'import SizeControls from '@/components/properties/layout/size/SizeControls.vue'import TextResizingControl from '@/components/properties/layout/TextResizingControl.vue'@@ -12,15 +13,13 @@ import IconButton from '@/components/ui/button/IconButton.vue'import PanelSection from '@/components/ui/panel/PanelSection.vue'const { panels } = useI18n()--const CONTAINER_TYPES = ['FRAME', 'COMPONENT', 'COMPONENT_SET', 'INSTANCE']</script><template><LayoutControlsRoot v-slot="ctx"><template v-if="ctx.node"><PanelSection :label="ctx.node.layoutMode === 'NONE' ? panels.layout : panels.autoLayout">- <template v-if="CONTAINER_TYPES.includes(ctx.node.type)" #actions>+ <template v-if="LAYOUT_CONTAINER_TYPES.has(ctx.node.type)" #actions><IconButton:label="ctx.node.layoutMode === 'NONE' ? panels.addAutoLayout : panels.removeAutoLayout"size="xs"@@ -37,17 +36,21 @@ const CONTAINER_TYPES = ['FRAME', 'COMPONENT', 'COMPONENT_SET', 'INSTANCE']</IconButton></template>- <LayoutFlowControl v-if="CONTAINER_TYPES.includes(ctx.node.type)" />+ <LayoutFlowControl v-if="LAYOUT_CONTAINER_TYPES.has(ctx.node.type)">+ <LayoutWrapToggle v-if="ctx.isFlex" />+ </LayoutFlowControl><div v-if="ctx.node.type !== 'TEXT'" class="mt-2 mb-1 text-[11px] text-muted">{{ panels.dimensions }}</div><TextResizingControl v-if="ctx.node.type === 'TEXT'" /><SizeControls /><ClipContentControl- v-if="CONTAINER_TYPES.includes(ctx.node.type) && ctx.node.layoutMode === 'NONE'"+ v-if="LAYOUT_CONTAINER_TYPES.has(ctx.node.type) && ctx.node.layoutMode === 'NONE'"/>- <template v-if="CONTAINER_TYPES.includes(ctx.node.type) && ctx.node.layoutMode !== 'NONE'">+ <template+ v-if="LAYOUT_CONTAINER_TYPES.has(ctx.node.type) && ctx.node.layoutMode !== 'NONE'"+ ><FlexControls v-if="ctx.isFlex" /><template v-if="ctx.isGrid"><GridControls />diff --git a/src/components/properties/layout/LayoutWrapToggle.vue b/src/components/properties/layout/LayoutWrapToggle.vuenew file mode 100644index 000000000..97b34ceee--- /dev/null+++ b/src/components/properties/layout/LayoutWrapToggle.vue@@ -0,0 +1,33 @@+<script setup lang="ts">+import { useI18n, useLayoutControlsContext } from '@open-pencil/vue'++import IconButton from '@/components/ui/button/IconButton.vue'++const ctx = useLayoutControlsContext()+const { panels } = useI18n()++function toggleWrap() {+ const node = ctx.node+ const enabling = node.layoutWrap !== 'WRAP'+ ctx.editor.updateNodeWithUndo(+ node.id,+ {+ layoutWrap: enabling ? 'WRAP' : 'NO_WRAP',+ primaryAxisAlign:+ enabling && node.primaryAxisAlign === 'SPACE_BETWEEN' ? 'MIN' : node.primaryAxisAlign+ },+ 'Toggle layout wrap'+ )+}+</script>++<template>+ <IconButton+ :label="panels.layoutWrap"+ size="xs"+ :active="ctx.node.layoutWrap === 'WRAP'"+ @click="toggleWrap"+ >+ <icon-lucide-wrap-text class="size-3.5" />+ </IconButton>+</template>diff --git a/src/components/properties/layout/TextResizingControl.vue b/src/components/properties/layout/TextResizingControl.vueindex fd4ab6ee8..b84f29ced 100644--- a/src/components/properties/layout/TextResizingControl.vue+++ b/src/components/properties/layout/TextResizingControl.vue@@ -1,42 +1,26 @@<script setup lang="ts">import { computed } from 'vue'-import type { SceneNode } from '@open-pencil/scene-graph'-import { useI18n, useLayoutControlsContext } from '@open-pencil/vue'+import { MIXED, useI18n, useSelectionLayout, type TextResizeMode } from '@open-pencil/vue'import Tip from '@/components/ui/overlay/Tip.vue'import PanelFieldGroup from '@/components/ui/panel/PanelFieldGroup.vue'import SegmentedControl from '@/components/ui/select/SegmentedControl.vue'-type TextResizeMode = 'AUTO_WIDTH' | 'AUTO_HEIGHT' | 'FIXED'--const ctx = useLayoutControlsContext()+const layout = useSelectionLayout()const { panels } = useI18n()-function modeFor(node: SceneNode | null): TextResizeMode {- if (node?.textAutoResize === 'WIDTH_AND_HEIGHT') return 'AUTO_WIDTH'- if (node?.textAutoResize === 'HEIGHT' || node?.textAutoResize === 'TRUNCATE') return 'AUTO_HEIGHT'- return 'FIXED'-}--const mode = computed<TextResizeMode>(() => modeFor(ctx.node))+// Texts resizing differently leave every option off.+const mode = computed(() => {+ const value = layout.textResize.value+ return value === MIXED || value === undefined ? '' : value+})const options = computed(() => [{ value: 'AUTO_WIDTH' as const, label: panels.value.resizeAutoWidth },{ value: 'AUTO_HEIGHT' as const, label: panels.value.resizeAutoHeight },{ value: 'FIXED' as const, label: panels.value.resizeFixed }])--function setMode(value: TextResizeMode) {- const node = ctx.node- if (!node) return- const byMode: Record<TextResizeMode, SceneNode['textAutoResize']> = {- AUTO_WIDTH: 'WIDTH_AND_HEIGHT',- AUTO_HEIGHT: 'HEIGHT',- FIXED: 'NONE'- }- ctx.editor.updateNodeWithUndo(node.id, { textAutoResize: byMode[value] }, 'Set text resizing')-}</script><template>@@ -45,7 +29,7 @@ function setMode(value: TextResizeMode) {:model-value="mode":options="options":label="panels.resizing"- @change="setMode($event as TextResizeMode)"+ @change="layout.setTextResize($event as TextResizeMode)"><template #option="{ option }"><Tip :label="option.label">diff --git a/src/components/properties/selection/SelectionColorsSection.vue b/src/components/properties/selection/SelectionColorsSection.vuenew file mode 100644index 000000000..e797a850b--- /dev/null+++ b/src/components/properties/selection/SelectionColorsSection.vue@@ -0,0 +1,70 @@+<script setup lang="ts">+import type { Color, Fill } from '@open-pencil/scene-graph'+import { useI18n, useSelectionColors } from '@open-pencil/vue'++import ColorPicker from '@/components/ColorPicker/ColorPicker.vue'+import PaintField from '@/components/inputs/PaintField.vue'+import PaintValue from '@/components/properties/paint/PaintValue.vue'+import FillSwatch from '@/components/ui/paint/FillSwatch.vue'+import PanelSection from '@/components/ui/panel/PanelSection.vue'++/** Figma's Selection colors: each colour in the selection, recoloured everywhere it is used. */+const selection = useSelectionColors()+const { panels } = useI18n()++function swatch(color: Color, opacity: number): Fill {+ return { type: 'SOLID', color, opacity, visible: true }+}++function onPickerOpenChange(open: boolean) {+ if (open) selection.begin()+ else selection.finish()+}+</script>++<template>+ <PanelSection+ v-if="selection.shown.value"+ :label="panels.selectionColors"+ data-test-id="selection-colors"+ >+ <div class="flex flex-col gap-1.5">+ <PaintField+ v-for="(entry, index) in selection.colors.value"+ :key="index"+ :opacity="entry.opacity"+ :opacity-label="panels.opacity"+ @update:opacity="selection.replace(index, { color: entry.color, opacity: $event })"+ >+ <template #preview>+ <ColorPicker+ :color="entry.color"+ @update="+ selection.replace(index, { color: { ...$event, a: 1 }, opacity: entry.opacity })+ "+ @open-change="onPickerOpenChange"+ >+ <template #trigger>+ <button+ type="button"+ :aria-label="panels.selectionColors"+ class="size-5 shrink-0 cursor-pointer rounded border-0 bg-transparent p-0"+ >+ <FillSwatch :fill="swatch(entry.color, entry.opacity)" class="size-full" />+ </button>+ </template>+ </ColorPicker>+ </template>+ <template #value>+ <PaintValue+ :color="entry.color"+ :label="panels.selectionColors"+ @update="+ selection.replace(index, { color: { ...$event, a: 1 }, opacity: entry.opacity })+ "+ />+ </template>+ </PaintField>+ </div>+ </PanelSection>+</template>diff --git a/src/components/properties/selection/SelectionLayoutSection.vue b/src/components/properties/selection/SelectionLayoutSection.vuenew file mode 100644index 000000000..e033916b8--- /dev/null+++ b/src/components/properties/selection/SelectionLayoutSection.vue@@ -0,0 +1,100 @@+<script setup lang="ts">+import {+ PositionControlsRoot,+ useEditorCommands,+ useI18n,+ useSelectionLayout+} from '@open-pencil/vue'++import NumberField from '@/components/inputs/NumberField.vue'+import ClipContentControl from '@/components/properties/layout/ClipContentControl.vue'+import LayoutFlowControl from '@/components/properties/layout/LayoutFlowControl.vue'+import TextResizingControl from '@/components/properties/layout/TextResizingControl.vue'+import IconButton from '@/components/ui/button/IconButton.vue'+import Tip from '@/components/ui/overlay/Tip.vue'+import PanelGrid from '@/components/ui/panel/PanelGrid.vue'+import PanelSection from '@/components/ui/panel/PanelSection.vue'++/**+ * Layout of several selected layers, as in Figma: flow when all can hold an auto layout, resizing+ * for the text among them, their sizes, the spacing of a row or column, and clip content for+ * those that can clip.+ */+const layout = useSelectionLayout()+const { getCommand } = useEditorCommands()+const wrapInAutoLayout = getCommand('selection.wrapInAutoLayout')+const { panels } = useI18n()+</script>++<template>+ <PanelSection :label="panels.layout" data-test-id="selection-layout">+ <template #actions>+ <IconButton+ :label="wrapInAutoLayout.label"+ size="xs"+ :disabled="!wrapInAutoLayout.enabled.value"+ @click="wrapInAutoLayout.run()"+ >+ <icon-lucide-layout-panel-top class="size-3.5" />+ </IconButton>+ </template>++ <LayoutFlowControl v-if="layout.layoutMode.value !== undefined" class="mb-2" />+ <TextResizingControl v-if="layout.textResize.value !== undefined" />+ <div class="mt-2 mb-1 text-[11px] text-muted">{{ panels.dimensions }}</div>++ <PositionControlsRoot v-slot="{ wValue, hValue, actions }">+ <PanelGrid :columns="2">+ <Tip :label="panels.width">+ <NumberField+ icon="W"+ data-property="width"+ :aria-label="panels.width"+ :model-value="wValue"+ :min="1"+ @update:model-value="actions.updateProp('width', $event)"+ @commit="(v: number, p: number) => actions.commitProp('width', v, p)"+ @cancel="actions.cancelProp('width')"+ />+ </Tip>+ <Tip :label="panels.height">+ <NumberField+ icon="H"+ data-property="height"+ :aria-label="panels.height"+ :model-value="hValue"+ :min="1"+ @update:model-value="actions.updateProp('height', $event)"+ @commit="(v: number, p: number) => actions.commitProp('height', v, p)"+ @cancel="actions.cancelProp('height')"+ />+ </Tip>+ </PanelGrid>+ </PositionControlsRoot>++ <template v-if="layout.spacingAxis.value">+ <div class="mt-2 mb-1 text-[11px] text-muted">{{ panels.spacing }}</div>+ <PanelGrid :columns="2">+ <Tip :label="panels.spacing">+ <NumberField+ data-property="selection-spacing"+ :aria-label="panels.spacing"+ :model-value="layout.spacing.value"+ @update:model-value="layout.setSpacing($event)"+ @commit="layout.flushSpacing()"+ >+ <template #icon>+ <icon-lucide-move-horizontal+ v-if="layout.spacingAxis.value === 'horizontal'"+ class="size-3"+ />+ <icon-lucide-move-vertical v-else class="size-3" />+ </template>+ </NumberField>+ </Tip>+ </PanelGrid>+ </template>++ <ClipContentControl v-if="layout.clipsContent.value !== undefined" />+ </PanelSection>+</template>diff --git a/src/components/properties/stroke/StrokeSection.vue b/src/components/properties/stroke/StrokeSection.vueindex 437cfa5a2..0ece12144 100644--- a/src/components/properties/stroke/StrokeSection.vue+++ b/src/components/properties/stroke/StrokeSection.vue@@ -1,5 +1,5 @@<script setup lang="ts">-import { ref } from 'vue'+import { computed, ref } from 'vue'import type { Color, Fill, SceneNode, Stroke } from '@open-pencil/scene-graph'import { colorToHexRaw } from '@open-pencil/scene-graph/color'@@ -7,8 +7,10 @@ import {applySolidStrokeColor,applyStrokePaint,BindableValueRoot,+ MIXED,useColorBindingProvider,useI18n,+ useNodeProps,useOkHCL,useStrokeControls} from '@open-pencil/vue'@@ -46,6 +48,12 @@ import StrokeSettingsPopover from './StrokeSettingsPopover.vue'const strokeCtx = useStrokeControls()const { advancedActive } = strokeCtx+const { nodes: selectedNodes } = useNodeProps()+/** Empty when the layers align their strokes differently, so the field reads Mixed. */+const alignValue = computed(() => {+ const align = strokeCtx.currentAlign()+ return align === MIXED ? '' : align+})const colorProvider = useColorBindingProvider()const okhcl = useOkHCL()const gradients = useGradientEditing()@@ -89,22 +97,12 @@ function updateStrokeColor(if (commit) commitPaintMutation(binding)}-function onToggleSides(activeNode: SceneNode | null) {- if (!activeNode) return+/** Opening the sides gives every layer its own weight per side; closing strokes all sides again. */+function onToggleSides(nodes: readonly SceneNode[]) {const next = !expandedSides.valueexpandedSides.value = next- if (next && !activeNode.independentStrokeWeights) {- const weight = activeNode.strokes[0]?.weight ?? 1- strokeCtx.selectSide('CUSTOM', {- ...activeNode,- borderTopWeight: weight,- borderRightWeight: weight,- borderBottomWeight: weight,- borderLeftWeight: weight- })- } else if (!next && activeNode.independentStrokeWeights) {- strokeCtx.selectSide('ALL', activeNode)- }+ if (next && nodes.some((node) => !node.independentStrokeWeights)) strokeCtx.selectSide('CUSTOM')+ else if (!next && nodes.some((node) => node.independentStrokeWeights)) strokeCtx.selectSide('ALL')}</script>@@ -228,10 +226,11 @@ function onToggleSides(activeNode: SceneNode | null) {<AppSelect:label="panels.strokeType":ui="{ trigger: 'w-[88px] flex-none' }"- :model-value="strokeCtx.currentAlign(activeNode)"+ :model-value="alignValue"+ :placeholder="panels.mixed":options="strokeCtx.alignOptions"data-property="stroke-align"- @update:model-value="strokeCtx.updateAlign($event as Stroke['align'], activeNode)"+ @update:model-value="strokeCtx.updateAlign($event as Stroke['align'])"/><Tip :label="panels.strokeWeight"><NumberField@@ -255,7 +254,7 @@ function onToggleSides(activeNode: SceneNode | null) {class="size-[26px] shrink-0":active="expandedSides"data-property="stroke-sides"- @click="onToggleSides(activeNode)"+ @click="onToggleSides(selectedNodes)"><icon-lucide-layout-grid class="size-3.5" /></IconButton>@@ -271,10 +270,10 @@ function onToggleSides(activeNode: SceneNode | null) {v-for="side in strokeCtx.borderSides":key="side":label="side[0].toUpperCase()"- :model-value="strokeCtx.borderWeight(activeNode, side)"+ :model-value="strokeCtx.borderWeight(side)":min="0":data-property="`stroke-${side}-weight`"- @update:model-value="strokeCtx.updateBorderWeight(side, $event, activeNode)"+ @update:model-value="strokeCtx.updateBorderWeight(side, $event)"/></div></PanelSection>diff --git a/src/components/properties/typography/LineHeightField.vue b/src/components/properties/typography/LineHeightField.vueindex e9f3a0573..b8c375666 100644--- a/src/components/properties/typography/LineHeightField.vue+++ b/src/components/properties/typography/LineHeightField.vue@@ -11,27 +11,41 @@ import {import { computed } from 'vue'import type { SceneNode } from '@open-pencil/scene-graph'-import { useEditor, useI18n, useRetainedPopup } from '@open-pencil/vue'+import { MIXED, useEditor, useI18n, useRetainedPopup } from '@open-pencil/vue'import VariableNumberField from '@/components/properties/VariableNumberField.vue'import { useSelectUI } from '@/components/ui/select/select'-const { node } = defineProps<{ node: SceneNode }>()+/** Every selected text layer; the field reads Mixed when their line heights differ. */+const { nodes } = defineProps<{ nodes: readonly SceneNode[] }>()const emit = defineEmits<{ update: [value: number]; commit: [value: number, previous: number] }>()const editor = useEditor()const { open: popupOpen, portalActive } = useRetainedPopup()const { panels } = useI18n()-const automatic = computed(() => node.lineHeight == null && !node.boundVariables.lineHeight)-const value = computed(() => node.lineHeight ?? Math.round((node.fontSize || 14) * 1.2))+const isAutomatic = (node: SceneNode) => node.lineHeight == null && !node.boundVariables.lineHeight+const fixedValue = (node: SceneNode) => node.lineHeight ?? Math.round((node.fontSize || 14) * 1.2)+const automatic = computed(() => nodes.length > 0 && nodes.every(isAutomatic))+const value = computed(() => {+ const values = nodes.map(fixedValue)+ const [first = 0] = values+ return values.every((current) => current === first) ? first : MIXED+})+const nodeId = computed(() => nodes.at(0)?.id ?? '')+const nodeIds = computed(() => nodes.map((node) => node.id))const menu = useSelectUI()function setMode(mode: string) {if (mode === 'AUTO') {editor.undo.runBatch('Use automatic line height', () => {- if (node.boundVariables.lineHeight) editor.unbindVariable(node.id, 'lineHeight')- editor.updateNodeWithUndo(node.id, { lineHeight: null }, 'Use automatic line height')+ for (const node of nodes) {+ if (node.boundVariables.lineHeight) editor.unbindVariable(node.id, 'lineHeight')+ editor.updateNodeWithUndo(node.id, { lineHeight: null }, 'Use automatic line height')+ }+ })+ } else if (mode === 'FIXED') {+ editor.undo.runBatch('Set line height', () => {+ for (const node of nodes.filter(isAutomatic))+ editor.updateNodeWithUndo(node.id, { lineHeight: fixedValue(node) }, 'Set line height')})- } else if (mode === 'FIXED' && automatic.value) {- editor.updateNodeWithUndo(node.id, { lineHeight: value.value }, 'Set line height')}}</script>@@ -42,7 +56,8 @@ function setMode(mode: string) {:aria-label="panels.lineHeight"suffix="px":min="0"- :node-id="node.id"+ :node-id="nodeId"+ :node-ids="nodeIds"binding-path="lineHeight"@update:model-value="emit('update', $event)"@commit="(current, previous) => emit('commit', current, previous)"diff --git a/tests/e2e/design/panel.spec.ts b/tests/e2e/design/panel.spec.tsindex 7e4950edd..f43375343 100644--- a/tests/e2e/design/panel.spec.ts+++ b/tests/e2e/design/panel.spec.ts@@ -438,7 +438,7 @@ test('multi-select shows mixed header and boolean operations', async () => {const multiHeader = editor.page.getByTestId('design-panel-multi')- .getByRole('heading', { name: /layers/ })+ .getByRole('heading', { name: /selected/ })await expect(multiHeader).toBeVisible()const booleanOperations = editor.page.getByTestId('boolean-operations-trigger')diff --git a/tests/e2e/panels/visual.spec.ts-snapshots/instance-openpencil-darwin.png b/tests/e2e/panels/visual.spec.ts-snapshots/instance-openpencil-darwin.pngindex 9434fdc83..a5390a775 100644Binary files a/tests/e2e/panels/visual.spec.ts-snapshots/instance-openpencil-darwin.png and b/tests/e2e/panels/visual.spec.ts-snapshots/instance-openpencil-darwin.png differdiff --git a/tests/e2e/panels/visual.spec.ts-snapshots/mixed-selection-openpencil-darwin.png b/tests/e2e/panels/visual.spec.ts-snapshots/mixed-selection-openpencil-darwin.pngindex 6f46d6c78..79e7a7cc7 100644Binary files a/tests/e2e/panels/visual.spec.ts-snapshots/mixed-selection-openpencil-darwin.png and b/tests/e2e/panels/visual.spec.ts-snapshots/mixed-selection-openpencil-darwin.png differdiff --git a/tests/e2e/properties/mixed-selection.spec.ts b/tests/e2e/properties/mixed-selection.spec.tsnew file mode 100644index 000000000..56420117e--- /dev/null+++ b/tests/e2e/properties/mixed-selection.spec.ts@@ -0,0 +1,94 @@+import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'+import { mixedSelectionDriver } from '#tests/helpers/canvas/mixed-selection-driver'+import { propertyField, propertySection } from '#tests/helpers/properties'++// Figma desktop 126, probed with the same layers: a multi-selection shows layout, typography for+// its text, strokes of the layers that have them, selection colors, and the spacing of a row.++const editor = useEditorSetupWithClear('/?test&no-rulers')+const scene = mixedSelectionDriver(() => editor.page)++async function select(...layers: Parameters<typeof scene.select>) {+ await scene.build()+ await scene.select(...layers)+ await editor.canvas.waitForRender()+}++async function typeInto(property: string, name: string, value: string) {+ await propertyField(editor.page, property).click()+ const input = propertyField(editor.page, property).getByRole('spinbutton', { name })+ await input.fill(value)+ await input.press('Enter')+}++test('font size edits every selected text in one undo step and leaves the rest alone', async () => {+ await select('textA', 'textB', 'rectA')+ const typography = propertySection(editor.page, 'Typography')+ await expect(typography).toBeVisible()+ await expect(propertyField(editor.page, 'fontSize')).toHaveAttribute('data-mixed')++ await typeInto('fontSize', 'Font size', '20')+ expect(await scene.read('fontSize', 'textA', 'textB')).toEqual([20, 20])++ await scene.undo()+ expect(await scene.read('fontSize', 'textA', 'textB')).toEqual([16, 24])+})++test('text resizing applies to the text among other layers', async () => {+ await select('textA', 'textB', 'rectA')+ await propertySection(editor.page, 'Layout').getByRole('button', { name: 'Fixed size' }).click()+ expect(await scene.read('textAutoResize', 'textA', 'textB')).toEqual(['NONE', 'NONE'])+})++test('flow reads mixed for frames with different layouts and sets them all', async () => {+ await select('frame', 'auto')+ const layout = propertySection(editor.page, 'Layout')+ const vertical = layout.getByRole('button', { name: 'Vertical layout' })+ await expect(vertical).toHaveAttribute('aria-pressed', 'false')+ await vertical.click()+ expect(await scene.read('layoutMode', 'frame', 'auto')).toEqual(['VERTICAL', 'VERTICAL'])+})++test('a stroke on some layers shows as theirs and an edit strokes them all', async () => {+ await select('rectA', 'ellipse')+ await expect(+ propertySection(editor.page, 'Stroke').getByText('Click + to replace mixed strokes')+ ).toBeHidden()++ await typeInto('stroke-weight', 'W', '3')+ const strokes = await scene.read('strokes', 'rectA', 'ellipse')+ expect(strokes.map((list) => (list as Array<{ weight: number }>)[0]?.weight)).toEqual([3, 3])+})++test('spacing reads the gaps of a row and spaces it from its first layer', async () => {+ await select('rectA', 'rectB')+ await expect(propertyField(editor.page, 'selection-spacing')).toHaveAttribute(+ 'aria-valuenow',+ '40'+ )++ await typeInto('selection-spacing', 'Spacing', '10')+ expect(await scene.read('x', 'rectA', 'rectB')).toEqual([0, 110])+})++test('selection colors recolour every paint that uses a colour', async () => {+ await select('rectA', 'ellipse')+ const colors = editor.page.getByTestId('selection-colors')+ await expect(colors.getByRole('textbox', { name: 'Selection colors' })).toHaveCount(3)++ const black = colors.getByRole('textbox', { name: 'Selection colors' }).first()+ await expect(black).toHaveValue('000000')+ await black.fill('00FF00')+ await black.press('Enter')+ const strokes = await scene.read('strokes', 'rectA')+ expect((strokes[0] as Array<{ color: { g: number } }>)[0]?.color.g).toBe(1)+})++test('stroke position edits every selected layer', async () => {+ await select('rectA', 'textA')+ const position = propertyField(editor.page, 'stroke-align')+ await expect(position).toContainText('Mixed')+ await position.click()+ await editor.page.getByRole('option', { name: 'Center' }).click()+ expect(await scene.read('strokeAlign', 'rectA', 'textA')).toEqual(['CENTER', 'CENTER'])+})diff --git a/tests/e2e/properties/panel.spec.ts b/tests/e2e/properties/panel.spec.tsindex 665fa3039..6d6f464d1 100644--- a/tests/e2e/properties/panel.spec.ts+++ b/tests/e2e/properties/panel.spec.ts@@ -49,6 +49,8 @@ test('appearance fields share control height and show variable actions', async (const triggerBox = expectDefined(await applyVariable.boundingBox(), 'variable trigger bounds')const pickerBox = expectDefined(await picker.boundingBox(), 'variable picker bounds')expect(pickerBox.x + pickerBox.width).toBeLessThanOrEqual(triggerBox.x)+ // Escape closes the picker once it holds focus, as it does for a person.+ await expect(picker.getByRole('textbox', { name: 'Search…' })).toBeFocused()await editor.page.keyboard.press('Escape')await expect(picker).toBeHidden()@@ -60,6 +62,7 @@ test('appearance fields share control height and show variable actions', async (try {await applyVariable.click()await expect(picker).toBeVisible()+ await expect(picker.getByRole('textbox', { name: 'Search…' })).toBeFocused()const shifted = expectDefined(await picker.boundingBox(), 'shifted picker bounds')expect(shifted.y).toBeGreaterThanOrEqual(0)expect(shifted.y + shifted.height).toBeLessThanOrEqual(height)diff --git a/tests/engine/vue/controls/typography-depth.test.ts b/tests/engine/vue/controls/typography-depth.test.tsindex b40f4214c..bf1079b53 100644--- a/tests/engine/vue/controls/typography-depth.test.ts+++ b/tests/engine/vue/controls/typography-depth.test.ts@@ -13,11 +13,12 @@ describe('typography depth actions', () => {maxLines: null,textStyleId: '1:20'})- const node = computed(() => editor.graph.getNode(text.id) ?? null)+ const nodes = computed(() =>+ [editor.graph.getNode(text.id)].filter((node) => node !== undefined)+ )const actions = createTypographyActions({editor,- node,- currentWeightLabel: computed(() => 'Regular'),+ nodes,activeFormatting: computed(() => []),options: {}})@@ -38,8 +39,7 @@ describe('typography depth actions', () => {})const actions = createTypographyActions({editor,- node: computed(() => editor.graph.getNode(text.id) ?? null),- currentWeightLabel: computed(() => 'Regular'),+ nodes: computed(() => [editor.graph.getNode(text.id)].filter((node) => node !== undefined)),activeFormatting: computed(() => []),options: {}})@@ -58,4 +58,33 @@ describe('typography depth actions', () => {textStyleId: '1:21'})})++ // Figma desktop 126 edits every selected text when several are selected.+ test('changes every text layer in one undo step', () => {+ const editor = createEditor()+ const pageId = editor.state.currentPageId+ const first = editor.graph.createNode('TEXT', pageId, { textCase: 'ORIGINAL' })+ const second = editor.graph.createNode('TEXT', pageId, { textCase: 'LOWER' })+ const actions = createTypographyActions({+ editor,+ nodes: computed(() =>+ [first.id, second.id]+ .map((id) => editor.graph.getNode(id))+ .filter((node) => node !== undefined)+ ),+ activeFormatting: computed(() => []),+ options: {}+ })++ actions.setTextCase('UPPER')+ expect([first.id, second.id].map((id) => editor.graph.getNode(id)?.textCase)).toEqual([+ 'UPPER',+ 'UPPER'+ ])+ editor.undo.undo()+ expect([first.id, second.id].map((id) => editor.graph.getNode(id)?.textCase)).toEqual([+ 'ORIGINAL',+ 'LOWER'+ ])+ })})diff --git a/tests/helpers/canvas/mixed-selection-driver.ts b/tests/helpers/canvas/mixed-selection-driver.tsnew file mode 100644index 000000000..11ce2f68d--- /dev/null+++ b/tests/helpers/canvas/mixed-selection-driver.ts@@ -0,0 +1,54 @@+import type { Page } from '@playwright/test'++import type * as MixedScene from '#tests/helpers/canvas/mixed-selection'++type SceneIds = ReturnType<typeof MixedScene.createMixedSelectionScene>+export type MixedLayer = keyof SceneIds++/** Builds the mixed-selection scene, selects parts of it, and reads layers back. */+export function mixedSelectionDriver(page: () => Page) {+ let ids: SceneIds | undefined++ function idsOf(layers: readonly MixedLayer[]) {+ if (!ids) throw new Error('Build the scene first')+ const scene = ids+ return layers.map((layer) => scene[layer])+ }++ return {+ async build() {+ ids = await page().evaluate(async () => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ const fixtureURL = '/tests/helpers/canvas/mixed-selection.ts'+ const scene: typeof MixedScene = await import(fixtureURL)+ const built = scene.createMixedSelectionScene(store.graph, store.state.currentPageId)+ store.requestRender()+ return built+ })+ },++ select(...layers: MixedLayer[]) {+ return page().evaluate(+ (select) => window.openPencil?.getStore?.().select(select),+ idsOf(layers)+ )+ },++ /** One field of each layer, in the order asked. */+ read<K extends string>(key: K, ...layers: MixedLayer[]) {+ return page().evaluate(+ ({ key, select }) =>+ select.map((id) => {+ const node = window.openPencil?.getStore?.().graph.getNode(id)+ return node ? structuredClone(node[key as keyof typeof node] ?? null) : null+ }) as unknown[],+ { key, select: idsOf(layers) }+ )+ },++ undo() {+ return page().evaluate(() => window.openPencil?.getStore?.().undoAction())+ }+ }+}diff --git a/tests/helpers/canvas/mixed-selection.ts b/tests/helpers/canvas/mixed-selection.tsnew file mode 100644index 000000000..538e0c5b9--- /dev/null+++ b/tests/helpers/canvas/mixed-selection.ts@@ -0,0 +1,112 @@+import type { Color, Fill, SceneGraph } from '@open-pencil/scene-graph'++const RED = { r: 1, g: 0.3, b: 0.2, a: 1 }+const BLUE = { r: 0.2, g: 0.4, b: 1, a: 1 }+const BLACK = { r: 0, g: 0, b: 0, a: 1 }++function solid(color: Color): Fill {+ return { type: 'SOLID', color, opacity: 1, visible: true }+}++/**+ * The layers Figma desktop 126 was probed with: a frame, an auto layout frame with a child, two+ * rectangles that differ in size, radius, opacity, stroke, and effects, an ellipse, and two texts.+ */+export function createMixedSelectionScene(graph: SceneGraph, pageId: string) {+ const frame = graph.createNode('FRAME', pageId, {+ name: 'Mix Frame',+ x: 0,+ y: 0,+ width: 200,+ height: 120,+ cornerRadius: 8,+ fills: [solid({ r: 1, g: 1, b: 1, a: 1 })]+ })+ const auto = graph.createNode('FRAME', pageId, {+ name: 'Mix Auto',+ x: 260,+ y: 0,+ width: 72,+ height: 100,+ layoutMode: 'HORIZONTAL',+ itemSpacing: 12,+ paddingLeft: 16,+ paddingRight: 16,+ paddingTop: 8,+ paddingBottom: 8,+ fills: [solid({ r: 0.9, g: 0.95, b: 1, a: 1 })]+ })+ graph.createNode('RECTANGLE', auto.id, {+ name: 'Rectangle',+ width: 40,+ height: 40,+ fills: [solid({ r: 0.85, g: 0.85, b: 0.85, a: 1 })]+ })+ const rectA = graph.createNode('RECTANGLE', pageId, {+ name: 'Mix Rect A',+ x: 0,+ y: 180,+ width: 100,+ height: 80,+ cornerRadius: 4,+ opacity: 0.5,+ fills: [solid(RED)],+ strokes: [{ ...solid(BLACK), weight: 2, align: 'INSIDE' }]+ })+ const rectB = graph.createNode('RECTANGLE', pageId, {+ name: 'Mix Rect B',+ x: 140,+ y: 180,+ width: 120,+ height: 80,+ cornerRadius: 12,+ fills: [solid(RED)],+ effects: [+ {+ type: 'DROP_SHADOW',+ color: { r: 0, g: 0, b: 0, a: 0.25 },+ offset: { x: 0, y: 4 },+ radius: 8,+ spread: 0,+ visible: true,+ blendMode: 'NORMAL'+ }+ ]+ })+ const ellipse = graph.createNode('ELLIPSE', pageId, {+ name: 'Mix Ellipse',+ x: 300,+ y: 180,+ width: 80,+ height: 80,+ fills: [solid(BLUE)]+ })+ const textA = graph.createNode('TEXT', pageId, {+ name: 'Mix Text A',+ x: 0,+ y: 300,+ text: 'Hello',+ fontSize: 16,+ textAutoResize: 'WIDTH_AND_HEIGHT',+ fills: [solid(BLACK)]+ })+ const textB = graph.createNode('TEXT', pageId, {+ name: 'Mix Text B',+ x: 140,+ y: 300,+ text: 'World',+ fontSize: 24,+ fontWeight: 700,+ textAutoResize: 'WIDTH_AND_HEIGHT',+ fills: [solid(BLACK)]+ })+ return {+ frame: frame.id,+ auto: auto.id,+ rectA: rectA.id,+ rectB: rectB.id,+ ellipse: ellipse.id,+ textA: textA.id,+ textB: textB.id+ }+}