Skip to content

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

chore: code formatting

Santos Alarcón091271b05fb0
diff --git a/packages/cli/src/commands/export.ts b/packages/cli/src/commands/export.ts
index fa4942fd2..f3eb47ee2 100644
--- a/packages/cli/src/commands/export.ts
+++ b/packages/cli/src/commands/export.ts
@@ -119,7 +119,9 @@ async function exportFromFile(format: string, args: ExportArgs) {
}
const formatId = format.toLowerCase()
- let options: { format?: string; scale?: number; quality?: number; renderThumbnail?: boolean } | undefined
+ let options:
+ | { format?: string; scale?: number; quality?: number; renderThumbnail?: boolean }
+ | undefined
if (format === 'JSX') {
options = { format: args.style }
} else if (format === 'FIG') {
diff --git a/packages/core/src/canvas/fills.ts b/packages/core/src/canvas/fills.ts
index 9eb2d0647..41ba4deba 100644
--- a/packages/core/src/canvas/fills.ts
+++ b/packages/core/src/canvas/fills.ts
@@ -110,7 +110,10 @@ export function linearGradientEndpoints(
transform: NonNullable<Fill['gradientTransform']>
) {
return {
- start: { x: (transform.m00 + transform.m02) * width, y: (transform.m10 + transform.m12) * height },
+ start: {
+ x: (transform.m00 + transform.m02) * width,
+ y: (transform.m10 + transform.m12) * height
+ },
end: { x: transform.m02 * width, y: transform.m12 * height }
}
}
diff --git a/packages/core/src/canvas/labels/selection.ts b/packages/core/src/canvas/labels/selection.ts
index 76b27f6ef..0de992a5c 100644
--- a/packages/core/src/canvas/labels/selection.ts
+++ b/packages/core/src/canvas/labels/selection.ts
@@ -1,6 +1,7 @@
import type { Canvas } from 'canvaskit-wasm'
import { getAbsolutePosition, getWorldMatrix } from '#core/canvas/coordinate'
+import type { SkiaRenderer, RenderOverlays } from '#core/canvas/renderer'
import {
LABEL_OFFSET_Y,
SIZE_PILL_PADDING_X,
@@ -12,8 +13,6 @@ import {
import { rotatedCorners } from '#core/geometry'
import type { SceneNode, SceneGraph } from '#core/scene-graph'
-import type { SkiaRenderer, RenderOverlays } from '#core/canvas/renderer'
-
import { ellipsizeLabelText } from './text'
function getOverlayRotation(node: SceneNode, overlays?: RenderOverlays): number {
diff --git a/packages/core/src/canvas/overlays/ai.ts b/packages/core/src/canvas/overlays/ai.ts
index 106c6754e..beb2d8826 100644
--- a/packages/core/src/canvas/overlays/ai.ts
+++ b/packages/core/src/canvas/overlays/ai.ts
@@ -1,5 +1,7 @@
import type { Canvas } from 'canvaskit-wasm'
+import { drawNodeHighlightRect } from '#core/canvas/highlight-rect'
+import type { SkiaRenderer } from '#core/canvas/renderer'
import {
AI_ACTIVE_COLOR,
AI_DONE_COLOR,
@@ -8,9 +10,6 @@ import {
} from '#core/constants'
import type { SceneGraph } from '#core/scene-graph'
-import { drawNodeHighlightRect } from '#core/canvas/highlight-rect'
-import type { SkiaRenderer } from '#core/canvas/renderer'
-
export function drawAiOverlays(r: SkiaRenderer, canvas: Canvas, graph: SceneGraph): void {
const now = performance.now()
diff --git a/packages/core/src/canvas/overlays/auto-layout-hover.ts b/packages/core/src/canvas/overlays/auto-layout-hover.ts
index 04fda6f86..74a982c58 100644
--- a/packages/core/src/canvas/overlays/auto-layout-hover.ts
+++ b/packages/core/src/canvas/overlays/auto-layout-hover.ts
@@ -70,7 +70,13 @@ function toScreenRect(r: SkiaRenderer, [x, y, width, height]: RectTuple) {
)
}
-function drawStripedRect(r: SkiaRenderer, canvas: Canvas, rectTuple: RectTuple, color: Color, fill: Color) {
+function drawStripedRect(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ rectTuple: RectTuple,
+ color: Color,
+ fill: Color
+) {
const [, , width, height] = rectTuple
if (width <= 0 || height <= 0) return
const rect = toScreenRect(r, rectTuple)
@@ -209,13 +215,7 @@ function drawSpacingHover(
) {
const rects = gapRects(node, graph)
for (const rect of rects) {
- drawStripedRect(
- r,
- canvas,
- rect,
- AUTO_LAYOUT_HOVER_MAGENTA,
- AUTO_LAYOUT_HOVER_MAGENTA_FILL
- )
+ drawStripedRect(r, canvas, rect, AUTO_LAYOUT_HOVER_MAGENTA, AUTO_LAYOUT_HOVER_MAGENTA_FILL)
}
if (!showValue || rects.length === 0) return
const [x, y, width, height] = rects[0]
diff --git a/packages/core/src/canvas/renderer/methods.ts b/packages/core/src/canvas/renderer/methods.ts
index 95decd9b0..5dc17eef5 100644
--- a/packages/core/src/canvas/renderer/methods.ts
+++ b/packages/core/src/canvas/renderer/methods.ts
@@ -1,12 +1,12 @@
import type { ImageFilter, MaskFilter, Canvas, Paint, Path } from 'canvaskit-wasm'
-import * as AiOverlays from '#core/canvas/overlays/ai'
import * as Effects from '#core/canvas/effects'
import * as Fills from '#core/canvas/fills'
import * as Labels from '#core/canvas/labels/draw'
import * as NodeEditOverlay from '#core/canvas/node-edit-overlay'
import type { NodeEditOverlayState } from '#core/canvas/node-edit-overlay'
import * as Overlays from '#core/canvas/overlays'
+import * as AiOverlays from '#core/canvas/overlays/ai'
import * as PenOverlay from '#core/canvas/pen-overlay'
import type { SkiaRenderer } from '#core/canvas/renderer'
import type { RenderOverlays } from '#core/canvas/renderer/types'
@@ -95,7 +95,11 @@ const rendererMethods: ThisType<SkiaRenderer> = {
Overlays.drawLayoutInsertIndicator(this, canvas, indicator)
},
- drawAutoLayoutHover(canvas: Canvas, graph: SceneGraph, hover?: RenderOverlays['autoLayoutHover']) {
+ drawAutoLayoutHover(
+ canvas: Canvas,
+ graph: SceneGraph,
+ hover?: RenderOverlays['autoLayoutHover']
+ ) {
Overlays.drawAutoLayoutHover(this, canvas, graph, hover)
},
diff --git a/packages/core/src/canvas/renderer/pipeline.ts b/packages/core/src/canvas/renderer/pipeline.ts
index 78d8ab867..2b7329884 100644
--- a/packages/core/src/canvas/renderer/pipeline.ts
+++ b/packages/core/src/canvas/renderer/pipeline.ts
@@ -176,7 +176,11 @@ export function render(
canvas.scale(r.dpr, r.dpr)
p.beginPhase('render:scene')
- if (layer === 'scene' && !hasVolatileOverlays && renderSceneBacking(r, canvas, graph, sceneVersion)) {
+ if (
+ layer === 'scene' &&
+ !hasVolatileOverlays &&
+ renderSceneBacking(r, canvas, graph, sceneVersion)
+ ) {
p.setScenePictureMode('hit', 'backing')
} else {
canvas.translate(r.panX, r.panY)
diff --git a/packages/core/src/canvas/renderer/retained-backing.ts b/packages/core/src/canvas/renderer/retained-backing.ts
index 3d25bfe82..d256d5579 100644
--- a/packages/core/src/canvas/renderer/retained-backing.ts
+++ b/packages/core/src/canvas/renderer/retained-backing.ts
@@ -45,10 +45,7 @@ export function updateSceneBackingPreviewState(r: SkiaRenderer, layer: RenderLay
if (layer !== 'scene') return
const previous = r.lastSceneViewport
const viewportChanged =
- !previous ||
- previous.panX !== r.panX ||
- previous.panY !== r.panY ||
- previous.zoom !== r.zoom
+ !previous || previous.panX !== r.panX || previous.panY !== r.panY || previous.zoom !== r.zoom
if (viewportChanged) {
const timestamp = now()
if (r.sceneBackingLastViewportEventAt > 0) {
@@ -85,7 +82,12 @@ function backingScreenCoverageContainsViewport(r: SkiaRenderer): boolean {
const scale = r.zoom / backing.zoom
const x = r.panX - backing.panX * scale
const y = r.panY - backing.panY * scale
- return x <= 0 && y <= 0 && x + backing.width * scale >= r.viewportWidth && y + backing.height * scale >= r.viewportHeight
+ return (
+ x <= 0 &&
+ y <= 0 &&
+ x + backing.width * scale >= r.viewportWidth &&
+ y + backing.height * scale >= r.viewportHeight
+ )
}
function backingWorldCoverageContainsLiveViewport(r: SkiaRenderer): boolean {
@@ -129,12 +131,7 @@ function drawSceneBacking(
const backing = r.sceneBacking
if (
!backing ||
- !backingCoverageContainsLiveViewport(
- r,
- sceneVersion,
- allowStaleZoom,
- positionPreviewVersion
- )
+ !backingCoverageContainsLiveViewport(r, sceneVersion, allowStaleZoom, positionPreviewVersion)
) {
return false
}
@@ -464,4 +461,3 @@ export function renderSceneBacking(
positionPreviewVersion
)
}
-
diff --git a/packages/core/src/canvas/text-derived.ts b/packages/core/src/canvas/text-derived.ts
index 825eedbd0..71ce05739 100644
--- a/packages/core/src/canvas/text-derived.ts
+++ b/packages/core/src/canvas/text-derived.ts
@@ -24,11 +24,7 @@ export function derivedUnderlineRect(node: Pick<SceneNode, 'width'>, baselineY:
}
}
-export function drawFigmaDerivedText(
- r: SkiaRenderer,
- canvas: Canvas,
- node: SceneNode
-): boolean {
+export function drawFigmaDerivedText(r: SkiaRenderer, canvas: Canvas, node: SceneNode): boolean {
if (!node.figmaDerivedTextGlyphs?.length) return false
let underlineBaselineY = 0
diff --git a/packages/core/src/canvas/text-outlines.ts b/packages/core/src/canvas/text-outlines.ts
index 2fb3182d4..fdac751e3 100644
--- a/packages/core/src/canvas/text-outlines.ts
+++ b/packages/core/src/canvas/text-outlines.ts
@@ -1,12 +1,17 @@
import type { Path } from 'canvaskit-wasm'
import type { SceneNode } from '#core/scene-graph'
-import { textNodeToOutlineLayout } from '#core/text/outlines'
import type { OutlineCommand } from '#core/text/opentype'
+import { textNodeToOutlineLayout } from '#core/text/outlines'
import type { SkiaRenderer } from './renderer'
-function appendOutlineCommand(path: Path, command: OutlineCommand, xOffset: number, yOffset: number): void {
+function appendOutlineCommand(
+ path: Path,
+ command: OutlineCommand,
+ xOffset: number,
+ yOffset: number
+): void {
switch (command.type) {
case 'M':
path.moveTo((command.x ?? 0) + xOffset, (command.y ?? 0) + yOffset)
diff --git a/packages/core/src/clipboard.ts b/packages/core/src/clipboard.ts
index 29e6c2356..995618698 100644
--- a/packages/core/src/clipboard.ts
+++ b/packages/core/src/clipboard.ts
@@ -1,10 +1,10 @@
import { inflateSync, deflateSync } from 'fflate'
+import { shapeTextForClipboard } from './canvas/text'
import { initCodec, getCompiledSchema, getSchemaBytes } from './kiwi/fig/codec'
import type { NodeChange as KiwiNodeChange } from './kiwi/fig/codec'
import { populateAndApplyOverrides } from './kiwi/fig/instance-overrides'
import type { InstanceNodeChange } from './kiwi/fig/instance-overrides'
-import { decodeBinarySchema, compileSchema, ByteBuffer } from './kiwi/schema-runtime'
import { nodeChangeToProps, sortChildren } from './kiwi/fig/node-change/convert'
import {
sceneNodeToKiwi,
@@ -15,9 +15,9 @@ import {
makeCanvasNodeChange,
buildFontDigestMap
} from './kiwi/fig/node-change/serialize'
+import { decodeBinarySchema, compileSchema, ByteBuffer } from './kiwi/schema-runtime'
import { randomInt } from './random'
import type { SceneGraph, SceneNode } from './scene-graph'
-import { shapeTextForClipboard } from './canvas/text'
import { buildDerivedTextDataV4 } from './text/derived-text/clipboard'
interface FigmaClipboardMeta {
@@ -337,7 +337,10 @@ export async function buildFigmaClipboardHTML(
if (!source) return
change.textAutoResize = 'NONE'
change.textUserLayoutVersion = 5
- change.lineHeight = { value: source.lineHeight ?? 100, units: source.lineHeight ? 'PIXELS' : 'PERCENT' }
+ change.lineHeight = {
+ value: source.lineHeight ?? 100,
+ units: source.lineHeight ? 'PIXELS' : 'PERCENT'
+ }
const shaped = await shapeTextForClipboard(source).catch(() => null)
change.derivedTextData = await buildDerivedTextDataV4(source, fontDigestMap, shaped, blobs)
})
diff --git a/packages/core/src/design-jsx/props-overrides.ts b/packages/core/src/design-jsx/props-overrides.ts
index f783c6bd9..3db9bdd73 100644
--- a/packages/core/src/design-jsx/props-overrides.ts
+++ b/packages/core/src/design-jsx/props-overrides.ts
@@ -395,10 +395,7 @@ function applyTextStyleOverrides(props: Record<string, unknown>, o: Partial<Scen
applyTextAlignmentOverrides(props, o)
}
-function applyTextAlignmentOverrides(
- props: Record<string, unknown>,
- o: Partial<SceneNode>
-): void {
+function applyTextAlignmentOverrides(props: Record<string, unknown>, o: Partial<SceneNode>): void {
const textAlign = props.textAlign ?? props.textAlignHorizontal ?? props.textHorizontalAlignment
if (typeof textAlign === 'string') {
o.textAlignHorizontal = TEXT_ALIGN_ALIAS_MAP[textAlign.toLowerCase()] ?? 'LEFT'
diff --git a/packages/core/src/editor/clipboard.ts b/packages/core/src/editor/clipboard.ts
index 892ab6252..104e75af9 100644
--- a/packages/core/src/editor/clipboard.ts
+++ b/packages/core/src/editor/clipboard.ts
@@ -10,11 +10,11 @@ import type { Vector } from '#core/types'
import { createClipboardCopyActions } from './clipboard/copy'
import { createClipboardExportActions } from './clipboard/export'
import { createClipboardFontActions } from './clipboard/fonts'
-import { createClipboardImageActions } from './clipboard/images'
import { deleteIds, recreateSnapshots, restoreDeletedEntries } from './clipboard/history'
+import { createClipboardImageActions } from './clipboard/images'
+import { replaceTargetsWithCreated, selectedReplacementTargets } from './clipboard/paste-replace'
import { resolvePasteTarget } from './clipboard/paste-target'
import { createClipboardPlacementActions } from './clipboard/placement'
-import { replaceTargetsWithCreated, selectedReplacementTargets } from './clipboard/paste-replace'
import { collectSubtrees, restoreSubtree, snapshotSubtree } from './clipboard/subtree-history'
import type { EditorContext } from './types'
@@ -22,7 +22,6 @@ type PasteOptions = {
replaceSelection?: boolean
}
-
export function createClipboardActions(ctx: EditorContext) {
function duplicateSelected(selectedNodes: SceneNode[]) {
const prevSelection = new Set(ctx.state.selectedIds)
diff --git a/packages/core/src/editor/clipboard/paste-replace.ts b/packages/core/src/editor/clipboard/paste-replace.ts
index 7d262a15c..76556f2ea 100644
--- a/packages/core/src/editor/clipboard/paste-replace.ts
+++ b/packages/core/src/editor/clipboard/paste-replace.ts
@@ -1,15 +1,10 @@
+import type { EditorContext } from '#core/editor/types'
import { computeAbsoluteBounds } from '#core/geometry'
import { computeAllLayouts } from '#core/layout'
import type { SceneNode } from '#core/scene-graph'
-import type { EditorContext } from '#core/editor/types'
+import { deleteIds, type DeletedEntry, recreateSnapshots, restoreDeletedEntries } from './history'
import { collectSubtrees, snapshotSubtree } from './subtree-history'
-import {
- deleteIds,
- type DeletedEntry,
- recreateSnapshots,
- restoreDeletedEntries
-} from './history'
type CenterNodesAt = (nodeIds: string[], cx: number, cy: number) => void
diff --git a/packages/core/src/editor/components/variants.ts b/packages/core/src/editor/components/variants.ts
index dfae8f747..6652eec38 100644
--- a/packages/core/src/editor/components/variants.ts
+++ b/packages/core/src/editor/components/variants.ts
@@ -2,12 +2,12 @@ import { omit } from 'es-toolkit/object'
import type { EditorContext } from '#core/editor/types'
import { randomHex } from '#core/random'
-import { buildVariantName, parseVariantName } from '#core/scene-graph/variant-name'
import type {
ComponentPropertyDefinition,
ComponentPropertyType,
SceneNode
} from '#core/scene-graph'
+import { buildVariantName, parseVariantName } from '#core/scene-graph/variant-name'
export type VariantConflict = {
values: Record<string, string>
diff --git a/packages/core/src/editor/state.ts b/packages/core/src/editor/state.ts
index 54e4f44bf..6ee8c1b4b 100644
--- a/packages/core/src/editor/state.ts
+++ b/packages/core/src/editor/state.ts
@@ -2,30 +2,30 @@ import { CANVAS_BG_COLOR } from '#core/constants'
import type { EditorState } from '#core/editor/types'
export function createDefaultEditorState(pageId: string): EditorState {
- return {
- activeTool: 'SELECT',
- currentPageId: pageId,
- selectedIds: new Set<string>(),
- marquee: null,
- snapGuides: [],
- rotationPreview: null,
- dropTargetId: null,
- layoutInsertIndicator: null,
- hoveredNodeId: null,
- editingTextId: null,
- penState: null,
- penCursorX: null,
- penCursorY: null,
- remoteCursors: [],
- autoLayoutHover: null,
- documentName: 'Untitled',
- panX: 0,
- pageColor: { ...CANVAS_BG_COLOR },
- panY: 0,
- zoom: 1,
- renderVersion: 0,
- sceneVersion: 0,
- loading: false,
- enteredContainerId: null
- }
+ return {
+ activeTool: 'SELECT',
+ currentPageId: pageId,
+ selectedIds: new Set<string>(),
+ marquee: null,
+ snapGuides: [],
+ rotationPreview: null,
+ dropTargetId: null,
+ layoutInsertIndicator: null,
+ hoveredNodeId: null,
+ editingTextId: null,
+ penState: null,
+ penCursorX: null,
+ penCursorY: null,
+ remoteCursors: [],
+ autoLayoutHover: null,
+ documentName: 'Untitled',
+ panX: 0,
+ pageColor: { ...CANVAS_BG_COLOR },
+ panY: 0,
+ zoom: 1,
+ renderVersion: 0,
+ sceneVersion: 0,
+ loading: false,
+ enteredContainerId: null
+ }
}
diff --git a/packages/core/src/editor/structure/selection.ts b/packages/core/src/editor/structure/selection.ts
index 451aeb560..10bc51663 100644
--- a/packages/core/src/editor/structure/selection.ts
+++ b/packages/core/src/editor/structure/selection.ts
@@ -11,7 +11,8 @@ export function selectedNodesInSharedParent(ctx: EditorContext, selectedNodes: S
if (topLevel.length === 0 || topLevel.some((node) => node.locked)) return null
const parentId = topLevel[0].parentId ?? ctx.state.currentPageId
- if (!topLevel.every((node) => (node.parentId ?? ctx.state.currentPageId) === parentId)) return null
+ if (!topLevel.every((node) => (node.parentId ?? ctx.state.currentPageId) === parentId))
+ return null
const parent = ctx.graph.getNode(parentId)
return parent ? { topLevel, parentId, parent } : null
diff --git a/packages/core/src/editor/tool-registry.ts b/packages/core/src/editor/tool-registry.ts
index b059affc9..43f5aef8f 100644
--- a/packages/core/src/editor/tool-registry.ts
+++ b/packages/core/src/editor/tool-registry.ts
@@ -1,34 +1,34 @@
-import type { Tool } from "./types";
+import type { Tool } from './types'
export interface EditorToolDef {
- key: Tool;
- label: string;
- shortcut: string;
- flyout?: Tool[];
+ key: Tool
+ label: string
+ shortcut: string
+ flyout?: Tool[]
}
export const EDITOR_TOOLS: EditorToolDef[] = [
- { key: "SELECT", label: "Move", shortcut: "V" },
- { key: "FRAME", label: "Frame", shortcut: "F", flyout: ["FRAME", "SECTION"] },
- {
- key: "RECTANGLE",
- label: "Rectangle",
- shortcut: "R",
- flyout: ["RECTANGLE", "LINE", "ELLIPSE", "POLYGON", "STAR"],
- },
- { key: "PEN", label: "Pen", shortcut: "P" },
- { key: "TEXT", label: "Text", shortcut: "T" },
- { key: "HAND", label: "Hand", shortcut: "H" },
-];
+ { key: 'SELECT', label: 'Move', shortcut: 'V' },
+ { key: 'FRAME', label: 'Frame', shortcut: 'F', flyout: ['FRAME', 'SECTION'] },
+ {
+ key: 'RECTANGLE',
+ label: 'Rectangle',
+ shortcut: 'R',
+ flyout: ['RECTANGLE', 'LINE', 'ELLIPSE', 'POLYGON', 'STAR']
+ },
+ { key: 'PEN', label: 'Pen', shortcut: 'P' },
+ { key: 'TEXT', label: 'Text', shortcut: 'T' },
+ { key: 'HAND', label: 'Hand', shortcut: 'H' }
+]
export const TOOL_SHORTCUTS: Partial<Record<string, Tool>> = {
- KeyV: "SELECT",
- KeyF: "FRAME",
- KeyS: "SECTION",
- KeyR: "RECTANGLE",
- KeyO: "ELLIPSE",
- KeyL: "LINE",
- KeyT: "TEXT",
- KeyP: "PEN",
- KeyH: "HAND",
-};
+ KeyV: 'SELECT',
+ KeyF: 'FRAME',
+ KeyS: 'SECTION',
+ KeyR: 'RECTANGLE',
+ KeyO: 'ELLIPSE',
+ KeyL: 'LINE',
+ KeyT: 'TEXT',
+ KeyP: 'PEN',
+ KeyH: 'HAND'
+}
diff --git a/packages/core/src/editor/undo.ts b/packages/core/src/editor/undo.ts
index d396d1d00..29a77db93 100644
--- a/packages/core/src/editor/undo.ts
+++ b/packages/core/src/editor/undo.ts
@@ -11,7 +11,6 @@ import {
snapshotPage as createPageSnapshot,
type PageSnapshot
} from './history/snapshot'
-
import type { EditorContext } from './types'
export function createUndoActions(ctx: EditorContext) {
diff --git a/packages/core/src/figma-api/index.ts b/packages/core/src/figma-api/index.ts
index c7cb3c4f7..4ea7acbfb 100644
--- a/packages/core/src/figma-api/index.ts
+++ b/packages/core/src/figma-api/index.ts
@@ -219,7 +219,11 @@ export class FigmaAPI implements NodeProxyHost {
return (node as BaseNode & { [INTERNAL_ID]: string })[INTERNAL_ID]
}
- group(nodes: ReadonlyArray<FigmaNodeProxy>, parent: FigmaNodeProxy, index?: number): FigmaGroupNode
+ group(
+ nodes: ReadonlyArray<FigmaNodeProxy>,
+ parent: FigmaNodeProxy,
+ index?: number
+ ): FigmaGroupNode
group(nodes: ReadonlyArray<BaseNode>, parent: BaseNode & ChildrenMixin, index?: number): GroupNode
group(
nodes: ReadonlyArray<BaseNode | FigmaNodeProxy>,
@@ -424,8 +428,16 @@ export class FigmaAPI implements NodeProxyHost {
// --- Flatten ---
- flatten(nodes: ReadonlyArray<FigmaNodeProxy>, parent?: FigmaNodeProxy, index?: number): FigmaVectorNode
- flatten(nodes: ReadonlyArray<BaseNode>, parent?: BaseNode & ChildrenMixin, index?: number): VectorNode
+ flatten(
+ nodes: ReadonlyArray<FigmaNodeProxy>,
+ parent?: FigmaNodeProxy,
+ index?: number
+ ): FigmaVectorNode
+ flatten(
+ nodes: ReadonlyArray<BaseNode>,
+ parent?: BaseNode & ChildrenMixin,
+ index?: number
+ ): VectorNode
flatten(
nodes: ReadonlyArray<BaseNode | FigmaNodeProxy>,
parent?: (BaseNode & ChildrenMixin) | FigmaNodeProxy,
diff --git a/packages/core/src/icons/svg.ts b/packages/core/src/icons/svg.ts
index 3e1a66187..a6591ca22 100644
--- a/packages/core/src/icons/svg.ts
+++ b/packages/core/src/icons/svg.ts
@@ -118,7 +118,9 @@ export function extractPaths(svgBody: string): IconPathInfo[] {
d,
fill: resolveAttr(attrValue(tag, 'fill'), groupAttrs.fill, 'currentColor'),
stroke: resolveAttr(attrValue(tag, 'stroke'), groupAttrs.stroke, null),
- strokeWidth: Number.parseFloat(attrValue(tag, 'stroke-width') ?? groupAttrs.strokeWidth ?? '1'),
+ strokeWidth: Number.parseFloat(
+ attrValue(tag, 'stroke-width') ?? groupAttrs.strokeWidth ?? '1'
+ ),
strokeCap: attrValue(tag, 'stroke-linecap') ?? groupAttrs.strokeCap ?? 'butt',
strokeJoin: attrValue(tag, 'stroke-linejoin') ?? groupAttrs.strokeJoin ?? 'miter',
fillRule: fillRuleAttr === 'evenodd' ? 'EVENODD' : 'NONZERO'
diff --git a/packages/core/src/io/formats/fig/export.ts b/packages/core/src/io/formats/fig/export.ts
index e00a3a526..9058d278b 100644
--- a/packages/core/src/io/formats/fig/export.ts
+++ b/packages/core/src/io/formats/fig/export.ts
@@ -4,9 +4,9 @@ import { deflateSync } from 'fflate'
import type { SkiaRenderer } from '#core/canvas'
import { CANVAS_BG_COLOR, IS_BROWSER, IS_TAURI } from '#core/constants'
import { renderThumbnail } from '#core/io/formats/raster'
-import { populateAllLazyFigImportRoots } from '#core/kiwi/fig/lazy-import'
import { initCodec, getCompiledSchema, getSchemaBytes } from '#core/kiwi/fig/codec'
import type { NodeChange } from '#core/kiwi/fig/codec'
+import { populateAllLazyFigImportRoots } from '#core/kiwi/fig/lazy-import'
import { stringToGuid } from '#core/kiwi/fig/node-change/convert'
import { buildFigmaPaintVariableColorMap } from '#core/kiwi/fig/node-change/export-node'
import {
@@ -91,11 +91,17 @@ async function renderFigThumbnail(
): Promise<Uint8Array> {
if (!pageId) return THUMBNAIL_1X1
if (ck && renderer) {
- return renderThumbnail(ck, renderer, graph, pageId, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT) ?? THUMBNAIL_1X1
+ return (
+ renderThumbnail(ck, renderer, graph, pageId, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT) ??
+ THUMBNAIL_1X1
+ )
}
if (!renderHeadless || IS_BROWSER || IS_TAURI) return THUMBNAIL_1X1
const { headlessRenderThumbnail } = await import('#core/io/formats/raster')
- return (await headlessRenderThumbnail(graph, pageId, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT)) ?? THUMBNAIL_1X1
+ return (
+ (await headlessRenderThumbnail(graph, pageId, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT)) ??
+ THUMBNAIL_1X1
+ )
}
function assignVariableGuids(
diff --git a/packages/core/src/io/formats/jsx/export.ts b/packages/core/src/io/formats/jsx/export.ts
index 1a24a93c8..39064f449 100644
--- a/packages/core/src/io/formats/jsx/export.ts
+++ b/packages/core/src/io/formats/jsx/export.ts
@@ -1,421 +1,366 @@
-import { DEFAULT_FONT_FAMILY } from "#core/constants";
-import type { SceneGraph, SceneNode, NodeType } from "#core/scene-graph";
-import { resolveNodeTextDirection } from "#core/text/direction";
+import { DEFAULT_FONT_FAMILY } from '#core/constants'
+import type { SceneGraph, SceneNode, NodeType } from '#core/scene-graph'
+import { resolveNodeTextDirection } from '#core/text/direction'
import {
- collectCornerRadii,
- collectPadding,
- emitPadding,
- escapeJSXText,
- formatProp,
- formatShadow,
- formatTracks,
- getNodeContext,
- solidFillColor,
- solidStroke,
-} from "./helpers";
-import { collectTailwindClasses } from "./tailwind-classes";
-
-export type JSXFormat = "openpencil" | "tailwind";
+ collectCornerRadii,
+ collectPadding,
+ emitPadding,
+ escapeJSXText,
+ formatProp,
+ formatShadow,
+ formatTracks,
+ getNodeContext,
+ solidFillColor,
+ solidStroke
+} from './helpers'
+import { collectTailwindClasses } from './tailwind-classes'
+
+export type JSXFormat = 'openpencil' | 'tailwind'
const NODE_TYPE_TO_TAG: Partial<Record<NodeType, string>> = {
- FRAME: "Frame",
- RECTANGLE: "Rectangle",
- ROUNDED_RECTANGLE: "Rectangle",
- ELLIPSE: "Ellipse",
- TEXT: "Text",
- LINE: "Line",
- STAR: "Star",
- POLYGON: "Polygon",
- VECTOR: "Vector",
- GROUP: "Group",
- SECTION: "Section",
- COMPONENT: "Component",
- COMPONENT_SET: "Frame",
- INSTANCE: "Frame",
-};
+ FRAME: 'Frame',
+ RECTANGLE: 'Rectangle',
+ ROUNDED_RECTANGLE: 'Rectangle',
+ ELLIPSE: 'Ellipse',
+ TEXT: 'Text',
+ LINE: 'Line',
+ STAR: 'Star',
+ POLYGON: 'Polygon',
+ VECTOR: 'Vector',
+ GROUP: 'Group',
+ SECTION: 'Section',
+ COMPONENT: 'Component',
+ COMPONENT_SET: 'Frame',
+ INSTANCE: 'Frame'
+}
const NODE_TYPE_TO_TW_TAG: Partial<Record<NodeType, string>> = {
- FRAME: "div",
- RECTANGLE: "div",
- ROUNDED_RECTANGLE: "div",
- ELLIPSE: "div",
- TEXT: "p",
- LINE: "div",
- STAR: "div",
- POLYGON: "div",
- VECTOR: "div",
- GROUP: "div",
- SECTION: "section",
- COMPONENT: "div",
- COMPONENT_SET: "div",
- INSTANCE: "div",
-};
+ FRAME: 'div',
+ RECTANGLE: 'div',
+ ROUNDED_RECTANGLE: 'div',
+ ELLIPSE: 'div',
+ TEXT: 'p',
+ LINE: 'div',
+ STAR: 'div',
+ POLYGON: 'div',
+ VECTOR: 'div',
+ GROUP: 'div',
+ SECTION: 'section',
+ COMPONENT: 'div',
+ COMPONENT_SET: 'div',
+ INSTANCE: 'div'
+}
// --- OpenPencil format helpers ---
-function collectGridSizingProps(
- node: SceneNode,
- props: [string, unknown][],
-): void {
- props.push(["grid", true]);
- if (node.gridTemplateColumns.length > 0)
- props.push(["columns", formatTracks(node.gridTemplateColumns)]);
- if (node.gridTemplateRows.length > 0)
- props.push(["rows", formatTracks(node.gridTemplateRows)]);
- if (node.width > 0) props.push(["w", node.width]);
- if (node.gridTemplateRows.length > 0 && node.height > 0)
- props.push(["h", node.height]);
- if (node.gridColumnGap > 0) props.push(["columnGap", node.gridColumnGap]);
- if (node.gridRowGap > 0) props.push(["rowGap", node.gridRowGap]);
+function collectGridSizingProps(node: SceneNode, props: [string, unknown][]): void {
+ props.push(['grid', true])
+ if (node.gridTemplateColumns.length > 0)
+ props.push(['columns', formatTracks(node.gridTemplateColumns)])
+ if (node.gridTemplateRows.length > 0) props.push(['rows', formatTracks(node.gridTemplateRows)])
+ if (node.width > 0) props.push(['w', node.width])
+ if (node.gridTemplateRows.length > 0 && node.height > 0) props.push(['h', node.height])
+ if (node.gridColumnGap > 0) props.push(['columnGap', node.gridColumnGap])
+ if (node.gridRowGap > 0) props.push(['rowGap', node.gridRowGap])
}
-function collectFlexSizingProps(
- node: SceneNode,
- props: [string, unknown][],
-): void {
- props.push(["flex", node.layoutMode === "HORIZONTAL" ? "row" : "col"]);
- if (node.layoutDirection === "RTL") props.push(["dir", "rtl"]);
- const primaryAxis = node.layoutMode === "HORIZONTAL" ? "width" : "height";
- const crossAxis = node.layoutMode === "HORIZONTAL" ? "height" : "width";
-
- if (node.primaryAxisSizing === "FILL")
- props.push([primaryAxis === "width" ? "w" : "h", "fill"]);
- else if (node.primaryAxisSizing !== "HUG")
- props.push([primaryAxis === "width" ? "w" : "h", node[primaryAxis]]);
-
- if (node.counterAxisSizing === "FILL")
- props.push([crossAxis === "width" ? "w" : "h", "fill"]);
- else if (node.counterAxisSizing !== "HUG")
- props.push([crossAxis === "width" ? "w" : "h", node[crossAxis]]);
+function collectFlexSizingProps(node: SceneNode, props: [string, unknown][]): void {
+ props.push(['flex', node.layoutMode === 'HORIZONTAL' ? 'row' : 'col'])
+ if (node.layoutDirection === 'RTL') props.push(['dir', 'rtl'])
+ const primaryAxis = node.layoutMode === 'HORIZONTAL' ? 'width' : 'height'
+ const crossAxis = node.layoutMode === 'HORIZONTAL' ? 'height' : 'width'
+
+ if (node.primaryAxisSizing === 'FILL') props.push([primaryAxis === 'width' ? 'w' : 'h', 'fill'])
+ else if (node.primaryAxisSizing !== 'HUG')
+ props.push([primaryAxis === 'width' ? 'w' : 'h', node[primaryAxis]])
+
+ if (node.counterAxisSizing === 'FILL') props.push([crossAxis === 'width' ? 'w' : 'h', 'fill'])
+ else if (node.counterAxisSizing !== 'HUG')
+ props.push([crossAxis === 'width' ? 'w' : 'h', node[crossAxis]])
}
-function collectGridPositionProps(
- node: SceneNode,
- props: [string, unknown][],
-): void {
- if (!node.gridPosition) return;
- const pos = node.gridPosition;
- if (pos.column > 0) props.push(["colStart", pos.column]);
- if (pos.row > 0) props.push(["rowStart", pos.row]);
- if (pos.columnSpan > 1) props.push(["colSpan", pos.columnSpan]);
- if (pos.rowSpan > 1) props.push(["rowSpan", pos.rowSpan]);
+function collectGridPositionProps(node: SceneNode, props: [string, unknown][]): void {
+ if (!node.gridPosition) return
+ const pos = node.gridPosition
+ if (pos.column > 0) props.push(['colStart', pos.column])
+ if (pos.row > 0) props.push(['rowStart', pos.row])
+ if (pos.columnSpan > 1) props.push(['colSpan', pos.columnSpan])
+ if (pos.rowSpan > 1) props.push(['rowSpan', pos.rowSpan])
}
-function collectFlexAlignmentProps(
- node: SceneNode,
- props: [string, unknown][],
-): void {
- if (node.itemSpacing > 0) props.push(["gap", node.itemSpacing]);
-
- if (node.layoutWrap === "WRAP") {
- props.push(["wrap", true]);
- if (node.counterAxisSpacing > 0)
- props.push(["rowGap", node.counterAxisSpacing]);
- }
-
- if (node.primaryAxisAlign === "CENTER") props.push(["justify", "center"]);
- else if (node.primaryAxisAlign === "MAX") props.push(["justify", "end"]);
- else if (node.primaryAxisAlign === "SPACE_BETWEEN")
- props.push(["justify", "between"]);
-
- if (node.counterAxisAlign === "CENTER") props.push(["items", "center"]);
- else if (node.counterAxisAlign === "MAX") props.push(["items", "end"]);
- else if (node.counterAxisAlign === "STRETCH")
- props.push(["items", "stretch"]);
+function collectFlexAlignmentProps(node: SceneNode, props: [string, unknown][]): void {
+ if (node.itemSpacing > 0) props.push(['gap', node.itemSpacing])
+
+ if (node.layoutWrap === 'WRAP') {
+ props.push(['wrap', true])
+ if (node.counterAxisSpacing > 0) props.push(['rowGap', node.counterAxisSpacing])
+ }
+
+ if (node.primaryAxisAlign === 'CENTER') props.push(['justify', 'center'])
+ else if (node.primaryAxisAlign === 'MAX') props.push(['justify', 'end'])
+ else if (node.primaryAxisAlign === 'SPACE_BETWEEN') props.push(['justify', 'between'])
+
+ if (node.counterAxisAlign === 'CENTER') props.push(['items', 'center'])
+ else if (node.counterAxisAlign === 'MAX') props.push(['items', 'end'])
+ else if (node.counterAxisAlign === 'STRETCH') props.push(['items', 'stretch'])
}
-function collectAutoLayoutPaddingProps(
- node: SceneNode,
- props: [string, unknown][],
-): void {
- const pad = collectPadding(node);
- if (!pad) return;
- props.push(
- ...emitPadding(
- pad,
- (v) => ["p", v] as [string, unknown],
- (y, x) =>
- [
- ["py", y],
- ["px", x],
- ] as [string, unknown][],
- ({ pt, pr, pb, pl }) => {
- const r: [string, unknown][] = [];
- if (pt > 0) r.push(["pt", pt]);
- if (pr > 0) r.push(["pr", pr]);
- if (pb > 0) r.push(["pb", pb]);
- if (pl > 0) r.push(["pl", pl]);
- return r;
- },
- ),
- );
+function collectAutoLayoutPaddingProps(node: SceneNode, props: [string, unknown][]): void {
+ const pad = collectPadding(node)
+ if (!pad) return
+ props.push(
+ ...emitPadding(
+ pad,
+ (v) => ['p', v] as [string, unknown],
+ (y, x) =>
+ [
+ ['py', y],
+ ['px', x]
+ ] as [string, unknown][],
+ ({ pt, pr, pb, pl }) => {
+ const r: [string, unknown][] = []
+ if (pt > 0) r.push(['pt', pt])
+ if (pr > 0) r.push(['pr', pr])
+ if (pb > 0) r.push(['pb', pb])
+ if (pl > 0) r.push(['pl', pl])
+ return r
+ }
+ )
+ )
}
-function collectCornerRadiiProps(
- node: SceneNode,
- props: [string, unknown][],
-): void {
- const corners = collectCornerRadii(node);
- if (!corners) return;
- const { tl, tr, br, bl } = corners;
- if (tl === tr && tr === br && br === bl) {
- props.push(["rounded", tl]);
- } else {
- if (tl > 0) props.push(["roundedTL", tl]);
- if (tr > 0) props.push(["roundedTR", tr]);
- if (br > 0) props.push(["roundedBR", br]);
- if (bl > 0) props.push(["roundedBL", bl]);
- }
+function collectCornerRadiiProps(node: SceneNode, props: [string, unknown][]): void {
+ const corners = collectCornerRadii(node)
+ if (!corners) return
+ const { tl, tr, br, bl } = corners
+ if (tl === tr && tr === br && br === bl) {
+ props.push(['rounded', tl])
+ } else {
+ if (tl > 0) props.push(['roundedTL', tl])
+ if (tr > 0) props.push(['roundedTR', tr])
+ if (br > 0) props.push(['roundedBR', br])
+ if (bl > 0) props.push(['roundedBL', bl])
+ }
}
-function collectAppearanceProps(
- node: SceneNode,
- props: [string, unknown][],
-): void {
- const bg = solidFillColor(node.fills);
- if (bg) props.push(["bg", bg]);
-
- const stroke = solidStroke(node.strokes);
- if (stroke) {
- props.push(["stroke", stroke.color]);
- if (stroke.weight !== 1) props.push(["strokeWidth", stroke.weight]);
- if (stroke.dash) props.push(["strokeDash", stroke.dash]);
- }
-
- collectCornerRadiiProps(node, props);
-
- if (node.cornerSmoothing > 0)
- props.push(["cornerSmoothing", node.cornerSmoothing]);
- if (node.opacity < 1)
- props.push(["opacity", Math.round(node.opacity * 100) / 100]);
- if (node.rotation !== 0)
- props.push(["rotate", Math.round(node.rotation * 100) / 100]);
- if (node.blendMode !== "PASS_THROUGH" && node.blendMode !== "NORMAL") {
- props.push(["blendMode", node.blendMode.toLowerCase()]);
- }
- if (node.clipsContent) props.push(["overflow", "hidden"]);
-
- for (const effect of node.effects) {
- if (!effect.visible) continue;
- if (effect.type === "DROP_SHADOW" || effect.type === "INNER_SHADOW") {
- const shadow = formatShadow(effect);
- if (shadow) props.push(["shadow", shadow]);
- } else if (
- effect.type === "LAYER_BLUR" ||
- effect.type === "BACKGROUND_BLUR"
- ) {
- props.push(["blur", effect.radius]);
- }
- }
+function collectAppearanceProps(node: SceneNode, props: [string, unknown][]): void {
+ const bg = solidFillColor(node.fills)
+ if (bg) props.push(['bg', bg])
+
+ const stroke = solidStroke(node.strokes)
+ if (stroke) {
+ props.push(['stroke', stroke.color])
+ if (stroke.weight !== 1) props.push(['strokeWidth', stroke.weight])
+ if (stroke.dash) props.push(['strokeDash', stroke.dash])
+ }
+
+ collectCornerRadiiProps(node, props)
+
+ if (node.cornerSmoothing > 0) props.push(['cornerSmoothing', node.cornerSmoothing])
+ if (node.opacity < 1) props.push(['opacity', Math.round(node.opacity * 100) / 100])
+ if (node.rotation !== 0) props.push(['rotate', Math.round(node.rotation * 100) / 100])
+ if (node.blendMode !== 'PASS_THROUGH' && node.blendMode !== 'NORMAL') {
+ props.push(['blendMode', node.blendMode.toLowerCase()])
+ }
+ if (node.clipsContent) props.push(['overflow', 'hidden'])
+
+ for (const effect of node.effects) {
+ if (!effect.visible) continue
+ if (effect.type === 'DROP_SHADOW' || effect.type === 'INNER_SHADOW') {
+ const shadow = formatShadow(effect)
+ if (shadow) props.push(['shadow', shadow])
+ } else if (effect.type === 'LAYER_BLUR' || effect.type === 'BACKGROUND_BLUR') {
+ props.push(['blur', effect.radius])
+ }
+ }
}
function collectPositionProps(
- node: SceneNode,
- ctx: ReturnType<typeof getNodeContext>,
- props: [string, unknown][],
+ node: SceneNode,
+ ctx: ReturnType<typeof getNodeContext>,
+ props: [string, unknown][]
): void {
- if (ctx.parentIsAutoLayout || ctx.parentIsGrid) return;
- if (node.x !== 0) props.push(["x", node.x]);
- if (node.y !== 0) props.push(["y", node.y]);
+ if (ctx.parentIsAutoLayout || ctx.parentIsGrid) return
+ if (node.x !== 0) props.push(['x', node.x])
+ if (node.y !== 0) props.push(['y', node.y])
}
function collectSizingProps(
- node: SceneNode,
- ctx: ReturnType<typeof getNodeContext>,
- graph: SceneGraph,
- props: [string, unknown][],
+ node: SceneNode,
+ ctx: ReturnType<typeof getNodeContext>,
+ graph: SceneGraph,
+ props: [string, unknown][]
): void {
- if (ctx.isGrid) collectGridSizingProps(node, props);
- else if (ctx.isFlex) collectFlexSizingProps(node, props);
- else if (node.type === "TEXT") collectTextSizingProps(node, graph, props);
- else {
- if (node.width > 0) props.push(["w", node.width]);
- if (node.height > 0) props.push(["h", node.height]);
- }
-
- if (!ctx.parentIsAutoLayout) return;
- if (node.layoutGrow > 0) props.push(["grow", node.layoutGrow]);
- if (node.layoutAlignSelf === "STRETCH") {
- const parent = node.parentId ? graph.getNode(node.parentId) : null;
- if (
- parent &&
- (parent.layoutMode === "HORIZONTAL" || parent.layoutMode === "VERTICAL")
- ) {
- const crossDim = parent.layoutMode === "HORIZONTAL" ? "h" : "w";
- if (!props.some(([k]) => k === crossDim)) props.push([crossDim, "fill"]);
- }
- }
+ if (ctx.isGrid) collectGridSizingProps(node, props)
+ else if (ctx.isFlex) collectFlexSizingProps(node, props)
+ else if (node.type === 'TEXT') collectTextSizingProps(node, graph, props)
+ else {
+ if (node.width > 0) props.push(['w', node.width])
+ if (node.height > 0) props.push(['h', node.height])
+ }
+
+ if (!ctx.parentIsAutoLayout) return
+ if (node.layoutGrow > 0) props.push(['grow', node.layoutGrow])
+ if (node.layoutAlignSelf === 'STRETCH') {
+ const parent = node.parentId ? graph.getNode(node.parentId) : null
+ if (parent && (parent.layoutMode === 'HORIZONTAL' || parent.layoutMode === 'VERTICAL')) {
+ const crossDim = parent.layoutMode === 'HORIZONTAL' ? 'h' : 'w'
+ if (!props.some(([k]) => k === crossDim)) props.push([crossDim, 'fill'])
+ }
+ }
}
function collectTextSizingProps(
- node: SceneNode,
- graph: SceneGraph,
- props: [string, unknown][],
+ node: SceneNode,
+ graph: SceneGraph,
+ props: [string, unknown][]
): void {
- const autoResize = node.textAutoResize;
- const emitH = autoResize === "NONE" || autoResize === "TRUNCATE";
- // Don't emit fixed w when text stretches to fill parent — the layoutAlignSelf
- // check below will emit w="fill" instead. Without this guard, w={computedPx}
- // gets emitted first and blocks the fill detection.
- const isFillWidth =
- node.layoutAlignSelf === "STRETCH" &&
- (() => {
- const parent = node.parentId ? graph.getNode(node.parentId) : null;
- return parent?.layoutMode === "VERTICAL";
- })();
- const isGrowWidth =
- node.layoutGrow > 0 &&
- (() => {
- const parent = node.parentId ? graph.getNode(node.parentId) : null;
- return parent?.layoutMode === "HORIZONTAL";
- })();
- const emitW =
- autoResize !== "WIDTH_AND_HEIGHT" && !isFillWidth && !isGrowWidth;
- if (emitW && node.width > 0) props.push(["w", node.width]);
- if (emitH && node.height > 0) props.push(["h", node.height]);
+ const autoResize = node.textAutoResize
+ const emitH = autoResize === 'NONE' || autoResize === 'TRUNCATE'
+ // Don't emit fixed w when text stretches to fill parent — the layoutAlignSelf
+ // check below will emit w="fill" instead. Without this guard, w={computedPx}
+ // gets emitted first and blocks the fill detection.
+ const isFillWidth =
+ node.layoutAlignSelf === 'STRETCH' &&
+ (() => {
+ const parent = node.parentId ? graph.getNode(node.parentId) : null
+ return parent?.layoutMode === 'VERTICAL'
+ })()
+ const isGrowWidth =
+ node.layoutGrow > 0 &&
+ (() => {
+ const parent = node.parentId ? graph.getNode(node.parentId) : null
+ return parent?.layoutMode === 'HORIZONTAL'
+ })()
+ const emitW = autoResize !== 'WIDTH_AND_HEIGHT' && !isFillWidth && !isGrowWidth
+ if (emitW && node.width > 0) props.push(['w', node.width])
+ if (emitH && node.height > 0) props.push(['h', node.height])
}
-function collectTextNodeProps(
- node: SceneNode,
- props: [string, unknown][],
-): void {
- const direction = resolveNodeTextDirection(node);
- if (node.fontSize !== 14) props.push(["size", node.fontSize]);
- if (node.fontFamily && node.fontFamily !== DEFAULT_FONT_FAMILY)
- props.push(["font", node.fontFamily]);
- if (node.fontWeight !== 400) {
- if (node.fontWeight === 700) props.push(["weight", "bold"]);
- else if (node.fontWeight === 500) props.push(["weight", "medium"]);
- else props.push(["weight", node.fontWeight]);
- }
- if (direction === "RTL") props.push(["dir", "rtl"]);
- if (node.textAlignHorizontal !== "LEFT") {
- props.push(["textAlign", node.textAlignHorizontal.toLowerCase()]);
- }
- if (node.lineHeight != null) props.push(["lineHeight", node.lineHeight]);
- if (node.letterSpacing !== 0)
- props.push(["letterSpacing", node.letterSpacing]);
- if (node.textDecoration !== "NONE")
- props.push(["textDecoration", node.textDecoration.toLowerCase()]);
- if (node.textCase !== "ORIGINAL")
- props.push(["textCase", node.textCase.toLowerCase()]);
- if (node.maxLines != null) props.push(["maxLines", node.maxLines]);
- if (node.textTruncation === "ENDING" && node.maxLines == null)
- props.push(["truncate", true]);
- const textColor = solidFillColor(node.fills);
- if (textColor) {
- const bgIdx = props.findIndex(([k]) => k === "bg");
- if (bgIdx !== -1) props.splice(bgIdx, 1);
- props.push(["color", textColor]);
- }
+function collectTextNodeProps(node: SceneNode, props: [string, unknown][]): void {
+ const direction = resolveNodeTextDirection(node)
+ if (node.fontSize !== 14) props.push(['size', node.fontSize])
+ if (node.fontFamily && node.fontFamily !== DEFAULT_FONT_FAMILY)
+ props.push(['font', node.fontFamily])
+ if (node.fontWeight !== 400) {
+ if (node.fontWeight === 700) props.push(['weight', 'bold'])
+ else if (node.fontWeight === 500) props.push(['weight', 'medium'])
+ else props.push(['weight', node.fontWeight])
+ }
+ if (direction === 'RTL') props.push(['dir', 'rtl'])
+ if (node.textAlignHorizontal !== 'LEFT') {
+ props.push(['textAlign', node.textAlignHorizontal.toLowerCase()])
+ }
+ if (node.lineHeight != null) props.push(['lineHeight', node.lineHeight])
+ if (node.letterSpacing !== 0) props.push(['letterSpacing', node.letterSpacing])
+ if (node.textDecoration !== 'NONE')
+ props.push(['textDecoration', node.textDecoration.toLowerCase()])
+ if (node.textCase !== 'ORIGINAL') props.push(['textCase', node.textCase.toLowerCase()])
+ if (node.maxLines != null) props.push(['maxLines', node.maxLines])
+ if (node.textTruncation === 'ENDING' && node.maxLines == null) props.push(['truncate', true])
+ const textColor = solidFillColor(node.fills)
+ if (textColor) {
+ const bgIdx = props.findIndex(([k]) => k === 'bg')
+ if (bgIdx !== -1) props.splice(bgIdx, 1)
+ props.push(['color', textColor])
+ }
}
-function collectShapeNodeProps(
- node: SceneNode,
- props: [string, unknown][],
-): void {
- if (node.type === "STAR") {
- if (node.pointCount !== 5) props.push(["points", node.pointCount]);
- if (node.starInnerRadius !== 0.382)
- props.push(["innerRadius", node.starInnerRadius]);
- }
- if (node.type === "POLYGON" && node.pointCount !== 3) {
- props.push(["points", node.pointCount]);
- }
+function collectShapeNodeProps(node: SceneNode, props: [string, unknown][]): void {
+ if (node.type === 'STAR') {
+ if (node.pointCount !== 5) props.push(['points', node.pointCount])
+ if (node.starInnerRadius !== 0.382) props.push(['innerRadius', node.starInnerRadius])
+ }
+ if (node.type === 'POLYGON' && node.pointCount !== 3) {
+ props.push(['points', node.pointCount])
+ }
}
function collectProps(node: SceneNode, graph: SceneGraph): [string, unknown][] {
- const props: [string, unknown][] = [];
- const ctx = getNodeContext(node, graph);
+ const props: [string, unknown][] = []
+ const ctx = getNodeContext(node, graph)
- if (node.name && node.name !== node.type) props.push(["name", node.name]);
+ if (node.name && node.name !== node.type) props.push(['name', node.name])
- collectPositionProps(node, ctx, props);
- collectSizingProps(node, ctx, graph, props);
- if (ctx.parentIsGrid) collectGridPositionProps(node, props);
- if (ctx.isFlex) collectFlexAlignmentProps(node, props);
- if (ctx.isAutoLayout) collectAutoLayoutPaddingProps(node, props);
- collectAppearanceProps(node, props);
- if (node.type === "TEXT") collectTextNodeProps(node, props);
- collectShapeNodeProps(node, props);
+ collectPositionProps(node, ctx, props)
+ collectSizingProps(node, ctx, graph, props)
+ if (ctx.parentIsGrid) collectGridPositionProps(node, props)
+ if (ctx.isFlex) collectFlexAlignmentProps(node, props)
+ if (ctx.isAutoLayout) collectAutoLayoutPaddingProps(node, props)
+ collectAppearanceProps(node, props)
+ if (node.type === 'TEXT') collectTextNodeProps(node, props)
+ collectShapeNodeProps(node, props)
- return props;
+ return props
}
// --- JSX rendering ---
-function nodeToJSX(
- node: SceneNode,
- graph: SceneGraph,
- indent: number,
- format: JSXFormat,
-): string {
- const tagMap = format === "tailwind" ? NODE_TYPE_TO_TW_TAG : NODE_TYPE_TO_TAG;
- const tag = tagMap[node.type];
- if (!tag) return "";
-
- const prefix = " ".repeat(indent);
- let attrsStr: string;
-
- if (format === "tailwind") {
- const classes = collectTailwindClasses(node, graph);
- const nameAttr =
- node.name && node.name !== node.type ? ` data-name="${node.name}"` : "";
- const classAttr =
- classes.length > 0 ? ` className="${classes.join(" ")}"` : "";
- attrsStr = `${nameAttr}${classAttr}`.trim();
- } else {
- const props = collectProps(node, graph);
- attrsStr = props.map(([k, v]) => formatProp(k, v)).join(" ");
- }
-
- const opening = attrsStr ? `<${tag} ${attrsStr}` : `<${tag}`;
- const children = graph.getChildren(node.id);
-
- if (node.type === "TEXT") {
- const text = node.text;
- if (!text) return `${prefix}${opening} />`;
- const escaped = escapeJSXText(text);
- if (!escaped.includes("\n")) {
- return `${prefix}${opening}>${escaped}</${tag}>`;
- }
- return [
- `${prefix}${opening}>`,
- ...escaped.split("\n").map((l) => `${prefix} ${l}`),
- `${prefix}</${tag}>`,
- ].join("\n");
- }
-
- if (children.length === 0) return `${prefix}${opening} />`;
-
- const childJSX = children
- .filter((c) => c.visible)
- .map((c) => nodeToJSX(c, graph, indent + 1, format))
- .filter(Boolean);
-
- if (childJSX.length === 0) return `${prefix}${opening} />`;
-
- return [`${prefix}${opening}>`, ...childJSX, `${prefix}</${tag}>`].join("\n");
+function nodeToJSX(node: SceneNode, graph: SceneGraph, indent: number, format: JSXFormat): string {
+ const tagMap = format === 'tailwind' ? NODE_TYPE_TO_TW_TAG : NODE_TYPE_TO_TAG
+ const tag = tagMap[node.type]
+ if (!tag) return ''
+
+ const prefix = ' '.repeat(indent)
+ let attrsStr: string
+
+ if (format === 'tailwind') {
+ const classes = collectTailwindClasses(node, graph)
+ const nameAttr = node.name && node.name !== node.type ? ` data-name="${node.name}"` : ''
+ const classAttr = classes.length > 0 ? ` className="${classes.join(' ')}"` : ''
+ attrsStr = `${nameAttr}${classAttr}`.trim()
+ } else {
+ const props = collectProps(node, graph)
+ attrsStr = props.map(([k, v]) => formatProp(k, v)).join(' ')
+ }
+
+ const opening = attrsStr ? `<${tag} ${attrsStr}` : `<${tag}`
+ const children = graph.getChildren(node.id)
+
+ if (node.type === 'TEXT') {
+ const text = node.text
+ if (!text) return `${prefix}${opening} />`
+ const escaped = escapeJSXText(text)
+ if (!escaped.includes('\n')) {
+ return `${prefix}${opening}>${escaped}</${tag}>`
+ }
+ return [
+ `${prefix}${opening}>`,
+ ...escaped.split('\n').map((l) => `${prefix} ${l}`),
+ `${prefix}</${tag}>`
+ ].join('\n')
+ }
+
+ if (children.length === 0) return `${prefix}${opening} />`
+
+ const childJSX = children
+ .filter((c) => c.visible)
+ .map((c) => nodeToJSX(c, graph, indent + 1, format))
+ .filter(Boolean)
+
+ if (childJSX.length === 0) return `${prefix}${opening} />`
+
+ return [`${prefix}${opening}>`, ...childJSX, `${prefix}</${tag}>`].join('\n')
}
export function sceneNodeToJSX(
- nodeId: string,
- graph: SceneGraph,
- format: JSXFormat = "openpencil",
+ nodeId: string,
+ graph: SceneGraph,
+ format: JSXFormat = 'openpencil'
): string {
- const node = graph.getNode(nodeId);
- if (!node) return "";
- return nodeToJSX(node, graph, 0, format);
+ const node = graph.getNode(nodeId)
+ if (!node) return ''
+ return nodeToJSX(node, graph, 0, format)
}
export function selectionToJSX(
- nodeIds: string[],
- graph: SceneGraph,
- format: JSXFormat = "openpencil",
+ nodeIds: string[],
+ graph: SceneGraph,
+ format: JSXFormat = 'openpencil'
): string {
- return nodeIds
- .map((id) => sceneNodeToJSX(id, graph, format))
- .filter(Boolean)
- .join("\n\n");
+ return nodeIds
+ .map((id) => sceneNodeToJSX(id, graph, format))
+ .filter(Boolean)
+ .join('\n\n')
}
diff --git a/packages/core/src/io/formats/jsx/tailwind-classes.ts b/packages/core/src/io/formats/jsx/tailwind-classes.ts
index cc02bf2de..87e919fdd 100644
--- a/packages/core/src/io/formats/jsx/tailwind-classes.ts
+++ b/packages/core/src/io/formats/jsx/tailwind-classes.ts
@@ -77,11 +77,7 @@ function applyPadding(style: Record<string, string>, node: SceneNode): void {
else style.padding = `${px(pt)} ${px(pr)} ${px(pb)} ${px(pl)}`
}
-function applyLayoutStyle(
- style: Record<string, string>,
- node: SceneNode,
- graph: SceneGraph
-): void {
+function applyLayoutStyle(style: Record<string, string>, node: SceneNode, graph: SceneGraph): void {
const ctx = getNodeContext(node, graph)
if (ctx.isGrid) {
@@ -143,11 +139,9 @@ function applyAppearanceStyle(style: Record<string, string>, node: SceneNode): v
function applyTextStyle(style: Record<string, string>, node: SceneNode): void {
if (node.type !== 'TEXT') return
style.fontSize = px(node.fontSize)
- if (node.fontFamily && node.fontFamily !== DEFAULT_FONT_FAMILY)
- style.fontFamily = node.fontFamily
+ if (node.fontFamily && node.fontFamily !== DEFAULT_FONT_FAMILY) style.fontFamily = node.fontFamily
if (node.fontWeight !== 400) style.fontWeight = String(node.fontWeight)
- if (node.textAlignHorizontal !== 'LEFT')
- style.textAlign = node.textAlignHorizontal.toLowerCase()
+ if (node.textAlignHorizontal !== 'LEFT') style.textAlign = node.textAlignHorizontal.toLowerCase()
const textColor = solidFillColor(node.fills)
if (textColor) style.color = textColor
}
diff --git a/packages/core/src/io/formats/svg/paths.ts b/packages/core/src/io/formats/svg/paths.ts
index 3e8ecb0ac..f0b4e1b02 100644
--- a/packages/core/src/io/formats/svg/paths.ts
+++ b/packages/core/src/io/formats/svg/paths.ts
@@ -1,5 +1,5 @@
-import { polygonVertices } from '#core/geometry'
import { nodeHasRadius } from '#core/canvas/shapes'
+import { polygonVertices } from '#core/geometry'
import type { SceneNode, VectorNetwork, VectorSegment, VectorVertex } from '#core/scene-graph'
const CMD_CLOSE = 0
diff --git a/packages/core/src/kiwi/fig/codec/index.ts b/packages/core/src/kiwi/fig/codec/index.ts
index 0b3fa19cf..4100d6f0b 100644
--- a/packages/core/src/kiwi/fig/codec/index.ts
+++ b/packages/core/src/kiwi/fig/codec/index.ts
@@ -136,7 +136,9 @@ export function encodeMessage(message: FigmaMessage): Uint8Array {
const ncHex = Buffer.from(ncBytes).toString('hex')
const finalHex = beforeArray + ncHex + afterArray
- const finalBytes = new Uint8Array(finalHex.match(/.{2}/g)?.map((b) => Number.parseInt(b, 16)) ?? [])
+ const finalBytes = new Uint8Array(
+ finalHex.match(/.{2}/g)?.map((b) => Number.parseInt(b, 16)) ?? []
+ )
return compress(finalBytes)
}
diff --git a/packages/core/src/kiwi/fig/import.ts b/packages/core/src/kiwi/fig/import.ts
index e4a470d8b..5a78bda5e 100644
--- a/packages/core/src/kiwi/fig/import.ts
+++ b/packages/core/src/kiwi/fig/import.ts
@@ -1,10 +1,10 @@
import { isNotNil } from 'es-toolkit/predicate'
import { BLACK } from '#core/constants'
-import { setLazyFigImportContext } from '#core/kiwi/fig/lazy-import'
import type { NodeChange, VariableDataValuesEntry, Color, GUID } from '#core/kiwi/fig/codec'
import { populateAndApplyOverrides } from '#core/kiwi/fig/instance-overrides'
import type { InstanceNodeChange } from '#core/kiwi/fig/instance-overrides'
+import { setLazyFigImportContext } from '#core/kiwi/fig/lazy-import'
import {
guidToString,
nodeChangeToProps,
@@ -19,10 +19,14 @@ import type { VariableType, VariableValue } from '#core/scene-graph'
type AssetRef = { key: string; version?: string }
type AliasRef = { guid?: GUID; assetRef?: AssetRef }
-function applyImportedCanvasMetadata(page: ReturnType<SceneGraph['addPage']>, canvasNc: NodeChange) {
+function applyImportedCanvasMetadata(
+ page: ReturnType<SceneGraph['addPage']>,
+ canvasNc: NodeChange
+) {
page.source.format = 'fig'
page.source.orderKey = canvasNc.parentIndex?.position ?? null
- if (canvasNc.backgroundColor) page.source.fig.rawNodeFields.backgroundColor = structuredClone(canvasNc.backgroundColor)
+ if (canvasNc.backgroundColor)
+ page.source.fig.rawNodeFields.backgroundColor = structuredClone(canvasNc.backgroundColor)
page.source.fig.rawNodeFields.strokeJoin = canvasNc.strokeJoin
page.source.fig.rawNodeFields.strokeWeight = canvasNc.strokeWeight
if (canvasNc.pageType) page.source.fig.rawNodeFields.pageType = canvasNc.pageType
@@ -476,7 +480,8 @@ export function importNodeChanges(
)
})
- if (activeRootIds) rememberLazyFigImportContext(graph, changeMap, guidToNodeId, blobs, activeRootIds)
+ if (activeRootIds)
+ rememberLazyFigImportContext(graph, changeMap, guidToNodeId, blobs, activeRootIds)
setVariableColorResolver(null)
diff --git a/packages/core/src/kiwi/fig/instance-overrides/component-props/apply.ts b/packages/core/src/kiwi/fig/instance-overrides/component-props/apply.ts
index 006944d1a..effd6384f 100644
--- a/packages/core/src/kiwi/fig/instance-overrides/component-props/apply.ts
+++ b/packages/core/src/kiwi/fig/instance-overrides/component-props/apply.ts
@@ -63,7 +63,8 @@ function applySwapProp(
val: ComponentPropValue,
modified?: Set<string>
): void {
- const swapId = propTextCharacters(val) ?? (val.guidValue ? guidToString(val.guidValue) : undefined)
+ const swapId =
+ propTextCharacters(val) ?? (val.guidValue ? guidToString(val.guidValue) : undefined)
const newCompId = swapId ? ctx.guidToNodeId.get(swapId) : undefined
if (!newCompId) return
applyPatchAndMark(
diff --git a/packages/core/src/kiwi/fig/instance-overrides/component-props/index.ts b/packages/core/src/kiwi/fig/instance-overrides/component-props/index.ts
index 8a08de0d5..038e21f00 100644
--- a/packages/core/src/kiwi/fig/instance-overrides/component-props/index.ts
+++ b/packages/core/src/kiwi/fig/instance-overrides/component-props/index.ts
@@ -1,10 +1,8 @@
-import {
- applyInstanceDirectAssignments,
- applyOverrideAssignments
-} from './assignments'
-import { collectAssignmentsMap, collectPropRefsMap } from './maps'
import type { OverrideContext } from '#core/kiwi/fig/instance-overrides/types'
+import { applyInstanceDirectAssignments, applyOverrideAssignments } from './assignments'
+import { collectAssignmentsMap, collectPropRefsMap } from './maps'
+
/**
* Apply all component property assignments (visibility toggles, instance swaps).
*
diff --git a/packages/core/src/kiwi/fig/instance-overrides/component-props/values.ts b/packages/core/src/kiwi/fig/instance-overrides/component-props/values.ts
index 684e90c4c..baf15d4e8 100644
--- a/packages/core/src/kiwi/fig/instance-overrides/component-props/values.ts
+++ b/packages/core/src/kiwi/fig/instance-overrides/component-props/values.ts
@@ -1,11 +1,10 @@
import type { GUID } from '#core/kiwi/fig/codec'
-import { guidToString } from '#core/kiwi/fig/node-change/convert'
-
import type {
ComponentPropAssignment,
ComponentPropValue,
OverrideContext
} from '#core/kiwi/fig/instance-overrides/types'
+import { guidToString } from '#core/kiwi/fig/node-change/convert'
export function normalizePropName(value: string): string {
return value.toLowerCase().replace(/[^a-z0-9]/g, '')
@@ -42,7 +41,8 @@ function resolveAssignmentValue(
if (variableValue?.symbolIdValue?.guid) return { guidValue: variableValue.symbolIdValue.guid }
if (variableValue?.boolValue !== undefined) return { boolValue: variableValue.boolValue }
if (variableValue?.textValue !== undefined) return { textValue: variableValue.textValue }
- if (variableValue?.textDataValue !== undefined) return { textDataValue: variableValue.textDataValue }
+ if (variableValue?.textDataValue !== undefined)
+ return { textDataValue: variableValue.textDataValue }
return resolveDefaults ? (ctx.propDefaults.get(key) ?? assignment.value) : assignment.value
}
diff --git a/packages/core/src/kiwi/fig/instance-overrides/derived-symbol-data/geometry.ts b/packages/core/src/kiwi/fig/instance-overrides/derived-symbol-data/geometry.ts
index 0d5885b03..8f0dea145 100644
--- a/packages/core/src/kiwi/fig/instance-overrides/derived-symbol-data/geometry.ts
+++ b/packages/core/src/kiwi/fig/instance-overrides/derived-symbol-data/geometry.ts
@@ -1,5 +1,5 @@
-import { resolveGeometryPaths } from '#core/kiwi/fig/node-change/convert'
import type { DerivedSymbolOverride } from '#core/kiwi/fig/instance-overrides/types'
+import { resolveGeometryPaths } from '#core/kiwi/fig/node-change/convert'
import type { GeometryPath, SceneNode } from '#core/scene-graph'
function scaleGeometryBlobs(geom: GeometryPath[], sx: number, sy: number): GeometryPath[] {
@@ -36,12 +36,20 @@ export function resolveDsdGeometry(
if (fg.length > 0) result.fillGeometry = fg
else if (d.size && target.fillGeometry.length > 0 && target.width > 0 && target.height > 0) {
- result.fillGeometry = scaleGeometryBlobs(target.fillGeometry, d.size.x / target.width, d.size.y / target.height)
+ result.fillGeometry = scaleGeometryBlobs(
+ target.fillGeometry,
+ d.size.x / target.width,
+ d.size.y / target.height
+ )
}
if (sg.length > 0) result.strokeGeometry = sg
else if (d.size && target.strokeGeometry.length > 0 && target.width > 0 && target.height > 0) {
- result.strokeGeometry = scaleGeometryBlobs(target.strokeGeometry, d.size.x / target.width, d.size.y / target.height)
+ result.strokeGeometry = scaleGeometryBlobs(
+ target.strokeGeometry,
+ d.size.x / target.width,
+ d.size.y / target.height
+ )
}
return result
diff --git a/packages/core/src/kiwi/fig/instance-overrides/derived-symbol-data/index.ts b/packages/core/src/kiwi/fig/instance-overrides/derived-symbol-data/index.ts
index 9e22f228d..e42a21cb6 100644
--- a/packages/core/src/kiwi/fig/instance-overrides/derived-symbol-data/index.ts
+++ b/packages/core/src/kiwi/fig/instance-overrides/derived-symbol-data/index.ts
@@ -1,6 +1,9 @@
import { applyOverridePatch } from '#core/kiwi/fig/instance-overrides/patches'
import { resolveOverrideTarget } from '#core/kiwi/fig/instance-overrides/resolve'
-import type { DerivedSymbolOverride, OverrideContext } from '#core/kiwi/fig/instance-overrides/types'
+import type {
+ DerivedSymbolOverride,
+ OverrideContext
+} from '#core/kiwi/fig/instance-overrides/types'
import { buildDsdLayoutUpdates } from './layout'
import { propagateDsdChanges } from './propagate'
@@ -45,7 +48,8 @@ function resolveDsdUpdates(ctx: OverrideContext): { modified: Set<string>; sizeS
const nodeId = ctx.guidToNodeId.get(ncId)
if (!nodeId || (ctx.activeNodeIds && !ctx.activeNodeIds.has(nodeId))) continue
- for (const d of derived) applyDsdOverride(ctx, visibleSiblingCount, nodeId, d, modified, sizeSet)
+ for (const d of derived)
+ applyDsdOverride(ctx, visibleSiblingCount, nodeId, d, modified, sizeSet)
}
return { modified, sizeSet }
diff --git a/packages/core/src/kiwi/fig/instance-overrides/derived-symbol-data/layout.ts b/packages/core/src/kiwi/fig/instance-overrides/derived-symbol-data/layout.ts
index 81d5e318c..a046c7c80 100644
--- a/packages/core/src/kiwi/fig/instance-overrides/derived-symbol-data/layout.ts
+++ b/packages/core/src/kiwi/fig/instance-overrides/derived-symbol-data/layout.ts
@@ -1,11 +1,18 @@
+import type {
+ DerivedSymbolOverride,
+ OverrideContext
+} from '#core/kiwi/fig/instance-overrides/types'
import { convertLetterSpacing, convertLineHeight } from '#core/kiwi/fig/node-change/convert'
import { convertFigmaDerivedTextGlyphs } from '#core/kiwi/fig/node-change/derived-text-glyphs'
-import type { DerivedSymbolOverride, OverrideContext } from '#core/kiwi/fig/instance-overrides/types'
import type { SceneNode } from '#core/scene-graph'
import { resolveDsdGeometry } from './geometry'
-function getVisibleSiblingCount(ctx: OverrideContext, cache: Map<string, number>, parentId: string): number {
+function getVisibleSiblingCount(
+ ctx: OverrideContext,
+ cache: Map<string, number>,
+ parentId: string
+): number {
const cached = cache.get(parentId)
if (cached !== undefined) return cached
const count = ctx.graph.getChildren(parentId).filter((child) => child.visible).length
@@ -18,12 +25,21 @@ function resolveSizeOnlyPosition(
visibleSiblingCount: Map<string, number>,
node: SceneNode
): Pick<SceneNode, 'x' | 'y'> | null {
- if (!node.parentId || getVisibleSiblingCount(ctx, visibleSiblingCount, node.parentId) !== 1 || !node.componentId) return null
+ if (
+ !node.parentId ||
+ getVisibleSiblingCount(ctx, visibleSiblingCount, node.parentId) !== 1 ||
+ !node.componentId
+ )
+ return null
const source = ctx.graph.getNode(node.componentId)
if (!source) return null
const sourceParent = source.parentId ? ctx.graph.getNode(source.parentId) : null
if (!sourceParent) return { x: source.x, y: source.y }
- const withinParent = source.x >= 0 && source.y >= 0 && source.x + source.width <= sourceParent.width + 0.01 && source.y + source.height <= sourceParent.height + 0.01
+ const withinParent =
+ source.x >= 0 &&
+ source.y >= 0 &&
+ source.x + source.width <= sourceParent.width + 0.01 &&
+ source.y + source.height <= sourceParent.height + 0.01
return withinParent ? { x: source.x, y: source.y } : { x: 0, y: 0 }
}
@@ -35,9 +51,13 @@ function buildDsdTextUpdates(
const updates: Partial<SceneNode> = {}
if (d.fontSize !== undefined) updates.fontSize = d.fontSize
if (d.lineHeight !== undefined) updates.lineHeight = convertLineHeight(d.lineHeight, d.fontSize)
- if (d.letterSpacing !== undefined) updates.letterSpacing = convertLetterSpacing(d.letterSpacing, d.fontSize)
+ if (d.letterSpacing !== undefined)
+ updates.letterSpacing = convertLetterSpacing(d.letterSpacing, d.fontSize)
if (d.strokeWeight !== undefined && target.strokes.length > 0) {
- updates.strokes = target.strokes.map((stroke) => ({ ...stroke, weight: d.strokeWeight as number }))
+ updates.strokes = target.strokes.map((stroke) => ({
+ ...stroke,
+ weight: d.strokeWeight as number
+ }))
}
const figmaDerivedTextGlyphs = convertFigmaDerivedTextGlyphs(d.derivedTextData, blobs)
if (figmaDerivedTextGlyphs.length > 0) updates.figmaDerivedTextGlyphs = figmaDerivedTextGlyphs
diff --git a/packages/core/src/kiwi/fig/instance-overrides/derived-symbol-data/propagate.ts b/packages/core/src/kiwi/fig/instance-overrides/derived-symbol-data/propagate.ts
index 69714867a..a8e1830a2 100644
--- a/packages/core/src/kiwi/fig/instance-overrides/derived-symbol-data/propagate.ts
+++ b/packages/core/src/kiwi/fig/instance-overrides/derived-symbol-data/propagate.ts
@@ -17,8 +17,10 @@ function buildCloneUpdates(
if (source.x !== clone.x) updates.x = source.x
if (source.y !== clone.y) updates.y = source.y
if (!ctx.geometryOverrideNodes.has(cloneId)) {
- if (source.fillGeometry !== clone.fillGeometry) updates.fillGeometry = copyGeometryPaths(source.fillGeometry)
- if (source.strokeGeometry !== clone.strokeGeometry) updates.strokeGeometry = copyGeometryPaths(source.strokeGeometry)
+ if (source.fillGeometry !== clone.fillGeometry)
+ updates.fillGeometry = copyGeometryPaths(source.fillGeometry)
+ if (source.strokeGeometry !== clone.strokeGeometry)
+ updates.strokeGeometry = copyGeometryPaths(source.strokeGeometry)
}
if (source.text === clone.text && source.figmaDerivedTextGlyphs) {
updates.figmaDerivedTextGlyphs = structuredClone(source.figmaDerivedTextGlyphs)
diff --git a/packages/core/src/kiwi/fig/instance-overrides/index.ts b/packages/core/src/kiwi/fig/instance-overrides/index.ts
index e307cb659..9914d2b23 100644
--- a/packages/core/src/kiwi/fig/instance-overrides/index.ts
+++ b/packages/core/src/kiwi/fig/instance-overrides/index.ts
@@ -14,10 +14,10 @@ import { guidToString } from '#core/kiwi/fig/node-change/convert'
import type { SceneGraph, SceneNode } from '#core/scene-graph'
import { copyFills, copyStyleRuns } from '#core/scene-graph/copy'
+import { applyComponentProperties } from './component-props'
import { applyConstraintScaling } from './constraints'
import { applyDerivedSymbolData } from './derived-symbol-data'
import { populateInstances } from './populate'
-import { applyComponentProperties } from './component-props'
import { preComputeRoots } from './resolve'
import { applySymbolOverrides } from './symbol/overrides'
import { propagateOverridesTransitively } from './sync'
@@ -100,7 +100,11 @@ function propagateResolvedChildPlacementClones(graph: SceneGraph): void {
const sourceChild = graph.getNode(source.childIds[i])
const child = graph.getNode(node.childIds[i])
if (!sourceChild || !child) continue
- if (sourceChild.overrideKey && child.overrideKey && sourceChild.overrideKey !== child.overrideKey) {
+ if (
+ sourceChild.overrideKey &&
+ child.overrideKey &&
+ sourceChild.overrideKey !== child.overrideKey
+ ) {
continue
}
const updates: Partial<SceneNode> = {}
diff --git a/packages/core/src/kiwi/fig/instance-overrides/resolve.ts b/packages/core/src/kiwi/fig/instance-overrides/resolve.ts
index 581895a35..4eaa8332d 100644
--- a/packages/core/src/kiwi/fig/instance-overrides/resolve.ts
+++ b/packages/core/src/kiwi/fig/instance-overrides/resolve.ts
@@ -325,7 +325,10 @@ export function resolveOverrideTarget(
* Only renames when the current name matches the root component name (preserves
* user-given names). Clears the componentIdRoot cache after changing the tree.
*/
-function collectStyledStrokeDescendants(ctx: OverrideContext, nodeId: string): SceneNode['strokes'][] {
+function collectStyledStrokeDescendants(
+ ctx: OverrideContext,
+ nodeId: string
+): SceneNode['strokes'][] {
const result: SceneNode['strokes'][] = []
const visit = (id: string) => {
const node = ctx.graph.getNode(id)
@@ -337,7 +340,11 @@ function collectStyledStrokeDescendants(ctx: OverrideContext, nodeId: string): S
return result
}
-function applyStrokeDescendants(ctx: OverrideContext, nodeId: string, strokes: SceneNode['strokes'][]): void {
+function applyStrokeDescendants(
+ ctx: OverrideContext,
+ nodeId: string,
+ strokes: SceneNode['strokes'][]
+): void {
let index = 0
const visit = (id: string) => {
const node = ctx.graph.getNode(id)
diff --git a/packages/core/src/kiwi/fig/instance-overrides/sync/fields.ts b/packages/core/src/kiwi/fig/instance-overrides/sync/fields.ts
index 07a572164..473651dca 100644
--- a/packages/core/src/kiwi/fig/instance-overrides/sync/fields.ts
+++ b/packages/core/src/kiwi/fig/instance-overrides/sync/fields.ts
@@ -27,12 +27,24 @@ function assignDirectUpdate(
updates: Partial<SceneNode>
): void {
switch (key) {
- case 'text': updates.text = source.text; break
- case 'visible': updates.visible = source.visible; break
- case 'opacity': updates.opacity = source.opacity; break
- case 'locked': updates.locked = source.locked; break
- case 'layoutGrow': updates.layoutGrow = source.layoutGrow; break
- case 'textAutoResize': updates.textAutoResize = source.textAutoResize; break
+ case 'text':
+ updates.text = source.text
+ break
+ case 'visible':
+ updates.visible = source.visible
+ break
+ case 'opacity':
+ updates.opacity = source.opacity
+ break
+ case 'locked':
+ updates.locked = source.locked
+ break
+ case 'layoutGrow':
+ updates.layoutGrow = source.layoutGrow
+ break
+ case 'textAutoResize':
+ updates.textAutoResize = source.textAutoResize
+ break
}
}
@@ -59,10 +71,18 @@ function assignCopiedUpdate(
updates: Partial<SceneNode>
): void {
switch (key) {
- case 'fills': updates.fills = copyFills(source.fills); break
- case 'strokes': updates.strokes = copyStrokes(source.strokes); break
- case 'effects': updates.effects = copyEffects(source.effects); break
- case 'styleRuns': updates.styleRuns = copyStyleRuns(source.styleRuns); break
+ case 'fills':
+ updates.fills = copyFills(source.fills)
+ break
+ case 'strokes':
+ updates.strokes = copyStrokes(source.strokes)
+ break
+ case 'effects':
+ updates.effects = copyEffects(source.effects)
+ break
+ case 'styleRuns':
+ updates.styleRuns = copyStyleRuns(source.styleRuns)
+ break
}
}
diff --git a/packages/core/src/kiwi/fig/node-change/convert.ts b/packages/core/src/kiwi/fig/node-change/convert.ts
index 010036905..78f0fcdf3 100644
--- a/packages/core/src/kiwi/fig/node-change/convert.ts
+++ b/packages/core/src/kiwi/fig/node-change/convert.ts
@@ -707,7 +707,9 @@ function preserveFigmaPayloadBlobs(value: unknown, blobs: Uint8Array[]): unknown
} else {
result[key] = {
__openPencilFigmaBlob:
- blob instanceof Uint8Array ? blob : new Uint8Array(Object.values(blob as Record<string, number>))
+ blob instanceof Uint8Array
+ ? blob
+ : new Uint8Array(Object.values(blob as Record<string, number>))
} satisfies PreservedFigmaBlob
}
} else {
@@ -798,10 +800,15 @@ function extractFigmaSymbolMetadata(
| undefined
return {
symbolOverrides: preserveFigmaPayloadBlobs(sd?.symbolOverrides ?? [], blobs) as unknown[],
- componentPropAssignments: preserveFigmaPayloadBlobs(nc.componentPropAssignments ?? [], blobs) as unknown[],
+ componentPropAssignments: preserveFigmaPayloadBlobs(
+ nc.componentPropAssignments ?? [],
+ blobs
+ ) as unknown[],
derivedSymbolData: preserveFigmaPayloadBlobs(nc.derivedSymbolData ?? [], blobs) as unknown[],
derivedSymbolDataLayoutVersion:
- typeof nc.derivedSymbolDataLayoutVersion === 'number' ? nc.derivedSymbolDataLayoutVersion : null,
+ typeof nc.derivedSymbolDataLayoutVersion === 'number'
+ ? nc.derivedSymbolDataLayoutVersion
+ : null,
uniformScaleFactor: typeof sd?.uniformScaleFactor === 'number' ? sd.uniformScaleFactor : null
}
}
diff --git a/packages/core/src/kiwi/fig/node-change/export-node.ts b/packages/core/src/kiwi/fig/node-change/export-node.ts
index 25b9f902f..5333d5503 100644
--- a/packages/core/src/kiwi/fig/node-change/export-node.ts
+++ b/packages/core/src/kiwi/fig/node-change/export-node.ts
@@ -102,7 +102,10 @@ function parseGuidOrNull(value: string) {
return /^\d+:\d+$/.test(value) ? stringToGuid(value) : null
}
-const FIGMA_PAYLOAD_VARIABLE_MAP_FIELDS = new Set(['variableConsumptionMap', 'parameterConsumptionMap'])
+const FIGMA_PAYLOAD_VARIABLE_MAP_FIELDS = new Set([
+ 'variableConsumptionMap',
+ 'parameterConsumptionMap'
+])
const FIGMA_PAYLOAD_PAINT_VARIABLE_FIELDS = new Set(['colorVar', 'opacityVar'])
const SUPPORTED_VARIABLE_DATA_TYPES = new Set([
@@ -118,14 +121,21 @@ const SUPPORTED_VARIABLE_DATA_TYPES = new Set([
function isSupportedVariableMapEntry(value: unknown): boolean {
if (!value || typeof value !== 'object') return false
- const entry = value as { variableData?: { dataType?: string; value?: { propRefValue?: unknown } } }
+ const entry = value as {
+ variableData?: { dataType?: string; value?: { propRefValue?: unknown } }
+ }
const dataType = entry.variableData?.dataType
- return (typeof dataType === 'string' && SUPPORTED_VARIABLE_DATA_TYPES.has(dataType)) || !!entry.variableData?.value?.propRefValue
+ return (
+ (typeof dataType === 'string' && SUPPORTED_VARIABLE_DATA_TYPES.has(dataType)) ||
+ !!entry.variableData?.value?.propRefValue
+ )
}
function isPropRefVariableMapEntry(value: unknown): boolean {
if (!value || typeof value !== 'object') return false
- const entry = value as { variableData?: { dataType?: string; value?: { propRefValue?: unknown } } }
+ const entry = value as {
+ variableData?: { dataType?: string; value?: { propRefValue?: unknown } }
+ }
return entry.variableData?.dataType === 'PROP_REF' || !!entry.variableData?.value?.propRefValue
}
@@ -143,8 +153,9 @@ function materializeSafeVariableMap(
function paintVariableKey(value: unknown): string | null {
if (!value || typeof value !== 'object') return null
- const assetRef = (value as { value?: { alias?: { assetRef?: { key?: unknown; version?: unknown } } } })
- .value?.alias?.assetRef
+ const assetRef = (
+ value as { value?: { alias?: { assetRef?: { key?: unknown; version?: unknown } } } }
+ ).value?.alias?.assetRef
return typeof assetRef?.key === 'string'
? `${assetRef.key}:${typeof assetRef.version === 'string' ? assetRef.version : ''}`
: null
@@ -192,7 +203,8 @@ function materializeFigmaPayload(
options: MaterializeFigmaPayloadOptions = {}
): unknown {
if (value instanceof Uint8Array) return value
- if (Array.isArray(value)) return value.map((item) => materializeFigmaPayload(item, blobs, options))
+ if (Array.isArray(value))
+ return value.map((item) => materializeFigmaPayload(item, blobs, options))
if (!value || typeof value !== 'object') return value
if ('__openPencilFigmaBlob' in value) {
return materializeFigmaBlob(
@@ -326,11 +338,15 @@ function applyInstancePayload(
if (symbolID) {
const symbolData: Record<string, unknown> = { symbolID }
if (node.source.fig.symbolOverrides.length > 0) {
- symbolData.symbolOverrides = materializeFigmaPayload(node.source.fig.symbolOverrides, context.blobs, {
- blobIndexByHex: context.blobIndexByHex,
- includeVariableMaps: true,
- paintVariableColorMap: context.paintVariableColorMap
- })
+ symbolData.symbolOverrides = materializeFigmaPayload(
+ node.source.fig.symbolOverrides,
+ context.blobs,
+ {
+ blobIndexByHex: context.blobIndexByHex,
+ includeVariableMaps: true,
+ paintVariableColorMap: context.paintVariableColorMap
+ }
+ )
}
if (node.source.fig.uniformScaleFactor != null) {
symbolData.uniformScaleFactor = node.source.fig.uniformScaleFactor
@@ -349,11 +365,15 @@ function applyInstancePayload(
)
}
if (node.source.fig.derivedSymbolData.length > 0) {
- nc.derivedSymbolData = materializeFigmaPayload(node.source.fig.derivedSymbolData, context.blobs, {
- blobIndexByHex: context.blobIndexByHex,
- includeVariableMaps: true,
- paintVariableColorMap: context.paintVariableColorMap
- })
+ nc.derivedSymbolData = materializeFigmaPayload(
+ node.source.fig.derivedSymbolData,
+ context.blobs,
+ {
+ blobIndexByHex: context.blobIndexByHex,
+ includeVariableMaps: true,
+ paintVariableColorMap: context.paintVariableColorMap
+ }
+ )
}
if (node.source.fig.derivedSymbolDataLayoutVersion != null) {
nc.derivedSymbolDataLayoutVersion = node.source.fig.derivedSymbolDataLayoutVersion
@@ -400,15 +420,22 @@ function applyComponentMetadata(node: SceneNode, nc: KiwiNodeChange): void {
}
function exportNodeSize(node: SceneNode): Vector {
- return node.source.fig.rawSize ? { ...node.source.fig.rawSize } : { x: node.width, y: node.height }
+ return node.source.fig.rawSize
+ ? { ...node.source.fig.rawSize }
+ : { x: node.width, y: node.height }
}
function exportNodeTransform(context: SceneNodeToKiwiContext, node: SceneNode): Matrix {
- return node.source.fig.rawTransform ? { ...node.source.fig.rawTransform } : context.computeExportTransform(node)
+ return node.source.fig.rawTransform
+ ? { ...node.source.fig.rawTransform }
+ : context.computeExportTransform(node)
}
function hasRawGeometryPayload(node: SceneNode): boolean {
- return 'fillGeometry' in node.source.fig.rawNodeFields || 'strokeGeometry' in node.source.fig.rawNodeFields
+ return (
+ 'fillGeometry' in node.source.fig.rawNodeFields ||
+ 'strokeGeometry' in node.source.fig.rawNodeFields
+ )
}
function hasRawVectorPayload(node: SceneNode): boolean {
diff --git a/packages/core/src/kiwi/fig/node-change/guid.ts b/packages/core/src/kiwi/fig/node-change/guid.ts
index 590d466ad..d0588bc28 100644
--- a/packages/core/src/kiwi/fig/node-change/guid.ts
+++ b/packages/core/src/kiwi/fig/node-change/guid.ts
@@ -6,7 +6,8 @@ export function guidToString(guid: GUID): string {
export function stringToGuid(str: string): GUID {
const match = str.match(/^(?:VariableID:|VariableCollectionId:)?(\d+):(\d+)$/)
- if (match) return { sessionID: Number.parseInt(match[1], 10), localID: Number.parseInt(match[2], 10) }
+ if (match)
+ return { sessionID: Number.parseInt(match[1], 10), localID: Number.parseInt(match[2], 10) }
const [session, local] = str.split(':')
return { sessionID: Number.parseInt(session, 10), localID: Number.parseInt(local, 10) }
}
diff --git a/packages/core/src/kiwi/fig/node-change/serialize.ts b/packages/core/src/kiwi/fig/node-change/serialize.ts
index d1b274941..71eb30fad 100644
--- a/packages/core/src/kiwi/fig/node-change/serialize.ts
+++ b/packages/core/src/kiwi/fig/node-change/serialize.ts
@@ -137,12 +137,13 @@ function buildDerivedTextData(
: glyphAdvance,
rotation: 0
}))
- : (getGlyphOutlineMetricsSync(
- node.fontFamily,
- weightToStyle(node.fontWeight, node.italic),
- node.text,
- node.fontSize
- ) ?? []
+ : (
+ getGlyphOutlineMetricsSync(
+ node.fontFamily,
+ weightToStyle(node.fontWeight, node.italic),
+ node.text,
+ node.fontSize
+ ) ?? []
).map((glyph, index) => ({
commandsBlob: appendGlyphBlob(
blobs,
@@ -322,16 +323,14 @@ function serializeTextProps(
}
}
-function normalizeStackMode(
- value: string | undefined
-): KiwiNodeChange['stackMode'] {
+function normalizeStackMode(value: string | undefined): KiwiNodeChange['stackMode'] {
return value === 'HORIZONTAL' || value === 'VERTICAL' || value === 'NONE' ? value : undefined
}
-function normalizeStackSizing(
- value: string | undefined
-): KiwiNodeChange['stackPrimarySizing'] {
- return value === 'FIXED' || value === 'RESIZE_TO_FIT' || value === 'RESIZE_TO_FIT_WITH_IMPLICIT_SIZE'
+function normalizeStackSizing(value: string | undefined): KiwiNodeChange['stackPrimarySizing'] {
+ return value === 'FIXED' ||
+ value === 'RESIZE_TO_FIT' ||
+ value === 'RESIZE_TO_FIT_WITH_IMPLICIT_SIZE'
? value
: undefined
}
diff --git a/packages/core/src/kiwi/fig/parse/transfer.ts b/packages/core/src/kiwi/fig/parse/transfer.ts
index 54c8b0119..f68019be0 100644
--- a/packages/core/src/kiwi/fig/parse/transfer.ts
+++ b/packages/core/src/kiwi/fig/parse/transfer.ts
@@ -1,5 +1,5 @@
-import { getLazyFigImportContext, setLazyFigImportContext } from '#core/kiwi/fig/lazy-import'
import type { InstanceNodeChange } from '#core/kiwi/fig/instance-overrides'
+import { getLazyFigImportContext, setLazyFigImportContext } from '#core/kiwi/fig/lazy-import'
import { SceneGraph } from '#core/scene-graph'
import type { SceneNode, Variable, VariableCollection, DocumentColorSpace } from '#core/scene-graph'
diff --git a/packages/core/src/kiwi/fig/parse/worker.ts b/packages/core/src/kiwi/fig/parse/worker.ts
index 3e17b78d7..db66f75f4 100644
--- a/packages/core/src/kiwi/fig/parse/worker.ts
+++ b/packages/core/src/kiwi/fig/parse/worker.ts
@@ -22,7 +22,10 @@ self.onmessage = (e: MessageEvent<ArrayBuffer | WorkerParseRequest>) => {
const graph = importNodeChanges(nodeChanges, blobs, new Map(images), request.options)
graph.figKiwiVersion = figKiwiVersion
const serialized = serializeSceneGraph(graph)
- ;(self as WorkerScope).postMessage({ graph: serialized }, serializedSceneGraphTransferList(serialized))
+ ;(self as WorkerScope).postMessage(
+ { graph: serialized },
+ serializedSceneGraphTransferList(serialized)
+ )
} catch (err) {
self.postMessage({ error: err instanceof Error ? err.message : String(err) })
}
diff --git a/packages/core/src/kiwi/schema-runtime/index.ts b/packages/core/src/kiwi/schema-runtime/index.ts
index ac279b743..9b8cbc5d4 100644
--- a/packages/core/src/kiwi/schema-runtime/index.ts
+++ b/packages/core/src/kiwi/schema-runtime/index.ts
@@ -3,4 +3,10 @@ export { ByteBuffer } from './bb'
export { compileSchema } from './js'
export { decodeBinarySchema, encodeBinarySchema } from './binary'
export { parseSchema } from './parser'
-export { validateSchema, expectFieldNumber, expectEnumValue, findDefinition, findField } from './validate'
+export {
+ validateSchema,
+ expectFieldNumber,
+ expectEnumValue,
+ findDefinition,
+ findField
+} from './validate'
diff --git a/packages/core/src/kiwi/schema-runtime/validate.ts b/packages/core/src/kiwi/schema-runtime/validate.ts
index a28f3300d..367a0f4a7 100644
--- a/packages/core/src/kiwi/schema-runtime/validate.ts
+++ b/packages/core/src/kiwi/schema-runtime/validate.ts
@@ -6,7 +6,9 @@ export function findDefinition(schema: Schema, name: string): Definition | null
}
export function findField(schema: Schema, definitionName: string, fieldName: string): Field | null {
- return findDefinition(schema, definitionName)?.fields.find((field) => field.name === fieldName) ?? null
+ return (
+ findDefinition(schema, definitionName)?.fields.find((field) => field.name === fieldName) ?? null
+ )
}
export function expectFieldNumber(
diff --git a/packages/core/src/layout/apply.ts b/packages/core/src/layout/apply.ts
index 0f92be791..42c8e3c4e 100644
--- a/packages/core/src/layout/apply.ts
+++ b/packages/core/src/layout/apply.ts
@@ -36,8 +36,14 @@ function updateChildFromYoga(graph: SceneGraph, child: SceneNode, yogaChild: Yog
const derived = child.figmaDerivedLayout
graph.updateNode(child.id, {
- x: child.type === 'INSTANCE' ? yogaChild.getComputedLeft() : (derived?.x ?? yogaChild.getComputedLeft()),
- y: child.type === 'INSTANCE' ? yogaChild.getComputedTop() : (derived?.y ?? yogaChild.getComputedTop()),
+ x:
+ child.type === 'INSTANCE'
+ ? yogaChild.getComputedLeft()
+ : (derived?.x ?? yogaChild.getComputedLeft()),
+ y:
+ child.type === 'INSTANCE'
+ ? yogaChild.getComputedTop()
+ : (derived?.y ?? yogaChild.getComputedTop()),
width: derived?.width ?? yogaChild.getComputedWidth(),
height: derived?.height ?? yogaChild.getComputedHeight()
})
diff --git a/packages/core/src/profiler/hud-renderer.ts b/packages/core/src/profiler/hud-renderer.ts
index 3fcbb0510..32a7f545b 100644
--- a/packages/core/src/profiler/hud-renderer.ts
+++ b/packages/core/src/profiler/hud-renderer.ts
@@ -155,8 +155,16 @@ export class HudRenderer {
const pictureLabel = stats.scenePictureMode === 'record' ? 'record' : 'picture'
const pictureTime =
- stats.scenePictureMode === 'record' ? stats.scenePictureRecordTime : stats.scenePictureDrawTime
- canvas.drawText(`${pictureLabel}: ${pictureTime.toFixed(1)}ms`, col1, y, this.textPaint, this.hudFont)
+ stats.scenePictureMode === 'record'
+ ? stats.scenePictureRecordTime
+ : stats.scenePictureDrawTime
+ canvas.drawText(
+ `${pictureLabel}: ${pictureTime.toFixed(1)}ms`,
+ col1,
+ y,
+ this.textPaint,
+ this.hudFont
+ )
canvas.drawText(`flush: ${stats.flushTime.toFixed(1)}ms`, col2, y, this.textPaint, this.hudFont)
if (visiblePhases.length > 0) {
diff --git a/packages/core/src/scene-graph/index.ts b/packages/core/src/scene-graph/index.ts
index 7a2e3e3d0..1208cd0d8 100644
--- a/packages/core/src/scene-graph/index.ts
+++ b/packages/core/src/scene-graph/index.ts
@@ -325,8 +325,6 @@ export class SceneGraph {
'maxHeight'
])
-
-
runPreviewUpdates(fn: () => void): void {
this.previewMutationDepth++
try {
diff --git a/packages/core/src/scene-graph/node-defaults.ts b/packages/core/src/scene-graph/node-defaults.ts
index 1db4f3628..ff4572354 100644
--- a/packages/core/src/scene-graph/node-defaults.ts
+++ b/packages/core/src/scene-graph/node-defaults.ts
@@ -36,9 +36,7 @@ export function createDefaultNode(
},
figmaDerivedLayout: null,
fills:
- type === 'TEXT'
- ? [{ type: 'SOLID' as const, color: BLACK, opacity: 1, visible: true }]
- : [],
+ type === 'TEXT' ? [{ type: 'SOLID' as const, color: BLACK, opacity: 1, visible: true }] : [],
strokes: [],
effects: [],
opacity: 1,
diff --git a/packages/core/src/scene-graph/preview.ts b/packages/core/src/scene-graph/preview.ts
index 72e569e03..6bbe85f85 100644
--- a/packages/core/src/scene-graph/preview.ts
+++ b/packages/core/src/scene-graph/preview.ts
@@ -1,6 +1,5 @@
-import { normalizeVectorNetwork } from './vector-network'
-
import type { SceneNode } from './types'
+import { normalizeVectorNetwork } from './vector-network'
type PreviewGraph = {
nodes: Map<string, SceneNode>
diff --git a/packages/core/src/text/derived-text/clipboard.ts b/packages/core/src/text/derived-text/clipboard.ts
index 2dcfc9b1e..ba94bde02 100644
--- a/packages/core/src/text/derived-text/clipboard.ts
+++ b/packages/core/src/text/derived-text/clipboard.ts
@@ -1,10 +1,8 @@
import { prepareWithSegments, layoutWithLines } from '@chenglou/pretext'
import type { NodeChange } from '#core/kiwi/fig/codec'
-import type { SceneNode } from '#core/scene-graph'
-
import { encodePathCommandsBlob } from '#core/kiwi/fig/node-change/path-commands'
-
+import type { SceneNode } from '#core/scene-graph'
import { normalizeFontFamily, weightToFigmaStyle, weightToStyle } from '#core/text/fonts'
import { type GlyphOutlineMetrics, getGlyphOutlineMetricsSync } from '#core/text/opentype'
@@ -136,7 +134,8 @@ export async function buildDerivedTextDataV4(
const normalizedFamily = normalizeFontFamily(node.fontFamily)
const key = `${normalizedFamily}|${style}`
const lineHeightFallback = node.lineHeight ?? Math.ceil(node.fontSize * 1.2)
- const glyphMetrics = getGlyphOutlineMetricsSync(node.fontFamily, style, node.text, node.fontSize) ?? []
+ const glyphMetrics =
+ getGlyphOutlineMetricsSync(node.fontFamily, style, node.text, node.fontSize) ?? []
const fallbackAdvance = node.text.length > 0 ? node.width / Math.max(node.text.length, 1) : 0
const textGlyphs = buildTextGlyphs(node.text, glyphMetrics, fallbackAdvance, node.fontSize)
@@ -144,7 +143,10 @@ export async function buildDerivedTextDataV4(
const lineBreaks = computeLineBreaks(node, glyphMetrics, textGlyphs, fallbackAdvance, shaped)
const lineBreakSet = new Set(lineBreaks)
- const shapedByChar = new Map<number, (typeof shaped extends null | undefined ? never : NonNullable<typeof shaped>)['glyphs'][number]>()
+ const shapedByChar = new Map<
+ number,
+ (typeof shaped extends null | undefined ? never : NonNullable<typeof shaped>)['glyphs'][number]
+ >()
if (shaped) {
for (const g of shaped.glyphs) shapedByChar.set(g.firstCharacter, g)
}
@@ -207,7 +209,11 @@ export async function buildDerivedTextDataV4(
glyphs,
fontMetaData: [
{
- key: { family: normalizedFamily, style: weightToFigmaStyle(node.fontWeight, node.italic), postscript: '' },
+ key: {
+ family: normalizedFamily,
+ style: weightToFigmaStyle(node.fontWeight, node.italic),
+ postscript: ''
+ },
fontLineHeight: 1.2,
fontDigest: digestMap.get(key),
fontStyle: node.italic ? 'ITALIC' : 'NORMAL',
diff --git a/packages/core/src/text/outlines.ts b/packages/core/src/text/outlines.ts
index 876e5c190..aed765e6b 100644
--- a/packages/core/src/text/outlines.ts
+++ b/packages/core/src/text/outlines.ts
@@ -2,7 +2,11 @@ import { prepareWithSegments, layoutWithLines } from '@chenglou/pretext'
import type { CharacterStyleOverride, SceneNode } from '#core/scene-graph'
import { fontManager, weightToStyle } from '#core/text/fonts'
-import { fontHasGlyphSync, getGlyphOutlineMetricsSync, type OutlineCommand } from '#core/text/opentype'
+import {
+ fontHasGlyphSync,
+ getGlyphOutlineMetricsSync,
+ type OutlineCommand
+} from '#core/text/opentype'
export type TextOutlineUnsupportedReason =
| 'not-text'
@@ -29,7 +33,12 @@ export interface TextOutlineLayout {
const COMPLEX_SCRIPT_PATTERN = /[\u0590-\u08ff\u0900-\u0dff\ufb1d-\ufdff\ufe70-\ufeff]/
-type TextStyle = Required<Pick<CharacterStyleOverride, 'fontFamily' | 'fontSize' | 'fontWeight' | 'italic' | 'letterSpacing'>>
+type TextStyle = Required<
+ Pick<
+ CharacterStyleOverride,
+ 'fontFamily' | 'fontSize' | 'fontWeight' | 'italic' | 'letterSpacing'
+ >
+>
function baseTextStyle(node: SceneNode): TextStyle {
return {
@@ -66,7 +75,10 @@ function resolvedGlyphStyle(style: TextStyle, char: string): TextStyle | null {
if (fontHasGlyphSync(style.fontFamily, styleName(style), char)) return style
const family = fallbackFamilies().find((candidate) => {
const next = fallbackStyle(style, candidate)
- return fontManager.loadedData(next.fontFamily, styleName(next)) && fontHasGlyphSync(next.fontFamily, styleName(next), char)
+ return (
+ fontManager.loadedData(next.fontFamily, styleName(next)) &&
+ fontHasGlyphSync(next.fontFamily, styleName(next), char)
+ )
})
return family ? fallbackStyle(style, family) : null
}
@@ -130,7 +142,12 @@ function glyphAdvance(node: SceneNode, absoluteIndex: number): number | null {
const char = node.text[absoluteIndex]
const style = resolvedGlyphStyle(textStyleAt(node, absoluteIndex), char)
if (!style) return null
- const metrics = getGlyphOutlineMetricsSync(style.fontFamily, styleName(style), char, style.fontSize)
+ const metrics = getGlyphOutlineMetricsSync(
+ style.fontFamily,
+ styleName(style),
+ char,
+ style.fontSize
+ )
const glyph = metrics?.[0]
return glyph ? glyph.advance + style.letterSpacing : null
}
@@ -211,7 +228,12 @@ function verticalOffset(node: SceneNode, contentHeight: number): number {
}
}
-function lineGlyphs(node: SceneNode, line: TextLine, baseline: number, xOffset: number): { glyphs: TextOutlineGlyph[]; width: number } | null {
+function lineGlyphs(
+ node: SceneNode,
+ line: TextLine,
+ baseline: number,
+ xOffset: number
+): { glyphs: TextOutlineGlyph[]; width: number } | null {
const glyphs: TextOutlineGlyph[] = []
let cursorX = xOffset
let index = 0
@@ -229,7 +251,12 @@ function lineGlyphs(node: SceneNode, line: TextLine, baseline: number, xOffset:
}
const segment = line.text.slice(index, end)
- const metrics = getGlyphOutlineMetricsSync(style.fontFamily, styleName(style), segment, style.fontSize)
+ const metrics = getGlyphOutlineMetricsSync(
+ style.fontFamily,
+ styleName(style),
+ segment,
+ style.fontSize
+ )
if (!metrics) return null
for (const glyph of metrics) {
@@ -258,7 +285,10 @@ export function textNodeToOutlineLayout(node: SceneNode): TextOutlineLayout | nu
if (!measured) return null
const xOffset = lineOffsetX(node, measured.width)
maxWidth = Math.max(maxWidth, measured.width)
- const placed = xOffset === 0 ? measured.glyphs : measured.glyphs.map((glyph) => ({ ...glyph, x: glyph.x + xOffset }))
+ const placed =
+ xOffset === 0
+ ? measured.glyphs
+ : measured.glyphs.map((glyph) => ({ ...glyph, x: glyph.x + xOffset }))
glyphs.push(...placed)
}
diff --git a/packages/core/src/tools/analyze/clusters.ts b/packages/core/src/tools/analyze/clusters.ts
index ae2af8d9d..9ccf6a705 100644
--- a/packages/core/src/tools/analyze/clusters.ts
+++ b/packages/core/src/tools/analyze/clusters.ts
@@ -88,13 +88,13 @@ export const analyzeClusters = defineTool({
[...signatureMap.entries()]
.filter(([, nodes]) => nodes.length >= minCount)
.map(([signature, nodes]) => {
- const avgWidth = nodes.reduce((sum, node) => sum + node.width, 0) / nodes.length
- const avgHeight = nodes.reduce((sum, node) => sum + node.height, 0) / nodes.length
- const widths = nodes.map((node) => node.width)
- const heights = nodes.map((node) => node.height)
- const widthRange = Math.max(...widths) - Math.min(...widths)
- const heightRange = Math.max(...heights) - Math.min(...heights)
- const confidence = calcClusterConfidence(nodes)
+ const avgWidth = nodes.reduce((sum, node) => sum + node.width, 0) / nodes.length
+ const avgHeight = nodes.reduce((sum, node) => sum + node.height, 0) / nodes.length
+ const widths = nodes.map((node) => node.width)
+ const heights = nodes.map((node) => node.height)
+ const widthRange = Math.max(...widths) - Math.min(...widths)
+ const heightRange = Math.max(...heights) - Math.min(...heights)
+ const confidence = calcClusterConfidence(nodes)
return {
signature,
diff --git a/packages/core/src/tools/create/svg.ts b/packages/core/src/tools/create/svg.ts
index 8fd4dd45c..0cc5f71ff 100644
--- a/packages/core/src/tools/create/svg.ts
+++ b/packages/core/src/tools/create/svg.ts
@@ -4,7 +4,6 @@ import { extractPaths } from '#core/icons/svg'
import type { IconPathInfo } from '#core/icons/types'
import { parseSVGPath } from '#core/io/formats/svg/parse-path'
import { defineTool } from '#core/tools/schema'
-
import type { Rect } from '#core/types'
function parseSvgViewBox(svg: string): Rect | null {
diff --git a/packages/core/src/vector/centerline.ts b/packages/core/src/vector/centerline.ts
index 02951f3e2..2aa14d135 100644
--- a/packages/core/src/vector/centerline.ts
+++ b/packages/core/src/vector/centerline.ts
@@ -1,10 +1,10 @@
import type { CanvasKit, Path } from 'canvaskit-wasm'
-import { addOpenSegmentsToPath } from './path-helpers'
-
import type { VectorNetwork } from '#core/scene-graph'
import type { Vector } from '#core/types'
+import { addOpenSegmentsToPath } from './path-helpers'
+
export function fitCircleArc(
pts: Vector[]
): { cx: number; cy: number; r: number; startAngleDeg: number; sweepDeg: number } | null {
diff --git a/packages/core/src/vector/index.ts b/packages/core/src/vector/index.ts
index f0ee290c0..b286fc7d5 100644
--- a/packages/core/src/vector/index.ts
+++ b/packages/core/src/vector/index.ts
@@ -12,8 +12,6 @@ export {
import type { CanvasKit, Path } from 'canvaskit-wasm'
-import { addOpenSegmentsToPath, addSegmentDirected } from './path-helpers'
-
import type {
HandleMirroring,
VectorNetwork,
@@ -22,6 +20,8 @@ import type {
VectorVertex,
WindingRule
} from '#core/scene-graph'
+
+import { addOpenSegmentsToPath, addSegmentDirected } from './path-helpers'
export { vectorNetworkToCenterlinePath, fitCircleArc, isClosedThinCrescent } from './centerline'
// --- vectorNetworkBlob binary format ---
diff --git a/packages/mcp/src/index.ts b/packages/mcp/src/index.ts
index d30de022c..2edc7bf84 100644
--- a/packages/mcp/src/index.ts
+++ b/packages/mcp/src/index.ts
@@ -4,7 +4,9 @@ import { serve } from '@hono/node-server'
import { startServer } from './server.js'
if (process.argv.includes('--help') || process.argv.includes('-h')) {
- process.stdout.write(`openpencil-mcp-http\n\nStart the OpenPencil MCP HTTP and WebSocket server.\n\nOptions:\n --help, -h Show this help message\n`)
+ process.stdout.write(
+ `openpencil-mcp-http\n\nStart the OpenPencil MCP HTTP and WebSocket server.\n\nOptions:\n --help, -h Show this help message\n`
+ )
process.exit(0)
}
diff --git a/packages/mcp/src/stdio.ts b/packages/mcp/src/stdio.ts
index 6ef903b1d..186fbaa1f 100644
--- a/packages/mcp/src/stdio.ts
+++ b/packages/mcp/src/stdio.ts
@@ -6,7 +6,9 @@ import { MCP_VERSION, registerTools } from './server.js'
import { createStdioRpcBridge } from './stdio-bridge.js'
if (process.argv.includes('--help') || process.argv.includes('-h')) {
- process.stdout.write(`openpencil-mcp\n\nStart the OpenPencil MCP stdio bridge.\n\nOptions:\n --help, -h Show this help message\n`)
+ process.stdout.write(
+ `openpencil-mcp\n\nStart the OpenPencil MCP stdio bridge.\n\nOptions:\n --help, -h Show this help message\n`
+ )
process.exit(0)
}
diff --git a/packages/mcp/src/tool/registration.ts b/packages/mcp/src/tool/registration.ts
index 149b7f88d..d82083af8 100644
--- a/packages/mcp/src/tool/registration.ts
+++ b/packages/mcp/src/tool/registration.ts
@@ -69,12 +69,15 @@ export function registerTools(mcpServer: McpServer, options: RegisterToolsOption
? `Save the current document to disk. If path is provided, it must be inside ${resolvedRoot}.`
: 'Save the current document to disk. Uses the existing file path if available, otherwise prompts for a location.',
inputSchema: resolvedRoot
- ? z.object({ path: z.string().describe('Optional absolute path for the .fig file').optional() })
+ ? z.object({
+ path: z.string().describe('Optional absolute path for the .fig file').optional()
+ })
: z.object({})
},
async (args: { path?: string }) => {
try {
- const safePath = args.path && resolvedRoot ? resolveSafePath(args.path, resolvedRoot) : undefined
+ const safePath =
+ args.path && resolvedRoot ? resolveSafePath(args.path, resolvedRoot) : undefined
const result = await sendRpc({ command: 'save_file', args: { path: safePath } })
const res = result as { ok?: boolean; error?: string }
if (res.ok === false) return fail(new Error(res.error))
diff --git a/packages/vue/src/canvas/tool-input/use.ts b/packages/vue/src/canvas/tool-input/use.ts
index 815ecdac1..a522ef107 100644
--- a/packages/vue/src/canvas/tool-input/use.ts
+++ b/packages/vue/src/canvas/tool-input/use.ts
@@ -46,7 +46,18 @@ export function handleToolMouseDown({
}
if (tool === 'SELECT') {
- handleSelectDown(event, cx, cy, sx, sy, editor, hitFns, tryStartRotation, handleTextEditClick, setDrag)
+ handleSelectDown(
+ event,
+ cx,
+ cy,
+ sx,
+ sy,
+ editor,
+ hitFns,
+ tryStartRotation,
+ handleTextEditClick,
+ setDrag
+ )
return
}
diff --git a/packages/vue/src/canvas/useCanvasInput.ts b/packages/vue/src/canvas/useCanvasInput.ts
index 32ec36164..98e665de7 100644
--- a/packages/vue/src/canvas/useCanvasInput.ts
+++ b/packages/vue/src/canvas/useCanvasInput.ts
@@ -14,8 +14,8 @@ import { createCanvasPointer } from '#vue/canvas/pointer/use'
import { createTextEditInput } from '#vue/canvas/text-edit/input'
import { handleToolMouseDown } from '#vue/canvas/tool-input/use'
import { createCanvasTransformInput } from '#vue/canvas/transform-input/use'
-import { createClickCounter } from '#vue/shared/input/click-count'
import { resolveAutoLayoutHover } from '#vue/shared/input/auto-layout-hover'
+import { createClickCounter } from '#vue/shared/input/click-count'
import { handleDrawMove, handleDrawUp } from '#vue/shared/input/draw'
import { handleMoveMove, handleMoveUp } from '#vue/shared/input/move'
import { handleNodeEditMove } from '#vue/shared/input/node-edit'
diff --git a/packages/vue/src/controls/effects/helpers.ts b/packages/vue/src/controls/effects/helpers.ts
index 0583a4d1b..f8852923a 100644
--- a/packages/vue/src/controls/effects/helpers.ts
+++ b/packages/vue/src/controls/effects/helpers.ts
@@ -1,122 +1,112 @@
-import type { Editor } from "@open-pencil/core/editor";
-import type { Effect, SceneNode } from "@open-pencil/core/scene-graph";
-import type { Color } from "@open-pencil/core/types";
-import type { Ref } from "vue";
-import { useI18n } from "#vue/i18n/useI18n.js";
+import type { Ref } from 'vue'
-type EffectType = Effect["type"];
+import type { Editor } from '@open-pencil/core/editor'
+import type { Effect, SceneNode } from '@open-pencil/core/scene-graph'
+import type { Color } from '@open-pencil/core/types'
-const { panels } = useI18n();
+import { useI18n } from '#vue/i18n/useI18n.js'
+
+type EffectType = Effect['type']
+
+const { panels } = useI18n()
const EFFECT_LABELS: Record<string, string> = {
- DROP_SHADOW: panels.value.dropShadow || "Drop shadow",
- INNER_SHADOW: panels.value.innerShadow || "Inner shadow",
- LAYER_BLUR: panels.value.layerBlur || "Layer blur",
- BACKGROUND_BLUR: panels.value.backgroundBlur || "Background blur",
- FOREGROUND_BLUR: panels.value.foregroundBlur || "Foreground blur",
-};
-
-export const EFFECT_TYPES = Object.keys(EFFECT_LABELS) as EffectType[];
+ DROP_SHADOW: panels.value.dropShadow || 'Drop shadow',
+ INNER_SHADOW: panels.value.innerShadow || 'Inner shadow',
+ LAYER_BLUR: panels.value.layerBlur || 'Layer blur',
+ BACKGROUND_BLUR: panels.value.backgroundBlur || 'Background blur',
+ FOREGROUND_BLUR: panels.value.foregroundBlur || 'Foreground blur'
+}
+
+export const EFFECT_TYPES = Object.keys(EFFECT_LABELS) as EffectType[]
export const EFFECT_OPTIONS = EFFECT_TYPES.map((t) => ({
- value: t,
- label: EFFECT_LABELS[t],
-}));
+ value: t,
+ label: EFFECT_LABELS[t]
+}))
export function isShadow(type: string) {
- return type === "DROP_SHADOW" || type === "INNER_SHADOW";
+ return type === 'DROP_SHADOW' || type === 'INNER_SHADOW'
}
export function createDefaultEffect(): Effect {
- return {
- type: "DROP_SHADOW",
- color: { r: 0, g: 0, b: 0, a: 0.25 },
- offset: { x: 0, y: 4 },
- radius: 4,
- spread: 0,
- visible: true,
- };
+ return {
+ type: 'DROP_SHADOW',
+ color: { r: 0, g: 0, b: 0, a: 0.25 },
+ offset: { x: 0, y: 4 },
+ radius: 4,
+ spread: 0,
+ visible: true
+ }
}
-export function createEffectEditActions(
- editor: Editor,
- effectsBeforeScrub: Ref<Effect[] | null>,
-) {
- function scrubEffect(
- node: SceneNode | null,
- index: number,
- changes: Partial<Effect>,
- ) {
- if (!node) return;
- if (!effectsBeforeScrub.value) {
- effectsBeforeScrub.value = node.effects.map((e) => ({
- ...e,
- color: { ...e.color },
- offset: { ...e.offset },
- }));
- }
- 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;
- const previous = effectsBeforeScrub.value;
- effectsBeforeScrub.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 }, "Change effect");
- }
- }
-
- return { scrubEffect, commitEffect };
+export function createEffectEditActions(editor: Editor, effectsBeforeScrub: Ref<Effect[] | null>) {
+ function scrubEffect(node: SceneNode | null, index: number, changes: Partial<Effect>) {
+ if (!node) return
+ if (!effectsBeforeScrub.value) {
+ effectsBeforeScrub.value = node.effects.map((e) => ({
+ ...e,
+ color: { ...e.color },
+ offset: { ...e.offset }
+ }))
+ }
+ 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
+ const previous = effectsBeforeScrub.value
+ effectsBeforeScrub.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 }, 'Change effect')
+ }
+ }
+
+ return { scrubEffect, commitEffect }
}
export function createEffectControlActions(expandedIndex: Ref<number | null>) {
- function updateType(
- patch: (index: number, changes: Partial<Effect>) => void,
- node: SceneNode | null,
- index: number,
- type: EffectType,
- ) {
- if (!node) return;
- const changes: Partial<Effect> = { type };
- if (!isShadow(type)) {
- changes.offset = { x: 0, y: 0 };
- changes.spread = 0;
- } else if (!isShadow(node.effects[index].type)) {
- changes.offset = { x: 0, y: 4 };
- changes.spread = 0;
- }
- patch(index, changes);
- }
-
- function updateColor(
- patch: (index: number, changes: Partial<Effect>) => void,
- index: number,
- color: Color,
- ) {
- patch(index, { color });
- }
-
- function handleRemove(removeFn: (index: number) => void, index: number) {
- removeFn(index);
- if (expandedIndex.value === index) expandedIndex.value = null;
- else if (expandedIndex.value !== null && expandedIndex.value > index)
- expandedIndex.value--;
- }
-
- function toggleExpand(index: number) {
- expandedIndex.value = expandedIndex.value === index ? null : index;
- }
-
- return { updateType, updateColor, handleRemove, toggleExpand };
+ function updateType(
+ patch: (index: number, changes: Partial<Effect>) => void,
+ node: SceneNode | null,
+ index: number,
+ type: EffectType
+ ) {
+ if (!node) return
+ const changes: Partial<Effect> = { type }
+ if (!isShadow(type)) {
+ changes.offset = { x: 0, y: 0 }
+ changes.spread = 0
+ } else if (!isShadow(node.effects[index].type)) {
+ changes.offset = { x: 0, y: 4 }
+ changes.spread = 0
+ }
+ patch(index, changes)
+ }
+
+ function updateColor(
+ patch: (index: number, changes: Partial<Effect>) => void,
+ index: number,
+ color: Color
+ ) {
+ patch(index, { color })
+ }
+
+ function handleRemove(removeFn: (index: number) => void, index: number) {
+ removeFn(index)
+ if (expandedIndex.value === index) expandedIndex.value = null
+ else if (expandedIndex.value !== null && expandedIndex.value > index) expandedIndex.value--
+ }
+
+ function toggleExpand(index: number) {
+ expandedIndex.value = expandedIndex.value === index ? null : index
+ }
+
+ return { updateType, updateColor, handleRemove, toggleExpand }
}
diff --git a/packages/vue/src/controls/layout/helpers.ts b/packages/vue/src/controls/layout/helpers.ts
index 0ae268732..40f5166fa 100644
--- a/packages/vue/src/controls/layout/helpers.ts
+++ b/packages/vue/src/controls/layout/helpers.ts
@@ -252,7 +252,8 @@ export function createLayoutActions({
updateProp('primaryAxisSizing', 'HUG')
} else {
if (n.primaryAxisSizing === 'HUG') updateProp('primaryAxisSizing', 'FIXED')
- if (isInAutoLayout.value) updateProp('layoutAlignSelf', sizing === 'FILL' ? 'STRETCH' : 'AUTO')
+ if (isInAutoLayout.value)
+ updateProp('layoutAlignSelf', sizing === 'FILL' ? 'STRETCH' : 'AUTO')
}
}
diff --git a/packages/vue/src/controls/okhcl/helpers.ts b/packages/vue/src/controls/okhcl/helpers.ts
index 52d0bb6ad..761875b58 100644
--- a/packages/vue/src/controls/okhcl/helpers.ts
+++ b/packages/vue/src/controls/okhcl/helpers.ts
@@ -1,6 +1,5 @@
import type { Ref } from 'vue'
-import { BLACK } from '@open-pencil/core/constants'
import {
getFillOkHCL,
getStrokeOkHCL,
@@ -10,6 +9,7 @@ import {
setNodeStrokeOkHCL
} from '@open-pencil/core/color'
import type { OkHCLColor } from '@open-pencil/core/color'
+import { BLACK } from '@open-pencil/core/constants'
import type { Editor } from '@open-pencil/core/editor'
import type { SceneNode } from '@open-pencil/core/scene-graph'
@@ -30,17 +30,11 @@ export function getStrokeOkHCLColor(node: SceneNode | null, index: number): OkHC
}
function fallbackFillOkHCL(node: SceneNode, index: number) {
- return (
- getFillOkHCLColor(node, index) ??
- rgbaToOkHCL(node.fills[index]?.color ?? BLACK)
- )
+ return getFillOkHCLColor(node, index) ?? rgbaToOkHCL(node.fills[index]?.color ?? BLACK)
}
function fallbackStrokeOkHCL(node: SceneNode, index: number) {
- return (
- getStrokeOkHCLColor(node, index) ??
- rgbaToOkHCL(node.strokes[index]?.color ?? BLACK)
- )
+ return getStrokeOkHCLColor(node, index) ?? rgbaToOkHCL(node.strokes[index]?.color ?? BLACK)
}
export function createOkHCLActions(editor: Editor) {
diff --git a/packages/vue/src/i18n/messages.ts b/packages/vue/src/i18n/messages.ts
index 74b1279f9..ae4e07f05 100644
--- a/packages/vue/src/i18n/messages.ts
+++ b/packages/vue/src/i18n/messages.ts
@@ -1,401 +1,396 @@
-import { createI18n, params } from "@nanostores/i18n";
-import type { ComponentsJSON } from "@nanostores/i18n";
+import { createI18n, params } from '@nanostores/i18n'
+import type { ComponentsJSON } from '@nanostores/i18n'
-import { locale } from "#vue/i18n/locale";
-import type { Locale } from "#vue/i18n/locale";
+import { locale } from '#vue/i18n/locale'
+import type { Locale } from '#vue/i18n/locale'
-const localeLoaders: Record<
- Exclude<Locale, "en">,
- () => Promise<{ default: ComponentsJSON }>
-> = {
- de: () => import("#vue/locales/de.json"),
- es: () => import("#vue/locales/es.json"),
- fr: () => import("#vue/locales/fr.json"),
- it: () => import("#vue/locales/it.json"),
- pl: () => import("#vue/locales/pl.json"),
- ru: () => import("#vue/locales/ru.json"),
- "zh-CN": () => import("#vue/locales/zh-CN.json"),
-};
+const localeLoaders: Record<Exclude<Locale, 'en'>, () => Promise<{ default: ComponentsJSON }>> = {
+ de: () => import('#vue/locales/de.json'),
+ es: () => import('#vue/locales/es.json'),
+ fr: () => import('#vue/locales/fr.json'),
+ it: () => import('#vue/locales/it.json'),
+ pl: () => import('#vue/locales/pl.json'),
+ ru: () => import('#vue/locales/ru.json'),
+ 'zh-CN': () => import('#vue/locales/zh-CN.json')
+}
-const i18n = createI18n<Locale, "en">(locale, {
- baseLocale: "en",
- async get(code) {
- if (code === "en") return {};
- const mod = await localeLoaders[code]();
- return mod.default;
- },
-});
+const i18n = createI18n<Locale, 'en'>(locale, {
+ baseLocale: 'en',
+ async get(code) {
+ if (code === 'en') return {}
+ const mod = await localeLoaders[code]()
+ return mod.default
+ }
+})
-export const menuMessages = i18n("menu", {
- file: "File",
- edit: "Edit",
- view: "View",
- object: "Object",
- arrange: "Arrange",
- text: "Text",
+export const menuMessages = i18n('menu', {
+ file: 'File',
+ edit: 'Edit',
+ view: 'View',
+ object: 'Object',
+ arrange: 'Arrange',
+ text: 'Text',
- new: "New",
- open: "Open…",
- save: "Save",
- saveAs: "Save as…",
- exportSelection: "Export selection…",
- autosave: "Auto-save to local file",
- closeTab: "Close tab",
+ new: 'New',
+ open: 'Open…',
+ save: 'Save',
+ saveAs: 'Save as…',
+ exportSelection: 'Export selection…',
+ autosave: 'Auto-save to local file',
+ closeTab: 'Close tab',
- copy: "Copy",
- paste: "Paste",
+ copy: 'Copy',
+ paste: 'Paste',
- zoomIn: "Zoom in",
- zoomOut: "Zoom out",
- profiler: "Performance profiler",
- language: "Language",
- checkUpdates: "Check for updates…",
+ zoomIn: 'Zoom in',
+ zoomOut: 'Zoom out',
+ profiler: 'Performance profiler',
+ language: 'Language',
+ checkUpdates: 'Check for updates…',
- moveToPage: "Move to page",
- createInstance: "Create instance",
- hide: "Hide",
- show: "Show",
- lock: "Lock",
- unlock: "Unlock",
- cut: "Cut",
- front: "Front",
- back: "Back",
- toggleUI: "Toggle UI",
+ moveToPage: 'Move to page',
+ createInstance: 'Create instance',
+ hide: 'Hide',
+ show: 'Show',
+ lock: 'Lock',
+ unlock: 'Unlock',
+ cut: 'Cut',
+ front: 'Front',
+ back: 'Back',
+ toggleUI: 'Toggle UI',
- bold: "Bold",
- italic: "Italic",
- underline: "Underline",
- strikethrough: "Strikethrough",
+ bold: 'Bold',
+ italic: 'Italic',
+ underline: 'Underline',
+ strikethrough: 'Strikethrough',
- pasteHere: "Paste here",
- pasteToReplace: "Paste to replace",
- copyPasteAs: "Copy/Paste as",
- copyAsText: "Copy as text",
- copyAsSVG: "Copy as SVG",
- copyAsPNG: "Copy as PNG",
- copyAsJSX: "Copy as JSX",
- copyNodeId: "Copy node ID",
- copyXPath: "Copy XPath",
- booleanOperations: "Boolean operations",
-});
+ pasteHere: 'Paste here',
+ pasteToReplace: 'Paste to replace',
+ copyPasteAs: 'Copy/Paste as',
+ copyAsText: 'Copy as text',
+ copyAsSVG: 'Copy as SVG',
+ copyAsPNG: 'Copy as PNG',
+ copyAsJSX: 'Copy as JSX',
+ copyNodeId: 'Copy node ID',
+ copyXPath: 'Copy XPath',
+ booleanOperations: 'Boolean operations'
+})
-export const commandMessages = i18n("commands", {
- undo: "Undo",
- redo: "Redo",
- selectAll: "Select all",
- duplicate: "Duplicate",
- delete: "Delete",
- group: "Group",
- groupSelection: "Group selection",
- frameSelection: "Frame selection",
- ungroup: "Ungroup",
- createComponent: "Create component",
- createComponentSet: "Create component set",
- createInstance: "Create instance",
- detachInstance: "Detach instance",
- goToMainComponent: "Go to main component",
- addAutoLayout: "Add auto layout",
- bringToFront: "Bring to front",
- sendToBack: "Send to back",
- showHide: "Show/Hide",
- lockUnlock: "Lock/Unlock",
- unionSelection: "Union selection",
- subtractSelection: "Subtract selection",
- intersectSelection: "Intersect selection",
- excludeSelection: "Exclude selection",
- flattenSelection: "Flatten",
- outlineText: "Outline text",
- outlineStroke: "Outline stroke",
- booleanOperations: "Boolean operations",
- flipHorizontal: "Flip horizontal",
- flipVertical: "Flip vertical",
- moveToPage: "Move to page",
- zoomTo100: "Zoom to 100%",
- zoomToFit: "Zoom to fit",
- zoomToSelection: "Zoom to selection",
-});
+export const commandMessages = i18n('commands', {
+ undo: 'Undo',
+ redo: 'Redo',
+ selectAll: 'Select all',
+ duplicate: 'Duplicate',
+ delete: 'Delete',
+ group: 'Group',
+ groupSelection: 'Group selection',
+ frameSelection: 'Frame selection',
+ ungroup: 'Ungroup',
+ createComponent: 'Create component',
+ createComponentSet: 'Create component set',
+ createInstance: 'Create instance',
+ detachInstance: 'Detach instance',
+ goToMainComponent: 'Go to main component',
+ addAutoLayout: 'Add auto layout',
+ bringToFront: 'Bring to front',
+ sendToBack: 'Send to back',
+ showHide: 'Show/Hide',
+ lockUnlock: 'Lock/Unlock',
+ unionSelection: 'Union selection',
+ subtractSelection: 'Subtract selection',
+ intersectSelection: 'Intersect selection',
+ excludeSelection: 'Exclude selection',
+ flattenSelection: 'Flatten',
+ outlineText: 'Outline text',
+ outlineStroke: 'Outline stroke',
+ booleanOperations: 'Boolean operations',
+ flipHorizontal: 'Flip horizontal',
+ flipVertical: 'Flip vertical',
+ moveToPage: 'Move to page',
+ zoomTo100: 'Zoom to 100%',
+ zoomToFit: 'Zoom to fit',
+ zoomToSelection: 'Zoom to selection'
+})
-export const toolMessages = i18n("tools", {
- move: "Move",
- frame: "Frame",
- section: "Section",
- rectangle: "Rectangle",
- ellipse: "Ellipse",
- line: "Line",
- polygon: "Polygon",
- star: "Star",
- pen: "Pen",
- text: "Text",
- hand: "Hand",
-});
+export const toolMessages = i18n('tools', {
+ move: 'Move',
+ frame: 'Frame',
+ section: 'Section',
+ rectangle: 'Rectangle',
+ ellipse: 'Ellipse',
+ line: 'Line',
+ polygon: 'Polygon',
+ star: 'Star',
+ pen: 'Pen',
+ text: 'Text',
+ hand: 'Hand'
+})
-export const panelMessages = i18n("panels", {
- untitled: "Untitled",
- nodeCopyString: " copy",
- layers: "Layers",
- pages: "Pages",
- design: "Design",
- code: "Code",
- ai: "AI",
- assets: "Assets",
- searchLocalComponents: "Search local components",
- assetLibraryBadge: "Library",
- assetVariantSummary: params("{count} variants · {names}"),
- duplicateVariantValues: "Duplicate variant values",
- openDocumentation: "Open documentation",
- noLocalComponents: "No local components",
- componentSet: "Component set",
- component: "Component",
- insertInstance: "Insert instance",
- description: "Description",
- documentation: "Documentation",
- openDocs: "Open docs",
- properties: "Properties",
+export const panelMessages = i18n('panels', {
+ untitled: 'Untitled',
+ nodeCopyString: ' copy',
+ layers: 'Layers',
+ pages: 'Pages',
+ design: 'Design',
+ code: 'Code',
+ ai: 'AI',
+ assets: 'Assets',
+ searchLocalComponents: 'Search local components',
+ assetLibraryBadge: 'Library',
+ assetVariantSummary: params('{count} variants · {names}'),
+ duplicateVariantValues: 'Duplicate variant values',
+ openDocumentation: 'Open documentation',
+ noLocalComponents: 'No local components',
+ componentSet: 'Component set',
+ component: 'Component',
+ insertInstance: 'Insert instance',
+ description: 'Description',
+ documentation: 'Documentation',
+ openDocs: 'Open docs',
+ properties: 'Properties',
- xAxis: "X Axis",
- yAxis: "Y Axis",
- rotation: "Rotation",
- width: "Width",
- height: "Height",
- opacity: "Opacity",
- radius: "Radius",
- spread: "Spread",
+ xAxis: 'X Axis',
+ yAxis: 'Y Axis',
+ rotation: 'Rotation',
+ width: 'Width',
+ height: 'Height',
+ opacity: 'Opacity',
+ radius: 'Radius',
+ spread: 'Spread',
- page: "Page",
- position: "Position",
- layout: "Layout",
- autoLayout: "Auto layout",
- alignment: "Alignment",
- appearance: "Appearance",
- fill: "Fill",
- stroke: "Stroke",
- effects: "Effects",
- export: "Export",
- typography: "Typography",
- variables: "Variables",
- variants: "Variants",
- constraints: "Constraints",
+ page: 'Page',
+ position: 'Position',
+ layout: 'Layout',
+ autoLayout: 'Auto layout',
+ alignment: 'Alignment',
+ appearance: 'Appearance',
+ fill: 'Fill',
+ stroke: 'Stroke',
+ effects: 'Effects',
+ export: 'Export',
+ typography: 'Typography',
+ variables: 'Variables',
+ variants: 'Variants',
+ constraints: 'Constraints',
- addFill: "Add fill",
- addStroke: "Add stroke",
- addEffect: "Add effect",
- addExport: "Add export",
- removeFill: "Remove fill",
- removeStroke: "Remove stroke",
- removeEffect: "Remove effect",
- removeExport: "Remove export",
- effectSettings: "Effect settings",
- expandEffectSettings: "Expand effect settings",
- collapseEffectSettings: "Collapse effect settings",
- toggleExportPreview: "Toggle export preview",
+ addFill: 'Add fill',
+ addStroke: 'Add stroke',
+ addEffect: 'Add effect',
+ addExport: 'Add export',
+ removeFill: 'Remove fill',
+ removeStroke: 'Remove stroke',
+ removeEffect: 'Remove effect',
+ removeExport: 'Remove export',
+ effectSettings: 'Effect settings',
+ expandEffectSettings: 'Expand effect settings',
+ collapseEffectSettings: 'Collapse effect settings',
+ toggleExportPreview: 'Toggle export preview',
- dropShadow: "Drop shadow",
- innerShadow: "Inner shadow",
- layerBlur: "Layer blur",
- backgroundBlur: "Background blur",
- foregroundBlur: "Foreground blur",
+ dropShadow: 'Drop shadow',
+ innerShadow: 'Inner shadow',
+ layerBlur: 'Layer blur',
+ backgroundBlur: 'Background blur',
+ foregroundBlur: 'Foreground blur',
- strokeType: "Stroke type",
- strokeWeight: "Stroke weight",
+ strokeType: 'Stroke type',
+ strokeWeight: 'Stroke weight',
- noSelection: "No selection",
- noLocalVariables: "No local variables",
- openVariables: "Open variables",
- addPage: "Add page",
- toggleVisibility: "Toggle visibility",
- independentCornerRadii: "Independent corner radii",
- detachVariable: "Detach variable",
- applyVariable: "Apply variable",
- noVariablesFound: "No variables found",
- addAutoLayout: "Add auto layout",
- removeAutoLayout: "Remove auto layout",
- alignLeft: "Align left",
- alignCenterHorizontally: "Align center horizontally",
- alignRight: "Align right",
- alignTop: "Align top",
- alignCenterVertically: "Align center vertically",
- alignBottom: "Align bottom",
- flipHorizontal: "Flip horizontal",
- flipVertical: "Flip vertical",
- rotate90: "Rotate 90°",
- mixedFillsHelp: "Click + to replace mixed fills",
- mixedStrokesHelp: "Click + to replace mixed strokes",
- mixedEffectsHelp: "Click + to replace mixed effects",
- strokeSides: "Stroke sides",
- strokeDash: "Dashed stroke",
- strokeAlignInside: "Inside",
- strokeAlignCenter: "Center",
- strokeAlignOutside: "Outside",
- exportScale: "Export scale",
- exportFormat: "Export format",
- exportPreview: "Preview",
- exportRenderingPreview: "Rendering preview…",
- create: "Create",
- add: "Add",
- createVariable: "Create variable",
- createColorVariable: params("Create color variable from {value}"),
- createNumberVariable: params("Create number variable from {value}"),
- variableName: "Variable name",
- mixed: "Mixed",
- layersCount: params("{count} layers"),
- goToMainComponent: "Go to Main Component",
- detachInstance: "Detach Instance",
+ noSelection: 'No selection',
+ noLocalVariables: 'No local variables',
+ openVariables: 'Open variables',
+ addPage: 'Add page',
+ toggleVisibility: 'Toggle visibility',
+ independentCornerRadii: 'Independent corner radii',
+ detachVariable: 'Detach variable',
+ applyVariable: 'Apply variable',
+ noVariablesFound: 'No variables found',
+ addAutoLayout: 'Add auto layout',
+ removeAutoLayout: 'Remove auto layout',
+ alignLeft: 'Align left',
+ alignCenterHorizontally: 'Align center horizontally',
+ alignRight: 'Align right',
+ alignTop: 'Align top',
+ alignCenterVertically: 'Align center vertically',
+ alignBottom: 'Align bottom',
+ flipHorizontal: 'Flip horizontal',
+ flipVertical: 'Flip vertical',
+ rotate90: 'Rotate 90°',
+ mixedFillsHelp: 'Click + to replace mixed fills',
+ mixedStrokesHelp: 'Click + to replace mixed strokes',
+ mixedEffectsHelp: 'Click + to replace mixed effects',
+ strokeSides: 'Stroke sides',
+ strokeDash: 'Dashed stroke',
+ strokeAlignInside: 'Inside',
+ strokeAlignCenter: 'Center',
+ strokeAlignOutside: 'Outside',
+ exportScale: 'Export scale',
+ exportFormat: 'Export format',
+ exportPreview: 'Preview',
+ exportRenderingPreview: 'Rendering preview…',
+ create: 'Create',
+ add: 'Add',
+ createVariable: 'Create variable',
+ createColorVariable: params('Create color variable from {value}'),
+ createNumberVariable: params('Create number variable from {value}'),
+ variableName: 'Variable name',
+ mixed: 'Mixed',
+ layersCount: params('{count} layers'),
+ goToMainComponent: 'Go to Main Component',
+ detachInstance: 'Detach Instance',
- gap: "Gap",
+ gap: 'Gap',
- solid: "Solid",
- linearGradient: "Linear",
- radialGradient: "Radial",
- image: "Image",
- stops: "Stops",
- addStop: "Add stop",
+ solid: 'Solid',
+ linearGradient: 'Linear',
+ radialGradient: 'Radial',
+ image: 'Image',
+ stops: 'Stops',
+ addStop: 'Add stop',
- alignCenter: "Align center",
- alignMiddle: "Align middle",
- clipContent: "Clip content",
- colorFormatRgb: "RGB",
- colorFormatHsl: "HSL",
- colorFormatHsb: "HSB",
- colorFormatOkhcl: "OkHCL",
- colorHintHsl: "H hue · S saturation · L lightness",
- colorHintHsb: "H hue · S saturation · B brightness",
- colorHintOkhcl: "H hue · C chroma · L lightness · A alpha",
- colorPreviewClipped: params("Clipped to {space} preview gamut"),
- rulers: "Rulers",
- multiplayerCursors: "Multiplayer cursors",
- direction: "Direction",
- flow: "Flow",
- gapAuto: "Auto gap",
- horizontalGap: "Horizontal gap",
- verticalGap: "Vertical gap",
- auto: "Auto",
- columns: "Columns",
- rows: "Rows",
- sizingFixed: "Fixed",
- sizingHug: "Hug",
- sizingFill: "Fill",
- sizingHugShort: "Hug",
- sizingFillShort: "Fill",
- addMinWidth: "Add min width",
- removeMinWidth: "Remove min width",
- addMaxWidth: "Add max width",
- removeMaxWidth: "Remove max width",
- addMinHeight: "Add min height",
- removeMinHeight: "Remove min height",
- addMaxHeight: "Add max height",
- removeMaxHeight: "Remove max height",
- minWidthShort: "Min W",
- maxWidthShort: "Max W",
- minHeightShort: "Min H",
- maxHeightShort: "Max H",
- setToCurrentWidth: "Set to current width",
- setToCurrentHeight: "Set to current height",
- sizingFillFr: "Fill (fr)",
- sizingFixedPx: "Fixed (px)",
- searchFonts: "Search fonts...",
-});
+ alignCenter: 'Align center',
+ alignMiddle: 'Align middle',
+ clipContent: 'Clip content',
+ colorFormatRgb: 'RGB',
+ colorFormatHsl: 'HSL',
+ colorFormatHsb: 'HSB',
+ colorFormatOkhcl: 'OkHCL',
+ colorHintHsl: 'H hue · S saturation · L lightness',
+ colorHintHsb: 'H hue · S saturation · B brightness',
+ colorHintOkhcl: 'H hue · C chroma · L lightness · A alpha',
+ colorPreviewClipped: params('Clipped to {space} preview gamut'),
+ rulers: 'Rulers',
+ multiplayerCursors: 'Multiplayer cursors',
+ direction: 'Direction',
+ flow: 'Flow',
+ gapAuto: 'Auto gap',
+ horizontalGap: 'Horizontal gap',
+ verticalGap: 'Vertical gap',
+ auto: 'Auto',
+ columns: 'Columns',
+ rows: 'Rows',
+ sizingFixed: 'Fixed',
+ sizingHug: 'Hug',
+ sizingFill: 'Fill',
+ sizingHugShort: 'Hug',
+ sizingFillShort: 'Fill',
+ addMinWidth: 'Add min width',
+ removeMinWidth: 'Remove min width',
+ addMaxWidth: 'Add max width',
+ removeMaxWidth: 'Remove max width',
+ addMinHeight: 'Add min height',
+ removeMinHeight: 'Remove min height',
+ addMaxHeight: 'Add max height',
+ removeMaxHeight: 'Remove max height',
+ minWidthShort: 'Min W',
+ maxWidthShort: 'Max W',
+ minHeightShort: 'Min H',
+ maxHeightShort: 'Max H',
+ setToCurrentWidth: 'Set to current width',
+ setToCurrentHeight: 'Set to current height',
+ sizingFillFr: 'Fill (fr)',
+ sizingFixedPx: 'Fixed (px)',
+ searchFonts: 'Search fonts...'
+})
-export const variableTypeMessages = i18n("variableTypes", {
- color: "Color",
- colorHint: "Paint values",
- number: "Number",
- numberHint: "Sizes, spacing, opacity",
- text: "Text",
- textHint: "Copy and labels",
- boolean: "Boolean",
- booleanHint: "True or false",
-});
+export const variableTypeMessages = i18n('variableTypes', {
+ color: 'Color',
+ colorHint: 'Paint values',
+ number: 'Number',
+ numberHint: 'Sizes, spacing, opacity',
+ text: 'Text',
+ textHint: 'Copy and labels',
+ boolean: 'Boolean',
+ booleanHint: 'True or false'
+})
-export const pageMessages = i18n("pages", {
- newPage: "New page",
- rename: "Rename",
- delete: "Delete",
- pageName: params("Page {number}"),
-});
+export const pageMessages = i18n('pages', {
+ newPage: 'New page',
+ rename: 'Rename',
+ delete: 'Delete',
+ pageName: params('Page {number}')
+})
-export const dialogMessages = i18n("dialogs", {
- cancel: "Cancel",
- apply: "Apply",
- close: "Close",
- ok: "OK",
- copy: "Copy",
- copied: "Copied",
- copiedExclamation: "Copied!",
- copyMessage: "Copy message",
- createCollection: "Create collection",
- renameCollection: "Rename collection",
- deleteCollection: "Delete collection",
- localVariables: "Local variables",
- noVariableCollections: "No variable collections",
- modes: "Modes",
- addMode: "Add mode",
- renameMode: "Rename mode",
- duplicateMode: "Duplicate mode",
- deleteMode: "Delete mode",
- setDefaultMode: "Set as default",
- selectLayerForJSX: "Select a layer to see its JSX code",
- copyJSXReference: "Copy JSX prop reference to clipboard",
- newTab: "New tab",
- closeTab: params("Close {name}"),
- showUI: params("Show UI ({shortcut})"),
- fontSettings: "Font settings",
- you: "You",
- youSuffix: "you",
- followingPeerStop: params("Following {name} (click to stop)"),
- clickToFollowPeer: params("Click to follow {name}"),
- connectAIProvider: "Connect an AI provider to start chatting.",
- connect: "Connect",
- getAPIKey: params("Get an {provider} API key →"),
- oneKeyManyModels: "One key for 100+ models from all providers.",
- describeChange: "Describe a change…",
- describeCreateOrChange: "Describe what you want to create or change.",
- stopGenerating: "Stop generating",
- sendMessage: "Send message",
- baseURLPlaceholder: "Base URL (e.g. http://localhost:11434/v1)",
- modelIDPlaceholder: "Model ID (e.g. llama-3.3-70b)",
- aiProvider: "AI Provider",
- providerSettings: "Provider settings",
- done: "Done",
- apiKey: "API Key",
- apiType: "API Type",
- baseURL: "Base URL",
- modelID: "Model ID",
- maxOutputTokens: "Max output tokens",
- clear: "Clear",
- keySavedReplace: "Key saved — enter new to replace",
- getAPIKeyGeneric: "Get API key →",
- pexelsAPIKey: "Pexels API Key (stock photos)",
- unsplashAccessKey: "Unsplash Access Key",
- stockPhotoToolOptional: "Optional — for stock_photo tool",
- pexelsAlternativeOptional: "Optional — alternative to Pexels",
- getPexelsAPIKey: "Get free Pexels API key →",
- getUnsplashAccessKey: "Get free Unsplash access key →",
- completions: "Completions",
- responses: "Responses",
- yourName: "Your name",
- enterYourName: "Enter your name",
- shareThisFile: "Share this file",
- joinRoom: "Join room",
- join: "Join",
- roomLink: "Room link",
- joinCollaboration: "Join collaboration",
- orJoinRoom: "or join a room",
- pasteRoomLinkOrId: "Paste room link or ID",
- connected: "Connected",
- search: "Search…",
- noResults: "No results",
- share: "Share",
- appUpToDate: "OpenPencil is up to date",
- updateAvailableTitle: "Update OpenPencil",
- updateAvailable: params("OpenPencil {version} is available."),
- updateInstallPrompt:
- "Download and install it now? The app will restart after the update is installed.",
- downloadingUpdate: params("Downloading OpenPencil {version}"),
- updateInstalledTitle: "Update installed",
- updateInstalled: params(
- "OpenPencil {version} was installed{size}. Restarting now.",
- ),
- updateUnavailable:
- "Updates are not available yet. Publish a signed release with latest.json first.",
- updateCheckFailed: params("Could not check for updates: {error}"),
-});
+export const dialogMessages = i18n('dialogs', {
+ cancel: 'Cancel',
+ apply: 'Apply',
+ close: 'Close',
+ ok: 'OK',
+ copy: 'Copy',
+ copied: 'Copied',
+ copiedExclamation: 'Copied!',
+ copyMessage: 'Copy message',
+ createCollection: 'Create collection',
+ renameCollection: 'Rename collection',
+ deleteCollection: 'Delete collection',
+ localVariables: 'Local variables',
+ noVariableCollections: 'No variable collections',
+ modes: 'Modes',
+ addMode: 'Add mode',
+ renameMode: 'Rename mode',
+ duplicateMode: 'Duplicate mode',
+ deleteMode: 'Delete mode',
+ setDefaultMode: 'Set as default',
+ selectLayerForJSX: 'Select a layer to see its JSX code',
+ copyJSXReference: 'Copy JSX prop reference to clipboard',
+ newTab: 'New tab',
+ closeTab: params('Close {name}'),
+ showUI: params('Show UI ({shortcut})'),
+ fontSettings: 'Font settings',
+ you: 'You',
+ youSuffix: 'you',
+ followingPeerStop: params('Following {name} (click to stop)'),
+ clickToFollowPeer: params('Click to follow {name}'),
+ connectAIProvider: 'Connect an AI provider to start chatting.',
+ connect: 'Connect',
+ getAPIKey: params('Get an {provider} API key →'),
+ oneKeyManyModels: 'One key for 100+ models from all providers.',
+ describeChange: 'Describe a change…',
+ describeCreateOrChange: 'Describe what you want to create or change.',
+ stopGenerating: 'Stop generating',
+ sendMessage: 'Send message',
+ baseURLPlaceholder: 'Base URL (e.g. http://localhost:11434/v1)',
+ modelIDPlaceholder: 'Model ID (e.g. llama-3.3-70b)',
+ aiProvider: 'AI Provider',
+ providerSettings: 'Provider settings',
+ done: 'Done',
+ apiKey: 'API Key',
+ apiType: 'API Type',
+ baseURL: 'Base URL',
+ modelID: 'Model ID',
+ maxOutputTokens: 'Max output tokens',
+ clear: 'Clear',
+ keySavedReplace: 'Key saved — enter new to replace',
+ getAPIKeyGeneric: 'Get API key →',
+ pexelsAPIKey: 'Pexels API Key (stock photos)',
+ unsplashAccessKey: 'Unsplash Access Key',
+ stockPhotoToolOptional: 'Optional — for stock_photo tool',
+ pexelsAlternativeOptional: 'Optional — alternative to Pexels',
+ getPexelsAPIKey: 'Get free Pexels API key →',
+ getUnsplashAccessKey: 'Get free Unsplash access key →',
+ completions: 'Completions',
+ responses: 'Responses',
+ yourName: 'Your name',
+ enterYourName: 'Enter your name',
+ shareThisFile: 'Share this file',
+ joinRoom: 'Join room',
+ join: 'Join',
+ roomLink: 'Room link',
+ joinCollaboration: 'Join collaboration',
+ orJoinRoom: 'or join a room',
+ pasteRoomLinkOrId: 'Paste room link or ID',
+ connected: 'Connected',
+ search: 'Search…',
+ noResults: 'No results',
+ share: 'Share',
+ appUpToDate: 'OpenPencil is up to date',
+ updateAvailableTitle: 'Update OpenPencil',
+ updateAvailable: params('OpenPencil {version} is available.'),
+ updateInstallPrompt:
+ 'Download and install it now? The app will restart after the update is installed.',
+ downloadingUpdate: params('Downloading OpenPencil {version}'),
+ updateInstalledTitle: 'Update installed',
+ updateInstalled: params('OpenPencil {version} was installed{size}. Restarting now.'),
+ updateUnavailable:
+ 'Updates are not available yet. Publish a signed release with latest.json first.',
+ updateCheckFailed: params('Could not check for updates: {error}')
+})
diff --git a/packages/vue/src/locales/es.json b/packages/vue/src/locales/es.json
index d8c6ae88f..c889c50d3 100644
--- a/packages/vue/src/locales/es.json
+++ b/packages/vue/src/locales/es.json
@@ -1,349 +1,349 @@
{
- "menu": {
- "file": "Archivo",
- "edit": "Editar",
- "view": "Ver",
- "object": "Objeto",
- "arrange": "Organizar",
- "text": "Texto",
- "new": "Nuevo",
- "open": "Abrir…",
- "save": "Guardar",
- "saveAs": "Guardar como…",
- "exportSelection": "Exportar selección…",
- "autosave": "Guardado automático en archivo",
- "copy": "Copiar",
- "paste": "Pegar",
- "zoomIn": "Ampliar",
- "zoomOut": "Reducir",
- "profiler": "Perfil de rendimiento",
- "language": "Idioma",
- "moveToPage": "Mover a página",
- "createInstance": "Crear instancia",
- "hide": "Ocultar",
- "show": "Mostrar",
- "lock": "Bloquear",
- "unlock": "Desbloquear",
- "cut": "Cortar",
- "front": "Al frente",
- "back": "Al fondo",
- "toggleUI": "Alternar interfaz",
- "bold": "Negrita",
- "italic": "Cursiva",
- "underline": "Subrayado",
- "pasteHere": "Pegar aquí",
- "pasteToReplace": "Pegar y reemplazar",
- "copyPasteAs": "Copiar/Pegar como",
- "copyAsText": "Copiar como texto",
- "copyAsSVG": "Copiar como SVG",
- "copyAsPNG": "Copiar como PNG",
- "copyAsJSX": "Copiar como JSX",
- "copyNodeId": "Copiar ID del nodo",
- "copyXPath": "Copiar XPath",
- "checkUpdates": "Buscar actualizaciones…",
- "booleanOperations": "Operaciones booleanas",
- "strikethrough": "Tachado"
- },
- "commands": {
- "undo": "Deshacer",
- "redo": "Rehacer",
- "selectAll": "Seleccionar todo",
- "duplicate": "Duplicar",
- "delete": "Eliminar",
- "group": "Agrupar",
- "ungroup": "Desagrupar",
- "createComponent": "Crear componente",
- "createComponentSet": "Crear conjunto de componentes",
- "createInstance": "Crear instancia",
- "detachInstance": "Separar instancia",
- "goToMainComponent": "Ir al componente principal",
- "addAutoLayout": "Añadir auto-layout",
- "bringToFront": "Traer al frente",
- "sendToBack": "Enviar al fondo",
- "moveToPage": "Mover a página",
- "zoomTo100": "Zoom 100 %",
- "zoomToFit": "Ajustar a pantalla",
- "zoomToSelection": "Zoom a selección",
- "groupSelection": "Agrupar",
- "frameSelection": "Selección de marco",
- "showHide": "Visibilidad",
- "lockUnlock": "Bloqueo",
- "unionSelection": "Selección de unión",
- "subtractSelection": "Selección de sustración",
- "intersectSelection": "Selección de intersección",
- "excludeSelection": "Selección de exclusión",
- "booleanOperations": "Operaciones boolean",
- "flipHorizontal": "Voltear horizontalmente",
- "flipVertical": "Voltear verticalmente",
- "flattenSelection": "Aplanar",
- "outlineText": "Contornear texto",
- "outlineStroke": "Cortornear trazo"
- },
- "tools": {
- "move": "Mover",
- "frame": "Marco",
- "section": "Sección",
- "rectangle": "Rectángulo",
- "ellipse": "Elipse",
- "line": "Línea",
- "polygon": "Polígono",
- "star": "Estrella",
- "pen": "Pluma",
- "text": "Texto",
- "hand": "Mano"
- },
- "panels": {
- "untitled": "Sin título",
- "nodeCopyString": " copia",
- "layers": "Capas",
- "pages": "Páginas",
- "design": "Diseño",
- "code": "Código",
- "ai": "IA",
- "assets": "Recursos",
- "page": "Página",
- "position": "Posición",
- "layout": "Diseño",
- "autoLayout": "Auto-layout",
- "alignment": "Alineación",
- "appearance": "Apariencia",
- "xAxis": "Eje X",
- "yAxis": "Eje Y",
- "rotation": "Rotación",
- "width": "Anchura",
- "height": "Altura",
- "opacity": "Opacidad",
- "radius": "Redondeado",
- "spread": "Esparcimiento",
- "fill": "Relleno",
- "stroke": "Trazo",
- "effects": "Efectos",
- "export": "Exportar",
- "typography": "Tipografía",
- "variables": "Variables",
- "constraints": "Restricciones",
- "addFill": "Añadir relleno",
- "addStroke": "Añadir trazo",
- "addEffect": "Añadir efecto",
- "addExport": "Añadir exportación",
- "dropShadow": "Sombra exterior",
- "innerShadow": "Sombra interior",
- "layerBlur": "Desenfoque de capa",
- "backgroundBlur": "Desenfoque de fondo",
- "foregroundBlur": "Desenfoque",
- "strokeType": "Tipo de trazado",
- "strokeWeight": "Grosor del trazado",
- "noSelection": "Sin selección",
- "noLocalVariables": "Sin variables locales",
- "openVariables": "Abrir variables",
- "addPage": "Añadir página",
- "toggleVisibility": "Alternar visibilidad",
- "independentCornerRadii": "Redondeo de esquina independientes",
- "detachVariable": "Desvincular variable",
- "applyVariable": "Aplicar variable",
- "noVariablesFound": "No se encontraron variables",
- "addAutoLayout": "Añadir auto-layout",
- "removeAutoLayout": "Quitar auto-layout",
- "mixed": "Mixto",
- "layersCount": "{count} capas",
- "goToMainComponent": "Ir al componente principal",
- "detachInstance": "Separar instancia",
- "solid": "Sólido",
- "linearGradient": "Lineal",
- "radialGradient": "Radial",
- "image": "Imagen",
- "stops": "Paradas",
- "addStop": "Añadir parada",
- "alignLeft": "Alinear a la izquierda",
- "alignCenter": "Centrar",
- "alignRight": "Alinear a la derecha",
- "alignTop": "Alinear arriba",
- "alignMiddle": "Centrar verticalmente",
- "alignBottom": "Alinear abajo",
- "alignCenterHorizontally": "Centrar horizontalmente",
- "alignCenterVertically": "Centrar verticalmente",
- "flipHorizontal": "Voltear horizontalmente",
- "flipVertical": "Voltear verticalmente",
- "rotate90": "Girar 90°",
- "mixedFillsHelp": "Haz clic en + para reemplazar rellenos mixtos",
- "mixedStrokesHelp": "Haz clic en + para reemplazar trazos mixtos",
- "mixedEffectsHelp": "Haz clic en + para reemplazar efectos mixtos",
- "strokeSides": "Lados del trazo",
- "clipContent": "Recortar contenido",
- "colorFormatRgb": "RGB",
- "colorFormatHsl": "HSL",
- "colorFormatHsb": "HSB",
- "colorFormatOkhcl": "OkHCL",
- "colorHintHsl": "H tono · S saturación · L luminosidad",
- "colorHintHsb": "H tono · S saturación · B brillo",
- "colorHintOkhcl": "H tono · C croma · L luminosidad · A alfa",
- "colorPreviewClipped": "Recortado a gama de vista previa {space}",
- "rulers": "Reglas",
- "multiplayerCursors": "Cursores de otros participantes",
- "direction": "Dirección",
- "flow": "Flujo",
- "auto": "Auto",
- "columns": "Columnas",
- "rows": "Filas",
- "gap": "Espaciado",
- "sizingFixed": "Fijo",
- "sizingHug": "Ajustar al contenido",
- "sizingFill": "Rellenar",
- "sizingHugShort": "Ajust.",
- "sizingFillShort": "Llenar",
- "sizingFillFr": "Rellenar (fr)",
- "sizingFixedPx": "Fijo (px)",
- "strokeAlignInside": "Interior",
- "strokeAlignCenter": "Centro",
- "strokeAlignOutside": "Exterior",
- "exportScale": "Escala de exportación",
- "exportFormat": "Formato de exportación",
- "exportPreview": "Vista previa",
- "exportRenderingPreview": "Renderizando vista previa…",
- "createVariable": "Crear variable",
- "createColorVariable": "Crear variable de color desde {value}",
- "variableName": "Nombre de variable",
- "create": "Crear",
- "createNumberVariable": "Crear variable numérica desde {value}",
- "strokeDash": "Trazo discontinuo",
- "add": "Añadir",
- "variants": "Variantes",
- "gapAuto": "Espaciado auto",
- "horizontalGap": "Espaciado horizontal",
- "verticalGap": "Espaciado vertical",
- "addMinWidth": "Agregar ancho min",
- "removeMinWidth": "Eliminar ancho min",
- "addMaxWidth": "Agregar ancho max",
- "removeMaxWidth": "Eliminar ancho max",
- "addMinHeight": "Agregar alto min",
- "removeMinHeight": "Eliminar alto min",
- "addMaxHeight": "Agregar alto max",
- "removeMaxHeight": "Eliminar alto max",
- "minWidthShort": "Min A",
- "maxWidthShort": "Max A",
- "minHeightShort": "Min Al",
- "maxHeightShort": "Max Al",
- "setToCurrentWidth": "Establecer ancho actual",
- "setToCurrentHeight": "Establecer alto actual",
- "searchLocalComponents": "Buscar componentes locales",
- "assetLibraryBadge": "Biblioteca",
- "assetVariantSummary": "{count} variantes · {names}",
- "duplicateVariantValues": "Valores de variante duplicados",
- "openDocumentation": "Abrir documentación",
- "noLocalComponents": "No hay componentes locales",
- "componentSet": "Conjunto de componentes",
- "component": "Componente",
- "insertInstance": "Insertar instancia",
- "description": "Descripción",
- "documentation": "Documentación",
- "openDocs": "Abrir docs",
- "properties": "Propiedades",
- "removeFill": "Eliminar relleno",
- "removeStroke": "Eliminar trazo",
- "removeEffect": "Eliminar efecto",
- "removeExport": "Eliminar exportación",
- "effectSettings": "Ajustes del efecto",
- "expandEffectSettings": "Expandir ajustes del efecto",
- "collapseEffectSettings": "Contraer ajustes del efecto",
- "toggleExportPreview": "Alternar vista previa de exportación",
- "searchFonts": "Buscar fuentes..."
- },
- "pages": {
- "newPage": "Nueva página",
- "rename": "Renombrar",
- "delete": "Eliminar",
- "pageName": "Página {number}"
- },
- "dialogs": {
- "cancel": "Cancelar",
- "apply": "Aplicar",
- "close": "Cerrar",
- "ok": "Aceptar",
- "copy": "Copiar",
- "copied": "Copiado",
- "createCollection": "Crear colección",
- "localVariables": "Variables locales",
- "noVariableCollections": "No hay colecciones de variables",
- "selectLayerForJSX": "Selecciona una capa para ver su código JSX",
- "connectAIProvider": "Conecta un proveedor de IA para empezar a chatear.",
- "connect": "Conectar",
- "getAPIKey": "Obtener una clave API de {provider} →",
- "oneKeyManyModels": "Una clave para más de 100 modelos de todos los proveedores.",
- "describeChange": "Describe un cambio…",
- "describeCreateOrChange": "Describe lo que quieres crear o cambiar.",
- "stopGenerating": "Detener generación",
- "sendMessage": "Enviar mensaje",
- "baseURLPlaceholder": "Base URL (p. ej. http://localhost:11434/v1)",
- "modelIDPlaceholder": "Model ID (p. ej. llama-3.3-70b)",
- "yourName": "Tu nombre",
- "enterYourName": "Introduce tu nombre",
- "shareThisFile": "Compartir este archivo",
- "joinRoom": "Unirse a la sala",
- "join": "Unirse",
- "roomLink": "Enlace de la sala",
- "joinCollaboration": "Unirse a la colaboración",
- "orJoinRoom": "o unirse a una sala",
- "pasteRoomLinkOrId": "Pega el enlace o ID de la sala",
- "connected": "Conectado",
- "search": "Buscar…",
- "noResults": "Sin resultados",
- "share": "Compartir",
- "appUpToDate": "OpenPencil está actualizado",
- "updateAvailableTitle": "Actualizar OpenPencil",
- "updateAvailable": "Está disponible la versión {version} de OpenPencil.",
- "updateInstallPrompt": "¿Descargar e instalar ahora? La app se reiniciará después de instalar la actualización.",
- "downloadingUpdate": "Descargando OpenPencil {version}",
- "updateInstalledTitle": "Actualización instalada",
- "updateInstalled": "Se ha instalado la versión {version} de OpenPencil. Reiniciando ahora...",
- "updateCheckFailed": "Error al encontrar actualizaciones: {error}",
- "updateUnavailable": "Las actualizaciones aún no están disponibles. Publica primero una versión firmada con latest.json.",
- "renameCollection": "Renombrar coleccion",
- "deleteCollection": "Eliminar coleccion",
- "modes": "Modos",
- "addMode": "Agregar modo",
- "renameMode": "Renombrar modo",
- "duplicateMode": "Duplicar modo",
- "deleteMode": "Eliminar modo",
- "setDefaultMode": "Establecer como predeterminado",
- "aiProvider": "Proveedor IA",
- "providerSettings": "Opciones del proveedor",
- "done": "Hecho",
- "apiKey": "Clave API",
- "apiType": "Tipo API",
- "baseURL": "URL base",
- "modelID": "ID Modelo",
- "maxOutputTokens": "Tokens de salida máx.",
- "clear": "Limpiar",
- "keySavedReplace": "Clave guardada - introduce una nueva para reemplazarla",
- "getAPIKeyGeneric": "Obtener clave API →",
- "pexelsAPIKey": "Clave API de Pexels (fotos stock)",
- "unsplashAccessKey": "Clave de acceso de Unsplash",
- "stockPhotoToolOptional": "Opcional — para herramienta stock_photo",
- "pexelsAlternativeOptional": "Opcional — alternativa a Pexels",
- "getPexelsAPIKey": "Obtener clave a la API gratis de Pexels →",
- "getUnsplashAccessKey": "Obtener clave a la API gratis de Unsplash →",
- "completions": "Completados",
- "responses": "Respuestas",
- "copiedExclamation": "¡Copiado!",
- "copyMessage": "Copiar mensaje",
- "copyJSXReference": "Copiar referencia de props JSX al portapapeles",
- "newTab": "Nueva pestaña",
- "closeTab": "Cerrar {name}",
- "showUI": "Mostrar interfaz ({shortcut})",
- "fontSettings": "Ajustes de fuentes",
- "you": "Tú",
- "youSuffix": "tú",
- "followingPeerStop": "Siguiendo a {name} (haz clic para detener)",
- "clickToFollowPeer": "Haz clic para seguir a {name}"
- },
- "variableTypes": {
- "color": "Color",
- "colorHint": "Valores de pintura",
- "number": "Número",
- "numberHint": "Tamaños, espaciado, opacidad",
- "text": "Texto",
- "textHint": "Texto y etiquetas",
- "boolean": "Booleano",
- "booleanHint": "Verdadero o falso"
- }
+ "menu": {
+ "file": "Archivo",
+ "edit": "Editar",
+ "view": "Ver",
+ "object": "Objeto",
+ "arrange": "Organizar",
+ "text": "Texto",
+ "new": "Nuevo",
+ "open": "Abrir…",
+ "save": "Guardar",
+ "saveAs": "Guardar como…",
+ "exportSelection": "Exportar selección…",
+ "autosave": "Guardado automático en archivo",
+ "copy": "Copiar",
+ "paste": "Pegar",
+ "zoomIn": "Ampliar",
+ "zoomOut": "Reducir",
+ "profiler": "Perfil de rendimiento",
+ "language": "Idioma",
+ "moveToPage": "Mover a página",
+ "createInstance": "Crear instancia",
+ "hide": "Ocultar",
+ "show": "Mostrar",
+ "lock": "Bloquear",
+ "unlock": "Desbloquear",
+ "cut": "Cortar",
+ "front": "Al frente",
+ "back": "Al fondo",
+ "toggleUI": "Alternar interfaz",
+ "bold": "Negrita",
+ "italic": "Cursiva",
+ "underline": "Subrayado",
+ "pasteHere": "Pegar aquí",
+ "pasteToReplace": "Pegar y reemplazar",
+ "copyPasteAs": "Copiar/Pegar como",
+ "copyAsText": "Copiar como texto",
+ "copyAsSVG": "Copiar como SVG",
+ "copyAsPNG": "Copiar como PNG",
+ "copyAsJSX": "Copiar como JSX",
+ "copyNodeId": "Copiar ID del nodo",
+ "copyXPath": "Copiar XPath",
+ "checkUpdates": "Buscar actualizaciones…",
+ "booleanOperations": "Operaciones booleanas",
+ "strikethrough": "Tachado"
+ },
+ "commands": {
+ "undo": "Deshacer",
+ "redo": "Rehacer",
+ "selectAll": "Seleccionar todo",
+ "duplicate": "Duplicar",
+ "delete": "Eliminar",
+ "group": "Agrupar",
+ "ungroup": "Desagrupar",
+ "createComponent": "Crear componente",
+ "createComponentSet": "Crear conjunto de componentes",
+ "createInstance": "Crear instancia",
+ "detachInstance": "Separar instancia",
+ "goToMainComponent": "Ir al componente principal",
+ "addAutoLayout": "Añadir auto-layout",
+ "bringToFront": "Traer al frente",
+ "sendToBack": "Enviar al fondo",
+ "moveToPage": "Mover a página",
+ "zoomTo100": "Zoom 100 %",
+ "zoomToFit": "Ajustar a pantalla",
+ "zoomToSelection": "Zoom a selección",
+ "groupSelection": "Agrupar",
+ "frameSelection": "Selección de marco",
+ "showHide": "Visibilidad",
+ "lockUnlock": "Bloqueo",
+ "unionSelection": "Selección de unión",
+ "subtractSelection": "Selección de sustración",
+ "intersectSelection": "Selección de intersección",
+ "excludeSelection": "Selección de exclusión",
+ "booleanOperations": "Operaciones boolean",
+ "flipHorizontal": "Voltear horizontalmente",
+ "flipVertical": "Voltear verticalmente",
+ "flattenSelection": "Aplanar",
+ "outlineText": "Contornear texto",
+ "outlineStroke": "Cortornear trazo"
+ },
+ "tools": {
+ "move": "Mover",
+ "frame": "Marco",
+ "section": "Sección",
+ "rectangle": "Rectángulo",
+ "ellipse": "Elipse",
+ "line": "Línea",
+ "polygon": "Polígono",
+ "star": "Estrella",
+ "pen": "Pluma",
+ "text": "Texto",
+ "hand": "Mano"
+ },
+ "panels": {
+ "untitled": "Sin título",
+ "nodeCopyString": " copia",
+ "layers": "Capas",
+ "pages": "Páginas",
+ "design": "Diseño",
+ "code": "Código",
+ "ai": "IA",
+ "assets": "Recursos",
+ "page": "Página",
+ "position": "Posición",
+ "layout": "Diseño",
+ "autoLayout": "Auto-layout",
+ "alignment": "Alineación",
+ "appearance": "Apariencia",
+ "xAxis": "Eje X",
+ "yAxis": "Eje Y",
+ "rotation": "Rotación",
+ "width": "Anchura",
+ "height": "Altura",
+ "opacity": "Opacidad",
+ "radius": "Redondeado",
+ "spread": "Esparcimiento",
+ "fill": "Relleno",
+ "stroke": "Trazo",
+ "effects": "Efectos",
+ "export": "Exportar",
+ "typography": "Tipografía",
+ "variables": "Variables",
+ "constraints": "Restricciones",
+ "addFill": "Añadir relleno",
+ "addStroke": "Añadir trazo",
+ "addEffect": "Añadir efecto",
+ "addExport": "Añadir exportación",
+ "dropShadow": "Sombra exterior",
+ "innerShadow": "Sombra interior",
+ "layerBlur": "Desenfoque de capa",
+ "backgroundBlur": "Desenfoque de fondo",
+ "foregroundBlur": "Desenfoque",
+ "strokeType": "Tipo de trazado",
+ "strokeWeight": "Grosor del trazado",
+ "noSelection": "Sin selección",
+ "noLocalVariables": "Sin variables locales",
+ "openVariables": "Abrir variables",
+ "addPage": "Añadir página",
+ "toggleVisibility": "Alternar visibilidad",
+ "independentCornerRadii": "Redondeo de esquina independientes",
+ "detachVariable": "Desvincular variable",
+ "applyVariable": "Aplicar variable",
+ "noVariablesFound": "No se encontraron variables",
+ "addAutoLayout": "Añadir auto-layout",
+ "removeAutoLayout": "Quitar auto-layout",
+ "mixed": "Mixto",
+ "layersCount": "{count} capas",
+ "goToMainComponent": "Ir al componente principal",
+ "detachInstance": "Separar instancia",
+ "solid": "Sólido",
+ "linearGradient": "Lineal",
+ "radialGradient": "Radial",
+ "image": "Imagen",
+ "stops": "Paradas",
+ "addStop": "Añadir parada",
+ "alignLeft": "Alinear a la izquierda",
+ "alignCenter": "Centrar",
+ "alignRight": "Alinear a la derecha",
+ "alignTop": "Alinear arriba",
+ "alignMiddle": "Centrar verticalmente",
+ "alignBottom": "Alinear abajo",
+ "alignCenterHorizontally": "Centrar horizontalmente",
+ "alignCenterVertically": "Centrar verticalmente",
+ "flipHorizontal": "Voltear horizontalmente",
+ "flipVertical": "Voltear verticalmente",
+ "rotate90": "Girar 90°",
+ "mixedFillsHelp": "Haz clic en + para reemplazar rellenos mixtos",
+ "mixedStrokesHelp": "Haz clic en + para reemplazar trazos mixtos",
+ "mixedEffectsHelp": "Haz clic en + para reemplazar efectos mixtos",
+ "strokeSides": "Lados del trazo",
+ "clipContent": "Recortar contenido",
+ "colorFormatRgb": "RGB",
+ "colorFormatHsl": "HSL",
+ "colorFormatHsb": "HSB",
+ "colorFormatOkhcl": "OkHCL",
+ "colorHintHsl": "H tono · S saturación · L luminosidad",
+ "colorHintHsb": "H tono · S saturación · B brillo",
+ "colorHintOkhcl": "H tono · C croma · L luminosidad · A alfa",
+ "colorPreviewClipped": "Recortado a gama de vista previa {space}",
+ "rulers": "Reglas",
+ "multiplayerCursors": "Cursores de otros participantes",
+ "direction": "Dirección",
+ "flow": "Flujo",
+ "auto": "Auto",
+ "columns": "Columnas",
+ "rows": "Filas",
+ "gap": "Espaciado",
+ "sizingFixed": "Fijo",
+ "sizingHug": "Ajustar al contenido",
+ "sizingFill": "Rellenar",
+ "sizingHugShort": "Ajust.",
+ "sizingFillShort": "Llenar",
+ "sizingFillFr": "Rellenar (fr)",
+ "sizingFixedPx": "Fijo (px)",
+ "strokeAlignInside": "Interior",
+ "strokeAlignCenter": "Centro",
+ "strokeAlignOutside": "Exterior",
+ "exportScale": "Escala de exportación",
+ "exportFormat": "Formato de exportación",
+ "exportPreview": "Vista previa",
+ "exportRenderingPreview": "Renderizando vista previa…",
+ "createVariable": "Crear variable",
+ "createColorVariable": "Crear variable de color desde {value}",
+ "variableName": "Nombre de variable",
+ "create": "Crear",
+ "createNumberVariable": "Crear variable numérica desde {value}",
+ "strokeDash": "Trazo discontinuo",
+ "add": "Añadir",
+ "variants": "Variantes",
+ "gapAuto": "Espaciado auto",
+ "horizontalGap": "Espaciado horizontal",
+ "verticalGap": "Espaciado vertical",
+ "addMinWidth": "Agregar ancho min",
+ "removeMinWidth": "Eliminar ancho min",
+ "addMaxWidth": "Agregar ancho max",
+ "removeMaxWidth": "Eliminar ancho max",
+ "addMinHeight": "Agregar alto min",
+ "removeMinHeight": "Eliminar alto min",
+ "addMaxHeight": "Agregar alto max",
+ "removeMaxHeight": "Eliminar alto max",
+ "minWidthShort": "Min A",
+ "maxWidthShort": "Max A",
+ "minHeightShort": "Min Al",
+ "maxHeightShort": "Max Al",
+ "setToCurrentWidth": "Establecer ancho actual",
+ "setToCurrentHeight": "Establecer alto actual",
+ "searchLocalComponents": "Buscar componentes locales",
+ "assetLibraryBadge": "Biblioteca",
+ "assetVariantSummary": "{count} variantes · {names}",
+ "duplicateVariantValues": "Valores de variante duplicados",
+ "openDocumentation": "Abrir documentación",
+ "noLocalComponents": "No hay componentes locales",
+ "componentSet": "Conjunto de componentes",
+ "component": "Componente",
+ "insertInstance": "Insertar instancia",
+ "description": "Descripción",
+ "documentation": "Documentación",
+ "openDocs": "Abrir docs",
+ "properties": "Propiedades",
+ "removeFill": "Eliminar relleno",
+ "removeStroke": "Eliminar trazo",
+ "removeEffect": "Eliminar efecto",
+ "removeExport": "Eliminar exportación",
+ "effectSettings": "Ajustes del efecto",
+ "expandEffectSettings": "Expandir ajustes del efecto",
+ "collapseEffectSettings": "Contraer ajustes del efecto",
+ "toggleExportPreview": "Alternar vista previa de exportación",
+ "searchFonts": "Buscar fuentes..."
+ },
+ "pages": {
+ "newPage": "Nueva página",
+ "rename": "Renombrar",
+ "delete": "Eliminar",
+ "pageName": "Página {number}"
+ },
+ "dialogs": {
+ "cancel": "Cancelar",
+ "apply": "Aplicar",
+ "close": "Cerrar",
+ "ok": "Aceptar",
+ "copy": "Copiar",
+ "copied": "Copiado",
+ "createCollection": "Crear colección",
+ "localVariables": "Variables locales",
+ "noVariableCollections": "No hay colecciones de variables",
+ "selectLayerForJSX": "Selecciona una capa para ver su código JSX",
+ "connectAIProvider": "Conecta un proveedor de IA para empezar a chatear.",
+ "connect": "Conectar",
+ "getAPIKey": "Obtener una clave API de {provider} →",
+ "oneKeyManyModels": "Una clave para más de 100 modelos de todos los proveedores.",
+ "describeChange": "Describe un cambio…",
+ "describeCreateOrChange": "Describe lo que quieres crear o cambiar.",
+ "stopGenerating": "Detener generación",
+ "sendMessage": "Enviar mensaje",
+ "baseURLPlaceholder": "Base URL (p. ej. http://localhost:11434/v1)",
+ "modelIDPlaceholder": "Model ID (p. ej. llama-3.3-70b)",
+ "yourName": "Tu nombre",
+ "enterYourName": "Introduce tu nombre",
+ "shareThisFile": "Compartir este archivo",
+ "joinRoom": "Unirse a la sala",
+ "join": "Unirse",
+ "roomLink": "Enlace de la sala",
+ "joinCollaboration": "Unirse a la colaboración",
+ "orJoinRoom": "o unirse a una sala",
+ "pasteRoomLinkOrId": "Pega el enlace o ID de la sala",
+ "connected": "Conectado",
+ "search": "Buscar…",
+ "noResults": "Sin resultados",
+ "share": "Compartir",
+ "appUpToDate": "OpenPencil está actualizado",
+ "updateAvailableTitle": "Actualizar OpenPencil",
+ "updateAvailable": "Está disponible la versión {version} de OpenPencil.",
+ "updateInstallPrompt": "¿Descargar e instalar ahora? La app se reiniciará después de instalar la actualización.",
+ "downloadingUpdate": "Descargando OpenPencil {version}",
+ "updateInstalledTitle": "Actualización instalada",
+ "updateInstalled": "Se ha instalado la versión {version} de OpenPencil. Reiniciando ahora...",
+ "updateCheckFailed": "Error al encontrar actualizaciones: {error}",
+ "updateUnavailable": "Las actualizaciones aún no están disponibles. Publica primero una versión firmada con latest.json.",
+ "renameCollection": "Renombrar coleccion",
+ "deleteCollection": "Eliminar coleccion",
+ "modes": "Modos",
+ "addMode": "Agregar modo",
+ "renameMode": "Renombrar modo",
+ "duplicateMode": "Duplicar modo",
+ "deleteMode": "Eliminar modo",
+ "setDefaultMode": "Establecer como predeterminado",
+ "aiProvider": "Proveedor IA",
+ "providerSettings": "Opciones del proveedor",
+ "done": "Hecho",
+ "apiKey": "Clave API",
+ "apiType": "Tipo API",
+ "baseURL": "URL base",
+ "modelID": "ID Modelo",
+ "maxOutputTokens": "Tokens de salida máx.",
+ "clear": "Limpiar",
+ "keySavedReplace": "Clave guardada - introduce una nueva para reemplazarla",
+ "getAPIKeyGeneric": "Obtener clave API →",
+ "pexelsAPIKey": "Clave API de Pexels (fotos stock)",
+ "unsplashAccessKey": "Clave de acceso de Unsplash",
+ "stockPhotoToolOptional": "Opcional — para herramienta stock_photo",
+ "pexelsAlternativeOptional": "Opcional — alternativa a Pexels",
+ "getPexelsAPIKey": "Obtener clave a la API gratis de Pexels →",
+ "getUnsplashAccessKey": "Obtener clave a la API gratis de Unsplash →",
+ "completions": "Completados",
+ "responses": "Respuestas",
+ "copiedExclamation": "¡Copiado!",
+ "copyMessage": "Copiar mensaje",
+ "copyJSXReference": "Copiar referencia de props JSX al portapapeles",
+ "newTab": "Nueva pestaña",
+ "closeTab": "Cerrar {name}",
+ "showUI": "Mostrar interfaz ({shortcut})",
+ "fontSettings": "Ajustes de fuentes",
+ "you": "Tú",
+ "youSuffix": "tú",
+ "followingPeerStop": "Siguiendo a {name} (haz clic para detener)",
+ "clickToFollowPeer": "Haz clic para seguir a {name}"
+ },
+ "variableTypes": {
+ "color": "Color",
+ "colorHint": "Valores de pintura",
+ "number": "Número",
+ "numberHint": "Tamaños, espaciado, opacidad",
+ "text": "Texto",
+ "textHint": "Texto y etiquetas",
+ "boolean": "Booleano",
+ "booleanHint": "Verdadero o falso"
+ }
}
diff --git a/packages/vue/src/shared/input/auto-layout-hover.ts b/packages/vue/src/shared/input/auto-layout-hover.ts
index 381196ddf..d0c4c0606 100644
--- a/packages/vue/src/shared/input/auto-layout-hover.ts
+++ b/packages/vue/src/shared/input/auto-layout-hover.ts
@@ -21,7 +21,11 @@ function isNear(value: number, target: number, tolerance = AUTO_LAYOUT_HOVER_TIC
return Math.abs(value - target) <= tolerance
}
-function resolvePaddingHover(node: SceneNode, localX: number, localY: number): AutoLayoutHover | null {
+function resolvePaddingHover(
+ node: SceneNode,
+ localX: number,
+ localY: number
+): AutoLayoutHover | null {
const centerX = node.width / 2
const centerY = node.height / 2
@@ -40,7 +44,10 @@ function resolvePaddingHover(node: SceneNode, localX: number, localY: number): A
if (isNear(localX, centerX) && isNear(localY, tickY)) {
return { nodeId: node.id, kind: 'padding-value', side: 'bottom' }
}
- if (localY >= node.height - Math.min(node.paddingBottom, AUTO_LAYOUT_HOVER_PADDING_REGION_TOLERANCE)) {
+ if (
+ localY >=
+ node.height - Math.min(node.paddingBottom, AUTO_LAYOUT_HOVER_PADDING_REGION_TOLERANCE)
+ ) {
return { nodeId: node.id, kind: 'padding', side: 'bottom' }
}
}
@@ -60,7 +67,10 @@ function resolvePaddingHover(node: SceneNode, localX: number, localY: number): A
if (isNear(localX, tickX) && isNear(localY, centerY)) {
return { nodeId: node.id, kind: 'padding-value', side: 'right' }
}
- if (localX >= node.width - Math.min(node.paddingRight, AUTO_LAYOUT_HOVER_PADDING_REGION_TOLERANCE)) {
+ if (
+ localX >=
+ node.width - Math.min(node.paddingRight, AUTO_LAYOUT_HOVER_PADDING_REGION_TOLERANCE)
+ ) {
return { nodeId: node.id, kind: 'padding', side: 'right' }
}
}
@@ -124,7 +134,11 @@ function resolveChildrenHover(
return null
}
-export function resolveAutoLayoutHover(cx: number, cy: number, editor: Editor): AutoLayoutHover | null {
+export function resolveAutoLayoutHover(
+ cx: number,
+ cy: number,
+ editor: Editor
+): AutoLayoutHover | null {
if (editor.state.selectedIds.size !== 1) return null
const nodeId = [...editor.state.selectedIds][0]
const node = editor.graph.getNode(nodeId)
@@ -139,7 +153,6 @@ export function resolveAutoLayoutHover(cx: number, cy: number, editor: Editor):
return (
resolveSpacingHover(node, children, localX, localY) ??
resolvePaddingHover(node, localX, localY) ??
- resolveChildrenHover(node, children, localX, localY) ??
- { nodeId: node.id, kind: 'frame' }
+ resolveChildrenHover(node, children, localX, localY) ?? { nodeId: node.id, kind: 'frame' }
)
}
diff --git a/packages/vue/src/shared/input/duplicate-drag.ts b/packages/vue/src/shared/input/duplicate-drag.ts
index 63a2a4a5f..18711989e 100644
--- a/packages/vue/src/shared/input/duplicate-drag.ts
+++ b/packages/vue/src/shared/input/duplicate-drag.ts
@@ -1,7 +1,7 @@
import type { Editor } from '@open-pencil/core/editor'
+import { useI18n } from '#vue/i18n/useI18n.js'
import type { DragState } from '#vue/shared/input/types'
-import { useI18n } from '#vue/i18n/useI18n.js';
type DragOriginal = { x: number; y: number; parentId: string }
@@ -13,14 +13,16 @@ export function duplicateAndDrag(
editor: Editor
): { originals: Map<string, DragOriginal>; drag: DragState } {
const previousSelection = new Set(editor.state.selectedIds)
- const {panels} = useI18n();
+ const { panels } = useI18n()
const newIds: string[] = []
const newOriginals = new Map<string, DragOriginal>()
for (const id of previousSelection) {
const source = editor.graph.getNode(id)
if (!source) continue
const parentId = source.parentId ?? editor.state.currentPageId
- const clone = editor.graph.cloneTree(id, parentId, { name: source.name + panels.value.nodeCopyString || ' copy' })
+ const clone = editor.graph.cloneTree(id, parentId, {
+ name: source.name + panels.value.nodeCopyString || ' copy'
+ })
if (!clone) continue
newIds.push(clone.id)
newOriginals.set(clone.id, {
diff --git a/packages/vue/src/shared/input/select/move.ts b/packages/vue/src/shared/input/select/move.ts
index 4e932e5bd..f6e274a16 100644
--- a/packages/vue/src/shared/input/select/move.ts
+++ b/packages/vue/src/shared/input/select/move.ts
@@ -64,7 +64,8 @@ export function createSelectionMoveDrag(
editor: Editor,
duplicate: boolean
): DragState {
- if (duplicate && editor.state.selectedIds.size > 0) return duplicateAndDrag(cx, cy, sx, sy, editor).drag
+ if (duplicate && editor.state.selectedIds.size > 0)
+ return duplicateAndDrag(cx, cy, sx, sy, editor).drag
const originals = collectMoveOriginals(editor)
diff --git a/packages/vue/src/variables/helpers.ts b/packages/vue/src/variables/helpers.ts
index ad16bb676..6b51061be 100644
--- a/packages/vue/src/variables/helpers.ts
+++ b/packages/vue/src/variables/helpers.ts
@@ -1,7 +1,7 @@
import type { Ref } from 'vue'
-import { BLACK } from '@open-pencil/core/constants'
import { colorToHexRaw, parseColor } from '@open-pencil/core/color'
+import { BLACK } from '@open-pencil/core/constants'
import type { Editor } from '@open-pencil/core/editor'
import { randomHex } from '@open-pencil/core/random'
import type {
diff --git a/scripts/check-package-metadata.ts b/scripts/check-package-metadata.ts
index fc06abbbf..068f52751 100644
--- a/scripts/check-package-metadata.ts
+++ b/scripts/check-package-metadata.ts
@@ -31,7 +31,8 @@ function checkRuntimePath(packageName: string, field: string, value: string): vo
function walkExports(packageName: string, value: unknown, path: string[] = []): void {
if (typeof value === 'string') {
const key = path.at(-1)
- if (key !== 'types' && key !== 'bun') checkRuntimePath(packageName, `exports.${path.join('.')}`, value)
+ if (key !== 'types' && key !== 'bun')
+ checkRuntimePath(packageName, `exports.${path.join('.')}`, value)
return
}
if (!value || typeof value !== 'object') return
@@ -59,7 +60,10 @@ for (const packageDir of publicPackages) {
walkExports(pkg.name, pkg.exports)
- if (pkg.publishConfig && ('exports' in pkg.publishConfig || 'main' in pkg.publishConfig || 'types' in pkg.publishConfig)) {
+ if (
+ pkg.publishConfig &&
+ ('exports' in pkg.publishConfig || 'main' in pkg.publishConfig || 'types' in pkg.publishConfig)
+ ) {
errors.push(`${pkg.name}: publishConfig must not rewrite runtime entrypoints`)
}
}
diff --git a/scripts/smoke-packages.ts b/scripts/smoke-packages.ts
index 895bac93e..a8b72af2d 100644
--- a/scripts/smoke-packages.ts
+++ b/scripts/smoke-packages.ts
@@ -30,7 +30,10 @@ try {
const tarballs: string[] = []
for (const packageDir of packageDirs) {
- const output = run(['bun', 'pm', 'pack', '--destination', tempDir, '--quiet'], join(rootDir, packageDir))
+ const output = run(
+ ['bun', 'pm', 'pack', '--destination', tempDir, '--quiet'],
+ join(rootDir, packageDir)
+ )
const filename = output
.split('\n')
.map((line) => line.trim())
diff --git a/src/app/ai/tools/index.ts b/src/app/ai/tools/index.ts
index 1cc049902..5e1cbce59 100644
--- a/src/app/ai/tools/index.ts
+++ b/src/app/ai/tools/index.ts
@@ -9,8 +9,8 @@ import type { StepBudget, ToolLogEntry } from '@open-pencil/core/tools'
import { makeFigmaFromStore } from '@/app/automation/bridge/figma-factory'
import { getActiveEditorStore } from '@/app/editor/active-store'
-import { ensureGraphFonts } from '@/app/editor/fonts'
import type { EditorStore } from '@/app/editor/active-store'
+import { ensureGraphFonts } from '@/app/editor/fonts'
export const MAX_AGENT_STEPS = 50
diff --git a/src/app/editor/canvas/menu/context.ts b/src/app/editor/canvas/menu/context.ts
index c67c7281f..1333e68ac 100644
--- a/src/app/editor/canvas/menu/context.ts
+++ b/src/app/editor/canvas/menu/context.ts
@@ -43,7 +43,9 @@ function copyAction(
): () => void {
switch (id) {
case 'copy-as-text':
- return runAsync(() => actions.clipboardWrite(editor.copySelectionAsText(actions.ids()), 'text'))
+ return runAsync(() =>
+ actions.clipboardWrite(editor.copySelectionAsText(actions.ids()), 'text')
+ )
case 'copy-as-svg':
return runAsync(() => actions.clipboardWrite(editor.copySelectionAsSVG(actions.ids()), 'SVG'))
case 'copy-as-png':
diff --git a/src/app/shell/keyboard/registry.ts b/src/app/shell/keyboard/registry.ts
index d9abc3d02..7dbb0e612 100644
--- a/src/app/shell/keyboard/registry.ts
+++ b/src/app/shell/keyboard/registry.ts
@@ -6,13 +6,13 @@ import { editorCommandMetadata } from '@open-pencil/vue'
import type { EditorCommandId } from '@open-pencil/vue'
import { TOOL_SHORTCUTS } from '@/app/editor/session'
-import { appMenuTinykeysShortcut } from '@/app/shell/menu/shortcut'
import { isEditing } from '@/app/shell/keyboard/focus'
import { bindSpaceHandTool } from '@/app/shell/keyboard/space-tool'
import type {
KeyboardShortcutOptions,
KeyboardShortcutRunOptions
} from '@/app/shell/keyboard/types'
+import { appMenuTinykeysShortcut } from '@/app/shell/menu/shortcut'
type ShortcutAction = (options: KeyboardShortcutRunOptions) => void
diff --git a/src/app/shell/menu/app-menu.ts b/src/app/shell/menu/app-menu.ts
index 27bb60348..d79d18b18 100644
--- a/src/app/shell/menu/app-menu.ts
+++ b/src/app/shell/menu/app-menu.ts
@@ -1,151 +1,137 @@
-import { computed } from "vue";
-
-import { useEditorCommands, useI18n } from "@open-pencil/vue";
-import type { MenuEntry } from "@open-pencil/vue";
-
-import { useEditorStore } from "@/app/editor/active-store";
-import { createSharedEditorMenuActions } from "@/app/shell/menu/editor-actions";
-import { APP_MENU_SCHEMA } from "@/app/shell/menu/schema";
-import type {
- AppMenuActionItem,
- AppMenuEntry,
- AppMenuGroupSchema,
-} from "@/app/shell/menu/schema";
-import { appMenuShortcutLabel } from "@/app/shell/menu/shortcut";
-import { openFileDialog } from "@/app/shell/menu/use";
-import { useAppTheme } from "@/app/shell/theme";
+import { computed } from 'vue'
+
+import { useEditorCommands, useI18n } from '@open-pencil/vue'
+import type { MenuEntry } from '@open-pencil/vue'
+
+import { useEditorStore } from '@/app/editor/active-store'
+import { createSharedEditorMenuActions } from '@/app/shell/menu/editor-actions'
+import { APP_MENU_SCHEMA } from '@/app/shell/menu/schema'
+import type { AppMenuActionItem, AppMenuEntry, AppMenuGroupSchema } from '@/app/shell/menu/schema'
+import { appMenuShortcutLabel } from '@/app/shell/menu/shortcut'
+import { openFileDialog } from '@/app/shell/menu/use'
+import { useAppTheme } from '@/app/shell/theme'
export interface AppMenuGroup {
- label: string;
- items: MenuEntry[];
+ label: string
+ items: MenuEntry[]
}
function isVisible(entry: { target?: string }): boolean {
- return entry.target !== "native";
+ return entry.target !== 'native'
}
-function isSeparator(
- entry: AppMenuEntry,
-): entry is Extract<AppMenuEntry, { type: "separator" }> {
- return entry.type === "separator";
+function isSeparator(entry: AppMenuEntry): entry is Extract<AppMenuEntry, { type: 'separator' }> {
+ return entry.type === 'separator'
}
export function useAppMenu() {
- const store = useEditorStore();
- const { menuItem: commandMenuItem } = useEditorCommands();
- const { locale, availableLocales, localeLabels, setLocale } = useI18n();
- const { theme, setTheme } = useAppTheme();
-
- const languageMenu = computed<MenuEntry[]>(() =>
- availableLocales.map((code) => ({
- label: localeLabels[code],
- checked: locale.value === code,
- onCheckedChange: (checked: boolean) => {
- if (checked) setLocale(code);
- },
- })),
- );
-
- function exportSelection(format: "png" | "svg" | "fig") {
- if (store.state.selectedIds.size > 0) void store.exportSelection(1, format);
- }
-
- const actions: Partial<Record<string, () => void>> = {
- new: () => {
- void import("@/app/tabs").then((m) => m.createTab());
- },
- open: () => void openFileDialog(),
- save: () => void store.saveFigFile(),
- "save-as": () => void store.saveFigFileAs(),
- "export-selection": () => exportSelection("png"),
- cut: () => document.execCommand("cut"),
- "export-png": () => exportSelection("png"),
- "export-svg": () => exportSelection("svg"),
- "export-fig": () => exportSelection("fig"),
- ...createSharedEditorMenuActions(setTheme),
- };
-
- function itemAction(item: AppMenuActionItem): (() => void) | undefined {
- return actions[item.id];
- }
-
- function checked(item: AppMenuActionItem): boolean | undefined {
- switch (item.id) {
- case "autosave":
- return store.state.autosaveEnabled;
- case "profiler":
- return store.renderer?.profiler.hudVisible ?? false;
- case "theme-light":
- return theme.value === "light";
- case "theme-dark":
- return theme.value === "dark";
- case "theme-auto":
- return theme.value === "auto";
- default:
- return undefined;
- }
- }
-
- function onCheckedChange(
- item: AppMenuActionItem,
- ): ((checked: boolean) => void) | undefined {
- switch (item.id) {
- case "autosave":
- return (value: boolean) => {
- store.state.autosaveEnabled = value;
- };
- case "profiler":
- return () => store.toggleProfiler();
- case "theme-light":
- case "theme-dark":
- case "theme-auto":
- return (value: boolean) => {
- if (value) itemAction(item)?.();
- };
- default:
- return undefined;
- }
- }
-
- function buildEntry(entry: AppMenuEntry): MenuEntry | null {
- if (!isVisible(entry)) return null;
- if (isSeparator(entry)) return { separator: true };
-
- if (entry.id === "language") {
- return { label: entry.label, sub: languageMenu.value };
- }
-
- if (entry.command) {
- return commandMenuItem(entry.command, appMenuShortcutLabel(entry.id));
- }
-
- return {
- label: entry.label,
- shortcut: appMenuShortcutLabel(entry.id),
- action: itemAction(entry),
- checked: checked(entry),
- onCheckedChange: onCheckedChange(entry),
- sub: entry.sub
- ?.map(buildEntry)
- .filter((item): item is MenuEntry => item !== null),
- };
- }
-
- function buildGroup(group: AppMenuGroupSchema): AppMenuGroup | null {
- if (!isVisible(group)) return null;
- return {
- label: group.label,
- items: group.items
- .map(buildEntry)
- .filter((item): item is MenuEntry => item !== null),
- };
- }
-
- const topMenus = computed<AppMenuGroup[]>(() =>
- APP_MENU_SCHEMA.map(buildGroup).filter(
- (group): group is AppMenuGroup => group !== null,
- ),
- );
-
- return { topMenus };
+ const store = useEditorStore()
+ const { menuItem: commandMenuItem } = useEditorCommands()
+ const { locale, availableLocales, localeLabels, setLocale } = useI18n()
+ const { theme, setTheme } = useAppTheme()
+
+ const languageMenu = computed<MenuEntry[]>(() =>
+ availableLocales.map((code) => ({
+ label: localeLabels[code],
+ checked: locale.value === code,
+ onCheckedChange: (checked: boolean) => {
+ if (checked) setLocale(code)
+ }
+ }))
+ )
+
+ function exportSelection(format: 'png' | 'svg' | 'fig') {
+ if (store.state.selectedIds.size > 0) void store.exportSelection(1, format)
+ }
+
+ const actions: Partial<Record<string, () => void>> = {
+ new: () => {
+ void import('@/app/tabs').then((m) => m.createTab())
+ },
+ open: () => void openFileDialog(),
+ save: () => void store.saveFigFile(),
+ 'save-as': () => void store.saveFigFileAs(),
+ 'export-selection': () => exportSelection('png'),
+ cut: () => document.execCommand('cut'),
+ 'export-png': () => exportSelection('png'),
+ 'export-svg': () => exportSelection('svg'),
+ 'export-fig': () => exportSelection('fig'),
+ ...createSharedEditorMenuActions(setTheme)
+ }
+
+ function itemAction(item: AppMenuActionItem): (() => void) | undefined {
+ return actions[item.id]
+ }
+
+ function checked(item: AppMenuActionItem): boolean | undefined {
+ switch (item.id) {
+ case 'autosave':
+ return store.state.autosaveEnabled
+ case 'profiler':
+ return store.renderer?.profiler.hudVisible ?? false
+ case 'theme-light':
+ return theme.value === 'light'
+ case 'theme-dark':
+ return theme.value === 'dark'
+ case 'theme-auto':
+ return theme.value === 'auto'
+ default:
+ return undefined
+ }
+ }
+
+ function onCheckedChange(item: AppMenuActionItem): ((checked: boolean) => void) | undefined {
+ switch (item.id) {
+ case 'autosave':
+ return (value: boolean) => {
+ store.state.autosaveEnabled = value
+ }
+ case 'profiler':
+ return () => store.toggleProfiler()
+ case 'theme-light':
+ case 'theme-dark':
+ case 'theme-auto':
+ return (value: boolean) => {
+ if (value) itemAction(item)?.()
+ }
+ default:
+ return undefined
+ }
+ }
+
+ function buildEntry(entry: AppMenuEntry): MenuEntry | null {
+ if (!isVisible(entry)) return null
+ if (isSeparator(entry)) return { separator: true }
+
+ if (entry.id === 'language') {
+ return { label: entry.label, sub: languageMenu.value }
+ }
+
+ if (entry.command) {
+ return commandMenuItem(entry.command, appMenuShortcutLabel(entry.id))
+ }
+
+ return {
+ label: entry.label,
+ shortcut: appMenuShortcutLabel(entry.id),
+ action: itemAction(entry),
+ checked: checked(entry),
+ onCheckedChange: onCheckedChange(entry),
+ sub: entry.sub?.map(buildEntry).filter((item): item is MenuEntry => item !== null)
+ }
+ }
+
+ function buildGroup(group: AppMenuGroupSchema): AppMenuGroup | null {
+ if (!isVisible(group)) return null
+ return {
+ label: group.label,
+ items: group.items.map(buildEntry).filter((item): item is MenuEntry => item !== null)
+ }
+ }
+
+ const topMenus = computed<AppMenuGroup[]>(() =>
+ APP_MENU_SCHEMA.map(buildGroup).filter((group): group is AppMenuGroup => group !== null)
+ )
+
+ return { topMenus }
}
diff --git a/src/app/shell/menu/editor-actions.ts b/src/app/shell/menu/editor-actions.ts
index 0994b417f..7e5f4bc08 100644
--- a/src/app/shell/menu/editor-actions.ts
+++ b/src/app/shell/menu/editor-actions.ts
@@ -10,7 +10,10 @@ type TextFormatUpdates = {
const store = useEditorStore()
-export function alignSelected(axis: 'horizontal' | 'vertical', align: 'min' | 'center' | 'max'): void {
+export function alignSelected(
+ axis: 'horizontal' | 'vertical',
+ align: 'min' | 'center' | 'max'
+): void {
store.alignNodes([...store.state.selectedIds], axis, align)
}
@@ -41,7 +44,9 @@ export function toggleSelectedTextUnderline(): void {
})
}
-export function createSharedEditorMenuActions(setTheme: (theme: 'light' | 'dark' | 'auto') => void) {
+export function createSharedEditorMenuActions(
+ setTheme: (theme: 'light' | 'dark' | 'auto') => void
+) {
return {
'zoom-in': () => store.applyZoom(-100, window.innerWidth / 2, window.innerHeight / 2),
'zoom-out': () => store.applyZoom(100, window.innerWidth / 2, window.innerHeight / 2),
diff --git a/src/app/shell/menu/schema.ts b/src/app/shell/menu/schema.ts
index b643bb73e..8fb6cb350 100644
--- a/src/app/shell/menu/schema.ts
+++ b/src/app/shell/menu/schema.ts
@@ -1,255 +1,255 @@
-import { type EditorCommandId, useI18n } from "@open-pencil/vue";
-const { menu } = useI18n();
+import { type EditorCommandId, useI18n } from '@open-pencil/vue'
+const { menu } = useI18n()
-export type AppMenuTarget = "all" | "browser" | "native";
+export type AppMenuTarget = 'all' | 'browser' | 'native'
export interface AppMenuActionItem {
- type?: "item";
- id: string;
- label: string;
- shortcut?: string;
- accelerator?: string;
- command?: EditorCommandId;
- checkbox?: boolean;
- target?: AppMenuTarget;
- sub?: AppMenuEntry[];
+ type?: 'item'
+ id: string
+ label: string
+ shortcut?: string
+ accelerator?: string
+ command?: EditorCommandId
+ checkbox?: boolean
+ target?: AppMenuTarget
+ sub?: AppMenuEntry[]
}
export interface AppMenuSeparatorItem {
- type: "separator";
- target?: AppMenuTarget;
+ type: 'separator'
+ target?: AppMenuTarget
}
-export type AppMenuEntry = AppMenuActionItem | AppMenuSeparatorItem;
+export type AppMenuEntry = AppMenuActionItem | AppMenuSeparatorItem
export interface AppMenuGroupSchema {
- label: string;
- target?: AppMenuTarget;
- items: AppMenuEntry[];
+ label: string
+ target?: AppMenuTarget
+ items: AppMenuEntry[]
}
export const APP_MENU_SCHEMA = [
- {
- label: "File",
- items: [
- { id: "new", label: menu.value.new || "New", shortcut: "MOD+N" },
- { id: "open", label: menu.value.open || "Open…", shortcut: "MOD+O" },
- { type: "separator" },
- { id: "save", label: menu.value.save || "Save", shortcut: "MOD+S" },
- {
- id: "save-as",
- label: menu.value.saveAs || "Save As…",
- shortcut: "MOD+SHIFT+S",
- },
- { type: "separator" },
- {
- id: "export-selection",
- label: menu.value.exportSelection || "Export Selection",
- shortcut: "MOD+SHIFT+E",
- sub: [
- { id: "export-png", label: "PNG" },
- { id: "export-svg", label: "SVG" },
- { id: "export-fig", label: ".fig" },
- ],
- },
- { type: "separator" },
- {
- id: "autosave",
- label: menu.value.autosave || "Autosave",
- checkbox: true,
- },
- {
- id: "close",
- label: menu.value.closeTab || "Close Tab",
- shortcut: "MOD+W",
- },
- ],
- },
- {
- label: "Edit",
- items: [
- {
- id: "edit.undo",
- label: "Undo",
- command: "edit.undo",
- },
- {
- id: "edit.redo",
- label: "Redo",
- command: "edit.redo",
- },
- { type: "separator" },
- { id: "copy", label: "Copy", shortcut: "MOD+C" },
- { id: "cut", label: "Cut", shortcut: "MOD+X" },
- { id: "paste", label: "Paste", shortcut: "MOD+V" },
- { id: "paste-to-replace", label: "Paste to replace" },
- {
- id: "selection.duplicate",
- label: "Duplicate",
- command: "selection.duplicate",
- },
- {
- id: "selection.delete",
- label: "Delete",
- command: "selection.delete",
- },
- { type: "separator" },
- {
- id: "selection.selectAll",
- label: "Select All",
- command: "selection.selectAll",
- },
- ],
- },
- {
- label: "View",
- items: [
- {
- id: "view.zoom100",
- label: "Zoom to 100%",
- command: "view.zoom100",
- },
- {
- id: "view.zoomFit",
- label: "Zoom to Fit",
- command: "view.zoomFit",
- },
- {
- id: "view.zoomSelection",
- label: "Zoom to Selection",
- command: "view.zoomSelection",
- },
- { id: "zoom-in", label: "Zoom In", shortcut: "MOD+=" },
- { id: "zoom-out", label: "Zoom Out", shortcut: "MOD+-" },
- { type: "separator" },
- {
- id: "theme",
- label: "Theme",
- sub: [
- { id: "theme-light", label: "Light", checkbox: true },
- { id: "theme-dark", label: "Dark", checkbox: true },
- { id: "theme-auto", label: "Auto", checkbox: true },
- ],
- },
- { id: "language", label: "Language", target: "browser" },
- { type: "separator" },
- { id: "toggle-ui", label: "Toggle UI", shortcut: "MOD+\\" },
- { id: "profiler", label: "Profiler", checkbox: true, target: "browser" },
- {
- id: "dev-tools",
- label: "Developer Tools",
- accelerator: "CmdOrCtrl+Alt+I",
- target: "native",
- },
- ],
- },
- {
- label: "Object",
- items: [
- {
- id: "selection.group",
- label: "Group Selection",
- command: "selection.group",
- },
- {
- id: "selection.frameSelection",
- label: "Frame Selection",
- command: "selection.frameSelection",
- },
- {
- id: "selection.ungroup",
- label: "Ungroup Selection",
- command: "selection.ungroup",
- },
- { type: "separator" },
- {
- id: "selection.booleanUnion",
- label: "Union selection",
- command: "selection.booleanUnion",
- },
- {
- id: "selection.booleanSubtract",
- label: "Subtract selection",
- command: "selection.booleanSubtract",
- },
- {
- id: "selection.booleanIntersect",
- label: "Intersect selection",
- command: "selection.booleanIntersect",
- },
- {
- id: "selection.booleanExclude",
- label: "Exclude selection",
- command: "selection.booleanExclude",
- },
- {
- id: "selection.flatten",
- label: "Flatten",
- command: "selection.flatten",
- },
- {
- id: "selection.outlineText",
- label: "Outline text",
- command: "selection.outlineText",
- },
- {
- id: "selection.outlineStroke",
- label: "Outline stroke",
- command: "selection.outlineStroke",
- },
- { type: "separator" },
- {
- id: "selection.createComponent",
- label: "Create Component",
- command: "selection.createComponent",
- },
- {
- id: "selection.createComponentSet",
- label: "Create Component Set",
- command: "selection.createComponentSet",
- },
- {
- id: "selection.detachInstance",
- label: "Detach Instance",
- command: "selection.detachInstance",
- },
- { type: "separator" },
- {
- id: "selection.bringToFront",
- label: "Bring to Front",
- command: "selection.bringToFront",
- },
- {
- id: "selection.sendToBack",
- label: "Send to Back",
- command: "selection.sendToBack",
- },
- ],
- },
- {
- label: "Text",
- items: [
- { id: "text.bold", label: "Bold", shortcut: "MOD+B" },
- { id: "text.italic", label: "Italic", shortcut: "MOD+I" },
- { id: "text.underline", label: "Underline", shortcut: "MOD+U" },
- ],
- },
- {
- label: "Arrange",
- items: [
- {
- id: "selection.wrapInAutoLayout",
- label: "Wrap in Auto Layout",
- command: "selection.wrapInAutoLayout",
- },
- { type: "separator" },
- { id: "align-left", label: "Align Left", shortcut: "ALT+A" },
- { id: "align-center", label: "Align Center", shortcut: "ALT+H" },
- { id: "align-right", label: "Align Right", shortcut: "ALT+D" },
- { type: "separator" },
- { id: "align-top", label: "Align Top", shortcut: "ALT+W" },
- { id: "align-middle", label: "Align Middle", shortcut: "ALT+V" },
- { id: "align-bottom", label: "Align Bottom", shortcut: "ALT+S" },
- ],
- },
-] satisfies AppMenuGroupSchema[];
+ {
+ label: 'File',
+ items: [
+ { id: 'new', label: menu.value.new || 'New', shortcut: 'MOD+N' },
+ { id: 'open', label: menu.value.open || 'Open…', shortcut: 'MOD+O' },
+ { type: 'separator' },
+ { id: 'save', label: menu.value.save || 'Save', shortcut: 'MOD+S' },
+ {
+ id: 'save-as',
+ label: menu.value.saveAs || 'Save As…',
+ shortcut: 'MOD+SHIFT+S'
+ },
+ { type: 'separator' },
+ {
+ id: 'export-selection',
+ label: menu.value.exportSelection || 'Export Selection',
+ shortcut: 'MOD+SHIFT+E',
+ sub: [
+ { id: 'export-png', label: 'PNG' },
+ { id: 'export-svg', label: 'SVG' },
+ { id: 'export-fig', label: '.fig' }
+ ]
+ },
+ { type: 'separator' },
+ {
+ id: 'autosave',
+ label: menu.value.autosave || 'Autosave',
+ checkbox: true
+ },
+ {
+ id: 'close',
+ label: menu.value.closeTab || 'Close Tab',
+ shortcut: 'MOD+W'
+ }
+ ]
+ },
+ {
+ label: 'Edit',
+ items: [
+ {
+ id: 'edit.undo',
+ label: 'Undo',
+ command: 'edit.undo'
+ },
+ {
+ id: 'edit.redo',
+ label: 'Redo',
+ command: 'edit.redo'
+ },
+ { type: 'separator' },
+ { id: 'copy', label: 'Copy', shortcut: 'MOD+C' },
+ { id: 'cut', label: 'Cut', shortcut: 'MOD+X' },
+ { id: 'paste', label: 'Paste', shortcut: 'MOD+V' },
+ { id: 'paste-to-replace', label: 'Paste to replace' },
+ {
+ id: 'selection.duplicate',
+ label: 'Duplicate',
+ command: 'selection.duplicate'
+ },
+ {
+ id: 'selection.delete',
+ label: 'Delete',
+ command: 'selection.delete'
+ },
+ { type: 'separator' },
+ {
+ id: 'selection.selectAll',
+ label: 'Select All',
+ command: 'selection.selectAll'
+ }
+ ]
+ },
+ {
+ label: 'View',
+ items: [
+ {
+ id: 'view.zoom100',
+ label: 'Zoom to 100%',
+ command: 'view.zoom100'
+ },
+ {
+ id: 'view.zoomFit',
+ label: 'Zoom to Fit',
+ command: 'view.zoomFit'
+ },
+ {
+ id: 'view.zoomSelection',
+ label: 'Zoom to Selection',
+ command: 'view.zoomSelection'
+ },
+ { id: 'zoom-in', label: 'Zoom In', shortcut: 'MOD+=' },
+ { id: 'zoom-out', label: 'Zoom Out', shortcut: 'MOD+-' },
+ { type: 'separator' },
+ {
+ id: 'theme',
+ label: 'Theme',
+ sub: [
+ { id: 'theme-light', label: 'Light', checkbox: true },
+ { id: 'theme-dark', label: 'Dark', checkbox: true },
+ { id: 'theme-auto', label: 'Auto', checkbox: true }
+ ]
+ },
+ { id: 'language', label: 'Language', target: 'browser' },
+ { type: 'separator' },
+ { id: 'toggle-ui', label: 'Toggle UI', shortcut: 'MOD+\\' },
+ { id: 'profiler', label: 'Profiler', checkbox: true, target: 'browser' },
+ {
+ id: 'dev-tools',
+ label: 'Developer Tools',
+ accelerator: 'CmdOrCtrl+Alt+I',
+ target: 'native'
+ }
+ ]
+ },
+ {
+ label: 'Object',
+ items: [
+ {
+ id: 'selection.group',
+ label: 'Group Selection',
+ command: 'selection.group'
+ },
+ {
+ id: 'selection.frameSelection',
+ label: 'Frame Selection',
+ command: 'selection.frameSelection'
+ },
+ {
+ id: 'selection.ungroup',
+ label: 'Ungroup Selection',
+ command: 'selection.ungroup'
+ },
+ { type: 'separator' },
+ {
+ id: 'selection.booleanUnion',
+ label: 'Union selection',
+ command: 'selection.booleanUnion'
+ },
+ {
+ id: 'selection.booleanSubtract',
+ label: 'Subtract selection',
+ command: 'selection.booleanSubtract'
+ },
+ {
+ id: 'selection.booleanIntersect',
+ label: 'Intersect selection',
+ command: 'selection.booleanIntersect'
+ },
+ {
+ id: 'selection.booleanExclude',
+ label: 'Exclude selection',
+ command: 'selection.booleanExclude'
+ },
+ {
+ id: 'selection.flatten',
+ label: 'Flatten',
+ command: 'selection.flatten'
+ },
+ {
+ id: 'selection.outlineText',
+ label: 'Outline text',
+ command: 'selection.outlineText'
+ },
+ {
+ id: 'selection.outlineStroke',
+ label: 'Outline stroke',
+ command: 'selection.outlineStroke'
+ },
+ { type: 'separator' },
+ {
+ id: 'selection.createComponent',
+ label: 'Create Component',
+ command: 'selection.createComponent'
+ },
+ {
+ id: 'selection.createComponentSet',
+ label: 'Create Component Set',
+ command: 'selection.createComponentSet'
+ },
+ {
+ id: 'selection.detachInstance',
+ label: 'Detach Instance',
+ command: 'selection.detachInstance'
+ },
+ { type: 'separator' },
+ {
+ id: 'selection.bringToFront',
+ label: 'Bring to Front',
+ command: 'selection.bringToFront'
+ },
+ {
+ id: 'selection.sendToBack',
+ label: 'Send to Back',
+ command: 'selection.sendToBack'
+ }
+ ]
+ },
+ {
+ label: 'Text',
+ items: [
+ { id: 'text.bold', label: 'Bold', shortcut: 'MOD+B' },
+ { id: 'text.italic', label: 'Italic', shortcut: 'MOD+I' },
+ { id: 'text.underline', label: 'Underline', shortcut: 'MOD+U' }
+ ]
+ },
+ {
+ label: 'Arrange',
+ items: [
+ {
+ id: 'selection.wrapInAutoLayout',
+ label: 'Wrap in Auto Layout',
+ command: 'selection.wrapInAutoLayout'
+ },
+ { type: 'separator' },
+ { id: 'align-left', label: 'Align Left', shortcut: 'ALT+A' },
+ { id: 'align-center', label: 'Align Center', shortcut: 'ALT+H' },
+ { id: 'align-right', label: 'Align Right', shortcut: 'ALT+D' },
+ { type: 'separator' },
+ { id: 'align-top', label: 'Align Top', shortcut: 'ALT+W' },
+ { id: 'align-middle', label: 'Align Middle', shortcut: 'ALT+V' },
+ { id: 'align-bottom', label: 'Align Bottom', shortcut: 'ALT+S' }
+ ]
+ }
+] satisfies AppMenuGroupSchema[]
diff --git a/src/app/shell/menu/shortcut.ts b/src/app/shell/menu/shortcut.ts
index a99790df6..c0097085c 100644
--- a/src/app/shell/menu/shortcut.ts
+++ b/src/app/shell/menu/shortcut.ts
@@ -10,7 +10,11 @@ function isActionItem(entry: AppMenuEntry): entry is AppMenuActionItem {
function findShortcutInEntries(entries: readonly AppMenuEntry[], id: string): string | undefined {
for (const entry of entries) {
if (!isActionItem(entry)) continue
- if (entry.id === id) return entry.shortcut ?? (entry.command ? editorCommandMetadata(entry.command).shortcut : undefined)
+ if (entry.id === id)
+ return (
+ entry.shortcut ??
+ (entry.command ? editorCommandMetadata(entry.command).shortcut : undefined)
+ )
const shortcut = entry.sub ? findShortcutInEntries(entry.sub, id) : undefined
if (shortcut) return shortcut
}
diff --git a/src/components/ColorPickerPanel/OkhclFields.vue b/src/components/ColorPickerPanel/OkhclFields.vue
index a8e55f882..5ed3dfeeb 100644
--- a/src/components/ColorPickerPanel/OkhclFields.vue
+++ b/src/components/ColorPickerPanel/OkhclFields.vue
@@ -29,7 +29,13 @@ const ctx = useColorPickerPanelContext()
:min="0"
:max="0.4"
:step="0.001"
- :display="{ value: toPercent(ctx.okhcl.okhcl.c), min: 0, max: 40, step: 1, parse: fromPercent }"
+ :display="{
+ value: toPercent(ctx.okhcl.okhcl.c),
+ min: 0,
+ max: 40,
+ step: 1,
+ parse: fromPercent
+ }"
:gradient-style="ctx.okhclSliderGradient?.okhclChroma ?? undefined"
:thumb-fill="colorToCSS(ctx.okhclSliderPreview?.okhclChroma ?? ctx.color)"
test-id="color-slider-okhcl-c"
@@ -42,7 +48,13 @@ const ctx = useColorPickerPanelContext()
:min="0"
:max="1"
:step="0.001"
- :display="{ value: toPercent(ctx.okhcl.okhcl.l), min: 0, max: 100, step: 1, parse: fromPercent }"
+ :display="{
+ value: toPercent(ctx.okhcl.okhcl.l),
+ min: 0,
+ max: 100,
+ step: 1,
+ parse: fromPercent
+ }"
:gradient-style="ctx.okhclSliderGradient?.okhclLightness ?? undefined"
:thumb-fill="colorToCSS(ctx.okhclSliderPreview?.okhclLightness ?? ctx.color)"
test-id="color-slider-okhcl-l"
@@ -55,7 +67,13 @@ const ctx = useColorPickerPanelContext()
:min="0"
:max="1"
:step="0.001"
- :display="{ value: toPercent(ctx.okhcl.okhcl.a ?? 1), min: 0, max: 100, step: 1, parse: fromPercent }"
+ :display="{
+ value: toPercent(ctx.okhcl.okhcl.a ?? 1),
+ min: 0,
+ max: 100,
+ step: 1,
+ parse: fromPercent
+ }"
checkerboard
:gradient-style="`background: linear-gradient(to right, transparent, ${colorToCSS(ctx.color)})`"
:thumb-fill="colorToCSS(ctx.color)"
diff --git a/src/components/LayerTree.vue b/src/components/LayerTree.vue
index 67eb46090..67a100234 100644
--- a/src/components/LayerTree.vue
+++ b/src/components/LayerTree.vue
@@ -3,12 +3,7 @@ import { useAttrs, watch } from 'vue'
import { templateRef } from '@vueuse/core'
import { TreeItem, ContextMenuRoot, ContextMenuTrigger, ContextMenuPortal } from 'reka-ui'
-import {
- LayerTreeRoot,
- LayerTreeItem,
- useI18n,
- useInlineRename
-} from '@open-pencil/vue'
+import { LayerTreeRoot, LayerTreeItem, useI18n, useInlineRename } from '@open-pencil/vue'
import { useEditorStore } from '@/app/editor/active-store'
import { nodeIcon, COMPONENT_TYPES } from '@/app/editor/icons'
import CanvasMenu from './CanvasMenu.vue'
@@ -53,165 +48,165 @@ function onTreeSelect(e: CustomEvent, select: (additive: boolean) => void) {
<div v-bind="attrs" class="relative min-h-0 flex-1 overflow-hidden">
<ContextMenuTrigger as-child @contextmenu="onLayerRightClick">
<div data-test-id="layers-scroll" class="scrollbar-thin h-full overflow-y-auto px-1">
- <template v-if="flattenItems">
- <LayerTreeItem
- v-for="item in flattenItems"
- :key="item._id"
- v-slot="{ node, isSelected, padLeft, actions }"
- :node="item.value"
- :level="item.level"
- :has-children="item.hasChildren"
- >
- <TreeItem
- v-slot="{ isExpanded }"
- :value="item.value"
+ <template v-if="flattenItems">
+ <LayerTreeItem
+ v-for="item in flattenItems"
+ :key="item._id"
+ v-slot="{ node, isSelected, padLeft, actions }"
+ :node="item.value"
:level="item.level"
- as-child
- @select="(e: CustomEvent) => onTreeSelect(e, actions.select)"
- @toggle="
- (e: CustomEvent) => {
- if (e.detail.originalEvent?.type === 'click') e.preventDefault()
- }
- "
+ :has-children="item.hasChildren"
>
- <!-- Rename mode -->
- <div
- v-if="rename.editingId.value === node.id"
- class="flex w-full items-center gap-1 py-1"
- :style="{ paddingLeft: padLeft }"
+ <TreeItem
+ v-slot="{ isExpanded }"
+ :value="item.value"
+ :level="item.level"
+ as-child
+ @select="(e: CustomEvent) => onTreeSelect(e, actions.select)"
+ @toggle="
+ (e: CustomEvent) => {
+ if (e.detail.originalEvent?.type === 'click') e.preventDefault()
+ }
+ "
>
- <span
- v-if="item.hasChildren"
- class="flex w-4 shrink-0 cursor-pointer items-center justify-center text-muted transition-transform hover:text-surface"
- :class="isExpanded ? 'rotate-90' : 'rotate-0'"
- @click.stop="actions.toggleExpand"
+ <!-- Rename mode -->
+ <div
+ v-if="rename.editingId.value === node.id"
+ class="flex w-full items-center gap-1 py-1"
+ :style="{ paddingLeft: padLeft }"
>
- <icon-lucide-chevron-right class="size-3" />
- </span>
- <span v-else class="w-4 shrink-0" />
- <component :is="nodeIcon(node)" class="size-3 shrink-0 opacity-70" />
- <input
- ref="renameInput"
- data-layer-edit
- data-test-id="layers-item-input"
- class="min-w-0 flex-1 rounded border border-accent bg-input px-1 py-0 text-xs text-surface outline-none"
- :value="node.name"
- @blur="rename.commit(node.id, $event)"
- @keydown.stop="rename.onKeydown"
- />
- </div>
+ <span
+ v-if="item.hasChildren"
+ class="flex w-4 shrink-0 cursor-pointer items-center justify-center text-muted transition-transform hover:text-surface"
+ :class="isExpanded ? 'rotate-90' : 'rotate-0'"
+ @click.stop="actions.toggleExpand"
+ >
+ <icon-lucide-chevron-right class="size-3" />
+ </span>
+ <span v-else class="w-4 shrink-0" />
+ <component :is="nodeIcon(node)" class="size-3 shrink-0 opacity-70" />
+ <input
+ ref="renameInput"
+ data-layer-edit
+ data-test-id="layers-item-input"
+ class="min-w-0 flex-1 rounded border border-accent bg-input px-1 py-0 text-xs text-surface outline-none"
+ :value="node.name"
+ @blur="rename.commit(node.id, $event)"
+ @keydown.stop="rename.onKeydown"
+ />
+ </div>
- <!-- Normal row -->
- <button
- v-else
- data-test-id="layers-item"
- class="group/row relative flex w-full cursor-pointer items-center gap-1 rounded border-none py-1 pr-1 text-left text-xs"
- :class="[
- isSelected
- ? 'bg-accent text-white'
- : 'bg-transparent text-surface hover:bg-hover',
- draggingId === node.id ? 'opacity-30' : '',
- instructionTargetId === node.id && instruction?.type === 'make-child'
- ? 'bg-accent/15 text-surface outline-2 outline-accent outline-offset-[-2px]'
- : '',
- !node.visible ? 'opacity-50' : ''
- ]"
- :style="{ paddingLeft: padLeft }"
- @dblclick="rename.start(node.id, node.name)"
- >
- <span
- v-if="item.hasChildren"
- class="flex w-4 shrink-0 cursor-pointer items-center justify-center text-muted transition-transform hover:text-surface"
- :class="isExpanded ? 'rotate-90' : 'rotate-0'"
- @click.stop="actions.toggleExpand"
+ <!-- Normal row -->
+ <button
+ v-else
+ data-test-id="layers-item"
+ class="group/row relative flex w-full cursor-pointer items-center gap-1 rounded border-none py-1 pr-1 text-left text-xs"
+ :class="[
+ isSelected
+ ? 'bg-accent text-white'
+ : 'bg-transparent text-surface hover:bg-hover',
+ draggingId === node.id ? 'opacity-30' : '',
+ instructionTargetId === node.id && instruction?.type === 'make-child'
+ ? 'bg-accent/15 text-surface outline-2 outline-accent outline-offset-[-2px]'
+ : '',
+ !node.visible ? 'opacity-50' : ''
+ ]"
+ :style="{ paddingLeft: padLeft }"
+ @dblclick="rename.start(node.id, node.name)"
>
- <icon-lucide-chevron-right class="size-3" />
- </span>
- <span v-else class="w-4 shrink-0" />
+ <span
+ v-if="item.hasChildren"
+ class="flex w-4 shrink-0 cursor-pointer items-center justify-center text-muted transition-transform hover:text-surface"
+ :class="isExpanded ? 'rotate-90' : 'rotate-0'"
+ @click.stop="actions.toggleExpand"
+ >
+ <icon-lucide-chevron-right class="size-3" />
+ </span>
+ <span v-else class="w-4 shrink-0" />
- <component
- :is="nodeIcon(node)"
- class="size-3 shrink-0"
- :class="
- COMPONENT_TYPES.has(node.type) ? 'text-component opacity-100' : 'opacity-70'
- "
- />
- <span class="min-w-0 flex-1 truncate">{{ node.name }}</span>
+ <component
+ :is="nodeIcon(node)"
+ class="size-3 shrink-0"
+ :class="
+ COMPONENT_TYPES.has(node.type) ? 'text-component opacity-100' : 'opacity-70'
+ "
+ />
+ <span class="min-w-0 flex-1 truncate">{{ node.name }}</span>
- <span
- class="flex shrink-0 items-center gap-0.5"
- :class="
- !node.locked && node.visible ? 'opacity-0 group-hover/row:opacity-100' : ''
- "
- >
- <Tip :label="node.locked ? t.unlock : t.lock">
- <span
- class="flex size-4 items-center justify-center rounded hover:bg-white/15"
- @pointerdown.stop
- @click.stop="actions.toggleLock"
- >
- <icon-lucide-lock
- v-if="node.locked"
- class="size-3"
- :class="isSelected ? 'text-white' : 'text-surface'"
- />
- <icon-lucide-unlock
- v-else
- class="size-3 opacity-0 group-hover/row:opacity-100"
- :class="isSelected ? 'text-white/80' : 'text-surface/70'"
- />
- </span>
- </Tip>
- <Tip :label="node.visible ? t.hide : t.show">
- <span
- class="flex size-4 items-center justify-center rounded hover:bg-white/15"
- @pointerdown.stop
- @click.stop="actions.toggleVisibility"
- >
- <icon-lucide-eye-off
- v-if="!node.visible"
- class="size-3"
- :class="isSelected ? 'text-white' : 'text-surface'"
- />
- <icon-lucide-eye
- v-else
- class="size-3 opacity-0 group-hover/row:opacity-100"
- :class="isSelected ? 'text-white/80' : 'text-surface/70'"
- />
- </span>
- </Tip>
- </span>
+ <span
+ class="flex shrink-0 items-center gap-0.5"
+ :class="
+ !node.locked && node.visible ? 'opacity-0 group-hover/row:opacity-100' : ''
+ "
+ >
+ <Tip :label="node.locked ? t.unlock : t.lock">
+ <span
+ class="flex size-4 items-center justify-center rounded hover:bg-white/15"
+ @pointerdown.stop
+ @click.stop="actions.toggleLock"
+ >
+ <icon-lucide-lock
+ v-if="node.locked"
+ class="size-3"
+ :class="isSelected ? 'text-white' : 'text-surface'"
+ />
+ <icon-lucide-unlock
+ v-else
+ class="size-3 opacity-0 group-hover/row:opacity-100"
+ :class="isSelected ? 'text-white/80' : 'text-surface/70'"
+ />
+ </span>
+ </Tip>
+ <Tip :label="node.visible ? t.hide : t.show">
+ <span
+ class="flex size-4 items-center justify-center rounded hover:bg-white/15"
+ @pointerdown.stop
+ @click.stop="actions.toggleVisibility"
+ >
+ <icon-lucide-eye-off
+ v-if="!node.visible"
+ class="size-3"
+ :class="isSelected ? 'text-white' : 'text-surface'"
+ />
+ <icon-lucide-eye
+ v-else
+ class="size-3 opacity-0 group-hover/row:opacity-100"
+ :class="isSelected ? 'text-white/80' : 'text-surface/70'"
+ />
+ </span>
+ </Tip>
+ </span>
- <div
- v-if="instructionTargetId === node.id && instruction?.type === 'make-child'"
- class="pointer-events-none absolute inset-y-1 rounded border border-accent bg-accent/10"
- :style="{
- left: `${item.level * INDENT}px`,
- right: '4px'
- }"
- />
+ <div
+ v-if="instructionTargetId === node.id && instruction?.type === 'make-child'"
+ class="pointer-events-none absolute inset-y-1 rounded border border-accent bg-accent/10"
+ :style="{
+ left: `${item.level * INDENT}px`,
+ right: '4px'
+ }"
+ />
- <!-- DnD reorder indicator -->
- <div
- v-if="
- instructionTargetId === node.id &&
- instruction &&
- instruction.type !== 'make-child'
- "
- class="pointer-events-none absolute h-0.5 bg-accent"
- :class="{
- 'bottom-0': instruction.type === 'reorder-below',
- 'top-0': instruction.type === 'reorder-above'
- }"
- :style="{
- left: `${(item.level - 1) * INDENT}px`,
- width: `calc(100% - ${(item.level - 1) * INDENT}px)`
- }"
- />
- </button>
- </TreeItem>
- </LayerTreeItem>
- </template>
+ <!-- DnD reorder indicator -->
+ <div
+ v-if="
+ instructionTargetId === node.id &&
+ instruction &&
+ instruction.type !== 'make-child'
+ "
+ class="pointer-events-none absolute h-0.5 bg-accent"
+ :class="{
+ 'bottom-0': instruction.type === 'reorder-below',
+ 'top-0': instruction.type === 'reorder-above'
+ }"
+ :style="{
+ left: `${(item.level - 1) * INDENT}px`,
+ width: `calc(100% - ${(item.level - 1) * INDENT}px)`
+ }"
+ />
+ </button>
+ </TreeItem>
+ </LayerTreeItem>
+ </template>
</div>
</ContextMenuTrigger>
</div>
diff --git a/src/components/PagesPanel.vue b/src/components/PagesPanel.vue
index 0a63aa795..a9e0469c0 100644
--- a/src/components/PagesPanel.vue
+++ b/src/components/PagesPanel.vue
@@ -53,45 +53,48 @@ function handlePageDblClick(
</Tip>
</div>
<div class="min-h-0 flex-1 overflow-hidden">
- <div data-test-id="pages-scroll" class="scrollbar-thin h-full overflow-x-hidden overflow-y-auto px-1 pb-1">
- <div v-for="pg in pages" :key="pg.id">
- <div
- v-if="rename.editingId.value === pg.id"
- class="flex w-full items-center gap-1.5 rounded px-2 py-1"
- >
- <icon-lucide-file class="size-3 shrink-0 opacity-70" />
- <input
- ref="pageInput"
- data-test-id="pages-item-input"
- class="min-w-0 flex-1 rounded border border-accent bg-input px-1 py-0 text-xs text-surface outline-none"
- :value="pg.name"
- @blur="rename.commit(pg.id, $event)"
- @keydown.stop="rename.onKeydown"
- />
- </div>
- <div
- v-else-if="isDivider(pg)"
- class="my-1 flex items-center px-2"
- @dblclick="startRename(pg)"
- >
- <div class="h-px flex-1 bg-border" />
+ <div
+ data-test-id="pages-scroll"
+ class="scrollbar-thin h-full overflow-x-hidden overflow-y-auto px-1 pb-1"
+ >
+ <div v-for="pg in pages" :key="pg.id">
+ <div
+ v-if="rename.editingId.value === pg.id"
+ class="flex w-full items-center gap-1.5 rounded px-2 py-1"
+ >
+ <icon-lucide-file class="size-3 shrink-0 opacity-70" />
+ <input
+ ref="pageInput"
+ data-test-id="pages-item-input"
+ class="min-w-0 flex-1 rounded border border-accent bg-input px-1 py-0 text-xs text-surface outline-none"
+ :value="pg.name"
+ @blur="rename.commit(pg.id, $event)"
+ @keydown.stop="rename.onKeydown"
+ />
+ </div>
+ <div
+ v-else-if="isDivider(pg)"
+ class="my-1 flex items-center px-2"
+ @dblclick="startRename(pg)"
+ >
+ <div class="h-px flex-1 bg-border" />
+ </div>
+ <button
+ v-else
+ data-test-id="pages-item"
+ class="flex w-full cursor-pointer items-center gap-1.5 rounded border-none px-2 py-1 text-left text-xs"
+ :class="
+ pg.id === currentPageId
+ ? 'bg-hover text-surface'
+ : 'bg-transparent text-muted hover:bg-hover hover:text-surface'
+ "
+ @click="actions.switch(pg.id)"
+ @dblclick="handlePageDblClick(pg, actions.rename)"
+ >
+ <icon-lucide-file class="size-3 shrink-0" />
+ <span class="truncate">{{ pg.name }}</span>
+ </button>
</div>
- <button
- v-else
- data-test-id="pages-item"
- class="flex w-full cursor-pointer items-center gap-1.5 rounded border-none px-2 py-1 text-left text-xs"
- :class="
- pg.id === currentPageId
- ? 'bg-hover text-surface'
- : 'bg-transparent text-muted hover:bg-hover hover:text-surface'
- "
- @click="actions.switch(pg.id)"
- @dblclick="handlePageDblClick(pg, actions.rename)"
- >
- <icon-lucide-file class="size-3 shrink-0" />
- <span class="truncate">{{ pg.name }}</span>
- </button>
- </div>
</div>
</div>
</div>
diff --git a/src/components/Toolbar/ToolButton.vue b/src/components/Toolbar/ToolButton.vue
index 055b52979..78351c627 100644
--- a/src/components/Toolbar/ToolButton.vue
+++ b/src/components/Toolbar/ToolButton.vue
@@ -8,12 +8,7 @@ interface ToolButtonProps extends RequiredTestIdProps {
mobile?: boolean
}
-const {
- icon,
- active = false,
- mobile = false,
- testId
-} = defineProps<ToolButtonProps>()
+const { icon, active = false, mobile = false, testId } = defineProps<ToolButtonProps>()
const emit = defineEmits<{
click: []
diff --git a/src/components/properties/AppearanceSection.vue b/src/components/properties/AppearanceSection.vue
index 0fd358c7b..54648e962 100644
--- a/src/components/properties/AppearanceSection.vue
+++ b/src/components/properties/AppearanceSection.vue
@@ -68,65 +68,65 @@ function onToggleCorners() {
<div class="flex gap-1.5">
<Tip :label="panels.opacity">
- <VariableScrubInput
- v-if="node"
- suffix="%"
- :model-value="opacityPercent"
- :min="0"
- :max="100"
- :node-id="node.id"
- binding-path="opacity"
- @update:model-value="updateProp('opacity', $event / 100)"
- @commit="(v: number, p: number) => commitProp('opacity', v / 100, p / 100)"
- >
- <template #icon>
- <icon-lucide-blend class="size-3" />
- </template>
- </VariableScrubInput>
- <ScrubInput
- v-else
- suffix="%"
- :model-value="opacityPercent"
- :min="0"
- :max="100"
- @update:model-value="updateProp('opacity', $event / 100)"
- @commit="(v: number, p: number) => commitProp('opacity', v / 100, p / 100)"
- >
- <template #icon>
- <icon-lucide-blend class="size-3" />
- </template>
- </ScrubInput>
- </Tip>
+ <VariableScrubInput
+ v-if="node"
+ suffix="%"
+ :model-value="opacityPercent"
+ :min="0"
+ :max="100"
+ :node-id="node.id"
+ binding-path="opacity"
+ @update:model-value="updateProp('opacity', $event / 100)"
+ @commit="(v: number, p: number) => commitProp('opacity', v / 100, p / 100)"
+ >
+ <template #icon>
+ <icon-lucide-blend class="size-3" />
+ </template>
+ </VariableScrubInput>
+ <ScrubInput
+ v-else
+ suffix="%"
+ :model-value="opacityPercent"
+ :min="0"
+ :max="100"
+ @update:model-value="updateProp('opacity', $event / 100)"
+ @commit="(v: number, p: number) => commitProp('opacity', v / 100, p / 100)"
+ >
+ <template #icon>
+ <icon-lucide-blend class="size-3" />
+ </template>
+ </ScrubInput>
+ </Tip>
<template v-if="hasCornerRadius">
- <Tip :label="panels.radius">
- <VariableScrubInput
- v-if="!showIndependentCorners && node"
- data-test-id="corner-radius-input"
- :model-value="cornerRadiusValue"
- :min="0"
- :node-id="node.id"
- binding-path="cornerRadius"
- @update:model-value="updateProp('cornerRadius', $event)"
- @commit="(v: number, p: number) => commitProp('cornerRadius', v, p)"
- >
- <template #icon>
- <icon-lucide-square-round-corner class="size-3" />
- </template>
- </VariableScrubInput>
- <ScrubInput
- v-else-if="!showIndependentCorners"
- data-test-id="corner-radius-input"
- :model-value="cornerRadiusValue"
- :min="0"
- @update:model-value="updateProp('cornerRadius', $event)"
- @commit="(v: number, p: number) => commitProp('cornerRadius', v, p)"
- >
- <template #icon>
- <icon-lucide-square-round-corner class="size-3" />
- </template>
- </ScrubInput>
- </Tip>
+ <Tip :label="panels.radius">
+ <VariableScrubInput
+ v-if="!showIndependentCorners && node"
+ data-test-id="corner-radius-input"
+ :model-value="cornerRadiusValue"
+ :min="0"
+ :node-id="node.id"
+ binding-path="cornerRadius"
+ @update:model-value="updateProp('cornerRadius', $event)"
+ @commit="(v: number, p: number) => commitProp('cornerRadius', v, p)"
+ >
+ <template #icon>
+ <icon-lucide-square-round-corner class="size-3" />
+ </template>
+ </VariableScrubInput>
+ <ScrubInput
+ v-else-if="!showIndependentCorners"
+ data-test-id="corner-radius-input"
+ :model-value="cornerRadiusValue"
+ :min="0"
+ @update:model-value="updateProp('cornerRadius', $event)"
+ @commit="(v: number, p: number) => commitProp('cornerRadius', v, p)"
+ >
+ <template #icon>
+ <icon-lucide-square-round-corner class="size-3" />
+ </template>
+ </ScrubInput>
+ </Tip>
<Tip :label="panels.independentCornerRadii">
<button
diff --git a/src/components/properties/ColorStyleRow.vue b/src/components/properties/ColorStyleRow.vue
index a1dc1bc66..b5094a1aa 100644
--- a/src/components/properties/ColorStyleRow.vue
+++ b/src/components/properties/ColorStyleRow.vue
@@ -54,16 +54,16 @@ const { panels, dialogs } = useI18n()
<slot />
</div>
- <Tip :label="panels.opacity">
- <ScrubInput
- class="w-12 shrink-0"
- suffix="%"
- :model-value="opacityPercent(item.opacity)"
- :min="0"
- :max="100"
- @update:model-value="emit('patch', { opacity: opacityFromPercent($event) })"
- />
- </Tip>
+ <Tip :label="panels.opacity">
+ <ScrubInput
+ class="w-12 shrink-0"
+ suffix="%"
+ :model-value="opacityPercent(item.opacity)"
+ :min="0"
+ :max="100"
+ @update:model-value="emit('patch', { opacity: opacityFromPercent($event) })"
+ />
+ </Tip>
<VariablePickerPopover
v-if="
diff --git a/src/components/properties/EffectsSection.vue b/src/components/properties/EffectsSection.vue
index 08c28415b..6bf66443a 100644
--- a/src/components/properties/EffectsSection.vue
+++ b/src/components/properties/EffectsSection.vue
@@ -103,54 +103,58 @@ const sectionCls = useSectionUI()
<div class="flex flex-col gap-1.5 py-1.5">
<template v-if="effectsCtx.isShadow(effect.type)">
<div class="flex items-center gap-1.5">
- <Tip :label="panels.xAxis">
- <ScrubInput
- icon="X"
- :model-value="effect.offset.x"
- @update:model-value="
- effectsCtx.scrubEffect(activeNode, i, { offset: { ...effect.offset, x: $event } })
- "
- @commit="
- effectsCtx.commitEffect(activeNode, i, {
- offset: { ...effect.offset, x: $event }
- })
- "
- />
- </Tip>
- <Tip :label="panels.yAxis">
- <ScrubInput
- icon="Y"
- :model-value="effect.offset.y"
- @update:model-value="
- effectsCtx.scrubEffect(activeNode, i, { offset: { ...effect.offset, y: $event } })
- "
- @commit="
- effectsCtx.commitEffect(activeNode, i, {
- offset: { ...effect.offset, y: $event }
- })
- "
- />
- </Tip>
+ <Tip :label="panels.xAxis">
+ <ScrubInput
+ icon="X"
+ :model-value="effect.offset.x"
+ @update:model-value="
+ effectsCtx.scrubEffect(activeNode, i, {
+ offset: { ...effect.offset, x: $event }
+ })
+ "
+ @commit="
+ effectsCtx.commitEffect(activeNode, i, {
+ offset: { ...effect.offset, x: $event }
+ })
+ "
+ />
+ </Tip>
+ <Tip :label="panels.yAxis">
+ <ScrubInput
+ icon="Y"
+ :model-value="effect.offset.y"
+ @update:model-value="
+ effectsCtx.scrubEffect(activeNode, i, {
+ offset: { ...effect.offset, y: $event }
+ })
+ "
+ @commit="
+ effectsCtx.commitEffect(activeNode, i, {
+ offset: { ...effect.offset, y: $event }
+ })
+ "
+ />
+ </Tip>
</div>
<div class="flex items-center gap-1.5">
- <Tip :label="panels.radius">
- <ScrubInput
- icon="B"
- :model-value="effect.radius"
- :min="0"
- @update:model-value="effectsCtx.scrubEffect(activeNode, i, { radius: $event })"
- @commit="effectsCtx.commitEffect(activeNode, i, { radius: $event })"
- />
- </Tip>
- <Tip :label="panels.spread">
- <ScrubInput
- icon="S"
- :model-value="effect.spread"
- @update:model-value="effectsCtx.scrubEffect(activeNode, i, { spread: $event })"
- @commit="effectsCtx.commitEffect(activeNode, i, { spread: $event })"
- />
- </Tip>
+ <Tip :label="panels.radius">
+ <ScrubInput
+ icon="B"
+ :model-value="effect.radius"
+ :min="0"
+ @update:model-value="effectsCtx.scrubEffect(activeNode, i, { radius: $event })"
+ @commit="effectsCtx.commitEffect(activeNode, i, { radius: $event })"
+ />
+ </Tip>
+ <Tip :label="panels.spread">
+ <ScrubInput
+ icon="S"
+ :model-value="effect.spread"
+ @update:model-value="effectsCtx.scrubEffect(activeNode, i, { spread: $event })"
+ @commit="effectsCtx.commitEffect(activeNode, i, { spread: $event })"
+ />
+ </Tip>
</div>
<div class="flex items-center gap-1.5">
@@ -159,25 +163,25 @@ const sectionCls = useSectionUI()
editable
@update="effectsCtx.updateColor(actions.patch, i, $event)"
/>
- <Tip :label="panels.opacity">
- <ScrubInput
- class="w-14"
- suffix="%"
- :model-value="Math.round(effect.color.a * 100)"
- :min="0"
- :max="100"
- @update:model-value="
- effectsCtx.scrubEffect(activeNode, i, {
- color: { ...effect.color, a: Math.max(0, Math.min(1, $event / 100)) }
- })
- "
- @commit="
- effectsCtx.commitEffect(activeNode, i, {
- color: { ...effect.color, a: Math.max(0, Math.min(1, $event / 100)) }
- })
- "
- />
- </Tip>
+ <Tip :label="panels.opacity">
+ <ScrubInput
+ class="w-14"
+ suffix="%"
+ :model-value="Math.round(effect.color.a * 100)"
+ :min="0"
+ :max="100"
+ @update:model-value="
+ effectsCtx.scrubEffect(activeNode, i, {
+ color: { ...effect.color, a: Math.max(0, Math.min(1, $event / 100)) }
+ })
+ "
+ @commit="
+ effectsCtx.commitEffect(activeNode, i, {
+ color: { ...effect.color, a: Math.max(0, Math.min(1, $event / 100)) }
+ })
+ "
+ />
+ </Tip>
</div>
</template>
diff --git a/src/components/properties/ExportSection.vue b/src/components/properties/ExportSection.vue
index cc102b3b2..6f040d074 100644
--- a/src/components/properties/ExportSection.vue
+++ b/src/components/properties/ExportSection.vue
@@ -150,19 +150,19 @@ onScopeDispose(() => {
:data-test-index="i"
class="flex items-center gap-1.5 py-0.5"
>
- <AppSelect
- v-if="formatSupportsScale(setting.format)"
- :model-value="setting.scale"
- :options="SCALE_OPTIONS"
- :label="panels.exportScale"
- @update:model-value="updateScale(i, Number($event))"
- />
- <AppSelect
- :model-value="setting.format"
- :options="FORMAT_OPTIONS"
- :label="panels.exportFormat"
- @update:model-value="updateFormat(i, $event as ExportFormatId)"
- />
+ <AppSelect
+ v-if="formatSupportsScale(setting.format)"
+ :model-value="setting.scale"
+ :options="SCALE_OPTIONS"
+ :label="panels.exportScale"
+ @update:model-value="updateScale(i, Number($event))"
+ />
+ <AppSelect
+ :model-value="setting.format"
+ :options="FORMAT_OPTIONS"
+ :label="panels.exportFormat"
+ @update:model-value="updateFormat(i, $event as ExportFormatId)"
+ />
<Tip :label="panels.removeExport">
<button
:class="useIconButtonUI({ ui: { base: 'shrink-0' } }).base"
diff --git a/src/components/properties/LayoutSection/SizeControls.vue b/src/components/properties/LayoutSection/SizeControls.vue
index f34ee67a3..e0073b3a5 100644
--- a/src/components/properties/LayoutSection/SizeControls.vue
+++ b/src/components/properties/LayoutSection/SizeControls.vue
@@ -170,171 +170,171 @@ function handleSizeSelect(axis: 'width' | 'height', value: SizeSelectValue) {
<template>
<div class="flex gap-1.5">
<div ref="widthFieldRef" class="min-w-0 flex-1">
- <Tip :label="panels.width">
- <ScrubInput
- data-test-id="layout-width-input"
- icon="W"
- :model-value="Math.round(resolvedBoundNumber('width') ?? ctx.node.width)"
- :min="0"
- @update:model-value="updateSizeProp('width', $event)"
- @commit="(v: number, p: number) => commitSizeProp('width', v, p)"
- >
- <template #suffix>
- <BoundVariableButton
- v-if="widthVariableBinding.getBoundVariable(ctx.node.id)"
- test-id="layout-width-unbind-variable"
- :label="panels.detachVariable"
- @detach="widthVariableBinding.unbindVariable(ctx.node.id)"
- />
- <VariablePickerPopover
- v-else
- v-model:search-term="widthVariableBinding.searchTerm.value"
- :variables="widthVariableBinding.filteredVariables.value"
- :trigger-label="panels.applyVariable"
- :search-placeholder="dialogs.search"
- :empty-label="panels.noVariablesFound"
- :trigger-test-id="'layout-width-apply-variable'"
- :create-label="panels.createNumberVariable({ value: Math.round(ctx.node.width) })"
- :create-name-placeholder="panels.variableName"
- :create-submit-label="panels.create"
- :create-test-id="'layout-width-apply-variable-create'"
- @select="bindSizeVariable('width', $event.id)"
- @create="createAndBindSizeVariable('width', $event)"
- />
- <SelectRoot
- :model-value="ctx.widthSizing"
- @update:model-value="handleSizeSelect('width', $event as SizeSelectValue)"
- >
- <SelectTrigger
- data-test-id="layout-width-sizing-menu"
- :reference="anchorRef(widthFieldRef)"
- class="flex shrink-0 cursor-pointer items-center justify-center self-stretch border-none bg-transparent px-1.5 text-[11px] text-muted outline-none"
- @pointerdown.stop
- >
- <icon-lucide-chevron-down class="size-3" />
- </SelectTrigger>
- <SelectPortal>
- <SelectContent
- position="popper"
- align="start"
- :side-offset="4"
- :class="sizingSelect.content"
- >
- <SelectViewport class="p-0.5">
- <SelectItem
- v-for="opt in ctx.widthSizingOptions"
- :key="opt.value"
- :value="opt.value"
- :class="sizingSelect.item"
- >
- <SelectItemIndicator
- class="absolute left-1.5 inline-flex items-center justify-center"
- >
- <icon-lucide-check class="size-3 text-accent" />
- </SelectItemIndicator>
- <SelectItemText>{{ opt.label }}</SelectItemText>
- </SelectItem>
- <SelectItem
- v-for="item in widthLimitItems"
- :key="item.prop"
- :value="`${ctx.node[item.prop] == null ? 'add' : 'remove'}-${item.prop}`"
- :class="sizingSelect.item"
- >
- <SelectItemText>
- {{ ctx.node[item.prop] == null ? item.addLabel() : item.removeLabel() }}
- </SelectItemText>
- </SelectItem>
- </SelectViewport>
- </SelectContent>
- </SelectPortal>
- </SelectRoot>
- </template>
- </ScrubInput>
- </Tip>
+ <Tip :label="panels.width">
+ <ScrubInput
+ data-test-id="layout-width-input"
+ icon="W"
+ :model-value="Math.round(resolvedBoundNumber('width') ?? ctx.node.width)"
+ :min="0"
+ @update:model-value="updateSizeProp('width', $event)"
+ @commit="(v: number, p: number) => commitSizeProp('width', v, p)"
+ >
+ <template #suffix>
+ <BoundVariableButton
+ v-if="widthVariableBinding.getBoundVariable(ctx.node.id)"
+ test-id="layout-width-unbind-variable"
+ :label="panels.detachVariable"
+ @detach="widthVariableBinding.unbindVariable(ctx.node.id)"
+ />
+ <VariablePickerPopover
+ v-else
+ v-model:search-term="widthVariableBinding.searchTerm.value"
+ :variables="widthVariableBinding.filteredVariables.value"
+ :trigger-label="panels.applyVariable"
+ :search-placeholder="dialogs.search"
+ :empty-label="panels.noVariablesFound"
+ :trigger-test-id="'layout-width-apply-variable'"
+ :create-label="panels.createNumberVariable({ value: Math.round(ctx.node.width) })"
+ :create-name-placeholder="panels.variableName"
+ :create-submit-label="panels.create"
+ :create-test-id="'layout-width-apply-variable-create'"
+ @select="bindSizeVariable('width', $event.id)"
+ @create="createAndBindSizeVariable('width', $event)"
+ />
+ <SelectRoot
+ :model-value="ctx.widthSizing"
+ @update:model-value="handleSizeSelect('width', $event as SizeSelectValue)"
+ >
+ <SelectTrigger
+ data-test-id="layout-width-sizing-menu"
+ :reference="anchorRef(widthFieldRef)"
+ class="flex shrink-0 cursor-pointer items-center justify-center self-stretch border-none bg-transparent px-1.5 text-[11px] text-muted outline-none"
+ @pointerdown.stop
+ >
+ <icon-lucide-chevron-down class="size-3" />
+ </SelectTrigger>
+ <SelectPortal>
+ <SelectContent
+ position="popper"
+ align="start"
+ :side-offset="4"
+ :class="sizingSelect.content"
+ >
+ <SelectViewport class="p-0.5">
+ <SelectItem
+ v-for="opt in ctx.widthSizingOptions"
+ :key="opt.value"
+ :value="opt.value"
+ :class="sizingSelect.item"
+ >
+ <SelectItemIndicator
+ class="absolute left-1.5 inline-flex items-center justify-center"
+ >
+ <icon-lucide-check class="size-3 text-accent" />
+ </SelectItemIndicator>
+ <SelectItemText>{{ opt.label }}</SelectItemText>
+ </SelectItem>
+ <SelectItem
+ v-for="item in widthLimitItems"
+ :key="item.prop"
+ :value="`${ctx.node[item.prop] == null ? 'add' : 'remove'}-${item.prop}`"
+ :class="sizingSelect.item"
+ >
+ <SelectItemText>
+ {{ ctx.node[item.prop] == null ? item.addLabel() : item.removeLabel() }}
+ </SelectItemText>
+ </SelectItem>
+ </SelectViewport>
+ </SelectContent>
+ </SelectPortal>
+ </SelectRoot>
+ </template>
+ </ScrubInput>
+ </Tip>
</div>
<div ref="heightFieldRef" class="min-w-0 flex-1">
- <Tip :label="panels.height">
- <ScrubInput
- data-test-id="layout-height-input"
- icon="H"
- :model-value="Math.round(resolvedBoundNumber('height') ?? ctx.node.height)"
- :min="0"
- @update:model-value="updateSizeProp('height', $event)"
- @commit="(v: number, p: number) => commitSizeProp('height', v, p)"
- >
- <template #suffix>
- <BoundVariableButton
- v-if="heightVariableBinding.getBoundVariable(ctx.node.id)"
- test-id="layout-height-unbind-variable"
- :label="panels.detachVariable"
- @detach="heightVariableBinding.unbindVariable(ctx.node.id)"
- />
- <VariablePickerPopover
- v-else
- v-model:search-term="heightVariableBinding.searchTerm.value"
- :variables="heightVariableBinding.filteredVariables.value"
- :trigger-label="panels.applyVariable"
- :search-placeholder="dialogs.search"
- :empty-label="panels.noVariablesFound"
- :trigger-test-id="'layout-height-apply-variable'"
- :create-label="panels.createNumberVariable({ value: Math.round(ctx.node.height) })"
- :create-name-placeholder="panels.variableName"
- :create-submit-label="panels.create"
- :create-test-id="'layout-height-apply-variable-create'"
- @select="bindSizeVariable('height', $event.id)"
- @create="createAndBindSizeVariable('height', $event)"
- />
- <SelectRoot
- :model-value="ctx.heightSizing"
- @update:model-value="handleSizeSelect('height', $event as SizeSelectValue)"
- >
- <SelectTrigger
- data-test-id="layout-height-sizing-menu"
- :reference="anchorRef(heightFieldRef)"
- class="flex shrink-0 cursor-pointer items-center justify-center self-stretch border-none bg-transparent px-1.5 text-[11px] text-muted outline-none"
- @pointerdown.stop
- >
- <icon-lucide-chevron-down class="size-3" />
- </SelectTrigger>
- <SelectPortal>
- <SelectContent
- position="popper"
- align="start"
- :side-offset="4"
- :class="sizingSelect.content"
- >
- <SelectViewport class="p-0.5">
- <SelectItem
- v-for="opt in ctx.heightSizingOptions"
- :key="opt.value"
- :value="opt.value"
- :class="sizingSelect.item"
- >
- <SelectItemIndicator
- class="absolute left-1.5 inline-flex items-center justify-center"
- >
- <icon-lucide-check class="size-3 text-accent" />
- </SelectItemIndicator>
- <SelectItemText>{{ opt.label }}</SelectItemText>
- </SelectItem>
- <SelectItem
- v-for="item in heightLimitItems"
- :key="item.prop"
- :value="`${ctx.node[item.prop] == null ? 'add' : 'remove'}-${item.prop}`"
- :class="sizingSelect.item"
- >
- <SelectItemText>
- {{ ctx.node[item.prop] == null ? item.addLabel() : item.removeLabel() }}
- </SelectItemText>
- </SelectItem>
- </SelectViewport>
- </SelectContent>
- </SelectPortal>
- </SelectRoot>
- </template>
- </ScrubInput>
- </Tip>
+ <Tip :label="panels.height">
+ <ScrubInput
+ data-test-id="layout-height-input"
+ icon="H"
+ :model-value="Math.round(resolvedBoundNumber('height') ?? ctx.node.height)"
+ :min="0"
+ @update:model-value="updateSizeProp('height', $event)"
+ @commit="(v: number, p: number) => commitSizeProp('height', v, p)"
+ >
+ <template #suffix>
+ <BoundVariableButton
+ v-if="heightVariableBinding.getBoundVariable(ctx.node.id)"
+ test-id="layout-height-unbind-variable"
+ :label="panels.detachVariable"
+ @detach="heightVariableBinding.unbindVariable(ctx.node.id)"
+ />
+ <VariablePickerPopover
+ v-else
+ v-model:search-term="heightVariableBinding.searchTerm.value"
+ :variables="heightVariableBinding.filteredVariables.value"
+ :trigger-label="panels.applyVariable"
+ :search-placeholder="dialogs.search"
+ :empty-label="panels.noVariablesFound"
+ :trigger-test-id="'layout-height-apply-variable'"
+ :create-label="panels.createNumberVariable({ value: Math.round(ctx.node.height) })"
+ :create-name-placeholder="panels.variableName"
+ :create-submit-label="panels.create"
+ :create-test-id="'layout-height-apply-variable-create'"
+ @select="bindSizeVariable('height', $event.id)"
+ @create="createAndBindSizeVariable('height', $event)"
+ />
+ <SelectRoot
+ :model-value="ctx.heightSizing"
+ @update:model-value="handleSizeSelect('height', $event as SizeSelectValue)"
+ >
+ <SelectTrigger
+ data-test-id="layout-height-sizing-menu"
+ :reference="anchorRef(heightFieldRef)"
+ class="flex shrink-0 cursor-pointer items-center justify-center self-stretch border-none bg-transparent px-1.5 text-[11px] text-muted outline-none"
+ @pointerdown.stop
+ >
+ <icon-lucide-chevron-down class="size-3" />
+ </SelectTrigger>
+ <SelectPortal>
+ <SelectContent
+ position="popper"
+ align="start"
+ :side-offset="4"
+ :class="sizingSelect.content"
+ >
+ <SelectViewport class="p-0.5">
+ <SelectItem
+ v-for="opt in ctx.heightSizingOptions"
+ :key="opt.value"
+ :value="opt.value"
+ :class="sizingSelect.item"
+ >
+ <SelectItemIndicator
+ class="absolute left-1.5 inline-flex items-center justify-center"
+ >
+ <icon-lucide-check class="size-3 text-accent" />
+ </SelectItemIndicator>
+ <SelectItemText>{{ opt.label }}</SelectItemText>
+ </SelectItem>
+ <SelectItem
+ v-for="item in heightLimitItems"
+ :key="item.prop"
+ :value="`${ctx.node[item.prop] == null ? 'add' : 'remove'}-${item.prop}`"
+ :class="sizingSelect.item"
+ >
+ <SelectItemText>
+ {{ ctx.node[item.prop] == null ? item.addLabel() : item.removeLabel() }}
+ </SelectItemText>
+ </SelectItem>
+ </SelectViewport>
+ </SelectContent>
+ </SelectPortal>
+ </SelectRoot>
+ </template>
+ </ScrubInput>
+ </Tip>
</div>
</div>
diff --git a/src/components/properties/PositionSection.vue b/src/components/properties/PositionSection.vue
index 138044e4b..435fd4eb0 100644
--- a/src/components/properties/PositionSection.vue
+++ b/src/components/properties/PositionSection.vue
@@ -93,61 +93,61 @@ function handleAlign(
</div>
<div class="flex gap-1.5">
- <Tip :label="panels.xAxis">
- <ScrubInput
- icon="X"
- :model-value="xValue"
- @update:model-value="actions.updateProp('x', $event)"
- @commit="(v: number, p: number) => actions.commitProp('x', v, p)"
- />
- </Tip>
- <Tip :label="panels.yAxis">
- <ScrubInput
- icon="Y"
- :model-value="yValue"
- @update:model-value="actions.updateProp('y', $event)"
- @commit="(v: number, p: number) => actions.commitProp('y', v, p)"
- />
- </Tip>
+ <Tip :label="panels.xAxis">
+ <ScrubInput
+ icon="X"
+ :model-value="xValue"
+ @update:model-value="actions.updateProp('x', $event)"
+ @commit="(v: number, p: number) => actions.commitProp('x', v, p)"
+ />
+ </Tip>
+ <Tip :label="panels.yAxis">
+ <ScrubInput
+ icon="Y"
+ :model-value="yValue"
+ @update:model-value="actions.updateProp('y', $event)"
+ @commit="(v: number, p: number) => actions.commitProp('y', v, p)"
+ />
+ </Tip>
</div>
<div v-if="isMulti" class="mt-1.5 flex gap-1.5">
- <Tip :label="panels.width">
- <ScrubInput
- icon="W"
- :model-value="wValue"
- :min="1"
- @update:model-value="actions.updateProp('width', $event)"
- @commit="(v: number, p: number) => actions.commitProp('width', v, p)"
- />
- </Tip>
- <Tip :label="panels.height">
- <ScrubInput
- icon="H"
- :model-value="hValue"
- :min="1"
- @update:model-value="actions.updateProp('height', $event)"
- @commit="(v: number, p: number) => actions.commitProp('height', v, p)"
- />
- </Tip>
+ <Tip :label="panels.width">
+ <ScrubInput
+ icon="W"
+ :model-value="wValue"
+ :min="1"
+ @update:model-value="actions.updateProp('width', $event)"
+ @commit="(v: number, p: number) => actions.commitProp('width', v, p)"
+ />
+ </Tip>
+ <Tip :label="panels.height">
+ <ScrubInput
+ icon="H"
+ :model-value="hValue"
+ :min="1"
+ @update:model-value="actions.updateProp('height', $event)"
+ @commit="(v: number, p: number) => actions.commitProp('height', v, p)"
+ />
+ </Tip>
</div>
<div class="mt-1.5 flex items-center gap-1.5">
- <Tip :label="panels.rotation">
- <ScrubInput
- class="flex-1"
- suffix="°"
- :model-value="rotationValue"
- :min="-360"
- :max="360"
- @update:model-value="actions.updateProp('rotation', $event)"
- @commit="(v: number, p: number) => actions.commitProp('rotation', v, p)"
- >
- <template #icon>
- <icon-lucide-rotate-cw class="size-3" />
- </template>
- </ScrubInput>
- </Tip>
+ <Tip :label="panels.rotation">
+ <ScrubInput
+ class="flex-1"
+ suffix="°"
+ :model-value="rotationValue"
+ :min="-360"
+ :max="360"
+ @update:model-value="actions.updateProp('rotation', $event)"
+ @commit="(v: number, p: number) => actions.commitProp('rotation', v, p)"
+ >
+ <template #icon>
+ <icon-lucide-rotate-cw class="size-3" />
+ </template>
+ </ScrubInput>
+ </Tip>
<Tip :label="panels.flipHorizontal">
<button
:class="useIconButtonUI({ size: 'md', ui: { base: 'shrink-0' } }).base"
diff --git a/src/components/properties/StrokeSection.vue b/src/components/properties/StrokeSection.vue
index 4351ca75b..c70d4bc7b 100644
--- a/src/components/properties/StrokeSection.vue
+++ b/src/components/properties/StrokeSection.vue
@@ -150,36 +150,36 @@ function setGap(stroke: Stroke | undefined, patch: StrokePatch, value: number) {
v-if="!isMixed && (items as unknown[]).length > 0"
class="mt-1 flex items-center gap-1.5"
>
- <AppSelect
- class="w-[72px]"
- :label="panels.strokeType"
- :model-value="strokeCtx.currentAlign(activeNode)"
- :options="strokeCtx.alignOptions"
- @update:model-value="strokeCtx.updateAlign($event as Stroke['align'], activeNode!)"
- />
- <Tip :label="panels.strokeWeight">
- <ScrubInput
- v-if="!expandedSides"
- class="flex-1"
- :model-value="activeNode!.strokes[0]?.weight ?? 1"
- :min="0"
- @update:model-value="actions.patch(0, { weight: $event })"
- >
- <template #icon>
- <svg
- class="size-3"
- viewBox="0 0 12 12"
- fill="none"
- stroke="currentColor"
- stroke-width="1.5"
- >
- <line x1="1" y1="3" x2="11" y2="3" />
- <line x1="1" y1="6" x2="11" y2="6" />
- <line x1="1" y1="9" x2="11" y2="9" />
- </svg>
- </template>
- </ScrubInput>
- </Tip>
+ <AppSelect
+ class="w-[72px]"
+ :label="panels.strokeType"
+ :model-value="strokeCtx.currentAlign(activeNode)"
+ :options="strokeCtx.alignOptions"
+ @update:model-value="strokeCtx.updateAlign($event as Stroke['align'], activeNode!)"
+ />
+ <Tip :label="panels.strokeWeight">
+ <ScrubInput
+ v-if="!expandedSides"
+ class="flex-1"
+ :model-value="activeNode!.strokes[0]?.weight ?? 1"
+ :min="0"
+ @update:model-value="actions.patch(0, { weight: $event })"
+ >
+ <template #icon>
+ <svg
+ class="size-3"
+ viewBox="0 0 12 12"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="1.5"
+ >
+ <line x1="1" y1="3" x2="11" y2="3" />
+ <line x1="1" y1="6" x2="11" y2="6" />
+ <line x1="1" y1="9" x2="11" y2="9" />
+ </svg>
+ </template>
+ </ScrubInput>
+ </Tip>
<Tip :label="panels.strokeSides">
<button
data-test-id="stroke-sides-toggle"
diff --git a/src/components/ui/AppSelect.vue b/src/components/ui/AppSelect.vue
index a5f46b131..0eed55d5a 100644
--- a/src/components/ui/AppSelect.vue
+++ b/src/components/ui/AppSelect.vue
@@ -49,28 +49,28 @@ const indicator = ui?.indicator ?? 'absolute left-1.5 inline-flex items-center j
<template>
<SelectRoot v-model="modelValue">
- <Tip :label="label">
- <SelectTrigger v-test-id="testId" :class="select.trigger">
- <SelectValue :placeholder="placeholder" />
- <icon-lucide-chevron-down class="ml-1 size-3 shrink-0 text-muted" />
- </SelectTrigger>
- <SelectPortal>
- <SelectContent position="popper" :side-offset="2" :class="select.content">
- <SelectViewport :class="viewport">
- <SelectItem
- v-for="opt in options"
- :key="String(opt.value)"
- :value="opt.value"
- :class="select.item"
- >
- <SelectItemIndicator :class="indicator">
- <icon-lucide-check class="size-3 text-accent" />
- </SelectItemIndicator>
- <SelectItemText>{{ opt.label }}</SelectItemText>
- </SelectItem>
- </SelectViewport>
- </SelectContent>
- </SelectPortal>
- </Tip>
+ <Tip :label="label">
+ <SelectTrigger v-test-id="testId" :class="select.trigger">
+ <SelectValue :placeholder="placeholder" />
+ <icon-lucide-chevron-down class="ml-1 size-3 shrink-0 text-muted" />
+ </SelectTrigger>
+ <SelectPortal>
+ <SelectContent position="popper" :side-offset="2" :class="select.content">
+ <SelectViewport :class="viewport">
+ <SelectItem
+ v-for="opt in options"
+ :key="String(opt.value)"
+ :value="opt.value"
+ :class="select.item"
+ >
+ <SelectItemIndicator :class="indicator">
+ <icon-lucide-check class="size-3 text-accent" />
+ </SelectItemIndicator>
+ <SelectItemText>{{ opt.label }}</SelectItemText>
+ </SelectItem>
+ </SelectViewport>
+ </SelectContent>
+ </SelectPortal>
+ </Tip>
</SelectRoot>
</template>
diff --git a/tests/e2e/clipboard/copy-paste.spec.ts b/tests/e2e/clipboard/copy-paste.spec.ts
index a86b44bbb..104c50222 100644
--- a/tests/e2e/clipboard/copy-paste.spec.ts
+++ b/tests/e2e/clipboard/copy-paste.spec.ts
@@ -1,5 +1,4 @@
import { expect, test, useEditorSetup } from '#tests/e2e/fixtures'
-
import { getSelectedNodes } from '#tests/helpers/store'
const editor = useEditorSetup()
@@ -20,7 +19,6 @@ function getSelectedCount() {
})
}
-
test('copy + paste via store duplicates a shape', async () => {
await editor.canvas.drawRect(100, 100, 120, 80)
await editor.canvas.waitForRender()
diff --git a/tests/e2e/code/panel.spec.ts b/tests/e2e/code/panel.spec.ts
index cbe4cb6a5..d4ff758ce 100644
--- a/tests/e2e/code/panel.spec.ts
+++ b/tests/e2e/code/panel.spec.ts
@@ -91,5 +91,10 @@ test('selecting a frame shows Frame in JSX', async () => {
test('switching back to Design tab works', async () => {
await designTab().click()
- await expect(editor.page.getByTestId('design-panel-single').or(editor.page.getByTestId('design-panel-empty')).first()).toBeVisible()
+ await expect(
+ editor.page
+ .getByTestId('design-panel-single')
+ .or(editor.page.getByTestId('design-panel-empty'))
+ .first()
+ ).toBeVisible()
})
diff --git a/tests/e2e/components/assets-panel.spec.ts b/tests/e2e/components/assets-panel.spec.ts
index 3a9569995..f920cced2 100644
--- a/tests/e2e/components/assets-panel.spec.ts
+++ b/tests/e2e/components/assets-panel.spec.ts
@@ -140,9 +140,7 @@ test('assets panel groups component sets and inserts the default variant', async
await expect(details.getByTestId('asset-details-description')).toContainText(
'Reusable button component'
)
- await expect(details.getByTestId('asset-details-library')).toContainText(
- 'lk-test-library'
- )
+ await expect(details.getByTestId('asset-details-library')).toContainText('lk-test-library')
await expect(details.getByTestId('asset-details-docs')).toBeVisible()
await expect(details.getByTestId('asset-details-property')).toContainText('Type')
await page.getByTestId('asset-details-close').click()
@@ -233,7 +231,9 @@ test('assets insertion accounts for entered container coordinates', async ({ pag
const selected = selectedId ? store.graph.getNode(selectedId) : null
if (!selected) return null
const abs = store.graph.getAbsolutePosition(selected.id)
- const center = store.screenToCanvas(...Object.values(store.viewportCanvasCenter()) as [number, number])
+ const center = store.screenToCanvas(
+ ...(Object.values(store.viewportCanvasCenter()) as [number, number])
+ )
return {
parentId: selected.parentId,
centerX: abs.x + selected.width / 2,
diff --git a/tests/e2e/context-menu/basic.spec.ts b/tests/e2e/context-menu/basic.spec.ts
index 7e8d106dd..3239f6975 100644
--- a/tests/e2e/context-menu/basic.spec.ts
+++ b/tests/e2e/context-menu/basic.spec.ts
@@ -227,7 +227,7 @@ test('outline stroke is disabled for fill-only shapes', async () => {
await editor.page.keyboard.press('Escape')
})
- test('Copy/Paste as submenu exists', async () => {
+test('Copy/Paste as submenu exists', async () => {
await rightClickShape(130, 130)
const submenuTrigger = contextItem('context-copy-paste-as')
diff --git a/tests/e2e/editor/auto-layout/drag.spec.ts b/tests/e2e/editor/auto-layout/drag.spec.ts
index 5d07f14cd..f8951f5e3 100644
--- a/tests/e2e/editor/auto-layout/drag.spec.ts
+++ b/tests/e2e/editor/auto-layout/drag.spec.ts
@@ -2,7 +2,9 @@ import { expect, test } from '@playwright/test'
import { CanvasHelper } from '#tests/helpers/canvas'
-test('dragging selected nested instance content reorders its auto-layout item', async ({ page }) => {
+test('dragging selected nested instance content reorders its auto-layout item', async ({
+ page
+}) => {
await page.goto('/')
const canvas = new CanvasHelper(page)
await canvas.waitForInit()
@@ -83,7 +85,9 @@ test('dragging selected nested instance content reorders its auto-layout item',
canvas.assertNoErrors()
})
-test('auto-layout drag does not show an insert indicator before order changes', async ({ page }) => {
+test('auto-layout drag does not show an insert indicator before order changes', async ({
+ page
+}) => {
await page.goto('/')
const canvas = new CanvasHelper(page)
await canvas.waitForInit()
diff --git a/tests/e2e/layers/reorder.spec.ts b/tests/e2e/layers/reorder.spec.ts
index e1731b350..c4c0c3e4f 100644
--- a/tests/e2e/layers/reorder.spec.ts
+++ b/tests/e2e/layers/reorder.spec.ts
@@ -75,7 +75,9 @@ test('dragging a layer into a container expands it and shows the child', async (
await source.dragTo(target, { targetPosition: { x: 70, y: 12 } })
await canvas.waitForRender()
- await expect(page.locator(`[data-node-id="${ids.rect}"]`).getByTestId('layers-item')).toBeVisible()
+ await expect(
+ page.locator(`[data-node-id="${ids.rect}"]`).getByTestId('layers-item')
+ ).toBeVisible()
expect(await layerOrder(page, ids.frame)).toEqual([ids.rect])
canvas.assertNoErrors()
})
diff --git a/tests/e2e/properties/corner-stroke-toggles.spec.ts b/tests/e2e/properties/corner-stroke-toggles.spec.ts
index 9e4b7a173..d1b7ccf6f 100644
--- a/tests/e2e/properties/corner-stroke-toggles.spec.ts
+++ b/tests/e2e/properties/corner-stroke-toggles.spec.ts
@@ -78,14 +78,16 @@ test('stroke sides toggle shows per-side weight inputs', async () => {
await expect(toggle).toBeVisible({ timeout: 5000 })
const sectionInputsBefore = await page
- .getByTestId('stroke-section').getByTestId('scrub-input')
+ .getByTestId('stroke-section')
+ .getByTestId('scrub-input')
.count()
await toggle.click()
await canvas.waitForRender()
const sectionInputsAfter = await page
- .getByTestId('stroke-section').getByTestId('scrub-input')
+ .getByTestId('stroke-section')
+ .getByTestId('scrub-input')
.count()
expect(sectionInputsAfter).toBeGreaterThan(sectionInputsBefore)
@@ -93,7 +95,8 @@ test('stroke sides toggle shows per-side weight inputs', async () => {
await canvas.waitForRender()
const sectionInputsFinal = await page
- .getByTestId('stroke-section').getByTestId('scrub-input')
+ .getByTestId('stroke-section')
+ .getByTestId('scrub-input')
.count()
expect(sectionInputsFinal).toBe(sectionInputsBefore)
})
diff --git a/tests/e2e/properties/panel.spec.ts b/tests/e2e/properties/panel.spec.ts
index e57bef461..52e4615ec 100644
--- a/tests/e2e/properties/panel.spec.ts
+++ b/tests/e2e/properties/panel.spec.ts
@@ -1,5 +1,4 @@
import { expect, test, useEditorSetup } from '#tests/e2e/fixtures'
-
import { expectDefined } from '#tests/helpers/assert'
import { getPageChildren, getSelectedNode } from '#tests/helpers/store'
@@ -11,9 +10,7 @@ test('ScrubInput drag changes X position', async () => {
const before = await getSelectedNode(editor.page)
const initialX = expectDefined(before, 'selected rectangle before drag').x
- const xScrub = editor.page
- .getByTestId('position-section').getByTestId('scrub-input')
- .first()
+ const xScrub = editor.page.getByTestId('position-section').getByTestId('scrub-input').first()
await editor.canvas.dragScrubInput(xScrub, 50)
const after = await getSelectedNode(editor.page)
diff --git a/tests/e2e/properties/visibility.spec.ts b/tests/e2e/properties/visibility.spec.ts
index 66bde4d73..301eab73f 100644
--- a/tests/e2e/properties/visibility.spec.ts
+++ b/tests/e2e/properties/visibility.spec.ts
@@ -1,32 +1,40 @@
import { expect, test, useEditorSetup } from '#tests/e2e/fixtures'
-
import { expectDefined } from '#tests/helpers/assert'
import { getSelectedNode } from '#tests/helpers/store'
const editor = useEditorSetup()
-
test('fill visibility supports repeat click and undo redo', async () => {
await editor.canvas.drawRect(120, 120, 120, 80)
await editor.canvas.waitForRender()
const fillButton = editor.page.getByTestId('fill-visibility-0')
await expect(fillButton).toBeVisible()
- expect(expectDefined(await getSelectedNode(editor.page), 'selected node').fills[0]?.visible).toBe(true)
+ expect(expectDefined(await getSelectedNode(editor.page), 'selected node').fills[0]?.visible).toBe(
+ true
+ )
await fillButton.click()
await editor.canvas.waitForRender()
- expect(expectDefined(await getSelectedNode(editor.page), 'selected node').fills[0]?.visible).toBe(false)
+ expect(expectDefined(await getSelectedNode(editor.page), 'selected node').fills[0]?.visible).toBe(
+ false
+ )
await fillButton.click()
await editor.canvas.waitForRender()
- expect(expectDefined(await getSelectedNode(editor.page), 'selected node').fills[0]?.visible).toBe(true)
+ expect(expectDefined(await getSelectedNode(editor.page), 'selected node').fills[0]?.visible).toBe(
+ true
+ )
await editor.canvas.undo()
- expect(expectDefined(await getSelectedNode(editor.page), 'selected node').fills[0]?.visible).toBe(false)
+ expect(expectDefined(await getSelectedNode(editor.page), 'selected node').fills[0]?.visible).toBe(
+ false
+ )
await editor.canvas.redo()
- expect(expectDefined(await getSelectedNode(editor.page), 'selected node').fills[0]?.visible).toBe(true)
+ expect(expectDefined(await getSelectedNode(editor.page), 'selected node').fills[0]?.visible).toBe(
+ true
+ )
})
test('stroke visibility supports repeat click and undo redo', async () => {
@@ -35,21 +43,31 @@ test('stroke visibility supports repeat click and undo redo', async () => {
const strokeButton = editor.page.getByTestId('stroke-visibility-0')
await expect(strokeButton).toBeVisible()
- expect(expectDefined(await getSelectedNode(editor.page), 'selected node').strokes[0]?.visible).toBe(true)
+ expect(
+ expectDefined(await getSelectedNode(editor.page), 'selected node').strokes[0]?.visible
+ ).toBe(true)
await strokeButton.click()
await editor.canvas.waitForRender()
- expect(expectDefined(await getSelectedNode(editor.page), 'selected node').strokes[0]?.visible).toBe(false)
+ expect(
+ expectDefined(await getSelectedNode(editor.page), 'selected node').strokes[0]?.visible
+ ).toBe(false)
await strokeButton.click()
await editor.canvas.waitForRender()
- expect(expectDefined(await getSelectedNode(editor.page), 'selected node').strokes[0]?.visible).toBe(true)
+ expect(
+ expectDefined(await getSelectedNode(editor.page), 'selected node').strokes[0]?.visible
+ ).toBe(true)
await editor.canvas.undo()
- expect(expectDefined(await getSelectedNode(editor.page), 'selected node').strokes[0]?.visible).toBe(false)
+ expect(
+ expectDefined(await getSelectedNode(editor.page), 'selected node').strokes[0]?.visible
+ ).toBe(false)
await editor.canvas.redo()
- expect(expectDefined(await getSelectedNode(editor.page), 'selected node').strokes[0]?.visible).toBe(true)
+ expect(
+ expectDefined(await getSelectedNode(editor.page), 'selected node').strokes[0]?.visible
+ ).toBe(true)
})
test('appearance visibility supports repeat click and undo redo in one step', async () => {
diff --git a/tests/e2e/text/editing.spec.ts b/tests/e2e/text/editing.spec.ts
index 15c137e44..5ce6575f9 100644
--- a/tests/e2e/text/editing.spec.ts
+++ b/tests/e2e/text/editing.spec.ts
@@ -1,11 +1,9 @@
import { expect, test, useEditorSetup } from '#tests/e2e/fixtures'
-
import { expectDefined } from '#tests/helpers/assert'
import { getSelectedNode } from '#tests/helpers/store'
const editor = useEditorSetup()
-
function getPageChildren() {
return editor.page.evaluate(() => {
const store = window.openPencil?.getStore?.()
diff --git a/tests/e2e/toolbar/basic.spec.ts b/tests/e2e/toolbar/basic.spec.ts
index 27c0fd874..4f6f0619d 100644
--- a/tests/e2e/toolbar/basic.spec.ts
+++ b/tests/e2e/toolbar/basic.spec.ts
@@ -1,5 +1,4 @@
import { expect, test, useEditorSetup } from '#tests/e2e/fixtures'
-
import { getPageChildren } from '#tests/helpers/store'
import { toolbarFlyoutItemTestId, toolbarFlyoutTestId } from '#tests/helpers/test-ids'
diff --git a/tests/e2e/variables/dialog.spec.ts b/tests/e2e/variables/dialog.spec.ts
index 8f0a14250..5f3dd0ae1 100644
--- a/tests/e2e/variables/dialog.spec.ts
+++ b/tests/e2e/variables/dialog.spec.ts
@@ -1,5 +1,4 @@
import { expect, test, useEditorSetup } from '#tests/e2e/fixtures'
-
import { variablesAddTestId } from '#tests/helpers/test-ids'
const editor = useEditorSetup()
@@ -57,9 +56,9 @@ test('add variable menu creates non-color variable types', async () => {
await editor.page.getByTestId('variables-add-variable').click()
await editor.page.getByTestId(variablesAddTestId('STRING')).click()
- await expect(
- editor.page.getByTestId('variable-row').filter({ hasText: 'New text' })
- ).toHaveCount(1)
+ await expect(editor.page.getByTestId('variable-row').filter({ hasText: 'New text' })).toHaveCount(
+ 1
+ )
await editor.page.getByTestId('variables-add-variable').click()
await editor.page.getByTestId(variablesAddTestId('BOOLEAN')).click()
@@ -91,10 +90,7 @@ test('color swatch opens color picker', async () => {
await editor.page.getByTestId('variables-section-open').click()
await expect(editor.page.getByTestId('variables-dialog')).toBeVisible({ timeout: 3000 })
- const swatch = editor.page
- .getByTestId('variable-row')
- .first()
- .getByTestId('color-picker-swatch')
+ const swatch = editor.page.getByTestId('variable-row').first().getByTestId('color-picker-swatch')
await expect(swatch).toBeVisible({ timeout: 3000 })
await swatch.click()
await expect(editor.page.getByTestId('color-picker-popover')).toBeVisible({ timeout: 5000 })
diff --git a/tests/engine/app/shell/menu/schema.test.ts b/tests/engine/app/shell/menu/schema.test.ts
index bcb9f612c..88832cc19 100644
--- a/tests/engine/app/shell/menu/schema.test.ts
+++ b/tests/engine/app/shell/menu/schema.test.ts
@@ -16,7 +16,9 @@ function actionItems(entries: readonly AppMenuEntry[]): AppMenuEntry[] {
describe('APP_MENU_SCHEMA', () => {
test('does not duplicate shortcuts for command-backed entries', () => {
const duplicated = APP_MENU_SCHEMA.flatMap((group) =>
- actionItems(group.items).filter((entry) => !('type' in entry) && entry.command && entry.shortcut)
+ actionItems(group.items).filter(
+ (entry) => !('type' in entry) && entry.command && entry.shortcut
+ )
)
expect(duplicated).toEqual([])
diff --git a/tests/engine/clipboard/figma/html.test.ts b/tests/engine/clipboard/figma/html.test.ts
index 44231392c..f8625026d 100644
--- a/tests/engine/clipboard/figma/html.test.ts
+++ b/tests/engine/clipboard/figma/html.test.ts
@@ -10,7 +10,9 @@ import {
import { expectDefined } from '#tests/helpers/assert'
-function expectFigmaEditableTextDefaults(textNode: NonNullable<Awaited<ReturnType<typeof parseFigmaClipboard>>>['nodes'][number]) {
+function expectFigmaEditableTextDefaults(
+ textNode: NonNullable<Awaited<ReturnType<typeof parseFigmaClipboard>>>['nodes'][number]
+) {
expect(textNode.textUserLayoutVersion).toBe(5)
expect(textNode.textExplicitLayoutVersion).toBe(1)
expect(textNode.textBidiVersion).toBe(1)
@@ -73,7 +75,9 @@ describe('buildFigmaClipboardHTML', () => {
expectFigmaEditableTextDefaults(textNode)
expect(textNode.derivedTextData?.glyphs).toBeDefined()
expect(textNode.derivedTextData?.baselines?.length).toBeGreaterThan(0)
- expect(textNode.derivedTextData?.logicalIndexToCharacterOffsetMap?.length).toBe(text.text.length + 1)
+ expect(textNode.derivedTextData?.logicalIndexToCharacterOffsetMap?.length).toBe(
+ text.text.length + 1
+ )
expect(textNode.derivedTextData?.derivedLines).toEqual([{ directionality: 'LTR' }])
})
diff --git a/tests/engine/clipboard/openpencil/images.test.ts b/tests/engine/clipboard/openpencil/images.test.ts
index 26ccaf0a4..099254ec7 100644
--- a/tests/engine/clipboard/openpencil/images.test.ts
+++ b/tests/engine/clipboard/openpencil/images.test.ts
@@ -1,11 +1,15 @@
import { describe, expect, test } from 'bun:test'
-import { buildOpenPencilClipboardHTML, FigmaAPI, parseOpenPencilClipboard, SceneGraph } from '@open-pencil/core'
+import {
+ buildOpenPencilClipboardHTML,
+ FigmaAPI,
+ parseOpenPencilClipboard,
+ SceneGraph
+} from '@open-pencil/core'
+import type { SceneNode } from '@open-pencil/core'
import { expectDefined } from '#tests/helpers/assert'
-import type { SceneNode } from '@open-pencil/core'
-
describe('clipboard roundtrip with images', () => {
function graphWithImageNode(): {
graph: SceneGraph
@@ -159,4 +163,3 @@ describe('clipboard roundtrip with images', () => {
expect(clipboard.images.get(hash)).toEqual(bytes)
})
})
-
diff --git a/tests/engine/editor/selection/hit-test.test.ts b/tests/engine/editor/selection/hit-test.test.ts
index aa2461c41..2e5b50d19 100644
--- a/tests/engine/editor/selection/hit-test.test.ts
+++ b/tests/engine/editor/selection/hit-test.test.ts
@@ -21,7 +21,10 @@ describe('editor scoped hit testing', () => {
})
editor.state.enteredContainerId = frame.id
- editor.setCanvasKit({} as Parameters<typeof editor.setCanvasKit>[0], {} as Parameters<typeof editor.setCanvasKit>[1])
+ editor.setCanvasKit(
+ {} as Parameters<typeof editor.setCanvasKit>[0],
+ {} as Parameters<typeof editor.setCanvasKit>[1]
+ )
expect(editor.hitTestAtPoint(130, 130)?.id).toBe(child.id)
})
diff --git a/tests/engine/editor/structure/boolean.test.ts b/tests/engine/editor/structure/boolean.test.ts
index 77f6f50e0..0d460e6ad 100644
--- a/tests/engine/editor/structure/boolean.test.ts
+++ b/tests/engine/editor/structure/boolean.test.ts
@@ -7,8 +7,18 @@ describe('booleanOperationSelected', () => {
test('wraps selected nodes in a boolean operation container', () => {
const editor = createEditor()
const pageId = editor.state.currentPageId
- const first = editor.graph.createNode('RECTANGLE', pageId, { x: 10, y: 20, width: 30, height: 40 })
- const second = editor.graph.createNode('ELLIPSE', pageId, { x: 80, y: 90, width: 20, height: 10 })
+ const first = editor.graph.createNode('RECTANGLE', pageId, {
+ x: 10,
+ y: 20,
+ width: 30,
+ height: 40
+ })
+ const second = editor.graph.createNode('ELLIPSE', pageId, {
+ x: 80,
+ y: 90,
+ width: 20,
+ height: 10
+ })
editor.select([first.id, second.id])
editor.booleanOperationSelected('UNION')
@@ -26,7 +36,10 @@ describe('booleanOperationSelected', () => {
test('does not wrap unsupported text nodes', () => {
const editor = createEditor()
const pageId = editor.state.currentPageId
- const first = editor.graph.createNode('TEXT', pageId, { text: 'Nope', fontFamily: 'Definitely Missing Font' })
+ const first = editor.graph.createNode('TEXT', pageId, {
+ text: 'Nope',
+ fontFamily: 'Definitely Missing Font'
+ })
const second = editor.graph.createNode('RECTANGLE', pageId)
editor.select([first.id, second.id])
@@ -57,7 +70,16 @@ describe('booleanOperationSelected', () => {
const editor = createEditor()
const pageId = editor.state.currentPageId
const first = editor.graph.createNode('RECTANGLE', pageId, {
- fills: [{ type: 'IMAGE', imageHash: 'image', imageScaleMode: 'FILL', color: TRANSPARENT, opacity: 1, visible: true }]
+ fills: [
+ {
+ type: 'IMAGE',
+ imageHash: 'image',
+ imageScaleMode: 'FILL',
+ color: TRANSPARENT,
+ opacity: 1,
+ visible: true
+ }
+ ]
})
const second = editor.graph.createNode('RECTANGLE', pageId)
@@ -82,7 +104,12 @@ describe('booleanOperationSelected', () => {
expect(editor.graph.getNode(pageId)?.childIds).toEqual([before.id, booleanId, after.id])
editor.undo.undo()
- expect(editor.graph.getNode(pageId)?.childIds).toEqual([before.id, first.id, second.id, after.id])
+ expect(editor.graph.getNode(pageId)?.childIds).toEqual([
+ before.id,
+ first.id,
+ second.id,
+ after.id
+ ])
expect(editor.state.selectedIds).toEqual(new Set([first.id, second.id]))
editor.undo.redo()
diff --git a/tests/engine/editor/structure/frame-selection.test.ts b/tests/engine/editor/structure/frame-selection.test.ts
index e681be7cd..fac6b1c5c 100644
--- a/tests/engine/editor/structure/frame-selection.test.ts
+++ b/tests/engine/editor/structure/frame-selection.test.ts
@@ -45,8 +45,18 @@ describe('frameSelection', () => {
test('undo and redo restore frame selection state', () => {
const editor = createEditor()
const pageId = editor.state.currentPageId
- const first = editor.graph.createNode('RECTANGLE', pageId, { x: 20, y: 30, width: 40, height: 50 })
- const second = editor.graph.createNode('ELLIPSE', pageId, { x: 100, y: 120, width: 30, height: 20 })
+ const first = editor.graph.createNode('RECTANGLE', pageId, {
+ x: 20,
+ y: 30,
+ width: 40,
+ height: 50
+ })
+ const second = editor.graph.createNode('ELLIPSE', pageId, {
+ x: 100,
+ y: 120,
+ width: 30,
+ height: 20
+ })
editor.select([first.id, second.id])
editor.frameSelection()
diff --git a/tests/engine/figma/api/images.test.ts b/tests/engine/figma/api/images.test.ts
index 8fa84f74b..595589e16 100644
--- a/tests/engine/figma/api/images.test.ts
+++ b/tests/engine/figma/api/images.test.ts
@@ -46,4 +46,3 @@ describe('FigmaAPI.createImage', () => {
expect(hash).toMatch(/^[0-9a-f]{40}$/)
})
})
-
diff --git a/tests/engine/geometry/angles.test.ts b/tests/engine/geometry/angles.test.ts
index 519028563..250a8b7b2 100644
--- a/tests/engine/geometry/angles.test.ts
+++ b/tests/engine/geometry/angles.test.ts
@@ -21,4 +21,3 @@ describe('degToRad / radToDeg', () => {
expect(radToDeg(degToRad(-90))).toBeCloseTo(-90, 10)
})
})
-
diff --git a/tests/engine/geometry/bounds.test.ts b/tests/engine/geometry/bounds.test.ts
index 6c77857b4..200a1f2a3 100644
--- a/tests/engine/geometry/bounds.test.ts
+++ b/tests/engine/geometry/bounds.test.ts
@@ -59,4 +59,3 @@ describe('computeAbsoluteBounds', () => {
expect(result).toEqual({ x: 10, y: 20, width: 60, height: 60 })
})
})
-
diff --git a/tests/engine/geometry/rotation.test.ts b/tests/engine/geometry/rotation.test.ts
index ef400f61f..8899275b9 100644
--- a/tests/engine/geometry/rotation.test.ts
+++ b/tests/engine/geometry/rotation.test.ts
@@ -92,4 +92,3 @@ describe('rotatedBBox', () => {
expect(pos.bottom - pos.top).toBeCloseTo(neg.bottom - neg.top, 5)
})
})
-
diff --git a/tests/engine/io/fig/export/text.test.ts b/tests/engine/io/fig/export/text.test.ts
index 808713888..b7f2ad519 100644
--- a/tests/engine/io/fig/export/text.test.ts
+++ b/tests/engine/io/fig/export/text.test.ts
@@ -62,7 +62,8 @@ describe('text node export', () => {
await initCodec()
const { unzipSync, inflateSync } = await import('fflate')
- const { decodeBinarySchema, compileSchema, ByteBuffer } = await import('#core/kiwi/schema-runtime')
+ const { decodeBinarySchema, compileSchema, ByteBuffer } =
+ await import('#core/kiwi/schema-runtime')
const { parseFigKiwiChunks } = await import('@open-pencil/core')
const graph = new SceneGraph()
@@ -123,7 +124,8 @@ describe('text node export', () => {
await initCodec()
const { unzipSync, inflateSync } = await import('fflate')
- const { decodeBinarySchema, compileSchema, ByteBuffer } = await import('#core/kiwi/schema-runtime')
+ const { decodeBinarySchema, compileSchema, ByteBuffer } =
+ await import('#core/kiwi/schema-runtime')
const { parseFigKiwiChunks } = await import('@open-pencil/core')
const graph = new SceneGraph()
@@ -148,7 +150,10 @@ describe('text node export', () => {
}
const message = compiled.decodeMessage(inflateSync(chunks?.[1] ?? new Uint8Array()))
const nodeChanges = message.nodeChanges as Array<Record<string, unknown>>
- const textNc = expectDefined(nodeChanges.find((nc) => nc.type === 'TEXT'), 'text node change')
+ const textNc = expectDefined(
+ nodeChanges.find((nc) => nc.type === 'TEXT'),
+ 'text node change'
+ )
const derivedTextData = textNc.derivedTextData as Record<string, unknown>
const fontMetaData = expectDefined(
derivedTextData.fontMetaData as Array<Record<string, unknown>> | undefined,
@@ -163,7 +168,8 @@ describe('text node export', () => {
await initCodec()
const { unzipSync, inflateSync } = await import('fflate')
- const { decodeBinarySchema, compileSchema, ByteBuffer } = await import('#core/kiwi/schema-runtime')
+ const { decodeBinarySchema, compileSchema, ByteBuffer } =
+ await import('#core/kiwi/schema-runtime')
const { parseFigKiwiChunks } = await import('@open-pencil/core')
const graph = new SceneGraph()
@@ -195,7 +201,10 @@ describe('text node export', () => {
}
const message = compiled.decodeMessage(inflateSync(chunks?.[1] ?? new Uint8Array()))
const nodeChanges = message.nodeChanges as Array<Record<string, unknown>>
- const textNc = expectDefined(nodeChanges.find((nc) => nc.type === 'TEXT'), 'text node change')
+ const textNc = expectDefined(
+ nodeChanges.find((nc) => nc.type === 'TEXT'),
+ 'text node change'
+ )
expect(textNc.textAutoResize).toBe('HEIGHT')
expect(textNc.lineHeight).toBeUndefined()
@@ -206,7 +215,8 @@ describe('text node export', () => {
await initCodec()
const { unzipSync, inflateSync } = await import('fflate')
- const { decodeBinarySchema, compileSchema, ByteBuffer } = await import('#core/kiwi/schema-runtime')
+ const { decodeBinarySchema, compileSchema, ByteBuffer } =
+ await import('#core/kiwi/schema-runtime')
const { parseFigKiwiChunks } = await import('@open-pencil/core')
const graph = new SceneGraph()
@@ -253,20 +263,23 @@ describe('text node export', () => {
expect(families).toContain('Regular')
})
- test.if(runsHeavyTests)('material3.fig text nodes have derivedTextData after round-trip', async () => {
- const original = await parseFixture('material3.fig')
+ test.if(runsHeavyTests)(
+ 'material3.fig text nodes have derivedTextData after round-trip',
+ async () => {
+ const original = await parseFixture('material3.fig')
- const textNodes = [...original.getAllNodes()].filter((n) => n.type === 'TEXT')
- expect(textNodes.length).toBeGreaterThan(0)
+ const textNodes = [...original.getAllNodes()].filter((n) => n.type === 'TEXT')
+ expect(textNodes.length).toBeGreaterThan(0)
- const exported = await exportFigFile(original)
- const reimported = await parseFigFile(exported.buffer as ArrayBuffer)
+ const exported = await exportFigFile(original)
+ const reimported = await parseFigFile(exported.buffer as ArrayBuffer)
- const reimportedText = [...reimported.getAllNodes()].filter((n) => n.type === 'TEXT')
- expect(reimportedText.length).toBe(textNodes.length)
+ const reimportedText = [...reimported.getAllNodes()].filter((n) => n.type === 'TEXT')
+ expect(reimportedText.length).toBe(textNodes.length)
- for (const node of reimportedText.slice(0, 10)) {
- expect(node.text.length).toBeGreaterThan(0)
+ for (const node of reimportedText.slice(0, 10)) {
+ expect(node.text.length).toBeGreaterThan(0)
+ }
}
- })
+ )
})
diff --git a/tests/engine/io/fig/import/component-props.test.ts b/tests/engine/io/fig/import/component-props.test.ts
index 02050bcfc..575669bd0 100644
--- a/tests/engine/io/fig/import/component-props.test.ts
+++ b/tests/engine/io/fig/import/component-props.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, test } from 'bun:test'
-import { importNodeChanges } from '#core/kiwi/fig/import'
import type { NodeChange } from '#core/kiwi/fig/codec'
+import { importNodeChanges } from '#core/kiwi/fig/import'
const documentGuid = { sessionID: 0, localID: 0 }
const pageGuid = { sessionID: 0, localID: 1 }
@@ -39,7 +39,13 @@ describe('Figma component property import', () => {
test('applies text data component prop assignments', () => {
const nodeChanges: NodeChange[] = [
{ guid: documentGuid, phase: 'CREATED', type: 'DOCUMENT', name: 'Document' },
- { guid: pageGuid, phase: 'CREATED', parentIndex: { guid: documentGuid, position: '!' }, type: 'CANVAS', name: 'Page' },
+ {
+ guid: pageGuid,
+ phase: 'CREATED',
+ parentIndex: { guid: documentGuid, position: '!' },
+ type: 'CANVAS',
+ name: 'Page'
+ },
{
guid: componentGuid,
phase: 'CREATED',
@@ -80,7 +86,13 @@ describe('Figma component property import', () => {
test('propagates nested instance swaps through clone chains', () => {
const nodeChanges: NodeChange[] = [
{ guid: documentGuid, phase: 'CREATED', type: 'DOCUMENT', name: 'Document' },
- { guid: pageGuid, phase: 'CREATED', parentIndex: { guid: documentGuid, position: '!' }, type: 'CANVAS', name: 'Page' },
+ {
+ guid: pageGuid,
+ phase: 'CREATED',
+ parentIndex: { guid: documentGuid, position: '!' },
+ type: 'CANVAS',
+ name: 'Page'
+ },
{
guid: strokeStyleGuid,
phase: 'CREATED',
@@ -177,9 +189,7 @@ describe('Figma component property import', () => {
symbolData: { symbolID: mailIconGuid },
size: { x: 16, y: 16 },
transform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 },
- componentPropRefs: [
- { defID: iconPropGuid, componentPropNodeField: 'OVERRIDDEN_SYMBOL_ID' }
- ]
+ componentPropRefs: [{ defID: iconPropGuid, componentPropNodeField: 'OVERRIDDEN_SYMBOL_ID' }]
},
{
guid: sourceInstanceGuid,
@@ -220,7 +230,9 @@ describe('Figma component property import', () => {
const graph = importNodeChanges(nodeChanges, [], undefined, { populate: 'all' })
const clone = Array.from(graph.getAllNodes()).find((node) => node.name === 'Menu item clone')
- const icon = clone?.childIds.map((id) => graph.getNode(id)).find((node) => node?.type === 'INSTANCE')
+ const icon = clone?.childIds
+ .map((id) => graph.getNode(id))
+ .find((node) => node?.type === 'INSTANCE')
const iconChild = icon?.childIds.map((id) => graph.getNode(id)).find(Boolean)
expect(icon?.name).toBe('icon/user')
expect(iconChild?.name).toBe('user-path')
diff --git a/tests/engine/io/fig/import/derived-symbol-data.test.ts b/tests/engine/io/fig/import/derived-symbol-data.test.ts
index a7f9e4929..41ec28726 100644
--- a/tests/engine/io/fig/import/derived-symbol-data.test.ts
+++ b/tests/engine/io/fig/import/derived-symbol-data.test.ts
@@ -1,8 +1,8 @@
import { describe, expect, test } from 'bun:test'
+import type { OverrideContext } from '#core/kiwi/fig/instance-overrides'
import { buildDsdLayoutUpdates } from '#core/kiwi/fig/instance-overrides/derived-symbol-data/layout'
import { propagateDsdChanges } from '#core/kiwi/fig/instance-overrides/derived-symbol-data/propagate'
-import type { OverrideContext } from '#core/kiwi/fig/instance-overrides'
import { SceneGraph } from '#core/scene-graph'
function pageId(graph: SceneGraph): string {
@@ -17,7 +17,10 @@ describe('fig import derived symbol data', () => {
figmaDerivedTextGlyphs: [{ commandsBlob: new Uint8Array([0]), x: 0, y: 10, fontSize: 14 }],
figmaDerivedLayout: { width: 56, height: 20 }
})
- const clone = graph.createNode('TEXT', pageId(graph), { text: 'Account', componentId: source.id })
+ const clone = graph.createNode('TEXT', pageId(graph), {
+ text: 'Account',
+ componentId: source.id
+ })
const ctx = {
graph,
activeNodeIds: new Set([source.id, clone.id]),
diff --git a/tests/engine/io/fig/import/legacy/text.test.ts b/tests/engine/io/fig/import/legacy/text.test.ts
index 410236bf7..e0b8e66ce 100644
--- a/tests/engine/io/fig/import/legacy/text.test.ts
+++ b/tests/engine/io/fig/import/legacy/text.test.ts
@@ -111,7 +111,9 @@ describe('fig-import: text properties', () => {
styleIdForText: { guid: { sessionID: 1, localID: 20 } }
} as Partial<NodeChange>)
])
- const styled = graph.getChildren(graph.getPages()[0].id).find((node) => node.text === 'Styled text')
+ const styled = graph
+ .getChildren(graph.getPages()[0].id)
+ .find((node) => node.text === 'Styled text')
expect(styled?.fontSize).toBe(16)
expect(styled?.fontWeight).toBe(400)
expect(styled?.lineHeight).toBe(24)
@@ -148,7 +150,9 @@ describe('fig-import: text properties', () => {
styleIdForFill: { guid: { sessionID: 1, localID: 30 } }
} as Partial<NodeChange>)
])
- const styled = graph.getChildren(graph.getPages()[0].id).find((node) => node.name === 'ROUNDED_RECTANGLE_10')
+ const styled = graph
+ .getChildren(graph.getPages()[0].id)
+ .find((node) => node.name === 'ROUNDED_RECTANGLE_10')
expect(styled?.fills[0]?.color).toEqual({
r: 0.05882352963089943,
g: 0.09019608050584793,
diff --git a/tests/engine/io/fig/import/scaled-instance-strokes.test.ts b/tests/engine/io/fig/import/scaled-instance-strokes.test.ts
index b065f660a..a9cccc2ff 100644
--- a/tests/engine/io/fig/import/scaled-instance-strokes.test.ts
+++ b/tests/engine/io/fig/import/scaled-instance-strokes.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, test } from 'bun:test'
import { importNodeChanges } from '@open-pencil/core'
+
import type { NodeChange } from '#core/kiwi/fig/codec'
import { canvas, doc, node } from './legacy/helpers'
@@ -47,7 +48,9 @@ describe('fig import scaled instance strokes', () => {
{ populate: 'all' }
)
- const instance = Array.from(graph.getAllNodes()).find((sceneNode) => sceneNode.name === 'INSTANCE_20')
+ const instance = Array.from(graph.getAllNodes()).find(
+ (sceneNode) => sceneNode.name === 'INSTANCE_20'
+ )
const vector = instance?.childIds.map((id) => graph.getNode(id)).find(Boolean)
expect(vector?.strokes[0]?.weight).toBe(2)
@@ -94,7 +97,9 @@ describe('fig import scaled instance strokes', () => {
{ populate: 'all' }
)
- const instance = Array.from(graph.getAllNodes()).find((sceneNode) => sceneNode.name === 'INSTANCE_40')
+ const instance = Array.from(graph.getAllNodes()).find(
+ (sceneNode) => sceneNode.name === 'INSTANCE_40'
+ )
const vector = instance?.childIds.map((id) => graph.getNode(id)).find(Boolean)
expect(vector?.strokes[0]?.weight).toBeCloseTo(4 / 3, 6)
diff --git a/tests/engine/io/fig/import/style-refs.test.ts b/tests/engine/io/fig/import/style-refs.test.ts
index 61b9cf632..83cab6e3e 100644
--- a/tests/engine/io/fig/import/style-refs.test.ts
+++ b/tests/engine/io/fig/import/style-refs.test.ts
@@ -13,7 +13,8 @@ describe('fig import style refs', () => {
visible: true,
blendMode: 'NORMAL' as const
}
- const fields: Record<string, unknown> & Pick<NodeChange, 'styleIdForStrokeFill' | 'strokePaints'> = {
+ const fields: Record<string, unknown> &
+ Pick<NodeChange, 'styleIdForStrokeFill' | 'strokePaints'> = {
styleIdForStrokeFill: { guid: styleGuid },
strokePaints: [
{
diff --git a/tests/engine/io/fig/roundtrip/glyph-blob.test.ts b/tests/engine/io/fig/roundtrip/glyph-blob.test.ts
index 6900976d5..a26cffac1 100644
--- a/tests/engine/io/fig/roundtrip/glyph-blob.test.ts
+++ b/tests/engine/io/fig/roundtrip/glyph-blob.test.ts
@@ -3,14 +3,17 @@ import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { exportFigFile, initCodec, parseFigFile, SceneGraph } from '@open-pencil/core'
-import { parseFigBuffer } from '#core/kiwi/fig/parse/core'
import { fontManager } from '@open-pencil/core/text'
+import { parseFigBuffer } from '#core/kiwi/fig/parse/core'
+
const FIXTURES = resolve(import.meta.dir, '../../../../fixtures')
const INTER_ASSETS = resolve(import.meta.dir, '../../../../../packages/core/assets')
function countGlyphBlobs(bytes: Uint8Array) {
- const parsed = parseFigBuffer(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength))
+ const parsed = parseFigBuffer(
+ bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength)
+ )
let glyphs = 0
let glyphsWithBlob = 0
const uniqueGlyphBlobs = new Set<number>()
@@ -50,7 +53,10 @@ describe('roundtrip: text glyph blobs', () => {
const input = countGlyphBlobs(fixtureBytes)
const graph = await parseFigFile(
- fixtureBytes.buffer.slice(fixtureBytes.byteOffset, fixtureBytes.byteOffset + fixtureBytes.byteLength)
+ fixtureBytes.buffer.slice(
+ fixtureBytes.byteOffset,
+ fixtureBytes.byteOffset + fixtureBytes.byteLength
+ )
)
const exported = await exportFigFile(graph)
const output = countGlyphBlobs(exported)
diff --git a/tests/engine/io/fig/roundtrip/source-metadata.test.ts b/tests/engine/io/fig/roundtrip/source-metadata.test.ts
index d0a1400cc..815bad1d0 100644
--- a/tests/engine/io/fig/roundtrip/source-metadata.test.ts
+++ b/tests/engine/io/fig/roundtrip/source-metadata.test.ts
@@ -1,9 +1,8 @@
import { beforeAll, describe, expect, test } from 'bun:test'
import { exportFigFile, initCodec, parseFigFile, SceneGraph } from '@open-pencil/core'
-
-import { parseFigBuffer } from '@open-pencil/core/kiwi/fig/parse/core'
import { guidToString } from '@open-pencil/core/kiwi/fig/node-change/convert'
+import { parseFigBuffer } from '@open-pencil/core/kiwi/fig/parse/core'
function decodeExport(bytes: Uint8Array) {
return parseFigBuffer(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength))
diff --git a/tests/engine/io/fig/roundtrip/variables.test.ts b/tests/engine/io/fig/roundtrip/variables.test.ts
index 3fcead3ee..33fcd9c79 100644
--- a/tests/engine/io/fig/roundtrip/variables.test.ts
+++ b/tests/engine/io/fig/roundtrip/variables.test.ts
@@ -117,17 +117,21 @@ describe('variable roundtrip', () => {
expect(Object.keys(reimportedRect.boundVariables)).toContain('strokes/0/color')
})
- test.if(runsHeavyTests)('material3.fig variables survive round-trip', async () => {
- const original = await parseFixture('material3.fig')
-
- const exported = await exportFigFile(original)
- const reimported = await parseFigFile(exported.buffer as ArrayBuffer)
-
- expect(reimported.variables.size).toBe(original.variables.size)
- expect(reimported.variableCollections.size).toBeGreaterThanOrEqual(
- [...original.variableCollections.values()].filter((c) => c.variableIds.length > 0).length
- )
- }, 120_000)
+ test.if(runsHeavyTests)(
+ 'material3.fig variables survive round-trip',
+ async () => {
+ const original = await parseFixture('material3.fig')
+
+ const exported = await exportFigFile(original)
+ const reimported = await parseFigFile(exported.buffer as ArrayBuffer)
+
+ expect(reimported.variables.size).toBe(original.variables.size)
+ expect(reimported.variableCollections.size).toBeGreaterThanOrEqual(
+ [...original.variableCollections.values()].filter((c) => c.variableIds.length > 0).length
+ )
+ },
+ 120_000
+ )
test('pluginID casing is consistent across full codec pipeline', async () => {
await initCodec()
diff --git a/tests/engine/io/subgraph.test.ts b/tests/engine/io/subgraph.test.ts
index 6f3272bdc..7bbfe3f86 100644
--- a/tests/engine/io/subgraph.test.ts
+++ b/tests/engine/io/subgraph.test.ts
@@ -1,11 +1,10 @@
-import { readFileSync } from 'node:fs'
-
import { describe, expect, test } from 'bun:test'
+import { readFileSync } from 'node:fs'
import { exportFigFile, extractExportGraph, parseFigFile } from '@open-pencil/core/io'
import { initCodec } from '@open-pencil/core/kiwi'
-import { parseFigBuffer } from '@open-pencil/core/kiwi/fig/parse/core'
import { guidToString } from '@open-pencil/core/kiwi/fig/node-change/guid'
+import { parseFigBuffer } from '@open-pencil/core/kiwi/fig/parse/core'
import { SceneGraph } from '@open-pencil/core/scene-graph'
describe('export subgraph extraction', () => {
@@ -96,7 +95,10 @@ describe('export subgraph extraction', () => {
await initCodec()
const fixture = new Uint8Array(readFileSync('tests/fixtures/gold-preview.fig'))
const graph = await parseFigFile(
- fixture.buffer.slice(fixture.byteOffset, fixture.byteOffset + fixture.byteLength) as ArrayBuffer
+ fixture.buffer.slice(
+ fixture.byteOffset,
+ fixture.byteOffset + fixture.byteLength
+ ) as ArrayBuffer
)
const exported = await exportFigFile(graph)
const parsed = parseFigBuffer(exported.buffer as ArrayBuffer)
diff --git a/tests/engine/profiler/capture-stack.test.ts b/tests/engine/profiler/capture-stack.test.ts
index 5cf4f7eee..36091cbe6 100644
--- a/tests/engine/profiler/capture-stack.test.ts
+++ b/tests/engine/profiler/capture-stack.test.ts
@@ -20,4 +20,3 @@ describe('CaptureStack', () => {
expect(roots[0].children[0].drawCalls).toBe(2)
})
})
-
diff --git a/tests/engine/profiler/draw-call-counter.test.ts b/tests/engine/profiler/draw-call-counter.test.ts
index f32e635cd..152dd685b 100644
--- a/tests/engine/profiler/draw-call-counter.test.ts
+++ b/tests/engine/profiler/draw-call-counter.test.ts
@@ -38,4 +38,3 @@ describe('DrawCallCounter', () => {
expect(rawDrawCalls).toBe(3)
})
})
-
diff --git a/tests/engine/profiler/frame-stats.test.ts b/tests/engine/profiler/frame-stats.test.ts
index 7882682e4..c62b7b52e 100644
--- a/tests/engine/profiler/frame-stats.test.ts
+++ b/tests/engine/profiler/frame-stats.test.ts
@@ -35,4 +35,3 @@ describe('FrameStats', () => {
expect(stats.gpuTime).toBe(0)
})
})
-
diff --git a/tests/engine/profiler/gpu-timer.test.ts b/tests/engine/profiler/gpu-timer.test.ts
index 3b0351e68..d67eadbbe 100644
--- a/tests/engine/profiler/gpu-timer.test.ts
+++ b/tests/engine/profiler/gpu-timer.test.ts
@@ -13,4 +13,3 @@ describe('GPUTimer', () => {
timer.destroy()
})
})
-
diff --git a/tests/engine/profiler/phase-timer.test.ts b/tests/engine/profiler/phase-timer.test.ts
index 3bfaeaa66..876b2869e 100644
--- a/tests/engine/profiler/phase-timer.test.ts
+++ b/tests/engine/profiler/phase-timer.test.ts
@@ -22,4 +22,3 @@ describe('PhaseTimer', () => {
timer.endPhase('test')
})
})
-
diff --git a/tests/engine/render/canvas/boolean-visual.test.ts b/tests/engine/render/canvas/boolean-visual.test.ts
index edbb057ce..58037c7e7 100644
--- a/tests/engine/render/canvas/boolean-visual.test.ts
+++ b/tests/engine/render/canvas/boolean-visual.test.ts
@@ -1,6 +1,5 @@
-import { existsSync } from 'node:fs'
-
import { describe, expect, test } from 'bun:test'
+import { existsSync } from 'node:fs'
import { initCanvasKit } from '#cli/headless'
diff --git a/tests/engine/render/canvas/boolean.test.ts b/tests/engine/render/canvas/boolean.test.ts
index e19a76ee1..62f1b02cf 100644
--- a/tests/engine/render/canvas/boolean.test.ts
+++ b/tests/engine/render/canvas/boolean.test.ts
@@ -1,10 +1,10 @@
import { describe, expect, test } from 'bun:test'
import { initCanvasKit } from '#cli/headless'
-import { BLACK } from '#core/constants'
import { makeBooleanOperationPath } from '#core/canvas/boolean'
-import { makeNodeShapePath, makePolygonPath, makeRRect } from '#core/canvas/shapes'
import type { SkiaRenderer } from '#core/canvas/renderer'
+import { makeNodeShapePath, makePolygonPath, makeRRect } from '#core/canvas/shapes'
+import { BLACK } from '#core/constants'
import { createAPI } from '#tests/engine/figma/api/helpers'
@@ -145,8 +145,12 @@ describe('boolean operation paths', () => {
expect(firstNode).toBeDefined()
expect(secondNode).toBeDefined()
if (!firstNode || !secondNode) return
- firstNode.strokes = [{ type: 'SOLID', color: BLACK, opacity: 1, visible: true, weight: 12, align: 'CENTER' }]
- secondNode.strokes = [{ type: 'SOLID', color: BLACK, opacity: 1, visible: true, weight: 12, align: 'CENTER' }]
+ firstNode.strokes = [
+ { type: 'SOLID', color: BLACK, opacity: 1, visible: true, weight: 12, align: 'CENTER' }
+ ]
+ secondNode.strokes = [
+ { type: 'SOLID', color: BLACK, opacity: 1, visible: true, weight: 12, align: 'CENTER' }
+ ]
const booleanNode = api.union([first, second], api.currentPage)
const node = api.graph.getNode(booleanNode.id)
diff --git a/tests/engine/render/canvas/culling.test.ts b/tests/engine/render/canvas/culling.test.ts
index d8bf0f29c..c0c58c63f 100644
--- a/tests/engine/render/canvas/culling.test.ts
+++ b/tests/engine/render/canvas/culling.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, mock, test } from 'bun:test'
-import { renderNode } from '#core/canvas/scene'
import type { SkiaRenderer } from '#core/canvas/renderer'
+import { renderNode } from '#core/canvas/scene'
import { SceneGraph } from '#core/scene-graph'
function pageId(graph: SceneGraph) {
diff --git a/tests/engine/render/canvas/effects/ordering.test.ts b/tests/engine/render/canvas/effects/ordering.test.ts
index f9b72be10..6c44d76df 100644
--- a/tests/engine/render/canvas/effects/ordering.test.ts
+++ b/tests/engine/render/canvas/effects/ordering.test.ts
@@ -3,8 +3,8 @@ import { describe, expect, mock, test } from 'bun:test'
import type { Canvas } from 'canvaskit-wasm'
import { renderShapeUncached } from '#core/canvas/scene'
-import { createDefaultNode } from '#core/scene-graph/node-defaults'
import type { SceneGraph } from '#core/scene-graph'
+import { createDefaultNode } from '#core/scene-graph/node-defaults'
import { createMockCanvas, createMockRenderer } from './helpers'
diff --git a/tests/engine/render/canvas/font-readiness.test.ts b/tests/engine/render/canvas/font-readiness.test.ts
index 93fef7aa5..792d32cf1 100644
--- a/tests/engine/render/canvas/font-readiness.test.ts
+++ b/tests/engine/render/canvas/font-readiness.test.ts
@@ -1,8 +1,8 @@
import { describe, expect, test } from 'bun:test'
import { isNodeFontLoaded } from '#core/canvas/text'
-import { fontManager } from '#core/text/fonts'
import type { SceneNode } from '#core/scene-graph'
+import { fontManager } from '#core/text/fonts'
describe('canvas text font readiness', () => {
test('requires the exact requested font weight before rendering text', () => {
diff --git a/tests/engine/render/canvas/renderer-lifecycle.test.ts b/tests/engine/render/canvas/renderer-lifecycle.test.ts
index ca5d87090..e7dbc92a5 100644
--- a/tests/engine/render/canvas/renderer-lifecycle.test.ts
+++ b/tests/engine/render/canvas/renderer-lifecycle.test.ts
@@ -1,4 +1,5 @@
import { expect, mock, test } from 'bun:test'
+
import type { Font, Paint, Surface } from 'canvaskit-wasm'
import type { SkiaRenderer } from '#core/canvas/renderer'
diff --git a/tests/engine/render/canvas/retained-backing.test.ts b/tests/engine/render/canvas/retained-backing.test.ts
index 7a6a44606..9fe0e5fec 100644
--- a/tests/engine/render/canvas/retained-backing.test.ts
+++ b/tests/engine/render/canvas/retained-backing.test.ts
@@ -1,4 +1,5 @@
import { expect, mock, test } from 'bun:test'
+
import type { Canvas, Image as CKImage, Surface } from 'canvaskit-wasm'
import type { SkiaRenderer } from '#core/canvas/renderer'
diff --git a/tests/engine/render/canvas/text.test.ts b/tests/engine/render/canvas/text.test.ts
index 1c432e098..38782cea6 100644
--- a/tests/engine/render/canvas/text.test.ts
+++ b/tests/engine/render/canvas/text.test.ts
@@ -10,8 +10,8 @@ import {
import { initCanvasKit } from '#cli/headless'
import type { SkiaRenderer } from '#core/canvas/renderer'
import { renderText } from '#core/canvas/scene'
-import type { SceneNode } from '#core/scene-graph'
import { buildParagraph } from '#core/canvas/text'
+import type { SceneNode } from '#core/scene-graph'
import { fontManager } from '#core/text/fonts'
import { expectDefined } from '#tests/helpers/assert'
diff --git a/tests/engine/render/canvas/visual/boolean-matrix.ts b/tests/engine/render/canvas/visual/boolean-matrix.ts
index 517aa875e..6c67f1afc 100644
--- a/tests/engine/render/canvas/visual/boolean-matrix.ts
+++ b/tests/engine/render/canvas/visual/boolean-matrix.ts
@@ -56,15 +56,23 @@ function makePair(name: CaseName, x: number, y: number) {
secondNode.type = 'ELLIPSE'
if (name === 'arc') {
firstNode.arcData = { startingAngle: 0, endingAngle: Math.PI * 1.5, innerRadius: 0.35 }
- secondNode.arcData = { startingAngle: Math.PI * 0.25, endingAngle: Math.PI * 1.75, innerRadius: 0.2 }
+ secondNode.arcData = {
+ startingAngle: Math.PI * 0.25,
+ endingAngle: Math.PI * 1.75,
+ innerRadius: 0.2
+ }
}
} else if (name === 'line') {
firstNode.type = 'LINE'
secondNode.type = 'LINE'
firstNode.height = 54
secondNode.height = 54
- firstNode.strokes = [{ type: 'SOLID', color: color(1), opacity: 1, visible: true, weight: 14, align: 'CENTER' }]
- secondNode.strokes = [{ type: 'SOLID', color: color(2), opacity: 1, visible: true, weight: 14, align: 'CENTER' }]
+ firstNode.strokes = [
+ { type: 'SOLID', color: color(1), opacity: 1, visible: true, weight: 14, align: 'CENTER' }
+ ]
+ secondNode.strokes = [
+ { type: 'SOLID', color: color(2), opacity: 1, visible: true, weight: 14, align: 'CENTER' }
+ ]
} else if (name === 'polygon' || name === 'star') {
firstNode.type = name === 'polygon' ? 'POLYGON' : 'STAR'
secondNode.type = name === 'polygon' ? 'POLYGON' : 'STAR'
diff --git a/tests/engine/text/derived-text/clipboard.test.ts b/tests/engine/text/derived-text/clipboard.test.ts
index 6d34c264c..7dd05c950 100644
--- a/tests/engine/text/derived-text/clipboard.test.ts
+++ b/tests/engine/text/derived-text/clipboard.test.ts
@@ -34,20 +34,25 @@ describe('clipboard derived text export', () => {
const fontDigestMap = await buildFontDigestMap(graph)
const blobs: Uint8Array[] = []
- const derived = await buildDerivedTextDataV4(text, fontDigestMap, {
- lineHeight: 20,
- lineAscent: 15,
- lineWidth: 42,
- baseline: 16,
- glyphs: [
- { firstCharacter: 0, x: 0, y: 16, advance: 8 },
- { firstCharacter: 1, x: 8, y: 16, advance: 8 },
- { firstCharacter: 2, x: 16, y: 16, advance: 8 },
- { firstCharacter: 3, x: 24, y: 16, advance: 8 },
- { firstCharacter: 4, x: 32, y: 16, advance: 10 }
- ],
- logicalIndexToCharacterOffsetMap: [0, 8, 16, 24, 32, 42]
- }, blobs)
+ const derived = await buildDerivedTextDataV4(
+ text,
+ fontDigestMap,
+ {
+ lineHeight: 20,
+ lineAscent: 15,
+ lineWidth: 42,
+ baseline: 16,
+ glyphs: [
+ { firstCharacter: 0, x: 0, y: 16, advance: 8 },
+ { firstCharacter: 1, x: 8, y: 16, advance: 8 },
+ { firstCharacter: 2, x: 16, y: 16, advance: 8 },
+ { firstCharacter: 3, x: 24, y: 16, advance: 8 },
+ { firstCharacter: 4, x: 32, y: 16, advance: 10 }
+ ],
+ logicalIndexToCharacterOffsetMap: [0, 8, 16, 24, 32, 42]
+ },
+ blobs
+ )
const derivedTextData = expectDefined(derived, 'derived text data')
const firstGlyph = expectDefined(derivedTextData.glyphs[0], 'first glyph')
@@ -89,37 +94,42 @@ describe('clipboard derived text export', () => {
})
const derived = expectDefined(
- await buildDerivedTextDataV4(text, await buildFontDigestMap(graph), {
- lineHeight: 68,
- lineAscent: 54,
- lineWidth: 272,
- baseline: 54.36,
- baselines: [
- {
- firstCharacter: 0,
- endCharacter: 10,
- position: { x: 0, y: 54.36 },
- width: 271.58,
- lineY: 0,
- lineHeight: 68,
- lineAscent: 54
- },
- {
- firstCharacter: 10,
- endCharacter: 18,
- position: { x: 0, y: 122.36 },
- width: 261.9,
- lineY: 68,
- lineHeight: 68,
- lineAscent: 54
- }
- ],
- glyphs: [
- { firstCharacter: 0, x: 0, y: 54.36, advance: 42 },
- { firstCharacter: 10, x: 0, y: 122.36, advance: 44 }
- ],
- logicalIndexToCharacterOffsetMap: Array.from({ length: 19 }, () => 0)
- }, null),
+ await buildDerivedTextDataV4(
+ text,
+ await buildFontDigestMap(graph),
+ {
+ lineHeight: 68,
+ lineAscent: 54,
+ lineWidth: 272,
+ baseline: 54.36,
+ baselines: [
+ {
+ firstCharacter: 0,
+ endCharacter: 10,
+ position: { x: 0, y: 54.36 },
+ width: 271.58,
+ lineY: 0,
+ lineHeight: 68,
+ lineAscent: 54
+ },
+ {
+ firstCharacter: 10,
+ endCharacter: 18,
+ position: { x: 0, y: 122.36 },
+ width: 261.9,
+ lineY: 68,
+ lineHeight: 68,
+ lineAscent: 54
+ }
+ ],
+ glyphs: [
+ { firstCharacter: 0, x: 0, y: 54.36, advance: 42 },
+ { firstCharacter: 10, x: 0, y: 122.36, advance: 44 }
+ ],
+ logicalIndexToCharacterOffsetMap: Array.from({ length: 19 }, () => 0)
+ },
+ null
+ ),
'derived text'
)
@@ -150,7 +160,10 @@ describe('clipboard derived text export', () => {
const fontDigestMap = await buildFontDigestMap(graph)
const blobs: Uint8Array[] = []
- const derived = expectDefined(await buildDerivedTextDataV4(text, fontDigestMap, null, blobs), 'derived text')
+ const derived = expectDefined(
+ await buildDerivedTextDataV4(text, fontDigestMap, null, blobs),
+ 'derived text'
+ )
expect(derived.fontMetaData[0].key.style).toBe('Semi Bold')
expect(derived.glyphs[0].commandsBlob).toBe(0)
diff --git a/tests/engine/text/style-runs/mutation.test.ts b/tests/engine/text/style-runs/mutation.test.ts
index 1befc1db2..5efc0ae94 100644
--- a/tests/engine/text/style-runs/mutation.test.ts
+++ b/tests/engine/text/style-runs/mutation.test.ts
@@ -147,4 +147,3 @@ describe('removeStyleFromRange — edge cases', () => {
expect(getStyleAt(result, 7).fontWeight).toBe(700)
})
})
-
diff --git a/tests/engine/tools/modify/image-fill.test.ts b/tests/engine/tools/modify/image-fill.test.ts
index 3ba2c9cd8..d0dd4f0ac 100644
--- a/tests/engine/tools/modify/image-fill.test.ts
+++ b/tests/engine/tools/modify/image-fill.test.ts
@@ -123,4 +123,3 @@ describe('set_image_fill tool', () => {
expect(graph.images.get(result.imageHash)).toEqual(PNG_MAGIC)
})
})
-
diff --git a/tests/engine/vector/blob/mutation.test.ts b/tests/engine/vector/blob/mutation.test.ts
index 3ecad2982..f9e78c69c 100644
--- a/tests/engine/vector/blob/mutation.test.ts
+++ b/tests/engine/vector/blob/mutation.test.ts
@@ -1,6 +1,10 @@
import { describe, test, expect } from 'bun:test'
-import { decodeVectorNetworkBlob, encodeVectorNetworkBlob, type VectorNetwork } from '@open-pencil/core'
+import {
+ decodeVectorNetworkBlob,
+ encodeVectorNetworkBlob,
+ type VectorNetwork
+} from '@open-pencil/core'
// ---------------------------------------------------------------------------
// vectorNetworkBlob — precision and handleMirroring round-trip
@@ -105,4 +109,3 @@ describe('vectorNetworkBlob — precision and mirroring', () => {
expect(Buffer.from(a).equals(Buffer.from(b))).toBe(true)
})
})
-
diff --git a/tests/engine/vector/blob/roundtrip.test.ts b/tests/engine/vector/blob/roundtrip.test.ts
index 4329d0c7f..aefa3350c 100644
--- a/tests/engine/vector/blob/roundtrip.test.ts
+++ b/tests/engine/vector/blob/roundtrip.test.ts
@@ -1,6 +1,10 @@
import { describe, test, expect } from 'bun:test'
-import { encodeVectorNetworkBlob, decodeVectorNetworkBlob, type VectorNetwork } from '@open-pencil/core'
+import {
+ encodeVectorNetworkBlob,
+ decodeVectorNetworkBlob,
+ type VectorNetwork
+} from '@open-pencil/core'
import {
lineNetwork,
@@ -101,4 +105,3 @@ describe('vectorNetworkBlob round-trip', () => {
expect(decoded.regions[1].loops).toEqual([[0, 2]])
})
})
-
diff --git a/tests/engine/vector/normalize.test.ts b/tests/engine/vector/normalize.test.ts
index eb4a9f3d9..211bcb511 100644
--- a/tests/engine/vector/normalize.test.ts
+++ b/tests/engine/vector/normalize.test.ts
@@ -1,6 +1,11 @@
import { describe, test, expect } from 'bun:test'
-import { decodeVectorNetworkBlob, encodeVectorNetworkBlob, normalizeVectorNetwork, type VectorNetwork } from '@open-pencil/core'
+import {
+ decodeVectorNetworkBlob,
+ encodeVectorNetworkBlob,
+ normalizeVectorNetwork,
+ type VectorNetwork
+} from '@open-pencil/core'
describe('normalizeVectorNetwork', () => {
test('passes through segments that already have tangents', () => {
@@ -73,4 +78,3 @@ describe('normalizeVectorNetwork', () => {
expect(decoded.regions[0].loops).toEqual([[0, 1, 2]])
})
})
-
diff --git a/tests/engine/vector/validate.test.ts b/tests/engine/vector/validate.test.ts
index abc1fa986..1de7e9e0f 100644
--- a/tests/engine/vector/validate.test.ts
+++ b/tests/engine/vector/validate.test.ts
@@ -54,4 +54,3 @@ describe('validateVectorNetwork', () => {
expect(errors[0]).toContain('x and y must be numbers')
})
})
-
diff --git a/tests/engine/vue/canvas/render-loop.test.ts b/tests/engine/vue/canvas/render-loop.test.ts
index 7d34632fa..91e37723d 100644
--- a/tests/engine/vue/canvas/render-loop.test.ts
+++ b/tests/engine/vue/canvas/render-loop.test.ts
@@ -1,9 +1,9 @@
import { describe, expect, test } from 'bun:test'
-import { createCanvasRenderLoop } from '#vue/canvas/surface/render-loop'
-
import type { Editor, EditorEvents } from '@open-pencil/core/editor'
+import { createCanvasRenderLoop } from '#vue/canvas/surface/render-loop'
+
type EditorEventName = keyof EditorEvents
type TestEditor = Pick<Editor, 'state' | 'onEditorEvent'>
diff --git a/tests/engine/vue/input/auto-layout-hover.test.ts b/tests/engine/vue/input/auto-layout-hover.test.ts
index 5cf9f57a0..acc9443f2 100644
--- a/tests/engine/vue/input/auto-layout-hover.test.ts
+++ b/tests/engine/vue/input/auto-layout-hover.test.ts
@@ -1,9 +1,10 @@
import { describe, expect, test } from 'bun:test'
-import { resolveAutoLayoutHover } from '#vue/shared/input/auto-layout-hover'
import type { Editor } from '@open-pencil/core/editor'
import type { SceneNode } from '@open-pencil/core/scene-graph'
+import { resolveAutoLayoutHover } from '#vue/shared/input/auto-layout-hover'
+
function frame(overrides: Partial<SceneNode> = {}): SceneNode {
return {
id: 'frame',
diff --git a/tests/engine/vue/input/move-threshold.test.ts b/tests/engine/vue/input/move-threshold.test.ts
index a01e08657..bdf7f0991 100644
--- a/tests/engine/vue/input/move-threshold.test.ts
+++ b/tests/engine/vue/input/move-threshold.test.ts
@@ -6,7 +6,11 @@ import { handleMoveMove, handleMoveUp, MOVE_DRAG_START_THRESHOLD_PX } from '#vue
import { createSelectionMoveDrag } from '#vue/shared/input/select/move'
import type { DragMove } from '#vue/shared/input/types'
-function setupMoveDrag(): { editor: ReturnType<typeof createEditor>; drag: DragMove; nodeId: string } {
+function setupMoveDrag(): {
+ editor: ReturnType<typeof createEditor>
+ drag: DragMove
+ nodeId: string
+} {
const editor = createEditor()
const pageId = editor.state.currentPageId
const node = editor.graph.createNode('RECTANGLE', pageId, {
diff --git a/tests/engine/vue/layout/hug-contents.test.ts b/tests/engine/vue/layout/hug-contents.test.ts
index 92f1bba95..83873b036 100644
--- a/tests/engine/vue/layout/hug-contents.test.ts
+++ b/tests/engine/vue/layout/hug-contents.test.ts
@@ -1,8 +1,13 @@
import { describe, expect, test } from 'bun:test'
-import { widthSizingForNode, heightSizingForNode, sizingOptionsForNode } from '#vue/controls/layout/helpers'
import type { SceneNode } from '@open-pencil/core/scene-graph'
+import {
+ widthSizingForNode,
+ heightSizingForNode,
+ sizingOptionsForNode
+} from '#vue/controls/layout/helpers'
+
function node(overrides: Partial<SceneNode>): SceneNode {
return {
id: 'node',
diff --git a/tests/helpers/canvas.ts b/tests/helpers/canvas.ts
index 28e2ea982..5e1c26c78 100644
--- a/tests/helpers/canvas.ts
+++ b/tests/helpers/canvas.ts
@@ -27,7 +27,10 @@ export class CanvasHelper {
}
async waitForInit() {
- await this.page.getByTestId('canvas-element').and(this.page.locator('[data-ready="1"]')).waitFor({ timeout: 30000 })
+ await this.page
+ .getByTestId('canvas-element')
+ .and(this.page.locator('[data-ready="1"]'))
+ .waitFor({ timeout: 30000 })
await this.page.getByTestId('canvas-loading').waitFor({ state: 'hidden', timeout: 30000 })
await this.page.locator('#loader').waitFor({ state: 'detached', timeout: 30000 })
}
diff --git a/vite.config.ts b/vite.config.ts
index 9c6a0cc24..67f965485 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -1,7 +1,5 @@
import process from 'node:process'
-import packageJson from './package.json'
-
import tailwindcss from '@tailwindcss/vite'
import vue from '@vitejs/plugin-vue'
import IconsResolver from 'unplugin-icons/resolver'
@@ -9,6 +7,7 @@ import Icons from 'unplugin-icons/vite'
import Components from 'unplugin-vue-components/vite'
import { defineConfig } from 'vite'
+import packageJson from './package.json'
import { createOpenPencilAliases } from './vite/aliases'
import { localAutomationToken, openPencilAutomationPlugin } from './vite/automation'
import { copyCanvasKitAssetsPlugin } from './vite/canvaskit-assets'