8
0

tableclipboard.js 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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 { 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 insertedTable = getTableFromContent( content );
  95. if ( !insertedTable ) {
  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. // Currently not handled. The selected table content should be trimmed to a rectangular selection.
  107. // See: https://github.com/ckeditor/ckeditor5/issues/6122.
  108. if ( !isSelectionRectangular( this.editor.model.document.selection, tableUtils ) ) {
  109. // @if CK_DEBUG // console.log( 'NOT IMPLEMENTED YET: Selection is not rectangular (non-mergeable).' );
  110. return;
  111. }
  112. const { last: lastColumnOfSelection, first: firstColumnOfSelection } = getColumnIndexes( selectedTableCells );
  113. const { first: firstRowOfSelection, last: lastRowOfSelection } = getRowIndexes( selectedTableCells );
  114. const selectionHeight = lastRowOfSelection - firstRowOfSelection + 1;
  115. const selectionWidth = lastColumnOfSelection - firstColumnOfSelection + 1;
  116. const insertHeight = tableUtils.getRows( insertedTable );
  117. const insertWidth = tableUtils.getColumns( insertedTable );
  118. // The if below is temporal and will be removed when handling this case.
  119. // See: https://github.com/ckeditor/ckeditor5/issues/6769.
  120. if ( selectionHeight > insertHeight || selectionWidth > insertWidth ) {
  121. // @if CK_DEBUG // console.log( 'NOT IMPLEMENTED YET: Pasted table is smaller than selection area.' );
  122. return;
  123. }
  124. const model = this.editor.model;
  125. model.change( writer => {
  126. // Crop pasted table if it extends selection area.
  127. if ( selectionHeight < insertHeight || selectionWidth < insertWidth ) {
  128. insertedTable = cropTableToDimensions( insertedTable, 0, 0, selectionHeight - 1, selectionWidth - 1, tableUtils, writer );
  129. }
  130. // Stores cells as a map of inserted table cell as 'row * column' index.
  131. const pastedTableMap = createLocationMap( insertedTable, selectionWidth, selectionHeight );
  132. // Content table to which we insert a table.
  133. const contentTable = findAncestor( 'table', selectedTableCells[ 0 ] );
  134. const tableMap = [ ...new TableWalker( contentTable, {
  135. startRow: firstRowOfSelection,
  136. endRow: lastRowOfSelection,
  137. includeSpanned: true
  138. } ) ];
  139. // Selection must be set to pasted cells (some might be removed or new created).
  140. const cellsToSelect = [];
  141. // Store previous cell in order to insert a new table cells after it if required.
  142. let previousCellInRow;
  143. // Content table replace cells algorithm iterates over a selected table fragment and:
  144. //
  145. // - Removes existing table cells at current slot (location).
  146. // - Inserts cell from a pasted table for a matched slots.
  147. //
  148. // This ensures proper table geometry after the paste
  149. for ( const { row, column, cell, isSpanned } of tableMap ) {
  150. if ( column === 0 ) {
  151. previousCellInRow = null;
  152. }
  153. // Could use startColumn, endColumn. See: https://github.com/ckeditor/ckeditor5/issues/6785.
  154. if ( column < firstColumnOfSelection || column > lastColumnOfSelection ) {
  155. previousCellInRow = cell;
  156. continue;
  157. }
  158. // If the slot is occupied by a cell in a selected table - remove it.
  159. // The slot of this cell will be either:
  160. // - Replaced by a pasted table cell.
  161. // - Spanned by a previously pasted table cell.
  162. if ( !isSpanned ) {
  163. writer.remove( cell );
  164. }
  165. // Map current table slot location to an inserted table slot location.
  166. const pastedCell = pastedTableMap[ row - firstRowOfSelection ][ column - firstColumnOfSelection ];
  167. // There is no cell to insert (might be spanned by other cell in a pasted table) - advance to the next content table slot.
  168. if ( !pastedCell ) {
  169. continue;
  170. }
  171. // Clone cell to insert (to duplicate its attributes and children).
  172. // Cloning is required to support repeating pasted table content when inserting to a bigger selection.
  173. const cellToInsert = pastedCell._clone( true );
  174. let insertPosition;
  175. if ( !previousCellInRow ) {
  176. insertPosition = writer.createPositionAt( contentTable.getChild( row ), 0 );
  177. } else {
  178. insertPosition = writer.createPositionAfter( previousCellInRow );
  179. }
  180. writer.insert( cellToInsert, insertPosition );
  181. cellsToSelect.push( cellToInsert );
  182. previousCellInRow = cellToInsert;
  183. }
  184. writer.setSelection( cellsToSelect.map( cell => writer.createRangeOn( cell ) ) );
  185. } );
  186. }
  187. }
  188. function getTableFromContent( content ) {
  189. if ( content.is( 'table' ) ) {
  190. return content;
  191. }
  192. for ( const child of Array.from( content ) ) {
  193. if ( child.is( 'table' ) ) {
  194. return child;
  195. }
  196. }
  197. return null;
  198. }
  199. // Returns two-dimensional array that is addressed by [ row ][ column ] that stores cells anchored at given location.
  200. //
  201. // At given row & column location it might be one of:
  202. //
  203. // * cell - cell from pasted table anchored at this location.
  204. // * null - if no cell is anchored at this location.
  205. //
  206. // For instance, from a table below:
  207. //
  208. // +----+----+----+----+
  209. // | 00 | 01 | 02 | 03 |
  210. // + +----+----+----+
  211. // | | 11 | 13 |
  212. // +----+ +----+
  213. // | 20 | | 23 |
  214. // +----+----+----+----+
  215. //
  216. // The method will return an array (numbers represents cell element):
  217. //
  218. // const map = [
  219. // [ '00', '01', '02', '03' ],
  220. // [ null, '11', null, '13' ],
  221. // [ '20', null, null, '23' ]
  222. // ]
  223. //
  224. // This allows for a quick access to table at give row & column. For instance to access table cell "13" from pasted table call:
  225. //
  226. // const cell = map[ 1 ][ 3 ]
  227. //
  228. function createLocationMap( table, width, height ) {
  229. // Create height x width (row x column) two-dimensional table to store cells.
  230. const map = new Array( height ).fill( null )
  231. .map( () => {
  232. return new Array( width ).fill( null );
  233. } );
  234. for ( const { column, row, cell } of new TableWalker( table ) ) {
  235. map[ row ][ column ] = cell;
  236. }
  237. return map;
  238. }