All files / roosterjs-content-model-plugins/lib/imageEdit ImageEditPlugin.ts

85.43% Statements 299/350
65.03% Branches 212/326
74.51% Functions 38/51
85.25% Lines 289/339

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 8721x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                         1x                   1x 1x 1x 1x 1x                 1x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x       37x           1x                   52x 52x 52x                           2x 2x 2x 2x             1x 1x 1x 1x                         1x 43x 12x 12x   43x 43x 43x                 1x 93x 9x   84x   6x 6x   10x 10x   3x 3x   15x 15x   1x 1x   2x 2x       1x 2x 1x         1x 1x       1x 1x 1x 1x 1x         1x 18x                       1x 10x 10x   10x   10x       1x 6x           2x       1x 1x 1x 1x 1x 1x       1x 1x     1x 1x 1x 1x         1x             1x 3x 3x         1x     1x   2x 1x   2x                   1x 1x 1x 1x 1x 1x 1x       1x 13x 1x 1x 1x       1x 15x   1x 1x   13x 13x   1x 1x             28x             28x 28x   28x   28x 28x     28x     28x   28x           28x 28x               8x       8x                   8x 2x     8x 8x 8x 8x   8x                       8x 2x     8x 8x     28x 28x   28x           20x 20x 20x 20x 20x 20x 20x     20x       28x       49x               6x     6x                       22x         22x 2x     22x         9x 1x 1x 1x 1x   9x 8x 8x     13x 13x       1x 14x 2x 2x       1x         11x       11x 11x     11x 11x 11x 11x 11x 11x 11x               11x 11x 11x 11x 11x 11x 11x 11x 11x   11x       11x     15x 15x 15x 15x 12x 12x                                                                                                                                                 12x                     12x                       1x             1x               12x 12x 12x 12x 12x 12x       12x                         1x                 1x       1x                                                                                                 1x 3x     3x 3x   3x 3x 3x               1x           4x 4x 2x     2x   2x               2x                     1x 48x 48x 48x 48x 48x 48x 48x 81x 48x 48x 48x 48x 48x 48x 48x 48x     1x                                   1x 3x 3x     3x 3x 3x 2x   2x   2x             2x     2x             1x 1x 1x     1x 1x 1x         1x  
import { applyChange } from './utils/applyChange';
import { canRegenerateImage } from './utils/canRegenerateImage';
import { checkIfImageWasResized, isASmallImage } from './utils/imageEditUtils';
import { createImageWrapper } from './utils/createImageWrapper';
import { Cropper } from './Cropper/cropperContext';
import { EDITING_MARKER, findEditingImage } from './utils/findEditingImage';
import { filterInnerResizerHandles } from './utils/filterInnerResizerHandles';
import { getDropAndDragHelpers } from './utils/getDropAndDragHelpers';
import { getHTMLImageOptions } from './utils/getHTMLImageOptions';
import { getSelectedImage } from './utils/getSelectedImage';
import { getSelectedImageMetadata, updateImageEditInfo } from './utils/updateImageEditInfo';
import { ImageEditElementClass } from './types/ImageEditElementClass';
import { normalizeImageSelection } from './utils/normalizeImageSelection';
import { Resizer } from './Resizer/resizerContext';
import { Rotator } from './Rotator/rotatorContext';
import { updateHandleCursor } from './utils/updateHandleCursor';
import { updateRotateHandle } from './Rotator/updateRotateHandle';
import { updateWrapper } from './utils/updateWrapper';
import {
    ChangeSource,
    getSafeIdSelector,
    getSelectedParagraphs,
    isElementOfType,
    isNodeOfType,
    mutateBlock,
    mutateSegment,
    setImageState,
    unwrap,
} from 'roosterjs-content-model-dom';
import type { DragAndDropHelper } from '../pluginUtils/DragAndDrop/DragAndDropHelper';
import type { DragAndDropContext } from './types/DragAndDropContext';
import type { ImageHtmlOptions } from './types/ImageHtmlOptions';
import type { ImageEditOptions } from './types/ImageEditOptions';
import type {
    ContentChangedEvent,
    ContentModelImage,
    EditorPlugin,
    IEditor,
    ImageEditOperation,
    ImageEditor,
    ImageMetadataFormat,
    KeyDownEvent,
    MouseDownEvent,
    MouseUpEvent,
    PluginEvent,
} from 'roosterjs-content-model-types';
 
