From 4d30236dce64b3040bb2ec3d27e811fd399a431d Mon Sep 17 00:00:00 2001 From: therealsama <263038098+therealsama@users.noreply.github.com> Date: Sat, 29 Aug 2026 15:12:47 +0200 Subject: [PATCH] feat: sharpen touch feel across the mobile swipe feed MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Five defects that each broke the illusion of a native feed on a phone. The first four are gesture and feedback gaps on a touch pointer; the fifth is a layout token that was wrong at every breakpoint, desktop included. - Contain vertical overscroll. Swipe mode scrolls the document itself, so the document scroller is the feed, and mobile browsers chained an overscroll at its top edge into pull-to-refresh — reloading the SPA and dropping the reader back at the first story. `contain` blocks the chain while keeping the local rubber-band that `none` would also remove. It sits on bare `html` rather than on swipe mode: testing on a phone found the profile route, which strips that class deliberately, reloading just as expensively. The cost is worth naming: an installed PWA has no address bar, so this gesture was the reader's only reload affordance and nothing replaces it. - Pair every hover affordance with a press state. Tailwind scopes `hover:` behind a `(hover: hover)` media query and its preflight zeroes the tap highlight, so a tap on a coarse pointer got no feedback at all. Reaching iOS took one more step: Safari applies `:active` only where a touch handler sits on the element or the document, and this app's only touchstart is on the swipe container — so the header, which mounts above the router, and every non-swipe route had no press feedback and no highlight left to fall back on. A passive no-op on the document is the whole fix. Dropdown items reach the same dead end from the other side: Radix guards its highlight behind `pointerType === 'mouse'`, so neither `hover:` nor `focus:` survives a touch press on the one menu that exists only where the nav is too narrow to hold its tabs. - Settle a committed swipe on a decelerating curve instead of `linear`, which arrived at full speed and stopped dead. Duration is budgeted against the curve's initial speed, so its first frame matches the finger rather than overshooting it, and the speed it inherits is measured over the last 80ms of the drag instead of averaged across the whole gesture. That average lost to the velocity floor on nearly every swipe, which left two gestures covering the same distance settling identically however they ended. A finger held still before lifting now reports a standstill rather than replaying its last burst of movement. - Guard the long-press selection UI, whose handles swallowed the drag: suppressed on chrome and collapsed at gesture lock, while story and comment prose stay selectable. Headlines are not, which testing on a phone settled: an Ask or Show post carries no URL, so its title renders as bare text and a long press raised the handles rather than a link callout. Content links do keep their callout, since those are arbitrary third-party URLs mid-thread and nothing else reaches them. - Derive `--header-height` from the header. Fixed swipe panels and the scroll indicator reserve space with this token, so when it under-reports the header paints over the top of every story — and the literal `53px` only ever described the header at a 16px default font size on a phone. At a 150% setting the header renders 79px. It is now `calc(3.25rem + 1px)`: the 2.25rem control row, the vertical padding, and the bottom border. The md/lg values come from Tailwind's variant directive rather than a hand-written px query, because the utilities they mirror compile to rem breakpoints that move with the reader's font size. Desktop had also been over-reserving by 8px, since only the base padding was ever encoded. Two sibling cleanups ride along. `.page-state-center-padded` is hand-written CSS standing in for a `max-w-6xl` utility container, and its gutters carried the same px-versus-rem mismatch. The theme toggle drops a `dark:hover:bg-muted` that was beating the ghost variant's `dark:hover:bg-muted/50` outright, since `cn()` is tailwind-merge and the button's own class lands last — leaving its dark hover opaque against a dark press at half that. Deleting it settles both on the variant's value. The body rule reserving room for the offline bar keeps its px query on purpose and now says why: it gates on which layout React mounted, which `useIsMobile` decides with `(max-width: 767px)`. Two new e2e specs hold all of it in place. `layout-tokens` measures both chrome tokens against the elements they describe, across four breakpoints at two font sizes and under emulated browser font settings. `touch-feel` pins the overscroll containment, including on the route that drops swipe mode, the selection collapse, and the iOS touch listener — each invisible in CI and only reproducible on hardware. The release-velocity estimator is unit tested directly, alongside a pair of gestures with identical displacement and different endings that fails against the old averaging. One existing spec stops asserting a literal 53px and 32px for padding these tokens already describe, and measures the chrome instead. Press states are the one surface no rendered test reaches, since a synthesised press leaves `:active` unset in every engine CI can drive, so a source-level check pairs each hover affordance with its `active:` twin. Every assertion was verified to fail against the mistake it exists to catch, not just to pass. --- e2e/fixtures/layout-helpers.ts | 42 ++++++ e2e/layout-tokens.spec.ts | 165 ++++++++++++++++++++++ e2e/network-status-bar.spec.ts | 18 ++- e2e/touch-feel.spec.ts | 208 ++++++++++++++++++++++++++++ src/components/AuthorByline.tsx | 2 +- src/components/Comment.tsx | 6 +- src/components/Header.tsx | 10 +- src/components/ItemArticle.tsx | 2 +- src/components/StoryCard.tsx | 6 +- src/components/ThemeToggle.tsx | 2 +- src/components/ui/button.tsx | 4 +- src/components/ui/dropdown-menu.tsx | 4 +- src/hooks/useItemWithComments.ts | 3 +- src/hooks/useSwipeScroll.test.ts | 42 ++++++ src/hooks/useSwipeScroll.ts | 53 +++++-- src/index.css | 70 +++++++++- src/lib/classes.ts | 5 +- src/lib/pressStates.test.ts | 74 ++++++++++ src/main.tsx | 3 + src/utils/releaseVelocity.test.ts | 59 ++++++++ src/utils/releaseVelocity.ts | 41 ++++++ src/utils/touchActiveStates.test.ts | 31 +++++ src/utils/touchActiveStates.ts | 11 ++ 23 files changed, 821 insertions(+), 40 deletions(-) create mode 100644 e2e/layout-tokens.spec.ts create mode 100644 e2e/touch-feel.spec.ts create mode 100644 src/lib/pressStates.test.ts create mode 100644 src/utils/releaseVelocity.test.ts create mode 100644 src/utils/releaseVelocity.ts create mode 100644 src/utils/touchActiveStates.test.ts create mode 100644 src/utils/touchActiveStates.ts diff --git a/e2e/fixtures/layout-helpers.ts b/e2e/fixtures/layout-helpers.ts index f6da9ab..e91d87e 100644 --- a/e2e/fixtures/layout-helpers.ts +++ b/e2e/fixtures/layout-helpers.ts @@ -34,6 +34,48 @@ export async function setOfflineAndWaitForBar(page: Page, context: BrowserContex }, { timeout: 5000 }); } +/** + * Assert that a chrome height token describes the element it claims to measure. + * + * `getComputedStyle` returns the literal `calc(…)` text for a custom property, + * so a probe element hands the expression back to the engine to be measured. + */ +export async function expectChromeTokenToMatch( + page: Page, + token: string, + selector: string, + { tolerance = 0.5 }: { tolerance?: number } = {}, +) { + // Poll: every engine can report a header mid-reflow for a frame or two after + // the root font size changes. A token that genuinely disagrees never converges. + await expect + .poll( + async () => { + const { declared, rendered } = await page.evaluate( + ({ token, selector }) => { + const probe = document.createElement('div'); + probe.style.cssText = + `position:absolute;top:0;left:0;width:1px;visibility:hidden;height:var(${token})`; + document.body.appendChild(probe); + const declared = probe.getBoundingClientRect().height; + probe.remove(); + + const el = document.querySelector(selector); + return { declared, rendered: el?.getBoundingClientRect().height ?? -1 }; + }, + { token, selector }, + ); + + if (rendered <= 0) return `${selector} is not rendered`; + return Math.abs(declared - rendered) <= tolerance + ? 'match' + : `${token} resolves to ${declared}px but ${selector} renders ${rendered}px`; + }, + { message: `${token} should describe ${selector}` }, + ) + .toBe('match'); +} + /** * Assert that a block is centered in the usable viewport between the fixed * header and the optional fixed bottom bar. diff --git a/e2e/layout-tokens.spec.ts b/e2e/layout-tokens.spec.ts new file mode 100644 index 0000000..a38b6e3 --- /dev/null +++ b/e2e/layout-tokens.spec.ts @@ -0,0 +1,165 @@ +import { test, expect, type Page } from '@playwright/test'; +import { setupApiMocks, stubNotFoundUser } from './fixtures/api-mocks'; +import { expectChromeTokenToMatch, setOfflineAndWaitForBar } from './fixtures/layout-helpers'; + +// `--header-height` and `--network-bar-height` duplicate, by hand, heights that +// Tailwind utilities produce on the components. Nothing in the build connects +// the two, and disagreement is silent: panels reserve space with the token, so +// one that under-reports leaves the header painting over every story. +// +// Both sizes matter at every breakpoint because the header's 2.25rem control row +// scales with the root font size, so a px token is only ever right at 16px. + +/** 150% browser font setting: realistic, and unambiguously off the default. */ +const ENLARGED_ROOT_PX = 24; + +const BREAKPOINTS = [ + { label: 'base', width: 375, height: 667 }, + { label: 'md', width: 800, height: 800 }, + { label: 'lg', width: 1100, height: 800 }, + { label: 'xl', width: 1400, height: 900 }, +]; + +/** + * Approximate a raised default font size by moving the root font size that every + * `rem` resolves against. Only an approximation: `rem` in a media query resolves + * against the browser's *initial* size, which no stylesheet can reach, so the + * breakpoints stay put. The Chromium CDP test below covers that half. + */ +async function enlargeRootFont(page: Page, px: number) { + await page.addInitScript((size) => { + const apply = () => { + const style = document.createElement('style'); + style.textContent = `html{font-size:${size}px}`; + document.head.appendChild(style); + }; + if (document.head) apply(); + else document.addEventListener('DOMContentLoaded', apply); + }, px); +} + +/** + * The theme toggle IS the control row that sets the header's height, so its paint + * is the readiness signal. Fonts too: a face swap re-measures the whole bar. + */ +async function awaitHeaderPainted(page: Page) { + await expect(page.getByTestId('theme-toggle')).toBeVisible(); + await page.evaluate(() => document.fonts.ready); +} + +for (const breakpoint of BREAKPOINTS) { + test.describe(`--header-height at the ${breakpoint.label} breakpoint`, () => { + test.use({ viewport: { width: breakpoint.width, height: breakpoint.height } }); + + test.beforeEach(async ({ page }) => { + await setupApiMocks(page); + }); + + test('matches the rendered header', async ({ page }) => { + await page.goto('/#/'); + await awaitHeaderPainted(page); + + await expectChromeTokenToMatch(page, '--header-height', '.app-header'); + }); + + test('still matches when the reader enlarges their default font size', async ({ page }) => { + await enlargeRootFont(page, ENLARGED_ROOT_PX); + await page.goto('/#/'); + await awaitHeaderPainted(page); + + // Guard the emulation: if the injected stylesheet stopped applying, the + // assertion below would quietly re-test the default size. + const rootFontSize = await page.evaluate( + () => getComputedStyle(document.documentElement).fontSize, + ); + expect(rootFontSize).toBe(`${ENLARGED_ROOT_PX}px`); + + await expectChromeTokenToMatch(page, '--header-height', '.app-header'); + }); + }); +} + +test.describe('breakpoint-driven layout under a real browser font setting', () => { + // 900px sits where a `768px` query and Tailwind's `md:` disagree at a 24px + // default font: 48rem becomes 1152px, so only a px query would have switched. + test.use({ viewport: { width: 900, height: 800 } }); + + const skipUnlessChromium = (browserName: string) => + test.skip( + browserName !== 'chromium', + 'Only Chromium can emulate the browser default font size rather than the root font size', + ); + + const emulateDefaultFontSize = async (page: Page) => { + const cdp = await page.context().newCDPSession(page); + await cdp.send('Page.setFontSizes', { + fontSizes: { standard: ENLARGED_ROOT_PX, fixed: ENLARGED_ROOT_PX }, + }); + }; + + test('--header-height changes on the same breakpoint as the padding it mirrors', async ({ page, browserName }) => { + skipUnlessChromium(browserName); + + await setupApiMocks(page); + await emulateDefaultFontSize(page); + + await page.goto('/#/'); + await awaitHeaderPainted(page); + + // Without this window there is nothing for the assertion below to catch. + const inDisagreementWindow = await page.evaluate( + () => + !window.matchMedia('(width >= 48rem)').matches && + window.matchMedia('(width >= 768px)').matches, + ); + expect( + inDisagreementWindow, + 'this viewport no longer sits between the rem and px md breakpoints', + ).toBe(true); + + await expectChromeTokenToMatch(page, '--header-height', '.app-header'); + }); + + test('a full-page state keeps the gutters of the container it replaces', async ({ page, browserName }) => { + skipUnlessChromium(browserName); + + await setupApiMocks(page); + await stubNotFoundUser(page, 'nope'); + await emulateDefaultFontSize(page); + + await page.goto('/#/user/nope'); + await expect(page.getByText('User not found')).toBeVisible(); + + // The class stands in for the header's `px-4 md:px-8 lg:px-16 xl:px-24` + // container, so misalignment is the visible symptom of drifted breakpoints. + const gutters = await page.evaluate(() => { + const paddingLeftOf = (selector: string) => { + const el = document.querySelector(selector); + return el ? getComputedStyle(el).paddingLeft : null; + }; + return { + state: paddingLeftOf('.page-state-center-padded'), + container: paddingLeftOf('.app-header > div'), + }; + }); + + expect(gutters.state, 'the padded state should be on screen').not.toBeNull(); + expect(gutters.state).toBe(gutters.container); + }); +}); + +test.describe('--network-bar-height', () => { + test.use({ viewport: { width: 375, height: 667 } }); + + test('matches the rendered offline bar', async ({ page, context }) => { + await setupApiMocks(page); + await page.goto('/#/'); + await awaitHeaderPainted(page); + + await setOfflineAndWaitForBar(page, context); + + // NetworkStatusBar writes this token from JS while the bar's own height + // comes from CSS — two literals with nothing but this test between them. + await expectChromeTokenToMatch(page, '--network-bar-height', '.network-status-bar'); + }); +}); diff --git a/e2e/network-status-bar.spec.ts b/e2e/network-status-bar.spec.ts index 1eb8c26..3e54568 100644 --- a/e2e/network-status-bar.spec.ts +++ b/e2e/network-status-bar.spec.ts @@ -193,21 +193,29 @@ test.describe('Network Status Bar - Mobile content spacing', () => { const afterMetrics = await page.evaluate(() => { const heading = document.querySelector('h1'); const header = document.querySelector('header'); + const bar = document.querySelector('.network-status-bar'); const panel = document.querySelector('[data-testid="swipe-panel"].active') ?? document.querySelector('[data-testid="swipe-panel"]'); - if (!(heading instanceof HTMLElement) || !(header instanceof HTMLElement) || !(panel instanceof HTMLElement)) { + if (!(heading instanceof HTMLElement) || !(header instanceof HTMLElement) + || !(bar instanceof HTMLElement) || !(panel instanceof HTMLElement)) { return null; } + const panelStyle = getComputedStyle(panel); return { gap: heading.getBoundingClientRect().top - header.getBoundingClientRect().bottom, - paddingTop: getComputedStyle(panel).paddingTop, - paddingBottom: getComputedStyle(panel).paddingBottom, + paddingTop: parseFloat(panelStyle.paddingTop), + paddingBottom: parseFloat(panelStyle.paddingBottom), + headerHeight: header.getBoundingClientRect().height, + barHeight: bar.getBoundingClientRect().height, }; }); expect(afterMetrics).not.toBeNull(); - expect(afterMetrics?.paddingTop).toBe('53px'); - expect(afterMetrics?.paddingBottom).toBe('32px'); + // Measured, not named in pixels: both paddings come from tokens that move + // with the header's padding and the reader's font size, so a literal here + // holds at one breakpoint only — and blames the bar for a header change. + expect(afterMetrics!.paddingTop).toBeCloseTo(afterMetrics!.headerHeight, 0); + expect(afterMetrics!.paddingBottom).toBeCloseTo(afterMetrics!.barHeight, 0); expect(Math.abs((afterMetrics?.gap ?? 0) - (beforeGap ?? 0))).toBeLessThanOrEqual(2); }); }); diff --git a/e2e/touch-feel.spec.ts b/e2e/touch-feel.spec.ts new file mode 100644 index 0000000..716e54c --- /dev/null +++ b/e2e/touch-feel.spec.ts @@ -0,0 +1,208 @@ +import { test, expect } from '@playwright/test'; +import { setupApiMocks } from './fixtures/api-mocks'; +import { waitForSwipeReady } from './fixtures/swipe-helpers'; + +// Gesture defences whose real symptoms only appear on a phone — a pull-to-refresh +// that reloads the feed, selection handles eating a drag — and which nothing else +// in the suite would notice disappearing. + +const MOBILE = { width: 390, height: 780 }; + +test.describe('Overscroll containment', () => { + test.use({ viewport: MOBILE }); + + test.beforeEach(async ({ page }) => { + await setupApiMocks(page); + }); + + test('the swipe feed does not chain its overscroll into pull-to-refresh', async ({ page }) => { + await page.goto('/#/'); + await waitForSwipeReady(page); + + // Swipe mode scrolls the document, so this is the scroller whose overscroll + // the browser turns into a reload back to the first story. + const overscrollY = await page.evaluate( + () => getComputedStyle(document.documentElement).overscrollBehaviorY, + ); + + expect(overscrollY).toBe('contain'); + }); + + test('survives the routes that drop swipe mode', async ({ page }) => { + await page.goto('/#/'); + await waitForSwipeReady(page); + + // `/user/:id` is an ordinary scrollable document, so it strips `swipe-mode`. + // Reloading it is no cheaper than reloading the feed, so containment cannot + // be scoped to that class — asserting the class is gone proves it isn't. + await page.goto('/#/user/pg'); + + await expect + .poll(() => + page.evaluate(() => ({ + swipeMode: document.documentElement.classList.contains('swipe-mode'), + overscrollY: getComputedStyle(document.documentElement).overscrollBehaviorY, + })), + ) + .toEqual({ swipeMode: false, overscrollY: 'contain' }); + }); +}); + +test.describe('The gate iOS puts in front of :active', () => { + test.use({ viewport: MOBILE }); + + test('a passive touchstart listener is registered on the document', async ({ + page, + browserName, + }) => { + test.skip( + browserName !== 'chromium', + 'Only Chromium can enumerate a target\'s event listeners', + ); + + await setupApiMocks(page); + await page.goto('/#/'); + await waitForSwipeReady(page); + + // iOS applies `:active` only where a touch handler exists, so this listener + // is what makes press states outside the swipe container work there. No + // engine CI can drive shows the effect, so nothing else would catch its loss. + const cdp = await page.context().newCDPSession(page); + const { result } = await cdp.send('Runtime.evaluate', { expression: 'document' }); + const { listeners } = await cdp.send('DOMDebugger.getEventListeners', { + objectId: result.objectId!, + }); + + const touchStarts = listeners.filter((listener) => listener.type === 'touchstart'); + expect(touchStarts.length, 'no touchstart listener on the document').toBeGreaterThan(0); + // Non-passive would cost the document its scroll fast path for nothing. + expect(touchStarts.some((listener) => listener.passive)).toBe(true); + }); +}); + +test.describe('Selection during a horizontal drag', () => { + test.use({ viewport: MOBILE }); + + test('a finger cannot start one on a text post headline, though its body still can', async ({ + page, + hasTouch, + }) => { + test.skip(!hasTouch, 'the lock is gated on a coarse pointer'); + await setupApiMocks(page); + // The Ask fixture carries `url: null`, so its title renders as bare text + // instead of a link — the case where a long press raised the handles rather + // than the link callout, handing the drag to the browser. + await page.goto('/#/item/88888'); + await waitForSwipeReady(page); + + const panel = page.locator('.swipe-snap-panel.active'); + const prose = panel.locator('.comment-content').first(); + const headline = panel.locator('h1').first(); + + // Prove a double-click selects at all here before concluding anything from + // the headline. Asserting the computed property instead would not travel: + // Gecko reports the initial `auto` where Blink resolves it against the panel. + await expect + .poll(async () => { + await prose.dblclick(); + return page.evaluate(() => window.getSelection()?.toString().length ?? 0); + }, { message: 'prose must stay selectable' }) + .toBeGreaterThan(0); + + await page.evaluate(() => window.getSelection()?.removeAllRanges()); + await headline.dblclick(); + const fromHeadline = await page.evaluate(() => window.getSelection()?.toString() ?? ''); + + expect(fromHeadline, 'the headline must not be selectable').toBe(''); + }); + + // The mirror of the test above: same headline, same double-click, opposite + // expectation. The lock exists to keep a long press off a swipe, and a mouse + // has no swipe to take, so it must not pay for one. + test('a mouse keeps that headline selectable', async ({ page, hasTouch }) => { + test.skip(hasTouch, 'a device with a finger has a gesture to protect'); + await setupApiMocks(page); + await page.goto('/#/item/88888'); + await waitForSwipeReady(page); + + const headline = page.locator('.swipe-snap-panel.active h1').first(); + + await expect + .poll(async () => { + await headline.dblclick(); + return page.evaluate(() => window.getSelection()?.toString().length ?? 0); + }, { message: 'the headline must stay selectable for a mouse' }) + .toBeGreaterThan(0); + }); + + test('a live selection is collapsed when the gesture locks horizontal', async ({ page }) => { + await setupApiMocks(page); + await page.goto('/#/'); + await waitForSwipeReady(page); + + // Prose is the surface that stays selectable, so it is where a long press + // can leave handles up before a swipe starts. This story is a link post + // with no body of its own, so its only prose is comments — which arrive + // after the panel a swipe-ready page waits for. + await expect(page.locator('.swipe-snap-panel.active .comment-content').first()) + .not.toBeEmpty(); + + const startedSelected = await page.evaluate(() => { + const prose = document.querySelector('.swipe-snap-panel.active .comment-content'); + if (!prose) return false; + const range = document.createRange(); + range.selectNodeContents(prose); + const selection = window.getSelection(); + selection?.removeAllRanges(); + selection?.addRange(range); + return !!selection && !selection.isCollapsed; + }); + expect(startedSelected, 'the fixture must start from a live selection').toBe(true); + + // Assert between touchmove and touchend: a committed swap re-renders the + // panel, which would clear the selection for the wrong reason. + const collapsedAtLock = await page.evaluate(() => { + const container = document.querySelector('[data-testid="swipe-container"]')!; + const rect = container.getBoundingClientRect(); + const y = rect.top + rect.height / 2; + const startX = rect.left + rect.width / 2; + + const makeTouch = (clientX: number) => ({ + identifier: 1, + target: container, + clientX, + clientY: y, + pageX: clientX, + pageY: y, + screenX: clientX, + screenY: y, + radiusX: 1, + radiusY: 1, + rotationAngle: 0, + force: 1, + }); + + // `new TouchEvent()` throws in WebKit, so events are shaped by hand — the + // same approach swipe-helpers.ts uses. + const dispatchTouch = (type: string, touches: object[], changed?: object[]) => { + const event = new Event(type, { bubbles: true, cancelable: true }); + Object.defineProperty(event, 'touches', { value: touches }); + Object.defineProperty(event, 'changedTouches', { value: changed ?? touches }); + Object.defineProperty(event, 'targetTouches', { value: touches }); + container.dispatchEvent(event); + }; + + dispatchTouch('touchstart', [makeTouch(startX)]); + // 30px clears the 10px lock threshold with no vertical component. + dispatchTouch('touchmove', [makeTouch(startX - 30)]); + + const selection = window.getSelection(); + const collapsed = !selection || selection.isCollapsed; + + dispatchTouch('touchend', [], [makeTouch(startX - 30)]); + return collapsed; + }); + + expect(collapsedAtLock).toBe(true); + }); +}); diff --git a/src/components/AuthorByline.tsx b/src/components/AuthorByline.tsx index afe20a7..3d333e9 100644 --- a/src/components/AuthorByline.tsx +++ b/src/components/AuthorByline.tsx @@ -62,7 +62,7 @@ export function AuthorByline({ {author} diff --git a/src/components/Comment.tsx b/src/components/Comment.tsx index d0da61e..4522c28 100644 --- a/src/components/Comment.tsx +++ b/src/components/Comment.tsx @@ -61,7 +61,7 @@ export function Comment({ comment, storyAuthor = '', stageIdx }: CommentProps) { {comment.author} @@ -69,7 +69,7 @@ export function Comment({ comment, storyAuthor = '', stageIdx }: CommentProps) { ) : isKnownAuthor(comment.author) ? ( {comment.author} @@ -109,7 +109,7 @@ export function Comment({ comment, storyAuthor = '', stageIdx }: CommentProps) { {/* Replies expander — negative margin compensates padding for tree alignment. */} diff --git a/src/components/ui/button.tsx b/src/components/ui/button.tsx index a04b7c6..4b4ca5f 100644 --- a/src/components/ui/button.tsx +++ b/src/components/ui/button.tsx @@ -17,9 +17,9 @@ const buttonVariants = cva( { variants: { variant: { - default: "bg-primary text-primary-foreground hover:bg-accent-hover", + default: "bg-primary text-primary-foreground hover:bg-accent-hover active:bg-accent-hover", ghost: - "hover:bg-muted hover:text-foreground dark:hover:bg-muted/50", + "hover:bg-muted hover:text-foreground active:bg-muted active:text-foreground dark:hover:bg-muted/50 dark:active:bg-muted/50", }, size: { sm: "h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5", diff --git a/src/components/ui/dropdown-menu.tsx b/src/components/ui/dropdown-menu.tsx index 50c32e3..e24b30a 100644 --- a/src/components/ui/dropdown-menu.tsx +++ b/src/components/ui/dropdown-menu.tsx @@ -62,7 +62,9 @@ function DropdownMenuItem({ className={cn( // Mirrors nav-pill hover pattern from the header. "relative flex cursor-pointer select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm font-medium capitalize outline-none transition-colors", - "hover:bg-muted hover:text-foreground focus:bg-muted focus:text-foreground", + // `active:` because Radix guards its highlight with `pointerType === 'mouse'`, + // so a touch press reaches neither `hover:` nor `focus:`. + "hover:bg-muted hover:text-foreground focus:bg-muted focus:text-foreground active:bg-muted active:text-foreground", "data-[disabled]:pointer-events-none data-[disabled]:opacity-50", className )} diff --git a/src/hooks/useItemWithComments.ts b/src/hooks/useItemWithComments.ts index 603995f..3a4638c 100644 --- a/src/hooks/useItemWithComments.ts +++ b/src/hooks/useItemWithComments.ts @@ -287,7 +287,8 @@ export function useItemWithComments(itemId: number | string, { initialItem = nul // Combined loading state for backward compatibility const loading = itemLoading && commentsLoading; - // Pull-to-refresh handler. + // Refetch behind the error states' retry action. No gesture reaches this: the + // root contains its overscroll, so there is no pull-to-refresh. const refresh = useCallback(async () => { setError(null); setIsNotFound(false); diff --git a/src/hooks/useSwipeScroll.test.ts b/src/hooks/useSwipeScroll.test.ts index 6793c34..94d58a1 100644 --- a/src/hooks/useSwipeScroll.test.ts +++ b/src/hooks/useSwipeScroll.test.ts @@ -431,6 +431,48 @@ describe('useSwipeScroll', () => { expect(hookResult.currentIndex).toBe(1); }); + it('settles a flick faster than a uniform drag that covered the same distance', () => { + render(createElement(TestHarness), { wrapper: Wrapper }); + const container = getContainer(); + + const settleDuration = () => { + const options = vi.mocked(Element.prototype.animate).mock.calls[0]?.[1]; + return typeof options === 'object' ? (options.duration as number) : undefined; + }; + + // 150px spread evenly over 500ms: no flick to continue, so the floor + // decides the settle. + dispatchTouch(container, 'touchstart', CENTER_X, CENTER_Y); + for (let step = 1; step <= 5; step++) { + act(() => { vi.advanceTimersByTime(100); }); + dispatchTouch(container, 'touchmove', CENTER_X - step * 30, CENTER_Y); + } + dispatchTouch(container, 'touchend', CENTER_X - 150, CENTER_Y); + const uniformDrag = settleDuration(); + + act(() => { vi.runAllTimers(); }); + vi.mocked(Element.prototype.animate).mockClear(); + + // The same 150px, but 130 of it inside the last 80ms. + dispatchTouch(container, 'touchstart', CENTER_X, CENTER_Y); + act(() => { vi.advanceTimersByTime(200); }); + dispatchTouch(container, 'touchmove', CENTER_X - 20, CENTER_Y); + act(() => { vi.advanceTimersByTime(40); }); + dispatchTouch(container, 'touchmove', CENTER_X - 80, CENTER_Y); + act(() => { vi.advanceTimersByTime(40); }); + dispatchTouch(container, 'touchmove', CENTER_X - 150, CENTER_Y); + dispatchTouch(container, 'touchend', CENTER_X - 150, CENTER_Y); + const flick = settleDuration(); + + expect(uniformDrag).toBeGreaterThan(0); + expect(flick).toBeGreaterThan(0); + // Identical distance left to travel, so only the speed it was handed can + // shorten the flick's settle. Averaged over the gesture, both are equal. + expect(flick!).toBeLessThan(uniformDrag!); + + act(() => { vi.runAllTimers(); }); + }); + it('preserves per-panel scroll position across swipes (reduced motion)', async () => { reducedMotionValue = true; render(createElement(TestHarness), { wrapper: Wrapper }); diff --git a/src/hooks/useSwipeScroll.ts b/src/hooks/useSwipeScroll.ts index 9d6a49e..5f17848 100644 --- a/src/hooks/useSwipeScroll.ts +++ b/src/hooks/useSwipeScroll.ts @@ -1,9 +1,26 @@ import { useState, useRef, useEffect, useLayoutEffect, useCallback } from 'react'; import { useScrollContainer } from './useScrollContainer'; import { prefersReducedMotion } from '../utils/prefersReducedMotion'; +import { + MAX_DRAG_SAMPLES, + releaseVelocityFrom, + type DragSample, +} from '../utils/releaseVelocity'; const noop = () => undefined; +/** + * Settle curve for a committed swipe: starts at 1.5× its average speed + * (`y1 / x1`) and arrives with zero slope, so the panel decelerates into rest. + * `linear()` would say this better but isn't old enough to assume, and an + * easing the engine can't parse makes `Element.animate()` throw. + */ +const COMMIT_EASE_POINTS = [0.2, 0.3, 0.45, 1] as const; +const COMMIT_EASE = `cubic-bezier(${COMMIT_EASE_POINTS.join(', ')})`; + +/** Derived, not restated: retuning the curve must move the budget with it. */ +const COMMIT_EASE_INITIAL_SLOPE = COMMIT_EASE_POINTS[1] / COMMIT_EASE_POINTS[0]; + interface UseSwipeScrollOptions { itemCount: number; initialIndex?: number; @@ -322,6 +339,7 @@ export function useSwipeScroll({ let startTime = 0; let startScrollY = 0; let lastClampedDelta = 0; + const dragSamples: DragSample[] = []; let directionLocked = false; let isSwiping = false; let touchActive = false; @@ -442,6 +460,7 @@ export function useSwipeScroll({ startTime = Date.now(); startScrollY = window.scrollY; lastClampedDelta = 0; + dragSamples.length = 0; directionLocked = false; isSwiping = false; touchActive = true; @@ -485,6 +504,11 @@ export function useSwipeScroll({ } isSwiping = true; + // Prose stays selectable (index.css) and live selection handles + // swallow the drag. Passive listeners can't preventDefault, but can + // still collapse the selection. + const selection = window.getSelection(); + if (selection && !selection.isCollapsed) selection.removeAllRanges(); // Hide scroll indicator immediately to prevent visible jump during swipe document.body.classList.remove('is-scrolling'); // Re-sticky the header for the swap: `fixed` blinks during the panel @@ -515,6 +539,9 @@ export function useSwipeScroll({ ? Math.min(0, deltaX) : Math.max(0, deltaX); lastClampedDelta = clampedDelta; + // Sampled here, not in the rAF frame below, which coalesces moves. + dragSamples.push({ x: clampedDelta, t: Date.now() }); + if (dragSamples.length > MAX_DRAG_SAMPLES) dragSamples.shift(); pendingDragDelta = clampedDelta; if (dragFrameId === 0) { @@ -543,12 +570,16 @@ export function useSwipeScroll({ const oldIndex = currentIndexRef.current; const activePanel = container.children[oldIndex] as HTMLElement | undefined; - const elapsed = Date.now() - startTime; - const velocity = Math.abs(lastClampedDelta) / elapsed; // px/ms + const releaseTime = Date.now(); + const elapsed = releaseTime - startTime; + // Committing reads the whole gesture: hauling a panel most of the way + // across earns the swap however the finger let go. Only the settle speed + // below cares about the ending. + const averageVelocity = Math.abs(lastClampedDelta) / elapsed; // px/ms const panelWidth = cachedPanelWidth || container.clientWidth || window.innerWidth; const shouldCommit = hasTarget && - (Math.abs(lastClampedDelta) > panelWidth * 0.25 || velocity > 0.3); + (Math.abs(lastClampedDelta) > panelWidth * 0.25 || averageVelocity > 0.3); if (shouldCommit) { // --- Commit: fly off + scale up --- @@ -562,15 +593,19 @@ export function useSwipeScroll({ cleanSlate(); commitPanelSwap(targetPanel, activePanel, targetIndex); } else { - // Velocity-matched duration: animation continues at finger speed. - // Slight 1.2× boost gives a "pop" feel on release (iOS-like). - // Floor velocity ensures slow drags still snap crisply. + // Budgeted against the curve's *initial* speed rather than its + // average, so the first frame matches targetVelocity instead of + // overshooting the finger. The 1.2× boost is release "pop"; the floor + // keeps slow drags and parked fingers from crawling. + const releaseVelocity = releaseVelocityFrom(dragSamples, releaseTime) ?? averageVelocity; const remainingDistance = panelWidth - Math.abs(lastClampedDelta); - const targetVelocity = Math.max(velocity * 1.2, panelWidth / 250); - const duration = Math.round(Math.max(50, Math.min(250, remainingDistance / targetVelocity))); + const targetVelocity = Math.max(releaseVelocity * 1.2, panelWidth / 250); + const duration = Math.round( + Math.max(50, Math.min(300, (remainingDistance * COMMIT_EASE_INITIAL_SLOPE) / targetVelocity)), + ); const animOptions: KeyframeAnimationOptions = { duration, - easing: 'linear', + easing: COMMIT_EASE, }; const anims: Animation[] = []; diff --git a/src/index.css b/src/index.css index 0053314..f4a27ec 100644 --- a/src/index.css +++ b/src/index.css @@ -34,9 +34,11 @@ button { --viewed: oklch(0.55 0.01 60); /* dimmed for read stories */ --tok-color: oklch(0.623 0 0); /* gray (#878787) */ --pill-glow: 0 2px 8px oklch(0.673 0.195 44 / 0.3); - /* MUST match the real rendered header height — fixed swipe panels and the - scroll indicator position off this literal and don't self-correct if it drifts. */ - --header-height: 53px; + /* .app-header's rendered height: 2.25rem control row + Header.tsx padding + + 1px border. Fixed panels and the scroll indicator position off it, so a + value that under-reports paints the header over content. `rem` keeps that + true when the reader raises their font size; layout-tokens.spec.ts guards it. */ + --header-height: calc(3.25rem + 1px); --network-bar-height: 0px; /* shadcn/ui token aliases — added in :root ONLY, not duplicated in .dark. @@ -52,6 +54,16 @@ button { --popover-foreground: var(--card-foreground); } +/* Only the header's padding changes with width (py-2 / md:py-1.5 / lg:py-1). + @variant, not a px query, so this flips on the same rem threshold as those + utilities — which themselves move with the reader's default font size. */ +@variant md { + :root { --header-height: calc(3rem + 1px); } +} +@variant lg { + :root { --header-height: calc(2.75rem + 1px); } +} + /* Dark mode — soft dark, warm tones */ .dark { --background: oklch(0.20 0.012 60); /* soft dark with warm tint */ @@ -389,6 +401,35 @@ html.dark { color-scheme: dark; } touch-action: pan-y; } +/* Long-press selection handles take over the drag and kill the swipe under + them. useSwipeScroll's listeners are all passive, so `preventDefault()` is + unavailable and these properties are the only lever. Behind a coarse pointer + because the hook binds touch alone — a mouse has no swipe to protect, so it + keeps ordinary selection. `any-` so a touch laptop still counts. */ +@media (any-pointer: coarse) { + body.swipe-mode .app-header, + .swipe-snap-panel { + -webkit-user-select: none; + user-select: none; + -webkit-touch-callout: none; + } + + /* Opt the prose back in: `.comment-content` is the story body and every + comment body. The headline stays locked — a text post's title has no link + wrapping it, so a long press raises the handles, not the link callout. */ + .swipe-snap-panel .comment-content { + -webkit-user-select: text; + user-select: text; + } + + /* Content links keep the long-press callout: with no share button or + clipboard path, on iOS it's the only way to lift a URL out of the feed. */ + .swipe-snap-panel h1 a, + .swipe-snap-panel .comment-content a { + -webkit-touch-callout: default; + } +} + /* Carousel: adjacent panel positioned off-screen, slides in with active */ .swipe-snap-panel.peeking, .swipe-snap-panel.incoming { @@ -418,6 +459,15 @@ html.dark { color-scheme: dark; } min-height: 100%; } +/* Browsers chain the document's top overscroll into pull-to-refresh, which + reloads the SPA and costs the reader their feed position. `contain` blocks the + chain but keeps the rubber-band `none` would remove. On the root because only + the root's value reaches the viewport, and unscoped because `/user/:id` leaves + swipe mode and is just as expensive to reload. */ +html { + overscroll-behavior-y: contain; +} + /* In swipe mode, the document scrolls naturally (enabling URL bar hiding). overflow-x prevents horizontal scroll from drag resistance transform. Native scrollbar is hidden — replaced by custom indicator below the header. */ @@ -517,20 +567,26 @@ body.swipe-mode.is-swiping .app-header { justify-content: center; } -@media (min-width: 768px) { +/* Stands in for the `max-w-6xl px-4 md:px-8 lg:px-16 xl:px-24` container, so its + gutters must switch where that container's do — hence @variant rather than px + queries, which drift once the reader's default font size moves. */ +@variant md { .page-state-center-padded { padding-inline: 2rem; } } -@media (min-width: 1024px) { +@variant lg { .page-state-center-padded { padding-inline: 4rem; } } -@media (min-width: 1280px) { +@variant xl { .page-state-center-padded { padding-inline: 6rem; } } /* ── Network status bar ────────────────────────────────────────────── */ /* Desktop only: pad body so scrollable content isn't hidden behind the bar. - Mobile uses height-based calc in swipe containers instead. */ + Mobile uses height-based calc in swipe containers instead. + + px on purpose, unlike the @variant rules above: this asks which layout React + mounted, and useIsMobile answers with `(max-width: 767px)`. */ @media (min-width: 768px) { body { padding-bottom: var(--network-bar-height); diff --git a/src/lib/classes.ts b/src/lib/classes.ts index 165cd58..2ed3c81 100644 --- a/src/lib/classes.ts +++ b/src/lib/classes.ts @@ -2,8 +2,11 @@ * Shared meta-row classNames. `metaItemClass` = non-clickable spans; * `metaPillClass` = clickable variant with hover backdrop and negative * margin to cancel padding so gap rhythm stays consistent. + * + * `active:` mirrors `hover:` because Tailwind scopes `hover:` behind + * `@media (hover: hover)`, leaving a tap with no feedback otherwise. */ export const metaItemClass = 'inline-flex items-center gap-1.5'; export const metaPillClass = - 'inline-flex items-center gap-1.5 px-1.5 py-0.5 -mx-1.5 -my-0.5 rounded-lg hover:bg-muted hover:text-foreground transition-colors'; + 'inline-flex items-center gap-1.5 px-1.5 py-0.5 -mx-1.5 -my-0.5 rounded-lg hover:bg-muted hover:text-foreground active:bg-muted active:text-foreground transition-colors'; diff --git a/src/lib/pressStates.test.ts b/src/lib/pressStates.test.ts new file mode 100644 index 0000000..2dafc57 --- /dev/null +++ b/src/lib/pressStates.test.ts @@ -0,0 +1,74 @@ +import { readdirSync, readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import { describe, it, expect } from 'vitest'; + +// Tailwind compiles `hover:` inside `@media (hover: hover)` and its preflight +// zeroes `-webkit-tap-highlight-color`, so a hover affordance with no `active:` +// twin is invisible to a finger. Nothing rendered can catch that: a synthesised +// press leaves `:active` unset in headless Chromium, so this reads the source — +// the same bind themeColors.test.ts is in. + +const SOURCE_ROOT = resolve(process.cwd(), 'src'); + +const sourceFiles = readdirSync(SOURCE_ROOT, { recursive: true, encoding: 'utf8' }) + .filter((path) => /\.tsx?$/.test(path) && !path.includes('.test.')) + .map((path) => resolve(SOURCE_ROOT, path)); + +/** Prose about a class is not a class. */ +const withoutComments = (source: string) => + source.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/.*$/gm, ''); + +/** `dark:hover:bg-muted/50` → variants `dark:`, property `bg`. The value is + * optional so a `hover:underline` still counts as an affordance. */ +const HOVER_UTILITY = /((?:[a-z-]+:)*)hover:([a-z]+)[a-z0-9/.[\]-]*/g; + +/** + * Same variants and same property, not the same value: a press may be a + * different shade than its hover, but it has to change the same thing. Both + * boundaries earn their keep — the lookbehind stops a bare `hover:` settling + * for the `dark:active:` beside it, and the lookahead stops a property passing + * for one that merely starts the same way. + */ +function hoversWithoutAPress(text: string) { + return [...text.matchAll(HOVER_UTILITY)] + .filter( + ([, variants, property]) => + !new RegExp(`(? ({ hover, twin: `${variants}active:${property}` })); +} + +describe('every hover affordance has a press state a finger can reach', () => { + it('pairs each hover utility with an active one on the same element', () => { + const offenders: string[] = []; + + for (const file of sourceFiles) { + withoutComments(readFileSync(file, 'utf8')) + .split('\n') + .forEach((text, index) => { + for (const { hover, twin } of hoversWithoutAPress(text)) { + offenders.push( + `${file.slice(SOURCE_ROOT.length + 1)}:${index + 1} — ${hover} has no ${twin} twin`, + ); + } + }); + } + + expect(offenders, `\n ${offenders.join('\n ')}\n`).toEqual([]); + }); + + it('recognises an unpaired hover when it sees one', () => { + // The scan above can only mean something if it can fail, and the repo has + // nothing left for it to catch. + const paired = 'hover:bg-muted active:bg-muted dark:hover:bg-muted/50 dark:active:bg-muted/50'; + const darkPressOnly = 'hover:bg-muted dark:hover:bg-muted/50 dark:active:bg-muted/50'; + + expect(hoversWithoutAPress(paired)).toEqual([]); + expect(hoversWithoutAPress(darkPressOnly)).toEqual([ + { hover: 'hover:bg-muted', twin: 'active:bg' }, + ]); + expect(hoversWithoutAPress('hover:underline')).toEqual([ + { hover: 'hover:underline', twin: 'active:underline' }, + ]); + }); +}); diff --git a/src/main.tsx b/src/main.tsx index 2851b4b..24d5dd9 100644 --- a/src/main.tsx +++ b/src/main.tsx @@ -3,10 +3,13 @@ import { createRoot } from 'react-dom/client' import './index.css' import App from './App' import { pruneExpiredViewed } from './utils/viewedItems' +import { enableTouchActiveStates } from './utils/touchActiveStates' // Clean up expired viewed entries on app load (runs exactly once) pruneExpiredViewed(); +enableTouchActiveStates(); + createRoot(document.getElementById('root')!).render( diff --git a/src/utils/releaseVelocity.test.ts b/src/utils/releaseVelocity.test.ts new file mode 100644 index 0000000..44766eb --- /dev/null +++ b/src/utils/releaseVelocity.test.ts @@ -0,0 +1,59 @@ +import { describe, it, expect } from 'vitest'; +import { releaseVelocityFrom } from './releaseVelocity'; + +// The settle animation inherits this number: measure the wrong stretch of the +// drag and a committed swipe visibly slows the moment the finger leaves. +describe('releaseVelocityFrom', () => { + it('reads the flick a reader ends on, not the pause before it', () => { + const samples = [ + { x: 0, t: 0 }, + { x: -10, t: 200 }, + { x: -20, t: 400 }, + { x: -60, t: 440 }, + { x: -100, t: 480 }, + ]; + + const velocity = releaseVelocityFrom(samples, 480); + const gestureAverage = 100 / 480; + + // 80px over the trailing 80ms, against 0.21px/ms across the whole drag. + expect(velocity).toBeCloseTo(1); + expect(velocity!).toBeGreaterThan(gestureAverage * 4); + }); + + it('rides over a jittery final frame instead of trusting the last pair', () => { + // Steady 1px/ms, but the last frame landed almost nowhere. The last two + // points alone would report a quarter of the real speed. + const samples = [ + { x: 0, t: 0 }, + { x: -40, t: 40 }, + { x: -80, t: 80 }, + { x: -81, t: 84 }, + ]; + + const velocity = releaseVelocityFrom(samples, 84); + const naiveLastPair = 1 / 4; + + expect(velocity).toBeCloseTo(0.96, 1); + expect(velocity!).toBeGreaterThan(naiveLastPair * 3); + }); + + it('reports a standstill when the finger parked before lifting', () => { + // Dragged fast, held 300ms, released: continuing that speed would fling a + // panel the reader had already stopped. + const samples = [ + { x: 0, t: 0 }, + { x: -120, t: 100 }, + ]; + + expect(releaseVelocityFrom(samples, 400)).toBe(0); + }); + + it('declines to guess from a drag too brief to measure', () => { + // `null` is not zero: it sends the caller back to its gesture average rather + // than reporting a flick as motionless. + expect(releaseVelocityFrom([], 0)).toBeNull(); + expect(releaseVelocityFrom([{ x: -30, t: 0 }], 0)).toBeNull(); + expect(releaseVelocityFrom([{ x: 0, t: 0 }, { x: -30, t: 4 }], 4)).toBeNull(); + }); +}); diff --git a/src/utils/releaseVelocity.ts b/src/utils/releaseVelocity.ts new file mode 100644 index 0000000..c04f65c --- /dev/null +++ b/src/utils/releaseVelocity.ts @@ -0,0 +1,41 @@ +/** + * Trailing window for release speed: wide enough to smooth 60Hz jitter, short + * enough that a pause before the flick falls outside it. + */ +const VELOCITY_WINDOW_MS = 80; + +/** Below this, a sample pair is too close in time to divide by. */ +const MIN_VELOCITY_SPAN_MS = 8; + +/** ~130ms of moves at 120Hz, so the window above is always spannable. */ +export const MAX_DRAG_SAMPLES = 16; + +export interface DragSample { + /** Clamped offset, so travel the panel never made isn't counted as speed. */ + x: number; + t: number; +} + +/** + * Speed the panel was moving at when the finger left, in px/ms. `null` when the + * drag is too brief to measure — the caller falls back to the gesture average. + */ +export function releaseVelocityFrom(samples: DragSample[], releaseTime: number): number | null { + const last = samples[samples.length - 1]; + if (!last) return null; + + // Parked before lifting: no momentum to continue. + if (releaseTime - last.t > VELOCITY_WINDOW_MS) return 0; + + // Measuring across the window needs a sample on the far side of it. + let oldest = last; + for (let i = samples.length - 2; i >= 0; i--) { + oldest = samples[i]; + if (last.t - oldest.t >= VELOCITY_WINDOW_MS) break; + } + + const span = last.t - oldest.t; + if (span < MIN_VELOCITY_SPAN_MS) return null; + + return Math.abs(last.x - oldest.x) / span; +} diff --git a/src/utils/touchActiveStates.test.ts b/src/utils/touchActiveStates.test.ts new file mode 100644 index 0000000..245b228 --- /dev/null +++ b/src/utils/touchActiveStates.test.ts @@ -0,0 +1,31 @@ +import { describe, it, expect, afterEach, vi } from 'vitest'; +import { enableTouchActiveStates } from './touchActiveStates'; + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe('enableTouchActiveStates', () => { + it('registers a passive touchstart handler on the document, which is what iOS gates :active on', () => { + const addEventListener = vi.spyOn(document, 'addEventListener'); + + enableTouchActiveStates(); + + // The handler does nothing, so a non-passive one would cost the document its + // scroll fast path for nothing. + expect(addEventListener).toHaveBeenCalledWith( + 'touchstart', + expect.any(Function), + { passive: true }, + ); + }); + + it('does nothing when a touch actually arrives', () => { + enableTouchActiveStates(); + + // Anything this handler did would run on every touch, including mid-swipe. + const event = new Event('touchstart', { bubbles: true, cancelable: true }); + expect(() => document.dispatchEvent(event)).not.toThrow(); + expect(event.defaultPrevented).toBe(false); + }); +}); diff --git a/src/utils/touchActiveStates.ts b/src/utils/touchActiveStates.ts new file mode 100644 index 0000000..57eb0c1 --- /dev/null +++ b/src/utils/touchActiveStates.ts @@ -0,0 +1,11 @@ +/** + * Let `:active` fire on iOS, where Safari applies it only if a touch handler + * sits on the element or the document. Without this, press states outside the + * swipe container never run — and Tailwind's preflight has already zeroed + * `-webkit-tap-highlight-color`, so nothing else gives feedback on a tap. + * + * Passive, so it cannot affect scrolling. Other engines ignore it. + */ +export function enableTouchActiveStates() { + document.addEventListener('touchstart', () => undefined, { passive: true }); +}