notion-page-tree
Version:
Recursively fetch nested Notion pages from the root page/database/block node.
54 lines (53 loc) • 1.92 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.cutSubtreeToDepth = exports.retrieveSubtree = void 0;
/**
* Find child with id and retrieve its subtree to some depth.
* @param root Root entity to search from.
* @param id Id of target child to search for.
* @param maxDepth Depth of target child's own children. If undefined, retrieve the full subtree.
* @returns Subtree from child to some depth/
*/
var retrieveSubtree = function (root, id, maxDepth) {
// find subtree
var subTree = findSubtreeWithId(root, id);
// console.log('subtree', subTree?.id, subTree?.children);
var result = subTree
? maxDepth === undefined
? subTree
: (0, exports.cutSubtreeToDepth)(subTree, maxDepth)
: root;
// console.log('result', result.id, result.children);
return result;
};
exports.retrieveSubtree = retrieveSubtree;
var findSubtreeWithId = function (root, id) {
// BFS
var search_queue = [];
var subtree = undefined;
search_queue.push(root);
while (search_queue.length > 0 && subtree === undefined) {
var current = search_queue.splice(0, 1)[0];
if (current.id === id)
return (subtree = current);
search_queue.push.apply(search_queue, current.children);
}
return subtree;
};
var cutSubtreeToDepth = function (root, maxDepth, _currentDepth) {
if (_currentDepth === void 0) { _currentDepth = 0; }
// DFS
if (_currentDepth >= maxDepth) {
root.children = root.children.map(function (ownChild) {
return typeof ownChild === 'string' ? ownChild : ownChild.id;
});
}
else {
root.children &&
root.children.forEach(function (child) {
(0, exports.cutSubtreeToDepth)(child, maxDepth, _currentDepth + 1);
});
}
return root;
};
exports.cutSubtreeToDepth = cutSubtreeToDepth;