Manual
Almnck.
Price: 50ⓐ

Layout Control Flow Refactor Implementation Plan

For Claude: REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.

Goal: Replace timing/retry-driven layout coordination with an explicit lifecycle and invalidation model for sidenotes, margin-box injection, HTMX swaps, and identity widget coupling.

Architecture: Introduce a small orchestrator inside sidenotes.js with explicit state and lifecycle events, then migrate consumers (identity-dropdown.js, swap handling, observers) to event-driven coordination. Keep window.Sidenotes and figure module APIs compatible while removing polling loops and reducing correctness-critical timeouts.

Tech Stack: Vanilla JavaScript, HTMX, Django templates, Playwright+pytest integration tests.

Design Document: doc/process/plans/2026-02-11-layout-control-flow-design.md

Wave 1 (COMPLETE — merged to main)

9 commits on refactor/layout-lifecycle, all tests green:

  1. Regression test suite (test_layout_lifecycle.py, 6 tests)
  2. Explicit LayoutState enum and runtime state object
  3. Lifecycle events and Sidenotes.whenReady()
  4. RAF-coalesced invalidate(reason) scheduler
  5. Tracked listener registry with symmetric cleanup
  6. Identity-dropdown migrated from polling to lifecycle events
  7. In-flight promise deduplication for identity.js
  8. Fix for TOCTOU duplicate widget race

Wave 2 Scope

Wave 2 addresses the remaining findings from the design document:

  • Identity as static margin box — eliminate runtime injection entirely (NEW, replaces old Phase 3 approach)
  • HTMX swap boundary fix — article-specific injected boxes go stale after swap
  • Performance — parallelize pinned fragment loading, reduce timeout-based correctness
  • Documentation and verification

Key insight from Wave 1: the identity widget was the only margin box managing its own lifecycle via injectMarginBox(). Making it a static HTML element eliminates an entire class of timing bugs and simplifies the HTMX boundary problem (identity no longer needs re-injection after swaps).


Phase 4: Identity Widget as Static Margin Box

Task 1: Add identity shell to base template and simplify identity-dropdown.js

Files: - Modify: src/almnck/templates/base.html - Modify: src/almnck/templates/units/article.html - Modify: src/almnck/templates/units/index.html - Modify: assets/js/identity-dropdown.js - Modify: assets/css/identity-dropdown.css (if needed) - Test: src/tests/test_layout_lifecycle.py

Step 1: Add empty identity shell to article templates

In article.html (and index.html), add a static margin box inside .margins-layout but outside #article-swap. Place it just before the closing </div> of .margins-layout:

<div class="margins-layout">
    <aside class="margin margin-left"></aside>
    <article id="article-swap" class="body-text">
        ...
    </article>
    <aside class="margin margin-right"></aside>
    <!-- Identity widget: static shell, populated by identity-dropdown.js -->
    <div class="margin-box" id="identity-margin-box"
         data-type="editorial"
         data-margin="left-top-high">
    </div>
</div>

This placement means: - collectMarginBoxes() finds it via document.querySelectorAll('.margin-box') - It’s outside #article-swap, so HTMX swaps don’t destroy it - positionMarginBoxes() handles its layout like any other box

Step 2: Rewrite identity-dropdown.js as data-binding script

Strip out all injection and lifecycle coordination. The new structure:

(function(global) {
  'use strict';

  // ... formatBalance, getTimeOfDay, getCachedProfile unchanged ...

  function populateWidget() {
    const shell = document.getElementById('identity-margin-box');
    if (!shell) return;

    // Build inner HTML (same buildWidgetHTML, but targeting the shell)
    shell.innerHTML = buildWidgetHTML();
    wireUpWidget();
  }

  function wireUpWidget() {
    // ... same updateUI logic, find elements by ID, bind data ...
  }

  function updateUI() {
    // ... same as current: read from AlmanackIdentity, write to DOM ...
  }

  async function initialize() {
    const Identity = global.AlmanackIdentity;
    if (!Identity) return;
    await Identity.init();
    updateUI();
    const result = await Identity.visit();
    updateUI();
  }

  // Listen for profile updates
  window.addEventListener('almanack:profile-updated', updateUI);

  // Populate shell when crypto is ready (no layout dependency needed)
  function start() {
    populateWidget();
    initialize();
  }

  function waitForCryptoAndStart() {
    if (window.nobleEd25519) {
      start();
    } else {
      window.addEventListener('noble-crypto-ready', start, { once: true });
    }
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', waitForCryptoAndStart);
  } else {
    waitForCryptoAndStart();
  }

})(window);

Key removals: - injectMarginBox() call - whenReady() dependency - layout-ready re-injection listener - layout-destroyed flag reset - widgetInjected flag - Double-RAF dance waiting for DOM node

Step 3: Verify no duplicate widget test still passes

