@jacebenson/jsn 5.5.7-dev.211.1 → 5.5.7-dev.213.1

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,195 +1,163 @@
1
1
  /**
2
- * Paginated search prompt built with @inquirer/core hooks.
2
+ * Paginated, searchable record picker built on src/prompt-engine.js.
3
+ *
4
+ * Contract (unchanged from the Inquirer version):
5
+ * paginatedSearch({ message, pageSize, totalCount, source }, context?)
6
+ * source(term, offset, { signal }) -> [{ name, value }]
7
+ * Enter resolves the active choice object; Escape resolves undefined.
8
+ * Down at the last loaded row loads more while loaded < totalCount.
3
9
  */
4
10
 
5
-
6
- export const paginatedSearch = async (...args) => {
7
- const { createPrompt, useState, useKeypress, usePagination, useEffect, useRef, isEnterKey, isUpKey, isDownKey } = await import('@inquirer/core');
8
- return createPrompt((config, done) => {
9
- const { message, pageSize = 10, totalCount = 0, source } = config;
10
-
11
- const [status, setStatus] = useState('loading');
12
- const [searchTerm, setSearchTerm] = useState('');
13
- const [choices, setChoices] = useState([]);
14
- const [active, setActive] = useState(0);
15
- const [loaded, setLoaded] = useState(0);
16
- const [searchMode, setSearchMode] = useState(false);
17
-
18
- // Refs for mutable state (no functional updaters — @inquirer/core doesn't support them)
19
- const choicesRef = useRef([]);
20
- const loadedRef = useRef(0);
21
- const activeRef = useRef(0);
22
- const totalCountRef = useRef(totalCount);
23
- const searchModeRef = useRef(false);
24
-
25
- const fullMessage = totalCount > 0
26
- ? `${message} (${loaded} of ${totalCount} loaded)`
27
- : message;
28
-
29
- // Load initial page
30
- useEffect(() => {
31
- const controller = new AbortController();
32
- setStatus('loading');
33
-
34
- const load = async () => {
35
- try {
36
- const items = await source(searchTerm || undefined, 0, { signal: controller.signal });
37
- if (!controller.signal.aborted) {
38
- choicesRef.current = items;
39
- loadedRef.current = items.length;
40
- activeRef.current = 0;
41
- setChoices(items);
42
- setLoaded(items.length);
43
- setActive(0);
44
- setStatus('done');
45
- }
46
- } catch {
47
- if (!controller.signal.aborted) {
48
- setStatus('done');
49
- setChoices([]);
50
- setLoaded(0);
51
- }
52
- }
53
- };
54
- load();
55
- return () => controller.abort();
56
- }, []);
57
-
58
- // Load more when scrolling past end
59
- async function loadMore() {
60
- if (loadedRef.current >= totalCountRef.current || searchModeRef.current) return;
61
- setStatus('loading');
62
- try {
63
- const newItems = await source('', loadedRef.current, { signal: new AbortController().signal });
64
- const updated = choicesRef.current.concat(newItems);
65
- choicesRef.current = updated;
66
- loadedRef.current = updated.length;
67
- setChoices([...updated]);
68
- setLoaded(updated.length);
69
- } catch (err) {
70
- console.error('Scroll load error:', err.message || err);
71
- loadedRef.current = totalCountRef.current;
72
- setLoaded(totalCountRef.current);
11
+ import { runPrompt, normalizeChoices, truncate, escapeResult } from './prompt-engine.js';
12
+
13
+ export const paginatedSearch = async (config = {}, context = {}) => {
14
+ const { message, pageSize = 10, totalCount = 0, source } = config;
15
+ let request;
16
+ const state = {
17
+ status: 'loading',
18
+ term: '',
19
+ choices: [],
20
+ active: 0,
21
+ loaded: 0,
22
+ searchMode: false,
23
+ token: 0,
24
+ error: '',
25
+ };
26
+
27
+ // Every request gets a token. A response may only be applied while its
28
+ // token is still current, so a stale (slower) search can never replace
29
+ // newer results or be selected by a later Enter.
30
+ const isCurrent = token => token === state.token && state.status !== 'cancelled';
31
+
32
+ async function load(term, offset, { append = false } = {}) {
33
+ request?.abort();
34
+ request = new AbortController();
35
+ const signal = context.signal ? AbortSignal.any([request.signal, context.signal]) : request.signal;
36
+ const token = ++state.token;
37
+ state.status = 'loading';
38
+ state.error = '';
39
+ try {
40
+ const items = normalizeChoices(await source(term || undefined, offset, { signal }) || []);
41
+ if (!isCurrent(token)) return;
42
+ state.choices = append ? state.choices.concat(items) : items;
43
+ state.loaded = state.choices.length;
44
+ state.active = Math.min(state.active, Math.max(0, state.choices.length - 1));
45
+ state.status = 'done';
46
+ } catch (error) {
47
+ if (!isCurrent(token)) return;
48
+ state.status = 'done';
49
+ state.error = error?.message || String(error);
50
+ if (!append) {
51
+ state.choices = [];
52
+ state.loaded = 0;
73
53
  }
74
- setStatus('done');
54
+ // A failed load-more keeps the rows already on screen.
75
55
  }
76
-
77
- // Search when term changes
78
- useEffect(() => {
79
- if (!searchTerm) {
80
- setSearchMode(false);
81
- searchModeRef.current = false;
82
- const controller = new AbortController();
83
- setStatus('loading');
84
- source('', 0, { signal: controller.signal }).then(items => {
85
- if (!controller.signal.aborted) {
86
- choicesRef.current = items;
87
- loadedRef.current = Math.min(items.length, totalCount || Infinity);
88
- activeRef.current = 0;
89
- setChoices(items);
90
- setLoaded(items.length);
91
- setActive(0);
92
- setStatus('done');
93
- }
94
- }).catch(() => {
95
- if (!controller.signal.aborted) setStatus('done');
96
- });
97
- return () => controller.abort();
98
- }
99
-
100
- const controller = new AbortController();
101
- setStatus('loading');
102
- setSearchMode(true);
103
- searchModeRef.current = true;
104
-
105
- source(searchTerm, undefined, { signal: controller.signal }).then(items => {
106
- if (!controller.signal.aborted) {
107
- choicesRef.current = items;
108
- loadedRef.current = items.length;
109
- activeRef.current = 0;
110
- setChoices(items);
111
- setLoaded(items.length);
112
- setActive(0);
113
- setStatus('done');
114
- }
115
- }).catch(() => {
116
- if (!controller.signal.aborted) {
117
- setStatus('done');
118
- setChoices([]);
119
- }
56
+ }
57
+
58
+ let api;
59
+ const prompt = runPrompt({ ...config, message }, context, {
60
+ escapeValue: escapeResult(undefined),
61
+ init() {
62
+ // Kick off the first page. Enter is ignored while status is 'loading',
63
+ // so nothing is selectable until this resolves.
64
+ state.pending = load('', 0);
65
+ return state;
66
+ },
67
+ onReady(handle) {
68
+ api = handle;
69
+ state.pending.then(() => {
70
+ if (state.status !== 'cancelled') api.redraw();
120
71
  });
121
-
122
- return () => controller.abort();
123
- }, [searchTerm]);
124
-
125
- // Key handling
126
- useKeypress((key, rl) => {
127
- if (status === 'loading') return;
128
-
129
- if (isEnterKey(key)) {
130
- if (choicesRef.current.length > 0 && activeRef.current >= 0 && activeRef.current < choicesRef.current.length) {
131
- done(choicesRef.current[activeRef.current]);
132
- }
133
- return;
134
- }
135
-
136
- if (key.name === 'escape') {
137
- done(undefined);
138
- return;
72
+ },
73
+ key(_state, key, handle) {
74
+ api = handle;
75
+ if (key.name === 'return' || key.name === 'enter') {
76
+ // No selecting a row while a request is in flight: the list on
77
+ // screen may be about to change.
78
+ if (state.status === 'loading' || !state.choices.length) return;
79
+ const choice = state.choices[state.active];
80
+ if (!choice) return;
81
+ return { done: choice };
139
82
  }
140
-
141
- if (isUpKey(key)) {
142
- if (activeRef.current > 0) {
143
- activeRef.current--;
144
- setActive(activeRef.current);
145
- }
83
+ if (key.name === 'up') {
84
+ if (state.active > 0) state.active -= 1;
85
+ api?.redraw();
146
86
  return;
147
87
  }
148
-
149
- if (isDownKey(key)) {
150
- if (activeRef.current < choicesRef.current.length - 1) {
151
- activeRef.current++;
152
- setActive(activeRef.current);
153
- } else if (!searchModeRef.current && loadedRef.current < totalCountRef.current) {
154
- loadMore().then(() => {
155
- activeRef.current++;
156
- setActive(activeRef.current);
88
+ if (key.name === 'down') {
89
+ if (state.status === 'loading') return;
90
+ if (state.active < state.choices.length - 1) {
91
+ state.active += 1;
92
+ api?.redraw();
93
+ } else if (!state.searchMode && state.loaded < totalCount) {
94
+ const before = state.loaded;
95
+ const pending = load('', state.loaded, { append: true });
96
+ const token = state.token;
97
+ void pending.then(() => {
98
+ if (!isCurrent(token)) return;
99
+ if (state.status === 'done' && state.loaded > before) state.active = before;
100
+ api?.redraw();
157
101
  });
102
+ api?.redraw();
158
103
  }
159
104
  return;
160
105
  }
161
-
162
- // Use readline's built-in line buffer for text input
163
- const newTerm = rl.line;
164
- if (newTerm !== searchTerm) {
165
- setSearchTerm(newTerm);
106
+ const previous = state.term;
107
+ if (key.name === 'backspace') state.term = state.term.slice(0, -1);
108
+ else if (key.name === 'space') state.term += ' ';
109
+ else if (key.text) state.term += key.text;
110
+ else return;
111
+ if (state.term === previous) return;
112
+
113
+ if (!state.term) {
114
+ state.searchMode = false;
115
+ state.active = 0;
116
+ void load('', 0).then(() => api?.redraw());
117
+ api?.redraw();
118
+ return;
166
119
  }
167
- });
168
-
169
- // Paginated rendering
170
- const page = usePagination({
171
- items: Array.isArray(choices) ? choices : [],
172
- active,
173
- pageSize,
174
- renderItem: ({ item, isActive }) => {
175
- const prefix = isActive ? '\x1b[7m' : ' ';
176
- const suffix = isActive ? '\x1b[0m' : '';
177
- const name = item.name || String(item.value || item);
178
- const display = name.length > 70 ? name.slice(0, 67) + '...' : name;
179
- return ` ${prefix}${display}${suffix}`;
180
- },
181
- loop: false,
182
- });
183
-
184
- const helpText = loaded < totalCount && !searchMode
185
- ? '(scroll to load more, type to search, Esc to cancel)'
186
- : '(type to search, Esc to cancel)';
187
-
188
- return [
189
- `${fullMessage} Search: ${searchTerm}${status === 'loading' ? ' ...' : ''}`,
190
- `${page}\n\n${helpText}`,
191
- ];
192
- })(...args);
120
+ state.searchMode = true;
121
+ state.active = 0;
122
+ void load(state.term, undefined).then(() => api?.redraw());
123
+ api?.redraw();
124
+ },
125
+ render() {
126
+ const pages = Math.max(1, Math.ceil(state.choices.length / pageSize));
127
+ const current = Math.min(pages - 1, Math.floor(state.active / pageSize));
128
+ const start = current * pageSize;
129
+ const visible = state.choices.slice(start, start + pageSize);
130
+ const header = totalCount > 0 && !state.searchMode
131
+ ? `${message} (${state.loaded} of ${totalCount} loaded)`
132
+ : message;
133
+ const lines = [`${header} Search: ${state.term}${state.status === 'loading' ? ' ...' : ''}`];
134
+ if (state.error) lines.push(` ${state.error}`);
135
+ else if (!state.choices.length) lines.push(state.status === 'loading' ? ' Loading...' : ' No matches');
136
+ visible.forEach((choice, index) => {
137
+ const absolute = start + index;
138
+ lines.push(`${absolute === state.active ? '>' : ' '} ${truncate(choice.name)}`);
139
+ });
140
+ const help = state.loaded < totalCount && !state.searchMode
141
+ ? '(scroll to load more, type to search, Esc to cancel)'
142
+ : '(type to search, Esc to cancel)';
143
+ lines.push('', help);
144
+ return lines;
145
+ },
146
+ });
147
+
148
+ return prompt.then(value => {
149
+ // Mark the prompt so an in-flight source response cannot redraw or
150
+ // apply after the picker closed.
151
+ state.status = 'cancelled';
152
+ state.token += 1;
153
+ request?.abort();
154
+ return value;
155
+ }, error => {
156
+ state.status = 'cancelled';
157
+ state.token += 1;
158
+ request?.abort();
159
+ throw error;
160
+ }).then(value => value);
193
161
  };
194
162
 
195
163
  export default paginatedSearch;
@@ -0,0 +1,169 @@
1
+ /**
2
+ * A small terminal prompt engine built on node:readline keypress events.
3
+ *
4
+ * This is deliberately not a general prompt library: it exists so JSN's
5
+ * observed prompt surface (input, password, confirm, select, search,
6
+ * checkbox, editor, paginated pickers) runs on Node built-ins with no
7
+ * runtime dependency, while keeping the existing caller contract
8
+ * `prompt(config, { input, output, signal })`.
9
+ *
10
+ * Every prompt restores raw mode and removes its listener in `finally`,
11
+ * on success, Escape, Ctrl+C and thrown errors alike.
12
+ */
13
+
14
+ import readline from 'node:readline';
15
+
16
+ export class PromptCancelled extends Error {
17
+ constructor() {
18
+ super('Cancelled.');
19
+ this.name = 'PromptCancelled';
20
+ }
21
+ }
22
+
23
+ /** Choices may be strings or { name, value, disabled }. */
24
+ export function normalizeChoices(choices = []) {
25
+ return choices.map(choice => {
26
+ if (choice && typeof choice === 'object') {
27
+ return {
28
+ name: String(choice.name ?? choice.value ?? ''),
29
+ value: 'value' in choice ? choice.value : choice.name,
30
+ disabled: Boolean(choice.disabled),
31
+ checked: Boolean(choice.checked),
32
+ };
33
+ }
34
+ return { name: String(choice), value: choice, disabled: false };
35
+ });
36
+ }
37
+
38
+ export function truncate(text, width = 70) {
39
+ const value = String(text ?? '');
40
+ return value.length > width ? `${value.slice(0, width - 3)}...` : value;
41
+ }
42
+
43
+ /**
44
+ * Run one interactive prompt.
45
+ *
46
+ * @param {object} config prompt config ({ message, ... })
47
+ * @param {object} context { input, output, signal }
48
+ * @param {object} spec
49
+ * init(config, context) -> state
50
+ * key(state, key, api) -> directive | undefined | Promise<...>
51
+ * directive: { done: value } finishes, { cancel: true } throws
52
+ * PromptCancelled, { escape: true } resolves undefined.
53
+ * render(config, state) -> string | string[]
54
+ * final(config, value, state) -> string | null — the settled answer line
55
+ * (Inquirer prints `✔ <message> <answer>`). Only written on a TTY after
56
+ * the live frame is erased, so one prompt yields exactly one final line
57
+ * and piped output keeps its existing byte contract.
58
+ * escapeValue — when the caller treats Escape as "leave this screen",
59
+ * pass a sentinel produced by `escapeResult(value)`.
60
+ */
61
+ export async function runPrompt(config, context, spec) {
62
+ const input = context.input || process.stdin;
63
+ const output = context.output || process.stdout;
64
+ const canRaw = typeof input.setRawMode === 'function';
65
+ const previousRaw = canRaw ? Boolean(input.isRaw) : false;
66
+
67
+ let state;
68
+ let height = 0;
69
+ let settled = false;
70
+ let resolveDone;
71
+ let rejectDone;
72
+
73
+ const done = new Promise((resolve, reject) => { resolveDone = resolve; rejectDone = reject; });
74
+
75
+ const draw = () => {
76
+ if (settled) return;
77
+ const rendered = spec.render(state);
78
+ const text = Array.isArray(rendered) ? rendered.join('\n') : String(rendered ?? '');
79
+ if (output.isTTY && height > 0) output.write(`\x1b[${height}A\x1b[0J`);
80
+ output.write(`${text}\n`);
81
+ height = text.split('\n').length;
82
+ };
83
+
84
+ const finish = value => {
85
+ if (settled) return;
86
+ settled = true;
87
+ // The settled answer replaces the live frame rather than appending to it:
88
+ // rewind the frame height first so a terminal reader sees one final line.
89
+ if (spec.final && output.isTTY) {
90
+ const line = spec.final(config, value, state);
91
+ if (line) {
92
+ if (height > 0) output.write(`\x1b[${height}A\x1b[0J`);
93
+ output.write(`${line}\n`);
94
+ height = 0;
95
+ }
96
+ }
97
+ resolveDone(value);
98
+ };
99
+ const fail = error => {
100
+ if (settled) return;
101
+ settled = true;
102
+ rejectDone(error);
103
+ };
104
+
105
+ const api = { finish, fail, redraw: draw };
106
+ let queue = Promise.resolve();
107
+ const onKeypress = (_chunk, key) => {
108
+ if (!key || settled) return;
109
+ // Cancellation cannot wait behind validation or a source request.
110
+ if (key.name === 'escape') {
111
+ if (spec.escapeValue !== undefined) finish(spec.escapeValue.value);
112
+ else fail(new PromptCancelled());
113
+ return;
114
+ }
115
+ if (key.ctrl && (key.name === 'c' || key.name === 'd')) {
116
+ fail(new PromptCancelled());
117
+ return;
118
+ }
119
+ key = { ...key, text: !key.ctrl && !key.meta && typeof _chunk === 'string' && Array.from(_chunk).every(char => char.codePointAt(0) >= 32 && char.codePointAt(0) !== 127) ? _chunk : '' };
120
+ // Serialize handling: a chunk can carry several keys at once, and async
121
+ // handlers (search/load-more) must not reorder Enter ahead of arrows.
122
+ queue = queue.then(async () => {
123
+ if (settled) return;
124
+
125
+ const directive = await spec.key(state, key, api);
126
+ if (!directive || settled) return;
127
+ if ('done' in directive) finish(directive.done);
128
+ else if (directive.cancel) fail(new PromptCancelled());
129
+ else if (directive.escape) finish(undefined);
130
+ }).catch(error => fail(error));
131
+ };
132
+
133
+ const onAbort = () => fail(context.signal.reason || new PromptCancelled());
134
+ const onEnd = () => fail(new PromptCancelled());
135
+
136
+ try {
137
+ readline.emitKeypressEvents(input);
138
+ if (canRaw) input.setRawMode(true);
139
+ input.on('keypress', onKeypress);
140
+ input.on('end', onEnd);
141
+ input.on('close', onEnd);
142
+ input.on('error', fail);
143
+ if (context.signal) {
144
+ if (context.signal.aborted) onAbort();
145
+ else context.signal.addEventListener('abort', onAbort, { once: true });
146
+ }
147
+ state = spec.init(config, context);
148
+ if (input.readableEnded || input.destroyed) onEnd();
149
+ if (typeof input.resume === 'function') input.resume();
150
+ draw();
151
+ spec.onReady?.(api);
152
+ return await done;
153
+ } finally {
154
+ input.removeListener('keypress', onKeypress);
155
+ input.removeListener('end', onEnd);
156
+ input.removeListener('close', onEnd);
157
+ input.removeListener('error', fail);
158
+ if (context.signal) context.signal.removeEventListener('abort', onAbort);
159
+ if (canRaw) {
160
+ try { input.setRawMode(previousRaw); } catch { /* stream already closed */ }
161
+ }
162
+ if (typeof input.pause === 'function' && input.isTTY) input.pause();
163
+ }
164
+ }
165
+
166
+ /** Escape resolves `value` instead of cancelling (record pickers). */
167
+ export function escapeResult(value) {
168
+ return { value };
169
+ }