@nbtca/prompt 1.5.16 → 1.5.18

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,6 +1,6 @@
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, MAX_FRAME_COLS } from '../core/theme.js';
3
+ import { c, type, space, glyph, MAX_FRAME_COLS, bodyWidth } 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';
@@ -25,21 +25,25 @@ 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
- export function renderNextClassBanner(next, now, cols = Number.POSITIVE_INFINITY, labelled = true) {
36
+ export function renderNextClassBanner(next, now, terminalCols = Number.POSITIVE_INFINITY, labelled = true) {
34
37
  const trans = t();
35
38
  if (!next)
36
39
  return '';
40
+ const cols = bodyWidth(terminalCols);
37
41
  const p = countdownParts(next.start, now);
38
42
  const when = formatClassCountdown(p);
39
43
  const styleWhen = isCountdownUrgent(p) ? c.warn : type.hint;
40
44
  const whenStyled = styleWhen(when);
41
- const dot = pickIcon('·', '-');
42
- const marker = type.active(glyph.cursor());
45
+ const dot = glyph.sep();
46
+ const marker = type.active(glyph.dot());
43
47
  const separator = ` ${dot} `;
44
48
  const detailedPrefix = labelled
45
49
  ? `${space.indent}${marker} ${type.label(trans.timetable.nextClass)}${separator}`
@@ -93,9 +97,9 @@ export function weekdayShortLabel(wd) {
93
97
  ];
94
98
  return labels[wd - 1] ?? '';
95
99
  }
96
- function weekdayLongLabel(wd) {
100
+ function weekdayName(wd, weekday) {
97
101
  return new Intl.DateTimeFormat(getCurrentLanguage() === 'zh' ? 'zh-CN' : 'en-US', {
98
- weekday: 'long',
102
+ weekday,
99
103
  timeZone: 'UTC',
100
104
  }).format(Date.UTC(2024, 0, wd));
101
105
  }
@@ -112,40 +116,55 @@ function renderTimeline(meetings, periods, now, day, alwaysShowLocation, cursorP
112
116
  if (sorted.length === 0) {
113
117
  const empty = day.isToday
114
118
  ? trans.timetable.noClassToday
115
- : fmt(trans.timetable.noClassOnDay, { weekday: weekdayLongLabel(day.weekday) });
119
+ : fmt(trans.timetable.noClassOnDay, { weekday: weekdayName(day.weekday, 'long') });
116
120
  return `${space.indent}${type.hint(empty)}`;
117
121
  }
118
122
  const today = campusIsoDate(now);
119
123
  const minute = Math.floor(now.getTime() / 60_000) * 60_000;
120
- const dot = pickIcon('·', '-');
124
+ const dot = glyph.sep();
121
125
  const rule = pickIcon('─', '-');
122
126
  const midConnector = pickIcon('┼', '+');
123
127
  const topConnector = pickIcon('┬', '+');
124
128
  const bottomConnector = pickIcon('┴', '+');
125
- const lines = sorted.map((m, i) => {
129
+ const rows = sorted.map((m) => {
126
130
  const startStr = periods.find((p) => p.period === m.startPeriod)?.start ?? '00:00';
127
131
  const endStr = periods.find((p) => p.period === m.endPeriod)?.end ?? '23:59';
128
132
  const end = campusDateTime(today, endStr);
129
133
  const isLive = day.isToday && campusDateTime(today, startStr).getTime() <= minute && minute <= end.getTime();
130
134
  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
135
  const minutesLeft = isLive ? formatMinutesLeft(end, now) : '';
137
136
  const statusText = isDone
138
137
  ? trans.timetable.classDone
139
138
  : isLive
140
139
  ? `${trans.timetable.classLive} ${dot} ${minutesLeft}`
141
140
  : '';
142
- const compactStatusText = isDone ? trans.timetable.classDone : minutesLeft;
143
141
  const showLoc = alwaysShowLocation ? Boolean(m.location) : isLive && Boolean(m.location);
144
- const locationText = showLoc ? (m.location ?? '') : '';
142
+ return {
143
+ m,
144
+ startStr,
145
+ isLive,
146
+ isDone,
147
+ minutesLeft,
148
+ statusText,
149
+ locationText: showLoc ? (m.location ?? '') : '',
150
+ };
151
+ });
152
+ const nameColW = Math.max(...rows.map((row) => visualWidth(row.m.courseName)));
153
+ const statusColW = Math.max(...rows.map((row) => visualWidth(row.statusText)));
154
+ const lines = rows.map(({ m, startStr, isLive, isDone, minutesLeft, statusText, locationText }, i) => {
155
+ const isCursor = cursorPeriod !== undefined && m.startPeriod <= cursorPeriod && cursorPeriod <= m.endPeriod;
156
+ const connector = i === 0 ? topConnector : midConnector;
157
+ const marker = isLive ? type.active(pickIcon('▶', '>')) : ' ';
158
+ const timeCol = `${marker}${type.hint(startStr)} ${rule}${connector}${rule}`;
159
+ const styleName = (name) => isLive ? type.active(name) : isDone ? type.hint(name) : type.body(name);
160
+ const compactStatusText = isDone ? trans.timetable.classDone : minutesLeft;
145
161
  const renderLine = (name, status, location, currentTimeCol = timeCol, indent = space.indent) => {
146
- const statusCol = status ? ` ${type.hint(status)}` : '';
162
+ const aligned = name === m.courseName;
163
+ const statusW = aligned && location ? statusColW : 0;
164
+ const statusCol = status || statusW > 0 ? ` ${type.hint(padEndV(status, statusW))}` : '';
147
165
  const locationCol = location ? ` ${type.hint(location)}` : '';
148
- const content = `${currentTimeCol} ${styleName(name)}${statusCol}${locationCol}`;
166
+ const shownName = aligned && (statusCol || locationCol) ? padEndV(name, nameColW) : name;
167
+ const content = `${currentTimeCol} ${styleName(shownName)}${statusCol}${locationCol}`;
149
168
  return `${indent}${isCursor ? type.cursor(content) : content}`;
150
169
  };
151
170
  const whole = [
@@ -168,7 +187,11 @@ function renderTimeline(meetings, periods, now, day, alwaysShowLocation, cursorP
168
187
  continue;
169
188
  return renderLine(clip(m.courseName, courseWidth), '', '', compactTimeCol, indent);
170
189
  }
171
- const timeOnly = [`${space.indent}${compactTimeCol}`, compactTimeCol, type.hint(startStr)].find(fits);
190
+ const timeOnly = [
191
+ `${space.indent}${compactTimeCol}`,
192
+ compactTimeCol,
193
+ type.hint(startStr),
194
+ ].find(fits);
172
195
  if (timeOnly)
173
196
  return timeOnly;
174
197
  return type.hint(startStr.slice(0, Math.max(0, Math.floor(width))));
@@ -192,7 +215,8 @@ export function renderTodayTimeline(meetings, periods, now, cols = Number.POSITI
192
215
  export function renderDayTimeline(meetings, periods, now, day, cursorPeriod, cols = Number.POSITIVE_INFINITY) {
193
216
  return renderTimeline(meetings, periods, now, day, true, cursorPeriod, cols);
194
217
  }
195
- export function renderDaySwitcher(selectedWeekday, todayWeekday, cols = Number.POSITIVE_INFINITY) {
218
+ export function renderDaySwitcher(selectedWeekday, todayWeekday, terminalCols = Number.POSITIVE_INFINITY) {
219
+ const cols = bodyWidth(terminalCols);
196
220
  const leftArrow = pickIcon('←', '<');
197
221
  const rightArrow = pickIcon('→', '>');
198
222
  const todayMark = pickIcon('•', '*');
@@ -241,36 +265,56 @@ function centerInWidth(text, width) {
241
265
  return ' '.repeat(left) + text + ' '.repeat(right);
242
266
  }
243
267
  const MIN_COL_WIDTH = 8;
244
- export function renderWeekGrid(timetable, weekNumber, now, cols = 80, cursor) {
268
+ function spreadWidths(ideal, available) {
269
+ const widths = [...ideal];
270
+ const target = Number.isFinite(available) ? available : Math.max(0, ...ideal) * ideal.length;
271
+ let spare = target - widths.reduce((a, b) => a + b, 0);
272
+ while (spare > 0 && widths.length > 0) {
273
+ const narrowest = widths.indexOf(Math.min(...widths));
274
+ widths[narrowest] = (widths[narrowest] ?? 0) + 1;
275
+ spare -= 1;
276
+ }
277
+ return widths;
278
+ }
279
+ const GRID_SEP_W = 3;
280
+ const GRID_CURSOR_TAIL_W = 1;
281
+ function weekGridMetrics(timetable, weekNumber, now) {
245
282
  const schedule = createTimetableSchedule(timetable);
246
283
  const week = schedule.meetingsInWeek(weekNumber);
247
284
  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
285
+ const rowHeadW = timetable.periods.reduce((w, p) => Math.max(w, visualWidth(rangeLabel(p.start, p.end))), 0) +
286
+ GRID_SEP_W;
256
287
  const idealColWidths = WEEKDAY_KEYS.map((_, i) => {
257
288
  const wd = i + 1;
258
289
  const dayMeetings = week.filter((m) => m.weekday === wd);
259
290
  const nameW = dayMeetings.reduce((max, m) => Math.max(max, visualWidth(m.courseName)), 0);
260
291
  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);
292
+ const headerW = visualWidth(weekdayShortLabel(wd)) + (wd === todayWd ? visualWidth(pickIcon('•', '*')) : 0);
262
293
  return Math.max(nameW, locW, headerW, MIN_COL_WIDTH);
263
294
  });
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 - space.indent.length
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;
295
+ return { rowHeadW, idealColWidths, totalIdealColW: idealColWidths.reduce((a, b) => a + b, 0) };
296
+ }
297
+ export function weekGridFullWidth(timetable, weekNumber, now) {
298
+ const { rowHeadW, totalIdealColW } = weekGridMetrics(timetable, weekNumber, now);
299
+ return (visualWidth(space.indent) * 2 + rowHeadW + totalIdealColW + 6 * GRID_SEP_W + GRID_CURSOR_TAIL_W);
300
+ }
301
+ export function renderWeekGrid(timetable, weekNumber, now, cols = 80, cursor) {
302
+ const schedule = createTimetableSchedule(timetable);
303
+ const week = schedule.meetingsInWeek(weekNumber);
304
+ const todayWd = schedule.weekdayAt(now);
305
+ const periods = timetable.periods;
306
+ const todayMark = pickIcon('•', '*');
307
+ const connector = pickIcon('│', '|');
308
+ const emptyGlyph = pickIcon('·', '.');
309
+ const sepGlyph = pickIcon('│', '|');
310
+ const gap = ` ${sepGlyph} `;
311
+ const sep = type.hint(gap);
312
+ const { rowHeadW, idealColWidths, totalIdealColW } = weekGridMetrics(timetable, weekNumber, now);
313
+ const availableForCols = Math.max(0, lineBudget(cols) - visualWidth(space.indent) - rowHeadW - 6 * GRID_SEP_W - GRID_CURSOR_TAIL_W);
314
+ const colWidths = totalIdealColW <= availableForCols
315
+ ? spreadWidths(idealColWidths, availableForCols)
316
+ : idealColWidths.map((w) => Math.max(3, Math.floor(w * (availableForCols / totalIdealColW))));
317
+ const totalW = rowHeadW + colWidths.reduce((a, b) => a + b, 0) + 6 * GRID_SEP_W;
274
318
  const startingAt = (wd, period) => week.find((m) => m.weekday === wd && m.startPeriod === period);
275
319
  const continuingAt = (wd, period) => week.find((m) => m.weekday === wd && m.startPeriod < period && period <= m.endPeriod);
276
320
  const lines = [];
@@ -286,9 +330,9 @@ export function renderWeekGrid(timetable, weekNumber, now, cols = 80, cursor) {
286
330
  lines.push(space.indent + blankHead + headerCells);
287
331
  const sorted = [...periods].sort((a, b) => a.period - b.period);
288
332
  sorted.forEach((p, i) => {
289
- const rowHead = type.hint(padEndV(`${p.start}-${p.end}`, rowHeadW));
290
333
  const nameCells = [];
291
334
  const locCells = [];
335
+ let widened = -1;
292
336
  for (let wdIdx = 0; wdIdx < 7; wdIdx++) {
293
337
  const wd = wdIdx + 1;
294
338
  const colW = colWidths[wdIdx] ?? 3;
@@ -301,7 +345,11 @@ export function renderWeekGrid(timetable, weekNumber, now, cols = 80, cursor) {
301
345
  const paddedName = centerInWidth(clip(rawName, colW), colW);
302
346
  const paddedLoc = centerInWidth(clip(rawLoc, colW), colW);
303
347
  if (isCursor) {
304
- nameCells.push(type.active(centerInWidth(`[${clip(rawName, colW - 2)}]`, colW)));
348
+ const wide = visualWidth(rawName) > colW - 2;
349
+ if (wide)
350
+ widened = wdIdx;
351
+ const inner = wide ? colW : colW - 2;
352
+ nameCells.push(type.active(centerInWidth(`[${clip(rawName, inner)}]`, inner + 2)));
305
353
  locCells.push(starting ? type.body(paddedLoc) : type.hint(paddedLoc));
306
354
  }
307
355
  else if (starting) {
@@ -313,7 +361,13 @@ export function renderWeekGrid(timetable, weekNumber, now, cols = 80, cursor) {
313
361
  locCells.push(type.hint(paddedLoc));
314
362
  }
315
363
  }
316
- lines.push(space.indent + rowHead + nameCells.join(sep));
364
+ const rowHead = type.hint(padEndV(rangeLabel(p.start, p.end), rowHeadW - (widened === 0 ? 1 : 0)));
365
+ const nameRow = nameCells
366
+ .map((cell, index) => index === 0
367
+ ? cell
368
+ : type.hint(gap.slice(index - 1 === widened ? 1 : 0, index === widened ? 2 : 3)) + cell)
369
+ .join('');
370
+ lines.push(space.indent + rowHead + nameRow);
317
371
  lines.push(space.indent + blankHead + locCells.join(sep));
318
372
  const next = sorted[i + 1];
319
373
  if (next && minutesOf(next.start) - minutesOf(p.end) > GAP_THRESHOLD_MINUTES) {
@@ -327,7 +381,7 @@ export function renderWeekAgenda(timetable, weekNumber, now, cols = Number.POSIT
327
381
  const todayWd = schedule.weekdayAt(now);
328
382
  const width = lineBudget(cols);
329
383
  const todayMark = pickIcon('•', '*');
330
- const dot = pickIcon('·', '-');
384
+ const dot = glyph.sep();
331
385
  const pointer = glyph.cursor();
332
386
  const labels = WEEKDAY_KEYS.map((_, i) => `${weekdayShortLabel(i + 1)}${i + 1 === todayWd ? todayMark : ''}`);
333
387
  const labelW = Math.max(...labels.map(visualWidth));
@@ -395,14 +449,17 @@ function formatWeekRange(weeks) {
395
449
  if (isContiguous) {
396
450
  const first = sorted[0];
397
451
  const last = sorted.at(-1);
398
- return sorted.length > 1 ? `${first}-${last}` : `${first}`;
452
+ return sorted.length > 1 ? rangeLabel(String(first), String(last)) : `${first}`;
399
453
  }
400
454
  return sorted.join(', ');
401
455
  }
402
456
  export function renderMeetingDetail(meeting, periods, cols = Number.POSITIVE_INFINITY) {
403
457
  const trans = t();
404
458
  const rows = [
405
- [trans.timetable.detailTime, `${weekdayShortLabel(meeting.weekday)} ${span(meeting, periods)}`],
459
+ [
460
+ trans.timetable.detailTime,
461
+ `${weekdayName(meeting.weekday, 'short')} ${span(meeting, periods)}`,
462
+ ],
406
463
  ];
407
464
  if (meeting.location)
408
465
  rows.push([trans.timetable.detailLocation, meeting.location]);
@@ -413,7 +470,7 @@ export function renderMeetingDetail(meeting, periods, cols = Number.POSITIVE_INF
413
470
  ]);
414
471
  }
415
472
  rows.push([trans.timetable.detailWeeks, formatWeekRange(meeting.weeks)]);
416
- const width = Number.isFinite(cols) ? Math.max(1, Math.floor(cols)) : Number.POSITIVE_INFINITY;
473
+ const width = bodyWidth(cols);
417
474
  const indent = visualWidth(space.indent) < width ? space.indent : '';
418
475
  const contentWidth = Math.max(1, width - visualWidth(indent));
419
476
  const labelWidth = rows.reduce((w, [label]) => Math.max(w, visualWidth(label)), 0);
@@ -437,7 +494,7 @@ export function renderMeetingDetail(meeting, periods, cols = Number.POSITIVE_INF
437
494
  }
438
495
  export function renderUnresolvedItems(items, cols = Number.POSITIVE_INFINITY) {
439
496
  const trans = t();
440
- const width = Number.isFinite(cols) ? Math.max(1, Math.floor(cols)) : Number.POSITIVE_INFINITY;
497
+ const width = bodyWidth(cols);
441
498
  const indent = visualWidth(space.indent) < width ? space.indent : '';
442
499
  const contentWidth = Math.max(1, width - visualWidth(indent));
443
500
  if (items.length === 0) {
@@ -445,7 +502,7 @@ export function renderUnresolvedItems(items, cols = Number.POSITIVE_INFINITY) {
445
502
  .map((part) => `${indent}${part}`)
446
503
  .join('\n');
447
504
  }
448
- const dot = pickIcon('·', '-');
505
+ const dot = glyph.sep();
449
506
  const lines = [];
450
507
  for (const item of items) {
451
508
  const name = item.sourceFields.kcmc ?? trans.timetable.unresolvedUnknownItem;
@@ -465,28 +522,17 @@ export function renderUnresolvedItems(items, cols = Number.POSITIVE_INFINITY) {
465
522
  }
466
523
  return lines.join('\n');
467
524
  }
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);
525
+ const DENSITY_HEIGHT = 5;
526
+ const DENSITY_COL = 3;
527
+ const BAR_RAMP = [' ', '▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'];
528
+ function barGlyph(eighths) {
529
+ const fill = Math.max(0, Math.min(8, eighths));
530
+ return pickIcon(BAR_RAMP[fill] ?? ' ', fill >= 4 ? '#' : fill > 0 ? '_' : ' ');
485
531
  }
486
532
  function weekStartDate(weekOneMonday, week) {
487
533
  return addLocalDays(parseLocalMonday(weekOneMonday), (week - 1) * 7);
488
534
  }
489
- function densityMonthText(weekOneMonday, startWeek, count, lang, maxWidth = Number.POSITIVE_INFINITY) {
535
+ function densityMonthText(weekOneMonday, startWeek, count, lang, maxWidth) {
490
536
  let text = '';
491
537
  let visualCol = 0;
492
538
  let previousMonth = -1;
@@ -499,104 +545,93 @@ function densityMonthText(weekOneMonday, startWeek, count, lang, maxWidth = Numb
499
545
  const label = new Intl.DateTimeFormat(lang === 'zh' ? 'zh-CN' : 'en-US', {
500
546
  month: 'short',
501
547
  }).format(date);
502
- const targetCol = index * 2;
503
- if (targetCol + visualWidth(label) > maxWidth)
548
+ const targetCol = index * DENSITY_COL;
549
+ if (targetCol < visualCol || targetCol + visualWidth(label) > maxWidth)
504
550
  continue;
505
- if (targetCol > visualCol)
506
- text += ' '.repeat(targetCol - visualCol);
507
- text += label;
551
+ text += ' '.repeat(targetCol - visualCol) + label;
508
552
  visualCol = targetCol + visualWidth(label);
509
553
  }
510
554
  return text;
511
555
  }
512
- function densityMarkerText(index, width, marker, label) {
513
- const markerCol = index * 2;
556
+ function densityMarkerLines(index, width, marker, label) {
557
+ const markerCol = index * DENSITY_COL;
514
558
  const after = `${' '.repeat(markerCol)}${marker} ${label}`;
515
559
  if (visualWidth(after) <= width)
516
- return after;
560
+ return [after];
517
561
  const beforeStart = markerCol - visualWidth(label) - 1;
518
562
  if (beforeStart >= 0)
519
- return `${' '.repeat(beforeStart)}${label} ${marker}`;
520
- return `${' '.repeat(markerCol)}${marker}`;
563
+ return [`${' '.repeat(beforeStart)}${label} ${marker}`];
564
+ return [`${' '.repeat(markerCol)}${marker}`, label];
521
565
  }
522
566
  export function renderTermDensity(meetings, weekOneMonday, currentWeek, cols = Number.POSITIVE_INFINITY) {
523
- const trans = t();
567
+ const trans = t().timetable;
524
568
  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);
569
+ const width = bodyWidth(cols);
570
+ const indent = visualWidth(space.indent) < width ? space.indent : '';
571
+ const contentWidth = Math.max(1, width - visualWidth(indent));
572
+ const wrap = (text) => wrapAnsiToVisualWidth(text, contentWidth).map((part) => `${indent}${part}`);
573
+ const lines = wrap(type.heading(trans.termDensityTitle));
574
+ const allWeeks = meetings.flatMap((m) => m.weeks);
575
+ if (allWeeks.length === 0) {
576
+ return [...lines, ...wrap(type.hint(trans.termDensityEmpty))].join('\n');
544
577
  }
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,
578
+ const firstWeek = Math.min(1, ...allWeeks);
579
+ 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));
580
+ const busy = slots.filter((value) => value > 0);
581
+ const low = Math.min(...busy);
582
+ const high = Math.max(...busy);
583
+ const current = currentWeek - firstWeek;
584
+ const currentSlots = slots[current];
585
+ const freeWeeks = slots.length - busy.length;
586
+ const summary = [
587
+ fmt(trans.termDensityWeeks, { weeks: String(slots.length) }),
588
+ ...(freeWeeks > 0 ? [fmt(trans.termDensityFreeWeeks, { count: String(freeWeeks) })] : []),
589
+ fmt(trans.termDensityPerWeek, {
590
+ periods: low === high ? String(high) : rangeLabel(String(low), String(high)),
591
+ }),
592
+ ...(currentSlots === undefined
593
+ ? []
594
+ : [fmt(trans.termDensityCurrent, { periods: String(currentSlots) })]),
574
595
  ];
575
- 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');
596
+ const summaryLines = [];
597
+ for (const part of summary) {
598
+ const joined = `${summaryLines.at(-1) ?? ''} ${glyph.sep()} ${part}`;
599
+ if (summaryLines.length > 0 && visualWidth(joined) <= contentWidth) {
600
+ summaryLines[summaryLines.length - 1] = joined;
601
+ }
602
+ else {
603
+ summaryLines.push(part);
604
+ }
578
605
  }
579
- const indent = visualWidth(space.indent) < width ? space.indent : '';
580
- 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))}`);
606
+ lines.push(...summaryLines.flatMap((line) => wrap(type.hint(line))));
607
+ const axisW = visualWidth(String(high));
608
+ const gutter = ' '.repeat(axisW + 3);
609
+ const perChunk = Math.max(1, Math.floor((contentWidth - gutter.length + 1) / DENSITY_COL));
610
+ for (let start = 0; start < slots.length; start += perChunk) {
611
+ const chunk = slots.slice(start, start + perChunk);
612
+ const style = (index) => start + index === current ? type.active : type.body;
613
+ lines.push('');
614
+ for (let row = DENSITY_HEIGHT - 1; row >= 0; row -= 1) {
615
+ const top = row === DENSITY_HEIGHT - 1;
616
+ const axis = `${(top ? String(high) : '').padStart(axisW)} ${top ? pickIcon('┤', '+') : glyph.bar()}`;
617
+ const bars = chunk.map((value, index) => {
618
+ const eighths = value === 0 ? 0 : Math.max(1, Math.round((value / high) * DENSITY_HEIGHT * 8));
619
+ return style(index)(barGlyph(eighths - row * 8).repeat(DENSITY_COL - 1));
620
+ });
621
+ lines.push(`${indent}${type.hint(axis)} ${bars.join(' ')}`);
622
+ }
623
+ lines.push(`${indent}${type.hint(`${'0'.padStart(axisW)} ${pickIcon('└', '+')}${glyph.rule().repeat(chunk.length * DENSITY_COL)}`)}`);
624
+ const numbers = chunk.map((_, index) => {
625
+ const label = String(firstWeek + start + index).padStart(DENSITY_COL - 1);
626
+ return start + index === current ? type.active(label) : type.hint(label);
627
+ });
628
+ lines.push(`${indent}${gutter}${numbers.join(' ')}`);
629
+ const room = contentWidth - gutter.length;
630
+ lines.push(`${indent}${gutter}${type.hint(densityMonthText(weekOneMonday, firstWeek + start, chunk.length, lang, room))}`);
631
+ if (current >= start && current < start + chunk.length) {
632
+ const marker = densityMarkerLines(current - start, room, pickIcon('↑', '^'), trans.termDensityThisWeek);
633
+ lines.push(...marker.map((line) => `${indent}${gutter}${type.hint(line)}`));
597
634
  }
598
635
  }
599
- lines.push('');
600
- lines.push(...wrapAnsiToVisualWidth(legendContent, contentWidth).map((part) => `${indent}${part}`));
601
636
  return lines.join('\n');
602
637
  }
@@ -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) => ({