UNPKG

2.64 kBJavaScriptView Raw
1/**
2 * @license Copyright (c) 2003-2024, 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.js';
6/**
7 * @module image/image/replaceimagesourcecommand
8 */
9/**
10 * Replace image source command.
11 *
12 * Changes image source to the one provided. Can be executed as follows:
13 *
14 * ```ts
15 * editor.execute( 'replaceImageSource', { source: 'http://url.to.the/image' } );
16 * ```
17 */
18export default class ReplaceImageSourceCommand extends Command {
19 constructor(editor) {
20 super(editor);
21 this.decorate('cleanupImage');
22 }
23 /**
24 * @inheritDoc
25 */
26 refresh() {
27 const editor = this.editor;
28 const imageUtils = editor.plugins.get('ImageUtils');
29 const element = this.editor.model.document.selection.getSelectedElement();
30 this.isEnabled = imageUtils.isImage(element);
31 this.value = this.isEnabled ? element.getAttribute('src') : null;
32 }
33 /**
34 * Executes the command.
35 *
36 * @fires execute
37 * @param options Options for the executed command.
38 * @param options.source The image source to replace.
39 */
40 execute(options) {
41 const image = this.editor.model.document.selection.getSelectedElement();
42 const imageUtils = this.editor.plugins.get('ImageUtils');
43 this.editor.model.change(writer => {
44 writer.setAttribute('src', options.source, image);
45 this.cleanupImage(writer, image);
46 imageUtils.setImageNaturalSizeAttributes(image);
47 });
48 }
49 /**
50 * Cleanup image attributes that are not relevant to the new source.
51 *
52 * Removed attributes are: 'srcset', 'sizes', 'sources', 'width', 'height', 'alt'.
53 *
54 * This method is decorated, to allow custom cleanup logic.
55 * For example, to remove 'myImageId' attribute after 'src' has changed:
56 *
57 * ```ts
58 * replaceImageSourceCommand.on( 'cleanupImage', ( eventInfo, [ writer, image ] ) => {
59 * writer.removeAttribute( 'myImageId', image );
60 * } );
61 * ```
62 */
63 cleanupImage(writer, image) {
64 writer.removeAttribute('srcset', image);
65 writer.removeAttribute('sizes', image);
66 /**
67 * In case responsive images some attributes should be cleaned up.
68 * Check: https://github.com/ckeditor/ckeditor5/issues/15093
69 */
70 writer.removeAttribute('sources', image);
71 writer.removeAttribute('width', image);
72 writer.removeAttribute('height', image);
73 writer.removeAttribute('alt', image);
74 }
75}