@textbus/collaborate 4.0.0-alpha.7 → 4.0.0-alpha.71

Sign up to get free protection for your applications and to get access to all the features.
@@ -1,7 +1,8 @@
1
1
  import { Injectable, Inject, Optional } from '@viewfly/core';
2
- import { Subject, map, filter } from '@tanbo/stream';
3
- import { makeError, HISTORY_STACK_SIZE, ChangeOrigin, Slot, RootComponentRef, Scheduler, Registry, Selection, History } from '@textbus/core';
4
- import { Doc, UndoManager, Array, createAbsolutePositionFromRelativePosition, createRelativePositionFromTypeIndex, Map, Text } from 'yjs';
2
+ import { Subject, map, filter, Subscription } from '@tanbo/stream';
3
+ import { makeError, HISTORY_STACK_SIZE, ChangeOrigin, createObjectProxy, createArrayProxy, Slot, RootComponentRef, Scheduler, Registry, Selection, History } from '@textbus/core';
4
+ import { Doc, UndoManager, Map, Array as Array$1, Text, createAbsolutePositionFromRelativePosition, createRelativePositionFromTypeIndex } from 'yjs';
5
+ import { WebsocketProvider } from 'y-websocket';
5
6
 
6
7
  /******************************************************************************
7
8
  Copyright (c) Microsoft Corporation.
@@ -41,38 +42,38 @@ typeof SuppressedError === "function" ? SuppressedError : function (error, suppr
41
42
  };
42
43
 
43
44
  const collaborateErrorFn = makeError('Collaborate');
44
- class ContentMap {
45
+ class SlotMap {
45
46
  constructor() {
46
47
  this.slotAndYTextMap = new WeakMap();
47
- this.yTextAndSLotMap = new WeakMap();
48
+ this.yTextAndSlotMap = new WeakMap();
48
49
  }
49
50
  set(key, value) {
50
51
  if (key instanceof Slot) {
51
52
  this.slotAndYTextMap.set(key, value);
52
- this.yTextAndSLotMap.set(value, key);
53
+ this.yTextAndSlotMap.set(value, key);
53
54
  }
54
55
  else {
55
56
  this.slotAndYTextMap.set(value, key);
56
- this.yTextAndSLotMap.set(key, value);
57
+ this.yTextAndSlotMap.set(key, value);
57
58
  }
58
59
  }
59
60
  get(key) {
60
61
  if (key instanceof Slot) {
61
62
  return this.slotAndYTextMap.get(key) || null;
62
63
  }
63
- return this.yTextAndSLotMap.get(key) || null;
64
+ return this.yTextAndSlotMap.get(key) || null;
64
65
  }
65
66
  delete(key) {
66
67
  if (key instanceof Slot) {
67
68
  const v = this.slotAndYTextMap.get(key);
68
69
  this.slotAndYTextMap.delete(key);
69
70
  if (v) {
70
- this.yTextAndSLotMap.delete(v);
71
+ this.yTextAndSlotMap.delete(v);
71
72
  }
72
73
  }
73
74
  else {
74
- const v = this.yTextAndSLotMap.get(key);
75
- this.yTextAndSLotMap.delete(key);
75
+ const v = this.yTextAndSlotMap.get(key);
76
+ this.yTextAndSlotMap.delete(key);
76
77
  if (v) {
77
78
  this.slotAndYTextMap.delete(v);
78
79
  }
@@ -105,13 +106,9 @@ let Collaborate = class Collaborate {
105
106
  this.manager = null;
106
107
  this.subscriptions = [];
107
108
  this.updateFromRemote = false;
108
- this.contentSyncCaches = new WeakMap();
109
- this.slotStateSyncCaches = new WeakMap();
110
- this.slotsSyncCaches = new WeakMap();
111
- this.componentStateSyncCaches = new WeakMap();
112
109
  this.localChangesAppliedEvent = new Subject();
113
110
  this.selectionChangeEvent = new Subject();
114
- this.contentMap = new ContentMap();
111
+ this.slotMap = new SlotMap();
115
112
  this.updateRemoteActions = [];
116
113
  this.noRecord = {};
117
114
  this.historyItems = [];
@@ -146,7 +143,7 @@ let Collaborate = class Collaborate {
146
143
  this.subscriptions.push(this.scheduler.onLocalChangeBefore.subscribe(() => {
147
144
  beforePosition = this.getRelativeCursorLocation();
148
145
  }));
149
- manager.on('stack-item-added', event => {
146
+ manager.on('stack-item-added', (event) => {
150
147
  if (event.type === 'undo') {
151
148
  if (event.origin === manager) {
152
149
  this.index++;
@@ -258,50 +255,145 @@ let Collaborate = class Collaborate {
258
255
  (_a = this.manager) === null || _a === void 0 ? void 0 : _a.destroy();
259
256
  }
260
257
  syncRootComponent(root, rootComponent) {
261
- let slots = root.get('slots');
262
- if (!slots) {
263
- slots = new Array();
264
- rootComponent.slots.toArray().forEach(i => {
265
- const sharedSlot = this.createSharedSlotBySlot(i);
266
- slots.push([sharedSlot]);
267
- });
258
+ let state = root.get('state');
259
+ if (!state) {
260
+ state = new Map();
261
+ this.syncLocalMapToSharedMap(rootComponent.state, state);
268
262
  this.yDoc.transact(() => {
269
- root.set('state', rootComponent.state);
270
- root.set('slots', slots);
263
+ root.set('state', state);
271
264
  });
272
265
  }
273
- else if (slots.length === 0) {
274
- rootComponent.updateState(() => {
275
- return root.get('state');
266
+ else {
267
+ Object.keys(rootComponent.state).forEach(key => {
268
+ Reflect.deleteProperty(rootComponent.state, key);
276
269
  });
277
- this.yDoc.transact(() => {
278
- rootComponent.slots.toArray().forEach(i => {
279
- const sharedSlot = this.createSharedSlotBySlot(i);
280
- slots.push([sharedSlot]);
270
+ this.syncSharedMapToLocalMap(state, rootComponent.state);
271
+ }
272
+ }
273
+ syncSharedMapToLocalMap(sharedMap, localMap) {
274
+ sharedMap.forEach((value, key) => {
275
+ localMap[key] = this.createLocalModelBySharedByModel(value);
276
+ });
277
+ this.syncObject(sharedMap, localMap);
278
+ }
279
+ createLocalMapBySharedMap(sharedMap) {
280
+ const localMap = createObjectProxy({});
281
+ this.syncSharedMapToLocalMap(sharedMap, localMap);
282
+ return localMap;
283
+ }
284
+ createLocalArrayBySharedArray(sharedArray) {
285
+ const localArray = createArrayProxy([]);
286
+ localArray.push(...sharedArray.map(item => this.createLocalModelBySharedByModel(item)));
287
+ this.syncArray(sharedArray, localArray);
288
+ return localArray;
289
+ }
290
+ syncLocalMapToSharedMap(localMap, sharedMap) {
291
+ Object.entries(localMap).forEach(([key, value]) => {
292
+ sharedMap.set(key, this.createSharedModelByLocalModel(value));
293
+ });
294
+ this.syncObject(sharedMap, localMap);
295
+ }
296
+ createSharedMapByLocalMap(localMap) {
297
+ const sharedMap = new Map();
298
+ this.syncLocalMapToSharedMap(localMap, sharedMap);
299
+ return sharedMap;
300
+ }
301
+ createSharedArrayByLocalArray(localArray) {
302
+ const sharedArray = new Array$1();
303
+ localArray.forEach(value => {
304
+ sharedArray.push([this.createSharedModelByLocalModel(value)]);
305
+ });
306
+ this.syncArray(sharedArray, localArray);
307
+ return sharedArray;
308
+ }
309
+ createSharedSlotByLocalSlot(localSlot) {
310
+ const sharedSlot = new Text();
311
+ sharedSlot.setAttribute('__schema__', [...localSlot.schema]);
312
+ let offset = 0;
313
+ localSlot.toDelta().forEach(i => {
314
+ let formats = {};
315
+ if (i.formats) {
316
+ i.formats.forEach(item => {
317
+ formats[item[0].name] = item[1];
281
318
  });
282
- });
319
+ }
320
+ else {
321
+ formats = null;
322
+ }
323
+ if (typeof i.insert === 'string') {
324
+ sharedSlot.insert(offset, i.insert, formats);
325
+ }
326
+ else {
327
+ const sharedComponent = this.createSharedComponentByLocalComponent(i.insert);
328
+ sharedSlot.insertEmbed(offset, sharedComponent, formats);
329
+ }
330
+ offset += i.insert.length;
331
+ });
332
+ localSlot.getAttributes().forEach(item => {
333
+ sharedSlot.setAttribute(item[0].name, item[1]);
334
+ });
335
+ this.syncSlot(sharedSlot, localSlot);
336
+ return sharedSlot;
337
+ }
338
+ createLocalSlotBySharedSlot(sharedSlot) {
339
+ const delta = sharedSlot.toDelta();
340
+ const localSlot = new Slot(sharedSlot.getAttribute('__schema__') || []); // TODO 这里有潜在的问题
341
+ const attrs = sharedSlot.getAttributes();
342
+ Object.keys(attrs).forEach(key => {
343
+ const attribute = this.registry.getAttribute(key);
344
+ if (attribute) {
345
+ localSlot.setAttribute(attribute, attrs[key]);
346
+ }
347
+ });
348
+ for (const action of delta) {
349
+ if (action.insert) {
350
+ if (typeof action.insert === 'string') {
351
+ const formats = remoteFormatsToLocal(this.registry, action.attributes);
352
+ localSlot.insert(action.insert, formats);
353
+ }
354
+ else {
355
+ const sharedComponent = action.insert;
356
+ const component = this.createLocalComponentBySharedComponent(sharedComponent);
357
+ localSlot.insert(component, remoteFormatsToLocal(this.registry, action.attributes));
358
+ }
359
+ }
360
+ else {
361
+ throw collaborateErrorFn('unexpected delta action.');
362
+ }
283
363
  }
284
- else {
285
- rootComponent.updateState(() => {
286
- return root.get('state');
287
- });
288
- rootComponent.slots.clean();
289
- slots.forEach(sharedSlot => {
290
- const slot = this.createSlotBySharedSlot(sharedSlot);
291
- this.syncSlotContent(sharedSlot.get('content'), slot);
292
- this.syncSlotState(sharedSlot, slot);
293
- rootComponent.slots.insert(slot);
294
- });
364
+ this.syncSlot(sharedSlot, localSlot);
365
+ return localSlot;
366
+ }
367
+ createSharedModelByLocalModel(localModel) {
368
+ if (localModel instanceof Slot) {
369
+ return this.createSharedSlotByLocalSlot(localModel);
370
+ }
371
+ if (Array.isArray(localModel)) {
372
+ return this.createSharedArrayByLocalArray(localModel);
373
+ }
374
+ if (typeof localModel === 'object' && localModel !== null) {
375
+ return this.createSharedMapByLocalMap(localModel);
295
376
  }
296
- this.syncComponentState(root, rootComponent);
297
- this.syncComponentSlots(slots, rootComponent);
377
+ return localModel;
378
+ }
379
+ createLocalModelBySharedByModel(sharedModel) {
380
+ if (sharedModel instanceof Map) {
381
+ return this.createLocalMapBySharedMap(sharedModel);
382
+ }
383
+ if (sharedModel instanceof Array$1) {
384
+ return this.createLocalArrayBySharedArray(sharedModel);
385
+ }
386
+ if (sharedModel instanceof Text) {
387
+ return this.createLocalSlotBySharedSlot(sharedModel);
388
+ }
389
+ return sharedModel;
298
390
  }
299
391
  getAbstractSelection(position) {
300
392
  const anchorPosition = createAbsolutePositionFromRelativePosition(position.anchor, this.yDoc);
301
393
  const focusPosition = createAbsolutePositionFromRelativePosition(position.focus, this.yDoc);
302
394
  if (anchorPosition && focusPosition) {
303
- const focusSlot = this.contentMap.get(focusPosition.type);
304
- const anchorSlot = this.contentMap.get(anchorPosition.type);
395
+ const focusSlot = this.slotMap.get(focusPosition.type);
396
+ const anchorSlot = this.slotMap.get(anchorPosition.type);
305
397
  if (focusSlot && anchorSlot) {
306
398
  return {
307
399
  anchorSlot,
@@ -316,11 +408,11 @@ let Collaborate = class Collaborate {
316
408
  getRelativeCursorLocation() {
317
409
  const { anchorSlot, anchorOffset, focusSlot, focusOffset } = this.selection;
318
410
  if (anchorSlot) {
319
- const anchorYText = this.contentMap.get(anchorSlot);
411
+ const anchorYText = this.slotMap.get(anchorSlot);
320
412
  if (anchorYText) {
321
413
  const anchorPosition = createRelativePositionFromTypeIndex(anchorYText, anchorOffset);
322
414
  if (focusSlot) {
323
- const focusYText = this.contentMap.get(focusSlot);
415
+ const focusYText = this.slotMap.get(focusSlot);
324
416
  if (focusYText) {
325
417
  const focusPosition = createRelativePositionFromTypeIndex(focusYText, focusOffset);
326
418
  return {
@@ -333,11 +425,10 @@ let Collaborate = class Collaborate {
333
425
  }
334
426
  return null;
335
427
  }
336
- syncSlotContent(content, slot) {
337
- this.contentMap.set(slot, content);
428
+ syncSlot(sharedSlot, localSlot) {
338
429
  const syncRemote = (ev, tr) => {
339
430
  this.runRemoteUpdate(tr, () => {
340
- slot.retain(0);
431
+ localSlot.retain(0);
341
432
  ev.keysChanged.forEach(key => {
342
433
  const change = ev.keys.get(key);
343
434
  if (!change) {
@@ -347,13 +438,13 @@ let Collaborate = class Collaborate {
347
438
  if (updateType === 'update' || updateType === 'add') {
348
439
  const attribute = this.registry.getAttribute(key);
349
440
  if (attribute) {
350
- slot.setAttribute(attribute, content.getAttribute(key));
441
+ localSlot.setAttribute(attribute, sharedSlot.getAttribute(key));
351
442
  }
352
443
  }
353
444
  else if (updateType === 'delete') {
354
445
  const attribute = this.registry.getAttribute(key);
355
446
  if (attribute) {
356
- slot.removeAttribute(attribute);
447
+ localSlot.removeAttribute(attribute);
357
448
  }
358
449
  }
359
450
  });
@@ -362,54 +453,52 @@ let Collaborate = class Collaborate {
362
453
  if (action.attributes) {
363
454
  const formats = remoteFormatsToLocal(this.registry, action.attributes);
364
455
  if (formats.length) {
365
- slot.retain(action.retain, formats);
456
+ localSlot.retain(action.retain, formats);
366
457
  }
367
- slot.retain(slot.index + action.retain);
458
+ localSlot.retain(localSlot.index + action.retain);
368
459
  }
369
460
  else {
370
- slot.retain(action.retain);
461
+ localSlot.retain(action.retain);
371
462
  }
372
463
  }
373
464
  else if (action.insert) {
374
- const index = slot.index;
465
+ const index = localSlot.index;
375
466
  let length = 1;
376
467
  if (typeof action.insert === 'string') {
377
468
  length = action.insert.length;
378
- slot.insert(action.insert, remoteFormatsToLocal(this.registry, action.attributes));
469
+ localSlot.insert(action.insert, remoteFormatsToLocal(this.registry, action.attributes));
379
470
  }
380
471
  else {
381
472
  const sharedComponent = action.insert;
382
- const component = this.createComponentBySharedComponent(sharedComponent);
383
- this.syncComponentSlots(sharedComponent.get('slots'), component);
384
- this.syncComponentState(sharedComponent, component);
385
- slot.insert(component);
473
+ const component = this.createLocalComponentBySharedComponent(sharedComponent);
474
+ localSlot.insert(component);
386
475
  }
387
476
  if (this.selection.isSelected && tr.origin !== this.manager) {
388
- if (slot === this.selection.anchorSlot && this.selection.anchorOffset > index) {
389
- this.selection.setAnchor(slot, this.selection.anchorOffset + length);
477
+ if (localSlot === this.selection.anchorSlot && this.selection.anchorOffset > index) {
478
+ this.selection.setAnchor(localSlot, this.selection.anchorOffset + length);
390
479
  }
391
- if (slot === this.selection.focusSlot && this.selection.focusOffset > index) {
392
- this.selection.setFocus(slot, this.selection.focusOffset + length);
480
+ if (localSlot === this.selection.focusSlot && this.selection.focusOffset > index) {
481
+ this.selection.setFocus(localSlot, this.selection.focusOffset + length);
393
482
  }
394
483
  }
395
484
  }
396
485
  else if (action.delete) {
397
- const index = slot.index;
398
- slot.delete(action.delete);
486
+ const index = localSlot.index;
487
+ localSlot.delete(action.delete);
399
488
  if (this.selection.isSelected && tr.origin !== this.manager) {
400
- if (slot === this.selection.anchorSlot && this.selection.anchorOffset >= index) {
401
- this.selection.setAnchor(slot, this.selection.startOffset - action.delete);
489
+ if (localSlot === this.selection.anchorSlot && this.selection.anchorOffset >= index) {
490
+ this.selection.setAnchor(localSlot, this.selection.startOffset - action.delete);
402
491
  }
403
- if (slot === this.selection.focusSlot && this.selection.focusOffset >= index) {
404
- this.selection.setFocus(slot, this.selection.focusOffset - action.delete);
492
+ if (localSlot === this.selection.focusSlot && this.selection.focusOffset >= index) {
493
+ this.selection.setFocus(localSlot, this.selection.focusOffset - action.delete);
405
494
  }
406
495
  }
407
496
  }
408
497
  });
409
498
  });
410
499
  };
411
- content.observe(syncRemote);
412
- const sub = slot.onContentChange.subscribe(actions => {
500
+ sharedSlot.observe(syncRemote);
501
+ const sub = localSlot.onContentChange.subscribe(actions => {
413
502
  this.runLocalUpdate(() => {
414
503
  var _a;
415
504
  let offset = 0;
@@ -428,170 +517,176 @@ let Collaborate = class Collaborate {
428
517
  }
429
518
  });
430
519
  if (length) {
431
- content.format(offset, action.offset, formats);
520
+ sharedSlot.format(offset, action.offset, formats);
432
521
  }
433
522
  }
434
523
  else {
435
524
  offset = action.offset;
436
525
  }
437
526
  }
438
- else if (action.type === 'insert') {
439
- const delta = content.toDelta();
527
+ else if (action.type === 'contentInsert') {
528
+ const delta = sharedSlot.toDelta();
440
529
  const isEmpty = delta.length === 1 && delta[0].insert === Slot.emptyPlaceholder;
441
530
  if (typeof action.content === 'string') {
442
531
  length = action.content.length;
443
- content.insert(offset, action.content, action.formats || {});
532
+ sharedSlot.insert(offset, action.content, action.formats || {});
444
533
  }
445
534
  else {
446
535
  length = 1;
447
- const sharedComponent = this.createSharedComponentByComponent(action.ref);
448
- content.insertEmbed(offset, sharedComponent, action.formats || {});
536
+ const sharedComponent = this.createSharedComponentByLocalComponent(action.ref);
537
+ sharedSlot.insertEmbed(offset, sharedComponent, action.formats || {});
449
538
  }
450
539
  if (isEmpty && offset === 0) {
451
- content.delete(content.length - 1, 1);
540
+ sharedSlot.delete(sharedSlot.length - 1, 1);
452
541
  }
453
542
  offset += length;
454
543
  }
455
544
  else if (action.type === 'delete') {
456
- const delta = content.toDelta();
457
- if (content.length) {
458
- content.delete(offset, action.count);
545
+ const delta = sharedSlot.toDelta();
546
+ if (sharedSlot.length) {
547
+ sharedSlot.delete(offset, action.count);
459
548
  }
460
- if (content.length === 0) {
461
- content.insert(0, '\n', (_a = delta[0]) === null || _a === void 0 ? void 0 : _a.attributes);
549
+ if (sharedSlot.length === 0) {
550
+ sharedSlot.insert(0, '\n', (_a = delta[0]) === null || _a === void 0 ? void 0 : _a.attributes);
462
551
  }
463
552
  }
464
553
  else if (action.type === 'attrSet') {
465
- content.setAttribute(action.name, action.value);
554
+ sharedSlot.setAttribute(action.name, action.value);
466
555
  }
467
- else if (action.type === 'attrRemove') {
468
- content.removeAttribute(action.name);
556
+ else if (action.type === 'attrDelete') {
557
+ sharedSlot.removeAttribute(action.name);
469
558
  }
470
559
  }
471
560
  });
472
561
  });
473
- sub.add(slot.onChildComponentRemove.subscribe(components => {
474
- components.forEach(c => {
475
- this.cleanSubscriptionsByComponent(c);
476
- });
477
- }));
478
- this.contentSyncCaches.set(slot, () => {
479
- content.unobserve(syncRemote);
562
+ this.slotMap.set(localSlot, sharedSlot);
563
+ localSlot.__changeMarker__.destroyCallbacks.push(() => {
564
+ this.slotMap.delete(localSlot);
565
+ sharedSlot.unobserve(syncRemote);
480
566
  sub.unsubscribe();
481
567
  });
482
568
  }
483
- syncSlotState(remoteSlot, slot) {
484
- const syncRemote = (ev, tr) => {
485
- this.runRemoteUpdate(tr, () => {
486
- ev.keysChanged.forEach(key => {
487
- if (key === 'state') {
488
- const state = ev.target.get('state');
489
- slot.updateState(draft => {
490
- if (typeof draft === 'object' && draft !== null) {
491
- Object.assign(draft, state);
569
+ createSharedComponentByLocalComponent(component) {
570
+ const sharedComponent = new Map();
571
+ const sharedState = this.createSharedMapByLocalMap(component.state);
572
+ sharedComponent.set('name', component.name);
573
+ sharedComponent.set('state', sharedState);
574
+ return sharedComponent;
575
+ }
576
+ createLocalComponentBySharedComponent(yMap) {
577
+ const componentName = yMap.get('name');
578
+ const sharedState = yMap.get('state');
579
+ const state = this.createLocalMapBySharedMap(sharedState);
580
+ const instance = this.registry.createComponentByData(componentName, state);
581
+ if (instance) {
582
+ return instance;
583
+ }
584
+ throw collaborateErrorFn(`cannot find component factory \`${componentName}\`.`);
585
+ }
586
+ /**
587
+ * 双向同步数组
588
+ * @param sharedArray
589
+ * @param localArray
590
+ * @private
591
+ */
592
+ syncArray(sharedArray, localArray) {
593
+ const sub = localArray.__changeMarker__.onSelfChange.subscribe((actions) => {
594
+ this.runLocalUpdate(() => {
595
+ let index = 0;
596
+ for (const action of actions) {
597
+ switch (action.type) {
598
+ case 'retain':
599
+ index = action.offset;
600
+ break;
601
+ case 'insert':
602
+ {
603
+ const ref = action.ref;
604
+ if (!Array.isArray(ref)) {
605
+ throw collaborateErrorFn('The insertion action must have a reference value.');
606
+ }
607
+ const data = ref.map(item => {
608
+ return this.createSharedModelByLocalModel(item);
609
+ });
610
+ sharedArray.insert(index, data);
492
611
  }
493
- else {
494
- return state;
612
+ break;
613
+ case 'delete':
614
+ if (action.count <= 0) {
615
+ break;
495
616
  }
496
- });
617
+ sharedArray.delete(index, action.count);
618
+ break;
619
+ case 'setIndex':
620
+ sharedArray.delete(action.index, 1);
621
+ sharedArray.insert(action.index, [this.createSharedModelByLocalModel(action.ref)]);
622
+ break;
497
623
  }
498
- });
624
+ }
499
625
  });
