Non-Article Margin Box Injection
Date: 2026-01-18 Status: Design complete, ready for implementation
Overview
Implement a system for injecting margin boxes that exist independently of articles—editorial asides, promotional content, ambient decoration—into pages across the site. These boxes participate in the existing sidenotes.js positioning system alongside article-native margin content.
Content Structure
Margin boxes live in editorial/margin-boxes/, organized freely with recursive directory walking:
editorial/margin-boxes/
subscriber-cta/
margin-box.md
site-announcement/
margin-box.md
aphorisms/ ← grouping directory (no margin-box.md)
cicero-friendship/
margin-box.md
seneca-time/
margin-box.md
assets/
hourglass.svg
promos/
merch-tshirt/
margin-box.md
assets/
shirt-thumb.png
Sync behavior: Walk editorial/margin-boxes/ recursively. If a directory contains margin-box.md, it’s a margin box unit—ingest it. If it contains only subdirectories (no primary document), keep walking.
Frontmatter Schema
---
type: aphorism # quote | ad | aphorism | poem | editorial | announcement
placement: right-top # left|right + top|bottom|near, or "any"
priority: normal # critical | high | normal | low
pages: [front, articles] # front | articles | pages | all
tags: [stoicism, featured] # arbitrary tags for filtering/organization
weight: 50 # selection weight (higher = more likely)
active: true # quick toggle without deleting
starts: 2026-01-01 # optional: don't show before this date
expires: 2026-03-01 # optional: stop showing after this date
interactive: counter # optional: ES module name for interactivity
publishes: [event-name] # optional: pub/sub events this box emits
subscribes: [other-event] # optional: pub/sub events this box listens to
---
*Time discovers truth.*
— Seneca
Selection Logic
Filtering
A margin box is eligible for a page if:
- active: true
- Current date is within starts/expires range (if specified)
- pages array includes this page type (front, articles, pages, or all)
Count Determination
- Default: 3 boxes per page (configurable in Django settings)
- Per-page override: Articles/pages can specify
margin-box-count: Nin frontmatter - Disable:
margin-box-count: 0suppresses all injected boxes
Seeded Pseudo-Random Selection
Selection uses a deterministic seed for build stability:
| Page Type | Seed |
|---|---|
| Front page | page_path + today's_date |
| Article | page_path + (last_frontpage_date or almanac_day) |
| Static page | page_path only (no date component) |
Algorithm:
1. Hash the seed to get a random state
2. From eligible boxes, randomly select N boxes weighted by weight field
3. Exception: priority: critical boxes bypass selection—always included if eligible
Result: Same inputs produce same outputs. Front page shuffles daily. Articles have stable marginalia. Static pages are completely stable.
Priority and Placement
Priority Tiers (highest to lowest)
- Critical injected boxes (
priority: critical) — Site emergencies, live announcements - Article sidenotes — Footnotes anchored to their references, positionally constrained
- Article-native margin boxes — The article’s own decorative margin content
- High-priority injected boxes (
priority: high) — Important but defers to article content - Normal/low injected boxes — Ambient decoration, fills remaining space
Placement Algorithm
Boxes declare preferences via data-margin attribute (e.g., right-top-normal). The existing sidenotes.js algorithm:
- Places higher-priority items first in their preferred positions
- Lower-priority items find best available position in remaining space
priority: lowboxes are most flexible—displaced if space is tight
Django Integration
New Model: MarginBox
class MarginBox(models.Model):
source_path = models.CharField(max_length=500, unique=True)
slug = models.SlugField(max_length=200)
content = models.TextField() # Rendered HTML
frontmatter = models.JSONField(default=dict)
# Denormalized from frontmatter for querying
box_type = models.CharField(max_length=50)
priority = models.CharField(max_length=20, default='normal')
weight = models.IntegerField(default=50)
active = models.BooleanField(default=True)
starts = models.DateField(null=True, blank=True)
expires = models.DateField(null=True, blank=True)
pages = models.JSONField(default=list) # ['front', 'articles', etc.]
tags = models.JSONField(default=list)
# Interactive features
interactive = models.CharField(max_length=100, blank=True)
publishes = models.JSONField(default=list)
subscribes = models.JSONField(default=list)
Sync Extension
The sync_with_repo management command gains a new phase:
- Walk
editorial/margin-boxes/recursively - For each
margin-box.mdfound, parse frontmatter and content - Render markdown to HTML
- Upsert into
MarginBoxmodel - Delete
MarginBoxrecords whose source paths no longer exist
View Helper
def select_margin_boxes(page_type, seed_date, page_path, count=3):
"""
Select margin boxes for a page using seeded random selection.
Args:
page_type: 'front', 'article', or 'page'
seed_date: Date for randomization seed (None for path-only seed)
page_path: URL path of the page
count: Number of boxes to select (0 to disable)
Returns:
List of MarginBox instances
"""
# Filter eligible boxes
eligible = MarginBox.objects.filter(active=True)
eligible = eligible.filter(
Q(pages__contains='all') | Q(pages__contains=page_type)
)
today = date.today()
eligible = eligible.filter(
Q(starts__isnull=True) | Q(starts__lte=today)
).filter(
Q(expires__isnull=True) | Q(expires__gte=today)
)
# Critical boxes always included
critical = list(eligible.filter(priority='critical'))
# Seed the random selection
seed_string = page_path + (str(seed_date) if seed_date else '')
seed = int(hashlib.sha256(seed_string.encode()).hexdigest()[:8], 16)
rng = random.Random(seed)
# Weighted random selection for remaining slots
remaining = list(eligible.exclude(priority='critical'))
selected = weighted_sample(remaining, count - len(critical), rng)
return critical + selected
Template Context
Views pass selected boxes to templates:
def article_detail(request, path):
article = get_object_or_404(Unit, output_path=path, status='published')
seed_date = article.last_frontpage_date or article.almanac_day
count = article.frontmatter.get('margin-box-count', 3)
margin_boxes = select_margin_boxes('article', seed_date, path, count)
return render(request, 'units/article.html', {
'item': article,
'margin_boxes': margin_boxes,
})
Template Integration
Injected Box Rendering
<!-- In article.html / index.html -->
<div class="margins-layout">
<div class="margin margin-left"></div>
<article class="maintext">
{{ content|safe }}
</article>
<div class="margin margin-right"></div>
</div>
<!-- Injected margin boxes (hidden until positioned by JS) -->
<template id="injected-margin-boxes">
{% for box in margin_boxes %}
<div class="margin-box margin-box-injected"
data-type="{{ box.box_type }}"
data-margin="{{ box.placement }}-{{ box.priority }}"
data-injected="true"
{% if box.interactive %}data-interactive="{{ box.interactive }}"{% endif %}
{% if box.publishes %}data-publishes="{{ box.publishes|join:',' }}"{% endif %}
{% if box.subscribes %}data-subscribes="{{ box.subscribes|join:',' }}"{% endif %}>
{{ box.content|safe }}
</div>
{% endfor %}
</template>
Sidenotes.js extracts boxes from the <template>, positions them in margins, and initializes interactive modules.
No-JS Fallback
Without JavaScript, <template> content is hidden by default. Ambient marginalia is treated as an enhancement—acceptable to omit for no-JS users.
Interactivity
ES Module Pattern
Interactive margin boxes follow the same pattern as article figures:
editorial/margin-boxes/live-subscriber-count/
margin-box.md
assets/
counter.js
Module interface:
// counter.js
export const meta = {
name: 'counter',
description: 'Live subscriber count display',
version: '1.0.0'
};
export function setup(container, { publish, subscribe }) {
// Initialize the interactive component
// container: the margin-box DOM element
// publish(event, data): emit to pub/sub bus
// subscribe(event, callback): listen to pub/sub bus
}
Pub/Sub Integration
Margin box modules connect to the same pub/sub bus as article figures:
- Margin boxes can communicate with each other
- Margin boxes can communicate with article figures
- Article figures can communicate with margin boxes
The shared bus lives at window.AlmanackPubSub (or integrated into the existing figure runtime).
Client-Side API
For dynamic injection (HTMX, WebSocket, etc.), sidenotes.js exposes:
window.Sidenotes = {
/**
* Inject a new margin box at runtime
* @returns {string} Box ID for later removal
*/
injectMarginBox({
content, // HTML string
type, // 'quote', 'ad', 'aphorism', etc.
placement, // 'right-top', 'left-bottom', 'any'
priority, // 'critical', 'high', 'normal', 'low'
interactive, // Optional module name
publishes, // Optional array of event names
subscribes // Optional array of event names
}),
/**
* Force reposition of all margin content
*/
reposition(),
/**
* Remove a dynamically injected box
* @param {string} id - Box ID returned from injectMarginBox
*/
removeMarginBox(id)
};
Reader-Pinned Margin Boxes
Readers can “pin” margin boxes to always appear on pages they view, persisting across sessions.
Storage
Pinned box slugs stored in localStorage:
// Key: 'almanack-pinned-margin-boxes'
// Value: JSON array of slugs
["seneca-time", "cicero-friendship", "subscriber-cta"]
Priority Tier
Pinned boxes slot in just below critical:
- Critical injected boxes — Site emergencies
- Reader-pinned boxes — Personal selections ← NEW
- Article sidenotes — Anchored footnotes
- Article-native margin boxes — The article’s own content
- High-priority injected boxes — Important site content
- Normal/low injected boxes — Ambient decoration
Integration with Build-Time Selection
Each margin box is distilled to a static HTML fragment:
/margin-boxes/
seneca-time.html
cicero-friendship.html
promo-spring.html
...
Each fragment is a complete margin box element ready for injection:
<!-- /margin-boxes/seneca-time.html -->
<div class="margin-box"
data-slug="seneca-time"
data-type="aphorism"
data-margin="right-top-normal">
<em>Time discovers truth.</em>
— Seneca
</div>
At runtime, sidenotes.js:
1. Processes inline selected boxes from <template> (as before)
2. Reads pinned slugs from localStorage
3. For pinned boxes not already inline, fetches /margin-boxes/{slug}.html
4. Injects pinned boxes at high priority
async function loadPinnedBoxes() {
const pinned = getPinnedBoxes(); // from localStorage
const inlineSlugs = getInlineSlugs(); // from <template>
for (const slug of pinned) {
if (!inlineSlugs.includes(slug)) {
const resp = await fetch(`/margin-boxes/${slug}.html`);
if (resp.ok) {
const html = await resp.text();
injectMarginBox(html, { pinned: true, priority: 'pinned' });
}
// 404 = box expired or deleted, silently skip
}
}
}
If a pinned box is also in the selected list, it only appears once (marked as pinned, gets unpin affordance).
Unpin Affordance
Only pinned boxes display an unpin control — a small × or pushpin icon in the corner:
<div class="margin-box margin-box-pinned" data-slug="seneca-time">
<button class="margin-box-unpin" aria-label="Unpin this box">📌</button>
<em>Time discovers truth.</em>
— Seneca
</div>
.margin-box-unpin {
position: absolute;
top: 0.25em;
right: 0.25em;
opacity: 0.4;
font-size: 0.75rem;
background: none;
border: none;
cursor: pointer;
}
.margin-box-unpin:hover {
opacity: 1;
}
/* Only pinned boxes have the unpin button */
.margin-box:not(.margin-box-pinned) .margin-box-unpin {
display: none;
}
Non-pinned boxes have no UI chrome — they appear as pure content.
Client-Side API Extension
window.Sidenotes = {
// ... existing methods ...
/**
* Pin a margin box by slug (persists to localStorage)
*/
pinMarginBox(slug),
/**
* Unpin a margin box by slug
*/
unpinMarginBox(slug),
/**
* Get array of currently pinned slugs
*/
getPinnedBoxes(),
/**
* Check if a specific box is pinned
*/
isBoxPinned(slug)
};
Pinning Mechanism
Out of scope for this design. The mechanism for initially pinning a box (gallery page, member dashboard, contextual gesture, etc.) will be designed separately. This design covers only:
- Storage format
- Priority integration
- Runtime injection of pinned boxes
- Unpin affordance on already-pinned boxes
Summary
| Aspect | Decision |
|---|---|
| Content location | editorial/margin-boxes/ with recursive walking |
| Structure | One directory per box, margin-box.md + optional assets/ |
| Frontmatter | type, placement, priority, pages, tags, weight, active, starts, expires, interactive, publishes, subscribes |
| Selection | Seeded pseudo-random; seed = page_path + contextual date |
| Seed dates | Front page: today. Articles: last frontpage or almanac-day. Static pages: path only |
| Count | Default 3, per-page override via margin-box-count |
| Priority tiers | critical → reader-pinned → sidenotes → article boxes → high injected → normal/low |
| Injection | Build-time via Django template + static fragments at /margin-boxes/{slug}.html + client-side API |
| Interactivity | ES modules with pub/sub, same pattern as figures |
| Reader pinning | localStorage slugs, fetch /margin-boxes/{slug}.html on demand, unpin affordance only on pinned boxes |
Next Steps
- Create
MarginBoxmodel and migration - Extend
sync_with_repoto walkeditorial/margin-boxes/ - Add
select_margin_boxes()helper function - Update views to pass margin boxes to templates
- Add
<template id="injected-margin-boxes">to templates - Extend sidenotes.js to process injected boxes and expose public API
- Integrate with existing pub/sub for interactive boxes
- Create sample margin boxes for testing
- Distill individual margin box HTML fragments to
/margin-boxes/{slug}.html - Implement localStorage pinning, fetch-on-demand, and unpin affordance in sidenotes.js
- Design pinning mechanism (separate design doc)