file-tree-actionable.js 13 KB

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