@textbus/collaborate 2.5.8 → 2.5.9

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