@escape-game-over/atlas 0.1.18 → 0.1.19

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.
@@ -470,6 +470,12 @@ faq.define(Faq);
470
470
  before they are read, so a broken nested copy cannot fail the outer lookup.
471
471
  - **The tag is written once.** `faq.tag` is what the template renders and
472
472
  `faq.define` registers the class under it.
473
+ - **The names are checked in the editor.** A tag without a hyphen, or a role
474
+ that is not camelCase, is a compile error where it is written — the rules are
475
+ types, character by character, as in `i18n/placeholders.ts`. Nothing is
476
+ validated at run time, because a name that reached the browser malformed would
477
+ already have been refused there: by `setAttribute`, by `querySelectorAll`, or
478
+ by `customElements.define`.
473
479
 
474
480
  `tag` and `define` are the component's own keys, so no role may take them. A role
475
481
  that lives outside every instance, such as a footer button that reopens a
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@escape-game-over/atlas",
3
- "version": "0.1.18",
3
+ "version": "0.1.19",
4
4
  "type": "module",
5
5
  "description": "Typed, data-driven machinery for static multi-locale, multi-deployment Astro sites.",
6
6
  "private": false,
package/src/astro/dom.ts CHANGED
@@ -1,40 +1,20 @@
1
1
  /**
2
- * Scoped element lookups, without the ceremony.
3
- *
4
- * `querySelector` returns `Element`, so anything that wants to set `hidden`,
5
- * read `dataset` or call `focus` has to say `<HTMLElement>` at every call — long
6
- * enough that the line wraps, on lookups that are otherwise trivial. And
7
- * `querySelectorAll` returns a `NodeList`, which needs spreading before it will
8
- * `map` or `entries`. Both are noise, and both hide the one thing worth reading:
9
- * what is being looked for.
2
+ * Scoped element lookups, typed.
10
3
  *
11
4
  * ```ts
12
5
  * const { one, all } = within(root);
13
- * const track = one("[data-carousel-track]");
14
6
  * const dots = all<HTMLButtonElement>("[data-carousel-dot]");
15
7
  * ```
16
8
  *
17
- * The root is bound once, which is the point: a client script that looks
18
- * everything up inside the element it was given cannot reach a second copy of
19
- * itself elsewhere on the page. `document` is a valid root, and should appear
20
- * exactly once per script — to find the roots.
9
+ * The root is bound once, so a script cannot reach a second copy of itself
10
+ * elsewhere on the page. `document` belongs in one place per script: finding
11
+ * the roots.
21
12
  *
22
13
  * **A selector with a combinator still matches against the whole document.**
23
- * `within(form).one("form p")` can match a `<p>` whose ancestor `<form>` is not
24
- * the one bound here; only the final filter is scoped. Simple selectors an
25
- * attribute, a class — are unaffected, which is what these are for. Use
26
- * `:scope` if a combinator is ever genuinely needed.
14
+ * `within(form).one("form p")` can match a `<p>` under a different form; only
15
+ * the final filter is scoped. Use `:scope` if a combinator is needed.
27
16
  */
28
17
 
