@nbtca/prompt 1.5.13 → 1.5.15

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,5 +1,4 @@
1
1
  import { marked } from 'marked';
2
- import { markedTerminal } from 'marked-terminal';
3
2
  import chalk from 'chalk';
4
3
  import { createHash } from 'node:crypto';
5
4
  import { runMenu, menuFooter } from '../core/components/menu.js';
@@ -11,9 +10,9 @@ import { spawn, execFileSync } from 'child_process';
11
10
  import { URLS } from '../config/data.js';
12
11
  import { t, fmt, getCurrentLanguage } from '../i18n/index.js';
13
12
  import { enterScreen, breadcrumb } from '../core/transitions.js';
14
- import { loadDocsIndex, saveDocsIndex } from './docs-store.js';
15
- import { sanitizeTerminalLine, sanitizeTerminalText, stripAnsi, truncate } from '../core/text.js';
16
- import { clearDocsClients, runDocsClientOperation } from './docs-client.js';
13
+ import { sanitizeTerminalLine, sanitizeTerminalText, truncate } from '../core/text.js';
14
+ import { isInternalHref, renderMarkdown } from './docs-markdown.js';
15
+ import { clearDocsClients, peekDocs, runDocsClientOperation } from './docs-client.js';
17
16
  import { launchBrowserUrl } from './links.js';
18
17
  function detectTerminalType() {
19
18
  const term = (process.env['TERM'] ?? '').toLowerCase();
@@ -55,93 +54,6 @@ function hasGlow() {
55
54
  _hasGlow ??= commandExists('glow');
56
55
  return _hasGlow;
57
56
  }
58
- function isInternalHref(href) {
59
- return /^\.{0,2}\/./.test(href);
60
- }
61
- let _markedConfigured = false;
62
- export function ensureMarkedConfigured() {
63
- if (_markedConfigured)
64
- return;
65
- _markedConfigured = true;
66
- const terminalType = getTerminalType();
67
- const extension = markedTerminal(getRendererOptions(terminalType));
68
- const renderer = extension.renderer ?? (extension.renderer = {});
69
- const renderExternalLink = renderer.link;
70
- if (renderExternalLink) {
71
- renderer.link = function (token) {
72
- if (isInternalHref(token.href))
73
- return chalk.cyan.underline(token.text);
74
- return renderExternalLink.call(this, token);
75
- };
76
- }
77
- const renderPlainText = renderer.text;
78
- if (renderPlainText) {
79
- renderer.text = function (token) {
80
- const withTokens = token;
81
- if (Array.isArray(withTokens.tokens) && withTokens.tokens.length > 0) {
82
- return this.parser.parseInline(withTokens.tokens);
83
- }
84
- return renderPlainText.call(this, token);
85
- };
86
- }
87
- marked.use(extension);
88
- }
89
- function getRendererOptions(type) {
90
- const width = 80;
91
- const unicodeTableChars = {
92
- top: '─',
93
- 'top-mid': '┬',
94
- 'top-left': '┌',
95
- 'top-right': '┐',
96
- bottom: '─',
97
- 'bottom-mid': '┴',
98
- 'bottom-left': '└',
99
- 'bottom-right': '┘',
100
- left: '│',
101
- 'left-mid': '├',
102
- mid: '─',
103
- 'mid-mid': '┼',
104
- right: '│',
105
- 'right-mid': '┤',
106
- middle: '│',
107
- };
108
- const asciiTableChars = {
109
- top: '-',
110
- 'top-mid': '+',
111
- 'top-left': '+',
112
- 'top-right': '+',
113
- bottom: '-',
114
- 'bottom-mid': '+',
115
- 'bottom-left': '+',
116
- 'bottom-right': '+',
117
- left: '|',
118
- 'left-mid': '+',
119
- mid: '-',
120
- 'mid-mid': '+',
121
- right: '|',
122
- 'right-mid': '+',
123
- middle: '|',
124
- };
125
- return {
126
- width,
127
- emoji: true,
128
- unescape: true,
129
- showSectionPrefix: false,
130
- firstHeading: chalk.bold.cyan,
131
- heading: chalk.bold.white,
132
- codespan: chalk.yellowBright,
133
- code: chalk.yellow,
134
- blockquote: chalk.italic.gray,
135
- strong: chalk.bold,
136
- em: chalk.italic,
137
- del: chalk.dim.strikethrough,
138
- link: chalk.cyan,
139
- href: chalk.cyan.underline,
140
- tableOptions: {
141
- chars: type === 'basic' ? asciiTableChars : unicodeTableChars,
142
- },
143
- };
144
- }
145
57
  const RENDER_CACHE_TTL_MS = 10 * 60 * 1000;
146
58
  const RENDER_CACHE_MAX = 50;
147
59
  const renderCache = new Map();
@@ -229,15 +141,13 @@ function loadDocMetadata(path, signal) {
229
141
  return metadata;
230
142
  });
