Open source, privacy-first web analytics. Lightweight, cookie-free Google Analytics alternative. Self-hosted or cloud.
TypeScript analyticsanalytics-dashboardclickhouseelixirgoogle-analyticsmarketingopen-source-analyticsphoenixplausible-analyticspostgresqlprivacyprivacy-friendlyself-hostedsimple-analyticsstatisticstailwindcssweb-analyticswebsite-analyticswebsite-statswebsite-tracking
Edit filters inline in the filter pills (#6730)
Sanne de Vries903d2d0440a7
diff --git a/assets/css/app.css b/assets/css/app.cssindex 37d302d9b8..1f58d4a46a 100644--- a/assets/css/app.css+++ b/assets/css/app.css@@ -190,6 +190,25 @@.tooltip-theme-darker {@apply dark:bg-gray-950 dark:ring-gray-900 dark:shadow-none;}++ /*+ * Checkbox component classes shared between the React `Checkbox` component+ * and `checkboxClassName` (assets/js/dashboard/components/form-elements.tsx).+ * Update here only.+ */+ .checkbox-base {+ @apply block shrink-0 rounded-sm border-gray-300 dark:border-gray-600+ dark:bg-gray-600 text-indigo-600 checked:border-indigo-600+ checked:bg-indigo-600;+ }++ .checkbox-sm {+ @apply size-4;+ }++ .checkbox-md {+ @apply size-5;+ }}@utility btn-text-primary {diff --git a/assets/js/dashboard/components/combobox.js b/assets/js/dashboard/components/combobox.jsdeleted file mode 100644index 0d8d3229a6..0000000000--- a/assets/js/dashboard/components/combobox.js+++ /dev/null@@ -1,379 +0,0 @@-import React, {- Fragment,- useState,- useCallback,- useEffect,- useRef-} from 'react'-import { Spinner } from './icons'-import { Transition } from '@headlessui/react'-import { ChevronDownIcon } from '@heroicons/react/20/solid'-import classNames from 'classnames'-import { useMountedEffect, useDebounce } from '../custom-hooks'--function Option({ isHighlighted, onClick, onMouseEnter, text, id }) {- const className = classNames(- 'relative cursor-pointer select-none py-2 px-3 text-gray-900 dark:text-gray-300',- {- 'bg-gray-100 dark:bg-gray-700': isHighlighted- }- )-- return (- // eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions- <li- className={className}- id={id}- onClick={onClick}- onMouseEnter={onMouseEnter}- >- <span className="block truncate">{text}</span>- </li>- )-}-function scrollTo(wrapper, id) {- if (wrapper) {- const el = wrapper.querySelector('#' + id)-- if (el) {- el.scrollIntoView({ block: 'center' })- }- }-}--function optionId(index) {- return `plausible-combobox-option-${index}`-}--export default function PlausibleCombobox({- values,- fetchOptions,- singleOption,- isDisabled,- autoFocus,- freeChoice,- disabledOptions,- onSelect,- placeholder,- forceLoading,- className,- boxClass-}) {- const isEmpty = values.length === 0- const [options, setOptions] = useState([])- const [isLoading, setLoading] = useState(false)- const [isOpen, setOpen] = useState(false)- const [search, setSearch] = useState('')- const [highlightedIndex, setHighlightedIndex] = useState(0)- const searchRef = useRef(null)- const containerRef = useRef(null)- const listRef = useRef(null)-- const loading = isLoading || !!forceLoading-- const visibleOptions = [...options]- if (- freeChoice &&- search.length > 0 &&- options.every((option) => option.value !== search)- ) {- visibleOptions.push({ value: search, label: search, freeChoice: true })- }-- const afterFetchOptions = useCallback((loadedOptions) => {- setLoading(false)- setHighlightedIndex(0)- setOptions(loadedOptions)- }, [])-- const initialFetchOptions = useCallback(() => {- setLoading(true)- fetchOptions('').then(afterFetchOptions)- }, [fetchOptions, afterFetchOptions])-- const searchOptions = useCallback(() => {- if (isOpen) {- setLoading(true)- fetchOptions(search).then(afterFetchOptions)- }- }, [search, isOpen, fetchOptions, afterFetchOptions])-- const debouncedSearchOptions = useDebounce(searchOptions)-- useEffect(() => {- if (isOpen) {- initialFetchOptions()- }- }, [isOpen, initialFetchOptions])-- useMountedEffect(() => {- debouncedSearchOptions()- }, [search])-- function highLight(index) {- let newIndex = index-- if (index < 0) {- newIndex = visibleOptions.length - 1- } else if (index >= visibleOptions.length) {- newIndex = 0- }-- setHighlightedIndex(newIndex)- scrollTo(listRef.current, optionId(newIndex))- }-- function onKeyDown(e) {- if (e.key === 'Enter') {- if (!isOpen || loading || visibleOptions.length === 0) return null- selectOption(visibleOptions[highlightedIndex])- e.preventDefault()- }- if (e.key === 'Escape') {- if (!isOpen || loading) return null- setOpen(false)- searchRef.current?.focus()- e.preventDefault()- }- if (e.key === 'ArrowDown') {- if (isOpen) {- highLight(highlightedIndex + 1)- } else {- setOpen(true)- }- }- if (e.key === 'ArrowUp') {- if (isOpen) {- highLight(highlightedIndex - 1)- } else {- setOpen(true)- }- }- }-- function isOptionDisabled(option) {- const optionAlreadySelected = values.some(- (val) => val.value === option.value- )- const optionDisabled = (disabledOptions || []).some(- (val) => val?.value === option.value- )- return optionAlreadySelected || optionDisabled- }-- function onInput(e) {- if (!isOpen) {- setOpen(true)- }- setSearch(e.target.value)- }-- function toggleOpen() {- if (!isOpen) {- setOpen(true)- searchRef.current.focus()- } else {- setSearch('')- setOpen(false)- }- }-- function selectOption(option) {- if (singleOption) {- onSelect([option])- } else {- searchRef.current.focus()- onSelect([...values, option])- }-- setOpen(false)- setSearch('')- }-- function removeOption(option, e) {- e.stopPropagation()- const newValues = values.filter((val) => val.value !== option.value)- onSelect(newValues)- searchRef.current.focus()- setOpen(false)- }-- const handleClick = useCallback((e) => {- if (containerRef.current && containerRef.current.contains(e.target)) {- return- }-- setSearch('')- setOpen(false)- }, [])-- useEffect(() => {- document.addEventListener('mousedown', handleClick, false)- return () => {- document.removeEventListener('mousedown', handleClick, false)- }- }, [handleClick])-- useEffect(() => {- if (singleOption && isEmpty && autoFocus) {- searchRef.current.focus()- }- }, [isEmpty, singleOption, autoFocus])-- const searchBoxClass =- 'border-none py-1 px-0 w-full inline-block rounded-md focus:outline-hidden focus:ring-0 text-sm'-- const containerClass = classNames('relative w-full', {- [className]: !!className,- 'opacity-30 cursor-default pointer-events-none': isDisabled- })-- function renderSingleOptionContent() {- const itemSelected = values.length === 1-- return (- <div className="flex items-center truncate">- {itemSelected && renderSingleSelectedItem()}- <input- className={searchBoxClass}- ref={searchRef}- value={search}- style={{ backgroundColor: 'inherit' }}- placeholder={itemSelected ? '' : placeholder}- type="text"- onChange={onInput}- ></input>- </div>- )- }-- function renderSingleSelectedItem() {- if (search === '') {- return (- <span className="dark:text-gray-300 text-sm w-0">- {values[0].label}- </span>- )- }- }-- function renderMultiOptionContent() {- return (- <>- {values.map((value) => {- return (- <div- key={value.value}- className="bg-indigo-100 dark:bg-indigo-600 flex justify-between w-full rounded-xs px-2 py-0.5 m-0.5 text-sm"- >- <span className="break-all">{value.label}</span>- <span- onClick={(e) => removeOption(value, e)}- className="cursor-pointer font-bold ml-1"- >- ×- </span>- </div>- )- })}- <input- className={searchBoxClass}- ref={searchRef}- value={search}- style={{ backgroundColor: 'inherit' }}- placeholder={placeholder}- type="text"- onChange={onInput}- ></input>- </>- )- }-- function renderDropDownContent() {- const matchesFound =- visibleOptions.length > 0 &&- visibleOptions.some((option) => !isOptionDisabled(option))-- if (loading) {- return (- <div className="relative cursor-default select-none py-2 px-4 text-gray-700 dark:text-gray-300">- Loading options...- </div>- )- }-- if (matchesFound) {- return visibleOptions- .filter((option) => !isOptionDisabled(option))- .map((option, i) => {- const text = option.freeChoice- ? `Filter by '${option.label}'`- : option.label-- return (- <Option- key={option.value}- id={optionId(i)}- isHighlighted={highlightedIndex === i}- onClick={() => selectOption(option)}- onMouseEnter={() => setHighlightedIndex(i)}- text={text}- />- )- })- }-- if (freeChoice) {- return (- <div className="relative cursor-default select-none py-2 px-4 text-gray-700 dark:text-gray-300">- Start typing to apply filter- </div>- )- }-- return (- <div className="relative cursor-default select-none py-2 px-4 text-gray-700 dark:text-gray-300">- No matches found in the current dashboard. Try selecting a different- time range or searching for something different- </div>- )- }-- const defaultBoxClass =- 'pl-2 pr-8 py-1 w-full dark:bg-gray-750 dark:text-gray-300 rounded-md shadow-xs border border-gray-300 dark:border-gray-750'- const finalBoxClass = classNames(boxClass || defaultBoxClass, {- 'ring-3 ring-indigo-500/20 dark:ring-indigo-500/25 border !border-indigo-500':- isOpen- })-- return (- <div onKeyDown={onKeyDown} ref={containerRef} className={containerClass}>- <div onClick={toggleOpen} className={finalBoxClass}>- {singleOption && renderSingleOptionContent()}- {!singleOption && renderMultiOptionContent()}- <div className="cursor-pointer absolute inset-y-0 right-0 flex items-center pr-2">- {!loading && <ChevronDownIcon className="h-4 w-4 text-gray-500" />}- {loading && (- <Spinner className="animate-spin size-4 text-indigo-500" />- )}- </div>- </div>- {isOpen && (- <Transition- as={Fragment}- leave="transition ease-in duration-100"- leaveFrom="opacity-100"- leaveTo="opacity-0"- show={isOpen}- >- <ul- ref={listRef}- className="z-50 absolute mt-1 max-h-60 w-full overflow-auto rounded-md bg-white py-1 text-base shadow-lg ring-1/5 ring-black focus:outline-hidden sm:text-sm dark:bg-gray-800"- >- {renderDropDownContent()}- </ul>- </Transition>- )}- </div>- )-}diff --git a/assets/js/dashboard/components/combobox.tsx b/assets/js/dashboard/components/combobox.tsxnew file mode 100644index 0000000000..d5a78263f7--- /dev/null+++ b/assets/js/dashboard/components/combobox.tsx@@ -0,0 +1,251 @@+import React, { useEffect, useId, useRef, useState } from 'react'+import classNames from 'classnames'+import { keepPreviousData, useQuery } from '@tanstack/react-query'+import { useDashboardStateContext } from '../dashboard-state-context'+import {+ fetchSuggestions,+ Suggestion,+ SuggestionsRequest+} from '../util/fetch-suggestions'+import { Spinner } from './icons'+import { popover } from './popover'+import { SearchInput } from './search-input'+import { checkboxClassName } from './form-elements'++export type ComboboxOption = Suggestion & { freeChoice?: boolean }++export const isSameValue = (a: Suggestion['value'], b: Suggestion['value']) =>+ String(a) === String(b)++const matchesSearch = (option: Suggestion, search: string) =>+ option.label.toLowerCase().includes(search.trim().toLowerCase())++export const Combobox = ({+ request,+ pinned = [],+ multiple = false,+ freeChoice = false,+ isSelected = () => false,+ isDisabled,+ onSelect,+ label,+ focusOnMount+}: {+ request: SuggestionsRequest | null+ /** Shown before the suggestions, and kept in place while the list is open */+ pinned?: Suggestion[]+ multiple?: boolean+ freeChoice?: boolean+ isSelected?: (option: Suggestion) => boolean+ isDisabled?: (option: Suggestion) => boolean+ onSelect: (option: ComboboxOption) => void+ label: string+ focusOnMount?: boolean+}) => {+ const { dashboardState } = useDashboardStateContext()+ // keeps the suggestions the same while the selected values change the dashboard+ const [initialDashboardState] = useState(dashboardState)+ const listboxId = useId()+ const inputRef = useRef<HTMLInputElement>(null)+ const listRef = useRef<HTMLUListElement>(null)+ const [input, setInput] = useState('')+ const [search, setSearch] = useState('')+ const [highlightedIndex, setHighlightedIndex] = useState(0)++ useEffect(() => {+ if (focusOnMount) {+ inputRef.current?.focus({ preventScroll: true })+ }+ }, [focusOnMount])++ const suggestionsQuery = useQuery({+ queryKey: [+ 'filter-suggestions',+ request?.path,+ request?.additionalFilter,+ search.trim(),+ initialDashboardState+ ],+ queryFn: () =>+ fetchSuggestions(+ request!.path,+ initialDashboardState,+ search,+ request!.additionalFilter+ ),+ enabled: !!request,+ placeholderData: keepPreviousData+ })++ const trimmedInput = input.trim()+ const pinnedOptions = pinned.filter((option) =>+ matchesSearch(option, trimmedInput)+ )+ const suggestedOptions = (+ request ? (suggestionsQuery.data ?? []) : []+ ).filter((option) => !pinned.some((p) => isSameValue(p.value, option.value)))+ const freeChoiceOptions: ComboboxOption[] =+ freeChoice &&+ trimmedInput.length > 0 &&+ ![...pinned, ...suggestedOptions].some((option) =>+ isSameValue(option.value, trimmedInput)+ )+ ? [{ value: trimmedInput, label: trimmedInput, freeChoice: true }]+ : []+ const options: ComboboxOption[] = [+ ...freeChoiceOptions,+ ...pinnedOptions,+ ...suggestedOptions+ ]+ const activeIndex = Math.min(highlightedIndex, options.length - 1)++ const optionId = (index: number) => `${listboxId}-option-${index}`++ const highlight = (index: number) => {+ const wrapped = (index + options.length) % options.length+ setHighlightedIndex(wrapped)+ listRef.current+ ?.querySelector(`[id="${optionId(wrapped)}"]`)+ ?.scrollIntoView?.({ block: 'nearest' })+ }++ const select = (option: ComboboxOption | undefined) => {+ if (!option || isDisabled?.(option)) {+ return+ }+ if (option.freeChoice) {+ setInput('')+ setSearch('')+ }+ onSelect(option)+ }++ const onKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {+ if (!options.length) {+ return+ }+ if (event.key === 'ArrowDown') {+ event.preventDefault()+ highlight(activeIndex + 1)+ } else if (event.key === 'ArrowUp') {+ event.preventDefault()+ highlight(Math.max(activeIndex, 0) - 1)+ } else if (event.key === 'Enter') {+ event.preventDefault()+ select(options[activeIndex])+ }+ }++ const isLoading = !!request && suggestionsQuery.isPending++ const getStatusMessage = () => {+ if (isLoading) {+ return 'Loading options...'+ }+ if (options.length) {+ return null+ }+ if (freeChoice) {+ return 'Start typing to apply filter'+ }+ return 'No matches found in the current dashboard. Try selecting a different time range or searching for something different'+ }+ const statusMessage = getStatusMessage()++ return (+ <div className="flex flex-col gap-y-1">+ <SearchInput+ searchRef={inputRef}+ className="!max-w-none"+ value={input}+ onChange={(value) => {+ setInput(value)+ setHighlightedIndex(0)+ }}+ onSearch={setSearch}+ inputProps={{+ role: 'combobox',+ 'aria-label': label,+ 'aria-expanded': options.length > 0,+ 'aria-controls': listboxId,+ 'aria-autocomplete': 'list',+ 'aria-activedescendant':+ activeIndex >= 0 ? optionId(activeIndex) : undefined,+ onKeyDown+ }}+ trailing={+ !!request &&+ suggestionsQuery.isFetching && (+ <Spinner className="animate-spin size-4 text-indigo-500" />+ )+ }+ />+ <ul+ ref={listRef}+ id={listboxId}+ role="listbox"+ aria-label={label}+ aria-multiselectable={multiple || undefined}+ className="flex flex-col gap-y-0.5 max-h-60 overflow-y-auto empty:hidden"+ onMouseLeave={() => setHighlightedIndex(-1)}+ >+ {options.map((option, index) => {+ const selected = isSelected(option)+ const disabled = !!isDisabled?.(option)+ const text = option.freeChoice+ ? `Filter by '${option.label}'`+ : option.label+ return (+ <li+ key={`${option.freeChoice ? 'free' : 'option'}-${option.value}`}+ id={optionId(index)}+ role="option"+ aria-selected={selected}+ aria-disabled={disabled || undefined}+ className={classNames(+ popover.items.classNames.staticRow,+ 'flex items-center gap-x-2 select-none',+ disabled+ ? 'cursor-default text-gray-400 dark:text-gray-500'+ : 'cursor-pointer',+ index === activeIndex &&+ !disabled &&+ popover.items.classNames.highlightedOption+ )}+ onMouseEnter={() => setHighlightedIndex(index)}+ onMouseDown={(event) => event.preventDefault()}+ onClick={() => select(option)}+ >+ {multiple && (+ <input+ type="checkbox"+ tabIndex={-1}+ aria-hidden="true"+ readOnly+ checked={selected}+ className={checkboxClassName({+ size: 'sm',+ className: 'pointer-events-none'+ })}+ />+ )}+ <span className={popover.items.classNames.label} title={text}>+ {text}+ </span>+ </li>+ )+ })}+ </ul>+ {statusMessage && (+ <div+ className={classNames(+ popover.items.classNames.staticRow,+ 'text-gray-500 dark:text-gray-400'+ )}+ >+ {statusMessage}+ </div>+ )}+ </div>+ )+}diff --git a/assets/js/dashboard/components/filter-operator-selector.js b/assets/js/dashboard/components/filter-operator-selector.jsdeleted file mode 100644index 46db51d0e5..0000000000--- a/assets/js/dashboard/components/filter-operator-selector.js+++ /dev/null@@ -1,95 +0,0 @@-import React, { useRef } from 'react'--import {- FILTER_OPERATIONS,- FILTER_OPERATIONS_DISPLAY_NAMES,- supportsContains,- supportsIsNot,- supportsHasDoneNot-} from '../util/filters'-import { Transition, Popover } from '@headlessui/react'-import { ChevronDownIcon } from '@heroicons/react/20/solid'-import classNames from 'classnames'-import { popover, BlurMenuButtonOnEscape } from './popover'--export default function FilterOperatorSelector(props) {- const filterName = props.forFilter- const buttonRef = useRef()-- return (- <div- className={classNames('w-full', {- 'opacity-20 cursor-default pointer-events-none': props.isDisabled- })}- >- <Popover className="relative w-full">- {({ close: closeDropdown }) => (- <>- <BlurMenuButtonOnEscape targetRef={buttonRef} />- <Popover.Button- ref={buttonRef}- className="relative flex justify-between items-center w-full rounded-md border border-gray-300 dark:border-gray-750 px-4 py-2 bg-white dark:bg-gray-750 text-sm text-gray-700 dark:text-gray-200 dark:hover:bg-gray-700 focus:outline-hidden focus:ring-2 focus:ring-offset-2 focus:ring-offset-gray-100 dark:focus:ring-offset-gray-900 focus:ring-indigo-500 text-left"- >- <span data-testid="filter-operator">- {FILTER_OPERATIONS_DISPLAY_NAMES[props.selectedType]}- </span>- <ChevronDownIcon- className="-mr-2 ml-2 h-4 w-4 text-gray-500 dark:text-gray-400"- aria-hidden="true"- />- </Popover.Button>- <Transition- as="div"- {...popover.transition.props}- className={classNames(popover.transition.classNames.left, 'mt-2')}- >- <Popover.Panel- className={classNames(- popover.panel.classNames.roundedSheet,- 'font-normal'- )}- >- {[- [FILTER_OPERATIONS.is, true],- [FILTER_OPERATIONS.isNot, supportsIsNot(filterName)],- [- FILTER_OPERATIONS.has_not_done,- supportsHasDoneNot(filterName)- ],- [FILTER_OPERATIONS.contains, supportsContains(filterName)],- [- FILTER_OPERATIONS.contains_not,- supportsContains(filterName) && supportsIsNot(filterName)- ]- ]- .filter(([_operation, supported]) => supported)- .map(([operation]) => (- <button- data-testid="filter-operator-option"- key={operation}- data-selected={operation === props.selectedType}- onClick={(e) => {- // Prevent the click propagating and closing modal- e.preventDefault()- e.stopPropagation()- props.onSelect(operation)- closeDropdown()- }}- className={classNames(- 'w-full text-left ',- popover.items.classNames.navigationLink,- popover.items.classNames.selectedOption,- popover.items.classNames.hoverLink- )}- >- {FILTER_OPERATIONS_DISPLAY_NAMES[operation]}- </button>- ))}- </Popover.Panel>- </Transition>- </>- )}- </Popover>- </div>- )-}diff --git a/assets/js/dashboard/components/form-elements.tsx b/assets/js/dashboard/components/form-elements.tsxindex 7b4238792f..44c01a6aa1 100644--- a/assets/js/dashboard/components/form-elements.tsx+++ b/assets/js/dashboard/components/form-elements.tsx@@ -249,23 +249,47 @@ export const getOptionDisabledMessage = ({return null}-/** Keep this component styled the same as checkboxes in PlausibleWeb.Live.Installation.Instructions */+/**+ * The actual Tailwind classes live in `assets/css/app.css` (.checkbox-base,+ * .checkbox-{sm,md}).+ */+export type CheckboxSize = 'sm' | 'md'++const checkboxBaseClass = 'checkbox-base'++const checkboxSizes: Record<CheckboxSize, string> = {+ sm: 'checkbox-sm',+ md: 'checkbox-md'+}++export const checkboxClassName = ({+ size = 'md',+ className+}: {+ size?: CheckboxSize+ className?: string+} = {}): string => classNames(checkboxBaseClass, checkboxSizes[size], className)+export const Checkbox = ({id,checked,onChange,+ size = 'md',children-}: React.DetailedHTMLProps<- React.InputHTMLAttributes<HTMLInputElement>,- HTMLInputElement->) => {+}: Omit<+ React.DetailedHTMLProps<+ React.InputHTMLAttributes<HTMLInputElement>,+ HTMLInputElement+ >,+ 'size'+> & { size?: CheckboxSize }) => {return (<labelclassName="text-sm block font-medium dark:text-gray-100 font-normal gap-x-2 flex flex-inline items-center justify-start"htmlFor={id}><input- className="block size-5 rounded-sm dark:bg-gray-600 border-gray-300 dark:border-gray-600 text-indigo-600"+ className={checkboxClassName({ size })}id={id}type="checkbox"checked={checked}diff --git a/assets/js/dashboard/components/notice.tsx b/assets/js/dashboard/components/notice.tsxindex cf4c221d7c..ec44f8f40f 100644--- a/assets/js/dashboard/components/notice.tsx+++ b/assets/js/dashboard/components/notice.tsx@@ -4,13 +4,25 @@ import classNames from 'classnames'export type NoticeProps = {title: stringdescription?: string+ theme?: 'yellow' | 'red'className?: string}-export const Notice = ({ title, description, className }: NoticeProps) => (+const themeClassNames: Record<NonNullable<NoticeProps['theme']>, string> = {+ yellow: 'bg-yellow-100/60 dark:bg-yellow-700/30',+ red: 'bg-red-100 dark:bg-red-700/30'+}++export const Notice = ({+ title,+ description,+ theme = 'yellow',+ className+}: NoticeProps) => (<divclassName={classNames(- 'flex flex-col gap-y-0.5 rounded-md bg-yellow-100/60 dark:bg-yellow-700/30 px-3 py-2.5',+ 'flex flex-col gap-y-0.5 rounded-md px-3 py-2.5',+ themeClassNames[theme],className)}>diff --git a/assets/js/dashboard/components/popover.tsx b/assets/js/dashboard/components/popover.tsxindex 08629c9662..c03bafc99e 100644--- a/assets/js/dashboard/components/popover.tsx+++ b/assets/js/dashboard/components/popover.tsx@@ -39,7 +39,7 @@ const toggleButton = {outline:'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-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',+ 'gap-x-1.5 px-2.5 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'@@ -85,7 +85,10 @@ const items = {'data-[selected=true]:dark:bg-gray-700','data-[selected=true]:text-gray-900','data-[selected=true]:dark:text-gray-100'- )+ ),+ /** For options that are highlighted by keyboard, not by hover or focus. */+ highlightedOption:+ 'bg-gray-100 text-gray-900 dark:bg-gray-700 dark:text-gray-100'}}diff --git a/assets/js/dashboard/components/search-input.tsx b/assets/js/dashboard/components/search-input.tsxindex 7992089aad..1cc90be9e5 100644--- a/assets/js/dashboard/components/search-input.tsx+++ b/assets/js/dashboard/components/search-input.tsx@@ -1,5 +1,7 @@import React, {ChangeEventHandler,+ InputHTMLAttributes,+ ReactNode,useCallback,useState,RefObject@@ -11,18 +13,38 @@ import classNames from 'classnames'export const SearchInput = ({searchRef,onSearch,+ value,+ onChange,+ inputProps,+ trailing,className,placeholderFocusedOrMobile = 'Search',placeholderUnfocusedOnlyDesktop = 'Press / to search'}: {searchRef: RefObject<HTMLInputElement>+ /** Called with a debounce */onSearch: (value: string) => void+ value?: string+ /** Called at once on every change */+ onChange?: (value: string) => void+ inputProps?: Omit<+ InputHTMLAttributes<HTMLInputElement>,+ | 'value'+ | 'onChange'+ | 'onFocus'+ | 'onBlur'+ | 'type'+ | 'placeholder'+ | 'className'+ >+ trailing?: ReactNodeclassName?: stringplaceholderFocusedOrMobile?: stringplaceholderUnfocusedOnlyDesktop?: string}) => {const [isFocused, setIsFocused] = useState(false)- const [hasValue, setHasValue] = useState(false)+ const [uncontrolledHasValue, setUncontrolledHasValue] = useState(false)+ const hasValue = value === undefined ? uncontrolledHasValue : value !== ''const onSearchInputChange: ChangeEventHandler<HTMLInputElement> = useCallback((event) => {@@ -35,10 +57,11 @@ export const SearchInput = ({const handleInputChange: ChangeEventHandler<HTMLInputElement> = useCallback((event) => {const value = event.target.value- setHasValue(value.length > 0)+ setUncontrolledHasValue(value.length > 0)+ onChange?.(value)debouncedOnSearchInputChange(event)},- [debouncedOnSearchInputChange]+ [onChange, debouncedOnSearchInputChange])const blurSearchBox = useCallback(() => {@@ -69,15 +92,22 @@ export const SearchInput = ({shouldIgnoreWhen={[isModifierPressed, () => isFocused]}targetRef="document"/>- <div className={classNames('relative max-w-64 w-full', className)}>+ <div+ className={classNames(+ 'relative flex items-center max-w-64 w-full rounded-md border border-gray-300 dark:border-gray-750 bg-white dark:bg-gray-750 focus-within:border-indigo-500 focus-within:ring-3 focus-within:ring-indigo-500/20 dark:focus-within:ring-indigo-500/25',+ className+ )}+ ><inputdata-testid="search-input"+ {...inputProps}onBlur={() => setIsFocused(false)}onFocus={() => setIsFocused(true)}ref={searchRef}type="text"placeholder=" "- className="peer w-full text-sm dark:text-gray-100 block border-gray-300 dark:border-gray-750 rounded-md dark:bg-gray-750 dark:placeholder:text-gray-400 focus:outline-none focus:ring-3 focus:ring-indigo-500/20 dark:focus:ring-indigo-500/25 focus:border-indigo-500"+ className="peer flex-1 min-w-0 border-none bg-transparent px-3 py-1.5 text-sm dark:text-gray-100 focus:outline-none focus:ring-0"+ value={value}onChange={handleInputChange}/>{!hasValue && (@@ -90,6 +120,7 @@ export const SearchInput = ({</span></>)}+ {trailing && <div className="flex shrink-0 pr-3">{trailing}</div>}</div></>)diff --git a/assets/js/dashboard/components/tabs.tsx b/assets/js/dashboard/components/tabs.tsxindex f3c71152ec..ce56ab0219 100644--- a/assets/js/dashboard/components/tabs.tsx+++ b/assets/js/dashboard/components/tabs.tsx@@ -32,11 +32,14 @@ const TabButtonText = ({active: boolean}) => (<span- className={classNames('truncate text-left text-xs uppercase', {- 'text-gray-500 dark:text-gray-400 group-hover/tab:text-gray-800 dark:group-hover/tab:text-gray-200 font-semibold cursor-pointer':- !active,- 'text-gray-900 dark:text-gray-100 font-bold tracking-[-.01em]': active- })}+ className={classNames(+ 'truncate text-left text-xs font-semibold uppercase',+ {+ 'text-gray-500 dark:text-gray-400 group-hover/tab:text-gray-800 dark:group-hover/tab:text-gray-200 cursor-pointer':+ !active,+ 'text-gray-900 dark:text-gray-100': active+ }+ )}><span data-active={active ? 'true' : 'false'} data-testid="tab-button">{children}diff --git a/assets/js/dashboard/filtering/filter-editor-context.test.tsx b/assets/js/dashboard/filtering/filter-editor-context.test.tsxnew file mode 100644index 0000000000..5b09c0edc2--- /dev/null+++ b/assets/js/dashboard/filtering/filter-editor-context.test.tsx@@ -0,0 +1,153 @@+import React, { ReactNode } from 'react'+import { act, renderHook } from '@testing-library/react'+import { useNavigate } from 'react-router-dom'+import { TestContextProviders } from '../../../test-utils/app-context-providers'+import { useDashboardStateContext } from '../dashboard-state-context'+import { Filter } from '../dashboard-state'+import { getRouterBasepath } from '../router'+import { stringifySearch } from '../util/url-search-params'+import {+ FilterEditorContextProvider,+ useFilterEditorContext+} from './filter-editor-context'++const domain = 'dummy.site'++const renderEditor = (filters: Filter[]) =>+ renderHook(+ () => ({+ editor: useFilterEditorContext(),+ urlFilters: useDashboardStateContext().dashboardState.filters,+ navigate: useNavigate()+ }),+ {+ wrapper: ({ children }: { children: ReactNode }) => (+ <TestContextProviders+ siteOptions={{ domain }}+ routerProps={{+ initialEntries: [+ {+ pathname: getRouterBasepath({ domain, shared: false }),+ search: stringifySearch({ filters })+ }+ ]+ }}+ >+ <FilterEditorContextProvider>{children}</FilterEditorContextProvider>+ </TestContextProviders>+ )+ }+ )++const page: Filter = ['is', 'page', ['/blog']]+const source: Filter = ['is', 'source', ['Google']]+const hostname: Filter = ['is', 'hostname', ['example.com']]++test('opening a pill while a new filter without values is open opens the correct filter', () => {+ const { result } = renderEditor([page, source])++ act(() => result.current.editor.add('hostname'))+ expect(result.current.editor.renderedFilters).toEqual([+ ['is', 'hostname', []],+ page,+ source+ ])++ act(() => result.current.editor.open(2, 'values'))+ expect(result.current.editor.renderedFilters).toEqual([page, source])+ expect(result.current.editor.openPosition).toBe(1)+})++test('removing a pill while an emptied filter is open removes the correct filter', () => {+ const { result } = renderEditor([page, source, hostname])++ act(() => result.current.editor.open(0, 'values'))+ act(() => result.current.editor.update(['is', 'page', []]))+ act(() => result.current.editor.remove(2))++ expect(result.current.urlFilters).toEqual([source])+ expect(result.current.editor.openPosition).toBeNull()+})++test('removing the last value removes the filter from the URL at once and keeps the pill open', () => {+ const { result } = renderEditor([page, source])++ act(() => result.current.editor.open(0, 'values'))+ act(() => result.current.editor.update(['is', 'page', []]))+ expect(result.current.urlFilters).toEqual([source])+ expect(result.current.editor.renderedFilters).toEqual([+ ['is', 'page', []],+ source+ ])+ expect(result.current.editor.openPosition).toBe(0)++ act(() => result.current.editor.update(page))+ expect(result.current.urlFilters).toEqual([page, source])+})++test('the editor closes when the browser goes back to the filter before its values were removed', () => {+ const { result } = renderEditor([page])++ act(() => result.current.editor.open(0, 'values'))+ act(() => result.current.editor.update(['is', 'page', []]))+ expect(result.current.urlFilters).toEqual([])++ act(() => result.current.navigate(-1))++ expect(result.current.urlFilters).toEqual([page])+ expect(result.current.editor.openPosition).toBeNull()+ expect(result.current.editor.renderedFilters).toEqual([page])+})++test('the editor closes when the browser goes back to before the new filter was added', () => {+ const { result } = renderEditor([page])++ act(() => result.current.editor.add('hostname'))+ act(() => result.current.editor.update(hostname))+ expect(result.current.urlFilters).toEqual([hostname, page])++ act(() => result.current.navigate(-1))++ expect(result.current.urlFilters).toEqual([page])+ expect(result.current.editor.openPosition).toBeNull()+ expect(result.current.editor.renderedFilters).toEqual([page])+})++test('the editor closes when the browser goes back to before a value was added', () => {+ const { result } = renderEditor([page])++ act(() => result.current.editor.open(0, 'values'))+ act(() => result.current.editor.update(['is', 'page', ['/blog', '/docs']]))+ act(() => result.current.navigate(-1))++ expect(result.current.urlFilters).toEqual([page])+ expect(result.current.editor.openPosition).toBeNull()+ expect(result.current.editor.renderedFilters).toEqual([page])+})++test('a change after the browser goes back adds a new history entry', () => {+ const { result } = renderEditor([page])++ act(() => result.current.editor.open(0, 'values'))+ act(() => result.current.editor.update(['is', 'page', ['/blog', '/docs']]))+ act(() => result.current.navigate(-1))+ act(() => result.current.editor.open(0, 'values'))+ act(() => result.current.editor.update(['is', 'page', ['/blog', '/about']]))+ act(() => result.current.navigate(-1))++ expect(result.current.urlFilters).toEqual([page])+})++test('an open pill shows the new URL filter when the URL changes', () => {+ const { result } = renderEditor([page])+ const otherPage: Filter = ['is', 'page', ['/docs']]++ act(() => result.current.editor.open(0, 'values'))+ act(() =>+ result.current.navigate({+ search: stringifySearch({ filters: [otherPage] })+ })+ )++ expect(result.current.editor.renderedFilters).toEqual([otherPage])+})diff --git a/assets/js/dashboard/filtering/filter-editor-context.tsx b/assets/js/dashboard/filtering/filter-editor-context.tsxnew file mode 100644index 0000000000..d275f88d2c--- /dev/null+++ b/assets/js/dashboard/filtering/filter-editor-context.tsx@@ -0,0 +1,271 @@+import React, {+ createContext,+ ReactNode,+ useCallback,+ useContext,+ useEffect,+ useMemo,+ useRef,+ useState+} from 'react'+import {+ NavigationType,+ useLocation,+ useNavigationType+} from 'react-router-dom'+import { useDashboardStateContext } from '../dashboard-state-context'+import { useAppNavigate } from '../navigation/use-app-navigate'+import { Filter, FilterClauseLabels } from '../dashboard-state'+import { cleanLabels, FILTER_OPERATIONS } from '../util/filters'+import { isSegmentFilter } from './segments'++export type FilterEditorPart = 'operator' | 'values'++/**+ * `position` is the index of the pill in `renderedFilters`.+ * Filters without values are not written to the URL: a new filter only+ * appears there when it gets its first value, and a filter is removed from+ * the URL when its last value is removed. While a filter has no values, it+ * is kept as `draft`, so the pill stays until the editor closes.+ */+type EditingFilter = {+ position: number+ part: FilterEditorPart+ draft: Filter | null+ hasPushedHistoryEntry: boolean+}++type FilterEditorContextValue = {+ renderedFilters: Filter[]+ openPosition: number | null+ openPart: FilterEditorPart | null+ open: (position: number, part: FilterEditorPart) => void+ close: () => void+ update: (filter: Filter, labels?: FilterClauseLabels) => void+ remove: (position: number) => void+ add: (filterKey: string) => void+}++const FilterEditorContext = createContext<FilterEditorContextValue | null>(null)++export const useFilterEditorContext = () => {+ const context = useContext(FilterEditorContext)+ if (!context) {+ throw new Error(+ 'useFilterEditorContext must be used within FilterEditorContextProvider'+ )+ }+ return context+}++const insertAt = (filters: Filter[], index: number, filter: Filter) => [+ ...filters.slice(0, index),+ filter,+ ...filters.slice(index)+]++const replaceAt = (filters: Filter[], index: number, filter: Filter) =>+ filters.map((f, i) => (i === index ? filter : f))++const removeAt = (filters: Filter[], index: number) =>+ filters.filter((_, i) => i !== index)++const hasValues = ([_operation, _key, clauses]: Filter) => clauses.length > 0++const canHaveMultipleFilters = (filterKey: string) => filterKey === 'goal'++const getNewFilterPosition = (filters: Filter[]) =>+ filters.length && isSegmentFilter(filters[0]) ? 1 : 0++const getUrlIndex = (editing: EditingFilter | null, position: number) =>+ editing?.draft && editing.position < position ? position - 1 : position++export const FilterEditorContextProvider = ({+ children+}: {+ children: ReactNode+}) => {+ const { dashboardState } = useDashboardStateContext()+ const navigate = useAppNavigate()+ const location = useLocation()+ const navigationType = useNavigationType()+ const [editing, setEditingState] = useState<EditingFilter | null>(null)+ const editingRef = useRef<EditingFilter | null>(null)++ const setEditing = useCallback((next: EditingFilter | null) => {+ editingRef.current = next+ setEditingState(next)+ }, [])++ const navigateToFilters = useCallback(+ (+ filters: Filter[],+ {+ replace,+ mergedKey,+ mergedLabels+ }: {+ replace: boolean+ mergedKey?: string+ mergedLabels?: FilterClauseLabels+ }+ ) =>+ navigate({+ search: (search) => ({+ ...search,+ filters,+ labels: cleanLabels(+ filters,+ dashboardState.labels,+ mergedKey,+ mergedLabels+ )+ }),+ replace+ }),+ [navigate, dashboardState.labels]+ )++ /** Closes the editor and returns the URL filters */+ const close = useCallback((): Filter[] => {+ setEditing(null)+ return dashboardState.filters+ }, [setEditing, dashboardState.filters])++ const open = useCallback(+ (position: number, part: FilterEditorPart) => {+ const current = editingRef.current+ if (current?.position === position) {+ setEditing({ ...current, part })+ return+ }+ const index = getUrlIndex(current, position)+ if (close()[index]) {+ setEditing({+ position: index,+ part,+ draft: null,+ hasPushedHistoryEntry: false+ })+ }+ },+ [setEditing, close]+ )++ const update = useCallback(+ (filter: Filter, labels?: FilterClauseLabels) => {+ const current = editingRef.current+ if (!current) {+ return+ }+ if (!hasValues(filter)) {+ if (!current.draft) {+ navigateToFilters(+ removeAt(dashboardState.filters, current.position),+ {+ replace: current.hasPushedHistoryEntry+ }+ )+ }+ setEditing({+ ...current,+ draft: filter,+ hasPushedHistoryEntry: current.hasPushedHistoryEntry || !current.draft+ })+ return+ }+ const filters = current.draft+ ? insertAt(dashboardState.filters, current.position, filter)+ : replaceAt(dashboardState.filters, current.position, filter)+ navigateToFilters(filters, {+ replace: current.hasPushedHistoryEntry,+ mergedKey: filter[1],+ mergedLabels: labels+ })+ setEditing({+ ...current,+ draft: null,+ hasPushedHistoryEntry: true+ })+ },+ [setEditing, dashboardState.filters, navigateToFilters]+ )++ const remove = useCallback(+ (position: number) => {+ const current = editingRef.current+ if (current?.position === position) {+ setEditing(null)+ if (!current.draft) {+ navigateToFilters(removeAt(dashboardState.filters, position), {+ replace: current.hasPushedHistoryEntry+ })+ }+ return+ }+ const index = getUrlIndex(current, position)+ navigateToFilters(removeAt(close(), index), { replace: false })+ },+ [setEditing, close, dashboardState.filters, navigateToFilters]+ )++ const add = useCallback(+ (filterKey: string) => {+ const filters = close()+ const existingIndex = canHaveMultipleFilters(filterKey)+ ? -1+ : filters.findIndex(([_operation, key]) => key === filterKey)+ if (existingIndex >= 0) {+ setEditing({+ position: existingIndex,+ part: 'values',+ draft: null,+ hasPushedHistoryEntry: false+ })+ return+ }+ setEditing({+ position: getNewFilterPosition(filters),+ part: 'values',+ draft: [FILTER_OPERATIONS.is, filterKey, []],+ hasPushedHistoryEntry: false+ })+ },+ [setEditing, close]+ )++ // the open editor belongs to one history entry, so back and forward close it+ useEffect(() => {+ if (navigationType === NavigationType.Pop) {+ setEditing(null)+ }+ }, [setEditing, location.key, navigationType])++ const renderedFilters = useMemo(+ () =>+ editing?.draft+ ? insertAt(dashboardState.filters, editing.position, editing.draft)+ : dashboardState.filters,+ [dashboardState.filters, editing]+ )++ const value = useMemo(+ () => ({+ renderedFilters,+ openPosition: editing?.position ?? null,+ openPart: editing?.part ?? null,+ open,+ close,+ update,+ remove,+ add+ }),+ [renderedFilters, editing, open, close, update, remove, add]+ )++ return (+ <FilterEditorContext.Provider value={value}>+ {children}+ </FilterEditorContext.Provider>+ )+}diff --git a/assets/js/dashboard/nav-menu/filter-menu-rows.tsx b/assets/js/dashboard/nav-menu/filter-menu-rows.tsxindex 83fbca50ee..9ce6e33f1b 100644--- a/assets/js/dashboard/nav-menu/filter-menu-rows.tsx+++ b/assets/js/dashboard/nav-menu/filter-menu-rows.tsx@@ -25,6 +25,7 @@ export type FilterDimension = keyof typeof formattedFiltersexport type FilterMenuRow =| { kind: 'segments'; key: 'segment'; label: string; Icon: IconComponent }+ | { kind: 'properties'; key: 'props'; label: string; Icon: IconComponent }| {kind: 'item'key: FilterGroupKey@@ -71,7 +72,11 @@ export function getFilterMenuRows({.filter((key) => key !== SEGMENTS_ROW.key && (key !== 'props' || propsAvailable))- .map((key) => {+ .map((key): FilterMenuRow => {+ if (key === 'props') {+ return { kind: 'properties', key, ...GROUPS[key] }+ }+const dimensions = FILTER_GROUP_TO_DIMENSIONS[key] as FilterDimension[]return dimensions.length > 1diff --git a/assets/js/dashboard/nav-menu/filter-menu.tsx b/assets/js/dashboard/nav-menu/filter-menu.tsxindex d72a486db1..d8f375db4b 100644--- a/assets/js/dashboard/nav-menu/filter-menu.tsx+++ b/assets/js/dashboard/nav-menu/filter-menu.tsx@@ -1,14 +1,14 @@import React, { useMemo, useRef } from 'react'-import { formattedFilters } from '../util/filters'+import { EVENT_PROPS_PREFIX, formattedFilters } from '../util/filters'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'+import { useFilterEditorContext } from '../filtering/filter-editor-context'+import { PropertyKeyPicker } from './property-key-picker'import {SegmentsSubmenu,useListableSegments@@ -185,20 +185,24 @@ const ItemRow = ({row: Extract<FilterMenuRow, { kind: 'item' }>onPointerOrFocus: () => voidcloseDropdown: () => void-}) => (- <AppNavigationLink- className={popover.items.classNames.iconRow}- onClick={closeDropdown}- onMouseEnter={onPointerOrFocus}- onFocus={onPointerOrFocus}- path={filterRoute.path}- params={{ field: row.dimension }}- search={(s) => s}- >- <row.Icon className={iconClassName} />- <span className={popover.items.classNames.label}>{row.label}</span>- </AppNavigationLink>-)+}) => {+ const { add } = useFilterEditorContext()+ return (+ <button+ type="button"+ className={popover.items.classNames.iconRow}+ onClick={() => {+ closeDropdown()+ add(row.dimension)+ }}+ onMouseEnter={onPointerOrFocus}+ onFocus={onPointerOrFocus}+ >+ <row.Icon className={iconClassName} />+ <span className={popover.items.classNames.label}>{row.label}</span>+ </button>+ )+}const SubmenuBody = ({row,@@ -207,24 +211,36 @@ const SubmenuBody = ({row: FilterSubmenuRowcloseDropdown: () => void}) => {+ const { add } = useFilterEditorContext()if (row.kind === 'segments') {return <SegmentsSubmenu closeList={closeDropdown} />}+ if (row.kind === 'properties') {+ return (+ <PropertyKeyPicker+ onSelect={(propKey) => {+ closeDropdown()+ add(`${EVENT_PROPS_PREFIX}${propKey}`)+ }}+ />+ )+ }return (<>{row.dimensions.map((dimension) => (- <AppNavigationLink+ <buttonkey={dimension}+ type="button"className={popover.items.classNames.iconRow}- onClick={closeDropdown}- path={filterRoute.path}- params={{ field: dimension }}- search={(s) => s}+ onClick={() => {+ closeDropdown()+ add(dimension)+ }}><span className={popover.items.classNames.label}>{formattedFilters[dimension]}</span>- </AppNavigationLink>+ </button>))}</>)diff --git a/assets/js/dashboard/nav-menu/filter-operator-list.tsx b/assets/js/dashboard/nav-menu/filter-operator-list.tsxnew file mode 100644index 0000000000..973e700801--- /dev/null+++ b/assets/js/dashboard/nav-menu/filter-operator-list.tsx@@ -0,0 +1,67 @@+import React, { useEffect, useRef } from 'react'+import classNames from 'classnames'+import { Filter, FilterOperator } from '../dashboard-state'+import {+ FILTER_OPERATIONS_DISPLAY_NAMES,+ getSupportedOperations+} from '../util/filters'+import { popover, SelectedCheckmark } from '../components/popover'++export const FilterOperatorList = ({+ filter,+ onSelect+}: {+ filter: Filter+ onSelect: (operation: FilterOperator) => void+}) => {+ const [selectedOperation, filterKey] = filter+ const listRef = useRef<HTMLDivElement>(null)+ const operations: FilterOperator[] = getSupportedOperations(filterKey)++ useEffect(() => {+ listRef.current+ ?.querySelector<HTMLButtonElement>('[data-selected="true"]')+ ?.focus({ preventScroll: true })+ }, [])++ const onKeyDown = (event: React.KeyboardEvent) => {+ if (!['ArrowDown', 'ArrowUp'].includes(event.key)) {+ return+ }+ event.preventDefault()+ const buttons = Array.from(+ listRef.current?.querySelectorAll('button') ?? []+ )+ const index = buttons.findIndex((b) => b === document.activeElement)+ const step = event.key === 'ArrowDown' ? 1 : -1+ buttons[(index + step + buttons.length) % buttons.length]?.focus()+ }++ return (+ <div+ ref={listRef}+ role="group"+ aria-label="Operators"+ className="flex flex-col gap-y-0.5"+ >+ {operations.map((operation) => (+ <button+ key={operation}+ type="button"+ data-selected={operation === selectedOperation}+ className={classNames(+ 'w-full text-left',+ popover.items.classNames.navigationLink,+ popover.items.classNames.selectedOption,+ popover.items.classNames.hoverLink+ )}+ onClick={() => onSelect(operation)}+ onKeyDown={onKeyDown}+ >+ {FILTER_OPERATIONS_DISPLAY_NAMES[operation]}+ <SelectedCheckmark selected={operation === selectedOperation} />+ </button>+ ))}+ </div>+ )+}diff --git a/assets/js/dashboard/nav-menu/filter-pill-popover.tsx b/assets/js/dashboard/nav-menu/filter-pill-popover.tsxnew file mode 100644index 0000000000..c3f1ba4406--- /dev/null+++ b/assets/js/dashboard/nav-menu/filter-pill-popover.tsx@@ -0,0 +1,102 @@+import React, { ReactNode, useEffect, useState } from 'react'+import { createPortal } from 'react-dom'+import { Transition } from '@headlessui/react'+import { usePopper } from 'react-popper'+import classNames from 'classnames'+import { popover } from '../components/popover'++/**+ * Headless UI popovers can't be opened from code, which the filter editor+ * needs when a filter is added from the filter menu.+ */+export const FilterPillPopover = ({+ anchorElement,+ containerElement,+ onClose,+ className,+ children+}: {+ anchorElement: HTMLElement | null+ /** Pointer and focus events inside this element don't close the popover */+ containerElement: HTMLElement | null+ onClose: (options: { refocus: boolean }) => void+ className?: string+ children: ReactNode+}) => {+ const [panelElement, setPanelElement] = useState<HTMLDivElement | null>(null)++ const { styles, attributes } = usePopper(anchorElement, panelElement, {+ placement: 'bottom-start',+ modifiers: [+ { name: 'offset', options: { offset: [-1, 8] } },+ { name: 'preventOverflow', options: { padding: 8 } }+ ]+ })++ useEffect(() => {+ anchorElement?.scrollIntoView?.({ block: 'nearest', inline: 'nearest' })+ }, [anchorElement])++ useEffect(() => {+ const isInside = (target: EventTarget | null) =>+ target instanceof Node &&+ (!!panelElement?.contains(target) || !!containerElement?.contains(target))++ const onPointerDown = (event: PointerEvent) => {+ if (!isInside(event.target)) {+ onClose({ refocus: false })+ }+ }+ const onFocusIn = (event: FocusEvent) => {+ if (!isInside(event.target)) {+ onClose({ refocus: false })+ }+ }+ document.addEventListener('pointerdown', onPointerDown)+ document.addEventListener('focusin', onFocusIn)+ return () => {+ document.removeEventListener('pointerdown', onPointerDown)+ document.removeEventListener('focusin', onFocusIn)+ }+ }, [panelElement, containerElement, onClose])++ return createPortal(+ <div+ ref={setPanelElement}+ style={styles.popper}+ {...attributes.popper}+ className="z-20"+ onKeyDown={(event) => {+ if (event.key === 'Escape') {+ event.stopPropagation()+ }+ }}+ // the dashboard clears all filters on Escape keyup+ onKeyUp={(event) => {+ if (event.key === 'Escape') {+ event.stopPropagation()+ onClose({ refocus: true })+ }+ }}+ >+ <Transition+ as="div"+ appear+ show+ {...popover.transition.props}+ className="origin-top-left"+ >+ <div+ className={classNames(+ popover.panel.classNames.roundedSheet,+ 'max-w-[calc(100vw-1rem)]',+ className+ )}+ >+ {children}+ </div>+ </Transition>+ </div>,+ document.body+ )+}diff --git a/assets/js/dashboard/nav-menu/filter-pill.tsx b/assets/js/dashboard/nav-menu/filter-pill.tsxindex 73a361c4c2..0a6a977e06 100644--- a/assets/js/dashboard/nav-menu/filter-pill.tsx+++ b/assets/js/dashboard/nav-menu/filter-pill.tsx@@ -8,35 +8,73 @@ import React, {import { createPortal } from 'react-dom'import { Popover, Transition } from '@headlessui/react'import { usePopper } from 'react-popper'-import {- AppNavigationLink,- AppNavigationTarget-} from '../navigation/use-app-navigate'import { XMarkIcon } from '@heroicons/react/24/outline'import classNames from 'classnames'import { BlurMenuButtonOnEscape, popover } from '../components/popover'+import { Filter, FilterClauseLabels, FilterOperator } from '../dashboard-state'+import {+ EVENT_PROPS_PREFIX,+ getPropertyKeyFromFilterKey,+ getSupportedOperations+} from '../util/filters'+import { getFilterTextParts, plainFilterText } from '../util/filter-text'+import {+ useFilterEditorContext,+ FilterEditorPart+} from '../filtering/filter-editor-context'+import { FilterPillPopover } from './filter-pill-popover'+import { FilterOperatorList } from './filter-operator-list'+import { FilterValuePicker } from './filter-value-picker'type RenderMenu = (closeMenu: () => void) => ReactNodeexport type FilterPillAction =- | { type: 'link'; navigationTarget: AppNavigationTarget }+ | { type: 'edit' }| { type: 'menu'; renderMenu: RenderMenu }export type FilterPillProps = {- plainText: string+ position: number+ filter: Filter+ labels: FilterClauseLabelsaction?: FilterPillAction+ error?: stringonRemoveClick?: () => void- children: ReactNode}-const PillContent = ({ children }: { children?: ReactNode }) => (- <span className="inline-block max-w-2xs md:max-w-xs truncate">- {children}- </span>+const partClassName = 'flex items-center h-full px-2 whitespace-nowrap'++const buttonPartClassName = classNames(+ partClassName,+ 'cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-750 aria-expanded:bg-gray-100 dark:aria-expanded:bg-gray-750')-const contentBaseClassName =- 'flex w-full h-full items-center rounded-l-md pl-2.5'+const PillValues = ({+ values,+ error+}: {+ values: string[]+ error?: string+}) => (+ <span+ className={classNames(+ 'inline-block max-w-2xs md:max-w-xs truncate',+ !!error && 'text-red-600 dark:text-red-400'+ )}+ >+ {values.length ? (+ values.map((value, index) => (+ <React.Fragment key={index}>+ {index > 0 && (+ <span className="text-gray-500 dark:text-gray-400"> or </span>+ )}+ {value}+ </React.Fragment>+ ))+ ) : (+ <span className="text-gray-500 dark:text-gray-400">Select...</span>+ )}+ </span>+)const PillMenuPanel = ({open,@@ -96,12 +134,12 @@ const PillMenuPanel = ({const PillMenu = ({className,- plainText,+ label,renderMenu,children}: {className: string- plainText: string+ label: stringrenderMenu: RenderMenuchildren: ReactNode}) => {@@ -122,10 +160,10 @@ const PillMenu = ({<BlurMenuButtonOnEscape targetRef={buttonRef} /><Popover.Buttonref={setButton}- className={classNames(className, 'cursor-pointer relative')}- title={plainText}+ className={classNames(className, 'relative')}+ aria-label={label}>- <PillContent>{children}</PillContent>+ {children}</Popover.Button><PillMenuPanel open={open} buttonElement={buttonElement}>{renderMenu(close)}@@ -137,48 +175,149 @@ const PillMenu = ({}export function FilterPill({- plainText,- children,- onRemoveClick,- action+ position,+ filter,+ labels,+ action,+ error,+ onRemoveClick}: FilterPillProps) {- const contentClassName = classNames(- contentBaseClassName,- !onRemoveClick && 'rounded-r-md pr-2.5'+ const editor = useFilterEditorContext()+ const [containerElement, setContainerElement] =+ useState<HTMLDivElement | null>(null)+ const [operatorButton, setOperatorButton] =+ useState<HTMLButtonElement | null>(null)+ const [valuesButton, setValuesButton] = useState<HTMLButtonElement | null>(+ null+ )++ const { dimension, operation, values } = getFilterTextParts(+ { labels },+ filter)+ const plainText = plainFilterText({ labels }, filter)+ const dimensionLabel = filter[1].startsWith(EVENT_PROPS_PREFIX)+ ? getPropertyKeyFromFilterKey(filter[1])+ : dimension+ const canChangeOperation =+ action?.type === 'edit' && getSupportedOperations(filter[1]).length > 1+ const openPart = editor.openPosition === position ? editor.openPart : null++ const toggle = (part: FilterEditorPart) =>+ openPart === part ? editor.close() : editor.open(position, part)++ const closeEditor = useCallback(+ ({ refocus }: { refocus: boolean }) => {+ const anchor =+ editor.openPart === 'operator' ? operatorButton : valuesButton+ editor.close()+ if (refocus) {+ anchor?.focus()+ }+ },+ [editor, operatorButton, valuesButton]+ )++ const onOperationSelect = (newOperation: FilterOperator) => {+ const [_operation, filterKey, clauses] = filter+ editor.update([newOperation, filterKey, clauses])+ if (clauses.length) {+ editor.close()+ operatorButton?.focus()+ } else {+ editor.open(position, 'values')+ }+ }++ const roundedRight = !onRemoveClick && 'rounded-r-md'return (- <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?.type === 'link' ? (- <AppNavigationLink- className={contentClassName}- title={`Edit filter: ${plainText}`}- {...action.navigationTarget}+ <div+ ref={setContainerElement}+ role="group"+ aria-label={plainText}+ className="flex h-8 shrink-0 items-center 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 divide-x divide-gray-200 dark:divide-gray-700"+ >+ <span className={classNames(partClassName, 'rounded-l-md')}>+ {dimensionLabel}+ </span>+ {canChangeOperation ? (+ <button+ ref={setOperatorButton}+ type="button"+ className={buttonPartClassName}+ aria-label={`Change operator: ${plainText}`}+ aria-expanded={openPart === 'operator'}+ onClick={() => toggle('operator')}>- <PillContent>{children}</PillContent>- </AppNavigationLink>+ {operation}+ </button>+ ) : (+ <span className={partClassName}>{operation}</span>+ )}+ {action?.type === 'edit' ? (+ <button+ ref={setValuesButton}+ type="button"+ className={classNames(buttonPartClassName, roundedRight)}+ title={plainText}+ aria-label={`Edit filter: ${plainText}`}+ aria-expanded={openPart === 'values'}+ onClick={() => toggle('values')}+ >+ <PillValues values={values} />+ </button>) : action?.type === 'menu' ? (<PillMenu- className={contentClassName}- plainText={plainText}+ className={classNames(buttonPartClassName, roundedRight)}+ label={`Open menu: ${plainText}${error ? ` (${error})` : ''}`}renderMenu={action.renderMenu}>- {children}+ <PillValues values={values} error={error} /></PillMenu>) : (- <div className={contentClassName} title={plainText}>- <PillContent>{children}</PillContent>- </div>+ <span+ className={classNames(partClassName, roundedRight)}+ title={plainText}+ >+ <PillValues values={values} />+ </span>)}{!!onRemoveClick && (<button+ type="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 "+ className="w-7.5 flex items-center justify-center h-full rounded-r-md cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-750"onClick={onRemoveClick}><XMarkIcon className="size-4" /></button>)}+ {openPart === 'operator' && (+ <FilterPillPopover+ anchorElement={operatorButton}+ containerElement={containerElement}+ onClose={closeEditor}+ className="w-44"+ >+ <FilterOperatorList filter={filter} onSelect={onOperationSelect} />+ </FilterPillPopover>+ )}+ {openPart === 'values' && (+ <FilterPillPopover+ anchorElement={valuesButton}+ containerElement={containerElement}+ onClose={closeEditor}+ className="w-80 max-w-[calc(100vw-1rem)]"+ >+ <FilterValuePicker+ filter={filter}+ labels={labels}+ onChange={editor.update}+ onDone={() => closeEditor({ refocus: true })}+ />+ </FilterPillPopover>+ )}</div>)}diff --git a/assets/js/dashboard/nav-menu/filter-pills-list.tsx b/assets/js/dashboard/nav-menu/filter-pills-list.tsxindex af9ab65450..5009a445b0 100644--- a/assets/js/dashboard/nav-menu/filter-pills-list.tsx+++ b/assets/js/dashboard/nav-menu/filter-pills-list.tsx@@ -1,15 +1,26 @@import React, { CSSProperties } from 'react'import { useDashboardStateContext } from '../dashboard-state-context'import { FilterPill, FilterPillAction } 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'import classNames from 'classnames'-import { filterRoute } from '../router'import { canRemoveFilter, isSegmentFilter } from '../filtering/segments'import { useSegmentsContext } from '../filtering/segments-context'-import { SegmentPillMenu } from './segments/segment-pill-menu'+import {+ MissingSegmentPillMenu,+ SegmentPillMenu,+ SEGMENT_NOT_FOUND+} from './segments/segment-pill-menu'import { Filter } from '../dashboard-state'+import { useFilterEditorContext } from '../filtering/filter-editor-context'++// new filters are inserted before existing ones, so index keys would move+// the state of one pill to another+const getPillKeys = (filters: Filter[]) => {+ const counts: Record<string, number> = {}+ return filters.map(([_operation, key]) => {+ counts[key] = (counts[key] ?? 0) + 1+ return `${key}:${counts[key]}`+ })+}export const AppliedFilterPillsList = React.forwardRef<HTMLDivElement,@@ -17,33 +28,31 @@ export const AppliedFilterPillsList = React.forwardRef<>(({ className, style }, ref) => {const { dashboardState } = useDashboardStateContext()const { segments, limitedToSegment } = useSegmentsContext()- const navigate = useAppNavigate()+ const editor = useFilterEditorContext()+ const filters = editor.renderedFilters+ const keys = getPillKeys(filters)- const getPillAction = (filter: Filter): FilterPillAction | undefined => {+ const getPillProps = (+ filter: Filter+ ): { action: FilterPillAction; error?: string } => {if (!isSegmentFilter(filter)) {- return {- type: 'link',- navigationTarget: {- path: filterRoute.path,- search: (s) => s,- params: {- field: filter[1].startsWith(EVENT_PROPS_PREFIX)- ? 'props'- : filter[1]- }- }- }+ return { action: { type: 'edit' } }}const [_operation, _dimension, [id]] = filterconst segment = segments.find((s) => String(s.id) === String(id))if (!segment) {- return undefined+ return {+ action: { type: 'menu', renderMenu: () => <MissingSegmentPillMenu /> },+ error: SEGMENT_NOT_FOUND+ }}return {- type: 'menu',- renderMenu: (closeMenu) => (- <SegmentPillMenu segment={segment} closeMenu={closeMenu} />- )+ action: {+ type: 'menu',+ renderMenu: (closeMenu) => (+ <SegmentPillMenu segment={segment} closeMenu={closeMenu} />+ )+ }}}@@ -56,31 +65,19 @@ export const AppliedFilterPillsList = React.forwardRef<className={classNames('flex gap-x-1 p-1', className)}style={style}>- {dashboardState.filters.map((filter, index) => (+ {filters.map((filter, index) => (<FilterPill- key={index}- plainText={plainFilterText(dashboardState, filter)}- action={getPillAction(filter)}+ key={keys[index]}+ position={index}+ filter={filter}+ labels={dashboardState.labels}+ {...getPillProps(filter)}onRemoveClick={canRemoveFilter(filter, limitedToSegment)- ? () => {- const newFilters = dashboardState.filters.filter(- (_, i) => i !== index- )-- navigate({- search: (searchRecord) => ({- ...searchRecord,- filters: newFilters,- labels: cleanLabels(newFilters, dashboardState.labels)- })- })- }+ ? () => editor.remove(index): undefined}- >- {styledFilterText(dashboardState, filter)}- </FilterPill>+ />))}</div></div>diff --git a/assets/js/dashboard/nav-menu/filter-value-picker.tsx b/assets/js/dashboard/nav-menu/filter-value-picker.tsxnew file mode 100644index 0000000000..f87548ee8f--- /dev/null+++ b/assets/js/dashboard/nav-menu/filter-value-picker.tsx@@ -0,0 +1,93 @@+import React, { useState } from 'react'+import { useSiteContext } from '../site-context'+import { Filter, FilterClauseLabels } from '../dashboard-state'+import {+ EVENT_PROPS_PREFIX,+ getLabel,+ getPropertyKeyFromFilterKey,+ isFreeChoiceFilterOperation+} from '../util/filters'+import {+ getValueSuggestionsRequest,+ Suggestion+} from '../util/fetch-suggestions'+import { Combobox, ComboboxOption, isSameValue } from '../components/combobox'+import { Button } from '../components/button'+import { MenuSeparator } from './nav-menu-components'++export const FilterValuePicker = ({+ filter,+ labels,+ onChange,+ onDone+}: {+ filter: Filter+ labels: FilterClauseLabels+ onChange: (filter: Filter, labels?: FilterClauseLabels) => void+ onDone: () => void+}) => {+ const site = useSiteContext()+ const [operation, filterKey, clauses] = filter+ const [pinned, setPinned] = useState<Suggestion[]>(() =>+ clauses.map((value) => ({+ value,+ label: getLabel(labels, filterKey, value)+ }))+ )++ const isSelected = (option: Suggestion) =>+ clauses.some((value) => isSameValue(value, option.value))++ const onSelect = (option: ComboboxOption) => {+ if (isSelected(option)) {+ onChange([+ operation,+ filterKey,+ clauses.filter((value) => !isSameValue(value, option.value))+ ])+ return+ }+ if (option.freeChoice) {+ setPinned((current) => [+ ...current,+ { value: option.value, label: option.label }+ ])+ }+ onChange([operation, filterKey, [...clauses, option.value]], {+ [option.value]: option.label+ })+ }++ return (+ <>+ <Combobox+ request={getValueSuggestionsRequest(site, filter)}+ pinned={pinned}+ multiple+ freeChoice={isFreeChoiceFilterOperation(operation)}+ isSelected={isSelected}+ onSelect={onSelect}+ label={+ filterKey.startsWith(EVENT_PROPS_PREFIX)+ ? `Values for ${getPropertyKeyFromFilterKey(filterKey)}`+ : 'Values'+ }+ focusOnMount+ />+ <MenuSeparator />+ <div className="flex items-center gap-x-2 px-3 py-2">+ <Button size="xs" theme="secondary" onClick={onDone}>+ Done+ </Button>+ <Button+ size="xs"+ theme="ghost"+ disabled={!clauses.length}+ onClick={() => onChange([operation, filterKey, []])}+ >+ Deselect all+ </Button>+ </div>+ </>+ )+}diff --git a/assets/js/dashboard/nav-menu/filters-bar.test.tsx b/assets/js/dashboard/nav-menu/filters-bar.test.tsxindex 0794fe95d8..0e593613b8 100644--- a/assets/js/dashboard/nav-menu/filters-bar.test.tsx+++ b/assets/js/dashboard/nav-menu/filters-bar.test.tsx@@ -1,8 +1,10 @@import React, { ComponentProps } from 'react'-import { render, screen, within } from '../../../test-utils'+import { render, screen, waitFor, within } from '../../../test-utils'import userEvent from '@testing-library/user-event'import { TestContextProviders } from '../../../test-utils/app-context-providers'+import { MockAPI } from '../../../test-utils/mock-api'import { FiltersBar } from './filters-bar'+import { FilterEditorContextProvider } from '../filtering/filter-editor-context'import {formatSegmentIdAsLabelKey,SavedSegment,@@ -19,6 +21,41 @@ mockResizeObserver()const domain = 'dummy.site'+let mockAPI: MockAPI++beforeAll(() => {+ mockAPI = new MockAPI().start()+})++afterAll(() => {+ mockAPI.stop()+})++beforeEach(() => {+ mockAPI.clear()+})++const suggestionsPath = (filterName: string) =>+ `/api/stats/${domain}/suggestions/${filterName}/`++const mockSuggestions = (filterName: string, values: string[]) =>+ mockAPI.get(+ suggestionsPath(filterName),+ values.map((value) => ({ value, label: value }))+ )++const getOptions = () =>+ within(screen.getByRole('listbox')).queryAllByRole('option')++const getOptionStates = () =>+ getOptions().map((option) => [+ option.textContent,+ option.getAttribute('aria-selected')+ ])++const getOption = (name: string) =>+ within(screen.getByRole('listbox')).getByRole('option', { name })+type SegmentWithData = SavedSegment & { segment_data: SegmentData }const makeSegment = (@@ -45,6 +82,11 @@ const getSegmentFilterSearch = (segment: SegmentWithData) => ({labels: { [formatSegmentIdAsLabelKey(segment.id)]: segment.name }})+const getPillNames = () =>+ screen+ .queryAllByRole('group')+ .map((group) => group.getAttribute('aria-label'))+const renderFiltersBar = ({searchRecord,expandedSegment,@@ -54,24 +96,29 @@ const renderFiltersBar = ({searchRecord: Record<string, unknown>expandedSegment?: SegmentWithData} & Omit<ComponentProps<typeof TestContextProviders>, 'children'>) =>- render(<FiltersBar />, {- wrapper: (props) => (- <TestContextProviders- routerProps={{- initialEntries: [- {- pathname: getRouterBasepath({ domain, shared: false }),- search: stringifySearch(searchRecord),- state: expandedSegment ? { expandedSegment } : undefined- }- ]- }}- siteOptions={{ domain, ...siteOptions }}- {...providerProps}- {...props}- />- )- })+ render(+ <FilterEditorContextProvider>+ <FiltersBar />+ </FilterEditorContextProvider>,+ {+ wrapper: (props) => (+ <TestContextProviders+ routerProps={{+ initialEntries: [+ {+ pathname: getRouterBasepath({ domain, shared: false }),+ search: stringifySearch(searchRecord),+ state: expandedSegment ? { expandedSegment } : undefined+ }+ ]+ }}+ siteOptions={{ domain, ...siteOptions }}+ {...providerProps}+ {...props}+ />+ )+ }+ )test('user can see expected filters and clear them one by one or all together', async () => {renderFiltersBar({@@ -85,10 +132,7 @@ test('user can see expected filters and clear them one by one or all together',}})- const queryFilterPills = () =>- screen.queryAllByRole('link', { hidden: false, name: /.* is .*/i })-- expect(queryFilterPills().map((m) => m.textContent)).toEqual([+ expect(getPillNames()).toEqual(['Country is Germany','Goal is Subscribed to Newsletter','Page is /docs or /blog'@@ -101,7 +145,7 @@ test('user can see expected filters and clear them one by one or all together',}))- expect(queryFilterPills().map((m) => m.textContent)).toEqual([+ expect(getPillNames()).toEqual(['Goal is Subscribed to Newsletter','Page is /docs or /blog'])@@ -113,7 +157,7 @@ test('user can see expected filters and clear them one by one or all together',}))- expect(queryFilterPills().map((m) => m.textContent)).toEqual([])+ expect(getPillNames()).toEqual([])})test('action tooltips show the keybind and the docs link', async () => {@@ -170,7 +214,7 @@ test('the segment pill opens a menu with the segment details and actions', async).not.toBeInTheDocument()await userEvent.click(- screen.getByRole('button', { name: 'Segment is Mac users' })+ screen.getByRole('button', { name: 'Open menu: Segment is Mac users' }))expect(screen.getByText('Created on 13 Mar by Jane Smith')).toBeVisible()@@ -199,9 +243,7 @@ test('the segment pill opens a menu with the segment details and actions', asyncawait userEvent.click(screen.getByRole('link', { name: 'Edit segment' }))expect(screen.getByRole('button', { name: 'Save' })).toBeVisible()- expect(- screen.getByRole('link', { hidden: false, name: 'Page is /blog' })- ).toBeVisible()+ expect(screen.getByRole('group', { name: 'Page is /blog' })).toBeVisible()})const loggedInUser = (role: Role): UserContextValue => ({@@ -256,7 +298,7 @@ describe('segment pill menu actions depend on the user', () => {})await userEvent.click(- screen.getByRole('button', { name: 'Segment is Mac users' })+ screen.getByRole('button', { name: 'Open menu: Segment is Mac users' }))expect(screen.getByText(authorship)).toBeVisible()@@ -278,7 +320,7 @@ test('the segment pill has no remove button when the dashboard is limited to the})expect(- screen.getByRole('button', { name: 'Segment is Mac users' })+ screen.getByRole('button', { name: 'Open menu: Segment is Mac users' })).toBeVisible()expect(screen.queryByRole('button', {@@ -287,6 +329,33 @@ test('the segment pill has no remove button when the dashboard is limited to the).not.toBeInTheDocument()})+test('a segment that is not found has a menu that explains it', async () => {+ const segment = makeSegment()++ renderFiltersBar({+ searchRecord: {+ filters: [+ ['is', 'segment', [segment.id]],+ ['is', 'page', ['/blog']]+ ],+ labels: getSegmentFilterSearch(segment).labels+ },+ preloaded: { segments: [] }+ })++ await userEvent.click(+ screen.getByRole('button', {+ name: 'Open menu: Segment is Mac users (Segment not found)'+ })+ )+ expect(screen.getByText('Segment not found')).toBeVisible()+ expect(+ screen.getByText(+ 'It may have been deleted. Remove this filter to see your stats.'+ )+ ).toBeVisible()+})+test('shows Add filter, Save and Cancel in segment edit mode', async () => {const segment = makeSegment({name: 'Country, source, page',@@ -307,7 +376,7 @@ test('shows Add filter, Save and Cancel in segment edit mode', async () => {})expect(- screen.getByRole('link', { hidden: false, name: 'Country is Germany' })+ screen.getByRole('group', { name: 'Country is Germany' })).toBeVisible()expect(screen.getByRole('button', { name: 'Add filter' })).toBeVisible()expect(screen.getByRole('button', { name: 'Save' })).toBeVisible()@@ -317,6 +386,330 @@ test('shows Add filter, Save and Cancel in segment edit mode', async () => {}})+describe('inline filter editing', () => {+ test('the value list shows the selected values first and applies changes at once', async () => {+ mockSuggestions('source', ['Bing', 'Google', 'DuckDuckGo'])+ renderFiltersBar({+ searchRecord: { filters: [['is', 'source', ['Google']]] }+ })++ await userEvent.click(+ screen.getByRole('button', { name: 'Edit filter: Source is Google' })+ )+ expect(screen.getByRole('combobox', { name: 'Values' })).toHaveFocus()++ await waitFor(() =>+ expect(getOptionStates()).toEqual([+ ['Google', 'true'],+ ['Bing', 'false'],+ ['DuckDuckGo', 'false']+ ])+ )++ await userEvent.click(getOption('Bing'))+ expect(getPillNames()).toEqual(['Source is Google or Bing'])+ expect(getOptionStates()).toEqual([+ ['Google', 'true'],+ ['Bing', 'true'],+ ['DuckDuckGo', 'false']+ ])+ })++ test('the value list supports the keyboard', async () => {+ mockSuggestions('source', ['Bing', 'Google'])+ renderFiltersBar({+ searchRecord: { filters: [['is', 'source', ['Google']]] }+ })++ await userEvent.click(+ screen.getByRole('button', { name: 'Edit filter: Source is Google' })+ )+ await waitFor(() => expect(getOptions()).toHaveLength(2))++ await userEvent.keyboard('{ArrowDown}{Enter}')+ expect(getPillNames()).toEqual(['Source is Google or Bing'])++ await userEvent.keyboard('{Escape}')+ expect(screen.queryByRole('listbox')).not.toBeInTheDocument()+ expect(+ screen.getByRole('button', {+ name: 'Edit filter: Source is Google or Bing'+ })+ ).toHaveFocus()+ })++ test('a filter without values is removed when the value list closes, and Escape does not clear the other filters', async () => {+ mockSuggestions('source', ['Google'])+ renderFiltersBar({+ searchRecord: {+ filters: [+ ['is', 'source', ['Google']],+ ['is', 'page', ['/blog']]+ ]+ }+ })++ await userEvent.click(+ screen.getByRole('button', { name: 'Edit filter: Source is Google' })+ )+ await userEvent.click(getOption('Google'))+ expect(getPillNames()).toEqual(['Source is', 'Page is /blog'])++ await userEvent.keyboard('{Escape}')+ expect(getPillNames()).toEqual(['Page is /blog'])+ })++ test('Done closes the value list and focuses the pill', async () => {+ mockSuggestions('source', ['Bing', 'Google'])+ renderFiltersBar({+ searchRecord: { filters: [['is', 'source', ['Google']]] }+ })++ await userEvent.click(+ screen.getByRole('button', { name: 'Edit filter: Source is Google' })+ )+ await userEvent.click(getOption('Bing'))+ await userEvent.click(screen.getByRole('button', { name: 'Done' }))++ expect(screen.queryByRole('listbox')).not.toBeInTheDocument()+ expect(getPillNames()).toEqual(['Source is Google or Bing'])+ expect(+ screen.getByRole('button', {+ name: 'Edit filter: Source is Google or Bing'+ })+ ).toHaveFocus()+ })++ test('Deselect all clears the values, and Done then removes the filter', async () => {+ mockSuggestions('source', ['Bing', 'Google'])+ renderFiltersBar({+ searchRecord: {+ filters: [+ ['is', 'source', ['Google', 'Bing']],+ ['is', 'page', ['/blog']]+ ]+ }+ })++ await userEvent.click(+ screen.getByRole('button', {+ name: 'Edit filter: Source is Google or Bing'+ })+ )+ await userEvent.click(screen.getByRole('button', { name: 'Deselect all' }))++ expect(getPillNames()).toEqual(['Source is', 'Page is /blog'])+ expect(getOptionStates()).toEqual([+ ['Google', 'false'],+ ['Bing', 'false']+ ])+ expect(screen.getByRole('button', { name: 'Deselect all' })).toBeDisabled()++ await userEvent.click(screen.getByRole('button', { name: 'Done' }))+ expect(getPillNames()).toEqual(['Page is /blog'])+ })++ test('the operator can be changed', async () => {+ renderFiltersBar({+ searchRecord: { filters: [['is', 'source', ['Google']]] }+ })++ await userEvent.click(+ screen.getByRole('button', { name: 'Change operator: Source is Google' })+ )+ const operators = screen.getByRole('group', { name: 'Operators' })+ expect(+ within(operators)+ .getAllByRole('button')+ .map((o) => o.textContent)+ ).toEqual(['is', 'is not', 'contains', 'does not contain'])++ await userEvent.click(+ within(operators).getByRole('button', { name: 'is not' })+ )+ expect(getPillNames()).toEqual(['Source is not Google'])+ expect(+ screen.queryByRole('group', { name: 'Operators' })+ ).not.toBeInTheDocument()+ })++ test('the operator is a button when the filter supports more than one operator', () => {+ renderFiltersBar({+ searchRecord: {+ filters: [['is', 'goal', ['Signup']]]+ }+ })+ expect(+ screen.getByRole('button', { name: 'Change operator: Goal is Signup' })+ ).toBeVisible()+ })++ test('the operator is not a button when the filter supports only one operator', () => {+ const segment = makeSegment()+ renderFiltersBar({+ searchRecord: getSegmentFilterSearch(segment),+ preloaded: { segments: [segment] }+ })+ expect(+ screen.queryByRole('button', {+ name: 'Change operator: Segment is Mac users'+ })+ ).not.toBeInTheDocument()+ })++ test('a contains filter takes typed values', async () => {+ renderFiltersBar({+ searchRecord: { filters: [['contains', 'page', ['/blog']]] }+ })++ await userEvent.click(+ screen.getByRole('button', { name: 'Edit filter: Page contains /blog' })+ )+ expect(getOptionStates()).toEqual([['/blog', 'true']])++ await userEvent.keyboard('/docs')+ expect(getOptionStates()).toEqual([["Filter by '/docs'", 'false']])++ await userEvent.keyboard('{Enter}')+ expect(getPillNames()).toEqual(['Page contains /blog or /docs'])+ expect(getOptionStates()).toEqual([+ ['/blog', 'true'],+ ['/docs', 'true']+ ])+ })++ test('location values keep their labels', async () => {+ mockAPI.get(suggestionsPath('country'), [+ { value: 'DE', label: 'Germany' },+ { value: 'EE', label: 'Estonia' }+ ])+ renderFiltersBar({+ searchRecord: {+ filters: [['is', 'country', ['DE']]],+ labels: { DE: 'Germany' }+ }+ })++ await userEvent.click(+ screen.getByRole('button', { name: 'Edit filter: Country is Germany' })+ )+ await waitFor(() => expect(getOptions()).toHaveLength(2))+ await userEvent.click(getOption('Estonia'))++ expect(getPillNames()).toEqual(['Country is Germany or Estonia'])+ })++ test('a new filter opens its value list, and goes away when closed without values', async () => {+ mockSuggestions('hostname', ['example.com'])+ renderFiltersBar({ searchRecord: {} })++ await userEvent.click(screen.getByRole('button', { name: 'Filter' }))+ await userEvent.click(screen.getByRole('button', { name: 'Hostname' }))++ expect(getPillNames()).toEqual(['Hostname is'])+ await waitFor(() =>+ expect(screen.getByRole('combobox', { name: 'Values' })).toHaveFocus()+ )+ expect(+ screen.queryByRole('button', { name: 'Add filter' })+ ).not.toBeInTheDocument()+ for (const action of ['Save as segment', 'Clear all filters']) {+ expect(+ screen.queryByRole('link', { name: action })+ ).not.toBeInTheDocument()+ }++ await userEvent.keyboard('{Escape}')+ expect(getPillNames()).toEqual([])+ expect(screen.getByRole('button', { name: 'Filter' })).toBeVisible()+ })++ test('a new filter is applied with its first value', async () => {+ mockSuggestions('hostname', ['example.com'])+ renderFiltersBar({+ searchRecord: { filters: [['is', 'page', ['/blog']]] }+ })++ await userEvent.click(screen.getByRole('button', { name: 'Add filter' }))+ await userEvent.click(screen.getByRole('button', { name: 'Hostname' }))+ expect(getPillNames()).toEqual(['Hostname is', 'Page is /blog'])++ await waitFor(() => expect(getOptions()).toHaveLength(1))+ await userEvent.click(getOption('example.com'))+ await userEvent.click(document.body)++ expect(getPillNames()).toEqual(['Hostname is example.com', 'Page is /blog'])+ })++ test('adding a dimension that already has a filter opens that filter', async () => {+ mockSuggestions('source', ['Google'])+ renderFiltersBar({+ searchRecord: { filters: [['is', 'source', ['Google']]] }+ })++ await userEvent.click(screen.getByRole('button', { name: 'Add filter' }))+ await userEvent.click(screen.getByRole('button', { name: 'Source' }))+ await userEvent.click(+ within(screen.getByTestId('filtermenu-submenu')).getByRole('button', {+ name: 'Source'+ })+ )++ expect(getPillNames()).toEqual(['Source is Google'])+ expect(+ screen.getByRole('button', { name: 'Edit filter: Source is Google' })+ ).toHaveAttribute('aria-expanded', 'true')+ })++ test('a goal can be added more than once', async () => {+ mockSuggestions('goal', ['Signup', 'Purchase'])+ renderFiltersBar({+ searchRecord: { filters: [['is', 'goal', ['Signup']]] }+ })++ await userEvent.click(screen.getByRole('button', { name: 'Add filter' }))+ await userEvent.click(screen.getByRole('button', { name: 'Goal' }))++ expect(getPillNames()).toEqual(['Goal is', 'Goal is Signup'])+ })++ test('a property is added from the property key list, where used keys are disabled', async () => {+ mockSuggestions('prop_key', ['author', 'logged_in'])+ mockAPI.get(+ `/api/stats/${domain}/suggestions/custom-prop-values/logged_in/`,+ [{ value: 'true', label: 'true' }]+ )+ renderFiltersBar({+ searchRecord: { filters: [['is', 'props:author', ['john']]] },+ siteOptions: { propsAvailable: true }+ })++ await userEvent.click(screen.getByRole('button', { name: 'Add filter' }))+ await userEvent.click(screen.getByRole('button', { name: 'Property' }))++ const keys = screen.getByRole('listbox', { name: 'Properties' })+ await waitFor(() =>+ expect(within(keys).getAllByRole('option')).toHaveLength(2)+ )+ expect(+ within(keys).getByRole('option', { name: 'author' })+ ).toHaveAttribute('aria-disabled', 'true')++ await userEvent.click(+ within(keys).getByRole('option', { name: 'logged_in' })+ )++ expect(getPillNames()).toEqual([+ "Property 'logged_in' is",+ "Property 'author' is john"+ ])+ expect(+ screen.getByRole('group', { name: "Property 'author' is john" })+ ).toHaveTextContent(/^authorisjohn$/)+ await waitFor(() => expect(getOptionStates()).toEqual([['true', 'false']]))+ })+})+describe('segment switch', () => {const segments = [makeSegment(),@@ -336,7 +729,7 @@ describe('segment switch', () => {})await userEvent.click(- screen.getByRole('button', { name: 'Segment is Mac users' })+ screen.getByRole('button', { name: 'Open menu: Segment is Mac users' }))await userEvent.click(screen.getByRole('button', { name: /^Mac users/ }))@@ -348,12 +741,10 @@ describe('segment switch', () => {await userEvent.click(within(list).getByRole('link', { name: /Windows users/ }))- expect(- screen.getByRole('button', { name: 'Segment is Windows users' })- ).toBeVisible()- expect(- screen.getByRole('link', { hidden: false, name: 'Page is /blog' })- ).toBeVisible()+ expect(getPillNames()).toEqual([+ 'Segment is Windows users',+ 'Page is /blog'+ ])})test('the segment title is static when there is no other segment', async () => {@@ -363,7 +754,7 @@ describe('segment switch', () => {})await userEvent.click(- screen.getByRole('button', { name: 'Segment is Mac users' })+ screen.getByRole('button', { name: 'Open menu: Segment is Mac users' }))expect(screen.getByTitle('Mac users')).toBeVisible()expect(diff --git a/assets/js/dashboard/nav-menu/filters-bar.tsx b/assets/js/dashboard/nav-menu/filters-bar.tsxindex f18da826b1..4c026a9400 100644--- a/assets/js/dashboard/nav-menu/filters-bar.tsx+++ b/assets/js/dashboard/nav-menu/filters-bar.tsx@@ -8,6 +8,7 @@ import React, {useState} from 'react'import { AppliedFilterPillsList } from './filter-pills-list'+import { useFilterEditorContext } from '../filtering/filter-editor-context'import { FilterMenu } from './filter-menu'import { SegmentMenu } from './segments/segment-menu'import { useDashboardStateContext } from '../dashboard-state-context'@@ -21,42 +22,29 @@ import {isSegmentFilter} from '../filtering/segments'import { useRoutelessModalsContext } from '../navigation/routeless-modals-context'-import { DashboardState } from '../dashboard-state'import { useUserContext } from '../user-context'const SCROLL_FADE_PX = 32type ScrollOverflow = { start: boolean; end: boolean }-const canShowClearAllAction = ({- filters,- isEditingSegment-}: Pick<DashboardState, 'filters'> & { isEditingSegment: boolean }): boolean =>- filters.length >= 1 && !isEditingSegment--const canShowSaveAsSegmentAction = ({- filters,- isEditingSegment-}: Pick<DashboardState, 'filters'> & { isEditingSegment: boolean }): boolean =>- filters.length >= 1 && !filters.some(isSegmentFilter) && !isEditingSegment-export const FiltersBar = () => {const { dashboardState, expandedSegment } = useDashboardStateContext()+ const { renderedFilters } = useFilterEditorContext()const user = useUserContext()- const showingClearAll = canShowClearAllAction({- filters: dashboardState.filters,- isEditingSegment: !!expandedSegment- })+ const isEditingSegment = !!expandedSegment+ const hasActiveFilters = dashboardState.filters.length > 0+ const showingClearAll = hasActiveFilters && !isEditingSegmentconst showingSaveAsSegment =- canShowSaveAsSegmentAction({- filters: dashboardState.filters,- isEditingSegment: !!expandedSegment- }) && canSeeSaveAsSegmentAction({ user })+ hasActiveFilters &&+ !isEditingSegment &&+ !dashboardState.filters.some(isSegmentFilter) &&+ canSeeSaveAsSegmentAction({ user })const hasActions = showingSaveAsSegment || showingClearAll- if (!dashboardState.filters.length) {+ if (!renderedFilters.length) {return (<div className="flex flex-1 justify-end"><FilterMenu />@@ -68,8 +56,8 @@ export const FiltersBar = () => {<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 || !!expandedSegment) && (+ {hasActiveFilters && <FilterMenu compact />}+ {(hasActions || isEditingSegment) && (<divaria-hidden="true"className="mx-1 h-4 w-px bg-gray-300 dark:bg-gray-600"@@ -100,13 +88,13 @@ const getFadeMask = ({ start, end }: ScrollOverflow) => {}const ScrollableFilterPills = () => {- const { dashboardState } = useDashboardStateContext()+ const { renderedFilters } = useFilterEditorContext()const scrollRef = useRef<HTMLDivElement>(null)const [overflow, setOverflow] = useState<ScrollOverflow>({start: false,end: false})- const filtersCount = dashboardState.filters.length+ const filtersCount = renderedFilters.lengthconst previousFiltersCount = useRef(filtersCount)const updateOverflow = (element: HTMLElement) => {@@ -142,7 +130,7 @@ const ScrollableFilterPills = () => {}previousFiltersCount.current = filtersCountupdateOverflow(element)- }, [dashboardState.filters, filtersCount])+ }, [renderedFilters, filtersCount])return (<AppliedFilterPillsListdiff --git a/assets/js/dashboard/nav-menu/property-key-picker.tsx b/assets/js/dashboard/nav-menu/property-key-picker.tsxnew file mode 100644index 0000000000..34371094d9--- /dev/null+++ b/assets/js/dashboard/nav-menu/property-key-picker.tsx@@ -0,0 +1,32 @@+import React from 'react'+import { useDashboardStateContext } from '../dashboard-state-context'+import { useSiteContext } from '../site-context'+import {+ EVENT_PROPS_PREFIX,+ getPropertyKeyFromFilterKey+} from '../util/filters'+import { apiPath } from '../util/url'+import { Combobox, isSameValue } from '../components/combobox'++export const PropertyKeyPicker = ({+ onSelect+}: {+ onSelect: (propKey: string) => void+}) => {+ const site = useSiteContext()+ const { dashboardState } = useDashboardStateContext()+ const usedKeys = dashboardState.filters+ .filter(([_operation, key]) => key.startsWith(EVENT_PROPS_PREFIX))+ .map(([_operation, key]) => getPropertyKeyFromFilterKey(key))++ return (+ <Combobox+ request={{ path: apiPath(site, '/suggestions/prop_key') }}+ isDisabled={(option) =>+ usedKeys.some((key) => isSameValue(key, option.value))+ }+ onSelect={(option) => onSelect(String(option.value))}+ label="Properties"+ />+ )+}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.tsxindex 9616250369..5de2fae719 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@@ -113,7 +113,7 @@ export const DashboardPeriodMenu = ({<Popover.Buttonref={buttonRef}className={classNames(- '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',+ 'flex items-center gap-x-1.5 pl-2.5 text-sm 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/segments/segment-pill-menu.tsx b/assets/js/dashboard/nav-menu/segments/segment-pill-menu.tsxindex fb33864428..000d339f29 100644--- a/assets/js/dashboard/nav-menu/segments/segment-pill-menu.tsx+++ b/assets/js/dashboard/nav-menu/segments/segment-pill-menu.tsx@@ -15,6 +15,7 @@ import { AppNavigationLink } from '../../navigation/use-app-navigate'import { popover } from '../../components/popover'import { PencilIcon, TrashIcon } from '../../components/icons'import { MenuSeparator } from '../nav-menu-components'+import { Notice } from '../../components/notice'import {SubmenuInPlace,SubmenuPanel,@@ -74,6 +75,17 @@ const SegmentTitle = ({ segment }: { segment: SavedSegments[number] }) => {)}+export const SEGMENT_NOT_FOUND = 'Segment not found'++export const MissingSegmentPillMenu = () => (+ <Notice+ className="m-1"+ theme="red"+ title={SEGMENT_NOT_FOUND}+ description="It may have been deleted. Remove this filter to see your stats."+ />+)+export const SegmentPillMenu = ({segment,closeMenudiff --git a/assets/js/dashboard/nav-menu/top-bar.test.tsx b/assets/js/dashboard/nav-menu/top-bar.test.tsxindex dc855c4e7e..0fa4ae6217 100644--- a/assets/js/dashboard/nav-menu/top-bar.test.tsx+++ b/assets/js/dashboard/nav-menu/top-bar.test.tsx@@ -129,12 +129,14 @@ test('user can open and close filters dropdown', async () => {'Goal'])- // rows without a submenu link straight to their dimension- expect(screen.getByRole('link', { name: 'Hostname' })).toHaveAttribute(- 'href',- `/${domain}/filter/hostname`+ // only rows with a submenu can expand+ expect(screen.getByRole('button', { name: 'Hostname' })).not.toHaveAttribute(+ 'aria-expanded'+ )+ expect(screen.getByRole('button', { name: 'Page' })).toHaveAttribute(+ 'aria-expanded',+ 'false')- expect(screen.queryByRole('link', { name: 'Page' })).not.toBeInTheDocument()await userEvent.click(toggleFilters)expect(screen.queryByTestId('filtermenu')).not.toBeInTheDocument()@@ -181,16 +183,8 @@ test.each([const submenu = screen.getByTestId('filtermenu-submenu')expect(- Array.from(submenu.querySelectorAll('a')).map((el) => [- el.textContent,- el.getAttribute('href')- ])- ).toEqual(- expectedItems.map(([label, dimension]) => [- label,- `/${domain}/filter/${dimension}`- ])- )+ Array.from(submenu.querySelectorAll('button')).map((el) => el.textContent)+ ).toEqual(expectedItems.map(([label]) => label))})test('user can walk the filter menu and a submenu with Tab', async () => {@@ -203,12 +197,14 @@ test('user can walk the filter menu and a submenu with Tab', async () => {await userEvent.click(screen.getByRole('button', { name: 'Filter' }))await userEvent.tab()- const pageRow = screen.getByRole('button', { name: 'Page' })+ const pageRow = within(screen.getByTestId('filtermenu')).getByRole('button', {+ name: 'Page',+ expanded: true+ })expect(pageRow).toHaveFocus()- expect(pageRow).toHaveAttribute('aria-expanded', 'true')const submenuLinks = Array.from(- screen.getByTestId('filtermenu-submenu').querySelectorAll('a')+ screen.getByTestId('filtermenu-submenu').querySelectorAll('button'))await userEvent.tab()expect(submenuLinks[0]).toHaveFocus()@@ -233,7 +229,7 @@ test('property row only shows when props are available', async () => {})await userEvent.click(screen.getByRole('button', { name: 'Filter' }))expect(- screen.queryByRole('link', { name: 'Property' })+ screen.queryByRole('button', { name: 'Property' })).not.toBeInTheDocument()unmount()@@ -246,9 +242,9 @@ test('property row only shows when props are available', async () => {)})await userEvent.click(screen.getByRole('button', { name: 'Filter' }))- expect(screen.getByRole('link', { name: 'Property' })).toHaveAttribute(- 'href',- `/${domain}/filter/props`+ expect(screen.getByRole('button', { name: 'Property' })).toHaveAttribute(+ 'aria-expanded',+ 'false')})@@ -454,18 +450,21 @@ describe('narrow viewport (no room for a submenu beside the menu)', () => {const submenu = screen.getByTestId('filtermenu-submenu')expect(- Array.from(submenu.querySelectorAll('a')).map((el) => el.textContent)+ Array.from(submenu.querySelectorAll('button')).map((el) => el.textContent)).toEqual(['Page', 'Entry page', 'Exit page'])// The main list is replaced, not shown beside the submenu.expect(- screen.queryByRole('link', { name: 'Hostname' })+ screen.queryByRole('button', { name: 'Hostname' })).not.toBeInTheDocument()- await userEvent.click(screen.getByRole('button', { name: 'Page' }))+ const backButton = screen+ .getAllByRole('button', { name: 'Page' })+ .find((button) => !submenu.contains(button))+ await userEvent.click(backButton!)expect(screen.queryByTestId('filtermenu-submenu')).not.toBeInTheDocument()- expect(screen.getByRole('link', { name: 'Hostname' })).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'Hostname' })).toBeInTheDocument()})test('tabbing onto a submenu row does not drill down', async () => {@@ -500,3 +499,36 @@ test('current visitors renders when visitors are present and disappears after viscreen.queryByRole('link', { name: /current visitors/ }))})++test('current visitors is hidden while there are filters, also if it is a new filter with no values yet', async () => {+ mockAPI.get(`/api/stats/${domain}/current-visitors`, 500)+ mockAPI.get(`/api/stats/${domain}/suggestions/hostname/`, [])+ render(<TopBar showCurrentVisitors={true} />, {+ wrapper: (props) => (+ <TestContextProviders siteOptions={{ domain }} {...props} />+ )+ })++ await waitFor(() => {+ expect(+ screen.queryByRole('link', { name: /500 current visitors/ })+ ).toBeVisible()+ })++ await userEvent.click(screen.getByRole('button', { name: 'Filter' }))+ await userEvent.click(screen.getByRole('button', { name: 'Hostname' }))++ expect(screen.getByRole('group', { name: 'Hostname is' })).toBeVisible()+ expect(+ screen.queryByRole('link', { name: /current visitors/ })+ ).not.toBeInTheDocument()++ await userEvent.keyboard('{Escape}')++ expect(+ screen.queryByRole('group', { name: 'Hostname is' })+ ).not.toBeInTheDocument()+ expect(+ screen.getByRole('link', { name: /500 current visitors/ })+ ).toBeVisible()+})diff --git a/assets/js/dashboard/nav-menu/top-bar.tsx b/assets/js/dashboard/nav-menu/top-bar.tsxindex 8b193699a4..a6d95981ae 100644--- a/assets/js/dashboard/nav-menu/top-bar.tsx+++ b/assets/js/dashboard/nav-menu/top-bar.tsx@@ -5,6 +5,10 @@ import CurrentVisitors from '../stats/current-visitors'import classNames from 'classnames'import { useInView } from 'react-intersection-observer'import { FiltersBar } from './filters-bar'+import {+ FilterEditorContextProvider,+ useFilterEditorContext+} from '../filtering/filter-editor-context'import { DashboardPeriodPicker } from './query-periods/dashboard-period-picker'import { DashboardOptionsMenu } from './dashboard-options-menu'import { useDashboardStateContext } from '../dashboard-state-context'@@ -15,9 +19,11 @@ interface TopBarProps {export function TopBar({ showCurrentVisitors }: TopBarProps) {return (- <TopBarStickyWrapper>- <TopBarInner showCurrentVisitors={showCurrentVisitors} />- </TopBarStickyWrapper>+ <FilterEditorContextProvider>+ <TopBarStickyWrapper>+ <TopBarInner showCurrentVisitors={showCurrentVisitors} />+ </TopBarStickyWrapper>+ </FilterEditorContextProvider>)}@@ -33,7 +39,7 @@ function TopBarStickyWrapper({ children }: { children: ReactNode }) {'col-span-full relative top-0 py-2 -my-3 sm:-my-4 z-10',!site.embedded &&!inView &&- 'sticky bg-gray-50 dark:bg-gray-950 before:absolute before:top-0 before:w-screen before:h-full before:bg-inherit before:shadow-[0_4px_2px_-2px_rgb(0_0_0/6%)] before:z-[-1] before:left-[calc(50%-50vw)]'+ 'sticky bg-gray-50 dark:bg-gray-950 before:absolute before:top-0 before:w-screen before:h-full before:bg-inherit before:shadow-sm before:[clip-path:inset(0_0_-8px_0)] dark:before:shadow-none before:z-[-1] before:left-[calc(50%-50vw)]')}>{children}@@ -44,12 +50,13 @@ function TopBarStickyWrapper({ children }: { children: ReactNode }) {function TopBarInner({ showCurrentVisitors }: TopBarProps) {const { expandedSegment } = useDashboardStateContext()+ const { renderedFilters } = useFilterEditorContext()return (<div 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"><div className="flex shrink-0 items-center sm:gap-x-1 md:gap-x-2.5 empty:hidden">{!expandedSegment && <SiteSwitcher />}- {showCurrentVisitors && <CurrentVisitors />}+ {showCurrentVisitors && !renderedFilters.length && <CurrentVisitors />}</div><div className="flex flex-1 md:min-w-0"><FiltersBar />diff --git a/assets/js/dashboard/router.tsx b/assets/js/dashboard/router.tsxindex 2fdc654208..9ee86c6209 100644--- a/assets/js/dashboard/router.tsx+++ b/assets/js/dashboard/router.tsx@@ -18,7 +18,6 @@ import {import { LocationsDetails } from './stats/locations/details'import PropsModal from './stats/modals/props'import ConversionsModal from './stats/modals/conversions'-import FilterModal from './stats/modals/filter-modal'import DashboardStateContextProvider from './dashboard-state-context'import { DashboardKeybinds } from './dashboard-keybinds'import LastLoadContextProvider from './last-load-context'@@ -203,11 +202,6 @@ export const customPropsRoute = {element: <PropsModal />}-export const filterRoute = {- path: 'filter/:field',- element: <FilterModal />-}-export function getRouterBasepath(site: Pick<PlausibleSite, 'shared' | 'domain'>): string {@@ -262,7 +256,6 @@ export function createAppRouter(site: PlausibleSite) {screenSizesRoute,conversionsRoute,customPropsRoute,- filterRoute,{ path: '*', element: null }]}diff --git a/assets/js/dashboard/stats/graph/top-stats.js b/assets/js/dashboard/stats/graph/top-stats.jsindex 1e5b51c381..9043916050 100644--- a/assets/js/dashboard/stats/graph/top-stats.js+++ b/assets/js/dashboard/stats/graph/top-stats.js@@ -123,11 +123,10 @@ export default function TopStats({const [statDisplayName, statExtraName] = stat.name.split(/(\(.+\))/g)const statDisplayNameClass = classNames(- 'text-xs uppercase whitespace-nowrap flex w-fit',+ 'text-xs font-semibold uppercase whitespace-nowrap flex w-fit',{- 'text-gray-900 dark:text-gray-100 font-bold tracking-[-.01em]':- isSelected,- 'font-semibold text-gray-500 dark:text-gray-400 group-hover:text-gray-900 dark:group-hover:text-gray-100':+ 'text-gray-900 dark:text-gray-100': isSelected,+ 'text-gray-500 dark:text-gray-400 group-hover:text-gray-900 dark:group-hover:text-gray-100':!isSelected})diff --git a/assets/js/dashboard/stats/modals/filter-modal-dimension.js b/assets/js/dashboard/stats/modals/filter-modal-dimension.jsdeleted file mode 100644index 2e4f9819b3..0000000000--- a/assets/js/dashboard/stats/modals/filter-modal-dimension.js+++ /dev/null@@ -1,79 +0,0 @@-import React, { useMemo } from 'react'-import FilterModalRow from './filter-modal-row'-import {- getFilterDimension,- getPropertyKeyFromFilterKey-} from '../../util/filters'-import FilterModalPropsRow from './filter-modal-props-row'--export default function FilterModalDimension({- dimension,- filterState,- labels,- onUpdateRowValue,- onAddRow,- onDeleteRow-}) {- const rows = useMemo(- () =>- Object.entries(filterState)- .filter(([_, filter]) => getFilterDimension(filter) == dimension)- .map(([id, filter]) => ({ id, filter })),- [dimension, filterState]- )- const disabledOptions = useMemo(- () =>- dimension == 'props'- ? rows.map(({ filter }) => ({- value: getPropertyKeyFromFilterKey(filter[1])- }))- : null,- [dimension, rows]- )-- const showAddRow = ['props', 'goal'].includes(dimension)-- return (- <>- <div>- {rows.map(({ id, filter }) =>- dimension === 'props' ? (- <FilterModalPropsRow- testId={id}- key={id}- filter={filter}- showDelete={rows.length > 1}- disabledOptions={disabledOptions}- onUpdate={(newFilter) => onUpdateRowValue(id, newFilter)}- onDelete={() => onDeleteRow(id)}- />- ) : (- <FilterModalRow- testId={id}- key={id}- filter={filter}- labels={labels}- canDelete={showAddRow}- showDelete={rows.length > 1}- onUpdate={(newFilter, labelUpdate) =>- onUpdateRowValue(id, newFilter, labelUpdate)- }- onDelete={() => onDeleteRow(id)}- />- )- )}- </div>- {showAddRow && (- <div className="mt-2">- {/* eslint-disable-next-line jsx-a11y/anchor-is-valid */}- <a- className="underline text-indigo-500 text-sm cursor-pointer"- onClick={() => onAddRow(dimension)}- >- + Add another- </a>- </div>- )}- </>- )-}diff --git a/assets/js/dashboard/stats/modals/filter-modal-props-row.js b/assets/js/dashboard/stats/modals/filter-modal-props-row.jsdeleted file mode 100644index f74ae6adf9..0000000000--- a/assets/js/dashboard/stats/modals/filter-modal-props-row.js+++ /dev/null@@ -1,129 +0,0 @@-import React, { useMemo } from 'react'-import { TrashIcon } from '../../components/icons'--import FilterOperatorSelector from '../../components/filter-operator-selector'-import Combobox from '../../components/combobox'--import { apiPath } from '../../util/url'-import {- EVENT_PROPS_PREFIX,- FILTER_OPERATIONS,- getPropertyKeyFromFilterKey,- isFreeChoiceFilterOperation-} from '../../util/filters'-import { fetchSuggestions } from '../../util/fetch-suggestions'-import { useDashboardStateContext } from '../../dashboard-state-context'-import { useSiteContext } from '../../site-context'--export default function FilterModalPropsRow({- testId,- filter,- showDelete,- disabledOptions,- onUpdate,- onDelete-}) {- const { dashboardState } = useDashboardStateContext()- const site = useSiteContext()- const [operation, filterKey, clauses] = filter-- const propKey = useMemo(- () => getPropertyKeyFromFilterKey(filterKey),- [filterKey]- )-- const selectedClauses = useMemo(- () => clauses.map((value) => ({ value, label: value })),- [clauses]- )-- function fetchPropKeyOptions(input) {- return fetchSuggestions(- apiPath(site, `/suggestions/prop_key`),- dashboardState,- input- )- }-- function fetchPropValueOptions(input) {- if (- [FILTER_OPERATIONS.contains, FILTER_OPERATIONS.contains_not].includes(- operation- ) ||- propKey == ''- ) {- return Promise.resolve([])- }- return fetchSuggestions(- apiPath(- site,- `/suggestions/custom-prop-values/${encodeURIComponent(propKey)}`- ),- dashboardState,- input,- [FILTER_OPERATIONS.isNot, filterKey, ['(none)']]- )- }-- function onPropKeySelect(selection) {- const { value } = selection[0]- onUpdate([operation, `${EVENT_PROPS_PREFIX}${value}`, clauses])- }-- function onPropValueSelect(selection) {- const newClauses = selection.map(({ value }) => value)- onUpdate([operation, filterKey, newClauses])- }-- return (- <div- data-testid={`filter-row-${testId}`}- className="grid grid-cols-12 mt-6"- >- <div className="col-span-4">- <Combobox- className="mr-2"- fetchOptions={fetchPropKeyOptions}- singleOption- // eslint-disable-next-line jsx-a11y/no-autofocus- autoFocus- values={propKey ? [{ value: propKey, label: propKey }] : []}- onSelect={onPropKeySelect}- placeholder="Property"- disabledOptions={disabledOptions}- />- </div>- <div className="col-span-3 mx-2">- <FilterOperatorSelector- isDisabled={!filterKey}- forFilter={'prop_value'}- onSelect={(newOperation) =>- onUpdate([newOperation, filterKey, clauses])- }- selectedType={operation}- />- </div>- <div className="col-span-4">- <Combobox- isDisabled={!filterKey}- fetchOptions={fetchPropValueOptions}- values={selectedClauses}- onSelect={onPropValueSelect}- placeholder={'Value'}- freeChoice={isFreeChoiceFilterOperation(operation)}- />- </div>- {showDelete && (- <div className="col-span-1 flex flex-col mt-2">- {/* eslint-disable-next-line jsx-a11y/anchor-is-valid */}- <a- className="ml-2 text-red-600 h-5 w-5 cursor-pointer"- onClick={onDelete}- >- <TrashIcon />- </a>- </div>- )}- </div>- )-}diff --git a/assets/js/dashboard/stats/modals/filter-modal-row.js b/assets/js/dashboard/stats/modals/filter-modal-row.jsdeleted file mode 100644index 094fa748cf..0000000000--- a/assets/js/dashboard/stats/modals/filter-modal-row.js+++ /dev/null@@ -1,127 +0,0 @@-import React, { useMemo } from 'react'-import { TrashIcon } from '../../components/icons'-import classNames from 'classnames'--import FilterOperatorSelector from '../../components/filter-operator-selector'-import Combobox from '../../components/combobox'--import {- FILTER_OPERATIONS,- isFreeChoiceFilterOperation,- getLabel,- formattedFilters-} from '../../util/filters'-import { fetchSuggestions } from '../../util/fetch-suggestions'-import { apiPath } from '../../util/url'-import { useDashboardStateContext } from '../../dashboard-state-context'-import { useSiteContext } from '../../site-context'--export default function FilterModalRow({- testId,- filter,- labels,- canDelete,- showDelete,- onUpdate,- onDelete-}) {- const { dashboardState } = useDashboardStateContext()- const site = useSiteContext()- const [operation, filterKey, clauses] = filter-- const selectedClauses = useMemo(- () =>- clauses.map((value) => ({- value,- label: getLabel(labels, filterKey, value)- })),- // eslint-disable-next-line react-hooks/exhaustive-deps- [filter, labels]- )-- function onComboboxSelect(selection) {- const newClauses = selection.map(({ value }) => value)- const newLabels = Object.fromEntries(- selection.map(({ label, value }) => [value, label])- )-- onUpdate([operation, filterKey, newClauses], newLabels)- }-- function fetchOptions(input) {- if (- [FILTER_OPERATIONS.contains, FILTER_OPERATIONS.contains_not].includes(- operation- )- ) {- return Promise.resolve([])- }-- let additionalFilter = null-- if (filterKey !== 'goal') {- additionalFilter = [FILTER_OPERATIONS.isNot, filterKey, clauses]- }-- return fetchSuggestions(- apiPath(site, `/suggestions/${filterKey}`),- dashboardState,- input,- additionalFilter- )- }-- return (- <div- data-testid={`filter-row-${testId}`}- className={classNames('grid mt-1', {- 'grid-cols-12': canDelete,- 'grid-cols-11': !canDelete- })}- >- <div className="col-span-3">- <FilterOperatorSelector- forFilter={filterKey}- onSelect={(newOperation) =>- onUpdate([newOperation, filterKey, clauses], labels)- }- selectedType={operation}- />- </div>- <div className="col-span-8 ml-2">- <Combobox- fetchOptions={fetchOptions}- freeChoice={isFreeChoiceFilterOperation(operation)}- values={selectedClauses}- onSelect={onComboboxSelect}- placeholder={`Select ${withIndefiniteArticle(formattedFilters[filterKey])}`}- />- </div>- {showDelete && (- <div className="col-span-1 flex flex-col mt-2">- {/* eslint-disable-next-line jsx-a11y/anchor-is-valid */}- <a- className="ml-2 text-red-600 h-5 w-5 cursor-pointer"- onClick={onDelete}- >- <TrashIcon />- </a>- </div>- )}- </div>- )-}--function withIndefiniteArticle(word) {- if (word.startsWith('UTM')) {- return `a ${word}`- }- if (- ['a', 'e', 'i', 'o', 'u'].some((vowel) =>- word.toLowerCase().startsWith(vowel)- )- ) {- return `an ${word}`- }- return `a ${word}`-}diff --git a/assets/js/dashboard/stats/modals/filter-modal.js b/assets/js/dashboard/stats/modals/filter-modal.jsdeleted file mode 100644index b2443b192c..0000000000--- a/assets/js/dashboard/stats/modals/filter-modal.js+++ /dev/null@@ -1,235 +0,0 @@-import React from 'react'-import { useParams } from 'react-router-dom'--import { ModalLayout, ModalFooter } from '../../components/modal-layout'-import {- EVENT_PROPS_PREFIX,- formattedFilters,- FILTER_OPERATIONS,- getFilterDimension,- cleanLabels,- getAvailableFilterDimensions-} from '../../util/filters'-import { useDashboardStateContext } from '../../dashboard-state-context'-import { useSiteContext } from '../../site-context'-import { isModifierPressed, isTyping } from '../../keybinding'-import FilterModalDimension from './filter-modal-dimension'-import { rootRoute } from '../../router'-import { useAppNavigate } from '../../navigation/use-app-navigate'-import { Button } from '../../components/button'--function partitionFilters(dimension, filters) {- const otherFilters = []- const filterState = {}- let filtersToRemoveCount = 0-- filters.forEach((filter, index) => {- if (getFilterDimension(filter) === dimension) {- const key = filterState[dimension] ? `${dimension}:${index}` : dimension- filterState[key] = filter- filtersToRemoveCount++- } else {- otherFilters.push(filter)- }- })-- if (!filterState[dimension]) {- filterState[dimension] = emptyFilter(dimension)- }-- return { filterState, otherFilters, filtersToRemoveCount }-}--function emptyFilter(key) {- const filterKey = key === 'props' ? EVENT_PROPS_PREFIX : key-- return [FILTER_OPERATIONS.is, filterKey, []]-}--class FilterModal extends React.Component {- constructor(props) {- super(props)-- const dashboardState = this.props.dashboardState- const { filterState, otherFilters, filtersToRemoveCount } =- partitionFilters(this.props.dimension, dashboardState.filters)-- this.handleKeydown = this.handleKeydown.bind(this)- this.closeModal = this.closeModal.bind(this)- this.state = {- dashboardState,- filterState,- labelState: dashboardState.labels,- otherFilters,- filtersToRemoveCount- }- }-- componentDidMount() {- document.addEventListener('keydown', this.handleKeydown)- }-- componentWillUnmount() {- document.removeEventListener('keydown', this.handleKeydown)- }-- handleKeydown(e) {- if (isTyping(e) || isModifierPressed(e)) return-- if (e.target.tagName === 'BODY' && e.key === 'Enter') {- this.handleSubmit()- }- }-- handleSubmit(e) {- const filters = Object.values(this.state.filterState)- .filter(([_op, _key, clauses]) => clauses.length > 0)- .concat(this.state.otherFilters)-- this.selectFiltersAndCloseModal(filters)- e.preventDefault()- }-- isDisabled() {- return Object.values(this.state.filterState).every(- ([_operation, _key, clauses]) => clauses.length === 0- )- }-- closeModal() {- this.props.navigate({- path: rootRoute.path,- search: (search) => search- })- }-- selectFiltersAndCloseModal(filters) {- this.props.navigate({- path: rootRoute.path,- search: (searchRecord) => ({- ...searchRecord,- filters: filters,- labels: cleanLabels(filters, this.state.labelState)- }),- replace: true- })- }-- onUpdateRowValue(id, newFilter, newLabels) {- this.setState((prevState) => {- const [_operation, filterKey, _clauses] = newFilter- return {- filterState: {- ...prevState.filterState,- [id]: newFilter- },- labelState: cleanLabels(- Object.values(this.state.filterState).concat(- this.state.dashboardState.filters- ),- prevState.labelState,- filterKey,- newLabels- )- }- })- }-- onAddRow(filterGroup) {- this.setState((prevState) => {- const filter = emptyFilter(filterGroup)- const id = `${filterGroup}${Object.keys(this.state.filterState).length}`-- return {- filterState: {- ...prevState.filterState,- [id]: filter- }- }- })- }-- onDeleteRow(id) {- this.setState((prevState) => {- const filterState = { ...prevState.filterState }- delete filterState[id]- return { filterState }- })- }-- render() {- return (- <ModalLayout- title={`Filter by ${formattedFilters[this.props.dimension]}`}- onClose={this.closeModal}- >- <form- className="flex flex-col gap-y-6"- onSubmit={this.handleSubmit.bind(this)}- >- <div className="flex flex-col gap-y-3 mb-2">- <FilterModalDimension- dimension={this.props.dimension}- filterState={this.state.filterState}- labels={this.state.labelState}- onUpdateRowValue={this.onUpdateRowValue.bind(this)}- onAddRow={this.onAddRow.bind(this)}- onDeleteRow={this.onDeleteRow.bind(this)}- />- </div>-- <ModalFooter>- {this.state.filtersToRemoveCount > 0 ? (- <Button- theme="secondary"- size="sm"- onClick={() => {- this.selectFiltersAndCloseModal(this.state.otherFilters)- }}- >- {this.state.filtersToRemoveCount > 1- ? 'Remove filters'- : 'Remove filter'}- </Button>- ) : (- <Button- type="button"- theme="secondary"- size="sm"- onClick={this.closeModal}- >- Cancel- </Button>- )}-- <Button type="submit" size="sm" disabled={this.isDisabled()}>- Apply filter- </Button>- </ModalFooter>- </form>- </ModalLayout>- )- }-}--export default function FilterModalWithRouter(props) {- const navigate = useAppNavigate()- const { field } = useParams()- const { dashboardState } = useDashboardStateContext()- const site = useSiteContext()- if (- field === 'segment' ||- !getAvailableFilterDimensions(site).includes(field)- ) {- return null- }- return (- <FilterModal- {...props}- dimension={field}- dashboardState={dashboardState}- navigate={navigate}- site={site}- />- )-}diff --git a/assets/js/dashboard/util/filter-text.test.ts b/assets/js/dashboard/util/filter-text.test.tsnew file mode 100644index 0000000000..cff9107044--- /dev/null+++ b/assets/js/dashboard/util/filter-text.test.ts@@ -0,0 +1,30 @@+import { Filter, FilterClauseLabels } from '../dashboard-state'+import { plainFilterText } from './filter-text'++describe('plainFilterText()', () => {+ it.each<[Filter, FilterClauseLabels, string]>([+ [['is', 'page', ['/docs', '/blog']], {}, 'Page is /docs or /blog'],+ [+ ['is', 'country', ['US']],+ { US: 'United States' },+ 'Country is United States'+ ],+ [['is', 'goal', ['Signup']], {}, 'Goal is Signup'],+ [+ ['is', 'props:browser_language', ['en-US']],+ {},+ "Property 'browser_language' is en-US"+ ],+ [+ ['has_not_done', 'goal', ['Signup', 'Login']],+ {},+ 'Goal is not Signup or Login'+ ],+ [['is', 'source', []], {}, 'Source is']+ ])(+ 'when filter is %p and labels are %p, returns %p',+ (filter, labels, expectedPlainText) => {+ expect(plainFilterText({ labels }, filter)).toBe(expectedPlainText)+ }+ )+})diff --git a/assets/js/dashboard/util/filter-text.test.tsx b/assets/js/dashboard/util/filter-text.test.tsxdeleted file mode 100644index 1179c5cc19..0000000000--- a/assets/js/dashboard/util/filter-text.test.tsx+++ /dev/null@@ -1,61 +0,0 @@-import React from 'react'-import { Filter, FilterClauseLabels } from '../dashboard-state'-import { plainFilterText, styledFilterText } from './filter-text'-import { render, screen } from '@testing-library/react'--describe('plainFilterText()', () => {- it.each<[Filter, FilterClauseLabels, string]>([- [['is', 'page', ['/docs', '/blog']], {}, 'Page is /docs or /blog'],- [- ['is', 'country', ['US']],- { US: 'United States' },- 'Country is United States'- ],- [['is', 'goal', ['Signup']], {}, 'Goal is Signup'],- [- ['is', 'props:browser_language', ['en-US']],- {},- "Property 'browser_language' is en-US"- ],- [- ['has_not_done', 'goal', ['Signup', 'Login']],- {},- 'Goal is not Signup or Login'- ],- [['is', 'source', []], {}, 'Source is']- ])(- 'when filter is %p and labels are %p, returns %p',- (filter, labels, expectedPlainText) => {- expect(plainFilterText({ labels }, filter)).toBe(expectedPlainText)- }- )-})--describe('styledFilterText()', () => {- it.each<[Filter, FilterClauseLabels, string]>([- [['is', 'page', ['/docs', '/blog']], {}, 'Page is /docs or /blog'],- [- ['is', 'country', ['US']],- { US: 'United States' },- 'Country is United States'- ],- [- ['is', 'props:browser_language', ['en-US']],- {},- 'Property browser_language is en-US'- ],- [- ['has_not_done', 'goal', ['Signup', 'Login']],- {},- 'Goal is not Signup or Login'- ]- ])(- 'when filter is %p and labels are %p, renders %p',- (filter, labels, expectedText) => {- render(- <p data-testid="filter-text">{styledFilterText({ labels }, filter)}</p>- )- expect(screen.getByTestId('filter-text')).toHaveTextContent(expectedText)- }- )-})diff --git a/assets/js/dashboard/util/filter-text.tsx b/assets/js/dashboard/util/filter-text.tssimilarity index 56%rename from assets/js/dashboard/util/filter-text.tsxrename to assets/js/dashboard/util/filter-text.tsindex 371f51dc1a..d0b9f07880 100644--- a/assets/js/dashboard/util/filter-text.tsx+++ b/assets/js/dashboard/util/filter-text.ts@@ -1,4 +1,3 @@-import React, { ReactNode, Fragment } from 'react'import { DashboardState, Filter } from '../dashboard-state'import {EVENT_PROPS_PREFIX,@@ -8,39 +7,6 @@ import {getPropertyKeyFromFilterKey} from './filters'-export function styledFilterText(- dashboardState: Pick<DashboardState, 'labels'>,- [operation, filterKey, clauses]: Filter-) {- if (filterKey.startsWith(EVENT_PROPS_PREFIX)) {- const propKey = getPropertyKeyFromFilterKey(filterKey)- return (- <>- Property <b>{propKey}</b> {FILTER_OPERATIONS_DISPLAY_NAMES[operation]}{' '}- {formatClauses(clauses)}- </>- )- }-- const formattedFilter = (- formattedFilters as Record<string, string | undefined>- )[filterKey]- const clausesLabels = clauses.map((value) =>- getLabel(dashboardState.labels, filterKey, value)- )-- if (!formattedFilter) {- throw new Error(`Unknown filter: ${filterKey}`)- }-- return (- <>- {capitalize(formattedFilter)} {FILTER_OPERATIONS_DISPLAY_NAMES[operation]}{' '}- {formatClauses(clausesLabels)}- </>- )-}-/** e.g. { dimension: 'Country', operation: 'is', values: ['Germany', 'Poland'] } */export function getFilterTextParts(dashboardState: Pick<DashboardState, 'labels'>,@@ -80,15 +46,6 @@ function getDimensionName(filterKey: string): string {return capitalize(formattedFilter)}-function formatClauses(labels: Array<string | number>): ReactNode[] {- return labels.map((label, index) => (- <Fragment key={index}>- {index > 0 && ' or '}- <span className="font-semibold">{label}</span>- </Fragment>- ))-}-function capitalize(str: string): string {return str[0].toUpperCase() + str.slice(1)}diff --git a/assets/js/dashboard/util/filters.js b/assets/js/dashboard/util/filters.jsindex 631630f48a..e99205d995 100644--- a/assets/js/dashboard/util/filters.js+++ b/assets/js/dashboard/util/filters.js@@ -40,18 +40,18 @@ export const FILTER_OPERATIONS_DISPLAY_NAMES = {[FILTER_OPERATIONS.has_not_done]: 'is not'}-export function supportsIsNot(filterName) {- return !['goal', 'prop_key'].includes(filterName)+function supportsIsNot(filterKey) {+ return filterKey !== 'goal'}-export function supportsContains(filterName) {+function supportsContains(filterKey) {return !['screen'].concat(FILTER_GROUP_TO_DIMENSIONS['location'])- .includes(filterName)+ .includes(filterKey)}-export function supportsHasDoneNot(filterName) {- return filterName === 'goal'+function supportsHasDoneNot(filterKey) {+ return filterKey === 'goal'}export function getSupportedOperations(filterKey) {@@ -271,15 +271,9 @@ function remapToApiFilter([operation, filterKey, clauses, ...modifiers]) {}}-export function getFilterDimension([_operation, filterKey, _clauses]) {- return filterKey.startsWith(EVENT_PROPS_PREFIX) ? 'props' : filterKey-}-export const formattedFilters = {goal: 'Goal',props: 'Property',- prop_key: 'Property',- prop_value: 'Value',source: 'Source',channel: 'Channel',utm_medium: 'UTM medium',diff --git a/e2e/tests/dashboard/filtering.spec.ts b/e2e/tests/dashboard/filtering.spec.tsindex 57ead268fd..d290400be0 100644--- a/e2e/tests/dashboard/filtering.spec.ts+++ b/e2e/tests/dashboard/filtering.spec.ts@@ -4,11 +4,17 @@ import {filterButton,filterItemButton,openFilterSubmenuItem,- applyFilterButton,- filterRow,- suggestedItem,- filterOperator,- filterOperatorOption+ openPropertyKeys,+ propertyKeySearch,+ propertyKeyOption,+ filterPill,+ filterPillValuesButton,+ filterPillOperatorButton,+ filterOperatorOption,+ filterValueSearch,+ filterValueOption,+ pickFilterValue,+ closeFilterEditor} from '../test-utils'test.describe('page filtering tests', () => {@@ -34,39 +40,37 @@ test.describe('page filtering tests', () => {await page.goto('/' + domain, { waitUntil: 'commit' })- const pageFilterRow = filterRow(page, 'page')- const pageInput = page.getByPlaceholder('Select a Page')-await filterButton(page).click()await openPageFilter(page, 'Page')- await expect(- page.getByRole('heading', { name: 'Filter by Page' })- ).toBeVisible()-- await expect(applyFilterButton(page, { disabled: true })).toBeVisible()- await pageInput.fill('page')+ await expect(filterPill(page, 'Page is')).toBeVisible()+ await expect(filterValueSearch(page)).toBeFocused()- await expect(suggestedItem(pageFilterRow, '/page1')).toBeVisible()- await expect(suggestedItem(pageFilterRow, '/page2')).toBeVisible()- await expect(suggestedItem(pageFilterRow, '/page3')).toBeVisible()- await expect(applyFilterButton(page, { disabled: true })).toBeVisible()+ await filterValueSearch(page).fill('page')- await pageInput.fill('/page1')+ await expect(filterValueOption(page, '/page1')).toBeVisible()+ await expect(filterValueOption(page, '/page2')).toBeVisible()+ await expect(filterValueOption(page, '/page3')).toBeVisible()+ await expect(page).not.toHaveURL(/f=/)- await expect(suggestedItem(pageFilterRow, '/page1')).toBeVisible()- await expect(applyFilterButton(page, { disabled: true })).toBeVisible()+ await filterValueSearch(page).fill('/page1')- await suggestedItem(pageFilterRow, '/page1').click()- await expect(applyFilterButton(page)).toBeVisible()+ await expect(filterValueOption(page, '/page1')).toBeVisible()+ await expect(filterValueOption(page, '/page2')).toBeHidden()- await applyFilterButton(page).click()+ await filterValueOption(page, '/page1').click()await expect(page).toHaveURL(/f=is,page,\/page1/)+ await expect(filterValueOption(page, '/page1')).toHaveAttribute(+ 'aria-selected',+ 'true'+ )++ await closeFilterEditor(page)await expect(- page.getByRole('link', { name: 'Page is /page1' })- ).toHaveAttribute('title', 'Edit filter: Page is /page1')+ filterPillValuesButton(page, 'Page is /page1')+ ).toHaveAttribute('title', 'Page is /page1')})test('filtering by page using different operators', async ({@@ -88,23 +92,16 @@ test.describe('page filtering tests', () => {await page.goto('/' + domain, { waitUntil: 'commit' })- const pageFilterRow = filterRow(page, 'page')- const pageInput = page.getByPlaceholder('Select a Page')-await test.step("'is not' operator", async () => {await filterButton(page).click()await openPageFilter(page, 'Page')- await filterOperator(pageFilterRow).click()- await filterOperatorOption(pageFilterRow, 'is not').click()- await pageInput.fill('page')- await suggestedItem(pageFilterRow, '/page1').click()-- await applyFilterButton(page).click()+ await filterPillOperatorButton(page, 'Page is').click()+ await filterOperatorOption(page, 'is not').click()+ await pickFilterValue(page, { search: 'page', value: '/page1' })+ await closeFilterEditor(page)- await expect(- page.getByRole('link', { name: 'Page is not /page1' })- ).toBeVisible()+ await expect(filterPill(page, 'Page is not /page1')).toBeVisible()await expect(page).toHaveURL(/f=is_not,page,\/page1/)@@ -119,16 +116,15 @@ test.describe('page filtering tests', () => {await filterButton(page).click()await openPageFilter(page, 'Page')- await filterOperator(pageFilterRow).click()- await filterOperatorOption(pageFilterRow, 'contains').click()- await pageInput.fill('page1')- await suggestedItem(pageFilterRow, "Filter by 'page1'").click()-- await applyFilterButton(page).click()+ await filterPillOperatorButton(page, 'Page is').click()+ await filterOperatorOption(page, 'contains').click()+ await pickFilterValue(page, {+ search: 'page1',+ value: "Filter by 'page1'"+ })+ await closeFilterEditor(page)- await expect(- page.getByRole('link', { name: 'Page contains page1' })- ).toBeVisible()+ await expect(filterPill(page, 'Page contains page1')).toBeVisible()await expect(page).toHaveURL(/f=contains,page,page1/)@@ -143,15 +139,16 @@ test.describe('page filtering tests', () => {await filterButton(page).click()await openPageFilter(page, 'Page')- await filterOperator(pageFilterRow).click()- await filterOperatorOption(pageFilterRow, 'does not contain').click()- await pageInput.fill('page1')- await suggestedItem(pageFilterRow, "Filter by 'page1'").click()-- await applyFilterButton(page).click()+ await filterPillOperatorButton(page, 'Page is').click()+ await filterOperatorOption(page, 'does not contain').click()+ await pickFilterValue(page, {+ search: 'page1',+ value: "Filter by 'page1'"+ })+ await closeFilterEditor(page)await expect(- page.getByRole('link', { name: 'Page does not contain page1' })+ filterPill(page, 'Page does not contain page1')).toBeVisible()await expect(page).toHaveURL(/f=contains_not,page,page1/)@@ -169,19 +166,34 @@ test.describe('page filtering tests', () => {await filterButton(page).click()await openPageFilter(page, 'Page')- await pageInput.fill('page')- await suggestedItem(pageFilterRow, '/page2').click()- await pageInput.fill('page')- await suggestedItem(pageFilterRow, '/page3').click()-- await applyFilterButton(page).click()+ await pickFilterValue(page, { search: 'page', value: '/page2' })+ await pickFilterValue(page, { value: '/page3' })+ await closeFilterEditor(page)- await expect(- page.getByRole('link', { name: 'Page is /page2 or /page3' })- ).toBeVisible()+ await expect(filterPill(page, 'Page is /page2 or /page3')).toBeVisible()await expect(page).toHaveURL(/f=is,page,\/page2,\/page3/)})++ await test.step('editing the values and the operator of a filter', async () => {+ await filterPillValuesButton(page, 'Page is /page2 or /page3').click()++ await expect(filterValueOption(page, '/page2')).toHaveAttribute(+ 'aria-selected',+ 'true'+ )+ await filterValueOption(page, '/page2').click()+ await expect(page).toHaveURL(/f=is,page,\/page3(&|$)/)++ await closeFilterEditor(page)+ await expect(filterPill(page, 'Page is /page3')).toBeVisible()++ await filterPillOperatorButton(page, 'Page is /page3').click()+ await filterOperatorOption(page, 'is not').click()++ await expect(filterPill(page, 'Page is not /page3')).toBeVisible()+ await expect(page).toHaveURL(/f=is_not,page,\/page3/)+ })})test('filtering by entry page', async ({ page, request }) => {@@ -203,20 +215,13 @@ test.describe('page filtering tests', () => {await page.goto('/' + domain, { waitUntil: 'commit' })- const entryPageFilterRow = filterRow(page, 'entry_page')- const entryPageInput = page.getByPlaceholder('Select an Entry Page')-await filterButton(page).click()await openPageFilter(page, 'Entry page')- await entryPageInput.fill('page')- await suggestedItem(entryPageFilterRow, '/page1').click()-- await applyFilterButton(page).click()+ await pickFilterValue(page, { search: 'page', value: '/page1' })+ await closeFilterEditor(page)- await expect(- page.getByRole('link', { name: 'Entry page is /page1' })- ).toBeVisible()+ await expect(filterPill(page, 'Entry page is /page1')).toBeVisible()await expect(page).toHaveURL(/f=is,entry_page,\/page1/)})@@ -240,20 +245,13 @@ test.describe('page filtering tests', () => {await page.goto('/' + domain, { waitUntil: 'commit' })- const exitPageFilterRow = filterRow(page, 'exit_page')- const exitPageInput = page.getByPlaceholder('Select an Exit Page')-await filterButton(page).click()await openPageFilter(page, 'Exit page')- await exitPageInput.fill('page')- await suggestedItem(exitPageFilterRow, '/page3').click()-- await applyFilterButton(page).click()+ await pickFilterValue(page, { search: 'page', value: '/page3' })+ await closeFilterEditor(page)- await expect(- page.getByRole('link', { name: 'Exit page is /page3' })- ).toBeVisible()+ await expect(filterPill(page, 'Exit page is /page3')).toBeVisible()await expect(page).toHaveURL(/f=is,exit_page,\/page3/)})@@ -277,20 +275,13 @@ test.describe('hostname filtering tests', () => {await page.goto('/' + domain, { waitUntil: 'commit' })- const hostnameFilterRow = filterRow(page, 'hostname')- const hostnameInput = page.getByPlaceholder('Select a Hostname')-await filterButton(page).click()await hostnameFilterButton(page).click()- await hostnameInput.fill('one')- await suggestedItem(hostnameFilterRow, 'one.example.com').click()-- await applyFilterButton(page).click()+ await pickFilterValue(page, { search: 'one', value: 'one.example.com' })+ await closeFilterEditor(page)- await expect(- page.getByRole('link', { name: 'Hostname is one.example.com' })- ).toBeVisible()+ await expect(filterPill(page, 'Hostname is one.example.com')).toBeVisible()await expect(page).toHaveURL(/f=is,hostname,one.example.com/)})@@ -316,20 +307,13 @@ test.describe('acquisition filtering tests', () => {await page.goto('/' + domain, { waitUntil: 'commit' })await test.step('filtering by source', async () => {- const sourceFilterRow = filterRow(page, 'source')- const sourceInput = page.getByPlaceholder('Select a Source')-await filterButton(page).click()await openSourceFilter(page, 'Source')- await sourceInput.fill('goog')- await suggestedItem(sourceFilterRow, 'Google').click()+ await pickFilterValue(page, { search: 'goog', value: 'Google' })+ await closeFilterEditor(page)- await applyFilterButton(page).click()-- await expect(- page.getByRole('link', { name: 'Source is Google' })- ).toBeVisible()+ await expect(filterPill(page, 'Source is Google')).toBeVisible()await expect(page).toHaveURL(/f=is,source,Google/)@@ -343,20 +327,13 @@ test.describe('acquisition filtering tests', () => {})await test.step('filtering by channel', async () => {- const channelFilterRow = filterRow(page, 'channel')- const channelInput = page.getByPlaceholder('Select a Channel')-await filterButton(page).click()await openSourceFilter(page, 'Channel')- await channelInput.fill('paid')- await suggestedItem(channelFilterRow, 'Paid Search').click()+ await pickFilterValue(page, { search: 'paid', value: 'Paid Search' })+ await closeFilterEditor(page)- await applyFilterButton(page).click()-- await expect(- page.getByRole('link', { name: 'Channel is Paid Search' })- ).toBeVisible()+ await expect(filterPill(page, 'Channel is Paid Search')).toBeVisible()await expect(page).toHaveURL(/f=is,channel,Paid%20Search/)@@ -370,21 +347,17 @@ test.describe('acquisition filtering tests', () => {})await test.step('filtering by referrer URL', async () => {- const referrerFilterRow = filterRow(page, 'referrer')- const referrerInput = page.getByPlaceholder('Select a Referrer URL')-await filterButton(page).click()await openSourceFilter(page, 'Referrer URL')- await referrerInput.fill('guard')- await suggestedItem(referrerFilterRow, 'https://theguardian.com').click()-- await applyFilterButton(page).click()+ await pickFilterValue(page, {+ search: 'guard',+ value: 'https://theguardian.com'+ })+ await closeFilterEditor(page)await expect(- page.getByRole('link', {- name: 'Referrer URL is https://theguardian.com'- })+ filterPill(page, 'Referrer URL is https://theguardian.com')).toBeVisible()await expect(page).toHaveURL(/f=is,referrer,https:\/\/theguardian\.com/)@@ -421,140 +394,51 @@ test.describe('acquisition filtering tests', () => {await page.goto('/' + domain, { waitUntil: 'commit' })- await test.step('filtering by UTM medium', async () => {- const utmMediumFilterRow = filterRow(page, 'utm_medium')- const utmMediumInput = page.getByPlaceholder('Select a UTM Medium')-- await filterButton(page).click()- await openUtmFilter(page, 'UTM medium')-- await utmMediumInput.fill('soc')- await suggestedItem(utmMediumFilterRow, 'social').click()-- await applyFilterButton(page).click()-- await expect(- page.getByRole('link', { name: 'UTM Medium is social' })- ).toBeVisible()-- await expect(page).toHaveURL(/f=is,utm_medium,social/)-- await page- .getByRole('button', {- name: 'Remove filter: UTM Medium is social'- })- .click()-- await expect(page).not.toHaveURL(/f=is,utm_medium,social/)- })-- await test.step('filtering by UTM source', async () => {- const utmSourceFilterRow = filterRow(page, 'utm_source')- const utmSourceInput = page.getByPlaceholder('Select a UTM Source')-- await filterButton(page).click()- await openUtmFilter(page, 'UTM source')-- await utmSourceInput.fill('hunt')- await suggestedItem(utmSourceFilterRow, 'producthunt').click()-- await applyFilterButton(page).click()-- await expect(- page.getByRole('link', { name: 'UTM Source is producthunt' })- ).toBeVisible()-- await expect(page).toHaveURL(/f=is,utm_source,producthunt/)-- await page- .getByRole('button', {- name: 'Remove filter: UTM Source is producthunt'- })- .click()-- await expect(page).not.toHaveURL(/f=is,utm_source,producthunt/)- })-- await test.step('filtering by UTM campaign', async () => {- const utmCampaignFilterRow = filterRow(page, 'utm_campaign')- const utmCampaignInput = page.getByPlaceholder('Select a UTM Campaign')-- await filterButton(page).click()- await openUtmFilter(page, 'UTM campaign')-- await utmCampaignInput.fill('ads')- await suggestedItem(utmCampaignFilterRow, 'ads').click()-- await applyFilterButton(page).click()-- await expect(- page.getByRole('link', { name: 'UTM Campaign is ads' })- ).toBeVisible()-- await expect(page).toHaveURL(/f=is,utm_campaign,ads/)-- await page- .getByRole('button', {- name: 'Remove filter: UTM Campaign is ads'- })- .click()-- await expect(page).not.toHaveURL(/f=is,utm_campaign,ads/)- })-- await test.step('filtering by UTM term', async () => {- const utmTermFilterRow = filterRow(page, 'utm_term')- const utmTermInput = page.getByPlaceholder('Select a UTM Term')-- await filterButton(page).click()- await openUtmFilter(page, 'UTM term')-- await utmTermInput.fill('pos')- await suggestedItem(utmTermFilterRow, 'post').click()-- await applyFilterButton(page).click()-- await expect(- page.getByRole('link', { name: 'UTM Term is post' })- ).toBeVisible()-- await expect(page).toHaveURL(/f=is,utm_term,post/)-- await page- .getByRole('button', {- name: 'Remove filter: UTM Term is post'- })- .click()-- await expect(page).not.toHaveURL(/f=is,utm_term,post/)- })-- await test.step('filtering by UTM content', async () => {- const utmContentFilterRow = filterRow(page, 'utm_content')- const utmContentInput = page.getByPlaceholder('Select a UTM Content')-- await filterButton(page).click()- await openUtmFilter(page, 'UTM content')-- await utmContentInput.fill('web')- await suggestedItem(utmContentFilterRow, 'website').click()-- await applyFilterButton(page).click()-- await expect(- page.getByRole('link', { name: 'UTM Content is website' })- ).toBeVisible()-- await expect(page).toHaveURL(/f=is,utm_content,website/)-- await page- .getByRole('button', {- name: 'Remove filter: UTM Content is website'- })- .click()-- await expect(page).not.toHaveURL(/f=is,utm_content,website/)- })+ const utmSteps = [+ { item: 'UTM medium', key: 'utm_medium', search: 'soc', value: 'social' },+ {+ item: 'UTM source',+ key: 'utm_source',+ search: 'hunt',+ value: 'producthunt'+ },+ {+ item: 'UTM campaign',+ key: 'utm_campaign',+ search: 'ads',+ value: 'ads'+ },+ { item: 'UTM term', key: 'utm_term', search: 'pos', value: 'post' },+ {+ item: 'UTM content',+ key: 'utm_content',+ search: 'web',+ value: 'website'+ }+ ]++ for (const { item, key, search, value } of utmSteps) {+ await test.step(`filtering by ${item}`, async () => {+ const pillName = `${item} is ${value}`+ const url = new RegExp(`f=is,${key},${value}`)++ await filterButton(page).click()+ await openUtmFilter(page, item)++ await pickFilterValue(page, { search, value })+ await closeFilterEditor(page)++ await expect(filterPill(page, pillName)).toBeVisible()++ await expect(page).toHaveURL(url)++ await page+ .getByRole('button', { name: `Remove filter: ${pillName}` })+ .click()++ await expect(page).not.toHaveURL(url)+ })+ }})})@@ -582,59 +466,38 @@ test.describe('location filtering tests', () => {await page.goto('/' + domain, { waitUntil: 'commit' })await test.step('filtering by country', async () => {- const countryFilterRow = filterRow(page, 'country')- const countryInput = page.getByPlaceholder('Select a Country')-await filterButton(page).click()await openLocationFilter(page, 'Country')- await countryInput.fill('est')- await suggestedItem(countryFilterRow, 'Estonia').click()+ await pickFilterValue(page, { search: 'est', value: 'Estonia' })+ await closeFilterEditor(page)- await applyFilterButton(page).click()-- await expect(- page.getByRole('link', { name: 'Country is Estonia' })- ).toBeVisible()+ await expect(filterPill(page, 'Country is Estonia')).toBeVisible()await expect(page).toHaveURL(/f=is,country,EE/)})await test.step('filtering by region', async () => {- const regionFilterRow = filterRow(page, 'region')- const regionInput = page.getByPlaceholder('Select a Region')-await filterButton(page).click()await openLocationFilter(page, 'Region')- await regionInput.fill('har')- await suggestedItem(regionFilterRow, 'Harjumaa').click()+ await pickFilterValue(page, { search: 'har', value: 'Harjumaa' })+ await closeFilterEditor(page)- await applyFilterButton(page).click()-- await expect(- page.getByRole('link', { name: 'Region is Harjumaa' })- ).toBeVisible()+ await expect(filterPill(page, 'Region is Harjumaa')).toBeVisible()await expect(page).toHaveURL(/f=is,region,EE-37/)await expect(page).toHaveURL(/f=is,country,EE/)})await test.step('filtering by city', async () => {- const cityFilterRow = filterRow(page, 'city')- const cityInput = page.getByPlaceholder('Select a City')-await filterButton(page).click()await openLocationFilter(page, 'City')- await cityInput.click()- await suggestedItem(cityFilterRow, 'Tallinn').click()+ await pickFilterValue(page, { value: 'Tallinn' })+ await closeFilterEditor(page)- await applyFilterButton(page).click()-- await expect(- page.getByRole('link', { name: 'City is Tallinn' })- ).toBeVisible()+ await expect(filterPill(page, 'City is Tallinn')).toBeVisible()await expect(page).toHaveURL(/f=is,city,588409/)await expect(page).toHaveURL(/f=is,region,EE-37/)@@ -661,9 +524,6 @@ test.describe('screen size filtering tests', () => {await page.goto('/' + domain, { waitUntil: 'commit' })- const screenSizeFilterRow = filterRow(page, 'screen')- const screenSizeInput = page.getByPlaceholder('Select a Screen size')-await filterButton(page).click()await screenSizeFilterButton(page).click()@@ -671,14 +531,10 @@ test.describe('screen size filtering tests', () => {// suggestions found but there are 2 pageview in the top stats.// When navigating live via `MIX_ENV=e2e_test iex -S mix`,// all works fine. Puzzling.- await screenSizeInput.fill('mob')- await suggestedItem(screenSizeFilterRow, 'Mobile').click()+ await pickFilterValue(page, { search: 'mob', value: 'Mobile' })+ await closeFilterEditor(page)- await applyFilterButton(page).click()-- await expect(- page.getByRole('link', { name: 'Screen size is Mobile' })- ).toBeVisible()+ await expect(filterPill(page, 'Screen size is Mobile')).toBeVisible()await expect(page).toHaveURL(/f=is,screen,Mobile/)})@@ -703,43 +559,25 @@ test.describe('browser filtering tests', () => {await page.goto('/' + domain, { waitUntil: 'commit' })await test.step('filtering by browser type', async () => {- const browserFilterRow = filterRow(page, 'browser')- const browserInput = page.getByPlaceholder('Select a Browser', {- exact: true- })-await filterButton(page).click()await openBrowserFilter(page, 'Browser')- await browserInput.fill('chrom')- await suggestedItem(browserFilterRow, 'Chrome').click()-- await applyFilterButton(page).click()+ await pickFilterValue(page, { search: 'chrom', value: 'Chrome' })+ await closeFilterEditor(page)- await expect(- page.getByRole('link', { name: 'Browser is Chrome' })- ).toBeVisible()+ await expect(filterPill(page, 'Browser is Chrome')).toBeVisible()await expect(page).toHaveURL(/f=is,browser,Chrome/)})await test.step('filtering by browser version', async () => {- const browserVersionFilterRow = filterRow(page, 'browser_version')- const browserVersionInput = page.getByPlaceholder(- 'Select a Browser Version'- )-await filterButton(page).click()await openBrowserFilter(page, 'Browser version')- await browserVersionInput.fill('14')- await suggestedItem(browserVersionFilterRow, '14.0.7').click()+ await pickFilterValue(page, { search: '14', value: '14.0.7' })+ await closeFilterEditor(page)- await applyFilterButton(page).click()-- await expect(- page.getByRole('link', { name: 'Browser version is 14.0.7' })- ).toBeVisible()+ await expect(filterPill(page, 'Browser version is 14.0.7')).toBeVisible()await expect(page).toHaveURL(/f=is,browser_version,14\.0\.7/)await expect(page).toHaveURL(/f=is,browser,Chrome/)@@ -776,48 +614,29 @@ test.describe('operating system filtering tests', () => {await page.goto('/' + domain, { waitUntil: 'commit' })await test.step('filtering by operating system type', async () => {- const operatingSystemFilterRow = filterRow(page, 'os')- const operatingSystemInput = page.getByPlaceholder(- 'Select an Operating system',- { exact: true }- )-await filterButton(page).click()await openOperatingSystemFilter(page, 'Operating system')// The same problem as in the case of screen size filter test.- await operatingSystemInput.click()- await suggestedItem(operatingSystemFilterRow, 'Windows').click()-- await applyFilterButton(page).click()+ await pickFilterValue(page, { value: 'Windows' })+ await closeFilterEditor(page)await expect(- page.getByRole('link', { name: 'Operating System is Windows' })+ filterPill(page, 'Operating system is Windows')).toBeVisible()await expect(page).toHaveURL(/f=is,os,Windows/)})await test.step('filtering by operating system version', async () => {- const operatingSystemVersionFilterRow = filterRow(page, 'os_version')- const operatingSystemVersionInput = page.getByPlaceholder(- 'Select an Operating system version'- )-await filterButton(page).click()- await openFilterSubmenuItem(- page,- 'Operating system',- 'Operating system version'- )-- await operatingSystemVersionInput.click()- await suggestedItem(operatingSystemVersionFilterRow, '11').click()+ await openOperatingSystemFilter(page, 'Operating system version')- await applyFilterButton(page).click()+ await pickFilterValue(page, { value: '11' })+ await closeFilterEditor(page)await expect(- page.getByRole('link', { name: 'Operating system version is 11' })+ filterPill(page, 'Operating system version is 11')).toBeVisible()await expect(page).toHaveURL(/f=is,os_version,11/)@@ -846,48 +665,31 @@ test.describe('goal filtering tests', () => {await page.goto('/' + domain, { waitUntil: 'commit' })- const goalFilterRow = filterRow(page, 'goal')- const goalInput = goalFilterRow.getByPlaceholder('Select a Goal')-await test.step('single goal filter', async () => {await filterButton(page).click()await goalFilterButton(page).click()- await goalInput.fill('page1')- await suggestedItem(goalFilterRow, 'Visit /page1').click()+ await pickFilterValue(page, { search: 'page1', value: 'Visit /page1' })+ await closeFilterEditor(page)- await applyFilterButton(page).click()-- await expect(- page.getByRole('link', { name: 'Goal is Visit /page1' })- ).toBeVisible()+ await expect(filterPill(page, 'Goal is Visit /page1')).toBeVisible()await expect(page).toHaveURL(/f=is,goal,Visit%20\/page1/)})- const goalFilterRow2 = filterRow(page, 'goal1')- const goalInput2 = goalFilterRow2.getByPlaceholder('Select a Goal')-await test.step('multiple goal filters', async () => {- await page.getByRole('link', { name: 'Goal is Visit /page1' }).click()-- await page.getByText('+ Add another').click()-- await filterOperator(goalFilterRow2).click()- await filterOperatorOption(goalFilterRow2, 'is not').click()-- await goalInput2.fill('page2')- await suggestedItem(goalFilterRow2, 'Visit /page2').click()+ await filterButton(page).click()+ await goalFilterButton(page).click()- await applyFilterButton(page).click()+ await expect(filterPill(page, 'Goal is')).toBeVisible()- await expect(- page.getByRole('link', { name: 'Goal is Visit /page1' })- ).toBeVisible()+ await filterPillOperatorButton(page, 'Goal is').click()+ await filterOperatorOption(page, 'is not').click()+ await pickFilterValue(page, { search: 'page2', value: 'Visit /page2' })+ await closeFilterEditor(page)- await expect(- page.getByRole('link', { name: 'Goal is not Visit /page2' })- ).toBeVisible()+ await expect(filterPill(page, 'Goal is Visit /page1')).toBeVisible()+ await expect(filterPill(page, 'Goal is not Visit /page2')).toBeVisible()await expect(page).toHaveURL(/f=is,goal,Visit%20\/page1/)await expect(page).toHaveURL(/f=has_not_done,goal,Visit%20\/page2/)@@ -896,9 +698,6 @@ test.describe('goal filtering tests', () => {})test.describe('property filtering tests', () => {- const propFilterButton = (page: Page) =>- page.getByTestId('filtermenu').getByRole('link', { name: 'Property' })-test('filtering by properties', async ({ page, request }) => {const { domain } = await setupSite({ page, request })@@ -921,58 +720,52 @@ test.describe('property filtering tests', () => {await page.goto('/' + domain, { waitUntil: 'commit' })- const propFilterRow = filterRow(page, 'props')- const propNameInput = propFilterRow.getByPlaceholder('Property')- const propValueInput = propFilterRow.getByPlaceholder('Value')-await test.step('single property filter', async () => {await filterButton(page).click()- await propFilterButton(page).click()+ await openPropertyKeys(page)++ await propertyKeySearch(page).fill('logged')+ await propertyKeyOption(page, 'logged_in').click()- await propNameInput.fill('logged')- await suggestedItem(propFilterRow, 'logged_in').click()- await propValueInput.fill('false')- await suggestedItem(propFilterRow, 'false').click()+ await expect(filterPill(page, "Property 'logged_in' is")).toBeVisible()- await applyFilterButton(page).click()+ await pickFilterValue(page, { search: 'false', value: 'false' })+ await closeFilterEditor(page)await expect(- page.getByRole('link', { name: 'Property logged_in is false' })+ filterPill(page, "Property 'logged_in' is false")).toBeVisible()await expect(page).toHaveURL(/f=is,props:logged_in,false/)})- const propFilterRow2 = filterRow(page, 'props1')- const propNameInput2 = propFilterRow2.getByPlaceholder('Property')- const propValueInput2 = propFilterRow2.getByPlaceholder('Value')-await test.step('multiple property filters', async () => {- await page- .getByRole('link', { name: 'Property logged_in is false' })- .click()+ await filterButton(page).click()+ await openPropertyKeys(page)- await page.getByText('+ Add another').click()+ await propertyKeySearch(page).fill('logged')+ await expect(propertyKeyOption(page, 'logged_in')).toHaveAttribute(+ 'aria-disabled',+ 'true'+ )- await propNameInput2.fill('browser')- await suggestedItem(propFilterRow2, 'browser_language').click()- await filterOperator(propFilterRow2).click()- await filterOperatorOption(propFilterRow2, 'is not').click()- await propValueInput2.fill('US')- await suggestedItem(propFilterRow2, 'en_US').click()+ await propertyKeySearch(page).fill('browser')+ await propertyKeyOption(page, 'browser_language').click()- await applyFilterButton(page).click()+ await filterPillOperatorButton(+ page,+ "Property 'browser_language' is"+ ).click()+ await filterOperatorOption(page, 'is not').click()+ await pickFilterValue(page, { search: 'US', value: 'en_US' })+ await closeFilterEditor(page)await expect(- page.getByRole('link', {- name: 'Property logged_in is false'- })+ filterPill(page, "Property 'logged_in' is false")).toBeVisible()await expect(- page.getByRole('link', {- name: 'Property browser_language is not en_US'- })+ filterPill(page, "Property 'browser_language' is not en_US")).toBeVisible()await expect(page).toHaveURL(/f=is,props:logged_in,false/)diff --git a/e2e/tests/dashboard/general.spec.ts b/e2e/tests/dashboard/general.spec.tsindex f96449a5a6..38dabbe193 100644--- a/e2e/tests/dashboard/general.spec.ts+++ b/e2e/tests/dashboard/general.spec.ts@@ -6,7 +6,11 @@ import {populateStats,createSharedLink} from '../fixtures'-import { openFilterSubmenuItem } from '../test-utils'+import {+ openFilterSubmenuItem,+ pickFilterValue,+ closeFilterEditor+} from '../test-utils'test('dashboard renders for logged in user', async ({ page, request }) => {const { domain } = await setupSite({ page, request })@@ -155,12 +159,16 @@ test('tab selection user preferences are preserved across reloads', async ({expect(currentTab).toEqual('exitPages')})-test('back navigation closes the modal', async ({ page, request, baseURL }) => {+test('back navigation removes an applied filter', async ({+ page,+ request,+ baseURL+}) => {const { domain } = await setupSite({ page, request })await populateStats({request,domain,- events: [{ name: 'pageview' }]+ events: [{ name: 'pageview', pathname: '/page1' }]})await page.goto('/' + domain, { waitUntil: 'commit' })@@ -168,8 +176,10 @@ test('back navigation closes the modal', async ({ page, request, baseURL }) => {await page.getByRole('button', { name: 'Filter' }).click()await openFilterSubmenuItem(page, 'Page', 'Page')+ await pickFilterValue(page, { value: '/page1' })+ await closeFilterEditor(page)- await expect(page).toHaveURL(baseURL + '/' + domain + '/filter/page')+ await expect(page).toHaveURL(/f=is,page,\/page1/)await page.goBack()diff --git a/e2e/tests/dashboard/segments.spec.ts b/e2e/tests/dashboard/segments.spec.tsindex 876220d813..0829d21f91 100644--- a/e2e/tests/dashboard/segments.spec.ts+++ b/e2e/tests/dashboard/segments.spec.ts@@ -6,10 +6,10 @@ import {openFilterSubmenuItem,openSegmentsSubmenu,closeFilterMenu,- filterSubmenuButton,- applyFilterButton,- filterRow,- suggestedItem,+ filterItemButton,+ filterPill,+ pickFilterValue,+ closeFilterEditor,modal} from '../test-utils'@@ -43,7 +43,10 @@ const setupSiteAndStats = async ({const openSegmentPillMenu = async (page: Page, segmentName: string) => {await page- .getByRole('button', { name: `Segment is ${segmentName}`, exact: true })+ .getByRole('button', {+ name: `Open menu: Segment is ${segmentName}`,+ exact: true+ }).click()}@@ -60,32 +63,22 @@ const segmentItemButton = (page: Page, name: string) =>filterSubmenuSegmentItem(page, name)const addSourceFilter = async (page: Page, sourceLabel: string) => {- const sourceFilterRow = filterRow(page, 'source')- const sourceInput = page.getByPlaceholder('Select a Source')-await filterButton(page).click()await openFilterSubmenuItem(page, 'Source', 'Source')- await sourceInput.click()- await suggestedItem(sourceFilterRow, sourceLabel).click()-- await applyFilterButton(page).click()+ await pickFilterValue(page, { value: sourceLabel })+ await closeFilterEditor(page)const url = new RegExp(`f=is,source,${sourceLabel}`)await expect(page).toHaveURL(url)}const addUtmSourceFilter = async (page: Page, utmSource: string) => {- const utmSourceFilterRow = filterRow(page, 'utm_source')- const utmSourceInput = page.getByPlaceholder('Select a UTM Source')-await filterButton(page).click()await openFilterSubmenuItem(page, 'UTM tags', 'UTM source')- await utmSourceInput.click()- await suggestedItem(utmSourceFilterRow, utmSource).click()-- await applyFilterButton(page).click()+ await pickFilterValue(page, { value: utmSource })+ await closeFilterEditor(page)const url = new RegExp(`f=is,utm_source,${utmSource}`)await expect(page).toHaveURL(url)@@ -250,9 +243,7 @@ test('creating a segment from a combination of segment and a filter is not allowawait createPersonalSegment(page, 'Traffic from Google')await addUtmSourceFilter(page, 'Adwords')- await expect(- page.getByRole('link', { name: 'UTM source is Adwords' })- ).toBeVisible()+ await expect(filterPill(page, 'UTM source is Adwords')).toBeVisible()await expect(page.getByRole('button', {name: 'Remove filter: Segment is Traffic from Google'@@ -301,12 +292,8 @@ test('editing an existing segment', async ({ page, request }) => {await enterEditMode(page, 'Ads from Google')- await expect(- page.getByRole('link', { name: 'UTM source is Adwords' })- ).toBeVisible()- await expect(- page.getByRole('link', { name: 'Source is Google' })- ).toBeVisible()+ await expect(filterPill(page, 'UTM source is Adwords')).toBeVisible()+ await expect(filterPill(page, 'Source is Google')).toBeVisible()await page.getByRole('link', { name: 'Cancel' }).click()@@ -351,9 +338,7 @@ test('duplicating a segment', async ({ page, request }) => {await enterEditMode(page, 'Google copy')- await expect(- page.getByRole('link', { name: 'Source is Google' })- ).toBeVisible()+ await expect(filterPill(page, 'Source is Google')).toBeVisible()await page.getByRole('link', { name: 'Cancel' }).click()@@ -391,7 +376,7 @@ test('deleting segment', async ({ page, request }) => {await filterButton(page).click()// The only segment is gone, so the filter menu no longer offers segments at all.- await expect(filterSubmenuButton(page, 'Segment')).toBeHidden()+ await expect(filterItemButton(page, 'Segment')).toBeHidden()})test('cancelling edited segment without saving', async ({ page, request }) => {@@ -413,10 +398,6 @@ test('cancelling edited segment without saving', async ({ page, request }) => {await enterEditMode(page, 'Traffic from Google')- await expect(- page.getByRole('link', { name: 'UTM source is Adwords' })- ).toBeHidden()- await expect(- page.getByRole('link', { name: 'Source is Google' })- ).toBeVisible()+ await expect(filterPill(page, 'UTM source is Adwords')).toBeHidden()+ await expect(filterPill(page, 'Source is Google')).toBeVisible()})diff --git a/e2e/tests/test-utils.ts b/e2e/tests/test-utils.tsindex db309cc7af..ade7b67446 100644--- a/e2e/tests/test-utils.ts+++ b/e2e/tests/test-utils.ts@@ -93,13 +93,10 @@ const filterMenu = (page: Page) => page.getByTestId('filtermenu')const filterSubmenu = (page: Page) => page.getByTestId('filtermenu-submenu')export const filterItemButton = (page: Page, label: HasTextArg) =>- filterMenu(page).getByRole('link', { name: label, exact: true })--export const filterSubmenuButton = (page: Page, label: HasTextArg) =>filterMenu(page).getByRole('button', { name: label, exact: true })export const filterSubmenuItemButton = (page: Page, label: HasTextArg) =>- filterSubmenu(page).getByRole('link', { name: label, exact: true })+ filterSubmenu(page).getByRole('button', { name: label, exact: true })export const filterSubmenuSegmentItem = (page: Page, name: HasTextArg) =>filterSubmenu(page).getByRole('link').filter({ hasText: name })@@ -109,12 +106,12 @@ export const openFilterSubmenuItem = async (row: string,item: string) => {- await filterSubmenuButton(page, row).click()+ await filterItemButton(page, row).click()await filterSubmenuItemButton(page, item).click()}export const openSegmentsSubmenu = (page: Page) =>- filterSubmenuButton(page, 'Segment').click()+ filterItemButton(page, 'Segment').click()// Waits for the panel to unmount. Reopening the menu during its closing// animation leaves the panel unmounted.@@ -123,23 +120,53 @@ export const closeFilterMenu = async (page: Page) => {await expect(filterMenu(page)).toBeHidden()}-export const applyFilterButton = (page: Page, { disabled = false } = {}) =>- page.getByRole('button', {- name: 'Apply filter',- disabled- })+export const openPropertyKeys = (page: Page) =>+ filterItemButton(page, 'Property').click()++export const propertyKeySearch = (page: Page) =>+ page.getByRole('combobox', { name: 'Properties' })++export const propertyKeyOption = (page: Page, key: string) =>+ page+ .getByRole('listbox', { name: 'Properties' })+ .getByRole('option', { name: key, exact: true })++export const filterPill = (page: Page, name: string) =>+ page.getByRole('group', { name, exact: true })++export const filterPillValuesButton = (page: Page, name: string) =>+ page.getByRole('button', { name: `Edit filter: ${name}`, exact: true })++export const filterPillOperatorButton = (page: Page, name: string) =>+ page.getByRole('button', { name: `Change operator: ${name}`, exact: true })-export const filterRow = (page: Page, key: string) =>- page.getByTestId(`filter-row-${key}`)+export const filterOperatorOption = (page: Page, option: string) =>+ page+ .getByRole('group', { name: 'Operators' })+ .getByRole('button', { name: option, exact: true })-export const suggestedItem = (scoped: Locator, url: string) =>- scoped.getByRole('listitem').filter({ hasText: url })+export const filterValueSearch = (page: Page) =>+ page.getByRole('combobox', { name: /^Values/ })-export const filterOperator = (scoped: Locator) =>- scoped.getByTestId('filter-operator')+export const filterValueOption = (page: Page, label: string) =>+ page+ .getByRole('listbox', { name: /^Values/ })+ .getByRole('option', { name: label, exact: true })-export const filterOperatorOption = (scoped: Locator, option: HasTextArg) =>- scoped.getByTestId('filter-operator-option').filter({ hasText: option })+export const pickFilterValue = async (+ page: Page,+ { search, value }: { search?: string; value: string }+) => {+ if (search !== undefined) {+ await filterValueSearch(page).fill(search)+ }+ await filterValueOption(page, value).click()+}++export const closeFilterEditor = async (page: Page) => {+ await page.keyboard.press('Escape')+ await expect(page.getByRole('listbox', { name: /^Values/ })).toBeHidden()+}type HaveTextArg = string | RegExp | ReadonlyArray<string | RegExp>type HasTextArg = string | RegExp