tableclipboard.js 20 KB

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