tabs-context.tsx 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. import { findInTree } from '@/features/file-tree/util/find-in-tree'
  2. import { useFileTreeData } from '@/shared/context/file-tree-data-context'
  3. import { useProjectContext } from '@/shared/context/project-context'
  4. import usePersistedState from '@/shared/hooks/use-persisted-state'
  5. import React, { FC, useCallback, useContext, useEffect, useMemo } from 'react'
  6. import { useFileTreeOpenContext } from './file-tree-open-context'
  7. import { useEditorManagerContext } from './editor-manager-context'
  8. import { debugConsole } from '@/utils/debugging'
  9. import { disambiguatePaths } from '../util/disambiguate-paths'
  10. import { isSplitTestEnabled } from '@/utils/splitTestUtils'
  11. import { useUserSettingsContext } from '@/shared/context/user-settings-context'
  12. import {
  13. FileTreeFindResult,
  14. isFileRefResult,
  15. } from '@/features/ide-react/types/file-tree'
  16. type PersistedTabInfo = { id: string; lifetime: Lifetime }
  17. type Lifetime = 'permanent' | 'temporary'
  18. export type EditorFileTab = {
  19. id: string
  20. name: string
  21. displayPath: string
  22. isLinkedFile: boolean
  23. lifetime: Lifetime
  24. }
  25. export const TAB_TRANSFER_TYPE = 'text/x.tab-id'
  26. const TabsContext = React.createContext<
  27. | {
  28. tabs: EditorFileTab[]
  29. openTab: (id: string) => void
  30. closeTab: (id: string) => void
  31. makeTabPermanent: (id: string) => void
  32. moveTab: (
  33. sourceTabId: string,
  34. targetTabId: string,
  35. position: 'left' | 'right'
  36. ) => void
  37. }
  38. | undefined
  39. >(undefined)
  40. export const TabsProvider: FC<React.PropsWithChildren> = ({ children }) => {
  41. const { projectId } = useProjectContext()
  42. const { fileTreeData } = useFileTreeData()
  43. const { openEntity } = useFileTreeOpenContext()
  44. const { openDocWithId, openFileWithId } = useEditorManagerContext()
  45. const tabsEnabled = isSplitTestEnabled('editor-tabs')
  46. const { userSettings } = useUserSettingsContext()
  47. const { previewTabs } = userSettings
  48. const [openTabs, setOpenTabs] = usePersistedState<PersistedTabInfo[]>(
  49. `open-tabs:${projectId}`,
  50. []
  51. )
  52. const tabs = useMemo(() => {
  53. if (!tabsEnabled) {
  54. return []
  55. }
  56. if (!fileTreeData) {
  57. return []
  58. }
  59. const tabsFileTreeLookup = openTabs
  60. .map(tab => ({
  61. lifetime: tab.lifetime,
  62. result: findInTree(fileTreeData, tab.id),
  63. }))
  64. .filter(x => !!x.result) as {
  65. lifetime: Lifetime
  66. result: FileTreeFindResult
  67. }[]
  68. const pathLookup = disambiguatePaths(
  69. tabsFileTreeLookup.map(tab => tab.result),
  70. fileTreeData
  71. )
  72. return tabsFileTreeLookup.map(tab => {
  73. const entity = tab.result.entity
  74. return {
  75. id: entity._id,
  76. name: entity.name,
  77. displayPath: pathLookup.get(entity._id) || entity.name,
  78. isLinkedFile:
  79. isFileRefResult(tab.result) &&
  80. !!tab.result.entity.linkedFileData?.provider,
  81. lifetime: tab.lifetime,
  82. }
  83. })
  84. }, [fileTreeData, openTabs, tabsEnabled])
  85. const openTab = useCallback(
  86. async (id: string) => {
  87. if (!fileTreeData) {
  88. return
  89. }
  90. const file = findInTree(fileTreeData, id)
  91. if (!file) {
  92. return
  93. }
  94. if (file.type === 'doc') {
  95. await openDocWithId(file.entity._id)
  96. } else if (file.type === 'fileRef') {
  97. openFileWithId(file.entity._id)
  98. } else {
  99. debugConsole.error('Attempting to open invalid entity type')
  100. }
  101. },
  102. [fileTreeData, openDocWithId, openFileWithId]
  103. )
  104. const closeTab = useCallback(
  105. async (id: string) => {
  106. if (openTabs.length <= 1) {
  107. // Can't close last file
  108. return
  109. }
  110. if (id === openEntity?.entity._id) {
  111. const currentIndex = openTabs.findIndex(tab => tab.id === id)
  112. if (currentIndex === -1) {
  113. debugConsole.warn('Attempting to close tab that is not open')
  114. return
  115. }
  116. const nextTab = openTabs[currentIndex + 1] || openTabs[currentIndex - 1]
  117. if (!nextTab) {
  118. debugConsole.warn('No next tab to switch to on close')
  119. return
  120. }
  121. await openTab(nextTab.id)
  122. }
  123. setOpenTabs(current => current.filter(tab => tab.id !== id))
  124. },
  125. [openTabs, openEntity, setOpenTabs, openTab]
  126. )
  127. const moveTab = useCallback(
  128. (sourceTabId: string, targetTabId: string, position: 'left' | 'right') => {
  129. debugConsole.log({ sourceTabId, targetTabId, position })
  130. if (sourceTabId === targetTabId) {
  131. debugConsole.debug(
  132. 'Source and target tab ids are the same for moving tab'
  133. )
  134. return
  135. }
  136. setOpenTabs(current => {
  137. const sourceTabIndex = current.findIndex(tab => tab.id === sourceTabId)
  138. const targetTabIndex = current.findIndex(tab => tab.id === targetTabId)
  139. if (sourceTabIndex === -1 || targetTabIndex === -1) {
  140. debugConsole.warn('Invalid tab ids for moving tab')
  141. return current
  142. }
  143. if (
  144. (position === 'right' && targetTabIndex === sourceTabIndex - 1) ||
  145. (position === 'left' && targetTabIndex === sourceTabIndex + 1)
  146. ) {
  147. debugConsole.debug(
  148. 'Source and target tab are already adjacent for move'
  149. )
  150. return current
  151. }
  152. return arrayMove(current, sourceTabIndex, targetTabIndex, position)
  153. })
  154. },
  155. [setOpenTabs]
  156. )
  157. const makeTabPermanent = useCallback(
  158. (id: string) => {
  159. setOpenTabs(current =>
  160. current.map(tab =>
  161. tab.id === id ? { ...tab, lifetime: 'permanent' } : tab
  162. )
  163. )
  164. },
  165. [setOpenTabs]
  166. )
  167. useEffect(() => {
  168. if (!tabsEnabled) {
  169. return
  170. }
  171. if (!openEntity) {
  172. return
  173. }
  174. setOpenTabs(current => {
  175. if (current.find(t => t.id === openEntity?.entity._id)) {
  176. return current
  177. }
  178. return [
  179. ...current.filter(tab => tab.lifetime !== 'temporary'),
  180. {
  181. id: openEntity.entity._id,
  182. lifetime: previewTabs ? 'temporary' : 'permanent',
  183. },
  184. ]
  185. })
  186. }, [openEntity, previewTabs, setOpenTabs, tabsEnabled])
  187. const value = useMemo(
  188. () => ({ tabs, openTab, closeTab, moveTab, makeTabPermanent }),
  189. [tabs, openTab, closeTab, moveTab, makeTabPermanent]
  190. )
  191. return <TabsContext.Provider value={value}>{children}</TabsContext.Provider>
  192. }
  193. export const useTabsContext = () => {
  194. const value = useContext(TabsContext)
  195. if (!value) {
  196. throw new Error('useTabsContext can only be used inside TabsProvider')
  197. }
  198. return value
  199. }
  200. function arrayMove<T>(
  201. array: T[],
  202. sourceIndex: number,
  203. targetIndex: number,
  204. side: 'left' | 'right'
  205. ): T[] {
  206. const result = [...array]
  207. const [movedItem] = result.splice(sourceIndex, 1)
  208. let newIndex = targetIndex
  209. if (sourceIndex < targetIndex) {
  210. newIndex -= 1
  211. }
  212. if (side === 'right') {
  213. newIndex += 1
  214. }
  215. result.splice(newIndex, 0, movedItem)
  216. return result
  217. }