-
Notifications
You must be signed in to change notification settings - Fork 97
/
Copy pathrga_tree_split.ts
1041 lines (899 loc) · 26.3 KB
/
rga_tree_split.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2020 The Yorkie Authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { logger } from '@yorkie-js-sdk/src/util/logger';
import { ActorID } from '@yorkie-js-sdk/src/document/time/actor_id';
import { Comparator } from '@yorkie-js-sdk/src/util/comparator';
import { SplayNode, SplayTree } from '@yorkie-js-sdk/src/util/splay_tree';
import { LLRBTree } from '@yorkie-js-sdk/src/util/llrb_tree';
import {
InitialTimeTicket,
MaxTimeTicket,
TimeTicket,
TimeTicketStruct,
} from '@yorkie-js-sdk/src/document/time/ticket';
import { GCChild, GCPair, GCParent } from '@yorkie-js-sdk/src/document/crdt/gc';
export interface ValueChange<T> {
actor: ActorID;
from: number;
to: number;
value?: T;
}
interface RGATreeSplitValue {
length: number;
substring(indexStart: number, indexEnd?: number): RGATreeSplitValue;
}
/**
* `RGATreeSplitPosStruct` is a structure represents the meta data of the node pos.
* It is used to serialize and deserialize the node pos.
*/
export type RGATreeSplitPosStruct = {
id: RGATreeSplitNodeIDStruct;
relativeOffset: number;
};
/**
* `RGATreeSplitNodeIDStruct` is a structure represents the meta data of the node id.
* It is used to serialize and deserialize the node id.
*/
export type RGATreeSplitNodeIDStruct = {
createdAt: TimeTicketStruct;
offset: number;
};
/**
* `RGATreeSplitNodeID` is an ID of RGATreeSplitNode.
*/
export class RGATreeSplitNodeID {
private createdAt: TimeTicket;
private offset: number;
constructor(createdAt: TimeTicket, offset: number) {
this.createdAt = createdAt;
this.offset = offset;
}
/**
* `of` creates a instance of RGATreeSplitNodeID.
*/
public static of(createdAt: TimeTicket, offset: number): RGATreeSplitNodeID {
return new RGATreeSplitNodeID(createdAt, offset);
}
/**
* `fromStruct` creates a instance of RGATreeSplitNodeID from the struct.
*/
public static fromStruct(
struct: RGATreeSplitNodeIDStruct,
): RGATreeSplitNodeID {
return RGATreeSplitNodeID.of(
TimeTicket.fromStruct(struct.createdAt),
struct.offset,
);
}
/**
* `getCreatedAt` returns the creation time of this ID.
*/
public getCreatedAt(): TimeTicket {
return this.createdAt;
}
/**
* `getOffset` returns returns the offset of this ID.
*/
public getOffset(): number {
return this.offset;
}
/**
* `equals` returns whether given ID equals to this ID or not.
*/
public equals(other: RGATreeSplitNodeID): boolean {
return (
this.createdAt.compare(other.createdAt) === 0 &&
this.offset === other.offset
);
}
/**
* `hasSameCreatedAt` returns whether given ID has same creation time with this ID.
*/
public hasSameCreatedAt(other: RGATreeSplitNodeID): boolean {
return this.createdAt.compare(other.createdAt) === 0;
}
/**
* `split` creates a new ID with an offset from this ID.
*/
public split(offset: number): RGATreeSplitNodeID {
return new RGATreeSplitNodeID(this.createdAt, this.offset + offset);
}
/**
* `toStruct` returns the structure of this node id.
*/
public toStruct(): RGATreeSplitNodeIDStruct {
return {
createdAt: this.createdAt.toStruct(),
offset: this.offset,
};
}
/**
* `toTestString` returns a String containing
* the meta data of the node id for debugging purpose.
*/
public toTestString(): string {
return `${this.createdAt.toTestString()}:${this.offset}`;
}
/**
* `toIDString` returns a string that can be used as an ID for this node id.
*/
public toIDString(): string {
return `${this.createdAt.toIDString()}:${this.offset}`;
}
}
const InitialRGATreeSplitNodeID = RGATreeSplitNodeID.of(InitialTimeTicket, 0);
/**
* `RGATreeSplitPos` is the position of the text inside the node.
*/
export class RGATreeSplitPos {
private id: RGATreeSplitNodeID;
private relativeOffset: number;
constructor(id: RGATreeSplitNodeID, relativeOffset: number) {
this.id = id;
this.relativeOffset = relativeOffset;
}
/**
* `of` creates a instance of RGATreeSplitPos.
*/
public static of(
id: RGATreeSplitNodeID,
relativeOffset: number,
): RGATreeSplitPos {
return new RGATreeSplitPos(id, relativeOffset);
}
/**
* `fromStruct` creates a instance of RGATreeSplitPos from the struct.
*/
public static fromStruct(struct: RGATreeSplitPosStruct): RGATreeSplitPos {
const id = RGATreeSplitNodeID.fromStruct(struct.id);
return RGATreeSplitPos.of(id, struct.relativeOffset);
}
/**
* `getID` returns the ID of this RGATreeSplitPos.
*/
public getID(): RGATreeSplitNodeID {
return this.id;
}
/**
* `getRelativeOffset` returns the relative offset of this RGATreeSplitPos.
*/
public getRelativeOffset(): number {
return this.relativeOffset;
}
/**
* `getAbsoluteID` returns the absolute id of this RGATreeSplitPos.
*/
public getAbsoluteID(): RGATreeSplitNodeID {
return RGATreeSplitNodeID.of(
this.id.getCreatedAt(),
this.id.getOffset() + this.relativeOffset,
);
}
/**
*`toTestString` returns a String containing
* the meta data of the position for debugging purpose.
*/
public toTestString(): string {
return `${this.id.toTestString()}:${this.relativeOffset}`;
}
/**
* `toStruct` returns the structure of this node pos.
*/
public toStruct(): RGATreeSplitPosStruct {
return {
id: this.id.toStruct(),
relativeOffset: this.relativeOffset,
};
}
/**
* `equals` returns whether given pos equal to this pos or not.
*/
public equals(other: RGATreeSplitPos): boolean {
if (!this.id.equals(other.id)) {
return false;
}
return this.relativeOffset === other.relativeOffset;
}
}
export type RGATreeSplitPosRange = [RGATreeSplitPos, RGATreeSplitPos];
/**
* `RGATreeSplitNode` is a node of RGATreeSplit.
*/
export class RGATreeSplitNode<T extends RGATreeSplitValue>
extends SplayNode<T>
implements GCChild
{
private id: RGATreeSplitNodeID;
private removedAt?: TimeTicket;
private prev?: RGATreeSplitNode<T>;
private next?: RGATreeSplitNode<T>;
private insPrev?: RGATreeSplitNode<T>;
private insNext?: RGATreeSplitNode<T>;
constructor(id: RGATreeSplitNodeID, value?: T, removedAt?: TimeTicket) {
super(value!);
this.id = id;
this.removedAt = removedAt;
}
/**
* `create` creates a instance of RGATreeSplitNode.
*/
public static create<T extends RGATreeSplitValue>(
id: RGATreeSplitNodeID,
value?: T,
): RGATreeSplitNode<T> {
return new RGATreeSplitNode(id, value);
}
/**
* `createComparator` creates a function to compare two RGATreeSplitNodeID.
*/
public static createComparator(): Comparator<RGATreeSplitNodeID> {
return (p1: RGATreeSplitNodeID, p2: RGATreeSplitNodeID): number => {
const compare = p1.getCreatedAt().compare(p2.getCreatedAt());
if (compare !== 0) {
return compare;
}
if (p1.getOffset() > p2.getOffset()) {
return 1;
} else if (p1.getOffset() < p2.getOffset()) {
return -1;
}
return 0;
};
}
/**
* `getID` returns the ID of this RGATreeSplitNode.
*/
public getID(): RGATreeSplitNodeID {
return this.id;
}
/**
* `getCreatedAt` returns creation time of the Id of RGATreeSplitNode.
*/
public getCreatedAt(): TimeTicket {
return this.id.getCreatedAt();
}
/**
* `getLength` returns the length of this node.
*/
public getLength(): number {
if (this.removedAt) {
return 0;
}
return this.getContentLength();
}
/**
* `getContentLength` returns the length of this value.
*/
public getContentLength(): number {
return (this.value && this.value.length) || 0;
}
/**
* `getPrev` returns a previous node of this node.
*/
public getPrev(): RGATreeSplitNode<T> | undefined {
return this.prev;
}
/**
* `getNext` returns a next node of this node.
*/
public getNext(): RGATreeSplitNode<T> | undefined {
return this.next;
}
/**
* `getInsPrev` returns a previous node of this node insertion.
*/
public getInsPrev(): RGATreeSplitNode<T> | undefined {
return this.insPrev;
}
/**
* `getInsNext` returns a next node of this node insertion.
*/
public getInsNext(): RGATreeSplitNode<T> | undefined {
return this.insNext;
}
/**
* `getInsPrevID` returns a ID of previous node insertion.
*/
public getInsPrevID(): RGATreeSplitNodeID {
return this.insPrev!.getID();
}
/**
* `setPrev` sets previous node of this node.
*/
public setPrev(node?: RGATreeSplitNode<T>): void {
this.prev = node;
if (node) {
node.next = this;
}
}
/**
* `setNext` sets next node of this node.
*/
public setNext(node?: RGATreeSplitNode<T>): void {
this.next = node;
if (node) {
node.prev = this;
}
}
/**
* `setInsPrev` sets previous node of this node insertion.
*/
public setInsPrev(node?: RGATreeSplitNode<T>): void {
this.insPrev = node;
if (node) {
node.insNext = this;
}
}
/**
* `setInsNext` sets next node of this node insertion.
*/
public setInsNext(node?: RGATreeSplitNode<T>): void {
this.insNext = node;
if (node) {
node.insPrev = this;
}
}
/**
* `hasNext` checks if next node exists.
*/
public hasNext(): boolean {
return !!this.next;
}
/**
* `hasInsPrev` checks if previous insertion node exists.
*/
public hasInsPrev(): boolean {
return !!this.insPrev;
}
/**
* `isRemoved` checks if removed time exists.
*/
public isRemoved(): boolean {
return !!this.removedAt;
}
/**
* `getRemovedAt` returns the remove time of this node.
*/
public getRemovedAt(): TimeTicket | undefined {
return this.removedAt;
}
/**
* `split` creates a new split node of the given offset.
*/
public split(offset: number): RGATreeSplitNode<T> {
return new RGATreeSplitNode(
this.id.split(offset),
this.splitValue(offset),
this.removedAt,
);
}
/**
* `canDelete` checks if node is able to delete.
*/
public canDelete(editedAt: TimeTicket, maxCreatedAt: TimeTicket): boolean {
const justRemoved = !this.removedAt;
if (
!this.getCreatedAt().after(maxCreatedAt) &&
(!this.removedAt || editedAt.after(this.removedAt))
) {
return justRemoved;
}
return false;
}
/**
* `canStyle` checks if node is able to set style.
*/
public canStyle(editedAt: TimeTicket, maxCreatedAt: TimeTicket): boolean {
return (
!this.getCreatedAt().after(maxCreatedAt) &&
(!this.removedAt || editedAt.after(this.removedAt))
);
}
/**
* `remove` removes node of given edited time.
*/
public remove(editedAt?: TimeTicket): void {
this.removedAt = editedAt;
}
/**
* `createRange` creates ranges of RGATreeSplitPos.
*/
public createPosRange(): RGATreeSplitPosRange {
return [
RGATreeSplitPos.of(this.id, 0),
RGATreeSplitPos.of(this.id, this.getLength()),
];
}
/**
* `deepcopy` returns a new instance of this RGATreeSplitNode without structural info.
*/
public deepcopy(): RGATreeSplitNode<T> {
return new RGATreeSplitNode(this.id, this.value, this.removedAt);
}
/**
* `toTestString` returns a String containing
* the meta data of the node for debugging purpose.
*/
public toTestString(): string {
return `${this.id.toTestString()} ${this.value ? this.value : ''}`;
}
private splitValue(offset: number): T {
const value = this.value;
this.value = value.substring(0, offset) as T;
return value.substring(offset, value.length) as T;
}
/**
* `toIDString` returns a string that can be used as an ID for this position.
*/
public toIDString(): string {
return this.id.toIDString();
}
}
/**
* `RGATreeSplit` is a block-based list with improved index-based lookup in RGA.
* The difference from RGATreeList is that it has data on a block basis to
* reduce the size of CRDT metadata. When an edit occurs on a block,
* the block is split.
*
*/
export class RGATreeSplit<T extends RGATreeSplitValue> implements GCParent {
private head: RGATreeSplitNode<T>;
private treeByIndex: SplayTree<T>;
private treeByID: LLRBTree<RGATreeSplitNodeID, RGATreeSplitNode<T>>;
constructor() {
this.head = RGATreeSplitNode.create(InitialRGATreeSplitNodeID);
this.treeByIndex = new SplayTree();
this.treeByID = new LLRBTree(RGATreeSplitNode.createComparator());
this.treeByIndex.insert(this.head);
this.treeByID.put(this.head.getID(), this.head);
}
/**
* `create` creates a instance RGATreeSplit.
*/
public static create<T extends RGATreeSplitValue>(): RGATreeSplit<T> {
return new RGATreeSplit();
}
/**
* `edit` does following steps
* 1. split nodes with from and to
* 2. delete between from and to
* 3. insert a new node
* 4. add removed node
* @param range - range of RGATreeSplitNode
* @param editedAt - edited time
* @param value - value
* @param maxCreatedAtMapByActor - maxCreatedAtMapByActor
* @returns `[RGATreeSplitPos, Map<string, TimeTicket>, Array<GCPair>, Array<Change>]`
*/
public edit(
range: RGATreeSplitPosRange,
editedAt: TimeTicket,
value?: T,
maxCreatedAtMapByActor?: Map<string, TimeTicket>,
): [
RGATreeSplitPos,
Map<string, TimeTicket>,
Array<GCPair>,
Array<ValueChange<T>>,
] {
// 01. split nodes with from and to
const [toLeft, toRight] = this.findNodeWithSplit(range[1], editedAt);
const [fromLeft, fromRight] = this.findNodeWithSplit(range[0], editedAt);
// 02. delete between from and to
const nodesToDelete = this.findBetween(fromRight, toRight);
const [changes, maxCreatedAtMap, removedNodes] = this.deleteNodes(
nodesToDelete,
editedAt,
maxCreatedAtMapByActor,
);
const caretID = toRight ? toRight.getID() : toLeft.getID();
let caretPos = RGATreeSplitPos.of(caretID, 0);
// 03. insert a new node
if (value) {
const idx = this.posToIndex(fromLeft.createPosRange()[1], true);
const inserted = this.insertAfter(
fromLeft,
RGATreeSplitNode.create(RGATreeSplitNodeID.of(editedAt, 0), value),
);
if (changes.length && changes[changes.length - 1].from === idx) {
changes[changes.length - 1].value = value;
} else {
changes.push({
actor: editedAt.getActorID(),
from: idx,
to: idx,
value,
});
}
caretPos = RGATreeSplitPos.of(
inserted.getID(),
inserted.getContentLength(),
);
}
// 04. add removed node
const pairs: Array<GCPair> = [];
for (const [, removedNode] of removedNodes) {
pairs.push({ parent: this, child: removedNode });
}
return [caretPos, maxCreatedAtMap, pairs, changes];
}
/**
* `indexToPos` finds RGATreeSplitPos of given offset.
*/
public indexToPos(idx: number): RGATreeSplitPos {
const [node, offset] = this.treeByIndex.find(idx);
const splitNode = node as RGATreeSplitNode<T>;
return RGATreeSplitPos.of(splitNode.getID(), offset);
}
/**
* `findIndexesFromRange` finds indexes based on range.
*/
public findIndexesFromRange(range: RGATreeSplitPosRange): [number, number] {
const [fromPos, toPos] = range;
return [this.posToIndex(fromPos, false), this.posToIndex(toPos, true)];
}
/**
* `posToIndex` converts the given position to index.
*/
public posToIndex(pos: RGATreeSplitPos, preferToLeft: boolean): number {
const absoluteID = pos.getAbsoluteID();
const node = preferToLeft
? this.findFloorNodePreferToLeft(absoluteID)
: this.findFloorNode(absoluteID);
if (!node) {
logger.fatal(
`the node of the given id should be found: ${absoluteID.toTestString()}`,
);
}
const index = this.treeByIndex.indexOf(node!);
const offset = node!.isRemoved()
? 0
: absoluteID.getOffset() - node!.getID().getOffset();
return index + offset;
}
/**
* `findNode` finds node of given id.
*/
public findNode(id: RGATreeSplitNodeID): RGATreeSplitNode<T> {
return this.findFloorNode(id)!;
}
/**
* `length` returns size of RGATreeSplit.
*/
public get length(): number {
return this.treeByIndex.length;
}
/**
* `checkWeight` returns false when there is an incorrect weight node.
* for debugging purpose.
*/
public checkWeight(): boolean {
return this.treeByIndex.checkWeight();
}
/**
* `toString` returns the string encoding of this RGATreeSplit.
*/
public toString(): string {
const str = [];
for (const node of this) {
if (!node.isRemoved()) {
str.push(node.getValue());
}
}
return str.join('');
}
// eslint-disable-next-line jsdoc/require-jsdoc
public *[Symbol.iterator](): IterableIterator<RGATreeSplitNode<T>> {
let node = this.head.getNext();
while (node) {
yield node;
node = node.getNext();
}
}
/**
* `getHead` returns head of RGATreeSplitNode.
*/
public getHead(): RGATreeSplitNode<T> {
return this.head;
}
/**
* `deepcopy` copies itself deeply.
*/
public deepcopy(): RGATreeSplit<T> {
const clone = new RGATreeSplit<T>();
let node = this.head.getNext();
let prev = clone.head;
let current;
while (node) {
current = clone.insertAfter(prev, node.deepcopy());
if (node.hasInsPrev()) {
const insPrevNode = clone.findNode(node.getInsPrevID());
current.setInsPrev(insPrevNode);
}
prev = current;
node = node.getNext();
}
return clone;
}
/**
* `toTestString` returns a String containing the meta data of the node
* for debugging purpose.
*/
public toTestString(): string {
const result = [];
let node: RGATreeSplitNode<T> | undefined = this.head;
while (node) {
if (node.isRemoved()) {
result.push(`{${node.toTestString()}}`);
} else {
result.push(`[${node.toTestString()}]`);
}
node = node.getNext();
}
return result.join('');
}
/**
* `insertAfter` inserts the given node after the given previous node.
*/
public insertAfter(
prevNode: RGATreeSplitNode<T>,
newNode: RGATreeSplitNode<T>,
): RGATreeSplitNode<T> {
const next = prevNode.getNext();
newNode.setPrev(prevNode);
if (next) {
next.setPrev(newNode);
}
this.treeByID.put(newNode.getID(), newNode);
this.treeByIndex.insertAfter(prevNode, newNode);
return newNode;
}
/**
* `findNodeWithSplit` splits and return nodes of the given position.
*/
public findNodeWithSplit(
pos: RGATreeSplitPos,
editedAt: TimeTicket,
): [RGATreeSplitNode<T>, RGATreeSplitNode<T>] {
const absoluteID = pos.getAbsoluteID();
let node = this.findFloorNodePreferToLeft(absoluteID);
const relativeOffset = absoluteID.getOffset() - node.getID().getOffset();
this.splitNode(node, relativeOffset);
while (node.hasNext() && node.getNext()!.getCreatedAt().after(editedAt)) {
node = node.getNext()!;
}
return [node, node.getNext()!];
}
private findFloorNodePreferToLeft(
id: RGATreeSplitNodeID,
): RGATreeSplitNode<T> {
let node = this.findFloorNode(id);
if (!node) {
logger.fatal(
`the node of the given id should be found: ${id.toTestString()}`,
);
}
if (id.getOffset() > 0 && node!.getID().getOffset() == id.getOffset()) {
// NOTE: InsPrev may not be present due to GC.
if (!node!.hasInsPrev()) {
return node!;
}
node = node!.getInsPrev();
}
return node!;
}
private findFloorNode(
id: RGATreeSplitNodeID,
): RGATreeSplitNode<T> | undefined {
const entry = this.treeByID.floorEntry(id);
if (!entry) {
return;
}
if (!entry.key.equals(id) && !entry.key.hasSameCreatedAt(id)) {
return;
}
return entry.value;
}
/**
* `findBetween` returns nodes between fromNode and toNode.
*/
public findBetween(
fromNode: RGATreeSplitNode<T>,
toNode: RGATreeSplitNode<T>,
): Array<RGATreeSplitNode<T>> {
const nodes = [];
let current: RGATreeSplitNode<T> | undefined = fromNode;
while (current && current !== toNode) {
nodes.push(current);
current = current.getNext();
}
return nodes;
}
private splitNode(
node: RGATreeSplitNode<T>,
offset: number,
): RGATreeSplitNode<T> | undefined {
if (offset > node.getContentLength()) {
logger.fatal('offset should be less than or equal to length');
}
if (offset === 0) {
return node;
} else if (offset === node.getContentLength()) {
return node.getNext();
}
const splitNode = node.split(offset);
this.treeByIndex.updateWeight(splitNode);
this.insertAfter(node, splitNode);
const insNext = node.getInsNext();
if (insNext) {
insNext.setInsPrev(splitNode);
}
splitNode.setInsPrev(node);
return splitNode;
}
private deleteNodes(
candidates: Array<RGATreeSplitNode<T>>,
editedAt: TimeTicket,
maxCreatedAtMapByActor?: Map<string, TimeTicket>,
): [
Array<ValueChange<T>>,
Map<string, TimeTicket>,
Map<string, RGATreeSplitNode<T>>,
] {
if (!candidates.length) {
return [[], new Map(), new Map()];
}
// There are 2 types of nodes in `candidates`: should delete, should not delete.
// `nodesToKeep` contains nodes should not delete,
// then is used to find the boundary of the range to be deleted.
const [nodesToDelete, nodesToKeep] = this.filterNodes(
candidates,
editedAt,
maxCreatedAtMapByActor,
);
const createdAtMapByActor = new Map();
const removedNodes = new Map();
// First we need to collect indexes for change.
const changes = this.makeChanges(nodesToKeep, editedAt);
for (const node of nodesToDelete) {
// Then make nodes be tombstones and map that.
const actorID = node.getCreatedAt().getActorID();
if (
!createdAtMapByActor.has(actorID) ||
node.getID().getCreatedAt().after(createdAtMapByActor.get(actorID))
) {
createdAtMapByActor.set(actorID, node.getID().getCreatedAt());
}
removedNodes.set(node.getID().toIDString(), node);
node.remove(editedAt);
}
// Finally remove index nodes of tombstones.
this.deleteIndexNodes(nodesToKeep);
return [changes, createdAtMapByActor, removedNodes];
}
private filterNodes(
candidates: Array<RGATreeSplitNode<T>>,
editedAt: TimeTicket,
maxCreatedAtMapByActor?: Map<string, TimeTicket>,
): [Array<RGATreeSplitNode<T>>, Array<RGATreeSplitNode<T> | undefined>] {
const isRemote = !!maxCreatedAtMapByActor;
const nodesToDelete: Array<RGATreeSplitNode<T>> = [];
const nodesToKeep: Array<RGATreeSplitNode<T> | undefined> = [];
const [leftEdge, rightEdge] = this.findEdgesOfCandidates(candidates);
nodesToKeep.push(leftEdge);
for (const node of candidates) {
const actorID = node.getCreatedAt().getActorID();
const maxCreatedAt = isRemote
? maxCreatedAtMapByActor!.has(actorID)
? maxCreatedAtMapByActor!.get(actorID)
: InitialTimeTicket
: MaxTimeTicket;
if (node.canDelete(editedAt, maxCreatedAt!)) {
nodesToDelete.push(node);
} else {
nodesToKeep.push(node);
}
}
nodesToKeep.push(rightEdge);
return [nodesToDelete, nodesToKeep];
}
/**
* `findEdgesOfCandidates` finds the edges outside `candidates`,
* (which has not already been deleted, or be undefined but not yet implemented)
* right edge is undefined means `candidates` contains the end of text.
*/
private findEdgesOfCandidates(
candidates: Array<RGATreeSplitNode<T>>,
): [RGATreeSplitNode<T>, RGATreeSplitNode<T> | undefined] {
return [
candidates[0].getPrev()!,
candidates[candidates.length - 1].getNext(),
];
}
private makeChanges(
boundaries: Array<RGATreeSplitNode<T> | undefined>,
editedAt: TimeTicket,
): Array<ValueChange<T>> {
const changes: Array<ValueChange<T>> = [];
let fromIdx: number, toIdx: number;
for (let i = 0; i < boundaries.length - 1; i++) {
const leftBoundary = boundaries[i];
const rightBoundary = boundaries[i + 1];
if (leftBoundary!.getNext() == rightBoundary) {
continue;
}
[fromIdx] = this.findIndexesFromRange(
leftBoundary!.getNext()!.createPosRange(),
);
if (rightBoundary) {
[, toIdx] = this.findIndexesFromRange(
rightBoundary.getPrev()!.createPosRange(),
);
} else {
toIdx = this.treeByIndex.length;
}
if (fromIdx < toIdx) {
changes.push({
actor: editedAt.getActorID(),
from: fromIdx,
to: toIdx,
});
}
}
return changes.reverse();
}
/**
* `deleteIndexNodes` clears the index nodes of the given deletion boundaries.
* The boundaries mean the nodes that will not be deleted in the range.
*/
private deleteIndexNodes(
boundaries: Array<RGATreeSplitNode<T> | undefined>,
): void {