utils.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /**
  2. * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module font/utils
  7. */
  8. import ColorTableView from './ui/colortableview';
  9. /**
  10. * Builds a proper {@link module:engine/conversion/conversion~ConverterDefinition converter definition} out of input data.
  11. *
  12. * @param {String} modelAttributeKey Key
  13. * @param {Array.<module:font/fontfamily~FontFamilyOption>|Array.<module:font/fontsize~FontSizeOption>} options
  14. * @returns {module:engine/conversion/conversion~ConverterDefinition}
  15. */
  16. export function buildDefinition( modelAttributeKey, options ) {
  17. const definition = {
  18. model: {
  19. key: modelAttributeKey,
  20. values: []
  21. },
  22. view: {},
  23. upcastAlso: {}
  24. };
  25. for ( const option of options ) {
  26. definition.model.values.push( option.model );
  27. definition.view[ option.model ] = option.view;
  28. if ( option.upcastAlso ) {
  29. definition.upcastAlso[ option.model ] = option.upcastAlso;
  30. }
  31. }
  32. return definition;
  33. }
  34. export const FONT_COLOR = 'fontColor';
  35. export const FONT_BACKGROUND_COLOR = 'fontBackgroundColor';
  36. export function renderUpcastAttribute( styleAttr ) {
  37. return viewElement => {
  38. const fontColor = viewElement.getStyle( styleAttr );
  39. return normalizeColorCode( fontColor );
  40. };
  41. }
  42. export function renderDowncastElement( styleAttr ) {
  43. return ( modelAttributeValue, viewWriter ) => viewWriter.createAttributeElement( 'span', {
  44. style: `${ styleAttr }:${ modelAttributeValue }`
  45. } );
  46. }
  47. function normalizeColorCode( value ) {
  48. return value.replace( /\s/g, '' );
  49. }
  50. export function normalizeOptions( configuredOptions ) {
  51. return configuredOptions
  52. .map( getOptionDefinition )
  53. .filter( option => !!option );
  54. }
  55. function getOptionDefinition( option ) {
  56. return {
  57. title: option.label,
  58. model: option.color,
  59. label: option.label,
  60. view: {
  61. name: 'span',
  62. styles: {
  63. color: `${ option.color }`
  64. },
  65. priority: 5
  66. }
  67. };
  68. }
  69. export const colorUI = {
  70. addColorsToDropdown( dropdownView, colors ) {
  71. const locale = dropdownView.locale;
  72. const colorTableView = new ColorTableView( locale, { colors } );
  73. dropdownView.colorTableView = colorTableView;
  74. dropdownView.panelView.children.add( colorTableView );
  75. colorTableView.delegate( 'execute' ).to( dropdownView, 'execute' );
  76. return colorTableView;
  77. }
  78. };