file-tree-data-context.tsx 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. import {
  2. createContext,
  3. useCallback,
  4. useReducer,
  5. useContext,
  6. useMemo,
  7. useState,
  8. FC,
  9. useEffect,
  10. } from 'react'
  11. import useScopeValue from '../hooks/use-scope-value'
  12. import {
  13. renameInTree,
  14. deleteInTree,
  15. moveInTree,
  16. createEntityInTree,
  17. } from '../../features/file-tree/util/mutate-in-tree'
  18. import { countFiles } from '../../features/file-tree/util/count-in-tree'
  19. import useDeepCompareEffect from '../../shared/hooks/use-deep-compare-effect'
  20. import { docsInFolder } from '@/features/file-tree/util/docs-in-folder'
  21. import useScopeValueSetterOnly from '@/shared/hooks/use-scope-value-setter-only'
  22. import { Folder } from '../../../../types/folder'
  23. import { Project } from '../../../../types/project'
  24. import { MainDocument } from '../../../../types/project-settings'
  25. import { FindResult } from '@/features/file-tree/util/path'
  26. import {
  27. StubSnapshotUtils,
  28. useSnapshotContext,
  29. } from '@/features/ide-react/context/snapshot-context'
  30. import importOverleafModules from '../../../macros/import-overleaf-module.macro'
  31. const { buildFileTree, createFolder } =
  32. (importOverleafModules('snapshotUtils')[0]
  33. ?.import as typeof StubSnapshotUtils) || StubSnapshotUtils
  34. const FileTreeDataContext = createContext<
  35. | {
  36. // fileTreeData is the up-to-date representation of the files list, updated
  37. // by the file tree
  38. fileTreeData: Folder
  39. fileCount: { value: number; status: string; limit: number } | number
  40. fileTreeReadOnly: boolean
  41. hasFolders: boolean
  42. selectedEntities: FindResult[]
  43. setSelectedEntities: (selectedEntities: FindResult[]) => void
  44. dispatchRename: (id: string, name: string) => void
  45. dispatchMove: (id: string, target: string) => void
  46. dispatchDelete: (id: string) => void
  47. dispatchCreateFolder: (name: string, folder: any) => void
  48. dispatchCreateDoc: (name: string, doc: any) => void
  49. dispatchCreateFile: (name: string, file: any) => void
  50. docs?: MainDocument[]
  51. }
  52. | undefined
  53. >(undefined)
  54. /* eslint-disable no-unused-vars */
  55. enum ACTION_TYPES {
  56. RENAME = 'RENAME',
  57. RESET = 'RESET',
  58. DELETE = 'DELETE',
  59. MOVE = 'MOVE',
  60. CREATE = 'CREATE',
  61. }
  62. /* eslint-enable no-unused-vars */
  63. type Action =
  64. | {
  65. type: ACTION_TYPES.RESET
  66. fileTreeData?: Folder
  67. }
  68. | {
  69. type: ACTION_TYPES.RENAME
  70. id: string
  71. newName: string
  72. }
  73. | {
  74. type: ACTION_TYPES.DELETE
  75. id: string
  76. }
  77. | {
  78. type: ACTION_TYPES.MOVE
  79. entityId: string
  80. toFolderId: string
  81. }
  82. | {
  83. type: typeof ACTION_TYPES.CREATE
  84. parentFolderId: string
  85. entity: any // TODO
  86. }
  87. function fileTreeMutableReducer(
  88. { fileTreeData }: { fileTreeData: Folder },
  89. action: Action
  90. ) {
  91. switch (action.type) {
  92. case ACTION_TYPES.RESET: {
  93. const newFileTreeData = action.fileTreeData
  94. return {
  95. fileTreeData: newFileTreeData,
  96. fileCount: countFiles(newFileTreeData),
  97. }
  98. }
  99. case ACTION_TYPES.RENAME: {
  100. const newFileTreeData = renameInTree(fileTreeData, action.id, {
  101. newName: action.newName,
  102. })
  103. return {
  104. fileTreeData: newFileTreeData,
  105. fileCount: countFiles(newFileTreeData),
  106. }
  107. }
  108. case ACTION_TYPES.DELETE: {
  109. const newFileTreeData = deleteInTree(fileTreeData, action.id)
  110. return {
  111. fileTreeData: newFileTreeData,
  112. fileCount: countFiles(newFileTreeData),
  113. }
  114. }
  115. case ACTION_TYPES.MOVE: {
  116. const newFileTreeData = moveInTree(
  117. fileTreeData,
  118. action.entityId,
  119. action.toFolderId
  120. )
  121. return {
  122. fileTreeData: newFileTreeData,
  123. fileCount: countFiles(newFileTreeData),
  124. }
  125. }
  126. case ACTION_TYPES.CREATE: {
  127. const newFileTreeData = createEntityInTree(
  128. fileTreeData,
  129. action.parentFolderId,
  130. action.entity
  131. )
  132. return {
  133. fileTreeData: newFileTreeData,
  134. fileCount: countFiles(newFileTreeData),
  135. }
  136. }
  137. default: {
  138. throw new Error(
  139. `Unknown mutable file tree action type: ${(action as Action).type}`
  140. )
  141. }
  142. }
  143. }
  144. const initialState = (rootFolder?: Folder[]) => {
  145. const fileTreeData = rootFolder?.[0]
  146. return {
  147. fileTreeData,
  148. fileCount: countFiles(fileTreeData),
  149. }
  150. }
  151. export function useFileTreeData() {
  152. const context = useContext(FileTreeDataContext)
  153. if (!context) {
  154. throw new Error(
  155. 'useFileTreeData is only available inside FileTreeDataProvider'
  156. )
  157. }
  158. return context
  159. }
  160. export const FileTreeDataProvider: FC<React.PropsWithChildren> = ({
  161. children,
  162. }) => {
  163. const [project] = useScopeValue<Project>('project')
  164. const [currentDocumentId] = useScopeValue('editor.open_doc_id')
  165. const [, setOpenDocName] = useScopeValueSetterOnly('editor.open_doc_name')
  166. const [permissionsLevel] = useScopeValue('permissionsLevel')
  167. const { fileTreeFromHistory, snapshot, snapshotVersion } =
  168. useSnapshotContext()
  169. const fileTreeReadOnly =
  170. permissionsLevel === 'readOnly' || fileTreeFromHistory
  171. const [rootFolder, setRootFolder] = useState(project?.rootFolder)
  172. useEffect(() => {
  173. if (fileTreeFromHistory) return
  174. setRootFolder(project?.rootFolder)
  175. }, [project, fileTreeFromHistory])
  176. useEffect(() => {
  177. if (!fileTreeFromHistory) return
  178. if (!rootFolder || rootFolder?.[0]?._id) {
  179. // Init or replace mongo rootFolder with stub while we load the snapshot.
  180. // In the future, project:joined should only fire once the snapshot is ready.
  181. setRootFolder([createFolder('', '')])
  182. }
  183. }, [fileTreeFromHistory, rootFolder])
  184. useEffect(() => {
  185. if (!fileTreeFromHistory || !snapshot) return
  186. setRootFolder([buildFileTree(snapshot)])
  187. }, [fileTreeFromHistory, snapshot, snapshotVersion])
  188. const [{ fileTreeData, fileCount }, dispatch] = useReducer(
  189. fileTreeMutableReducer,
  190. rootFolder,
  191. initialState
  192. )
  193. const [selectedEntities, setSelectedEntities] = useState<FindResult[]>([])
  194. const docs = useMemo(
  195. () => (fileTreeData ? docsInFolder(fileTreeData) : undefined),
  196. [fileTreeData]
  197. )
  198. useDeepCompareEffect(() => {
  199. dispatch({
  200. type: ACTION_TYPES.RESET,
  201. fileTreeData: rootFolder?.[0],
  202. })
  203. }, [rootFolder])
  204. const dispatchCreateFolder = useCallback(
  205. (parentFolderId: string, entity: any) => {
  206. entity.type = 'folder'
  207. dispatch({
  208. type: ACTION_TYPES.CREATE,
  209. parentFolderId,
  210. entity,
  211. })
  212. },
  213. []
  214. )
  215. const dispatchCreateDoc = useCallback(
  216. (parentFolderId: string, entity: any) => {
  217. entity.type = 'doc'
  218. dispatch({
  219. type: ACTION_TYPES.CREATE,
  220. parentFolderId,
  221. entity,
  222. })
  223. },
  224. []
  225. )
  226. const dispatchCreateFile = useCallback(
  227. (parentFolderId: string, entity: any) => {
  228. entity.type = 'fileRef'
  229. dispatch({
  230. type: ACTION_TYPES.CREATE,
  231. parentFolderId,
  232. entity,
  233. })
  234. },
  235. []
  236. )
  237. const dispatchRename = useCallback(
  238. (id: string, newName: string) => {
  239. dispatch({
  240. type: ACTION_TYPES.RENAME,
  241. newName,
  242. id,
  243. })
  244. if (id === currentDocumentId) {
  245. setOpenDocName(newName)
  246. }
  247. },
  248. [currentDocumentId, setOpenDocName]
  249. )
  250. const dispatchDelete = useCallback((id: string) => {
  251. dispatch({ type: ACTION_TYPES.DELETE, id })
  252. }, [])
  253. const dispatchMove = useCallback((entityId: string, toFolderId: string) => {
  254. dispatch({ type: ACTION_TYPES.MOVE, entityId, toFolderId })
  255. }, [])
  256. const value = useMemo(() => {
  257. return {
  258. dispatchCreateDoc,
  259. dispatchCreateFile,
  260. dispatchCreateFolder,
  261. dispatchDelete,
  262. dispatchMove,
  263. dispatchRename,
  264. fileCount,
  265. fileTreeData,
  266. fileTreeReadOnly,
  267. hasFolders: fileTreeData?.folders.length > 0,
  268. selectedEntities,
  269. setSelectedEntities,
  270. docs,
  271. }
  272. }, [
  273. dispatchCreateDoc,
  274. dispatchCreateFile,
  275. dispatchCreateFolder,
  276. dispatchDelete,
  277. dispatchMove,
  278. dispatchRename,
  279. fileCount,
  280. fileTreeData,
  281. fileTreeReadOnly,
  282. selectedEntities,
  283. setSelectedEntities,
  284. docs,
  285. ])
  286. return (
  287. <FileTreeDataContext.Provider value={value}>
  288. {children}
  289. </FileTreeDataContext.Provider>
  290. )
  291. }