From b8c78b618fd544fb19463759b746c8e4e7c43afd Mon Sep 17 00:00:00 2001 From: hamed-musallam Date: Mon, 13 Mar 2023 16:21:02 +0100 Subject: [PATCH] fix: parse hex color and extract opacity --- src/component/1d/Line.tsx | 11 +++++++---- src/component/utility/parseColor.ts | 20 ++++++++++++++++++++ 2 files changed, 27 insertions(+), 4 deletions(-) create mode 100644 src/component/utility/parseColor.ts diff --git a/src/component/1d/Line.tsx b/src/component/1d/Line.tsx index 551b56631..8dd52a6cc 100644 --- a/src/component/1d/Line.tsx +++ b/src/component/1d/Line.tsx @@ -4,6 +4,7 @@ import { useScaleChecked } from '../context/ScaleContext'; import useActiveSpectrumStyleOptions from '../hooks/useActiveSpectrumStyleOptions'; import useXYReduce, { XYReducerDomainAxis } from '../hooks/useXYReduce'; import { PathBuilder } from '../utility/PathBuilder'; +import { parseColor } from '../utility/parseColor'; interface LineProps { data?: { @@ -41,16 +42,18 @@ function Line({ data, id, display, index }: LineProps) { } }, [scaleX, scaleY, id, data, xyReduce]); + const { color: stroke, opacity: strokeOpacity } = parseColor( + display?.color || 'black', + ); + return ( diff --git a/src/component/utility/parseColor.ts b/src/component/utility/parseColor.ts new file mode 100644 index 000000000..e967f7a3b --- /dev/null +++ b/src/component/utility/parseColor.ts @@ -0,0 +1,20 @@ +export function parseColor(color: string) { + if (!color.startsWith('#')) { + return { color, opacity: 1 }; + } + + const hex = color.replace('#', ''); + + if (hex.length === 3) { + return { + color: `#${hex[0]}${hex[0]}${hex[1]}${hex[1]}${hex[2]}${hex[2]}`, + opacity: 1, + }; + } + + const hexOpacity = hex.slice(6) || 'FF'; + const opacity = + Math.round((Number.parseInt(hexOpacity, 16) / 255) * 100) / 100; + + return { color: `#${hex.slice(0, 6)}`, opacity }; +}