Skip to content

Commit 37c332f

Browse files
Add toJS to return TreeNode of Tree (#639)
Co-authored-by: Youngteac Hong <susukang98@gmail.com>
1 parent 876d3dc commit 37c332f

File tree

2 files changed

+23
-5
lines changed

2 files changed

+23
-5
lines changed

src/document/crdt/tree.ts

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -453,9 +453,9 @@ export class CRDTTreeNode extends IndexTreeNode<CRDTTreeNode> {
453453
}
454454

455455
/**
456-
* toJSON converts the given CRDTNode to JSON.
456+
* toTreeNode converts the given CRDTTreeNode to TreeNode.
457457
*/
458-
function toJSON(node: CRDTTreeNode): TreeNode {
458+
function toTreeNode(node: CRDTTreeNode): TreeNode {
459459
if (node.isText) {
460460
const currentNode = node;
461461
return {
@@ -466,7 +466,7 @@ function toJSON(node: CRDTTreeNode): TreeNode {
466466

467467
return {
468468
type: node.type,
469-
children: node.children.map(toJSON),
469+
children: node.children.map(toTreeNode),
470470
attributes: node.attrs
471471
? parseObjectValues(node.attrs?.toObject())
472472
: undefined,
@@ -679,7 +679,7 @@ export class CRDTTree extends CRDTGCElement {
679679
toPath: this.toPath(toParent, toLeft),
680680
actor: editedAt.getActorID()!,
681681
value: contents?.length
682-
? contents.map((content) => toJSON(content))
682+
? contents.map((content) => toTreeNode(content))
683683
: undefined,
684684
});
685685

@@ -951,7 +951,14 @@ export class CRDTTree extends CRDTGCElement {
951951
* `toJSON` returns the JSON encoding of this tree.
952952
*/
953953
public toJSON(): string {
954-
return JSON.stringify(toJSON(this.indexTree.getRoot()));
954+
return JSON.stringify(this.getRootTreeNode());
955+
}
956+
957+
/**
958+
* `getRootTreeNode` returns the converted value of this tree to TreeNode.
959+
*/
960+
public getRootTreeNode(): TreeNode {
961+
return toTreeNode(this.indexTree.getRoot());
955962
}
956963

957964
/**

src/document/json/tree.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -471,6 +471,17 @@ export class Tree {
471471
return this.tree.toJSON();
472472
}
473473

474+
/**
475+
* `getRootTreeNode` returns TreeNode of this tree.
476+
*/
477+
public getRootTreeNode() {
478+
if (!this.context || !this.tree) {
479+
throw new Error('it is not initialized yet');
480+
}
481+
482+
return this.tree.getRootTreeNode();
483+
}
484+
474485
/**
475486
* `indexToPath` returns the path of the given index.
476487
*/

0 commit comments

Comments
 (0)