file-tree-data-context.tsx 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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 = ({ children }) => {
  161. const [project] = useScopeValue<Project>('project')
  162. const [currentDocumentId] = useScopeValue('editor.open_doc_id')
  163. const [, setOpenDocName] = useScopeValueSetterOnly('editor.open_doc_name')
  164. const [permissionsLevel] = useScopeValue('permissionsLevel')
  165. const { fileTreeFromHistory, snapshot, snapshotVersion } =
  166. useSnapshotContext()
  167. const fileTreeReadOnly =
  168. permissionsLevel === 'readOnly' || fileTreeFromHistory
  169. const [rootFolder, setRootFolder] = useState(project?.rootFolder)
  170. useEffect(() => {
  171. if (fileTreeFromHistory) return
  172. setRootFolder(project?.rootFolder)
  173. }, [project, fileTreeFromHistory])
  174. useEffect(() => {
  175. if (!fileTreeFromHistory) return
  176. if (!rootFolder || rootFolder?.[0]?._id) {
  177. // Init or replace mongo rootFolder with stub while we load the snapshot.
  178. // In the future, project:joined should only fire once the snapshot is ready.
  179. setRootFolder([createFolder('', '')])
  180. }
  181. }, [fileTreeFromHistory, rootFolder])
  182. useEffect(() => {
  183. if (!fileTreeFromHistory || !snapshot) return
  184. setRootFolder([buildFileTree(snapshot)])
  185. }, [fileTreeFromHistory, snapshot, snapshotVersion])
  186. const [{ fileTreeData, fileCount }, dispatch] = useReducer(
  187. fileTreeMutableReducer,
  188. rootFolder,
  189. initialState
  190. )
  191. const [selectedEntities, setSelectedEntities] = useState<FindResult[]>([])
  192. const docs = useMemo(
  193. () => (fileTreeData ? docsInFolder(fileTreeData) : undefined),
  194. [fileTreeData]
  195. )
  196. useDeepCompareEffect(() => {
  197. dispatch({
  198. type: ACTION_TYPES.RESET,
  199. fileTreeData: rootFolder?.[0],
  200. })
  201. }, [rootFolder])
  202. const dispatchCreateFolder = useCallback((parentFolderId, entity) => {
  203. entity.type = 'folder'
  204. dispatch({
  205. type: ACTION_TYPES.CREATE,
  206. parentFolderId,
  207. entity,
  208. })
  209. }, [])
  210. const dispatchCreateDoc = useCallback(
  211. (parentFolderId: string, entity: any) => {
  212. entity.type = 'doc'
  213. dispatch({
  214. type: ACTION_TYPES.CREATE,
  215. parentFolderId,
  216. entity,
  217. })
  218. },
  219. []
  220. )
  221. const dispatchCreateFile = useCallback(
  222. (parentFolderId: string, entity: any) => {
  223. entity.type = 'fileRef'
  224. dispatch({
  225. type: ACTION_TYPES.CREATE,
  226. parentFolderId,
  227. entity,
  228. })
  229. },
  230. []
  231. )
  232. const dispatchRename = useCallback(
  233. (id: string, newName: string) => {
  234. dispatch({
  235. type: ACTION_TYPES.RENAME,
  236. newName,
  237. id,
  238. })
  239. if (id === currentDocumentId) {
  240. setOpenDocName(newName)
  241. }
  242. },
  243. [currentDocumentId, setOpenDocName]
  244. )
  245. const dispatchDelete = useCallback((id: string) => {
  246. dispatch({ type: ACTION_TYPES.DELETE, id })
  247. }, [])
  248. const dispatchMove = useCallback((entityId: string, toFolderId: string) => {
  249. dispatch({ type: ACTION_TYPES.MOVE, entityId, toFolderId })
  250. }, [])
  251. const value = useMemo(() => {
  252. return {
  253. dispatchCreateDoc,
  254. dispatchCreateFile,
  255. dispatchCreateFolder,
  256. dispatchDelete,
  257. dispatchMove,
  258. dispatchRename,
  259. fileCount,
  260. fileTreeData,
  261. fileTreeReadOnly,
  262. hasFolders: fileTreeData?.folders.length > 0,
  263. selectedEntities,
  264. setSelectedEntities,
  265. docs,
  266. }
  267. }, [
  268. dispatchCreateDoc,
  269. dispatchCreateFile,
  270. dispatchCreateFolder,
  271. dispatchDelete,
  272. dispatchMove,
  273. dispatchRename,
  274. fileCount,
  275. fileTreeData,
  276. fileTreeReadOnly,
  277. selectedEntities,
  278. setSelectedEntities,
  279. docs,
  280. ])
  281. return (
  282. <FileTreeDataContext.Provider value={value}>
  283. {children}
  284. </FileTreeDataContext.Provider>
  285. )
  286. }