diff --git a/src/app/views/schedule-render.ts b/src/app/views/schedule-render.ts index 6086117..e788a81 100644 --- a/src/app/views/schedule-render.ts +++ b/src/app/views/schedule-render.ts @@ -28,6 +28,7 @@ import { import type { AcademicWindow, OnBreak } from '@nbtca/nbtcal'; import type { GridCursor } from './schedule-grid-cursor.js'; import { renderRecapCard, type RecapCard } from './term-recap-render.js'; +import { courseProgress } from '../../features/course-progress.js'; import type { TermRecap } from '../../features/term-recap.js'; import { getCapabilities } from '../../core/capabilities.js'; import { @@ -598,7 +599,14 @@ export function renderSchedule( } case 'meetingDetail': return state.detailMeeting && state.timetable - ? renderMeetingDetail(state.detailMeeting, state.timetable.periods, cols).split('\n') + ? renderMeetingDetail( + state.detailMeeting, + state.timetable.periods, + cols, + state.weekOne + ? courseProgress(state.timetable, state.weekOne, state.detailMeeting, now) + : undefined, + ).split('\n') : [hint(trans.timetable.genericError)]; case 'error': return hintLines(state.errorMessage ?? trans.timetable.genericError, cols); diff --git a/src/features/course-progress.test.ts b/src/features/course-progress.test.ts new file mode 100644 index 0000000..7cc9db6 --- /dev/null +++ b/src/features/course-progress.test.ts @@ -0,0 +1,56 @@ +import { describe, it, expect } from 'vitest'; +import { campusDateTime, type Timetable, type TimetableMeeting } from '@nbtca/nbtcal/timetable'; +import { courseProgress } from './course-progress.js'; + +const meeting = (o: Partial): TimetableMeeting => ({ + sourceId: null, + courseName: 'Accounting', + teacherNames: [], + location: 'SF104', + weekday: 4, + startPeriod: 1, + endPeriod: 2, + weeks: [1, 2, 3], + kind: 'regular', + ...o, +}); + +const thursday = meeting({}); +const makeUp = meeting({ weekday: 1, weeks: [4] }); +const timetable: Timetable = { + term: { academicYear: '2026', semester: '3' }, + meetings: [thursday, makeUp, meeting({ courseName: 'Other', weekday: 2, weeks: [1, 2, 3, 4] })], + unresolvedItems: [], + periods: [ + { period: 1, label: null, start: '08:00', end: '08:45' }, + { period: 2, label: null, start: '08:50', end: '09:35' }, + ], + calendarDays: [], + warnings: [], + fetchedAt: new Date('2026-09-01T00:00:00Z'), +}; +const WEEK_ONE = '2026-09-14'; + +describe('courseProgress', () => { + it('counts every slot of the course and finds the next session', () => { + const now = campusDateTime('2026-09-25', '12:00'); + const progress = courseProgress(timetable, WEEK_ONE, thursday, now); + expect(progress).toMatchObject({ held: 2, total: 4, termWeeks: 4, currentWeek: 2 }); + expect(progress?.next?.date).toBe('2026-10-01'); + expect(progress?.live).toBeUndefined(); + expect(progress?.others).toEqual([makeUp]); + }); + + it('reports the session in progress', () => { + const now = campusDateTime('2026-09-17', '08:30'); + const progress = courseProgress(timetable, WEEK_ONE, thursday, now); + expect(progress?.live?.date).toBe('2026-09-17'); + expect(progress?.held).toBe(0); + }); + + it('has no next session once the course is over', () => { + const progress = courseProgress(timetable, WEEK_ONE, thursday, new Date('2026-12-01')); + expect(progress).toMatchObject({ held: 4, total: 4 }); + expect(progress?.next).toBeUndefined(); + }); +}); diff --git a/src/features/course-progress.ts b/src/features/course-progress.ts new file mode 100644 index 0000000..a330b8b --- /dev/null +++ b/src/features/course-progress.ts @@ -0,0 +1,56 @@ +import { + createTimetableSchedule, + type Timetable, + type TimetableMeeting, + type TimetableOccurrence, +} from '@nbtca/nbtcal/timetable'; + +export interface CourseProgress { + now: Date; + held: number; + total: number; + live?: TimetableOccurrence; + next?: TimetableOccurrence; + /** The course's other weekly slots, such as a second weekday or a make-up week. */ + others: TimetableMeeting[]; + termWeeks: number; + currentWeek: number; +} + +const sameSlot = (a: TimetableMeeting, b: TimetableMeeting): boolean => + a.courseName === b.courseName && + a.weekday === b.weekday && + a.startPeriod === b.startPeriod && + a.endPeriod === b.endPeriod; + +/** Where a course stands this term, counted over every slot it has; undefined when the timetable cannot be scheduled. */ +export function courseProgress( + timetable: Timetable, + weekOneMonday: string, + meeting: TimetableMeeting, + now: Date, +): CourseProgress | undefined { + try { + const schedule = createTimetableSchedule(timetable, { weekOneMonday }); + const at = now.getTime(); + const sessions = schedule + .occurrences() + .filter((o) => o.meeting.courseName === meeting.courseName); + const live = sessions.find((o) => o.start.getTime() <= at && at < o.end.getTime()); + const next = sessions.find((o) => o.start.getTime() > at); + return { + now, + held: sessions.filter((o) => o.end.getTime() <= at).length, + total: sessions.length, + ...(live ? { live } : {}), + ...(next ? { next } : {}), + others: timetable.meetings.filter( + (m) => m.courseName === meeting.courseName && !sameSlot(m, meeting), + ), + termWeeks: Math.max(0, ...timetable.meetings.flatMap((m) => m.weeks)), + currentWeek: schedule.weekAt(now), + }; + } catch { + return undefined; + } +} diff --git a/src/features/schedule-render.test.ts b/src/features/schedule-render.test.ts index d2cc2a4..641546d 100644 --- a/src/features/schedule-render.test.ts +++ b/src/features/schedule-render.test.ts @@ -20,6 +20,7 @@ import { weekdayShortLabel, } from './schedule-render.js'; import { setLanguage } from '../i18n/index.js'; +import type { CourseProgress } from './course-progress.js'; import { resetIconCache } from '../core/icons.js'; import { campusDateTime } from '@nbtca/nbtcal/timetable'; import { stripAnsi, visualWidth } from '../core/text.js'; @@ -778,6 +779,50 @@ describe('renderMeetingDetail', () => { expect(out).toContain('1, 3, 5'); }); + it('collapses runs of three or more weeks inside a list', () => { + const out = stripAnsi(renderMeetingDetail(mk({ weeks: [1, 3, 5, 6, 7, 8, 10, 11] }), periods)); + expect(out).toContain('1, 3, 5-8, 10, 11'); + }); + + it('adds periods, length, progress, the next session, and other slots', () => { + const meeting = mk({ weekday: 4, weeks: [1, 2, 3] }); + const other = mk({ weekday: 1, weeks: [4] }); + const progress = { + now: campusDateTime('2026-09-16', '12:00'), + held: 1, + total: 4, + next: { + meeting, + week: 1, + date: '2026-09-17', + startTime: '08:00', + endTime: '09:40', + start: campusDateTime('2026-09-17', '08:00'), + end: campusDateTime('2026-09-17', '09:40'), + }, + others: [other], + termWeeks: 4, + currentWeek: 1, + }; + const out = stripAnsi(renderMeetingDetail(meeting, periods, 100, progress)); + expect(out).toMatch(/Time\s+Thu 08:00-09:40 - periods 1-2 - 100 min/); + expect(out).toContain('now week 1'); + expect(out).toContain('# # # .'); + expect(out).toContain('1 done, 3 to go'); + expect(out).toMatch(/Next\s+Tomorrow 08:00 - in 20h/); + expect(out).toMatch(/Also\s+Mon 08:00-09:40 - weeks 4/); + + const live = { ...progress, live: progress.next, now: campusDateTime('2026-09-17', '09:00') }; + expect(stripAnsi(renderMeetingDetail(meeting, periods, 100, live))).toContain( + 'In class now, 40 min left', + ); + const ended: CourseProgress = { ...progress }; + delete ended.next; + expect(stripAnsi(renderMeetingDetail(meeting, periods, 100, ended))).toContain( + 'Finished for this term', + ); + }); + it('never collapses into one array entry when split on newlines', () => { const out = renderMeetingDetail(mk({}), periods); expect(out.split('\n').length).toBeGreaterThan(1); diff --git a/src/features/schedule-render.ts b/src/features/schedule-render.ts index b603959..d19ad7f 100644 --- a/src/features/schedule-render.ts +++ b/src/features/schedule-render.ts @@ -8,6 +8,7 @@ import type { } from '@nbtca/nbtcal/timetable'; import { campusDateTime, campusIsoDate, createTimetableSchedule } from '@nbtca/nbtcal/timetable'; import { countdownParts, isCountdownUrgent, type Countdown } from './calendar-query.js'; +import type { CourseProgress } from './course-progress.js'; import { c, type, space, glyph, MAX_FRAME_COLS, bodyWidth } from '../core/theme.js'; import { pickIcon } from '../core/icons.js'; import { padEndV, truncate, visualWidth, wrapAnsiToVisualWidth } from '../core/text.js'; @@ -579,60 +580,180 @@ export function renderWeekAgenda( return lines; } +/** Lists weeks with runs of three or more collapsed, such as "1, 3, 5–17". */ function formatWeekRange(weeks: readonly number[]): string { - if (weeks.length === 0) return ''; - const sorted = [...weeks].sort((a, b) => a - b); - const isContiguous = sorted.every((week, index) => { - const previous = sorted[index - 1]; - return index === 0 || (previous !== undefined && week === previous + 1); - }); - if (isContiguous) { - const first = sorted[0]; - const last = sorted.at(-1); - return sorted.length > 1 ? rangeLabel(String(first), String(last)) : `${first}`; + const sorted = [...new Set(weeks)].sort((a, b) => a - b); + const parts: string[] = []; + for (let index = 0; index < sorted.length;) { + let end = index; + while (sorted[end + 1] === (sorted[end] ?? 0) + 1) end += 1; + const first = String(sorted[index]); + if (end - index >= 2) parts.push(rangeLabel(first, String(sorted[end]))); + else parts.push(...sorted.slice(index, end + 1).map(String)); + index = end + 1; + } + return parts.join(t().timetable.listSeparator); +} + +function weekStrip(meeting: TimetableMeeting, progress: CourseProgress): string { + const weeks = new Set(meeting.weeks); + const full = pickIcon('■', '#'); + const empty = pickIcon('·', '.'); + return Array.from({ length: progress.termWeeks }, (_, index) => { + const week = index + 1; + const mark = weeks.has(week) ? full : empty; + if (week === progress.currentWeek) return type.active(mark); + return weeks.has(week) && week > progress.currentWeek ? type.body(mark) : type.hint(mark); + }).join(' '); +} + +function periodLabel(meeting: TimetableMeeting): string { + const trans = t().timetable; + return meeting.startPeriod === meeting.endPeriod + ? fmt(trans.detailPeriod, { period: meeting.startPeriod }) + : fmt(trans.detailPeriods, { + periods: rangeLabel(String(meeting.startPeriod), String(meeting.endPeriod)), + }); +} + +function sessionMinutes(meeting: TimetableMeeting, periods: readonly TimetablePeriod[]): number { + const start = periods.find((p) => p.period === meeting.startPeriod)?.start; + const end = periods.find((p) => p.period === meeting.endPeriod)?.end; + if (!start || !end) return 0; + const minutes = (clock: string) => Number(clock.slice(0, 2)) * 60 + Number(clock.slice(3, 5)); + return Math.max(0, minutes(end) - minutes(start)); +} + +function sessionDay(occurrence: TimetableOccurrence, now: Date): string { + const trans = t().timetable; + const today = campusIsoDate(now); + const tomorrow = campusIsoDate(new Date(now.getTime() + 86_400_000)); + if (occurrence.date === today) return trans.detailToday; + if (occurrence.date === tomorrow) return trans.detailTomorrow; + const date = new Date(`${occurrence.date}T00:00:00Z`).toLocaleDateString( + getCurrentLanguage() === 'zh' ? 'zh-CN' : 'en-US', + { month: 'short', day: 'numeric', timeZone: 'UTC' }, + ); + return `${date} ${weekdayName(occurrence.meeting.weekday, 'short')}`; +} + +function nextSessionText(progress: CourseProgress): string | string[] { + const trans = t().timetable; + if (progress.live) { + const minutes = Math.max( + 1, + Math.ceil((progress.live.end.getTime() - progress.now.getTime()) / 60_000), + ); + return fmt(trans.detailLiveNow, { minutes }); } - return sorted.join(', '); + if (!progress.next) return trans.detailEnded; + const countdown = formatClassCountdown(countdownParts(progress.next.start, progress.now)); + return [`${sessionDay(progress.next, progress.now)} ${progress.next.startTime}`, countdown]; +} + +function joinSegments(value: string | readonly string[], dot: string, width: number): string[] { + const segments = typeof value === 'string' ? [value] : value; + const lines: string[] = []; + let current = ''; + for (const segment of segments) { + const joined = current ? `${current}${dot}${segment}` : segment; + if (!current || visualWidth(joined) <= width) { + current = joined; + continue; + } + lines.push(current); + current = segment; + } + if (current) lines.push(current); + return lines.flatMap((line) => wrapAnsiToVisualWidth(type.body(line), width)); +} + +interface DetailRow { + label: string; + /** Segments joined by a separator dot; lines break between segments before inside one. */ + value: string | readonly string[]; + /** A pre-styled line under the value, dropped when it does not fit. */ + below?: string; } export function renderMeetingDetail( meeting: TimetableMeeting, periods: readonly TimetablePeriod[], cols = Number.POSITIVE_INFINITY, + progress?: CourseProgress, ): string { const trans = t(); - const rows: [string, string][] = [ - [ - trans.timetable.detailTime, - `${weekdayName(meeting.weekday, 'short')} ${span(meeting, periods)}`, - ], + const dot = ` ${glyph.sep()} `; + const minutes = sessionMinutes(meeting, periods); + const rows: DetailRow[] = [ + { + label: trans.timetable.detailTime, + value: [ + `${weekdayName(meeting.weekday, 'short')} ${span(meeting, periods)}`, + periodLabel(meeting), + ...(minutes > 0 ? [fmt(trans.timetable.detailMinutes, { minutes })] : []), + ], + }, ]; - if (meeting.location) rows.push([trans.timetable.detailLocation, meeting.location]); + if (meeting.location) + rows.push({ label: trans.timetable.detailLocation, value: meeting.location }); if (meeting.teacherNames.length > 0) { - rows.push([ - trans.timetable.detailTeacher, - meeting.teacherNames.join(trans.timetable.teacherSeparator), - ]); + rows.push({ + label: trans.timetable.detailTeacher, + value: meeting.teacherNames.join(trans.timetable.teacherSeparator), + }); + } + const showStrip = progress !== undefined && progress.termWeeks > 1; + rows.push({ + label: trans.timetable.detailWeeks, + value: + progress && progress.currentWeek >= 1 && progress.currentWeek <= progress.termWeeks + ? [ + formatWeekRange(meeting.weeks), + fmt(trans.timetable.detailCurrentWeek, { week: progress.currentWeek }), + ] + : formatWeekRange(meeting.weeks), + ...(showStrip ? { below: weekStrip(meeting, progress) } : {}), + }); + if (progress && progress.total > 0) { + rows.push({ + label: trans.timetable.detailProgress, + value: fmt(trans.timetable.detailProgressValue, { + held: progress.held, + left: progress.total - progress.held, + }), + }); + rows.push({ label: trans.timetable.detailNext, value: nextSessionText(progress) }); + } + for (const other of progress?.others ?? []) { + rows.push({ + label: trans.timetable.detailAlso, + value: [ + `${weekdayName(other.weekday, 'short')} ${span(other, periods)}`, + fmt(trans.timetable.detailWeeksValue, { weeks: formatWeekRange(other.weeks) }), + ], + }); } - rows.push([trans.timetable.detailWeeks, formatWeekRange(meeting.weeks)]); const width = bodyWidth(cols); const indent = visualWidth(space.indent) < width ? space.indent : ''; const contentWidth = Math.max(1, width - visualWidth(indent)); - const labelWidth = rows.reduce((w, [label]) => Math.max(w, visualWidth(label)), 0); + const labelWidth = rows.reduce((w, { label }) => Math.max(w, visualWidth(label)), 0); const lines = wrapAnsiToVisualWidth(type.heading(meeting.courseName), contentWidth).map( (part) => `${indent}${part}`, ); lines.push(''); - for (const [label, value] of rows) { + for (const { label, value, below } of rows) { const inlinePrefix = `${indent}${type.label(padEndV(label, labelWidth))} `; const inlineValueWidth = width - visualWidth(inlinePrefix); if (!Number.isFinite(width) || inlineValueWidth >= 12) { - const parts = wrapAnsiToVisualWidth(type.body(value), inlineValueWidth); + const parts = joinSegments(value, dot, inlineValueWidth); const continuation = ' '.repeat(visualWidth(inlinePrefix)); lines.push( ...parts.map((part, index) => `${index === 0 ? inlinePrefix : continuation}${part}`), ); + if (below && visualWidth(continuation + below) <= width) lines.push(continuation + below); continue; } @@ -641,9 +762,7 @@ export function renderMeetingDetail( ); const valueIndent = visualWidth(indent) + 2 < width ? `${indent} ` : indent; const valueWidth = Math.max(1, width - visualWidth(valueIndent)); - lines.push( - ...wrapAnsiToVisualWidth(type.body(value), valueWidth).map((part) => `${valueIndent}${part}`), - ); + lines.push(...joinSegments(value, dot, valueWidth).map((part) => `${valueIndent}${part}`)); } return lines.join('\n'); } diff --git a/src/i18n/index.ts b/src/i18n/index.ts index 176656c..b95b8db 100644 --- a/src/i18n/index.ts +++ b/src/i18n/index.ts @@ -359,6 +359,20 @@ export interface Translations { detailLocation: string; detailTeacher: string; detailWeeks: string; + listSeparator: string; + detailPeriod: string; + detailPeriods: string; + detailMinutes: string; + detailCurrentWeek: string; + detailProgress: string; + detailProgressValue: string; + detailNext: string; + detailLiveNow: string; + detailEnded: string; + detailToday: string; + detailTomorrow: string; + detailAlso: string; + detailWeeksValue: string; teacherSeparator: string; noClassOnDay: string; countdownDays: string; diff --git a/src/i18n/locales/en.json b/src/i18n/locales/en.json index 72fd3c4..f32b505 100644 --- a/src/i18n/locales/en.json +++ b/src/i18n/locales/en.json @@ -439,6 +439,20 @@ "detailLocation": "Location", "detailTeacher": "Teacher", "detailWeeks": "Weeks", + "listSeparator": ", ", + "detailPeriod": "period {period}", + "detailPeriods": "periods {periods}", + "detailMinutes": "{minutes} min", + "detailCurrentWeek": "now week {week}", + "detailProgress": "Progress", + "detailProgressValue": "{held} done, {left} to go", + "detailNext": "Next", + "detailLiveNow": "In class now, {minutes} min left", + "detailEnded": "Finished for this term", + "detailToday": "Today", + "detailTomorrow": "Tomorrow", + "detailAlso": "Also", + "detailWeeksValue": "weeks {weeks}", "teacherSeparator": ", ", "noClassOnDay": "No classes on {weekday}", "countdownDays": "in {days}d {hours}h", diff --git a/src/i18n/locales/zh.json b/src/i18n/locales/zh.json index 1a7e70d..56d8b44 100644 --- a/src/i18n/locales/zh.json +++ b/src/i18n/locales/zh.json @@ -439,6 +439,20 @@ "detailLocation": "地点", "detailTeacher": "教师", "detailWeeks": "周次", + "listSeparator": "、", + "detailPeriod": "第 {period} 节", + "detailPeriods": "第 {periods} 节", + "detailMinutes": "{minutes} 分钟", + "detailCurrentWeek": "现在第 {week} 周", + "detailProgress": "进度", + "detailProgressValue": "已上 {held} 次,还剩 {left} 次", + "detailNext": "下次", + "detailLiveNow": "正在上课,还剩 {minutes} 分钟", + "detailEnded": "本学期已结课", + "detailToday": "今天", + "detailTomorrow": "明天", + "detailAlso": "另有", + "detailWeeksValue": "第 {weeks} 周", "teacherSeparator": "、", "noClassOnDay": "{weekday}没有课", "countdownDays": "{days} 天 {hours} 小时后",