tableclipboard.js 19 KB

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