@nbtca/prompt 1.5.24 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -25,7 +25,11 @@ Or try it without installing: `npx @nbtca/prompt`.
25
25
  `nbtca` opens a full-screen client. Press `1`–`5` or `Tab` to switch tabs, and
26
26
  `?` to list every key.
27
27
 
28
- - **Home**: today's classes and the next club events.
28
+ - **Home**: today's classes and the next club events, over a seascape that
29
+ follows the campus sun and moon. Solar terms bring rain or snow, and New
30
+ Year, the Spring Festival, the Lantern Festival, and the Mid-Autumn Festival
31
+ light up the night. An owl keeps watch between 01:00 and 05:00, and March
32
+ marks the club's founding in 2002.
29
33
  - **Schedule**: the current term, week, and next break. Log in to the campus
30
34
  system to see your timetable and export it to any calendar app as `.ics`.
31
35
  Press `a` for personal exam arrangements or `c` for grades. Both are also
@@ -34,8 +38,13 @@ Or try it without installing: `npx @nbtca/prompt`.
34
38
  `Enter` to read full details. Press `/` to search by course name or code, `f`
35
39
  to filter upcoming exams or unpublished and void grades, and `s` to change
36
40
  terms. Wide terminals show details beside the list.
41
+ Press `r` for a term recap: how many classes you had, early starts, your
42
+ fullest day, the course and room you saw most, and club events held in the
43
+ same weeks. Near the end of term, Home tells you the recap is ready.
37
44
  - **Events**: a countdown to the next event, plus week and month views, search,
38
- history, and a one-year activity heatmap.
45
+ history, and a one-year activity heatmap. Tall terminals also draw the past
46
+ year as a star map: one star per event, colored by kind, with nearby events
47
+ of a kind joined into constellations.
39
48
  - **Docs**: read and search the knowledge base. It works even when GitHub is
40
49
  unreachable.
41
50
  - **Settings**: language, icons, and colors.
@@ -54,6 +63,7 @@ nbtca exams [--term=2025-2] [--json] [--one-shot]
54
63
  nbtca exams --output=exams.ics [--term=2025-2]
55
64
  nbtca grades [--term=2025-2] [--json] [--one-shot]
56
65
  nbtca status [--watch]
66
+ nbtca prompt [--json] [--shell=fish|zsh|bash|tmux]
57
67
  nbtca docs
58
68
  nbtca website|github|roadmap|repair [--open]
59
69
  nbtca lang zh|en
@@ -75,6 +85,11 @@ the school's original numeric or textual result; Prompt does not calculate an
75
85
  overall GPA. Records stay in memory and are not cached. `--json` writes them to
76
86
  standard output, so keep redirected output private.
77
87
 
88
+ In the interactive client, a grade published since your last look stays hidden
89
+ as `▒▒▒ new` until you open it with `Enter`. To know which grades are new,
90
+ Prompt keeps a salted fingerprint of each course whose result it has seen,
91
+ never the result itself. Logging out removes the fingerprints.
92
+
78
93
  Use `nbtca exams --output=exams.ics` to export a private calendar for a calendar
79
94
  app. Export requires a published time for every exam; it fails before writing if
80
95
  any time is unavailable. Authentication stays in Prompt. The `nbtcal/academic`
@@ -83,6 +98,22 @@ module owns academic queries, parsing, calendar conversion and ICS serialization
83
98
  Prompt never stores your password. A saved campus session gets user-only file
84
99
  permissions. See [SECURITY.md](SECURITY.md).
85
100
 
101
+ ## Shell prompt
102
+
103
+ `nbtca prompt` prints the class in progress or the next class today, such as
104
+ `● Calculus · 3-201 · 17 min left`, and prints nothing otherwise. It reads only
105
+ the saved timetable, never the network, so it is fast enough to run on every
106
+ prompt. Print the setup line for your shell and add it to your shell config:
107
+
108
+ ```bash
109
+ nbtca prompt --shell=fish >> ~/.config/fish/config.fish
110
+ nbtca prompt --shell=zsh >> ~/.zshrc
111
+ ```
112
+
113
+ `--shell=bash` and `--shell=tmux` work the same way. `--json` prints the same
114
+ class as an object, or `null`, for other prompt tools. While the interactive
115
+ client is open, the terminal title shows the same line.
116
+
86
117
  ## Development
87
118
 
