diff --git a/src/utils/general.ts b/src/utils/general.ts index 5705670..d4cba23 100644 --- a/src/utils/general.ts +++ b/src/utils/general.ts @@ -48,17 +48,36 @@ export function friendlyFormatShortcut(shortcut?: string) { } } +/** + * if item's name matches path, return self-depth of the item + * else return 0 + */ +function measureDistance(item: TreeNode, path: TreeNode['name'][]): number { + const pathString = path.join('/') + if (item.name.indexOf(pathString + '/') === 0) { + // If accessing a leading item of compressed node, path will be shorter than item.name + return path.length + } else if (pathString === item.name || pathString.indexOf(item.name + '/') === 0) { + return item.name.split('/').length + } + return 0 +} + +/** + * look for the first item matches given path under root.content + */ export function findNode( root: TreeNode, - path: string[], + path: TreeNode['name'][], callback?: (node: TreeNode) => void, ): TreeNode | undefined { if (Array.isArray(root.contents)) { - for (const content of root.contents) { - if (content.name === path[0]) { - if (callback) callback(content) - if (path.length === 1) return content - return findNode(content, path.slice(1), callback) + for (const item of root.contents) { + const distance = measureDistance(item, path) + if (distance > 0) { + if (callback) callback(item) + if (path.length === distance) return item + return findNode(item, path.slice(distance), callback) } } }