From addbdf499a8118afdfb446eee10831dc004414a8 Mon Sep 17 00:00:00 2001
From: Yuwang Cai <mrcaidev@gmail.com>
Date: Mon, 27 May 2024 13:22:57 +0800
Subject: [PATCH] refactor: utilize parseColorName in plugin part

---
 src/plugin.ts | 30 +++++++++++-------------------
 src/utils.ts  | 23 +++++++++++++++++++++++
 2 files changed, 34 insertions(+), 19 deletions(-)

diff --git a/src/plugin.ts b/src/plugin.ts
index 3815f5d..634c006 100644
--- a/src/plugin.ts
+++ b/src/plugin.ts
@@ -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
@@ -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;
diff --git a/src/utils.ts b/src/utils.ts
index 0601c0b..412040b 100644
--- a/src/utils.ts
+++ b/src/utils.ts
@@ -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;
+}