All files / color get-svg-fill-color.ts

100% Statements 6/6
100% Branches 2/2
100% Functions 1/1
100% Lines 6/6

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    1x                       5x 5x 5x 2x   3x    
import type { Rgb } from './rgb';
 
const RGB_PATTERN = /^rgba?\((?<r>[\d.]+)[,\s]+(?<g>[\d.]+)[,\s]+(?<b>[\d.]+)/v;
 
/**
 * Reads the fill color of an SVG element as rendered, whatever sets it: attribute, class, inherited style.
 *
 * @param element - A rendered SVG element.
 * @returns The fill color.
 * @throws {TypeError} When the fill is not an sRGB color, such as `none` or a gradient.
 * @example
 * getSvgFillColor(tank); // { r: 0, g: 128, b: 255 }
 */
export function getSvgFillColor(element: SVGGraphicsElement): Rgb {
  const { fill } = getComputedStyle(element);
  const groups = RGB_PATTERN.exec(fill)?.groups;
  if (!groups) {
    throw new TypeError(`The fill is not an sRGB color: '${fill}'`);
  }
  return { r: Number(groups['r']), g: Number(groups['g']), b: Number(groups['b']) };
}