tablepropertiesui.js 11 KB

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