file-tree-actionable.js 14 KB

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