@nbtca/prompt 1.5.14 → 1.5.16

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.
@@ -1,12 +1,12 @@
1
- import { fetchFeed, parseCalendar, createCalendar, FeedFetchError, FeedParseError, eventToICS, } from '@nbtca/nbtcal';
1
+ import { fetchFeedConditional, parseCalendar, createCalendar, FeedFetchError, FeedParseError, eventToICS, } from '@nbtca/nbtcal';
2
2
  import chalk from 'chalk';
3
3
  import { c, type, space, glyph } from '../core/theme.js';
4
4
  import { pickIcon } from '../core/icons.js';
5
5
  import { padEndV, sanitizeTerminalLine, sanitizeTerminalText, truncate, visualWidth, wrapAnsiWithIndent, wrapAnsiToVisualWidth, } from '../core/text.js';
6
6
  import { t } from '../i18n/index.js';
7
- import { addLocalDays, localDayDifference } from '../core/calendar-day.js';
8
- import { countdownParts, isCountdownUrgent, buildExportFilename } from './calendar-query.js';
9
- import { loadFeedCache, saveFeedCache } from './calendar-store.js';
7
+ import { localDayDifference } from '../core/calendar-day.js';
8
+ import { countdownParts, isCountdownUrgent, buildExportFilename, formatDuration, pastYearRange, } from './calendar-query.js';
9
+ import { loadFeedCache, saveFeedCache, touchFeedCache } from './calendar-store.js';
10
10
  import { writeFileSync, existsSync } from 'fs';
11
11
  import { join } from 'path';
