Volume 2 Companion: The Web FrontendPractice for Volume 2
0 / 0

Workbench / Volume 2 Companion: The Web Frontend

V2·21

UI Architecture

Companion to Volume 2, chapter 21: how components, design systems and code organisation connect; new angles (components as a kitchen's stations, tokens as a recipe's measurements, dependency direction as a supply chain, a state machine as a railway signal box); what the chapter simplifies, measured: a connection modelled with three booleans that reaches "connected and gave up", English plural rules that break in Hindi and Russian, a rupee helper that writes ₹123456.00 where Indian readers expect ₹1,23,456.00, and a 16-pixel CSS change that makes 38% of a screenshot "different"; the theory behind it; how Preact Signals keeps a diamond of computed values glitch-free (and why a computed array re-runs effects that a string wouldn't); four debugging drills; interview questions with how to approach each.

6 sections · ~14 min to read
Updated Suggest a correction

Understanding it better

Concept map

Chapter 21 has three strands. Components: UI as a function of state, component boundaries, composition, primitives, compound and headless components, keys and identity. Design systems: tokens, styling approaches, versioning and adoption, Web Components (and, from this companion, internationalisation). Organising the code: feature modules, domain boundaries, shared libraries, dependency direction, the cost of abstraction, and how frameworks keep the screen in sync (and, here, state machines).

components design systems organising the code UI = f(state) describe, don't mutate component boundaries one reason to change composition children · slots primitives button · field · dialog compound, headless behaviour without looks keys, identity which item is which tokens decisions as data styling approaches CSS · modules · utilities design system primitives + rules + docs versioning, adoption semver for UI Web Components the platform's components internationalisation plurals · numbers · direction feature modules code by capability domain boundaries orders ≠ menu ≠ kitchen shared libraries earned, not planned dependency direction features → shared reactivity VDOM · signals · compiler state machines only legal states split by joined by built from or lists need applied by packaged as released with or as plus follow may need obey plus plus goes deeper: ch14 CSS · ch15 JavaScript · ch20 accessibility · ch22 React · ch23 Angular · ch25 state management exercises: P1–P9 god components, signals, keys, compound and headless components, tokens, boundaries, barrels, Web Components
Concept map of chapter 21, UI architecture: components (UI as a function of state, component boundaries, composition, primitives, compound and headless components, keys and identity), design systems (tokens, styling approaches, versioning and adoption, Web Components) and organising code (feature modules, domain boundaries, shared libraries, coupling and dependency direction, the cost of abstraction, reactivity strategies), with links such as state flowing down into components and boundaries enforced by tools.

The links worth remembering:

  • State is the input; the screen is the output. Every architecture in the chapter is a way to keep "what's on screen" a function of "what's true", and to make what's true small and explicit (Gaps 1).
  • Boundaries are about change, not size. A good component or module changes for one reason; a good shared library changes rarely. Dependency direction (features depend on shared code, never the reverse) keeps a change in one feature from rippling into others.
  • A design system is decisions, encoded. Tokens encode visual decisions, primitives encode interaction and accessibility decisions, and formatting helpers encode language decisions (Gaps 2). Each decision made once is a bug fixed everywhere.

Explain it differently

1. Components are a kitchen's stations. The dosa station, the chutney station and the pass each own one job, take inputs (orders, ingredients) and hand out results. A station that also does billing is a god component: every change in billing disturbs the dosas.

2. Tokens are a recipe's measurements. "A cup of rice, two of dal" lets any cook reproduce the dish; "some rice" doesn't. --space-4 and --accent are measurements; hard-coded 13px and #0b6 are "some".

3. Dependency direction is a supply chain. Farms supply the market, the market supplies kitchens. If a farm had to ask a particular kitchen before planting, every kitchen's menu change would ripple back to the farm. Shared libraries are farms: features depend on them, never the other way round.

4. A state machine is a railway signal box. Trains (events) arrive in any order, but the box only allows moves that are legal from the current state: no train enters a section that's occupied. Booleans set by separate handlers are signals operated by separate people who never talk (Gaps 1).

5. Keys are name tags at a wedding. Reorder the guests and the tags tell the caterer who's who; without tags (index keys), the caterer assumes the person in seat 3 is still the vegetarian, whoever is sitting there now (Chapter Exercises P3).

6. Headless components are a car's engine and gearbox sold without a body. The hard parts (keyboard behaviour, focus, ARIA) are engineered once; each product team builds its own body (styles) on top.

7. Premature abstraction is buying a bus for a family of three. It can carry everyone you might ever have; it's also hard to park, expensive to run and slower than the car you needed. Wait until the third use to build the shared thing.

8. Signals are a spreadsheet; virtual DOM is a photocopier. In a spreadsheet, changing one cell recalculates exactly the cells that depend on it. A virtual DOM re-renders a copy of the whole sheet and compares it with the last copy to find what changed. Both are correct; they spend effort in different places (Code walkthrough).

Gaps and misconceptions

What the chapter oversimplifies

All outputs are real, from Node 22 and Chromium (exp/21).

1. State machines: booleans let in states that mean nothing. The chapter's components take state as input. What that state is shaped like matters as much. A connection modelled the way UI code often grows (three booleans, each set by a separate handler as features arrived) against the same behaviour as an explicit machine (each state lists the events it accepts), fed 10,000 random sequences of 12 events:

Terminal
three booleans: 4 distinct states reached: connected, connected+gaveUp, connected+reconnecting, connected+reconnecting+gaveUp
state machine: 4 distinct states reached: backingOff, connecting, live, reconnecting

The same number of states, but the boolean version's include "connected and gave up" and "connected, reconnecting and gave up": combinations no screen can sensibly show, reached by ordinary event orders (an error after open never clears connected). The machine can only be in states someone designed, and each shows one thing. The stage 17 display grew exactly this way (downSince, source, retryTimer, attempt); stage 21 of the build turns its connection logic into a machine (drill D1).

2. Internationalisation: plurals and numbers aren't English with translated words. The build's search status says ${n} ${n === 1 ? 'dish matches' : 'dishes match'}, and prices come from a hand-written rupees() helper. Plural categories from Intl.PluralRules, and prices from Intl.NumberFormat:

Terminal
plural category for 0, 1, 2, 5, 21:
  en: 0=other 1=one 2=other 5=other 21=other
  hi: 0=one 1=one 2=other 5=other 21=other
  te: 0=other 1=one 2=other 5=other 21=other
  ar: 0=zero 1=one 2=two 5=few 21=many
  ru: 0=many 1=one 2=few 5=many 21=one
12345600 paise -> rupees(): ₹123456.00 | en-IN: ₹1,23,456.00 | hi-IN: ₹1,23,456.00 | te-IN: ₹1,23,456.00 | en-US: ₹123,456.00
-3135 paise -> rupees(): −₹31.35 | en-IN: -₹31.35 | hi-IN: -₹31.35 | te-IN: -₹31.35 | en-US: -₹31.35

Hindi uses the singular form for 0 as well as 1; Arabic has six categories; in Russian, 21 takes the singular. An n === 1 rule is English-only, and a translator given "dish matches"/"dishes match" can't express the others. And rupees() never groups digits: ₹1,23,456.00 (lakh grouping) is what Indian readers expect, which en-IN produces and en-US doesn't. Message formats with plural categories (ICU MessageFormat) and Intl formatters are architecture: one formatting layer, never string concatenation in components (drill D2).

3. Visual testing: one shift, and the whole screenshot "differs". The chapter leaves out visual regression testing. Two screenshots of the build's menu page at 375 px, with the same CSS, and with stage 19's against stage 20's CSS (stage 20 added 8 px of padding above and below the header links):

Terminal
same CSS, two renders: 0 pixels differ (0.0%), box None
stage 19 CSS against stage 20 CSS: 99973 pixels differ (38.1%), box (0, 19, 375, 700)

Rendering is deterministic (the same input gives identical pixels), which is what makes visual tests possible. But a 16-pixel change in the header moved everything below it, so 38% of pixels differ, and the diff's box is the entire page below the header: a reviewer learns that "something changed" and nothing about what. Visual tests work at component level (one component per screenshot, in a fixed frame, as Storybook-style stories do), with thresholds and a human approving each baseline change (drill D3).

Common misconceptions

Misconception What's actually true Where it's shown
"A few booleans are simpler than a state machine." They allow combinations nobody designed; a machine allows only the states you list. Gaps 1; drill D1
"i18n is translating strings." Plurals, number grouping, dates and direction need a formatting layer, not concatenation. Gaps 2; drill D2
"Full-page screenshots catch visual regressions." Any shift floods the diff; test components in isolation. Gaps 3; drill D3
"Signals re-run only what changed." They re-run what depends on a value that's no longer ===; a computed array is new every time. Code walkthrough; drill D4
"Shared code should be extracted early." Extract at the third use, when the shape is known. Explain it differently 7
"Micro-frontends fix team coupling." They move it to runtime contracts and duplicate frameworks; they solve an organisational problem at a technical cost. Interview Q5

Theoretical gaps: the ideas behind the chapter

1. Make illegal states unrepresentable. A type or a state machine whose possible values are exactly the meaningful ones removes a class of bugs instead of testing for it. It's the same principle as stage 5's lifecycle table and TypeScript's discriminated unions (chapter 16): count the states your representation allows, and compare with the states you meant.

2. Statecharts extend state machines for real UIs. David Harel's statecharts (1987) add hierarchy (a "connected" state containing "idle" and "busy"), parallel regions (connection state and filter state independently) and history. They keep machines readable as they grow, which is what XState and similar libraries implement.

3. Conway's law: systems mirror the organisations that build them. Module boundaries tend to follow team boundaries. Designing boundaries is partly designing who talks to whom; the "inverse Conway manoeuvre" shapes teams to get the architecture you want. Micro-frontends are Conway's law taken literally.

4. Coupling and cohesion, measured. Afferent and efferent coupling (who depends on a module, what it depends on), instability (efferent over total) and the "stable dependencies principle" (depend in the direction of stability) are Robert C. Martin's metrics for package design. They apply to UI modules unchanged and can be checked by tools (fitness functions).

5. Reactivity is incremental computation with a scheduling policy. Signals build a dependency graph and propagate changes; virtual DOM recomputes and diffs; compilers (Svelte) generate the update code ahead of time. All must avoid glitches (an observer seeing a half-updated graph) and decide when updates run (immediately, batched, per frame). It's the same problem as spreadsheets and build systems ("build systems à la carte", Mokhov and others).

6. Locale is data, and CLDR holds it. Plural rules, number grouping, date formats, currency symbols and collation for every language come from the Unicode Common Locale Data Repository, which Intl exposes. Hard-coding any of them in components means re-deriving data that already exists, wrongly.

Applying it

Code walkthrough

Chapter Exercises P2 builds a small signals library and finds its glitch. Preact Signals is a production one, used by Preact and adaptable to other frameworks. Excerpts from @preact/signals-core 1.8.0, src/index.ts, installed from npm.

Writing a signal

TypeScript
	set(this: Signal, value) {
		if (value !== this._value) {
			if (batchIteration > 100) {
				throw new Error("Cycle detected");
			}

			this._value = value;
			this._version++;
			globalVersion++;

			/**@__INLINE__*/ startBatch();
			try {
				for (
					let node = this._targets;
					node !== undefined;
					node = node._nextTarget
				) {
					node._target._notify();
				}
			} finally {
				endBatch();
			}
		}
	},

A write does three things: compares with !== (so writing an equal primitive does nothing, but a new array always counts as a change), bumps two version numbers (the signal's own and a global one), and notifies dependents inside a batch. Notifying doesn't recompute anything: it marks computed values as possibly outdated and queues effects. Effects run in endBatch, after every notification, which is what prevents glitches: no effect runs while the graph is half-updated.

Pulling: recompute only if a source really changed

TypeScript
function needsToRecompute(target: Computed | Effect): boolean {
	// Check the dependencies for changed values. The dependency list is already
	// in order of use. Therefore if multiple dependencies have changed values, only
	// the first used dependency is re-evaluated at this point.
	for (
		let node = target._sources;
		node !== undefined;
		node = node._nextSource
	) {
		// If there's a new version of the dependency before or after refreshing,
		// or the dependency has something blocking it from refreshing at all (e.g. a
		// dependency cycle), then we need to recompute.
		if (
			node._source._version !== node._version ||
			!node._source._refresh() ||
			node._source._version !== node._version
		) {
			return true;
		}
	}
	// If none of the dependencies have changed values since last recompute then
	// there's no need to recompute.
	return false;
}

Each dependency edge remembers the version of the source it last saw. A computed value recomputes only if some source's version moved, after asking that source to refresh itself first (recursively). So a computed whose inputs were notified but produced equal values doesn't run its function, and neither do its dependents: "push" marks things dirty, "pull" decides what really changed. The _refresh code adds two shortcuts: if the global version hasn't moved since the last check, nothing can have changed; and a computed's own version only increases if its new value is !== the old one.

Read it yourself

  1. Build a diamond: openCount and lateCount both read orders; summary reads both; an effect reads summary. Change orders once. How many times does each run, and what does the effect see?
  2. An effect reads a computed that returns orders.value.filter(o => o.late); another reads a computed that returns the late ids joined into a string. A new order arrives that isn't late. Which effects run? Then: two writes in a row, with and without batch.

Debugging drills

D1. "Live" and "Reconnecting" at the same time

The kitchen display sometimes shows the green "Live" badge and the red "Reconnecting since 12:40" banner together; after a while it shows "Live" while no orders arrive. The connection code has isConnected, isReconnecting and gaveUp flags, each set in a different event handler, and the template shows the badge if isConnected and the banner if isReconnecting.

D2. Hindi plurals that are wrong for zero, and prices that are hard to read

The Hindi launch shows "0 व्यंजन मिले" when nothing matches, and the team's Hindi-speaking QA says the form is wrong for zero, and kitchen managers complain that order totals like ₹123456.00 are hard to read. The code: ${n} ${n === 1 ? t('dish.one') : t('dish.other')} and the rupees() helper.

D3. The visual test fails on every pull request

The team added full-page screenshot comparisons for 20 pages. Since then, almost every pull request fails visual tests, with diffs covering most of each page; people have started approving new baselines without looking. The last real visual bug (a button colour) went unnoticed among 19 other "changed" pages.

D4. The display's summary bar flickers and the CPU fan spins

After moving the display to signals, the summary bar ("42 open, 3 late") flickers on every order event, and profiling shows the late-orders effect running on every event, even when nothing is late. The code: const late = computed(() => orders.value.filter(isLate)), effect(() => renderLateBanner(late.value)), and the snapshot handler does for (const o of snap.orders) orders.value = upsert(orders.value, o).

Career-oriented

Interview prep

Mid level

Q1. You inherit a component with isLoading, isError, data and isEmpty props, and bug reports about spinners shown over error messages. How do you fix it properly?

How to get there. Count the combinations the props allow (16), list the ones that make sense, and replace the props with a representation that allows only those.

Q2. Where should date, number and currency formatting live in a frontend, and why?

How to get there. Consider who needs formatting (every component), what it depends on (the user's locale, time zone, currency), and what goes wrong when it's scattered (Gaps 2).

Senior level

Q3. The kitchen display's logic (connection, snapshot and events, actions with retries, announcements, timers) has grown into one 300-line file. Propose a structure.

How to get there. Separate by reason to change: protocol (the stream), state (orders, connection), effects (network, timers, wake lock), and view (cards, announcer). Decide what's pure and testable without a browser.

Q4. Two product teams both want a "date picker". One has built one already. Should the design system own it, and how?

How to get there. Chapter Exercises S1–S3 cover build-or-adopt and versioning. Focus on the move from one team's component to a shared one: requirements from both, accessibility, ownership, and how the first team migrates.

Staff level

Q5. Leadership asks whether TiffinBox should adopt micro-frontends so that the customer, kitchen and partner teams can deploy independently. What do you recommend?

How to get there. Chapter Exercises leaves micro-frontends out. Separate the goal (independent delivery) from the mechanism (runtime composition), estimate costs (duplicated frameworks, shared state and design consistency, cross-app contracts), and compare with alternatives.

Q6. How do you keep the frontend's architecture from eroding over two years and four teams?

How to get there. Chapter Exercises leaves fitness functions out. Turn architectural decisions into automated checks, decide which are enforced in CI, and plan how they evolve.