From e91ea4b061097f2db161645827a9eb2072e057b5 Mon Sep 17 00:00:00 2001 From: sadkodev Date: Thu, 16 Jul 2026 22:12:50 -0400 Subject: [PATCH 01/12] feat(keyboard): add Figma-style opacity shortcuts 1-9/0 Add opacity keyboard shortcuts matching Figma: pressing Digit1-Digit9 sets the selected layers to 10%-90% opacity, and Digit0 sets 100%. - Add 'selection.setOpacity' EditorCommandId with registry metadata (shortcut display '1-9, 0') so it appears in the command cheatsheet - Implement the command in selection.ts using editor.undo.runBatch + updateNodeWithUndo, following the toggleVisibility/setBlendMode pattern - Add setOpacityTarget closure in useEditorCommands so the external keyboard handler can inject the digit value before runCommand - Add canSetOpacity capability (enabled when there is a selection) - Add bindOpacityKeys handler in src/app/shell/keyboard/opacity.ts, following the nudging.ts external-handler pattern since the opacity value comes from event.code and cannot be expressed as a fixed keybinding in the registry - Guard against text editing, number field focus, and modifier keys - Add i18n label 'setOpacity' across all 8 locales - Add unit tests for single/multi selection, undo batch, and no-op --- CHANGELOG.md | 1 + packages/vue/src/editor/commands/context.ts | 1 + packages/vue/src/editor/commands/registry.ts | 1 + packages/vue/src/editor/commands/selection.ts | 21 ++++- packages/vue/src/editor/commands/types.ts | 1 + packages/vue/src/editor/commands/use.ts | 9 +- .../src/editor/selection-capabilities/use.ts | 1 + .../vue/src/i18n/locales/de/commands.json | 1 + .../vue/src/i18n/locales/es/commands.json | 1 + .../vue/src/i18n/locales/fr/commands.json | 1 + .../vue/src/i18n/locales/it/commands.json | 1 + .../vue/src/i18n/locales/ja/commands.json | 1 + .../vue/src/i18n/locales/pl/commands.json | 1 + .../vue/src/i18n/locales/ru/commands.json | 1 + .../vue/src/i18n/locales/zh-cn/commands.json | 1 + packages/vue/src/i18n/messages/commands.ts | 1 + src/app/shell/keyboard/opacity.ts | 42 +++++++++ src/app/shell/keyboard/use.ts | 4 +- tests/engine/editor/opacity.test.ts | 89 +++++++++++++++++++ 19 files changed, 176 insertions(+), 3 deletions(-) create mode 100644 src/app/shell/keyboard/opacity.ts create mode 100644 tests/engine/editor/opacity.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 953ff17e1..64cd0bb10 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ ### Changed +- Add Figma-style opacity keyboard shortcuts (`1`-`9` for 10%-90%, `0` for 100%) on the selected layers, with undo-batched multi-selection support. - Add Figma-style page management in the Pages panel, including rename/delete actions and drag-and-drop page reordering. - Add DOM/CSS import and authoring support so HTML, CSS, Tailwind, and JSX can be converted into editable OpenPencil documents from the app, CLI, and SDK. - Add Tailwind class serialization for DOM/CSS HTML export in the SDK and CLI. diff --git a/packages/vue/src/editor/commands/context.ts b/packages/vue/src/editor/commands/context.ts index 634d70899..cb0eaecd3 100644 --- a/packages/vue/src/editor/commands/context.ts +++ b/packages/vue/src/editor/commands/context.ts @@ -16,4 +16,5 @@ export type EditorCommandMapOptions = { messages: CommandMessagesStore otherPages: ComputedRef> moveSelectionToPage: (pageId: string) => void + getOpacityTarget: () => number } diff --git a/packages/vue/src/editor/commands/registry.ts b/packages/vue/src/editor/commands/registry.ts index 77e4de0ee..319f7c2ec 100644 --- a/packages/vue/src/editor/commands/registry.ts +++ b/packages/vue/src/editor/commands/registry.ts @@ -96,6 +96,7 @@ export const EDITOR_COMMAND_METADATA = { 'selection.outlineText': { contextTestId: 'context-outline-text' }, 'selection.outlineStroke': { contextTestId: 'context-outline-stroke' }, 'selection.moveToPage': {}, + 'selection.setOpacity': { shortcut: '1-9, 0' }, 'view.zoom100': { keybinding: '$mod+Digit0' }, 'view.zoomFit': { keybinding: ['$mod+Digit1', 'Shift+Digit1'] }, 'view.zoomSelection': { keybinding: ['$mod+Digit2', 'Shift+Digit2'] } diff --git a/packages/vue/src/editor/commands/selection.ts b/packages/vue/src/editor/commands/selection.ts index 151984b02..8bcf70a32 100644 --- a/packages/vue/src/editor/commands/selection.ts +++ b/packages/vue/src/editor/commands/selection.ts @@ -29,7 +29,8 @@ export function createSelectionCommands({ capabilities, messages: t, otherPages, - moveSelectionToPage + moveSelectionToPage, + getOpacityTarget }: EditorCommandMapOptions): Record { return { 'selection.selectAll': { @@ -261,6 +262,24 @@ export function createSelectionCommands({ run: () => { moveSelectionToPage(otherPages.value[0].id) } + }, + 'selection.setOpacity': { + id: 'selection.setOpacity', + get label() { + return t.value.setOpacity + }, + enabled: capabilities.canSetOpacity, + run: () => { + const opacity = getOpacityTarget() + const targets = editor.getSelectedNodes() + if (targets.length === 0) return + editor.undo.runBatch('Set opacity', () => { + for (const target of targets) { + if (target.opacity === opacity) continue + editor.updateNodeWithUndo(target.id, { opacity }, 'Set opacity') + } + }) + } } } } diff --git a/packages/vue/src/editor/commands/types.ts b/packages/vue/src/editor/commands/types.ts index 2e341182c..a3a2b272d 100644 --- a/packages/vue/src/editor/commands/types.ts +++ b/packages/vue/src/editor/commands/types.ts @@ -30,6 +30,7 @@ export type EditorCommandId = | 'selection.outlineText' | 'selection.outlineStroke' | 'selection.moveToPage' + | 'selection.setOpacity' | 'view.zoom100' | 'view.zoomFit' | 'view.zoomSelection' diff --git a/packages/vue/src/editor/commands/use.ts b/packages/vue/src/editor/commands/use.ts index 0f9ff9b41..a628c0550 100644 --- a/packages/vue/src/editor/commands/use.ts +++ b/packages/vue/src/editor/commands/use.ts @@ -41,19 +41,26 @@ export function useEditorCommands() { editor.moveToPage(pageId) } + let opacityTarget = 1 + function setOpacityTarget(value: number) { + opacityTarget = value + } + const commands = createEditorCommandMap({ editor, selection, capabilities, messages: t, otherPages, - moveSelectionToPage + moveSelectionToPage, + getOpacityTarget: () => opacityTarget }) return { commands, otherPages, moveSelectionToPage, + setOpacityTarget, ...createEditorCommandActions(commands) } } diff --git a/packages/vue/src/editor/selection-capabilities/use.ts b/packages/vue/src/editor/selection-capabilities/use.ts index a11653f12..a77edd80f 100644 --- a/packages/vue/src/editor/selection-capabilities/use.ts +++ b/packages/vue/src/editor/selection-capabilities/use.ts @@ -66,6 +66,7 @@ export function useSelectionCapabilities() { canGoToMainComponent: computed(() => selection.isInstance.value), canCreateInstance: computed(() => selectedNode.value?.type === 'COMPONENT'), canMoveToPage: useSceneComputed(() => hasSelection.value && editor.graph.getPages().length > 1), + canSetOpacity: computed(() => hasSelection.value), canSelectAll: useSceneComputed( () => editor.graph.getChildren(editor.state.currentPageId).length > 0 ), diff --git a/packages/vue/src/i18n/locales/de/commands.json b/packages/vue/src/i18n/locales/de/commands.json index 642538812..d411cdc11 100644 --- a/packages/vue/src/i18n/locales/de/commands.json +++ b/packages/vue/src/i18n/locales/de/commands.json @@ -15,6 +15,7 @@ "bringToFront": "In den Vordergrund", "sendToBack": "In den Hintergrund", "moveToPage": "Auf Seite verschieben", + "setOpacity": "Deckkraft festlegen", "zoomTo100": "Zoom 100 %", "zoomToFit": "Einpassen", "zoomToSelection": "Auswahl einpassen", diff --git a/packages/vue/src/i18n/locales/es/commands.json b/packages/vue/src/i18n/locales/es/commands.json index 427c5095f..7587ca63e 100644 --- a/packages/vue/src/i18n/locales/es/commands.json +++ b/packages/vue/src/i18n/locales/es/commands.json @@ -15,6 +15,7 @@ "bringToFront": "Traer al frente", "sendToBack": "Enviar al fondo", "moveToPage": "Mover a página", + "setOpacity": "Establecer opacidad", "zoomTo100": "Zoom 100 %", "zoomToFit": "Ajustar a pantalla", "zoomToSelection": "Zoom a selección", diff --git a/packages/vue/src/i18n/locales/fr/commands.json b/packages/vue/src/i18n/locales/fr/commands.json index fd470a22b..a76efb041 100644 --- a/packages/vue/src/i18n/locales/fr/commands.json +++ b/packages/vue/src/i18n/locales/fr/commands.json @@ -15,6 +15,7 @@ "bringToFront": "Mettre au premier plan", "sendToBack": "Mettre en arrière-plan", "moveToPage": "Déplacer vers la page", + "setOpacity": "Définir l'opacité", "zoomTo100": "Zoom 100 %", "zoomToFit": "Ajuster à l'écran", "zoomToSelection": "Zoom sur la sélection", diff --git a/packages/vue/src/i18n/locales/it/commands.json b/packages/vue/src/i18n/locales/it/commands.json index a9542c114..be2f1dd71 100644 --- a/packages/vue/src/i18n/locales/it/commands.json +++ b/packages/vue/src/i18n/locales/it/commands.json @@ -15,6 +15,7 @@ "bringToFront": "Porta in primo piano", "sendToBack": "Porta in secondo piano", "moveToPage": "Sposta nella pagina", + "setOpacity": "Imposta opacità", "zoomTo100": "Zoom 100%", "zoomToFit": "Adatta allo schermo", "zoomToSelection": "Zoom sulla selezione", diff --git a/packages/vue/src/i18n/locales/ja/commands.json b/packages/vue/src/i18n/locales/ja/commands.json index 426d1a306..f83c011d7 100644 --- a/packages/vue/src/i18n/locales/ja/commands.json +++ b/packages/vue/src/i18n/locales/ja/commands.json @@ -15,6 +15,7 @@ "bringToFront": "最前面へ移動", "sendToBack": "最背面へ移動", "moveToPage": "ページへ移動", + "setOpacity": "不透明度を設定", "zoomTo100": "100%にズーム", "zoomToFit": "画面に合わせる", "zoomToSelection": "選択範囲にズーム", diff --git a/packages/vue/src/i18n/locales/pl/commands.json b/packages/vue/src/i18n/locales/pl/commands.json index 32482b1b6..09db34849 100644 --- a/packages/vue/src/i18n/locales/pl/commands.json +++ b/packages/vue/src/i18n/locales/pl/commands.json @@ -15,6 +15,7 @@ "bringToFront": "Przenieś na wierzch", "sendToBack": "Przenieś na spód", "moveToPage": "Przenieś na stronę", + "setOpacity": "Ustaw krycie", "zoomTo100": "Zoom 100%", "zoomToFit": "Dopasuj do ekranu", "zoomToSelection": "Zoom do zaznaczenia", diff --git a/packages/vue/src/i18n/locales/ru/commands.json b/packages/vue/src/i18n/locales/ru/commands.json index 57e59500f..25a100df3 100644 --- a/packages/vue/src/i18n/locales/ru/commands.json +++ b/packages/vue/src/i18n/locales/ru/commands.json @@ -15,6 +15,7 @@ "bringToFront": "На передний план", "sendToBack": "На задний план", "moveToPage": "Переместить на страницу", + "setOpacity": "Задать непрозрачность", "zoomTo100": "Масштаб 100%", "zoomToFit": "Вписать в экран", "zoomToSelection": "Масштаб по выделению", diff --git a/packages/vue/src/i18n/locales/zh-cn/commands.json b/packages/vue/src/i18n/locales/zh-cn/commands.json index 99138a415..ab222b8e3 100644 --- a/packages/vue/src/i18n/locales/zh-cn/commands.json +++ b/packages/vue/src/i18n/locales/zh-cn/commands.json @@ -15,6 +15,7 @@ "bringToFront": "置于顶层", "sendToBack": "置于底层", "moveToPage": "移动到页面", + "setOpacity": "设置不透明度", "zoomTo100": "缩放到 100%", "zoomToFit": "适应屏幕", "zoomToSelection": "适应所选内容", diff --git a/packages/vue/src/i18n/messages/commands.ts b/packages/vue/src/i18n/messages/commands.ts index da696cfa6..1dd11b669 100644 --- a/packages/vue/src/i18n/messages/commands.ts +++ b/packages/vue/src/i18n/messages/commands.ts @@ -33,6 +33,7 @@ export const commandMessageDefaults = { flipHorizontal: 'Flip horizontal', flipVertical: 'Flip vertical', moveToPage: 'Move to page', + setOpacity: 'Set opacity', zoomTo100: 'Zoom to 100%', zoomToFit: 'Zoom to fit', zoomToSelection: 'Zoom to selection' diff --git a/src/app/shell/keyboard/opacity.ts b/src/app/shell/keyboard/opacity.ts new file mode 100644 index 000000000..93dce8d94 --- /dev/null +++ b/src/app/shell/keyboard/opacity.ts @@ -0,0 +1,42 @@ +import { useEventListener } from '@vueuse/core' + +import type { useEditorCommands } from '@open-pencil/vue' + +import type { EditorStore } from '@/app/editor/active-store' +import { isEditing } from '@/app/shell/keyboard/focus' + +type OpacityShortcutOptions = { + store: EditorStore + setOpacityTarget: ReturnType['setOpacityTarget'] + runCommand: ReturnType['runCommand'] +} + +const DIGIT_OPACITY = { + Digit0: 1, + Digit1: 0.1, + Digit2: 0.2, + Digit3: 0.3, + Digit4: 0.4, + Digit5: 0.5, + Digit6: 0.6, + Digit7: 0.7, + Digit8: 0.8, + Digit9: 0.9 +} as const + +export function bindOpacityKeys({ store, setOpacityTarget, runCommand }: OpacityShortcutOptions) { + useEventListener(window, 'keydown', (e: KeyboardEvent) => { + if (isEditing(e)) return + if (store.state.editingTextId) return + if (store.state.numberFieldFocused) return + if (e.metaKey || e.ctrlKey || e.altKey) return + if (store.state.selectedIds.size === 0) return + + if (!(e.code in DIGIT_OPACITY)) return + const opacity: number = DIGIT_OPACITY[e.code as keyof typeof DIGIT_OPACITY] + + e.preventDefault() + setOpacityTarget(opacity) + runCommand('selection.setOpacity') + }) +} diff --git a/src/app/shell/keyboard/use.ts b/src/app/shell/keyboard/use.ts index 6eaa56b2f..08ad1d44f 100644 --- a/src/app/shell/keyboard/use.ts +++ b/src/app/shell/keyboard/use.ts @@ -9,6 +9,7 @@ import { createKeyboardActions } from '@/app/shell/keyboard/actions' import { bindEditorClipboard } from '@/app/shell/keyboard/clipboard' import { isInputElement } from '@/app/shell/keyboard/focus' import { bindNudgeKeys } from '@/app/shell/keyboard/nudging' +import { bindOpacityKeys } from '@/app/shell/keyboard/opacity' import { registerKeyboardShortcuts } from '@/app/shell/keyboard/registry' import { openFileDialog } from '@/app/shell/menu/use' import { closeTab, createTab, activeTab as activeTabRef } from '@/app/tabs' @@ -17,7 +18,7 @@ export function useKeyboard() { const { activeTab } = useAIChat() const store = useEditorStore() const { isMobile } = useViewportKind() - const { runCommand } = useEditorCommands() + const { runCommand, setOpacityTarget } = useEditorCommands() const activeElement = useActiveElement() const inputFocused = computed(() => isInputElement(activeElement.value)) @@ -25,6 +26,7 @@ export function useKeyboard() { bindEditorClipboard(store) bindNudgeKeys(store) + bindOpacityKeys({ store, setOpacityTarget, runCommand }) registerKeyboardShortcuts({ inputFocused, diff --git a/tests/engine/editor/opacity.test.ts b/tests/engine/editor/opacity.test.ts new file mode 100644 index 000000000..691b338c4 --- /dev/null +++ b/tests/engine/editor/opacity.test.ts @@ -0,0 +1,89 @@ +import { describe, test, expect } from 'bun:test' + +import { createEditor } from '@open-pencil/core/editor' + +import { getNodeOrThrow } from '#tests/helpers/assert' + +describe('opacity via updateNodeWithUndo + runBatch', () => { + function setup() { + const editor = createEditor() + const pageId = editor.graph.getPages()[0].id + const rect = editor.graph.createNode('RECTANGLE', pageId, { + name: 'Rect', + x: 0, + y: 0, + width: 50, + height: 50 + }) + editor.select([rect.id]) + return { editor, rect } + } + + function setOpacity(editor: ReturnType, opacity: number) { + const targets = editor.getSelectedNodes() + if (targets.length === 0) return + editor.undo.runBatch('Set opacity', () => { + for (const target of targets) { + if (target.opacity === opacity) continue + editor.updateNodeWithUndo(target.id, { opacity }, 'Set opacity') + } + }) + } + + test('sets opacity to 50%', () => { + const { editor, rect } = setup() + + setOpacity(editor, 0.5) + expect(getNodeOrThrow(editor.graph, rect.id).opacity).toBe(0.5) + }) + + test('0 digit sets opacity to 100%', () => { + const { editor, rect } = setup() + + setOpacity(editor, 0.5) + setOpacity(editor, 1) + expect(getNodeOrThrow(editor.graph, rect.id).opacity).toBe(1) + }) + + test('opacity change is undoable as a single batch entry', () => { + const { editor, rect } = setup() + + setOpacity(editor, 0.3) + expect(editor.undo.canUndo).toBe(true) + + editor.undo.undo() + expect(getNodeOrThrow(editor.graph, rect.id).opacity).toBe(1) + + editor.undo.redo() + expect(getNodeOrThrow(editor.graph, rect.id).opacity).toBe(0.3) + }) + + test('opacity batch for multiple selections collapses to one undo entry', () => { + const { editor, rect } = setup() + const pageId = editor.graph.getPages()[0].id + const rect2 = editor.graph.createNode('RECTANGLE', pageId, { + name: 'Rect2', + x: 100, + y: 0, + width: 50, + height: 50 + }) + editor.select([rect.id, rect2.id]) + + setOpacity(editor, 0.7) + expect(getNodeOrThrow(editor.graph, rect.id).opacity).toBe(0.7) + expect(getNodeOrThrow(editor.graph, rect2.id).opacity).toBe(0.7) + + editor.undo.undo() + expect(getNodeOrThrow(editor.graph, rect.id).opacity).toBe(1) + expect(getNodeOrThrow(editor.graph, rect2.id).opacity).toBe(1) + }) + + test('no-op when opacity already matches', () => { + const { editor, rect } = setup() + + setOpacity(editor, 1) + expect(getNodeOrThrow(editor.graph, rect.id).opacity).toBe(1) + expect(editor.undo.canUndo).toBe(false) + }) +}) From 183019fe849a7bc4c145cec37f34b6f6b28de798 Mon Sep 17 00:00:00 2001 From: Sadko <62859156+sadkodev@users.noreply.github.com> Date: Thu, 16 Jul 2026 22:37:31 -0400 Subject: [PATCH 02/12] Update src/app/shell/keyboard/opacity.ts Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> --- src/app/shell/keyboard/opacity.ts | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/app/shell/keyboard/opacity.ts b/src/app/shell/keyboard/opacity.ts index 93dce8d94..13c846108 100644 --- a/src/app/shell/keyboard/opacity.ts +++ b/src/app/shell/keyboard/opacity.ts @@ -13,15 +13,25 @@ type OpacityShortcutOptions = { const DIGIT_OPACITY = { Digit0: 1, + Numpad0: 1, Digit1: 0.1, + Numpad1: 0.1, Digit2: 0.2, + Numpad2: 0.2, Digit3: 0.3, + Numpad3: 0.3, Digit4: 0.4, + Numpad4: 0.4, Digit5: 0.5, + Numpad5: 0.5, Digit6: 0.6, + Numpad6: 0.6, Digit7: 0.7, + Numpad7: 0.7, Digit8: 0.8, - Digit9: 0.9 + Numpad8: 0.8, + Digit9: 0.9, + Numpad9: 0.9 } as const export function bindOpacityKeys({ store, setOpacityTarget, runCommand }: OpacityShortcutOptions) { @@ -29,7 +39,7 @@ export function bindOpacityKeys({ store, setOpacityTarget, runCommand }: Opacity if (isEditing(e)) return if (store.state.editingTextId) return if (store.state.numberFieldFocused) return - if (e.metaKey || e.ctrlKey || e.altKey) return + if (e.metaKey || e.ctrlKey || e.altKey || e.shiftKey) return if (store.state.selectedIds.size === 0) return if (!(e.code in DIGIT_OPACITY)) return From 0300cb521be1d62eceabc1baed3f00d53a6aa8cd Mon Sep 17 00:00:00 2001 From: sadkodev Date: Fri, 17 Jul 2026 14:09:40 -0400 Subject: [PATCH 03/12] refactor(keyboard): address review feedback on opacity shortcuts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Move setOpacity to core editor action (packages/core/src/editor/nodes.ts) so it is testable directly without duplicating logic in tests - Replace external window listener with tinykeys bindings in registerKeyboardShortcuts, reusing shared input/focus guards - Add 20 bindings for Digit0-9 and Numpad0-9 with modifier guards - Implement Figma-style multi-digit buffer: 2→20%, 28→28%, 00→0%, 100→100% with 400ms timeout and auto-apply at 3 digits - Simplify selection.setOpacity command to delegate to editor.setOpacity - Rewrite unit tests to call editor.setOpacity directly - Add ofetch to dependencies (was imported but missing from package.json) - Update CHANGELOG --- CHANGELOG.md | 2 +- bun.lock | 1 + package.json | 1 + packages/core/src/editor/nodes.ts | 15 ++++++ packages/vue/src/editor/commands/selection.ts | 12 +---- src/app/shell/keyboard/actions.ts | 32 +++++++++++- src/app/shell/keyboard/opacity.ts | 52 ------------------- src/app/shell/keyboard/registry.ts | 26 +++++++++- src/app/shell/keyboard/types.ts | 1 + src/app/shell/keyboard/use.ts | 10 ++-- tests/engine/editor/opacity.test.ts | 49 ++++++++++------- 11 files changed, 112 insertions(+), 89 deletions(-) delete mode 100644 src/app/shell/keyboard/opacity.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index d36487dd6..aae39da6f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ ### Changed -- Add Figma-style opacity keyboard shortcuts (`1`-`9` for 10%-90%, `0` for 100%) on the selected layers, with undo-batched multi-selection support. +- Add Figma-style opacity keyboard shortcuts (`1`-`9` for 10%-90%, `0` for 100%) with multi-digit buffer support (`28` → 28%, `00` → 0%, `100` → 100%), undo-batched multi-selection, and both top-row and numpad digit support. - Add Figma-style page management in the Pages panel, including rename/delete actions and drag-and-drop page reordering. - Add DOM/CSS import and authoring support so HTML, CSS, Tailwind, and JSX can be converted into editable OpenPencil documents from the app, CLI, and SDK. - Add Tailwind class serialization for DOM/CSS HTML export in the SDK and CLI. diff --git a/bun.lock b/bun.lock index be1e55a26..e84aa2a06 100644 --- a/bun.lock +++ b/bun.lock @@ -44,6 +44,7 @@ "jspdf": "^4.2.1", "lib0": "^0.2.117", "motion-v": "^2.0.0", + "ofetch": "^1.5.1", "opentype.js": "^2.0.0", "prismjs": "^1.30.0", "reka-ui": "^2.9.0", diff --git a/package.json b/package.json index 38abddb32..51a0a7e75 100644 --- a/package.json +++ b/package.json @@ -97,6 +97,7 @@ "jspdf": "^4.2.1", "lib0": "^0.2.117", "motion-v": "^2.0.0", + "ofetch": "^1.5.1", "opentype.js": "^2.0.0", "prismjs": "^1.30.0", "reka-ui": "^2.9.0", diff --git a/packages/core/src/editor/nodes.ts b/packages/core/src/editor/nodes.ts index f00fa443c..b4042272b 100644 --- a/packages/core/src/editor/nodes.ts +++ b/packages/core/src/editor/nodes.ts @@ -51,9 +51,24 @@ export function createNodeActions(ctx: EditorContext) { ctx.requestRender() } + function setOpacity(opacity: number) { + const clamped = Math.max(0, Math.min(1, opacity)) + const ids = [...ctx.state.selectedIds] + if (ids.length === 0) return + const targets = ids.map((id) => ctx.graph.getNode(id)).filter((n): n is SceneNode => n != null) + const changed = targets.filter((t) => t.opacity !== clamped) + if (changed.length === 0) return + ctx.undo.runBatch('Set opacity', () => { + for (const target of changed) { + updateNodeWithUndo(target.id, { opacity: clamped }, 'Set opacity') + } + }) + } + return { updateNode, updateNodeWithUndo, + setOpacity, ...layoutModeActions, ...variableBindingActions, ...nudgeActions diff --git a/packages/vue/src/editor/commands/selection.ts b/packages/vue/src/editor/commands/selection.ts index 8bcf70a32..6753b53ef 100644 --- a/packages/vue/src/editor/commands/selection.ts +++ b/packages/vue/src/editor/commands/selection.ts @@ -269,17 +269,7 @@ export function createSelectionCommands({ return t.value.setOpacity }, enabled: capabilities.canSetOpacity, - run: () => { - const opacity = getOpacityTarget() - const targets = editor.getSelectedNodes() - if (targets.length === 0) return - editor.undo.runBatch('Set opacity', () => { - for (const target of targets) { - if (target.opacity === opacity) continue - editor.updateNodeWithUndo(target.id, { opacity }, 'Set opacity') - } - }) - } + run: () => editor.setOpacity(getOpacityTarget()) } } } diff --git a/src/app/shell/keyboard/actions.ts b/src/app/shell/keyboard/actions.ts index 5d7f7c4e9..95143200a 100644 --- a/src/app/shell/keyboard/actions.ts +++ b/src/app/shell/keyboard/actions.ts @@ -9,13 +9,15 @@ type KeyboardActionsOptions = { activeTab: Ref<'design' | 'code' | 'ai'> isMobile: ReturnType['isMobile'] runCommand: ReturnType['runCommand'] + setOpacityTarget: ReturnType['setOpacityTarget'] } export function createKeyboardActions({ store, activeTab, isMobile, - runCommand + runCommand, + setOpacityTarget }: KeyboardActionsOptions) { function hasNodeEditSelection() { return ( @@ -98,6 +100,31 @@ export function createKeyboardActions({ if (store.state.selectedIds.size > 0) void store.exportSelection(1, 'png') } + let opacityBuffer = '' + let opacityTimer: ReturnType | undefined + + function applyOpacityBuffer() { + clearTimeout(opacityTimer) + if (!opacityBuffer) return + const n = Number.parseInt(opacityBuffer, 10) + const percent = opacityBuffer.length === 1 ? n * 10 : n + const clamped = Math.min(100, Math.max(0, percent)) + opacityBuffer = '' + setOpacityTarget(clamped / 100) + runCommand('selection.setOpacity') + } + + function opacityDigit(digit: string) { + if (store.state.selectedIds.size === 0) return + opacityBuffer += digit + clearTimeout(opacityTimer) + if (opacityBuffer.length >= 3) { + applyOpacityBuffer() + } else { + opacityTimer = setTimeout(applyOpacityBuffer, 400) + } + } + return { smartDelete, confirmOrEnterText, @@ -105,6 +132,7 @@ export function createKeyboardActions({ toggleAutoLayout, toggleUI, toggleAI, - exportSelectionPng + exportSelectionPng, + opacityDigit } } diff --git a/src/app/shell/keyboard/opacity.ts b/src/app/shell/keyboard/opacity.ts deleted file mode 100644 index 13c846108..000000000 --- a/src/app/shell/keyboard/opacity.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { useEventListener } from '@vueuse/core' - -import type { useEditorCommands } from '@open-pencil/vue' - -import type { EditorStore } from '@/app/editor/active-store' -import { isEditing } from '@/app/shell/keyboard/focus' - -type OpacityShortcutOptions = { - store: EditorStore - setOpacityTarget: ReturnType['setOpacityTarget'] - runCommand: ReturnType['runCommand'] -} - -const DIGIT_OPACITY = { - Digit0: 1, - Numpad0: 1, - Digit1: 0.1, - Numpad1: 0.1, - Digit2: 0.2, - Numpad2: 0.2, - Digit3: 0.3, - Numpad3: 0.3, - Digit4: 0.4, - Numpad4: 0.4, - Digit5: 0.5, - Numpad5: 0.5, - Digit6: 0.6, - Numpad6: 0.6, - Digit7: 0.7, - Numpad7: 0.7, - Digit8: 0.8, - Numpad8: 0.8, - Digit9: 0.9, - Numpad9: 0.9 -} as const - -export function bindOpacityKeys({ store, setOpacityTarget, runCommand }: OpacityShortcutOptions) { - useEventListener(window, 'keydown', (e: KeyboardEvent) => { - if (isEditing(e)) return - if (store.state.editingTextId) return - if (store.state.numberFieldFocused) return - if (e.metaKey || e.ctrlKey || e.altKey || e.shiftKey) return - if (store.state.selectedIds.size === 0) return - - if (!(e.code in DIGIT_OPACITY)) return - const opacity: number = DIGIT_OPACITY[e.code as keyof typeof DIGIT_OPACITY] - - e.preventDefault() - setOpacityTarget(opacity) - runCommand('selection.setOpacity') - }) -} diff --git a/src/app/shell/keyboard/registry.ts b/src/app/shell/keyboard/registry.ts index c6ba53d29..69f907f46 100644 --- a/src/app/shell/keyboard/registry.ts +++ b/src/app/shell/keyboard/registry.ts @@ -36,6 +36,29 @@ function commandShortcuts(...commands: EditorCommandId[]): ShortcutDefinition[] }) } +const OPACITY_DIGITS = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] + +function opacityBindings(): ShortcutDefinition[] { + return OPACITY_DIGITS.flatMap((digit) => [ + { + id: `opacity-Digit${digit}`, + keys: `Digit${digit}`, + run: ({ keyEvent, actions }: KeyboardShortcutRunOptions) => { + if (keyEvent.metaKey || keyEvent.ctrlKey || keyEvent.altKey || keyEvent.shiftKey) return + actions.opacityDigit(digit) + } + }, + { + id: `opacity-Numpad${digit}`, + keys: `Numpad${digit}`, + run: ({ keyEvent, actions }: KeyboardShortcutRunOptions) => { + if (keyEvent.metaKey || keyEvent.ctrlKey || keyEvent.altKey || keyEvent.shiftKey) return + actions.opacityDigit(digit) + } + } + ]) +} + function shouldIgnoreShortcut(event: KeyboardEvent, options: KeyboardShortcutOptions) { return ( (event.target instanceof Element && event.target.closest('[data-picker-content]') !== null) || @@ -136,7 +159,8 @@ export function registerKeyboardShortcuts(options: KeyboardShortcutOptions) { { id: 'delete', keys: 'Delete', run: ({ actions }) => actions.smartDelete(false) }, { id: 'delete-alt', keys: 'Alt+Delete', run: ({ actions }) => actions.smartDelete(true) }, { id: 'enter', keys: 'Enter', run: ({ actions }) => actions.confirmOrEnterText() }, - { id: 'escape', keys: 'Escape', run: ({ actions }) => actions.escapeOrDeselect() } + { id: 'escape', keys: 'Escape', run: ({ actions }) => actions.escapeOrDeselect() }, + ...opacityBindings() ] const bindings: KeyBindingMap = {} diff --git a/src/app/shell/keyboard/types.ts b/src/app/shell/keyboard/types.ts index b0e311060..d4c3d2a15 100644 --- a/src/app/shell/keyboard/types.ts +++ b/src/app/shell/keyboard/types.ts @@ -12,6 +12,7 @@ export type KeyboardShortcutActions = { toggleUI: () => void toggleAI: () => void exportSelectionPng: () => void + opacityDigit: (digit: string) => void } export type KeyboardShortcutOptions = { diff --git a/src/app/shell/keyboard/use.ts b/src/app/shell/keyboard/use.ts index 08ad1d44f..38abea9c5 100644 --- a/src/app/shell/keyboard/use.ts +++ b/src/app/shell/keyboard/use.ts @@ -9,7 +9,6 @@ import { createKeyboardActions } from '@/app/shell/keyboard/actions' import { bindEditorClipboard } from '@/app/shell/keyboard/clipboard' import { isInputElement } from '@/app/shell/keyboard/focus' import { bindNudgeKeys } from '@/app/shell/keyboard/nudging' -import { bindOpacityKeys } from '@/app/shell/keyboard/opacity' import { registerKeyboardShortcuts } from '@/app/shell/keyboard/registry' import { openFileDialog } from '@/app/shell/menu/use' import { closeTab, createTab, activeTab as activeTabRef } from '@/app/tabs' @@ -22,11 +21,16 @@ export function useKeyboard() { const activeElement = useActiveElement() const inputFocused = computed(() => isInputElement(activeElement.value)) - const actions = createKeyboardActions({ store, activeTab, isMobile, runCommand }) + const actions = createKeyboardActions({ + store, + activeTab, + isMobile, + runCommand, + setOpacityTarget + }) bindEditorClipboard(store) bindNudgeKeys(store) - bindOpacityKeys({ store, setOpacityTarget, runCommand }) registerKeyboardShortcuts({ inputFocused, diff --git a/tests/engine/editor/opacity.test.ts b/tests/engine/editor/opacity.test.ts index 691b338c4..495249af6 100644 --- a/tests/engine/editor/opacity.test.ts +++ b/tests/engine/editor/opacity.test.ts @@ -4,7 +4,7 @@ import { createEditor } from '@open-pencil/core/editor' import { getNodeOrThrow } from '#tests/helpers/assert' -describe('opacity via updateNodeWithUndo + runBatch', () => { +describe('editor.setOpacity', () => { function setup() { const editor = createEditor() const pageId = editor.graph.getPages()[0].id @@ -19,36 +19,39 @@ describe('opacity via updateNodeWithUndo + runBatch', () => { return { editor, rect } } - function setOpacity(editor: ReturnType, opacity: number) { - const targets = editor.getSelectedNodes() - if (targets.length === 0) return - editor.undo.runBatch('Set opacity', () => { - for (const target of targets) { - if (target.opacity === opacity) continue - editor.updateNodeWithUndo(target.id, { opacity }, 'Set opacity') - } - }) - } - test('sets opacity to 50%', () => { const { editor, rect } = setup() - setOpacity(editor, 0.5) + editor.setOpacity(0.5) expect(getNodeOrThrow(editor.graph, rect.id).opacity).toBe(0.5) }) - test('0 digit sets opacity to 100%', () => { + test('sets opacity to 100% (digit 0)', () => { const { editor, rect } = setup() - setOpacity(editor, 0.5) - setOpacity(editor, 1) + editor.setOpacity(0.5) + editor.setOpacity(1) expect(getNodeOrThrow(editor.graph, rect.id).opacity).toBe(1) }) + test('clamps opacity above 100%', () => { + const { editor, rect } = setup() + + editor.setOpacity(1.5) + expect(getNodeOrThrow(editor.graph, rect.id).opacity).toBe(1) + }) + + test('clamps opacity below 0%', () => { + const { editor, rect } = setup() + + editor.setOpacity(-0.3) + expect(getNodeOrThrow(editor.graph, rect.id).opacity).toBe(0) + }) + test('opacity change is undoable as a single batch entry', () => { const { editor, rect } = setup() - setOpacity(editor, 0.3) + editor.setOpacity(0.3) expect(editor.undo.canUndo).toBe(true) editor.undo.undo() @@ -70,7 +73,7 @@ describe('opacity via updateNodeWithUndo + runBatch', () => { }) editor.select([rect.id, rect2.id]) - setOpacity(editor, 0.7) + editor.setOpacity(0.7) expect(getNodeOrThrow(editor.graph, rect.id).opacity).toBe(0.7) expect(getNodeOrThrow(editor.graph, rect2.id).opacity).toBe(0.7) @@ -82,8 +85,16 @@ describe('opacity via updateNodeWithUndo + runBatch', () => { test('no-op when opacity already matches', () => { const { editor, rect } = setup() - setOpacity(editor, 1) + editor.setOpacity(1) expect(getNodeOrThrow(editor.graph, rect.id).opacity).toBe(1) expect(editor.undo.canUndo).toBe(false) }) + + test('no-op with no selection', () => { + const { editor } = setup() + + editor.clearSelection() + editor.setOpacity(0.5) + expect(editor.undo.canUndo).toBe(false) + }) }) From 9d88c4f0451d4ad22f2d6312bd5f788e5ad7d995 Mon Sep 17 00:00:00 2001 From: sadkodev Date: Fri, 17 Jul 2026 14:26:45 -0400 Subject: [PATCH 04/12] fix(keyboard): apply opacity immediately on each keypress MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replace the 400ms apply-timeout with immediate application on every digit press. A separate 800ms reset timer clears the buffer between sequences so digits typed in quick succession still compose (28→28%, 00→0%, 100→100%) but single digits no longer have a perceptible delay. --- src/app/shell/keyboard/actions.ts | 29 +++++++++++------------------ 1 file changed, 11 insertions(+), 18 deletions(-) diff --git a/src/app/shell/keyboard/actions.ts b/src/app/shell/keyboard/actions.ts index 95143200a..54af17101 100644 --- a/src/app/shell/keyboard/actions.ts +++ b/src/app/shell/keyboard/actions.ts @@ -101,28 +101,21 @@ export function createKeyboardActions({ } let opacityBuffer = '' - let opacityTimer: ReturnType | undefined - - function applyOpacityBuffer() { - clearTimeout(opacityTimer) - if (!opacityBuffer) return - const n = Number.parseInt(opacityBuffer, 10) - const percent = opacityBuffer.length === 1 ? n * 10 : n - const clamped = Math.min(100, Math.max(0, percent)) - opacityBuffer = '' - setOpacityTarget(clamped / 100) - runCommand('selection.setOpacity') - } + let opacityResetTimer: ReturnType | undefined function opacityDigit(digit: string) { if (store.state.selectedIds.size === 0) return opacityBuffer += digit - clearTimeout(opacityTimer) - if (opacityBuffer.length >= 3) { - applyOpacityBuffer() - } else { - opacityTimer = setTimeout(applyOpacityBuffer, 400) - } + if (opacityBuffer.length > 3) opacityBuffer = opacityBuffer.slice(-3) + const n = Number.parseInt(opacityBuffer, 10) + const percent = opacityBuffer.length === 1 ? n * 10 : n + const clamped = Math.min(100, Math.max(0, percent)) + setOpacityTarget(clamped / 100) + runCommand('selection.setOpacity') + clearTimeout(opacityResetTimer) + opacityResetTimer = setTimeout(() => { + opacityBuffer = '' + }, 800) } return { From b5de9806322c3f671119ec3cc86dd058be4e9930 Mon Sep 17 00:00:00 2001 From: sadkodev Date: Fri, 17 Jul 2026 14:41:36 -0400 Subject: [PATCH 05/12] fix(keyboard): treat single 0 as 100% opacity Figma treats pressing 0 alone as 100% opacity, not 0%. The single-digit decena rule (n * 10) would produce 0 * 10 = 0% for 0, which is wrong. Add an explicit check: buffer '0' applies 100%, all other single digits apply n * 10, and multi-digit buffers apply the literal value. --- src/app/shell/keyboard/actions.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/app/shell/keyboard/actions.ts b/src/app/shell/keyboard/actions.ts index 54af17101..2d8823afa 100644 --- a/src/app/shell/keyboard/actions.ts +++ b/src/app/shell/keyboard/actions.ts @@ -108,7 +108,10 @@ export function createKeyboardActions({ opacityBuffer += digit if (opacityBuffer.length > 3) opacityBuffer = opacityBuffer.slice(-3) const n = Number.parseInt(opacityBuffer, 10) - const percent = opacityBuffer.length === 1 ? n * 10 : n + let percent: number + if (opacityBuffer === '0') percent = 100 + else if (opacityBuffer.length === 1) percent = n * 10 + else percent = n const clamped = Math.min(100, Math.max(0, percent)) setOpacityTarget(clamped / 100) runCommand('selection.setOpacity') From 1ca1cbc8965a804bac6fdd365c4be7bcf670d8d4 Mon Sep 17 00:00:00 2001 From: sadkodev Date: Fri, 17 Jul 2026 14:49:00 -0400 Subject: [PATCH 06/12] refactor(keyboard): deduplicate opacity binding handler Collapse the duplicated Digit/Numpad opacity bindings into a single OPACITY_CODES array with one shared run handler. Digit value is extracted via code.slice(-1), which works for both Digit0-9 and Numpad0-9. --- src/app/shell/keyboard/registry.ts | 29 +++++++++++------------------ 1 file changed, 11 insertions(+), 18 deletions(-) diff --git a/src/app/shell/keyboard/registry.ts b/src/app/shell/keyboard/registry.ts index 69f907f46..506e8eb00 100644 --- a/src/app/shell/keyboard/registry.ts +++ b/src/app/shell/keyboard/registry.ts @@ -36,27 +36,20 @@ function commandShortcuts(...commands: EditorCommandId[]): ShortcutDefinition[] }) } -const OPACITY_DIGITS = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] +const OPACITY_CODES = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'].flatMap((d) => [ + `Digit${d}`, + `Numpad${d}` +]) function opacityBindings(): ShortcutDefinition[] { - return OPACITY_DIGITS.flatMap((digit) => [ - { - id: `opacity-Digit${digit}`, - keys: `Digit${digit}`, - run: ({ keyEvent, actions }: KeyboardShortcutRunOptions) => { - if (keyEvent.metaKey || keyEvent.ctrlKey || keyEvent.altKey || keyEvent.shiftKey) return - actions.opacityDigit(digit) - } - }, - { - id: `opacity-Numpad${digit}`, - keys: `Numpad${digit}`, - run: ({ keyEvent, actions }: KeyboardShortcutRunOptions) => { - if (keyEvent.metaKey || keyEvent.ctrlKey || keyEvent.altKey || keyEvent.shiftKey) return - actions.opacityDigit(digit) - } + return OPACITY_CODES.map((code) => ({ + id: `opacity-${code}`, + keys: code, + run: ({ keyEvent, actions }: KeyboardShortcutRunOptions) => { + if (keyEvent.metaKey || keyEvent.ctrlKey || keyEvent.altKey || keyEvent.shiftKey) return + actions.opacityDigit(code.slice(-1)) } - ]) + })) } function shouldIgnoreShortcut(event: KeyboardEvent, options: KeyboardShortcutOptions) { From d58cf0b9e93ed146e3ece013019392cd0f8e4130 Mon Sep 17 00:00:00 2001 From: sadkodev Date: Fri, 17 Jul 2026 15:00:10 -0400 Subject: [PATCH 07/12] test(keyboard): add unit tests for opacity buffer logic MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Extract opacityFromBuffer as a pure function in core/editor and test it directly. Covers Figma semantics: 0→100%, 5→50%, 28→28%, 00→0%, 100→100%, clamp at 100%, NaN guard. Refactor the keyboard handler to reuse the shared function instead of inlining the buffer math. --- packages/core/src/editor/index.ts | 1 + packages/core/src/editor/nodes.ts | 8 ++++++++ src/app/shell/keyboard/actions.ts | 9 ++------- tests/engine/editor/opacity.test.ts | 31 ++++++++++++++++++++++++++++- 4 files changed, 41 insertions(+), 8 deletions(-) diff --git a/packages/core/src/editor/index.ts b/packages/core/src/editor/index.ts index 6f266d20c..d7d955d74 100644 --- a/packages/core/src/editor/index.ts +++ b/packages/core/src/editor/index.ts @@ -1,6 +1,7 @@ export { createDefaultEditorState, createEditor } from './create' export type { Editor } from './create' export { createTextActions } from './text' +export { opacityFromBuffer } from './nodes' export { EDITOR_TOOLS, TOOL_SHORTCUTS } from './tool-registry' export type { EditorToolDef } from './tool-registry' export type { diff --git a/packages/core/src/editor/nodes.ts b/packages/core/src/editor/nodes.ts index b4042272b..f563ba5c5 100644 --- a/packages/core/src/editor/nodes.ts +++ b/packages/core/src/editor/nodes.ts @@ -8,6 +8,14 @@ import { textAutoResizeChanges } from './text/auto-resize' import type { EditorContext } from './types' import { createVariableBindingActions } from './variable-bindings' +export function opacityFromBuffer(buffer: string): number { + if (buffer === '0') return 1 + const n = Number.parseInt(buffer, 10) + if (Number.isNaN(n)) return 1 + const percent = buffer.length === 1 ? n * 10 : n + return Math.min(100, Math.max(0, percent)) / 100 +} + export function createNodeActions(ctx: EditorContext) { const layoutModeActions = createLayoutModeActions(ctx) const nudgeActions = createNudgeActions(ctx) diff --git a/src/app/shell/keyboard/actions.ts b/src/app/shell/keyboard/actions.ts index 2d8823afa..b0ac6eb02 100644 --- a/src/app/shell/keyboard/actions.ts +++ b/src/app/shell/keyboard/actions.ts @@ -1,5 +1,6 @@ import type { Ref } from 'vue' +import { opacityFromBuffer } from '@open-pencil/core/editor' import type { useEditorCommands, useViewportKind } from '@open-pencil/vue' import type { EditorStore } from '@/app/editor/active-store' @@ -107,13 +108,7 @@ export function createKeyboardActions({ if (store.state.selectedIds.size === 0) return opacityBuffer += digit if (opacityBuffer.length > 3) opacityBuffer = opacityBuffer.slice(-3) - const n = Number.parseInt(opacityBuffer, 10) - let percent: number - if (opacityBuffer === '0') percent = 100 - else if (opacityBuffer.length === 1) percent = n * 10 - else percent = n - const clamped = Math.min(100, Math.max(0, percent)) - setOpacityTarget(clamped / 100) + setOpacityTarget(opacityFromBuffer(opacityBuffer)) runCommand('selection.setOpacity') clearTimeout(opacityResetTimer) opacityResetTimer = setTimeout(() => { diff --git a/tests/engine/editor/opacity.test.ts b/tests/engine/editor/opacity.test.ts index 495249af6..a4b346e63 100644 --- a/tests/engine/editor/opacity.test.ts +++ b/tests/engine/editor/opacity.test.ts @@ -1,6 +1,6 @@ import { describe, test, expect } from 'bun:test' -import { createEditor } from '@open-pencil/core/editor' +import { createEditor, opacityFromBuffer } from '@open-pencil/core/editor' import { getNodeOrThrow } from '#tests/helpers/assert' @@ -98,3 +98,32 @@ describe('editor.setOpacity', () => { expect(editor.undo.canUndo).toBe(false) }) }) + +describe('opacityFromBuffer', () => { + test('single 0 returns 100%', () => { + expect(opacityFromBuffer('0')).toBe(1) + }) + + test('single digit returns decena', () => { + expect(opacityFromBuffer('5')).toBe(0.5) + expect(opacityFromBuffer('2')).toBe(0.2) + expect(opacityFromBuffer('9')).toBe(0.9) + }) + + test('two digits returns literal percent', () => { + expect(opacityFromBuffer('28')).toBe(0.28) + expect(opacityFromBuffer('35')).toBe(0.35) + expect(opacityFromBuffer('00')).toBe(0) + expect(opacityFromBuffer('05')).toBe(0.05) + }) + + test('three digits clamps to 100%', () => { + expect(opacityFromBuffer('100')).toBe(1) + expect(opacityFromBuffer('150')).toBe(1) + }) + + test('invalid buffer returns 100%', () => { + expect(opacityFromBuffer('')).toBe(1) + expect(opacityFromBuffer('abc')).toBe(1) + }) +}) From d1284cd01ba93dff8d3b61f126aee9cca201e44e Mon Sep 17 00:00:00 2001 From: sadkodev Date: Fri, 17 Jul 2026 15:26:31 -0400 Subject: [PATCH 08/12] fix(editor): guard setOpacity against non-finite values Add Number.isFinite guard to editor.setOpacity so NaN, Infinity, and -Infinity are rejected silently instead of corrupting node opacity. Tighten opacityFromBuffer to use Number.isFinite for the same reason. Add 3 unit tests covering NaN, Infinity, and -Infinity rejection. --- packages/core/src/editor/nodes.ts | 3 ++- tests/engine/editor/opacity.test.ts | 24 ++++++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/packages/core/src/editor/nodes.ts b/packages/core/src/editor/nodes.ts index f563ba5c5..f5fcb3337 100644 --- a/packages/core/src/editor/nodes.ts +++ b/packages/core/src/editor/nodes.ts @@ -11,7 +11,7 @@ import { createVariableBindingActions } from './variable-bindings' export function opacityFromBuffer(buffer: string): number { if (buffer === '0') return 1 const n = Number.parseInt(buffer, 10) - if (Number.isNaN(n)) return 1 + if (!Number.isFinite(n)) return 1 const percent = buffer.length === 1 ? n * 10 : n return Math.min(100, Math.max(0, percent)) / 100 } @@ -60,6 +60,7 @@ export function createNodeActions(ctx: EditorContext) { } function setOpacity(opacity: number) { + if (!Number.isFinite(opacity)) return const clamped = Math.max(0, Math.min(1, opacity)) const ids = [...ctx.state.selectedIds] if (ids.length === 0) return diff --git a/tests/engine/editor/opacity.test.ts b/tests/engine/editor/opacity.test.ts index a4b346e63..5e8e3de8b 100644 --- a/tests/engine/editor/opacity.test.ts +++ b/tests/engine/editor/opacity.test.ts @@ -97,6 +97,30 @@ describe('editor.setOpacity', () => { editor.setOpacity(0.5) expect(editor.undo.canUndo).toBe(false) }) + + test('rejects NaN', () => { + const { editor, rect } = setup() + + editor.setOpacity(Number.NaN) + expect(getNodeOrThrow(editor.graph, rect.id).opacity).toBe(1) + expect(editor.undo.canUndo).toBe(false) + }) + + test('rejects Infinity', () => { + const { editor, rect } = setup() + + editor.setOpacity(Number.POSITIVE_INFINITY) + expect(getNodeOrThrow(editor.graph, rect.id).opacity).toBe(1) + expect(editor.undo.canUndo).toBe(false) + }) + + test('rejects -Infinity', () => { + const { editor, rect } = setup() + + editor.setOpacity(Number.NEGATIVE_INFINITY) + expect(getNodeOrThrow(editor.graph, rect.id).opacity).toBe(1) + expect(editor.undo.canUndo).toBe(false) + }) }) describe('opacityFromBuffer', () => { From a5cffcc1ed29c424f6e7d20fbc72155e186ac71a Mon Sep 17 00:00:00 2001 From: sadkodev Date: Fri, 17 Jul 2026 15:30:43 -0400 Subject: [PATCH 09/12] fix(editor): reject partially numeric opacity buffers Add /^\d+$/ guard to opacityFromBuffer so strings like '12x', '5abc', or '3.5' return 100% instead of silently parsing the numeric prefix. Add unit tests for partial, decimal, scientific, negative, and whitespace-prefixed buffers. --- packages/core/src/editor/nodes.ts | 1 + tests/engine/editor/opacity.test.ts | 9 +++++++++ 2 files changed, 10 insertions(+) diff --git a/packages/core/src/editor/nodes.ts b/packages/core/src/editor/nodes.ts index f5fcb3337..0a35eea31 100644 --- a/packages/core/src/editor/nodes.ts +++ b/packages/core/src/editor/nodes.ts @@ -10,6 +10,7 @@ import { createVariableBindingActions } from './variable-bindings' export function opacityFromBuffer(buffer: string): number { if (buffer === '0') return 1 + if (!/^\d+$/.test(buffer)) return 1 const n = Number.parseInt(buffer, 10) if (!Number.isFinite(n)) return 1 const percent = buffer.length === 1 ? n * 10 : n diff --git a/tests/engine/editor/opacity.test.ts b/tests/engine/editor/opacity.test.ts index 5e8e3de8b..0f3fafa71 100644 --- a/tests/engine/editor/opacity.test.ts +++ b/tests/engine/editor/opacity.test.ts @@ -150,4 +150,13 @@ describe('opacityFromBuffer', () => { expect(opacityFromBuffer('')).toBe(1) expect(opacityFromBuffer('abc')).toBe(1) }) + + test('rejects partially numeric buffers', () => { + expect(opacityFromBuffer('12x')).toBe(1) + expect(opacityFromBuffer('5abc')).toBe(1) + expect(opacityFromBuffer('3.5')).toBe(1) + expect(opacityFromBuffer('1e2')).toBe(1) + expect(opacityFromBuffer('-5')).toBe(1) + expect(opacityFromBuffer(' 5')).toBe(1) + }) }) From 6e4cff3d1fd89670c5248125c0bcc80812e5e789 Mon Sep 17 00:00:00 2001 From: Sadko <62859156+sadkodev@users.noreply.github.com> Date: Fri, 17 Jul 2026 18:28:55 -0400 Subject: [PATCH 10/12] Update CHANGELOG.md --- CHANGELOG.md | 943 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 943 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 19bc835cf..aea92b65d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,949 @@ ## Unreleased +### Changed +- Add Figma-style opacity keyboard shortcuts (`1`-`9` for 10%-90%, `0` for 100%) with multi-digit buffer support (`28` → 28%, `00` → 0%, `100` → 100%), undo-batched multi-selection, and both top-row and numpad digit support. +- Move complete `.fig` archive parsing into `@open-pencil/fig`, keeping `@open-pencil/kiwi` focused on Kiwi schema, message, and raw container mechanics. +- Add Figma-style page management in the Pages panel, including rename/delete actions and drag-and-drop page reordering. +- Add DOM/CSS import and authoring support so HTML, CSS, Tailwind, and JSX can be converted into editable OpenPencil documents from the app, CLI, and SDK. +- Add Tailwind class serialization for DOM/CSS HTML export in the SDK and CLI. +- Add standalone browser-openable HTML export with compiled CSS and optional external image/font assets. +- Add richer Design JSX authoring for components, variables, structured fills, gradients, shadows, and blur effects. +- Add overlap analysis for finding layout collisions and overflowing children from the CLI, AI tools, and MCP. +- Add saved per-node export settings for repeat exports. +- Add Design panel controls for layer blend modes and alpha, vector, and luminance masks. +- Refine Design panel foundations with 26px controls, consistently aligned action rails, shared Tailwind themes, and Storybook component states. +- Scale the Layers panel to 5,000-node documents with virtualized rows, indexed updates, scroll-to-selection, range selection, and focus-aware themed states. +- Add Figma-style horizontal and vertical constraint controls with pin interactions, mixed-selection editing, undo, and responsive frame resizing. +- Add mixed-selection stroke cap, join, and miter-limit controls with CanvasKit rendering and `.fig` roundtrip support. +- Add a mixed-selection corner-smoothing percentage control with live preview, per-node undo restoration, and `.fig` roundtrip coverage. +- Model imported fill, stroke, text, effect, and grid styles with reusable SDK/app selectors, automatic detach-on-edit, undo, and `.fig` definition roundtrips. +- Add variant, text, boolean, and nested instance-swap component property controls with mixed-selection undo and typed `.fig` metadata roundtrips. +- Add fill and effect blend-mode controls with shared-style detachment and mixed-selection undo. +- Add text case, justification, vertical alignment, truncation/max-lines, and common OpenType controls with CanvasKit rendering and undo. +- Standardize Pages, Layers/Assets navigation, and document tab states across light and dark themes. +- Standardize Vue SDK and app override type names on the `UI` acronym, including `FontPickerUI`. +- Add a headless Vue SDK NumberField with pointer scrubbing, keyboard stepping, safe arithmetic expressions, and mixed/bound states; remove the superseded ScrubInput API. +- Add provider-driven BindableValue primitives for variable and token binding, including detach-on-edit, read-only, edit-variable, mixed-value, and undo-batched interactions. +- Add headless PropertySection, SegmentedControl, and typed PropertyList anatomy, with controlled list events and an undo-aware OpenPencil adapter. +- Refine variable-bound number fields with a quiet identity pill, one picker affordance, an accessible variable combobox, and non-destructive focus behavior. +- Redesign Position and Appearance controls with aligned panel grids, SDK-owned independent-corner state, and compact type-icon selection headers. +- Rebuild Layout size fields with shared variable binding, inline sizing modes, semantic field anatomy, and one-step Hug/Fill-to-Fixed editing. +- Replace the fragmented Vue SDK color-picker model helpers with `useColorModel()`, providing precise Reka bridges, extensible formats, and shared RGB, HSL, HSB, and OkHCL channel behavior. +- Add accessible color-channel sliders, binding-aware fill primitives, and keyboard-operable gradient stops while separating fill state from popover composition. +- Rebuild Fill, Stroke, Effects, and Export controls with shared compact item rows, semantic actions, binding-aware paint fields, and reversible color-picker edits. +- Finish the Design panel migration with compact labeled Typography, Variant, Mask, and Page controls plus semantic empty-section states. +- Remove the deprecated `FillPickerRoot`, `useFillPicker()`, and `PanelRow` compatibility APIs after migrating consumers to the canonical fill and panel primitives. +- Upgrade Vue SDK documentation with shared Tailwind demos, source-generated component API tables, and type-aware Twoslash examples in VitePress. +- Add desktop image drag-and-drop into the Tauri app window. +- Add open-document discovery for live CLI and MCP automation so agents can target the intended document and page. +- Publish lower-level SceneGraph, Pen, Kiwi, Fig, and DOM/CSS functionality through clearer package boundaries for SDK and automation consumers. +- Upgrade `opentype.js` to v2 and add BCP-47 text-language hints for language-correct CJK shaping and fallback order. + +### Fixes + +- Preserve unrelated Figma prototype, library, export, and raw metadata when editing modeled `.fig` fields, while still overriding stale field-specific payloads. +- Make canvas text rendering demand missing font faces and verify CJK/Arabic fallback coverage from CanvasKit shaping results instead of coarse script predictions. +- Resolve fonts before loaded, pasted, imported, and tool-created nodes render; invalidate generation-stale text caches and use baked `.fig` glyphs only after live font resolution is exhausted. +- Load character-specific remote font subsets without Latin-only assumptions, preserve cumulative subset coverage, and reject unavailable desktop font styles instead of substituting the first family face. +- Render downloaded CJK and Arabic faces under their source family names so CanvasKit produces visible glyphs, with first-paint and interactive fallback snapshots covering CJK, Arabic, and mixed scripts. +- Fix live CLI and MCP automation drifting to the wrong open document or page when multiple files are open. +- Improve Chinese, Japanese, and Korean text rendering with glyph-aware fallback fonts and outline rendering when needed. +- Preserve imported Figma text sizing more accurately, especially auto-sized text inside auto-layout frames. +- Match Figma auto-layout reflow when deleting children, hiding optional instance slots, or syncing component changes. +- Fix desktop clipboard copy, cut, and paste when browser clipboard events are unavailable. +- Fix desktop "Share This File" links so they use the public app URL. +- Fix collaborators joining a room without receiving the current document contents. +- Fix `.fig` round-trips that could corrupt files because of duplicate generated IDs. +- Fix resizing groups and boolean operations so child layers scale with the parent. +- Fix Hangul IME composition while editing text. +- Improve large layer-tree responsiveness and keep expanded state stable while editing. +- Improve AI provider setup with a connection test and clearer errors for OpenAI-compatible endpoints. +- Fix published package type resolution for TypeScript consumers. +- Fix clone operations sharing mutable data with the original, including fills, strokes, variable bindings, overrides, and vector networks. +- Fix variable bindings left behind when fills or strokes are removed. +- Improve Figma group, boolean, instance, rotated vector, complex text fill, layout grid, page guide, pattern/noise, and other imported visual details. +- Fix file-backed CLI commands under Node by avoiding Bun-only filesystem APIs. +- Improve overlap analysis accuracy for rotated stroked nodes, nested clipping, empty limits, and trimmed filter values. + +## 0.13.2 — 2026-05-30 + +### Changed + +- Update the Homebrew install command to use the published `openpencil` cask. + +### Fixes + +- Fix the published MCP package so global installs include the `openpencil-mcp` and `openpencil-mcp-http` launchers required by desktop app integrations. + +## 0.13.1 — 2026-05-29 + +### Fixes + +- Fix the npm package contents for the CLI so Bun installs include the built `openpencil` binary and runtime bundle. + +## 0.13.0 — 2026-05-29 + +### Fixes + +- Fix the published CLI package so Bun global installs run the built `openpencil` binary instead of raw TypeScript sources. + +- Greatly improve importing Figma `.fig` files with complex component systems: badges, avatars, icons, links, input fields, lists, date pickers, nested instances, component swaps, and variant properties now open much closer to their original Figma appearance. +- Fix missing or white content in imported `.fig` files caused by unresolved Figma variable bindings, including image/avatar badges, icon colors, text colors, and variable-backed component overrides. +- Preserve more Figma document details when opening and saving `.fig` files, including internal component pages, component ordering, page metadata, canvas backgrounds, text layout, glyph rendering, vector geometry, effects, shadows, and instance overrides. +- Keep user edits after opening an imported `.fig` file: changing size, position, fills, text, or layout now wins over preserved Figma round-trip data when the document is saved again. +- Fix `.fig` exports so files reopened in Figma or OpenPencil keep their pages, components, instances, text wrapping, icons, avatars, and preview thumbnail intact. +- Fix live canvas updates during move/resize/edit previews so visible scene changes repaint immediately. +- Fix accidental duplicate creation when Alt-clicking without dragging. +- Fix MCP startup in the browser. +- Fix CanvasKit loading outside the browser when project paths contain spaces. +- Render imported Figma layer and fill blend modes such as multiply, screen, overlay, difference, hue, saturation, color, and luminosity. +- Render common imported Figma mask stacks so visible layers above alpha, vector, or luminance masks are clipped by the mask shape, including consecutive mask layers. +- Render Figma-style smoothed rectangle corners, including independent corner radii, and effect blend modes from imported Figma files. +- Improve imported tiled image fills by applying Figma image transforms when repeating image patterns. +- Keep imported Figma boolean operations editable as boolean-operation nodes instead of flattening them to vectors. +- Apply imported variable font axes from Figma `fontVariations` when rendering text. +- Render more imported Figma visual metadata, including text decoration styles, leading trim, pattern fills, layout grids, page guides, and deterministic fallbacks for raw noise effects. + +### Performance + +- Open large `.fig` files faster by deferring work for pages you have not viewed yet while still preparing all needed content before export. +- Improve canvas responsiveness during zooming, panning, dragging, and editing by reusing cached scene backing where safe. +- Speed up `.fig` export for documents with many preserved Figma paint and variable payloads. + +## 0.12.2 — 2026-05-19 + +### Added + +- Allow OpenRouter users to enter any model ID from provider settings with cached autocomplete suggestions for tool-capable models, while keeping the curated dropdown as the default when no custom model is set. + +### Changed + +- Use localized app tooltips instead of native browser titles across editor controls, panels, and menus. +- Update Claude Code MCP setup documentation and the docs landing screenshot. +- Ignore non-source Markdown files in the app dev watcher so documentation edits do not reload the running editor. + +### Fixes + +- Route Claude Code stdio MCP requests through the live OpenPencil app connection, including immediate disconnected errors when no document is connected. +- Keep MCP disconnected guidance focused on starting OpenPencil and opening a document. +- Improve agent-rendered JSX compatibility with Figma-style text, alignment, and rotation aliases; strip HTML comments; and report unsupported props from render tools. +- Load exact text font styles after MCP and AI tool mutations so newly created bold/weighted text renders immediately. +- Include text style fields in MCP `get_node` output so agents can verify generated text accurately. +- Keep provider settings tooltip/popover composition working in WebKit. + +## 0.12.1 — 2026-05-19 + +### Fixes + +- Fix `.fig` round-trips for OpenPencil component sets and variable bindings, and recompute imported layouts after opening documents. +- Report desktop/MCP package version mismatches explicitly and include package-manager-aware install guidance from the MCP server. +- Support scoped MCP `save_file({ path })` workflows while keeping file saving in the desktop app. +- Use native Tauri path handling for save parent directories so Unicode and Windows paths are handled correctly. +- Fix the web font picker so Google Fonts remain available in Safari, local font access is requested on first open when supported, font sources are labeled, and Google font previews load lazily for visible rows. +- Fix background blur rendering so it blurs the backdrop behind a layer instead of applying a no-op content filter, and keep effect parameter controls visible in the properties panel. + +## 0.12.0 — 2026-05-18 + +### Added + +- Assets panel — browse, search, and insert document components directly from the left sidebar. +- Component variants — switch instance variants from the right inspector; default variant respects property definitions. +- Figma library metadata — component keys, source libraries, version IDs, descriptions, and docs links are preserved on import/export. +- Desktop file associations — double-click `.fig` or `.pen` files in Finder/Explorer to open them in OpenPencil. +- Auto-update — startup update checks and a Check for Updates menu item on desktop. +- Light theme with theme-aware canvas rulers. +- PDF export — available in the export panel, CLI (`--format pdf`), and MCP. +- SVG import tool for automation workflows. +- DeepSeek AI provider. +- Variable modes — create, rename, duplicate, delete, and set defaults per collection. +- Variable binding controls for fills, strokes, sizing, min/max, and typography fields. +- Auto-layout inspector controls for min/max dimensions, auto gap, wrap gap, and two-axis padding. +- Stroke dash/gap controls. +- Font settings — local font access, fallback predownloads, and downloaded font cache management. +- Editor commands for frame selection, paste to replace, Boolean operations, flatten, outline text, and outline stroke. +- Boolean operations panel control and canvas context-menu entries for flattening and outlining supported selections. + +### Changed + +- Smaller domain modules across core, app, Vue SDK, CLI, MCP, docs, and desktop with enforced package boundaries. +- Separate scene and overlay canvas layers — rulers, labels, and selections no longer cause scene redraws. +- Shared menu schema between browser and native Tauri menus. +- Editor command metadata now drives shortcut display across browser menus, native menus, tooltips, and context menus. +- Text-to-vector conversion now uses shared loaded-font outline geometry across Boolean, flatten, and outline commands. + +### Fixes + +- Fix `.fig` export of component variant properties and text stretch alignment so designs round-trip correctly through Figma. +- Fix CJK and Arabic text rendering — fallback fonts now load before the first paint instead of showing blank text. +- Fix large `.fig` files freezing on open — parsing runs in a worker, and the viewport fits to content after loading. +- Improve Figma import fidelity — variable aliases, nested instances, avatar swaps, badge internals, and input text alignment are preserved. +- Improve Figma export fidelity — flipped vectors, stroke geometry, visual overflow, and stroked-shape drop shadows are preserved. +- Fix variant switching so instances update their contents, not just the component reference. +- Fix text editing inside components and instances on double-click. +- Fix paste into selected containers and entered frames. +- Fix clipboard parsing to safely ignore invalid data. +- Fix undo/redo for duplicate, state restore, and modifier-key release. +- Prevent browser from intercepting app-level undo/redo shortcuts. +- Fix font loading and bundled font resolution. +- Show the startup loader until fonts load and the first render completes. +- Improve light theme polish and canvas ruler colors. +- Normalize browser zoom speed. +- Fix variable picker popovers and color binding swatches. +- Fix dashed strokes on vector nodes and gradient fills on text. +- Fix inner shadow rendering on text nodes. +- Fix imported Figma-derived underlined text rendering. +- Fix exponential `.fig` file growth on repeated save/load cycles. +- Fix opening large `.fig` files so every page populates component instances, preventing missing nested content when switching pages. +- Fix canvas size badges scaling with zoom. +- Fix layout inspector dropdown anchoring and spacing/padding icon clarity. +- Fix section drawing and color input forwarding in the property panel. +- Fix asset insertion coordinates inside entered containers. +- Fix MCP stdio handshake and eval return values. +- Fix `@open-pencil/vue` npm imports referencing an unexported core subpath. +- Fix Figma clipboard text compatibility — pasted OpenPencil text keeps editable fixed bounds, line wrapping, baselines, glyph offsets, and Figma edit-mode layout. +- Fix local font matching so requested upright and weighted faces do not fall back to italic or regular faces. +- Fix CanvasKit paragraph rendering to preserve requested text weights and slants. +- Fix nested text editing interactions — drill double-click enters nested text edit mode, and clicking another text node switches edit targets while editing. +- Fix auto-height text edit commits so text bounds and undo state stay in sync. +- Fix Boolean, flatten, and outline operations to reject unsupported image/complex-script sources safely instead of silently dropping geometry. +- Fix outline stroke enablement for stroked descendants inside groups and containers. + +### Performance + +- Event-driven canvas rendering — scene and overlay layers only repaint when their inputs change, replacing continuous polling. +- Shared RAF scheduler coalesces scene and overlay frames into a single animation frame per editor. +- Font-family fallback arrays and downloaded remote fonts are cached to avoid repeated work. +- WebGL draw-call instrumentation only runs while the profiler is active. +- Instance override resolution is cached and `.fig` pages load lazily for large files. +- Live drag/resize uses repaint-only previews to skip layout during interaction. + +## 0.11.8 — 2026-04-23 + +### Fixes + +- Fix MCP server not spawning on Windows — use `cmd /c` to resolve `.cmd` wrappers from npm global installs +- Fix MCP server and automation WebSocket not connecting on Windows/Linux — inline `__TAURI_INTERNALS__` check at call time instead of using stale module-level `IS_TAURI` constant +- Fix shell PATH not inherited by GUI app on macOS/Linux — add `fix-path-env-rs` to read shell config + +## 0.11.7 — 2026-04-22 + +### Features + +- Add stdio transport for MCP server — `openpencil-mcp` now works as a proper stdio MCP server for Claude Code, Cursor, etc. HTTP server available as `openpencil-mcp-http`. +- Default canvas background to dark when system prefers dark color scheme +- Add `list_available_fonts` MCP tool for font discovery +- Copy node ID / XPath from context menu; CLI selection command +- Arrow key nudge for selected nodes (1px, Shift+arrow for 10px) +- JSX renderer: `position="absolute"`, `top`, `left` props for absolute children inside auto-layout containers +- MCP server sends `notifications/tools/list_changed` when the desktop app connects or disconnects +- Headless text measurement via opentype.js per-glyph advance widths — no CanvasKit needed +- Add `open_file` and `new_document` MCP tools with `OPENPENCIL_MCP_ROOT` path scoping +- Optional `path` param on `export_image`, `export_svg`, `get_jsx` — write output to disk instead of returning base64/string +- Multi-root JSX support — multiple top-level elements auto-wrapped in a fragment +- `Component` and `Instance` tag aliases in JSX renderer +- JSX prop reference doc — copy to clipboard via book icon in Code panel +- Prompts (`CODEGEN_PROMPT`, `JSX_REFERENCE`) moved from embedded strings to markdown files + +### Fixes + +- Fix Backspace not deleting selected nodes after clicking on canvas — canvas now receives focus on click so keyboard shortcuts aren't blocked by stale input focus +- Support Cmd/Ctrl+click for additive multi-select in layers panel (previously only Shift+click worked) +- Fix macOS Tauri build — move `NSAllowsLocalNetworking` ATS config from invalid `tauri.conf.json` property to a proper `Info.plist` file +- Fix tab order and keyboard handling in inspector panel +- Fix design token variables not resolved before passing to yoga-layout +- Suppress keyboard shortcuts while editing property panel inputs +- Fix tooltip competing with popover trigger on Windows +- Fix hit area for nodes with rotated parents +- Error toasts auto-dismiss, deduplicate, and cap stack at 5 +- Bump yoga-layout to 3.3.0-grid.3 with `Node.free()` support +- Bump PWA precache limit for canvaskit-webgpu +- Fix color picker dragging flooding the undo stack — fill/stroke/effect color and opacity drags now collapse into a single undo entry per interaction via debounced batching in `PropertyListRoot` +- Fix .fig import crash on alias variables without a GUID +- Fix `save_file` crash on vectors with missing tangent control points — default to straight segments +- Validate `create_vector` path JSON upfront with clear error messages for malformed input +- Fix MCP/AI tools rejecting string-encoded numeric arguments from MCP clients (`"42"` → `42`) +- Fix "Create Instance" context menu item always grayed out — inverted disabled flag +- Show "Create Instance" instead of "Create Component" in context menu when a component is selected +- Fix headless layout: use stored .fig dimensions instead of rough text size estimates (26K → 11K mismatches on material3.fig) +- Fix `--help` output with huge vertical gaps between commands — remove inline examples from query description +- Fix `openpencil-mcp` npm package missing `dist/stdio.js` — explicitly list entry points in tsconfig +- Show toast when MCP server fails to start instead of silently swallowing the error +- Fix provider settings popover not appearing — tooltip wrapper broke floating-ui positioning +- Fix `set_font_range` producing invalid style runs that crash `.fig` export — use `applyStyleToRange`, apply color and fontWeight from style name +- Fix MCP "app not connected" error — message now instructs the agent to stop and inform the user +- Fix external links in AI panel blocked by Tauri ACL — use opener plugin instead of shell + +## 0.11.6 — 2026-04-08 + +### Fixes + +- Switch `@open-pencil/core` build from `tsgo` + `fix-esm-import-path` to `tsdown` — fixes bare directory imports that broke Node.js and Bun consumers + +## 0.11.5 — 2026-04-08 + +### Fixes + +- Fix published npm packages resolving to TypeScript source instead of compiled JavaScript — `publishConfig.exports` overrides are now applied during CI publish +- Fix Windows CI build failures caused by backslash file paths in custom lint rules + +## 0.11.4 — 2026-04-08 + +### Fixes + +- Fix `@open-pencil/core` published package containing stale import paths from before the domain module restructuring — CLI and MCP installs from npm now resolve correctly +- Add `save_file` MCP tool for saving the current document to disk +- Clipboard text export now writes richer v4 `derivedTextData` payloads with glyph outlines for better paste fidelity + +## 0.11.3 — 2026-04-08 + +### Fixes + +- Show actionable install errors in the chat panel when a required local AI CLI is missing +- Fix inline layer rename so clearing the name restores the default name, and Backspace/Delete inside rename inputs no longer delete the layer +- Fix rotated frame hit testing, hover highlights, and selection overlays so interactive areas and overlay labels stay aligned during rotation +- Fix text edit undo so it restores both the original text and `styleRuns` +- Pressing Enter with a selected text node now starts text editing and selects all text +- Fix `ScrubInput` Enter handling so committing a value no longer triggers a second blur-based commit that overwrites it +- Show the auto-layout panel for `COMPONENT`, `COMPONENT_SET`, and `INSTANCE` nodes +- Fix missing layout direction icons in the auto-layout controls +- Fix nested text selection inside gradient cards +- Unify the size control into a single inline sizing input/dropdown with shorter localized labels to prevent overflow + +## 0.11.2 — 2026-03-30 + +### Fixes + +- Stabilize npm publishing with isolated temp publish directories instead of mutating tracked package manifests in CI +- Strip build-time scripts and dev dependencies from generated publish manifests so tarballs pack from verified artifacts only +- Fix `@open-pencil/mcp` release packaging so the published npm tarball includes its built `dist/` CLI and server entrypoints deterministically +- Fix `@open-pencil/core` release build configuration so CI publish jobs include Node and Bun ambient types when compiling package artifacts + +## 0.11.1 — 2026-03-30 + +### Fixes + +- Fix npm publishing pipeline to publish packed tarballs instead of raw package folders +- Attempt to fix `@open-pencil/mcp` npm package contents so the published CLI includes its built `dist/` entrypoints +- Fix `@open-pencil/vue` npm package metadata and build output so the published package resolves from `dist/` while local workspace development keeps using source aliases + +## 0.11.0 — 2026-03-30 + +### Features + +- Lock and visibility toggle buttons in layers panel (hover to reveal, always shown when active) +- Figma-style selection scope — double-click to enter groups/frames/components, Escape to exit +- Nested container navigation — each double-click goes one level deeper +- Dashed border around entered container for visual feedback +- Layer panel click syncs canvas scope automatically +- Vue SDK internationalization primitives — `useI18n()`, locale detection, persisted locale selection, lazy-loaded locale JSON files, and exported locale metadata for custom editor shells +- Vue SDK docs and public API audit — documented advanced exports (`useOkHCL()`, variables helpers, viewport and locale APIs), aligned docs with the actual `provideEditor()` injection model, and expanded release-ready SDK guidance +- npm release pipeline now publishes `@open-pencil/core`, `@open-pencil/cli`, `@open-pencil/mcp`, and `@open-pencil/vue` together on version tags +- App language picker in the menu bar — switch UI locale without reloading +- Added a vector curve editor and improved drawing experience with the pen tool +- Resume pen drawing from existing open path endpoints — click an endpoint to continue the curve +- Close open paths by dragging one endpoint to the other +- Align selected anchor points relative to each other in vector edit mode — the standard alignment buttons in the position panel now operate on selected vertices when 2 or more are selected +- Unified core IO format registry — `.fig` is now modeled as the native document format alongside shared export adapters for PNG, JPG, WEBP, SVG, and JSX +- Export selection or current page as `.fig` from the app export UI and app menu +- New CLI commands: `open-pencil convert` for document conversion, `open-pencil formats` to inspect readable/writable/exportable formats, and `open-pencil lint` for design consistency, structure, and accessibility checks +- CLI export now supports `.fig` output and routes PNG/JPG/WEBP/SVG/JSX/`.fig` through the shared IO layer +- `Open…` now supports `.pen` Pencil documents through the shared document reader pipeline while keeping `.fig` as the native save format +- Display‑P3 document color space pipeline — documents now default to Display‑P3, `.fig` import/export preserves document color profiles, the live canvas requests P3 surfaces with sRGB fallback, and raster/SVG export paths accept explicit color-space targets +- Color picker overhaul — unified `RGB` / `HSL` / `HSB` / `OkHCL` field formats, slider-space-aware track/thumb previews, and better neutral-color editing behavior for fills, strokes, gradient stops, and component fills +- OkHCL metadata now round-trips through `.fig` plugin data and integrates directly into the main fill/stroke color workflow with preview gamut diagnostics +- Vue SDK now exposes reusable color-picker model helpers and solid fill/stroke commit helpers for custom editor shells +- Update built-in Z.ai and MiniMax model lists — Z.ai now uses the Anthropic-compatible endpoint for GLM coding models, adds GLM-5.1, and MiniMax adds M2.7 / M2.7-highspeed +- Arabic and RTL support across text rendering, editing, layout, export, and AI tooling — text nodes support `Auto`/`LTR`/`RTL`, auto-layout frames support `Auto`/`LTR`/`RTL` flow, and JSX/AI prompts/tools can now generate and edit both explicitly + +### Fixes + +- Fix shortcuts, now work on non-English keyboard layouts. +- Fix imported `.fig` file open and page-switch regressions — loaded documents now keep graph/store state in sync, remap imported canvas/page children correctly, and recompute imported auto-layout descendants when switching pages +- Fix first canvas render happening before fonts load — wait for fonts before the initial draw to avoid Safari and text measurement glitches +- Preserve `fig-kiwi` version on `.fig` roundtrip — imports keep the original header version instead of rewriting everything to a hardcoded value; new files default to version 101 +- Normalize auto-layout text export for Figma — text children inside auto-layout frames now serialize with `NONE` auto-resize to match Figma behavior and avoid overflow on reimport +- Fix keyboard editing regressions after the refactor — canvas shortcuts no longer fire while editing text, and Delete/Backspace no longer delete nodes during text entry +- Fix MCP page switching persistence — `switch_page` now survives across tool calls in the same session +- Improve CJK font fallback coverage — load multiple Google Fonts for broader Han/Japanese/Korean text support +- Normalize more visible UI strings for localized app chrome — menus, panels, variables dialog, code panel, chat setup, and editor controls now respect the selected locale instead of falling back to English in common flows +- Fix imported text rendering in browser and headless export — preserve stored bounds until fonts are ready, restore missing font-loaded guards, use natural width for `WIDTH_AND_HEIGHT` text, and clip text to node bounds +- Fix browser/headless rendering mismatch for imported toolbar/instance content by correcting runtime imported layout recomputation instead of diverging browser rendering behavior +- Fix `set_layout` tool not defaulting to HUG sizing when enabling auto-layout — frames now shrink/grow to fit children instead of keeping fixed dimensions +- Normalize font family names on `.fig` export — strip optical size suffixes (e.g. "DM Sans 9pt" → "DM Sans") so Figma recognizes the font +- TEXT nodes now default to a solid black fill — previously exported with no fill, making text invisible when opened in Figma +- Fix save crash when COLOR variable is missing alpha channel +- Fix console error spam on deployed web app from automation WebSocket reconnect loop +- Fix headless CLI font fallback — bundled Inter font now ships with `@open-pencil/core` and loads without a web server +- Locked nodes now block move, resize, rotate, and delete on canvas +- Locked containers block double-click enter +- Marquee selection skips locked and hidden nodes +- COMPONENT/INSTANCE containers are now enterable via double-click +- Replaced the alignment and reflection icons with the correct ones + +## 0.10.0 — 2026-03-15 + +### Performance + +- Offload .fig parsing (unzip + Kiwi decode) to a Web Worker — main thread stays responsive during file open +- Offload .fig compression to a Web Worker during save (was blocking 450ms+) +- Add instance index (`componentId → Set`) — `getInstances()` is O(1) instead of scanning all nodes +- Defer graph event subscription until after layout computation during file open — eliminates redundant `syncInstances` calls +- Cache label collection (sections/components) per scene mutation instead of walking the full tree every frame +- Blocking font loading — fonts load before first render to ensure correct glyphs + +### Features + +- ACP agent support — use Claude Code, Codex, or Gemini CLI as AI assistants in the desktop chat panel +- Permission confirmation dialog — ACP agents request user approval for file/shell operations, MCP design tools auto-approved +- Unified MCP server — single HTTP + WebSocket proxy replaces Vite SSR bridge +- Stock photo integration — `stock_photo` tool fetches images from Pexels or Unsplash and applies to design nodes. Provider adapter supports custom providers. +- Skeleton-first AI workflow — 4-phase design process (plan → skeleton → content fill via `replace_id` → polish) for more reliable AI-generated layouts +- Batched AI tools — `calc` accepts arrays of expressions, `stock_photo` fetches all images in parallel, `batch_update` applies multiple property changes in one call, `describe` accepts `ids` array for multi-node inspection +- AI visual feedback — blue pulsing border on nodes being modified, green flash on completion +- Auto-depth `describe` — adapts inspection depth to subtree size (small block → deeper, large page → shallower) +- `set_fill` gradient support — linear gradients with `color_end` and `gradient` direction params +- `render` tool `replace_id` — atomically swap skeleton placeholders with real content +- MCP `export_image_file` tool for headless PNG rendering +- Grid layout in AI chat — JSX renderer supports `grid`, `columns`, `rows`, `gap` props +- Configurable max output tokens in AI provider settings (default 16384) +- Z.ai AI provider with GLM-5, GLM-4.7, GLM-4.6, GLM-4.5 model families +- MiniMax AI provider with M2.5, M2.1, M2 models + +### Improved .fig import fidelity + +- Resolve variable-bound fill colors through alias chains +- Fix SCALE constraint resizing for auto-layout instances +- Propagate SCALE constraints through instance clone chains +- Skip self-referencing symbolOverrides on nodes with explicit kiwi properties +- Fix DSD resolution for swapped instance children +- Fix instance swap override propagation through clone chains +- Fix component property override resolution through clone chains +- Fix text/property overrides clobbered by second transitive sync + +### Fixes + +- Fix text rendering with wrong fonts on file open — all font weights (including default family) are now loaded before the first render +- Fix `weightToStyle` mapping: weight 400 now correctly maps to "Regular" instead of "Medium" +- Fix detached ArrayBuffer crash when switching pages after saving — export worker now copies image buffers before transferring +- Show warning toast when fonts fail to load, error toast when file open fails +- Fix FillPicker crash when selecting image fills (missing `ref` import from #92) +- Fix Google Fonts TLS/network errors not cached — failed families no longer retry on every render +- Fix CJK text garbled when font is unavailable — fallback now renders through paragraph shaper instead of raw `drawText`, preserving CJK characters via the fallback font chain +- Fix auto-layout overflow in AI-generated designs — text wrapping, min/max constraints, absolute positioning, and FILL sizing now work correctly +- Fix `layoutAlignSelf` limited to STRETCH — full range supported (CENTER, MAX, MIN, BASELINE) +- Fix hidden auto-layout children losing their dimensions on layout recompute +- Fix ProviderSettings popover not visible in AI chat +- Fix paste/copy/cut intercepted by canvas in AI chat input +- Strip TypeScript casts from AI-generated JSX (`as any`, `as const`) +- Fix parsing complex .fig files crashing on missing GUIDs in component overrides +- Fix headless text layout using 100×100 default size instead of estimated dimensions — multi-line wrapping now estimated correctly +- Fix clipboard roundtrip losing properties — clipsContent, constraints, arcData, strokeCap/Join, layoutAlignSelf, textAutoResize, autoRename now preserved in Figma Kiwi serialization +- Fix MCP headless export crashing on `window.queryLocalFonts` in non-browser runtimes (Bun/Node) +- Fix MCP `export_image` rendering blank text — fonts now loaded before rasterization +- Fix text always using paragraph rendering with Inter fallback chain (no more missing-font garbling) +- Clip children to rounded corners when `clipsContent` is true +- Use child shape for drop shadows on transparent containers +- Treat `FOREGROUND_BLUR` as layer blur wrapping children +- Fix radial, angular, and diamond gradient rendering +- Fix .fig export roundtrip: variable GUIDs colliding with document +- Fix file open dialog not working on first click in Safari +- Skip variable fonts from local font access, use Google Fonts instead +- Disable autosave by default + +## 0.9.0 — 2026-03-09 + +### Features + +- XPath query command — `open-pencil query design.fig "//FRAME[@width < 300]"` to find nodes by type, attributes, and tree structure using XPath selectors +- CSS Grid layout mode — select a frame, click the grid icon in the auto layout toolbar to switch from flex to grid. Configure column/row tracks (fr, fixed px, auto), column and row gaps, and per-side padding. Powered by a [Yoga fork](https://github.com/open-pencil/yoga/tree/grid) with cherry-picked CSS Grid PRs from upstream +- JSX and Tailwind CSS export for grid layouts — `grid grid-cols-N`, `gap-x-*`/`gap-y-*`, child `col-start-*`/`row-start-*`/`col-span-*`/`row-span-*` +- Multi-provider AI support — connect to Anthropic, OpenAI, Google AI, or any OpenAI-compatible endpoint directly, in addition to OpenRouter. Per-provider API key storage, provider settings popover, automatic migration from single OpenRouter key +- Anthropic-compatible provider for custom API endpoints +- New AI tools: `get_jsx` (JSX roundtrip view), `diff_jsx` (structural diff), `describe` (semantic role, visual style, layout, design issues) +- AI visual verification — `export_image` returns image content to the model for vision-based review +- API type toggle (Completions/Responses) for OpenAI-compatible providers +- Figma zoom shortcuts — ⌘0 (100%), ⌘1 (zoom to fit), ⌘2 (zoom to selection), ⇧1/⇧2 alternatives +- XPath query tool — `query_nodes` for AI/MCP with attribute selectors, tree traversal, and type filtering + +### Fixes + +- Serialize variables, collections, and bindings to `.fig` files — previously lost on save (#65) +- Text nodes created via MCP now render in Figma — emit `derivedTextData` with font metadata and layout size (#64) +- Double-click on layer tree no longer toggles expand/collapse — use the chevron instead +- Page rename input matches layer rename styling +- Fix `w="fill"`/`h="fill"` in JSX renderer — now direction-aware based on parent flex axis +- Fix text auto-resize defaulting to fixed 100×100 — text without explicit width uses `WIDTH_AND_HEIGHT` +- Fix `clipsContent` not propagated to Yoga — frames with clip enabled now set `Overflow.Hidden` +- Fix `COUNTER_ALIGN_MAP` mapping stretch to `MIN` instead of `STRETCH` +- Fix JSX export omitting x/y for absolute-positioned children +- Fix JSX export ignoring `textAutoResize` for text sizing +- Fix drag terminating on mouseleave — drags now continue outside the canvas +- Fix `export_image` stack overflow on large nodes — chunked base64 encoding +- Undo support for auto-layout reorder, layer tree reorder, and drag reparent +- Page snapshot undo for AI tool mutations +- Fix collab sync for same-parent reorder — `node:reordered` events now propagated to Yjs peers +- Fix orphaned instances on clipboard paste — detach to FRAME when component is missing +- Fix text typography lost on Figma clipboard import — preserve fontFamily, fontWeight, fontSize, lineHeight +- Fix `copyFill` missing `gradientTransform` and `imageTransform` — gradient fills now round-trip correctly + +### Performance + +- Event-driven rendering and component sync — `SceneGraph` emits typed events on mutations; `requestRender()` calls reduced from 94 to 22, component instance sync uses microtask batching with deduplication +- Replace `structuredClone` with typed copy helpers for fills, strokes, effects, and style runs (~24× faster in hot paths) +- Filter .fig unzip to only decompress canvas and image entries, skipping metadata cruft + +### Improvements + +- Padding on a frame auto-enables vertical auto-layout +- AI tools run `computeAllLayouts` after execution — layout updates immediately +- Enhanced AI system prompt with full JSX prop reference and verification workflow +- Chat panel preserves messages when toggling UI visibility +- SceneGraph event bus (nanoevents) — `node:created`, `node:updated`, `node:deleted`, `node:reparented`, `node:reordered` events replace monkey-patching in collab sync and manual render invalidation +- Replace esbuild-wasm (14 MB) with sucrase (201 KB) for JSX transform — `buildComponent()` and `renderJSX()` now synchronous and browser-compatible +- `useMagicKeys` keyboard shortcut system — replaces tinykeys with VueUse built-in, cross-platform Meta/Control handling, modifier exclusion for combo conflicts +- Dev-only debug toolbar for copying chat logs +- Auto-layout icons in layer tree — vertical (rows), horizontal (columns), and grid icons for auto-layout frames; components keep their purple diamond +- Frame titles on canvas are now draggable — clicking a selected top-level frame's name label starts a drag +- Compact layout controls — icon-based gap (↔/↕) and padding (T/R/B/L) inputs instead of text labels +- Auto-detect horizontal vs vertical direction when wrapping in auto layout (Shift+A) +- Fix alignment grid for vertical layouts — visual positions now match spatial axes +- Fix grid switch from HUG-sized frames — frame expands to fit children +- Remove unwanted white fill when wrapping in auto layout + +## 0.8.0 — 2026-03-07 + +### Features + +- Mobile layout & PWA — responsive editor with touch-optimized toolbar, swipeable bottom drawer (layers/properties/design/code), HUD overlay, and installable PWA with icons and service worker +- Tailwind CSS v4 JSX export — export selections as HTML with Tailwind utility classes (`
`) from the Code panel, CLI (`bun open-pencil export --format jsx --style tailwind`), or programmatically via `sceneNodeToJSX(id, graph, 'tailwind')`. Supports layout, sizing, colors, border radius, opacity, rotation, overflow, shadows, blur, and typography. Uses v4 spacing semantics (px/4 multiplier) with automatic fallback to arbitrary values. +- Code panel format toggle — switch between OpenPencil (custom components) and Tailwind (HTML + utility classes) output +- Homebrew tap — `brew install open-pencil/tap/open-pencil` for macOS (arm64 + x64), auto-updated on each release +- Double-click to rename layers — inline rename in layer panel, shared `useInlineRename` composable +- New AI/MCP tools: `analyze_colors`, `analyze_typography`, `analyze_spacing`, `analyze_clusters`, `diff_create`, `diff_show`, `get_components`, `get_current_page`, `arrange`, `node_to_component` +- CLI-to-app RPC bridge — all CLI commands work against the running app when no file is specified. Start the app, then run `bun open-pencil tree` to inspect the live document +- VitePress docs site — user guide, reference, architecture, and development docs at openpencil.dev with 6 locales (en, de, fr, es, it, pl), SEO (OG tags, hreflang, JSON-LD, sitemap), and dark theme + +### Improvements + +- Refactor mobile drawer tabs, layout sizing dropdowns, and inline rename to use Reka UI primitives +- Add shared UI style helpers with tailwind-variants for menus, selects, buttons, and surfaces +- Unified tool definitions — define once in `packages/core/src/tools/`, automatically available in AI chat, CLI, and MCP +- Harden FigmaAPI — hide internals via Symbols, freeze arrays, fix `layoutSizing`, 30+ new properties and methods +- Split tools into domain files (read, create, modify, structure, variables, vector, analyze) — easier to navigate and extend +- Replace inline type definitions with named types (`Color`, `Vector`, `SceneNode`) across the codebase +- Split 3200-line `renderer.ts` into `packages/core/src/renderer/` with 10 focused files (scene, overlays, fills, strokes, shapes, effects, rulers, labels) +- Centralize all color utilities in `packages/core/src/color.ts` — `colorToHex8`, `colorToCSSCompact`, `normalizeColor`, `colorDistance`; remove 5 duplicate implementations across the codebase +- Add `geometry.ts` with shared rotation math (`degToRad`, `radToDeg`, `rotatePoint`, `rotatedCorners`, `rotatedBBox`) +- Extract `isArrayMixed()` helper for multi-selection property panels + +### Fixes + +- Fix drawer animation jump on close — single spring transition instead of two-phase +- Fix `ALL_TOOLS` registry missing newer tools (`analyzeColors`, `diffCreate`, `exportImage`, `arrangeNodes`) +- Fix `renderJSX` typo in tool definitions (`renderJsx` → `renderJSX`) +- Fix all oxlint warnings and tsgo errors — replace `!` non-null assertions in `use-collab.ts` with local const captures +- Fix broken test imports — stale `../../src/engine/` paths updated to `@open-pencil/core` +- Fix flaky E2E tests: layers panel navigates to `/demo`, zoom-to-fit test zooms in first, snapshot rendering stabilized with `workers: 1` and `colorScheme: dark` +- Fix bogus .fig import mappings for `expanded` and `strokeMiterLimit` fields +- Fix PWA manifest error in dev mode, handle invalid font data gracefully +- Fix eval response unwrapping and `export_jsx` page selection in RPC bridge +- Fix automation commands not recomputing layouts after mutations +- Fix workspace dependency not resolved when installing from npm (switch CI to pnpm publish) + +### Internal + +- Add `motion-v` for declarative animations — used in mobile drawer (spring-animated height with pan gestures) and toolbar (layout-animated category switching with directional slide transitions) +- Mobile drawer: replace `useSwipe` + manual rAF animation with `motion.div` `:animate` + `@pan`/`@panEnd`; always-on tab state (no more null `activeRibbonTab`); content stays rendered when closed +- Mobile toolbar: replace manual `scrollWidth` measuring + inline CSS transitions with `motion.div layout` + `AnimatePresence` directional slide variants +- Mobile UI cleanup: extract shared `colorToCSS` util to core, `initials` to `src/utils/text`, `toolIcons` to `src/utils/tools`; replace hand-rolled dropdowns with reka-ui Popover/DropdownMenu; narrow `mobileDrawerSnap` type to string union; move magic numbers to constants; disable PWA service worker in dev mode +- 83 new E2E tests (57 → 140): design panel, code panel, components, copy/paste, multi-page, text editing, keyboard shortcuts, context menu +- 150 new unit tests (588 → 738): color, undo, snap, vector, style-runs, text-editor +- 48 new E2E tests (9 spec files) + 26 mutation unit tests + store/canvas test helpers +- Add `data-test-id` attributes to AppearanceSection, LayoutSection, TypographySection, VariablesDialog, EditorView + +## 0.7.0 — 2026-03-05 + +### Features + +- SVG export — export selections as SVG from the export panel, context menu, CLI (`bun open-pencil export --format svg`), or MCP/AI tools (`export_svg`). Supports rectangles, ellipses, lines, stars, polygons, vectors, text with style runs, gradients, image fills, effects, blend modes, clip paths, and nested groups (#46) +- Copy/Paste as submenu in context menu — Copy as text, Copy as SVG, Copy as PNG (⇧⌘C), Copy as JSX +- Stroke align (Inside/Center/Outside) with clip-based rendering matching Figma behavior +- Individual stroke weights per side (Top/Right/Bottom/Left) with side selector dropdown +- Google Fonts fallback — automatically loads fonts from Google Fonts API when not available locally +- Auto-save toggle in File menu — disable to prevent automatic writes to the opened .fig file +- Renderer profiler with in-canvas HUD overlay, GPU timing, and phase instrumentation + +### Improvements + +- Replace custom color picker with Reka UI Color components (ColorArea, ColorSlider, ColorField) — adds keyboard navigation and accessibility to the color area, hue, and alpha controls + +### Fixes + +- CJK text rendering — load a system CJK font (PingFang SC, Microsoft YaHei, Noto Sans CJK) as fallback; falls back to Noto Sans SC from Google Fonts when no system font is available (#48) +- Font registration errors no longer cache invalid font data — `loadFont` only caches after successful CanvasKit registration +- Fix `render` tool failing on Windows + Bun with "Cannot find module" error (#43) +- Fix hover highlighting nodes from internal component pages — scope hit-test to current page +- Fix hit-testing on transparent frames and groups — empty containers without fills or strokes are now click-through, clipping parents reject hits outside their bounds, matching Figma behavior +- Fix instance overrides on .fig import and clipboard paste — resolve guidPaths by overrideKey, handle component swaps (`overriddenSymbolID`), propagate through nested clone chains. Import and paste now share a single override engine. +- Apply Figma component property assignments on import — boolean visibility toggles and instance swaps via `componentPropRefs`/`componentPropAssignments` +- Apply `derivedSymbolData` sizes on import — containers now shrink correctly when component properties hide children +- Fix override resolution for nested instance targets — check the current node before searching descendants +- Fix component property assignments for nested instances — resolve scoped `componentPropAssignments` inside `symbolOverrides` via guidPath, handle `guidValue` for instance swaps, reorder phases so transitive sync doesn't clobber visibility +- Pixel-perfect vector rendering using pre-computed `fillGeometry`/`strokeGeometry` blobs from .fig files — eliminates white gaps between adjacent stroked shapes +- Stroke outlines on clipboard paste — convert vectorNetwork paths to filled outlines via CanvasKit when geometry blobs are unavailable +- Apply `derivedSymbolData` transforms and geometry during import — instance children render at correct scale and position +- Fix internal pages becoming visible after .fig round-trip — preserve `internalOnly` flag on export +- Scope layout recomputation to current page for paste/undo/font-load (major speedup on large multi-page files) +- Show loading overlay until all document fonts are loaded (no more partially rendered text) +- Load fonts when switching pages (previously only loaded for the first page) +- Always show visibility toggle on fill, stroke, and effect rows (matches Figma) +- Fix renderer crash on double destroy when closing files quickly +- Fix .fig page ordering — use deterministic byte comparison for fractional index positions +- Fix text truncation using `textTruncation` field instead of `textAutoResize` +- Fix horizontal scrollbar on design and pages panels +- Style scrollbars for Tauri (thin dark overlay instead of default OS chrome) +- Enable file watcher in Tauri — `watch` feature was missing from `tauri-plugin-fs` + +## 0.6.0 — 2026-03-04 + +### Features + +- Multi-selection properties panel — edit position, size, appearance, fill, stroke, and effects across multiple selected nodes +- Shared values display normally, differing values show "Mixed" +- W/H inputs in multi-selection mode +- Flip horizontal/vertical using scale transform instead of rotation +- Single-node alignment aligns to parent frame bounds +- ACP agent package — Agent Communication Protocol server for AI coding tools, reusing core ToolDefs + +### Build + +- Apple code signing and notarization for macOS builds +- Git LFS storage moved from GitHub to Cloudflare R2 + +### Fixes + +- Fix Figma clipboard paste: extract shared kiwi→SceneNode conversion, fixing broken auto-layout, missing gradient/image fills, effects, style runs, and text properties +- Fix vector rendering on paste — scale path coordinates from Figma's normalizedSize to actual node bounds +- Fix pasted instances having no children — populate from component via symbolData when both are in clipboard +- Detect component sets on import — promote FRAME nodes with VARIANT componentPropDefs to COMPONENT_SET +- Skip internal canvas on paste — components on Figma's hidden internal page populate instances but are not pasted as visible nodes +- Apply instance overrides on paste — text content, fills, visibility, layoutGrow, and textAutoResize from symbolOverrides +- Fix auto-layout child ordering — sort by geometric position instead of z-order position strings +- Load fonts on paste and .fig import — collect font families from text nodes and load into CanvasKit +- Text measurement in auto-layout — use CanvasKit paragraph metrics for WIDTH_AND_HEIGHT text nodes +- Recompute layouts after font loading completes +- Fix PERCENT line height conversion — was stored as raw value instead of pixels +- Fix InvalidCharacterError when copying nodes with non-ASCII text +- Load all font weight/style variants needed by pasted text nodes +- Fix font loading not registering in core cache +- Fix halfLeading applied to text measurement — enable only for rendering +- Clear hover on zoom/pinch to keep scene picture cache valid +- Fix flip buttons using rotation math instead of actual mirroring +- Fix flip transform encoding — scale first matrix column only (was incorrectly producing 180° rotation) +- Decode flip state from .fig transform matrix on import + +## 0.5.1 — 2026-03-03 + +### Fixes + +- Fix File → Save crash when document has layer blur effects + +## 0.5.0 — 2026-03-03 + +### Features + +- Effects rendering: drop shadow, inner shadow, shadow spread, layer blur, background blur, foreground blur +- Text shadows render on glyphs instead of bounding box +- Multi-file tabs — open multiple documents in tabs within a single window +- Tab bar with close buttons, middle-click to close, and new tab (+) button +- Keyboard shortcuts: ⌘N/⌘T new tab, ⌘W close tab, ⌘O opens in new tab +- Native Tauri menu: File → New and File → Close Tab wired to tab actions +- Render text from SkPicture cache when fonts are missing — pixel-perfect display without the font installed +- Missing font indicator (⚠) next to font picker in the sidebar +- Right-click context menu on layers panel — same actions as the canvas context menu +- 40+ new AI/MCP tools ported from figma-use: + - Granular set tools: `set_rotation`, `set_opacity`, `set_radius`, `set_minmax`, `set_text`, `set_font`, `set_font_range`, `set_text_resize`, `set_visible`, `set_blend`, `set_locked`, `set_stroke_align` + - Node operations: `node_bounds`, `node_move`, `node_resize`, `node_ancestors`, `node_children`, `node_tree`, `node_bindings`, `node_replace_with` + - Variable CRUD: `get_variable`, `find_variables`, `create_variable`, `set_variable`, `delete_variable`, `bind_variable` + - Collection CRUD: `get_collection`, `create_collection`, `delete_collection` + - Boolean operations: `boolean_union`, `boolean_subtract`, `boolean_intersect`, `boolean_exclude` + - Vector path tools: `path_get`, `path_set`, `path_scale`, `path_flip`, `path_move` + - Create tools: `create_page`, `create_vector`, `create_slice` + - Viewport: `viewport_get`, `viewport_set`, `viewport_zoom_to_fit`, `page_bounds` + - Misc: `flatten_nodes`, `list_fonts` +- `set_text_properties` tool: alignment, auto-resize, decoration +- `set_layout_child` tool: sizing, grow, align_self, positioning +- 13 MCP server integration tests via `InMemoryTransport` + +### UI + +- Resizable pages/layers split in left panel with reka-ui Splitter +- Layers tree auto-expands and scrolls to reveal selected node +- Loading overlay on canvas while opening .fig files +- Hide internal-only pages (e.g. "Internal Only Canvas" in design systems) +- Render page dividers — pages named with only dashes/asterisks/spaces show as horizontal lines +- Only show component labels for COMPONENT and COMPONENT_SET, not instances +- Replace all native `` dropdowns with reka-ui `AppSelect` component -- Smoother trackpad pinch-to-zoom with `Math.exp` curve and deltaMode normalization -- Fix font picker dropdown truncating long font names -- Show explanation in font picker when Local Font Access API unavailable (Safari/Firefox) - -### Fixes - -- Fix drop shadow rendering on top of fills — shadow now draws behind opaque content -- Fix effect property changes not recorded in undo/redo history -- Fix active tab text invisible against same-color background -- Fix clipboard "Outside int range" error — `pasteID` used unsigned int exceeding Kiwi's signed 32-bit field -- Error toasts are now sticky (don't auto-dismiss), with selectable text, copy button, and close button -- Truncate long node names in export button - -### Performance - -- Per-node SkPicture cache for effect rendering — unchanged shadow/blur nodes replay from cache on scene redraws -- Drop shadows use `MaskFilter` direct draw instead of `saveLayer` offscreen buffers -- Cached `ImageFilter`, `MaskFilter`, reusable effect paint — zero per-frame WASM allocations for effects -- Reuse GL context on panel resize — swap surface without recreating renderer, preserving all caches -- Per-frame absolute position cache — avoids repeated parent-chain walks during rendering -- Optimize zoom/pan smoothness with `shallowReactive`, `useRafFn`, and input coalescing - -### Build - -- Auto-populate GitHub Release notes from CHANGELOG.md via `ffurrer2/extract-release-notes@v2` -- Skip already-published npm versions on CI re-runs instead of failing -- Exclude non-app directories from Vite file watcher - -### Internal - -- Extract shared color constants (`BLACK`, `TRANSPARENT`, `DEFAULT_SHADOW_COLOR`) — replaces 8 inline literals across core -- Extract shared `NodeContextMenuContent` component to avoid menu duplication -- Fix `@open-pencil/core` dep in MCP package: `workspace:*` for local dev (pnpm resolves at publish time) -- Replace store thunks with a late-binding proxy - -### Tests - -- Clipboard roundtrip tests: encode to Figma Kiwi binary → decode → verify -- 9 visual regression snapshot tests for effects rendering -- Zoom/pan E2E tests and pipeline benchmark -- MCP server edge-case tests for `find_nodes` and Zod validation -- 6 unit tests for absolute position cache - -## [0.4.2] (2026-03-02) - -### Fixes - -- Fix Figma clipboard paste: skip non-visual node types (variables, widgets, stickies, connectors) -- Fix text not rendering after paste — `letterSpacing` from Figma is a `{value, units}` object, was passed as-is → `NaN` broke CanvasKit paragraph layout -- Fix undo/redo for Figma paste — no undo entry was recorded; redo duplicated `childIds` -- Center pasted Figma content in viewport instead of using original coordinates -- Compute auto-layouts after clipboard paste (same as .fig import and demo creation) - -### Improvements - -- Import additional properties from Figma clipboard: `layoutAlignSelf`, `clipsContent`, `fontWeight`, `italic`, `letterSpacing`, `lineHeight` -- Convert `letterSpacing` PERCENT units to pixels based on font size - -### Tests - -- 7 new clipboard import unit tests (14 total) - -## [0.4.1] (2026-03-02) - -### Fixes - -- Fix text disappearing after hover when SkPicture cache was recorded before fonts loaded -- Invalidate scene picture cache on font load to prevent stale fallback text - -### Docs - -- Highlight copy & paste with Figma in README and feature docs -- Replace "fig-kiwi" format name with "Kiwi binary" — the format is shared between .fig files and clipboard - -## [0.4.0] (2026-03-02) - -### Features - -- MCP server (`@open-pencil/mcp`) — 29 tools for headless .fig editing via stdio (Claude Code, Cursor, Windsurf) or HTTP (Hono + Streamable HTTP with sessions) -- `openpencil-mcp` and `openpencil-mcp-http` binaries — install globally via `bun add -g @open-pencil/mcp` - -### Build - -- All packages emit JS via tsgo + fix-esm-import-path — `@open-pencil/core` and `@open-pencil/mcp` work on Node.js without Bun -- Core package exports: `bun` condition → src (dev), `import` condition → dist (npm consumers) -- `@open-pencil/mcp` added to CI publish workflow - -## [0.3.2] (2026-03-02) - -### Performance - -- Re-apply SkPicture scene caching for ~7x faster pan/zoom (0.98ms vs 6.8ms per frame at 500 nodes) - -### Tests - -- Visual regression tests for SkPicture cache: hover on/off cycle, multiple cycles, mouse hover, scene change + hover -- Type `window.__OPEN_PENCIL_STORE__` globally, remove ad-hoc casts from tests - -## [0.3.1] (2026-03-02) - -### Fixes - -- Fix text disappearing after hovering a frame (revert SkPicture scene caching) -- Fix macOS startup hang: async font loading, show window on reopen - -## [0.3.0] (2026-03-01) - -### Performance - -- SkPicture scene caching — pan/zoom replays cached display list instead of re-rendering all nodes -- Cache vector network paths — avoid rebuilding WASM paths every frame -- Cache ruler and pen overlay paints — eliminate 10 WASM Paint allocations per frame -- Only enable `preserveDrawingBuffer` in test mode -- Hoist URL param parsing out of render loop - -### Fixes - -- Fix npm publish: use pnpm for workspace dependency resolution with provenance -- CLI version now reads from package.json instead of hardcoded value -- Update README: accurate app size (~7 MB), streamlined feature list, current project structure - -## [0.2.1] (2026-03-01) - -### UI - -- Panel header with app logo, editable document name, and sidebar toggle -- ⌘\\ to toggle side panels for distraction-free canvas -- Panels hidden by default on mobile (< 768px) -- Floating bar with logo, filename, and restore button when panels hidden -- Always show local user avatar in collab header -- Touch support for pan and pinch-zoom on iOS - -### Performance - -- Stubbed shiki to remove 9MB of unused language grammars (20MB → 11MB bundle) - -## [0.2.0] (2026-03-01) - -### Collaboration - -- Real-time P2P collaboration via Trystero (WebRTC) + Yjs CRDT -- Peer-to-peer sync — no server relay, zero hosting cost -- WebRTC signaling via MQTT public brokers -- STUN (Google, Cloudflare) + TURN (Open Relay) for NAT traversal -- Awareness protocol: live cursors, selections, presence -- Figma-style colored cursor arrows with name pills -- Click peer avatar to follow their viewport, click again to stop -- Stale cursor cleanup on peer disconnect -- Local persistence via y-indexeddb — room survives page refresh -- Share link at `/share/` with vue-router -- Secure room IDs via `crypto.getRandomValues()` -- Removed Cloudflare Durable Object relay server (`packages/collab/`) - -### UI - -- Toast notifications via Reka UI Toast — top-center blue pill for info, red for errors -- Global error handler (window.error + unhandledrejection) shows errors as toasts -- Link copied toast on share and copy link actions -- HsvColorArea extracted as shared component (ColorPicker + FillPicker) -- Scrollable app menu without visible scrollbar -- Selection broadcasting to remote peers - -## [0.1.0-alpha] (2026-03-01) - -First public alpha. The editor is functional but not production-ready. - -### Editor - -- Canvas rendering via CanvasKit (Skia WASM) on WebGL surface -- Rectangle, Ellipse, Line, Polygon, Star drawing tools -- Pen tool with vector network model (bezier curves, open/closed paths) -- Inline text editing on canvas with phantom textarea for input/IME -- Rich text formatting: bold, italic, underline per-character via style runs -- Font picker with system font enumeration (font-kit on desktop, Local Font Access API in browser) -- Auto-layout via Yoga WASM (direction, gap, padding, justify, align, child sizing) -- Components, instances, component sets with live sync and override preservation -- Variables with collections, modes, color bindings, alias chains -- Undo/redo for all operations (inverse-command pattern) -- Snap guides with rotation-aware edge/center snapping -- Canvas rulers with selection range badges -- Marquee selection, multi-select, resize handles, rotation -- Group/ungroup, z-order, visibility, lock -- Sections with title pills and auto-adoption of overlapping nodes -- Multi-page documents with independent viewport state -- Hover highlight following node geometry (ellipses, rounded rects, vectors) -- Context menu with clipboard, z-order, grouping, component, and visibility actions -- Color picker with HSV, gradients (linear, radial, angular, diamond), image fills -- Properties panel: position, appearance, fill, stroke, effects, typography, layout, export -- ScrubInput drag-to-change number controls -- Resizable side panels via reka-ui Splitter - -### File Format - -- .fig file import via Kiwi binary codec (194 definitions, ~390 fields) -- .fig file export with Kiwi encoding, Zstd compression, thumbnail generation -- Figma clipboard: copy/paste between OpenPencil and Figma -- Round-trip fidelity for supported node types - -### AI Integration - -- Built-in AI chat in properties panel (⌘J) -- Direct browser → OpenRouter communication, no backend -- Model selector: Claude, Gemini, GPT, DeepSeek, Qwen, Kimi, Llama -- 10 AI tools: create_shape, set_fill, set_stroke, update_node, set_layout, delete_node, select_nodes, get_page_tree, get_selection, rename_node -- Streaming markdown responses (vue-stream-markdown) -- Tool call timeline with collapsible details - -### Code Panel - -- JSX export of selected nodes with Tailwind-like shorthand props -- Syntax highlighting via Prism.js -- Copy to clipboard - -### CLI (`@open-pencil/cli`) - -- `info` — document stats, node types, fonts -- `tree` — visual node tree -- `find` — search by name/type -- `export` — render to PNG/JPG/WEBP at any scale -- `node` — detailed properties by ID -- `pages` — list pages with node counts -- `variables` — list design variables and collections -- `eval` — run scripts with Figma-compatible plugin API -- `analyze colors` — color palette usage -- `analyze typography` — font/size/weight distribution -- `analyze spacing` — gap/padding values -- `analyze clusters` — repeated patterns -- All commands support `--json` - -### Core (`@open-pencil/core`) - -- Scene graph with flat Map storage and parentIndex tree -- FigmaAPI with ~65% Figma plugin API compatibility -- JSX renderer (TreeNode builder functions with shorthand props) -- Kiwi binary codec (encode/decode) -- Vector network blob encoder/decoder - -### Desktop App - -- Tauri v2 (~5 MB) -- Native menu bar, save/open dialogs -- System font enumeration via font-kit -- Zstd compression in Rust -- macOS and Windows builds via GitHub Actions - -### Web App - -- Runs at [app.openpencil.dev](https://app.openpencil.dev) -- No installation required -- File System Access API for save/open (Chrome/Edge), download fallback elsewhere - -### Documentation - -- [openpencil.dev](https://openpencil.dev) — VitePress site with user guide, reference, and development docs -- Deployed via Cloudflare Pages From 798a3c2b2c60b58c844cf50ed3ba405e61b93974 Mon Sep 17 00:00:00 2001 From: Danila Poyarkov Date: Sat, 18 Jul 2026 04:22:38 +0300 Subject: [PATCH 12/12] fix(editor): harden opacity shortcuts - Match numeric keypad input by generated key so NumLock-off navigation remains available - Coalesce buffered opacity updates into one undo interaction - Add end-to-end coverage for digit composition, modifiers, and undo --- bun.lock | 1 - package.json | 1 - packages/core/src/editor/nodes.ts | 16 +++-- packages/scene-graph/src/undo.ts | 23 ++++++-- packages/vue/src/editor/commands/context.ts | 2 +- packages/vue/src/editor/commands/selection.ts | 5 +- packages/vue/src/editor/commands/use.ts | 6 +- src/app/shell/keyboard/actions.ts | 21 +++++-- src/app/shell/keyboard/registry.ts | 22 ++++--- tests/e2e/keyboard/shortcuts.spec.ts | 59 +++++++++++++++++++ tests/engine/editor/opacity.test.ts | 25 ++++++++ 11 files changed, 146 insertions(+), 35 deletions(-) diff --git a/bun.lock b/bun.lock index fe5081831..2404ffe91 100644 --- a/bun.lock +++ b/bun.lock @@ -44,7 +44,6 @@ "jspdf": "^4.2.1", "lib0": "^0.2.117", "motion-v": "^2.0.0", - "ofetch": "^1.5.1", "opentype.js": "^2.0.0", "prismjs": "^1.30.0", "reka-ui": "^2.9.0", diff --git a/package.json b/package.json index 26e4be1cf..1196c589f 100644 --- a/package.json +++ b/package.json @@ -97,7 +97,6 @@ "jspdf": "^4.2.1", "lib0": "^0.2.117", "motion-v": "^2.0.0", - "ofetch": "^1.5.1", "opentype.js": "^2.0.0", "prismjs": "^1.30.0", "reka-ui": "^2.9.0", diff --git a/packages/core/src/editor/nodes.ts b/packages/core/src/editor/nodes.ts index 0a35eea31..ce19f306d 100644 --- a/packages/core/src/editor/nodes.ts +++ b/packages/core/src/editor/nodes.ts @@ -60,7 +60,7 @@ export function createNodeActions(ctx: EditorContext) { ctx.requestRender() } - function setOpacity(opacity: number) { + function setOpacity(opacity: number, coalesceKey?: string) { if (!Number.isFinite(opacity)) return const clamped = Math.max(0, Math.min(1, opacity)) const ids = [...ctx.state.selectedIds] @@ -68,11 +68,15 @@ export function createNodeActions(ctx: EditorContext) { const targets = ids.map((id) => ctx.graph.getNode(id)).filter((n): n is SceneNode => n != null) const changed = targets.filter((t) => t.opacity !== clamped) if (changed.length === 0) return - ctx.undo.runBatch('Set opacity', () => { - for (const target of changed) { - updateNodeWithUndo(target.id, { opacity: clamped }, 'Set opacity') - } - }) + ctx.undo.runBatch( + 'Set opacity', + () => { + for (const target of changed) { + updateNodeWithUndo(target.id, { opacity: clamped }, 'Set opacity') + } + }, + coalesceKey + ) } return { diff --git a/packages/scene-graph/src/undo.ts b/packages/scene-graph/src/undo.ts index af9780c23..268aa556f 100644 --- a/packages/scene-graph/src/undo.ts +++ b/packages/scene-graph/src/undo.ts @@ -2,6 +2,7 @@ export interface UndoEntry { label: string forward: () => void inverse: () => void + coalesceKey?: string } export interface UndoManagerOptions { @@ -11,6 +12,7 @@ export interface UndoManagerOptions { interface UndoBatch { label: string entries: UndoEntry[] + coalesceKey?: string } const DEFAULT_HISTORY_LIMIT = 200 @@ -63,8 +65,8 @@ export class UndoManager { return entry.label } - beginBatch(label: string): void { - this.batches.push({ label, entries: [] }) + beginBatch(label: string, coalesceKey?: string): void { + this.batches.push({ label, entries: [], coalesceKey }) } commitBatch(): void { @@ -77,8 +79,8 @@ export class UndoManager { else this.pushUndoEntry(entry) } - runBatch(label: string, fn: () => T): T { - this.beginBatch(label) + runBatch(label: string, fn: () => T, coalesceKey?: string): T { + this.beginBatch(label, coalesceKey) try { const result = fn() this.commitBatch() @@ -129,12 +131,21 @@ export class UndoManager { return { label: batch.label, forward: () => batch.entries.forEach((entry) => entry.forward()), - inverse: () => batch.entries.toReversed().forEach((entry) => entry.inverse()) + inverse: () => batch.entries.toReversed().forEach((entry) => entry.inverse()), + coalesceKey: batch.coalesceKey } } private pushUndoEntry(entry: UndoEntry): void { - this.undoStack.push(entry) + const previous = this.undoStack.at(-1) + if (entry.coalesceKey && previous?.coalesceKey === entry.coalesceKey) { + this.undoStack[this.undoStack.length - 1] = { + ...entry, + inverse: previous.inverse + } + } else { + this.undoStack.push(entry) + } this.redoStack = [] this.trimUndoStack() } diff --git a/packages/vue/src/editor/commands/context.ts b/packages/vue/src/editor/commands/context.ts index cb0eaecd3..aa6f989e3 100644 --- a/packages/vue/src/editor/commands/context.ts +++ b/packages/vue/src/editor/commands/context.ts @@ -16,5 +16,5 @@ export type EditorCommandMapOptions = { messages: CommandMessagesStore otherPages: ComputedRef> moveSelectionToPage: (pageId: string) => void - getOpacityTarget: () => number + getOpacityTarget: () => { value: number; coalesceKey?: string } } diff --git a/packages/vue/src/editor/commands/selection.ts b/packages/vue/src/editor/commands/selection.ts index 6753b53ef..6047e4d96 100644 --- a/packages/vue/src/editor/commands/selection.ts +++ b/packages/vue/src/editor/commands/selection.ts @@ -269,7 +269,10 @@ export function createSelectionCommands({ return t.value.setOpacity }, enabled: capabilities.canSetOpacity, - run: () => editor.setOpacity(getOpacityTarget()) + run: () => { + const target = getOpacityTarget() + editor.setOpacity(target.value, target.coalesceKey) + } } } } diff --git a/packages/vue/src/editor/commands/use.ts b/packages/vue/src/editor/commands/use.ts index a628c0550..b98e4851f 100644 --- a/packages/vue/src/editor/commands/use.ts +++ b/packages/vue/src/editor/commands/use.ts @@ -41,9 +41,9 @@ export function useEditorCommands() { editor.moveToPage(pageId) } - let opacityTarget = 1 - function setOpacityTarget(value: number) { - opacityTarget = value + let opacityTarget: { value: number; coalesceKey?: string } = { value: 1 } + function setOpacityTarget(value: number, coalesceKey?: string) { + opacityTarget = coalesceKey ? { value, coalesceKey } : { value } } const commands = createEditorCommandMap({ diff --git a/src/app/shell/keyboard/actions.ts b/src/app/shell/keyboard/actions.ts index b0ac6eb02..83805e537 100644 --- a/src/app/shell/keyboard/actions.ts +++ b/src/app/shell/keyboard/actions.ts @@ -102,18 +102,31 @@ export function createKeyboardActions({ } let opacityBuffer = '' + let opacitySelectionKey = '' + let opacityCoalesceKey = '' let opacityResetTimer: ReturnType | undefined + function resetOpacityBuffer() { + opacityBuffer = '' + opacitySelectionKey = '' + opacityCoalesceKey = '' + clearTimeout(opacityResetTimer) + } + function opacityDigit(digit: string) { if (store.state.selectedIds.size === 0) return + const selectionKey = [...store.state.selectedIds].sort().join('\0') + if (selectionKey !== opacitySelectionKey) resetOpacityBuffer() + if (!opacityBuffer) { + opacitySelectionKey = selectionKey + opacityCoalesceKey = crypto.randomUUID() + } opacityBuffer += digit if (opacityBuffer.length > 3) opacityBuffer = opacityBuffer.slice(-3) - setOpacityTarget(opacityFromBuffer(opacityBuffer)) + setOpacityTarget(opacityFromBuffer(opacityBuffer), opacityCoalesceKey) runCommand('selection.setOpacity') clearTimeout(opacityResetTimer) - opacityResetTimer = setTimeout(() => { - opacityBuffer = '' - }, 800) + opacityResetTimer = setTimeout(resetOpacityBuffer, 800) } return { diff --git a/src/app/shell/keyboard/registry.ts b/src/app/shell/keyboard/registry.ts index 506e8eb00..a9706c83e 100644 --- a/src/app/shell/keyboard/registry.ts +++ b/src/app/shell/keyboard/registry.ts @@ -20,6 +20,7 @@ type ShortcutDefinition = { id: string keys: string | string[] run: ShortcutAction + shouldPreventDefault?: (event: KeyboardEvent) => boolean } function commandShortcut( @@ -36,19 +37,16 @@ function commandShortcuts(...commands: EditorCommandId[]): ShortcutDefinition[] }) } -const OPACITY_CODES = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'].flatMap((d) => [ - `Digit${d}`, - `Numpad${d}` -]) - function opacityBindings(): ShortcutDefinition[] { - return OPACITY_CODES.map((code) => ({ - id: `opacity-${code}`, - keys: code, - run: ({ keyEvent, actions }: KeyboardShortcutRunOptions) => { + return ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'].map((digit) => ({ + id: `selection-opacity-${digit}`, + keys: digit, + run: ({ keyEvent, actions }) => { if (keyEvent.metaKey || keyEvent.ctrlKey || keyEvent.altKey || keyEvent.shiftKey) return - actions.opacityDigit(code.slice(-1)) - } + actions.opacityDigit(digit) + }, + shouldPreventDefault: (event) => + !event.metaKey && !event.ctrlKey && !event.altKey && !event.shiftKey })) } @@ -161,8 +159,8 @@ export function registerKeyboardShortcuts(options: KeyboardShortcutOptions) { for (const shortcut of shortcuts) { bindShortcut(bindings, shortcut.keys, (event) => { - event.preventDefault() shortcut.run(runOptions(event)) + if (shortcut.shouldPreventDefault?.(event) ?? true) event.preventDefault() }) } diff --git a/tests/e2e/keyboard/shortcuts.spec.ts b/tests/e2e/keyboard/shortcuts.spec.ts index 328c4185a..c3746c256 100644 --- a/tests/e2e/keyboard/shortcuts.spec.ts +++ b/tests/e2e/keyboard/shortcuts.spec.ts @@ -48,6 +48,15 @@ function getZoom() { }) } +function getSelectedOpacity() { + return editor.page.evaluate(() => { + const store = window.openPencil?.getStore?.() + if (!store) throw new Error('OpenPencil store not initialized') + const id = [...store.state.selectedIds][0] + return id ? store.graph.getNode(id)?.opacity : undefined + }) +} + test.describe('tool switching', () => { test('V → SELECT', async () => { await editor.page.keyboard.press('v') @@ -222,6 +231,56 @@ test.describe('duplicate', () => { }) }) +test.describe('opacity shortcuts', () => { + test.beforeEach(async () => { + await editor.canvas.clearCanvas() + await editor.canvas.drawRect(100, 100, 60, 60) + }) + + test('combines digits and undoes them as one interaction', async () => { + await editor.page.keyboard.press('2') + await editor.page.keyboard.press('8') + expect(await getSelectedOpacity()).toBe(0.28) + + await editor.page.keyboard.press('Meta+z') + expect(await getSelectedOpacity()).toBe(1) + + await editor.page.keyboard.press('Meta+Shift+z') + expect(await getSelectedOpacity()).toBe(0.28) + }) + + test('maps 0 to 100% and 00 to 0%', async () => { + await editor.page.keyboard.press('5') + expect(await getSelectedOpacity()).toBe(0.5) + + await editor.canvas.clearCanvas() + await editor.canvas.drawRect(100, 100, 60, 60) + await editor.page.keyboard.press('0') + expect(await getSelectedOpacity()).toBe(1) + await editor.page.keyboard.press('0') + expect(await getSelectedOpacity()).toBe(0) + }) + + test('does not consume shifted digits or NumLock-off navigation keys', async () => { + await editor.page.keyboard.press('5') + await editor.page.keyboard.press('Shift+1') + expect(await getSelectedOpacity()).toBe(0.5) + + const prevented = await editor.page.evaluate(() => { + const event = new KeyboardEvent('keydown', { + key: 'End', + code: 'Numpad1', + bubbles: true, + cancelable: true + }) + window.dispatchEvent(event) + return event.defaultPrevented + }) + expect(prevented).toBe(false) + expect(await getSelectedOpacity()).toBe(0.5) + }) +}) + test.describe('zoom shortcuts', () => { test('⌘0 zooms to 100%', async () => { await editor.canvas.clearCanvas() diff --git a/tests/engine/editor/opacity.test.ts b/tests/engine/editor/opacity.test.ts index 0f3fafa71..c2cbb378d 100644 --- a/tests/engine/editor/opacity.test.ts +++ b/tests/engine/editor/opacity.test.ts @@ -61,6 +61,31 @@ describe('editor.setOpacity', () => { expect(getNodeOrThrow(editor.graph, rect.id).opacity).toBe(0.3) }) + test('coalesces buffered shortcut updates into one undo entry', () => { + const { editor, rect } = setup() + + editor.setOpacity(0.2, 'shortcut-session') + editor.setOpacity(0.28, 'shortcut-session') + + editor.undo.undo() + expect(getNodeOrThrow(editor.graph, rect.id).opacity).toBe(1) + + editor.undo.redo() + expect(getNodeOrThrow(editor.graph, rect.id).opacity).toBe(0.28) + }) + + test('keeps separate shortcut sessions as separate undo entries', () => { + const { editor, rect } = setup() + + editor.setOpacity(0.2, 'shortcut-session-1') + editor.setOpacity(0.8, 'shortcut-session-2') + + editor.undo.undo() + expect(getNodeOrThrow(editor.graph, rect.id).opacity).toBe(0.2) + editor.undo.undo() + expect(getNodeOrThrow(editor.graph, rect.id).opacity).toBe(1) + }) + test('opacity batch for multiple selections collapses to one undo entry', () => { const { editor, rect } = setup() const pageId = editor.graph.getPages()[0].id