UNPKG

2.21 kBJavaScriptView Raw
1/**
2 * @license Copyright (c) 2003-2023, CKSource Holding sp. z o.o. All rights reserved.
3 * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
4 */
5/**
6 * Returns a function that converts the model "url" attribute to the view representation.
7 *
8 * Depending on the configuration, the view representation can be "semantic" (for the data pipeline):
9 *
10 * ```html
11 * <figure class="media">
12 * <oembed url="foo"></oembed>
13 * </figure>
14 * ```
15 *
16 * or "non-semantic" (for the editing view pipeline):
17 *
18 * ```html
19 * <figure class="media">
20 * <div data-oembed-url="foo">[ non-semantic media preview for "foo" ]</div>
21 * </figure>
22 * ```
23 *
24 * **Note:** Changing the model "url" attribute replaces the entire content of the
25 * `<figure>` in the view.
26 *
27 * @param registry The registry providing
28 * the media and their content.
29 * @param options options object with following properties:
30 * - elementName When set, overrides the default element name for semantic media embeds.
31 * - renderMediaPreview When `true`, the converter will create the view in the non-semantic form.
32 * - renderForEditingView When `true`, the converter will create a view specific for the
33 * editing pipeline (e.g. including CSS classes, content placeholders).
34 */
35export function modelToViewUrlAttributeConverter(registry, options) {
36 const converter = (evt, data, conversionApi) => {
37 if (!conversionApi.consumable.consume(data.item, evt.name)) {
38 return;
39 }
40 const url = data.attributeNewValue;
41 const viewWriter = conversionApi.writer;
42 const figure = conversionApi.mapper.toViewElement(data.item);
43 const mediaContentElement = [...figure.getChildren()]
44 .find(child => child.getCustomProperty('media-content'));
45 // TODO: removing the wrapper and creating it from scratch is a hack. We can do better than that.
46 viewWriter.remove(mediaContentElement);
47 const mediaViewElement = registry.getMediaViewElement(viewWriter, url, options);
48 viewWriter.insert(viewWriter.createPositionAt(figure, 0), mediaViewElement);
49 };
50 return dispatcher => {
51 dispatcher.on('attribute:url:media', converter);
52 };
53}