8
0

tableclipboard.js 19 KB

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