diff --git a/e2e/share.spec.ts b/e2e/share.spec.ts new file mode 100644 index 0000000..e107075 --- /dev/null +++ b/e2e/share.spec.ts @@ -0,0 +1,134 @@ +import { test, expect, type Page } from '@playwright/test'; +import { setupApiMocks } from './fixtures/api-mocks'; +import { waitForSwipeReady } from './fixtures/swipe-helpers'; + +// The share control is the app's only route for lifting an item's own URL out +// of the feed. It renders through ItemArticle, which both the desktop detail +// page and the mobile swipe panel mount, so both surfaces are checked. +// +// Neither Web Share nor the clipboard can be driven for real here: the share +// sheet is OS chrome Playwright cannot see, and clipboard access needs +// per-browser permission grants. Both APIs are therefore installed as recorders +// before the app boots, which is also the only way to assert the exact payload. + +const ITEM_ID = 12345; + +declare global { + interface Window { + __sharePayloads?: { title?: string; url?: string }[]; + __clipboardWrites?: string[]; + } +} + +/** Install a recording `navigator.share`, as a platform that has a share sheet. */ +async function recordShares(page: Page) { + await page.addInitScript(() => { + window.__sharePayloads = []; + Object.defineProperty(navigator, 'share', { + configurable: true, + value: (data: { title?: string; url?: string }) => { + window.__sharePayloads!.push(data); + return Promise.resolve(); + }, + }); + }); +} + +/** + * Present a platform with no share sheet but a working clipboard, which is what + * desktop Firefox actually is. + */ +async function recordClipboardOnly(page: Page) { + await page.addInitScript(() => { + window.__clipboardWrites = []; + // WebKit ships a real `navigator.share` on the prototype, so deleting an own + // property leaves it in place — it has to be shadowed instead. + Object.defineProperty(navigator, 'share', { configurable: true, value: undefined }); + Object.defineProperty(navigator, 'clipboard', { + configurable: true, + value: { + writeText: (text: string) => { + window.__clipboardWrites!.push(text); + return Promise.resolve(); + }, + }, + }); + }); +} + +const shareButton = (page: Page) => page.getByRole('button', { name: 'Share' }); + +test.describe('Share control', () => { + test.describe('desktop detail page', () => { + test.use({ viewport: { width: 1280, height: 720 } }); + + test('shares this app\'s link to the item', async ({ page }) => { + await recordShares(page); + await setupApiMocks(page); + await page.goto(`/#/item/${ITEM_ID}`); + + await shareButton(page).click(); + + const payloads = await page.evaluate(() => window.__sharePayloads); + expect(payloads).toHaveLength(1); + expect(payloads![0].url).toBe(`${new URL(page.url()).origin}/#/item/${ITEM_ID}`); + // A bare URL in a share sheet gives the recipient no context, so the + // headline travels with it. + expect(payloads![0].title).toBeTruthy(); + }); + + test('copies the link and says so where there is no share sheet', async ({ page }) => { + await recordClipboardOnly(page); + await setupApiMocks(page); + await page.goto(`/#/item/${ITEM_ID}`); + + await shareButton(page).click(); + + const writes = await page.evaluate(() => window.__clipboardWrites); + expect(writes).toEqual([`${new URL(page.url()).origin}/#/item/${ITEM_ID}`]); + // The sheet would have confirmed itself; a silent copy has to be announced. + await expect( + page.getByRole('status').filter({ hasText: 'Link copied to clipboard' }), + ).toHaveCount(1); + }); + }); + + test.describe('mobile swipe panel', () => { + // A finger as well as a narrow viewport: the swipe viewer asks for both, so + // a narrowed desktop window would get the detail page instead. + test.use({ viewport: { width: 375, height: 667 }, hasTouch: true }); + + test('shares from inside the swipe viewer', async ({ page }) => { + await recordShares(page); + await setupApiMocks(page); + await page.goto(`/#/item/${ITEM_ID}`); + await waitForSwipeReady(page); + + await page + .locator('.swipe-snap-panel.active') + .getByRole('button', { name: 'Share' }) + .click(); + + const payloads = await page.evaluate(() => window.__sharePayloads); + expect(payloads).toHaveLength(1); + expect(payloads![0].url).toBe(`${new URL(page.url()).origin}/#/item/${ITEM_ID}`); + }); + }); + + test.describe('platforms with neither route', () => { + test('renders no control at all rather than a dead one', async ({ page }) => { + await page.addInitScript(() => { + Object.defineProperty(navigator, 'share', { configurable: true, value: undefined }); + Object.defineProperty(navigator, 'clipboard', { configurable: true, value: undefined }); + }); + await setupApiMocks(page); + await page.goto(`/#/item/${ITEM_ID}`); + + // Anchor on the article having rendered, so this can't pass just because + // the page never loaded. Scoped to the first match because the swipe + // viewer keeps inactive panels in the DOM behind `display: none`. + await expect(page.locator('article h1').first()).toBeVisible(); + await expect(shareButton(page)).toHaveCount(0); + }); + }); +}); diff --git a/src/components/ItemArticle.tsx b/src/components/ItemArticle.tsx index 6be051f..741aeb5 100644 --- a/src/components/ItemArticle.tsx +++ b/src/components/ItemArticle.tsx @@ -4,9 +4,11 @@ import { ChevronUp, Clock, Globe, MessageSquare } from 'lucide-react'; import { getHostname } from '../api/hn'; import { sanitizeHtml } from '../utils/sanitize'; import { useIsViewed, markViewedWithTime } from '../utils/viewedItems'; +import { itemPermalink } from '../utils/share'; import { metaItemClass, metaPillClass } from '../lib/classes'; import { AuthorByline } from './AuthorByline'; import { RelativeTime } from './RelativeTime'; +import { ShareButton } from './ShareButton'; import type { Item } from '../types'; interface ItemArticleProps { @@ -76,6 +78,8 @@ export function ItemArticle({ item, className = 'mb-4 pb-4 border-b border-borde {item.type !== 'job' ? (item.commentCount ?? 0) : 0} comments + + {sanitizedText && ( diff --git a/src/components/ShareButton.test.tsx b/src/components/ShareButton.test.tsx new file mode 100644 index 0000000..88877ef --- /dev/null +++ b/src/components/ShareButton.test.tsx @@ -0,0 +1,141 @@ +import { describe, it, expect, afterEach, vi } from 'vitest'; +import { render, screen, act, fireEvent } from '@testing-library/react'; +import { ShareButton } from './ShareButton'; + +// jsdom provides neither API, so every test installs the capabilities it needs. +function stubNavigator(props: { share?: unknown; clipboard?: unknown }) { + for (const [key, value] of Object.entries(props)) { + Object.defineProperty(navigator, key, { value, configurable: true, writable: true }); + } +} + +/** Click and let the async share/copy handler settle before asserting. */ +async function clickShare() { + await act(async () => { + fireEvent.click(screen.getByRole('button', { name: 'Share' })); + }); +} + +afterEach(() => { + for (const key of ['share', 'clipboard']) { + if (key in navigator) Reflect.deleteProperty(navigator, key); + } + vi.useRealTimers(); + vi.restoreAllMocks(); +}); + +const props = { title: 'Rust Is the Future', url: 'https://example.test/#/item/1' }; + +describe('ShareButton', () => { + it('renders nothing when the platform can neither share nor copy', () => { + const { container } = render(); + expect(container).toBeEmptyDOMElement(); + }); + + it('keeps a stable accessible name so the label swap cannot rename it', async () => { + stubNavigator({ clipboard: { writeText: vi.fn().mockResolvedValue(undefined) } }); + render(); + + await clickShare(); + + expect(screen.getByText('copied')).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Share' })).toBeInTheDocument(); + }); + + it('hands the title and URL to the share sheet', async () => { + const share = vi.fn().mockResolvedValue(undefined); + stubNavigator({ share }); + render(); + + await clickShare(); + + expect(share).toHaveBeenCalledWith(props); + }); + + it('still copies on a later press when an earlier share never settles', async () => { + // Browsers have left a dismissed share pending for good. Every later call + // then rejects with InvalidStateError, so the clipboard is the only route + // left, and a press must not be swallowed while waiting on the first. + let pending = false; + const share = vi.fn(() => { + if (pending) { + return Promise.reject( + new DOMException('An earlier share has not yet completed.', 'InvalidStateError'), + ); + } + pending = true; + return new Promise(() => { /* never resolves */ }); + }); + const writeText = vi.fn().mockResolvedValue(undefined); + stubNavigator({ share, clipboard: { writeText } }); + render(); + + await clickShare(); + await clickShare(); + + expect(writeText).toHaveBeenCalledWith(props.url); + expect(screen.getByRole('status')).toHaveTextContent('Link copied to clipboard'); + }); + + it('stays silent after a successful share, because the sheet is its own feedback', async () => { + stubNavigator({ share: vi.fn().mockResolvedValue(undefined) }); + render(); + + await clickShare(); + + expect(screen.getByText('share')).toBeInTheDocument(); + expect(screen.queryByText('copied')).not.toBeInTheDocument(); + expect(screen.getByRole('status')).toBeEmptyDOMElement(); + }); + + it('confirms visibly and audibly when it falls back to the clipboard', async () => { + const writeText = vi.fn().mockResolvedValue(undefined); + stubNavigator({ clipboard: { writeText } }); + render(); + + await clickShare(); + + expect(writeText).toHaveBeenCalledWith(props.url); + expect(screen.getByText('copied')).toBeInTheDocument(); + expect(screen.getByRole('status')).toHaveTextContent('Link copied to clipboard'); + }); + + it('reverts the confirmation after it has been read', async () => { + vi.useFakeTimers(); + stubNavigator({ clipboard: { writeText: vi.fn().mockResolvedValue(undefined) } }); + render(); + + await clickShare(); + expect(screen.getByText('copied')).toBeInTheDocument(); + + await act(async () => { + vi.advanceTimersByTime(2000); + }); + + expect(screen.getByText('share')).toBeInTheDocument(); + expect(screen.getByRole('status')).toBeEmptyDOMElement(); + }); + + it('says nothing when neither route succeeds', async () => { + stubNavigator({ clipboard: { writeText: vi.fn().mockRejectedValue(new Error('denied')) } }); + render(); + + await clickShare(); + + expect(screen.getByText('share')).toBeInTheDocument(); + expect(screen.getByRole('status')).toBeEmptyDOMElement(); + }); + + it('does not leave the revert timer running past unmount', async () => { + vi.useFakeTimers(); + stubNavigator({ clipboard: { writeText: vi.fn().mockResolvedValue(undefined) } }); + const { unmount } = render(); + + await clickShare(); + expect(vi.getTimerCount()).toBe(1); + + unmount(); + + expect(vi.getTimerCount()).toBe(0); + }); +}); diff --git a/src/components/ShareButton.tsx b/src/components/ShareButton.tsx new file mode 100644 index 0000000..b68a7a4 --- /dev/null +++ b/src/components/ShareButton.tsx @@ -0,0 +1,64 @@ +import { useCallback, useEffect, useRef, useState } from 'react'; +import { Check, Share2 } from 'lucide-react'; +import { metaPillClass } from '../lib/classes'; +import { canShareOrCopy, shareOrCopy } from '../utils/share'; + +/** How long the copy confirmation holds before the label reverts. */ +const COPIED_FEEDBACK_MS = 2000; + +interface ShareButtonProps { + title: string; + url: string; +} + +/** + * Meta-row control that hands an item to the platform share sheet. + * + * Only the clipboard path gets visible feedback: the share sheet is its own + * confirmation, whereas a copy is otherwise silent. The label carries that + * feedback, but the button keeps a fixed accessible name so the control doesn't + * appear to rename itself two seconds after being pressed; the copy is + * announced separately instead. + */ +export function ShareButton({ title, url }: ShareButtonProps) { + const [copied, setCopied] = useState(false); + const revertTimerRef = useRef | null>(null); + + useEffect( + () => () => { + if (revertTimerRef.current) clearTimeout(revertTimerRef.current); + }, + [], + ); + + const handleClick = useCallback(async () => { + const outcome = await shareOrCopy({ title, url }); + // 'shared' and 'dismissed' both mean the sheet spoke for us, and + // 'unavailable' has nothing truthful to report. + if (outcome !== 'copied') return; + + setCopied(true); + if (revertTimerRef.current) clearTimeout(revertTimerRef.current); + revertTimerRef.current = setTimeout(() => setCopied(false), COPIED_FEEDBACK_MS); + }, [title, url]); + + // A control that cannot act is worse than no control. + if (!canShareOrCopy()) return null; + + return ( + <> + + {/* Out of flow, so it adds no gap to the meta row. */} + + {copied ? 'Link copied to clipboard' : ''} + + + ); +} diff --git a/src/components/index.ts b/src/components/index.ts index c8ec494..cc44e13 100644 --- a/src/components/index.ts +++ b/src/components/index.ts @@ -18,3 +18,4 @@ export { FullScreenComment, FullScreenCommentSkeleton, FullScreenCommentSkeleton export { CommentsSection } from './CommentsSection'; export { StateView } from './StateView'; export { NetworkStatusBar } from './NetworkStatusBar'; +export { ShareButton } from './ShareButton'; diff --git a/src/index.css b/src/index.css index 12f9ca2..7f28689 100644 --- a/src/index.css +++ b/src/index.css @@ -422,8 +422,10 @@ html.dark { color-scheme: dark; } 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. */ + /* Content links keep the long-press callout. The meta row's share control + carries the item's own link, not the article the headline points to or + the third-party URLs in prose, so on iOS this is still the only way to + lift those out of the feed. */ .swipe-snap-panel h1 a, .swipe-snap-panel .comment-content a { -webkit-touch-callout: default; diff --git a/src/utils/share.test.ts b/src/utils/share.test.ts new file mode 100644 index 0000000..8413b8d --- /dev/null +++ b/src/utils/share.test.ts @@ -0,0 +1,110 @@ +import { describe, it, expect, afterEach, vi } from 'vitest'; +import { canShareOrCopy, itemPermalink, shareOrCopy } from './share'; + +/** + * jsdom ships neither `navigator.share` nor `navigator.clipboard`, so each + * capability has to be installed per test. `configurable` matters: without it + * the property can't be removed again and would leak into the next test. + */ +function stubNavigator(props: { share?: unknown; clipboard?: unknown }) { + for (const [key, value] of Object.entries(props)) { + Object.defineProperty(navigator, key, { value, configurable: true, writable: true }); + } +} + +function clearNavigatorStubs() { + for (const key of ['share', 'clipboard']) { + if (key in navigator) { + Reflect.deleteProperty(navigator, key); + } + } +} + +const payload = { title: 'Rust Is the Future', url: 'https://example.test/#/item/1' }; + +afterEach(() => { + clearNavigatorStubs(); + vi.restoreAllMocks(); +}); + +describe('itemPermalink', () => { + it('builds an absolute hash-route URL on the current origin', () => { + expect(itemPermalink(42)).toBe(`${window.location.origin}/#/item/42`); + }); + + it('accepts a string id without reformatting it', () => { + expect(itemPermalink('42')).toBe(`${window.location.origin}/#/item/42`); + }); +}); + +describe('canShareOrCopy', () => { + it('is false when the platform offers neither route', () => { + expect(canShareOrCopy()).toBe(false); + }); + + it('is true with only the share sheet', () => { + stubNavigator({ share: vi.fn() }); + expect(canShareOrCopy()).toBe(true); + }); + + it('is true with only the clipboard', () => { + stubNavigator({ clipboard: { writeText: vi.fn() } }); + expect(canShareOrCopy()).toBe(true); + }); + + it('is false when clipboard exists but cannot write (non-secure context)', () => { + stubNavigator({ clipboard: {} }); + expect(canShareOrCopy()).toBe(false); + }); +}); + +describe('shareOrCopy', () => { + it('prefers the share sheet and reports it handled the interaction', async () => { + const share = vi.fn().mockResolvedValue(undefined); + const writeText = vi.fn(); + stubNavigator({ share, clipboard: { writeText } }); + + await expect(shareOrCopy(payload)).resolves.toBe('shared'); + expect(share).toHaveBeenCalledWith(payload); + expect(writeText).not.toHaveBeenCalled(); + }); + + it('treats a dismissed sheet as a completed interaction, not a copy', async () => { + const abort = Object.assign(new Error('cancelled'), { name: 'AbortError' }); + const writeText = vi.fn(); + stubNavigator({ share: vi.fn().mockRejectedValue(abort), clipboard: { writeText } }); + + await expect(shareOrCopy(payload)).resolves.toBe('dismissed'); + // The reader chose to back out; silently copying instead would override that. + expect(writeText).not.toHaveBeenCalled(); + }); + + it('falls through to the clipboard when the sheet fails for any other reason', async () => { + const writeText = vi.fn().mockResolvedValue(undefined); + stubNavigator({ + share: vi.fn().mockRejectedValue(new Error('NotAllowedError')), + clipboard: { writeText }, + }); + + await expect(shareOrCopy(payload)).resolves.toBe('copied'); + expect(writeText).toHaveBeenCalledWith(payload.url); + }); + + it('copies the URL when there is no share sheet at all', async () => { + const writeText = vi.fn().mockResolvedValue(undefined); + stubNavigator({ clipboard: { writeText } }); + + await expect(shareOrCopy(payload)).resolves.toBe('copied'); + expect(writeText).toHaveBeenCalledWith(payload.url); + }); + + it('reports unavailable rather than claiming success when the copy is refused', async () => { + stubNavigator({ clipboard: { writeText: vi.fn().mockRejectedValue(new Error('denied')) } }); + + await expect(shareOrCopy(payload)).resolves.toBe('unavailable'); + }); + + it('reports unavailable when neither route exists', async () => { + await expect(shareOrCopy(payload)).resolves.toBe('unavailable'); + }); +}); diff --git a/src/utils/share.ts b/src/utils/share.ts new file mode 100644 index 0000000..148dda0 --- /dev/null +++ b/src/utils/share.ts @@ -0,0 +1,71 @@ +/** + * Sharing an item, with a clipboard path for the browsers that have no share + * sheet. Kept out of the component so the capability matrix — which is most of + * the complexity here — is testable without rendering anything. + */ + +export type ShareOutcome = + /** The system sheet took over; it provides its own confirmation. */ + | 'shared' + /** The reader dismissed the sheet. A completed interaction, not a failure. */ + | 'dismissed' + /** No sheet available (or it failed), so the URL went to the clipboard. */ + | 'copied' + /** Neither route worked; the caller should stay silent rather than lie. */ + | 'unavailable'; + +const canUseShare = () => typeof navigator?.share === 'function'; + +// Types declare `navigator.clipboard` as always present, but it is absent in +// jsdom and outside a secure context, so this has to be a runtime check. +const canUseClipboard = () => typeof navigator?.clipboard?.writeText === 'function'; + +/** Whether a share control has anything to do on this platform. */ +export function canShareOrCopy(): boolean { + return canUseShare() || canUseClipboard(); +} + +/** + * Absolute link to an item's own route. Built from `location.origin` rather than + * a baked-in host so preview deploys and local runs share their own URL, and + * from BASE_URL so it survives the app moving off the domain root. + * + * The `#` is load-bearing: routing is a HashRouter. `index.html` does redirect + * `/item/123` into `/#/item/123`, but only the hash form avoids that round trip. + */ +export function itemPermalink(id: number | string): string { + return `${window.location.origin}${import.meta.env.BASE_URL}#/item/${id}`; +} + +/** + * Hand `data` to the platform share sheet, falling back to the clipboard. + * + * Callers must invoke this directly from a user gesture: `navigator.share` + * requires transient activation and rejects without it. + */ +export async function shareOrCopy(data: { title: string; url: string }): Promise { + if (canUseShare()) { + try { + await navigator.share(data); + return 'shared'; + } catch (error) { + // Dismissal arrives as an exception, so it has to be told apart from a + // real fault before anything is treated as one. + if (error instanceof Error && error.name === 'AbortError') return 'dismissed'; + // Anything else (no activation, an earlier share still pending, an + // OS-level refusal) still leaves the reader wanting the URL, so fall + // through rather than dead-ending. + } + } + + if (canUseClipboard()) { + try { + await navigator.clipboard.writeText(data.url); + return 'copied'; + } catch { + return 'unavailable'; + } + } + + return 'unavailable'; +}