diff --git a/.claude/skills/verify-outline/journeys/search-filters.mjs b/.claude/skills/verify-outline/journeys/search-filters.mjs new file mode 100644 index 0000000000..e18ddd8b48 --- /dev/null +++ b/.claude/skills/verify-outline/journeys/search-filters.mjs @@ -0,0 +1,156 @@ +// Drive the search filter bar: pinned chips, the "Filter" add menu, a pending +// chip that opens its options, a toggle filter, and removing a filter. +// Args: query= (a word in a document title, required), collection= (required). +export default async ({ page, click, step, args, log, psql, literal }) => { + if (!args.query || !args.collection) { + throw new Error("query= and collection= are required"); + } + await page.goto("/search"); + await page.waitForLoadState("networkidle"); + await step("empty"); + + // Every filter is available before a query is typed. + for (const name of [/^Collection$/, /^Edited by$/, /^Status/]) { + await page.getByRole("button", { name }).waitFor(); + } + await click(page.getByRole("button", { name: "More filters" })); + for (const name of ["Updated", "Created by", "Created", "Template", "Title only"]) { + await page.getByRole("menuitem", { name, exact: true }).waitFor(); + } + await step("empty-add-menu"); + await page.keyboard.press("Escape"); + + // A filter alone, with no query, lists results. + await click(page.getByRole("button", { name: "More filters" })); + await click(page.getByRole("menuitem", { name: "Updated", exact: true })); + await click(page.getByRole("menuitem", { name: "Past week" })); + await page.waitForURL(/updatedAt\.gte=-P1W/); + await page.getByRole("link", { name: new RegExp(args.query) }).last().waitFor(); + await step("filter-without-query"); + await click(page.getByRole("button", { name: "Remove filter" })); + await page.waitForURL((url) => !url.search.includes("updatedAt")); + + // A toggle filter alone, with no query, lists results. + await click(page.getByRole("button", { name: "More filters" })); + await click(page.getByRole("menuitem", { name: "Title only" })); + await page.waitForURL(/titleOnly=true/); + await page.getByRole("link", { name: new RegExp(args.query) }).last().waitFor(); + await step("title-only-without-query"); + await click(page.getByRole("button", { name: "Remove filter" })); + await page.waitForURL((url) => !url.search.includes("titleOnly")); + + // A document scope alone, with no query, lists results. + const [documentId] = await psql( + `select id from documents where title like ${literal(`%${args.query}%`)}` + ); + await page.goto(`/search?documentId=${documentId}`); + await page.getByRole("link", { name: new RegExp(args.query) }).last().waitFor(); + await step("document-scope-without-query"); + await page.goto("/search"); + + const box = page.getByRole("searchbox"); + await box.fill(args.query); + await box.press("Enter"); + await page.getByRole("link", { name: new RegExp(args.query) }).last().waitFor(); + await page.getByText("1 result", { exact: true }).waitFor(); + await step("results"); + + // Pinned chip: pick a collection. + await click(page.getByRole("button", { name: "Collection", exact: true })); + await click(page.getByRole("menuitem", { name: args.collection })); + await page.waitForURL(/collectionId\.eq=/); + await page.getByRole("link", { name: new RegExp(args.query) }).last().waitFor(); + await step("collection-chip"); + + // Extra filter: add "Created by", its options open on their own. + await click(page.getByRole("button", { name: "More filters" })); + await step("add-menu-open"); + await click(page.getByRole("menuitem", { name: "Created by" })); + const menu = page.getByRole("menu"); + await menu.waitFor({ timeout: 5000 }); + await step("created-by-options-open"); + await click(menu.getByRole("menuitem").first()); + await page.waitForURL(/createdById\.eq=/); + await page.getByRole("link", { name: new RegExp(args.query) }).last().waitFor(); + await step("created-by-chip"); + + // Toggle filter: "Title only" adds a chip with no options. + await click(page.getByRole("button", { name: "More filters" })); + await click(page.getByRole("menuitem", { name: "Title only" })); + await page.waitForURL(/titleOnly=true/); + await page.getByRole("link", { name: new RegExp(args.query) }).last().waitFor(); + await step("title-only-chip"); + + // Add a filter, then close its options without a value: the chip goes away. + await click(page.getByRole("button", { name: "More filters" })); + await click(page.getByRole("menuitem", { name: "Template" })); + await page.getByRole("menu").waitFor({ timeout: 5000 }); + await page.keyboard.press("Escape"); + await page.getByRole("menu").waitFor({ state: "detached", timeout: 5000 }); + const templateChips = await page + .getByRole("button", { name: /^Template/ }) + .count(); + if (templateChips !== 0) { + throw new Error("pending Template chip stayed after closing with no value"); + } + await step("pending-chip-removed"); + + // Remove filters with their × buttons. + const removeButtons = page.getByRole("button", { name: "Remove filter" }); + const before = await removeButtons.count(); + await click(removeButtons.last()); + await page.waitForURL((url) => !url.search.includes("titleOnly")); + const after = await removeButtons.count(); + if (after !== before - 1) { + throw new Error(`expected ${before - 1} remove buttons, saw ${after}`); + } + await step("title-only-removed"); + + await page.reload(); + await page.getByRole("link", { name: new RegExp(args.query) }).last().waitFor(); + await step("after-reload"); + // Legacy URLs still apply their filters. + const searchBodies = []; + let searchTitleCalls = 0; + page.on("request", (req) => { + if (req.url().endsWith("/api/documents.search_titles")) { + searchTitleCalls += 1; + searchBodies.push(req.postDataJSON()); + } + }); + await page.goto(`/search?q=${args.query}&dateFilter=week&titleFilter=true`); + await page.getByRole("button", { name: /^Updated\s*Past week/ }).waitFor(); + await page.getByText("Title only", { exact: true }).waitFor(); + await page.getByRole("link", { name: new RegExp(args.query) }).last().waitFor(); + const legacyFilters = JSON.stringify(searchBodies.at(-1)?.filters ?? []); + if (!legacyFilters.includes('"field":"updatedAt","operator":"gte","value":"-P1W"')) { + throw new Error(`legacy dateFilter not sent to the API: ${legacyFilters}`); + } + if (!searchTitleCalls) { + throw new Error("legacy titleFilter did not use title search"); + } + await step("legacy-url"); + await page.goBack(); + await page.getByRole("link", { name: new RegExp(args.query) }).last().waitFor(); + + const finalUrl = page.url(); + log("final url:", finalUrl); + + // Narrow viewport: chips wrap and sort moves to the header. + await page.setViewportSize({ width: 390, height: 844 }); + await page.waitForTimeout(300); + await step("mobile"); + await page.setViewportSize({ width: 1280, height: 800 }); + + // Drafts and Trash reuse the shared option hooks. + await page.goto("/drafts"); + await page.getByRole("button", { name: "Any collection" }).waitFor(); + await click(page.getByRole("button", { name: "Any collection" })); + await page.getByRole("menuitem", { name: args.collection }).waitFor(); + await step("drafts-collection-filter"); + await page.keyboard.press("Escape"); + await page.goto("/trash"); + await page.getByRole("button", { name: "Any time" }).waitFor(); + await step("trash-filters"); + return { url: finalUrl }; +}; diff --git a/app/components/ExpiryDatePicker.tsx b/app/components/ExpiryDatePicker.tsx index b71797e3c2..56961b5e61 100644 --- a/app/components/ExpiryDatePicker.tsx +++ b/app/components/ExpiryDatePicker.tsx @@ -70,14 +70,16 @@ const ExpiryDatePicker = ({ side="right" shrink > - + + + {selectedDate && onClear && ( @@ -96,6 +98,10 @@ const ExpiryDatePicker = ({ ); }; +const CalendarPadding = styled.div` + padding: 12px; +`; + const Wrapper = styled.div` position: relative; display: inline-flex; diff --git a/app/components/FilterOptions.tsx b/app/components/FilterOptions.tsx index 058807c49c..00b1712e4d 100644 --- a/app/components/FilterOptions.tsx +++ b/app/components/FilterOptions.tsx @@ -25,7 +25,7 @@ import { Menu, MenuContent, MenuTrigger, MenuButton } from "./primitives/Menu"; import * as MenuComponents from "./primitives/components/Menu"; import { MenuIconWrapper } from "./primitives/components/Menu"; -interface TFilterOption extends PaginatedItem { +export interface TFilterOption extends PaginatedItem { key: string; label: string; icon?: React.ReactNode; @@ -42,6 +42,12 @@ type Props = { 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 = ({ @@ -54,13 +60,28 @@ const FilterOptions = ({ 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, setOpen] = React.useState(false); + 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) ); @@ -111,7 +132,7 @@ const FilterOptions = ({ /> ); }, - [onSelect, showIcons, selectedKeys, isMobile] + [onSelect, setOpen, showIcons, selectedKeys, isMobile] ); const handleFilter = React.useCallback( @@ -193,7 +214,7 @@ const FilterOptions = ({ break; } }, - [filteredOptions, onSelect] + [filteredOptions, onSelect, setOpen] ); const handleEscapeFromList = React.useCallback((ev: React.KeyboardEvent) => { @@ -219,7 +240,7 @@ const FilterOptions = ({ const showFilterInput = showFilter || options.length > 10; const defaultLabel = rest.defaultLabel || t("Filter options"); - const trigger = ( + const trigger = customTrigger ?? ( {trigger} - + {list} {showFilterInput && ( + + + + + ); +} diff --git a/app/components/Sharing/components/ShareExpiryDialog.tsx b/app/components/Sharing/components/ShareExpiryDialog.tsx index 25e0dd2970..8d88ff7bcb 100644 --- a/app/components/Sharing/components/ShareExpiryDialog.tsx +++ b/app/components/Sharing/components/ShareExpiryDialog.tsx @@ -3,7 +3,6 @@ import { observer } from "mobx-react"; import { useCallback, useState } from "react"; import { useTranslation } from "react-i18next"; import { toast } from "sonner"; -import styled from "styled-components"; import { Calendar } from "@shared/components/Calendar"; import { dateLocale } from "@shared/utils/date"; import type Share from "~/models/Share"; @@ -64,18 +63,16 @@ export const ShareExpiryDialog = observer(function ShareExpiryDialog({ return (
- - - + + +
+ + ); +} diff --git a/app/scenes/Search/components/DocumentFilter.tsx b/app/scenes/Search/components/DocumentFilter.tsx index 5416d5a370..252b174230 100644 --- a/app/scenes/Search/components/DocumentFilter.tsx +++ b/app/scenes/Search/components/DocumentFilter.tsx @@ -1,27 +1,31 @@ -import { CloseIcon } from "outline-icons"; -import * as React from "react"; +import { DocumentIcon } from "outline-icons"; import { useTranslation } from "react-i18next"; import type Document from "~/models/Document"; -import { StyledButton } from "~/components/FilterOptions"; -import Tooltip from "~/components/Tooltip"; +import { Chip, ChipContent, ChipRemoveButton, ChipStatic } from "./FilterChip"; type Props = { /** The currently selected document */ document: Document; /** Callback to remove the document filter */ - onClick: React.MouseEventHandler; + onRemove: () => void; }; export function DocumentFilter(props: Props) { const { t } = useTranslation(); return ( -
- - } neutral> - {props.document.displayTitle} - - -
+ + + } + label={t("Document")} + value={props.document.displayTitle} + /> + + + ); } diff --git a/app/scenes/Search/components/DocumentTypeFilter.tsx b/app/scenes/Search/components/DocumentTypeFilter.tsx deleted file mode 100644 index 5ec6155a7f..0000000000 --- a/app/scenes/Search/components/DocumentTypeFilter.tsx +++ /dev/null @@ -1,54 +0,0 @@ -import { useMemo } from "react"; -import { useTranslation } from "react-i18next"; -import { StatusFilter as TStatusFilter } from "@shared/types"; -import FilterOptions from "~/components/FilterOptions"; - -type Props = { - /** The selected status filters */ - statusFilter: TStatusFilter[]; - /** Callback when a status filter is selected */ - onSelect: (option: { statusFilter: TStatusFilter[] }) => void; -}; - -const DocumentTypeFilter = ({ statusFilter, onSelect }: Props) => { - const { t } = useTranslation(); - const options = useMemo( - () => [ - { - key: TStatusFilter.Published, - label: t("Published"), - }, - { - key: TStatusFilter.Archived, - label: t("Archived"), - }, - { - key: TStatusFilter.Draft, - label: t("Drafts"), - }, - ], - [t] - ); - - const handleSelect = (key: TStatusFilter) => { - let modifiedStatusFilter; - if (statusFilter.includes(key)) { - modifiedStatusFilter = statusFilter.filter((status) => status !== key); - } else { - modifiedStatusFilter = [...statusFilter, key]; - } - - onSelect({ statusFilter: modifiedStatusFilter }); - }; - - return ( - - ); -}; - -export default DocumentTypeFilter; diff --git a/app/scenes/Search/components/FilterChip.tsx b/app/scenes/Search/components/FilterChip.tsx new file mode 100644 index 0000000000..607cace7ae --- /dev/null +++ b/app/scenes/Search/components/FilterChip.tsx @@ -0,0 +1,189 @@ +import { CloseIcon, DisclosureIcon } from "outline-icons"; +import styled from "styled-components"; +import { hover, s } from "@shared/styles"; +import { breakpoint } from "@shared/styles/breakpoint"; +import NudeButton from "~/components/NudeButton"; +import Text from "~/components/Text"; +import Tooltip from "~/components/Tooltip"; + +interface ChipContentProps { + /** Icon shown before the label. */ + icon?: React.ReactNode; + /** Name of the filter. */ + label: string; + /** The selected value, omitted when there is no value. */ + value?: string; + /** Whether to show a disclosure arrow after the content. */ + disclosure?: boolean; +} + +/** + * The icon, filter name and selected value shown inside a filter chip. + * + * @param props the content props. + * @returns the chip content. + */ +export function ChipContent({ + icon, + label, + value, + disclosure, +}: ChipContentProps) { + return ( + <> + {icon && {icon}} + {label} + {value && ( + + {value} + + )} + {disclosure && } + + ); +} + +interface ChipRemoveButtonProps { + /** Accessible label and tooltip for the button. */ + label: string; + /** Callback when the button is clicked. */ + onClick: () => void; +} + +/** + * A button at the end of a filter chip that removes the filter. + * + * @param props the button props. + * @returns the remove button. + */ +export function ChipRemoveButton({ label, onClick }: ChipRemoveButtonProps) { + return ( + + + + + + ); +} + +/** Outlined container for a filter chip. */ +export const Chip = styled.div` + display: inline-flex; + align-items: stretch; + max-width: 100%; + height: 28px; + border: 1px solid ${s("buttonNeutralBorder")}; + border-radius: 8px; + overflow: hidden; + user-select: none; + font-size: 13px; + font-weight: 450; + color: ${s("text")}; + + &:has(:focus-visible) { + border-color: ${s("inputBorderFocused")}; + } + + ${breakpoint("mobile", "tablet")` + height: 36px; + font-size: 15px; + `}; +`; + +/** The button inside a chip that opens the options of the filter. */ +export const ChipButton = styled.button` + display: inline-flex; + align-items: center; + gap: 4px; + min-width: 0; + height: 100%; + padding: 0 4px 0 7px; + margin: 0; + border: 0; + background: none; + color: inherit; + font: inherit; + cursor: var(--pointer); + transition: background 100ms ease-out; + + &:${hover}, + &[aria-expanded="true"] { + background: ${s("buttonNeutralHoverBackground")}; + } + + &:focus-visible { + outline: none; + } +`; + +/** A part of a chip that only shows content, for filters without options. */ +export const ChipStatic = styled.span` + display: inline-flex; + align-items: center; + gap: 4px; + min-width: 0; + padding: 0 4px 0 6px; +`; + +const ChipIcon = styled.span` + display: inline-flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + width: 18px; + height: 18px; + margin-inline-start: -2px; + color: ${s("textTertiary")}; + + svg { + width: 18px; + height: 18px; + } +`; + +const ChipLabel = styled(Text)` + flex-shrink: 0; + white-space: nowrap; +`; + +const ChipValue = styled(Text)` + max-width: 240px; +`; + +const RemoveButton = styled(NudeButton)` + display: inline-flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + width: 24px; + height: auto; + padding-inline-end: 2px; + border-radius: 0; + border-inline-start: 1px solid transparent; + color: ${s("textTertiary")}; + transition: + background 100ms ease-out, + border-color 100ms ease-out, + color 100ms ease-out; + + &:${hover}, + &:focus-visible { + color: ${s("text")}; + background: ${s("buttonNeutralHoverBackground")}; + border-color: ${s("buttonNeutralBorder")}; + } + + &:focus-visible { + outline: none; + } + + ${breakpoint("mobile", "tablet")` + width: 32px; + `}; +`; + +const Disclosure = styled(DisclosureIcon)` + flex-shrink: 0; + margin-inline-start: -3px; + color: ${s("textTertiary")}; +`; diff --git a/app/scenes/Search/components/SearchFilterChip.tsx b/app/scenes/Search/components/SearchFilterChip.tsx new file mode 100644 index 0000000000..f320e6ca23 --- /dev/null +++ b/app/scenes/Search/components/SearchFilterChip.tsx @@ -0,0 +1,154 @@ +import { observer } from "mobx-react"; +import { useCallback, useMemo } from "react"; +import { useTranslation } from "react-i18next"; +import FilterOptions from "~/components/FilterOptions"; +import type { SearchFilter, SelectSearchFilter } from "../searchFilters"; +import { CUSTOM_RANGE } from "../searchFilters"; +import { + Chip, + ChipButton, + ChipContent, + ChipRemoveButton, + ChipStatic, +} from "./FilterChip"; + +interface Props { + /** The filter to show. */ + filter: SearchFilter; + /** The selected values, including defaults. */ + values: string[]; + /** Whether the URL sets the filter, as opposed to using its defaults. */ + isSet: boolean; + /** Whether the options are open when the chip mounts. */ + defaultOpen?: boolean; + /** Callback when the selected values change, undefined removes the filter. */ + onChange: (filter: SearchFilter, values: string[] | undefined) => void; + /** Callback when the options open or close. */ + onOpenChange?: (filter: SearchFilter, open: boolean) => void; + /** Label of a custom date range, shown in place of an option label. */ + rangeLabel?: string; + /** Callback when the user asks to choose a custom date range. */ + onCustomRange?: (filter: SearchFilter) => void; +} + +/** + * A chip that shows the value of one search filter and lets the user change + * or remove it. + * + * @param props the chip props. + * @returns the filter chip. + */ +export function SearchFilterChip(props: Props) { + const { t } = useTranslation(); + const { filter, onChange } = props; + + if (filter.type === "select") { + return ; + } + + return ( + + + + + onChange(filter, undefined)} + /> + + ); +} + +const SelectFilterChip = observer(function SelectFilterChip_({ + filter, + values, + isSet, + defaultOpen, + onChange, + onOpenChange, + rangeLabel, + onCustomRange, +}: Props & { filter: SelectSearchFilter }) { + const { t } = useTranslation(); + const source = filter.useOptions(); + const { multiple } = filter; + const allowsRange = filter.selection === "date" && !!onCustomRange; + + const options = useMemo( + () => + allowsRange + ? [...source.options, { key: CUSTOM_RANGE, label: `${t("Custom")}…` }] + : source.options, + [allowsRange, source.options, t] + ); + + const selected = useMemo( + () => source.options.filter((option) => values.includes(option.key)), + [source.options, values] + ); + + const handleSelect = useCallback( + (key: string | null | undefined) => { + if (!key) { + return; + } + if (key === CUSTOM_RANGE) { + onCustomRange?.(filter); + return; + } + if (!multiple) { + onChange(filter, [key]); + return; + } + const next = values.includes(key) + ? values.filter((value) => value !== key) + : [...values, key]; + onChange(filter, next.length ? next : undefined); + }, + [filter, multiple, values, onChange, onCustomRange] + ); + + const handleOpenChange = useCallback( + (open: boolean) => onOpenChange?.(filter, open), + [filter, onOpenChange] + ); + + // Default values are implied, so only show values that the user picked. + const shown = isSet ? selected : []; + const icon = + shown.length === 1 && shown[0].icon ? shown[0].icon : filter.icon; + + return ( + + + option.label).join(", ") + } + disclosure={!isSet} + /> + + } + /> + {isSet && ( + onChange(filter, undefined)} + /> + )} + + ); +}); diff --git a/app/scenes/Search/components/SearchInput.tsx b/app/scenes/Search/components/SearchInput.tsx index df61fa074e..1d64e47273 100644 --- a/app/scenes/Search/components/SearchInput.tsx +++ b/app/scenes/Search/components/SearchInput.tsx @@ -1,8 +1,8 @@ import { SearchIcon } from "outline-icons"; import * as React from "react"; -import styled, { useTheme } from "styled-components"; +import styled from "styled-components"; import { s } from "@shared/styles"; -import Flex from "~/components/Flex"; +import Input, { NativeInput, Outline } from "~/components/Input"; interface Props extends React.InputHTMLAttributes { name: string; @@ -11,77 +11,58 @@ interface Props extends React.InputHTMLAttributes { } function SearchInput({ defaultValue, ref, ...rest }: Props) { - const theme = useTheme(); - const focusInput = React.useCallback(() => { - ref.current?.focus(); - }, [ref]); - React.useEffect(() => { // ensure that focus is placed at end of input const len = (defaultValue || "").length; ref.current?.setSelectionRange(len, len); const timeoutId = setTimeout(() => { - focusInput(); + ref.current?.focus(); }, 100); // arbitrary number return () => { clearTimeout(timeoutId); }; - }, [ref, defaultValue, focusInput]); + }, [ref, defaultValue]); return ( - - - - + } + defaultValue={defaultValue} + ref={ref} + spellCheck="false" + margin="0 0 12px" + autoFocus + /> ); } -const Wrapper = styled(Flex)` - position: relative; - margin-bottom: 8px; -`; +const StyledInput = styled(Input)` + ${Outline} { + border-color: transparent; + border-radius: 10px; + background: ${s("backgroundSecondary")}; + transition: + background 100ms ease-out, + border-color 100ms ease-out; + } -const StyledInput = styled.input` - width: 100%; - padding-block: 10px 10px; - padding-inline: 60px 10px; - font-size: 30px; - font-weight: 400; - outline: none; - border: 0; - background: ${s("inputBackground")}; - border-radius: 4px; - color: ${s("text")}; + &:focus-within ${Outline} { + border-color: ${s("inputBorderFocused")}; + background: ${s("background")}; + } - &::-webkit-search-cancel-button { - -webkit-appearance: none; - } - &::-webkit-input-placeholder { - color: ${s("placeholder")}; - } - &:-moz-placeholder { - color: ${s("placeholder")}; - } - &::-moz-placeholder { - color: ${s("placeholder")}; - } - &:-ms-input-placeholder { - color: ${s("placeholder")}; + ${NativeInput} { + height: 46px; + padding-inline-start: 12px; + font-size: 17px; } `; -const StyledIcon = styled(SearchIcon)` - position: absolute; - inset-inline-start: 8px; - opacity: 0.7; +const StyledSearchIcon = styled(SearchIcon)` + margin-inline-start: 4px; + color: ${s("textTertiary")}; `; export default SearchInput; diff --git a/app/scenes/Search/components/SortInput.tsx b/app/scenes/Search/components/SortInput.tsx index e59a4e3c11..354a0c9e4a 100644 --- a/app/scenes/Search/components/SortInput.tsx +++ b/app/scenes/Search/components/SortInput.tsx @@ -1,7 +1,13 @@ import type { DirectionFilter, SortFilter as TSortFilter } from "@shared/types"; -import { SortAscendingIcon, SortDescendingIcon } from "outline-icons"; +import { + DisclosureIcon, + SortAscendingIcon, + SortDescendingIcon, +} from "outline-icons"; import { useMemo } from "react"; import { useTranslation } from "react-i18next"; +import styled from "styled-components"; +import { hover, s } from "@shared/styles"; import FilterOptions from "~/components/FilterOptions"; type Props = { @@ -64,15 +70,56 @@ export const SortInput = ({ sort, direction, onSelect }: Props) => { onSelect(sortField, sortDirection); }; + const selectedLabel = + options.find((option) => option.key === selectedKey)?.label ?? + t("Relevance"); + return ( - + + {t("Sorted by")} + + {selectedLabel} + + + } + /> + ); }; + +const Wrapper = styled.div` + display: flex; + align-items: center; + gap: 4px; +`; + +const Trigger = styled.button` + display: inline-flex; + align-items: center; + margin: 0; + padding: 0 0 0 2px; + border: 0; + border-radius: 4px; + background: none; + font: inherit; + font-weight: 500; + color: ${s("text")}; + cursor: var(--pointer); + + &:${hover}, + &[aria-expanded="true"] { + text-decoration: underline; + } +`; + +const Disclosure = styled(DisclosureIcon)` + color: ${s("textTertiary")}; +`; diff --git a/app/scenes/Search/components/UserFilter.tsx b/app/scenes/Search/components/UserFilter.tsx index fd16b4e774..30bd6f63bb 100644 --- a/app/scenes/Search/components/UserFilter.tsx +++ b/app/scenes/Search/components/UserFilter.tsx @@ -2,12 +2,8 @@ import { observer } from "mobx-react"; import { UserIcon } from "outline-icons"; import { useMemo } from "react"; import { useTranslation } from "react-i18next"; -import styled from "styled-components"; -import { Avatar, AvatarSize } from "~/components/Avatar"; import FilterOptions from "~/components/FilterOptions"; -import useCurrentTeam from "~/hooks/useCurrentTeam"; -import usePolicy from "~/hooks/usePolicy"; -import useStores from "~/hooks/useStores"; +import { useUserOptions } from "../filterOptions"; type Props = { /** The currently selected user ID */ @@ -18,31 +14,23 @@ type Props = { onSelect: (key: string | undefined) => void; }; -const fetchQueryOptions = { sort: "name", direction: "ASC" }; - function UserFilter(props: Props) { const { onSelect, userId } = props; const { t } = useTranslation(); - const { users } = useStores(); - const team = useCurrentTeam(); - const can = usePolicy(team); + const source = useUserOptions(); const anyLabel = props.anyLabel ?? t("Any author"); - const options = useMemo(() => { - const userOptions = users.all.map((user) => ({ - key: user.id, - label: user.name, - icon: , - })); - return [ + const options = useMemo( + () => [ { key: "", label: anyLabel, icon: , }, - ...userOptions, - ]; - }, [users.all, anyLabel]); + ...source.options, + ], + [source.options, anyLabel] + ); return ( ); } -const StyledAvatar = styled(Avatar)` - margin: 2px; -`; - export default observer(UserFilter); diff --git a/app/scenes/Search/filterOptions.tsx b/app/scenes/Search/filterOptions.tsx new file mode 100644 index 0000000000..bfd5ba7cfe --- /dev/null +++ b/app/scenes/Search/filterOptions.tsx @@ -0,0 +1,171 @@ +import { NewDocumentIcon } from "outline-icons"; +import { useMemo } from "react"; +import { useTranslation } from "react-i18next"; +import styled from "styled-components"; +import Icon from "@shared/components/Icon"; +import { durationForDateFilter } from "@shared/helpers/FilterHelper"; +import { StatusFilter } from "@shared/types"; +import { Avatar, AvatarSize } from "~/components/Avatar"; +import type { TFilterOption } from "~/components/FilterOptions"; +import CollectionIcon from "~/components/Icons/CollectionIcon"; +import type { PaginatedItem } from "~/components/PaginatedList"; +import useCurrentTeam from "~/hooks/useCurrentTeam"; +import usePolicy from "~/hooks/usePolicy"; +import useStores from "~/hooks/useStores"; +import type { FetchPageParams } from "~/stores/base/Store"; + +/** The options a filter picks from, and how to load more of them. */ +export interface FilterOptionSource { + /** The options to pick from. */ + options: TFilterOption[]; + /** Loads more options from the server as the user types. */ + fetchQuery?: (options: FetchPageParams) => Promise; + /** Extra parameters to send with fetchQuery. */ + fetchQueryOptions?: Record; + /** Whether to show the filter input even for a short list. */ + showFilter?: boolean; +} + +const userFetchQueryOptions = { sort: "name", direction: "ASC" }; + +/** + * Options for each collection the user can see. + * + * @returns the collection options. + */ +export function useCollectionOptions(): FilterOptionSource { + const { collections } = useStores(); + + return useMemo( + () => ({ + options: collections.orderedData.map((collection) => ({ + key: collection.id, + label: collection.displayName, + icon: , + })), + showFilter: true, + }), + [collections.orderedData] + ); +} + +/** + * Options for each user in the workspace, loaded from the server as needed. + * + * @returns the user options. + */ +export function useUserOptions(): FilterOptionSource { + const { users } = useStores(); + const team = useCurrentTeam(); + const can = usePolicy(team); + const fetchQuery = can.listUsers ? users.fetchPage : undefined; + + return useMemo( + () => ({ + options: users.all.map((user) => ({ + key: user.id, + label: user.name, + icon: , + })), + fetchQuery, + fetchQueryOptions: userFetchQueryOptions, + showFilter: true, + }), + [users.all, fetchQuery] + ); +} + +/** + * Options for each template, loaded from the server as needed. + * + * @returns the template options. + */ +export function useTemplateOptions(): FilterOptionSource { + const { templates } = useStores(); + + return useMemo( + () => ({ + options: templates.all.map((template) => ({ + key: template.id, + label: template.displayTitle, + icon: template.icon ? ( + + ) : ( + + ), + })), + fetchQuery: templates.fetchPage, + showFilter: true, + }), + [templates.all, templates.fetchPage] + ); +} + +/** + * Options for a relative date range, from the past day to the past year. + * + * @returns the date options. + */ +export function useDateOptions(): FilterOptionSource { + const { t } = useTranslation(); + + return useMemo( + () => ({ + options: [ + { key: "day", label: t("Past day") }, + { key: "week", label: t("Past week") }, + { key: "month", label: t("Past month") }, + { key: "year", label: t("Past year") }, + ], + }), + [t] + ); +} + +/** + * Options for a relative date range, keyed by the ISO 8601 duration that the + * API accepts as a lower bound. + * + * @returns the relative date options. + */ +export function useRelativeDateOptions(): FilterOptionSource { + const source = useDateOptions(); + + return useMemo( + () => ({ + options: source.options.map((option) => ({ + ...option, + key: durationForDateFilter(option.key) ?? option.key, + })), + }), + [source.options] + ); +} + +/** + * Options for the status of a document. + * + * @returns the status options. + */ +export function useStatusOptions(): FilterOptionSource { + const { t } = useTranslation(); + + return useMemo( + () => ({ + options: [ + { key: StatusFilter.Published, label: t("Published") }, + { key: StatusFilter.Archived, label: t("Archived") }, + { key: StatusFilter.Draft, label: t("Drafts") }, + ], + }), + [t] + ); +} + +const StyledAvatar = styled(Avatar)` + margin: 2px; +`; diff --git a/app/scenes/Search/searchFilters.test.ts b/app/scenes/Search/searchFilters.test.ts new file mode 100644 index 0000000000..c48e9a2a39 --- /dev/null +++ b/app/scenes/Search/searchFilters.test.ts @@ -0,0 +1,387 @@ +import { endOfDay, startOfDay } from "date-fns"; +import i18next from "i18next"; +import { StatusFilter } from "@shared/types"; +import type { SearchFilter, SelectSearchFilter } from "./searchFilters"; +import { + createSearchFilters, + formatDateRange, + getApiFilter, + getDateRange, + getDateRangeParamChanges, + getFilterConditions, + getFilterParamChanges, + getFilterValues, + isFilterSet, + parseKey, +} from "./searchFilters"; + +const filters = createSearchFilters(i18next.t); + +const collectionA = "9f1b8c2e-3a4d-4e5f-8a6b-7c8d9e0f1a2b"; +const collectionB = "1a2b3c4d-5e6f-4a8b-9c0d-1e2f3a4b5c6d"; + +function getFilter(id: string): SearchFilter { + const filter = filters.find((item) => item.id === id); + if (!filter) { + throw new Error(`Missing filter ${id}`); + } + return filter; +} + +function getSelectFilter(id: string): SelectSearchFilter { + const filter = getFilter(id); + if (filter.type !== "select") { + throw new Error(`Filter ${id} is not a select filter`); + } + return filter; +} + +function params(search: string) { + return new URLSearchParams(search); +} + +describe("searchFilters", () => { + it("has a unique id for each filter", () => { + const ids = filters.map((filter) => filter.id); + expect(new Set(ids).size).toBe(ids.length); + }); + + it("offers every filter without a query", () => { + const available = filters.filter( + (filter) => filter.isAvailable?.({}) ?? true + ); + expect(available).toEqual(filters); + }); + + describe("parseKey", () => { + it("reads a bare key as eq", () => { + expect(parseKey("collectionId")).toEqual({ + field: "collectionId", + operator: "eq", + }); + }); + + it("splits the field and operator", () => { + expect(parseKey("updatedAt.gte")).toEqual({ + field: "updatedAt", + operator: "gte", + }); + }); + + it("rejects an unknown operator", () => { + expect(parseKey("updatedAt.after")).toBeUndefined(); + }); + }); + + describe("getFilterConditions", () => { + it("reads bare, eq and in keys", () => { + const collection = getSelectFilter("collectionId"); + + expect( + getFilterConditions(collection, params(`collectionId=${collectionA}`)) + ).toEqual({ eq: [collectionA] }); + expect( + getFilterConditions( + collection, + params(`collectionId.in=${collectionA},${collectionB}`) + ) + ).toEqual({ in: [collectionA, collectionB] }); + }); + + it("drops operators the filter does not allow", () => { + expect( + getFilterConditions( + getSelectFilter("userId"), + params(`userId.neq=${collectionA}`) + ) + ).toEqual({}); + }); + + it("drops values that are not valid", () => { + expect( + getFilterConditions( + getSelectFilter("collectionId"), + params("collectionId=not-a-uuid") + ) + ).toEqual({}); + expect( + getFilterConditions( + getSelectFilter("updatedAt"), + params("updatedAt.gte=yesterday") + ) + ).toEqual({}); + }); + + it("reads date ranges with durations and dates", () => { + expect( + getFilterConditions( + getSelectFilter("createdAt"), + params("createdAt.gte=2026-03-01&createdAt.lte=2026-04-15") + ) + ).toEqual({ gte: ["2026-03-01"], lte: ["2026-04-15"] }); + }); + + it("reads legacy parameters", () => { + expect( + getFilterConditions( + getSelectFilter("updatedAt"), + params("dateFilter=week") + ) + ).toEqual({ gte: ["-P1W"] }); + expect( + getFilterConditions( + getSelectFilter("status"), + params("statusFilter=archived&statusFilter=draft") + ) + ).toEqual({ in: [StatusFilter.Archived, StatusFilter.Draft] }); + expect( + getFilterConditions( + getSelectFilter("status"), + params("statusFilter=archived,draft") + ) + ).toEqual({ in: [StatusFilter.Archived, StatusFilter.Draft] }); + }); + + it("prefers the current format over a legacy parameter", () => { + expect( + getFilterConditions( + getSelectFilter("updatedAt"), + params("updatedAt.gte=-P1D&dateFilter=week") + ) + ).toEqual({ gte: ["-P1D"] }); + }); + }); + + describe("getFilterValues", () => { + it("falls back to default values", () => { + const status = getFilter("status"); + + expect(isFilterSet(status, params(""))).toBe(false); + expect(getFilterValues(status, params(""))).toEqual([ + StatusFilter.Published, + StatusFilter.Draft, + ]); + }); + + it("reads toggle filters, including the legacy parameter", () => { + const title = getFilter("titleOnly"); + + expect(isFilterSet(title, params("titleOnly=true"))).toBe(true); + expect(isFilterSet(title, params("titleFilter=true"))).toBe(true); + expect(isFilterSet(title, params("titleOnly=false"))).toBe(false); + }); + }); + + describe("getApiFilter", () => { + it("matches one or many values", () => { + const createdBy = getFilter("createdById"); + + expect(getApiFilter(createdBy, params(""))).toBeUndefined(); + expect( + getApiFilter(createdBy, params(`createdById.eq=${collectionA}`)) + ).toEqual({ field: "createdById", operator: "eq", value: collectionA }); + expect( + getApiFilter( + createdBy, + params(`createdById.in=${collectionA},${collectionB}`) + ) + ).toEqual({ + field: "createdById", + operator: "in", + value: [collectionA, collectionB], + }); + }); + + it("supports exclusion", () => { + expect( + getApiFilter( + getFilter("collectionId"), + params(`collectionId.neq=${collectionA}`) + ) + ).toEqual({ field: "collectionId", operator: "neq", value: collectionA }); + }); + + it("sends a date range as whole local days, combined with AND", () => { + expect( + getApiFilter( + getFilter("publishedAt"), + params("publishedAt.gte=2026-03-01&publishedAt.lte=2026-04-15") + ) + ).toEqual({ + operator: "AND", + filters: [ + { + field: "publishedAt", + operator: "lte", + value: endOfDay(new Date(2026, 3, 15)).toISOString(), + }, + { + field: "publishedAt", + operator: "gte", + value: startOfDay(new Date(2026, 2, 1)).toISOString(), + }, + ], + }); + }); + + it("sends durations and full timestamps without change", () => { + expect( + getApiFilter(getFilter("updatedAt"), params("updatedAt.gte=-P1W")) + ).toEqual({ field: "updatedAt", operator: "gte", value: "-P1W" }); + expect( + getApiFilter( + getFilter("updatedAt"), + params("updatedAt.lt=2026-03-01T10:00:00Z") + ) + ).toEqual({ + field: "updatedAt", + operator: "lt", + value: "2026-03-01T10:00:00Z", + }); + }); + + it("combines default statuses with OR", () => { + expect(getApiFilter(getFilter("status"), params(""))).toEqual({ + operator: "OR", + filters: [ + { + operator: "AND", + filters: [ + { field: "archivedAt", operator: "isNull" }, + { field: "publishedAt", operator: "isNotNull" }, + ], + }, + { + operator: "AND", + filters: [ + { field: "archivedAt", operator: "isNull" }, + { field: "publishedAt", operator: "isNull" }, + ], + }, + ], + }); + expect( + getApiFilter(getFilter("status"), params("status.eq=archived")) + ).toEqual({ field: "archivedAt", operator: "isNotNull" }); + }); + + it("adds no condition for toggle filters", () => { + expect( + getApiFilter(getFilter("titleOnly"), params("titleOnly=true")) + ).toBeUndefined(); + }); + }); + + describe("getFilterParamChanges", () => { + it("writes one value as eq and many as in", () => { + const collection = getFilter("collectionId"); + + expect( + getFilterParamChanges(collection, [collectionA], params("")) + ).toEqual({ "collectionId.eq": collectionA }); + expect( + getFilterParamChanges( + collection, + [collectionA, collectionB], + params(`collectionId.eq=${collectionA}`) + ) + ).toEqual({ + "collectionId.eq": undefined, + "collectionId.in": [collectionA, collectionB], + }); + }); + + it("writes dates as a lower bound and clears the legacy parameter", () => { + expect( + getFilterParamChanges( + getFilter("updatedAt"), + ["-P1M"], + params("dateFilter=week") + ) + ).toEqual({ dateFilter: undefined, "updatedAt.gte": "-P1M" }); + }); + + it("clears every key of a removed filter", () => { + expect( + getFilterParamChanges( + getFilter("createdAt"), + undefined, + params("createdAt.gte=2026-03-01&createdAt.lte=2026-04-15&q=x") + ) + ).toEqual({ "createdAt.gte": undefined, "createdAt.lte": undefined }); + }); + + it("round trips through the URL", () => { + const status = getFilter("status"); + const changes = getFilterParamChanges( + status, + [StatusFilter.Archived, StatusFilter.Draft], + params("") + ); + const next = new URLSearchParams(); + for (const [key, value] of Object.entries(changes)) { + if (value !== undefined) { + next.set(key, Array.isArray(value) ? value.join(",") : value); + } + } + + expect(getFilterValues(status, next)).toEqual([ + StatusFilter.Archived, + StatusFilter.Draft, + ]); + }); + + it("writes toggles and clears the legacy parameter", () => { + expect( + getFilterParamChanges( + getFilter("titleOnly"), + ["true"], + params("titleFilter=true") + ) + ).toEqual({ titleFilter: undefined, titleOnly: "true" }); + }); + }); + + describe("date ranges", () => { + it("reads a custom range and ignores presets", () => { + const updated = getFilter("updatedAt"); + + expect( + getDateRange( + updated, + params("updatedAt.gte=2026-03-01&updatedAt.lte=2026-04-15") + ) + ).toEqual({ from: "2026-03-01", to: "2026-04-15" }); + expect( + getDateRange(updated, params("updatedAt.gte=-P1W")) + ).toBeUndefined(); + expect( + getDateRange(getFilter("collectionId"), params("")) + ).toBeUndefined(); + }); + + it("replaces a preset with a range", () => { + expect( + getDateRangeParamChanges( + getFilter("updatedAt"), + { from: "2026-03-01", to: "2026-04-15" }, + params("updatedAt.gte=-P1W&dateFilter=week") + ) + ).toEqual({ + dateFilter: undefined, + "updatedAt.gte": "2026-03-01", + "updatedAt.lte": "2026-04-15", + }); + }); + + it("labels ranges with one bound", () => { + expect(formatDateRange({ from: "2026-03-01" }, i18next.t)).toMatch( + /^From / + ); + expect(formatDateRange({ to: "2026-03-01" }, i18next.t)).toMatch( + /^Until / + ); + expect(formatDateRange({ from: "bad" }, i18next.t)).toBeUndefined(); + }); + }); +}); diff --git a/app/scenes/Search/searchFilters.tsx b/app/scenes/Search/searchFilters.tsx new file mode 100644 index 0000000000..65900b1767 --- /dev/null +++ b/app/scenes/Search/searchFilters.tsx @@ -0,0 +1,635 @@ +import { + CalendarIcon, + CollectionIcon, + DoneIcon, + EditIcon, + NewDocumentIcon, + TextWrapIcon, + UserIcon, +} from "outline-icons"; +import { endOfDay, startOfDay } from "date-fns"; +import { uniq } from "es-toolkit/compat"; +import { useMemo } from "react"; +import type { TFunction } from "i18next"; +import { useTranslation } from "react-i18next"; +import type { Filter } from "@shared/helpers/FilterHelper"; +import { + ComparisonOperator, + durationForDateFilter, + RANGE_OPERATORS, + scalarMatchesKind, + statusToFilter, +} from "@shared/helpers/FilterHelper"; +import { StatusFilter } from "@shared/types"; +import { + dateRangeToReadable, + isISODate, + parseISODate, +} from "@shared/utils/date"; +import type { locales } from "@shared/utils/date"; +import type Document from "~/models/Document"; +import { isTruthyQueryValue } from "~/utils/urls"; +import type { FilterOptionSource } from "./filterOptions"; +import { + useCollectionOptions, + useRelativeDateOptions, + useStatusOptions, + useTemplateOptions, + useUserOptions, +} from "./filterOptions"; + +/** The state of the search page that controls which filters can show. */ +interface SearchFilterContext { + /** The document that the search is limited to, if there is one. */ + document?: Document; +} + +/** The values of a filter for each operator, as read from the URL. */ +export type FilterConditions = Partial>; + +/** A URL parameter from before the `.` format. */ +interface LegacyParam { + /** The name of the URL parameter. */ + param: string; + /** The operator that the parameter stands for. */ + operator: ComparisonOperator; + /** Converts a legacy value to the current format, undefined drops it. */ + map?: (value: string) => string | undefined; +} + +interface BaseSearchFilter { + /** + * Unique identifier and the field name in the URL, which is + * `.=`. A bare `=` is read as `eq`. + */ + id: string; + /** Name of the filter, shown on the chip and in the add menu. */ + label: string; + /** Icon shown in the add menu and on the chip when there is no value icon. */ + icon: React.ReactNode; + /** Pinned filters always show, others are added from the "More" menu. */ + pinned?: boolean; + /** Whether the filter can be used in the given context, defaults to always. */ + isAvailable?: (context: SearchFilterContext) => boolean; +} + +/** A filter where the user picks one or more values from a list. */ +export interface SelectSearchFilter extends BaseSearchFilter { + type: "select"; + /** Operators that the URL may use for this filter, others are dropped. */ + operators: readonly ComparisonOperator[]; + /** Whether a URL value is valid for the operator, others are dropped. */ + isValidValue: (value: string, operator: ComparisonOperator) => boolean; + /** + * How a selection is written to the URL: "match" writes one value as `eq` + * and many as `in`, "date" writes a preset as a `gte` lower bound and a + * custom range as `gte` and `lte` dates. + */ + selection: "match" | "date"; + /** Whether more than one value can be selected. */ + multiple?: boolean; + /** Values that apply when the URL does not include the filter. */ + defaultValues?: string[]; + /** Hook that returns the options to pick from. */ + useOptions: () => FilterOptionSource; + /** A URL parameter from before the current format, still read. */ + legacy?: LegacyParam; + /** Builds the API expression, defaults to one condition per operator. */ + toFilter?: (conditions: FilterConditions) => Filter | undefined; +} + +/** A filter that is either on or off, and is not an API condition. */ +export interface ToggleSearchFilter extends BaseSearchFilter { + type: "toggle"; + /** A URL parameter from before the current format, still read. */ + legacyParam?: string; +} + +/** A filter that can be applied on the search page. */ +export type SearchFilter = SelectSearchFilter | ToggleSearchFilter; + +/** A custom date range, as ISO dates (yyyy-MM-dd) in local time. */ +export interface DateRange { + /** The first day of the range. */ + from?: string; + /** The last day of the range. */ + to?: string; +} + +/** The URL value that turns a toggle filter on. */ +export const TOGGLE_ON = "true"; + +/** The option key that opens the custom date range picker. */ +export const CUSTOM_RANGE = "custom"; + +/** + * Hook that returns every filter that can be applied on the search page. + * + * @returns the search filters. + */ +export function useSearchFilters(): SearchFilter[] { + const { t } = useTranslation(); + return useMemo(() => createSearchFilters(t), [t]); +} + +/** + * Create every filter that can be applied on the search page, in display + * order. To add a filter, add a definition to this list. + * + * @param t the translation function. + * @returns the search filters. + */ +export function createSearchFilters(t: TFunction): SearchFilter[] { + return [ + { + type: "select", + id: "collectionId", + label: t("Collection"), + icon: , + pinned: true, + isAvailable: ({ document }) => !document, + ...matchSelection, + useOptions: useCollectionOptions, + }, + { + type: "select", + id: "userId", + label: t("Edited by"), + icon: , + pinned: true, + ...matchSelection, + // The API only supports membership checks for these fields. + operators: ["eq", "in"], + useOptions: useUserOptions, + }, + { + type: "select", + id: "status", + label: t("Status"), + icon: , + pinned: true, + operators: ["eq", "in"], + isValidValue: isStatus, + selection: "match", + multiple: true, + defaultValues: [StatusFilter.Published, StatusFilter.Draft], + useOptions: useStatusOptions, + legacy: { param: "statusFilter", operator: "in" }, + toFilter: (conditions) => + statusesToFilter([...(conditions.eq ?? []), ...(conditions.in ?? [])]), + }, + { + type: "select", + id: "updatedAt", + label: t("Updated"), + icon: , + ...dateSelection, + legacy: { + param: "dateFilter", + operator: "gte", + map: durationForDateFilter, + }, + }, + { + type: "select", + id: "createdById", + label: t("Created by"), + icon: , + ...matchSelection, + // The API only supports membership checks for these fields. + operators: ["eq", "in"], + useOptions: useUserOptions, + }, + { + type: "select", + id: "createdAt", + label: t("Created"), + icon: , + ...dateSelection, + }, + { + type: "select", + id: "publishedAt", + label: t("Published"), + icon: , + ...dateSelection, + }, + { + type: "select", + id: "templateId", + label: t("Template"), + icon: , + ...matchSelection, + useOptions: useTemplateOptions, + }, + { + type: "toggle", + id: "titleOnly", + label: t("Title only"), + icon: , + legacyParam: "titleFilter", + }, + ]; +} + +/** + * Read the conditions of a filter that the URL sets, from both the + * `.` format and any legacy parameter. Keys with an unknown + * operator, an operator the filter does not allow, or a value that is not + * valid are dropped. + * + * @param filter the filter to read. + * @param params the URL query parameters. + * @returns the conditions, empty when the URL does not set the filter. + */ +export function getFilterConditions( + filter: SelectSearchFilter, + params: URLSearchParams +): FilterConditions { + const conditions: FilterConditions = {}; + const add = (operator: ComparisonOperator, raw: string) => { + if (!filter.operators.includes(operator)) { + return; + } + const values = splitValues(operator, raw).filter((value) => + filter.isValidValue(value, operator) + ); + if (values.length > 0 || isNullOperator(operator)) { + conditions[operator] = [...(conditions[operator] ?? []), ...values]; + } + }; + + for (const [key, raw] of params.entries()) { + const parsed = parseKey(key); + if (parsed?.field === filter.id) { + add(parsed.operator, raw); + } + } + + const { legacy } = filter; + if (legacy && Object.keys(conditions).length === 0) { + for (const raw of params.getAll(legacy.param)) { + for (const value of raw.split(",").filter(Boolean)) { + const mapped = legacy.map ? legacy.map(value) : value; + if (mapped) { + add(legacy.operator, mapped); + } + } + } + } + + return conditions; +} + +/** The state of one filter, read from the URL in one pass. */ +export interface FilterState { + /** Whether the URL sets the filter, as opposed to it using its defaults. */ + isSet: boolean; + /** The selected option keys, including defaults. */ + values: string[]; + /** The API expression, undefined when the filter adds no condition. */ + apiFilter?: Filter; + /** A custom date range, for date filters only. */ + range?: DateRange; +} + +/** + * Read the full state of a filter from the URL, parsing it once. + * + * @param filter the filter to read. + * @param params the URL query parameters. + * @returns the state of the filter. + */ +export function readFilter( + filter: SearchFilter, + params: URLSearchParams +): FilterState { + if (filter.type === "toggle") { + const isSet = + isTruthyQueryValue(params.get(filter.id)) || + (!!filter.legacyParam && + isTruthyQueryValue(params.get(filter.legacyParam))); + return { isSet, values: isSet ? [TOGGLE_ON] : [] }; + } + + const set = getFilterConditions(filter, params); + const isSet = Object.keys(set).length > 0; + const isDate = filter.selection === "date"; + const selected = isDate + ? (set.gte ?? []) + : uniq([...(set.eq ?? []), ...(set.in ?? [])]); + const conditions = + isSet || !filter.defaultValues ? set : { in: filter.defaultValues }; + const apiFilter = filter.toFilter + ? filter.toFilter(conditions) + : conditionsToFilter( + filter.id, + isDate ? toLocalDayBounds(conditions) : conditions + ); + const from = set.gte?.find(isISODate); + const to = set.lte?.find(isISODate); + + return { + isSet, + values: selected.length > 0 ? selected : (filter.defaultValues ?? []), + apiFilter, + range: isDate && (from || to) ? { from, to } : undefined, + }; +} + +/** + * Whether the URL sets a value for the filter, as opposed to the filter using + * its default values. + * + * @param filter the filter to check. + * @param params the URL query parameters. + * @returns true if the URL sets the filter. + */ +export function isFilterSet( + filter: SearchFilter, + params: URLSearchParams +): boolean { + return readFilter(filter, params).isSet; +} + +/** + * Read the selected values of a filter from the URL, falling back to its + * defaults. These are the option keys that the chip shows as selected. + * + * @param filter the filter to read. + * @param params the URL query parameters. + * @returns the selected values. + */ +export function getFilterValues( + filter: SearchFilter, + params: URLSearchParams +): string[] { + return readFilter(filter, params).values; +} + +/** + * Convert the state of a filter in the URL to an API filter expression. + * + * @param filter the filter to convert. + * @param params the URL query parameters. + * @returns the expression, or undefined when the filter adds no condition. + */ +export function getApiFilter( + filter: SearchFilter, + params: URLSearchParams +): Filter | undefined { + return readFilter(filter, params).apiFilter; +} + +/** + * Read a custom date range of a date filter from the URL. + * + * @param filter the filter to read. + * @param params the URL query parameters. + * @returns the range as ISO dates, or undefined when the filter has none. + */ +export function getDateRange( + filter: SearchFilter, + params: URLSearchParams +): DateRange | undefined { + return readFilter(filter, params).range; +} + +/** + * Build the URL parameter changes that replace the state of a filter. Every + * key the filter uses now is cleared, including legacy parameters. + * + * @param filter the filter to change. + * @param values the new selected values, or undefined to remove the filter. + * @param params the current URL query parameters. + * @returns a map of parameter name to new value, undefined removes the key + * and an array is a comma separated list. + */ +export function getFilterParamChanges( + filter: SearchFilter, + values: string[] | undefined, + params: URLSearchParams +): Record { + if (filter.type === "toggle") { + const changes = clearFilterParams(filter, params); + changes[filter.id] = values?.length ? TOGGLE_ON : undefined; + return changes; + } + + if (!values?.length) { + return clearFilterParams(filter, params); + } + if (filter.selection === "date") { + return getConditionParamChanges(filter, { gte: [values[0]] }, params); + } + return getConditionParamChanges( + filter, + values.length === 1 ? { eq: values } : { in: values }, + params + ); +} + +/** + * Format a custom date range as a short label, for example "Mar 1 – 15, 2026". + * A range with one bound is labelled "From …" or "Until …". + * + * @param range the range as ISO dates. + * @param t the translation function. + * @param language the user's language preference. + * @returns the label, or undefined when the range has no valid date. + */ +export function formatDateRange( + range: DateRange, + t: TFunction, + language?: keyof typeof locales | null +): string | undefined { + const from = range.from ? parseISODate(range.from) : null; + const to = range.to ? parseISODate(range.to) : null; + if (from && to) { + return dateRangeToReadable(from, to, language); + } + if (from) { + return t("From {{ date }}", { + date: dateRangeToReadable(from, null, language), + }); + } + if (to) { + return t("Until {{ date }}", { + date: dateRangeToReadable(null, to, language), + }); + } + return undefined; +} + +/** + * Build the URL parameter changes that set a custom date range on a date + * filter, replacing any value it has now. + * + * @param filter the date filter to change. + * @param range the range as ISO dates. + * @param params the current URL query parameters. + * @returns a map of parameter name to new value, undefined removes the key. + */ +export function getDateRangeParamChanges( + filter: SearchFilter, + range: Required, + params: URLSearchParams +): Record { + return getConditionParamChanges( + filter, + { gte: [range.from], lte: [range.to] }, + params + ); +} + +/** + * Split a URL key in the `.` format. A key without an + * operator is read as `eq`. + * + * @param key the URL parameter name. + * @returns the field and operator, or undefined if the operator is unknown. + */ +export function parseKey( + key: string +): { field: string; operator: ComparisonOperator } | undefined { + const dot = key.lastIndexOf("."); + if (dot === -1) { + return { field: key, operator: "eq" }; + } + const operator = ComparisonOperator.safeParse(key.slice(dot + 1)); + return operator.success + ? { field: key.slice(0, dot), operator: operator.data } + : undefined; +} + +const matchSelection = { + operators: ["eq", "neq", "in", "notIn"], + isValidValue: (value: string, operator: ComparisonOperator) => + scalarMatchesKind("uuid", value, operator), + selection: "match", +} as const; + +const dateSelection = { + operators: [...RANGE_OPERATORS], + isValidValue: (value: string, operator: ComparisonOperator) => + scalarMatchesKind("date", value, operator), + selection: "date", + useOptions: useRelativeDateOptions, +} as const; + +function clearFilterParams( + filter: SearchFilter, + params: URLSearchParams +): Record { + const changes: Record = {}; + for (const key of params.keys()) { + if (parseKey(key)?.field === filter.id) { + changes[key] = undefined; + } + } + const legacyParam = + filter.type === "toggle" ? filter.legacyParam : filter.legacy?.param; + if (legacyParam) { + changes[legacyParam] = undefined; + } + return changes; +} + +function getConditionParamChanges( + filter: SearchFilter, + conditions: FilterConditions, + params: URLSearchParams +): Record { + const changes = clearFilterParams(filter, params); + for (const operator of ComparisonOperator.options) { + const values = conditions[operator]; + if (values?.length) { + changes[`${filter.id}.${operator}`] = isListOperator(operator) + ? values + : values[0]; + } + } + return changes; +} + +/** + * Convert date-only bounds to the start or end of that day in local time, so + * that a range includes the whole of its first and last day. + */ +function toLocalDayBounds(conditions: FilterConditions): FilterConditions { + const result: FilterConditions = { ...conditions }; + for (const operator of RANGE_OPERATORS) { + result[operator] = conditions[operator]?.map((value) => { + const date = isISODate(value) ? parseISODate(value) : null; + if (!date) { + return value; + } + const bound = + operator === "gt" || operator === "gte" + ? startOfDay(date) + : endOfDay(date); + return bound.toISOString(); + }); + } + return result; +} + +function isNullOperator(operator: ComparisonOperator) { + return operator === "isNull" || operator === "isNotNull"; +} + +function isListOperator(operator: ComparisonOperator) { + return operator === "in" || operator === "notIn"; +} + +function splitValues(operator: ComparisonOperator, raw: string): string[] { + if (isNullOperator(operator)) { + return []; + } + return isListOperator(operator) ? raw.split(",").filter(Boolean) : [raw]; +} + +function conditionsToFilter( + field: string, + conditions: FilterConditions +): Filter | undefined { + const leaves = ComparisonOperator.options.flatMap((operator): Filter[] => { + const values = conditions[operator]; + if (!values) { + return []; + } + if (isNullOperator(operator)) { + return [{ field, operator }]; + } + if (isListOperator(operator)) { + return [{ field, operator, value: values }]; + } + if (values.length > 1 && (operator === "eq" || operator === "neq")) { + return [ + { + field, + operator: operator === "eq" ? "in" : "notIn", + value: values, + }, + ]; + } + return values.map((value) => ({ field, operator, value })); + }); + + if (leaves.length === 0) { + return undefined; + } + return leaves.length === 1 ? leaves[0] : { operator: "AND", filters: leaves }; +} + +function statusesToFilter(values: string[]): Filter | undefined { + const shapes = uniq(values).filter(isStatus).map(statusToFilter); + if (shapes.length === 0) { + return undefined; + } + return shapes.length === 1 ? shapes[0] : { operator: "OR", filters: shapes }; +} + +function isStatus(value: string): value is StatusFilter { + return Object.values(StatusFilter).includes(value); +} diff --git a/app/stores/DocumentsStore.ts b/app/stores/DocumentsStore.ts index 0fdec64fc5..4d125e909a 100644 --- a/app/stores/DocumentsStore.ts +++ b/app/stores/DocumentsStore.ts @@ -21,7 +21,8 @@ import { subtractDate } from "@shared/utils/date"; import { bytesToHumanReadable } from "@shared/utils/files"; import naturalSort from "@shared/utils/naturalSort"; import type RootStore from "~/stores/RootStore"; -import Store from "~/stores/base/Store"; +import type { PaginatedResponse } from "~/stores/base/Store"; +import Store, { PAGINATION_SYMBOL } from "~/stores/base/Store"; import Document from "~/models/Document"; import env from "~/env"; import type { @@ -510,7 +511,9 @@ export default class DocumentsStore extends Store { }; @action - search = async (options: SearchParams): Promise => { + search = async ( + options: SearchParams + ): Promise> => { const compactedOptions = omitBy(options, (o) => !o); const res = await client.post("/documents.search", { ...compactedOptions, @@ -525,7 +528,7 @@ export default class DocumentsStore extends Store { // store a reference to the document model in the search cache instead // of the original result from the API. - const results: SearchResult[] = compact( + const results: PaginatedResponse = compact( res.data.map((result: SearchResult) => { const document = this.data.get(result.document.id); if (!document) { @@ -539,6 +542,7 @@ export default class DocumentsStore extends Store { }; }) ); + results[PAGINATION_SYMBOL] = res.pagination; return results; }; diff --git a/server/models/helpers/Filters.ts b/server/models/helpers/Filters.ts index 6095e4487f..3223d85163 100644 --- a/server/models/helpers/Filters.ts +++ b/server/models/helpers/Filters.ts @@ -9,9 +9,10 @@ import { createFilterSchema, DURATION_BY_DATE_FILTER, RANGE_OPERATORS, + statusToFilter, } from "@shared/helpers/FilterHelper"; import type { DateFilter, StatusFilter } from "@shared/types"; -import { StatusFilter as StatusFilterEnum, UserRole } from "@shared/types"; +import { UserRole } from "@shared/types"; import { Collection } from "@server/models"; import type User from "@server/models/User"; import { authorize } from "@server/policies"; @@ -314,29 +315,6 @@ interface LegacyParams { statusFilter?: StatusFilter[]; } -function statusToFilter(status: StatusFilter): Filter { - if (status === StatusFilterEnum.Archived) { - return { field: "archivedAt", operator: "isNotNull" }; - } - if (status === StatusFilterEnum.Published) { - return { - operator: "AND", - filters: [ - { field: "archivedAt", operator: "isNull" }, - { field: "publishedAt", operator: "isNotNull" }, - ], - }; - } - // Draft - return { - operator: "AND", - filters: [ - { field: "archivedAt", operator: "isNull" }, - { field: "publishedAt", operator: "isNull" }, - ], - }; -} - /** * Translate deprecated top-level params into an equivalent filter expression. * Callers pass only the subset of params their route accepts; each one becomes diff --git a/shared/components/Calendar.tsx b/shared/components/Calendar.tsx index 7c703e1123..e1f6da5e3f 100644 --- a/shared/components/Calendar.tsx +++ b/shared/components/Calendar.tsx @@ -25,7 +25,6 @@ export function Calendar(props: Props) { } const Wrapper = styled.div` - padding: 12px; color: ${s("text")}; .rdp { @@ -62,7 +61,7 @@ const Wrapper = styled.div` display: flex; align-items: center; justify-content: space-between; - padding: 0 2px 8px; + padding: 0 0 8px; } .rdp-caption_label { diff --git a/shared/editor/components/DateMentionPicker.tsx b/shared/editor/components/DateMentionPicker.tsx index fb36dc0c7a..0108f4bd9a 100644 --- a/shared/editor/components/DateMentionPicker.tsx +++ b/shared/editor/components/DateMentionPicker.tsx @@ -98,6 +98,7 @@ export default function DateMentionPicker({ const DatePopoverContent = styled.div` z-index: ${depths.modal}; + padding: 12px; background: ${s("menuBackground")}; box-shadow: ${s("menuShadow")}; ${borderRadius(8)} diff --git a/shared/helpers/FilterHelper.ts b/shared/helpers/FilterHelper.ts index 1e460da5ab..855f7c749e 100644 --- a/shared/helpers/FilterHelper.ts +++ b/shared/helpers/FilterHelper.ts @@ -1,8 +1,45 @@ import { z } from "zod"; import type { DateFilter } from "../types"; +import { StatusFilter } from "../types"; import { isISO8601Duration } from "../utils/date"; import { FilterValidation } from "../validations"; +/** + * Look up the ISO 8601 duration for a coarse date filter name. + * + * @param value the date filter name, such as "week". + * @returns the duration, or undefined if the value is not a date filter. + */ +export function durationForDateFilter(value: string): string | undefined { + return isDateFilter(value) ? DURATION_BY_DATE_FILTER[value] : undefined; +} + +function isDateFilter(value: string): value is DateFilter { + return Object.hasOwn(DURATION_BY_DATE_FILTER, value); +} + +/** + * Build the filter expression that matches documents with a status. + * + * @param status the document status. + * @returns the filter expression for the status. + */ +export function statusToFilter(status: StatusFilter): Filter { + if (status === StatusFilter.Archived) { + return { field: "archivedAt", operator: "isNotNull" }; + } + return { + operator: "AND", + filters: [ + { field: "archivedAt", operator: "isNull" }, + { + field: "publishedAt", + operator: status === StatusFilter.Published ? "isNotNull" : "isNull", + }, + ], + }; +} + /** The ISO 8601 duration each coarse date filter corresponds to. */ export const DURATION_BY_DATE_FILTER: Record = { day: "-P1D", @@ -134,7 +171,7 @@ export const RANGE_OPERATORS = new Set([ * @param operator the operator the value is used with. * @returns true if the value is a valid input for the field. */ -function scalarMatchesKind( +export function scalarMatchesKind( kind: FieldKind, value: unknown, operator: ComparisonOperator diff --git a/shared/i18n/locales/en_US/translation.json b/shared/i18n/locales/en_US/translation.json index d40292aa6a..2031334022 100644 --- a/shared/i18n/locales/en_US/translation.json +++ b/shared/i18n/locales/en_US/translation.json @@ -1222,25 +1222,38 @@ "Read all data": "Read all data", "Write all data": "Write all data", "Create all data": "Create all data", + "More filters": "More filters", + "More": "More", "Any collection": "Any collection", "All time": "All time", - "Past day": "Past day", - "Past week": "Past week", - "Past month": "Past month", - "Past year": "Past year", "Any time": "Any time", + "Choose the first and last day": "Choose the first and last day", + "Apply": "Apply", "Remove document filter": "Remove document filter", - "Any status": "Any status", "Remove search": "Remove search", + "Remove filter": "Remove filter", "Relevance": "Relevance", "Newest": "Newest", "Oldest": "Oldest", "A → Z": "A → Z", "Z → A": "Z → A", + "Sorted by": "Sorted by", "Any author": "Any author", - "Search titles only": "Search titles only", + "Past day": "Past day", + "Past week": "Past week", + "Past month": "Past month", + "Past year": "Past year", + "{{ count }} result": "{{ count }} result", + "{{ count }} result_plural": "{{ count }} result", "Please try again or contact support if the problem persists": "Please try again or contact support if the problem persists", "No documents found for your search filters.": "No documents found for your search filters.", + "Edited by": "Edited by", + "Status": "Status", + "Updated": "Updated", + "Created by": "Created by", + "Title only": "Title only", + "From {{ date }}": "From {{ date }}", + "Until {{ date }}": "Until {{ date }}", "Settings saved": "Settings saved", "Copied to clipboard": "Copied to clipboard", "Control how AI features are used in the workspace.": "Control how AI features are used in the workspace.", @@ -1324,7 +1337,6 @@ "Revoking": "Revoking", "Are you sure you want to revoke the {{ tokenName }} token?": "Are you sure you want to revoke the {{ tokenName }} token?", "Key": "Key", - "Created by": "Created by", "Never": "Never", "Expires": "Expires", "Could not load preference": "Could not load preference", @@ -1432,6 +1444,7 @@ "Editors": "Editors", "Invited by": "Invited by", "Joined": "Joined", + "Any status": "Any status", "Active": "Active", "Could not load emojis": "Could not load emojis", "Custom emojis can be used throughout your workspace in documents, comments, and reactions.": "Custom emojis can be used throughout your workspace in documents, comments, and reactions.", diff --git a/shared/utils/date.ts b/shared/utils/date.ts index 33bdb5fdfc..4020b395c9 100644 --- a/shared/utils/date.ts +++ b/shared/utils/date.ts @@ -367,6 +367,16 @@ export function toISODateTime(date: Date): string { const isoDateRegex = /^\d{4}-\d{2}-\d{2}$/; const isoDateTimeRegex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/; +/** + * Whether a string is a date-only ISO value (yyyy-MM-dd). + * + * @param value The string to check. + * @returns true when the value is a date-only ISO string. + */ +export function isISODate(value: string): boolean { + return isoDateRegex.test(value); +} + /** * Whether a date mention's stored ISO value carries a time component. *