@bitbaum/listkit 0.0.0-stage → 0.2.2
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 +21 -0
- package/README.md +143 -2
- package/dist/apply.d.ts +46 -0
- package/dist/apply.js +88 -0
- package/dist/facets.d.ts +82 -0
- package/dist/facets.js +79 -0
- package/dist/index.d.ts +30 -0
- package/dist/index.js +30 -0
- package/dist/page.d.ts +42 -0
- package/dist/page.js +62 -0
- package/dist/query.d.ts +71 -0
- package/dist/query.js +123 -0
- package/dist/search.d.ts +46 -0
- package/dist/search.js +76 -0
- package/dist/sort.d.ts +25 -0
- package/dist/sort.js +68 -0
- package/dist/values.d.ts +47 -0
- package/dist/values.js +73 -0
- package/package.json +58 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Mao Nakamoto
|
|
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
CHANGED
|
@@ -1,3 +1,144 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @bitbaum/listkit
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A list as a query. Filtering, sorting, searching and paging are the same problem
|
|
4
|
+
everywhere, and they were solved separately everywhere.
|
|
5
|
+
|
|
6
|
+
A survey of twelve repositories in this fleet on 2026-09-11 found:
|
|
7
|
+
|
|
8
|
+
| what | count |
|
|
9
|
+
| --- | --- |
|
|
10
|
+
| incompatible filter-state shapes | 12, no two alike |
|
|
11
|
+
| hand-built URL builders | ~34 |
|
|
12
|
+
| copies of "toggle a value in a set" | ~25, in two encodings |
|
|
13
|
+
| debounces, at five different delays | ~11 |
|
|
14
|
+
| copies of `Math.ceil(total / pageSize)` | ~11, three in one repo |
|
|
15
|
+
| repos that escape `%` and `_` before a SQL `LIKE` | 3 of 7 that need to |
|
|
16
|
+
|
|
17
|
+
Two of the toggle copies were character-for-character identical in repos that
|
|
18
|
+
share no code. One repo wrote the same three-line body eight times for eight
|
|
19
|
+
facets, plus eleven more for its boolean flags — about a hundred and twenty
|
|
20
|
+
lines expressing one idea.
|
|
21
|
+
|
|
22
|
+
Four live bugs were among the URL builders, and this codec exists so they cannot
|
|
23
|
+
be written again:
|
|
24
|
+
|
|
25
|
+
- one built `new URLSearchParams()` from scratch, so applying a preset silently
|
|
26
|
+
wiped the reader's active search and five other facets;
|
|
27
|
+
- one changed a date range without clearing `page`, landing the reader on page 4
|
|
28
|
+
of a two-page result;
|
|
29
|
+
- one preserved exactly three params by name, so every param added later had to
|
|
30
|
+
be remembered in six separate template strings;
|
|
31
|
+
- one used `push` rather than `replace` for a debounced search box, so the back
|
|
32
|
+
button walked backwards through every intermediate spelling of the word.
|
|
33
|
+
|
|
34
|
+
## What it ships
|
|
35
|
+
|
|
36
|
+
The **decisions**, and nothing else.
|
|
37
|
+
|
|
38
|
+
```ts
|
|
39
|
+
import { parseQuery, writeQuery, applyQuery, type ListSpec } from "@bitbaum/listkit";
|
|
40
|
+
|
|
41
|
+
const spec: ListSpec<Project> = {
|
|
42
|
+
facets: [
|
|
43
|
+
{ key: "kind", kind: "one", value: (p) => p.kind, options: ["product", "client", "demo"] },
|
|
44
|
+
{ key: "status", kind: "many", value: (p) => p.status, options: ["live", "prospect"] },
|
|
45
|
+
{ key: "nosite", kind: "flag", value: (p) => !p.site },
|
|
46
|
+
],
|
|
47
|
+
search: { text: (p) => [p.name, p.description, p.host] },
|
|
48
|
+
sorts: [
|
|
49
|
+
{ key: "name", by: [(p) => p.name] },
|
|
50
|
+
{ key: "newest", by: [(p) => p.since, (p) => p.name] },
|
|
51
|
+
],
|
|
52
|
+
defaultSort: "name",
|
|
53
|
+
defaultPageSize: 25,
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
const query = parseQuery(searchParams, spec); // validated, clamped
|
|
57
|
+
const { rows, matched, page, counts } = applyQuery(projects, spec, query);
|
|
58
|
+
const url = `?${writeQuery(searchParams, next, spec, query)}`;
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
### Five facet kinds, and no magic sentinel
|
|
62
|
+
|
|
63
|
+
`one` · `many` · `flag` · `range` · `ordinal`. The value for "no filter" is the
|
|
64
|
+
**empty selection**, never a magic string. One surveyed repo used the translated
|
|
65
|
+
label (`"Alle"`) as its all-value, which made filter identity depend on the
|
|
66
|
+
reader's language.
|
|
67
|
+
|
|
68
|
+
### Rules the tests pin
|
|
69
|
+
|
|
70
|
+
- An **empty selection filters nothing**, not everything.
|
|
71
|
+
- **Missing values sort last in both directions.** A record with no date is not
|
|
72
|
+
the oldest record.
|
|
73
|
+
- **`?page=0` can never become a negative offset**, and an empty list still has
|
|
74
|
+
one page rather than "page 1 of 0".
|
|
75
|
+
- **Facet counts are computed with that facet's own selection lifted**, so while
|
|
76
|
+
filtering by `kind=product` the count beside `kind=demo` still says how many
|
|
77
|
+
demos exist, instead of zero.
|
|
78
|
+
- **Writing copies the params you were given.** A locale or a referrer survives.
|
|
79
|
+
- **`page` is dropped when the result set changes**, kept when only the page moves.
|
|
80
|
+
- **A superseded async search resolves to `undefined`**, so a slow "ab" cannot
|
|
81
|
+
overwrite a fast "abc".
|
|
82
|
+
- **Every search word must match, folded**, and a non-match scores 0.
|
|
83
|
+
- **A reader's chosen sort is never overridden by relevance.**
|
|
84
|
+
|
|
85
|
+
### Search that finds what people type
|
|
86
|
+
|
|
87
|
+
- **Every word, any order.** `bike sell` finds "Sell my old bike".
|
|
88
|
+
- **Accents and ß fold.** `zurich` finds "Zürich", `strasse` finds "Straße".
|
|
89
|
+
- **Best match first.** While a search is active and the reader has not picked
|
|
90
|
+
a sort, results rank by where a word matched — `search.text` lists fields
|
|
91
|
+
most important first — and how well: the whole field, its start, a word's
|
|
92
|
+
start, anywhere inside. A phrase match earns a bonus; ties keep the default
|
|
93
|
+
order. A sort the reader chose wins. `?sort=relevance` asks for it
|
|
94
|
+
explicitly; `search: { rank: false }` opts a list out.
|
|
95
|
+
- **One rule for SQL too.** `searchTerms(q)` gives the folded words; apply one
|
|
96
|
+
`likeContains` per term, ANDed, and the database agrees with the array.
|
|
97
|
+
(Fold the column the same way — `unaccent()` in Postgres.)
|
|
98
|
+
|
|
99
|
+
No stemming, no typo tolerance, no index: that is a search engine's job.
|
|
100
|
+
|
|
101
|
+
## What it deliberately does not ship
|
|
102
|
+
|
|
103
|
+
Markup, tokens, React, a search engine, or an HTTP client.
|
|
104
|
+
|
|
105
|
+
Nine token vocabularies and six chip treatments were found among those same
|
|
106
|
+
repos, several different **on purpose** — one marketplace is monochrome by
|
|
107
|
+
design, one product reserves an accent colour for Bitcoin UI, one is the only
|
|
108
|
+
RTL-aware surface in the fleet. The fleet has already run the experiment where a
|
|
109
|
+
shared renderer owns the markup: it reached two consumers out of twenty and
|
|
110
|
+
shipped the same two defects to both, unfixable downstream because a consumer
|
|
111
|
+
cannot patch markup it does not own.
|
|
112
|
+
|
|
113
|
+
Centralize the rule; render it locally.
|
|
114
|
+
|
|
115
|
+
The execution engine is also yours. `applyQuery` is the in-memory engine, for
|
|
116
|
+
bounded collections. The same `ListSpec` describes what a SQL builder should do
|
|
117
|
+
with a large one — `escapeLike` and `likeContains` are exported for exactly that.
|
|
118
|
+
Forcing one execution model would serve one repo and strand the rest.
|
|
119
|
+
|
|
120
|
+
## Install
|
|
121
|
+
|
|
122
|
+
```bash
|
|
123
|
+
pnpm add @bitbaum/listkit
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
## Develop
|
|
127
|
+
|
|
128
|
+
```bash
|
|
129
|
+
pnpm install
|
|
130
|
+
pnpm run verify # format, lint, typecheck, build, test
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
Tests import the package **by name**, so a broken `exports` or `files` map fails
|
|
134
|
+
here rather than at the first consumer's install.
|
|
135
|
+
|
|
136
|
+
MIT.
|
|
137
|
+
|
|
138
|
+
---
|
|
139
|
+
|
|
140
|
+
Part of **[bitbaum](https://bitbaum.orangecat.ch)** — AI-native products on open
|
|
141
|
+
infrastructure, built in Zürich. Every package here lists the apps that use it:
|
|
142
|
+
**[which apps use listkit](https://bitbaum.orangecat.ch/packages/#listkit)**.
|
|
143
|
+
|
|
144
|
+
Git releases include the compiled `dist/` artifact and require no consumer-side prepare build. Package CI rebuilds it and refuses a mismatch with committed output, so consumers can retain pnpm's default build-script restrictions. The same public exports work for Git and npm installs.
|
package/dist/apply.d.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Running a query against an in-memory array, and counting the result.
|
|
3
|
+
*
|
|
4
|
+
* This is one of two execution models on purpose. The survey found repos that
|
|
5
|
+
* filter entirely in the browser over a bounded, statically generated array
|
|
6
|
+
* (correct for them), repos that never do client work and push every predicate
|
|
7
|
+
* into SQL (also correct), and repos that must mix because a computed column
|
|
8
|
+
* cannot be filtered in the database. A package that forces one of those serves
|
|
9
|
+
* one repo and strands the rest — so the SPEC is shared and the engine is not.
|
|
10
|
+
* This module is the array engine; a SQL engine consumes the same spec.
|
|
11
|
+
*/
|
|
12
|
+
import { type ListSpec } from "./facets.js";
|
|
13
|
+
import { type PageInfo } from "./page.js";
|
|
14
|
+
import { type ListQuery } from "./query.js";
|
|
15
|
+
export type ListResult<T> = {
|
|
16
|
+
/** The rows on the current page. */
|
|
17
|
+
rows: T[];
|
|
18
|
+
/** Every row that passed, before paging — for "N of M". */
|
|
19
|
+
matched: number;
|
|
20
|
+
total: number;
|
|
21
|
+
page: PageInfo;
|
|
22
|
+
/**
|
|
23
|
+
* For each facet, how many rows each option would leave if it were added to
|
|
24
|
+
* the current selection. Rendering a filter that leads to nothing is how a
|
|
25
|
+
* reader concludes the page is broken.
|
|
26
|
+
*/
|
|
27
|
+
counts: Record<string, Record<string, number>>;
|
|
28
|
+
};
|
|
29
|
+
/** Every row that passes the query, unpaged and unsorted. */
|
|
30
|
+
export declare function matches<T>(rows: readonly T[], spec: ListSpec<T>, query: ListQuery): T[];
|
|
31
|
+
/**
|
|
32
|
+
* How many rows each option of each facet would yield.
|
|
33
|
+
*
|
|
34
|
+
* Counted with that facet's OWN selection lifted, which is what makes the
|
|
35
|
+
* numbers useful: while filtering by `kind=product`, the count beside
|
|
36
|
+
* `kind=demo` should say how many demos there are, not zero.
|
|
37
|
+
*/
|
|
38
|
+
export declare function facetCounts<T>(rows: readonly T[], spec: ListSpec<T>, query: ListQuery): Record<string, Record<string, number>>;
|
|
39
|
+
/**
|
|
40
|
+
* Is this query ordered by relevance? Only while there is text to rank by,
|
|
41
|
+
* and only when the reader asked for it (`?sort=relevance`) or has not chosen
|
|
42
|
+
* a sort of their own — an explicit "newest" stays newest while searching.
|
|
43
|
+
*/
|
|
44
|
+
export declare function isRanked<T>(spec: ListSpec<T>, query: ListQuery): boolean;
|
|
45
|
+
/** Filter, sort, count and page in one pass. */
|
|
46
|
+
export declare function applyQuery<T>(rows: readonly T[], spec: ListSpec<T>, query: ListQuery): ListResult<T>;
|
package/dist/apply.js
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Running a query against an in-memory array, and counting the result.
|
|
3
|
+
*
|
|
4
|
+
* This is one of two execution models on purpose. The survey found repos that
|
|
5
|
+
* filter entirely in the browser over a bounded, statically generated array
|
|
6
|
+
* (correct for them), repos that never do client work and push every predicate
|
|
7
|
+
* into SQL (also correct), and repos that must mix because a computed column
|
|
8
|
+
* cannot be filtered in the database. A package that forces one of those serves
|
|
9
|
+
* one repo and strands the rest — so the SPEC is shared and the engine is not.
|
|
10
|
+
* This module is the array engine; a SQL engine consumes the same spec.
|
|
11
|
+
*/
|
|
12
|
+
import { facetMatches } from "./facets.js";
|
|
13
|
+
import { searchMatches, searchScore, searchTerms } from "./search.js";
|
|
14
|
+
import { compareBy } from "./sort.js";
|
|
15
|
+
import { pageOf } from "./page.js";
|
|
16
|
+
import { RELEVANCE_SORT } from "./query.js";
|
|
17
|
+
/** Every row that passes the query, unpaged and unsorted. */
|
|
18
|
+
export function matches(rows, spec, query) {
|
|
19
|
+
return rows.filter((row) => {
|
|
20
|
+
if (!searchMatches(spec.search, row, query.q))
|
|
21
|
+
return false;
|
|
22
|
+
for (const facet of spec.facets) {
|
|
23
|
+
if (!facetMatches(facet, row, query.facets[facet.key] ?? []))
|
|
24
|
+
return false;
|
|
25
|
+
}
|
|
26
|
+
return true;
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* How many rows each option of each facet would yield.
|
|
31
|
+
*
|
|
32
|
+
* Counted with that facet's OWN selection lifted, which is what makes the
|
|
33
|
+
* numbers useful: while filtering by `kind=product`, the count beside
|
|
34
|
+
* `kind=demo` should say how many demos there are, not zero.
|
|
35
|
+
*/
|
|
36
|
+
export function facetCounts(rows, spec, query) {
|
|
37
|
+
const out = {};
|
|
38
|
+
for (const facet of spec.facets) {
|
|
39
|
+
const others = { ...query, facets: { ...query.facets, [facet.key]: [] } };
|
|
40
|
+
const pool = matches(rows, spec, others);
|
|
41
|
+
const tally = {};
|
|
42
|
+
for (const option of facet.options ?? []) {
|
|
43
|
+
tally[option] = pool.filter((row) => facetMatches(facet, row, [option])).length;
|
|
44
|
+
}
|
|
45
|
+
out[facet.key] = tally;
|
|
46
|
+
}
|
|
47
|
+
return out;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Is this query ordered by relevance? Only while there is text to rank by,
|
|
51
|
+
* and only when the reader asked for it (`?sort=relevance`) or has not chosen
|
|
52
|
+
* a sort of their own — an explicit "newest" stays newest while searching.
|
|
53
|
+
*/
|
|
54
|
+
export function isRanked(spec, query) {
|
|
55
|
+
if (!spec.search || searchTerms(query.q).length === 0)
|
|
56
|
+
return false;
|
|
57
|
+
if (query.sort === RELEVANCE_SORT)
|
|
58
|
+
return true;
|
|
59
|
+
return spec.search.rank !== false && query.sort === spec.defaultSort;
|
|
60
|
+
}
|
|
61
|
+
/** Filter, sort, count and page in one pass. */
|
|
62
|
+
export function applyQuery(rows, spec, query) {
|
|
63
|
+
const passed = matches(rows, spec, query);
|
|
64
|
+
const sort = spec.sorts.find((s) => s.key === query.sort) ??
|
|
65
|
+
spec.sorts.find((s) => s.key === spec.defaultSort) ??
|
|
66
|
+
spec.sorts[0];
|
|
67
|
+
const byKey = sort ? compareBy(sort.by, query.dir) : null;
|
|
68
|
+
let sorted;
|
|
69
|
+
if (isRanked(spec, query)) {
|
|
70
|
+
// Score once per row, not once per comparison. Ties keep the list's own
|
|
71
|
+
// order, so equally good matches still read alphabetically (or newest
|
|
72
|
+
// first, or whatever the default is).
|
|
73
|
+
const scored = passed.map((row) => ({ row, score: searchScore(spec.search, row, query.q) }));
|
|
74
|
+
scored.sort((a, b) => b.score - a.score || (byKey ? byKey(a.row, b.row) : 0));
|
|
75
|
+
sorted = scored.map((s) => s.row);
|
|
76
|
+
}
|
|
77
|
+
else {
|
|
78
|
+
sorted = byKey ? [...passed].sort(byKey) : passed;
|
|
79
|
+
}
|
|
80
|
+
const page = pageOf(sorted.length, query.page, query.pageSize);
|
|
81
|
+
return {
|
|
82
|
+
rows: sorted.slice(page.from, page.to),
|
|
83
|
+
matched: passed.length,
|
|
84
|
+
total: rows.length,
|
|
85
|
+
page,
|
|
86
|
+
counts: facetCounts(rows, spec, query),
|
|
87
|
+
};
|
|
88
|
+
}
|
package/dist/facets.d.ts
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What you can narrow a list by.
|
|
3
|
+
*
|
|
4
|
+
* A survey of twelve repositories on 2026-09-11 found twelve incompatible
|
|
5
|
+
* filter-state shapes and no two alike. The thing they actually disagree about
|
|
6
|
+
* is not the data — it is what KIND of narrowing each field supports, and each
|
|
7
|
+
* repo rediscovered the kinds one at a time. This is the closed set, taken from
|
|
8
|
+
* what those repos already do:
|
|
9
|
+
*
|
|
10
|
+
* one pick a single value "kind = product"
|
|
11
|
+
* many pick several "status in (live, validating)"
|
|
12
|
+
* flag a boolean switch "has no site"
|
|
13
|
+
* range numeric between "price 10..50"
|
|
14
|
+
* ordinal a threshold on a scale "tier B or better"
|
|
15
|
+
*
|
|
16
|
+
* The sentinel for "no filter" is the EMPTY SELECTION, never a magic string.
|
|
17
|
+
* One repo used the translated label ("Alle") as its all-value, which makes
|
|
18
|
+
* filter identity depend on the reader's language — a German user and an
|
|
19
|
+
* English user filtering the same list got different results.
|
|
20
|
+
*/
|
|
21
|
+
/** The kinds of narrowing a field can support. */
|
|
22
|
+
export type FacetKind = "one" | "many" | "flag" | "range" | "ordinal";
|
|
23
|
+
/** How several selected values combine. `any` is union, `all` is intersection. */
|
|
24
|
+
export type FacetLogic = "any" | "all";
|
|
25
|
+
export type Facet<T> = {
|
|
26
|
+
/** URL parameter name. Short, stable, lowercase. */
|
|
27
|
+
key: string;
|
|
28
|
+
kind: FacetKind;
|
|
29
|
+
/**
|
|
30
|
+
* The comparable value(s) on a record. Returning an array makes a record
|
|
31
|
+
* match on any of them, which is what tags and themes need.
|
|
32
|
+
*/
|
|
33
|
+
value: (row: T) => string | string[] | number | boolean | null | undefined;
|
|
34
|
+
/**
|
|
35
|
+
* Permitted values, when the set is known. Anything else arriving in the URL
|
|
36
|
+
* is dropped rather than passed through: a filter nobody can produce from the
|
|
37
|
+
* UI is either a typo or someone probing, and neither deserves a query.
|
|
38
|
+
*/
|
|
39
|
+
options?: readonly string[];
|
|
40
|
+
/** `many` only — defaults to `any`. */
|
|
41
|
+
logic?: FacetLogic;
|
|
42
|
+
/** `ordinal` only — the scale, lowest first. Selection means "this or better". */
|
|
43
|
+
scale?: readonly string[];
|
|
44
|
+
};
|
|
45
|
+
/** Free-text search: which parts of a record the query is matched against. */
|
|
46
|
+
export type SearchSpec<T> = {
|
|
47
|
+
/**
|
|
48
|
+
* Every string worth matching, MOST IMPORTANT FIRST — the order is the
|
|
49
|
+
* ranking: a word found in the first field outranks the same word in the
|
|
50
|
+
* third. Empty strings and nulls are ignored.
|
|
51
|
+
*/
|
|
52
|
+
text: (row: T) => (string | null | undefined)[];
|
|
53
|
+
/**
|
|
54
|
+
* Rank results by relevance while a search is active and the reader has not
|
|
55
|
+
* picked a sort of their own (the sort is the spec's default). On unless set
|
|
56
|
+
* to false — a list whose order IS the content, a timeline say, opts out.
|
|
57
|
+
*/
|
|
58
|
+
rank?: boolean;
|
|
59
|
+
};
|
|
60
|
+
export type Sortable<T> = {
|
|
61
|
+
key: string;
|
|
62
|
+
/** Sort keys, applied in order until one separates the two records. */
|
|
63
|
+
by: ((row: T) => string | number | boolean | null | undefined)[];
|
|
64
|
+
label?: string;
|
|
65
|
+
};
|
|
66
|
+
export type ListSpec<T> = {
|
|
67
|
+
facets: readonly Facet<T>[];
|
|
68
|
+
search?: SearchSpec<T>;
|
|
69
|
+
sorts: readonly Sortable<T>[];
|
|
70
|
+
/** Sort key used when the URL names none. Must exist in `sorts`. */
|
|
71
|
+
defaultSort: string;
|
|
72
|
+
defaultDir?: "asc" | "desc";
|
|
73
|
+
defaultPageSize?: number;
|
|
74
|
+
};
|
|
75
|
+
/**
|
|
76
|
+
* Does one record pass one facet's selection?
|
|
77
|
+
*
|
|
78
|
+
* An empty selection always passes. That is the whole reason this returns true
|
|
79
|
+
* early: "no filter chosen" and "filter chosen that nothing matches" are
|
|
80
|
+
* different states, and conflating them is how a list silently empties itself.
|
|
81
|
+
*/
|
|
82
|
+
export declare function facetMatches<T>(facet: Facet<T>, row: T, selected: readonly string[]): boolean;
|
package/dist/facets.js
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What you can narrow a list by.
|
|
3
|
+
*
|
|
4
|
+
* A survey of twelve repositories on 2026-09-11 found twelve incompatible
|
|
5
|
+
* filter-state shapes and no two alike. The thing they actually disagree about
|
|
6
|
+
* is not the data — it is what KIND of narrowing each field supports, and each
|
|
7
|
+
* repo rediscovered the kinds one at a time. This is the closed set, taken from
|
|
8
|
+
* what those repos already do:
|
|
9
|
+
*
|
|
10
|
+
* one pick a single value "kind = product"
|
|
11
|
+
* many pick several "status in (live, validating)"
|
|
12
|
+
* flag a boolean switch "has no site"
|
|
13
|
+
* range numeric between "price 10..50"
|
|
14
|
+
* ordinal a threshold on a scale "tier B or better"
|
|
15
|
+
*
|
|
16
|
+
* The sentinel for "no filter" is the EMPTY SELECTION, never a magic string.
|
|
17
|
+
* One repo used the translated label ("Alle") as its all-value, which makes
|
|
18
|
+
* filter identity depend on the reader's language — a German user and an
|
|
19
|
+
* English user filtering the same list got different results.
|
|
20
|
+
*/
|
|
21
|
+
function asList(v) {
|
|
22
|
+
if (v === null || v === undefined)
|
|
23
|
+
return [];
|
|
24
|
+
if (Array.isArray(v))
|
|
25
|
+
return v.map(String);
|
|
26
|
+
return [String(v)];
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Does one record pass one facet's selection?
|
|
30
|
+
*
|
|
31
|
+
* An empty selection always passes. That is the whole reason this returns true
|
|
32
|
+
* early: "no filter chosen" and "filter chosen that nothing matches" are
|
|
33
|
+
* different states, and conflating them is how a list silently empties itself.
|
|
34
|
+
*/
|
|
35
|
+
export function facetMatches(facet, row, selected) {
|
|
36
|
+
if (selected.length === 0)
|
|
37
|
+
return true;
|
|
38
|
+
const raw = facet.value(row);
|
|
39
|
+
switch (facet.kind) {
|
|
40
|
+
case "flag": {
|
|
41
|
+
// Present in the selection means "the flag must be true". A flag is the
|
|
42
|
+
// only kind whose value is about the RECORD, not about a match.
|
|
43
|
+
const want = selected[0] !== "0" && selected[0] !== "false";
|
|
44
|
+
return Boolean(raw) === want;
|
|
45
|
+
}
|
|
46
|
+
case "one":
|
|
47
|
+
return asList(raw).some((v) => v === selected[0]);
|
|
48
|
+
case "many": {
|
|
49
|
+
const have = new Set(asList(raw));
|
|
50
|
+
return (facet.logic ?? "any") === "all"
|
|
51
|
+
? selected.every((s) => have.has(s))
|
|
52
|
+
: selected.some((s) => have.has(s));
|
|
53
|
+
}
|
|
54
|
+
case "range": {
|
|
55
|
+
// selected is [min, max]; either end may be blank, meaning unbounded.
|
|
56
|
+
const n = Number(raw);
|
|
57
|
+
if (!Number.isFinite(n))
|
|
58
|
+
return false;
|
|
59
|
+
const lo = selected[0] === "" || selected[0] === undefined ? -Infinity : Number(selected[0]);
|
|
60
|
+
const hi = selected[1] === "" || selected[1] === undefined ? Infinity : Number(selected[1]);
|
|
61
|
+
if (!Number.isFinite(lo) && lo !== -Infinity)
|
|
62
|
+
return true;
|
|
63
|
+
if (!Number.isFinite(hi) && hi !== Infinity)
|
|
64
|
+
return true;
|
|
65
|
+
return n >= lo && n <= hi;
|
|
66
|
+
}
|
|
67
|
+
case "ordinal": {
|
|
68
|
+
const scale = facet.scale ?? [];
|
|
69
|
+
const threshold = selected[0];
|
|
70
|
+
if (threshold === undefined)
|
|
71
|
+
return true;
|
|
72
|
+
const floor = scale.indexOf(threshold);
|
|
73
|
+
if (floor < 0)
|
|
74
|
+
return true; // an unknown threshold filters nothing
|
|
75
|
+
const at = scale.indexOf(asList(raw)[0] ?? "");
|
|
76
|
+
return at >= 0 && at >= floor;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* listkit — a list as a query.
|
|
3
|
+
*
|
|
4
|
+
* Filtering, sorting, searching and paging are the same problem everywhere and
|
|
5
|
+
* were solved separately everywhere: a survey of twelve repositories on
|
|
6
|
+
* 2026-09-11 found twelve incompatible filter-state shapes, ~34 hand-built URL
|
|
7
|
+
* builders, ~25 copies of "toggle a value in a set", ~11 debounces at five
|
|
8
|
+
* different delays, ~11 copies of `Math.ceil(total / pageSize)`, and four live
|
|
9
|
+
* bugs that a shared codec makes unreachable.
|
|
10
|
+
*
|
|
11
|
+
* What this ships: the DECISIONS. A closed set of facet kinds, a URL codec that
|
|
12
|
+
* copies rather than rebuilds, a comparator that puts missing values last, page
|
|
13
|
+
* arithmetic that cannot produce a negative offset, and the handful of one-line
|
|
14
|
+
* functions everyone rewrites.
|
|
15
|
+
*
|
|
16
|
+
* What this deliberately does not ship: markup, tokens, React, a search engine,
|
|
17
|
+
* or an HTTP client. Nine token vocabularies and six chip treatments were found
|
|
18
|
+
* among those same repos, several of them different on purpose. The fleet has
|
|
19
|
+
* already run the experiment where a shared renderer owns the markup: it
|
|
20
|
+
* reached two consumers out of twenty and shipped the same two defects to both,
|
|
21
|
+
* unfixable downstream because a consumer cannot patch markup it does not own.
|
|
22
|
+
* Centralize the rule; render it locally.
|
|
23
|
+
*/
|
|
24
|
+
export { facetMatches, type Facet, type FacetKind, type FacetLogic, type SearchSpec, type Sortable, type ListSpec, } from "./facets.js";
|
|
25
|
+
export { parseQuery, writeQuery, emptyQuery, isNarrowed, sameResultSet, PAGE_KEY, SIZE_KEY, SORT_KEY, DIR_KEY, TEXT_KEY, RELEVANCE_SORT, type ListQuery, type ParamsLike, type ParseOptions, } from "./query.js";
|
|
26
|
+
export { searchMatches, searchScore, searchTerms, normalise } from "./search.js";
|
|
27
|
+
export { applyQuery, matches, facetCounts, isRanked, type ListResult } from "./apply.js";
|
|
28
|
+
export { compareBy, nextDirection, type SortKey, type Direction } from "./sort.js";
|
|
29
|
+
export { pageOf, pageWindow, type PageInfo } from "./page.js";
|
|
30
|
+
export { toggleInSet, toggleFlag, escapeLike, likeContains, debounce, latest } from "./values.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* listkit — a list as a query.
|
|
3
|
+
*
|
|
4
|
+
* Filtering, sorting, searching and paging are the same problem everywhere and
|
|
5
|
+
* were solved separately everywhere: a survey of twelve repositories on
|
|
6
|
+
* 2026-09-11 found twelve incompatible filter-state shapes, ~34 hand-built URL
|
|
7
|
+
* builders, ~25 copies of "toggle a value in a set", ~11 debounces at five
|
|
8
|
+
* different delays, ~11 copies of `Math.ceil(total / pageSize)`, and four live
|
|
9
|
+
* bugs that a shared codec makes unreachable.
|
|
10
|
+
*
|
|
11
|
+
* What this ships: the DECISIONS. A closed set of facet kinds, a URL codec that
|
|
12
|
+
* copies rather than rebuilds, a comparator that puts missing values last, page
|
|
13
|
+
* arithmetic that cannot produce a negative offset, and the handful of one-line
|
|
14
|
+
* functions everyone rewrites.
|
|
15
|
+
*
|
|
16
|
+
* What this deliberately does not ship: markup, tokens, React, a search engine,
|
|
17
|
+
* or an HTTP client. Nine token vocabularies and six chip treatments were found
|
|
18
|
+
* among those same repos, several of them different on purpose. The fleet has
|
|
19
|
+
* already run the experiment where a shared renderer owns the markup: it
|
|
20
|
+
* reached two consumers out of twenty and shipped the same two defects to both,
|
|
21
|
+
* unfixable downstream because a consumer cannot patch markup it does not own.
|
|
22
|
+
* Centralize the rule; render it locally.
|
|
23
|
+
*/
|
|
24
|
+
export { facetMatches, } from "./facets.js";
|
|
25
|
+
export { parseQuery, writeQuery, emptyQuery, isNarrowed, sameResultSet, PAGE_KEY, SIZE_KEY, SORT_KEY, DIR_KEY, TEXT_KEY, RELEVANCE_SORT, } from "./query.js";
|
|
26
|
+
export { searchMatches, searchScore, searchTerms, normalise } from "./search.js";
|
|
27
|
+
export { applyQuery, matches, facetCounts, isRanked } from "./apply.js";
|
|
28
|
+
export { compareBy, nextDirection } from "./sort.js";
|
|
29
|
+
export { pageOf, pageWindow } from "./page.js";
|
|
30
|
+
export { toggleInSet, toggleFlag, escapeLike, likeContains, debounce, latest } from "./values.js";
|
package/dist/page.d.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Paging arithmetic, done once.
|
|
3
|
+
*
|
|
4
|
+
* `Math.ceil(total / pageSize)` appeared about eleven times across the surveyed
|
|
5
|
+
* repos, three times in one of them. The arithmetic is trivial; the edges are
|
|
6
|
+
* not, and the edges are where the bugs were:
|
|
7
|
+
*
|
|
8
|
+
* - `parseInt(searchParams.page ?? "1")` with no clamp, so `?page=0` produced
|
|
9
|
+
* `offset = -25` and the query threw;
|
|
10
|
+
* - a total of zero yielding zero pages, so the UI rendered "page 1 of 0";
|
|
11
|
+
* - a page number past the end returning an empty slice with no way back,
|
|
12
|
+
* because the control that would have taken the reader to page 1 was itself
|
|
13
|
+
* rendered from the out-of-range number.
|
|
14
|
+
*
|
|
15
|
+
* So `pageOf` always returns a page that exists, and says when it had to move
|
|
16
|
+
* the reader — a caller that wants to correct the URL can see that it should.
|
|
17
|
+
*/
|
|
18
|
+
export type PageInfo = {
|
|
19
|
+
/** The page actually being shown, 1-based and always within range. */
|
|
20
|
+
page: number;
|
|
21
|
+
pageSize: number;
|
|
22
|
+
total: number;
|
|
23
|
+
totalPages: number;
|
|
24
|
+
/** Slice bounds, for `array.slice(from, to)`. */
|
|
25
|
+
from: number;
|
|
26
|
+
to: number;
|
|
27
|
+
/** 1-based inclusive range of items shown, for "showing 21–40 of 97". */
|
|
28
|
+
firstItem: number;
|
|
29
|
+
lastItem: number;
|
|
30
|
+
hasPrev: boolean;
|
|
31
|
+
hasNext: boolean;
|
|
32
|
+
/** The requested page did not exist and the reader was moved to this one. */
|
|
33
|
+
clamped: boolean;
|
|
34
|
+
};
|
|
35
|
+
export declare function pageOf(total: number, requested: number, pageSize: number): PageInfo;
|
|
36
|
+
/**
|
|
37
|
+
* The page numbers to render, with gaps collapsed.
|
|
38
|
+
*
|
|
39
|
+
* `null` is a gap. Returning it rather than a string keeps the ellipsis a
|
|
40
|
+
* rendering decision, which is the caller's to make.
|
|
41
|
+
*/
|
|
42
|
+
export declare function pageWindow(page: number, totalPages: number, span?: number): (number | null)[];
|
package/dist/page.js
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Paging arithmetic, done once.
|
|
3
|
+
*
|
|
4
|
+
* `Math.ceil(total / pageSize)` appeared about eleven times across the surveyed
|
|
5
|
+
* repos, three times in one of them. The arithmetic is trivial; the edges are
|
|
6
|
+
* not, and the edges are where the bugs were:
|
|
7
|
+
*
|
|
8
|
+
* - `parseInt(searchParams.page ?? "1")` with no clamp, so `?page=0` produced
|
|
9
|
+
* `offset = -25` and the query threw;
|
|
10
|
+
* - a total of zero yielding zero pages, so the UI rendered "page 1 of 0";
|
|
11
|
+
* - a page number past the end returning an empty slice with no way back,
|
|
12
|
+
* because the control that would have taken the reader to page 1 was itself
|
|
13
|
+
* rendered from the out-of-range number.
|
|
14
|
+
*
|
|
15
|
+
* So `pageOf` always returns a page that exists, and says when it had to move
|
|
16
|
+
* the reader — a caller that wants to correct the URL can see that it should.
|
|
17
|
+
*/
|
|
18
|
+
export function pageOf(total, requested, pageSize) {
|
|
19
|
+
const size = Math.max(1, Math.floor(pageSize) || 1);
|
|
20
|
+
const count = Math.max(0, Math.floor(total) || 0);
|
|
21
|
+
// An empty list still has one page — the one that says there is nothing.
|
|
22
|
+
const totalPages = Math.max(1, Math.ceil(count / size));
|
|
23
|
+
const wanted = Math.max(1, Math.floor(requested) || 1);
|
|
24
|
+
const page = Math.min(wanted, totalPages);
|
|
25
|
+
const from = (page - 1) * size;
|
|
26
|
+
const to = Math.min(from + size, count);
|
|
27
|
+
return {
|
|
28
|
+
page,
|
|
29
|
+
pageSize: size,
|
|
30
|
+
total: count,
|
|
31
|
+
totalPages,
|
|
32
|
+
from,
|
|
33
|
+
to,
|
|
34
|
+
firstItem: count === 0 ? 0 : from + 1,
|
|
35
|
+
lastItem: to,
|
|
36
|
+
hasPrev: page > 1,
|
|
37
|
+
hasNext: page < totalPages,
|
|
38
|
+
clamped: page !== wanted,
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* The page numbers to render, with gaps collapsed.
|
|
43
|
+
*
|
|
44
|
+
* `null` is a gap. Returning it rather than a string keeps the ellipsis a
|
|
45
|
+
* rendering decision, which is the caller's to make.
|
|
46
|
+
*/
|
|
47
|
+
export function pageWindow(page, totalPages, span = 1) {
|
|
48
|
+
const keep = new Set([1, totalPages]);
|
|
49
|
+
for (let i = page - span; i <= page + span; i++)
|
|
50
|
+
if (i >= 1 && i <= totalPages)
|
|
51
|
+
keep.add(i);
|
|
52
|
+
const sorted = [...keep].sort((a, b) => a - b);
|
|
53
|
+
const out = [];
|
|
54
|
+
let previous = 0;
|
|
55
|
+
for (const n of sorted) {
|
|
56
|
+
if (previous && n - previous > 1)
|
|
57
|
+
out.push(null);
|
|
58
|
+
out.push(n);
|
|
59
|
+
previous = n;
|
|
60
|
+
}
|
|
61
|
+
return out;
|
|
62
|
+
}
|
package/dist/query.d.ts
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The query, and its round trip through a URL.
|
|
3
|
+
*
|
|
4
|
+
* Across the surveyed repos there were roughly thirty-four hand-built URL
|
|
5
|
+
* builders, and four live bugs among them that this codec exists to make
|
|
6
|
+
* impossible:
|
|
7
|
+
*
|
|
8
|
+
* - one built `new URLSearchParams()` from scratch, so applying a preset
|
|
9
|
+
* silently wiped the reader's active search and five other facets;
|
|
10
|
+
* - one changed a date range without clearing `page`, so the reader landed on
|
|
11
|
+
* page 4 of a two-page result and saw nothing;
|
|
12
|
+
* - one preserved exactly three params by name, so every param added later had
|
|
13
|
+
* to be remembered in six separate template strings;
|
|
14
|
+
* - one used push rather than replace for a debounced search box, so the back
|
|
15
|
+
* button walked backwards through every intermediate spelling of the word.
|
|
16
|
+
*
|
|
17
|
+
* So: always copy the params you were given, always drop `page` when the result
|
|
18
|
+
* set changes, and never write a value that equals the default — a URL should
|
|
19
|
+
* carry what the reader chose, not a restatement of what they did not.
|
|
20
|
+
*/
|
|
21
|
+
import type { ListSpec } from "./facets.js";
|
|
22
|
+
export type ListQuery = {
|
|
23
|
+
/** Free text. Empty means no text filter. */
|
|
24
|
+
q: string;
|
|
25
|
+
/** facet key → selected values. An absent key and an empty array are the same. */
|
|
26
|
+
facets: Record<string, string[]>;
|
|
27
|
+
sort: string;
|
|
28
|
+
dir: "asc" | "desc";
|
|
29
|
+
/** 1-based. Clamped on parse: `?page=0` must never become a negative offset. */
|
|
30
|
+
page: number;
|
|
31
|
+
pageSize: number;
|
|
32
|
+
};
|
|
33
|
+
export declare const PAGE_KEY = "page";
|
|
34
|
+
export declare const SIZE_KEY = "size";
|
|
35
|
+
export declare const SORT_KEY = "sort";
|
|
36
|
+
export declare const DIR_KEY = "dir";
|
|
37
|
+
export declare const TEXT_KEY = "q";
|
|
38
|
+
/**
|
|
39
|
+
* The sort key that means "best match first". Accepted on any spec with a
|
|
40
|
+
* search; it needs no entry in `sorts` and falls back to the default sort when
|
|
41
|
+
* there is no text to rank by.
|
|
42
|
+
*/
|
|
43
|
+
export declare const RELEVANCE_SORT = "relevance";
|
|
44
|
+
/** Params as given by a router: a real URLSearchParams or Next's plain record. */
|
|
45
|
+
export type ParamsLike = URLSearchParams | Record<string, string | string[] | undefined>;
|
|
46
|
+
export type ParseOptions = {
|
|
47
|
+
maxPageSize?: number;
|
|
48
|
+
};
|
|
49
|
+
/**
|
|
50
|
+
* Read a query out of URL params, keeping only what the spec permits.
|
|
51
|
+
*
|
|
52
|
+
* Values outside a facet's declared `options` are dropped. One surveyed repo
|
|
53
|
+
* cast `searchParams.sort` straight into a union with no runtime check and fell
|
|
54
|
+
* through to a default, which meant a mistyped sort looked like it worked.
|
|
55
|
+
*/
|
|
56
|
+
export declare function parseQuery<T>(params: ParamsLike, spec: ListSpec<T>, opts?: ParseOptions): ListQuery;
|
|
57
|
+
/** True when two queries would produce the same rows — page and size aside. */
|
|
58
|
+
export declare function sameResultSet(a: ListQuery, b: ListQuery): boolean;
|
|
59
|
+
/**
|
|
60
|
+
* Write a query back over the params the reader arrived with.
|
|
61
|
+
*
|
|
62
|
+
* `current` is copied, never replaced, so params this list knows nothing about
|
|
63
|
+
* — a locale, a referrer, a feature flag — survive. When the result set
|
|
64
|
+
* changes, `page` is dropped: page 4 of the old filter is not page 4 of the new
|
|
65
|
+
* one, and the reader would land on an empty list they did not ask for.
|
|
66
|
+
*/
|
|
67
|
+
export declare function writeQuery<T>(current: ParamsLike, next: ListQuery, spec: ListSpec<T>, previous?: ListQuery): URLSearchParams;
|
|
68
|
+
/** The query with everything cleared but the reader's page size. */
|
|
69
|
+
export declare function emptyQuery<T>(spec: ListSpec<T>): ListQuery;
|
|
70
|
+
/** Has the reader narrowed anything? Drives "clear all" and the empty state. */
|
|
71
|
+
export declare function isNarrowed(query: ListQuery): boolean;
|
package/dist/query.js
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
export const PAGE_KEY = "page";
|
|
2
|
+
export const SIZE_KEY = "size";
|
|
3
|
+
export const SORT_KEY = "sort";
|
|
4
|
+
export const DIR_KEY = "dir";
|
|
5
|
+
export const TEXT_KEY = "q";
|
|
6
|
+
/**
|
|
7
|
+
* The sort key that means "best match first". Accepted on any spec with a
|
|
8
|
+
* search; it needs no entry in `sorts` and falls back to the default sort when
|
|
9
|
+
* there is no text to rank by.
|
|
10
|
+
*/
|
|
11
|
+
export const RELEVANCE_SORT = "relevance";
|
|
12
|
+
function readAll(params, key) {
|
|
13
|
+
if (params instanceof URLSearchParams)
|
|
14
|
+
return params.getAll(key).flatMap((v) => v.split(","));
|
|
15
|
+
const v = params[key];
|
|
16
|
+
if (v === undefined)
|
|
17
|
+
return [];
|
|
18
|
+
return (Array.isArray(v) ? v : [v]).flatMap((s) => String(s).split(","));
|
|
19
|
+
}
|
|
20
|
+
function clampInt(raw, fallback, min, max) {
|
|
21
|
+
const n = Number.parseInt(raw ?? "", 10);
|
|
22
|
+
if (!Number.isFinite(n))
|
|
23
|
+
return fallback;
|
|
24
|
+
return Math.min(max, Math.max(min, n));
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Read a query out of URL params, keeping only what the spec permits.
|
|
28
|
+
*
|
|
29
|
+
* Values outside a facet's declared `options` are dropped. One surveyed repo
|
|
30
|
+
* cast `searchParams.sort` straight into a union with no runtime check and fell
|
|
31
|
+
* through to a default, which meant a mistyped sort looked like it worked.
|
|
32
|
+
*/
|
|
33
|
+
export function parseQuery(params, spec, opts = {}) {
|
|
34
|
+
const maxSize = opts.maxPageSize ?? 200;
|
|
35
|
+
const facets = {};
|
|
36
|
+
for (const f of spec.facets) {
|
|
37
|
+
const wanted = readAll(params, f.key)
|
|
38
|
+
.map((v) => v.trim())
|
|
39
|
+
.filter(Boolean);
|
|
40
|
+
const allowed = f.options
|
|
41
|
+
? wanted.filter((v) => f.options.includes(v))
|
|
42
|
+
: wanted;
|
|
43
|
+
// `one` and `ordinal` take a single value; extra ones are noise, not intent.
|
|
44
|
+
const capped = f.kind === "one" || f.kind === "ordinal" ? allowed.slice(0, 1) : allowed;
|
|
45
|
+
if (capped.length)
|
|
46
|
+
facets[f.key] = capped;
|
|
47
|
+
}
|
|
48
|
+
const sortRaw = readAll(params, SORT_KEY)[0];
|
|
49
|
+
const sort = sortRaw !== undefined &&
|
|
50
|
+
(spec.sorts.some((s) => s.key === sortRaw) || (sortRaw === RELEVANCE_SORT && !!spec.search))
|
|
51
|
+
? sortRaw
|
|
52
|
+
: spec.defaultSort;
|
|
53
|
+
const dirRaw = readAll(params, DIR_KEY)[0];
|
|
54
|
+
const dir = dirRaw === "asc" || dirRaw === "desc" ? dirRaw : (spec.defaultDir ?? "asc");
|
|
55
|
+
return {
|
|
56
|
+
q: (readAll(params, TEXT_KEY)[0] ?? "").trim(),
|
|
57
|
+
facets,
|
|
58
|
+
sort,
|
|
59
|
+
dir,
|
|
60
|
+
page: clampInt(readAll(params, PAGE_KEY)[0], 1, 1, Number.MAX_SAFE_INTEGER),
|
|
61
|
+
pageSize: clampInt(readAll(params, SIZE_KEY)[0], spec.defaultPageSize ?? 25, 1, maxSize),
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
/** True when two queries would produce the same rows — page and size aside. */
|
|
65
|
+
export function sameResultSet(a, b) {
|
|
66
|
+
if (a.q !== b.q || a.sort !== b.sort || a.dir !== b.dir)
|
|
67
|
+
return false;
|
|
68
|
+
const keys = new Set([...Object.keys(a.facets), ...Object.keys(b.facets)]);
|
|
69
|
+
for (const k of keys) {
|
|
70
|
+
const x = a.facets[k] ?? [];
|
|
71
|
+
const y = b.facets[k] ?? [];
|
|
72
|
+
if (x.length !== y.length || x.some((v, i) => v !== y[i]))
|
|
73
|
+
return false;
|
|
74
|
+
}
|
|
75
|
+
return true;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Write a query back over the params the reader arrived with.
|
|
79
|
+
*
|
|
80
|
+
* `current` is copied, never replaced, so params this list knows nothing about
|
|
81
|
+
* — a locale, a referrer, a feature flag — survive. When the result set
|
|
82
|
+
* changes, `page` is dropped: page 4 of the old filter is not page 4 of the new
|
|
83
|
+
* one, and the reader would land on an empty list they did not ask for.
|
|
84
|
+
*/
|
|
85
|
+
export function writeQuery(current, next, spec, previous) {
|
|
86
|
+
const out = current instanceof URLSearchParams
|
|
87
|
+
? new URLSearchParams(current)
|
|
88
|
+
: new URLSearchParams(Object.entries(current).flatMap(([k, v]) => v === undefined
|
|
89
|
+
? []
|
|
90
|
+
: (Array.isArray(v) ? v : [v]).map((s) => [k, String(s)])));
|
|
91
|
+
const set = (key, value) => {
|
|
92
|
+
if (value === null || value === "")
|
|
93
|
+
out.delete(key);
|
|
94
|
+
else
|
|
95
|
+
out.set(key, value);
|
|
96
|
+
};
|
|
97
|
+
set(TEXT_KEY, next.q || null);
|
|
98
|
+
for (const f of spec.facets) {
|
|
99
|
+
const sel = next.facets[f.key] ?? [];
|
|
100
|
+
set(f.key, sel.length ? sel.join(",") : null);
|
|
101
|
+
}
|
|
102
|
+
set(SORT_KEY, next.sort === spec.defaultSort ? null : next.sort);
|
|
103
|
+
set(DIR_KEY, next.dir === (spec.defaultDir ?? "asc") ? null : next.dir);
|
|
104
|
+
set(SIZE_KEY, next.pageSize === (spec.defaultPageSize ?? 25) ? null : String(next.pageSize));
|
|
105
|
+
const resultSetChanged = previous ? !sameResultSet(previous, next) : false;
|
|
106
|
+
set(PAGE_KEY, resultSetChanged || next.page <= 1 ? null : String(next.page));
|
|
107
|
+
return out;
|
|
108
|
+
}
|
|
109
|
+
/** The query with everything cleared but the reader's page size. */
|
|
110
|
+
export function emptyQuery(spec) {
|
|
111
|
+
return {
|
|
112
|
+
q: "",
|
|
113
|
+
facets: {},
|
|
114
|
+
sort: spec.defaultSort,
|
|
115
|
+
dir: spec.defaultDir ?? "asc",
|
|
116
|
+
page: 1,
|
|
117
|
+
pageSize: spec.defaultPageSize ?? 25,
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
/** Has the reader narrowed anything? Drives "clear all" and the empty state. */
|
|
121
|
+
export function isNarrowed(query) {
|
|
122
|
+
return query.q !== "" || Object.values(query.facets).some((v) => v.length > 0);
|
|
123
|
+
}
|
package/dist/search.d.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Free-text search: which records match, and in what order to show them.
|
|
3
|
+
*
|
|
4
|
+
* v0.1 matched the whole query as one substring. That failed the two ways
|
|
5
|
+
* people actually type:
|
|
6
|
+
*
|
|
7
|
+
* - word order. "bike sell" did not find "Sell my old bike", because the
|
|
8
|
+
* phrase "bike sell" appears nowhere. Every word must appear somewhere; the
|
|
9
|
+
* order is the reader's, not the record's.
|
|
10
|
+
* - accents. "zurich" did not find "Zürich", and "strasse" did not find
|
|
11
|
+
* "Straße" — on platforms whose readers type on whatever keyboard is in
|
|
12
|
+
* front of them. Text is folded before comparing, on both sides.
|
|
13
|
+
*
|
|
14
|
+
* And it did not rank. A match on the title and a match three paragraphs into a
|
|
15
|
+
* description sorted by name alike, so the record the reader meant could land
|
|
16
|
+
* on page two. `searchScore` ranks by WHERE a word matched (the spec lists the
|
|
17
|
+
* fields most important first) and HOW well (the whole field, a field's start,
|
|
18
|
+
* a word's start, anywhere inside).
|
|
19
|
+
*
|
|
20
|
+
* Still no search engine: no stemming, no typo tolerance, no index. Those
|
|
21
|
+
* belong to a database or a dedicated engine; this is the rule an in-memory
|
|
22
|
+
* list and a SQL builder can share.
|
|
23
|
+
*/
|
|
24
|
+
import type { SearchSpec } from "./facets.js";
|
|
25
|
+
/**
|
|
26
|
+
* Casefold, strip accents, collapse whitespace. " Zürich Straße " and
|
|
27
|
+
* "zurich strasse" become the same string. ß has no decomposition, so it is
|
|
28
|
+
* mapped by hand, the same way German itself spells it without the letter.
|
|
29
|
+
*/
|
|
30
|
+
export declare function normalise(v: string): string;
|
|
31
|
+
/**
|
|
32
|
+
* The words of a query, normalised and de-duplicated. A SQL builder applies
|
|
33
|
+
* one `likeContains` per term, ANDed, to agree with `searchMatches`.
|
|
34
|
+
*/
|
|
35
|
+
export declare function searchTerms(q: string): string[];
|
|
36
|
+
/** Does every word of the query appear in at least one of the record's fields? */
|
|
37
|
+
export declare function searchMatches<T>(spec: SearchSpec<T> | undefined, row: T, q: string): boolean;
|
|
38
|
+
/**
|
|
39
|
+
* How well a record matches, higher first; 0 when it does not match at all.
|
|
40
|
+
*
|
|
41
|
+
* Each term scores its best field, weighted by that field's position in
|
|
42
|
+
* `spec.text` (first field 1, second 1/2, third 1/3 …), and the whole query
|
|
43
|
+
* found as a phrase earns a bonus — so "old bike" ranks "Old bike for sale"
|
|
44
|
+
* above "Bike, old frame".
|
|
45
|
+
*/
|
|
46
|
+
export declare function searchScore<T>(spec: SearchSpec<T> | undefined, row: T, q: string): number;
|
package/dist/search.js
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Casefold, strip accents, collapse whitespace. " Zürich Straße " and
|
|
3
|
+
* "zurich strasse" become the same string. ß has no decomposition, so it is
|
|
4
|
+
* mapped by hand, the same way German itself spells it without the letter.
|
|
5
|
+
*/
|
|
6
|
+
export function normalise(v) {
|
|
7
|
+
return v
|
|
8
|
+
.normalize("NFKD")
|
|
9
|
+
.replace(/\p{M}+/gu, "")
|
|
10
|
+
.replace(/ß/g, "ss")
|
|
11
|
+
.toLowerCase()
|
|
12
|
+
.trim()
|
|
13
|
+
.replace(/\s+/g, " ");
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* The words of a query, normalised and de-duplicated. A SQL builder applies
|
|
17
|
+
* one `likeContains` per term, ANDed, to agree with `searchMatches`.
|
|
18
|
+
*/
|
|
19
|
+
export function searchTerms(q) {
|
|
20
|
+
return [...new Set(normalise(q).split(" ").filter(Boolean))];
|
|
21
|
+
}
|
|
22
|
+
function fields(spec, row) {
|
|
23
|
+
return spec.text(row).map((v) => (v ? normalise(v) : ""));
|
|
24
|
+
}
|
|
25
|
+
/** Does every word of the query appear in at least one of the record's fields? */
|
|
26
|
+
export function searchMatches(spec, row, q) {
|
|
27
|
+
const terms = searchTerms(q);
|
|
28
|
+
if (!terms.length || !spec)
|
|
29
|
+
return true;
|
|
30
|
+
const text = fields(spec, row).filter(Boolean);
|
|
31
|
+
return terms.every((t) => text.some((f) => f.includes(t)));
|
|
32
|
+
}
|
|
33
|
+
const startsWord = (field, term) => field.startsWith(term) || field.includes(` ${term}`);
|
|
34
|
+
/** How well one term matches one field: 0 (absent) to 4 (the whole field). */
|
|
35
|
+
function quality(field, term) {
|
|
36
|
+
if (!field || !field.includes(term))
|
|
37
|
+
return 0;
|
|
38
|
+
if (field === term)
|
|
39
|
+
return 4;
|
|
40
|
+
if (field.startsWith(term))
|
|
41
|
+
return 3;
|
|
42
|
+
if (startsWord(field, term))
|
|
43
|
+
return 2;
|
|
44
|
+
return 1;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* How well a record matches, higher first; 0 when it does not match at all.
|
|
48
|
+
*
|
|
49
|
+
* Each term scores its best field, weighted by that field's position in
|
|
50
|
+
* `spec.text` (first field 1, second 1/2, third 1/3 …), and the whole query
|
|
51
|
+
* found as a phrase earns a bonus — so "old bike" ranks "Old bike for sale"
|
|
52
|
+
* above "Bike, old frame".
|
|
53
|
+
*/
|
|
54
|
+
export function searchScore(spec, row, q) {
|
|
55
|
+
const terms = searchTerms(q);
|
|
56
|
+
if (!terms.length || !spec)
|
|
57
|
+
return 0;
|
|
58
|
+
const text = fields(spec, row);
|
|
59
|
+
let score = 0;
|
|
60
|
+
for (const term of terms) {
|
|
61
|
+
let best = 0;
|
|
62
|
+
text.forEach((field, i) => {
|
|
63
|
+
best = Math.max(best, quality(field, term) / (i + 1));
|
|
64
|
+
});
|
|
65
|
+
if (best === 0)
|
|
66
|
+
return 0;
|
|
67
|
+
score += best;
|
|
68
|
+
}
|
|
69
|
+
const phrase = terms.join(" ");
|
|
70
|
+
if (terms.length > 1) {
|
|
71
|
+
const at = text.findIndex((f) => f.includes(phrase));
|
|
72
|
+
if (at >= 0)
|
|
73
|
+
score += 2 / (at + 1);
|
|
74
|
+
}
|
|
75
|
+
return score;
|
|
76
|
+
}
|
package/dist/sort.d.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Ordering by several keys at once.
|
|
3
|
+
*
|
|
4
|
+
* The survey found about fourteen hand-written multi-key comparators, chained
|
|
5
|
+
* with `||` and each rediscovering the same two decisions: how to break a tie,
|
|
6
|
+
* and where to put a missing value. Nobody agreed on the second. Nulls that
|
|
7
|
+
* sort first push every incomplete record to the top of a list, which is
|
|
8
|
+
* exactly the opposite of what a reader wants from "sort by date".
|
|
9
|
+
*
|
|
10
|
+
* So: missing values always sort LAST, in both directions. A record with no
|
|
11
|
+
* date is not the oldest record; it is a record with no date, and it belongs at
|
|
12
|
+
* the bottom whichever way the arrow points.
|
|
13
|
+
*/
|
|
14
|
+
export type SortKey<T> = (row: T) => string | number | boolean | null | undefined;
|
|
15
|
+
export type Direction = "asc" | "desc";
|
|
16
|
+
/**
|
|
17
|
+
* A comparator over several keys, first key wins, later keys break ties.
|
|
18
|
+
*
|
|
19
|
+
* `dir` applies to every key. Where a list needs a fixed first key and a
|
|
20
|
+
* flippable second — "always show attention first, then by name" — express the
|
|
21
|
+
* fixed part as a boolean key, which coerces to 0/1 and orders stably.
|
|
22
|
+
*/
|
|
23
|
+
export declare function compareBy<T>(keys: readonly SortKey<T>[], dir?: Direction, locales?: string | string[]): (a: T, b: T) => number;
|
|
24
|
+
/** The direction a header should switch to when clicked. */
|
|
25
|
+
export declare function nextDirection(activeKey: string, clickedKey: string, current: Direction): Direction;
|
package/dist/sort.js
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Ordering by several keys at once.
|
|
3
|
+
*
|
|
4
|
+
* The survey found about fourteen hand-written multi-key comparators, chained
|
|
5
|
+
* with `||` and each rediscovering the same two decisions: how to break a tie,
|
|
6
|
+
* and where to put a missing value. Nobody agreed on the second. Nulls that
|
|
7
|
+
* sort first push every incomplete record to the top of a list, which is
|
|
8
|
+
* exactly the opposite of what a reader wants from "sort by date".
|
|
9
|
+
*
|
|
10
|
+
* So: missing values always sort LAST, in both directions. A record with no
|
|
11
|
+
* date is not the oldest record; it is a record with no date, and it belongs at
|
|
12
|
+
* the bottom whichever way the arrow points.
|
|
13
|
+
*/
|
|
14
|
+
const MISSING = Symbol("missing");
|
|
15
|
+
function coerce(v) {
|
|
16
|
+
if (v === null || v === undefined)
|
|
17
|
+
return MISSING;
|
|
18
|
+
if (typeof v === "boolean")
|
|
19
|
+
return v ? 1 : 0;
|
|
20
|
+
if (typeof v === "number")
|
|
21
|
+
return Number.isFinite(v) ? v : MISSING;
|
|
22
|
+
const s = v.trim();
|
|
23
|
+
return s === "" ? MISSING : s;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Compare two values of one key. Strings compare with `localeCompare` so that
|
|
27
|
+
* accented names land where a reader expects rather than where their code
|
|
28
|
+
* points fall.
|
|
29
|
+
*/
|
|
30
|
+
function compareOne(a, b, dir, locales) {
|
|
31
|
+
const x = coerce(a);
|
|
32
|
+
const y = coerce(b);
|
|
33
|
+
// Missing is not a value to be ordered — it is the absence of one, and it
|
|
34
|
+
// goes last regardless of direction. Hence this runs BEFORE the flip.
|
|
35
|
+
if (x === MISSING && y === MISSING)
|
|
36
|
+
return 0;
|
|
37
|
+
if (x === MISSING)
|
|
38
|
+
return 1;
|
|
39
|
+
if (y === MISSING)
|
|
40
|
+
return -1;
|
|
41
|
+
let cmp;
|
|
42
|
+
if (typeof x === "number" && typeof y === "number")
|
|
43
|
+
cmp = x - y;
|
|
44
|
+
else
|
|
45
|
+
cmp = String(x).localeCompare(String(y), locales, { numeric: true, sensitivity: "base" });
|
|
46
|
+
return dir === "desc" ? -cmp : cmp;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* A comparator over several keys, first key wins, later keys break ties.
|
|
50
|
+
*
|
|
51
|
+
* `dir` applies to every key. Where a list needs a fixed first key and a
|
|
52
|
+
* flippable second — "always show attention first, then by name" — express the
|
|
53
|
+
* fixed part as a boolean key, which coerces to 0/1 and orders stably.
|
|
54
|
+
*/
|
|
55
|
+
export function compareBy(keys, dir = "asc", locales) {
|
|
56
|
+
return (a, b) => {
|
|
57
|
+
for (const key of keys) {
|
|
58
|
+
const cmp = compareOne(key(a), key(b), dir, locales);
|
|
59
|
+
if (cmp !== 0)
|
|
60
|
+
return cmp;
|
|
61
|
+
}
|
|
62
|
+
return 0;
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
/** The direction a header should switch to when clicked. */
|
|
66
|
+
export function nextDirection(activeKey, clickedKey, current) {
|
|
67
|
+
return activeKey === clickedKey && current === "asc" ? "desc" : "asc";
|
|
68
|
+
}
|
package/dist/values.d.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The small operations every list rewrites.
|
|
3
|
+
*
|
|
4
|
+
* `toggleInSet` was found about twenty-five times across twelve repositories,
|
|
5
|
+
* in two encodings, and two of the copies were character-for-character
|
|
6
|
+
* identical in repos that share no code. One repo wrote the same three-line
|
|
7
|
+
* body eight times for eight facets, plus eleven more for its boolean flags.
|
|
8
|
+
* That is roughly a hundred and twenty lines in one file expressing one idea.
|
|
9
|
+
*
|
|
10
|
+
* `escapeLike` is the sharper case: three repos escape `%` and `_` before
|
|
11
|
+
* putting a reader's text into a SQL LIKE, and four do not. In those four,
|
|
12
|
+
* typing a single underscore matches every row.
|
|
13
|
+
*/
|
|
14
|
+
/** Add a value if absent, remove it if present. Order is preserved. */
|
|
15
|
+
export declare function toggleInSet(values: readonly string[], value: string): string[];
|
|
16
|
+
/** A flag's two states, as the codec writes them: `["1"]` on, `[]` off. */
|
|
17
|
+
export declare function toggleFlag(values: readonly string[]): string[];
|
|
18
|
+
/**
|
|
19
|
+
* Escape a reader's text for a SQL `LIKE`/`ILIKE` pattern.
|
|
20
|
+
*
|
|
21
|
+
* `%` and `_` are wildcards there. Unescaped, a search for "a_b" matches "axb",
|
|
22
|
+
* and a search for "%" matches every row in the table — which reads to the
|
|
23
|
+
* reader as a filter that does nothing. The backslash must go first or it
|
|
24
|
+
* escapes the escapes.
|
|
25
|
+
*/
|
|
26
|
+
export declare function escapeLike(value: string): string;
|
|
27
|
+
/** `escapeLike`, wrapped for a contains match. */
|
|
28
|
+
export declare function likeContains(value: string): string;
|
|
29
|
+
/**
|
|
30
|
+
* Call `fn` only once the caller has stopped for `ms`.
|
|
31
|
+
*
|
|
32
|
+
* Eleven hand-rolled copies, five different delays, and — more importantly —
|
|
33
|
+
* only three of the twelve repos also guarded against a slow earlier response
|
|
34
|
+
* overwriting a fast later one. `debounce` cannot fix that race on its own, so
|
|
35
|
+
* `latest` below does, and they are exported together to make the pair obvious.
|
|
36
|
+
*/
|
|
37
|
+
export declare function debounce<A extends unknown[]>(fn: (...args: A) => void, ms: number): ((...args: A) => void) & {
|
|
38
|
+
cancel: () => void;
|
|
39
|
+
};
|
|
40
|
+
/**
|
|
41
|
+
* Wrap an async function so only the most recent call can resolve.
|
|
42
|
+
*
|
|
43
|
+
* Without this, typing "ab" then "abc" can render the results for "ab" if the
|
|
44
|
+
* first request happens to be slower — the reader sees results that do not
|
|
45
|
+
* match the box they are looking at, and nothing in the UI admits it.
|
|
46
|
+
*/
|
|
47
|
+
export declare function latest<A extends unknown[], R>(fn: (...args: A) => Promise<R>): (...args: A) => Promise<R | undefined>;
|
package/dist/values.js
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The small operations every list rewrites.
|
|
3
|
+
*
|
|
4
|
+
* `toggleInSet` was found about twenty-five times across twelve repositories,
|
|
5
|
+
* in two encodings, and two of the copies were character-for-character
|
|
6
|
+
* identical in repos that share no code. One repo wrote the same three-line
|
|
7
|
+
* body eight times for eight facets, plus eleven more for its boolean flags.
|
|
8
|
+
* That is roughly a hundred and twenty lines in one file expressing one idea.
|
|
9
|
+
*
|
|
10
|
+
* `escapeLike` is the sharper case: three repos escape `%` and `_` before
|
|
11
|
+
* putting a reader's text into a SQL LIKE, and four do not. In those four,
|
|
12
|
+
* typing a single underscore matches every row.
|
|
13
|
+
*/
|
|
14
|
+
/** Add a value if absent, remove it if present. Order is preserved. */
|
|
15
|
+
export function toggleInSet(values, value) {
|
|
16
|
+
return values.includes(value) ? values.filter((v) => v !== value) : [...values, value];
|
|
17
|
+
}
|
|
18
|
+
/** A flag's two states, as the codec writes them: `["1"]` on, `[]` off. */
|
|
19
|
+
export function toggleFlag(values) {
|
|
20
|
+
return values.length ? [] : ["1"];
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Escape a reader's text for a SQL `LIKE`/`ILIKE` pattern.
|
|
24
|
+
*
|
|
25
|
+
* `%` and `_` are wildcards there. Unescaped, a search for "a_b" matches "axb",
|
|
26
|
+
* and a search for "%" matches every row in the table — which reads to the
|
|
27
|
+
* reader as a filter that does nothing. The backslash must go first or it
|
|
28
|
+
* escapes the escapes.
|
|
29
|
+
*/
|
|
30
|
+
export function escapeLike(value) {
|
|
31
|
+
return value.replace(/\\/g, "\\\\").replace(/[%_]/g, "\\$&");
|
|
32
|
+
}
|
|
33
|
+
/** `escapeLike`, wrapped for a contains match. */
|
|
34
|
+
export function likeContains(value) {
|
|
35
|
+
return `%${escapeLike(value)}%`;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Call `fn` only once the caller has stopped for `ms`.
|
|
39
|
+
*
|
|
40
|
+
* Eleven hand-rolled copies, five different delays, and — more importantly —
|
|
41
|
+
* only three of the twelve repos also guarded against a slow earlier response
|
|
42
|
+
* overwriting a fast later one. `debounce` cannot fix that race on its own, so
|
|
43
|
+
* `latest` below does, and they are exported together to make the pair obvious.
|
|
44
|
+
*/
|
|
45
|
+
export function debounce(fn, ms) {
|
|
46
|
+
let timer;
|
|
47
|
+
const run = (...args) => {
|
|
48
|
+
if (timer)
|
|
49
|
+
clearTimeout(timer);
|
|
50
|
+
timer = setTimeout(() => fn(...args), ms);
|
|
51
|
+
};
|
|
52
|
+
run.cancel = () => {
|
|
53
|
+
if (timer)
|
|
54
|
+
clearTimeout(timer);
|
|
55
|
+
timer = undefined;
|
|
56
|
+
};
|
|
57
|
+
return run;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Wrap an async function so only the most recent call can resolve.
|
|
61
|
+
*
|
|
62
|
+
* Without this, typing "ab" then "abc" can render the results for "ab" if the
|
|
63
|
+
* first request happens to be slower — the reader sees results that do not
|
|
64
|
+
* match the box they are looking at, and nothing in the UI admits it.
|
|
65
|
+
*/
|
|
66
|
+
export function latest(fn) {
|
|
67
|
+
let ticket = 0;
|
|
68
|
+
return async (...args) => {
|
|
69
|
+
const mine = ++ticket;
|
|
70
|
+
const result = await fn(...args);
|
|
71
|
+
return mine === ticket ? result : undefined;
|
|
72
|
+
};
|
|
73
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,60 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bitbaum/listkit",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.2",
|
|
4
|
+
"description": "A list as a query: a closed set of facet kinds, a URL codec that copies rather than rebuilds, a comparator that puts missing values last, and page arithmetic that cannot produce a negative offset. No markup, no React, no HTTP client.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "Cato",
|
|
7
|
+
"homepage": "https://github.com/bitbaum/listkit#readme",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/bitbaum/listkit.git"
|
|
11
|
+
},
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/bitbaum/listkit/issues"
|
|
14
|
+
},
|
|
15
|
+
"keywords": [
|
|
16
|
+
"filter",
|
|
17
|
+
"sort",
|
|
18
|
+
"facets",
|
|
19
|
+
"pagination",
|
|
20
|
+
"search-params",
|
|
21
|
+
"headless"
|
|
22
|
+
],
|
|
23
|
+
"type": "module",
|
|
24
|
+
"sideEffects": false,
|
|
25
|
+
"packageManager": "pnpm@11.25.0",
|
|
26
|
+
"engines": {
|
|
27
|
+
"node": ">=20"
|
|
28
|
+
},
|
|
29
|
+
"publishConfig": {
|
|
30
|
+
"access": "public",
|
|
31
|
+
"provenance": true
|
|
32
|
+
},
|
|
33
|
+
"files": [
|
|
34
|
+
"dist"
|
|
35
|
+
],
|
|
36
|
+
"exports": {
|
|
37
|
+
".": {
|
|
38
|
+
"types": "./dist/index.d.ts",
|
|
39
|
+
"default": "./dist/index.js"
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
"scripts": {
|
|
43
|
+
"build": "tsc -p tsconfig.json",
|
|
44
|
+
"lint": "eslint .",
|
|
45
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
46
|
+
"test": "node --test test/*.test.js",
|
|
47
|
+
"verify": "pnpm run format:check && pnpm run lint && pnpm run typecheck && pnpm run build && pnpm test",
|
|
48
|
+
"format": "prettier --write .",
|
|
49
|
+
"format:check": "prettier --check ."
|
|
50
|
+
},
|
|
51
|
+
"devDependencies": {
|
|
52
|
+
"@eslint/js": "^10.0.1",
|
|
53
|
+
"@types/node": "^26.4.1",
|
|
54
|
+
"eslint": "^10.9.1",
|
|
55
|
+
"globals": "^17.12.0",
|
|
56
|
+
"prettier": "3.9.10",
|
|
57
|
+
"typescript": "^6.0.3",
|
|
58
|
+
"typescript-eslint": "^8.69.0"
|
|
59
|
+
}
|
|
60
|
+
}
|