Manual
Almnck.
Price: 50ⓐ

Margin Box Positioning Preferences Implementation Plan

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

Goal: Extend sidenotes.js to support placement preferences (vertical, horizontal, priority) for margin boxes while preserving sidenote collision-avoidance.

Architecture: Parse data-margin attributes into preference objects, implement tiered placement (sidenotes first, then high/normal/low priority boxes), add redistribution phase to even spacing. The existing collision-avoidance system remains intact; we layer preferences on top.

Tech Stack: Vanilla JavaScript (no build step), direct DOM manipulation, no external dependencies.

Related design: 2026-01-11-margin-box-positioning-design.md


Task 1: Add parseMarginPreferences Function

Files: - Modify: assets/js/sidenotes.js:26 (after state declarations)

Step 1: Add the parsing function

Add after line 26 (after let isEnabled = false;):

/**
 * Parse margin placement preferences from data-margin attribute
 * Tokens: vertical (top|bottom|near), horizontal (left|right), priority (high|low)
 * Order-independent: "right-top-high" = "top-right-high"
 */
function parseMarginPreferences(element, isInline = true) {
  const attr = element.dataset.margin || '';
  const tokens = attr.toLowerCase().split('-').filter(Boolean);

  const verticalOptions = ['top', 'bottom', 'near'];
  const horizontalOptions = ['left', 'right'];
  const priorityOptions = ['high', 'low'];

  return {
    vertical: tokens.find(t => verticalOptions.includes(t))
              || (isInline ? 'near' : null),
    horizontal: tokens.find(t => horizontalOptions.includes(t)) || null,
    priority: tokens.find(t => priorityOptions.includes(t)) || 'normal'
  };
}

Step 2: Verify syntax

Run: node --check assets/js/sidenotes.js Expected: No output (success)

Step 3: Commit

git add assets/js/sidenotes.js
git commit -m "feat(sidenotes): add parseMarginPreferences function

Parses data-margin attribute into {vertical, horizontal, priority} object.
Tokens are order-independent. Inline boxes default to 'near', external to null."

Task 2: Store Preferences When Collecting Margin Boxes

Files: - Modify: assets/js/sidenotes.js:422-426 (margin box collection in init)

Step 1: Update margin box collection to parse and store preferences

Replace lines 422-426:

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

With:

// Collect margin boxes with preferences and original positions
document.querySelectorAll('.margin-box').forEach(box => {
  // Determine if inline (defined in body) vs external (injected from elsewhere)
  const isInline = box.closest('.maintext') !== null;
  box.dataset.originalTop = getVerticalPosition(box);
  box._prefs = parseMarginPreferences(box, isInline);
  marginBoxes.push(box);
});

Step 2: Verify syntax

Run: node --check assets/js/sidenotes.js Expected: No output (success)

Step 3: Commit

git add assets/js/sidenotes.js
git commit -m "feat(sidenotes): parse preferences when collecting margin boxes

Stores parsed preferences in box._prefs. Inline boxes (in .maintext)
default to 'near' vertical; external boxes default to null."

Task 3: Add Helper Functions for Placement

Files: - Modify: assets/js/sidenotes.js (after parseMarginPreferences, ~line 45)

Step 1: Add helper functions for finding available slots

Add after parseMarginPreferences:

/**
 * Find first available vertical position in a margin, avoiding occupied ranges
 * @param {number} desiredTop - Where we want to place the element
 * @param {number} height - Element height
 * @param {Array} occupied - Array of {top, bottom} ranges
 * @param {string} direction - 'down' fills downward, 'up' fills upward
 * @returns {number} - Available top position
 */
function findAvailableSlot(desiredTop, height, occupied, direction = 'down') {
  const spacing = CONFIG.sidenoteSpacing;
  let top = desiredTop;

  if (direction === 'down') {
    // Fill downward: find first gap below desiredTop
    for (const range of occupied) {
      if (top < range.bottom + spacing && top + height > range.top - spacing) {
        top = range.bottom + spacing;
      }
    }
  } else {
    // Fill upward: find first gap above desiredTop
    // Sort occupied by bottom descending for upward search
    const sortedDesc = [...occupied].sort((a, b) => b.bottom - a.bottom);
    for (const range of sortedDesc) {
      if (top + height > range.top - spacing && top < range.bottom + spacing) {
        top = range.top - height - spacing;
      }
    }
  }

  return top;
}

