converters.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /**
  2. * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module media-embed/converters
  7. */
  8. import ViewRange from '@ckeditor/ckeditor5-engine/src/view/range';
  9. import ViewPosition from '@ckeditor/ckeditor5-engine/src/view/position';
  10. /**
  11. * Returns a function that converts the model "url" attribute to the view representation.
  12. *
  13. * Depending on the configuration, the view representation can be "semantic" (for the data pipeline):
  14. *
  15. * <figure class="media">
  16. * <oembed url="foo"></oembed>
  17. * </figure>
  18. *
  19. * or "non-semantic" (for the editing view pipeline):
  20. *
  21. * <figure class="media">
  22. * <div data-oembed-url="foo">[ non-semantic media preview for "foo" ]</div>
  23. * </figure>
  24. *
  25. * **Note:** Changing the model "url" attribute replaces the entire content of the
  26. * `<figure>` in the view.
  27. *
  28. * @param {module:media-embed/mediaregistry~MediaRegistry} registry The registry providing
  29. * the media and their content.
  30. * @param {Object} options
  31. * @param {String} [options.renderMediaPreview] When `true`, the converter will create the view in the non-semantic form.
  32. * @param {String} [options.renderForEditingView] When `true`, the converter will create a view specific for the
  33. * editing pipeline (e.g. including CSS classes, content placeholders).
  34. * @returns {Function}
  35. */
  36. export function modelToViewUrlAttributeConverter( registry, options ) {
  37. return dispatcher => {
  38. dispatcher.on( 'attribute:url:media', converter );
  39. };
  40. function converter( evt, data, conversionApi ) {
  41. if ( !conversionApi.consumable.consume( data.item, evt.name ) ) {
  42. return;
  43. }
  44. const url = data.attributeNewValue;
  45. const viewWriter = conversionApi.writer;
  46. const figure = conversionApi.mapper.toViewElement( data.item );
  47. // TODO: removing it and creating it from scratch is a hack. We can do better than that.
  48. viewWriter.remove( ViewRange.createIn( figure ) );
  49. const mediaViewElement = registry.getMediaViewElement( viewWriter, url, options );
  50. viewWriter.insert( ViewPosition.createAt( figure, 0 ), mediaViewElement );
  51. }
  52. }