88
119
  ```bash
package/SECURITY.md CHANGED
@@ -11,7 +11,10 @@ on POSIX systems. Use `nbtca schedule logout` to remove it, or `--one-shot` to
11
11
  avoid reading or writing a session.
12
12
 
13
13
  Exam and grade queries use allowlisted, read-only academic endpoints. Prompt
14
- discards unrelated identity fields and does not cache these records. JSON output
14
+ discards unrelated identity fields and does not cache these records. To mark
15
+ new grades, it stores a salted HMAC-SHA256 fingerprint of each course whose
16
+ result has been published, with `0600` permissions; the file holds no result.
17
+ `nbtca schedule logout` removes it. JSON output
15
18
  contains personal academic information; redirected output and terminal scrollback
16
19
  may retain it.
17
20
 
@@ -3,6 +3,7 @@ import { padEndV, visualWidth } from '../core/text.js';
3
3
  import chalk from 'chalk';
4
4
  import { pictureMode, renderBitmap } from '../core/pixel-art.js';
5
5
  import { mountainScene, scaleBitmap, shelfScene, skyScene } from '../art/scene.js';
6
+ import { starMapScene } from '../art/star-map.js';
6
7
  import { teaCup } from '../art/motifs.js';
7
8
  import { gasGiantLines, moonLines, planetSize } from '../art/planet.js';
8
9
  import { space } from '../core/theme.js';
@@ -28,7 +29,7 @@ function remember(key, build) {
28
29
  }
29
30
  /** A landscape that fills the given box of cells with Braille-fine pixels, or undefined when the box is too small. */
30
31
  function scene(spec, cols, rows, now) {
31
- if (spec.kind !== 'sky' && spec.kind !== 'mountain' && spec.kind !== 'shelf')
32
+ if (spec.kind === 'emblem' || spec.kind === 'planet' || spec.kind === 'icon')
32
33
  return undefined;
33
34
  const width = Math.min(cols, MAX_COLS);
34
35
  if (width < MIN_COLS || rows < MIN_ROWS)
@@ -40,6 +41,7 @@ function scene(spec, cols, rows, now) {
40
41
  rows,
41
42
  minute,
42
43
  spec.kind === 'mountain' ? spec.progress.toFixed(3) : '',
44
+ spec.kind === 'stars' ? `${spec.stars.length}:${spec.stars.at(-1)?.at ?? 0}` : '',
43
45
  pictureMode(),
44
46
  chalk.level,
45
47
  ].join('|');
@@ -49,7 +51,9 @@ function scene(spec, cols, rows, now) {
49
51
  ? skyScene(pixels.width, pixels.height, now)
50
52
  : spec.kind === 'mountain'
51
53
  ? mountainScene(pixels.width, pixels.height, spec.progress, spec.weeks, now)
52
- : shelfScene(pixels.width, pixels.height);
54
+ : spec.kind === 'stars'
55
+ ? starMapScene(pixels.width, pixels.height, spec.stars, now)
56
+ : shelfScene(pixels.width, pixels.height);
53
57
  return renderBitmap(bitmap, undefined, SCENE_GAMMA);
54
58
  });
55
59
  }
@@ -65,7 +69,7 @@ function compact(spec, cols, rows, now) {
65
69
  const size = planetSize(cols, rows);
66
70
  return spec.style === 'moon' ? moonLines(size, now) : gasGiantLines(size);
67
71
  }
68
- if (spec.kind !== 'icon')
72
+ if (spec.kind !== 'icon' && spec.kind !== 'stars')
69
73
  return undefined;
70
74
  const factor = Math.min(Math.floor(cols / (spec.icon.rows[0]?.length ?? 1)), Math.floor((rows * 2) / spec.icon.rows.length), 3);
71
75
  return factor >= 2 ? renderBitmap(scaleBitmap(spec.icon, factor)) : undefined;
@@ -79,15 +83,17 @@ export function withAmbient(body, spec, cols, bodyRows, now = new Date()) {
79
83
  return [...body];
80
84
  const indent = visualWidth(space.indent);
81
85
  const rows = Math.floor(bodyRows);
82
- const below = rows - body.length - 1;
86
+ const legend = spec.kind === 'stars' ? [space.indent + spec.legend] : [];
87
+ const below = rows - body.length - 1 - legend.length;
83
88
  const panorama = scene(spec, cols - indent * 2, below, now);
84
89
  if (panorama && below >= MIN_PANORAMA_ROWS) {
85
- return [...body, '', ...panorama.map((line) => space.indent + line)];
90
+ return [...body, '', ...panorama.map((line) => space.indent + line), ...legend];
86
91
  }
87
92
  const contentWidth = Math.max(0, ...body.map(visualWidth));
88
93
  const width = cols - contentWidth - GAP - indent;
89
94
  const side = Math.min(rows - 1, Math.round(Math.min(width, MAX_COLS) * 0.55));
90
- const art = scene(spec, width, side, now) ?? compact(spec, width, rows - 1, now);
95
+ const art = (spec.kind === 'stars' ? undefined : scene(spec, width, side, now)) ??
96
+ compact(spec, width, rows - 1, now);
91
97
  if (!art)
92
98
  return [...body];
93
99
  return Array.from({ length: Math.max(body.length, art.length) }, (_, index) => {
package/dist/app/app.js CHANGED
@@ -13,6 +13,9 @@ import { getAppTabs } from './tabs.js';
13
13
  import { renderHelp } from './help.js';
14
14
  import { t } from '../i18n/index.js';
15
15
  import { SPINNER_FRAME_MS } from '../core/components/spinner.js';
16
+ import { peekSchedule } from '../features/schedule-view.js';
17
+ import { promptClass, promptLine } from '../features/prompt-line.js';
18
+ import { useUnicodeIcons } from '../core/icons.js';
16
19
  export async function runApp() {
17
20
  if (!process.stdin.isTTY || !process.stdout.isTTY)
18
21
  return;
@@ -29,6 +32,7 @@ export async function runApp() {
29
32
  let helpOpen = false;
30
33
  let painted;
31
34
  let lastBody = { length: 0, height: 0 };
35
+ let title;
32
36
  const viewIds = getAppTabs().map((tab) => tab.id);
33
37
  const nativeViews = {
34
38
  home: homeView,
@@ -211,11 +215,23 @@ export async function runApp() {
211
215
  dispatchKey(key);
212
216
  }
213
217
  }
218
+ function updateTitle() {
219
+ if (!entered)
220
+ return;
221
+ const schedule = peekSchedule();
222
+ const line = promptLine(schedule ? promptClass(schedule) : undefined, useUnicodeIcons());
223
+ const next = line || 'NBTCA Prompt';
224
+ if (next === title)
225
+ return;
226
+ title = next;
227
+ process.stdout.write(ansi.title(next));
228
+ }
214
229
  function scheduleClock() {
215
230
  if (!running)
216
231
  return;
217
232
  clockTimer = setTimeout(() => {
218
233
  clockTimer = undefined;
234
+ updateTitle();
219
235
  render();
220
236
  scheduleClock();
221
237
  }, 60_000 - (Date.now() % 60_000));
@@ -244,7 +260,9 @@ export async function runApp() {
244
260
  keyDecoder.reset();
245
261
  ensureCursorRestored();
246
262
  try {
247
- process.stdout.write(ansi.enterAlt + ansi.hideCursor);
263
+ process.stdout.write(ansi.enterAlt + ansi.hideCursor + ansi.pushTitle);
264
+ title = undefined;
265
+ updateTitle();
248
266
  if (process.stdin.isTTY)
249
267
  process.stdin.setRawMode(true);
250
268
  process.stdin.resume();
@@ -264,7 +282,7 @@ export async function runApp() {
264
282
  process.stdin.removeListener('data', onKey);
265
283
  if (process.stdin.isTTY)
266
284
  process.stdin.setRawMode(false);
267
- process.stdout.write(ansi.showCursor + ansi.leaveAlt);
285
+ process.stdout.write(ansi.popTitle + ansi.showCursor + ansi.leaveAlt);
268
286
  process.stdin.pause();
269
287
  }
270
288
  function switchTo(id) {
@@ -1,4 +1,6 @@
1
- import { eventIcon } from '../../features/event-art.js';
1
+ import { eventIcon, eventKind } from '../../features/event-art.js';
2
+ import { STAR_COLORS } from '../../art/star-map.js';
3
+ import chalk from 'chalk';
2
4
  import { eventIconDefault } from '../../art/bitmaps.js';
3
5
  import { captureFooterHint, passiveFooterHint } from '../chrome.js';
4
6
  import { ListField, computeMaxVisible } from '../fields/list-field.js';
@@ -113,6 +115,27 @@ function moveHeatmapCursor(key, cols) {
113
115
  const next = shiftHeatmapDay(current, step);
114
116
  selectHeatmapDay(next < start ? start : next > end ? end : next);
115
117
  }
118
+ const YEAR_MS = 365 * 86_400_000;
119
+ function stableSeed(text) {
120
+ let hash = 0;
121
+ for (let index = 0; index < text.length; index++) {
122
+ hash = (Math.imul(hash, 31) + text.charCodeAt(index)) | 0;
123
+ }
124
+ return Math.abs(hash);
125
+ }
126
+ function eventStars(cal, now) {
127
+ return cal.inRange(new Date(now.getTime() - YEAR_MS), now).map((event) => ({
128
+ at: event.start.getTime(),
129
+ kind: eventKind(event.title ?? '', event.description ?? ''),
130
+ seed: stableSeed(`${event.uid}@${event.start.toISOString()}`),
131
+ }));
132
+ }
133
+ function starLegend(stars) {
134
+ const trans = t().calendar.stars;
135
+ const kinds = Object.keys(STAR_COLORS).filter((kind) => stars.some((star) => star.kind === kind));
136
+ const keys = kinds.map((kind) => `${chalk.hex(STAR_COLORS[kind])(glyph.dot())} ${trans[kind]}`);
137
+ return [trans.title, ...keys].join(' ');
138
+ }
116
139
  function goToHub() {
117
140
  const now = new Date();
118
141
  const upcoming = calendar ? currentEvents(calendar, now) : [];
@@ -124,6 +147,7 @@ function goToHub() {
124
147
  ...(nextEvent === undefined ? {} : { nextEvent: toDisplayEvent(nextEvent) }),
125
148
  heatmapBuckets: calendar ? yearHeatmap(calendar, now) : [],
126
149
  recentEvents: upcoming.slice(0, RECENT_EVENTS_CAP).map(toDisplayEvent),
150
+ stars: calendar ? eventStars(calendar, now) : [],
127
151
  };
128
152
  }
129
153
  function showDetail(raw) {
@@ -187,10 +211,11 @@ export const eventsView = {
187
211
  if (state.mode !== 'hub')
188
212
  return undefined;
189
213
  const next = state.nextEvent;
190
- return {
191
- kind: 'icon',
192
- icon: next ? eventIcon(next.title, next.description) : eventIconDefault,
193
- };
214
+ const icon = next ? eventIcon(next.title, next.description) : eventIconDefault;
215
+ const stars = state.stars ?? [];
216
+ return stars.length > 0
217
+ ? { kind: 'stars', stars, icon, legend: starLegend(stars) }
218
+ : { kind: 'icon', icon };
194
219
  },
195
220
  isBusy() {
196
221
  return state.mode === 'loading';
@@ -1,4 +1,7 @@
1
1
  import { c, type, space, glyph } from '../../core/theme.js';
2
+ import { occasion } from '../../art/almanac.js';
3
+ import { isOwlHour } from '../../art/scene.js';
4
+ import { FOUNDED } from '../../config/data.js';
2
5
  import { t, fmt } from '../../i18n/index.js';
3
6
  import { pickIcon } from '../../core/icons.js';
4
7
  import { padEndV, visualWidth, wrapAnsiWithIndent } from '../../core/text.js';
@@ -10,6 +13,7 @@ import { campusDateTime, campusIsoDate } from '@nbtca/nbtcal/timetable';
10
13
  import { isoDayDifference, localDayDifference, parseLocalDate } from '../../core/calendar-day.js';
11
14
  import { currentEvents } from '../../features/calendar-query.js';
12
15
  import { emptyStateLines, loadingStateLines } from '../../core/components/empty-state.js';
16
+ import { termRecap } from '../../features/term-recap.js';
13
17
  const WEEKDAYS = [1, 2, 3, 4, 5, 6, 7];
14
18
  function wrappedIndentedLines(label, cols, style) {
15
19
  return wrapAnsiWithIndent(style(label), cols, space.indent);
@@ -23,6 +27,7 @@ function wrappedRenderedLines(line, cols) {
23
27
  }
24
28
  const DAY_MS = 86_400_000;
25
29
  const DAY_PROGRESS_WIDTH = 20;
30
+ const GREETING_MIN_ROWS = 20;
26
31
  function renderDayProgress(now, cols) {
27
32
  const midnight = campusDateTime(campusIsoDate(now), '00:00');
28
33
  const fraction = Math.min(1, Math.max(0, (now.getTime() - midnight.getTime()) / DAY_MS));
@@ -81,6 +86,19 @@ export function renderHome(data, now, bodyRows = 100, cols = 80) {
81
86
  const trans = t();
82
87
  const eventsStale = data.eventsLoadFailed === true && (data.eventLines?.length ?? 0) > 0;
83
88
  const lines = eventsStale ? offlineNotice(cols) : [];
89
+ const roomy = bodyRows >= GREETING_MIN_ROWS;
90
+ const greetings = [
91
+ roomy && isOwlHour(now) ? trans.greeting.lateNight : undefined,
92
+ roomy && now.getMonth() + 1 === FOUNDED.month
93
+ ? fmt(trans.greeting.anniversary, { years: now.getFullYear() - FOUNDED.year })
94
+ : undefined,
95
+ ].filter((line) => line !== undefined);
96
+ for (const greeting of greetings) {
97
+ const line = `${type.active(glyph.dot())} ${type.body(greeting)}`;
98
+ lines.push(...wrappedIndentedLines(line, cols, (value) => value));
99
+ }
100
+ if (greetings.length > 0)
101
+ lines.push('');
84
102
  if (data.schedule === null) {
85
103
  lines.push(...panelHeading(trans.timetable.menuTitle, cols));
86
104
  lines.push(...wrappedIndentedLines(fmt(cols < 40 || bodyRows < 10
@@ -96,11 +114,19 @@ export function renderHome(data, now, bodyRows = 100, cols = 80) {
96
114
  lines.push(...panelHeading(trans.timetable.nextClass, cols));
97
115
  lines.push(...(next ? [next] : wrappedIndentedLines(trans.timetable.noNextClass, cols, type.hint)));
98
116
  lines.push('');
99
- lines.push(...panelHeading(trans.timetable.hubToday, cols));
117
+ const today = occasion(now);
118
+ const todayHeading = today
119
+ ? `${trans.timetable.hubToday} ${glyph.sep()} ${trans.almanac[today.name]}`
120
+ : trans.timetable.hubToday;
121
+ lines.push(...panelHeading(todayHeading, cols));
100
122
  lines.push(renderDayProgress(now, cols));
101
123
  lines.push(...todayLines(data.schedule, now, cols));
102
124
  lines.push('');
103
125
  }
126
+ if (data.recapReady) {
127
+ const ready = `${type.active(glyph.dot())} ${type.body(trans.recap.homeReady)}`;
128
+ lines.push(...wrappedIndentedLines(ready, cols, (value) => value), '');
129
+ }
104
130
  if (data.weekAhead) {
105
131
  lines.push(...panelHeading(trans.timetable.weekOverviewTitle, cols));
106
132
  lines.push(...renderWeekAheadGrid(data.weekAhead.classDays, data.weekAhead.eventDays, cols).split('\n'));
@@ -156,6 +182,7 @@ export function renderHome(data, now, bodyRows = 100, cols = 80) {
156
182
  return lines;
157
183
  }
158
184
  const HOME_EVENT_FETCH_CAP = 15;
185
+ const RECAP_READY_PROGRESS = 0.9;
159
186
  function calendarSnapshot(cal, weekAhead) {
160
187
  const now = new Date();
161
188
  const current = currentEvents(cal, now);
@@ -198,9 +225,11 @@ export const homeView = {
198
225
  return;
199
226
  const schedule = peekSchedule();
200
227
  const weekAhead = schedule ? weekAheadInfo(schedule) : null;
228
+ const recap = schedule && termRecap(schedule.timetable, schedule.weekOneMonday, new Date());
201
229
  data = {
202
230
  loading: true,
203
231
  schedule,
232
+ ...(recap && recap.progress >= RECAP_READY_PROGRESS ? { recapReady: true } : {}),
204
233
  ...(weekAhead ? { weekAhead: { classDays: weekAhead.classDays } } : {}),
205
234
  };
206
235
  const cached = peekCalendar();
@@ -4,6 +4,8 @@ import { pickIcon } from '../../core/icons.js';
4
4
  import { t, fmt } from '../../i18n/index.js';
5
5
  import { renderListFieldWithContext } from '../fields/list-field.js';
6
6
  import { renderNextClassBanner, renderWeekGrid, renderUnresolvedItems, renderTodayTimeline, weekdayShortLabel, renderTermDensity, renderMeetingDetail, renderDayTimeline, renderDaySwitcher, renderWeekAgenda, weekGridFullWidth, lineBudget, } from '../../features/schedule-render.js';
7
+ import { renderRecapCard } from './term-recap-render.js';
8
+ import { getCapabilities } from '../../core/capabilities.js';
7
9
  import { sanitizeTerminalLine, truncate, truncateStart, visualWidth, wrapAnsiWithIndent, } from '../../core/text.js';
8
10
  import { isoDayDifference } from '../../core/calendar-day.js';
9
11
  import { loadingLines } from '../../core/components/spinner.js';
@@ -29,6 +31,7 @@ export function hubShortcuts(tt) {
29
31
  const shortcuts = [
30
32
  { key: 'w', label: trans.timetable.hubFullGrid },
31
33
  { key: 't', label: trans.timetable.hubTermDensity },
34
+ { key: 'r', label: trans.recap.title },
32
35
  { key: 's', label: trans.timetable.hubSwitchTerm },
33
36
  { key: 'e', label: trans.timetable.hubExport },
34
37
  { key: 'a', label: trans.records.exams },
@@ -363,6 +366,14 @@ export function renderSchedule(state, now, bodyRows = 100, cols = 80) {
363
366
  '',
364
367
  ...renderUnresolvedItems(state.timetable?.unresolvedItems ?? [], cols).split('\n'),
365
368
  ];
369
+ case 'recap': {
370
+ if (!state.recap)
371
+ return [hint(trans.timetable.genericError)];
372
+ const { recap, cards, index, shownAt } = state.recap;
373
+ const title = recap.finished ? trans.recap.title : trans.recap.titleSoFar;
374
+ const elapsed = getCapabilities().reducedMotion ? Infinity : now.getTime() - shownAt;
375
+ return renderRecapCard(cards, index, title, elapsed, cols);
376
+ }
366
377
  case 'meetingDetail':
367
378
  return state.detailMeeting && state.timetable
368
379
  ? renderMeetingDetail(state.detailMeeting, state.timetable.periods, cols).split('\n')
@@ -4,7 +4,7 @@ import { captureFooterHint, digitTabHint, fitFooterHint, passiveFooterHint } fro
4
4
  import { ListField, computeMaxVisible } from '../fields/list-field.js';
5
5
  import { TextField } from '../fields/text-field.js';
6
6
  import { renderSchedule, hubShortcuts, termProgress, } from './schedule-render.js';
7
- import { handleGridKey, todayGridCursor } from './schedule-grid-cursor.js';
7
+ import { handleGridKey, todayGridCursor, KEY_ARROW_LEFT, KEY_ARROW_RIGHT, KEY_ENTER_CR, KEY_ENTER_LF, } from './schedule-grid-cursor.js';
8
8
  import { setVimKeysActive } from '../../core/vim-keys.js';
9
9
  import { t } from '../../i18n/index.js';
10
10
  import { pickIcon } from '../../core/icons.js';
@@ -14,11 +14,14 @@ import { loginWithStudentPassword, restoreNbtSession, } from '../../auth/nbt-aut
14
14
  import { createSessionStore } from '../../auth/session-store.js';
15
15
  import { resolveTerm, relevantTerms, writePrivateIcs, isSessionExpired, JWXT_ORIGIN, safeMessage, } from '../../features/student-timetable.js';
16
16
  import { termKey, loadWeekOne, saveWeekOne, saveTimetableCache, saveCurrentPointer, loadCurrentPointer, loadTimetableCache, clearScheduleCache, } from '../../features/schedule-store.js';
17
- import { loadSchoolCalendarOrCache } from '../../features/calendar.js';
17
+ import { loadSchoolCalendarOrCache, peekCalendar } from '../../features/calendar.js';
18
18
  import { currentAcademicWindow, inferWeekOneMonday, } from '@nbtca/nbtcal';
19
19
  import { sanitizeAcademicTerm, sanitizeTimetable } from '../../features/timetable-sanitize.js';
20
20
  import { addLocalDays, parseLocalMonday } from '../../core/calendar-day.js';
21
21
  import { StudentRecordsPanel } from './student-records.js';
22
+ import { termRecap } from '../../features/term-recap.js';
23
+ import { COUNT_UP_MS, recapCards } from './term-recap-render.js';
24
+ import { getCapabilities } from '../../core/capabilities.js';
22
25
  let state = { mode: 'loading' };
23
26
  let session = null;
24
27
  let client = null;
@@ -44,6 +47,20 @@ function gridFooterHint(tabCount, cols) {
44
47
  const quit = `Esc ${dot} q ${trans.menu.hintQuit}`;
45
48
  return fitFooterHint(cols, `${digitTabHint(tabCount)}${local} ${dot} ${labelled} ${dot} ${trans.help.hint}`, `${digitTabHint(tabCount)}${local} ${dot} ${labelled}`, `${digitTabHint(tabCount)}${local} ${dot} ${quit}`, `${local} ${dot} ${labelled}`, `${local} ${dot} ${quit}`, `${local} ${dot} Esc ${dot} q`, local, `Esc ${dot} q`, 'q');
46
49
  }
50
+ const RECAP_STEPS = {
51
+ [KEY_ARROW_RIGHT]: 1,
52
+ [KEY_ENTER_CR]: 1,
53
+ [KEY_ENTER_LF]: 1,
54
+ l: 1,
55
+ [KEY_ARROW_LEFT]: -1,
56
+ h: -1,
57
+ };
58
+ function recapFooterHint(cols) {
59
+ const trans = t();
60
+ const dot = glyph.sep();
61
+ const page = `${pickIcon('← →', 'left/right')} ${trans.recap.footerPage}`;
62
+ return fitFooterHint(cols, `${page} ${dot} Esc ${trans.menu.hintBack} ${dot} q ${trans.menu.hintQuit}`, `${page} ${dot} Esc ${dot} q`, page);
63
+ }
47
64
  function isLifecycleActive(ctx, generation) {
48
65
  return generation === lifecycleGeneration && ctx.signal?.aborted !== true;
49
66
  }
@@ -407,6 +424,12 @@ export const scheduleView = {
407
424
  return renderSchedule(state, new Date(), ctx.bodyRows, ctx.size.cols);
408
425
  },
409
426
  ambient() {
427
+ if (state.mode === 'recap' && state.recap) {
428
+ const { recap, cards, index } = state.recap;
429
+ return index === cards.length - 1
430
+ ? { kind: 'mountain', progress: recap.progress, weeks: recap.weeks }
431
+ : undefined;
432
+ }
410
433
  if (state.mode !== 'public' && state.mode !== 'hub')
411
434
  return undefined;
412
435
  const term = termProgress(state.publicWindow);
@@ -415,6 +438,9 @@ export const scheduleView = {
415
438
  isBusy() {
416
439
  if (state.mode === 'records')
417
440
  return recordsPanel?.isBusy() ?? false;
441
+ if (state.mode === 'recap' && state.recap && !getCapabilities().reducedMotion) {
442
+ return Date.now() - state.recap.shownAt < COUNT_UP_MS;
443
+ }
418
444
  return state.mode === 'loading';
419
445
  },
420
446
  scrollsBody() {
@@ -467,6 +493,8 @@ export const scheduleView = {
467
493
  state.mode === 'termDensity';
468
494
  if (passive)
469
495
  return passiveFooterHint(tabCount, cols);
496
+ if (state.mode === 'recap')
497
+ return recapFooterHint(cols);
470
498
  return state.mode === 'hub' || state.mode === 'week'
471
499
  ? gridFooterHint(tabCount, cols)
472
500
  : undefined;
@@ -502,6 +530,7 @@ export const scheduleView = {
502
530
  return returnToHub();
503
531
  }
504
532
  if (state.mode === 'week' ||
533
+ state.mode === 'recap' ||
505
534
  state.mode === 'unresolved' ||
506
535
  state.mode === 'termPicker' ||
507
536
  state.mode === 'termDensity') {
@@ -659,6 +688,21 @@ export const scheduleView = {
659
688
  state = { ...state, mode: 'termDensity' };
660
689
  return;
661
690
  }
691
+ if (shortcut.key === 'r') {
692
+ const calendar = peekCalendar();
693
+ const recap = termRecap(tt, hubWeekOne, new Date(), calendar && ((start, end) => calendar.inRange(start, end).length));
694
+ if (!recap) {
695
+ state = { ...state, statusMessage: t().recap.empty };
696
+ delete state.exportedPath;
697
+ return;
698
+ }
699
+ state = {
700
+ ...state,
701
+ mode: 'recap',
702
+ recap: { recap, cards: recapCards(recap), index: 0, shownAt: Date.now() },
703
+ };
704
+ return;
705
+ }
662
706
  if (shortcut.key === 'u') {
663
707
  state = { ...state, mode: 'unresolved' };
664
708
  return;
@@ -754,6 +798,24 @@ export const scheduleView = {
754
798
  returnToHub();
755
799
  return;
756
800
  }
801
+ case 'recap': {
802
+ if (!state.recap) {
803
+ returnToHub();
804
+ return;
805
+ }
806
+ const step = RECAP_STEPS[key];
807
+ if (step === undefined)
808
+ return;
809
+ const index = state.recap.index + step;
810
+ if (index >= state.recap.cards.length) {
811
+ returnToHub();
812
+ return;
813
+ }
814
+ if (index < 0)
815
+ return;
816
+ state = { ...state, recap: { ...state.recap, index, shownAt: Date.now() } };
817
+ return;
818
+ }
757
819
  case 'termPicker': {
758
820
  const result = state.termField?.handleKey(key);
759
821
  if (!result?.selected)
@@ -2,9 +2,23 @@ import { campusIsoDate } from '@nbtca/nbtcal/timetable';
2
2
  import { c, type, glyph, space, bodyEdge } from '../../core/theme.js';
3
3
  import { clipAnsiToVisualWidth, padEndV, sanitizeTerminalLine, truncate, visualWidth, wrapAnsiToVisualWidth, } from '../../core/text.js';
4
4
  import { spinnerFrame } from '../../core/components/spinner.js';
5
+ import { pickIcon } from '../../core/icons.js';
5
6
  import { isoDayDifference } from '../../core/calendar-day.js';
6
7
  import { displaySemesterLabel } from '../../features/student-timetable.js';
7
8
  import { fmt, getCurrentLanguage, t } from '../../i18n/index.js';
9
+ const SCRAMBLE = '0123456789ABCDF';
10
+ function sealMark() {
11
+ return pickIcon('▒▒▒', '###');
12
+ }
13
+ function scramble(text, progress, frame) {
14
+ if (progress >= 1)
15
+ return text;
16
+ const chars = Array.from(text);
17
+ const settled = Math.floor(Math.max(0, (progress - 0.4) / 0.6) * chars.length);
18
+ return chars
19
+ .map((ch, i) => (i < settled ? ch : (SCRAMBLE[(frame * 7 + i * 13) % SCRAMBLE.length] ?? ch)))
20
+ .join('');
21
+ }
8
22
  const formatters = new Map();
9
23
  function dateText(date, format) {
10
24
  const language = getCurrentLanguage();
@@ -76,23 +90,30 @@ function resultText(grade) {
76
90
  const value = grade.grade ?? t().records.notPublished;
77
91
  return grade.voided ? `${value} ${t().records.voidTag}` : value;
78
92
  }
79
- function gradeRow(grade, width, selected, table) {
93
+ function gradeRow(grade, width, selected, table, sealed) {
80
94
  const marker = selected ? `${glyph.cursor()} ` : ' ';
95
+ const result = sealed ? `${sealMark()} ${t().records.newTag}` : resultText(grade);
96
+ const gradePoint = sealed ? null : grade.gradePoint;
81
97
  if (!table) {
82
98
  return [
83
- pair(marker + grade.courseName, resultText(grade), width),
84
- ` ${[grade.credits === null ? '' : fmt(t().records.credits, { value: grade.credits }), grade.gradePoint === null ? '' : fmt(t().records.gradePoint, { value: grade.gradePoint })].filter(Boolean).join(' · ')}`,
99
+ pair(marker + grade.courseName, result, width),
100
+ ` ${[grade.credits === null ? '' : fmt(t().records.credits, { value: grade.credits }), gradePoint === null ? '' : fmt(t().records.gradePoint, { value: gradePoint })].filter(Boolean).join(' · ')}`,
85
101
  ];
86
102
  }
87
103
  const courseWidth = width - 31;
88
- const value = padEndV(truncate(resultText(grade), 10, '…'), 10);
104
+ const value = padEndV(truncate(result, 10, '…'), 10);
89
105
  const credits = String(grade.credits ?? '—');
90
- const point = String(grade.gradePoint ?? '—');
106
+ const point = sealed ? sealMark().slice(0, 1) : String(grade.gradePoint ?? '—');
91
107
  const plain = `${marker}${padEndV(truncate(grade.courseName, courseWidth, '…'), courseWidth)} ${value} ${padEndV(credits, 7)} ${padEndV(point, 6)}`;
92
108
  if (selected)
93
109
  return [type.cursor(padEndV(plain, width))];
110
+ const styled = sealed
111
+ ? type.active(value)
112
+ : grade.voided || grade.grade === null
113
+ ? c.warn(value)
114
+ : type.heading(value);
94
115
  return [
95
- `${marker}${padEndV(truncate(grade.courseName, courseWidth, '…'), courseWidth)} ${grade.voided || grade.grade === null ? c.warn(value) : type.heading(value)} ${type.hint(padEndV(credits, 7))} ${type.hint(padEndV(point, 6))}`,
116
+ `${marker}${padEndV(truncate(grade.courseName, courseWidth, '…'), courseWidth)} ${styled} ${type.hint(padEndV(credits, 7))} ${type.hint(padEndV(point, 6))}`,
96
117
  ];
97
118
  }
98
119
  function examRow(exam, width, selected, now) {
@@ -113,7 +134,7 @@ function examRow(exam, width, selected, now) {
113
134
  type.hint(truncate(meta, width, '…')),
114
135
  ];
115
136
  }
116
- export function renderStudentRecordDetail(data, index, cols, now) {
137
+ export function renderStudentRecordDetail(data, index, cols, now, seal = { sealed: false }) {
117
138
  const item = data.items[index];
118
139
  if (!item)
119
140
  return [];
@@ -128,13 +149,21 @@ export function renderStudentRecordDetail(data, index, cols, now) {
128
149
  lines.push('');
129
150
  if (data.kind === 'grades') {
130
151
  const grade = item;
131
- add(fmt(trans.gradeValue, { value: grade.grade ?? trans.notPublished }), grade.voided ? c.warn : type.active);
132
- if (grade.voided)
152
+ const hidden = seal.sealed || (seal.reveal !== undefined && seal.reveal.progress < 1);
153
+ const value = seal.sealed
154
+ ? sealMark()
155
+ : seal.reveal
156
+ ? scramble(grade.grade ?? trans.notPublished, seal.reveal.progress, seal.reveal.frame)
157
+ : (grade.grade ?? trans.notPublished);
158
+ add(fmt(trans.gradeValue, { value }), grade.voided && !hidden ? c.warn : type.active);
159
+ if (seal.sealed)
160
+ add(trans.revealHint, type.hint);
161
+ if (grade.voided && !hidden)
133
162
  add(trans.voided, c.warn);
134
163
  lines.push('');
135
164
  if (grade.credits !== null)
136
165
  add(fmt(trans.credits, { value: grade.credits }));
137
- if (grade.gradePoint !== null)
166
+ if (grade.gradePoint !== null && !hidden)
138
167
  add(fmt(trans.gradePoint, { value: grade.gradePoint }));
139
168
  if (grade.courseNature)
140
169
  add(`${trans.courseNature} ${grade.courseNature}`);
@@ -163,11 +192,12 @@ export function renderStudentRecordDetail(data, index, cols, now) {
163
192
  }
164
193
  return lines;
165
194
  }
166
- function summary(data, attention) {
195
+ function summary(data, attention, fresh) {
167
196
  const trans = t().records;
168
197
  if (data.kind === 'grades') {
169
198
  const published = data.items.filter((grade) => grade.grade !== null).length;
170
- return `${fmt(trans.gradeSummary, { published, total: data.items.length })}${attention ? ` · ${trans.needsAttention}` : ''}`;
199
+ const news = fresh > 0 ? ` · ${fmt(trans.newSummary, { count: fresh })}` : '';
200
+ return `${fmt(trans.gradeSummary, { published, total: data.items.length })}${news}${attention ? ` · ${trans.needsAttention}` : ''}`;
171
201
  }
172
202
  const pending = data.items.filter((exam) => !exam.start).length;
173
203
  return `${fmt(trans.examSummary, { total: data.items.length, pending })}${attention ? ` · ${trans.upcomingOnly}` : ''}`;
@@ -192,7 +222,7 @@ export function renderStudentRecordsPanel(state, bodyRows, cols, now) {
192
222
  lines.push(type.hint(pair(term, updated, width)));
193
223
  }
194
224
  if (rows >= 10 && state.data)
195
- lines.push(type.hint(truncate(summary(state.data, state.attention), width, '…')));
225
+ lines.push(type.hint(truncate(summary(state.data, state.attention, state.sealed?.size ?? 0), width, '…')));
196
226
  if (state.query || state.searching)
197
227
  lines.push(type.active(truncate(`/ ${state.query}${state.searching ? '▏' : ''}${state.searching && !state.query ? ` ${trans.searchHint}` : ''}`, width, '…')));
198
228
  if (state.data?.kind === 'exams' && rows >= 15 && !state.query) {
@@ -236,7 +266,7 @@ export function renderStudentRecordsPanel(state, bodyRows, cols, now) {
236
266
  if (!item)
237
267
  continue;
238
268
  const record = state.kind === 'grades'
239
- ? gradeRow(item, listWidth, offset === selected, table)
269
+ ? gradeRow(item, listWidth, offset === selected, table, state.sealed?.has(index ?? -1) === true)
240
270
  : examRow(item, listWidth, offset === selected, now);
241
271
  list.push(...record
242
272
  .slice(0, rowHeight)
@@ -244,7 +274,9 @@ export function renderStudentRecordsPanel(state, bodyRows, cols, now) {
244
274
  }
245
275
  }
246
276
  const detail = split && state.data && indices[selected] !== undefined
247
- ? renderStudentRecordDetail(state.data, indices[selected], width - listWidth - 3, now)
277
+ ? renderStudentRecordDetail(state.data, indices[selected], width - listWidth - 3, now, {
278
+ sealed: state.sealed?.has(indices[selected]) === true,
279
+ })
248
280
  : [];
249
281
  for (let row = 0; row < available; row += 1) {
250
282
  const left = clipAnsiToVisualWidth(list[row] ?? '', listWidth);