Margin Nudge: Incremental Layout for Dynamic Content
Date: 2026-02-21
Problem
When a margin box changes size dynamically (subscribe confirmation, video annotations), the layout engine does a full reposition: clears all positions, re-measures everything, re-runs the multi-pass placement algorithm. This causes two problems:
- Teleportation: the growing box may land somewhere else entirely, even though the reader’s attention is on it.
- Overlap: if reposition doesn’t trigger or is delayed, the growing box overlaps items below it.
Design
Split the layout response into two paths: nudge for in-place content changes, full reposition for structural changes.
Trigger Routing
| Trigger | Response |
|---|---|
| ResizeObserver on a placed box | Nudge |
| Window resize | Full reposition |
injectMarginBox |
Full reposition |
removeMarginBox |
Full reposition |
Sidenotes.reposition() (API) |
Full reposition |
| HTMX swap / history restore | Full reinitialize |
Nudge Behaviour
- Box grows: shift all items below it on the same margin side down by the
height delta. Grow the margin column if items are pushed past the body
bottom (
ensureColumnsAccommodateContent()). - Box shrinks: update the element’s occupied range but move nothing. The gap remains until the next full reposition.
- Animated: nudged items transition smoothly (200ms ease-out). Full reposition keeps its existing snap-and-reveal.
No Proactive Cleanup
Accumulated gaps from shrink events are cleaned up by the next natural full reposition (window resize, page navigation). No threshold-based cleanup – it would reintroduce the teleportation problem.
Implementation
1. Persistent placedState Structure
Promote the ephemeral occupied local variable to a module-level canonical
data structure used by all layout functions:
let placedState = null; // null when no layout exists
// After positioning:
placedState = {
occupied: {
left: [ { top, bottom, element }, ... ], // sorted by top ascending
right: [ { top, bottom, element }, ... ] // sorted by top ascending
},
heights: new Map() // element -> last known height (px)
};
Sorted invariant: both occupied.left and occupied.right are maintained
in ascending top order via binary-insert. This eliminates defensive sort
copies in findAvailableSlot(), findLargestGap(), and makes nudge trivial
(“everything below” = array slice after the changed element’s index).
Set to null on cleanup().
2. Refactor Existing Functions to Use placedState
reposition()– initialisesplacedStateat the start instead of using a localoccupiedvariable. Records heights intoplacedState.heightsafter placement.positionSidenotes()– writes intoplacedState.occupiedinstead of returning a new object.positionMarginBoxes()/redistributeBoxes()– read and writeplacedState.occupied.findAvailableSlot(),findLargestGap()– drop[...occupied].sort()copies; read the pre-sorted arrays directly.cleanup()– setsplacedState = null.
3. Smarter ResizeObserver Callback
Replace the blunt debounced invalidate('content-reflow') with entry
inspection:
resizeObserver = new ResizeObserver((entries) => {
if (!placedState) { invalidate('content-reflow'); return; }
const changes = [];
for (const entry of entries) {
const el = entry.target;
const oldHeight = placedState.heights.get(el);
if (oldHeight === undefined) continue;
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);
});
No debounce on the nudge path (nudge is cheap). The 50ms debounce only
applied to the full-reposition path and is preserved there via invalidate().
4. The nudge() Function
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 range
ranges[index].bottom += delta;
if (delta > 0) {
// Growing: push everything below down
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
}
ensureColumnsAccommodateContent();
}
5. Helper: Binary Insert
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);
}
6. Helper: Find Occupied Side
function findOccupiedSide(element) {
for (const side of ['left', 'right']) {
if (placedState.occupied[side].some(r => r.element === element)) {
return side;
}
}
return null;
}
7. CSS Transitions
.margin-box,
.sidenote {
transition: top 200ms ease-out;
}
body.repositioning .margin-box,
body.repositioning .sidenote {
transition: none;
}
The repositioning class (already added/removed by reposition()) suppresses
transitions during full recalculation. Nudge never adds it, so transitions
fire naturally.
Files Changed
| File | Change |
|---|---|
assets/js/sidenotes.js |
All JS changes: placedState, nudge, refactored functions, ResizeObserver |
src/almnck/static/css/sidenotes.css (or equivalent) |
Transition rules |
What Stays the Same
- Full reposition path (window resize, inject/remove, API, HTMX)
- Touch/swipe mode
- Priority tiers, wash assignment, sundial properties
- Public API surface (
injectMarginBox,removeMarginBox,reposition)