@nbtca/prompt 1.3.2 → 1.4.1

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.
Files changed (65) hide show
  1. package/README.md +44 -0
  2. package/SECURITY.md +47 -0
  3. package/dist/app/app.js +202 -0
  4. package/dist/app/chrome.js +104 -0
  5. package/dist/app/fields/list-field.js +174 -0
  6. package/dist/app/fields/text-field.js +38 -0
  7. package/dist/app/frame.js +48 -0
  8. package/dist/app/keys.js +20 -0
  9. package/dist/app/tabs.js +11 -0
  10. package/dist/app/view.js +1 -0
  11. package/dist/app/views/docs-render.js +82 -0
  12. package/dist/app/views/docs.js +457 -0
  13. package/dist/app/views/events-render.js +111 -0
  14. package/dist/app/views/events.js +228 -0
  15. package/dist/app/views/home.js +236 -0
  16. package/dist/app/views/schedule-grid-cursor.js +52 -0
  17. package/dist/app/views/schedule-render.js +317 -0
  18. package/dist/app/views/schedule.js +472 -0
  19. package/dist/app/views/settings-render.js +53 -0
  20. package/dist/app/views/settings.js +153 -0
  21. package/dist/auth/cookie-transport.js +222 -0
  22. package/dist/auth/errors.js +18 -0
  23. package/dist/auth/nbt-auth.js +239 -0
  24. package/dist/auth/session-store.js +118 -0
  25. package/dist/config/paths.js +22 -2
  26. package/dist/core/canvas.js +23 -0
  27. package/dist/core/capabilities.js +42 -0
  28. package/dist/core/components/confirm.js +75 -0
  29. package/dist/core/components/input-session.js +24 -0
  30. package/dist/core/components/menu.js +122 -0
  31. package/dist/core/components/messages.js +16 -0
  32. package/dist/core/components/note.js +18 -0
  33. package/dist/core/components/painter.js +26 -0
  34. package/dist/core/components/screen.js +18 -0
  35. package/dist/core/components/spinner.js +47 -0
  36. package/dist/core/components/text-input.js +98 -0
  37. package/dist/core/logo.js +40 -15
  38. package/dist/core/menu.js +24 -6
  39. package/dist/core/motion.js +86 -0
  40. package/dist/core/text.js +127 -5
  41. package/dist/core/theme.js +61 -0
  42. package/dist/core/transitions.js +19 -0
  43. package/dist/core/ui.js +5 -29
  44. package/dist/features/calendar-heatmap.js +29 -27
  45. package/dist/features/calendar-query.js +50 -0
  46. package/dist/features/calendar.js +192 -98
  47. package/dist/features/docs.js +258 -55
  48. package/dist/features/links.js +7 -4
  49. package/dist/features/schedule-query.js +47 -0
  50. package/dist/features/schedule-render.js +574 -0
  51. package/dist/features/schedule-store.js +73 -0
  52. package/dist/features/schedule-view.js +260 -0
  53. package/dist/features/settings.js +41 -30
  54. package/dist/features/status.js +37 -13
  55. package/dist/features/student-timetable.js +346 -0
  56. package/dist/features/update.js +16 -8
  57. package/dist/i18n/locales/en.json +149 -6
  58. package/dist/i18n/locales/zh.json +149 -6
  59. package/dist/index.js +59 -5
  60. package/dist/logo/ca-dotmatrix-large.txt +26 -0
  61. package/dist/logo/ca-dotmatrix-small.txt +12 -0
  62. package/dist/logo/ca-dotmatrix.txt +18 -16
  63. package/dist/logo/ca-logo.png +0 -0
  64. package/dist/main.js +33 -13
  65. package/package.json +10 -7