231
143
  }
232
- function normalizeRenderedTasks(content, type) {
233
- if (type !== 'basic')
234
- return content;
235
- return content
236
- .split('\n')
237
- .map((line) => /^\s*(?:[-*+]|\d+[.)])\s+\[X\](?:\s|$)/.test(stripAnsi(line))
238
- ? line.replace('[X]', '[x]')
239
- : line)
240
- .join('\n');
144
+ function memoizedRender(tokens) {
145
+ let last = null;
146
+ return (width) => {
147
+ if (last?.width !== width)
148
+ last = { width, lines: renderMarkdown(tokens, width) };
149
+ return last.lines;
150
+ };
241
151
  }
242
152
  async function loadRenderedDoc(filePath, signal) {
243
153
  const generation = cacheGeneration;
@@ -253,11 +163,10 @@ async function loadRenderedDoc(filePath, signal) {
253
163
  const terminalType = getTerminalType();
254
164
  const cleaned = cleanMarkdownContent(rawContent, terminalType);
255
165
  const title = sanitizeTerminalLine(page.title) || cleanFileName(filePath.split('/').pop() ?? filePath);
256
- const markedOutput = normalizeRenderedTasks(await marked(cleaned), terminalType);
257
166
  const renderedDoc = {
258
167
  fingerprint,
259
168
  cleaned,
260
- rendered: chalk.level === 0 ? sanitizeTerminalText(markedOutput) : markedOutput,
169
+ render: memoizedRender(marked.lexer(cleaned)),
261
170
  title,
262
171
  readTime: estimateReadTime(cleaned),
263
172
  };
@@ -305,9 +214,7 @@ function processFencedCodeBlocks(content) {
305
214
  result.push(`> ${icon} **${firstToken}** — _${trans.docs.mermaidHint}_`);
306
215
  }
307
216
  else {
308
- if (blockLang)
309
- result.push(`\`${blockLang}\``);
310
- result.push(fence);
217
+ result.push(fence + blockLang);
311
218
  result.push(...blockBody);
312
219
  result.push(fence);
313
220
  }
@@ -600,7 +507,6 @@ export function resolveInternalHref(href, fromPath) {
600
507
  return target;
601
508
  }
602
509
  export async function loadDocForReader(filePath, signal) {
603
- ensureMarkedConfigured();
604
510
  const { renderedDoc } = await loadRenderedDoc(filePath, signal);
605
511
  const seen = new Set();
606
512
  const links = [];
@@ -614,7 +520,7 @@ export async function loadDocForReader(filePath, signal) {
614
520
  return {
615
521
  path: filePath,
616
522
  title: renderedDoc.title,
617
- lines: renderedDoc.rendered.split('\n'),
523
+ render: renderedDoc.render,
618
524
  links,
619
525
  };
620
526
  }
@@ -743,20 +649,11 @@ export async function fetchAllDocs(signal) {
743
649
  return runDocsClientOperation(signal, (client) => client.listAll());
744
650
  }
745
651
  export async function fetchSections(signal) {
746
- const docs = await fetchAllDocs(signal);
747
- saveDocsIndex(docs);
748
- return buildSections(docs);
652
+ return buildSections(await fetchAllDocs(signal));
749
653
  }
750
654
  export function peekSections() {
751
- const docs = loadDocsIndex();
752
- if (!docs)
753
- return null;
754
- try {
755
- return buildSections(docs);
756
- }
757
- catch {
758
- return null;
759
- }
655
+ const docs = peekDocs();
656
+ return docs ? buildSections(docs) : null;
760
657
  }
761
658
  async function loadSections() {
762
659
  const trans = t();
@@ -767,8 +664,14 @@ async function loadSections() {
767
664
  return sections;
768
665
  }
769
666
  catch {
770
- s.error(trans.docs.loadError);
771
- return null;
667
+ const cached = peekSections();
668
+ if (!cached) {
669
+ s.error(trans.docs.loadError);
670
+ return null;
671
+ }
672
+ s.stop();
673
+ warning(trans.docs.stale);
674
+ return cached;
772
675
  }
773
676
  }
774
677
  function pipeToPager(command, args, content, plain = false) {
@@ -814,9 +717,12 @@ export async function displayWithGlow(cleanedMarkdown) {
814
717
  const cols = String(Math.min(process.stdout.columns || 80, 80));
815
718
  return pipeToPager('glow', ['--pager', '--width', cols, '-'], cleanedMarkdown);
816
719
  }
817
- async function displayWithLess(rendered, title, filePath, readTime, toc) {
720
+ async function displayWithLess(doc, filePath) {
818
721
  const trans = t();
819
722
  const cols = Math.min(process.stdout.columns || 80, 80);
723
+ const { title, readTime } = doc;
724
+ const toc = extractTOC(doc.cleaned);
725
+ const rendered = doc.render(cols).join('\n');
820
726
  const rule = chalk.dim('─'.repeat(cols));
821
727
  const tocBlock = toc.length >= 3
822
728
  ? [
@@ -934,20 +840,13 @@ async function showArchivedSection(files) {
934
840
  }
935
841
  async function viewMarkdownFile(filePath) {
936
842
  const trans = t();
937
- ensureMarkedConfigured();
938
843
  const s = createSpinner(`${trans.docs.loadingFile}: ${filePath}`);
939
844
  try {
940
845
  const { rawContent, renderedDoc } = await loadRenderedDoc(filePath);
941
846
  s.stop(`${chalk.bold(renderedDoc.title)} ${chalk.dim(renderedDoc.readTime)}`);
942
- const toc = extractTOC(renderedDoc.cleaned);
943
- if (chalk.level > 0 && hasGlow()) {
944
- if (!(await displayWithGlow(renderedDoc.cleaned))) {
945
- await displayWithLess(renderedDoc.rendered, renderedDoc.title, filePath, renderedDoc.readTime, toc);
946
- }
947
- }
948
- else {
949
- await displayWithLess(renderedDoc.rendered, renderedDoc.title, filePath, renderedDoc.readTime, toc);
950
- }
847
+ const shownWithGlow = chalk.level > 0 && hasGlow() && (await displayWithGlow(renderedDoc.cleaned));
848
+ if (!shownWithGlow)
849
+ await displayWithLess(renderedDoc, filePath);
951
850
  const needsBrowser = hasMarkdownTable(rawContent) || hasMermaidBlock(rawContent);
952
851
  const action = await runMenu({
953
852
  title: trans.docs.chooseAction,
@@ -1089,7 +988,7 @@ export async function showDocsMenu() {
1089
988
  title: trans.docs.chooseCategory,
1090
989
  options: [
1091
990
  ...sections.map((sec) => ({ value: sec.key, label: sec.label })),
1092
- { value: 'search', label: chalk.dim(trans.docs.searchPrompt.replace(':', '')) },
991
+ { value: 'search', label: chalk.dim(trans.docs.searchPrompt) },
1093
992
  { value: 'browser', label: chalk.dim(trans.docs.openBrowser) },
1094
993
  ],
1095
994
  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,33 +1,49 @@
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 ?? '';
11
31
  return e ? `${s}${pickIcon('–', '-')}${e}` : s;
12
32
  }
13
- export function renderNextClassBanner(next, now, cols = Number.POSITIVE_INFINITY) {
33
+ export function renderNextClassBanner(next, now, cols = Number.POSITIVE_INFINITY, labelled = true) {
14
34
  const trans = t();
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('·', '-');
28
42
  const marker = type.active(glyph.cursor());
29
43
  const separator = ` ${dot} `;
30
- const detailedPrefix = `${space.indent}${marker} ${type.label(trans.timetable.nextClass)}${separator}`;
44
+ const detailedPrefix = labelled
45
+ ? `${space.indent}${marker} ${type.label(trans.timetable.nextClass)}${separator}`
46
+ : `${space.indent}${marker} `;
31
47
  const suffix = `${separator}${whenStyled}`;
32
48
  const courseName = next.meeting.courseName;
33
49
  const location = next.meeting.location ? `${separator}${next.meeting.location}` : '';
@@ -42,7 +58,7 @@ export function renderNextClassBanner(next, now, cols = Number.POSITIVE_INFINITY
42
58
  const courseWidth = Math.floor(cols - visualWidth(prefix) - visualWidth(suffix));
43
59
  if (courseWidth < 3)
44
60
  continue;
45
- return `${prefix}${type.body(truncate(courseName, courseWidth))}${suffix}`;
61
+ return `${prefix}${type.body(clip(courseName, courseWidth))}${suffix}`;
46
62
  }
47
63
  const countdownOnly = [
48
64
  `${space.indent}${marker} ${whenStyled}`,
@@ -55,7 +71,7 @@ export function renderNextClassBanner(next, now, cols = Number.POSITIVE_INFINITY
55
71
  if (whenWidth === 0)
56
72
  return '';
57
73
  if (whenWidth >= 3)
58
- return styleWhen(truncate(when, whenWidth));
74
+ return styleWhen(clip(when, whenWidth));
59
75
  let compactWhen = '';
60
76
  for (const char of when) {
61
77
  if (visualWidth(compactWhen + char) > whenWidth)
@@ -77,11 +93,28 @@ export function weekdayShortLabel(wd) {
77
93
  ];
78
94
  return labels[wd - 1] ?? '';
79
95
  }
80
- 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) {
81
108
  const trans = t();
109
+ const width = lineBudget(cols);
110
+ const fits = (line) => visualWidth(line) <= width;
82
111
  const sorted = [...meetings].sort((a, b) => a.startPeriod - b.startPeriod);
83
- if (sorted.length === 0)
84
- 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
+ }
85
118
  const today = campusIsoDate(now);
86
119
  const minute = Math.floor(now.getTime() / 60_000) * 60_000;
87
120
  const dot = pickIcon('·', '-');
@@ -93,25 +126,20 @@ function renderTimeline(meetings, periods, now, isToday, alwaysShowLocation, cur
93
126
  const startStr = periods.find((p) => p.period === m.startPeriod)?.start ?? '00:00';
94
127
  const endStr = periods.find((p) => p.period === m.endPeriod)?.end ?? '23:59';
95
128
  const end = campusDateTime(today, endStr);
96
- const isLive = isToday && campusDateTime(today, startStr).getTime() <= minute && minute <= end.getTime();
97
- 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();
98
131
  const isCursor = cursorPeriod !== undefined && m.startPeriod <= cursorPeriod && cursorPeriod <= m.endPeriod;
99
132
  const connector = i === 0 ? topConnector : midConnector;
100
133
  const marker = isLive ? type.active(pickIcon('▶', '>')) : ' ';
101
134
  const timeCol = `${marker}${type.hint(startStr)} ${rule}${connector}${rule}`;
102
135
  const styleName = (name) => isLive ? type.active(name) : isDone ? type.hint(name) : type.body(name);
103
- let statusText = '';
104
- let compactStatusText = '';
105
- if (isDone) {
106
- statusText = trans.timetable.classDone;
107
- compactStatusText = statusText;
108
- }
109
- else if (isLive) {
110
- const remaining = countdownParts(end, now);
111
- const mins = remaining.days * 1440 + remaining.hours * 60 + remaining.minutes;
112
- statusText = `${trans.timetable.classLive} ${dot} ${fmt(trans.timetable.minutesRemaining, { minutes: String(mins) })}`;
113
- compactStatusText = `${mins}m`;
114
- }
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;
115
143
  const showLoc = alwaysShowLocation ? Boolean(m.location) : isLive && Boolean(m.location);
116
144
  const locationText = showLoc ? (m.location ?? '') : '';
117
145
  const renderLine = (name, status, location, currentTimeCol = timeCol, indent = space.indent) => {
@@ -120,57 +148,49 @@ function renderTimeline(meetings, periods, now, isToday, alwaysShowLocation, cur
120
148
  const content = `${currentTimeCol} ${styleName(name)}${statusCol}${locationCol}`;
121
149
  return `${indent}${isCursor ? type.cursor(content) : content}`;
122
150
  };
123
- const full = renderLine(m.courseName, statusText, locationText);
124
- if (!Number.isFinite(cols) || visualWidth(full) <= cols)
125
- return full;
126
- const compactWithLocation = renderLine(m.courseName, compactStatusText, locationText);
127
- if (visualWidth(compactWithLocation) <= cols)
128
- return compactWithLocation;
129
- const compact = renderLine(m.courseName, compactStatusText, '');
130
- if (visualWidth(compact) <= cols)
131
- return compact;
132
- const adaptiveStatuses = compactStatusText ? [compactStatusText, ''] : [''];
133
- for (const status of adaptiveStatuses) {
134
- const courseWidth = Math.floor(cols - visualWidth(renderLine('', status, '')));
135
- 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()))
136
161
  continue;
137
- return renderLine(truncate(m.courseName, courseWidth), status, '');
162
+ return renderLine(clip(m.courseName, courseWidth), status, '');
138
163
  }
139
164
  const compactTimeCol = `${marker}${type.hint(startStr)}`;
140
165
  for (const indent of [space.indent, '']) {
141
- const courseWidth = Math.floor(cols - visualWidth(renderLine('', '', '', compactTimeCol, indent)));
142
- if (courseWidth < 3)
166
+ const courseWidth = Math.floor(width - visualWidth(renderLine('', '', '', compactTimeCol, indent)));
167
+ if (courseWidth <= visualWidth(ellipsis()))
143
168
  continue;
144
- return renderLine(truncate(m.courseName, courseWidth), '', '', compactTimeCol, indent);
169
+ return renderLine(clip(m.courseName, courseWidth), '', '', compactTimeCol, indent);
145
170
  }
146
- 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);
147
172
  if (timeOnly)
148
173
  return timeOnly;
149
- 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))));
150
175
  });
151
176
  const last = sorted.at(-1);
152
177
  if (!last)
153
178
  return lines.join('\n');
154
179
  const lastEnd = periods.find((p) => p.period === last.endPeriod)?.end ?? '23:59';
155
- const fullEnd = `${space.indent} ${type.hint(lastEnd)} ${rule}${bottomConnector}${rule} ${type.hint(trans.timetable.timelineEnd)}`;
156
- if (!Number.isFinite(cols) || visualWidth(fullEnd) <= cols) {
157
- lines.push(fullEnd);
158
- }
159
- else {
160
- const compactEnd = [
161
- `${space.indent}${type.hint(lastEnd)} ${rule}${bottomConnector}${rule}`,
162
- `${space.indent}${type.hint(lastEnd)}`,
163
- type.hint(lastEnd),
164
- ].find((candidate) => visualWidth(candidate) <= cols);
165
- lines.push(compactEnd ?? type.hint(lastEnd.slice(0, Math.max(0, Math.floor(cols)))));
166
- }
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)))));
167
187
  return lines.join('\n');
168
188
  }
169
189
  export function renderTodayTimeline(meetings, periods, now, cols = Number.POSITIVE_INFINITY) {
170
- return renderTimeline(meetings, periods, now, true, false, undefined, cols);
190
+ return renderTimeline(meetings, periods, now, { weekday: 0, isToday: true }, false, undefined, cols);
171
191
  }
172
- export function renderDayTimeline(meetings, periods, now, isToday, cursorPeriod, cols = Number.POSITIVE_INFINITY) {
173
- 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);
174
194
  }
