Workbench / The TiffinBox Build
S15 · V2·15
Search as You Type
Volume 2, chapter 15. The first JavaScript in TiffinBox: the stage 13 menu search, enhanced to search as you type. A tested helper module (debounce, latest-wins requests with AbortController, rupee formatting), a module that updates the page in place with text (never HTML), a live status for screen readers, and a URL that follows the query. Browser tests prove one request per typed word, that a slow old response can't overwrite a newer one (the naive version showed "3 dishes match "m"" under a box that said "me"), and that a failing service or a broken script leaves the plain form working. The stage also found a syntax error that unit tests and `node --check` both passed, and a search that matched nothing for any two-word query.
Stage 15: search as you type
The brief
What you'll build.
web/lib.js, a dependency-free module:debounce,latest(only the newest call's result counts; older calls are aborted),rupees, andgetJson(timeout, errors for non-2xx);web-tests/lib.test.mjs: unit tests with Node's built-in test runner and fake timers;web/search.js: enhances/menu: searches 200 ms after typing stops, renders results with DOM methods, announces the count in a live region, keeps the query in the URL, and degrades to the plain form on any failure;- server changes: the menu page gets a stable structure (status, list, "no dishes" message) and loads the module;
/menu/searchwith a blank query returns the menu; multi-word queries match (a bug found in step 5); web-tests/stage15.py(browser evidence) andweb-tests/check-js.sh(syntax check plus unit tests).
Why a real company needs this. Search-as-you-type is where most frontends first meet concurrency: overlapping requests, responses in the wrong order, requests for text the user has already deleted, and a service that's slow or down. Getting it right once, in a small tested helper, is the pattern every later screen reuses (stage 19's retries, stage 29's background sync).
Why now. Chapter 15 is JavaScript: closures, promises, async/await, cancellation with AbortController, the event loop and UI races. The stage 13 form gives a baseline that must keep working, so the enhancement can be judged against it.
What you'll have at the end.
- search-as-you-type in about 4 KB of JavaScript (about 2 KB gzipped), with no framework;
- 6 unit tests and a browser test that compares the naive and the latest-wins versions;
- ADR-0017: progressive enhancement rules for scripts.
Theory to own
- Debounce. Typing "masala dosa" at a steady pace, how many requests does a 200 ms debounce send, and what's the trade-off in choosing 200 ms?
- Out-of-order responses. Requests for "m" and then "me" are both in flight. Why can "m"'s response arrive second, and what must the page do about it? (Chapter: "Race conditions in UI code"; Lab experiment 3.)
- Abort is not enough. If you abort the old request, why do you still need to check that a response belongs to the latest call?
- Rendering untrusted text. Dish names come from the server. Why build list items with
textContentinstead of a template string andinnerHTML, given stage 12's CSP? - Enhancement. The script fails to load, throws on start, or the search service returns 503. What must the user still be able to do?
Build it
Step 1: the helpers, tested first
Write web/lib.js with four exports: debounce(fn, ms) (with cancel, no return value: Companion, Code walkthrough), latest() (each run(work) aborts the previous call's AbortController and resolves to { value } only if it's still the newest call, otherwise { stale: true }), rupees(paise) matching the server's format, and getJson(url, { signal, timeoutMs }). Then write web-tests/lib.test.mjs with node:test and t.mock.timers, including a test where the old work ignores its signal.
Checkpoint. node --test web-tests/*.test.mjs passes 6 tests.
Step 2: a page structure the script can update
Change the server's /menu page so the parts that change always exist: <p id="search-status" role="status"> (empty without a query), <ul class="dishes" id="dishes">, and <p id="no-dishes" hidden>. Load the module only on this page: page(…, "/search.js") adds <script type="module" src="/search.js"> to the head. Make /menu/search with a blank query return the menu, as /menu does. Update PagesTest's "no script element" assertion: the page's own module is now the one allowed script.
Checkpoint. The server tests pass (17), and the stage 13 flow with JavaScript off is unchanged.
Step 3: the enhancement
Write web/search.js. Find the form, input, list, status and empty message; if any is missing, do nothing. On input, call a 200 ms debounced run; on submit, prevent the navigation, cancel the pending debounce and run now. run uses latest().run(signal => getJson(…, { signal })) and renders only non-stale results. render builds each <li> with createElement and textContent, toggles the empty message, sets the status text, updates the URL with history.replaceState and the document title. On failure, show "Search isn't available right now. Press Search to try again." in the status, and leave the list as it was. Mark the form data-enhanced="true" at the end.
Checkpoint. Run web-tests/stage15.py.
Step 4: prove it in a browser
Extend stage15.py: type "masala dosa" at 80 ms per key and record every /menu/search request; make the service return 503; clear the box; type "pon" and reload; check CSP violations; and repeat a search with JavaScript off.
Checkpoint. One request for the typed text, the right results, a message on failure, the query surviving a reload, no CSP violations.
Step 5: out-of-order responses, naive against latest-wins
Make "m" slow: in Playwright's async API, route /menu/search* and delay the response for q=m by 1.2 s. Type "m", wait 400 ms (so "m" is sent), type "e" ("me" is sent and answers at once), wait 2 s, and record what's shown. Run it twice: once with a naive search.js (served through page.route, rendering every response as it arrives), and once with the real one.
Checkpoint. The naive page shows the wrong results; the real one shows "me"'s, and the "m" request is aborted.
Senior and architect lens
1. Enhancement means the baseline is tested, not assumed. Every check in stage15.py has a "what if the script isn't there" counterpart, and the syntax error proved why: a broken module is invisible to a user only because the HTML underneath works. Without stage 13, that bug would have been a dead search box.
2. ADR-0017: progressive enhancement rules for scripts. Write it with these points:
- Decision: scripts are same-origin ES modules that enhance server-rendered pages; a page must remain usable when its script fails to load, fails to parse, throws, or its API fails.
- Rules: data is rendered with DOM methods (
textContent), neverinnerHTML; every async UI action useslatest()or an equivalent (abort plus a staleness check); every fetch has a timeout; failures show a message and leave the baseline in place; URL state usesreplaceStatefor refinements andpushStatefor navigations. - Checks:
check-js.sh(syntax, unit tests) and a browser test per enhanced page, including a JavaScript-off run. - Revisit when: a page can't have a meaningful no-JavaScript version (the live kitchen display, stage 17).
3. Concurrency in a single thread is about time, not memory. No locks are needed in the browser, but every await is a point where the world can change (Companion, theoretical gap 2). latest() is the frontend's equivalent of a version check: the same idea as stage 5's idempotency keys and Volume 3's optimistic locking.
4. A test that blocks its own event loop measures itself. Both the sync-API sleep here and the stale server in stage 14 are harness bugs that made tests report something other than the system under test. Treat a surprising result from a test as a question about the test first.
5. Features find old bugs. The multi-word search bug had been in the core since Volume 1 and in the HTML form since stage 13. A new way of using a feature (typing whole names) exposed it. That's an argument for testing behaviour through realistic inputs (full dish names, typos, other scripts), not just the inputs each layer was designed around.
What breaks first, and when it's addressed:
| Pressure | What breaks | Where it's addressed |
|---|---|---|
a type change in the JSON (pricePaise renamed) |
the script renders undefined or throws at runtime |
stage 16 (contract types from one source) |
| hundreds of searches per second on a popular kitchen | every keystroke burst is a request; no caching | stage 19 (HTTP caching, ETags) |
| typos and transliteration ("dosai", "dosha", "దోస") | prefix search finds nothing | Volume 3 (search ranking and fuzzy matching) |
| screen-reader users get every count announced while typing | role="status" on every update |
stage 20 (announce only when typing pauses) |
| the module grows and pages need different scripts | one file per page, no shared build | stage 30 (workspace and bundling) |
Evidence
web-tests/check-js.shprints "syntax ok" and 6 passing tests; thenode --checkresult that missed the syntax error is in the README.web-tests/stage15.pyoutput, including the naive and latest-wins lines, is in the README.- The multi-word search fix has tests in
core(44 passing) and the server tests pass (17). stage13.py,stage14.py(stillfailures: 0) andvalidate.shstill pass.- ADR-0017 is committed.
Carry forward
latest()is used for every async UI action from now on; stage 19 adds retries inside it.getJsonbecomes the typed API client in stage 16, generated from the server's contract.- The page structure (status, list, empty state as stable elements) is the model for every later view of a list: the kitchen display (stage 17) and its React version (stage 22).
check-js.shruns on every stage; stage 30 replaces the hand-written loop with the workspace's build.