From 7318b32f9db85f01aac3f5c68bc05fe49dcfbc56 Mon Sep 17 00:00:00 2001 From: therealsama <263038098+therealsama@users.noreply.github.com> Date: Fri, 29 May 2026 19:56:14 +0200 Subject: [PATCH] fix: prevent panel swipe from capturing horizontal scroll in
 code blocks

- Add touch target detection in useSwipeScroll to yield horizontal gestures
  to scrollable 
 elements and [data-swipe-ignore] regions
- Add overscroll-behavior-x: contain to .comment-content pre in CSS
- Add tabindex=0 to 
 elements via sanitizer for keyboard accessibility
- Add unit tests for scrollable element bail logic
- Add e2e test for code block horizontal scroll on mobile
---
 e2e/comment-swipe.spec.ts        | 94 ++++++++++++++++++++++++++++++++
 e2e/fixtures/api-mocks.ts        |  2 +-
 e2e/fixtures/mock-data.ts        |  4 +-
 e2e/mobile-swipe.spec.ts         |  3 +-
 src/hooks/useSwipeScroll.test.ts | 88 ++++++++++++++++++++++++++++++
 src/hooks/useSwipeScroll.ts      | 20 +++++++
 src/index.css                    |  1 +
 src/utils/sanitize.test.ts       | 14 ++---
 src/utils/sanitize.ts            |  2 +
 9 files changed, 217 insertions(+), 11 deletions(-)

diff --git a/e2e/comment-swipe.spec.ts b/e2e/comment-swipe.spec.ts
index 0cf69c7..75a1724 100644
--- a/e2e/comment-swipe.spec.ts
+++ b/e2e/comment-swipe.spec.ts
@@ -367,4 +367,98 @@ test.describe('Mobile Comment Swipe Viewer', () => {
 
     await waitForSwipeReady(page, 4);
   });
+
+  test('horizontal swipe inside 
 code block scrolls code, not panel', async ({ page }) => {
+    // Navigate to comment 1001 which contains a 
 block with wide content
+    await page.goto('/#/item/1001');
+
+    await expectActiveSwipePanelText(page, 'patio11', { timeout: 10000 });
+    await waitForSwipeReady(page, 4);
+
+    // Find the 
 element inside the active comment panel
+    const pre = page.locator('.swipe-snap-panel.active .comment-content pre');
+    await expect(pre).toBeVisible({ timeout: 5000 });
+
+    // Verify it actually has horizontal overflow (scrollable)
+    const isScrollable = await pre.evaluate((el) => el.scrollWidth > el.clientWidth);
+    expect(isScrollable).toBe(true);
+
+    // Get bounding box for touch coordinates
+    const box = await pre.boundingBox();
+    expect(box).not.toBeNull();
+
+    const startX = box!.x + box!.width / 2;
+    const startY = box!.y + box!.height / 2;
+
+    // Perform horizontal touch swipe inside the 
+    await page.touchscreen.tap(startX, startY);
+    // Manual touch sequence: start, move left, end
+    // Use page.evaluate to dispatch proper touch events with correct target
+    // Note: WebKit doesn't support `new Touch()` constructor, so we use the
+    // deprecated document.createTouch/document.createTouchList as a fallback.
+    await page.evaluate(({ x, y, distance }) => {
+      const el = document.elementFromPoint(x, y);
+      if (!el) return;
+
+      interface WebKitDocument {
+        createTouch?(view: Window, target: EventTarget, id: number, pageX: number, pageY: number, screenX: number, screenY: number): Touch;
+        createTouchList?(...touches: Touch[]): TouchList;
+      }
+
+      function makeTouch(target: EventTarget, id: number, cx: number, cy: number): Touch {
+        try {
+          return new Touch({ identifier: id, target, clientX: cx, clientY: cy });
+        } catch {
+          // WebKit fallback (deprecated but still functional in Safari)
+          const doc = document as unknown as WebKitDocument;
+          return doc.createTouch!(window, target, id, cx, cy, cx, cy);
+        }
+      }
+
+      function makeTouchList(...touches: Touch[]): Touch[] | TouchList {
+        const doc = document as unknown as WebKitDocument;
+        if (doc.createTouchList) {
+          return doc.createTouchList(...touches);
+        }
+        return touches;
+      }
+
+      const startTouch = makeTouch(el, 1, x, y);
+      const touchStart = new TouchEvent('touchstart', {
+        bubbles: true,
+        cancelable: true,
+        touches: makeTouchList(startTouch),
+        changedTouches: makeTouchList(startTouch),
+      });
+      el.dispatchEvent(touchStart);
+
+      const endX = x - distance;
+      const moveTouch = makeTouch(el, 1, endX, y);
+      const touchMove = new TouchEvent('touchmove', {
+        bubbles: true,
+        cancelable: true,
+        touches: makeTouchList(moveTouch),
+        changedTouches: makeTouchList(moveTouch),
+      });
+      el.dispatchEvent(touchMove);
+
+      const endTouch = makeTouch(el, 1, endX, y);
+      const touchEnd = new TouchEvent('touchend', {
+        bubbles: true,
+        cancelable: true,
+        touches: makeTouchList(),
+        changedTouches: makeTouchList(endTouch),
+      });
+      el.dispatchEvent(touchEnd);
+    }, { x: startX, y: startY, distance: 80 });
+
+    // Wait a moment for any potential panel transition
+    await page.waitForTimeout(300);
+
+    // Panel should still show the same comment (not transitioned)
+    await expectActiveSwipePanelText(page, 'patio11');
+
+    // URL should not have changed
+    await expect(page).toHaveURL(/\/item\/1001/);
+  });
 });
