UNPKG

2.49 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 */
5import { Command } from 'ckeditor5/src/core';
6import { findOptimalInsertionRange } from 'ckeditor5/src/widget';
7import { getSelectedMediaModelWidget, insertMedia } from './utils';
8/**
9 * The insert media command.
10 *
11 * The command is registered by the {@link module:media-embed/mediaembedediting~MediaEmbedEditing} as `'mediaEmbed'`.
12 *
13 * To insert media at the current selection, execute the command and specify the URL:
14 *
15 * ```ts
16 * editor.execute( 'mediaEmbed', 'http://url.to.the/media' );
17 * ```
18 */
19export default class MediaEmbedCommand extends Command {
20 /**
21 * @inheritDoc
22 */
23 refresh() {
24 const model = this.editor.model;
25 const selection = model.document.selection;
26 const selectedMedia = getSelectedMediaModelWidget(selection);
27 this.value = selectedMedia ? selectedMedia.getAttribute('url') : undefined;
28 this.isEnabled = isMediaSelected(selection) || isAllowedInParent(selection, model);
29 }
30 /**
31 * Executes the command, which either:
32 *
33 * * updates the URL of the selected media,
34 * * inserts the new media into the editor and puts the selection around it.
35 *
36 * @fires execute
37 * @param url The URL of the media.
38 */
39 execute(url) {
40 const model = this.editor.model;
41 const selection = model.document.selection;
42 const selectedMedia = getSelectedMediaModelWidget(selection);
43 if (selectedMedia) {
44 model.change(writer => {
45 writer.setAttribute('url', url, selectedMedia);
46 });
47 }
48 else {
49 insertMedia(model, url, selection, true);
50 }
51 }
52}
53/**
54 * Checks if the media embed is allowed in the parent.
55 */
56function isAllowedInParent(selection, model) {
57 const insertionRange = findOptimalInsertionRange(selection, model);
58 let parent = insertionRange.start.parent;
59 // The model.insertContent() will remove empty parent (unless it is a $root or a limit).
60 if (parent.isEmpty && !model.schema.isLimit(parent)) {
61 parent = parent.parent;
62 }
63 return model.schema.checkChild(parent, 'media');
64}
65/**
66 * Checks if the media object is selected.
67 */
68function isMediaSelected(selection) {
69 const element = selection.getSelectedElement();
70 return !!element && element.name === 'media';
71}