mobx-keystone-yjs 1.4.0 → 1.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,96 +1,98 @@
1
- import { Patch } from "mobx-keystone"
2
- import * as Y from "yjs"
3
- import { failure } from "../utils/error"
4
- import { convertJsonToYjsData } from "./convertJsonToYjsData"
5
-
6
- export function applyMobxKeystonePatchToYjsObject(patch: Patch, yjs: unknown): void {
7
- if (patch.path.length > 1) {
8
- const [key, ...rest] = patch.path
9
-
10
- if (yjs instanceof Y.Map) {
11
- const child = yjs.get(String(key))
12
- if (child === undefined) {
13
- throw failure(
14
- `invalid patch path, key "${key}" not found in Yjs map - patch: ${JSON.stringify(patch)}`
15
- )
16
- }
17
- applyMobxKeystonePatchToYjsObject({ ...patch, path: rest }, child)
18
- } else if (yjs instanceof Y.Array) {
19
- const child = yjs.get(Number(key))
20
- if (child === undefined) {
21
- throw failure(
22
- `invalid patch path, key "${key}" not found in Yjs array - patch: ${JSON.stringify(
23
- patch
24
- )}`
25
- )
26
- }
27
- applyMobxKeystonePatchToYjsObject({ ...patch, path: rest }, child)
28
- } else if (yjs instanceof Y.Text) {
29
- // changes to deltaList will be handled by the array observe in the YjsTextModel class
30
- } else {
31
- throw failure(
32
- `invalid patch path, key "${key}" not found in unknown Yjs object - patch: ${JSON.stringify(
33
- patch
34
- )}`
35
- )
36
- }
37
- } else if (patch.path.length === 1) {
38
- if (yjs instanceof Y.Map) {
39
- const key = String(patch.path[0])
40
-
41
- switch (patch.op) {
42
- case "add":
43
- case "replace": {
44
- yjs.set(key, convertJsonToYjsData(patch.value))
45
- break
46
- }
47
- case "remove": {
48
- yjs.delete(key)
49
- break
50
- }
51
- default: {
52
- throw failure(`invalid patch operation for map`)
53
- }
54
- }
55
- } else if (yjs instanceof Y.Array) {
56
- const key = patch.path[0]
57
-
58
- switch (patch.op) {
59
- case "replace": {
60
- if (key === "length") {
61
- if (yjs.length > patch.value) {
62
- const toDelete = yjs.length - patch.value
63
- yjs.delete(patch.value, toDelete)
64
- } else if (yjs.length < patch.value) {
65
- const toInsert = patch.value - yjs.length
66
- yjs.insert(yjs.length, Array(toInsert).fill(undefined))
67
- }
68
- } else {
69
- yjs.delete(Number(key))
70
- yjs.insert(Number(key), [convertJsonToYjsData(patch.value)])
71
- }
72
- break
73
- }
74
- case "add": {
75
- yjs.insert(Number(key), [convertJsonToYjsData(patch.value)])
76
- break
77
- }
78
- case "remove": {
79
- yjs.delete(Number(key))
80
- break
81
- }
82
- default: {
83
- throw failure(`invalid patch operation for array`)
84
- }
85
- }
86
- } else if (yjs instanceof Y.Text) {
87
- // initialization of a YjsTextModel, do nothing
88
- } else {
89
- throw failure(
90
- `invalid patch path, the Yjs object is of an unkown type, so key "${patch.path[0]}" cannot be found in it`
91
- )
92
- }
93
- } else {
94
- throw failure(`invalid patch path, it cannot be empty`)
95
- }
96
- }
1
+ import { Patch } from "mobx-keystone"
2
+ import * as Y from "yjs"
3
+ import { failure } from "../utils/error"
4
+ import { convertJsonToYjsData } from "./convertJsonToYjsData"
5
+ import { JsonValueWithUndefined } from "../jsonTypes"
6
+
7
+ export function applyMobxKeystonePatchToYjsObject(patch: Patch, yjs: unknown): void {
8
+ if (patch.path.length > 1) {
9
+ const [key, ...rest] = patch.path
10
+
11
+ if (yjs instanceof Y.Map) {
12
+ const child = yjs.get(String(key)) as unknown
13
+ if (child === undefined) {
14
+ throw failure(
15
+ `invalid patch path, key "${key}" not found in Yjs map - patch: ${JSON.stringify(patch)}`
16
+ )
17
+ }
18
+ applyMobxKeystonePatchToYjsObject({ ...patch, path: rest }, child)
19
+ } else if (yjs instanceof Y.Array) {
20
+ const child = yjs.get(Number(key)) as unknown
21
+ if (child === undefined) {
22
+ throw failure(
23
+ `invalid patch path, key "${key}" not found in Yjs array - patch: ${JSON.stringify(
24
+ patch
25
+ )}`
26
+ )
27
+ }
28
+ applyMobxKeystonePatchToYjsObject({ ...patch, path: rest }, child)
29
+ } else if (yjs instanceof Y.Text) {
30
+ // changes to deltaList will be handled by the array observe in the YjsTextModel class
31
+ } else {
32
+ throw failure(
33
+ `invalid patch path, key "${key}" not found in unknown Yjs object - patch: ${JSON.stringify(
34
+ patch
35
+ )}`
36
+ )
37
+ }
38
+ } else if (patch.path.length === 1) {
39
+ if (yjs instanceof Y.Map) {
40
+ const key = String(patch.path[0])
41
+
42
+ switch (patch.op) {
43
+ case "add":
44
+ case "replace": {
45
+ yjs.set(key, convertJsonToYjsData(patch.value as JsonValueWithUndefined))
46
+ break
47
+ }
48
+ case "remove": {
49
+ yjs.delete(key)
50
+ break
51
+ }
52
+ default: {
53
+ throw failure(`invalid patch operation for map`)
54
+ }
55
+ }
56
+ } else if (yjs instanceof Y.Array) {
57
+ const key = patch.path[0]
58
+
59
+ switch (patch.op) {
60
+ case "replace": {
61
+ if (key === "length") {
62
+ const newLength = patch.value as number
63
+ if (yjs.length > newLength) {
64
+ const toDelete = yjs.length - newLength
65
+ yjs.delete(newLength, toDelete)
66
+ } else if (yjs.length < patch.value) {
67
+ const toInsert = patch.value - yjs.length
68
+ yjs.insert(yjs.length, Array(toInsert).fill(undefined))
69
+ }
70
+ } else {
71
+ yjs.delete(Number(key))
72
+ yjs.insert(Number(key), [convertJsonToYjsData(patch.value as JsonValueWithUndefined)])
73
+ }
74
+ break
75
+ }
76
+ case "add": {
77
+ yjs.insert(Number(key), [convertJsonToYjsData(patch.value as JsonValueWithUndefined)])
78
+ break
79
+ }
80
+ case "remove": {
81
+ yjs.delete(Number(key))
82
+ break
83
+ }
84
+ default: {
85
+ throw failure(`invalid patch operation for array`)
86
+ }
87
+ }
88
+ } else if (yjs instanceof Y.Text) {
89
+ // initialization of a YjsTextModel, do nothing
90
+ } else {
91
+ throw failure(
92
+ `invalid patch path, the Yjs object is of an unkown type, so key "${String(patch.path[0])}" cannot be found in it`
93
+ )
94
+ }
95
+ } else {
96
+ throw failure(`invalid patch path, it cannot be empty`)
97
+ }
98
+ }
@@ -1,191 +1,192 @@
1
- import { action } from "mobx"
2
- import {
3
- AnyDataModel,
4
- AnyModel,
5
- AnyStandardType,
6
- ModelClass,
7
- Patch,
8
- TypeToData,
9
- applyPatches,
10
- fromSnapshot,
11
- getParentToChildPath,
12
- onGlobalPatches,
13
- onPatches,
14
- onSnapshot,
15
- } from "mobx-keystone"
16
- import * as Y from "yjs"
17
- import { getOrCreateYjsCollectionAtom } from "../utils/getOrCreateYjsCollectionAtom"
18
- import { applyMobxKeystonePatchToYjsObject } from "./applyMobxKeystonePatchToYjsObject"
19
- import { convertYjsDataToJson } from "./convertYjsDataToJson"
20
- import { convertYjsEventToPatches } from "./convertYjsEventToPatches"
21
- import { YjsBindingContext, yjsBindingContext } from "./yjsBindingContext"
22
-
23
- /**
24
- * Creates a bidirectional binding between a Y.js data structure and a mobx-keystone model.
25
- */
26
- export function bindYjsToMobxKeystone<
27
- TType extends AnyStandardType | ModelClass<AnyModel> | ModelClass<AnyDataModel>,
28
- >({
29
- yjsDoc,
30
- yjsObject,
31
- mobxKeystoneType,
32
- }: {
33
- /**
34
- * The Y.js document.
35
- */
36
- yjsDoc: Y.Doc
37
- /**
38
- * The bound Y.js data structure.
39
- */
40
- yjsObject: Y.Map<unknown> | Y.Array<unknown> | Y.Text
41
- /**
42
- * The mobx-keystone model type.
43
- */
44
- mobxKeystoneType: TType
45
- }): {
46
- /**
47
- * The bound mobx-keystone instance.
48
- */
49
- boundObject: TypeToData<TType>
50
- /**
51
- * Disposes the binding.
52
- */
53
- dispose(): void
54
- /**
55
- * The Y.js origin symbol used for binding transactions.
56
- */
57
- yjsOrigin: symbol
58
- } {
59
- const yjsOrigin = Symbol("bindYjsToMobxKeystoneTransactionOrigin")
60
-
61
- let applyingYjsChangesToMobxKeystone = 0
62
-
63
- const bindingContext: YjsBindingContext = {
64
- yjsDoc,
65
- yjsObject,
66
- mobxKeystoneType,
67
- yjsOrigin,
68
- boundObject: undefined, // not yet created
69
-
70
- get isApplyingYjsChangesToMobxKeystone() {
71
- return applyingYjsChangesToMobxKeystone > 0
72
- },
73
- }
74
-
75
- const yjsJson = convertYjsDataToJson(yjsObject)
76
-
77
- const initializationGlobalPatches: { target: object; patches: Patch[] }[] = []
78
-
79
- const createBoundObject = () => {
80
- const disposeOnGlobalPatches = onGlobalPatches((target, patches) => {
81
- initializationGlobalPatches.push({ target, patches })
82
- })
83
-
84
- try {
85
- const boundObject = yjsBindingContext.apply(
86
- () => fromSnapshot(mobxKeystoneType, yjsJson as any),
87
- bindingContext
88
- )
89
- yjsBindingContext.set(boundObject, { ...bindingContext, boundObject })
90
- return boundObject
91
- } finally {
92
- disposeOnGlobalPatches()
93
- }
94
- }
95
-
96
- const boundObject = createBoundObject()
97
-
98
- // bind any changes from yjs to mobx-keystone
99
- const observeDeepCb = action((events: Y.YEvent<any>[]) => {
100
- const patches: Patch[] = []
101
- events.forEach((event) => {
102
- if (event.transaction.origin !== yjsOrigin) {
103
- patches.push(...convertYjsEventToPatches(event))
104
- }
105
-
106
- if (event.target instanceof Y.Map || event.target instanceof Y.Array) {
107
- getOrCreateYjsCollectionAtom(event.target).reportChanged()
108
- }
109
- })
110
-
111
- if (patches.length > 0) {
112
- applyingYjsChangesToMobxKeystone++
113
- try {
114
- applyPatches(boundObject, patches)
115
- } finally {
116
- applyingYjsChangesToMobxKeystone--
117
- }
118
- }
119
- })
120
-
121
- yjsObject.observeDeep(observeDeepCb)
122
-
123
- // bind any changes from mobx-keystone to yjs
124
- let pendingArrayOfArrayOfPatches: Patch[][] = []
125
- const disposeOnPatches = onPatches(boundObject, (patches) => {
126
- if (applyingYjsChangesToMobxKeystone > 0) {
127
- return
128
- }
129
-
130
- pendingArrayOfArrayOfPatches.push(patches)
131
- })
132
-
133
- // this is only used so we can transact all patches to the snapshot boundary
134
- const disposeOnSnapshot = onSnapshot(boundObject, () => {
135
- if (pendingArrayOfArrayOfPatches.length === 0) {
136
- return
137
- }
138
-
139
- const arrayOfArrayOfPatches = pendingArrayOfArrayOfPatches
140
- pendingArrayOfArrayOfPatches = []
141
-
142
- yjsDoc.transact(() => {
143
- arrayOfArrayOfPatches.forEach((arrayOfPatches) => {
144
- arrayOfPatches.forEach((patch) => {
145
- applyMobxKeystonePatchToYjsObject(patch, yjsObject)
146
- })
147
- })
148
- }, yjsOrigin)
149
- })
150
-
151
- // sync initial patches, that might include setting defaults, IDs, etc
152
- yjsDoc.transact(() => {
153
- // we need to skip initializations until we hit the initialization of the bound object
154
- // this is because default objects might be created and initialized before the main object
155
- // but we just need to catch when those are actually assigned to the bound object
156
- let boundObjectFound = false
157
-
158
- initializationGlobalPatches.forEach(({ target, patches }) => {
159
- if (!boundObjectFound) {
160
- if (target !== boundObject) {
161
- return // skip
162
- }
163
- boundObjectFound = true
164
- }
165
-
166
- const parentToChildPath = getParentToChildPath(boundObject, target)
167
- // this is undefined only if target is not a child of boundModel
168
- if (parentToChildPath !== undefined) {
169
- patches.forEach((patch) => {
170
- applyMobxKeystonePatchToYjsObject(
171
- {
172
- ...patch,
173
- path: [...parentToChildPath, ...patch.path],
174
- },
175
- yjsObject
176
- )
177
- })
178
- }
179
- })
180
- }, yjsOrigin)
181
-
182
- return {
183
- boundObject,
184
- dispose: () => {
185
- disposeOnPatches()
186
- disposeOnSnapshot()
187
- yjsObject.unobserveDeep(observeDeepCb)
188
- },
189
- yjsOrigin,
190
- }
191
- }
1
+ import { action } from "mobx"
2
+ import {
3
+ AnyDataModel,
4
+ AnyModel,
5
+ AnyStandardType,
6
+ ModelClass,
7
+ Patch,
8
+ SnapshotInOf,
9
+ TypeToData,
10
+ applyPatches,
11
+ fromSnapshot,
12
+ getParentToChildPath,
13
+ onGlobalPatches,
14
+ onPatches,
15
+ onSnapshot,
16
+ } from "mobx-keystone"
17
+ import * as Y from "yjs"
18
+ import { getYjsCollectionAtom } from "../utils/getOrCreateYjsCollectionAtom"
19
+ import { applyMobxKeystonePatchToYjsObject } from "./applyMobxKeystonePatchToYjsObject"
20
+ import { YjsData, convertYjsDataToJson } from "./convertYjsDataToJson"
21
+ import { convertYjsEventToPatches } from "./convertYjsEventToPatches"
22
+ import { YjsBindingContext, yjsBindingContext } from "./yjsBindingContext"
23
+
24
+ /**
25
+ * Creates a bidirectional binding between a Y.js data structure and a mobx-keystone model.
26
+ */
27
+ export function bindYjsToMobxKeystone<
28
+ TType extends AnyStandardType | ModelClass<AnyModel> | ModelClass<AnyDataModel>,
29
+ >({
30
+ yjsDoc,
31
+ yjsObject,
32
+ mobxKeystoneType,
33
+ }: {
34
+ /**
35
+ * The Y.js document.
36
+ */
37
+ yjsDoc: Y.Doc
38
+ /**
39
+ * The bound Y.js data structure.
40
+ */
41
+ yjsObject: Y.Map<unknown> | Y.Array<unknown> | Y.Text
42
+ /**
43
+ * The mobx-keystone model type.
44
+ */
45
+ mobxKeystoneType: TType
46
+ }): {
47
+ /**
48
+ * The bound mobx-keystone instance.
49
+ */
50
+ boundObject: TypeToData<TType>
51
+ /**
52
+ * Disposes the binding.
53
+ */
54
+ dispose: () => void
55
+ /**
56
+ * The Y.js origin symbol used for binding transactions.
57
+ */
58
+ yjsOrigin: symbol
59
+ } {
60
+ const yjsOrigin = Symbol("bindYjsToMobxKeystoneTransactionOrigin")
61
+
62
+ let applyingYjsChangesToMobxKeystone = 0
63
+
64
+ const bindingContext: YjsBindingContext = {
65
+ yjsDoc,
66
+ yjsObject,
67
+ mobxKeystoneType,
68
+ yjsOrigin,
69
+ boundObject: undefined, // not yet created
70
+
71
+ get isApplyingYjsChangesToMobxKeystone() {
72
+ return applyingYjsChangesToMobxKeystone > 0
73
+ },
74
+ }
75
+
76
+ const yjsJson = convertYjsDataToJson(yjsObject as YjsData)
77
+
78
+ const initializationGlobalPatches: { target: object; patches: Patch[] }[] = []
79
+
80
+ const createBoundObject = () => {
81
+ const disposeOnGlobalPatches = onGlobalPatches((target, patches) => {
82
+ initializationGlobalPatches.push({ target, patches })
83
+ })
84
+
85
+ try {
86
+ const boundObject = yjsBindingContext.apply(
87
+ () => fromSnapshot(mobxKeystoneType, yjsJson as unknown as SnapshotInOf<TypeToData<TType>>),
88
+ bindingContext
89
+ )
90
+ yjsBindingContext.set(boundObject, { ...bindingContext, boundObject })
91
+ return boundObject
92
+ } finally {
93
+ disposeOnGlobalPatches()
94
+ }
95
+ }
96
+
97
+ const boundObject = createBoundObject()
98
+
99
+ // bind any changes from yjs to mobx-keystone
100
+ const observeDeepCb = action((events: Y.YEvent<any>[]) => {
101
+ const patches: Patch[] = []
102
+ events.forEach((event) => {
103
+ if (event.transaction.origin !== yjsOrigin) {
104
+ patches.push(...convertYjsEventToPatches(event))
105
+ }
106
+
107
+ if (event.target instanceof Y.Map || event.target instanceof Y.Array) {
108
+ getYjsCollectionAtom(event.target)?.reportChanged()
109
+ }
110
+ })
111
+
112
+ if (patches.length > 0) {
113
+ applyingYjsChangesToMobxKeystone++
114
+ try {
115
+ applyPatches(boundObject, patches)
116
+ } finally {
117
+ applyingYjsChangesToMobxKeystone--
118
+ }
119
+ }
120
+ })
121
+
122
+ yjsObject.observeDeep(observeDeepCb)
123
+
124
+ // bind any changes from mobx-keystone to yjs
125
+ let pendingArrayOfArrayOfPatches: Patch[][] = []
126
+ const disposeOnPatches = onPatches(boundObject, (patches) => {
127
+ if (applyingYjsChangesToMobxKeystone > 0) {
128
+ return
129
+ }
130
+
131
+ pendingArrayOfArrayOfPatches.push(patches)
132
+ })
133
+
134
+ // this is only used so we can transact all patches to the snapshot boundary
135
+ const disposeOnSnapshot = onSnapshot(boundObject, () => {
136
+ if (pendingArrayOfArrayOfPatches.length === 0) {
137
+ return
138
+ }
139
+
140
+ const arrayOfArrayOfPatches = pendingArrayOfArrayOfPatches
141
+ pendingArrayOfArrayOfPatches = []
142
+
143
+ yjsDoc.transact(() => {
144
+ arrayOfArrayOfPatches.forEach((arrayOfPatches) => {
145
+ arrayOfPatches.forEach((patch) => {
146
+ applyMobxKeystonePatchToYjsObject(patch, yjsObject)
147
+ })
148
+ })
149
+ }, yjsOrigin)
150
+ })
151
+
152
+ // sync initial patches, that might include setting defaults, IDs, etc
153
+ yjsDoc.transact(() => {
154
+ // we need to skip initializations until we hit the initialization of the bound object
155
+ // this is because default objects might be created and initialized before the main object
156
+ // but we just need to catch when those are actually assigned to the bound object
157
+ let boundObjectFound = false
158
+
159
+ initializationGlobalPatches.forEach(({ target, patches }) => {
160
+ if (!boundObjectFound) {
161
+ if (target !== boundObject) {
162
+ return // skip
163
+ }
164
+ boundObjectFound = true
165
+ }
166
+
167
+ const parentToChildPath = getParentToChildPath(boundObject, target)
168
+ // this is undefined only if target is not a child of boundModel
169
+ if (parentToChildPath !== undefined) {
170
+ patches.forEach((patch) => {
171
+ applyMobxKeystonePatchToYjsObject(
172
+ {
173
+ ...patch,
174
+ path: [...parentToChildPath, ...patch.path],
175
+ },
176
+ yjsObject
177
+ )
178
+ })
179
+ }
180
+ })
181
+ }, yjsOrigin)
182
+
183
+ return {
184
+ boundObject,
185
+ dispose: () => {
186
+ disposeOnPatches()
187
+ disposeOnSnapshot()
188
+ yjsObject.unobserveDeep(observeDeepCb)
189
+ },
190
+ yjsOrigin,
191
+ }
192
+ }