const DefaultOptions: Partial<ImageEditOptions> = {
    borderColor: '#DB626C',
    minWidth: 10,
    minHeight: 10,
    preserveRatio: true,
    disableRotate: false,
    disableSideResize: false,
    onSelectState: ['resize', 'rotate'],
};
 
const MouseRightButton = 2;
const DRAG_ID = '_dragging';
const IMAGE_EDIT_CLASS = 'imageEdit';
const IMAGE_EDIT_CLASS_CARET = 'imageEditCaretColor';
const IMAGE_EDIT_FORMAT_EVENT = 'ImageEditEvent';
 
/**
 * ImageEdit plugin handles the following image editing features:
 * - Resize image
 * - Crop image
 * - Rotate image
 * - Flip image
 */
export class ImageEditPlugin implements ImageEditor, EditorPlugin {
    protected editor: IEditor | null = null;
    private shadowSpan: HTMLSpanElement | null = null;
    private selectedImage: HTMLImageElement | null = null;
    protected wrapper: HTMLSpanElement | null = null;
    protected imageEditInfo: ImageMetadataFormat | null = null;
    private imageHTMLOptions: ImageHtmlOptions | null = null;
    private dndHelpers: DragAndDropHelper<DragAndDropContext, any>[] = [];
    private clonedImage: HTMLImageElement | null = null;
    private lastSrc: string | null = null;
    private wasImageResized: boolean = false;
    private isCropMode: boolean = false;
    private resizers: HTMLDivElement[] = [];
    private rotators: HTMLDivElement[] = [];
    private croppers: HTMLDivElement[] = [];
    private zoomScale: number = 1;
    private disposer: (() => void) | null = null;
    protected isEditing = false;
    protected options: ImageEditOptions;
 
    constructor(options?: ImageEditOptions) {
        this.options = { ...DefaultOptions, ...options };
    }
 
    /**
     * Get name of this plugin
     */
    getName() {
        return 'ImageEdit';
    }
 
    /**
     * The first method that editor will call to a plugin when editor is initializing.
     * It will pass in the editor instance, plugin should take this chance to save the
     * editor reference so that it can call to any editor method or format API later.
     * @param editor The editor object
     */
    initialize(editor: IEditor) {
        this.editor = editor;
        this.disposer = editor.attachDomEvent({
            blur: {
                beforeDispatch: () => {
                    if (this.isEditing && this.editor && !this.editor.isDisposed()) {
                        this.applyFormatWithContentModel(
                            this.editor,
                            this.isCropMode,
                            true /* shouldSelectImage */
                        );
                    }
                },
            },
            dragstart: {
                beforeDispatch: ev => {
                    Eif (this.editor) {
                        const target = ev.target as Node;
                        Eif (this.isImageSelection(target)) {
                            target.id = target.id + DRAG_ID;
                        }
                    }
                },
            },
            dragend: {
                beforeDispatch: ev => {
                    Eif (this.editor) {
                        const target = ev.target as Node;
                        Eif (this.isImageSelection(target) && target.id.includes(DRAG_ID)) {
                            target.id = target.id.replace(DRAG_ID, '').trim();
                        }
                    }
                },
            },
        });
    }
 
    /**
     * The last method that editor will call to a plugin before it is disposed.
     * Plugin can take this chance to clear the reference to editor. After this method is
     * called, plugin should not call to any editor method since it will result in error.
     */
    dispose() {
        if (this.disposer) {
            this.disposer();
            this.disposer = null;
        }
        this.isEditing = false;
        this.cleanInfo();
        this.editor = null;
    }
 
    /**
     * Core method for a plugin. Once an event happens in editor, editor will call this
     * method of each plugin to handle the event as long as the event is not handled
     * exclusively by another plugin.
     * @param event The event to handle:
     */
    onPluginEvent(event: PluginEvent) {
        if (!this.editor) {
            return;
        }
        switch (event.eventType) {
            case 'mouseDown':
                this.mouseDownHandler(this.editor, event);
                break;
            case 'mouseUp':
                this.mouseUpHandler(this.editor, event);
                break;
            case 'keyDown':
                this.keyDownHandler(this.editor, event);
                break;
            case 'contentChanged':
                this.contentChangedHandler(this.editor, event);
                break;
            case 'extractContentWithDom':
                this.removeImageEditing(event.clonedRoot);
                break;
            case 'beforeLogicalRootChange':
                this.handleBeforeLogicalRootChange();
                break;
        }
    }
 
