file-tree-actionable.tsx 17 KB

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