Manual
Almnck.
Price: 50ⓐ

iOS Safari Horizontal Scroll-Snap Bug

Date: 2026-01-25 Status: FIXED Playwright test: src/tests/test_mobile_margins.py (TestMobileMarginsWithInteractiveFigures)

The Bug

On iOS Safari, vertical swipes on the body text of articles with certain content cause unexpected horizontal scroll-snap navigation to the left margin column.

Symptoms: - User swipes vertically to scroll down the article - Page unexpectedly snaps horizontally to the left margin (scrollLeft goes from ~332px to 0) - Only affects certain pages (regolith), not others (front page, logiebair)

Test Setup

  • Appium with XCUITest driver for iOS Safari automation
  • iOS Simulator: iPhone 16e, iOS 26.2, UDID: AB908206-17BD-41F1-8911-7D7D6A23E4F2
  • JavaScript instrumentation to detect scroll position changes (avoids screenshot overhead)
  • Test URL: http://localhost:1969/6026/1/3/regolith-with-latitude/

Key Findings

1. The Bug is Real and Reproducible

  • Automated test confirms 332px horizontal drift on vertical swipe
  • Bug occurs on regolith page but NOT on front page or logiebair (which also has interactive figures)

2. Safari Caching is a Major Confound

  • Safari aggressively caches pages, CSS, and JS
  • Tests on the same URL may show stale behavior
  • Solution: Create fresh test articles at new URLs (e.g., /_draft/6026/1/XX/test-name/)
  • Killing Safari and clearing defaults doesn’t reliably clear the cache

3. What Does NOT Cause the Bug

Hypothesis Test Result
touch-action: none on canvas Changed to pan-x, then removed Still fails
touch-action on figures Added pan-y to [data-interactive] Still fails
touch-action on body-text Added pan-y Still fails
Figure JavaScript (initFigures) Disabled JS entirely Still fails
display: flex on figures Removed Still fails
data-interactive attribute Removed Still fails
Number of interactive figures Tested 1, 2, 3 figures All pass on minimal page
The <script type="module"> tag Removed entirely Still fails
scroll-snap-align on margin-box Added none Still fails
contain: layout on margin-box Added Still fails

4. What DOES Cause the Bug

The data-margin attribute containing “bottom” triggers the bug.

Test Result
Full regolith content (poem has data-margin="bottom-high") FAIL (332px drift)
Regolith WITHOUT the poem aside PASS (0px drift)
Regolith with poem but WITHOUT data-margin attribute PASS (0px drift)
Quote aside WITH data-margin="bottom-high" FAIL (332px drift)
Quote aside WITHOUT data-margin PASS (0px drift)
data-margin="bottom" FAIL (332px drift)
data-margin="high" PASS (0px drift)
data-margin="left" PASS (0px drift)

It’s not: - The data-type="poem" attribute - The markdown attribute - The content length - Any specific aside type - The “high” priority token - The “left” positioning token

It IS: - Specifically the token “bottom” in data-margin - The bug occurs even WITHOUT JavaScript running (0 canvases initialized) - This is a pure HTML/CSS interaction with iOS Safari’s scroll-snap behavior

5. The Margin-Box Lifecycle

  1. Initial HTML: The <aside class="margin-box"> is written inline in the article markdown, inside .body-text
  2. JS Processing: sidenotes.js moves it to the margin column (.margin-left or .margin-right)
  3. CSS Positioning: It gets position: absolute and is visually placed in the margin

After JS runs, the margin-box: - Has parent: 'margin margin-left' (moved to margin column) - Has inBodyText: false (no longer in body-text) - Has top: 0px and full column width

6. Working vs Broken Pages

Page Has Interactive Figures Has Inline Margin-Box Result
Front page No No PASS
Logiebair Yes (3) No (has injected ones only?) PASS
Regolith Yes (3) Yes (poem aside) FAIL
Minimal test (3 figs, no aside) Yes No PASS
Minimal test (3 figs, with aside) Yes Yes FAIL

7. Figure JS Can Crash WebKit

When testing a minimal page with figure JS initialization, Safari/WebKit crashed entirely. This suggests the figure JS may have other iOS Safari compatibility issues beyond this scroll bug.

Root Cause (FOUND)

Absolutely positioned elements extending beyond their scroll-snap column trigger an iOS Safari bug.

Through systematic testing, we found the exact threshold:

Position BoxBottom ColHeight Overflow Result
2699 3438 3438 0 PASS
2749 3488 3438 50 FAIL

Any overflow beyond the column height triggers the bug. Even 50px is enough.

Why the Initial Fix Failed

