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

feat: add onBeforePasteCell event to excel copy buffer #1298

Merged
merged 6 commits into from
Jan 4, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import 'jest-extended';

import { SelectionModel } from '../../enums/index';
import type { Column, GridOption, } from '../../interfaces/index';
import type { Column, GridOption, OnEventArgs, } from '../../interfaces/index';
import { SlickCellSelectionModel } from '../slickCellSelectionModel';
import { SlickCellExternalCopyManager } from '../slickCellExternalCopyManager';
import { InputEditor } from '../../editors/inputEditor';
Expand Down Expand Up @@ -331,6 +331,46 @@ describe('CellExternalCopyManager', () => {
}, 2);
});

it('should not paste on cells where onBeforePasteCell handler returns false', (done) => {
let clipCommand;
const clipboardCommandHandler = (cmd) => {
clipCommand = cmd;
cmd.execute();
};
jest.spyOn(gridStub.getSelectionModel() as SelectionModel, 'getSelectedRanges').mockReturnValueOnce([new SlickRange(0, 1, 1, 2)]).mockReturnValueOnce(null as any);
plugin.init(gridStub, { clipboardPasteDelay: 1, clearCopySelectionDelay: 1, includeHeaderWhenCopying: true, clipboardCommandHandler, onBeforePasteCell: (e: SlickEventData, args: OnEventArgs) => args.cell > 0 });

const keyDownCtrlCopyEvent = new Event('keydown');
Object.defineProperty(keyDownCtrlCopyEvent, 'ctrlKey', { writable: true, configurable: true, value: true });
Object.defineProperty(keyDownCtrlCopyEvent, 'key', { writable: true, configurable: true, value: 'c' });
Object.defineProperty(keyDownCtrlCopyEvent, 'isPropagationStopped', { writable: true, configurable: true, value: jest.fn() });
Object.defineProperty(keyDownCtrlCopyEvent, 'isImmediatePropagationStopped', { writable: true, configurable: true, value: jest.fn() });
gridStub.onKeyDown.notify({ cell: 0, row: 0, grid: gridStub }, keyDownCtrlCopyEvent, gridStub);

const updateCellSpy = jest.spyOn(gridStub, 'updateCell');
const onCellChangeSpy = jest.spyOn(gridStub.onCellChange, 'notify');
const getActiveCellSpy = jest.spyOn(gridStub, 'getActiveCell').mockReturnValue({ cell: 0, row: 1 });
const keyDownCtrlPasteEvent = new Event('keydown');
jest.spyOn(gridStub, 'getColumns').mockReturnValue(mockColumns);
Object.defineProperty(keyDownCtrlPasteEvent, 'ctrlKey', { writable: true, configurable: true, value: true });
Object.defineProperty(keyDownCtrlPasteEvent, 'key', { writable: true, configurable: true, value: 'v' });
Object.defineProperty(keyDownCtrlPasteEvent, 'isPropagationStopped', { writable: true, configurable: true, value: jest.fn() });
Object.defineProperty(keyDownCtrlPasteEvent, 'isImmediatePropagationStopped', { writable: true, configurable: true, value: jest.fn() });
gridStub.onKeyDown.notify({ cell: 0, row: 0, grid: gridStub }, keyDownCtrlPasteEvent, gridStub);
document.querySelector('textarea')!.value = `Doe\tserialized output`;

setTimeout(() => {
expect(getActiveCellSpy).toHaveBeenCalled();
expect(updateCellSpy).not.toHaveBeenCalledWith(1, 0);
expect(updateCellSpy).toHaveBeenCalledWith(1, 1);
expect(onCellChangeSpy).toHaveBeenCalledWith({ row: 1, cell: 1, item: { firstName: 'John', lastName: 'serialized output' }, grid: gridStub, column: {} });
const getDataItemSpy = jest.spyOn(gridStub, 'getDataItem');
clipCommand.undo();
expect(getDataItemSpy).toHaveBeenCalled();
done();
}, 2);
});

