All files / roosterjs-content-model-dom/lib/formatHandlers/utils color.ts

100% Statements 57/57
98.82% Branches 84/85
100% Functions 6/6
100% Lines 53/53

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 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 1851x                   1x                                                   1x 1x 1x 1x 1x 1x 1x 1x 1x                 1x             4730x       4730x 62x 4668x 204x   204x 8x 196x       18x       4730x                     1x             554x 554x   554x   554x 417x   417x     417x     417x         417x     554x 554x               1x 409x                 1x 203x     203x 2x         201x 65x 136x 36x       100x               18x   18x 14x 18x   18x               14x 12x       6x    
import { getObjectKeys } from '../../domUtils/getObjectKeys';
import type {
    DarkColorHandler,
    Colors,
    ColorTransformFunction,
} from 'roosterjs-content-model-types';
 
/**
 * List of deprecated colors
 */
export const DeprecatedColors: string[] = [
    'inactiveborder',
    'activeborder',
    'inactivecaptiontext',
    'inactivecaption',
    'activecaption',
    'appworkspace',
    'infobackground',
    'background',
    'buttonhighlight',
    'buttonshadow',
    'captiontext',
    'infotext',
    'menutext',
    'menu',
    'scrollbar',
    'threeddarkshadow',
    'threedface',
    'threedhighlight',
    'threedlightshadow',
    'threedfhadow',
    'windowtext',
    'windowframe',
    'window',
];
 
const BlackColor = 'rgb(0, 0, 0)';
const HEX3_REGEX = /^#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])$/;
const HEX6_REGEX = /^#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})$/;
const RGB_REGEX = /^rgb\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*\)$/;
const RGBA_REGEX = /^rgba\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*\)$/;
const VARIABLE_REGEX = /^\s*var\(\s*(\-\-[a-zA-Z0-9\-_]+)\s*(?:,\s*(.*))?\)\s*$/;
const VARIABLE_PREFIX = 'var(';
const VARIABLE_POSTFIX = ')';
const COLOR_VAR_PREFIX = '--darkColor';
 
/**
 * Get color from given HTML element
 * @param element The element to get color from
 * @param isBackground True to get background color, false to get text color
 * @param isDarkMode Whether element is in dark mode now
 * @param darkColorHandler @optional The dark color handler object to help manager dark mode color
 */
export function getColor(
    element: HTMLElement,
    isBackground: boolean,
    isDarkMode: boolean,
    darkColorHandler?: DarkColorHandler
): string | undefined {
    let color =
        (isBackground ? element.style.backgroundColor : element.style.color) ||
        element.getAttribute(isBackground ? 'bgcolor' : 'color') ||
        undefined;
 
    if (color && DeprecatedColors.indexOf(color) > -1) {
        color = isBackground ? undefined : BlackColor;
    } else if (darkColorHandler && color) {
        const match = color.startsWith(VARIABLE_PREFIX) ? VARIABLE_REGEX.exec(color) : null;
 
        if (match) {
            color = match[2] || '';
        } else if (isDarkMode) {
            // If editor is in dark mode but the color is not in dark color format, it is possible the color was inserted from external code
            // without any light color info. So we first try to see if there is a known dark color can match this color, and use its related
            // light color as light mode color. Otherwise we need to drop this color to avoid show "white on white" content.
            color = findLightColorFromDarkColor(color, darkColorHandler.knownColors) || '';
        }
    }
 
    return color;
}
 
/**
 * Set color to given HTML element
 * @param element The element to set color to
 * @param color The color to set, always pass in color in light mode
 * @param isBackground True to set background color, false to set text color
 * @param isDarkMode Whether element is in dark mode now
 * @param darkColorHandler @optional The dark color handler object to help manager dark mode color
 */
export function setColor(
    element: HTMLElement,
    color: string | null | undefined,
    isBackground: boolean,
    isDarkMode: boolean,
    darkColorHandler?: DarkColorHandler
) {
    const match = color && color.startsWith(VARIABLE_PREFIX) ? VARIABLE_REGEX.exec(color) : null;
    const [_, existingKey, fallbackColor] = match ?? [];
 
    color = fallbackColor ?? color;
 
    if (darkColorHandler && color) {
        const colorType = isBackground ? 'background' : 'text';
        const key =
            existingKey ||
            darkColorHandler.generateColorKey(color, undefined /*baseLValue*/, colorType, element);
        const darkModeColor =
            darkColorHandler.knownColors?.[key]?.darkModeColor ||
            darkColorHandler.getDarkColor(color, undefined /*baseLValue*/, colorType, element);
 
        darkColorHandler.updateKnownColor(isDarkMode, key, {
            lightModeColor: color,
            darkModeColor,
        });
 
        color = isDarkMode ? `${VARIABLE_PREFIX}${key}, ${color}${VARIABLE_POSTFIX}` : color;
    }
 
    element.removeAttribute(isBackground ? 'bgcolor' : 'color');
    element.style.setProperty(isBackground ? 'background-color' : 'color', color || null);
}
 
/**
 * Generate color key for dark color
 * @param lightColor The input light color
 * @returns Key of the color
 */
export const defaultGenerateColorKey: ColorTransformFunction = lightColor => {
    return `${COLOR_VAR_PREFIX}_${lightColor.replace(/[^\d\w]/g, '_')}`;
};
 
/**
 * Parse color string to r/g/b value.
 * If the given color is not in a recognized format, return null
 * @param color The source color to parse
 * @returns An array of Red/Green/Blue value, or null if fail to parse
 */
export function parseColor(color: string): [number, number, number] | null {
    color = (color || '').trim();
 
    let match: RegExpMatchArray | null;
    if ((match = color.match(HEX3_REGEX))) {
        return [
            parseInt(match[1] + match[1], 16),
            parseInt(match[2] + match[2], 16),
            parseInt(match[3] + match[3], 16),
        ];
    } else if ((match = color.match(HEX6_REGEX))) {
        return [parseInt(match[1], 16), parseInt(match[2], 16), parseInt(match[3], 16)];
    } else if ((match = color.match(RGB_REGEX) || color.match(RGBA_REGEX))) {
        return [parseInt(match[1]), parseInt(match[2]), parseInt(match[3])];
    } else {
        // CSS color names such as red, green is not included for now.
        // If need, we can add those colors from https://www.w3.org/wiki/CSS/Properties/color/keywords
        return null;
    }
}
 
function findLightColorFromDarkColor(
    darkColor: string,
    knownColors?: Record<string, Colors>
): string | null {
    const rgbSearch = parseColor(darkColor);
 
    if (rgbSearch && knownColors) {
        const key = getObjectKeys(knownColors).find(key => {
            const rgbCurrent = parseColor(knownColors[key].darkModeColor);
 
            return (
                rgbCurrent &&
                rgbCurrent[0] == rgbSearch[0] &&
                rgbCurrent[1] == rgbSearch[1] &&
                rgbCurrent[2] == rgbSearch[2]
            );
        });
 
        if (key) {
            return knownColors[key].lightModeColor;
        }
    }
 
    return null;
}