@@ -0,0 +1,111 @@
1
+ import { type, space } from '../../core/theme.js';
2
+ import { t } from '../../i18n/index.js';
3
+ import { renderListFieldWithContext } from '../fields/list-field.js';
4
+ import { renderCountdownBanner, renderEventBrief } from '../../features/calendar.js';
5
+ import { renderHeatmap } from '../../features/calendar-heatmap.js';
6
+ import { visualWidth, wrapAnsiToVisualWidth } from '../../core/text.js';
7
+ function wrappedIndentedLines(label, cols, style) {
8
+ const width = Number.isFinite(cols) ? Math.max(1, Math.floor(cols ?? 1)) : Number.POSITIVE_INFINITY;
9
+ const styled = style(label);
10
+ const styledWidth = visualWidth(styled);
11
+ const preferredIndent = visualWidth(space.indent) < width ? space.indent : '';
12
+ const indent = preferredIndent
13
+ && styledWidth > width - visualWidth(preferredIndent)
14
+ && styledWidth <= width
15
+ ? ''
16
+ : preferredIndent;
17
+ const contentWidth = Math.max(1, width - visualWidth(indent));
18
+ return wrapAnsiToVisualWidth(styled, contentWidth).map((line) => `${indent}${line}`);
19
+ }
20
+ function wrappedRenderedLine(line, cols) {
21
+ const content = line.startsWith(space.indent) ? line.slice(space.indent.length) : line;
22
+ return wrappedIndentedLines(content, cols, (value) => value);
23
+ }
24
+ // Lines a fully-expanded hub needs: banner+blank (2) + heatmap+blank (12) +
25
+ // recent-activity heading+up to 5 events+blank (7) + hubField
26
+ // (title+blank+6 options, 8) = 29. Below this, a terminal can't fit the
27
+ // heatmap without pushing the menu into scroll territory — better to keep
28
+ // it as the existing drill-down destination than show a truncated grid.
29
+ const EXPANDED_HUB_MIN_BODY_ROWS = 29;
30
+ function renderHubBody(state, now, bodyRows, cols) {
31
+ const trans = t();
32
+ const lines = [];
33
+ const rows = Number.isFinite(bodyRows)
34
+ ? Math.max(0, Math.floor(bodyRows))
35
+ : Number.POSITIVE_INFINITY;
36
+ const banner = renderCountdownBanner(state.nextEvent, now, cols);
37
+ if (banner)
38
+ lines.push(...banner.split('\n'), '');
39
+ const buckets = state.heatmapBuckets;
40
+ if (bodyRows >= EXPANDED_HUB_MIN_BODY_ROWS && buckets && buckets.length > 0) {
41
+ lines.push(...renderHeatmap(buckets, now, { color: true, cols }).split('\n'));
42
+ lines.push('');
43
+ }
44
+ if (state.recentEvents && state.recentEvents.length > 0) {
45
+ const activityHeading = wrappedIndentedLines(trans.calendar.recentActivity, cols, type.heading);
46
+ const fieldRows = state.hubField
47
+ ? state.hubField.render(Number.POSITIVE_INFINITY, cols).length
48
+ : 0;
49
+ const collectEventLines = (reservedFieldRows) => {
50
+ const budget = Math.max(0, rows - lines.length - activityHeading.length - 1 - reservedFieldRows);
51
+ const collected = [];
52
+ for (const event of state.recentEvents ?? []) {
53
+ const wrapped = wrappedRenderedLine(renderEventBrief(event, now), cols);
54
+ if (collected.length + wrapped.length > budget)
55
+ break;
56
+ collected.push(...wrapped);
57
+ }
58
+ return collected;
59
+ };
60
+ let eventLines = collectEventLines(fieldRows);
61
+ if (eventLines.length === 0 && state.hubField && fieldRows > 3) {
62
+ eventLines = collectEventLines(Math.min(3, rows));
63
+ }
64
+ if (eventLines.length > 0)
65
+ lines.push(...activityHeading, ...eventLines, '');
66
+ }
67
+ if (state.hubField) {
68
+ return renderListFieldWithContext(lines, state.hubField, bodyRows, cols);
69
+ }
70
+ return lines;
71
+ }
72
+ export function renderEvents(state, now, bodyRows = 100, cols) {
73
+ const trans = t();
74
+ switch (state.mode) {
75
+ case 'loading':
76
+ return wrappedIndentedLines(trans.calendar.loading, cols, type.hint);
77
+ case 'hub':
78
+ return renderHubBody(state, now, bodyRows, cols);
79
+ case 'heatmap':
80
+ // renderHeatmap() already prints its own title (space.indent +
81
+ // type.heading), so this mode doesn't add a second heading on top —
82
+ // unlike Schedule's 'week'/'unresolved' modes, which wrap a
83
+ // title-less renderer.
84
+ return state.heatmapBuckets && state.heatmapBuckets.length > 0
85
+ ? renderHeatmap(state.heatmapBuckets, now, { color: true, cols }).split('\n')
86
+ : wrappedIndentedLines(trans.calendar.noEvents, cols, type.hint);
87
+ case 'list':
88
+ return state.listField?.render(bodyRows, cols) ?? [];
89
+ case 'detail': {
90
+ const context = [
91
+ ...wrappedIndentedLines(state.detailTitle ?? '', cols, type.heading),
92
+ ...wrappedIndentedLines(state.detailMeta ?? '', cols, type.hint),
93
+ '',
94
+ ...(state.detailDescription
95
+ ? state.detailDescription.split('\n').flatMap((line) => wrappedIndentedLines(line, cols, type.body))
96
+ : wrappedIndentedLines(trans.calendar.noDescription, cols, type.hint)),
97
+ '',
98
+ ...(state.statusMessage ? [...wrappedIndentedLines(state.statusMessage, cols, type.hint), ''] : []),
99
+ ];
100
+ return state.detailField
101
+ ? renderListFieldWithContext(context, state.detailField, bodyRows, cols)
102
+ : Number.isFinite(bodyRows) ? context.slice(0, Math.max(0, Math.floor(bodyRows))) : context;
103
+ }
104
+ case 'search':
105
+ return state.searchField?.render(cols) ?? [];
106
+ case 'error':
107
+ return wrappedIndentedLines(state.errorMessage ?? trans.calendar.error, cols, type.hint);
108
+ default:
109
+ return [];
110
+ }
111
+ }
@@ -0,0 +1,228 @@
1
+ import { captureFooterHint, passiveFooterHint } from '../chrome.js';
2
+ import { ListField, computeMaxVisible } from '../fields/list-field.js';
3
+ import { TextField } from '../fields/text-field.js';
4
+ import { renderEvents } from './events-render.js';
5
+ import { setVimKeysActive } from '../../core/vim-keys.js';
6
+ import { pickIcon } from '../../core/icons.js';
7
+ import { t } from '../../i18n/index.js';
8
+ import { loadCalendarOrThrow, toDisplayEvent, exportEventIcs } from '../../features/calendar.js';
9
+ import { weekRange, monthRange, filterEvents } from '../../features/calendar-query.js';
10
+ let state = { mode: 'loading' };
11
+ let calendar = null;
12
+ let currentList = [];
13
+ function backLabel() {
14
+ return t().common.back;
15
+ }
16
+ function buildHubField() {
17
+ const trans = t();
18
+ const options = [
19
+ { value: 'upcoming', label: trans.menu.events },
20
+ { value: 'week', label: trans.calendar.thisWeek },
21
+ { value: 'month', label: trans.calendar.thisMonth },
22
+ { value: 'search', label: trans.calendar.search },
23
+ { value: 'past', label: trans.calendar.pastEvents },
24
+ { value: 'heatmap', label: trans.calendar.heatmap.title },
25
+ ];
26
+ return new ListField({ title: trans.menu.events, options });
27
+ }
28
+ function buildListField(title, events, maxVisible) {
29
+ const trans = t();
30
+ const display = events.map(toDisplayEvent);
31
+ const options = [
32
+ ...events.map((_e, i) => ({
33
+ value: String(i),
34
+ label: `${display[i].date}${display[i].time ? ' ' + display[i].time : ''} ${display[i].title}`,
35
+ hint: display[i].location,
36
+ })),
37
+ { value: '__back__', label: backLabel() },
38
+ ];
39
+ return new ListField({
40
+ title: title || trans.menu.events,
41
+ options: options.length > 1 ? options : [{ value: '__back__', label: `${trans.calendar.noEvents} — ${backLabel()}` }],
42
+ maxVisible,
43
+ });
44
+ }
45
+ function showList(title, events, ctx) {
46
+ currentList = events;
47
+ state = { mode: 'list', listField: buildListField(title, events, computeMaxVisible(ctx.bodyRows)) };
48
+ }
49
+ // A glance-panel ceiling, not "browse everything" (this tab's own "Events"
50
+ // list is for that) — just needs to be at least as many as the tallest
51
+ // reasonable terminal could fit; renderHubBody trims further based on the
52
+ // real ctx.bodyRows.
53
+ const RECENT_ACTIVITY_FETCH_CAP = 15;
54
+ function goToHub() {
55
+ const upcoming = calendar ? calendar.upcoming({ days: 30 }) : [];
56
+ state = {
57
+ mode: 'hub',
58
+ hubField: buildHubField(),
59
+ nextEvent: upcoming[0] ? toDisplayEvent(upcoming[0]) : undefined,
60
+ heatmapBuckets: calendar
61
+ ? calendar.heatmap({ start: new Date(Date.now() - 365 * 86400000), end: new Date(), bucket: 'day' })
62
+ : [],
63
+ recentEvents: upcoming.slice(0, RECENT_ACTIVITY_FETCH_CAP).map(toDisplayEvent),
64
+ };
65
+ }
66
+ function showDetail(raw) {
67
+ const trans = t();
68
+ const e = toDisplayEvent(raw);
69
+ const dot = pickIcon('·', '-');
70
+ state = {
71
+ mode: 'detail',
72
+ detailTitle: e.title,
73
+ detailMeta: `${e.date}${e.time ? ' ' + e.time : ''} ${dot} ${e.location}${raw.recurring ? ` ${dot} ${trans.calendar.recurringLabel}` : ''}`,
74
+ detailDescription: e.description,
75
+ detailEvent: raw,
76
+ detailField: new ListField({
77
+ // Empty, not e.title: renderEvents already prints the event title as
78
+ // its own heading right above (detailTitle) -- giving the field the
79
+ // same string a second time repeated it verbatim just above the
80
+ // Export/Back options.
81
+ title: '',
82
+ options: [
83
+ { value: 'export', label: trans.calendar.exportIcs },
84
+ { value: '__back__', label: backLabel() },
85
+ ],
86
+ }),
87
+ };
88
+ }
89
+ export const eventsView = {
90
+ id: 'events',
91
+ title: t().menu.events,
92
+ async load(ctx) {
93
+ state = { mode: 'loading' };
94
+ ctx.rerender();
95
+ try {
96
+ calendar = await loadCalendarOrThrow();
97
+ goToHub();
98
+ }
99
+ catch {
100
+ state = { mode: 'error', errorMessage: t().calendar.error };
101
+ }
102
+ ctx.rerender();
103
+ },
104
+ render(ctx) {
105
+ // Sync the list's scroll window to the *current* terminal size on every
106
+ // frame (not just construction time) — this is what keeps a long list
107
+ // correctly windowed across a live resize.
108
+ state.listField?.setMaxVisible(computeMaxVisible(ctx.bodyRows));
109
+ return renderEvents(state, new Date(), ctx.bodyRows, ctx.size.cols);
110
+ },
111
+ capturesInput() {
112
+ return state.mode === 'search';
113
+ },
114
+ footerHint(tabCount, cols = Number.POSITIVE_INFINITY) {
115
+ if (state.mode === 'search')
116
+ return captureFooterHint(cols);
117
+ // A pure "read this, any key returns to the hub" drill-down (see
118
+ // handleKey below) -- no field to move a cursor within or open an item
119
+ // from, so the generic "move · open" hint would promise keys that
120
+ // don't do that here.
121
+ const passive = state.mode === 'loading' || state.mode === 'error' || state.mode === 'heatmap';
122
+ return passive ? passiveFooterHint(tabCount, cols) : undefined;
123
+ },
124
+ handleBack() {
125
+ if (state.mode === 'list' || state.mode === 'detail' || state.mode === 'search' || state.mode === 'heatmap') {
126
+ if (state.mode === 'search')
127
+ setVimKeysActive(true);
128
+ goToHub();
129
+ return true;
130
+ }
131
+ return false;
132
+ },
133
+ handleKey(key, ctx) {
134
+ if (!calendar)
135
+ return;
136
+ switch (state.mode) {
137
+ case 'hub': {
138
+ const result = state.hubField?.handleKey(key);
139
+ if (!result?.selected)
140
+ return;
141
+ const now = new Date();
142
+ if (result.selected === 'upcoming') {
143
+ showList(t().menu.events, calendar.upcoming({ days: 30 }), ctx);
144
+ return;
145
+ }
146
+ if (result.selected === 'week') {
147
+ const r = weekRange(now);
148
+ showList(t().calendar.thisWeek, calendar.inRange(r.start, r.end), ctx);
149
+ return;
150
+ }
151
+ if (result.selected === 'month') {
152
+ const r = monthRange(now);
153
+ showList(t().calendar.thisMonth, calendar.inRange(r.start, r.end), ctx);
154
+ return;
155
+ }
156
+ if (result.selected === 'past') {
157
+ showList(t().calendar.pastEvents, calendar.past({ days: 30 }).reverse(), ctx);
158
+ return;
159
+ }
160
+ if (result.selected === 'heatmap') {
161
+ state = { ...state, mode: 'heatmap' };
162
+ return;
163
+ }
164
+ if (result.selected === 'search') {
165
+ setVimKeysActive(false);
166
+ state = { mode: 'search', searchField: new TextField({ message: t().calendar.searchPrompt, placeholder: t().calendar.searchPlaceholder, allowEmpty: true }) };
167
+ }
168
+ return;
169
+ }
170
+ // A pure detail/drill-down view with no field of its own — any key
171
+ // returns to the hub, matching Schedule's 'week'/'unresolved' modes.
172
+ case 'heatmap': {
173
+ goToHub();
174
+ return;
175
+ }
176
+ case 'list': {
177
+ const result = state.listField?.handleKey(key);
178
+ if (!result?.selected)
179
+ return;
180
+ if (result.selected === '__back__') {
181
+ goToHub();
182
+ return;
183
+ }
184
+ const raw = currentList[Number.parseInt(result.selected, 10)];
185
+ if (raw)
186
+ showDetail(raw);
187
+ return;
188
+ }
189
+ case 'detail': {
190
+ const result = state.detailField?.handleKey(key);
191
+ if (!result?.selected)
192
+ return;
193
+ if (result.selected === '__back__') {
194
+ showList('', currentList, ctx);
195
+ return;
196
+ }
197
+ if (result.selected === 'export' && state.detailEvent) {
198
+ const res = exportEventIcs(state.detailEvent);
199
+ state = { ...state, statusMessage: res.ok ? `${t().calendar.exportSuccess}: ${res.path}` : `${t().calendar.exportError}: ${res.error ?? ''}` };
200
+ }
201
+ return;
202
+ }
203
+ case 'search': {
204
+ const result = state.searchField?.handleKey(key);
205
+ if (result?.cancelled) {
206
+ setVimKeysActive(true);
207
+ goToHub();
208
+ return;
209
+ }
210
+ if (result?.submitted !== undefined) {
211
+ setVimKeysActive(true);
212
+ const query = result.submitted.trim();
213
+ if (!query || !calendar) {
214
+ goToHub();
215
+ return;
216
+ }
217
+ const now = new Date();
218
+ const pool = calendar.inRange(now, new Date(now.getTime() + 365 * 86400000));
219
+ const results = filterEvents(pool, query);
220
+ showList(`${t().calendar.search}: ${query}`, results, ctx);
221
+ }
222
+ return;
223
+ }
224
+ default:
225
+ return;
226
+ }
227
+ },
228
+ };
@@ -0,0 +1,236 @@
1
+ import { c, type, space, glyph } from '../../core/theme.js';
2
+ import { t } from '../../i18n/index.js';
3
+ import { pickIcon } from '../../core/icons.js';
4
+ import { padEndV, visualWidth, wrapAnsiToVisualWidth } from '../../core/text.js';
5
+ import { peekNextClassLine, peekTodayLines, peekWeekAheadInfo, peekUnresolvedCount } from '../../features/schedule-view.js';
6
+ import { loadCalendarOrThrow, toDisplayEvent, renderEventBrief } from '../../features/calendar.js';
7
+ import { weekdayShortLabel } from '../../features/schedule-render.js';
8
+ import { campusWeekday } from '../../features/schedule-query.js';
9
+ import { passiveFooterHint } from '../chrome.js';
10
+ function wrappedIndentedLines(label, cols, style) {
11
+ const width = Number.isFinite(cols) ? Math.max(1, Math.floor(cols)) : Number.POSITIVE_INFINITY;
12
+ const styled = style(label);
13
+ const preferredIndent = visualWidth(space.indent) < width ? space.indent : '';
14
+ const indent = preferredIndent
15
+ && visualWidth(styled) > width - visualWidth(preferredIndent)
16
+ && visualWidth(styled) <= width
17
+ ? ''
18
+ : preferredIndent;
19
+ const contentWidth = Math.max(1, width - visualWidth(indent));
20
+ return wrapAnsiToVisualWidth(styled, contentWidth).map((line) => `${indent}${line}`);
21
+ }
22
+ function panelHeading(label, cols) {
23
+ return wrappedIndentedLines(label, cols, type.heading);
24
+ }
25
+ function loadingLines(cols) {
26
+ return wrappedIndentedLines(t().common.loading, cols, type.hint);
27
+ }
28
+ function wrappedRenderedLines(line, cols) {
29
+ const content = line.startsWith(space.indent) ? line.slice(space.indent.length) : line;
30
+ return wrappedIndentedLines(content, cols, (value) => value);
31
+ }
32
+ const DAY_PROGRESS_WIDTH = 20;
33
+ /** Pure: a block-character bar for how far into the calendar day `now` is. */
34
+ function renderDayProgress(now, cols) {
35
+ const minutesElapsed = now.getHours() * 60 + now.getMinutes();
36
+ const fraction = Math.min(1, Math.max(0, minutesElapsed / 1440));
37
+ const pct = Math.round(fraction * 100);
38
+ const percentage = `${pct}%`;
39
+ const width = Number.isFinite(cols) ? Math.max(1, Math.floor(cols)) : Number.POSITIVE_INFINITY;
40
+ const indent = visualWidth(space.indent) + 2 + visualWidth(percentage) + 1 <= width ? space.indent : '';
41
+ const gap = visualWidth(indent) + 2 + visualWidth(percentage) + 1 <= width
42
+ ? ' '
43
+ : visualWidth(indent) + 1 + visualWidth(percentage) + 1 <= width ? ' ' : '';
44
+ const barWidth = Math.max(0, Math.min(DAY_PROGRESS_WIDTH, width - visualWidth(indent) - visualWidth(gap) - visualWidth(percentage)));
45
+ const filled = Math.round(fraction * barWidth);
46
+ const filledChar = glyph.barFilled();
47
+ const emptyChar = glyph.barEmpty();
48
+ const bar = filledChar.repeat(filled) + emptyChar.repeat(barWidth - filled);
49
+ return `${indent}${type.body(bar)}${gap}${type.hint(percentage)}`;
50
+ }
51
+ /** Combined class+event density grid for the coming campus week — the one
52
+ * visualization neither Schedule nor Events alone can produce, since it
53
+ * needs both data sources at once. Deliberately coarser (binary, not
54
+ * 5-level) than Schedule's own term-density strip, and deliberately
55
+ * uncolored (see the design spec's "Visual language decision") since it's
56
+ * an overview of two other already-colored things, not a third color
57
+ * language to learn. */
58
+ function renderWeekAheadGrid(classDays, eventDays, cols) {
59
+ const trans = t();
60
+ const hasClassChar = pickIcon('▓▓', '##');
61
+ const freeChar = pickIcon('░░', '..');
62
+ const weekendChar = pickIcon('··', '..');
63
+ const blankCell = ' ';
64
+ const rowLabelW = Math.max(visualWidth(trans.timetable.weekAheadClasses), visualWidth(trans.menu.events)) + 1;
65
+ const days = [1, 2, 3, 4, 5, 6, 7];
66
+ const dayLabels = days.map((wd) => type.hint(weekdayShortLabel(wd))).join(' ');
67
+ const headerLine = `${space.indent}${padEndV('', rowLabelW)}${dayLabels}`;
68
+ // Class row: weekend is hardcoded to the "N/A" glyph regardless of
69
+ // classDays data (campus never has weekend classes) -- the same
70
+ // weekend treatment used throughout the Schedule tab's own renderers.
71
+ const classCells = days.map((wd) => {
72
+ const isWeekend = wd === 6 || wd === 7;
73
+ const glyphChar = isWeekend ? weekendChar : (classDays[wd - 1] ? hasClassChar : freeChar);
74
+ return type.body(glyphChar);
75
+ }).join(' ');
76
+ const classLine = `${space.indent}${type.hint(padEndV(trans.timetable.weekAheadClasses, rowLabelW))}${classCells}`;
77
+ // Event row: deliberately NOT hardcoding weekend -- a club event can
78
+ // happen on a Saturday, so this row checks real data for all 7 days.
79
+ // undefined eventDays (events still loading, or the fetch failed) means
80
+ // "not yet known" -- rendered as blank, not the "free" glyph, to
81
+ // visually distinguish "no data yet" from "checked, nothing happening".
82
+ const eventCells = days.map((wd) => {
83
+ if (!eventDays)
84
+ return blankCell;
85
+ return type.body(eventDays[wd - 1] ? hasClassChar : freeChar);
86
+ }).join(' ');
87
+ const eventLine = `${space.indent}${type.hint(padEndV(trans.menu.events, rowLabelW))}${eventCells}`;
88
+ const legend = `${space.indent}${type.hint(`${hasClassChar} ${trans.timetable.weekAheadBusy} ${freeChar} ${trans.timetable.weekAheadFree} ${weekendChar} ${trans.timetable.weekAheadNone}`)}`;
89
+ const wideLines = [headerLine, classLine, eventLine, legend];
90
+ const width = Number.isFinite(cols) ? Math.max(1, Math.floor(cols)) : Number.POSITIVE_INFINITY;
91
+ if (wideLines.every((line) => visualWidth(line) <= width))
92
+ return wideLines.join('\n');
93
+ const compactHeading = wrappedIndentedLines(`${trans.timetable.weekAheadClasses} / ${trans.menu.events}`, cols, type.hint);
94
+ const compactDays = days.flatMap((wd) => {
95
+ const classCell = wd === 6 || wd === 7
96
+ ? weekendChar
97
+ : classDays[wd - 1] ? hasClassChar : freeChar;
98
+ const eventCell = eventDays
99
+ ? eventDays[wd - 1] ? hasClassChar : freeChar
100
+ : blankCell;
101
+ const row = `${type.hint(weekdayShortLabel(wd))} ${type.body(classCell)} ${type.body(eventCell)}`;
102
+ return wrappedIndentedLines(row, cols, (value) => value);
103
+ });
104
+ const compactLegend = wrappedIndentedLines(`${hasClassChar} ${trans.timetable.weekAheadBusy} ${freeChar} ${trans.timetable.weekAheadFree} ${weekendChar} ${trans.timetable.weekAheadNone}`, cols, type.hint);
105
+ return [...compactHeading, ...compactDays, ...compactLegend].join('\n');
106
+ }
107
+ /** Pure: renders the schedule-first dashboard from already-fetched data. No I/O. */
108
+ export function renderHome(data, now, bodyRows = 100, cols = 80) {
109
+ const trans = t();
110
+ const lines = [];
111
+ // Next class (cache-only, instant).
112
+ const nextClass = data.nextClassLine !== undefined && data.nextClassLine.trim().length > 0
113
+ ? wrappedRenderedLines(data.nextClassLine, cols)
114
+ : wrappedIndentedLines(trans.timetable.noNextClass, cols, type.hint);
115
+ lines.push(...panelHeading(trans.timetable.nextClass, cols));
116
+ lines.push(...nextClass);
117
+ lines.push('');
118
+ // Today's classes (cache-only, instant).
119
+ lines.push(...panelHeading(trans.timetable.hubToday, cols));
120
+ lines.push(renderDayProgress(now, cols));
121
+ if (data.todayLines && data.todayLines.length > 0) {
122
+ for (const line of data.todayLines)
123
+ lines.push(...wrappedRenderedLines(line, cols));
124
+ }
125
+ else {
126
+ lines.push(...wrappedIndentedLines(trans.timetable.noClassToday, cols, type.hint));
127
+ }
128
+ lines.push('');
129
+ // Week overview (Part D): only when the student has a set-up, in-term
130
+ // personal timetable -- mirrors peekWeekAheadInfo's own "not set up yet
131
+ // / term hasn't started" -> null contract, hiding the whole panel rather
132
+ // than showing empty/misleading cells.
133
+ if (data.weekAhead) {
134
+ lines.push(...panelHeading(trans.timetable.weekOverviewTitle, cols));
135
+ lines.push(...renderWeekAheadGrid(data.weekAhead.classDays, data.weekAhead.eventDays, cols).split('\n'));
136
+ lines.push('');
137
+ }
138
+ // Unresolved schedule items (Part E): surfaced directly on Home instead
139
+ // of only inside Schedule's own hub menu -- same c.warn + ⚠ treatment
140
+ // buildHubField() (schedule.ts) already uses for this exact condition,
141
+ // matching the "everything that needs your attention, in one place"
142
+ // spirit of a gh-status-like control center.
143
+ if ((data.unresolvedCount ?? 0) > 0) {
144
+ lines.push(...wrappedIndentedLines(`${pickIcon('⚠', '!')} ${trans.timetable.hubUnresolved} · ${data.unresolvedCount}`, cols, c.warn));
145
+ lines.push('');
146
+ }
147
+ // Upcoming events (network, best-effort). How many fit is whatever room
148
+ // is actually left after next-class/today above — on a tall terminal
149
+ // that's most of `data.eventLines`; on a normal one, still just a few,
150
+ // same as before this was ever adaptive.
151
+ lines.push(...panelHeading(trans.menu.events, cols));
152
+ if (data.eventLines && data.eventLines.length > 0) {
153
+ const remaining = Number.isFinite(bodyRows)
154
+ ? Math.max(0, Math.floor(bodyRows) - lines.length)
155
+ : Number.POSITIVE_INFINITY;
156
+ let usedRows = 0;
157
+ for (const line of data.eventLines) {
158
+ const wrapped = wrappedRenderedLines(line, cols);
159
+ if (usedRows + wrapped.length > remaining) {
160
+ if (usedRows === 0 && remaining === 0)
161
+ lines.push(...wrapped);
162
+ break;
163
+ }
164
+ lines.push(...wrapped);
165
+ usedRows += wrapped.length;
166
+ }
167
+ }
168
+ else if (data.loading) {
169
+ lines.push(...loadingLines(cols));
170
+ }
171
+ else if (data.eventsError) {
172
+ lines.push(...wrappedIndentedLines(trans.calendar.error, cols, type.hint));
173
+ }
174
+ else {
175
+ lines.push(...wrappedIndentedLines(trans.calendar.noEvents, cols, type.hint));
176
+ }
177
+ return lines;
178
+ }
179
+ let data = { loading: true };
180
+ export const homeView = {
181
+ id: 'home',
182
+ title: 'Home',
183
+ footerHint(tabCount, cols = Number.POSITIVE_INFINITY) {
184
+ return passiveFooterHint(tabCount, cols);
185
+ },
186
+ async load(ctx) {
187
+ // Schedule panels are cache-only and instant — populate them
188
+ // synchronously first. weekAheadSync is computed once here and reused
189
+ // below (peekWeekAheadInfo is itself cache-only/cheap, but capturing
190
+ // its result avoids a second, redundant cache read for weekStartDate).
191
+ const weekAheadSync = peekWeekAheadInfo();
192
+ try {
193
+ data = {
194
+ loading: true,
195
+ nextClassLine: peekNextClassLine(),
196
+ todayLines: peekTodayLines(),
197
+ unresolvedCount: peekUnresolvedCount(),
198
+ weekAhead: weekAheadSync ? { classDays: weekAheadSync.classDays } : undefined,
199
+ };
200
+ }
201
+ catch {
202
+ data = { loading: true };
203
+ }
204
+ ctx.rerender();
205
+ // Events is the only networked panel; best-effort. Fetches the calendar
206
+ // exactly once and reuses that same Calendar instance for both the
207
+ // upcoming-events list below and the week-ahead event row (when there's
208
+ // a personal timetable to correlate it against) — not two separate
209
+ // network round-trips for what both come from the same public feed.
210
+ const HOME_EVENT_FETCH_CAP = 15;
211
+ try {
212
+ const cal = await loadCalendarOrThrow();
213
+ const now = new Date();
214
+ const items = cal.upcoming({ days: 30 }).slice(0, HOME_EVENT_FETCH_CAP).map(toDisplayEvent);
215
+ const eventLines = items.map((e) => renderEventBrief(e, now));
216
+ let weekAhead = data.weekAhead;
217
+ if (weekAheadSync) {
218
+ const weekEnd = new Date(weekAheadSync.weekStartDate.getTime() + 7 * 86400000);
219
+ const weekEvents = cal.inRange(weekAheadSync.weekStartDate, weekEnd);
220
+ const daySet = new Set(weekEvents.map((e) => campusWeekday(e.start)));
221
+ weekAhead = { classDays: weekAheadSync.classDays, eventDays: [1, 2, 3, 4, 5, 6, 7].map((wd) => daySet.has(wd)) };
222
+ }
223
+ data = { ...data, eventLines, weekAhead };
224
+ }
225
+ catch {
226
+ data = { ...data, eventsError: true };
227
+ }
228
+ finally {
229
+ data = { ...data, loading: false };
230
+ ctx.rerender();
231
+ }
232
+ },
233
+ render(ctx) {
234
+ return renderHome(data, new Date(), ctx.bodyRows, ctx.size.cols);
235
+ },
236
+ };
@@ -0,0 +1,52 @@
1
+ import { meetingAtCursor } from '../../features/schedule-query.js';
2
+ export const KEY_ARROW_LEFT = '\x1b[D';
3
+ export const KEY_ARROW_RIGHT = '\x1b[C';
4
+ export const KEY_ARROW_UP = '\x1b[A';
5
+ export const KEY_ARROW_DOWN = '\x1b[B';
6
+ export const KEY_ENTER_CR = '\r';
7
+ export const KEY_ENTER_LF = '\n';
8
+ /** The cursor's starting position on entering hub/week mode: today's own
9
+ * weekday (falling back to Monday on a weekend, since the grid's Sat/Sun
10
+ * columns are always empty for a personal timetable) and the first period
11
+ * this term's own period table actually defines. */
12
+ export function defaultGridCursor(todayWeekday, periods) {
13
+ const sorted = [...periods].sort((a, b) => a.period - b.period);
14
+ const firstPeriod = sorted[0]?.period ?? 1;
15
+ const weekday = todayWeekday >= 1 && todayWeekday <= 5 ? todayWeekday : 1;
16
+ return { weekday, period: firstPeriod };
17
+ }
18
+ /** Moves the cursor one weekday left/right, clamped to [1, 7] with no
19
+ * wraparound -- a 7-day week has a real fixed edge, unlike a scrollable
20
+ * list where wrapping back to the top makes sense. */
21
+ export function moveCursorWeekday(cursor, delta) {
22
+ return { ...cursor, weekday: Math.max(1, Math.min(7, cursor.weekday + delta)) };
23
+ }
24
+ /** Moves the cursor to the previous/next *defined* period in the sorted
25
+ * period table (not period±1 -- real period numbers aren't always
26
+ * contiguous), clamped at the first/last period with no wraparound. */
27
+ export function moveCursorPeriod(cursor, periods, delta) {
28
+ const sorted = [...periods].sort((a, b) => a.period - b.period);
29
+ if (sorted.length === 0)
30
+ return cursor;
31
+ const idx = sorted.findIndex((p) => p.period === cursor.period);
32
+ const nextIdx = Math.max(0, Math.min(sorted.length - 1, (idx === -1 ? 0 : idx) + delta));
33
+ return { ...cursor, period: sorted[nextIdx].period };
34
+ }
35
+ /** Pure key-to-action mapping shared by hub mode's inline grid and the
36
+ * standalone full-screen 'week' mode -- both are cursor-navigable over the
37
+ * exact same rules, so this is the one place that logic lives. */
38
+ export function handleGridKey(key, cursor, tt, week) {
39
+ if (key === KEY_ARROW_LEFT)
40
+ return { kind: 'moveCursor', cursor: moveCursorWeekday(cursor, -1) };
41
+ if (key === KEY_ARROW_RIGHT)
42
+ return { kind: 'moveCursor', cursor: moveCursorWeekday(cursor, 1) };
43
+ if (key === KEY_ARROW_UP)
44
+ return { kind: 'moveCursor', cursor: moveCursorPeriod(cursor, tt.periods, -1) };
45
+ if (key === KEY_ARROW_DOWN)
46
+ return { kind: 'moveCursor', cursor: moveCursorPeriod(cursor, tt.periods, 1) };
47
+ if (key === KEY_ENTER_CR || key === KEY_ENTER_LF) {
48
+ const meeting = meetingAtCursor(tt.meetings, week, cursor);
49
+ return meeting ? { kind: 'openDetail', meeting } : { kind: 'none' };
50
+ }
51
+ return { kind: 'none' };
52
+ }