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
6 changes: 6 additions & 0 deletions .changeset/clipboard-copy-fallback.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
---
'@hyperdx/app': patch
---

Fall back when the browser Clipboard API is unavailable and show a clear error
if copying still fails.
37 changes: 31 additions & 6 deletions packages/app/src/components/DBRowJsonViewer.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -29,6 +29,10 @@ import {

import HyperJson, { GetLineActions, LineAction } from '@/components/HyperJson';
import { mergePath } from '@/utils';
import {
CLIPBOARD_ERROR_MESSAGE,
copyTextToClipboard,
} from '@/utils/clipboard';

type JSONExtractFn =
| 'JSONExtractString'
Expand DownExpand Up@@ -219,12 +223,19 @@ function HyperJsonMenu({ rowData }: { rowData: any }) {
<Group>
{rowData != null && (
<UnstyledButton
onClick={() => {
window.navigator.clipboard.writeText(
onClick={async () => {
const copied = await copyTextToClipboard(
typeof rowData === 'string'
? rowData
: JSON.stringify(rowData, null, 2),
);
if (!copied) {
notifications.show({
color: 'red',
message: CLIPBOARD_ERROR_MESSAGE,
});
return;
}
notifications.show({
color: 'green',
message: `Value copied to clipboard`,
Expand DownExpand Up@@ -547,7 +558,7 @@ export function DBRowJsonViewer({
});
}

const handleCopyObject = () => {
const handleCopyObject = async () => {
let copiedObj;

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

window.navigator.clipboard.writeText(
const copied = await copyTextToClipboard(
JSON.stringify(copiedObj, null, 2),
);
if (!copied) {
notifications.show({
color: 'red',
message: CLIPBOARD_ERROR_MESSAGE,
});
return;
}
notifications.show({
color: 'green',
message: `Copied object to clipboard`,
Expand All@@ -583,12 +601,19 @@ export function DBRowJsonViewer({
Copy Value
</Group>
),
onClick: () => {
window.navigator.clipboard.writeText(
onClick: async () => {
const copied = await copyTextToClipboard(
typeof value === 'string'
? value
: JSON.stringify(value, null, 2),
);
if (!copied) {
notifications.show({
color: 'red',
message: CLIPBOARD_ERROR_MESSAGE,
});
return;
}
notifications.show({
color: 'green',
message: `Value copied to clipboard`,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,8 +2,14 @@ import React, { useContext, useEffect, useRef, useState } from 'react';
import cx from 'classnames';
import { Popover } from '@mantine/core';
import { useDisclosure } from '@mantine/hooks';
import { notifications } from '@mantine/notifications';
import { IconCopy, IconFilter, IconFilterX } from '@tabler/icons-react';

import {
CLIPBOARD_ERROR_MESSAGE,
copyTextToClipboard,
} from '@/utils/clipboard';

import { RowSidePanelContext } from '../DBRowSidePanel';

import { DBRowTableIconButton } from './DBRowTableIconButton';
Expand DownExpand Up@@ -83,16 +89,18 @@ const DBRowTableFieldWithPopover = ({
};

const copyFieldValue = async () => {
try {
const value =
typeof cellValue === 'string' ? cellValue : String(cellValue ?? '');
await navigator.clipboard.writeText(value);
setIsCopied(true);
setTimeout(() => setIsCopied(false), 2000);
} catch (error) {
console.error('Failed to copy to clipboard:', error);
// Optionally show an error toast notification to the user
const value =
typeof cellValue === 'string' ? cellValue : String(cellValue ?? '');
const copied = await copyTextToClipboard(value);
if (!copied) {
notifications.show({
color: 'red',
message: CLIPBOARD_ERROR_MESSAGE,
});
return;
}
setIsCopied(true);
setTimeout(() => setIsCopied(false), 2000);
};

const addFilter = () => {
Expand Down
52 changes: 34 additions & 18 deletions packages/app/src/components/DBTable/DBRowTableRowButtons.tsx
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
import React, { useState } from 'react';
import { notifications } from '@mantine/notifications';
import { IconCopy, IconLink, IconTextWrap } from '@tabler/icons-react';

import { INTERNAL_ROW_FIELDS, RowWhereResult } from '@/hooks/useRowWhere';
import {
CLIPBOARD_ERROR_MESSAGE,
copyTextToClipboard,
} from '@/utils/clipboard';

import { DBRowTableIconButton } from './DBRowTableIconButton';

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

const rowData = JSON.stringify(parsedRow, null, 2);
await navigator.clipboard.writeText(rowData);
const copied = await copyTextToClipboard(rowData);
if (!copied) {
notifications.show({
color: 'red',
message: CLIPBOARD_ERROR_MESSAGE,
});
return;
}
setIsCopied(true);
setTimeout(() => setIsCopied(false), 2000);
} catch (error) {
console.error('Failed to copy row data to clipboard:', error);
// Optionally show an error toast notification to the user
} catch {
notifications.show({
color: 'red',
message: CLIPBOARD_ERROR_MESSAGE,
});
}
};

const copyRowUrl = async () => {
try {
const rowWhereResult = getRowWhere(row);
const currentUrl = new URL(window.location.href);
// Add the row identifier as query parameters
currentUrl.searchParams.set('rowWhere', rowWhereResult.where);
if (sourceId) {
currentUrl.searchParams.set('rowSource', sourceId);
}
await navigator.clipboard.writeText(currentUrl.toString());
setIsUrlCopied(true);
setTimeout(() => setIsUrlCopied(false), 2000);
} catch (error) {
console.error('Failed to copy URL to clipboard:', error);
// Optionally show an error toast notification to the user
const rowWhereResult = getRowWhere(row);
const currentUrl = new URL(window.location.href);
// Add the row identifier as query parameters
currentUrl.searchParams.set('rowWhere', rowWhereResult.where);
if (sourceId) {
currentUrl.searchParams.set('rowSource', sourceId);
}
const copied = await copyTextToClipboard(currentUrl.toString());
if (!copied) {
notifications.show({
color: 'red',
message: CLIPBOARD_ERROR_MESSAGE,
});
return;
}
setIsUrlCopied(true);
setTimeout(() => setIsUrlCopied(false), 2000);
};

return (
Expand Down
131 changes: 131 additions & 0 deletions packages/app/src/utils/__tests__/clipboard.test.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
import { copyTextToClipboard } from '../clipboard';

describe('copyTextToClipboard', () => {
const originalClipboard = navigator.clipboard;
const originalExecCommand = document.execCommand;

afterEach(() => {
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: originalClipboard,
});
document.execCommand = originalExecCommand;
document.body.innerHTML = '';
jest.restoreAllMocks();
});

it('uses the Clipboard API when it is available', async () => {
const writeText = jest.fn().mockResolvedValue(undefined);
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: { writeText },
});

await expect(copyTextToClipboard('hello')).resolves.toBe(true);

expect(writeText).toHaveBeenCalledWith('hello');
});

it('falls back to a textarea copy when the Clipboard API is unavailable', async () => {
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: undefined,
});
document.execCommand = jest.fn().mockReturnValue(true);
const initialChildCount = document.body.childElementCount;

await expect(copyTextToClipboard('fallback text')).resolves.toBe(true);

expect(document.execCommand).toHaveBeenCalledWith('copy');
expect(document.body.childElementCount).toBe(initialChildCount);
});

it('falls back to a textarea copy when the Clipboard API rejects', async () => {
const writeText = jest.fn().mockRejectedValue(new Error('denied'));
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: { writeText },
});
document.execCommand = jest.fn().mockReturnValue(true);

await expect(copyTextToClipboard('blocked')).resolves.toBe(true);

expect(writeText).toHaveBeenCalledWith('blocked');
expect(document.execCommand).toHaveBeenCalledWith('copy');
});

it('removes the fallback textarea when execCommand throws', async () => {
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: undefined,
});
document.execCommand = jest.fn(() => {
throw new Error('copy failed');
});
const initialChildCount = document.body.childElementCount;

await expect(copyTextToClipboard('throwing copy')).resolves.toBe(false);

expect(document.body.childElementCount).toBe(initialChildCount);
});

it('restores the previous selection after the textarea fallback', async () => {
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: undefined,
});
document.execCommand = jest.fn().mockReturnValue(true);
const selectedText = document.createTextNode('selected text');
const container = document.createElement('div');
container.appendChild(selectedText);
document.body.appendChild(container);
const range = document.createRange();
range.selectNodeContents(selectedText);
const selection = document.getSelection();
selection?.removeAllRanges();
selection?.addRange(range);

await expect(copyTextToClipboard('copy text')).resolves.toBe(true);

expect(selection?.rangeCount).toBe(1);
expect(selection?.getRangeAt(0).toString()).toBe('selected text');
});

it('still reports the copy result if selection restoration fails', async () => {
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: undefined,
});
document.execCommand = jest.fn().mockReturnValue(true);
const selectedText = document.createTextNode('selected text');
const container = document.createElement('div');
container.appendChild(selectedText);
document.body.appendChild(container);
const range = document.createRange();
range.selectNodeContents(selectedText);
const selection = document.getSelection();
selection?.removeAllRanges();
selection?.addRange(range);
const addRange = jest
.spyOn(selection!, 'addRange')
.mockImplementation(() => {
throw new Error('range detached');
});

await expect(copyTextToClipboard('copy text')).resolves.toBe(true);

expect(addRange).toHaveBeenCalled();
});

it('reports failure when both copy methods are unavailable', async () => {
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: undefined,
});
document.execCommand = jest.fn().mockReturnValue(false);

await expect(copyTextToClipboard('nope')).resolves.toBe(false);

expect(document.execCommand).toHaveBeenCalledWith('copy');
});
});
Loading
Loading