Skip to content

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

fix(collab): keep concurrent comments and document settings in shared rooms (#1378)

Danila Poyarkov347047a0d227
diff --git a/changes/1378/breaking.md b/changes/1378/breaking.md
new file mode 100644
index 000000000..cde9a27e6
--- /dev/null
+++ b/changes/1378/breaking.md
@@ -0,0 +1 @@
+- Shared rooms record document data in a new format, so people on this version and on earlier versions can no longer join each other's rooms, and rooms this browser saved with an earlier version are not converted.
diff --git a/changes/1378/fixed.md b/changes/1378/fixed.md
new file mode 100644
index 000000000..9f9503877
--- /dev/null
+++ b/changes/1378/fixed.md
@@ -0,0 +1 @@
+- In a shared room, comments, replies, review statuses, and file settings that several people change at once all keep their changes instead of one replacing the others, and enabled libraries and the document's color space now reach everyone in the room.
diff --git a/packages/cloud/src/contract/collaboration.ts b/packages/cloud/src/contract/collaboration.ts
index e0f75f4b8..6119f0062 100644
--- a/packages/cloud/src/contract/collaboration.ts
+++ b/packages/cloud/src/contract/collaboration.ts
@@ -17,6 +17,18 @@ export const collaborationPrincipalSchema = v.variant('kind', [
])
export type CollaborationPrincipal = v.InferOutput<typeof collaborationPrincipalSchema>
+/**
+ * Who the relay verified a peer to be, as it writes into that peer's presence under `cloud`, so
+ * other peers can trust it over what the peer says of itself.
+ */
+export const cloudPresenceSchema = v.object({
+ kind: v.picklist(['user', 'guest']),
+ id: v.string(),
+ name: v.string(),
+ permission: documentPermissionSchema
+})
+export type CloudPresence = v.InferOutput<typeof cloudPresenceSchema>
+
export const collaborationTicketSchema = v.object({
token: v.string(),
provider: v.optional(v.picklist(['trystero', 'relay'])),
diff --git a/packages/cloud/src/contract/index.ts b/packages/cloud/src/contract/index.ts
index 42d332afa..eb77f635d 100644
--- a/packages/cloud/src/contract/index.ts
+++ b/packages/cloud/src/contract/index.ts
@@ -34,8 +34,10 @@ export {
} from './ai'
export * from './admin'
export {
+ cloudPresenceSchema,
collaborationPrincipalSchema,
collaborationTicketSchema,
+ type CloudPresence,
type CollaborationPrincipal,
type CollaborationTicket
} from './collaboration'
diff --git a/packages/cloud/src/server/collaboration/relay/awareness.ts b/packages/cloud/src/server/collaboration/relay/awareness.ts
index 00aef030b..d6693459d 100644
--- a/packages/cloud/src/server/collaboration/relay/awareness.ts
+++ b/packages/cloud/src/server/collaboration/relay/awareness.ts
@@ -1,4 +1,9 @@
-import { presenceName, type CollaborationPrincipal, type DocumentPermission } from '#cloud/contract'
+import {
+ presenceName,
+ type CloudPresence,
+ type CollaborationPrincipal,
+ type DocumentPermission
+} from '#cloud/contract'
import * as decoding from 'lib0/decoding'
import * as encoding from 'lib0/encoding'
import * as v from 'valibot'
@@ -46,7 +51,7 @@ export type VerifiedPresence = {
permission: DocumentPermission
}
-function verifiedIdentity({ principal, permission }: VerifiedPresence) {
+function verifiedIdentity({ principal, permission }: VerifiedPresence): CloudPresence {
return {
kind: principal.kind,
id: principal.kind === 'user' ? principal.userId : principal.guestId,
diff --git a/packages/core/src/editor/create.ts b/packages/core/src/editor/create.ts
index 66e45948c..7ce7264e4 100644
--- a/packages/core/src/editor/create.ts
+++ b/packages/core/src/editor/create.ts
@@ -39,6 +39,7 @@ import { createConnectorDrawActions, createConnectorEndpointActions } from './co
import { createConnectorRouting } from './connectors/routing'
import { createConnectorStyleActions } from './connectors/style'
import { createDesignTokenActions } from './design-tokens'
+import { createDocumentSettingsActions } from './document-settings'
import { createFigCompressionActions } from './fig-compression'
import { createGraphEventSubscription } from './graph-events'
import { createGraphReadActions } from './graph-reads'
@@ -287,6 +288,7 @@ export function createEditor(options?: EditorOptions) {
const components = createComponentActions(ctx)
const clipboard = createClipboardActions(ctx)
const colorSpace = createColorSpaceActions(ctx)
+ const documentSettings = createDocumentSettingsActions(ctx)
const undoActions = createUndoActions(ctx)
const text = createTextActions(ctx)
const nodes = createNodeActions(ctx)
@@ -519,6 +521,8 @@ export function createEditor(options?: EditorOptions) {
redoAction: () => text.runTextEditStep(undoBridge.redoAction),
setDocumentColorSpace: colorSpace.setDocumentColorSpace,
+ updateEnabledLibraries: documentSettings.updateEnabledLibraries,
+ refreshDocumentSettings: documentSettings.refreshDocumentSettings,
figCompression: figCompression.figCompression,
setFigCompression: figCompression.setFigCompression,
diff --git a/packages/core/src/editor/document-settings.ts b/packages/core/src/editor/document-settings.ts
new file mode 100644
index 000000000..d6dd8eb76
--- /dev/null
+++ b/packages/core/src/editor/document-settings.ts
@@ -0,0 +1,35 @@
+import { isEqual } from 'es-toolkit'
+
+import type { EnabledLibraryBinding } from '@open-pencil/scene-graph'
+
+import type { EditorContext } from './types'
+
+export function createDocumentSettingsActions(ctx: EditorContext) {
+ /**
+ * Changes which library revisions the document uses, and announces it when anything changed,
+ * so what follows the document, such as a collaboration room, hears of it.
+ */
+ function updateEnabledLibraries<T>(
+ change: (bindings: Map<string, EnabledLibraryBinding>) => T
+ ): T {
+ const before = structuredClone(ctx.graph.enabledLibraries)
+ const result = change(ctx.graph.enabledLibraries)
+ if (!isEqual(before, ctx.graph.enabledLibraries)) {
+ ctx.emitEditorEvent('document:libraries-changed')
+ }
+ return result
+ }
+
+ /**
+ * Announces libraries and a color space written to the graph from elsewhere, as a
+ * collaboration room writes its peers' settings, and draws the document again. It changes
+ * nothing itself, so a read-only document offers it, as it does `refreshVariables`.
+ */
+ function refreshDocumentSettings() {
+ ctx.emitEditorEvent('document:libraries-changed')
+ ctx.emitEditorEvent('document:color-space-changed', ctx.graph.documentColorSpace)
+ ctx.requestRender()
+ }
+
+ return { updateEnabledLibraries, refreshDocumentSettings }
+}
diff --git a/packages/core/src/editor/read-only/actions.ts b/packages/core/src/editor/read-only/actions.ts
index b9bfdd74e..b82dfa1ab 100644
--- a/packages/core/src/editor/read-only/actions.ts
+++ b/packages/core/src/editor/read-only/actions.ts
@@ -136,6 +136,7 @@ export const READ_ONLY_ACTIONS: ReadonlySet<string> = new Set([
'hasShaderRasterizer',
'loadFontsForNodes',
'onEditorEvent',
+ 'refreshDocumentSettings',
'refreshVariables',
'releaseGraphResources',
'removeCanvasRenderer',
diff --git a/packages/core/src/editor/types.ts b/packages/core/src/editor/types.ts
index bf73999d8..55a2f3bd0 100644
--- a/packages/core/src/editor/types.ts
+++ b/packages/core/src/editor/types.ts
@@ -216,6 +216,7 @@ export interface EditorEvents extends SceneGraphEvents {
'repaint:requested': (versions: { renderVersion: number; sceneVersion: number }) => void
'graph:replaced': (graph: SceneGraph) => void
'document:color-space-changed': (colorSpace: DocumentColorSpace) => void
+ 'document:libraries-changed': () => void
'document:read-only-changed': (readOnly: boolean) => void
'history:changed': () => void
'selection:changed': (selectedIds: string[], previousIds: string[]) => void
diff --git a/packages/core/tests/editor/document-settings.test.ts b/packages/core/tests/editor/document-settings.test.ts
new file mode 100644
index 000000000..c9e0b5da7
--- /dev/null
+++ b/packages/core/tests/editor/document-settings.test.ts
@@ -0,0 +1,31 @@
+import { afterEach, describe, expect, test } from 'bun:test'
+
+import { createEditor, type Editor } from '@open-pencil/core/editor'
+
+let editor: Editor
+
+afterEach(() => editor.dispose())
+
+const binding = { libraryId: 'lib-1', revisionId: 'rev-1', enabled: true }
+
+describe('document settings in the editor', () => {
+ test('announces a change to the libraries, and nothing when they stay the same', () => {
+ editor = createEditor()
+ let announced = 0
+ editor.onEditorEvent('document:libraries-changed', () => announced++)
+ editor.updateEnabledLibraries((bindings) => bindings.set('lib-1', binding))
+ editor.updateEnabledLibraries((bindings) => bindings.set('lib-1', { ...binding }))
+ expect(announced).toBe(1)
+ expect(editor.graph.enabledLibraries.get('lib-1')).toEqual(binding)
+ })
+
+ test('a read-only document still takes settings written from elsewhere', () => {
+ editor = createEditor()
+ editor.setReadOnly(true)
+ const colorSpaces: string[] = []
+ editor.onEditorEvent('document:color-space-changed', (colorSpace) => colorSpaces.push(colorSpace))
+ editor.graph.documentColorSpace = 'display-p3'
+ editor.refreshDocumentSettings()
+ expect(colorSpaces).toEqual(['display-p3'])
+ })
+})
diff --git a/packages/scene-graph/package.json b/packages/scene-graph/package.json
index 4ff187d0b..45e178d01 100644
--- a/packages/scene-graph/package.json
+++ b/packages/scene-graph/package.json
@@ -224,6 +224,12 @@
"import": "./dist/order-keys.js",
"default": "./dist/order-keys.js"
},
+ "./paints": {
+ "types": "./dist/paints/index.d.ts",
+ "bun": "./src/paints/index.ts",
+ "import": "./dist/paints/index.js",
+ "default": "./dist/paints/index.js"
+ },
"./parse-path": {
"types": "./dist/parse-path.d.ts",
"bun": "./src/parse-path.ts",
@@ -249,10 +255,10 @@
"default": "./dist/preview.js"
},
"./primitives": {
- "types": "./dist/primitives.d.ts",
- "bun": "./src/primitives.ts",
- "import": "./dist/primitives.js",
- "default": "./dist/primitives.js"
+ "types": "./dist/primitives/index.d.ts",
+ "bun": "./src/primitives/index.ts",
+ "import": "./dist/primitives/index.js",
+ "default": "./dist/primitives/index.js"
},
"./random": {
"types": "./dist/random.d.ts",
diff --git a/packages/scene-graph/src/color/index.ts b/packages/scene-graph/src/color/index.ts
index b08c021c6..523d5db30 100644
--- a/packages/scene-graph/src/color/index.ts
+++ b/packages/scene-graph/src/color/index.ts
@@ -86,3 +86,4 @@ export function colorDistance(c1: Color, c2: Color): number {
) * 255
)
}
+export * from './schema'
diff --git a/packages/scene-graph/src/color/schema.ts b/packages/scene-graph/src/color/schema.ts
new file mode 100644
index 000000000..ded8cae7f
--- /dev/null
+++ b/packages/scene-graph/src/color/schema.ts
@@ -0,0 +1,10 @@
+import * as v from 'valibot'
+
+import { finiteNumberSchema } from '../primitives/schema'
+
+export const colorSchema = v.object({
+ r: finiteNumberSchema,
+ g: finiteNumberSchema,
+ b: finiteNumberSchema,
+ a: finiteNumberSchema
+})
diff --git a/packages/scene-graph/src/comments/index.ts b/packages/scene-graph/src/comments/index.ts
index 9f75a910a..32bbb54ec 100644
--- a/packages/scene-graph/src/comments/index.ts
+++ b/packages/scene-graph/src/comments/index.ts
@@ -2,3 +2,4 @@ export * from './document'
export * from './list'
export * from './merge'
export * from './threads'
+export * from './schema'
diff --git a/packages/scene-graph/src/comments/schema.ts b/packages/scene-graph/src/comments/schema.ts
new file mode 100644
index 000000000..27f13789f
--- /dev/null
+++ b/packages/scene-graph/src/comments/schema.ts
@@ -0,0 +1,51 @@
+import * as v from 'valibot'
+
+import type { CommentThread } from '../types'
+
+// Lenient on purpose: other tools may write comments, so missing fields get defaults and one
+// malformed thread is skipped instead of hiding every comment.
+const commentAuthorColorSchema = v.fallback(
+ v.optional(v.object({ r: v.number(), g: v.number(), b: v.number(), a: v.number() })),
+ undefined
+)
+
+/** What a comment and each reply say, who wrote them and when, and whether they were deleted. */
+const commentEntry = {
+ author: v.fallback(v.string(), ''),
+ authorColor: commentAuthorColorSchema,
+ text: v.fallback(v.string(), ''),
+ createdAt: v.fallback(v.string(), ''),
+ deleted: v.optional(v.boolean())
+}
+
+const commentReplySchema = v.object({ id: v.string(), ...commentEntry })
+
+const commentThreadSchema = v.object({
+ id: v.string(),
+ pageId: v.string(),
+ pageName: v.optional(v.string()),
+ nodeId: v.optional(v.nullable(v.string())),
+ nodeName: v.optional(v.nullable(v.string())),
+ offsetX: v.optional(v.number()),
+ offsetY: v.optional(v.number()),
+ x: v.fallback(v.number(), 0),
+ y: v.fallback(v.number(), 0),
+ ...commentEntry,
+ updatedAt: v.fallback(v.string(), ''),
+ resolved: v.fallback(v.boolean(), false),
+ resolvedAt: v.optional(v.nullable(v.string())),
+ replies: v.fallback(v.array(commentReplySchema), [])
+})
+
+/** A list of comment threads as files and rooms hold them; threads that cannot be read are left out. */
+export const commentThreadsSchema: v.GenericSchema<unknown, CommentThread[]> = v.pipe(
+ v.array(v.unknown()),
+ v.transform((items) =>
+ items.flatMap((item) => {
+ const parsed = v.safeParse(commentThreadSchema, item)
+ if (!parsed.success) return []
+ const thread = parsed.output
+ return [{ ...thread, updatedAt: thread.updatedAt || thread.createdAt }]
+ })
+ )
+)
diff --git a/packages/scene-graph/src/paints/index.ts b/packages/scene-graph/src/paints/index.ts
new file mode 100644
index 000000000..cb7cdd48b
--- /dev/null
+++ b/packages/scene-graph/src/paints/index.ts
@@ -0,0 +1 @@
+export * from './schema'
diff --git a/packages/scene-graph/src/paints/schema.ts b/packages/scene-graph/src/paints/schema.ts
new file mode 100644
index 000000000..ae57a0e61
--- /dev/null
+++ b/packages/scene-graph/src/paints/schema.ts
@@ -0,0 +1,37 @@
+import * as v from 'valibot'
+
+import { colorSchema } from '../color/schema'
+import { finiteNumberSchema, matrixSchema, vectorSchema } from '../primitives/schema'
+import type { FillType } from '../types'
+
+export const gradientStopSchema = v.object({ position: finiteNumberSchema, color: colorSchema })
+
+/** Every fill type, as a record so a type added to `FillType` fails to compile until listed. */
+const FILL_TYPES = {
+ SOLID: true,
+ GRADIENT_LINEAR: true,
+ GRADIENT_RADIAL: true,
+ GRADIENT_ANGULAR: true,
+ GRADIENT_DIAMOND: true,
+ IMAGE: true,
+ VIDEO: true,
+ PATTERN: true,
+ NOISE: true,
+ CUSTOM: true
+} as const satisfies Record<FillType, true>
+
+/**
+ * A fill as data from outside the process, such as a collaborator's, can hold it: the fields a
+ * renderer reads without checking are checked, and the rest pass through as they are.
+ */
+export const fillSchema = v.looseObject({
+ type: v.picklist(Object.keys(FILL_TYPES) as FillType[]),
+ color: colorSchema,
+ opacity: finiteNumberSchema,
+ visible: v.boolean(),
+ gradientStops: v.optional(v.array(gradientStopSchema)),
+ gradientTransform: v.optional(matrixSchema),
+ imageTransform: v.optional(matrixSchema),
+ patternSpacing: v.optional(vectorSchema),
+ noiseSize: v.optional(vectorSchema)
+})
diff --git a/packages/scene-graph/src/plugin-data/fields.ts b/packages/scene-graph/src/plugin-data/fields.ts
index 4cdd08bce..8e5eb2204 100644
--- a/packages/scene-graph/src/plugin-data/fields.ts
+++ b/packages/scene-graph/src/plugin-data/fields.ts
@@ -2,6 +2,7 @@ import * as v from 'valibot'
import { behaviourSchema } from '../behaviours/schema'
import type { OkHCLPayload } from '../color/okhcl'
+import { commentThreadsSchema } from '../comments/schema'
import { isExportFormatId, type ExportFormatId } from '../export-format'
import { clampExportScale } from '../export-scale'
import { FIG_COMPRESSIONS } from '../fig-compression'
@@ -12,7 +13,6 @@ import { nodeStatusSchema, statusWorkflowSchema } from '../statuses/schema'
import {
MODE_ATTRIBUTE_PATTERN,
TOKEN_UNITS,
- type CommentThread,
type EnabledLibraryBinding,
type ExportSetting,
type LayoutDirection,
@@ -137,53 +137,6 @@ const sourceLibraryPublication: v.GenericSchema<unknown, SourceLibraryPublicatio
catalogSource: v.optional(v.string())
})
-// Lenient on purpose: other tools may write comments, so missing fields get defaults and one
-// malformed thread is skipped instead of hiding every comment.
-const commentAuthorColor = v.fallback(
- v.optional(v.object({ r: v.number(), g: v.number(), b: v.number(), a: v.number() })),
- undefined
-)
-
-/** What a comment and each reply say, who wrote them and when, and whether they were deleted. */
-const commentEntry = {
- author: v.fallback(v.string(), ''),
- authorColor: commentAuthorColor,
- text: v.fallback(v.string(), ''),
- createdAt: v.fallback(v.string(), ''),
- deleted: v.optional(v.boolean())
-}
-
-const commentReply = v.object({ id: v.string(), ...commentEntry })
-
-const commentThread = v.object({
- id: v.string(),
- pageId: v.string(),
- pageName: v.optional(v.string()),
- nodeId: v.optional(v.nullable(v.string())),
- nodeName: v.optional(v.nullable(v.string())),
- offsetX: v.optional(v.number()),
- offsetY: v.optional(v.number()),
- x: v.fallback(v.number(), 0),
- y: v.fallback(v.number(), 0),
- ...commentEntry,
- updatedAt: v.fallback(v.string(), ''),
- resolved: v.fallback(v.boolean(), false),
- resolvedAt: v.optional(v.nullable(v.string())),
- replies: v.fallback(v.array(commentReply), [])
-})
-
-const comments: v.GenericSchema<unknown, CommentThread[]> = v.pipe(
- v.array(v.unknown()),
- v.transform((items) =>
- items.flatMap((item) => {
- const parsed = v.safeParse(commentThread, item)
- if (!parsed.success) return []
- const thread = parsed.output
- return [{ ...thread, updatedAt: thread.updatedAt || thread.createdAt }]
- })
- )
-)
-
/**
* Every plugin-data entry OpenPencil writes under {@link OPEN_PENCIL_PLUGIN_ID}: state Figma's
* format has no field for. Add a key here, never as a string elsewhere, so reading and writing
@@ -221,7 +174,7 @@ export const OPEN_PENCIL_PLUGIN_DATA = {
sourceLibraryPublication
),
/** Canvas comment threads, deleted ones included, on the DOCUMENT node. */
- comments: jsonPluginDataField('comments', 'bookkeeping', comments),
+ comments: jsonPluginDataField('comments', 'bookkeeping', commentThreadsSchema),
/** The statuses layers can be in, on the DOCUMENT node. */
statuses: jsonPluginDataField('statuses', 'bookkeeping', statusWorkflowSchema),
/** How tightly the document's `.fig` data is compressed, on the DOCUMENT node. */
diff --git a/packages/scene-graph/src/primitives.ts b/packages/scene-graph/src/primitives/index.ts
similarity index 96%
rename from packages/scene-graph/src/primitives.ts
rename to packages/scene-graph/src/primitives/index.ts
index 3acbf1e67..c993e96c8 100644
--- a/packages/scene-graph/src/primitives.ts
+++ b/packages/scene-graph/src/primitives/index.ts
@@ -40,3 +40,5 @@ export type JSONPrimitive = string | number | boolean | null
export type JSONValue = JSONPrimitive | JSONObject | JSONArray
export type JSONObject = { [key: string]: unknown }
export type JSONArray = unknown[]
+
+export * from './schema'
diff --git a/packages/scene-graph/src/primitives/schema.ts b/packages/scene-graph/src/primitives/schema.ts
new file mode 100644
index 000000000..f6fc4a868
--- /dev/null
+++ b/packages/scene-graph/src/primitives/schema.ts
@@ -0,0 +1,14 @@
+import * as v from 'valibot'
+
+export const finiteNumberSchema = v.pipe(v.number(), v.finite())
+
+export const vectorSchema = v.object({ x: finiteNumberSchema, y: finiteNumberSchema })
+
+export const matrixSchema = v.object({
+ m00: finiteNumberSchema,
+ m01: finiteNumberSchema,
+ m02: finiteNumberSchema,
+ m10: finiteNumberSchema,
+ m11: finiteNumberSchema,
+ m12: finiteNumberSchema
+})
diff --git a/packages/scene-graph/src/variables/schema.ts b/packages/scene-graph/src/variables/schema.ts
index 84e7e5432..cd577a0b8 100644
--- a/packages/scene-graph/src/variables/schema.ts
+++ b/packages/scene-graph/src/variables/schema.ts
@@ -1,13 +1,31 @@
import * as v from 'valibot'
-export const variableAliasSchema = v.object({ aliasId: v.string() })
-const finiteNumber = v.pipe(v.number(), v.finite())
+import { colorSchema } from '../color/schema'
+import { finiteNumberSchema } from '../primitives/schema'
+export const variableAliasSchema = v.object({ aliasId: v.string() })
export const variableColorExpressionSchema = v.object({
expression: v.literal('COMPOSE_COLOR'),
- color: v.union([
- variableAliasSchema,
- v.object({ r: finiteNumber, g: finiteNumber, b: finiteNumber, a: finiteNumber })
- ]),
- opacity: v.union([variableAliasSchema, finiteNumber])
+ color: v.union([variableAliasSchema, colorSchema]),
+ opacity: v.union([variableAliasSchema, finiteNumberSchema])
+})
+
+/**
+ * A variable or collection as data from outside the process can hold it: the fields every
+ * reader relies on are checked, and the rest pass through as they are.
+ */
+export const variableSchema = v.looseObject({
+ id: v.string(),
+ name: v.string(),
+ type: v.string(),
+ collectionId: v.string(),
+ valuesByMode: v.record(v.string(), v.unknown())
+})
+
+export const variableCollectionSchema = v.looseObject({
+ id: v.string(),
+ name: v.string(),
+ defaultModeId: v.string(),
+ modes: v.array(v.unknown()),
+ variableIds: v.array(v.unknown())
})
diff --git a/packages/scene-graph/tsdown.config.ts b/packages/scene-graph/tsdown.config.ts
index 93b47cce8..7db15f8c0 100644
--- a/packages/scene-graph/tsdown.config.ts
+++ b/packages/scene-graph/tsdown.config.ts
@@ -36,11 +36,12 @@ export default defineConfig({
'mutation-impact': './src/mutation-impact.ts',
'node-defaults': './src/node-defaults.ts',
'order-keys': './src/order-keys.ts',
+ 'paints/index': './src/paints/index.ts',
'parse-path': './src/parse-path.ts',
'plugin-data/index': './src/plugin-data/index.ts',
polygon: './src/polygon.ts',
preview: './src/preview.ts',
- primitives: './src/primitives.ts',
+ 'primitives/index': './src/primitives/index.ts',
random: './src/random.ts',
resize: './src/resize.ts',
'scaling/index': './src/scaling/index.ts',
diff --git a/src/AGENTS.md b/src/AGENTS.md
index e726b17ef..78dcb5295 100644
--- a/src/AGENTS.md
+++ b/src/AGENTS.md
@@ -39,7 +39,8 @@ Root Tauri/Vite app. Services and state live under `src/app/**`, views under `sr
- A room's voice call lives in its session (`src/app/collab/voice/room.ts`): who is in it and muted travels in awareness, the microphone goes only to peers in the call through the transport's `media`, and speaking comes from WebRTC's reported audio levels. One window holds one call, owned by `useVoiceCall()` in `src/app/collab/voice/call.ts`, which opens the microphone with VueUse and ends the call when its room goes (`tests/app/collab/voice/room.test.ts`).
- Every agent at work, the built-in chat's and each MCP session's (`src/app/automation/agents.ts`), is registered with `addAgent` in `src/app/presence/registry.ts`, and presence cursors reach the editor only through `showCursors` in `src/app/presence/cursor-motion.ts`, which glides them; never assign `presenceCursors` directly (`tests/app/presence/registry.test.ts`).
- Agent presence in awareness is metadata only. The one content an agent shares is its streamed `render` JSX, published through `publishAgentPreview` (`src/app/presence/preview-stream.ts`) and sent on the room's `agent-preview` channel by `shareAgentPreviews` (`src/app/collab/agent-preview.ts`), which validates and bounds what peers send and draws it with the chat run's canvas preview; never put prompts or other tool arguments in either (`tests/app/collab/agent-preview.test.ts`).
-- Changing how a shared document records data bumps `TREE_FORMAT` and `COLLAB_APP_ID` together, so mismatched builds never meet, and converts saved rooms in `src/app/collab/shared-tree/migration.ts` (`tests/app/collab/shared-tree/migration.test.ts`).
+- What a document holds outside its layers, its document node's plugin data, comment threads, libraries and color space, travels in the room's own maps through `bindDocumentSync` (`src/app/collab/document/sync.ts`), entry by entry and thread by thread, never on the root layer, so people changing it at once all keep their change (`tests/app/collab/document/sync.test.ts`).
+- Changing how a shared document records data bumps `TREE_FORMAT` and `COLLAB_APP_ID` together, so mismatched builds never meet; rooms saved by an earlier format are not converted (`src/app/collab/shared-tree/fields.ts`).
## Browser baseline
diff --git a/src/app/cloud/rooms/live.ts b/src/app/cloud/rooms/live.ts
index b06b806e1..d656c28b4 100644
--- a/src/app/cloud/rooms/live.ts
+++ b/src/app/cloud/rooms/live.ts
@@ -1,7 +1,12 @@
import { isEqual } from 'es-toolkit'
+import * as v from 'valibot'
import { effectScope, onScopeDispose, shallowRef, watch } from 'vue'
-import { RELAY_SERVER_PEER, type CollaborationTicket } from '@open-pencil/cloud/contract'
+import {
+ cloudPresenceSchema,
+ RELAY_SERVER_PEER,
+ type CollaborationTicket
+} from '@open-pencil/cloud/contract'
import type { RoomImageStore } from '@/app/collab/images'
import { leaveRoom, openDocumentRoom, roomForStore } from '@/app/collab/rooms'
@@ -53,9 +58,8 @@ export function electCloudSaver(
const editors = [...presence]
.filter(([clientId, state]) => {
if (clientId === self.clientId) return self.canSave
- const cloud = state.cloud
- if (typeof cloud !== 'object' || cloud === null) return false
- return Reflect.get(cloud, 'permission') === 'edit' && Reflect.get(cloud, 'kind') === 'user'
+ const cloud = v.safeParse(cloudPresenceSchema, state.cloud)
+ return cloud.success && cloud.output.permission === 'edit' && cloud.output.kind === 'user'
})
.map(([clientId]) => clientId)
return editors.length ? Math.min(...editors) : null
diff --git a/src/app/collab/document/sync.ts b/src/app/collab/document/sync.ts
new file mode 100644
index 000000000..96f4a4205
--- /dev/null
+++ b/src/app/collab/document/sync.ts
@@ -0,0 +1,306 @@
+import { isEqual, isPlainObject, keyBy } from 'es-toolkit'
+import * as v from 'valibot'
+import type * as Y from 'yjs'
+
+import type {
+ CommentReply,
+ CommentThread,
+ DocumentColorSpace,
+ EnabledLibraryBinding,
+ PluginDataEntry
+} from '@open-pencil/scene-graph'
+import { commentThreadsSchema } from '@open-pencil/scene-graph/comments'
+import {
+ isPluginDataEntry,
+ OPEN_PENCIL_PLUGIN_DATA,
+ readPluginData,
+ withPluginData
+} from '@open-pencil/scene-graph/plugin-data'
+
+import type { EditorStore } from '@/app/editor/active-store'
+
+import { changedIds, writeChanges, type YRecords } from '../records'
+import { readRoot, type YMeta } from '../shared-tree/fields'
+
+const { comments } = OPEN_PENCIL_PLUGIN_DATA
+const COLOR_SPACE_KEY = 'colorSpace'
+/** A thread's replies are a map of their own by id, so replies written at once all stay. */
+const BY_REPLY = new Set(['replies'])
+
+/** Plugin data of one plugin and key on the document node; a key may hold several values. */
+type EntryRecord = { pluginId: string; key: string; values: string[] }
+type ThreadRecord = Omit<CommentThread, 'replies'> & { replies: Record<string, CommentReply> }
+
+const entryRecordSchema = v.object({
+ pluginId: v.string(),
+ key: v.string(),
+ values: v.array(v.string())
+})
+const bindingSchema = v.object({
+ libraryId: v.string(),
+ revisionId: v.string(),
+ enabled: v.boolean()
+})
+const colorSpaceSchema = v.picklist(['srgb', 'display-p3'] satisfies DocumentColorSpace[])
+
+/**
+ * The room's maps for what the document holds outside its layers: the document node's plugin
+ * data by plugin and key, its comment threads by id, its libraries by id, and its settings,
+ * such as the color space, by name.
+ */
+export type YDocumentData = {
+ entries: YRecords
+ threads: YRecords
+ libraries: YRecords
+ settings: Y.Map<unknown>
+}
+
+export function roomDocumentData(ydoc: Y.Doc): YDocumentData {
+ return {
+ entries: ydoc.getMap('documentEntries'),
+ threads: ydoc.getMap('commentThreads'),
+ libraries: ydoc.getMap('libraries'),
+ settings: ydoc.getMap('documentSettings')
+ }
+}
+
+type DocumentData = DocumentNodeData & {
+ libraries: Map<string, EnabledLibraryBinding>
+ colorSpace: DocumentColorSpace | undefined
+}
+
+/** The document node's plugin data as the room keeps it: entries by plugin and key, threads by id. */
+type DocumentNodeData = {
+ entries: Map<string, EntryRecord>
+ threads: Map<string, ThreadRecord>
+}
+
+const entryId = (pluginId: string, key: string) => JSON.stringify([pluginId, key])
+
+function threadRecord(thread: CommentThread): ThreadRecord {
+ return { ...thread, replies: keyBy(thread.replies, (reply) => reply.id) }
+}
+
+/** A thread the room holds, read as files are; one that cannot be read is left out. */
+function readThread(value: unknown): CommentThread | undefined {
+ if (!isPlainObject(value)) return undefined
+ const replies = isPlainObject(value.replies) ? Object.values(value.replies) : []
+ const parsed = v.safeParse(commentThreadsSchema, [{ ...value, replies }])
+ const thread = parsed.success ? parsed.output[0] : undefined
+ return thread && { ...thread, replies: thread.replies.toSorted(byCreatedAt) }
+}
+
+function byCreatedAt(first: CommentReply, second: CommentReply): number {
+ return first.createdAt.localeCompare(second.createdAt)
+}
+
+/** The document node's plugin data split as the room keeps it. */
+function documentNodeData(pluginData: readonly PluginDataEntry[]): DocumentNodeData {
+ const entries = new Map<string, EntryRecord>()
+ for (const entry of pluginData) {
+ if (isPluginDataEntry(entry, comments)) continue
+ const id = entryId(entry.pluginId, entry.key)
+ const record = entries.get(id) ?? { pluginId: entry.pluginId, key: entry.key, values: [] }
+ record.values.push(entry.value)
+ entries.set(id, record)
+ }
+ const threads = readPluginData(pluginData, comments) ?? []
+ return { entries, threads: new Map(threads.map((thread) => [thread.id, threadRecord(thread)])) }
+}
+
+/** What the document holds that the room shares outside its layers. */
+function readDocumentData(store: EditorStore): DocumentData {
+ const { graph } = store
+ return {
+ ...documentNodeData(graph.getNode(graph.rootId)?.pluginData ?? []),
+ libraries: structuredClone(graph.enabledLibraries),
+ colorSpace: graph.documentColorSpace
+ }
+}
+
+function pluginDataOf(data: DocumentData): PluginDataEntry[] {
+ const entries = [...data.entries.values()]
+ .toSorted((first, second) =>
+ entryId(first.pluginId, first.key).localeCompare(entryId(second.pluginId, second.key))
+ )
+ .flatMap(({ pluginId, key, values }) => values.map((value) => ({ pluginId, key, value })))
+ const threads = [...data.threads.values()].flatMap((record) => readThread(record) ?? [])
+ return withPluginData(entries, comments, threads.length > 0 ? threads : undefined)
+}
+
+/** Takes the room's records with `ids`, or all of them, into `target`. */
+function takeRecords<T>(
+ records: YRecords,
+ target: Map<string, T>,
+ read: (value: unknown) => T | undefined,
+ ids?: ReadonlySet<string>
+): void {
+ for (const id of ids ?? new Set([...records.keys(), ...target.keys()])) {
+ const value = read(records.get(id)?.toJSON())
+ if (value === undefined) target.delete(id)
+ else target.set(id, value)
+ }
+}
+
+const readEntry = (value: unknown) => {
+ const parsed = v.safeParse(entryRecordSchema, value)
+ return parsed.success ? parsed.output : undefined
+}
+const readBinding = (value: unknown) => {
+ const parsed = v.safeParse(bindingSchema, value)
+ return parsed.success ? parsed.output : undefined
+}
+const readThreadRecord = (value: unknown) => {
+ const thread = readThread(value)
+ return thread && threadRecord(thread)
+}
+
+/**
+ * Keeps what the document holds outside its layers in step with the room: the document node's
+ * plugin data, which holds the review statuses and file settings, entry by entry; comment
+ * threads one by one with their replies by id, so people commenting at once all keep theirs;
+ * the libraries it uses; and its color space. A viewer receives these and sends none.
+ */
+export function bindDocumentSync({
+ store,
+ ydoc,
+ data,
+ meta
+}: {
+ store: EditorStore
+ ydoc: Y.Doc
+ data: YDocumentData
+ meta: YMeta
+}) {
+ // What the room holds as this peer last wrote or read it, so only what changed since is sent.
+ let sent = readDocumentData(store)
+ /** Set while the room's data is applied, so applying it is not sent back. */
+ let receiving = false
+ /** The root the room's document data was last taken in whole for. */
+ let followedRoot: string | null = null
+
+ function send() {
+ // A joining tab's own document is not the room's until it follows the room.
+ if (receiving || store.state.readOnly || !holdsRoomRoot()) return
+ write()
+ }
+
+ function write() {
+ const next = readDocumentData(store)
+ ydoc.transact(() => {
+ writeChanges(data.entries, next.entries, sent.entries)
+ writeChanges(data.threads, next.threads, sent.threads, { nested: BY_REPLY })
+ writeChanges(data.libraries, next.libraries, sent.libraries)
+ if (next.colorSpace !== sent.colorSpace) data.settings.set(COLOR_SPACE_KEY, next.colorSpace)
+ })
+ sent = structuredClone(next)
+ }
+
+ /** Whether this tab shows the room's document, so its document node is the room's. */
+ function holdsRoomRoot(): boolean {
+ const rootId = readRoot(meta)
+ return rootId !== undefined && rootId === store.graph.rootId
+ }
+
+ /**
+ * Applies the room's records to the document; with no ids, all of them. They count as sent
+ * before the document changes, so the change is not sent back.
+ */
+ function receive(ids?: {
+ entries?: ReadonlySet<string>
+ threads?: ReadonlySet<string>
+ libraries?: ReadonlySet<string>
+ settings?: true
+ }) {
+ const next = readDocumentData(store)
+ if (!ids || ids.entries) takeRecords(data.entries, next.entries, readEntry, ids?.entries)
+ if (!ids || ids.threads) takeRecords(data.threads, next.threads, readThreadRecord, ids?.threads)
+ if (!ids || ids.libraries) {
+ takeRecords(data.libraries, next.libraries, readBinding, ids?.libraries)
+ }
+ if (!ids || ids.settings) {
+ const colorSpace = v.safeParse(colorSpaceSchema, data.settings.get(COLOR_SPACE_KEY))
+ if (colorSpace.success) next.colorSpace = colorSpace.output
+ }
+ sent = structuredClone(next)
+ receiving = true
+ try {
+ apply(next)
+ } finally {
+ receiving = false
+ }
+ }
+
+ /**
+ * Writes what the room holds into the document. Peers' settings go straight to the graph, as
+ * peers' layers do, so a viewer, whose editor refuses edits, takes them too.
+ */
+ function apply(next: DocumentData) {
+ const { graph } = store
+ const root = graph.getNode(graph.rootId)
+ const pluginData = pluginDataOf(next)
+ if (root && !isEqual(root.pluginData, pluginData)) graph.updateNode(root.id, { pluginData })
+ const libraries = !isEqual(graph.enabledLibraries, next.libraries)
+ if (libraries) graph.enabledLibraries = structuredClone(next.libraries)
+ const colorSpace = next.colorSpace !== undefined && next.colorSpace !== graph.documentColorSpace
+ if (next.colorSpace !== undefined) graph.documentColorSpace = next.colorSpace
+ if (libraries || colorSpace) store.refreshDocumentSettings()
+ }
+
+ /**
+ * Once the tab shows the room's document, takes the room's document data in whole: the room
+ * holds what its people changed since the document was saved.
+ */
+ function follow() {
+ if (!holdsRoomRoot() || followedRoot === store.graph.rootId) return
+ followedRoot = store.graph.rootId
+ receive()
+ }
+
+ function observe(key: 'entries' | 'threads' | 'libraries') {
+ const records = data[key]
+ const handler = (events: Y.YEvent<Y.Map<unknown>>[], transaction: Y.Transaction) => {
+ // This peer's own writes are already in its document; the room's document data reaches a
+ // tab that shows another document when it follows the room.
+ if (transaction.local || !holdsRoomRoot()) return
+ receive({ [key]: changedIds(records, events) })
+ }
+ records.observeDeep(handler)
+ return () => records.unobserveDeep(handler)
+ }
+
+ function onSettings(_event: Y.YMapEvent<unknown>, transaction: Y.Transaction) {
+ if (transaction.local || !holdsRoomRoot()) return
+ receive({ settings: true })
+ }
+
+ const stops = [
+ observe('entries'),
+ observe('threads'),
+ observe('libraries'),
+ store.onEditorEvent('node:updated', (id, changes) => {
+ if (id === store.graph.rootId && 'pluginData' in changes) send()
+ }),
+ store.onEditorEvent('document:libraries-changed', send),
+ store.onEditorEvent('document:color-space-changed', send)
+ ]
+ data.settings.observe(onSettings)
+
+ return {
+ /**
+ * Writes everything, as Share does with the layers. It runs before Share claims the room's
+ * root, and the sharing tab is the room's source, so it has nothing to follow.
+ */
+ share() {
+ if (store.state.readOnly) return
+ followedRoot = store.graph.rootId
+ sent = { entries: new Map(), threads: new Map(), libraries: new Map(), colorSpace: undefined }
+ write()
+ },
+ follow,
+ dispose() {
+ for (const stop of stops) stop()
+ data.settings.unobserve(onSettings)
+ }
+ }
+}
diff --git a/src/app/collab/images.ts b/src/app/collab/images.ts
index 0ef3a470f..c5a3cd453 100644
--- a/src/app/collab/images.ts
+++ b/src/app/collab/images.ts
@@ -24,6 +24,25 @@ export function imageRetryDelayMs(attempt: number): number {
return Math.min(1000 * 2 ** attempt, 60_000)
}
+/**
+ * Images a tab's closed room was still storing, by name, for the tab's next room to store and
+ * name. A room closes while an upload is in flight when it starts over, as after a restore or a
+ * refused join. The bytes go along, not the reference: the next room may be another workspace's,
+ * and storing what its workspace already holds uploads nothing.
+ */
+const handedOver = new WeakMap<EditorStore, Map<string, Uint8Array>>()
+/** Each tab's open room, so an upload that ends after its room closed reaches the next one. */
+const openRooms = new WeakMap<EditorStore, { take: (images: Map<string, Uint8Array>) => void }>()
+
+/** Gives the tab's next room the images a closed room was still storing. */
+function handOver(store: EditorStore, images: Iterable<readonly [string, Uint8Array]>) {
+ const pending = handedOver.get(store) ?? new Map<string, Uint8Array>()
+ for (const [name, bytes] of images) pending.set(name, bytes)
+ const room = openRooms.get(store)
+ if (room) room.take(pending)
+ else handedOver.set(store, pending)
+}
+
/** The room's image references by name, beside the `images` map of bytes. */
export type YImageRefs = Y.Map<string>
@@ -83,7 +102,13 @@ export function bindRoomImages({
for (const image of batch) busy.add(image.name)
try {
const refs = await images.store(batch)
- if (disposed) return
+ if (disposed) {
+ handOver(
+ store,
+ batch.map((image) => [image.name, image.bytes] as const)
+ )
+ return
+ }
ydoc.transact(() => {
for (const [name, ref] of refs) {
yrefs.set(name, ref)
@@ -91,6 +116,13 @@ export function bindRoomImages({
}
})
} catch (error) {
+ if (disposed) {
+ handOver(
+ store,
+ batch.map((image) => [image.name, image.bytes] as const)
+ )
+ return
+ }
// The bytes stay in the room, as a peer that cannot store images leaves them.
for (const image of batch) {
if (!yimages.has(image.name) && !yrefs.has(image.name)) {
@@ -171,8 +203,21 @@ export function bindRoomImages({
}
}
+ /** Stores and names the images a closed room was still storing. */
+ function take(pending: Map<string, Uint8Array>) {
+ handedOver.delete(store)
+ for (const [name, bytes] of pending) {
+ if (images.canStore) wantStore(name, bytes)
+ // A room this peer cannot store in carries the bytes, as a guest's images travel.
+ else if (!yrefs.has(name) && !yimages.has(name)) yimages.set(name, bytes)
+ }
+ }
+
yrefs.observe(onRefs)
yimages.observe(onImages)
+ openRooms.set(store, { take })
+ const pending = handedOver.get(store)
+ if (pending) take(pending)
for (const name of yrefs.keys()) wantLoad(name)
for (const [name, bytes] of yimages) wantStore(name, bytes)
@@ -185,6 +230,10 @@ export function bindRoomImages({
hasRef: (name) => yrefs.has(name),
dispose() {
disposed = true
+ if (openRooms.get(store)?.take === take) openRooms.delete(store)
+ // Images queued but not yet sent to the store go to the tab's next room.
+ if (toStore.size > 0) handOver(store, toStore)
+ toStore.clear()
for (const timer of retries) clearTimeout(timer)
retries.clear()
yrefs.unobserve(onRefs)
diff --git a/src/app/collab/node-codec.ts b/src/app/collab/node-codec.ts
index b59028ba5..e6eb79df4 100644
--- a/src/app/collab/node-codec.ts
+++ b/src/app/collab/node-codec.ts
@@ -1,22 +1,25 @@
-import { isEqual } from 'es-toolkit/predicate'
-
-import type {
- Fill,
- FillType,
- GeometryPath,
- SceneNode,
- SourceMetadata
-} from '@open-pencil/scene-graph'
+import { isPlainObject, omit } from 'es-toolkit'
+import * as v from 'valibot'
+
+import type { Fill, GeometryPath, SceneNode, SourceMetadata } from '@open-pencil/scene-graph'
import { copyFills } from '@open-pencil/scene-graph/copy'
import {
deserializeInstanceOverrideState,
serializeInstanceOverrideState
} from '@open-pencil/scene-graph/instances/overrides'
import { createDefaultSourceMetadata } from '@open-pencil/scene-graph/node-defaults'
-import type { Matrix, Vector } from '@open-pencil/scene-graph/primitives'
+import { fillSchema } from '@open-pencil/scene-graph/paints'
+import {
+ matrixSchema,
+ vectorSchema,
+ type Matrix,
+ type Vector
+} from '@open-pencil/scene-graph/primitives'
import { ORDER_KEY_FIELD, PAGE_FIELD, PARENTS_FIELD } from '@/app/collab/shared-tree/fields'
+import { writeRecord, type YFields } from './records'
+
const DERIVED_NODE_FIELDS = new Set<keyof SceneNode>(['textPicture'])
/**
* The layer tree syncs as parent entries, order keys and pages (`src/app/collab/shared-tree/fields.ts`), so a
@@ -29,19 +32,6 @@ const TREE_FIELDS = new Set<string>([
ORDER_KEY_FIELD,
PAGE_FIELD
])
-const FILL_TYPES = new Set<FillType>([
- 'SOLID',
- 'GRADIENT_LINEAR',
- 'GRADIENT_RADIAL',
- 'GRADIENT_ANGULAR',
- 'GRADIENT_DIAMOND',
- 'IMAGE',
- 'VIDEO',
- 'PATTERN',
- 'NOISE',
- 'CUSTOM'
-])
-
type YjsNodeLike = {
entries(): IterableIterator<[string, unknown]>
}
@@ -61,21 +51,22 @@ export function encodeNodeForYjs(node: SceneNode): Record<string, unknown> {
return encoded
}
+/**
+ * The document node's plugin data is shared entry by entry beside the layers
+ * (`src/app/collab/document/sync.ts`), so the document node's own map leaves it out.
+ */
+export const DOCUMENT_NODE_FIELDS: readonly (keyof SceneNode)[] = ['pluginData']
+
export function syncEncodedNodeToYMap(
node: SceneNode,
- ynode: {
- delete(key: string): void
- get(key: string): unknown
- has(key: string): boolean
- set(key: string, value: unknown): void
- }
+ ynode: YFields,
+ omitted: readonly (keyof SceneNode)[] = []
): void {
for (const key of DERIVED_NODE_FIELDS) {
if (ynode.has(key)) ynode.delete(key)
}
- for (const [key, value] of Object.entries(encodeNodeForYjs(node))) {
- if (!isEqual(ynode.get(key), value)) ynode.set(key, value)
- }
+ // The tree's fields live beside the layer's own, so fields the layer lacks are left alone.
+ writeRecord(ynode, omit(encodeNodeForYjs(node), omitted), { drop: false })
}
export function decodeNodeFromYjs(ynode: YjsNodeLike): Partial<SceneNode> {
@@ -98,9 +89,9 @@ export function decodeNodeFromYjs(ynode: YjsNodeLike): Partial<SceneNode> {
export function normalizeSourceMetadata(source: unknown): SourceMetadata {
const defaults = createDefaultSourceMetadata()
- if (!isRecord(source)) return defaults
+ if (!isPlainObject(source)) return defaults
- const fig = isRecord(source.fig) ? source.fig : {}
+ const fig = isPlainObject(source.fig) ? source.fig : {}
return {
format: source.format === 'fig' ? 'fig' : null,
id: stringOrNull(source.id),
@@ -109,8 +100,8 @@ export function normalizeSourceMetadata(source: unknown): SourceMetadata {
fig: {
rawSize: normalizeVector(fig.rawSize),
rawTransform: normalizeMatrix(fig.rawTransform),
- rawNodeFields: isRecord(fig.rawNodeFields) ? structuredClone(fig.rawNodeFields) : {},
- layout: isRecord(fig.layout)
+ rawNodeFields: isPlainObject(fig.rawNodeFields) ? structuredClone(fig.rawNodeFields) : {},
+ layout: isPlainObject(fig.layout)
? (structuredClone(fig.layout) as SourceMetadata['fig']['layout'])
: null,
symbolOverrides: arrayOrEmpty(fig.symbolOverrides),
@@ -126,7 +117,7 @@ function normalizeGeometryPaths(value: unknown): GeometryPath[] {
if (!Array.isArray(value)) return []
const paths: GeometryPath[] = []
for (const item of value) {
- if (!isRecord(item) || !(item.commandsBlob instanceof Uint8Array)) continue
+ if (!isPlainObject(item) || !(item.commandsBlob instanceof Uint8Array)) continue
const path: GeometryPath = {
windingRule: item.windingRule === 'EVENODD' ? 'EVENODD' : 'NONZERO',
commandsBlob: new Uint8Array(item.commandsBlob)
@@ -140,72 +131,17 @@ function normalizeGeometryPaths(value: unknown): GeometryPath[] {
}
function normalizeVector(value: unknown): Vector | null {
- if (!isRecord(value) || !isFiniteNumber(value.x) || !isFiniteNumber(value.y)) return null
- return { x: value.x, y: value.y }
+ const result = v.safeParse(vectorSchema, value)
+ return result.success ? result.output : null
}
function normalizeMatrix(value: unknown): Matrix | null {
- if (!isRecord(value)) return null
- const entries = [value.m00, value.m01, value.m02, value.m10, value.m11, value.m12]
- if (!entries.every((item) => isFiniteNumber(item))) return null
- return {
- m00: value.m00 as number,
- m01: value.m01 as number,
- m02: value.m02 as number,
- m10: value.m10 as number,
- m11: value.m11 as number,
- m12: value.m12 as number
- }
+ const result = v.safeParse(matrixSchema, value)
+ return result.success ? result.output : null
}
function normalizeFills(value: unknown): Fill[] {
- return Array.isArray(value) ? value.filter(isFill) : []
-}
-
-function isFill(value: unknown): value is Fill {
- return (
- isRecord(value) &&
- typeof value.type === 'string' &&
- FILL_TYPES.has(value.type as FillType) &&
- isColor(value.color) &&
- isFiniteNumber(value.opacity) &&
- typeof value.visible === 'boolean' &&
- isOptionalGradientStops(value.gradientStops) &&
- isOptionalMatrix(value.gradientTransform) &&
- isOptionalMatrix(value.imageTransform) &&
- isOptionalVector(value.patternSpacing) &&
- isOptionalVector(value.noiseSize)
- )
-}
-
-function isOptionalGradientStops(value: unknown): boolean {
- return (
- value === undefined ||
- (Array.isArray(value) &&
- value.every((stop) => isRecord(stop) && isFiniteNumber(stop.position) && isColor(stop.color)))
- )
-}
-
-function isOptionalMatrix(value: unknown): boolean {
- return value === undefined || normalizeMatrix(value) !== null
-}
-
-function isOptionalVector(value: unknown): boolean {
- return value === undefined || normalizeVector(value) !== null
-}
-
-function isColor(value: unknown): boolean {
- return (
- isRecord(value) &&
- isFiniteNumber(value.r) &&
- isFiniteNumber(value.g) &&
- isFiniteNumber(value.b) &&
- isFiniteNumber(value.a)
- )
-}
-
-function isFiniteNumber(value: unknown): value is number {
- return typeof value === 'number' && Number.isFinite(value)
+ return Array.isArray(value) ? value.filter((fill): fill is Fill => v.is(fillSchema, fill)) : []
}
function arrayOrEmpty(value: unknown): unknown[] {
@@ -225,7 +161,3 @@ function stringOrNull(value: unknown): string | null {
function numberOrNull(value: unknown): number | null {
return typeof value === 'number' && Number.isFinite(value) ? value : null
}
-
-function isRecord(value: unknown): value is Record<string, unknown> {
- return typeof value === 'object' && value !== null && !Array.isArray(value)
-}
diff --git a/src/app/collab/records.ts b/src/app/collab/records.ts
new file mode 100644
index 000000000..b252eff63
--- /dev/null
+++ b/src/app/collab/records.ts
@@ -0,0 +1,84 @@
+import { isEqual, isPlainObject } from 'es-toolkit'
+import * as Y from 'yjs'
+
+/**
+ * Records in a room by id, as variables and collections are. Each record is a map of its fields,
+ * so peers changing different fields of one record both keep theirs.
+ */
+export type YRecords = Y.Map<Y.Map<unknown>>
+
+/** A room map that holds one record's fields, as a layer's or a variable's does. */
+export type YFields = Pick<Y.Map<unknown>, 'delete' | 'get' | 'has' | 'keys' | 'set'>
+
+type WriteOptions = {
+ /**
+ * Fields that hold a map of their own, keyed by id or mode, written field by field in turn, so
+ * peers changing different entries of one field both keep theirs.
+ */
+ nested?: ReadonlySet<string>
+ /** Whether fields `record` lacks are removed from the room; false leaves them as they are. */
+ drop?: boolean
+}
+
+/**
+ * Writes the fields of `record` that differ from what the room holds, as a peer sends its edit:
+ * a field another peer changed meanwhile keeps that change unless this record changes it too.
+ */
+export function writeRecord(
+ target: YFields,
+ record: object,
+ { nested, drop = true }: WriteOptions = {}
+): void {
+ const fields = new Map<string, unknown>(Object.entries(record))
+ if (drop) {
+ // 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 (nested?.has(key) && isPlainObject(value)) {
+ let entries = target.get(key)
+ if (!(entries instanceof Y.Map)) {
+ entries = new Y.Map<unknown>()
+ target.set(key, entries)
+ }
+ writeRecord(entries as Y.Map<unknown>, value, { drop })
+ continue
+ }
+ if (value === undefined) {
+ if (target.has(key)) 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. */
+export function writeChanges<T extends object>(
+ target: YRecords,
+ records: ReadonlyMap<string, T>,
+ sent: ReadonlyMap<string, T>,
+ options?: Omit<WriteOptions, 'drop'>
+): 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, options)
+ }
+}
+
+/** The ids of records an event batch on `records` added, changed, or removed. */
+export 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
+}
diff --git a/src/app/collab/session.ts b/src/app/collab/session.ts
index 89c5b5f2b..7d665d50e 100644
--- a/src/app/collab/session.ts
+++ b/src/app/collab/session.ts
@@ -8,9 +8,11 @@ import type { Color } from '@open-pencil/scene-graph/primitives'
import { shareAgentPreviews } from '@/app/collab/agent-preview'
import { buildRemotePeers } from '@/app/collab/awareness'
+import { bindDocumentSync, roomDocumentData } from '@/app/collab/document/sync'
import { useCollabIdentity } from '@/app/collab/identity'
import { bindRoomImages, type RoomImageStore } from '@/app/collab/images'
import { publishLocalAgents } from '@/app/collab/local-awareness'
+import type { YRecords } from '@/app/collab/records'
import { connectCollabRoom } from '@/app/collab/room/connection'
import { trackRoomSaves, type RoomSaves } from '@/app/collab/room/saves'
import { deriveRoomStatus, type RoomStatus } from '@/app/collab/room/status'
@@ -24,7 +26,7 @@ import {
import type { JoinCollabRoom } from '@/app/collab/transport'
import type { CollabAction } from '@/app/collab/transport/types'
import type { RemotePeer } from '@/app/collab/types'
-import { bindVariableSync, type YRecords } from '@/app/collab/variables'
+import { bindVariableSync } from '@/app/collab/variables'
import { attachRoomVoice, type RoomVoice } from '@/app/collab/voice/room'
import {
bindCollabGraphEvents,
@@ -145,8 +147,19 @@ export function openRoomSession({
const meta = ydoc.getMap<unknown>('meta')
const yvariables: YRecords = ydoc.getMap('variables')
const ycollections: YRecords = ydoc.getMap('collections')
+ const documentData = roomDocumentData(ydoc)
const persistence = openSavedCopy(roomId, ydoc)
- const saves = trackRoomSaves(ydoc, [ynodes, yimages, yvariables, ycollections])
+ const saves = trackRoomSaves(ydoc, [
+ ynodes,
+ yimages,
+ yvariables,
+ ycollections,
+ documentData.entries,
+ documentData.threads,
+ documentData.libraries,
+ documentData.settings
+ ])
+ const documentSync = bindDocumentSync({ store, ydoc, data: documentData, meta })
const adopt = (apply: () => void) => (holdsDocument ? store.adoptChanges(apply) : apply())
const peers = shallowRef<RemotePeer[]>([])
@@ -203,6 +216,7 @@ export function openRoomSession({
suppressGraphSync = false
}
}
+ if (hasDocument.value) documentSync.follow()
// Newcomers wait for someone who has the file, so peers say whether they do.
if (awareness.getLocalState()?.hasFile !== hasDocument.value) {
awareness.setLocalStateField('hasFile', hasDocument.value)
@@ -303,6 +317,8 @@ export function openRoomSession({
awareness.setLocalStateField('selection', ids)
},
shareDocument() {
+ // Before the root is claimed, which makes the tab follow the room's document data.
+ documentSync.share()
sync.syncAllNodesToYjs()
variableSync.share()
writeRoomName(meta, store.state.documentName)
@@ -320,6 +336,7 @@ export function openRoomSession({
// Unbinding writes an edit still waiting to be sent, so it runs while the room is open.
unbindGraphEvents()
variableSync.dispose()
+ documentSync.dispose()
roomImages?.dispose()
disposed = true
connectionTimer.pause()
diff --git a/src/app/collab/shared-tree/fields.ts b/src/app/collab/shared-tree/fields.ts
index 4a5821e44..ce3b9d1cd 100644
--- a/src/app/collab/shared-tree/fields.ts
+++ b/src/app/collab/shared-tree/fields.ts
@@ -9,9 +9,10 @@ import { randomIndex } from '@open-pencil/scene-graph/random'
* fractional position among siblings, and `page`, the page this peer last placed it on, where it
* goes once no recorded parent is left; `parentId` and `childIds` are derived on each peer
* (`src/app/collab/tree/layer-tree.ts`). The document-wide `meta` map holds the room's root and
- * name, the move clock, and the tree format.
+ * name, the move clock, and the tree format. The document node's plugin data, comments,
+ * libraries, and settings live in their own maps (`src/app/collab/document/sync.ts`).
*/
-export const TREE_FORMAT = 3
+export const TREE_FORMAT = 4
export const PARENTS_FIELD = 'parents'
export const ORDER_KEY_FIELD = 'orderKey'
export const PAGE_FIELD = 'page'
diff --git a/src/app/collab/shared-tree/migration.ts b/src/app/collab/shared-tree/migration.ts
deleted file mode 100644
index 36d9e440f..000000000
--- a/src/app/collab/shared-tree/migration.ts
+++ /dev/null
@@ -1,158 +0,0 @@
-import { orderBy, uniq } from 'es-toolkit'
-import * as v from 'valibot'
-import * as Y from 'yjs'
-
-import { siblingOrderKeys } from '@open-pencil/scene-graph/order-keys'
-
-import { topEdge } from '@/app/collab/tree/entries'
-
-import {
- claimRoot,
- markTreeFormat,
- PARENTS_FIELD,
- readOrderKey,
- readParentEntries,
- readRoot,
- writeOrderKey,
- writePage,
- writeParentEntry,
- writeRootEntries,
- type YMeta,
- type YNodes
-} from './fields'
-
-/** Fields format 1 synced directly and format 2 derives. */
-const LEGACY_TREE_FIELDS = ['parentId', 'childIds'] as const
-const legacyParentSchema = v.nullable(v.string())
-const legacyChildIdsSchema = v.array(v.string())
-
-/** The origin of a migration this peer writes; the change that triggered it applies it. */
-export const TREE_MIGRATION_ORIGIN = Symbol('collab-tree-migration')
-
-export function isLegacyLayer(ynode: Y.Map<unknown>): boolean {
- return !(ynode.get(PARENTS_FIELD) instanceof Y.Map) && ynode.has('parentId')
-}
-
-function legacyParentOf(ynode: Y.Map<unknown>): string | null | undefined {
- const result = v.safeParse(legacyParentSchema, ynode.get('parentId'))
- return result.success ? result.output : undefined
-}
-
-function legacyChildIdsOf(ynode: Y.Map<unknown> | undefined): string[] {
- const result = v.safeParse(legacyChildIdsSchema, ynode?.get('childIds'))
- return result.success ? result.output : []
-}
-
-/**
- * Converts layers a format 1 document recorded to format 2: each layer's synced parent becomes
- * its only entry, with counter 0, and its position in that parent's synced `childIds` becomes an
- * order key, and the page its synced ancestors reach becomes its page; siblings already converted
- * keep theirs. The root with the most children becomes the room's root. The result depends only on the document, so
- * peers that convert the same layers at once write the same values. Returns the converted ids.
- */
-export function migrateLegacyLayers(
- ydoc: Y.Doc,
- ynodes: YNodes,
- meta: YMeta,
- layerIds: Iterable<string>
-): string[] {
- const legacy = uniq(Array.from(layerIds)).filter((id) => {
- const ynode = ynodes.get(id)
- return ynode !== undefined && isLegacyLayer(ynode)
- })
- if (legacy.length === 0) return []
-
- const byParent = new Map<string | null, Set<string>>()
- for (const id of legacy) {
- const parentId = legacyParentOf(ynodes.get(id) ?? new Y.Map())
- if (parentId === undefined) continue
- let siblings = byParent.get(parentId)
- if (!siblings) {
- siblings = new Set()
- byParent.set(parentId, siblings)
- }
- siblings.add(id)
- }
-
- // Pages are found before any layer drops its synced parent.
- const pages = new Map(legacy.map((id) => [id, legacyPageOf(ynodes, id)]))
-
- ydoc.transact(() => {
- for (const [parentId, migrating] of byParent) {
- if (parentId === null) {
- for (const id of migrating) {
- const ynode = ynodes.get(id)
- if (ynode) writeRootEntries(ynode)
- }
- claimLegacyRoot(ynodes, meta, migrating)
- continue
- }
- const listed = legacyChildIdsOf(ynodes.get(parentId)).filter(
- (id) => ynodes.get(id) && (migrating.has(id) || legacyParentOrEntry(ynodes, id, parentId))
- )
- const order = uniq(listed)
- const unlisted = [...migrating].filter((id) => !order.includes(id)).sort()
- order.push(...unlisted)
- const keys = siblingOrderKeys(
- order.map((id) => {
- const ynode = ynodes.get(id)
- return ynode && !migrating.has(id) ? readOrderKey(ynode) : undefined
- })
- )
- order.forEach((id, index) => {
- const ynode = ynodes.get(id)
- if (!ynode || !migrating.has(id)) return
- writeParentEntry(ynode, parentId, 0)
- writeOrderKey(ynode, keys[index])
- const pageId = pages.get(id)
- if (pageId !== undefined) writePage(ynode, pageId)
- })
- }
- for (const id of legacy) {
- const ynode = ynodes.get(id)
- if (!ynode || !(ynode.get(PARENTS_FIELD) instanceof Y.Map)) continue
- for (const field of LEGACY_TREE_FIELDS) if (ynode.has(field)) ynode.delete(field)
- }
- markTreeFormat(meta)
- }, TREE_MIGRATION_ORIGIN)
- return legacy
-}
-
-/** Whether a converted sibling still lists `parentId` among its entries. */
-function legacyParentOrEntry(ynodes: YNodes, id: string, parentId: string): boolean {
- const ynode = ynodes.get(id)
- return ynode !== undefined && readParentEntries(ynode)?.has(parentId) === true
-}
-
-/**
- * The nearest page above a layer, following each ancestor's synced parent, or its newest entry
- * once it has been converted. Undefined for the root and the pages themselves.
- */
-function legacyPageOf(ynodes: YNodes, id: string): string | undefined {
- if (ynodes.get(id)?.get('type') === 'CANVAS') return undefined
- let current = ynodes.get(id)
- for (let steps = 0; current && steps < ynodes.size; steps++) {
- const entries = readParentEntries(current)
- const parentId = entries ? topEdge(entries)?.parentId : legacyParentOf(current)
- if (!parentId) return undefined
- current = ynodes.get(parentId)
- if (current?.get('type') === 'CANVAS') return parentId
- }
- return undefined
-}
-
-/**
- * Claims the room's root for a converted document. Format 1 rooms could hold several parentless
- * layers, such as a joiner's own document; the one with the most children, then the lowest id,
- * is the room's, so every converting peer claims the same one.
- */
-function claimLegacyRoot(ynodes: YNodes, meta: YMeta, roots: ReadonlySet<string>): void {
- if (readRoot(meta) !== undefined) return
- const ranked = orderBy(
- [...roots].map((id) => ({ id, children: legacyChildIdsOf(ynodes.get(id)).length })),
- ['children', 'id'],
- ['desc', 'asc']
- )
- const root = ranked.at(0)
- if (root) claimRoot(meta, root.id)
-}
diff --git a/src/app/collab/variables.ts b/src/app/collab/variables.ts
index 76504eb35..784e82fd7 100644
--- a/src/app/collab/variables.ts
+++ b/src/app/collab/variables.ts
@@ -1,18 +1,16 @@
import { isEqual } from 'es-toolkit/predicate'
-import * as Y from 'yjs'
+import * as v from 'valibot'
+import type * as Y from 'yjs'
import type { Variable, VariableCollection } from '@open-pencil/scene-graph'
+import { variableCollectionSchema, variableSchema } from '@open-pencil/scene-graph/variables'
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>>
+import { changedIds, writeChanges, type YRecords } from './records'
-const VALUES_BY_MODE = 'valuesByMode'
+/** A variable's values are a map of their own by mode. */
+const BY_MODE = new Set(['valuesByMode'])
type VariableSyncOptions = {
store: EditorStore
@@ -21,68 +19,12 @@ type VariableSyncOptions = {
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)
- )
+ return v.is(variableSchema, value)
}
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)
- }
+ return v.is(variableCollectionSchema, value)
}
/** Sets a record in place where it exists, as views may hold it, as undo does. */
@@ -98,20 +40,6 @@ function applyRecord<T extends object>(target: Map<string, T>, id: string, value
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;
@@ -129,7 +57,7 @@ export function bindVariableSync({ store, ydoc, yvariables, ycollections }: Vari
if (isEqual(sentVariables, variables) && isEqual(sentCollections, variableCollections)) return
ydoc.transact(() => {
writeChanges(ycollections, variableCollections, sentCollections)
- writeChanges(yvariables, variables, sentVariables)
+ writeChanges(yvariables, variables, sentVariables, { nested: BY_MODE })
})
sentVariables = structuredClone(variables)
sentCollections = structuredClone(variableCollections)
diff --git a/src/app/collab/yjs-sync.ts b/src/app/collab/yjs-sync.ts
index 835de5478..115429fac 100644
--- a/src/app/collab/yjs-sync.ts
+++ b/src/app/collab/yjs-sync.ts
@@ -1,10 +1,14 @@
-import { isEmptyObject, isEqual, pickBy } from 'es-toolkit'
+import { isEmptyObject, isEqual, omit, pickBy } from 'es-toolkit'
import * as Y from 'yjs'
import type { SceneGraph } from '@open-pencil/scene-graph'
import { siblingOrderKeys } from '@open-pencil/scene-graph/order-keys'
-import { decodeNodeFromYjs, syncEncodedNodeToYMap } from '@/app/collab/node-codec'
+import {
+ decodeNodeFromYjs,
+ DOCUMENT_NODE_FIELDS,
+ syncEncodedNodeToYMap
+} from '@/app/collab/node-codec'
import {
claimRoot,
markTreeFormat,
@@ -15,7 +19,6 @@ import {
writeRootEntries,
type YNodes
} from '@/app/collab/shared-tree/fields'
-import { migrateLegacyLayers, TREE_MIGRATION_ORIGIN } from '@/app/collab/shared-tree/migration'
import {
applySharedTree,
createLocalEdit,
@@ -140,9 +143,8 @@ export function registerYjsObservers({
setSuppressGraphSync,
applyYjsToGraph
}: YjsObserverOptions): () => void {
- function onNodes(events: Y.YEvent<Y.Map<unknown>>[], transaction: Y.Transaction) {
- // A migration this peer wrote was applied by the change that triggered it.
- if (getSuppressYjsEvents() || transaction.origin === TREE_MIGRATION_ORIGIN) return
+ function onNodes(events: Y.YEvent<Y.Map<unknown>>[]) {
+ if (getSuppressYjsEvents()) return
setSuppressGraphSync(true)
try {
applyYjsToGraph(events)
@@ -207,7 +209,7 @@ export function createYjsGraphSync({
ynode = new Y.Map()
ynodes.set(nodeId, ynode)
}
- syncEncodedNodeToYMap(node, ynode)
+ syncEncodedNodeToYMap(node, ynode, nodeId === graph.rootId ? DOCUMENT_NODE_FIELDS : [])
const localYimages = getYimages()
if (!localYimages) return
@@ -318,10 +320,10 @@ export function createYjsGraphSync({
if (typeof nodeId === 'string') changed.add(nodeId)
}
- migrateLegacyLayers(ydoc, ynodes, ydoc.getMap('meta'), changed)
+ const roomRoot = readRoot(ydoc.getMap('meta'))
for (const nodeId of changed) {
const ynode = ynodes.get(nodeId)
- if (ynode) applyYnodeToGraph(store.graph, nodeId, ynode)
+ if (ynode) applyYnodeToGraph(store.graph, nodeId, ynode, roomRoot)
}
const gone = [...deleted].filter((nodeId) => !ynodes.has(nodeId))
// Moves go first, so a layer moved out of a deleted parent survives the deletion.
@@ -331,8 +333,16 @@ export function createYjsGraphSync({
}
/** Applies a layer's own fields; `applySharedTree` places it in the tree afterwards. */
- function applyYnodeToGraph(graph: SceneGraph, nodeId: string, ynode: Y.Map<unknown>) {
- const props = decodeNodeFromYjs(ynode)
+ function applyYnodeToGraph(
+ graph: SceneGraph,
+ nodeId: string,
+ ynode: Y.Map<unknown>,
+ roomRoot: string | undefined
+ ) {
+ const decoded = decodeNodeFromYjs(ynode)
+ // The document node's plugin data arrives entry by entry (`src/app/collab/document/sync.ts`).
+ const props: ReturnType<typeof decodeNodeFromYjs> =
+ nodeId === roomRoot || nodeId === graph.rootId ? omit(decoded, DOCUMENT_NODE_FIELDS) : decoded
const node = graph.getNode(nodeId)
if (node) {
// Only what differs: joining a room replays every layer, and a layer that already reads the
diff --git a/src/app/libraries/service.ts b/src/app/libraries/service.ts
index b3e4e8359..67667a2b5 100644
--- a/src/app/libraries/service.ts
+++ b/src/app/libraries/service.ts
@@ -220,7 +220,7 @@ export class LibraryService implements ComponentCatalog {
let createdRootIds: string[] = []
const applyRevision = () => {
const existingNodeIds = new Set(editor.graph.nodes.keys())
- for (const asset of updatable) materializeLibraryAsset(editor.graph, latest, asset.key)
+ for (const asset of updatable) this.#materializeAsset(editor, latest, asset.key)
createdRootIds = [...editor.graph.getAllNodes()]
.filter((node) => {
if (existingNodeIds.has(node.id)) return false
@@ -239,11 +239,9 @@ export class LibraryService implements ComponentCatalog {
editor.graph.swapInstanceComponent(plan.instanceId, plan.componentId)
reapplyInstanceComponentProperties(editor, plan.instanceId)
}
- editor.graph.enabledLibraries.set(libraryId, {
- libraryId,
- revisionId: update.latestRevisionId,
- enabled: true
- })
+ editor.updateEnabledLibraries((bindings) =>
+ bindings.set(libraryId, { libraryId, revisionId: update.latestRevisionId, enabled: true })
+ )
editor.requestRender()
}
const restorePrevious = () => {
@@ -254,8 +252,10 @@ export class LibraryService implements ComponentCatalog {
for (const rootId of createdRootIds) {
if (editor.graph.getNode(rootId)) editor.graph.deleteNode(rootId)
}
- if (previousBinding) editor.graph.enabledLibraries.set(libraryId, previousBinding)
- else editor.graph.enabledLibraries.delete(libraryId)
+ editor.updateEnabledLibraries((bindings) => {
+ if (previousBinding) bindings.set(libraryId, previousBinding)
+ else bindings.delete(libraryId)
+ })
editor.requestRender()
}
@@ -279,7 +279,7 @@ export class LibraryService implements ComponentCatalog {
const summary = this.#summaries.value.find((item) => item.libraryId === identity.libraryId)
if (!summary || summary.latestRevisionId === identity.revisionId) return
const latest = await this.#getRevision(identity.libraryId, summary.latestRevisionId)
- materializeLibraryAsset(editor.graph, latest, identity.assetKey)
+ this.#materializeAsset(editor, latest, identity.assetKey)
const plans = planOutdatedLibraryInstances(
editor.graph,
latest,
@@ -347,7 +347,7 @@ export class LibraryService implements ComponentCatalog {
const plans: ReturnType<typeof planOutdatedLibraryInstances> = []
for (const group of groups) {
const latest = await this.#getRevision(group.libraryId)
- materializeLibraryAsset(editor.graph, latest, group.assetKey)
+ this.#materializeAsset(editor, latest, group.assetKey)
plans.push(
...planOutdatedLibraryInstances(
editor.graph,
@@ -387,7 +387,7 @@ export class LibraryService implements ComponentCatalog {
label = 'Update library instances'
): Promise<void> {
const latest = await this.#getRevision(libraryId)
- materializeLibraryAsset(editor.graph, latest, assetKey)
+ this.#materializeAsset(editor, latest, assetKey)
const plans = planOutdatedLibraryInstances(
editor.graph,
latest,
@@ -403,7 +403,7 @@ export class LibraryService implements ComponentCatalog {
const summary = this.#summaries.value.find((item) => item.libraryId === libraryId)
if (!summary) return
const latest = await this.#getRevision(libraryId, summary.latestRevisionId)
- materializeLibraryAsset(editor.graph, latest, assetKey)
+ this.#materializeAsset(editor, latest, assetKey)
const plans = planOutdatedLibraryInstances(editor.graph, latest, new Set([assetKey]))
if (plans.length === 0) return
this.#applyPlans(editor, plans, 'Update library asset')
@@ -515,27 +515,42 @@ export class LibraryService implements ComponentCatalog {
async enable(editor: EditorStore, libraryId: string, revisionId?: string): Promise<void> {
const revision = await this.#getRevision(libraryId, revisionId)
- editor.graph.enabledLibraries.set(libraryId, {
- libraryId,
- revisionId: revision.manifest.revisionId,
- enabled: true
- })
+ editor.updateEnabledLibraries((bindings) =>
+ bindings.set(libraryId, {
+ libraryId,
+ revisionId: revision.manifest.revisionId,
+ enabled: true
+ })
+ )
await this.refresh(editor)
}
async disable(editor: EditorStore, libraryId: string): Promise<void> {
- const binding = editor.graph.enabledLibraries.get(libraryId)
- if (binding) editor.graph.enabledLibraries.set(libraryId, { ...binding, enabled: false })
+ editor.updateEnabledLibraries((bindings) => {
+ const binding = bindings.get(libraryId)
+ if (binding) bindings.set(libraryId, { ...binding, enabled: false })
+ })
await this.refresh(editor)
}
async materialize(editor: EditorStore, libraryId: string, revisionId: string, assetKey: string) {
const revision = await this.#getRevision(libraryId, revisionId)
- const result = materializeLibraryAsset(editor.graph, revision, assetKey)
+ const result = this.#materializeAsset(editor, revision, assetKey)
editor.requestRender()
return result
}
+ /** Copies a library asset into the document, which enables its library, and announces that. */
+ #materializeAsset(
+ editor: EditorStore,
+ revision: Parameters<typeof materializeLibraryAsset>[1],
+ assetKey: string
+ ) {
+ return editor.updateEnabledLibraries(() =>
+ materializeLibraryAsset(editor.graph, revision, assetKey)
+ )
+ }
+
#revisionCacheKey(libraryId: string, revisionId: string): string {
return `${libraryId}\u0000${revisionId}`
}
diff --git a/src/components/libraries/useLibraryManager.ts b/src/components/libraries/useLibraryManager.ts
index a69d0c762..98edb000c 100644
--- a/src/components/libraries/useLibraryManager.ts
+++ b/src/components/libraries/useLibraryManager.ts
@@ -1,4 +1,4 @@
-import { computed, ref, watch, type Ref } from 'vue'
+import { computed, onScopeDispose, ref, watch, type Ref } from 'vue'
import type { EditorStore } from '@/app/editor/session'
import { notificationMessages } from '@/app/i18n/notifications'
@@ -129,6 +129,13 @@ export function useLibraryManager(
{ immediate: true }
)
+ // A collaborator's change to the document's libraries shows while the manager is open.
+ onScopeDispose(
+ editor.onEditorEvent('document:libraries-changed', () => {
+ if (open.value) void refresh()
+ })
+ )
+
const source = readLibraryCatalogSource()
if (source === 'storage' && !open.value) void setSource('storage')
diff --git a/src/constants.ts b/src/constants.ts
index d69c83edd..41207bf8f 100644
--- a/src/constants.ts
+++ b/src/constants.ts
@@ -66,7 +66,7 @@ import type { Color } from '@open-pencil/scene-graph/primitives'
* 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/5'
+export const COLLAB_APP_ID = 'openpencil/6'
// 32 base36 characters provide roughly 165 bits of entropy. The room ID is a
// bearer credential and must resist offline enumeration from public signaling topics.
diff --git a/tests/app/cloud/rooms/saver.test.ts b/tests/app/cloud/rooms/saver.test.ts
index 53ba0bf77..aa67dcd74 100644
--- a/tests/app/cloud/rooms/saver.test.ts
+++ b/tests/app/cloud/rooms/saver.test.ts
@@ -2,9 +2,10 @@ import { describe, expect, test } from 'bun:test'
import { electCloudSaver } from '@/app/cloud/rooms/live'
-const editor = { cloud: { kind: 'user', permission: 'edit' } }
-const viewer = { cloud: { kind: 'user', permission: 'view' } }
-const guest = { cloud: { kind: 'guest', permission: 'edit' } }
+// What the relay writes into presence (`stampAwareness`).
+const editor = { cloud: { kind: 'user', id: 'u1', name: 'Ann', permission: 'edit' } }
+const viewer = { cloud: { kind: 'user', id: 'u2', name: 'Ben', permission: 'view' } }
+const guest = { cloud: { kind: 'guest', id: 'g1', name: 'Guest', permission: 'edit' } }
describe('the room saver', () => {
test('is the editor with the lowest presence client, this tab included', () => {
diff --git a/tests/app/collab/document/sync.test.ts b/tests/app/collab/document/sync.test.ts
new file mode 100644
index 000000000..8a246da5e
--- /dev/null
+++ b/tests/app/collab/document/sync.test.ts
@@ -0,0 +1,216 @@
+import { describe, expect, test } from 'bun:test'
+
+import { SceneGraph, type CommentReply, type CommentThread } from '@open-pencil/scene-graph'
+import { readComments, writeComments } from '@open-pencil/scene-graph/comments'
+
+import { openRoomSession, type RoomSession } from '@/app/collab/session'
+import { createEditorStore, type EditorStore } from '@/app/editor/session'
+
+import { expectDefined } from '#tests/helpers/assert'
+import { createMemoryRooms } from '#tests/helpers/collab/memory-transport'
+
+const ROOM = 'dddddddddddddddddddddddddddddddd'
+
+const noSavedCopy = () => ({ whenSynced: Promise.resolve(), destroy: () => undefined })
+
+function thread(id: string, author: string, replies: CommentReply[] = []): CommentThread {
+ return {
+ id,
+ pageId: '0:1',
+ x: 0,
+ y: 0,
+ author,
+ text: `${author} says hi`,
+ createdAt: '2026-10-22T10:00:00.000Z',
+ updatedAt: '2026-10-22T10:00:00.000Z',
+ resolved: false,
+ replies
+ }
+}
+
+function reply(id: string, author: string, minute: number): CommentReply {
+ return { id, author, text: `${author} replies`, createdAt: `2026-10-22T10:0${minute}:00.000Z` }
+}
+
+/** Adds a thread to the document as the comments panel does: on top of what it holds now. */
+function comment(store: EditorStore, next: CommentThread) {
+ writeComments(store.graph, [...readComments(store.graph), next])
+}
+
+function replyTo(store: EditorStore, threadId: string, next: CommentReply) {
+ writeComments(
+ store.graph,
+ readComments(store.graph).map((item) =>
+ item.id === threadId ? { ...item, replies: [...item.replies, next] } : item
+ )
+ )
+}
+
+const threadIds = (store: EditorStore) => readComments(store.graph).map((item) => item.id)
+
+type Room = {
+ host: EditorStore
+ guest: EditorStore
+ hostSession: RoomSession
+ guestSession: RoomSession
+ settle: () => Promise<void>
+}
+
+/**
+ * A host shares a document with one comment thread, and whatever `prepare` adds; a guest joins.
+ */
+async function withRoom(
+ run: (room: Room) => Promise<void>,
+ prepare: (host: EditorStore) => void = () => undefined
+) {
+ const rooms = createMemoryRooms()
+ const sessions: RoomSession[] = []
+ const host = createEditorStore(new SceneGraph())
+ const guest = createEditorStore(new SceneGraph())
+ try {
+ comment(host, thread('t1', 'Ann'))
+ prepare(host)
+ const open = (store: EditorStore, origin: 'shared' | 'joined') => {
+ const session = openRoomSession({
+ roomId: ROOM,
+ store,
+ origin,
+ joinRoom: rooms.join,
+ openSavedCopy: noSavedCopy
+ })
+ sessions.push(session)
+ return session
+ }
+ const hostSession = open(host, 'shared')
+ hostSession.shareDocument()
+ const guestSession = open(guest, 'joined')
+ await rooms.settle()
+ await run({ host, guest, hostSession, guestSession, settle: rooms.settle })
+ } finally {
+ for (const session of sessions) session.dispose()
+ host.preparationController.dispose()
+ guest.preparationController.dispose()
+ }
+}
+
+describe('document data in a room', () => {
+ test('a peer that joins gets the comments the document holds', async () => {
+ await withRoom(async ({ guest }) => {
+ expect(threadIds(guest)).toEqual(['t1'])
+ expect(readComments(guest.graph)[0]?.author).toBe('Ann')
+ })
+ })
+
+ test('people commenting at once all keep their threads', async () => {
+ await withRoom(async ({ host, guest, settle }) => {
+ comment(host, thread('t2', 'Ann'))
+ comment(guest, thread('t3', 'Ben'))
+ await settle()
+ expect(threadIds(host).toSorted()).toEqual(['t1', 't2', 't3'])
+ expect(threadIds(guest).toSorted()).toEqual(['t1', 't2', 't3'])
+ })
+ })
+
+ test('people replying to one thread at once all keep their replies', async () => {
+ await withRoom(async ({ host, guest, settle }) => {
+ replyTo(host, 't1', reply('r1', 'Ann', 1))
+ replyTo(guest, 't1', reply('r2', 'Ben', 2))
+ await settle()
+ for (const store of [host, guest]) {
+ const replies = expectDefined(readComments(store.graph)[0], 'thread').replies
+ expect(replies.map((item) => item.id)).toEqual(['r1', 'r2'])
+ }
+ })
+ })
+
+ test('a file setting changed while someone comments keeps both', async () => {
+ await withRoom(async ({ host, guest, settle }) => {
+ host.setFigCompression('smallest')
+ comment(guest, thread('t2', 'Ben'))
+ await settle()
+ expect(guest.figCompression()).toBe('smallest')
+ expect(threadIds(host).toSorted()).toEqual(['t1', 't2'])
+ })
+ })
+
+ test('libraries and the color space reach the other peer', async () => {
+ await withRoom(async ({ host, guest, settle }) => {
+ guest.updateEnabledLibraries((bindings) =>
+ bindings.set('lib-1', { libraryId: 'lib-1', revisionId: 'rev-1', enabled: true })
+ )
+ host.setDocumentColorSpace('display-p3')
+ await settle()
+ expect(host.graph.enabledLibraries.get('lib-1')?.revisionId).toBe('rev-1')
+ expect(guest.graph.documentColorSpace).toBe('display-p3')
+ })
+ })
+
+ test('a peer that joins takes the libraries and color space without sending its own back', async () => {
+ await withRoom(
+ async ({ host, guest, guestSession }) => {
+ // Taking the room's document is no edit of the guest's own.
+ expect([...guestSession.saves.counts().values()]).toHaveLength(1)
+ for (const store of [host, guest]) {
+ expect(store.graph.enabledLibraries.get('lib-1')?.revisionId).toBe('rev-1')
+ expect(store.graph.documentColorSpace).toBe('display-p3')
+ }
+ },
+ (host) => {
+ host.updateEnabledLibraries((bindings) =>
+ bindings.set('lib-1', { libraryId: 'lib-1', revisionId: 'rev-1', enabled: true })
+ )
+ host.setDocumentColorSpace('display-p3')
+ }
+ )
+ })
+
+ test('a viewer takes peers’ libraries and color space', async () => {
+ await withRoom(async ({ host, guest, settle }) => {
+ guest.setReadOnly(true)
+ host.updateEnabledLibraries((bindings) =>
+ bindings.set('lib-1', { libraryId: 'lib-1', revisionId: 'rev-1', enabled: true })
+ )
+ host.setDocumentColorSpace('display-p3')
+ await settle()
+ expect(guest.graph.enabledLibraries.get('lib-1')?.revisionId).toBe('rev-1')
+ expect(guest.graph.documentColorSpace).toBe('display-p3')
+ })
+ })
+
+ test('a color space change is an edit the room has not saved', async () => {
+ await withRoom(async ({ host, hostSession }) => {
+ hostSession.saves.markSaved(hostSession.saves.counts())
+ expect(hostSession.saves.unsaved()).toBe(false)
+ host.setDocumentColorSpace('display-p3')
+ expect(hostSession.saves.unsaved()).toBe(true)
+ })
+ })
+
+ test("a joining tab's own settings stay out of the room until it shows the room's document", async () => {
+ const rooms = createMemoryRooms()
+ const host = createEditorStore(new SceneGraph())
+ const guest = createEditorStore(new SceneGraph())
+ const open = (store: EditorStore, origin: 'shared' | 'joined') =>
+ openRoomSession({
+ roomId: ROOM,
+ store,
+ origin,
+ joinRoom: rooms.join,
+ openSavedCopy: noSavedCopy
+ })
+ const sessions = [open(host, 'shared')]
+ try {
+ sessions[0]?.shareDocument()
+ sessions.push(open(guest, 'joined'))
+ guest.updateEnabledLibraries((bindings) =>
+ bindings.set('own', { libraryId: 'own', revisionId: 'rev-1', enabled: true })
+ )
+ await rooms.settle()
+ expect(host.graph.enabledLibraries.has('own')).toBe(false)
+ } finally {
+ for (const session of sessions) session.dispose()
+ host.preparationController.dispose()
+ guest.preparationController.dispose()
+ }
+ })
+})
diff --git a/tests/app/collab/images.test.ts b/tests/app/collab/images.test.ts
index 53edc419b..06b6db823 100644
--- a/tests/app/collab/images.test.ts
+++ b/tests/app/collab/images.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, test } from 'bun:test'
+import { noop } from 'es-toolkit'
import * as Y from 'yjs'
import { bindRoomImages, type RoomImageStore } from '@/app/collab/images'
@@ -168,4 +169,83 @@ describe('room images', () => {
await afterRetry()
expect(loads).toBe(1)
})
+
+ describe('a room that closes while storing', () => {
+ /** One tab whose rooms come and go, as a room that starts over does. */
+ function tab() {
+ const editor = asDouble<EditorStore>({
+ graph: { images: new Map<string, Uint8Array>() },
+ requestRender: () => undefined
+ })
+ return (images: RoomImageStore) => {
+ const ydoc = new Y.Doc()
+ const bound = bindRoomImages({
+ ydoc,
+ yimages: ydoc.getMap<Uint8Array>('images'),
+ yrefs: ydoc.getMap<string>('imageRefs'),
+ store: editor,
+ images,
+ report: () => undefined
+ })
+ return { ydoc, bound }
+ }
+ }
+
+ test("stores an image whose upload ended after it closed in the tab's next room", async () => {
+ const images = memoryImageStore()
+ let land: () => void = noop
+ const slow: RoomImageStore = {
+ ...images.store,
+ async store(batch) {
+ await new Promise<void>((resolve) => {
+ land = resolve
+ })
+ return images.store.store(batch)
+ }
+ }
+ const open = tab()
+ const first = open(slow)
+ first.bound.share('a1', photo)
+ await settle()
+ first.bound.dispose()
+ const next = open(images.store)
+ land()
+ await settle()
+ expect(next.ydoc.getMap<string>('imageRefs').get('a1')).toBe('ref:a1')
+ })
+
+ test("stores an image in the next room's own store, as another workspace's would be", async () => {
+ const open = tab()
+ const first = open(memoryImageStore().store)
+ first.bound.share('a1', photo)
+ first.bound.dispose()
+ const other = memoryImageStore()
+ const next = open(other.store)
+ await settle()
+ expect(next.ydoc.getMap<string>('imageRefs').get('a1')).toBe('ref:a1')
+ expect(other.kept.get('ref:a1')).toEqual(photo)
+ })
+
+ test("stores an image it never sent in the tab's next room", async () => {
+ const images = memoryImageStore()
+ const open = tab()
+ const first = open(images.store)
+ first.bound.share('a1', photo)
+ first.bound.dispose()
+ const next = open(images.store)
+ await settle()
+ expect(next.ydoc.getMap<string>('imageRefs').get('a1')).toBe('ref:a1')
+ expect(images.calls.stored).toBe(1)
+ })
+
+ test('leaves the bytes in a next room this peer cannot store in', async () => {
+ const open = tab()
+ const first = open(memoryImageStore().store)
+ first.bound.share('a1', photo)
+ first.bound.dispose()
+ const next = open(memoryImageStore(false).store)
+ await settle()
+ expect(next.ydoc.getMap<Uint8Array>('images').get('a1')).toEqual(photo)
+ })
+ })
})
diff --git a/tests/app/collab/records.test.ts b/tests/app/collab/records.test.ts
new file mode 100644
index 000000000..a47245358
--- /dev/null
+++ b/tests/app/collab/records.test.ts
@@ -0,0 +1,54 @@
+import { describe, expect, test } from 'bun:test'
+
+import * as Y from 'yjs'
+
+import { writeRecord } from '@/app/collab/records'
+
+/** Two peers of one room, each with the record's map, and a way to exchange what they wrote. */
+function peers() {
+ const first = new Y.Doc()
+ const second = new Y.Doc()
+ const exchange = () => {
+ Y.applyUpdate(second, Y.encodeStateAsUpdate(first, Y.encodeStateVector(second)))
+ Y.applyUpdate(first, Y.encodeStateAsUpdate(second, Y.encodeStateVector(first)))
+ }
+ return {
+ first: first.getMap<unknown>('record'),
+ second: second.getMap<unknown>('record'),
+ exchange
+ }
+}
+
+const BY_MODE = new Set(['valuesByMode'])
+
+describe('room records', () => {
+ test('peers changing different fields both keep their change', () => {
+ const { first, second, exchange } = peers()
+ writeRecord(first, { name: 'Brand', hidden: false })
+ exchange()
+ writeRecord(first, { name: 'Primary', hidden: false })
+ writeRecord(second, { name: 'Brand', hidden: true })
+ exchange()
+ expect(first.toJSON()).toEqual({ name: 'Primary', hidden: true })
+ expect(second.toJSON()).toEqual(first.toJSON())
+ })
+
+ test('peers changing different entries of a nested field both keep theirs', () => {
+ const { first, second, exchange } = peers()
+ writeRecord(first, { valuesByMode: { light: 1, dark: 2 } }, { nested: BY_MODE })
+ exchange()
+ writeRecord(first, { valuesByMode: { light: 10, dark: 2 } }, { nested: BY_MODE })
+ writeRecord(second, { valuesByMode: { light: 1, dark: 20 } }, { nested: BY_MODE })
+ exchange()
+ expect(first.toJSON()).toEqual({ valuesByMode: { light: 10, dark: 20 } })
+ })
+
+ test('drops fields the record lacks unless told to leave them', () => {
+ const { first } = peers()
+ writeRecord(first, { name: 'Brand', parents: 'kept by the tree' })
+ writeRecord(first, { name: 'Brand' }, { drop: false })
+ expect(first.toJSON()).toEqual({ name: 'Brand', parents: 'kept by the tree' })
+ writeRecord(first, { name: 'Brand', description: undefined })
+ expect(first.toJSON()).toEqual({ name: 'Brand' })
+ })
+})
diff --git a/tests/app/collab/shared-tree/migration.test.ts b/tests/app/collab/shared-tree/migration.test.ts
deleted file mode 100644
index cf0942e8f..000000000
--- a/tests/app/collab/shared-tree/migration.test.ts
+++ /dev/null
@@ -1,167 +0,0 @@
-import { describe, expect, test } from 'bun:test'
-
-import * as Y from 'yjs'
-
-import { SceneGraph } from '@open-pencil/scene-graph'
-
-import { encodeNodeForYjs } from '@/app/collab/node-codec'
-import {
- claimRoot,
- readOrderKey,
- readPage,
- readParentEntries,
- readRoot,
- TREE_FORMAT
-} from '@/app/collab/shared-tree/fields'
-import { migrateLegacyLayers } from '@/app/collab/shared-tree/migration'
-
-import { expectDefined, getNodeOrThrow } from '#tests/helpers/assert'
-import {
- expectSameLayerTree,
- settleGraphSync,
- type SyncedStores,
- withSyncedStores
-} from '#tests/helpers/collab/synced-stores'
-import { connectYDocs } from '#tests/helpers/yjs'
-
-/** A document as format 1 wrote it: each layer's map holds its parentId and childIds. */
-function legacyDocument(): { update: Uint8Array; graph: SceneGraph; pageId: string } {
- const graph = new SceneGraph()
- const pageId = expectDefined(graph.getPages()[0], 'first page').id
- graph.createNode('FRAME', pageId, { id: 'frame:1' })
- graph.createNode('RECTANGLE', 'frame:1', { id: 'rect:2' })
- graph.createNode('RECTANGLE', 'frame:1', { id: 'rect:1' })
- graph.createNode('RECTANGLE', pageId, { id: 'rect:3' })
- graph.insertChildAt('rect:3', pageId, 0)
-
- const doc = new Y.Doc()
- const ynodes = doc.getMap<Y.Map<unknown>>('nodes')
- doc.transact(() => {
- for (const node of graph.getAllNodes()) {
- const ynode = new Y.Map<unknown>()
- ynodes.set(node.id, ynode)
- for (const [key, value] of Object.entries(encodeNodeForYjs(node))) ynode.set(key, value)
- ynode.set('parentId', node.parentId)
- ynode.set('childIds', [...node.childIds])
- }
- })
- const update = Y.encodeStateAsUpdate(doc)
- doc.destroy()
- return { update, graph, pageId }
-}
-
-function expectMatchesLegacy(graph: SceneGraph, legacy: SceneGraph) {
- for (const node of legacy.getAllNodes()) {
- const synced = getNodeOrThrow(graph, node.id)
- expect(synced.parentId).toBe(node.parentId)
- expect(synced.childIds).toEqual(node.childIds)
- }
-}
-
-function sharedTreeFields(doc: Y.Doc) {
- const fields: Record<string, unknown> = {}
- for (const [id, ynode] of doc.getMap<Y.Map<unknown>>('nodes')) {
- fields[id] = {
- parents: Object.fromEntries(readParentEntries(ynode) ?? []),
- orderKey: readOrderKey(ynode),
- page: readPage(ynode),
- legacy: ynode.has('parentId') || ynode.has('childIds')
- }
- }
- return fields
-}
-
-async function withLegacyRoom(run: (stores: SyncedStores) => void | Promise<void>) {
- await withSyncedStores(run, { connectImmediately: false })
-}
-
-describe('collab tree format migration', () => {
- test('opening a format 1 document converts its tree and keeps it', async () => {
- const legacy = legacyDocument()
- await withLegacyRoom(({ hostStore, hostDoc }) => {
- Y.applyUpdate(hostDoc, legacy.update)
-
- expectMatchesLegacy(hostStore.graph, legacy.graph)
- expect(hostStore.graph.rootId).toBe(legacy.graph.rootId)
- expect(readRoot(hostDoc.getMap('meta'))).toBe(legacy.graph.rootId)
- expect(hostDoc.getMap('meta').get('treeFormat')).toBe(TREE_FORMAT)
- const fields = sharedTreeFields(hostDoc)
- expect(fields['rect:2']).toMatchObject({
- parents: { 'frame:1': 0 },
- page: legacy.pageId,
- legacy: false
- })
- expect(fields['rect:3']).toMatchObject({ page: legacy.pageId })
- expect(fields[legacy.pageId]).toMatchObject({ page: undefined })
- expect(fields[legacy.graph.rootId]).toMatchObject({ parents: {}, legacy: false })
- const first = expectDefined(readOrderKey(getYnode(hostDoc, 'rect:2')), 'first key')
- const second = expectDefined(readOrderKey(getYnode(hostDoc, 'rect:1')), 'second key')
- expect(first < second).toBe(true)
- })
- })
-
- test('two peers converting the same document at once write the same tree', async () => {
- const legacy = legacyDocument()
- await withLegacyRoom(async (stores) => {
- const { hostStore, peerStore, hostDoc, peerDoc } = stores
- Y.applyUpdate(hostDoc, legacy.update)
- Y.applyUpdate(peerDoc, legacy.update)
- expect(sharedTreeFields(peerDoc)).toEqual(sharedTreeFields(hostDoc))
-
- const disconnect = connectYDocs(hostDoc, peerDoc)
- try {
- await settleGraphSync()
- expectSameLayerTree(stores, [legacy.pageId])
- expectMatchesLegacy(hostStore.graph, legacy.graph)
- expectMatchesLegacy(peerStore.graph, legacy.graph)
- } finally {
- disconnect()
- }
- })
- })
-
- test('a converted layer moves like any other', async () => {
- const legacy = legacyDocument()
- await withSyncedStores(
- async (stores) => {
- const { hostStore, peerStore, hostDoc } = stores
- Y.applyUpdate(hostDoc, legacy.update)
- hostStore.graph.reparentNode('rect:3', 'frame:1')
- await settleGraphSync()
- expect(getNodeOrThrow(peerStore.graph, 'rect:3').parentId).toBe('frame:1')
- expectSameLayerTree(stores, [legacy.pageId])
- },
- { bindGraphEvents: true }
- )
- })
-
- test('converting an already converted document writes nothing', async () => {
- const legacy = legacyDocument()
- await withLegacyRoom(({ hostDoc }) => {
- Y.applyUpdate(hostDoc, legacy.update)
- let updates = 0
- const count = () => updates++
- hostDoc.on('update', count)
- const ynodes = hostDoc.getMap<Y.Map<unknown>>('nodes')
- const migrated = migrateLegacyLayers(hostDoc, ynodes, hostDoc.getMap('meta'), ynodes.keys())
- hostDoc.off('update', count)
- expect(migrated).toEqual([])
- expect(updates).toBe(0)
- })
- })
-
- test('converting a room keeps a root already shared into it', () => {
- const legacy = legacyDocument()
- const doc = new Y.Doc()
- const meta = doc.getMap('meta')
- claimRoot(meta, 'shared-root')
- Y.applyUpdate(doc, legacy.update)
- const ynodes = doc.getMap<Y.Map<unknown>>('nodes')
- migrateLegacyLayers(doc, ynodes, meta, ynodes.keys())
- expect(readRoot(meta)).toBe('shared-root')
- })
-})
-
-function getYnode(doc: Y.Doc, id: string): Y.Map<unknown> {
- return expectDefined(doc.getMap<Y.Map<unknown>>('nodes').get(id), `ynode ${id}`)
-}