@nbtca/prompt 1.5.16 → 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.
@@ -6,8 +6,9 @@ import { setVimKeysActive } from '../../core/vim-keys.js';
6
6
  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
- import { sanitizeTerminalLine, truncate } from '../../core/text.js';
10
- import { localizeDocSections, fetchSections, peekSections, fetchDocMetadata, fetchSectionMetadata, peekListedDocs, searchDocuments, getArchivedGroups, displayDocTitle, loadDocForReader, openDocsInBrowser, docsUrlFromPath, clearDocsCache, } from '../../features/docs.js';
9
+ import { sanitizeTerminalLine } from '../../core/text.js';
10
+ import { localizeDocSections, fetchSections, peekSections, fetchDocMetadata, fetchSectionMetadata, peekListedDocs, searchDocuments, getArchivedGroups, displayDocTitle, loadDocForReader, openDocsInBrowser, docsUrlFromPath, clearDocsCache, withFileNameTitle, } from '../../features/docs.js';
11
+ import { launchBrowserUrl } from '../../features/links.js';
11
12
  let state = { mode: 'loading' };
12
13
  let sections = [];
13
14
  let archivedGroups = new Map();
@@ -17,6 +18,7 @@ let loadedLanguage = null;
17
18
  let currentSectionKey = null;
18
19
  let currentArchivedGroupKey = null;
19
20
  let currentSearchResults = [];
21
+ let currentSearchQuery = '';
20
22
  let sectionsRequestId = 0;
21
23
  let metadataRequestId = 0;
22
24
  let searchRequestId = 0;
@@ -26,7 +28,6 @@ let readerPrevState = null;
26
28
  let readerLoadingPrevState = null;
27
29
  let readerRequestId = 0;
28
30
  let lifecycleGeneration = 0;
29
- const DOC_HINT_WIDTH = 44;
30
31
  function isLifecycleActive(ctx, generation) {
31
32
  return generation === lifecycleGeneration && ctx.signal?.aborted !== true;
32
33
  }
@@ -40,10 +41,10 @@ function backLabel() {
40
41
  return t().common.back;
41
42
  }
42
43
  function optionalHint(hint) {
43
- return hint === undefined ? {} : { hint };
44
+ return hint ? { hint, hintColumn: true } : {};
44
45
  }
