@nbtca/prompt 1.5.21 → 1.5.22

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
@@ -28,8 +28,12 @@ Or try it without installing: `npx @nbtca/prompt`.
28
28
  - **Home**: today's classes and the next club events.
29
29
  - **Schedule**: the current term, week, and next break. Log in to the campus
30
30
  system to see your timetable and export it to any calendar app as `.ics`.
31
- Press `a` for personal exam arrangements or `g` for grades. Both are also
32
- available from the public Schedule menu before login.
31
+ Press `a` for personal exam arrangements or `c` for grades. Both are also
32
+ available from the public Schedule menu before login. Use `←` / `→` to switch
33
+ between exams and grades, `↑` / `↓` or `PgUp` / `PgDn` to select courses, and
34
+ `Enter` to read full details. Press `/` to search by course name or code, `f`
35
+ to filter upcoming exams or unpublished and void grades, and `s` to change
36
+ terms. Wide terminals show details beside the list.
33
37
  - **Events**: a countdown to the next event, plus week and month views, search,
34
38
  history, and a one-year activity heatmap.
35
39
  - **Docs**: read and search the knowledge base. It works even when GitHub is
@@ -31,7 +31,7 @@ export function hubShortcuts(tt) {
31
31
  { key: 's', label: trans.timetable.hubSwitchTerm },
32
32
  { key: 'e', label: trans.timetable.hubExport },
33
33
  { key: 'a', label: trans.records.exams },
34
- { key: 'g', label: trans.records.grades },
34
+ { key: 'c', label: trans.records.grades },
35
35
  ];
