Skip to content

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

Align app UI primitives with shared ui overrides

Danila Poyarkov329dd301bd3c
diff --git a/.oxfmtrc.json b/.oxfmtrc.json
index 53675cfd2..f74a75d74 100644
--- a/.oxfmtrc.json
+++ b/.oxfmtrc.json
@@ -6,11 +6,6 @@
"singleQuote": true,
"printWidth": 100,
"arrowParens": "always",
- "sortTailwindcss": {
- "stylesheet": "src/app.css",
- "functions": ["twMerge", "tv"],
- "preserveDuplicates": false
- },
"sortImports": {
"order": "asc",
"ignoreCase": true,
diff --git a/REFACTOR.md b/REFACTOR.md
index cf96174bf..8a5698a86 100644
--- a/REFACTOR.md
+++ b/REFACTOR.md
@@ -91,7 +91,10 @@ Status of all items from the codebase audit.
## Additional work completed
- **vue-tsc errors**: Fixed all 135, now a check gate (was never checked before)
-- **`@open-pencil/vue` SDK**: Headless package with 8 composables, 6 renderless components
+- **`@open-pencil/vue` SDK**: Headless package with renderless components plus shared editor composables for selection, commands, viewport, and menu models
+- **SDK command spine**: `useSelectionCapabilities()`, `useEditorCommands()`, `useViewportKind()`, `useMenuModel()` now power keyboard/menu/context-menu flows
+- **App UI primitives cleanup**: base app-styled components moved under `src/components/ui/`, `ui` prop adopted for grouped/simple selects, lightweight `useComponentUI()` added and expanded into button/input/icon-button helpers; slot helpers now have `useMenuUI()`, `usePopoverUI()`, `useDialogUI()`, `useTooltipUI()`, `useSelectUI()`
+- **Formatter restored**: `.oxfmtrc.json` recovered from git history, import sorting restored, formatting now covers all packages
- **Editor variable actions**: 7 undo-able CRUD operations, wired into VariablesDialog
- **Editor alignment actions**: alignNodes, flipNodes, rotateNodes, wired into PositionSection
- **`updateNodeWithUndo` auto-renders**: eliminated 15+ redundant requestRender() calls
diff --git a/SDK-PLAN.md b/SDK-PLAN.md
index f5dedfbba..2c810552f 100644
--- a/SDK-PLAN.md
+++ b/SDK-PLAN.md
@@ -82,8 +82,10 @@ OpenPencil app becomes a styled composition of these primitives.
| SDK | Type | Slot props |
|-----|------|-----------|
-| `EditorContextMenu` | Component | Selection-aware context menu items |
-| `EditorMenuBar` | Component | File/Edit/View menu structure |
+| `useEditorCommands()` | Composable | Typed command registry, enablement, run helpers |
+| `useMenuModel()` | Composable | Renderless menu trees for app/context/mobile menus |
+| `EditorContextMenu` | Component | Optional thin renderer over `useMenuModel().canvasMenu` |
+| `EditorMenuBar` | Component | Optional thin renderer over `useMenuModel().appMenu` |
### Inputs
@@ -98,6 +100,10 @@ OpenPencil app becomes a styled composition of these primitives.
|-----|---------|
| `useEditor()` | Inject editor |
| `useSelectionState()` | Reactive selection queries |
+| `useSelectionCapabilities()` | Selection-aware command enablement |
+| `useEditorCommands()` | Shared command execution layer |
+| `useMenuModel()` | Renderless menu data model |
+| `useViewportKind()` | Shared mobile/desktop breakpoint state |
| `useNodeProps()` | Property editing with undo |
| `useInlineRename()` | Inline rename input |
| `useLayerDrag()` | Atlaskit tree DnD |
@@ -113,6 +119,7 @@ OpenPencil app becomes a styled composition of these primitives.
- `AppToast` — toast styling
- `CodePanel` — JSX generation
- `use-collab.ts`, `use-chat.ts`, `use-keyboard.ts`, `use-menu.ts`
+- app-styled UI primitives in `src/components/ui/` (`AppSelect`, `AppGroupedSelect`, `Tip`, style helpers) stay outside SDK unless rewritten as headless/generic primitives
## Migration Phases
@@ -135,7 +142,9 @@ OpenPencil app becomes a styled composition of these primitives.
- Rename, selection sync
### Phase 5: Menu primitives
-- `EditorContextMenu`, `EditorMenuBar`
+- ✅ `useEditorCommands()`
+- ✅ `useMenuModel()`
+- Next: optional `EditorContextMenu`, `EditorMenuBar` renderers once app-side host overrides settle
### Phase 6: Dialog/picker primitives
- `VariablesEditorRoot`
@@ -145,3 +154,21 @@ OpenPencil app becomes a styled composition of these primitives.
### Phase 7: App migration
- Rewrite every app component as styled SDK composition
- App files = styling + layout only
+
+## Current status
+
+Completed:
+- `useSelectionCapabilities()`
+- `useEditorCommands()`
+- `useViewportKind()`
+- `useMenuModel()`
+- `CanvasMenu.vue` partly rendered from SDK menu model
+- `AppMenu.vue` partly rendered from SDK menu model
+- keyboard shortcuts migrated to shared command execution for core editor actions
+
+Next recommended steps:
+1. Standardize remaining app primitives on the `ui` + `useComponentUI()` pattern, preferring semantic slot overrides over raw class props
+2. Continue moving app-styled reusable components into `src/components/ui/`
+3. Normalize slot-based style helpers (`menu`, `dialog`, `popover`, `tooltip`, `select`) around the same override conventions
+4. Move remaining `MobileHud` menu/action groups behind command/menu abstractions
+5. Decide whether `EditorContextMenu` / `EditorMenuBar` should exist as SDK renderers or stay as app renderers over SDK data
diff --git a/package.json b/package.json
index a2c1f08a3..16ecedbf2 100644
--- a/package.json
+++ b/package.json
@@ -13,7 +13,7 @@
"preview": "vite preview",
"tauri": "tauri",
"lint": "oxlint -c oxlint.json --type-aware --type-check src/ packages/core/src/ packages/cli/src/ packages/mcp/src/",
- "format": "oxfmt --write src/",
+ "format": "oxfmt --write src/ packages/core/src/ packages/cli/src/ packages/mcp/src/ packages/vue/src/",
"check": "bun run lint && tsgo --noEmit && vue-tsc --noEmit",
"test": "playwright test --project=openpencil",
"test:update": "playwright test --project=openpencil --update-snapshots",
diff --git a/packages/core/src/kiwi/instance-overrides/dsd.ts b/packages/core/src/kiwi/instance-overrides/dsd.ts
index c6b662e03..cdcf70d06 100644
--- a/packages/core/src/kiwi/instance-overrides/dsd.ts
+++ b/packages/core/src/kiwi/instance-overrides/dsd.ts
@@ -1,10 +1,11 @@
-import type { SceneNode, GeometryPath } from '../../scene-graph'
import { copyGeometryPaths } from '../../copy'
-import type { OverrideContext, DerivedSymbolOverride } from './types'
import { resolveGeometryPaths } from '../kiwi-convert'
import { resolveOverrideTarget } from './resolve'
import { buildClonesMap } from './sync'
+import type { SceneNode, GeometryPath } from '../../scene-graph'
+import type { OverrideContext, DerivedSymbolOverride } from './types'
+
function scaleGeometryBlobs(geom: GeometryPath[], sx: number, sy: number): GeometryPath[] {
if (sx === 1 && sy === 1) return geom
return geom.map((g) => {
@@ -14,7 +15,9 @@ function scaleGeometryBlobs(geom: GeometryPath[], sx: number, sy: number): Geome
while (o < scaled.length) {
const cmd = scaled[o++]
if (cmd === 0) continue
- const coords = cmd === 1 || cmd === 2 ? 1 : (cmd === 4 ? 3 : -1)
+ let coords = -1
+ if (cmd === 1 || cmd === 2) coords = 1
+ else if (cmd === 4) coords = 3
if (coords < 0) {
console.warn(`scaleGeometryBlobs: unknown path command ${cmd} at offset ${o - 1}`)
break
@@ -41,13 +44,21 @@ 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
@@ -97,7 +108,11 @@ function resolveDsdUpdates(ctx: OverrideContext): { modified: Set<string>; sizeS
return { modified, sizeSet }
}
-function propagateDsdChanges(ctx: OverrideContext, modified: Set<string>, sizeSet: Set<string>): void {
+function propagateDsdChanges(
+ ctx: OverrideContext,
+ modified: Set<string>,
+ sizeSet: Set<string>
+): void {
if (modified.size === 0) return
const clonesOf = buildClonesMap(ctx.graph)
@@ -120,8 +135,10 @@ function propagateDsdChanges(ctx: OverrideContext, modified: Set<string>, sizeSe
if (source.height !== clone.height) cu.height = source.height
if (source.x !== clone.x) cu.x = source.x
if (source.y !== clone.y) cu.y = source.y
- if (source.fillGeometry !== clone.fillGeometry) cu.fillGeometry = copyGeometryPaths(source.fillGeometry)
- if (source.strokeGeometry !== clone.strokeGeometry) cu.strokeGeometry = copyGeometryPaths(source.strokeGeometry)
+ if (source.fillGeometry !== clone.fillGeometry)
+ cu.fillGeometry = copyGeometryPaths(source.fillGeometry)
+ if (source.strokeGeometry !== clone.strokeGeometry)
+ cu.strokeGeometry = copyGeometryPaths(source.strokeGeometry)
if (Object.keys(cu).length > 0) ctx.graph.updateNode(cloneId, cu)
}
queue.push(cloneId)
diff --git a/packages/core/src/kiwi/kiwi-convert-overrides.ts b/packages/core/src/kiwi/kiwi-convert-overrides.ts
index 7234d9806..99f088145 100644
--- a/packages/core/src/kiwi/kiwi-convert-overrides.ts
+++ b/packages/core/src/kiwi/kiwi-convert-overrides.ts
@@ -1,7 +1,4 @@
import { styleToWeight } from '../fonts'
-
-import type { SceneNode, ArcData, TextAutoResize } from '../scene-graph'
-import type { NodeChange, Paint, Effect as KiwiEffect } from './codec'
import {
convertFills,
mapStackSizing,
@@ -14,9 +11,12 @@ import {
mapArcData,
importStyleRuns,
convertStrokes,
- convertEffects,
+ convertEffects
} from './kiwi-convert'
+import type { SceneNode, ArcData, TextAutoResize } from '../scene-graph'
+import type { NodeChange, Paint, Effect as KiwiEffect } from './codec'
+
function applyOverridePaints(ov: Record<string, unknown>, updates: Partial<SceneNode>): void {
if (ov.textData != null) {
const td = ov.textData as { characters?: string }
@@ -55,8 +55,7 @@ function applyOverrideGeometry(ov: Record<string, unknown>, updates: Partial<Sce
updates.bottomLeftRadius = ov.rectangleBottomLeftCornerRadius as number
if (ov.rectangleCornerRadiiIndependent != null)
updates.independentCorners = ov.rectangleCornerRadiiIndependent as boolean
- if (ov.arcData != null)
- updates.arcData = mapArcData(ov.arcData as Partial<ArcData> | undefined)
+ if (ov.arcData != null) updates.arcData = mapArcData(ov.arcData as Partial<ArcData> | undefined)
if (ov.frameMaskDisabled != null) updates.clipsContent = ov.frameMaskDisabled === false
}
@@ -74,8 +73,7 @@ function applyOverrideLayout(ov: Record<string, unknown>, updates: Partial<Scene
if (ov.stackChildAlignSelf != null)
updates.layoutAlignSelf = mapAlignSelf(ov.stackChildAlignSelf as string)
if (ov.stackPositioning != null)
- updates.layoutPositioning =
- (ov.stackPositioning as string) === 'ABSOLUTE' ? 'ABSOLUTE' : 'AUTO'
+ updates.layoutPositioning = (ov.stackPositioning as string) === 'ABSOLUTE' ? 'ABSOLUTE' : 'AUTO'
if (ov.stackVerticalPadding != null) {
updates.paddingTop = ov.stackVerticalPadding as number
if (ov.stackPaddingBottom == null) updates.paddingBottom = ov.stackVerticalPadding as number
@@ -93,8 +91,9 @@ function applyOverrideStrokes(ov: Record<string, unknown>, updates: Partial<Scen
updates.strokes = updates.strokes ?? []
}
if (ov.strokeAlign != null && updates.strokes) {
- const align =
- ov.strokeAlign === 'INSIDE' ? 'INSIDE' : (ov.strokeAlign === 'OUTSIDE' ? 'OUTSIDE' : 'CENTER')
+ let align: 'INSIDE' | 'OUTSIDE' | 'CENTER' = 'CENTER'
+ if (ov.strokeAlign === 'INSIDE') align = 'INSIDE'
+ else if (ov.strokeAlign === 'OUTSIDE') align = 'OUTSIDE'
for (const s of updates.strokes) s.align = align
}
if (ov.borderTopWeight != null) updates.borderTopWeight = ov.borderTopWeight as number
@@ -130,8 +129,7 @@ function applyOverrideText(ov: Record<string, unknown>, updates: Partial<SceneNo
)
if (ov.maxLines != null) updates.maxLines = ov.maxLines as number | null
if (ov.textTruncation != null)
- updates.textTruncation =
- (ov.textTruncation as string) === 'ENDING' ? 'ENDING' : 'DISABLED'
+ updates.textTruncation = (ov.textTruncation as string) === 'ENDING' ? 'ENDING' : 'DISABLED'
if (ov.textDecoration != null)
updates.textDecoration = mapTextDecoration(ov.textDecoration as string)
}
diff --git a/packages/core/src/kiwi/kiwi-convert.ts b/packages/core/src/kiwi/kiwi-convert.ts
index d893012be..fececc26c 100644
--- a/packages/core/src/kiwi/kiwi-convert.ts
+++ b/packages/core/src/kiwi/kiwi-convert.ts
@@ -3,7 +3,6 @@ import { normalizeColor } from '../color'
import { DEFAULT_FONT_FAMILY, DEFAULT_STROKE_MITER_LIMIT } from '../constants'
import { styleToWeight } from '../fonts'
import { decodeVectorNetworkBlob } from '../vector'
-import type { Color, Matrix, Vector } from '../types'
import type {
SceneNode,
@@ -34,10 +33,9 @@ import type {
CharacterStyleOverride,
WindingRule
} from '../scene-graph'
+import type { Color, Matrix, Vector } from '../types'
import type { NodeChange, Paint, Effect as KiwiEffect, GUID } from './codec'
-
-
export function guidToString(guid: GUID): string {
return `${guid.sessionID}:${guid.localID}`
}
@@ -149,16 +147,16 @@ export function convertStrokes(
dashPattern?: number[]
): Stroke[] {
if (!paints) return []
+ let strokeAlign: 'INSIDE' | 'OUTSIDE' | 'CENTER' = 'CENTER'
+ if (align === 'INSIDE') strokeAlign = 'INSIDE'
+ else if (align === 'OUTSIDE') strokeAlign = 'OUTSIDE'
+
return paints.map((p) => ({
color: convertColor(resolveColorVar(p) ?? p.color),
weight: weight ?? 1,
opacity: p.opacity ?? 1,
visible: p.visible ?? true,
- align: (align === 'INSIDE'
- ? 'INSIDE'
- : (align === 'OUTSIDE'
- ? 'OUTSIDE'
- : 'CENTER')),
+ align: strokeAlign,
cap: (cap ?? 'NONE') as StrokeCap,
join: (join ?? 'MITER') as StrokeJoin,
dashPattern: dashPattern ?? []
@@ -343,7 +341,10 @@ function convertStyleOverride(
}
if (override.fontSize !== undefined) style.fontSize = override.fontSize
if (override.letterSpacing) {
- style.letterSpacing = convertLetterSpacing(override.letterSpacing, override.fontSize ?? fallbackFontSize)
+ style.letterSpacing = convertLetterSpacing(
+ override.letterSpacing,
+ override.fontSize ?? fallbackFontSize
+ )
}
if (override.lineHeight) {
const lh = convertLineHeight(override.lineHeight, override.fontSize ?? fallbackFontSize)
@@ -408,10 +409,7 @@ export function importStyleRuns(nc: NodeChange): StyleRun[] {
return collectStyleRuns(ids, styleMap)
}
-function resolveVectorNetwork(
- nc: NodeChange,
- blobs: Uint8Array[]
-): VectorNetwork | null {
+function resolveVectorNetwork(nc: NodeChange, blobs: Uint8Array[]): VectorNetwork | null {
const vectorData = nc.vectorData as
| {
vectorNetworkBlob?: number
@@ -488,7 +486,9 @@ function extractBoundVariables(nc: NodeChange): Record<string, string> {
return bindings
}
-function convertTransformProps(nc: NodeChange): Pick<SceneNode, 'x' | 'y' | 'width' | 'height' | 'rotation' | 'flipX' | 'flipY'> {
+function convertTransformProps(
+ nc: NodeChange
+): Pick<SceneNode, 'x' | 'y' | 'width' | 'height' | 'rotation' | 'flipX' | 'flipY'> {
const x = nc.transform?.m02 ?? 0
const y = nc.transform?.m12 ?? 0
const width = nc.size?.x ?? 100
@@ -506,7 +506,18 @@ function convertTransformProps(nc: NodeChange): Pick<SceneNode, 'x' | 'y' | 'wid
return { x, y, width, height, rotation, flipX, flipY: false }
}
-function convertCornerProps(nc: NodeChange): Pick<SceneNode, 'cornerRadius' | 'topLeftRadius' | 'topRightRadius' | 'bottomRightRadius' | 'bottomLeftRadius' | 'independentCorners' | 'cornerSmoothing'> {
+function convertCornerProps(
+ nc: NodeChange
+): Pick<
+ SceneNode,
+ | 'cornerRadius'
+ | 'topLeftRadius'
+ | 'topRightRadius'
+ | 'bottomRightRadius'
+ | 'bottomLeftRadius'
+ | 'independentCorners'
+ | 'cornerSmoothing'
+> {
return {
cornerRadius: nc.cornerRadius ?? 0,
topLeftRadius: nc.rectangleTopLeftCornerRadius ?? nc.cornerRadius ?? 0,
@@ -518,14 +529,37 @@ function convertCornerProps(nc: NodeChange): Pick<SceneNode, 'cornerRadius' | 't
}
}
-function convertTextProps(nc: NodeChange): Pick<SceneNode, 'text' | 'fontSize' | 'fontFamily' | 'fontWeight' | 'italic' | 'textAlignHorizontal' | 'textAlignVertical' | 'textAutoResize' | 'textCase' | 'textDecoration' | 'lineHeight' | 'letterSpacing' | 'maxLines' | 'styleRuns' | 'textTruncation'> {
+function convertTextProps(
+ nc: NodeChange
+): Pick<
+ SceneNode,
+ | 'text'
+ | 'fontSize'
+ | 'fontFamily'
+ | 'fontWeight'
+ | 'italic'
+ | 'textAlignHorizontal'
+ | 'textAlignVertical'
+ | 'textAutoResize'
+ | 'textCase'
+ | 'textDecoration'
+ | 'lineHeight'
+ | 'letterSpacing'
+ | 'maxLines'
+ | 'styleRuns'
+ | 'textTruncation'
+> {
return {
text: nc.textData?.characters ?? '',
fontSize: nc.fontSize ?? 14,
fontFamily: nc.fontName?.family ?? DEFAULT_FONT_FAMILY,
fontWeight: styleToWeight(nc.fontName?.style ?? ''),
italic: nc.fontName?.style.toLowerCase().includes('italic') ?? false,
- textAlignHorizontal: (nc.textAlignHorizontal ?? 'LEFT') as 'LEFT' | 'CENTER' | 'RIGHT' | 'JUSTIFIED',
+ textAlignHorizontal: (nc.textAlignHorizontal ?? 'LEFT') as
+ | 'LEFT'
+ | 'CENTER'
+ | 'RIGHT'
+ | 'JUSTIFIED',
textAlignVertical: (nc.textAlignVertical ?? 'TOP') as TextAlignVertical,
textAutoResize: (nc.textAutoResize ?? 'NONE') as TextAutoResize,
textCase: (nc.textCase ?? 'ORIGINAL') as TextCase,
@@ -538,7 +572,9 @@ function convertTextProps(nc: NodeChange): Pick<SceneNode, 'text' | 'fontSize' |
}
}
-function convertLayoutPadding(nc: NodeChange): Pick<SceneNode, 'paddingTop' | 'paddingBottom' | 'paddingLeft' | 'paddingRight'> {
+function convertLayoutPadding(
+ nc: NodeChange
+): Pick<SceneNode, 'paddingTop' | 'paddingBottom' | 'paddingLeft' | 'paddingRight'> {
return {
paddingTop: nc.stackVerticalPadding ?? nc.stackPadding ?? 0,
paddingBottom: nc.stackPaddingBottom ?? nc.stackVerticalPadding ?? nc.stackPadding ?? 0,
@@ -547,7 +583,29 @@ function convertLayoutPadding(nc: NodeChange): Pick<SceneNode, 'paddingTop' | 'p
}
}
-function convertLayoutProps(nc: NodeChange): Pick<SceneNode, 'layoutMode' | 'itemSpacing' | 'paddingTop' | 'paddingBottom' | 'paddingLeft' | 'paddingRight' | 'primaryAxisSizing' | 'counterAxisSizing' | 'primaryAxisAlign' | 'counterAxisAlign' | 'layoutWrap' | 'counterAxisSpacing' | 'layoutPositioning' | 'layoutGrow' | 'layoutAlignSelf' | 'counterAxisAlignContent' | 'itemReverseZIndex' | 'strokesIncludedInLayout'> {
+function convertLayoutProps(
+ nc: NodeChange
+): Pick<
+ SceneNode,
+ | 'layoutMode'
+ | 'itemSpacing'
+ | 'paddingTop'
+ | 'paddingBottom'
+ | 'paddingLeft'
+ | 'paddingRight'
+ | 'primaryAxisSizing'
+ | 'counterAxisSizing'
+ | 'primaryAxisAlign'
+ | 'counterAxisAlign'
+ | 'layoutWrap'
+ | 'counterAxisSpacing'
+ | 'layoutPositioning'
+ | 'layoutGrow'
+ | 'layoutAlignSelf'
+ | 'counterAxisAlignContent'
+ | 'itemReverseZIndex'
+ | 'strokesIncludedInLayout'
+> {
return {
layoutMode: mapStackMode(nc.stackMode),
itemSpacing: nc.stackSpacing ?? 0,
@@ -561,13 +619,32 @@ function convertLayoutProps(nc: NodeChange): Pick<SceneNode, 'layoutMode' | 'ite
layoutPositioning: nc.stackPositioning === 'ABSOLUTE' ? 'ABSOLUTE' : 'AUTO',
layoutGrow: nc.stackChildPrimaryGrow ?? 0,
layoutAlignSelf: mapAlignSelf(nc.stackChildAlignSelf),
- counterAxisAlignContent: (nc.stackCounterAlignContent as string) === 'SPACE_BETWEEN' ? 'SPACE_BETWEEN' : 'AUTO',
+ counterAxisAlignContent:
+ (nc.stackCounterAlignContent as string) === 'SPACE_BETWEEN' ? 'SPACE_BETWEEN' : 'AUTO',
itemReverseZIndex: (nc.stackReverseZIndex ?? false) as boolean,
strokesIncludedInLayout: (nc.strokesIncludedInLayout ?? false) as boolean
}
}
-function convertVectorAndStrokeProps(nc: NodeChange, blobs: Uint8Array[]): Pick<SceneNode, 'vectorNetwork' | 'fillGeometry' | 'strokeGeometry' | 'arcData' | 'strokeCap' | 'strokeJoin' | 'dashPattern' | 'borderTopWeight' | 'borderRightWeight' | 'borderBottomWeight' | 'borderLeftWeight' | 'independentStrokeWeights' | 'strokeMiterLimit'> {
+function convertVectorAndStrokeProps(
+ nc: NodeChange,
+ blobs: Uint8Array[]
+): Pick<
+ SceneNode,
+ | 'vectorNetwork'
+ | 'fillGeometry'
+ | 'strokeGeometry'
+ | 'arcData'
+ | 'strokeCap'
+ | 'strokeJoin'
+ | 'dashPattern'
+ | 'borderTopWeight'
+ | 'borderRightWeight'
+ | 'borderBottomWeight'
+ | 'borderLeftWeight'
+ | 'independentStrokeWeights'
+ | 'strokeMiterLimit'
+> {
return {
vectorNetwork: resolveVectorNetwork(nc, blobs),
fillGeometry: resolveGeometryPaths(nc.fillGeometry, blobs),
@@ -601,7 +678,14 @@ export function nodeChangeToProps(
locked: nc.locked ?? false,
blendMode: (nc.blendMode as Fill['blendMode']) ?? 'PASS_THROUGH',
fills: convertFills(nc.fillPaints),
- strokes: convertStrokes(nc.strokePaints, nc.strokeWeight, nc.strokeAlign, nc.strokeCap, nc.strokeJoin, nc.dashPattern ?? []),
+ strokes: convertStrokes(
+ nc.strokePaints,
+ nc.strokeWeight,
+ nc.strokeAlign,
+ nc.strokeCap,
+ nc.strokeJoin,
+ nc.dashPattern ?? []
+ ),
effects: convertEffects(nc.effects),
...convertCornerProps(nc),
...convertTextProps(nc),
@@ -646,16 +730,15 @@ export function sortChildren(
children.sort((a, b) => {
const aPos = nodeMap.get(a)?.parentIndex?.position ?? ''
const bPos = nodeMap.get(b)?.parentIndex?.position ?? ''
- return aPos < bPos ? -1 : (aPos > bPos ? 1 : 0)
+ if (aPos < bPos) return -1
+ if (aPos > bPos) return 1
+ return 0
})
}
}
function extractSymbolId(nc: NodeChange): string {
- const sd = nc.symbolData as
- | { symbolID?: GUID }
- | undefined
+ const sd = nc.symbolData as { symbolID?: GUID } | undefined
if (!sd?.symbolID) return ''
return guidToString(sd.symbolID)
}
-
diff --git a/packages/core/src/layout.ts b/packages/core/src/layout.ts
index 4f1271579..884429769 100644
--- a/packages/core/src/layout.ts
+++ b/packages/core/src/layout.ts
@@ -361,8 +361,7 @@ function configureChildAsLeaf(yogaChild: YogaNode, child: SceneNode, parent: Sce
: parent.counterAxisAlign === 'STRETCH'
const isText = child.type === 'TEXT'
- const needsMeasureFunc =
- isText && globalTextMeasurer && child.textAutoResize !== 'NONE'
+ const needsMeasureFunc = isText && globalTextMeasurer && child.textAutoResize !== 'NONE'
if (needsMeasureFunc) {
configureTextLeaf(yogaChild, child, parent)
@@ -374,7 +373,8 @@ function configureChildAsLeaf(yogaChild: YogaNode, child: SceneNode, parent: Sce
yogaChild.setWidth(est.width)
yogaChild.setHeight(est.height)
} else if (child.textAutoResize === 'HEIGHT') {
- const stretches = child.layoutAlignSelf === 'STRETCH' ||
+ const stretches =
+ child.layoutAlignSelf === 'STRETCH' ||
(child.layoutAlignSelf === 'AUTO' && parent.counterAxisAlign === 'STRETCH')
if (!(!isRow && stretches)) {
yogaChild.setWidth(child.width)
@@ -392,11 +392,7 @@ function configureChildAsLeaf(yogaChild: YogaNode, child: SceneNode, parent: Sce
applyMinMaxConstraints(yogaChild, child)
}
-function configureTextLeaf(
- yogaChild: YogaNode,
- child: SceneNode,
- parent: SceneNode
-): void {
+function configureTextLeaf(yogaChild: YogaNode, child: SceneNode, parent: SceneNode): void {
const autoResize = child.textAutoResize
const isRow = parent.layoutMode === 'HORIZONTAL'
@@ -420,7 +416,8 @@ function configureTextLeaf(
return result
})
} else if (autoResize === 'HEIGHT') {
- const stretchesCross = child.layoutAlignSelf === 'STRETCH' ||
+ const stretchesCross =
+ child.layoutAlignSelf === 'STRETCH' ||
(child.layoutAlignSelf === 'AUTO' && parent.counterAxisAlign === 'STRETCH')
// Don't set fixed width when text stretches on cross axis (w="fill" in
// flex="col" parent) — setWidth blocks Yoga's alignSelf:stretch, leaving
@@ -431,15 +428,21 @@ function configureTextLeaf(
yogaChild.setWidth(fixedWidth)
}
yogaChild.setMeasureFunc((width, widthMode, _height, _heightMode) => {
- const constraintW = fillsWidth
- ? (widthMode === MeasureMode.Undefined ? fixedWidth : width)
- : (widthMode === MeasureMode.Undefined ? fixedWidth : Math.min(width, fixedWidth || width))
+ let constraintW = fixedWidth
+ if (fillsWidth) {
+ if (widthMode !== MeasureMode.Undefined) constraintW = width
+ } else if (widthMode !== MeasureMode.Undefined) {
+ constraintW = Math.min(width, fixedWidth || width)
+ }
const cacheKey = Math.round(constraintW)
const cached = cache.get(cacheKey)
if (cached) return cached
const measured = globalTextMeasurer?.(child, constraintW)
- const result = { width: constraintW, height: measured?.height ?? estimateTextSize(child, constraintW).height }
+ const result = {
+ width: constraintW,
+ height: measured?.height ?? estimateTextSize(child, constraintW).height
+ }
cache.set(cacheKey, result)
return result
})
@@ -569,7 +572,11 @@ function applyYogaLayout(graph: SceneGraph, frame: SceneNode, yogaNode: YogaNode
if (child.layoutMode !== 'NONE') {
if (child.layoutMode === 'GRID' && child.visible && child.layoutPositioning !== 'ABSOLUTE') {
computeLayout(graph, child.id)
- } else if (frame.layoutMode === 'GRID' && child.visible && child.layoutPositioning !== 'ABSOLUTE') {
+ } else if (
+ frame.layoutMode === 'GRID' &&
+ child.visible &&
+ child.layoutPositioning !== 'ABSOLUTE'
+ ) {
recomputeGridChild(graph, child)
} else {
applyYogaLayout(graph, child, yogaChild)
diff --git a/packages/core/src/render/mini-react.ts b/packages/core/src/render/mini-react.ts
index ff892a43e..f42a19cdd 100644
--- a/packages/core/src/render/mini-react.ts
+++ b/packages/core/src/render/mini-react.ts
@@ -17,12 +17,7 @@ export function createElement(
type,
props: {
...props,
- children:
- flatChildren.length === 1
- ? flatChildren
- : (flatChildren.length > 0
- ? flatChildren
- : undefined)
+ children: flatChildren.length > 0 ? flatChildren : undefined
}
}
}
diff --git a/packages/core/src/renderer/strokes.ts b/packages/core/src/renderer/strokes.ts
index 3ff5aefe5..375866d4d 100644
--- a/packages/core/src/renderer/strokes.ts
+++ b/packages/core/src/renderer/strokes.ts
@@ -1,6 +1,6 @@
import type { SceneNode, Stroke } from '../scene-graph'
-import type { Canvas, Paint } from 'canvaskit-wasm'
import type { SkiaRenderer } from './renderer'
+import type { Canvas, Paint } from 'canvaskit-wasm'
export function drawNodeStroke(
r: SkiaRenderer,
@@ -58,12 +58,7 @@ export function drawStrokeWithAlign(
canvas.restore()
} else if (align === 'OUTSIDE') {
canvas.save()
- const bigRect = r.ck.LTRBRect(
- -node.width,
- -node.height,
- node.width * 2,
- node.height * 2
- )
+ const bigRect = r.ck.LTRBRect(-node.width, -node.height, node.width * 2, node.height * 2)
const outerPath = new r.ck.Path()
outerPath.addRect(bigRect)
const innerPath = r.makeNodeShapePath(node, rect, hasRadius)
@@ -98,9 +93,7 @@ export function drawRRectStrokeWithAlign(
} else if (stroke.align === 'OUTSIDE') {
canvas.save()
const outerPath = new r.ck.Path()
- outerPath.addRect(
- r.ck.LTRBRect(-node.width, -node.height, node.width * 2, node.height * 2)
- )
+ outerPath.addRect(r.ck.LTRBRect(-node.width, -node.height, node.width * 2, node.height * 2))
const innerPath = new r.ck.Path()
innerPath.addRRect(rrect)
outerPath.op(innerPath, r.ck.PathOp.Difference)
@@ -129,28 +122,36 @@ export function drawIndividualSideStrokes(
const tw = node.borderTopWeight
if (tw > 0) {
- const y = inside ? tw / 2 : (outside ? -tw / 2 : 0)
+ let y = 0
+ if (inside) y = tw / 2
+ else if (outside) y = -tw / 2
r.strokePaint.setStrokeWidth(tw)
canvas.drawLine(0, y, w, y, r.strokePaint)
}
const rw = node.borderRightWeight
if (rw > 0) {
- const x = inside ? w - rw / 2 : (outside ? w + rw / 2 : w)
+ let x = w
+ if (inside) x = w - rw / 2
+ else if (outside) x = w + rw / 2
r.strokePaint.setStrokeWidth(rw)
canvas.drawLine(x, 0, x, h, r.strokePaint)
}
const bw = node.borderBottomWeight
if (bw > 0) {
- const y = inside ? h - bw / 2 : (outside ? h + bw / 2 : h)
+ let y = h
+ if (inside) y = h - bw / 2
+ else if (outside) y = h + bw / 2
r.strokePaint.setStrokeWidth(bw)
canvas.drawLine(0, y, w, y, r.strokePaint)
}
const lw = node.borderLeftWeight
if (lw > 0) {
- const x = inside ? lw / 2 : (outside ? -lw / 2 : 0)
+ let x = 0
+ if (inside) x = lw / 2
+ else if (outside) x = -lw / 2
r.strokePaint.setStrokeWidth(lw)
canvas.drawLine(x, 0, x, h, r.strokePaint)
}
diff --git a/packages/core/src/renderer/text.ts b/packages/core/src/renderer/text.ts
index 1f199d19b..14afc1689 100644
--- a/packages/core/src/renderer/text.ts
+++ b/packages/core/src/renderer/text.ts
@@ -28,12 +28,9 @@ export function measureTextNode(
if (node.type !== 'TEXT' || !node.text) return null
const paragraph = buildParagraph(r, node)
- const layoutWidth =
- maxWidth !== undefined
- ? maxWidth
- : (node.textAutoResize === 'WIDTH_AND_HEIGHT'
- ? 1e6
- : node.width || 1e6)
+ let layoutWidth = node.width || 1e6
+ if (maxWidth !== undefined) layoutWidth = maxWidth
+ else if (node.textAutoResize === 'WIDTH_AND_HEIGHT') layoutWidth = 1e6
paragraph.layout(layoutWidth)
const width = paragraph.getLongestLine()
const height = paragraph.getHeight()
diff --git a/packages/core/src/rpc/commands.ts b/packages/core/src/rpc/commands.ts
index 3287738ef..031686a4e 100644
--- a/packages/core/src/rpc/commands.ts
+++ b/packages/core/src/rpc/commands.ts
@@ -1,8 +1,9 @@
/* eslint-disable max-lines -- RPC commands are cohesive; splitting adds indirection */
import { colorToHex, colorDistance as colorDist } from '../color'
import { queryByXPath } from '../xpath'
-import type { Color } from '../types'
+
import type { SceneGraph, SceneNode, Variable } from '../scene-graph'
+import type { Color } from '../types'
export interface RpcCommand<A = unknown, R = unknown> {
name: string
@@ -23,7 +24,12 @@ function walkNodes(graph: SceneGraph, rootId: string, fn: (node: SceneNode) => b
function countNodes(graph: SceneGraph, pageId: string): number {
let count = 0
const page = graph.getNode(pageId)
- if (page) for (const cid of page.childIds) walkNodes(graph, cid, () => { count++; return true })
+ if (page)
+ for (const cid of page.childIds)
+ walkNodes(graph, cid, () => {
+ count++
+ return true
+ })
return count
}
@@ -97,7 +103,12 @@ export interface TreeNodeResult {
children?: TreeNodeResult[]
}
-function buildTreeNode(graph: SceneGraph, id: string, depth: number, maxDepth: number): TreeNodeResult | null {
+function buildTreeNode(
+ graph: SceneGraph,
+ id: string,
+ depth: number,
+ maxDepth: number
+): TreeNodeResult | null {
const node = graph.getNode(id)
if (!node) return null
const result: TreeNodeResult = {
@@ -128,7 +139,10 @@ export const treeCommand: RpcCommand<TreeArgs, TreeResult | { error: string }> =
const pages = graph.getPages()
const maxDepth = args.depth ?? Infinity
const page = args.page ? pages.find((p) => p.name === args.page) : pages[0]
- if (!page) return { error: `Page "${args.page}" not found. Available: ${pages.map((p) => p.name).join(', ')}` }
+ if (!page)
+ return {
+ error: `Page "${args.page}" not found. Available: ${pages.map((p) => p.name).join(', ')}`
+ }
return {
page: { id: page.id, name: page.name, type: page.type },
@@ -173,8 +187,11 @@ export const findCommand: RpcCommand<FindArgs, FindNodeResult[]> = {
const matchesType = !typeFilter || node.type === typeFilter
if (matchesName && matchesType) {
results.push({
- id: node.id, name: node.name, type: node.type,
- width: Math.round(node.width), height: Math.round(node.height)
+ id: node.id,
+ name: node.name,
+ type: node.type,
+ width: Math.round(node.width),
+ height: Math.round(node.height)
})
}
return true
@@ -302,7 +319,11 @@ export const nodeCommand: RpcCommand<NodeArgs, NodeResult | { error: string }> =
fontFamily: node.fontFamily,
fontSize: node.fontSize,
fontWeight: node.fontWeight,
- text: node.text.length ? (node.text.length > 200 ? node.text.slice(0, 200) + '…' : node.text) : null,
+ text: (() => {
+ if (!node.text.length) return null
+ if (node.text.length > 200) return node.text.slice(0, 200) + '…'
+ return node.text
+ })(),
parent: parent ? { id: parent.id, name: parent.name, type: parent.type } : null,
children: node.childIds.length,
boundVariables: boundVars
@@ -364,7 +385,8 @@ export const variablesCommand: RpcCommand<VariablesArgs, VariablesResult> = {
for (const coll of graph.variableCollections.values()) {
if (collFilter && !coll.name.toLowerCase().includes(collFilter)) continue
- const collVars = graph.getVariablesForCollection(coll.id)
+ const collVars = graph
+ .getVariablesForCollection(coll.id)
.filter((v) => !typeFilter || v.type === typeFilter)
if (collVars.length === 0) continue
@@ -413,7 +435,11 @@ function clusterColors(colors: ColorInfo[], threshold: number): ColorCluster[] {
for (const color of sorted) {
if (used.has(color.hex)) continue
- const cluster: ColorCluster = { colors: [color], suggestedHex: color.hex, totalCount: color.count }
+ const cluster: ColorCluster = {
+ colors: [color],
+ suggestedHex: color.hex,
+ totalCount: color.count
+ }
used.add(color.hex)
for (const other of sorted) {
@@ -490,7 +516,12 @@ export const analyzeColorsCommand: RpcCommand<AnalyzeColorsArgs, AnalyzeColorsRe
name: 'analyze_colors',
execute: (graph, args) => {
const { colors, totalNodes } = collectColors(graph)
- const clusters = args.similar ? clusterColors(colors.filter((c) => !c.variableName), args.threshold ?? 15) : []
+ const clusters = args.similar
+ ? clusterColors(
+ colors.filter((c) => !c.variableName),
+ args.threshold ?? 15
+ )
+ : []
return { colors: colors.sort((a, b) => b.count - a.count), totalNodes, clusters }
}
}
@@ -512,27 +543,36 @@ export interface AnalyzeTypographyResult {
totalTextNodes: number
}
-export const analyzeTypographyCommand: RpcCommand<AnalyzeTypographyArgs, AnalyzeTypographyResult> = {
- name: 'analyze_typography',
- execute: (graph) => {
- const styleMap = new Map<string, TypographyStyle>()
- let totalTextNodes = 0
-
- for (const node of graph.getAllNodes()) {
- if (node.type !== 'TEXT') continue
- totalTextNodes++
-
- const lh = node.lineHeight === null ? 'auto' : `${node.lineHeight}px`
- const key = `${node.fontFamily}|${node.fontSize}|${node.fontWeight}|${lh}`
- const existing = styleMap.get(key)
- if (existing) { existing.count++ } else {
- styleMap.set(key, { family: node.fontFamily, size: node.fontSize, weight: node.fontWeight, lineHeight: lh, count: 1 })
+export const analyzeTypographyCommand: RpcCommand<AnalyzeTypographyArgs, AnalyzeTypographyResult> =
+ {
+ name: 'analyze_typography',
+ execute: (graph) => {
+ const styleMap = new Map<string, TypographyStyle>()
+ let totalTextNodes = 0
+
+ for (const node of graph.getAllNodes()) {
+ if (node.type !== 'TEXT') continue
+ totalTextNodes++
+
+ const lh = node.lineHeight === null ? 'auto' : `${node.lineHeight}px`
+ const key = `${node.fontFamily}|${node.fontSize}|${node.fontWeight}|${lh}`
+ const existing = styleMap.get(key)
+ if (existing) {
+ existing.count++
+ } else {
+ styleMap.set(key, {
+ family: node.fontFamily,
+ size: node.fontSize,
+ weight: node.fontWeight,
+ lineHeight: lh,
+ count: 1
+ })
+ }
}
- }
- return { styles: [...styleMap.values()].sort((a, b) => b.count - a.count), totalTextNodes }
+ return { styles: [...styleMap.values()].sort((a, b) => b.count - a.count), totalTextNodes }
+ }
}
-}
// ── analyze spacing ──
@@ -558,16 +598,25 @@ export const analyzeSpacingCommand: RpcCommand<void, AnalyzeSpacingResult> = {
if (node.type === 'CANVAS' || node.layoutMode === 'NONE') continue
totalNodes++
- if (node.itemSpacing > 0) gapMap.set(node.itemSpacing, (gapMap.get(node.itemSpacing) ?? 0) + 1)
- if (node.counterAxisSpacing > 0) gapMap.set(node.counterAxisSpacing, (gapMap.get(node.counterAxisSpacing) ?? 0) + 1)
-
- for (const pad of [node.paddingTop, node.paddingRight, node.paddingBottom, node.paddingLeft]) {
+ if (node.itemSpacing > 0)
+ gapMap.set(node.itemSpacing, (gapMap.get(node.itemSpacing) ?? 0) + 1)
+ if (node.counterAxisSpacing > 0)
+ gapMap.set(node.counterAxisSpacing, (gapMap.get(node.counterAxisSpacing) ?? 0) + 1)
+
+ for (const pad of [
+ node.paddingTop,
+ node.paddingRight,
+ node.paddingBottom,
+ node.paddingLeft
+ ]) {
if (pad > 0) paddingMap.set(pad, (paddingMap.get(pad) ?? 0) + 1)
}
}
const toValues = (map: Map<number, number>) =>
- [...map.entries()].map(([value, count]) => ({ value, count })).sort((a, b) => b.count - a.count)
+ [...map.entries()]
+ .map(([value, count]) => ({ value, count }))
+ .sort((a, b) => b.count - a.count)
return { gaps: toValues(gapMap), paddings: toValues(paddingMap), totalNodes }
}
@@ -605,7 +654,10 @@ function buildSignature(graph: SceneGraph, node: SceneNode): string {
if (!child) continue
childTypes.set(child.type, (childTypes.get(child.type) ?? 0) + 1)
}
- const childPart = [...childTypes.entries()].sort((a, b) => a[0].localeCompare(b[0])).map(([t, c]) => `${t}:${c}`).join(',')
+ const childPart = [...childTypes.entries()]
+ .sort((a, b) => a[0].localeCompare(b[0]))
+ .map(([t, c]) => `${t}:${c}`)
+ .join(',')
const w = Math.round(node.width / 10) * 10
const h = Math.round(node.height / 10) * 10
return `${node.type}:${w}x${h}|${childPart}`
@@ -629,8 +681,12 @@ export const analyzeClustersCommand: RpcCommand<AnalyzeClustersArgs, AnalyzeClus
const sig = buildSignature(graph, node)
const arr = sigMap.get(sig) ?? []
arr.push({
- id: node.id, name: node.name, type: node.type,
- width: Math.round(node.width), height: Math.round(node.height), childCount: node.childIds.length
+ id: node.id,
+ name: node.name,
+ type: node.type,
+ width: Math.round(node.width),
+ height: Math.round(node.height),
+ childCount: node.childIds.length
})
sigMap.set(sig, arr)
}
diff --git a/packages/core/src/svg-export/index.ts b/packages/core/src/svg-export/index.ts
index bfce18a32..e3cca26f7 100644
--- a/packages/core/src/svg-export/index.ts
+++ b/packages/core/src/svg-export/index.ts
@@ -1,13 +1,4 @@
import { computeContentBounds } from '../render-image'
-import {
- round,
- geometryBlobToSVGPath,
- vectorNetworkToSVGPaths,
- makePolygonPoints,
- hasRadius,
- roundedRectPath,
- arcPath
-} from './paths'
import {
nextDefId,
formatColor,
@@ -17,13 +8,22 @@ import {
SVG_STROKE_JOIN,
SVG_BLEND_MODE
} from './defs'
+import {
+ round,
+ geometryBlobToSVGPath,
+ vectorNetworkToSVGPaths,
+ makePolygonPoints,
+ hasRadius,
+ roundedRectPath,
+ arcPath
+} from './paths'
export { geometryBlobToSVGPath, vectorNetworkToSVGPaths } from './paths'
import { svg, renderSVGNode } from '../svg-node'
-import type { SVGNode } from '../svg-node'
import type { SceneGraph, SceneNode, Fill, Stroke, CharacterStyleOverride } from '../scene-graph'
+import type { SVGNode } from '../svg-node'
import type { SVGExportContext } from './defs'
// --- Node rendering ---
@@ -138,7 +138,9 @@ function nodeShapeElements(
}
}
-function styleOverrideToTspanAttrs(style: CharacterStyleOverride): Record<string, string | number | undefined> {
+function styleOverrideToTspanAttrs(
+ style: CharacterStyleOverride
+): Record<string, string | number | undefined> {
const attrs: Record<string, string | number | undefined> = {}
if (style.fontFamily) attrs['font-family'] = style.fontFamily
if (style.fontSize) attrs['font-size'] = style.fontSize
@@ -157,33 +159,28 @@ function styleOverrideToTspanAttrs(style: CharacterStyleOverride): Record<string
}
function renderTextNode(node: SceneNode, fillAttr: string | null): SVGNode {
+ let textAnchor: 'middle' | 'end' | undefined
+ if (node.textAlignHorizontal === 'CENTER') textAnchor = 'middle'
+ else if (node.textAlignHorizontal === 'RIGHT') textAnchor = 'end'
+
+ let textDecoration: 'underline' | 'line-through' | undefined
+ if (node.textDecoration === 'UNDERLINE') textDecoration = 'underline'
+ else if (node.textDecoration === 'STRIKETHROUGH') textDecoration = 'line-through'
+
const attrs: Record<string, string | number | undefined> = {
'font-family': node.fontFamily || undefined,
'font-size': node.fontSize || undefined,
'font-weight': node.fontWeight !== 400 ? node.fontWeight : undefined,
'font-style': node.italic ? 'italic' : undefined,
fill: fillAttr ?? undefined,
- 'text-anchor':
- node.textAlignHorizontal === 'CENTER'
- ? 'middle'
- : (node.textAlignHorizontal === 'RIGHT'
- ? 'end'
- : undefined),
- 'text-decoration':
- node.textDecoration === 'UNDERLINE'
- ? 'underline'
- : (node.textDecoration === 'STRIKETHROUGH'
- ? 'line-through'
- : undefined),
+ 'text-anchor': textAnchor,
+ 'text-decoration': textDecoration,
'letter-spacing': node.letterSpacing ? round(node.letterSpacing) : undefined
}
- const x =
- node.textAlignHorizontal === 'CENTER'
- ? round(node.width / 2)
- : (node.textAlignHorizontal === 'RIGHT'
- ? round(node.width)
- : 0)
+ let x = 0
+ if (node.textAlignHorizontal === 'CENTER') x = round(node.width / 2)
+ else if (node.textAlignHorizontal === 'RIGHT') x = round(node.width)
const y = node.fontSize || 14
if (node.styleRuns.length > 0) {
@@ -258,7 +255,9 @@ function buildGroupAttrs(
return { attrs, clipId }
}
-function buildSVGStrokeAttrs(visibleStrokes: Stroke[]): Record<string, string | number | undefined> {
+function buildSVGStrokeAttrs(
+ visibleStrokes: Stroke[]
+): Record<string, string | number | undefined> {
if (visibleStrokes.length === 0) return {}
const stroke = visibleStrokes[0]
const attrs: Record<string, string | number | undefined> = {
@@ -329,7 +328,12 @@ function renderNode(node: SceneNode, ctx: SVGExportContext): SVGNode | null {
const strokeAttrs = buildSVGStrokeAttrs(visibleStrokes)
const children: (SVGNode | null)[] = buildShapeChildren(
- node, visibleFills, fillAttr, strokeAttrs, visibleStrokes.length, ctx
+ node,
+ visibleFills,
+ fillAttr,
+ strokeAttrs,
+ visibleStrokes.length,
+ ctx
)
const childNodes = ctx.graph.getChildren(node.id)
@@ -399,9 +403,7 @@ export function renderNodesToSVG(
const offsetY = abs.y - minY
const needsOffset = offsetX !== node.x || offsetY !== node.y
- const clone = needsOffset
- ? { ...node, x: round(offsetX), y: round(offsetY) }
- : node
+ const clone = needsOffset ? { ...node, x: round(offsetX), y: round(offsetY) } : node
const rendered = renderNode(clone, ctx)
if (rendered) contentNodes.push(rendered)
diff --git a/packages/core/src/tools/modify.ts b/packages/core/src/tools/modify.ts
index fbb29b307..d8ac8374e 100644
--- a/packages/core/src/tools/modify.ts
+++ b/packages/core/src/tools/modify.ts
@@ -1,18 +1,23 @@
/* eslint-disable max-lines -- property setters share common patterns, splitting would scatter related tools */
import { parseColor } from '../color'
import { DEFAULT_SHADOW_COLOR } from '../constants'
+import { defineTool } from './schema'
+
import type { CharacterStyleOverride, Effect, StyleRun } from '../scene-graph'
import type { Matrix } from '../types'
-import { defineTool } from './schema'
-
export const setFill = defineTool({
name: 'set_fill',
mutates: true,
- description: 'Set fill on a node. Solid: color="#ff0000". Linear gradient: gradient="top-bottom" or "left-right" with color (start) and color_end (end).',
+ description:
+ 'Set fill on a node. Solid: color="#ff0000". Linear gradient: gradient="top-bottom" or "left-right" with color (start) and color_end (end).',
params: {
id: { type: 'string', description: 'Node ID', required: true },
- color: { type: 'color', description: 'Color (hex). For gradient: start color.', required: true },
+ color: {
+ type: 'color',
+ description: 'Color (hex). For gradient: start color.',
+ required: true
+ },
color_end: { type: 'color', description: 'End color for gradient (if omitted, solid fill)' },
gradient: {
type: 'string',
@@ -34,17 +39,19 @@ export const setFill = defineTool({
'left-right': { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 },
'right-left': { m00: -1, m01: 0, m02: 1, m10: 0, m11: -1, m12: 1 }
}
- node.fills = [{
- type: 'GRADIENT_LINEAR',
- color: c,
- opacity: 1,
- visible: true,
- gradientStops: [
- { position: 0, color: c },
- { position: 1, color: cEnd }
- ],
- gradientTransform: transforms[gradient] ?? transforms['top-bottom']
- }]
+ node.fills = [
+ {
+ type: 'GRADIENT_LINEAR',
+ color: c,
+ opacity: 1,
+ visible: true,
+ gradientStops: [
+ { position: 0, color: c },
+ { position: 1, color: cEnd }
+ ],
+ gradientTransform: transforms[gradient] ?? transforms['top-bottom']
+ }
+ ]
return { id, gradient, start: c, end: cEnd }
}
@@ -110,9 +117,9 @@ export const setEffects = defineTool({
if (!node) return { error: `Node "${args.id}" not found` }
const isBlur = args.type === 'FOREGROUND_BLUR' || args.type === 'BACKGROUND_BLUR'
- const color = isBlur
- ? { r: 0, g: 0, b: 0, a: 0 }
- : (args.color ? parseColor(args.color) : { ...DEFAULT_SHADOW_COLOR })
+ let color = { ...DEFAULT_SHADOW_COLOR }
+ if (isBlur) color = { r: 0, g: 0, b: 0, a: 0 }
+ else if (args.color) color = parseColor(args.color)
const effect: Effect = {
type: args.type as Effect['type'],
visible: true,
@@ -205,8 +212,16 @@ export const setLayout = defineTool({
description: 'Layout direction (keeps current if omitted)',
enum: ['HORIZONTAL', 'VERTICAL']
},
- spacing: { type: 'number', description: 'Gap between items (only changes if provided)', min: 0 },
- padding: { type: 'number', description: 'Equal padding on all sides (only changes if provided)', min: 0 },
+ spacing: {
+ type: 'number',
+ description: 'Gap between items (only changes if provided)',
+ min: 0
+ },
+ padding: {
+ type: 'number',
+ description: 'Equal padding on all sides (only changes if provided)',
+ min: 0
+ },
padding_horizontal: { type: 'number', description: 'Horizontal padding', min: 0 },
padding_vertical: { type: 'number', description: 'Vertical padding', min: 0 },
align: {
@@ -226,7 +241,9 @@ export const setLayout = defineTool({
const raw = figma.graph.getNode(args.id)
if (!args.direction && raw?.layoutMode === 'NONE') {
- return { error: 'Frame has no auto-layout. Pass direction ("HORIZONTAL" or "VERTICAL") to enable it.' }
+ return {
+ error: 'Frame has no auto-layout. Pass direction ("HORIZONTAL" or "VERTICAL") to enable it.'
+ }
}
const wasNone = raw?.layoutMode === 'NONE'
@@ -685,7 +702,11 @@ export const setImageFill = defineTool({
description: 'Set an image fill on a node from base64-encoded image data.',
params: {
id: { type: 'string', description: 'Node ID', required: true },
- image_data: { type: 'string', description: 'Base64-encoded image bytes (PNG, JPEG, or WEBP)', required: true },
+ image_data: {
+ type: 'string',
+ description: 'Base64-encoded image bytes (PNG, JPEG, or WEBP)',
+ required: true
+ },
scale_mode: {
type: 'string',
description: 'Image scale mode',
@@ -699,14 +720,16 @@ export const setImageFill = defineTool({
const bytes = Uint8Array.fromBase64(image_data)
const image = figma.createImage(bytes)
const mode = (scale_mode ?? 'FILL') as 'FILL' | 'FIT' | 'CROP' | 'TILE'
- node.fills = [{
- type: 'IMAGE',
- color: { r: 0, g: 0, b: 0, a: 1 },
- opacity: 1,
- visible: true,
- imageHash: image.hash,
- imageScaleMode: mode
- }]
+ node.fills = [
+ {
+ type: 'IMAGE',
+ color: { r: 0, g: 0, b: 0, a: 1 },
+ opacity: 1,
+ visible: true,
+ imageHash: image.hash,
+ imageScaleMode: mode
+ }
+ ]
return { id, imageHash: image.hash, scaleMode: mode }
}
})
diff --git a/packages/vue/src/LayerTree/LayerTreeItem.vue b/packages/vue/src/LayerTree/LayerTreeItem.vue
index 26f972fb5..e3321d83c 100644
--- a/packages/vue/src/LayerTree/LayerTreeItem.vue
+++ b/packages/vue/src/LayerTree/LayerTreeItem.vue
@@ -11,6 +11,14 @@ const { node, level, hasChildren } = defineProps<{
hasChildren: boolean
}>()
+const emit = defineEmits<{
+ select: [id: string, additive: boolean]
+ toggleExpand: [id: string]
+ toggleVisibility: [id: string]
+ toggleLock: [id: string]
+ rename: [id: string, name: string]
+}>()
+
const ctx = useLayerTree()
const isSelected = computed(() => ctx.selectedIds.value.has(node.id))
@@ -37,11 +45,11 @@ defineExpose({ rowEl })
:is-selected="isSelected"
:is-dragging="isDragging"
:pad-left="padLeft"
- :select="(additive: boolean) => ctx.select(node.id, additive)"
- :toggle-expand="() => ctx.toggleExpand(node.id)"
- :toggle-visibility="() => ctx.toggleVisibility(node.id)"
- :toggle-lock="() => ctx.toggleLock(node.id)"
- :rename="(name: string) => ctx.rename(node.id, name)"
+ :select="(additive: boolean) => { emit('select', node.id, additive); ctx.select(node.id, additive) }"
+ :toggle-expand="() => { emit('toggleExpand', node.id); ctx.toggleExpand(node.id) }"
+ :toggle-visibility="() => { emit('toggleVisibility', node.id); ctx.toggleVisibility(node.id) }"
+ :toggle-lock="() => { emit('toggleLock', node.id); ctx.toggleLock(node.id) }"
+ :rename="(name: string) => { emit('rename', node.id, name); ctx.rename(node.id, name) }"
/>
</div>
</template>
diff --git a/packages/vue/src/LayerTree/LayerTreeRoot.vue b/packages/vue/src/LayerTree/LayerTreeRoot.vue
index a4e3edc7e..5aa4217e3 100644
--- a/packages/vue/src/LayerTree/LayerTreeRoot.vue
+++ b/packages/vue/src/LayerTree/LayerTreeRoot.vue
@@ -10,6 +10,14 @@ const { indentPerLevel = 16 } = defineProps<{
indentPerLevel?: number
}>()
+const emit = defineEmits<{
+ select: [id: string, additive: boolean]
+ toggleExpand: [id: string]
+ toggleVisibility: [id: string]
+ toggleLock: [id: string]
+ rename: [id: string, name: string]
+}>()
+
const editor = useEditor()
function buildTree(parentId: string): LayerNode[] {
@@ -81,6 +89,7 @@ function syncCanvasScope(nodeId: string) {
}
function select(id: string, additive: boolean) {
+ emit('select', id, additive)
if (additive) {
editor.select([id], true)
} else {
@@ -90,6 +99,7 @@ function select(id: string, additive: boolean) {
}
function toggleExpand(id: string) {
+ emit('toggleExpand', id)
const idx = expanded.value.indexOf(id)
if (idx !== -1) expanded.value = expanded.value.filter((e) => e !== id)
else expanded.value = [...expanded.value, id]
@@ -104,9 +114,18 @@ provideLayerTree({
indentPerLevel,
select,
toggleExpand,
- toggleVisibility: (id: string) => editor.toggleNodeVisibility(id),
- toggleLock: (id: string) => editor.toggleNodeLock(id),
- rename: (id: string, name: string) => editor.renameNode(id, name),
+ toggleVisibility: (id: string) => {
+ emit('toggleVisibility', id)
+ editor.toggleNodeVisibility(id)
+ },
+ toggleLock: (id: string) => {
+ emit('toggleLock', id)
+ editor.toggleNodeLock(id)
+ },
+ rename: (id: string, name: string) => {
+ emit('rename', id, name)
+ editor.renameNode(id, name)
+ },
setRowRef
})
</script>
diff --git a/packages/vue/src/PropertyList/PropertyListItem.vue b/packages/vue/src/PropertyList/PropertyListItem.vue
index 14234e822..60295ed1f 100644
--- a/packages/vue/src/PropertyList/PropertyListItem.vue
+++ b/packages/vue/src/PropertyList/PropertyListItem.vue
@@ -5,15 +5,22 @@ const { index } = defineProps<{
index: number
}>()
+const emit = defineEmits<{
+ update: [index: number, item: unknown]
+ patch: [index: number, changes: Record<string, unknown>]
+ remove: [index: number]
+ toggleVisibility: [index: number]
+}>()
+
const { update, patch, remove, toggleVisibility } = usePropertyList()
</script>
<template>
<slot
:index="index"
- :update="(item: unknown) => update(index, item)"
- :patch="(changes: Record<string, unknown>) => patch(index, changes)"
- :remove="() => remove(index)"
- :toggle-visibility="() => toggleVisibility(index)"
+ :update="(item: unknown) => { emit('update', index, item); update(index, item) }"
+ :patch="(changes: Record<string, unknown>) => { emit('patch', index, changes); patch(index, changes) }"
+ :remove="() => { emit('remove', index); remove(index) }"
+ :toggle-visibility="() => { emit('toggleVisibility', index); toggleVisibility(index) }"
/>
</template>
diff --git a/packages/vue/src/PropertyList/PropertyListRoot.vue b/packages/vue/src/PropertyList/PropertyListRoot.vue
index feaf110f3..34f8735ba 100644
--- a/packages/vue/src/PropertyList/PropertyListRoot.vue
+++ b/packages/vue/src/PropertyList/PropertyListRoot.vue
@@ -14,6 +14,14 @@ const { propKey } = defineProps<{
label?: string
}>()
+const emit = defineEmits<{
+ add: [item: ArrayItemType]
+ remove: [index: number]
+ update: [index: number, item: ArrayItemType]
+ patch: [index: number, changes: Record<string, unknown>]
+ toggleVisibility: [index: number]
+}>()
+
const editor = useEditor()
const selectedNodes = computed(() => editor.getSelectedNodes())
@@ -44,6 +52,7 @@ function targetNodes(): SceneNode[] {
}
function add(defaults: ArrayItemType) {
+ emit('add', defaults)
for (const n of targetNodes()) {
const arr = isMulti.value ? [defaults] : [...n[propKey], defaults]
editor.updateNodeWithUndo(n.id, { [propKey]: arr } as Partial<SceneNode>, isMulti.value ? `Set ${propKey}` : `Add ${propKey}`)
@@ -51,6 +60,7 @@ function add(defaults: ArrayItemType) {
}
function remove(index: number) {
+ emit('remove', index)
for (const n of targetNodes()) {
editor.updateNodeWithUndo(
n.id,
@@ -61,6 +71,7 @@ function remove(index: number) {
}
function update(index: number, item: ArrayItemType) {
+ emit('update', index, item)
for (const n of targetNodes()) {
const arr = [...n[propKey]] as ArrayItemType[]
arr[index] = item
@@ -69,6 +80,7 @@ function update(index: number, item: ArrayItemType) {
}
function patch(index: number, changes: Record<string, unknown>) {
+ emit('patch', index, changes)
for (const n of targetNodes()) {
const arr = [...n[propKey]] as ArrayItemType[]
arr[index] = { ...arr[index], ...changes } as ArrayItemType
@@ -77,6 +89,7 @@ function patch(index: number, changes: Record<string, unknown>) {
}
function toggleVisibility(index: number) {
+ emit('toggleVisibility', index)
for (const n of targetNodes()) {
const arr = n[propKey] as Array<{ visible: boolean }>
if (!arr[index]) continue
diff --git a/packages/vue/src/index.ts b/packages/vue/src/index.ts
index 6c5791432..6d454c9a2 100644
--- a/packages/vue/src/index.ts
+++ b/packages/vue/src/index.ts
@@ -20,6 +20,7 @@ export type { MenuEntry } from './commands/useMenuModel'
export { useViewportKind } from './viewport/useViewportKind'
export { useLayerDrag } from './shared/useLayerDrag'
export { useInlineRename } from './shared/useInlineRename'
+export { useToolbarState } from './shared/useToolbarState'
export { useNodeFontStatus } from './shared/useFontStatus'
export { usePropScrub } from './shared/usePropScrub'
export { toolCursor } from './shared/toolCursor'
@@ -30,9 +31,12 @@ export { useTypography } from './shared/useTypography'
export type { UseTypographyOptions } from './shared/useTypography'
export { useExport } from './shared/useExport'
export { useVariables } from './shared/useVariables'
+export { useVariablesDialogState } from './shared/useVariablesDialogState'
+export { useVariablesTable } from './shared/useVariablesTable'
export { useFillPicker } from './shared/useFillPicker'
export { useGradientStops } from './shared/useGradientStops'
export { usePageList } from './shared/usePageList'
+export { useFontPicker } from './shared/useFontPicker'
export * from './Canvas'
export * from './GradientEditor'
diff --git a/packages/vue/src/shared/useFontPicker.ts b/packages/vue/src/shared/useFontPicker.ts
new file mode 100644
index 000000000..065a20e02
--- /dev/null
+++ b/packages/vue/src/shared/useFontPicker.ts
@@ -0,0 +1,42 @@
+import { computed, onMounted, ref, watch } from 'vue'
+import { useFilter } from 'reka-ui'
+
+export interface UseFontPickerOptions {
+ modelValue: { value: string }
+ listFamilies: () => Promise<string[]>
+ onSelect?: (family: string) => void
+}
+
+export function useFontPicker(options: UseFontPickerOptions) {
+ const families = ref<string[]>([])
+ const searchTerm = ref('')
+ const open = ref(false)
+
+ const { contains } = useFilter({ sensitivity: 'base' })
+ const filtered = computed(() => {
+ if (!searchTerm.value) return families.value
+ return families.value.filter((family) => contains(family, searchTerm.value))
+ })
+
+ onMounted(async () => {
+ families.value = await options.listFamilies()
+ })
+
+ watch(open, (isOpen) => {
+ if (isOpen) searchTerm.value = ''
+ })
+
+ function select(family: string) {
+ options.modelValue.value = family
+ options.onSelect?.(family)
+ open.value = false
+ }
+
+ return {
+ families,
+ searchTerm,
+ open,
+ filtered,
+ select
+ }
+}
diff --git a/packages/vue/src/shared/useToolbarState.ts b/packages/vue/src/shared/useToolbarState.ts
new file mode 100644
index 000000000..f5aa4a402
--- /dev/null
+++ b/packages/vue/src/shared/useToolbarState.ts
@@ -0,0 +1,46 @@
+import { computed, ref } from 'vue'
+
+import type { Tool, EditorToolDef } from '@open-pencil/core/editor'
+
+const CATEGORY_COUNT = 3
+
+export function useToolbarState() {
+ const mobileCategory = ref(0)
+ const slideDirection = ref(1)
+
+ const hasPrev = computed(() => mobileCategory.value > 0)
+ const hasNext = computed(() => mobileCategory.value < CATEGORY_COUNT - 1)
+
+ function isActive(tool: EditorToolDef, activeTool: Tool): boolean {
+ if (tool.key === activeTool) return true
+ return tool.flyout?.includes(activeTool) ?? false
+ }
+
+ function activeKeyForTool(tool: EditorToolDef, activeTool: Tool): Tool {
+ if (tool.flyout?.includes(activeTool)) return activeTool
+ return tool.key
+ }
+
+ function goPrev() {
+ if (!hasPrev.value) return
+ slideDirection.value = -1
+ mobileCategory.value--
+ }
+
+ function goNext() {
+ if (!hasNext.value) return
+ slideDirection.value = 1
+ mobileCategory.value++
+ }
+
+ return {
+ mobileCategory,
+ slideDirection,
+ hasPrev,
+ hasNext,
+ isActive,
+ activeKeyForTool,
+ goPrev,
+ goNext
+ }
+}
diff --git a/packages/vue/src/shared/useVariablesDialogState.ts b/packages/vue/src/shared/useVariablesDialogState.ts
new file mode 100644
index 000000000..ee8662056
--- /dev/null
+++ b/packages/vue/src/shared/useVariablesDialogState.ts
@@ -0,0 +1,47 @@
+import { nextTick, ref } from 'vue'
+
+import { useVariables } from './useVariables'
+
+export function useVariablesDialogState() {
+ const variables = useVariables()
+
+ const editingCollectionId = ref<string | null>(null)
+ const collectionInputRefs = new Map<string, HTMLInputElement>()
+ const pendingCollectionFocusId = ref<string | null>(null)
+
+ function setCollectionInputRef(id: string, el: HTMLInputElement | null) {
+ if (el) collectionInputRefs.set(id, el)
+ else collectionInputRefs.delete(id)
+
+ if (el && pendingCollectionFocusId.value === id) {
+ pendingCollectionFocusId.value = null
+ void nextTick(() => {
+ el.focus()
+ el.select()
+ })
+ }
+ }
+
+ function startRenameCollection(id: string) {
+ editingCollectionId.value = id
+ pendingCollectionFocusId.value = id
+ }
+
+ function commitRenameCollection(id: string, input: HTMLInputElement) {
+ if (editingCollectionId.value !== id) return
+ const value = input.value.trim()
+ const col = variables.collections.value.find((collection) => collection.id === id)
+ if (col && value && value !== col.name) {
+ variables.renameCollection(id, value)
+ }
+ editingCollectionId.value = null
+ }
+
+ return {
+ ...variables,
+ editingCollectionId,
+ setCollectionInputRef,
+ startRenameCollection,
+ commitRenameCollection
+ }
+}
diff --git a/packages/vue/src/shared/useVariablesTable.ts b/packages/vue/src/shared/useVariablesTable.ts
new file mode 100644
index 000000000..c6d9889a7
--- /dev/null
+++ b/packages/vue/src/shared/useVariablesTable.ts
@@ -0,0 +1,138 @@
+import { computed, h, type Component } from 'vue'
+import { EditableArea, EditableInput, EditablePreview, EditableRoot } from 'reka-ui'
+import type { ColumnDef } from '@tanstack/vue-table'
+
+import type { Color, Variable, VariableValue } from '@open-pencil/core'
+
+import type { ComputedRef } from 'vue'
+
+interface VariablesTableOptions {
+ activeModes: ComputedRef<{ modeId: string; name: string }[]>
+ formatModeValue: (variable: Variable, modeId: string) => string
+ parseVariableValue: (variable: Variable, raw: string) => VariableValue | undefined
+ shortName: (variable: Variable) => string
+ renameVariable: (id: string, newName: string) => void
+ updateVariableValue: (id: string, modeId: string, value: VariableValue) => void
+ removeVariable: (id: string) => void
+ ColorInput: Component
+ icons: Record<string, Component>
+ fallbackIcon: Component
+ deleteIcon: Component
+}
+
+export function useVariablesTable(options: VariablesTableOptions) {
+ function commitNameEdit(variable: Variable, newName: string) {
+ if (newName && newName !== variable.name) {
+ options.renameVariable(variable.id, newName)
+ }
+ }
+
+ function commitValueEdit(variable: Variable, modeId: string, newValue: string) {
+ const parsed = options.parseVariableValue(variable, newValue)
+ if (parsed !== undefined) {
+ options.updateVariableValue(variable.id, modeId, parsed)
+ }
+ }
+
+ const columns = computed<ColumnDef<Variable>[]>(() => {
+ const nameCol: ColumnDef<Variable> = {
+ id: 'name',
+ header: 'Name',
+ size: 200,
+ minSize: 120,
+ maxSize: 400,
+ cell: ({ row }) => {
+ const variable = row.original
+ const iconClass = 'size-3.5 shrink-0 text-muted'
+ const iconComponent = options.icons[variable.type] ?? options.fallbackIcon
+ const icon = h(iconComponent, { class: iconClass })
+
+ return h('div', { class: 'flex items-center gap-2' }, [
+ icon,
+ h(
+ EditableRoot,
+ {
+ defaultValue: options.shortName(variable),
+ class: 'min-w-0 flex-1',
+ onSubmit: (value: string | null | undefined) => value && commitNameEdit(variable, value)
+ },
+ () =>
+ h(EditableArea, { class: 'flex' }, () => [
+ h(EditablePreview, {
+ class: 'min-w-0 flex-1 cursor-text truncate text-xs text-surface'
+ }),
+ h(EditableInput, {
+ class:
+ 'min-w-0 flex-1 rounded border border-border bg-surface/10 px-1 py-0.5 text-xs text-surface outline-none'
+ })
+ ])
+ )
+ ])
+ }
+ }
+
+ const modeCols: ColumnDef<Variable>[] = options.activeModes.value.map((mode) => ({
+ id: `mode-${mode.modeId}`,
+ header: mode.name,
+ size: 200,
+ minSize: 120,
+ maxSize: 500,
+ cell: ({ row }) => {
+ const variable = row.original
+ const value = variable.valuesByMode[mode.modeId]
+
+ if (variable.type === 'COLOR' && value && typeof value === 'object' && 'r' in value) {
+ return h(options.ColorInput, {
+ color: value as Color,
+ onUpdate: (color: Color) => options.updateVariableValue(variable.id, mode.modeId, color)
+ })
+ }
+
+ return h(
+ EditableRoot,
+ {
+ defaultValue: options.formatModeValue(variable, mode.modeId),
+ class: 'min-w-0 flex-1',
+ onSubmit: (value: string | null | undefined) =>
+ value && commitValueEdit(variable, mode.modeId, value)
+ },
+ () =>
+ h(EditableArea, { class: 'flex' }, () => [
+ h(EditablePreview, {
+ class: 'min-w-0 flex-1 cursor-text truncate font-mono text-xs text-muted'
+ }),
+ h(EditableInput, {
+ class:
+ 'min-w-0 flex-1 rounded border border-border bg-surface/10 px-1 py-0.5 font-mono text-xs text-surface outline-none'
+ })
+ ])
+ )
+ }
+ }))
+
+ const deleteCol: ColumnDef<Variable> = {
+ id: 'actions',
+ header: '',
+ size: 36,
+ minSize: 36,
+ maxSize: 36,
+ enableResizing: false,
+ cell: ({ row }) =>
+ h(
+ 'button',
+ {
+ class:
+ 'flex size-5 cursor-pointer items-center justify-center rounded border-none bg-transparent text-muted opacity-0 transition-opacity group-hover:opacity-100 hover:text-surface',
+ onClick: () => options.removeVariable(row.original.id)
+ },
+ h(options.deleteIcon, { class: 'size-3' })
+ )
+ }
+
+ return [nameCol, ...modeCols, deleteCol]
+ })
+
+ return {
+ columns
+ }
+}
diff --git a/src/components/AppMenu.vue b/src/components/AppMenu.vue
index ba6401008..8ab8fa489 100644
--- a/src/components/AppMenu.vue
+++ b/src/components/AppMenu.vue
@@ -18,15 +18,13 @@ import IconChevronRight from '~icons/lucide/chevron-right'
import { computed } from 'vue'
-import { useEditorCommands, useInlineRename, useMenuModel } from '@open-pencil/vue'
-import { menuContent, menuItem, menuSeparator } from '@/components/ui/menu'
+import { useInlineRename } from '@open-pencil/vue'
+import { useMenuUI } from '@/components/ui/menu'
import { IS_TAURI } from '@/constants'
-import { openFileDialog } from '@/composables/use-menu'
+import { useAppMenu } from '@/composables/use-app-menu'
import { useEditorStore } from '@/stores/editor'
const store = useEditorStore()
-const { menuItem: commandMenuItem } = useEditorCommands()
-const { appMenu } = useMenuModel()
const DOCUMENT_NAME_ID = 'document-name'
const rename = useInlineRename<'document-name'>((_id, name) => {
@@ -66,132 +64,10 @@ interface MenuSeparator {
type MenuEntry = MenuAction | MenuSeparator
-const fileMenu: MenuEntry[] = [
- {
- label: 'New',
- shortcut: `${mod}N`,
- action: () => import('@/stores/tabs').then((m) => m.createTab())
- },
- { label: 'Open…', shortcut: `${mod}O`, action: () => openFileDialog() },
- { separator: true },
- { label: 'Save', shortcut: `${mod}S`, action: () => store.saveFigFile() },
- { label: 'Save as…', shortcut: `${mod}⇧S`, action: () => store.saveFigFileAs() },
- { separator: true },
- {
- label: 'Export selection…',
- shortcut: `${mod}⇧E`,
- action: () => {
- if (store.state.selectedIds.size > 0) store.exportSelection(1, 'PNG')
- },
- disabled: store.state.selectedIds.size === 0
- },
- { separator: true },
- {
- label: 'Auto-save to local file',
- get checked() {
- return store.state.autosaveEnabled
- },
- onCheckedChange: (v: boolean) => {
- store.state.autosaveEnabled = v
- }
- }
-]
-
-const textMenu: MenuEntry[] = [
- { label: 'Bold', shortcut: `${mod}B` },
- { label: 'Italic', shortcut: `${mod}I` },
- { label: 'Underline', shortcut: `${mod}U` }
-]
-
-const topMenus = [
- { label: 'File', items: fileMenu },
- ...appMenu.value.map((menu) => {
- if (menu.label === 'View') {
- return {
- label: 'View',
- items: [
- commandMenuItem('view.zoom100', `${mod}0`),
- commandMenuItem('view.zoomFit', `${mod}1`),
- commandMenuItem('view.zoomSelection', `${mod}2`),
- {
- label: 'Zoom in',
- shortcut: `${mod}=`,
- action: () => store.applyZoom(-100, window.innerWidth / 2, window.innerHeight / 2)
- },
- {
- label: 'Zoom out',
- shortcut: `${mod}-`,
- action: () => store.applyZoom(100, window.innerWidth / 2, window.innerHeight / 2)
- },
- { separator: true },
- {
- label: 'Performance profiler',
- get checked() {
- return store.renderer?.profiler.hudVisible ?? false
- },
- onCheckedChange: () => {
- store.toggleProfiler()
- }
- }
- ]
- }
- }
-
- if (menu.label === 'Edit') {
- return {
- label: 'Edit',
- items: [
- commandMenuItem('edit.undo', `${mod}Z`),
- commandMenuItem('edit.redo', `${mod}⇧Z`),
- { separator: true },
- { label: 'Copy', shortcut: `${mod}C` },
- { label: 'Paste', shortcut: `${mod}V` },
- commandMenuItem('selection.duplicate', `${mod}D`),
- commandMenuItem('selection.delete', '⌫'),
- { separator: true },
- commandMenuItem('selection.selectAll', `${mod}A`)
- ]
- }
- }
-
- if (menu.label === 'Object') {
- return {
- label: 'Object',
- items: [
- commandMenuItem('selection.group', `${mod}G`),
- commandMenuItem('selection.ungroup', `${mod}⇧G`),
- { separator: true },
- commandMenuItem('selection.createComponent', `${mod}⌥K`),
- commandMenuItem('selection.createComponentSet'),
- commandMenuItem('selection.detachInstance'),
- { separator: true },
- commandMenuItem('selection.bringToFront', ']'),
- commandMenuItem('selection.sendToBack', '[')
- ]
- }
- }
-
- if (menu.label === 'Arrange') {
- return {
- label: 'Arrange',
- items: [
- commandMenuItem('selection.wrapInAutoLayout', '⇧A'),
- { separator: true },
- { label: 'Align left', shortcut: '⌥A' },
- { label: 'Align center', shortcut: '⌥H' },
- { label: 'Align right', shortcut: '⌥D' },
- { separator: true },
- { label: 'Align top', shortcut: '⌥W' },
- { label: 'Align middle', shortcut: '⌥V' },
- { label: 'Align bottom', shortcut: '⌥S' }
- ]
- }
- }
-
- return menu
- }),
- { label: 'Text', items: textMenu }
-]
+const { topMenus } = useAppMenu(mod)
+const menuCls = useMenuUI()
+const mainMenuCls = useMenuUI({ content: 'min-w-52' })
+const subMenuCls = useMenuUI({ content: 'min-w-44' })
</script>
<template>
@@ -236,32 +112,39 @@ const topMenus = [
</MenubarTrigger>
<MenubarPortal>
- <MenubarContent
- :side-offset="4"
- align="start"
- :class="menuContent({ class: 'min-w-52' })"
- >
+ <MenubarContent :side-offset="4" align="start" :class="mainMenuCls.content">
<template v-for="(item, i) in menu.items" :key="i">
- <MenubarSeparator v-if="'separator' in item && item.separator" :class="menuSeparator()" />
+ <MenubarSeparator
+ v-if="'separator' in item && item.separator"
+ :class="menuCls.separator"
+ />
<MenubarSub v-else-if="'sub' in item && item.sub">
- <MenubarSubTrigger :class="menuItem()">
+ <MenubarSubTrigger :class="menuCls.item">
<span class="flex-1">{{ 'label' in item ? item.label : '' }}</span>
<IconChevronRight class="size-3 text-muted" />
</MenubarSubTrigger>
<MenubarPortal>
- <MenubarSubContent :side-offset="4" :class="menuContent({ class: 'min-w-44' })">
- <template v-for="(sub, j) in ('sub' in item && item.sub ? item.sub : [])" :key="j">
- <MenubarSeparator v-if="'separator' in sub && sub.separator" :class="menuSeparator()" />
+ <MenubarSubContent :side-offset="4" :class="subMenuCls.content">
+ <template
+ v-for="(sub, j) in 'sub' in item && item.sub ? item.sub : []"
+ :key="j"
+ >
+ <MenubarSeparator
+ v-if="'separator' in sub && sub.separator"
+ :class="menuCls.separator"
+ />
<MenubarItem
v-else
- :class="menuItem()"
+ :class="menuCls.item"
:disabled="'disabled' in sub ? sub.disabled : undefined"
@select="'action' in sub ? sub.action?.() : undefined"
>
<span class="flex-1">{{ 'label' in sub ? sub.label : '' }}</span>
- <span v-if="'shortcut' in sub && sub.shortcut" class="text-[11px] text-muted">{{
- sub.shortcut
- }}</span>
+ <span
+ v-if="'shortcut' in sub && sub.shortcut"
+ class="text-[11px] text-muted"
+ >{{ sub.shortcut }}</span
+ >
</MenubarItem>
</template>
</MenubarSubContent>
@@ -270,7 +153,7 @@ const topMenus = [
<MenubarCheckboxItem
v-else-if="'onCheckedChange' in item && item.onCheckedChange"
:model-value="'checked' in item ? item.checked : undefined"
- :class="menuItem()"
+ :class="menuCls.item"
@update:model-value="item.onCheckedChange?.($event as boolean)"
>
<span class="flex-1">{{ 'label' in item ? item.label : '' }}</span>
@@ -280,7 +163,7 @@ const topMenus = [
</MenubarCheckboxItem>
<MenubarItem
v-else
- :class="menuItem()"
+ :class="menuCls.item"
:disabled="'disabled' in item ? item.disabled : undefined"
@select="'action' in item ? item.action?.() : undefined"
>
diff --git a/src/components/CanvasMenu.vue b/src/components/CanvasMenu.vue
index 09bdd4512..ab02669bd 100644
--- a/src/components/CanvasMenu.vue
+++ b/src/components/CanvasMenu.vue
@@ -13,7 +13,7 @@ import { useEditorCommands, useMenuModel, useSelectionState } from '@open-pencil
import { toast } from '@/utils/toast'
import { useEditorStore } from '@/stores/editor'
-import { menuContent, menuItem, menuSeparator } from '@/components/ui/menu'
+import { menu, useMenuUI } from '@/components/ui/menu'
const store = useEditorStore()
const { copy } = useClipboard()
@@ -22,7 +22,6 @@ const { editor, selectedIds, hasSelection } = useSelectionState()
const { getCommand } = useEditorCommands()
const { canvasMenu } = useMenuModel()
-
function ids() {
return [...selectedIds.value]
}
@@ -45,13 +44,17 @@ async function copyAsPNG() {
toast.show('Copied as PNG')
}
+const menuCls = useMenuUI({
+ content: 'min-w-56 shadow-[0_8px_30px_rgb(0_0_0/0.4)] animate-in fade-in zoom-in-95',
+ separator: 'my-1'
+})
+const componentMenu = menu({ tone: 'component' })
+
const cls = {
- menu: menuContent({
- class: 'min-w-56 shadow-[0_8px_30px_rgb(0_0_0/0.4)] animate-in fade-in zoom-in-95'
- }),
- item: menuItem(),
- component: menuItem({ tone: 'component' }),
- sep: menuSeparator({ class: 'my-1' })
+ menu: menuCls.content,
+ item: menuCls.item,
+ component: componentMenu.item(),
+ sep: menuCls.separator
}
</script>
@@ -73,7 +76,11 @@ const cls = {
>
<span>Duplicate</span><span class="text-[11px] text-muted">⌘D</span>
</ContextMenuItem>
- <ContextMenuItem :class="cls.item" :disabled="!hasSelection" @select="getCommand('selection.delete').run()">
+ <ContextMenuItem
+ :class="cls.item"
+ :disabled="!hasSelection"
+ @select="getCommand('selection.delete').run()"
+ >
<span>Delete</span><span class="text-[11px] text-muted">⌫</span>
</ContextMenuItem>
@@ -81,7 +88,8 @@ const cls = {
<ContextMenuSeparator v-if="item.separator" :class="cls.sep" />
<ContextMenuSub v-else-if="item.sub">
<ContextMenuSubTrigger :class="cls.item">
- <span>{{ item.label }}</span><span class="text-sm text-muted">›</span>
+ <span>{{ item.label }}</span
+ ><span class="text-sm text-muted">›</span>
</ContextMenuSubTrigger>
<ContextMenuPortal>
<ContextMenuSubContent :class="cls.menu">
@@ -102,12 +110,25 @@ const cls = {
</ContextMenuSub>
<ContextMenuItem
v-else
- :class="item.label.includes('component') || item.label.includes('instance') ? cls.component : cls.item"
+ :class="
+ item.label.includes('component') || item.label.includes('instance')
+ ? cls.component
+ : cls.item
+ "
:disabled="item.disabled"
@select="item.action?.()"
>
<span class="flex-1">{{ item.label }}</span>
- <span v-if="item.shortcut" class="text-[11px]" :class="item.label.includes('component') || item.label.includes('instance') ? 'text-component/60' : 'text-muted'">{{ item.shortcut }}</span>
+ <span
+ v-if="item.shortcut"
+ class="text-[11px]"
+ :class="
+ item.label.includes('component') || item.label.includes('instance')
+ ? 'text-component/60'
+ : 'text-muted'
+ "
+ >{{ item.shortcut }}</span
+ >
</ContextMenuItem>
</template>
diff --git a/src/components/CollabPanel.vue b/src/components/CollabPanel.vue
index c49d4597b..0c133e965 100644
--- a/src/components/CollabPanel.vue
+++ b/src/components/CollabPanel.vue
@@ -2,25 +2,18 @@
import { useClipboard } from '@vueuse/core'
import { computed, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
-import {
- PopoverRoot,
- PopoverTrigger,
- PopoverPortal,
- PopoverContent,
- TooltipRoot,
- TooltipTrigger,
- TooltipPortal,
- TooltipContent,
- TooltipProvider
-} from 'reka-ui'
+import { PopoverRoot, PopoverTrigger, PopoverPortal, PopoverContent } from 'reka-ui'
import { colorToCSS } from '@open-pencil/core'
+import Tip from '@/components/ui/Tip.vue'
+import { usePopoverUI } from '@/components/ui/popover'
import { DEFAULT_COLLAB_STATE, useCollabInjected } from '@/composables/use-collab'
import { toast } from '@/utils/toast'
import { initials } from '@/utils/text'
const route = useRoute()
const router = useRouter()
+const cls = usePopoverUI({ content: 'z-50 w-72 p-3' })
const collab = useCollabInjected()
const { copy, copied } = useClipboard({ copiedDuring: 2000 })
@@ -76,59 +69,39 @@ function onDisconnect() {
<template>
<div class="flex w-full items-center justify-end gap-2">
<!-- Avatar stack -->
- <TooltipProvider :delay-duration="200">
- <div class="flex -space-x-1.5">
- <TooltipRoot>
- <TooltipTrigger as-child>
- <div
- data-test-id="collab-local-avatar"
- class="flex size-6 items-center justify-center rounded-full border-2 border-panel text-[10px] font-semibold text-white"
- :style="{ background: colorToCSS(state.localColor) }"
- >
- {{ initials(state.localName || 'You') }}
- </div>
- </TooltipTrigger>
- <TooltipPortal>
- <TooltipContent
- class="rounded bg-neutral-800 px-2 py-1 text-xs text-white shadow-lg"
- :side-offset="4"
- >
- {{ state.localName || 'You' }} (you)
- </TooltipContent>
- </TooltipPortal>
- </TooltipRoot>
-
- <TooltipRoot v-for="peer in peers" :key="peer.clientId">
- <TooltipTrigger as-child>
- <div
- data-test-id="collab-peer-avatar"
- class="flex size-6 cursor-pointer items-center justify-center rounded-full border-2 text-[10px] font-semibold text-white transition-all"
- :class="
- followingPeer === peer.clientId
- ? 'border-white ring-2 ring-white/40'
- : 'border-panel'
- "
- :style="{ background: colorToCSS(peer.color) }"
- @click="collab?.followPeer(followingPeer === peer.clientId ? null : peer.clientId)"
- >
- {{ initials(peer.name) }}
- </div>
- </TooltipTrigger>
- <TooltipPortal>
- <TooltipContent
- class="rounded bg-neutral-800 px-2 py-1 text-xs text-white shadow-lg"
- :side-offset="4"
- >
- {{
- followingPeer === peer.clientId
- ? `Following ${peer.name} (click to stop)`
- : `Click to follow ${peer.name}`
- }}
- </TooltipContent>
- </TooltipPortal>
- </TooltipRoot>
- </div>
- </TooltipProvider>
+ <div class="flex -space-x-1.5">
+ <Tip :label="`${state.localName || 'You'} (you)`">
+ <div
+ data-test-id="collab-local-avatar"
+ class="flex size-6 items-center justify-center rounded-full border-2 border-panel text-[10px] font-semibold text-white"
+ :style="{ background: colorToCSS(state.localColor) }"
+ >
+ {{ initials(state.localName || 'You') }}
+ </div>
+ </Tip>
+
+ <Tip
+ v-for="peer in peers"
+ :key="peer.clientId"
+ :label="
+ followingPeer === peer.clientId
+ ? `Following ${peer.name} (click to stop)`
+ : `Click to follow ${peer.name}`
+ "
+ >
+ <div
+ data-test-id="collab-peer-avatar"
+ class="flex size-6 cursor-pointer items-center justify-center rounded-full border-2 text-[10px] font-semibold text-white transition-all"
+ :class="
+ followingPeer === peer.clientId ? 'border-white ring-2 ring-white/40' : 'border-panel'
+ "
+ :style="{ background: colorToCSS(peer.color) }"
+ @click="collab?.followPeer(followingPeer === peer.clientId ? null : peer.clientId)"
+ >
+ {{ initials(peer.name) }}
+ </div>
+ </Tip>
+ </div>
<div class="flex-1" />
@@ -154,7 +127,7 @@ function onDisconnect() {
<PopoverPortal>
<PopoverContent
data-test-id="collab-popover"
- class="z-50 w-72 rounded-lg border border-border bg-panel p-3 shadow-xl"
+ :class="cls.content"
:side-offset="8"
side="bottom"
align="end"
diff --git a/src/components/ColorPicker.vue b/src/components/ColorPicker.vue
index 676ebca7e..859bfb757 100644
--- a/src/components/ColorPicker.vue
+++ b/src/components/ColorPicker.vue
@@ -4,11 +4,13 @@ import { PopoverRoot, PopoverTrigger, PopoverPortal, PopoverContent } from 'reka
import { colorToCSS } from '@open-pencil/core'
import HsvColorArea from './HsvColorArea.vue'
+import { usePopoverUI } from './ui/popover'
import type { Color } from '@open-pencil/core'
const { color } = defineProps<{ color: Color }>()
const emit = defineEmits<{ update: [color: Color] }>()
+const cls = usePopoverUI({ content: 'w-56 p-2' })
const swatchBg = computed(() => colorToCSS(color))
</script>
@@ -26,7 +28,7 @@ const swatchBg = computed(() => colorToCSS(color))
<PopoverPortal>
<PopoverContent
data-test-id="color-picker-popover"
- class="z-[100] w-56 rounded-lg border border-border bg-panel p-2 shadow-xl"
+ :class="cls.content"
:side-offset="4"
side="left"
>
diff --git a/src/components/FillPicker.vue b/src/components/FillPicker.vue
index 5d99e90c2..61f082292 100644
--- a/src/components/FillPicker.vue
+++ b/src/components/FillPicker.vue
@@ -8,7 +8,8 @@ import HsvColorArea from './HsvColorArea.vue'
import ImageFillPicker from './ImageFillPicker.vue'
import { useFillPicker } from '@open-pencil/vue'
-import Tip from './Tip.vue'
+import Tip from './ui/Tip.vue'
+import { usePopoverUI } from './ui/popover'
import type { Fill } from '@open-pencil/core'
@@ -24,6 +25,7 @@ function tabClass(active: boolean) {
const { fill } = defineProps<{ fill: Fill }>()
const emit = defineEmits<{ update: [fill: Fill] }>()
+const cls = usePopoverUI({ content: 'w-60 p-2' })
const { category, swatchBg, toSolid, toGradient, toImage } = useFillPicker(
computed(() => fill),
@@ -42,11 +44,7 @@ const { category, swatchBg, toSolid, toGradient, toImage } = useFillPicker(
</PopoverTrigger>
<PopoverPortal>
- <PopoverContent
- class="z-[100] w-60 rounded-lg border border-border bg-panel p-2 shadow-xl"
- :side-offset="4"
- side="left"
- >
+ <PopoverContent :class="cls.content" :side-offset="4" side="left">
<div class="mb-2 flex items-center gap-0.5">
<Tip label="Solid">
<button
diff --git a/src/components/FontPicker.vue b/src/components/FontPicker.vue
index 0fd65f847..df4941f89 100644
--- a/src/components/FontPicker.vue
+++ b/src/components/FontPicker.vue
@@ -1,89 +1,74 @@
<script setup lang="ts">
-import { computed, nextTick, onMounted, ref, watch } from 'vue'
+import { nextTick, ref } from 'vue'
import {
- type AcceptableValue,
- type ListboxFilter,
- ListboxContent,
- ListboxItem,
- ListboxRoot,
- ListboxVirtualizer,
- PopoverAnchor,
- PopoverContent,
- PopoverRoot,
- useFilter
+ ComboboxAnchor,
+ ComboboxContent,
+ ComboboxInput,
+ ComboboxItem,
+ ComboboxItemIndicator,
+ ComboboxPortal,
+ ComboboxRoot,
+ ComboboxVirtualizer,
+ ComboboxViewport,
+ type AcceptableValue
} from 'reka-ui'
-import { selectItem, selectTrigger } from '@/components/ui/select'
-import { panelSurface } from '@/components/ui/surface'
+import { useSelectUI } from '@/components/ui/select'
+import { usePopoverUI } from '@/components/ui/popover'
import { listFamilies } from '@/engine/fonts'
+import { useFontPicker } from '@open-pencil/vue'
const modelValue = defineModel<string>({ required: true })
const emit = defineEmits<{ select: [family: string] }>()
-const families = ref<string[]>([])
-const searchTerm = ref('')
-const open = ref(false)
-const filterRef = ref<InstanceType<typeof ListboxFilter> | null>(null)
-
-const { contains } = useFilter({ sensitivity: 'base' })
-const filtered = computed(() => {
- if (!searchTerm.value) return families.value
- return families.value.filter((f) => contains(f, searchTerm.value))
+const cls = usePopoverUI({
+ content: 'w-[var(--reka-combobox-trigger-width)] min-w-56 overflow-hidden p-0'
})
-
-onMounted(async () => {
- families.value = await listFamilies()
+const inputRef = ref<HTMLInputElement | null>(null)
+const selectCls = useSelectUI({
+ trigger: 'w-full rounded px-2 py-1 text-xs',
+ item: 'w-full gap-2 px-2 py-2 text-sm'
})
-watch(open, (isOpen) => {
- if (isOpen) searchTerm.value = ''
+const { searchTerm, open, filtered, select } = useFontPicker({
+ modelValue,
+ listFamilies,
+ onSelect: (family) => emit('select', family)
})
-
-function select(family: string) {
- modelValue.value = family
- emit('select', family)
- open.value = false
-}
</script>
<template>
- <PopoverRoot :open="open" @update:open="(v) => (open = v)">
- <PopoverAnchor>
- <button
- data-test-id="font-picker-trigger"
- :class="selectTrigger({ class: 'w-full rounded px-2 py-1 text-xs' })"
- @click="open = !open"
- >
+ <ComboboxRoot
+ v-model:open="open"
+ :model-value="modelValue"
+ :ignore-filter="true"
+ @update:model-value="
+ (v: AcceptableValue) => {
+ if (typeof v === 'string') select(v)
+ }
+ "
+ >
+ <ComboboxAnchor as-child>
+ <button data-test-id="font-picker-trigger" :class="selectCls.trigger">
<span class="truncate">{{ modelValue }}</span>
<icon-lucide-chevron-down class="size-3 shrink-0 text-muted" />
</button>
- </PopoverAnchor>
- <PopoverContent
- :side-offset="2"
- align="start"
- :class="
- panelSurface({
- radius: 'md',
- padding: 'none',
- class: 'z-50 flex w-[var(--reka-popper-anchor-width)] min-w-56 flex-col overflow-hidden'
- })
- "
- @open-auto-focus.prevent
- @vue:mounted="nextTick(() => filterRef?.$el?.focus())"
- >
- <ListboxRoot
- :model-value="modelValue"
- @update:model-value="
- (v: AcceptableValue) => {
- if (typeof v === 'string') select(v)
- }
- "
+ </ComboboxAnchor>
+
+ <ComboboxPortal>
+ <ComboboxContent
+ :side-offset="2"
+ align="start"
+ position="popper"
+ :class="cls.content"
+ @open-auto-focus.prevent
+ @vue:mounted="nextTick(() => inputRef?.focus())"
>
<div class="flex items-center gap-1 border-b border-border px-2 py-1">
<icon-lucide-search class="size-3 shrink-0 text-muted" />
- <input
- ref="filterRef"
- :value="searchTerm"
+ <ComboboxInput
+ ref="inputRef"
+ v-model="searchTerm"
data-test-id="font-picker-search"
class="min-w-0 flex-1 border-none bg-transparent text-xs text-surface outline-none placeholder:text-muted"
placeholder="Search fonts…"
@@ -91,27 +76,30 @@ function select(family: string) {
autocorrect="off"
autocapitalize="off"
spellcheck="false"
- @input="searchTerm = ($event.target as HTMLInputElement).value"
/>
</div>
- <ListboxContent class="h-72 overflow-y-auto">
- <ListboxVirtualizer
+
+ <ComboboxViewport class="max-h-72 overflow-y-auto">
+ <ComboboxVirtualizer
v-slot="{ option }"
:options="filtered"
- :text-content="(f: string) => f"
+ :text-content="(family: string) => family"
:estimate-size="36"
>
- <ListboxItem
+ <ComboboxItem
:value="option"
data-test-id="font-picker-item"
- :class="selectItem({ class: 'w-full gap-2 px-2 py-2 text-sm' })"
+ :class="selectCls.item"
:style="{ fontFamily: `'${option}', sans-serif` }"
>
- <icon-lucide-check v-if="option === modelValue" class="size-3 shrink-0 text-accent" />
- <span v-else class="size-3 shrink-0" />
+ <ComboboxItemIndicator>
+ <icon-lucide-check class="size-3 shrink-0 text-accent" />
+ </ComboboxItemIndicator>
+ <span v-if="option !== modelValue" class="size-3 shrink-0" />
<span class="truncate">{{ option }}</span>
- </ListboxItem>
- </ListboxVirtualizer>
+ </ComboboxItem>
+ </ComboboxVirtualizer>
+
<div
v-if="filtered.length === 0 && searchTerm"
class="px-2 py-3 text-center text-xs text-muted"
@@ -120,15 +108,15 @@ function select(family: string) {
</div>
<div
v-else-if="filtered.length === 0"
- class="flex h-full items-center justify-center px-3 text-center text-xs text-muted"
+ class="flex h-full items-center justify-center px-3 py-3 text-center text-xs text-muted"
>
<div>
<p>No local fonts available.</p>
<p class="mt-1">Use the desktop app or Chrome/Edge to access system fonts.</p>
</div>
</div>
- </ListboxContent>
- </ListboxRoot>
- </PopoverContent>
- </PopoverRoot>
+ </ComboboxViewport>
+ </ComboboxContent>
+ </ComboboxPortal>
+ </ComboboxRoot>
</template>
diff --git a/src/components/MobileHud.vue b/src/components/MobileHud.vue
index 669d94ff7..f322e17ea 100644
--- a/src/components/MobileHud.vue
+++ b/src/components/MobileHud.vue
@@ -20,12 +20,12 @@ import IconImageDown from '~icons/lucide/image-down'
import IconSave from '~icons/lucide/save'
import IconZoomIn from '~icons/lucide/zoom-in'
-import { menuContent, menuItem } from '@/components/ui/menu'
+import { menu, useMenuUI } from '@/components/ui/menu'
import { openFileDialog } from '@/composables/use-menu'
import { DEFAULT_COLLAB_STATE, useCollabInjected } from '@/composables/use-collab'
import { toast } from '@/utils/toast'
import { useEditorStore } from '@/stores/editor'
-import Tip from '@/components/Tip.vue'
+import Tip from '@/components/ui/Tip.vue'
import { colorToCSS } from '@open-pencil/core'
import { useEditorCommands } from '@open-pencil/vue'
import { toolIcons } from '@/utils/tools'
@@ -58,6 +58,10 @@ function onDisconnect() {
}
const activeToolIcon = computed(() => toolIcons[store.state.activeTool])
+const menuCls = useMenuUI({
+ content: 'w-48 rounded-xl p-1.5 shadow-xl',
+ item: 'w-full gap-2.5 rounded-lg border-none bg-transparent px-2.5 py-2 active:bg-hover'
+})
interface MenuAction {
icon: Component
@@ -225,22 +229,11 @@ const onlineCount = computed(() => collabPeers.value.length + 1)
</button>
</DropdownMenuTrigger>
<DropdownMenuPortal>
- <DropdownMenuContent
- :side-offset="8"
- side="bottom"
- align="end"
- :class="menuContent({ class: 'w-48 rounded-xl p-1.5 shadow-xl' })"
- >
+ <DropdownMenuContent :side-offset="8" side="bottom" align="end" :class="menuCls.content">
<DropdownMenuItem
v-for="item in menuItems"
:key="item.label"
- :class="
- menuItem({
- justify: 'start',
- class:
- 'w-full gap-2.5 rounded-lg border-none bg-transparent px-2.5 py-2 active:bg-hover'
- })
- "
+ :class="menu({ justify: 'start' }).item({ class: menuCls.item })"
@click="item.action()"
>
<component :is="item.icon" class="size-4 text-muted" />
diff --git a/src/components/Toolbar.vue b/src/components/Toolbar.vue
index ba124ea58..9971ed23c 100644
--- a/src/components/Toolbar.vue
+++ b/src/components/Toolbar.vue
@@ -1,5 +1,4 @@
<script setup lang="ts">
-import { ref, computed } from 'vue'
import {
DropdownMenuRoot,
DropdownMenuTrigger,
@@ -23,18 +22,25 @@ import IconGroup from '~icons/lucide/group'
import IconUngroup from '~icons/lucide/ungroup'
import IconLock from '~icons/lucide/lock'
-import { menuContent, menuItem } from '@/components/ui/menu'
-import Tip from '@/components/Tip.vue'
-import { ACTION_TOAST_DURATION } from '@/constants'
+import { menu, useMenuUI } from '@/components/ui/menu'
+import Tip from '@/components/ui/Tip.vue'
+import { useActionToast } from '@/composables/use-action-toast'
import { useEditorStore } from '@/stores/editor'
import { toolIcons } from '@/utils/tools'
-import { ToolbarRoot, ToolbarItem, useEditorCommands, useViewportKind } from '@open-pencil/vue'
+import {
+ ToolbarRoot,
+ ToolbarItem,
+ useEditorCommands,
+ useToolbarState,
+ useViewportKind
+} from '@open-pencil/vue'
import type { Component } from 'vue'
-import type { EditorToolDef, Tool } from '@open-pencil/vue'
+import type { Tool } from '@open-pencil/vue'
const store = useEditorStore()
const { isMobile } = useViewportKind()
const { getCommand } = useEditorCommands()
+const { showActionToast } = useActionToast()
const toolLabels: Record<Tool, string> = {
SELECT: 'Move',
@@ -64,22 +70,14 @@ const toolShortcuts: Record<Tool, string> = {
HAND: 'H'
}
-function isActive(tool: EditorToolDef, activeTool: Tool): boolean {
- if (tool.key === activeTool) return true
- return tool.flyout?.includes(activeTool) ?? false
-}
-
-function activeKeyForTool(tool: EditorToolDef, activeTool: Tool): Tool {
- if (tool.flyout?.includes(activeTool)) return activeTool
- return tool.key
-}
-
interface ActionItem {
icon: Component
label: string
action: () => void
}
+const flyoutMenuCls = useMenuUI({ content: 'min-w-32' })
+
const editActions: ActionItem[] = [
{ icon: IconCopy, label: 'Copy', action: () => store.mobileCopy() },
{ icon: IconClipboard, label: 'Paste', action: () => store.mobilePaste() },
@@ -89,48 +87,42 @@ const editActions: ActionItem[] = [
]
const arrangeActions: ActionItem[] = [
- { icon: IconArrowUpToLine, label: 'Front', action: () => getCommand('selection.bringToFront').run() },
- { icon: IconArrowDownToLine, label: 'Back', action: () => getCommand('selection.sendToBack').run() },
+ {
+ icon: IconArrowUpToLine,
+ label: 'Front',
+ action: () => getCommand('selection.bringToFront').run()
+ },
+ {
+ icon: IconArrowDownToLine,
+ label: 'Back',
+ action: () => getCommand('selection.sendToBack').run()
+ },
{ icon: IconGroup, label: 'Group', action: () => getCommand('selection.group').run() },
{ icon: IconUngroup, label: 'Ungroup', action: () => getCommand('selection.ungroup').run() },
{ icon: IconLock, label: 'Lock', action: () => getCommand('selection.toggleLock').run() }
]
-const CATEGORY_COUNT = 3
-const mobileCategory = ref(0)
-const hasPrev = computed(() => mobileCategory.value > 0)
-const hasNext = computed(() => mobileCategory.value < CATEGORY_COUNT - 1)
-
-let toastTimer: ReturnType<typeof setTimeout> | undefined
+const {
+ mobileCategory,
+ slideDirection,
+ hasPrev,
+ hasNext,
+ isActive,
+ activeKeyForTool,
+ goPrev,
+ goNext
+} = useToolbarState()
function onActionTap(item: ActionItem) {
item.action()
- store.state.actionToast = item.label
- clearTimeout(toastTimer)
- toastTimer = setTimeout(() => {
- store.state.actionToast = null
- }, ACTION_TOAST_DURATION)
+ showActionToast(item.label)
}
-const slideDirection = ref(1)
-
const slideVariants = {
initial: (dir: unknown) => ({ opacity: 0, x: (dir as number) * 20 }),
animate: { opacity: 1, x: 0 },
exit: (dir: unknown) => ({ opacity: 0, x: (dir as number) * -20 })
}
-
-function goPrev() {
- if (!hasPrev.value) return
- slideDirection.value = -1
- mobileCategory.value--
-}
-
-function goNext() {
- if (!hasNext.value) return
- slideDirection.value = 1
- mobileCategory.value++
-}
</script>
<template>
@@ -180,7 +172,7 @@ function goNext() {
side="top"
:side-offset="8"
align="start"
- :class="menuContent({ class: 'min-w-32' })"
+ :class="flyoutMenuCls.content"
>
<ToolbarItem
v-for="sub in tool.flyout"
@@ -191,9 +183,7 @@ function goNext() {
<DropdownMenuItem
:data-test-id="`toolbar-flyout-item-${sub.toLowerCase()}`"
:class="
- menuItem({
- class: subActive ? 'bg-accent text-white' : undefined
- })
+ menu().item({ class: subActive ? 'bg-accent text-white' : undefined })
"
@select="selectSub"
>
@@ -303,7 +293,7 @@ function goNext() {
side="top"
:side-offset="8"
align="start"
- :class="menuContent({ class: 'min-w-32' })"
+ :class="flyoutMenuCls.content"
>
<ToolbarItem
v-for="sub in tool.flyout"
@@ -314,9 +304,7 @@ function goNext() {
<DropdownMenuItem
:data-test-id="`mobile-toolbar-flyout-item-${sub.toLowerCase()}`"
:class="
- menuItem({
- class: subActive ? 'bg-accent text-white' : undefined
- })
+ menu().item({ class: subActive ? 'bg-accent text-white' : undefined })
"
@select="selectSub"
>
diff --git a/src/components/VariablesDialog.vue b/src/components/VariablesDialog.vue
index 5bbb9ae77..a9d133e49 100644
--- a/src/components/VariablesDialog.vue
+++ b/src/components/VariablesDialog.vue
@@ -1,5 +1,5 @@
<script setup lang="ts">
-import { ref, computed, nextTick, h, type Component } from 'vue'
+import { type Component } from 'vue'
import {
DialogRoot,
DialogPortal,
@@ -10,25 +10,22 @@ import {
TabsRoot,
TabsList,
TabsTrigger,
- TabsContent,
- EditableRoot,
- EditableArea,
- EditableInput,
- EditablePreview
+ TabsContent
} from 'reka-ui'
-import { useVueTable, getCoreRowModel, FlexRender, type ColumnDef } from '@tanstack/vue-table'
+import { useVueTable, getCoreRowModel, FlexRender } from '@tanstack/vue-table'
import IconPalette from '~icons/lucide/palette'
import IconHash from '~icons/lucide/hash'
import IconType from '~icons/lucide/type'
import IconToggleLeft from '~icons/lucide/toggle-left'
import IconX from '~icons/lucide/x'
-import Tip from './Tip.vue'
+import Tip from './ui/Tip.vue'
import ColorInput from './ColorInput.vue'
-import { useVariables } from '@open-pencil/vue'
-import type { Variable, Color } from '@open-pencil/core'
+import { useDialogUI } from '@/components/ui/dialog'
+import { useVariablesDialogState, useVariablesTable } from '@open-pencil/vue'
const open = defineModel<boolean>('open', { default: false })
+const cls = useDialogUI({ content: 'flex h-[75vh] w-[800px] max-w-[90vw] flex-col' })
const {
collections,
@@ -37,60 +34,18 @@ const {
activeModes,
searchTerm,
addCollection,
- renameCollection,
addVariable,
removeVariable,
renameVariable,
updateVariableValue,
formatModeValue,
parseVariableValue,
- shortName
-} = useVariables()
-
-const editingCollectionId = ref<string | null>(null)
-const collectionInputRefs = new Map<string, HTMLInputElement>()
-const pendingCollectionFocusId = ref<string | null>(null)
-
-function setCollectionInputRef(id: string, el: HTMLInputElement | null) {
- if (el) collectionInputRefs.set(id, el)
- else collectionInputRefs.delete(id)
-
- if (el && pendingCollectionFocusId.value === id) {
- pendingCollectionFocusId.value = null
- void nextTick(() => {
- el.focus()
- el.select()
- })
- }
-}
-
-function startRenameCollection(id: string) {
- editingCollectionId.value = id
- pendingCollectionFocusId.value = id
-}
-
-function commitRenameCollection(id: string, input: HTMLInputElement) {
- if (editingCollectionId.value !== id) return
- const value = input.value.trim()
- const col = collections.value.find((c) => c.id === id)
- if (col && value && value !== col.name) {
- renameCollection(id, value)
- }
- editingCollectionId.value = null
-}
-
-function commitNameEdit(variable: Variable, newName: string) {
- if (newName && newName !== variable.name) {
- renameVariable(variable.id, newName)
- }
-}
-
-function commitValueEdit(variable: Variable, modeId: string, newValue: string) {
- const parsed = parseVariableValue(variable, newValue)
- if (parsed !== undefined) {
- updateVariableValue(variable.id, modeId, parsed)
- }
-}
+ shortName,
+ editingCollectionId,
+ setCollectionInputRef,
+ startRenameCollection,
+ commitRenameCollection
+} = useVariablesDialogState()
const VARIABLE_TYPE_ICONS: Record<string, Component> = {
COLOR: IconPalette,
@@ -99,101 +54,18 @@ const VARIABLE_TYPE_ICONS: Record<string, Component> = {
BOOLEAN: IconToggleLeft
}
-const columns = computed<ColumnDef<Variable>[]>(() => {
- const nameCol: ColumnDef<Variable> = {
- id: 'name',
- header: 'Name',
- size: 200,
- minSize: 120,
- maxSize: 400,
- cell: ({ row }) => {
- const v = row.original
- const iconClass = 'size-3.5 shrink-0 text-muted'
- const iconComponent = VARIABLE_TYPE_ICONS[v.type] ?? IconToggleLeft
- const icon = h(iconComponent, { class: iconClass })
-
- return h('div', { class: 'flex items-center gap-2' }, [
- icon,
- h(
- EditableRoot,
- {
- defaultValue: shortName(v),
- class: 'min-w-0 flex-1',
- onSubmit: (val: string | null | undefined) => val && commitNameEdit(v, val)
- },
- () =>
- h(EditableArea, { class: 'flex' }, () => [
- h(EditablePreview, {
- class: 'min-w-0 flex-1 cursor-text truncate text-xs text-surface'
- }),
- h(EditableInput, {
- class:
- 'min-w-0 flex-1 rounded border border-border bg-surface/10 px-1 py-0.5 text-xs text-surface outline-none'
- })
- ])
- )
- ])
- }
- }
-
- const modeCols: ColumnDef<Variable>[] = activeModes.value.map((mode) => ({
- id: `mode-${mode.modeId}`,
- header: mode.name,
- size: 200,
- minSize: 120,
- maxSize: 500,
- cell: ({ row }) => {
- const v = row.original
- const value = v.valuesByMode[mode.modeId]
-
- if (v.type === 'COLOR' && value && typeof value === 'object' && 'r' in value) {
- return h(ColorInput, {
- color: value as Color,
- onUpdate: (c: Color) => updateVariableValue(v.id, mode.modeId, c)
- })
- }
-
- return h(
- EditableRoot,
- {
- defaultValue: formatModeValue(v, mode.modeId),
- class: 'min-w-0 flex-1',
- onSubmit: (val: string | null | undefined) => val && commitValueEdit(v, mode.modeId, val)
- },
- () =>
- h(EditableArea, { class: 'flex' }, () => [
- h(EditablePreview, {
- class: 'min-w-0 flex-1 cursor-text truncate font-mono text-xs text-muted'
- }),
- h(EditableInput, {
- class:
- 'min-w-0 flex-1 rounded border border-border bg-surface/10 px-1 py-0.5 font-mono text-xs text-surface outline-none'
- })
- ])
- )
- }
- }))
-
- const deleteCol: ColumnDef<Variable> = {
- id: 'actions',
- header: '',
- size: 36,
- minSize: 36,
- maxSize: 36,
- enableResizing: false,
- cell: ({ row }) =>
- h(
- 'button',
- {
- class:
- 'flex size-5 cursor-pointer items-center justify-center rounded border-none bg-transparent text-muted opacity-0 transition-opacity group-hover:opacity-100 hover:text-surface',
- onClick: () => removeVariable(row.original.id)
- },
- h(IconX, { class: 'size-3' })
- )
- }
-
- return [nameCol, ...modeCols, deleteCol]
+const { columns } = useVariablesTable({
+ activeModes: activeModes,
+ formatModeValue,
+ parseVariableValue,
+ shortName,
+ renameVariable,
+ updateVariableValue,
+ removeVariable,
+ ColorInput,
+ icons: VARIABLE_TYPE_ICONS,
+ fallbackIcon: IconToggleLeft,
+ deleteIcon: IconX
})
const table = useVueTable({
@@ -216,11 +88,8 @@ const table = useVueTable({
<template>
<DialogRoot v-model:open="open">
<DialogPortal>
- <DialogOverlay class="fixed inset-0 z-40 bg-black/50" />
- <DialogContent
- data-test-id="variables-dialog"
- class="fixed top-1/2 left-1/2 z-50 flex h-[75vh] w-[800px] max-w-[90vw] -translate-x-1/2 -translate-y-1/2 flex-col rounded-xl border border-border bg-panel shadow-2xl outline-none"
- >
+ <DialogOverlay :class="cls.overlay" />
+ <DialogContent data-test-id="variables-dialog" :class="cls.content">
<div v-if="collections.length === 0" class="flex flex-1 flex-col">
<div class="flex shrink-0 items-center justify-between border-b border-border px-4 py-3">
<DialogTitle class="text-sm font-semibold text-surface">Local variables</DialogTitle>
diff --git a/src/components/chat/ACPPermissionDialog.vue b/src/components/chat/ACPPermissionDialog.vue
index 4fb29c5b6..02e872a23 100644
--- a/src/components/chat/ACPPermissionDialog.vue
+++ b/src/components/chat/ACPPermissionDialog.vue
@@ -16,8 +16,13 @@ import {
rejectCurrentPermission,
respondToPermission
} from '@/ai/acp-permission'
+import { useDialogUI } from '@/components/ui/dialog'
const open = computed(() => currentPermission.value !== null)
+const cls = useDialogUI({
+ overlay: 'z-50',
+ content: 'w-80 rounded-lg p-4 shadow-xl'
+})
interface ToolCallInfo {
title?: string
@@ -56,10 +61,10 @@ function handleDismiss() {
<template>
<AlertDialogRoot :open="open">
<AlertDialogPortal>
- <AlertDialogOverlay class="fixed inset-0 z-50 bg-black/50" @click="handleDismiss" />
+ <AlertDialogOverlay :class="cls.overlay" @click="handleDismiss" />
<AlertDialogContent
data-test-id="acp-permission-dialog"
- class="fixed top-1/2 left-1/2 z-50 w-80 -translate-x-1/2 -translate-y-1/2 rounded-lg border border-border bg-panel p-4 shadow-xl"
+ :class="cls.content"
@escape-key-down="handleDismiss"
>
<AlertDialogTitle class="text-sm font-semibold text-surface">
diff --git a/src/components/chat/ChatInput.vue b/src/components/chat/ChatInput.vue
index b79760457..ade195572 100644
--- a/src/components/chat/ChatInput.vue
+++ b/src/components/chat/ChatInput.vue
@@ -1,24 +1,12 @@
<script setup lang="ts">
-import {
- SelectContent,
- SelectItem,
- SelectItemText,
- SelectPortal,
- SelectRoot,
- SelectTrigger,
- SelectViewport,
- TooltipContent,
- TooltipPortal,
- TooltipProvider,
- TooltipRoot,
- TooltipTrigger
-} from 'reka-ui'
+import { TooltipProvider } from 'reka-ui'
import { computed, ref } from 'vue'
+import ProviderModelSelect from '@/components/chat/ProviderModelSelect.vue'
import ProviderSettings from '@/components/chat/ProviderSettings.vue'
+import Tip from '@/components/ui/Tip.vue'
import { uiButton } from '@/components/ui/button'
import { uiInput } from '@/components/ui/input'
-import { selectContent, selectItem, selectTrigger } from '@/components/ui/select'
import { useAIChat } from '@/composables/use-chat'
import { ACP_AGENTS } from '@open-pencil/core'
@@ -80,48 +68,9 @@ function handleSubmit(e: Event) {
{{ selectedModelName }}
</div>
</template>
- <SelectRoot v-else v-model="modelID">
- <SelectTrigger
- data-test-id="chat-model-selector"
- :class="
- selectTrigger({
- class:
- 'gap-1 rounded border-none bg-transparent px-1.5 py-0.5 text-[10px] text-muted'
- })
- "
- >
- <icon-lucide-bot class="size-3" />
- {{ selectedModelName }}
- <icon-lucide-chevron-down class="size-2.5" />
- </SelectTrigger>
- <SelectPortal>
- <SelectContent
- position="popper"
- side="top"
- :side-offset="4"
- :class="
- selectContent({ radius: 'lg', padding: 'md', class: 'max-h-60 overflow-y-auto' })
- "
- >
- <SelectViewport>
- <SelectItem
- v-for="model in providerDef.models"
- :key="model.id"
- :value="model.id"
- :class="selectItem({ class: 'gap-2 rounded px-2 py-1.5 text-[11px]' })"
- >
- <SelectItemText class="flex-1">{{ model.name }}</SelectItemText>
- <span
- v-if="model.tag"
- class="rounded bg-accent/10 px-1 py-px text-[9px] text-accent"
- >
- {{ model.tag }}
- </span>
- </SelectItem>
- </SelectViewport>
- </SelectContent>
- </SelectPortal>
- </SelectRoot>
+ <ProviderModelSelect v-else>
+ <template #value>{{ selectedModelName }}</template>
+ </ProviderModelSelect>
<div class="ml-auto">
<ProviderSettings />
@@ -135,68 +84,46 @@ function handleSubmit(e: Event) {
type="text"
data-test-id="chat-input"
placeholder="Describe a change…"
- :class="uiInput({ class: 'min-w-0 flex-1 placeholder:text-muted' })"
+ :class="uiInput({ ui: { base: 'min-w-0 flex-1 placeholder:text-muted' } })"
:disabled="isStreaming"
@paste.stop
@copy.stop
@cut.stop
/>
- <TooltipRoot v-if="isStreaming">
- <TooltipTrigger as-child>
- <button
- type="button"
- data-test-id="chat-stop-button"
- :class="
- uiButton({
- tone: 'ghost',
- shape: 'rounded',
- size: 'sm',
- class: 'shrink-0 border border-border px-2 py-1.5'
- })
- "
- @click="emit('stop')"
- >
- <icon-lucide-square class="size-3" />
- </button>
- </TooltipTrigger>
- <TooltipPortal>
- <TooltipContent
- side="top"
- :side-offset="4"
- class="rounded bg-surface px-2 py-1 text-[10px] text-canvas"
- >
- Stop generating
- </TooltipContent>
- </TooltipPortal>
- </TooltipRoot>
- <TooltipRoot v-else>
- <TooltipTrigger as-child>
- <button
- type="submit"
- data-test-id="chat-send-button"
- :class="
- uiButton({
- tone: 'accent',
- shape: 'rounded',
- size: 'sm',
- class: 'shrink-0 px-2.5 py-1.5 font-medium'
- })
- "
- :disabled="!input.trim()"
- >
- <icon-lucide-send class="size-3" />
- </button>
- </TooltipTrigger>
- <TooltipPortal>
- <TooltipContent
- side="top"
- :side-offset="4"
- class="rounded bg-surface px-2 py-1 text-[10px] text-canvas"
- >
- Send message
- </TooltipContent>
- </TooltipPortal>
- </TooltipRoot>
+ <Tip v-if="isStreaming" label="Stop generating">
+ <button
+ type="button"
+ data-test-id="chat-stop-button"
+ :class="
+ uiButton({
+ tone: 'ghost',
+ shape: 'rounded',
+ size: 'sm',
+ ui: { base: 'shrink-0 border border-border px-2 py-1.5' }
+ })
+ "
+ @click="emit('stop')"
+ >
+ <icon-lucide-square class="size-3" />
+ </button>
+ </Tip>
+ <Tip v-else label="Send message">
+ <button
+ type="submit"
+ data-test-id="chat-send-button"
+ :class="
+ uiButton({
+ tone: 'accent',
+ shape: 'rounded',
+ size: 'sm',
+ ui: { base: 'shrink-0 px-2.5 py-1.5 font-medium' }
+ })
+ "
+ :disabled="!input.trim()"
+ >
+ <icon-lucide-send class="size-3" />
+ </button>
+ </Tip>
</form>
</div>
</TooltipProvider>
diff --git a/src/components/chat/ProviderModelSelect.vue b/src/components/chat/ProviderModelSelect.vue
new file mode 100644
index 000000000..c7a5944c0
--- /dev/null
+++ b/src/components/chat/ProviderModelSelect.vue
@@ -0,0 +1,48 @@
+<script setup lang="ts">
+import {
+ SelectContent,
+ SelectItem,
+ SelectItemText,
+ SelectPortal,
+ SelectRoot,
+ SelectTrigger,
+ SelectViewport
+} from 'reka-ui'
+
+import { useSelectUI } from '@/components/ui/select'
+import { useAIChat } from '@/composables/use-chat'
+
+const { modelID, providerDef } = useAIChat()
+const selectCls = useSelectUI({
+ trigger: 'gap-1 rounded border-none bg-transparent px-1.5 py-0.5 text-[10px] text-muted',
+ content: 'max-h-60 overflow-y-auto',
+ item: 'gap-2 rounded px-2 py-1.5 text-[11px]'
+})
+</script>
+
+<template>
+ <SelectRoot v-model="modelID">
+ <SelectTrigger data-test-id="chat-model-selector" :class="selectCls.trigger">
+ <icon-lucide-bot class="size-3" />
+ <slot name="value" />
+ <icon-lucide-chevron-down class="size-2.5" />
+ </SelectTrigger>
+ <SelectPortal>
+ <SelectContent position="popper" side="top" :side-offset="4" :class="selectCls.content">
+ <SelectViewport>
+ <SelectItem
+ v-for="model in providerDef.models"
+ :key="model.id"
+ :value="model.id"
+ :class="selectCls.item"
+ >
+ <SelectItemText class="flex-1">{{ model.name }}</SelectItemText>
+ <span v-if="model.tag" class="rounded bg-accent/10 px-1 py-px text-[9px] text-accent">
+ {{ model.tag }}
+ </span>
+ </SelectItem>
+ </SelectViewport>
+ </SelectContent>
+ </SelectPortal>
+ </SelectRoot>
+</template>
diff --git a/src/components/chat/ProviderSelect.vue b/src/components/chat/ProviderSelect.vue
index 66d88ab33..90387b267 100644
--- a/src/components/chat/ProviderSelect.vue
+++ b/src/components/chat/ProviderSelect.vue
@@ -1,19 +1,7 @@
<script setup lang="ts">
-import {
- SelectContent,
- SelectGroup,
- SelectItem,
- SelectItemText,
- SelectLabel,
- SelectPortal,
- SelectRoot,
- SelectSeparator,
- SelectTrigger,
- SelectViewport
-} from 'reka-ui'
import { computed, onMounted, ref } from 'vue'
-import { selectContent, selectItem, selectTrigger } from '@/components/ui/select'
+import AppGroupedSelect from '@/components/ui/AppGroupedSelect.vue'
import { ACP_AGENTS, AI_PROVIDERS, AUTOMATION_HTTP_PORT, IS_TAURI } from '@open-pencil/core'
import { useAIChat } from '@/composables/use-chat'
@@ -53,64 +41,48 @@ const displayName = computed(() => {
return providerDef.value.name
})
-const { triggerClass, itemClass, testId } = defineProps<{
- triggerClass?: string
- itemClass?: string
+const { ui, testId } = defineProps<{
+ ui?: {
+ trigger?: string
+ content?: string
+ item?: string
+ label?: string
+ separator?: string
+ }
testId?: string
}>()
+
+const groups = computed(() => {
+ const result: Array<{ label?: string; items: Array<{ value: string; label: string }> }> = []
+
+ if (acpAgents.value.length) {
+ result.push({
+ label: 'Your agents',
+ items: acpAgents.value.map((agent) => ({
+ value: `acp:${agent.id}`,
+ label: agent.name
+ }))
+ })
+ }
+
+ result.push({
+ label: acpAgents.value.length ? 'API key' : undefined,
+ items: AI_PROVIDERS.map((provider) => ({
+ value: provider.id,
+ label: provider.name
+ }))
+ })
+
+ return result
+})
</script>
<template>
- <SelectRoot v-model="providerID">
- <SelectTrigger
- :data-test-id="testId"
- :class="
- selectTrigger({
- class:
- triggerClass ??
- 'w-full justify-between rounded border border-border bg-input px-2 py-1 text-[11px] text-surface'
- })
- "
- >
- {{ displayName }}
- <icon-lucide-chevron-down class="size-2.5 shrink-0 text-muted" />
- </SelectTrigger>
- <SelectPortal>
- <SelectContent
- position="popper"
- :side-offset="4"
- :class="selectContent({ radius: 'lg', padding: 'md', class: 'isolate z-[52]' })"
- >
- <SelectViewport>
- <template v-if="acpAgents.length">
- <SelectGroup>
- <SelectLabel class="px-2 py-1 text-[10px] text-muted">Your agents</SelectLabel>
- <SelectItem
- v-for="agent in acpAgents"
- :key="agent.id"
- :value="`acp:${agent.id}`"
- :class="selectItem({ class: itemClass ?? 'rounded px-2 py-1 text-[11px]' })"
- >
- <SelectItemText>{{ agent.name }}</SelectItemText>
- </SelectItem>
- </SelectGroup>
- <SelectSeparator class="mx-1 my-1 h-px bg-border" />
- </template>
- <SelectGroup>
- <SelectLabel v-if="acpAgents.length" class="px-2 py-1 text-[10px] text-muted">
- API key
- </SelectLabel>
- <SelectItem
- v-for="provider in AI_PROVIDERS"
- :key="provider.id"
- :value="provider.id"
- :class="selectItem({ class: itemClass ?? 'rounded px-2 py-1 text-[11px]' })"
- >
- <SelectItemText>{{ provider.name }}</SelectItemText>
- </SelectItem>
- </SelectGroup>
- </SelectViewport>
- </SelectContent>
- </SelectPortal>
- </SelectRoot>
+ <AppGroupedSelect
+ v-model="providerID"
+ :groups="groups"
+ :display-value="displayName"
+ :ui="ui"
+ :test-id="testId"
+ />
</template>
diff --git a/src/components/chat/ProviderSelectField.vue b/src/components/chat/ProviderSelectField.vue
new file mode 100644
index 000000000..26f11da16
--- /dev/null
+++ b/src/components/chat/ProviderSelectField.vue
@@ -0,0 +1,18 @@
+<script setup lang="ts">
+import ProviderSelect from '@/components/chat/ProviderSelect.vue'
+
+const { testId = 'provider-selector' } = defineProps<{
+ testId?: string
+}>()
+</script>
+
+<template>
+ <ProviderSelect
+ :test-id="testId"
+ :ui="{
+ trigger:
+ 'w-full justify-between rounded border border-border bg-input px-2.5 py-1.5 text-xs text-surface',
+ item: 'rounded px-2 py-1.5 text-[11px]'
+ }"
+ />
+</template>
diff --git a/src/components/chat/ProviderSettings.vue b/src/components/chat/ProviderSettings.vue
index e39f171ce..86790cc9a 100644
--- a/src/components/chat/ProviderSettings.vue
+++ b/src/components/chat/ProviderSettings.vue
@@ -12,10 +12,13 @@ import {
} from 'reka-ui'
import { computed, ref, watch } from 'vue'
-import ProviderSelect from '@/components/chat/ProviderSelect.vue'
+import ProviderSelectField from '@/components/chat/ProviderSelectField.vue'
import { uiInput } from '@/components/ui/input'
+import { usePopoverUI } from '@/components/ui/popover'
import { useAIChat } from '@/composables/use-chat'
+const cls = usePopoverUI({ content: 'isolate z-[51] w-64 p-3' })
+
const {
providerID,
providerDef,
@@ -108,7 +111,7 @@ function clearUnsplashKey() {
align="end"
:collision-padding="16"
:avoid-collisions="true"
- class="isolate z-[51] w-64 rounded-lg border border-border bg-panel p-3 shadow-lg"
+ :class="cls.content"
@interact-outside="
(e: Event) => {
const target = e.target as HTMLElement | null
@@ -123,7 +126,7 @@ function clearUnsplashKey() {
<div class="flex flex-col gap-2.5">
<h3 class="text-[11px] font-semibold text-surface">AI Provider</h3>
- <ProviderSelect test-id="provider-settings-provider" />
+ <ProviderSelectField test-id="provider-settings-provider" />
<!-- Max output tokens -->
<div v-if="!isACP" class="flex flex-col gap-1">
diff --git a/src/components/chat/ProviderSetup.vue b/src/components/chat/ProviderSetup.vue
index e6ddd8b2b..2f65b8a0d 100644
--- a/src/components/chat/ProviderSetup.vue
+++ b/src/components/chat/ProviderSetup.vue
@@ -1,7 +1,7 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
-import ProviderSelect from '@/components/chat/ProviderSelect.vue'
+import ProviderSelectField from '@/components/chat/ProviderSelectField.vue'
import { uiInput } from '@/components/ui/input'
import { useAIChat } from '@/composables/use-chat'
import { ACP_AGENTS } from '@open-pencil/core'
@@ -39,11 +39,7 @@ function save() {
<p class="mb-5 text-center text-xs text-muted">Connect an AI provider to start chatting.</p>
<form v-if="!isACP" class="flex w-full flex-col gap-2" @submit.prevent="save">
- <ProviderSelect
- test-id="provider-selector"
- trigger-class="w-full justify-between rounded border border-border bg-input px-2.5 py-1.5 text-xs text-surface"
- item-class="rounded px-2 py-1.5 text-[11px]"
- />
+ <ProviderSelectField test-id="provider-selector" />
<!-- Base URL (OpenAI-compatible only) -->
<input
@@ -85,11 +81,7 @@ function save() {
<!-- ACP agent — no API key needed -->
<div v-else class="flex w-full flex-col gap-2">
- <ProviderSelect
- test-id="provider-selector"
- trigger-class="w-full justify-between rounded border border-border bg-input px-2.5 py-1.5 text-xs text-surface"
- item-class="rounded px-2 py-1.5 text-[11px]"
- />
+ <ProviderSelectField test-id="provider-selector" />
<p class="text-center text-[10px] leading-relaxed text-muted">
Uses your existing {{ acpAgent?.name }} subscription. Make sure
diff --git a/src/components/properties/ExportSection.vue b/src/components/properties/ExportSection.vue
index 9578c2548..adb9b52fe 100644
--- a/src/components/properties/ExportSection.vue
+++ b/src/components/properties/ExportSection.vue
@@ -1,7 +1,7 @@
<script setup lang="ts">
import { ref, computed, watch, onScopeDispose } from 'vue'
-import AppSelect from '@/components/AppSelect.vue'
+import AppSelect from '@/components/ui/AppSelect.vue'
import { iconButton } from '@/components/ui/icon-button'
import { sectionLabel, sectionWrapper } from '@/components/ui/section'
import { useEditorStore } from '@/stores/editor'
@@ -94,7 +94,7 @@ onScopeDispose(() => {
:options="FORMAT_OPTIONS"
@update:model-value="updateFormat(i, $event as ExportFormat)"
/>
- <button :class="iconButton({ class: 'shrink-0' })" @click="removeSetting(i)">−</button>
+ <button :class="iconButton({ ui: { base: 'shrink-0' } })" @click="removeSetting(i)">−</button>
</div>
<button
diff --git a/src/components/properties/PositionSection.vue b/src/components/properties/PositionSection.vue
index d6f1d1eb0..64472b5c0 100644
--- a/src/components/properties/PositionSection.vue
+++ b/src/components/properties/PositionSection.vue
@@ -2,7 +2,7 @@
import { computed } from 'vue'
import ScrubInput from '@/components/ScrubInput.vue'
-import Tip from '@/components/Tip.vue'
+import Tip from '@/components/ui/Tip.vue'
import { iconButton } from '@/components/ui/icon-button'
import { sectionWrapper } from '@/components/ui/section'
import { useNodeProps } from '@open-pencil/vue'
@@ -149,7 +149,7 @@ const ids = computed(() => nodes.value.map((n) => n.id))
</ScrubInput>
<Tip label="Flip horizontal">
<button
- :class="iconButton({ size: 'md', class: 'shrink-0' })"
+ :class="iconButton({ size: 'md', ui: { base: 'shrink-0' } })"
data-test-id="position-flip-horizontal"
@click="store.flipNodes(ids, 'horizontal')"
>
@@ -158,7 +158,7 @@ const ids = computed(() => nodes.value.map((n) => n.id))
</Tip>
<Tip label="Flip vertical">
<button
- :class="iconButton({ size: 'md', class: 'shrink-0' })"
+ :class="iconButton({ size: 'md', ui: { base: 'shrink-0' } })"
data-test-id="position-flip-vertical"
@click="store.flipNodes(ids, 'vertical')"
>
@@ -167,7 +167,7 @@ const ids = computed(() => nodes.value.map((n) => n.id))
</Tip>
<Tip label="Rotate 90°">
<button
- :class="iconButton({ size: 'md', class: 'shrink-0' })"
+ :class="iconButton({ size: 'md', ui: { base: 'shrink-0' } })"
data-test-id="position-rotate-90"
@click="store.rotateNodes(ids, 90)"
>
diff --git a/src/components/properties/StrokeSection.vue b/src/components/properties/StrokeSection.vue
index 684af8c75..740b2dee1 100644
--- a/src/components/properties/StrokeSection.vue
+++ b/src/components/properties/StrokeSection.vue
@@ -8,14 +8,14 @@ import {
DropdownMenuPortal
} from 'reka-ui'
-import AppSelect from '@/components/AppSelect.vue'
+import AppSelect from '@/components/ui/AppSelect.vue'
import ColorInput from '@/components/ColorInput.vue'
import ScrubInput from '@/components/ScrubInput.vue'
-import Tip from '@/components/Tip.vue'
+import Tip from '@/components/ui/Tip.vue'
import { iconButton } from '@/components/ui/icon-button'
import { sectionLabel, sectionWrapper } from '@/components/ui/section'
import { PropertyListRoot, useEditor } from '@open-pencil/vue'
-import { menuContent, menuItem } from '@/components/ui/menu'
+import { menu, useMenuUI } from '@/components/ui/menu'
import type { SceneNode, Stroke } from '@open-pencil/core'
@@ -41,6 +41,10 @@ const SIDE_OPTIONS: { value: StrokeSides; label: string }[] = [
const BORDER_SIDES = ['top', 'right', 'bottom', 'left'] as const
const sideMenuOpen = ref(false)
+const sideMenuCls = useMenuUI({
+ content: 'min-w-[140px] rounded-md p-0.5',
+ item: 'relative px-2'
+})
function updateAlign(align: Stroke['align'], activeNode: SceneNode) {
const strokes = activeNode.strokes.map((s) => ({ ...s, align }))
@@ -184,7 +188,7 @@ const DEFAULT_STROKE: Stroke = {
<icon-lucide-eye v-if="stroke.visible" class="size-3.5" />
<icon-lucide-eye-off v-else class="size-3.5" />
</button>
- <button :class="iconButton({ class: 'shrink-0' })" @click="remove(i)">−</button>
+ <button :class="iconButton({ ui: { base: 'shrink-0' } })" @click="remove(i)">−</button>
</div>
<!-- Stroke details -->
@@ -236,15 +240,11 @@ const DEFAULT_STROKE: Stroke = {
</DropdownMenuTrigger>
</Tip>
<DropdownMenuPortal>
- <DropdownMenuContent
- :side-offset="4"
- align="end"
- :class="menuContent({ class: 'min-w-[140px] rounded-md p-0.5' })"
- >
+ <DropdownMenuContent :side-offset="4" align="end" :class="sideMenuCls.content">
<DropdownMenuItem
v-for="opt in SIDE_OPTIONS"
:key="opt.value"
- :class="menuItem({ justify: 'start', class: 'relative px-2' })"
+ :class="menu({ justify: 'start' }).item({ class: sideMenuCls.item })"
@click="selectSide(opt.value, activeNode)"
>
<icon-lucide-check
diff --git a/src/components/ui/AppGroupedSelect.vue b/src/components/ui/AppGroupedSelect.vue
new file mode 100644
index 000000000..1229ce0eb
--- /dev/null
+++ b/src/components/ui/AppGroupedSelect.vue
@@ -0,0 +1,93 @@
+<script setup lang="ts" generic="T extends string | number">
+import {
+ SelectContent,
+ SelectGroup,
+ SelectItem,
+ SelectItemText,
+ SelectLabel,
+ SelectPortal,
+ SelectRoot,
+ SelectSeparator,
+ SelectTrigger,
+ SelectViewport
+} from 'reka-ui'
+import { computed } from 'vue'
+
+import { selectContent, selectItem, selectTrigger } from '@/components/ui/select'
+import { useComponentUI } from '@/components/ui/use-component-ui'
+
+interface SelectOption<TValue extends string | number> {
+ value: TValue
+ label: string
+}
+
+interface SelectGroupDef<TValue extends string | number> {
+ label?: string
+ items: SelectOption<TValue>[]
+}
+
+interface GroupedSelectUi {
+ trigger?: string
+ content?: string
+ item?: string
+ label?: string
+ separator?: string
+}
+
+const { groups, displayValue, ui, testId } = defineProps<{
+ groups: SelectGroupDef<T>[]
+ displayValue: string
+ ui?: GroupedSelectUi
+ testId?: string
+}>()
+
+const modelValue = defineModel<T>({ required: true })
+
+const uiProp = useComponentUI(ui, {
+ trigger:
+ 'w-full justify-between rounded border border-border bg-input px-2 py-1 text-[11px] text-surface',
+ content: 'isolate z-[52]',
+ item: 'rounded px-2 py-1 text-[11px]',
+ label: 'px-2 py-1 text-[10px] text-muted',
+ separator: 'mx-1 my-1 h-px bg-border'
+})
+
+const cls = computed(() => ({
+ trigger: selectTrigger({ class: uiProp.value.trigger }),
+ content: selectContent({ radius: 'lg', padding: 'md', class: uiProp.value.content }),
+ item: selectItem({ class: uiProp.value.item }),
+ label: uiProp.value.label,
+ separator: uiProp.value.separator
+}))
+</script>
+
+<template>
+ <SelectRoot v-model="modelValue">
+ <SelectTrigger :data-test-id="testId" :class="cls.trigger">
+ <slot name="value">{{ displayValue }}</slot>
+ <icon-lucide-chevron-down class="size-2.5 shrink-0 text-muted" />
+ </SelectTrigger>
+ <SelectPortal>
+ <SelectContent position="popper" :side-offset="4" :class="cls.content">
+ <SelectViewport>
+ <template v-for="(group, index) in groups" :key="index">
+ <SelectGroup>
+ <SelectLabel v-if="group.label" :class="cls.label">
+ {{ group.label }}
+ </SelectLabel>
+ <SelectItem
+ v-for="item in group.items"
+ :key="String(item.value)"
+ :value="item.value"
+ :class="cls.item"
+ >
+ <SelectItemText>{{ item.label }}</SelectItemText>
+ </SelectItem>
+ </SelectGroup>
+ <SelectSeparator v-if="index < groups.length - 1" :class="cls.separator" />
+ </template>
+ </SelectViewport>
+ </SelectContent>
+ </SelectPortal>
+ </SelectRoot>
+</template>
diff --git a/src/components/AppSelect.vue b/src/components/ui/AppSelect.vue
similarity index 58%
rename from src/components/AppSelect.vue
rename to src/components/ui/AppSelect.vue
index 9c4cb6fcb..7a37f633e 100644
--- a/src/components/AppSelect.vue
+++ b/src/components/ui/AppSelect.vue
@@ -12,21 +12,36 @@ import {
} from 'reka-ui'
import { selectContent, selectItem, selectTrigger } from '@/components/ui/select'
+import { useComponentUI } from '@/components/ui/use-component-ui'
-const { options, placeholder } = defineProps<{
+interface SelectUi {
+ trigger?: string
+ content?: string
+ viewport?: string
+ item?: string
+ indicator?: string
+}
+
+const { options, placeholder, ui } = defineProps<{
options: { value: T; label: string }[]
placeholder?: string
+ ui?: SelectUi
}>()
const modelValue = defineModel<T>({ required: true })
+
+const cls = useComponentUI(ui, {
+ trigger: 'min-w-0 flex-1 rounded px-1.5 py-1 text-xs',
+ content: 'max-h-56',
+ viewport: 'p-0.5',
+ item: 'rounded py-1.5 pr-2 pl-6 text-xs',
+ indicator: 'absolute left-1.5 inline-flex items-center justify-center'
+})
</script>
<template>
<SelectRoot v-model="modelValue">
- <SelectTrigger
- data-test-id="app-select-trigger"
- :class="selectTrigger({ class: 'min-w-0 flex-1 rounded px-1.5 py-1 text-xs' })"
- >
+ <SelectTrigger data-test-id="app-select-trigger" :class="selectTrigger({ class: cls.trigger })">
<SelectValue :placeholder="placeholder" />
<icon-lucide-chevron-down class="ml-1 size-3 shrink-0 text-muted" />
</SelectTrigger>
@@ -34,16 +49,16 @@ const modelValue = defineModel<T>({ required: true })
<SelectContent
position="popper"
:side-offset="2"
- :class="selectContent({ class: 'max-h-56' })"
+ :class="selectContent({ class: cls.content })"
>
- <SelectViewport class="p-0.5">
+ <SelectViewport :class="cls.viewport">
<SelectItem
v-for="opt in options"
:key="String(opt.value)"
:value="opt.value"
- :class="selectItem({ class: 'rounded py-1.5 pr-2 pl-6 text-xs' })"
+ :class="selectItem({ class: cls.item })"
>
- <SelectItemIndicator class="absolute left-1.5 inline-flex items-center justify-center">
+ <SelectItemIndicator :class="cls.indicator">
<icon-lucide-check class="size-3 text-accent" />
</SelectItemIndicator>
<SelectItemText>{{ opt.label }}</SelectItemText>
diff --git a/src/components/Tip.vue b/src/components/ui/Tip.vue
similarity index 68%
rename from src/components/Tip.vue
rename to src/components/ui/Tip.vue
index e5ea11029..33db56585 100644
--- a/src/components/Tip.vue
+++ b/src/components/ui/Tip.vue
@@ -1,6 +1,10 @@
<script setup lang="ts">
import { TooltipContent, TooltipPortal, TooltipRoot, TooltipTrigger } from 'reka-ui'
+import { useTooltipUI } from '@/components/ui/tooltip'
+
+const cls = useTooltipUI({ content: 'animate-in zoom-in-95 fade-in' })
+
const { side = 'top' } = defineProps<{
label: string
side?: 'top' | 'bottom' | 'left' | 'right'
@@ -13,11 +17,7 @@ const { side = 'top' } = defineProps<{
<slot />
</TooltipTrigger>
<TooltipPortal>
- <TooltipContent
- :side="side"
- :side-offset="4"
- class="z-50 animate-in rounded bg-neutral-800 px-2 py-1 text-xs text-white shadow-lg zoom-in-95 fade-in"
- >
+ <TooltipContent :side="side" :side-offset="4" :class="cls.content">
{{ label }}
</TooltipContent>
</TooltipPortal>
diff --git a/src/components/ui/button.ts b/src/components/ui/button.ts
index 2eca2e856..8445b62eb 100644
--- a/src/components/ui/button.ts
+++ b/src/components/ui/button.ts
@@ -1,6 +1,8 @@
import { twMerge } from 'tailwind-merge'
import { tv } from 'tailwind-variants'
+import { useComponentUI } from '@/components/ui/use-component-ui'
+
const button = tv({
base: 'inline-flex items-center justify-center transition-colors select-none',
variants: {
@@ -48,7 +50,10 @@ export function uiButton(options?: {
shape?: 'square' | 'rounded' | 'pill'
size?: 'sm' | 'md' | 'icon' | 'iconSm'
bordered?: boolean
- class?: string
+ ui?: {
+ base?: string
+ }
}) {
- return twMerge(button(options), options?.class)
+ const ui = useComponentUI(options?.ui, { base: '' })
+ return twMerge(button(options), ui.value.base)
}
diff --git a/src/components/ui/dialog.ts b/src/components/ui/dialog.ts
new file mode 100644
index 000000000..c74482e57
--- /dev/null
+++ b/src/components/ui/dialog.ts
@@ -0,0 +1,28 @@
+import { tv } from 'tailwind-variants'
+
+export const dialog = tv({
+ slots: {
+ overlay: 'fixed inset-0 z-40 bg-black/50',
+ content:
+ 'fixed top-1/2 left-1/2 z-50 -translate-x-1/2 -translate-y-1/2 rounded-xl border border-border bg-panel shadow-2xl outline-none',
+ title: 'text-sm font-semibold text-surface',
+ description: 'text-xs text-muted'
+ }
+})
+
+interface DialogUi {
+ overlay?: string
+ content?: string
+ title?: string
+ description?: string
+}
+
+export function useDialogUI(ui?: DialogUi) {
+ const cls = dialog()
+ return {
+ overlay: cls.overlay({ class: ui?.overlay }),
+ content: cls.content({ class: ui?.content }),
+ title: cls.title({ class: ui?.title }),
+ description: cls.description({ class: ui?.description })
+ }
+}
diff --git a/src/components/ui/icon-button.ts b/src/components/ui/icon-button.ts
index 01cb70359..748893b0d 100644
--- a/src/components/ui/icon-button.ts
+++ b/src/components/ui/icon-button.ts
@@ -1,6 +1,9 @@
import { tv } from 'tailwind-variants'
+import { computed } from 'vue'
-export const iconButton = tv({
+import { useComponentUI } from '@/components/ui/use-component-ui'
+
+const iconButtonStyles = tv({
base: 'flex cursor-pointer items-center justify-center rounded border-none bg-transparent text-muted hover:bg-hover hover:text-surface',
variants: {
size: {
@@ -10,3 +13,14 @@ export const iconButton = tv({
},
defaultVariants: { size: 'sm' }
})
+
+export function iconButton(options?: {
+ size?: 'sm' | 'md'
+ ui?: {
+ base?: string
+ }
+}) {
+ const ui = useComponentUI(options?.ui, { base: '' })
+ const classes = computed(() => iconButtonStyles({ size: options?.size, class: ui.value.base }))
+ return classes.value
+}
diff --git a/src/components/ui/input.ts b/src/components/ui/input.ts
index 3ed8266f8..b09820271 100644
--- a/src/components/ui/input.ts
+++ b/src/components/ui/input.ts
@@ -1,6 +1,8 @@
import { twMerge } from 'tailwind-merge'
import { tv } from 'tailwind-variants'
+import { useComponentUI } from '@/components/ui/use-component-ui'
+
const input = tv({
base: 'w-full rounded border border-border bg-input text-surface outline-none focus:border-accent',
variants: {
@@ -14,6 +16,12 @@ const input = tv({
}
})
-export function uiInput(options?: { size?: 'sm' | 'md'; class?: string }) {
- return twMerge(input(options), options?.class)
+export function uiInput(options?: {
+ size?: 'sm' | 'md'
+ ui?: {
+ base?: string
+ }
+}) {
+ const ui = useComponentUI(options?.ui, { base: '' })
+ return twMerge(input(options), ui.value.base)
}
diff --git a/src/components/ui/menu.ts b/src/components/ui/menu.ts
index e0a22cd2d..539cb8d15 100644
--- a/src/components/ui/menu.ts
+++ b/src/components/ui/menu.ts
@@ -1,21 +1,34 @@
-import { twMerge } from 'tailwind-merge'
import { tv } from 'tailwind-variants'
-const content = tv({
- base: 'z-50 rounded-lg border border-border bg-panel p-1 shadow-lg'
-})
-
-const item = tv({
- base: 'flex cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-xs outline-none select-none data-[disabled]:cursor-default data-[disabled]:text-muted/50 data-[highlighted]:bg-hover',
+export const menu = tv({
+ slots: {
+ content: 'z-50 rounded-lg border border-border bg-panel p-1 shadow-lg',
+ item: 'flex cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-xs outline-none select-none data-[disabled]:cursor-default data-[disabled]:text-muted/50 data-[highlighted]:bg-hover',
+ separator: 'mx-1 my-1 h-px bg-border',
+ shortcut: 'text-[11px] text-muted',
+ icon: 'size-3 text-muted',
+ subTrigger:
+ 'flex cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-xs outline-none select-none'
+ },
variants: {
tone: {
- default: 'text-surface',
- component:
- 'text-component data-[disabled]:text-component/40 data-[highlighted]:bg-component/12'
+ default: {
+ item: 'text-surface',
+ subTrigger: 'text-surface'
+ },
+ component: {
+ item: 'text-component data-[disabled]:text-component/40 data-[highlighted]:bg-component/12',
+ shortcut: 'text-component/60',
+ subTrigger: 'text-component'
+ }
},
justify: {
- between: 'justify-between gap-6',
- start: 'justify-start'
+ between: {
+ item: 'justify-between gap-6'
+ },
+ start: {
+ item: 'justify-start'
+ }
}
},
defaultVariants: {
@@ -24,12 +37,29 @@ const item = tv({
}
})
-const separator = tv({
- base: 'mx-1 my-1 h-px bg-border'
-})
+interface MenuUi {
+ content?: string
+ item?: string
+ separator?: string
+ shortcut?: string
+ icon?: string
+ subTrigger?: string
+}
+
+export function useMenuUI(ui?: MenuUi) {
+ const cls = menu()
+ return {
+ content: cls.content({ class: ui?.content }),
+ item: cls.item({ class: ui?.item }),
+ separator: cls.separator({ class: ui?.separator }),
+ shortcut: cls.shortcut({ class: ui?.shortcut }),
+ icon: cls.icon({ class: ui?.icon }),
+ subTrigger: cls.subTrigger({ class: ui?.subTrigger })
+ }
+}
export function menuContent(options?: { class?: string }) {
- return twMerge(content(), options?.class)
+ return menu().content({ class: options?.class })
}
export function menuItem(options?: {
@@ -37,9 +67,9 @@ export function menuItem(options?: {
justify?: 'between' | 'start'
class?: string
}) {
- return twMerge(item(options), options?.class)
+ return menu(options).item({ class: options?.class })
}
export function menuSeparator(options?: { class?: string }) {
- return twMerge(separator(), options?.class)
+ return menu().separator({ class: options?.class })
}
diff --git a/src/components/ui/popover.ts b/src/components/ui/popover.ts
new file mode 100644
index 000000000..b6c05d644
--- /dev/null
+++ b/src/components/ui/popover.ts
@@ -0,0 +1,27 @@
+import { tv } from 'tailwind-variants'
+
+export const popover = tv({
+ slots: {
+ content: 'z-[100] rounded-lg border border-border bg-panel shadow-xl',
+ header: '',
+ body: '',
+ footer: ''
+ }
+})
+
+interface PopoverUi {
+ content?: string
+ header?: string
+ body?: string
+ footer?: string
+}
+
+export function usePopoverUI(ui?: PopoverUi) {
+ const cls = popover()
+ return {
+ content: cls.content({ class: ui?.content }),
+ header: cls.header({ class: ui?.header }),
+ body: cls.body({ class: ui?.body }),
+ footer: cls.footer({ class: ui?.footer })
+ }
+}
diff --git a/src/components/ui/select.ts b/src/components/ui/select.ts
index a30fe0be4..6f8a90c9f 100644
--- a/src/components/ui/select.ts
+++ b/src/components/ui/select.ts
@@ -33,6 +33,20 @@ const item = tv({
base: 'relative flex cursor-pointer items-center text-surface outline-none data-[highlighted]:bg-hover'
})
+interface SelectUi {
+ trigger?: string
+ content?: string
+ item?: string
+}
+
+export function useSelectUI(ui?: SelectUi) {
+ return {
+ trigger: twMerge(trigger(), ui?.trigger),
+ content: twMerge(content(), ui?.content),
+ item: twMerge(item(), ui?.item)
+ }
+}
+
export function selectTrigger(options?: { class?: string }) {
return twMerge(trigger(), options?.class)
}
diff --git a/src/components/ui/tooltip.ts b/src/components/ui/tooltip.ts
new file mode 100644
index 000000000..9cd772493
--- /dev/null
+++ b/src/components/ui/tooltip.ts
@@ -0,0 +1,19 @@
+import { tv } from 'tailwind-variants'
+
+export const tooltip = tv({
+ slots: {
+ content:
+ 'z-50 rounded-md border border-border bg-panel px-2 py-1 text-xs text-surface shadow-lg'
+ }
+})
+
+interface TooltipUi {
+ content?: string
+}
+
+export function useTooltipUI(ui?: TooltipUi) {
+ const cls = tooltip()
+ return {
+ content: cls.content({ class: ui?.content })
+ }
+}
diff --git a/src/components/ui/use-component-ui.ts b/src/components/ui/use-component-ui.ts
new file mode 100644
index 000000000..d4c529ee5
--- /dev/null
+++ b/src/components/ui/use-component-ui.ts
@@ -0,0 +1,5 @@
+import { computed } from 'vue'
+
+export function useComponentUI<T extends object>(ui: Partial<T> | undefined, defaults: T) {
+ return computed(() => ({ ...defaults, ...ui }))
+}
diff --git a/src/composables/use-action-toast.ts b/src/composables/use-action-toast.ts
new file mode 100644
index 000000000..75b3be8fc
--- /dev/null
+++ b/src/composables/use-action-toast.ts
@@ -0,0 +1,20 @@
+import { ACTION_TOAST_DURATION } from '@/constants'
+import { useEditorStore } from '@/stores/editor'
+
+let toastTimer: ReturnType<typeof setTimeout> | undefined
+
+export function useActionToast() {
+ const store = useEditorStore()
+
+ function showActionToast(label: string) {
+ store.state.actionToast = label
+ clearTimeout(toastTimer)
+ toastTimer = setTimeout(() => {
+ store.state.actionToast = null
+ }, ACTION_TOAST_DURATION)
+ }
+
+ return {
+ showActionToast
+ }
+}
diff --git a/src/composables/use-app-menu.ts b/src/composables/use-app-menu.ts
new file mode 100644
index 000000000..aedbbe311
--- /dev/null
+++ b/src/composables/use-app-menu.ts
@@ -0,0 +1,138 @@
+import { computed } from 'vue'
+
+import { useEditorStore } from '@/stores/editor'
+import { useEditorCommands, useMenuModel } from '@open-pencil/vue'
+
+export function useAppMenu(mod: string) {
+ const store = useEditorStore()
+ const { menuItem: commandMenuItem } = useEditorCommands()
+ const { appMenu } = useMenuModel()
+
+ const textMenu = [
+ { label: 'Bold', shortcut: `${mod}B` },
+ { label: 'Italic', shortcut: `${mod}I` },
+ { label: 'Underline', shortcut: `${mod}U` }
+ ]
+
+ const fileMenu = [
+ {
+ label: 'New',
+ shortcut: `${mod}N`,
+ action: () => import('@/stores/tabs').then((m) => m.createTab())
+ },
+ { label: 'Open…', shortcut: `${mod}O` },
+ { separator: true as const },
+ { label: 'Save', shortcut: `${mod}S` },
+ { label: 'Save as…', shortcut: `${mod}⇧S` },
+ { separator: true as const },
+ {
+ label: 'Export selection…',
+ shortcut: `${mod}⇧E`,
+ disabled: store.state.selectedIds.size === 0
+ },
+ { separator: true as const },
+ {
+ label: 'Auto-save to local file',
+ get checked() {
+ return store.state.autosaveEnabled
+ },
+ onCheckedChange: (value: boolean) => {
+ store.state.autosaveEnabled = value
+ }
+ }
+ ]
+
+ const topMenus = computed(() => [
+ { label: 'File', items: fileMenu },
+ ...appMenu.value.map((menu) => {
+ if (menu.label === 'View') {
+ return {
+ label: 'View',
+ items: [
+ commandMenuItem('view.zoom100', `${mod}0`),
+ commandMenuItem('view.zoomFit', `${mod}1`),
+ commandMenuItem('view.zoomSelection', `${mod}2`),
+ {
+ label: 'Zoom in',
+ shortcut: `${mod}=`,
+ action: () => store.applyZoom(-100, window.innerWidth / 2, window.innerHeight / 2)
+ },
+ {
+ label: 'Zoom out',
+ shortcut: `${mod}-`,
+ action: () => store.applyZoom(100, window.innerWidth / 2, window.innerHeight / 2)
+ },
+ { separator: true as const },
+ {
+ label: 'Performance profiler',
+ get checked() {
+ return store.renderer?.profiler.hudVisible ?? false
+ },
+ onCheckedChange: () => {
+ store.toggleProfiler()
+ }
+ }
+ ]
+ }
+ }
+
+ if (menu.label === 'Edit') {
+ return {
+ label: 'Edit',
+ items: [
+ commandMenuItem('edit.undo', `${mod}Z`),
+ commandMenuItem('edit.redo', `${mod}⇧Z`),
+ { separator: true as const },
+ { label: 'Copy', shortcut: `${mod}C` },
+ { label: 'Paste', shortcut: `${mod}V` },
+ commandMenuItem('selection.duplicate', `${mod}D`),
+ commandMenuItem('selection.delete', '⌫'),
+ { separator: true as const },
+ commandMenuItem('selection.selectAll', `${mod}A`)
+ ]
+ }
+ }
+
+ if (menu.label === 'Object') {
+ return {
+ label: 'Object',
+ items: [
+ commandMenuItem('selection.group', `${mod}G`),
+ commandMenuItem('selection.ungroup', `${mod}⇧G`),
+ { separator: true as const },
+ commandMenuItem('selection.createComponent', `${mod}⌥K`),
+ commandMenuItem('selection.createComponentSet'),
+ commandMenuItem('selection.detachInstance'),
+ { separator: true as const },
+ commandMenuItem('selection.bringToFront', ']'),
+ commandMenuItem('selection.sendToBack', '[')
+ ]
+ }
+ }
+
+ if (menu.label === 'Arrange') {
+ return {
+ label: 'Arrange',
+ items: [
+ commandMenuItem('selection.wrapInAutoLayout', '⇧A'),
+ { separator: true as const },
+ { label: 'Align left', shortcut: '⌥A' },
+ { label: 'Align center', shortcut: '⌥H' },
+ { label: 'Align right', shortcut: '⌥D' },
+ { separator: true as const },
+ { label: 'Align top', shortcut: '⌥W' },
+ { label: 'Align middle', shortcut: '⌥V' },
+ { label: 'Align bottom', shortcut: '⌥S' }
+ ]
+ }
+ }
+
+ return menu
+ }),
+ { label: 'Text', items: textMenu }
+ ])
+
+ return {
+ topMenus
+ }
+}
diff --git a/src/composables/use-keyboard.ts b/src/composables/use-keyboard.ts
index 2e3d67fd2..c8230ed37 100644
--- a/src/composables/use-keyboard.ts
+++ b/src/composables/use-keyboard.ts
@@ -4,7 +4,11 @@ import { computed } from 'vue'
import { useAIChat } from '@/composables/use-chat'
import { TOOL_SHORTCUTS, useEditorStore } from '@/stores/editor'
import { closeTab, createTab, activeTab as activeTabRef } from '@/stores/tabs'
-import { extractImageFilesFromClipboard, useEditorCommands, useViewportKind } from '@open-pencil/vue'
+import {
+ extractImageFilesFromClipboard,
+ useEditorCommands,
+ useViewportKind
+} from '@open-pencil/vue'
import { openFileDialog } from './use-menu'