it('should Copy, Paste and run Execute clip command with only 1 cell to copy', (done) => {
jest.spyOn(gridStub.getSelectionModel() as SelectionModel, 'getSelectedRanges').mockReturnValueOnce([new SlickRange(0, 1, 1, 2)]).mockReturnValueOnce([new SlickRange(0, 1, 1, 2)]);
let clipCommand;
Expand Down
36 changes: 34 additions & 2 deletions packages/common/src/extensions/slickCellExternalCopyManager.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { createDomElement, stripTags } from '@slickgrid-universal/utils';

import type { Column, ExcelCopyBufferOption, ExternalCopyClipCommand } from '../interfaces/index';
import { SlickEvent, SlickEventData, SlickEventHandler, type SlickGrid, SlickRange } from '../core/index';
import type { Column, ExcelCopyBufferOption, ExternalCopyClipCommand, OnEventArgs } from '../interfaces/index';
import { SlickEvent, SlickEventData, SlickEventHandler, type SlickGrid, SlickRange, SlickDataView } from '../core/index';

// using external SlickGrid JS libraries
const CLEAR_COPY_SELECTION_DELAY = 2000;
Expand All @@ -20,6 +20,7 @@ export class SlickCellExternalCopyManager {
onCopyCells = new SlickEvent<{ ranges: SlickRange[]; }>();
onCopyCancelled = new SlickEvent<{ ranges: SlickRange[]; }>();
onPasteCells = new SlickEvent<{ ranges: SlickRange[]; }>();
onBeforePasteCell = new SlickEvent<{ cell: number; row: number; item: any; columnDef: Column; value: any; }>();
ghiscoding marked this conversation as resolved.
Show resolved Hide resolved

protected _addonOptions!: ExcelCopyBufferOption;
protected _bodyElement = document.body;
Expand Down Expand Up @@ -68,6 +69,26 @@ export class SlickCellExternalCopyManager {
this._grid.focus();
}
});

if (typeof this._addonOptions?.onBeforePasteCell === 'function') {
const dataView = grid?.getData<SlickDataView>();
ghiscoding marked this conversation as resolved.
Show resolved Hide resolved

// subscribe to this Slickgrid event of onBeforeEditCell
this._eventHandler.subscribe(this.onBeforePasteCell, (e, args) => {
const column: Column = grid.getColumns()[args.cell];
const returnedArgs: OnEventArgs = {
row: args.row!,
cell: args.cell,
dataView,
grid,
columnDef: column,
dataContext: grid.getDataItem(args.row!)
};

// finally call up the Slick column.onBeforeEditCells.... function
return this._addonOptions.onBeforePasteCell?.(e, returnedArgs);
});
}
}

dispose() {
Expand Down Expand Up @@ -258,6 +279,11 @@ export class SlickCellExternalCopyManager {
if (desty < clipCommand.maxDestY && destx < clipCommand.maxDestX) {
// const nd = this._grid.getCellNode(desty, destx);
const dt = this._grid.getDataItem(desty);

if (this.trigger(this.onBeforePasteCell, { row: desty, cell: destx, dt, column: columns[destx], target: 'grid' }).getReturnValue() === false) {
continue;
}

clipCommand.oldValues[y][x] = dt[columns[destx]['field']];
if (oneCellToMultiple) {
this.setDataItemValueForColumn(dt, columns[destx], clippedRange[0][0]);
Expand Down Expand Up @@ -345,6 +371,12 @@ export class SlickCellExternalCopyManager {
}
}

protected trigger<ArgType = any>(evt: SlickEvent, args?: ArgType, e?: Event | SlickEventData) {
Copy link
Owner

Choose a reason for hiding this comment

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

so this looks like a full copy of the trigger method from SlickGrid, so perhaps we could just make the SlickGrid method as a public method and call it from here (and probably better to rename it as something like triggerEvent, or any other name, to be a little more specific)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I was hesitant to ask for that but yep this would be my prefered solution as well

const event: SlickEventData = (e || new SlickEventData(e, args)) as SlickEventData;
const eventArgs = (args || {}) as ArgType & { grid: SlickGrid; };
eventArgs.grid = this._grid;
return evt.notify(eventArgs, event, this._grid);
}

protected handleKeyDown(e: any): boolean | void {
let ranges: SlickRange[];
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@

import type { Column, FormatterResultWithHtml, FormatterResultWithText, } from './index';
import type { Column, FormatterResultWithHtml, FormatterResultWithText, OnEventArgs, } from './index';
import type { SlickCellExcelCopyManager, } from '../extensions/slickCellExcelCopyManager';
import type { SlickEventData, SlickRange } from '../core/index';

Expand Down Expand Up @@ -61,4 +61,7 @@ export interface ExcelCopyBufferOption<T = any> {

/** Fired when the user paste cells to the grid */
onPasteCells?: (e: SlickEventData, args: { ranges: SlickRange[]; }) => void;

/** Fired for each cell before pasting. Return false if you want to deny pasting for the specific cell */
onBeforePasteCell?: (e: SlickEventData, args: OnEventArgs) => boolean;
}
2 changes: 1 addition & 1 deletion packages/common/src/services/gridEvent.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export class GridEventService {
this._eventHandler.unsubscribeAll();
}

/* OnCellChange Event */
/* OnBeforeEditCell Event */
bindOnBeforeEditCell(grid: SlickGrid) {
const dataView = grid?.getData<SlickDataView>();

Expand Down