From b24c85775cf1b560d755029db2ca37ea3cc4a563 Mon Sep 17 00:00:00 2001 From: YoussefHanyy Date: Fri, 27 Nov 2026 17:41:40 +0200 Subject: [PATCH 01/24] Update course icons and portal design --- apps/web/public/portal-studio/app.js | 11 +- apps/web/public/portal-studio/index.html | 4 +- .../portal-studio/notification-scenes.js | 28 +- .../public/portal-studio/quiet-calendar.css | 53 +++ .../public/portal-studio/quiet-calendar.js | 259 ++++++++++++ .../public/portal-studio/student-pages.css | 8 + apps/web/src/components/AcademicWorkspace.jsx | 399 ++++++------------ apps/web/src/components/B1Pages.jsx | 4 +- apps/web/src/components/FilterDisclosure.jsx | 1 + .../src/components/FinancialRecordsPage.jsx | 4 +- apps/web/src/components/GraduationReview.jsx | 4 +- .../components/MandatoryRemovalDashboard.jsx | 2 + apps/web/src/components/SlotChangesPage.jsx | 4 +- apps/web/src/portal-academic.css | 115 +++++ apps/web/src/portal-services.jsx | 3 + apps/web/src/term-validation.js | 28 ++ apps/web/src/term-validation.test.js | 25 ++ apps/web/vite.config.js | 2 +- docs/portal-design-system.md | 12 + tests/browser/portal.spec.mjs | 124 ++++++ tests/browser/quiet-calendar.spec.mjs | 102 +++++ work/term-page-styles.css | 56 +++ work/terms-workspace.jsx | 147 +++++++ 23 files changed, 1122 insertions(+), 273 deletions(-) create mode 100644 apps/web/public/portal-studio/quiet-calendar.css create mode 100644 apps/web/public/portal-studio/quiet-calendar.js create mode 100644 apps/web/src/term-validation.js create mode 100644 apps/web/src/term-validation.test.js create mode 100644 tests/browser/quiet-calendar.spec.mjs create mode 100644 work/term-page-styles.css create mode 100644 work/terms-workspace.jsx diff --git a/apps/web/public/portal-studio/app.js b/apps/web/public/portal-studio/app.js index 3e933d8..dd34309 100644 --- a/apps/web/public/portal-studio/app.js +++ b/apps/web/public/portal-studio/app.js @@ -687,7 +687,7 @@ function notifications(){ ${emailStatus ? `Email: ${escapeHtml(emailStatus)}` : ''} ${item.isRead ? 'Read' : button('Mark as read','read-one','btn desk-action', `data-notification="${escapeHtml(item._id)}"`)} `; - }).join('')}` : `
${role === 'coordinator' ? notificationScenes('tube',false) : ''}

You’re all caught up.

${tab === 'unread' ? 'No unread notifications.' : 'No notifications yet.'}

`))+''; + }).join('')}` : `
${notificationScenes('coffee',false)}

You’re all caught up.

${tab === 'unread' ? 'No unread notifications.' : 'No notifications yet.'}

`))+''; } async function markPortalNotifications(ids, control) { @@ -1322,6 +1322,9 @@ function mountPortalService(host) { } function render(focus=false){ + const previousRole = document.body.dataset.portalRole; + const sidebarScroll = app.querySelector('.sidebar')?.scrollTop || 0; + const navigationScroll = app.querySelector('.sidebar nav')?.scrollTop || 0; loadStudentSchedule(); loadAccountData(focus); closeDeadline(); @@ -1364,6 +1367,12 @@ function render(focus=false){ const lamp = app.querySelector('.desk-lamp-scene'); if (lamp) mountDeskLamp(lamp); binderMotion.mount(app.querySelector('[data-concertina=true] .folio-stack')); + if (!authPages.has(page) && previousRole === role) { + const sidebar = app.querySelector('.sidebar'); + const navigation = sidebar?.querySelector('nav'); + if (sidebar) sidebar.scrollTop = sidebarScroll; + if (navigation) navigation.scrollTop = navigationScroll; + } if(focus)document.querySelector('#content')?.focus({preventScroll:true}); } function navigate(target, url, state = {}) { diff --git a/apps/web/public/portal-studio/index.html b/apps/web/public/portal-studio/index.html index eeb3c79..c9669f4 100644 --- a/apps/web/public/portal-studio/index.html +++ b/apps/web/public/portal-studio/index.html @@ -22,6 +22,7 @@ + @@ -29,6 +30,7 @@ + @@ -43,6 +45,6 @@ - + diff --git a/apps/web/public/portal-studio/notification-scenes.js b/apps/web/public/portal-studio/notification-scenes.js index 5b09e6c..10b76d2 100644 --- a/apps/web/public/portal-studio/notification-scenes.js +++ b/apps/web/public/portal-studio/notification-scenes.js @@ -89,11 +89,33 @@ const notificationScenes = (() => { (full?peg(138,68)+peg(231,78):peg(191,78))+peg(293,72)+plant+ path('m35 173 46-3m219 10 63-3m26-10 40-3','none','stroke="var(--muted)" opacity=".65"'); } - const scenes = {tube,pigeon,lighthouse,press,line}; + function coffee() { + // A letter lies flat under the saucer; its turned corner has its own opaque face. + const stationery = path('M57 147q57 2 118 15l-18 25q-53-12-116-16Z',paper)+ + path('m157 187-13-13 22-2q-5 7-9 15Z','#dfd0af')+ + path('m69 160 34 6m-39 1 56 11','none','stroke="#a5967b" stroke-width="1.2"'); + const saucer = path('M62 155q49-14 102 0-49 21-102 0Z','#91aa9a')+ + path('M71 156q42 10 84-1','none','stroke="#c9d3b8" stroke-width="1.3"'); + const cup = path('M82 112c-31-15-36 23-4 24','none','stroke="#d6ae70" stroke-width="8"')+ + path('M82 112c-31-15-36 23-4 24','none','stroke-width="1.3"')+ + path('M80 105q32 6 65 0l-4 30q-3 20-29 19-25-1-28-20Z',paper)+ + path('m81 115q32 7 62 0l-1 7q-30 6-60-1Z','#719386')+ + path('M80 105c0-9 65-9 65 0s-65 9-65 0Z',paper)+ + path('M87 105q25-6 51 0-25 6-51 0Z','#574a38'); + const steam = moving('coffee-steam',path('M102 85c-11-12 10-17 1-30m20 29c-11-11 10-17 1-30','none','stroke="var(--muted)" stroke-width="1.5"')); + const bell = circle(228,114,4,brass)+path('m225 118 1 5h5v-5',brass)+ + path('M201 149q2-27 28-28 25 0 28 27l5 5-66 1Z',brass)+ + path('m208 137 4-6','none','stroke="#f5ecd6" stroke-width="2"')+ + path('m196 153q31-4 66-1l2 6q-33 4-70 1Z','#dfbb80')+ + path('m190 161q37-6 78-1l2 7q-39 6-82 0Z','#60877a'); + return path('M39 184q111 5 241-1','none','stroke="var(--line)" stroke-width="1.2"')+ + stationery+saucer+cup+steam+bell; + } + const scenes = {tube,pigeon,lighthouse,press,line,coffee}; return function draw(name,full) { - const key = Object.hasOwn(scenes,name) ? name : 'tube'; + const key = !full && (!name || name === 'tube') ? 'coffee' : Object.hasOwn(scenes,name) ? name : 'tube'; return ``; }; })(); diff --git a/apps/web/public/portal-studio/quiet-calendar.css b/apps/web/public/portal-studio/quiet-calendar.css new file mode 100644 index 0000000..2da38ca --- /dev/null +++ b/apps/web/public/portal-studio/quiet-calendar.css @@ -0,0 +1,53 @@ +.quiet-calendar,.quiet-calendar *{box-sizing:border-box} +body dialog.quiet-calendar{animation:none;--qc-paper:#252522;--qc-ink:#efeee9;--qc-muted:#bdbbb0;--qc-line:#484843;--qc-selected:#e8e4d9;--qc-selected-ink:#252522;position:fixed;inset:auto;margin:0;padding:26px;width:min(420px,calc(100vw - 24px));max-width:none;max-height:calc(100dvh - 24px);overflow:auto;border:1px solid var(--qc-line);border-radius:16px;background:var(--qc-paper);color:var(--qc-ink);box-shadow:0 18px 60px #0005;font:14px/1.5 Styrene,Arial,sans-serif;overscroll-behavior:contain;color-scheme:dark} +html[data-theme=light] body dialog.quiet-calendar{animation:none;--qc-paper:#f8f6ef;--qc-ink:#302d28;--qc-muted:#615c52;--qc-line:#d1cdc2;--qc-selected:#302d28;--qc-selected-ink:#f8f6ef;color-scheme:light} +.quiet-calendar::backdrop{background:#0002} +.quiet-calendar header{display:flex;justify-content:space-between;align-items:flex-start;gap:20px;margin-bottom:24px} +.quiet-calendar h2{font:600 23px/1.3 Styrene,Arial,sans-serif;margin:0 0 6px;letter-spacing:-.4px;color:var(--qc-ink)} +.quiet-calendar p{margin:0;color:var(--qc-muted)} +.quiet-calendar button{font:inherit;color:var(--qc-ink);border:1px solid transparent;background:none;border-radius:8px;cursor:pointer;min-height:38px;padding:7px 13px;touch-action:manipulation} +.quiet-calendar button:hover{background:color-mix(in srgb,var(--qc-ink) 9%,transparent)} +.quiet-calendar button:active{transform:scale(.97)} +.quiet-calendar button:focus-visible,.quiet-calendar input:focus-visible{outline:2px solid var(--qc-ink);outline-offset:3px} +.quiet-calendar button:disabled{opacity:.3;cursor:default;transform:none} +.quiet-calendar .quiet-calendar-close{font-size:24px;line-height:1;padding:4px 10px} +.quiet-calendar-layout{display:grid;grid-template-columns:minmax(0,1fr);gap:0} +.quiet-calendar-month-head{display:flex;align-items:center;justify-content:space-between;margin-bottom:14px} +.quiet-calendar-month-head h3{font-size:17px;font-weight:500;color:var(--qc-ink);margin:0} +.quiet-calendar .quiet-calendar-month-head h3 button{width:auto;font-size:17px;line-height:1.4;padding:6px 10px;border:0} +.quiet-calendar-year{display:flex;align-items:center;gap:10px;color:var(--qc-muted);font-size:13px} +.quiet-calendar-year input{width:100px;border:1px solid var(--qc-line);border-radius:8px;padding:8px;background:transparent;color:var(--qc-ink);font:inherit;font-size:17px} +.quiet-calendar-months{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px;padding:8px 0} +.quiet-calendar-months button{min-height:48px;border-color:var(--qc-line)} +.quiet-calendar-months button[aria-pressed=true]{background:var(--qc-selected);color:var(--qc-selected-ink)} +.quiet-calendar-month-head button{border-color:var(--qc-line);font-size:25px;line-height:1;width:38px;padding:4px} +.quiet-calendar-grid [role=row]{display:grid;grid-template-columns:repeat(7,minmax(0,1fr))} +.quiet-calendar-grid .quiet-calendar-weekdays span{text-align:center;font-size:12px;color:var(--qc-muted);padding:8px 0} +.quiet-calendar .quiet-calendar-grid button{position:relative;isolation:isolate;min-width:0;min-height:40px;border:0;border-radius:0;padding:6px 0;font-variant-numeric:tabular-nums;background:transparent} +.quiet-calendar-grid button::before{content:"";position:absolute;inset:3px 0;z-index:-2} +.quiet-calendar-grid button.is-between::before,.quiet-calendar-grid button.is-start:not(.is-end)::before,.quiet-calendar-grid button.is-end:not(.is-start)::before{background:color-mix(in srgb,var(--qc-selected) 16%,transparent)} +.quiet-calendar-grid button.is-start::before{left:50%} +.quiet-calendar-grid button.is-end::before{right:50%} +.quiet-calendar-grid button.is-selected::after{content:"";position:absolute;inset:2px;z-index:-1;background:var(--qc-selected);border-radius:50%} +.quiet-calendar .quiet-calendar-grid button.is-selected{color:var(--qc-selected-ink);font-weight:600} +.quiet-calendar-grid button:hover::after{content:"";position:absolute;inset:2px;z-index:-1;border:1px solid var(--qc-muted);border-radius:50%} +.quiet-calendar-grid button[aria-current=date]:not(.is-selected){text-decoration:underline;text-underline-offset:5px} +.quiet-calendar .quiet-calendar-today{margin-top:12px;font-size:12px;color:var(--qc-muted)} +.quiet-calendar-label{display:block;color:var(--qc-muted);font-size:13px;margin:0 0 10px} +.quiet-calendar-edges{display:flex;gap:8px;margin-top:14px} +.quiet-calendar-edges button{font-size:12px;border-color:var(--qc-line);flex:1} +.quiet-calendar-edges button[aria-pressed=true]{background:var(--qc-selected);color:var(--qc-selected-ink)} +.quiet-calendar .quiet-calendar-hint{font-size:12px;margin-top:14px} +.quiet-calendar-times{margin-top:24px} +.quiet-calendar-times>div{display:flex;align-items:center;gap:12px} +.quiet-calendar-times label{display:grid;gap:5px;font-size:12px;color:var(--qc-muted);flex:1;min-width:0} +.quiet-calendar-times input{width:100%;min-width:0;padding:10px;border:1px solid var(--qc-line);background:transparent;color:var(--qc-ink);border-radius:8px;font:inherit;font-size:15px} +.quiet-calendar-presets{display:flex;flex-wrap:wrap;gap:7px;margin-top:16px} +.quiet-calendar-presets button{font-size:11px;border-color:var(--qc-line);min-height:32px;padding:4px 8px} +.quiet-calendar .quiet-calendar-error{color:#e3a591;font-size:12px;margin-top:12px} +html[data-theme=light] .quiet-calendar .quiet-calendar-error{color:#97422b} +.quiet-calendar footer{display:flex;justify-content:space-between;align-items:center;gap:12px;margin-top:24px;padding-top:18px;border-top:1px solid var(--qc-line)} +.quiet-calendar footer>div{display:flex;gap:10px} +.quiet-calendar footer .quiet-calendar-apply{background:var(--qc-selected);color:var(--qc-selected-ink);padding-inline:24px;font-weight:600} + +@media(max-width:620px){body dialog.quiet-calendar{padding:18px}.quiet-calendar header{margin-bottom:14px}.quiet-calendar h2{font-size:21px}} diff --git a/apps/web/public/portal-studio/quiet-calendar.js b/apps/web/public/portal-studio/quiet-calendar.js new file mode 100644 index 0000000..093f39f --- /dev/null +++ b/apps/web/public/portal-studio/quiet-calendar.js @@ -0,0 +1,259 @@ +/* Shared date picker for Portal and embedded service shadow roots. */ +(() => { + 'use strict'; + const selector = 'input[type="date"],input[type="datetime-local"]'; + const pad = n => String(n).padStart(2, '0'); + const iso = date => `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`; + const parse = value => { + const match = /^(\d{4})-(\d{2})-(\d{2})/.exec(value || ''); + if (!match) return null; + const date = new Date(0); + date.setFullYear(+match[1], +match[2] - 1, +match[3]); + date.setHours(12, 0, 0, 0); + return iso(date) === match[0] ? date : null; + }; + const shift = (date, days) => { const next = new Date(date); next.setDate(next.getDate() + days); return next; }; + const escape = value => String(value).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); + let active; + + function close(restore = true) { + if (!active) return; + const { panel, trigger, onClose } = active; + active = null; + panel.close(); + panel.remove(); + onClose?.(); + if (restore && trigger.isConnected) trigger.focus({ preventScroll: true }); + } + + function open(trigger, root, commit) { + if (trigger.disabled || trigger.readOnly) return; + close(false); + const key = trigger.dataset.calendarRange; + const candidates = key ? [...root.querySelectorAll(selector)].filter(input => input.dataset.calendarRange === key && !input.disabled && !input.readOnly) : [trigger]; + const start = candidates.find(input => input.dataset.calendarEdge === 'start') || trigger; + const end = candidates.find(input => input.dataset.calendarEdge === 'end'); + const inputs = end && end !== start ? [start, end] : [trigger]; + const range = inputs.length === 2; + const timed = inputs.some(input => input.type === 'datetime-local'); + const values = inputs.map(input => input.value.slice(0, 10)); + const times = inputs.map((input, index) => input.value.slice(11, 16) || (index ? '17:00' : '09:00')); + const lower = (range ? start.min : trigger.min).slice(0, 10); + const upper = (range ? end.max : trigger.max).slice(0, 10); + let edge = range && trigger === end ? 1 : 0; + let focused = values[edge] || values[0] || iso(new Date()); + let month = parse(focused) || new Date(); + month = new Date(month.getFullYear(), month.getMonth(), 1, 12); + let choosingPeriod = false; + let yearDraft = String(month.getFullYear()); + const panel = document.createElement('dialog'); + panel.className = 'quiet-calendar'; + panel.setAttribute('aria-labelledby', 'quiet-calendar-title'); + const fieldLabel = trigger.labels?.[0]?.textContent?.trim() || trigger.getAttribute('aria-label') || 'Choose date'; + const zone = /\bUTC\b/.test(fieldLabel) ? ' (UTC)' : ''; + const available = value => (!lower || value >= lower) && (!upper || value <= upper); + const firstYear = lower ? +lower.slice(0, 4) : 1; + const lastYear = upper ? +upper.slice(0, 4) : 9999; + const validYear = () => Number.isInteger(+yearDraft) && +yearDraft >= firstYear && +yearDraft <= lastYear; + const monthAvailable = (year, index) => { + const first = new Date(0); first.setFullYear(year, index, 1); first.setHours(12, 0, 0, 0); + const last = new Date(first); last.setMonth(last.getMonth() + 1); last.setDate(0); + return (!lower || iso(last) >= lower) && (!upper || iso(first) <= upper); + }; + const state = { panel, trigger, root }; + active = state; + trigger.setAttribute('aria-expanded', 'true'); + state.onClose = () => trigger.removeAttribute('aria-expanded'); + + function position() { + if (!trigger.isConnected) { close(false); return; } + const anchor = trigger.getBoundingClientRect(); + const rect = panel.getBoundingClientRect(); + panel.style.left = `${Math.max(12, Math.min(anchor.left, innerWidth - rect.width - 12))}px`; + panel.style.top = `${Math.max(12, Math.min(anchor.bottom + 12, innerHeight - rect.height - 12))}px`; + panel.style.setProperty('--quiet-pointer', `${Math.max(24, Math.min(anchor.left + 28 - parseFloat(panel.style.left), rect.width - 24))}px`); + } + + function render(focusDay = false) { + const first = new Date(month.getFullYear(), month.getMonth(), 1, 12); + const count = new Date(month.getFullYear(), month.getMonth() + 1, 0).getDate(); + const cells = Array.from({ length: Math.ceil((first.getDay() + count) / 7) * 7 }, (_, index) => { + const day = index - first.getDay() + 1; + if (day < 1 || day > count) return ''; + const date = new Date(month.getFullYear(), month.getMonth(), day, 12); + const value = iso(date); + const selected = values.includes(value); + const between = range && values[0] && values[1] && value > values[0] && value < values[1]; + const completeRange = range && values[0] && values[1]; + const classes = [selected ? 'is-selected' : '', between ? 'is-between' : '', completeRange && value === values[0] ? 'is-start' : '', completeRange && value === values[1] ? 'is-end' : ''].filter(Boolean).join(' '); + return ``; + }); + const rows = []; + for (let i = 0; i < cells.length; i += 7) rows.push(`
${cells.slice(i, i + 7).join('')}
`); + const periodChooser = `
${Array.from({length:12}, (_, index) => ``).join('')}
`; + const dayChooser = `

