tableediting.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. /**
  2. * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module table/tableediting
  7. */
  8. import Plugin from '@ckeditor/ckeditor5-core/src/plugin';
  9. import { upcastElementToElement } from '@ckeditor/ckeditor5-engine/src/conversion/upcast-converters';
  10. import Range from '@ckeditor/ckeditor5-engine/src/model/range';
  11. import Position from '@ckeditor/ckeditor5-engine/src/model/position';
  12. import { keyCodes } from '@ckeditor/ckeditor5-utils/src/keyboard';
  13. import upcastTable from './converters/upcasttable';
  14. import {
  15. downcastInsertCell,
  16. downcastInsertRow,
  17. downcastInsertTable,
  18. downcastRemoveRow,
  19. downcastTableHeadingColumnsChange,
  20. downcastTableHeadingRowsChange
  21. } from './converters/downcast';
  22. import InsertTableCommand from './commands/inserttablecommand';
  23. import InsertRowCommand from './commands/insertrowcommand';
  24. import InsertColumnCommand from './commands/insertcolumncommand';
  25. import SplitCellCommand from './commands/splitcellcommand';
  26. import MergeCellCommand from './commands/mergecellcommand';
  27. import RemoveRowCommand from './commands/removerowcommand';
  28. import RemoveColumnCommand from './commands/removecolumncommand';
  29. import SetHeaderRowCommand from './commands/setheaderrowcommand';
  30. import SetHeaderColumnCommand from './commands/setheadercolumncommand';
  31. import { getParentTable, updateNumericAttribute } from './commands/utils';
  32. import TableWalker from './tablewalker';
  33. import TableUtils from '../src/tableutils';
  34. import '../theme/tableediting.css';
  35. /**
  36. * The table editing feature.
  37. *
  38. * @extends module:core/plugin~Plugin
  39. */
  40. export default class TableEditing extends Plugin {
  41. /**
  42. * @inheritDoc
  43. */
  44. init() {
  45. const editor = this.editor;
  46. const model = editor.model;
  47. const schema = model.schema;
  48. const conversion = editor.conversion;
  49. schema.register( 'table', {
  50. allowWhere: '$block',
  51. allowAttributes: [ 'headingRows', 'headingColumns' ],
  52. isLimit: true,
  53. isObject: true
  54. } );
  55. schema.register( 'tableRow', {
  56. allowIn: 'table',
  57. isLimit: true
  58. } );
  59. schema.register( 'tableCell', {
  60. allowIn: 'tableRow',
  61. allowContentOf: '$block',
  62. allowAttributes: [ 'colspan', 'rowspan' ],
  63. isLimit: true
  64. } );
  65. // Table conversion.
  66. conversion.for( 'upcast' ).add( upcastTable() );
  67. conversion.for( 'editingDowncast' ).add( downcastInsertTable( { asWidget: true } ) );
  68. conversion.for( 'dataDowncast' ).add( downcastInsertTable() );
  69. // Table row conversion.
  70. conversion.for( 'upcast' ).add( upcastElementToElement( { model: 'tableRow', view: 'tr' } ) );
  71. conversion.for( 'editingDowncast' ).add( downcastInsertRow( { asWidget: true } ) );
  72. conversion.for( 'dataDowncast' ).add( downcastInsertRow() );
  73. conversion.for( 'downcast' ).add( downcastRemoveRow() );
  74. // Table cell conversion.
  75. conversion.for( 'upcast' ).add( upcastElementToElement( { model: 'tableCell', view: 'td' } ) );
  76. conversion.for( 'upcast' ).add( upcastElementToElement( { model: 'tableCell', view: 'th' } ) );
  77. conversion.for( 'editingDowncast' ).add( downcastInsertCell( { asWidget: true } ) );
  78. conversion.for( 'dataDowncast' ).add( downcastInsertCell() );
  79. // Table attributes conversion.
  80. conversion.attributeToAttribute( { model: 'colspan', view: 'colspan' } );
  81. conversion.attributeToAttribute( { model: 'rowspan', view: 'rowspan' } );
  82. // Table heading rows and cols conversion.
  83. conversion.for( 'editingDowncast' ).add( downcastTableHeadingColumnsChange( { asWidget: true } ) );
  84. conversion.for( 'dataDowncast' ).add( downcastTableHeadingColumnsChange() );
  85. conversion.for( 'editingDowncast' ).add( downcastTableHeadingRowsChange( { asWidget: true } ) );
  86. conversion.for( 'dataDowncast' ).add( downcastTableHeadingRowsChange() );
  87. // Define all the commands.
  88. editor.commands.add( 'insertTable', new InsertTableCommand( editor ) );
  89. editor.commands.add( 'insertTableRowAbove', new InsertRowCommand( editor, { order: 'above' } ) );
  90. editor.commands.add( 'insertTableRowBelow', new InsertRowCommand( editor, { order: 'below' } ) );
  91. editor.commands.add( 'insertTableColumnBefore', new InsertColumnCommand( editor, { order: 'before' } ) );
  92. editor.commands.add( 'insertTableColumnAfter', new InsertColumnCommand( editor, { order: 'after' } ) );
  93. editor.commands.add( 'removeTableRow', new RemoveRowCommand( editor ) );
  94. editor.commands.add( 'removeTableColumn', new RemoveColumnCommand( editor ) );
  95. editor.commands.add( 'splitTableCellVertically', new SplitCellCommand( editor, { direction: 'vertically' } ) );
  96. editor.commands.add( 'splitTableCellHorizontally', new SplitCellCommand( editor, { direction: 'horizontally' } ) );
  97. editor.commands.add( 'mergeTableCellRight', new MergeCellCommand( editor, { direction: 'right' } ) );
  98. editor.commands.add( 'mergeTableCellLeft', new MergeCellCommand( editor, { direction: 'left' } ) );
  99. editor.commands.add( 'mergeTableCellDown', new MergeCellCommand( editor, { direction: 'down' } ) );
  100. editor.commands.add( 'mergeTableCellUp', new MergeCellCommand( editor, { direction: 'up' } ) );
  101. editor.commands.add( 'setTableColumnHeader', new SetHeaderColumnCommand( editor ) );
  102. editor.commands.add( 'setTableRowHeader', new SetHeaderRowCommand( editor ) );
  103. injectTablePostFixer( model, this.editor.plugins.get( TableUtils ) );
  104. // Handle tab key navigation.
  105. this.listenTo( editor.editing.view.document, 'keydown', ( ...args ) => this._handleTabOnSelectedTable( ...args ) );
  106. this.listenTo( editor.editing.view.document, 'keydown', ( ...args ) => this._handleTabInsideTable( ...args ) );
  107. }
  108. /**
  109. * @inheritDoc
  110. */
  111. static get requires() {
  112. return [ TableUtils ];
  113. }
  114. /**
  115. * Handles {@link module:engine/view/document~Document#event:keydown keydown} events for the <kbd>Tab</kbd> key executed
  116. * when the table widget is selected.
  117. *
  118. * @private
  119. * @param {module:utils/eventinfo~EventInfo} eventInfo
  120. * @param {module:engine/view/observer/domeventdata~DomEventData} domEventData
  121. */
  122. _handleTabOnSelectedTable( eventInfo, domEventData ) {
  123. const tabPressed = domEventData.keyCode == keyCodes.tab;
  124. // Act only on TAB & SHIFT-TAB - Do not override native CTRL+TAB handler.
  125. if ( !tabPressed || domEventData.ctrlKey ) {
  126. return;
  127. }
  128. const editor = this.editor;
  129. const selection = editor.model.document.selection;
  130. if ( !selection.isCollapsed && selection.rangeCount === 1 && selection.getFirstRange().isFlat ) {
  131. const selectedElement = selection.getSelectedElement();
  132. if ( !selectedElement || selectedElement.name != 'table' ) {
  133. return;
  134. }
  135. eventInfo.stop();
  136. domEventData.preventDefault();
  137. domEventData.stopPropagation();
  138. editor.model.change( writer => {
  139. writer.setSelection( Range.createIn( selectedElement.getChild( 0 ).getChild( 0 ) ) );
  140. } );
  141. }
  142. }
  143. /**
  144. * Handles {@link module:engine/view/document~Document#event:keydown keydown} events for the <kbd>Tab</kbd> key executed inside table
  145. * cell.
  146. *
  147. * @private
  148. * @param {module:utils/eventinfo~EventInfo} eventInfo
  149. * @param {module:engine/view/observer/domeventdata~DomEventData} domEventData
  150. */
  151. _handleTabInsideTable( eventInfo, domEventData ) {
  152. const tabPressed = domEventData.keyCode == keyCodes.tab;
  153. // Act only on TAB & SHIFT-TAB - Do not override native CTRL+TAB handler.
  154. if ( !tabPressed || domEventData.ctrlKey ) {
  155. return;
  156. }
  157. const editor = this.editor;
  158. const selection = editor.model.document.selection;
  159. const table = getParentTable( selection.getFirstPosition() );
  160. if ( !table ) {
  161. return;
  162. }
  163. domEventData.preventDefault();
  164. domEventData.stopPropagation();
  165. const tableCell = selection.focus.parent;
  166. const tableRow = tableCell.parent;
  167. const currentRowIndex = table.getChildIndex( tableRow );
  168. const currentCellIndex = tableRow.getChildIndex( tableCell );
  169. const isForward = !domEventData.shiftKey;
  170. const isFirstCellInRow = currentCellIndex === 0;
  171. if ( !isForward && isFirstCellInRow && currentRowIndex === 0 ) {
  172. // It's the first cell of a table - don't do anything (stay in current position).
  173. return;
  174. }
  175. const isLastCellInRow = currentCellIndex === tableRow.childCount - 1;
  176. const isLastRow = currentRowIndex === table.childCount - 1;
  177. if ( isForward && isLastRow && isLastCellInRow ) {
  178. editor.plugins.get( TableUtils ).insertRows( table, { at: table.childCount } );
  179. }
  180. let cellToFocus;
  181. // Move to first cell in next row.
  182. if ( isForward && isLastCellInRow ) {
  183. const nextRow = table.getChild( currentRowIndex + 1 );
  184. cellToFocus = nextRow.getChild( 0 );
  185. }
  186. // Move to last cell in a previous row.
  187. else if ( !isForward && isFirstCellInRow ) {
  188. const previousRow = table.getChild( currentRowIndex - 1 );
  189. cellToFocus = previousRow.getChild( previousRow.childCount - 1 );
  190. }
  191. // Move to next/previous cell.
  192. else {
  193. cellToFocus = tableRow.getChild( currentCellIndex + ( isForward ? 1 : -1 ) );
  194. }
  195. editor.model.change( writer => {
  196. writer.setSelection( Range.createIn( cellToFocus ) );
  197. } );
  198. }
  199. }
  200. function injectTablePostFixer( model, tableUtils ) {
  201. model.document.registerPostFixer( writer => tablePostFixer( writer, model, tableUtils ) );
  202. }
  203. function tablePostFixer( writer, model, tableUtils ) {
  204. const changes = model.document.differ.getChanges();
  205. let wasFixed = false;
  206. const tableRowsOfRemovedCells = [];
  207. for ( const entry of changes ) {
  208. if ( entry.type == 'insert' ) {
  209. let table;
  210. if ( entry.name == 'table' ) {
  211. table = entry.position.nodeAfter;
  212. }
  213. if ( entry.name == 'tableRow' ) {
  214. const tableRow = entry.position.nodeAfter;
  215. table = tableRow.parent;
  216. }
  217. if ( table ) {
  218. wasFixed = fixTableOnInsert( tableUtils, table, writer, wasFixed );
  219. }
  220. }
  221. if ( entry.type == 'remove' && entry.name == 'tableCell' ) {
  222. const tableRow = entry.position.parent;
  223. tableRowsOfRemovedCells.push( tableRow );
  224. }
  225. }
  226. wasFixed = fixTableOnRemoveCells( tableRowsOfRemovedCells, writer ) || wasFixed;
  227. return wasFixed;
  228. }
  229. function getRowsLengths( table ) {
  230. const lengths = {};
  231. const headingRows = parseInt( table.getAttribute( 'headingRows' ) || 0 );
  232. const cellsToTrim = [];
  233. for ( const data of new TableWalker( table ) ) {
  234. const row = data.row;
  235. const column = data.column;
  236. const colspan = data.colspan;
  237. const rowspan = data.rowspan;
  238. if ( !lengths[ row ] ) {
  239. // Le first row - the first column will be current width including rowspanned cells.
  240. lengths[ row ] = column;
  241. }
  242. lengths[ row ] += colspan;
  243. const maxRows = table.childCount;
  244. if ( headingRows > row ) {
  245. if ( row + rowspan > headingRows ) {
  246. const newRowspan = headingRows - row;
  247. cellsToTrim.push( { cell: data.cell, rowspan: newRowspan } );
  248. }
  249. } else {
  250. if ( row + rowspan + headingRows > maxRows ) {
  251. const newRowspan = maxRows - row - headingRows + 1;
  252. cellsToTrim.push( { cell: data.cell, rowspan: newRowspan } );
  253. }
  254. }
  255. }
  256. return { lengths, cellsToTrim };
  257. }
  258. function fixTableOnInsert( tableUtils, table, writer, wasFixed ) {
  259. const tableSize = tableUtils.getColumns( table );
  260. const { lengths, cellsToTrim } = getRowsLengths( table );
  261. const isValid = Object.values( lengths ).every( length => length === tableSize );
  262. if ( !isValid ) {
  263. const maxColumns = Object.values( lengths ).reduce( ( prev, current ) => current > prev ? current : prev, 0 );
  264. for ( const [ rowIndex, size ] of Object.entries( lengths ) ) {
  265. const columnsToInsert = maxColumns - size;
  266. if ( columnsToInsert ) {
  267. for ( let i = 0; i < columnsToInsert; i++ ) {
  268. writer.insertElement( 'tableCell', Position.createAt( table.getChild( rowIndex ), 'end' ) );
  269. }
  270. wasFixed = true;
  271. }
  272. }
  273. }
  274. if ( cellsToTrim.length ) {
  275. for ( const data of cellsToTrim ) {
  276. updateNumericAttribute( 'rowspan', data.rowspan, data.cell, writer, 1 );
  277. }
  278. }
  279. return wasFixed;
  280. }
  281. function fixTableOnRemoveCells( tableRowsToCheck, writer ) {
  282. let wasFixed = false;
  283. if ( !tableRowsToCheck.length ) {
  284. return wasFixed;
  285. }
  286. const indexes = tableRowsToCheck.map( tableRow => tableRow.index );
  287. const table = tableRowsToCheck[ 0 ].parent;
  288. const allIndexes = [ ...table.getChildren() ].map( tableRow => tableRow.index );
  289. const other = allIndexes.filter( index => !indexes.includes( index ) );
  290. const { lengths } = getRowsLengths( table );
  291. const areSame = indexes.every( index => lengths[ index ] === lengths[ 0 ] );
  292. if ( areSame ) {
  293. const properLength = lengths[ 0 ];
  294. other.map( index => {
  295. let length = lengths[ index ];
  296. const tableRow = table.getChild( index );
  297. while ( length > properLength ) {
  298. const tableCell = tableRow.getChild( tableRow.childCount - 1 );
  299. const howMany = length - properLength;
  300. const colspan = parseInt( tableCell.getAttribute( 'colspan' ) || 1 );
  301. if ( colspan > howMany ) {
  302. writer.setAttribute( 'colspan', colspan - howMany, tableCell );
  303. length = properLength;
  304. } else {
  305. writer.remove( tableCell );
  306. length -= colspan;
  307. }
  308. length = properLength - 10;
  309. wasFixed = true;
  310. }
  311. } );
  312. }
  313. return wasFixed;
  314. }