The duplicate-widget test should now be trivially satisfied (only one #identity-margin-box in the HTML, never injected at runtime).

source bin/a-activate && pytest src/tests/test_layout_lifecycle.py -v

Step 4: Update duplicate-widget tests

The test assertions may need updating: - Change #identity-widget selectors to #identity-margin-box (or keep inner #identity-widget if the shell contains it) - The TOCTOU-specific test can become a simpler “widget exists and is unique” check

Step 5: Verify on dev server

source bin/a-activate && make serve

Check: identity widget appears, shows cached data immediately, updates after crypto init, survives HTMX article swaps.

Step 6: Commit

git add src/almnck/templates/ assets/js/identity-dropdown.js src/tests/test_layout_lifecycle.py
git commit -m "refactor(identity): make identity widget a static margin box in templates"

Phase 5: HTMX Swap Boundary for Article-Specific Injected Boxes

Task 2: Ensure injected margin-box template updates with article swaps

Files: - Modify: src/almnck/templates/units/article.html - Modify: src/almnck/templates/units/index.html - Modify: assets/js/sidenotes.js (reinitialize trigger) - Test: src/tests/test_layout_lifecycle.py

Step 1: Move <template id="injected-margin-boxes"> inside #article-swap

Currently the template is outside .margins-layout, so HTMX swaps don’t replace it. Move it inside #article-swap so it gets swapped with the article content:

<article id="article-swap" class="body-text">
    {% include "partials/_article_header.html" with item=unit %}
    <div class="maintext">
        {{ content|safe }}
    </div>
    {% if margin_boxes %}
    <template id="injected-margin-boxes">
      {% for box in margin_boxes %}
      ...
      {% endfor %}
    </template>
    {% endif %}
</article>

This is the simplest fix: the swap payload already uses hx-select="#article-swap", so the template comes along for free.

Step 2: Verify extractInjectedBoxes() still finds the template

Check that extractInjectedBoxes() uses document.getElementById('injected-margin-boxes') (not scoped to a specific parent). It should work regardless of template location.

Step 3: Run the margin-box refresh test

source bin/a-activate && pytest src/tests/test_layout_lifecycle.py::TestMarginBoxRefresh -v

This test currently checks that sidenotes stay enabled after swap. Extend it to verify that injected margin boxes actually correspond to the new article’s boxes (compare slugs before and after swap).

Step 4: Commit

git add src/almnck/templates/ assets/js/sidenotes.js src/tests/test_layout_lifecycle.py
git commit -m "fix(layout): include injected margin-box template in HTMX swap boundary"

Phase 6: Performance and Reflow Robustness

Task 3: Parallelize pinned fragment loading

Files: - Modify: assets/js/sidenotes.js - Test: src/tests/test_layout_lifecycle.py

Step 1: Refactor loadPinnedBoxes() to use Promise.allSettled

Replace sequential fetch loop with concurrent loading. Preserve deterministic insertion order by sorting results by original slug list position.

Step 2: Verify failure handling unchanged

404s and network errors should remain non-fatal (same as current behavior).

Step 3: Run tests

source bin/a-activate && pytest src/tests/test_layout_lifecycle.py -v

Step 4: Commit

git add assets/js/sidenotes.js
git commit -m "perf(layout): parallelize pinned margin-box fragment fetching"

Task 4: Reduce timeout-based correctness dependencies

Files: - Modify: assets/js/sidenotes.js - Modify: src/tests/test_layout_lifecycle.py - Modify: src/tests/test_mobile_margins.py - Modify: src/tests/test_margin_box_overlap.py

Step 1: Extend observation to margin columns

Add ResizeObserver coverage beyond .maintext to catch layout-affecting changes in margin containers.

Step 2: Replace correctness-critical setTimeout where feasible

Audit remaining setTimeout calls. Replace those used as correctness gates with condition-based approaches (e.g., scrollend event, bounded position polling with invalidation).

Step 3: Update test helpers to use selector/state waits instead of wait_for_timeout

Where tests use page.wait_for_timeout(N), replace with page.wait_for_selector or page.wait_for_function where possible.

Step 4: Run mobile and layout suites

source bin/a-activate && pytest src/tests/test_mobile_margins.py src/tests/test_margin_box_overlap.py -v
source bin/a-activate && pytest src/tests/test_layout_lifecycle.py -v

Step 5: Commit

git add assets/js/sidenotes.js src/tests/
git commit -m "refactor(layout): broaden invalidation signals and reduce timeout-based correctness"

Phase 7: Documentation and Final Verification

Task 5: Update technical documentation

Files: - Modify: doc/website/02-site-design.md or doc/website/04-figures.md (margin box docs) - Modify: doc/website/05-membership-api.md (identity event model)

Step 1: Document Sidenotes.whenReady() and lifecycle events

Add section covering the event contract, state machine, and how to use whenReady() for new consumers.

Step 2: Document identity as static margin box

Explain that the identity widget is a declared margin box in the template, populated by identity-dropdown.js. Note that injectMarginBox() is reserved for truly dynamic content.

Step 3: Run doc tests

source bin/a-activate && make test-doc

Step 4: Commit

git add doc/
git commit -m "docs(layout): document lifecycle contracts and static identity margin box"

Task 6: Final verification matrix

Files: - No code changes unless failures discovered.

Step 1: Run all test suites

source bin/a-activate && make test
source bin/a-activate && pytest src/tests/test_layout_lifecycle.py -v
source bin/a-activate && pytest src/tests/test_mobile_margins.py src/tests/test_margin_box_overlap.py -v

Step 2: Manual sanity check on dev server

Open frontpage, perform multiple HTMX swaps, verify: - Identity widget persists and shows correct data - Article-specific margin boxes update after swap - No console errors - Permalink interactions work - Fragment navigation works

Step 3: Commit only if follow-up fixes were needed


Execution Notes

  • Keep all public window.Sidenotes methods API-compatible.
  • Do not change figure module setup(container, capabilities) contract.
  • Land each task as an isolated commit for easy rollback.
  • The identity static-box change (Task 1) should land first — it simplifies testing for subsequent tasks.