The TiffinBox BuildOne system, every chapter
0 / 0

Workbench / The TiffinBox Build

S25 · V2·25

State in the Right Place

Volume 2, chapter 25. Three pieces of state get a proper home. The plain kitchen view moves onto the shared store and the page's embedded state, so all three views now run on one data path and the plain view no longer downloads a second 108 KB snapshot (all 500 cards on screen in 0.61 s, from 0.69–0.77). Which orders a screen shows becomes URL state: `?show=Ready` is the pass, rendered by the server, kept by Back, bookmarkable, and the same in every view; a GET form makes it work without JavaScript. The theme becomes a remembered preference in an HttpOnly cookie that the server turns into `data-theme`, with tokens rewritten as `light-dark()`; a frame-by-frame comparison shows the cookie paints no wrong frames where the usual localStorage script paints one.

6 parts · ~6 min to read
Updated Suggest a correction

Stage 25: state in the right place

The brief

What you'll build.

  • plain view on the store: kitchen.ts rewritten as a renderer of kitchen/store.ts, started from the page's embedded state (now on every kitchen page); one card touched for one change, chunked reconciling for many;
  • the filter as URL state: kitchen/filters.ts (pure: parseShow, shows, withShow) and kitchen/show-store.ts (the URL as a store: the form's change pushes history, Back restores, the radios follow); the server renders the filtered first screen and the form; all three views use it;
  • the theme as a preference: POST /preferences/theme (a form, Post/Redirect/Get, HttpOnly cookie, no open redirect); every HTML page gets data-theme from the cookie; colour tokens as light-dark() with color-scheme set by data-theme;
  • checks: PagesTest.theThemePreferenceIsAFormACookieAndAnAttribute, the stream test extended for the filter and embedded state on the plain view, a filters unit test, 24 px radio targets; web-tests/stage25.py for the filter in every view, without JavaScript, and the theme's first paint.

Why a real company needs this. State in the wrong place causes most of the bugs that feel random: a filter lost on reload, a link that opens the wrong screen, a theme that flickers, two tabs disagreeing, Back that "doesn't work". Classifying each piece of state and giving it one home is cheap at design time and expensive to retrofit.

Why now. Chapter 25 is state management: kinds of state, client stores, server state as a cache. Stages 22–24 built a shared store; this stage finishes moving every view onto it and adds the two kinds of state the display didn't have yet: what the screen is (URL) and how the user likes it (a preference).

What you'll have at the end.

  • one data path for three views, and a filter and a theme that behave the same everywhere, with or without JavaScript;
  • a measured reason for keeping the preference where the server can read it;
  • ADR-0027: where each kind of state lives in TiffinBox's frontend.

Theory to own

  1. Classifying state. For each of the display's state (open orders, connection status, filter, theme, a pending action), which kind is it and where should it live? (The chapter, "Classify first".)
  2. URL state. What belongs in the URL, and when should a change push a history entry rather than replace one? (Companion, Gaps 2 and drill D1.)
  3. Single source of truth. When state is shown in two places (the URL and a form), what keeps them in step? (Companion, drill D2.)
  4. Persisted preferences. What are the trade-offs between localStorage, a cookie and a server profile? (Companion, Gaps 1 and 3.)
  5. Server state as a cache. The store holds a copy of the server's open orders. What keeps it fresh, and what replaces it when it can't be? (Stages 17 and 24.)

Build it

Step 1: the plain view on the shared store

Rewrite kitchen.ts as a renderer: create the store from readPage(), subscribe, and on each notification compare with what was last drawn. If only the connection changed, update the status line; if one order changed (lastChange) and the filter didn't, touch that one card (tb:order); otherwise reconcile everything in chunks of 50 per frame, removing cards no longer shown and moving a card only when it's out of place. Keep stage 20's rules (focus kept through updates, aria-disabled, the announcer, the wake lock) and stage 18's measures. The server now embeds the state on every kitchen page.

Checkpoint. Stages 17–20 pass on the plain view; stage24.py shows the plain view's stream sending a ping, not a snapshot.

Step 2: the filter as URL state

Write kitchen/filters.ts (pure, so it's added to the boundary check's pure modules) and kitchen/show-store.ts. On the server, render a GET form with radios (All open orders, New, Cooking, At the pass), carrying view through a hidden field, and filter the first screen by show. Use the filter in all three views: the plain view in its reconcile, React with useSyncExternalStore, Angular through a signal. Announce new orders only when the current screen shows them. Write stage25.py's filter part: load ?show=Ready, choose New, press Back, count page loads; then the same with JavaScript off.

Checkpoint. Every view shows only the chosen orders, changes without a request, and restores on Back; the no-JavaScript form works.

Step 3: the theme as a remembered preference

Add POST /preferences/theme: parse the form strictly, accept system, light or dark, set (or clear, for system) an HttpOnly, SameSite=Lax cookie for a year, and redirect with 303 to a return path that must start with a single /. Add a small theme form to the page header. In one place (Pages.themed, applied to every HTML response), read the cookie, accept only the three values, put data-theme on <html>, select the current option, and set the form's return to the current page. Rewrite the colour tokens as light-dark(light, dark) so one color-scheme value switches them, set by data-theme.

Checkpoint. The theme test passes; stage 14's audit passes in both system themes; stage 20 finds no target under 24 px.

Step 4: measure the first paint

Extend stage25.py: set the device to light and the preference to dark, throttle the CPU 4×, sample the body's background colour every frame from navigation start, and compare the cookie with a common alternative, a module script that reads localStorage and sets data-theme (injected by the test through request interception, not shipped). Also set the theme without JavaScript.

Checkpoint. You know how many wrong frames each approach paints.

Senior and architect lens

1. Classify before choosing tools. This stage needed no new library: a URL store of 25 lines, a cookie and a pure module. The decisions were where each piece of state lives and who must see it when.

2. ADR-0027: state in TiffinBox's frontend. Write it with these points:

State Home Why
orders, connection kitchen/store.ts, started from the page, kept by the stream server state, shared by all views
which screen (kitchen, view, filter) the URL, validated on both sides links, reloads and the server's first render
theme an HttpOnly cookie now, the staff profile later (Volume 3) right on the first paint, without JavaScript
pending actions, retry notes local to the card nobody else needs them
localStorage not used for state it can throw, fill up and lag the first paint (Companion, Gaps 1 and 3)

3. One path, three views. After this stage the views differ only in rendering. A bug in data handling is fixed once (stage 23's double publish showed why); a feature like the filter is a pure module plus a few lines per view.

4. The URL is user input and a public format. It's validated like a form field, its defaults are omitted, and once people bookmark it, changing what show=Ready means is a breaking change.

5. Pages that vary by a cookie mustn't be cached as if they didn't. Every HTML page now depends on the theme cookie. They're no-store today; stage 31's caching must add Vary: Cookie or keep personal variation out of cacheable pages.

What breaks first, and when it's addressed:

Pressure What breaks Where it's addressed
several display tabs on one device each opens its own stream; HTTP/1.1 allows six connections stage 31 (HTTP/2)
staff move between devices the theme cookie is per device Volume 3 (staff profiles)
a cached page varies by cookie one visitor's theme served to another stage 31 (caching rules)
the contract can't express optional fields, unions, or pricedBy as two fields API cleanup postponed stage 30 (the contract as a workspace package)
checkout is still a form post without retries a lost response leaves the customer unsure stage 29 (client-side placement with keys, queued offline)

Evidence

  • stage25.py passes: the filter in all three views and without JavaScript, the theme without JavaScript, and the first-paint comparison.
  • 31 server tests pass, including the theme test (open redirect, bogus cookie, clearing) and the plain view's embedded state and filter.
  • check-js.sh passes (19 modules, 25 tests); stages 12–20, 22 (both views) and 24 pass.
  • The NullPointerException from List.of(…).contains(null) is recorded with its fix.
  • ADR-0027 is committed.

Carry forward

  • kitchen/store.ts is now the only data path for the display; stage 29 adds an offline command queue beside it.
  • ?show= and show-store.ts are the pattern for any screen-defining state; stage 26 tests keyboard use of the filter in every view.
  • Pages.themed is the one place per-request presentation is applied; stage 28 adds the CSP nonce there.
  • light-dark() tokens are checked against stage 27's Baseline policy.