Skip to content

Commit

Permalink
Add toJS to return TreeNode of Tree (#639)
Browse files Browse the repository at this point in the history
Co-authored-by: Youngteac Hong <susukang98@gmail.com>
  • Loading branch information
JOOHOJANG and hackerwins authored Sep 12, 2023
1 parent 876d3dc commit 37c332f
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 5 deletions.
17 changes: 12 additions & 5 deletions src/document/crdt/tree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -453,9 +453,9 @@ export class CRDTTreeNode extends IndexTreeNode<CRDTTreeNode> {
}

/**
* toJSON converts the given CRDTNode to JSON.
* toTreeNode converts the given CRDTTreeNode to TreeNode.
*/
function toJSON(node: CRDTTreeNode): TreeNode {
function toTreeNode(node: CRDTTreeNode): TreeNode {
if (node.isText) {
const currentNode = node;
return {
Expand All @@ -466,7 +466,7 @@ function toJSON(node: CRDTTreeNode): TreeNode {

return {
type: node.type,
children: node.children.map(toJSON),
children: node.children.map(toTreeNode),
attributes: node.attrs
? parseObjectValues(node.attrs?.toObject())
: undefined,
Expand Down Expand Up @@ -679,7 +679,7 @@ export class CRDTTree extends CRDTGCElement {
toPath: this.toPath(toParent, toLeft),
actor: editedAt.getActorID()!,
value: contents?.length
? contents.map((content) => toJSON(content))
? contents.map((content) => toTreeNode(content))
: undefined,
});

Expand Down Expand Up @@ -951,7 +951,14 @@ export class CRDTTree extends CRDTGCElement {
* `toJSON` returns the JSON encoding of this tree.
*/
public toJSON(): string {
return JSON.stringify(toJSON(this.indexTree.getRoot()));
return JSON.stringify(this.getRootTreeNode());
}

/**
* `getRootTreeNode` returns the converted value of this tree to TreeNode.
*/
public getRootTreeNode(): TreeNode {
return toTreeNode(this.indexTree.getRoot());
}

/**
Expand Down
11 changes: 11 additions & 0 deletions src/document/json/tree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -471,6 +471,17 @@ export class Tree {
return this.tree.toJSON();
}

/**
* `getRootTreeNode` returns TreeNode of this tree.
*/
public getRootTreeNode() {
if (!this.context || !this.tree) {
throw new Error('it is not initialized yet');
}

return this.tree.getRootTreeNode();
}

/**
* `indexToPath` returns the path of the given index.
*/
Expand Down

0 comments on commit 37c332f

Please sign in to comment.