Skip to content

Commit

Permalink
allow hex colors for theme (#509)
Browse files Browse the repository at this point in the history
  • Loading branch information
mosch authored Jan 10, 2025
1 parent cdcc458 commit 6614f67
Showing 1 changed file with 63 additions and 1 deletion.
64 changes: 63 additions & 1 deletion packages/zudoku/src/vite/plugin-theme-css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,72 @@ const uncamelize = (str: string) =>

export type Theme = Partial<Record<(typeof THEME_VARIABLES)[number], string>>;

const hexToHSLA = (hex: string): string => {
// Remove # if present
hex = hex.replace('#', '');

// Convert 3-digit hex to 6-digit
if (hex.length === 3) {
hex = hex.split('').map(char => char + char).join('');
}

// Parse the hex values
const r = parseInt(hex.substring(0, 2), 16) / 255;
const g = parseInt(hex.substring(2, 4), 16) / 255;
const b = parseInt(hex.substring(4, 6), 16) / 255;

const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
let h = 0;
let s = 0;
const l = (max + min) / 2;

if (max !== min) {
const d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);

switch (max) {
case r:
h = (g - b) / d + (g < b ? 6 : 0);
break;
case g:
h = (b - r) / d + 2;
break;
case b:
h = (r - g) / d + 4;
break;
}

h /= 6;
}

// Convert to degrees and percentages
h = Math.round(h * 360);
s = Math.round(s * 100);
const lPercent = Math.round(l * 100);

return `${h} ${s}% ${lPercent}%`;
};

const isHexColor = (value: string): boolean => {
return /^#([A-Fa-f0-9]{3}){1,2}$/.test(value);
};

const processColorValue = (value: string | undefined): string => {
if (!value) return '';
if (isHexColor(value)) {
return hexToHSLA(value);
}
return value;
};

const generateCss = (theme: Theme) =>
objectEntries(theme)
.filter(([key]) => THEME_VARIABLES.includes(key))
.map(([key, value]) => `--${uncamelize(key)}:${value};`)
.map(([key, value]) => {
const processedValue = processColorValue(value);
return `--${uncamelize(key)}:${processedValue};`;
})
.join("\n");

export const viteThemeCss = (getConfig: () => ZudokuPluginOptions): Plugin => {
Expand Down

0 comments on commit 6614f67

Please sign in to comment.