Skip to content

Commit 710d2b0

Browse files
authored
fix(docs): preserve user gesture when copying remote page markdown (#1486)
Co-authored-by: sentry[bot] <39604003+sentry[bot]@users.noreply.github.com>
1 parent db37e2f commit 710d2b0

3 files changed

Lines changed: 234 additions & 46 deletions

File tree

‎src/components/CopyPageDropdown.tsx‎

Lines changed: 61 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,9 @@ import {
1111
DropdownItem,
1212
} from './Dropdown'
1313
import { getPackageManager } from '~/utils/markdown/installCommand'
14+
import * as Sentry from '@sentry/tanstackstart-react'
1415
import {
15-
copyTextToClipboard,
16+
copyTextPromiseToClipboard,
1617
openPopupWindow,
1718
useTemporaryFlag,
1819
} from '~/utils/browser-effects'
@@ -150,72 +151,87 @@ export function CopyPageDropdown({
150151
? `https://raw.githubusercontent.com/${repo}/${branch}/${filePath}`
151152
: pageMarkdownUrl
152153

153-
const handleCopyPage = async () => {
154+
// Resolve the text to copy (raw content, cache, fetched markdown, or fallbacks).
155+
const resolveCopyContent = async (): Promise<{
156+
content: string
157+
source?: string
158+
}> => {
154159
if (rawContent) {
155-
await copyTextToClipboard(rawContent)
156-
copied.trigger()
157-
notify(
158-
<div>
159-
<div className="font-medium">Copied to clipboard</div>
160-
</div>,
161-
{ id: 'page-copied' },
162-
)
163-
return
160+
return { content: rawContent }
164161
}
165162

166163
const urlToFetch = sourceMarkdownUrl
167164
const cached = markdownCache.get(urlToFetch)
168165

169-
const copyContent = async (content: string, source: string) => {
170-
await copyTextToClipboard(content)
171-
copied.trigger()
172-
notify(
173-
<div>
174-
<div className="font-medium">Copied to clipboard</div>
175-
<div className="text-xs text-gray-500 dark:text-gray-400">
176-
{source}
177-
</div>
178-
</div>,
179-
{ id: 'page-copied' },
180-
)
181-
}
182-
183166
if (cached) {
184-
await copyContent(cached, 'Markdown content copied from cache')
185-
return
167+
return { content: cached, source: 'Markdown content copied from cache' }
186168
}
187169

188170
try {
189171
const response = await fetch(urlToFetch)
190172
if (!response.ok) throw new Error('Failed to fetch')
191173
const content = await response.text()
192174
markdownCache.set(urlToFetch, content)
193-
await copyContent(
175+
return {
194176
content,
195-
repo === 'tanstack/tanstack.com' && hasPageMarkdownEndpoint
196-
? 'Markdown content copied from markdown endpoint'
197-
: 'Markdown content copied from GitHub',
198-
)
177+
source:
178+
repo === 'tanstack/tanstack.com' && hasPageMarkdownEndpoint
179+
? 'Markdown content copied from markdown endpoint'
180+
: 'Markdown content copied from GitHub',
181+
}
199182
} catch {
200183
// Fallback: try to copy current page content if available
201184
const pageContent =
202185
document.querySelector('.styled-markdown-content')?.textContent || ''
203186
if (pageContent) {
204-
await copyContent(pageContent, 'Copied rendered page content')
205-
} else {
206-
// Last resort: copy the URL
207-
await copyTextToClipboard(window.location.href)
208-
copied.trigger()
209-
notify(
210-
<div>
211-
<div className="font-medium">Copied to clipboard</div>
187+
return { content: pageContent, source: 'Copied rendered page content' }
188+
}
189+
// Last resort: copy the URL
190+
return { content: window.location.href, source: 'Page URL copied' }
191+
}
192+
}
193+
194+
const handleCopyPage = async () => {
195+
// Start the clipboard write synchronously inside the click handler and let
196+
// the content resolve later. Awaiting the fetch first consumes the user
197+
// activation, and WebKit (iOS Safari) then rejects every clipboard write.
198+
const contentPromise = resolveCopyContent()
199+
const copyPromise = copyTextPromiseToClipboard(
200+
contentPromise.then(({ content }) => content),
201+
)
202+
203+
try {
204+
await copyPromise
205+
const { source } = await contentPromise
206+
copied.trigger()
207+
notify(
208+
<div>
209+
<div className="font-medium">Copied to clipboard</div>
210+
{source ? (
212211
<div className="text-xs text-gray-500 dark:text-gray-400">
213-
Page URL copied
212+
{source}
214213
</div>
215-
</div>,
216-
{ id: 'page-copied' },
217-
)
218-
}
214+
) : null}
215+
</div>,
216+
{ id: 'page-copied' },
217+
)
218+
} catch (error) {
219+
Sentry.captureException(error, {
220+
tags: { feature: 'copy-page' },
221+
extra: {
222+
sourceMarkdownUrl,
223+
hasClipboardItem: typeof ClipboardItem !== 'undefined',
224+
},
225+
})
226+
notify(
227+
<div>
228+
<div className="font-medium">Copy failed</div>
229+
<div className="text-xs text-gray-500 dark:text-gray-400">
230+
Your browser blocked clipboard access. Try View as Markdown instead.
231+
</div>
232+
</div>,
233+
{ id: 'page-copy-failed' },
234+
)
219235
}
220236
}
221237

‎src/utils/browser-effects.ts‎

Lines changed: 60 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,20 @@
11
import * as React from 'react'
22
import { trackScarfClipboardText } from '~/utils/analytics/scarf'
33

4+
// Analytics must never turn a successful copy into a failure.
5+
function trackClipboardCopy(text: string) {
6+
try {
7+
trackScarfClipboardText('copy', text)
8+
} catch {
9+
// ignore analytics failures
10+
}
11+
}
12+
413
export async function copyTextToClipboard(value: string) {
514
if (typeof navigator !== 'undefined' && navigator.clipboard) {
615
try {
716
await navigator.clipboard.writeText(value)
8-
trackScarfClipboardText('copy', value)
17+
trackClipboardCopy(value)
918
return
1019
} catch {
1120
// Fall back for restricted contexts where the Clipboard API exists but rejects.
@@ -40,6 +49,56 @@ export async function copyTextToClipboard(value: string) {
4049
}
4150
}
4251

52+
/**
53+
* Copies text that is still being produced (e.g. fetched over the network).
54+
*
55+
* The clipboard write is started synchronously, before the text is ready, so it
56+
* stays tied to the user gesture that triggered it. WebKit (iOS Safari) rejects
57+
* clipboard writes made after an await has consumed the user activation.
58+
*/
59+
export function copyTextPromiseToClipboard(
60+
textPromise: Promise<string>,
61+
): Promise<string> {
62+
const fallback = async () => {
63+
const text = await textPromise
64+
await copyTextToClipboard(text)
65+
return text
66+
}
67+
68+
if (
69+
typeof navigator === 'undefined' ||
70+
!navigator.clipboard ||
71+
typeof navigator.clipboard.write !== 'function' ||
72+
typeof ClipboardItem === 'undefined'
73+
) {
74+
return fallback()
75+
}
76+
77+
let writePromise: Promise<void>
78+
try {
79+
const blobPromise = textPromise.then(
80+
(text) => new Blob([text], { type: 'text/plain' }),
81+
)
82+
// Avoid an unhandled rejection if the browser never consumes the blob.
83+
blobPromise.catch(() => {})
84+
writePromise = navigator.clipboard.write([
85+
new ClipboardItem({ 'text/plain': blobPromise }),
86+
])
87+
} catch {
88+
return fallback()
89+
}
90+
91+
return writePromise.then(
92+
async () => {
93+
const text = await textPromise
94+
trackClipboardCopy(text)
95+
return text
96+
},
97+
// Promise-based ClipboardItem unsupported or rejected: try the text path.
98+
fallback,
99+
)
100+
}
101+
43102
export function openPopupWindow(
44103
url: string,
45104
target = '_blank',

‎tests/copy-text-promise.test.ts‎

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
import assert from 'node:assert/strict'
2+
import test from 'node:test'
3+
import { copyTextPromiseToClipboard } from '../src/utils/browser-effects'
4+
5+
type Globals = { navigator?: unknown; ClipboardItem?: unknown }
6+
const g = globalThis as unknown as Globals
7+
8+
function withGlobals(
9+
overrides: Globals,
10+
fn: () => Promise<void>,
11+
): Promise<void> {
12+
const navDesc = Object.getOwnPropertyDescriptor(globalThis, 'navigator')
13+
const itemDesc = Object.getOwnPropertyDescriptor(globalThis, 'ClipboardItem')
14+
Object.defineProperty(globalThis, 'navigator', {
15+
value: overrides.navigator,
16+
configurable: true,
17+
writable: true,
18+
})
19+
Object.defineProperty(globalThis, 'ClipboardItem', {
20+
value: overrides.ClipboardItem,
21+
configurable: true,
22+
writable: true,
23+
})
24+
return fn().finally(() => {
25+
if (navDesc) Object.defineProperty(globalThis, 'navigator', navDesc)
26+
else delete g.navigator
27+
if (itemDesc) Object.defineProperty(globalThis, 'ClipboardItem', itemDesc)
28+
else delete g.ClipboardItem
29+
})
30+
}
31+
32+
class FakeClipboardItem {
33+
constructor(public items: Record<string, Promise<Blob>>) {}
34+
}
35+
36+
test('starts clipboard.write synchronously before the text resolves', async () => {
37+
const written: Array<unknown> = []
38+
let resolveText!: (text: string) => void
39+
const textPromise = new Promise<string>((resolve) => {
40+
resolveText = resolve
41+
})
42+
43+
await withGlobals(
44+
{
45+
ClipboardItem: FakeClipboardItem,
46+
navigator: {
47+
clipboard: {
48+
write: async (items: Array<FakeClipboardItem>) => {
49+
written.push(items)
50+
const blob = await items[0].items['text/plain']
51+
assert.equal(await blob.text(), '# Markdown')
52+
},
53+
writeText: async () => {
54+
throw new Error('writeText should not be used')
55+
},
56+
},
57+
},
58+
},
59+
async () => {
60+
const result = copyTextPromiseToClipboard(textPromise)
61+
// write() must be invoked synchronously, while still in the gesture.
62+
assert.equal(written.length, 1)
63+
resolveText('# Markdown')
64+
assert.equal(await result, '# Markdown')
65+
},
66+
)
67+
})
68+
69+
test('falls back to writeText when the promise-based write rejects', async () => {
70+
const writeTextCalls: Array<string> = []
71+
72+
await withGlobals(
73+
{
74+
ClipboardItem: FakeClipboardItem,
75+
navigator: {
76+
clipboard: {
77+
write: async () => {
78+
throw new Error('NotAllowedError')
79+
},
80+
writeText: async (text: string) => {
81+
writeTextCalls.push(text)
82+
},
83+
},
84+
},
85+
},
86+
async () => {
87+
const result = await copyTextPromiseToClipboard(Promise.resolve('hello'))
88+
assert.equal(result, 'hello')
89+
assert.deepEqual(writeTextCalls, ['hello'])
90+
},
91+
)
92+
})
93+
94+
test('uses writeText when ClipboardItem is unavailable', async () => {
95+
const writeTextCalls: Array<string> = []
96+
97+
await withGlobals(
98+
{
99+
ClipboardItem: undefined,
100+
navigator: {
101+
clipboard: {
102+
writeText: async (text: string) => {
103+
writeTextCalls.push(text)
104+
},
105+
},
106+
},
107+
},
108+
async () => {
109+
assert.equal(await copyTextPromiseToClipboard(Promise.resolve('x')), 'x')
110+
assert.deepEqual(writeTextCalls, ['x'])
111+
},
112+
)
113+
})

0 commit comments

Comments
 (0)