tablecellpropertiesui.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. /**
  2. * @license Copyright (c) 2003-2019, 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/tablecellproperties/tablecellpropertiesui
  7. */
  8. import Plugin from '@ckeditor/ckeditor5-core/src/plugin';
  9. import ButtonView from '@ckeditor/ckeditor5-ui/src/button/buttonview';
  10. import { getTableWidgetAncestor } from '../utils';
  11. import clickOutsideHandler from '@ckeditor/ckeditor5-ui/src/bindings/clickoutsidehandler';
  12. import ContextualBalloon from '@ckeditor/ckeditor5-ui/src/panel/balloon/contextualballoon';
  13. import TableCellPropertiesView from './ui/tablecellpropertiesview';
  14. import tableCellProperties from './../../theme/icons/table-cell-properties.svg';
  15. import {
  16. repositionContextualBalloon,
  17. getBalloonCellPositionData,
  18. getLocalizedColorErrorText,
  19. getLocalizedLengthErrorText,
  20. colorFieldValidator,
  21. lengthFieldValidator,
  22. defaultColors
  23. } from '../ui/utils';
  24. import {
  25. getLocalizedColorOptions,
  26. normalizeColorOptions
  27. } from '@ckeditor/ckeditor5-ui/src/colorgrid/utils';
  28. import { debounce } from 'lodash-es';
  29. const DEFAULT_BORDER_STYLE = 'none';
  30. const DEFAULT_HORIZONTAL_ALIGNMENT = 'left';
  31. const DEFAULT_VERTICAL_ALIGNMENT = 'middle';
  32. const ERROR_TEXT_TIMEOUT = 500;
  33. /**
  34. * The table cell properties UI plugin. It introduces the `'tableCellProperties'` button
  35. * that opens a form allowing to specify visual styling of a table cell.
  36. *
  37. * It uses the
  38. * {@link module:ui/panel/balloon/contextualballoon~ContextualBalloon contextual balloon plugin}.
  39. *
  40. * @extends module:core/plugin~Plugin
  41. */
  42. export default class TableCellPropertiesUI extends Plugin {
  43. /**
  44. * @inheritDoc
  45. */
  46. static get requires() {
  47. return [ ContextualBalloon ];
  48. }
  49. /**
  50. * @inheritDoc
  51. */
  52. static get pluginName() {
  53. return 'TableCellPropertiesUI';
  54. }
  55. /**
  56. * @inheritDoc
  57. */
  58. constructor( editor ) {
  59. super( editor );
  60. editor.config.define( 'table.tableCellProperties', {
  61. border: {
  62. colors: defaultColors
  63. },
  64. backgroundColors: defaultColors
  65. } );
  66. }
  67. /**
  68. * @inheritDoc
  69. */
  70. init() {
  71. const editor = this.editor;
  72. const t = editor.t;
  73. /**
  74. * The contextual balloon plugin instance.
  75. *
  76. * @private
  77. * @member {module:ui/panel/balloon/contextualballoon~ContextualBalloon}
  78. */
  79. this._balloon = editor.plugins.get( ContextualBalloon );
  80. /**
  81. * The cell properties form view displayed inside the balloon.
  82. *
  83. * @member {module:table/tablecellproperties/ui/tablecellpropertiesview~TableCellPropertiesView}
  84. */
  85. this.view = this._createPropertiesView();
  86. /**
  87. * The batch used to undo all changes made by the form (which are live, as the user types)
  88. * when "Cancel" was pressed. Each time the view is shown, a new batch is created.
  89. *
  90. * @protected
  91. * @member {module:engine/model/batch~Batch}
  92. */
  93. this._undoStepBatch = null;
  94. editor.ui.componentFactory.add( 'tableCellProperties', locale => {
  95. const view = new ButtonView( locale );
  96. view.set( {
  97. label: t( 'Cell properties' ),
  98. icon: tableCellProperties,
  99. tooltip: true
  100. } );
  101. this.listenTo( view, 'execute', () => this._showView() );
  102. return view;
  103. } );
  104. }
  105. /**
  106. * @inheritDoc
  107. */
  108. destroy() {
  109. super.destroy();
  110. // Destroy created UI components as they are not automatically destroyed.
  111. // See https://github.com/ckeditor/ckeditor5/issues/1341.
  112. this.view.destroy();
  113. }
  114. /**
  115. * Creates the {@link module:table/tablecellproperties/ui/tablecellpropertiesview~TableCellPropertiesView} instance.
  116. *
  117. * @private
  118. * @returns {module:table/tablecellproperties/ui/tablecellpropertiesview~TableCellPropertiesView} The cell
  119. * properties form view instance.
  120. */
  121. _createPropertiesView() {
  122. const editor = this.editor;
  123. const viewDocument = editor.editing.view.document;
  124. const config = editor.config.get( 'table.tableCellProperties' );
  125. const borderColorsConfig = normalizeColorOptions( config.border.colors );
  126. const localizedBorderColors = getLocalizedColorOptions( editor.locale, borderColorsConfig );
  127. const backgroundColorsConfig = normalizeColorOptions( config.backgroundColors );
  128. const localizedBackgroundColors = getLocalizedColorOptions( editor.locale, backgroundColorsConfig );
  129. const view = new TableCellPropertiesView( editor.locale, {
  130. borderColors: localizedBorderColors,
  131. backgroundColors: localizedBackgroundColors
  132. } );
  133. const t = editor.t;
  134. // Render the view so its #element is available for the clickOutsideHandler.
  135. view.render();
  136. this.listenTo( view, 'submit', () => {
  137. this._hideView();
  138. } );
  139. this.listenTo( view, 'cancel', () => {
  140. // https://github.com/ckeditor/ckeditor5/issues/6180
  141. if ( this._undoStepBatch.operations.length ) {
  142. editor.execute( 'undo', this._undoStepBatch );
  143. }
  144. this._hideView();
  145. } );
  146. // Close the balloon on Esc key press.
  147. view.keystrokes.set( 'Esc', ( data, cancel ) => {
  148. this._hideView();
  149. cancel();
  150. } );
  151. // Reposition the balloon or hide the form if a table cell is no longer selected.
  152. this.listenTo( editor.ui, 'update', () => {
  153. if ( !getTableWidgetAncestor( viewDocument.selection ) ) {
  154. this._hideView();
  155. } else if ( this._isViewVisible ) {
  156. repositionContextualBalloon( editor, 'cell' );
  157. }
  158. } );
  159. // Close on click outside of balloon panel element.
  160. clickOutsideHandler( {
  161. emitter: view,
  162. activator: () => this._isViewInBalloon,
  163. contextElements: [ this._balloon.view.element ],
  164. callback: () => this._hideView()
  165. } );
  166. const colorErrorText = getLocalizedColorErrorText( t );
  167. const lengthErrorText = getLocalizedLengthErrorText( t );
  168. // Create the "UI -> editor data" binding.
  169. // These listeners update the editor data (via table commands) when any observable
  170. // property of the view has changed. They also validate the value and display errors in the UI
  171. // when necessary. This makes the view live, which means the changes are
  172. // visible in the editing as soon as the user types or changes fields' values.
  173. view.on( 'change:borderStyle', this._getPropertyChangeCallback( 'tableCellBorderStyle' ) );
  174. view.on( 'change:borderColor', this._getValidatedPropertyChangeCallback( {
  175. viewField: view.borderColorInput,
  176. commandName: 'tableCellBorderColor',
  177. errorText: colorErrorText,
  178. validator: colorFieldValidator
  179. } ) );
  180. view.on( 'change:borderWidth', this._getValidatedPropertyChangeCallback( {
  181. viewField: view.borderWidthInput,
  182. commandName: 'tableCellBorderWidth',
  183. errorText: lengthErrorText,
  184. validator: lengthFieldValidator
  185. } ) );
  186. view.on( 'change:padding', this._getValidatedPropertyChangeCallback( {
  187. viewField: view.paddingInput,
  188. commandName: 'tableCellPadding',
  189. errorText: lengthErrorText,
  190. validator: lengthFieldValidator
  191. } ) );
  192. view.on( 'change:width', this._getValidatedPropertyChangeCallback( {
  193. viewField: view.widthInput,
  194. commandName: 'tableCellWidth',
  195. errorText: lengthErrorText,
  196. validator: lengthFieldValidator
  197. } ) );
  198. view.on( 'change:height', this._getValidatedPropertyChangeCallback( {
  199. viewField: view.heightInput,
  200. commandName: 'tableCellHeight',
  201. errorText: lengthErrorText,
  202. validator: lengthFieldValidator
  203. } ) );
  204. view.on( 'change:backgroundColor', this._getValidatedPropertyChangeCallback( {
  205. viewField: view.backgroundInput,
  206. commandName: 'tableCellBackgroundColor',
  207. errorText: colorErrorText,
  208. validator: colorFieldValidator
  209. } ) );
  210. view.on( 'change:horizontalAlignment', this._getPropertyChangeCallback( 'tableCellHorizontalAlignment' ) );
  211. view.on( 'change:verticalAlignment', this._getPropertyChangeCallback( 'tableCellVerticalAlignment' ) );
  212. return view;
  213. }
  214. /**
  215. * In this method the "editor data -> UI" binding is happening.
  216. *
  217. * When executed, this method obtains selected cell property values from various table commands
  218. * and passes them to the {@link #view}.
  219. *
  220. * This way, the UI stays up–to–date with the editor data.
  221. *
  222. * @private
  223. */
  224. _fillViewFormFromCommandValues() {
  225. const commands = this.editor.commands;
  226. this.view.set( {
  227. borderStyle: commands.get( 'tableCellBorderStyle' ).value || DEFAULT_BORDER_STYLE,
  228. borderColor: commands.get( 'tableCellBorderColor' ).value || '',
  229. borderWidth: commands.get( 'tableCellBorderWidth' ).value || '',
  230. width: commands.get( 'tableCellWidth' ).value || '',
  231. height: commands.get( 'tableCellHeight' ).value || '',
  232. padding: commands.get( 'tableCellPadding' ).value || '',
  233. backgroundColor: commands.get( 'tableCellBackgroundColor' ).value || '',
  234. horizontalAlignment: commands.get( 'tableCellHorizontalAlignment' ).value || DEFAULT_HORIZONTAL_ALIGNMENT,
  235. verticalAlignment: commands.get( 'tableCellVerticalAlignment' ).value || DEFAULT_VERTICAL_ALIGNMENT,
  236. } );
  237. }
  238. /**
  239. * Shows the {@link #view} in the {@link #_balloon}.
  240. *
  241. * **Note**: Each time a view is shown, the new {@link #_undoStepBatch} is created that contains
  242. * all changes made to the document when the view is visible, allowing a single undo step
  243. * for all of them.
  244. *
  245. * @protected
  246. */
  247. _showView() {
  248. const editor = this.editor;
  249. this._balloon.add( {
  250. view: this.view,
  251. position: getBalloonCellPositionData( editor )
  252. } );
  253. // Create a new batch. Clicking "Cancel" will undo this batch.
  254. this._undoStepBatch = editor.model.createBatch();
  255. // Update the view with the model values.
  256. this._fillViewFormFromCommandValues();
  257. // Basic a11y.
  258. this.view.focus();
  259. }
  260. /**
  261. * Removes the {@link #view} from the {@link #_balloon}.
  262. *
  263. * @protected
  264. */
  265. _hideView() {
  266. if ( !this._isViewInBalloon ) {
  267. return;
  268. }
  269. const editor = this.editor;
  270. this.stopListening( editor.ui, 'update' );
  271. // Blur any input element before removing it from DOM to prevent issues in some browsers.
  272. // See https://github.com/ckeditor/ckeditor5/issues/1501.
  273. this.view.saveButtonView.focus();
  274. this._balloon.remove( this.view );
  275. // Make sure the focus is not lost in the process by putting it directly
  276. // into the editing view.
  277. this.editor.editing.view.focus();
  278. }
  279. /**
  280. * Returns `true` when the {@link #view} is the visible in the {@link #_balloon}.
  281. *
  282. * @private
  283. * @type {Boolean}
  284. */
  285. get _isViewVisible() {
  286. return this._balloon.visibleView === this.view;
  287. }
  288. /**
  289. * Returns `true` when the {@link #view} is in the {@link #_balloon}.
  290. *
  291. * @private
  292. * @type {Boolean}
  293. */
  294. get _isViewInBalloon() {
  295. return this._balloon.hasView( this.view );
  296. }
  297. /**
  298. * Creates a callback that when executed upon {@link #view view's} property change
  299. * executes a related editor command with the new property value.
  300. *
  301. * @private
  302. * @param {String} commandName
  303. * @returns {Function}
  304. */
  305. _getPropertyChangeCallback( commandName ) {
  306. return ( evt, propertyName, newValue ) => {
  307. this.editor.execute( commandName, {
  308. value: newValue,
  309. batch: this._undoStepBatch
  310. } );
  311. };
  312. }
  313. /**
  314. * Creates a callback that when executed upon {@link #view view's} property change:
  315. * * executes a related editor command with the new property value if the value is valid,
  316. * * or sets the error text next to the invalid field, if the value did not pass the validation.
  317. *
  318. * @private
  319. * @param {Object} options
  320. * @param {String} options.commandName
  321. * @param {module:ui/view~View} options.viewField
  322. * @param {Function} options.validator
  323. * @param {String} options.errorText
  324. * @returns {Function}
  325. */
  326. _getValidatedPropertyChangeCallback( { commandName, viewField, validator, errorText } ) {
  327. const setErrorTextDebounced = debounce( () => {
  328. viewField.errorText = errorText;
  329. }, ERROR_TEXT_TIMEOUT );
  330. return ( evt, propertyName, newValue ) => {
  331. setErrorTextDebounced.cancel();
  332. if ( validator( newValue ) ) {
  333. this.editor.execute( commandName, {
  334. value: newValue,
  335. batch: this._undoStepBatch
  336. } );
  337. viewField.errorText = null;
  338. } else {
  339. setErrorTextDebounced();
  340. }
  341. };
  342. }
  343. }