-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
resizeimagecommand.ts
80 lines (70 loc) · 2.01 KB
/
resizeimagecommand.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/**
* @license Copyright (c) 2003-2024, CKSource Holding sp. z o.o. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
/**
* @module image/imageresize/resizeimagecommand
*/
import { Command } from 'ckeditor5/src/core.js';
import type ImageUtils from '../imageutils.js';
/**
* The resize image command. Currently, it only supports the width attribute.
*/
export default class ResizeImageCommand extends Command {
/**
* Desired image width and height.
*/
declare public value: null | {
width: string | null;
height: string | null;
};
/**
* @inheritDoc
*/
public override refresh(): void {
const editor = this.editor;
const imageUtils: ImageUtils = editor.plugins.get( 'ImageUtils' );
const element = imageUtils.getClosestSelectedImageElement( editor.model.document.selection );
this.isEnabled = !!element;
if ( !element || !element.hasAttribute( 'resizedWidth' ) ) {
this.value = null;
} else {
this.value = {
width: element.getAttribute( 'resizedWidth' ) as string,
height: null
};
}
}
/**
* Executes the command.
*
* ```ts
* // Sets the width to 50%:
* editor.execute( 'resizeImage', { width: '50%' } );
*
* // Removes the width attribute:
* editor.execute( 'resizeImage', { width: null } );
* ```
*
* @param options
* @param options.width The new width of the image.
* @fires execute
*/
public override execute( options: { width: string | null } ): void {
const editor = this.editor;
const model = editor.model;
const imageUtils: ImageUtils = editor.plugins.get( 'ImageUtils' );
const imageElement = imageUtils.getClosestSelectedImageElement( model.document.selection );
this.value = {
width: options.width,
height: null
};
if ( imageElement ) {
model.change( writer => {
writer.setAttribute( 'resizedWidth', options.width, imageElement );
writer.removeAttribute( 'resizedHeight', imageElement );
imageUtils.setImageNaturalSizeAttributes( imageElement );
} );
}
}
}