file-tree-actionable.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  1. import {
  2. createContext,
  3. useCallback,
  4. useMemo,
  5. useReducer,
  6. useContext,
  7. useEffect,
  8. useState,
  9. FC,
  10. } from 'react'
  11. import { mapSeries } from '../../../infrastructure/promise'
  12. import {
  13. syncRename,
  14. syncDelete,
  15. syncMove,
  16. syncCreateEntity,
  17. } from '../util/sync-mutation'
  18. import { findInTree, findInTreeOrThrow } from '../util/find-in-tree'
  19. import { isNameUniqueInFolder } from '../util/is-name-unique-in-folder'
  20. import { isBlockedFilename, isCleanFilename } from '../util/safe-path'
  21. import { useProjectContext } from '../../../shared/context/project-context'
  22. import { useFileTreeData } from '../../../shared/context/file-tree-data-context'
  23. import { useFileTreeSelectable } from './file-tree-selectable'
  24. import {
  25. InvalidFilenameError,
  26. BlockedFilenameError,
  27. DuplicateFilenameError,
  28. DuplicateFilenameMoveError,
  29. } from '../errors'
  30. import { Folder } from '../../../../../types/folder'
  31. import { useReferencesContext } from '@/features/ide-react/context/references-context'
  32. import { usePermissionsContext } from '@/features/ide-react/context/permissions-context'
  33. import { fileUrl } from '@/features/utils/fileUrl'
  34. type DroppedFile = File & {
  35. relativePath?: string
  36. }
  37. type DroppedFiles = {
  38. files: DroppedFile[]
  39. targetFolderId: string
  40. }
  41. const FileTreeActionableContext = createContext<
  42. | {
  43. isDeleting: boolean
  44. isRenaming: boolean
  45. isCreatingFile: boolean
  46. isCreatingFolder: boolean
  47. isMoving: boolean
  48. inFlight: boolean
  49. actionedEntities: any | null
  50. newFileCreateMode: any | null
  51. error: any | null
  52. canDelete: boolean
  53. canRename: boolean
  54. canCreate: boolean
  55. parentFolderId: string
  56. selectedFileName: string | null | undefined
  57. isDuplicate: (parentFolderId: string, name: string) => boolean
  58. startRenaming: any
  59. finishRenaming: any
  60. startDeleting: any
  61. finishDeleting: any
  62. finishMoving: any
  63. startCreatingFile: any
  64. startCreatingFolder: any
  65. finishCreatingFolder: any
  66. startCreatingDocOrFile: any
  67. startUploadingDocOrFile: any
  68. finishCreatingDoc: any
  69. finishCreatingLinkedFile: any
  70. cancel: () => void
  71. droppedFiles: { files: File[]; targetFolderId: string } | null
  72. setDroppedFiles: (value: DroppedFiles | null) => void
  73. downloadPath?: string
  74. }
  75. | undefined
  76. >(undefined)
  77. /* eslint-disable no-unused-vars */
  78. enum ACTION_TYPES {
  79. START_RENAME = 'START_RENAME',
  80. START_DELETE = 'START_DELETE',
  81. DELETING = 'DELETING',
  82. START_CREATE_FILE = 'START_CREATE_FILE',
  83. START_CREATE_FOLDER = 'START_CREATE_FOLDER',
  84. CREATING_FILE = 'CREATING_FILE',
  85. CREATING_FOLDER = 'CREATING_FOLDER',
  86. MOVING = 'MOVING',
  87. CANCEL = 'CANCEL',
  88. CLEAR = 'CLEAR',
  89. ERROR = 'ERROR',
  90. }
  91. /* eslint-enable no-unused-vars */
  92. type State = {
  93. isDeleting: boolean
  94. isRenaming: boolean
  95. isCreatingFile: boolean
  96. isCreatingFolder: boolean
  97. isMoving: boolean
  98. inFlight: boolean
  99. actionedEntities: any | null
  100. newFileCreateMode: any | null
  101. error: unknown | null
  102. }
  103. const defaultState: State = {
  104. isDeleting: false,
  105. isRenaming: false,
  106. isCreatingFile: false,
  107. isCreatingFolder: false,
  108. isMoving: false,
  109. inFlight: false,
  110. actionedEntities: null,
  111. newFileCreateMode: null,
  112. error: null,
  113. }
  114. function fileTreeActionableReadOnlyReducer(state: State) {
  115. return state
  116. }
  117. type Action =
  118. | {
  119. type: ACTION_TYPES.START_RENAME
  120. }
  121. | {
  122. type: ACTION_TYPES.START_DELETE
  123. actionedEntities: any | null
  124. }
  125. | {
  126. type: ACTION_TYPES.START_CREATE_FILE
  127. newFileCreateMode: any | null
  128. }
  129. | {
  130. type: ACTION_TYPES.START_CREATE_FOLDER
  131. }
  132. | {
  133. type: ACTION_TYPES.CREATING_FILE
  134. }
  135. | {
  136. type: ACTION_TYPES.CREATING_FOLDER
  137. }
  138. | {
  139. type: ACTION_TYPES.DELETING
  140. }
  141. | {
  142. type: ACTION_TYPES.MOVING
  143. }
  144. | {
  145. type: ACTION_TYPES.CLEAR
  146. }
  147. | {
  148. type: ACTION_TYPES.CANCEL
  149. }
  150. | {
  151. type: ACTION_TYPES.ERROR
  152. error: unknown
  153. }
  154. function fileTreeActionableReducer(state: State, action: Action) {
  155. switch (action.type) {
  156. case ACTION_TYPES.START_RENAME:
  157. return { ...defaultState, isRenaming: true }
  158. case ACTION_TYPES.START_DELETE:
  159. return {
  160. ...defaultState,
  161. isDeleting: true,
  162. actionedEntities: action.actionedEntities,
  163. }
  164. case ACTION_TYPES.START_CREATE_FILE:
  165. return {
  166. ...defaultState,
  167. isCreatingFile: true,
  168. newFileCreateMode: action.newFileCreateMode,
  169. }
  170. case ACTION_TYPES.START_CREATE_FOLDER:
  171. return { ...defaultState, isCreatingFolder: true }
  172. case ACTION_TYPES.CREATING_FILE:
  173. return {
  174. ...defaultState,
  175. isCreatingFile: true,
  176. newFileCreateMode: state.newFileCreateMode,
  177. inFlight: true,
  178. }
  179. case ACTION_TYPES.CREATING_FOLDER:
  180. return { ...defaultState, isCreatingFolder: true, inFlight: true }
  181. case ACTION_TYPES.DELETING:
  182. // keep `actionedEntities` so the entities list remains displayed in the
  183. // delete modal
  184. return {
  185. ...defaultState,
  186. isDeleting: true,
  187. inFlight: true,
  188. actionedEntities: state.actionedEntities,
  189. }
  190. case ACTION_TYPES.MOVING:
  191. return {
  192. ...defaultState,
  193. isMoving: true,
  194. inFlight: true,
  195. }
  196. case ACTION_TYPES.CLEAR:
  197. return { ...defaultState }
  198. case ACTION_TYPES.CANCEL:
  199. if (state.inFlight) return state
  200. return { ...defaultState }
  201. case ACTION_TYPES.ERROR:
  202. return { ...state, inFlight: false, error: action.error }
  203. default:
  204. throw new Error(`Unknown user action type: ${(action as Action).type}`)
  205. }
  206. }
  207. export const FileTreeActionableProvider: FC = ({ children }) => {
  208. const { _id: projectId } = useProjectContext()
  209. const { fileTreeReadOnly } = useFileTreeData()
  210. const { indexAllReferences } = useReferencesContext()
  211. const { write } = usePermissionsContext()
  212. const [state, dispatch] = useReducer(
  213. fileTreeReadOnly
  214. ? fileTreeActionableReadOnlyReducer
  215. : fileTreeActionableReducer,
  216. defaultState
  217. )
  218. const { fileTreeData, dispatchRename, dispatchMove } = useFileTreeData()
  219. const { selectedEntityIds, isRootFolderSelected } = useFileTreeSelectable()
  220. const [droppedFiles, setDroppedFiles] = useState<DroppedFiles | null>(null)
  221. const startRenaming = useCallback(() => {
  222. dispatch({ type: ACTION_TYPES.START_RENAME })
  223. }, [])
  224. // update the entity with the new name immediately in the tree, but revert to
  225. // the old name if the sync fails
  226. const finishRenaming = useCallback(
  227. (newName: string) => {
  228. const selectedEntityId = Array.from(selectedEntityIds)[0]
  229. const found = findInTreeOrThrow(fileTreeData, selectedEntityId)
  230. const oldName = found.entity.name
  231. if (newName === oldName) {
  232. return dispatch({ type: ACTION_TYPES.CLEAR })
  233. }
  234. const error = validateRename(fileTreeData, found, newName)
  235. if (error) return dispatch({ type: ACTION_TYPES.ERROR, error })
  236. dispatch({ type: ACTION_TYPES.CLEAR })
  237. dispatchRename(selectedEntityId, newName)
  238. return syncRename(projectId, found.type, found.entity._id, newName).catch(
  239. error => {
  240. dispatchRename(selectedEntityId, oldName)
  241. // The state from this error action isn't used anywhere right now
  242. // but we need to handle the error for linting
  243. dispatch({ type: ACTION_TYPES.ERROR, error })
  244. }
  245. )
  246. },
  247. [dispatchRename, fileTreeData, projectId, selectedEntityIds]
  248. )
  249. const isDuplicate = useCallback(
  250. (parentFolderId: string, name: string) => {
  251. return !isNameUniqueInFolder(fileTreeData, parentFolderId, name)
  252. },
  253. [fileTreeData]
  254. )
  255. // init deletion flow (this will open the delete modal).
  256. // A copy of the selected entities is set as `actionedEntities` so it is kept
  257. // unchanged as the entities are deleted and the selection is updated
  258. const startDeleting = useCallback(() => {
  259. const actionedEntities = Array.from(selectedEntityIds).map(
  260. entityId => findInTreeOrThrow(fileTreeData, entityId).entity
  261. )
  262. dispatch({ type: ACTION_TYPES.START_DELETE, actionedEntities })
  263. }, [fileTreeData, selectedEntityIds])
  264. // deletes entities in series. Tree will be updated via the socket event
  265. const finishDeleting = useCallback(() => {
  266. dispatch({ type: ACTION_TYPES.DELETING })
  267. let shouldReindexReferences = false
  268. return (
  269. mapSeries(Array.from(selectedEntityIds), id => {
  270. const found = findInTreeOrThrow(fileTreeData, id)
  271. shouldReindexReferences =
  272. shouldReindexReferences || /\.bib$/.test(found.entity.name)
  273. return syncDelete(projectId, found.type, found.entity._id).catch(
  274. error => {
  275. // throw unless 404
  276. if (error.info.statusCode !== 404) {
  277. throw error
  278. }
  279. }
  280. )
  281. })
  282. // @ts-ignore (TODO: improve mapSeries types)
  283. .then(() => {
  284. if (shouldReindexReferences) {
  285. indexAllReferences(true)
  286. }
  287. dispatch({ type: ACTION_TYPES.CLEAR })
  288. })
  289. .catch((error: Error) => {
  290. // set an error and allow user to retry
  291. dispatch({ type: ACTION_TYPES.ERROR, error })
  292. })
  293. )
  294. }, [fileTreeData, projectId, selectedEntityIds, indexAllReferences])
  295. // moves entities. Tree is updated immediately and data are sync'd after.
  296. const finishMoving = useCallback(
  297. (toFolderId: string, draggedEntityIds: Set<string>) => {
  298. dispatch({ type: ACTION_TYPES.MOVING })
  299. // find entities and filter out no-ops and nested files
  300. const founds = Array.from(draggedEntityIds)
  301. .map(draggedEntityId =>
  302. findInTreeOrThrow(fileTreeData, draggedEntityId)
  303. )
  304. .filter(
  305. found =>
  306. found.parentFolderId !== toFolderId &&
  307. !draggedEntityIds.has(found.parentFolderId)
  308. )
  309. // make sure all entities can be moved, return early otherwise
  310. const isMoveToRoot = toFolderId === fileTreeData._id
  311. const validationError = founds
  312. .map(found =>
  313. validateMove(fileTreeData, toFolderId, found, isMoveToRoot)
  314. )
  315. .find(error => error)
  316. if (validationError) {
  317. return dispatch({ type: ACTION_TYPES.ERROR, error: validationError })
  318. }
  319. // keep track of old parent folder ids so we can revert entities if sync fails
  320. const oldParentFolderIds: Record<string, string> = {}
  321. let isMoveFailed = false
  322. // dispatch moves immediately
  323. founds.forEach(found => {
  324. oldParentFolderIds[found.entity._id] = found.parentFolderId
  325. dispatchMove(found.entity._id, toFolderId)
  326. })
  327. // sync dispatched moves after
  328. return (
  329. mapSeries(founds, async found => {
  330. try {
  331. await syncMove(projectId, found.type, found.entity._id, toFolderId)
  332. } catch (error) {
  333. isMoveFailed = true
  334. dispatchMove(found.entity._id, oldParentFolderIds[found.entity._id])
  335. dispatch({ type: ACTION_TYPES.ERROR, error })
  336. }
  337. })
  338. // @ts-ignore (TODO: improve mapSeries types)
  339. .then(() => {
  340. if (!isMoveFailed) {
  341. dispatch({ type: ACTION_TYPES.CLEAR })
  342. }
  343. })
  344. )
  345. },
  346. [dispatchMove, fileTreeData, projectId]
  347. )
  348. const startCreatingFolder = useCallback(() => {
  349. dispatch({ type: ACTION_TYPES.START_CREATE_FOLDER })
  350. }, [])
  351. const parentFolderId = useMemo(() => {
  352. return getSelectedParentFolderId(
  353. fileTreeData,
  354. selectedEntityIds,
  355. isRootFolderSelected
  356. )
  357. }, [fileTreeData, selectedEntityIds, isRootFolderSelected])
  358. // return the name of the selected file or doc if there is only one selected
  359. const selectedFileName = useMemo(() => {
  360. if (selectedEntityIds.size === 1) {
  361. const [selectedEntityId] = selectedEntityIds
  362. const selectedEntity = findInTree(fileTreeData, selectedEntityId)
  363. return selectedEntity?.entity?.name
  364. }
  365. return null
  366. }, [fileTreeData, selectedEntityIds])
  367. const finishCreatingEntity = useCallback(
  368. entity => {
  369. const error = validateCreate(fileTreeData, parentFolderId, entity)
  370. if (error) {
  371. return Promise.reject(error)
  372. }
  373. return syncCreateEntity(projectId, parentFolderId, entity)
  374. },
  375. [fileTreeData, parentFolderId, projectId]
  376. )
  377. const finishCreatingFolder = useCallback(
  378. name => {
  379. dispatch({ type: ACTION_TYPES.CREATING_FOLDER })
  380. return finishCreatingEntity({ endpoint: 'folder', name })
  381. .then(() => {
  382. dispatch({ type: ACTION_TYPES.CLEAR })
  383. })
  384. .catch(error => {
  385. dispatch({ type: ACTION_TYPES.ERROR, error })
  386. })
  387. },
  388. [finishCreatingEntity]
  389. )
  390. const startCreatingFile = useCallback(newFileCreateMode => {
  391. dispatch({ type: ACTION_TYPES.START_CREATE_FILE, newFileCreateMode })
  392. }, [])
  393. const startCreatingDocOrFile = useCallback(() => {
  394. startCreatingFile('doc')
  395. }, [startCreatingFile])
  396. const startUploadingDocOrFile = useCallback(() => {
  397. startCreatingFile('upload')
  398. }, [startCreatingFile])
  399. const finishCreatingDocOrFile = useCallback(
  400. entity => {
  401. dispatch({ type: ACTION_TYPES.CREATING_FILE })
  402. return finishCreatingEntity(entity)
  403. .then(() => {
  404. dispatch({ type: ACTION_TYPES.CLEAR })
  405. })
  406. .catch(error => {
  407. dispatch({ type: ACTION_TYPES.ERROR, error })
  408. })
  409. },
  410. [finishCreatingEntity]
  411. )
  412. const finishCreatingDoc = useCallback(
  413. entity => {
  414. entity.endpoint = 'doc'
  415. return finishCreatingDocOrFile(entity)
  416. },
  417. [finishCreatingDocOrFile]
  418. )
  419. const finishCreatingLinkedFile = useCallback(
  420. entity => {
  421. entity.endpoint = 'linked_file'
  422. return finishCreatingDocOrFile(entity)
  423. },
  424. [finishCreatingDocOrFile]
  425. )
  426. const cancel = useCallback(() => {
  427. dispatch({ type: ACTION_TYPES.CANCEL })
  428. }, [])
  429. // listen for `file-tree.start-creating` events
  430. useEffect(() => {
  431. function handleEvent(event: Event) {
  432. dispatch({
  433. type: ACTION_TYPES.START_CREATE_FILE,
  434. newFileCreateMode: (event as CustomEvent<{ mode: string }>).detail.mode,
  435. })
  436. }
  437. window.addEventListener('file-tree.start-creating', handleEvent)
  438. return () => {
  439. window.removeEventListener('file-tree.start-creating', handleEvent)
  440. }
  441. }, [])
  442. // build the path for downloading a single file or doc
  443. const downloadPath = useMemo(() => {
  444. if (selectedEntityIds.size === 1) {
  445. const [selectedEntityId] = selectedEntityIds
  446. const selectedEntity = findInTree(fileTreeData, selectedEntityId)
  447. if (selectedEntity?.type === 'fileRef') {
  448. return fileUrl(projectId, selectedEntityId, selectedEntity.entity.hash)
  449. }
  450. if (selectedEntity?.type === 'doc') {
  451. return `/project/${projectId}/doc/${selectedEntityId}/download`
  452. }
  453. }
  454. }, [fileTreeData, projectId, selectedEntityIds])
  455. const value = useMemo(
  456. () => ({
  457. canDelete: write && selectedEntityIds.size > 0 && !isRootFolderSelected,
  458. canRename: write && selectedEntityIds.size === 1 && !isRootFolderSelected,
  459. canCreate: write && selectedEntityIds.size < 2,
  460. ...state,
  461. parentFolderId,
  462. selectedFileName,
  463. isDuplicate,
  464. startRenaming,
  465. finishRenaming,
  466. startDeleting,
  467. finishDeleting,
  468. finishMoving,
  469. startCreatingFile,
  470. startCreatingFolder,
  471. finishCreatingFolder,
  472. startCreatingDocOrFile,
  473. startUploadingDocOrFile,
  474. finishCreatingDoc,
  475. finishCreatingLinkedFile,
  476. cancel,
  477. droppedFiles,
  478. setDroppedFiles,
  479. downloadPath,
  480. }),
  481. [
  482. cancel,
  483. downloadPath,
  484. droppedFiles,
  485. finishCreatingDoc,
  486. finishCreatingFolder,
  487. finishCreatingLinkedFile,
  488. finishDeleting,
  489. finishMoving,
  490. finishRenaming,
  491. isDuplicate,
  492. isRootFolderSelected,
  493. parentFolderId,
  494. selectedEntityIds.size,
  495. selectedFileName,
  496. startCreatingDocOrFile,
  497. startCreatingFile,
  498. startCreatingFolder,
  499. startDeleting,
  500. startRenaming,
  501. startUploadingDocOrFile,
  502. state,
  503. write,
  504. ]
  505. )
  506. return (
  507. <FileTreeActionableContext.Provider value={value}>
  508. {children}
  509. </FileTreeActionableContext.Provider>
  510. )
  511. }
  512. export function useFileTreeActionable() {
  513. const context = useContext(FileTreeActionableContext)
  514. if (!context) {
  515. throw new Error(
  516. 'useFileTreeActionable is only available inside FileTreeActionableProvider'
  517. )
  518. }
  519. return context
  520. }
  521. function getSelectedParentFolderId(
  522. fileTreeData: Folder,
  523. selectedEntityIds: Set<string>,
  524. isRootFolderSelected: boolean
  525. ) {
  526. if (isRootFolderSelected) {
  527. return fileTreeData._id
  528. }
  529. // we expect only one entity to be selected in that case, so we pick the first
  530. const selectedEntityId = Array.from(selectedEntityIds)[0]
  531. if (!selectedEntityId) {
  532. // in some cases no entities are selected. Return the root folder id then.
  533. return fileTreeData._id
  534. }
  535. const found = findInTree(fileTreeData, selectedEntityId)
  536. if (!found) {
  537. // if the entity isn't in the tree, return the root folder id.
  538. return fileTreeData._id
  539. }
  540. return found.type === 'folder' ? found.entity._id : found.parentFolderId
  541. }
  542. function validateCreate(
  543. fileTreeData: Folder,
  544. parentFolderId: string,
  545. entity: { name: string; endpoint: string }
  546. ) {
  547. if (!isCleanFilename(entity.name)) {
  548. return new InvalidFilenameError()
  549. }
  550. if (!isNameUniqueInFolder(fileTreeData, parentFolderId, entity.name)) {
  551. return new DuplicateFilenameError()
  552. }
  553. // check that the name of a file is allowed, if creating in the root folder
  554. const isMoveToRoot = parentFolderId === fileTreeData._id
  555. const isFolder = entity.endpoint === 'folder'
  556. if (isMoveToRoot && !isFolder && isBlockedFilename(entity.name)) {
  557. return new BlockedFilenameError()
  558. }
  559. }
  560. function validateRename(
  561. fileTreeData: Folder,
  562. found: { parentFolderId: string; path: string[]; type: string },
  563. newName: string
  564. ) {
  565. if (!isCleanFilename(newName)) {
  566. return new InvalidFilenameError()
  567. }
  568. if (!isNameUniqueInFolder(fileTreeData, found.parentFolderId, newName)) {
  569. return new DuplicateFilenameError()
  570. }
  571. const isTopLevel = found.path.length === 1
  572. const isFolder = found.type === 'folder'
  573. if (isTopLevel && !isFolder && isBlockedFilename(newName)) {
  574. return new BlockedFilenameError()
  575. }
  576. }
  577. function validateMove(
  578. fileTreeData: Folder,
  579. toFolderId: string,
  580. found: { entity: { name: string }; type: string },
  581. isMoveToRoot: boolean
  582. ) {
  583. if (!isNameUniqueInFolder(fileTreeData, toFolderId, found.entity.name)) {
  584. const error = new DuplicateFilenameMoveError()
  585. ;(error as DuplicateFilenameMoveError & { entityName: string }).entityName =
  586. found.entity.name
  587. return error
  588. }
  589. const isFolder = found.type === 'folder'
  590. if (isMoveToRoot && !isFolder && isBlockedFilename(found.entity.name)) {
  591. return new BlockedFilenameError()
  592. }
  593. }