Skip to content
Merged
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
2 changes: 1 addition & 1 deletion .github/workflows/format.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ jobs:
- name: Set up Node.js
uses: actions/setup-node@v3
with:
node-version: 22
node-version: 24

- name: Install dependencies
run: npm install
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/generationTest.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ jobs:
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: 22
node-version: 24

- name: Install dependencies
run: npm ci
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ jobs:
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: 22
node-version: 24
cache: npm

- name: Install dependencies
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/ui-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ jobs:
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: 22
node-version: 24

- name: Install dependencies
run: npm ci
Expand Down
1 change: 1 addition & 0 deletions .nvmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
24
3 changes: 3 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
"private": true,
"version": "0.0.0",
"type": "module",
"engines": {
"node": "24.x"
},
"scripts": {
"dev": "cross-env VITE_API_BASE_URL=https://brocktimetable.connorbernard.com/api vite",
"dev:local": "cross-env VITE_API_BASE_URL=http://localhost:3001/api vite",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { describe, expect, it } from "vitest";
import { getVisibleCandidates } from "../calendarViewUtils";

const timetable = (id) => ({
courses: [
{
courseCode: "COSC1P02",
mainComponents: [
{ id, schedule: { duration: "2", startDate: 100, endDate: 200 } },
],
secondaryComponents: {},
},
],
});

describe("getVisibleCandidates", () => {
it("keeps one representative for visually identical timetable candidates", () => {
const first = { id: "first", timetable: timetable("100-1") };
const duplicate = { id: "duplicate", timetable: timetable("100-2") };
const distinct = { id: "distinct", timetable: timetable("101-1") };

expect(
getVisibleCandidates([first, duplicate, distinct], {
start: new Date(100_000),
end: new Date(201_000),
}),
).toEqual([first, distinct]);
});
});
25 changes: 17 additions & 8 deletions src/components/generator/Calendar/utils/calendarViewUtils.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,29 +96,38 @@ export const getVisibleTimetableSignature = (timetable, viewRange) => {
return courseSignatures.join("||");
};

export const getVisibleTimetables = (timetables, viewRange) => {
if (!Array.isArray(timetables)) return [];
if (!viewRange) return timetables;
export const getVisibleCandidates = (candidates, viewRange) => {
if (!Array.isArray(candidates)) return [];
if (!viewRange) return candidates;

const uniqueSignatures = new Set();
const filteredTimetables = [];
const visibleCandidates = [];

timetables.forEach((timetable) => {
candidates.forEach((candidate) => {
const timetable = candidate.timetable || candidate;
const signature = getVisibleTimetableSignature(timetable, viewRange);
if (signature == null) {
filteredTimetables.push(timetable);
visibleCandidates.push(candidate);
return;
}

if (!uniqueSignatures.has(signature)) {
uniqueSignatures.add(signature);
filteredTimetables.push(timetable);
visibleCandidates.push(candidate);
}
});

return filteredTimetables;
return visibleCandidates;
};

export const getVisibleTimetables = (timetables, viewRange) =>
Array.isArray(timetables)
? getVisibleCandidates(
timetables.map((timetable) => ({ timetable })),
viewRange,
).map(({ timetable }) => timetable)
: [];

// Get calendar view notification message
export const getCalendarViewNotificationMessage = (startDate) => {
return (
Expand Down
11 changes: 7 additions & 4 deletions src/lib/contexts/generator/CourseColorsContext.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,10 @@ export const CourseColorsProvider = ({ children }) => {
if (prev[courseCode]) {
return prev;
}
const currentUsedColors = usedColorsRef.current;
// Several courses can be added in one React commit (for example through
// WebMCP). Derive the palette from `prev`, not the asynchronously updated
// ref, so each queued initializer sees colors assigned by the earlier one.
const currentUsedColors = Object.values(prev);
const availableColors = defaultColors.filter(
(color) => !currentUsedColors.includes(color),
);
Expand All @@ -106,12 +109,12 @@ export const CourseColorsProvider = ({ children }) => {
} else {
newColor = availableColors[0];
}
// Update usedColors
setUsedColors((current) => [...current, newColor]);
return {
const nextColors = {
...prev,
[courseCode]: newColor,
};
setUsedColors(Object.values(nextColors));
return nextColors;
});
}, []);

Expand Down
37 changes: 37 additions & 0 deletions src/lib/contexts/generator/__tests__/CourseColorsContext.test.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// @vitest-environment jsdom
import { useContext, useEffect } from "react";
import { render, screen } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import {
CourseColorsContext,
CourseColorsProvider,
} from "../CourseColorsContext";
import { defaultColors } from "../courseColorPalette";

function BatchInitializer() {
const { courseColors, initializeCourseColor } =
useContext(CourseColorsContext);

useEffect(() => {
initializeCourseColor("COSC1P02");
initializeCourseColor("MATH1P01");
}, [initializeCourseColor]);

return <output>{JSON.stringify(courseColors)}</output>;
}

describe("CourseColorsContext", () => {
it("assigns distinct palette colours to courses initialized in one commit", async () => {
render(
<CourseColorsProvider>
<BatchInitializer />
</CourseColorsProvider>,
);

await screen.findByText((content) => content.includes("MATH1P01"));
expect(JSON.parse(screen.getByRole("status").textContent)).toEqual({
COSC1P02: defaultColors[0],
MATH1P01: defaultColors[1],
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { beforeEach, describe, expect, it } from "vitest";
import {
clearAllCourseData,
storeCourseData,
} from "@/lib/generator/courseData";
import { clearAllPins } from "@/lib/generator/pinnedComponents";
import { reinitializeTimeSlots } from "@/lib/generator/timeSlots";
import {
generateTimetables,
getValidTimetables,
previewTimetables,
} from "../timetableGeneration";
import coscData from "./__mocks__/COSC1P02.json";
import biolData from "./__mocks__/BIOL2P02.json";

describe("previewTimetables", () => {
beforeEach(() => {
clearAllCourseData();
clearAllPins();
reinitializeTimeSlots();
storeCourseData(coscData);
});

it("returns a what-if result without replacing the current timetable results", () => {
generateTimetables("default");
const currentResults = getValidTimetables();

expect(previewTimetables([biolData])).not.toHaveLength(0);
expect(getValidTimetables()).toBe(currentResults);
});
});
26 changes: 26 additions & 0 deletions src/lib/generator/timetableGeneration/timetableGeneration.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { buildConflictFallback } from "./utils/conflictUtils";
import { calculateWaitingTime, calculateClassDays } from "./utils/sortUtils";
import { getCourseData } from "../courseData";
import { getTimeSlots } from "../timeSlots";
import { getPinnedComponents } from "../pinnedComponents";

let validTimetables = [];
let previousSortOption = "default";
Expand Down Expand Up @@ -123,6 +124,31 @@ export const generateTimetables = (sortOption) => {

export const getValidTimetables = () => validTimetables;

// Generates a read-only what-if result for WebMCP. Unlike generateTimetables,
// it neither changes the visible result list nor emits UI events.
export const previewTimetables = (additionalCourses, additionalPins = []) => {
const courses = [...Object.values(getCourseData()), ...additionalCourses];
const performance = { totalCombinationsProcessed: 0 };
const options = {
pinnedComponents: [...getPinnedComponents(), ...additionalPins],
emitOverride: false,
markPinned: false,
};
const combinations = courses.map((course) =>
generateSingleCourseCombinations(course, getTimeSlots(), options),
);
if (
combinations.some((courseCombinations) => courseCombinations.length === 0)
)
return [];

return generateTimetableCombinations(combinations, performance, {
onTruncate: () => {},
})
.filter(isTimetableValid)
.map((courses) => ({ courses }));
};

export const getGenerationPerformance = () => {
const {
generationStartTime,
Expand Down
33 changes: 27 additions & 6 deletions src/lib/generator/timetableGeneration/utils/combinationUtils.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,15 @@ export const cartesianProduct = (arrays) => {
return result;
};

export const generateSingleCourseCombinations = (course, timeSlots) => {
const pinnedComponents = getPinnedComponents();

export const generateSingleCourseCombinations = (
course,
timeSlots,
{
pinnedComponents = getPinnedComponents(),
emitOverride = true,
markPinned = true,
} = {},
) => {
const durationFilter = pinnedComponents.find((p) => {
const [pinnedCourse, type] = p.split(" ");
return pinnedCourse === course.courseCode && type === "DURATION";
Expand All @@ -57,9 +63,16 @@ export const generateSingleCourseCombinations = (course, timeSlots) => {
const { availableGroups: mainAvailable } = filterComponentsAgainstTimeSlots(
validMainComponents,
timeSlots,
{ emitOverride },
);

validMainComponents = filterPinned(mainAvailable, course.courseCode, "MAIN");
validMainComponents = filterPinned(
mainAvailable,
course.courseCode,
"MAIN",
pinnedComponents,
markPinned,
);

if (validMainComponents.length === 0) {
return [];
Expand All @@ -78,9 +91,16 @@ export const generateSingleCourseCombinations = (course, timeSlots) => {
const { availableGroups } = filterComponentsAgainstTimeSlots(
items,
timeSlots,
{ emitOverride },
);

const filtered = filterPinned(availableGroups, course.courseCode, type);
const filtered = filterPinned(
availableGroups,
course.courseCode,
type,
pinnedComponents,
markPinned,
);
return filtered;
};

Expand Down Expand Up @@ -189,6 +209,7 @@ export const generateSingleCourseCombinations = (course, timeSlots) => {
export const generateTimetableCombinations = (
courseCombinations,
performanceMetrics,
{ onTruncate = emitTruncationWarning } = {},
) => {
let results = [];
let count = 0;
Expand All @@ -199,7 +220,7 @@ export const generateTimetableCombinations = (
count++;
performanceMetrics.totalCombinationsProcessed++;
if (count >= maxComboThreshold) {
emitTruncationWarning();
onTruncate();
return false;
}
return true;
Expand Down
21 changes: 15 additions & 6 deletions src/lib/generator/timetableGeneration/utils/filterUtils.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,11 @@ import {
import { getPinnedComponents } from "@/lib/generator/pinnedComponents";
import { emitTimetableOverridden } from "./UIEventsUtils";

export const filterComponentsAgainstTimeSlots = (components, timeSlots) => {
export const filterComponentsAgainstTimeSlots = (
components,
timeSlots,
{ emitOverride = true } = {},
) => {
const timeRegex = /[a-zA-Z]/;
const groupedComponents = new Map();
const blockedComponents = [];
Expand Down Expand Up @@ -53,7 +57,7 @@ export const filterComponentsAgainstTimeSlots = (components, timeSlots) => {
}

if (availableGroups.length === 0 && blockedComponents.length > 0) {
emitTimetableOverridden();
if (emitOverride) emitTimetableOverridden();
blockedComponents.sort((a, b) => a.blockedPercentage - b.blockedPercentage);
availableGroups.push(blockedComponents[0].group);
return {
Expand All @@ -70,9 +74,14 @@ export const filterComponentsAgainstTimeSlots = (components, timeSlots) => {
};
};

export const filterPinned = (components, courseCode, componentType) => {
components.forEach((component) => (component.pinned = false));
const pinnedComponents = getPinnedComponents();
export const filterPinned = (
components,
courseCode,
componentType,
pinnedComponents = getPinnedComponents(),
markPinned = true,
) => {
if (markPinned) components.forEach((component) => (component.pinned = false));

const coursePinnedComponents = pinnedComponents.filter((p) => {
const [course, type] = p.split(" ");
Expand All @@ -86,7 +95,7 @@ export const filterPinned = (components, courseCode, componentType) => {
const [, , id] = pinned.split(" ");
const baseComponentId = getBaseComponentId(component.id);
if (baseComponentId === id) {
component.pinned = true;
if (markPinned) component.pinned = true;
return true;
}
return false;
Expand Down
Loading
Loading