tablecellpropertiesui.js 12 KB

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