Certainly! Here's an upgraded version of your theme configuration with some improvements for better usability, maintainability, and scalability. I've added:
More colours for better UI consistency.
Semantic colouring for better accessibility and theming.
A function to easily switch themes.
TypeScript types for better type safety (assuming you're using TypeScript; if not, you can remove the types).
CSS Custom Properties for easier CSS integration.
Upgraded Theme Configuration
typescript
// Define a type for the theme colours
type ThemeColours = {
primary: string;
background: string;
text: string;
secondary: string;
accent: string;
error: string;
warning: string;
success: string;
disabled: string;
};
// Define a type for the theme
type Theme = {
colours: ThemeColours;
};
// Light theme
export const lightTheme: Theme = {
colours: {
primary: '#ffffff',
background: '#f5f5f5',
text: '#000000',
secondary: '#e0e0e0',
accent: '#6200ee',
error: '#b00020',
warning: '#ffc107',
success: '#4caf50',
disabled: '#bdbdbd',
},
};
// Dark theme
export const darkTheme: Theme = {
colours: {
primary: '#121212',
background: '#000000',
text: '#ffffff',
secondary: '#303030',
accent: '#bb86fc',
error: '#cf6679',
warning: '#ffea00',
success: '#a5d6a7',
disabled: '#616161',
},
};
export const themes = {
LIGHT: 'light',
DARK: 'dark',
};
// Function to get the current theme
export const getTheme = (themeName: string): Theme => {
switch (themeName) {
case themes.DARK:
return darkTheme;
case themes.LIGHT:
default:
return lightTheme;
}
};
// Function to set CSS custom properties for the given theme
export const setCssCustomProperties = (theme: Theme) => {
const root = window.document.documentElement;
const { colours } = theme;
Object.entries(colours).forEach(([key, value]) => {
root.style.setProperty(`--colour-${key}`, value);
});
};
// Example usage
const currentTheme = getTheme(themes.DARK);
setCssCustomProperties(currentTheme);
Explanation:
Types:
ThemeColours: Defines the structure of the colours object.
Theme: Defines the structure of a theme.
Themes:
lightTheme and darkTheme now include additional colours for secondary, accent, error, warning, success, and disabled. These provide more flexibility when styling your application.
The colours have also been updated to be more modern.
getTheme Function:
This function takes a themeName and returns the corresponding theme. It defaults to the lightTheme if an invalid theme name is provided.
setCssCustomProperties Function:
This function takes a theme and sets CSS custom properties on the :root element. This allows you to easily use the theme colours in your CSS.
To use the CSS variables you can use var(--colour-primary) for example.
Usage in CSS
With the setCssCustomProperties function, you can now use the theme colours in your CSS like this: