Manual
Almnck.
Price: 50ⓐ

Margins and Sidenotes Implementation Plan

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

Goal: Implement three-column layout with sidenotes and margin boxes for article pages.

Architecture: CSS Grid for three-column layout. JavaScript transforms Pandoc footnotes into positioned sidenotes, moves inline margin boxes to margins. Progressive enhancement ensures graceful degradation.

Tech Stack: CSS Grid, vanilla JavaScript (adapted from gwern.net’s sidenotes.js), Django templates.

Design Document: doc/process/plans/2026-01-04-margins-sidenotes-design.md


Task 1: Add CSS Grid Layout

Files: - Modify: assets/css/almanack.css

Step 1: Add margins-layout grid styles

Add after the existing main styles (around line 138):

/* Three-column margins layout */
.margins-layout {
  display: grid;
  grid-template-columns:
    minmax(10rem, 1fr)
    minmax(30rem, 43rem)
    minmax(10rem, 1fr);
  gap: 2rem;
  max-width: 80rem;
  margin: 0 auto;
  padding: 0 1rem;
}

.margin {
  position: relative;
  font-size: 0.85rem;
  line-height: 1.4;
  font-family: "Cormorant Garamond", Georgia, serif;
}

.margin-left {
  grid-column: 1;
}

.body-text {
  grid-column: 2;
}

.margin-right {
  grid-column: 3;
}

/* Collapse to single column on narrow screens */
@media (max-width: 900px) {
  .margins-layout {
    display: block;
    max-width: 43em;
    padding: 0;
  }
  .margin {
    display: none;
  }
}

Step 2: Verify CSS is valid

Run: source bin/a-activate && python -c "import cssutils; cssutils.parseFile('assets/css/almanack.css')"

Note: If cssutils not available, visually inspect the file for syntax errors.

Step 3: Commit

git add assets/css/almanack.css
git commit -m "feat: add CSS Grid three-column margins layout"

Task 2: Add Sidenote Styles

Files: - Modify: assets/css/almanack.css

Step 1: Add sidenote element styles

Add after the margins-layout styles:

/* Sidenote elements */
.sidenote {
  position: absolute;
  width: 100%;
  padding: 0.5em 0;
}

.sidenote-number {
  font-weight: 600;
  margin-right: 0.3em;
}

.sidenote-content {
  display: inline;
}

.sidenote-content p {
  display: inline;
  margin: 0;
}

/* Collapsed state */
.sidenote.collapsed .sidenote-content {
  display: none;
}

.sidenote.collapsed .sidenote-number::after {
  content: "…";
  color: #666;
  font-weight: normal;
}

/* Bidirectional highlight */
.sidenote.highlighted,
.footnote-ref.highlighted {
  background-color: #ffffd0;
}

/* Hide footnotes section when sidenotes enabled */
.sidenotes-enabled .footnotes {
  position: absolute;
  width: 1px;
  height: 1px;
  padding: 0;
  margin: -1px;
  overflow: hidden;
  clip: rect(0, 0, 0, 0);
  border: 0;
}

/* Show footnotes on narrow screens */
@media (max-width: 900px) {
  .sidenotes-enabled .footnotes {
    position: static;
    width: auto;
    height: auto;
    padding: 0;
    margin: 0;
    overflow: visible;
    clip: auto;
  }
}

Step 2: Commit

git add assets/css/almanack.css
git commit -m "feat: add sidenote element styles"

Task 3: Add Margin Box Styles

Files: - Modify: assets/css/almanack.css

Step 1: Add margin box styles

Add after sidenote styles:

/* Margin boxes - inline fallback for no-JS/mobile */
.margin-box {
  margin: 1.5em auto;
  max-width: 70%;
  padding: 1em;
  border-top: 1px solid #1a1a1a;
  border-bottom: 1px solid #1a1a1a;
  font-size: 0.9rem;
}

/* JS enabled: boxes get absolutely positioned in margins */
.sidenotes-enabled .margin-box {
  position: absolute;
  width: 100%;
  margin: 0;
  max-width: none;
  border: none;
  padding: 0.5em 0;
}

