import { deburr } from "es-toolkit/compat"; import { CheckmarkIcon } from "outline-icons"; import * as React from "react"; import { useTranslation } from "react-i18next"; import styled from "styled-components"; import { breakpoint } from "@shared/styles/breakpoint"; import { MOBILE_TOUCH_TARGET } from "@shared/constants"; import { s } from "@shared/styles"; import type { FetchPageParams } from "~/stores/base/Store"; import Button, { Inner } from "~/components/Button"; import Scrollable from "~/components/Scrollable"; import Text from "~/components/Text"; import useMobile from "~/hooks/useMobile"; import Input, { NativeInput, Outline } from "./Input"; import type { PaginatedItem } from "./PaginatedList"; import PaginatedList from "./PaginatedList"; import { Drawer, DrawerContent, DrawerTitle, DrawerTrigger, } from "./primitives/Drawer"; import { MenuProvider } from "./primitives/Menu/MenuContext"; import { Menu, MenuContent, MenuTrigger, MenuButton } from "./primitives/Menu"; import * as MenuComponents from "./primitives/components/Menu"; import { MenuIconWrapper } from "./primitives/components/Menu"; export interface TFilterOption extends PaginatedItem { key: string; label: string; icon?: React.ReactNode; } type Props = { options: TFilterOption[]; selectedKeys: (string | null | undefined)[]; defaultLabel?: string; className?: string; onSelect: (key: string | null | undefined) => void; showFilter?: boolean; showIcons?: boolean; fetchQuery?: (options: FetchPageParams) => Promise; fetchQueryOptions?: Record; disclosure?: boolean; /** Custom element that opens the options, defaults to a button showing the selection. */ trigger?: React.ReactElement; /** Whether the options are open when the component mounts. */ defaultOpen?: boolean; /** Callback when the options open or close. */ onOpenChange?: (open: boolean) => void; }; const FilterOptions = ({ options, selectedKeys, className, onSelect, showFilter, showIcons = true, fetchQuery, fetchQueryOptions, disclosure = true, trigger: customTrigger, defaultOpen = false, onOpenChange, ...rest }: Props) => { const { t } = useTranslation(); const isMobile = useMobile(); const searchInputRef = React.useRef(null); const listRef = React.useRef(null); const [open, setOpenState] = React.useState(defaultOpen); // A menu that mounts open shows at once; later opens animate as usual. const [skipAnimation, setSkipAnimation] = React.useState(defaultOpen); const setOpen = React.useCallback( (value: boolean) => { setOpenState(value); if (!value) { setSkipAnimation(false); } onOpenChange?.(value); }, [onOpenChange] ); const selectedItems = options.filter((option) => selectedKeys.includes(option.key) ); const [query, setQuery] = React.useState(""); // Defer filtering so typing in the search input stays responsive. const deferredQuery = React.useDeferredValue(query); const selectedLabel = selectedItems.length ? selectedItems.map((selected) => selected.label).join(", ") : ""; const renderItem = React.useCallback( (option: TFilterOption) => { const handleClick = () => { onSelect(option.key); setOpen(false); }; const icon = option.icon && showIcons ? ( {option.icon} ) : undefined; // On mobile the options render inside a Drawer (bottom sheet) rather than // a Radix dropdown menu, so use the raw menu components directly instead // of the dropdown-bound MenuButton which expects a menu root context. if (isMobile) { return ( {icon} {option.label} {selectedKeys.includes(option.key) ? ( ) : null} ); } return ( ); }, [onSelect, setOpen, showIcons, selectedKeys, isMobile] ); const handleFilter = React.useCallback( (ev: React.ChangeEvent) => { setQuery(ev.target.value); }, [] ); const filteredOptions = React.useMemo(() => { const normalizedQuery = deburr(deferredQuery.toLowerCase()); const filtered = deferredQuery ? options.filter((option) => deburr(option.label).toLowerCase().includes(normalizedQuery) ) : options; return filtered.sort((a, b) => { const aSelected = selectedKeys.includes(a.key); const bSelected = selectedKeys.includes(b.key); // Selected items come first if (aSelected && !bSelected) { return -1; } if (!aSelected && bSelected) { return 1; } // If both have the same selection state and there's a query, // sort options starting with query first if (deferredQuery) { const aStartsWith = deburr(a.label) .toLowerCase() .startsWith(normalizedQuery); const bStartsWith = deburr(b.label) .toLowerCase() .startsWith(normalizedQuery); if (aStartsWith && !bStartsWith) { return -1; } if (!aStartsWith && bStartsWith) { return 1; } } return 0; }); }, [options, deferredQuery, selectedKeys]); const handleKeyDown = React.useCallback( (ev: React.KeyboardEvent) => { if (ev.nativeEvent.isComposing || ev.shiftKey) { return; } // Stop all keyboard events from propagating to prevent Radix UI menu // from handling them and potentially moving focus ev.stopPropagation(); switch (ev.key) { case "Escape": setOpen(false); break; case "Enter": if (filteredOptions.length === 1) { ev.preventDefault(); onSelect(filteredOptions[0].key); setOpen(false); } break; case "ArrowDown": ev.preventDefault(); (listRef.current?.firstElementChild as HTMLElement)?.focus(); break; default: break; } }, [filteredOptions, onSelect, setOpen] ); const handleEscapeFromList = React.useCallback((ev: React.KeyboardEvent) => { searchInputRef.current?.focus(); if (ev.key === "Backspace") { setQuery((prev) => prev.slice(0, -1)); } }, []); React.useEffect(() => { if (open) { // Avoid auto-focusing on mobile as it immediately pops the on-screen // keyboard over the drawer. if (!isMobile) { searchInputRef.current?.focus(); } } else { setQuery(""); } }, [open, isMobile]); const showFilterInput = showFilter || options.length > 10; const defaultLabel = rest.defaultLabel || t("Filter options"); const trigger = customTrigger ?? ( {selectedItems.length ? selectedLabel : defaultLabel} ); const list = ( listRef={listRef} options={{ query, ...fetchQueryOptions }} items={filteredOptions} fetch={fetchQuery} renderItem={renderItem} onEscape={handleEscapeFromList} heading={showFilterInput && !isMobile ? : undefined} empty={} /> ); // On mobile render the options inside a Drawer (bottom sheet) to match the // popover style used by context menus across the app. if (isMobile) { return ( {trigger} {defaultLabel} {showFilterInput && ( )} {list} ); } return ( {trigger} {list} {showFilterInput && ( )} ); }; const Empty = () => { const { t } = useTranslation(); return ( <> {t("No results")} ); }; const Spacer = styled.div` height: 30px; `; const SearchInput = styled(Input)` position: absolute; width: 100%; border: none; border-top-left-radius: 6px; border-top-right-radius: 6px; overflow: hidden; margin: 0; top: 0; left: 0; right: 0; ${Outline} { border: none; border-radius: 0; border-bottom: 1px solid ${s("divider")}; background: ${s("menuBackground")}; margin: 0; } ${NativeInput} { font-size: 14px; } `; const MobileSearchInput = styled(Input)` /* "none" keeps an auto basis so the input retains its natural height; a flexible/0% basis would collapse it and overlap the list below. */ flex: none; margin: 0 6px 6px; ${NativeInput} { /* 16px avoids iOS zooming the viewport when the input is focused. */ font-size: 16px; } `; const StyledScrollable = styled(Scrollable)` max-height: 75vh; `; export const StyledButton = styled(Button)` box-shadow: none; text-transform: none; border-color: transparent; height: auto; &:hover { background: transparent; } ${Inner} { line-height: 28px; min-height: auto; } ${breakpoint("mobile", "tablet")` && { height: ${MOBILE_TOUCH_TARGET}px; } && ${Inner} { min-height: ${MOBILE_TOUCH_TARGET}px; } `}; `; export default FilterOptions;