29
- /**
30
- * Constrained to `Element` but defaulting to `HTMLElement`.
31
- *
32
- * The default is what almost every lookup wants — `hidden`, `dataset` and
33
- * `focus` all live on `HTMLElement`, and having to name it at each call is the
34
- * noise this exists to remove. The wider constraint is for the rest: inline
35
- * `<svg>` and `<use>` are `SVGElement`, which is an `Element` and not an
36
- * `HTMLElement`, so a narrower bound would refuse a perfectly ordinary lookup.
37
- */
38
18
  export interface Within {
39
19
  /** The first match inside the root, or `null`. */
40
20
  one<T extends Element = HTMLElement>(selector: string): T | null;
@@ -42,6 +22,8 @@ export interface Within {
42
22
  all<T extends Element = HTMLElement>(selector: string): T[];
43
23
  }
44
24
 
25
+ // `HTMLElement` by default because `hidden`, `dataset` and `focus` live there;
26
+ // the bound stays `Element` so inline `<svg>` lookups are not refused.
45
27
  export function within(root: ParentNode): Within {
46
28
  return {
47
29
  one: <T extends Element = HTMLElement>(selector: string) =>
@@ -2,19 +2,13 @@ import { reportDevError } from "./dev-log.ts";
2
2
  import { within } from "./dom.ts";
3
3
 
4
4
  /**
5
- * A base for custom elements, holding the parts every one of them gets wrong.
6
- *
7
- * In `astro/` because it touches the DOM, which the core is type-checked
8
- * without — this, `consent.ts`, `carousel.ts` and `dom.ts` are the folder
9
- * allowed it.
5
+ * A base for custom elements: two lifetimes, and one abort signal.
10
6
  *
11
7
  * ```ts
12
8
  * class Thing extends AtlasElement {
13
- * #count = 0;
14
- *
15
- * protected setup(): void { … } // once, ever
16
- * protected connect(): void { // every time it enters the document
17
- * this.require("form").addEventListener("submit", this.#send, {
9
+ * protected setup(): void { … } // once, ever: what the element is
10
+ * protected connect(): void { // every connection: bind with signal
11
+ * this.require("form").addEventListener("submit", send, {
18
12
  * signal: this.signal,
19
13
  * });
20
14
  * }
@@ -22,75 +16,49 @@ import { within } from "./dom.ts";
22
16
  * customElements.define("atlas-thing", Thing);
23
17
  * ```
24
18
  *
25
- * **Two lifetimes, and confusing them is the whole reason this class exists.**
26
- * An element is constructed once and may be connected many times: moving it in
27
- * the DOM runs `disconnectedCallback` then `connectedCallback` again. So
28
- * `setup` is for what the element *is* state, defaults, anything a reader
29
- * would be annoyed to lose — and `connect` is for what a connection *owns* —
30
- * listeners, timers, observers. Anything registered with `signal` is torn down
31
- * on every disconnect and re-registered on every connect, so a re-entry rebinds
32
- * rather than duplicating.
33
- *
34
- * **Subclasses implement `setup`, `connect` and `disconnect` never
35
- * `connectedCallback` or `disconnectedCallback`.** Overriding those replaces
36
- * this class's, the controller is never created, and every listener leaks on
37
- * each disconnect. `connect` is abstract, so forgetting it is a compile error;
38
- * the adjacent mistake is caught at construction in development, below.
19
+ * - **An element is constructed once and connected many times.** Moving it in
20
+ * the DOM runs `disconnectedCallback` then `connectedCallback` again, so
21
+ * state belongs in `setup` and listeners in `connect`. Anything registered
22
+ * with `signal` is dropped on disconnect and rebound on the next connect.
23
+ * - **Override `setup`, `connect` and `disconnect`, never the callbacks.**
24
+ * Overriding `connectedCallback` skips the controller and leaks every
25
+ * listener; that mistake throws in development, below.
26
+ * - **The defining script must stay a deferred module.** Astro emits
27
+ * `<script src>` as `type="module"`, so the element has its children when it
28
+ * is upgraded. `is:inline` runs it too early and every lookup finds nothing.
29
+ * - **`attributeChangedCallback` runs before `connectedCallback`**, where
30
+ * `signal` is not readable yet. Record what changed and act on it in
31
+ * `connect`.
32
+ * - **`disconnect` is not a destructor.** A move fires it and connects again a
33
+ * moment later, so it is connection teardown and nothing else.
39
34
  *
40
- * **The script that defines a subclass must stay a deferred module.** Astro
41
- * emits `<script>` and `<script src="./…">` as `type="module"`, which runs after
42
- * the document is parsed, so an element has its children by the time it is
43
- * upgraded. `is:inline` opts out and runs the script where it sits — usually
44
- * above the element it wires — and every lookup then finds nothing. The
45
- * protection comes from the bundling, not from custom elements.
46
- *
47
- * **`attributeChangedCallback` runs before `connectedCallback`** for attributes
48
- * present in the initial markup, so `signal` is not available there and reading
49
- * it throws. A subclass with `observedAttributes` should record what changed and
50
- * act on it in `connect`.
51
- *
52
- * What is deliberately *not* modelled is destruction. `disconnect` fires on
53
- * every move, so it is connection teardown and nothing else — it is not the
54
- * place to flush state or release something genuinely scarce, because the
55
- * element may well be back a microtask later.
35
+ * See docs/client-scripts.md.
56
36
  */
57
37
  export abstract class AtlasElement extends HTMLElement {
58
38
  /**
59
- * Cancels this connection's listeners, and only this connection's.
60
- *
61
- * Remade on every connect rather than held in a field initializer, because
62
- * an `AbortController` is single-use: a controller that outlived the first
63
- * connection would come back already aborted, `addEventListener` with an
64
- * aborted signal silently adds nothing, and the element would return looking
65
- * perfectly normal and be inert forever.
39
+ * This connection's listeners, and only this connection's. Remade on every
40
+ * connect: an `AbortController` is single-use, and a reused one comes back
41
+ * already aborted, leaving the element inert but normal-looking.
66
42
  */
67
43
  #ac?: AbortController;
68
44
 
69
- /** Whether `setup` has run. See the two-lifetimes note above. */
70
45
  #ready = false;
71
46
 
72
47
  constructor() {
73
48
  super();
74
- // Written as the bare expression Vite substitutes: `import.meta.env.DEV`
75
- // is replaced with a literal, so this collapses to `if (false)` and the
76
- // method below is dropped from the bundle. An optional chain would be
77
- // replaced as `import.meta.env` instead — an object literal, whose
78
- // `.DEV` a minifier has to fold rather than simply delete.
49
+ // The bare expression Vite substitutes, so this collapses to
50
+ // `if (false)` and the method below leaves the bundle.
79
51
  if (import.meta.env.DEV) this.#assertHooks();
80
52
  }
81
53
 
82
54
  /**
83
- * Refuses a subclass that overrode the wrong lifecycle method.
84
- *
85
- * An override is an *own* property of the subclass prototype, where the
86
- * inherited one is not — so walking up to this class's prototype finds it.
87
- * The loop rather than a single check, because an intermediate base class
88
- * could be the one that got it wrong.
55
+ * Refuses a subclass that overrode the wrong lifecycle method. An override
56
+ * is an *own* property of the subclass prototype; the loop covers an
57
+ * intermediate base class that got it wrong.
89
58
  */
90
59
  #assertHooks(): void {
91
- // A tuple array rather than an object: `Object.entries` widens its keys
92
- // back to `string`, so the pairing would stop being checked exactly
93
- // where a typo would matter.
60
+ // A tuple array, not an object: `Object.entries` would widen the keys
61
+ // back to `string` and stop checking the pairing.
94
62
  const wrong = [
95
63
  ["connectedCallback", "connect"],
96
64
  ["disconnectedCallback", "disconnect"],
@@ -106,11 +74,8 @@ export abstract class AtlasElement extends HTMLElement {
106
74
  const error = new Error(
107
75
  `override "${hook}", not "${callback}" — see AtlasElement`
108
76
  );
109
- // Reported before throwing: this runs during upgrade, so
110
- // `connectedCallback`'s catch has not been entered and the
111
- // throw would surface only as an uncaught error in the
112
- // console — invisible, for the one mistake this whole
113
- // apparatus exists to catch.
77
+ // Reported before throwing: this runs during upgrade, where
78
+ // a throw would only surface as an uncaught console error.
114
79
  reportDevError(this.constructor.name, error);
115
80
  throw error;
116
81
  }
@@ -120,10 +85,7 @@ export abstract class AtlasElement extends HTMLElement {
120
85
 
121
86
  /**
122
87
  * Pass to `addEventListener`, observers, anything that should stop when the
123
- * element leaves the document.
124
- *
125
- * Throws when read outside a connection, which is a programming error
126
- * rather than a state to handle: there is nothing sensible to return.
88
+ * element leaves the document. Throws outside a connection.
127
89
  */
128
90
  protected get signal(): AbortSignal {
129
91
  if (!this.#ac) {
@@ -135,25 +97,17 @@ export abstract class AtlasElement extends HTMLElement {
135
97
  }
136
98
 
137
99
  connectedCallback(): void {
138
- // Insurance. The spec pairs the callbacks, so this should never find a
139
- // live controller — but if it ever did, overwriting one would orphan
140
- // every listener it owned, silently, which is the failure this class
141
- // exists to make impossible.
100
+ // Insurance: overwriting a live controller would orphan its listeners.
142
101
  this.#ac?.abort();
143
102
  this.#ac = new AbortController();
144
103
 
145
- // Caught here so one broken element logs and sits inert rather than
146
- // taking its siblings with it: the browser calls this once per element,
147
- // so the blast radius is already one. That is what lets `require`
148
- // throw instead of returning something every call site has to check.
104
+ // Caught so one broken element logs and sits inert rather than taking
105
+ // its siblings with it which is what lets `require` throw.
149
106
  try {
150
107
  if (!this.#ready) {
151
108
  this.setup();
152
- // Only once it returned. Setting the flag first would mean a
153
- // `setup` that threw was never retried, and the next connect
154
- // would run `connect` against state that was never initialized
155
- // — a component that renders perfectly and does nothing, which
156
- // is the failure this class exists to make impossible.
109
+ // Only once it returned, so a `setup` that threw is retried
110
+ // rather than leaving `connect` to run against nothing.
157
111
  this.#ready = true;
158
112
  }
159
113
  this.connect();
@@ -163,18 +117,13 @@ export abstract class AtlasElement extends HTMLElement {
163
117
  }
164
118
 
165
119
  disconnectedCallback(): void {
166
- // Idempotent, so `adoptedCallback` can delegate here without running a
167
- // subclass's teardown twice.
120
+ // Idempotent, so `adoptedCallback` can delegate here.
168
121
  if (!this.#ac) return;
169
122
  this.#ac.abort();
170
123
 
171
- // Caught for the same reason as `connect`, and it matters more: a
172
- // throw here escapes into whatever is swapping the DOM — a router, a
173
- // view transition — rather than staying in the component.
174
124
  try {
175
125
  // Before `#ac` is cleared, so `this.signal` is readable and already
176
- // aborted: an async continuation can check `signal.aborted` and
177
- // bail rather than finishing against a detached element.
126
+ // aborted: an async continuation can check it and bail.
178
127
  this.disconnect();
179
128
  } catch (error) {
180
129
  this.#report(error);
@@ -183,13 +132,7 @@ export abstract class AtlasElement extends HTMLElement {
183
132
  this.#ac = undefined;
184
133
  }
185
134
 
186
- /**
187
- * Fires when the element moves to another document.
188
- *
189
- * Delegates, because the controller belongs to the connection in the old
190
- * document and nothing else would tear it down. Exotic — `adoptNode` and
191
- * iframe work — and one line either way.
192
- */
135
+ /** Moving to another document ends the old document's connection. */
193
136
  adoptedCallback(): void {
194
137
  this.disconnectedCallback();
195
138
  }
@@ -202,30 +145,13 @@ export abstract class AtlasElement extends HTMLElement {
202
145
  console.error(`${this.localName}:`, error);
203
146
  }
204
147
 
205
- /**
206
- * Runs once per element, before its first `connect`.
207
- *
208
- * Where state belongs. A move re-runs `connect` but never this, so anything
209
- * initialised here survives one — which is the difference between a reader
210
- * coming back to the slide they left and coming back to the first one.
211
- */
148
+ /** Runs once per element, before its first `connect`. State belongs here. */
212
149
  protected setup(): void {}
213
150
 
214
151
  /** Runs on every connect, with `signal` and the children both available. */
215
152
  protected abstract connect(): void;
216
153
 
217
- /**
218
- * Runs on every disconnect, once the signal has been aborted.
219
- *
220
- * `signal` is still readable here and reports `aborted` — which is what an
221
- * async continuation should check before touching a now-detached element.
222
- * What it is *not* is a destructor: a move fires this and then `connect`
223
- * again a moment later, so it is connection teardown and nothing else.
224
- * Flushing state or releasing something scarce does not belong here.
225
- *
226
- * Empty by default: anything registered with `signal` is already gone, and
227
- * most elements have nothing else to undo.
228
- */
154
+ /** Runs on every disconnect, once the signal has been aborted. */
229
155
  protected disconnect(): void {}
230
156
 
231
157
  /** The first match inside this element, or `null`. */
@@ -239,13 +165,9 @@ export abstract class AtlasElement extends HTMLElement {
239
165
  }
240
166
 
241
167
  /**
242
- * The first match, or a thrown error naming what was missing.
243
- *
244
- * Throws rather than returning `T | null`, because a nullable return puts an
245
- * `?.` at every call site — and that optional chain swallows the failure
246
- * just as thoroughly as the missing element did, which is the thing worth
247
- * avoiding. `connectedCallback` catches it, so one element with broken
248
- * markup logs and stops while every other element on the page is untouched.
168
+ * The first match, or a thrown error naming what was missing. Throws rather
169
+ * than returning `null`, because the `?.` at every call site swallows the
170
+ * failure as thoroughly as the missing element did.
249
171
  */
250
172
  protected require<T extends Element = HTMLElement>(selector: string): T {
251
173
  const found = this.one<T>(selector);
@@ -1,120 +1,63 @@
1
1
  /**
2
- * The DOM writes every filtered list turns out to make, and only those.
2
+ * The two DOM writes every filtered list turned out to share.
3
3
  *
4
- * `filters` decides which items match and what the address bar says, and hands
5
- * both to `onChange`. Everything a page does about that answer is its own — and
6
- * mostly stays that way: three lists in one repository draw their results three
7
- * different ways, with tabs and a blurb on one, an exclusive `<details>`
8
- * accordion on another, a two-level country roll-up on the third.
4
+ * `filters` decides which items match; what a page does about that is its own.
5
+ * These are the parts three lists wrote identically, and getting wrong was
6
+ * silent. Both take elements, never selectors, so no attribute name in this
7
+ * package has to be matched by a consumer.
9
8
  *
10
- * These two helpers are what all three, or two of three, wrote identically. That
11
- * is the whole bar for being here: not "a list might want this" but "every list
12
- * we have written already did, character for character, and getting it wrong was
13
- * silent". Anything the three disagreed about is still theirs.
9
+ * They write only what is binary and derived an input's `value`, and `hidden`
10
+ * on a clear button, an empty message or a section with nothing left. No class,
11
+ * style or `aria`: that is where the choices live.
14
12
  *
15
- * **Both take elements, never selectors.** A project decides what its markup is
16
- * called and hands over what it found, so no attribute name in this package has
17
- * to be matched by any consumer — the reason `filters` itself has no markup
18
- * contract, kept intact one layer up.
13
+ * Two notes for the markup:
19
14
  *
20
- * These write to elements, which the rest of `astro/` refuses to do, and the
21
- * line is worth being exact about. `carousel` will not write a transform because
22
- * a transform is a design decision with no single right answer. Everything
23
- * written here is the opposite: an input's `value` is the control's own state,
24
- * and `hidden` on a clear button, an empty message or a section with nothing
25
- * left in it is binary and derived. Nothing here sets a class, a style or an
26
- * `aria` attribute, which is where the choices live.
15
+ * - **`hidden` needs help in a grid.** Any author rule setting `display` beats
16
+ * it. Tailwind v4's preflight ships `[hidden] { display: none !important }`;
17
+ * without something like it these writes are inert and nothing filters.
18
+ * - **A result count wants `aria-live="polite"`**, in the template.
27
19
  *
28
- * Two notes for the markup on the other side of that boundary:
29
- *
30
- * - **`hidden` needs help in a grid.** It is a `display: none` from the user
31
- * agent, and any author rule setting `display: flex` or `grid` beats it. A
32
- * project on Tailwind v4 gets `[hidden] { display: none !important }` from
33
- * preflight and needs nothing; anything else should ship that rule itself, or
34
- * every one of these writes is inert and the list simply never filters.
35
- * - **A result count wants `aria-live="polite"`.** Filtering as you type changes
36
- * the page silently for anyone not looking at it. The attribute belongs on the
37
- * element in the template, not here — this package is handed elements and does
38
- * not decide what they are.
20
+ * See docs/client-scripts.md.
39
21
  */
40
22
 
41
23
  import type { FieldMap, Filters } from "./filters.ts";
42
24
 
43
- /**
44
- * The fields of `F` that hold text, so a search box cannot be pointed at a flag.
45
- *
46
- * `list.set(field, input.value)` hands over a string; aimed at a `flag` that is
47
- * a type error worth getting at the call site rather than a filter that silently
48
- * never matches.
49
- */
25
+ /** The `text` fields of `F`, so a search box cannot be pointed at a flag. */
50
26
  export type TextFieldOf<F extends FieldMap> = {
51
27
  [K in keyof F]: F[K] extends { kind: "text" } ? K : never;
52
28
  }[keyof F];
53
29
 
54
30
  /**
55
- * What a search box is made of, as much of it as exists.
56
- *
57
- * Every part is optional and `null` is accepted, because `within(root).one(…)`
58
- * returns `null` and a page is allowed to have a search field with no clear
59
- * button, or a list with no empty state. Handing over what a lookup returned,
60
- * without checking it first, is the point.
31
+ * What a search box is made of, as much of it as exists. Every part is
32
+ * optional and `null` is accepted, so what a lookup returned can be handed over
33
+ * without checking it first.
61
34
  */
62
35
  export interface SearchBoxElements {
63
36
  readonly input?: HTMLInputElement | null;
64
37
  /** Clears the field. Hidden while the field is already empty. */
65
38
  readonly clear?: HTMLElement | null;
66
- /**
67
- * The "nothing matched" message.
68
- *
69
- * Tracks the whole result set rather than this field alone — a list emptied
70
- * by a category is as empty as one emptied by a query, and there is one
71
- * message either way. It lives here because it is the same line in every
72
- * consumer, not because it belongs to the search box.
73
- */
39
+ /** The "nothing matched" message. Tracks the whole result set. */
74
40
  readonly empty?: HTMLElement | null;
75
41
  /**
76
- * How many matched, written as digits and nothing else.
77
- *
78
- * Two of the three write this, and the same way. Digits only, because the
79
- * sentence around them is not ours to build: a list that reads "6 of 42" in
80
- * one language reads "6 din 42" in another, and a translated string is not
81
- * something to take apart in a browser to get at one number. Give the count
82
- * an element of its own and let the copy sit beside it — which is what the
83
- * consumer doing this already had to do.
84
- *
85
- * Same rule as the rest of this file, one field further: derived, and with
86
- * no choice in it. Where the number *goes* is still the template's.
87
- *
88
- * Give it `aria-live="polite"` there. Filtering as you type changes the
89
- * page silently for anyone not watching it, and this package is handed
90
- * elements rather than deciding what they are.
42
+ * How many matched, as digits and nothing else: the sentence around them is
43
+ * translated, and not something to take apart in a browser. Give the count
44
+ * its own element and let the copy sit beside it.
91
45
  */
92
46
  readonly count?: HTMLElement | null;
93
47
  }
94
48
 
95
49
  export interface SearchBox {
96
50
  /**
97
- * Brings the box into line with the state, from inside `onChange`.
98
- *
99
- * Takes two scalars rather than the change object, so this stays independent
100
- * of what the field was named and of which other fields the list has.
101
- *
102
- * Safe before `bind` and after the undo it returns: this only writes to the
103
- * elements it was given, so a box that is no longer wired renders the last
104
- * thing it was told rather than throwing.
51
+ * Brings the box into line with the state, from inside `onChange`. Two
52
+ * scalars rather than the change object, so this does not care what the
53
+ * field was named.
105
54
  */
106
55
  render(query: string, matchCount: number): void;
107
56
  /**
108
- * Points the input and the clear button at one `text` field of a list, and
109
- * returns the undo.
110
- *
111
- * Separate from construction because of an ordering knot rather than a
112
- * preference: `render` is called from the list's own `onChange`, so the box
113
- * has to exist before the list, and this needs the list. Two calls and a
114
- * `const` each way is the honest version of that; the alternative is a `let`
115
- * the reader has to hold in their head.
116
- *
117
- * One `AbortController`, as everywhere else here — see `carousel.attach`.
57
+ * Points the input and the clear button at one `text` field, and returns
58
+ * the undo. Separate from construction because `render` is called from the
59
+ * list's `onChange`: the box has to exist before the list, and this needs
60
+ * the list.
118
61
  */
119
62
  bind<F extends FieldMap>(
120
63
  list: Filters<F>,
@@ -123,45 +66,26 @@ export interface SearchBox {
123
66
  }
124
67
 
125
68
  /**
126
- * The search input beside a `filters` list, and the two things every one of them
127
- * has to remember.
69
+ * The search input beside a `filters` list.
128
70
  *
129
71
  * ```ts
130
- * const search = searchBox({
131
- * input: one<HTMLInputElement>("[data-filter-search]"),
132
- * clear: one("[data-filter-clear]"),
133
- * empty: one("[data-filter-empty]"),
134
- * count: one("[data-filter-count]"),
135
- * });
136
- *
72
+ * const search = searchBox({ input, clear, empty, count });
137
73
  * const list = filters({
138
- * fields, items,
139
- * onChange({ state, matched }) {
140
- * search.render(state.q, matched.size);
141
- * // …everything this list draws for itself
142
- * },
74
+ * fields,
75
+ * items,
76
+ * onChange: ({ state, matched }) => search.render(state.q, matched.size),
143
77
  * });
144
- *
145
78
  * const unbind = search.bind(list, "q");
146
- * const detach = list.attach();
147
79
  * ```
148
- *
149
- * It writes rather than calling back, and that is the only reason it exists.
150
- * `filters.onChange` is already the callback that hands a consumer the value and
151
- * gets out of the way; a second one here would hand back `query` and `count` and
152
- * leave the same three writes to be spelled out at every call site, which is the
153
- * duplication this was extracted from.
154
80
  */
155
81
  export function searchBox(elements: SearchBoxElements): SearchBox {
156
82
  const { input, clear, empty, count } = elements;
157
83
 
158
84
  return {
159
85
  render(query, matchCount) {
160
- // Guarded by inequality, not written unconditionally. Assigning
161
- // `value` while someone is typing in the field moves the caret to
162
- // the end, so the one case this exists for — state that moved
163
- // without the keyboard, from the back button or a `reset` — must not
164
- // cost a caret jump on every other keystroke.
86
+ // Guarded by inequality: assigning `value` while someone types
87
+ // moves the caret to the end, and this exists for state that moved
88
+ // without the keyboard the back button, or a `reset`.
165
89
  if (input != null && input.value !== query) input.value = query;
166
90
  if (clear != null) clear.hidden = query === "";
167
91
  if (empty != null) empty.hidden = matchCount > 0;
@@ -171,9 +95,8 @@ export function searchBox(elements: SearchBoxElements): SearchBox {
171
95
  bind(list, field) {
172
96
  const listeners = new AbortController();
173
97
  const { signal } = listeners;
174
- // The narrowing `TextFieldOf` already did, restated for the
175
- // implementation: inside a generic function TypeScript cannot see
176
- // that this field's value type is `string`, though every caller can.
98
+ // The narrowing `TextFieldOf` already did: inside a generic
99
+ // function TypeScript cannot see that this field holds a string.
177
100
  const name = field as Parameters<typeof list.set>[0];
178
101
 
179
102
  input?.addEventListener(
@@ -186,10 +109,7 @@ export function searchBox(elements: SearchBoxElements): SearchBox {
186
109
  "click",
187
110
  () => {
188
111
  list.reset(name);
189
- // Focus follows the click, because the button the pointer
190
- // was on has just hidden itself — leaving focus on a
191
- // `hidden` element strands a keyboard reader at a control
192
- // that is no longer there.
112
+ // The button just hid itself; focus must not stay on it.
193
113
  input?.focus();
194
114
  },
195
115
  { signal }
@@ -201,40 +121,19 @@ export function searchBox(elements: SearchBoxElements): SearchBox {
201
121
  }
202
122
 
203
123
  /**
204
- * Hides each group that has nothing visible left inside it.
205
- *
206
- * ```ts
207
- * onChange({ matched }) {
208
- * for (const item of items) item.hidden = !matched.has(keyOf(item));
209
- * hideEmpty(groups, (group) => within(group).all("[data-faq-key]"));
210
- * }
211
- * ```
212
- *
213
- * A filtered list that renders its results under headings has this problem and
214
- * nothing else does: hide the items and the headings stay, so a search for one
215
- * word leaves a page of section titles with nothing under them. It reads as a
216
- * broken template rather than as a result, which is what makes forgetting it
217
- * expensive — nothing errors, and the page looks wrong in a way that does not
218
- * point at the filter.
124
+ * Hides each group that has nothing visible left inside it — the heading
125
+ * problem a list with sections has and nothing else does.
219
126
  *
220
- * **Reads `hidden`, rather than taking the matched set.** The items were just
221
- * hidden by the caller, so their state is the shortest true description of what
222
- * survived and reading it is what lets this nest. A country is empty when
223
- * every city in it is hidden; a region is empty when every country in it is
224
- * hidden, *including the ones this call just hid*.
127
+ * **Reads `hidden` rather than the matched set**, which is what lets it nest: a
128
+ * country is empty when every city is hidden, a region when every country is,
129
+ * *including the ones the previous call just hid*.
225
130
  *
226
- * **Which makes the order load-bearing: innermost first.**
131
+ * **So the order is load-bearing: innermost first.**
227
132
  *
228
133
  * ```ts
229
134
  * hideEmpty(countries, (c) => within(c).all("[data-city]"));
230
135
  * hideEmpty(regions, (r) => within(r).all("[data-country]"));
231
136
  * ```
232
- *
233
- * Run the other way round, the regions are judged against countries that have
234
- * not been hidden yet, and a region with nothing in it survives.
235
- *
236
- * A group with no children at all is hidden, which is the same answer by the
237
- * same rule — there is nothing visible in it.
238
137
  */
239
138
  export function hideEmpty<T extends HTMLElement>(
240
139
  groups: Iterable<T>,