/* Margin box type variants */
.margin-box[data-type="quote"] {
  font-style: italic;
  border-left: 2px solid #1a1a1a;
  padding-left: 0.5em;
  border-top: none;
  border-bottom: none;
}

.margin-box[data-type="quote"] cite {
  display: block;
  margin-top: 0.5em;
  font-style: normal;
  font-size: 0.9em;
}

.margin-box[data-type="ad"] {
  border: 1px solid #1a1a1a;
  padding: 0.5em;
  text-align: center;
}

.margin-box[data-type="aphorism"] {
  font-family: "Fell English", serif;
  text-align: center;
  font-size: 1rem;
}

/* Full-bleed elements span all columns */
.full-bleed {
  grid-column: 1 / -1;
  width: 100%;
  margin: 2rem 0;
}

Step 2: Commit

git add assets/css/almanack.css
git commit -m "feat: add margin box and full-bleed styles"

Task 4: Add Reader Preference Toggle Styles

Files: - Modify: assets/css/almanack.css

Step 1: Add toggle styles

Add after margin box styles:

/* Sidenote preference toggle */
.sidenote-toggle {
  font-family: "Fell English", serif;
  font-size: 0.9rem;
}

.sidenote-toggle button {
  background: none;
  border: none;
  cursor: pointer;
  padding: 0.2em 0.4em;
  color: #666;
  font-family: inherit;
  font-size: inherit;
}

.sidenote-toggle button:hover {
  color: #1a1a1a;
}

.sidenote-toggle button.active {
  color: #1a1a1a;
  text-decoration: underline;
}

/* Hide toggle on narrow screens (sidenotes not shown) */
@media (max-width: 900px) {
  .sidenote-toggle {
    display: none;
  }
}

Step 2: Commit

git add assets/css/almanack.css
git commit -m "feat: add sidenote toggle styles"

Task 5: Create JavaScript Directory and Sidenotes Script

Files: - Create: assets/js/sidenotes.js

Step 1: Create js directory

mkdir -p assets/js

Step 2: Create sidenotes.js with initialization

Create assets/js/sidenotes.js:

/**
 * Sidenotes and Margin Boxes
 *
 * Transforms Pandoc footnotes into margin sidenotes and positions
 * margin boxes in the remaining space.
 *
 * Adapted from Said Achmiz's sidenotes.js (MIT License)
 * https://github.com/gwern/gwern.net/blob/master/js/sidenotes.js
 *
 * Extensions: margin box support, two-margin layout
 */

