file-tree-actionable.tsx 17 KB

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