Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: No context menu item for paste in an input table #2341

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
4 changes: 4 additions & 0 deletions packages/grid/src/Grid.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1552,6 +1552,10 @@ class Grid extends PureComponent<GridProps, GridState> {

const edits: EditOperation[] = [];
ranges.forEach(range => {
if ((range.startColumn ?? 0) + tableWidth > columnCount) {
throw new PasteError('Pasted content would overflow columns.');
}

for (let x = 0; x < tableWidth; x += 1) {
for (let y = 0; y < tableHeight; y += 1) {
edits.push({
Expand Down
6 changes: 3 additions & 3 deletions packages/grid/src/key-handlers/PasteKeyHandler.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,13 +66,13 @@ describe('table parsing', () => {

const TEXT_TABLE_FIREFOX = (
<>
A&nbsp;&nbsp; &nbsp;B&nbsp;&nbsp; &nbsp;C
A&nbsp;&nbsp;&nbsp; B&nbsp;&nbsp;&nbsp; C
<br />
1&nbsp;&nbsp; &nbsp;2&nbsp;&nbsp; &nbsp;3
1&nbsp;&nbsp;&nbsp; 2&nbsp;&nbsp;&nbsp; 3
</>
);

const SINGLE_ROW_FIREFOX = <>A&nbsp;&nbsp; &nbsp;B&nbsp;&nbsp; &nbsp;C</>;
const SINGLE_ROW_FIREFOX = <>A&nbsp;&nbsp;&nbsp; B&nbsp;&nbsp;&nbsp; C</>;

function testTable(jsx: JSX.Element, expectedValue: string[][]) {
const element = makeElementFromJsx(jsx);
Expand Down
5 changes: 2 additions & 3 deletions packages/grid/src/key-handlers/PasteKeyHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,9 @@ export function parseValueFromNodes(nodes: NodeListOf<ChildNode>): string[][] {
if (text.length > 0) {
// When Chrome pastes a table from text, it preserves the tab characters
// In Firefox, it breaks it into a combination of non-breaking spaces and spaces
result.push(text.split(/\t|\u00a0\u00a0 \u00a0/));
result.push(text.split(/\t|\u00a0\u00a0\u00a0 /));
}
});

return result;
}

Expand All @@ -62,7 +61,7 @@ export function parseValueFromElement(
// If there's only one row and it doesn't contain a tab, then just treat it as a regular value
const { childNodes } = element;
const hasTabChar = text.includes('\t');
const hasFirefoxTab = text.includes('\u00a0\u00a0 \u00a0');
const hasFirefoxTab = text.includes('\u00a0\u00a0\u00a0 ');
if (
hasTabChar &&
childNodes.length !== 0 &&
Expand Down
27 changes: 27 additions & 0 deletions packages/iris-grid/src/IrisGrid.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,7 @@ import {
import type ColumnHeaderGroup from './ColumnHeaderGroup';
import { IrisGridThemeContext } from './IrisGridThemeProvider';
import { isMissingPartitionError } from './MissingPartitionError';
import { NoPastePermissionModal } from './NoPastePermissionModal';

const log = Log.module('IrisGrid');

Expand Down Expand Up @@ -442,6 +443,8 @@ export interface IrisGridState {
toastMessage: JSX.Element | null;
frozenColumns: readonly ColumnName[];
showOverflowModal: boolean;
showNoPastePermissionModal: boolean;
noPastePermissionError: string;
overflowText: string;
overflowButtonTooltipProps: CSSProperties | null;
expandCellTooltipProps: CSSProperties | null;
Expand Down Expand Up @@ -624,6 +627,8 @@ class IrisGrid extends Component<IrisGridProps, IrisGridState> {
this.handleCrossColumnSearch = this.handleCrossColumnSearch.bind(this);
this.handleRollupChange = this.handleRollupChange.bind(this);
this.handleOverflowClose = this.handleOverflowClose.bind(this);
this.handleCloseNoPastePermissionModal =
this.handleCloseNoPastePermissionModal.bind(this);
this.getColumnBoundingRect = this.getColumnBoundingRect.bind(this);
this.handleGotoRowSelectedRowNumberChanged =
this.handleGotoRowSelectedRowNumberChanged.bind(this);
Expand Down Expand Up @@ -870,6 +875,8 @@ class IrisGrid extends Component<IrisGridProps, IrisGridState> {
toastMessage: null,
frozenColumns,
showOverflowModal: false,
showNoPastePermissionModal: false,
noPastePermissionError: '',
overflowText: '',
overflowButtonTooltipProps: null,
expandCellTooltipProps: null,
Expand Down Expand Up @@ -3853,6 +3860,19 @@ class IrisGrid extends Component<IrisGridProps, IrisGridState> {
});
}

handleOpenNoPastePermissionModal(errorMessage: string): void {
this.setState({
showNoPastePermissionModal: true,
noPastePermissionError: errorMessage,
});
}

handleCloseNoPastePermissionModal(): void {
this.setState({
showNoPastePermissionModal: false,
});
}

getColumnBoundingRect(): DOMRect {
const { metrics, shownColumnTooltip } = this.state;
assertNotNull(metrics);
Expand Down Expand Up @@ -4273,6 +4293,8 @@ class IrisGrid extends Component<IrisGridProps, IrisGridState> {
frozenColumns,
columnHeaderGroups,
showOverflowModal,
showNoPastePermissionModal,
noPastePermissionError,
overflowText,
overflowButtonTooltipProps,
expandCellTooltipProps,
Expand Down Expand Up @@ -4998,6 +5020,11 @@ class IrisGrid extends Component<IrisGridProps, IrisGridState> {
</div>
</SlideTransition>
<ContextActions actions={this.contextActions} />
<NoPastePermissionModal
isOpen={showNoPastePermissionModal}
onClose={this.handleCloseNoPastePermissionModal}
errorMessage={noPastePermissionError}
/>
</div>
);
}
Expand Down
36 changes: 36 additions & 0 deletions packages/iris-grid/src/NoPastePermissionModal.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import {
Button,
GLOBAL_SHORTCUTS,
Modal,
ModalBody,
ModalFooter,
ModalHeader,
} from '@deephaven/components';

export type NoPastePermissionModalProps = {
isOpen: boolean;
onClose: () => void;
errorMessage: string;
};

export function NoPastePermissionModal({
isOpen,
onClose,
errorMessage,
}: NoPastePermissionModalProps): JSX.Element {
const pasteShortcutText = GLOBAL_SHORTCUTS.PASTE.getDisplayText();
return (
<Modal isOpen={isOpen} toggle={onClose} centered>
<ModalHeader closeButton={false}>No Paste Permission</ModalHeader>
<ModalBody>
<p>{errorMessage}</p>
<p>You can still use {pasteShortcutText} to paste.</p>
</ModalBody>
<ModalFooter>
<Button kind="primary" onClick={onClose}>
Dismiss
</Button>
</ModalFooter>
</Modal>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,14 @@ import {
import Log from '@deephaven/log';
import type { DebouncedFunc } from 'lodash';
import {
ClipboardPermissionsDeniedError,
ClipboardUnavailableError,
TextUtils,
assertNotEmpty,
assertNotNaN,
assertNotNull,
copyToClipboard,
readFromClipboard,
} from '@deephaven/utils';
import {
DateTimeFormatContextMenu,
Expand Down Expand Up @@ -477,6 +480,31 @@ class IrisGridContextMenuHandler extends GridMouseHandler {
});
}

actions.push({
title: 'Paste',
group: IrisGridContextMenuHandler.GROUP_COPY,
order: 50,
action: async () => {
try {
const text = await readFromClipboard();
const items = text.split('\n').map(row => row.split('\t'));
ericlln marked this conversation as resolved.
Show resolved Hide resolved
await grid.pasteValue(items);
} catch (err) {
if (err instanceof ClipboardUnavailableError) {
irisGrid.handleOpenNoPastePermissionModal(
'For security reasons your browser does not allow access to your clipboard on click.'
);
} else if (err instanceof ClipboardPermissionsDeniedError) {
irisGrid.handleOpenNoPastePermissionModal(
'Requested clipboard permissions have not been granted, please grant them and try again.'
);
} else {
throw err;
}
}
},
});

actions.push({
title: 'View Cell Contents',
group: IrisGridContextMenuHandler.GROUP_VIEW_CONTENTS,
Expand Down
120 changes: 119 additions & 1 deletion packages/utils/src/ClipboardUtils.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,16 @@
import { copyToClipboard } from './ClipboardUtils';
import { copyToClipboard, readFromClipboard } from './ClipboardUtils';
import {
ClipboardPermissionsDeniedError,
ClipboardUnavailableError,
} from './errors';
import { checkPermission } from './PermissionUtils';

document.execCommand = jest.fn();

jest.mock('./PermissionUtils', () => ({
checkPermission: jest.fn(),
}));

describe('Clipboard', () => {
describe('writeText', () => {
beforeEach(() => jest.resetAllMocks());
Expand Down Expand Up @@ -55,4 +64,113 @@ describe('Clipboard', () => {
await expect(document.execCommand).toHaveBeenCalledWith('copy');
});
});

describe('readFromClipboard', () => {
beforeEach(() => jest.resetAllMocks());

it('should throw unavailable error if clipboard is undefined', async () => {
Object.assign(navigator, {
clipboard: undefined,
});

await expect(readFromClipboard()).rejects.toThrow(
ClipboardUnavailableError
);
});

it('should throw unavailable error if PermissionState is null', async () => {
(checkPermission as jest.Mock).mockResolvedValue(null);

await expect(readFromClipboard()).rejects.toThrow(
ClipboardUnavailableError
);
});

it('should return text if PermissionState is granted', async () => {
Object.assign(navigator, {
clipboard: {
readText: jest.fn().mockResolvedValueOnce('text from clipboard'),
},
});

(checkPermission as jest.Mock).mockResolvedValueOnce('granted');

await expect(readFromClipboard()).resolves.toBe('text from clipboard');
});

it('should throw denied error if PermissionState is denied', async () => {
Object.assign(navigator, {
clipboard: {
readText: jest.fn(),
},
});

(checkPermission as jest.Mock).mockResolvedValue('denied');

await expect(readFromClipboard()).rejects.toThrow(
ClipboardPermissionsDeniedError
);
});

it('should return text if permission prompt accepted', async () => {
const mockClipboard = {
readText: jest
.fn()
.mockRejectedValueOnce(new Error('Missing permission'))
.mockResolvedValueOnce('text from clipboard'),
};

Object.assign(navigator, {
clipboard: mockClipboard,
});

(checkPermission as jest.Mock)
.mockResolvedValueOnce('prompt')
.mockResolvedValue('granted');

await expect(readFromClipboard()).resolves.toBe('text from clipboard');
expect(checkPermission).toHaveBeenCalledTimes(2);
expect(mockClipboard.readText).toHaveBeenCalledTimes(2);
});

it('should throw denied error if permission prompt denied', async () => {
const mockClipboard = {
readText: jest
.fn()
.mockRejectedValueOnce(new Error('Missing permission')),
};

Object.assign(navigator, {
clipboard: mockClipboard,
});

(checkPermission as jest.Mock)
.mockResolvedValueOnce('prompt')
.mockResolvedValue('denied');

await expect(readFromClipboard()).rejects.toThrow(
ClipboardPermissionsDeniedError
);
expect(checkPermission).toHaveBeenCalledTimes(2);
expect(mockClipboard.readText).toHaveBeenCalledTimes(1);
});

it('should throw denied error if permission prompt closed', async () => {
const mockClipboard = {
readText: jest.fn().mockRejectedValue(new Error('Missing permission')),
};

Object.assign(navigator, {
clipboard: mockClipboard,
});

(checkPermission as jest.Mock).mockResolvedValue('prompt');

await expect(readFromClipboard()).rejects.toThrow(
ClipboardPermissionsDeniedError
);
expect(checkPermission).toHaveBeenCalledTimes(2);
expect(mockClipboard.readText).toHaveBeenCalledTimes(1);
});
});
});
Loading
Loading