Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add toJS to return TreeNode of Tree #639

Merged
merged 5 commits into from
Sep 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -678,7 +678,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 @@ -950,7 +950,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