(function() {
  'use strict';

  // Configuration
  const CONFIG = {
    sidenoteSpacing: 16,  // Minimum pixels between sidenotes
    minViewportWidth: 900, // Below this, use fallback
    storageKey: 'sidenote-mode'
  };

  // State
  let sidenotes = [];
  let marginBoxes = [];
  let isEnabled = false;

  /**
   * Check if viewport is wide enough for sidenotes
   */
  function viewportIsWideEnough() {
    return window.innerWidth > CONFIG.minViewportWidth;
  }

  /**
   * Get or create margin container
   */
  function getMargin(side) {
    return document.querySelector(`.margin-${side}`);
  }

  /**
   * Get saved preference or default
   */
  function getSavedMode() {
    try {
      return localStorage.getItem(CONFIG.storageKey) || 'expanded';
    } catch (e) {
      return 'expanded';
    }
  }

  /**
   * Save preference
   */
  function saveMode(mode) {
    try {
      localStorage.setItem(CONFIG.storageKey, mode);
    } catch (e) {
      // localStorage unavailable
    }
  }

  /**
   * Create sidenote element from footnote
   */
  function createSidenote(footnoteRef, footnoteContent, index) {
    const sidenote = document.createElement('div');
    sidenote.className = 'sidenote';
    sidenote.id = `sn:${index}`;
    sidenote.dataset.anchor = footnoteRef.id;

    const number = document.createElement('span');
    number.className = 'sidenote-number';
    number.textContent = index;

    const content = document.createElement('div');
    content.className = 'sidenote-content';
    content.innerHTML = footnoteContent.innerHTML;

    // Remove back-reference link from sidenote content
    const backref = content.querySelector('.footnote-backref');
    if (backref) backref.remove();

    sidenote.appendChild(number);
    sidenote.appendChild(content);

    // Bidirectional highlighting
    sidenote.addEventListener('mouseenter', () => {
      sidenote.classList.add('highlighted');
      footnoteRef.classList.add('highlighted');
    });
    sidenote.addEventListener('mouseleave', () => {
      sidenote.classList.remove('highlighted');
      footnoteRef.classList.remove('highlighted');
    });
    footnoteRef.addEventListener('mouseenter', () => {
      sidenote.classList.add('highlighted');
      footnoteRef.classList.add('highlighted');
    });
    footnoteRef.addEventListener('mouseleave', () => {
      sidenote.classList.remove('highlighted');
      footnoteRef.classList.remove('highlighted');
    });

    return sidenote;
  }

  /**
   * Calculate vertical position of an element relative to document
   */
  function getVerticalPosition(element) {
    const rect = element.getBoundingClientRect();
    return rect.top + window.scrollY;
  }

  /**
   * Position sidenotes in margins, avoiding overlaps
   */
  function positionSidenotes() {
    if (!viewportIsWideEnough()) return;

    const leftMargin = getMargin('left');
    const rightMargin = getMargin('right');
    if (!leftMargin || !rightMargin) return;

    // Track occupied ranges in each margin
    const occupied = {
      left: [],
      right: []
    };

    // Alternate margins, starting with right
    let currentMargin = 'right';

    sidenotes.forEach((sn, i) => {
      const anchor = document.getElementById(sn.dataset.anchor);
      if (!anchor) return;

      const desiredTop = getVerticalPosition(anchor);
      const margin = currentMargin === 'right' ? rightMargin : leftMargin;

      // Find actual position avoiding overlaps
      let actualTop = desiredTop;
      const ranges = occupied[currentMargin];

      for (const range of ranges) {
        if (actualTop < range.bottom + CONFIG.sidenoteSpacing &&
            actualTop + sn.offsetHeight > range.top - CONFIG.sidenoteSpacing) {
          actualTop = range.bottom + CONFIG.sidenoteSpacing;
        }
      }

      // Position the sidenote
      sn.style.top = `${actualTop}px`;
      margin.appendChild(sn);

      // Record occupied range
      occupied[currentMargin].push({
        top: actualTop,
        bottom: actualTop + sn.offsetHeight
      });

      // Alternate margins
      currentMargin = currentMargin === 'right' ? 'left' : 'right';
    });

    return occupied;
  }

  /**
   * Position margin boxes in remaining space
   */
  function positionMarginBoxes(occupied) {
    if (!viewportIsWideEnough()) return;

    const leftMargin = getMargin('left');
    const rightMargin = getMargin('right');
    if (!leftMargin || !rightMargin) return;

    marginBoxes.forEach((box) => {
      // Get original position in document flow
      const originalTop = parseFloat(box.dataset.originalTop) || 0;

      // Try left margin first, then right
      for (const side of ['left', 'right']) {
        const margin = side === 'left' ? leftMargin : rightMargin;
        const ranges = occupied[side];

        // Find a gap near the original position
        let top = originalTop;
        let fits = true;

        for (const range of ranges) {
          if (top < range.bottom + CONFIG.sidenoteSpacing &&
              top + box.offsetHeight > range.top - CONFIG.sidenoteSpacing) {
            top = range.bottom + CONFIG.sidenoteSpacing;
            fits = false;
          }
        }

        // Use this margin if box fits reasonably close to original position
        if (fits || top < originalTop + 200) {
          box.style.top = `${top}px`;
          margin.appendChild(box);

          occupied[side].push({
            top: top,
            bottom: top + box.offsetHeight
          });

          break;
        }
      }
    });
  }

  /**
   * Apply collapsed/expanded mode
   */
  function applyMode(mode) {
    sidenotes.forEach(sn => {
      sn.classList.toggle('collapsed', mode === 'collapsed');
    });

    // Update toggle buttons
    document.querySelectorAll('.sidenote-toggle button').forEach(btn => {
      btn.classList.toggle('active', btn.dataset.mode === mode);
    });

    // Reposition after mode change (heights changed)
    requestAnimationFrame(() => {
      reposition();
    });
  }

  /**
   * Reposition all elements
   */
  function reposition() {
    if (!isEnabled) return;

    // Reset positions
    sidenotes.forEach(sn => {
      sn.style.top = '';
    });
    marginBoxes.forEach(box => {
      box.style.top = '';
    });

    // Recalculate
    const occupied = positionSidenotes();
    if (occupied) {
      positionMarginBoxes(occupied);
    }
  }

  /**
   * Initialize sidenotes system
   */
  function init() {
    // Check for margins layout
    const marginsLayout = document.querySelector('.margins-layout');
    if (!marginsLayout) return;

    // Check viewport width
    if (!viewportIsWideEnough()) return;

    // Find all footnote references
    const footnoteRefs = document.querySelectorAll('.footnote-ref');
    if (footnoteRefs.length === 0) return;

    // Create sidenotes from footnotes
    footnoteRefs.forEach((ref, i) => {
      const href = ref.getAttribute('href');
      if (!href) return;

      const footnoteId = href.replace('#', '');
      const footnoteContent = document.getElementById(footnoteId);
      if (!footnoteContent) return;

      const sidenote = createSidenote(ref, footnoteContent, i + 1);
      sidenotes.push(sidenote);
    });

    // Collect margin boxes and record original positions
    document.querySelectorAll('.margin-box').forEach(box => {
      box.dataset.originalTop = getVerticalPosition(box);
      marginBoxes.push(box);
    });

    // Mark as enabled
    document.body.classList.add('sidenotes-enabled');
    isEnabled = true;

    // Position everything
    const occupied = positionSidenotes();
    if (occupied) {
      positionMarginBoxes(occupied);
    }

    // Apply saved preference
    applyMode(getSavedMode());

    // Set up toggle
    document.querySelectorAll('.sidenote-toggle button').forEach(btn => {
      btn.addEventListener('click', () => {
        const mode = btn.dataset.mode;
        saveMode(mode);
        applyMode(mode);
      });
    });

    // Handle resize
    let resizeTimeout;
    window.addEventListener('resize', () => {
      clearTimeout(resizeTimeout);
      resizeTimeout = setTimeout(() => {
        if (viewportIsWideEnough()) {
          reposition();
        }
      }, 100);
    });
  }

  // Initialize when DOM is ready
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }
})();