    private handleBeforeLogicalRootChange() {
        if (this.isEditing && this.editor && !this.editor.isDisposed()) {
            this.applyFormatWithContentModel(
                this.editor,
                this.isCropMode,
                false /* shouldSelectImage */
            );
            this.removeImageWrapper();
            this.cleanInfo();
        }
    }
 
    private removeImageEditing(clonedRoot: HTMLElement) {
        const images = clonedRoot.querySelectorAll('img');
        images.forEach(image => {
            Eif (image.dataset.editingInfo) {
                delete image.dataset.editingInfo;
            }
        });
    }
 
    private isImageSelection(target: Node): target is HTMLElement {
        return (
            isNodeOfType(target, 'ELEMENT_NODE') &&
            (isElementOfType(target, 'img') ||
                !!(
                    isElementOfType(target, 'span') &&
                    target.firstElementChild &&
                    isNodeOfType(target.firstElementChild, 'ELEMENT_NODE') &&
                    isElementOfType(target.firstElementChild, 'img')
                ))
        );
    }
 
    private mouseUpHandler(editor: IEditor, event: MouseUpEvent) {
        const selection = editor.getDOMSelection();
        Eif ((selection && selection.type == 'image') || this.isEditing) {
            const shouldSelectImage =
                this.isImageSelection(event.rawEvent.target as Node) &&
                event.rawEvent.button === MouseRightButton;
            this.applyFormatWithContentModel(editor, this.isCropMode, shouldSelectImage);
        }
    }
 
    private mouseDownHandler(editor: IEditor, event: MouseDownEvent) {
        if (
            this.isEditing &&
            this.isImageSelection(event.rawEvent.target as Node) &&
            event.rawEvent.button !== MouseRightButton &&
            !this.isCropMode
        ) {
            this.applyFormatWithContentModel(editor, this.isCropMode);
        }
    }
 
    private onDropHandler(editor: IEditor) {
        const selection = editor.getDOMSelection();
        Eif (selection?.type == 'image') {
            editor.formatContentModel(model => {
                const imageDragged = findEditingImage(model, selection.image.id);
                const imageDropped = findEditingImage(
                    model,
                    selection.image.id.replace(DRAG_ID, '').trim()
                );
                Eif (imageDragged && imageDropped) {
                    const draggedIndex = imageDragged.paragraph.segments.indexOf(
                        imageDragged.image
                    );
                    mutateBlock(imageDragged.paragraph).segments.splice(draggedIndex, 1);
                    const segment = imageDropped.image;
                    const paragraph = imageDropped.paragraph;
                    mutateSegment(paragraph, segment, image => {
                        image.isSelected = true;
                        image.isSelectedAsImageSelection = true;
                    });
 
                    return true;
                }
                return false;
            });
        }
    }
 
    private keyDownHandler(editor: IEditor, event: KeyDownEvent) {
        Eif (this.isEditing) {
            if (
                event.rawEvent.key === 'Escape' ||
                event.rawEvent.key === 'Delete' ||
                event.rawEvent.key === 'Backspace'
            ) {
                Iif (event.rawEvent.key === 'Escape') {
                    this.removeImageWrapper();
                }
                this.cleanInfo();
            } else {
                if (event.rawEvent.key == 'Enter' && this.isCropMode) {
                    event.rawEvent.preventDefault();
                }
                this.applyFormatWithContentModel(
                    editor,
                    this.isCropMode,
                    true /** should selectImage */,
                    false /* isApiOperation */
                );
            }
        }
    }
 
    private setContentHandler(editor: IEditor) {
        const selection = editor.getDOMSelection();
        Eif (selection?.type == 'image') {
            this.cleanInfo();
            setImageState(selection.image, '');
            this.isEditing = false;
            this.isCropMode = false;
        }
    }
 
