Skip to content

Open source, privacy-first web analytics. Lightweight, cookie-free Google Analytics alternative. Self-hosted or cloud.

Show all filter pills in one scrolling row (#6717)

Sanne de Vries50cdfe067663
diff --git a/assets/js/dashboard/components/icons.tsx b/assets/js/dashboard/components/icons.tsx
index ac1e5471cc..56451e9e8b 100644
--- a/assets/js/dashboard/components/icons.tsx
+++ b/assets/js/dashboard/components/icons.tsx
@@ -96,6 +96,57 @@ export const PencilIcon = ({ className }: { className?: string }) => (
</svg>
)
+export const TrashIcon = ({ className }: { className?: string }) => (
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 24 24"
+ fill="none"
+ className={className}
+ >
+ <path
+ stroke="currentColor"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth="1.5"
+ d="m4.75 6.5.905 12.89a2 2 0 0 0 1.995 1.86h8.7a2 2 0 0 0 1.995-1.86L19.25 6.5M3.25 5.75h17.5M8.523 5.583a3.5 3.5 0 0 1 6.951 0"
+ />
+ </svg>
+)
+
+export const QuestionMarkCircleIcon = ({
+ className
+}: {
+ className?: string
+}) => (
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 24 24"
+ fill="none"
+ className={className}
+ >
+ <path
+ stroke="currentColor"
+ strokeLinecap="round"
+ strokeMiterlimit="10"
+ strokeWidth="1.5"
+ d="M12 22c5.523 0 10-4.477 10-10S17.523 2 12 2 2 6.477 2 12s4.477 10 10 10Z"
+ />
+ <path
+ stroke="currentColor"
+ strokeLinecap="round"
+ strokeMiterlimit="10"
+ strokeWidth="1.5"
+ d="M9 10a3 3 0 1 1 6 0c0 1.31-.839 2.11-2.008 2.389-.538.128-.992.559-.992 1.111"
+ />
+ <path
+ stroke="currentColor"
+ strokeLinecap="round"
+ strokeWidth="2.5"
+ d="M12 17.01V17"
+ />
+ </svg>
+)
+
export const CursorIcon = ({ className }: { className?: string }) => (
<svg
xmlns="http://www.w3.org/2000/svg"
diff --git a/assets/js/dashboard/components/popover.tsx b/assets/js/dashboard/components/popover.tsx
index e6217df88c..ddcb663aff 100644
--- a/assets/js/dashboard/components/popover.tsx
+++ b/assets/js/dashboard/components/popover.tsx
@@ -27,19 +27,19 @@ const transition = {
const panel = {
classNames: {
roundedSheet:
- 'flex flex-col gap-0.5 p-1 focus:outline-hidden rounded-md shadow-lg bg-white dark:bg-gray-800 ring-1 ring-black/5 font-medium text-gray-800 dark:text-gray-200'
+ 'flex flex-col gap-0.5 p-1 focus:outline-hidden rounded-md shadow-lg bg-white dark:bg-gray-800 ring-1 ring-black/5 text-gray-800 dark:text-gray-200'
}
}
const toggleButton = {
classNames: {
- rounded: 'flex items-center rounded-md text-sm leading-tight h-8',
+ rounded: 'flex items-center rounded-md text-sm h-8',
shadow:
'bg-white dark:bg-gray-750 shadow-sm text-gray-800 dark:text-gray-200 dark:hover:bg-gray-700',
outline:
- 'border border-gray-300 dark:border-gray-750 bg-white dark:bg-gray-750 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 dark:hover:border-gray-700 dark:hover:text-gray-100',
+ 'border border-gray-300 dark:border-gray-750 bg-white dark:bg-gray-750 text-gray-800 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 dark:hover:border-gray-700 dark:hover:text-gray-100',
ghost:
- 'gap-x-1.5 px-2.5 font-medium text-gray-700 dark:text-gray-100 hover:bg-gray-150/80 dark:hover:bg-gray-800 aria-expanded:bg-gray-150/80 dark:aria-expanded:bg-gray-800',
+ 'gap-x-1.5 px-2.5 font-medium text-gray-800 dark:text-gray-100 hover:bg-gray-150/80 dark:hover:bg-gray-800 aria-expanded:bg-gray-150/80 dark:aria-expanded:bg-gray-800',
truncatedText: 'truncate block',
linkLike:
'text-gray-700 dark:text-gray-300 hover:text-gray-900 dark:hover:text-gray-100 transition-colors duration-150'
@@ -48,7 +48,7 @@ const toggleButton = {
const navigationLink = classNames(
'flex items-center justify-between',
- 'px-4 py-2.5 text-sm leading-tight rounded-md',
+ 'px-4 py-2.5 text-sm rounded-md',
'cursor-pointer'
)
diff --git a/assets/js/dashboard/hooks/use-scroll-fade-mask.ts b/assets/js/dashboard/hooks/use-scroll-fade-mask.ts
new file mode 100644
index 0000000000..4be06ff761
--- /dev/null
+++ b/assets/js/dashboard/hooks/use-scroll-fade-mask.ts
@@ -0,0 +1,60 @@
+import { useCallback, useLayoutEffect, useRef, useState } from 'react'
+
+const SCROLL_FADE_PX = 32
+
+type ScrollOverflow = { start: boolean; end: boolean }
+
+const getScrollOverflow = (element: HTMLElement): ScrollOverflow => ({
+ start: element.scrollLeft > 1,
+ end: element.scrollLeft + element.clientWidth < element.scrollWidth - 1
+})
+
+const getFadeMask = ({ start, end }: ScrollOverflow) => {
+ if (!start && !end) {
+ return undefined
+ }
+ const from = start ? `transparent, black ${SCROLL_FADE_PX}px` : 'black'
+ const to = end
+ ? `black calc(100% - ${SCROLL_FADE_PX}px), transparent`
+ : 'black'
+ return `linear-gradient(to right, ${from}, ${to})`
+}
+
+export function useScrollFadeMask<T extends HTMLElement>() {
+ const ref = useRef<T>(null)
+ const [overflow, setOverflow] = useState<ScrollOverflow>({
+ start: false,
+ end: false
+ })
+
+ const update = useCallback(() => {
+ const element = ref.current
+ if (!element) {
+ return
+ }
+ const next = getScrollOverflow(element)
+ setOverflow((current) =>
+ current.start === next.start && current.end === next.end ? current : next
+ )
+ }, [])
+
+ useLayoutEffect(() => {
+ const element = ref.current
+ if (!element) {
+ return
+ }
+ // children can grow without resizing the scroll container itself
+ const resizeObserver = new ResizeObserver(update)
+ resizeObserver.observe(element)
+ Array.from(element.children).forEach((child) =>
+ resizeObserver.observe(child)
+ )
+ element.addEventListener('scroll', update, { passive: true })
+ return () => {
+ resizeObserver.disconnect()
+ element.removeEventListener('scroll', update)
+ }
+ }, [update])
+
+ return { ref, maskImage: getFadeMask(overflow), update }
+}
diff --git a/assets/js/dashboard/nav-menu/filter-menu.tsx b/assets/js/dashboard/nav-menu/filter-menu.tsx
index 2ed6381d85..d72a486db1 100644
--- a/assets/js/dashboard/nav-menu/filter-menu.tsx
+++ b/assets/js/dashboard/nav-menu/filter-menu.tsx
@@ -4,6 +4,8 @@ import { useSiteContext } from '../site-context'
import { filterRoute } from '../router'
import { FilterIcon } from '../components/icons'
import { Popover, Transition } from '@headlessui/react'
+import { PlusIcon } from '@heroicons/react/24/outline'
+import { Tooltip } from '../util/tooltip'
import { popover, BlurMenuButtonOnEscape } from '../components/popover'
import classNames from 'classnames'
import { AppNavigationLink } from '../navigation/use-app-navigate'
@@ -27,31 +29,61 @@ import {
useSubmenu
} from './submenu'
-const FilterMenuItems = ({ closeDropdown }: { closeDropdown: () => void }) => {
+const FilterMenuItems = ({
+ open,
+ closeDropdown,
+ compact
+}: {
+ open: boolean
+ closeDropdown: () => void
+ compact: boolean
+}) => {
const buttonRef = useRef<HTMLButtonElement>(null)
return (
<>
<BlurMenuButtonOnEscape targetRef={buttonRef} />
- <Popover.Button
- ref={buttonRef}
- className={classNames(
- popover.toggleButton.classNames.rounded,
- popover.toggleButton.classNames.ghost,
- 'relative z-20'
- )}
- >
- <FilterIcon className="block size-3.5" />
- <span className={popover.toggleButton.classNames.truncatedText}>
- Filter
- </span>
- </Popover.Button>
+ {compact ? (
+ <Tooltip
+ info={open ? null : 'Add filter'}
+ containerRef={{ current: document.body }}
+ >
+ <Popover.Button
+ ref={buttonRef}
+ aria-label="Add filter"
+ className={classNames(
+ popover.toggleButton.classNames.rounded,
+ popover.toggleButton.classNames.ghost,
+ 'justify-center relative z-20'
+ )}
+ >
+ <PlusIcon className="block size-4" />
+ </Popover.Button>
+ </Tooltip>
+ ) : (
+ <Popover.Button
+ ref={buttonRef}
+ className={classNames(
+ popover.toggleButton.classNames.rounded,
+ popover.toggleButton.classNames.ghost,
+ 'relative z-20'
+ )}
+ >
+ <FilterIcon className="block size-3.5" />
+ <span className={popover.toggleButton.classNames.truncatedText}>
+ Filter
+ </span>
+ </Popover.Button>
+ )}
<Transition
as="div"
{...popover.transition.props}
className={classNames(
popover.transition.classNames.fullwidth,
- 'mt-2 md:left-auto md:w-56 md:origin-top-right'
+ 'mt-2 md:w-56',
+ compact
+ ? 'md:right-auto md:origin-top-left'
+ : 'md:left-auto md:origin-top-right'
)}
>
<div className="fixed top-0 left-0 w-full h-full"></div>
@@ -198,8 +230,10 @@ const SubmenuBody = ({
)
}
-export const FilterMenu = () => (
+export const FilterMenu = ({ compact = false }: { compact?: boolean }) => (
<Popover className="shrink-0 md:relative">
- {({ close }) => <FilterMenuItems closeDropdown={close} />}
+ {({ open, close }) => (
+ <FilterMenuItems open={open} closeDropdown={close} compact={compact} />
+ )}
</Popover>
)
diff --git a/assets/js/dashboard/nav-menu/filter-pill.tsx b/assets/js/dashboard/nav-menu/filter-pill.tsx
index 003fdc505e..ef812b15a6 100644
--- a/assets/js/dashboard/nav-menu/filter-pill.tsx
+++ b/assets/js/dashboard/nav-menu/filter-pill.tsx
@@ -3,20 +3,19 @@ import {
AppNavigationLink,
AppNavigationTarget
} from '../navigation/use-app-navigate'
-import { XMarkIcon } from '@heroicons/react/20/solid'
+import { XMarkIcon } from '@heroicons/react/24/outline'
import classNames from 'classnames'
+export type FilterPillAction = {
+ type: 'link'
+ navigationTarget: AppNavigationTarget
+}
+
export type FilterPillProps = {
- className?: string
plainText: string
- interactive:
- | {
- onRemoveClick?: () => void
- navigationTarget: AppNavigationTarget
- }
- | false
+ action?: FilterPillAction
+ onRemoveClick?: () => void
children: ReactNode
- actions?: ReactNode
}
const PillContent = ({ children }: { children?: ReactNode }) => (
@@ -25,49 +24,43 @@ const PillContent = ({ children }: { children?: ReactNode }) => (
</span>
)
+const contentBaseClassName =
+ 'flex w-full h-full items-center rounded-l-md pl-2.5'
+
export function FilterPill({
- className,
plainText,
children,
- interactive,
- actions
+ onRemoveClick,
+ action
}: FilterPillProps) {
- const contentClassName = 'flex w-full h-full items-center pl-2.5 last:pr-2.5'
+ const contentClassName = classNames(
+ contentBaseClassName,
+ !onRemoveClick && 'rounded-r-md pr-2.5'
+ )
return (
- <div
- className={classNames(
- 'flex h-8 shadow-sm rounded-md bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 text-sm items-center',
- className
- )}
- >
- {interactive ? (
- <>
- <AppNavigationLink
- className={contentClassName}
- title={`Edit filter: ${plainText}`}
- {...interactive.navigationTarget}
- >
- <PillContent>{children}</PillContent>
- </AppNavigationLink>
- {!!interactive.onRemoveClick && (
- <button
- title={`Remove filter: ${plainText}`}
- className="flex items-center h-full pl-1.5 pr-2.5 cursor-pointer hover:text-indigo-700 dark:hover:text-indigo-500 "
- onClick={interactive.onRemoveClick}
- >
- <XMarkIcon className="w-4 h-4" />
- </button>
- )}
- {actions}
- </>
+ <div className="flex h-8 rounded-md bg-white border border-gray-200 dark:border-gray-700 dark:bg-gray-800 text-gray-800 dark:text-gray-100 text-sm items-center">
+ {action ? (
+ <AppNavigationLink
+ className={contentClassName}
+ title={`Edit filter: ${plainText}`}
+ {...action.navigationTarget}
+ >
+ <PillContent>{children}</PillContent>
+ </AppNavigationLink>
) : (
- <>
- <div className={contentClassName} title={plainText}>
- <PillContent>{children}</PillContent>
- </div>
- {actions}
- </>
+ <div className={contentClassName} title={plainText}>
+ <PillContent>{children}</PillContent>
+ </div>
+ )}
+ {!!onRemoveClick && (
+ <button
+ title={`Remove filter: ${plainText}`}
+ className="flex items-center h-full rounded-r-md pl-1.5 pr-2.5 cursor-pointer hover:text-indigo-700 dark:hover:text-indigo-500 "
+ onClick={onRemoveClick}
+ >
+ <XMarkIcon className="size-4" />
+ </button>
)}
</div>
)
diff --git a/assets/js/dashboard/nav-menu/filter-pills-list.tsx b/assets/js/dashboard/nav-menu/filter-pills-list.tsx
index df11e8cb19..6e3c4d61f4 100644
--- a/assets/js/dashboard/nav-menu/filter-pills-list.tsx
+++ b/assets/js/dashboard/nav-menu/filter-pills-list.tsx
@@ -1,6 +1,6 @@
-import React, { DetailedHTMLProps, HTMLAttributes } from 'react'
+import React, { CSSProperties } from 'react'
import { useDashboardStateContext } from '../dashboard-state-context'
-import { FilterPill, FilterPillProps } from './filter-pill'
+import { FilterPill, FilterPillAction, FilterPillProps } from './filter-pill'
import { cleanLabels, EVENT_PROPS_PREFIX } from '../util/filters'
import { styledFilterText, plainFilterText } from '../util/filter-text'
import { useAppNavigate } from '../navigation/use-app-navigate'
@@ -8,133 +8,77 @@ import classNames from 'classnames'
import { filterRoute } from '../router'
import { canRemoveFilter } from '../filtering/segments'
import { useSegmentsContext } from '../filtering/segments-context'
-
-export const PILL_X_GAP_PX = 10
-export const PILL_Y_GAP_PX = 8
-
-type SliceStartEnd = {
- /** The beginning index of the specified portion of the array. If start is undefined, then the slice begins at index 0. */
- start?: number
- /** The end index of the specified portion of the array. This is exclusive of the element at the index 'end'. If end is undefined, then the slice extends to the end of the array. */
- end?: number
-}
-
-type InvisibleOutsideSlice = {
- type: 'invisible-outside'
-} & SliceStartEnd
-
-type NoRenderOutsideSlice = {
- type: 'no-render-outside'
-} & SliceStartEnd
-
-type AppliedFilterPillsListProps = Omit<
- FilterPillsListProps,
- 'slice' | 'pillProps' | 'pills'
-> & {
- slice?: InvisibleOutsideSlice | NoRenderOutsideSlice
- pillClassName?: string
-}
-
-type FilterPillsListProps = {
- direction: 'horizontal' | 'vertical'
-} & DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement> & {
- pills: FilterPillProps[]
- }
+import { Filter } from '../dashboard-state'
export const AppliedFilterPillsList = React.forwardRef<
HTMLDivElement,
- AppliedFilterPillsListProps
->(({ className, style, slice, direction, pillClassName }, ref) => {
+ { className?: string; style?: CSSProperties }
+>(({ className, style }, ref) => {
const { dashboardState } = useDashboardStateContext()
const { limitedToSegment } = useSegmentsContext()
const navigate = useAppNavigate()
- const renderableFilters =
- slice?.type === 'no-render-outside'
- ? dashboardState.filters.slice(slice.start, slice.end)
- : dashboardState.filters
-
- const indexAdjustment =
- slice?.type === 'no-render-outside' ? (slice.start ?? 0) : 0
-
- const isInvisible = (index: number) => {
- return slice?.type === 'invisible-outside'
- ? index < (slice.start ?? 0) ||
- index > (slice.end ?? dashboardState.filters.length) - 1
- : false
- }
-
- return (
- <FilterPillsList
- pills={renderableFilters.map((filter, index) => ({
- className: classNames(isInvisible(index) && 'invisible', pillClassName),
- plainText: plainFilterText(dashboardState, filter),
- children: styledFilterText(dashboardState, filter),
- interactive: {
- navigationTarget: {
- path: filterRoute.path,
- search: (s) => s,
- params: {
- field: filter[1].startsWith(EVENT_PROPS_PREFIX)
- ? 'props'
- : filter[1]
- }
- },
- onRemoveClick: canRemoveFilter(filter, limitedToSegment)
- ? () => {
- const newFilters = dashboardState.filters.filter(
- (_, i) => i !== index + indexAdjustment
- )
-
- navigate({
- search: (searchRecord) => ({
- ...searchRecord,
- filters: newFilters,
- labels: cleanLabels(newFilters, dashboardState.labels)
- })
- })
- }
- : undefined
- }
- }))}
- className={className}
- style={style}
- ref={ref}
- direction={direction}
- />
- )
-})
+ const getPillAction = (filter: Filter): FilterPillAction => ({
+ type: 'link',
+ navigationTarget: {
+ path: filterRoute.path,
+ search: (s) => s,
+ params: {
+ field: filter[1].startsWith(EVENT_PROPS_PREFIX) ? 'props' : filter[1]
+ }
+ }
+ })
-export const FilterPillsList = React.forwardRef<
- HTMLDivElement,
- FilterPillsListProps
->(({ className, style, direction, pills }, ref) => {
- // this padding allows pill dropshadows to be visible
- // even when overflow:hidden is given to pill parent container
- // box-content guarantees width given as style to apply to available space
- const innerClassName = 'p-1 box-content'
- // this hides the padding of the inner component to ease placement
- const wrapperClassName = '-m-1'
return (
- <div className={wrapperClassName}>
+ // the negative margin hides the inner padding, which keeps
+ // pill focus rings visible when the pills scroll
+ <div className="-m-1 min-w-0">
<div
ref={ref}
- className={classNames(
- 'flex',
- {
- 'flex-row': direction === 'horizontal',
- 'flex-col items-start': direction === 'vertical'
- },
- innerClassName,
- className
- )}
- // gaps given as style to be able to use their numeric values in calculations
- style={{ columnGap: PILL_X_GAP_PX, rowGap: PILL_Y_GAP_PX, ...style }}
+ className={classNames('flex gap-x-1 p-1', className)}
+ style={style}
>
- {pills.map((options, index) => (
- <FilterPill key={index} {...options} />
+ {dashboardState.filters.map((filter, index) => (
+ <FilterPill
+ key={index}
+ plainText={plainFilterText(dashboardState, filter)}
+ action={getPillAction(filter)}
+ onRemoveClick={
+ canRemoveFilter(filter, limitedToSegment)
+ ? () => {
+ const newFilters = dashboardState.filters.filter(
+ (_, i) => i !== index
+ )
+
+ navigate({
+ search: (searchRecord) => ({
+ ...searchRecord,
+ filters: newFilters,
+ labels: cleanLabels(newFilters, dashboardState.labels)
+ })
+ })
+ }
+ : undefined
+ }
+ >
+ {styledFilterText(dashboardState, filter)}
+ </FilterPill>
))}
</div>
</div>
)
})
+
+export const FilterPillsList = ({
+ className,
+ pills
+}: {
+ className?: string
+ pills: FilterPillProps[]
+}) => (
+ <div className={classNames('flex gap-2', className)}>
+ {pills.map((pill, index) => (
+ <FilterPill key={index} {...pill} />
+ ))}
+ </div>
+)
diff --git a/assets/js/dashboard/nav-menu/filters-bar.test.tsx b/assets/js/dashboard/nav-menu/filters-bar.test.tsx
index ea228a61bf..abf774b4ba 100644
--- a/assets/js/dashboard/nav-menu/filters-bar.test.tsx
+++ b/assets/js/dashboard/nav-menu/filters-bar.test.tsx
@@ -1,78 +1,57 @@
-import React from 'react'
+import React, { ComponentProps } from 'react'
import { render, screen } from '../../../test-utils'
import userEvent from '@testing-library/user-event'
import { TestContextProviders } from '../../../test-utils/app-context-providers'
-import { FiltersBar, handleVisibility } from './filters-bar'
+import { FiltersBar } from './filters-bar'
import { getRouterBasepath } from '../router'
import { stringifySearch } from '../util/url-search-params'
import { mockAnimationsApi, mockResizeObserver } from 'jsdom-testing-mocks'
mockAnimationsApi()
-const resizeObserver = mockResizeObserver()
+mockResizeObserver()
const domain = 'dummy.site'
-test('user can see expected filters and clear them one by one or all together on small screens', async () => {
- const searchRecord = {
- filters: [
- ['is', 'country', ['DE']],
- ['is', 'goal', ['Subscribed to Newsletter']],
- ['is', 'page', ['/docs', '/blog']]
- ],
- labels: { DE: 'Germany' }
- }
- const startUrl = `${getRouterBasepath({ domain, shared: false })}${stringifySearch(searchRecord)}`
+const renderFiltersBar = ({
+ searchRecord,
+ siteOptions,
+ ...providerProps
+}: {
+ searchRecord: Record<string, unknown>
+} & Omit<ComponentProps<typeof TestContextProviders>, 'children'>) =>
+ render(<FiltersBar />, {
+ wrapper: (props) => (
+ <TestContextProviders
+ routerProps={{
+ initialEntries: [
+ {
+ pathname: getRouterBasepath({ domain, shared: false }),
+ search: stringifySearch(searchRecord)
+ }
+ ]
+ }}
+ siteOptions={{ domain, ...siteOptions }}
+ {...providerProps}
+ {...props}
+ />
+ )
+ })
- render(
- <FiltersBar
- accessors={{
- topBar: jest.fn(
- () =>
- ({
- getBoundingClientRect: jest.fn().mockReturnValue(600)
- }) as unknown as HTMLElement
- ),
- leftSection: jest.fn(
- () =>
- ({
- getBoundingClientRect: jest.fn().mockReturnValue(200)
- }) as unknown as HTMLElement
- ),
- rightSection: jest.fn(
- () =>
- ({
- getBoundingClientRect: jest.fn().mockReturnValue(300)
- }) as unknown as HTMLElement
- )
- }}
- />,
- {
- wrapper: (props) => (
- <TestContextProviders
- routerProps={{ initialEntries: [startUrl] }}
- siteOptions={{ domain }}
- {...props}
- />
- )
+test('user can see expected filters and clear them one by one or all together', async () => {
+ renderFiltersBar({
+ searchRecord: {
+ filters: [
+ ['is', 'country', ['DE']],
+ ['is', 'goal', ['Subscribed to Newsletter']],
+ ['is', 'page', ['/docs', '/blog']]
+ ],
+ labels: { DE: 'Germany' }
}
- )
-
- // needed to initiate the layout calculation effect of the component
- resizeObserver.resize()
+ })
const queryFilterPills = () =>
screen.queryAllByRole('link', { hidden: false, name: /.* is .*/i })
- // all filters appear in See more menu (see the mock widths in props)
- expect(queryFilterPills().map((m) => m.textContent)).toEqual([])
-
- await userEvent.click(
- screen.getByRole('button', {
- hidden: false,
- name: 'See 3 more filters and actions'
- })
- )
-
expect(queryFilterPills().map((m) => m.textContent)).toEqual([
'Country is Germany',
'Goal is Subscribed to Newsletter',
@@ -101,74 +80,32 @@ test('user can see expected filters and clear them one by one or all together on
expect(queryFilterPills().map((m) => m.textContent)).toEqual([])
})
-describe(`${handleVisibility.name}`, () => {
- it('is able to fit all exactly, whether "See more" is rendered in the actions or not', () => {
- const setVisibility = jest.fn()
- const input = {
- setVisibility,
- leftoverWidth: 1000,
- seeMoreWidth: 100,
- pillWidths: [200, 200, 200, 200],
- pillGap: 25,
- mustShowSeeMoreMenu: true
+test('action tooltips show the keybind and the docs link', async () => {
+ renderFiltersBar({
+ searchRecord: {
+ filters: [['is', 'country', ['DE']]],
+ labels: { DE: 'Germany' }
}
- handleVisibility(input)
- expect(setVisibility).toHaveBeenCalledTimes(1)
- expect(setVisibility).toHaveBeenLastCalledWith({
- width: 900,
- visibleCount: 4
- })
-
- handleVisibility({
- ...input
- })
- expect(setVisibility).toHaveBeenCalledTimes(2)
- expect(setVisibility).toHaveBeenLastCalledWith({
- width: 900,
- visibleCount: 4
- })
-
- handleVisibility({ ...input, leftoverWidth: 999 })
- expect(setVisibility).toHaveBeenCalledTimes(3)
- expect(setVisibility).toHaveBeenLastCalledWith({
- width: 675,
- visibleCount: 3
- })
})
- it('handles 1 filter correctly', () => {
- const setVisibility = jest.fn()
- const input = {
- setVisibility,
- leftoverWidth: 300,
- seeMoreWidth: 50,
- pillWidths: [250],
- pillGap: 25,
- mustShowSeeMoreMenu: false
- }
- handleVisibility(input)
- expect(setVisibility).toHaveBeenCalledTimes(1)
- expect(setVisibility).toHaveBeenLastCalledWith({
- width: 275,
- visibleCount: 1
- })
- })
+ const addFilter = screen.getByRole('button', { name: 'Add filter' })
+ await userEvent.hover(addFilter)
+ expect(screen.getByRole('tooltip')).toHaveTextContent('Add filter')
+ await userEvent.unhover(addFilter)
- it('handles 2 filters correctly, shrinking to 0 width', () => {
- const setVisibility = jest.fn()
- const input = {
- setVisibility,
- leftoverWidth: 300,
- seeMoreWidth: 50,
- pillWidths: [250, 200],
- pillGap: 25,
- mustShowSeeMoreMenu: true
- }
- handleVisibility(input)
- expect(setVisibility).toHaveBeenCalledTimes(1)
- expect(setVisibility).toHaveBeenLastCalledWith({
- width: 0,
- visibleCount: 0
- })
- })
+ const clearAll = screen.getByRole('link', { name: 'Clear all filters' })
+ await userEvent.hover(clearAll)
+ expect(screen.getByRole('tooltip')).toHaveTextContent('Clear all filtersESC')
+ await userEvent.unhover(clearAll)
+
+ await userEvent.hover(screen.getByRole('link', { name: 'Save as segment' }))
+ await userEvent.hover(
+ screen.getByRole('link', { name: 'Learn more about segments' })
+ )
+ expect(
+ screen.getByRole('link', { name: 'Learn more about segments' })
+ ).toHaveAttribute(
+ 'href',
+ 'https://plausible.io/docs/filters-segments#how-to-save-a-segment'
+ )
})
diff --git a/assets/js/dashboard/nav-menu/filters-bar.tsx b/assets/js/dashboard/nav-menu/filters-bar.tsx
index 7f090282f1..4e1bf4c278 100644
--- a/assets/js/dashboard/nav-menu/filters-bar.tsx
+++ b/assets/js/dashboard/nav-menu/filters-bar.tsx
@@ -1,11 +1,13 @@
-import { EllipsisHorizontalIcon } from '@heroicons/react/24/solid'
+import { StarIcon } from '@heroicons/react/24/outline'
import classNames from 'classnames'
-import React, { useRef, useState, useLayoutEffect } from 'react'
-import { AppliedFilterPillsList, PILL_X_GAP_PX } from './filter-pills-list'
+import React, { ReactNode, useEffect, useRef } from 'react'
+import { AppliedFilterPillsList } from './filter-pills-list'
+import { FilterMenu } from './filter-menu'
import { useDashboardStateContext } from '../dashboard-state-context'
import { AppNavigationLink } from '../navigation/use-app-navigate'
-import { Popover, Transition } from '@headlessui/react'
-import { popover, BlurMenuButtonOnEscape } from '../components/popover'
+import { popover } from '../components/popover'
+import { QuestionMarkCircleIcon, TrashIcon } from '../components/icons'
+import { Tooltip } from '../util/tooltip'
import {
canSeeSaveAsSegmentAction,
isSegmentFilter
@@ -13,104 +15,11 @@ import {
import { useRoutelessModalsContext } from '../navigation/routeless-modals-context'
import { DashboardState } from '../dashboard-state'
import { useUserContext } from '../user-context'
-
-// Component structure is
-// `..[ filter (x) ]..[ filter (x) ]..[ three dot menu ]..`
-// where `..` represents an ideally equal length.
-// The following calculations guarantee that.
-const SEE_MORE_WIDTH_PX = 32
-const SEE_MORE_RIGHT_MARGIN_PX = PILL_X_GAP_PX
-const SEE_MORE_LEFT_MARGIN_PX = 0
-
-export const handleVisibility = ({
- setVisibility,
- leftoverWidth,
- seeMoreWidth,
- pillWidths,
- pillGap,
- mustShowSeeMoreMenu
-}: {
- setVisibility: (v: VisibilityState) => void
- leftoverWidth: number | null
- pillWidths: (number | null)[] | null
- seeMoreWidth: number
- pillGap: number
- mustShowSeeMoreMenu: boolean
-}): void => {
- if (leftoverWidth === null || pillWidths === null) {
- return
- }
-
- const fitToWidth = (maxWidth: number) => {
- let visibleCount = 0
- let currentWidth = 0
- let lastValidWidth = 0
- for (const pillWidth of pillWidths) {
- currentWidth += (pillWidth ?? 0) + pillGap
- if (currentWidth <= maxWidth) {
- lastValidWidth = currentWidth
- visibleCount += 1
- } else {
- break
- }
- }
- return { visibleCount, lastValidWidth }
- }
-
- const fits = fitToWidth(leftoverWidth)
-
- const seeMoreWillBePresent =
- fits.visibleCount < pillWidths.length || mustShowSeeMoreMenu
-
- // Check if the appearance of "See more" would cause overflow
- if (seeMoreWillBePresent) {
- const maybeFitsLess = fitToWidth(leftoverWidth - seeMoreWidth)
- if (maybeFitsLess.visibleCount < fits.visibleCount) {
- return setVisibility({
- width: maybeFitsLess.lastValidWidth,
- visibleCount: maybeFitsLess.visibleCount
- })
- }
- }
-
- return setVisibility({
- width: fits.lastValidWidth,
- visibleCount: fits.visibleCount
- })
-}
-
-const getElementWidthOrNull = <
- T extends Pick<HTMLElement, 'getBoundingClientRect'>
->(
- element: T | null
-) => (element === null ? null : element.getBoundingClientRect().width)
-
-type VisibilityState = {
- width: number
- visibleCount: number
-}
-
-type ElementAccessor = (
- filtersBarElement: HTMLElement | null
-) => HTMLElement | null | undefined
-
-/**
- * The accessors are paths to other elements that FiltersBar needs to measure:
- * they depend on the structure of the parent and are thus passed as props.
- * Passing these with refs would be more reactive, but the main layout effect
- * didn't trigger then as expected.
- */
-interface FiltersBarProps {
- accessors: {
- topBar: ElementAccessor
- leftSection: ElementAccessor
- rightSection: ElementAccessor
- }
-}
+import { useScrollFadeMask } from '../hooks/use-scroll-fade-mask'
const canShowClearAllAction = ({
filters
-}: Pick<DashboardState, 'filters'>): boolean => filters.length >= 2
+}: Pick<DashboardState, 'filters'>): boolean => filters.length >= 1
const canShowSaveAsSegmentAction = ({
filters,
@@ -118,10 +27,7 @@ const canShowSaveAsSegmentAction = ({
}: Pick<DashboardState, 'filters'> & { isEditingSegment: boolean }): boolean =>
filters.length >= 1 && !filters.some(isSegmentFilter) && !isEditingSegment
-export const FiltersBar = ({ accessors }: FiltersBarProps) => {
- const containerRef = useRef<HTMLDivElement>(null)
- const pillsRef = useRef<HTMLDivElement>(null)
- const [visibility, setVisibility] = useState<null | VisibilityState>(null)
+export const FiltersBar = () => {
const { dashboardState, expandedSegment } = useDashboardStateContext()
const user = useUserContext()
@@ -134,235 +40,143 @@ export const FiltersBar = ({ accessors }: FiltersBarProps) => {
isEditingSegment: !!expandedSegment
}) && canSeeSaveAsSegmentAction({ user })
- const actionsInSeeMoreMenu = [
- showingSaveAsSegment && ('save as segment' as const),
- showingClearAll && ('clear all filters' as const)
- ].filter((f) => f)
-
- const mustShowSeeMoreMenu = actionsInSeeMoreMenu.length > 0
-
- useLayoutEffect(() => {
- const topBar = accessors.topBar(containerRef.current)
- const leftSection = accessors.leftSection(containerRef.current)
- const rightSection = accessors.rightSection(containerRef.current)
-
- const resizeObserver = new ResizeObserver(() => {
- const pillWidths = pillsRef.current
- ? Array.from(pillsRef.current.children).map((el) =>
- getElementWidthOrNull(el)
- )
- : null
- handleVisibility({
- setVisibility,
- pillWidths,
- pillGap: PILL_X_GAP_PX,
- leftoverWidth:
- topBar && leftSection && rightSection
- ? getElementWidthOrNull(topBar)! -
- getElementWidthOrNull(leftSection)! -
- getElementWidthOrNull(rightSection)!
- : null,
- seeMoreWidth:
- SEE_MORE_LEFT_MARGIN_PX +
- SEE_MORE_WIDTH_PX +
- SEE_MORE_RIGHT_MARGIN_PX,
- mustShowSeeMoreMenu
- })
- })
-
- if (containerRef.current && topBar) {
- resizeObserver.observe(topBar)
- }
-
- return () => {
- resizeObserver.disconnect()
- }
- }, [accessors, dashboardState.filters, mustShowSeeMoreMenu])
+ const hasActions = showingSaveAsSegment || showingClearAll
if (!dashboardState.filters.length) {
- // functions as spacer between elements.leftSection and elements.rightSection
- return <div className="w-4" />
+ return (
+ <div className="flex flex-1 justify-end">
+ <FilterMenu />
+ </div>
+ )
}
return (
- <div
- className={classNames(
- 'flex w-full items-center',
- visibility === null && 'invisible' // hide until we've calculated the positions
- )}
- ref={containerRef}
- >
- <div className="flex items-center">
- <AppliedFilterPillsList
- ref={pillsRef}
- direction="horizontal"
- slice={{
- type: 'invisible-outside',
- start: 0,
- end: visibility?.visibleCount
- }}
- className="overflow-hidden"
- style={{ width: visibility?.width ?? 0 }}
- />
- </div>
- {visibility !== null &&
- (dashboardState.filters.length !== visibility.visibleCount ||
- mustShowSeeMoreMenu) && (
- <SeeMoreMenu
- actions={actionsInSeeMoreMenu}
- className="md:relative"
- filtersCount={dashboardState.filters.length}
- visibleFiltersCount={visibility.visibleCount}
+ <div className="flex items-center gap-x-1 md:min-w-0">
+ <ScrollableFilterPills />
+ <div className="flex shrink-0 items-center gap-x-1">
+ <FilterMenu compact />
+ {hasActions && (
+ <div
+ aria-hidden="true"
+ className="mx-1 h-4 w-px bg-gray-300 dark:bg-gray-600"
/>
)}
+ {showingSaveAsSegment && <SaveAsSegmentAction />}
+ {showingClearAll && <ClearAction />}
+ </div>
</div>
)
}
-const SeeMoreMenu = ({
- className,
- filtersCount,
- visibleFiltersCount,
- actions
-}: {
- className?: string
- filtersCount: number
- visibleFiltersCount: number
- actions: Array<'save as segment' | 'clear all filters' | false>
-}) => {
- const seeMoreRef = useRef<HTMLButtonElement>(null)
- const filtersInMenuCount = filtersCount - visibleFiltersCount
-
- const title =
- filtersInMenuCount === 1
- ? 'See 1 more filter and actions'
- : filtersInMenuCount > 1
- ? `See ${filtersInMenuCount} more filters and actions`
- : 'See actions'
+const ScrollableFilterPills = () => {
+ const { dashboardState } = useDashboardStateContext()
+ const { ref, maskImage, update } = useScrollFadeMask<HTMLDivElement>()
+ const filtersCount = dashboardState.filters.length
+ const previousFiltersCount = useRef(filtersCount)
- const showMoreFilters = filtersCount !== visibleFiltersCount
- const showSomeActions = actions.some((a) => a)
+ useEffect(() => {
+ const element = ref.current
+ if (!element) {
+ return
+ }
+ // new filters are prepended, so bring the start into view when one is added
+ if (filtersCount > previousFiltersCount.current) {
+ element.scrollLeft = 0
+ }
+ previousFiltersCount.current = filtersCount
+ update()
+ }, [ref, update, dashboardState.filters, filtersCount])
return (
- <Popover className={className}>
- <BlurMenuButtonOnEscape targetRef={seeMoreRef} />
- <Popover.Button
- title={title}
- ref={seeMoreRef}
- className={classNames(
- popover.toggleButton.classNames.rounded,
- popover.toggleButton.classNames.shadow,
- 'justify-center',
- 'relative group'
- )}
- style={{
- height: SEE_MORE_WIDTH_PX,
- width: SEE_MORE_WIDTH_PX,
- marginLeft: SEE_MORE_LEFT_MARGIN_PX,
- marginRight: SEE_MORE_RIGHT_MARGIN_PX
- }}
- >
- <EllipsisHorizontalIcon className="block size-4" />
- {showMoreFilters && (
- <div
- aria-hidden="true"
- className="absolute flex justify-end left-0 -right-1 bottom-0 translate-y-1/4"
- >
- <div className="text-[10px] leading-[10px] min-w-[10px] font-medium shadow-sm px-[3px] py-[1px] flex items-center rounded-xs bg-gray-100 dark:bg-gray-850">
- +{filtersInMenuCount}
- </div>
- </div>
- )}
- </Popover.Button>
- <Transition
- as="div"
- {...popover.transition.props}
- className={classNames(
- popover.transition.classNames.fullwidth,
- 'mt-2 md:right-auto md:origin-top-left'
- )}
- >
- <Popover.Panel
- className={classNames(
- popover.panel.classNames.roundedSheet,
- 'flex flex-col'
- )}
- >
- {showMoreFilters && (
- <>
- <div className="py-4 px-4">
- <AppliedFilterPillsList
- direction="vertical"
- pillClassName="!shadow-none !bg-gray-100 dark:!bg-gray-700"
- slice={{
- type: 'no-render-outside',
- start: visibleFiltersCount
- }}
- />
- </div>
- {showSomeActions && (
- <div className="mb-1 border-gray-200 dark:border-gray-700 border-b"></div>
- )}
- </>
- )}
- {showSomeActions && (
- <div className="flex flex-col">
- {actions.map((action) => {
- const linkClassName = classNames(
- popover.items.classNames.navigationLink,
- popover.items.classNames.selectedOption,
- popover.items.classNames.hoverLink,
- 'whitespace-nowrap'
- )
-
- switch (action) {
- case 'clear all filters':
- return (
- <ClearAction key={action} className={linkClassName} />
- )
- case 'save as segment':
- return (
- <SaveAsSegmentAction
- key={action}
- className={linkClassName}
- />
- )
- default:
- return null
- }
- })}
- </div>
- )}
- </Popover.Panel>
- </Transition>
- </Popover>
+ <AppliedFilterPillsList
+ ref={ref}
+ className="md:overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
+ style={{ maskImage }}
+ />
)
}
-const ClearAction = ({ className }: { className?: string }) => (
- <AppNavigationLink
- className={className}
- search={(search) => ({
- ...search,
- filters: null,
- labels: null
- })}
+const actionClassName = classNames(
+ popover.toggleButton.classNames.rounded,
+ popover.toggleButton.classNames.ghost,
+ 'justify-center'
+)
+
+const ActionTooltip = ({
+ label,
+ keybind,
+ children,
+ docsLink
+}: {
+ label: string
+ keybind?: string
+ children: ReactNode
+ docsLink?: { href: string; label: string }
+}) => (
+ <Tooltip
+ interactive={!!docsLink}
+ containerRef={{ current: document.body }}
+ info={
+ <span className="flex items-center gap-x-2 whitespace-nowrap">
+ {label}
+ {keybind && (
+ <kbd className="rounded-sm border border-gray-600 dark:border-gray-500 px-1 font-sans text-xs text-gray-300">
+ {keybind}
+ </kbd>
+ )}
+ {docsLink && (
+ <a
+ href={docsLink.href}
+ target="_blank"
+ rel="noreferrer"
+ aria-label={docsLink.label}
+ >
+ <QuestionMarkCircleIcon className="size-4" />
+ </a>
+ )}
+ </span>
+ }
>
- Clear all filters
- </AppNavigationLink>
+ {children}
+ </Tooltip>
)
-const SaveAsSegmentAction = ({ className }: { className?: string }) => {
+const ClearAction = () => (
+ <ActionTooltip label="Clear all filters" keybind="ESC">
+ <AppNavigationLink
+ aria-label="Clear all filters"
+ className={actionClassName}
+ search={(search) => ({
+ ...search,
+ filters: null,
+ labels: null
+ })}
+ >
+ <TrashIcon className="block size-4" />
+ </AppNavigationLink>
+ </ActionTooltip>
+)
+
+const SaveAsSegmentAction = () => {
const { setModal } = useRoutelessModalsContext()
return (
- <AppNavigationLink
- className={className}
- search={(s) => s}
- onClick={() => setModal({ type: 'create-segment' })}
- state={{ expandedSegment: null }}
+ <ActionTooltip
+ label="Save as segment"
+ docsLink={{
+ href: 'https://plausible.io/docs/filters-segments#how-to-save-a-segment',
+ label: 'Learn more about segments'
+ }}
>
- Save as segment
- </AppNavigationLink>
+ <AppNavigationLink
+ aria-label="Save as segment"
+ className={actionClassName}
+ search={(s) => s}
+ onClick={() => setModal({ type: 'create-segment' })}
+ state={{ expandedSegment: null }}
+ >
+ <StarIcon className="block size-4" />
+ </AppNavigationLink>
+ </ActionTooltip>
)
}
diff --git a/assets/js/dashboard/nav-menu/query-periods/dashboard-period-menu.tsx b/assets/js/dashboard/nav-menu/query-periods/dashboard-period-menu.tsx
index 204d48a5ee..0ca5bbabe6 100644
--- a/assets/js/dashboard/nav-menu/query-periods/dashboard-period-menu.tsx
+++ b/assets/js/dashboard/nav-menu/query-periods/dashboard-period-menu.tsx
@@ -109,7 +109,7 @@ export const DashboardPeriodMenu = ({
<Popover.Button
ref={buttonRef}
className={classNames(
- 'flex items-center gap-x-1.5 pl-2.5 text-sm font-medium text-gray-700 dark:text-gray-100 leading-tight h-full rounded-md focus-visible:ring-0 focus-visible:ring-offset-0',
+ 'flex items-center gap-x-1.5 pl-2.5 text-sm font-medium text-gray-800 dark:text-gray-100 leading-tight h-full rounded-md focus-visible:ring-0 focus-visible:ring-offset-0',
periodsWithArrows.includes(dashboardState.period)
? 'pr-1.5'
: 'pr-2.5'
diff --git a/assets/js/dashboard/nav-menu/query-periods/move-period-arrows.tsx b/assets/js/dashboard/nav-menu/query-periods/move-period-arrows.tsx
index bfce22d42c..51ac1331dd 100644
--- a/assets/js/dashboard/nav-menu/query-periods/move-period-arrows.tsx
+++ b/assets/js/dashboard/nav-menu/query-periods/move-period-arrows.tsx
@@ -59,7 +59,7 @@ function ArrowIcon({
'size-3.5',
disabled
? 'text-gray-400 dark:text-gray-500'
- : 'text-gray-700 dark:text-gray-300'
+ : 'text-gray-800 dark:text-gray-300'
)}
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
@@ -99,7 +99,7 @@ export function MovePeriodArrows() {
classNames(
'flex items-center justify-center px-px h-full rounded-md',
enabled
- ? 'text-gray-700 dark:text-gray-300'
+ ? 'text-gray-800 dark:text-gray-300'
: 'text-gray-400 dark:text-gray-600 cursor-not-allowed'
)
diff --git a/assets/js/dashboard/nav-menu/top-bar.tsx b/assets/js/dashboard/nav-menu/top-bar.tsx
index aba9aa7355..7c2b29269f 100644
--- a/assets/js/dashboard/nav-menu/top-bar.tsx
+++ b/assets/js/dashboard/nav-menu/top-bar.tsx
@@ -1,14 +1,14 @@
-import React, { ReactNode, useRef } from 'react'
+import React, { CSSProperties, ReactNode } from 'react'
import { SiteSwitcher } from '../site-switcher'
import { useSiteContext } from '../site-context'
import CurrentVisitors from '../stats/current-visitors'
import classNames from 'classnames'
import { useInView } from 'react-intersection-observer'
-import { FilterMenu } from './filter-menu'
import { FiltersBar } from './filters-bar'
import { DashboardPeriodPicker } from './query-periods/dashboard-period-picker'
import { SegmentMenu } from './segments/segment-menu'
import { DashboardOptionsMenu } from './dashboard-options-menu'
+import { useScrollFadeMask } from '../hooks/use-scroll-fade-mask'
interface TopBarProps {
showCurrentVisitors: boolean
@@ -44,33 +44,22 @@ function TopBarStickyWrapper({ children }: { children: ReactNode }) {
}
function TopBarInner({ showCurrentVisitors }: TopBarProps) {
- const leftActionsRef = useRef<HTMLDivElement>(null)
+ const { ref, maskImage } = useScrollFadeMask<HTMLDivElement>()
return (
- <div className="flex min-w-0 flex-nowrap items-center gap-x-1 md:gap-x-2.5 overflow-x-auto md:overflow-visible w-full touch-pan-x md:touch-auto [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden py-1 -my-1 md:py-0 md:my-0">
- <div
- className="flex shrink-0 items-center sm:gap-x-1 md:gap-x-2.5"
- ref={leftActionsRef}
- >
+ <div
+ ref={ref}
+ className="flex min-w-0 flex-nowrap items-center gap-x-1 overflow-x-auto md:overflow-visible w-full touch-pan-x md:touch-auto [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden py-1 -my-1 md:py-0 md:my-0 max-md:[mask-image:var(--scroll-fade-mask)]"
+ style={{ '--scroll-fade-mask': maskImage } as CSSProperties}
+ >
+ <div className="flex shrink-0 items-center sm:gap-x-1 md:gap-x-2.5">
<SiteSwitcher />
{showCurrentVisitors && <CurrentVisitors />}
</div>
- <div className="flex flex-1">
- <FiltersBar
- accessors={{
- topBar: (filtersBarElement) =>
- filtersBarElement?.parentElement?.parentElement,
- leftSection: (filtersBarElement) =>
- filtersBarElement?.parentElement?.parentElement
- ?.firstElementChild as HTMLElement,
- rightSection: (filtersBarElement) =>
- filtersBarElement?.parentElement?.parentElement
- ?.lastElementChild as HTMLElement
- }}
- />
+ <div className="flex flex-1 md:min-w-0">
+ <FiltersBar />
</div>
- <div className="flex gap-x-1 md:gap-x-2.5 shrink-0">
- <FilterMenu />
+ <div className="flex gap-x-1 shrink-0">
<SegmentMenu />
<DashboardPeriodPicker />
<DashboardOptionsMenu />
diff --git a/assets/js/dashboard/segments/segment-modals.tsx b/assets/js/dashboard/segments/segment-modals.tsx
index bc4c7a147d..19162724ef 100644
--- a/assets/js/dashboard/segments/segment-modals.tsx
+++ b/assets/js/dashboard/segments/segment-modals.tsx
@@ -261,12 +261,9 @@ const RelatedSharedLinks = ({ sharedLinks }: { sharedLinks: string[] }) => {
<p className={inModalSectionLabelClassName}>Shared links</p>
<FilterPillsList
className="flex-wrap"
- direction="horizontal"
pills={sharedLinks.map((name) => ({
- className: 'dark:!shadow-gray-950/60',
plainText: name,
- children: name,
- interactive: false
+ children: name
}))}
/>
</div>
@@ -430,12 +427,9 @@ const FiltersInSegment = ({
<p className={inModalSectionLabelClassName}>Filters in segment</p>
<FilterPillsList
className="flex-wrap"
- direction="horizontal"
pills={segment_data.filters.map((filter) => ({
- className: 'dark:!shadow-gray-950/60',
plainText: plainFilterText({ labels: segment_data.labels }, filter),
- children: styledFilterText({ labels: segment_data.labels }, filter),
- interactive: false
+ children: styledFilterText({ labels: segment_data.labels }, filter)
}))}
/>
</div>
diff --git a/assets/js/dashboard/site-switcher.tsx b/assets/js/dashboard/site-switcher.tsx
index d684fb6415..fddc90818f 100644
--- a/assets/js/dashboard/site-switcher.tsx
+++ b/assets/js/dashboard/site-switcher.tsx
@@ -59,7 +59,7 @@ const SiteSwitcherStatic = () => {
data-testid="site-switcher-static"
className={classNames(
popover.toggleButton.classNames.rounded,
- 'gap-x-1.5 pl-0 pr-2.5 font-medium text-gray-700 dark:text-gray-100'
+ 'gap-x-1.5 pl-0 pr-2.5 font-medium text-gray-800 dark:text-gray-100'
)}
title={currentSite.domain}
>
diff --git a/assets/js/dashboard/stats/modals/filter-modal-props-row.js b/assets/js/dashboard/stats/modals/filter-modal-props-row.js
index 3912beb374..f74ae6adf9 100644
--- a/assets/js/dashboard/stats/modals/filter-modal-props-row.js
+++ b/assets/js/dashboard/stats/modals/filter-modal-props-row.js
@@ -1,5 +1,5 @@
import React, { useMemo } from 'react'
-import { TrashIcon } from '@heroicons/react/20/solid'
+import { TrashIcon } from '../../components/icons'
import FilterOperatorSelector from '../../components/filter-operator-selector'
import Combobox from '../../components/combobox'
diff --git a/assets/js/dashboard/stats/modals/filter-modal-row.js b/assets/js/dashboard/stats/modals/filter-modal-row.js
index 8759dba7bb..094fa748cf 100644
--- a/assets/js/dashboard/stats/modals/filter-modal-row.js
+++ b/assets/js/dashboard/stats/modals/filter-modal-row.js
@@ -1,5 +1,5 @@
import React, { useMemo } from 'react'
-import { TrashIcon } from '@heroicons/react/20/solid'
+import { TrashIcon } from '../../components/icons'
import classNames from 'classnames'
import FilterOperatorSelector from '../../components/filter-operator-selector'
diff --git a/assets/js/dashboard/util/filter-text.tsx b/assets/js/dashboard/util/filter-text.tsx
index 444adf0d51..ba561b980b 100644
--- a/assets/js/dashboard/util/filter-text.tsx
+++ b/assets/js/dashboard/util/filter-text.tsx
@@ -52,7 +52,7 @@ function formatClauses(labels: Array<string | number>): ReactNode[] {
return labels.map((label, index) => (
<Fragment key={index}>
{index > 0 && ' or '}
- <b>{label}</b>
+ <span className="font-semibold">{label}</span>
</Fragment>
))
}
diff --git a/assets/js/dashboard/util/tooltip.tsx b/assets/js/dashboard/util/tooltip.tsx
index 98febf3dec..d2b9bcda68 100644
--- a/assets/js/dashboard/util/tooltip.tsx
+++ b/assets/js/dashboard/util/tooltip.tsx
@@ -1,4 +1,11 @@
-import React, { CSSProperties, ReactNode, RefObject, useState } from 'react'
+import React, {
+ CSSProperties,
+ ReactNode,
+ RefObject,
+ useEffect,
+ useRef,
+ useState
+} from 'react'
import { usePopper } from 'react-popper'
import classNames from 'classnames'
import { createPortal } from 'react-dom'
@@ -9,7 +16,8 @@ export function Tooltip({
className,
onClick,
boundary,
- containerRef
+ containerRef,
+ interactive = false
}: {
info: ReactNode
children: ReactNode
@@ -19,8 +27,11 @@ export function Tooltip({
boundary?: HTMLElement | null
/** if defined, the tooltip is rendered in a portal to this element */
containerRef?: RefObject<HTMLElement>
+ /** if true, the tooltip stays open while hovered, so its content can be clicked */
+ interactive?: boolean
}) {
const [visible, setVisible] = useState(false)
+ const hideTimeout = useRef<ReturnType<typeof setTimeout>>()
const [referenceElement, setReferenceElement] =
useState<HTMLDivElement | null>(null)
const [popperElement, setPopperElement] = useState<HTMLDivElement | null>(
@@ -49,12 +60,28 @@ export function Tooltip({
]
})
+ useEffect(() => () => clearTimeout(hideTimeout.current), [])
+
+ const show = () => {
+ clearTimeout(hideTimeout.current)
+ setVisible(true)
+ }
+
+ const hide = () => {
+ if (interactive) {
+ // lets the pointer move onto the tooltip before it hides
+ hideTimeout.current = setTimeout(() => setVisible(false))
+ } else {
+ setVisible(false)
+ }
+ }
+
return (
<div className={classNames('relative', className)}>
<div
ref={setReferenceElement}
- onMouseEnter={() => setVisible(true)}
- onMouseLeave={() => setVisible(false)}
+ onMouseEnter={show}
+ onMouseLeave={hide}
onClick={onClick}
>
{children}
@@ -65,6 +92,9 @@ export function Tooltip({
popperStyle={styles.popper}
popperAttributes={attributes.popper}
setPopperElement={setPopperElement}
+ interactive={interactive}
+ onMouseEnter={interactive ? show : undefined}
+ onMouseLeave={interactive ? hide : undefined}
>
{info}
</TooltipMessage>
@@ -78,12 +108,18 @@ function TooltipMessage({
popperStyle,
popperAttributes,
setPopperElement,
+ interactive,
+ onMouseEnter,
+ onMouseLeave,
children
}: {
containerRef?: RefObject<HTMLElement>
popperStyle: CSSProperties
popperAttributes?: Record<string, string>
setPopperElement: (element: HTMLDivElement) => void
+ interactive: boolean
+ onMouseEnter?: () => void
+ onMouseLeave?: () => void
children: ReactNode
}) {
const messageElement = (
@@ -91,8 +127,15 @@ function TooltipMessage({
ref={setPopperElement}
style={popperStyle}
{...popperAttributes}
- className="pointer-events-none z-[99] [body:has(.modal.is-open)_&]:z-[1000] px-2 py-1 rounded-sm text-sm text-gray-100 font-medium bg-gray-800 dark:bg-gray-700"
+ className={classNames(
+ 'z-[99] [body:has(.modal.is-open)_&]:z-[1000] px-2 py-1 rounded-sm text-sm text-gray-100 font-medium bg-gray-800 dark:bg-gray-700',
+ interactive
+ ? 'before:absolute before:inset-x-0 before:top-full before:h-1.5 [&[data-popper-placement^=bottom]]:before:top-auto [&[data-popper-placement^=bottom]]:before:bottom-full'
+ : 'pointer-events-none'
+ )}
role="tooltip"
+ onMouseEnter={onMouseEnter}
+ onMouseLeave={onMouseLeave}
>
{children}
</div>
diff --git a/e2e/tests/dashboard/filtering.spec.ts b/e2e/tests/dashboard/filtering.spec.ts
index 7ab2b88719..57ead268fd 100644
--- a/e2e/tests/dashboard/filtering.spec.ts
+++ b/e2e/tests/dashboard/filtering.spec.ts
@@ -623,18 +623,6 @@ test.describe('location filtering tests', () => {
await test.step('filtering by city', async () => {
const cityFilterRow = filterRow(page, 'city')
const cityInput = page.getByPlaceholder('Select a City')
- const browserFilterRow = filterRow(page, 'browser')
- const browserInput = page.getByPlaceholder('Select a Browser', {
- exact: true
- })
-
- // Add a browser filter so city ends up as the 4th pill. This ensures it overflows
- // into "See more" regardless of viewport width.
- await filterButton(page).click()
- await openFilterSubmenuItem(page, 'Browser', 'Browser')
- await browserInput.fill('chrom')
- await suggestedItem(browserFilterRow, 'Chrome').click()
- await applyFilterButton(page).click()
await filterButton(page).click()
await openLocationFilter(page, 'City')
@@ -644,7 +632,6 @@ test.describe('location filtering tests', () => {
await applyFilterButton(page).click()
- await page.getByRole('button', { name: /See.*more/ }).click()
await expect(
page.getByRole('link', { name: 'City is Tallinn' })
).toBeVisible()
@@ -816,28 +803,6 @@ test.describe('operating system filtering tests', () => {
const operatingSystemVersionInput = page.getByPlaceholder(
'Select an Operating system version'
)
- const browserFilterRow = filterRow(page, 'browser')
- const browserVersionFilterRow = filterRow(page, 'browser_version')
- const browserInput = page.getByPlaceholder('Select a Browser', {
- exact: true
- })
- const browserVersionInput = page.getByPlaceholder(
- 'Select a Browser Version'
- )
-
- // Add browser and browser version filters so OS version ends up as the 4th pill.
- // This ensures it overflows into "See more" regardless of viewport width
- await filterButton(page).click()
- await openFilterSubmenuItem(page, 'Browser', 'Browser')
- await browserInput.fill('chrom')
- await suggestedItem(browserFilterRow, 'Chrome').click()
- await applyFilterButton(page).click()
-
- await filterButton(page).click()
- await openFilterSubmenuItem(page, 'Browser', 'Browser version')
- await browserVersionInput.fill('14')
- await suggestedItem(browserVersionFilterRow, '14.0.7').click()
- await applyFilterButton(page).click()
await filterButton(page).click()
await openFilterSubmenuItem(
@@ -851,7 +816,6 @@ test.describe('operating system filtering tests', () => {
await applyFilterButton(page).click()
- await page.getByRole('button', { name: /See.*more/ }).click()
await expect(
page.getByRole('link', { name: 'Operating system version is 11' })
).toBeVisible()
@@ -999,10 +963,6 @@ test.describe('property filtering tests', () => {
await applyFilterButton(page).click()
- await page
- .getByRole('button', { name: 'See 1 more filter and actions' })
- .click()
-
await expect(
page.getByRole('link', {
name: 'Property logged_in is false'
diff --git a/e2e/tests/dashboard/segments.spec.ts b/e2e/tests/dashboard/segments.spec.ts
index c5ef0d3280..90242a21a7 100644
--- a/e2e/tests/dashboard/segments.spec.ts
+++ b/e2e/tests/dashboard/segments.spec.ts
@@ -79,8 +79,6 @@ const addUtmSourceFilter = async (page: Page, utmSource: string) => {
}
const createPersonalSegment = async (page: Page, name: string) => {
- await page.getByRole('button', { name: 'See actions' }).click()
-
await page.getByRole('link', { name: 'Save as segment' }).click()
await modal(page).getByLabel('Segment name').fill(name)
@@ -98,8 +96,6 @@ test('saving a segment', async ({ page, request }) => {
await test.step('creating personal segment using defaults', async () => {
await addSourceFilter(page, 'Facebook')
- await page.getByRole('button', { name: 'See actions' }).click()
-
await page.getByRole('link', { name: 'Save as segment' }).click()
await expect(
@@ -139,8 +135,6 @@ test('saving a segment', async ({ page, request }) => {
await test.step('creating a personal segment with a custom name', async () => {
await addSourceFilter(page, 'Google')
- await page.getByRole('button', { name: 'See actions' }).click()
-
await page.getByRole('link', { name: 'Save as segment' }).click()
await expect(
@@ -180,8 +174,6 @@ test('saving a segment', async ({ page, request }) => {
await addSourceFilter(page, 'Google')
await addUtmSourceFilter(page, 'Adwords')
- await page.getByRole('button', { name: 'See actions' }).click()
-
await page.getByRole('link', { name: 'Save as segment' }).click()
await expect(
@@ -239,28 +231,6 @@ test('creating a segment from a combination of segment and a filter is not allow
await createPersonalSegment(page, 'Traffic from Google')
await addUtmSourceFilter(page, 'Adwords')
- // Add UTM medium and campaign filters. Every new filter is prepended, so
- // Segment ends up as the last pill and overflows into "See more".
- const utmMediumFilterRow = filterRow(page, 'utm_medium')
- const utmCampaignFilterRow = filterRow(page, 'utm_campaign')
-
- await filterButton(page).click()
- await openFilterSubmenuItem(page, 'UTM tags', 'UTM medium')
- await page.getByPlaceholder('Select a UTM Medium').click()
- await suggestedItem(utmMediumFilterRow, 'email').click()
- await applyFilterButton(page).click()
-
- await filterButton(page).click()
- await openFilterSubmenuItem(page, 'UTM tags', 'UTM campaign')
- await page.getByPlaceholder('Select a UTM Campaign').click()
- await suggestedItem(utmCampaignFilterRow, 'promo').click()
- await applyFilterButton(page).click()
-
- await expect(
- page.getByRole('link', { name: 'UTM campaign is promo' })
- ).toBeVisible()
-
- await page.getByRole('button', { name: /See.*more/ }).click()
await expect(
page.getByRole('link', { name: 'UTM source is Adwords' })
).toBeVisible()
diff --git a/e2e/tests/test-utils.ts b/e2e/tests/test-utils.ts
index b25c4330d7..db309cc7af 100644
--- a/e2e/tests/test-utils.ts
+++ b/e2e/tests/test-utils.ts
@@ -86,7 +86,7 @@ export const closeModalButton = (page: Page) =>
page.getByRole('button', { name: 'Close modal' })
export const filterButton = (page: Page) =>
- page.getByRole('button', { name: 'Filter', exact: true })
+ page.getByRole('button', { name: /^(Filter|Add filter)$/ })
const filterMenu = (page: Page) => page.getByTestId('filtermenu')