Skip to content

Commit

Permalink
refactor: utilize parseColorName in plugin part
Browse files Browse the repository at this point in the history
  • Loading branch information
mrcaidev committed May 27, 2024
1 parent 943062d commit addbdf4
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 19 deletions.
30 changes: 11 additions & 19 deletions src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import type {
Palette,
TailwindcssRadixColorsOptions,
} from "./types";
import { buildColorName, parseColorName } from "./utils";

/**
* Build the "plugin" part of `tailwindcss-radix-colors`, which will be used as
Expand Down Expand Up @@ -211,27 +212,18 @@ function checkShouldProcess(
* it makes no sense to have a foreground text with alpha value.
*/
function findColorFamily(palette: Palette, colorName: string) {
// Dark colors have already been filtered by `checkShouldProcess`, so there
// is no need to put "dark" into regular expression again.
const regex = colorName.match(/^(.+?)(a|p3|p3a)?$/);

if (!regex) {
throw new Error(`Invalid color name: ${colorName}`);
}

const baseColorName = regex[1] as keyof typeof foregroundColorPairs;
const suffix = regex[2] ?? "";
const { base, p3, alpha } = parseColorName(colorName);

const darkColorName: ColorName =
baseColorName === "black"
? `white${suffix}`
: baseColorName === "white"
? `black${suffix}`
: `${baseColorName}dark${suffix}`;

const foregroundColorName = suffix.includes("p3")
? `${foregroundColorPairs[baseColorName]}p3`
: foregroundColorPairs[baseColorName];
base === "black"
? buildColorName({ base: "white", dark: false, p3, alpha })
: base === "white"
? buildColorName({ base: "black", dark: false, p3, alpha })
: buildColorName({ base, dark: true, p3, alpha });

const foregroundColorName = p3
? `${foregroundColorPairs[base as keyof typeof foregroundColorPairs]}p3`
: foregroundColorPairs[base as keyof typeof foregroundColorPairs];

const darkColor = palette[darkColorName] as Color;
const foregroundColor = palette[foregroundColorName] as Color;
Expand Down
23 changes: 23 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,26 @@ export function parseColorName(colorName: string) {
alpha: alpha !== undefined,
} as ParsedColorName;
}

/**
* Build a color name string from a parsed color name object.
*/
export function buildColorName(parsedColorName: ParsedColorName) {
const { base, dark, p3, alpha } = parsedColorName;

let colorName = base;

if (dark) {
colorName += "dark";
}

if (p3) {
colorName += "p3";
}

if (alpha) {
colorName += "a";
}

return colorName;
}

0 comments on commit addbdf4

Please sign in to comment.