-
Notifications
You must be signed in to change notification settings - Fork 3k
/
copyPaste.js
815 lines (694 loc) · 25.4 KB
/
copyPaste.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
import { BasePlugin } from '../base';
import Hooks from '../../pluginHooks';
import { stringify, parse } from '../../3rdparty/SheetClip';
import { arrayEach } from '../../helpers/array';
import { sanitize } from '../../helpers/string';
import {
removeContentEditableFromElementAndDeselect,
runWithSelectedContendEditableElement,
makeElementContentEditableAndSelectItsContent
} from '../../helpers/dom/element';
import { isSafari } from '../../helpers/browser';
import copyItem from './contextMenuItem/copy';
import copyColumnHeadersOnlyItem from './contextMenuItem/copyColumnHeadersOnly';
import copyWithColumnGroupHeadersItem from './contextMenuItem/copyWithColumnGroupHeaders';
import copyWithColumnHeadersItem from './contextMenuItem/copyWithColumnHeaders';
import cutItem from './contextMenuItem/cut';
import PasteEvent from './pasteEvent';
import {
CopyableRangesFactory,
normalizeRanges,
} from './copyableRanges';
import { _dataToHTML, htmlToGridSettings } from '../../utils/parseTable';
import './copyPaste.css';
Hooks.getSingleton().register('afterCopyLimit');
Hooks.getSingleton().register('modifyCopyableRange');
Hooks.getSingleton().register('beforeCut');
Hooks.getSingleton().register('afterCut');
Hooks.getSingleton().register('beforePaste');
Hooks.getSingleton().register('afterPaste');
Hooks.getSingleton().register('beforeCopy');
Hooks.getSingleton().register('afterCopy');
export const PLUGIN_KEY = 'copyPaste';
export const PLUGIN_PRIORITY = 80;
const SETTING_KEYS = ['fragmentSelection'];
const META_HEAD = [
'<meta name="generator" content="Handsontable"/>',
'<style type="text/css">td{white-space:normal}br{mso-data-placement:same-cell}</style>',
].join('');
/* eslint-disable jsdoc/require-description-complete-sentence */
/**
* @description
* Copy, cut, and paste data by using the `CopyPaste` plugin.
*
* Control the `CopyPaste` plugin programmatically through its [API methods](#methods).
*
* The user can access the copy-paste features through:
* - The [context menu](@/guides/cell-features/clipboard.md#context-menu).
* - The [keyboard shortcuts](@/guides/cell-features/clipboard.md#related-keyboard-shortcuts).
* - The browser's menu bar.
*
* Read more:
* - [Guides: Clipboard](@/guides/cell-features/clipboard.md)
* - [Configuration options: `copyPaste`](@/api/options.md#copypaste)
*
* @example
* ```js
* // enable the plugin with the default configuration
* copyPaste: true,
*
* // or, enable the plugin with a custom configuration
* copyPaste: {
* columnsLimit: 25,
* rowsLimit: 50,
* pasteMode: 'shift_down',
* copyColumnHeaders: true,
* copyColumnGroupHeaders: true,
* copyColumnHeadersOnly: true,
* uiContainer: document.body,
* },
* ```
* @class CopyPaste
* @plugin CopyPaste
*/
export class CopyPaste extends BasePlugin {
static get PLUGIN_KEY() {
return PLUGIN_KEY;
}
static get SETTING_KEYS() {
return [
PLUGIN_KEY,
...SETTING_KEYS
];
}
static get PLUGIN_PRIORITY() {
return PLUGIN_PRIORITY;
}
/**
* The maximum number of columns than can be copied to the clipboard.
*
* @type {number}
* @default Infinity
*/
columnsLimit = Infinity;
/**
* The maximum number of rows than can be copied to the clipboard.
*
* @type {number}
* @default Infinity
*/
rowsLimit = Infinity;
/**
* When pasting:
* - `'overwrite'`: overwrite the currently-selected cells
* - `'shift_down'`: move currently-selected cells down
* - `'shift_right'`: move currently-selected cells to the right
*
* @type {string}
* @default 'overwrite'
*/
pasteMode = 'overwrite';
/**
* The UI container for the secondary focusable element.
*
* @type {HTMLElement}
*/
uiContainer = this.hot.rootDocument.body;
/**
* Shows the "Copy with headers" item in the context menu and extends the context menu with the
* `'copy_with_column_headers'` option that can be used for creating custom menus arrangements.
*
* @type {boolean}
* @default false
*/
#enableCopyColumnHeaders = false;
/**
* Shows the "Copy with group headers" item in the context menu and extends the context menu with the
* `'copy_with_column_group headers'` option that can be used for creating custom menus arrangements.
*
* @type {boolean}
* @default false
*/
#enableCopyColumnGroupHeaders = false;
/**
* Shows the "Copy headers only" item in the context menu and extends the context menu with the
* `'copy_column_headers_only'` option that can be used for creating custom menus arrangements.
*
* @type {boolean}
* @default false
*/
#enableCopyColumnHeadersOnly = false;
/**
* Defines the data range to copy. Possible values:
* * `'cells-only'` Copy selected cells only;
* * `'column-headers-only'` Copy column headers only;
* * `'with-column-group-headers'` Copy cells with all column headers;
* * `'with-column-headers'` Copy cells with column headers;
*
* @type {'cells-only' | 'column-headers-only' | 'with-column-group-headers' | 'with-column-headers'}
*/
#copyMode = 'cells-only';
/**
* Flag that is used to prevent copying when the native shortcut was not pressed.
*
* @type {boolean}
*/
#isTriggeredByCopy = false;
/**
* Flag that is used to prevent cutting when the native shortcut was not pressed.
*
* @type {boolean}
*/
#isTriggeredByCut = false;
/**
* Class that helps generate copyable ranges based on the current selection for different copy mode
* types.
*
* @type {CopyableRangesFactory}
*/
#copyableRangesFactory = new CopyableRangesFactory({
countRows: () => this.hot.countRows(),
countColumns: () => this.hot.countCols(),
rowsLimit: () => this.rowsLimit,
columnsLimit: () => this.columnsLimit,
countColumnHeaders: () => this.hot.view.getColumnHeadersCount(),
});
/**
* Ranges of the cells coordinates, which should be used to copy/cut/paste actions.
*
* @private
* @type {Array<{startRow: number, startCol: number, endRow: number, endCol: number}>}
*/
copyableRanges = [];
/**
* Checks if the [`CopyPaste`](#copypaste) plugin is enabled.
*
* This method gets called by Handsontable's [`beforeInit`](@/api/hooks.md#beforeinit) hook.
* If it returns `true`, the [`enablePlugin()`](#enableplugin) method gets called.
*
* @returns {boolean}
*/
isEnabled() {
return !!this.hot.getSettings()[PLUGIN_KEY];
}
/**
* Enables the [`CopyPaste`](#copypaste) plugin for your Handsontable instance.
*/
enablePlugin() {
if (this.enabled) {
return;
}
const { [PLUGIN_KEY]: settings } = this.hot.getSettings();
if (typeof settings === 'object') {
this.pasteMode = settings.pasteMode ?? this.pasteMode;
this.rowsLimit = isNaN(settings.rowsLimit) ? this.rowsLimit : settings.rowsLimit;
this.columnsLimit = isNaN(settings.columnsLimit) ? this.columnsLimit : settings.columnsLimit;
this.#enableCopyColumnHeaders = !!settings.copyColumnHeaders;
this.#enableCopyColumnGroupHeaders = !!settings.copyColumnGroupHeaders;
this.#enableCopyColumnHeadersOnly = !!settings.copyColumnHeadersOnly;
this.uiContainer = settings.uiContainer ?? this.uiContainer;
}
this.addHook('afterContextMenuDefaultOptions', options => this.#onAfterContextMenuDefaultOptions(options));
this.addHook('afterSelectionEnd', () => this.#onAfterSelectionEnd());
this.eventManager.addEventListener(this.hot.rootDocument, 'copy', (...args) => this.onCopy(...args));
this.eventManager.addEventListener(this.hot.rootDocument, 'cut', (...args) => this.onCut(...args));
this.eventManager.addEventListener(this.hot.rootDocument, 'paste', (...args) => this.onPaste(...args));
// Without this workaround Safari (tested on Safari@16.5.2) does allow copying/cutting from the browser menu.
if (isSafari()) {
this.eventManager.addEventListener(
this.hot.rootDocument.body, 'mouseenter', (...args) => this.#onSafariMouseEnter(...args)
);
this.eventManager.addEventListener(
this.hot.rootDocument.body, 'mouseleave', (...args) => this.#onSafariMouseLeave(...args)
);
this.addHook('afterSelection', () => this.#onSafariAfterSelection());
}
super.enablePlugin();
}
/**
* Updates the state of the [`CopyPaste`](#copypaste) plugin.
*
* Gets called when [`updateSettings()`](@/api/core.md#updatesettings)
* is invoked with any of the following configuration options:
* - [`copyPaste`](@/api/options.md#copypaste)
* - [`fragmentSelection`](@/api/options.md#fragmentselection)
*/
updatePlugin() {
this.disablePlugin();
this.enablePlugin();
super.updatePlugin();
}
/**
* Disables the [`CopyPaste`](#copypaste) plugin for your Handsontable instance.
*/
disablePlugin() {
super.disablePlugin();
}
/**
* Copies the contents of the selected cells (and/or their related column headers) to the system clipboard.
*
* Takes an optional parameter (`copyMode`) that defines the scope of copying:
*
* | `copyMode` value | Description |
* | ----------------------------- | --------------------------------------------------------------- |
* | `'cells-only'` (default) | Copy the selected cells |
* | `'with-column-headers'` | - Copy the selected cells<br>- Copy the nearest column headers |
* | `'with-column-group-headers'` | - Copy the selected cells<br>- Copy all related columns headers |
* | `'column-headers-only'` | Copy the nearest column headers (without copying cells) |
*
* @param {string} [copyMode='cells-only'] Copy mode.
*/
copy(copyMode = 'cells-only') {
this.#copyMode = copyMode;
this.#isTriggeredByCopy = true;
this.#ensureClipboardEventsGetTriggered('copy');
}
/**
* Copies the contents of the selected cells.
*/
copyCellsOnly() {
this.copy('cells-only');
}
/**
* Copies the contents of column headers that are nearest to the selected cells.
*/
copyColumnHeadersOnly() {
this.copy('column-headers-only');
}
/**
* Copies the contents of the selected cells and all their related column headers.
*/
copyWithAllColumnHeaders() {
this.copy('with-column-group-headers');
}
/**
* Copies the contents of the selected cells and their nearest column headers.
*/
copyWithColumnHeaders() {
this.copy('with-column-headers');
}
/**
* Cuts the contents of the selected cells to the system clipboard.
*/
cut() {
this.#isTriggeredByCut = true;
this.#ensureClipboardEventsGetTriggered('cut');
}
/**
* Converts the contents of multiple ranges (`ranges`) into a single string.
*
* @param {Array<{startRow: number, startCol: number, endRow: number, endCol: number}>} ranges Array of objects with properties `startRow`, `endRow`, `startCol` and `endCol`.
* @returns {string} A string that will be copied to the clipboard.
*/
getRangedCopyableData(ranges) {
return stringify(this.getRangedData(ranges));
}
/**
* Converts the contents of multiple ranges (`ranges`) into an array of arrays.
*
* @param {Array<{startRow: number, startCol: number, endRow: number, endCol: number}>} ranges Array of objects with properties `startRow`, `startCol`, `endRow` and `endCol`.
* @returns {Array[]} An array of arrays that will be copied to the clipboard.
*/
getRangedData(ranges) {
const data = [];
const { rows, columns } = normalizeRanges(ranges);
// concatenate all rows and columns data defined in ranges into one copyable string
arrayEach(rows, (row) => {
const rowSet = [];
arrayEach(columns, (column) => {
if (row < 0) {
// `row` as the second argument acts here as the `headerLevel` argument
rowSet.push(this.hot.getColHeader(column, row));
} else {
rowSet.push(this.hot.getCopyableData(row, column));
}
});
data.push(rowSet);
});
return data;
}
/**
* Simulates the paste action.
*
* For security reasons, modern browsers don't allow reading from the system clipboard.
*
* @param {string} pastableText The value to paste, as a raw string.
* @param {string} [pastableHtml=''] The value to paste, as HTML.
*/
paste(pastableText = '', pastableHtml = pastableText) {
if (!pastableText && !pastableHtml) {
return;
}
const pasteData = new PasteEvent();
if (pastableText) {
pasteData.clipboardData.setData('text/plain', pastableText);
}
if (pastableHtml) {
pasteData.clipboardData.setData('text/html', pastableHtml);
}
this.onPaste(pasteData);
}
/**
* Prepares copyable text from the cells selection in the invisible textarea.
*/
setCopyableText() {
const selectionRange = this.hot.getSelectedRangeLast();
if (!selectionRange) {
return;
}
if (selectionRange.isSingleHeader()) {
this.copyableRanges = [];
return;
}
this.#copyableRangesFactory.setSelectedRange(selectionRange);
const groupedRanges = new Map([
['headers', null],
['cells', null],
]);
if (this.#copyMode === 'column-headers-only') {
groupedRanges.set('headers', this.#copyableRangesFactory.getMostBottomColumnHeadersRange());
} else {
if (this.#copyMode === 'with-column-headers') {
groupedRanges.set('headers', this.#copyableRangesFactory.getMostBottomColumnHeadersRange());
} else if (this.#copyMode === 'with-column-group-headers') {
groupedRanges.set('headers', this.#copyableRangesFactory.getAllColumnHeadersRange());
}
groupedRanges.set('cells', this.#copyableRangesFactory.getCellsRange());
}
this.copyableRanges = Array.from(groupedRanges.values())
.filter(range => range !== null)
.map(({ startRow, startCol, endRow, endCol }) => ({ startRow, startCol, endRow, endCol }));
this.copyableRanges = this.hot.runHooks('modifyCopyableRange', this.copyableRanges);
const cellsRange = groupedRanges.get('cells');
if (cellsRange !== null && cellsRange.isRangeTrimmed) {
const {
startRow, startCol, endRow, endCol
} = cellsRange;
this.hot.runHooks('afterCopyLimit',
endRow - startRow + 1, endCol - startCol + 1, this.rowsLimit, this.columnsLimit);
}
}
/**
* Verifies if editor exists and is open.
*
* @private
* @returns {boolean}
*/
isEditorOpened() {
return this.hot.getActiveEditor()?.isOpened();
}
/**
* Ensure that the `copy`/`cut` events get triggered properly in Safari.
*
* @param {string} eventName Name of the event to get triggered.
*/
#ensureClipboardEventsGetTriggered(eventName) {
// Without this workaround Safari (tested on Safari@16.5.2) does not trigger the 'copy' event.
if (isSafari()) {
const lastSelectedRange = this.hot.getSelectedRangeLast();
if (lastSelectedRange) {
const { row: highlightRow, col: highlightColumn } = lastSelectedRange.highlight;
const currentlySelectedCell = this.hot.getCell(highlightRow, highlightColumn, true);
if (currentlySelectedCell) {
runWithSelectedContendEditableElement(currentlySelectedCell, () => {
this.hot.rootDocument.execCommand(eventName);
});
}
}
} else {
this.hot.rootDocument.execCommand(eventName);
}
}
/**
* Counts how many column headers will be copied based on the passed range.
*
* @private
* @param {Array<{startRow: number, startCol: number, endRow: number, endCol: number}>} ranges Array of objects with properties `startRow`, `startCol`, `endRow` and `endCol`.
* @returns {{ columnHeadersCount: number }} Returns an object with keys that holds
* information with the number of copied headers.
*/
#countCopiedHeaders(ranges) {
const { rows } = normalizeRanges(ranges);
let columnHeadersCount = 0;
for (let row = 0; row < rows.length; row++) {
if (rows[row] >= 0) {
break;
}
columnHeadersCount += 1;
}
return {
columnHeadersCount,
};
}
/**
* Prepares new values to populate them into datasource.
*
* @private
* @param {Array} inputArray An array of the data to populate.
* @param {Array} [selection] The selection which indicates from what position the data will be populated.
* @returns {Array} Range coordinates after populate data.
*/
populateValues(inputArray, selection = this.hot.getSelectedRangeLast()) {
if (!inputArray.length) {
return;
}
const populatedRowsLength = inputArray.length;
const populatedColumnsLength = inputArray[0].length;
const newRows = [];
const { row: startRow, col: startColumn } = selection.getTopStartCorner();
const { row: endRowFromSelection, col: endColumnFromSelection } = selection.getBottomEndCorner();
let visualRowForPopulatedData = startRow;
let visualColumnForPopulatedData = startColumn;
let lastVisualRow = startRow;
let lastVisualColumn = startColumn;
// We try to populate just all copied data or repeat copied data within a selection. Please keep in mind that we
// don't know whether populated data is bigger than selection on start as there are some cells for which values
// should be not inserted (it's known right after getting cell meta).
while (newRows.length < populatedRowsLength || visualRowForPopulatedData <= endRowFromSelection) {
const { skipRowOnPaste, visualRow } = this.hot.getCellMeta(visualRowForPopulatedData, startColumn);
visualRowForPopulatedData = visualRow + 1;
if (skipRowOnPaste === true) {
/* eslint-disable no-continue */
continue;
}
lastVisualRow = visualRow;
visualColumnForPopulatedData = startColumn;
const newRow = [];
const insertedRow = newRows.length % populatedRowsLength;
while (newRow.length < populatedColumnsLength || visualColumnForPopulatedData <= endColumnFromSelection) {
const { skipColumnOnPaste, visualCol } = this.hot.getCellMeta(startRow, visualColumnForPopulatedData);
visualColumnForPopulatedData = visualCol + 1;
if (skipColumnOnPaste === true) {
/* eslint-disable no-continue */
continue;
}
lastVisualColumn = visualCol;
const insertedColumn = newRow.length % populatedColumnsLength;
newRow.push(inputArray[insertedRow][insertedColumn]);
}
newRows.push(newRow);
}
this.hot.populateFromArray(startRow, startColumn, newRows, undefined, undefined, 'CopyPaste.paste', this.pasteMode);
return [startRow, startColumn, lastVisualRow, lastVisualColumn];
}
/**
* Add the `contenteditable` attribute to the highlighted cell and select its content.
*/
#addContentEditableToHighlightedCell() {
if (this.hot.isListening()) {
const lastSelectedRange = this.hot.getSelectedRangeLast();
if (lastSelectedRange) {
const { row: highlightRow, col: highlightColumn } = lastSelectedRange.highlight;
const currentlySelectedCell = this.hot.getCell(highlightRow, highlightColumn, true);
if (currentlySelectedCell) {
makeElementContentEditableAndSelectItsContent(currentlySelectedCell);
}
}
}
}
/**
* Remove the `contenteditable` attribute from the highlighted cell and deselect its content.
*/
#removeContentEditableFromHighlightedCell() {
// If the instance is not listening, the workaround is not needed.
if (this.hot.isListening()) {
const lastSelectedRange = this.hot.getSelectedRangeLast();
if (lastSelectedRange) {
const { row: highlightRow, col: highlightColumn } = lastSelectedRange.highlight;
const currentlySelectedCell = this.hot.getCell(highlightRow, highlightColumn, true);
if (currentlySelectedCell?.hasAttribute('contenteditable')) {
removeContentEditableFromElementAndDeselect(currentlySelectedCell);
}
}
}
}
/**
* `copy` event callback on textarea element.
*
* @param {Event} event ClipboardEvent.
* @private
*/
onCopy(event) {
if ((!this.hot.isListening() && !this.#isTriggeredByCopy) || this.isEditorOpened()) {
return;
}
this.setCopyableText();
this.#isTriggeredByCopy = false;
const data = this.getRangedData(this.copyableRanges);
const copiedHeadersCount = this.#countCopiedHeaders(this.copyableRanges);
const allowCopying = !!this.hot.runHooks('beforeCopy', data, this.copyableRanges, copiedHeadersCount);
if (allowCopying) {
const textPlain = stringify(data);
if (event && event.clipboardData) {
const textHTML = _dataToHTML(data, this.hot.rootDocument);
event.clipboardData.setData('text/plain', textPlain);
event.clipboardData.setData('text/html', [META_HEAD, textHTML].join(''));
} else if (typeof ClipboardEvent === 'undefined') {
this.hot.rootWindow.clipboardData.setData('Text', textPlain);
}
this.hot.runHooks('afterCopy', data, this.copyableRanges, copiedHeadersCount);
}
this.#copyMode = 'cells-only';
event.preventDefault();
}
/**
* `cut` event callback on textarea element.
*
* @param {Event} event ClipboardEvent.
* @private
*/
onCut(event) {
if ((!this.hot.isListening() && !this.#isTriggeredByCut) || this.isEditorOpened()) {
return;
}
this.setCopyableText();
this.#isTriggeredByCut = false;
const rangedData = this.getRangedData(this.copyableRanges);
const allowCuttingOut = !!this.hot.runHooks('beforeCut', rangedData, this.copyableRanges);
if (allowCuttingOut) {
const textPlain = stringify(rangedData);
if (event && event.clipboardData) {
const textHTML = _dataToHTML(rangedData, this.hot.rootDocument);
event.clipboardData.setData('text/plain', textPlain);
event.clipboardData.setData('text/html', [META_HEAD, textHTML].join(''));
} else if (typeof ClipboardEvent === 'undefined') {
this.hot.rootWindow.clipboardData.setData('Text', textPlain);
}
this.hot.emptySelectedCells('CopyPaste.cut');
this.hot.runHooks('afterCut', rangedData, this.copyableRanges);
}
event.preventDefault();
}
/**
* `paste` event callback on textarea element.
*
* @param {Event} event ClipboardEvent or pseudo ClipboardEvent, if paste was called manually.
* @private
*/
onPaste(event) {
if (!this.hot.isListening() || this.isEditorOpened() || !this.hot.getSelected()) {
return;
}
if (event && event.preventDefault) {
event.preventDefault();
}
let pastedData;
if (event && typeof event.clipboardData !== 'undefined') {
const textHTML = sanitize(event.clipboardData.getData('text/html'), {
ADD_TAGS: ['meta'],
ADD_ATTR: ['content'],
FORCE_BODY: true,
});
if (textHTML && /(<table)|(<TABLE)/g.test(textHTML)) {
const parsedConfig = htmlToGridSettings(textHTML, this.hot.rootDocument);
pastedData = parsedConfig.data;
} else {
pastedData = event.clipboardData.getData('text/plain');
}
} else if (typeof ClipboardEvent === 'undefined' && typeof this.hot.rootWindow.clipboardData !== 'undefined') {
pastedData = this.hot.rootWindow.clipboardData.getData('Text');
}
if (typeof pastedData === 'string') {
pastedData = parse(pastedData);
}
if (pastedData === void 0 || pastedData && pastedData.length === 0) {
return;
}
if (this.hot.runHooks('beforePaste', pastedData, this.copyableRanges) === false) {
return;
}
const [startRow, startColumn, endRow, endColumn] = this.populateValues(pastedData);
this.hot.selectCell(
startRow,
startColumn,
Math.min(this.hot.countRows() - 1, endRow),
Math.min(this.hot.countCols() - 1, endColumn),
);
this.hot.runHooks('afterPaste', pastedData, this.copyableRanges);
}
/**
* Add copy and cut options to the Context Menu.
*
* @param {object} options Contains default added options of the Context Menu.
*/
#onAfterContextMenuDefaultOptions(options) {
options.items.push(
{ name: '---------' },
copyItem(this),
);
if (this.#enableCopyColumnHeaders) {
options.items.push(
copyWithColumnHeadersItem(this),
);
}
if (this.#enableCopyColumnGroupHeaders) {
options.items.push(
copyWithColumnGroupHeadersItem(this),
);
}
if (this.#enableCopyColumnHeadersOnly) {
options.items.push(
copyColumnHeadersOnlyItem(this),
);
}
options.items.push(cutItem(this));
}
/**
* Force focus on focusableElement after end of the selection.
*/
#onAfterSelectionEnd() {
if (this.isEditorOpened()) {
return;
}
if (this.hot.getSettings().fragmentSelection) {
return;
}
this.setCopyableText();
}
/**
* `document.body` `mouseenter` callback used to work around a Safari's problem with copying/cutting from the
* browser's menu.
*/
#onSafariMouseEnter() {
this.#removeContentEditableFromHighlightedCell();
}
/**
* `document.body` `mouseleave` callback used to work around a Safari's problem with copying/cutting from the
* browser's menu.
*/
#onSafariMouseLeave() {
this.#addContentEditableToHighlightedCell();
}
/**
* `afterSelection` hook callback triggered only on Safari.
*/
#onSafariAfterSelection() {
this.#removeContentEditableFromHighlightedCell();
}
/**
* Destroys the `CopyPaste` plugin instance.
*/
destroy() {
super.destroy();
}
}