All files / roosterjs-content-model-plugins/lib/paste/parsers imageSizeParser.ts

100% Statements 11/11
100% Branches 7/7
100% Functions 1/1
100% Lines 10/10

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 291x       1x           1x         14x 14x   14x 3x     3x 1x 1x        
import { parseValueWithUnit } from 'roosterjs-content-model-dom';
import type { ContentModelImageFormat, FormatParser } from 'roosterjs-content-model-types';
 
// Only process absolute units (px, pt, in, cm, mm)
const AbsoluteUnitRegex = /^\s*\d+(\.\d+)?\s*(px|pt|in|cm|mm)\s*$/i;
 
/**
 * @internal
 * Remove image size if it is larger than editor view width to let it auto size
 */
export const imageSizeParser: FormatParser<ContentModelImageFormat> = (
    format,
    element,
    context
) => {
    const maxImageSize = context.editorViewWidth;
    const { width } = format;
 
    if (width && maxImageSize && AbsoluteUnitRegex.test(width)) {
        const widthValue = parseValueWithUnit(width, element);
 
        // If the given width is larger than editor view width, we clear both width and height to let it auto size
        if (widthValue > maxImageSize) {
            delete format.width;
            delete format.height;
        }
    }
};