175
195
  export function renderDaySwitcher(selectedWeekday, todayWeekday, cols = Number.POSITIVE_INFINITY) {
176
196
  const leftArrow = pickIcon('←', '<');
@@ -243,10 +263,13 @@ export function renderWeekGrid(timetable, weekNumber, now, cols = 80, cursor) {
243
263
  });
244
264
  const fixedOverhead = space.indent.length + rowHeadW + 6 * sepW;
245
265
  const availableForCols = Math.max(0, cols - fixedOverhead);
266
+ const evenColW = Math.max(...idealColWidths);
246
267
  const totalIdealColW = idealColWidths.reduce((a, b) => a + b, 0);
247
- const colWidths = totalIdealColW <= availableForCols
248
- ? idealColWidths
249
- : idealColWidths.map((w) => Math.max(3, Math.floor(w * (availableForCols / totalIdealColW))));
268
+ const colWidths = evenColW * 7 <= availableForCols
269
+ ? idealColWidths.map(() => evenColW)
270
+ : totalIdealColW <= availableForCols
271
+ ? idealColWidths
272
+ : idealColWidths.map((w) => Math.max(3, Math.floor(w * (availableForCols / totalIdealColW))));
250
273
  const totalW = rowHeadW + colWidths.reduce((a, b) => a + b, 0) + 6 * sepW;
