tablecellwidthcommand.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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/commands/tablecellwidthcommand
  7. */
  8. import Command from '@ckeditor/ckeditor5-core/src/command';
  9. import { findAncestor } from './utils';
  10. /**
  11. * The table cell width command.
  12. *
  13. * The command is registered by {@link module:table/tablecellpropertiesediting~TableCellPropertiesEditing} as
  14. * `'tableCellWidth'` editor command.
  15. *
  16. * To change cell width of the selected cell, execute the command:
  17. *
  18. * editor.execute( 'tableCellWidth', {
  19. * value: '5px'
  20. * } );
  21. *
  22. * @extends module:core/command~Command
  23. */
  24. export default class TableCellWidthCommand extends Command {
  25. constructor( editor ) {
  26. super( editor );
  27. this.attributeName = 'width';
  28. }
  29. /**
  30. * @inheritDoc
  31. */
  32. refresh() {
  33. const editor = this.editor;
  34. const selection = editor.model.document.selection;
  35. const tableCell = findAncestor( 'tableCell', selection.getFirstPosition() );
  36. this.isEnabled = !!tableCell;
  37. this.value = this._getValue( tableCell );
  38. }
  39. _getValue( tableCell ) {
  40. if ( !tableCell ) {
  41. return;
  42. }
  43. return tableCell.getAttribute( this.attributeName );
  44. }
  45. /**
  46. * Executes the command.
  47. *
  48. * @fires execute
  49. * @param {Object} [options]
  50. * @param {Boolean} [options.value] If set the command will set width. If width is not set the command will remove the attribute.
  51. */
  52. execute( options = {} ) {
  53. const model = this.editor.model;
  54. const selection = model.document.selection;
  55. const { value } = options;
  56. const tableCells = Array.from( selection.getSelectedBlocks() )
  57. .map( element => findAncestor( 'tableCell', model.createPositionAt( element, 0 ) ) );
  58. model.change( writer => {
  59. if ( value ) {
  60. tableCells.forEach( tableCell => writer.setAttribute( this.attributeName, value, tableCell ) );
  61. } else {
  62. tableCells.forEach( tableCell => writer.removeAttribute( this.attributeName, tableCell ) );
  63. }
  64. } );
  65. }
  66. }