find-in-tree.ts 2.2 KB

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