file-tree-actionable.jsx 15 KB

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