12
12
  function formatDate(date) {
@@ -26,15 +26,18 @@ function formatTime(date) {
26
26
  const MEMO_TTL_MS = 5 * 60 * 1000;
27
27
  let memo;
28
28
  let inFlight;
29
+ function remember(text, validators, fetchedAt) {
30
+ memo = { calendar: createCalendar(parseCalendar(text)), validators, fetchedAt };
31
+ return memo.calendar;
32
+ }
29
33
  export function peekCalendar() {
30
34
  if (memo)
31
35
  return memo.calendar;
32
- const text = loadFeedCache();
33
- if (text === null)
36
+ const cache = loadFeedCache();
37
+ if (cache === null)
34
38
  return undefined;
35
39
  try {
36
- memo = { calendar: createCalendar(parseCalendar(text)), fetchedAt: 0 };
37
- return memo.calendar;
40
+ return remember(cache.text, cache.validators, 0);
38
41
  }
39
42
  catch {
40
43
  return undefined;
@@ -42,12 +45,21 @@ export function peekCalendar() {
42
45
  }
43
46
  async function refetchCalendar(signal) {
44
47
  try {
45
- const text = await fetchFeed(undefined, {
48
+ peekCalendar();
49
+ const result = await fetchFeedConditional(undefined, {
46
50
  timeoutMs: 15000,
47
51
  ...(signal === undefined ? {} : { signal }),
52
+ validators: memo?.validators ?? {},
48
53
  });
49
- memo = { calendar: createCalendar(parseCalendar(text)), fetchedAt: Date.now() };
50
- saveFeedCache(text);
54
+ if (result.status === 'modified') {
55
+ const calendar = remember(result.text, result.validators, Date.now());
56
+ saveFeedCache(result);
57
+ return calendar;
58
+ }
59
+ if (!memo)
60
+ throw new FeedFetchError('Feed request failed: HTTP 304');
61
+ memo = { ...memo, validators: result.validators, fetchedAt: Date.now() };
62
+ touchFeedCache(result.validators);
51
63
  return memo.calendar;
52
64
  }
53
65
  catch (err) {
@@ -88,7 +100,7 @@ export async function loadCalendarOrCache(signal) {
88
100
  }
89
101
  }
90
102
  export function yearHeatmap(calendar, now) {
91
- return calendar.heatmap({ start: addLocalDays(now, -365), end: now, bucket: 'day' });
103
+ return calendar.heatmap({ ...pastYearRange(now), bucket: 'day' });
92
104
  }
93
105
  export function serializeEvents(events) {
94
106
  return events.map((event) => ({
@@ -166,7 +178,22 @@ function styleTitle(title, style) {
166
178
  return style(title);
167
179
  return `${type.hint(match[1])}${match[2]}${style(title.slice(match[0].length))}`;
168
180
  }
169
- export function renderEventBrief(e, now) {
181
+ const TIME_COLUMN = ' 00:00'.length;
182
+ export function eventWhen(e) {
183
+ return e.time ? `${e.date} ${e.time}` : padEndV(e.date, visualWidth(e.date) + TIME_COLUMN);
184
+ }
185
+ export function recurringMark(e) {
186
+ return e.recurring ? ` ${pickIcon('↻', '~')}` : '';
187
+ }
188
+ function hangingLines(marker, content, cols) {
189
+ const width = Number.isFinite(cols) ? Math.max(1, Math.floor(cols)) : Number.POSITIVE_INFINITY;
190
+ const prefixes = [`${space.indent}${marker} `, `${marker} `, marker, ''];
191
+ const prefix = prefixes.find((candidate) => visualWidth(candidate) < width) ?? '';
192
+ const continuation = ' '.repeat(visualWidth(prefix));
193
+ const contentWidth = Math.max(1, width - visualWidth(prefix));
194
+ return wrapAnsiToVisualWidth(content, contentWidth).map((line, index) => `${index === 0 ? prefix : continuation}${line}`);
195
+ }
196
+ export function renderEventBriefLines(e, now, cols = Number.POSITIVE_INFINITY) {
170
197
  const dot = pickIcon('·', '-');
171
198
  const proximity = eventProximity(e.startDate, now);
172
199
  const dateStyle = proximity === 'today'
@@ -176,37 +203,26 @@ export function renderEventBrief(e, now) {
176
203
  : proximity === 'week'
177
204
  ? type.body
178
205
  : type.hint;
179
- const dateTime = `${e.date}${e.time ? ' ' + e.time : ''}`;
180
206
  const marker = proximity === 'today' ? type.active(pickIcon('●', '*')) : dateStyle(pickIcon('·', '-'));
181
207
  const titleStyled = styleTitle(e.title, proximity === 'today' ? type.active : type.body);
182
- const recurringMark = e.recurring ? ` ${type.hint(pickIcon('↻', '~'))}` : '';
183
- return `${space.indent}${marker} ${dateStyle(dateTime)} ${type.hint(dot)} ${titleStyled}${recurringMark}`;
208
+ const content = `${dateStyle(eventWhen(e))} ${type.hint(dot)} ${titleStyled}${type.hint(recurringMark(e))}`;
209
+ return hangingLines(marker, content, cols);
210
+ }
211
+ export function renderEventBrief(e, now) {
212
+ return renderEventBriefLines(e, now)[0] ?? '';
184
213
  }
185
214
  export function renderCountdownBanner(event, now, cols = Number.POSITIVE_INFINITY) {
186
215
  if (!event)
187
216
  return '';
188
217
  const trans = t();
189
218
  const p = countdownParts(event.startDate, now);
190
- const inp = trans.calendar.inPrefix;
191
219
  const when = p.past
192
220
  ? trans.calendar.startingNow
193
- : p.days > 0
194
- ? `${inp} ${p.days}d ${p.hours}h`
195
- : p.hours > 0
196
- ? `${inp} ${p.hours}h ${p.minutes}m`
197
- : `${inp} ${p.minutes}m`;
221
+ : `${trans.calendar.inPrefix} ${formatDuration(p)}`;
198
222
  const whenStyled = isCountdownUrgent(p) ? c.warn(when) : type.hint(when);
199
223
  const dot = pickIcon('·', '-');
200
- const width = Number.isFinite(cols) ? Math.max(1, Math.floor(cols)) : Number.POSITIVE_INFINITY;
201
- const cursor = type.active(glyph.cursor());
202
- const prefixes = [`${space.indent}${cursor} `, `${cursor} `, cursor, ''];
203
- const prefix = prefixes.find((candidate) => visualWidth(candidate) < width) ?? '';
204
- const continuation = ' '.repeat(visualWidth(prefix));
205
- const contentWidth = Math.max(1, width - visualWidth(prefix));
206
224
  const content = `${type.label(trans.calendar.next)} ${dot} ${type.body(event.title)} ${dot} ${whenStyled}`;
207
- return wrapAnsiToVisualWidth(content, contentWidth)
208
- .map((line, index) => `${index === 0 ? prefix : continuation}${line}`)
209
- .join('\n');
225
+ return hangingLines(type.active(glyph.cursor()), content, cols).join('\n');
210
226
  }
211
227
  export function exportEventIcs(event, dir = process.cwd()) {
212
228
  const base = buildExportFilename(event);
@@ -1,5 +1,5 @@
1
1
  import { AsyncLocalStorage } from 'node:async_hooks';
2
- import { createDocsClient } from '@nbtca/docs';
2
+ import { createDocsClient, parseDoc } from '@nbtca/docs';
3
3
  import { createDocsStore } from './docs-store.js';
4
4
  const contextKey = Symbol.for('@nbtca/prompt/docs-fetch-context/v2');
5
5
  const globalWithContext = globalThis;
@@ -182,6 +182,17 @@ function clientFor(signal) {
182
182
  export function peekDocs() {
183
183
  return defaultClient.peekAll();
184
184
  }
185
+ export function peekDocument(item) {
186
+ if (!item.sha)
187
+ return undefined;
188
+ try {
189
+ const content = store.read(`blob-${item.sha}`);
190
+ return content === undefined ? undefined : parseDoc(item.path, content);
191
+ }
192
+ catch {
193
+ return undefined;
194
+ }
195
+ }
185
196
  export function clearDocsClients() {
186
197
  for (const client of clients)
187
198
  client.clear();
@@ -12,7 +12,7 @@ import { t, fmt, getCurrentLanguage } from '../i18n/index.js';
12
12
  import { enterScreen, breadcrumb } from '../core/transitions.js';
13
13
  import { sanitizeTerminalLine, sanitizeTerminalText, truncate } from '../core/text.js';
14
14
  import { isInternalHref, renderMarkdown } from './docs-markdown.js';
15
- import { clearDocsClients, peekDocs, runDocsClientOperation } from './docs-client.js';
15
+ import { clearDocsClients, peekDocs, peekDocument, runDocsClientOperation } from './docs-client.js';
16
16
  import { launchBrowserUrl } from './links.js';
17
17
  function detectTerminalType() {
18
18
  const term = (process.env['TERM'] ?? '').toLowerCase();
@@ -129,6 +129,17 @@ function setMetadata(path, value) {
129
129
  metadataCache.delete(oldest);
130
130
  }
131
131
  }
132
+ function peekDocMetadata(item) {
133
+ const cached = getFreshMetadata(item.path);
134
+ if (cached)
135
+ return cached;
136
+ const page = peekDocument(item);
137
+ if (!page)
138
+ return undefined;
139
+ const metadata = metadataFromPage(page);
140
+ setMetadata(item.path, metadata);
141
+ return metadata;
142
+ }
132
143
  function loadDocMetadata(path, signal) {
133
144
  const cached = getFreshMetadata(path);
134
145
  if (cached)
@@ -586,6 +597,17 @@ export async function fetchDocMetadata(items, signal) {
586
597
  await Promise.all(Array.from({ length: workerCount }, worker));
587
598
  return results;
588
599
  }
600
+ export function peekListedDocs(items) {
601
+ let complete = true;
602
+ const docs = items.map((item) => {
603
+ const metadata = peekDocMetadata(item);
604
+ if (metadata)
605
+ return listedDoc(item, metadata);
606
+ complete = false;
607
+ return item;
608
+ });
609
+ return { docs, complete };
610
+ }
589
611
  export async function fetchSectionMetadata(section, signal) {
590
612
  const files = await fetchDocMetadata(section.files, signal);
591
613
  return { ...section, count: files.length, files };
@@ -670,7 +692,7 @@ async function loadSections() {
670
692
  return null;
671
693
  }
672
694
  s.stop();
673
- warning(trans.docs.stale);
695
+ warning(trans.common.offline);
674
696
  return cached;
675
697
  }
676
698
  }
@@ -988,7 +1010,7 @@ export async function showDocsMenu() {
988
1010
  title: trans.docs.chooseCategory,
989
1011
  options: [
990
1012
  ...sections.map((sec) => ({ value: sec.key, label: sec.label })),
991
- { value: 'search', label: chalk.dim(trans.docs.searchPrompt.replace(':', '')) },
1013
+ { value: 'search', label: chalk.dim(trans.docs.searchPrompt) },
992
1014
  { value: 'browser', label: chalk.dim(trans.docs.openBrowser) },
993
1015
  ],
994
1016
  footer: menuFooter(),
@@ -1,5 +1,5 @@
1
1
  import chalk from 'chalk';
2
- import open from 'open';
2
+ import { spawn } from 'child_process';
3
3
  import { sanitizeTerminalLine } from '../core/text.js';
4
4
  import { fmt, t } from '../i18n/index.js';
5
5
  const BROWSER_LAUNCH_SETTLE_MS = 1000;
@@ -32,9 +32,23 @@ function settleBrowserLauncher(child) {
32
32
  }
33
33
  });
34
34
  }
35
+ function browserCommand(url) {
36
+ if (process.platform === 'darwin')
37
+ return ['open', [url]];
38
+ // rundll32 takes the URL as one argument, so no shell ever parses it.
39
+ if (process.platform === 'win32' || process.env['WSL_DISTRO_NAME']) {
40
+ return ['rundll32.exe', ['url.dll,FileProtocolHandler', url]];
41
+ }
42
+ return ['xdg-open', [url]];
43
+ }
35
44
  export async function launchBrowserUrl(url) {
45
+ if (!/^https?:\/\//i.test(url))
46
+ return false;
36
47
  try {
37
- return await settleBrowserLauncher(await open(url));
48
+ const [command, args] = browserCommand(url);
49
+ const child = spawn(command, args, { stdio: 'ignore', detached: true });
50
+ child.unref();
51
+ return await settleBrowserLauncher(child);
38
52
  }
39
53
  catch {
40
54
  return false;
@@ -1,10 +1,30 @@
1
1
  import { campusDateTime, campusIsoDate, createTimetableSchedule } from '@nbtca/nbtcal/timetable';
2
2
  import { countdownParts, isCountdownUrgent } from './calendar-query.js';
3
- import { c, type, space, glyph } from '../core/theme.js';
3
+ import { c, type, space, glyph, MAX_FRAME_COLS } from '../core/theme.js';
4
4
  import { pickIcon } from '../core/icons.js';
5
5
  import { padEndV, truncate, visualWidth, wrapAnsiToVisualWidth } from '../core/text.js';
6
6
  import { addLocalDays, parseLocalMonday } from '../core/calendar-day.js';
7
7
  import { t, fmt, getCurrentLanguage } from '../i18n/index.js';
8
+ const ellipsis = () => pickIcon('…', '...');
9
+ function clip(text, width) {
10
+ return truncate(text, width, ellipsis());
11
+ }
12
+ export function formatClassCountdown(p) {
13
+ const trans = t().timetable;
14
+ if (p.past)
15
+ return trans.nowLabel;
16
+ const values = { days: String(p.days), hours: String(p.hours), minutes: String(p.minutes) };
17
+ if (p.days > 0)
18
+ return fmt(trans.countdownDays, values);
19
+ if (p.hours > 0)
20
+ return fmt(trans.countdownHours, values);
21
+ return fmt(trans.countdownMinutes, values);
22
+ }
23
+ function formatMinutesLeft(end, now) {
24
+ const p = countdownParts(end, now);
25
+ const minutes = p.days * 1440 + p.hours * 60 + p.minutes;
26
+ return fmt(t().timetable.minutesRemaining, { minutes: String(minutes) });
27
+ }
8
28
  function span(m, periods) {
9
29
  const s = periods.find((p) => p.period === m.startPeriod)?.start ?? '';
10
30
  const e = periods.find((p) => p.period === m.endPeriod)?.end ?? '';
@@ -15,13 +35,7 @@ export function renderNextClassBanner(next, now, cols = Number.POSITIVE_INFINITY
15
35
  if (!next)
16
36
  return '';
17
37
  const p = countdownParts(next.start, now);
18
- const when = p.past
19
- ? trans.timetable.nowLabel
20
- : p.days > 0
21
- ? `${p.days}d ${p.hours}h`
22
- : p.hours > 0
23
- ? `${p.hours}h ${p.minutes}m`
24
- : `${p.minutes}m`;
38
+ const when = formatClassCountdown(p);
25
39
  const styleWhen = isCountdownUrgent(p) ? c.warn : type.hint;
26
40
  const whenStyled = styleWhen(when);
27
41
  const dot = pickIcon('·', '-');
@@ -44,7 +58,7 @@ export function renderNextClassBanner(next, now, cols = Number.POSITIVE_INFINITY
44
58
  const courseWidth = Math.floor(cols - visualWidth(prefix) - visualWidth(suffix));
45
59
  if (courseWidth < 3)
46
60
  continue;
47
- return `${prefix}${type.body(truncate(courseName, courseWidth))}${suffix}`;
61
+ return `${prefix}${type.body(clip(courseName, courseWidth))}${suffix}`;
48
62
  }
49
63
  const countdownOnly = [
50
64
  `${space.indent}${marker} ${whenStyled}`,
@@ -57,7 +71,7 @@ export function renderNextClassBanner(next, now, cols = Number.POSITIVE_INFINITY
57
71
  if (whenWidth === 0)
58
72
  return '';
59
73
  if (whenWidth >= 3)
60
- return styleWhen(truncate(when, whenWidth));
74
+ return styleWhen(clip(when, whenWidth));
61
75
  let compactWhen = '';
62
76
  for (const char of when) {
63
77
  if (visualWidth(compactWhen + char) > whenWidth)
@@ -79,11 +93,28 @@ export function weekdayShortLabel(wd) {
79
93
  ];
80
94
  return labels[wd - 1] ?? '';
81
95
  }
82
- function renderTimeline(meetings, periods, now, isToday, alwaysShowLocation, cursorPeriod, cols = Number.POSITIVE_INFINITY) {
96
+ function weekdayLongLabel(wd) {
97
+ return new Intl.DateTimeFormat(getCurrentLanguage() === 'zh' ? 'zh-CN' : 'en-US', {
98
+ weekday: 'long',
99
+ timeZone: 'UTC',
100
+ }).format(Date.UTC(2024, 0, wd));
101
+ }
102
+ export function lineBudget(cols) {
103
+ return Number.isFinite(cols)
104
+ ? Math.max(1, Math.min(Math.floor(cols), MAX_FRAME_COLS) - visualWidth(space.indent))
105
+ : Number.POSITIVE_INFINITY;
106
+ }
107
+ function renderTimeline(meetings, periods, now, day, alwaysShowLocation, cursorPeriod, cols = Number.POSITIVE_INFINITY) {
83
108
  const trans = t();
109
+ const width = lineBudget(cols);
110
+ const fits = (line) => visualWidth(line) <= width;
84
111
  const sorted = [...meetings].sort((a, b) => a.startPeriod - b.startPeriod);
85
- if (sorted.length === 0)
86
- return `${space.indent}${type.hint(trans.timetable.noClassToday)}`;
112
+ if (sorted.length === 0) {
113
+ const empty = day.isToday
114
+ ? trans.timetable.noClassToday
115
+ : fmt(trans.timetable.noClassOnDay, { weekday: weekdayLongLabel(day.weekday) });
116
+ return `${space.indent}${type.hint(empty)}`;
117
+ }
87
118
  const today = campusIsoDate(now);
88
119
  const minute = Math.floor(now.getTime() / 60_000) * 60_000;
89
120
  const dot = pickIcon('·', '-');
@@ -95,25 +126,20 @@ function renderTimeline(meetings, periods, now, isToday, alwaysShowLocation, cur
95
126
  const startStr = periods.find((p) => p.period === m.startPeriod)?.start ?? '00:00';
96
127
  const endStr = periods.find((p) => p.period === m.endPeriod)?.end ?? '23:59';
97
128
  const end = campusDateTime(today, endStr);
98
- const isLive = isToday && campusDateTime(today, startStr).getTime() <= minute && minute <= end.getTime();
99
- const isDone = isToday && minute > end.getTime();
129
+ const isLive = day.isToday && campusDateTime(today, startStr).getTime() <= minute && minute <= end.getTime();
130
+ const isDone = day.isToday && minute > end.getTime();
100
131
  const isCursor = cursorPeriod !== undefined && m.startPeriod <= cursorPeriod && cursorPeriod <= m.endPeriod;
101
132
  const connector = i === 0 ? topConnector : midConnector;
102
133
  const marker = isLive ? type.active(pickIcon('▶', '>')) : ' ';
103
134
  const timeCol = `${marker}${type.hint(startStr)} ${rule}${connector}${rule}`;
104
135
  const styleName = (name) => isLive ? type.active(name) : isDone ? type.hint(name) : type.body(name);
105
- let statusText = '';
106
- let compactStatusText = '';
107
- if (isDone) {
108
- statusText = trans.timetable.classDone;
109
- compactStatusText = statusText;
110
- }
111
- else if (isLive) {
112
- const remaining = countdownParts(end, now);
113
- const mins = remaining.days * 1440 + remaining.hours * 60 + remaining.minutes;
114
- statusText = `${trans.timetable.classLive} ${dot} ${fmt(trans.timetable.minutesRemaining, { minutes: String(mins) })}`;
115
- compactStatusText = `${mins}m`;
116
- }
136
+ const minutesLeft = isLive ? formatMinutesLeft(end, now) : '';
137
+ const statusText = isDone
138
+ ? trans.timetable.classDone
139
+ : isLive
140
+ ? `${trans.timetable.classLive} ${dot} ${minutesLeft}`
141
+ : '';
142
+ const compactStatusText = isDone ? trans.timetable.classDone : minutesLeft;
117
143
  const showLoc = alwaysShowLocation ? Boolean(m.location) : isLive && Boolean(m.location);
118
144
  const locationText = showLoc ? (m.location ?? '') : '';
119
145
  const renderLine = (name, status, location, currentTimeCol = timeCol, indent = space.indent) => {
@@ -122,57 +148,49 @@ function renderTimeline(meetings, periods, now, isToday, alwaysShowLocation, cur
122
148
  const content = `${currentTimeCol} ${styleName(name)}${statusCol}${locationCol}`;
123
149
  return `${indent}${isCursor ? type.cursor(content) : content}`;
124
150
  };
125
- const full = renderLine(m.courseName, statusText, locationText);
126
- if (!Number.isFinite(cols) || visualWidth(full) <= cols)
127
- return full;
128
- const compactWithLocation = renderLine(m.courseName, compactStatusText, locationText);
129
- if (visualWidth(compactWithLocation) <= cols)
130
- return compactWithLocation;
131
- const compact = renderLine(m.courseName, compactStatusText, '');
132
- if (visualWidth(compact) <= cols)
133
- return compact;
134
- const adaptiveStatuses = compactStatusText ? [compactStatusText, ''] : [''];
135
- for (const status of adaptiveStatuses) {
136
- const courseWidth = Math.floor(cols - visualWidth(renderLine('', status, '')));
137
- if (courseWidth < 3)
151
+ const whole = [
152
+ renderLine(m.courseName, statusText, locationText),
153
+ renderLine(m.courseName, statusText, ''),
154
+ renderLine(m.courseName, compactStatusText, ''),
155
+ ].find(fits);
156
+ if (whole)
157
+ return whole;
158
+ for (const status of compactStatusText ? [compactStatusText, ''] : ['']) {
159
+ const courseWidth = Math.floor(width - visualWidth(renderLine('', status, '')));
160
+ if (courseWidth <= visualWidth(ellipsis()))
138
161
  continue;
139
- return renderLine(truncate(m.courseName, courseWidth), status, '');
162
+ return renderLine(clip(m.courseName, courseWidth), status, '');
140
163
  }
141
164
  const compactTimeCol = `${marker}${type.hint(startStr)}`;
142
165
  for (const indent of [space.indent, '']) {
143
- const courseWidth = Math.floor(cols - visualWidth(renderLine('', '', '', compactTimeCol, indent)));
144
- if (courseWidth < 3)
166
+ const courseWidth = Math.floor(width - visualWidth(renderLine('', '', '', compactTimeCol, indent)));
167
+ if (courseWidth <= visualWidth(ellipsis()))
145
168
  continue;
146
- return renderLine(truncate(m.courseName, courseWidth), '', '', compactTimeCol, indent);
169
+ return renderLine(clip(m.courseName, courseWidth), '', '', compactTimeCol, indent);
147
170
  }
148
- const timeOnly = [`${space.indent}${compactTimeCol}`, compactTimeCol, type.hint(startStr)].find((candidate) => visualWidth(candidate) <= cols);
171
+ const timeOnly = [`${space.indent}${compactTimeCol}`, compactTimeCol, type.hint(startStr)].find(fits);
149
172
  if (timeOnly)
150
173
  return timeOnly;
151
- return type.hint(startStr.slice(0, Math.max(0, Math.floor(cols))));
174
+ return type.hint(startStr.slice(0, Math.max(0, Math.floor(width))));
152
175
  });
153
176
  const last = sorted.at(-1);
154
177
  if (!last)
155
178
  return lines.join('\n');
156
179
  const lastEnd = periods.find((p) => p.period === last.endPeriod)?.end ?? '23:59';
157
- const fullEnd = `${space.indent} ${type.hint(lastEnd)} ${rule}${bottomConnector}${rule} ${type.hint(trans.timetable.timelineEnd)}`;
158
- if (!Number.isFinite(cols) || visualWidth(fullEnd) <= cols) {
159
- lines.push(fullEnd);
160
- }
161
- else {
162
- const compactEnd = [
163
- `${space.indent}${type.hint(lastEnd)} ${rule}${bottomConnector}${rule}`,
164
- `${space.indent}${type.hint(lastEnd)}`,
165
- type.hint(lastEnd),
166
- ].find((candidate) => visualWidth(candidate) <= cols);
167
- lines.push(compactEnd ?? type.hint(lastEnd.slice(0, Math.max(0, Math.floor(cols)))));
168
- }
180
+ const endLine = [
181
+ `${space.indent} ${type.hint(lastEnd)} ${rule}${bottomConnector}${rule} ${type.hint(trans.timetable.timelineEnd)}`,
182
+ `${space.indent}${type.hint(lastEnd)} ${rule}${bottomConnector}${rule}`,
183
+ `${space.indent}${type.hint(lastEnd)}`,
184
+ type.hint(lastEnd),
185
+ ].find(fits);
186
+ lines.push(endLine ?? type.hint(lastEnd.slice(0, Math.max(0, Math.floor(width)))));
169
187
  return lines.join('\n');
170
188
  }
171
189
  export function renderTodayTimeline(meetings, periods, now, cols = Number.POSITIVE_INFINITY) {
172
- return renderTimeline(meetings, periods, now, true, false, undefined, cols);
190
+ return renderTimeline(meetings, periods, now, { weekday: 0, isToday: true }, false, undefined, cols);
173
191
  }
174
- export function renderDayTimeline(meetings, periods, now, isToday, cursorPeriod, cols = Number.POSITIVE_INFINITY) {
175
- return renderTimeline(meetings, periods, now, isToday, true, cursorPeriod, cols);
192
+ export function renderDayTimeline(meetings, periods, now, day, cursorPeriod, cols = Number.POSITIVE_INFINITY) {
193
+ return renderTimeline(meetings, periods, now, day, true, cursorPeriod, cols);
176
194
  }
177
195
  export function renderDaySwitcher(selectedWeekday, todayWeekday, cols = Number.POSITIVE_INFINITY) {
178
196
  const leftArrow = pickIcon('←', '<');
@@ -245,10 +263,13 @@ export function renderWeekGrid(timetable, weekNumber, now, cols = 80, cursor) {
245
263
  });
246
264
  const fixedOverhead = space.indent.length + rowHeadW + 6 * sepW;
247
265
  const availableForCols = Math.max(0, cols - fixedOverhead);
266
+ const evenColW = Math.max(...idealColWidths);
248
267
  const totalIdealColW = idealColWidths.reduce((a, b) => a + b, 0);
249
- const colWidths = totalIdealColW <= availableForCols
250
- ? idealColWidths
251
- : idealColWidths.map((w) => Math.max(3, Math.floor(w * (availableForCols / totalIdealColW))));
268
+ const colWidths = evenColW * 7 <= availableForCols - space.indent.length
269
+ ? idealColWidths.map(() => evenColW)
270
+ : totalIdealColW <= availableForCols
271
+ ? idealColWidths
272
+ : idealColWidths.map((w) => Math.max(3, Math.floor(w * (availableForCols / totalIdealColW))));
252
273
  const totalW = rowHeadW + colWidths.reduce((a, b) => a + b, 0) + 6 * sepW;
253
274
  const startingAt = (wd, period) => week.find((m) => m.weekday === wd && m.startPeriod === period);
254
275
  const continuingAt = (wd, period) => week.find((m) => m.weekday === wd && m.startPeriod < period && period <= m.endPeriod);
@@ -259,7 +280,7 @@ export function renderWeekGrid(timetable, weekNumber, now, cols = 80, cursor) {
259
280
  const d = weekdayShortLabel(wd);
260
281
  const label = wd === todayWd ? `${d}${todayMark}` : d;
261
282
  const colWidth = colWidths[i] ?? 3;
262
- const padded = centerInWidth(truncate(label, colWidth), colWidth);
283
+ const padded = centerInWidth(clip(label, colWidth), colWidth);
263
284
  return wd === todayWd ? type.active(padded) : type.hint(padded);
264
285
  }).join(sep);
265
286
  lines.push(space.indent + blankHead + headerCells);
@@ -277,11 +298,11 @@ export function renderWeekGrid(timetable, weekNumber, now, cols = 80, cursor) {
277
298
  const isContinuation = !starting && continuingAt(wd, p.period);
278
299
  const rawName = starting ? starting.courseName : isContinuation ? connector : emptyGlyph;
279
300
  const rawLoc = starting ? (starting.location ?? '') : isContinuation ? connector : '';
280
- const paddedName = centerInWidth(truncate(rawName, colW), colW);
281
- const paddedLoc = centerInWidth(truncate(rawLoc, colW), colW);
301
+ const paddedName = centerInWidth(clip(rawName, colW), colW);
302
+ const paddedLoc = centerInWidth(clip(rawLoc, colW), colW);
282
303
  if (isCursor) {
283
- nameCells.push(type.cursor(paddedName));
284
- locCells.push(type.cursor(paddedLoc));
304
+ nameCells.push(type.active(centerInWidth(`[${clip(rawName, colW - 2)}]`, colW)));
305
+ locCells.push(starting ? type.body(paddedLoc) : type.hint(paddedLoc));
285
306
  }
286
307
  else if (starting) {
287
308
  nameCells.push(isToday ? type.active(paddedName) : type.body(paddedName));
@@ -301,6 +322,68 @@ export function renderWeekGrid(timetable, weekNumber, now, cols = 80, cursor) {
301
322
  });
302
323
  return lines.join('\n');
303
324
  }
325
+ export function renderWeekAgenda(timetable, weekNumber, now, cols = Number.POSITIVE_INFINITY, cursor, oneLinePerDay = false) {
326
+ const schedule = createTimetableSchedule(timetable);
327
+ const todayWd = schedule.weekdayAt(now);
328
+ const width = lineBudget(cols);
329
+ const todayMark = pickIcon('•', '*');
330
+ const dot = pickIcon('·', '-');
331
+ const pointer = glyph.cursor();
332
+ const labels = WEEKDAY_KEYS.map((_, i) => `${weekdayShortLabel(i + 1)}${i + 1 === todayWd ? todayMark : ''}`);
333
+ const labelW = Math.max(...labels.map(visualWidth));
334
+ const nameColW = Math.max(0, ...schedule.meetingsInWeek(weekNumber).map((m) => visualWidth(m.courseName)));
335
+ const lines = [];
336
+ WEEKDAY_KEYS.forEach((_, i) => {
337
+ const wd = i + 1;
338
+ const meetings = [...schedule.meetingsOnDay(weekNumber, wd)].sort((a, b) => a.startPeriod - b.startPeriod);
339
+ const isSelected = (m) => cursor?.weekday === wd && m.startPeriod <= cursor.period && cursor.period <= m.endPeriod;
340
+ const selectedIndex = Math.max(0, meetings.findIndex(isSelected));
341
+ const label = padEndV(labels[i] ?? '', labelW);
342
+ const head = (row) => {
343
+ const mark = cursor?.weekday === wd && row === selectedIndex
344
+ ? type.active(pointer)
345
+ : ' '.repeat(visualWidth(pointer));
346
+ const day = row > 0 ? ' '.repeat(labelW) : wd === todayWd ? type.active(label) : type.hint(label);
347
+ return `${space.indent}${mark} ${day} `;
348
+ };
349
+ const room = Math.max(1, width - visualWidth(head(0)));
350
+ const nameStyle = (m) => isSelected(m) ? type.active : type.body;
351
+ if (meetings.length === 0) {
352
+ lines.push(`${head(0)}${type.hint(dot)}`);
353
+ return;
354
+ }
355
+ if (oneLinePerDay) {
356
+ let used = 0;
357
+ let text = '';
358
+ for (const [index, m] of meetings.entries()) {
359
+ const sep = index === 0 ? '' : ` ${dot} `;
360
+ const left = room - used - visualWidth(sep);
361
+ if (left < 2) {
362
+ if (used + visualWidth(ellipsis()) + 1 <= room)
363
+ text += ` ${type.hint(ellipsis())}`;
364
+ break;
365
+ }
366
+ const name = clip(m.courseName, left);
367
+ text += `${type.hint(sep)}${nameStyle(m)(name)}`;
368
+ used += visualWidth(sep) + visualWidth(name);
369
+ }
370
+ lines.push(`${head(0)}${text}`);
371
+ return;
372
+ }
373
+ meetings.forEach((m, row) => {
374
+ const start = timetable.periods.find((p) => p.period === m.startPeriod)?.start ?? '';
375
+ const time = `${start} `;
376
+ const nameRoom = room - visualWidth(time);
377
+ const location = m.location ?? '';
378
+ const nameW = [nameColW, visualWidth(m.courseName)].find((w) => w + 3 + visualWidth(location) <= nameRoom);
379
+ const body = location && nameW !== undefined
380
+ ? `${nameStyle(m)(padEndV(m.courseName, nameW))} ${type.hint(location)}`
381
+ : nameStyle(m)(clip(m.courseName, Math.max(1, nameRoom)));
382
+ lines.push(`${head(row)}${type.hint(time)}${body}`);
383
+ });
384
+ });
385
+ return lines;
386
+ }
304
387
  function formatWeekRange(weeks) {
305
388
  if (weeks.length === 0)
306
389
  return '';