utils.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. /**
  2. * @license Copyright (c) 2003-2020, 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/ui/utils
  7. */
  8. import BalloonPanelView from '@ckeditor/ckeditor5-ui/src/panel/balloon/balloonpanelview';
  9. import ButtonView from '@ckeditor/ckeditor5-ui/src/button/buttonview';
  10. import Collection from '@ckeditor/ckeditor5-utils/src/collection';
  11. import Model from '@ckeditor/ckeditor5-ui/src/model';
  12. import ColorInputView from './colorinputview';
  13. import { isColor, isLength, isPercentage } from '@ckeditor/ckeditor5-engine/src/view/styles/utils';
  14. import { getTableWidgetAncestor } from '../utils';
  15. import { findAncestor } from '../commands/utils';
  16. import Rect from '@ckeditor/ckeditor5-utils/src/dom/rect';
  17. import { centeredBalloonPositionForLongWidgets } from '@ckeditor/ckeditor5-widget/src/utils';
  18. const DEFAULT_BALLOON_POSITIONS = BalloonPanelView.defaultPositions;
  19. const BALLOON_POSITIONS = [
  20. DEFAULT_BALLOON_POSITIONS.northArrowSouth,
  21. DEFAULT_BALLOON_POSITIONS.northArrowSouthWest,
  22. DEFAULT_BALLOON_POSITIONS.northArrowSouthEast,
  23. DEFAULT_BALLOON_POSITIONS.southArrowNorth,
  24. DEFAULT_BALLOON_POSITIONS.southArrowNorthWest,
  25. DEFAULT_BALLOON_POSITIONS.southArrowNorthEast
  26. ];
  27. const TABLE_PROPERTIES_BALLOON_POSITIONS = [
  28. ...BALLOON_POSITIONS,
  29. centeredBalloonPositionForLongWidgets
  30. ];
  31. const isEmpty = val => val === '';
  32. /**
  33. * A helper utility that positions the
  34. * {@link module:ui/panel/balloon/contextualballoon~ContextualBalloon contextual balloon} instance
  35. * with respect to the table in the editor content, if one is selected.
  36. *
  37. * @param {module:core/editor/editor~Editor} editor The editor instance.
  38. * @param {String} target Either "cell" or "table". Determines the target the balloon will
  39. * be attached to.
  40. */
  41. export function repositionContextualBalloon( editor, target ) {
  42. const balloon = editor.plugins.get( 'ContextualBalloon' );
  43. if ( getTableWidgetAncestor( editor.editing.view.document.selection ) ) {
  44. let position;
  45. if ( target === 'cell' ) {
  46. position = getBalloonCellPositionData( editor );
  47. } else {
  48. position = getBalloonTablePositionData( editor );
  49. }
  50. balloon.updatePosition( position );
  51. }
  52. }
  53. /**
  54. * Returns the positioning options that control the geometry of the
  55. * {@link module:ui/panel/balloon/contextualballoon~ContextualBalloon contextual balloon} with respect
  56. * to the selected table in the editor content.
  57. *
  58. * @param {module:core/editor/editor~Editor} editor The editor instance.
  59. * @returns {module:utils/dom/position~Options}
  60. */
  61. export function getBalloonTablePositionData( editor ) {
  62. const firstPosition = editor.model.document.selection.getFirstPosition();
  63. const modelTable = findAncestor( 'table', firstPosition );
  64. const viewTable = editor.editing.mapper.toViewElement( modelTable );
  65. return {
  66. target: editor.editing.view.domConverter.viewToDom( viewTable ),
  67. positions: TABLE_PROPERTIES_BALLOON_POSITIONS
  68. };
  69. }
  70. /**
  71. * Returns the positioning options that control the geometry of the
  72. * {@link module:ui/panel/balloon/contextualballoon~ContextualBalloon contextual balloon} with respect
  73. * to the selected table cell in the editor content.
  74. *
  75. * @param {module:core/editor/editor~Editor} editor The editor instance.
  76. * @returns {module:utils/dom/position~Options}
  77. */
  78. export function getBalloonCellPositionData( editor ) {
  79. const mapper = editor.editing.mapper;
  80. const domConverter = editor.editing.view.domConverter;
  81. const selection = editor.model.document.selection;
  82. if ( selection.rangeCount > 1 ) {
  83. return {
  84. target: () => createBoundingRect( selection.getRanges(), modelRange => {
  85. const modelTableCell = getTableCellAtPosition( modelRange.start );
  86. const viewTableCell = mapper.toViewElement( modelTableCell );
  87. return new Rect( domConverter.viewToDom( viewTableCell ) );
  88. } ),
  89. positions: BALLOON_POSITIONS
  90. };
  91. }
  92. const modelTableCell = getTableCellAtPosition( selection.getFirstPosition() );
  93. const viewTableCell = mapper.toViewElement( modelTableCell );
  94. return {
  95. target: domConverter.viewToDom( viewTableCell ),
  96. positions: BALLOON_POSITIONS
  97. };
  98. }
  99. /**
  100. * Returns an object containing pairs of CSS border style values and their localized UI
  101. * labels. Used by {@link module:table/tablecellproperties/ui/tablecellpropertiesview~TableCellPropertiesView}
  102. * and {@link module:table/tableproperties/ui/tablepropertiesview~TablePropertiesView}.
  103. *
  104. * @param {module:utils/locale~Locale#t} t The "t" function provided by the editor
  105. * that is used to localize strings.
  106. * @returns {Object.<String,String>}
  107. */
  108. export function getBorderStyleLabels( t ) {
  109. return {
  110. none: t( 'None' ),
  111. solid: t( 'Solid' ),
  112. dotted: t( 'Dotted' ),
  113. dashed: t( 'Dashed' ),
  114. double: t( 'Double' ),
  115. groove: t( 'Groove' ),
  116. ridge: t( 'Ridge' ),
  117. inset: t( 'Inset' ),
  118. outset: t( 'Outset' )
  119. };
  120. }
  121. /**
  122. * Returns a localized error string that can be displayed next to color (background, border)
  123. * fields that have an invalid value.
  124. *
  125. * @param {module:utils/locale~Locale#t} t The "t" function provided by the editor
  126. * that is used to localize strings.
  127. * @returns {String}
  128. */
  129. export function getLocalizedColorErrorText( t ) {
  130. return t( 'The color is invalid. Try "#FF0000" or "rgb(255,0,0)" or "red".' );
  131. }
  132. /**
  133. * Returns a localized error string that can be displayed next to length (padding, border width)
  134. * fields that have an invalid value.
  135. *
  136. * @param {module:utils/locale~Locale#t} t The "t" function provided by the editor
  137. * that is used to localize strings.
  138. * @returns {String}
  139. */
  140. export function getLocalizedLengthErrorText( t ) {
  141. return t( 'The value is invalid. Try "10px" or "2em" or simply "2".' );
  142. }
  143. /**
  144. * Returns `true` when the passed value is an empty string or a valid CSS color expression.
  145. * Otherwise, `false` is returned.
  146. *
  147. * See {@link module:engine/view/styles/utils~isColor}.
  148. *
  149. * @param {String} value
  150. * @returns {Boolean}
  151. */
  152. export function colorFieldValidator( value ) {
  153. value = value.trim();
  154. return isEmpty( value ) || isColor( value );
  155. }
  156. /**
  157. * Returns `true` when the passed value is an empty string, a number without a unit or a valid CSS length expression.
  158. * Otherwise, `false` is returned.
  159. *
  160. * See {@link module:engine/view/styles/utils~isLength}.
  161. * See {@link module:engine/view/styles/utils~isPercentage}.
  162. *
  163. * @param {String} value
  164. * @returns {Boolean}
  165. */
  166. export function lengthFieldValidator( value ) {
  167. value = value.trim();
  168. return isEmpty( value ) || isNumberString( value ) || isLength( value ) || isPercentage( value );
  169. }
  170. /**
  171. * Returns `true` when the passed value is an empty string, a number without a unit or a valid CSS length expression.
  172. * Otherwise, `false` is returned.
  173. *
  174. * See {@link module:engine/view/styles/utils~isLength}.
  175. *
  176. * @param {String} value
  177. * @returns {Boolean}
  178. */
  179. export function lineWidthFieldValidator( value ) {
  180. value = value.trim();
  181. return isEmpty( value ) || isNumberString( value ) || isLength( value );
  182. }
  183. /**
  184. * Generates item definitions for a UI dropdown that allows changing the border style of a table or a table cell.
  185. *
  186. * @param {module:table/tablecellproperties/ui/tablecellpropertiesview~TableCellPropertiesView|
  187. * module:table/tableproperties/ui/tablepropertiesview~TablePropertiesView} view
  188. * @returns {Iterable.<module:ui/dropdown/utils~ListDropdownItemDefinition>}
  189. */
  190. export function getBorderStyleDefinitions( view ) {
  191. const itemDefinitions = new Collection();
  192. const styleLabels = getBorderStyleLabels( view.t );
  193. for ( const style in styleLabels ) {
  194. const definition = {
  195. type: 'button',
  196. model: new Model( {
  197. _borderStyleValue: style === 'none' ? '' : style,
  198. label: styleLabels[ style ],
  199. withText: true
  200. } )
  201. };
  202. if ( style === 'none' ) {
  203. definition.model.bind( 'isOn' ).to( view, 'borderStyle', value => !value );
  204. } else {
  205. definition.model.bind( 'isOn' ).to( view, 'borderStyle', value => {
  206. return value === style;
  207. } );
  208. }
  209. itemDefinitions.add( definition );
  210. }
  211. return itemDefinitions;
  212. }
  213. /**
  214. * A helper that fills a toolbar with buttons that:
  215. *
  216. * * have some labels,
  217. * * have some icons,
  218. * * set a certain UI view property value upon execution.
  219. *
  220. * @param {Object} options
  221. * @param {module:table/tablecellproperties/ui/tablecellpropertiesview~TableCellPropertiesView|
  222. * module:table/tableproperties/ui/tablepropertiesview~TablePropertiesView} options.view
  223. * @param {Array.<String>} options.icons
  224. * @param {module:ui/toolbar/toolbarview~ToolbarView} options.toolbar
  225. * @param {Object.<String,String>} labels
  226. * @param {String} propertyName
  227. * @param {Function} nameToValue A function that maps a button name to a value. By default names are the same as values.
  228. */
  229. export function fillToolbar( { view, icons, toolbar, labels, propertyName, nameToValue } ) {
  230. for ( const name in labels ) {
  231. const button = new ButtonView( view.locale );
  232. button.set( {
  233. label: labels[ name ],
  234. icon: icons[ name ],
  235. tooltip: labels[ name ]
  236. } );
  237. button.bind( 'isOn' ).to( view, propertyName, value => {
  238. return value === nameToValue( name );
  239. } );
  240. button.on( 'execute', () => {
  241. view[ propertyName ] = nameToValue( name );
  242. } );
  243. toolbar.items.add( button );
  244. }
  245. }
  246. /**
  247. * A default color palette used by various user interfaces related to tables, for instance,
  248. * by {@link module:table/tablecellproperties/tablecellpropertiesui~TableCellPropertiesUI} or
  249. * {@link module:table/tableproperties/tablepropertiesui~TablePropertiesUI}.
  250. *
  251. * The color palette follows the {@link module:table/table~TableColorConfig table color configuration format}
  252. * and contains the following color definitions:
  253. *
  254. * const defaultColors = [
  255. * {
  256. * color: 'hsl(0, 0%, 0%)',
  257. * label: 'Black'
  258. * },
  259. * {
  260. * color: 'hsl(0, 0%, 30%)',
  261. * label: 'Dim grey'
  262. * },
  263. * {
  264. * color: 'hsl(0, 0%, 60%)',
  265. * label: 'Grey'
  266. * },
  267. * {
  268. * color: 'hsl(0, 0%, 90%)',
  269. * label: 'Light grey'
  270. * },
  271. * {
  272. * color: 'hsl(0, 0%, 100%)',
  273. * label: 'White',
  274. * hasBorder: true
  275. * },
  276. * {
  277. * color: 'hsl(0, 75%, 60%)',
  278. * label: 'Red'
  279. * },
  280. * {
  281. * color: 'hsl(30, 75%, 60%)',
  282. * label: 'Orange'
  283. * },
  284. * {
  285. * color: 'hsl(60, 75%, 60%)',
  286. * label: 'Yellow'
  287. * },
  288. * {
  289. * color: 'hsl(90, 75%, 60%)',
  290. * label: 'Light green'
  291. * },
  292. * {
  293. * color: 'hsl(120, 75%, 60%)',
  294. * label: 'Green'
  295. * },
  296. * {
  297. * color: 'hsl(150, 75%, 60%)',
  298. * label: 'Aquamarine'
  299. * },
  300. * {
  301. * color: 'hsl(180, 75%, 60%)',
  302. * label: 'Turquoise'
  303. * },
  304. * {
  305. * color: 'hsl(210, 75%, 60%)',
  306. * label: 'Light blue'
  307. * },
  308. * {
  309. * color: 'hsl(240, 75%, 60%)',
  310. * label: 'Blue'
  311. * },
  312. * {
  313. * color: 'hsl(270, 75%, 60%)',
  314. * label: 'Purple'
  315. * }
  316. * ];
  317. */
  318. export const defaultColors = [
  319. {
  320. color: 'hsl(0, 0%, 0%)',
  321. label: 'Black'
  322. },
  323. {
  324. color: 'hsl(0, 0%, 30%)',
  325. label: 'Dim grey'
  326. },
  327. {
  328. color: 'hsl(0, 0%, 60%)',
  329. label: 'Grey'
  330. },
  331. {
  332. color: 'hsl(0, 0%, 90%)',
  333. label: 'Light grey'
  334. },
  335. {
  336. color: 'hsl(0, 0%, 100%)',
  337. label: 'White',
  338. hasBorder: true
  339. },
  340. {
  341. color: 'hsl(0, 75%, 60%)',
  342. label: 'Red'
  343. },
  344. {
  345. color: 'hsl(30, 75%, 60%)',
  346. label: 'Orange'
  347. },
  348. {
  349. color: 'hsl(60, 75%, 60%)',
  350. label: 'Yellow'
  351. },
  352. {
  353. color: 'hsl(90, 75%, 60%)',
  354. label: 'Light green'
  355. },
  356. {
  357. color: 'hsl(120, 75%, 60%)',
  358. label: 'Green'
  359. },
  360. {
  361. color: 'hsl(150, 75%, 60%)',
  362. label: 'Aquamarine'
  363. },
  364. {
  365. color: 'hsl(180, 75%, 60%)',
  366. label: 'Turquoise'
  367. },
  368. {
  369. color: 'hsl(210, 75%, 60%)',
  370. label: 'Light blue'
  371. },
  372. {
  373. color: 'hsl(240, 75%, 60%)',
  374. label: 'Blue'
  375. },
  376. {
  377. color: 'hsl(270, 75%, 60%)',
  378. label: 'Purple'
  379. }
  380. ];
  381. /**
  382. * Returns a creator for a color input with a label.
  383. *
  384. * For given options, it returns a function that creates an instance of a
  385. * {@link module:table/ui/colorinputview~ColorInputView color input} logically related to
  386. * a {@link module:ui/labeledfield/labeledfieldview~LabeledFieldView labeled view} in the DOM.
  387. *
  388. * The helper does the following:
  389. *
  390. * * It sets the color input `id` and `ariaDescribedById` attributes.
  391. * * It binds the color input `isReadOnly` to the labeled view.
  392. * * It binds the color input `hasError` to the labeled view.
  393. * * It enables a logic that cleans up the error when the user starts typing in the color input.
  394. *
  395. * Usage:
  396. *
  397. * const colorInputCreator = getLabeledColorInputCreator( {
  398. * colorConfig: [ ... ],
  399. * columns: 3,
  400. * } );
  401. *
  402. * const labeledInputView = new LabeledFieldView( locale, colorInputCreator );
  403. * console.log( labeledInputView.view ); // A color input instance.
  404. *
  405. * @private
  406. * @param options Color input options.
  407. * @param {module:table/table~TableColorConfig} options.colorConfig The configuration of the color palette
  408. * displayed in the input's dropdown.
  409. * @param {Number} options.columns The configuration of the number of columns the color palette consists of
  410. * in the input's dropdown.
  411. * @returns {Function}
  412. */
  413. export function getLabeledColorInputCreator( options ) {
  414. return ( labeledFieldView, viewUid, statusUid ) => {
  415. const inputView = new ColorInputView( labeledFieldView.locale, {
  416. colorDefinitions: colorConfigToColorGridDefinitions( options.colorConfig ),
  417. columns: options.columns
  418. } );
  419. inputView.set( {
  420. id: viewUid,
  421. ariaDescribedById: statusUid
  422. } );
  423. inputView.bind( 'isReadOnly' ).to( labeledFieldView, 'isEnabled', value => !value );
  424. inputView.bind( 'errorText' ).to( labeledFieldView );
  425. inputView.on( 'input', () => {
  426. // UX: Make the error text disappear and disable the error indicator as the user
  427. // starts fixing the errors.
  428. labeledFieldView.errorText = null;
  429. } );
  430. return inputView;
  431. };
  432. }
  433. // A simple helper method to detect number strings.
  434. // I allows full number notation, so omitting 0 is not allowed:
  435. function isNumberString( value ) {
  436. const parsedValue = parseFloat( value );
  437. return !Number.isNaN( parsedValue ) && value === String( parsedValue );
  438. }
  439. // @param {Array.<Object>} colorConfig
  440. // @returns {Array.<module:ui/colorgrid/colorgrid~ColorDefinition>}
  441. function colorConfigToColorGridDefinitions( colorConfig ) {
  442. return colorConfig.map( item => ( {
  443. color: item.model,
  444. label: item.label,
  445. options: {
  446. hasBorder: item.hasBorder
  447. }
  448. } ) );
  449. }
  450. // Returns the first selected table cell from a multi-cell or in-cell selection.
  451. //
  452. // @param {module:engine/model/position~Position} position Document position.
  453. // @returns {module:engine/model/element~Element}
  454. function getTableCellAtPosition( position ) {
  455. const isTableCellSelected = position.nodeAfter && position.nodeAfter.is( 'tableCell' );
  456. return isTableCellSelected ? position.nodeAfter : findAncestor( 'tableCell', position );
  457. }
  458. // Returns bounding rect for list of rects.
  459. //
  460. // @param {Array.<module:utils/dom/rect~Rect>|Array.<*>} list List of `Rect`s or any list to map by `mapFn`.
  461. // @param {Function} mapFn Mapping function for list elements.
  462. // @returns {module:utils/dom/rect~Rect}
  463. function createBoundingRect( list, mapFn ) {
  464. const rectData = {
  465. left: Number.POSITIVE_INFINITY,
  466. top: Number.POSITIVE_INFINITY,
  467. right: Number.NEGATIVE_INFINITY,
  468. bottom: Number.NEGATIVE_INFINITY
  469. };
  470. for ( const item of list ) {
  471. const rect = mapFn( item );
  472. rectData.left = Math.min( rectData.left, rect.left );
  473. rectData.top = Math.min( rectData.top, rect.top );
  474. rectData.right = Math.max( rectData.right, rect.right );
  475. rectData.bottom = Math.max( rectData.bottom, rect.bottom );
  476. }
  477. rectData.width = rectData.right - rectData.left;
  478. rectData.height = rectData.bottom - rectData.top;
  479. return new Rect( rectData );
  480. }