diff --git a/e2e/fixtures/api-mocks.ts b/e2e/fixtures/api-mocks.ts
index 7ab5141..a31d079 100644
--- a/e2e/fixtures/api-mocks.ts
+++ b/e2e/fixtures/api-mocks.ts
@@ -310,7 +310,7 @@ export async function setupApiMocks(page: Page) {
         {
           objectID: '1001',
           author: 'patio11',
-          comment_text: 'The wasm-bindgen approach is really interesting. It essentially lets you write Rust that compiles to WebAssembly and then generates JS bindings automatically.',
+          comment_text: 'The wasm-bindgen approach is really interesting. It essentially lets you write Rust that compiles to WebAssembly and then generates JS bindings automatically.
const longCodeLine = "this is a very long line of code that extends well beyond the viewport width to ensure horizontal scrolling is required to see all content";
', created_at_i: Math.floor(Date.now() / 1000) - 1800, parent_id: 12345, story_id: 12345, diff --git a/e2e/fixtures/mock-data.ts b/e2e/fixtures/mock-data.ts index 530fb61..9dd4cec 100644 --- a/e2e/fixtures/mock-data.ts +++ b/e2e/fixtures/mock-data.ts @@ -20,7 +20,7 @@ export const mockItem1 = { export const mockComment = { id: 1001, by: 'patio11', - text: 'This is a really well-written piece. The section on wasm-bindgen was particularly insightful.', + text: 'This is a really well-written piece. The section on wasm-bindgen was particularly insightful.
const longCodeLine = "this is a very long line of code that extends well beyond the viewport width to ensure horizontal scrolling is required to see all content";
', time: now() - 1800, parent: 12345, kids: [2001], @@ -226,7 +226,7 @@ export const mockAlgoliaCommentItem = { id: 1001, type: 'comment', author: 'patio11', - text: 'The wasm-bindgen approach is really interesting. It essentially lets you write Rust that compiles to WebAssembly and then generates JS bindings automatically.', + text: 'This is a really well-written piece. The section on wasm-bindgen was particularly insightful.
const longCodeLine = "this is a very long line of code that extends well beyond the viewport width to ensure horizontal scrolling is required to see all content";
', created_at_i: now() - 1800, parent_id: 12345, story_id: 12345, diff --git a/e2e/mobile-swipe.spec.ts b/e2e/mobile-swipe.spec.ts index bd00248..0b79f0c 100644 --- a/e2e/mobile-swipe.spec.ts +++ b/e2e/mobile-swipe.spec.ts @@ -304,7 +304,8 @@ test.describe('Mobile Swipe Viewer', () => { const activePanel = getActiveSwipePanel(page); await activePanel.getByRole('button', { name: /1 reply|\d+ replies/i }).first().click(); - await expect(activePanel.locator('.reply-fade > *').first()).toBeVisible({ timeout: 5000 }); + // Wait for reply content to appear (stable selector — .reply-fade is transient and removed after 180ms) + await expect(activePanel.locator('.tree-trunk > .tree-branch .comment-content').first()).toBeVisible({ timeout: 5000 }); const getReplyState = () => activePanel.evaluate((panel) => { const replyBranch = panel.querySelector('.tree-trunk > .tree-branch'); diff --git a/src/hooks/useSwipeScroll.test.ts b/src/hooks/useSwipeScroll.test.ts index a3ec618..759d546 100644 --- a/src/hooks/useSwipeScroll.test.ts +++ b/src/hooks/useSwipeScroll.test.ts @@ -602,4 +602,92 @@ describe('useSwipeScroll', () => { expect(vi.getTimerCount()).toBe(0); }); }); + + describe('scrollable element bail', () => { + it('yields horizontal gesture to a scrollable
 with scroll room', () => {
+      render(createElement(TestHarness), { wrapper: Wrapper });
+
+      const panel = getPanel(0);
+
+      // Create a 
 element inside the panel with scrollable content
+      const pre = document.createElement('pre');
+      panel.appendChild(pre);
+      Object.defineProperty(pre, 'scrollLeft', { value: 0, writable: true, configurable: true });
+      Object.defineProperty(pre, 'scrollWidth', { value: 800, configurable: true });
+      Object.defineProperty(pre, 'clientWidth', { value: 300, configurable: true });
+
+      // Dispatch touch events directly on the 
 (they bubble to container)
+      dispatchTouch(pre, 'touchstart', CENTER_X, CENTER_Y);
+      // Horizontal swipe left (drag finger left = deltaX negative = scroll content right)
+      dispatchTouch(pre, 'touchmove', CENTER_X - 30, CENTER_Y);
+      dispatchTouch(pre, 'touchend', CENTER_X - 30, CENTER_Y);
+
+      // Panel should NOT have transitioned
+      expect(hookResult.currentIndex).toBe(0);
+      expect(Element.prototype.animate).not.toHaveBeenCalled();
+    });
+
+    it('blocks swipe when 
 has overflow even if no scroll room in drag direction', () => {
+      render(createElement(TestHarness), { wrapper: Wrapper });
+
+      const container = getContainer();
+      const panel = getPanel(0);
+      Object.defineProperty(container, 'clientWidth', { value: 375, configurable: true });
+
+      const pre = document.createElement('pre');
+      panel.appendChild(pre);
+      // Scrolled all the way to the right — no room left to scroll left
+      Object.defineProperty(pre, 'scrollLeft', { value: 500, configurable: true });
+      Object.defineProperty(pre, 'scrollWidth', { value: 800, configurable: true });
+      Object.defineProperty(pre, 'clientWidth', { value: 300, configurable: true });
+
+      dispatchTouch(pre, 'touchstart', CENTER_X, CENTER_Y);
+      dispatchTouch(pre, 'touchmove', CENTER_X - 30, CENTER_Y);
+      dispatchTouch(pre, 'touchend', CENTER_X - 30, CENTER_Y);
+
+      // Panel should NOT transition — browser handles overscroll bounce
+      expect(Element.prototype.animate).not.toHaveBeenCalled();
+    });
+
+    it('allows swipe when 
 has no horizontal overflow', () => {
+      render(createElement(TestHarness), { wrapper: Wrapper });
+
+      const container = getContainer();
+      const panel = getPanel(0);
+      Object.defineProperty(container, 'clientWidth', { value: 375, configurable: true });
+
+      const pre = document.createElement('pre');
+      panel.appendChild(pre);
+      // No overflow — content fits within the element
+      Object.defineProperty(pre, 'scrollLeft', { value: 0, configurable: true });
+      Object.defineProperty(pre, 'scrollWidth', { value: 300, configurable: true });
+      Object.defineProperty(pre, 'clientWidth', { value: 300, configurable: true });
+
+      dispatchTouch(pre, 'touchstart', CENTER_X, CENTER_Y);
+      dispatchTouch(pre, 'touchmove', CENTER_X - 30, CENTER_Y);
+      dispatchTouch(pre, 'touchend', CENTER_X - 30, CENTER_Y);
+
+      // Panel SHOULD transition since 
 has no overflow
+      expect(Element.prototype.animate).toHaveBeenCalled();
+    });
+
+    it('bails unconditionally for elements with data-swipe-ignore', () => {
+      render(createElement(TestHarness), { wrapper: Wrapper });
+
+      const panel = getPanel(0);
+
+      const wrapper = document.createElement('div');
+      wrapper.setAttribute('data-swipe-ignore', '');
+      const child = document.createElement('span');
+      wrapper.appendChild(child);
+      panel.appendChild(wrapper);
+
+      dispatchTouch(child, 'touchstart', CENTER_X, CENTER_Y);
+      dispatchTouch(child, 'touchmove', CENTER_X - 30, CENTER_Y);
+      dispatchTouch(child, 'touchend', CENTER_X - 30, CENTER_Y);
+
+      expect(hookResult.currentIndex).toBe(0);
+      expect(Element.prototype.animate).not.toHaveBeenCalled();
+    });
+  });
 });