/**
 * Get the lowest available position for 'top' boxes or highest for 'bottom' boxes
 * Used to determine which margin offers better placement
 */
function getBestPositionInMargin(direction, height, occupied, boundaryTop, boundaryBottom) {
  const spacing = CONFIG.sidenoteSpacing;

  if (direction === 'top') {
    // Want highest position (lowest number)
    return findAvailableSlot(boundaryTop, height, occupied, 'down');
  } else if (direction === 'bottom') {
    // Want lowest position (highest number, but above boundary)
    return findAvailableSlot(boundaryBottom - height, height, occupied, 'up');
  }
  return null;
}

/**
 * Find closest available position to a target
 */
function findClosestSlot(targetTop, height, occupied) {
  const spacing = CONFIG.sidenoteSpacing;

  // Try target position first
  let testTop = targetTop;
  let hasCollision = true;

  while (hasCollision) {
    hasCollision = false;
    for (const range of occupied) {
      if (testTop < range.bottom + spacing && testTop + height > range.top - spacing) {
        testTop = range.bottom + spacing;
        hasCollision = true;
        break;
      }
    }
  }

  return testTop;
}

/**
 * Find largest gap in a margin
 */
function findLargestGap(occupied, boundaryTop, boundaryBottom) {
  const spacing = CONFIG.sidenoteSpacing;
  const sorted = [...occupied].sort((a, b) => a.top - b.top);

  let largestGap = { start: boundaryTop, size: 0 };
  let prevBottom = boundaryTop;

  for (const range of sorted) {
    const gapSize = range.top - prevBottom - spacing * 2;
    if (gapSize > largestGap.size) {
      largestGap = { start: prevBottom + spacing, size: gapSize };
    }
    prevBottom = range.bottom;
  }

  // Check gap after last element
  const finalGap = boundaryBottom - prevBottom - spacing;
  if (finalGap > largestGap.size) {
    largestGap = { start: prevBottom + spacing, size: finalGap };
  }

  return largestGap;
}

Step 2: Verify syntax

Run: node --check assets/js/sidenotes.js Expected: No output (success)

Step 3: Commit

git add assets/js/sidenotes.js
git commit -m "feat(sidenotes): add slot-finding helper functions

findAvailableSlot - finds position avoiding occupied ranges
getBestPositionInMargin - optimal position for top/bottom boxes
findClosestSlot - nearest available to target
findLargestGap - biggest empty space in margin"

Task 4: Rewrite positionMarginBoxes with Tiered Placement

Files: - Modify: assets/js/sidenotes.js:303-351 (replace entire positionMarginBoxes function)

Step 1: Replace positionMarginBoxes function

Replace the entire positionMarginBoxes function (lines 303-351) with:

/**
 * Position margin boxes using preference-based tiered placement
 * Order: sidenotes (already placed) → high priority → normal → low priority
 */
function positionMarginBoxes(occupied) {
  if (!viewportIsWideEnough()) return;

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

  // Get body text boundary (margin boxes shouldn't extend below this)
  const maintext = document.querySelector('.maintext');
  const bodyBottom = maintext
    ? getVerticalPosition(maintext) + maintext.offsetHeight
    : Infinity;
  const bodyTop = maintext ? getVerticalPosition(maintext) : 0;

  // Margin offsets for coordinate conversion
  const marginOffsets = {
    left: getVerticalPosition(leftMargin),
    right: getVerticalPosition(rightMargin)
  };

  // Partition boxes by priority
  const byPriority = {
    high: marginBoxes.filter(b => b._prefs?.priority === 'high'),
    normal: marginBoxes.filter(b => b._prefs?.priority === 'normal' || !b._prefs?.priority),
    low: marginBoxes.filter(b => b._prefs?.priority === 'low')
  };

  // Track which boxes are flexible (for redistribution)
  const flexibleBoxes = [];

  // Place each priority tier
  for (const tier of ['high', 'normal', 'low']) {
    const boxes = byPriority[tier];
    const isFlexible = tier !== 'high';

    // Partition by vertical preference
    const topBoxes = boxes.filter(b => b._prefs?.vertical === 'top');
    const bottomBoxes = boxes.filter(b => b._prefs?.vertical === 'bottom');
    const nearBoxes = boxes.filter(b => b._prefs?.vertical === 'near');
    const noPrefBoxes = boxes.filter(b => !b._prefs?.vertical);

    // Place TOP boxes (fill downward from top)
    for (const box of topBoxes) {
      const placed = placeBox(box, 'top', occupied, marginOffsets, bodyTop, bodyBottom);
      if (placed && isFlexible) flexibleBoxes.push(box);
    }

    // Place BOTTOM boxes (fill upward from body bottom)
    for (const box of bottomBoxes) {
      const placed = placeBox(box, 'bottom', occupied, marginOffsets, bodyTop, bodyBottom);
      if (placed && isFlexible) flexibleBoxes.push(box);
    }

    // Place NEAR boxes (close to definition point)
    for (const box of nearBoxes) {
      const placed = placeBox(box, 'near', occupied, marginOffsets, bodyTop, bodyBottom);
      if (placed && isFlexible) flexibleBoxes.push(box);
    }

    // Place NO-PREFERENCE boxes (fill largest gaps)
    for (const box of noPrefBoxes) {
      const placed = placeBox(box, 'gap', occupied, marginOffsets, bodyTop, bodyBottom);
      if (placed && isFlexible) flexibleBoxes.push(box);
    }
  }

  // Redistribution phase for flexible boxes
  redistributeBoxes(flexibleBoxes, occupied, bodyTop, bodyBottom, marginOffsets);
}

