extending-content-arbitrary-attribute-values.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /**
  2. * @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /* globals ClassicEditor, console, window, document */
  6. import { CS_CONFIG } from '@ckeditor/ckeditor5-cloud-services/tests/_utils/cloud-services-config';
  7. function HandleFontSizeValue( editor ) {
  8. // Add a special catch-all converter for the font size feature.
  9. editor.conversion.for( 'upcast' ).elementToAttribute( {
  10. view: {
  11. name: 'span',
  12. styles: {
  13. 'font-size': /[\s\S]+/
  14. }
  15. },
  16. model: {
  17. key: 'fontSize',
  18. value: viewElement => {
  19. const value = parseFloat( viewElement.getStyle( 'font-size' ) ).toFixed( 0 );
  20. // It might be needed to further convert the value to meet business requirements.
  21. // In the sample the font size is configured to handle only the sizes:
  22. // 12, 14, 'default', 18, 20, 22, 24, 26, 28, 30
  23. // Other sizes will be converted to the model but the UI might not be aware of them.
  24. // The font size feature expects numeric values to be Number, not String.
  25. return parseInt( value );
  26. }
  27. },
  28. converterPriority: 'high'
  29. } );
  30. // Add a special converter for the font size feature to convert all (even not configured)
  31. // model attribute values.
  32. editor.conversion.for( 'downcast' ).attributeToElement( {
  33. model: {
  34. key: 'fontSize'
  35. },
  36. view: ( modelValue, { writer: viewWriter } ) => {
  37. return viewWriter.createAttributeElement( 'span', {
  38. style: `font-size:${ modelValue }px`
  39. } );
  40. },
  41. converterPriority: 'high'
  42. } );
  43. }
  44. ClassicEditor
  45. .create( document.querySelector( '#snippet-arbitrary-attribute-values' ), {
  46. cloudServices: CS_CONFIG,
  47. extraPlugins: [ HandleFontSizeValue ],
  48. toolbar: {
  49. items: [ 'heading', '|', 'bold', 'italic', '|', 'fontSize' ],
  50. viewportTopOffset: window.getViewportTopOffsetConfig()
  51. },
  52. fontSize: {
  53. options: [ 10, 12, 14, 'default', 18, 20, 22 ]
  54. }
  55. } )
  56. .then( editor => {
  57. window.editor = editor;
  58. } )
  59. .catch( err => {
  60. console.error( err.stack );
  61. } );