AI-native design editor. Open-source Figma alternative.
Add event emitter to SceneGraph, refactor collab sync
Danila Poyarkovabe108c473f3
diff --git a/bun.lock b/bun.lockindex ec6f63749..e459c32ad 100644--- a/bun.lock+++ b/bun.lock@@ -115,6 +115,7 @@"fflate": "^0.8.2","fontoxpath": "^3.34.0","fzstd": "^0.1.1",+ "nanoevents": "^9.1.0","sucrase": "^3.35.1","yoga-layout": "npm:@open-pencil/[email protected]",},@@ -1892,6 +1893,8 @@"mz": ["[email protected]", "", { "dependencies": { "any-promise": "^1.0.0", "object-assign": "^4.0.1", "thenify-all": "^1.0.0" } }, "sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q=="],+ "nanoevents": ["[email protected]", "", {}, "sha512-Jd0fILWG44a9luj8v5kED4WI+zfkkgwKyRQKItTtlPfEsh7Lznfi1kr8/iZ+XAIss4Qq5GqRB0qtWbaz9ceO/A=="],+"nanoid": ["[email protected]", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w=="],"negotiator": ["[email protected]", "", {}, "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg=="],diff --git a/packages/core/package.json b/packages/core/package.jsonindex 3ef08d76f..d2179fa12 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -42,6 +42,7 @@"fflate": "^0.8.2","fontoxpath": "^3.34.0","fzstd": "^0.1.1",+ "nanoevents": "^9.1.0","sucrase": "^3.35.1","yoga-layout": "npm:@open-pencil/[email protected]"},diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 14758ea05..3252e5115 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -46,7 +46,8 @@ export {type VariableCollection,type VariableCollectionMode,type CharacterStyleOverride,- type StyleRun+ type StyleRun,+ type SceneGraphEvents} from './scene-graph'export { FigmaAPI, FigmaNodeProxy, type FigmaFontName } from './figma-api'diff --git a/packages/core/src/scene-graph.ts b/packages/core/src/scene-graph.tsindex 742a09ff8..a7826d923 100644--- a/packages/core/src/scene-graph.ts+++ b/packages/core/src/scene-graph.ts@@ -1,8 +1,19 @@+import { createNanoEvents } from 'nanoevents'+import { BLACK, DEFAULT_FONT_FAMILY, DEFAULT_STROKE_MITER_LIMIT } from './constants'import { copyEffects, copyFills, copyStrokes, copyStyleRuns } from './copy'export type { GUID, Color } from './types'import type { Matrix, Vector, Color, Rect } from './types'+import type { Emitter } from 'nanoevents'++export interface SceneGraphEvents {+ 'node:created': (node: SceneNode) => void+ 'node:updated': (id: string, changes: Partial<SceneNode>) => void+ 'node:deleted': (id: string) => void+ 'node:reparented': (nodeId: string, oldParentId: string | null, newParentId: string) => void+ 'node:reordered': (nodeId: string, parentId: string, index: number) => void+}export type HandleMirroring = 'NONE' | 'ANGLE' | 'ANGLE_AND_LENGTH'export type WindingRule = 'NONZERO' | 'EVENODD'@@ -452,6 +463,7 @@ export class SceneGraph {variableCollections = new Map<string, VariableCollection>()activeMode = new Map<string, string>()rootId: string+ readonly emitter: Emitter<SceneGraphEvents> = createNanoEvents()private absPosCache = new Map<string, Vector>()constructor() {@@ -705,6 +717,7 @@ export class SceneGraph {parent.childIds.push(node.id)}+ this.emitter.emit('node:created', node)return node}@@ -713,6 +726,7 @@ export class SceneGraph {if (!node) returnthis.absPosCache.clear()Object.assign(node, changes)+ this.emitter.emit('node:updated', id, changes)}reparentNode(nodeId: string, newParentId: string): void {@@ -725,6 +739,7 @@ export class SceneGraph {if (!newParent) returnif (node.parentId === newParentId) return+ const oldParentId = node.parentIdthis.absPosCache.clear()// Convert absolute position@@ -747,6 +762,8 @@ export class SceneGraph {// Adjust position so node stays in same visual placenode.x = absPos.x - newParentAbs.xnode.y = absPos.y - newParentAbs.y++ this.emitter.emit('node:reparented', nodeId, oldParentId, newParentId)}reorderChild(nodeId: string, parentId: string, insertIndex: number): void {@@ -774,6 +791,8 @@ export class SceneGraph {node.parentId = parentIdidx = Math.min(idx, newParent.childIds.length)newParent.childIds.splice(idx, 0, nodeId)++ this.emitter.emit('node:reordered', nodeId, parentId, idx)}deleteNode(id: string): void {@@ -792,6 +811,7 @@ export class SceneGraph {}this.nodes.delete(id)+ this.emitter.emit('node:deleted', id)}hitTest(px: number, py: number, scopeId?: string): SceneNode | null {diff --git a/src/composables/use-collab.ts b/src/composables/use-collab.tsindex 02319e235..98e3f2ec3 100644--- a/src/composables/use-collab.ts+++ b/src/composables/use-collab.ts@@ -48,8 +48,9 @@ export function useCollab(store: EditorStore) {let ynodes: Y.Map<Y.Map<unknown>> | null = nulllet room: Room | null = nulllet persistence: IndexeddbPersistence | null = null- let suppressGraphEvents = false+ let suppressGraphSync = falselet suppressYjsEvents = false+ let unbindGraphEvents: (() => void) | null = nulllet sendYjsUpdate: ((data: Uint8Array, peerId?: string) => void) | null = nulllet sendAwareness: ((data: Uint8Array, peerId?: string) => void) | null = nulllet sendSyncStep1: ((data: Uint8Array, peerId?: string) => void) | null = null@@ -73,11 +74,11 @@ export function useCollab(store: EditorStore) {ynodes.observeDeep((events) => {if (suppressYjsEvents) return- suppressGraphEvents = true+ suppressGraphSync = truetry {applyYjsToGraph(events)} finally {- suppressGraphEvents = false+ suppressGraphSync = false}store.requestRender()})@@ -191,16 +192,38 @@ export function useCollab(store: EditorStore) {})- const origUpdateNode = store.graph.updateNode.bind(store.graph)- store.graph.updateNode = (id: string, changes: Partial<SceneNode>) => {- origUpdateNode(id, changes)- if (!suppressGraphEvents && ydoc && ynodes) {- syncNodeToYjs(id)+ function onGraphMutation(nodeId: string) {+ if (!suppressGraphSync && ydoc && ynodes) {+ syncNodeToYjs(nodeId)}}++ const unbindUpdated = store.graph.emitter.on('node:updated', (id) => onGraphMutation(id))+ const unbindCreated = store.graph.emitter.on('node:created', (node) => onGraphMutation(node.id))+ const unbindReparented = store.graph.emitter.on('node:reparented', (nodeId) =>+ onGraphMutation(nodeId)+ )+ const unbindDeleted = store.graph.emitter.on('node:deleted', (id) => {+ if (!suppressGraphSync && ydoc && ynodes) {+ suppressYjsEvents = true+ ydoc.transact(() => {+ ynodes!.delete(id)+ })+ suppressYjsEvents = false+ }+ })++ unbindGraphEvents = () => {+ unbindUpdated()+ unbindCreated()+ unbindReparented()+ unbindDeleted()+ }}function disconnect() {+ unbindGraphEvents?.()+ unbindGraphEvents = nullvoid room?.leave()room = nullsendYjsUpdate = nulldiff --git a/src/stores/editor.ts b/src/stores/editor.tsindex 0b85d5818..f86d27fed 100644--- a/src/stores/editor.ts+++ b/src/stores/editor.ts@@ -668,6 +668,7 @@ export function createEditorStore() {await new Promise((r) => requestAnimationFrame(r))const imported = await readFigFile(file)graph = imported+ subscribeToGraph()computeAllLayouts(graph)undo.clear()pageViewports.clear()@@ -794,11 +795,13 @@ export function createEditorStore() {const file = new File([blob], state.documentName + '.fig')const imported = await readFigFile(file)graph = imported+ subscribeToGraph()computeAllLayouts(graph)} else if (fileHandle) {const file = await fileHandle.getFile()const imported = await readFigFile(file)graph = imported+ subscribeToGraph()computeAllLayouts(graph)} else {return@@ -989,17 +992,19 @@ export function createEditorStore() {}}- function updateNode(id: string, changes: Partial<SceneNode>) {- graph.updateNode(id, changes)+ function onNodeUpdated(id: string, changes: Partial<SceneNode>) {if ('vectorNetwork' in changes) {_renderer?.invalidateVectorPath(id)}_renderer?.invalidateNodePicture(id)- runLayoutForNode(id)- syncIfInsideComponent(id)- requestRender()}+ function subscribeToGraph() {+ graph.emitter.on('node:updated', onNodeUpdated)+ }++ subscribeToGraph()+function syncIfInsideComponent(nodeId: string) {let current = graph.getNode(nodeId)while (current) {@@ -1011,6 +1016,13 @@ export function createEditorStore() {}}+ function updateNode(id: string, changes: Partial<SceneNode>) {+ graph.updateNode(id, changes)+ runLayoutForNode(id)+ syncIfInsideComponent(id)+ requestRender()+ }+function updateNodeWithUndo(id: string, changes: Partial<SceneNode>, label = 'Update') {const node = graph.getNode(id)if (!node) return