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

98.51% Statements 66/67
96.7% Branches 88/91
100% Functions 9/9
98.41% Lines 62/63

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 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 2671x 1x                     1x                                                   1x 1x 1x 1x 1x 1x 1x 1x 1x                   1x             6500x   6500x                         1x           643x 38x   605x   605x 18x 587x       30x     575x           1x         6510x   3357x     3153x                               1x               742x                 742x 742x           1x               773x 773x   773x   773x   649x                 649x                 649x         649x     773x               1x             635x 635x                 1x 314x     314x 2x         312x 151x 161x 50x       111x               30x   30x 24x 31x   31x               24x 21x       9x    
import { BorderColorKeyMap } from './borderKeys';
import { getObjectKeys } from '../../domUtils/getObjectKeys';
import type {
    DarkColorHandler,
    Colors,
    ColorTransformFunction,
    BorderKey,
} 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
 * @param fallback @optional Fallback color to use if no color is found from the element
 */
export function getColor(
    element: HTMLElement,
    isBackground: boolean,
    isDarkMode: boolean,
    darkColorHandler?: DarkColorHandler,
    fallback?: string
): string | undefined {
    const color = retrieveElementColor(element, isBackground ? 'background' : 'text', fallback);
 
    return color
        ? getLightModeColor(
              color,
              isDarkMode,
              darkColorHandler,
              isBackground ? undefined : BlackColor
          )
        : undefined;
}
 
/**
 * @internal
 */
export function getLightModeColor(
    color: string,
    isDarkMode: boolean,
    darkColorHandler?: DarkColorHandler,
    fallback?: string
) {
    if (DeprecatedColors.indexOf(color) > -1) {
        return fallback;
    } else {
        const match = color.startsWith(VARIABLE_PREFIX) ? VARIABLE_REGEX.exec(color) : null;
 
        if (match) {
            color = match[2] || '';
        } else if (isDarkMode && darkColorHandler) {
            // 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.
            return findLightColorFromDarkColor(color, darkColorHandler.knownColors) || '';
        }
    }
    return color;
}
 
/**
 * @internal
 */
export function retrieveElementColor(
    element: HTMLElement,
    source: 'text' | 'background' | BorderKey,
    fallback?: string
): string | undefined {
    switch (source) {
        case 'text':
            return element.style.color || element.getAttribute('color') || fallback;
 
        case 'background':
            return element.style.backgroundColor || element.getAttribute('bgcolor') || fallback;
 
        default:
            return element.style.getPropertyValue(BorderColorKeyMap[source]) || fallback;
    }
}
 
/**
 * 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
 * @param comparingColor @optional When generating dark color for background color, we can provide text color as comparingColor to make sure the generated dark border color has enough contrast with text color in dark mode
 */
export function setColor(
    element: HTMLElement,
    color: string | null | undefined,
    isBackground: boolean,
    isDarkMode: boolean,
    darkColorHandler?: DarkColorHandler,
    comparingColor?: string
) {
    const newColor = adaptColor(
        element,
        color,
        isBackground ? 'background' : 'text',
        isDarkMode,
        darkColorHandler,
        comparingColor
    );
 
    element.removeAttribute(isBackground ? 'bgcolor' : 'color');
    element.style.setProperty(isBackground ? 'background-color' : 'color', newColor || null);
}
 
/**
 * @internal
 */
export function adaptColor(
    element: HTMLElement,
    color: string | null | undefined,
    colorType: 'text' | 'background' | 'border',
    isDarkMode: boolean,
    darkColorHandler?: DarkColorHandler,
    comparingColor?: string
) {
    const match = color && color.startsWith(VARIABLE_PREFIX) ? VARIABLE_REGEX.exec(color) : null;
    const [_, existingKey, fallbackColor] = match ?? [];
 
    color = fallbackColor ?? color;
 
    if (darkColorHandler && color) {
        const key =
            existingKey ||
            darkColorHandler.generateColorKey(
                color,
                undefined /*baseLValue*/,
                colorType,
                element,
                comparingColor
            );
        const darkModeColor =
            darkColorHandler.knownColors?.[key]?.darkModeColor ||
            darkColorHandler.getDarkColor(
                color,
                undefined /*baseLValue*/,
                colorType,
                element,
                comparingColor
            );
 
        darkColorHandler.updateKnownColor(isDarkMode, key, {
            lightModeColor: color,
            darkModeColor,
        });
 
        color = isDarkMode ? `${VARIABLE_PREFIX}${key}, ${color}${VARIABLE_POSTFIX}` : color;
    }
 
    return color;
}
 
/**
 * Generate color key for dark color
 * @param lightColor The input light color
 * @returns Key of the color
 */
export const defaultGenerateColorKey: ColorTransformFunction = (
    lightColor,
    _1,
    _2,
    _3,
    comparingColor
) => {
    const comparingColorKey = comparingColor ? `_${comparingColor.replace(/[^\d\w]/g, '_')}` : '';
    return `${COLOR_VAR_PREFIX}_${lightColor.replace(/[^\d\w]/g, '_')}${comparingColorKey}`;
};
 
/**
 * 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;
}