tablecellhorizontalalignmentcommand.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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/tablecellhorizontalalignmentcommand
  7. */
  8. import Command from '@ckeditor/ckeditor5-core/src/command';
  9. import { findAncestor } from './utils';
  10. /**
  11. * The table cell horizontal alignment command.
  12. *
  13. * The command is registered by {@link module:table/tablecellpropertiesediting~TableCellPropertiesEditing} as
  14. * `'tableCellHorizontalAlignment'` editor command.
  15. *
  16. * To change cell horizontal alignment of the selected cell, execute the command:
  17. *
  18. * editor.execute( 'tableCellHorizontalAlignment', {
  19. * value: '5px'
  20. * } );
  21. *
  22. * @extends module:core/command~Command
  23. */
  24. export default class TableCellHorizontalAlignmentCommand extends Command {
  25. constructor( editor ) {
  26. super( editor );
  27. this.attributeName = 'horizontalAlignment';
  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 horizontal alignment.
  51. * If horizontal alignment is not set the command will remove the attribute.
  52. */
  53. execute( options = {} ) {
  54. const model = this.editor.model;
  55. const selection = model.document.selection;
  56. const { value } = options;
  57. const tableCells = Array.from( selection.getSelectedBlocks() )
  58. .map( element => findAncestor( 'tableCell', model.createPositionAt( element, 0 ) ) );
  59. model.change( writer => {
  60. if ( value ) {
  61. tableCells.forEach( tableCell => writer.setAttribute( this.attributeName, value, tableCell ) );
  62. } else {
  63. tableCells.forEach( tableCell => writer.removeAttribute( this.attributeName, tableCell ) );
  64. }
  65. } );
  66. }
  67. }