@ywldan/kiro 0.2.12 → 0.3.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.
@@ -0,0 +1,112 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useState } from 'react';
3
+ import { Box, Text, useInput } from 'ink';
4
+ import { pickerPopupRows, pickerRangeLabel, pickerWindow } from './model-picker.js';
5
+ import { buildSessionRows, sessionCounts, sessionEmptyText, sessionRange, sessionRowItems, sessionRowLines, sessionRowText, sessionTabLabel, } from './session-picker.js';
6
+ /** Keys are highlighted so the hint reads at a glance; the rest stays dim. */
7
+ const KEY_COLOR = '#ff9e64';
8
+ function Key({ children }) {
9
+ return _jsx(Text, { color: KEY_COLOR, children: children });
10
+ }
11
+ function Said({ children }) {
12
+ return _jsx(Text, { dimColor: true, children: children });
13
+ }
14
+ /**
15
+ * Session picker with two tabs: the current directory and every other
16
+ * directory that has saved sessions. Left/right switch tabs.
17
+ */
18
+ export function SessionPicker({ cwd, data, activeSessionId = null, width, maxRows = 8, height, onSelect, onCancel, }) {
19
+ const [scope, setScope] = useState('current');
20
+ const [index, setIndex] = useState(0);
21
+ const [query, setQuery] = useState('');
22
+ const counts = sessionCounts(data);
23
+ const rows = buildSessionRows(data, scope, cwd, query);
24
+ const lines = sessionRowLines(rows);
25
+ const sessions = sessionRowItems(rows);
26
+ const count = sessions.length;
27
+ const selected = Math.min(index, Math.max(0, count - 1));
28
+ const selectedLine = lines[selected] ?? 0;
29
+ const popup = height !== undefined;
30
+ const hintRows = scope === 'others' ? 1 : 0;
31
+ // The tab bar takes one row the model picker does not have.
32
+ const listRows = popup ? pickerPopupRows(height, hintRows + 1) : maxRows;
33
+ const { start, end } = pickerWindow(selectedLine, rows.length, listRows);
34
+ const range = popup ? sessionRange(rows, start, end) : null;
35
+ const empty = sessionEmptyText(scope, query, count > 0);
36
+ // The opaque frame needs an explicit foreground even on light terminal themes.
37
+ const base = popup ? 'white' : undefined;
38
+ const switchScope = (next) => {
39
+ if (next === scope)
40
+ return;
41
+ setScope(next);
42
+ setIndex(0);
43
+ setQuery('');
44
+ };
45
+ useInput((input, key) => {
46
+ if (key.leftArrow) {
47
+ switchScope('current');
48
+ return;
49
+ }
50
+ if (key.rightArrow) {
51
+ switchScope('others');
52
+ return;
53
+ }
54
+ if (key.tab) {
55
+ switchScope(scope === 'current' ? 'others' : 'current');
56
+ return;
57
+ }
58
+ if (key.escape) {
59
+ if (query) {
60
+ setQuery('');
61
+ setIndex(0);
62
+ return;
63
+ }
64
+ onCancel();
65
+ return;
66
+ }
67
+ if (key.upArrow || key.downArrow) {
68
+ if (count === 0)
69
+ return;
70
+ const delta = key.upArrow ? -1 : 1;
71
+ setIndex(Math.min(count - 1, Math.max(0, selected + delta)));
72
+ return;
73
+ }
74
+ if (key.home) {
75
+ setIndex(0);
76
+ return;
77
+ }
78
+ if (key.end) {
79
+ setIndex(Math.max(0, count - 1));
80
+ return;
81
+ }
82
+ if (!key.return) {
83
+ if (key.backspace || key.delete) {
84
+ if (query) {
85
+ setQuery(query.slice(0, -1));
86
+ setIndex(0);
87
+ }
88
+ return;
89
+ }
90
+ if (key.ctrl || key.meta || key.pageUp || key.pageDown)
91
+ return;
92
+ const typed = input.replace(/[\u0000-\u001f\u007f]/g, '');
93
+ if (typed) {
94
+ setQuery(query + typed);
95
+ setIndex(0);
96
+ }
97
+ return;
98
+ }
99
+ const session = sessions[selected];
100
+ if (session)
101
+ onSelect(session);
102
+ });
103
+ return (_jsxs(Box, { flexDirection: "column", width: width, height: height, borderStyle: "round", borderColor: "cyan", paddingX: 1, flexShrink: 0, backgroundColor: popup ? 'black' : undefined, overflow: height === undefined ? undefined : 'hidden', children: [_jsx(Text, { bold: true, color: "cyan", wrap: "truncate-end", children: "Sessions" }), _jsxs(Text, { color: base, wrap: "truncate-end", children: [_jsx(Text, { inverse: scope === 'current', color: scope === 'current' ? 'cyan' : base, children: ` ${sessionTabLabel('current', counts)} ` }), _jsx(Said, { children: " " }), _jsx(Text, { inverse: scope === 'others', color: scope === 'others' ? 'cyan' : base, children: ` ${sessionTabLabel('others', counts)} ` })] }), _jsxs(Text, { color: base, wrap: "truncate-end", children: [_jsx(Said, { children: "Search: " }), query || _jsx(Said, { children: "type to filter" })] }), rows.slice(start, end).map((row, offset) => {
104
+ const line = start + offset;
105
+ if (row.kind === 'header') {
106
+ return (_jsx(Text, { dimColor: true, color: base, wrap: "truncate-end", children: row.text }, `h${line}`));
107
+ }
108
+ const focused = line === selectedLine;
109
+ return (_jsx(Text, { color: focused ? 'cyan' : base, bold: focused, wrap: "truncate-end", children: sessionRowText(row.session, row.session.id === activeSessionId) }, `s${line}`));
110
+ }), empty ? (_jsx(Text, { dimColor: true, color: base, wrap: "truncate-end", children: empty })) : null, scope === 'others' ? (_jsx(Text, { dimColor: true, color: base, wrap: "truncate-end", children: "Enter shows the directory to resume from." })) : null, range ? (_jsx(Text, { dimColor: true, color: base, wrap: "truncate-end", children: pickerRangeLabel(range) })) : null, height === undefined ? null : _jsx(Box, { flexGrow: 1 }), _jsxs(Text, { color: base, wrap: "truncate-end", children: [_jsx(Key, { children: "\u2190/\u2192" }), _jsx(Said, { children: " tab \u00B7 " }), _jsx(Key, { children: "\u2191/\u2193" }), _jsx(Said, { children: " move \u00B7 " }), _jsx(Key, { children: "Enter" }), _jsx(Said, { children: " resume \u00B7 " }), _jsx(Key, { children: "Esc" }), _jsx(Said, { children: ` ${query ? 'clear search' : 'close'}` })] })] }));
111
+ }
112
+ //# sourceMappingURL=SessionPicker.js.map
@@ -6,8 +6,8 @@ export const SLASH_COMMANDS = [
6
6
  { name: '/context', description: 'show approximate context usage' },
7
7
  { name: '/usage', description: 'show or hide the usage card' },
8
8
  { name: '/compact', description: 'summarize older turns to free context' },
9
- { name: '/sessions', description: 'list saved sessions for this directory' },
10
- { name: '/resume', usage: '<n | id>', description: 'resume a saved session' },
9
+ { name: '/sessions', description: 'list saved sessions, this directory and others' },
10
+ { name: '/resume', usage: '[n | id]', description: 'open the session picker, or resume by number or id' },
11
11
  { name: '/undo', description: 'revert the last file change Kiro made (write/edit/patch)' },
12
12
  { name: '/clear', description: 'start a new session' },
13
13
  { name: '/export', usage: '[file]', description: 'write the transcript to a Markdown file' },
@@ -0,0 +1,111 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { promisify } from 'node:util';
3
+ import { walkTree } from '../tools/walk.js';
4
+ const execFileAsync = promisify(execFile);
5
+ export const MAX_INDEX_FILES = 50_000;
6
+ const MAX_GIT_OUTPUT_BYTES = 20 * 1024 * 1024;
7
+ function normalize(paths) {
8
+ const unique = new Set();
9
+ for (const raw of paths) {
10
+ const path = raw.split('\\').join('/').replace(/^\.\//, '');
11
+ if (!path || path.includes('\n'))
12
+ continue;
13
+ unique.add(path);
14
+ }
15
+ return [...unique].sort((left, right) => left.localeCompare(right)).slice(0, MAX_INDEX_FILES);
16
+ }
17
+ /** Tracked and untracked files, honouring .gitignore. Null when git is unavailable or fails. */
18
+ async function gitFiles(cwd, signal) {
19
+ try {
20
+ const { stdout } = await execFileAsync('git', ['ls-files', '-z', '--cached', '--others', '--exclude-standard'], {
21
+ cwd,
22
+ timeout: 3000,
23
+ maxBuffer: MAX_GIT_OUTPUT_BYTES,
24
+ signal,
25
+ });
26
+ return normalize(stdout.split('\0'));
27
+ }
28
+ catch {
29
+ return null;
30
+ }
31
+ }
32
+ async function walkFiles(cwd, signal) {
33
+ const controller = new AbortController();
34
+ const onAbort = () => controller.abort();
35
+ if (signal?.aborted)
36
+ return [];
37
+ signal?.addEventListener('abort', onAbort, { once: true });
38
+ const files = [];
39
+ try {
40
+ await walkTree({
41
+ cwd,
42
+ rootAbs: cwd,
43
+ signal: controller.signal,
44
+ visit(entry) {
45
+ if (entry.isDir)
46
+ return true;
47
+ files.push(entry.rel);
48
+ return files.length < MAX_INDEX_FILES;
49
+ },
50
+ });
51
+ }
52
+ finally {
53
+ signal?.removeEventListener('abort', onAbort);
54
+ }
55
+ return normalize(files);
56
+ }
57
+ /** File list for the @ menu: git first, then a .gitignore-aware walk. */
58
+ export async function listProjectFiles(cwd, signal) {
59
+ if (signal?.aborted)
60
+ return [];
61
+ const fromGit = await gitFiles(cwd, signal);
62
+ if (fromGit !== null)
63
+ return fromGit;
64
+ return walkFiles(cwd, signal);
65
+ }
66
+ function subsequence(text, needle) {
67
+ let index = 0;
68
+ for (const char of text) {
69
+ if (char === needle[index])
70
+ index++;
71
+ if (index === needle.length)
72
+ return true;
73
+ }
74
+ return false;
75
+ }
76
+ /** Ranks paths for a mention query: basename matches first, then path matches. */
77
+ export function filterFiles(files, query, limit = 200) {
78
+ const needle = query.trim().toLowerCase();
79
+ if (!needle)
80
+ return files.slice(0, limit);
81
+ const scored = [];
82
+ for (const file of files) {
83
+ const lower = file.toLowerCase();
84
+ const base = lower.slice(lower.lastIndexOf('/') + 1);
85
+ let score = 0;
86
+ if (lower === needle)
87
+ score = 1000;
88
+ else if (base.startsWith(needle))
89
+ score = 900;
90
+ else if (base.includes(needle))
91
+ score = 800;
92
+ else if (lower.startsWith(needle))
93
+ score = 750;
94
+ else if (lower.split('/').some((segment) => segment.startsWith(needle)))
95
+ score = 700;
96
+ else if (lower.includes(needle))
97
+ score = 600;
98
+ else if (subsequence(base, needle))
99
+ score = 500;
100
+ else if (subsequence(lower, needle))
101
+ score = 400;
102
+ else
103
+ continue;
104
+ scored.push({ path: file, score });
105
+ }
106
+ scored.sort((left, right) => right.score - left.score ||
107
+ left.path.length - right.path.length ||
108
+ left.path.localeCompare(right.path));
109
+ return scored.slice(0, limit).map((entry) => entry.path);
110
+ }
111
+ //# sourceMappingURL=file-index.js.map
@@ -0,0 +1,63 @@
1
+ const BOUNDARY = /[\s([{'"]/;
2
+ /** Index of a freshly typed @ that can start a mention, or null. */
3
+ export function mentionOpeningAt(chars, cursor) {
4
+ if (cursor < 1 || chars[cursor - 1] !== '@')
5
+ return null;
6
+ if (cursor === 1)
7
+ return 0;
8
+ return BOUNDARY.test(chars[cursor - 2] ?? '') ? cursor - 1 : null;
9
+ }
10
+ /** Nearest valid mention ending at the caret, used after a typed chunk. */
11
+ export function mentionNearby(chars, cursor) {
12
+ for (let start = cursor - 1; start >= 0 && cursor - start <= 200; start--) {
13
+ const char = chars[start];
14
+ if (char === '\n')
15
+ return null;
16
+ if (char !== '@')
17
+ continue;
18
+ if (start > 0 && !BOUNDARY.test(chars[start - 1] ?? ''))
19
+ continue;
20
+ if (mentionAt(chars, cursor, start))
21
+ return start;
22
+ }
23
+ return null;
24
+ }
25
+ /** Reads the mention that starts at `start`, or null when the caret left it or it has whitespace. */
26
+ export function mentionAt(chars, cursor, start) {
27
+ if (start < 0 || start >= chars.length || chars[start] !== '@')
28
+ return null;
29
+ if (start > 0 && !BOUNDARY.test(chars[start - 1] ?? ''))
30
+ return null;
31
+ if (cursor <= start)
32
+ return null;
33
+ const quote = chars[start + 1];
34
+ if (quote === '"') {
35
+ let close = -1;
36
+ for (let index = start + 2; index < chars.length; index++) {
37
+ if (chars[index] === '"') {
38
+ close = index;
39
+ break;
40
+ }
41
+ if (chars[index] === '\n')
42
+ return null;
43
+ }
44
+ if (close !== -1 && close < cursor)
45
+ return null;
46
+ const end = close === -1 ? cursor : close + 1;
47
+ return {
48
+ start,
49
+ end,
50
+ query: chars.slice(start + 2, Math.min(cursor, end)).join(''),
51
+ quoted: true,
52
+ };
53
+ }
54
+ const query = chars.slice(start + 1, cursor).join('');
55
+ if (/[\s\n]/.test(query))
56
+ return null;
57
+ return { start, end: cursor, query, quoted: false };
58
+ }
59
+ /** Text to insert for a file path, quoting names that contain spaces. */
60
+ export function mentionText(file) {
61
+ return /[\s"]/.test(file) ? `@"${file.replace(/"/g, '\\"')}"` : `@${file}`;
62
+ }
63
+ //# sourceMappingURL=mention.js.map
@@ -0,0 +1,96 @@
1
+ import { homedir } from 'node:os';
2
+ import path from 'node:path';
3
+ import { formatSessionTime } from '../sessions.js';
4
+ /** Rows the inline session picker reserves below the transcript. */
5
+ export const SESSION_INLINE_ROWS = 13;
6
+ export function sessionCounts(data) {
7
+ return {
8
+ current: data.current.length,
9
+ others: data.others.reduce((total, group) => total + group.sessions.length, 0),
10
+ };
11
+ }
12
+ export function sessionTabLabel(scope, counts) {
13
+ return scope === 'current'
14
+ ? `This directory (${counts.current})`
15
+ : `Other directories (${counts.others})`;
16
+ }
17
+ /** Home-relative path so other directories read short in the picker. */
18
+ export function shortCwd(cwd, currentCwd) {
19
+ const resolved = path.resolve(cwd);
20
+ if (resolved === path.resolve(currentCwd))
21
+ return '.';
22
+ const home = homedir();
23
+ if (resolved === home)
24
+ return '~';
25
+ if (resolved.startsWith(`${home}${path.sep}`))
26
+ return `~${resolved.slice(home.length)}`;
27
+ return resolved;
28
+ }
29
+ /** Case-insensitive multi-term search across title, id, and directory. */
30
+ export function filterSessions(sessions, query) {
31
+ const terms = query.toLowerCase().split(/\s+/).filter(Boolean);
32
+ if (terms.length === 0)
33
+ return sessions;
34
+ return sessions.filter((session) => {
35
+ const haystack = `${session.title} ${session.id} ${session.cwd} ${session.profile} ${session.model}`.toLowerCase();
36
+ return terms.every((term) => haystack.includes(term));
37
+ });
38
+ }
39
+ export function sessionRowText(session, active) {
40
+ const marker = active ? '*' : ' ';
41
+ const count = `${session.messageCount} msg${session.messageCount === 1 ? '' : 's'}`;
42
+ return `${marker} ${session.id.slice(0, 8)} ${formatSessionTime(session.updatedAt)} ${count} ${session.title}`;
43
+ }
44
+ /** Display rows for one tab; other directories get a header per cwd. */
45
+ export function buildSessionRows(data, scope, currentCwd, query = '') {
46
+ if (scope === 'current') {
47
+ return filterSessions(data.current, query).map((session) => ({
48
+ kind: 'session',
49
+ scope,
50
+ session,
51
+ }));
52
+ }
53
+ const rows = [];
54
+ for (const group of data.others) {
55
+ const sessions = filterSessions(group.sessions, query);
56
+ if (sessions.length === 0)
57
+ continue;
58
+ rows.push({
59
+ kind: 'header',
60
+ scope,
61
+ text: `${shortCwd(group.cwd, currentCwd)} (${sessions.length})`,
62
+ });
63
+ for (const session of sessions)
64
+ rows.push({ kind: 'session', scope, session });
65
+ }
66
+ return rows;
67
+ }
68
+ export function sessionRowLines(rows) {
69
+ return rows.flatMap((row, index) => (row.kind === 'session' ? [index] : []));
70
+ }
71
+ export function sessionRowItems(rows) {
72
+ return rows.flatMap((row) => (row.kind === 'session' ? [row.session] : []));
73
+ }
74
+ /** Same as profileRange, counting sessions while skipping directory headers. */
75
+ export function sessionRange(rows, start, end) {
76
+ const lines = sessionRowLines(rows);
77
+ const above = lines.filter((line) => line < start).length;
78
+ const visible = lines.filter((line) => line >= start && line < end).length;
79
+ return {
80
+ above,
81
+ below: lines.length - above - visible,
82
+ first: visible === 0 ? 0 : above + 1,
83
+ last: above + visible,
84
+ total: lines.length,
85
+ };
86
+ }
87
+ export function sessionEmptyText(scope, query, hasSessions) {
88
+ if (query.trim())
89
+ return `No sessions match "${query}". Backspace to edit, Esc to clear.`;
90
+ if (hasSessions)
91
+ return '';
92
+ return scope === 'current'
93
+ ? 'No saved sessions for this directory.'
94
+ : 'No sessions from other directories.';
95
+ }
96
+ //# sourceMappingURL=session-picker.js.map
package/dist/ui/text.js CHANGED
@@ -114,7 +114,7 @@ export function parseEditSequence(text) {
114
114
  }
115
115
  const clamp = (value, max) => Math.max(0, Math.min(value, max));
116
116
  const ANSI_TOKEN = new RegExp(`(${ANSI_CSI.source}|${ANSI_OSC.source})`, 'g');
117
- /** Above this chunk size a trailing newline is treated as pasted text, not Enter. */
117
+ /** Above this chunk size a trailing carriage return is treated as pasted text, not Enter. */
118
118
  const MAX_SUBMIT_CHUNK = 200;
119
119
  /**
120
120
  * Ink hands a whole stdin chunk to a single `useInput` call and only decodes
@@ -128,7 +128,7 @@ export function parseInputChunk(text) {
128
128
  if (text === '' || parseEditSequence(text) !== null)
129
129
  return [];
130
130
  const lineBreaks = (text.match(/[\r\n]/g) ?? []).length;
131
- const trailingEnter = lineBreaks === 1 && text.length <= MAX_SUBMIT_CHUNK && /[\r\n]$/.test(text);
131
+ const trailingEnter = lineBreaks === 1 && text.length <= MAX_SUBMIT_CHUNK && text.endsWith('\r');
132
132
  const ops = [];
133
133
  let buffer = '';
134
134
  const flush = () => {
@@ -148,21 +148,32 @@ export function parseInputChunk(text) {
148
148
  }
149
149
  continue;
150
150
  }
151
- for (const char of token) {
151
+ for (let index = 0; index < token.length; index++) {
152
+ const char = token[index];
152
153
  const code = char.codePointAt(0) ?? 0;
153
154
  if (char === '\x7f' || char === '\x08') {
154
155
  flush();
155
156
  ops.push({ type: 'backspace', count: 1 });
156
157
  }
157
- else if (char === '\r' || char === '\n') {
158
+ else if (char === '\r') {
158
159
  if (trailingEnter) {
159
- flush();
160
- ops.push({ type: 'submit' });
160
+ if (buffer.endsWith('\\')) {
161
+ buffer = `${buffer.slice(0, -1)}\n`;
162
+ }
163
+ else {
164
+ flush();
165
+ ops.push({ type: 'submit' });
166
+ }
161
167
  }
162
168
  else {
163
- buffer += ' ';
169
+ buffer += '\n';
170
+ if (token[index + 1] === '\n')
171
+ index++;
164
172
  }
165
173
  }
174
+ else if (char === '\n') {
175
+ buffer += '\n';
176
+ }
166
177
  else if (char === '\t') {
167
178
  buffer += ' ';
168
179
  }
@@ -257,6 +268,147 @@ export function applyInputOps(state, ops, maxChars = Number.POSITIVE_INFINITY) {
257
268
  }
258
269
  return { state: current, submitted: false };
259
270
  }
271
+ export const PASTE_START = '\x1b[200~';
272
+ export const PASTE_END = '\x1b[201~';
273
+ const PASTE_START_BARE = '[200~';
274
+ const PASTE_END_BARE = '[201~';
275
+ export function normalizePastedText(text) {
276
+ return text
277
+ .replace(/\r\n?/g, '\n')
278
+ .replace(/\t/g, ' ')
279
+ .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, '');
280
+ }
281
+ function findPasteStart(text) {
282
+ const escaped = text.indexOf(PASTE_START);
283
+ if (escaped !== -1)
284
+ return { index: escaped, length: PASTE_START.length };
285
+ if (text.startsWith(PASTE_START_BARE))
286
+ return { index: 0, length: PASTE_START_BARE.length };
287
+ return null;
288
+ }
289
+ function findPasteEnd(text) {
290
+ const escaped = text.indexOf(PASTE_END);
291
+ const bare = text.indexOf(PASTE_END_BARE);
292
+ if (escaped === -1 && bare === -1)
293
+ return null;
294
+ if (escaped === -1)
295
+ return { index: bare, length: PASTE_END_BARE.length };
296
+ if (bare === -1 || escaped <= bare)
297
+ return { index: escaped, length: PASTE_END.length };
298
+ return { index: bare, length: PASTE_END_BARE.length };
299
+ }
300
+ /** Longest suffix that could still become a start marker. */
301
+ function pendingStart(text) {
302
+ const limit = Math.min(PASTE_START.length - 1, text.length);
303
+ for (let length = limit; length >= 3; length--) {
304
+ const suffix = text.slice(-length);
305
+ if (PASTE_START.startsWith(suffix) || PASTE_START_BARE.startsWith(suffix))
306
+ return suffix;
307
+ }
308
+ return '';
309
+ }
310
+ /**
311
+ * Consumes bracketed paste markers from a raw input chunk. Ink strips one
312
+ * leading escape byte per chunk and a terminal may split a marker across
313
+ * reads, so both cases are buffered.
314
+ */
315
+ export function feedPaste(state, input) {
316
+ if (state.open) {
317
+ const combined = state.buffer + input;
318
+ const end = findPasteEnd(combined);
319
+ if (!end) {
320
+ return {
321
+ state: { open: true, buffer: combined, pending: '' },
322
+ text: null,
323
+ consumed: true,
324
+ };
325
+ }
326
+ const text = normalizePastedText(combined.slice(0, end.index)) +
327
+ normalizePastedText(combined.slice(end.index + end.length));
328
+ return { state: { open: false, buffer: '', pending: '' }, text, consumed: true };
329
+ }
330
+ const hadPending = state.pending !== '';
331
+ const combined = state.pending + input;
332
+ const start = findPasteStart(combined);
333
+ if (!start) {
334
+ const pending = pendingStart(combined);
335
+ if (pending.length >= 3 && pending.length === combined.length) {
336
+ return { state: { open: false, buffer: '', pending }, text: null, consumed: true };
337
+ }
338
+ if (!hadPending) {
339
+ return { state: { open: false, buffer: '', pending: '' }, text: null, consumed: false };
340
+ }
341
+ const flushed = combined.slice(0, combined.length - pending.length);
342
+ return {
343
+ state: { open: false, buffer: '', pending },
344
+ text: flushed ? normalizePastedText(flushed) : null,
345
+ consumed: true,
346
+ };
347
+ }
348
+ const prefix = combined.slice(0, start.index);
349
+ const after = combined.slice(start.index + start.length);
350
+ const end = findPasteEnd(after);
351
+ if (!end) {
352
+ return {
353
+ state: { open: true, buffer: after, pending: '' },
354
+ text: prefix ? normalizePastedText(prefix) : null,
355
+ consumed: true,
356
+ };
357
+ }
358
+ const pasted = after.slice(0, end.index);
359
+ const rest = after.slice(end.index + end.length);
360
+ return {
361
+ state: { open: false, buffer: '', pending: '' },
362
+ text: normalizePastedText(prefix + pasted) + normalizePastedText(rest),
363
+ consumed: true,
364
+ };
365
+ }
366
+ /** Splits input into visual lines, honouring explicit newlines and hard wrapping. */
367
+ export function layoutInput(chars, width, masked = false) {
368
+ const maxWidth = Math.max(1, width);
369
+ const lines = [];
370
+ let start = 0;
371
+ let text = '';
372
+ let used = 0;
373
+ const flush = (end, wrapped) => {
374
+ lines.push({ start, end, text, wrapped });
375
+ start = end;
376
+ text = '';
377
+ used = 0;
378
+ };
379
+ for (let index = 0; index < chars.length; index++) {
380
+ const char = masked ? '•' : chars[index];
381
+ if (char === '\n') {
382
+ flush(index, false);
383
+ start = index + 1;
384
+ continue;
385
+ }
386
+ const charWidth = Math.max(1, stringWidth(char));
387
+ if (used > 0 && used + charWidth > maxWidth)
388
+ flush(index, true);
389
+ text += char;
390
+ used += charWidth;
391
+ }
392
+ flush(chars.length, false);
393
+ return lines;
394
+ }
395
+ /** Finds the visual line holding the caret; wraps forward, newlines stay put. */
396
+ export function cursorLineIndex(lines, cursor) {
397
+ for (let index = 0; index < lines.length; index++) {
398
+ const line = lines[index];
399
+ if (cursor < line.start)
400
+ return Math.max(0, index - 1);
401
+ if (cursor < line.end)
402
+ return index;
403
+ if (cursor === line.end) {
404
+ const next = lines[index + 1];
405
+ if (line.wrapped && next && next.start === cursor)
406
+ return index + 1;
407
+ return index;
408
+ }
409
+ }
410
+ return lines.length - 1;
411
+ }
260
412
  export function formatDuration(ms) {
261
413
  if (ms < 1000)
262
414
  return `${ms}ms`;
package/dist/version.js CHANGED
@@ -1,2 +1,2 @@
1
- export const VERSION = '0.2.12';
1
+ export const VERSION = '0.3.0';
2
2
  //# sourceMappingURL=version.js.map