@sdxc/facets 0.0.0-pre.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +21 -0
- package/README.md +199 -0
- package/dist/facet-set.d.ts +96 -0
- package/dist/facet-set.js +425 -0
- package/dist/facet.d.ts +86 -0
- package/dist/facet.js +65 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +9 -0
- package/dist/types.d.ts +82 -0
- package/dist/types.js +8 -0
- package/package.json +32 -0
package/LICENSE.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Sergio Xalambrí
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
# @sdxc/facets
|
|
2
|
+
|
|
3
|
+
Faceted filtering over in-memory records: URL filters, disjunctive facet counts and range buckets.
|
|
4
|
+
|
|
5
|
+
One definition parses a URL's filters, writes them back, narrows a list of records and counts
|
|
6
|
+
every option with the other facets applied, so a filter link and the number beside it always
|
|
7
|
+
agree. Built for catalogues and lists small enough to filter in the request.
|
|
8
|
+
|
|
9
|
+
## Installation
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
npm add @sdxc/facets
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Parsing returns a `Result` from [`@sdxc/result`](https://www.npmjs.com/package/@sdxc/result) and
|
|
16
|
+
fails with the `ValidationError` from [`@sdxc/validate`](https://www.npmjs.com/package/@sdxc/validate).
|
|
17
|
+
|
|
18
|
+
## Usage
|
|
19
|
+
|
|
20
|
+
### Define the facets once
|
|
21
|
+
|
|
22
|
+
```typescript
|
|
23
|
+
import { createFacets } from "@sdxc/facets";
|
|
24
|
+
|
|
25
|
+
interface Poster {
|
|
26
|
+
style: string;
|
|
27
|
+
colors: string[];
|
|
28
|
+
price: number;
|
|
29
|
+
stock: number;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export const posterFacets = createFacets<Poster>()
|
|
33
|
+
.terms("style", (poster) => poster.style, { values: ["geometric", "botanical", "travel"] })
|
|
34
|
+
.terms("color", (poster) => poster.colors)
|
|
35
|
+
.range("price", (poster) => poster.price, { buckets: [0, 2500, 5000, 10000] })
|
|
36
|
+
.toggle("inStock", (poster) => poster.stock > 0, { param: "in_stock" });
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
### Filter and count from the request URL
|
|
40
|
+
|
|
41
|
+
```typescript
|
|
42
|
+
import { isFailure } from "@sdxc/result";
|
|
43
|
+
|
|
44
|
+
let filters = posterFacets.parse(url.searchParams);
|
|
45
|
+
// ?style=travel&color=ochre&color=blue&price_min=2500&price_max=5000&in_stock=1
|
|
46
|
+
if (isFailure(filters)) return new Response("Bad Request", { status: 400 });
|
|
47
|
+
|
|
48
|
+
let { items, total, counts } = posterFacets.apply(posters, filters.data);
|
|
49
|
+
|
|
50
|
+
counts.color; // [{ value: "ochre", count: 12, selected: true }, { value: "blue", count: 7, selected: true }, …]
|
|
51
|
+
counts.price.buckets; // [{ min: 0, max: 2500, count: 3, selected: false }, …]
|
|
52
|
+
counts.inStock; // { count: 18, selected: true }
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Each facet's counts are taken over the records every _other_ facet leaves. Choosing "ochre"
|
|
56
|
+
narrows the styles and prices, while the other colours keep the counts a visitor would get by
|
|
57
|
+
adding them.
|
|
58
|
+
|
|
59
|
+
### Build the links
|
|
60
|
+
|
|
61
|
+
```typescript
|
|
62
|
+
let href = (next: typeof filters.data) => `?${posterFacets.serialize(next, url.searchParams)}`;
|
|
63
|
+
|
|
64
|
+
href(posterFacets.toggleTerm(filters.data, "color", "green")); // tick or untick one option
|
|
65
|
+
href(posterFacets.set(filters.data, "price", { min: 0, max: 2500 })); // pick a bucket
|
|
66
|
+
href(posterFacets.clear(filters.data)); // "Clear all"
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
`serialize()` keeps the parameters no facet owns (`q`, `sort`) and writes terms in a stable
|
|
70
|
+
order, so one selection always yields one URL.
|
|
71
|
+
|
|
72
|
+
## API
|
|
73
|
+
|
|
74
|
+
### `createFacets<T>(): FacetSet<T>`
|
|
75
|
+
|
|
76
|
+
Starts an empty facet set for records of type `T`. Every facet name is inferred from the
|
|
77
|
+
chain, and a name may be used only once.
|
|
78
|
+
|
|
79
|
+
### `.terms(name, read, options?)`
|
|
80
|
+
|
|
81
|
+
A facet over values a record carries: `read` returns one string, several, or nothing. Chosen
|
|
82
|
+
values match a record carrying any one of them. Options:
|
|
83
|
+
|
|
84
|
+
- `param`: the query parameter; it defaults to the name and repeats once per value, the shape a
|
|
85
|
+
group of checkboxes submits.
|
|
86
|
+
- `values`: the accepted values in display order. Listed even at a count of 0, and any other
|
|
87
|
+
value in a URL fails to parse.
|
|
88
|
+
- `limit`: the most values one URL may choose; defaults to 50.
|
|
89
|
+
|
|
90
|
+
### `.range(name, read, options?)`
|
|
91
|
+
|
|
92
|
+
A numeric facet filtered by `{ min, max }`, where `min` is inclusive and `max` exclusive.
|
|
93
|
+
`buckets: [0, 25, 50]` counts `[0, 25)`, `[25, 50)` and `[50, ∞)`. Read from `minParam` and
|
|
94
|
+
`maxParam`, which default to `<name>_min` and `<name>_max`. A record without a value stays
|
|
95
|
+
while the range is open.
|
|
96
|
+
|
|
97
|
+
### `.toggle(name, read, options?)`
|
|
98
|
+
|
|
99
|
+
A yes/no facet. Reads `1`, `true` or `on` as on and `0`, `false` or `off` as off, and writes `1`.
|
|
100
|
+
|
|
101
|
+
### `.parse(searchParams): Result<Filters, ValidationError>`
|
|
102
|
+
|
|
103
|
+
Reads every facet's selection. Blank parameters are absent. Every problem is reported in one
|
|
104
|
+
failure, each issue's `path` naming its parameter: an undeclared value, a non-number, a
|
|
105
|
+
reversed range, or too many values.
|
|
106
|
+
|
|
107
|
+
### `.serialize(filters, base?): URLSearchParams`
|
|
108
|
+
|
|
109
|
+
Writes a full or partial selection into a copy of `base`, replacing only the facets' own
|
|
110
|
+
parameters.
|
|
111
|
+
|
|
112
|
+
### `.apply(records, filters?): FacetResult`
|
|
113
|
+
|
|
114
|
+
Returns `{ items, total, counts }`: the matching records in input order, and every facet's
|
|
115
|
+
counts in one pass over the records. A chosen term is always listed, at a count of 0 when
|
|
116
|
+
nothing matches it, so its checkbox can be unticked. Range counts carry the `min` and `max`
|
|
117
|
+
values of the counted records for a slider's bounds.
|
|
118
|
+
|
|
119
|
+
### `.empty()`, `.toggleTerm()`, `.set()`, `.clear()`
|
|
120
|
+
|
|
121
|
+
Return new selections: everything cleared, one term flipped, one facet replaced, and one facet
|
|
122
|
+
(or all of them) cleared.
|
|
123
|
+
|
|
124
|
+
### `.applied(filters): AppliedFilter[]`
|
|
125
|
+
|
|
126
|
+
One entry per chosen term, range and toggle, each with `filters` already minus that entry, for
|
|
127
|
+
a row of removable chips.
|
|
128
|
+
|
|
129
|
+
### Types
|
|
130
|
+
|
|
131
|
+
`Filters`, `Counts`, `FacetResult`, `TermCount`, `RangeCounts`, `BucketCount`, `ToggleCount`,
|
|
132
|
+
`NumberRange`, `AppliedFilter`, `FacetShape`, `FacetKind` and `FacetsOfKind`, plus the option
|
|
133
|
+
types `TermsOptions`, `RangeOptions` and `ToggleOptions`.
|
|
134
|
+
|
|
135
|
+
## Patterns
|
|
136
|
+
|
|
137
|
+
### Pattern: A filter form that works without script
|
|
138
|
+
|
|
139
|
+
```typescript
|
|
140
|
+
import { createFacets } from "@sdxc/facets";
|
|
141
|
+
import { isFailure } from "@sdxc/result";
|
|
142
|
+
|
|
143
|
+
interface Book {
|
|
144
|
+
genre: string;
|
|
145
|
+
pages: number;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const BOOK_FACETS = createFacets<Book>()
|
|
149
|
+
.terms("genre", (book) => book.genre)
|
|
150
|
+
.range("pages", (book) => book.pages, { buckets: [0, 200, 400] });
|
|
151
|
+
|
|
152
|
+
export function listBooks(url: URL, books: Book[]) {
|
|
153
|
+
let filters = BOOK_FACETS.parse(url.searchParams);
|
|
154
|
+
if (isFailure(filters)) return { status: 400, issues: filters.error.issues };
|
|
155
|
+
|
|
156
|
+
let { items, counts } = BOOK_FACETS.apply(books, filters.data);
|
|
157
|
+
let chips = BOOK_FACETS.applied(filters.data).map((chip) => ({
|
|
158
|
+
label: typeof chip.value === "string" ? chip.value : chip.facet,
|
|
159
|
+
href: `?${BOOK_FACETS.serialize(chip.filters, url.searchParams)}`,
|
|
160
|
+
}));
|
|
161
|
+
return { status: 200, items, counts, chips };
|
|
162
|
+
}
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
Render `counts.genre` as checkboxes named `genre` and the range as two number inputs named
|
|
166
|
+
`pages_min` and `pages_max`, inside one `<form method="get">`. Submitting the form produces
|
|
167
|
+
exactly the URL `parse()` reads, so the page works before any script loads. Serialize chip
|
|
168
|
+
links onto a copy of the search parameters with `page` deleted, so a changed filter starts
|
|
169
|
+
again from page one.
|
|
170
|
+
|
|
171
|
+
## Versioning
|
|
172
|
+
|
|
173
|
+
Releases are dated rather than semantic. A version is the UTC date it was published,
|
|
174
|
+
written `YYYY.M.D`, so `2026.9.4` is the release from 4 September 2026. At most one
|
|
175
|
+
release goes out per day.
|
|
176
|
+
|
|
177
|
+
Those numbers say when, not what: a later date means a later release and carries no
|
|
178
|
+
compatibility promise. Any release may change or remove an export.
|
|
179
|
+
|
|
180
|
+
Depend on one exact date, and move it when you are ready to take the change:
|
|
181
|
+
|
|
182
|
+
```json
|
|
183
|
+
{
|
|
184
|
+
"dependencies": {
|
|
185
|
+
"@sdxc/facets": "2026.9.4"
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
A caret or tilde range reads the date as major, minor and patch, so it accepts every
|
|
191
|
+
later release in the same year. An exact version keeps the upgrade yours to schedule.
|
|
192
|
+
|
|
193
|
+
## License
|
|
194
|
+
|
|
195
|
+
MIT
|
|
196
|
+
|
|
197
|
+
## Author
|
|
198
|
+
|
|
199
|
+
[Sergio Xalambrí](https://sergiodxa.com)
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The facet set: a typed list of facets over one record type that parses a URL's filters,
|
|
3
|
+
* writes them back, narrows records and counts every option with the other facets applied.
|
|
4
|
+
* One definition answers all four, so a filter link and the counts beside it always agree.
|
|
5
|
+
*
|
|
6
|
+
* @author [Sergio Xalambrí](https://sergiodxa.com)
|
|
7
|
+
* @copyright Sergio Xalambrí 2026
|
|
8
|
+
*/
|
|
9
|
+
import type { Result } from "@sdxc/result";
|
|
10
|
+
import { ValidationError } from "@sdxc/validate";
|
|
11
|
+
import type { FacetEntry, RangeOptions, TermsOptions, ToggleOptions } from "./facet.js";
|
|
12
|
+
import type { AppliedFilter, FacetResult, FacetShape, FacetsOfKind, Filters } from "./types.js";
|
|
13
|
+
/** A facet name new to the set; reusing a name is a type error. */
|
|
14
|
+
type NewName<N extends string, D extends FacetShape> = N extends keyof D ? never : N;
|
|
15
|
+
/**
|
|
16
|
+
* Faceted filtering for one record type. Build it once with `createFacets<Record>()` and a
|
|
17
|
+
* chain of `.terms()`, `.range()` and `.toggle()`; each call returns a new set, so a set
|
|
18
|
+
* shared across requests is never changed by one of them.
|
|
19
|
+
*
|
|
20
|
+
* @template T The record type.
|
|
21
|
+
* @template D The facets by name, each mapped to its kind.
|
|
22
|
+
*/
|
|
23
|
+
export declare class FacetSet<T, D extends FacetShape = Record<never, never>> {
|
|
24
|
+
#private;
|
|
25
|
+
/** @param entries The facets in definition order, which is also the URL's parameter order. */
|
|
26
|
+
constructor(entries?: readonly FacetEntry<T>[]);
|
|
27
|
+
/**
|
|
28
|
+
* Adds a facet whose options are values a record carries, one or several per record.
|
|
29
|
+
* Several chosen values match a record carrying any one of them.
|
|
30
|
+
*
|
|
31
|
+
* @example createFacets<Poster>().terms("color", (poster) => poster.colors)
|
|
32
|
+
*/
|
|
33
|
+
terms<N extends string>(name: NewName<N, D>, read: (record: T) => string | readonly string[] | null | undefined, options?: TermsOptions): FacetSet<T, D & Record<N, "terms">>;
|
|
34
|
+
/**
|
|
35
|
+
* Adds a numeric facet filtered by an interval and counted in buckets. A record without a
|
|
36
|
+
* value is kept while the range is open and dropped once either end is set.
|
|
37
|
+
*
|
|
38
|
+
* @example createFacets<Poster>().range("price", (poster) => poster.price, { buckets: [0, 2500, 5000] })
|
|
39
|
+
*/
|
|
40
|
+
range<N extends string>(name: NewName<N, D>, read: (record: T) => number | null | undefined, options?: RangeOptions): FacetSet<T, D & Record<N, "range">>;
|
|
41
|
+
/**
|
|
42
|
+
* Adds a yes/no facet, such as "in stock", that keeps only records passing the test once on.
|
|
43
|
+
*
|
|
44
|
+
* @example createFacets<Poster>().toggle("inStock", (poster) => poster.stock > 0)
|
|
45
|
+
*/
|
|
46
|
+
toggle<N extends string>(name: NewName<N, D>, read: (record: T) => boolean, options?: ToggleOptions): FacetSet<T, D & Record<N, "toggle">>;
|
|
47
|
+
/** A selection with every facet cleared: no terms, open ranges, toggles off. */
|
|
48
|
+
empty(): Filters<D>;
|
|
49
|
+
/**
|
|
50
|
+
* Reads the filters from a URL's query. Blank parameters count as absent; every malformed
|
|
51
|
+
* one (an undeclared value, a non-number, a reversed range, too many values) is reported
|
|
52
|
+
* together, each issue's path naming its parameter.
|
|
53
|
+
*
|
|
54
|
+
* @example let filters = posterFacets.parse(url.searchParams);
|
|
55
|
+
*/
|
|
56
|
+
parse(searchParams: URLSearchParams): Result<Filters<D>, ValidationError>;
|
|
57
|
+
/**
|
|
58
|
+
* Writes filters into query parameters. Parameters in `base` that no facet owns (a search
|
|
59
|
+
* query, a sort) are kept, every facet parameter is rewritten, and terms come out in a
|
|
60
|
+
* stable order so one selection always yields one URL.
|
|
61
|
+
*
|
|
62
|
+
* @example `?${posterFacets.serialize(posterFacets.toggleTerm(filters, "color", "ochre"), url.searchParams)}`
|
|
63
|
+
*/
|
|
64
|
+
serialize(filters: Partial<Filters<D>>, base?: URLSearchParams): URLSearchParams;
|
|
65
|
+
/**
|
|
66
|
+
* Narrows the records to those passing every filter, and counts each facet's options over
|
|
67
|
+
* the records every *other* facet leaves, so choosing a colour never hides the other
|
|
68
|
+
* colours' counts. One pass over the records, whatever the number of facets.
|
|
69
|
+
*
|
|
70
|
+
* @example let { items, total, counts } = posterFacets.apply(posters, filters);
|
|
71
|
+
*/
|
|
72
|
+
apply(records: Iterable<T>, filters?: Partial<Filters<D>>): FacetResult<T, D>;
|
|
73
|
+
/**
|
|
74
|
+
* Adds a value to a terms facet's selection, or removes it when already chosen: the link
|
|
75
|
+
* behind one checkbox in a facet list.
|
|
76
|
+
*/
|
|
77
|
+
toggleTerm<N extends FacetsOfKind<D, "terms">>(filters: Filters<D>, name: N, value: string): Filters<D>;
|
|
78
|
+
/** Replaces one facet's selection, leaving the others as they are. */
|
|
79
|
+
set<N extends keyof D & string>(filters: Filters<D>, name: N, value: Filters<D>[N]): Filters<D>;
|
|
80
|
+
/** Clears one facet's selection, or every facet's when no name is given. */
|
|
81
|
+
clear(filters: Filters<D>, name?: keyof D & string): Filters<D>;
|
|
82
|
+
/**
|
|
83
|
+
* Lists every filter in effect, one entry per chosen term, range or toggle, each carrying
|
|
84
|
+
* the selection without it so a chip's remove link is one `serialize()` away.
|
|
85
|
+
*/
|
|
86
|
+
applied(filters: Filters<D>): AppliedFilter<D>[];
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Starts a facet set for one record type; chain `.terms()`, `.range()` and `.toggle()` to add
|
|
90
|
+
* facets. The record type is the only type argument, and every facet name is inferred.
|
|
91
|
+
*
|
|
92
|
+
* @template T The record type.
|
|
93
|
+
* @example let posterFacets = createFacets<Poster>().terms("style", (p) => p.style).toggle("inStock", (p) => p.stock > 0);
|
|
94
|
+
*/
|
|
95
|
+
export declare function createFacets<T>(): FacetSet<T>;
|
|
96
|
+
export {};
|
|
@@ -0,0 +1,425 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The facet set: a typed list of facets over one record type that parses a URL's filters,
|
|
3
|
+
* writes them back, narrows records and counts every option with the other facets applied.
|
|
4
|
+
* One definition answers all four, so a filter link and the counts beside it always agree.
|
|
5
|
+
*
|
|
6
|
+
* @author [Sergio Xalambrí](https://sergiodxa.com)
|
|
7
|
+
* @copyright Sergio Xalambrí 2026
|
|
8
|
+
*/
|
|
9
|
+
import { failure, success } from "@sdxc/result";
|
|
10
|
+
import { ValidationError } from "@sdxc/validate";
|
|
11
|
+
import { DEFAULT_TERM_LIMIT, inRange, isActive, isRange, matches, MAX_TERM_LENGTH, readTerms, } from "./facet.js";
|
|
12
|
+
/** Parameter text a toggle reads as on; `on` is what a checkbox without a value submits. */
|
|
13
|
+
const TOGGLE_ON = new Set(["1", "true", "on"]);
|
|
14
|
+
/** Parameter text a toggle reads as off. */
|
|
15
|
+
const TOGGLE_OFF = new Set(["0", "false", "off"]);
|
|
16
|
+
/**
|
|
17
|
+
* Faceted filtering for one record type. Build it once with `createFacets<Record>()` and a
|
|
18
|
+
* chain of `.terms()`, `.range()` and `.toggle()`; each call returns a new set, so a set
|
|
19
|
+
* shared across requests is never changed by one of them.
|
|
20
|
+
*
|
|
21
|
+
* @template T The record type.
|
|
22
|
+
* @template D The facets by name, each mapped to its kind.
|
|
23
|
+
*/
|
|
24
|
+
export class FacetSet {
|
|
25
|
+
#entries;
|
|
26
|
+
/** @param entries The facets in definition order, which is also the URL's parameter order. */
|
|
27
|
+
constructor(entries = []) {
|
|
28
|
+
this.#entries = entries;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Adds a facet whose options are values a record carries, one or several per record.
|
|
32
|
+
* Several chosen values match a record carrying any one of them.
|
|
33
|
+
*
|
|
34
|
+
* @example createFacets<Poster>().terms("color", (poster) => poster.colors)
|
|
35
|
+
*/
|
|
36
|
+
terms(name, read, options = {}) {
|
|
37
|
+
return new FacetSet([
|
|
38
|
+
...this.#entries,
|
|
39
|
+
{
|
|
40
|
+
kind: "terms",
|
|
41
|
+
name,
|
|
42
|
+
param: options.param ?? name,
|
|
43
|
+
values: options.values ?? null,
|
|
44
|
+
limit: options.limit ?? DEFAULT_TERM_LIMIT,
|
|
45
|
+
read,
|
|
46
|
+
},
|
|
47
|
+
]);
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Adds a numeric facet filtered by an interval and counted in buckets. A record without a
|
|
51
|
+
* value is kept while the range is open and dropped once either end is set.
|
|
52
|
+
*
|
|
53
|
+
* @example createFacets<Poster>().range("price", (poster) => poster.price, { buckets: [0, 2500, 5000] })
|
|
54
|
+
*/
|
|
55
|
+
range(name, read, options = {}) {
|
|
56
|
+
return new FacetSet([
|
|
57
|
+
...this.#entries,
|
|
58
|
+
{
|
|
59
|
+
kind: "range",
|
|
60
|
+
name,
|
|
61
|
+
minParam: options.minParam ?? `${name}_min`,
|
|
62
|
+
maxParam: options.maxParam ?? `${name}_max`,
|
|
63
|
+
buckets: [...(options.buckets ?? [])].sort((a, b) => a - b),
|
|
64
|
+
read,
|
|
65
|
+
},
|
|
66
|
+
]);
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Adds a yes/no facet, such as "in stock", that keeps only records passing the test once on.
|
|
70
|
+
*
|
|
71
|
+
* @example createFacets<Poster>().toggle("inStock", (poster) => poster.stock > 0)
|
|
72
|
+
*/
|
|
73
|
+
toggle(name, read, options = {}) {
|
|
74
|
+
return new FacetSet([
|
|
75
|
+
...this.#entries,
|
|
76
|
+
{ kind: "toggle", name, param: options.param ?? name, read },
|
|
77
|
+
]);
|
|
78
|
+
}
|
|
79
|
+
/** A selection with every facet cleared: no terms, open ranges, toggles off. */
|
|
80
|
+
empty() {
|
|
81
|
+
let filters = {};
|
|
82
|
+
for (let entry of this.#entries)
|
|
83
|
+
filters[entry.name] = blank(entry);
|
|
84
|
+
return filters;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Reads the filters from a URL's query. Blank parameters count as absent; every malformed
|
|
88
|
+
* one (an undeclared value, a non-number, a reversed range, too many values) is reported
|
|
89
|
+
* together, each issue's path naming its parameter.
|
|
90
|
+
*
|
|
91
|
+
* @example let filters = posterFacets.parse(url.searchParams);
|
|
92
|
+
*/
|
|
93
|
+
parse(searchParams) {
|
|
94
|
+
let issues = [];
|
|
95
|
+
let filters = {};
|
|
96
|
+
for (let entry of this.#entries) {
|
|
97
|
+
if (entry.kind === "terms")
|
|
98
|
+
filters[entry.name] = parseTerms(entry, searchParams, issues);
|
|
99
|
+
else if (entry.kind === "range")
|
|
100
|
+
filters[entry.name] = parseRange(entry, searchParams, issues);
|
|
101
|
+
else
|
|
102
|
+
filters[entry.name] = parseToggle(entry, searchParams, issues);
|
|
103
|
+
}
|
|
104
|
+
if (issues.length > 0)
|
|
105
|
+
return failure(new ValidationError(issues));
|
|
106
|
+
return success(filters);
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Writes filters into query parameters. Parameters in `base` that no facet owns (a search
|
|
110
|
+
* query, a sort) are kept, every facet parameter is rewritten, and terms come out in a
|
|
111
|
+
* stable order so one selection always yields one URL.
|
|
112
|
+
*
|
|
113
|
+
* @example `?${posterFacets.serialize(posterFacets.toggleTerm(filters, "color", "ochre"), url.searchParams)}`
|
|
114
|
+
*/
|
|
115
|
+
serialize(filters, base) {
|
|
116
|
+
let params = new URLSearchParams(base);
|
|
117
|
+
let selection = filters;
|
|
118
|
+
for (let entry of this.#entries) {
|
|
119
|
+
for (let param of paramsOf(entry))
|
|
120
|
+
params.delete(param);
|
|
121
|
+
}
|
|
122
|
+
for (let entry of this.#entries) {
|
|
123
|
+
let value = selection[entry.name];
|
|
124
|
+
if (!isActive(value))
|
|
125
|
+
continue;
|
|
126
|
+
if (entry.kind === "terms") {
|
|
127
|
+
for (let term of orderTerms(value, entry.values))
|
|
128
|
+
params.append(entry.param, term);
|
|
129
|
+
}
|
|
130
|
+
else if (entry.kind === "range") {
|
|
131
|
+
let range = value;
|
|
132
|
+
if (range.min !== null)
|
|
133
|
+
params.set(entry.minParam, String(range.min));
|
|
134
|
+
if (range.max !== null)
|
|
135
|
+
params.set(entry.maxParam, String(range.max));
|
|
136
|
+
}
|
|
137
|
+
else {
|
|
138
|
+
params.set(entry.param, "1");
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
return params;
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Narrows the records to those passing every filter, and counts each facet's options over
|
|
145
|
+
* the records every *other* facet leaves, so choosing a colour never hides the other
|
|
146
|
+
* colours' counts. One pass over the records, whatever the number of facets.
|
|
147
|
+
*
|
|
148
|
+
* @example let { items, total, counts } = posterFacets.apply(posters, filters);
|
|
149
|
+
*/
|
|
150
|
+
apply(records, filters = {}) {
|
|
151
|
+
let selection = filters;
|
|
152
|
+
let tallies = this.#entries.map((entry) => new Tally(entry, selection[entry.name]));
|
|
153
|
+
let items = [];
|
|
154
|
+
for (let record of records) {
|
|
155
|
+
let failed = -1;
|
|
156
|
+
let failures = 0;
|
|
157
|
+
for (let [index, entry] of this.#entries.entries()) {
|
|
158
|
+
if (matches(entry, record, selection[entry.name]))
|
|
159
|
+
continue;
|
|
160
|
+
failures += 1;
|
|
161
|
+
failed = index;
|
|
162
|
+
if (failures > 1)
|
|
163
|
+
break;
|
|
164
|
+
}
|
|
165
|
+
if (failures === 0) {
|
|
166
|
+
items.push(record);
|
|
167
|
+
for (let tally of tallies)
|
|
168
|
+
tally.add(record);
|
|
169
|
+
}
|
|
170
|
+
else if (failures === 1) {
|
|
171
|
+
tallies[failed]?.add(record);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
let counts = {};
|
|
175
|
+
for (let tally of tallies)
|
|
176
|
+
counts[tally.entry.name] = tally.result();
|
|
177
|
+
return { items, total: items.length, counts: counts };
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Adds a value to a terms facet's selection, or removes it when already chosen: the link
|
|
181
|
+
* behind one checkbox in a facet list.
|
|
182
|
+
*/
|
|
183
|
+
toggleTerm(filters, name, value) {
|
|
184
|
+
let selected = filters[name];
|
|
185
|
+
let current = Array.isArray(selected) ? selected : [];
|
|
186
|
+
let next = current.includes(value)
|
|
187
|
+
? current.filter((term) => term !== value)
|
|
188
|
+
: [...current, value];
|
|
189
|
+
return { ...filters, [name]: next };
|
|
190
|
+
}
|
|
191
|
+
/** Replaces one facet's selection, leaving the others as they are. */
|
|
192
|
+
set(filters, name, value) {
|
|
193
|
+
return { ...filters, [name]: value };
|
|
194
|
+
}
|
|
195
|
+
/** Clears one facet's selection, or every facet's when no name is given. */
|
|
196
|
+
clear(filters, name) {
|
|
197
|
+
if (name === undefined)
|
|
198
|
+
return this.empty();
|
|
199
|
+
let entry = this.#entries.find((candidate) => candidate.name === name);
|
|
200
|
+
if (entry === undefined)
|
|
201
|
+
return filters;
|
|
202
|
+
return { ...filters, [name]: blank(entry) };
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Lists every filter in effect, one entry per chosen term, range or toggle, each carrying
|
|
206
|
+
* the selection without it so a chip's remove link is one `serialize()` away.
|
|
207
|
+
*/
|
|
208
|
+
applied(filters) {
|
|
209
|
+
let list = [];
|
|
210
|
+
let selection = filters;
|
|
211
|
+
for (let entry of this.#entries) {
|
|
212
|
+
let value = selection[entry.name];
|
|
213
|
+
if (!isActive(value))
|
|
214
|
+
continue;
|
|
215
|
+
let facet = entry.name;
|
|
216
|
+
if (entry.kind === "terms") {
|
|
217
|
+
for (let term of orderTerms(value, entry.values)) {
|
|
218
|
+
let rest = value.filter((other) => other !== term);
|
|
219
|
+
list.push({ facet, kind: "terms", value: term, filters: { ...filters, [facet]: rest } });
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
else if (entry.kind === "range") {
|
|
223
|
+
list.push({
|
|
224
|
+
facet,
|
|
225
|
+
kind: "range",
|
|
226
|
+
value: value,
|
|
227
|
+
filters: this.clear(filters, facet),
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
else {
|
|
231
|
+
list.push({ facet, kind: "toggle", value: true, filters: this.clear(filters, facet) });
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
return list;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* Starts a facet set for one record type; chain `.terms()`, `.range()` and `.toggle()` to add
|
|
239
|
+
* facets. The record type is the only type argument, and every facet name is inferred.
|
|
240
|
+
*
|
|
241
|
+
* @template T The record type.
|
|
242
|
+
* @example let posterFacets = createFacets<Poster>().terms("style", (p) => p.style).toggle("inStock", (p) => p.stock > 0);
|
|
243
|
+
*/
|
|
244
|
+
export function createFacets() {
|
|
245
|
+
return new FacetSet();
|
|
246
|
+
}
|
|
247
|
+
/** Counts one facet's options over the records it is shown. */
|
|
248
|
+
class Tally {
|
|
249
|
+
entry;
|
|
250
|
+
#selection;
|
|
251
|
+
#terms = new Map();
|
|
252
|
+
#buckets;
|
|
253
|
+
#on = 0;
|
|
254
|
+
#min = null;
|
|
255
|
+
#max = null;
|
|
256
|
+
constructor(entry, selection) {
|
|
257
|
+
this.entry = entry;
|
|
258
|
+
this.#selection = selection;
|
|
259
|
+
this.#buckets = entry.kind === "range" ? entry.buckets.map(() => 0) : [];
|
|
260
|
+
}
|
|
261
|
+
add(record) {
|
|
262
|
+
let entry = this.entry;
|
|
263
|
+
if (entry.kind === "terms") {
|
|
264
|
+
for (let term of readTerms(entry, record))
|
|
265
|
+
this.#terms.set(term, (this.#terms.get(term) ?? 0) + 1);
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
if (entry.kind === "toggle") {
|
|
269
|
+
if (entry.read(record) === true)
|
|
270
|
+
this.#on += 1;
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
let value = entry.read(record);
|
|
274
|
+
if (typeof value !== "number" || !Number.isFinite(value))
|
|
275
|
+
return;
|
|
276
|
+
this.#min = this.#min === null ? value : Math.min(this.#min, value);
|
|
277
|
+
this.#max = this.#max === null ? value : Math.max(this.#max, value);
|
|
278
|
+
let index = bucketIndex(entry.buckets, value);
|
|
279
|
+
if (index !== -1)
|
|
280
|
+
this.#buckets[index] = (this.#buckets[index] ?? 0) + 1;
|
|
281
|
+
}
|
|
282
|
+
result() {
|
|
283
|
+
let entry = this.entry;
|
|
284
|
+
if (entry.kind === "terms")
|
|
285
|
+
return termCounts(this.#terms, this.#selection, entry.values);
|
|
286
|
+
if (entry.kind === "toggle")
|
|
287
|
+
return { count: this.#on, selected: this.#selection === true };
|
|
288
|
+
let range = isRange(this.#selection) ? this.#selection : { min: null, max: null };
|
|
289
|
+
let buckets = entry.buckets.map((min, index) => {
|
|
290
|
+
let max = entry.buckets[index + 1] ?? null;
|
|
291
|
+
return {
|
|
292
|
+
min,
|
|
293
|
+
max,
|
|
294
|
+
count: this.#buckets[index] ?? 0,
|
|
295
|
+
selected: range.min === min && range.max === max,
|
|
296
|
+
};
|
|
297
|
+
});
|
|
298
|
+
return { min: this.#min, max: this.#max, buckets };
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
/**
|
|
302
|
+
* Orders a terms facet's options: declared values in their declared order, zeros included;
|
|
303
|
+
* otherwise by count, most first, then by value. A chosen value always stays in the list,
|
|
304
|
+
* so its checkbox can be unticked even when nothing matches it any more.
|
|
305
|
+
*/
|
|
306
|
+
function termCounts(tally, selection, values) {
|
|
307
|
+
let chosen = Array.isArray(selection) ? selection : [];
|
|
308
|
+
let names = values === null ? [...tally.keys()] : [...values];
|
|
309
|
+
for (let term of chosen)
|
|
310
|
+
if (!names.includes(term))
|
|
311
|
+
names.push(term);
|
|
312
|
+
let counts = names.map((value) => ({
|
|
313
|
+
value,
|
|
314
|
+
count: tally.get(value) ?? 0,
|
|
315
|
+
selected: chosen.includes(value),
|
|
316
|
+
}));
|
|
317
|
+
if (values !== null)
|
|
318
|
+
return counts;
|
|
319
|
+
return counts.sort((a, b) => b.count - a.count || compareText(a.value, b.value));
|
|
320
|
+
}
|
|
321
|
+
/** Code-unit order, so counts sort the same in every runtime and locale. */
|
|
322
|
+
function compareText(a, b) {
|
|
323
|
+
if (a === b)
|
|
324
|
+
return 0;
|
|
325
|
+
return a < b ? -1 : 1;
|
|
326
|
+
}
|
|
327
|
+
/** The bucket `[edge, nextEdge)` a value falls in, or -1 below the first edge. */
|
|
328
|
+
function bucketIndex(edges, value) {
|
|
329
|
+
for (let index = edges.length - 1; index >= 0; index -= 1) {
|
|
330
|
+
let edge = edges[index];
|
|
331
|
+
if (edge !== undefined && inRange(value, { min: edge, max: edges[index + 1] ?? null }))
|
|
332
|
+
return index;
|
|
333
|
+
}
|
|
334
|
+
return -1;
|
|
335
|
+
}
|
|
336
|
+
/** Puts chosen terms in declared order, or alphabetical order without one, deduplicated. */
|
|
337
|
+
function orderTerms(terms, values) {
|
|
338
|
+
let unique = [...new Set(terms)];
|
|
339
|
+
if (values === null)
|
|
340
|
+
return unique.sort(compareText);
|
|
341
|
+
let rank = (term) => {
|
|
342
|
+
let index = values.indexOf(term);
|
|
343
|
+
return index === -1 ? values.length : index;
|
|
344
|
+
};
|
|
345
|
+
return unique.sort((a, b) => rank(a) - rank(b) || compareText(a, b));
|
|
346
|
+
}
|
|
347
|
+
/** The query parameters a facet owns. */
|
|
348
|
+
function paramsOf(entry) {
|
|
349
|
+
return entry.kind === "range" ? [entry.minParam, entry.maxParam] : [entry.param];
|
|
350
|
+
}
|
|
351
|
+
/** A facet's cleared selection. */
|
|
352
|
+
function blank(entry) {
|
|
353
|
+
if (entry.kind === "terms")
|
|
354
|
+
return [];
|
|
355
|
+
if (entry.kind === "range")
|
|
356
|
+
return { min: null, max: null };
|
|
357
|
+
return false;
|
|
358
|
+
}
|
|
359
|
+
/** Reads a parameter, treating blank text as absent. */
|
|
360
|
+
function readParam(searchParams, name) {
|
|
361
|
+
let raw = searchParams.get(name);
|
|
362
|
+
if (raw === null)
|
|
363
|
+
return null;
|
|
364
|
+
let trimmed = raw.trim();
|
|
365
|
+
return trimmed === "" ? null : trimmed;
|
|
366
|
+
}
|
|
367
|
+
/** Reads a terms facet's repeated parameter, the shape a group of checkboxes submits. */
|
|
368
|
+
function parseTerms(entry, searchParams, issues) {
|
|
369
|
+
let terms = [
|
|
370
|
+
...new Set(searchParams
|
|
371
|
+
.getAll(entry.param)
|
|
372
|
+
.map((term) => term.trim())
|
|
373
|
+
.filter((term) => term !== "")),
|
|
374
|
+
];
|
|
375
|
+
if (terms.length > entry.limit) {
|
|
376
|
+
issues.push({ message: `Choose at most ${entry.limit} values`, path: [entry.param] });
|
|
377
|
+
return [];
|
|
378
|
+
}
|
|
379
|
+
for (let term of terms) {
|
|
380
|
+
if (term.length > MAX_TERM_LENGTH) {
|
|
381
|
+
issues.push({
|
|
382
|
+
message: `Expected a value of at most ${MAX_TERM_LENGTH} characters`,
|
|
383
|
+
path: [entry.param],
|
|
384
|
+
});
|
|
385
|
+
}
|
|
386
|
+
else if (entry.values !== null && !entry.values.includes(term)) {
|
|
387
|
+
issues.push({ message: `Unknown value "${term}"`, path: [entry.param] });
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
return terms;
|
|
391
|
+
}
|
|
392
|
+
/** Reads a range facet's two ends, each optional, and checks they are in order. */
|
|
393
|
+
function parseRange(entry, searchParams, issues) {
|
|
394
|
+
let min = parseNumber(searchParams, entry.minParam, issues);
|
|
395
|
+
let max = parseNumber(searchParams, entry.maxParam, issues);
|
|
396
|
+
if (min !== null && max !== null && min >= max) {
|
|
397
|
+
issues.push({ message: "Expected the lower end below the upper end", path: [entry.maxParam] });
|
|
398
|
+
}
|
|
399
|
+
return { min, max };
|
|
400
|
+
}
|
|
401
|
+
/** Reads one finite number, reporting anything else. */
|
|
402
|
+
function parseNumber(searchParams, param, issues) {
|
|
403
|
+
let raw = readParam(searchParams, param);
|
|
404
|
+
if (raw === null)
|
|
405
|
+
return null;
|
|
406
|
+
let value = Number(raw);
|
|
407
|
+
if (!Number.isFinite(value)) {
|
|
408
|
+
issues.push({ message: "Expected a number", path: [param] });
|
|
409
|
+
return null;
|
|
410
|
+
}
|
|
411
|
+
return value;
|
|
412
|
+
}
|
|
413
|
+
/** Reads a toggle, accepting what a checkbox, a link or a hand-typed URL would send. */
|
|
414
|
+
function parseToggle(entry, searchParams, issues) {
|
|
415
|
+
let raw = readParam(searchParams, entry.param);
|
|
416
|
+
if (raw === null)
|
|
417
|
+
return false;
|
|
418
|
+
let text = raw.toLowerCase();
|
|
419
|
+
if (TOGGLE_ON.has(text))
|
|
420
|
+
return true;
|
|
421
|
+
if (TOGGLE_OFF.has(text))
|
|
422
|
+
return false;
|
|
423
|
+
issues.push({ message: "Expected 1 or 0", path: [entry.param] });
|
|
424
|
+
return false;
|
|
425
|
+
}
|
package/dist/facet.d.ts
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The three facet definitions a set is built from, and how each reads a record, matches it
|
|
3
|
+
* against a selection and counts it. Each definition owns its query parameters, so parsing,
|
|
4
|
+
* serializing and counting a facet all agree on one spelling.
|
|
5
|
+
*
|
|
6
|
+
* @author [Sergio Xalambrí](https://sergiodxa.com)
|
|
7
|
+
* @copyright Sergio Xalambrí 2026
|
|
8
|
+
*/
|
|
9
|
+
import type { NumberRange } from "./types.js";
|
|
10
|
+
/** Longest single term value a URL may carry; longer text is a malformed link, not a value. */
|
|
11
|
+
export declare const MAX_TERM_LENGTH = 200;
|
|
12
|
+
/** How many values one terms facet may select from a URL unless its options say otherwise. */
|
|
13
|
+
export declare const DEFAULT_TERM_LIMIT = 50;
|
|
14
|
+
/** Options for a terms facet. */
|
|
15
|
+
export interface TermsOptions {
|
|
16
|
+
/** The query parameter the facet reads and writes. @default the facet name */
|
|
17
|
+
param?: string;
|
|
18
|
+
/**
|
|
19
|
+
* The values the facet accepts, in display order. Declared values are listed even at a
|
|
20
|
+
* count of 0, and a URL naming any other value fails to parse.
|
|
21
|
+
*/
|
|
22
|
+
values?: readonly string[];
|
|
23
|
+
/** The most values one URL may select. @default 50 */
|
|
24
|
+
limit?: number;
|
|
25
|
+
}
|
|
26
|
+
/** Options for a range facet. */
|
|
27
|
+
export interface RangeOptions {
|
|
28
|
+
/** The parameter holding the inclusive lower end. @default `<name>_min` */
|
|
29
|
+
minParam?: string;
|
|
30
|
+
/** The parameter holding the exclusive upper end. @default `<name>_max` */
|
|
31
|
+
maxParam?: string;
|
|
32
|
+
/**
|
|
33
|
+
* Ascending bucket edges: `[0, 25, 50]` counts `[0, 25)`, `[25, 50)` and `[50, ∞)`.
|
|
34
|
+
* A value below the first edge falls in no bucket, so start at the lowest possible value.
|
|
35
|
+
* @default []
|
|
36
|
+
*/
|
|
37
|
+
buckets?: readonly number[];
|
|
38
|
+
}
|
|
39
|
+
/** Options for a toggle facet. */
|
|
40
|
+
export interface ToggleOptions {
|
|
41
|
+
/** The query parameter the facet reads and writes. @default the facet name */
|
|
42
|
+
param?: string;
|
|
43
|
+
}
|
|
44
|
+
/** A terms facet as a set stores it. */
|
|
45
|
+
export interface TermsEntry<T> {
|
|
46
|
+
kind: "terms";
|
|
47
|
+
name: string;
|
|
48
|
+
param: string;
|
|
49
|
+
values: readonly string[] | null;
|
|
50
|
+
limit: number;
|
|
51
|
+
read(record: T): string | readonly string[] | null | undefined;
|
|
52
|
+
}
|
|
53
|
+
/** A range facet as a set stores it. */
|
|
54
|
+
export interface RangeEntry<T> {
|
|
55
|
+
kind: "range";
|
|
56
|
+
name: string;
|
|
57
|
+
minParam: string;
|
|
58
|
+
maxParam: string;
|
|
59
|
+
buckets: readonly number[];
|
|
60
|
+
read(record: T): number | null | undefined;
|
|
61
|
+
}
|
|
62
|
+
/** A toggle facet as a set stores it. */
|
|
63
|
+
export interface ToggleEntry<T> {
|
|
64
|
+
kind: "toggle";
|
|
65
|
+
name: string;
|
|
66
|
+
param: string;
|
|
67
|
+
read(record: T): boolean;
|
|
68
|
+
}
|
|
69
|
+
/** Any facet a set stores. */
|
|
70
|
+
export type FacetEntry<T> = TermsEntry<T> | RangeEntry<T> | ToggleEntry<T>;
|
|
71
|
+
/**
|
|
72
|
+
* Reads a record's terms as a deduplicated list, so a record tagged twice with one value
|
|
73
|
+
* counts once and a missing value counts nowhere.
|
|
74
|
+
*/
|
|
75
|
+
export declare function readTerms<T>(entry: TermsEntry<T>, record: T): string[];
|
|
76
|
+
/** Whether a selection on this facet narrows the records at all. */
|
|
77
|
+
export declare function isActive(selection: unknown): boolean;
|
|
78
|
+
/** Whether a value has the shape of a range selection. */
|
|
79
|
+
export declare function isRange(value: unknown): value is NumberRange;
|
|
80
|
+
/** Whether a number falls in `[min, max)`, with a `null` end left open. */
|
|
81
|
+
export declare function inRange(value: number, range: NumberRange): boolean;
|
|
82
|
+
/**
|
|
83
|
+
* Whether a record passes one facet's selection. Within a terms facet the chosen values are
|
|
84
|
+
* alternatives (any one matches); a range needs a value inside it; a toggle needs `true`.
|
|
85
|
+
*/
|
|
86
|
+
export declare function matches<T>(entry: FacetEntry<T>, record: T, selection: unknown): boolean;
|
package/dist/facet.js
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The three facet definitions a set is built from, and how each reads a record, matches it
|
|
3
|
+
* against a selection and counts it. Each definition owns its query parameters, so parsing,
|
|
4
|
+
* serializing and counting a facet all agree on one spelling.
|
|
5
|
+
*
|
|
6
|
+
* @author [Sergio Xalambrí](https://sergiodxa.com)
|
|
7
|
+
* @copyright Sergio Xalambrí 2026
|
|
8
|
+
*/
|
|
9
|
+
/** Longest single term value a URL may carry; longer text is a malformed link, not a value. */
|
|
10
|
+
export const MAX_TERM_LENGTH = 200;
|
|
11
|
+
/** How many values one terms facet may select from a URL unless its options say otherwise. */
|
|
12
|
+
export const DEFAULT_TERM_LIMIT = 50;
|
|
13
|
+
/**
|
|
14
|
+
* Reads a record's terms as a deduplicated list, so a record tagged twice with one value
|
|
15
|
+
* counts once and a missing value counts nowhere.
|
|
16
|
+
*/
|
|
17
|
+
export function readTerms(entry, record) {
|
|
18
|
+
let raw = entry.read(record);
|
|
19
|
+
if (raw === null || raw === undefined)
|
|
20
|
+
return [];
|
|
21
|
+
if (typeof raw === "string")
|
|
22
|
+
return [raw];
|
|
23
|
+
return [...new Set(raw)];
|
|
24
|
+
}
|
|
25
|
+
/** Whether a selection on this facet narrows the records at all. */
|
|
26
|
+
export function isActive(selection) {
|
|
27
|
+
if (Array.isArray(selection))
|
|
28
|
+
return selection.length > 0;
|
|
29
|
+
if (typeof selection === "boolean")
|
|
30
|
+
return selection;
|
|
31
|
+
if (isRange(selection))
|
|
32
|
+
return selection.min !== null || selection.max !== null;
|
|
33
|
+
return false;
|
|
34
|
+
}
|
|
35
|
+
/** Whether a value has the shape of a range selection. */
|
|
36
|
+
export function isRange(value) {
|
|
37
|
+
return typeof value === "object" && value !== null && "min" in value && "max" in value;
|
|
38
|
+
}
|
|
39
|
+
/** Whether a number falls in `[min, max)`, with a `null` end left open. */
|
|
40
|
+
export function inRange(value, range) {
|
|
41
|
+
if (range.min !== null && value < range.min)
|
|
42
|
+
return false;
|
|
43
|
+
if (range.max !== null && value >= range.max)
|
|
44
|
+
return false;
|
|
45
|
+
return true;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Whether a record passes one facet's selection. Within a terms facet the chosen values are
|
|
49
|
+
* alternatives (any one matches); a range needs a value inside it; a toggle needs `true`.
|
|
50
|
+
*/
|
|
51
|
+
export function matches(entry, record, selection) {
|
|
52
|
+
if (!isActive(selection))
|
|
53
|
+
return true;
|
|
54
|
+
if (entry.kind === "terms") {
|
|
55
|
+
let chosen = selection;
|
|
56
|
+
return readTerms(entry, record).some((value) => chosen.includes(value));
|
|
57
|
+
}
|
|
58
|
+
if (entry.kind === "range") {
|
|
59
|
+
let value = entry.read(record);
|
|
60
|
+
return (typeof value === "number" &&
|
|
61
|
+
Number.isFinite(value) &&
|
|
62
|
+
inRange(value, selection));
|
|
63
|
+
}
|
|
64
|
+
return entry.read(record) === true;
|
|
65
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Faceted filtering over records already in memory: filters parsed from and written to a URL,
|
|
3
|
+
* the matching records, and each facet's counts with the other facets applied. For catalogues
|
|
4
|
+
* and lists small enough to filter in the request rather than in the database.
|
|
5
|
+
*
|
|
6
|
+
* @author [Sergio Xalambrí](https://sergiodxa.com)
|
|
7
|
+
* @copyright Sergio Xalambrí 2026
|
|
8
|
+
*/
|
|
9
|
+
export type { RangeOptions, TermsOptions, ToggleOptions } from "./facet.js";
|
|
10
|
+
export type { AppliedFilter, BucketCount, Counts, FacetKind, FacetResult, FacetShape, FacetsOfKind, Filters, NumberRange, RangeCounts, TermCount, ToggleCount, } from "./types.js";
|
|
11
|
+
export { createFacets, FacetSet } from "./facet-set.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Faceted filtering over records already in memory: filters parsed from and written to a URL,
|
|
3
|
+
* the matching records, and each facet's counts with the other facets applied. For catalogues
|
|
4
|
+
* and lists small enough to filter in the request rather than in the database.
|
|
5
|
+
*
|
|
6
|
+
* @author [Sergio Xalambrí](https://sergiodxa.com)
|
|
7
|
+
* @copyright Sergio Xalambrí 2026
|
|
8
|
+
*/
|
|
9
|
+
export { createFacets, FacetSet } from "./facet-set.js";
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The shapes a facet set reads and returns: the filters a URL carries, the counts each facet
|
|
3
|
+
* shows beside its options, and the applied filters a chip row lists. Every shape is keyed by
|
|
4
|
+
* facet name, so a typo in a facet name is a type error at the call site.
|
|
5
|
+
*
|
|
6
|
+
* @author [Sergio Xalambrí](https://sergiodxa.com)
|
|
7
|
+
* @copyright Sergio Xalambrí 2026
|
|
8
|
+
*/
|
|
9
|
+
/** How a facet matches records: by listed values, by a numeric interval, or by a yes/no test. */
|
|
10
|
+
export type FacetKind = "terms" | "range" | "toggle";
|
|
11
|
+
/** A facet set's facets by name, each mapped to its kind. */
|
|
12
|
+
export type FacetShape = Record<string, FacetKind>;
|
|
13
|
+
/**
|
|
14
|
+
* A numeric interval with either end open. `min` is inclusive and `max` exclusive, so
|
|
15
|
+
* adjacent buckets never both claim a record sitting on their shared edge.
|
|
16
|
+
*/
|
|
17
|
+
export interface NumberRange {
|
|
18
|
+
min: number | null;
|
|
19
|
+
max: number | null;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* The selection for every facet: the values chosen on a terms facet (empty when none),
|
|
23
|
+
* the interval on a range facet (both ends `null` when none), and whether a toggle is on.
|
|
24
|
+
*/
|
|
25
|
+
export type Filters<D extends FacetShape> = {
|
|
26
|
+
[K in keyof D]: D[K] extends "terms" ? string[] : D[K] extends "range" ? NumberRange : boolean;
|
|
27
|
+
};
|
|
28
|
+
/** One option of a terms facet, counted with every other facet's filter applied. */
|
|
29
|
+
export interface TermCount {
|
|
30
|
+
value: string;
|
|
31
|
+
count: number;
|
|
32
|
+
/** Whether the filters choose this value; a chosen value stays listed at a count of 0. */
|
|
33
|
+
selected: boolean;
|
|
34
|
+
}
|
|
35
|
+
/** One bucket of a range facet: `[min, max)`, where a `null` max is open-ended. */
|
|
36
|
+
export interface BucketCount {
|
|
37
|
+
min: number;
|
|
38
|
+
max: number | null;
|
|
39
|
+
count: number;
|
|
40
|
+
/** Whether the range filter is exactly this bucket's interval. */
|
|
41
|
+
selected: boolean;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* A range facet's counts, plus the smallest and largest value among the records the other
|
|
45
|
+
* facets leave, for a slider's bounds; both are `null` when no record carries a value.
|
|
46
|
+
*/
|
|
47
|
+
export interface RangeCounts {
|
|
48
|
+
min: number | null;
|
|
49
|
+
max: number | null;
|
|
50
|
+
buckets: BucketCount[];
|
|
51
|
+
}
|
|
52
|
+
/** How many records a toggle would leave on, counted with every other facet applied. */
|
|
53
|
+
export interface ToggleCount {
|
|
54
|
+
count: number;
|
|
55
|
+
selected: boolean;
|
|
56
|
+
}
|
|
57
|
+
/** The counts every facet shows, in the shape its kind calls for. */
|
|
58
|
+
export type Counts<D extends FacetShape> = {
|
|
59
|
+
[K in keyof D]: D[K] extends "terms" ? TermCount[] : D[K] extends "range" ? RangeCounts : ToggleCount;
|
|
60
|
+
};
|
|
61
|
+
/** The records that pass every filter, how many there are, and every facet's counts. */
|
|
62
|
+
export interface FacetResult<T, D extends FacetShape> {
|
|
63
|
+
/** The matching records in their input order; sorting and paging stay with the caller. */
|
|
64
|
+
items: T[];
|
|
65
|
+
total: number;
|
|
66
|
+
counts: Counts<D>;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* One filter in effect, for a row of removable chips: a chosen term, a range, or a toggle
|
|
70
|
+
* that is on. `filters` is the full selection with only this one removed, ready to serialize
|
|
71
|
+
* into the chip's link.
|
|
72
|
+
*/
|
|
73
|
+
export interface AppliedFilter<D extends FacetShape> {
|
|
74
|
+
facet: keyof D & string;
|
|
75
|
+
kind: FacetKind;
|
|
76
|
+
value: string | NumberRange | true;
|
|
77
|
+
filters: Filters<D>;
|
|
78
|
+
}
|
|
79
|
+
/** The facet names of one kind, such as every terms facet for `toggle()`. */
|
|
80
|
+
export type FacetsOfKind<D extends FacetShape, K extends FacetKind> = {
|
|
81
|
+
[N in keyof D]: D[N] extends K ? N : never;
|
|
82
|
+
}[keyof D] & string;
|
package/dist/types.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The shapes a facet set reads and returns: the filters a URL carries, the counts each facet
|
|
3
|
+
* shows beside its options, and the applied filters a chip row lists. Every shape is keyed by
|
|
4
|
+
* facet name, so a typo in a facet name is a type error at the call site.
|
|
5
|
+
*
|
|
6
|
+
* @author [Sergio Xalambrí](https://sergiodxa.com)
|
|
7
|
+
* @copyright Sergio Xalambrí 2026
|
|
8
|
+
*/
|
package/package.json
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@sdxc/facets",
|
|
3
|
+
"version": "0.0.0-pre.1",
|
|
4
|
+
"description": "Faceted filtering over in-memory records: URL filters, disjunctive facet counts and range buckets",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": "./dist/index.js"
|
|
9
|
+
},
|
|
10
|
+
"dependencies": {
|
|
11
|
+
"@sdxc/result": "2026.10.13",
|
|
12
|
+
"@sdxc/validate": "2026.11.10"
|
|
13
|
+
},
|
|
14
|
+
"gitHead": "29c98dd14bcff38142e870a7fe8041c7901bc9a2",
|
|
15
|
+
"publishConfig": {
|
|
16
|
+
"access": "public"
|
|
17
|
+
},
|
|
18
|
+
"repository": {
|
|
19
|
+
"type": "git",
|
|
20
|
+
"url": "git+https://github.com/sergiodxa/monorepo.git",
|
|
21
|
+
"directory": "packages/facets"
|
|
22
|
+
},
|
|
23
|
+
"homepage": "https://sdxc.dev/api/facets",
|
|
24
|
+
"author": {
|
|
25
|
+
"name": "Sergio Xalambrí",
|
|
26
|
+
"url": "https://sergiodxa.com"
|
|
27
|
+
},
|
|
28
|
+
"funding": {
|
|
29
|
+
"type": "github",
|
|
30
|
+
"url": "https://github.com/sponsors/sergiodxa"
|
|
31
|
+
}
|
|
32
|
+
}
|