Self-Contained Interactive Margin Boxes
For Claude: REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
Goal: Make interactive margin boxes self-contained — JS, CSS, and content all live in the margin box’s own directory, loaded by convention rather than configuration.
Architecture: A generic loader discovers margin boxes with data-interactive, imports /static/margin-boxes/<slug>/code.js by convention, and calls setup(container). CSS lives in <style> blocks inside margin-box.md. The sync command auto-detects interactivity from the presence of assets/code.js. Two boxes are migrated: subscribe (already partially done) and identity (currently hardcoded in templates).
Tech Stack: ES modules, Django sync command, Playwright browser tests
Context for the Implementer
Directory Convention
Every interactive margin box follows this structure:
editorial/margin-boxes/<slug>/
├── margin-box.md ← content (markdown + YAML frontmatter) + <style> block
└── assets/
└── code.js ← ES module exporting setup(container)
The presence of assets/code.js is the sole signal that a margin box is interactive. No manifest file, no frontmatter flag needed.
Module Contract
export function setup(container) {
// container is the .margin-box DOM element
// server-rendered markdown content is already inside
// may read from window.* globals (platform services like AlmanackIdentity)
// must not set window.* globals
return () => { /* optional cleanup for HTMX teardown */ };
}
Platform Services
identity.js (sets window.AlmanackIdentity) stays in base.html as site-wide infrastructure. Margin box modules consume it but never provide globals.
Dev Symlinks
For make serve, assets must be symlinked:
mkdir -p assets/margin-boxes/<slug>
ln -sf ../../../editorial/margin-boxes/<slug>/assets/code.js assets/margin-boxes/<slug>/code.js
The build command (_copy_margin_box_assets) copies everything from editorial/margin-boxes/<slug>/assets/ to web/static/margin-boxes/<slug>/ automatically.
Key Files Reference
| File | Role |
|---|---|
assets/js/subscribe-box.js |
Current loader (to be rewritten) |
editorial/margin-boxes/subscribe/assets/subscribe.js |
Current subscribe module (to be renamed) |
editorial/margin-boxes/subscribe/assets/manifest.json |
Current manifest (to be deleted) |
assets/js/identity-dropdown.js |
Current identity UI (to become margin box code.js) |
assets/css/identity-dropdown.css |
Current identity CSS (to move into margin-box.md) |
src/almnck/templates/base.html:76-77 |
Loads identity-dropdown.js and subscribe-box.js |
src/almnck/templates/base.html:13 |
Loads identity-dropdown.css |
src/almnck/templates/units/article.html:85-87 |
Hardcoded identity margin box div |
src/almnck/templates/units/index.html:42-44 |
Hardcoded identity margin box div |
src/almnck/units/management/commands/sync_with_repo.py:411 |
Sets interactive from frontmatter |
src/almnck/units/management/commands/build_with_distill.py:122-141 |
Copies margin box assets |
src/tests/test_subscribe_box.py |
Browser tests for subscribe box |
Task 1: Rewrite the Loader
Rewrite assets/js/subscribe-box.js as a convention-based loader. No manifest fetch — just import code.js by slug.
Files:
- Modify: assets/js/subscribe-box.js (complete rewrite)
Step 1: Rewrite the loader
Replace the entire contents of assets/js/subscribe-box.js with:
// interactive-margin-boxes.js — Convention-based loader for interactive margin boxes
//
// For each .margin-box[data-interactive], imports /static/margin-boxes/<slug>/code.js
// and calls the module's setup(container) function.
//
// Convention: the module must be at assets/code.js inside the margin box's
// editorial directory. The build copies it to /static/margin-boxes/<slug>/code.js.
//
// CSS lives in <style> blocks inside margin-box.md (hoisted before setup runs).
// The module's setup() receives the .margin-box element as its container.
(function () {
'use strict';
// Track cleanup functions keyed by slug for HTMX teardown
var cleanups = {};
function initAll() {
var boxes = document.querySelectorAll('.margin-box[data-interactive]');
boxes.forEach(function (box) {
if (box.dataset.interactiveReady) return;
box.dataset.interactiveReady = '1';
var slug = box.dataset.slug;
if (!slug) return;
// Hoist <style> blocks so they survive innerHTML replacements in setup()
box.querySelectorAll('style').forEach(function (s) {
box.parentNode.insertBefore(s, box);
});
var moduleUrl = '/static/margin-boxes/' + slug + '/code.js';
import(moduleUrl)
.then(function (mod) {
if (mod && typeof mod.setup === 'function') {
var cleanup = mod.setup(box);
if (typeof cleanup === 'function') {
cleanups[slug] = cleanup;
}
}
})
.catch(function (err) {
console.error('Interactive margin box [' + slug + '] failed:', err);
});
});
}
function teardownAll() {
Object.keys(cleanups).forEach(function (slug) {
try {
cleanups[slug]();
} catch (e) {
console.error('Cleanup failed for [' + slug + ']:', e);
}
});
cleanups = {};
// Reset ready flags so boxes re-init after swap
document.querySelectorAll('.margin-box[data-interactive]').forEach(function (box) {
delete box.dataset.interactiveReady;
});
}
// Wait for sidenotes to position boxes before enhancing them
if (window.Sidenotes && window.Sidenotes.whenReady) {
window.Sidenotes.whenReady().then(initAll);
} else {
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initAll);
} else {
initAll();
}
}
// Re-init after HTMX swaps (frontpage navigation replaces #article-swap)
document.addEventListener('htmx:beforeSwap', teardownAll);
document.addEventListener('htmx:afterSettle', function () {
setTimeout(initAll, 100);
});
})();
Step 2: Verify the dev server still loads the script
Run: make serve (in background), visit http://localhost:1969/ in browser, check console for no errors from the loader. The subscribe box won’t work yet (module path changed) — that’s expected.
Step 3: Commit
git add assets/js/subscribe-box.js
git commit -m "Rewrite margin box loader: convention-based code.js, no manifest"
Task 2: Migrate Subscribe Margin Box
Rename subscribe.js to code.js, delete manifest.json, create dev symlinks.
Files:
- Rename: editorial/margin-boxes/subscribe/assets/subscribe.js → code.js
- Delete: editorial/margin-boxes/subscribe/assets/manifest.json
- Create symlink: assets/margin-boxes/subscribe/code.js
- Modify: editorial/margin-boxes/subscribe/assets/code.js (remove style-hoisting — loader does it now)
Step 1: Rename subscribe.js to code.js and delete manifest
cd editorial/margin-boxes/subscribe/assets
\mv subscribe.js code.js
\rm manifest.json
Step 2: Remove style-hoisting from code.js
The loader now hoists <style> blocks before calling setup(). Remove lines 33-36 from code.js (the container.querySelectorAll('style').forEach(...) block).
The setup() function should start directly with reading from the identity system:
export function setup(container) {
// Get whimsical name from identity system (may not be loaded yet)
const identity = window.AlmanackIdentity;
...
Step 3: Create dev symlink
mkdir -p assets/margin-boxes/subscribe
ln -sf ../../../editorial/margin-boxes/subscribe/assets/code.js assets/margin-boxes/subscribe/code.js
Remove any stale symlinks (like old subscribe.js or manifest.json) from assets/margin-boxes/subscribe/.
Step 4: Test
Run: make serve, visit an article page, verify:
- Subscribe form appears in the margin
- Console shows no errors
- Form submission works (use a test email or just verify the button works)
Run: make test to verify existing tests still pass.
Step 5: Commit
git add editorial/margin-boxes/subscribe/assets/code.js
git add assets/margin-boxes/subscribe/code.js
git commit -m "Subscribe margin box: rename to code.js, remove manifest"
Note: use git rm for the deleted manifest if git tracks it.
Task 3: Auto-Detect Interactivity in Sync
Make the sync command auto-detect interactive margin boxes by checking for assets/code.js instead of requiring a frontmatter field.
Files:
- Modify: src/almnck/units/management/commands/sync_with_repo.py:411
- Modify: editorial/margin-boxes/subscribe/margin-box.md (remove interactive: subscribe line)
Step 1: Update sync command
In sync_with_repo.py, replace line 411:
"interactive": frontmatter.get("interactive", ""),
With auto-detection logic. After the frontmatter is parsed (around line 397), before the defaults dict, add:
# Auto-detect interactivity from assets/code.js
code_js = mb_dir / "assets" / "code.js"
is_interactive = code_js.exists()
Then in the defaults dict:
"interactive": slug if is_interactive else "",
This sets interactive to the slug (e.g., “subscribe”) when code.js exists, regardless of frontmatter. The frontmatter interactive field is no longer needed.
Step 2: Remove frontmatter field from subscribe
Edit editorial/margin-boxes/subscribe/margin-box.md, remove line 8 (interactive: subscribe).
The frontmatter should be:
---
type: editorial
placement: right-top
priority: critical
pages: [articles, front]
weight: 70
active: true
wash: saffron
---
Step 3: Test sync
make sync
Verify output shows “Updated margin box: subscribe” and check the DB:
python src/manage.py shell -c "from almnck.units.models import MarginBox; print(MarginBox.objects.get(slug='subscribe').interactive)"
Expected output: subscribe
Step 4: Verify site still works
Run: make serve, visit an article page, confirm subscribe box loads and is interactive.
Step 5: Commit
git add src/almnck/units/management/commands/sync_with_repo.py
git add editorial/margin-boxes/subscribe/margin-box.md
git commit -m "Auto-detect interactive margin boxes from assets/code.js"
Task 4: Create Identity Margin Box Editorial Content
Create the identity margin box as a proper editorial margin box with content, styles, and code.
Files:
- Create: editorial/margin-boxes/identity/margin-box.md
- Create: editorial/margin-boxes/identity/assets/code.js
- Create symlink: assets/margin-boxes/identity/code.js
Step 1: Create margin-box.md
Create editorial/margin-boxes/identity/margin-box.md:
---
type: editorial
placement: left-top
priority: critical
pages: [articles, front]
weight: 100
active: true
---
<style>
/* Identity widget in margin box */
.margin-box[data-slug="identity"] .identity-widget {
display: block;
text-align: left;
font-size: 0.9em;
line-height: 1.4;
}
.margin-box[data-slug="identity"] .identity-greeting {
font-style: italic;
}
.margin-box[data-slug="identity"] .identity-name {
margin-top: 0.25em;
}
.margin-box[data-slug="identity"] .identity-balance {
margin-top: 0.25em;
}
.margin-box[data-slug="identity"] .identity-links {
margin-top: 0.5em;
font-size: 0.9em;
opacity: 0.85;
}
.margin-box[data-slug="identity"] .identity-links a {
white-space: nowrap;
}
#member-balance.negative {
color: var(--negative-color, #c00);
}
#member-balance.positive {
color: var(--positive-color, #080);
}
</style>
Welcome, compeer.
The static markdown (“Welcome, compeer.”) is the no-JS fallback, replaced by code.js once it runs.
Step 2: Create code.js
Create editorial/margin-boxes/identity/assets/code.js. This is adapted from assets/js/identity-dropdown.js, converted to an ES module with setup(container):
// code.js — Identity widget for margin box
//
// Populates the margin box with greeting, balance, and links.
// Reads from window.AlmanackIdentity (platform service loaded in base.html).
// Waits for noble-crypto-ready if crypto isn't loaded yet.
function formatBalance(balance) {
const sign = balance < 0 ? '\u2212' : '';
return sign + Math.abs(balance).toLocaleString();
}
function getTimeOfDay() {
const hour = new Date().getHours();
if (hour < 12) return 'morning';
if (hour < 17) return 'afternoon';
return 'evening';
}
function getCachedProfile() {
try {
const stored = localStorage.getItem('almanack:profile');
return stored ? JSON.parse(stored) : null;
} catch {
return null;
}
}
function buildWidgetHTML() {
const cached = getCachedProfile();
const name = cached?.name || '';
const parts = name.split(' ');
const firstname = parts[1] || parts[0] || '';
const balance = cached?.balance || 0;
return `
<div class="identity-widget">
<div class="identity-greeting">Good <span class="js-time-of-day">${getTimeOfDay()}</span>, <span class="js-member-firstname">${firstname}</span>.</div>
<div class="identity-name">For: <a href="/topup/" class="js-member-name">${name}</a></div>
<div class="identity-balance">Balance: <span id="member-balance" class="js-member-balance">${formatBalance(balance)}</span> \u24D0</div>
<div class="identity-links">
<a href="/topup/">Top Up</a> \u00b7
<a href="/topup/" class="js-work-link">${balance < 0 ? 'Work Off Debt' : 'Work'}</a> \u00b7
<a href="/topup/">Not <span class="js-member-name-short">${firstname || 'you'}</span>?</a>
</div>
</div>
`;
}
export function setup(container) {
container.innerHTML = buildWidgetHTML();
// DOM references (scoped to container, not document-wide IDs)
const nameEl = container.querySelector('.js-member-name');
const nameShortEl = container.querySelector('.js-member-name-short');
const firstnameEl = container.querySelector('.js-member-firstname');
const timeOfDayEl = container.querySelector('.js-time-of-day');
const balanceEl = container.querySelector('.js-member-balance');
const workLinkEl = container.querySelector('.js-work-link');
function updateUI() {
const Identity = window.AlmanackIdentity;
if (!Identity || !nameEl) return;
const name = Identity.getName();
const balance = Identity.getBalance();
nameEl.textContent = name;
const parts = name.split(' ');
const firstname = parts[1] || parts[0] || '';
if (nameShortEl) nameShortEl.textContent = firstname || 'you';
if (firstnameEl) firstnameEl.textContent = firstname;
if (timeOfDayEl) timeOfDayEl.textContent = getTimeOfDay();
if (balanceEl) {
balanceEl.textContent = formatBalance(balance);
balanceEl.classList.toggle('negative', balance < 0);
balanceEl.classList.toggle('positive', balance > 0);
}
if (workLinkEl) {
workLinkEl.textContent = balance < 0 ? 'Work Off Debt' : 'Work';
}
}
async function initialize() {
const Identity = window.AlmanackIdentity;
if (!Identity) {
console.warn('AlmanackIdentity not loaded');
return;
}
try {
await Identity.init();
updateUI();
const visitResult = await Identity.visit();
updateUI();
if (visitResult.jubilee) {
console.log('Jubilee day! No charge.');
}
} catch (err) {
console.error('Failed to initialize identity:', err);
}
}
function start() {
if (window.nobleEd25519) {
initialize();
} else {
window.addEventListener('noble-crypto-ready', function () { initialize(); }, { once: true });
}
}
const profileHandler = function () { updateUI(); };
window.addEventListener('almanack:profile-updated', profileHandler);
start();
// Cleanup for HTMX teardown
return function () {
window.removeEventListener('almanack:profile-updated', profileHandler);
};
}
Key changes from identity-dropdown.js:
- ES module with setup(container) export instead of IIFE
- Uses class selectors (.js-member-name) scoped to container instead of document-wide IDs
- Keeps id="member-balance" for the balance element (used by existing CSS #member-balance.negative)
- Returns cleanup function
- No longer searches for #identity-margin-box by ID — receives container directly
Step 3: Create dev symlink
mkdir -p assets/margin-boxes/identity
ln -sf ../../../editorial/margin-boxes/identity/assets/code.js assets/margin-boxes/identity/code.js
Step 4: Sync and verify
make sync
python src/manage.py shell -c "from almnck.units.models import MarginBox; b = MarginBox.objects.get(slug='identity'); print(b.interactive, b.placement, b.priority)"
Expected: identity left-top critical
Step 5: Commit
git add editorial/margin-boxes/identity/
git add assets/margin-boxes/identity/code.js
git commit -m "Create identity as self-contained interactive margin box"
Task 5: Remove Hardcoded Identity From Templates
Remove the hardcoded identity div from templates and the identity-dropdown.js/css from base.html.
Files:
- Modify: src/almnck/templates/units/article.html:85-87 (remove identity div)
- Modify: src/almnck/templates/units/index.html:42-44 (remove identity div)
- Modify: src/almnck/templates/base.html:13 (remove identity-dropdown.css link)
- Modify: src/almnck/templates/base.html:76 (remove identity-dropdown.js script)
- Delete: assets/js/identity-dropdown.js
- Delete: assets/css/identity-dropdown.css
Step 1: Remove hardcoded identity div from article.html
In src/almnck/templates/units/article.html, remove lines 85-87:
<div class="margin-box" id="identity-margin-box"
data-type="editorial"
data-margin="left-top-high"></div>
The closing </div> for margins-layout (previously after the identity div) stays.
Step 2: Remove hardcoded identity div from index.html
In src/almnck/templates/units/index.html, remove lines 42-44 (same div).
Step 3: Remove identity-dropdown.css from base.html
In src/almnck/templates/base.html, remove line 13:
<link rel="stylesheet" href="{% cdnstatic 'css/identity-dropdown.css' %}">
Step 4: Remove identity-dropdown.js from base.html
In src/almnck/templates/base.html, remove line 76:
<script src="{% cdnstatic 'js/identity-dropdown.js' %}" defer></script>
Step 5: Rename subscribe-box.js reference in base.html
While we’re here, the script tag on line 77 still says subscribe-box.js. The file itself has been rewritten as a generic loader. Consider whether to rename the file to interactive-margin-boxes.js and update this reference. If renaming:
In base.html, change:
<script src="{% cdnstatic 'js/subscribe-box.js' %}" defer></script>
to:
<script src="{% cdnstatic 'js/interactive-margin-boxes.js' %}" defer></script>
And rename the file:
\mv assets/js/subscribe-box.js assets/js/interactive-margin-boxes.js
Step 6: Delete old files
\rm assets/js/identity-dropdown.js
\rm assets/css/identity-dropdown.css
Step 7: Test
make sync && make serve
Visit an article page. Verify: - Identity widget appears in the left margin (now loaded as a margin box, not hardcoded) - Subscribe form appears in the right margin - Both work correctly - Console has no errors
Run: make test
Step 8: Commit
git add -A src/almnck/templates/
git add assets/js/interactive-margin-boxes.js
git commit -m "Remove hardcoded identity box, load via margin box convention"
Note: also git rm the deleted files (identity-dropdown.js, identity-dropdown.css, and subscribe-box.js if renamed).
Task 6: Handle Identity-Dropdown CSS Used Outside Margin Box
Some styles in identity-dropdown.css are used by elements outside the margin box (the masthead pricing, dropdown menu, etc.). Check whether any remain needed.
Files:
- Possibly modify: assets/css/almanack.css (absorb any non-margin-box styles)
Step 1: Audit identity-dropdown.css usage
Search for class names from identity-dropdown.css across templates and JS:
grep -r "identity-dropdown\|identity-pricing\|identity-trigger\|dropdown-menu\|dropdown-arrow\|not-you-link\|balance-display\|frontispiece-wrapper" src/almnck/templates/ assets/js/
Check which selectors are used outside the margin box context:
- .identity-pricing — used in base.html:39 (masthead area)
- .frontispiece-wrapper — used in base.html:35
Step 2: Move non-margin-box styles to almanack.css
Any styles from identity-dropdown.css that apply to elements outside the margin box (like .identity-pricing and .frontispiece-wrapper) must be moved to almanack.css since they can’t live in the margin box’s <style> block.
Add them to an appropriate section of almanack.css (near masthead styles).
Step 3: Test the masthead still renders correctly
Run: make serve, verify the price display and frontispiece wrapper look correct.
Step 4: Commit
git add assets/css/almanack.css
git commit -m "Move non-margin-box identity styles to almanack.css"
Task 7: Update Browser Tests
Update existing subscribe box tests and add identity margin box tests.
Files:
- Modify: src/tests/test_subscribe_box.py (verify tests still pass as-is)
- Create: src/tests/test_identity_margin_box.py
Step 1: Run existing subscribe tests
make test-browser
The existing test_subscribe_box.py tests should pass without changes since they find elements by [data-slug="subscribe"], not by script path.
Step 2: Write identity margin box test
Create src/tests/test_identity_margin_box.py:
"""Browser tests for the identity margin box.
Tests verify:
- The identity margin box appears on article pages (loaded via convention)
- The identity widget populates with greeting and balance
- No hardcoded identity div exists outside #article-swap
"""
import pytest
pytestmark = pytest.mark.browser
ARTICLE_URL = "/5921/2/13/kropotkins-funeral/"
class TestIdentityMarginBox:
"""Test the identity margin box renders via the interactive loader."""
def test_identity_box_appears(self, browser, dev_server_url):
"""Identity margin box is present on article pages."""
page = browser.new_page()
page.goto(dev_server_url + ARTICLE_URL)
page.wait_for_function("window.Sidenotes?.whenReady")
page.evaluate("() => window.Sidenotes.whenReady()")
box = page.query_selector('[data-slug="identity"]')
assert box is not None, "Identity margin box not found"
page.close()
def test_identity_widget_populates(self, browser, dev_server_url):
"""Identity widget builds its UI inside the margin box."""
page = browser.new_page()
page.goto(dev_server_url + ARTICLE_URL)
page.wait_for_function("window.Sidenotes?.whenReady")
page.evaluate("() => window.Sidenotes.whenReady()")
# Wait for the interactive module to enhance the box
page.wait_for_selector('[data-slug="identity"] .identity-widget',
timeout=5000)
box = page.query_selector('[data-slug="identity"]')
widget = box.query_selector('.identity-widget')
assert widget is not None, "Identity widget not built"
# Should have greeting, balance, and links
assert box.query_selector('.identity-greeting') is not None
assert box.query_selector('.identity-balance') is not None
assert box.query_selector('.identity-links') is not None
page.close()
def test_no_hardcoded_identity_div(self, browser, dev_server_url):
"""No hardcoded #identity-margin-box div exists outside the margin box system."""
page = browser.new_page()
page.goto(dev_server_url + ARTICLE_URL)
hardcoded = page.query_selector('#identity-margin-box')
assert hardcoded is None, "Hardcoded #identity-margin-box should be removed"
page.close()
Step 3: Run all tests
make test
make test-browser
All tests should pass.
Step 4: Commit
git add src/tests/test_identity_margin_box.py
git commit -m "Add browser tests for identity margin box"
Task 8: Create the Skill Document
Create a skill for future interactive margin box creation.
Files:
- Create: .claude/skills/interactive-margin-boxes/SKILL.md
Step 1: Write the skill
Create .claude/skills/interactive-margin-boxes/SKILL.md:
---
name: interactive-margin-boxes
description: >-
Use when creating a new interactive margin box or modifying an existing one.
Covers the directory convention, module contract, CSS scoping, dev symlinks,
and integration with the sync/build pipeline. Invoke when the user asks to
add interactivity to a margin box, create a new interactive margin box, or
debug why a margin box's code.js isn't loading.
---
# Creating an Interactive Margin Box
Interactive margin boxes are self-contained editorial components that run
their own JavaScript. They follow a strict convention-based loading pattern
— no manifest files or configuration needed.
## Directory Structure
editorial/margin-boxes/