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

100% Statements 16/16
83.33% Branches 5/6
100% Functions 4/4
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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 501x                             1x 4x   4x 2x   2x 2x 2x             4x   4x 4x   4x 4x     4x 4x   4x              
import {
    mergeModel,
    readFile,
    addSegment,
    createContentModelDocument,
    createImage,
    setSelection,
} from 'roosterjs-content-model-dom';
import type { IEditor } from 'roosterjs-content-model-types';
 
/**
 * Insert an image into current selected position
 * @param editor The editor to operate on
 * @param file Image Blob file or source string
 */
export function insertImage(editor: IEditor, imageFileOrSrc: File | string) {
    editor.focus();
 
    if (typeof imageFileOrSrc == 'string') {
        insertImageWithSrc(editor, imageFileOrSrc);
    } else {
        readFile(imageFileOrSrc, dataUrl => {
            Eif (dataUrl && !editor.isDisposed()) {
                insertImageWithSrc(editor, dataUrl);
            }
        });
    }
}
 
function insertImageWithSrc(editor: IEditor, src: string) {
    editor.formatContentModel(
        (model, context) => {
            const image = createImage(src, { backgroundColor: '' });
            const doc = createContentModelDocument();
 
            addSegment(doc, image);
            mergeModel(model, doc, context, {
                mergeFormat: 'mergeAll',
            });
            image.isSelected = true;
            setSelection(model, image);
 
            return true;
        },
        {
            apiName: 'insertImage',
        }
    );
}