Skip to content

Commit b1004b7

Browse files
authored
fix: guard clipboard copy actions (#2292)
## Summary Fixes #2135. Adds a shared `copyTextToClipboard` helper for the trace/event copy actions. It now: - uses `navigator.clipboard.writeText` when the browser permits it - falls back to a hidden textarea + `document.execCommand('copy')` path when the Clipboard API is unavailable, such as insecure/non-HTTPS contexts - shows a clear error notification if both copy methods fail instead of throwing `Cannot read properties of undefined (reading 'writeText')` ### Screenshots or video No screenshot included. This changes the failure/fallback path for browser clipboard permissions rather than the normal visible layout. ### How to test on Vercel preview **Preview routes:** /search **Steps:** 1. Open a search result row with event or trace attributes. 2. Use the copy button for a row value or row JSON. 3. Verify copying succeeds in secure contexts, or shows `Could not access the clipboard. Check browser permissions or use HTTPS.` if clipboard access is unavailable. ### References - Linear Issue: N/A - Related PRs: N/A ### Validation - `yarn build:common-utils` - `yarn workspace @hyperdx/app jest --runTestsByPath src/utils/clipboard.test.ts src/components/DBRowJsonViewer.test.tsx --coverage=false` (passes; existing Mantine notification `act(...)` warnings are printed) - `yarn workspace @hyperdx/app exec tsc --noEmit` - `yarn workspace @hyperdx/app exec npx eslint --quiet src/utils/clipboard.ts src/utils/clipboard.test.ts src/components/DBRowJsonViewer.tsx src/components/DBTable/DBRowTableFieldWithPopover.tsx src/components/DBTable/DBRowTableRowButtons.tsx` Note: full `yarn workspace @hyperdx/app lint` is blocked locally on Windows by unrelated CRLF Prettier errors across existing files in the checkout.
1 parent 4c2c3f3 commit b1004b7

6 files changed

Lines changed: 288 additions & 33 deletions

File tree

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
'@hyperdx/app': patch
3+
---
4+
5+
Fall back when the browser Clipboard API is unavailable and show a clear error
6+
if copying still fails.

‎packages/app/src/components/DBRowJsonViewer.tsx‎

Lines changed: 31 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,10 @@ import {
2929

3030
import HyperJson, { GetLineActions, LineAction } from '@/components/HyperJson';
3131
import { mergePath } from '@/utils';
32+
import {
33+
CLIPBOARD_ERROR_MESSAGE,
34+
copyTextToClipboard,
35+
} from '@/utils/clipboard';
3236

3337
type JSONExtractFn =
3438
| 'JSONExtractString'
@@ -219,12 +223,19 @@ function HyperJsonMenu({ rowData }: { rowData: any }) {
219223
<Group>
220224
{rowData != null && (
221225
<UnstyledButton
222-
onClick={() => {
223-
window.navigator.clipboard.writeText(
226+
onClick={async () => {
227+
const copied = await copyTextToClipboard(
224228
typeof rowData === 'string'
225229
? rowData
226230
: JSON.stringify(rowData, null, 2),
227231
);
232+
if (!copied) {
233+
notifications.show({
234+
color: 'red',
235+
message: CLIPBOARD_ERROR_MESSAGE,
236+
});
237+
return;
238+
}
228239
notifications.show({
229240
color: 'green',
230241
message: `Value copied to clipboard`,
@@ -547,7 +558,7 @@ export function DBRowJsonViewer({
547558
});
548559
}
549560

550-
const handleCopyObject = () => {
561+
const handleCopyObject = async () => {
551562
let copiedObj;
552563

553564
// When in parsed JSON context (e.g., expanded stringified JSON),
@@ -559,9 +570,16 @@ export function DBRowJsonViewer({
559570
copiedObj = keyPath.length === 0 ? rowData : get(rowData, keyPath);
560571
}
561572

562-
window.navigator.clipboard.writeText(
573+
const copied = await copyTextToClipboard(
563574
JSON.stringify(copiedObj, null, 2),
564575
);
576+
if (!copied) {
577+
notifications.show({
578+
color: 'red',
579+
message: CLIPBOARD_ERROR_MESSAGE,
580+
});
581+
return;
582+
}
565583
notifications.show({
566584
color: 'green',
567585
message: `Copied object to clipboard`,
@@ -583,12 +601,19 @@ export function DBRowJsonViewer({
583601
Copy Value
584602
</Group>
585603
),
586-
onClick: () => {
587-
window.navigator.clipboard.writeText(
604+
onClick: async () => {
605+
const copied = await copyTextToClipboard(
588606
typeof value === 'string'
589607
? value
590608
: JSON.stringify(value, null, 2),
591609
);
610+
if (!copied) {
611+
notifications.show({
612+
color: 'red',
613+
message: CLIPBOARD_ERROR_MESSAGE,
614+
});
615+
return;
616+
}
592617
notifications.show({
593618
color: 'green',
594619
message: `Value copied to clipboard`,

‎packages/app/src/components/DBTable/DBRowTableFieldWithPopover.tsx‎

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,14 @@ import React, { useContext, useEffect, useRef, useState } from 'react';
22
import cx from 'classnames';
33
import { Popover } from '@mantine/core';
44
import { useDisclosure } from '@mantine/hooks';
5+
import { notifications } from '@mantine/notifications';
56
import { IconCopy, IconFilter, IconFilterX } from '@tabler/icons-react';
67

8+
import {
9+
CLIPBOARD_ERROR_MESSAGE,
10+
copyTextToClipboard,
11+
} from '@/utils/clipboard';
12+
713
import { RowSidePanelContext } from '../DBRowSidePanel';
814

915
import { DBRowTableIconButton } from './DBRowTableIconButton';
@@ -83,16 +89,18 @@ const DBRowTableFieldWithPopover = ({
8389
};
8490

8591
const copyFieldValue = async () => {
86-
try {
87-
const value =
88-
typeof cellValue === 'string' ? cellValue : String(cellValue ?? '');
89-
await navigator.clipboard.writeText(value);
90-
setIsCopied(true);
91-
setTimeout(() => setIsCopied(false), 2000);
92-
} catch (error) {
93-
console.error('Failed to copy to clipboard:', error);
94-
// Optionally show an error toast notification to the user
92+
const value =
93+
typeof cellValue === 'string' ? cellValue : String(cellValue ?? '');
94+
const copied = await copyTextToClipboard(value);
95+
if (!copied) {
96+
notifications.show({
97+
color: 'red',
98+
message: CLIPBOARD_ERROR_MESSAGE,
99+
});
100+
return;
95101
}
102+
setIsCopied(true);
103+
setTimeout(() => setIsCopied(false), 2000);
96104
};
97105

98106
const addFilter = () => {

‎packages/app/src/components/DBTable/DBRowTableRowButtons.tsx‎

Lines changed: 34 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
11
import React, { useState } from 'react';
2+
import { notifications } from '@mantine/notifications';
23
import { IconCopy, IconLink, IconTextWrap } from '@tabler/icons-react';
34

45
import { INTERNAL_ROW_FIELDS, RowWhereResult } from '@/hooks/useRowWhere';
6+
import {
7+
CLIPBOARD_ERROR_MESSAGE,
8+
copyTextToClipboard,
9+
} from '@/utils/clipboard';
510

611
import { DBRowTableIconButton } from './DBRowTableIconButton';
712

@@ -53,31 +58,42 @@ const DBRowTableRowButtons: React.FC<DBRowTableRowButtonsProps> = ({
5358
);
5459

5560
const rowData = JSON.stringify(parsedRow, null, 2);
56-
await navigator.clipboard.writeText(rowData);
61+
const copied = await copyTextToClipboard(rowData);
62+
if (!copied) {
63+
notifications.show({
64+
color: 'red',
65+
message: CLIPBOARD_ERROR_MESSAGE,
66+
});
67+
return;
68+
}
5769
setIsCopied(true);
5870
setTimeout(() => setIsCopied(false), 2000);
59-
} catch (error) {
60-
console.error('Failed to copy row data to clipboard:', error);
61-
// Optionally show an error toast notification to the user
71+
} catch {
72+
notifications.show({
73+
color: 'red',
74+
message: CLIPBOARD_ERROR_MESSAGE,
75+
});
6276
}
6377
};
6478

6579
const copyRowUrl = async () => {
66-
try {
67-
const rowWhereResult = getRowWhere(row);
68-
const currentUrl = new URL(window.location.href);
69-
// Add the row identifier as query parameters
70-
currentUrl.searchParams.set('rowWhere', rowWhereResult.where);
71-
if (sourceId) {
72-
currentUrl.searchParams.set('rowSource', sourceId);
73-
}
74-
await navigator.clipboard.writeText(currentUrl.toString());
75-
setIsUrlCopied(true);
76-
setTimeout(() => setIsUrlCopied(false), 2000);
77-
} catch (error) {
78-
console.error('Failed to copy URL to clipboard:', error);
79-
// Optionally show an error toast notification to the user
80+
const rowWhereResult = getRowWhere(row);
81+
const currentUrl = new URL(window.location.href);
82+
// Add the row identifier as query parameters
83+
currentUrl.searchParams.set('rowWhere', rowWhereResult.where);
84+
if (sourceId) {
85+
currentUrl.searchParams.set('rowSource', sourceId);
86+
}
87+
const copied = await copyTextToClipboard(currentUrl.toString());
88+
if (!copied) {
89+
notifications.show({
90+
color: 'red',
91+
message: CLIPBOARD_ERROR_MESSAGE,
92+
});
93+
return;
8094
}
95+
setIsUrlCopied(true);
96+
setTimeout(() => setIsUrlCopied(false), 2000);
8197
};
8298

8399
return (
Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
import { copyTextToClipboard } from '../clipboard';
2+
3+
describe('copyTextToClipboard', () => {
4+
const originalClipboard = navigator.clipboard;
5+
const originalExecCommand = document.execCommand;
6+
7+
afterEach(() => {
8+
Object.defineProperty(navigator, 'clipboard', {
9+
configurable: true,
10+
value: originalClipboard,
11+
});
12+
document.execCommand = originalExecCommand;
13+
document.body.innerHTML = '';
14+
jest.restoreAllMocks();
15+
});
16+
17+
it('uses the Clipboard API when it is available', async () => {
18+
const writeText = jest.fn().mockResolvedValue(undefined);
19+
Object.defineProperty(navigator, 'clipboard', {
20+
configurable: true,
21+
value: { writeText },
22+
});
23+
24+
await expect(copyTextToClipboard('hello')).resolves.toBe(true);
25+
26+
expect(writeText).toHaveBeenCalledWith('hello');
27+
});
28+
29+
it('falls back to a textarea copy when the Clipboard API is unavailable', async () => {
30+
Object.defineProperty(navigator, 'clipboard', {
31+
configurable: true,
32+
value: undefined,
33+
});
34+
document.execCommand = jest.fn().mockReturnValue(true);
35+
const initialChildCount = document.body.childElementCount;
36+
37+
await expect(copyTextToClipboard('fallback text')).resolves.toBe(true);
38+
39+
expect(document.execCommand).toHaveBeenCalledWith('copy');
40+
expect(document.body.childElementCount).toBe(initialChildCount);
41+
});
42+
43+
it('falls back to a textarea copy when the Clipboard API rejects', async () => {
44+
const writeText = jest.fn().mockRejectedValue(new Error('denied'));
45+
Object.defineProperty(navigator, 'clipboard', {
46+
configurable: true,
47+
value: { writeText },
48+
});
49+
document.execCommand = jest.fn().mockReturnValue(true);
50+
51+
await expect(copyTextToClipboard('blocked')).resolves.toBe(true);
52+
53+
expect(writeText).toHaveBeenCalledWith('blocked');
54+
expect(document.execCommand).toHaveBeenCalledWith('copy');
55+
});
56+
57+
it('removes the fallback textarea when execCommand throws', async () => {
58+
Object.defineProperty(navigator, 'clipboard', {
59+
configurable: true,
60+
value: undefined,
61+
});
62+
document.execCommand = jest.fn(() => {
63+
throw new Error('copy failed');
64+
});
65+
const initialChildCount = document.body.childElementCount;
66+
67+
await expect(copyTextToClipboard('throwing copy')).resolves.toBe(false);
68+
69+
expect(document.body.childElementCount).toBe(initialChildCount);
70+
});
71+
72+
it('restores the previous selection after the textarea fallback', async () => {
73+
Object.defineProperty(navigator, 'clipboard', {
74+
configurable: true,
75+
value: undefined,
76+
});
77+
document.execCommand = jest.fn().mockReturnValue(true);
78+
const selectedText = document.createTextNode('selected text');
79+
const container = document.createElement('div');
80+
container.appendChild(selectedText);
81+
document.body.appendChild(container);
82+
const range = document.createRange();
83+
range.selectNodeContents(selectedText);
84+
const selection = document.getSelection();
85+
selection?.removeAllRanges();
86+
selection?.addRange(range);
87+
88+
await expect(copyTextToClipboard('copy text')).resolves.toBe(true);
89+
90+
expect(selection?.rangeCount).toBe(1);
91+
expect(selection?.getRangeAt(0).toString()).toBe('selected text');
92+
});
93+
94+
it('still reports the copy result if selection restoration fails', async () => {
95+
Object.defineProperty(navigator, 'clipboard', {
96+
configurable: true,
97+
value: undefined,
98+
});
99+
document.execCommand = jest.fn().mockReturnValue(true);
100+
const selectedText = document.createTextNode('selected text');
101+
const container = document.createElement('div');
102+
container.appendChild(selectedText);
103+
document.body.appendChild(container);
104+
const range = document.createRange();
105+
range.selectNodeContents(selectedText);
106+
const selection = document.getSelection();
107+
selection?.removeAllRanges();
108+
selection?.addRange(range);
109+
const addRange = jest
110+
.spyOn(selection!, 'addRange')
111+
.mockImplementation(() => {
112+
throw new Error('range detached');
113+
});
114+
115+
await expect(copyTextToClipboard('copy text')).resolves.toBe(true);
116+
117+
expect(addRange).toHaveBeenCalled();
118+
});
119+
120+
it('reports failure when both copy methods are unavailable', async () => {
121+
Object.defineProperty(navigator, 'clipboard', {
122+
configurable: true,
123+
value: undefined,
124+
});
125+
document.execCommand = jest.fn().mockReturnValue(false);
126+
127+
await expect(copyTextToClipboard('nope')).resolves.toBe(false);
128+
129+
expect(document.execCommand).toHaveBeenCalledWith('copy');
130+
});
131+
});

0 commit comments

Comments
 (0)