All files / roosterjs-content-model-api/lib/publicApi/image changeImage.ts

100% Statements 16/16
70.59% Branches 12/17
100% Functions 3/3
100% Lines 16/16

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 361x 1x               1x 4x   4x 4x 4x 4x 1x 1x   1x 1x 1x 1x 1x   1x                    
import { formatImageWithContentModel } from '../utils/formatImageWithContentModel';
import { getImageMetadata, readFile } from 'roosterjs-content-model-dom';
import type { ContentModelImage, IEditor } from 'roosterjs-content-model-types';
 
/**
 * Change the selected image src
 * @param editor The editor instance
 * @param file The image file
 */
export function changeImage(editor: IEditor, file: File) {
    editor.focus();
 
    const selection = editor.getDOMSelection();
    readFile(file, dataUrl => {
        Eif (dataUrl && !editor.isDisposed() && selection?.type === 'image') {
            formatImageWithContentModel(editor, 'changeImage', (image: ContentModelImage) => {
                const originalSrc = getImageMetadata(image)?.src ?? '';
                const previousSrc = image.src;
 
                image.src = dataUrl;
                image.dataset = {};
                image.format.width = '';
                image.format.height = '';
                image.alt = '';
 
                editor.triggerEvent('editImage', {
                    image: selection.image,
                    previousSrc,
                    newSrc: dataUrl,
                    originalSrc,
                });
            });
        }
    });
}