file-tree-selectable.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. import React, {
  2. createContext,
  3. useCallback,
  4. useContext,
  5. useReducer,
  6. useEffect,
  7. useMemo,
  8. useState
  9. } from 'react'
  10. import PropTypes from 'prop-types'
  11. import classNames from 'classnames'
  12. import { findInTree } from '../util/find-in-tree'
  13. import { useFileTreeMutable } from './file-tree-mutable'
  14. import { useFileTreeMainContext } from './file-tree-main'
  15. import usePersistedState from '../../../infrastructure/persisted-state-hook'
  16. const FileTreeSelectableContext = createContext()
  17. const ACTION_TYPES = {
  18. SELECT: 'SELECT',
  19. MULTI_SELECT: 'MULTI_SELECT',
  20. UNSELECT: 'UNSELECT'
  21. }
  22. function fileTreeSelectableReadWriteReducer(selectedEntityIds, action) {
  23. switch (action.type) {
  24. case ACTION_TYPES.SELECT: {
  25. // reset selection
  26. return new Set([action.id])
  27. }
  28. case ACTION_TYPES.MULTI_SELECT: {
  29. const selectedEntityIdsCopy = new Set(selectedEntityIds)
  30. if (selectedEntityIdsCopy.has(action.id)) {
  31. // entity already selected
  32. if (selectedEntityIdsCopy.size > 1) {
  33. // entity already multi-selected; remove from set
  34. selectedEntityIdsCopy.delete(action.id)
  35. }
  36. } else {
  37. // entity not selected: add to set
  38. selectedEntityIdsCopy.add(action.id)
  39. }
  40. return selectedEntityIdsCopy
  41. }
  42. case ACTION_TYPES.UNSELECT: {
  43. const selectedEntityIdsCopy = new Set(selectedEntityIds)
  44. selectedEntityIdsCopy.delete(action.id)
  45. return selectedEntityIdsCopy
  46. }
  47. default:
  48. throw new Error(`Unknown selectable action type: ${action.type}`)
  49. }
  50. }
  51. function fileTreeSelectableReadOnlyReducer(selectedEntityIds, action) {
  52. switch (action.type) {
  53. case ACTION_TYPES.SELECT:
  54. return new Set([action.id])
  55. case ACTION_TYPES.MULTI_SELECT:
  56. case ACTION_TYPES.UNSELECT:
  57. return selectedEntityIds
  58. default:
  59. throw new Error(`Unknown selectable action type: ${action.type}`)
  60. }
  61. }
  62. export function FileTreeSelectableProvider({
  63. hasWritePermissions,
  64. rootDocId,
  65. onSelect,
  66. children
  67. }) {
  68. const { projectId } = useFileTreeMainContext()
  69. const [initialSelectedEntityId] = usePersistedState(
  70. `doc.open_id.${projectId}`,
  71. rootDocId
  72. )
  73. const { fileTreeData } = useFileTreeMutable()
  74. const [selectedEntityIds, dispatch] = useReducer(
  75. hasWritePermissions
  76. ? fileTreeSelectableReadWriteReducer
  77. : fileTreeSelectableReadOnlyReducer,
  78. null,
  79. () => {
  80. if (!initialSelectedEntityId) return new Set()
  81. // the entity with id=initialSelectedEntityId might not exist in the tree
  82. // anymore. This checks that it exists before initialising the reducer
  83. // with the id.
  84. if (findInTree(fileTreeData, initialSelectedEntityId))
  85. return new Set([initialSelectedEntityId])
  86. // the entity doesn't exist anymore; don't select any files
  87. return new Set()
  88. }
  89. )
  90. const [selectedEntityParentIds, setSelectedEntityParentIds] = useState(
  91. new Set()
  92. )
  93. // fills `selectedEntityParentIds` set
  94. useEffect(() => {
  95. const ids = new Set()
  96. selectedEntityIds.forEach(id => {
  97. const found = findInTree(fileTreeData, id)
  98. if (found) {
  99. found.path.forEach(pathItem => ids.add(pathItem))
  100. }
  101. })
  102. setSelectedEntityParentIds(ids)
  103. }, [fileTreeData, selectedEntityIds])
  104. // calls `onSelect` on entities selection
  105. useEffect(() => {
  106. const selectedEntities = Array.from(selectedEntityIds).map(id =>
  107. findInTree(fileTreeData, id)
  108. )
  109. onSelect(selectedEntities)
  110. }, [fileTreeData, selectedEntityIds, onSelect])
  111. useEffect(() => {
  112. // listen for `editor.openDoc` and selected that doc
  113. function handleOpenDoc(ev) {
  114. const found = findInTree(fileTreeData, ev.detail)
  115. if (!found) return
  116. dispatch({ type: ACTION_TYPES.SELECT, id: found.entity._id })
  117. }
  118. window.addEventListener('editor.openDoc', handleOpenDoc)
  119. return () => window.removeEventListener('editor.openDoc', handleOpenDoc)
  120. }, [fileTreeData])
  121. return (
  122. <FileTreeSelectableContext.Provider
  123. value={{ selectedEntityIds, selectedEntityParentIds, dispatch }}
  124. >
  125. {children}
  126. </FileTreeSelectableContext.Provider>
  127. )
  128. }
  129. FileTreeSelectableProvider.propTypes = {
  130. hasWritePermissions: PropTypes.bool.isRequired,
  131. rootDocId: PropTypes.string,
  132. onSelect: PropTypes.func.isRequired,
  133. children: PropTypes.oneOfType([
  134. PropTypes.arrayOf(PropTypes.node),
  135. PropTypes.node
  136. ]).isRequired
  137. }
  138. export function useSelectableEntity(id) {
  139. const { selectedEntityIds, dispatch } = useContext(FileTreeSelectableContext)
  140. const isSelected = selectedEntityIds.has(id)
  141. const selectOrMultiSelectEntity = useCallback(
  142. ev => {
  143. const isMultiSelect = ev.ctrlKey || ev.metaKey
  144. const actionType = isMultiSelect
  145. ? ACTION_TYPES.MULTI_SELECT
  146. : ACTION_TYPES.SELECT
  147. dispatch({ type: actionType, id })
  148. },
  149. [dispatch, id]
  150. )
  151. const handleClick = useCallback(
  152. ev => {
  153. selectOrMultiSelectEntity(ev)
  154. },
  155. [selectOrMultiSelectEntity]
  156. )
  157. const handleKeyPress = useCallback(
  158. ev => {
  159. if (ev.key === 'Enter' || ev.key === ' ') {
  160. selectOrMultiSelectEntity(ev)
  161. }
  162. },
  163. [selectOrMultiSelectEntity]
  164. )
  165. const handleContextMenu = useCallback(
  166. ev => {
  167. // make sure the right-clicked entity gets selected
  168. if (!selectedEntityIds.has(id)) selectOrMultiSelectEntity(ev)
  169. },
  170. [id, selectOrMultiSelectEntity, selectedEntityIds]
  171. )
  172. const props = useMemo(
  173. () => ({
  174. className: classNames({ selected: isSelected }),
  175. 'aria-selected': isSelected,
  176. onClick: handleClick,
  177. onContextMenu: handleContextMenu,
  178. onKeyPress: handleKeyPress
  179. }),
  180. [handleClick, handleContextMenu, handleKeyPress, isSelected]
  181. )
  182. return { isSelected, props }
  183. }
  184. export function useFileTreeSelectable() {
  185. const { selectedEntityIds, selectedEntityParentIds, dispatch } = useContext(
  186. FileTreeSelectableContext
  187. )
  188. const select = useCallback(
  189. id => {
  190. dispatch({ type: ACTION_TYPES.SELECT, id })
  191. },
  192. [dispatch]
  193. )
  194. const unselect = useCallback(
  195. id => {
  196. dispatch({ type: ACTION_TYPES.UNSELECT, id })
  197. },
  198. [dispatch]
  199. )
  200. return {
  201. selectedEntityIds,
  202. selectedEntityParentIds,
  203. select,
  204. unselect
  205. }
  206. }