The initial attempt to measure height before placement failed because:

  1. Margin-boxes have different CSS in body-text vs margin column:
  2. In body-text: max-width: 70% (narrower)
  3. In margin: width: 100% (wider)
  4. The poem text wraps differently at different widths
  5. Measured height in body-text was 538px, actual height in margin was 739px
  6. Using the wrong height caused incorrect clamping (2864px instead of 2699px)

The Fix

Measure height AFTER placing the box in its margin column, then clamp:

// Place box in margin column first
box.style.top = `${bestTop}px`;
margin.appendChild(box);

// Measure actual height in the margin column context
box.style.opacity = '0';
box.style.display = 'block';
const actualHeight = box.offsetHeight;
box.style.display = '';
box.style.opacity = '';

// Clamp using actual height
const maxTop = bodyBottom - marginOffset - actualHeight;
const clampedTop = Math.max(0, Math.min(bestTop, maxTop));

if (clampedTop !== bestTop) {
  box.style.top = `${clampedTop}px`;
}

This ensures we measure in the actual rendering context where width affects text wrapping.

Testing the Fix

All pages now pass the vertical swipe test: - Regolith (with interactive figures + poem aside): PASS - Logiebair (with interactive figures): PASS - Front page: PASS

Files Modified

  • assets/js/sidenotes.js - Measure height after placement, then clamp
  • src/tests/test_mobile_margins.py - Added Playwright tests for swipe behavior

Note: Django serves JS from assets/ in dev mode, so no need to copy files.

Cleanup Needed

  • Remove test articles from editorial/inbox/ (regolith-margin-*, regolith-poem-no-js, etc.)
  • Consider filing a WebKit bug report about scroll-snap sensitivity to overflowing absolute elements

Appendix: iOS Safari Test Script (Appium)

This script was used to debug the issue on actual iOS Safari. It requires: - Appium with XCUITest driver - iOS Simulator running - Local dev server at localhost:1969

#!/usr/bin/env python3
"""Test iOS Safari swipe behavior on pages with interactive figures.

Uses Appium to automate Safari on iOS Simulator and JavaScript instrumentation
to detect scroll position issues without relying on screenshots.

Requirements:
    pip install Appium-Python-Client

Run Appium server:
    appium --use-drivers=xcuitest

Run iOS Simulator:
    xcrun simctl boot "iPhone 16e"
"""

import time
from appium import webdriver
from appium.options.ios import XCUITestOptions


def create_driver():
    """Create Appium driver for Safari on iOS Simulator."""
    options = XCUITestOptions()
    options.platform_name = "iOS"
    options.platform_version = "26.2"  # Update for your simulator
    options.device_name = "iPhone 16e"
    options.browser_name = "Safari"
    # Get UDID with: xcrun simctl list devices | grep Booted
    options.udid = "YOUR-SIMULATOR-UDID"

    return webdriver.Remote(
        command_executor="http://localhost:4723/wd/hub",
        options=options
    )


def inject_scroll_monitor(driver):
    """Inject JavaScript to monitor scroll events."""
    driver.execute_script("""
        window._scrollMonitor = {
            initialScrollLeft: null,
            currentScrollLeft: null,
            events: []
        };

        const layout = document.querySelector('.margins-layout');
        if (layout) {
            window._scrollMonitor.initialScrollLeft = layout.scrollLeft;
            window._scrollMonitor.currentScrollLeft = layout.scrollLeft;

            layout.addEventListener('scroll', function(e) {
                window._scrollMonitor.currentScrollLeft = layout.scrollLeft;
                window._scrollMonitor.events.push({
                    time: Date.now(),
                    scrollLeft: layout.scrollLeft
                });
            });
        }
    """)


def test_vertical_scroll():
    """Test that vertical scroll doesn't cause horizontal drift."""
    driver = create_driver()
    try:
        driver.get("http://localhost:1969/6026/1/3/regolith-with-latitude/")
        time.sleep(3)

        inject_scroll_monitor(driver)

        # Get body text position
        body_rect = driver.execute_script("""
            const el = document.querySelector('.body-text');
            const rect = el.getBoundingClientRect();
            return { x: rect.x + rect.width/2, y: rect.y + 150 };
        """)

        # Vertical swipe
        start_x = int(body_rect['x'])
        start_y = int(body_rect['y'])
        driver.swipe(start_x, start_y, start_x, start_y - 300, duration=100)
        time.sleep(1)

        # Check drift
        state = driver.execute_script("return window._scrollMonitor")
        drift = abs(state['currentScrollLeft'] - state['initialScrollLeft'])

        print(f"Initial: {state['initialScrollLeft']}, Final: {state['currentScrollLeft']}")
        print(f"Drift: {drift}px - {'FAIL' if drift > 50 else 'PASS'}")

    finally:
        driver.quit()


if __name__ == "__main__":
    test_vertical_scroll()