draggableTabBar.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. import 'intersection-observer'; // polyfill
  2. import {useContext, useState} from 'react';
  3. import type {InjectedRouter} from 'react-router';
  4. import styled from '@emotion/styled';
  5. import type {Node} from '@react-types/shared';
  6. import Badge from 'sentry/components/badge/badge';
  7. import {DraggableTabList} from 'sentry/components/draggableTabs/draggableTabList';
  8. import type {DraggableTabListItemProps} from 'sentry/components/draggableTabs/item';
  9. import type {MenuItemProps} from 'sentry/components/dropdownMenu';
  10. import QueryCount from 'sentry/components/queryCount';
  11. import {TabsContext} from 'sentry/components/tabs';
  12. import {t} from 'sentry/locale';
  13. import {defined} from 'sentry/utils';
  14. import normalizeUrl from 'sentry/utils/url/normalizeUrl';
  15. import {useNavigate} from 'sentry/utils/useNavigate';
  16. import {DraggableTabMenuButton} from 'sentry/views/issueList/groupSearchViewTabs/draggableTabMenuButton';
  17. import EditableTabTitle from 'sentry/views/issueList/groupSearchViewTabs/editableTabTitle';
  18. import type {IssueSortOptions} from 'sentry/views/issueList/utils';
  19. export interface Tab {
  20. id: string;
  21. key: string;
  22. label: string;
  23. query: string;
  24. querySort: IssueSortOptions;
  25. content?: React.ReactNode;
  26. queryCount?: number;
  27. unsavedChanges?: [string, IssueSortOptions];
  28. }
  29. export interface DraggableTabBarProps {
  30. initialTabKey: string;
  31. orgSlug: string;
  32. router: InjectedRouter;
  33. setTabs: (tabs: Tab[]) => void;
  34. setTempTab: (tab: Tab | undefined) => void;
  35. tabs: Tab[];
  36. /**
  37. * Callback function to be called when user clicks the `Add View` button.
  38. */
  39. onAddView?: (newTabs: Tab[]) => void;
  40. /**
  41. * Callback function to be called when user clicks the `Delete` button.
  42. * Note: The `Delete` button only appears for persistent views
  43. */
  44. onDelete?: (newTabs: Tab[]) => void;
  45. /**
  46. * Callback function to be called when user clicks on the `Discard Changes` button.
  47. * Note: The `Discard Changes` button only appears for persistent views when `isChanged=true`
  48. */
  49. onDiscard?: () => void;
  50. /**
  51. * Callback function to be called when user clicks on the `Discard` button for temporary views.
  52. * Note: The `Discard` button only appears for temporary views
  53. */
  54. onDiscardTempView?: () => void;
  55. /**
  56. * Callback function to be called when user clicks the 'Duplicate' button.
  57. * Note: The `Duplicate` button only appears for persistent views
  58. */
  59. onDuplicate?: (newTabs: Tab[]) => void;
  60. /**
  61. * Callback function to be called when the user reorders the tabs. Returns the
  62. * new order of the tabs along with their props.
  63. */
  64. onReorder?: (newTabs: Tab[]) => void;
  65. /**
  66. * Callback function to be called when user clicks the 'Save' button.
  67. * Note: The `Save` button only appears for persistent views when `isChanged=true`
  68. */
  69. onSave?: (newTabs: Tab[]) => void;
  70. /**
  71. * Callback function to be called when user clicks the 'Save View' button for temporary views.
  72. */
  73. onSaveTempView?: (newTabs: Tab[]) => void;
  74. /**
  75. * Callback function to be called when user renames a tab.
  76. * Note: The `Rename` button only appears for persistent views
  77. */
  78. onTabRenamed?: (newTabs: Tab[], newLabel: string) => void;
  79. tempTab?: Tab;
  80. }
  81. export const generateTempViewId = () => `_${Math.random().toString().substring(2, 7)}`;
  82. export function DraggableTabBar({
  83. initialTabKey,
  84. tabs,
  85. setTabs,
  86. tempTab,
  87. setTempTab,
  88. orgSlug,
  89. router,
  90. onReorder,
  91. onAddView,
  92. onDelete,
  93. onDiscard,
  94. onDuplicate,
  95. onTabRenamed,
  96. onSave,
  97. onDiscardTempView,
  98. onSaveTempView,
  99. }: DraggableTabBarProps) {
  100. // TODO: Extract this to a separate component encompassing Tab.Item in the future
  101. const [editingTabKey, setEditingTabKey] = useState<string | null>(null);
  102. const navigate = useNavigate();
  103. const {cursor: _cursor, page: _page, ...queryParams} = router?.location?.query ?? {};
  104. const {tabListState} = useContext(TabsContext);
  105. const handleOnReorder = (newOrder: Node<DraggableTabListItemProps>[]) => {
  106. const newTabs = newOrder
  107. .map(node => {
  108. const foundTab = tabs.find(tab => tab.key === node.key);
  109. return foundTab?.key === node.key ? foundTab : null;
  110. })
  111. .filter(defined);
  112. setTabs(newTabs);
  113. onReorder?.(newTabs);
  114. };
  115. const handleOnSaveChanges = () => {
  116. const originalTab = tabs.find(tab => tab.key === tabListState?.selectedKey);
  117. if (originalTab) {
  118. const newTabs = tabs.map(tab => {
  119. return tab.key === tabListState?.selectedKey && tab.unsavedChanges
  120. ? {
  121. ...tab,
  122. query: tab.unsavedChanges[0],
  123. querySort: tab.unsavedChanges[1],
  124. unsavedChanges: undefined,
  125. }
  126. : tab;
  127. });
  128. setTabs(newTabs);
  129. onSave?.(newTabs);
  130. }
  131. };
  132. const handleOnDiscardChanges = () => {
  133. const originalTab = tabs.find(tab => tab.key === tabListState?.selectedKey);
  134. if (originalTab) {
  135. setTabs(
  136. tabs.map(tab => {
  137. return tab.key === tabListState?.selectedKey
  138. ? {...tab, unsavedChanges: undefined}
  139. : tab;
  140. })
  141. );
  142. navigate({
  143. query: {
  144. ...queryParams,
  145. query: originalTab.query,
  146. sort: originalTab.querySort,
  147. ...(originalTab.id ? {viewId: originalTab.id} : {}),
  148. },
  149. pathname: `/organizations/${orgSlug}/issues/`,
  150. });
  151. onDiscard?.();
  152. }
  153. };
  154. const handleOnTabRenamed = (newLabel: string, tabKey: string) => {
  155. const renamedTab = tabs.find(tb => tb.key === tabKey);
  156. if (renamedTab && newLabel !== renamedTab.label) {
  157. const newTabs = tabs.map(tab =>
  158. tab.key === renamedTab.key ? {...tab, label: newLabel} : tab
  159. );
  160. setTabs(newTabs);
  161. onTabRenamed?.(newTabs, newLabel);
  162. }
  163. };
  164. const handleOnDuplicate = () => {
  165. const idx = tabs.findIndex(tb => tb.key === tabListState?.selectedKey);
  166. if (idx !== -1) {
  167. const tempId = generateTempViewId();
  168. const duplicatedTab = tabs[idx];
  169. const newTabs = [
  170. ...tabs.slice(0, idx + 1),
  171. {
  172. ...duplicatedTab,
  173. id: tempId,
  174. key: tempId,
  175. label: `${duplicatedTab.label} (Copy)`,
  176. },
  177. ...tabs.slice(idx + 1),
  178. ];
  179. navigate({
  180. query: {
  181. ...queryParams,
  182. viewId: tempId,
  183. },
  184. pathname: `/organizations/${orgSlug}/issues/`,
  185. });
  186. setTabs(newTabs);
  187. tabListState?.setSelectedKey(tempId);
  188. onDuplicate?.(newTabs);
  189. }
  190. };
  191. const handleOnDelete = () => {
  192. if (tabs.length > 1) {
  193. const newTabs = tabs.filter(tb => tb.key !== tabListState?.selectedKey);
  194. setTabs(newTabs);
  195. tabListState?.setSelectedKey(newTabs[0].key);
  196. onDelete?.(newTabs);
  197. }
  198. };
  199. const handleOnSaveTempView = () => {
  200. if (tempTab) {
  201. const tempId = generateTempViewId();
  202. const newTab: Tab = {
  203. id: tempId,
  204. key: tempId,
  205. label: 'New View',
  206. query: tempTab.query,
  207. querySort: tempTab.querySort,
  208. };
  209. const newTabs = [...tabs, newTab];
  210. setTabs(newTabs);
  211. tabListState?.setSelectedKey(tempId);
  212. onSaveTempView?.(newTabs);
  213. }
  214. };
  215. const handleOnDiscardTempView = () => {
  216. tabListState?.setSelectedKey(tabs[0].key);
  217. setTempTab(undefined);
  218. onDiscardTempView?.();
  219. };
  220. const handleOnAddView = () => {
  221. const tempId = generateTempViewId();
  222. const currentTab = tabs.find(tab => tab.key === tabListState?.selectedKey);
  223. if (currentTab) {
  224. const newTabs = [
  225. ...tabs,
  226. {
  227. id: tempId,
  228. key: tempId,
  229. label: 'New View',
  230. query: currentTab.unsavedChanges
  231. ? currentTab.unsavedChanges[0]
  232. : currentTab.query,
  233. querySort: currentTab.unsavedChanges
  234. ? currentTab.unsavedChanges[1]
  235. : currentTab.querySort,
  236. },
  237. ];
  238. navigate({
  239. query: {
  240. ...queryParams,
  241. viewId: tempId,
  242. },
  243. pathname: `/organizations/${orgSlug}/issues/`,
  244. });
  245. setTabs(newTabs);
  246. tabListState?.setSelectedKey(tempId);
  247. onAddView?.(newTabs);
  248. }
  249. };
  250. const makeMenuOptions = (tab: Tab): MenuItemProps[] => {
  251. if (tab.key === 'temporary-tab') {
  252. return makeTempViewMenuOptions({
  253. onSaveTempView: handleOnSaveTempView,
  254. onDiscardTempView: handleOnDiscardTempView,
  255. });
  256. }
  257. if (tab.unsavedChanges) {
  258. return makeUnsavedChangesMenuOptions({
  259. onRename: () => setEditingTabKey(tab.key),
  260. onDuplicate: handleOnDuplicate,
  261. onDelete: tabs.length > 1 ? handleOnDelete : undefined,
  262. onSave: handleOnSaveChanges,
  263. onDiscard: handleOnDiscardChanges,
  264. });
  265. }
  266. return makeDefaultMenuOptions({
  267. onRename: () => setEditingTabKey(tab.key),
  268. onDuplicate: handleOnDuplicate,
  269. onDelete: tabs.length > 1 ? handleOnDelete : undefined,
  270. });
  271. };
  272. const allTabs = tempTab ? [...tabs, tempTab] : tabs;
  273. return (
  274. <DraggableTabList
  275. onReorder={handleOnReorder}
  276. defaultSelectedKey={initialTabKey}
  277. onAddView={handleOnAddView}
  278. orientation="horizontal"
  279. hideBorder
  280. >
  281. {allTabs.map(tab => (
  282. <DraggableTabList.Item
  283. textValue={`${tab.label} tab`}
  284. key={tab.key}
  285. to={normalizeUrl({
  286. query: {
  287. ...queryParams,
  288. query: tab.unsavedChanges?.[0] ?? tab.query,
  289. sort: tab.unsavedChanges?.[1] ?? tab.querySort,
  290. ...(tab.id !== 'temporary-tab' ? {viewId: tab.id} : {}),
  291. },
  292. pathname: `/organizations/${orgSlug}/issues/`,
  293. })}
  294. >
  295. <TabContentWrap selected={tabListState?.selectedKey === tab.key}>
  296. <EditableTabTitle
  297. label={tab.label}
  298. isEditing={editingTabKey === tab.key}
  299. setIsEditing={isEditing => setEditingTabKey(isEditing ? tab.key : null)}
  300. onChange={newLabel => handleOnTabRenamed(newLabel.trim(), tab.key)}
  301. />
  302. {tab.key !== 'temporary-tab' && tab.queryCount !== undefined && (
  303. <StyledBadge>
  304. <QueryCount
  305. hideParens
  306. hideIfEmpty={false}
  307. count={tab.queryCount}
  308. max={1000}
  309. />
  310. </StyledBadge>
  311. )}
  312. {tabListState?.selectedKey === tab.key && (
  313. <DraggableTabMenuButton
  314. hasUnsavedChanges={!!tab.unsavedChanges}
  315. menuOptions={makeMenuOptions(tab)}
  316. aria-label={`${tab.label} Tab Options`}
  317. />
  318. )}
  319. </TabContentWrap>
  320. </DraggableTabList.Item>
  321. ))}
  322. </DraggableTabList>
  323. );
  324. }
  325. const makeDefaultMenuOptions = ({
  326. onRename,
  327. onDuplicate,
  328. onDelete,
  329. }: {
  330. onDelete?: (key: string) => void;
  331. onDuplicate?: (key: string) => void;
  332. onRename?: (key: string) => void;
  333. }): MenuItemProps[] => {
  334. const menuOptions: MenuItemProps[] = [
  335. {
  336. key: 'rename-tab',
  337. label: t('Rename'),
  338. onAction: onRename,
  339. },
  340. {
  341. key: 'duplicate-tab',
  342. label: t('Duplicate'),
  343. onAction: onDuplicate,
  344. },
  345. ];
  346. if (onDelete) {
  347. menuOptions.push({
  348. key: 'delete-tab',
  349. label: t('Delete'),
  350. priority: 'danger',
  351. onAction: onDelete,
  352. });
  353. }
  354. return menuOptions;
  355. };
  356. const makeUnsavedChangesMenuOptions = ({
  357. onRename,
  358. onDuplicate,
  359. onDelete,
  360. onSave,
  361. onDiscard,
  362. }: {
  363. onDelete?: (key: string) => void;
  364. onDiscard?: (key: string) => void;
  365. onDuplicate?: (key: string) => void;
  366. onRename?: (key: string) => void;
  367. onSave?: (key: string) => void;
  368. }): MenuItemProps[] => {
  369. return [
  370. {
  371. key: 'changed',
  372. children: [
  373. {
  374. key: 'save-changes',
  375. label: t('Save Changes'),
  376. priority: 'primary',
  377. onAction: onSave,
  378. },
  379. {
  380. key: 'discard-changes',
  381. label: t('Discard Changes'),
  382. onAction: onDiscard,
  383. },
  384. ],
  385. },
  386. {
  387. key: 'default',
  388. children: makeDefaultMenuOptions({onRename, onDuplicate, onDelete}),
  389. },
  390. ];
  391. };
  392. const makeTempViewMenuOptions = ({
  393. onSaveTempView,
  394. onDiscardTempView,
  395. }: {
  396. onDiscardTempView: () => void;
  397. onSaveTempView: () => void;
  398. }): MenuItemProps[] => {
  399. return [
  400. {
  401. key: 'save-changes',
  402. label: t('Save View'),
  403. priority: 'primary',
  404. onAction: onSaveTempView,
  405. },
  406. {
  407. key: 'discard-changes',
  408. label: t('Discard'),
  409. onAction: onDiscardTempView,
  410. },
  411. ];
  412. };
  413. const TabContentWrap = styled('span')<{selected: boolean}>`
  414. white-space: nowrap;
  415. display: flex;
  416. align-items: center;
  417. flex-direction: row;
  418. padding: 0;
  419. gap: 6px;
  420. ${p => (p.selected ? 'z-index: 1;' : 'z-index: 0;')}
  421. `;
  422. const StyledBadge = styled(Badge)`
  423. display: flex;
  424. height: 16px;
  425. align-items: center;
  426. justify-content: center;
  427. border-radius: 10px;
  428. background: transparent;
  429. border: 1px solid ${p => p.theme.gray200};
  430. color: ${p => p.theme.gray300};
  431. margin-left: 0;
  432. `;