import { SpecifyColorValue } from '@specifyapp/specify-design-token-format'; import { AnyColor, colord, extend as extendColord } from 'colord'; import labPlugin from 'colord/plugins/lab'; import lchPlugin from 'colord/plugins/lch'; // @ts-ignore extendColord([labPlugin, lchPlugin]); export function colorToTarget( color: SpecifyColorValue, targetModel: SpecifyColorValue['model'], ): SpecifyColorValue { if (color.model === targetModel) return color; let input: AnyColor; switch (color.model) { case 'rgb': input = { r: color.red, g: color.green, b: color.blue, }; break; case 'hex': input = color.hex; break; case 'hsb': input = { h: color.hue, s: color.saturation, v: color.brightness, }; break; case 'hsl': input = { h: color.hue, s: color.saturation, l: color.lightness, }; break; case 'lab': input = { l: color.lightness, a: color.aAxis, b: color.bAxis, }; break; case 'lch': input = { l: color.lightness, c: color.chroma, h: color.hue, }; break; } const toConvert = colord(input); const common = { model: targetModel, alpha: color.alpha, }; switch (targetModel) { case 'rgb': const rgb = toConvert.toRgb(); return { ...common, red: rgb.r, green: rgb.g, blue: rgb.b, } as SpecifyColorValue; case 'hex': return { ...common, hex: toConvert.toHex(), } as SpecifyColorValue; case 'hsb': const hsb = toConvert.toHsv(); return { ...common, hue: hsb.h, saturation: hsb.s, brightness: hsb.v, } as SpecifyColorValue; case 'hsl': const hsl = toConvert.toHsl(); return { ...common, hue: hsl.h, saturation: hsl.s, lightness: hsl.l, } as SpecifyColorValue; case 'lab': const lab = toConvert.toLab(); return { ...common, lightness: lab.l, aAxis: lab.a, bAxis: lab.b, } as SpecifyColorValue; case 'lch': const lch = toConvert.toLch(); return { ...common, lightness: lch.l, chroma: lch.c, hue: lch.h, } as SpecifyColorValue; } }