    private formatEventHandler(event: ContentChangedEvent) {
        if (this.isEditing && event.formatApiName !== IMAGE_EDIT_FORMAT_EVENT) {
            this.cleanInfo();
            this.isEditing = false;
            this.isCropMode = false;
        }
    }
 
    private contentChangedHandler(editor: IEditor, event: ContentChangedEvent) {
        switch (event.source) {
            case ChangeSource.SetContent:
                this.setContentHandler(editor);
                break;
            case ChangeSource.Format:
                this.formatEventHandler(event);
                break;
            case ChangeSource.Drop:
                this.onDropHandler(editor);
                break;
        }
    }
 
    /**
     * EXPOSED FOR TESTING PURPOSE ONLY
     */
    protected applyFormatWithContentModel(
        editor: IEditor,
        isCropMode: boolean,
        shouldSelectImage?: boolean,
        isApiOperation?: boolean
    ) {
        let editingImageModel: ContentModelImage | undefined;
        const selection = editor.getDOMSelection();
        let isRTL: boolean = false;
 
        editor.formatContentModel(
            (model, context) => {
                const editingImage = getSelectedImage(model);
                const previousSelectedImage = isApiOperation
                    ? editingImage
                    : findEditingImage(model);
                let result = false;
 
                // Skip adding undo snapshot for now. If we detect any changes later, we will reset it
                context.skipUndoSnapshot = 'SkipAll';
 
                Eif (
                    shouldSelectImage ||
                    previousSelectedImage?.image != editingImage?.image ||
                    previousSelectedImage?.image.format.imageState == EDITING_MARKER ||
                    isApiOperation
                ) {
                    const { lastSrc, selectedImage, imageEditInfo, clonedImage } = this;
                    if (
                        (this.isEditing || isApiOperation) &&
                        previousSelectedImage &&
                        lastSrc &&
                        selectedImage &&
                        imageEditInfo &&
                        clonedImage
                    ) {
                        mutateSegment(
                            previousSelectedImage.paragraph,
                            previousSelectedImage.image,
                            image => {
                                const changeState = applyChange(
                                    editor,
                                    selectedImage,
                                    image,
                                    imageEditInfo,
                                    lastSrc,
                                    this.wasImageResized || this.isCropMode,
                                    clonedImage
                                );
 
                                if (this.wasImageResized || changeState == 'FullyChanged') {
                                    context.skipUndoSnapshot = false;
                                }
                                const isSameImage =
                                    previousSelectedImage?.image === editingImage?.image;
                                image.isSelected = isSameImage || shouldSelectImage;
                                image.isSelectedAsImageSelection = isSameImage || shouldSelectImage;
                                image.format.imageState = undefined;
 
                                Iif (selection?.type == 'range' && !selection.range.collapsed) {
                                    const selectedParagraphs = getSelectedParagraphs(model, true);
                                    const isImageInRange = selectedParagraphs.some(paragraph =>
                                        paragraph.segments.includes(image)
                                    );
                                    if (isImageInRange) {
                                        image.isSelected = true;
                                    }
                                }
                            }
                        );
 
                        if (shouldSelectImage) {
                            normalizeImageSelection(previousSelectedImage);
                        }
 
                        this.cleanInfo();
                        result = true;
                    }
 
                    this.isEditing = false;
                    this.isCropMode = false;
 
                    if (
                        editingImage &&
                        selection?.type == 'image' &&
                        !shouldSelectImage &&
                        !isApiOperation
                    ) {
                        this.isEditing = true;
                        this.isCropMode = isCropMode;
                        mutateSegment(editingImage.paragraph, editingImage.image, image => {
                            editingImageModel = image;
                            isRTL = editingImage.paragraph.format.direction == 'rtl';
                            this.imageEditInfo = updateImageEditInfo(image, selection.image);
                            image.format.imageState = 'isEditing';
                        });
 
                        result = true;
                    }
                }
 
                return result;
            },
            {
                onNodeCreated: (model, node) => {
                    if (
                        !isApiOperation &&
                        editingImageModel &&
                        editingImageModel == model &&
                        editingImageModel.format.imageState == EDITING_MARKER &&
                        isNodeOfType(node, 'ELEMENT_NODE') &&
                        isElementOfType(node, 'img')
                    ) {
                        Iif (isCropMode) {
                            this.startCropMode(editor, node, isRTL);
                        } else {
                            this.startRotateAndResize(editor, node, isRTL);
                        }
                    }
                },
                apiName: IMAGE_EDIT_FORMAT_EVENT,
            },
            {
                tryGetFromCache: true,
            }
        );
    }
 
