insertrowcommand.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /**
  2. * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module table/insertrowcommand
  7. */
  8. import Command from '@ckeditor/ckeditor5-core/src/command';
  9. /**
  10. * The insert row command.
  11. *
  12. * @extends module:core/command~Command
  13. */
  14. export default class InsertRowCommand extends Command {
  15. /**
  16. * @inheritDoc
  17. */
  18. refresh() {
  19. const model = this.editor.model;
  20. const doc = model.document;
  21. const tableParent = getValidParent( doc.selection.getFirstPosition() );
  22. this.isEnabled = !!tableParent;
  23. }
  24. /**
  25. * Executes the command.
  26. *
  27. * @param {Object} [options] Options for the executed command.
  28. * @param {Number} [options.rows=1] Number of rows to insert.
  29. * @param {Number} [options.at=0] Row index to insert at.
  30. *
  31. * @fires execute
  32. */
  33. execute( options = {} ) {
  34. const model = this.editor.model;
  35. const document = model.document;
  36. const selection = document.selection;
  37. const rows = parseInt( options.rows ) || 1;
  38. const insertAt = parseInt( options.at ) || 0;
  39. const table = getValidParent( selection.getFirstPosition() );
  40. const headingRows = table.getAttribute( 'headingRows' ) || 0;
  41. const columns = getColumns( table );
  42. model.change( writer => {
  43. if ( headingRows > insertAt ) {
  44. writer.setAttribute( 'headingRows', headingRows + rows, table );
  45. }
  46. // TODO: test me - I'm wrong
  47. for ( let rowIndex = 0; rowIndex < rows; rowIndex++ ) {
  48. const row = writer.createElement( 'tableRow' );
  49. writer.insert( row, table, insertAt );
  50. for ( let column = 0; column < columns; column++ ) {
  51. const cell = writer.createElement( 'tableCell' );
  52. writer.insert( cell, row, 'end' );
  53. }
  54. }
  55. } );
  56. }
  57. }
  58. function getValidParent( firstPosition ) {
  59. let parent = firstPosition.parent;
  60. while ( parent ) {
  61. if ( parent.name === 'table' ) {
  62. return parent;
  63. }
  64. parent = parent.parent;
  65. }
  66. }
  67. function getColumns( table ) {
  68. const row = table.getChild( 0 );
  69. return [ ...row.getChildren() ].reduce( ( columns, row ) => {
  70. const columnWidth = parseInt( row.getAttribute( 'colspan' ) ) || 1;
  71. return columns + ( columnWidth );
  72. }, 0 );
  73. }