${['Sun','Mon','Tue','Wed','Thu','Fri','Sat'].map(day => `${day}`).join('')}
${rows.join('')}
`; + panel.innerHTML = `

Calendar

${range ? 'Select a date range' : 'Select a date'}${timed ? ' and time' : ''}${zone}.

+
${choosingPeriod ? periodChooser : dayChooser}
+ ${range ? `

Choose the ${edge ? 'end' : 'start'} date.

` : ''} + ${timed ? `
${range ? 'Time range' : 'Time'}${zone}
${inputs.map((input, i) => ``).join('')}
${range ? '
' : ''}` : ''} +
`; + // Always offer a tab stop, including when the selected date is in another month. + if (!panel.querySelector('[data-date][tabindex="0"]:not(:disabled)')) { + const firstEnabled = panel.querySelector('[data-date]:not(:disabled)'); + if (firstEnabled) { firstEnabled.tabIndex = 0; focused = firstEnabled.dataset.date; } + } + if (panel.open) position(); + if (focusDay) panel.querySelector('[data-date][tabindex="0"]')?.focus({ preventScroll: true }); + } + + function apply() { + const proposed = inputs.map((input, i) => values[i] ? values[i] + (input.type === 'datetime-local' ? 'T' + times[i] : '') : ''); + let message = ''; + if (proposed.some((value, i) => !value && inputs[i].required)) message = 'Choose a date before applying.'; + else if (inputs.some((input, i) => input.type === 'datetime-local' && values[i] && !times[i])) message = 'Choose a time before applying.'; + else if (values.some(value => value && !available(value))) message = 'Choose a date within the allowed dates.'; + else if (range && proposed[0] && proposed[1] && proposed[0] > proposed[1]) message = 'The end must be on or after the start.'; + else if (range && ((proposed[0] && start.min && proposed[0] < start.min) || (proposed[1] && end.max && proposed[1] > end.max))) message = 'Choose a date and time within the allowed range.'; + else if (inputs.some((input, i) => { + const probe = input.cloneNode(); + probe.removeAttribute('min'); probe.removeAttribute('max'); + if (!range) { probe.min = input.min; probe.max = input.max; } + probe.value = proposed[i]; + return !probe.validity.valid; + })) message = 'Choose a valid date and time.'; + if (message) { panel.querySelector('.quiet-calendar-error').textContent = message; return; } + // Close before committing: a React update may unmount the source fields. + close(false); + inputs.forEach((input, i) => { + if (!input.isConnected) return; + const update = () => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set.call(input, proposed[i]); + input.dispatchEvent(new Event('input', { bubbles: true, composed: true })); + input.dispatchEvent(new Event('change', { bubbles: true, composed: true })); + }; + commit ? commit(update) : update(); + }); + if (trigger.isConnected) trigger.focus({ preventScroll: true }); + } + + panel.addEventListener('click', event => { + event.stopPropagation(); + const button = event.target.closest('button'); + if (!button) { if (event.target === panel) { const r = panel.getBoundingClientRect(); if (event.clientX < r.left || event.clientX > r.right || event.clientY < r.top || event.clientY > r.bottom) close(); } return; } + const action = button.dataset.action; + if (action === 'cancel') return close(); + if (action === 'apply') return apply(); + if (action === 'choose-period') { + choosingPeriod = !choosingPeriod; yearDraft = String(month.getFullYear()); render(); + panel.querySelector(choosingPeriod ? '[data-year]' : '[data-action="choose-period"]')?.focus({preventScroll:true}); + if (choosingPeriod) panel.querySelector('[data-year]').select(); + return; + } + if (action === 'previous-year' || action === 'next-year') { + const year = (validYear() ? +yearDraft : month.getFullYear()) + (action === 'next-year' ? 1 : -1); + yearDraft = String(Math.max(firstYear, Math.min(lastYear, year))); + render(); panel.querySelector(`[data-action="${action}"]`)?.focus(); return; + } + if (button.dataset.month !== undefined) { + if (!validYear()) return; + month.setFullYear(+yearDraft, +button.dataset.month, 1); + focused = iso(month); choosingPeriod = false; render(true); return; + } + if (action === 'clear') { values.fill(''); render(); return; } + if (button.dataset.edge) { edge = +button.dataset.edge; render(); panel.querySelector(`[data-edge="${edge}"]`)?.focus(); return; } + if (button.dataset.preset) { times.splice(0, 2, ...button.dataset.preset.split(',')); render(); return; } + if (action === 'previous' || action === 'next') { + month.setMonth(month.getMonth() + (action === 'next' ? 1 : -1)); + focused = iso(month); render(); panel.querySelector(`[data-action="${action}"]`).focus(); return; + } + const value = action === 'today' ? iso(new Date()) : button.dataset.date; + if (!value || !available(value)) return; + values[edge] = value; + if (range && values[0] && values[1] && values[0] > values[1]) values.reverse(); + focused = value; + month = parse(value); month.setDate(1); + if (range) edge = edge ? 0 : 1; + render(true); + }); + panel.addEventListener('input', event => { + if (event.target.matches('[data-time]')) times[+event.target.dataset.time] = event.target.value; + if (event.target.matches('[data-year]')) { + yearDraft = event.target.value; + panel.querySelectorAll('[data-month]').forEach(button => { + button.disabled = !validYear() || !monthAvailable(+yearDraft, +button.dataset.month); + button.setAttribute('aria-pressed', String(month.getFullYear() === +yearDraft && month.getMonth() === +button.dataset.month)); + }); + panel.querySelector('[data-action="previous-year"]').disabled = !validYear() || +yearDraft <= firstYear; + panel.querySelector('[data-action="next-year"]').disabled = !validYear() || +yearDraft >= lastYear; + panel.querySelector('.quiet-calendar-error').textContent = validYear() ? '' : `Choose a year from ${firstYear} to ${lastYear}.`; + } + }); + panel.addEventListener('keydown', event => { + event.stopPropagation(); + if (event.target.matches('[data-year]') && event.key === 'Enter') { + event.preventDefault(); + if (validYear()) panel.querySelector('[data-month]:not(:disabled)')?.focus(); + return; + } + const cell = event.target.closest('[data-date]'); + if (!cell) return; + const date = parse(cell.dataset.date); + let next; + const offsets = { ArrowLeft: -1, ArrowRight: 1, ArrowUp: -7, ArrowDown: 7 }; + if (Object.hasOwn(offsets, event.key)) next = shift(date, offsets[event.key]); + if (event.key === 'Home') next = shift(date, -date.getDay()); + if (event.key === 'End') next = shift(date, 6 - date.getDay()); + if (event.key === 'PageUp' || event.key === 'PageDown') { + next = new Date(date); next.setDate(1); next.setMonth(next.getMonth() + (event.key === 'PageDown' ? 1 : -1) * (event.shiftKey ? 12 : 1)); + next.setDate(Math.min(date.getDate(), new Date(next.getFullYear(), next.getMonth() + 1, 0).getDate())); + } + if (!next) return; + event.preventDefault(); + if (!available(iso(next))) return; + focused = iso(next); month = new Date(next.getFullYear(), next.getMonth(), 1, 12); render(true); + }); + panel.addEventListener('cancel', event => { event.preventDefault(); close(); }); + render(); + document.body.append(panel); + panel.showModal(); + position(); + panel.querySelector('[data-date][tabindex="0"]')?.focus({ preventScroll: true }); + } + + function mount(root, options = {}) { + const decorate = () => root.querySelectorAll(selector).forEach(input => input.setAttribute('aria-haspopup', 'dialog')); + decorate(); + const inputFor = event => event.target instanceof HTMLInputElement && event.target.matches(selector) ? event.target : null; + const pointer = event => { + const input = inputFor(event); + if (input && !input.disabled && !input.readOnly && event.button === 0) event.preventDefault(); + }; + const click = event => { + const input = inputFor(event); + if (!input || input.disabled || input.readOnly) return; + event.preventDefault(); open(input, root, options.commit); + }; + const key = event => { + const input = inputFor(event); + if (input && (event.key === 'Enter' || event.key === ' ' || (event.altKey && event.key === 'ArrowDown'))) { + event.preventDefault(); open(input, root, options.commit); + } + }; + root.addEventListener('pointerdown', pointer, true); + root.addEventListener('click', click, true); + root.addEventListener('keydown', key, true); + const observer = new MutationObserver(() => { decorate(); if (active?.root === root && !active.trigger.isConnected) close(false); }); + observer.observe(root, { childList: true, subtree: true }); + return () => { + if (active?.root === root) close(false); + observer.disconnect(); + root.removeEventListener('pointerdown', pointer, true); + root.removeEventListener('click', click, true); + root.removeEventListener('keydown', key, true); + }; + } + window.BobosCalendar = { mount, close, version: '3' }; + mount(document); + window.addEventListener('resize', () => close()); + window.addEventListener('popstate', () => close(false)); +})(); diff --git a/apps/web/public/portal-studio/student-pages.css b/apps/web/public/portal-studio/student-pages.css index 528b470..722b48a 100644 --- a/apps/web/public/portal-studio/student-pages.css +++ b/apps/web/public/portal-studio/student-pages.css @@ -283,6 +283,14 @@ .student-inbox .notification-plate + .student-inbox-list {gap:10px} .student-inbox .notification-plate + .student-inbox-list li {background:transparent;padding:4px 0} .student-inbox .notification-plate + .student-inbox-empty {background:transparent;padding:8px 0} +.notification-plate[data-scene=coffee] {width:min(320px,100%);max-height:210px} +.portal-studio #notice-results .empty .notification-plate[data-scene=coffee] {width:min(320px,90%);margin:0 auto 18px} +@media (prefers-reduced-motion:no-preference) { + .notification-plate[data-scene=coffee].arrived .scene-coffee-steam {animation:coffee-steam-arrive 1.8s ease-out} + .notification-plate[data-scene=coffee]:hover .scene-coffee-steam {animation:coffee-steam-hover 1.8s ease-out} +} +@keyframes coffee-steam-arrive {0%,100%{opacity:1;transform:translateY(0)}55%{opacity:.35;transform:translate(1px,-6px)}75%{opacity:0;transform:translate(1px,-8px)}76%{opacity:0;transform:translateY(3px)}} +@keyframes coffee-steam-hover {0%,100%{opacity:1;transform:translateY(0)}55%{opacity:.35;transform:translate(1px,-6px)}75%{opacity:0;transform:translate(1px,-8px)}76%{opacity:0;transform:translateY(3px)}} .notification-study-pair {display:grid;grid-template-columns:minmax(0,1.15fr) minmax(0,1fr);align-items:start;gap:clamp(20px,4vw,52px)} @media (max-width:680px) {.notification-study-pair {grid-template-columns:minmax(0,1fr)}} @media (prefers-reduced-motion:no-preference) { diff --git a/apps/web/src/components/AcademicWorkspace.jsx b/apps/web/src/components/AcademicWorkspace.jsx index 2c4bad0..4dbd84f 100644 --- a/apps/web/src/components/AcademicWorkspace.jsx +++ b/apps/web/src/components/AcademicWorkspace.jsx @@ -3,6 +3,8 @@ import { termLabel } from "../term-label.js"; import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react"; import { api, explainApiError } from "../api.js"; import PaperTossButton, { waitForPaperToss } from "./PaperTossButton.jsx"; +import { StudentRegister } from "./CoordinatorRecords.jsx"; +import { validateAcademicTerm, termFieldLabels } from "../term-validation.js"; const pretty = (value = "") => String(value || "—").replace(/([a-z])([A-Z])/g, "$1 $2").replace(/^./, (letter) => letter.toUpperCase()); const seasons = ["winter", "spring", "summer", "firstMakeup", "secondMakeup"]; @@ -170,292 +172,168 @@ function TermCalendar({ term }) { function TermsWorkspace({ token, role, notify }) { const [form, setForm] = useState(blankTerm); - const [termId, setTermId] = useState(""); + const [termId, setTermId] = useState(''); const [terms, setTerms] = useState([]); const [loading, setLoading] = useState(false); const [fetchingTerms, setFetchingTerms] = useState(false); - const [message, setMessage] = useState(""); - const [error, setError] = useState(""); + const [message, setMessage] = useState(''); + const [error, setError] = useState(''); + const [loadError, setLoadError] = useState(''); const [recordingStanding, setRecordingStanding] = useState(false); + const [editing, setEditing] = useState(false); + const [viewing, setViewing] = useState(null); + const [touched, setTouched] = useState({}); + const [attempt, setAttempt] = useState(0); + const [search, setSearch] = useState(''); + const [filters, setFilters] = useState({ year: '', season: '', status: '' }); + const editor = useRef(null); + const validation = validateAcademicTerm(form); + const visibleError = field => (attempt || touched[field]) ? validation[field] : ''; const loadTerms = async () => { - setFetchingTerms(true); + setFetchingTerms(true); setLoadError(''); try { - const data = await api("/api/academic-terms/academicTerm", { token }); + const data = await api('/api/academic-terms/academicTerm', { token }); setTerms(Array.isArray(data) ? data : []); - } catch (e) { - setError(explainApiError(e, "Academic terms")); - setTerms(readRecentTerms()); - } finally { - setFetchingTerms(false); - } + } catch { + setLoadError('Could not refresh academic terms. Your last loaded terms are still shown.'); + setTerms(current => current.length ? current : readRecentTerms()); + } finally { setFetchingTerms(false); } }; - + useEffect(() => { loadTerms(); }, [token]); useEffect(() => { - loadTerms(); - }, [token]); + if (attempt) editor.current?.querySelector('[aria-invalid="true"]')?.focus(); + }, [attempt]); - const update = (field, value) => { - setForm((current) => ({ ...current, [field]: value })); + const update = (field, value) => { setForm(current => ({ ...current, [field]: value })); setError(''); }; + const openEditor = term => { + setTermId(term?._id || term?.code || ''); setForm(term ? termToForm(term) : { ...blankTerm }); + setTouched({}); setAttempt(0); setError(''); setMessage(''); setViewing(null); setEditing(true); }; - - const toPayload = () => { - const payload = {}; - for (const key of Object.keys(blankTerm)) { - if (form[key] !== undefined) { - payload[key] = termDateFields.includes(key) && form[key] - ? dateToIso(form[key]) - : form[key]; - } - } - payload.code = form.code || `${form.season}-${form.academicYear.replace(/[^0-9]/g, "")}`; - return payload; - }; - - const validateDates = () => { - if (form.termStart && form.termEnd && form.termStart > form.termEnd) { - return "Term end must be on or after term start."; - } - if (form.teachingStart && form.teachingEnd && form.teachingStart > form.teachingEnd) { - return "Teaching end must be on or after teaching start."; - } - if (form.termStart && form.teachingStart && form.teachingStart < form.termStart) { - return "Teaching start must be on or after term start (Teaching must start during the term)."; - } - if (form.termEnd && form.teachingEnd && form.teachingEnd > form.termEnd) { - return "Teaching end must be on or before term end (Teaching must end during the term)."; - } - if (form.registrationStart && form.registrationEnd && form.registrationStart > form.registrationEnd) { - return "Registration end must be on or after registration start."; - } - return null; - }; - - const submit = async (event) => { - event.preventDefault(); - setError(""); - setMessage(""); - - const clientValidation = validateDates(); - if (clientValidation) { - setError(clientValidation); - return; - } - + const submit = async event => { + event.preventDefault(); if (loading) return; + setAttempt(value => value + 1); setError(''); + if (Object.keys(validation).length) return; + const payload = Object.fromEntries(Object.keys(blankTerm).map(key => [key, + termDateFields.includes(key) ? dateToIso(form[key]) : typeof form[key] === 'string' ? form[key].trim() : form[key], + ])); + payload.code = form.code || `${form.season}-${form.academicYear.replace(/[^0-9]/g, '')}`; setLoading(true); try { - const data = await api( - termId.trim() - ? `/api/academic-terms/academicTerm/${encodeURIComponent(termId.trim())}` - : "/api/academic-terms/academicTerm", - { - token, - method: termId.trim() ? "PUT" : "POST", - body: toPayload(), - } - ); - setTermId(data._id || data.code); - const next = [data, ...terms.filter((term) => term._id !== data._id && term.code !== data.code)].slice(0, 8); - window.localStorage.setItem("bobos.recentTerms", JSON.stringify(next)); - window.localStorage.setItem("bobos.lastTermId", data.code || data._id); - setMessage(`${termLabel(data)} saved.`); - notify("success", `${termLabel(data)} saved.`); + const data = await api(termId ? `/api/academic-terms/academicTerm/${encodeURIComponent(termId)}` : '/api/academic-terms/academicTerm', { + token, method: termId ? 'PUT' : 'POST', body: payload, + }); + const next = [data, ...terms.filter(term => term._id !== data._id && term.code !== data.code)]; + setTerms(next); setTermId(data._id || data.code); + setSearch(''); setFilters({ year: '', season: '', status: '' }); + window.localStorage.setItem('bobos.recentTerms', JSON.stringify(next.slice(0, 8))); + window.localStorage.setItem('bobos.lastTermId', data.code || data._id); + setEditing(false); setMessage(`${termLabel(data)} saved.`); notify('success', `${termLabel(data)} saved.`); loadTerms(); - } catch (e) { - setError(e.message); - } finally { - setLoading(false); - } - }; - - const useTerm = (term) => { - setTermId(term._id || term.code); - setForm(termToForm(term)); - setMessage(""); - setError(""); + } catch (requestError) { + setError(requestError.status === 409 + ? 'This academic year and season already exist. Edit that term or choose a different season.' + : requestError.status === 400 ? 'The term could not be saved. Check the dates and try again.' + : 'Could not save the term. Your entries are kept. Please try again.'); + } finally { setLoading(false); } }; - const standingSaved = ({ warningEmailStatus }) => { setRecordingStanding(false); - setMessage(warningEmailStatus === "sent" ? "Semester standing saved. Probation warning email sent." : "Semester standing saved."); - if (warningEmailStatus === "failed") setError("The probation warning email could not be delivered."); - if (warningEmailStatus === "pending") setMessage("Semester standing saved. The probation warning check is pending."); + const text = warningEmailStatus === 'sent' ? 'Standing saved. Probation warning email sent.' + : warningEmailStatus === 'failed' ? 'Standing saved. The probation warning email could not be sent.' + : warningEmailStatus === 'pending' ? 'Standing saved. The probation warning email is pending.' : 'Standing saved.'; + setMessage(text); notify(warningEmailStatus === 'failed' ? 'warning' : 'success', text); + }; + const dateField = (field, shortLabel) => { + const problem = visibleError(field); + const minimum = field === 'termEnd' || field === 'teachingStart' ? form.termStart + : field === 'teachingEnd' ? form.teachingStart : field === 'registrationEnd' ? form.registrationStart : ''; + return ; }; - if (role !== "administrator") { + if (role !== 'administrator') { const selectedTerm = terms.find(term => (term._id || term.code) === termId) || terms.find(term => term.isActive) || terms[0]; return
- - {error &&
{error}
} - {fetchingTerms ? : !selectedTerm ? : <> -
- -
-

Dates and deadlines

{selectedTerm.isActive ? "Active term" : "Inactive term"}
-
{Object.entries(termDateGroups).map(([label, fields]) =>
{label}
selectedTerm[field])} />
)}
-
- -
- } + + {loadError &&
{loadError}
} + {fetchingTerms && !terms.length ? : !selectedTerm ? :
+ +

Dates and deadlines

{selectedTerm.isActive ? 'Active' : 'Inactive'}
{Object.entries(termDateGroups).map(([label, fields]) =>
{label}
selectedTerm[field])} />
)}
+ +
}
; } - - return ( -
- 0 && ( - - )} - /> - {message &&
{message}
} - {error &&
{error}
} -
-
-
-
- -

{termId ? "Update term" : "Create a term"}

-
- -
-
-
- - update("academicYear", e.target.value)} - placeholder="2026/2027" - /> - - - - - -
- {Object.entries(termDateGroups).slice(0,3).map(([group, fields]) =>
{group}
- {fields.map((field) => ( - - update(field, e.target.value)} - /> - - ))} -
)} -
Scheduling deadlines
{termDateFields.slice(-2).map(field => update(field, event.target.value)} />)}
-
- - -
-
-
-
-
-
-

ACADEMIC TERMS

-

Configured terms

-
- {terms.length.toString().padStart(2, "0")} -
- {fetchingTerms ? ( - - ) : terms.length ? ( -
- {terms.map((term) => ( - - ))} -
- ) : ( - - )} - -
-
- {recordingStanding && ( - term._id === termId || term.code === termId)} - onClose={() => setRecordingStanding(false)} - onSaved={standingSaved} - /> - )} -
- ); + const years = [...new Set(terms.map(term => term.academicYear).filter(Boolean))].sort().reverse(); + const matching = terms.filter(term => (!filters.year || term.academicYear === filters.year) + && (!filters.season || term.season === filters.season) + && (!filters.status || Boolean(term.isActive) === (filters.status === 'active')) + && `${termLabel(term)} ${term.code}`.toLowerCase().includes(search.trim().toLowerCase())); + const resetFilters = () => { setSearch(''); setFilters({ year: '', season: '', status: '' }); }; + const chips = Object.entries(filters).filter(([, value]) => value).map(([key, value]) => ({ + key, label: pretty(value), onRemove: () => setFilters(current => ({ ...current, [key]: '' })), + })); + return
+ + +
} /> + {message &&
{message}
} + {loadError &&
{loadError}
} +
+ + {[['year', 'Academic year', years], ['season', 'Season', seasons], ['status', 'Status', ['active', 'inactive']]].map(([key, label, options]) => )} + +
+
+

Terms

{matching.length} of {terms.length}
+ {fetchingTerms && !terms.length ? : matching.length ? + {matching.map(term => + {term.isActive ? 'Active' : 'Inactive'} + )} + :

{terms.length ? 'No matching terms' : 'No academic terms yet'}

{terms.length ? 'Try another search or clear the filters.' : 'Add your first term to set up its dates.'}

} +
+ {viewing && setViewing(null)} wide>
{Object.entries(termDateGroups).map(([label, fields]) =>
{label}
viewing[field])} />
)}
} + {editing && { if (!loading) setEditing(false); }} wide> +
+ {attempt > 0 && Object.keys(validation).length > 0 &&
Complete {Object.keys(validation).length} highlighted {Object.keys(validation).length === 1 ? 'field' : 'fields'} before saving.
} + {error &&
{error}
} +
Term details
+ + + +
+
Date windows{[['Term', ['termStart', 'termEnd']], ['Teaching', ['teachingStart', 'teachingEnd']], ['Registration', ['registrationStart', 'registrationEnd']]].map(([label, fields]) =>

{label}

{fields.map(field => dateField(field, ''))}
)}
+
Deadlines
{dateField('advisingDeadline', 'Advising')}{dateField('wholeScheduleSwapDeadline', 'Schedule swaps')}
+
+
+
} + {recordingStanding && term._id === termId || term.code === termId) || terms.find(term => term.isActive)} onClose={() => setRecordingStanding(false)} onSaved={standingSaved} />} + ; } function TermStandingModal({ token, terms, selectedTerm, onClose, onSaved }) { const [saving, setSaving] = useState(false); const [error, setError] = useState(""); + const [fieldErrors, setFieldErrors] = useState({}); const save = async (event) => { event.preventDefault(); const form = new FormData(event.currentTarget); const term = form.get("term"); const studentId = form.get("studentId").trim(); - if (!studentId) { - setError("Enter a student ID."); + const missing = {}; + if (!term) missing.term = 'Choose an academic term.'; + if (!studentId) missing.studentId = 'Enter the student ID.'; + if (!form.get('academicStanding')) missing.academicStanding = 'Choose a standing.'; + setFieldErrors(missing); + if (Object.keys(missing).length) { + const element = event.currentTarget; + requestAnimationFrame(() => element.querySelector('[aria-invalid="true"]')?.focus()); return; } setSaving(true); @@ -468,31 +346,34 @@ function TermStandingModal({ token, terms, selectedTerm, onClose, onSaved }) { }); onSaved(result); } catch (requestError) { - setError(explainApiError(requestError, "Semester standing")); + setError(requestError.status === 404 ? 'The student or term could not be found. Check the student ID and try again.' : 'Could not save the standing. Your entries are kept. Please try again.'); } finally { setSaving(false); } }; - return !saving && onClose()}> -
+ return !saving && onClose()}> + { const name = event.target.name; setFieldErrors(current => ({ ...current, [name]: '' })); setError(''); }}> - {terms.map(term => )} + {fieldErrors.term && {fieldErrors.term}} - + + {fieldErrors.studentId && {fieldErrors.studentId}} - + {fieldErrors.academicStanding && {fieldErrors.academicStanding}} {error &&
{error}
} @@ -896,7 +777,7 @@ function SlotFields({ index, slot, onChange, onRemove, canRemove }) { function PageTitle({ eyebrow, title, description, action }) { return

{eyebrow}

{title}

{description}

{action}
; } function Field({ label, children, className = "" }) { return ; } -export function Modal({ title, eyebrow, onClose, children, wide = false }) { +export function Modal({ title, eyebrow, onClose, children, wide = false, busy = false }) { const ref = useRef(null); useLayoutEffect(() => { const dialog = ref.current; @@ -907,7 +788,7 @@ export function Modal({ title, eyebrow, onClose, children, wide = false }) { onCancel={event => { event.preventDefault(); onClose(); }} onClick={event => { if (event.target === ref.current) onClose(); }}>
-
{eyebrow &&

{eyebrow}

}

{title}

+
{eyebrow &&

{eyebrow}

}

{title}

{children}
; diff --git a/apps/web/src/components/B1Pages.jsx b/apps/web/src/components/B1Pages.jsx index f5d2ebe..fa89ebd 100644 --- a/apps/web/src/components/B1Pages.jsx +++ b/apps/web/src/components/B1Pages.jsx @@ -255,8 +255,8 @@ export function ScheduleActivityPage({ token, studentId }) { } >
- - + +
{error &&
{error}
}
diff --git a/apps/web/src/components/FilterDisclosure.jsx b/apps/web/src/components/FilterDisclosure.jsx index 9907014..96783f2 100644 --- a/apps/web/src/components/FilterDisclosure.jsx +++ b/apps/web/src/components/FilterDisclosure.jsx @@ -11,6 +11,7 @@ export default function FilterDisclosure({ search, chips = [], onClear, children useEffect(() => { if (!floating || !open) return; const outside = (event) => { + if (event.composedPath().some(node => node.classList?.contains("quiet-calendar"))) return; if (!event.composedPath().includes(root.current)) setOpen(false); }; document.addEventListener("pointerdown", outside, true); diff --git a/apps/web/src/components/FinancialRecordsPage.jsx b/apps/web/src/components/FinancialRecordsPage.jsx index 4b0385d..5039f2e 100644 --- a/apps/web/src/components/FinancialRecordsPage.jsx +++ b/apps/web/src/components/FinancialRecordsPage.jsx @@ -353,11 +353,11 @@ export default function FinancialRecordsPage({ token, role, notify }) { const dateFields = <> ; return ( diff --git a/apps/web/src/components/GraduationReview.jsx b/apps/web/src/components/GraduationReview.jsx index 40a8468..4cc06f5 100644 --- a/apps/web/src/components/GraduationReview.jsx +++ b/apps/web/src/components/GraduationReview.jsx @@ -173,11 +173,11 @@ export default function GraduationReview({ token, role }) { diff --git a/apps/web/src/components/MandatoryRemovalDashboard.jsx b/apps/web/src/components/MandatoryRemovalDashboard.jsx index bf3705b..7dbdfe8 100644 --- a/apps/web/src/components/MandatoryRemovalDashboard.jsx +++ b/apps/web/src/components/MandatoryRemovalDashboard.jsx @@ -277,6 +277,7 @@ export default function MandatoryRemovalDashboard({ token, role, notify }) { setDateFrom(e.target.value)} /> @@ -287,6 +288,7 @@ export default function MandatoryRemovalDashboard({ token, role, notify }) { setDateTo(e.target.value)} /> diff --git a/apps/web/src/components/SlotChangesPage.jsx b/apps/web/src/components/SlotChangesPage.jsx index 2332fb7..0e2cfbb 100644 --- a/apps/web/src/components/SlotChangesPage.jsx +++ b/apps/web/src/components/SlotChangesPage.jsx @@ -165,8 +165,8 @@ export default function SlotChangesPage({ token, role, onOpenSchedule }) { - - + + } {shown.length ? mine ?
diff --git a/apps/web/src/portal-academic.css b/apps/web/src/portal-academic.css index f838ab5..e722c77 100644 --- a/apps/web/src/portal-academic.css +++ b/apps/web/src/portal-academic.css @@ -1112,3 +1112,118 @@ .academic-services-embedded .template-row-actions { grid-column:1/-1; } .academic-services-embedded .template-row-actions :is(.outline-button,.paper-toss-button) { min-height:44px; } } + +/* Academic terms: browse first, edit only when needed. */ +.academic-services-embedded .terms-manager { gap:24px; } +.academic-services-embedded .terms-header-actions { display:flex; align-items:center; gap:10px; flex-wrap:wrap; } +.academic-services-embedded .terms-manager .page-description { max-width:48ch; } +.academic-services-embedded .terms-search { width:min(100%,360px); } +.academic-services-embedded .terms-filters { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:18px; max-width:760px; } +.academic-services-embedded .terms-results-heading { display:flex; align-items:center; justify-content:space-between; gap:16px; margin-bottom:14px; } +.academic-services-embedded .terms-results-heading h2 { font-size:18px; font-weight:500; margin:0; } +.academic-services-embedded .terms-results-heading>span { color:var(--muted); font-size:13px; } +.academic-services-embedded .terms-table table { width:100%; } +.academic-services-embedded .terms-table td { vertical-align:middle; } +.academic-services-embedded .terms-manager .terms-table :is(th,td) { padding-inline:16px; } +.academic-services-embedded .terms-table td:nth-child(2) { font-variant-numeric:tabular-nums; } +.academic-services-embedded .term-name { display:flex; align-items:center; gap:14px; border:0; padding:3px 0; color:var(--ink); background:transparent; text-align:start; cursor:pointer; } +.academic-services-embedded .term-name strong { display:block; font-size:15px; font-weight:550; } +.academic-services-embedded .term-name small { display:block; font-size:12px; color:var(--muted); margin-top:4px; } +.academic-services-embedded .term-name:hover strong { text-decoration:underline; text-underline-offset:4px; } +.academic-services-embedded .term-name .term-calendar-mark { width:36px; height:40px; flex:none; display:grid; place-items:center; background:#e8e0c8; border-top:6px solid #a8b9a5; border-radius:4px; color:#443d31; font-size:18px; } +.academic-services-embedded .terms-empty { display:grid; justify-items:center; gap:10px; padding:42px 20px; text-align:center; } +.academic-services-embedded .terms-empty h3 { margin:4px 0 0; font-size:17px; } +.academic-services-embedded .terms-empty p { color:var(--muted); font-size:14px; margin:0 0 7px; } +.academic-services-embedded .terms-load-error { display:flex; justify-content:space-between; align-items:center; gap:16px; } +.academic-services-embedded .term-editor { display:grid; gap:22px; } +.academic-services-embedded .term-editor-note { color:var(--muted); font-size:12px; margin:0; } +.academic-services-embedded .term-editor fieldset { min-width:0; margin:0; padding:0; border:0; } +.academic-services-embedded .term-editor legend { color:var(--ink); font-size:15px; font-weight:550; padding:0; margin-bottom:12px; } +.academic-services-embedded .term-identity-fields { display:grid; grid-template-columns:1fr 1fr auto; align-items:start; gap:16px; } +.academic-services-embedded .term-identity-fields .check-field { margin-top:33px; white-space:nowrap; } +.academic-services-embedded .term-editor-dates { display:grid; grid-template-columns:1fr 1fr; align-items:start; gap:24px; padding-top:20px; border-top:1px solid var(--line); } +.academic-services-embedded .term-date-fields { display:grid; grid-template-columns:1fr 1fr; align-items:start; gap:12px; } +.academic-services-embedded .term-editor .field>span { font-size:12px; color:var(--muted); } +.academic-services-embedded .term-editor input { min-width:0; width:100%; } +.academic-services-embedded .term-editor input[type=checkbox] { width:auto; } +.academic-services-embedded .term-field-error { display:block; font-size:12px; line-height:1.45; color:#e5ad9a; font-weight:400; margin-top:5px; } +.academic-services-embedded .term-editor [aria-invalid=true],.academic-services-embedded .term-standing-form [aria-invalid=true] { border-color:#c78d7b; } +.academic-services-embedded .term-validation-summary { padding:10px 13px; border-left:3px solid #c78d7b; background:color-mix(in srgb,var(--paper) 92%,#c78d7b); color:var(--ink); font-size:13px; } +.academic-services-embedded .term-editor .form-footer { margin-top:0; padding-top:18px; border-top:1px solid var(--line); } +.academic-services-embedded .terms-detail-layout { display:grid; grid-template-columns:minmax(0,1fr) 280px; gap:28px; align-items:start; } +.academic-services-embedded .terms-detail-dates { margin:0; } +.academic-services-embedded .terms-detail-dates>div { padding:13px 0; border-bottom:1px solid var(--line); } +.academic-services-embedded .terms-detail-dates dt { font-size:12px; color:var(--muted); margin-bottom:7px; } +.academic-services-embedded .terms-detail-dates dd { margin:0; font-size:15px; color:var(--ink); font-variant-numeric:tabular-nums; } +.service-surface[data-theme=light] .term-field-error { color:#94452f; } +@media(max-width:760px) { + .academic-services-embedded .term-editor-dates { grid-template-columns:1fr; } + .academic-services-embedded .terms-detail-layout { grid-template-columns:1fr; } + .academic-services-embedded .terms-detail-layout .term-calendar { max-width:300px; } +} +@media(max-width:540px) { + .academic-services-embedded .terms-manager .terms-table table { display:block; min-width:0; width:100%; } + .academic-services-embedded .terms-manager .terms-table thead { display:none; } + .academic-services-embedded .terms-manager .terms-table tbody { display:block; } + .academic-services-embedded .terms-manager .terms-table tr { display:grid; grid-template: "identity actions" auto "dates status" auto / minmax(0,1fr) auto; gap:12px; padding:16px; border-bottom:1px solid var(--line); } + .academic-services-embedded .terms-manager .terms-table tr:last-child { border-bottom:0; } + .academic-services-embedded .terms-manager .terms-table td { display:block; position:static; padding:0; min-width:0; border:0; background:transparent; } + .academic-services-embedded .terms-manager .terms-table td:nth-child(1) { grid-area:identity; } + .academic-services-embedded .terms-manager .terms-table td:nth-child(2) { grid-area:dates; align-self:center; font-size:13px; line-height:1.5; } + .academic-services-embedded .terms-manager .terms-table td:nth-child(3) { grid-area:status; justify-self:end; align-self:center; } + .academic-services-embedded .terms-manager .terms-table td:nth-child(4) { grid-area:actions; justify-self:end; align-self:center; } + .academic-services-embedded .terms-manager .terms-table .status-pill { font-size:12px; gap:6px; } + .academic-services-embedded .terms-manager .terms-table .status-pill::before { width:16px; height:16px; } + .academic-services-embedded .terms-manager .terms-table .term-name { gap:10px; } + .academic-services-embedded .terms-manager .terms-table .term-name strong { font-size:14px; } + .academic-services-embedded .terms-filters { grid-template-columns:1fr; } + .academic-services-embedded .term-identity-fields { grid-template-columns:1fr 1fr; } + .academic-services-embedded .term-identity-fields .check-field { grid-column:1/-1; margin-top:0; } + .academic-services-embedded .terms-manager .page-title-row { align-items:flex-start; } + .academic-services-embedded .terms-header-actions { width:100%; } + .academic-services-embedded .terms-header-actions button { flex:1; } +} + +.academic-services-embedded .terms-toolbar { display:grid; grid-template-columns:minmax(200px,1.65fr) repeat(3,minmax(125px,1fr)) auto; align-items:end; gap:16px; padding:18px; border:1px solid var(--line); border-radius:10px; background:var(--paper); } +.academic-services-embedded .terms-toolbar .field { margin:0; min-width:0; } +.academic-services-embedded .terms-toolbar .field>span { font-size:12px; color:var(--muted); } +.academic-services-embedded .terms-clear { min-height:42px; padding-inline:8px; } +.academic-services-embedded .terms-results-heading>div { display:flex; align-items:baseline; gap:12px; } +.academic-services-embedded .terms-results-heading>div>span { color:var(--muted); font-size:13px; } +.academic-services-embedded .terms-table table { table-layout:fixed; } +.academic-services-embedded .terms-table th:first-child { width:34%; } +.academic-services-embedded .terms-table th:nth-child(2),.academic-services-embedded .terms-table th:nth-child(3) { width:18%; } +.academic-services-embedded .terms-table th:nth-child(4) { width:18%; } +.academic-services-embedded .terms-table th:last-child { width:12%; } +.academic-services-embedded .terms-manager .terms-table :is(th,td):last-child { text-align:end; } +.academic-services-embedded .term-editor .term-window-group { padding-block:18px; border-block:1px solid var(--line); } +.academic-services-embedded .term-window-labels,.academic-services-embedded .term-window-row { display:grid; grid-template-columns:105px minmax(0,1fr) minmax(0,1fr); align-items:start; gap:14px; } +.academic-services-embedded .term-window-labels { color:var(--muted); font-size:12px; margin-bottom:9px; } +.academic-services-embedded .term-window-row+.term-window-row { margin-top:14px; } +.academic-services-embedded .term-window-row h3 { align-self:center; margin:0; font-size:14px; font-weight:500; } +.academic-services-embedded .term-window-row .field { margin:0; } +.service-surface[data-service=terms] .academic-services-embedded .modal-card.wide-modal:has(.term-editor) { width:min(760px,100%); } +@media(max-width:1000px) { + .academic-services-embedded .terms-toolbar { grid-template-columns:repeat(3,minmax(0,1fr)); } + .academic-services-embedded .terms-toolbar>.field:first-child { grid-column:1/3; } + .academic-services-embedded .terms-toolbar>.field:nth-child(2) { grid-column:3; } +} +@media(max-width:540px) { + .academic-services-embedded .terms-toolbar { grid-template-columns:1fr 1fr; gap:14px; padding:14px; } + .academic-services-embedded .terms-toolbar>.field:first-child { grid-column:1/-1; } + .academic-services-embedded .terms-toolbar>.field:nth-child(2) { grid-column:auto; } + .academic-services-embedded .terms-clear { justify-self:start; } + .academic-services-embedded .terms-results-heading { gap:12px; } + .academic-services-embedded .terms-results-heading>div { gap:8px; } + .academic-services-embedded .terms-results-heading>div>span { font-size:12px; } + .academic-services-embedded .term-window-labels { grid-template-columns:75px minmax(0,1fr) minmax(0,1fr); gap:8px; } + .academic-services-embedded .term-window-row { grid-template-columns:75px minmax(0,1fr) minmax(0,1fr); gap:8px; } + .academic-services-embedded .term-window-row h3 { font-size:12px; } + .academic-services-embedded .term-window-row input { padding-inline:5px; font-size:12px; } + .academic-services-embedded .terms-manager .terms-table tr { grid-template: "identity actions" auto "start end" auto "status status" auto / minmax(0,1fr) auto; } + .academic-services-embedded .terms-manager .terms-table td:nth-child(2) { grid-area:start; } + .academic-services-embedded .terms-manager .terms-table td:nth-child(3) { grid-area:end; justify-self:start; font-size:13px; } + .academic-services-embedded .terms-manager .terms-table td:nth-child(4) { grid-area:status; justify-self:start; } + .academic-services-embedded .terms-manager .terms-table td:nth-child(5) { grid-area:actions; justify-self:end; } + .academic-services-embedded .terms-table td[data-label]::before { content:attr(data-label); display:block; color:var(--muted); font-size:11px; margin-bottom:4px; } +} diff --git a/apps/web/src/portal-services.jsx b/apps/web/src/portal-services.jsx index f985627..d5781f0 100644 --- a/apps/web/src/portal-services.jsx +++ b/apps/web/src/portal-services.jsx @@ -1,6 +1,7 @@ import "@vitejs/plugin-react/preamble"; import React from "react"; import { createRoot } from "react-dom/client"; +import { flushSync } from "react-dom"; import App from "./App.jsx"; import baseStyles from "./style.css?inline"; import workspaceStyles from "./workspace-polish.css?inline"; @@ -84,12 +85,14 @@ export function mount(host) { observer.observe(document.documentElement, { attributeFilter: ["data-theme"] }); host.replaceChildren(); shadow.append(style, surface); + const disposeCalendar = window.BobosCalendar?.mount(shadow, { commit: flushSync }); const disposeInk = window.mountPortalControlInk?.(shadow, { coordinator: surface.dataset.portalRole === "coordinator" }); const root = createRoot(surface); root.render(); return () => { observer.disconnect(); disposeInk?.(); + disposeCalendar?.(); root.unmount(); }; } diff --git a/apps/web/src/term-validation.js b/apps/web/src/term-validation.js new file mode 100644 index 0000000..f7aa743 --- /dev/null +++ b/apps/web/src/term-validation.js @@ -0,0 +1,28 @@ +export const termFieldLabels = { + academicYear: 'Academic year', season: 'Season', termStart: 'Term start', termEnd: 'Term end', + teachingStart: 'Teaching start', teachingEnd: 'Teaching end', registrationStart: 'Registration start', + registrationEnd: 'Registration end', advisingDeadline: 'Advising deadline', wholeScheduleSwapDeadline: 'Whole-schedule swap deadline', +}; + +export function validateAcademicTerm(form) { + const errors = {}; + const missingDate = { termStart: 'Choose when the term starts.', termEnd: 'Choose when the term ends.', teachingStart: 'Choose when teaching starts.', teachingEnd: 'Choose when teaching ends.', registrationStart: 'Choose when registration opens.', registrationEnd: 'Choose when registration closes.', advisingDeadline: 'Choose the advising deadline.', wholeScheduleSwapDeadline: 'Choose the schedule-swap deadline.' }; + for (const [field, label] of Object.entries(termFieldLabels)) { + if (!String(form[field] || '').trim()) errors[field] = field === 'season' ? 'Choose a season.' : field === 'academicYear' ? 'Enter the academic year.' : missingDate[field]; + } + if (form.academicYear?.trim() && !/^\d{4}\/\d{4}$/.test(form.academicYear.trim())) errors.academicYear = 'Use YYYY/YYYY, for example 2026/2027.'; + for (const field of Object.keys(termFieldLabels).filter(key => !['academicYear', 'season'].includes(key))) { + if (!form[field]) continue; + const value = String(form[field]); + const parsed = new Date(value + 'T12:00:00Z'); + if (!/^\d{4}-\d{2}-\d{2}$/.test(value) || !Number.isFinite(parsed.getTime()) || parsed.toISOString().slice(0, 10) !== value) errors[field] = 'Choose a valid date.'; + } + for (const [start, end, message] of [ + ['termStart', 'termEnd', 'Term end must be on or after term start.'], + ['teachingStart', 'teachingEnd', 'Teaching end must be on or after teaching start.'], + ['registrationStart', 'registrationEnd', 'Registration end must be on or after registration start.'], + ]) if (form[start] && form[end] && !errors[start] && !errors[end] && form[start] > form[end]) errors[end] = message; + if (form.teachingStart && form.termStart && !errors.teachingStart && !errors.termStart && form.teachingStart < form.termStart) errors.teachingStart = 'Teaching must start on or after term start.'; + if (form.teachingEnd && form.termEnd && !errors.teachingEnd && !errors.termEnd && form.teachingEnd > form.termEnd) errors.teachingEnd = 'Teaching must end on or before term end.'; + return errors; +} diff --git a/apps/web/src/term-validation.test.js b/apps/web/src/term-validation.test.js new file mode 100644 index 0000000..57b2bd0 --- /dev/null +++ b/apps/web/src/term-validation.test.js @@ -0,0 +1,25 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { validateAcademicTerm } from './term-validation.js'; +const valid = { academicYear: '2026/2027', season: 'spring', termStart: '2027-02-01', termEnd: '2027-07-01', teachingStart: '2027-02-07', teachingEnd: '2027-06-20', registrationStart: '2027-01-01', registrationEnd: '2027-01-25', advisingDeadline: '2027-02-06', wholeScheduleSwapDeadline: '2027-02-10' }; +test('Academic terms: missing entries receive individual actionable messages', () => { + const errors = validateAcademicTerm({}); + assert.equal(Object.keys(errors).length, 10); + assert.equal(errors.academicYear, 'Enter the academic year.'); + assert.equal(errors.advisingDeadline, 'Choose the advising deadline.'); + assert.equal(errors.season, 'Choose a season.'); +}); +test('Academic terms: valid dates allow registration before the term and either active state', () => { + assert.deepEqual(validateAcademicTerm({ ...valid, isActive: false }), {}); + assert.deepEqual(validateAcademicTerm({ ...valid, isActive: true }), {}); +}); +test('Academic terms: ordering feedback identifies the affected field', () => { + assert.equal(validateAcademicTerm({ ...valid, termEnd: '2027-01-01' }).termEnd, 'Term end must be on or after term start.'); + assert.equal(validateAcademicTerm({ ...valid, teachingStart: '2027-01-20' }).teachingStart, 'Teaching must start on or after term start.'); + assert.equal(validateAcademicTerm({ ...valid, teachingEnd: '2027-08-01' }).teachingEnd, 'Teaching must end on or before term end.'); + assert.equal(validateAcademicTerm({ ...valid, registrationEnd: '2026-12-20' }).registrationEnd, 'Registration end must be on or after registration start.'); +}); +test('Academic terms: malformed years and impossible dates do not submit', () => { + assert.match(validateAcademicTerm({ ...valid, academicYear: '2027' }).academicYear, /YYYY\/YYYY/); + assert.equal(validateAcademicTerm({ ...valid, termStart: '2027-02-30' }).termStart, 'Choose a valid date.'); +}); diff --git a/apps/web/vite.config.js b/apps/web/vite.config.js index 08b3173..ef55579 100644 --- a/apps/web/vite.config.js +++ b/apps/web/vite.config.js @@ -107,7 +107,7 @@ function portalSite() { for (const page of htmlEntries) { const file = join(out, page); const html = readFileSync(file, "utf8").replace(/(src|href)="([^"?]+\.(?:js|css))(?:\?[^"]*)?"/g, (original, attr, url) => { - const path = url.startsWith("/") ? url.slice(1) : join(dirname(page), url); + const path = (url.startsWith("/") ? url.slice(1) : join(dirname(page), url)).replaceAll("\\", "/"); if (!path.startsWith("portal-studio/")) return original; return `${attr}="/${fingerprint(path)}"`; }); diff --git a/docs/portal-design-system.md b/docs/portal-design-system.md index df28d2b..b4829ab 100644 --- a/docs/portal-design-system.md +++ b/docs/portal-design-system.md @@ -1,5 +1,17 @@ # Portal design system +Academic terms keeps search, Academic year, Season, Status and Clear together in one visible filter bar; omit Refresh. Create term is the page's primary action, with Record standing beside the register heading. Give Starts and Ends separate table columns. In the editor, Term details comes first, then a Date windows register with one shared Starts/Ends header for Term, Teaching and Registration, followed by Deadlines. Use Create term for creation and Save changes for editing. Preserve inline validation, failed-save entries and mobile stacked records. + +Academic terms is a browse-first register. Keep search visible and group Academic year, Season and Status under Filters. New term and Edit open a compact editor with Term information, Term, Teaching, Registration and Deadlines groups; use Starts/Ends within date windows instead of repeating the full field names. Term names open a read-only date summary and calendar. Keep required and date-order feedback beside its field, connect it with aria-describedby, focus the first invalid field after Save, and keep entries on failed requests. Duplicate terms explain how to resolve the conflict. Record standing uses the same field-level feedback; distinguish a saved standing from a failed warning email. Preserve administrator-only write access and read-only term views for other roles. + +Empty notifications use the approved coffee-break illustration (concept 7): a ceramic cup, brass desk bell and a letter lying flat beneath the saucer with an opaque turned corner. The cup and bell stay anchored while two steam curls rise once on arrival and hover; reduced motion keeps the resting pose. Reuse the `coffee` scene in `notification-scenes.js` for every role's empty Notifications view and the empty overview inbox. Keep the pneumatic scene for unread messages and preserve the loading, error and notification-read behavior. + +Clicking the Calendar's month/year heading opens a compact month chooser with an editable year and previous/next-year controls. A month selection returns to the day grid without committing a date. Honor the source field's date bounds in both chooser views. The live picker version is exposed as `BobosCalendar.version` to verify that an open browser tab has loaded the current script. + +The picker is titled Calendar and uses a compact single-column month view without a selected-date summary sidebar. Range and time controls, where applicable, sit beneath the month grid. All date and date-time inputs use the shared Calendar in `quiet-calendar.js` and `quiet-calendar.css`. It mounts on the document and embedded service shadow roots through `portal-services.jsx`, retaining native field values, form validation and existing change handlers. Paired filter inputs use `data-calendar-range` and `data-calendar-edge` for one range picker; individual term fields remain single-date selections. Changes stay in the picker until Apply; Cancel, outside click and Escape discard them and restore focus. Keep date-only APIs date-only. Time controls/presets appear only for datetime-local fields and retain the field's timezone meaning. Preserve min/max, required/read-only/disabled states, keyboard day/month navigation, light/dark themes and narrow-screen containment. Calendar interaction must not dismiss an enclosing filter panel. + +Keep the left navigation at its current scroll position when switching pages or using browser Back/Forward within the same role. Preserve both the navigation's scroll container and the outer sidebar when rebuilding the Portal shell, without scrolling the focused main content into view. + DMET 501 uses a complete open clapperboard with aligned slate stripes, a play mark and an opaque foreground gear in `images/symbols/media-engineering.svg`. Keep the full drawing inside its viewBox and hide board edges behind the gear. German courses use `german-language.svg`: an open book with a vector-drawn umlauted A. Keep the generic `languages-book.svg` for the other language courses. The CSEN 905–909 and DMET 905–909 electives each have a dedicated subject drawing in the shared `course-icons.js` registry: a robot reading with a learning-check bubble, cloud servers, document search, security key, parallel workers, game controller, VR headset, screen interaction, 3D mesh and interactive media. Use the shared identities throughout course lists and schedules. diff --git a/tests/browser/portal.spec.mjs b/tests/browser/portal.spec.mjs index 68c754f..a68ef08 100644 --- a/tests/browser/portal.spec.mjs +++ b/tests/browser/portal.spec.mjs @@ -84,6 +84,38 @@ async function signIn(page, account, pass) { await page.getByRole("button", { name: /continue/i }).click(); } +test("Sidebar keeps lower navigation links in place across page changes and history", async ({ page }) => { + await page.setViewportSize({ width: 1100, height: 420 }); + await page.goto(baseURL); + await signIn(page, "regression@guc.edu.eg", password); + const navigation = page.getByRole("navigation", { name: "Main navigation" }); + const sidebar = page.locator('.sidebar'); + const position = await sidebar.evaluate(side => { + side.scrollTop = side.scrollHeight; + const nav = side.querySelector('nav'); + nav.scrollTop = nav.scrollHeight; + return { sidebar: side.scrollTop, navigation: nav.scrollTop }; + }); + expect(position.sidebar + position.navigation).toBeGreaterThan(0); + const expectPosition = async () => { + await expect.poll(() => sidebar.evaluate(side => ({ + sidebar: side.scrollTop, navigation: side.querySelector('nav').scrollTop, + }))).toEqual(position); + }; + await navigation.locator('[data-page="terms"]').click(); + await expect(page).toHaveURL(/page=terms/); + await expectPosition(); + await navigation.locator('[data-page="group-assignments"]').click(); + await expect(page).toHaveURL(/page=group-assignments/); + await expectPosition(); + await page.goBack(); + await expect(page).toHaveURL(/page=terms/); + await expectPosition(); + await page.goForward(); + await expect(page).toHaveURL(/page=group-assignments/); + await expectPosition(); +}); + test("Req 1–5: reset through email, view your profile and inbox, and sign out", async ({ page }) => { await page.goto(baseURL); await page.getByRole("link", { name: /forgot password/i }).click(); @@ -180,6 +212,98 @@ test("Req 6–10: student directory finds the matching profile and changes the a await expect(details.getByRole("button", { name: "Deactivate account" })).toBeVisible(); }); +test("Academic terms group browsing and editing, validate fields and retain failed saves", async ({ page }) => { + test.setTimeout(90_000); + const response = await page.request.post(baseURL + '/api/identity/login', { data: { email: 'regression@guc.edu.eg', password } }); + const session = await response.json(); + await page.addInitScript(token => { localStorage.setItem('bobos.token', token); localStorage.setItem('portal-account-role', 'administrator'); }, session.token); + await page.goto(baseURL + '/portal-studio/index.html?page=terms&role=administrator&preview=live'); + await expect(page.getByRole('dialog')).toHaveCount(0); + await page.getByRole('button', { name: 'Create term', exact: true }).first().click(); + const form = page.getByRole('dialog', { name: 'Create term', exact: true }); + await form.getByRole('button', { name: 'Create term', exact: true }).click(); + await expect(form.getByRole('alert')).toHaveText('Complete 8 highlighted fields before saving.'); + await expect(form.getByLabel('Term start', { exact: true })).toBeFocused(); + const values = { termStart: '2093-02-01', termEnd: '2093-07-01', teachingStart: '2093-02-07', teachingEnd: '2093-06-20', registrationStart: '2093-01-01', registrationEnd: '2093-01-25', advisingDeadline: '2093-02-06', wholeScheduleSwapDeadline: '2093-02-10' }; + await form.getByLabel('Academic year', { exact: true }).fill('2093/2094'); + for (const [name, value] of Object.entries(values)) await form.locator(`input[name="${name}"]`).fill(value); + await form.getByLabel('Teaching end', { exact: true }).fill('2093-08-01'); + await form.getByRole('button', { name: 'Create term', exact: true }).click(); + await expect(form.getByText('Teaching must end on or before term end.', { exact: true })).toBeVisible(); + await form.getByLabel('Teaching end', { exact: true }).fill(values.teachingEnd); + const endpoint = '**/api/academic-terms/academicTerm'; + await page.route(endpoint, route => route.request().method() === 'POST' ? route.fulfill({status:503,json:{message:'Unavailable'}}) : route.continue()); + await form.getByRole('button', { name: 'Create term', exact: true }).click(); + await expect(form.getByRole('alert')).toHaveText('Could not save the term. Your entries are kept. Please try again.'); + await expect(form.getByLabel('Term start', { exact: true })).toHaveValue(values.termStart); + await page.unroute(endpoint); + await page.route(endpoint, route => route.request().method() === 'POST' ? route.fulfill({status:409,json:{message:'Already exists'}}) : route.continue()); + await form.getByRole('button', { name: 'Create term', exact: true }).click(); + await expect(form.getByRole('alert')).toHaveText('This academic year and season already exist. Edit that term or choose a different season.'); + await page.unroute(endpoint); + await form.getByRole('button', { name: 'Create term', exact: true }).click(); + await expect(form).toHaveCount(0); + const register = page.getByRole('table', { name: 'Academic terms', exact: true }); + await expect(register.getByRole('row', { name: /Spring 2093\/2094/ })).toBeVisible(); + await page.getByLabel('Find a term').fill('no-such-term'); + await expect(page.getByRole('heading', { name: 'No matching terms' })).toBeVisible(); + await page.getByRole('button', { name: 'Clear filters', exact: true }).click(); + await page.getByLabel('Status', { exact: true }).selectOption('active'); + await expect(register.getByRole('row', { name: /Spring 2093\/2094/ })).toHaveCount(0); + await page.getByRole('button', { name: 'Clear filters', exact: true }).click(); + await register.getByRole('button', { name: 'Edit Spring 2093/2094', exact: true }).click(); + const edit = page.getByRole('dialog', { name: 'Edit term', exact: true }); + await expect(edit.getByLabel('Term start', { exact: true })).toHaveValue(values.termStart); + await edit.getByLabel('Academic year', { exact: true }).fill('2095/2096'); + await edit.getByRole('button', { name: 'Save changes', exact: true }).click(); + await expect(edit).toHaveCount(0); + await expect(register.getByRole('row', { name: /Spring 2095\/2096/ })).toBeVisible(); + await page.getByRole('button', { name: 'Record standing', exact: true }).click(); + const standing = page.getByRole('dialog', { name: 'Record semester standing' }); + await standing.getByRole('button', { name: /Save standing/ }).click(); + await expect(standing.getByText('Enter the student ID.', { exact: true })).toBeVisible(); + await expect(standing.getByText('Choose a standing.', { exact: true })).toBeVisible(); + await expect(standing.getByLabel('Student ID', { exact: true })).toBeFocused(); + await standing.getByRole('button', { name: 'Cancel', exact: true }).click(); + await page.setViewportSize({width:390,height:844}); + expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBeTruthy(); + const dates = register.locator('td:nth-child(2)').first(); + expect((await dates.boundingBox()).height).toBeLessThan(50); +}); + +test("Calendar commits both controlled financial filters and Cancel preserves them", async ({ page }) => { + const response = await page.request.post(baseURL + '/api/identity/login', { + data: { email: 'regression@guc.edu.eg', password }, + }); + expect(response.ok()).toBeTruthy(); + const session = await response.json(); + await page.addInitScript(token => { + localStorage.setItem('bobos.token', token); + localStorage.setItem('portal-account-role', 'administrator'); + }, session.token); + await page.goto(baseURL + '/portal-studio/index.html?page=financial-records&role=administrator&preview=live'); + const from = page.getByLabel("From date"); + const through = page.getByLabel("To date"); + await from.fill("2025-09-10"); + await from.click(); + const calendar = page.getByRole("dialog", { name: "Calendar" }); + await calendar.getByRole("gridcell", { name: "Monday, September 15, 2025", exact: true }).click(); + await calendar.getByRole("gridcell", { name: "Wednesday, September 17, 2025", exact: true }).click(); + const filtered = page.waitForResponse(response => { + const url = new URL(response.url()); + return url.pathname === '/api/finance/records' && url.searchParams.get('startDate') === '2025-09-15' && url.searchParams.get('endDate') === '2025-09-17'; + }); + await calendar.getByRole("button", { name: "Apply", exact: true }).click(); + await filtered; + await expect(from).toHaveValue("2025-09-15"); + await expect(through).toHaveValue("2025-09-17"); + await from.click(); + await calendar.getByRole("gridcell", { name: "Friday, September 19, 2025", exact: true }).click(); + await calendar.getByRole("button", { name: "Cancel", exact: true }).click(); + await expect(from).toHaveValue("2025-09-15"); + await expect(through).toHaveValue("2025-09-17"); +}); + test("Req 100 and 127: the Portal ledger and downloaded CSV use the same date and settlement filters", async ({ page }) => { await FinancialTransaction.create([ { student: regressionStudent._id, settlementOption: "wallet", transactionReference: "AUDIT-MATCH", occurredAt: "2025-09-15T12:00:00Z" }, diff --git a/tests/browser/quiet-calendar.spec.mjs b/tests/browser/quiet-calendar.spec.mjs new file mode 100644 index 0000000..4094274 --- /dev/null +++ b/tests/browser/quiet-calendar.spec.mjs @@ -0,0 +1,102 @@ +import { once } from 'node:events'; +import { fileURLToPath } from 'node:url'; +import express from 'express'; +import { test, expect } from '@playwright/test'; + +let server, url; +test.beforeAll(async () => { + const app = express(); + app.use(express.static(fileURLToPath(new URL('../../apps/web/public/portal-studio', import.meta.url)))); + app.get('/fixture', (_req, res) => res.send(` + + + + + + `)); + server = app.listen(0, '127.0.0.1'); + await once(server, 'listening'); + url = `http://127.0.0.1:${server.address().port}/fixture`; +}); +test.afterAll(async () => { if (server) await new Promise(resolve => server.close(resolve)); }); + +test('Calendar: single-date bounds, keyboard selection, Cancel and focus restoration', async ({ page }) => { + await page.goto(url); + const field = page.getByLabel('Single date', { exact: true }); + await field.click(); + const picker = page.getByRole('dialog', { name: 'Calendar' }); + await expect(picker.getByRole('heading', { name: 'Calendar', exact: true })).toBeVisible(); + await expect(picker.locator('.quiet-calendar-selection')).toHaveCount(0); + expect((await picker.boundingBox()).width).toBeLessThanOrEqual(420); + await expect(picker.getByRole('gridcell', { name: 'Sunday, March 2, 2025', exact: true })).toBeDisabled(); + await expect(picker.getByRole('button', { name: 'Clear', exact: true })).toBeDisabled(); + await picker.getByRole('gridcell', { name: 'Wednesday, March 12, 2025', exact: true }).click(); + await picker.getByRole('button', { name: 'Cancel', exact: true }).click(); + await expect(field).toHaveValue('2025-03-10'); + await expect(field).toBeFocused(); + await field.press('Alt+ArrowDown'); + await picker.getByRole('gridcell', { name: 'Monday, March 10, 2025', exact: true }).press('ArrowRight'); + await page.keyboard.press('Enter'); + await picker.getByRole('button', { name: 'Apply', exact: true }).click(); + await expect(field).toHaveValue('2025-03-11'); + await expect(field).toBeFocused(); + expect(await page.evaluate(() => window.changes)).toEqual(['2025-03-11']); +}); + +test('Calendar: ranges extend beyond the previous end, commit together and clear', async ({ page }) => { + await page.goto(url); + await page.getByLabel('End', { exact: true }).click(); + const picker = page.getByRole('dialog', { name: 'Calendar' }); + await picker.getByRole('gridcell', { name: 'Thursday, March 20, 2025', exact: true }).click(); + await picker.getByRole('button', { name: 'Start date', exact: true }).click(); + await picker.getByRole('gridcell', { name: 'Saturday, March 15, 2025', exact: true }).click(); + await expect(page.getByLabel('Start', { exact: true })).toHaveValue('2025-03-10'); + await picker.getByRole('button', { name: 'Apply', exact: true }).click(); + await expect(page.getByLabel('Start', { exact: true })).toHaveValue('2025-03-15'); + await expect(page.getByLabel('End', { exact: true })).toHaveValue('2025-03-20'); + await page.getByLabel('Start', { exact: true }).click(); + await picker.getByRole('button', { name: 'Clear', exact: true }).click(); + await picker.getByRole('button', { name: 'Apply', exact: true }).click(); + await expect(page.getByLabel('Start', { exact: true })).toHaveValue(''); + await expect(page.getByLabel('End', { exact: true })).toHaveValue(''); +}); + +test('Calendar: time presets, month navigation, Escape and mobile containment', async ({ page }) => { + await page.setViewportSize({ width: 390, height: 844 }); + await page.goto(url); + await page.getByLabel('Start time', { exact: true }).click(); + const picker = page.getByRole('dialog', { name: 'Calendar' }); + await picker.getByRole('button', { name: 'Next month' }).click(); + await expect(picker.getByRole('heading', { name: 'April 2025' })).toBeVisible(); + await picker.getByRole('button', { name: 'Previous month' }).click(); + await picker.getByRole('button', { name: '00:00 – 12:00', exact: true }).click(); + await picker.getByRole('button', { name: 'Apply', exact: true }).click(); + await expect(page.getByLabel('Start time', { exact: true })).toHaveValue('2025-03-10T00:00'); + await expect(page.getByLabel('End time', { exact: true })).toHaveValue('2025-03-14T12:00'); + await page.getByLabel('Start time', { exact: true }).click(); + const bounds = await picker.boundingBox(); + expect(bounds.x).toBeGreaterThanOrEqual(0); + expect(bounds.x + bounds.width).toBeLessThanOrEqual(390); + await page.keyboard.press('Escape'); + await expect(picker).toHaveCount(0); +}); + +test('Calendar: heading opens direct month and year selection without applying a date', async ({ page }) => { + await page.goto(url); + const start = page.getByLabel('Start', { exact: true }); + await start.click(); + const picker = page.getByRole('dialog', { name: 'Calendar' }); + await picker.getByRole('button', { name: 'Choose month and year' }).click(); + await picker.getByRole('spinbutton', { name: 'Year', exact: true }).fill('2032'); + await picker.getByRole('button', { name: 'Feb', exact: true }).click(); + await expect(picker.getByRole('heading', { name: 'February 2032' })).toBeVisible(); + await expect(picker.getByRole('gridcell', { name: /February 29, 2032/ })).toBeVisible(); + await expect(start).toHaveValue('2025-03-10'); + await picker.getByRole('button', { name: 'Cancel', exact: true }).click(); + await expect(start).toHaveValue('2025-03-10'); + await page.getByLabel('Single date', { exact: true }).click(); + await picker.getByRole('button', { name: 'Choose month and year' }).click(); + await picker.getByRole('spinbutton', { name: 'Year', exact: true }).fill('2032'); + await expect(picker.getByRole('button', { name: 'Feb', exact: true })).toBeDisabled(); + await expect(picker.getByRole('alert')).toHaveText('Choose a year from 2025 to 2025.'); +}); diff --git a/work/term-page-styles.css b/work/term-page-styles.css new file mode 100644 index 0000000..63f5123 --- /dev/null +++ b/work/term-page-styles.css @@ -0,0 +1,56 @@ + +/* Academic terms: browse first, edit only when needed. */ +.academic-services-embedded .terms-manager { gap:24px; } +.academic-services-embedded .terms-header-actions { display:flex; align-items:center; gap:10px; flex-wrap:wrap; } +.academic-services-embedded .terms-manager .page-description { max-width:48ch; } +.academic-services-embedded .terms-search { width:min(100%,360px); } +.academic-services-embedded .terms-filters { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:18px; max-width:760px; } +.academic-services-embedded .terms-results-heading { display:flex; align-items:center; justify-content:space-between; gap:16px; margin-bottom:14px; } +.academic-services-embedded .terms-results-heading h2 { font-size:18px; font-weight:500; margin:0; } +.academic-services-embedded .terms-results-heading>span { color:var(--muted); font-size:13px; } +.academic-services-embedded .terms-table table { width:100%; } +.academic-services-embedded .terms-table td { vertical-align:middle; } +.academic-services-embedded .terms-table td:nth-child(2) { font-variant-numeric:tabular-nums; } +.academic-services-embedded .term-name { display:flex; align-items:center; gap:14px; border:0; padding:3px 0; color:var(--ink); background:transparent; text-align:start; cursor:pointer; } +.academic-services-embedded .term-name strong { display:block; font-size:15px; font-weight:550; } +.academic-services-embedded .term-name small { display:block; font-size:12px; color:var(--muted); margin-top:4px; } +.academic-services-embedded .term-name:hover strong { text-decoration:underline; text-underline-offset:4px; } +.academic-services-embedded .term-name .term-calendar-mark { width:36px; height:40px; flex:none; display:grid; place-items:center; background:#e8e0c8; border-top:6px solid #a8b9a5; border-radius:4px; color:#443d31; font-size:18px; } +.academic-services-embedded .terms-empty { display:grid; justify-items:center; gap:10px; padding:42px 20px; text-align:center; } +.academic-services-embedded .terms-empty h3 { margin:4px 0 0; font-size:17px; } +.academic-services-embedded .terms-empty p { color:var(--muted); font-size:14px; margin:0 0 7px; } +.academic-services-embedded .terms-load-error { display:flex; justify-content:space-between; align-items:center; gap:16px; } +.academic-services-embedded .term-editor { display:grid; gap:22px; } +.academic-services-embedded .term-editor-note { color:var(--muted); font-size:12px; margin:0; } +.academic-services-embedded .term-editor fieldset { min-width:0; margin:0; padding:0; border:0; } +.academic-services-embedded .term-editor legend { color:var(--ink); font-size:15px; font-weight:550; padding:0; margin-bottom:12px; } +.academic-services-embedded .term-identity-fields { display:grid; grid-template-columns:1fr 1fr auto; align-items:start; gap:16px; } +.academic-services-embedded .term-identity-fields .check-field { margin-top:33px; white-space:nowrap; } +.academic-services-embedded .term-editor-dates { display:grid; grid-template-columns:1fr 1fr; align-items:start; gap:24px; padding-top:20px; border-top:1px solid var(--line); } +.academic-services-embedded .term-date-fields { display:grid; grid-template-columns:1fr 1fr; align-items:start; gap:12px; } +.academic-services-embedded .term-editor .field>span { font-size:12px; color:var(--muted); } +.academic-services-embedded .term-editor input { min-width:0; width:100%; } +.academic-services-embedded .term-editor input[type=checkbox] { width:auto; } +.academic-services-embedded .term-field-error { display:block; font-size:12px; line-height:1.45; color:#e5ad9a; font-weight:400; margin-top:5px; } +.academic-services-embedded .term-editor [aria-invalid=true],.academic-services-embedded .term-standing-form [aria-invalid=true] { border-color:#c78d7b; } +.academic-services-embedded .term-validation-summary { padding:10px 13px; border-left:3px solid #c78d7b; background:color-mix(in srgb,var(--paper) 92%,#c78d7b); color:var(--ink); font-size:13px; } +.academic-services-embedded .term-editor .form-footer { margin-top:0; padding-top:18px; border-top:1px solid var(--line); } +.academic-services-embedded .terms-detail-layout { display:grid; grid-template-columns:minmax(0,1fr) 280px; gap:28px; align-items:start; } +.academic-services-embedded .terms-detail-dates { margin:0; } +.academic-services-embedded .terms-detail-dates>div { padding:13px 0; border-bottom:1px solid var(--line); } +.academic-services-embedded .terms-detail-dates dt { font-size:12px; color:var(--muted); margin-bottom:7px; } +.academic-services-embedded .terms-detail-dates dd { margin:0; font-size:15px; color:var(--ink); font-variant-numeric:tabular-nums; } +.service-surface[data-theme=light] .term-field-error { color:#94452f; } +@media(max-width:760px) { + .academic-services-embedded .term-editor-dates { grid-template-columns:1fr; } + .academic-services-embedded .terms-detail-layout { grid-template-columns:1fr; } + .academic-services-embedded .terms-detail-layout .term-calendar { max-width:300px; } +} +@media(max-width:540px) { + .academic-services-embedded .terms-filters { grid-template-columns:1fr; } + .academic-services-embedded .term-identity-fields { grid-template-columns:1fr 1fr; } + .academic-services-embedded .term-identity-fields .check-field { grid-column:1/-1; margin-top:0; } + .academic-services-embedded .terms-manager .page-title-row { align-items:flex-start; } + .academic-services-embedded .terms-header-actions { width:100%; } + .academic-services-embedded .terms-header-actions button { flex:1; } +} diff --git a/work/terms-workspace.jsx b/work/terms-workspace.jsx new file mode 100644 index 0000000..eab4cfc --- /dev/null +++ b/work/terms-workspace.jsx @@ -0,0 +1,147 @@ +function TermsWorkspace({ token, role, notify }) { + const [form, setForm] = useState(blankTerm); + const [termId, setTermId] = useState(''); + const [terms, setTerms] = useState([]); + const [loading, setLoading] = useState(false); + const [fetchingTerms, setFetchingTerms] = useState(false); + const [message, setMessage] = useState(''); + const [error, setError] = useState(''); + const [loadError, setLoadError] = useState(''); + const [recordingStanding, setRecordingStanding] = useState(false); + const [editing, setEditing] = useState(false); + const [viewing, setViewing] = useState(null); + const [touched, setTouched] = useState({}); + const [attempt, setAttempt] = useState(0); + const [search, setSearch] = useState(''); + const [filters, setFilters] = useState({ year: '', season: '', status: '' }); + const editor = useRef(null); + const validation = validateAcademicTerm(form); + const visibleError = field => (attempt || touched[field]) ? validation[field] : ''; + + const loadTerms = async () => { + setFetchingTerms(true); setLoadError(''); + try { + const data = await api('/api/academic-terms/academicTerm', { token }); + setTerms(Array.isArray(data) ? data : []); + } catch { + setLoadError('Could not refresh academic terms. Your last loaded terms are still shown.'); + setTerms(current => current.length ? current : readRecentTerms()); + } finally { setFetchingTerms(false); } + }; + useEffect(() => { loadTerms(); }, [token]); + useEffect(() => { + if (attempt) editor.current?.querySelector('[aria-invalid="true"]')?.focus(); + }, [attempt]); + + const update = (field, value) => { setForm(current => ({ ...current, [field]: value })); setError(''); }; + const openEditor = term => { + setTermId(term?._id || term?.code || ''); setForm(term ? termToForm(term) : { ...blankTerm }); + setTouched({}); setAttempt(0); setError(''); setMessage(''); setViewing(null); setEditing(true); + }; + const submit = async event => { + event.preventDefault(); if (loading) return; + setAttempt(value => value + 1); setError(''); + if (Object.keys(validation).length) return; + const payload = Object.fromEntries(Object.keys(blankTerm).map(key => [key, + termDateFields.includes(key) ? dateToIso(form[key]) : typeof form[key] === 'string' ? form[key].trim() : form[key], + ])); + payload.code = form.code || `${form.season}-${form.academicYear.replace(/[^0-9]/g, '')}`; + setLoading(true); + try { + const data = await api(termId ? `/api/academic-terms/academicTerm/${encodeURIComponent(termId)}` : '/api/academic-terms/academicTerm', { + token, method: termId ? 'PUT' : 'POST', body: payload, + }); + const next = [data, ...terms.filter(term => term._id !== data._id && term.code !== data.code)]; + setTerms(next); setTermId(data._id || data.code); + window.localStorage.setItem('bobos.recentTerms', JSON.stringify(next.slice(0, 8))); + window.localStorage.setItem('bobos.lastTermId', data.code || data._id); + setEditing(false); setMessage(`${termLabel(data)} saved.`); notify('success', `${termLabel(data)} saved.`); + loadTerms(); + } catch (requestError) { + setError(requestError.status === 409 + ? 'This academic year and season already exist. Edit that term or choose a different season.' + : requestError.status === 400 ? 'The term could not be saved. Check the dates and try again.' + : 'Could not save the term. Your entries are kept. Please try again.'); + } finally { setLoading(false); } + }; + const standingSaved = ({ warningEmailStatus }) => { + setRecordingStanding(false); + const text = warningEmailStatus === 'sent' ? 'Standing saved. Probation warning email sent.' + : warningEmailStatus === 'failed' ? 'Standing saved. The probation warning email could not be sent.' + : warningEmailStatus === 'pending' ? 'Standing saved. The probation warning email is pending.' : 'Standing saved.'; + setMessage(text); notify(warningEmailStatus === 'failed' ? 'warning' : 'success', text); + }; + const dateField = (field, shortLabel) => { + const problem = visibleError(field); + const minimum = field === 'termEnd' || field === 'teachingStart' ? form.termStart + : field === 'teachingEnd' ? form.teachingStart : field === 'registrationEnd' ? form.registrationStart : ''; + return ; + }; + + if (role !== 'administrator') { + const selectedTerm = terms.find(term => (term._id || term.code) === termId) || terms.find(term => term.isActive) || terms[0]; + return
+ + {loadError &&
{loadError}
} + {fetchingTerms && !terms.length ? : !selectedTerm ? :
+ +

Dates and deadlines

{selectedTerm.isActive ? 'Active' : 'Inactive'}
{Object.entries(termDateGroups).map(([label, fields]) =>
{label}
selectedTerm[field])} />
)}
+ +
} +
; + } + const years = [...new Set(terms.map(term => term.academicYear).filter(Boolean))].sort().reverse(); + const matching = terms.filter(term => (!filters.year || term.academicYear === filters.year) + && (!filters.season || term.season === filters.season) + && (!filters.status || Boolean(term.isActive) === (filters.status === 'active')) + && `${termLabel(term)} ${term.code}`.toLowerCase().includes(search.trim().toLowerCase())); + const resetFilters = () => { setSearch(''); setFilters({ year: '', season: '', status: '' }); }; + const chips = Object.entries(filters).filter(([, value]) => value).map(([key, value]) => ({ + key, label: pretty(value), onRemove: () => setFilters(current => ({ ...current, [key]: '' })), + })); + return
+ + + +
} /> + {message &&
{message}
} + {loadError &&
{loadError}
} + Find a term setSearch(event.target.value)} />} + chips={chips} onClear={resetFilters} actions={}> +
{[['year', 'Academic year', years], ['season', 'Season', seasons], ['status', 'Status', ['active', 'inactive']]].map(([key, label, options]) => )}
+
+
+

