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

Implementation of Cell Copy/Paste Events Using Clipboard Events #3462

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -186,10 +186,6 @@ A number defining the height of summary rows.

###### `onFill?: Maybe<(event: FillEvent<R>) => R>`

###### `onCopy?: Maybe<(event: CopyEvent<R>) => void>`

###### `onPaste?: Maybe<(event: PasteEvent<R>) => R>`

###### `onCellClick?: Maybe<(args: CellClickArgs<R, SR>, event: CellMouseEvent) => void>`

###### `onCellDoubleClick?: Maybe<(args: CellClickArgs<R, SR>, event: CellMouseEvent) => void>`
Expand All @@ -198,6 +194,10 @@ A number defining the height of summary rows.

###### `onCellKeyDown?: Maybe<(args: CellKeyDownArgs<R, SR>, event: CellKeyboardEvent) => void>`

###### `onCopy?: Maybe<(args: CellCopyArgs<R>, event: CellClipboardEvent) => void>`

###### `onPaste?: Maybe<(args: CellPasteArgs<R>, event: CellClipboardEvent) => R>`
Copy link
Author

@naoki-tateyama naoki-tateyama Feb 24, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are two things to consider.

  • It might be more appropriate to name each handler onCellCopy/onCellPaste
  • onPaste might not need to return R.

However, above changes will be breaking changes for some developers.
I leave them as they are without making any changes for now.


###### `onSelectedCellChange?: Maybe<(args: CellSelectArgs<R, SR>) => void>;`

