diff --git a/frontend/documentation/components/DropdownMenu.stories.tsx b/frontend/documentation/components/DropdownMenu.stories.tsx index 1270adc60df5..4225ff760bc9 100644 --- a/frontend/documentation/components/DropdownMenu.stories.tsx +++ b/frontend/documentation/components/DropdownMenu.stories.tsx @@ -1,45 +1,100 @@ -import React from 'react' +import React, { useState } from 'react' import type { Meta, StoryObj } from 'storybook' import { screen, userEvent, within } from 'storybook/test' -import DropdownMenu from 'components/base/DropdownMenu' +import DropdownMenu, { DropdownMenuItem } from 'components/base/DropdownMenu' +import Button from 'components/base/forms/Button' +import Icon from 'components/icons/Icon' -const meta: Meta = { +const meta: Meta = { + component: DropdownMenu, parameters: { - docs: { story: { height: '260px' } }, + docs: { story: { height: '320px' } }, layout: 'centered', }, title: 'Components/Data Display/DropdownMenu', } export default meta -type Story = StoryObj +type Story = StoryObj -const DEMO_ITEMS = [ - { label: 'Edit', onClick: () => {} }, - { label: 'Duplicate', onClick: () => {} }, - { label: 'Archive', onClick: () => {} }, - { label: 'Delete', onClick: () => {} }, -] +const noop = () => undefined -export const Default: Story = { - render: () => , +const ActionsMenu = () => ( + + + + Copy feature name + + + + Show audit logs + + + + Show history + + + + Remove feature + + +) + +const SECTIONS = ['Value', 'Segment overrides', 'History', 'Settings'] + +const SectionsMenu = () => { + const [current, setCurrent] = useState(2) + return ( + {SECTIONS[current]}} + > + {SECTIONS.map((section, i) => ( + setCurrent(i)} + > + {section} + + ))} + + ) } -export const Open: Story = { +const openMenu = async (canvasElement: HTMLElement, name: string) => { + const canvas = within(canvasElement) + await userEvent.click(canvas.getByRole('button', { name })) + await screen.findByRole('dialog') +} + +export const Actions: Story = { + parameters: { chromatic: { delay: 300 } }, + play: ({ canvasElement }: { canvasElement: HTMLElement }) => + openMenu(canvasElement, 'Feature actions'), + render: () => , +} + +export const CurrentItem: Story = { + parameters: { chromatic: { delay: 300 } }, + play: ({ canvasElement }: { canvasElement: HTMLElement }) => + openMenu(canvasElement, 'History'), + render: () => , +} + +// On phones the menu opens as a bottom sheet +export const MobileSheet: Story = { + globals: { viewport: { isRotated: false, value: 'mobile1' } }, parameters: { chromatic: { delay: 300 }, - docs: { - description: { - story: - 'Menu in its open state. Storybook clicks the trigger in `play`; the menu portals into `document.body`, so it is queried via `screen` rather than the local canvas.', - }, - }, - }, - play: async ({ canvasElement }: { canvasElement: HTMLElement }) => { - const canvas = within(canvasElement) - await userEvent.click(canvas.getByRole('button')) - await screen.findByText('Edit') + docs: { story: { height: '420px', inline: false } }, }, - render: () => , + play: ({ canvasElement }: { canvasElement: HTMLElement }) => + openMenu(canvasElement, 'Feature actions'), + render: () => , } diff --git a/frontend/documentation/components/OverflowNav.stories.tsx b/frontend/documentation/components/OverflowNav.stories.tsx index 75233f6a09b1..fd30cca1d60b 100644 --- a/frontend/documentation/components/OverflowNav.stories.tsx +++ b/frontend/documentation/components/OverflowNav.stories.tsx @@ -48,6 +48,7 @@ const NAV_ITEMS = ( export const ProjectNavbar: Story = { render: () => ( ( ( false); if (!isDropdownVisible) { - await this.click(byId('segment_overrides')); + await this.openFeatureTab('Segment Overrides'); } await this.click(dropdownSelector); await this.waitForElementVisible(this.segmentOverrideValueField(index)); @@ -638,7 +638,7 @@ export class E2EHelpers { // Add a remote config override for a segment picked by name, so other // segments in a shared project can't shift the selection async addSegmentOverrideConfigForSegment(segmentName: string, value: string) { - await this.click(byId('segment_overrides')); + await this.openFeatureTab('Segment Overrides'); // E2E builds render the select's options as plain links await this.page .locator('[data-test^="select-segment-option-"]') @@ -659,7 +659,7 @@ export class E2EHelpers { // Set segment override index (for reordering) async setSegmentOverrideIndex(index: number, newIndex: number) { - await this.click(byId('segment_overrides')); + await this.openFeatureTab('Segment Overrides'); await this.setText(byId(`sort-${index}`), `${newIndex}`); } @@ -809,15 +809,28 @@ export class E2EHelpers { throw new Error(`Try-it failed after ${maxRetries} attempts: ${key}.${field} never became ${expected}`); } + // Open a feature drawer tab, from "More tabs" when it has overflowed + async openFeatureTab(name: string) { + const tab = this.page + .getByRole('button', { name: new RegExp(`^${name}`) }) + .filter({ visible: true }); + if (!(await tab.count())) { + await this.page.getByRole('button', { exact: true, name: 'More tabs' }).click(); + } + await tab.first().click(); + } + // Go to feature versions async goToFeatureVersions(featureName: string) { await this.gotoFeature(featureName); - if (await this.isElementExists('change-history')) { - await this.click(byId('change-history')); - } else { - await this.click(byId('tabs-overflow-button')); - await this.click(byId('change-history')); + // History is a tab, or an item in the "More tabs" menu when the tabs overflow + const history = this.page + .getByRole('button', { exact: true, name: 'History' }) + .filter({ visible: true }); + if (!(await history.count())) { + await this.page.getByRole('button', { exact: true, name: 'More tabs' }).click(); } + await history.first().click(); } // Compare version diff --git a/frontend/e2e/tests/environment-permission-test.pw.ts b/frontend/e2e/tests/environment-permission-test.pw.ts index 7bc3a5b56ee3..8a09ae4fac32 100644 --- a/frontend/e2e/tests/environment-permission-test.pw.ts +++ b/frontend/e2e/tests/environment-permission-test.pw.ts @@ -26,6 +26,7 @@ test.describe('Environment Permission Tests', () => { gotoTraits, login, logout, + openFeatureTab, setUserPermission, toggleFeature, waitForElementClickable, @@ -100,7 +101,7 @@ test.describe('Environment Permission Tests', () => { await login(E2E_NON_ADMIN_USER_WITH_ENV_PERMISSIONS, PASSWORD) await gotoProject(PROJECT_NAME) await gotoFeature('my_feature') - await click(byId('segment_overrides')) + await openFeatureTab('Segment Overrides') await waitForElementNotClickable('#update-feature-segments-btn') await closeModal() await logout() @@ -112,7 +113,7 @@ test.describe('Environment Permission Tests', () => { await login(E2E_NON_ADMIN_USER_WITH_ENV_PERMISSIONS, PASSWORD) await gotoProject(PROJECT_NAME) await gotoFeature('my_feature') - await click(byId('segment_overrides')) + await openFeatureTab('Segment Overrides') await waitForElementClickable('#update-feature-segments-btn') await closeModal() await logout() diff --git a/frontend/e2e/tests/experimentation-test.pw.ts b/frontend/e2e/tests/experimentation-test.pw.ts index 473fa2081945..d1cf11d3e1a2 100644 --- a/frontend/e2e/tests/experimentation-test.pw.ts +++ b/frontend/e2e/tests/experimentation-test.pw.ts @@ -112,8 +112,14 @@ test.describe('Experimentation Tests', () => { page, }, testInfo) => { await skipOnSaas() - const { click, closeModal, featureValueField, gotoFeature, gotoFeatures } = - await setup(page) + const { + click, + closeModal, + featureValueField, + gotoFeature, + gotoFeatures, + openFeatureTab, + } = await setup(page) log('Create an experiment') await createExperiment(page, FIRST_EXPERIMENT) @@ -127,7 +133,7 @@ test.describe('Experimentation Tests', () => { `This flag is part of the experiment ${FIRST_EXPERIMENT}`, ) await expect(featureValueField()).not.toBeEditable() - await click(byId('segment_overrides')) + await openFeatureTab('Segment Overrides') await expect(rolloutOverride(page)).toHaveCount(1) await closeModal() }) @@ -142,6 +148,7 @@ test.describe('Experimentation Tests', () => { closeModal, gotoFeature, gotoFeatures, + openFeatureTab, waitForToast, } = await setup(page) @@ -172,7 +179,7 @@ test.describe('Experimentation Tests', () => { '100', ) await expect(page.locator(byId('featureVariationWeighta'))).toHaveValue('0') - await click(byId('segment_overrides')) + await openFeatureTab('Segment Overrides') await expectNoRolloutOverride(page) await closeModal() }) diff --git a/frontend/web/components/IntegrationList.tsx b/frontend/web/components/IntegrationList.tsx index da603c557cc0..5183a21160c5 100644 --- a/frontend/web/components/IntegrationList.tsx +++ b/frontend/web/components/IntegrationList.tsx @@ -14,7 +14,8 @@ import { } from 'common/types/responses' import map from 'lodash/map' import Button from './base/forms/Button' -import DropdownMenu from './base/DropdownMenu' +import DropdownMenu, { DropdownMenuItem } from './base/DropdownMenu' +import { configuredActionsLabel } from './integrations/configuredActionsLabel' import Icon from './icons/Icon' import { IonIcon } from '@ionic/react' import { close as closeIcon } from 'ionicons/icons' @@ -270,7 +271,22 @@ const Integration: FC = (props) => { } return button } - return + return ( + + {actions.map((action) => ( + + {action.label} + + ))} + + ) } return ( @@ -325,7 +341,7 @@ const Integration: FC = (props) => { )} {activeIntegrations && - activeIntegrations.map((integration) => ( + activeIntegrations.map((integration, index) => (
= (props) => { integration={props.integration} /> -
e.stopPropagation()}> - edit(integration), - }, - { - dataTest: 'delete-integration', - label: 'Delete', - onClick: () => remove(integration), - }, - ]} - /> -
+ + edit(integration)}> + Edit + + remove(integration)} + > + Delete + +
))} diff --git a/frontend/web/components/base/DropdownMenu.tsx b/frontend/web/components/base/DropdownMenu.tsx deleted file mode 100644 index 8c5daed73556..000000000000 --- a/frontend/web/components/base/DropdownMenu.tsx +++ /dev/null @@ -1,117 +0,0 @@ -import React, { useLayoutEffect, useRef, useState } from 'react' -import Icon, { IconName } from 'components/icons/Icon' -import classNames from 'classnames' -import useOutsideClick from 'common/useOutsideClick' -import { createPortal } from 'react-dom' -import { calculateListPosition } from 'common/utils/calculateListPosition' - -type MenuItem = { - icon?: IconName - label: string | React.ReactNode - onClick: (e: React.MouseEvent) => void - disabled?: boolean - tooltip?: string - dataTest?: string - className?: string -} - -type DropdownMenuProps = { - items: MenuItem[] - className?: string - buttonClassName?: string - iconClassName?: string - iconWidth?: number - iconFill?: string -} - -const DropdownMenu: React.FC = ({ - buttonClassName, - className, - iconClassName, - iconFill = '#9DA4AE', - iconWidth = 18, - items, -}) => { - const [isOpen, setIsOpen] = useState(false) - const btnRef = useRef(null) - const dropDownRef = useRef(null) - useOutsideClick(dropDownRef, () => setIsOpen(false)) - - useLayoutEffect(() => { - if (!isOpen || !dropDownRef.current || !btnRef.current) return - const listPosition = calculateListPosition( - btnRef.current, - dropDownRef.current, - ) - dropDownRef.current.style.top = `${listPosition.top}px` - dropDownRef.current.style.left = `${listPosition.left}px` - }, [btnRef, isOpen, dropDownRef]) - - return ( -
- - - {isOpen && - createPortal( -
- {items.map((item, index) => ( - { - e.stopPropagation() - if (!item.disabled) { - item.onClick(e) - setIsOpen(false) - } - }} - style={{ - zIndex: 999999, - }} - > - {item.icon && ( - - )} - {item.label} -
- } - place='right' - > - {item.tooltip ?? ''} - - ))} -
, - document.body, - )} - - ) -} - -export default DropdownMenu diff --git a/frontend/web/components/base/DropdownMenu/DropdownMenu.scss b/frontend/web/components/base/DropdownMenu/DropdownMenu.scss new file mode 100644 index 000000000000..0d0936bbf1ef --- /dev/null +++ b/frontend/web/components/base/DropdownMenu/DropdownMenu.scss @@ -0,0 +1,117 @@ +.ds-dropdown-menu { + // States and the sheet set these; the elements below only read them + --ds-dropdown-menu-row: 44px; + --ds-dropdown-menu-font: var(--font-size-body-md); + --ds-dropdown-menu-icon: 16px; + --ds-dropdown-menu-gap: 12px; + + display: flex; + flex-direction: column; + gap: 2px; + padding: 4px; + min-width: 200px; + + // In a bottom sheet rows are larger, like native action sheets. There is no + // 16px body token, so the size is set here + &--sheet { + --ds-dropdown-menu-row: 48px; + --ds-dropdown-menu-font: 16px; + --ds-dropdown-menu-icon: 20px; + } + + &__item { + --ds-dropdown-menu-text: var(--color-text-default); + --ds-dropdown-menu-icon-color: var(--color-icon-secondary); + + display: flex; + min-height: var(--ds-dropdown-menu-row); + border-radius: var(--radius-md); + align-items: center; + gap: var(--ds-dropdown-menu-gap); + width: 100%; + padding: 0 12px; + font-size: var(--ds-dropdown-menu-font); + text-align: left; + text-decoration: none; + + // Scoped to outrank the global link colours (body.dark a), as rows can be + // links + .ds-dropdown-menu &, + .ds-dropdown-menu &:hover, + .ds-dropdown-menu &:focus { + color: var(--ds-dropdown-menu-text); + } + + // Touch screens keep :hover after a tap, so only devices that can hover + // get it + @media (hover: hover) { + &:not([aria-disabled='true']):hover { + background: var(--color-surface-hover); + } + } + + // Inset, so the ring stays inside the row and keeps its corners. Set here + // too, as link rows don't get BareButton's ring + &:focus-visible { + outline: 2px solid var(--color-border-action); + outline-offset: -2px; + } + + // true for a selected option, page for the current page's link + &[aria-current='true'], + &[aria-current='page'] { + --ds-dropdown-menu-text: var(--color-text-action); + --ds-dropdown-menu-icon-color: var(--color-icon-action); + + font-weight: var(--font-weight-semibold); + background: var(--color-surface-action-subtle); + } + + &--destructive { + --ds-dropdown-menu-text: var(--color-text-danger); + --ds-dropdown-menu-icon-color: var(--color-icon-danger); + } + + &[aria-disabled='true'] { + --ds-dropdown-menu-text: var(--color-text-disabled); + --ds-dropdown-menu-icon-color: var(--color-icon-disabled); + + cursor: not-allowed; + } + } + + &__content { + display: flex; + flex: 1; + flex-direction: column; + min-width: 0; + } + + // The label and an optional icon before it + &__label { + display: flex; + align-items: center; + gap: var(--ds-dropdown-menu-gap); + } + + &__label > svg, + &__check { + flex-shrink: 0; + width: var(--ds-dropdown-menu-icon); + height: var(--ds-dropdown-menu-icon); + color: var(--ds-dropdown-menu-icon-color); + } + + // Why a disabled item can't be used; its description for screen readers + &__reason { + font-size: var(--font-size-body-sm); + color: var(--color-text-secondary); + } + + // Lines up with the text, not the icon + &__label:has(> svg) + &__reason { + padding-left: calc( + var(--ds-dropdown-menu-icon) + var(--ds-dropdown-menu-gap) + ); + } +} diff --git a/frontend/web/components/base/DropdownMenu/DropdownMenu.tsx b/frontend/web/components/base/DropdownMenu/DropdownMenu.tsx new file mode 100644 index 000000000000..ed3e0bdc6a6b --- /dev/null +++ b/frontend/web/components/base/DropdownMenu/DropdownMenu.tsx @@ -0,0 +1,58 @@ +import { cloneElement, FC, ReactElement, ReactNode } from 'react' +import Popover, { PopoverPlacement } from 'components/base/Popover' +import IconButton from 'components/base/IconButton' +import Icon from 'components/icons/Icon' +import classNames from 'classnames' +import { useBreakpoint } from 'common/hooks/useBreakpoint' +import { DropdownMenuCloseProvider } from './DropdownMenuContext' +import './DropdownMenu.scss' + +export type DropdownMenuProps = { + // Names the menu, and the default trigger + 'aria-label': string + // Any element; it receives the ref and open/close props. Defaults to a + // "more" button. + trigger?: ReactElement + children: ReactNode + placement?: PopoverPlacement +} + +const DropdownMenu: FC = ({ + 'aria-label': ariaLabel, + children, + placement = 'bottom-end', + trigger, +}) => { + // Popover opens as a sheet on the same breakpoint, where rows get larger + const asSheet = useBreakpoint('isPhone') + return ( + + cloneElement( + trigger ?? ( + + + + ), + props, + ) + } + > + {(close) => ( + +
+ {children} +
+
+ )} +
+ ) +} + +export default DropdownMenu diff --git a/frontend/web/components/base/DropdownMenu/DropdownMenuContext.ts b/frontend/web/components/base/DropdownMenu/DropdownMenuContext.ts new file mode 100644 index 000000000000..98ada1b1fc1e --- /dev/null +++ b/frontend/web/components/base/DropdownMenu/DropdownMenuContext.ts @@ -0,0 +1,13 @@ +import { createContext, useContext } from 'react' + +// Holds the menu's close; null outside a menu +const DropdownMenuContext = createContext<(() => void) | null>(null) + +const noop = () => undefined + +export const DropdownMenuCloseProvider = DropdownMenuContext.Provider +export const useCloseDropdownMenu = () => + useContext(DropdownMenuContext) ?? noop +// Nav links render as menu rows when they overflow into a menu +export const useIsInDropdownMenu = () => + useContext(DropdownMenuContext) !== null diff --git a/frontend/web/components/base/DropdownMenu/DropdownMenuItem.tsx b/frontend/web/components/base/DropdownMenu/DropdownMenuItem.tsx new file mode 100644 index 000000000000..f7af3622dfe6 --- /dev/null +++ b/frontend/web/components/base/DropdownMenu/DropdownMenuItem.tsx @@ -0,0 +1,70 @@ +import { FC, MouseEvent, ReactNode, useId } from 'react' +import classNames from 'classnames' +import BareButton from 'components/base/forms/BareButton' +import Icon from 'components/icons/Icon' +import { useCloseDropdownMenu } from './DropdownMenuContext' + +export type DropdownMenuItemProps = { + // The label, with an optional icon first: Copy + children: ReactNode + onSelect: (e: MouseEvent) => void + // The selected option, as in a section switcher: ticked and announced + current?: boolean + destructive?: boolean + disabled?: boolean + // Shown under the label while disabled + disabledReason?: string +} + +const DropdownMenuItem: FC = ({ + children, + current = false, + destructive = false, + disabled = false, + disabledReason, + onSelect, +}) => { + const close = useCloseDropdownMenu() + const id = useId() + const reasonId = `${id}-reason` + const reason = disabled ? disabledReason : undefined + // aria-disabled keeps the item focusable, and the reason shows under the + // label, so keyboard and touch users both get it. Named by the label alone, + // so the reason is read once, as the description + return ( + { + if (disabled) return + onSelect(e) + close() + }} + > + + + {children} + + {reason && ( + + {reason} + + )} + + {current && ( + + )} + + ) +} + +export default DropdownMenuItem diff --git a/frontend/web/components/base/DropdownMenu/DropdownMenuLink.tsx b/frontend/web/components/base/DropdownMenu/DropdownMenuLink.tsx new file mode 100644 index 000000000000..8cf2db71c942 --- /dev/null +++ b/frontend/web/components/base/DropdownMenu/DropdownMenuLink.tsx @@ -0,0 +1,25 @@ +import { FC } from 'react' +import { NavLink, NavLinkProps } from 'react-router-dom' +import { useCloseDropdownMenu } from './DropdownMenuContext' + +// A menu row that navigates; the current page gets the selected look. +// Children are the label, with an optional icon first. +const DropdownMenuLink: FC = ({ children, onClick, ...rest }) => { + const close = useCloseDropdownMenu() + return ( + { + onClick?.(e) + close() + }} + > + + {children} + + + ) +} + +export default DropdownMenuLink diff --git a/frontend/web/components/base/DropdownMenu/index.ts b/frontend/web/components/base/DropdownMenu/index.ts new file mode 100644 index 000000000000..9b564469cc92 --- /dev/null +++ b/frontend/web/components/base/DropdownMenu/index.ts @@ -0,0 +1,6 @@ +export { default } from './DropdownMenu' +export { default as DropdownMenuItem } from './DropdownMenuItem' +export { default as DropdownMenuLink } from './DropdownMenuLink' +export type { DropdownMenuProps } from './DropdownMenu' +export type { DropdownMenuItemProps } from './DropdownMenuItem' +export { useIsInDropdownMenu } from './DropdownMenuContext' diff --git a/frontend/web/components/base/Popover/BottomSheet/BottomSheet.tsx b/frontend/web/components/base/Popover/BottomSheet/BottomSheet.tsx index 753f1e68e46a..15b8382bd1f0 100644 --- a/frontend/web/components/base/Popover/BottomSheet/BottomSheet.tsx +++ b/frontend/web/components/base/Popover/BottomSheet/BottomSheet.tsx @@ -11,6 +11,7 @@ import { useInteractions, useRole, } from '@floating-ui/react' +import { stopPropagation } from 'components/base/Popover/stopPropagation' import './BottomSheet.scss' type BottomSheetProps = { @@ -61,7 +62,12 @@ const BottomSheet: FC = ({ return ( - + & { @@ -51,6 +53,10 @@ const Popover: FC = ({ const [isOpen, setIsOpen] = useState(false) const close = () => setIsOpen(false) const asSheet = useBreakpoint('isPhone') + // Back or forward leaves the page, so an open popover goes with it. There + // is no router in stories + const history = useHistory() + useEffect(() => history?.listen(() => setIsOpen(false)), [history]) const { context, refs, x, y } = useFloating({ middleware: [ @@ -87,7 +93,10 @@ const Popover: FC = ({ {renderTrigger( { ref: refs.setReference, - ...getReferenceProps(), + ...getReferenceProps({ + onClick: stopPropagation, + onKeyDown: stopPropagation, + }), // useRole is off for the sheet, so state the popup here ...(asSheet && { 'aria-expanded': isOpen, @@ -115,7 +124,8 @@ const Popover: FC = ({ className={classNames('ds-popover', className)} data-placement={context.placement} aria-label={ariaLabel} - {...getFloatingProps()} + // Keys pass through, so Escape still closes it + {...getFloatingProps({ onClick: stopPropagation })} > {typeof children === 'function' ? children(close) : children} diff --git a/frontend/web/components/base/Popover/index.ts b/frontend/web/components/base/Popover/index.ts index 47263e10f2a0..5bf8b0be8525 100644 --- a/frontend/web/components/base/Popover/index.ts +++ b/frontend/web/components/base/Popover/index.ts @@ -1,2 +1,6 @@ export { default } from './Popover' -export type { PopoverProps, PopoverTriggerProps } from './Popover' +export type { + PopoverPlacement, + PopoverProps, + PopoverTriggerProps, +} from './Popover' diff --git a/frontend/web/components/base/Popover/stopPropagation.ts b/frontend/web/components/base/Popover/stopPropagation.ts new file mode 100644 index 000000000000..299f372a0ffa --- /dev/null +++ b/frontend/web/components/base/Popover/stopPropagation.ts @@ -0,0 +1,6 @@ +import { SyntheticEvent } from 'react' + +// Popovers often open from a clickable row, and the panel renders in a portal +// that React still bubbles through. Clicks on the trigger or inside the panel +// must not also reach the row +export const stopPropagation = (e: SyntheticEvent) => e.stopPropagation() diff --git a/frontend/web/components/experiments/ExperimentActionDropdown/ExperimentActionDropdown.tsx b/frontend/web/components/experiments/ExperimentActionDropdown/ExperimentActionDropdown.tsx index c112816c17b7..085178e3cbd8 100644 --- a/frontend/web/components/experiments/ExperimentActionDropdown/ExperimentActionDropdown.tsx +++ b/frontend/web/components/experiments/ExperimentActionDropdown/ExperimentActionDropdown.tsx @@ -6,9 +6,15 @@ import { useStartExperimentMutation, } from 'common/services/useExperiment' import { ENABLE_EXPERIMENT_LIFECYCLE } from 'components/experiments/constants' -import DropdownMenu from 'components/base/DropdownMenu' +import DropdownMenu, { DropdownMenuItem } from 'components/base/DropdownMenu' import CompleteExperimentModal from 'components/experiments/CompleteExperimentModal' +type ExperimentAction = { + label: string + onClick: () => void + destructive?: boolean +} + type ExperimentActionDropdownProps = { experimentId: number experimentName: string @@ -83,13 +89,13 @@ const ExperimentActionDropdown: FC = ({ }) }, [deleteExperiment, experimentName, params]) - const items = useMemo(() => { + const items = useMemo((): ExperimentAction[] => { switch (status) { case 'created': return [ { label: 'Start Experiment', onClick: handleStart }, { - className: 'text-danger', + destructive: true, label: 'Delete', onClick: handleDelete, }, @@ -109,7 +115,7 @@ const ExperimentActionDropdown: FC = ({ case 'completed': return [ { - className: 'text-danger', + destructive: true, label: 'Delete', onClick: handleDelete, }, @@ -119,7 +125,19 @@ const ExperimentActionDropdown: FC = ({ } }, [status, handleStart, handlePause, handleComplete, handleDelete]) - return + return ( + + {items.map((item) => ( + + {item.label} + + ))} + + ) } export default ExperimentActionDropdown diff --git a/frontend/web/components/integrations/__tests__/configuredActionsLabel.test.ts b/frontend/web/components/integrations/__tests__/configuredActionsLabel.test.ts new file mode 100644 index 000000000000..f4807485ab87 --- /dev/null +++ b/frontend/web/components/integrations/__tests__/configuredActionsLabel.test.ts @@ -0,0 +1,16 @@ +import { configuredActionsLabel } from 'components/integrations/configuredActionsLabel' + +describe('configuredActionsLabel', () => { + it.each` + title | index | count | expected + ${'Grafana'} | ${0} | ${1} | ${'Actions for Grafana'} + ${'Grafana'} | ${1} | ${3} | ${'Actions for Grafana, 2 of 3'} + ${undefined} | ${0} | ${1} | ${'Actions for integration'} + ${undefined} | ${0} | ${2} | ${'Actions for integration, 1 of 2'} + `( + '$title, $index of $count: $expected', + ({ count, expected, index, title }) => { + expect(configuredActionsLabel(title, index, count)).toBe(expected) + }, + ) +}) diff --git a/frontend/web/components/integrations/configuredActionsLabel.ts b/frontend/web/components/integrations/configuredActionsLabel.ts new file mode 100644 index 000000000000..638ca478ea0b --- /dev/null +++ b/frontend/web/components/integrations/configuredActionsLabel.ts @@ -0,0 +1,9 @@ +// Several configured instances of one integration need their own names +export const configuredActionsLabel = ( + title: string | undefined, + index: number, + count: number, +): string => { + const name = `Actions for ${title ?? 'integration'}` + return count > 1 ? `${name}, ${index + 1} of ${count}` : name +} diff --git a/frontend/web/components/navigation/EnvironmentAside.tsx b/frontend/web/components/navigation/EnvironmentAside.tsx index 2629c396da77..0598a8aeede4 100644 --- a/frontend/web/components/navigation/EnvironmentAside.tsx +++ b/frontend/web/components/navigation/EnvironmentAside.tsx @@ -242,7 +242,8 @@ const EnvironmentAside: FC = ({ environmentId, projectId }) => { {E2E && createEnvironmentButton} } force containerClassName='d-block d-md-none' > diff --git a/frontend/web/components/navigation/NavSubLink.tsx b/frontend/web/components/navigation/NavSubLink.tsx index bb407abc74b7..b663fb9b0251 100644 --- a/frontend/web/components/navigation/NavSubLink.tsx +++ b/frontend/web/components/navigation/NavSubLink.tsx @@ -3,6 +3,10 @@ import type * as H from 'history' import { LinkProps, NavLink, match } from 'react-router-dom' import { IonIcon } from '@ionic/react' import classNames from 'classnames' +import { + DropdownMenuLink, + useIsInDropdownMenu, +} from 'components/base/DropdownMenu' type NavSubLinkType = LinkProps & { icon: string | ReactNode @@ -19,6 +23,15 @@ const NavSubLink: FC = ({ isActive, ...rest }) => { + const iconNode = typeof icon === 'string' ? : icon + if (useIsInDropdownMenu()) { + return ( + + {iconNode} + {children} + + ) + } return ( = ({ className={classNames(rest.className, 'py-md-2 py-1 px-1 nav-sub-link')} >
- {typeof icon === 'string' ? : icon} + {iconNode} {children}
diff --git a/frontend/web/components/navigation/OverflowNav.tsx b/frontend/web/components/navigation/OverflowNav.tsx index 3544dbbdc4f6..6ef6d6374412 100644 --- a/frontend/web/components/navigation/OverflowNav.tsx +++ b/frontend/web/components/navigation/OverflowNav.tsx @@ -1,28 +1,33 @@ -import React, { FC, ReactNode, useEffect, useRef, useState } from 'react' -import InlineModal from 'components/InlineModal' -import { IonIcon } from '@ionic/react' -import { ellipsisHorizontal } from 'ionicons/icons' -import Button from 'components/base/forms/Button' +import React, { FC, ReactNode, useRef } from 'react' +import IconButton from 'components/base/IconButton' +import Icon from 'components/icons/Icon' +import DropdownMenu from 'components/base/DropdownMenu' import classNames from 'classnames' -import { useHistory } from 'react-router-dom' import { useOverflowVisibleCount } from 'common/hooks/useOverflowVisibleCount' type OverflowNavProps = { + // Names the overflow button; each nav on a page needs its own + label: string children: ReactNode containerClassName?: string className?: string gap?: number - icon?: string + // The trigger's icon; defaults to the "more" dots + icon?: ReactNode force?: boolean } -const buttonWidth = 34 +// Room for the overflow button, with some spare: nav icons load late and +// grow their items after they are measured +const OVERFLOW_BUTTON_WIDTH = 54 + const OverflowNav: FC = ({ children: _children, className = '', containerClassName, force, gap = 2, - icon = ellipsisHorizontal, + icon = , + label, }) => { const items = React.Children.toArray( (_children as React.ReactElement)?.props?.children || _children, @@ -30,23 +35,14 @@ const OverflowNav: FC = ({ const outerContainerRef = useRef(null) const itemsContainerRef = useRef(null) - const [open, setOpen] = useState(false) - const history = useHistory() const { isMeasuring, visibleCount } = useOverflowVisibleCount({ - extraWidth: buttonWidth + 20, + extraWidth: OVERFLOW_BUTTON_WIDTH, force, itemCount: items.length, itemsContainerRef, outerContainerRef, }) - useEffect(() => { - const unlisten = history.listen(() => { - setOpen(false) - }) - return () => unlisten() - }, [history]) - const visible = items.slice(0, visibleCount) const overflow = items.slice(visibleCount) @@ -83,31 +79,22 @@ const OverflowNav: FC = ({ {overflow.length > 0 && !isMeasuring && ( -
- - setOpen(false)} - > -
- {overflow.map((child, idx) => ( - {child} - ))} -
-
-
+ + {icon} + + } + > + {/* Nav links render as menu rows inside the menu */} + {overflow} + )} ) diff --git a/frontend/web/components/navigation/SidebarLink.tsx b/frontend/web/components/navigation/SidebarLink.tsx index 3a01d2e30ab0..7f82af842b4d 100644 --- a/frontend/web/components/navigation/SidebarLink.tsx +++ b/frontend/web/components/navigation/SidebarLink.tsx @@ -2,6 +2,10 @@ import React, { FC, ReactNode } from 'react' import { NavLink, NavLinkProps } from 'react-router-dom' import classNames from 'classnames' import Icon, { IconName } from 'components/icons/Icon' +import { + DropdownMenuLink, + useIsInDropdownMenu, +} from 'components/base/DropdownMenu' type SidebarLinkType = Partial & { icon?: IconName @@ -18,6 +22,15 @@ const SidebarLink: FC = ({ to, ...rest }) => { + const inMenu = useIsInDropdownMenu() + if (inMenu && to) { + return ( + + {!!icon && } + {children} + + ) + } const Tag = (to ? NavLink : 'div') as any return ( diff --git a/frontend/web/components/navigation/TabMenu/TabButton.tsx b/frontend/web/components/navigation/TabMenu/TabButton.tsx index cc66c53092c7..b8bd5135f3dd 100644 --- a/frontend/web/components/navigation/TabMenu/TabButton.tsx +++ b/frontend/web/components/navigation/TabMenu/TabButton.tsx @@ -2,8 +2,8 @@ import React from 'react' import { themeClassNames } from 'components/base/forms/Button' import Button from 'components/base/forms/Button' -import ColorSwatch from 'components/ColorSwatch' -import { colorIconWarning } from 'common/theme/tokens' +import { TabItemProps } from './TabItem' +import TabLabel from './TabLabel' interface TabButtonProps { noFocus?: boolean @@ -11,7 +11,7 @@ interface TabButtonProps { onClick?: (e: React.MouseEvent) => void buttonTheme?: string className?: string - child: React.ReactElement + child: React.ReactElement children: React.ReactNode } @@ -30,12 +30,10 @@ const TabButton = React.forwardRef( } ${className}`} > - {child.props.tabLabel} - {child.props.isDirty && ( - - - - )} + ) diff --git a/frontend/web/components/navigation/TabMenu/TabItem.tsx b/frontend/web/components/navigation/TabMenu/TabItem.tsx index 622184d05abc..1c014a256db5 100644 --- a/frontend/web/components/navigation/TabMenu/TabItem.tsx +++ b/frontend/web/components/navigation/TabMenu/TabItem.tsx @@ -1,6 +1,6 @@ import { FC, ReactNode } from 'react' -type TabItemType = { +export type TabItemProps = { tabLabelString?: string tabLabel: ReactNode children: ReactNode @@ -9,9 +9,11 @@ type TabItemType = { // so positioning lives in one place and TabButton can wrap label + badge in // a flex container that prevents the badge from breaking onto a new line. isDirty?: boolean + 'data-test'?: string + id?: string } -const TabItem: FC = ({ children }) => { +const TabItem: FC = ({ children }) => { return children || (null as any) } diff --git a/frontend/web/components/navigation/TabMenu/TabLabel.tsx b/frontend/web/components/navigation/TabMenu/TabLabel.tsx new file mode 100644 index 000000000000..630bf014f9b8 --- /dev/null +++ b/frontend/web/components/navigation/TabMenu/TabLabel.tsx @@ -0,0 +1,19 @@ +import { FC } from 'react' +import ColorSwatch from 'components/ColorSwatch' +import { colorIconWarning } from 'common/theme/tokens' +import { TabItemProps } from './TabItem' + +type TabLabelProps = Pick + +const TabLabel: FC = ({ isDirty, tabLabel }) => ( + <> + {tabLabel} + {isDirty && ( + + + + )} + +) + +export default TabLabel diff --git a/frontend/web/components/navigation/TabMenu/Tabs.tsx b/frontend/web/components/navigation/TabMenu/Tabs.tsx index 455ec789273e..d3f509829ade 100644 --- a/frontend/web/components/navigation/TabMenu/Tabs.tsx +++ b/frontend/web/components/navigation/TabMenu/Tabs.tsx @@ -1,13 +1,28 @@ -import React, { ReactNode, useCallback, useMemo, useRef, useState } from 'react' +import React, { + isValidElement, + ReactElement, + ReactNode, + useCallback, + useMemo, + useRef, + useState, +} from 'react' import ModalHR from 'components/modals/ModalHR' import Utils from 'common/utils/utils' import { useHistory } from 'react-router-dom' import TabButton from './TabButton' +import { TabItemProps } from './TabItem' +import TabLabel from './TabLabel' import classNames from 'classnames' -import DropdownMenu from 'components/base/DropdownMenu' +import DropdownMenu, { DropdownMenuItem } from 'components/base/DropdownMenu' +import IconButton from 'components/base/IconButton' +import Icon from 'components/icons/Icon' import { useOverflowVisibleCount } from 'common/hooks/useOverflowVisibleCount' +// Room for the "More tabs" button, with some spare +const OVERFLOW_BUTTON_WIDTH = 48 + interface TabsProps { children: ReactNode | ReactNode[] onChange?: (index: number) => void @@ -25,9 +40,6 @@ interface TabsProps { cta?: ReactNode } -// 40px rendered button (btn padding beats its 32px width) + ms-2 margin -const OVERFLOW_BUTTON_WIDTH = 48 - const Tabs: React.FC = ({ buttonTheme, children, @@ -44,7 +56,7 @@ const Tabs: React.FC = ({ value: propValue = 0, }) => { const tabChildren = (Array.isArray(children) ? children : [children]).filter( - Boolean, + (child): child is ReactElement => isValidElement(child), ) const [internalValue, setInternalValue] = useState(0) const routerHistory = useHistory() || history @@ -68,6 +80,7 @@ const Tabs: React.FC = ({ const outerContainerRef = useRef(null) const itemsContainerRef = useRef(null) + const { isMeasuring, visibleCount } = useOverflowVisibleCount({ extraWidth: OVERFLOW_BUTTON_WIDTH, force: false, @@ -86,6 +99,9 @@ const Tabs: React.FC = ({ [tabChildren, visibleCount, disableOverflow], ) const canGrow = !isMeasuring && visibleCount === tabChildren.length + const hasOverflow = overflow.length > 0 && !isMeasuring + const tabLabelOf = (child: ReactElement) => + String(child.props.tabLabelString || child.props.tabLabel) const handleChange = useCallback( (e: React.MouseEvent, tabLabel: string, i: number) => { @@ -119,7 +135,7 @@ const Tabs: React.FC = ({ >
@@ -132,11 +148,7 @@ const Tabs: React.FC = ({ className={canGrow ? 'tab-nav-full' : ''} noFocus={noFocus} onClick={(e: React.MouseEvent) => - handleChange( - e, - String(child.props.tabLabelString || child.props.tabLabel), - i, - ) + handleChange(e, tabLabelOf(child), i) } child={child} buttonTheme={buttonTheme} @@ -146,57 +158,36 @@ const Tabs: React.FC = ({ ) })}
- {overflow.length > 0 && !isMeasuring && ( -
+ + + } > - { - const actualIndex = i + visibleCount - const active = value === actualIndex - return { - className: classNames('', [ - active - ? 'text-action fw-semibold bg-primary-opacity-5 fill-primary' - : 'hover-color-primary', - ]), - label: ( -
- - {child.props.tabLabel} - -
- ) as React.ReactNode, - onClick: (e: any) => { - handleChange( - e, - String( - child.props.tabLabelString || child.props.tabLabel, - ), - actualIndex, - ) - }, - } - })} - /> -
+ {overflow.map((child) => { + const i = tabChildren.indexOf(child) + return ( + handleChange(e, tabLabelOf(child), i)} + > + + + ) + })} +
)} {cta &&
{cta}
} diff --git a/frontend/web/components/navigation/navbars/OrganisationNavbar.tsx b/frontend/web/components/navigation/navbars/OrganisationNavbar.tsx index 15a076e8f6c1..7ac2166b5861 100644 --- a/frontend/web/components/navigation/navbars/OrganisationNavbar.tsx +++ b/frontend/web/components/navigation/navbars/OrganisationNavbar.tsx @@ -1,6 +1,6 @@ import React, { FC } from 'react' import NavSubLink from 'components/navigation/NavSubLink' -import { apps, statsChart } from 'ionicons/icons' +import { apps } from 'ionicons/icons' import Utils from 'common/utils/utils' import UsersIcon from 'components/icons/UsersIcon' import AccountStore from 'common/stores/account-store' @@ -14,6 +14,7 @@ type OrganisationNavType = {} const OrganisationNavbar: FC = ({}) => { return ( = ({}) => { {!Project.disableAnalytics && AccountStore.isAdmin() && ( } id='permissions-link' to={`/organisation/${AccountStore.getOrganisation().id}/usage`} > diff --git a/frontend/web/components/navigation/navbars/ProjectNavbar.tsx b/frontend/web/components/navigation/navbars/ProjectNavbar.tsx index c3f66390b067..ce7d630e68ce 100644 --- a/frontend/web/components/navigation/navbars/ProjectNavbar.tsx +++ b/frontend/web/components/navigation/navbars/ProjectNavbar.tsx @@ -1,6 +1,6 @@ import React, { FC } from 'react' import NavSubLink from 'components/navigation/NavSubLink' -import { barChart, gitBranch, gitCompare } from 'ionicons/icons' +import { gitBranch } from 'ionicons/icons' import SegmentsIcon from 'components/icons/SegmentsIcon' import Permission, { useHasPermission } from 'common/providers/Permission' import AuditLogIcon from 'components/icons/AuditLogIcon' @@ -27,6 +27,7 @@ const ProjectNavbar: FC = ({ environmentId, projectId }) => { ) return ( = ({ environmentId, projectId }) => { )} {projectMetricsTooltipEnabled && ( } to={`/project/${projectId}/reporting`} id='reporting-link' disabled @@ -106,7 +107,7 @@ const ProjectNavbar: FC = ({ environmentId, projectId }) => { )} } id='compare-link' to={`/project/${projectId}/compare`} > diff --git a/frontend/web/components/pages/feature-lifecycle/components/StaleSection.tsx b/frontend/web/components/pages/feature-lifecycle/components/StaleSection.tsx index 2f345d07efe6..6731fcdd7b29 100644 --- a/frontend/web/components/pages/feature-lifecycle/components/StaleSection.tsx +++ b/frontend/web/components/pages/feature-lifecycle/components/StaleSection.tsx @@ -1,5 +1,6 @@ import React, { FC, useCallback } from 'react' -import DropdownMenu from 'components/base/DropdownMenu' +import DropdownMenu, { DropdownMenuItem } from 'components/base/DropdownMenu' +import Icon from 'components/icons/Icon' import SectionShell from './SectionShell' import { useClientPagination } from 'components/pages/feature-lifecycle/hooks/useClientPagination' import { useCreateCleanupIssueMutation } from 'common/services/useGithubIntegration' @@ -132,20 +133,16 @@ const StaleSection: FC = ({ prevPage={prevPage} goToPage={goToPage} renderActions={(flag) => ( - handleCreateCleanupIssue(flag), - }, - { - icon: 'copy', - label: 'Copy Cleanup AI Prompt', - onClick: () => handleCopyCleanupPrompt(flag), - }, - ]} - /> + + handleCreateCleanupIssue(flag)}> + + Create Cleanup Issue + + handleCopyCleanupPrompt(flag)}> + + Copy Cleanup AI Prompt + + )} /> ) diff --git a/frontend/web/components/release-pipelines/ReleasePipelinesList.tsx b/frontend/web/components/release-pipelines/ReleasePipelinesList.tsx index 9e49bfc9a6a9..363c4b240f57 100644 --- a/frontend/web/components/release-pipelines/ReleasePipelinesList.tsx +++ b/frontend/web/components/release-pipelines/ReleasePipelinesList.tsx @@ -2,8 +2,8 @@ import { useDeleteReleasePipelineMutation } from 'common/services/useReleasePipe import { PagedResponse, ReleasePipeline } from 'common/types/responses' import { useHistory } from 'react-router-dom' import Button from 'components/base/forms/Button' -import Icon, { IconName } from 'components/icons/Icon' -import DropdownMenu from 'components/base/DropdownMenu' +import Icon from 'components/icons/Icon' +import DropdownMenu, { DropdownMenuItem } from 'components/base/DropdownMenu' import PanelSearch from 'components/PanelSearch' import Tag from 'components/tags/Tag' import { useEffect } from 'react' @@ -146,13 +146,6 @@ const ReleasePipelinesList = ({ const canUnpublish = isPublished && !features?.length const canDelete = !features?.length - const getTooltip = (action: string) => { - if (isPublished) { - return `Cannot ${action} a published release pipeline` - } - return undefined - } - return ( {features?.length ?? 0}
Features
- { - history.push( - `/project/${projectId}/release-pipelines/${id}/edit`, - ) - }, - tooltip: getTooltip('edit'), - }, - { - disabled: isPublished && !canUnpublish, - icon: isPublished - ? 'minus-circle' - : ('checkmark-circle' as IconName), - label: isPublished ? 'Unpublish' : 'Publish', - onClick: () => - openChangeReleasePipelineStatusModal( - projectId, - id, - isPublished, - ), - tooltip: - isPublished && !canUnpublish - ? 'Cannot unpublish a release pipeline with in-flight features' - : undefined, - }, - { - icon: 'copy' as IconName, - label: 'Clone', - onClick: () => - openModal2( - 'Clone Release Pipeline', - , - ), - }, - { - disabled: !canDelete, - icon: 'trash-2', - label: 'Remove', - onClick: () => { - openModal2( - 'Remove Release Pipeline', - , - ) - }, - tooltip: canDelete - ? undefined - : 'Cannot remove a release pipeline with in-flight features', - }, - ]} - /> + + + history.push( + `/project/${projectId}/release-pipelines/${id}/edit`, + ) + } + > + + Edit + + + openChangeReleasePipelineStatusModal( + projectId, + id, + isPublished, + ) + } + > + + {isPublished ? 'Unpublish' : 'Publish'} + + + openModal2( + 'Clone Release Pipeline', + , + ) + } + > + + Clone + + + openModal2( + 'Remove Release Pipeline', + , + ) + } + > + + Remove + +
)