Terms

{matching.length} of {terms.length}
+ {fetchingTerms && !terms.length ? : matching.length ? + {matching.map(term =>
+ + )} + :

{terms.length ? 'No matching terms' : 'No academic terms yet'}

{terms.length ? 'Try another search or clear the filters.' : 'Add your first term to set up its dates.'}

} + + {viewing && setViewing(null)} wide>
{Object.entries(termDateGroups).map(([label, fields]) =>
{label}
viewing[field])} />
)}
} + {editing && { if (!loading) setEditing(false); }} wide> + +

All dates are required.

+ {attempt > 0 && Object.keys(validation).length > 0 &&
Complete {Object.keys(validation).length} highlighted {Object.keys(validation).length === 1 ? 'field' : 'fields'} before saving.
} + {error &&
{error}
} +
Term information
+ + + +
+
{[['Term', ['termStart', 'termEnd']], ['Teaching', ['teachingStart', 'teachingEnd']], ['Registration', ['registrationStart', 'registrationEnd']]].map(([label, fields]) =>
{label}
{fields.map((field, index) => dateField(field, index ? 'Ends' : 'Starts'))}
)} +
Deadlines
{dateField('advisingDeadline', 'Advising')}{dateField('wholeScheduleSwapDeadline', 'Schedule swaps')}
+
+
+ +
} + {recordingStanding && term._id === termId || term.code === termId) || terms.find(term => term.isActive)} onClose={() => setRecordingStanding(false)} onSaved={standingSaved} />} + ; +} + From c91221939084ca25155035a2231e99391aea6e10 Mon Sep 17 00:00:00 2001 From: omar Abuelmagd <166958715+wweater@users.noreply.github.com> Date: Fri, 27 Nov 2026 20:58:21 +0200 Subject: [PATCH 02/24] refactor: organize the course editor into tabs --- apps/web/src/components/AcademicWorkspace.jsx | 34 ++++++++++++++----- apps/web/src/portal-academic.css | 17 +++++++++- docs/portal-design-system.md | 2 ++ tests/browser/portal.spec.mjs | 6 +++- 4 files changed, 48 insertions(+), 11 deletions(-) diff --git a/apps/web/src/components/AcademicWorkspace.jsx b/apps/web/src/components/AcademicWorkspace.jsx index c714bf2..1500016 100644 --- a/apps/web/src/components/AcademicWorkspace.jsx +++ b/apps/web/src/components/AcademicWorkspace.jsx @@ -1,3 +1,4 @@ +import { flushSync } from "react-dom"; import OfferingCourseIcon from "./OfferingCourseIcon.jsx"; import { termLabel } from "../term-label.js"; import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react"; @@ -1240,30 +1241,45 @@ function catalogueMajors(course) { } function CourseEditor({ course, courses, onSave, onClose, saving, error }) { + const [section, setSection] = useState("details"); const [search, setSearch] = useState(""); const [requiredIds, setRequiredIds] = useState(() => (course.prerequisites || []).map(item => item._id || item)); const options = courses.filter(item => item._id !== course._id && `${item.code} ${item.name}`.toLowerCase().includes(search.trim().toLowerCase())); return -
-
Course information
+ { + const panel = event.target.closest("fieldset[data-course-section]"); + if (panel?.hidden) flushSync(() => setSection(panel.dataset.courseSection)); + }}> + + +
Course and slotSubmittedStatusDetails
{term.isActive ? 'Active' : 'Inactive'}