-
Notifications
You must be signed in to change notification settings - Fork 146
/
ImageEdit.ts
818 lines (733 loc) · 29.4 KB
/
ImageEdit.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
import applyChange from './editInfoUtils/applyChange';
import canRegenerateImage from './api/canRegenerateImage';
import DragAndDropHelper from '../../pluginUtils/DragAndDropHelper';
import getGeneratedImageSize from './editInfoUtils/getGeneratedImageSize';
import { Cropper, getCropHTML } from './imageEditors/Cropper';
import { deleteEditInfo, getEditInfoFromImage } from './editInfoUtils/editInfo';
import { getRotateHTML, Rotator, updateRotateHandleState } from './imageEditors/Rotator';
import { ImageEditElementClass } from './types/ImageEditElementClass';
import { MIN_HEIGHT_WIDTH } from './constants/constants';
import type { DNDDirectionX, DnDDirectionY } from './types/DragAndDropContext';
import type DragAndDropContext from './types/DragAndDropContext';
import type DragAndDropHandler from '../../pluginUtils/DragAndDropHandler';
import type ImageEditInfo from './types/ImageEditInfo';
import type ImageHtmlOptions from './types/ImageHtmlOptions';
import {
arrayPush,
Browser,
createElement,
getComputedStyle,
getObjectKeys,
safeInstanceOf,
toArray,
unwrap,
wrap,
} from 'roosterjs-editor-dom';
import type { OnShowResizeHandle } from './imageEditors/Resizer';
import {
Resizer,
doubleCheckResize,
getSideResizeHTML,
getCornerResizeHTML,
getResizeBordersHTML,
} from './imageEditors/Resizer';
import type {
ImageEditOptions,
EditorPlugin,
IEditor,
PluginEvent,
CreateElementData,
ModeIndependentColor,
} from 'roosterjs-editor-types';
import {
ImageEditOperation,
PluginEventType,
KnownCreateElementDataIndex,
SelectionRangeTypes,
ChangeSource,
} from 'roosterjs-editor-types';
import type { CompatibleImageEditOperation } from 'roosterjs-editor-types/lib/compatibleTypes';
const PI = Math.PI;
const DIRECTIONS = 8;
const DirectionRad = (PI * 2) / DIRECTIONS;
const DirectionOrder = ['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w'];
/**
* Default image edit options
*/
const DefaultOptions: Required<ImageEditOptions> = {
borderColor: '#DB626C',
minWidth: 10,
minHeight: 10,
preserveRatio: false,
minRotateDeg: 5,
imageSelector: 'img',
rotateIconHTML: '',
disableCrop: false,
disableRotate: false,
disableSideResize: false,
onSelectState: ImageEditOperation.ResizeAndRotate,
applyChangesOnMouseUp: false,
};
/**
* Map the image edit operation to a function that returns editing elements HTML to help
* build image editing UI
*/
const ImageEditHTMLMap = {
[ImageEditOperation.CornerResize]: getCornerResizeHTML,
[ImageEditOperation.SideResize]: getSideResizeHTML,
[ImageEditOperation.Rotate]: getRotateHTML,
[ImageEditOperation.Crop]: getCropHTML,
};
/**
* Default background colors for rotate handle
*/
const LIGHT_MODE_BGCOLOR = 'white';
const DARK_MODE_BGCOLOR = '#333';
/**
* ImageEdit plugin provides the ability to edit an inline image in editor, including image resizing, rotation and cropping
*/
export default class ImageEdit implements EditorPlugin {
protected editor: IEditor | null = null;
protected options: ImageEditOptions;
private disposer: (() => void) | null = null;
// Allowed editing operations
private allowedOperations: ImageEditOperation;
// Current editing image
private image: HTMLImageElement | null = null;
// Image cloned from the current editing image
private clonedImage: HTMLImageElement | null = null;
// The image wrapper
private wrapper: HTMLSpanElement | null = null;
// Current edit info of the image. All changes user made will be stored in this object.
// We use this object to update the editing UI, and finally we will use this object to generate
// the new image if necessary
private editInfo: ImageEditInfo | null = null;
// Src of the image before current editing
private lastSrc: string | null = null;
// Drag and drop helper objects
private dndHelpers: DragAndDropHelper<DragAndDropContext, any>[] = [];
/**
* Identify if the image was resized by the user.
*/
private wasResized: boolean = false;
/**
* The span element that wraps the image and opens shadow dom
*/
private shadowSpan: HTMLSpanElement | null = null;
/**
* The span element that wraps the image and opens shadow dom
*/
private isCropping: boolean = false;
/**
* Create a new instance of ImageEdit
* @param options Image editing options
* @param onShowResizeHandle An optional callback to allow customize resize handle element of image resizing.
* To customize the resize handle element, add this callback and change the attributes of elementData then it
* will be picked up by ImageEdit code
*/
constructor(options?: ImageEditOptions, private onShowResizeHandle?: OnShowResizeHandle) {
this.options = {
...DefaultOptions,
...(options || {}),
};
this.allowedOperations =
ImageEditOperation.CornerResize |
(this.options.disableCrop ? 0 : ImageEditOperation.Crop) |
(this.options.disableRotate ? 0 : ImageEditOperation.Rotate) |
(this.options.disableSideResize ? 0 : ImageEditOperation.SideResize);
}
/**
* Get a friendly name of this plugin
*/
getName() {
return 'ImageEdit';
}
/**
* Initialize this plugin. This should only be called from Editor
* @param editor Editor instance
*/
initialize(editor: IEditor) {
this.editor = editor;
this.disposer = editor.addDomEventHandler({
blur: () => this.onBlur(),
dragstart: e => {
if (this.image) {
e.preventDefault();
}
},
});
}
/**
* Dispose this plugin
*/
dispose() {
this.clearDndHelpers();
this.disposer?.();
this.disposer = null;
this.editor = null;
}
/**
* Handle events triggered from editor
* @param e PluginEvent object
*/
onPluginEvent(e: PluginEvent) {
switch (e.eventType) {
case PluginEventType.SelectionChanged:
if (
e.selectionRangeEx &&
e.selectionRangeEx.type === SelectionRangeTypes.ImageSelection &&
this.options &&
this.options.onSelectState !== undefined
) {
this.setEditingImage(e.selectionRangeEx.image, this.options.onSelectState);
}
break;
case PluginEventType.MouseDown:
// When left click in a image that already in editing mode, do not quit edit mode
const mouseTarget = e.rawEvent.target;
const button = e.rawEvent.button;
if (
this.shadowSpan !== mouseTarget ||
(this.shadowSpan === mouseTarget && button !== 0) ||
this.isCropping
) {
this.setEditingImage(null);
}
break;
case PluginEventType.MouseUp:
if (this.editor && this.image && this.shadowSpan) {
// When mouse up, if the image and the shadow span exists, the editing mode is on.
// To make sure the selection did not jump to the shadow root, reselect the image.
this.editor.select(this.image);
}
break;
case PluginEventType.KeyDown:
this.setEditingImage(null);
break;
case PluginEventType.ContentChanged:
//After contentChanged event, the current image wrapper may not be valid any more, remove all of them if any
this.removeWrapper();
break;
case PluginEventType.ExtractContentWithDom:
// When extract content, remove all image info since they may not be valid when load the content again
if (this.options?.imageSelector) {
toArray(e.clonedRoot.querySelectorAll(this.options.imageSelector)).forEach(
img => {
deleteEditInfo(img as HTMLImageElement);
}
);
}
break;
case PluginEventType.BeforeDispose:
this.removeWrapper();
break;
}
}
/**
* Check if the given image edit operation is allowed by this plugin
* @param operation The image edit operation to check
* @returns True means it is allowed, otherwise false
*/
isOperationAllowed(operation: ImageEditOperation): boolean {
return !!(this.allowedOperations & operation);
}
/**
* Set current image for edit. If there is already image in editing, it will quit editing mode and any pending editing
* operation will be submitted
* @param image The image to edit
* @param operation The editing operation
*/
setEditingImage(
image: HTMLImageElement,
operation: ImageEditOperation | CompatibleImageEditOperation
): void;
/**
* Stop editing image. If there is already image in editing, it will quit editing mode and any pending editing
* operation will be submitted
* @param image The image to edit
* @param selectImage True to select this image after quit editing mode
*/
setEditingImage(image: null, selectImage?: boolean): void;
setEditingImage(
image: HTMLImageElement | null,
operationOrSelect?: ImageEditOperation | CompatibleImageEditOperation | boolean
) {
let operation =
typeof operationOrSelect === 'number' ? operationOrSelect : ImageEditOperation.None;
const selectImage = typeof operationOrSelect === 'number' ? false : !!operationOrSelect;
if (
!image &&
this.image &&
this.editor &&
this.editInfo &&
this.lastSrc &&
this.clonedImage
) {
// When there is image in editing, clean up any cached objects and elements
this.clearDndHelpers();
// Apply the changes, and add undo snapshot if necessary
applyChange(
this.editor,
this.image,
this.editInfo,
this.lastSrc,
this.wasResized || this.isCropping,
this.clonedImage
);
// Remove editing wrapper
this.removeWrapper();
this.editor.addUndoSnapshot(() => this.image, ChangeSource.ImageResize);
if (selectImage) {
this.editor.select(this.image);
}
this.image = null;
this.editInfo = null;
this.lastSrc = null;
this.clonedImage = null;
this.isCropping = false;
}
if (!this.image && image?.isContentEditable && this.editor) {
// If there is new image to edit, enter editing mode for this image
this.editor.addUndoSnapshot();
this.image = image;
// Get initial edit info
this.editInfo = getEditInfoFromImage(image);
//Check if the image was resized by the user
this.wasResized = checkIfImageWasResized(this.image);
operation =
(canRegenerateImage(image) ? operation : ImageEditOperation.Resize) &
this.allowedOperations;
// Create and update editing wrapper and elements
this.createWrapper(operation);
this.updateWrapper();
// Init drag and drop
this.dndHelpers = [
...this.createDndHelpers(ImageEditElementClass.ResizeHandle, Resizer),
...this.createDndHelpers(ImageEditElementClass.RotateHandle, Rotator),
...this.createDndHelpers(ImageEditElementClass.CropHandle, Cropper),
...this.createDndHelpers(ImageEditElementClass.CropContainer, Cropper),
];
this.editor.select(this.image);
}
}
/**
* Flip the image.
* @param image The image to be flipped
* @param direction
*/
public flipImage(image: HTMLImageElement, direction: 'vertical' | 'horizontal') {
this.image = image;
this.editInfo = getEditInfoFromImage(image);
const { angleRad } = this.editInfo;
const isInVerticalPostion =
(angleRad >= Math.PI / 2 && angleRad < (3 * Math.PI) / 4) ||
(angleRad <= -Math.PI / 2 && angleRad > (-3 * Math.PI) / 4);
if (isInVerticalPostion) {
if (direction === 'horizontal') {
this.editInfo.flippedVertical = !this.editInfo.flippedVertical;
} else {
this.editInfo.flippedHorizontal = !this.editInfo.flippedHorizontal;
}
} else {
if (direction === 'vertical') {
this.editInfo.flippedVertical = !this.editInfo.flippedVertical;
} else {
this.editInfo.flippedHorizontal = !this.editInfo.flippedHorizontal;
}
}
this.createWrapper(ImageEditOperation.Rotate);
this.updateWrapper();
this.setEditingImage(null);
this.editor?.select(image);
}
/**
* Rotate the image in radian angle.
* @param image The image to be rotated
* @param angleRad The angle in radian that the image must be rotated.
*/
public rotateImage(image: HTMLImageElement, angleRad: number) {
this.image = image;
this.editInfo = getEditInfoFromImage(image);
this.editInfo.angleRad = this.editInfo.angleRad + angleRad;
this.createWrapper(ImageEditOperation.Rotate);
this.updateWrapper();
this.setEditingImage(null);
this.editor?.select(image);
}
/**
* quit editing mode when editor lose focus
*/
private onBlur = () => {
this.setEditingImage(null, false /* selectImage */);
};
/**
* Create editing wrapper for the image
*/
private createWrapper(operation: ImageEditOperation | CompatibleImageEditOperation) {
if (this.image && this.editor && this.options && this.editInfo) {
//Clone the image and insert the clone in a entity
this.clonedImage = this.image.cloneNode(true) as HTMLImageElement;
this.clonedImage.removeAttribute('id');
this.clonedImage.style.removeProperty('max-width');
this.clonedImage.style.removeProperty('max-height');
this.clonedImage.style.width = this.editInfo.widthPx + 'px';
this.clonedImage.style.height = this.editInfo.heightPx + 'px';
this.wrapper = createElement(
KnownCreateElementDataIndex.ImageEditWrapper,
this.image.ownerDocument
) as HTMLSpanElement;
this.wrapper?.firstChild?.appendChild(this.clonedImage);
this.wrapper.style.display = Browser.isSafari ? 'inline-block' : 'inline-flex';
// Cache current src so that we can compare it after edit see if src is changed
this.lastSrc = this.image.getAttribute('src');
// Set image src to original src to help show editing UI, also it will be used when regenerate image dataURL after editing
if (this.clonedImage) {
this.clonedImage.src = this.editInfo.src;
this.clonedImage.style.position = 'absolute';
}
// Get HTML for all edit elements (resize handle, rotate handle, crop handle and overlay, ...) and create HTML element
const options: ImageHtmlOptions = {
borderColor: getColorString(this.options.borderColor!, this.editor.isDarkMode()),
rotateIconHTML: this.options.rotateIconHTML!,
rotateHandleBackColor: this.editor.isDarkMode()
? DARK_MODE_BGCOLOR
: LIGHT_MODE_BGCOLOR,
isSmallImage: isASmallImage(this.editInfo.widthPx, this.editInfo.heightPx),
};
const htmlData: CreateElementData[] = [getResizeBordersHTML(options)];
getObjectKeys(ImageEditHTMLMap).forEach(thisOperation => {
const element = ImageEditHTMLMap[thisOperation](options, this.onShowResizeHandle);
if ((operation & thisOperation) == thisOperation && element) {
arrayPush(htmlData, element);
}
});
htmlData.forEach(data => {
const element = createElement(data, this.image!.ownerDocument);
if (element && this.wrapper) {
this.wrapper.appendChild(element);
}
});
this.insertImageWrapper(this.wrapper);
}
}
/**
* EXPORTED FOR TESTING PURPOSES ONLY
* @param wrapper
*/
public insertImageWrapper(wrapper: HTMLSpanElement) {
if (this.image) {
this.shadowSpan = wrap(this.image, 'span');
if (this.shadowSpan) {
const shadowRoot = this.shadowSpan.attachShadow({
mode: 'open',
});
this.shadowSpan.style.verticalAlign = 'bottom';
wrapper.style.fontSize = '24px';
if (this.options.applyChangesOnMouseUp) {
wrapper.addEventListener(
'mouseup',
this.changesWhenMouseUp,
true /* useCapture*/
);
}
shadowRoot.appendChild(wrapper);
}
}
}
/**
* Remove the temp wrapper of the image
*/
private removeWrapper = () => {
if (this.shadowSpan) {
unwrap(this.shadowSpan);
}
if (this.options.applyChangesOnMouseUp) {
this.wrapper?.removeEventListener(
'mouseup',
this.changesWhenMouseUp,
true /* useCapture*/
);
}
this.wrapper = null;
this.shadowSpan = null;
};
private changesWhenMouseUp = () => {
if (this.editor && this.image && this.editInfo && this.lastSrc && this.clonedImage) {
applyChange(
this.editor,
this.image,
this.editInfo,
this.lastSrc,
this.wasResized,
this.clonedImage,
this.options.applyChangesOnMouseUp
);
}
};
/**
* Update image edit elements to reflect current editing result
* @param context
*/
private updateWrapper = (context?: DragAndDropContext) => {
const wrapper = this.wrapper;
if (
wrapper &&
this.editInfo &&
this.image &&
this.clonedImage &&
this.options &&
this.shadowSpan?.parentElement
) {
// Prepare: get related editing elements
const cropContainers = getEditElements(wrapper, ImageEditElementClass.CropContainer);
const cropOverlays = getEditElements(wrapper, ImageEditElementClass.CropOverlay);
const resizeHandles = getEditElements(wrapper, ImageEditElementClass.ResizeHandle);
const rotateCenter = getEditElements(wrapper, ImageEditElementClass.RotateCenter)[0];
const rotateHandle = getEditElements(wrapper, ImageEditElementClass.RotateHandle)[0];
const cropHandles = getEditElements(wrapper, ImageEditElementClass.CropHandle);
// Cropping and resizing will show different UI, so check if it is cropping here first
this.isCropping = cropContainers.length == 1 && cropOverlays.length == 4;
const {
angleRad,
bottomPercent,
leftPercent,
rightPercent,
topPercent,
flippedHorizontal,
flippedVertical,
} = this.editInfo;
// Width/height of the image
const {
targetWidth,
targetHeight,
originalWidth,
originalHeight,
visibleWidth,
visibleHeight,
} = getGeneratedImageSize(this.editInfo, this.isCropping);
const marginHorizontal = (targetWidth - visibleWidth) / 2;
const marginVertical = (targetHeight - visibleHeight) / 2;
const cropLeftPx = originalWidth * leftPercent;
const cropRightPx = originalWidth * rightPercent;
const cropTopPx = originalHeight * topPercent;
const cropBottomPx = originalHeight * bottomPercent;
// Update size and margin of the wrapper
wrapper.style.margin = `${marginVertical}px ${marginHorizontal}px`;
wrapper.style.transform = `rotate(${angleRad}rad)`;
setWrapperSizeDimensions(wrapper, this.image, visibleWidth, visibleHeight);
// Update the text-alignment to avoid the image to overflow if the parent element have align center or right
// or if the direction is Right To Left
wrapper.style.textAlign = isRtl(this.shadowSpan.parentElement) ? 'right' : 'left';
// Update size of the image
this.clonedImage.style.width = getPx(originalWidth);
this.clonedImage.style.height = getPx(originalHeight);
//Update flip direction
setFlipped(this.clonedImage.parentElement, flippedHorizontal, flippedVertical);
if (this.isCropping) {
// For crop, we also need to set position of the overlays
setSize(
cropContainers[0],
cropLeftPx,
cropTopPx,
cropRightPx,
cropBottomPx,
undefined,
undefined
);
setSize(cropOverlays[0], 0, 0, cropRightPx, undefined, undefined, cropTopPx);
setSize(cropOverlays[1], undefined, 0, 0, cropBottomPx, cropRightPx, undefined);
setSize(cropOverlays[2], cropLeftPx, undefined, 0, 0, undefined, cropBottomPx);
setSize(cropOverlays[3], 0, cropTopPx, undefined, 0, cropLeftPx, undefined);
updateHandleCursor(cropHandles, angleRad);
} else {
// For rotate/resize, set the margin of the image so that cropped part won't be visible
this.clonedImage.style.margin = `${-cropTopPx}px 0 0 ${-cropLeftPx}px`;
// Double check resize
if (context?.elementClass == ImageEditElementClass.ResizeHandle) {
const clientWidth = wrapper.clientWidth;
const clientHeight = wrapper.clientHeight;
this.wasResized = true;
doubleCheckResize(
this.editInfo,
this.options.preserveRatio || false,
clientWidth,
clientHeight
);
this.updateWrapper();
}
const viewport = this.editor?.getVisibleViewport();
const isSmall = isASmallImage(targetWidth, targetHeight);
if (rotateHandle && rotateCenter && viewport) {
updateRotateHandleState(
viewport,
angleRad,
wrapper,
rotateCenter,
rotateHandle,
isSmall
);
}
updateSideHandlesVisibility(resizeHandles, isSmall);
updateHandleCursor(resizeHandles, angleRad);
}
}
};
/**
* Create drag and drop helpers
* @param wrapper
* @param elementClass
* @param dragAndDrop
*/
private createDndHelpers(
elementClass: ImageEditElementClass,
dragAndDrop: DragAndDropHandler<DragAndDropContext, any>
): DragAndDropHelper<DragAndDropContext, any>[] {
const wrapper = this.wrapper;
return wrapper && this.editInfo
? getEditElements(wrapper, elementClass).map(
element =>
new DragAndDropHelper<DragAndDropContext, any>(
element,
{
editInfo: this.editInfo!,
options: this.options,
elementClass,
x: element.dataset.x as DNDDirectionX,
y: element.dataset.y as DnDDirectionY,
},
this.updateWrapper,
dragAndDrop,
this.editor ? this.editor.getZoomScale() : 1
)
)
: [];
}
/**
* Clean up drag and drop helpers
*/
private clearDndHelpers() {
this.dndHelpers?.forEach(helper => helper.dispose());
this.dndHelpers = [];
}
}
function setSize(
element: HTMLElement,
left: number | undefined,
top: number | undefined,
right: number | undefined,
bottom: number | undefined,
width: number | undefined,
height: number | undefined
) {
element.style.left = left !== undefined ? getPx(left) : element.style.left;
element.style.top = top !== undefined ? getPx(top) : element.style.top;
element.style.right = right !== undefined ? getPx(right) : element.style.right;
element.style.bottom = bottom !== undefined ? getPx(bottom) : element.style.bottom;
element.style.width = width !== undefined ? getPx(width) : element.style.width;
element.style.height = height !== undefined ? getPx(height) : element.style.height;
}
function setWrapperSizeDimensions(
wrapper: HTMLElement,
image: HTMLImageElement,
width: number,
height: number
) {
const hasBorder = image.style.borderStyle;
if (hasBorder) {
const borderWidth = image.style.borderWidth ? 2 * parseInt(image.style.borderWidth) : 2;
wrapper.style.width = getPx(width + borderWidth);
wrapper.style.height = getPx(height + borderWidth);
return;
}
wrapper.style.width = getPx(width);
wrapper.style.height = getPx(height);
}
function getPx(value: number): string {
return value + 'px';
}
function getEditElements(wrapper: HTMLElement, elementClass: ImageEditElementClass): HTMLElement[] {
return toArray(wrapper.querySelectorAll('.' + elementClass)) as HTMLElement[];
}
function isRtl(element: Node): boolean {
return safeInstanceOf(element, 'HTMLElement')
? getComputedStyle(element, 'direction') == 'rtl'
: false;
}
function handleRadIndexCalculator(angleRad: number): number {
const idx = Math.round(angleRad / DirectionRad) % DIRECTIONS;
return idx < 0 ? idx + DIRECTIONS : idx;
}
function rotateHandles(angleRad: number, y: string = '', x: string = ''): string {
const radIndex = handleRadIndexCalculator(angleRad);
const originalDirection = y + x;
const originalIndex = DirectionOrder.indexOf(originalDirection);
const rotatedIndex = originalIndex >= 0 && originalIndex + radIndex;
return rotatedIndex ? DirectionOrder[rotatedIndex % DIRECTIONS] : '';
}
/**
* Rotate the resizer and cropper handles according to the image position.
* @param handles The resizer handles.
* @param angleRad The angle that the image was rotated.
*/
function updateHandleCursor(handles: HTMLElement[], angleRad: number) {
handles.forEach(handle => {
const { y, x } = handle.dataset;
handle.style.cursor = `${rotateHandles(angleRad, y, x)}-resize`;
});
}
function updateSideHandlesVisibility(handles: HTMLElement[], isSmall: boolean) {
handles.forEach(handle => {
const { y, x } = handle.dataset;
const coordinate = (y ?? '') + (x ?? '');
const directions = ['n', 's', 'e', 'w'];
const isSideHandle = directions.indexOf(coordinate) > -1;
handle.style.display = isSideHandle && isSmall ? 'none' : '';
});
}
/**
* Check if the current image was resized by the user
* @param image the current image
* @returns if the user resized the image, returns true, otherwise, returns false
*/
function checkIfImageWasResized(image: HTMLImageElement): boolean {
const { width, height, style } = image;
const isMaxWidthInitial =
style.maxWidth === '' || style.maxWidth === 'initial' || style.maxWidth === 'auto';
if (
isMaxWidthInitial &&
(isFixedNumberValue(style.height) ||
isFixedNumberValue(style.width) ||
isFixedNumberValue(width) ||
isFixedNumberValue(height))
) {
return true;
} else {
return false;
}
}
function isFixedNumberValue(value: string | number) {
const numberValue = typeof value === 'string' ? parseInt(value) : value;
return !isNaN(numberValue);
}
function isASmallImage(widthPx: number, heightPx: number): boolean {
return widthPx && heightPx && (widthPx < MIN_HEIGHT_WIDTH || heightPx < MIN_HEIGHT_WIDTH)
? true
: false;
}
function getColorString(color: string | ModeIndependentColor, isDarkMode: boolean): string {
if (typeof color === 'string') {
return color.trim();
}
return isDarkMode ? color.darkModeColor.trim() : color.lightModeColor.trim();
}
function setFlipped(
element: HTMLElement | null,
flippedHorizontally?: boolean,
flippedVertically?: boolean
) {
if (element) {
element.style.transform = `scale(${flippedHorizontally ? -1 : 1}, ${
flippedVertically ? -1 : 1
})`;
}
}