find-in-tree.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import OError from '@overleaf/o-error'
  2. export function findInTreeOrThrow(tree, id) {
  3. const found = findInTree(tree, id)
  4. if (found) return found
  5. throw new OError('Entity not found in tree', { entityId: id })
  6. }
  7. export function findAllInTreeOrThrow(tree, ids) {
  8. const list = new Set()
  9. ids.forEach(id => {
  10. list.add(findInTreeOrThrow(tree, id))
  11. })
  12. return list
  13. }
  14. export function findAllFolderIdsInFolder(folder) {
  15. const list = new Set([folder._id])
  16. for (const index in folder.folders) {
  17. const subFolder = folder.folders[index]
  18. findAllFolderIdsInFolder(subFolder).forEach(subFolderId => {
  19. list.add(subFolderId)
  20. })
  21. }
  22. return list
  23. }
  24. export function findAllFolderIdsInFolders(folders) {
  25. const list = new Set()
  26. folders.forEach(folder => {
  27. findAllFolderIdsInFolder(folder).forEach(folderId => {
  28. list.add(folderId)
  29. })
  30. })
  31. return list
  32. }
  33. export function findInTree(tree, id, path) {
  34. if (!path) {
  35. path = [tree._id]
  36. }
  37. for (const index in tree.docs) {
  38. const doc = tree.docs[index]
  39. if (doc._id === id) {
  40. return {
  41. entity: doc,
  42. type: 'doc',
  43. parent: tree.docs,
  44. parentFolderId: tree._id,
  45. path,
  46. index,
  47. }
  48. }
  49. }
  50. for (const index in tree.fileRefs) {
  51. const file = tree.fileRefs[index]
  52. if (file._id === id) {
  53. return {
  54. entity: file,
  55. type: 'fileRef',
  56. parent: tree.fileRefs,
  57. parentFolderId: tree._id,
  58. path,
  59. index,
  60. }
  61. }
  62. }
  63. for (const index in tree.folders) {
  64. const folder = tree.folders[index]
  65. if (folder._id === id) {
  66. return {
  67. entity: folder,
  68. type: 'folder',
  69. parent: tree.folders,
  70. parentFolderId: tree._id,
  71. path,
  72. index,
  73. }
  74. }
  75. const found = findInTree(folder, id, path.concat(folder._id))
  76. if (found) return found
  77. }
  78. return null
  79. }