    private startEditing(
        editor: IEditor,
        image: HTMLImageElement,
        apiOperation: ImageEditOperation[]
    ) {
        if (!this.imageEditInfo) {
            this.imageEditInfo = getSelectedImageMetadata(editor, image);
        }
 
        if (
            (this.imageEditInfo.widthPx == 0 || this.imageEditInfo.heightPx == 0) &&
            !image.complete
        ) {
            // Image dimensions are zero and loading is incomplete, wait for image to load.
            image.onload = () => {
                this.updateImageDimensionsIfZero(image);
                this.startEditingInternal(editor, image, apiOperation);
                image.onload = null;
                image.onerror = null;
            };
            image.onerror = () => {
                image.onload = null;
                image.onerror = null;
            };
        } else {
            this.updateImageDimensionsIfZero(image);
            this.startEditingInternal(editor, image, apiOperation);
        }
    }
 
    private updateImageDimensionsIfZero(image: HTMLImageElement) {
        if (this.imageEditInfo?.widthPx === 0 || this.imageEditInfo?.heightPx === 0) {
            this.imageEditInfo.widthPx = image.clientWidth;
            this.imageEditInfo.heightPx = image.clientHeight;
        }
    }
 
    private startEditingInternal(
        editor: IEditor,
        image: HTMLImageElement,
        apiOperation: ImageEditOperation[]
    ) {
        Iif (!this.imageEditInfo) {
            this.imageEditInfo = getSelectedImageMetadata(editor, image);
        }
 
        this.imageHTMLOptions = getHTMLImageOptions(editor, this.options, this.imageEditInfo);
        this.lastSrc = image.getAttribute('src');
 
        const {
            resizers,
            rotators,
            wrapper,
            shadowSpan,
            imageClone,
            croppers,
        } = createImageWrapper(
            editor,
            image,
            this.options,
            this.imageEditInfo,
            this.imageHTMLOptions,
            apiOperation
        );
        this.shadowSpan = shadowSpan;
        this.selectedImage = image;
        this.wrapper = wrapper;
        this.clonedImage = imageClone;
        this.wasImageResized = checkIfImageWasResized(image);
        this.resizers = resizers;
        this.rotators = rotators;
        this.croppers = croppers;
        this.zoomScale = editor.getDOMHelper().calculateZoomScale();
 
        editor.setEditorStyle(IMAGE_EDIT_CLASS, `outline-style:none!important;`, [
            `span:has(>img${getSafeIdSelector(this.selectedImage.id)})`,
        ]);
 
        editor.setEditorStyle(IMAGE_EDIT_CLASS_CARET, `caret-color: transparent;`);
    }
 
