tableclipboard.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. /**
  2. * @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
  4. */
  5. /**
  6. * @module table/tableclipboard
  7. */
  8. import Plugin from '@ckeditor/ckeditor5-core/src/plugin';
  9. import TableSelection from './tableselection';
  10. import TableWalker from './tablewalker';
  11. import {
  12. getColumnIndexes,
  13. getVerticallyOverlappingCells,
  14. getRowIndexes,
  15. getSelectionAffectedTableCells,
  16. getHorizontallyOverlappingCells,
  17. isSelectionRectangular,
  18. splitHorizontally,
  19. splitVertically
  20. } from './utils';
  21. import { findAncestor } from './commands/utils';
  22. import { cropTableToDimensions } from './tableselection/croptable';
  23. import TableUtils from './tableutils';
  24. /**
  25. * This plugin adds support for copying/cutting/pasting fragments of tables.
  26. * It is loaded automatically by the {@link module:table/table~Table} plugin.
  27. *
  28. * @extends module:core/plugin~Plugin
  29. */
  30. export default class TableClipboard extends Plugin {
  31. /**
  32. * @inheritDoc
  33. */
  34. static get pluginName() {
  35. return 'TableClipboard';
  36. }
  37. /**
  38. * @inheritDoc
  39. */
  40. static get requires() {
  41. return [ TableSelection, TableUtils ];
  42. }
  43. /**
  44. * @inheritDoc
  45. */
  46. init() {
  47. const editor = this.editor;
  48. const viewDocument = editor.editing.view.document;
  49. this.listenTo( viewDocument, 'copy', ( evt, data ) => this._onCopyCut( evt, data ) );
  50. this.listenTo( viewDocument, 'cut', ( evt, data ) => this._onCopyCut( evt, data ) );
  51. this.listenTo( editor.model, 'insertContent', ( evt, args ) => this._onInsertContent( evt, ...args ), { priority: 'high' } );
  52. }
  53. /**
  54. * Copies table content to a clipboard on "copy" & "cut" events.
  55. *
  56. * @private
  57. * @param {module:utils/eventinfo~EventInfo} evt An object containing information about the handled event.
  58. * @param {Object} data Clipboard event data.
  59. */
  60. _onCopyCut( evt, data ) {
  61. const tableSelection = this.editor.plugins.get( TableSelection );
  62. if ( !tableSelection.getSelectedTableCells() ) {
  63. return;
  64. }
  65. if ( evt.name == 'cut' && this.editor.isReadOnly ) {
  66. return;
  67. }
  68. data.preventDefault();
  69. evt.stop();
  70. const dataController = this.editor.data;
  71. const viewDocument = this.editor.editing.view.document;
  72. const content = dataController.toView( tableSelection.getSelectionAsFragment() );
  73. viewDocument.fire( 'clipboardOutput', {
  74. dataTransfer: data.dataTransfer,
  75. content,
  76. method: evt.name
  77. } );
  78. }
  79. /**
  80. * Overrides default {@link module:engine/model/model~Model#insertContent `model.insertContent()`} method to handle pasting table inside
  81. * selected table fragment.
  82. *
  83. * Depending on selected table fragment:
  84. * - If a selected table fragment is smaller than paste table it will crop pasted table to match dimensions.
  85. * - If dimensions are equal it will replace selected table fragment with a pasted table contents.
  86. *
  87. * @private
  88. * @param evt
  89. * @param {module:engine/model/documentfragment~DocumentFragment|module:engine/model/item~Item} content The content to insert.
  90. * @param {module:engine/model/selection~Selectable} [selectable=model.document.selection]
  91. * The selection into which the content should be inserted. If not provided the current model document selection will be used.
  92. */
  93. _onInsertContent( evt, content, selectable ) {
  94. if ( selectable && !selectable.is( 'documentSelection' ) ) {
  95. return;
  96. }
  97. const model = this.editor.model;
  98. const tableUtils = this.editor.plugins.get( TableUtils );
  99. const selectedTableCells = getSelectionAffectedTableCells( model.document.selection );
  100. if ( !selectedTableCells.length ) {
  101. return;
  102. }
  103. // We might need to crop table before inserting so reference might change.
  104. let pastedTable = getTableIfOnlyTableInContent( content );
  105. if ( !pastedTable ) {
  106. return;
  107. }
  108. // Override default model.insertContent() handling at this point.
  109. evt.stop();
  110. model.change( writer => {
  111. const columnIndexes = getColumnIndexes( selectedTableCells );
  112. const rowIndexes = getRowIndexes( selectedTableCells );
  113. let { first: firstColumnOfSelection, last: lastColumnOfSelection } = columnIndexes;
  114. let { first: firstRowOfSelection, last: lastRowOfSelection } = rowIndexes;
  115. const pasteHeight = tableUtils.getRows( pastedTable );
  116. const pasteWidth = tableUtils.getColumns( pastedTable );
  117. // Content table to which we insert a pasted table.
  118. const selectedTable = findAncestor( 'table', selectedTableCells[ 0 ] );
  119. // Single cell selected - expand selection to pasted table dimensions.
  120. const shouldExpandSelection = selectedTableCells.length === 1;
  121. if ( shouldExpandSelection ) {
  122. lastRowOfSelection += pasteHeight - 1;
  123. lastColumnOfSelection += pasteWidth - 1;
  124. expandTableSize( selectedTable, lastRowOfSelection + 1, lastColumnOfSelection + 1, writer, tableUtils );
  125. }
  126. // In case of expanding selection we do not reset the selection so in this case we will always try to fix selection
  127. // like in the case of a non-rectangular area. This might be fixed by re-setting selected cells array but this shortcut is safe.
  128. if ( shouldExpandSelection || !isSelectionRectangular( selectedTableCells, tableUtils ) ) {
  129. const splitDimensions = {
  130. firstRow: firstRowOfSelection,
  131. lastRow: lastRowOfSelection,
  132. firstColumn: firstColumnOfSelection,
  133. lastColumn: lastColumnOfSelection
  134. };
  135. // For a non-rectangular selection (ie in which some cells sticks out from a virtual selection rectangle) we need to create
  136. // a table layout that has a rectangular selection. This will split cells so the selection become rectangular.
  137. // Beyond this point we will operate on fixed content table.
  138. splitCellsToRectangularSelection( selectedTable, splitDimensions, writer );
  139. }
  140. // However a rectangular selection might consist an invalid sub-table (if the selected cell would be moved outside the table).
  141. // This happens in a table which has:
  142. // - last row has empty slots (so are covered by cells from rows above) and/or
  143. // - last column has empty slots (are covered by cells from previous columns)
  144. // This case needs only adjusting the selection dimension as the rest of the algorithm operates on empty slots also.
  145. else {
  146. lastRowOfSelection = adjustLastRowIndex( selectedTable, rowIndexes, columnIndexes );
  147. lastColumnOfSelection = adjustLastColumnIndex( selectedTable, rowIndexes, columnIndexes );
  148. }
  149. // Beyond this point we operate on a fixed content table with rectangular selection and proper last row/column values.
  150. const selectionHeight = lastRowOfSelection - firstRowOfSelection + 1;
  151. const selectionWidth = lastColumnOfSelection - firstColumnOfSelection + 1;
  152. // The if below is temporal and will be removed when handling this case.
  153. // This if to be removed as handling of replicating cells should be done in replaceSelectedCellsWithPasted().
  154. // See: https://github.com/ckeditor/ckeditor5/issues/6769.
  155. if ( selectionHeight > pasteHeight || selectionWidth > pasteWidth ) {
  156. // @if CK_DEBUG // console.log( 'NOT IMPLEMENTED YET: Pasted table is smaller than selection area.' );
  157. return;
  158. }
  159. // Crop pasted table if:
  160. // - Pasted table dimensions exceeds selection area.
  161. // - Pasted table has broken layout (ie some cells sticks out by the table dimensions established by the first and last row).
  162. //
  163. // Note: The table dimensions are established by the width of the first row and the total number of rows.
  164. // It is possible to programmatically create a table that has rows which would have cells anchored beyond first row width but
  165. // such table will not be created by other editing solutions.
  166. const cropDimensions = {
  167. startRow: 0,
  168. startColumn: 0,
  169. endRow: Math.min( selectionHeight - 1, pasteHeight - 1 ),
  170. endColumn: Math.min( selectionWidth - 1, pasteWidth - 1 )
  171. };
  172. pastedTable = cropTableToDimensions( pastedTable, cropDimensions, writer, tableUtils );
  173. const selectionDimensions = {
  174. firstColumnOfSelection,
  175. firstRowOfSelection,
  176. lastColumnOfSelection,
  177. lastRowOfSelection,
  178. selectionHeight,
  179. selectionWidth
  180. };
  181. replaceSelectedCellsWithPasted( pastedTable, selectedTable, selectionDimensions, writer );
  182. } );
  183. }
  184. }
  185. // Replaces the part of selectedTable with pastedTable.
  186. //
  187. // @param {module:engine/model/element~Element} pastedTable
  188. // @param {module:engine/model/element~Element} selectedTable
  189. // @param {Object} selectionDimensions
  190. // @param {Number} selectionDimensions.firstColumnOfSelection
  191. // @param {Number} selectionDimensions.firstRowOfSelection
  192. // @param {Number} selectionDimensions.lastColumnOfSelection
  193. // @param {Number} selectionDimensions.lastRowOfSelection
  194. // @param {Number} selectionDimensions.selectionHeight
  195. // @param {Number} selectionDimensions.selectionWidth
  196. // @param {module:engine/model/writer~Writer} writer
  197. function replaceSelectedCellsWithPasted( pastedTable, selectedTable, selectionDimensions, writer ) {
  198. const {
  199. firstColumnOfSelection, lastColumnOfSelection,
  200. firstRowOfSelection, lastRowOfSelection,
  201. selectionWidth, selectionHeight
  202. } = selectionDimensions;
  203. // Holds two-dimensional array that is addressed by [ row ][ column ] that stores cells anchored at given location.
  204. const pastedTableLocationMap = createLocationMap( pastedTable, selectionWidth, selectionHeight );
  205. const selectedTableMap = [ ...new TableWalker( selectedTable, {
  206. startRow: firstRowOfSelection,
  207. endRow: lastRowOfSelection,
  208. includeSpanned: true
  209. } ) ];
  210. // Selection must be set to pasted cells (some might be removed or new created).
  211. const cellsToSelect = [];
  212. // Store previous cell in order to insert a new table cells after it (if required).
  213. let previousCellInRow;
  214. // Content table replace cells algorithm iterates over a selected table fragment and:
  215. //
  216. // - Removes existing table cells at current slot (location).
  217. // - Inserts cell from a pasted table for a matched slots.
  218. //
  219. // This ensures proper table geometry after the paste
  220. for ( const { row, column, cell, isSpanned } of selectedTableMap ) {
  221. if ( column === 0 ) {
  222. previousCellInRow = null;
  223. }
  224. // Could use startColumn, endColumn. See: https://github.com/ckeditor/ckeditor5/issues/6785.
  225. if ( column < firstColumnOfSelection || column > lastColumnOfSelection ) {
  226. // Only update the previousCellInRow for non-spanned slots.
  227. if ( !isSpanned ) {
  228. previousCellInRow = cell;
  229. }
  230. continue;
  231. }
  232. // If the slot is occupied by a cell in a selected table - remove it.
  233. // The slot of this cell will be either:
  234. // - Replaced by a pasted table cell.
  235. // - Spanned by a previously pasted table cell.
  236. if ( !isSpanned ) {
  237. writer.remove( cell );
  238. }
  239. // Map current table slot location to an pasted table slot location.
  240. const pastedCell = pastedTableLocationMap[ row - firstRowOfSelection ][ column - firstColumnOfSelection ];
  241. // There is no cell to insert (might be spanned by other cell in a pasted table) - advance to the next content table slot.
  242. if ( !pastedCell ) {
  243. continue;
  244. }
  245. // Clone cell to insert (to duplicate its attributes and children).
  246. // Cloning is required to support repeating pasted table content when inserting to a bigger selection.
  247. const cellToInsert = pastedCell._clone( true );
  248. let insertPosition;
  249. if ( !previousCellInRow ) {
  250. insertPosition = writer.createPositionAt( selectedTable.getChild( row ), 0 );
  251. } else {
  252. insertPosition = writer.createPositionAfter( previousCellInRow );
  253. }
  254. writer.insert( cellToInsert, insertPosition );
  255. cellsToSelect.push( cellToInsert );
  256. previousCellInRow = cellToInsert;
  257. }
  258. writer.setSelection( cellsToSelect.map( cell => writer.createRangeOn( cell ) ) );
  259. }
  260. // Expand table (in place) to expected size.
  261. function expandTableSize( table, expectedHeight, expectedWidth, writer, tableUtils ) {
  262. const tableWidth = tableUtils.getColumns( table );
  263. const tableHeight = tableUtils.getRows( table );
  264. if ( expectedWidth > tableWidth ) {
  265. tableUtils.insertColumns( table, {
  266. batch: writer.batch,
  267. at: tableWidth,
  268. columns: expectedWidth - tableWidth
  269. } );
  270. }
  271. if ( expectedHeight > tableHeight ) {
  272. tableUtils.insertRows( table, {
  273. batch: writer.batch,
  274. at: tableHeight,
  275. rows: expectedHeight - tableHeight
  276. } );
  277. }
  278. }
  279. function getTableIfOnlyTableInContent( content ) {
  280. // Table passed directly.
  281. if ( content.is( 'table' ) ) {
  282. return content;
  283. }
  284. // We do not support mixed content when pasting table into table.
  285. // See: https://github.com/ckeditor/ckeditor5/issues/6817.
  286. if ( content.childCount != 1 || !content.getChild( 0 ).is( 'table' ) ) {
  287. return null;
  288. }
  289. return content.getChild( 0 );
  290. }
  291. // Returns two-dimensional array that is addressed by [ row ][ column ] that stores cells anchored at given location.
  292. //
  293. // At given row & column location it might be one of:
  294. //
  295. // * cell - cell from pasted table anchored at this location.
  296. // * null - if no cell is anchored at this location.
  297. //
  298. // For instance, from a table below:
  299. //
  300. // +----+----+----+----+
  301. // | 00 | 01 | 02 | 03 |
  302. // + +----+----+----+
  303. // | | 11 | 13 |
  304. // +----+ +----+
  305. // | 20 | | 23 |
  306. // +----+----+----+----+
  307. //
  308. // The method will return an array (numbers represents cell element):
  309. //
  310. // const map = [
  311. // [ '00', '01', '02', '03' ],
  312. // [ null, '11', null, '13' ],
  313. // [ '20', null, null, '23' ]
  314. // ]
  315. //
  316. // This allows for a quick access to table at give row & column. For instance to access table cell "13" from pasted table call:
  317. //
  318. // const cell = map[ 1 ][ 3 ]
  319. //
  320. function createLocationMap( table, width, height ) {
  321. // Create height x width (row x column) two-dimensional table to store cells.
  322. const map = new Array( height ).fill( null )
  323. .map( () => new Array( width ).fill( null ) );
  324. for ( const { column, row, cell } of new TableWalker( table ) ) {
  325. map[ row ][ column ] = cell;
  326. }
  327. return map;
  328. }
  329. // Make selected cells rectangular by splitting the cells that stand out from a rectangular selection.
  330. //
  331. // In the table below a selection is shown with "::" and slots with anchor cells are named.
  332. //
  333. // +----+----+----+----+----+ +----+----+----+----+----+
  334. // | 00 | 01 | 02 | 03 | | 00 | 01 | 02 | 03 |
  335. // + +----+ +----+----+ | ::::::::::::::::----+
  336. // | | 11 | | 13 | 14 | | ::11 | | 13:: 14 | <- first row
  337. // +----+----+ + +----+ +----::---| | ::----+
  338. // | 20 | 21 | | | 24 | select cells: | 20 ::21 | | :: 24 |
  339. // +----+----+ +----+----+ 11 -> 33 +----::---| |---::----+
  340. // | 30 | | 33 | 34 | | 30 :: | | 33:: 34 | <- last row
  341. // + + +----+ + | :::::::::::::::: +
  342. // | | | 43 | | | | | 43 | |
  343. // +----+----+----+----+----+ +----+----+----+----+----+
  344. // ^ ^
  345. // first & last columns
  346. //
  347. // Will update table to:
  348. //
  349. // +----+----+----+----+----+
  350. // | 00 | 01 | 02 | 03 |
  351. // + +----+----+----+----+
  352. // | | 11 | | 13 | 14 |
  353. // +----+----+ + +----+
  354. // | 20 | 21 | | | 24 |
  355. // +----+----+ +----+----+
  356. // | 30 | | | 33 | 34 |
  357. // + +----+----+----+ +
  358. // | | | | 43 | |
  359. // +----+----+----+----+----+
  360. //
  361. // In th example above:
  362. // - Cell "02" which have `rowspan = 4` must be trimmed at first and at after last row.
  363. // - Cell "03" which have `rowspan = 2` and `colspan = 2` must be trimmed at first column and after last row.
  364. // - Cells "00", "03" & "30" which cannot be cut by this algorithm as they are outside the trimmed area.
  365. // - Cell "13" cannot be cut as it is inside the trimmed area.
  366. function splitCellsToRectangularSelection( table, dimensions, writer ) {
  367. const { firstRow, lastRow, firstColumn, lastColumn } = dimensions;
  368. const rowIndexes = { first: firstRow, last: lastRow };
  369. const columnIndexes = { first: firstColumn, last: lastColumn };
  370. // 1. Split cells vertically in two steps as first step might create cells that needs to split again.
  371. doVerticalSplit( table, firstColumn, rowIndexes, writer );
  372. doVerticalSplit( table, lastColumn + 1, rowIndexes, writer );
  373. // 2. Split cells horizontally in two steps as first step might create cells that needs to split again.
  374. doHorizontalSplit( table, firstRow, columnIndexes, writer );
  375. doHorizontalSplit( table, lastRow + 1, columnIndexes, writer, firstRow );
  376. }
  377. function doHorizontalSplit( table, splitRow, limitColumns, writer, startRow = 0 ) {
  378. // If selection starts at first row then no split is needed.
  379. if ( splitRow < 1 ) {
  380. return;
  381. }
  382. const overlappingCells = getVerticallyOverlappingCells( table, splitRow, startRow );
  383. // Filter out cells that are not touching insides of the rectangular selection.
  384. const cellsToSplit = overlappingCells.filter( ( { column, colspan } ) => isAffectedBySelection( column, colspan, limitColumns ) );
  385. for ( const { cell } of cellsToSplit ) {
  386. splitHorizontally( cell, splitRow, writer );
  387. }
  388. }
  389. function doVerticalSplit( table, splitColumn, limitRows, writer ) {
  390. // If selection starts at first column then no split is needed.
  391. if ( splitColumn < 1 ) {
  392. return;
  393. }
  394. const overlappingCells = getHorizontallyOverlappingCells( table, splitColumn );
  395. // Filter out cells that are not touching insides of the rectangular selection.
  396. const cellsToSplit = overlappingCells.filter( ( { row, rowspan } ) => isAffectedBySelection( row, rowspan, limitRows ) );
  397. for ( const { cell, column } of cellsToSplit ) {
  398. splitVertically( cell, column, splitColumn, writer );
  399. }
  400. }
  401. // Checks if cell at given row (column) is affected by a rectangular selection defined by first/last column (row).
  402. //
  403. // The same check is used for row as for column.
  404. function isAffectedBySelection( index, span, limit ) {
  405. const endIndex = index + span - 1;
  406. const { first, last } = limit;
  407. const isInsideSelection = index >= first && index <= last;
  408. const overlapsSelectionFromOutside = index < first && endIndex >= first;
  409. return isInsideSelection || overlapsSelectionFromOutside;
  410. }
  411. // Returns adjusted last row index if selection covers part of a row with empty slots (spanned by other cells).
  412. // The rowIndexes.last is equal to last row index but selection might be bigger.
  413. //
  414. // This happens *only* on rectangular selection so we analyze a case like this:
  415. //
  416. // +---+---+---+---+
  417. // 0 | a | b | c | d |
  418. // + + +---+---+
  419. // 1 | | e | f | g |
  420. // + +---+ +---+
  421. // 2 | | h | | i | <- last row, each cell has rowspan = 2,
  422. // + + + + + so we need to return 3, not 2
  423. // 3 | | | | |
  424. // +---+---+---+---+
  425. function adjustLastRowIndex( table, rowIndexes, columnIndexes ) {
  426. const tableIterator = new TableWalker( table, {
  427. startRow: rowIndexes.last,
  428. endRow: rowIndexes.last
  429. } );
  430. const lastRowMap = Array.from( tableIterator ).filter( ( { column } ) => {
  431. // Could use startColumn, endColumn. See: https://github.com/ckeditor/ckeditor5/issues/6785.
  432. return columnIndexes.first <= column && column <= columnIndexes.last;
  433. } );
  434. const everyCellHasSingleRowspan = lastRowMap.every( ( { rowspan } ) => rowspan === 1 );
  435. // It is a "flat" row, so the last row index is OK.
  436. if ( everyCellHasSingleRowspan ) {
  437. return rowIndexes.last;
  438. }
  439. // Otherwise get any cell's rowspan and adjust the last row index.
  440. const rowspanAdjustment = lastRowMap.pop().rowspan - 1;
  441. return rowIndexes.last + rowspanAdjustment;
  442. }
  443. // Returns adjusted last column index if selection covers part of a column with empty slots (spanned by other cells).
  444. // The columnIndexes.last is equal to last column index but selection might be bigger.
  445. //
  446. // This happens *only* on rectangular selection so we analyze a case like this:
  447. //
  448. // 0 1 2 3
  449. // +---+---+---+---+
  450. // | a |
  451. // +---+---+---+---+
  452. // | b | c | d |
  453. // +---+---+---+---+
  454. // | e | f |
  455. // +---+---+---+---+
  456. // | g | h |
  457. // +---+---+---+---+
  458. // ^
  459. // last column, each cell has colspan = 2, so we need to return 3, not 2
  460. function adjustLastColumnIndex( table, rowIndexes, columnIndexes ) {
  461. const lastColumnMap = Array.from( new TableWalker( table, {
  462. startRow: rowIndexes.first,
  463. endRow: rowIndexes.last,
  464. column: columnIndexes.last
  465. } ) );
  466. const everyCellHasSingleColspan = lastColumnMap.every( ( { colspan } ) => colspan === 1 );
  467. // It is a "flat" column, so the last column index is OK.
  468. if ( everyCellHasSingleColspan ) {
  469. return columnIndexes.last;
  470. }
  471. // Otherwise get any cell's colspan and adjust the last column index.
  472. const colspanAdjustment = lastColumnMap.pop().colspan - 1;
  473. return columnIndexes.last + colspanAdjustment;
  474. }