diff --git a/src/hooks/useSwipeScroll.ts b/src/hooks/useSwipeScroll.ts
index b6b4853..4d96d7c 100644
--- a/src/hooks/useSwipeScroll.ts
+++ b/src/hooks/useSwipeScroll.ts
@@ -370,6 +370,26 @@ export function useSwipeScroll({
         if (Math.abs(deltaX) > 10 || Math.abs(deltaY) > 10) {
           directionLocked = true;
           if (Math.abs(deltaX) > Math.abs(deltaY)) {
+            // Check if touch originated in an element that should handle its own horizontal scroll
+            const el = touch.target instanceof Element
+              ? touch.target
+              : (touch.target as Node)?.parentElement;
+
+            // Unconditional bail: developer opt-out via data-swipe-ignore
+            if (el?.closest('[data-swipe-ignore]')) {
+              touchActive = false;
+              isDraggingRef.current = false;
+              return;
+            }
+
+            // Conditional bail: scrollable 
 with horizontal overflow
+            const scrollable = el?.closest('pre') as HTMLElement | null;
+            if (scrollable && scrollable.scrollWidth > scrollable.clientWidth + 1) {
+              touchActive = false;
+              isDraggingRef.current = false;
+              return;
+            }
+
             isSwiping = true;
             // Hide scroll indicator immediately to prevent visible jump during swipe
             document.body.classList.remove('is-scrolling');
diff --git a/src/index.css b/src/index.css
index a5edc06..05ab451 100644
--- a/src/index.css
+++ b/src/index.css
@@ -165,6 +165,7 @@ button {
   padding: 12px 14px;
   border-radius: 6px;
   overflow-x: auto;
+  overscroll-behavior-x: contain;
   margin: 0.75em 0;
   border: 1px solid var(--border);
   white-space: pre;
diff --git a/src/utils/sanitize.test.ts b/src/utils/sanitize.test.ts
index dc4384e..3b7b9ab 100644
--- a/src/utils/sanitize.test.ts
+++ b/src/utils/sanitize.test.ts
@@ -25,7 +25,7 @@ describe('sanitizeHtml', () => {
       expect(sanitizeHtml('bold')).toContain('');
       expect(sanitizeHtml('italic')).toContain('');
       expect(sanitizeHtml('code')).toContain('');
-      expect(sanitizeHtml('
pre
')).toContain('
');
+      expect(sanitizeHtml('
pre
')).toContain('
');
     });
   });
 
@@ -33,25 +33,25 @@ describe('sanitizeHtml', () => {
     it('strips uniform leading indent from a 
 block', () => {
       const html = '
    line1\n    line2\n    line3
'; const result = sanitizeHtml(html); - expect(result).toContain('
line1\nline2\nline3
'); + expect(result).toContain('
line1\nline2\nline3
'); }); it('preserves relative indent (continuation lines stay indented under their parent)', () => { const html = '
    if (x)\n        foo();\n    bar();
'; const result = sanitizeHtml(html); - expect(result).toContain('
if (x)\n    foo();\nbar();
'); + expect(result).toContain('
if (x)\n    foo();\nbar();
'); }); it('ignores blank lines when computing the common indent', () => { const html = '
    line1\n\n    line2
'; const result = sanitizeHtml(html); - expect(result).toContain('
line1\n\nline2
'); + expect(result).toContain('
line1\n\nline2
'); }); it('leaves a block with no leading indent unchanged', () => { const html = '
line1\nline2
'; const result = sanitizeHtml(html); - expect(result).toContain('
line1\nline2
'); + expect(result).toContain('
line1\nline2
'); }); it('preserves the inner wrapper so `.comment-content pre code` styles still apply', () => { @@ -64,7 +64,7 @@ describe('sanitizeHtml', () => { it('handles bare
 (no  child) by dedenting the 
 directly', () => {
       const html = '
    line1\n    line2
'; const result = sanitizeHtml(html); - expect(result).toContain('
line1\nline2
'); + expect(result).toContain('
line1\nline2
'); }); it('preserves an auto-linkified URL inside a
 at the cost of skipping dedent', () => {
@@ -92,7 +92,7 @@ describe('sanitizeHtml', () => {
         '    {
'; const result = sanitizeHtml(html); expect(result).toContain( - '
// Step 9. Null move search\n' +
+        '
// Step 9. Null move search\n' +
           'if (cutNode\n' +
           '    && pos.non_pawn_material(us))\n' +
           '{
', diff --git a/src/utils/sanitize.ts b/src/utils/sanitize.ts index 42a2e5d..7aec1de 100644 --- a/src/utils/sanitize.ts +++ b/src/utils/sanitize.ts @@ -240,6 +240,8 @@ function isAutoLinkifiedText(text: string, parsed: URL): boolean { purify.addHook('afterSanitizeAttributes', (node) => { if (node.tagName === 'PRE') { + // Make scrollable pre blocks keyboard-accessible (WCAG 2.1.1) + node.setAttribute('tabindex', '0'); // Target the inner when present so the wrapper // survives (keeps `.comment-content pre code`'s background-reset // / font-size override applying). Falls back to the
 itself