From bc8966c34bcb0abe9f39b565d1a29e0496080af0 Mon Sep 17 00:00:00 2001 From: Siddharth Gupta Date: Mon, 23 Nov 2026 20:55:26 -0500 Subject: [PATCH 1/4] (feat) side-by-side compare view for two plans (TIG-337) Students pick a second plan and see both semester boards side by side, each with its own requirement progress. The active plan stays editable on the left; the compared plan is read-only on the right. - Backend: get_schedule / get_requirements take an optional ?planId= (GET only, scoped to the user's plans, 404 otherwise). Reads never change the active plan or write anything. - usePlanner: comparePlanId with read-only compare schedule and requirements; stale responses dropped; closes if the plan is deleted; selecting the compared plan's tab swaps the sides. - Board gains a readOnly mode without drag-and-drop or remove buttons. - Compact per-major/minor summaries per side; below 1100px one board at a time with a toggle. - Tests: 5 backend (own majors per plan, no writes, 404s, save ignores planId) and compare helper unit tests. Decision log: docs/decisions/TIG-337-compare-view.md Co-Authored-By: Claude Opus 5.5 --- docs/decisions/TIG-337-compare-view.md | 83 ++++++ frontend/src/new/App.jsx | 135 +++++++-- frontend/src/new/api.js | 10 +- frontend/src/new/components/Board.jsx | 64 ++++- frontend/src/new/components/ComparePicker.jsx | 51 ++++ .../src/new/components/CompareSummary.jsx | 46 ++++ frontend/src/new/components/Icon.jsx | 1 + frontend/src/new/helpers/compare.js | 41 +++ frontend/src/new/helpers/compare.test.js | 40 +++ frontend/src/new/styles.css | 258 ++++++++++++++++++ frontend/src/new/usePlanner.js | 61 ++++- tigerpath/tests.py | 86 ++++++ tigerpath/views.py | 31 ++- 13 files changed, 870 insertions(+), 37 deletions(-) create mode 100644 docs/decisions/TIG-337-compare-view.md create mode 100644 frontend/src/new/components/ComparePicker.jsx create mode 100644 frontend/src/new/components/CompareSummary.jsx create mode 100644 frontend/src/new/helpers/compare.js create mode 100644 frontend/src/new/helpers/compare.test.js diff --git a/docs/decisions/TIG-337-compare-view.md b/docs/decisions/TIG-337-compare-view.md new file mode 100644 index 00000000..442e4839 --- /dev/null +++ b/docs/decisions/TIG-337-compare-view.md @@ -0,0 +1,83 @@ +# TIG-337: side-by-side compare view (decision log) + +Branch: `tig-337-tigerpath-side-by-side-parallel-view-for-comparing`. It's stacked on TIG-330 +(`tig-330-tigerpath-implement-lucys-color-gradient-ui-on-the`), as the issue asks ("start it after TIG-330"), +so the compare boards use the gradient tokens. + +## What ships + +- **Backend:** `GET /api/v1/get_schedule/?planId=` and `GET /api/v1/get_requirements/?planId=` read any of + the user's own plans. Without `planId` they behave exactly as before (active plan). A plan id that is + missing, malformed or belongs to someone else returns 404. Neither read changes the active plan or writes anything. +- **`usePlanner`:** `comparePlanId` plus `compareSchedule`/`compareRequirements`, loaded through those + GETs only. Stale responses are dropped when the user switches quickly. +- **UI:** a **Compare** button next to the plan tabs opens a "Compare with" picker. The active plan is + editable on the left; the compared plan is read-only on the right. Each side shows a compact + requirement summary for every major and minor on that plan. Below 1100px it's one board at a time, + with a toggle between the two plans. + +## Checks from the issue + +| Check | How it's covered | +|---|---| +| Plans with different `additional_major_ids` each show their own requirements | `ComparePlanApiTest.test_each_plan_reports_its_own_majors`. Preview: plan b has two majors (SPI and POL). | +| Opening or closing compare never changes the active plan or writes a schedule | `test_compare_reads_never_change_active_plan_or_write` (plans' `schedule` and `updated_at` unchanged). Preview: zero non-GET requests across open, switch and close. | +| Selecting the same plan twice is blocked | The picker never lists the active plan (`compareOptions`, unit-tested); `setComparePlanId` refuses it as well. | +| Screenshots at 1440px and 1100px | In the PR. | + +## Decisions + +### D1. A read-only `planId` on the existing GETs, not a new endpoint + +**Blocker:** both endpoints only ever returned the active plan (`get_active_plan`). +**Decision:** add an optional `planId` to the two existing GET views, scoped to `profile.schedule_plans`. +It's honored on GET only, so `update_schedule_and_get_requirements` (POST, which reuses +`get_requirements`) always answers for the active plan it just saved. Tested. +*Other option:* a separate `get_plan_snapshot` endpoint. That's more surface area for the same data. + +### D2. The Figma has no finished side-by-side design + +The file's only compare artifact is Angelina's low-fidelity grey "STEP 2: COMPARE" wireframe: two +halves, each with a majors/minors box. **Decision:** follow the issue's behavior spec and the existing new-planner +visual language (gradient tokens, plan-tab styling). Lucy should review the layout (see the PR). + +### D3. Compare layout: two boards plus compact summaries; search and the full requirements panel are hidden + +At 1440px a search column, two boards and two full `RequirementsPanel`s don't fit. Each board would be about 360px, +which truncates every course code. **Decision:** while comparing, the two boards take the full width (about 680px +each, close to the normal board), and each side gets a compact per-major/minor summary (the issue's +"compact per-major summary" fallback). Search, settling and external credits need the full panel, +so close compare to use them. Moving and removing courses on the left still works. +*Other option:* keep `RequirementsPanel` per side and drop the search column only. That's still too narrow at 1440px. + +### D4. The read-only board renders without drag-and-drop + +Both boards sit inside one `DragDropContext`. Reusing `Droppable`/`Draggable` on the right would duplicate the +`sem0`…`sem7` droppable ids. `Board readOnly` renders static markup instead: no remove button, no +grab cursor, no hover gradient, and no `#semesters` id (the tutorial targets the left board's). + +### D5. Clicking the compared plan's tab swaps the sides + +Making the compared plan active would otherwise put the same plan on both sides. **Decision:** the +previously active plan moves to the compare side. This is the only compare-related flow that writes, +because the user explicitly chose a new active plan (`set_active_plan`). It's the same request as clicking any tab. + +### D6. Compare state isn't persisted + +Compare closes on reload. Persisting it would mean a write (`user_state`) when opening compare, and +the issue says opening and closing compare must not write. + +### D7. Summary text stays at WCAG AA + +The summary's "x/y complete" count and the "not supported yet" label use the text color, because the existing +muted grey (4.31:1) and incomplete red (4.06:1) fall just under 4.5:1 on the tinted requirement card. Colored +dots carry each requirement's done/incomplete status. +*Not changed:* the existing full requirements panel still shows its red count on white (4.27:1). Flagged for follow-up. + +### D8. The tutorial closes compare first + +The tour highlights the search pane and requirements panel, which compare mode hides. + +### D9. Print shows the active plan only + +The compare side and the summaries are `dont-print`. The printout stays "My Four Year Schedule: ". diff --git a/frontend/src/new/App.jsx b/frontend/src/new/App.jsx index 54015e3a..9f26fc1e 100644 --- a/frontend/src/new/App.jsx +++ b/frontend/src/new/App.jsx @@ -12,13 +12,16 @@ import Board from './components/Board'; import RequirementsPanel from './components/RequirementsPanel'; import CourseDrawer from './components/CourseDrawer'; import SettingsModal from './components/SettingsModal'; +import ComparePicker from './components/ComparePicker'; +import CompareSummary from './components/CompareSummary'; import './styles.css'; const semesterIndexOf = (droppableId) => parseInt(droppableId.replace('sem', ''), 10); export default function App() { const planner = usePlanner(); - const { profile, plans, activePlan, schedule, requirements } = planner; + const { profile, plans, activePlan, schedule, requirements, comparePlan } = planner; + const comparing = Boolean(comparePlan); const [searchQuery, setSearchQuery] = useState(''); const [searchResults, setSearchResults] = useState([]); @@ -28,6 +31,8 @@ export default function App() { const [pathModal, setPathModal] = useState(null); // {mode: 'create'|'edit', plan} const [settingsOpen, setSettingsOpen] = useState(false); const [creditPath, setCreditPath] = useState(null); + // Below 1100px compare mode shows one board at a time; this picks which. + const [compareView, setCompareView] = useState('active'); const themeName = profile?.theme || 'purple'; useEffect(() => { @@ -97,12 +102,52 @@ export default function App() { const switchToClassic = () => setUiVersion('classic').then(() => window.location.reload()); + const centerTop = ( +
+ setPathModal({ mode: 'edit', plan })} + onCreate={() => setPathModal({ mode: 'create' })} + /> + { + setCompareView('active'); + planner.setComparePlanId(id); + }} + /> + + {planner.saving ? 'Saving…' : ''} + +
+ ); + + const activeBoard = schedule ? ( + + ) : ( +

Loading your plan...

+ ); + return (
setSettingsOpen(true)} onSwitchToClassic={switchToClassic} - onStartTutorial={startTutorial} + onStartTutorial={() => { + // The tour points at the search pane and requirements panel, which compare mode hides. + if (!comparing) return startTutorial(); + planner.setComparePlanId(null); + return requestAnimationFrame(() => requestAnimationFrame(startTutorial)); + }} />
@@ -114,6 +159,67 @@ export default function App() {
+ {comparing ? ( +
+
+ {centerTop} + {planner.notice && ( +
+ {planner.notice.text} +
+ )} +
+ + +
+
+
+
+

{activePlan?.name || 'Active plan'}

+ Editing +
+
+ +
+ {activeBoard} +
+
+
+

{comparePlan.name}

+ Read-only +
+ + {planner.compareSchedule ? ( + + ) : ( +

Loading {comparePlan.name}...

+ )} +
+
+
+
+ ) : (
-
- setPathModal({ mode: 'edit', plan })} - onCreate={() => setPathModal({ mode: 'create' })} - /> - - {planner.saving ? 'Saving…' : ''} - -
+ {centerTop} {planner.notice && (
{planner.notice.text}
)} - {schedule ? ( - - ) : ( -

Loading your plan...

- )} + {activeBoard}
activePlan && setPathModal({ mode: 'edit', plan: activePlan })} />
+ )}
minorCodes: JSON.stringify(minorCodes || []), }); -export const getSchedule = () => apiFetch('/api/v1/get_schedule/'); +// Without a planId these read the active plan. With one (compare mode) they read that plan +// read-only; the server never changes the active plan for these GETs. +export const getSchedule = (planId) => + apiFetch(planId == null ? '/api/v1/get_schedule/' : `/api/v1/get_schedule/?planId=${encodeURIComponent(planId)}`); // "grouped" returns {majors, degrees, minors} covering every major on the plan. -export const getRequirements = () => apiFetch('/api/v1/get_requirements/?layout=grouped'); +export const getRequirements = (planId) => + apiFetch( + `/api/v1/get_requirements/?layout=grouped${planId == null ? '' : `&planId=${encodeURIComponent(planId)}`}` + ); export const saveScheduleAndGetRequirements = (strippedSchedule) => apiPost('/api/v1/update_schedule_and_get_requirements/?layout=grouped', { schedule: JSON.stringify(strippedSchedule), diff --git a/frontend/src/new/components/Board.jsx b/frontend/src/new/components/Board.jsx index 8e76e834..e43506bb 100644 --- a/frontend/src/new/components/Board.jsx +++ b/frontend/src/new/components/Board.jsx @@ -40,6 +40,26 @@ function CourseHoverCard({ course, semesterIndex, duplicate }) { ); } +/** Compare mode's right-hand board: same look, no drag-and-drop and no remove button. */ +function ReadOnlyCourseChip({ course, semesterIndex, duplicate }) { + const [hover, setHover] = useState(false); + return ( +
setHover(true)} + onMouseLeave={() => setHover(false)} + onFocus={() => setHover(true)} + onBlur={() => setHover(false)} + aria-label={`${course.name}${course.title ? `: ${course.title}` : ''}`} + > + {course.name} + {course.title} + {hover && } +
+ ); +} + function CourseChip({ course, semesterIndex, index, duplicate, onRemove }) { const [hover, setHover] = useState(false); return ( @@ -80,6 +100,25 @@ function CourseChip({ course, semesterIndex, index, duplicate, onRemove }) { ); } +function ReadOnlySemester({ index, season, courses, duplicateNames }) { + return ( +
+ {season} +
+ {courses.map((course, i) => ( + + ))} + {courses.length === 0 &&

No courses

} +
+
+ ); +} + function Semester({ index, season, courses, draggingSeason, duplicateNames, onRemove }) { return ( @@ -120,14 +159,22 @@ function Semester({ index, season, courses, draggingSeason, duplicateNames, onRe ); } -export default function Board({ schedule, classYear, draggingSeason, onRemove }) { +/** + * The four-year grid. `readOnly` renders the compare-mode board: no drag-and-drop (so its ids never + * collide with the editable board's droppables) and no #semesters id, which the tutorial targets. + */ +export default function Board({ schedule, classYear, draggingSeason, onRemove, readOnly = false, label }) { const counts = new Map(); (schedule || []).slice(0, 8).flat().forEach((c) => counts.set(c.name, (counts.get(c.name) || 0) + 1)); const duplicateNames = new Set([...counts].filter(([, n]) => n > 1).map(([name]) => name)); return ( -
- {!classYear && ( +
+ {!classYear && !readOnly && (

Set your class year in Settings to label semesters correctly.

)}
@@ -137,6 +184,17 @@ export default function Board({ schedule, classYear, draggingSeason, onRemove })
{SEASONS.map((season, s) => { const index = y * 2 + s; + if (readOnly) { + return ( + + ); + } return ( onChange(options[0].id)} + > + Compare + + ); + } + + return ( +
+ + +
+ ); +} diff --git a/frontend/src/new/components/CompareSummary.jsx b/frontend/src/new/components/CompareSummary.jsx new file mode 100644 index 00000000..9645f44d --- /dev/null +++ b/frontend/src/new/components/CompareSummary.jsx @@ -0,0 +1,46 @@ +import React from 'react'; +import { planSummaries } from '../helpers/compare'; + +/** + * Compact per-program progress for one side of compare mode. Two full RequirementsPanels do not fit + * beside two boards, so each side gets one row per major/minor with its top-level requirements. + */ +export default function CompareSummary({ requirements }) { + if (!requirements) return

Loading requirements...

; + const summaries = planSummaries(requirements); + if (summaries.length === 0) { + return

No major or minors on this plan yet.

; + } + return ( +
    + {summaries.map((s, i) => ( +
  • +
    + {s.label} + {s.unsupported ? ( + not supported yet + ) : ( + + {s.done}/{s.total} complete + + )} +
    + {!s.unsupported && s.items.length > 0 && ( +
      + {s.items.map((item, j) => ( +
    • + {item.name} + {item.min > 0 && ( + + {item.count}/{item.min} + + )} +
    • + ))} +
    + )} +
  • + ))} +
+ ); +} diff --git a/frontend/src/new/components/Icon.jsx b/frontend/src/new/components/Icon.jsx index 9d95bb8b..a25c9731 100644 --- a/frontend/src/new/components/Icon.jsx +++ b/frontend/src/new/components/Icon.jsx @@ -43,6 +43,7 @@ const PATHS = { plusCircle: ['M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20z', 'M8 12h8', 'M12 8v8'], history: ['M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8', 'M3 3v5h5', 'M12 7v5l4 2'], loader: ['M21 12a9 9 0 1 1-6.22-8.56'], + columns: ['M5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z', 'M12 3v18'], }; export default function Icon({ name, size = 18, strokeWidth = 2, className = '', title }) { diff --git a/frontend/src/new/helpers/compare.js b/frontend/src/new/helpers/compare.js new file mode 100644 index 00000000..51f39937 --- /dev/null +++ b/frontend/src/new/helpers/compare.js @@ -0,0 +1,41 @@ +import { majorLabel, minorLabel, requirementStatus } from './requirements'; + +/** Plans the user can compare against the active one: every other plan, never the active plan itself. */ +export function compareOptions(plans, activePlanId) { + return (plans || []).filter((plan) => plan.id !== activePlanId); +} + +/** + * Compact progress for one program tree (compare mode shows two of these side by side instead of + * two full RequirementsPanels). Unsupported majors arrive from the API as plain strings. + */ +export function programSummary(program, kind) { + const label = kind === 'minor' ? minorLabel(program) : majorLabel(program); + if (!program || typeof program !== 'object') { + return { label, name: String(program || label), unsupported: true, done: 0, total: 0, items: [] }; + } + const items = (program.req_list || []).map((req) => ({ + name: req.name, + count: req.count, + min: req.min_needed, + status: requirementStatus(req), + })); + const counted = items.filter((item) => item.status !== 'neutral'); + return { + label, + name: program.name || label, + unsupported: false, + done: counted.filter((item) => item.status === 'done').length, + total: counted.length, + items, + }; +} + +/** Every major then minor on a plan, as summaries. */ +export function planSummaries(requirements) { + if (!requirements) return []; + return [ + ...(requirements.majors || []).map((m) => programSummary(m, 'major')), + ...(requirements.minors || []).map((m) => programSummary(m, 'minor')), + ]; +} diff --git a/frontend/src/new/helpers/compare.test.js b/frontend/src/new/helpers/compare.test.js new file mode 100644 index 00000000..3ae91500 --- /dev/null +++ b/frontend/src/new/helpers/compare.test.js @@ -0,0 +1,40 @@ +import { describe, expect, it } from 'vitest'; +import { compareOptions, planSummaries, programSummary } from './compare'; + +const leaf = (name, count, min) => ({ name, count, min_needed: min, settled: [] }); + +describe('compareOptions', () => { + it('never offers the active plan, so the same plan cannot be on both sides', () => { + const plans = [{ id: 1 }, { id: 2 }, { id: 3 }]; + expect(compareOptions(plans, 2).map((p) => p.id)).toEqual([1, 3]); + expect(compareOptions([{ id: 1 }], 1)).toEqual([]); + }); +}); + +describe('programSummary', () => { + it('counts finished top-level requirements and skips neutral ones', () => { + const eco = { + name: 'Economics', + code: 'ECO', + req_list: [leaf('Prerequisites', 3, 3), leaf('Core', 2, 3), leaf('Notes', 0, 0)], + }; + const summary = programSummary(eco, 'major'); + expect(summary).toMatchObject({ label: 'ECO', name: 'Economics', done: 1, total: 2, unsupported: false }); + expect(summary.items.map((i) => i.status)).toEqual(['done', 'incomplete', 'neutral']); + }); + + it('marks unsupported majors (plain strings from the API)', () => { + expect(programSummary('Astrophysics', 'major')).toMatchObject({ unsupported: true, name: 'Astrophysics' }); + }); +}); + +describe('planSummaries', () => { + it('lists each plan’s own majors then minors', () => { + const reqs = { + majors: [{ name: 'Computer Science', code: 'COS', req_list: [] }, 'Politics'], + minors: [{ name: 'Finance', code: 'FIN', req_list: [leaf('Core', 1, 1)] }], + }; + expect(planSummaries(reqs).map((s) => s.label)).toEqual(['COS', 'Politics', 'FIN']); + expect(planSummaries(null)).toEqual([]); + }); +}); diff --git a/frontend/src/new/styles.css b/frontend/src/new/styles.css index bb23c605..fe2bf837 100644 --- a/frontend/src/new/styles.css +++ b/frontend/src/new/styles.css @@ -1282,6 +1282,218 @@ button:disabled { line-height: 1.5; } +/* ── Compare mode (TIG-337) ────────────────────────────────────────────── */ + +.tp-compare-btn { + display: inline-flex; + align-items: center; + gap: 6px; + height: 38px; + padding: 0 14px; + border: 1.5px solid var(--tp-border); + border-radius: 19px; + background: #fff; + font-size: 14px; + font-weight: 700; + flex-shrink: 0; +} + +.tp-compare-btn:hover:not(:disabled) { + border-color: var(--tp-active-plan-border); +} + +.tp-compare-picker { + display: flex; + align-items: center; + gap: 4px; + flex-shrink: 0; +} + +.tp-compare-picker label { + display: flex; + align-items: center; + gap: 8px; + font-size: 14px; + font-weight: 700; + white-space: nowrap; +} + +.tp-compare-picker .tp-select { + width: auto; + min-width: 140px; + max-width: 220px; +} + +.tp-main.comparing { + grid-template-columns: minmax(0, 1fr); +} + +.tp-compare { + display: flex; + flex-direction: column; + min-width: 0; + min-height: 0; +} + +.tp-compare-toggle { + display: none; +} + +.tp-compare-sides { + flex: 1; + min-height: 0; + display: grid; + grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); + /* Header, summary, board: shared rows keep both boards top-aligned whatever each summary holds. */ + grid-template-rows: auto auto minmax(0, 1fr); + column-gap: 22px; +} + +.tp-compare-side { + display: grid; + grid-row: span 3; + grid-template-rows: subgrid; + min-width: 0; + min-height: 0; +} + +.tp-compare-head { + display: flex; + align-items: center; + gap: 10px; + margin-bottom: 8px; +} + +.tp-compare-head h2 { + margin: 0; + font-size: 20px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.tp-compare-tag { + flex-shrink: 0; + padding: 2px 10px; + border-radius: 999px; + background: var(--tp-plan-tabs-fill); + color: var(--tp-text); + font-size: 12px; + font-weight: 700; +} + +.tp-compare-tag.editable { + background: var(--tp-plan-tab-active-fill); +} + +.tp-compare-summary { + list-style: none; + margin: 0 0 12px; + padding: 0; + display: flex; + flex-wrap: wrap; + gap: 8px; + max-height: 150px; + overflow-y: auto; +} + +.tp-compare-program { + flex: 1 1 200px; + min-width: 0; + padding: 8px 10px; + border-radius: 10px; + background: var(--tp-req-panel-fill); + box-shadow: 0 0 6px rgba(0, 0, 0, 0.12); +} + +.tp-compare-program-head { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 8px; + font-size: 15px; +} + +.tp-compare-program-head .tp-req-count { + font-size: 13px; +} + +/* Text color, not muted grey or --tp-incomplete red: both fall just under 4.5:1 on the tinted card. + The status dots carry the done/incomplete signal. */ +.tp-compare-program-head .tp-req-count.incomplete .current, +.tp-compare-unsupported { + color: var(--tp-text); +} + +.tp-compare-unsupported { + font-size: 13px; + font-style: italic; +} + +.tp-compare-reqs { + list-style: none; + margin: 4px 0 0; + padding: 0; + font-size: 13px; +} + +.tp-compare-req { + display: flex; + align-items: center; + gap: 6px; + min-height: 20px; +} + +.tp-compare-req::before { + content: ''; + width: 7px; + height: 7px; + border-radius: 50%; + flex-shrink: 0; + background: var(--tp-border); +} + +.tp-compare-req.done::before { + background: var(--tp-req-chip-text); +} + +.tp-compare-req.incomplete::before { + background: var(--tp-incomplete); +} + +.tp-compare-req-name { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.tp-compare-req-count { + font-variant-numeric: tabular-nums; + font-weight: 700; +} + +.tp-compare-side .tp-board { + min-height: 0; +} + +.tp-compare-side .tp-year-title { + padding: 10px 0 8px; + font-size: clamp(18px, 1.6vw, 24px); +} + +/* The compared plan is read-only: no grab cursor and no hover gradient that suggests dragging. */ +.tp-course.readonly { + cursor: default; +} + +.tp-course.readonly:hover, +.tp-course.readonly:focus-visible { + background: linear-gradient(to bottom, var(--tp-course-card-fill-start), var(--tp-course-card-fill-end)); + box-shadow: none; +} + /* ── Responsive ────────────────────────────────────────────────────────── */ @media (max-width: 1100px) { @@ -1302,6 +1514,52 @@ button:disabled { .tp-center { min-height: 720px; } + + /* Compare mode falls back to one board at a time with a toggle between the two plans. */ + .tp-compare-toggle { + display: flex; + align-self: flex-start; + gap: 4px; + margin-bottom: 12px; + padding: 4px; + border-radius: 19px; + background: var(--tp-plan-tabs-fill); + } + + .tp-compare-toggle button { + height: 30px; + padding: 0 14px; + border: 1.5px solid transparent; + border-radius: 15px; + background: none; + font-size: 14px; + font-weight: 500; + } + + .tp-compare-toggle button.active { + background: var(--tp-plan-tab-active-fill); + border-color: var(--tp-active-plan-border); + font-weight: 700; + } + + .tp-compare-sides { + grid-template-columns: minmax(0, 1fr); + } + + .tp-compare[data-show='active'] .compare-side, + .tp-compare[data-show='compare'] .active-side { + display: none; + } + + .tp-compare-sides { + grid-template-rows: none; + } + + .tp-compare-side { + display: flex; + flex-direction: column; + min-height: 720px; + } } @media (max-width: 760px) { diff --git a/frontend/src/new/usePlanner.js b/frontend/src/new/usePlanner.js index 10edeebc..aa87576e 100644 --- a/frontend/src/new/usePlanner.js +++ b/frontend/src/new/usePlanner.js @@ -25,6 +25,11 @@ export default function usePlanner() { const [editorOptions, setEditorOptions] = useState({ majorOptions: [], minorOptions: [], maxMajors: 3 }); const [notice, setNotice] = useState(null); const [saving, setSaving] = useState(false); + // Compare mode (TIG-337): a second plan shown read-only next to the active one. + const [comparePlanId, setComparePlanIdState] = useState(null); + const [compareSchedule, setCompareSchedule] = useState(null); + const [compareRequirements, setCompareRequirements] = useState(null); + const compareSeq = useRef(0); // Responses for older saves are ignored so fast edits can't apply stale requirements. const saveSeq = useRef(0); @@ -171,6 +176,45 @@ export default function usePlanner() { [schedule, commitSchedule] ); + // ── Compare mode ───────────────────────────────────────────────────────── + // Read-only GETs by planId: opening, switching or closing compare never calls setActivePlan + // and never saves a schedule. + + const loadCompare = useCallback((planId) => { + const seq = ++compareSeq.current; + setCompareSchedule(null); + setCompareRequirements(null); + if (planId == null) return; + api + .getSchedule(planId) + .then((data) => seq === compareSeq.current && setCompareSchedule(data && data.length ? data : emptySchedule())) + .catch(() => seq === compareSeq.current && setCompareSchedule(emptySchedule())); + api + .getRequirements(planId) + .then((data) => seq === compareSeq.current && setCompareRequirements(unwrapGroupedRequirements(data))) + .catch(() => seq === compareSeq.current && setCompareRequirements(unwrapGroupedRequirements(null))); + }, []); + + const setComparePlanId = useCallback( + (planId) => { + const next = planId == null ? null : planId; + // The same plan can't be on both sides. + if (next != null && next === activePlanId) return; + setComparePlanIdState(next); + loadCompare(next); + }, + [activePlanId, loadCompare] + ); + + // Close compare if its plan disappears (deleted) and keep the two sides distinct. + useEffect(() => { + if (comparePlanId == null) return; + if (!plans.some((p) => p.id === comparePlanId)) { + setComparePlanIdState(null); + loadCompare(null); + } + }, [plans, comparePlanId, loadCompare]); + // ── Plans ──────────────────────────────────────────────────────────────── const planAction = useCallback( @@ -185,7 +229,15 @@ export default function usePlanner() { const actions = useMemo( () => ({ - selectPlan: (id) => (id === activePlanId ? Promise.resolve() : planAction(api.setActivePlan(id))), + selectPlan: (id) => { + if (id === activePlanId) return Promise.resolve(); + // Picking the compared plan as active swaps the sides instead of showing one plan twice. + if (id === comparePlanId) { + setComparePlanIdState(activePlanId); + loadCompare(activePlanId); + } + return planAction(api.setActivePlan(id)); + }, createPlan: () => planAction(api.createPlan()), copyPlan: (sourcePlanId, name) => planAction(api.copyPlan({ sourcePlanId, name })), deletePlan: (id) => planAction(api.deletePlan(id)), @@ -198,10 +250,11 @@ export default function usePlanner() { ); }, }), - [activePlanId, planAction] + [activePlanId, comparePlanId, loadCompare, planAction] ); const activePlan = plans.find((p) => p.id === activePlanId) || null; + const comparePlan = plans.find((p) => p.id === comparePlanId) || null; return { profile, @@ -221,6 +274,10 @@ export default function usePlanner() { addExternalCredit, removeExternalCredit, reloadPlan: loadPlanContents, + comparePlan, + compareSchedule, + compareRequirements, + setComparePlanId, ...actions, }; } diff --git a/tigerpath/tests.py b/tigerpath/tests.py index 7f37774f..eed476f3 100644 --- a/tigerpath/tests.py +++ b/tigerpath/tests.py @@ -478,3 +478,89 @@ def test_copy_plan_copies_additional_majors(self): def test_editor_options_expose_major_cap(self): options = self.client.get("/api/v1/get_plan_editor_options/").json() self.assertEqual(options["maxMajors"], 3) + + +# External credits need no Course rows, so these fixtures stay independent of course data. +ACTIVE_CREDIT = {"id": "a1", "external": True, "name": "Credit A", "settled": []} +OTHER_CREDIT = {"id": "b1", "external": True, "name": "Credit B", "settled": []} + + +class ComparePlanApiTest(TestCase): + """TIG-337: compare mode reads a second plan by ?planId= without touching the active plan.""" + + def setUp(self): + self.user = User.objects.create_user(username="compare_user", password="testpass") + self.client.force_login(self.user) + self.profile = self.user.profile + self.profile.year = forms.create_year_choices()[0][0] + self.profile.save(update_fields=["year"]) + self.eco = Major.objects.create(name="Economics", code="ECO", degree="AB", supported=False) + self.pol = Major.objects.create(name="Politics", code="POL", degree="AB", supported=False) + self.cos = Major.objects.create( + name="Computer Science", code="COS", degree="BSE", supported=False + ) + + self.active = self.profile.schedule_plans.get() + self.active.major = self.eco + self.active.additional_major_ids = [self.pol.id] + self.active.schedule = [[ACTIVE_CREDIT]] + [[] for _ in range(8)] + self.active.save() + self.other = SchedulePlan.objects.create( + user_profile=self.profile, + name="Plan B", + major=self.cos, + minors=[], + additional_major_ids=[], + schedule=[[], [OTHER_CREDIT]] + [[] for _ in range(7)], + ) + state = self.profile.user_state or {} + state["active_plan_id"] = self.active.id + self.profile.user_state = state + self.profile.save(update_fields=["user_state"]) + + def active_plan_id(self): + return self.client.get("/api/v1/get_profile/").json()["activePlanId"] + + def test_schedule_for_compare_plan(self): + response = self.client.get(f"/api/v1/get_schedule/?planId={self.other.id}") + self.assertEqual(response.status_code, 200) + self.assertEqual(response.json()[1][0]["name"], "Credit B") + # Without planId the active plan is still returned. + active_schedule = self.client.get("/api/v1/get_schedule/").json() + self.assertEqual(active_schedule[0][0]["name"], "Credit A") + + def test_each_plan_reports_its_own_majors(self): + # Plans with different additional_major_ids (migration 0023) get their own requirements. + active = self.client.get("/api/v1/get_requirements/?layout=grouped").json() + other = self.client.get( + f"/api/v1/get_requirements/?layout=grouped&planId={self.other.id}" + ).json() + self.assertEqual(active["majors"], ["Economics", "Politics"]) + self.assertEqual(other["majors"], ["Computer Science"]) + + def test_compare_reads_never_change_active_plan_or_write(self): + before = {p.id: (p.schedule, p.updated_at) for p in self.profile.schedule_plans.all()} + self.client.get(f"/api/v1/get_schedule/?planId={self.other.id}") + self.client.get(f"/api/v1/get_requirements/?layout=grouped&planId={self.other.id}") + self.client.get(f"/api/v1/get_requirements/?planId={self.other.id}") + self.assertEqual(self.active_plan_id(), self.active.id) + after = {p.id: (p.schedule, p.updated_at) for p in self.profile.schedule_plans.all()} + self.assertEqual(before, after) + + def test_other_users_plan_is_not_found(self): + stranger = User.objects.create_user(username="stranger", password="testpass") + foreign = stranger.profile.schedule_plans.get() + for url in ("/api/v1/get_schedule/", "/api/v1/get_requirements/?layout=grouped"): + sep = "&" if "?" in url else "?" + self.assertEqual(self.client.get(f"{url}{sep}planId={foreign.id}").status_code, 404) + self.assertEqual(self.client.get(f"{url}{sep}planId=not-a-number").status_code, 404) + + def test_schedule_save_ignores_plan_id(self): + # The save endpoint always writes and answers for the active plan. + response = self.client.post( + f"/api/v1/update_schedule_and_get_requirements/?layout=grouped&planId={self.other.id}", + {"schedule": json.dumps([[] for _ in range(9)])}, + ) + self.assertEqual(response.json()["majors"], ["Economics", "Politics"]) + self.other.refresh_from_db() + self.assertEqual(self.other.schedule[1], [OTHER_CREDIT]) diff --git a/tigerpath/views.py b/tigerpath/views.py index e8dff83b..2c633718 100644 --- a/tigerpath/views.py +++ b/tigerpath/views.py @@ -1035,12 +1035,29 @@ def update_schedule(request): return JsonResponse({"status": "ok"}) -# returns user's existing schedule +def get_requested_plan(request, profile): + """The plan named by ?planId= (read-only compare view), else the active plan. + + Looking up a plan this way never changes which plan is active. Returns None when + planId is given but is not one of this user's plans. + """ + raw_plan_id = request.GET.get("planId") if request.method == "GET" else None + if raw_plan_id in (None, ""): + return get_active_plan(profile) + plan_id = parse_plan_id(raw_plan_id) + if plan_id is None: + return None + return profile.schedule_plans.filter(id=plan_id).first() + + +# returns user's existing schedule (the active plan, or ?planId= for compare mode) @login_required def get_schedule(request): profile = request.user.profile - active_plan = get_active_plan(profile) - schedule = ensure_minimum_schedule(active_plan.schedule) + plan = get_requested_plan(request, profile) + if plan is None: + return JsonResponse({"error": "Plan not found"}, status=404) + schedule = ensure_minimum_schedule(plan.schedule) return JsonResponse(schedule, safe=False) @@ -1048,11 +1065,13 @@ def get_schedule(request): @login_required def get_requirements(request): curr_user = request.user.profile - active_plan = get_active_plan(curr_user) + plan = get_requested_plan(request, curr_user) + if plan is None: + return JsonResponse({"error": "Plan not found"}, status=404) # The new UI asks for every major and minor on the plan; the classic response is unchanged. if request.GET.get("layout") == "grouped": - return JsonResponse(build_grouped_requirements(curr_user, active_plan)) - requirements = build_requirements_for_plan(curr_user, active_plan) + return JsonResponse(build_grouped_requirements(curr_user, plan)) + requirements = build_requirements_for_plan(curr_user, plan) return JsonResponse(requirements, safe=False) From 42bcf489fbd5724d94ddc81801ecd7e08f8ee635 Mon Sep 17 00:00:00 2001 From: Siddharth Gupta Date: Tue, 24 Nov 2026 14:20:12 -0500 Subject: [PATCH 2/4] (feat) TIG-337: "By year" compare layout, semesters lined up across plans Compare mode now opens in a By year layout: one row per semester, each plan's courses on a single line, the two plans side by side so every semester lines up for easy diffing. Courses only in one plan get a solid outline; courses in a different semester there get a dashed outline with a tooltip saying where. A summary counts both. The left plan stays editable (horizontal drop targets); below 1100px the toggle shows one column. The two-board layout remains under "Boards". Adds diffSchedules (unit-tested). Decision log D10. Co-Authored-By: Claude Opus 5.5 --- docs/decisions/TIG-337-compare-view.md | 18 ++ frontend/src/new/App.jsx | 48 ++++- frontend/src/new/components/Board.jsx | 57 ++++-- frontend/src/new/components/CompareByYear.jsx | 155 ++++++++++++++++ frontend/src/new/helpers/compare.js | 40 +++++ frontend/src/new/helpers/compare.test.js | 27 +++ frontend/src/new/styles.css | 167 +++++++++++++++++- 7 files changed, 493 insertions(+), 19 deletions(-) create mode 100644 frontend/src/new/components/CompareByYear.jsx diff --git a/docs/decisions/TIG-337-compare-view.md b/docs/decisions/TIG-337-compare-view.md index 442e4839..2b902ffe 100644 --- a/docs/decisions/TIG-337-compare-view.md +++ b/docs/decisions/TIG-337-compare-view.md @@ -81,3 +81,21 @@ The tour highlights the search pane and requirements panel, which compare mode h ### D9. Print shows the active plan only The compare side and the summaries are `dont-print`. The printout stays "My Four Year Schedule: ". + +### D10. "By year" is the default compare layout; "Boards" stays as an option + +Requested in review: line the two plans up year by year so each semester can be compared at a glance. +**Decision:** compare mode opens in **By year**: Freshman to Senior run top to bottom, each with a Fall row +and a Spring row. Each row holds one plan's courses on a single line, active plan on the left and compared plan +on the right, so the same semester sits side by side. +- **Differences** are shown by outline shape, not color alone. A solid outline means the course is only in this + plan; a dashed outline means it's in a different semester in the other plan (the chip's tooltip says which). + Courses in the same semester in both plans stay plain. A one-line summary counts each kind, and screen readers + get the same wording. Matching uses the catalog id (external credits match by name), over the eight board + semesters (`diffSchedules`, unit-tested). +- **The left plan stays editable:** each row is a horizontal drop target, so courses can be reordered, moved + between semesters (including by keyboard) or removed. Chips shrink and truncate to keep one line per semester; + the hover card shows the full name. +- **Below 1100px** the existing toggle shows one plan's column, still aligned by semester with the markers. +- **Printing** while comparing prints the active plan as a normal board. +- **Boards** (two four-year grids, the issue's literal ask) is one click away, so reviewers can choose. diff --git a/frontend/src/new/App.jsx b/frontend/src/new/App.jsx index 9f26fc1e..8a88b957 100644 --- a/frontend/src/new/App.jsx +++ b/frontend/src/new/App.jsx @@ -14,6 +14,7 @@ import CourseDrawer from './components/CourseDrawer'; import SettingsModal from './components/SettingsModal'; import ComparePicker from './components/ComparePicker'; import CompareSummary from './components/CompareSummary'; +import CompareByYear from './components/CompareByYear'; import './styles.css'; const semesterIndexOf = (droppableId) => parseInt(droppableId.replace('sem', ''), 10); @@ -33,6 +34,8 @@ export default function App() { const [creditPath, setCreditPath] = useState(null); // Below 1100px compare mode shows one board at a time; this picks which. const [compareView, setCompareView] = useState('active'); + // 'year': semesters lined up across both plans (default); 'boards': two four-year boards. + const [compareLayout, setCompareLayout] = useState('year'); const themeName = profile?.theme || 'purple'; useEffect(() => { @@ -168,7 +171,28 @@ export default function App() { {planner.notice.text}
)} -
+
+
+ + +
+
+
+ {compareLayout === 'year' ? ( + <> +
+ +
+ {/* Printing while comparing prints the active plan as a normal board. */} +
+ {schedule && } +
+ + ) : (
@@ -217,6 +262,7 @@ export default function App() { )}
+ )}
) : ( diff --git a/frontend/src/new/components/Board.jsx b/frontend/src/new/components/Board.jsx index e43506bb..894e0337 100644 --- a/frontend/src/new/components/Board.jsx +++ b/frontend/src/new/components/Board.jsx @@ -40,12 +40,29 @@ function CourseHoverCard({ course, semesterIndex, duplicate }) { ); } +/** + * By-year compare marker. The chip's outline (solid = only in this plan, dashed = other semester there) + * shows the difference; this text says it for screen readers, and the chip's title for hover. + */ +function DiffTag({ diff }) { + if (!diff || diff.status === 'same') return null; + return {diff.status === 'only' ? ' (only in this plan)' : ` (${diff.title})`}; +} + +const diffTitle = (diff) => { + if (!diff || diff.status === 'same') return undefined; + return diff.status === 'only' ? 'Only in this plan' : `Moved: ${diff.title}`; +}; + +const diffClass = (diff) => (diff && diff.status !== 'same' ? `diff-${diff.status}` : ''); + /** Compare mode's right-hand board: same look, no drag-and-drop and no remove button. */ -function ReadOnlyCourseChip({ course, semesterIndex, duplicate }) { +export function ReadOnlyCourseChip({ course, semesterIndex, duplicate, diff }) { const [hover, setHover] = useState(false); return (
setHover(true)} onMouseLeave={() => setHover(false)} @@ -54,13 +71,14 @@ function ReadOnlyCourseChip({ course, semesterIndex, duplicate }) { aria-label={`${course.name}${course.title ? `: ${course.title}` : ''}`} > {course.name} + {course.title} {hover && }
); } -function CourseChip({ course, semesterIndex, index, duplicate, onRemove }) { +export function CourseChip({ course, semesterIndex, index, duplicate, onRemove, diff }) { const [hover, setHover] = useState(false); return ( @@ -71,7 +89,8 @@ function CourseChip({ course, semesterIndex, index, duplicate, onRemove }) { {...provided.dragHandleProps} className={`tp-course ${snapshot.isDragging ? 'dragging' : ''} ${ isWrongSeason(course, semesterIndex) ? 'wrong-season' : '' - }`} + } ${diffClass(diff)}`} + title={diffTitle(diff)} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)} onFocus={() => setHover(true)} @@ -79,6 +98,7 @@ function CourseChip({ course, semesterIndex, index, duplicate, onRemove }) { aria-label={`${course.name}${course.title ? `: ${course.title}` : ''}`} > {course.name} + {course.title}
- {compareLayout === 'year' ? ( + {planner.compareError ? ( +
+

Couldn't load {comparePlan.name} to compare. Your own plan is unaffected.

+
+ + +
+
+ ) : compareLayout === 'year' ? ( <>
`${YEARS[Math.floor(index / 2)]} ${SEASONS[index % 2]}`; @@ -31,7 +31,7 @@ function EditableRow({ index, season, courses, draggingSeason, duplicateNames, m index={i} duplicate={duplicateNames.has(course.name)} onRemove={onRemove} - diff={withTitle(marks.get(courseKey(course)), otherName)} + diff={withTitle(marks.get(occurrenceKey(course, index)), otherName)} /> ))} {provided.placeholder} @@ -51,7 +51,7 @@ function ReadOnlyRow({ index, courses, duplicateNames, marks, otherName }) { course={course} semesterIndex={index} duplicate={duplicateNames.has(course.name)} - diff={withTitle(marks.get(courseKey(course)), otherName)} + diff={withTitle(marks.get(occurrenceKey(course, index)), otherName)} /> ))} {courses.length === 0 && —} diff --git a/frontend/src/new/helpers/compare.js b/frontend/src/new/helpers/compare.js index d4aa9634..c8d2baf9 100644 --- a/frontend/src/new/helpers/compare.js +++ b/frontend/src/new/helpers/compare.js @@ -45,37 +45,45 @@ const BOARD_SEMESTERS = 8; /** One identity per course: catalog id, or the name for external credits (which have random ids). */ export const courseKey = (course) => (course?.external ? `ext:${course.name}` : `id:${course?.id}`); -function semesterIndexByKey(schedule) { +/** Every board semester each course appears in (a course can be scheduled more than once). */ +function semestersByKey(schedule) { const where = new Map(); (schedule || []).slice(0, BOARD_SEMESTERS).forEach((semester, index) => { (semester || []).forEach((course) => { const key = courseKey(course); - if (!where.has(key)) where.set(key, index); + if (!where.has(key)) where.set(key, new Set()); + where.get(key).add(index); }); }); return where; } +/** Mark key for one occurrence: the course plus the semester it sits in. */ +export const occurrenceKey = (course, semesterIndex) => `${courseKey(course)}@${semesterIndex}`; + function markSide(schedule, otherWhere) { const marks = new Map(); (schedule || []).slice(0, BOARD_SEMESTERS).forEach((semester, index) => { (semester || []).forEach((course) => { - const key = courseKey(course); - if (!otherWhere.has(key)) marks.set(key, { status: 'only' }); - else if (otherWhere.get(key) !== index) marks.set(key, { status: 'moved', otherIndex: otherWhere.get(key) }); - else marks.set(key, { status: 'same' }); + const others = otherWhere.get(courseKey(course)); + let mark; + if (!others) mark = { status: 'only' }; + else if (others.has(index)) mark = { status: 'same' }; + else mark = { status: 'moved', otherIndex: Math.min(...others) }; + marks.set(occurrenceKey(course, index), mark); }); }); return marks; } /** - * Per-course differences between two plans, for the "By year" compare view: each course is - * 'same' (same semester in both), 'moved' (other semester in the other plan: `otherIndex`) or - * 'only' (not in the other plan at all). Only the eight board semesters are compared. + * Per-occurrence differences between two plans, for the "By year" compare view, keyed by + * `occurrenceKey(course, semester)`: 'same' (the other plan has it in this semester too), 'moved' + * (only in other semesters there: `otherIndex`) or 'only' (not in the other plan at all). A course + * scheduled twice gets a mark for each copy. Only the eight board semesters are compared. */ export function diffSchedules(left, right) { - const leftWhere = semesterIndexByKey(left); - const rightWhere = semesterIndexByKey(right); + const leftWhere = semestersByKey(left); + const rightWhere = semestersByKey(right); return { left: markSide(left, rightWhere), right: markSide(right, leftWhere) }; } diff --git a/frontend/src/new/helpers/compare.test.js b/frontend/src/new/helpers/compare.test.js index a7949db9..93b9e9b0 100644 --- a/frontend/src/new/helpers/compare.test.js +++ b/frontend/src/new/helpers/compare.test.js @@ -39,7 +39,7 @@ describe('planSummaries', () => { }); }); -import { courseKey, diffSchedules } from './compare'; +import { courseKey, diffSchedules, occurrenceKey } from './compare'; describe('diffSchedules', () => { const sched = (...semesters) => [...semesters, ...Array.from({ length: 9 - semesters.length }, () => [])]; @@ -49,11 +49,11 @@ describe('diffSchedules', () => { const left = sched([c('eco100'), c('cos126')], [c('mat103')]); const right = sched([c('eco100')], [], [c('cos126'), c('pol220')]); const { left: l, right: r } = diffSchedules(left, right); - expect(l.get('id:eco100')).toEqual({ status: 'same' }); - expect(l.get('id:cos126')).toEqual({ status: 'moved', otherIndex: 2 }); - expect(l.get('id:mat103')).toEqual({ status: 'only' }); - expect(r.get('id:cos126')).toEqual({ status: 'moved', otherIndex: 0 }); - expect(r.get('id:pol220')).toEqual({ status: 'only' }); + expect(l.get('id:eco100@0')).toEqual({ status: 'same' }); + expect(l.get('id:cos126@0')).toEqual({ status: 'moved', otherIndex: 2 }); + expect(l.get('id:mat103@1')).toEqual({ status: 'only' }); + expect(r.get('id:cos126@2')).toEqual({ status: 'moved', otherIndex: 0 }); + expect(r.get('id:pol220@2')).toEqual({ status: 'only' }); }); it('matches external credits by name and ignores the external-credits slot', () => { @@ -61,7 +61,16 @@ describe('diffSchedules', () => { const left = sched([ap]); const right = sched([{ ...ap, id: 'random-2' }]); right[8] = [c('only-in-slot-9')]; - expect(diffSchedules(left, right).left.get(courseKey(ap))).toEqual({ status: 'same' }); - expect(diffSchedules(left, right).right.has('id:only-in-slot-9')).toBe(false); + expect(diffSchedules(left, right).left.get(occurrenceKey(ap, 0))).toEqual({ status: 'same' }); + expect(diffSchedules(left, right).right.has('id:only-in-slot-9@8')).toBe(false); + }); + + it('marks each copy of a course scheduled twice on its own', () => { + // Left has COS 126 in semesters 0 and 2; right has it only in semester 0. + const left = sched([c('cos126')], [], [c('cos126')]); + const right = sched([c('cos126')]); + const { left: l } = diffSchedules(left, right); + expect(l.get('id:cos126@0')).toEqual({ status: 'same' }); + expect(l.get('id:cos126@2')).toEqual({ status: 'moved', otherIndex: 0 }); }); }); diff --git a/frontend/src/new/styles.css b/frontend/src/new/styles.css index 905e5cf9..58ad9097 100644 --- a/frontend/src/new/styles.css +++ b/frontend/src/new/styles.css @@ -1496,6 +1496,14 @@ button:disabled { /* ── Compare: By year layout (TIG-337) ──────────────────────────────────── */ +.tp-compare-error p { + margin: 0; +} + +.tp-compare-error .tp-confirm-actions { + margin-top: 10px; +} + .tp-compare-controls { display: flex; align-items: center; diff --git a/frontend/src/new/usePlanner.js b/frontend/src/new/usePlanner.js index 8f612a85..b2a54afc 100644 --- a/frontend/src/new/usePlanner.js +++ b/frontend/src/new/usePlanner.js @@ -29,6 +29,8 @@ export default function usePlanner() { const [comparePlanId, setComparePlanIdState] = useState(null); const [compareSchedule, setCompareSchedule] = useState(null); const [compareRequirements, setCompareRequirements] = useState(null); + // A failed compare read shows an error, never an empty plan (which would look like every course differs). + const [compareError, setCompareError] = useState(false); const compareSeq = useRef(0); // True while a tab click swaps the two sides: for a moment the compared plan equals the still-active // plan, which must not count as "both sides show the same plan". @@ -188,15 +190,22 @@ export default function usePlanner() { const seq = ++compareSeq.current; setCompareSchedule(null); setCompareRequirements(null); + setCompareError(false); if (planId == null) return; + const failed = () => { + if (seq !== compareSeq.current) return; + setCompareSchedule(null); + setCompareRequirements(null); + setCompareError(true); + }; api .getSchedule(planId) .then((data) => seq === compareSeq.current && setCompareSchedule(data && data.length ? data : emptySchedule())) - .catch(() => seq === compareSeq.current && setCompareSchedule(emptySchedule())); + .catch(failed); api .getRequirements(planId) .then((data) => seq === compareSeq.current && setCompareRequirements(unwrapGroupedRequirements(data))) - .catch(() => seq === compareSeq.current && setCompareRequirements(unwrapGroupedRequirements(null))); + .catch(failed); }, []); const setComparePlanId = useCallback( @@ -302,6 +311,8 @@ export default function usePlanner() { comparePlan, compareSchedule, compareRequirements, + compareError, + retryCompare: () => loadCompare(comparePlanId), setComparePlanId, ...actions, };