converters.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 media-embed/converters
  7. */
  8. /**
  9. * Returns a function that converts the model "url" attribute to the view representation.
  10. *
  11. * Depending on the configuration, the view representation can be "semantic" (for the data pipeline):
  12. *
  13. * <figure class="media">
  14. * <oembed url="foo"></oembed>
  15. * </figure>
  16. *
  17. * or "non-semantic" (for the editing view pipeline):
  18. *
  19. * <figure class="media">
  20. * <div data-oembed-url="foo">[ non-semantic media preview for "foo" ]</div>
  21. * </figure>
  22. *
  23. * **Note:** Changing the model "url" attribute replaces the entire content of the
  24. * `<figure>` in the view.
  25. *
  26. * @param {module:media-embed/mediaregistry~MediaRegistry} registry The registry providing
  27. * the media and their content.
  28. * @param {Object} options
  29. * @param {String} [options.renderMediaPreview] When `true`, the converter will create the view in the non-semantic form.
  30. * @param {String} [options.renderForEditingView] When `true`, the converter will create a view specific for the
  31. * editing pipeline (e.g. including CSS classes, content placeholders).
  32. * @returns {Function}
  33. */
  34. export function modelToViewUrlAttributeConverter( registry, options ) {
  35. return dispatcher => {
  36. dispatcher.on( 'attribute:url:media', converter );
  37. };
  38. function converter( evt, data, conversionApi ) {
  39. if ( !conversionApi.consumable.consume( data.item, evt.name ) ) {
  40. return;
  41. }
  42. const url = data.attributeNewValue;
  43. const viewWriter = conversionApi.writer;
  44. const figure = conversionApi.mapper.toViewElement( data.item );
  45. const mediaContentElement = [ ...figure.getChildren() ]
  46. .find( child => child.getCustomProperty( 'media-content' ) );
  47. // TODO: removing the wrapper and creating it from scratch is a hack. We can do better than that.
  48. viewWriter.remove( mediaContentElement );
  49. const mediaViewElement = registry.getMediaViewElement( viewWriter, url, options );
  50. viewWriter.insert( viewWriter.createPositionAt( figure, 0 ), mediaViewElement );
  51. }
  52. }