@nbtca/prompt 1.5.15 → 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.
package/dist/app/app.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { ansi, ensureCursorRestored } from '../core/canvas.js';
2
- import { composeFrameLines, computeBodyRows, diffFrame } from './frame.js';
2
+ import { composeFrameLines, computeBodyRows, diffFrame, frameWidth } from './frame.js';
3
3
  import { isPrintableKey, KeyStreamDecoder, routeGlobalKey } from './keys.js';
4
4
  import { renderHeader, renderFooter, resolveChromeLayout } from './chrome.js';
5
5
  import { homeView } from './views/home.js';
@@ -46,9 +46,13 @@ export async function runApp() {
46
46
  .finally(() => pendingLoads.delete(id));
47
47
  pendingLoads.set(id, pending);
48
48
  }
49
- function size() {
49
+ function terminalSize() {
50
50
  return { rows: process.stdout.rows || 24, cols: process.stdout.columns || 80 };
51
51
  }
52
+ function size() {
53
+ const terminal = terminalSize();
54
+ return { rows: terminal.rows, cols: frameWidth(terminal.cols) };
55
+ }
52
56
  const ctx = {
53
57
  signal: lifecycle.signal,
54
58
  get size() {
@@ -76,6 +80,7 @@ export async function runApp() {
76
80
  if (suspended || !running)
77
81
  return;
78
82
  const { rows, cols } = size();
83
+ const terminalCols = terminalSize().cols;
79
84
  const active = nativeViews[view];
80
85
  const tabs = getAppTabs();
81
86
  const chrome = resolveChromeLayout(rows);
@@ -88,9 +93,9 @@ export async function runApp() {
88
93
  const height = computeBodyRows(rows, chrome.headerLines, chrome.footerLines);
89
94
  lastBody = { length: body.length, height };
90
95
  const footer = renderFooter(view, cols, tabs.length, helpOpen ? t().help.close : active?.footerHint?.(tabs.length, cols), chrome.footerLines, !helpOpen && active?.scrollsBody?.() === true ? scrollPercent() : undefined);
91
- const lines = composeFrameLines(header, body, footer, rows, cols, bodyScroll);
92
- const patch = diffFrame(painted?.cols === cols ? painted.lines : undefined, lines);
93
- painted = { cols, lines };
96
+ const lines = composeFrameLines(header, body, footer, rows, terminalCols, bodyScroll);
97
+ const patch = diffFrame(painted?.cols === terminalCols ? painted.lines : undefined, lines);
98
+ painted = { cols: terminalCols, lines };
94
99
  if (patch)
95
100
  process.stdout.write(patch);
96
101
  scheduleBusyTick(active?.isBusy?.() === true);
@@ -1,7 +1,7 @@
1
- import { type, space, glyph, brandMark, MAX_FRAME_COLS } from '../core/theme.js';
1
+ import { c, type, space, glyph, brandMark } from '../core/theme.js';
2
2
  import { pickIcon } from '../core/icons.js';
3
3
  import { t } from '../i18n/index.js';
4
- import { clipAnsiToVisualWidth, visualWidth } from '../core/text.js';
4
+ import { clipAnsiToVisualWidth, visualWidth, wrapAnsiWithIndent } from '../core/text.js';
5
5
  export const HEADER_LINES = 3;
6
6
  export const FOOTER_LINES = 2;
7
7
  export function resolveChromeLayout(rows) {
@@ -19,8 +19,7 @@ export function resolveChromeLayout(rows) {
19
19
  return { headerLines: 0, footerLines: 0 };
20
20
  }
21
21
  function renderRule(cols) {
22
- const terminal = Number.isFinite(cols) ? Math.max(1, Math.floor(cols)) : 80;
23
- const width = Math.min(terminal, MAX_FRAME_COLS);
22
+ const width = Number.isFinite(cols) ? Math.max(1, Math.floor(cols)) : 80;
24
23
  const indent = visualWidth(space.indent) < width ? space.indent : '';
25
24
  const ruleWidth = Math.max(1, width - visualWidth(indent) * 2);
26
25
  return indent + type.hint(glyph.rule().repeat(ruleWidth));
@@ -94,6 +93,10 @@ export function renderHeader(views, active, cols, lineCount = HEADER_LINES, cont
94
93
  return [brand, tabs];
95
94
  return [brand, tabs, rule];
96
95
  }
96
+ export function offlineNotice(cols) {
97
+ const notice = `${c.warn(pickIcon('⚠', '!'))} ${t().common.offline}`;
98
+ return [...wrapAnsiWithIndent(notice, cols, space.indent), ''];
99
+ }
97
100
  export function fitFooterHint(cols, ...candidates) {
98
101
  return (candidates.find((candidate) => visualWidth(space.indent + candidate) <= cols) ??
99
102
  candidates[candidates.length - 1] ??
@@ -149,9 +152,8 @@ export function renderFooter(_active, cols, tabCount, overrideHint, lineCount =
149
152
  function withPosition(hint, hintText, indent, position, cols) {
150
153
  if (position === undefined)
151
154
  return hint;
152
- const frame = Math.min(cols, MAX_FRAME_COLS);
153
- const margin = visualWidth(space.indent) < frame ? space.indent : '';
154
- const gap = frame - visualWidth(indent + hintText) - visualWidth(position) - visualWidth(margin);
155
+ const margin = visualWidth(space.indent) < cols ? space.indent : '';
156
+ const gap = cols - visualWidth(indent + hintText) - visualWidth(position) - visualWidth(margin);
155
157
  if (gap < 2)
156
158
  return hint;
157
159
  return hint + ' '.repeat(gap) + type.hint(position) + margin;
package/dist/app/frame.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { ansi } from '../core/canvas.js';
2
+ import { MAX_FRAME_COLS } from '../core/theme.js';
2
3
  import { clipAnsiToVisualWidth, visualWidth } from '../core/text.js';
3
4
  export function clipToWidth(line, cols) {
4
5
  if (visualWidth(line) <= cols)
@@ -18,12 +19,18 @@ export function fitBody(lines, height, scroll, cols) {
18
19
  out.push(' '.repeat(cols));
19
20
  return out;
20
21
  }
22
+ export function frameWidth(cols) {
23
+ return Math.min(cols, MAX_FRAME_COLS);
24
+ }
21
25
  export function composeFrameLines(header, body, footer, rows, cols, scroll) {
22
- const h = header.map((l) => fitLine(l, cols));
23
- const f = footer.map((l) => fitLine(l, cols));
26
+ const width = frameWidth(cols);
27
+ const left = ' '.repeat(Math.floor((cols - width) / 2));
28
+ const right = ' '.repeat(cols - width - left.length);
29
+ const h = header.map((l) => fitLine(l, width));
30
+ const f = footer.map((l) => fitLine(l, width));
24
31
  const bodyH = Math.max(0, rows - h.length - f.length);
25
- const b = fitBody(body, bodyH, scroll, cols);
26
- return [...h, ...b, ...f].slice(0, rows);
32
+ const b = fitBody(body, bodyH, scroll, width);
33
+ return [...h, ...b, ...f].slice(0, rows).map((line) => left + line + right);
27
34
  }
28
35
  export function diffFrame(prev, next) {
29
36
  if (prev?.length !== next.length)
@@ -1,6 +1,7 @@
1
1
  import { type, space } from '../../core/theme.js';
2
2
  import { t } from '../../i18n/index.js';
3
3
  import { renderListFieldWithContext } from '../fields/list-field.js';
4
+ import { offlineNotice } from '../chrome.js';
4
5
  import { visualWidth, wrapAnsiWithIndent } from '../../core/text.js';
5
6
  import { loadingLines } from '../../core/components/spinner.js';
6
7
  function hintLines(label, cols) {
@@ -41,17 +42,19 @@ export function renderDocs(state, cols = 80, bodyRows = Number.POSITIVE_INFINITY
41
42
  break;
42
43
  case 'sections':
43
44
  lines = state.sectionsField
44
- ? renderListFieldWithContext(state.stale ? [...hintLines(trans.docs.stale, cols), ''] : [], state.sectionsField, bodyRows, cols)
45
+ ? renderListFieldWithContext(state.stale ? offlineNotice(cols) : [], state.sectionsField, bodyRows, cols)
45
46
  : [];
46
47
  break;
47
48
  case 'files':
48
- lines = state.filesField?.render(bodyRows, cols) ?? [];
49
+ lines = state.filesField?.render(bodyRows, cols) ?? loadingLines(trans.common.loading, cols);
49
50
  break;
50
51
  case 'archivedGroups':
51
52
  lines = state.archivedGroupsField?.render(bodyRows, cols) ?? [];
52
53
  break;
53
54
  case 'archivedFiles':
54
- lines = state.archivedFilesField?.render(bodyRows, cols) ?? [];
55
+ lines =
56
+ state.archivedFilesField?.render(bodyRows, cols) ??
57
+ loadingLines(trans.common.loading, cols);
55
58
  break;
56
59
  case 'search':
57
60
  lines = state.searchField?.render(cols) ?? [];
@@ -7,7 +7,7 @@ import { pickIcon } from '../../core/icons.js';
7
7
  import { glyph } from '../../core/theme.js';
8
8
  import { fmt, getCurrentLanguage, t } from '../../i18n/index.js';
9
9
  import { sanitizeTerminalLine, truncate } from '../../core/text.js';
10
- import { localizeDocSections, fetchSections, peekSections, fetchDocMetadata, fetchSectionMetadata, searchDocuments, getArchivedGroups, displayDocTitle, loadDocForReader, openDocsInBrowser, docsUrlFromPath, clearDocsCache, } from '../../features/docs.js';
10
+ import { localizeDocSections, fetchSections, peekSections, fetchDocMetadata, fetchSectionMetadata, peekListedDocs, searchDocuments, getArchivedGroups, displayDocTitle, loadDocForReader, openDocsInBrowser, docsUrlFromPath, clearDocsCache, } from '../../features/docs.js';
11
11
  let state = { mode: 'loading' };
12
12
  let sections = [];
13
13
  let archivedGroups = new Map();
@@ -177,12 +177,12 @@ function relocalizeStateFields(value, maxVisible) {
177
177
  if (value.mode === 'sections') {
178
178
  return { ...value, sectionsField: buildSectionsField() };
179
179
  }
180
- if (value.mode === 'files' && currentSectionKey) {
180
+ if (value.mode === 'files' && value.filesField && currentSectionKey) {
181
181
  const section = sections.find((candidate) => candidate.key === currentSectionKey);
182
182
  return section
183
183
  ? {
184
184
  ...value,
185
- filesField: buildFilesField(section, maxVisible, value.filesField?.selectedIndex),
185
+ filesField: buildFilesField(section, maxVisible, value.filesField.selectedIndex),
186
186
  }
187
187
  : value;
188
188
  }
@@ -192,10 +192,10 @@ function relocalizeStateFields(value, maxVisible) {
192
192
  archivedGroupsField: buildArchivedGroupsField(archivedGroups, maxVisible, value.archivedGroupsField?.selectedIndex),
193
193
  };
194
194
  }
195
- if (value.mode === 'archivedFiles' && currentArchivedGroupKey) {
195
+ if (value.mode === 'archivedFiles' && value.archivedFilesField && currentArchivedGroupKey) {
196
196
  return {
197
197
  ...value,
198
- archivedFilesField: buildArchivedFilesField(currentArchivedGroupKey, archivedGroups.get(currentArchivedGroupKey) ?? [], maxVisible, value.archivedFilesField?.selectedIndex),
198
+ archivedFilesField: buildArchivedFilesField(currentArchivedGroupKey, archivedGroups.get(currentArchivedGroupKey) ?? [], maxVisible, value.archivedFilesField.selectedIndex),
199
199
  };
200
200
  }
201
201
  if (value.mode === 'searchResults') {
@@ -227,10 +227,13 @@ async function openSectionFiles(ctx, section) {
227
227
  return;
228
228
  const requestId = ++metadataRequestId;
229
229
  currentSectionKey = section.key;
230
- state = {
231
- mode: 'files',
232
- filesField: buildFilesField(section, computeMaxVisible(ctx.bodyRows)),
233
- };
230
+ const stored = peekListedDocs(section.files);
231
+ const known = { ...section, files: stored.docs };
232
+ state = { mode: 'files', filesField: buildFilesField(known, computeMaxVisible(ctx.bodyRows)) };
233
+ if (stored.complete) {
234
+ replaceSection(known);
235
+ return;
236
+ }
234
237
  ctx.rerender();
235
238
  try {
236
239
  const hydrated = await fetchSectionMetadata(section, ctx.signal);
@@ -252,7 +255,11 @@ async function openSectionFiles(ctx, section) {
252
255
  state.mode !== 'files' ||
253
256
  currentSectionKey !== section.key)
254
257
  return;
255
- state = { ...state, errorMessage: t().docs.loadError };
258
+ state = {
259
+ mode: 'files',
260
+ filesField: buildFilesField(section, computeMaxVisible(ctx.bodyRows)),
261
+ errorMessage: t().docs.loadError,
262
+ };
256
263
  }
257
264
  if (isLifecycleActive(ctx, generation))
258
265
  ctx.rerender();
@@ -263,10 +270,15 @@ async function openArchivedFiles(ctx, groupKey, groupFiles) {
263
270
  return;
264
271
  const requestId = ++metadataRequestId;
265
272
  currentArchivedGroupKey = groupKey;
273
+ const stored = peekListedDocs(groupFiles);
266
274
  state = {
267
275
  mode: 'archivedFiles',
268
- archivedFilesField: buildArchivedFilesField(groupKey, groupFiles, computeMaxVisible(ctx.bodyRows)),
276
+ archivedFilesField: buildArchivedFilesField(groupKey, stored.docs, computeMaxVisible(ctx.bodyRows)),
269
277
  };
278
+ if (stored.complete) {
279
+ archivedGroups.set(groupKey, stored.docs);
280
+ return;
281
+ }
270
282
  ctx.rerender();
271
283
  try {
272
284
  const hydrated = await fetchDocMetadata(groupFiles, ctx.signal);
@@ -288,7 +300,8 @@ async function openArchivedFiles(ctx, groupKey, groupFiles) {
288
300
  currentArchivedGroupKey !== groupKey)
289
301
  return;
290
302
  state = {
291
- ...state,
303
+ mode: 'archivedFiles',
304
+ archivedFilesField: buildArchivedFilesField(groupKey, groupFiles, computeMaxVisible(ctx.bodyRows)),
292
305
  errorMessage: t().docs.loadError,
293
306
  };
294
307
  }
@@ -1,6 +1,7 @@
1
1
  import { type, space } from '../../core/theme.js';
2
2
  import { t } from '../../i18n/index.js';
3
3
  import { renderListFieldWithContext } from '../fields/list-field.js';
4
+ import { offlineNotice } from '../chrome.js';
4
5
  import { renderCountdownBanner, renderEventBriefLines, } from '../../features/calendar.js';
5
6
  import { renderHeatmap } from '../../features/calendar-heatmap.js';
6
7
  import { wrapAnsiWithIndent } from '../../core/text.js';
@@ -16,7 +17,7 @@ function renderHubBody(state, now, bodyRows, cols) {
16
17
  ? Math.max(0, Math.floor(bodyRows))
17
18
  : Number.POSITIVE_INFINITY;
18
19
  if (state.stale)
19
- lines.push(...wrappedIndentedLines(trans.calendar.stale, cols, type.hint), '');
20
+ lines.push(...offlineNotice(cols ?? Number.POSITIVE_INFINITY));
20
21
  const banner = renderCountdownBanner(state.nextEvent, now, cols);
21
22
  if (banner)
22
23
  lines.push(...banner.split('\n'), '');
@@ -5,7 +5,7 @@ import { padEndV, visualWidth, wrapAnsiWithIndent } from '../../core/text.js';
5
5
  import { nextClassLine, peekSchedule, todayLines, weekAheadInfo, } from '../../features/schedule-view.js';
6
6
  import { loadCalendarOrThrow, peekCalendar, toDisplayEvent, renderEventBrief, } from '../../features/calendar.js';
7
7
  import { weekdayShortLabel } from '../../features/schedule-render.js';
8
- import { passiveFooterHint } from '../chrome.js';
8
+ import { offlineNotice, passiveFooterHint } from '../chrome.js';
9
9
  import { campusDateTime, campusIsoDate } from '@nbtca/nbtcal/timetable';
10
10
  import { isoDayDifference, localDayDifference, parseLocalDate } from '../../core/calendar-day.js';
11
11
  import { currentEvents } from '../../features/calendar-query.js';
@@ -74,7 +74,8 @@ function renderWeekAheadGrid(classDays, eventDays, cols) {
74
74
  }
75
75
  export function renderHome(data, now, bodyRows = 100, cols = 80) {
76
76
  const trans = t();
77
- const lines = [];
77
+ const eventsStale = data.eventsLoadFailed === true && (data.eventLines?.length ?? 0) > 0;
78
+ const lines = eventsStale ? offlineNotice(cols) : [];
78
79
  if (data.schedule === null) {
79
80
  lines.push(...panelHeading(trans.timetable.menuTitle, cols));
80
81
  lines.push(...wrappedIndentedLines(fmt(trans.timetable.homeLoginCta, {
@@ -103,10 +104,7 @@ export function renderHome(data, now, bodyRows = 100, cols = 80) {
103
104
  lines.push(...wrappedIndentedLines(`${pickIcon('⚠', '!')} ${trans.timetable.hubUnresolved} · ${unresolvedCount}`, cols, c.warn));
104
105
  lines.push('');
105
106
  }
106
- const eventsStale = data.eventsLoadFailed === true && (data.eventLines?.length ?? 0) > 0;
107
- lines.push(...(eventsStale
108
- ? wrappedIndentedLines(`${type.heading(trans.menu.events)} ${type.hint(`${pickIcon('·', '-')} ${trans.calendar.stale}`)}`, cols, (value) => value)
109
- : panelHeading(trans.menu.events, cols)));
107
+ lines.push(...panelHeading(trans.menu.events, cols));
110
108
  if (data.eventLines && data.eventLines.length > 0) {
111
109
  const remaining = Number.isFinite(bodyRows)
112
110
  ? Math.max(0, Math.floor(bodyRows) - lines.length)
package/dist/cli.js CHANGED
@@ -264,7 +264,7 @@ async function runEventsCommand(flags) {
264
264
  }
265
265
  const { calendar, stale } = await loadCalendarOrCache();
266
266
  if (stale)
267
- console.error(chalk.yellow(t().calendar.stale));
267
+ console.error(chalk.yellow(t().common.offline));
268
268
  const now = new Date();
269
269
  if (flags.has('--heatmap')) {
270
270
  const buckets = yearHeatmap(calendar, now);
@@ -60,8 +60,7 @@ export const glyph = {
60
60
  barFilled: () => pickIcon('█', '#'),
61
61
  barEmpty: () => pickIcon('░', '-'),
62
62
  };
63
- /** Beyond this the app stops stretching; a terminal wider than this keeps the slack. */
64
- export const MAX_FRAME_COLS = 100;
63
+ export const MAX_FRAME_COLS = 120;
65
64
  export const space = {
66
65
  indent: ' ',
67
66
  };
@@ -2,10 +2,40 @@ import fs from 'fs';
2
2
  import path from 'path';
3
3
  import { getStateDir, getWritableStateDir } from '../config/paths.js';
4
4
  const FEED_FILE = 'calendar-feed.ics';
5
+ const VALIDATORS_FILE = 'calendar-feed.json';
5
6
  const MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
6
- export function saveFeedCache(text, dir) {
7
+ const HEADER_VALUE = /^[\x21-\x7e][\x20-\x7e]*$/;
8
+ function headerValue(value) {
9
+ return typeof value === 'string' && HEADER_VALUE.test(value) ? value : undefined;
10
+ }
11
+ function readValidators(dir) {
12
+ try {
13
+ const data = JSON.parse(fs.readFileSync(path.join(dir, VALIDATORS_FILE), 'utf8'));
14
+ const etag = headerValue(data['etag']);
15
+ const lastModified = headerValue(data['lastModified']);
16
+ return { ...(etag ? { etag } : {}), ...(lastModified ? { lastModified } : {}) };
17
+ }
18
+ catch {
19
+ return {};
20
+ }
21
+ }
22
+ // Validators are written after the text and read before it, so they can never be newer than the text.
23
+ export function saveFeedCache({ text, validators }, dir) {
24
+ try {
25
+ const target = dir ?? getWritableStateDir();
26
+ fs.writeFileSync(path.join(target, FEED_FILE), text, { encoding: 'utf8', mode: 0o600 });
27
+ touchFeedCache(validators, target);
28
+ }
29
+ catch {
30
+ /* best effort */
31
+ }
32
+ }
33
+ export function touchFeedCache(validators, dir) {
7
34
  try {
8
- fs.writeFileSync(path.join(dir ?? getWritableStateDir(), FEED_FILE), text, {
35
+ const target = dir ?? getWritableStateDir();
36
+ const now = new Date();
37
+ fs.utimesSync(path.join(target, FEED_FILE), now, now);
38
+ fs.writeFileSync(path.join(target, VALIDATORS_FILE), JSON.stringify(validators), {
9
39
  encoding: 'utf8',
10
40
  mode: 0o600,
11
41
  });
@@ -16,10 +46,12 @@ export function saveFeedCache(text, dir) {
16
46
  }
17
47
  export function loadFeedCache(dir, maxAgeMs = MAX_AGE_MS) {
18
48
  try {
19
- const file = path.join(dir ?? getStateDir(), FEED_FILE);
49
+ const source = dir ?? getStateDir();
50
+ const validators = readValidators(source);
51
+ const file = path.join(source, FEED_FILE);
20
52
  if (Date.now() - fs.statSync(file).mtimeMs > maxAgeMs)
21
53
  return null;
22
- return fs.readFileSync(file, 'utf8');
54
+ return { text: fs.readFileSync(file, 'utf8'), validators };
23
55
  }
24
56
  catch {
25
57
  return null;
@@ -1,4 +1,4 @@
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';
@@ -6,7 +6,7 @@ import { padEndV, sanitizeTerminalLine, sanitizeTerminalText, truncate, visualWi
6
6
  import { t } from '../i18n/index.js';
7
7
  import { localDayDifference } from '../core/calendar-day.js';
8
8
  import { countdownParts, isCountdownUrgent, buildExportFilename, formatDuration, pastYearRange, } from './calendar-query.js';
9
- import { loadFeedCache, saveFeedCache } from './calendar-store.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) {
@@ -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
  }
@@ -265,7 +265,7 @@ export function renderWeekGrid(timetable, weekNumber, now, cols = 80, cursor) {
265
265
  const availableForCols = Math.max(0, cols - fixedOverhead);
266
266
  const evenColW = Math.max(...idealColWidths);
267
267
  const totalIdealColW = idealColWidths.reduce((a, b) => a + b, 0);
268
- const colWidths = evenColW * 7 <= availableForCols
268
+ const colWidths = evenColW * 7 <= availableForCols - space.indent.length
269
269
  ? idealColWidths.map(() => evenColW)
270
270
  : totalIdealColW <= availableForCols
271
271
  ? idealColWidths
@@ -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 last fetched data"
14
15
  },
15
16
  "help": {
16
17
  "title": "Keys",
@@ -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",
@@ -125,7 +125,6 @@
125
125
  "chooseCategory": "Docs",
126
126
  "refreshCache": "Refresh cache",
127
127
  "cacheCleared": "Documentation cache cleared",
128
- "stale": "offline, showing last known docs",
129
128
  "currentDir": "Current directory",
130
129
  "chooseDoc": "Choose a document or directory",
131
130
  "emptyDir": "This directory is empty",
@@ -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": "日期时间",
@@ -125,7 +125,6 @@
125
125
  "chooseCategory": "文档",
126
126
  "refreshCache": "刷新缓存",
127
127
  "cacheCleared": "文档缓存已清除",
128
- "stale": "离线,显示上次获取的文档",
129
128
  "currentDir": "当前目录",
130
129
  "chooseDoc": "选择文档或目录",
131
130
  "emptyDir": "该目录为空",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nbtca/prompt",
3
- "version": "1.5.15",
3
+ "version": "1.5.16",
4
4
  "type": "module",
5
5
  "main": "dist/index.js",
6
6
  "exports": {
@@ -47,7 +47,7 @@
47
47
  ],
48
48
  "dependencies": {
49
49
  "@nbtca/docs": "^0.3.2",
50
- "@nbtca/nbtcal": "^0.4.2",
50
+ "@nbtca/nbtcal": "^0.4.3",
51
51
  "chalk": "^5.6.2",
52
52
  "marked": "^15.0.12"
53
53
  },