@textbus/collaborate 2.5.2 → 2.5.3

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,1006 @@
1
+ 'use strict';
2
+
3
+ var core = require('@textbus/core');
4
+ var di = require('@tanbo/di');
5
+ var stream = require('@tanbo/stream');
6
+ var yjs = require('yjs');
7
+ var browser = require('@textbus/browser');
8
+
9
+ /*! *****************************************************************************
10
+ Copyright (c) Microsoft Corporation.
11
+
12
+ Permission to use, copy, modify, and/or distribute this software for any
13
+ purpose with or without fee is hereby granted.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
16
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
17
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
18
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
19
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
20
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
21
+ PERFORMANCE OF THIS SOFTWARE.
22
+ ***************************************************************************** */
23
+
24
+ function __decorate(decorators, target, key, desc) {
25
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
26
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
27
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
28
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
29
+ }
30
+
31
+ function __param(paramIndex, decorator) {
32
+ return function (target, key) { decorator(target, key, paramIndex); }
33
+ }
34
+
35
+ function __metadata(metadataKey, metadataValue) {
36
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
37
+ }
38
+
39
+ class CollaborateSelectionAwarenessDelegate {
40
+ }
41
+ exports.CollaborateCursor = class CollaborateCursor {
42
+ constructor(container, awarenessDelegate, nativeSelection, scheduler, selection) {
43
+ this.container = container;
44
+ this.awarenessDelegate = awarenessDelegate;
45
+ this.nativeSelection = nativeSelection;
46
+ this.scheduler = scheduler;
47
+ this.selection = selection;
48
+ this.host = browser.createElement('div', {
49
+ styles: {
50
+ position: 'absolute',
51
+ left: 0,
52
+ top: 0,
53
+ width: '100%',
54
+ height: '100%',
55
+ pointerEvents: 'none',
56
+ zIndex: 1
57
+ }
58
+ });
59
+ this.canvasContainer = browser.createElement('div', {
60
+ styles: {
61
+ position: 'absolute',
62
+ left: 0,
63
+ top: 0,
64
+ width: '100%',
65
+ height: '100%',
66
+ overflow: 'hidden'
67
+ }
68
+ });
69
+ this.canvas = browser.createElement('canvas', {
70
+ styles: {
71
+ position: 'absolute',
72
+ opacity: 0.5,
73
+ left: 0,
74
+ top: 0,
75
+ width: '100%',
76
+ height: document.documentElement.clientHeight + 'px',
77
+ pointerEvents: 'none',
78
+ }
79
+ });
80
+ this.context = this.canvas.getContext('2d');
81
+ this.tooltips = browser.createElement('div', {
82
+ styles: {
83
+ position: 'absolute',
84
+ left: 0,
85
+ top: 0,
86
+ width: '100%',
87
+ height: '100%',
88
+ pointerEvents: 'none',
89
+ fontSize: '12px',
90
+ zIndex: 10
91
+ }
92
+ });
93
+ this.onRectsChange = new stream.Subject();
94
+ this.subscription = new stream.Subscription();
95
+ this.currentSelection = [];
96
+ this.canvasContainer.append(this.canvas);
97
+ this.host.append(this.canvasContainer, this.tooltips);
98
+ container.prepend(this.host);
99
+ this.subscription.add(this.onRectsChange.subscribe(rects => {
100
+ for (const rect of rects) {
101
+ this.context.fillStyle = rect.color;
102
+ this.context.beginPath();
103
+ this.context.rect(rect.left, rect.top, rect.width, rect.height);
104
+ this.context.fill();
105
+ this.context.closePath();
106
+ }
107
+ }), stream.fromEvent(window, 'resize').subscribe(() => {
108
+ this.canvas.style.height = document.documentElement.clientHeight + 'px';
109
+ this.refresh();
110
+ }), this.scheduler.onDocChanged.subscribe(() => {
111
+ this.refresh();
112
+ }));
113
+ }
114
+ refresh() {
115
+ this.draw(this.currentSelection);
116
+ }
117
+ destroy() {
118
+ this.subscription.unsubscribe();
119
+ }
120
+ draw(paths) {
121
+ this.currentSelection = paths;
122
+ const containerRect = this.container.getBoundingClientRect();
123
+ this.canvas.style.top = containerRect.top * -1 + 'px';
124
+ this.canvas.width = this.canvas.offsetWidth;
125
+ this.canvas.height = this.canvas.offsetHeight;
126
+ this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
127
+ const users = [];
128
+ paths.filter(i => {
129
+ return i.paths.anchor.length && i.paths.focus.length;
130
+ }).forEach(item => {
131
+ const anchorPaths = [...item.paths.anchor];
132
+ const focusPaths = [...item.paths.focus];
133
+ const anchorOffset = anchorPaths.pop();
134
+ const anchorSlot = this.selection.findSlotByPaths(anchorPaths);
135
+ const focusOffset = focusPaths.pop();
136
+ const focusSlot = this.selection.findSlotByPaths(focusPaths);
137
+ if (!anchorSlot || !focusSlot) {
138
+ return;
139
+ }
140
+ const { focus, anchor } = this.nativeSelection.getPositionByRange({
141
+ focusOffset,
142
+ anchorOffset,
143
+ focusSlot,
144
+ anchorSlot
145
+ });
146
+ if (!focus || !anchor) {
147
+ return;
148
+ }
149
+ const nativeRange = document.createRange();
150
+ nativeRange.setStart(anchor.node, anchor.offset);
151
+ nativeRange.setEnd(focus.node, focus.offset);
152
+ if ((anchor.node !== focus.node || anchor.offset !== focus.offset) && nativeRange.collapsed) {
153
+ nativeRange.setStart(focus.node, focus.offset);
154
+ nativeRange.setEnd(anchor.node, anchor.offset);
155
+ }
156
+ let rects = false;
157
+ if (this.awarenessDelegate) {
158
+ rects = this.awarenessDelegate.getRects({
159
+ focusOffset,
160
+ anchorOffset,
161
+ focusSlot,
162
+ anchorSlot
163
+ }, nativeRange);
164
+ }
165
+ if (!rects) {
166
+ rects = nativeRange.getClientRects();
167
+ }
168
+ const selectionRects = [];
169
+ for (let i = rects.length - 1; i >= 0; i--) {
170
+ const rect = rects[i];
171
+ selectionRects.push({
172
+ id: item.id,
173
+ color: item.color,
174
+ username: item.username,
175
+ left: rect.left - containerRect.left,
176
+ top: rect.top,
177
+ width: rect.width,
178
+ height: rect.height,
179
+ });
180
+ }
181
+ this.onRectsChange.next(selectionRects);
182
+ const cursorRange = nativeRange.cloneRange();
183
+ cursorRange.setStart(focus.node, focus.offset);
184
+ cursorRange.collapse(true);
185
+ const cursorRect = browser.getLayoutRectByRange(cursorRange);
186
+ const rect = {
187
+ id: item.id,
188
+ username: item.username,
189
+ color: item.color,
190
+ left: cursorRect.left - containerRect.left,
191
+ top: cursorRect.top - containerRect.top,
192
+ width: 2,
193
+ height: cursorRect.height
194
+ };
195
+ if (rect.left < 0 || rect.top < 0 || rect.left > containerRect.width) {
196
+ return;
197
+ }
198
+ users.push(rect);
199
+ });
200
+ this.drawUserCursor(users);
201
+ }
202
+ drawUserCursor(rects) {
203
+ for (let i = 0; i < rects.length; i++) {
204
+ const rect = rects[i];
205
+ const { cursor, userTip, anchor } = this.getUserCursor(i);
206
+ Object.assign(cursor.style, {
207
+ left: rect.left + 'px',
208
+ top: rect.top + 'px',
209
+ width: rect.width + 'px',
210
+ height: rect.height + 'px',
211
+ background: rect.color,
212
+ display: 'block'
213
+ });
214
+ anchor.style.background = rect.color;
215
+ userTip.innerText = rect.username;
216
+ userTip.style.background = rect.color;
217
+ }
218
+ for (let i = rects.length; i < this.tooltips.children.length; i++) {
219
+ this.tooltips.removeChild(this.tooltips.children[i]);
220
+ }
221
+ }
222
+ getUserCursor(index) {
223
+ let child = this.tooltips.children[index];
224
+ if (child) {
225
+ const anchor = child.children[0];
226
+ return {
227
+ cursor: child,
228
+ anchor,
229
+ userTip: anchor.children[0]
230
+ };
231
+ }
232
+ const userTip = browser.createElement('span', {
233
+ styles: {
234
+ position: 'absolute',
235
+ display: 'none',
236
+ left: '50%',
237
+ transform: 'translateX(-50%)',
238
+ marginBottom: '2px',
239
+ bottom: '100%',
240
+ whiteSpace: 'nowrap',
241
+ color: '#fff',
242
+ boxShadow: '0 1px 2px rgba(0,0,0,.1)',
243
+ borderRadius: '3px',
244
+ padding: '3px 5px',
245
+ pointerEvents: 'none',
246
+ }
247
+ });
248
+ const anchor = browser.createElement('span', {
249
+ styles: {
250
+ position: 'absolute',
251
+ top: '-2px',
252
+ left: '-2px',
253
+ width: '6px',
254
+ height: '6px',
255
+ pointerEvents: 'auto',
256
+ pointer: 'cursor',
257
+ },
258
+ children: [userTip],
259
+ on: {
260
+ mouseenter() {
261
+ userTip.style.display = 'block';
262
+ },
263
+ mouseleave() {
264
+ userTip.style.display = 'none';
265
+ }
266
+ }
267
+ });
268
+ child = browser.createElement('span', {
269
+ styles: {
270
+ position: 'absolute',
271
+ },
272
+ children: [
273
+ anchor
274
+ ]
275
+ });
276
+ this.tooltips.append(child);
277
+ return {
278
+ cursor: child,
279
+ anchor,
280
+ userTip
281
+ };
282
+ }
283
+ };
284
+ exports.CollaborateCursor = __decorate([
285
+ di.Injectable(),
286
+ __param(0, di.Inject(browser.VIEW_CONTAINER)),
287
+ __param(1, di.Optional()),
288
+ __metadata("design:paramtypes", [HTMLElement,
289
+ CollaborateSelectionAwarenessDelegate,
290
+ browser.SelectionBridge,
291
+ core.Scheduler,
292
+ core.Selection])
293
+ ], exports.CollaborateCursor);
294
+
295
+ function createUnknownComponent(factoryName, canInsertInlineComponent) {
296
+ const unknownComponent = core.defineComponent({
297
+ type: canInsertInlineComponent ? core.ContentType.InlineComponent : core.ContentType.BlockComponent,
298
+ name: 'UnknownComponent',
299
+ setup() {
300
+ console.error(`cannot find component factory \`${factoryName}\`.`);
301
+ return {
302
+ render() {
303
+ return core.VElement.createElement('textbus-unknown-component', {
304
+ style: {
305
+ display: canInsertInlineComponent ? 'inline' : 'block',
306
+ color: '#f00'
307
+ }
308
+ }, unknownComponent.name);
309
+ }
310
+ };
311
+ }
312
+ });
313
+ return unknownComponent;
314
+ }
315
+
316
+ const collaborateErrorFn = core.makeError('Collaborate');
317
+ class ContentMap {
318
+ constructor() {
319
+ this.slotAndYTextMap = new WeakMap();
320
+ this.yTextAndSLotMap = new WeakMap();
321
+ }
322
+ set(key, value) {
323
+ if (key instanceof core.Slot) {
324
+ this.slotAndYTextMap.set(key, value);
325
+ this.yTextAndSLotMap.set(value, key);
326
+ }
327
+ else {
328
+ this.slotAndYTextMap.set(value, key);
329
+ this.yTextAndSLotMap.set(key, value);
330
+ }
331
+ }
332
+ get(key) {
333
+ if (key instanceof core.Slot) {
334
+ return this.slotAndYTextMap.get(key) || null;
335
+ }
336
+ return this.yTextAndSLotMap.get(key) || null;
337
+ }
338
+ delete(key) {
339
+ if (key instanceof core.Slot) {
340
+ const v = this.slotAndYTextMap.get(key);
341
+ this.slotAndYTextMap.delete(key);
342
+ if (v) {
343
+ this.yTextAndSLotMap.delete(v);
344
+ }
345
+ }
346
+ else {
347
+ const v = this.yTextAndSLotMap.get(key);
348
+ this.yTextAndSLotMap.delete(key);
349
+ if (v) {
350
+ this.slotAndYTextMap.delete(v);
351
+ }
352
+ }
353
+ }
354
+ }
355
+ exports.Collaborate = class Collaborate {
356
+ constructor(stackSize, rootComponentRef, collaborateCursor, controller, scheduler, translator, registry, selection, starter) {
357
+ this.stackSize = stackSize;
358
+ this.rootComponentRef = rootComponentRef;
359
+ this.collaborateCursor = collaborateCursor;
360
+ this.controller = controller;
361
+ this.scheduler = scheduler;
362
+ this.translator = translator;
363
+ this.registry = registry;
364
+ this.selection = selection;
365
+ this.starter = starter;
366
+ this.yDoc = new yjs.Doc();
367
+ this.backEvent = new stream.Subject();
368
+ this.forwardEvent = new stream.Subject();
369
+ this.changeEvent = new stream.Subject();
370
+ this.pushEvent = new stream.Subject();
371
+ this.manager = null;
372
+ this.subscriptions = [];
373
+ this.updateFromRemote = false;
374
+ this.contentSyncCaches = new WeakMap();
375
+ this.slotStateSyncCaches = new WeakMap();
376
+ this.slotsSyncCaches = new WeakMap();
377
+ this.componentStateSyncCaches = new WeakMap();
378
+ this.selectionChangeEvent = new stream.Subject();
379
+ this.contentMap = new ContentMap();
380
+ this.updateRemoteActions = [];
381
+ this.noRecord = {};
382
+ this.onSelectionChange = this.selectionChangeEvent.asObservable().pipe(stream.delay());
383
+ this.onBack = this.backEvent.asObservable();
384
+ this.onForward = this.forwardEvent.asObservable();
385
+ this.onChange = this.changeEvent.asObservable();
386
+ this.onPush = this.pushEvent.asObservable();
387
+ }
388
+ get canBack() {
389
+ var _a;
390
+ return ((_a = this.manager) === null || _a === void 0 ? void 0 : _a.canUndo()) || false;
391
+ }
392
+ get canForward() {
393
+ var _a;
394
+ return ((_a = this.manager) === null || _a === void 0 ? void 0 : _a.canRedo()) || false;
395
+ }
396
+ listen() {
397
+ const root = this.yDoc.getMap('RootComponent');
398
+ const rootComponent = this.rootComponentRef.component;
399
+ this.manager = new yjs.UndoManager(root, {
400
+ trackedOrigins: new Set([this.yDoc])
401
+ });
402
+ const cursorKey = 'cursor-position';
403
+ this.manager.on('stack-item-added', event => {
404
+ event.stackItem.meta.set(cursorKey, this.getRelativeCursorLocation());
405
+ if (this.manager.undoStack.length > this.stackSize) {
406
+ this.manager.undoStack.shift();
407
+ }
408
+ if (event.origin === this.yDoc) {
409
+ this.pushEvent.next();
410
+ }
411
+ this.changeEvent.next();
412
+ });
413
+ this.manager.on('stack-item-popped', event => {
414
+ const position = event.stackItem.meta.get(cursorKey);
415
+ if (position) {
416
+ this.restoreCursorLocation(position);
417
+ }
418
+ });
419
+ this.subscriptions.push(this.selection.onChange.subscribe(() => {
420
+ const paths = this.selection.getPaths();
421
+ this.selectionChangeEvent.next(paths);
422
+ }), this.scheduler.onDocChanged.pipe(stream.map(item => {
423
+ return item.filter(i => {
424
+ return i.from !== core.ChangeOrigin.Remote;
425
+ });
426
+ }), stream.filter(item => {
427
+ return item.length;
428
+ })).subscribe(() => {
429
+ const updates = [];
430
+ let update = null;
431
+ for (const item of this.updateRemoteActions) {
432
+ if (!update) {
433
+ update = {
434
+ record: item.record,
435
+ actions: []
436
+ };
437
+ updates.push(update);
438
+ }
439
+ if (update.record === item.record) {
440
+ update.actions.push(item.action);
441
+ }
442
+ else {
443
+ update = {
444
+ record: item.record,
445
+ actions: [item.action]
446
+ };
447
+ updates.push(update);
448
+ }
449
+ }
450
+ this.updateRemoteActions = [];
451
+ for (const item of updates) {
452
+ this.yDoc.transact(() => {
453
+ item.actions.forEach(fn => {
454
+ fn();
455
+ });
456
+ }, item.record ? this.yDoc : this.noRecord);
457
+ }
458
+ }));
459
+ this.syncRootComponent(root, rootComponent);
460
+ }
461
+ updateRemoteSelection(paths) {
462
+ this.collaborateCursor.draw(paths);
463
+ }
464
+ back() {
465
+ var _a;
466
+ if (this.canBack) {
467
+ (_a = this.manager) === null || _a === void 0 ? void 0 : _a.undo();
468
+ this.backEvent.next();
469
+ }
470
+ }
471
+ forward() {
472
+ var _a;
473
+ if (this.canForward) {
474
+ (_a = this.manager) === null || _a === void 0 ? void 0 : _a.redo();
475
+ this.forwardEvent.next();
476
+ }
477
+ }
478
+ clear() {
479
+ var _a;
480
+ (_a = this.manager) === null || _a === void 0 ? void 0 : _a.clear();
481
+ this.changeEvent.next();
482
+ }
483
+ destroy() {
484
+ var _a;
485
+ this.subscriptions.forEach(i => i.unsubscribe());
486
+ this.collaborateCursor.destroy();
487
+ (_a = this.manager) === null || _a === void 0 ? void 0 : _a.destroy();
488
+ }
489
+ syncRootComponent(root, rootComponent) {
490
+ let slots = root.get('slots');
491
+ if (!slots) {
492
+ slots = new yjs.Array();
493
+ rootComponent.slots.toArray().forEach(i => {
494
+ const sharedSlot = this.createSharedSlotBySlot(i);
495
+ slots.push([sharedSlot]);
496
+ });
497
+ this.yDoc.transact(() => {
498
+ root.set('state', rootComponent.state);
499
+ root.set('slots', slots);
500
+ });
501
+ }
502
+ else if (slots.length === 0) {
503
+ rootComponent.updateState(() => {
504
+ return root.get('state');
505
+ });
506
+ this.yDoc.transact(() => {
507
+ rootComponent.slots.toArray().forEach(i => {
508
+ const sharedSlot = this.createSharedSlotBySlot(i);
509
+ slots.push([sharedSlot]);
510
+ });
511
+ });
512
+ }
513
+ else {
514
+ rootComponent.updateState(() => {
515
+ return root.get('state');
516
+ });
517
+ rootComponent.slots.clean();
518
+ slots.forEach(sharedSlot => {
519
+ const slot = this.createSlotBySharedSlot(sharedSlot);
520
+ this.syncContent(sharedSlot.get('content'), slot);
521
+ this.syncSlot(sharedSlot, slot);
522
+ rootComponent.slots.insert(slot);
523
+ });
524
+ }
525
+ this.syncComponent(root, rootComponent);
526
+ this.syncSlots(slots, rootComponent);
527
+ }
528
+ restoreCursorLocation(position) {
529
+ const anchorPosition = yjs.createAbsolutePositionFromRelativePosition(position.anchor, this.yDoc);
530
+ const focusPosition = yjs.createAbsolutePositionFromRelativePosition(position.focus, this.yDoc);
531
+ if (anchorPosition && focusPosition) {
532
+ const focusSlot = this.contentMap.get(focusPosition.type);
533
+ const anchorSlot = this.contentMap.get(anchorPosition.type);
534
+ if (focusSlot && anchorSlot) {
535
+ this.selection.setBaseAndExtent(anchorSlot, anchorPosition.index, focusSlot, focusPosition.index);
536
+ return;
537
+ }
538
+ }
539
+ this.selection.unSelect();
540
+ }
541
+ getRelativeCursorLocation() {
542
+ const { anchorSlot, anchorOffset, focusSlot, focusOffset } = this.selection;
543
+ if (anchorSlot) {
544
+ const anchorYText = this.contentMap.get(anchorSlot);
545
+ if (anchorYText) {
546
+ const anchorPosition = yjs.createRelativePositionFromTypeIndex(anchorYText, anchorOffset);
547
+ if (focusSlot) {
548
+ const focusYText = this.contentMap.get(focusSlot);
549
+ if (focusYText) {
550
+ const focusPosition = yjs.createRelativePositionFromTypeIndex(focusYText, focusOffset);
551
+ return {
552
+ focus: focusPosition,
553
+ anchor: anchorPosition
554
+ };
555
+ }
556
+ }
557
+ }
558
+ }
559
+ return null;
560
+ }
561
+ syncContent(content, slot) {
562
+ this.contentMap.set(slot, content);
563
+ const syncRemote = (ev, tr) => {
564
+ this.runRemoteUpdate(tr, () => {
565
+ slot.retain(0);
566
+ ev.delta.forEach(action => {
567
+ if (Reflect.has(action, 'retain')) {
568
+ if (action.attributes) {
569
+ const formats = remoteFormatsToLocal(this.registry, action.attributes);
570
+ if (formats.length) {
571
+ slot.retain(action.retain, formats);
572
+ }
573
+ slot.retain(slot.index + action.retain);
574
+ }
575
+ else {
576
+ slot.retain(action.retain);
577
+ }
578
+ }
579
+ else if (action.insert) {
580
+ const index = slot.index;
581
+ let length = 1;
582
+ if (typeof action.insert === 'string') {
583
+ length = action.insert.length;
584
+ slot.insert(action.insert, remoteFormatsToLocal(this.registry, action.attributes));
585
+ }
586
+ else {
587
+ const sharedComponent = action.insert;
588
+ const canInsertInlineComponent = slot.schema.includes(core.ContentType.InlineComponent);
589
+ const component = this.createComponentBySharedComponent(sharedComponent, canInsertInlineComponent);
590
+ this.syncSlots(sharedComponent.get('slots'), component);
591
+ this.syncComponent(sharedComponent, component);
592
+ slot.insert(component);
593
+ }
594
+ if (this.selection.isSelected) {
595
+ if (slot === this.selection.anchorSlot && this.selection.anchorOffset > index) {
596
+ this.selection.setAnchor(slot, this.selection.anchorOffset + length);
597
+ }
598
+ if (slot === this.selection.focusSlot && this.selection.focusOffset > index) {
599
+ this.selection.setFocus(slot, this.selection.focusOffset + length);
600
+ }
601
+ }
602
+ }
603
+ else if (action.delete) {
604
+ const index = slot.index;
605
+ slot.retain(slot.index);
606
+ slot.delete(action.delete);
607
+ if (this.selection.isSelected) {
608
+ if (slot === this.selection.anchorSlot && this.selection.anchorOffset >= index) {
609
+ this.selection.setAnchor(slot, this.selection.startOffset - action.delete);
610
+ }
611
+ if (slot === this.selection.focusSlot && this.selection.focusOffset >= index) {
612
+ this.selection.setFocus(slot, this.selection.focusOffset - action.delete);
613
+ }
614
+ }
615
+ }
616
+ else if (action.attributes) {
617
+ slot.updateState(draft => {
618
+ if (typeof draft === 'object' && draft !== null) {
619
+ Object.assign(draft, action.attributes);
620
+ }
621
+ else {
622
+ return action.attributes;
623
+ }
624
+ });
625
+ }
626
+ });
627
+ });
628
+ };
629
+ content.observe(syncRemote);
630
+ const sub = slot.onContentChange.subscribe(actions => {
631
+ this.runLocalUpdate(() => {
632
+ var _a;
633
+ let offset = 0;
634
+ let length = 0;
635
+ for (const action of actions) {
636
+ if (action.type === 'retain') {
637
+ const formats = action.formats;
638
+ if (formats) {
639
+ const keys = Object.keys(formats);
640
+ let length = keys.length;
641
+ keys.forEach(key => {
642
+ const formatter = this.registry.getFormatter(key);
643
+ if (!formatter) {
644
+ length--;
645
+ Reflect.deleteProperty(formats, key);
646
+ }
647
+ });
648
+ if (length) {
649
+ content.format(offset, action.offset, formats);
650
+ }
651
+ }
652
+ else {
653
+ offset = action.offset;
654
+ }
655
+ }
656
+ else if (action.type === 'insert') {
657
+ const delta = content.toDelta();
658
+ const isEmpty = delta.length === 1 && delta[0].insert === core.Slot.emptyPlaceholder;
659
+ if (typeof action.content === 'string') {
660
+ length = action.content.length;
661
+ content.insert(offset, action.content, action.formats || {});
662
+ }
663
+ else {
664
+ length = 1;
665
+ const sharedComponent = this.createSharedComponentByComponent(action.ref);
666
+ content.insertEmbed(offset, sharedComponent, action.formats || {});
667
+ }
668
+ if (isEmpty && offset === 0) {
669
+ content.delete(content.length - 1, 1);
670
+ }
671
+ offset += length;
672
+ }
673
+ else if (action.type === 'delete') {
674
+ const delta = content.toDelta();
675
+ if (content.length) {
676
+ content.delete(offset, action.count);
677
+ }
678
+ if (content.length === 0) {
679
+ content.insert(0, '\n', (_a = delta[0]) === null || _a === void 0 ? void 0 : _a.attributes);
680
+ }
681
+ }
682
+ }
683
+ });
684
+ });
685
+ sub.add(slot.onChildComponentRemove.subscribe(components => {
686
+ components.forEach(c => {
687
+ this.cleanSubscriptionsByComponent(c);
688
+ });
689
+ }));
690
+ this.contentSyncCaches.set(slot, () => {
691
+ content.unobserve(syncRemote);
692
+ sub.unsubscribe();
693
+ });
694
+ }
695
+ syncSlot(remoteSlot, slot) {
696
+ const syncRemote = (ev, tr) => {
697
+ this.runRemoteUpdate(tr, () => {
698
+ ev.keysChanged.forEach(key => {
699
+ if (key === 'state') {
700
+ const state = ev.target.get('state');
701
+ slot.updateState(draft => {
702
+ if (typeof draft === 'object' && draft !== null) {
703
+ Object.assign(draft, state);
704
+ }
705
+ else {
706
+ return state;
707
+ }
708
+ });
709
+ }
710
+ });
711
+ });
712
+ };
713
+ remoteSlot.observe(syncRemote);
714
+ const sub = slot.onStateChange.subscribe(change => {
715
+ this.runLocalUpdate(() => {
716
+ remoteSlot.set('state', change.newState);
717
+ }, change.record);
718
+ });
719
+ this.slotStateSyncCaches.set(slot, () => {
720
+ remoteSlot.unobserve(syncRemote);
721
+ sub.unsubscribe();
722
+ });
723
+ }
724
+ syncSlots(remoteSlots, component) {
725
+ const slots = component.slots;
726
+ const syncRemote = (ev, tr) => {
727
+ this.runRemoteUpdate(tr, () => {
728
+ let index = 0;
729
+ slots.retain(index);
730
+ ev.delta.forEach(action => {
731
+ if (Reflect.has(action, 'retain')) {
732
+ index += action.retain;
733
+ slots.retain(index);
734
+ }
735
+ else if (action.insert) {
736
+ action.insert.forEach(item => {
737
+ const slot = this.createSlotBySharedSlot(item);
738
+ slots.insert(slot);
739
+ this.syncContent(item.get('content'), slot);
740
+ this.syncSlot(item, slot);
741
+ index++;
742
+ });
743
+ }
744
+ else if (action.delete) {
745
+ slots.retain(index);
746
+ slots.delete(action.delete);
747
+ }
748
+ });
749
+ });
750
+ };
751
+ remoteSlots.observe(syncRemote);
752
+ const sub = slots.onChange.subscribe(operations => {
753
+ this.runLocalUpdate(() => {
754
+ const applyActions = operations.apply;
755
+ let index;
756
+ applyActions.forEach(action => {
757
+ if (action.type === 'retain') {
758
+ index = action.offset;
759
+ }
760
+ else if (action.type === 'insertSlot') {
761
+ const sharedSlot = this.createSharedSlotBySlot(action.ref);
762
+ remoteSlots.insert(index, [sharedSlot]);
763
+ index++;
764
+ }
765
+ else if (action.type === 'delete') {
766
+ remoteSlots.delete(index, action.count);
767
+ }
768
+ });
769
+ });
770
+ });
771
+ sub.add(slots.onChildSlotRemove.subscribe(slots => {
772
+ slots.forEach(slot => {
773
+ this.cleanSubscriptionsBySlot(slot);
774
+ });
775
+ }));
776
+ this.slotsSyncCaches.set(component, () => {
777
+ remoteSlots.unobserve(syncRemote);
778
+ sub.unsubscribe();
779
+ });
780
+ }
781
+ syncComponent(remoteComponent, component) {
782
+ const syncRemote = (ev, tr) => {
783
+ this.runRemoteUpdate(tr, () => {
784
+ ev.keysChanged.forEach(key => {
785
+ if (key === 'state') {
786
+ const state = ev.target.get('state');
787
+ component.updateState(draft => {
788
+ if (typeof draft === 'object' && draft !== null) {
789
+ Object.assign(draft, state);
790
+ }
791
+ else {
792
+ return state;
793
+ }
794
+ });
795
+ }
796
+ });
797
+ });
798
+ };
799
+ remoteComponent.observe(syncRemote);
800
+ const sub = component.onStateChange.subscribe(change => {
801
+ this.runLocalUpdate(() => {
802
+ remoteComponent.set('state', change.newState);
803
+ }, change.record);
804
+ });
805
+ this.componentStateSyncCaches.set(component, () => {
806
+ remoteComponent.unobserve(syncRemote);
807
+ sub.unsubscribe();
808
+ });
809
+ }
810
+ runLocalUpdate(fn, record = true) {
811
+ if (this.updateFromRemote || this.controller.readonly) {
812
+ return;
813
+ }
814
+ this.updateRemoteActions.push({
815
+ record,
816
+ action: fn
817
+ });
818
+ }
819
+ runRemoteUpdate(tr, fn) {
820
+ if (tr.origin === this.yDoc) {
821
+ return;
822
+ }
823
+ this.updateFromRemote = true;
824
+ if (tr.origin === this.manager) {
825
+ this.scheduler.historyApplyTransact(fn);
826
+ }
827
+ else {
828
+ this.scheduler.remoteUpdateTransact(fn);
829
+ }
830
+ this.updateFromRemote = false;
831
+ }
832
+ createSharedComponentByComponent(component) {
833
+ const sharedComponent = new yjs.Map();
834
+ sharedComponent.set('state', component.state);
835
+ sharedComponent.set('name', component.name);
836
+ const sharedSlots = new yjs.Array();
837
+ sharedComponent.set('slots', sharedSlots);
838
+ component.slots.toArray().forEach(slot => {
839
+ const sharedSlot = this.createSharedSlotBySlot(slot);
840
+ sharedSlots.push([sharedSlot]);
841
+ });
842
+ this.syncSlots(sharedSlots, component);
843
+ this.syncComponent(sharedComponent, component);
844
+ return sharedComponent;
845
+ }
846
+ createSharedSlotBySlot(slot) {
847
+ const sharedSlot = new yjs.Map();
848
+ sharedSlot.set('schema', slot.schema);
849
+ sharedSlot.set('state', slot.state);
850
+ const sharedContent = new yjs.Text();
851
+ sharedSlot.set('content', sharedContent);
852
+ let offset = 0;
853
+ slot.toDelta().forEach(i => {
854
+ let formats = {};
855
+ if (i.formats) {
856
+ i.formats.forEach(item => {
857
+ formats[item[0].name] = item[1];
858
+ });
859
+ }
860
+ else {
861
+ formats = null;
862
+ }
863
+ if (typeof i.insert === 'string') {
864
+ sharedContent.insert(offset, i.insert, formats);
865
+ }
866
+ else {
867
+ const sharedComponent = this.createSharedComponentByComponent(i.insert);
868
+ sharedContent.insertEmbed(offset, sharedComponent, formats);
869
+ }
870
+ offset += i.insert.length;
871
+ });
872
+ this.syncContent(sharedContent, slot);
873
+ this.syncSlot(sharedSlot, slot);
874
+ return sharedSlot;
875
+ }
876
+ createComponentBySharedComponent(yMap, canInsertInlineComponent) {
877
+ const sharedSlots = yMap.get('slots');
878
+ const slots = [];
879
+ sharedSlots.forEach(sharedSlot => {
880
+ const slot = this.createSlotBySharedSlot(sharedSlot);
881
+ slots.push(slot);
882
+ });
883
+ const name = yMap.get('name');
884
+ const state = yMap.get('state');
885
+ const instance = this.translator.createComponentByData(name, {
886
+ state,
887
+ slots
888
+ });
889
+ if (instance) {
890
+ instance.slots.toArray().forEach((slot, index) => {
891
+ let sharedSlot = sharedSlots.get(index);
892
+ if (!sharedSlot) {
893
+ sharedSlot = this.createSharedSlotBySlot(slot);
894
+ sharedSlots.push([sharedSlot]);
895
+ }
896
+ this.syncSlot(sharedSlot, slot);
897
+ this.syncContent(sharedSlot.get('content'), slot);
898
+ });
899
+ return instance;
900
+ }
901
+ return createUnknownComponent(name, canInsertInlineComponent).createInstance(this.starter);
902
+ }
903
+ createSlotBySharedSlot(sharedSlot) {
904
+ const content = sharedSlot.get('content');
905
+ const delta = content.toDelta();
906
+ const slot = this.translator.createSlot({
907
+ schema: sharedSlot.get('schema'),
908
+ state: sharedSlot.get('state'),
909
+ formats: {},
910
+ content: []
911
+ });
912
+ for (const action of delta) {
913
+ if (action.insert) {
914
+ if (typeof action.insert === 'string') {
915
+ const blockFormats = [];
916
+ const formats = remoteFormatsToLocal(this.registry, action.attributes).filter(item => {
917
+ if (item[0].type === core.FormatType.Block) {
918
+ blockFormats.push(item);
919
+ return false;
920
+ }
921
+ return true;
922
+ });
923
+ slot.insert(action.insert, formats);
924
+ const index = slot.index;
925
+ blockFormats.forEach(item => {
926
+ slot.setAttribute(item[0], item[1]);
927
+ });
928
+ slot.retain(index);
929
+ }
930
+ else {
931
+ const sharedComponent = action.insert;
932
+ const canInsertInlineComponent = slot.schema.includes(core.ContentType.InlineComponent);
933
+ const component = this.createComponentBySharedComponent(sharedComponent, canInsertInlineComponent);
934
+ slot.insert(component, remoteFormatsToLocal(this.registry, action.attributes));
935
+ this.syncSlots(sharedComponent.get('slots'), component);
936
+ this.syncComponent(sharedComponent, component);
937
+ }
938
+ }
939
+ else {
940
+ throw collaborateErrorFn('unexpected delta action.');
941
+ }
942
+ }
943
+ return slot;
944
+ }
945
+ cleanSubscriptionsBySlot(slot) {
946
+ this.contentMap.delete(slot);
947
+ [this.contentSyncCaches.get(slot), this.slotStateSyncCaches.get(slot)].forEach(fn => {
948
+ if (fn) {
949
+ fn();
950
+ }
951
+ });
952
+ slot.sliceContent().forEach(i => {
953
+ if (typeof i !== 'string') {
954
+ this.cleanSubscriptionsByComponent(i);
955
+ }
956
+ });
957
+ }
958
+ cleanSubscriptionsByComponent(component) {
959
+ [this.slotsSyncCaches.get(component), this.componentStateSyncCaches.get(component)].forEach(fn => {
960
+ if (fn) {
961
+ fn();
962
+ }
963
+ });
964
+ component.slots.toArray().forEach(slot => {
965
+ this.cleanSubscriptionsBySlot(slot);
966
+ });
967
+ }
968
+ };
969
+ exports.Collaborate = __decorate([
970
+ di.Injectable(),
971
+ __param(0, di.Inject(core.HISTORY_STACK_SIZE)),
972
+ __metadata("design:paramtypes", [Number, core.RootComponentRef,
973
+ exports.CollaborateCursor,
974
+ core.Controller,
975
+ core.Scheduler,
976
+ core.Translator,
977
+ core.Registry,
978
+ core.Selection,
979
+ core.Starter])
980
+ ], exports.Collaborate);
981
+ function remoteFormatsToLocal(registry, attrs) {
982
+ const formats = [];
983
+ if (attrs) {
984
+ Object.keys(attrs).forEach(key => {
985
+ const formatter = registry.getFormatter(key);
986
+ if (formatter) {
987
+ formats.push([formatter, attrs[key]]);
988
+ }
989
+ });
990
+ }
991
+ return formats;
992
+ }
993
+
994
+ const collaborateModule = {
995
+ providers: [
996
+ exports.Collaborate,
997
+ exports.CollaborateCursor,
998
+ {
999
+ provide: core.History,
1000
+ useClass: exports.Collaborate
1001
+ }
1002
+ ]
1003
+ };
1004
+
1005
+ exports.CollaborateSelectionAwarenessDelegate = CollaborateSelectionAwarenessDelegate;
1006
+ exports.collaborateModule = collaborateModule;