45
- function docHint(value) {
46
- return value ? truncate(value, DOC_HINT_WIDTH) : undefined;
46
+ function docLabel(doc) {
47
+ return doc.title ? { label: doc.title } : { label: pickIcon('…', '...'), dim: true };
47
48
  }
48
49
  function withoutReaderLinksField(value) {
49
50
  const next = { ...value };
@@ -55,21 +56,16 @@ function withoutErrorMessage(value) {
55
56
  delete next.errorMessage;
56
57
  return next;
57
58
  }
58
- async function runBrowserOpen(ctx, path) {
59
+ async function openBrowserFromView(ctx, path, generation = lifecycleGeneration) {
60
+ await openUrlFromView(ctx, docsUrlFromPath(path), () => openDocsInBrowser(path, ctx.signal), generation);
61
+ }
62
+ async function openUrlFromView(ctx, url, open, generation = lifecycleGeneration) {
59
63
  let opened;
60
64
  await ctx.runClassic(async () => {
61
- opened =
62
- path === undefined
63
- ? await openDocsInBrowser(undefined, ctx.signal)
64
- : await openDocsInBrowser(path, ctx.signal);
65
+ opened = await open();
65
66
  });
66
- return opened;
67
- }
68
- async function openBrowserFromView(ctx, path, generation = lifecycleGeneration) {
69
- const opened = await runBrowserOpen(ctx, path);
70
67
  if (!isLifecycleActive(ctx, generation) || opened === true)
71
68
  return;
72
- const url = docsUrlFromPath(path);
73
69
  state = {
74
70
  ...state,
75
71
  errorMessage: sanitizeTerminalLine(`${t().docs.browserError}. ${fmt(t().links.openManually, { url })}`),
@@ -100,8 +96,8 @@ function buildFilesField(section, maxVisible, initialIndex = 0) {
100
96
  ...(index ? [{ value: index.path, label: trans.docs.overviewLabel }] : []),
101
97
  ...files.map((file) => ({
102
98
  value: file.path,
103
- label: displayDocTitle(file.name, file.title),
104
- ...optionalHint(docHint(file.summary)),
99
+ ...docLabel(file),
100
+ ...optionalHint(file.summary),
105
101
  })),
106
102
  { value: '__back__', label: backLabel() },
107
103
  ];
@@ -134,10 +130,10 @@ function buildArchivedFilesField(groupKey, groupFiles, maxVisible, initialIndex
134
130
  const sub = f.path.split('/').slice(2, -1).join('/');
135
131
  return {
136
132
  value: f.path,
137
- label: displayDocTitle(f.name, f.title),
138
- ...optionalHint(docHint(subDirs.size > 1
133
+ ...docLabel(f),
134
+ ...optionalHint(subDirs.size > 1
139
135
  ? [sanitizeTerminalLine(sub), f.summary].filter(Boolean).join(' · ')
140
- : f.summary)),
136
+ : f.summary),
141
137
  };
142
138
  }),
143
139
  { value: '__back__', label: backLabel() },
@@ -152,7 +148,14 @@ function buildArchivedFilesField(groupKey, groupFiles, maxVisible, initialIndex
152
148
  function buildReaderLinksField(links, maxVisible, initialIndex = 0) {
153
149
  const trans = t();
154
150
  const options = [
155
- ...links.map((l) => ({ value: l.href, label: l.text })),
151
+ ...links.map((l) => {
152
+ const address = l.external ? l.href.replace(/^https?:\/\//i, '').replace(/\/$/, '') : '';
153
+ return {
154
+ value: l.href,
155
+ label: l.text,
156
+ ...optionalHint(address === l.text ? undefined : address),
157
+ };
158
+ }),
156
159
  { value: '__back__', label: backLabel() },
157
160
  ];
158
161
  return new ListField({ title: trans.docs.readerLinksTitle, options, maxVisible, initialIndex });
@@ -163,15 +166,20 @@ function buildSearchResultsField(matches, maxVisible, initialIndex = 0) {
163
166
  ...matches.map((result) => ({
164
167
  value: result.path,
165
168
  label: displayDocTitle(result.name, result.title),
166
- ...optionalHint(docHint(result.excerpt ||
169
+ ...optionalHint(result.excerpt ||
167
170
  result.summary ||
168
171
  (result.path.includes('/')
169
172
  ? sanitizeTerminalLine(result.path.split('/').slice(0, -1).join('/'))
170
- : undefined))),
173
+ : undefined)),
171
174
  })),
172
175
  { value: '__back__', label: backLabel() },
173
176
  ];
174
- return new ListField({ title: trans.docs.chooseDoc, options, maxVisible, initialIndex });
177
+ return new ListField({
178
+ title: fmt(trans.docs.searchResultsTitle, { query: currentSearchQuery, count: matches.length }),
179
+ options,
180
+ maxVisible,
181
+ initialIndex,
182
+ });
175
183
  }
176
184
  function relocalizeStateFields(value, maxVisible) {
177
185
  if (value.mode === 'sections') {
@@ -218,6 +226,19 @@ function goToSections() {
218
226
  currentSearchResults = [];
219
227
  state = { mode: 'sections', sectionsField: buildSectionsField(), stale };
220
228
  }
229
+ function showLoadError() {
230
+ const trans = t();
231
+ state = {
232
+ mode: 'error',
233
+ errorMessage: trans.docs.offlineError,
234
+ errorField: new ListField({
235
+ options: [
236
+ { value: '__retry__', label: trans.docs.retryLoad },
237
+ { value: '__browser__', label: trans.docs.openBrowser },
238
+ ],
239
+ }),
240
+ };
241
+ }
221
242
  function replaceSection(section) {
222
243
  sections = sections.map((current) => (current.key === section.key ? section : current));
223
244
  }
@@ -229,37 +250,41 @@ async function openSectionFiles(ctx, section) {
229
250
  currentSectionKey = section.key;
230
251
  const stored = peekListedDocs(section.files);
231
252
  const known = { ...section, files: stored.docs };
232
- state = { mode: 'files', filesField: buildFilesField(known, computeMaxVisible(ctx.bodyRows)) };
253
+ const isCurrent = () => isLifecycleActive(ctx, generation) &&
254
+ requestId === metadataRequestId &&
255
+ state.mode === 'files' &&
256
+ currentSectionKey === section.key;
257
+ const show = (value, extra = {}) => {
258
+ state = {
259
+ mode: 'files',
260
+ filesField: buildFilesField(value, computeMaxVisible(ctx.bodyRows), state.filesField?.selectedIndex),
261
+ ...extra,
262
+ };
263
+ };
264
+ show(known);
233
265
  if (stored.complete) {
234
266
  replaceSection(known);
235
267
  return;
236
268
  }
237
269
  ctx.rerender();
238
270
  try {
239
- const hydrated = await fetchSectionMetadata(section, ctx.signal);
240
- if (!isLifecycleActive(ctx, generation) ||
241
- requestId !== metadataRequestId ||
242
- state.mode !== 'files' ||
243
- currentSectionKey !== section.key)
271
+ const hydrated = await fetchSectionMetadata(section, ctx.signal, (index, doc) => {
272
+ if (!isCurrent() || known.files[index]?.title)
273
+ return;
274
+ known.files[index] = doc;
275
+ show(known);
276
+ ctx.rerender();
277
+ });
278
+ if (!isCurrent())
244
279
  return;
245
280
  const localized = localizeDocSections([hydrated], t())[0] ?? hydrated;
246
281
  replaceSection(localized);
247
- state = {
248
- mode: 'files',
249
- filesField: buildFilesField(localized, computeMaxVisible(ctx.bodyRows), state.filesField?.selectedIndex),
250
- };
282
+ show(localized);
251
283
  }
252
284
  catch {
253
- if (!isLifecycleActive(ctx, generation) ||
254
- requestId !== metadataRequestId ||
255
- state.mode !== 'files' ||
256
- currentSectionKey !== section.key)
285
+ if (!isCurrent())
257
286
  return;
258
- state = {
259
- mode: 'files',
260
- filesField: buildFilesField(section, computeMaxVisible(ctx.bodyRows)),
261
- errorMessage: t().docs.loadError,
262
- };
287
+ show({ ...known, files: known.files.map(withFileNameTitle) }, { errorMessage: t().docs.loadError });
263
288
  }
264
289
  if (isLifecycleActive(ctx, generation))
265
290
  ctx.rerender();
@@ -271,39 +296,40 @@ async function openArchivedFiles(ctx, groupKey, groupFiles) {
271
296
  const requestId = ++metadataRequestId;
272
297
  currentArchivedGroupKey = groupKey;
273
298
  const stored = peekListedDocs(groupFiles);
274
- state = {
275
- mode: 'archivedFiles',
276
- archivedFilesField: buildArchivedFilesField(groupKey, stored.docs, computeMaxVisible(ctx.bodyRows)),
299
+ const isCurrent = () => isLifecycleActive(ctx, generation) &&
300
+ requestId === metadataRequestId &&
301
+ state.mode === 'archivedFiles' &&
302
+ currentArchivedGroupKey === groupKey;
303
+ const show = (files, extra = {}) => {
304
+ state = {
305
+ mode: 'archivedFiles',
306
+ archivedFilesField: buildArchivedFilesField(groupKey, files, computeMaxVisible(ctx.bodyRows), state.archivedFilesField?.selectedIndex),
307
+ ...extra,
308
+ };
277
309
  };
310
+ show(stored.docs);
278
311
  if (stored.complete) {
279
312
  archivedGroups.set(groupKey, stored.docs);
280
313
  return;
281
314
  }
282
315
  ctx.rerender();
283
316
  try {
284
- const hydrated = await fetchDocMetadata(groupFiles, ctx.signal);
285
- if (!isLifecycleActive(ctx, generation) ||
286
- requestId !== metadataRequestId ||
287
- state.mode !== 'archivedFiles' ||
288
- currentArchivedGroupKey !== groupKey)
317
+ const hydrated = await fetchDocMetadata(groupFiles, ctx.signal, (index, doc) => {
318
+ if (!isCurrent() || stored.docs[index]?.title)
319
+ return;
320
+ stored.docs[index] = doc;
321
+ show(stored.docs);
322
+ ctx.rerender();
323
+ });
324
+ if (!isCurrent())
289
325
  return;
290
326
  archivedGroups.set(groupKey, hydrated);
291
- state = {
292
- mode: 'archivedFiles',
293
- archivedFilesField: buildArchivedFilesField(groupKey, hydrated, computeMaxVisible(ctx.bodyRows), state.archivedFilesField?.selectedIndex),
294
- };
327
+ show(hydrated);
295
328
  }
296
329
  catch {
297
- if (!isLifecycleActive(ctx, generation) ||
298
- requestId !== metadataRequestId ||
299
- state.mode !== 'archivedFiles' ||
300
- currentArchivedGroupKey !== groupKey)
330
+ if (!isCurrent())
301
331
  return;
302
- state = {
303
- mode: 'archivedFiles',
304
- archivedFilesField: buildArchivedFilesField(groupKey, groupFiles, computeMaxVisible(ctx.bodyRows)),
305
- errorMessage: t().docs.loadError,
306
- };
332
+ show(stored.docs.map(withFileNameTitle), { errorMessage: t().docs.loadError });
307
333
  }
308
334
  if (isLifecycleActive(ctx, generation))
309
335
  ctx.rerender();
@@ -316,9 +342,15 @@ async function runSearch(ctx, query) {
316
342
  state = { mode: 'searchLoading' };
317
343
  ctx.rerender();
318
344
  try {
319
- const matches = await searchDocuments(query, ctx.signal);
345
+ const matches = await searchDocuments(query, ctx.signal, (done, total) => {
346
+ if (!isLifecycleActive(ctx, generation) || requestId !== searchRequestId)
347
+ return;
348
+ state = { mode: 'searchLoading', searchProgress: { done, total } };
349
+ ctx.rerender();
350
+ });
320
351
  if (!isLifecycleActive(ctx, generation) || requestId !== searchRequestId)
321
352
  return;
353
+ currentSearchQuery = query;
322
354
  currentSearchResults = matches;
323
355
  state = {
324
356
  mode: 'searchResults',
@@ -380,6 +412,25 @@ function enterReaderFrom(ctx, path) {
380
412
  readerCurrentPath = null;
381
413
  void openInReader(ctx, path, false);
382
414
  }
415
+ function reloadDocs(ctx) {
416
+ clearDocsCache();
417
+ sectionsRequestId++;
418
+ metadataRequestId++;
419
+ searchRequestId++;
420
+ loaded = false;
421
+ loadedLanguage = null;
422
+ sections = [];
423
+ archivedGroups = new Map();
424
+ currentSectionKey = null;
425
+ currentArchivedGroupKey = null;
426
+ currentSearchResults = [];
427
+ readerCurrentPath = null;
428
+ readerNavStack = [];
429
+ readerPrevState = null;
430
+ readerLoadingPrevState = null;
431
+ readerRequestId++;
432
+ void docsView.load(ctx);
433
+ }
383
434
  export const docsView = {
384
435
  id: 'docs',
385
436
  title: t().menu.docs,
@@ -436,7 +487,7 @@ export const docsView = {
436
487
  state = { ...state, stale };
437
488
  }
438
489
  else {
439
- state = { mode: 'error', errorMessage: t().docs.loadError };
490
+ showLoadError();
440
491
  }
441
492
  }
442
493
  if (isLifecycleActive(ctx, generation))
@@ -515,12 +566,15 @@ export const docsView = {
515
566
  state.mode === 'archivedGroups' ||
516
567
  state.mode === 'archivedFiles' ||
517
568
  state.mode === 'searchResults' ||
569
+ (state.mode === 'error' && state.errorField !== undefined) ||
518
570
  (state.mode === 'reader' && state.readerLinksField !== undefined));
519
571
  },
520
572
  footerHint(tabCount, cols = Number.POSITIVE_INFINITY) {
521
573
  if (state.mode === 'search')
522
574
  return captureFooterHint(cols);
523
- if (state.mode === 'loading' || state.mode === 'searchLoading' || state.mode === 'error')
575
+ if (state.mode === 'loading' ||
576
+ state.mode === 'searchLoading' ||
577
+ (state.mode === 'error' && !state.errorField))
524
578
  return passiveFooterHint(tabCount, cols);
525
579
  if (state.mode === 'readerLoading') {
526
580
  return fitFooterHint(cols, `${digitTabHint(tabCount)}q ${t().menu.hintQuit}`, `${digitTabHint(tabCount)}q`, 'q');
@@ -611,23 +665,7 @@ export const docsView = {
611
665
  return;
612
666
  }
613
667
  if (result.selected === '__refresh__') {
614
- clearDocsCache();
615
- sectionsRequestId++;
616
- metadataRequestId++;
617
- searchRequestId++;
618
- loaded = false;
619
- loadedLanguage = null;
620
- sections = [];
621
- archivedGroups = new Map();
622
- currentSectionKey = null;
623
- currentArchivedGroupKey = null;
624
- currentSearchResults = [];
625
- readerCurrentPath = null;
626
- readerNavStack = [];
627
- readerPrevState = null;
628
- readerLoadingPrevState = null;
629
- readerRequestId++;
630
- void docsView.load(ctx);
668
+ reloadDocs(ctx);
631
669
  return;
632
670
  }
633
671
  if (result.selected === '__browser__') {
@@ -726,8 +764,15 @@ export const docsView = {
726
764
  state = withoutReaderLinksField(state);
727
765
  return;
728
766
  }
729
- if (result.selected)
767
+ const link = state.readerLinks?.find((candidate) => candidate.href === result.selected);
768
+ if (link?.external) {
769
+ const href = link.href;
770
+ state = withoutReaderLinksField(state);
771
+ void openUrlFromView(ctx, href, () => launchBrowserUrl(href));
772
+ }
773
+ else if (result.selected) {
730
774
  void openInReader(ctx, result.selected, true);
775
+ }
731
776
  return;
732
777
  }
733
778
  if (key === 'f' && (state.readerLinks?.length ?? 0) > 0) {
@@ -743,7 +788,14 @@ export const docsView = {
743
788
  }
744
789
  return;
745
790
  }
746
- case 'error':
791
+ case 'error': {
792
+ const result = state.errorField?.handleKey(key);
793
+ if (result?.selected === '__retry__')
794
+ reloadDocs(ctx);
795
+ if (result?.selected === '__browser__')
796
+ void openBrowserFromView(ctx);
797
+ return;
798
+ }
747
799
  case 'loading':
748
800
  case 'readerLoading':
749
801
  case 'searchLoading':
@@ -10,6 +10,15 @@ function wrappedIndentedLines(label, cols, style) {
10
10
  return wrapAnsiWithIndent(style(label), cols ?? Number.POSITIVE_INFINITY, space.indent);
11
11
  }
12
12
  const EXPANDED_HUB_MIN_BODY_ROWS = 29;
13
+ export function hubShowsHeatmap(bodyRows, buckets = []) {
14
+ return bodyRows >= EXPANDED_HUB_MIN_BODY_ROWS && buckets.length > 0;
15
+ }
16
+ function heatmapLines(buckets, now, cols) {
17
+ return renderHeatmap(buckets, now, {
18
+ color: true,
19
+ ...(cols === undefined ? {} : { cols }),
20
+ }).split('\n');
21
+ }
13
22
  function renderHubBody(state, now, bodyRows, cols) {
14
23
  const trans = t();
15
24
  const lines = [];
@@ -22,13 +31,8 @@ function renderHubBody(state, now, bodyRows, cols) {
22
31
  if (banner)
23
32
  lines.push(...banner.split('\n'), '');
24
33
  const buckets = state.heatmapBuckets;
25
- if (bodyRows >= EXPANDED_HUB_MIN_BODY_ROWS && buckets && buckets.length > 0) {
26
- lines.push(...renderHeatmap(buckets, now, {
27
- color: true,
28
- ...(cols === undefined ? {} : { cols }),
29
- }).split('\n'));
30
- lines.push('');
31
- }
34
+ if (buckets && hubShowsHeatmap(bodyRows, buckets))
35
+ lines.push(...heatmapLines(buckets, now, cols), '');
32
36
  if (state.recentEvents && state.recentEvents.length > 0) {
33
37
  const activityHeading = wrappedIndentedLines(trans.calendar.recentActivity, cols, type.heading);
34
38
  const fieldRows = state.hubField
@@ -65,33 +69,36 @@ function renderHubBody(state, now, bodyRows, cols) {
65
69
  }
66
70
  export function renderEvents(state, now, bodyRows = 100, cols) {
67
71
  const trans = t();
72
+ const notice = state.stale ? offlineNotice(cols ?? Number.POSITIVE_INFINITY) : [];
68
73
  switch (state.mode) {
69
74
  case 'loading':
70
75
  return loadingLines(trans.calendar.loading, cols);
71
76
  case 'hub':
72
77
  return renderHubBody(state, now, bodyRows, cols);
73
78
  case 'heatmap':
74
- return state.heatmapBuckets && state.heatmapBuckets.length > 0
75
- ? renderHeatmap(state.heatmapBuckets, now, {
76
- color: true,
77
- ...(cols === undefined ? {} : { cols }),
78
- }).split('\n')
79
- : wrappedIndentedLines(trans.calendar.noEvents, cols, type.hint);
79
+ return [
80
+ ...notice,
81
+ ...(state.heatmapBuckets && state.heatmapBuckets.length > 0
82
+ ? heatmapLines(state.heatmapBuckets, now, cols)
83
+ : wrappedIndentedLines(trans.calendar.noEvents, cols, type.hint)),
84
+ ];
80
85
  case 'list': {
81
86
  if (!state.listField)
82
87
  return [];
83
- if (state.listNotice === undefined)
84
- return state.listField.render(bodyRows, cols);
85
- const context = [
86
- ...wrappedIndentedLines(state.listTitle ?? '', cols, type.heading),
87
- '',
88
- ...wrappedIndentedLines(state.listNotice, cols, type.hint),
89
- '',
90
- ];
88
+ const context = state.listNotice === undefined
89
+ ? notice
90
+ : [
91
+ ...notice,
92
+ ...wrappedIndentedLines(state.listTitle ?? '', cols, type.heading),
93
+ '',
94
+ ...wrappedIndentedLines(state.listNotice, cols, type.hint),
95
+ '',
96
+ ];
91
97
  return renderListFieldWithContext(context, state.listField, bodyRows, cols);
92
98
  }
93
99
  case 'detail': {
94
100
  const context = [
101
+ ...notice,
95
102
  ...wrappedIndentedLines(state.detailTitle ?? '', cols, type.heading),
96
103
  ...wrappedIndentedLines(state.detailMeta ?? '', cols, type.hint),
97
104
  '',
@@ -112,9 +119,20 @@ export function renderEvents(state, now, bodyRows = 100, cols) {
112
119
  : context;
113
120
  }
114
121
  case 'search':
115
- return state.searchField?.render(cols) ?? [];
116
- case 'error':
117
- return wrappedIndentedLines(state.errorMessage ?? trans.calendar.error, cols, type.hint);
122
+ return [...notice, ...(state.searchField?.render(cols) ?? [])];
123
+ case 'error': {
124
+ const context = [
125
+ ...wrappedIndentedLines(state.errorMessage ?? trans.calendar.error, cols, type.body),
126
+ ...wrappedIndentedLines(trans.calendar.errorHint, cols, type.hint),
127
+ '',
128
+ ];
129
+ if (state.errorField) {
130
+ return renderListFieldWithContext(context, state.errorField, bodyRows, cols);
131
+ }
132
+ return Number.isFinite(bodyRows)
133
+ ? context.slice(0, Math.max(0, Math.floor(bodyRows)))
134
+ : context;
135
+ }
118
136
  default:
119
137
  return [];
120
138
  }