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

72.22% Statements 13/18
41.67% Branches 5/12
100% Functions 1/1
72.22% Lines 13/18

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                1x       2x 1x         1x             1x 1x 1x 1x 1x 1x 1x 1x 1x                
/**
 * @internal
 * Check if we can regenerate edited image from the source image.
 * An image can't regenerate result when there is CORS issue of the source content.
 * @param img The image element to test
 * @param resolveImageSource Optional callback to resolve an image `src` into a canvas-safe URL (e.g., a data URL).
 * @returns True when we can regenerate the edited image, otherwise false
 */
export function canRegenerateImage(
    img: HTMLImageElement | null,
    resolveImageSource?: (src: string) => string | undefined
): boolean {
    if (!img) {
        return false;
    }
 
    // If a resolveImageSource callback is provided, the image source should be resolved to a
    // canvas-compatible URL when editing starts, so we can assume the image can be regenerated.
    Iif (resolveImageSource && img.src) {
        const resolved = resolveImageSource(img.src);
        if (resolved && resolved !== img.src) {
            return true;
        }
    }
 
    try {
        const canvas = img.ownerDocument.createElement('canvas');
        canvas.width = 10;
        canvas.height = 10;
        const context = canvas.getContext('2d');
        Eif (context) {
            context.drawImage(img, 0, 0);
            context.getImageData(0, 0, 1, 1);
            return true;
        }
 
        return false;
    } catch {
        return false;
    }
}