36
36
  if (tt.unresolvedItems.length > 0) {
37
37
  shortcuts.push({
@@ -328,7 +328,7 @@ async function openStudentRecords(ctx, kind, generation = ++lifecycleGeneration)
328
328
  term.semester === previousTerm.semester) ?? resolveTerm(catalog);
329
329
  pendingRecordsKind = null;
330
330
  const panel = new StudentRecordsPanel(kind, selected, relevantTerms(catalog), session.timetableTransport, () => isLifecycleActive(ctx, generation) && recordsPanel === panel, () => {
331
- pendingRecordsKind = kind;
331
+ pendingRecordsKind = panel.kind;
332
332
  createSessionStore().clear();
333
333
  recordsPanel?.dispose();
334
334
  recordsPanel = null;
@@ -414,6 +414,9 @@ export const scheduleView = {
414
414
  scrollsBody() {
415
415
  return state.mode === 'records' && !recordsPanel?.capturesPageKeys();
416
416
  },
417
+ contextPath() {
418
+ return state.mode === 'records' ? recordsPanel?.contextPath() : undefined;
419
+ },
417
420
  shortcuts() {
418
421
  if (state.mode === 'records')
419
422
  return recordsPanel?.shortcuts() ?? [];
@@ -431,6 +434,8 @@ export const scheduleView = {
431
434
  return [...grid, ...hubShortcuts(state.timetable).map(({ key, label }) => ({ key, label }))];
432
435
  },
433
436
  capturesInput() {
437
+ if (state.mode === 'records')
438
+ return recordsPanel?.capturesInput() ?? false;
434
439
  return (state.mode === 'needsLoginId' ||
435
440
  state.mode === 'needsLoginPassword' ||
436
441
  state.mode === 'needsWeekOne');
@@ -442,7 +447,7 @@ export const scheduleView = {
442
447
  },
443
448
  footerHint(tabCount, cols = Number.POSITIVE_INFINITY) {
444
449
  if (state.mode === 'records')
445
- return passiveFooterHint(tabCount, cols);
450
+ return recordsPanel?.footerHint(tabCount, cols) ?? passiveFooterHint(tabCount, cols);
446
451
  const capturing = state.mode === 'needsLoginId' ||
447
452
  state.mode === 'needsLoginPassword' ||
448
453
  state.mode === 'needsWeekOne';
@@ -515,7 +520,7 @@ export const scheduleView = {
515
520
  return;
516
521
  }
517
522
  case 'records':
518
- if (key === 'x' && !recordsPanel?.capturesPageKeys())
523
+ if (key === 'x' && recordsPanel?.acceptsActions())
519
524
  logout(ctx);
520
525
  else
521
526
  recordsPanel?.handleKey(key, ctx);
@@ -636,7 +641,7 @@ export const scheduleView = {
636
641
  const shortcut = hubShortcuts(tt).find((sc) => sc.key === key);
637
642
  if (!shortcut)
638
643
  return;
639
- if (shortcut.key === 'a' || shortcut.key === 'g') {
644
+ if (shortcut.key === 'a' || shortcut.key === 'c') {
640
645
  void openStudentRecords(ctx, shortcut.key === 'a' ? 'exams' : 'grades');
641
646
  return;
642
647
  }
@@ -0,0 +1,268 @@
1
+ import { campusIsoDate } from '@nbtca/nbtcal/timetable';
2
+ import { c, type, glyph, space, bodyEdge } from '../../core/theme.js';
3
+ import { clipAnsiToVisualWidth, padEndV, sanitizeTerminalLine, truncate, visualWidth, wrapAnsiToVisualWidth, } from '../../core/text.js';
4
+ import { spinnerFrame } from '../../core/components/spinner.js';
5
+ import { isoDayDifference } from '../../core/calendar-day.js';
6
+ import { displaySemesterLabel } from '../../features/student-timetable.js';
7
+ import { fmt, getCurrentLanguage, t } from '../../i18n/index.js';
8
+ const formatters = new Map();
9
+ function dateText(date, format) {
10
+ const language = getCurrentLanguage();
11
+ const key = `${language}:${format}`;
12
+ let formatter = formatters.get(key);
13
+ if (!formatter) {
14
+ formatter = new Intl.DateTimeFormat(language === 'zh' ? 'zh-CN' : 'en-GB', {
15
+ timeZone: 'Asia/Shanghai',
16
+ ...(format !== 'clock'
17
+ ? {
18
+ month: '2-digit',
19
+ day: '2-digit',
20
+ ...(format === 'day' ? { weekday: 'short' } : {}),
21
+ }
22
+ : { hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }),
23
+ });
24
+ formatters.set(key, formatter);
25
+ }
26
+ if (format === 'clock')
27
+ return formatter.format(date);
28
+ const parts = formatter.formatToParts(date);
29
+ const part = (name) => parts.find((entry) => entry.type === name)?.value ?? '';
30
+ if (format === 'shortDay')
31
+ return `${part('month')}/${part('day')}`;
32
+ return language === 'zh'
33
+ ? `${part('month')}/${part('day')} ${part('weekday')}`
34
+ : `${part('weekday')} ${part('day')}/${part('month')}`;
35
+ }
36
+ function examStatus(exam, now) {
37
+ const trans = t().records;
38
+ if (!exam.start || !exam.end)
39
+ return trans.pendingTag;
40
+ if (exam.end <= now)
41
+ return trans.ended;
42
+ if (exam.start <= now)
43
+ return trans.inProgress;
44
+ const days = isoDayDifference(campusIsoDate(now), campusIsoDate(exam.start));
45
+ return days === 0 ? trans.today : days === 1 ? trans.tomorrow : fmt(trans.daysAway, { days });
46
+ }
47
+ function examTime(exam, compact = false) {
48
+ return exam.start && exam.end
49
+ ? `${dateText(exam.start, compact ? 'shortDay' : 'day')} ${dateText(exam.start, 'clock')}–${dateText(exam.end, 'clock')}`
50
+ : (exam.timeText ?? t().records.timeUnavailable);
51
+ }
52
+ export function visibleStudentRecords(data, query, attention, now) {
53
+ if (!data)
54
+ return [];
55
+ const needle = query.trim().normalize('NFKC').toLowerCase();
56
+ return data.items.flatMap((item, index) => {
57
+ if (needle &&
58
+ !`${item.courseName} ${item.courseCode ?? ''}`
59
+ .normalize('NFKC')
60
+ .toLowerCase()
61
+ .includes(needle))
62
+ return [];
63
+ if (attention &&
64
+ ('end' in item ? item.end !== null && item.end <= now : item.grade !== null && !item.voided))
65
+ return [];
66
+ return [index];
67
+ });
68
+ }
69
+ function pair(left, right, width) {
70
+ const room = width - visualWidth(right) - 2;
71
+ if (room < 4)
72
+ return truncate(left, width, '…');
73
+ return padEndV(truncate(left, room, '…'), width - visualWidth(right)) + right;
74
+ }
75
+ function resultText(grade) {
76
+ const value = grade.grade ?? t().records.notPublished;
77
+ return grade.voided ? `${value} ${t().records.voidTag}` : value;
78
+ }
79
+ function gradeRow(grade, width, selected, table) {
80
+ const marker = selected ? `${glyph.cursor()} ` : ' ';
81
+ if (!table) {
82
+ 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(' · ')}`,
85
+ ];
86
+ }
87
+ const courseWidth = width - 31;
88
+ const value = padEndV(truncate(resultText(grade), 10, '…'), 10);
89
+ const credits = String(grade.credits ?? '—');
90
+ const point = String(grade.gradePoint ?? '—');
91
+ const plain = `${marker}${padEndV(truncate(grade.courseName, courseWidth, '…'), courseWidth)} ${value} ${padEndV(credits, 7)} ${padEndV(point, 6)}`;
92
+ if (selected)
93
+ return [type.cursor(padEndV(plain, width))];
94
+ 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))}`,
96
+ ];
97
+ }
98
+ function examRow(exam, width, selected, now) {
99
+ const main = pair(`${selected ? glyph.cursor() : ' '} ${exam.courseName}`, examStatus(exam, now), width);
100
+ const location = [
101
+ exam.location,
102
+ width >= 54 && exam.seat ? fmt(t().records.seat, { value: exam.seat }) : null,
103
+ ]
104
+ .filter(Boolean)
105
+ .join(' · ');
106
+ const meta = ` ${examTime(exam, width < 54)}${location ? ` · ${location}` : ''}`;
107
+ return [
108
+ selected
109
+ ? type.cursor(padEndV(main, width))
110
+ : exam.end && exam.end <= now
111
+ ? type.hint(main)
112
+ : type.heading(main),
113
+ type.hint(truncate(meta, width, '…')),
114
+ ];
115
+ }
116
+ export function renderStudentRecordDetail(data, index, cols, now) {
117
+ const item = data.items[index];
118
+ if (!item)
119
+ return [];
120
+ const trans = t().records;
121
+ const lines = [];
122
+ const add = (value, style = type.body) => {
123
+ lines.push(...wrapAnsiToVisualWidth(style(sanitizeTerminalLine(value)), cols));
124
+ };
125
+ add(item.courseName, type.heading);
126
+ if (item.courseCode)
127
+ add(item.courseCode, type.hint);
128
+ lines.push('');
129
+ if (data.kind === 'grades') {
130
+ const grade = item;
131
+ add(fmt(trans.gradeValue, { value: grade.grade ?? trans.notPublished }), grade.voided ? c.warn : type.active);
132
+ if (grade.voided)
133
+ add(trans.voided, c.warn);
134
+ lines.push('');
135
+ if (grade.credits !== null)
136
+ add(fmt(trans.credits, { value: grade.credits }));
137
+ if (grade.gradePoint !== null)
138
+ add(fmt(trans.gradePoint, { value: grade.gradePoint }));
139
+ if (grade.courseNature)
140
+ add(`${trans.courseNature} ${grade.courseNature}`);
141
+ if (grade.examNature)
142
+ add(`${trans.examNature} ${grade.examNature}`);
143
+ if (grade.remark) {
144
+ lines.push('');
145
+ add(grade.remark, type.hint);
146
+ }
147
+ }
148
+ else {
149
+ const exam = item;
150
+ add(examStatus(exam, now), exam.start ? type.active : c.warn);
151
+ add(examTime(exam));
152
+ lines.push('');
153
+ if (exam.location)
154
+ add(`${trans.location} ${exam.location}`);
155
+ if (exam.campus)
156
+ add(`${trans.campus} ${exam.campus}`);
157
+ if (exam.seat)
158
+ add(fmt(trans.seat, { value: exam.seat }), type.heading);
159
+ if (exam.examName)
160
+ add(`${trans.examName} ${exam.examName}`);
161
+ if (exam.assessment)
162
+ add(`${trans.assessment} ${exam.assessment}`);
163
+ }
164
+ return lines;
165
+ }
166
+ function summary(data, attention) {
167
+ const trans = t().records;
168
+ if (data.kind === 'grades') {
169
+ const published = data.items.filter((grade) => grade.grade !== null).length;
170
+ return `${fmt(trans.gradeSummary, { published, total: data.items.length })}${attention ? ` · ${trans.needsAttention}` : ''}`;
171
+ }
172
+ const pending = data.items.filter((exam) => !exam.start).length;
173
+ return `${fmt(trans.examSummary, { total: data.items.length, pending })}${attention ? ` · ${trans.upcomingOnly}` : ''}`;
174
+ }
175
+ export function renderStudentRecordsPanel(state, bodyRows, cols, now) {
176
+ const rows = Math.max(0, Math.floor(bodyRows));
177
+ const width = Math.max(1, bodyEdge(cols) - (cols > 6 ? space.indent.length : 0));
178
+ const indent = cols > 6 ? space.indent : '';
179
+ const trans = t().records;
180
+ const lines = [];
181
+ const tabs = ['exams', 'grades']
182
+ .map((kind) => (kind === state.kind ? type.active(`[${trans[kind]}]`) : type.hint(trans[kind])))
183
+ .join(' ');
184
+ lines.push(visualWidth(tabs) <= width ? tabs : type.heading(truncate(trans[state.kind], width, '…')));
185
+ if (rows >= 6) {
186
+ const term = `${state.term.academicYearLabel} · ${displaySemesterLabel(state.term)}`;
187
+ const updated = state.attention && rows < 10
188
+ ? trans.filtered
189
+ : state.data
190
+ ? `${trans.updated} ${dateText(state.data.fetchedAt, 'clock')}`
191
+ : '';
192
+ lines.push(type.hint(pair(term, updated, width)));
193
+ }
194
+ if (rows >= 10 && state.data)
195
+ lines.push(type.hint(truncate(summary(state.data, state.attention), width, '…')));
196
+ if (state.query || state.searching)
197
+ lines.push(type.active(truncate(`/ ${state.query}${state.searching ? '▏' : ''}${state.searching && !state.query ? ` ${trans.searchHint}` : ''}`, width, '…')));
198
+ if (state.data?.kind === 'exams' && rows >= 15 && !state.query) {
199
+ const next = state.data.items.find((exam) => exam.start && exam.end && exam.end > now);
200
+ if (next) {
201
+ lines.push('');
202
+ lines.push(type.active(truncate(`${trans.nextExam} · ${examStatus(next, now)} · ${next.courseName}`, width, '…')));
203
+ lines.push(type.hint(truncate(`${examTime(next)}${next.location ? ` · ${next.location}` : ''}`, width, '…')));
204
+ }
205
+ }
206
+ if (rows >= 10)
207
+ lines.push('');
208
+ const indices = visibleStudentRecords(state.data, state.query, state.attention, now);
209
+ const selected = Math.min(Math.max(0, state.selected), Math.max(0, indices.length - 1));
210
+ const split = width >= 94 && rows >= 12 && indices.length > 0;
211
+ const listWidth = split ? Math.floor(width * 0.6) : width;
212
+ const table = state.kind === 'grades' && listWidth >= 54 && rows >= 9 && indices.length > 0;
213
+ if (table) {
214
+ lines.push(type.hint(` ${padEndV(trans.course, listWidth - 31)} ${padEndV(trans.result, 10)} ${padEndV(trans.creditLabel, 7)} ${trans.pointLabel}`));
215
+ lines.push(type.hint(glyph.rule().repeat(width)));
216
+ }
217
+ const available = Math.max(0, rows - lines.length - 1);
218
+ const rowHeight = table || rows < 7 ? 1 : 2;
219
+ const pageSize = Math.max(1, Math.floor(available / rowHeight));
220
+ const start = Math.floor(selected / pageSize) * pageSize;
221
+ const list = [];
222
+ if (state.pending)
223
+ list.push(type.hint(`${spinnerFrame()} ${trans.loading}`));
224
+ else if (state.error)
225
+ list.push(...wrapAnsiToVisualWidth(c.warn(state.error), listWidth));
226
+ else if (indices.length === 0) {
227
+ const filtered = Boolean(state.query || state.attention);
228
+ list.push(...wrapAnsiToVisualWidth(filtered ? trans.noMatches : state.kind === 'grades' ? trans.noGrades : trans.noExams, listWidth));
229
+ list.push('');
230
+ list.push(...wrapAnsiToVisualWidth(type.hint(filtered ? trans.clearFilters : trans.emptyHint), listWidth));
231
+ }
232
+ else if (state.data) {
233
+ for (let offset = start; offset < Math.min(indices.length, start + pageSize); offset += 1) {
234
+ const index = indices[offset];
235
+ const item = index === undefined ? undefined : state.data.items[index];
236
+ if (!item)
237
+ continue;
238
+ const record = state.kind === 'grades'
239
+ ? gradeRow(item, listWidth, offset === selected, table)
240
+ : examRow(item, listWidth, offset === selected, now);
241
+ list.push(...record
242
+ .slice(0, rowHeight)
243
+ .map((line) => offset === selected && !table && state.kind === 'grades' ? type.active(line) : line));
244
+ }
245
+ }
246
+ const detail = split && state.data && indices[selected] !== undefined
247
+ ? renderStudentRecordDetail(state.data, indices[selected], width - listWidth - 3, now)
248
+ : [];
249
+ for (let row = 0; row < available; row += 1) {
250
+ const left = clipAnsiToVisualWidth(list[row] ?? '', listWidth);
251
+ lines.push(split ? `${padEndV(left, listWidth)} ${type.hint(glyph.bar())} ${detail[row] ?? ''}` : left);
252
+ }
253
+ const count = indices.length ? `${selected + 1}/${indices.length}` : '';
254
+ const actions = (state.searching
255
+ ? [trans.searchFooter, 'Enter · Esc']
256
+ : state.pending
257
+ ? ['←→ · x']
258
+ : [
259
+ `s ${trans.termAction} · / ${trans.searchAction} · f ${state.attention ? trans.allRecords : trans.filterAction} · r ${trans.refresh} · x ${t().timetable.hubLogout}`,
260
+ 's · / · f · r · x',
261
+ 's / f r x',
262
+ ]).find((value) => visualWidth(value) + visualWidth(count) + 2 <= width) ?? '';
263
+ lines.push(type.hint(pair(actions, count, width)));
264
+ return {
265
+ lines: lines.slice(0, rows).map((line) => indent + clipAnsiToVisualWidth(line, width)),
266
+ pageSize,
267
+ };
268
+ }
@@ -1,11 +1,14 @@
1
1
  import { JWXT_ORIGIN } from '../../config/campus.js';
2
- import { loadingLines } from '../../core/components/spinner.js';
3
2
  import { wrapAnsiWithIndent } from '../../core/text.js';
3
+ import { space, type, glyph } from '../../core/theme.js';
4
+ import { setVimKeysActive } from '../../core/vim-keys.js';
4
5
  import { isSessionExpired, safeMessage, displaySemesterLabel, } from '../../features/student-timetable.js';
5
- import { createStudentRecordsClient, } from '../../features/student-records-client.js';
6
- import { renderStudentRecords } from '../../features/student-records-render.js';
6
+ import { createStudentRecordsClient } from '../../features/student-records-client.js';
7
7
  import { t } from '../../i18n/index.js';
8
8
  import { ListField, computeMaxVisible, renderListFieldWithContext } from '../fields/list-field.js';
9
+ import { TextField } from '../fields/text-field.js';
10
+ import { fitFooterHint, passiveFooterHint } from '../chrome.js';
11
+ import { renderStudentRecordsPanel, renderStudentRecordDetail, visibleStudentRecords, } from './student-records-render.js';
9
12
  export class StudentRecordsPanel {
10
13
  kind;
11
14
  term;
@@ -16,8 +19,16 @@ export class StudentRecordsPanel {
16
19
  data;
17
20
  error;
18
21
  termsField;
22
+ searchField;
23
+ previousQuery = '';
24
+ query = '';
25
+ attention = false;
26
+ selected = 0;
27
+ pageSize = 1;
28
+ detailIndex;
19
29
  controller;
20
30
  pending = false;
31
+ results = new Map();
21
32
  constructor(kind, term, catalog, transport, isActive, onSessionExpired) {
22
33
  this.kind = kind;
23
34
  this.term = term;
@@ -36,7 +47,9 @@ export class StudentRecordsPanel {
36
47
  this.pending = true;
37
48
  this.error = undefined;
38
49
  this.data = undefined;
50
+ this.results.delete(this.kind);
39
51
  this.termsField = undefined;
52
+ this.detailIndex = undefined;
40
53
  ctx.resetScroll();
41
54
  ctx.rerender();
42
55
  try {
@@ -44,6 +57,11 @@ export class StudentRecordsPanel {
44
57
  if (signal.aborted || !this.isActive())
45
58
  return;
46
59
  this.data = data;
60
+ this.results.set(data.kind, data);
61
+ const next = data.kind === 'exams'
62
+ ? data.items.findIndex((exam) => exam.start && exam.end && exam.end > new Date())
63
+ : -1;
64
+ this.selected = Math.max(0, this.indices().indexOf(next));
47
65
  }
48
66
  catch (error) {
49
67
  if (signal.aborted || !this.isActive())
@@ -63,64 +81,181 @@ export class StudentRecordsPanel {
63
81
  dispose() {
64
82
  this.controller?.abort();
65
83
  this.data = undefined;
84
+ this.results.clear();
66
85
  this.termsField = undefined;
86
+ this.searchField = undefined;
87
+ this.query = '';
88
+ setVimKeysActive(true);
67
89
  }
68
90
  isBusy() {
69
91
  return this.pending;
70
92
  }
93
+ capturesInput() {
94
+ return this.searchField !== undefined;
95
+ }
71
96
  capturesPageKeys() {
72
- return this.termsField !== undefined;
97
+ return this.detailIndex === undefined;
98
+ }
99
+ acceptsActions() {
100
+ return !this.termsField && !this.searchField;
101
+ }
102
+ contextPath() {
103
+ return [
104
+ t().records[this.kind],
105
+ `${this.term.academicYearLabel} · ${displaySemesterLabel(this.term)}`,
106
+ ];
107
+ }
108
+ footerHint(tabCount, cols) {
109
+ if (this.searchField)
110
+ return fitFooterHint(cols, `${t().records.searchFooter} · Ctrl+C ${t().menu.hintQuit}`, 'Enter · Esc · Ctrl+C', 'Esc Ctrl+C');
111
+ if (this.pending)
112
+ return passiveFooterHint(tabCount, cols);
113
+ if (this.termsField || this.detailIndex !== undefined)
114
+ return passiveFooterHint(tabCount, cols);
115
+ const trans = t();
116
+ return fitFooterHint(cols, `${glyph.updown()} ${trans.records.moveAction} · ${glyph.enter()} ${trans.records.detailAction} · ←→ ${trans.records.switchView} · Esc ${trans.menu.hintBack} · ? ${trans.help.title}`, `${glyph.updown()} ${glyph.enter()} ${trans.records.detailAction} · ←→ ${trans.records.switchView} · Esc · ?`, `${glyph.updown()} ${glyph.enter()} · ←→ · Esc · ?`, 'Esc · ?');
73
117
  }
74
118
  handleBack() {
75
- if (!this.termsField)
76
- return false;
77
- this.termsField = undefined;
78
- return true;
119
+ if (this.searchField) {
120
+ this.query = this.previousQuery;
121
+ this.searchField = undefined;
122
+ this.selected = 0;
123
+ setVimKeysActive(true);
124
+ return true;
125
+ }
126
+ if (this.termsField) {
127
+ this.termsField = undefined;
128
+ return true;
129
+ }
130
+ if (this.detailIndex !== undefined) {
131
+ this.detailIndex = undefined;
132
+ return true;
133
+ }
134
+ if (this.query || this.attention) {
135
+ this.query = '';
136
+ this.attention = false;
137
+ this.selected = 0;
138
+ return true;
139
+ }
140
+ return false;
79
141
  }
80
142
  shortcuts() {
81
- return this.pending || this.termsField
82
- ? []
83
- : [
84
- { key: 's', label: t().records.switchTerm },
85
- { key: 'r', label: t().records.refresh },
143
+ if (this.searchField || this.termsField)
144
+ return [];
145
+ if (this.pending)
146
+ return [
147
+ { key: '← →', label: t().records.switchView },
86
148
  { key: 'x', label: t().timetable.hubLogout },
87
149
  ];
150
+ const trans = t();
151
+ return [
152
+ ...(this.detailIndex === undefined
153
+ ? [
154
+ { key: glyph.updown(), label: trans.records.moveAction },
155
+ { key: glyph.enter(), label: trans.records.detailAction },
156
+ ]
157
+ : []),
158
+ { key: '← →', label: trans.records.switchView },
159
+ ...(this.detailIndex === undefined
160
+ ? [
161
+ { key: '/', label: trans.records.searchAction },
162
+ {
163
+ key: 'f',
164
+ label: this.kind === 'exams'
165
+ ? trans.records.upcomingFilter
166
+ : trans.records.attentionFilter,
167
+ },
168
+ ]
169
+ : []),
170
+ { key: 's', label: trans.records.switchTerm },
171
+ { key: 'r', label: trans.records.refresh },
172
+ { key: 'x', label: trans.timetable.hubLogout },
173
+ ];
88
174
  }
89
175
  render(ctx) {
90
176
  if (this.termsField) {
91
177
  this.termsField.setMaxVisible(computeMaxVisible(ctx.bodyRows));
92
178
  return renderListFieldWithContext([], this.termsField, ctx.bodyRows, ctx.size.cols);
93
179
  }
94
- if (this.pending)
95
- return loadingLines(t().common.loading, ctx.size.cols);
96
- const lines = this.data
97
- ? renderStudentRecords(this.data, this.term, ctx.size.cols)
98
- : wrapAnsiWithIndent(this.error ?? t().timetable.genericError, ctx.size.cols, ' ');
99
- return [
100
- ...lines,
101
- '',
102
- ...wrapAnsiWithIndent(`[s] ${t().records.switchTerm} · [r] ${t().records.refresh} · [x] ${t().timetable.hubLogout}`, ctx.size.cols, ' '),
103
- ];
180
+ if (this.detailIndex !== undefined && this.data) {
181
+ const index = this.detailIndex;
182
+ return [
183
+ ...wrapAnsiWithIndent(type.hint(t().records.detailHint), ctx.size.cols, space.indent),
184
+ '',
185
+ ...renderStudentRecordDetail(this.data, index, Math.max(1, ctx.size.cols - 6), new Date()).map((line) => space.indent + line),
186
+ ];
187
+ }
188
+ const rendered = renderStudentRecordsPanel({
189
+ kind: this.kind,
190
+ term: this.term,
191
+ data: this.data,
192
+ pending: this.pending,
193
+ error: this.error,
194
+ selected: this.selected,
195
+ query: this.query,
196
+ attention: this.attention,
197
+ searching: this.searchField !== undefined,
198
+ }, ctx.bodyRows, ctx.size.cols, new Date());
199
+ this.pageSize = rendered.pageSize;
200
+ return rendered.lines;
201
+ }
202
+ indices() {
203
+ return visibleStudentRecords(this.data, this.query, this.attention, new Date());
104
204
  }
105
205
  handleKey(key, ctx) {
206
+ if (this.searchField) {
207
+ const result = this.searchField.handleKey(key);
208
+ this.query = this.searchField.currentValue;
209
+ this.selected = 0;
210
+ if (result.cancelled)
211
+ this.handleBack();
212
+ else if (result.submitted !== undefined) {
213
+ this.searchField = undefined;
214
+ setVimKeysActive(true);
215
+ }
216
+ return;
217
+ }
106
218
  if (this.termsField) {
107
219
  const result = this.termsField.handleKey(key);
108
- if (result.cancelled || result.selected === '__back__') {
220
+ if (result.cancelled || result.selected === '__back__')
109
221
  this.termsField = undefined;
110
- }
111
222
  else if (result.selected) {
112
223
  const term = this.catalog.find((candidate) => `${candidate.academicYear}:${candidate.semester}` === result.selected);
113
224
  if (term) {
114
225
  this.term = term;
226
+ this.results.clear();
227
+ this.query = '';
228
+ this.attention = false;
229
+ this.selected = 0;
115
230
  void this.load(ctx);
116
231
  }
117
232
  }
118
233
  return;
119
234
  }
235
+ if (key === '\x1b[C' || key === '\x1b[D') {
236
+ this.controller?.abort();
237
+ this.kind = this.kind === 'exams' ? 'grades' : 'exams';
238
+ this.detailIndex = undefined;
239
+ this.query = '';
240
+ this.attention = false;
241
+ this.selected = 0;
242
+ this.error = undefined;
243
+ ctx.resetScroll();
244
+ const cached = this.results.get(this.kind);
245
+ if (cached) {
246
+ this.data = cached;
247
+ this.pending = false;
248
+ }
249
+ else
250
+ void this.load(ctx);
251
+ return;
252
+ }
120
253
  if (this.pending)
121
254
  return;
122
- if (key === 'r')
255
+ if (key === 'r') {
123
256
  void this.load(ctx);
257
+ return;
258
+ }
124
259
  if (key === 's') {
125
260
  this.termsField = new ListField({
126
261
  title: t().records.switchTerm,
@@ -134,6 +269,41 @@ export class StudentRecordsPanel {
134
269
  initialIndex: Math.max(0, this.catalog.findIndex((term) => term.academicYear === this.term.academicYear && term.semester === this.term.semester)),
135
270
  });
136
271
  ctx.resetScroll();
272
+ return;
273
+ }
274
+ if (this.detailIndex !== undefined)
275
+ return;
276
+ if (key === '/') {
277
+ this.previousQuery = this.query;
278
+ this.searchField = new TextField({ message: t().records.searchPrompt, allowEmpty: true });
279
+ this.query = '';
280
+ this.selected = 0;
281
+ setVimKeysActive(false);
282
+ return;
283
+ }
284
+ if (key === 'f') {
285
+ this.attention = !this.attention;
286
+ this.selected = 0;
287
+ return;
288
+ }
289
+ const count = this.indices().length;
290
+ const last = Math.max(0, count - 1);
291
+ this.selected = Math.min(last, this.selected);
292
+ if (key === '\x1b[A')
293
+ this.selected = Math.max(0, this.selected - 1);
294
+ if (key === '\x1b[B')
295
+ this.selected = Math.min(last, this.selected + 1);
296
+ if (key === '\x1b[5~')
297
+ this.selected = Math.max(0, this.selected - this.pageSize);
298
+ if (key === '\x1b[6~' || key === ' ')
299
+ this.selected = Math.min(last, this.selected + this.pageSize);
300
+ if (key === '\x1b[H')
301
+ this.selected = 0;
302
+ if (key === '\x1b[F')
303
+ this.selected = last;
304
+ if ((key === '\r' || key === '\n') && count > 0) {
305
+ this.detailIndex = this.indices()[this.selected];
306
+ ctx.resetScroll();
137
307
  }
138
308
  }
139
309
  }
@@ -229,7 +229,48 @@
229
229
  "switchTerm": "Switch term",
230
230
  "exportNeedsTime": "Some exam times are unpublished. A complete exam calendar cannot be exported yet.",
231
231
  "invalidExportOptions": "Use a nonempty --output path for exams without --json.",
232
- "exported": "Exported the exam calendar to {file}."
232
+ "exported": "Exported the exam calendar to {file}.",
233
+ "pendingTag": "Pending",
234
+ "ended": "Ended",
235
+ "inProgress": "In progress",
236
+ "today": "Today",
237
+ "tomorrow": "Tomorrow",
238
+ "daysAway": "In {days}d",
239
+ "voidTag": "Void",
240
+ "courseNature": "Course type",
241
+ "examNature": "Attempt",
242
+ "location": "Room",
243
+ "campus": "Campus",
244
+ "examName": "Exam",
245
+ "assessment": "Assessment",
246
+ "gradeSummary": "{published}/{total} courses published",
247
+ "examSummary": "{total} exams · {pending} awaiting time",
248
+ "needsAttention": "Needs attention",
249
+ "upcomingOnly": "Upcoming + pending",
250
+ "updated": "Updated",
251
+ "nextExam": "Next exam",
252
+ "course": "Course",
253
+ "result": "Grade",
254
+ "creditLabel": "Credits",
255
+ "pointLabel": "Points",
256
+ "loading": "Querying the selected term…",
257
+ "noMatches": "No courses match this view.",
258
+ "clearFilters": "Press Esc to clear the search and filter.",
259
+ "emptyHint": "Press s to check another term.",
260
+ "termAction": "Term",
261
+ "searchAction": "Search",
262
+ "filterAction": "Filter",
263
+ "detailAction": "Details",
264
+ "moveAction": "Select course",
265
+ "switchView": "Switch exams / grades",
266
+ "searchPrompt": "Search courses",
267
+ "searchHint": "Course name or code",
268
+ "allRecords": "All",
269
+ "detailHint": "Esc returns to the list",
270
+ "searchFooter": "Enter apply · Esc cancel",
271
+ "upcomingFilter": "Upcoming exams",
272
+ "attentionFilter": "Unpublished / void grades",
273
+ "filtered": "Filtered"
233
274
  },
234
275
  "timetable": {
235
276
  "menuTitle": "My Timetable",
@@ -229,7 +229,48 @@
229
229
  "switchTerm": "切换学期",
230
230
  "exportNeedsTime": "部分考试尚未公布时间,暂时无法导出完整的考试日历。",
231
231
  "invalidExportOptions": "请使用非空的 --output 路径导出考试日历,并且不要同时使用 --json。",
232
- "exported": "考试日历已导出至 {file}。"
232
+ "exported": "考试日历已导出至 {file}。",
233
+ "pendingTag": "待定",
234
+ "ended": "已结束",
235
+ "inProgress": "进行中",
236
+ "today": "今天",
237
+ "tomorrow": "明天",
238
+ "daysAway": "{days}天后",
239
+ "voidTag": "作废",
240
+ "courseNature": "课程性质",
241
+ "examNature": "考试性质",
242
+ "location": "考场",
243
+ "campus": "校区",
244
+ "examName": "考试名称",
245
+ "assessment": "考核方式",
246
+ "gradeSummary": "共 {total} 门课程,已公布 {published} 门",
247
+ "examSummary": "共 {total} 场考试,{pending} 场时间待定",
248
+ "needsAttention": "仅待关注",
249
+ "upcomingOnly": "仅待参加及时间待定",
250
+ "updated": "更新于",
251
+ "nextExam": "下一场考试",
252
+ "course": "课程",
253
+ "result": "成绩",
254
+ "creditLabel": "学分",
255
+ "pointLabel": "绩点",
256
+ "loading": "正在查询这个学期…",
257
+ "noMatches": "没有符合条件的课程。",
258
+ "clearFilters": "按 Esc 清除搜索和筛选。",
259
+ "emptyHint": "按 s 切换学期,查看历史记录。",
260
+ "termAction": "学期",
261
+ "searchAction": "搜索",
262
+ "filterAction": "筛选",
263
+ "detailAction": "详情",
264
+ "moveAction": "选择课程",
265
+ "switchView": "切换考试和成绩",
266
+ "searchPrompt": "搜索课程",
267
+ "searchHint": "输入课程名或课程代码",
268
+ "allRecords": "全部",
269
+ "detailHint": "按 Esc 返回列表",
270
+ "searchFooter": "Enter 确认 · Esc 取消",
271
+ "upcomingFilter": "待参加的考试",
272
+ "attentionFilter": "待公布或作废的成绩",
273
+ "filtered": "筛选中"
233
274
  },
234
275
  "timetable": {
235
276
  "menuTitle": "我的课表",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nbtca/prompt",
3
- "version": "1.5.21",
3
+ "version": "1.5.22",
4
4
  "type": "module",
5
5
  "main": "dist/index.js",
6
6
  "exports": {