Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 94 additions & 0 deletions e2e/comment-swipe.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -367,4 +367,98 @@ test.describe('Mobile Comment Swipe Viewer', () => {

await waitForSwipeReady(page, 4);
});

test('horizontal swipe inside <pre> code block scrolls code, not panel', async ({ page }) => {
// Navigate to comment 1001 which contains a <pre> block with wide content
await page.goto('/#/item/1001');

await expectActiveSwipePanelText(page, 'patio11', { timeout: 10000 });
await waitForSwipeReady(page, 4);

// Find the <pre> 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 <pre>
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/);
});
});
2 changes: 1 addition & 1 deletion e2e/fixtures/api-mocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -310,7 +310,7 @@ export async function setupApiMocks(page: Page) {
{
objectID: '1001',
author: 'patio11',
comment_text: 'The <a href="https://github.com/aspect-build/bazel-lib">wasm-bindgen</a> approach is really interesting. It essentially lets you write Rust that compiles to WebAssembly and then generates <code>JS bindings</code> automatically.',
comment_text: 'The <a href="https://github.com/aspect-build/bazel-lib">wasm-bindgen</a> approach is really interesting. It essentially lets you write Rust that compiles to WebAssembly and then generates <code>JS bindings</code> automatically.<pre>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";</pre>',
created_at_i: Math.floor(Date.now() / 1000) - 1800,
parent_id: 12345,
story_id: 12345,
Expand Down
4 changes: 2 additions & 2 deletions e2e/fixtures/mock-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 <code>wasm-bindgen</code> was particularly insightful.',
text: 'This is a really well-written piece. The section on <code>wasm-bindgen</code> was particularly insightful.<pre>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";</pre>',
time: now() - 1800,
parent: 12345,
kids: [2001],
Expand Down Expand Up @@ -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 <code>JS bindings</code> automatically.',
text: 'This is a really well-written piece. The section on <code>wasm-bindgen</code> was particularly insightful.<pre>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";</pre>',
created_at_i: now() - 1800,
parent_id: 12345,
story_id: 12345,
Expand Down
3 changes: 2 additions & 1 deletion e2e/mobile-swipe.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down
88 changes: 88 additions & 0 deletions src/hooks/useSwipeScroll.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -602,4 +602,92 @@ describe('useSwipeScroll', () => {
expect(vi.getTimerCount()).toBe(0);
});
});

describe('scrollable element bail', () => {
it('yields horizontal gesture to a scrollable <pre> with scroll room', () => {
render(createElement(TestHarness), { wrapper: Wrapper });

const panel = getPanel(0);

// Create a <pre> 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 <pre> (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 <pre> 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 <pre> 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 <pre> 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();
});
});
});
20 changes: 20 additions & 0 deletions src/hooks/useSwipeScroll.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 <pre> 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');
Expand Down
1 change: 1 addition & 0 deletions src/index.css
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
14 changes: 7 additions & 7 deletions src/utils/sanitize.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,33 +25,33 @@ describe('sanitizeHtml', () => {
expect(sanitizeHtml('<strong>bold</strong>')).toContain('<strong>');
expect(sanitizeHtml('<em>italic</em>')).toContain('<em>');
expect(sanitizeHtml('<code>code</code>')).toContain('<code>');
expect(sanitizeHtml('<pre>pre</pre>')).toContain('<pre>');
expect(sanitizeHtml('<pre>pre</pre>')).toContain('<pre tabindex="0">');
});
});

describe('<pre> dedent', () => {
it('strips uniform leading indent from a <pre><code> block', () => {
const html = '<pre><code> line1\n line2\n line3</code></pre>';
const result = sanitizeHtml(html);
expect(result).toContain('<pre><code>line1\nline2\nline3</code></pre>');
expect(result).toContain('<pre tabindex="0"><code>line1\nline2\nline3</code></pre>');
});

it('preserves relative indent (continuation lines stay indented under their parent)', () => {
const html = '<pre><code> if (x)\n foo();\n bar();</code></pre>';
const result = sanitizeHtml(html);
expect(result).toContain('<pre><code>if (x)\n foo();\nbar();</code></pre>');
expect(result).toContain('<pre tabindex="0"><code>if (x)\n foo();\nbar();</code></pre>');
});

it('ignores blank lines when computing the common indent', () => {
const html = '<pre><code> line1\n\n line2</code></pre>';
const result = sanitizeHtml(html);
expect(result).toContain('<pre><code>line1\n\nline2</code></pre>');
expect(result).toContain('<pre tabindex="0"><code>line1\n\nline2</code></pre>');
});

it('leaves a block with no leading indent unchanged', () => {
const html = '<pre><code>line1\nline2</code></pre>';
const result = sanitizeHtml(html);
expect(result).toContain('<pre><code>line1\nline2</code></pre>');
expect(result).toContain('<pre tabindex="0"><code>line1\nline2</code></pre>');
});

it('preserves the inner <code> wrapper so `.comment-content pre code` styles still apply', () => {
Expand All @@ -64,7 +64,7 @@ describe('sanitizeHtml', () => {
it('handles bare <pre> (no <code> child) by dedenting the <pre> directly', () => {
const html = '<pre> line1\n line2</pre>';
const result = sanitizeHtml(html);
expect(result).toContain('<pre>line1\nline2</pre>');
expect(result).toContain('<pre tabindex="0">line1\nline2</pre>');
});

it('preserves an auto-linkified URL inside a <pre> at the cost of skipping dedent', () => {
Expand Down Expand Up @@ -92,7 +92,7 @@ describe('sanitizeHtml', () => {
' {</code></pre>';
const result = sanitizeHtml(html);
expect(result).toContain(
'<pre><code>// Step 9. Null move search\n' +
'<pre tabindex="0"><code>// Step 9. Null move search\n' +
'if (cutNode\n' +
' &amp;&amp; pos.non_pawn_material(us))\n' +
'{</code></pre>',
Expand Down
2 changes: 2 additions & 0 deletions src/utils/sanitize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 <code> when present so the <code> wrapper
// survives (keeps `.comment-content pre code`'s background-reset
// / font-size override applying). Falls back to the <pre> itself
Expand Down