mirror of
https://github.com/outline/outline.git
synced 2026-11-20 21:23:06 +03:00
Redesign search filters with a scalable chip bar (#14589)
* Redesign search filters * Design refinement * Search filter polish: chip states, Text components, Published filter * Encode search filters as <field>.<operator> URL params Filters read and write a standard <field>.<operator>=<value> format, a bare key reads as eq, and the previous dateFilter, statusFilter and titleFilter params are still read. * Add custom date ranges to search date filters Updated, Created and Published get a Custom option that opens a range calendar in a modal. The range is stored as <field>.gte and <field>.lte dates and sent to the API as whole days in local time. * Keep date filter chip shown while its range dialog is open * Align calendar with modal edges The calendar had its own 12px padding, so in modals it sat inside the title and footer edges. The popovers that need the space now pad it. * Search filter refinements: menu height, chip spacing, steady results line * Simplify search filters and address review comments Parse each filter once per URL change, unify URL writes, share status and date helpers with the server, add a maxHeight prop to MenuContent, ignore counts from obsolete searches, and show the empty state for filter-only searches. * Refine filter chip remove button and skip animation on auto-opened menus
This commit is contained in:
1 parent
6a6987ec2d
commit
c3274d17d1
29 files changed
+2450
-476
No files matched your search
@@ -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 };
|
||||
};
|
||||
@@ -70,14 +70,16 @@ const ExpiryDatePicker = ({
|
||||
side="right"
|
||||
shrink
|
||||
>
|
||||
<Calendar
|
||||
required
|
||||
mode="single"
|
||||
selected={selectedDate}
|
||||
onSelect={handleSelect}
|
||||
locale={locale}
|
||||
disabled={{ before: new Date() }}
|
||||
/>
|
||||
<CalendarPadding>
|
||||
<Calendar
|
||||
required
|
||||
mode="single"
|
||||
selected={selectedDate}
|
||||
onSelect={handleSelect}
|
||||
locale={locale}
|
||||
disabled={{ before: new Date() }}
|
||||
/>
|
||||
</CalendarPadding>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
{selectedDate && onClear && (
|
||||
@@ -96,6 +98,10 @@ const ExpiryDatePicker = ({
|
||||
);
|
||||
};
|
||||
|
||||
const CalendarPadding = styled.div`
|
||||
padding: 12px;
|
||||
`;
|
||||
|
||||
const Wrapper = styled.div`
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
|
||||
@@ -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<PaginatedItem[]>;
|
||||
fetchQueryOptions?: Record<string, string>;
|
||||
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<HTMLInputElement>(null);
|
||||
const listRef = React.useRef<HTMLDivElement | null>(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 ?? (
|
||||
<StyledButton
|
||||
className={className}
|
||||
icon={selectedItems[0]?.key && selectedItems[0]?.icon}
|
||||
@@ -271,7 +292,12 @@ const FilterOptions = ({
|
||||
<MenuProvider variant="dropdown">
|
||||
<Menu open={open} onOpenChange={setOpen}>
|
||||
<MenuTrigger>{trigger}</MenuTrigger>
|
||||
<MenuContent aria-label={defaultLabel} align="start">
|
||||
<MenuContent
|
||||
aria-label={defaultLabel}
|
||||
align="start"
|
||||
maxHeight="75vh"
|
||||
skipAnimation={skipAnimation}
|
||||
>
|
||||
{list}
|
||||
{showFilterInput && (
|
||||
<SearchInput
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
type Props = {
|
||||
/** The size of the icon, 24px is default to match standard icons */
|
||||
size?: number;
|
||||
/** The color of the icon, defaults to the current text color */
|
||||
color?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Three stacked lines of decreasing width, used for filter controls.
|
||||
*
|
||||
* @param props the icon props.
|
||||
* @returns the icon.
|
||||
*/
|
||||
export function FilterIcon({ size = 24, color = "currentColor" }: Props) {
|
||||
return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill={color}>
|
||||
<rect x="5" y="7" width="14" height="2" rx="1" />
|
||||
<rect x="7.5" y="11" width="9" height="2" rx="1" />
|
||||
<rect x="10" y="15" width="4" height="2" rx="1" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -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 (
|
||||
<form onSubmit={handleSubmit}>
|
||||
<Flex gap={12} column>
|
||||
<CalendarWrapper>
|
||||
<Calendar
|
||||
required
|
||||
mode="single"
|
||||
numberOfMonths={2}
|
||||
selected={date}
|
||||
onSelect={setDate}
|
||||
defaultMonth={date}
|
||||
locale={dateLocale(userLocale)}
|
||||
disabled={{ before: new Date() }}
|
||||
/>
|
||||
</CalendarWrapper>
|
||||
<Calendar
|
||||
required
|
||||
mode="single"
|
||||
numberOfMonths={2}
|
||||
selected={date}
|
||||
onSelect={setDate}
|
||||
defaultMonth={date}
|
||||
locale={dateLocale(userLocale)}
|
||||
disabled={{ before: new Date() }}
|
||||
/>
|
||||
<Flex justify="flex-end">
|
||||
<Button type="submit" disabled={!date || isSaving}>
|
||||
{isSaving ? `${t("Saving")}…` : t("Save")}
|
||||
@@ -85,8 +82,3 @@ export const ShareExpiryDialog = observer(function ShareExpiryDialog({
|
||||
</form>
|
||||
);
|
||||
});
|
||||
|
||||
const CalendarWrapper = styled.div`
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
`;
|
||||
@@ -78,11 +78,15 @@ type ContentProps = React.ComponentPropsWithoutRef<
|
||||
> &
|
||||
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Content> & {
|
||||
ref?: React.Ref<React.ComponentRef<typeof DropdownMenuPrimitive.Content>>;
|
||||
/** The largest height of the menu, defaults to 85vh. */
|
||||
maxHeight?: string;
|
||||
/** Show the menu at once, without the opening animation. */
|
||||
skipAnimation?: boolean;
|
||||
};
|
||||
|
||||
function MenuContent(props: ContentProps) {
|
||||
const { variant } = useMenuContext();
|
||||
const { ref, children, ...rest } = props;
|
||||
const { ref, children, maxHeight, skipAnimation, ...rest } = props;
|
||||
|
||||
const Portal =
|
||||
variant === "dropdown"
|
||||
@@ -111,7 +115,12 @@ function MenuContent(props: ContentProps) {
|
||||
return (
|
||||
<Portal>
|
||||
<Content ref={ref} {...offsetProp} {...rest} collisionPadding={6} asChild>
|
||||
<Components.MenuContent {...contentProps} hiddenScrollbars>
|
||||
<Components.MenuContent
|
||||
{...contentProps}
|
||||
maxHeight={maxHeight}
|
||||
$skipAnimation={skipAnimation}
|
||||
hiddenScrollbars
|
||||
>
|
||||
{children}
|
||||
</Components.MenuContent>
|
||||
</Content>
|
||||
|
||||
@@ -194,6 +194,10 @@ export const MenuShortcut = styled.span`
|
||||
type MenuContentProps = {
|
||||
maxHeightVar: string;
|
||||
transformOriginVar: string;
|
||||
/** The largest height of the menu, defaults to 85vh. */
|
||||
maxHeight?: string;
|
||||
/** Show the menu at once, without the opening animation. */
|
||||
$skipAnimation?: boolean;
|
||||
};
|
||||
|
||||
export const MenuContent = styled(Scrollable).attrs<MenuContentProps>(
|
||||
@@ -207,7 +211,8 @@ export const MenuContent = styled(Scrollable).attrs<MenuContentProps>(
|
||||
min-width: 180px;
|
||||
max-width: 320px;
|
||||
min-height: 44px;
|
||||
max-height: ${({ maxHeightVar }) => `min(85vh, var(${maxHeightVar}))`};
|
||||
max-height: ${({ maxHeight = "85vh", maxHeightVar }) =>
|
||||
`min(${maxHeight}, var(${maxHeightVar}))`};
|
||||
font-weight: normal;
|
||||
|
||||
background: ${s("menuBackground")};
|
||||
@@ -227,9 +232,13 @@ export const MenuContent = styled(Scrollable).attrs<MenuContentProps>(
|
||||
|
||||
transform-origin: ${({ transformOriginVar }) => `var(${transformOriginVar})`};
|
||||
|
||||
&[data-state="open"] {
|
||||
animation: ${fadeAndScaleIn} 150ms ease-out;
|
||||
}
|
||||
${({ $skipAnimation }) =>
|
||||
!$skipAnimation &&
|
||||
css`
|
||||
&[data-state="open"] {
|
||||
animation: ${fadeAndScaleIn} 150ms ease-out;
|
||||
}
|
||||
`}
|
||||
|
||||
@media print {
|
||||
display: none;
|
||||
|
||||
+290
-210
@@ -8,13 +8,10 @@ import styled from "styled-components";
|
||||
import { breakpoint } from "@shared/styles/breakpoint";
|
||||
import { Pagination } from "@shared/constants";
|
||||
import type { Filter } from "@shared/helpers/FilterHelper";
|
||||
import { DURATION_BY_DATE_FILTER } from "@shared/helpers/FilterHelper";
|
||||
import type {
|
||||
SortFilter as TSortFilter,
|
||||
DirectionFilter as TDirectionFilter,
|
||||
DateFilter as TDateFilter,
|
||||
} from "@shared/types";
|
||||
import { StatusFilter as TStatusFilter } from "@shared/types";
|
||||
import ArrowKeyNavigation from "~/components/ArrowKeyNavigation";
|
||||
import DocumentListItem from "~/components/DocumentListItem";
|
||||
import DocumentSelectionToolbar from "~/components/DocumentSelectionToolbar";
|
||||
@@ -24,31 +21,39 @@ import LoadingIndicator from "~/components/LoadingIndicator";
|
||||
import { ModelSelectionProvider } from "~/components/ModelSelectionContext";
|
||||
import RegisterKeyDown from "~/components/RegisterKeyDown";
|
||||
import Scene from "~/components/Scene";
|
||||
import Switch from "~/components/Switch";
|
||||
import Text from "~/components/Text";
|
||||
import { Waypoint } from "~/components/Waypoint";
|
||||
import usePaginatedRequest from "~/hooks/usePaginatedRequest";
|
||||
import useQuery from "~/hooks/useQuery";
|
||||
import useStores from "~/hooks/useStores";
|
||||
import useUserLocale from "~/hooks/useUserLocale";
|
||||
import { PAGINATION_SYMBOL } from "~/stores/base/Store";
|
||||
import type { PaginationParams, SearchResult } from "~/types";
|
||||
import { preventDefault } from "~/utils/events";
|
||||
import { searchPath } from "~/utils/routeHelpers";
|
||||
import { decodeURIComponentSafe, isTruthyQueryValue } from "~/utils/urls";
|
||||
import CollectionFilter from "./components/CollectionFilter";
|
||||
import DateFilter from "./components/DateFilter";
|
||||
import { decodeURIComponentSafe } from "~/utils/urls";
|
||||
import { AddFilterButton } from "./components/AddFilterButton";
|
||||
import { DocumentFilter } from "./components/DocumentFilter";
|
||||
import DocumentTypeFilter from "./components/DocumentTypeFilter";
|
||||
import RecentSearches from "./components/RecentSearches";
|
||||
import SearchInput from "./components/SearchInput";
|
||||
import { SortInput } from "./components/SortInput";
|
||||
import UserFilter from "./components/UserFilter";
|
||||
import { HStack } from "~/components/primitives/HStack";
|
||||
import useMobile from "~/hooks/useMobile";
|
||||
import { SearchFilterChip } from "./components/SearchFilterChip";
|
||||
import { DateRangeDialog } from "./components/DateRangeDialog";
|
||||
import type { DateRange, SearchFilter } from "./searchFilters";
|
||||
import {
|
||||
TOGGLE_ON,
|
||||
formatDateRange,
|
||||
getDateRange,
|
||||
getDateRangeParamChanges,
|
||||
getFilterParamChanges,
|
||||
readFilter,
|
||||
useSearchFilters,
|
||||
} from "./searchFilters";
|
||||
|
||||
function Search() {
|
||||
const { t } = useTranslation();
|
||||
const { documents, searches, policies } = useStores();
|
||||
const isMobile = useMobile();
|
||||
const { documents, searches, policies, dialogs } = useStores();
|
||||
const userLocale = useUserLocale();
|
||||
|
||||
// routing
|
||||
const params = useQuery();
|
||||
@@ -66,99 +71,79 @@ function Search() {
|
||||
routeMatch.params.query ?? params.get("q") ?? params.get("query") ?? ""
|
||||
).trim();
|
||||
const query = decodedQuery !== "" ? decodedQuery : undefined;
|
||||
const collectionId = params.get("collectionId") ?? "";
|
||||
const userId = params.get("userId") ?? "";
|
||||
const documentId = params.get("documentId") ?? undefined;
|
||||
const dateFilter = (params.get("dateFilter") as TDateFilter) ?? "";
|
||||
// Keyed on the serialized value so the array keeps a stable identity between
|
||||
// renders and can be used directly as a dependency.
|
||||
const statusFilterKey = params.getAll("statusFilter").join(",");
|
||||
const statusFilter = React.useMemo(
|
||||
() =>
|
||||
statusFilterKey
|
||||
? (statusFilterKey.split(",") as TStatusFilter[])
|
||||
: [TStatusFilter.Published, TStatusFilter.Draft],
|
||||
[statusFilterKey]
|
||||
);
|
||||
const titleFilter = isTruthyQueryValue(params.get("titleFilter"));
|
||||
const documentId =
|
||||
params.get("documentId") ?? params.get("documentId.eq") ?? undefined;
|
||||
const sort = (params.get("sort") as TSortFilter) ?? "";
|
||||
const direction = (params.get("direction") as TDirectionFilter) ?? "";
|
||||
|
||||
const isSearchable = !!(query || collectionId || userId);
|
||||
|
||||
const document = documentId ? documents.get(documentId) : undefined;
|
||||
|
||||
const filterVisibility = {
|
||||
document: !!document,
|
||||
collection: !document,
|
||||
user: !document || !!(document && query),
|
||||
documentType: isSearchable,
|
||||
date: isSearchable,
|
||||
title: !!query && !document,
|
||||
sort: isSearchable,
|
||||
};
|
||||
const searchFilters = useSearchFilters();
|
||||
// A filter added from the "More" menu shows while its options are open.
|
||||
const [pendingFilterId, setPendingFilterId] = React.useState<string>();
|
||||
// A filter stays shown while its custom date range dialog is open.
|
||||
const [rangeFilterId, setRangeFilterId] = React.useState<string>();
|
||||
|
||||
const filters = React.useMemo<Filter[] | undefined>(() => {
|
||||
const children: Filter[] = [];
|
||||
if (collectionId) {
|
||||
children.push({
|
||||
field: "collectionId",
|
||||
operator: "eq",
|
||||
value: collectionId,
|
||||
});
|
||||
}
|
||||
if (userId) {
|
||||
children.push({ field: "userId", operator: "eq", value: userId });
|
||||
}
|
||||
if (documentId) {
|
||||
children.push({
|
||||
field: "documentId",
|
||||
operator: "eq",
|
||||
value: documentId,
|
||||
});
|
||||
}
|
||||
if (dateFilter) {
|
||||
const duration = DURATION_BY_DATE_FILTER[dateFilter];
|
||||
if (duration) {
|
||||
children.push({ field: "updatedAt", operator: "gte", value: duration });
|
||||
const { isSearchable, visibleFilters, filterStates, filters, titleFilter } =
|
||||
React.useMemo(() => {
|
||||
const visible = searchFilters.filter(
|
||||
(filter) => filter.isAvailable?.({ document }) ?? true
|
||||
);
|
||||
const states = new Map(
|
||||
visible.map((filter) => [filter.id, readFilter(filter, params)])
|
||||
);
|
||||
const setStates = [...states.values()];
|
||||
|
||||
const expressions = setStates
|
||||
.map((state) => state.apiFilter)
|
||||
.filter((filter): filter is Filter => !!filter);
|
||||
if (documentId) {
|
||||
expressions.push({
|
||||
field: "documentId",
|
||||
operator: "eq",
|
||||
value: documentId,
|
||||
});
|
||||
}
|
||||
}
|
||||
if (statusFilter.length > 0) {
|
||||
const statusShape = (status: TStatusFilter): Filter => {
|
||||
if (status === TStatusFilter.Archived) {
|
||||
return { field: "archivedAt", operator: "isNotNull" };
|
||||
}
|
||||
if (status === TStatusFilter.Published) {
|
||||
return {
|
||||
operator: "AND",
|
||||
filters: [
|
||||
{ field: "archivedAt", operator: "isNull" },
|
||||
{ field: "publishedAt", operator: "isNotNull" },
|
||||
],
|
||||
};
|
||||
}
|
||||
return {
|
||||
operator: "AND",
|
||||
filters: [
|
||||
{ field: "archivedAt", operator: "isNull" },
|
||||
{ field: "publishedAt", operator: "isNull" },
|
||||
],
|
||||
};
|
||||
|
||||
return {
|
||||
// Show results when there is a query or at least one filter is set.
|
||||
isSearchable:
|
||||
!!query || !!documentId || setStates.some((state) => state.isSet),
|
||||
visibleFilters: visible,
|
||||
filterStates: states,
|
||||
filters: expressions.length > 0 ? expressions : undefined,
|
||||
// An empty query matches every title, so list all results without one.
|
||||
titleFilter: !!query && !!states.get("titleOnly")?.isSet,
|
||||
};
|
||||
const statusGroup =
|
||||
statusFilter.length === 1
|
||||
? statusShape(statusFilter[0])
|
||||
: ({
|
||||
operator: "OR",
|
||||
filters: statusFilter.map(statusShape),
|
||||
} as Filter);
|
||||
children.push(statusGroup);
|
||||
}
|
||||
if (children.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
return children;
|
||||
}, [collectionId, userId, documentId, dateFilter, statusFilter]);
|
||||
}, [searchFilters, params, query, document, documentId]);
|
||||
|
||||
const rangeLabels = React.useMemo(
|
||||
() =>
|
||||
new Map(
|
||||
[...filterStates].map(([id, state]) => [
|
||||
id,
|
||||
state.range ? formatDateRange(state.range, t, userLocale) : undefined,
|
||||
])
|
||||
),
|
||||
[filterStates, t, userLocale]
|
||||
);
|
||||
|
||||
const isCollectionScoped = !!filterStates.get("collectionId")?.isSet;
|
||||
|
||||
const { shownFilters, addableFilters } = React.useMemo(() => {
|
||||
const shown = visibleFilters.filter(
|
||||
(filter) =>
|
||||
filter.pinned ||
|
||||
filterStates.get(filter.id)?.isSet ||
|
||||
pendingFilterId === filter.id ||
|
||||
rangeFilterId === filter.id
|
||||
);
|
||||
return {
|
||||
shownFilters: shown,
|
||||
addableFilters: visibleFilters.filter(
|
||||
(filter) => !shown.includes(filter)
|
||||
),
|
||||
};
|
||||
}, [visibleFilters, filterStates, pendingFilterId, rangeFilterId]);
|
||||
|
||||
const requestParams = React.useMemo(
|
||||
() => ({
|
||||
@@ -171,6 +156,17 @@ function Search() {
|
||||
[query, titleFilter, sort, direction, filters]
|
||||
);
|
||||
|
||||
const [resultCount, setResultCount] = React.useState<{
|
||||
params: typeof requestParams;
|
||||
total: number;
|
||||
}>();
|
||||
|
||||
// Responses from earlier searches must not replace the current count.
|
||||
const currentRequestParams = React.useRef(requestParams);
|
||||
React.useEffect(() => {
|
||||
currentRequestParams.current = requestParams;
|
||||
}, [requestParams]);
|
||||
|
||||
const requestFn = React.useMemo(() => {
|
||||
// Add to the searches store so this search can immediately appear in the recent searches list
|
||||
// without a flash of loading.
|
||||
@@ -188,15 +184,26 @@ function Search() {
|
||||
offset: params?.offset,
|
||||
limit: params?.limit,
|
||||
};
|
||||
return titleFilter
|
||||
? await documents.searchTitles({
|
||||
...requestParams,
|
||||
...paginationParams,
|
||||
})
|
||||
: await documents.search({
|
||||
...requestParams,
|
||||
...paginationParams,
|
||||
});
|
||||
if (titleFilter) {
|
||||
return await documents.searchTitles({
|
||||
...requestParams,
|
||||
...paginationParams,
|
||||
});
|
||||
}
|
||||
|
||||
const results = await documents.search({
|
||||
...requestParams,
|
||||
...paginationParams,
|
||||
});
|
||||
const total = results[PAGINATION_SYMBOL]?.total;
|
||||
if (
|
||||
!params?.offset &&
|
||||
total !== undefined &&
|
||||
currentRequestParams.current === requestParams
|
||||
) {
|
||||
setResultCount({ params: requestParams, total });
|
||||
}
|
||||
return results;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -207,6 +214,10 @@ function Search() {
|
||||
limit: Pagination.defaultLimit,
|
||||
});
|
||||
|
||||
// Keep the previous count on screen, disabled, until the new one arrives.
|
||||
const isResultCountStale = resultCount?.params !== requestParams;
|
||||
const total = titleFilter || error ? undefined : resultCount?.total;
|
||||
|
||||
// Only updatable documents are selectable, matching the per-item checkboxes.
|
||||
const itemIds = React.useMemo(
|
||||
() =>
|
||||
@@ -233,33 +244,96 @@ function Search() {
|
||||
});
|
||||
};
|
||||
|
||||
// All filters go through the query string so that searches are bookmarkable, which neccesitates
|
||||
// some complexity as the query string is the source of truth for the filters.
|
||||
const handleFilterChange = (search: {
|
||||
collectionId?: string | undefined;
|
||||
documentId?: string | undefined;
|
||||
userId?: string | undefined;
|
||||
dateFilter?: TDateFilter;
|
||||
statusFilter?: TStatusFilter[];
|
||||
titleFilter?: boolean | undefined;
|
||||
sort?: string | undefined;
|
||||
direction?: string | undefined;
|
||||
}) => {
|
||||
if (search.sort === "relevance") {
|
||||
search.sort = undefined;
|
||||
search.direction = undefined;
|
||||
}
|
||||
// All filters go through the query string so that searches are bookmarkable,
|
||||
// which means the query string is the source of truth for the filters.
|
||||
const replaceParams = React.useCallback(
|
||||
(
|
||||
getChanges: (
|
||||
current: URLSearchParams
|
||||
) => Record<string, string | string[] | undefined>
|
||||
) => {
|
||||
const { search } = history.location;
|
||||
history.replace({
|
||||
pathname: history.location.pathname,
|
||||
search: queryString.stringify(
|
||||
{
|
||||
...queryString.parse(search),
|
||||
...getChanges(new URLSearchParams(search)),
|
||||
},
|
||||
{ skipEmptyString: true, arrayFormat: "comma" }
|
||||
),
|
||||
});
|
||||
},
|
||||
[history]
|
||||
);
|
||||
|
||||
history.replace({
|
||||
pathname: history.location.pathname,
|
||||
search: queryString.stringify(
|
||||
{ ...queryString.parse(history.location.search), ...search },
|
||||
{
|
||||
skipEmptyString: true,
|
||||
}
|
||||
const handleChangeFilter = React.useCallback(
|
||||
(filter: SearchFilter, values: string[] | undefined) =>
|
||||
replaceParams((current) =>
|
||||
getFilterParamChanges(filter, values, current)
|
||||
),
|
||||
});
|
||||
};
|
||||
[replaceParams]
|
||||
);
|
||||
|
||||
const handleCustomRange = React.useCallback(
|
||||
(filter: SearchFilter) => {
|
||||
const handleSubmit = (range: Required<DateRange>) => {
|
||||
replaceParams((current) =>
|
||||
getDateRangeParamChanges(filter, range, current)
|
||||
);
|
||||
setRangeFilterId(undefined);
|
||||
dialogs.closeAllModals();
|
||||
};
|
||||
|
||||
setRangeFilterId(filter.id);
|
||||
dialogs.openModal({
|
||||
title: filter.label,
|
||||
width: "600px",
|
||||
onClose: () => setRangeFilterId(undefined),
|
||||
content: (
|
||||
<DateRangeDialog
|
||||
defaultRange={getDateRange(
|
||||
filter,
|
||||
new URLSearchParams(history.location.search)
|
||||
)}
|
||||
onSubmit={handleSubmit}
|
||||
/>
|
||||
),
|
||||
});
|
||||
},
|
||||
[dialogs, history, replaceParams]
|
||||
);
|
||||
|
||||
const handleAddFilter = React.useCallback(
|
||||
(id: string) => {
|
||||
const filter = searchFilters.find((item) => item.id === id);
|
||||
if (filter?.type === "toggle") {
|
||||
handleChangeFilter(filter, [TOGGLE_ON]);
|
||||
return;
|
||||
}
|
||||
setPendingFilterId(id);
|
||||
},
|
||||
[searchFilters, handleChangeFilter]
|
||||
);
|
||||
|
||||
const handleFilterOpenChange = React.useCallback(
|
||||
(filter: SearchFilter, open: boolean) => {
|
||||
if (!open) {
|
||||
setPendingFilterId((id) => (id === filter.id ? undefined : id));
|
||||
}
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
const handleSort = React.useCallback(
|
||||
(sort: string, direction: string) =>
|
||||
replaceParams(() =>
|
||||
sort === "relevance"
|
||||
? { sort: undefined, direction: undefined }
|
||||
: { sort, direction }
|
||||
),
|
||||
[replaceParams]
|
||||
);
|
||||
|
||||
const handleKeyDown = (ev: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
if (ev.nativeEvent.isComposing) {
|
||||
@@ -309,21 +383,28 @@ function Search() {
|
||||
};
|
||||
|
||||
const handleEscape = () => searchInputRef.current?.focus();
|
||||
const showEmpty = !loading && query && data?.length === 0;
|
||||
const showEmpty = !loading && isSearchable && data?.length === 0;
|
||||
|
||||
const sortInput = filterVisibility.sort ? (
|
||||
<SortInput
|
||||
sort={sort}
|
||||
direction={direction}
|
||||
onSelect={(sort, direction) => handleFilterChange({ sort, direction })}
|
||||
const renderFilterChip = (filter: SearchFilter) => (
|
||||
<SearchFilterChip
|
||||
key={filter.id}
|
||||
filter={filter}
|
||||
values={filterStates.get(filter.id)?.values ?? EMPTY_VALUES}
|
||||
isSet={!!filterStates.get(filter.id)?.isSet}
|
||||
defaultOpen={pendingFilterId === filter.id}
|
||||
onChange={handleChangeFilter}
|
||||
onOpenChange={handleFilterOpenChange}
|
||||
rangeLabel={rangeLabels.get(filter.id)}
|
||||
onCustomRange={handleCustomRange}
|
||||
/>
|
||||
);
|
||||
|
||||
const sortInput = isSearchable ? (
|
||||
<SortInput sort={sort} direction={direction} onSelect={handleSort} />
|
||||
) : null;
|
||||
|
||||
return (
|
||||
<Scene
|
||||
textTitle={query ? `${query} – ${t("Search")}` : t("Search")}
|
||||
actions={isMobile ? sortInput : null}
|
||||
>
|
||||
<Scene textTitle={query ? `${query} – ${t("Search")}` : t("Search")}>
|
||||
<RegisterKeyDown trigger="Escape" handler={handleGoBack} />
|
||||
{loading && <LoadingIndicator />}
|
||||
<ResultsWrapper column auto>
|
||||
@@ -335,66 +416,50 @@ function Search() {
|
||||
placeholder={`${
|
||||
documentId
|
||||
? t("Search in document")
|
||||
: collectionId
|
||||
: isCollectionScoped
|
||||
? t("Search in collection")
|
||||
: t("Search")
|
||||
}…`}
|
||||
onKeyDown={handleKeyDown}
|
||||
defaultValue={query ?? ""}
|
||||
/>
|
||||
<Filters>
|
||||
<Flex align="center" gap={4} wrap>
|
||||
{filterVisibility.document && (
|
||||
<DocumentFilter
|
||||
document={document!}
|
||||
onClick={() => {
|
||||
handleFilterChange({ documentId: undefined });
|
||||
}}
|
||||
/>
|
||||
<FilterChips align="center" gap={6} wrap>
|
||||
{document && (
|
||||
<DocumentFilter
|
||||
document={document}
|
||||
onRemove={() =>
|
||||
replaceParams(() => ({
|
||||
documentId: undefined,
|
||||
"documentId.eq": undefined,
|
||||
}))
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{shownFilters.map(renderFilterChip)}
|
||||
{addableFilters.length > 0 && (
|
||||
<AddFilterButton
|
||||
filters={addableFilters}
|
||||
onSelect={handleAddFilter}
|
||||
/>
|
||||
)}
|
||||
</FilterChips>
|
||||
{sortInput && (
|
||||
<ResultsMeta
|
||||
as="div"
|
||||
type="secondary"
|
||||
size="small"
|
||||
aria-busy={isResultCountStale}
|
||||
$disabled={isResultCountStale && total !== undefined}
|
||||
>
|
||||
{total !== undefined && (
|
||||
<>
|
||||
<span>{t("{{ count }} result", { count: total })}</span>
|
||||
<span aria-hidden>·</span>
|
||||
</>
|
||||
)}
|
||||
{filterVisibility.collection && (
|
||||
<CollectionFilter
|
||||
collectionId={collectionId}
|
||||
onSelect={(collectionId) =>
|
||||
handleFilterChange({ collectionId })
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{filterVisibility.user && (
|
||||
<UserFilter
|
||||
userId={userId}
|
||||
onSelect={(userId) => handleFilterChange({ userId })}
|
||||
/>
|
||||
)}
|
||||
{filterVisibility.documentType && (
|
||||
<DocumentTypeFilter
|
||||
statusFilter={statusFilter}
|
||||
onSelect={({ statusFilter }) =>
|
||||
handleFilterChange({ statusFilter })
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{filterVisibility.date && (
|
||||
<DateFilter
|
||||
dateFilter={dateFilter}
|
||||
onSelect={(dateFilter) => handleFilterChange({ dateFilter })}
|
||||
/>
|
||||
)}
|
||||
{filterVisibility.title && (
|
||||
<SearchTitlesFilter
|
||||
width={26}
|
||||
height={14}
|
||||
label={t("Search titles only")}
|
||||
onChange={(checked: boolean) => {
|
||||
handleFilterChange({ titleFilter: checked });
|
||||
}}
|
||||
checked={titleFilter}
|
||||
inForm={false}
|
||||
/>
|
||||
)}
|
||||
</Flex>
|
||||
{isMobile ? null : sortInput}
|
||||
</Filters>
|
||||
{sortInput}
|
||||
</ResultsMeta>
|
||||
)}
|
||||
</form>
|
||||
{isSearchable ? (
|
||||
<>
|
||||
@@ -451,7 +516,7 @@ function Search() {
|
||||
</ResultList>
|
||||
</ModelSelectionProvider>
|
||||
</>
|
||||
) : documentId ? null : (
|
||||
) : (
|
||||
<RecentSearches ref={recentSearchesRef} onEscape={handleEscape} />
|
||||
)}
|
||||
</ResultsWrapper>
|
||||
@@ -482,24 +547,39 @@ const StyledArrowKeyNavigation = styled(ArrowKeyNavigation)`
|
||||
flex: 1;
|
||||
`;
|
||||
|
||||
const Filters = styled(HStack)`
|
||||
flex-wrap: wrap;
|
||||
justify-content: space-between;
|
||||
const FilterChips = styled(Flex)`
|
||||
row-gap: 8px;
|
||||
margin-bottom: 12px;
|
||||
transition: opacity 100ms ease-in-out;
|
||||
padding: 8px 0;
|
||||
padding-top: 4px;
|
||||
|
||||
${breakpoint("tablet")`
|
||||
padding: 0;
|
||||
${breakpoint("mobile", "tablet")`
|
||||
flex-wrap: nowrap;
|
||||
overflow-x: auto;
|
||||
scrollbar-width: none;
|
||||
margin-inline: -16px;
|
||||
padding: 4px 16px 0;
|
||||
|
||||
& > * {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
`};
|
||||
`;
|
||||
|
||||
const SearchTitlesFilter = styled(Switch)`
|
||||
white-space: nowrap;
|
||||
margin-left: 8px;
|
||||
font-size: 14px;
|
||||
font-weight: 400;
|
||||
height: 28px;
|
||||
const ResultsMeta = styled(Text)<{ $disabled: boolean }>`
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
margin-bottom: 8px;
|
||||
transition: opacity 100ms ease-out;
|
||||
|
||||
${(props) =>
|
||||
props.$disabled &&
|
||||
`
|
||||
opacity: 0.8;
|
||||
pointer-events: none;
|
||||
`}
|
||||
`;
|
||||
|
||||
const EMPTY_VALUES: string[] = [];
|
||||
|
||||
export default observer(Search);
|
||||
@@ -0,0 +1,59 @@
|
||||
import { useCallback, useMemo } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import FilterOptions from "~/components/FilterOptions";
|
||||
import { FilterIcon } from "~/components/Icons/FilterIcon";
|
||||
import type { SearchFilter } from "../searchFilters";
|
||||
import { Chip, ChipButton, ChipContent } from "./FilterChip";
|
||||
|
||||
interface Props {
|
||||
/** The filters that can be added. */
|
||||
filters: SearchFilter[];
|
||||
/** Callback when a filter is picked. */
|
||||
onSelect: (id: string) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* A button that opens a list of the filters that are not shown yet.
|
||||
*
|
||||
* @param props the button props.
|
||||
* @returns the add filter button.
|
||||
*/
|
||||
export function AddFilterButton({ filters, onSelect }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const handleSelect = useCallback(
|
||||
(key: string | null | undefined) => {
|
||||
if (key) {
|
||||
onSelect(key);
|
||||
}
|
||||
},
|
||||
[onSelect]
|
||||
);
|
||||
|
||||
const options = useMemo(
|
||||
() =>
|
||||
filters.map((filter) => ({
|
||||
key: filter.id,
|
||||
label: filter.label,
|
||||
icon: filter.icon,
|
||||
})),
|
||||
[filters]
|
||||
);
|
||||
|
||||
return (
|
||||
<Chip>
|
||||
<FilterOptions
|
||||
options={options}
|
||||
selectedKeys={NO_SELECTION}
|
||||
onSelect={handleSelect}
|
||||
defaultLabel={t("More filters")}
|
||||
trigger={
|
||||
<ChipButton aria-label={t("More filters")}>
|
||||
<ChipContent icon={<FilterIcon />} label={t("More")} disclosure />
|
||||
</ChipButton>
|
||||
}
|
||||
/>
|
||||
</Chip>
|
||||
);
|
||||
}
|
||||
|
||||
const NO_SELECTION: string[] = [];
|
||||
@@ -3,8 +3,7 @@ import { CollectionIcon as SVGCollectionIcon } from "outline-icons";
|
||||
import { useMemo } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import FilterOptions from "~/components/FilterOptions";
|
||||
import CollectionIcon from "~/components/Icons/CollectionIcon";
|
||||
import useStores from "~/hooks/useStores";
|
||||
import { useCollectionOptions } from "../filterOptions";
|
||||
|
||||
type Props = {
|
||||
/** The currently selected collection ID */
|
||||
@@ -15,23 +14,19 @@ type Props = {
|
||||
|
||||
function CollectionFilter(props: Props) {
|
||||
const { t } = useTranslation();
|
||||
const { collections } = useStores();
|
||||
const { onSelect, collectionId } = props;
|
||||
const options = useMemo(() => {
|
||||
const collectionOptions = collections.orderedData.map((collection) => ({
|
||||
key: collection.id,
|
||||
label: collection.displayName,
|
||||
icon: <CollectionIcon collection={collection} size={24} />,
|
||||
}));
|
||||
return [
|
||||
const source = useCollectionOptions();
|
||||
const options = useMemo(
|
||||
() => [
|
||||
{
|
||||
key: "",
|
||||
label: t("Any collection"),
|
||||
icon: <SVGCollectionIcon size={24} />,
|
||||
},
|
||||
...collectionOptions,
|
||||
];
|
||||
}, [collections.orderedData, t]);
|
||||
...source.options,
|
||||
],
|
||||
[source.options, t]
|
||||
);
|
||||
|
||||
return (
|
||||
<FilterOptions
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useMemo } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { DateFilter as TDateFilter } from "@shared/types";
|
||||
import FilterOptions from "~/components/FilterOptions";
|
||||
import { useDateOptions } from "../filterOptions";
|
||||
|
||||
type Props = {
|
||||
/** The selected date filter */
|
||||
@@ -12,30 +13,10 @@ type Props = {
|
||||
|
||||
const DateFilter = ({ dateFilter, onSelect }: Props) => {
|
||||
const { t } = useTranslation();
|
||||
const source = useDateOptions();
|
||||
const options = useMemo(
|
||||
() => [
|
||||
{
|
||||
key: "",
|
||||
label: t("All time"),
|
||||
},
|
||||
{
|
||||
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]
|
||||
() => [{ key: "", label: t("All time") }, ...source.options],
|
||||
[source.options, t]
|
||||
);
|
||||
|
||||
return (
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import { subMonths } from "date-fns";
|
||||
import { useCallback, useState } from "react";
|
||||
import type { DateRange as DayPickerRange } from "react-day-picker";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Calendar } from "@shared/components/Calendar";
|
||||
import {
|
||||
dateLocale,
|
||||
dateRangeToReadable,
|
||||
parseISODate,
|
||||
toISODate,
|
||||
} from "@shared/utils/date";
|
||||
import Button from "~/components/Button";
|
||||
import Flex from "~/components/Flex";
|
||||
import Text from "~/components/Text";
|
||||
import useUserLocale from "~/hooks/useUserLocale";
|
||||
import type { DateRange } from "../searchFilters";
|
||||
|
||||
interface Props {
|
||||
/** The range to show as selected when the dialog opens. */
|
||||
defaultRange?: DateRange;
|
||||
/** Called with the chosen range as ISO dates. */
|
||||
onSubmit: (range: Required<DateRange>) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Dialog content to choose the first and last day of a date filter.
|
||||
*/
|
||||
export function DateRangeDialog({ defaultRange, onSubmit }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const userLocale = useUserLocale();
|
||||
const [today] = useState(() => new Date());
|
||||
const [range, setRange] = useState<DayPickerRange | undefined>(() => {
|
||||
const from = defaultRange?.from ? parseISODate(defaultRange.from) : null;
|
||||
const to = defaultRange?.to ? parseISODate(defaultRange.to) : null;
|
||||
if (!from && !to) {
|
||||
return undefined;
|
||||
}
|
||||
return { from: from ?? to ?? undefined, to: to ?? undefined };
|
||||
});
|
||||
|
||||
// Show the last day of the range in the right month, so that future months
|
||||
// (which cannot be picked) are not shown.
|
||||
const [defaultMonth] = useState(() => subMonths(range?.to ?? today, 1));
|
||||
|
||||
// When a whole range is selected, the next click starts a new range.
|
||||
const handleSelect = useCallback(
|
||||
(next: DayPickerRange | undefined, selectedDay: Date) => {
|
||||
setRange((current) =>
|
||||
current?.from && current.to ? { from: selectedDay } : next
|
||||
);
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
const handleSubmit = useCallback(
|
||||
(ev: React.FormEvent) => {
|
||||
ev.preventDefault();
|
||||
if (!range?.from) {
|
||||
return;
|
||||
}
|
||||
onSubmit({
|
||||
from: toISODate(range.from),
|
||||
to: toISODate(range.to ?? range.from),
|
||||
});
|
||||
},
|
||||
[range, onSubmit]
|
||||
);
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit}>
|
||||
<Flex gap={12} column>
|
||||
<Calendar
|
||||
mode="range"
|
||||
numberOfMonths={2}
|
||||
showOutsideDays={false}
|
||||
selected={range}
|
||||
onSelect={handleSelect}
|
||||
defaultMonth={defaultMonth}
|
||||
locale={dateLocale(userLocale)}
|
||||
disabled={{ after: today }}
|
||||
/>
|
||||
<Flex justify="space-between" align="center" gap={12}>
|
||||
<Text type="secondary" size="small">
|
||||
{range?.from
|
||||
? dateRangeToReadable(
|
||||
range.from,
|
||||
range.to ?? range.from,
|
||||
userLocale
|
||||
)
|
||||
: t("Choose the first and last day")}
|
||||
</Text>
|
||||
<Button type="submit" disabled={!range?.from}>
|
||||
{t("Apply")}
|
||||
</Button>
|
||||
</Flex>
|
||||
</Flex>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -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 (
|
||||
<div>
|
||||
<Tooltip content={t("Remove document filter")}>
|
||||
<StyledButton onClick={props.onClick} icon={<CloseIcon />} neutral>
|
||||
{props.document.displayTitle}
|
||||
</StyledButton>
|
||||
</Tooltip>
|
||||
</div>
|
||||
<Chip>
|
||||
<ChipStatic>
|
||||
<ChipContent
|
||||
icon={<DocumentIcon />}
|
||||
label={t("Document")}
|
||||
value={props.document.displayTitle}
|
||||
/>
|
||||
</ChipStatic>
|
||||
<ChipRemoveButton
|
||||
label={t("Remove document filter")}
|
||||
onClick={props.onRemove}
|
||||
/>
|
||||
</Chip>
|
||||
);
|
||||
}
|
||||
@@ -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 (
|
||||
<FilterOptions
|
||||
options={options}
|
||||
selectedKeys={statusFilter}
|
||||
onSelect={handleSelect}
|
||||
defaultLabel={t("Any status")}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default DocumentTypeFilter;
|
||||
@@ -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 && <ChipIcon aria-hidden>{icon}</ChipIcon>}
|
||||
<ChipLabel type={value ? "secondary" : undefined}>{label}</ChipLabel>
|
||||
{value && (
|
||||
<ChipValue weight="bold" ellipsis>
|
||||
{value}
|
||||
</ChipValue>
|
||||
)}
|
||||
{disclosure && <Disclosure size={20} aria-hidden />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<Tooltip content={label}>
|
||||
<RemoveButton aria-label={label} onClick={onClick}>
|
||||
<CloseIcon size={18} />
|
||||
</RemoveButton>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
/** 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")};
|
||||
`;
|
||||
@@ -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 <SelectFilterChip {...props} filter={filter} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<Chip>
|
||||
<ChipStatic>
|
||||
<ChipContent icon={filter.icon} label={filter.label} />
|
||||
</ChipStatic>
|
||||
<ChipRemoveButton
|
||||
label={t("Remove filter")}
|
||||
onClick={() => onChange(filter, undefined)}
|
||||
/>
|
||||
</Chip>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<Chip>
|
||||
<FilterOptions
|
||||
options={options}
|
||||
selectedKeys={rangeLabel ? [CUSTOM_RANGE] : values}
|
||||
onSelect={handleSelect}
|
||||
fetchQuery={source.fetchQuery}
|
||||
fetchQueryOptions={source.fetchQueryOptions}
|
||||
showFilter={source.showFilter}
|
||||
defaultLabel={filter.label}
|
||||
defaultOpen={defaultOpen}
|
||||
onOpenChange={handleOpenChange}
|
||||
trigger={
|
||||
<ChipButton>
|
||||
<ChipContent
|
||||
icon={icon}
|
||||
label={filter.label}
|
||||
value={
|
||||
rangeLabel ?? shown.map((option) => option.label).join(", ")
|
||||
}
|
||||
disclosure={!isSet}
|
||||
/>
|
||||
</ChipButton>
|
||||
}
|
||||
/>
|
||||
{isSet && (
|
||||
<ChipRemoveButton
|
||||
label={t("Remove filter")}
|
||||
onClick={() => onChange(filter, undefined)}
|
||||
/>
|
||||
)}
|
||||
</Chip>
|
||||
);
|
||||
});
|
||||
@@ -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<HTMLInputElement> {
|
||||
name: string;
|
||||
@@ -11,77 +11,58 @@ interface Props extends React.InputHTMLAttributes<HTMLInputElement> {
|
||||
}
|
||||
|
||||
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 (
|
||||
<Wrapper align="center">
|
||||
<StyledIcon size={46} color={theme.placeholder} onClick={focusInput} />
|
||||
<StyledInput
|
||||
{...rest}
|
||||
defaultValue={defaultValue}
|
||||
ref={ref}
|
||||
spellCheck="false"
|
||||
type="search"
|
||||
autoFocus
|
||||
/>
|
||||
</Wrapper>
|
||||
<StyledInput
|
||||
{...rest}
|
||||
type="search"
|
||||
icon={<StyledSearchIcon />}
|
||||
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;
|
||||
@@ -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 (
|
||||
<FilterOptions
|
||||
showFilter={false}
|
||||
showIcons={false}
|
||||
disclosure={false}
|
||||
options={options}
|
||||
selectedKeys={[selectedKey]}
|
||||
onSelect={handleSelect}
|
||||
defaultLabel={t("Relevance")}
|
||||
/>
|
||||
<Wrapper>
|
||||
{t("Sorted by")}
|
||||
<FilterOptions
|
||||
showFilter={false}
|
||||
showIcons={false}
|
||||
options={options}
|
||||
selectedKeys={[selectedKey]}
|
||||
onSelect={handleSelect}
|
||||
defaultLabel={t("Sort")}
|
||||
trigger={
|
||||
<Trigger>
|
||||
{selectedLabel}
|
||||
<Disclosure size={20} aria-hidden />
|
||||
</Trigger>
|
||||
}
|
||||
/>
|
||||
</Wrapper>
|
||||
);
|
||||
};
|
||||
|
||||
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")};
|
||||
`;
|
||||
@@ -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: <StyledAvatar model={user} size={AvatarSize.Small} />,
|
||||
}));
|
||||
return [
|
||||
const options = useMemo(
|
||||
() => [
|
||||
{
|
||||
key: "",
|
||||
label: anyLabel,
|
||||
icon: <UserIcon size={20} />,
|
||||
},
|
||||
...userOptions,
|
||||
];
|
||||
}, [users.all, anyLabel]);
|
||||
...source.options,
|
||||
],
|
||||
[source.options, anyLabel]
|
||||
);
|
||||
|
||||
return (
|
||||
<FilterOptions
|
||||
@@ -50,15 +38,11 @@ function UserFilter(props: Props) {
|
||||
selectedKeys={[userId]}
|
||||
onSelect={onSelect}
|
||||
defaultLabel={anyLabel}
|
||||
fetchQuery={can.listUsers ? users.fetchPage : undefined}
|
||||
fetchQueryOptions={fetchQueryOptions}
|
||||
fetchQuery={source.fetchQuery}
|
||||
fetchQueryOptions={source.fetchQueryOptions}
|
||||
showFilter
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const StyledAvatar = styled(Avatar)`
|
||||
margin: 2px;
|
||||
`;
|
||||
|
||||
export default observer(UserFilter);
|
||||
@@ -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<PaginatedItem[]>;
|
||||
/** Extra parameters to send with fetchQuery. */
|
||||
fetchQueryOptions?: Record<string, string>;
|
||||
/** 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: <CollectionIcon collection={collection} size={24} />,
|
||||
})),
|
||||
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: <StyledAvatar model={user} size={AvatarSize.Small} />,
|
||||
})),
|
||||
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 ? (
|
||||
<Icon
|
||||
value={template.icon}
|
||||
initial={template.initial}
|
||||
color={template.color ?? undefined}
|
||||
/>
|
||||
) : (
|
||||
<NewDocumentIcon />
|
||||
),
|
||||
})),
|
||||
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;
|
||||
`;
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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<Record<ComparisonOperator, string[]>>;
|
||||
|
||||
/** A URL parameter from before the `<field>.<operator>` 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
|
||||
* `<id>.<operator>=<value>`. A bare `<id>=<value>` 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: <CollectionIcon />,
|
||||
pinned: true,
|
||||
isAvailable: ({ document }) => !document,
|
||||
...matchSelection,
|
||||
useOptions: useCollectionOptions,
|
||||
},
|
||||
{
|
||||
type: "select",
|
||||
id: "userId",
|
||||
label: t("Edited by"),
|
||||
icon: <UserIcon />,
|
||||
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: <DoneIcon />,
|
||||
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: <CalendarIcon />,
|
||||
...dateSelection,
|
||||
legacy: {
|
||||
param: "dateFilter",
|
||||
operator: "gte",
|
||||
map: durationForDateFilter,
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "select",
|
||||
id: "createdById",
|
||||
label: t("Created by"),
|
||||
icon: <EditIcon />,
|
||||
...matchSelection,
|
||||
// The API only supports membership checks for these fields.
|
||||
operators: ["eq", "in"],
|
||||
useOptions: useUserOptions,
|
||||
},
|
||||
{
|
||||
type: "select",
|
||||
id: "createdAt",
|
||||
label: t("Created"),
|
||||
icon: <CalendarIcon />,
|
||||
...dateSelection,
|
||||
},
|
||||
{
|
||||
type: "select",
|
||||
id: "publishedAt",
|
||||
label: t("Published"),
|
||||
icon: <CalendarIcon />,
|
||||
...dateSelection,
|
||||
},
|
||||
{
|
||||
type: "select",
|
||||
id: "templateId",
|
||||
label: t("Template"),
|
||||
icon: <NewDocumentIcon />,
|
||||
...matchSelection,
|
||||
useOptions: useTemplateOptions,
|
||||
},
|
||||
{
|
||||
type: "toggle",
|
||||
id: "titleOnly",
|
||||
label: t("Title only"),
|
||||
icon: <TextWrapIcon />,
|
||||
legacyParam: "titleFilter",
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the conditions of a filter that the URL sets, from both the
|
||||
* `<field>.<operator>` 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<string, string | string[] | undefined> {
|
||||
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<DateRange>,
|
||||
params: URLSearchParams
|
||||
): Record<string, string | string[] | undefined> {
|
||||
return getConditionParamChanges(
|
||||
filter,
|
||||
{ gte: [range.from], lte: [range.to] },
|
||||
params
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Split a URL key in the `<field>.<operator>` 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<string, string | string[] | undefined> {
|
||||
const changes: Record<string, string | string[] | undefined> = {};
|
||||
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<string, string | string[] | undefined> {
|
||||
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<string>(StatusFilter).includes(value);
|
||||
}
|
||||
@@ -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<Document> {
|
||||
};
|
||||
|
||||
@action
|
||||
search = async (options: SearchParams): Promise<SearchResult[]> => {
|
||||
search = async (
|
||||
options: SearchParams
|
||||
): Promise<PaginatedResponse<SearchResult>> => {
|
||||
const compactedOptions = omitBy(options, (o) => !o);
|
||||
const res = await client.post("/documents.search", {
|
||||
...compactedOptions,
|
||||
@@ -525,7 +528,7 @@ export default class DocumentsStore extends Store<Document> {
|
||||
|
||||
// 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<SearchResult> = 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<Document> {
|
||||
};
|
||||
})
|
||||
);
|
||||
results[PAGINATION_SYMBOL] = res.pagination;
|
||||
return results;
|
||||
};
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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)}
|
||||
|
||||
@@ -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<DateFilter, string> = {
|
||||
day: "-P1D",
|
||||
@@ -134,7 +171,7 @@ export const RANGE_OPERATORS = new Set<ComparisonOperator>([
|
||||
* @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
|
||||
|
||||
@@ -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.",
|
||||
|
||||
@@ -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.
|
||||
*
|
||||
|
||||
Reference in new issue
Block a user