diff --git a/src/components/hexInput/index.ts b/src/components/hexInput/index.ts index 5abe271..d915ae7 100644 --- a/src/components/hexInput/index.ts +++ b/src/components/hexInput/index.ts @@ -5,6 +5,7 @@ import { oklabToOkhsv, sRgbToOklab } from "../../utils/color"; +import { isHex, getHexTokensFromString, getRgbaFromHex } from "../../utils/hex"; import { getOklab, updateSliderRangeInputs @@ -37,14 +38,10 @@ function handleFocus(e: Event) { function handleInput(e: Event) { const el = e.target; - let tokens = getHexTokens(el.value); + let hex = getHexTokensFromString(el.value); - if (isHex(tokens)) { - let [r, g, b, alpha] = tokens!.map((v: string) => - v.length === 1 ? parseInt(v + v, 16) : parseInt(v, 16) - ); - - alpha = alpha === undefined ? 1 : alpha / 255; + if (isHex(hex)) { + let [r, g, b, alpha] = getRgbaFromHex(hex); const fn = state.sliderMode === SLIDER_MODES.OKHSV ? oklabToOkhsv : oklabToOkhsl; @@ -72,16 +69,3 @@ function handleKeydown(e: KeyboardEvent) { } } } - -function getHexTokens(value: string) { - let tokens = value.match( - /^#*([a-f0-9]{1})([a-f0-9]{1})([a-f0-9]{1})$|^#*([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})$|^#*([a-f0-9]{1})([a-f0-9]{1})([a-f0-9]{1})([a-f0-9]{1})$|^#*([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})$/i - ); - tokens ??= []; - tokens &&= tokens.slice(1).filter((v) => !!v); // remove complete match and null matches - return tokens; -} - -function isHex(tokens: string[]) { - return !tokens?.length ? false : true; -} diff --git a/src/utils/hex.ts b/src/utils/hex.ts new file mode 100644 index 0000000..430a734 --- /dev/null +++ b/src/utils/hex.ts @@ -0,0 +1,20 @@ +export function isHex(tokens: string[]) { + return !tokens?.length ? false : true; +} + +export function getHexTokensFromString(value: string) { + let tokens = value.match( + /^#*([a-f0-9]{1})([a-f0-9]{1})([a-f0-9]{1})$|^#*([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})$|^#*([a-f0-9]{1})([a-f0-9]{1})([a-f0-9]{1})([a-f0-9]{1})$|^#*([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})$/i + ); + tokens ??= []; + tokens &&= tokens.slice(1).filter((v) => !!v); // remove complete match and null matches + return tokens; +} + +export function getRgbaFromHex(tokens: string[]) { + let [r, g, b, alpha] = tokens!.map((v: string) => + v.length === 1 ? parseInt(v + v, 16) : parseInt(v, 16) + ); + alpha = alpha === undefined ? 1 : alpha / 255; + return [r, g, b, alpha]; +}