Manual
Almnck.
Price: 50ⓐ

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

  1. Django view selects margin boxes via select_margin_boxes().
  2. Template renders article content inside .margins-layout and emits injected margin boxes in <template id="injected-margin-boxes">.
  3. Base template loads scripts in this order:
  4. htmx.min.js
  5. sidenotes.js
  6. frontpage-nav.js
  7. noble crypto scripts
  8. identity.js
  9. identity-dropdown.js

Client layout lifecycle (sidenotes.js)

  1. DOM/content readiness gate: DOMContentLoaded + document.fonts.ready.
  2. init() collects footnotes, inline margin boxes, template-injected boxes, and figure IDs.
  3. loadPinnedBoxes() fetches missing pinned fragments from /margin-boxes/{slug}.html.
  4. Enables classes (sidenotes-enabled, optional swipe-margins-enabled).
  5. Positions sidenotes and margin boxes.
  6. Schedules reveal via SETTLE_DELAY timer.
  7. Installs observers/listeners (resize, maintext ResizeObserver, fragment handling, permalink handlers).
  8. Repeats reposition on reflow signals.

HTMX path

  1. Prev/next links use hx-select="#article-swap" and hx-target="#article-swap".
  2. htmx:afterSwap triggers:
  3. frontpage-nav.js: masthead/nav refresh
  4. sidenotes.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

  1. ~~Polling for readiness instead of lifecycle events~~ (RESOLVED in Wave 1) ~~identity-dropdown.js retries for window.Sidenotes and then retries for #identity-widget existence.~~ Replaced with Sidenotes.whenReady() and lifecycle events.

  2. ~~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 to identity.js; layout state machine prevents re-entrant init.

  3. ~~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.

  4. 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.

  5. Delay-based correctness points Several fixed setTimeout values are used as correctness gates (not just UX polish), which is brittle across device/browser conditions.

  6. Narrow observation surface Reflow observation is focused on .maintext; layout-affecting changes in margins or asynchronously loaded injected content can be under-observed.

  7. Sequential pinned fetch path loadPinnedBoxes() is serial and blocks completion windows; this extends unstable initialization periods.

  8. 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 the getElementById guard 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 by collectMarginBoxes() 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.js becomes a pure data-binding script: find the shell, populate with cached profile data, update on identity/profile events.
  • No injectMarginBox() call, no whenReady() dependency for the box itself, no re-injection after HTMX swaps (the box lives outside #article-swap and 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)

  1. DOM + fonts ready -> layout-init-start
  2. collect sidenotes, margin boxes (including identity shell), figures -> layout-cycle
  3. stable -> layout-ready
  4. identity-dropdown populates shell when crypto is ready (no layout dependency)
  5. HTMX swap -> layout-destroyed -> fresh init cycle (identity shell outside swap boundary, persists)
  6. profile updates -> almanack:profile-updated -> UI repaint only (no polling)

Performance and Parallelization Opportunities

  1. Parallelize pinned slug fetches with Promise.allSettled.
  2. Parallelize independent figure module setup (retain API compatibility).
  3. Debounce invalidations centrally, not per observer.
  4. 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):

  1. Regression test suite (test_layout_lifecycle.py, 6 tests)
  2. Explicit LayoutState enum and runtime state object
  3. Lifecycle events (layout-init-start, layout-cycle, layout-ready, layout-destroyed) and Sidenotes.whenReady()
  4. RAF-coalesced invalidate(reason) replacing direct reposition() calls
  5. Tracked listener registry with symmetric clearListeners() in cleanup
  6. Identity-dropdown migrated from polling to whenReady() + lifecycle events
  7. In-flight promise deduplication for identity.js async operations
  8. Fix for TOCTOU duplicate widget race (synchronous widgetInjected guard)

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):

  1. Static identity margin box — #identity-margin-box declared in article/index templates; identity-dropdown.js rewritten as pure data binding (~120 lines, down from ~185). _staticParent tracking ensures cleanup returns static boxes to their parent instead of removing them.
  2. HTMX swap boundary fix — <template id="injected-margin-boxes"> moved inside #article-swap so article-specific boxes update with swaps.
  3. Parallel pinned fetches — loadPinnedBoxes() refactored from sequential loop to Promise.allSettled with deterministic insertion order.
  4. Broader invalidation signals — ResizeObserver extended to margin columns; test wait_for_timeout calls replaced with wait_for_selector/wait_for_function.
  5. 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

  1. HTMX payload boundary changes can affect frontpage-nav assumptions.
  2. Listener cleanup mistakes can regress interactivity.
  3. 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