* fix(ai): stop white section bands on dark-themed pages - role-resolver: skip fixSectionAlternation when parent fill luminance < 0.5, so we no longer paint #FFFFFF/#F8FAFC over a dark root - strip-redundant-section-fills: add SAFE_LIGHT_HEXES so stale whites from earlier runs (or weak-model hedges) are cleaned up on the sink side - regression tests for both layers * feat(ai): design.md-driven background + sidebar color pipeline - orchestrator-sidebar-color: extract sidebar surface picker; prefer design.md palette role (sidebar/panel/surface) over catalog style-guide legacy cell - orchestrator-planning: force rootFrame fill from design.md background when a user spec is provided, so sections don't inherit a bright catalog default - orchestrator-prompt-optimizer: infer design.md background + neutral theme fallback for sub-agent prompts - orchestrator-sub-agent / ai-prompts: tell sub-agents to leave section root fills unset when design.md drives the palette - design-md-style-policy: surface-colors policy block keeps MCP and web pipeline aligned - add planning + prompt-optimizer regression tests * chore: ignore .omx/ directory * Enable local OS fonts with vector rendering and proper permission handling (#110) * docs(readme): update cover screenshot * fix(renderer): enable local OS fonts with vector rendering and proper permission handling * test(renderer): refactoring names and creating vi.stubGlobal for the navigator as it's not available in the test environment. --------- Co-authored-by: Fini <fini.yang@gmail.com> Co-authored-by: Daniel Chettiar <danielc@snapwork.com> * feat(types): add AppendContext and SubTask.existingSectionLabels * feat(ai): add detectAppendIntent for continue/append prompts * feat(ai): detect append intent before generate_design dispatch * feat(ai): add applyAppendContextToPlan helper * feat(ai): reuse existing content-root in append mode * feat(ai): sub-agent APPEND MODE preamble for existing siblings * docs(ai): teach horizontal scroll card-row pattern * chore(ai): enable incremental-add skill in generation phase * fix(canvas): render synchronously on resize to prevent white flash Setting canvas.width/height clears the pixel buffer to transparent. resize() previously only marked dirty, leaving the canvas transparent until the next RAF and showing the container bg-muted through for one frame whenever the flex layout shifted (e.g. RightPanel mount on first selection after idle). Rendering inline after recreateSurface fills the new surface before the browser paints, closing that window. * style: apply oxfmt formatting drift across web and renderer files Non-semantic line-break and wrapping adjustments picked up by oxfmt. No behavior changes. * fix(mcp): run codex via shell on Windows to handle .cmd shims Since Node 18.20/20.12 (CVE-2024-27980) execFileSync refuses to spawn .cmd/.bat files directly and throws EINVAL. On Windows route through execSync with shell resolution so PATHEXT picks whichever shim exists (codex.exe / codex.cmd / codex.ps1). * feat(editor): anchor paste to selected container or sibling Pressing Cmd/Ctrl+V now inserts pasted nodes into the selected container (if it can hold children) or immediately after the selected node as a sibling, falling back to the root when nothing is selected. Previously every paste landed at document root, which broke expected behavior when working inside nested frames. * docs(ai): expand horizontal scroll card-row example in overflow skill Flesh out the inline JSON example so the generation-phase skill shows the full clipContent + nested fit_content row pattern, instead of a truncated snippet that left model output inconsistent. * style(lint): clear 7 oxlint warnings from recent commits - orchestrator-planning.test.ts: narrow fill-array type to Array<{...}> | undefined and use ?.[0] instead of unchecked [0] so optional chain does not throw on short-circuit - mcp-install.ts: drop `?? {}` fallbacks when spreading config.mcpServers; spread of undefined in an object literal is a no-op (ES2018+) * style(lint): clear remaining 15 oxlint warnings across repo Removes pre-existing warnings not related to any single feature: - no-useless-fallback-in-spread (6): drop `?? {}` when spreading possibly-undefined records (document-store-variable-actions, pen-mcp/tools/{variables,theme-presets}, variable-theme-manager) - no-useless-spread (2): replace `[...iterable]` with `Array.from` in for-of snapshots (document-events, agent-indicator), keeping the re-entry-safe copy intent explicit - no-control-regex (2): use `\P{ASCII}` unicode property escape instead of `[^\x00-\x7F]` to express "non-ASCII" without referencing U+0000 (opencode clients) - no-new-array (1): `Array.from({ length }, () => '..')` in document-assets - no-unused-vars (3): drop unused catch params (agent.ts, code-generation-pipeline) and unused globSync import (patch-srvx-bun) - no-useless-escape (1): `[[{]` instead of `[\[{]` in chat-message-content regex --------- Co-authored-by: Fini <fini.yang@gmail.com> Co-authored-by: Daniel Chettiar <74943095+1MochaChan1@users.noreply.github.com> Co-authored-by: Daniel Chettiar <danielc@snapwork.com> |
||
|---|---|---|
| .. | ||
| src | ||
| CLAUDE.md | ||
| LICENSE | ||
| package.json | ||
| README.md | ||
| tsconfig.json | ||
@zseven-w/pen-engine
Headless design engine for OpenPencil — framework-free document management, selection, history, viewport, and spatial queries. Build your own design tool UI on top of this engine.
Install
npm install @zseven-w/pen-engine
# or
bun add @zseven-w/pen-engine
Overview
pen-engine is the core runtime that powers OpenPencil's editor. It manages the entire document lifecycle without any framework dependency — React, Vue, Svelte, or vanilla JS all work. The optional browser.ts entry adds GPU-accelerated canvas rendering via CanvasKit/Skia.
DesignEngine
|- DocumentManager Node CRUD, tree operations
|- SelectionManager Multi-select, hover tracking
|- HistoryManager Undo/redo with debounce + batch
|- PageManager Multi-page support
|- VariableManager Design variables ($refs)
|- ViewportController Zoom, pan, coordinate transforms
|- SpatialIndex R-tree for hit testing & spatial queries
|- EventEmitter Typed event system
Quick Start
import { DesignEngine } from '@zseven-w/pen-engine';
const engine = new DesignEngine();
// Load or create a document
engine.loadDocument(myDocument);
// Add a node
engine.addNode(null, {
id: 'frame-1',
type: 'frame',
name: 'Header',
width: 1200,
height: 80,
layout: 'horizontal',
});
// Select, undo, inspect
engine.select(['frame-1']);
engine.undo();
console.log(engine.getDocument());
Features
Document Operations
Create, query, and mutate the node tree:
engine.addNode(parentId, node, index?);
engine.updateNode(id, { fill: [{ type: 'solid', color: '#FF0000' }] });
engine.removeNode(id);
engine.moveNode(id, newParentId, index);
engine.duplicateNode(id);
engine.groupNodes(['node-1', 'node-2']);
engine.ungroupNode(groupId);
engine.getNodeById(id);
Selection & Hover
engine.select(['node-1', 'node-2']);
engine.clearSelection();
engine.getSelection(); // string[]
engine.setHoveredId('node-3');
engine.getHoveredId(); // string | null
History (Undo / Redo)
Structural history with debouncing and batch support:
engine.undo();
engine.redo();
engine.canUndo; // boolean
engine.canRedo; // boolean
// Batch multiple mutations into a single history entry
engine.batch(() => {
engine.updateNode('a', { x: 100 });
engine.updateNode('b', { x: 200 });
});
Viewport
Pan, zoom, and coordinate conversion:
engine.setViewport(zoom, panX, panY);
engine.zoomToRect(x, y, w, h, containerW, containerH);
engine.getContentBounds(); // { x, y, w, h } | null
engine.screenToScene(screenX, screenY); // { x, y }
engine.sceneToScreen(sceneX, sceneY); // { x, y }
Hit Testing (Spatial Index)
R-tree backed queries for click and marquee selection:
engine.hitTest(x, y); // PenNode | null
engine.searchRect(x, y, w, h); // PenNode[]
Multi-Page
engine.addPage(); // returns pageId
engine.removePage(pageId);
engine.setActivePage(pageId);
engine.getActivePage();
Design Variables
engine.setVariable('primary', { type: 'color', value: '#2563EB' });
engine.removeVariable('primary');
engine.renameVariable('primary', 'brand');
engine.resolveVariable('$primary'); // '#2563EB'
SVG Import
Isomorphic SVG parser (DOM in browser, regex fallback in Node.js):
import { parseSvgToNodes } from '@zseven-w/pen-engine';
const nodes = parseSvgToNodes(svgString, 400);
engine.addNode(null, nodes[0]);
Events
Typed event system for reactive UI binding:
const unsub = engine.on('document:change', (doc) => {
/* re-render */
});
engine.on('selection:change', (ids) => {
/* update UI */
});
engine.on('viewport:change', (viewport) => {
/* update zoom indicator */
});
unsub(); // unsubscribe
Browser Canvas (Optional)
GPU-accelerated rendering via CanvasKit/Skia — import from @zseven-w/pen-engine/browser:
import { attachCanvas, attachInteraction } from '@zseven-w/pen-engine/browser';
const binding = await attachCanvas(engine, canvasElement);
const detach = attachInteraction(engine, canvasElement);
// Later
binding.dispose();
detach();
API Reference
| Method | Description |
|---|---|
loadDocument(doc) |
Load a PenDocument |
getDocument() |
Get current document |
createDocument() |
Create empty document |
addNode(parent, node, index?) |
Insert node |
updateNode(id, updates) |
Partial update |
removeNode(id) |
Delete node + children |
moveNode(id, parent, index) |
Reparent node |
duplicateNode(id) |
Deep clone |
groupNodes(ids) |
Group into frame |
ungroupNode(id) |
Dissolve group |
select(ids) |
Set selection |
undo() / redo() |
History navigation |
batch(fn) |
Batch mutations |
setViewport(z, x, y) |
Set viewport |
hitTest(x, y) |
Point query |
searchRect(x, y, w, h) |
Area query |
importSVG(svg, parent?) |
Parse and insert SVG |
dispose() |
Clean up resources |