@textbus/collaborate 5.1.6 → 5.2.0

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.
@@ -0,0 +1,959 @@
1
+ import { Injectable as w, Inject as $, Optional as Y } from "@viewfly/core";
2
+ import { makeError as x, HISTORY_STACK_SIZE as H, ChangeOrigin as q, Slot as m, observe as T, AsyncSlot as R, AsyncComponent as D, Component as N, History as L, Selection as j } from "@textbus/core";
3
+ import { Subject as l, map as K, filter as Z, Subscription as _ } from "@tanbo/stream";
4
+ import { UndoManager as b, Doc as G, createAbsolutePositionFromRelativePosition as P, createRelativePositionFromTypeIndex as O, Map as S, Array as F, Text as v } from "yjs";
5
+ import { HocuspocusProvider as J } from "@hocuspocus/provider";
6
+ import { WebsocketProvider as Q } from "y-websocket";
7
+ var V = Object.getOwnPropertyDescriptor, X = (t, e, s, n) => {
8
+ for (var o = n > 1 ? void 0 : n ? V(e, s) : e, r = t.length - 1, a; r >= 0; r--)
9
+ (a = t[r]) && (o = a(o) || o);
10
+ return o;
11
+ }, I = (t, e) => (s, n) => e(s, n, t);
12
+ class pe {
13
+ }
14
+ const ee = x("CollabHistory");
15
+ let E = class {
16
+ constructor(t, e, s, n, o) {
17
+ this.rootComponentRef = t, this.collaborate = e, this.scheduler = s, this.stackSize = n, this.undoManagerConfig = o, this.onBack = this.backEvent.asObservable(), this.onForward = this.forwardEvent.asObservable(), this.onChange = this.changeEvent.asObservable(), this.onPush = this.pushEvent.asObservable();
18
+ }
19
+ rootComponentRef;
20
+ collaborate;
21
+ scheduler;
22
+ stackSize;
23
+ undoManagerConfig;
24
+ onBack;
25
+ onForward;
26
+ onChange;
27
+ onPush;
28
+ get canBack() {
29
+ return this.manager?.canUndo() || !1;
30
+ }
31
+ get canForward() {
32
+ return this.manager?.canRedo() || !1;
33
+ }
34
+ manager = null;
35
+ historyItems = [];
36
+ index = 0;
37
+ subscriptions = [];
38
+ backEvent = new l();
39
+ forwardEvent = new l();
40
+ changeEvent = new l();
41
+ pushEvent = new l();
42
+ listen() {
43
+ const t = this.collaborate.yDoc.getMap("RootComponent"), e = this.rootComponentRef.component;
44
+ this.collaborate.syncRootComponent(this.collaborate.yDoc, t, e);
45
+ const s = this.undoManagerConfig || {}, n = new b(t, {
46
+ trackedOrigins: /* @__PURE__ */ new Set([this.collaborate.yDoc]),
47
+ captureTransaction(r) {
48
+ return s.captureTransaction ? s.captureTransaction(r) : !0;
49
+ },
50
+ deleteFilter(r) {
51
+ return s.deleteFilter ? s.deleteFilter(r) : !0;
52
+ }
53
+ });
54
+ this.manager = n;
55
+ let o = null;
56
+ this.subscriptions.push(
57
+ this.scheduler.onLocalChangeBefore.subscribe(() => {
58
+ o = this.collaborate.getRelativeCursorLocation();
59
+ }),
60
+ this.collaborate.onAddSubModel.subscribe(() => {
61
+ throw ee("single document does not support submodels.");
62
+ })
63
+ ), n.on("stack-item-added", (r) => {
64
+ r.type === "undo" ? r.origin === n ? this.index++ : (this.historyItems.length = this.index, this.historyItems.push({
65
+ before: o,
66
+ after: this.collaborate.getRelativeCursorLocation()
67
+ }), this.index++) : this.index--, n.undoStack.length > this.stackSize && (this.historyItems.shift(), n.undoStack.shift()), r.origin === this.collaborate.yDoc && this.pushEvent.next(), this.changeEvent.next();
68
+ }), n.on("stack-item-popped", (r) => {
69
+ const a = r.type === "undo" ? this.index : this.index - 1, i = this.historyItems[a] || null, c = r.type === "undo" ? i?.before : i?.after;
70
+ this.collaborate.restoreCursorPosition(c);
71
+ });
72
+ }
73
+ back() {
74
+ this.canBack && (this.manager?.undo(), this.backEvent.next());
75
+ }
76
+ forward() {
77
+ this.canForward && (this.manager?.redo(), this.forwardEvent.next());
78
+ }
79
+ clear() {
80
+ const t = this.historyItems.pop();
81
+ this.historyItems = t ? [t] : [], this.index = t ? 1 : 0, this.manager?.clear(), this.changeEvent.next();
82
+ }
83
+ destroy() {
84
+ this.index = 0, this.historyItems = [], this.subscriptions.forEach((t) => t.unsubscribe()), this.manager && (this.manager.destroy(), this.manager.captureTransaction = () => !0, this.manager.deleteFilter = () => !0, this.manager.trackedOrigins = /* @__PURE__ */ new Set([null])), this.manager = null;
85
+ }
86
+ };
87
+ E = X([
88
+ w(),
89
+ I(3, $(H)),
90
+ I(4, Y())
91
+ ], E);
92
+ var te = Object.getOwnPropertyDescriptor, se = (t, e, s, n) => {
93
+ for (var o = n > 1 ? void 0 : n ? te(e, s) : e, r = t.length - 1, a; r >= 0; r--)
94
+ (a = t[r]) && (o = a(o) || o);
95
+ return o;
96
+ };
97
+ const g = x("Collaborate");
98
+ class ne {
99
+ slotAndYTextMap = /* @__PURE__ */ new WeakMap();
100
+ yTextAndSlotMap = /* @__PURE__ */ new WeakMap();
101
+ set(e, s) {
102
+ e instanceof m ? (this.slotAndYTextMap.set(e, s), this.yTextAndSlotMap.set(s, e)) : (this.slotAndYTextMap.set(s, e), this.yTextAndSlotMap.set(e, s));
103
+ }
104
+ get(e) {
105
+ return e instanceof m ? this.slotAndYTextMap.get(e) || null : this.yTextAndSlotMap.get(e) || null;
106
+ }
107
+ delete(e) {
108
+ if (e instanceof m) {
109
+ const s = this.slotAndYTextMap.get(e);
110
+ this.slotAndYTextMap.delete(e), s && this.yTextAndSlotMap.delete(s);
111
+ } else {
112
+ const s = this.yTextAndSlotMap.get(e);
113
+ this.yTextAndSlotMap.delete(e), s && this.slotAndYTextMap.delete(s);
114
+ }
115
+ }
116
+ }
117
+ let f = class {
118
+ constructor(t, e, s, n) {
119
+ this.scheduler = t, this.registry = e, this.selection = s, this.subModelLoader = n, this.onAddSubModel = this.addSubModelEvent.asObservable();
120
+ }
121
+ scheduler;
122
+ registry;
123
+ selection;
124
+ subModelLoader;
125
+ yDoc = new G();
126
+ slotMap = new ne();
127
+ onAddSubModel;
128
+ subscriptions = [];
129
+ updateFromRemote = !1;
130
+ addSubModelEvent = new l();
131
+ updateRemoteActions = /* @__PURE__ */ new WeakMap();
132
+ noRecord = {};
133
+ syncRootComponent(t, e, s) {
134
+ this.initSyncEvent(t), this.syncComponent(t, e, s);
135
+ }
136
+ syncRootSlot(t, e, s) {
137
+ e.length ? (s.retain(0), s.delete(s.length), s.cleanAttributes(), s.cleanFormats(), this.initLocalSlotBySharedSlot(e, s)) : t.transact(() => {
138
+ this.initSharedSlotByLocalSlot(e, s);
139
+ }), this.initSyncEvent(t), this.syncSlot(e, s);
140
+ }
141
+ getAbstractSelection(t) {
142
+ const e = P(t.anchor.position, t.anchor.doc), s = P(t.focus.position, t.focus.doc);
143
+ if (e && s) {
144
+ const n = this.slotMap.get(s.type), o = this.slotMap.get(e.type);
145
+ if (n && o)
146
+ return {
147
+ anchorSlot: o,
148
+ anchorOffset: e.index,
149
+ focusSlot: n,
150
+ focusOffset: s.index
151
+ };
152
+ }
153
+ return null;
154
+ }
155
+ getRelativeCursorLocation() {
156
+ const { anchorSlot: t, anchorOffset: e, focusSlot: s, focusOffset: n } = this.selection;
157
+ if (t) {
158
+ const o = this.slotMap.get(t);
159
+ if (o) {
160
+ const r = O(o, e);
161
+ if (s) {
162
+ const a = this.slotMap.get(s);
163
+ if (a) {
164
+ const i = O(a, n);
165
+ return {
166
+ focus: {
167
+ doc: a.doc,
168
+ position: i
169
+ },
170
+ anchor: {
171
+ doc: o.doc,
172
+ position: r
173
+ }
174
+ };
175
+ }
176
+ }
177
+ }
178
+ }
179
+ return null;
180
+ }
181
+ restoreCursorPosition(t) {
182
+ if (!t) {
183
+ this.selection.unSelect();
184
+ return;
185
+ }
186
+ const e = this.getAbstractSelection(t);
187
+ e && this.selection.setBaseAndExtent(
188
+ e.anchorSlot,
189
+ e.anchorOffset,
190
+ e.focusSlot,
191
+ e.focusOffset
192
+ );
193
+ }
194
+ initSyncEvent(t) {
195
+ this.subscriptions.push(
196
+ this.scheduler.onDocChanged.pipe(
197
+ K((e) => e.filter((s) => s.from !== q.Remote)),
198
+ Z((e) => e.length)
199
+ ).subscribe(() => {
200
+ const e = [];
201
+ let s = null;
202
+ const n = this.updateRemoteActions.get(t) || [];
203
+ for (const o of n)
204
+ s || (s = {
205
+ record: o.record,
206
+ actions: []
207
+ }, e.push(s)), s.record === o.record ? s.actions.push(o.action) : (s = {
208
+ record: o.record,
209
+ actions: [o.action]
210
+ }, e.push(s));
211
+ this.updateRemoteActions.delete(t);
212
+ for (const o of e)
213
+ t.transact(() => {
214
+ o.actions.forEach((r) => {
215
+ r();
216
+ });
217
+ }, o.record ? t : this.noRecord);
218
+ })
219
+ );
220
+ }
221
+ syncComponent(t, e, s) {
222
+ let n = e.get("state");
223
+ n ? (Object.keys(s.state).forEach((o) => {
224
+ Reflect.deleteProperty(s.state, o);
225
+ }), this.syncSharedMapToLocalMap(n, s.state)) : (n = new S(), this.syncLocalMapToSharedMap(s.state, n), t.transact(() => {
226
+ e.set("state", n);
227
+ }));
228
+ }
229
+ syncSlot(t, e) {
230
+ const s = (o, r) => {
231
+ this.runRemoteUpdate(r, () => {
232
+ e.retain(0), o.keysChanged.forEach((a) => {
233
+ const i = o.keys.get(a);
234
+ if (!i)
235
+ return;
236
+ const c = i.action;
237
+ if (c === "update" || c === "add") {
238
+ const h = this.registry.getAttribute(a);
239
+ h && e.setAttribute(h, t.getAttribute(a));
240
+ } else if (c === "delete") {
241
+ const h = this.registry.getAttribute(a);
242
+ h && e.removeAttribute(h);
243
+ }
244
+ }), o.delta.forEach((a) => {
245
+ if (Reflect.has(a, "retain")) {
246
+ if (a.attributes) {
247
+ const i = C(this.registry, a.attributes);
248
+ i.length && e.retain(a.retain, i);
249
+ }
250
+ e.retain(e.index + a.retain);
251
+ } else if (a.insert) {
252
+ const i = e.index;
253
+ let c = 1;
254
+ if (typeof a.insert == "string")
255
+ c = a.insert.length, e.insert(a.insert, C(this.registry, a.attributes));
256
+ else {
257
+ const h = a.insert, d = this.createLocalComponentBySharedComponent(h);
258
+ e.insert(d);
259
+ }
260
+ this.selection.isSelected && !(r.origin instanceof b) && (e === this.selection.anchorSlot && this.selection.anchorOffset > i && this.selection.setAnchor(e, this.selection.anchorOffset + c), e === this.selection.focusSlot && this.selection.focusOffset > i && this.selection.setFocus(e, this.selection.focusOffset + c));
261
+ } else if (a.delete) {
262
+ const i = e.index;
263
+ e.delete(a.delete), this.selection.isSelected && !(r.origin instanceof b) && (e === this.selection.anchorSlot && this.selection.anchorOffset >= i && this.selection.setAnchor(e, this.selection.startOffset - a.delete), e === this.selection.focusSlot && this.selection.focusOffset >= i && this.selection.setFocus(e, this.selection.focusOffset - a.delete));
264
+ }
265
+ });
266
+ });
267
+ };
268
+ t.observe(s);
269
+ const n = e.onContentChange.subscribe((o) => {
270
+ this.runLocalUpdate(t.doc, !0, () => {
271
+ let r = 0, a = 0;
272
+ for (const i of o)
273
+ if (i.type === "retain") {
274
+ const c = i.formats;
275
+ if (c) {
276
+ const h = Object.keys(c);
277
+ let d = h.length;
278
+ h.forEach((u) => {
279
+ this.registry.getFormatter(u) || (d--, Reflect.deleteProperty(c, u));
280
+ }), d && t.format(r, i.offset, c);
281
+ } else
282
+ r = i.offset;
283
+ } else if (i.type === "contentInsert") {
284
+ const c = t.toDelta(), h = c.length === 1 && c[0].insert === m.emptyPlaceholder;
285
+ if (typeof i.content == "string")
286
+ a = i.content.length, t.insert(r, i.content, i.formats || {});
287
+ else {
288
+ a = 1;
289
+ const d = this.createSharedComponentByLocalComponent(i.ref);
290
+ t.insertEmbed(r, d, i.formats || {});
291
+ }
292
+ h && r === 0 && t.delete(t.length - 1, 1), r += a;
293
+ } else if (i.type === "delete") {
294
+ const c = t.toDelta();
295
+ t.length && t.delete(r, i.count), t.length === 0 && t.insert(0, `
296
+ `, c[0]?.attributes);
297
+ } else i.type === "attrSet" ? t.setAttribute(i.name, i.value) : i.type === "attrDelete" && t.removeAttribute(i.name);
298
+ });
299
+ });
300
+ this.slotMap.set(e, t), e.__changeMarker__.addDetachCallback(() => {
301
+ this.slotMap.delete(e), t.unobserve(s), n.unsubscribe();
302
+ });
303
+ }
304
+ destroy() {
305
+ this.subscriptions.forEach((t) => t.unsubscribe()), this.subscriptions = [];
306
+ }
307
+ syncSharedMapToLocalMap(t, e) {
308
+ t.forEach((s, n) => {
309
+ e[n] = this.createLocalModelBySharedByModel(s);
310
+ }), this.syncObject(t, e);
311
+ }
312
+ createLocalMapBySharedMap(t) {
313
+ const e = T({});
314
+ return this.syncSharedMapToLocalMap(t, e), e;
315
+ }
316
+ createLocalArrayBySharedArray(t) {
317
+ const e = T([]);
318
+ return e.push(...t.map((s) => this.createLocalModelBySharedByModel(s))), this.syncArray(t, e), e;
319
+ }
320
+ syncLocalMapToSharedMap(t, e) {
321
+ Object.entries(t).forEach(([s, n]) => {
322
+ e.set(s, this.createSharedModelByLocalModel(n));
323
+ }), this.syncObject(e, t);
324
+ }
325
+ createSharedMapByLocalMap(t) {
326
+ const e = new S();
327
+ return this.syncLocalMapToSharedMap(t, e), e;
328
+ }
329
+ createSharedArrayByLocalArray(t) {
330
+ const e = new F();
331
+ return t.forEach((s) => {
332
+ e.push([this.createSharedModelByLocalModel(s)]);
333
+ }), this.syncArray(e, t), e;
334
+ }
335
+ createSharedSlotByLocalSlot(t) {
336
+ const e = new v(), s = t instanceof R;
337
+ if (e.setAttribute("schema", [...t.schema]), e.setAttribute("type", s ? "async" : "sync"), s) {
338
+ let r = !1;
339
+ const a = this.createSharedMapByLocalMap(t.metadata);
340
+ return e.setAttribute("metadata", a), this.subModelLoader.createSubModelBySlot(t).then((i) => {
341
+ if (r)
342
+ return;
343
+ const c = i.getText("content"), h = i.getMap("state");
344
+ this.syncLocalMapToSharedMap(t.state, h), this.initSharedSlotByLocalSlot(c, t), this.syncSlot(c, t), this.addSubModelEvent.next({
345
+ yDoc: i,
346
+ yType: c
347
+ }), this.initSyncEvent(i), t.loader.markAsLoaded();
348
+ }), t.__changeMarker__.addDetachCallback(() => {
349
+ r = !0;
350
+ }), e;
351
+ }
352
+ const n = new S();
353
+ this.syncLocalMapToSharedMap(t.state, n), e.setAttribute("state", n);
354
+ const o = new v();
355
+ return this.initSharedSlotByLocalSlot(o, t), e.insertEmbed(0, o), this.syncSlot(o, t), e;
356
+ }
357
+ initSharedSlotByLocalSlot(t, e) {
358
+ let s = 0;
359
+ e.toDelta().forEach((n) => {
360
+ let o = {};
361
+ if (n.formats ? n.formats.forEach((r) => {
362
+ o[r[0].name] = r[1];
363
+ }) : o = null, typeof n.insert == "string")
364
+ t.insert(s, n.insert, o);
365
+ else {
366
+ const r = this.createSharedComponentByLocalComponent(n.insert);
367
+ t.insertEmbed(s, r, o);
368
+ }
369
+ s += n.insert.length;
370
+ }), e.getAttributes().forEach((n) => {
371
+ t.setAttribute(n[0].name, n[1]);
372
+ });
373
+ }
374
+ createLocalSlotBySharedSlot(t) {
375
+ const e = t.getAttribute("type"), s = t.getAttribute("schema");
376
+ if (e === "async") {
377
+ const i = t.getAttribute("metadata"), c = new R(s || [], {}, {});
378
+ this.syncSharedMapToLocalMap(i, c.metadata);
379
+ const h = this.subModelLoader.getLoadedModelBySlot(c);
380
+ if (h) {
381
+ const u = h.getText("content"), M = h.getMap("state");
382
+ return this.syncSharedMapToLocalMap(M, c.state), this.syncRootSlot(h, u, c), this.addSubModelEvent.next({
383
+ yDoc: h,
384
+ yType: u
385
+ }), c.loader.markAsLoaded(), c;
386
+ }
387
+ let d = !1;
388
+ return c.loader.onRequestLoad.toPromise().then(() => this.subModelLoader.loadSubModelBySlot(c)).then((u) => {
389
+ if (d)
390
+ return;
391
+ const M = u.getText("content"), W = u.getMap("state");
392
+ this.syncSharedMapToLocalMap(W, c.state), this.syncRootSlot(u, M, c), this.addSubModelEvent.next({
393
+ yDoc: u,
394
+ yType: M
395
+ }), c.loader.markAsLoaded();
396
+ }), c.__changeMarker__.addDetachCallback(() => {
397
+ d = !0;
398
+ }), c;
399
+ }
400
+ const o = t.toDelta()[0]?.insert;
401
+ if (!(o instanceof v))
402
+ throw g("shared slot content type is not `YText`.");
403
+ const r = new m(s || [], {}), a = t.getAttribute("state");
404
+ return this.syncSharedMapToLocalMap(a, r.state), this.initLocalSlotBySharedSlot(o, r), this.syncSlot(o, r), r;
405
+ }
406
+ initLocalSlotBySharedSlot(t, e) {
407
+ const s = t.toDelta(), n = t.getAttributes();
408
+ Object.keys(n).forEach((o) => {
409
+ const r = this.registry.getAttribute(o);
410
+ r && e.setAttribute(r, n[o]);
411
+ });
412
+ for (const o of s)
413
+ if (o.insert)
414
+ if (typeof o.insert == "string") {
415
+ const r = C(this.registry, o.attributes);
416
+ e.insert(o.insert, r);
417
+ } else {
418
+ const r = o.insert, a = this.createLocalComponentBySharedComponent(r);
419
+ e.insert(a, C(this.registry, o.attributes));
420
+ }
421
+ else
422
+ throw g("unexpected delta action.");
423
+ }
424
+ createSharedModelByLocalModel(t) {
425
+ return t instanceof m ? this.createSharedSlotByLocalSlot(t) : Array.isArray(t) ? this.createSharedArrayByLocalArray(t) : typeof t == "object" && t !== null ? this.createSharedMapByLocalMap(t) : t;
426
+ }
427
+ createLocalModelBySharedByModel(t) {
428
+ return t instanceof S ? this.createLocalMapBySharedMap(t) : t instanceof F ? this.createLocalArrayBySharedArray(t) : t instanceof v ? this.createLocalSlotBySharedSlot(t) : t;
429
+ }
430
+ createSharedComponentByLocalComponent(t) {
431
+ const e = new S();
432
+ if (e.set("name", t.name), t instanceof D) {
433
+ e.set("type", "async");
434
+ const n = this.createSharedMapByLocalMap(t.metadata);
435
+ e.set("metadata", n);
436
+ const o = t.state;
437
+ let r = !1;
438
+ return o.__changeMarker__.addDetachCallback(() => {
439
+ r = !0;
440
+ }), this.subModelLoader.createSubModelByComponent(t).then((a) => {
441
+ if (r)
442
+ return;
443
+ const i = a.getMap("state");
444
+ this.syncComponent(a, i, t), this.addSubModelEvent.next({
445
+ yType: i,
446
+ yDoc: a
447
+ }), this.initSyncEvent(a), t.loader.markAsLoaded();
448
+ }), e;
449
+ }
450
+ const s = this.createSharedMapByLocalMap(t.state);
451
+ return e.set("state", s), e.set("type", "sync"), e;
452
+ }
453
+ createLocalComponentBySharedComponent(t) {
454
+ const e = t.get("name"), s = t.get("type");
455
+ let n;
456
+ if (s === "async") {
457
+ if (n = this.registry.createComponentByData(e, {}, {}), n instanceof D) {
458
+ const o = t.get("metadata");
459
+ this.syncSharedMapToLocalMap(o, n.metadata);
460
+ const r = this.subModelLoader.getLoadedModelByComponent(n);
461
+ if (r) {
462
+ const c = r.getMap("state");
463
+ return this.syncComponent(r, c, n), this.addSubModelEvent.next({
464
+ yType: c,
465
+ yDoc: r
466
+ }), n.loader.markAsLoaded(), n;
467
+ }
468
+ const a = n.state;
469
+ let i = !1;
470
+ n.loader.onRequestLoad.toPromise().then(() => this.subModelLoader.loadSubModelByComponent(n)).then((c) => {
471
+ if (i)
472
+ return;
473
+ const h = c.getMap("state");
474
+ this.syncComponent(c, h, n), this.addSubModelEvent.next({
475
+ yType: h,
476
+ yDoc: c
477
+ }), n.loader.markAsLoaded();
478
+ }), a.__changeMarker__.addDetachCallback(() => {
479
+ i = !0;
480
+ });
481
+ } else if (n instanceof N)
482
+ throw g(`component name \`${e}\` is not a async component.`);
483
+ } else {
484
+ const o = t.get("state"), r = this.createLocalMapBySharedMap(o);
485
+ n = this.registry.createComponentByData(e, r);
486
+ }
487
+ if (n)
488
+ return n;
489
+ throw g(`cannot find component factory \`${e}\`.`);
490
+ }
491
+ /**
492
+ * 双向同步数组
493
+ * @param sharedArray
494
+ * @param localArray
495
+ * @private
496
+ */
497
+ syncArray(t, e) {
498
+ function s(r) {
499
+ console.error(g(`${r} error, length exceeded, path in ${e.__changeMarker__.getPaths().join("/")}`));
500
+ }
501
+ const n = e.__changeMarker__.onSelfChange.subscribe((r) => {
502
+ this.runLocalUpdate(t.doc, !e.__changeMarker__.irrevocableUpdate, () => {
503
+ let a = 0;
504
+ for (const i of r)
505
+ switch (i.type) {
506
+ case "retain":
507
+ a = i.offset;
508
+ break;
509
+ case "insert":
510
+ {
511
+ const c = i.ref;
512
+ if (!Array.isArray(c))
513
+ throw g("The insertion action must have a reference value.");
514
+ const h = c.map((d) => this.createSharedModelByLocalModel(d));
515
+ a <= t.length ? t.insert(a, h) : (t.insert(t.length, h), s("insert"));
516
+ }
517
+ break;
518
+ case "delete":
519
+ if (i.count <= 0)
520
+ break;
521
+ a < t.length ? t.delete(a, i.count) : s("delete");
522
+ break;
523
+ case "setIndex":
524
+ i.index < t.length ? (t.delete(i.index, 1), t.insert(i.index, [this.createSharedModelByLocalModel(i.ref)])) : (t.insert(t.length, [this.createSharedModelByLocalModel(i.ref)]), s("setIndex"));
525
+ break;
526
+ }
527
+ });
528
+ }), o = (r, a) => {
529
+ this.runRemoteUpdate(a, () => {
530
+ let i = 0;
531
+ r.delta.forEach((c) => {
532
+ if (Reflect.has(c, "retain"))
533
+ i += c.retain;
534
+ else if (c.insert) {
535
+ const h = c.insert.map((d) => this.createLocalModelBySharedByModel(d));
536
+ e.splice(i, 0, ...h), i += h.length;
537
+ } else c.delete && e.splice(i, c.delete);
538
+ });
539
+ });
540
+ };
541
+ t.observe(o), e.__changeMarker__.addDetachCallback(() => {
542
+ n.unsubscribe(), t.unobserve(o);
543
+ });
544
+ }
545
+ /**
546
+ * 双向同步对象
547
+ * @param sharedObject
548
+ * @param localObject
549
+ * @private
550
+ */
551
+ syncObject(t, e) {
552
+ const s = (o, r) => {
553
+ this.runRemoteUpdate(r, () => {
554
+ o.changes.keys.forEach((a, i) => {
555
+ if (a.action === "add" || a.action === "update") {
556
+ const c = t.get(i);
557
+ e[i] = this.createLocalModelBySharedByModel(c);
558
+ } else
559
+ Reflect.deleteProperty(e, i);
560
+ });
561
+ });
562
+ };
563
+ t.observe(s);
564
+ const n = e.__changeMarker__.onSelfChange.subscribe((o) => {
565
+ this.runLocalUpdate(t.doc, !e.__changeMarker__.irrevocableUpdate, () => {
566
+ for (const r of o)
567
+ switch (r.type) {
568
+ case "propSet":
569
+ {
570
+ const a = this.createSharedModelByLocalModel(r.ref);
571
+ t.set(r.key, a), t.size === 0 && console.error(g(`prop set error, key is ${r.key}`));
572
+ }
573
+ break;
574
+ case "propDelete":
575
+ t.delete(r.key);
576
+ break;
577
+ }
578
+ });
579
+ });
580
+ e.__changeMarker__.addDetachCallback(function() {
581
+ t.unobserve(s), n.unsubscribe();
582
+ });
583
+ }
584
+ runLocalUpdate(t, e, s) {
585
+ if (this.updateFromRemote || !t)
586
+ return;
587
+ let n = this.updateRemoteActions.get(t);
588
+ n || (n = [], this.updateRemoteActions.set(t, n)), n.push({
589
+ record: e,
590
+ action: s
591
+ });
592
+ }
593
+ runRemoteUpdate(t, e) {
594
+ t.origin !== t.doc && (this.updateFromRemote = !0, t.origin instanceof b ? this.scheduler.historyApplyTransact(e) : this.scheduler.remoteUpdateTransact(e), this.updateFromRemote = !1);
595
+ }
596
+ };
597
+ f = se([
598
+ w()
599
+ ], f);
600
+ function C(t, e) {
601
+ const s = [];
602
+ return e && Object.keys(e).forEach((n) => {
603
+ const o = t.getFormatter(n);
604
+ o && s.push([o, e[n]]);
605
+ }), s;
606
+ }
607
+ class z {
608
+ onSync;
609
+ syncEvent = new l();
610
+ constructor() {
611
+ this.onSync = this.syncEvent.asObservable();
612
+ }
613
+ /**
614
+ * 立即同步消息
615
+ */
616
+ sync() {
617
+ this.syncEvent.next();
618
+ }
619
+ }
620
+ var oe = Object.getOwnPropertyDescriptor, re = (t, e, s, n) => {
621
+ for (var o = n > 1 ? void 0 : n ? oe(e, s) : e, r = t.length - 1, a; r >= 0; r--)
622
+ (a = t[r]) && (o = a(o) || o);
623
+ return o;
624
+ }, U = (t, e) => (s, n) => e(s, n, t);
625
+ let k = class {
626
+ constructor(t, e, s, n, o) {
627
+ this.collaborate = t, this.scheduler = e, this.rootComponentRef = s, this.stackSize = n, this.undoManagerConfig = o, this.onChange = this.changeEvent.asObservable(), this.onBack = this.backEvent.asObservable(), this.onForward = this.forwardEvent.asObservable(), this.onPush = this.pushEvent.asObservable();
628
+ }
629
+ collaborate;
630
+ scheduler;
631
+ rootComponentRef;
632
+ stackSize;
633
+ undoManagerConfig;
634
+ onChange;
635
+ onBack;
636
+ onForward;
637
+ onPush;
638
+ get canBack() {
639
+ return this.actionStack.length > 0 && this.index > 0;
640
+ }
641
+ get canForward() {
642
+ return this.actionStack.length > 0 && this.index < this.actionStack.length;
643
+ }
644
+ isListen = !1;
645
+ changeEvent = new l();
646
+ backEvent = new l();
647
+ forwardEvent = new l();
648
+ pushEvent = new l();
649
+ actionStack = [];
650
+ index = 0;
651
+ stackItem = null;
652
+ timer = null;
653
+ beforePosition = null;
654
+ subscription = new _();
655
+ subDocs = /* @__PURE__ */ new Set();
656
+ listenerCaches = /* @__PURE__ */ new Set();
657
+ listen() {
658
+ this.isListen = !0;
659
+ const t = this.collaborate.yDoc.getMap("RootComponent"), e = this.rootComponentRef.component;
660
+ this.collaborate.syncRootComponent(this.collaborate.yDoc, t, e), this.listenItem(t, this.collaborate.yDoc), this.subscription.add(
661
+ this.collaborate.onAddSubModel.subscribe(({ yType: s, yDoc: n }) => {
662
+ this.subDocs.has(s) || (this.subDocs.add(s), this.isListen && this.listenItem(s, n));
663
+ }),
664
+ this.scheduler.onLocalChangeBefore.subscribe(() => {
665
+ this.beforePosition = this.collaborate.getRelativeCursorLocation();
666
+ })
667
+ );
668
+ }
669
+ forward() {
670
+ if (!this.canForward)
671
+ return;
672
+ clearTimeout(this.timer);
673
+ const t = this.actionStack[this.index];
674
+ if (t) {
675
+ for (const e of t.undoManagers)
676
+ e.redo();
677
+ this.collaborate.restoreCursorPosition(t.after);
678
+ }
679
+ this.index++, this.forwardEvent.next(), this.changeEvent.next();
680
+ }
681
+ back() {
682
+ if (!this.canBack)
683
+ return;
684
+ clearTimeout(this.timer);
685
+ let t;
686
+ this.stackItem ? (t = this.stackItem, this.stackItem = null) : (this.index--, t = this.actionStack[this.index]);
687
+ let e = t.undoManagers.length;
688
+ for (; e > 0; )
689
+ e--, t.undoManagers[e].undo();
690
+ if (t) {
691
+ const s = t.before;
692
+ this.collaborate.restoreCursorPosition(s), this.backEvent.next(), this.changeEvent.next();
693
+ }
694
+ }
695
+ clear() {
696
+ this.actionStack = [], this.stackItem = null, this.index = 0, this.beforePosition = null, clearTimeout(this.timer), this.listenerCaches.forEach((t) => {
697
+ t.clear();
698
+ }), this.changeEvent.next();
699
+ }
700
+ destroy() {
701
+ this.clear(), this.beforePosition = this.stackItem = null, this.subscription.unsubscribe(), this.listenerCaches.forEach((t) => {
702
+ t.destroy();
703
+ }), this.subDocs.clear(), this.listenerCaches.clear();
704
+ }
705
+ listenItem(t, e) {
706
+ const s = this.undoManagerConfig || {}, n = new b(t, {
707
+ trackedOrigins: /* @__PURE__ */ new Set([e]),
708
+ captureTimeout: 0,
709
+ captureTransaction(o) {
710
+ return s.captureTransaction ? s.captureTransaction(o) : !0;
711
+ },
712
+ deleteFilter(o) {
713
+ return s.deleteFilter ? s.deleteFilter(o) : !0;
714
+ }
715
+ });
716
+ n.on("stack-item-added", (o) => {
717
+ o.type === "undo" && !(o.origin instanceof b) && (this.index != this.actionStack.length && (this.actionStack.slice(this.index).forEach((a) => {
718
+ a.undoManagers.forEach((i) => {
719
+ i.clear(!1, !0);
720
+ });
721
+ }), this.actionStack.length = this.index, this.changeEvent.next()), this.stackItem === null && (this.stackItem = {
722
+ before: this.beforePosition,
723
+ after: null,
724
+ undoManagers: []
725
+ }, this.timer = setTimeout(() => {
726
+ this.actionStack.length >= this.stackSize ? this.actionStack.shift() : this.index++, this.stackItem.after = this.beforePosition, this.actionStack.push(this.stackItem), this.stackItem = null, this.pushEvent.next(), this.changeEvent.next();
727
+ }, 500)), this.stackItem.undoManagers.push(n));
728
+ }), this.listenerCaches.add(n);
729
+ }
730
+ };
731
+ k = re([
732
+ w(),
733
+ U(3, $(H)),
734
+ U(4, Y())
735
+ ], k);
736
+ var ae = Object.getOwnPropertyDescriptor, ie = (t, e, s, n) => {
737
+ for (var o = n > 1 ? void 0 : n ? ae(e, s) : e, r = t.length - 1, a; r >= 0; r--)
738
+ (a = t[r]) && (o = a(o) || o);
739
+ return o;
740
+ };
741
+ const y = x("subModelLoaderError");
742
+ class A {
743
+ }
744
+ let B = class extends A {
745
+ createSubModelBySlot() {
746
+ throw y("single document does not support async slot.");
747
+ }
748
+ createSubModelByComponent() {
749
+ throw y("single document does not support async component.");
750
+ }
751
+ loadSubModelByComponent() {
752
+ throw y("single document does not support async component.");
753
+ }
754
+ loadSubModelBySlot() {
755
+ throw y("single document does not support async slot.");
756
+ }
757
+ getLoadedModelBySlot() {
758
+ throw y("single document does not support async slot.");
759
+ }
760
+ getLoadedModelByComponent() {
761
+ throw y("single document does not support async component.");
762
+ }
763
+ };
764
+ B = ie([
765
+ w()
766
+ ], B);
767
+ class p {
768
+ /**
769
+ * 当文档加载完成时触发的观察者
770
+ */
771
+ onLoad;
772
+ /**
773
+ * 当文档 awareness 状态变更时触发的观察者
774
+ */
775
+ onStateChange;
776
+ loadEvent = new l();
777
+ stateChangeEvent = new l();
778
+ constructor() {
779
+ this.onLoad = this.loadEvent.asObservable(), this.onStateChange = this.stateChangeEvent.asObservable();
780
+ }
781
+ }
782
+ class ge extends p {
783
+ provide;
784
+ constructor(e) {
785
+ super(), this.provide = new J({
786
+ ...e,
787
+ onSynced: (s) => {
788
+ e.onSynced?.(s), this.loadEvent.next();
789
+ },
790
+ onAwarenessUpdate: (s) => {
791
+ e.onAwarenessUpdate?.(s);
792
+ const n = s.states.map((o) => ({
793
+ clientId: o.clientId,
794
+ message: o.message
795
+ }));
796
+ this.stateChangeEvent.next(n);
797
+ }
798
+ });
799
+ }
800
+ setLocalStateField(e, s) {
801
+ this.provide.setAwarenessField(e, s);
802
+ }
803
+ onDestroy() {
804
+ this.provide.disconnect(), this.provide.destroy();
805
+ }
806
+ }
807
+ class ye extends p {
808
+ provide;
809
+ onSync = (e) => {
810
+ e && this.loadEvent.next();
811
+ };
812
+ onUpdate = () => {
813
+ const e = [];
814
+ this.provide.awareness.getStates().forEach((s, n) => {
815
+ e.push({
816
+ clientId: n,
817
+ message: s.message
818
+ });
819
+ }), this.stateChangeEvent.next(e);
820
+ };
821
+ constructor(e, s, n) {
822
+ super(), this.onLoad = this.loadEvent.asObservable(), this.onStateChange = this.stateChangeEvent.asObservable(), this.provide = new Q(e, s, n), this.provide.once("sync", this.onSync), this.provide.awareness.on("update", this.onUpdate);
823
+ }
824
+ setLocalStateField(e, s) {
825
+ this.provide.awareness.setLocalStateField(e, s);
826
+ }
827
+ onDestroy() {
828
+ this.provide.awareness.off("update", this.onUpdate), this.provide.disconnect(), this.provide.destroy();
829
+ }
830
+ }
831
+ class me {
832
+ constructor(e) {
833
+ this.config = e;
834
+ }
835
+ config;
836
+ subscription = new _();
837
+ providers = [
838
+ f,
839
+ E,
840
+ {
841
+ provide: L,
842
+ useExisting: E
843
+ },
844
+ {
845
+ provide: p,
846
+ useFactory: (e) => this.config.createConnector(e.yDoc),
847
+ deps: [f]
848
+ },
849
+ {
850
+ provide: A,
851
+ useClass: B
852
+ }
853
+ ];
854
+ timer = null;
855
+ setup(e) {
856
+ const s = e.get(z, null), n = e.get(p), o = e.get(f);
857
+ if (s) {
858
+ const r = e.get(j);
859
+ n.setLocalStateField("message", s.get(e)), this.subscription.add(
860
+ s.onSync.subscribe(() => {
861
+ n.setLocalStateField("message", s.get(e));
862
+ }),
863
+ r.onChange.subscribe(() => {
864
+ n.setLocalStateField("message", s.get(e));
865
+ }),
866
+ n.onStateChange.subscribe((a) => {
867
+ s.consume(a, e);
868
+ })
869
+ );
870
+ }
871
+ return n.onLoad.toPromise().then(() => {
872
+ if (!this.config.onlyLoad)
873
+ return;
874
+ const r = o.yDoc.getMap("RootComponent");
875
+ if (!r.has("state"))
876
+ return new Promise((a) => {
877
+ const i = () => {
878
+ r.has("state") ? a() : this.timer = setTimeout(i, 1e3);
879
+ };
880
+ this.timer = setTimeout(i, 1e3);
881
+ });
882
+ });
883
+ }
884
+ onDestroy(e) {
885
+ this.subscription.unsubscribe(), e.get(f).destroy(), e.get(L).destroy(), e.get(p).onDestroy(), clearTimeout(this.timer);
886
+ }
887
+ }
888
+ class be {
889
+ constructor(e) {
890
+ this.config = e;
891
+ }
892
+ config;
893
+ subscription = new _();
894
+ providers = [
895
+ f,
896
+ k,
897
+ {
898
+ provide: L,
899
+ useExisting: k
900
+ },
901
+ {
902
+ provide: p,
903
+ useFactory: (e) => this.config.createConnector(e.yDoc),
904
+ deps: [f]
905
+ },
906
+ {
907
+ provide: A,
908
+ useFactory: () => this.config.subModelLoader
909
+ }
910
+ ];
911
+ timer = null;
912
+ setup(e) {
913
+ const s = e.get(z, null), n = e.get(p), o = e.get(f);
914
+ if (s) {
915
+ const r = e.get(j);
916
+ n.setLocalStateField("message", s.get(e)), this.subscription.add(
917
+ s.onSync.subscribe(() => {
918
+ n.setLocalStateField("message", s.get(e));
919
+ }),
920
+ r.onChange.subscribe(() => {
921
+ n.setLocalStateField("message", s.get(e));
922
+ }),
923
+ n.onStateChange.subscribe((a) => {
924
+ s.consume(a, e);
925
+ })
926
+ );
927
+ }
928
+ return n.onLoad.toPromise().then(() => {
929
+ if (!this.config.onlyLoad)
930
+ return;
931
+ const r = o.yDoc.getMap("RootComponent");
932
+ if (!r.has("state"))
933
+ return new Promise((a) => {
934
+ const i = () => {
935
+ r.has("state") ? a() : this.timer = setTimeout(i, 1e3);
936
+ };
937
+ this.timer = setTimeout(i, 1e3);
938
+ });
939
+ });
940
+ }
941
+ onDestroy(e) {
942
+ this.subscription.unsubscribe(), e.get(f).destroy(), e.get(L).destroy(), e.get(p).onDestroy(), clearTimeout(this.timer);
943
+ }
944
+ }
945
+ export {
946
+ E as CollabHistory,
947
+ f as Collaborate,
948
+ me as CollaborateModule,
949
+ pe as CustomUndoManagerConfig,
950
+ ge as HocuspocusConnector,
951
+ z as MessageBus,
952
+ k as MultipleDocCollabHistory,
953
+ be as MultipleDocumentCollaborateModule,
954
+ B as NonSubModelLoader,
955
+ A as SubModelLoader,
956
+ p as SyncConnector,
957
+ ye as YWebsocketConnector
958
+ };
959
+ //# sourceMappingURL=index.esm.js.map