500
- };
501
- remoteSlot.observe(syncRemote);
502
- const sub = slot.onStateChange.subscribe(change => {
503
- this.runLocalUpdate(() => {
504
- remoteSlot.set('state', change.newState);
505
- }, change.record);
506
626
  });
507
- this.slotStateSyncCaches.set(slot, () => {
508
- remoteSlot.unobserve(syncRemote);
509
- sub.unsubscribe();
510
- });
511
- }
512
- syncComponentSlots(remoteSlots, component) {
513
- const slots = component.slots;
514
627
  const syncRemote = (ev, tr) => {
515
628
  this.runRemoteUpdate(tr, () => {
516
629
  let index = 0;
517
- slots.retain(index);
518
- ev.delta.forEach(action => {
630
+ ev.delta.forEach((action) => {
519
631
  if (Reflect.has(action, 'retain')) {
520
632
  index += action.retain;
521
- slots.retain(index);
522
633
  }
523
634
  else if (action.insert) {
524
- action.insert.forEach(item => {
525
- const slot = this.createSlotBySharedSlot(item);
526
- slots.insert(slot);
527
- this.syncSlotContent(item.get('content'), slot);
528
- this.syncSlotState(item, slot);
529
- index++;
635
+ const data = action.insert.map((item) => {
636
+ return this.createLocalModelBySharedByModel(item);
530
637
  });
638
+ localArray.splice(index, 0, ...data);
639
+ index += data.length;
531
640
  }
532
641
  else if (action.delete) {
533
- slots.retain(index);
534
- slots.delete(action.delete);
642
+ localArray.splice(index, action.delete);
535
643
  }
536
644
  });
537
645
  });
538
646
  };
539
- remoteSlots.observe(syncRemote);
540
- const sub = slots.onChange.subscribe(operations => {
541
- this.runLocalUpdate(() => {
542
- const applyActions = operations.apply;
543
- let index;
544
- applyActions.forEach(action => {
545
- if (action.type === 'retain') {
546
- index = action.offset;
547
- }
548
- else if (action.type === 'insertSlot') {
549
- const sharedSlot = this.createSharedSlotBySlot(action.ref);
550
- remoteSlots.insert(index, [sharedSlot]);
551
- index++;
552
- }
553
- else if (action.type === 'delete') {
554
- remoteSlots.delete(index, action.count);
555
- }
556
- });
557
- });
558
- });
559
- sub.add(slots.onChildSlotRemove.subscribe(slots => {
560
- slots.forEach(slot => {
561
- this.cleanSubscriptionsBySlot(slot);
562
- });
563
- }));
564
- this.slotsSyncCaches.set(component, () => {
565
- remoteSlots.unobserve(syncRemote);
647
+ sharedArray.observe(syncRemote);
648
+ localArray.__changeMarker__.destroyCallbacks.push(() => {
566
649
  sub.unsubscribe();
650
+ sharedArray.unobserve(syncRemote);
567
651
  });
568
652
  }
569
- syncComponentState(remoteComponent, component) {
653
+ /**
654
+ * 双向同步对象
655
+ * @param sharedObject
656
+ * @param localObject
657
+ * @private
658
+ */
659
+ syncObject(sharedObject, localObject) {
570
660
  const syncRemote = (ev, tr) => {
571
661
  this.runRemoteUpdate(tr, () => {
572
- ev.keysChanged.forEach(key => {
573
- if (key === 'state') {
574
- const state = ev.target.get('state');
575
- component.updateState(draft => {
576
- if (typeof draft === 'object' && draft !== null) {
577
- Object.assign(draft, state);
578
- }
579
- else {
580
- return state;
581
- }
582
- });
662
+ ev.changes.keys.forEach((item, key) => {
663
+ if (item.action === 'add' || item.action === 'update') {
664
+ const value = sharedObject.get(key);
665
+ localObject[key] = this.createLocalModelBySharedByModel(value);
666
+ }
667
+ else {
668
+ Reflect.deleteProperty(localObject, key);
583
669
  }
584
670
  });
585
671
  });
586
672
  };
587
- remoteComponent.observe(syncRemote);
588
- const sub = component.onStateChange.subscribe(change => {
673
+ sharedObject.observe(syncRemote);
674
+ const sub = localObject.__changeMarker__.onSelfChange.subscribe((actions) => {
589
675
  this.runLocalUpdate(() => {
590
- remoteComponent.set('state', change.newState);
591
- }, change.record);
676
+ for (const action of actions) {
677
+ switch (action.type) {
678
+ case 'propSet':
679
+ sharedObject.set(action.key, this.createSharedModelByLocalModel(action.ref));
680
+ break;
681
+ case 'propDelete':
682
+ sharedObject.delete(action.key);
683
+ break;
684
+ }
685
+ }
686
+ });
592
687
  });
593
- this.componentStateSyncCaches.set(component, () => {
594
- remoteComponent.unobserve(syncRemote);
688
+ localObject.__changeMarker__.destroyCallbacks.push(function () {
689
+ sharedObject.unobserve(syncRemote);
595
690
  sub.unsubscribe();
596
691
  });
597
692
  }
@@ -617,140 +712,6 @@ let Collaborate = class Collaborate {
617
712
  }
618
713
  this.updateFromRemote = false;
619
714
  }
620
- createSharedComponentByComponent(component) {
621
- const sharedComponent = new Map();
622
- sharedComponent.set('state', component.state);
623
- sharedComponent.set('name', component.name);
624
- const sharedSlots = new Array();
625
- sharedComponent.set('slots', sharedSlots);
626
- component.slots.toArray().forEach(slot => {
627
- const sharedSlot = this.createSharedSlotBySlot(slot);
628
- sharedSlots.push([sharedSlot]);
629
- });
630
- this.syncComponentSlots(sharedSlots, component);
631
- this.syncComponentState(sharedComponent, component);
632
- return sharedComponent;
633
- }
634
- createSharedSlotBySlot(slot) {
635
- const sharedSlot = new Map();
636
- sharedSlot.set('schema', slot.schema);
637
- sharedSlot.set('state', slot.state);
638
- const sharedContent = new Text();
639
- sharedSlot.set('content', sharedContent);
640
- let offset = 0;
641
- slot.toDelta().forEach(i => {
642
- let formats = {};
643
- if (i.formats) {
644
- i.formats.forEach(item => {
645
- formats[item[0].name] = item[1];
646
- });
647
- }
648
- else {
649
- formats = null;
650
- }
651
- if (typeof i.insert === 'string') {
652
- sharedContent.insert(offset, i.insert, formats);
653
- }
654
- else {
655
- const sharedComponent = this.createSharedComponentByComponent(i.insert);
656
- sharedContent.insertEmbed(offset, sharedComponent, formats);
657
- }
658
- offset += i.insert.length;
659
- });
660
- slot.getAttributes().forEach(item => {
661
- sharedContent.setAttribute(item[0].name, item[1]);
662
- });
663
- this.syncSlotContent(sharedContent, slot);
664
- this.syncSlotState(sharedSlot, slot);
665
- return sharedSlot;
666
- }
667
- createComponentBySharedComponent(yMap) {
668
- const sharedSlots = yMap.get('slots');
669
- const slots = [];
670
- sharedSlots.forEach(sharedSlot => {
671
- const slot = this.createSlotBySharedSlot(sharedSlot);
672
- slots.push(slot);
673
- });
674
- const name = yMap.get('name');
675
- const state = yMap.get('state');
676
- const instance = this.registry.createComponentByData(name, {
677
- state,
678
- slots
679
- });
680
- if (instance) {
681
- instance.slots.toArray().forEach((slot, index) => {
682
- let sharedSlot = sharedSlots.get(index);
683
- if (!sharedSlot) {
684
- sharedSlot = this.createSharedSlotBySlot(slot);
685
- sharedSlots.push([sharedSlot]);
686
- }
687
- this.syncSlotState(sharedSlot, slot);
688
- this.syncSlotContent(sharedSlot.get('content'), slot);
689
- });
690
- return instance;
691
- }
692
- throw collaborateErrorFn(`cannot find component factory \`${name}\`.`);
693
- }
694
- createSlotBySharedSlot(sharedSlot) {
695
- const content = sharedSlot.get('content');
696
- const delta = content.toDelta();
697
- const slot = this.registry.createSlot({
698
- schema: sharedSlot.get('schema'),
699
- state: sharedSlot.get('state'),
700
- attributes: {},
701
- formats: {},
702
- content: []
703
- });
704
- const attrs = content.getAttributes();
705
- Object.keys(attrs).forEach(key => {
706
- const attribute = this.registry.getAttribute(key);
707
- if (attribute) {
708
- slot.setAttribute(attribute, attrs[key]);
709
- }
710
- });
711
- for (const action of delta) {
712
- if (action.insert) {
713
- if (typeof action.insert === 'string') {
714
- const formats = remoteFormatsToLocal(this.registry, action.attributes);
715
- slot.insert(action.insert, formats);
716
- }
717
- else {
718
- const sharedComponent = action.insert;
719
- const component = this.createComponentBySharedComponent(sharedComponent);
720
- slot.insert(component, remoteFormatsToLocal(this.registry, action.attributes));
721
- this.syncComponentSlots(sharedComponent.get('slots'), component);
722
- this.syncComponentState(sharedComponent, component);
723
- }
724
- }
725
- else {
726
- throw collaborateErrorFn('unexpected delta action.');
727
- }
728
- }
729
- return slot;
730
- }
731
- cleanSubscriptionsBySlot(slot) {
732
- this.contentMap.delete(slot);
733
- [this.contentSyncCaches.get(slot), this.slotStateSyncCaches.get(slot)].forEach(fn => {
734
- if (fn) {
735
- fn();
736
- }
737
- });
738
- slot.sliceContent().forEach(i => {
739
- if (typeof i !== 'string') {
740
- this.cleanSubscriptionsByComponent(i);
741
- }
742
- });
743
- }
744
- cleanSubscriptionsByComponent(component) {
745
- [this.slotsSyncCaches.get(component), this.componentStateSyncCaches.get(component)].forEach(fn => {
746
- if (fn) {
747
- fn();
748
- }
749
- });
750
- component.slots.toArray().forEach(slot => {
751
- this.cleanSubscriptionsBySlot(slot);
752
- });
753
- }
754
715
  };
755
716
  Collaborate = __decorate([
756
717
  Injectable(),
@@ -775,16 +736,82 @@ function remoteFormatsToLocal(registry, attrs) {
775
736
  return formats;
776
737
  }
777
738
 
739
+ let UserActivity = class UserActivity {
740
+ constructor(websocketProvider, selection) {
741
+ this.websocketProvider = websocketProvider;
742
+ this.selection = selection;
743
+ this.stateChangeEvent = new Subject();
744
+ this.userChangeEvent = new Subject();
745
+ this.subscription = new Subscription();
746
+ this.onStateChange = this.stateChangeEvent.asObservable();
747
+ this.onUserChange = this.userChangeEvent.asObservable();
748
+ }
749
+ init(userinfo) {
750
+ const provide = this.websocketProvider;
751
+ provide.awareness.setLocalStateField('user', userinfo);
752
+ this.subscription.add(this.selection.onChange.subscribe(() => {
753
+ const selection = this.selection.getPaths();
754
+ provide.awareness.setLocalStateField('selection', Object.assign(Object.assign({}, userinfo), { selection }));
755
+ }));
756
+ provide.awareness.on('update', () => {
757
+ const users = [];
758
+ const remoteSelections = [];
759
+ provide.awareness.getStates().forEach(state => {
760
+ if (state.user) {
761
+ users.push(state.user);
762
+ }
763
+ if (state.selection) {
764
+ remoteSelections.push(state.selection);
765
+ }
766
+ });
767
+ const selections = remoteSelections.filter(i => i.id !== userinfo.id);
768
+ this.userChangeEvent.next(users);
769
+ this.stateChangeEvent.next(selections);
770
+ });
771
+ }
772
+ destroy() {
773
+ this.subscription.unsubscribe();
774
+ }
775
+ };
776
+ UserActivity = __decorate([
777
+ Injectable(),
778
+ __metadata("design:paramtypes", [WebsocketProvider,
779
+ Selection])
780
+ ], UserActivity);
781
+
778
782
  class CollaborateModule {
779
- constructor() {
783
+ constructor(config) {
784
+ this.config = config;
780
785
  this.providers = [
781
786
  Collaborate,
787
+ UserActivity,
782
788
  {
783
789
  provide: History,
784
790
  useExisting: Collaborate
791
+ }, {
792
+ provide: WebsocketProvider,
793
+ useFactory: (collab) => {
794
+ return new WebsocketProvider(this.config.url, this.config.roomName, collab.yDoc);
795
+ },
796
+ deps: [Collaborate]
785
797
  }
786
798
  ];
787
799
  }
800
+ setup(textbus) {
801
+ const provide = textbus.get(WebsocketProvider);
802
+ const userActivity = textbus.get(UserActivity);
803
+ userActivity.init(this.config.userinfo);
804
+ return new Promise((resolve) => {
805
+ provide.on('sync', (is) => {
806
+ if (is) {
807
+ resolve(() => {
808
+ provide.disconnect();
809
+ userActivity.destroy();
810
+ });
811
+ }
812
+ });
813
+ });
814
+ }
788
815
  }
789
816
 
790
- export { Collaborate, CollaborateModule, CustomUndoManagerConfig };
817
+ export { Collaborate, CollaborateModule, CustomUndoManagerConfig, UserActivity };