Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
"main": "src/server.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"test": "vitest",
"test:coverage": "vitest run --coverage",
"start": "node .",
"dev": "nodemon . --ignore 'src/assets/js/*.js' --ignore 'cypress/**/*.js' --ignore 'test/**/*.js'",
"css": "npx tailwindcss -i ./src/tailwind.css -o ./src/assets/css/index.css --watch",
Expand Down Expand Up @@ -56,6 +57,13 @@
"nodemon": "^3.0.2",
"supertest": "^6.3.3",
"tailwindcss": "^3.1.8",
"vitest": "^3.0.7"
"vitest": "^3.1.3"
},
"vitest": {
"globals": true,
"environment": "node",
"include": [
"src/**/*.test.js"
]
}
}
101 changes: 101 additions & 0 deletions src/assets/js/theme-toggle.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import { meetsContrastStandard } from '../utils/color-contrast.js';

/**
* Theme management utility for dark mode
*/
class ThemeManager {
constructor() {
this.storageKey = 'theme-preference';
this.darkModeMediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
this.initTheme();
this.bindSystemThemeListener();
}

/**
* Initialize theme based on stored preference or system settings
*/
initTheme() {
const savedTheme = this.getStoredTheme();
const systemTheme = this.getSystemTheme();

if (savedTheme) {
this.applyTheme(savedTheme);
} else if (systemTheme) {
this.applyTheme(systemTheme);
}
}

/**
* Get stored theme preference
* @returns {string|null} Stored theme preference
*/
getStoredTheme() {
return localStorage.getItem(this.storageKey);
}

/**
* Get system's color scheme preference
* @returns {string} Theme based on system preference
*/
getSystemTheme() {
return this.darkModeMediaQuery.matches ? 'dark' : 'light';
}

/**
* Apply theme to the document
* @param {string} theme - Theme to apply (light/dark)
*/
applyTheme(theme) {
document.documentElement.classList.toggle('dark', theme === 'dark');
this.validateColorContrast();
localStorage.setItem(this.storageKey, theme);
}

/**
* Validate color contrast for current theme
*/
validateColorContrast() {
const isDarkMode = document.documentElement.classList.contains('dark');

// Example color validation for the entire page
const testCases = [
{
foreground: isDarkMode ? '#E0E0E0' : '#000000',
background: isDarkMode ? '#121212' : '#FFFFFF'
}
];

const invalidContrasts = testCases.filter(
colors => !meetsContrastStandard(colors.foreground, colors.background)
);

if (invalidContrasts.length > 0) {
console.warn('Color contrast issue detected in current theme', invalidContrasts);
}
}

/**
* Toggle between light and dark themes
*/
toggleTheme() {
const currentTheme = this.getStoredTheme() || this.getSystemTheme();
const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
this.applyTheme(newTheme);
}

/**
* Bind system theme change listener
*/
bindSystemThemeListener() {
this.darkModeMediaQuery.addEventListener('change', (e) => {
const systemTheme = e.matches ? 'dark' : 'light';
// Only change if no user preference is set
if (!this.getStoredTheme()) {
this.applyTheme(systemTheme);
}
});
}
}

// Export singleton instance
export const themeManager = new ThemeManager();
90 changes: 90 additions & 0 deletions src/utils/color-contrast.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/**
* Utility functions for color contrast validation
* Implements WCAG 2.1 contrast ratio calculation
*/

/**
* Convert hex color to RGB
* @param {string} hex - Hex color code
* @returns {Array} RGB values
*/
export function hexToRgb(hex) {
// Remove # if present
hex = hex.replace(/^#/, '');

// Handle 3-digit hex codes by doubling each character
if (hex.length === 3) {
hex = hex.split('').map(char => char + char).join('');
}

// Handle 6-digit hex codes
const bigint = parseInt(hex, 16);
const r = (bigint >> 16) & 255;
const g = (bigint >> 8) & 255;
const b = bigint & 255;

return [r, g, b];
}

/**
* Calculate relative luminance of a color
* @param {Array} rgb - RGB color values
* @returns {number} Relative luminance
*/
export function calculateRelativeLuminance(rgb) {
const [r, g, b] = rgb.map(c => {
c /= 255;
return c <= 0.03928
? c / 12.92
: Math.pow((c + 0.055) / 1.055, 2.4);
});

return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}

/**
* Calculate contrast ratio between two colors
* @param {string} color1 - First color (hex)
* @param {string} color2 - Second color (hex)
* @returns {number} Contrast ratio
*/
export function calculateContrastRatio(color1, color2) {
// Validate input
if (!color1 || !color2) {
throw new Error('Both colors must be provided');
}

// Convert colors to RGB
const rgb1 = hexToRgb(color1);
const rgb2 = hexToRgb(color2);

// Calculate luminance
const l1 = calculateRelativeLuminance(rgb1);
const l2 = calculateRelativeLuminance(rgb2);

// Calculate contrast ratio
const lighter = Math.max(l1, l2);
const darker = Math.min(l1, l2);

return (lighter + 0.05) / (darker + 0.05);
}

/**
* Check if color contrast meets WCAG 2.1 Level AA standard
* @param {string} foreground - Foreground color (hex)
* @param {string} background - Background color (hex)
* @returns {boolean} Whether contrast meets standard
*/
export function meetsContrastStandard(foreground, background) {
try {
const contrastRatio = calculateContrastRatio(foreground, background);

// WCAG 2.1 Level AA requires:
// - 4.5:1 for normal text
// - 3:1 for large text (18pt or 14pt bold)
return contrastRatio >= 4.5;
} catch (error) {
console.error('Contrast validation error:', error);
return false;
}
};
55 changes: 55 additions & 0 deletions src/utils/color-contrast.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { describe, it, expect } from 'vitest';
import {
hexToRgb,
calculateRelativeLuminance,
calculateContrastRatio,
meetsContrastStandard
} from './color-contrast.js';

describe('Color Contrast Utility', () => {
describe('hexToRgb', () => {
it('converts 6-digit hex to RGB', () => {
expect(hexToRgb('#FFFFFF')).toEqual([255, 255, 255]);
expect(hexToRgb('#000000')).toEqual([0, 0, 0]);
expect(hexToRgb('#FF0000')).toEqual([255, 0, 0]);
});

it('converts 3-digit hex to RGB', () => {
expect(hexToRgb('#FFF')).toEqual([255, 255, 255]);
expect(hexToRgb('#000')).toEqual([0, 0, 0]);
});
});

describe('calculateRelativeLuminance', () => {
it('calculates relative luminance correctly', () => {
expect(calculateRelativeLuminance([255, 255, 255])).toBeCloseTo(1);
expect(calculateRelativeLuminance([0, 0, 0])).toBeCloseTo(0);
});
});

describe('calculateContrastRatio', () => {
it('calculates contrast ratio between black and white', () => {
const ratio = calculateContrastRatio('#FFFFFF', '#000000');
expect(ratio).toBeCloseTo(21);
});

it('throws error for invalid colors', () => {
expect(() => calculateContrastRatio()).toThrow();
});
});

describe('meetsContrastStandard', () => {
it('validates high contrast colors', () => {
expect(meetsContrastStandard('#FFFFFF', '#000000')).toBe(true);
expect(meetsContrastStandard('#000000', '#FFFFFF')).toBe(true);
});

it('detects low contrast colors', () => {
expect(meetsContrastStandard('#888888', '#AAAAAA')).toBe(false);
});

it('handles error cases', () => {
expect(meetsContrastStandard()).toBe(false);
});
});
});
Loading