tablepropertiesui.js 11 KB

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