Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 | 37x 37x 37x 908x 37x 23x 23x 20x 18x 390x 390x 390x 390x 390x 1805x 390x 390x 390x 368x 390x 385x 385x 992x 992x 57x 57x 935x 935x 385x 390x 27x 27x 27x 27x 390x 5x 390x 390x 18x 18x 390x 971x 390x 885x 390x 4x 4x 6x 390x 390x 182x 390x | import { ViewMode } from "@/components/buttons/ViewToggle/ViewToggle";
import { useCallback, useMemo } from "react";
import { useSearchParams } from "react-router-dom";
/**
* Search / filter / view state for a resource collection, held in the URL.
*
* Every resource page needs the same four things — a query string, a set of
* named filters with defaults, a grid/list preference, and a "how many
* filters are narrowing this?" count driving the Clear button — and every
* page that hand-rolls them drifts: one forgets to count the search box,
* another clears the sort along with the filters. Owning it here keeps the
* behaviour identical across pages while leaving *which* filters exist
* entirely up to the page.
*
* **The URL is the state.** A narrowed list is a thing people send each other
* and come back to — "the failed runs", "just the graph sources" — and while
* it lived in `useState` none of that worked: the link opened the unfiltered
* list, a reload threw the filter away, and a deep link into a filtered view
* had to be faked by seeding the initial state. Params carry only what is
* *away from* its default, so an untouched collection has a clean URL, and
* anything the hook does not own (`section`, `version`) is left alone.
*
* Writes replace the history entry rather than pushing one: typing in the
* search box would otherwise bury the previous page under one entry per
* keystroke. Back leaves the page, as it did when this was component state.
*
* Sort is deliberately not counted as an active filter: reordering hides
* nothing, so offering to "clear" it would be misleading. Pass it as a
* filter only if a page genuinely wants it cleared with the rest.
*/
/** A filter's value: a single choice (`"all"`, `"file"`) or a multi-select. */
export type FilterValue = string | string[];
/** The params the hook owns beyond the page's own filter keys. */
const SEARCH_PARAM = "q";
const VIEW_PARAM = "view";
export interface UseCollectionFiltersOptions<F> {
/** Each filter's neutral value — the one that narrows nothing. Also what a
* param is compared against: a filter at its default is left out of the
* URL entirely. */
defaults?: F;
/** Initial grid/list preference, used until `?view=` says otherwise. */
view?: ViewMode;
/** Filters excluded from the active count and from `clear()`, e.g. a sort
* key that reorders rather than narrows. They are still URL-backed —
* "sorted by cost" is worth linking to even though it hides nothing. */
unfiltered?: (keyof F)[];
/** Prefix for this collection's params, for the rare page rendering two
* collections at once. Omit for the common case of one. */
prefix?: string;
}
export interface CollectionFilters<F extends Record<string, FilterValue>> {
search: string;
setSearch: (value: string) => void;
filters: F;
/** Set one filter, leaving the rest untouched. */
setFilter: <K extends keyof F>(key: K, value: F[K]) => void;
view: ViewMode;
setView: (view: ViewMode) => void;
/** Filters away from their default, plus one for a non-empty search. */
activeFilterCount: number;
/** True while anything is narrowing the collection — drives the "no
* matches" empty state rather than the "nothing here yet" one. */
isFiltered: boolean;
/** Reset search and every filter (bar `unfiltered`) to its default. */
clear: () => void;
/** Case-insensitive match of the current query against any of `fields`.
* Returns true when the query is empty, so it composes with `&&`. */
matches: (...fields: (string | null | undefined)[]) => boolean;
/** Ready-made `Toolbar`/`ResourceCollection` props for the shared parts. */
toolbarProps: {
activeFilterCount: number;
onClear: () => void;
view: ViewMode;
onViewChange: (view: ViewMode) => void;
};
}
const isDefault = (value: FilterValue, fallback: FilterValue): boolean =>
Array.isArray(value) && Array.isArray(fallback)
? value.length === fallback.length &&
value.every((v, i) => v === fallback[i])
: value === fallback;
/** Write `value` at `key`, or drop the key when it is at its default.
* Multi-selects repeat the key (`?tags=a&tags=b`) so a value containing a
* comma is not silently split in two. */
const writeParam = (
params: URLSearchParams,
key: string,
value: FilterValue,
fallback: FilterValue,
): void => {
params.delete(key);
if (isDefault(value, fallback)) return;
if (Array.isArray(value)) for (const v of value) params.append(key, v);
else params.set(key, value);
};
export function useCollectionFilters<
F extends Record<string, FilterValue> = Record<string, never>,
>(options: UseCollectionFiltersOptions<F> = {}): CollectionFilters<F> {
const { defaults, view: initialView = "grid", unfiltered, prefix } = options;
const emptyDefaults = useMemo(() => ({}) as F, []);
const baseline = defaults ?? emptyDefaults;
const [searchParams, setSearchParams] = useSearchParams();
const param = useCallback(
(key: string) => (prefix ? `${prefix}_${key}` : key),
[prefix],
);
const search = searchParams.get(param(SEARCH_PARAM)) ?? "";
const view = (searchParams.get(param(VIEW_PARAM)) as ViewMode) || initialView;
const keys = useMemo(
() => Object.keys(baseline) as (keyof F & string)[],
[baseline],
);
// Derived, not stored: the URL is the single copy of this state, so there is
// no second one to fall out of step with it on a back button or a reload.
const filters = useMemo(() => {
const next = { ...baseline };
for (const key of keys) {
const fallback = baseline[key];
if (Array.isArray(fallback)) {
const values = searchParams.getAll(param(key));
if (values.length) next[key] = values as F[typeof key];
} else {
const value = searchParams.get(param(key));
if (value !== null) next[key] = value as F[typeof key];
}
}
return next;
}, [baseline, keys, searchParams, param]);
/** Apply `edit` to the current params, keeping everything the hook does not
* own. The functional form matters: two writes in one tick (clearing a
* filter and the search) must not each start from a stale snapshot. */
const update = useCallback(
(edit: (params: URLSearchParams) => void) =>
setSearchParams(
(prev) => {
const next = new URLSearchParams(prev);
edit(next);
return next;
},
{ replace: true },
),
[setSearchParams],
);
const setSearch = useCallback(
(value: string) =>
update((params) => writeParam(params, param(SEARCH_PARAM), value, "")),
[update, param],
);
const setView = useCallback(
(value: ViewMode) =>
update((params) =>
writeParam(params, param(VIEW_PARAM), value, initialView),
),
[update, param, initialView],
);
const setFilter = useCallback(
<K extends keyof F>(key: K, value: F[K]) =>
update((params) =>
writeParam(
params,
param(key as string),
value,
baseline[key] ?? (Array.isArray(value) ? [] : ""),
),
),
[update, param, baseline],
);
const counted = useMemo(
() => keys.filter((key) => !unfiltered?.includes(key)),
[keys, unfiltered],
);
const activeFilterCount = useMemo(
() =>
(search.trim() ? 1 : 0) +
counted.filter((key) => !isDefault(filters[key], baseline[key])).length,
[search, filters, baseline, counted],
);
const clear = useCallback(
() =>
update((params) => {
params.delete(param(SEARCH_PARAM));
for (const key of counted) params.delete(param(key));
}),
[update, param, counted],
);
const query = search.trim().toLowerCase();
const matches = useCallback(
(...fields: (string | null | undefined)[]) =>
!query || fields.some((f) => (f ?? "").toLowerCase().includes(query)),
[query],
);
return {
search,
setSearch,
filters,
setFilter,
view,
setView,
activeFilterCount,
isFiltered: activeFilterCount > 0,
clear,
matches,
toolbarProps: {
activeFilterCount,
onClear: clear,
view,
onViewChange: setView,
},
};
}
|