@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.
- package/dist/app/app.js +36 -32
- package/dist/app/chrome.js +25 -30
- package/dist/app/fields/list-field.js +2 -2
- package/dist/app/frame.js +8 -4
- package/dist/app/help.js +2 -2
- package/dist/app/views/docs-render.js +29 -10
- package/dist/app/views/docs.js +153 -88
- package/dist/app/views/events-render.js +44 -25
- package/dist/app/views/events.js +50 -18
- package/dist/app/views/home.js +5 -7
- package/dist/app/views/schedule-render.js +70 -27
- package/dist/app/views/schedule.js +5 -2
- package/dist/app/views/settings-render.js +1 -0
- package/dist/app/views/settings.js +37 -12
- package/dist/cli.js +1 -1
- package/dist/core/components/menu.js +7 -4
- package/dist/core/logo.js +23 -5
- package/dist/core/text.js +6 -14
- package/dist/core/theme.js +11 -2
- package/dist/features/about.js +2 -2
- package/dist/features/calendar-heatmap.js +49 -59
- package/dist/features/calendar-query.js +1 -1
- package/dist/features/calendar-store.js +36 -4
- package/dist/features/calendar.js +39 -11
- package/dist/features/docs-client.js +16 -3
- package/dist/features/docs-markdown.js +16 -24
- package/dist/features/docs.js +64 -19
- package/dist/features/schedule-render.js +160 -139
- package/dist/features/status.js +5 -1
- package/dist/i18n/locales/en.json +30 -13
- package/dist/i18n/locales/zh.json +23 -6
- package/package.json +3 -3
package/dist/core/theme.js
CHANGED
|
@@ -60,11 +60,20 @@ export const glyph = {
|
|
|
60
60
|
barFilled: () => pickIcon('█', '#'),
|
|
61
61
|
barEmpty: () => pickIcon('░', '-'),
|
|
62
62
|
};
|
|
63
|
-
|
|
64
|
-
export const MAX_FRAME_COLS = 100;
|
|
63
|
+
export const MAX_FRAME_COLS = 120;
|
|
65
64
|
export const space = {
|
|
66
65
|
indent: ' ',
|
|
67
66
|
};
|
|
67
|
+
export function frameWidth(cols) {
|
|
68
|
+
return Math.min(cols, MAX_FRAME_COLS);
|
|
69
|
+
}
|
|
70
|
+
export function frameLeft(cols) {
|
|
71
|
+
return Math.floor((cols - frameWidth(cols)) / 2);
|
|
72
|
+
}
|
|
73
|
+
const RIGHT_MARGIN_MIN_COLS = 40;
|
|
74
|
+
export function bodyEdge(cols) {
|
|
75
|
+
return cols >= RIGHT_MARGIN_MIN_COLS ? cols - space.indent.length : cols;
|
|
76
|
+
}
|
|
68
77
|
export const type = {
|
|
69
78
|
heading: (s) => chalk.bold(s),
|
|
70
79
|
label: (s) => s,
|
package/dist/features/about.js
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import chalk from 'chalk';
|
|
2
2
|
import { APP_INFO, URLS } from '../config/data.js';
|
|
3
3
|
import { note } from '../core/components/note.js';
|
|
4
|
-
import { pickIcon } from '../core/icons.js';
|
|
5
4
|
import { padEndV } from '../core/text.js';
|
|
6
5
|
import { t } from '../i18n/index.js';
|
|
7
6
|
export function showAbout() {
|
|
@@ -17,7 +16,8 @@ export function showAbout() {
|
|
|
17
16
|
link(trans.about.website, URLS.homepage),
|
|
18
17
|
link(trans.about.email, URLS.email),
|
|
19
18
|
'',
|
|
20
|
-
row(trans.about.license,
|
|
19
|
+
row(trans.about.license, 'MIT'),
|
|
20
|
+
row(trans.about.author, 'm1ngsama'),
|
|
21
21
|
].join('\n');
|
|
22
22
|
note(content, trans.about.title);
|
|
23
23
|
}
|
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import chalk from 'chalk';
|
|
2
1
|
import { pickIcon } from '../core/icons.js';
|
|
3
|
-
import { space, type } from '../core/theme.js';
|
|
2
|
+
import { c, space, type } from '../core/theme.js';
|
|
4
3
|
import { t, getCurrentLanguage } from '../i18n/index.js';
|
|
5
4
|
import { visualWidth } from '../core/text.js';
|
|
6
5
|
function parseBucketDate(date) {
|
|
@@ -13,25 +12,39 @@ function parseBucketDate(date) {
|
|
|
13
12
|
function utcDayToMonIndex(utcDay) {
|
|
14
13
|
return (utcDay + 6) % 7;
|
|
15
14
|
}
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
if (count === 3)
|
|
24
|
-
return pickIcon('▓', '-');
|
|
25
|
-
return pickIcon('█', '=');
|
|
26
|
-
}
|
|
27
|
-
const HEATMAP_RAMP = ['#1b4332', '#2d6a4f', '#40916c', '#52b788'];
|
|
15
|
+
const LEVEL_GLYPHS = [
|
|
16
|
+
['·', ' '],
|
|
17
|
+
['░', '.'],
|
|
18
|
+
['▒', ':'],
|
|
19
|
+
['▓', '-'],
|
|
20
|
+
['█', '='],
|
|
21
|
+
];
|
|
28
22
|
const MAX_WEEK_COLUMNS = 53;
|
|
29
23
|
const GRID_PREFIX_WIDTH = 6;
|
|
30
|
-
function
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
const
|
|
34
|
-
|
|
24
|
+
function levelCell(count, useColor) {
|
|
25
|
+
const level = Math.max(0, Math.min(count, LEVEL_GLYPHS.length - 1));
|
|
26
|
+
const [unicode, ascii] = LEVEL_GLYPHS[level] ?? LEVEL_GLYPHS[0];
|
|
27
|
+
const cell = pickIcon(unicode, ascii);
|
|
28
|
+
if (!useColor)
|
|
29
|
+
return cell;
|
|
30
|
+
return level === 0 ? type.hint(cell) : c.success(cell);
|
|
31
|
+
}
|
|
32
|
+
function placeMonthLabels(anchors, width, format, strict) {
|
|
33
|
+
let line = '';
|
|
34
|
+
for (const [index, anchor] of anchors.entries()) {
|
|
35
|
+
const label = format(anchor.date);
|
|
36
|
+
const end = anchor.start + visualWidth(label);
|
|
37
|
+
const used = visualWidth(line);
|
|
38
|
+
const gap = index === 0 ? 2 : 1;
|
|
39
|
+
const limit = (anchors[index + 1]?.start ?? width + gap) - gap;
|
|
40
|
+
if (anchor.start >= used + (used > 0 ? 1 : 0) && end <= limit) {
|
|
41
|
+
line += ' '.repeat(anchor.start - used) + label;
|
|
42
|
+
}
|
|
43
|
+
else if (strict && index > 0) {
|
|
44
|
+
return undefined;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return line;
|
|
35
48
|
}
|
|
36
49
|
export function renderHeatmap(buckets, today, options) {
|
|
37
50
|
const useColor = options?.color === true;
|
|
@@ -78,30 +91,23 @@ export function renderHeatmap(buckets, today, options) {
|
|
|
78
91
|
timeZone: 'UTC',
|
|
79
92
|
});
|
|
80
93
|
const cellsWidth = numCols * cellWidth;
|
|
81
|
-
|
|
94
|
+
const anchors = [];
|
|
82
95
|
let prevMonth = -1;
|
|
83
|
-
for (
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
const cell = columns[col]?.[row];
|
|
87
|
-
if (cell !== null && cell !== undefined) {
|
|
88
|
-
labelDate = parseBucketDate(cell.date);
|
|
89
|
-
break;
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
if (labelDate === null)
|
|
96
|
+
for (const [col, column] of columns.entries()) {
|
|
97
|
+
const cell = column.find((candidate) => candidate !== null);
|
|
98
|
+
if (!cell)
|
|
93
99
|
continue;
|
|
94
|
-
const
|
|
95
|
-
if (
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
const used = visualWidth(monthLine);
|
|
100
|
-
if (start >= used + (used > 0 ? 1 : 0) && start + visualWidth(label) <= cellsWidth) {
|
|
101
|
-
monthLine += ' '.repeat(start - used) + label;
|
|
102
|
-
}
|
|
103
|
-
}
|
|
100
|
+
const date = parseBucketDate(cell.date);
|
|
101
|
+
if (date.getUTCMonth() === prevMonth)
|
|
102
|
+
continue;
|
|
103
|
+
prevMonth = date.getUTCMonth();
|
|
104
|
+
anchors.push({ start: col * cellWidth, date });
|
|
104
105
|
}
|
|
106
|
+
const monthNumber = (date) => String(date.getUTCMonth() + 1);
|
|
107
|
+
const monthLine = placeMonthLabels(anchors, cellsWidth, (date) => monthFmt.format(date), true) ??
|
|
108
|
+
placeMonthLabels(anchors, cellsWidth, monthNumber, true) ??
|
|
109
|
+
placeMonthLabels(anchors, cellsWidth, monthNumber, false) ??
|
|
110
|
+
'';
|
|
105
111
|
const monthLabelLine = space.indent + weekdayLabel + monthLine;
|
|
106
112
|
const weekdayNames = [
|
|
107
113
|
trans.timetable.weekdayMon.slice(0, 2),
|
|
@@ -122,28 +128,12 @@ export function renderHeatmap(buckets, today, options) {
|
|
|
122
128
|
const cell = col[row];
|
|
123
129
|
if (cell === null || cell === undefined)
|
|
124
130
|
return ' ';
|
|
125
|
-
|
|
126
|
-
return applyColor(glyph, cell.count, useColor);
|
|
131
|
+
return levelCell(cell.count, useColor);
|
|
127
132
|
});
|
|
128
133
|
lines.push(`${space.indent}${wdLabel} ${cells.join(cellWidth === 2 ? ' ' : '')}`);
|
|
129
134
|
}
|
|
130
|
-
const
|
|
131
|
-
pickIcon('·', ' '),
|
|
132
|
-
pickIcon('░', '.'),
|
|
133
|
-
pickIcon('▒', ':'),
|
|
134
|
-
pickIcon('▓', '-'),
|
|
135
|
-
pickIcon('█', '='),
|
|
136
|
-
];
|
|
137
|
-
const legendColored = useColor
|
|
138
|
-
? [
|
|
139
|
-
legendGlyphs[0] ?? '·',
|
|
140
|
-
applyColor(legendGlyphs[1] ?? '░', 1, true),
|
|
141
|
-
applyColor(legendGlyphs[2] ?? '▒', 2, true),
|
|
142
|
-
applyColor(legendGlyphs[3] ?? '▓', 3, true),
|
|
143
|
-
applyColor(legendGlyphs[4] ?? '█', 4, true),
|
|
144
|
-
]
|
|
145
|
-
: legendGlyphs;
|
|
135
|
+
const legend = LEVEL_GLYPHS.map((_, level) => levelCell(level, useColor)).join('');
|
|
146
136
|
lines.push('');
|
|
147
|
-
lines.push(`${space.indent}${type.hint(trans.calendar.heatmap.legendLess)} ${
|
|
137
|
+
lines.push(`${space.indent}${type.hint(trans.calendar.heatmap.legendLess)} ${legend} ${type.hint(trans.calendar.heatmap.legendMore)}`);
|
|
148
138
|
return lines.join('\n');
|
|
149
139
|
}
|
|
@@ -22,7 +22,7 @@ export function eventEnd(event) {
|
|
|
22
22
|
? new Date(event.start.getFullYear(), event.start.getMonth(), event.start.getDate() + 1)
|
|
23
23
|
: event.start));
|
|
24
24
|
}
|
|
25
|
-
function hasEnded(event, now) {
|
|
25
|
+
export function hasEnded(event, now) {
|
|
26
26
|
return event.start < now && eventEnd(event) <= now;
|
|
27
27
|
}
|
|
28
28
|
export function currentEvents(calendar, now) {
|
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
|
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,12 +1,12 @@
|
|
|
1
|
-
import {
|
|
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';
|
|
5
5
|
import { padEndV, sanitizeTerminalLine, sanitizeTerminalText, truncate, visualWidth, wrapAnsiWithIndent, wrapAnsiToVisualWidth, } from '../core/text.js';
|
|
6
6
|
import { t } from '../i18n/index.js';
|
|
7
7
|
import { localDayDifference } from '../core/calendar-day.js';
|
|
8
|
-
import { countdownParts, isCountdownUrgent, buildExportFilename, formatDuration, pastYearRange, } from './calendar-query.js';
|
|
9
|
-
import { loadFeedCache, saveFeedCache } from './calendar-store.js';
|
|
8
|
+
import { countdownParts, eventEnd, isCountdownUrgent, buildExportFilename, formatDuration, pastYearRange, } from './calendar-query.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
|
|
33
|
-
if (
|
|
36
|
+
const cache = loadFeedCache();
|
|
37
|
+
if (cache === null)
|
|
34
38
|
return undefined;
|
|
35
39
|
try {
|
|
36
|
-
|
|
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
|
-
|
|
48
|
+
peekCalendar();
|
|
49
|
+
const result = await fetchFeedConditional(undefined, {
|
|
46
50
|
timeoutMs: 15000,
|
|
47
51
|
...(signal === undefined ? {} : { signal }),
|
|
52
|
+
validators: memo?.validators ?? {},
|
|
48
53
|
});
|
|
49
|
-
|
|
50
|
-
|
|
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) {
|
|
@@ -76,6 +88,22 @@ export function toDisplayEvent(e) {
|
|
|
76
88
|
uid: e.uid,
|
|
77
89
|
};
|
|
78
90
|
}
|
|
91
|
+
export function eventTimeRange(e) {
|
|
92
|
+
const dash = pickIcon('–', '-');
|
|
93
|
+
const startDate = formatDate(e.start);
|
|
94
|
+
if (e.isAllDay) {
|
|
95
|
+
const lastDay = new Date(eventEnd(e).getTime() - 1);
|
|
96
|
+
const endDate = formatDate(lastDay);
|
|
97
|
+
return endDate === startDate ? startDate : `${startDate} ${dash} ${endDate}`;
|
|
98
|
+
}
|
|
99
|
+
const start = `${startDate} ${formatTime(e.start)}`;
|
|
100
|
+
if (!e.end || e.end <= e.start)
|
|
101
|
+
return start;
|
|
102
|
+
const endDate = formatDate(e.end);
|
|
103
|
+
return endDate === startDate
|
|
104
|
+
? `${start}${dash}${formatTime(e.end)}`
|
|
105
|
+
: `${start} ${dash} ${endDate} ${formatTime(e.end)}`;
|
|
106
|
+
}
|
|
79
107
|
export async function loadCalendarOrCache(signal) {
|
|
80
108
|
try {
|
|
81
109
|
return { calendar: await loadCalendarOrThrow(signal), stale: false };
|
|
@@ -210,7 +238,7 @@ export function renderCountdownBanner(event, now, cols = Number.POSITIVE_INFINIT
|
|
|
210
238
|
const whenStyled = isCountdownUrgent(p) ? c.warn(when) : type.hint(when);
|
|
211
239
|
const dot = pickIcon('·', '-');
|
|
212
240
|
const content = `${type.label(trans.calendar.next)} ${dot} ${type.body(event.title)} ${dot} ${whenStyled}`;
|
|
213
|
-
return hangingLines(type.active(glyph.
|
|
241
|
+
return hangingLines(type.active(glyph.dot()), content, cols).join('\n');
|
|
214
242
|
}
|
|
215
243
|
export function exportEventIcs(event, dir = process.cwd()) {
|
|
216
244
|
const base = buildExportFilename(event);
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
2
|
-
import { createDocsClient } from '@nbtca/docs';
|
|
2
|
+
import { createDocsClient, parseDoc } from '@nbtca/docs';
|
|
3
|
+
import { URLS } from '../config/data.js';
|
|
3
4
|
import { createDocsStore } from './docs-store.js';
|
|
4
5
|
const contextKey = Symbol.for('@nbtca/prompt/docs-fetch-context/v2');
|
|
5
6
|
const globalWithContext = globalThis;
|
|
@@ -160,7 +161,8 @@ function beginDocsFetch() {
|
|
|
160
161
|
};
|
|
161
162
|
}
|
|
162
163
|
const store = createDocsStore();
|
|
163
|
-
const
|
|
164
|
+
const options = { store, mirror: `${URLS.docs}/docs-api` };
|
|
165
|
+
const defaultClient = createDocsClient(options);
|
|
164
166
|
const clientsBySignal = new WeakMap();
|
|
165
167
|
const clients = new Set([defaultClient]);
|
|
166
168
|
function clientFor(signal) {
|
|
@@ -169,7 +171,7 @@ function clientFor(signal) {
|
|
|
169
171
|
const existing = clientsBySignal.get(signal);
|
|
170
172
|
if (existing)
|
|
171
173
|
return existing;
|
|
172
|
-
const client = createDocsClient(
|
|
174
|
+
const client = createDocsClient(options);
|
|
173
175
|
clientsBySignal.set(signal, client);
|
|
174
176
|
clients.add(client);
|
|
175
177
|
signal.addEventListener('abort', () => {
|
|
@@ -182,6 +184,17 @@ function clientFor(signal) {
|
|
|
182
184
|
export function peekDocs() {
|
|
183
185
|
return defaultClient.peekAll();
|
|
184
186
|
}
|
|
187
|
+
export function peekDocument(item) {
|
|
188
|
+
if (!item.sha)
|
|
189
|
+
return undefined;
|
|
190
|
+
try {
|
|
191
|
+
const content = store.read(`blob-${item.sha}`);
|
|
192
|
+
return content === undefined ? undefined : parseDoc(item.path, content);
|
|
193
|
+
}
|
|
194
|
+
catch {
|
|
195
|
+
return undefined;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
185
198
|
export function clearDocsClients() {
|
|
186
199
|
for (const client of clients)
|
|
187
200
|
client.clear();
|
|
@@ -26,38 +26,30 @@ const CJK_SOFT_BREAK = new RegExp(`(?<=${CJK})[ \\t]*\\n[ \\t]*(?=${CJK})`, 'gu'
|
|
|
26
26
|
function joinSoftBreaks(text) {
|
|
27
27
|
return text.replace(CJK_SOFT_BREAK, '').replace(/[ \t]*\n[ \t]*/g, ' ');
|
|
28
28
|
}
|
|
29
|
-
function renderInline(tokens
|
|
30
|
-
return (tokens ?? []).map((token) => renderInlineToken(token
|
|
29
|
+
function renderInline(tokens) {
|
|
30
|
+
return (tokens ?? []).map((token) => renderInlineToken(token)).join('');
|
|
31
31
|
}
|
|
32
|
-
function renderLink(token
|
|
33
|
-
|
|
34
|
-
const bare = (href) => href.replace(/^(?:https?:\/\/|mailto:)/, '').replace(/\/$/, '');
|
|
35
|
-
const selfLabelled = bare(stripAnsi(text)) === bare(token.href);
|
|
36
|
-
if (isInternalHref(token.href) || token.href.startsWith('#') || selfLabelled) {
|
|
37
|
-
return chalk.underline(c.accent(text));
|
|
38
|
-
}
|
|
39
|
-
return hrefs ? `${c.accent(text)} ${c.url(`(${token.href})`)}` : c.accent(text);
|
|
32
|
+
function renderLink(token) {
|
|
33
|
+
return chalk.underline(c.accent(renderInline(token.tokens)));
|
|
40
34
|
}
|
|
41
|
-
function renderInlineToken(token
|
|
35
|
+
function renderInlineToken(token) {
|
|
42
36
|
switch (token.type) {
|
|
43
37
|
case 'text':
|
|
44
|
-
return token.tokens
|
|
45
|
-
? renderInline(token.tokens, hrefs)
|
|
46
|
-
: joinSoftBreaks(decodeEntities(token.text));
|
|
38
|
+
return token.tokens ? renderInline(token.tokens) : joinSoftBreaks(decodeEntities(token.text));
|
|
47
39
|
case 'escape':
|
|
48
40
|
return token.text;
|
|
49
41
|
case 'strong':
|
|
50
|
-
return chalk.bold(renderInline(token.tokens
|
|
42
|
+
return chalk.bold(renderInline(token.tokens));
|
|
51
43
|
case 'em':
|
|
52
|
-
return chalk.italic(renderInline(token.tokens
|
|
44
|
+
return chalk.italic(renderInline(token.tokens));
|
|
53
45
|
case 'del':
|
|
54
|
-
return chalk.strikethrough(c.muted(renderInline(token.tokens
|
|
46
|
+
return chalk.strikethrough(c.muted(renderInline(token.tokens)));
|
|
55
47
|
case 'codespan':
|
|
56
48
|
return c.code(token.text);
|
|
57
49
|
case 'br':
|
|
58
50
|
return '\n';
|
|
59
51
|
case 'link':
|
|
60
|
-
return renderLink(token
|
|
52
|
+
return renderLink(token);
|
|
61
53
|
case 'image':
|
|
62
54
|
return `${pickIcon('🖼️', '[image]')} ${token.text || 'image'}`;
|
|
63
55
|
case 'html':
|
|
@@ -94,7 +86,7 @@ function styleHeading(text, depth) {
|
|
|
94
86
|
return chalk.bold(text);
|
|
95
87
|
}
|
|
96
88
|
function renderHeading(token, width) {
|
|
97
|
-
const lines = wrap(styleHeading(renderInline(token.tokens
|
|
89
|
+
const lines = wrap(styleHeading(renderInline(token.tokens), token.depth), width);
|
|
98
90
|
if (token.depth !== 2)
|
|
99
91
|
return lines;
|
|
100
92
|
const underline = Math.min(width, Math.max(...lines.map(visualWidth)));
|
|
@@ -173,8 +165,8 @@ function renderRecords(header, rows, width) {
|
|
|
173
165
|
return lines;
|
|
174
166
|
}
|
|
175
167
|
function renderTable(token, width) {
|
|
176
|
-
const header = token.header.map((cell) => renderInline(cell.tokens
|
|
177
|
-
const rows = token.rows.map((row) => row.map((cell) => renderInline(cell.tokens
|
|
168
|
+
const header = token.header.map((cell) => renderInline(cell.tokens));
|
|
169
|
+
const rows = token.rows.map((row) => row.map((cell) => renderInline(cell.tokens)));
|
|
178
170
|
const natural = header.map((label, column) => Math.max(cellWidth(label), ...rows.map((row) => cellWidth(row[column] ?? ''))));
|
|
179
171
|
const available = width - (3 * header.length + 1);
|
|
180
172
|
const floor = natural.map((columnWidth) => Math.min(columnWidth, MIN_COLUMN));
|
|
@@ -216,9 +208,9 @@ function renderBlock(token, width, depth) {
|
|
|
216
208
|
case 'heading':
|
|
217
209
|
return renderHeading(token, width);
|
|
218
210
|
case 'paragraph':
|
|
219
|
-
return wrap(renderInline(token.tokens
|
|
211
|
+
return wrap(renderInline(token.tokens), width);
|
|
220
212
|
case 'text':
|
|
221
|
-
return wrap(renderInlineToken(token
|
|
213
|
+
return wrap(renderInlineToken(token), width);
|
|
222
214
|
case 'code':
|
|
223
215
|
return renderCode(token, width);
|
|
224
216
|
case 'blockquote':
|
|
@@ -245,7 +237,7 @@ function renderBlock(token, width, depth) {
|
|
|
245
237
|
case 'image':
|
|
246
238
|
case 'link':
|
|
247
239
|
case 'strong':
|
|
248
|
-
return wrap(renderInlineToken(token
|
|
240
|
+
return wrap(renderInlineToken(token), width);
|
|
249
241
|
}
|
|
250
242
|
}
|
|
251
243
|
function renderBlocks(tokens, width, depth, tight) {
|
package/dist/features/docs.js
CHANGED
|
@@ -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();
|
|
@@ -59,7 +59,7 @@ const RENDER_CACHE_MAX = 50;
|
|
|
59
59
|
const renderCache = new Map();
|
|
60
60
|
const METADATA_CACHE_TTL_MS = 10 * 60 * 1000;
|
|
61
61
|
const METADATA_CACHE_MAX = 200;
|
|
62
|
-
const METADATA_CONCURRENCY =
|
|
62
|
+
const METADATA_CONCURRENCY = 6;
|
|
63
63
|
const metadataCache = new Map();
|
|
64
64
|
let cacheGeneration = 0;
|
|
65
65
|
function getFreshRender(key) {
|
|
@@ -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)
|
|
@@ -470,13 +481,16 @@ function hasMarkdownTable(content) {
|
|
|
470
481
|
function hasMermaidBlock(content) {
|
|
471
482
|
return /^```mermaid\b/m.test(content);
|
|
472
483
|
}
|
|
473
|
-
function
|
|
484
|
+
function isExternalHref(href) {
|
|
485
|
+
return /^https?:\/\//i.test(href);
|
|
486
|
+
}
|
|
487
|
+
function extractLinks(markdown) {
|
|
474
488
|
const links = [];
|
|
475
|
-
const re = /\[([^\]]+)\]\(([^)]+)
|
|
489
|
+
const re = /\[([^\]]+)\]\(([^)\s]+)[^)]*\)/g;
|
|
476
490
|
let m;
|
|
477
491
|
while ((m = re.exec(markdown))) {
|
|
478
492
|
const href = m[2] ?? '';
|
|
479
|
-
if (isInternalHref(href))
|
|
493
|
+
if (isInternalHref(href) || isExternalHref(href))
|
|
480
494
|
links.push({ text: m[1] ?? '', href });
|
|
481
495
|
}
|
|
482
496
|
return links;
|
|
@@ -510,12 +524,15 @@ export async function loadDocForReader(filePath, signal) {
|
|
|
510
524
|
const { renderedDoc } = await loadRenderedDoc(filePath, signal);
|
|
511
525
|
const seen = new Set();
|
|
512
526
|
const links = [];
|
|
513
|
-
for (const raw of
|
|
514
|
-
const
|
|
515
|
-
|
|
527
|
+
for (const raw of extractLinks(renderedDoc.cleaned)) {
|
|
528
|
+
const external = isExternalHref(raw.href);
|
|
529
|
+
const href = external
|
|
530
|
+
? sanitizeTerminalLine(raw.href)
|
|
531
|
+
: resolveInternalHref(raw.href, filePath);
|
|
532
|
+
if (seen.has(href))
|
|
516
533
|
continue;
|
|
517
|
-
seen.add(
|
|
518
|
-
links.push({ text: sanitizeTerminalLine(raw.text), href:
|
|
534
|
+
seen.add(href);
|
|
535
|
+
links.push({ text: sanitizeTerminalLine(raw.text), href, ...(external ? { external } : {}) });
|
|
519
536
|
}
|
|
520
537
|
return {
|
|
521
538
|
path: filePath,
|
|
@@ -551,11 +568,14 @@ function listedDoc(item, metadata) {
|
|
|
551
568
|
return {
|
|
552
569
|
...item,
|
|
553
570
|
name: sanitizeTerminalLine(item.name),
|
|
554
|
-
title: displayDocTitle(item.name, metadata
|
|
571
|
+
title: metadata ? displayDocTitle(item.name, metadata.title) : '',
|
|
555
572
|
summary: sanitizeTerminalLine(metadata?.summary ?? ''),
|
|
556
573
|
};
|
|
557
574
|
}
|
|
558
|
-
export
|
|
575
|
+
export function withFileNameTitle(doc) {
|
|
576
|
+
return doc.title ? doc : { ...doc, title: displayDocTitle(doc.name) };
|
|
577
|
+
}
|
|
578
|
+
export async function fetchDocMetadata(items, signal, onDoc) {
|
|
559
579
|
const results = items.map((item) => listedDoc(item));
|
|
560
580
|
let nextIndex = 0;
|
|
561
581
|
async function worker() {
|
|
@@ -578,32 +598,57 @@ export async function fetchDocMetadata(items, signal) {
|
|
|
578
598
|
catch (error) {
|
|
579
599
|
if (signal?.aborted)
|
|
580
600
|
throw error;
|
|
581
|
-
results[index] = listedDoc(item);
|
|
601
|
+
results[index] = withFileNameTitle(listedDoc(item));
|
|
582
602
|
}
|
|
603
|
+
onDoc?.(index, results[index]);
|
|
583
604
|
}
|
|
584
605
|
}
|
|
585
606
|
const workerCount = Math.min(METADATA_CONCURRENCY, items.length);
|
|
586
607
|
await Promise.all(Array.from({ length: workerCount }, worker));
|
|
587
608
|
return results;
|
|
588
609
|
}
|
|
589
|
-
export
|
|
590
|
-
|
|
610
|
+
export function peekListedDocs(items) {
|
|
611
|
+
let complete = true;
|
|
612
|
+
const docs = items.map((item) => {
|
|
613
|
+
const metadata = peekDocMetadata(item);
|
|
614
|
+
if (!metadata)
|
|
615
|
+
complete = false;
|
|
616
|
+
return listedDoc(item, metadata);
|
|
617
|
+
});
|
|
618
|
+
return { docs, complete };
|
|
619
|
+
}
|
|
620
|
+
export async function fetchSectionMetadata(section, signal, onDoc) {
|
|
621
|
+
const files = await fetchDocMetadata(section.files, signal, onDoc);
|
|
591
622
|
return { ...section, count: files.length, files };
|
|
592
623
|
}
|
|
624
|
+
function withoutLeadingTitle(excerpt, title) {
|
|
625
|
+
const text = excerpt.trim();
|
|
626
|
+
return title && text.startsWith(title) ? text.slice(title.length).trimStart() : text;
|
|
627
|
+
}
|
|
593
628
|
function searchDoc(result) {
|
|
629
|
+
const title = displayDocTitle(result.name, result.title);
|
|
594
630
|
return {
|
|
595
631
|
name: sanitizeTerminalLine(result.name),
|
|
596
632
|
path: result.path,
|
|
597
633
|
type: 'file',
|
|
598
|
-
title
|
|
634
|
+
title,
|
|
599
635
|
summary: sanitizeTerminalLine(result.summary),
|
|
600
|
-
excerpt: sanitizeTerminalLine(result.excerpt),
|
|
636
|
+
excerpt: withoutLeadingTitle(sanitizeTerminalLine(result.excerpt), title),
|
|
601
637
|
route: result.route,
|
|
602
638
|
score: result.score,
|
|
603
639
|
section: result.section,
|
|
604
640
|
};
|
|
605
641
|
}
|
|
606
|
-
export async function searchDocuments(query, signal) {
|
|
642
|
+
export async function searchDocuments(query, signal, onProgress) {
|
|
643
|
+
if (onProgress) {
|
|
644
|
+
const items = await fetchAllDocs(signal);
|
|
645
|
+
let done = 0;
|
|
646
|
+
onProgress(done, items.length);
|
|
647
|
+
await fetchDocMetadata(items, signal, () => {
|
|
648
|
+
done += 1;
|
|
649
|
+
onProgress(done, items.length);
|
|
650
|
+
});
|
|
651
|
+
}
|
|
607
652
|
return (await runDocsClientOperation(signal, (client) => client.search(query, { limit: 20 }))).map(searchDoc);
|
|
608
653
|
}
|
|
609
654
|
export function buildSections(all) {
|
|
@@ -670,7 +715,7 @@ async function loadSections() {
|
|
|
670
715
|
return null;
|
|
671
716
|
}
|
|
672
717
|
s.stop();
|
|
673
|
-
warning(trans.
|
|
718
|
+
warning(trans.common.offline);
|
|
674
719
|
return cached;
|
|
675
720
|
}
|
|
676
721
|
}
|