Step 3: Commit

git add assets/js/sidenotes.js
git commit -m "feat: add sidenotes.js for margin positioning

Adapted from Said Achmiz's sidenotes.js (MIT License).
Handles footnote transformation, collision avoidance,
and margin box positioning."

Task 6: Update Base Template

Files: - Modify: src/almnck/templates/base.html

Step 1: Add JS include and toggle UI

Update base.html:

{% load cdnstaticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}Almnck.{% endblock %}</title>
    <link rel="stylesheet" href="{% cdnstatic 'css/almanack.css' %}">
    <link rel="alternate" type="application/rss+xml" title="Almnck. RSS Feed" href="/feed.xml">
</head>
<body>
    <div class="masthead">
        <div class="meta-left">{% block meta_left %}Since 4000 BCE{% endblock %}</div>
        <h1 class="frontispiece"><a href="/">Almnck.</a></h1>
        <div class="meta-right">
            {% block meta_right %}{% endblock %}
            {% block sidenote_toggle %}{% endblock %}
        </div>
    </div>
    <main>
        {% block content %}{% endblock %}
    </main>
    <script src="{% cdnstatic 'js/sidenotes.js' %}" defer></script>
</body>
</html>

Step 2: Commit

git add src/almnck/templates/base.html
git commit -m "feat: add sidenotes.js include and toggle block to base template"

