Margin Box Injection Implementation Plan
For Claude: REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
Goal: Implement a system for injecting margin boxes (editorial asides, promotions, aphorisms) into pages across the site, participating in the existing sidenotes.js positioning system.
Architecture: New MarginBox Django model synced from editorial/margin-boxes/. Views select boxes using seeded pseudo-random selection. Boxes render via <template> element, extracted and positioned by sidenotes.js. Static HTML fragments enable client-side pinning.
Tech Stack: Django 5.0, Python-Markdown, sidenotes.js (vanilla JS), localStorage for pinning
Phase 1: Model and Migration
Task 1.1: Write MarginBox Model Test
Files:
- Create: src/tests/test_margin_box_model.py
Step 1: Write the failing test
"""Tests for MarginBox model."""
import pytest
from django.utils import timezone
from datetime import date, timedelta
@pytest.mark.django_db
class TestMarginBoxModel:
def test_create_margin_box(self):
"""Can create a basic margin box."""
from almnck.units.models import MarginBox
box = MarginBox.objects.create(
source_path='margin-boxes/test-box',
slug='test-box',
content='<p>Test content</p>',
box_type='aphorism',
priority='normal',
weight=50,
active=True,
pages=['articles'],
)
assert box.slug == 'test-box'
assert box.box_type == 'aphorism'
assert box.active is True
def test_margin_box_date_filtering(self):
"""Boxes respect starts/expires dates."""
from almnck.units.models import MarginBox
today = date.today()
yesterday = today - timedelta(days=1)
tomorrow = today + timedelta(days=1)
# Active box (no date restrictions)
active = MarginBox.objects.create(
source_path='margin-boxes/active',
slug='active',
content='Active',
box_type='quote',
active=True,
pages=['all'],
)
# Expired box
expired = MarginBox.objects.create(
source_path='margin-boxes/expired',
slug='expired',
content='Expired',
box_type='quote',
active=True,
expires=yesterday,
pages=['all'],
)
# Future box
future = MarginBox.objects.create(
source_path='margin-boxes/future',
slug='future',
content='Future',
box_type='quote',
active=True,
starts=tomorrow,
pages=['all'],
)
# Query for currently valid boxes
valid = MarginBox.objects.filter(active=True).filter(
starts__isnull=True
) | MarginBox.objects.filter(active=True, starts__lte=today)
valid = valid.filter(
expires__isnull=True
) | valid.filter(expires__gte=today)
slugs = list(valid.values_list('slug', flat=True))
assert 'active' in slugs
assert 'expired' not in slugs
assert 'future' not in slugs
Step 2: Run test to verify it fails
Run: make test
Expected: FAIL with “No module named ‘almnck.units.models.MarginBox’” or similar
Step 3: Write the MarginBox model
Modify: src/almnck/units/models.py
Add after the Unit model class:
class MarginBox(models.Model):
"""An injectable margin box for editorial asides, promotions, etc."""
# File system location (relative to editorial/)
source_path = models.CharField(max_length=500, unique=True)
slug = models.SlugField(max_length=200)
# Rendered content
content = models.TextField() # Rendered HTML
frontmatter = models.JSONField(default=dict)
# Denormalized from frontmatter for querying
box_type = models.CharField(max_length=50) # quote, ad, aphorism, poem, editorial, announcement
placement = models.CharField(max_length=50, default='any') # right-top, left-bottom, any
priority = models.CharField(max_length=20, default='normal') # critical, high, normal, low
weight = models.IntegerField(default=50) # Selection weight (higher = more likely)
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', 'pages', 'all']
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 tracking
file_hash = models.CharField(max_length=64, blank=True)
last_synced = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['-weight', 'slug']
def __str__(self):
return f"{self.slug} ({self.box_type})"
Step 4: Create and run migration
Run: cd src && python manage.py makemigrations units --name margin_box
Run: cd src && python manage.py migrate
Expected: Migration created and applied successfully
Step 5: Run test to verify it passes
Run: make test
Expected: PASS
Step 6: Commit
git add src/almnck/units/models.py src/almnck/units/migrations/ src/tests/test_margin_box_model.py
git commit -m "feat: add MarginBox model for injectable margin content"
Phase 2: Sync Extension
Task 2.1: Write Sync Test for Margin Boxes
Files:
- Create: src/tests/test_sync_margin_boxes.py
Step 1: Write the failing test
"""Tests for margin box sync."""
import pytest
import tempfile
from pathlib import Path
from django.core.management import call_command
from django.conf import settings
@pytest.mark.django_db
class TestSyncMarginBoxes:
def test_sync_basic_margin_box(self, tmp_path, monkeypatch):
"""Sync a basic margin box from editorial directory."""
from almnck.units.models import MarginBox
# Create test margin box
mb_dir = tmp_path / 'margin-boxes' / 'test-quote'
mb_dir.mkdir(parents=True)
(mb_dir / 'margin-box.md').write_text('''---
type: quote
placement: right-top
priority: normal
pages: [articles]
weight: 50
active: true
---
*Time discovers truth.*
— Seneca
''')
# Point settings at test directory
monkeypatch.setattr(settings, 'EDITORIAL_DIR', str(tmp_path))
# Run sync
call_command('sync_with_repo')
# Verify
box = MarginBox.objects.get(slug='test-quote')
assert box.box_type == 'quote'
assert box.placement == 'right-top'
assert box.priority == 'normal'
assert 'articles' in box.pages
assert '<em>Time discovers truth.</em>' in box.content or 'Time discovers truth' in box.content
def test_sync_recursive_walking(self, tmp_path, monkeypatch):
"""Sync walks nested directories."""
from almnck.units.models import MarginBox
# Create nested structure
aphorisms = tmp_path / 'margin-boxes' / 'aphorisms'
(aphorisms / 'seneca-time').mkdir(parents=True)
(aphorisms / 'seneca-time' / 'margin-box.md').write_text('''---
type: aphorism
pages: [all]
---
Time discovers truth.
''')
(aphorisms / 'cicero-friendship').mkdir(parents=True)
(aphorisms / 'cicero-friendship' / 'margin-box.md').write_text('''---
type: aphorism
pages: [all]
---
Friendship improves happiness.
''')
monkeypatch.setattr(settings, 'EDITORIAL_DIR', str(tmp_path))
call_command('sync_with_repo')
assert MarginBox.objects.filter(slug='seneca-time').exists()
assert MarginBox.objects.filter(slug='cicero-friendship').exists()
def test_sync_removes_deleted_boxes(self, tmp_path, monkeypatch):
"""Sync removes boxes that no longer exist on disk."""
from almnck.units.models import MarginBox
# Create initial box
mb_dir = tmp_path / 'margin-boxes' / 'will-delete'
mb_dir.mkdir(parents=True)
(mb_dir / 'margin-box.md').write_text('''---
type: quote
pages: [all]
---
Delete me
''')
monkeypatch.setattr(settings, 'EDITORIAL_DIR', str(tmp_path))
call_command('sync_with_repo')
assert MarginBox.objects.filter(slug='will-delete').exists()
# Delete from disk and resync
(mb_dir / 'margin-box.md').unlink()
mb_dir.rmdir()
call_command('sync_with_repo')
assert not MarginBox.objects.filter(slug='will-delete').exists()
Step 2: Run test to verify it fails
Run: make test
Expected: FAIL (sync doesn’t handle margin boxes yet)
Step 3: Extend sync_with_repo command
Modify: src/almnck/units/management/commands/sync_with_repo.py
Add import at top:
from almnck.units.models import Unit, MarginBox
Add new method to Command class:
def _sync_margin_boxes(self, editorial_dir: Path):
"""Sync margin boxes from editorial/margin-boxes/."""
margin_boxes_dir = editorial_dir / 'margin-boxes'
if not margin_boxes_dir.exists():
return
self.stdout.write(f"Scanning {margin_boxes_dir} for margin boxes...")
boxes_found = set()
for mb_dir in self._find_margin_box_dirs(margin_boxes_dir):
relative_path = str(mb_dir.relative_to(editorial_dir))
boxes_found.add(relative_path)
self._sync_margin_box(mb_dir, relative_path)
# Remove boxes that no longer exist on disk
missing = MarginBox.objects.exclude(source_path__in=boxes_found)
if missing.exists():
self.stdout.write(f"Removing {missing.count()} margin boxes no longer on disk")
missing.delete()
self.stdout.write(self.style.SUCCESS(f"Synced {len(boxes_found)} margin boxes"))
def _find_margin_box_dirs(self, base_dir: Path):
"""Find directories containing margin-box.md."""
for path in base_dir.rglob('margin-box.md'):
yield path.parent
def _sync_margin_box(self, mb_dir: Path, relative_path: str):
"""Sync a single margin box to database."""
content_file = mb_dir / 'margin-box.md'
if not content_file.exists():
return
content = content_file.read_text()
file_hash = hashlib.sha256(content.encode()).hexdigest()[:16]
# Check if already synced with same hash
try:
existing = MarginBox.objects.get(source_path=relative_path)
if existing.file_hash == file_hash:
return # No changes
except MarginBox.DoesNotExist:
existing = None
# Parse frontmatter
frontmatter, body = self._parse_frontmatter(content)
# Render markdown to HTML
import markdown
md = markdown.Markdown(extensions=['smarty', 'attr_list'])
rendered_content = md.convert(body)
slug = mb_dir.name
defaults = {
'slug': slug,
'content': rendered_content,
'frontmatter': frontmatter,
'box_type': frontmatter.get('type', 'quote'),
'placement': frontmatter.get('placement', 'any'),
'priority': frontmatter.get('priority', 'normal'),
'weight': frontmatter.get('weight', 50),
'active': frontmatter.get('active', True),
'starts': frontmatter.get('starts'),
'expires': frontmatter.get('expires'),
'pages': frontmatter.get('pages', ['all']),
'tags': frontmatter.get('tags', []),
'interactive': frontmatter.get('interactive', ''),
'publishes': frontmatter.get('publishes', []),
'subscribes': frontmatter.get('subscribes', []),
'file_hash': file_hash,
}
box, created = MarginBox.objects.update_or_create(
source_path=relative_path,
defaults=defaults
)
action = "Created" if created else "Updated"
self.stdout.write(f" {action} margin box: {box.slug}")
Add call in handle method, after syncing units:
# Sync margin boxes
if not subpath:
self._sync_margin_boxes(editorial_dir)
Step 4: Run test to verify it passes
Run: make test
Expected: PASS
Step 5: Commit
git add src/almnck/units/management/commands/sync_with_repo.py src/tests/test_sync_margin_boxes.py
git commit -m "feat: sync margin boxes from editorial/margin-boxes/"
Phase 3: Selection Helper
Task 3.1: Write Selection Helper Test
Files:
- Create: src/tests/test_select_margin_boxes.py
Step 1: Write the failing test
"""Tests for margin box selection."""
import pytest
from datetime import date
@pytest.mark.django_db
class TestSelectMarginBoxes:
def test_select_filters_by_page_type(self):
"""Selection respects page type filtering."""
from almnck.units.models import MarginBox
from almnck.units.margin_boxes import select_margin_boxes
MarginBox.objects.create(
source_path='mb/articles-only',
slug='articles-only',
content='For articles',
box_type='quote',
active=True,
pages=['articles'],
)
MarginBox.objects.create(
source_path='mb/front-only',
slug='front-only',
content='For front',
box_type='quote',
active=True,
pages=['front'],
)
MarginBox.objects.create(
source_path='mb/all-pages',
slug='all-pages',
content='For all',
box_type='quote',
active=True,
pages=['all'],
)
article_boxes = select_margin_boxes('article', date.today(), '/test/', count=10)
slugs = [b.slug for b in article_boxes]
assert 'articles-only' in slugs
assert 'all-pages' in slugs
assert 'front-only' not in slugs
def test_select_deterministic_with_seed(self):
"""Same seed produces same selection."""
from almnck.units.models import MarginBox
from almnck.units.margin_boxes import select_margin_boxes
for i in range(10):
MarginBox.objects.create(
source_path=f'mb/box-{i}',
slug=f'box-{i}',
content=f'Box {i}',
box_type='quote',
active=True,
pages=['all'],
weight=50,
)
seed_date = date(2026, 1, 15)
path = '/test/article/'
selection1 = select_margin_boxes('article', seed_date, path, count=3)
selection2 = select_margin_boxes('article', seed_date, path, count=3)
assert [b.slug for b in selection1] == [b.slug for b in selection2]
def test_critical_always_included(self):
"""Critical priority boxes are always included."""
from almnck.units.models import MarginBox
from almnck.units.margin_boxes import select_margin_boxes
MarginBox.objects.create(
source_path='mb/critical',
slug='critical',
content='Important!',
box_type='announcement',
active=True,
pages=['all'],
priority='critical',
)
for i in range(10):
MarginBox.objects.create(
source_path=f'mb/normal-{i}',
slug=f'normal-{i}',
content=f'Normal {i}',
box_type='quote',
active=True,
pages=['all'],
priority='normal',
weight=100, # High weight but not critical
)
boxes = select_margin_boxes('article', date.today(), '/test/', count=3)
slugs = [b.slug for b in boxes]
assert 'critical' in slugs
def test_respects_date_range(self):
"""Selection filters by starts/expires dates."""
from almnck.units.models import MarginBox
from almnck.units.margin_boxes import select_margin_boxes
from datetime import timedelta
today = date.today()
MarginBox.objects.create(
source_path='mb/active',
slug='active',
content='Active',
box_type='quote',
active=True,
pages=['all'],
)
MarginBox.objects.create(
source_path='mb/expired',
slug='expired',
content='Expired',
box_type='quote',
active=True,
expires=today - timedelta(days=1),
pages=['all'],
)
MarginBox.objects.create(
source_path='mb/future',
slug='future',
content='Future',
box_type='quote',
active=True,
starts=today + timedelta(days=1),
pages=['all'],
)
boxes = select_margin_boxes('article', today, '/test/', count=10)
slugs = [b.slug for b in boxes]
assert 'active' in slugs
assert 'expired' not in slugs
assert 'future' not in slugs
Step 2: Run test to verify it fails
Run: make test
Expected: FAIL with “No module named ‘almnck.units.margin_boxes’”
Step 3: Write the selection helper
Create: src/almnck/units/margin_boxes.py
"""Margin box selection for page rendering."""
import hashlib
import random
from datetime import date
from django.db.models import Q
from .models import MarginBox
def select_margin_boxes(page_type: str, seed_date: date | None, page_path: str, count: int = 3) -> list[MarginBox]:
"""
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
"""
if count <= 0:
return []
today = date.today()
# Map page_type to pages field values
page_type_map = {
'front': 'front',
'article': 'articles',
'page': 'pages',
}
page_value = page_type_map.get(page_type, page_type)
# Filter eligible boxes
eligible = MarginBox.objects.filter(active=True)
# Filter by page type (check for 'all' or specific page type)
# JSONField contains check
eligible = eligible.filter(
Q(pages__contains='all') | Q(pages__contains=page_value)
)
# Filter by date range
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'))
# Remaining slots for non-critical boxes
remaining_count = count - len(critical)
if remaining_count <= 0:
return critical[:count]
# 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
candidates = list(eligible.exclude(priority='critical'))
selected = weighted_sample(candidates, remaining_count, rng)
return critical + selected
def weighted_sample(items: list[MarginBox], count: int, rng: random.Random) -> list[MarginBox]:
"""
Weighted random sampling without replacement.
Args:
items: List of MarginBox objects with weight attribute
count: Number of items to select
rng: Random instance for deterministic selection
Returns:
List of selected MarginBox objects
"""
if not items or count <= 0:
return []
# Build weighted pool
pool = list(items)
selected = []
while pool and len(selected) < count:
# Calculate total weight
total_weight = sum(item.weight for item in pool)
if total_weight <= 0:
break
# Pick random point in weight space
pick = rng.uniform(0, total_weight)
cumulative = 0
for i, item in enumerate(pool):
cumulative += item.weight
if cumulative >= pick:
selected.append(item)
pool.pop(i)
break
return selected
Step 4: Run test to verify it passes
Run: make test
Expected: PASS
Step 5: Commit
git add src/almnck/units/margin_boxes.py src/tests/test_select_margin_boxes.py
git commit -m "feat: add seeded margin box selection helper"
Phase 4: View Integration
Task 4.1: Update Article View
Files:
- Modify: src/almnck/units/views.py
Step 1: Add import
from .margin_boxes import select_margin_boxes
Step 2: Update article_detail view
Find the article_detail function and add margin box selection before the return statement:
def article_detail(request, path):
"""Render a single article."""
output_path = '/' + path.strip('/') + '/'
unit = get_object_or_404(
Unit,
output_path=output_path,
status=Unit.Status.PUBLISHED
)
signoff_html = make_signoff_html(unit)
content = render_markdown(unit.content, signoff_html=signoff_html)
content = inject_image_dimensions(content, unit.source_path)
display_date = format_day(unit.frontmatter.get('almanac-day'))
# Get frontpage dates for fallback link
frontpage_dates = unit.frontmatter.get('frontpage', [])
latest_frontpage = max(frontpage_dates) if frontpage_dates else None
frontpage_count = len(frontpage_dates)
# Select margin boxes
margin_box_count = unit.frontmatter.get('margin-box-count', 3)
almanac_day = unit.frontmatter.get('almanac-day')
seed_date = None
if almanac_day:
try:
from datetime import datetime
seed_date = datetime.strptime(almanac_day, '%Y-%m-%d').date()
except ValueError:
pass
margin_boxes = select_margin_boxes('article', seed_date, output_path, count=margin_box_count)
return render(request, 'units/article.html', {
'unit': unit,
'content': content,
'display_date': display_date,
'latest_frontpage': latest_frontpage,
'latest_frontpage_formatted': format_frontpage_date(latest_frontpage) if latest_frontpage else None,
'frontpage_count': frontpage_count,
'margin_boxes': margin_boxes,
})
Step 3: Update index view similarly
In the index function, add before the return:
# Select margin boxes for front page
margin_box_count = article.frontmatter.get('margin-box-count', 3) if article else 3
margin_boxes = select_margin_boxes('front', datetime.now().date(), '/', count=margin_box_count)
And add to the context dict:
'margin_boxes': margin_boxes,
Step 4: Verify manually
Run: make serve
Visit an article page, check no errors.
Step 5: Commit
git add src/almnck/units/views.py
git commit -m "feat: pass margin boxes to article and front page views"
Phase 5: Template Integration
Task 5.1: Add Margin Box Template
Files:
- Modify: src/almnck/templates/units/article.html
Step 1: Add template block for injected margin boxes
After the closing </div> of .margins-layout, add:
{% if margin_boxes %}
<template id="injected-margin-boxes">
{% for box in margin_boxes %}
<div class="margin-box margin-box-injected"
data-slug="{{ box.slug }}"
data-type="{{ box.box_type }}"
data-margin="{{ box.placement }}-{{ box.priority }}"
data-injected="true"
{% if box.interactive %}data-interactive="{{ box.interactive }}"{% endif %}>
{{ box.content|safe }}
</div>
{% endfor %}
</template>
{% endif %}
Step 2: Commit
git add src/almnck/templates/units/article.html
git commit -m "feat: add template injection for margin boxes"
Phase 6: JavaScript Integration
Task 6.1: Extend sidenotes.js for Injected Boxes
Files:
- Modify: web/static/js/sidenotes.js
Step 1: Add function to extract injected boxes from template
Add after the marginBoxes variable declaration:
/**
* Extract margin boxes from <template> element
*/
function extractInjectedBoxes() {
const template = document.getElementById('injected-margin-boxes');
if (!template) return [];
const boxes = [];
const content = template.content || template;
content.querySelectorAll('.margin-box-injected').forEach(box => {
// Clone the box from template
const clone = box.cloneNode(true);
boxes.push(clone);
});
return boxes;
}
Step 2: Modify init() to include injected boxes
In the init() function, after collecting margin boxes from .maintext, add:
// Collect injected margin boxes from template
const injectedBoxes = extractInjectedBoxes();
injectedBoxes.forEach(box => {
// Injected boxes are external, not inline
box._prefs = parseMarginPreferences(box, false);
marginBoxes.push(box);
});
Step 3: Add public API
At the end of the IIFE, before the closing })();, add:
// Public API
window.Sidenotes = {
/**
* Inject a new margin box at runtime
* @returns {string} Box ID for later removal
*/
injectMarginBox({ content, type, placement, priority, interactive, publishes, subscribes }) {
const id = 'injected-' + Date.now() + '-' + Math.random().toString(36).substr(2, 9);
const box = document.createElement('div');
box.className = 'margin-box margin-box-injected';
box.id = id;
box.dataset.type = type || 'quote';
box.dataset.margin = `${placement || 'any'}-${priority || 'normal'}`;
box.dataset.injected = 'true';
if (interactive) box.dataset.interactive = interactive;
if (publishes) box.dataset.publishes = publishes.join(',');
if (subscribes) box.dataset.subscribes = subscribes.join(',');
box.innerHTML = content;
box._prefs = parseMarginPreferences(box, false);
marginBoxes.push(box);
reposition();
return id;
},
/**
* Remove a dynamically injected box
*/
removeMarginBox(id) {
const index = marginBoxes.findIndex(b => b.id === id);
if (index !== -1) {
marginBoxes[index].remove();
marginBoxes.splice(index, 1);
reposition();
}
},
/**
* Force reposition of all margin content
*/
reposition() {
reposition();
}
};
Step 4: Test manually
Run: make build && make serve
Create a test margin box in editorial/margin-boxes/test-aphorism/margin-box.md
Run: make sync
Visit an article page, verify the margin box appears.
Step 5: Commit
git add web/static/js/sidenotes.js
git commit -m "feat: extend sidenotes.js for injected margin boxes and public API"
Phase 7: Sample Content
Task 7.1: Create Sample Margin Boxes
Files:
- Create: editorial/margin-boxes/seneca-time/margin-box.md
- Create: editorial/margin-boxes/subscriber-cta/margin-box.md
Step 1: Create aphorism box
---
type: aphorism
placement: right-top
priority: normal
pages: [articles]
weight: 50
active: true
tags: [stoicism, featured]
---
*Time discovers truth.*
— Seneca
Step 2: Create CTA box
---
type: editorial
placement: right-bottom
priority: high
pages: [articles]
weight: 75
active: true
---
**Support the Almanack**
Become a member to access the full archive and support independent publishing.
[Learn more →](/membership/)
Step 3: Sync and verify
Run: make sync && make build
Visit article pages to verify boxes appear.
Step 4: Commit
git add editorial/margin-boxes/
git commit -m "feat: add sample margin boxes for testing"
Phase 8: Static HTML Fragments for Pinning
Task 8.1: Add Distill Route for Margin Box Fragments
Files:
- Modify: src/almnck/units/views.py
- Modify: src/almnck/units/urls.py
Step 1: Add view for margin box fragment
def margin_box_fragment(request, slug):
"""Render a single margin box as an HTML fragment for pinning."""
from .models import MarginBox
box = get_object_or_404(MarginBox, slug=slug, active=True)
html = f'''<div class="margin-box"
data-slug="{box.slug}"
data-type="{box.box_type}"
data-margin="{box.placement}-{box.priority}">
{box.content}
</div>'''
return HttpResponse(html, content_type='text/html')
Step 2: Add URL route
In urls.py, add:
path('margin-boxes/<slug:slug>.html', views.margin_box_fragment, name='margin_box_fragment'),
Step 3: Add distill configuration
Add to distill URLs or use build system to generate fragments.
Step 4: Commit
git add src/almnck/units/views.py src/almnck/units/urls.py
git commit -m "feat: add static HTML fragments for margin box pinning"
Phase 9: Client-Side Pinning
Task 9.1: Add Pinning to sidenotes.js
Files:
- Modify: web/static/js/sidenotes.js
Step 1: Add localStorage helpers
const PINNED_STORAGE_KEY = 'almanack-pinned-margin-boxes';
function getPinnedBoxes() {
try {
return JSON.parse(localStorage.getItem(PINNED_STORAGE_KEY)) || [];
} catch (e) {
return [];
}
}
function savePinnedBoxes(slugs) {
try {
localStorage.setItem(PINNED_STORAGE_KEY, JSON.stringify(slugs));
} catch (e) {
// localStorage unavailable
}
}
Step 2: Add pin/unpin functions
function pinMarginBox(slug) {
const pinned = getPinnedBoxes();
if (!pinned.includes(slug)) {
pinned.push(slug);
savePinnedBoxes(pinned);
}
}
function unpinMarginBox(slug) {
const pinned = getPinnedBoxes().filter(s => s !== slug);
savePinnedBoxes(pinned);
// Remove unpin affordance if box is still on page
const box = document.querySelector(`[data-slug="${slug}"]`);
if (box) {
box.classList.remove('margin-box-pinned');
const unpinBtn = box.querySelector('.margin-box-unpin');
if (unpinBtn) unpinBtn.remove();
}
}
Step 3: Add fetch-on-demand for pinned boxes
async function loadPinnedBoxes() {
const pinned = getPinnedBoxes();
const inlineSlugs = marginBoxes.map(b => b.dataset?.slug).filter(Boolean);
for (const slug of pinned) {
if (!inlineSlugs.includes(slug)) {
try {
const resp = await fetch(`/margin-boxes/${slug}.html`);
if (resp.ok) {
const html = await resp.text();
const temp = document.createElement('div');
temp.innerHTML = html;
const box = temp.firstElementChild;
if (box) {
box.classList.add('margin-box-pinned');
box._prefs = parseMarginPreferences(box, false);
box._prefs.priority = 'pinned'; // Boost priority
marginBoxes.push(box);
addUnpinAffordance(box);
}
}
// 404 = box expired or deleted, silently skip
} catch (e) {
// Network error, skip
}
} else {
// Mark inline box as pinned
const box = marginBoxes.find(b => b.dataset?.slug === slug);
if (box) {
box.classList.add('margin-box-pinned');
addUnpinAffordance(box);
}
}
}
}
function addUnpinAffordance(box) {
if (box.querySelector('.margin-box-unpin')) return;
const btn = document.createElement('button');
btn.className = 'margin-box-unpin';
btn.setAttribute('aria-label', 'Unpin this box');
btn.textContent = '📌';
btn.addEventListener('click', (e) => {
e.stopPropagation();
unpinMarginBox(box.dataset.slug);
});
box.appendChild(btn);
}
Step 4: Call loadPinnedBoxes in init
Add after collecting margin boxes, before positioning:
// Load pinned boxes
await loadPinnedBoxes();
(Note: Make init() async if needed)
Step 5: Extend public API
pinMarginBox(slug) {
pinMarginBox(slug);
},
unpinMarginBox(slug) {
unpinMarginBox(slug);
},
getPinnedBoxes() {
return getPinnedBoxes();
},
isBoxPinned(slug) {
return getPinnedBoxes().includes(slug);
}
Step 6: Commit
git add web/static/js/sidenotes.js
git commit -m "feat: add client-side pinning for margin boxes"
Phase 10: CSS Styling
Task 10.1: Add Margin Box and Pinning Styles
Files:
- Modify: appropriate CSS file (likely web/static/css/styles.css or similar)
Step 1: Add unpin button styles
.margin-box-unpin {
position: absolute;
top: 0.25em;
right: 0.25em;
opacity: 0.4;
font-size: 0.75rem;
background: none;
border: none;
cursor: pointer;
padding: 0.25em;
line-height: 1;
}
.margin-box-unpin:hover {
opacity: 1;
}
/* Only pinned boxes have the unpin button visible */
.margin-box:not(.margin-box-pinned) .margin-box-unpin {
display: none;
}
/* Pinned boxes get subtle highlight */
.margin-box-pinned {
position: relative;
}
Step 2: Commit
git add web/static/css/
git commit -m "style: add margin box pinning UI styles"
Final Verification
Task 11.1: End-to-End Test
Step 1: Run full test suite
Run: make test
Expected: All tests pass
Step 2: Manual verification
- Create margin boxes in
editorial/margin-boxes/ - Run
make sync && make build - Visit articles, verify boxes appear in margins
- Verify different page types show appropriate boxes
- Test the public JS API in browser console
Step 3: Final commit
git add -A
git commit -m "docs: complete margin box injection implementation"
Summary
| Phase | Description | Key Files |
|---|---|---|
| 1 | MarginBox model | models.py, migration |
| 2 | Sync extension | sync_with_repo.py |
| 3 | Selection helper | margin_boxes.py |
| 4 | View integration | views.py |
| 5 | Template injection | article.html |
| 6 | JS positioning | sidenotes.js |
| 7 | Sample content | editorial/margin-boxes/ |
| 8 | Static fragments | views.py, urls.py |
| 9 | Client pinning | sidenotes.js |
| 10 | CSS styling | styles.css |