123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458 |
- import 'intersection-observer'; // polyfill
- import {useContext, useState} from 'react';
- import type {InjectedRouter} from 'react-router';
- import styled from '@emotion/styled';
- import type {Node} from '@react-types/shared';
- import Badge from 'sentry/components/badge/badge';
- import {DraggableTabList} from 'sentry/components/draggableTabs/draggableTabList';
- import type {DraggableTabListItemProps} from 'sentry/components/draggableTabs/item';
- import type {MenuItemProps} from 'sentry/components/dropdownMenu';
- import QueryCount from 'sentry/components/queryCount';
- import {TabsContext} from 'sentry/components/tabs';
- import {t} from 'sentry/locale';
- import {defined} from 'sentry/utils';
- import normalizeUrl from 'sentry/utils/url/normalizeUrl';
- import {useNavigate} from 'sentry/utils/useNavigate';
- import {DraggableTabMenuButton} from 'sentry/views/issueList/groupSearchViewTabs/draggableTabMenuButton';
- import EditableTabTitle from 'sentry/views/issueList/groupSearchViewTabs/editableTabTitle';
- import type {IssueSortOptions} from 'sentry/views/issueList/utils';
- export interface Tab {
- id: string;
- key: string;
- label: string;
- query: string;
- querySort: IssueSortOptions;
- content?: React.ReactNode;
- queryCount?: number;
- unsavedChanges?: [string, IssueSortOptions];
- }
- export interface DraggableTabBarProps {
- initialTabKey: string;
- orgSlug: string;
- router: InjectedRouter;
- setTabs: (tabs: Tab[]) => void;
- setTempTab: (tab: Tab | undefined) => void;
- tabs: Tab[];
- /**
- * Callback function to be called when user clicks the `Add View` button.
- */
- onAddView?: (newTabs: Tab[]) => void;
- /**
- * Callback function to be called when user clicks the `Delete` button.
- * Note: The `Delete` button only appears for persistent views
- */
- onDelete?: (newTabs: Tab[]) => void;
- /**
- * Callback function to be called when user clicks on the `Discard Changes` button.
- * Note: The `Discard Changes` button only appears for persistent views when `isChanged=true`
- */
- onDiscard?: () => void;
- /**
- * Callback function to be called when user clicks on the `Discard` button for temporary views.
- * Note: The `Discard` button only appears for temporary views
- */
- onDiscardTempView?: () => void;
- /**
- * Callback function to be called when user clicks the 'Duplicate' button.
- * Note: The `Duplicate` button only appears for persistent views
- */
- onDuplicate?: (newTabs: Tab[]) => void;
- /**
- * Callback function to be called when the user reorders the tabs. Returns the
- * new order of the tabs along with their props.
- */
- onReorder?: (newTabs: Tab[]) => void;
- /**
- * Callback function to be called when user clicks the 'Save' button.
- * Note: The `Save` button only appears for persistent views when `isChanged=true`
- */
- onSave?: (newTabs: Tab[]) => void;
- /**
- * Callback function to be called when user clicks the 'Save View' button for temporary views.
- */
- onSaveTempView?: (newTabs: Tab[]) => void;
- /**
- * Callback function to be called when user renames a tab.
- * Note: The `Rename` button only appears for persistent views
- */
- onTabRenamed?: (newTabs: Tab[], newLabel: string) => void;
- tempTab?: Tab;
- }
- export const generateTempViewId = () => `_${Math.random().toString().substring(2, 7)}`;
- export function DraggableTabBar({
- initialTabKey,
- tabs,
- setTabs,
- tempTab,
- setTempTab,
- orgSlug,
- router,
- onReorder,
- onAddView,
- onDelete,
- onDiscard,
- onDuplicate,
- onTabRenamed,
- onSave,
- onDiscardTempView,
- onSaveTempView,
- }: DraggableTabBarProps) {
- // TODO: Extract this to a separate component encompassing Tab.Item in the future
- const [editingTabKey, setEditingTabKey] = useState<string | null>(null);
- const navigate = useNavigate();
- const {cursor: _cursor, page: _page, ...queryParams} = router?.location?.query ?? {};
- const {tabListState} = useContext(TabsContext);
- const handleOnReorder = (newOrder: Node<DraggableTabListItemProps>[]) => {
- const newTabs = newOrder
- .map(node => {
- const foundTab = tabs.find(tab => tab.key === node.key);
- return foundTab?.key === node.key ? foundTab : null;
- })
- .filter(defined);
- setTabs(newTabs);
- onReorder?.(newTabs);
- };
- const handleOnSaveChanges = () => {
- const originalTab = tabs.find(tab => tab.key === tabListState?.selectedKey);
- if (originalTab) {
- const newTabs = tabs.map(tab => {
- return tab.key === tabListState?.selectedKey && tab.unsavedChanges
- ? {
- ...tab,
- query: tab.unsavedChanges[0],
- querySort: tab.unsavedChanges[1],
- unsavedChanges: undefined,
- }
- : tab;
- });
- setTabs(newTabs);
- onSave?.(newTabs);
- }
- };
- const handleOnDiscardChanges = () => {
- const originalTab = tabs.find(tab => tab.key === tabListState?.selectedKey);
- if (originalTab) {
- setTabs(
- tabs.map(tab => {
- return tab.key === tabListState?.selectedKey
- ? {...tab, unsavedChanges: undefined}
- : tab;
- })
- );
- navigate({
- query: {
- ...queryParams,
- query: originalTab.query,
- sort: originalTab.querySort,
- ...(originalTab.id ? {viewId: originalTab.id} : {}),
- },
- pathname: `/organizations/${orgSlug}/issues/`,
- });
- onDiscard?.();
- }
- };
- const handleOnTabRenamed = (newLabel: string, tabKey: string) => {
- const renamedTab = tabs.find(tb => tb.key === tabKey);
- if (renamedTab && newLabel !== renamedTab.label) {
- const newTabs = tabs.map(tab =>
- tab.key === renamedTab.key ? {...tab, label: newLabel} : tab
- );
- setTabs(newTabs);
- onTabRenamed?.(newTabs, newLabel);
- }
- };
- const handleOnDuplicate = () => {
- const idx = tabs.findIndex(tb => tb.key === tabListState?.selectedKey);
- if (idx !== -1) {
- const tempId = generateTempViewId();
- const duplicatedTab = tabs[idx];
- const newTabs = [
- ...tabs.slice(0, idx + 1),
- {
- ...duplicatedTab,
- id: tempId,
- key: tempId,
- label: `${duplicatedTab.label} (Copy)`,
- },
- ...tabs.slice(idx + 1),
- ];
- navigate({
- query: {
- ...queryParams,
- viewId: tempId,
- },
- pathname: `/organizations/${orgSlug}/issues/`,
- });
- setTabs(newTabs);
- tabListState?.setSelectedKey(tempId);
- onDuplicate?.(newTabs);
- }
- };
- const handleOnDelete = () => {
- if (tabs.length > 1) {
- const newTabs = tabs.filter(tb => tb.key !== tabListState?.selectedKey);
- setTabs(newTabs);
- tabListState?.setSelectedKey(newTabs[0].key);
- onDelete?.(newTabs);
- }
- };
- const handleOnSaveTempView = () => {
- if (tempTab) {
- const tempId = generateTempViewId();
- const newTab: Tab = {
- id: tempId,
- key: tempId,
- label: 'New View',
- query: tempTab.query,
- querySort: tempTab.querySort,
- };
- const newTabs = [...tabs, newTab];
- setTabs(newTabs);
- tabListState?.setSelectedKey(tempId);
- onSaveTempView?.(newTabs);
- }
- };
- const handleOnDiscardTempView = () => {
- tabListState?.setSelectedKey(tabs[0].key);
- setTempTab(undefined);
- onDiscardTempView?.();
- };
- const handleOnAddView = () => {
- const tempId = generateTempViewId();
- const currentTab = tabs.find(tab => tab.key === tabListState?.selectedKey);
- if (currentTab) {
- const newTabs = [
- ...tabs,
- {
- id: tempId,
- key: tempId,
- label: 'New View',
- query: currentTab.unsavedChanges
- ? currentTab.unsavedChanges[0]
- : currentTab.query,
- querySort: currentTab.unsavedChanges
- ? currentTab.unsavedChanges[1]
- : currentTab.querySort,
- },
- ];
- navigate({
- query: {
- ...queryParams,
- viewId: tempId,
- },
- pathname: `/organizations/${orgSlug}/issues/`,
- });
- setTabs(newTabs);
- tabListState?.setSelectedKey(tempId);
- onAddView?.(newTabs);
- }
- };
- const makeMenuOptions = (tab: Tab): MenuItemProps[] => {
- if (tab.key === 'temporary-tab') {
- return makeTempViewMenuOptions({
- onSaveTempView: handleOnSaveTempView,
- onDiscardTempView: handleOnDiscardTempView,
- });
- }
- if (tab.unsavedChanges) {
- return makeUnsavedChangesMenuOptions({
- onRename: () => setEditingTabKey(tab.key),
- onDuplicate: handleOnDuplicate,
- onDelete: tabs.length > 1 ? handleOnDelete : undefined,
- onSave: handleOnSaveChanges,
- onDiscard: handleOnDiscardChanges,
- });
- }
- return makeDefaultMenuOptions({
- onRename: () => setEditingTabKey(tab.key),
- onDuplicate: handleOnDuplicate,
- onDelete: tabs.length > 1 ? handleOnDelete : undefined,
- });
- };
- const allTabs = tempTab ? [...tabs, tempTab] : tabs;
- return (
- <DraggableTabList
- onReorder={handleOnReorder}
- defaultSelectedKey={initialTabKey}
- onAddView={handleOnAddView}
- orientation="horizontal"
- hideBorder
- >
- {allTabs.map(tab => (
- <DraggableTabList.Item
- textValue={`${tab.label} tab`}
- key={tab.key}
- to={normalizeUrl({
- query: {
- ...queryParams,
- query: tab.unsavedChanges?.[0] ?? tab.query,
- sort: tab.unsavedChanges?.[1] ?? tab.querySort,
- ...(tab.id !== 'temporary-tab' ? {viewId: tab.id} : {}),
- },
- pathname: `/organizations/${orgSlug}/issues/`,
- })}
- >
- <TabContentWrap selected={tabListState?.selectedKey === tab.key}>
- <EditableTabTitle
- label={tab.label}
- isEditing={editingTabKey === tab.key}
- setIsEditing={isEditing => setEditingTabKey(isEditing ? tab.key : null)}
- onChange={newLabel => handleOnTabRenamed(newLabel.trim(), tab.key)}
- />
- {tab.key !== 'temporary-tab' && tab.queryCount !== undefined && (
- <StyledBadge>
- <QueryCount
- hideParens
- hideIfEmpty={false}
- count={tab.queryCount}
- max={1000}
- />
- </StyledBadge>
- )}
- {tabListState?.selectedKey === tab.key && (
- <DraggableTabMenuButton
- hasUnsavedChanges={!!tab.unsavedChanges}
- menuOptions={makeMenuOptions(tab)}
- aria-label={`${tab.label} Tab Options`}
- />
- )}
- </TabContentWrap>
- </DraggableTabList.Item>
- ))}
- </DraggableTabList>
- );
- }
- const makeDefaultMenuOptions = ({
- onRename,
- onDuplicate,
- onDelete,
- }: {
- onDelete?: (key: string) => void;
- onDuplicate?: (key: string) => void;
- onRename?: (key: string) => void;
- }): MenuItemProps[] => {
- const menuOptions: MenuItemProps[] = [
- {
- key: 'rename-tab',
- label: t('Rename'),
- onAction: onRename,
- },
- {
- key: 'duplicate-tab',
- label: t('Duplicate'),
- onAction: onDuplicate,
- },
- ];
- if (onDelete) {
- menuOptions.push({
- key: 'delete-tab',
- label: t('Delete'),
- priority: 'danger',
- onAction: onDelete,
- });
- }
- return menuOptions;
- };
- const makeUnsavedChangesMenuOptions = ({
- onRename,
- onDuplicate,
- onDelete,
- onSave,
- onDiscard,
- }: {
- onDelete?: (key: string) => void;
- onDiscard?: (key: string) => void;
- onDuplicate?: (key: string) => void;
- onRename?: (key: string) => void;
- onSave?: (key: string) => void;
- }): MenuItemProps[] => {
- return [
- {
- key: 'changed',
- children: [
- {
- key: 'save-changes',
- label: t('Save Changes'),
- priority: 'primary',
- onAction: onSave,
- },
- {
- key: 'discard-changes',
- label: t('Discard Changes'),
- onAction: onDiscard,
- },
- ],
- },
- {
- key: 'default',
- children: makeDefaultMenuOptions({onRename, onDuplicate, onDelete}),
- },
- ];
- };
- const makeTempViewMenuOptions = ({
- onSaveTempView,
- onDiscardTempView,
- }: {
- onDiscardTempView: () => void;
- onSaveTempView: () => void;
- }): MenuItemProps[] => {
- return [
- {
- key: 'save-changes',
- label: t('Save View'),
- priority: 'primary',
- onAction: onSaveTempView,
- },
- {
- key: 'discard-changes',
- label: t('Discard'),
- onAction: onDiscardTempView,
- },
- ];
- };
- const TabContentWrap = styled('span')<{selected: boolean}>`
- white-space: nowrap;
- display: flex;
- align-items: center;
- flex-direction: row;
- padding: 0;
- gap: 6px;
- ${p => (p.selected ? 'z-index: 1;' : 'z-index: 0;')}
- `;
- const StyledBadge = styled(Badge)`
- display: flex;
- height: 16px;
- align-items: center;
- justify-content: center;
- border-radius: 10px;
- background: transparent;
- border: 1px solid ${p => p.theme.gray200};
- color: ${p => p.theme.gray300};
- margin-left: 0;
- `;
|