Skip to content

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

P2P collaboration: cursors, follow mode, cleanup

Danila Poyarkovf90e1400b7c0
diff --git a/AGENTS.md b/AGENTS.md
index 55d956fc0..2b978bbe7 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -33,6 +33,49 @@ The root app (`src/`) is the Tauri/Vite desktop editor. Its `src/engine/` files
- `bun open-pencil analyze spacing <file>` — gap/padding values
- `bun open-pencil analyze clusters <file>` — repeated patterns
+## Releases & CI
+
+### How to release
+
+1. Update version in `package.json`, `packages/core/package.json`, `packages/cli/package.json`, `desktop/tauri.conf.json`
+2. Update `CHANGELOG.md` — move "Unreleased" items under new version heading with date
+3. Commit: `Release v0.x.y`
+4. Tag: `git tag v0.x.y && git push --tags`
+5. The `build.yml` workflow triggers on `v*` tags and:
+ - Builds Tauri binaries for macOS (arm64 + x64), Windows (x64 + arm64), Linux (x64)
+ - Creates a draft GitHub Release with all platform binaries
+ - Publishes `@open-pencil/core` and `@open-pencil/cli` to npm with provenance
+6. Go to GitHub Releases → edit the draft → paste changelog section → publish
+
+### CI workflows
+
+| Workflow | Trigger | What it does |
+|----------|---------|--------------|
+| `build.yml` | `v*` tag push or manual | Build Tauri desktop apps (5 targets), create GitHub Release, publish npm |
+| `app.yml` | Push to `master` (non-docs) | Build web app, deploy to Cloudflare Pages (`app.openpencil.dev`) |
+| `docs.yml` | Push to `master` (`packages/docs/**`) | Build VitePress docs, deploy to Cloudflare Pages (`openpencil.dev`) |
+
+### Before committing
+
+Run all quality gates:
+
+```sh
+bun run check # oxlint + typecheck
+bun run format # oxfmt
+bun run test:dupes # jscpd < 3%
+bun run test:unit # bun:test
+bun run test # Playwright E2E
+```
+
+## Documentation
+
+- `CHANGELOG.md` — all user-facing changes, grouped by version. "Unreleased" section at top for in-progress work.
+- `README.md` — user-facing: features, getting started, CLI, project structure. No implementation details.
+- `AGENTS.md` (this file) — contributor/agent reference: architecture, conventions, how to release.
+- `packages/docs/` — VitePress site deployed at `openpencil.dev`. User guide, reference, development docs.
+
+When adding features, update `CHANGELOG.md` (Unreleased section) and `README.md` (if user-facing). Update `AGENTS.md` when architecture or conventions change.
+
## CLI
- All CLI output must use `agentfmt` formatters — `fmtList`, `fmtHistogram`, `fmtSummary`, `fmtNode`, `fmtTree`, `kv`, `entity`, `bold`, `dim`, etc.
@@ -50,17 +93,31 @@ The root app (`src/`) is the Tauri/Vite desktop editor. Its `src/engine/` files
- To add a new tool: add a `defineTool()` in `schema.ts`, add to `ALL_TOOLS` array — it's instantly available in AI chat, and via `eval` in CLI
- `FigmaAPI` (`packages/core/src/figma-api.ts`) is the execution target for all tools — Figma Plugin API compatible, uses Symbols for hidden internals
+## Collaboration
+
+- P2P via Trystero (WebRTC) — no server relay. Signaling over MQTT public brokers.
+- Yjs CRDT for document state sync. Awareness protocol for cursors/selections/presence.
+- y-indexeddb for local persistence — room survives page refresh.
+- Constants in `src/constants.ts`: `TRYSTERO_APP_ID`, `PEER_COLORS`, `ROOM_ID_LENGTH`, `ROOM_ID_CHARS`, `YJS_JSON_FIELDS`
+- `src/composables/use-collab.ts` — composable: connect/disconnect, cursor/selection broadcasting, follow mode, Yjs ↔ SceneGraph sync
+- Provided via `COLLAB_KEY` injection — `useCollabInjected()` in child components
+- ICE servers: Google STUN + Cloudflare STUN + Open Relay TURN (TCP + UDP)
+- Room IDs use `crypto.getRandomValues()` — no `Math.random()` anywhere in codebase
+- Stale cursors cleaned on peer disconnect via `removeAwarenessStates()`
+
## Code conventions
- `@/` import alias for app cross-directory imports, relative imports within core
- No `any` — use proper types, generics, declaration merging
- No `!` non-null assertions — use guards, `?.`, `??`
+- No `Math.random()` — use `crypto.getRandomValues()` everywhere
- Shared types (GUID, Color, Vector, Matrix, Rect) live in `packages/core/src/types.ts`
- Window API extensions (showOpenFilePicker, queryLocalFonts) live in `src/global.d.ts` and `packages/core/src/global.d.ts`
- Use `culori` for color conversions — don't reimplement parseColor/colorToRgba
- Use `@vueuse/core` hooks (useEventListener, etc.) — don't do manual addEventListener/removeEventListener
- `packages/core/src/kiwi/kiwi-schema/` is vendored — don't modify
- Core code must guard browser APIs: `typeof window !== 'undefined'`, `typeof document === 'undefined'`
+- Constants in `src/constants.ts` — no magic numbers in components or composables
## Rendering
@@ -73,6 +130,7 @@ The root app (`src/`) is the Tauri/Vite desktop editor. Its `src/engine/` files
- Selection border width must be constant regardless of zoom — divide by scale
- Section/frame title text never scales — render at fixed font size, ellipsize to fit
- Rulers are rendered on the canvas (not DOM), with selection range badges that don't overlap tick numbers
+- Remote cursors: Figma-style colored arrows with white border + name pill, rendered in screen space
## Scene graph
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3572f954c..161bdc9fd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,28 @@
# Changelog
+## Unreleased
+
+### 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/<room-id>` with vue-router
+- Secure room IDs via `crypto.getRandomValues()`
+- Removed Cloudflare Durable Object relay server (`packages/collab/`)
+
+### UI
+
+- 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.
diff --git a/README.md b/README.md
index 2a8fee140..f07e367bf 100644
--- a/README.md
+++ b/README.md
@@ -30,6 +30,7 @@ Your design files are yours. Your tools should be too.
- **Figma .fig file import** — open native Figma files directly
- **Figma clipboard** — copy/paste between OpenPencil and Figma
+- **Real-time collaboration** — P2P via WebRTC, no server required. Share a link, co-edit live with cursors and presence
- **Vector networks** — complex boolean shapes and open paths, like Figma
- **Auto-layout** — constraint-based layout matching Figma behavior
- **Components & instances** — with live sync, overrides, component sets
@@ -52,6 +53,7 @@ Your design files are yours. Your tools should be too.
| Layout | Yoga WASM |
| File format | Kiwi binary (vendored) + Zstd + ZIP |
| Color | culori |
+| Collaboration | Trystero (WebRTC P2P) + Yjs (CRDT) + y-indexeddb |
| Desktop | Tauri v2 |
| CLI | citty, agentfmt |
| Testing | Playwright (visual regression), bun:test (unit) |
@@ -64,6 +66,17 @@ bun install
bun run dev
```
+## Collaboration
+
+Share a link to co-edit in real time. No server, no account — peers connect directly via WebRTC.
+
+1. Click the share button in the top-right panel
+2. Share the generated link (`app.openpencil.dev/share/<room-id>`)
+3. Collaborators see your cursor, selection, and edits in real time
+4. Click a peer's avatar to follow their viewport
+
+All sync happens peer-to-peer via [Trystero](https://github.com/dmotz/trystero). Document state is persisted locally in IndexedDB — refreshing the page keeps your work.
+
## CLI
Headless .fig file operations — no GUI needed:
@@ -140,7 +153,7 @@ packages/
cli/ @open-pencil/cli — headless CLI (info, tree, find, export)
src/
components/ Vue SFCs (canvas, panels, toolbar, color picker)
- composables/ Canvas input, keyboard shortcuts, rendering
+ composables/ Canvas input, keyboard shortcuts, collaboration, rendering
stores/ Editor state (Vue reactivity)
engine/ Re-export shims from @open-pencil/core
kiwi/ Re-export shims from @open-pencil/core
diff --git a/packages/core/src/canvaskit.ts b/packages/core/src/canvaskit.ts
index 56833af08..84dee5447 100644
--- a/packages/core/src/canvaskit.ts
+++ b/packages/core/src/canvaskit.ts
@@ -9,10 +9,12 @@ export interface CanvasKitOptions {
export async function getCanvasKit(options?: CanvasKitOptions): Promise<CanvasKit> {
if (instance) return instance
instance = await CanvasKitInit({
- locateFile: options?.locateFile ?? ((file) => {
- if (typeof window !== 'undefined') return `/${file}`
- return file
- })
+ locateFile:
+ options?.locateFile ??
+ ((file) => {
+ if (typeof window !== 'undefined') return `/${file}`
+ return file
+ })
})
return instance
}
diff --git a/packages/core/src/clipboard.ts b/packages/core/src/clipboard.ts
index c8eff1f3c..2b8025239 100644
--- a/packages/core/src/clipboard.ts
+++ b/packages/core/src/clipboard.ts
@@ -1,16 +1,16 @@
import { inflateSync, deflateSync } from 'fflate'
-import { initCodec, getCompiledSchema, getSchemaBytes } from './kiwi/codec'
-import { decodeBinarySchema, compileSchema, ByteBuffer } from './kiwi/kiwi-schema'
import {
sceneNodeToKiwi,
buildFigKiwi,
parseFigKiwiChunks,
decompressFigKiwiDataAsync
} from './kiwi-serialize'
-
+import { initCodec, getCompiledSchema, getSchemaBytes } from './kiwi/codec'
+import { decodeBinarySchema, compileSchema, ByteBuffer } from './kiwi/kiwi-schema'
import { decodeVectorNetworkBlob } from './vector'
+import type { NodeChange as KiwiNodeChange } from './kiwi/codec'
import type {
SceneGraph,
SceneNode,
@@ -22,7 +22,6 @@ import type {
LayoutCounterAlign,
VectorNetwork
} from './scene-graph'
-import type { NodeChange as KiwiNodeChange } from './kiwi/codec'
interface FigmaClipboardMeta {
fileKey: string
@@ -34,8 +33,6 @@ export async function prefetchFigmaSchema(): Promise<void> {
await initCodec()
}
-
-
function binaryToBase64(bytes: Uint8Array): string {
let binary = ''
for (let i = 0; i < bytes.length; i++) {
@@ -349,7 +346,7 @@ export function buildFigmaClipboardHTML(nodes: SceneNode[], graph: SceneGraph):
type: 'NODE_CHANGES',
sessionID: 0,
ackID: 0,
- pasteID: Math.floor(Math.random() * 2147483647),
+ pasteID: crypto.getRandomValues(new Uint32Array(1))[0],
pasteFileKey: 'openpencil',
nodeChanges
}
diff --git a/packages/core/src/constants.ts b/packages/core/src/constants.ts
index 496be3a42..ec8257fcb 100644
--- a/packages/core/src/constants.ts
+++ b/packages/core/src/constants.ts
@@ -83,12 +83,27 @@ export interface ModelOption {
export const AI_MODELS: ModelOption[] = [
// Best for design: vision + frontend + tool calling (WebDev Arena #1, DesignBench, SWE-bench 79.6%)
- { id: 'anthropic/claude-sonnet-4.6', name: 'Claude Sonnet 4.6', provider: 'Anthropic', tag: 'Best for design' },
- { id: 'anthropic/claude-opus-4.6', name: 'Claude Opus 4.6', provider: 'Anthropic', tag: 'Smartest' },
+ {
+ id: 'anthropic/claude-sonnet-4.6',
+ name: 'Claude Sonnet 4.6',
+ provider: 'Anthropic',
+ tag: 'Best for design'
+ },
+ {
+ id: 'anthropic/claude-opus-4.6',
+ name: 'Claude Opus 4.6',
+ provider: 'Anthropic',
+ tag: 'Smartest'
+ },
// 76.8% SWE-bench, vision + UI-to-code specialist
{ id: 'moonshotai/kimi-k2.5', name: 'Kimi K2.5', provider: 'Moonshot', tag: 'Vision + code' },
// 1M context, multimodal (text+image+audio+video), 78% SWE-bench
- { id: 'google/gemini-3.1-pro-preview', name: 'Gemini 3.1 Pro', provider: 'Google', tag: '1M context' },
+ {
+ id: 'google/gemini-3.1-pro-preview',
+ name: 'Gemini 3.1 Pro',
+ provider: 'Google',
+ tag: '1M context'
+ },
// 80% SWE-bench, 400K context, agentic coding
{ id: 'openai/gpt-5.3-codex', name: 'GPT-5.3 Codex', provider: 'OpenAI' },
@@ -99,7 +114,7 @@ export const AI_MODELS: ModelOption[] = [
// Free (with tool calling)
{ id: 'qwen/qwen3-coder:free', name: 'Qwen3 Coder', provider: 'Qwen', tag: 'Free' },
- { id: 'openai/gpt-oss-120b:free', name: 'GPT-OSS 120B', provider: 'OpenAI', tag: 'Free' },
+ { id: 'openai/gpt-oss-120b:free', name: 'GPT-OSS 120B', provider: 'OpenAI', tag: 'Free' }
]
export const DEFAULT_AI_MODEL = AI_MODELS[0].id
diff --git a/packages/core/src/fig-export.ts b/packages/core/src/fig-export.ts
index 4adf55da7..83bfd8cc8 100644
--- a/packages/core/src/fig-export.ts
+++ b/packages/core/src/fig-export.ts
@@ -1,13 +1,13 @@
import { zipSync, deflateSync } from 'fflate'
import { IS_TAURI } from './constants'
-import { initCodec, getCompiledSchema, getSchemaBytes } from './kiwi/codec'
import { sceneNodeToKiwi, fractionalPosition, buildFigKiwi } from './kiwi-serialize'
+import { initCodec, getCompiledSchema, getSchemaBytes } from './kiwi/codec'
import { renderThumbnail } from './render-image'
+import type { NodeChange } from './kiwi/codec'
import type { SkiaRenderer } from './renderer'
import type { SceneGraph } from './scene-graph'
-import type { NodeChange } from './kiwi/codec'
import type { CanvasKit } from 'canvaskit-wasm'
const THUMBNAIL_1X1 = Uint8Array.from(
@@ -126,5 +126,3 @@ export async function exportFigFile(
'meta.json': new TextEncoder().encode(metaJson)
})
}
-
-
diff --git a/packages/core/src/figma-api.ts b/packages/core/src/figma-api.ts
index d6570cb13..51edf3720 100644
--- a/packages/core/src/figma-api.ts
+++ b/packages/core/src/figma-api.ts
@@ -1,4 +1,5 @@
-import type { Rect } from './types'
+import { SceneGraph } from './scene-graph'
+
import type {
SceneNode,
NodeType,
@@ -7,9 +8,9 @@ import type {
Effect,
LayoutMode,
Variable,
- VariableCollection,
+ VariableCollection
} from './scene-graph'
-import { SceneGraph } from './scene-graph'
+import type { Rect } from './types'
const MIXED = Symbol('mixed')
@@ -25,7 +26,7 @@ function weightToStyleName(weight: number, italic: boolean): string {
600: 'Semi Bold',
700: 'Bold',
800: 'Extra Bold',
- 900: 'Black',
+ 900: 'Black'
}
const base = names[weight] ?? 'Regular'
return italic ? `${base} Italic` : base
@@ -49,7 +50,7 @@ function styleNameToWeight(style: string): { weight: number; italic: boolean } {
'extra bold': 800,
'ultra bold': 800,
black: 900,
- heavy: 900,
+ heavy: 900
}
return { weight: map[clean] ?? 400, italic }
}
@@ -141,7 +142,7 @@ class FigmaNodeProxy {
const pos = this[INTERNAL_GRAPH].getAbsolutePosition(this[INTERNAL_ID])
return [
[1, 0, pos.x],
- [0, 1, pos.y],
+ [0, 1, pos.y]
]
}
@@ -235,7 +236,7 @@ class FigmaNodeProxy {
topRightRadius: v as number,
bottomRightRadius: v as number,
bottomLeftRadius: v as number,
- independentCorners: false,
+ independentCorners: false
})
}
@@ -244,7 +245,10 @@ class FigmaNodeProxy {
}
set topLeftRadius(v: number) {
- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { topLeftRadius: v, independentCorners: true })
+ this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {
+ topLeftRadius: v,
+ independentCorners: true
+ })
}
get topRightRadius(): number {
@@ -252,7 +256,10 @@ class FigmaNodeProxy {
}
set topRightRadius(v: number) {
- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { topRightRadius: v, independentCorners: true })
+ this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {
+ topRightRadius: v,
+ independentCorners: true
+ })
}
get bottomLeftRadius(): number {
@@ -260,7 +267,10 @@ class FigmaNodeProxy {
}
set bottomLeftRadius(v: number) {
- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { bottomLeftRadius: v, independentCorners: true })
+ this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {
+ bottomLeftRadius: v,
+ independentCorners: true
+ })
}
get bottomRightRadius(): number {
@@ -268,7 +278,10 @@ class FigmaNodeProxy {
}
set bottomRightRadius(v: number) {
- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { bottomRightRadius: v, independentCorners: true })
+ this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {
+ bottomRightRadius: v,
+ independentCorners: true
+ })
}
get cornerSmoothing(): number {
@@ -346,7 +359,10 @@ class FigmaNodeProxy {
}
set strokeTopWeight(v: number) {
- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { borderTopWeight: v, independentStrokeWeights: true })
+ this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {
+ borderTopWeight: v,
+ independentStrokeWeights: true
+ })
}
get strokeBottomWeight(): number {
@@ -354,7 +370,10 @@ class FigmaNodeProxy {
}
set strokeBottomWeight(v: number) {
- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { borderBottomWeight: v, independentStrokeWeights: true })
+ this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {
+ borderBottomWeight: v,
+ independentStrokeWeights: true
+ })
}
get strokeLeftWeight(): number {
@@ -362,7 +381,10 @@ class FigmaNodeProxy {
}
set strokeLeftWeight(v: number) {
- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { borderLeftWeight: v, independentStrokeWeights: true })
+ this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {
+ borderLeftWeight: v,
+ independentStrokeWeights: true
+ })
}
get strokeRightWeight(): number {
@@ -370,7 +392,10 @@ class FigmaNodeProxy {
}
set strokeRightWeight(v: number) {
- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { borderRightWeight: v, independentStrokeWeights: true })
+ this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {
+ borderRightWeight: v,
+ independentStrokeWeights: true
+ })
}
// --- Text ---
@@ -398,7 +423,11 @@ class FigmaNodeProxy {
set fontName(v: FigmaFontName) {
const { weight, italic } = styleNameToWeight(v.style)
- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { fontFamily: v.family, fontWeight: weight, italic })
+ this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {
+ fontFamily: v.family,
+ fontWeight: weight,
+ italic
+ })
}
get fontWeight(): number {
@@ -414,7 +443,9 @@ class FigmaNodeProxy {
}
set textAlignHorizontal(v: string) {
- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { textAlignHorizontal: v as SceneNode['textAlignHorizontal'] })
+ this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {
+ textAlignHorizontal: v as SceneNode['textAlignHorizontal']
+ })
}
get textAlignVertical(): string {
@@ -422,7 +453,9 @@ class FigmaNodeProxy {
}
set textAlignVertical(v: string) {
- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { textAlignVertical: v as SceneNode['textAlignVertical'] })
+ this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {
+ textAlignVertical: v as SceneNode['textAlignVertical']
+ })
}
get textAutoResize(): string {
@@ -430,7 +463,9 @@ class FigmaNodeProxy {
}
set textAutoResize(v: string) {
- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { textAutoResize: v as SceneNode['textAutoResize'] })
+ this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {
+ textAutoResize: v as SceneNode['textAutoResize']
+ })
}
get letterSpacing(): number {
@@ -462,7 +497,9 @@ class FigmaNodeProxy {
}
set textDecoration(v: string) {
- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { textDecoration: v as SceneNode['textDecoration'] })
+ this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {
+ textDecoration: v as SceneNode['textDecoration']
+ })
}
get maxLines(): number | null {
@@ -478,7 +515,9 @@ class FigmaNodeProxy {
}
set textTruncation(v: string) {
- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { textTruncation: v as SceneNode['textTruncation'] })
+ this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {
+ textTruncation: v as SceneNode['textTruncation']
+ })
}
get autoRename(): boolean {
@@ -516,7 +555,9 @@ class FigmaNodeProxy {
}
set primaryAxisAlignItems(v: string) {
- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { primaryAxisAlign: v as SceneNode['primaryAxisAlign'] })
+ this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {
+ primaryAxisAlign: v as SceneNode['primaryAxisAlign']
+ })
}
get counterAxisAlignItems(): string {
@@ -524,7 +565,9 @@ class FigmaNodeProxy {
}
set counterAxisAlignItems(v: string) {
- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { counterAxisAlign: v as SceneNode['counterAxisAlign'] })
+ this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {
+ counterAxisAlign: v as SceneNode['counterAxisAlign']
+ })
}
get itemSpacing(): number {
@@ -589,7 +632,9 @@ class FigmaNodeProxy {
set primaryAxisSizingMode(v: string) {
const mapped = v === 'AUTO' ? 'HUG' : v
- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { primaryAxisSizing: mapped as SceneNode['primaryAxisSizing'] })
+ this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {
+ primaryAxisSizing: mapped as SceneNode['primaryAxisSizing']
+ })
}
get counterAxisSizingMode(): string {
@@ -598,7 +643,9 @@ class FigmaNodeProxy {
set counterAxisSizingMode(v: string) {
const mapped = v === 'AUTO' ? 'HUG' : v
- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { counterAxisSizing: mapped as SceneNode['counterAxisSizing'] })
+ this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {
+ counterAxisSizing: mapped as SceneNode['counterAxisSizing']
+ })
}
get counterAxisAlignContent(): string {
@@ -606,7 +653,9 @@ class FigmaNodeProxy {
}
set counterAxisAlignContent(v: string) {
- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { counterAxisAlignContent: v as SceneNode['counterAxisAlignContent'] })
+ this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {
+ counterAxisAlignContent: v as SceneNode['counterAxisAlignContent']
+ })
}
get itemReverseZIndex(): boolean {
@@ -632,7 +681,9 @@ class FigmaNodeProxy {
}
set layoutPositioning(v: string) {
- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { layoutPositioning: v as SceneNode['layoutPositioning'] })
+ this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {
+ layoutPositioning: v as SceneNode['layoutPositioning']
+ })
}
get layoutGrow(): number {
@@ -650,13 +701,15 @@ class FigmaNodeProxy {
set layoutAlign(v: string) {
const mapped = v === 'STRETCH' ? 'STRETCH' : 'AUTO'
- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { layoutAlignSelf: mapped as SceneNode['layoutAlignSelf'] })
+ this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {
+ layoutAlignSelf: mapped as SceneNode['layoutAlignSelf']
+ })
}
get layoutSizingHorizontal(): string {
const n = this._raw()
const parent = n.parentId ? this[INTERNAL_GRAPH].getNode(n.parentId) : undefined
- const refLayout = (parent && parent.layoutMode !== 'NONE') ? parent.layoutMode : n.layoutMode
+ const refLayout = parent && parent.layoutMode !== 'NONE' ? parent.layoutMode : n.layoutMode
if (refLayout === 'NONE') return 'FIXED'
return refLayout === 'HORIZONTAL' ? n.primaryAxisSizing : n.counterAxisSizing
}
@@ -664,18 +717,22 @@ class FigmaNodeProxy {
set layoutSizingHorizontal(v: string) {
const n = this._raw()
const parent = n.parentId ? this[INTERNAL_GRAPH].getNode(n.parentId) : undefined
- const refLayout = (parent && parent.layoutMode !== 'NONE') ? parent.layoutMode : n.layoutMode
+ const refLayout = parent && parent.layoutMode !== 'NONE' ? parent.layoutMode : n.layoutMode
if (refLayout === 'VERTICAL') {
- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { counterAxisSizing: v as SceneNode['counterAxisSizing'] })
+ this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {
+ counterAxisSizing: v as SceneNode['counterAxisSizing']
+ })
} else {
- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { primaryAxisSizing: v as SceneNode['primaryAxisSizing'] })
+ this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {
+ primaryAxisSizing: v as SceneNode['primaryAxisSizing']
+ })
}
}
get layoutSizingVertical(): string {
const n = this._raw()
const parent = n.parentId ? this[INTERNAL_GRAPH].getNode(n.parentId) : undefined
- const refLayout = (parent && parent.layoutMode !== 'NONE') ? parent.layoutMode : n.layoutMode
+ const refLayout = parent && parent.layoutMode !== 'NONE' ? parent.layoutMode : n.layoutMode
if (refLayout === 'NONE') return 'FIXED'
return refLayout === 'VERTICAL' ? n.primaryAxisSizing : n.counterAxisSizing
}
@@ -683,11 +740,15 @@ class FigmaNodeProxy {
set layoutSizingVertical(v: string) {
const n = this._raw()
const parent = n.parentId ? this[INTERNAL_GRAPH].getNode(n.parentId) : undefined
- const refLayout = (parent && parent.layoutMode !== 'NONE') ? parent.layoutMode : n.layoutMode
+ const refLayout = parent && parent.layoutMode !== 'NONE' ? parent.layoutMode : n.layoutMode
if (refLayout === 'HORIZONTAL') {
- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { counterAxisSizing: v as SceneNode['counterAxisSizing'] })
+ this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {
+ counterAxisSizing: v as SceneNode['counterAxisSizing']
+ })
} else {
- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { primaryAxisSizing: v as SceneNode['primaryAxisSizing'] })
+ this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {
+ primaryAxisSizing: v as SceneNode['primaryAxisSizing']
+ })
}
}
@@ -701,7 +762,7 @@ class FigmaNodeProxy {
set constraints(v: { horizontal: string; vertical: string }) {
this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {
horizontalConstraint: v.horizontal as SceneNode['horizontalConstraint'],
- verticalConstraint: v.vertical as SceneNode['verticalConstraint'],
+ verticalConstraint: v.vertical as SceneNode['verticalConstraint']
})
}
@@ -878,7 +939,7 @@ class FigmaNodeProxy {
x: n.x,
y: n.y,
width: n.width,
- height: n.height,
+ height: n.height
}
if (n.fills.length > 0) obj.fills = n.fills
if (n.strokes.length > 0) obj.strokes = n.strokes
@@ -936,7 +997,9 @@ export class FigmaAPI {
return proxy
}
- private _ensurePageProxy(proxy: FigmaNodeProxy): FigmaNodeProxy & { selection: FigmaNodeProxy[] } {
+ private _ensurePageProxy(
+ proxy: FigmaNodeProxy
+ ): FigmaNodeProxy & { selection: FigmaNodeProxy[] } {
if (!this._pageProxies.has(proxy)) {
const self = this
Object.defineProperty(proxy, 'selection', {
@@ -947,7 +1010,7 @@ export class FigmaAPI {
self._selection = nodes
},
enumerable: true,
- configurable: true,
+ configurable: true
})
this._pageProxies.add(proxy)
}
@@ -1071,7 +1134,7 @@ export class FigmaAPI {
paddingTop: raw.paddingTop,
paddingRight: raw.paddingRight,
paddingBottom: raw.paddingBottom,
- paddingLeft: raw.paddingLeft,
+ paddingLeft: raw.paddingLeft
})
for (const childId of raw.childIds) {
this.graph.cloneTree(childId, comp.id)
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 0db758d8c..012e7fda9 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -1,10 +1,4 @@
-export type {
- GUID,
- Color,
- Vector,
- Matrix,
- Rect
-} from './types'
+export type { GUID, Color, Vector, Matrix, Rect } from './types'
export * from './constants'
@@ -65,7 +59,12 @@ export {
weightToStyle
} from './fonts'
export { parseColor, colorToHex, colorToHexRaw, colorToRgba255 } from './color'
-export { vectorNetworkToPath, decodeVectorNetworkBlob, encodeVectorNetworkBlob, computeVectorBounds } from './vector'
+export {
+ vectorNetworkToPath,
+ decodeVectorNetworkBlob,
+ encodeVectorNetworkBlob,
+ computeVectorBounds
+} from './vector'
export { computeSelectionBounds, computeSnap, type SnapGuide } from './snap'
export { UndoManager } from './undo'
export { TextEditor, type TextCaret, type TextEditorState } from './text-editor'
diff --git a/packages/core/src/kiwi-serialize.ts b/packages/core/src/kiwi-serialize.ts
index 6aaf9d224..429a93d48 100644
--- a/packages/core/src/kiwi-serialize.ts
+++ b/packages/core/src/kiwi-serialize.ts
@@ -2,11 +2,11 @@ export const FIG_KIWI_VERSION = 106
import { deflateSync, inflateSync } from 'fflate'
-import { encodeVectorNetworkBlob } from './vector'
import { weightToStyle } from './fonts'
+import { encodeVectorNetworkBlob } from './vector'
-import type { SceneGraph, SceneNode, CharacterStyleOverride } from './scene-graph'
import type { NodeChange, Paint } from './kiwi/codec'
+import type { SceneGraph, SceneNode, CharacterStyleOverride } from './scene-graph'
type KiwiNodeChange = NodeChange & Record<string, unknown>
@@ -110,8 +110,6 @@ export function fractionalPosition(index: number): string {
return String.fromCharCode('!'.charCodeAt(0) + index)
}
-
-
function exportTextData(node: SceneNode): NodeChange['textData'] {
const runs = node.styleRuns
if (runs.length === 0) {
diff --git a/packages/core/src/kiwi/codec.ts b/packages/core/src/kiwi/codec.ts
index 7425790e1..63b2188b9 100644
--- a/packages/core/src/kiwi/codec.ts
+++ b/packages/core/src/kiwi/codec.ts
@@ -9,7 +9,6 @@
import { decompress as zstdDecompress } from 'fzstd'
import { parseColor } from '../color'
-
import { compileSchema, encodeBinarySchema } from './kiwi-schema'
import { isZstdCompressed, getKiwiMessageType } from './protocol'
import figmaSchema from './schema'
diff --git a/packages/core/src/kiwi/fig-file.ts b/packages/core/src/kiwi/fig-file.ts
index 643dfa115..811d91ea5 100644
--- a/packages/core/src/kiwi/fig-file.ts
+++ b/packages/core/src/kiwi/fig-file.ts
@@ -5,8 +5,8 @@ import { importNodeChanges } from './fig-import'
import { decodeBinarySchema, compileSchema, ByteBuffer } from './kiwi-schema'
import { isZstdCompressed } from './protocol'
-import type { FigmaMessage } from './codec'
import type { SceneGraph } from '../scene-graph'
+import type { FigmaMessage } from './codec'
interface FigKiwiPayload {
schemaDeflated: Uint8Array
diff --git a/packages/core/src/kiwi/fig-import.ts b/packages/core/src/kiwi/fig-import.ts
index 35036636d..c2f956e0f 100644
--- a/packages/core/src/kiwi/fig-import.ts
+++ b/packages/core/src/kiwi/fig-import.ts
@@ -1,9 +1,8 @@
import { DEFAULT_STROKE_MITER_LIMIT } from '../constants'
-import { SceneGraph } from '../scene-graph'
import { styleToWeight } from '../fonts'
+import { SceneGraph } from '../scene-graph'
import { decodeVectorNetworkBlob } from '../vector'
-import type { NodeChange, Paint, Effect as KiwiEffect, GUID } from './codec'
import type {
NodeType,
Fill,
@@ -30,6 +29,7 @@ import type {
StyleRun,
CharacterStyleOverride
} from '../scene-graph'
+import type { NodeChange, Paint, Effect as KiwiEffect, GUID } from './codec'
function ext(nc: NodeChange): Record<string, unknown> {
return nc as unknown as Record<string, unknown>
@@ -240,8 +240,6 @@ function mapStackCounterAlign(align?: string): LayoutCounterAlign {
}
}
-
-
function mapConstraint(c?: string): ConstraintType {
switch (c) {
case 'CENTER':
@@ -292,7 +290,7 @@ function importStyleRuns(nc: NodeChange): StyleRun[] {
const style: CharacterStyleOverride = {}
if (override.fontName) {
style.fontFamily = override.fontName.family
- style.fontWeight = styleToWeight(override.fontName.style ?? "")
+ style.fontWeight = styleToWeight(override.fontName.style ?? '')
style.italic = override.fontName.style?.toLowerCase().includes('italic') ?? false
}
if (override.fontSize !== undefined) style.fontSize = override.fontSize
@@ -451,7 +449,7 @@ export function importNodeChanges(
text: nc.textData?.characters ?? '',
fontSize: nc.fontSize ?? 14,
fontFamily: nc.fontName?.family ?? 'Inter',
- fontWeight: styleToWeight(nc.fontName?.style ?? ""),
+ fontWeight: styleToWeight(nc.fontName?.style ?? ''),
italic: nc.fontName?.style?.toLowerCase().includes('italic') ?? false,
textAlignHorizontal:
(nc.textAlignHorizontal as 'LEFT' | 'CENTER' | 'RIGHT' | 'JUSTIFIED') ?? 'LEFT',
@@ -497,7 +495,8 @@ export function importNodeChanges(
maxHeight: (ext(nc).maxHeight as number) ?? null,
isMask: (ext(nc).isMask as boolean) ?? false,
maskType: ((ext(nc).maskType as string) ?? 'ALPHA') as 'ALPHA' | 'VECTOR' | 'LUMINANCE',
- counterAxisAlignContent: (ext(nc).stackCounterAlignContent as string) === 'SPACE_BETWEEN' ? 'SPACE_BETWEEN' : 'AUTO',
+ counterAxisAlignContent:
+ (ext(nc).stackCounterAlignContent as string) === 'SPACE_BETWEEN' ? 'SPACE_BETWEEN' : 'AUTO',
itemReverseZIndex: (ext(nc).stackReverseZIndex as boolean) ?? false,
strokesIncludedInLayout: (ext(nc).strokesIncludedInLayout as boolean) ?? false,
expanded: true,
@@ -529,7 +528,14 @@ export function importNodeChanges(
function importVariables() {
for (const [id, nc] of changeMap) {
if (nc.type !== 'VARIABLE') continue
- const varData = (ext(nc) as { variableData?: { value?: { boolValue?: boolean; textValue?: string; floatValue?: number }; dataType?: string } }).variableData
+ const varData = (
+ ext(nc) as {
+ variableData?: {
+ value?: { boolValue?: boolean; textValue?: string; floatValue?: number }
+ dataType?: string
+ }
+ }
+ ).variableData
if (!varData) continue
const parentId = parentMap.get(id) ?? ''
diff --git a/packages/core/src/kiwi/kiwi-schema/bb.ts b/packages/core/src/kiwi/kiwi-schema/bb.ts
index b6facbe20..6992b7a7e 100644
--- a/packages/core/src/kiwi/kiwi-schema/bb.ts
+++ b/packages/core/src/kiwi/kiwi-schema/bb.ts
@@ -52,14 +52,30 @@ export class ByteBuffer {
let i = this._index
let b = data[i++]
let value = b & 127
- if (b < 128) { this._index = i; return value }
- b = data[i++]; value |= (b & 127) << 7
- if (b < 128) { this._index = i; return value }
- b = data[i++]; value |= (b & 127) << 14
- if (b < 128) { this._index = i; return value }
- b = data[i++]; value |= (b & 127) << 21
- if (b < 128) { this._index = i; return value }
- b = data[i++]; value |= (b & 127) << 28
+ if (b < 128) {
+ this._index = i
+ return value
+ }
+ b = data[i++]
+ value |= (b & 127) << 7
+ if (b < 128) {
+ this._index = i
+ return value
+ }
+ b = data[i++]
+ value |= (b & 127) << 14
+ if (b < 128) {
+ this._index = i
+ return value
+ }
+ b = data[i++]
+ value |= (b & 127) << 21
+ if (b < 128) {
+ this._index = i
+ return value
+ }
+ b = data[i++]
+ value |= (b & 127) << 28
this._index = i
return value >>> 0
}
diff --git a/packages/core/src/render-image.ts b/packages/core/src/render-image.ts
index ca2cac8ec..77f68f03b 100644
--- a/packages/core/src/render-image.ts
+++ b/packages/core/src/render-image.ts
@@ -92,11 +92,21 @@ export function renderNodesToImage(
if (pixelW <= 0 || pixelH <= 0) return null
const quality = options.quality ?? (options.format === 'PNG' ? 100 : 90)
- return renderToSurface(ck, renderer, graph, pageId, pixelW, pixelH, options.format, quality, (canvas) => {
- canvas.clear(ck.TRANSPARENT)
- canvas.scale(options.scale, options.scale)
- canvas.translate(-bounds.minX, -bounds.minY)
- })
+ return renderToSurface(
+ ck,
+ renderer,
+ graph,
+ pageId,
+ pixelW,
+ pixelH,
+ options.format,
+ quality,
+ (canvas) => {
+ canvas.clear(ck.TRANSPARENT)
+ canvas.scale(options.scale, options.scale)
+ canvas.translate(-bounds.minX, -bounds.minY)
+ }
+ )
}
export function renderThumbnail(
diff --git a/packages/core/src/render/export-jsx.ts b/packages/core/src/render/export-jsx.ts
index d50bb0949..a80d4a3a0 100644
--- a/packages/core/src/render/export-jsx.ts
+++ b/packages/core/src/render/export-jsx.ts
@@ -21,7 +21,13 @@ const NODE_TYPE_TO_TAG: Partial<Record<NodeType, string>> = {
function formatColor(color: Color, opacity = 1): string {
const hex = colorToHex(color)
- if (opacity < 1) return hex + Math.round(opacity * 255).toString(16).padStart(2, '0')
+ if (opacity < 1)
+ return (
+ hex +
+ Math.round(opacity * 255)
+ .toString(16)
+ .padStart(2, '0')
+ )
return hex
}
@@ -144,7 +150,12 @@ function collectProps(node: SceneNode, graph: SceneGraph): [string, unknown][] {
if (node.cornerRadius > 0) {
if (node.independentCorners) {
- const { topLeftRadius: tl, topRightRadius: tr, bottomRightRadius: br, bottomLeftRadius: bl } = node
+ const {
+ topLeftRadius: tl,
+ topRightRadius: tr,
+ bottomRightRadius: br,
+ bottomLeftRadius: bl
+ } = node
if (tl === tr && tr === br && br === bl) {
props.push(['rounded', tl])
} else {
@@ -206,11 +217,7 @@ function collectProps(node: SceneNode, graph: SceneGraph): [string, unknown][] {
return props
}
-function nodeToJsx(
- node: SceneNode,
- graph: SceneGraph,
- indent: number
-): string {
+function nodeToJsx(node: SceneNode, graph: SceneGraph, indent: number): string {
const tag = NODE_TYPE_TO_TAG[node.type]
if (!tag) return ''
@@ -226,7 +233,15 @@ function nodeToJsx(
const text = node.text
if (!text) return `${prefix}${opening} />`
const escaped = text.replace(/[{}<>&]/g, (c) =>
- c === '{' ? '&#123;' : c === '}' ? '&#125;' : c === '<' ? '&lt;' : c === '>' ? '&gt;' : '&amp;'
+ c === '{'
+ ? '&#123;'
+ : c === '}'
+ ? '&#125;'
+ : c === '<'
+ ? '&lt;'
+ : c === '>'
+ ? '&gt;'
+ : '&amp;'
)
if (!escaped.includes('\n')) {
return `${prefix}${opening}>${escaped}</${tag}>`
@@ -253,26 +268,16 @@ function nodeToJsx(
return `${prefix}${opening} />`
}
- return [
- `${prefix}${opening}>`,
- ...childJsx,
- `${prefix}</${tag}>`
- ].join('\n')
+ return [`${prefix}${opening}>`, ...childJsx, `${prefix}</${tag}>`].join('\n')
}
-export function sceneNodeToJsx(
- nodeId: string,
- graph: SceneGraph
-): string {
+export function sceneNodeToJsx(nodeId: string, graph: SceneGraph): string {
const node = graph.getNode(nodeId)
if (!node) return ''
return nodeToJsx(node, graph, 0)
}
-export function selectionToJsx(
- nodeIds: string[],
- graph: SceneGraph
-): string {
+export function selectionToJsx(nodeIds: string[], graph: SceneGraph): string {
return nodeIds
.map((id) => sceneNodeToJsx(id, graph))
.filter(Boolean)
diff --git a/packages/core/src/render/index.ts b/packages/core/src/render/index.ts
index 40537c409..2bd23f0fe 100644
--- a/packages/core/src/render/index.ts
+++ b/packages/core/src/render/index.ts
@@ -17,7 +17,15 @@ export {
INTRINSIC_ELEMENTS
} from './components'
-export { type TreeNode, type BaseProps, type TextProps, type StyleProps, isTreeNode, node, resolveToTree } from './tree'
+export {
+ type TreeNode,
+ type BaseProps,
+ type TextProps,
+ type StyleProps,
+ isTreeNode,
+ node,
+ resolveToTree
+} from './tree'
export { renderTree, type RenderResult } from './renderer'
diff --git a/packages/core/src/render/render-jsx.ts b/packages/core/src/render/render-jsx.ts
index a00e94a12..8137620cc 100644
--- a/packages/core/src/render/render-jsx.ts
+++ b/packages/core/src/render/render-jsx.ts
@@ -1,6 +1,6 @@
import * as React from './mini-react'
-import { resolveToTree, type TreeNode } from './tree'
import { renderTree, type RenderResult } from './renderer'
+import { resolveToTree, type TreeNode } from './tree'
import type { SceneGraph } from '../scene-graph'
@@ -14,7 +14,9 @@ export async function buildComponent(jsxString: string): Promise<() => unknown>
try {
esbuild = await import('esbuild')
} catch {
- throw new Error('esbuild is required for JSX string rendering. Install it or use renderTreeNode() instead.')
+ throw new Error(
+ 'esbuild is required for JSX string rendering. Install it or use renderTreeNode() instead.'
+ )
}
const code = `
diff --git a/packages/core/src/render/renderer.ts b/packages/core/src/render/renderer.ts
index 7030758f1..d775ff6ee 100644
--- a/packages/core/src/render/renderer.ts
+++ b/packages/core/src/render/renderer.ts
@@ -1,8 +1,8 @@
import { parseColor, colorToFill } from '../color'
+import { isTreeNode } from './tree'
import type { SceneGraph, SceneNode, NodeType, LayoutMode, Stroke } from '../scene-graph'
import type { TreeNode } from './tree'
-import { isTreeNode } from './tree'
const TYPE_MAP: Record<string, NodeType> = {
frame: 'FRAME',
@@ -105,9 +105,7 @@ function renderNode(graph: SceneGraph, tree: TreeNode, parentId: string): SceneN
const overrides = propsToOverrides(tree.props, isText)
if (isText) {
- const textContent = tree.children
- .filter((c): c is string => typeof c === 'string')
- .join('')
+ const textContent = tree.children.filter((c): c is string => typeof c === 'string').join('')
if (textContent) overrides.text = textContent
}
@@ -158,8 +156,12 @@ function propsToOverrides(props: Record<string, unknown>, isText: boolean): Part
if (typeof rounded === 'number') {
o.cornerRadius = rounded
}
- if (props.roundedTL !== undefined || props.roundedTR !== undefined ||
- props.roundedBL !== undefined || props.roundedBR !== undefined) {
+ if (
+ props.roundedTL !== undefined ||
+ props.roundedTR !== undefined ||
+ props.roundedBL !== undefined ||
+ props.roundedBR !== undefined
+ ) {
o.independentCorners = true
if (props.roundedTL !== undefined) o.topLeftRadius = props.roundedTL as number
if (props.roundedTR !== undefined) o.topRightRadius = props.roundedTR as number
@@ -211,8 +213,14 @@ function propsToOverrides(props: Record<string, unknown>, isText: boolean): Part
}
const px = props.px as number | undefined
const py = props.py as number | undefined
- if (px !== undefined) { o.paddingLeft = px; o.paddingRight = px }
- if (py !== undefined) { o.paddingTop = py; o.paddingBottom = py }
+ if (px !== undefined) {
+ o.paddingLeft = px
+ o.paddingRight = px
+ }
+ if (py !== undefined) {
+ o.paddingTop = py
+ o.paddingBottom = py
+ }
if (props.pt !== undefined) o.paddingTop = props.pt as number
if (props.pr !== undefined) o.paddingRight = props.pr as number
if (props.pb !== undefined) o.paddingBottom = props.pb as number
@@ -246,7 +254,7 @@ function propsToOverrides(props: Record<string, unknown>, isText: boolean): Part
}
o.textAutoResize = props.textAutoResize
- ? TEXT_AUTO_RESIZE_MAP[props.textAutoResize as string] ?? 'NONE'
+ ? (TEXT_AUTO_RESIZE_MAP[props.textAutoResize as string] ?? 'NONE')
: 'HEIGHT'
}
diff --git a/packages/core/src/renderer.ts b/packages/core/src/renderer.ts
index aad4c4bc0..511841312 100644
--- a/packages/core/src/renderer.ts
+++ b/packages/core/src/renderer.ts
@@ -57,13 +57,12 @@ import {
TEXT_CARET_COLOR,
TEXT_CARET_WIDTH
} from './constants'
-
import { vectorNetworkToPath } from './vector'
import type { SceneNode, SceneGraph, Fill, Stroke } from './scene-graph'
-import type { Color } from './types'
import type { SnapGuide } from './snap'
import type { TextEditor } from './text-editor'
+import type { Color } from './types'
import type { Rect } from './types'
import type { EmbindEnumEntity, Image as CKImage, Path } from 'canvaskit-wasm'
import type {
@@ -1558,10 +1557,7 @@ export class SkiaRenderer {
}
}
- buildParagraph(
- node: SceneNode,
- color?: Float32Array
- ): import('canvaskit-wasm').Paragraph {
+ buildParagraph(node: SceneNode, color?: Float32Array): import('canvaskit-wasm').Paragraph {
const ck = this.ck
const baseColor = color ?? ck.BLACK
const baseFontSize = node.fontSize || DEFAULT_FONT_SIZE
@@ -1602,15 +1598,13 @@ export class SkiaRenderer {
fontSize: s.fontSize ?? baseFontSize,
fontStyle: {
weight: { value: (s.fontWeight ?? node.fontWeight) || 400 } as FontWeight,
- slant: (s.italic ?? node.italic)
- ? ck.FontSlant.Italic
- : ck.FontSlant.Upright
+ slant: (s.italic ?? node.italic) ? ck.FontSlant.Italic : ck.FontSlant.Upright
},
letterSpacing: s.letterSpacing ?? (node.letterSpacing || 0),
decoration: this.textDecorationValue(s.textDecoration ?? node.textDecoration),
heightMultiplier: (s.lineHeight !== undefined ? s.lineHeight : node.lineHeight)
- ? ((s.lineHeight !== undefined ? s.lineHeight : node.lineHeight)! /
- (s.fontSize ?? baseFontSize))
+ ? (s.lineHeight !== undefined ? s.lineHeight : node.lineHeight)! /
+ (s.fontSize ?? baseFontSize)
: undefined
})
)
@@ -1703,7 +1697,12 @@ export class SkiaRenderer {
return fill.color
}
- resolveStrokeColor(stroke: Stroke, strokeIndex: number, node: SceneNode, graph: SceneGraph): Color {
+ resolveStrokeColor(
+ stroke: Stroke,
+ strokeIndex: number,
+ node: SceneNode,
+ graph: SceneGraph
+ ): Color {
const varId = node.boundVariables[`strokes/${strokeIndex}/color`]
if (varId) {
const resolved = graph.resolveColorVariable(varId)
@@ -1991,12 +1990,12 @@ export class SkiaRenderer {
): void {
if (!cursors || cursors.length === 0) return
- const CURSOR_SIZE = 16
- const LABEL_PADDING_X = 6
- const LABEL_PADDING_Y = 3
- const LABEL_FONT_SIZE = 11
+ const CURSOR_SIZE = 9
+ const LABEL_PADDING_X = 4
+ const LABEL_PADDING_Y = 2
+ const LABEL_FONT_SIZE = 10
const LABEL_OFFSET_X = 12
- const LABEL_OFFSET_Y = 18
+ const LABEL_OFFSET_Y = 20
for (const cursor of cursors) {
const screenX = cursor.x * this.zoom + this.panX
@@ -2020,20 +2019,27 @@ export class SkiaRenderer {
}
}
- // Draw cursor arrow (triangle pointing top-left)
- this.auxFill.setColor(this.ck.Color4f(r, g, b, 1))
+ // Figma-style cursor arrow
+ const S = CURSOR_SIZE
const path = new this.ck.Path()
path.moveTo(screenX, screenY)
- path.lineTo(screenX, screenY + CURSOR_SIZE)
- path.lineTo(screenX + CURSOR_SIZE * 0.4, screenY + CURSOR_SIZE * 0.7)
+ path.lineTo(screenX, screenY + S * 1.35)
+ path.lineTo(screenX + S * 0.38, screenY + S * 1.0)
+ path.lineTo(screenX + S * 0.72, screenY + S * 1.5)
+ path.lineTo(screenX + S * 0.92, screenY + S * 1.38)
+ path.lineTo(screenX + S * 0.58, screenY + S * 0.88)
+ path.lineTo(screenX + S * 1.0, screenY + S * 0.82)
path.close()
- canvas.drawPath(path, this.auxFill)
- // White outline for contrast
- this.auxStroke.setColor(this.ck.Color4f(1, 1, 1, 0.9))
- this.auxStroke.setStrokeWidth(1)
+ // White border for contrast
+ this.auxStroke.setColor(this.ck.Color4f(1, 1, 1, 1))
+ this.auxStroke.setStrokeWidth(2)
this.auxStroke.setPathEffect(null)
canvas.drawPath(path, this.auxStroke)
+
+ // Filled arrow in peer color
+ this.auxFill.setColor(this.ck.Color4f(r, g, b, 1))
+ canvas.drawPath(path, this.auxFill)
path.delete()
// Draw name label
@@ -2057,7 +2063,8 @@ export class SkiaRenderer {
textWidth + LABEL_PADDING_X * 2,
LABEL_FONT_SIZE + LABEL_PADDING_Y * 2
),
- 4, 4
+ 4,
+ 4
)
canvas.drawRRect(bgRect, this.auxFill)
diff --git a/packages/core/src/scene-graph.ts b/packages/core/src/scene-graph.ts
index 534b6f371..5cae0a0cb 100644
--- a/packages/core/src/scene-graph.ts
+++ b/packages/core/src/scene-graph.ts
@@ -489,7 +489,11 @@ export class SceneGraph {
this.activeMode.set(collectionId, modeId)
}
- resolveVariable(variableId: string, modeId?: string, visited?: Set<string>): VariableValue | undefined {
+ resolveVariable(
+ variableId: string,
+ modeId?: string,
+ visited?: Set<string>
+ ): VariableValue | undefined {
if (visited?.has(variableId)) return undefined
const variable = this.variables.get(variableId)
if (!variable) return undefined
diff --git a/packages/core/src/style-runs.ts b/packages/core/src/style-runs.ts
index 68fd75137..c44348151 100644
--- a/packages/core/src/style-runs.ts
+++ b/packages/core/src/style-runs.ts
@@ -9,10 +9,7 @@ export function getStyleAt(runs: StyleRun[], index: number): CharacterStyleOverr
return {}
}
-function expandRuns(
- runs: StyleRun[],
- textLength: number
-): (CharacterStyleOverride | null)[] {
+function expandRuns(runs: StyleRun[], textLength: number): (CharacterStyleOverride | null)[] {
const chars: (CharacterStyleOverride | null)[] = new Array(textLength).fill(null)
for (const run of runs) {
for (let i = run.start; i < run.start + run.length && i < textLength; i++) {
@@ -104,7 +101,11 @@ function compactRuns(chars: (CharacterStyleOverride | null)[]): StyleRun[] {
return result
}
-export function adjustRunsForInsert(runs: StyleRun[], pos: number, insertLength: number): StyleRun[] {
+export function adjustRunsForInsert(
+ runs: StyleRun[],
+ pos: number,
+ insertLength: number
+): StyleRun[] {
return runs.map((run) => {
if (pos <= run.start) {
return { ...run, start: run.start + insertLength }
@@ -116,7 +117,11 @@ export function adjustRunsForInsert(runs: StyleRun[], pos: number, insertLength:
})
}
-export function adjustRunsForDelete(runs: StyleRun[], start: number, deleteLength: number): StyleRun[] {
+export function adjustRunsForDelete(
+ runs: StyleRun[],
+ start: number,
+ deleteLength: number
+): StyleRun[] {
const end = start + deleteLength
const result: StyleRun[] = []
for (const run of runs) {
@@ -157,7 +162,12 @@ export function toggleBoldInRange(
return { runs: newRuns, newWeight: targetWeight }
}
-function selectionAllBold(runs: StyleRun[], start: number, end: number, nodeWeight: number): boolean {
+function selectionAllBold(
+ runs: StyleRun[],
+ start: number,
+ end: number,
+ nodeWeight: number
+): boolean {
for (let i = start; i < end; i++) {
const style = getStyleAt(runs, i)
const weight = style.fontWeight ?? nodeWeight
@@ -180,7 +190,12 @@ export function toggleItalicInRange(
return { runs: newRuns, newItalic: !allItalic }
}
-function selectionAllItalic(runs: StyleRun[], start: number, end: number, nodeItalic: boolean): boolean {
+function selectionAllItalic(
+ runs: StyleRun[],
+ start: number,
+ end: number,
+ nodeItalic: boolean
+): boolean {
for (let i = start; i < end; i++) {
const style = getStyleAt(runs, i)
if (!(style.italic ?? nodeItalic)) return false
diff --git a/packages/core/src/text-editor.ts b/packages/core/src/text-editor.ts
index 4e1b062ca..8dc8636f1 100644
--- a/packages/core/src/text-editor.ts
+++ b/packages/core/src/text-editor.ts
@@ -1,7 +1,7 @@
-import type { CanvasKit, Paragraph } from 'canvaskit-wasm'
import type { SkiaRenderer } from './renderer'
import type { SceneNode } from './scene-graph'
import type { Rect } from './types'
+import type { CanvasKit, Paragraph } from 'canvaskit-wasm'
export interface TextCaret {
x: number
@@ -342,7 +342,6 @@ export class TextEditor {
return { x: left, y: top, width: right - left, height: bottom - top }
})
}
-
}
function isWordBoundary(ch: string): boolean {
diff --git a/packages/core/src/tools/ai-adapter.ts b/packages/core/src/tools/ai-adapter.ts
index 545e012b5..55eb3d263 100644
--- a/packages/core/src/tools/ai-adapter.ts
+++ b/packages/core/src/tools/ai-adapter.ts
@@ -5,8 +5,8 @@
* functions with FigmaAPI instantiation.
*/
-import type { ToolDef, ParamDef, ParamType } from './schema'
import type { FigmaAPI } from '../figma-api'
+import type { ToolDef, ParamDef, ParamType } from './schema'
export interface AIAdapterOptions {
getFigma: () => FigmaAPI
diff --git a/packages/core/src/tools/schema.ts b/packages/core/src/tools/schema.ts
index f90b7a8cd..09121d507 100644
--- a/packages/core/src/tools/schema.ts
+++ b/packages/core/src/tools/schema.ts
@@ -7,6 +7,7 @@
*/
import { parseColor } from '../color'
+
import type { FigmaAPI, FigmaNodeProxy } from '../figma-api'
export type ParamType = 'string' | 'number' | 'boolean' | 'color' | 'string[]'
@@ -213,7 +214,7 @@ export const setFill = defineTool({
execute: (figma, { id, color }) => {
const node = figma.getNodeById(id)
if (!node) return { error: `Node "${id}" not found` }
-
+
const c = parseColor(color)
node.fills = [{ type: 'SOLID', color: c, opacity: 1, visible: true }]
return { id, color: c }
@@ -237,10 +238,16 @@ export const setStroke = defineTool({
execute: (figma, { id, color, weight, align }) => {
const node = figma.getNodeById(id)
if (!node) return { error: `Node "${id}" not found` }
-
+
const c = parseColor(color)
node.strokes = [
- { color: c, weight: weight ?? 1, opacity: 1, visible: true, align: (align ?? 'INSIDE') as 'INSIDE' | 'CENTER' | 'OUTSIDE' }
+ {
+ color: c,
+ weight: weight ?? 1,
+ opacity: 1,
+ visible: true,
+ align: (align ?? 'INSIDE') as 'INSIDE' | 'CENTER' | 'OUTSIDE'
+ }
]
return { id, color: c, weight: weight ?? 1 }
}
@@ -276,7 +283,6 @@ export const setEffects = defineTool({
}
if (!isBlur) {
-
effect.color = args.color ? parseColor(args.color) : { r: 0, g: 0, b: 0, a: 0.25 }
effect.offset = { x: args.offset_x ?? 0, y: args.offset_y ?? 4 }
effect.spread = args.spread ?? 0
@@ -309,19 +315,34 @@ export const updateNode = defineTool({
const node = figma.getNodeById(args.id)
if (!node) return { error: `Node "${args.id}" not found` }
const updated: string[] = []
- if (args.x !== undefined) { node.x = args.x; updated.push('x') }
- if (args.y !== undefined) { node.y = args.y; updated.push('y') }
+ if (args.x !== undefined) {
+ node.x = args.x
+ updated.push('x')
+ }
+ if (args.y !== undefined) {
+ node.y = args.y
+ updated.push('y')
+ }
if (args.width !== undefined || args.height !== undefined) {
node.resize(args.width ?? node.width, args.height ?? node.height)
updated.push('size')
}
- if (args.opacity !== undefined) { node.opacity = args.opacity; updated.push('opacity') }
+ if (args.opacity !== undefined) {
+ node.opacity = args.opacity
+ updated.push('opacity')
+ }
if (args.corner_radius !== undefined) {
node.cornerRadius = args.corner_radius
updated.push('cornerRadius')
}
- if (args.visible !== undefined) { node.visible = args.visible; updated.push('visible') }
- if (args.name !== undefined) { node.name = args.name; updated.push('name') }
+ if (args.visible !== undefined) {
+ node.visible = args.visible
+ updated.push('visible')
+ }
+ if (args.name !== undefined) {
+ node.name = args.name
+ updated.push('name')
+ }
if (args.text !== undefined) {
figma.graph.updateNode(node.id, { text: args.text })
updated.push('text')
@@ -578,9 +599,7 @@ export const switchPage = defineTool({
page: { type: 'string', description: 'Page name or ID', required: true }
},
execute: (figma, { page }) => {
- const target =
- figma.root.children.find((p) => p.name === page) ??
- figma.getNodeById(page)
+ const target = figma.root.children.find((p) => p.name === page) ?? figma.getNodeById(page)
if (!target) return { error: `Page "${page}" not found` }
figma.currentPage = target
return { page: target.name, id: target.id }
diff --git a/src/components/CollabPanel.vue b/src/components/CollabPanel.vue
index eb32bae44..7984c7c48 100644
--- a/src/components/CollabPanel.vue
+++ b/src/components/CollabPanel.vue
@@ -19,6 +19,7 @@ const props = defineProps<{
state: CollabState
peers: RemotePeer[]
pendingRoomId?: string | null
+ followingPeer?: number | null
}>()
const emit = defineEmits<{
@@ -26,6 +27,7 @@ const emit = defineEmits<{
join: [roomId: string]
disconnect: []
'update:name': [name: string]
+ follow: [clientId: number | null]
}>()
const joinInput = ref('')
@@ -107,8 +109,14 @@ function initials(name: string): string {
<TooltipRoot v-for="peer in peers" :key="peer.clientId">
<TooltipTrigger as-child>
<div
- class="flex size-6 items-center justify-center rounded-full border-2 border-panel text-[10px] font-semibold text-white"
+ class="flex size-6 cursor-pointer items-center justify-center rounded-full border-2 text-[10px] font-semibold text-white transition-all"
+ :class="
+ followingPeer === peer.clientId
+ ? 'border-white ring-2 ring-white/40'
+ : 'border-panel'
+ "
:style="{ background: colorToCSS(peer.color) }"
+ @click="emit('follow', followingPeer === peer.clientId ? null : peer.clientId)"
>
{{ initials(peer.name) }}
</div>
@@ -118,7 +126,11 @@ function initials(name: string): string {
class="rounded bg-neutral-800 px-2 py-1 text-xs text-white shadow-lg"
:side-offset="4"
>
- {{ peer.name }}
+ {{
+ followingPeer === peer.clientId
+ ? `Following ${peer.name} (click to stop)`
+ : `Click to follow ${peer.name}`
+ }}
</TooltipContent>
</TooltipPortal>
</TooltipRoot>
diff --git a/src/components/EditorCanvas.vue b/src/components/EditorCanvas.vue
index 4da5ecc07..384eeaac1 100644
--- a/src/components/EditorCanvas.vue
+++ b/src/components/EditorCanvas.vue
@@ -1,13 +1,15 @@
<script setup lang="ts">
-import { ref, computed } from 'vue'
+import { ref, computed, watch } from 'vue'
import { useCanvas } from '@/composables/use-canvas'
import { useCanvasInput } from '@/composables/use-canvas-input'
+import { useCollabInjected } from '@/composables/use-collab'
import { useTextEdit } from '@/composables/use-text-edit'
import { useEditorStore } from '@/stores/editor'
import CanvasContextMenu from './CanvasContextMenu.vue'
const store = useEditorStore()
+const collab = useCollabInjected()
const canvasRef = ref<HTMLCanvasElement | null>(null)
const { hitTestSectionTitle, hitTestComponentLabel } = useCanvas(canvasRef, store)
@@ -15,11 +17,17 @@ const { cursorOverride } = useCanvasInput(
canvasRef,
store,
hitTestSectionTitle,
- hitTestComponentLabel
+ hitTestComponentLabel,
+ (cx, cy) => collab?.updateCursor(cx, cy, store.state.currentPageId)
)
useTextEdit(canvasRef, store)
+watch(
+ () => [...store.state.selectedIds],
+ (ids) => collab?.updateSelection(ids)
+)
+
const cursor = computed(() => {
if (cursorOverride.value) return cursorOverride.value
const tool = store.state.activeTool
diff --git a/src/components/FillPicker.vue b/src/components/FillPicker.vue
index f2bf1a203..235f7ed35 100644
--- a/src/components/FillPicker.vue
+++ b/src/components/FillPicker.vue
@@ -405,11 +405,7 @@ function stopSwatchColor(stop: GradientStop) {
</div>
<!-- HSV color area (solid mode, or editing active gradient stop) -->
- <HsvColorArea
- v-if="fill.type !== 'IMAGE'"
- :color="activeColor"
- @update="onColorUpdate"
- />
+ <HsvColorArea v-if="fill.type !== 'IMAGE'" :color="activeColor" @update="onColorUpdate" />
</PopoverContent>
</PopoverPortal>
</PopoverRoot>
diff --git a/src/components/HsvColorArea.vue b/src/components/HsvColorArea.vue
index bfdd9262b..ef304945f 100644
--- a/src/components/HsvColorArea.vue
+++ b/src/components/HsvColorArea.vue
@@ -146,14 +146,7 @@ const hueColor = computed(() => {
<!-- Hue slider -->
<div class="mt-2">
- <input
- type="range"
- class="hue-slider"
- :value="hue"
- min="0"
- max="360"
- @input="onHueInput"
- />
+ <input type="range" class="hue-slider" :value="hue" min="0" max="360" @input="onHueInput" />
</div>
<!-- Alpha slider -->
diff --git a/src/composables/use-canvas-input.ts b/src/composables/use-canvas-input.ts
index 4d868bccb..aae42013a 100644
--- a/src/composables/use-canvas-input.ts
+++ b/src/composables/use-canvas-input.ts
@@ -225,7 +225,11 @@ export function useCanvasInput(
canvasRef: Ref<HTMLCanvasElement | null>,
store: EditorStore,
hitTestSectionTitle: (cx: number, cy: number) => import('@/engine/scene-graph').SceneNode | null,
- hitTestComponentLabel: (cx: number, cy: number) => import('@/engine/scene-graph').SceneNode | null
+ hitTestComponentLabel: (
+ cx: number,
+ cy: number
+ ) => import('@/engine/scene-graph').SceneNode | null,
+ onCursorMove?: (cx: number, cy: number) => void
) {
const drag = ref<DragState | null>(null)
const cursorOverride = ref<string | null>(null)
@@ -481,6 +485,11 @@ export function useCanvasInput(
}
function onMouseMove(e: MouseEvent) {
+ if (onCursorMove) {
+ const { cx, cy } = getCoords(e)
+ onCursorMove(cx, cy)
+ }
+
// Pen tool: track cursor for preview line
if (store.state.activeTool === 'PEN' && store.state.penState && !drag.value) {
const { cx, cy } = getCoords(e)
diff --git a/src/composables/use-collab.ts b/src/composables/use-collab.ts
index ec99f1a01..df0684344 100644
--- a/src/composables/use-collab.ts
+++ b/src/composables/use-collab.ts
@@ -1,26 +1,21 @@
-import { ref, onUnmounted, computed } from 'vue'
-import * as awarenessProtocol from 'y-protocols/awareness'
+import { joinRoom as joinTrysteroRoom } from 'trystero/mqtt'
+import { ref, watch, onUnmounted, computed, type InjectionKey, inject } from 'vue'
import { IndexeddbPersistence } from 'y-indexeddb'
-import { joinRoom as joinTrysteroRoom } from 'trystero'
-import type { Room } from 'trystero'
+import * as awarenessProtocol from 'y-protocols/awareness'
import * as Y from 'yjs'
+import {
+ TRYSTERO_APP_ID,
+ PEER_COLORS,
+ ROOM_ID_LENGTH,
+ ROOM_ID_CHARS,
+ YJS_JSON_FIELDS
+} from '@/constants'
+
import type { SceneNode } from '@/engine/scene-graph'
import type { EditorStore } from '@/stores/editor'
import type { Color } from '@/types'
-
-const TRYSTERO_APP_ID = 'openpencil'
-
-const PEER_COLORS: Color[] = [
- { r: 0.96, g: 0.26, b: 0.21, a: 1 },
- { r: 0.13, g: 0.59, b: 0.95, a: 1 },
- { r: 0.3, g: 0.69, b: 0.31, a: 1 },
- { r: 1.0, g: 0.76, b: 0.03, a: 1 },
- { r: 0.61, g: 0.15, b: 0.69, a: 1 },
- { r: 1.0, g: 0.34, b: 0.13, a: 1 },
- { r: 0.0, g: 0.74, b: 0.83, a: 1 },
- { r: 0.91, g: 0.12, b: 0.39, a: 1 },
-]
+import type { Room } from 'trystero'
export interface RemotePeer {
clientId: number
@@ -44,7 +39,7 @@ export function useCollab(store: EditorStore) {
roomId: null,
peers: [],
localName: localStorage.getItem('op-collab-name') || '',
- localColor: PEER_COLORS[Math.floor(Math.random() * PEER_COLORS.length)],
+ localColor: PEER_COLORS[crypto.getRandomValues(new Uint8Array(1))[0] % PEER_COLORS.length]
})
let ydoc: Y.Doc | null = null
@@ -72,6 +67,7 @@ export function useCollab(store: EditorStore) {
awareness.on('change', () => {
updatePeersList()
+ tickFollow()
})
ynodes.observeDeep((events) => {
@@ -85,19 +81,37 @@ export function useCollab(store: EditorStore) {
store.requestRender()
})
- room = joinTrysteroRoom({ appId: TRYSTERO_APP_ID }, roomId)
+ room = joinTrysteroRoom(
+ {
+ appId: TRYSTERO_APP_ID,
+ rtcConfig: {
+ iceServers: [
+ { urls: 'stun:stun.l.google.com:19302' },
+ { urls: 'stun:stun.cloudflare.com:3478' },
+ {
+ urls: 'turn:openrelay.metered.ca:443',
+ username: 'openrelayproject',
+ credential: 'openrelayproject'
+ },
+ {
+ urls: 'turn:openrelay.metered.ca:443?transport=tcp',
+ username: 'openrelayproject',
+ credential: 'openrelayproject'
+ }
+ ]
+ }
+ },
+ roomId
+ )
const [sendUpdate, getUpdate] = room.makeAction<Uint8Array>('yjs-update')
const [sendAw, getAw] = room.makeAction<Uint8Array>('awareness')
const [sendSync, getSync] = room.makeAction<Uint8Array>('sync-step1')
const [sendSyncReply, getSyncReply] = room.makeAction<Uint8Array>('sync-reply')
- sendYjsUpdate = (data, peerId) =>
- peerId ? sendUpdate(data, peerId) : sendUpdate(data)
- sendAwareness = (data, peerId) =>
- peerId ? sendAw(data, peerId) : sendAw(data)
- sendSyncStep1 = (data, peerId) =>
- peerId ? sendSync(data, peerId) : sendSync(data)
+ sendYjsUpdate = (data, peerId) => (peerId ? sendUpdate(data, peerId) : sendUpdate(data))
+ sendAwareness = (data, peerId) => (peerId ? sendAw(data, peerId) : sendAw(data))
+ sendSyncStep1 = (data, peerId) => (peerId ? sendSync(data, peerId) : sendSync(data))
getUpdate((data) => {
if (!ydoc) return
@@ -126,15 +140,14 @@ export function useCollab(store: EditorStore) {
sendYjsUpdate?.(update)
})
- awareness.on('update', ({ added, updated, removed }: {
- added: number[]
- updated: number[]
- removed: number[]
- }) => {
- const changedClients = [...added, ...updated, ...removed]
- const encodedUpdate = awarenessProtocol.encodeAwarenessUpdate(awareness!, changedClients)
- sendAwareness?.(encodedUpdate)
- })
+ awareness.on(
+ 'update',
+ ({ added, updated, removed }: { added: number[]; updated: number[]; removed: number[] }) => {
+ const changedClients = [...added, ...updated, ...removed]
+ const encodedUpdate = awarenessProtocol.encodeAwarenessUpdate(awareness!, changedClients)
+ sendAwareness?.(encodedUpdate)
+ }
+ )
room.onPeerJoin((peerId) => {
state.value.connected = true
@@ -142,21 +155,37 @@ export function useCollab(store: EditorStore) {
sendSyncStep1?.(sv, peerId)
if (awareness) {
- const encodedUpdate = awarenessProtocol.encodeAwarenessUpdate(
- awareness,
- [awareness.clientID]
- )
+ const encodedUpdate = awarenessProtocol.encodeAwarenessUpdate(awareness, [
+ awareness.clientID
+ ])
sendAwareness?.(encodedUpdate, peerId)
}
})
room.onPeerLeave(() => {
+ if (awareness) {
+ const remoteClients = [...awareness.getStates().keys()].filter(
+ (id) => id !== awareness!.clientID
+ )
+ awarenessProtocol.removeAwarenessStates(awareness, remoteClients, 'peer-left')
+ }
updatePeersList()
})
state.value.connected = true
broadcastAwareness()
+ watch(
+ () => store.state.zoom,
+ (zoom) => {
+ if (!awareness) return
+ const prev = awareness.getLocalState()?.cursor as Record<string, unknown> | undefined
+ if (prev) {
+ awareness.setLocalStateField('cursor', { ...prev, zoom })
+ }
+ }
+ )
+
const origUpdateNode = store.graph.updateNode.bind(store.graph)
store.graph.updateNode = (id: string, changes: Partial<SceneNode>) => {
origUpdateNode(id, changes)
@@ -266,15 +295,11 @@ export function useCollab(store: EditorStore) {
}
function applyYnodeToGraph(nodeId: string, ynode: Y.Map<unknown>) {
- const JSON_FIELDS = new Set([
- 'childIds', 'fills', 'strokes', 'effects',
- 'vectorNetwork', 'boundVariables', 'styleRuns',
- ])
const existing = store.graph.getNode(nodeId)
const props: Record<string, unknown> = {}
for (const [key, value] of ynode.entries()) {
- if (JSON_FIELDS.has(key)) {
+ if (YJS_JSON_FIELDS.has(key)) {
try {
props[key] = typeof value === 'string' ? JSON.parse(value) : value
} catch {
@@ -303,13 +328,13 @@ export function useCollab(store: EditorStore) {
if (!awareness) return
awareness.setLocalStateField('user', {
name: state.value.localName,
- color: state.value.localColor,
+ color: state.value.localColor
})
}
function updateCursor(x: number, y: number, pageId: string) {
if (!awareness) return
- awareness.setLocalStateField('cursor', { x, y, pageId })
+ awareness.setLocalStateField('cursor', { x, y, pageId, zoom: store.state.zoom })
}
function updateSelection(ids: string[]) {
@@ -333,7 +358,7 @@ export function useCollab(store: EditorStore) {
name: user.name || 'Anonymous',
color: user.color || PEER_COLORS[clientId % PEER_COLORS.length],
cursor: peerState.cursor as RemotePeer['cursor'],
- selection: peerState.selection as string[],
+ selection: peerState.selection as string[]
})
})
@@ -345,7 +370,7 @@ export function useCollab(store: EditorStore) {
color: p.color,
x: p.cursor!.x,
y: p.cursor!.y,
- selection: p.selection,
+ selection: p.selection
}))
store.requestRender()
}
@@ -357,10 +382,10 @@ export function useCollab(store: EditorStore) {
}
function generateRoomId(): string {
- const chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
+ const bytes = crypto.getRandomValues(new Uint8Array(ROOM_ID_LENGTH))
let result = ''
- for (let i = 0; i < 8; i++) {
- result += chars[Math.floor(Math.random() * chars.length)]
+ for (let i = 0; i < ROOM_ID_LENGTH; i++) {
+ result += ROOM_ID_CHARS[bytes[i] % ROOM_ID_CHARS.length]
}
return result
}
@@ -376,6 +401,33 @@ export function useCollab(store: EditorStore) {
connect(roomId)
}
+ const followingPeer = ref<number | null>(null)
+
+ function followPeer(clientId: number | null) {
+ followingPeer.value = clientId
+ }
+
+ function tickFollow() {
+ if (!followingPeer.value || !awareness) return
+ const peerState = awareness.getStates().get(followingPeer.value)
+ if (!peerState?.cursor) {
+ followingPeer.value = null
+ return
+ }
+ const cursor = peerState.cursor as { x: number; y: number; pageId: string; zoom?: number }
+ if (cursor.pageId !== store.state.currentPageId) {
+ store.switchPage(cursor.pageId)
+ }
+ const canvas = document.querySelector('canvas')
+ if (!canvas) return
+ if (cursor.zoom) store.state.zoom = cursor.zoom
+ const cw = canvas.width / devicePixelRatio
+ const ch = canvas.height / devicePixelRatio
+ store.state.panX = cw / 2 - cursor.x * store.state.zoom
+ store.state.panY = ch / 2 - cursor.y * store.state.zoom
+ store.requestRender()
+ }
+
onUnmounted(() => {
disconnect()
})
@@ -383,11 +435,20 @@ export function useCollab(store: EditorStore) {
return {
state,
remotePeers,
+ followingPeer,
connect: joinRoom,
disconnect,
shareCurrentDoc,
updateCursor,
updateSelection,
setLocalName,
+ followPeer,
+ tickFollow
}
}
+
+export type CollabReturn = ReturnType<typeof useCollab>
+export const COLLAB_KEY = Symbol('collab') as InjectionKey<CollabReturn>
+export function useCollabInjected() {
+ return inject(COLLAB_KEY)
+}
diff --git a/src/constants.ts b/src/constants.ts
index aafc7733e..4504055ce 100644
--- a/src/constants.ts
+++ b/src/constants.ts
@@ -57,8 +57,34 @@ export {
RULER_MAJOR_TOLERANCE
} from '@open-pencil/core'
+import type { Color } from '@/types'
import type { Fill, Stroke } from '@open-pencil/core'
+export const TRYSTERO_APP_ID = 'openpencil'
+export const ROOM_ID_LENGTH = 8
+export const ROOM_ID_CHARS = 'abcdefghijklmnopqrstuvwxyz0123456789'
+
+export const PEER_COLORS: Color[] = [
+ { r: 0.96, g: 0.26, b: 0.21, a: 1 },
+ { r: 0.13, g: 0.59, b: 0.95, a: 1 },
+ { r: 0.3, g: 0.69, b: 0.31, a: 1 },
+ { r: 1.0, g: 0.76, b: 0.03, a: 1 },
+ { r: 0.61, g: 0.15, b: 0.69, a: 1 },
+ { r: 1.0, g: 0.34, b: 0.13, a: 1 },
+ { r: 0.0, g: 0.74, b: 0.83, a: 1 },
+ { r: 0.91, g: 0.12, b: 0.39, a: 1 }
+]
+
+export const YJS_JSON_FIELDS = new Set([
+ 'childIds',
+ 'fills',
+ 'strokes',
+ 'effects',
+ 'vectorNetwork',
+ 'boundVariables',
+ 'styleRuns'
+])
+
export const DEFAULT_SHAPE_FILL: Fill = {
type: 'SOLID',
color: { r: 0.83, g: 0.83, b: 0.83, a: 1 },
diff --git a/src/views/EditorView.vue b/src/views/EditorView.vue
index 36eafaf7e..90a718de2 100644
--- a/src/views/EditorView.vue
+++ b/src/views/EditorView.vue
@@ -1,11 +1,12 @@
<script setup lang="ts">
+import { provide } from 'vue'
import { useEventListener, useUrlSearchParams } from '@vueuse/core'
import { useRoute, useRouter } from 'vue-router'
import { SplitterGroup, SplitterPanel, SplitterResizeHandle } from 'reka-ui'
import { useKeyboard } from '@/composables/use-keyboard'
import { useMenu } from '@/composables/use-menu'
-import { useCollab } from '@/composables/use-collab'
+import { useCollab, COLLAB_KEY } from '@/composables/use-collab'
import { createDemoShapes } from '@/demo'
import { provideEditorStore } from '@/stores/editor'
@@ -23,6 +24,7 @@ const store = provideEditorStore()
useKeyboard(store)
useMenu(store)
const collab = useCollab(store)
+provide(COLLAB_KEY, collab)
;(window as Window & { __OPEN_PENCIL_STORE__?: typeof store }).__OPEN_PENCIL_STORE__ = store
useEventListener(
@@ -90,10 +92,12 @@ function onDisconnect() {
:state="collab.state.value"
:peers="collab.remotePeers.value"
:pending-room-id="pendingRoomId"
+ :following-peer="collab.followingPeer.value"
@share="onShare"
@join="onJoin"
@disconnect="onDisconnect"
@update:name="collab.setLocalName"
+ @follow="collab.followPeer"
/>
</div>
<PropertiesPanel />