file-tree-actionable.jsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  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
  200. const founds = Array.from(draggedEntityIds)
  201. .map(draggedEntityId =>
  202. findInTreeOrThrow(fileTreeData, draggedEntityId)
  203. )
  204. .filter(found => found.parentFolderId !== toFolderId)
  205. // make sure all entities can be moved, return early otherwise
  206. const isMoveToRoot = toFolderId === fileTreeData._id
  207. const validationError = founds
  208. .map(found =>
  209. validateMove(fileTreeData, toFolderId, found, isMoveToRoot)
  210. )
  211. .find(error => error)
  212. if (validationError) {
  213. return dispatch({ type: ACTION_TYPES.ERROR, error: validationError })
  214. }
  215. // keep track of old parent folder ids so we can revert entities if sync fails
  216. const oldParentFolderIds = {}
  217. let isMoveFailed = false
  218. // dispatch moves immediately
  219. founds.forEach(found => {
  220. oldParentFolderIds[found.entity._id] = found.parentFolderId
  221. dispatchMove(found.entity._id, toFolderId)
  222. })
  223. // sync dispatched moves after
  224. return mapSeries(founds, async found => {
  225. try {
  226. await syncMove(projectId, found.type, found.entity._id, toFolderId)
  227. } catch (error) {
  228. isMoveFailed = true
  229. dispatchMove(found.entity._id, oldParentFolderIds[found.entity._id])
  230. dispatch({ type: ACTION_TYPES.ERROR, error })
  231. }
  232. }).then(() => {
  233. if (!isMoveFailed) {
  234. dispatch({ type: ACTION_TYPES.CLEAR })
  235. }
  236. })
  237. },
  238. [dispatchMove, fileTreeData, projectId]
  239. )
  240. const startCreatingFolder = useCallback(() => {
  241. dispatch({ type: ACTION_TYPES.START_CREATE_FOLDER })
  242. }, [])
  243. const parentFolderId = useMemo(() => {
  244. return getSelectedParentFolderId(
  245. fileTreeData,
  246. selectedEntityIds,
  247. isRootFolderSelected
  248. )
  249. }, [fileTreeData, selectedEntityIds, isRootFolderSelected])
  250. const finishCreatingEntity = useCallback(
  251. entity => {
  252. const error = validateCreate(fileTreeData, parentFolderId, entity)
  253. if (error) {
  254. return Promise.reject(error)
  255. }
  256. return syncCreateEntity(projectId, parentFolderId, entity)
  257. },
  258. [fileTreeData, parentFolderId, projectId]
  259. )
  260. const finishCreatingFolder = useCallback(
  261. name => {
  262. dispatch({ type: ACTION_TYPES.CREATING_FOLDER })
  263. return finishCreatingEntity({ endpoint: 'folder', name })
  264. .then(() => {
  265. dispatch({ type: ACTION_TYPES.CLEAR })
  266. })
  267. .catch(error => {
  268. dispatch({ type: ACTION_TYPES.ERROR, error })
  269. })
  270. },
  271. [finishCreatingEntity]
  272. )
  273. const startCreatingFile = useCallback(newFileCreateMode => {
  274. dispatch({ type: ACTION_TYPES.START_CREATE_FILE, newFileCreateMode })
  275. }, [])
  276. const startCreatingDocOrFile = useCallback(() => {
  277. startCreatingFile('doc')
  278. }, [startCreatingFile])
  279. const startUploadingDocOrFile = useCallback(() => {
  280. startCreatingFile('upload')
  281. }, [startCreatingFile])
  282. const finishCreatingDocOrFile = useCallback(
  283. entity => {
  284. dispatch({ type: ACTION_TYPES.CREATING_FILE })
  285. return finishCreatingEntity(entity)
  286. .then(() => {
  287. dispatch({ type: ACTION_TYPES.CLEAR })
  288. })
  289. .catch(error => {
  290. dispatch({ type: ACTION_TYPES.ERROR, error })
  291. })
  292. },
  293. [finishCreatingEntity]
  294. )
  295. const finishCreatingDoc = useCallback(
  296. entity => {
  297. entity.endpoint = 'doc'
  298. return finishCreatingDocOrFile(entity)
  299. },
  300. [finishCreatingDocOrFile]
  301. )
  302. const finishCreatingLinkedFile = useCallback(
  303. entity => {
  304. entity.endpoint = 'linked_file'
  305. return finishCreatingDocOrFile(entity)
  306. },
  307. [finishCreatingDocOrFile]
  308. )
  309. const cancel = useCallback(() => {
  310. dispatch({ type: ACTION_TYPES.CANCEL })
  311. }, [])
  312. // listen for `file-tree.start-creating` events
  313. useEffect(() => {
  314. function handleEvent(event) {
  315. dispatch({
  316. type: ACTION_TYPES.START_CREATE_FILE,
  317. newFileCreateMode: event.detail.mode,
  318. })
  319. }
  320. window.addEventListener('file-tree.start-creating', handleEvent)
  321. return () => {
  322. window.removeEventListener('file-tree.start-creating', handleEvent)
  323. }
  324. }, [])
  325. // build the path for downloading a single file
  326. const downloadPath = useMemo(() => {
  327. if (selectedEntityIds.size === 1) {
  328. const [selectedEntityId] = selectedEntityIds
  329. const selectedEntity = findInTree(fileTreeData, selectedEntityId)
  330. if (selectedEntity?.type === 'fileRef') {
  331. return `/project/${projectId}/file/${selectedEntityId}`
  332. }
  333. }
  334. }, [fileTreeData, projectId, selectedEntityIds])
  335. const value = {
  336. canDelete: selectedEntityIds.size > 0 && !isRootFolderSelected,
  337. canRename: selectedEntityIds.size === 1 && !isRootFolderSelected,
  338. canCreate: selectedEntityIds.size < 2,
  339. ...state,
  340. parentFolderId,
  341. isDuplicate,
  342. startRenaming,
  343. finishRenaming,
  344. startDeleting,
  345. finishDeleting,
  346. finishMoving,
  347. startCreatingFile,
  348. startCreatingFolder,
  349. finishCreatingFolder,
  350. startCreatingDocOrFile,
  351. startUploadingDocOrFile,
  352. finishCreatingDoc,
  353. finishCreatingLinkedFile,
  354. cancel,
  355. droppedFiles,
  356. setDroppedFiles,
  357. downloadPath,
  358. }
  359. return (
  360. <FileTreeActionableContext.Provider value={value}>
  361. {children}
  362. </FileTreeActionableContext.Provider>
  363. )
  364. }
  365. FileTreeActionableProvider.propTypes = {
  366. reindexReferences: PropTypes.func.isRequired,
  367. children: PropTypes.oneOfType([
  368. PropTypes.arrayOf(PropTypes.node),
  369. PropTypes.node,
  370. ]).isRequired,
  371. }
  372. const projectContextPropTypes = {
  373. _id: PropTypes.string.isRequired,
  374. }
  375. const editorContextPropTypes = {
  376. permissionsLevel: PropTypes.oneOf(['readOnly', 'readAndWrite', 'owner']),
  377. }
  378. export function useFileTreeActionable() {
  379. const context = useContext(FileTreeActionableContext)
  380. if (!context) {
  381. throw new Error(
  382. 'useFileTreeActionable is only available inside FileTreeActionableProvider'
  383. )
  384. }
  385. return context
  386. }
  387. function getSelectedParentFolderId(
  388. fileTreeData,
  389. selectedEntityIds,
  390. isRootFolderSelected
  391. ) {
  392. if (isRootFolderSelected) {
  393. return fileTreeData._id
  394. }
  395. // we expect only one entity to be selected in that case, so we pick the first
  396. const selectedEntityId = Array.from(selectedEntityIds)[0]
  397. if (!selectedEntityId) {
  398. // in some cases no entities are selected. Return the root folder id then.
  399. return fileTreeData._id
  400. }
  401. const found = findInTree(fileTreeData, selectedEntityId)
  402. if (!found) {
  403. // if the entity isn't in the tree, return the root folder id.
  404. return fileTreeData._id
  405. }
  406. return found.type === 'folder' ? found.entity._id : found.parentFolderId
  407. }
  408. function validateCreate(fileTreeData, parentFolderId, entity) {
  409. if (!isCleanFilename(entity.name)) {
  410. return new InvalidFilenameError()
  411. }
  412. if (!isNameUniqueInFolder(fileTreeData, parentFolderId, entity.name)) {
  413. return new DuplicateFilenameError()
  414. }
  415. // check that the name of a file is allowed, if creating in the root folder
  416. const isMoveToRoot = parentFolderId === fileTreeData._id
  417. const isFolder = entity.endpoint === 'folder'
  418. if (isMoveToRoot && !isFolder && isBlockedFilename(entity.name)) {
  419. return new BlockedFilenameError()
  420. }
  421. }
  422. function validateRename(fileTreeData, found, newName) {
  423. if (!isCleanFilename(newName)) {
  424. return new InvalidFilenameError()
  425. }
  426. if (!isNameUniqueInFolder(fileTreeData, found.parentFolderId, newName)) {
  427. return new DuplicateFilenameError()
  428. }
  429. const isTopLevel = found.path.length === 1
  430. const isFolder = found.type === 'folder'
  431. if (isTopLevel && !isFolder && isBlockedFilename(newName)) {
  432. return new BlockedFilenameError()
  433. }
  434. }
  435. function validateMove(fileTreeData, toFolderId, found, isMoveToRoot) {
  436. if (!isNameUniqueInFolder(fileTreeData, toFolderId, found.entity.name)) {
  437. const error = new DuplicateFilenameMoveError()
  438. error.entityName = found.entity.name
  439. return error
  440. }
  441. const isFolder = found.type === 'folder'
  442. if (isMoveToRoot && !isFolder && isBlockedFilename(found.entity.name)) {
  443. return new BlockedFilenameError()
  444. }
  445. }