Skip to content

Commit

Permalink
Add toJS to return TreeNode of Tree (#115)
Browse files Browse the repository at this point in the history
* Add toJS to return TreeNode of Tree

* linting
  • Loading branch information
humdrum authored Sep 25, 2023
1 parent 38ea3c2 commit 0690620
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 5 deletions.
17 changes: 12 additions & 5 deletions Sources/Document/CRDT/CRDTTree.swift
Original file line number Diff line number Diff line change
Expand Up @@ -359,15 +359,15 @@ final class CRDTTreeNode: IndexTreeNode {
}

/**
* toJSON converts the given CRDTNode to JSON.
* `toTreeNode` converts the given CRDTTreeNode to TreeNode.
*/
var toJSON: TreeNode {
var toTreeNode: TreeNode {
if self.isText {
return TreeNode(type: self.type, value: self.value)
}

let children = self.children.compactMap {
$0.toJSON
$0.toTreeNode
}

let attrs = self.attrs?.toObject().mapValues { $0.value }
Expand Down Expand Up @@ -592,7 +592,7 @@ class CRDTTree: CRDTGCElement {

var value: TreeChangeValue?

if let nodes = contents?.compactMap({ $0.toJSON }) {
if let nodes = contents?.compactMap({ $0.toTreeNode }) {
value = .nodes(nodes)
}

Expand Down Expand Up @@ -849,7 +849,14 @@ class CRDTTree: CRDTGCElement {
* `toJSON` returns the JSON encoding of this tree.
*/
func toJSON() -> String {
self.indexTree.root.toJSON.toJSONString
self.rootTreeNode.toJSONString
}

/**
* `rootTreeNode` returns the converted value of this tree to TreeNode.
*/
var rootTreeNode: TreeNode {
self.indexTree.root.toTreeNode
}

/**
Expand Down
11 changes: 11 additions & 0 deletions Sources/Document/Json/JSONTree.swift
Original file line number Diff line number Diff line change
Expand Up @@ -420,6 +420,17 @@ public class JSONTree {
return tree.toJSON()
}

/**
* `getRootTreeNode` returns TreeNode of this tree.
*/
public func getRootTreeNode() throws -> TreeNode? {
guard self.context != nil, let tree else {
throw YorkieError.unexpected(message: "it is not initialized yet")
}

return tree.rootTreeNode
}

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

0 comments on commit 0690620

Please sign in to comment.