Step 2: Verify syntax

Run: node --check assets/js/sidenotes.js Expected: Error - placeBox and redistributeBoxes not defined yet. That’s expected.

Step 3: Commit (partial - will complete in next tasks)

git add assets/js/sidenotes.js
git commit -m "feat(sidenotes): rewrite positionMarginBoxes with tiered placement

WIP: Implements priority tiers (high→normal→low) and vertical preference
partitioning (top→bottom→near→gap). Calls placeBox and redistributeBoxes
which will be added in subsequent commits."

Task 5: Add placeBox Function

Files: - Modify: assets/js/sidenotes.js (add before positionMarginBoxes)

Step 1: Add placeBox function

Add before positionMarginBoxes:

/**
 * Place a single margin box according to its preferences
 * @returns {boolean} - Whether placement succeeded
 */
function placeBox(box, direction, occupied, marginOffsets, bodyTop, bodyBottom) {
  const leftMargin = getMargin('left');
  const rightMargin = getMargin('right');
  const prefs = box._prefs || {};
  const height = box.offsetHeight;

  // Determine candidate sides
  let candidateSides;
  if (prefs.horizontal) {
    candidateSides = [prefs.horizontal];
  } else {
    candidateSides = ['left', 'right'];
  }

  let bestSide = null;
  let bestTop = null;

  for (const side of candidateSides) {
    const marginOffset = marginOffsets[side];
    const ranges = occupied[side];
    let candidateTop;

    switch (direction) {
      case 'top':
        // Fill from top downward
        candidateTop = findAvailableSlot(0, height, ranges, 'down');
        // Pick side that allows highest placement
        if (bestTop === null || candidateTop < bestTop) {
          bestTop = candidateTop;
          bestSide = side;
        }
        break;

      case 'bottom':
        // Fill from body bottom upward
        const bottomTarget = bodyBottom - marginOffset - height;
        candidateTop = findAvailableSlot(bottomTarget, height, ranges, 'up');
        // Ensure we don't go below body text
        candidateTop = Math.min(candidateTop, bodyBottom - marginOffset - height);
        // Pick side that allows lowest placement
        if (bestTop === null || candidateTop > bestTop) {
          bestTop = candidateTop;
          bestSide = side;
        }
        break;

      case 'near':
        // Place near original position in document
        const originalTop = parseFloat(box.dataset.originalTop) || 0;
        const targetTop = originalTop - marginOffset;
        candidateTop = findClosestSlot(targetTop, height, ranges);
        // Pick side closest to original position
        const distance = Math.abs(candidateTop - targetTop);
        if (bestTop === null || distance < Math.abs(bestTop - (parseFloat(box.dataset.originalTop) - marginOffsets[bestSide]))) {
          bestTop = candidateTop;
          bestSide = side;
        }
        break;

      case 'gap':
        // Fill largest available gap
        const relativeBodyTop = bodyTop - marginOffset;
        const relativeBodyBottom = bodyBottom - marginOffset;
        const gap = findLargestGap(ranges, relativeBodyTop, relativeBodyBottom);
        candidateTop = gap.start;
        // Pick side with largest gap
        if (bestTop === null || gap.size > (box._bestGapSize || 0)) {
          bestTop = candidateTop;
          bestSide = side;
          box._bestGapSize = gap.size;
        }
        break;
    }
  }

  // Place the box
  if (bestSide && bestTop !== null) {
    const margin = bestSide === 'left' ? leftMargin : rightMargin;

    // Clamp to body boundaries
    const marginOffset = marginOffsets[bestSide];
    const maxTop = bodyBottom - marginOffset - height;
    bestTop = Math.max(0, Math.min(bestTop, maxTop));

    box.style.top = `${bestTop}px`;
    box.classList.add(`margin-${bestSide}`);
    box._placedSide = bestSide;
    box._placedTop = bestTop;
    margin.appendChild(box);

    // Record occupied space
    occupied[bestSide].push({
      top: bestTop,
      bottom: bestTop + height,
      element: box
    });

    // Clean up temporary property
    delete box._bestGapSize;

    return true;
  }

  return false;
}

