Margin Nudge Implementation Plan
For Claude: REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
Goal: Replace the all-or-nothing reposition with a two-path system: cheap incremental nudge for in-place content changes, full reposition for structural changes.
Design Document: doc/05-process/plans/2026-02-21-margin-nudge-design.md
Tech Stack: Vanilla JavaScript, CSS transitions, Playwright+pytest browser tests.
Approach: Two phases. Phase 1 refactors occupied into a persistent, sorted placedState — full reposition should behave identically afterward. Phase 2 adds the nudge code path. Each phase is independently testable and committable.
Phase 1: Promote occupied to placedState
Task 1: Introduce placedState and binary-insert helper
Files:
- Modify: assets/js/sidenotes.js
Step 1: Add placedState declaration alongside existing module state (near line 103)
Add after the existing let resizeHandler block:
let placedState = null;
Step 2: Add insertOccupiedRange() helper in the Slot Placement Algorithms section (after findLargestGap, near line 259)
function insertOccupiedRange(side, range) {
const ranges = placedState.occupied[side];
let lo = 0, hi = ranges.length;
while (lo < hi) {
const mid = (lo + hi) >>> 1;
if (ranges[mid].top < range.top) lo = mid + 1;
else hi = mid;
}
ranges.splice(lo, 0, range);
}
Verification: No behaviour change yet. make test should pass unchanged.
Task 2: Refactor reposition() to initialise placedState
Files:
- Modify: assets/js/sidenotes.js
Step 1: In reposition() (line 1465), initialise placedState before calling sub-functions
Replace the comment // Recalculate and the local occupied variable with:
placedState = {
occupied: { left: [], right: [] },
heights: new Map()
};
Step 2: Remove const occupied = from the positionSidenotes() call
Change:
const occupied = positionSidenotes();
if (occupied) {
positionMarginBoxes(occupied);
}
To:
if (positionSidenotes()) {
positionMarginBoxes();
}
positionSidenotes() will return a truthy signal (e.g. true) instead of the occupied object. positionMarginBoxes() reads from placedState directly.
Verification: Tests should still pass. Layout should be identical.
Task 3: Refactor positionSidenotes() to write into placedState
Files:
- Modify: assets/js/sidenotes.js
Step 1: Remove local occupied declaration (line 789)
The function currently creates const occupied = { left: [], right: [] }. Remove this — it now uses placedState.occupied.
Step 2: Replace .push() with insertOccupiedRange() (line 895)
Change:
occupied[currentMargin].push({
top: actualTop,
bottom: sidenoteBottom,
element: null
});
To:
insertOccupiedRange(currentMargin, {
top: actualTop,
bottom: sidenoteBottom,
element: null
});
Note: sidenotes are placed in document order and alternate L/R, so they’re already approximately sorted by top within each side. Binary-insert handles the cases where collision-avoidance pushes a sidenote past a later one.
Step 3: Record sidenote heights in placedState.heights
After positioning each sidenote (after the sn.style.top = ... line), add:
placedState.heights.set(sn, snHeight);
Step 4: Change return value
Replace return occupied; with return true;. On the early-return paths
(guards at top of function), return false instead of bare return.
Verification: make test passes. Layout identical.
Task 4: Refactor positionMarginBoxes() and placeBox() to use placedState
Files:
- Modify: assets/js/sidenotes.js
Step 1: Remove occupied parameter from positionMarginBoxes() (line 1119)
Change signature from function positionMarginBoxes(occupied) to
function positionMarginBoxes(). All references to occupied inside this
function become placedState.occupied.
Step 2: Remove occupied parameter from placeBox() (line 922)
Change signature from placeBox(box, direction, occupied, marginOffsets, bodyTop, bodyBottom) to placeBox(box, direction, marginOffsets, bodyTop, bodyBottom). Read ranges from placedState.occupied[side].
Step 3: Replace .push() with insertOccupiedRange() in placeBox() (line 1042)
Change:
occupied[bestSide].push({
top: clampedTop,
bottom: clampedTop + height,
element: box
});
To:
insertOccupiedRange(bestSide, {
top: clampedTop,
bottom: clampedTop + height,
element: box
});
Step 4: Record box heights in placedState.heights
After placing the box, add:
placedState.heights.set(box, height);
Step 5: Update all placeBox() call sites
Remove the occupied argument from every call to placeBox() inside
positionMarginBoxes().
Verification: make test passes. Layout identical.
Task 5: Refactor redistributeBoxes() to use placedState
Files:
- Modify: assets/js/sidenotes.js
Step 1: Remove occupied parameter from signature (line 1022)
Change from redistributeBoxes(flexibleBoxes, occupied, bodyTop, bodyBottom, marginOffsets) to redistributeBoxes(flexibleBoxes, bodyTop, bodyBottom, marginOffsets). Read from placedState.occupied inside the function.
Step 2: Update the call site in positionMarginBoxes()
Remove the occupied argument.
Step 3: When updating occupied ranges during redistribution (line 1080-1083), update placedState.heights too if height changed
The redistribution doesn’t change box heights, only positions. The existing
range-update logic (finding and updating occupied[side][rangeIndex]) is
fine — it’s already updating placedState.occupied since we removed the
local variable.
Verification: make test passes. Layout identical.
Task 6: Drop defensive sorts from slot-finding functions
Files:
- Modify: assets/js/sidenotes.js
Now that placedState.occupied arrays are maintained in sorted order, the
defensive copies can go.
Step 1: In findAvailableSlot() (line 181)
For the 'down' branch, replace:
const sortedAsc = [...occupied].sort((a, b) => a.top - b.top);
for (const range of sortedAsc) {
With:
for (const range of occupied) {
For the 'up' branch, the descending sort is still needed since we iterate
in reverse order. Replace the spread+sort with a reverse iteration:
for (let i = occupied.length - 1; i >= 0; i--) {
const range = occupied[i];
Step 2: In findLargestGap() (line 237)
Replace:
const sorted = [...occupied].sort((a, b) => a.top - b.top);
With:
const sorted = occupied; // already sorted by top ascending
(Or just use occupied directly and remove the sorted variable.)
Step 3: In findAvailableRegions() (line 1095)
Replace:
const sorted = [...lockedRanges].sort((a, b) => a.top - b.top);
lockedRanges is a .filter() of placedState.occupied[side], which
preserves order. So this sort is also redundant. Replace with direct use.
Verification: make test passes. Layout identical. This is the payoff
of the sorted invariant — less allocation, fewer copies, clearer code.
Task 7: Null out placedState on cleanup
Files:
- Modify: assets/js/sidenotes.js
Step 1: In cleanup() (around line 1509), add:
placedState = null;
Add it near the top of the function, alongside the existing timer cancellation.
Verification: make test passes. HTMX swap tests in
test_layout_lifecycle.py confirm no regressions.
Task 8: Commit Phase 1
Commit all Phase 1 changes as a single commit. Message:
Promote occupied ranges to persistent placedState with sorted invariant
Replaces the ephemeral local occupied variable with a module-level
placedState structure maintained in sorted order via binary-insert.
Eliminates defensive sort copies in slot-finding functions. No
behaviour change — preparation for incremental nudge.
Run make test one final time before committing.
Phase 2: Add Nudge Path
Task 9: Add findOccupiedSide() and nudge() functions
Files:
- Modify: assets/js/sidenotes.js
Step 1: Add findOccupiedSide() helper near insertOccupiedRange()
function findOccupiedSide(element) {
for (const side of ['left', 'right']) {
if (placedState.occupied[side].some(r => r.element === element)) {
return side;
}
}
return null;
}
Step 2: Add nudge() function after the helper section, before reposition()
function nudge(changes) {
for (const { element, oldHeight, newHeight } of changes) {
const delta = newHeight - oldHeight;
placedState.heights.set(element, newHeight);
const side = findOccupiedSide(element);
if (!side) continue;
const ranges = placedState.occupied[side];
const index = ranges.findIndex(r => r.element === element);
if (index === -1) continue;
// Update this element's own occupied range
ranges[index].bottom += delta;
if (delta > 0) {
// Growing: push everything below down by delta
for (let i = index + 1; i < ranges.length; i++) {
ranges[i].top += delta;
ranges[i].bottom += delta;
if (ranges[i].element) {
ranges[i].element.style.top =
parseFloat(ranges[i].element.style.top) + delta + 'px';
}
}
}
// Shrinking: do nothing to items below — gap remains
}
ensureColumnsAccommodateContent();
}
Verification: Function exists but is not called yet. make test passes.
Task 10: Rewrite ResizeObserver callback to route nudge vs invalidate
Files:
- Modify: assets/js/sidenotes.js
Step 1: Replace the ResizeObserver creation in setupObservers() (line 1722)
Replace:
resizeObserver = new ResizeObserver(() => {
clearTimeout(reflowTimeout);
reflowTimeout = setTimeout(() => {
if (shouldEnableMargins()) {
invalidate('content-reflow');
}
}, 50);
});
With:
let reflowTimeout;
resizeObserver = new ResizeObserver((entries) => {
if (!placedState || !isEnabled) {
// No layout state yet (mid-init or after cleanup) — full reposition
clearTimeout(reflowTimeout);
reflowTimeout = setTimeout(() => {
if (shouldEnableMargins()) {
invalidate('content-reflow');
}
}, 50);
return;
}
const changes = [];
for (const entry of entries) {
const el = entry.target;
const oldHeight = placedState.heights.get(el);
if (oldHeight === undefined) continue; // not a placed element
const newHeight = entry.contentRect.height;
if (Math.abs(newHeight - oldHeight) < 1) continue; // sub-pixel noise
changes.push({ element: el, oldHeight, newHeight });
}
if (changes.length === 0) return;
nudge(changes);
});
Note: the let reflowTimeout may already be declared in the enclosing
scope — check and avoid redeclaration.
Verification: make test passes. Dynamic content changes now route to
nudge() instead of full reposition.
Task 11: Add CSS transition for nudged items
Files:
- Modify: assets/css/almanack.css
Step 1: Add top transition to sidenotes and margin boxes
Find the existing .repositioning rule (line 750-754). Just above it, add a
transition to the base sidenote/margin-box rules. The exact location depends
on where the base .sidenote and .margin-box rules are — the transition
should be on the elements themselves, not scoped to a parent class.
Add to the existing .sidenote rule (near line 739, which already has
transition: opacity 0.4s ease-out, transform 0.4s ease-out):
Extend that existing transition to include top:
transition: opacity 0.4s ease-out, transform 0.4s ease-out, top 200ms ease-out;
For .margin-box, find or add a similar base rule with:
transition: top 200ms ease-out;
The existing .repositioning override (transition: none !important) already
suppresses all transitions during full reposition.
Verification: make test passes. Visually confirm that nudged items
slide smoothly when a box grows.
Task 12: Write browser test for nudge behaviour
Files:
- Create: src/tests/test_margin_nudge.py
Write a Playwright browser test that:
- Navigates to a page with multiple margin boxes
- Waits for layout ready
- Records the
toppositions of all margin boxes on one side - Injects content into one box to make it grow (via
page.evaluate()to changeinnerHTMLof a margin box) - Waits briefly for the nudge to apply (200ms + buffer)
- Asserts that the grown box stayed at its original
topposition - Asserts that boxes below it moved down by approximately the growth delta
- Asserts that boxes above it did not move
Mark with @pytest.mark.browser.
A second test for the shrink case:
- Same setup
- Shrink a box’s content
- Assert that items below it did NOT move (gap preserved)
- Assert the box itself stayed at its original
top
Verification: make test-browser passes with the new tests.
Task 13: Commit Phase 2
Commit all Phase 2 changes. Message:
Add incremental nudge for dynamic margin box content changes
When a margin box grows, items below it slide down smoothly instead
of the whole layout being recalculated. When a box shrinks, the gap
is preserved until the next structural reposition. Full reposition
still fires for window resize, inject/remove, and HTMX swaps.
Run make test before committing.