Files
CatoandClaude Opus 5 69cb4f4ef1 feat: listkit — a list as a query
Filtering, sorting, searching and paging are the same problem everywhere
and were solved separately everywhere. A survey of twelve repositories in
this fleet on 2026-09-11 found twelve incompatible filter-state shapes and
no two alike, ~34 hand-built URL builders, ~25 copies of "toggle a value
in a set" in two encodings, ~11 debounces at five different delays, ~11
copies of Math.ceil(total / pageSize) with three in one repo, and three of
the seven repos that need to escape a SQL LIKE pattern doing so.

Two of the toggle copies are character-for-character identical in repos
that share no code. One repo writes the same three-line body eight times
for eight facets plus eleven more for its boolean flags — about a hundred
and twenty lines expressing one idea. This is well past the rule of three.

Four live bugs were among the URL builders, and the codec here exists so
they cannot be written again: a preset that rebuilt the params from
scratch and wiped the reader's search; a date range that did not clear
page and stranded the reader past the end; a builder that preserved three
params by name so every later param had to be remembered in six template
strings; and a debounced box using push rather than replace, so the back
button walked through every spelling of the word.

What it ships is the decisions. Five facet kinds — one, many, flag, range,
ordinal — with the empty selection as the only sentinel, because one repo
used its translated label as the all-value and made filter identity depend
on the reader's language. A comparator that puts missing values last in
BOTH directions, since a record with no date is not the oldest record. Page
arithmetic that cannot produce a negative offset and gives an empty list
one page rather than "page 1 of 0". Facet counts computed with that
facet's own selection lifted, so an unselected option never reads as a
dead end.

What it deliberately does not ship is markup, tokens, React, a search
engine or an HTTP client. Nine token vocabularies and six chip treatments
were found among the same repos, several different on purpose. The fleet
has already run the experiment where a shared renderer owns the markup: it
reached two consumers of twenty and shipped the same two defects to both,
unfixable downstream. Centralize the rule; render it locally.

43 tests, importing the package by name so a broken exports map fails here
rather than at the first consumer's install.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018Z7YRpgsEtNjRqr1usHMQY
2026-09-11 17:17:16 +02:00

83 lines
3.0 KiB
TypeScript

/**
* The small operations every list rewrites.
*
* `toggleInSet` was found about twenty-five times across twelve repositories,
* in two encodings, and two of the copies were character-for-character
* identical in repos that share no code. One repo wrote the same three-line
* body eight times for eight facets, plus eleven more for its boolean flags.
* That is roughly a hundred and twenty lines in one file expressing one idea.
*
* `escapeLike` is the sharper case: three repos escape `%` and `_` before
* putting a reader's text into a SQL LIKE, and four do not. In those four,
* typing a single underscore matches every row.
*/
/** Add a value if absent, remove it if present. Order is preserved. */
export function toggleInSet(values: readonly string[], value: string): string[] {
return values.includes(value) ? values.filter((v) => v !== value) : [...values, value];
}
/** A flag's two states, as the codec writes them: `["1"]` on, `[]` off. */
export function toggleFlag(values: readonly string[]): string[] {
return values.length ? [] : ["1"];
}
/**
* Escape a reader's text for a SQL `LIKE`/`ILIKE` pattern.
*
* `%` and `_` are wildcards there. Unescaped, a search for "a_b" matches "axb",
* and a search for "%" matches every row in the table — which reads to the
* reader as a filter that does nothing. The backslash must go first or it
* escapes the escapes.
*/
export function escapeLike(value: string): string {
return value.replace(/\\/g, "\\\\").replace(/[%_]/g, "\\$&");
}
/** `escapeLike`, wrapped for a contains match. */
export function likeContains(value: string): string {
return `%${escapeLike(value)}%`;
}
/**
* Call `fn` only once the caller has stopped for `ms`.
*
* Eleven hand-rolled copies, five different delays, and — more importantly —
* only three of the twelve repos also guarded against a slow earlier response
* overwriting a fast later one. `debounce` cannot fix that race on its own, so
* `latest` below does, and they are exported together to make the pair obvious.
*/
export function debounce<A extends unknown[]>(
fn: (...args: A) => void,
ms: number,
): ((...args: A) => void) & { cancel: () => void } {
let timer: ReturnType<typeof setTimeout> | undefined;
const run = (...args: A) => {
if (timer) clearTimeout(timer);
timer = setTimeout(() => fn(...args), ms);
};
run.cancel = () => {
if (timer) clearTimeout(timer);
timer = undefined;
};
return run;
}
/**
* Wrap an async function so only the most recent call can resolve.
*
* Without this, typing "ab" then "abc" can render the results for "ab" if the
* first request happens to be slower — the reader sees results that do not
* match the box they are looking at, and nothing in the UI admits it.
*/
export function latest<A extends unknown[], R>(
fn: (...args: A) => Promise<R>,
): (...args: A) => Promise<R | undefined> {
let ticket = 0;
return async (...args: A) => {
const mine = ++ticket;
const result = await fn(...args);
return mine === ticket ? result : undefined;
};
}