tableclipboard.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  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. findAncestor
  13. } from './utils/common';
  14. import TableUtils from './tableutils';
  15. import { getColumnIndexes, getRowIndexes, getSelectionAffectedTableCells, isSelectionRectangular } from './utils/selection';
  16. import {
  17. cropTableToDimensions,
  18. getHorizontallyOverlappingCells,
  19. getVerticallyOverlappingCells,
  20. splitHorizontally,
  21. splitVertically,
  22. trimTableCellIfNeeded
  23. } from './utils/structure';
  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, model );
  105. if ( !pastedTable ) {
  106. return;
  107. }
  108. // Override default model.insertContent() handling at this point.
  109. evt.stop();
  110. model.change( writer => {
  111. const pastedDimensions = {
  112. width: tableUtils.getColumns( pastedTable ),
  113. height: tableUtils.getRows( pastedTable )
  114. };
  115. // Prepare the table for pasting.
  116. const selection = prepareTableForPasting( selectedTableCells, pastedDimensions, writer, tableUtils );
  117. // Beyond this point we operate on a fixed content table with rectangular selection and proper last row/column values.
  118. const selectionHeight = selection.lastRow - selection.firstRow + 1;
  119. const selectionWidth = selection.lastColumn - selection.firstColumn + 1;
  120. // Crop pasted table if:
  121. // - Pasted table dimensions exceeds selection area.
  122. // - Pasted table has broken layout (ie some cells sticks out by the table dimensions established by the first and last row).
  123. //
  124. // Note: The table dimensions are established by the width of the first row and the total number of rows.
  125. // It is possible to programmatically create a table that has rows which would have cells anchored beyond first row width but
  126. // such table will not be created by other editing solutions.
  127. const cropDimensions = {
  128. startRow: 0,
  129. startColumn: 0,
  130. endRow: Math.min( selectionHeight, pastedDimensions.height ) - 1,
  131. endColumn: Math.min( selectionWidth, pastedDimensions.width ) - 1
  132. };
  133. pastedTable = cropTableToDimensions( pastedTable, cropDimensions, writer );
  134. // Content table to which we insert a pasted table.
  135. const selectedTable = findAncestor( 'table', selectedTableCells[ 0 ] );
  136. replaceSelectedCellsWithPasted( pastedTable, pastedDimensions, selectedTable, selection, writer );
  137. } );
  138. }
  139. }
  140. // Prepares a table for pasting and returns adjusted selection dimensions.
  141. //
  142. // @param {Array.<module:engine/model/element~Element>} selectedTableCells
  143. // @param {Object} pastedDimensions
  144. // @param {Number} pastedDimensions.height
  145. // @param {Number} pastedDimensions.width
  146. // @param {module:engine/model/writer~Writer} writer
  147. // @param {module:table/tableutils~TableUtils} tableUtils
  148. // @returns {Object} selection
  149. // @returns {Number} selection.firstColumn
  150. // @returns {Number} selection.firstRow
  151. // @returns {Number} selection.lastColumn
  152. // @returns {Number} selection.lastRow
  153. function prepareTableForPasting( selectedTableCells, pastedDimensions, writer, tableUtils ) {
  154. const selectedTable = findAncestor( 'table', selectedTableCells[ 0 ] );
  155. const columnIndexes = getColumnIndexes( selectedTableCells );
  156. const rowIndexes = getRowIndexes( selectedTableCells );
  157. const selection = {
  158. firstColumn: columnIndexes.first,
  159. lastColumn: columnIndexes.last,
  160. firstRow: rowIndexes.first,
  161. lastRow: rowIndexes.last
  162. };
  163. // Single cell selected - expand selection to pasted table dimensions.
  164. const shouldExpandSelection = selectedTableCells.length === 1;
  165. if ( shouldExpandSelection ) {
  166. selection.lastRow += pastedDimensions.height - 1;
  167. selection.lastColumn += pastedDimensions.width - 1;
  168. expandTableSize( selectedTable, selection.lastRow + 1, selection.lastColumn + 1, writer, tableUtils );
  169. }
  170. // In case of expanding selection we do not reset the selection so in this case we will always try to fix selection
  171. // like in the case of a non-rectangular area. This might be fixed by re-setting selected cells array but this shortcut is safe.
  172. if ( shouldExpandSelection || !isSelectionRectangular( selectedTableCells, tableUtils ) ) {
  173. // For a non-rectangular selection (ie in which some cells sticks out from a virtual selection rectangle) we need to create
  174. // a table layout that has a rectangular selection. This will split cells so the selection become rectangular.
  175. // Beyond this point we will operate on fixed content table.
  176. splitCellsToRectangularSelection( selectedTable, selection, writer );
  177. }
  178. // However a selected table fragment might be invalid if examined alone. Ie such table fragment:
  179. //
  180. // +---+---+---+---+
  181. // 0 | a | b | c | d |
  182. // + + +---+---+
  183. // 1 | | e | f | g |
  184. // + +---+ +---+
  185. // 2 | | h | | i | <- last row, each cell has rowspan = 2,
  186. // + + + + + so we need to return 3, not 2
  187. // 3 | | | | |
  188. // +---+---+---+---+
  189. //
  190. // is invalid as the cells "h" and "i" have rowspans.
  191. // This case needs only adjusting the selection dimension as the rest of the algorithm operates on empty slots also.
  192. else {
  193. selection.lastRow = adjustLastRowIndex( selectedTable, selection );
  194. selection.lastColumn = adjustLastColumnIndex( selectedTable, selection );
  195. }
  196. return selection;
  197. }
  198. // Replaces the part of selectedTable with pastedTable.
  199. //
  200. // @param {module:engine/model/element~Element} pastedTable
  201. // @param {Object} pastedDimensions
  202. // @param {Number} pastedDimensions.height
  203. // @param {Number} pastedDimensions.width
  204. // @param {module:engine/model/element~Element} selectedTable
  205. // @param {Object} selection
  206. // @param {Number} selection.firstColumn
  207. // @param {Number} selection.firstRow
  208. // @param {Number} selection.lastColumn
  209. // @param {Number} selection.lastRow
  210. // @param {module:engine/model/writer~Writer} writer
  211. function replaceSelectedCellsWithPasted( pastedTable, pastedDimensions, selectedTable, selection, writer ) {
  212. const { width: pastedWidth, height: pastedHeight } = pastedDimensions;
  213. // Holds two-dimensional array that is addressed by [ row ][ column ] that stores cells anchored at given location.
  214. const pastedTableLocationMap = createLocationMap( pastedTable, pastedWidth, pastedHeight );
  215. const selectedTableMap = [ ...new TableWalker( selectedTable, {
  216. startRow: selection.firstRow,
  217. endRow: selection.lastRow,
  218. startColumn: selection.firstColumn,
  219. endColumn: selection.lastColumn,
  220. includeAllSlots: true
  221. } ) ];
  222. // Selection must be set to pasted cells (some might be removed or new created).
  223. const cellsToSelect = [];
  224. // Store next cell insert position.
  225. let insertPosition;
  226. // Content table replace cells algorithm iterates over a selected table fragment and:
  227. //
  228. // - Removes existing table cells at current slot (location).
  229. // - Inserts cell from a pasted table for a matched slots.
  230. //
  231. // This ensures proper table geometry after the paste
  232. for ( const tableSlot of selectedTableMap ) {
  233. const { row, column, cell, isAnchor } = tableSlot;
  234. // Save the insert position for current row start.
  235. if ( column === selection.firstColumn ) {
  236. insertPosition = tableSlot.getPositionBefore();
  237. }
  238. // If the slot is occupied by a cell in a selected table - remove it.
  239. // The slot of this cell will be either:
  240. // - Replaced by a pasted table cell.
  241. // - Spanned by a previously pasted table cell.
  242. if ( isAnchor ) {
  243. writer.remove( cell );
  244. }
  245. // Map current table slot location to an pasted table slot location.
  246. const pastedRow = row - selection.firstRow;
  247. const pastedColumn = column - selection.firstColumn;
  248. const pastedCell = pastedTableLocationMap[ pastedRow % pastedHeight ][ pastedColumn % pastedWidth ];
  249. // There is no cell to insert (might be spanned by other cell in a pasted table) - advance to the next content table slot.
  250. if ( !pastedCell ) {
  251. continue;
  252. }
  253. // Clone cell to insert (to duplicate its attributes and children).
  254. // Cloning is required to support repeating pasted table content when inserting to a bigger selection.
  255. const cellToInsert = writer.cloneElement( pastedCell );
  256. // Trim the cell if it's row/col-spans would exceed selection area.
  257. trimTableCellIfNeeded( cellToInsert, row, column, selection.lastRow, selection.lastColumn, writer );
  258. writer.insert( cellToInsert, insertPosition );
  259. cellsToSelect.push( cellToInsert );
  260. insertPosition = writer.createPositionAfter( cellToInsert );
  261. }
  262. writer.setSelection( cellsToSelect.map( cell => writer.createRangeOn( cell ) ) );
  263. }
  264. // Expand table (in place) to expected size.
  265. function expandTableSize( table, expectedHeight, expectedWidth, writer, tableUtils ) {
  266. const tableWidth = tableUtils.getColumns( table );
  267. const tableHeight = tableUtils.getRows( table );
  268. if ( expectedWidth > tableWidth ) {
  269. tableUtils.insertColumns( table, {
  270. batch: writer.batch,
  271. at: tableWidth,
  272. columns: expectedWidth - tableWidth
  273. } );
  274. }
  275. if ( expectedHeight > tableHeight ) {
  276. tableUtils.insertRows( table, {
  277. batch: writer.batch,
  278. at: tableHeight,
  279. rows: expectedHeight - tableHeight
  280. } );
  281. }
  282. }
  283. function getTableIfOnlyTableInContent( content, model ) {
  284. // Table passed directly.
  285. if ( content.is( 'table' ) ) {
  286. return content;
  287. }
  288. // We do not support mixed content when pasting table into table.
  289. // See: https://github.com/ckeditor/ckeditor5/issues/6817.
  290. if ( content.childCount == 1 && content.getChild( 0 ).is( 'table' ) ) {
  291. return content.getChild( 0 );
  292. }
  293. // If there are only whitespaces around a table then use that table for pasting.
  294. const contentRange = model.createRangeIn( content );
  295. for ( const element of contentRange.getItems() ) {
  296. if ( element.is( 'table' ) ) {
  297. // Stop checking if there is some content before table.
  298. const rangeBefore = model.createRange( contentRange.start, model.createPositionBefore( element ) );
  299. if ( model.hasContent( rangeBefore, { ignoreWhitespaces: true } ) ) {
  300. return null;
  301. }
  302. // Stop checking if there is some content after table.
  303. const rangeAfter = model.createRange( model.createPositionAfter( element ), contentRange.end );
  304. if ( model.hasContent( rangeAfter, { ignoreWhitespaces: true } ) ) {
  305. return null;
  306. }
  307. // There wasn't any content neither before nor after.
  308. return element;
  309. }
  310. }
  311. return null;
  312. }
  313. // Returns two-dimensional array that is addressed by [ row ][ column ] that stores cells anchored at given location.
  314. //
  315. // At given row & column location it might be one of:
  316. //
  317. // * cell - cell from pasted table anchored at this location.
  318. // * null - if no cell is anchored at this location.
  319. //
  320. // For instance, from a table below:
  321. //
  322. // +----+----+----+----+
  323. // | 00 | 01 | 02 | 03 |
  324. // + +----+----+----+
  325. // | | 11 | 13 |
  326. // +----+ +----+
  327. // | 20 | | 23 |
  328. // +----+----+----+----+
  329. //
  330. // The method will return an array (numbers represents cell element):
  331. //
  332. // const map = [
  333. // [ '00', '01', '02', '03' ],
  334. // [ null, '11', null, '13' ],
  335. // [ '20', null, null, '23' ]
  336. // ]
  337. //
  338. // This allows for a quick access to table at give row & column. For instance to access table cell "13" from pasted table call:
  339. //
  340. // const cell = map[ 1 ][ 3 ]
  341. //
  342. function createLocationMap( table, width, height ) {
  343. // Create height x width (row x column) two-dimensional table to store cells.
  344. const map = new Array( height ).fill( null )
  345. .map( () => new Array( width ).fill( null ) );
  346. for ( const { column, row, cell } of new TableWalker( table ) ) {
  347. map[ row ][ column ] = cell;
  348. }
  349. return map;
  350. }
  351. // Make selected cells rectangular by splitting the cells that stand out from a rectangular selection.
  352. //
  353. // In the table below a selection is shown with "::" and slots with anchor cells are named.
  354. //
  355. // +----+----+----+----+----+ +----+----+----+----+----+
  356. // | 00 | 01 | 02 | 03 | | 00 | 01 | 02 | 03 |
  357. // + +----+ +----+----+ | ::::::::::::::::----+
  358. // | | 11 | | 13 | 14 | | ::11 | | 13:: 14 | <- first row
  359. // +----+----+ + +----+ +----::---| | ::----+
  360. // | 20 | 21 | | | 24 | select cells: | 20 ::21 | | :: 24 |
  361. // +----+----+ +----+----+ 11 -> 33 +----::---| |---::----+
  362. // | 30 | | 33 | 34 | | 30 :: | | 33:: 34 | <- last row
  363. // + + +----+ + | :::::::::::::::: +
  364. // | | | 43 | | | | | 43 | |
  365. // +----+----+----+----+----+ +----+----+----+----+----+
  366. // ^ ^
  367. // first & last columns
  368. //
  369. // Will update table to:
  370. //
  371. // +----+----+----+----+----+
  372. // | 00 | 01 | 02 | 03 |
  373. // + +----+----+----+----+
  374. // | | 11 | | 13 | 14 |
  375. // +----+----+ + +----+
  376. // | 20 | 21 | | | 24 |
  377. // +----+----+ +----+----+
  378. // | 30 | | | 33 | 34 |
  379. // + +----+----+----+ +
  380. // | | | | 43 | |
  381. // +----+----+----+----+----+
  382. //
  383. // In th example above:
  384. // - Cell "02" which have `rowspan = 4` must be trimmed at first and at after last row.
  385. // - Cell "03" which have `rowspan = 2` and `colspan = 2` must be trimmed at first column and after last row.
  386. // - Cells "00", "03" & "30" which cannot be cut by this algorithm as they are outside the trimmed area.
  387. // - Cell "13" cannot be cut as it is inside the trimmed area.
  388. function splitCellsToRectangularSelection( table, dimensions, writer ) {
  389. const { firstRow, lastRow, firstColumn, lastColumn } = dimensions;
  390. const rowIndexes = { first: firstRow, last: lastRow };
  391. const columnIndexes = { first: firstColumn, last: lastColumn };
  392. // 1. Split cells vertically in two steps as first step might create cells that needs to split again.
  393. doVerticalSplit( table, firstColumn, rowIndexes, writer );
  394. doVerticalSplit( table, lastColumn + 1, rowIndexes, writer );
  395. // 2. Split cells horizontally in two steps as first step might create cells that needs to split again.
  396. doHorizontalSplit( table, firstRow, columnIndexes, writer );
  397. doHorizontalSplit( table, lastRow + 1, columnIndexes, writer, firstRow );
  398. }
  399. function doHorizontalSplit( table, splitRow, limitColumns, writer, startRow = 0 ) {
  400. // If selection starts at first row then no split is needed.
  401. if ( splitRow < 1 ) {
  402. return;
  403. }
  404. const overlappingCells = getVerticallyOverlappingCells( table, splitRow, startRow );
  405. // Filter out cells that are not touching insides of the rectangular selection.
  406. const cellsToSplit = overlappingCells.filter( ( { column, cellWidth } ) => isAffectedBySelection( column, cellWidth, limitColumns ) );
  407. for ( const { cell } of cellsToSplit ) {
  408. splitHorizontally( cell, splitRow, writer );
  409. }
  410. }
  411. function doVerticalSplit( table, splitColumn, limitRows, writer ) {
  412. // If selection starts at first column then no split is needed.
  413. if ( splitColumn < 1 ) {
  414. return;
  415. }
  416. const overlappingCells = getHorizontallyOverlappingCells( table, splitColumn );
  417. // Filter out cells that are not touching insides of the rectangular selection.
  418. const cellsToSplit = overlappingCells.filter( ( { row, cellHeight } ) => isAffectedBySelection( row, cellHeight, limitRows ) );
  419. for ( const { cell, column } of cellsToSplit ) {
  420. splitVertically( cell, column, splitColumn, writer );
  421. }
  422. }
  423. // Checks if cell at given row (column) is affected by a rectangular selection defined by first/last column (row).
  424. //
  425. // The same check is used for row as for column.
  426. function isAffectedBySelection( index, span, limit ) {
  427. const endIndex = index + span - 1;
  428. const { first, last } = limit;
  429. const isInsideSelection = index >= first && index <= last;
  430. const overlapsSelectionFromOutside = index < first && endIndex >= first;
  431. return isInsideSelection || overlapsSelectionFromOutside;
  432. }
  433. // Returns adjusted last row index if selection covers part of a row with empty slots (spanned by other cells).
  434. // The rowIndexes.last is equal to last row index but selection might be bigger.
  435. //
  436. // This happens *only* on rectangular selection so we analyze a case like this:
  437. //
  438. // +---+---+---+---+
  439. // 0 | a | b | c | d |
  440. // + + +---+---+
  441. // 1 | | e | f | g |
  442. // + +---+ +---+
  443. // 2 | | h | | i | <- last row, each cell has rowspan = 2,
  444. // + + + + + so we need to return 3, not 2
  445. // 3 | | | | |
  446. // +---+---+---+---+
  447. function adjustLastRowIndex( table, dimensions ) {
  448. const lastRowMap = Array.from( new TableWalker( table, {
  449. startColumn: dimensions.firstColumn,
  450. endColumn: dimensions.lastColumn,
  451. row: dimensions.lastRow
  452. } ) );
  453. const everyCellHasSingleRowspan = lastRowMap.every( ( { cellHeight } ) => cellHeight === 1 );
  454. // It is a "flat" row, so the last row index is OK.
  455. if ( everyCellHasSingleRowspan ) {
  456. return dimensions.lastRow;
  457. }
  458. // Otherwise get any cell's rowspan and adjust the last row index.
  459. const rowspanAdjustment = lastRowMap[ 0 ].cellHeight - 1;
  460. return dimensions.lastRow + rowspanAdjustment;
  461. }
  462. // Returns adjusted last column index if selection covers part of a column with empty slots (spanned by other cells).
  463. // The columnIndexes.last is equal to last column index but selection might be bigger.
  464. //
  465. // This happens *only* on rectangular selection so we analyze a case like this:
  466. //
  467. // 0 1 2 3
  468. // +---+---+---+---+
  469. // | a |
  470. // +---+---+---+---+
  471. // | b | c | d |
  472. // +---+---+---+---+
  473. // | e | f |
  474. // +---+---+---+---+
  475. // | g | h |
  476. // +---+---+---+---+
  477. // ^
  478. // last column, each cell has colspan = 2, so we need to return 3, not 2
  479. function adjustLastColumnIndex( table, dimensions ) {
  480. const lastColumnMap = Array.from( new TableWalker( table, {
  481. startRow: dimensions.firstRow,
  482. endRow: dimensions.lastRow,
  483. column: dimensions.lastColumn
  484. } ) );
  485. const everyCellHasSingleColspan = lastColumnMap.every( ( { cellWidth } ) => cellWidth === 1 );
  486. // It is a "flat" column, so the last column index is OK.
  487. if ( everyCellHasSingleColspan ) {
  488. return dimensions.lastColumn;
  489. }
  490. // Otherwise get any cell's colspan and adjust the last column index.
  491. const colspanAdjustment = lastColumnMap[ 0 ].cellWidth - 1;
  492. return dimensions.lastColumn + colspanAdjustment;
  493. }