-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
ValNode.ts
95 lines (83 loc) · 2.45 KB
/
ValNode.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
import {compare, ITimestampStruct, printTs} from '../../../json-crdt-patch/clock';
import {SESSION} from '../../../json-crdt-patch/constants';
import {printTree} from 'tree-dump/lib/printTree';
import {UNDEFINED} from '../../model/Model';
import type {JsonNode, JsonNodeView} from '..';
import type {Model} from '../../model';
import type {Printable} from 'tree-dump/lib/types';
/**
* Represents a `val` JSON CRDT node, which is a Last-write-wins (LWW) register.
* The `val` node holds a single value, which is a reference to another JSON
* CRDT node.
*
* @category CRDT Node
*/
export class ValNode<Value extends JsonNode = JsonNode> implements JsonNode<JsonNodeView<Value>>, Printable {
constructor(
/**
* @ignore
*/
public readonly doc: Model<any>,
public readonly id: ITimestampStruct,
/**
* The current value of the node, which is a reference to another JSON CRDT
* node.
*/
public val: ITimestampStruct,
) {}
/**
* @ignore
*/
public set(val: ITimestampStruct): ITimestampStruct | undefined {
if (compare(val, this.val) <= 0 && this.val.sid !== SESSION.SYSTEM) return;
if (compare(val, this.id) <= 0) return;
const oldVal = this.val;
this.val = val;
return oldVal;
}
/**
* Returns the latest value of the node, the JSON CRDT node that `val` points
* to.
*
* @returns The latest value of the node.
*/
public node(): Value {
return this.val.sid === SESSION.SYSTEM ? <any>UNDEFINED : this.child();
}
// ----------------------------------------------------------------- JsonNode
public view(): JsonNodeView<Value> {
return this.node()?.view() as JsonNodeView<Value>;
}
/**
* @ignore
*/
public children(callback: (node: Value) => void) {
callback(this.node());
}
/**
* @ignore
*/
public child(): Value {
return this.doc.index.get(this.val)! as Value;
}
/**
* @ignore
*/
public container(): JsonNode | undefined {
const child = this.node();
return child ? child.container() : undefined;
}
/**
* @ignore
*/
public api: undefined | unknown = undefined;
public name(): string {
return 'val';
}
// ---------------------------------------------------------------- Printable
public toString(tab: string = ''): string {
const node = this.node();
const header = this.name() + ' ' + printTs(this.id);
return header + printTree(tab, [(tab) => (node ? node.toString(tab) : printTs(this.val))]);
}
}