All files / roosterjs-content-model-dom/lib/modelApi/editing setTableCellBackgroundColor.ts

76.36% Statements 42/55
41.94% Branches 26/62
70% Functions 7/10
76.36% Lines 42/55

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 1431x 1x 1x           1x 1x 1x 1x                 1x           241x 128x   128x 5x 5x 5x 5x       128x   128x 5x 123x 93x   30x     128x 119x     113x 113x 113x 111x           111x 83x 83x   83x           83x 84x                       119x 89x                                                                                     128x       128x 37x 37x 37x     37x   91x      
import { mutateBlock } from '../common/mutate';
import { parseColor } from '../../formatHandlers/utils/color';
import { updateTableCellMetadata } from '../metadata/updateTableCellMetadata';
import type { ShallowMutableContentModelTableCell } from 'roosterjs-content-model-types';
 
// Using the HSL (hue, saturation and lightness) representation for RGB color values.
// If the value of the lightness is less than 20, the color is dark.
// If the value of the lightness is more than 80, the color is bright
const DARK_COLORS_LIGHTNESS = 20;
const BRIGHT_COLORS_LIGHTNESS = 80;
const White = '#ffffff';
const Black = '#000000';
 
/**
 * Set shade color of table cell
 * @param cell The cell to set shade color to
 * @param color The color to set
 * @param isColorOverride @optional When pass true, it means this shade color is not part of table format, so it can be preserved when apply table format
 * @param applyToSegments @optional When pass true, we will also apply text color from table cell to its child blocks and segments
 */
export function setTableCellBackgroundColor(
    cell: ShallowMutableContentModelTableCell,
    color: string | null | undefined,
    isColorOverride?: boolean,
    applyToSegments?: boolean
) {
    if (color) {
        cell.format.backgroundColor = color;
 
        if (isColorOverride) {
            updateTableCellMetadata(cell, metadata => {
                metadata = metadata || {};
                metadata.bgColorOverride = true;
                return metadata;
            });
        }
 
        const lightness = calculateLightness(color);
 
        if (lightness < DARK_COLORS_LIGHTNESS) {
            cell.format.textColor = White;
        } else if (lightness > BRIGHT_COLORS_LIGHTNESS) {
            cell.format.textColor = Black;
        } else {
            delete cell.format.textColor;
        }
 
        if (applyToSegments) {
            setAdaptiveCellColor(cell);
        }
    } else {
        delete cell.format.backgroundColor;
        delete cell.format.textColor;
        if (applyToSegments) {
            removeAdaptiveCellColor(cell);
        }
    }
}
 
function removeAdaptiveCellColor(cell: ShallowMutableContentModelTableCell) {
    cell.blocks.forEach(readonlyBlock => {
        Eif (readonlyBlock.blockType == 'Paragraph') {
            const block = mutateBlock(readonlyBlock);
 
            Iif (
                block.segmentFormat?.textColor &&
                shouldRemoveColor(block.segmentFormat?.textColor, cell.format.backgroundColor || '')
            ) {
                delete block.segmentFormat.textColor;
            }
            block.segments.forEach(segment => {
                Iif (
                    segment.format.textColor &&
                    shouldRemoveColor(segment.format.textColor, cell.format.backgroundColor || '')
                ) {
                    delete segment.format.textColor;
                }
            });
        }
    });
}
 
function setAdaptiveCellColor(cell: ShallowMutableContentModelTableCell) {
    if (cell.format.textColor) {
        cell.blocks.forEach(readonlyBlock => {
            if (readonlyBlock.blockType == 'Paragraph') {
                const block = mutateBlock(readonlyBlock);
 
                if (!block.segmentFormat?.textColor) {
                    block.segmentFormat = {
                        ...block.segmentFormat,
                        textColor: cell.format.textColor,
                    };
                }
                block.segments.forEach(segment => {
                    if (!segment.format?.textColor) {
                        segment.format = {
                            ...segment.format,
                            textColor: cell.format.textColor,
                        };
                    }
                });
            }
        });
    }
}
 
/**
 * If the cell background color is too dark or too bright, and the text color is white or black, we should remove the text color
 * @param textColor the segment or block text color
 * @param cellBackgroundColor the cell background color
 * @returns
 */
function shouldRemoveColor(textColor: string, cellBackgroundColor: string) {
    const lightness = calculateLightness(cellBackgroundColor);
    if (
        ([White, 'rgb(255,255,255)'].indexOf(textColor) > -1 &&
            (lightness > BRIGHT_COLORS_LIGHTNESS || cellBackgroundColor == '')) ||
        ([Black, 'rgb(0,0,0)'].indexOf(textColor) > -1 &&
            (lightness < DARK_COLORS_LIGHTNESS || cellBackgroundColor == ''))
    ) {
        return true;
    }
    return false;
}
 
function calculateLightness(color: string) {
    const colorValues = parseColor(color);
 
    // Use the values of r,g,b to calculate the lightness in the HSl representation
    //First calculate the fraction of the light in each color, since in css the value of r,g,b is in the interval of [0,255], we have
    if (colorValues) {
        const red = colorValues[0] / 255;
        const green = colorValues[1] / 255;
        const blue = colorValues[2] / 255;
 
        //Then the lightness in the HSL representation is the average between maximum fraction of r,g,b and the minimum fraction
        return (Math.max(red, green, blue) + Math.min(red, green, blue)) * 50;
    } else {
        return 255;
    }
}