@nbtca/prompt 1.5.15 → 1.5.17

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.
@@ -25,10 +25,13 @@ function formatMinutesLeft(end, now) {
25
25
  const minutes = p.days * 1440 + p.hours * 60 + p.minutes;
26
26
  return fmt(t().timetable.minutesRemaining, { minutes: String(minutes) });
27
27
  }
28
+ function rangeLabel(start, end) {
29
+ return end ? `${start}${pickIcon('–', '-')}${end}` : start;
30
+ }
28
31
  function span(m, periods) {
29
32
  const s = periods.find((p) => p.period === m.startPeriod)?.start ?? '';
30
33
  const e = periods.find((p) => p.period === m.endPeriod)?.end ?? '';
31
- return e ? `${s}${pickIcon('–', '-')}${e}` : s;
34
+ return rangeLabel(s, e);
32
35
  }
33
36
  export function renderNextClassBanner(next, now, cols = Number.POSITIVE_INFINITY, labelled = true) {
34
37
  const trans = t();
@@ -39,7 +42,7 @@ export function renderNextClassBanner(next, now, cols = Number.POSITIVE_INFINITY
39
42
  const styleWhen = isCountdownUrgent(p) ? c.warn : type.hint;
40
43
  const whenStyled = styleWhen(when);
41
44
  const dot = pickIcon('·', '-');
42
- const marker = type.active(glyph.cursor());
45
+ const marker = type.active(glyph.dot());
43
46
  const separator = ` ${dot} `;
44
47
  const detailedPrefix = labelled
45
48
  ? `${space.indent}${marker} ${type.label(trans.timetable.nextClass)}${separator}`
@@ -93,9 +96,9 @@ export function weekdayShortLabel(wd) {
93
96
  ];
94
97
  return labels[wd - 1] ?? '';
95
98
  }
96
- function weekdayLongLabel(wd) {
99
+ function weekdayName(wd, weekday) {
97
100
  return new Intl.DateTimeFormat(getCurrentLanguage() === 'zh' ? 'zh-CN' : 'en-US', {
98
- weekday: 'long',
101
+ weekday,
99
102
  timeZone: 'UTC',
100
103
  }).format(Date.UTC(2024, 0, wd));
101
104
  }
@@ -112,7 +115,7 @@ function renderTimeline(meetings, periods, now, day, alwaysShowLocation, cursorP
112
115
  if (sorted.length === 0) {
113
116
  const empty = day.isToday
114
117
  ? trans.timetable.noClassToday
115
- : fmt(trans.timetable.noClassOnDay, { weekday: weekdayLongLabel(day.weekday) });
118
+ : fmt(trans.timetable.noClassOnDay, { weekday: weekdayName(day.weekday, 'long') });
116
119
  return `${space.indent}${type.hint(empty)}`;
117
120
  }
118
121
  const today = campusIsoDate(now);
@@ -122,30 +125,45 @@ function renderTimeline(meetings, periods, now, day, alwaysShowLocation, cursorP
122
125
  const midConnector = pickIcon('┼', '+');
123
126
  const topConnector = pickIcon('┬', '+');
124
127
  const bottomConnector = pickIcon('┴', '+');
125
- const lines = sorted.map((m, i) => {
128
+ const rows = sorted.map((m) => {
126
129
  const startStr = periods.find((p) => p.period === m.startPeriod)?.start ?? '00:00';
127
130
  const endStr = periods.find((p) => p.period === m.endPeriod)?.end ?? '23:59';
128
131
  const end = campusDateTime(today, endStr);
129
132
  const isLive = day.isToday && campusDateTime(today, startStr).getTime() <= minute && minute <= end.getTime();
130
133
  const isDone = day.isToday && minute > end.getTime();
131
- const isCursor = cursorPeriod !== undefined && m.startPeriod <= cursorPeriod && cursorPeriod <= m.endPeriod;
132
- const connector = i === 0 ? topConnector : midConnector;
133
- const marker = isLive ? type.active(pickIcon('▶', '>')) : ' ';
134
- const timeCol = `${marker}${type.hint(startStr)} ${rule}${connector}${rule}`;
135
- const styleName = (name) => isLive ? type.active(name) : isDone ? type.hint(name) : type.body(name);
136
134
  const minutesLeft = isLive ? formatMinutesLeft(end, now) : '';
137
135
  const statusText = isDone
138
136
  ? trans.timetable.classDone
139
137
  : isLive
140
138
  ? `${trans.timetable.classLive} ${dot} ${minutesLeft}`
141
139
  : '';
142
- const compactStatusText = isDone ? trans.timetable.classDone : minutesLeft;
143
140
  const showLoc = alwaysShowLocation ? Boolean(m.location) : isLive && Boolean(m.location);
144
- const locationText = showLoc ? (m.location ?? '') : '';
141
+ return {
142
+ m,
143
+ startStr,
144
+ isLive,
145
+ isDone,
146
+ minutesLeft,
147
+ statusText,
148
+ locationText: showLoc ? (m.location ?? '') : '',
149
+ };
150
+ });
151
+ const nameColW = Math.max(...rows.map((row) => visualWidth(row.m.courseName)));
152
+ const statusColW = Math.max(...rows.map((row) => visualWidth(row.statusText)));
153
+ const lines = rows.map(({ m, startStr, isLive, isDone, minutesLeft, statusText, locationText }, i) => {
154
+ const isCursor = cursorPeriod !== undefined && m.startPeriod <= cursorPeriod && cursorPeriod <= m.endPeriod;
155
+ const connector = i === 0 ? topConnector : midConnector;
156
+ const marker = isLive ? type.active(pickIcon('▶', '>')) : ' ';
157
+ const timeCol = `${marker}${type.hint(startStr)} ${rule}${connector}${rule}`;
158
+ const styleName = (name) => isLive ? type.active(name) : isDone ? type.hint(name) : type.body(name);
159
+ const compactStatusText = isDone ? trans.timetable.classDone : minutesLeft;
145
160
  const renderLine = (name, status, location, currentTimeCol = timeCol, indent = space.indent) => {
146
- const statusCol = status ? ` ${type.hint(status)}` : '';
161
+ const aligned = name === m.courseName;
162
+ const statusW = aligned && location ? statusColW : 0;
163
+ const statusCol = status || statusW > 0 ? ` ${type.hint(padEndV(status, statusW))}` : '';
147
164
  const locationCol = location ? ` ${type.hint(location)}` : '';
148
- const content = `${currentTimeCol} ${styleName(name)}${statusCol}${locationCol}`;
165
+ const shownName = aligned && (statusCol || locationCol) ? padEndV(name, nameColW) : name;
166
+ const content = `${currentTimeCol} ${styleName(shownName)}${statusCol}${locationCol}`;
149
167
  return `${indent}${isCursor ? type.cursor(content) : content}`;
150
168
  };
151
169
  const whole = [
@@ -168,7 +186,11 @@ function renderTimeline(meetings, periods, now, day, alwaysShowLocation, cursorP
168
186
  continue;
169
187
  return renderLine(clip(m.courseName, courseWidth), '', '', compactTimeCol, indent);
170
188
  }
171
- const timeOnly = [`${space.indent}${compactTimeCol}`, compactTimeCol, type.hint(startStr)].find(fits);
189
+ const timeOnly = [
190
+ `${space.indent}${compactTimeCol}`,
191
+ compactTimeCol,
192
+ type.hint(startStr),
193
+ ].find(fits);
172
194
  if (timeOnly)
173
195
  return timeOnly;
174
196
  return type.hint(startStr.slice(0, Math.max(0, Math.floor(width))));
@@ -241,36 +263,54 @@ function centerInWidth(text, width) {
241
263
  return ' '.repeat(left) + text + ' '.repeat(right);
242
264
  }
243
265
  const MIN_COL_WIDTH = 8;
244
- export function renderWeekGrid(timetable, weekNumber, now, cols = 80, cursor) {
266
+ function spreadWidths(ideal, available) {
267
+ const widths = [...ideal];
268
+ const target = Number.isFinite(available) ? available : Math.max(0, ...ideal) * ideal.length;
269
+ let spare = target - widths.reduce((a, b) => a + b, 0);
270
+ while (spare > 0 && widths.length > 0) {
271
+ const narrowest = widths.indexOf(Math.min(...widths));
272
+ widths[narrowest] = (widths[narrowest] ?? 0) + 1;
273
+ spare -= 1;
274
+ }
275
+ return widths;
276
+ }
277
+ const GRID_SEP_W = 3;
278
+ function weekGridMetrics(timetable, weekNumber, now) {
245
279
  const schedule = createTimetableSchedule(timetable);
246
280
  const week = schedule.meetingsInWeek(weekNumber);
247
281
  const todayWd = schedule.weekdayAt(now);
248
- const periods = timetable.periods;
249
- const rowHeadW = 12;
250
- const todayMark = pickIcon('•', '*');
251
- const connector = pickIcon('│', '|');
252
- const emptyGlyph = pickIcon('·', '.');
253
- const sepGlyph = pickIcon('│', '|');
254
- const sep = type.hint(` ${sepGlyph} `);
255
- const sepW = 3; // " │ " / " | " -- always 3 display columns regardless of icon mode
282
+ const rowHeadW = timetable.periods.reduce((w, p) => Math.max(w, visualWidth(rangeLabel(p.start, p.end))), 0) +
283
+ GRID_SEP_W;
256
284
  const idealColWidths = WEEKDAY_KEYS.map((_, i) => {
257
285
  const wd = i + 1;
258
286
  const dayMeetings = week.filter((m) => m.weekday === wd);
259
287
  const nameW = dayMeetings.reduce((max, m) => Math.max(max, visualWidth(m.courseName)), 0);
260
288
  const locW = dayMeetings.reduce((max, m) => Math.max(max, m.location ? visualWidth(m.location) : 0), 0);
261
- const headerW = visualWidth(weekdayShortLabel(wd)) + (wd === todayWd ? visualWidth(todayMark) : 0);
289
+ const headerW = visualWidth(weekdayShortLabel(wd)) + (wd === todayWd ? visualWidth(pickIcon('•', '*')) : 0);
262
290
  return Math.max(nameW, locW, headerW, MIN_COL_WIDTH);
263
291
  });
264
- const fixedOverhead = space.indent.length + rowHeadW + 6 * sepW;
265
- const availableForCols = Math.max(0, cols - fixedOverhead);
266
- const evenColW = Math.max(...idealColWidths);
267
- const totalIdealColW = idealColWidths.reduce((a, b) => a + b, 0);
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))));
273
- const totalW = rowHeadW + colWidths.reduce((a, b) => a + b, 0) + 6 * sepW;
292
+ return { rowHeadW, idealColWidths, totalIdealColW: idealColWidths.reduce((a, b) => a + b, 0) };
293
+ }
294
+ export function weekGridFullWidth(timetable, weekNumber, now) {
295
+ const { rowHeadW, totalIdealColW } = weekGridMetrics(timetable, weekNumber, now);
296
+ return visualWidth(space.indent) * 2 + rowHeadW + totalIdealColW + 6 * GRID_SEP_W;
297
+ }
298
+ export function renderWeekGrid(timetable, weekNumber, now, cols = 80, cursor) {
299
+ const schedule = createTimetableSchedule(timetable);
300
+ const week = schedule.meetingsInWeek(weekNumber);
301
+ const todayWd = schedule.weekdayAt(now);
302
+ const periods = timetable.periods;
303
+ const todayMark = pickIcon('•', '*');
304
+ const connector = pickIcon('│', '|');
305
+ const emptyGlyph = pickIcon('·', '.');
306
+ const sepGlyph = pickIcon('│', '|');
307
+ const sep = type.hint(` ${sepGlyph} `);
308
+ const { rowHeadW, idealColWidths, totalIdealColW } = weekGridMetrics(timetable, weekNumber, now);
309
+ const availableForCols = Math.max(0, lineBudget(cols) - visualWidth(space.indent) - rowHeadW - 6 * GRID_SEP_W);
310
+ const colWidths = totalIdealColW <= availableForCols
311
+ ? spreadWidths(idealColWidths, availableForCols)
312
+ : idealColWidths.map((w) => Math.max(3, Math.floor(w * (availableForCols / totalIdealColW))));
313
+ const totalW = rowHeadW + colWidths.reduce((a, b) => a + b, 0) + 6 * GRID_SEP_W;
274
314
  const startingAt = (wd, period) => week.find((m) => m.weekday === wd && m.startPeriod === period);
275
315
  const continuingAt = (wd, period) => week.find((m) => m.weekday === wd && m.startPeriod < period && period <= m.endPeriod);
276
316
  const lines = [];
@@ -286,7 +326,7 @@ export function renderWeekGrid(timetable, weekNumber, now, cols = 80, cursor) {
286
326
  lines.push(space.indent + blankHead + headerCells);
287
327
  const sorted = [...periods].sort((a, b) => a.period - b.period);
288
328
  sorted.forEach((p, i) => {
289
- const rowHead = type.hint(padEndV(`${p.start}-${p.end}`, rowHeadW));
329
+ const rowHead = type.hint(padEndV(rangeLabel(p.start, p.end), rowHeadW));
290
330
  const nameCells = [];
291
331
  const locCells = [];
292
332
  for (let wdIdx = 0; wdIdx < 7; wdIdx++) {
@@ -395,14 +435,17 @@ function formatWeekRange(weeks) {
395
435
  if (isContiguous) {
396
436
  const first = sorted[0];
397
437
  const last = sorted.at(-1);
398
- return sorted.length > 1 ? `${first}-${last}` : `${first}`;
438
+ return sorted.length > 1 ? rangeLabel(String(first), String(last)) : `${first}`;
399
439
  }
400
440
  return sorted.join(', ');
401
441
  }
402
442
  export function renderMeetingDetail(meeting, periods, cols = Number.POSITIVE_INFINITY) {
403
443
  const trans = t();
404
444
  const rows = [
405
- [trans.timetable.detailTime, `${weekdayShortLabel(meeting.weekday)} ${span(meeting, periods)}`],
445
+ [
446
+ trans.timetable.detailTime,
447
+ `${weekdayName(meeting.weekday, 'short')} ${span(meeting, periods)}`,
448
+ ],
406
449
  ];
407
450
  if (meeting.location)
408
451
  rows.push([trans.timetable.detailLocation, meeting.location]);
@@ -465,28 +508,17 @@ export function renderUnresolvedItems(items, cols = Number.POSITIVE_INFINITY) {
465
508
  }
466
509
  return lines.join('\n');
467
510
  }
468
- const DENSITY_GLYPHS = [
469
- ['·', ' '],
470
- ['░', '.'],
471
- ['▒', ':'],
472
- ['▓', '-'],
473
- ['█', '='],
474
- ];
475
- function levelGlyph(level) {
476
- const pair = DENSITY_GLYPHS[Math.max(0, Math.min(4, level))] ?? ['·', ' '];
477
- return pickIcon(pair[0], pair[1]);
478
- }
479
- function applyDensityColor(glyphChar, level) {
480
- if (level <= 0)
481
- return type.hint(glyphChar);
482
- if (level >= 4)
483
- return type.active(glyphChar);
484
- return c.brand(glyphChar);
511
+ const DENSITY_HEIGHT = 5;
512
+ const DENSITY_COL = 3;
513
+ const BAR_RAMP = [' ', '▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'];
514
+ function barGlyph(eighths) {
515
+ const fill = Math.max(0, Math.min(8, eighths));
516
+ return pickIcon(BAR_RAMP[fill] ?? ' ', fill >= 4 ? '#' : fill > 0 ? '_' : ' ');
485
517
  }
486
518
  function weekStartDate(weekOneMonday, week) {
487
519
  return addLocalDays(parseLocalMonday(weekOneMonday), (week - 1) * 7);
488
520
  }
489
- function densityMonthText(weekOneMonday, startWeek, count, lang, maxWidth = Number.POSITIVE_INFINITY) {
521
+ function densityMonthText(weekOneMonday, startWeek, count, lang, maxWidth) {
490
522
  let text = '';
491
523
  let visualCol = 0;
492
524
  let previousMonth = -1;
@@ -499,104 +531,93 @@ function densityMonthText(weekOneMonday, startWeek, count, lang, maxWidth = Numb
499
531
  const label = new Intl.DateTimeFormat(lang === 'zh' ? 'zh-CN' : 'en-US', {
500
532
  month: 'short',
501
533
  }).format(date);
502
- const targetCol = index * 2;
503
- if (targetCol + visualWidth(label) > maxWidth)
534
+ const targetCol = index * DENSITY_COL;
535
+ if (targetCol < visualCol || targetCol + visualWidth(label) > maxWidth)
504
536
  continue;
505
- if (targetCol > visualCol)
506
- text += ' '.repeat(targetCol - visualCol);
507
- text += label;
537
+ text += ' '.repeat(targetCol - visualCol) + label;
508
538
  visualCol = targetCol + visualWidth(label);
509
539
  }
510
540
  return text;
511
541
  }
512
- function densityMarkerText(index, width, marker, label) {
513
- const markerCol = index * 2;
542
+ function densityMarkerLines(index, width, marker, label) {
543
+ const markerCol = index * DENSITY_COL;
514
544
  const after = `${' '.repeat(markerCol)}${marker} ${label}`;
515
545
  if (visualWidth(after) <= width)
516
- return after;
546
+ return [after];
517
547
  const beforeStart = markerCol - visualWidth(label) - 1;
518
548
  if (beforeStart >= 0)
519
- return `${' '.repeat(beforeStart)}${label} ${marker}`;
520
- return `${' '.repeat(markerCol)}${marker}`;
549
+ return [`${' '.repeat(beforeStart)}${label} ${marker}`];
550
+ return [`${' '.repeat(markerCol)}${marker}`, label];
521
551
  }
522
552
  export function renderTermDensity(meetings, weekOneMonday, currentWeek, cols = Number.POSITIVE_INFINITY) {
523
- const trans = t();
553
+ const trans = t().timetable;
524
554
  const lang = getCurrentLanguage();
525
- let minWeek = currentWeek;
526
- let maxWeek = currentWeek;
527
- for (const m of meetings) {
528
- for (const w of m.weeks) {
529
- if (w < minWeek)
530
- minWeek = w;
531
- if (w > maxWeek)
532
- maxWeek = w;
533
- }
534
- }
535
- const numWeeks = maxWeek - minWeek + 1;
536
- const weekSlots = [];
537
- for (let w = minWeek; w <= maxWeek; w++) {
538
- let slots = 0;
539
- for (const m of meetings) {
540
- if (m.weeks.includes(w))
541
- slots += m.endPeriod - m.startPeriod + 1;
542
- }
543
- weekSlots.push(slots);
544
- }
545
- const max = Math.max(0, ...weekSlots);
546
- const levels = weekSlots.map((v) => {
547
- if (v === 0 || max === 0)
548
- return 0;
549
- if (v <= max * 0.25)
550
- return 1;
551
- if (v <= max * 0.5)
552
- return 2;
553
- if (v <= max * 0.75)
554
- return 3;
555
- return 4;
556
- });
557
- const monthLabelText = densityMonthText(weekOneMonday, minWeek, numWeeks, lang);
558
- const monthLabelLine = `${space.indent}${monthLabelText}`;
559
- const glyphLine = `${space.indent}${levels.map((lvl) => applyDensityColor(levelGlyph(lvl), lvl)).join(' ')}`;
560
- const currentWeekIndex = Math.max(0, currentWeek - minWeek);
561
- const markerGlyph = pickIcon('↑', '^');
562
- const markerLine = `${space.indent}${type.hint(`${' '.repeat(currentWeekIndex * 2)}${markerGlyph} ${trans.timetable.termDensityThisWeek}`)}`;
563
- const legendGlyphs = [0, 1, 2, 3, 4].map((lvl) => applyDensityColor(levelGlyph(lvl), lvl));
564
- const legendContent = `${type.hint(trans.calendar.heatmap.legendLess)} ${legendGlyphs.join('')} ${type.hint(trans.calendar.heatmap.legendMore)}`;
565
- const legendLine = `${space.indent}${legendContent}`;
566
- const fullLines = [
567
- `${space.indent}${type.heading(trans.timetable.termDensityTitle)}`,
568
- '',
569
- monthLabelLine,
570
- glyphLine,
571
- markerLine,
572
- '',
573
- legendLine,
574
- ];
575
555
  const width = Number.isFinite(cols) ? Math.max(1, Math.floor(cols)) : Number.POSITIVE_INFINITY;
576
- if (!Number.isFinite(width) || fullLines.every((line) => visualWidth(line) <= width)) {
577
- return fullLines.join('\n');
578
- }
579
556
  const indent = visualWidth(space.indent) < width ? space.indent : '';
580
557
  const contentWidth = Math.max(1, width - visualWidth(indent));
581
- const weeksPerChunk = Math.max(1, Math.floor((contentWidth + 1) / 2));
582
- const lines = wrapAnsiToVisualWidth(type.heading(trans.timetable.termDensityTitle), contentWidth).map((part) => `${indent}${part}`);
583
- lines.push('');
584
- for (let start = 0; start < numWeeks; start += weeksPerChunk) {
585
- if (start > 0)
586
- lines.push('');
587
- const count = Math.min(weeksPerChunk, numWeeks - start);
588
- const chunkMonthText = densityMonthText(weekOneMonday, minWeek + start, count, lang, contentWidth);
589
- lines.push(`${indent}${chunkMonthText}`);
590
- lines.push(`${indent}${levels
591
- .slice(start, start + count)
592
- .map((level) => applyDensityColor(levelGlyph(level), level))
593
- .join(' ')}`);
594
- if (currentWeekIndex >= start && currentWeekIndex < start + count) {
595
- const relativeIndex = currentWeekIndex - start;
596
- lines.push(`${indent}${type.hint(densityMarkerText(relativeIndex, contentWidth, markerGlyph, trans.timetable.termDensityThisWeek))}`);
558
+ const wrap = (text) => wrapAnsiToVisualWidth(text, contentWidth).map((part) => `${indent}${part}`);
559
+ const lines = wrap(type.heading(trans.termDensityTitle));
560
+ const allWeeks = meetings.flatMap((m) => m.weeks);
561
+ if (allWeeks.length === 0) {
562
+ return [...lines, ...wrap(type.hint(trans.termDensityEmpty))].join('\n');
563
+ }
564
+ const firstWeek = Math.min(1, ...allWeeks);
565
+ const slots = Array.from({ length: Math.max(...allWeeks) - firstWeek + 1 }, (_, index) => meetings.reduce((sum, m) => m.weeks.includes(firstWeek + index) ? sum + m.endPeriod - m.startPeriod + 1 : sum, 0));
566
+ const busy = slots.filter((value) => value > 0);
567
+ const low = Math.min(...busy);
568
+ const high = Math.max(...busy);
569
+ const current = currentWeek - firstWeek;
570
+ const currentSlots = slots[current];
571
+ const freeWeeks = slots.length - busy.length;
572
+ const summary = [
573
+ fmt(trans.termDensityWeeks, { weeks: String(slots.length) }),
574
+ ...(freeWeeks > 0 ? [fmt(trans.termDensityFreeWeeks, { count: String(freeWeeks) })] : []),
575
+ fmt(trans.termDensityPerWeek, {
576
+ periods: low === high ? String(high) : rangeLabel(String(low), String(high)),
577
+ }),
578
+ ...(currentSlots === undefined
579
+ ? []
580
+ : [fmt(trans.termDensityCurrent, { periods: String(currentSlots) })]),
581
+ ];
582
+ const summaryLines = [];
583
+ for (const part of summary) {
584
+ const joined = `${summaryLines.at(-1) ?? ''} ${pickIcon('·', '-')} ${part}`;
585
+ if (summaryLines.length > 0 && visualWidth(joined) <= contentWidth) {
586
+ summaryLines[summaryLines.length - 1] = joined;
587
+ }
588
+ else {
589
+ summaryLines.push(part);
590
+ }
591
+ }
592
+ lines.push(...summaryLines.flatMap((line) => wrap(type.hint(line))));
593
+ const axisW = visualWidth(String(high));
594
+ const gutter = ' '.repeat(axisW + 3);
595
+ const perChunk = Math.max(1, Math.floor((contentWidth - gutter.length + 1) / DENSITY_COL));
596
+ for (let start = 0; start < slots.length; start += perChunk) {
597
+ const chunk = slots.slice(start, start + perChunk);
598
+ const style = (index) => start + index === current ? type.active : type.body;
599
+ lines.push('');
600
+ for (let row = DENSITY_HEIGHT - 1; row >= 0; row -= 1) {
601
+ const top = row === DENSITY_HEIGHT - 1;
602
+ const axis = `${(top ? String(high) : '').padStart(axisW)} ${top ? pickIcon('┤', '+') : glyph.bar()}`;
603
+ const bars = chunk.map((value, index) => {
604
+ const eighths = value === 0 ? 0 : Math.max(1, Math.round((value / high) * DENSITY_HEIGHT * 8));
605
+ return style(index)(barGlyph(eighths - row * 8).repeat(DENSITY_COL - 1));
606
+ });
607
+ lines.push(`${indent}${type.hint(axis)} ${bars.join(' ')}`);
608
+ }
609
+ lines.push(`${indent}${type.hint(`${'0'.padStart(axisW)} ${pickIcon('└', '+')}${glyph.rule().repeat(chunk.length * DENSITY_COL)}`)}`);
610
+ const numbers = chunk.map((_, index) => {
611
+ const label = String(firstWeek + start + index).padStart(DENSITY_COL - 1);
612
+ return start + index === current ? type.active(label) : type.hint(label);
613
+ });
614
+ lines.push(`${indent}${gutter}${numbers.join(' ')}`);
615
+ const room = contentWidth - gutter.length;
616
+ lines.push(`${indent}${gutter}${type.hint(densityMonthText(weekOneMonday, firstWeek + start, chunk.length, lang, room))}`);
617
+ if (current >= start && current < start + chunk.length) {
618
+ const marker = densityMarkerLines(current - start, room, pickIcon('↑', '^'), trans.termDensityThisWeek);
619
+ lines.push(...marker.map((line) => `${indent}${gutter}${type.hint(line)}`));
597
620
  }
598
621
  }
599
- lines.push('');
600
- lines.push(...wrapAnsiToVisualWidth(legendContent, contentWidth).map((part) => `${indent}${part}`));
601
622
  return lines.join('\n');
602
623
  }
@@ -119,6 +119,8 @@ async function checkService(name, url, timeoutMs, signal) {
119
119
  cancelResponseBody(response);
120
120
  }
121
121
  }
122
+ // Campus-only hosts answer fast on the campus network and never off it.
123
+ const INTRANET_TIMEOUT_MS = 1500;
122
124
  async function checkServiceWithRetry(target, timeoutMs, retries, signal) {
123
125
  let lastResult = await checkService(target.name, target.url, timeoutMs, signal);
124
126
  if (!lastResult.ok) {
@@ -143,7 +145,9 @@ export async function checkServices(options = {}) {
143
145
  const retries = options.retries ?? 1;
144
146
  if (options.signal?.aborted)
145
147
  throw abortError(options.signal);
146
- return Promise.all(getServiceTargets().map((target) => checkServiceWithRetry(target, timeoutMs, retries, options.signal)));
148
+ return Promise.all(getServiceTargets().map((target) => target.intranet
149
+ ? checkServiceWithRetry(target, Math.min(timeoutMs, INTRANET_TIMEOUT_MS), 0, options.signal)
150
+ : checkServiceWithRetry(target, timeoutMs, retries, options.signal)));
147
151
  }
148
152
  export function serializeServiceStatus(items) {
149
153
  return items.map((item) => ({
@@ -10,7 +10,8 @@
10
10
  "goodbye": "Goodbye!",
11
11
  "current": "current",
12
12
  "moreAbove": "{count} more above",
13
- "moreBelow": "{count} more below"
13
+ "moreBelow": "{count} more below",
14
+ "offline": "Offline, showing cached data"
14
15
  },
15
16
  "help": {
16
17
  "title": "Keys",
@@ -36,7 +37,7 @@
36
37
  "status": "Status",
37
38
  "statusDesc": "Online status",
38
39
  "timetable": "My Timetable",
39
- "timetableDesc": "Sign in to JWXT, choose a term and export ICS",
40
+ "timetableDesc": "Log in to JWXT, choose a term and export ICS",
40
41
  "links": "Links",
41
42
  "linksDesc": "website · GitHub · roadmap",
42
43
  "settings": "Settings",
@@ -64,7 +65,6 @@
64
65
  "loading": "Loading event calendar...",
65
66
  "noEvents": "No upcoming events",
66
67
  "error": "Failed to load event calendar",
67
- "stale": "offline, showing last known",
68
68
  "errorHint": "Please try again later or visit https://nbtca.space",
69
69
  "eventsFound": "events found",
70
70
  "dateTime": "Date & Time",
@@ -108,7 +108,9 @@
108
108
  "days": "{days}d {hours}h",
109
109
  "hours": "{hours}h {minutes}m",
110
110
  "minutes": "{minutes}m"
111
- }
111
+ },
112
+ "offlineError": "Couldn't load the events calendar. You may be offline.",
113
+ "retry": "Retry"
112
114
  },
113
115
  "docs": {
114
116
  "loading": "Loading documentation list...",
@@ -125,7 +127,6 @@
125
127
  "chooseCategory": "Docs",
126
128
  "refreshCache": "Refresh cache",
127
129
  "cacheCleared": "Documentation cache cleared",
128
- "stale": "offline, showing last known docs",
129
130
  "currentDir": "Current directory",
130
131
  "chooseDoc": "Choose a document or directory",
131
132
  "emptyDir": "This directory is empty",
@@ -160,7 +161,12 @@
160
161
  "loadingFile": "Loading",
161
162
  "readerLinksTitle": "Jump to",
162
163
  "readerLinksHint": "links",
163
- "readerNoLinks": "This page has no links to other docs"
164
+ "readerNoLinks": "This page has no links to other docs",
165
+ "offlineError": "Couldn't load the docs. You may be offline.",
166
+ "offlineHint": "Try again later, or read them at https://docs.nbtca.space",
167
+ "retryLoad": "Retry",
168
+ "searchResultsTitle": "Results for “{query}” · {count}",
169
+ "searchProgress": "Searching every document: {done} of {total} checked"
164
170
  },
165
171
  "links": {
166
172
  "choose": "Links",
@@ -210,8 +216,8 @@
210
216
  "menuTitle": "My Timetable",
211
217
  "actionExport": "Export ICS",
212
218
  "actionTerms": "List terms",
213
- "actionLogin": "Sign in or refresh session",
214
- "actionLogout": "Sign out",
219
+ "actionLogin": "Log in or refresh session",
220
+ "actionLogout": "Log out",
215
221
  "actionStatus": "Login status",
216
222
  "termPrompt": "Term code",
217
223
  "termPromptHint": "Leave empty for current, for example 2026:3",
@@ -225,7 +231,7 @@
225
231
  "sessionRefreshFailed": "The operation completed, but the saved session expiry could not be refreshed.",
226
232
  "candidateTerms": "Candidate JWXT terms (not every term necessarily has a personal timetable):",
227
233
  "semesterNumber": "Semester {number}",
228
- "expiredRelogin": "The saved login session expired. Please sign in again.",
234
+ "expiredRelogin": "The saved login session expired. Please log in again.",
229
235
  "studentId": "Student id",
230
236
  "studentIdHint": "Sent only to the school authentication service",
231
237
  "password": "Password",
@@ -243,7 +249,7 @@
243
249
  "accountLocked": "The account is temporarily locked. Try later or use the official school page.",
244
250
  "accountInactive": "The account is inactive. Activate it on the official school page first.",
245
251
  "challenge": "The school requires a slider or browser challenge; CLI login stopped safely.",
246
- "sessionExpired": "The login session expired. Please sign in again.",
252
+ "sessionExpired": "The login session expired. Please log in again.",
247
253
  "timeout": "The school service timed out.",
248
254
  "network": "Could not connect to the school service.",
249
255
  "profileIncomplete": "The school wants this account's profile completed first; finish it in a browser, then try again.",
@@ -305,6 +311,12 @@
305
311
  "hubTermDensity": "Term density",
306
312
  "termDensityTitle": "Term density",
307
313
  "termDensityThisWeek": "This week",
314
+ "termDensityWeeks": "{weeks} weeks",
315
+ "termDensityPerWeek": "{periods} periods a week",
316
+ "termDensityFreeWeeks": "{count} without classes",
317
+ "termDensityCurrent": "{periods} this week",
318
+ "termDensityEmpty": "No classes scheduled this term",
319
+ "exportSaved": "Saved: {path}",
308
320
  "weekOverviewTitle": "Week overview",
309
321
  "weekAheadClasses": "Classes",
310
322
  "weekAheadBusy": "Busy",
@@ -340,13 +352,18 @@
340
352
  "modeOn": "On",
341
353
  "modeOff": "Off",
342
354
  "backToMenu": "Back to menu",
343
- "iconMode": "Icon mode",
344
- "colorMode": "Color mode",
355
+ "iconMode": "Icon Mode",
356
+ "colorMode": "Color Mode",
345
357
  "updated": "Theme setting updated",
346
358
  "updatedSessionOnly": "Theme setting updated for this session only (failed to save config)",
347
359
  "reset": "Theme settings reset",
348
- "resetLabel": "Reset to defaults",
360
+ "resetLabel": "Reset to Defaults",
349
361
  "resetSessionOnly": "Theme settings reset for this session only (failed to save config)",
362
+ "resetConfirm": "Reset icon mode and color mode to their defaults?",
363
+ "iconUpdated": "Icon mode updated",
364
+ "iconUpdatedSessionOnly": "Icon mode changed for this session only (failed to save config)",
365
+ "colorUpdated": "Color mode updated",
366
+ "colorUpdatedSessionOnly": "Color mode changed for this session only (failed to save config)",
350
367
  "usage": "Usage: nbtca theme | nbtca theme icon <auto|ascii|unicode> | nbtca theme color <auto|on|off> | nbtca theme reset",
351
368
  "invalidValue": "Invalid value. Use one of:"
352
369
  },
@@ -10,7 +10,8 @@
10
10
  "goodbye": "再见!",
11
11
  "current": "当前",
12
12
  "moreAbove": "上方还有 {count} 项",
13
- "moreBelow": "下方还有 {count} 项"
13
+ "moreBelow": "下方还有 {count} 项",
14
+ "offline": "当前离线,显示的是上次获取的内容"
14
15
  },
15
16
  "help": {
16
17
  "title": "快捷键",
@@ -64,7 +65,6 @@
64
65
  "loading": "正在获取活动日历...",
65
66
  "noEvents": "近期暂无活动安排",
66
67
  "error": "无法获取活动日历",
67
- "stale": "离线,显示上次获取的数据",
68
68
  "errorHint": "请稍后重试或访问 https://nbtca.space",
69
69
  "eventsFound": "个活动",
70
70
  "dateTime": "日期时间",
@@ -108,7 +108,9 @@
108
108
  "days": "{days} 天 {hours} 小时",
109
109
  "hours": "{hours} 小时 {minutes} 分钟",
110
110
  "minutes": "{minutes} 分钟"
111
- }
111
+ },
112
+ "offlineError": "无法获取活动日历,可能是网络没有连接。",
113
+ "retry": "重试"
112
114
  },
113
115
  "docs": {
114
116
  "loading": "正在加载文档列表...",
@@ -125,7 +127,6 @@
125
127
  "chooseCategory": "文档",
126
128
  "refreshCache": "刷新缓存",
127
129
  "cacheCleared": "文档缓存已清除",
128
- "stale": "离线,显示上次获取的文档",
129
130
  "currentDir": "当前目录",
130
131
  "chooseDoc": "选择文档或目录",
131
132
  "emptyDir": "该目录为空",
@@ -160,7 +161,12 @@
160
161
  "loadingFile": "正在加载",
161
162
  "readerLinksTitle": "跳转到",
162
163
  "readerLinksHint": "链接",
163
- "readerNoLinks": "本页没有指向其他文档的链接"
164
+ "readerNoLinks": "本页没有指向其他文档的链接",
165
+ "offlineError": "无法加载文档目录,可能是网络没有连接。",
166
+ "offlineHint": "请稍后重试,或者到 https://docs.nbtca.space 阅读",
167
+ "retryLoad": "重试",
168
+ "searchResultsTitle": "“{query}”的搜索结果 · {count} 篇",
169
+ "searchProgress": "正在逐篇检索文档,已检索 {done} / {total} 篇"
164
170
  },
165
171
  "links": {
166
172
  "choose": "链接",
@@ -295,7 +301,7 @@
295
301
  "weekdayFri": "五",
296
302
  "weekdaySat": "六",
297
303
  "weekdaySun": "日",
298
- "todayHeading": "今日 · 周{weekday} · 第{week}教学周",
304
+ "todayHeading": "今日 · 周{weekday} · 第 {week} 教学周",
299
305
  "classDone": "已结束",
300
306
  "classLive": "进行中",
301
307
  "minutesRemaining": "还剩 {minutes} 分钟",
@@ -305,6 +311,12 @@
305
311
  "hubTermDensity": "学期活跃度",
306
312
  "termDensityTitle": "学期活跃度",
307
313
  "termDensityThisWeek": "本周",
314
+ "termDensityWeeks": "共 {weeks} 周",
315
+ "termDensityPerWeek": "每周 {periods} 节",
316
+ "termDensityFreeWeeks": "其中 {count} 周无课",
317
+ "termDensityCurrent": "本周 {periods} 节",
318
+ "termDensityEmpty": "本学期还没有课程安排",
319
+ "exportSaved": "已保存:{path}",
308
320
  "weekOverviewTitle": "本周概览",
309
321
  "weekAheadClasses": "课程",
310
322
  "weekAheadBusy": "较满",
@@ -347,6 +359,11 @@
347
359
  "reset": "主题设置已重置",
348
360
  "resetLabel": "恢复默认",
349
361
  "resetSessionOnly": "主题设置仅在当前会话重置(无法写入配置文件)",
362
+ "resetConfirm": "把图标模式和颜色模式恢复为默认值?",
363
+ "iconUpdated": "图标模式已更新",
364
+ "iconUpdatedSessionOnly": "图标模式仅在当前会话生效(无法写入配置文件)",
365
+ "colorUpdated": "颜色模式已更新",
366
+ "colorUpdatedSessionOnly": "颜色模式仅在当前会话生效(无法写入配置文件)",
350
367
  "usage": "用法: nbtca theme | nbtca theme icon <auto|ascii|unicode> | nbtca theme color <auto|on|off> | nbtca theme reset",
351
368
  "invalidValue": "无效取值,可选:"
352
369
  },