tableclipboard.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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 { cutCellsHorizontallyAt, cutCellsVerticallyAt, getColumnIndexes, getRowIndexes, isSelectionRectangular } from './utils';
  12. import { findAncestor } from './commands/utils';
  13. import { cropTableToDimensions } from './tableselection/croptable';
  14. import TableUtils from './tableutils';
  15. /**
  16. * This plugin adds support for copying/cutting/pasting fragments of tables.
  17. * It is loaded automatically by the {@link module:table/table~Table} plugin.
  18. *
  19. * @extends module:core/plugin~Plugin
  20. */
  21. export default class TableClipboard extends Plugin {
  22. /**
  23. * @inheritDoc
  24. */
  25. static get pluginName() {
  26. return 'TableClipboard';
  27. }
  28. /**
  29. * @inheritDoc
  30. */
  31. static get requires() {
  32. return [ TableSelection, TableUtils ];
  33. }
  34. /**
  35. * @inheritDoc
  36. */
  37. init() {
  38. const editor = this.editor;
  39. const viewDocument = editor.editing.view.document;
  40. this.listenTo( viewDocument, 'copy', ( evt, data ) => this._onCopyCut( evt, data ) );
  41. this.listenTo( viewDocument, 'cut', ( evt, data ) => this._onCopyCut( evt, data ) );
  42. this.listenTo( editor.model, 'insertContent', ( evt, args ) => this._onInsertContent( evt, ...args ), { priority: 'high' } );
  43. }
  44. /**
  45. * Copies table content to a clipboard on "copy" & "cut" events.
  46. *
  47. * @private
  48. * @param {module:utils/eventinfo~EventInfo} evt An object containing information about the handled event.
  49. * @param {Object} data Clipboard event data.
  50. */
  51. _onCopyCut( evt, data ) {
  52. const tableSelection = this.editor.plugins.get( TableSelection );
  53. if ( !tableSelection.getSelectedTableCells() ) {
  54. return;
  55. }
  56. if ( evt.name == 'cut' && this.editor.isReadOnly ) {
  57. return;
  58. }
  59. data.preventDefault();
  60. evt.stop();
  61. const dataController = this.editor.data;
  62. const viewDocument = this.editor.editing.view.document;
  63. const content = dataController.toView( tableSelection.getSelectionAsFragment() );
  64. viewDocument.fire( 'clipboardOutput', {
  65. dataTransfer: data.dataTransfer,
  66. content,
  67. method: evt.name
  68. } );
  69. }
  70. /**
  71. * Overrides default {@link module:engine/model/model~Model#insertContent `model.insertContent()`} method to handle pasting table inside
  72. * selected table fragment.
  73. *
  74. * Depending on selected table fragment:
  75. * - If a selected table fragment is smaller than paste table it will crop pasted table to match dimensions.
  76. * - If dimensions are equal it will replace selected table fragment with a pasted table contents.
  77. *
  78. * @private
  79. * @param evt
  80. * @param {module:engine/model/documentfragment~DocumentFragment|module:engine/model/item~Item} content The content to insert.
  81. * @param {module:engine/model/selection~Selectable} [selectable=model.document.selection]
  82. * The selection into which the content should be inserted. If not provided the current model document selection will be used.
  83. */
  84. _onInsertContent( evt, content, selectable ) {
  85. if ( selectable && !selectable.is( 'documentSelection' ) ) {
  86. return;
  87. }
  88. const tableSelection = this.editor.plugins.get( TableSelection );
  89. const selectedTableCells = tableSelection.getSelectedTableCells();
  90. if ( !selectedTableCells ) {
  91. return;
  92. }
  93. // We might need to crop table before inserting so reference might change.
  94. let pastedTable = getTableIfOnlyTableInContent( content );
  95. if ( !pastedTable ) {
  96. return;
  97. }
  98. // Override default model.insertContent() handling at this point.
  99. evt.stop();
  100. // Currently not handled. See: https://github.com/ckeditor/ckeditor5/issues/6121.
  101. if ( selectedTableCells.length === 1 ) {
  102. // @if CK_DEBUG // console.log( 'NOT IMPLEMENTED YET: Single table cell is selected.' );
  103. return;
  104. }
  105. const tableUtils = this.editor.plugins.get( TableUtils );
  106. const model = this.editor.model;
  107. model.change( writer => {
  108. // Currently not handled. The selected table content should be trimmed to a rectangular selection.
  109. // See: https://github.com/ckeditor/ckeditor5/issues/6122.
  110. if ( !isSelectionRectangular( selectedTableCells, tableUtils ) ) {
  111. prepareLandingPlace( selectedTableCells, writer );
  112. }
  113. const { last: lastColumnOfSelection, first: firstColumnOfSelection } = getColumnIndexes( selectedTableCells );
  114. const { first: firstRowOfSelection, last: lastRowOfSelection } = getRowIndexes( selectedTableCells );
  115. const selectionHeight = lastRowOfSelection - firstRowOfSelection + 1;
  116. const selectionWidth = lastColumnOfSelection - firstColumnOfSelection + 1;
  117. const pasteHeight = tableUtils.getRows( pastedTable );
  118. const pasteWidth = tableUtils.getColumns( pastedTable );
  119. // The if below is temporal and will be removed when handling this case.
  120. // See: https://github.com/ckeditor/ckeditor5/issues/6769.
  121. if ( selectionHeight > pasteHeight || selectionWidth > pasteWidth ) {
  122. // @if CK_DEBUG // console.log( 'NOT IMPLEMENTED YET: Pasted table is smaller than selection area.' );
  123. return;
  124. }
  125. // Crop pasted table if it extends selection area.
  126. if ( selectionHeight < pasteHeight || selectionWidth < pasteWidth ) {
  127. const cropDimensions = {
  128. startRow: 0,
  129. startColumn: 0,
  130. endRow: selectionHeight - 1,
  131. endColumn: selectionWidth - 1
  132. };
  133. pastedTable = cropTableToDimensions( pastedTable, cropDimensions, writer, tableUtils );
  134. }
  135. // Holds two-dimensional array that is addressed by [ row ][ column ] that stores cells anchored at given location.
  136. const pastedTableLocationMap = createLocationMap( pastedTable, selectionWidth, selectionHeight );
  137. // Content table to which we insert a pasted table.
  138. const selectedTable = findAncestor( 'table', selectedTableCells[ 0 ] );
  139. const selectedTableMap = [ ...new TableWalker( selectedTable, {
  140. startRow: firstRowOfSelection,
  141. endRow: lastRowOfSelection,
  142. includeSpanned: true
  143. } ) ];
  144. // Selection must be set to pasted cells (some might be removed or new created).
  145. const cellsToSelect = [];
  146. // Store previous cell in order to insert a new table cells after it (if required).
  147. let previousCellInRow;
  148. // Content table replace cells algorithm iterates over a selected table fragment and:
  149. //
  150. // - Removes existing table cells at current slot (location).
  151. // - Inserts cell from a pasted table for a matched slots.
  152. //
  153. // This ensures proper table geometry after the paste
  154. for ( const { row, column, cell, isSpanned } of selectedTableMap ) {
  155. if ( column === 0 ) {
  156. previousCellInRow = null;
  157. }
  158. // Could use startColumn, endColumn. See: https://github.com/ckeditor/ckeditor5/issues/6785.
  159. if ( column < firstColumnOfSelection || column > lastColumnOfSelection ) {
  160. // Only update the previousCellInRow for non-spanned slots.
  161. if ( !isSpanned ) {
  162. previousCellInRow = cell;
  163. }
  164. continue;
  165. }
  166. // If the slot is occupied by a cell in a selected table - remove it.
  167. // The slot of this cell will be either:
  168. // - Replaced by a pasted table cell.
  169. // - Spanned by a previously pasted table cell.
  170. if ( !isSpanned ) {
  171. writer.remove( cell );
  172. }
  173. // Map current table slot location to an pasted table slot location.
  174. const pastedCell = pastedTableLocationMap[ row - firstRowOfSelection ][ column - firstColumnOfSelection ];
  175. // There is no cell to insert (might be spanned by other cell in a pasted table) - advance to the next content table slot.
  176. if ( !pastedCell ) {
  177. continue;
  178. }
  179. // Clone cell to insert (to duplicate its attributes and children).
  180. // Cloning is required to support repeating pasted table content when inserting to a bigger selection.
  181. const cellToInsert = pastedCell._clone( true );
  182. let insertPosition;
  183. if ( !previousCellInRow ) {
  184. insertPosition = writer.createPositionAt( selectedTable.getChild( row ), 0 );
  185. } else {
  186. insertPosition = writer.createPositionAfter( previousCellInRow );
  187. }
  188. writer.insert( cellToInsert, insertPosition );
  189. cellsToSelect.push( cellToInsert );
  190. previousCellInRow = cellToInsert;
  191. }
  192. writer.setSelection( cellsToSelect.map( cell => writer.createRangeOn( cell ) ) );
  193. } );
  194. }
  195. }
  196. function getTableIfOnlyTableInContent( content ) {
  197. // Table passed directly.
  198. if ( content.is( 'table' ) ) {
  199. return content;
  200. }
  201. // We do not support mixed content when pasting table into table.
  202. // See: https://github.com/ckeditor/ckeditor5/issues/6817.
  203. if ( content.childCount != 1 || !content.getChild( 0 ).is( 'table' ) ) {
  204. return null;
  205. }
  206. return content.getChild( 0 );
  207. }
  208. // Returns two-dimensional array that is addressed by [ row ][ column ] that stores cells anchored at given location.
  209. //
  210. // At given row & column location it might be one of:
  211. //
  212. // * cell - cell from pasted table anchored at this location.
  213. // * null - if no cell is anchored at this location.
  214. //
  215. // For instance, from a table below:
  216. //
  217. // +----+----+----+----+
  218. // | 00 | 01 | 02 | 03 |
  219. // + +----+----+----+
  220. // | | 11 | 13 |
  221. // +----+ +----+
  222. // | 20 | | 23 |
  223. // +----+----+----+----+
  224. //
  225. // The method will return an array (numbers represents cell element):
  226. //
  227. // const map = [
  228. // [ '00', '01', '02', '03' ],
  229. // [ null, '11', null, '13' ],
  230. // [ '20', null, null, '23' ]
  231. // ]
  232. //
  233. // This allows for a quick access to table at give row & column. For instance to access table cell "13" from pasted table call:
  234. //
  235. // const cell = map[ 1 ][ 3 ]
  236. //
  237. function createLocationMap( table, width, height ) {
  238. // Create height x width (row x column) two-dimensional table to store cells.
  239. const map = new Array( height ).fill( null )
  240. .map( () => new Array( width ).fill( null ) );
  241. for ( const { column, row, cell } of new TableWalker( table ) ) {
  242. map[ row ][ column ] = cell;
  243. }
  244. return map;
  245. }
  246. function prepareLandingPlace( selectedTableCells, writer ) {
  247. const table = findAncestor( 'table', selectedTableCells[ 0 ] );
  248. const { first: firstRow, last: lastRow } = getRowIndexes( selectedTableCells );
  249. const { first: firstColumn, last: lastColumn } = getColumnIndexes( selectedTableCells );
  250. if ( firstColumn > 0 ) {
  251. cutCellsVerticallyAt( table, firstColumn, 0, writer, { firstRow, firstColumn: 0, lastRow, lastColumn: 1000 } );
  252. }
  253. cutCellsVerticallyAt( table, lastColumn + 1, firstColumn, writer, { firstRow, firstColumn: 0, lastRow, lastColumn: 1000 } );
  254. if ( firstRow > 0 ) {
  255. cutCellsHorizontallyAt( table, firstRow, 0, writer, { firstRow: 0, firstColumn, lastRow: 1000, lastColumn } );
  256. }
  257. cutCellsHorizontallyAt( table, lastRow + 1, firstRow, writer, { firstRow: 0, firstColumn, lastRow: 1000, lastColumn } );
  258. }