tablecellpropertiesui.js 12 KB

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