Step 2: Verify syntax

Run: node --check assets/js/sidenotes.js Expected: No output (success) or error for missing redistributeBoxes (that’s fine)

Step 3: Commit

git add assets/js/sidenotes.js
git commit -m "feat(sidenotes): add placeBox function for preference-based placement

Handles four placement modes:
- top: fill downward from margin top
- bottom: fill upward from body text end
- near: closest to original document position
- gap: fill largest available space

Respects horizontal preferences when specified."

Task 6: Add redistributeBoxes Function

Files: - Modify: assets/js/sidenotes.js (add after placeBox)

Step 1: Add redistributeBoxes function

Add after placeBox:

/**
 * Redistribute flexible boxes to even out spacing
 * High-priority boxes remain locked; normal and low priority can shift
 */
function redistributeBoxes(flexibleBoxes, occupied, bodyTop, bodyBottom, marginOffsets) {
  if (flexibleBoxes.length === 0) return;

  // Process each margin independently
  for (const side of ['left', 'right']) {
    const sideBoxes = flexibleBoxes.filter(b => b._placedSide === side);
    if (sideBoxes.length === 0) continue;

    const marginOffset = marginOffsets[side];
    const ranges = occupied[side];

    // Get locked elements (sidenotes and high-priority boxes)
    const lockedRanges = ranges.filter(r => {
      if (!r.element) return true; // Sidenotes don't have element ref
      return r.element._prefs?.priority === 'high';
    });

    // Sort flexible boxes by current position
    sideBoxes.sort((a, b) => a._placedTop - b._placedTop);

    // Calculate total available space and required space
    const relativeBodyTop = Math.max(0, bodyTop - marginOffset);
    const relativeBodyBottom = bodyBottom - marginOffset;

    let totalRequiredHeight = 0;
    for (const box of sideBoxes) {
      totalRequiredHeight += box.offsetHeight + CONFIG.sidenoteSpacing;
    }

    // Find contiguous regions not occupied by locked elements
    const availableRegions = findAvailableRegions(lockedRanges, relativeBodyTop, relativeBodyBottom);

    // Distribute flexible boxes evenly within available regions
    // Simple approach: even spacing within the region they're currently in
    for (const region of availableRegions) {
      const regionBoxes = sideBoxes.filter(b =>
        b._placedTop >= region.start && b._placedTop < region.end
      );

      if (regionBoxes.length === 0) continue;

      // Calculate even spacing
      let totalBoxHeight = 0;
      for (const box of regionBoxes) {
        totalBoxHeight += box.offsetHeight;
      }

      const availableSpace = region.end - region.start - totalBoxHeight;
      const gapCount = regionBoxes.length + 1;
      const evenGap = Math.max(CONFIG.sidenoteSpacing, availableSpace / gapCount);

      // Reposition boxes with even gaps
      let currentTop = region.start + evenGap;
      for (const box of regionBoxes) {
        box.style.top = `${currentTop}px`;
        box._placedTop = currentTop;

        // Update occupied range
        const rangeIndex = occupied[side].findIndex(r => r.element === box);
        if (rangeIndex !== -1) {
          occupied[side][rangeIndex].top = currentTop;
          occupied[side][rangeIndex].bottom = currentTop + box.offsetHeight;
        }

        currentTop += box.offsetHeight + evenGap;
      }
    }
  }
}

/**
 * Find regions not occupied by locked elements
 */
