file-tree-actionable.js 15 KB

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