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
134 changes: 134 additions & 0 deletions e2e/share.spec.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
});
4 changes: 4 additions & 0 deletions src/components/ItemArticle.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -76,6 +78,8 @@ export function ItemArticle({ item, className = 'mb-4 pb-4 border-b border-borde
<MessageSquare aria-hidden className="size-3.5" />
<span>{item.type !== 'job' ? (item.commentCount ?? 0) : 0} comments</span>
</span>

<ShareButton title={item.title} url={itemPermalink(item.id)} />
</div>

{sanitizedText && (
Expand Down
141 changes: 141 additions & 0 deletions src/components/ShareButton.test.tsx
Original file line number Diff line number Diff line change
@@ -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(<ShareButton {...props} />);
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(<ShareButton {...props} />);

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(<ShareButton {...props} />);

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<void>(() => { /* never resolves */ });
});
const writeText = vi.fn().mockResolvedValue(undefined);
stubNavigator({ share, clipboard: { writeText } });
render(<ShareButton {...props} />);

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(<ShareButton {...props} />);

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(<ShareButton {...props} />);

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(<ShareButton {...props} />);

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(<ShareButton {...props} />);

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(<ShareButton {...props} />);

await clickShare();
expect(vi.getTimerCount()).toBe(1);

unmount();

expect(vi.getTimerCount()).toBe(0);
});
});
64 changes: 64 additions & 0 deletions src/components/ShareButton.tsx
Original file line number Diff line number Diff line change
@@ -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<ReturnType<typeof setTimeout> | 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 (
<>
<button type="button" onClick={handleClick} className={metaPillClass} aria-label="Share">
{copied ? (
<Check aria-hidden className="size-3.5" />
) : (
<Share2 aria-hidden className="size-3.5" />
)}
<span aria-hidden>{copied ? 'copied' : 'share'}</span>
</button>
{/* Out of flow, so it adds no gap to the meta row. */}
<span role="status" className="sr-only">
{copied ? 'Link copied to clipboard' : ''}
</span>
</>
);
}
1 change: 1 addition & 0 deletions src/components/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,4 @@ export { FullScreenComment, FullScreenCommentSkeleton, FullScreenCommentSkeleton
export { CommentsSection } from './CommentsSection';
export { StateView } from './StateView';
export { NetworkStatusBar } from './NetworkStatusBar';
export { ShareButton } from './ShareButton';
6 changes: 4 additions & 2 deletions src/index.css
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Loading
Loading