    public startRotateAndResize(editor: IEditor, image: HTMLImageElement, isRTL: boolean) {
        Eif (this.imageEditInfo) {
            this.startEditing(editor, image, ['resize', 'rotate']);
            if (this.selectedImage && this.imageEditInfo && this.wrapper && this.clonedImage) {
                const isMobileOrTable = !!editor.getEnvironment().isMobileOrTablet;
                this.dndHelpers = [
                    ...getDropAndDragHelpers(
                        this.wrapper,
                        this.imageEditInfo,
                        this.options,
                        ImageEditElementClass.ResizeHandle,
                        Resizer,
                        () => {
                            if (
                                this.imageEditInfo &&
                                this.selectedImage &&
                                this.wrapper &&
                                this.clonedImage
                            ) {
                                updateWrapper(
                                    this.imageEditInfo,
                                    this.options,
                                    this.selectedImage,
                                    this.clonedImage,
                                    this.wrapper,
                                    this.resizers,
                                    undefined /* croppers */,
                                    isRTL
                                );
                                this.wasImageResized = true;
                            }
                        },
                        this.zoomScale,
                        isMobileOrTable
                    ),
                    ...getDropAndDragHelpers(
                        this.wrapper,
                        this.imageEditInfo,
                        this.options,
                        ImageEditElementClass.RotateHandle,
                        Rotator,
                        () => {
                            if (
                                this.imageEditInfo &&
                                this.selectedImage &&
                                this.wrapper &&
                                this.clonedImage
                            ) {
                                updateWrapper(
                                    this.imageEditInfo,
                                    this.options,
                                    this.selectedImage,
                                    this.clonedImage,
                                    this.wrapper,
                                    undefined /* resizers */,
                                    undefined /* croppers */,
                                    isRTL,
                                    true /* isRotating */
                                );
                                this.updateRotateHandleState(
                                    editor,
                                    this.selectedImage,
                                    this.wrapper,
                                    this.rotators,
                                    this.imageEditInfo?.angleRad,
                                    !!this.options?.disableSideResize
                                );
                                this.updateResizeHandleDirection(
                                    this.resizers,
                                    this.imageEditInfo.angleRad
                                );
                            }
                        },
                        this.zoomScale,
                        isMobileOrTable
                    ),
                ];
 
                updateWrapper(
                    this.imageEditInfo,
                    this.options,
                    this.selectedImage,
                    this.clonedImage,
                    this.wrapper,
                    this.resizers,
                    undefined /* croppers */,
                    isRTL
                );
 
                this.updateRotateHandleState(
                    editor,
                    this.selectedImage,
                    this.wrapper,
                    this.rotators,
                    this.imageEditInfo?.angleRad,
                    !!this.options?.disableSideResize
                );
            }
        }
    }
 
    private updateResizeHandleDirection(resizers: HTMLDivElement[], angleRad: number | undefined) {
        const resizeHandles = filterInnerResizerHandles(resizers);
        if (angleRad !== undefined) {
            updateHandleCursor(resizeHandles, angleRad);
        }
    }
 
    private updateRotateHandleState(
        editor: IEditor,
        image: HTMLImageElement,
        wrapper: HTMLSpanElement,
        rotators: HTMLDivElement[],
        angleRad: number | undefined,
        disableSideResize: boolean
    ) {
        const viewport = editor.getVisibleViewport();
        const smallImage = isASmallImage(image.width, image.height);
        Eif (viewport && rotators && rotators.length > 0) {
            const rotator = rotators[0];
            const rotatorHandle = rotator.firstElementChild;
            Eif (
                isNodeOfType(rotatorHandle, 'ELEMENT_NODE') &&
                isElementOfType(rotatorHandle, 'div')
            ) {
                updateRotateHandle(
                    viewport,
                    angleRad ?? 0,
                    wrapper,
                    rotator,
                    rotatorHandle,
                    smallImage,
                    disableSideResize
                );
            }
        }
    }
 
    public isOperationAllowed(operation: ImageEditOperation): boolean {
        return (
            operation === 'resize' ||
            operation === 'rotate' ||
            operation === 'flip' ||
            operation === 'crop'
        );
    }
 
    public canRegenerateImage(image: HTMLImageElement): boolean {
        return canRegenerateImage(image);
    }
 
    private startCropMode(editor: IEditor, image: HTMLImageElement, isRTL: boolean) {
        if (this.imageEditInfo) {
            this.startEditing(editor, image, ['crop']);
            if (this.imageEditInfo && this.selectedImage && this.wrapper && this.clonedImage) {
                this.dndHelpers = [
                    ...getDropAndDragHelpers(
                        this.wrapper,
                        this.imageEditInfo,
                        this.options,
                        ImageEditElementClass.CropHandle,
                        Cropper,
                        () => {
                            if (
                                this.imageEditInfo &&
                                this.selectedImage &&
                                this.wrapper &&
                                this.clonedImage
                            ) {
                                updateWrapper(
                                    this.imageEditInfo,
                                    this.options,
                                    this.selectedImage,
                                    this.clonedImage,
                                    this.wrapper,
                                    undefined /* resizers */,
                                    this.croppers,
                                    isRTL
                                );
                                this.isCropMode = true;
                            }
                        },
                        this.zoomScale,
                        !!editor.getEnvironment().isMobileOrTablet
                    ),
                ];
                updateWrapper(
                    this.imageEditInfo,
                    this.options,
                    this.selectedImage,
                    this.clonedImage,
                    this.wrapper,
                    undefined /* resizers */,
                    this.croppers,
                    isRTL
                );
            }
        }
    }
 