function findAvailableRegions(lockedRanges, boundaryTop, boundaryBottom) {
  const sorted = [...lockedRanges].sort((a, b) => a.top - b.top);
  const regions = [];
  let prevEnd = boundaryTop;

  for (const range of sorted) {
    if (range.top > prevEnd + CONFIG.sidenoteSpacing * 2) {
      regions.push({ start: prevEnd, end: range.top });
    }
    prevEnd = Math.max(prevEnd, range.bottom + CONFIG.sidenoteSpacing);
  }

  // Final region after last locked element
  if (boundaryBottom > prevEnd + CONFIG.sidenoteSpacing) {
    regions.push({ start: prevEnd, end: boundaryBottom });
  }

  return regions;
}

Step 2: Verify syntax

Run: node --check assets/js/sidenotes.js Expected: No output (success)

Step 3: Commit

git add assets/js/sidenotes.js
git commit -m "feat(sidenotes): add redistributeBoxes for even spacing

Shifts normal and low priority boxes to balance gaps.
High priority boxes and sidenotes remain locked.
Preserves relative order within each margin."

Task 7: Update reposition to Clear Placement State

Files: - Modify: assets/js/sidenotes.js:375-393 (reposition function)

Step 1: Update reposition to clear box placement state

Find the reposition function and update the marginBoxes reset loop. Replace:

marginBoxes.forEach(box => {
  box.style.top = '';
  box.classList.remove('margin-left', 'margin-right');
});

With:

marginBoxes.forEach(box => {
  box.style.top = '';
  box.classList.remove('margin-left', 'margin-right');
  delete box._placedSide;
  delete box._placedTop;
});

Step 2: Verify syntax

Run: node --check assets/js/sidenotes.js Expected: No output (success)

Step 3: Commit

git add assets/js/sidenotes.js
git commit -m "fix(sidenotes): clear placement state on reposition

Ensures _placedSide and _placedTop are reset when recalculating
positions (e.g., on window resize)."

Task 8: Manual Browser Testing

Files: - Test: assets/js/sidenotes.js (in browser)

Step 1: Start development server

Run: make serve (in a separate terminal)

Step 2: Create test HTML with various margin preferences

Create a test article or modify an existing one to include margin boxes with different preferences:

<!-- Test cases to verify in browser -->
<div class="margin-box" data-margin="top-right-high">Premium (top-right-high)</div>
<div class="margin-box" data-margin="top-left">Top left, normal priority</div>
<div class="margin-box" data-margin="bottom-low">Bottom, low priority</div>
<div class="margin-box" data-margin="near">Near anchor point</div>
<div class="margin-box">No preference (gap fill)</div>

Step 3: Verify placement behavior

Check in browser console that: 1. High priority boxes are placed first and don’t move during redistribution 2. Top boxes fill from top downward 3. Bottom boxes fill from body bottom upward 4. Near boxes stay close to their original position 5. No-preference boxes fill gaps 6. Redistribution evens out spacing for normal/low priority

Step 4: Test edge cases

  • Many sidenotes (collision handling)
  • Window resize (reposition works)
  • Narrow viewport (falls back correctly)

Step 5: Commit any fixes

git add assets/js/sidenotes.js
git commit -m "fix(sidenotes): [describe any fixes from testing]"

Task 9: Add Sidenote Element References to Occupied Ranges

Files: - Modify: assets/js/sidenotes.js:287-291 (in positionSidenotes)

Step 1: Add element reference to sidenote occupied ranges

In positionSidenotes, find the occupied range recording (around line 287-291):

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

Change to:

// Record occupied range (no element ref = sidenote, always locked)
occupied[currentMargin].push({
  top: actualTop,
  bottom: actualTop + sn.offsetHeight,
  element: null  // null signals this is a sidenote (always locked)
});

Step 2: Verify syntax

Run: node --check assets/js/sidenotes.js Expected: No output (success)

Step 3: Commit

git add assets/js/sidenotes.js
git commit -m "refactor(sidenotes): add null element ref to sidenote occupied ranges

Allows redistributeBoxes to distinguish sidenotes (always locked)
from margin boxes (may be flexible)."

Summary

After completing all tasks, the sidenotes.js file will support:

  1. Preference parsing - data-margin="top-right-high" etc.
  2. Tiered placement - sidenotes → high → normal → low priority
  3. Vertical preferences - top, bottom, near, gap-fill
  4. Horizontal preferences - left, right, or algorithm’s choice
  5. Redistribution - even spacing for flexible boxes
  6. Boundary constraint - content doesn’t overflow body text

The CSS requires no changes - positioning remains absolute within margin containers.