8
0

tablepropertiesui.js 11 KB

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