tableclipboard.js 20 KB

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