Task 7: Update Article Template with Margins Layout

Files: - Modify: src/almnck/templates/units/article.html

Step 1: Wrap article in margins-layout

Update article.html:

{% extends "base.html" %}

{% block title %}{{ unit.title }} - Almnck.{% endblock %}

{% block meta_left %}Vol. {{ unit.volume }}, No. {{ unit.issue }}{% endblock %}

{% block meta_right %}{{ display_date }}{% endblock %}

{% block sidenote_toggle %}
<div class="sidenote-toggle">
    <button data-mode="expanded" title="Show sidenotes">¶</button>
    <button data-mode="collapsed" title="Hide sidenotes">※</button>
</div>
{% endblock %}

{% block content %}
<div class="margins-layout">
    <aside class="margin margin-left"></aside>
    <article class="body-text">
        <header>
            <h1 class="title"><a href="{{ unit.output_path }}">{{ unit.title }}</a></h1>
            {% if unit.day %}
            <p class="date">{{ unit.day }}</p>
            {% endif %}
        </header>
        <div class="maintext">
            {{ content|safe }}
        </div>
    </article>
    <aside class="margin margin-right"></aside>
</div>
{% endblock %}

Step 2: Commit

git add src/almnck/templates/units/article.html
git commit -m "feat: wrap article in margins-layout with toggle UI"

Task 8: Copy Static Files to Web Directory

Files: - Check: Makefile for static file handling

Step 1: Verify static file copy in build process

Check how assets/js would be copied to web/static/js. Look at Makefile:

grep -n "static\|assets\|css" Makefile

If needed, add js copying alongside css.

Step 2: Test the build

source bin/a-activate
make sync-django
make build-django-site

Step 3: Verify output

ls -la web/static/js/
cat web/static/js/sidenotes.js | head -20

Step 4: Commit any Makefile changes if needed

git add Makefile
git commit -m "build: include js files in static asset copy"

Task 9: Visual Testing

Files: - None (manual testing)

Step 1: Start development server

source bin/a-activate
make serve

Step 2: Open in browser

Visit http://localhost:8000/ and click on an article.

Step 3: Verify checklist

  • [ ] Three columns visible on wide viewport
  • [ ] Sidenotes appear in margins aligned with footnote refs
  • [ ] Footnotes section hidden
  • [ ] Toggle switches between expanded/collapsed
  • [ ] Preference persists on page reload
  • [ ] Hovering sidenote highlights footnote ref (and vice versa)
  • [ ] Narrow viewport: margins hidden, footnotes visible
  • [ ] No JS: footnotes visible at bottom

Step 4: Document any issues found

Create issues or fix immediately if minor.


Task 10: Add Sample Margin Box to Test

Files: - Modify: editorial/articles/look-back-up/article.md (or create test content)

Step 1: Add a margin box to test article

The margin box HTML goes inline in the article. Since content comes from markdown, we may need to add it via a template or post-processing.

For now, test by manually adding to generated HTML or creating a test template that includes a margin box.

Step 2: Verify margin box positioning

  • [ ] Box appears in margin on wide viewport
  • [ ] Box appears inline on narrow viewport
  • [ ] Box doesn’t overlap with sidenotes

Task 11: Final Cleanup and Documentation

Files: - Modify: doc/process/plans/2026-01-04-margins-sidenotes-design.md (if needed)

Step 1: Update design doc with any implementation notes

Add any learnings or deviations from the original design.

Step 2: Final commit

git add -A
git commit -m "docs: update design doc with implementation notes"

Future Tasks (Not in Scope)

These are documented but not implemented:

  1. Margin box injection - Django template tag or view logic to inject boxes from a pool
  2. Mobile swipe-to-reveal - Touch gesture to slide margins into view
  3. Per-article preference - Frontmatter control for default expand/collapse
  4. Markdown syntax for boxes - Custom Pandoc filter for :::margin-box blocks

Addendum (2026-01-17): Makefile commands were reorganized. sync-django → sync, build-django-site → build.