extending-content-allow-div-attributes.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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 ConvertDivAttributes( editor ) {
  8. // Allow <div> elements in the model.
  9. editor.model.schema.register( 'div', {
  10. allowWhere: '$block',
  11. allowContentOf: '$root'
  12. } );
  13. // Allow <div> elements in the model to have all attributes.
  14. editor.model.schema.addAttributeCheck( context => {
  15. if ( context.endsWith( 'div' ) ) {
  16. return true;
  17. }
  18. } );
  19. // View-to-model converter converting a view <div> with all its attributes to the model.
  20. editor.conversion.for( 'upcast' ).elementToElement( {
  21. view: 'div',
  22. model: ( viewElement, { writer: modelWriter } ) => {
  23. return modelWriter.createElement( 'div', viewElement.getAttributes() );
  24. }
  25. } );
  26. // Model-to-view converter for the <div> element (attrbiutes are converted separately).
  27. editor.conversion.for( 'downcast' ).elementToElement( {
  28. model: 'div',
  29. view: 'div'
  30. } );
  31. // Model-to-view converter for <div> attributes.
  32. // Note that a lower-level, event-based API is used here.
  33. editor.conversion.for( 'downcast' ).add( dispatcher => {
  34. dispatcher.on( 'attribute', ( evt, data, conversionApi ) => {
  35. // Convert <div> attributes only.
  36. if ( data.item.name != 'div' ) {
  37. return;
  38. }
  39. const viewWriter = conversionApi.writer;
  40. const viewDiv = conversionApi.mapper.toViewElement( data.item );
  41. // In the model-to-view conversion we convert changes. An attribute can be added or removed or changed.
  42. // The below code handles all 3 cases.
  43. if ( data.attributeNewValue ) {
  44. viewWriter.setAttribute( data.attributeKey, data.attributeNewValue, viewDiv );
  45. } else {
  46. viewWriter.removeAttribute( data.attributeKey, viewDiv );
  47. }
  48. } );
  49. } );
  50. }
  51. ClassicEditor
  52. .create( document.querySelector( '#snippet-div-attributes' ), {
  53. cloudServices: CS_CONFIG,
  54. extraPlugins: [ ConvertDivAttributes ],
  55. toolbar: {
  56. viewportTopOffset: window.getViewportTopOffsetConfig()
  57. }
  58. } )
  59. .then( editor => {
  60. window.editor = editor;
  61. } )
  62. .catch( err => {
  63. console.error( err.stack );
  64. } );