Triggered when the selected cell is changed.
Expand Down
71 changes: 34 additions & 37 deletions src/DataGrid.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,18 +31,19 @@ import {
import type {
CalculatedColumn,
CellClickArgs,
CellClipboardEvent,
CellCopyArgs,
CellKeyboardEvent,
CellKeyDownArgs,
CellMouseEvent,
CellNavigationMode,
CellPasteArgs,
CellSelectArgs,
Column,
ColumnOrColumnGroup,
CopyEvent,
Direction,
FillEvent,
Maybe,
PasteEvent,
Position,
Renderers,
RowsChangeData,
Expand Down Expand Up @@ -154,8 +155,6 @@ export interface DataGridProps<R, SR = unknown, K extends Key = Key> extends Sha
onSortColumnsChange?: Maybe<(sortColumns: SortColumn[]) => void>;
defaultColumnOptions?: Maybe<DefaultColumnOptions<R, SR>>;
onFill?: Maybe<(event: FillEvent<R>) => R>;
onCopy?: Maybe<(event: CopyEvent<R>) => void>;
onPaste?: Maybe<(event: PasteEvent<R>) => R>;

/**
* Event props
Expand All @@ -167,6 +166,10 @@ export interface DataGridProps<R, SR = unknown, K extends Key = Key> extends Sha
/** Function called whenever a cell is right clicked */
onCellContextMenu?: Maybe<(args: CellClickArgs<R, SR>, event: CellMouseEvent) => void>;
onCellKeyDown?: Maybe<(args: CellKeyDownArgs<R, SR>, event: CellKeyboardEvent) => void>;
/** Function called whenever a copy event occurs on a cell */
onCopy?: Maybe<(args: CellCopyArgs<R>, event: CellClipboardEvent) => void>;
/** Function called whenever a paste event occurs on a cell */
onPaste?: Maybe<(args: CellPasteArgs<R>, event: CellClipboardEvent) => R>;
/** Function called whenever cell selection is changed */
onSelectedCellChange?: Maybe<(args: CellSelectArgs<R, SR>) => void>;
/** Called when the grid is scrolled */
Expand Down Expand Up @@ -547,29 +550,6 @@ function DataGrid<R, SR, K extends Key>(
const isRowEvent = isTreeGrid && event.target === focusSinkRef.current;
if (!isCellEvent && !isRowEvent) return;

const { keyCode } = event;

if (
selectedCellIsWithinViewportBounds &&
(onPaste != null || onCopy != null) &&
isCtrlKeyHeldDown(event)
) {
// event.key may differ by keyboard input language, so we use event.keyCode instead
// event.nativeEvent.code cannot be used either as it would break copy/paste for the DVORAK layout
const cKey = 67;
const vKey = 86;
if (keyCode === cKey) {
// copy highlighted text only
if (window.getSelection()?.isCollapsed === false) return;
handleCopy();
return;
}
if (keyCode === vKey) {
handlePaste();
return;
}
}

switch (event.key) {
case 'Escape':
setCopiedCell(null);
Expand Down Expand Up @@ -617,29 +597,44 @@ function DataGrid<R, SR, K extends Key>(
updateRow(columns[selectedPosition.idx], selectedPosition.rowIdx, selectedPosition.row);
}

function handleCopy() {
function handleCopy(event: React.ClipboardEvent<HTMLDivElement>) {
if ((!onPaste && !onCopy) || !selectedCellIsWithinViewportBounds) return;
const { idx, rowIdx } = selectedPosition;
const sourceRow = rows[rowIdx];
const sourceColumnKey = columns[idx].key;
const cellEvent = createCellEvent(event);
onCopy?.({ sourceRow, sourceColumnKey }, cellEvent);
if (cellEvent.isGridDefaultPrevented()) return;

setCopiedCell({ row: sourceRow, columnKey: sourceColumnKey });
Comment on lines +607 to 609
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if developers use event.preventGridDefault() in onCopy handler, the default behavior to set the copied cell internally would be prevented.

onCopy?.({ sourceRow, sourceColumnKey });
}

function handlePaste() {
if (!onPaste || !onRowsChange || copiedCell === null || !isCellEditable(selectedPosition)) {
function handlePaste(event: React.ClipboardEvent<HTMLDivElement>) {
if (
!onPaste ||
!onRowsChange ||
copiedCell === null ||
!isCellEditable(selectedPosition) ||
!selectedCellIsWithinViewportBounds
) {
return;
}

const { idx, rowIdx } = selectedPosition;
const targetColumn = columns[idx];
const targetRow = rows[rowIdx];

const updatedTargetRow = onPaste({
sourceRow: copiedCell.row,
sourceColumnKey: copiedCell.columnKey,
targetRow,
targetColumnKey: targetColumn.key
});
const cellEvent = createCellEvent(event);
const updatedTargetRow = onPaste(
{
sourceRow: copiedCell.row,
sourceColumnKey: copiedCell.columnKey,
targetRow,
targetColumnKey: targetColumn.key
},
cellEvent
);
if (cellEvent.isGridDefaultPrevented()) return;

updateRow(targetColumn, rowIdx, updatedTargetRow);
Comment on lines +637 to 639
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if developers use event.preventGridDefault() in onPaste handler, the default behavior to update the row would be prevented.

}
Expand Down Expand Up @@ -1076,6 +1071,8 @@ function DataGrid<R, SR, K extends Key>(
ref={gridRef}
onScroll={handleScroll}
onKeyDown={handleKeyDown}
onCopy={handleCopy}
onPaste={handlePaste}
data-testid={testId}
>
<DataGridDefaultRenderersProvider value={defaultGridComponents}>
Expand Down
26 changes: 14 additions & 12 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,8 @@ export type CellMouseEvent = CellEvent<React.MouseEvent<HTMLDivElement>>;

export type CellKeyboardEvent = CellEvent<React.KeyboardEvent<HTMLDivElement>>;

export type CellClipboardEvent = CellEvent<React.ClipboardEvent<HTMLDivElement>>;

export interface CellClickArgs<TRow, TSummaryRow = unknown> {
row: TRow;
column: CalculatedColumn<TRow, TSummaryRow>;
Expand Down Expand Up @@ -193,6 +195,18 @@ export type CellKeyDownArgs<TRow, TSummaryRow = unknown> =
| SelectCellKeyDownArgs<TRow, TSummaryRow>
| EditCellKeyDownArgs<TRow, TSummaryRow>;

export interface CellCopyArgs<TRow> {
sourceColumnKey: string;
sourceRow: TRow;
}

export interface CellPasteArgs<TRow> {
sourceColumnKey: string;
sourceRow: TRow;
targetColumnKey: string;
targetRow: TRow;
}

export interface CellSelectArgs<TRow, TSummaryRow = unknown> {
rowIdx: number;
row: TRow;
Expand Down Expand Up @@ -241,18 +255,6 @@ export interface FillEvent<TRow> {
targetRow: TRow;
}

export interface CopyEvent<TRow> {
sourceColumnKey: string;
sourceRow: TRow;
}

export interface PasteEvent<TRow> {
sourceColumnKey: string;
sourceRow: TRow;
targetColumnKey: string;
targetRow: TRow;
}

export interface GroupRow<TRow> {
readonly childRows: readonly TRow[];
readonly id: string;
Expand Down
4 changes: 2 additions & 2 deletions test/copyPaste.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ test('should allow copy if only onCopy is specified', async () => {
await userEvent.click(getCellsAtRowIndex(0)[0]);
copySelectedCell();
expect(getSelectedCell()).toHaveClass(copyCellClassName);
expect(onCopySpy).toHaveBeenCalledWith({
expect(onCopySpy.mock.calls[0][0]).toStrictEqual({
sourceRow: initialRows[0],
sourceColumnKey: 'col'
});
Expand All @@ -127,7 +127,7 @@ test('should allow copy/paste if both onPaste & onCopy is specified', async () =
await userEvent.click(getCellsAtRowIndex(0)[0]);
copySelectedCell();
expect(getSelectedCell()).toHaveClass(copyCellClassName);
expect(onCopySpy).toHaveBeenCalledWith({
expect(onCopySpy.mock.calls[0][0]).toStrictEqual({
sourceRow: initialRows[0],
sourceColumnKey: 'col'
});
Expand Down
11 changes: 2 additions & 9 deletions test/utils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -68,19 +68,12 @@ export function validateCellPosition(columnIdx: number, rowIdx: number) {
}

export function copySelectedCell() {
// eslint-disable-next-line testing-library/prefer-user-event
fireEvent.keyDown(document.activeElement!, {
keyCode: '67',
ctrlKey: true
});
fireEvent.copy(document.activeElement!);
}

export function pasteSelectedCell() {
// eslint-disable-next-line testing-library/prefer-user-event
fireEvent.keyDown(document.activeElement!, {
keyCode: '86',
ctrlKey: true
});
fireEvent.paste(document.activeElement!);
}

export async function scrollGrid({
Expand Down
11 changes: 7 additions & 4 deletions website/demos/AllFeatures.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { css } from '@linaria/core';

import DataGrid, { SelectColumn, textEditor } from '../../src';
import type { Column, CopyEvent, FillEvent, PasteEvent } from '../../src';
import { type CellClipboardEvent } from '../../src/types';
import { renderAvatar, renderDropdown } from './renderers';
import type { Props } from './types';

Expand Down Expand Up @@ -189,10 +190,12 @@ export default function AllFeatures({ direction }: Props) {
return { ...targetRow, [targetColumnKey]: sourceRow[sourceColumnKey as keyof Row] };
}

function handleCopy({ sourceRow, sourceColumnKey }: CopyEvent<Row>): void {
if (window.isSecureContext) {
navigator.clipboard.writeText(sourceRow[sourceColumnKey as keyof Row]);
}
function handleCopy(
{ sourceRow, sourceColumnKey }: CopyEvent<Row>,
event: CellClipboardEvent
): void {
event.preventDefault();
event.clipboardData.setData('text/plain', sourceRow[sourceColumnKey as keyof Row]);
}

return (
Expand Down