251
274
  const startingAt = (wd, period) => week.find((m) => m.weekday === wd && m.startPeriod === period);
252
275
  const continuingAt = (wd, period) => week.find((m) => m.weekday === wd && m.startPeriod < period && period <= m.endPeriod);
@@ -257,7 +280,7 @@ export function renderWeekGrid(timetable, weekNumber, now, cols = 80, cursor) {
257
280
  const d = weekdayShortLabel(wd);
258
281
  const label = wd === todayWd ? `${d}${todayMark}` : d;
259
282
  const colWidth = colWidths[i] ?? 3;
260
- const padded = centerInWidth(truncate(label, colWidth), colWidth);
283
+ const padded = centerInWidth(clip(label, colWidth), colWidth);
261
284
  return wd === todayWd ? type.active(padded) : type.hint(padded);
262
285
  }).join(sep);
263
286
  lines.push(space.indent + blankHead + headerCells);
@@ -275,11 +298,11 @@ export function renderWeekGrid(timetable, weekNumber, now, cols = 80, cursor) {
275
298
  const isContinuation = !starting && continuingAt(wd, p.period);
276
299
  const rawName = starting ? starting.courseName : isContinuation ? connector : emptyGlyph;
277
300
  const rawLoc = starting ? (starting.location ?? '') : isContinuation ? connector : '';
278
- const paddedName = centerInWidth(truncate(rawName, colW), colW);
279
- const paddedLoc = centerInWidth(truncate(rawLoc, colW), colW);
301
+ const paddedName = centerInWidth(clip(rawName, colW), colW);
302
+ const paddedLoc = centerInWidth(clip(rawLoc, colW), colW);
280
303
  if (isCursor) {
281
- nameCells.push(type.cursor(paddedName));
282
- 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));
283
306
  }
284
307
  else if (starting) {
285
308
  nameCells.push(isToday ? type.active(paddedName) : type.body(paddedName));
@@ -299,6 +322,68 @@ export function renderWeekGrid(timetable, weekNumber, now, cols = 80, cursor) {
299
322
  });
300
323
  return lines.join('\n');
301
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
+ }
302
387
  function formatWeekRange(weeks) {
303
388
  if (weeks.length === 0)
304
389
  return '';