Layout Control Flow and State Coordination Design
Date: 2026-02-11 (updated 2026-02-12) Status: Wave 1 and Wave 2 complete
Goal
Build a robust, event-driven control model for the JavaScript layout system centered on sidenotes.js, margin-box injection, and identity widget injection, replacing timing/polling heuristics with explicit lifecycle contracts and state transitions.
Scope
In scope:
- assets/js/sidenotes.js
- margin-box template injection/selection path (views.py + templates)
- HTMX swap integration (frontpage-nav.js + sidenotes.js)
- identity UI coupling (identity.js, identity-dropdown.js, topup.js)
Out of scope:
- figure module API changes (setup(container, caps) remains compatible)
- major crypto protocol redesign in identity.js
Commit Review Impact (Latest Commits)
Reviewed commits:
- e8d24cf Add profile-updated event and topup payment return handling
- 65c095e Fix identity system not initializing on first visit
- 579c782 topup browser integration test
Conclusion:
- These commits do not change the core layout race analysis.
- They confirm existing concerns: the identity widget still relies on retry loops (wireUpWidget polling) and runtime timing assumptions about when injected boxes appear.
- New almanack:profile-updated event is useful and should become part of a broader explicit lifecycle/event model.
Existing System: End-to-End Flow
Server composition
- Django view selects margin boxes via
select_margin_boxes(). - Template renders article content inside
.margins-layoutand emits injected margin boxes in<template id="injected-margin-boxes">. - Base template loads scripts in this order:
htmx.min.jssidenotes.jsfrontpage-nav.js- noble crypto scripts
identity.jsidentity-dropdown.js
Client layout lifecycle (sidenotes.js)
- DOM/content readiness gate:
DOMContentLoaded+document.fonts.ready. init()collects footnotes, inline margin boxes, template-injected boxes, and figure IDs.loadPinnedBoxes()fetches missing pinned fragments from/margin-boxes/{slug}.html.- Enables classes (
sidenotes-enabled, optionalswipe-margins-enabled). - Positions sidenotes and margin boxes.
- Schedules reveal via
SETTLE_DELAYtimer. - Installs observers/listeners (resize, maintext
ResizeObserver, fragment handling, permalink handlers). - Repeats reposition on reflow signals.
HTMX path
- Prev/next links use
hx-select="#article-swap"andhx-target="#article-swap". htmx:afterSwaptriggers:frontpage-nav.js: masthead/nav refreshsidenotes.js: cleanup + reinitialize
Current Implicit State Machines
Sidenotes runtime (implicit today)
Observed effective states:
- idle
- waiting_for_fonts
- initializing
- ready
- repositioning
- cleanup/reinitialize
Problem: only a boolean isEnabled is tracked. There is no initializing lock, no cycle token, and no formal lifecycle events for dependent subsystems.
Identity runtime (implicit today)
Observed states across identity.js + dropdown:
- uninitialized
- local_loaded
- generated_unregistered
- registered
- visit_syncing
- degraded (API failure fallback)
Problem: these states are not explicit in code, so callers race each other (init, visit, UI updates) and compensate with retries/timeouts.
Race and Coupling Findings
-
~~Polling for readiness instead of lifecycle events~~ (RESOLVED in Wave 1) ~~
identity-dropdown.jsretries forwindow.Sidenotesand then retries for#identity-widgetexistence.~~ Replaced withSidenotes.whenReady()and lifecycle events. -
~~Init re-entrancy risk~~ (RESOLVED in Wave 1) ~~
init()can be reached from multiple triggers without a proper in-flight guard.~~ In-flight deduplication added toidentity.js; layout state machine prevents re-entrant init. -
~~Listener accumulation risk~~ (RESOLVED in Wave 1) ~~document-level permalink/touch handlers are installed per init path but not symmetrically removed in cleanup.~~ Tracked listener registry with symmetric
clearListeners()in cleanup. -
HTMX swap boundary mismatch HTMX swaps only
#article-swap; injected margin-box template is outside it. That can leave stale injected box sources across article swaps. -
Delay-based correctness points Several fixed
setTimeoutvalues are used as correctness gates (not just UX polish), which is brittle across device/browser conditions. -
Narrow observation surface Reflow observation is focused on
.maintext; layout-affecting changes in margins or asynchronously loaded injected content can be under-observed. -
Sequential pinned fetch path
loadPinnedBoxes()is serial and blocks completion windows; this extends unstable initialization periods. -
Identity widget injected at runtime instead of declared in HTML (NEW, discovered in Wave 1) The identity widget uses
injectMarginBox()to insert itself at runtime, making it the only margin box that manages its own lifecycle. This created a TOCTOU race:injectMarginBox()defers DOM insertion to the next RAF, so thegetElementByIdguard can miss an in-flight injection from a concurrent caller. Root cause: the identity box fights the layout system rather than participating in it. Every other margin box is declared in HTML and collected bycollectMarginBoxes()during init.
Desired Target Architecture
1. Layout Orchestrator with explicit lifecycle
Introduce an internal orchestrator in sidenotes.js with explicit state:
- idle
- initializing
- ready
- reflow_pending
- destroying
- destroyed
Expose:
- window.Sidenotes.whenReady(): Promise<void>
- lifecycle events:
- almanack:layout-init-start
- almanack:layout-ready
- almanack:layout-cycle
- almanack:layout-destroyed
2. Single invalidation scheduler
Replace direct reposition() calls with invalidate(reason):
- coalesced via requestAnimationFrame
- one active cycle at a time
- cycle token to cancel stale commits
3. Strict read/solve/write phases
Each layout cycle should be: 1. read phase (all measurements) 2. solve phase (pure placement decisions) 3. commit phase (DOM writes)
This reduces layout thrash and improves determinism.
4. HTMX boundary fix
Ensure article swap payload includes both:
- #article-swap
- updated injected margin-box source
Preferred options: - swap a container wrapping both article and template; or - keep current swap and add explicit OOB template replacement.
5. Identity as static margin box (REVISED)
The identity widget should be a declared margin box in the Django base template, not a runtime-injected box. This means:
- The base template renders an empty
<div class="margin-box" id="identity-margin-box" data-margin="left-top-high">shell. collectMarginBoxes()picks it up during normal init, positions it alongside other margin boxes.identity-dropdown.jsbecomes a pure data-binding script: find the shell, populate with cached profile data, update on identity/profile events.- No
injectMarginBox()call, nowhenReady()dependency for the box itself, no re-injection after HTMX swaps (the box lives outside#article-swapand survives naturally). - The
injectMarginBox()API remains available for truly dynamic boxes (user-pinned quotes, etc.) but the identity widget stops being its most complex consumer.
identity.js state transitions and in-flight deduplication are already formalized (Wave 1).
Event Stream Model (Target)
- DOM + fonts ready ->
layout-init-start - collect sidenotes, margin boxes (including identity shell), figures ->
layout-cycle - stable ->
layout-ready - identity-dropdown populates shell when crypto is ready (no layout dependency)
- HTMX swap ->
layout-destroyed-> fresh init cycle (identity shell outside swap boundary, persists) - profile updates ->
almanack:profile-updated-> UI repaint only (no polling)
Performance and Parallelization Opportunities
- Parallelize pinned slug fetches with
Promise.allSettled. - Parallelize independent figure module setup (retain API compatibility).
- Debounce invalidations centrally, not per observer.
- Replace fixed waits in tests with condition-based assertions.
Compatibility Constraints
Must remain compatible:
- window.Sidenotes.injectMarginBox/removeMarginBox/reposition/pin/unpin
- figure module interface setup(container, capabilities)
- existing margin-box fragment route /margin-boxes/{slug}.html
Wave 1 Results (Merged)
Completed and merged to main (9 commits on refactor/layout-lifecycle):
- Regression test suite (
test_layout_lifecycle.py, 6 tests) - Explicit
LayoutStateenum andruntimestate object - Lifecycle events (
layout-init-start,layout-cycle,layout-ready,layout-destroyed) andSidenotes.whenReady() - RAF-coalesced
invalidate(reason)replacing directreposition()calls - Tracked listener registry with symmetric
clearListeners()in cleanup - Identity-dropdown migrated from polling to
whenReady()+ lifecycle events - In-flight promise deduplication for
identity.jsasync operations - Fix for TOCTOU duplicate widget race (synchronous
widgetInjectedguard)
All 6 lifecycle tests green. 57/57 doc tests green. 85/85 unit tests green.
Wave 2 Results
Completed on branch refactor/layout-wave2 (5 commits):
- Static identity margin box —
#identity-margin-boxdeclared in article/index templates;identity-dropdown.jsrewritten as pure data binding (~120 lines, down from ~185)._staticParenttracking ensures cleanup returns static boxes to their parent instead of removing them. - HTMX swap boundary fix —
<template id="injected-margin-boxes">moved inside#article-swapso article-specific boxes update with swaps. - Parallel pinned fetches —
loadPinnedBoxes()refactored from sequential loop toPromise.allSettledwith deterministic insertion order. - Broader invalidation signals — ResizeObserver extended to margin columns; test
wait_for_timeoutcalls replaced withwait_for_selector/wait_for_function. - Documentation — Lifecycle contracts, margin box taxonomy, and identity static box pattern documented in
doc/website/.
All 6 lifecycle tests green. 57/57 doc tests green. 81/81 unit tests green.
Success Criteria
Functional:
- ~~No retry loops in identity dropdown.~~ (DONE, Wave 1)
- ~~No duplicate global listeners after repeated HTMX swaps.~~ (DONE, Wave 1)
- ~~Injected margin boxes always correspond to current article after swap.~~ (DONE, Wave 2 — template moved inside #article-swap)
- ~~Identity widget is a static margin box, not runtime-injected.~~ (DONE, Wave 2 — declared in article/index templates)
- ~~Mobile + iOS layout tests remain green.~~ (DONE — 3 pre-existing mobile scroll-snap failures unrelated to this refactor)
Operational:
- ~~deterministic layout cycles with explicit reason logging.~~ (DONE — invalidate(reason) with RAF coalescing)
- ~~reduction in raw setTimeout correctness dependencies.~~ (DONE, Wave 2 — ResizeObserver extended to margin columns, tests use condition-based waits)
Risks
- HTMX payload boundary changes can affect frontpage-nav assumptions.
- Listener cleanup mistakes can regress interactivity.
- Over-eager invalidation can cause layout thrash if not coalesced.
Mitigation: - land incrementally behind feature flags. - add targeted integration tests before each phase.
Flowchart
Control-flow diagram is stored at:
doc/process/plans/2026-02-11-layout-control-flow-current.dot