All files / roosterjs-content-model-dom/lib/formatHandlers/common sizeFormatHandler.ts

100% Statements 35/35
100% Branches 38/38
100% Functions 3/3
100% Lines 35/35

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      1x         1x   1419x 1419x 1419x 1419x 1419x 1419x   1419x 266x   1419x 214x   1419x 8x   1419x 2x   1419x 1x   1419x 1x       1707x 75x   1707x 61x   1707x 15x   1707x 3x   1707x 1x   1707x 1x           2366x 2366x   2366x            
import type { FormatHandler } from '../FormatHandler';
import type { SizeFormat } from 'roosterjs-content-model-types';
 
const PercentageRegex = /[\d\.]+%/;
 
/**
 * @internal
 */
export const sizeFormatHandler: FormatHandler<SizeFormat> = {
    parse: (format, element, context) => {
        const width = element.style.width || tryParseSize(element, 'width');
        const height = element.style.height || tryParseSize(element, 'height');
        const maxWidth = element.style.maxWidth;
        const maxHeight = element.style.maxHeight;
        const minWidth = element.style.minWidth;
        const minHeight = element.style.minHeight;
 
        if (width) {
            format.width = width;
        }
        if (height) {
            format.height = height;
        }
        if (maxWidth) {
            format.maxWidth = maxWidth;
        }
        if (maxHeight) {
            format.maxHeight = maxHeight;
        }
        if (minWidth) {
            format.minWidth = minWidth;
        }
        if (minHeight) {
            format.minHeight = minHeight;
        }
    },
    apply: (format, element) => {
        if (format.width) {
            element.style.width = format.width;
        }
        if (format.height) {
            element.style.height = format.height;
        }
        if (format.maxWidth) {
            element.style.maxWidth = format.maxWidth;
        }
        if (format.maxHeight) {
            element.style.maxHeight = format.maxHeight;
        }
        if (format.minWidth) {
            element.style.minWidth = format.minWidth;
        }
        if (format.minHeight) {
            element.style.minHeight = format.minHeight;
        }
    },
};
 
function tryParseSize(element: HTMLElement, attrName: 'width' | 'height'): string | undefined {
    const attrValue = element.getAttribute(attrName);
    const value = parseInt(attrValue || '');
 
    return attrValue && PercentageRegex.test(attrValue)
        ? attrValue
        : Number.isNaN(value) || value == 0
        ? undefined
        : value + 'px';
}