Skip to content

Commit

Permalink
Merge branch 'main' into derek/injectedAddButton3
Browse files Browse the repository at this point in the history
  • Loading branch information
doprz authored Jan 21, 2025
2 parents db0e562 + 1f635d2 commit 65a682b
Show file tree
Hide file tree
Showing 34 changed files with 1,162 additions and 239 deletions.
2 changes: 1 addition & 1 deletion src/pages/background/handler/userScheduleHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import type { MessageHandler } from 'chrome-extension-toolkit';

const userScheduleHandler: MessageHandler<UserScheduleMessages> = {
addCourse({ data, sendResponse }) {
addCourse(data.scheduleId, new Course(data.course)).then(sendResponse);
addCourse(data.scheduleId, new Course(data.course), data.hasColor ?? false).then(sendResponse);
},
removeCourse({ data, sendResponse }) {
removeCourse(data.scheduleId, new Course(data.course)).then(sendResponse);
Expand Down
2 changes: 1 addition & 1 deletion src/shared/messages/UserScheduleMessages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export interface UserScheduleMessages {
*
* @param data - The schedule id and course to add
*/
addCourse: (data: { scheduleId: string; course: Course }) => void;
addCourse: (data: { scheduleId: string; course: Course; hasColor?: boolean }) => void;

/**
* Adds a course by URL
Expand Down
5 changes: 5 additions & 0 deletions src/shared/types/Color.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,8 @@ export type sRGB = [r: number, g: number, b: number];
* Represents a Lab color value.
*/
export type Lab = [l: number, a: number, b: number];

/**
* Represents a HSL color value.
*/
export type HSL = [h: number, s: number, l: number];
12 changes: 12 additions & 0 deletions src/shared/types/Spacing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,15 @@ export const spacing = {
'spacing-7': '1.5rem',
'spacing-8': '2rem',
} as const;

type SpacingKey = keyof typeof spacing;

/**
* Converts a spacing value from rem to pixels
* @param key - The spacing key to convert
* @returns The spacing value in pixels
*/
export function getSpacingInPx(key: SpacingKey): number {
const remValue = parseFloat(spacing[key]);
return remValue * 16; // 1rem = 16px
}
176 changes: 165 additions & 11 deletions src/shared/util/colors.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import type { Serialized } from 'chrome-extension-toolkit';
import { theme } from 'unocss/preset-mini';

import type { HexColor, Lab, RGB, sRGB } from '../types/Color';
import type { HexColor, HSL, Lab, RGB, sRGB } from '../types/Color';
import { isHexColor } from '../types/Color';
import type { Course } from '../types/Course';
import type { CourseColors, TWColorway, TWIndex } from '../types/ThemeColors';
import { colorwayIndexes } from '../types/ThemeColors';
import { colors, colorwayIndexes } from '../types/ThemeColors';
import type { UserSchedule } from '../types/UserSchedule';

/**
Expand All @@ -26,6 +26,19 @@ export function hexToRGB(hex: HexColor): RGB | undefined {
return [parseInt(result[1]!, 16), parseInt(result[2]!, 16), parseInt(result[3]!, 16)];
}

/**
* Checks if a given string is a valid hex color.
*
* A valid hex color is a string that starts with a '#' followed by either
* 3 or 6 hexadecimal characters (0-9, A-F, a-f).
*
* @param hex - The hex color string to validate.
* @returns True if the string is a valid hex color, false otherwise.
*/
export function isValidHexColor(hex: string): boolean {
return /^#?([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/.test(hex);
}

export const useableColorways = Object.keys(theme.colors)
// check that the color is a colorway (is an object)
.filter(color => typeof theme.colors[color as keyof typeof theme.colors] === 'object')
Expand Down Expand Up @@ -56,6 +69,13 @@ export function pickFontColor(bgColor: HexColor): 'text-white' | 'text-black' |
return Ys < 0.365 ? 'text-black' : 'text-theme-black';
}

// Mapping of Tailwind CSS class names to their corresponding hex values
export const tailwindColorMap: Record<string, HexColor> = {
'text-white': '#FFFFFF',
'text-black': '#000000',
'text-theme-black': colors.theme.black,
};

/**
* Get primary and secondary colors from a Tailwind colorway
*
Expand All @@ -82,10 +102,15 @@ export function getCourseColors(colorway: TWColorway, index?: number, offset: nu
* @param color - The hexadecimal color value.
* @returns The Tailwind colorway.
*/
export function getColorwayFromColor(color: HexColor): TWColorway {
export function getColorwayFromColor(color: HexColor): {
colorway: TWColorway;
index: TWIndex;
} {
for (const colorway of useableColorways) {
if (Object.values(theme.colors[colorway]).includes(color)) {
return colorway as TWColorway;
const colorValues = Object.values(theme.colors[colorway]);
const index = colorValues.indexOf(color);
if (index !== -1) {
return { colorway: colorway as TWColorway, index: (index * 100) as TWIndex };
}
}

Expand Down Expand Up @@ -121,6 +146,124 @@ export function getColorwayFromColor(color: HexColor): TWColorway {
return getColorwayFromColor(closestColor);
}

/**
* Converts a hexadecimal color value to HSL (Hue, Saturation, Lightness) format
*
* @param hex - The hexadecimal color string
* @returns An array of [hue (0-360), saturation (0-100), lightness (0-100)]
* @throws If the hex color cannot be converted to RGB
*/
export const hexToHSL = (hex: HexColor): HSL => {
const rgb = hexToRGB(hex);

if (!rgb) {
throw new Error('hexToRGB returned undefined');
}

// Convert RGB to decimals
const r = rgb[0] / 255;
const g = rgb[1] / 255;
const b = rgb[2] / 255;

// Find min/max/delta
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
const delta = max - min;

// Calculate HSL values
let h = 0;
let s = 0;
let l = (max + min) / 2;

if (delta !== 0) {
// Calculate saturation
s = delta / (1 - Math.abs(2 * l - 1));

// Calculate hue
if (max === r) {
h = ((g - b) / delta) % 6;
} else if (max === g) {
h = (b - r) / delta + 2;
} else {
h = (r - g) / delta + 4;
}
h *= 60;
}

// Normalize values
h = Math.round(h < 0 ? h + 360 : h);
s = Math.round(s * 100);
l = Math.round(l * 100);

return [h, s, l];
};

/**
* Converts an HSL color value to RGB format.
*
* @param hsl - The HSL color value
* @returns An RGB color value
*/
function hslToRGB([hue, saturation, lightness]: HSL): RGB {
// Convert percentages to decimals
const s = saturation / 100;
const l = lightness / 100;

// Calculate intermediate values
const c = (1 - Math.abs(2 * l - 1)) * s;
const x = c * (1 - Math.abs(((hue / 60) % 2) - 1));
const m = l - c / 2;

let r = 0;
let g = 0;
let b = 0;

// Determine RGB values based on hue
if (hue >= 0 && hue < 60) {
[r, g, b] = [c, x, 0];
} else if (hue >= 60 && hue < 120) {
[r, g, b] = [x, c, 0];
} else if (hue >= 120 && hue < 180) {
[r, g, b] = [0, c, x];
} else if (hue >= 180 && hue < 240) {
[r, g, b] = [0, x, c];
} else if (hue >= 240 && hue < 300) {
[r, g, b] = [x, 0, c];
} else {
[r, g, b] = [c, 0, x];
}

// Convert to 0-255 range and round
return [Math.round((r + m) * 255), Math.round((g + m) * 255), Math.round((b + m) * 255)];
}

/**
* Returns a darker shade of the given hex color by reducing the lightness in HSL color space.
*
* @param color - The hexadecimal color value to darken.
* @param offset - The percentage to reduce the lightness by (default is 20).
* @returns The darker shade of the given hex color.
* @throws If the provided color is not a valid hex color.
*/
export function getDarkerShade(color: HexColor, offset: number = 20): HexColor {
const rgb = hexToRGB(color);
if (!rgb) {
throw new Error('color: Invalid hex.');
}

// Convert to HSL
const [h, s, l] = hexToHSL(color);

// Reduce lightness by offset percentage, ensuring it doesn't go below 0
const newL = Math.max(0, l - offset);

// Convert back to RGB
const newRGB = hslToRGB([h, s, newL]);

// Convert to hex
return `#${newRGB.map(c => Math.round(c).toString(16).padStart(2, '0')).join('')}`;
}

/**
* Get next unused color in a tailwind colorway for a given schedule
*
Expand Down Expand Up @@ -153,17 +296,28 @@ export function getUnusedColor(

const scheduleCourses = schedule.courses.map(c => ({
...c,
colorway: getColorwayFromColor(c.colors.primaryColor),
theme: (() => {
try {
return getColorwayFromColor(c.colors.primaryColor);
} catch (error) {
// Default to emerald colorway with index 500
return {
colorway: 'emerald' as TWColorway,
index: 500 as TWIndex,
};
}
})(),
}));
const usedColorways = new Set(scheduleCourses.map(c => c.colorway));

const usedColorways = new Set(scheduleCourses.map(c => c.theme.colorway));
const availableColorways = new Set(useableColorways.filter(c => !usedColorways.has(c)));

if (availableColorways.size > 0) {
let sameDepartment = scheduleCourses.filter(c => c.department === course.department);

sameDepartment.sort((a, b) => {
const aIndex = useableColorways.indexOf(a.colorway);
const bIndex = useableColorways.indexOf(b.colorway);
const aIndex = useableColorways.indexOf(a.theme.colorway);
const bIndex = useableColorways.indexOf(b.theme.colorway);

return aIndex - bIndex;
});
Expand All @@ -172,8 +326,8 @@ export function getUnusedColor(
// check to see if any adjacent colorways are available
const centerCourse = sameDepartment[Math.floor(Math.random() * sameDepartment.length)]!;

let nextColorway = getNextColorway(centerCourse.colorway);
let prevColorway = getPreviousColorway(centerCourse.colorway);
let nextColorway = getNextColorway(centerCourse.theme.colorway);
let prevColorway = getPreviousColorway(centerCourse.theme.colorway);

// eslint-disable-next-line no-constant-condition
while (true) {
Expand Down
81 changes: 81 additions & 0 deletions src/shared/util/tests/colors.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import { hexToHSL, isValidHexColor } from '@shared/util/colors';
import { describe, expect, it } from 'vitest';

describe('hexToHSL', () => {
it('should convert pure red to HSL', () => {
const result = hexToHSL('#FF0000');
expect(result).toEqual([0, 100, 50]);
});

it('should convert pure green to HSL', () => {
const result = hexToHSL('#00FF00');
expect(result).toEqual([120, 100, 50]);
});

it('should convert pure blue to HSL', () => {
const result = hexToHSL('#0000FF');
expect(result).toEqual([240, 100, 50]);
});

it('should convert white to HSL', () => {
const result = hexToHSL('#FFFFFF');
expect(result).toEqual([0, 0, 100]);
});

it('should convert black to HSL', () => {
const result = hexToHSL('#000000');
expect(result).toEqual([0, 0, 0]);
});

it('should convert UT burnt orange to HSL', () => {
const result = hexToHSL('#BF5700');
expect(result).toEqual([27, 100, 37]);
});

it('should convert gray to HSL', () => {
const result = hexToHSL('#808080');
expect(result).toEqual([0, 0, 50]);
});

it('should throw error for invalid hex color', () => {
expect(() => hexToHSL('#GGGGGG')).toThrow('hexToRGB returned undefined');
});
});

describe('isValidHexColor', () => {
it('should validate 6-digit hex colors with hash', () => {
expect(isValidHexColor('#000000')).toBe(true);
expect(isValidHexColor('#FFFFFF')).toBe(true);
expect(isValidHexColor('#BF5700')).toBe(true);
expect(isValidHexColor('#D6D2C4')).toBe(true);
});

it('should validate 6-digit hex colors without hash', () => {
expect(isValidHexColor('000000')).toBe(true);
expect(isValidHexColor('FFFFFF')).toBe(true);
expect(isValidHexColor('BF5700')).toBe(true);
});

it('should validate 3-digit hex colors with hash', () => {
expect(isValidHexColor('#000')).toBe(true);
expect(isValidHexColor('#FFF')).toBe(true);
expect(isValidHexColor('#F0F')).toBe(true);
});

it('should validate 3-digit hex colors without hash', () => {
expect(isValidHexColor('000')).toBe(true);
expect(isValidHexColor('FFF')).toBe(true);
expect(isValidHexColor('F0F')).toBe(true);
});

it('should reject invalid hex colors', () => {
expect(isValidHexColor('#')).toBe(false);
expect(isValidHexColor('#GGG')).toBe(false);
expect(isValidHexColor('#GGGGGG')).toBe(false);
expect(isValidHexColor('GGGGGG')).toBe(false);
expect(isValidHexColor('#12345')).toBe(false);
expect(isValidHexColor('#1234567')).toBe(false);
expect(isValidHexColor('not a color')).toBe(false);
expect(isValidHexColor('')).toBe(false);
});
});
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import type { Meta, StoryObj } from '@storybook/react';
import ImportantLinks from '@views/components/calendar/ImportantLinks';
import ResourceLinks from '@views/components/calendar/ResourceLinks';

const meta = {
title: 'Components/Common/ImportantLinks',
component: ImportantLinks,
title: 'Components/Common/ResourceLinks',
component: ResourceLinks,
parameters: {
layout: 'centered',
},
tags: ['autodocs'],
argTypes: {},
} satisfies Meta<typeof ImportantLinks>;
} satisfies Meta<typeof ResourceLinks>;
export default meta;

type Story = StoryObj<typeof meta>;
Expand Down
Loading

0 comments on commit 65a682b

Please sign in to comment.