Skip to content

Commit

Permalink
refactor: hex input
Browse files Browse the repository at this point in the history
  • Loading branch information
holbrookdev committed Jul 1, 2022
1 parent 5645a94 commit 5188f3d
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 20 deletions.
24 changes: 4 additions & 20 deletions src/components/hexInput/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
oklabToOkhsv,
sRgbToOklab
} from "../../utils/color";
import { isHex, getHexTokensFromString, getRgbaFromHex } from "../../utils/hex";
import {
getOklab,
updateSliderRangeInputs
Expand Down Expand Up @@ -37,14 +38,10 @@ function handleFocus(e: Event) {

function handleInput(e: Event) {
const el = <HTMLInputElement>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;
Expand Down Expand Up @@ -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;
}
20 changes: 20 additions & 0 deletions src/utils/hex.ts
Original file line number Diff line number Diff line change
@@ -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];
}

0 comments on commit 5188f3d

Please sign in to comment.