overleaf/services/web/frontend/js/features/file-tree/util/find-in-tree.js
Timothée Alby 420aa4a657 Merge pull request #3232 from overleaf/ta-file-tree-react
React File Tree

GitOrigin-RevId: fb3141ba8cd9ca0d68e87edb74764a360144c8fe
2020-11-27 03:05:05 +00:00

78 lines
1.7 KiB
JavaScript

export function findInTreeOrThrow(tree, id) {
const found = findInTree(tree, id)
if (found) return found
throw new Error(`Entity not found with id=${id}`)
}
export function findAllInTreeOrThrow(tree, ids) {
let list = new Set()
ids.forEach(id => {
list.add(findInTreeOrThrow(tree, id))
})
return list
}
export function findAllFolderIdsInFolder(folder) {
const list = new Set([folder._id])
for (const index in folder.folders) {
const subFolder = folder.folders[index]
findAllFolderIdsInFolder(subFolder).forEach(subFolderId => {
list.add(subFolderId)
})
}
return list
}
export function findAllFolderIdsInFolders(folders) {
let list = new Set()
folders.forEach(folder => {
findAllFolderIdsInFolder(folder).forEach(folderId => {
list.add(folderId)
})
})
return list
}
export function findInTree(tree, id) {
for (const index in tree.docs) {
const doc = tree.docs[index]
if (doc._id === id) {
return {
entity: doc,
type: 'doc',
parent: tree.docs,
parentFolderId: tree._id,
index
}
}
}
for (const index in tree.fileRefs) {
const file = tree.fileRefs[index]
if (file._id === id) {
return {
entity: file,
type: 'fileRef',
parent: tree.fileRefs,
parentFolderId: tree._id,
index
}
}
}
for (const index in tree.folders) {
const folder = tree.folders[index]
if (folder._id === id) {
return {
entity: folder,
type: 'folder',
parent: tree.folders,
parentFolderId: tree._id,
index
}
}
const found = findInTree(folder, id)
if (found) return found
}
return null
}