AI-native design editor. Open-source Figma alternative.
feat(collab): share variables and collections in a room (#1153)
Danila Poyarkovb85c9d40ac09
diff --git a/changes/1153/fixed.md b/changes/1153/fixed.mdnew file mode 100644index 000000000..b811e3435--- /dev/null+++ b/changes/1153/fixed.md@@ -0,0 +1 @@+- People who join a shared room see and edit the document's variables: collections, modes, and values reach everyone in the room, layers bound to them follow, and two people editing different modes of one variable both keep their change. Rooms opened by earlier builds do not meet rooms opened by this one.diff --git a/packages/core/src/editor/variables.ts b/packages/core/src/editor/variables.tsindex fb032ab9f..260d33301 100644--- a/packages/core/src/editor/variables.ts+++ b/packages/core/src/editor/variables.ts@@ -64,7 +64,8 @@ export function createVariableActions(ctx: EditorContext) {* Re-resolves the layers a change to what variables resolve to can reach: those bound to the* changed variables or to variables aliasing them. Every other variable change, such as adding,* renaming, reordering, or a token field, changes nothing the canvas draws, so it only refreshes- * the views and leaves the canvas's recorded pictures in place.+ * the views and leaves the canvas's recorded pictures in place. Records written into the graph+ * without an editor action, such as a collaborator's, take effect through it.*/function refreshVariables(scope: BindingScope) {reconcileVariableLayouts(ctx.graph, scope)@@ -539,6 +540,7 @@ export function createVariableActions(ctx: EditorContext) {}return {+ refreshVariables,updateVariableToken,setModeCondition,duplicateVariable,diff --git a/src/app/collab/session.ts b/src/app/collab/session.tsindex 6c2e35820..b4034b8b3 100644--- a/src/app/collab/session.ts+++ b/src/app/collab/session.ts@@ -19,6 +19,7 @@ import {} from '@/app/collab/shared-tree/fields'import type { JoinCollabRoom } from '@/app/collab/transport'import type { RemotePeer } from '@/app/collab/types'+import { bindVariableSync, type YRecords } from '@/app/collab/variables'import { attachRoomVoice, type RoomVoice } from '@/app/collab/voice/room'import {bindCollabGraphEvents,@@ -89,6 +90,8 @@ export function openRoomSession({const ynodes: YNodes = ydoc.getMap('nodes')const yimages = ydoc.getMap<Uint8Array>('images')const meta = ydoc.getMap<unknown>('meta')+ const yvariables: YRecords = ydoc.getMap('variables')+ const ycollections: YRecords = ydoc.getMap('collections')const persistence = openSavedCopy(roomId, ydoc)const peers = shallowRef<RemotePeer[]>([])@@ -201,6 +204,7 @@ export function openRoomSession({const stopAgentSync = publishLocalAgents(store, () => awareness, identity.color)const stopAgentPreviews = shareAgentPreviews(store, connection)const voice = attachRoomVoice({ awareness, peers, connection })+ const variableSync = bindVariableSync({ store, ydoc, yvariables, ycollections })const unbindGraphEvents = bindCollabGraphEvents({store,getYdoc: () => (disposed ? null : ydoc),@@ -225,6 +229,7 @@ export function openRoomSession({},shareDocument() {sync.syncAllNodesToYjs()+ variableSync.share()writeRoomName(meta, store.state.documentName)refreshDocument()},@@ -232,6 +237,7 @@ export function openRoomSession({if (disposed) return// Unbinding writes an edit still waiting to be sent, so it runs while the room is open.unbindGraphEvents()+ variableSync.dispose()disposed = trueconnectionTimer.pause()stopNameWatch()diff --git a/src/app/collab/variables.ts b/src/app/collab/variables.tsnew file mode 100644index 000000000..76504eb35--- /dev/null+++ b/src/app/collab/variables.ts@@ -0,0 +1,238 @@+import { isEqual } from 'es-toolkit/predicate'+import * as Y from 'yjs'++import type { Variable, VariableCollection } from '@open-pencil/scene-graph'++import type { EditorStore } from '@/app/editor/active-store'++/**+ * Variables and collections in a room, by id. Each record is a map of its fields, so peers+ * changing different fields both keep theirs; a variable's values are a nested map by mode, so+ * two people editing a color in different modes do too.+ */+export type YRecords = Y.Map<Y.Map<unknown>>++const VALUES_BY_MODE = 'valuesByMode'++type VariableSyncOptions = {+ store: EditorStore+ ydoc: Y.Doc+ yvariables: YRecords+ ycollections: YRecords+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value)+}++function isVariable(value: unknown): value is Variable {+ return (+ isRecord(value) &&+ typeof value.id === 'string' &&+ typeof value.name === 'string' &&+ typeof value.type === 'string' &&+ typeof value.collectionId === 'string' &&+ isRecord(value.valuesByMode)+ )+}++function isCollection(value: unknown): value is VariableCollection {+ return (+ isRecord(value) &&+ typeof value.id === 'string' &&+ typeof value.name === 'string' &&+ typeof value.defaultModeId === 'string' &&+ Array.isArray(value.modes) &&+ Array.isArray(value.variableIds)+ )+}++/** Writes the fields of `record` that differ from what the room holds, and drops the others. */+function writeRecord(target: Y.Map<unknown>, record: object): void {+ const fields = new Map<string, unknown>(Object.entries(record))+ // Collected first: deleting from a Yjs map while iterating its keys skips some.+ for (const key of Array.from(target.keys())) if (!fields.has(key)) target.delete(key)+ for (const [key, value] of fields) {+ if (key === VALUES_BY_MODE && isRecord(value)) {+ let modes = target.get(key)+ if (!(modes instanceof Y.Map)) {+ modes = new Y.Map<unknown>()+ target.set(key, modes)+ }+ writeRecord(modes as Y.Map<unknown>, value)+ continue+ }+ if (value === undefined) target.delete(key)+ else if (!isEqual(target.get(key), value)) target.set(key, structuredClone(value))+ }+}++/** Writes `records` that differ from `sent` into the room, and removes those gone since. */+function writeChanges<T extends { id: string }>(+ target: YRecords,+ records: Map<string, T>,+ sent: Map<string, T>+): void {+ for (const id of sent.keys()) if (!records.has(id)) target.delete(id)+ for (const [id, record] of records) {+ if (isEqual(sent.get(id), record)) continue+ let ymap = target.get(id)+ if (!ymap) {+ ymap = new Y.Map<unknown>()+ target.set(id, ymap)+ }+ writeRecord(ymap, record)+ }+}++/** Sets a record in place where it exists, as views may hold it, as undo does. */+function applyRecord<T extends object>(target: Map<string, T>, id: string, value: T): void {+ const existing = target.get(id)+ if (!existing) {+ target.set(id, value)+ return+ }+ for (const key of Object.keys(existing)) {+ if (!Object.hasOwn(value, key)) Reflect.deleteProperty(existing, key)+ }+ Object.assign(existing, value)+}++/** The ids of records an event batch on `records` added, changed, or removed. */+function changedIds(records: YRecords, events: Y.YEvent<Y.Map<unknown>>[]): Set<string> {+ const ids = new Set<string>()+ for (const event of events) {+ if (event.target === records) {+ for (const key of event.changes.keys.keys()) ids.add(key)+ continue+ }+ const [id] = event.path+ if (typeof id === 'string') ids.add(id)+ }+ return ids+}++/**+ * Keeps the document's variables and collections in step with the room's. Local edits reach the+ * room after every change to the history, which every variable edit, undo, and redo makes;+ * peers' edits are applied without one, and the layers bound to them are laid out again.+ * Which mode a collection shows is each viewer's own, and stays out of the room.+ */+export function bindVariableSync({ store, ydoc, yvariables, ycollections }: VariableSyncOptions) {+ const graph = () => store.graph+ // What the room holds as this peer last wrote or read it, so only what changed since is sent.+ let sentVariables = structuredClone(graph().variables)+ let sentCollections = structuredClone(graph().variableCollections)++ function send() {+ const { variables, variableCollections } = graph()+ if (isEqual(sentVariables, variables) && isEqual(sentCollections, variableCollections)) return+ ydoc.transact(() => {+ writeChanges(ycollections, variableCollections, sentCollections)+ writeChanges(yvariables, variables, sentVariables)+ })+ sentVariables = structuredClone(variables)+ sentCollections = structuredClone(variableCollections)+ }++ /** Writes every variable and collection, as Share does with the layers. */+ function share() {+ sentVariables = new Map()+ sentCollections = new Map()+ send()+ }++ /**+ * A collection lists its variables in order. Two peers adding variables at once each write+ * their own list, and the room keeps one, so a variable missing from its collection's list is+ * added at the end, in the same order on every peer.+ */+ function keepCollectionsComplete(collectionIds: Iterable<string>) {+ const { variables, variableCollections } = graph()+ for (const id of collectionIds) {+ const collection = variableCollections.get(id)+ if (!collection) continue+ const listed = new Set(collection.variableIds)+ const missing = [...variables.values()]+ .filter((variable) => variable.collectionId === id && !listed.has(variable.id))+ .map((variable) => variable.id)+ .toSorted()+ if (missing.length > 0) collection.variableIds = [...collection.variableIds, ...missing]+ }+ }++ /** Applies a peer's records; one that is not well formed is left as this peer has it. */+ function receive<T extends object>(+ records: YRecords,+ target: Map<string, T>,+ isValid: (value: unknown) => value is T,+ events: Y.YEvent<Y.Map<unknown>>[]+ ): Set<string> {+ const ids = changedIds(records, events)+ for (const id of ids) {+ const value: unknown = records.get(id)?.toJSON()+ if (value === undefined) target.delete(id)+ else if (isValid(value)) applyRecord(target, id, value)+ }+ return ids+ }++ /** Takes the records a peer sent as what the room holds; others may hold unsent edits. */+ function markReceived<T>(sent: Map<string, T>, records: Map<string, T>, ids: Set<string>) {+ for (const id of ids) {+ const record = records.get(id)+ if (record) sent.set(id, structuredClone(record))+ else sent.delete(id)+ }+ }++ /**+ * Lays out what the received records reach. Only those records are taken as sent: an edit not+ * yet in the history, such as a running plugin script's, still goes out with the next change.+ */+ function settle(variableIds: Set<string>, collectionIds: Set<string>) {+ const { variables, variableCollections } = graph()+ markReceived(sentVariables, variables, variableIds)+ markReceived(sentCollections, variableCollections, collectionIds)+ const collections = new Set(collectionIds)+ for (const id of variableIds) {+ const collectionId = variables.get(id)?.collectionId+ if (collectionId) collections.add(collectionId)+ }+ // A list completed here differs from the room's, and goes out with the next change.+ keepCollectionsComplete(collections)+ const scope = new Set(variableIds)+ for (const id of collections) {+ for (const variableId of variableCollections.get(id)?.variableIds ?? []) scope.add(variableId)+ }+ store.refreshVariables({ variables: scope })+ }++ // This peer's own writes are already in its graph.+ function onVariables(events: Y.YEvent<Y.Map<unknown>>[], transaction: Y.Transaction) {+ if (transaction.local) return+ const ids = receive(yvariables, graph().variables, isVariable, events)+ if (ids.size > 0) settle(ids, new Set())+ }++ function onCollections(events: Y.YEvent<Y.Map<unknown>>[], transaction: Y.Transaction) {+ if (transaction.local) return+ const ids = receive(ycollections, graph().variableCollections, isCollection, events)+ if (ids.size > 0) settle(new Set(), ids)+ }++ yvariables.observeDeep(onVariables)+ ycollections.observeDeep(onCollections)+ const stopHistory = store.onEditorEvent('history:changed', send)++ return {+ share,+ dispose() {+ // An edit made just before leaving still reaches the room.+ send()+ stopHistory()+ yvariables.unobserveDeep(onVariables)+ ycollections.unobserveDeep(onCollections)+ }+ }+}diff --git a/src/constants.ts b/src/constants.tsindex 3a02d3bd1..b1a5f9bbb 100644--- a/src/constants.ts+++ b/src/constants.ts@@ -65,10 +65,10 @@ import type { Color } from '@open-pencil/scene-graph/primitives'/*** The collaboration namespace. It names the shared document format and how peers send it, so- * builds that sync the layer tree differently, or encode what they send differently, never join- * each other's rooms; change it with either.+ * builds that sync the layer tree or variables differently, or encode what they send+ * differently, never join each other's rooms; change it with either.*/-export const COLLAB_APP_ID = 'openpencil/4'+export const COLLAB_APP_ID = 'openpencil/5'/*** The most a room message may decode to, compressed or not. A peer's update past it is droppeddiff --git a/tests/app/collab/variables.test.ts b/tests/app/collab/variables.test.tsnew file mode 100644index 000000000..2de5e23c7--- /dev/null+++ b/tests/app/collab/variables.test.ts@@ -0,0 +1,181 @@+import { describe, expect, test } from 'bun:test'++import { SceneGraph, type Color, type Variable } from '@open-pencil/scene-graph'++import { openRoomSession, type RoomSession } from '@/app/collab/session'+import { createEditorStore, type EditorStore } from '@/app/editor/session'++import { expectDefined, getNodeOrThrow } from '#tests/helpers/assert'+import { createMemoryRooms } from '#tests/helpers/collab/memory-transport'++const ROOM = 'cccccccccccccccccccccccccccccccc'+const RED: Color = { r: 1, g: 0, b: 0, a: 1 }+const BLUE: Color = { r: 0, g: 0, b: 1, a: 1 }+const GREEN: Color = { r: 0, g: 1, b: 0, a: 1 }++const noSavedCopy = () => ({ whenSynced: Promise.resolve(), destroy: () => undefined })++type Room = {+ host: EditorStore+ guest: EditorStore+ settle: () => Promise<void>+ ids: { collection: string; light: string; dark: string; brand: string; card: string }+}++/**+ * A host shares a document with a Theme collection, Light and Dark modes, a Brand color, and a+ * card filled with it; a guest joins.+ */+async function withRoom(run: (room: Room) => Promise<void>) {+ const rooms = createMemoryRooms()+ const sessions: RoomSession[] = []+ const host = createEditorStore(new SceneGraph())+ const guest = createEditorStore(new SceneGraph())+ try {+ const collection = host.graph.createCollection('Theme')+ const light = collection.defaultModeId+ const dark = expectDefined(host.graph.createMode(collection.id, 'Dark'), 'Dark mode')+ const brand = host.graph.createVariable('Brand', 'COLOR', collection.id, RED)+ brand.valuesByMode[dark] = BLUE+ const page = expectDefined(host.graph.getPages()[0], 'first page').id+ const card = host.graph.createNode('RECTANGLE', page, {+ name: 'Card',+ fills: [{ type: 'SOLID', color: RED, opacity: 1, visible: true }],+ boundVariables: { 'fills/0/color': brand.id }+ })++ const open = (store: EditorStore, origin: 'shared' | 'joined') => {+ const session = openRoomSession({+ roomId: ROOM,+ store,+ origin,+ joinRoom: rooms.join,+ openSavedCopy: noSavedCopy+ })+ sessions.push(session)+ return session+ }+ open(host, 'shared').shareDocument()+ open(guest, 'joined')+ await rooms.settle()+ await run({+ host,+ guest,+ settle: rooms.settle,+ ids: { collection: collection.id, light, dark, brand: brand.id, card: card.id }+ })+ } finally {+ for (const session of sessions) session.dispose()+ host.preparationController.dispose()+ guest.preparationController.dispose()+ }+}++function brandOf(store: EditorStore, id: string): Variable {+ return expectDefined(store.graph.variables.get(id), 'Brand')+}++describe('variables in a room', () => {+ test('a joined tab receives the collections, modes, and values of the shared document', async () => {+ await withRoom(async ({ guest, ids }) => {+ const collection = expectDefined(guest.graph.variableCollections.get(ids.collection), 'Theme')+ expect(collection.name).toBe('Theme')+ expect(collection.modes.map((mode) => mode.name)).toEqual(['Mode 1', 'Dark'])+ expect(collection.variableIds).toEqual([ids.brand])+ expect(brandOf(guest, ids.brand).valuesByMode).toEqual({+ [ids.light]: RED,+ [ids.dark]: BLUE+ })+ })+ })++ test('an edited value reaches the other tab, where the layers bound to it draw it', async () => {+ await withRoom(async ({ host, guest, settle, ids }) => {+ host.updateVariableValue(ids.brand, ids.light, GREEN)+ await settle()+ expect(brandOf(guest, ids.brand).valuesByMode[ids.light]).toEqual(GREEN)+ // The renderer resolves a bound color as it draws the layer.+ const card = getNodeOrThrow(guest.graph, ids.card)+ expect(guest.graph.resolveColorVariableForNode(card.id, ids.brand)).toEqual(GREEN)+ })+ })++ test('two people editing different modes of one variable both keep their change', async () => {+ await withRoom(async ({ host, guest, settle, ids }) => {+ host.updateVariableValue(ids.brand, ids.light, GREEN)+ guest.updateVariableValue(ids.brand, ids.dark, RED)+ await settle()+ for (const store of [host, guest]) {+ expect(brandOf(store, ids.brand).valuesByMode).toEqual({+ [ids.light]: GREEN,+ [ids.dark]: RED+ })+ }+ })+ })++ test('two people adding variables at once both find theirs in the collection', async () => {+ await withRoom(async ({ host, guest, settle, ids }) => {+ const make = (store: EditorStore, name: string) => {+ const variable = store.graph.createVariable(name, 'COLOR', ids.collection, RED)+ // Created through the graph, it is registered already; the editor action records it.+ store.graph.variables.delete(variable.id)+ const collection = expectDefined(store.graph.variableCollections.get(ids.collection), 'c')+ collection.variableIds = collection.variableIds.filter((id) => id !== variable.id)+ store.addVariable(variable)+ return variable.id+ }+ const accent = make(host, 'Accent')+ const muted = make(guest, 'Muted')+ await settle()+ const lists = [host, guest].map(+ (store) =>+ expectDefined(store.graph.variableCollections.get(ids.collection), 'c').variableIds+ )+ expect(lists[0]).toEqual(lists[1])+ expect(new Set(lists[0])).toEqual(new Set([ids.brand, accent, muted]))+ })+ })++ test('an undo reaches the other tab', async () => {+ await withRoom(async ({ host, guest, settle, ids }) => {+ host.renameVariable(ids.brand, 'Primary')+ await settle()+ expect(brandOf(guest, ids.brand).name).toBe('Primary')+ host.undoAction()+ await settle()+ expect(brandOf(guest, ids.brand).name).toBe('Brand')+ })+ })++ test('a removed collection is removed for everyone, with its variables', async () => {+ await withRoom(async ({ host, guest, settle, ids }) => {+ host.removeCollection(ids.collection)+ await settle()+ expect(guest.graph.variableCollections.has(ids.collection)).toBe(false)+ expect(guest.graph.variables.has(ids.brand)).toBe(false)+ })+ })++ test('an edit not yet in the history still reaches the room when a peer’s edit lands first', async () => {+ await withRoom(async ({ host, guest, settle, ids }) => {+ // A plugin script changes the graph at once and records its undo step when it ends.+ const theme = expectDefined(host.graph.variableCollections.get(ids.collection), 'Theme')+ theme.name = 'Palette'+ guest.updateVariableValue(ids.brand, ids.light, GREEN)+ await settle()+ host.updateVariableValue(ids.brand, ids.dark, GREEN)+ await settle()+ expect(guest.graph.variableCollections.get(ids.collection)?.name).toBe('Palette')+ })+ })++ test('which mode a collection shows stays each viewer’s own', async () => {+ await withRoom(async ({ host, guest, settle, ids }) => {+ host.setActiveMode(ids.collection, ids.dark)+ await settle()+ expect(host.graph.activeMode.get(ids.collection)).toBe(ids.dark)+ expect(guest.graph.activeMode.get(ids.collection)).toBeUndefined()+ })+ })+})