UNPKG

1.68 kBJavaScriptView Raw
1/**
2 * @license Copyright (c) 2003-2022, 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/**
7 * @module image/imageresize/resizeimagecommand
8 */
9
10import { Command } from 'ckeditor5/src/core';
11
12/**
13 * The resize image command. Currently, it only supports the width attribute.
14 *
15 * @extends module:core/command~Command
16 */
17export default class ResizeImageCommand extends Command {
18 /**
19 * @inheritDoc
20 */
21 refresh() {
22 const editor = this.editor;
23 const imageUtils = editor.plugins.get( 'ImageUtils' );
24 const element = imageUtils.getClosestSelectedImageElement( editor.model.document.selection );
25
26 this.isEnabled = !!element;
27
28 if ( !element || !element.hasAttribute( 'width' ) ) {
29 this.value = null;
30 } else {
31 this.value = {
32 width: element.getAttribute( 'width' ),
33 height: null
34 };
35 }
36 }
37
38 /**
39 * Executes the command.
40 *
41 * // Sets the width to 50%:
42 * editor.execute( 'resizeImage', { width: '50%' } );
43 *
44 * // Removes the width attribute:
45 * editor.execute( 'resizeImage', { width: null } );
46 *
47 * @param {Object} options
48 * @param {String|null} options.width The new width of the image.
49 * @fires execute
50 */
51 execute( options ) {
52 const editor = this.editor;
53 const model = editor.model;
54 const imageUtils = editor.plugins.get( 'ImageUtils' );
55 const imageElement = imageUtils.getClosestSelectedImageElement( model.document.selection );
56
57 this.value = {
58 width: options.width,
59 height: null
60 };
61
62 if ( imageElement ) {
63 model.change( writer => {
64 writer.setAttribute( 'width', options.width, imageElement );
65 } );
66 }
67 }
68}