    public cropImage() {
        Iif (!this.editor) {
            return;
        }
        Eif (!this.editor.getEnvironment().isSafari) {
            this.editor.focus(); // Safari will keep the selection when click crop, then the focus() call should not be called
        }
        const selection = this.editor.getDOMSelection();
        Eif (selection?.type == 'image') {
            this.applyFormatWithContentModel(
                this.editor,
                true /* isCropMode */,
                false /* shouldSelectImage */
            );
        }
    }
 
    private editImage(
        editor: IEditor,
        image: HTMLImageElement,
        apiOperation: ImageEditOperation[],
        operation: (imageEditInfo: ImageMetadataFormat) => void
    ) {
        this.startEditing(editor, image, apiOperation);
        if (!this.selectedImage || !this.imageEditInfo || !this.wrapper || !this.clonedImage) {
            return;
        }
 
        operation(this.imageEditInfo);
 
        updateWrapper(
            this.imageEditInfo,
            this.options,
            this.selectedImage,
            this.clonedImage,
            this.wrapper
        );
 
        this.applyFormatWithContentModel(
            editor,
            false /* isCrop */,
            true /* shouldSelect*/,
            true /* isApiOperation */
        );
    }
 
    /**
     * Exported for testing purpose only
     */
    public cleanInfo() {
        this.editor?.setEditorStyle(IMAGE_EDIT_CLASS, null);
        this.editor?.setEditorStyle(IMAGE_EDIT_CLASS_CARET, null);
        this.selectedImage = null;
        this.shadowSpan = null;
        this.wrapper = null;
        this.imageEditInfo = null;
        this.imageHTMLOptions = null;
        this.dndHelpers.forEach(helper => helper.dispose());
        this.dndHelpers = [];
        this.clonedImage = null;
        this.lastSrc = null;
        this.wasImageResized = false;
        this.isCropMode = false;
        this.resizers = [];
        this.rotators = [];
        this.croppers = [];
    }
 
    private removeImageWrapper() {
        let image: HTMLImageElement | null = null;
        if (this.shadowSpan && this.shadowSpan.parentElement) {
            if (
                this.shadowSpan.firstElementChild &&
                isNodeOfType(this.shadowSpan.firstElementChild, 'ELEMENT_NODE') &&
                isElementOfType(this.shadowSpan.firstElementChild, 'img')
            ) {
                image = this.shadowSpan.firstElementChild;
            }
            unwrap(this.shadowSpan);
            this.shadowSpan = null;
            this.wrapper = null;
        }
 
        return image;
    }
 
    public flipImage(direction: 'horizontal' | 'vertical') {
        const selection = this.editor?.getDOMSelection();
        Iif (!this.editor || !selection || selection.type !== 'image') {
            return;
        }
        const image = selection.image;
        Eif (this.editor) {
            this.editImage(this.editor, image, ['flip'], imageEditInfo => {
                const angleRad = imageEditInfo.angleRad || 0;
                const isInVerticalPostion =
                    (angleRad >= Math.PI / 2 && angleRad < (3 * Math.PI) / 4) ||
                    (angleRad <= -Math.PI / 2 && angleRad > (-3 * Math.PI) / 4);
                Iif (isInVerticalPostion) {
                    if (direction === 'horizontal') {
                        imageEditInfo.flippedVertical = !imageEditInfo.flippedVertical;
                    } else {
                        imageEditInfo.flippedHorizontal = !imageEditInfo.flippedHorizontal;
                    }
                } else {
                    Iif (direction === 'vertical') {
                        imageEditInfo.flippedVertical = !imageEditInfo.flippedVertical;
                    } else {
                        imageEditInfo.flippedHorizontal = !imageEditInfo.flippedHorizontal;
                    }
                }
            });
        }
    }
 
    public rotateImage(angleRad: number) {
        const selection = this.editor?.getDOMSelection();
        Iif (!this.editor || !selection || selection.type !== 'image') {
            return;
        }
        const image = selection.image;
        Eif (this.editor) {
            this.editImage(this.editor, image, [], imageEditInfo => {
                imageEditInfo.angleRad = (imageEditInfo.angleRad || 0) + angleRad;
            });
        }
    }
}