@alexwkleung/reika 0.7.0 → 0.8.0

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.
@@ -7,6 +7,8 @@ import chalk from 'chalk';
7
7
  import { theme, themeChalk } from './theme.js';
8
8
  import { highlightCode } from './highlight.js';
9
9
  import { drawnWidth, sanitizeTerminalText } from './termtext.js';
10
+ import { sliceStyled, wrapStyledRows } from './layout.js';
11
+ import stripAnsi from 'strip-ansi';
10
12
  export function DiffView({ diff, path, maxWidth, startLine, oldStartLine, maxRows, hiddenNote = n => `… ${n} more lines`, }) {
11
13
  const lang = detectLanguage(path);
12
14
  const blocks = parseDiffBlocks(sanitizeDiffLines(diff));
@@ -39,7 +41,9 @@ export function fitRowsToHeight(lines, maxRows, contentWidth) {
39
41
  const total = heights.reduce((a, b) => a + b, 0);
40
42
  if (total <= maxRows)
41
43
  return { lines, hidden: 0 };
42
- const budget = Math.max(1, maxRows - 1);
44
+ // As in the command preview: the footer costs a row, and the rows kept must stay inside
45
+ // `maxRows` — a one-row budget draws the footer alone.
46
+ const budget = Math.max(0, maxRows - 1);
43
47
  let used = 0;
44
48
  let kept = 0;
45
49
  while (kept < lines.length && used + heights[kept] <= budget)
@@ -192,15 +196,13 @@ const CONTINUATION = ' ';
192
196
  // Ink counts as one row while the screen spends two (the undercount the live-frame budget can't
193
197
  // afford). So wrap here, where the widths are known.
194
198
  //
195
- // wrap-ansi does the breaking because the content is already syntax-highlighted: it re-opens the
196
- // active SGR codes on each row instead of leaving the tail unstyled. `hard` breaks tokens with no
197
- // space in them — a long path or a base64 blob — which is the common case in code.
199
+ // wrap-ansi does the breaking because the content is already syntax-highlighted, and
200
+ // `wrapStyledRows` re-opens every active style on each row — wrap-ansi alone re-opens only the
201
+ // innermost, which dropped a wrapped comment's gray (#852). `hard` breaks tokens with no space in
202
+ // them — a long path or a base64 blob — which is the common case in code.
198
203
  function WrappedRow({ content, prefix, gutter, maxWidth, side, }) {
199
204
  const bg = side ? rowBg(side) : undefined;
200
- const rows = wrapAnsi(content, Math.max(1, maxWidth - prefix.length), {
201
- trim: false,
202
- hard: true,
203
- }).split('\n');
205
+ const rows = wrapStyledRows(content, maxWidth - prefix.length);
204
206
  // Columns the gutter holds: its digits plus the space between it and the code.
205
207
  const gutterCells = gutter ? gutter.length + 1 : 0;
206
208
  return (_jsx(_Fragment, { children: rows.map((row, i) => {
@@ -290,6 +292,12 @@ function PairedLine({ line, other, side, language, maxWidth, gutter, }) {
290
292
  // Painted into one string rather than nested <Text> elements: wrapping needs a single run of
291
293
  // text to break, and chalk re-opens the outer style after each nested close, so the line's base
292
294
  // background survives every highlighted span the same way Ink's own nesting would.
295
+ //
296
+ // The line is highlighted whole and the unchanged parts cut out of it: highlighted alone, a part
297
+ // from the middle of a comment has no `//` and came out in the default color (#852).
298
+ const highlighted = highlightCode(line, language);
299
+ const sliceable = stripAnsi(highlighted) === line;
300
+ let offset = 0;
293
301
  const painted = parts
294
302
  .map(p => {
295
303
  // Skip segments that belong only to the other side.
@@ -297,13 +305,16 @@ function PairedLine({ line, other, side, language, maxWidth, gutter, }) {
297
305
  return '';
298
306
  if (side === 'added' && p.removed)
299
307
  return '';
308
+ const start = offset;
309
+ offset += p.value.length;
300
310
  const isChange = side === 'removed' ? p.removed : p.added;
301
311
  // Brighter background for the changed portion — stands out against the line's own.
302
- return isChange
303
- ? chalk.level === 1
312
+ if (isChange) {
313
+ return chalk.level === 1
304
314
  ? chalk[side === 'added' ? 'bgGreen' : 'bgRed'].whiteBright(p.value)
305
- : chalk.bgHex(highlightBg).hex(HIGHLIGHT_FG)(p.value)
306
- : highlightCode(p.value, language);
315
+ : chalk.bgHex(highlightBg).hex(HIGHLIGHT_FG)(p.value);
316
+ }
317
+ return sliceable ? sliceStyled(highlighted, start, offset) : highlightCode(p.value, language);
307
318
  })
308
319
  .join('');
309
320
  return (_jsx(WrappedRow, { content: painted, prefix: prefix, gutter: gutter, maxWidth: maxWidth, side: side }));
@@ -15,17 +15,26 @@ export const OWN_ANSWER_LABEL = 'Something else — type your own answer';
15
15
  // The dialog sits in Ink's live frame, and every word in it is model-written: a frame as tall as
16
16
  // the viewport makes Ink repaint with `\x1b[3J` and strands the dialog in the scrollback (#456,
17
17
  // the #447 shape). Fixed rows: marginTop, top border, both paddingY rows, the header, the margins
18
- // above the question, the options and the hint, and the hint — then the input and status bar
19
- // underneath, plus slack.
20
- const DIALOG_FIXED_ROWS = 9;
18
+ // above the question, the options and the hint — then the input and status bar underneath, plus
19
+ // slack. The hint rides ON TOP of that, measured at the live width (#842): it is one row on a wide
20
+ // terminal and three on a narrow pane, and counting it as one is how the frame outgrew the budget
21
+ // that sized the question and cleared the scrollback.
22
+ const FRAME_ROWS = 4; // marginTop, top border, and both paddingY rows
23
+ const LABEL_ROWS = 1; // the `⏺ Question` header
24
+ const GAP_ROWS = 2; // the margins above the question and above the options
25
+ const HINT_GAP_ROWS = 1; // … and the one above the hint, which goes with it
21
26
  const BELOW_DIALOG_ROWS = 6;
22
27
  // While the user types, the input under the dialog is live and scrolls its own window once the
23
28
  // answer outgrows the room the dialog leaves it (App passes `questionDialogHeight` to Input). That
24
29
  // window never goes below three lines plus its two "… lines above/below" markers, so the question
25
30
  // holds those rows back — the input can't be squeezed into overflowing the frame.
26
31
  const TYPING_INPUT_ROWS = 4;
27
- // What fits, in the order things are given up: the options are what the user acts on, so every
28
- // option row and the own-answer row always show; descriptions go first, then the question's tail.
32
+ // The two hint lines, and what the dialog says while the reason field is open on the question.
33
+ const QUESTION_HINT = '↑↓ or 1-9 navigate · enter select · tab add a note · ctrl-c abort';
34
+ const QUESTION_TYPING_HINT = 'enter submit · ctrl-c back to the options';
35
+ // What fits, in the order things are given up: the options are what the user acts on, so the
36
+ // own-answer row always shows and an option row is the last thing to go; descriptions go first,
37
+ // then the hint (see below), then the question's tail.
29
38
  // Exported for unit tests.
30
39
  export function fitQuestionToHeight(questionRows, labelRows, descriptionRows, budget) {
31
40
  if (questionRows + labelRows + descriptionRows <= budget) {
@@ -36,15 +45,77 @@ export function fitQuestionToHeight(questionRows, labelRows, descriptionRows, bu
36
45
  // One row goes to the "more lines" note, and the question keeps at least its first row.
37
46
  return { showDescriptions: false, questionRows: Math.max(1, budget - labelRows - 1) };
38
47
  }
48
+ // For the typing state, where the option list is not drawn: nothing visible, nothing hidden.
49
+ const EMPTY_WINDOW = { start: 0, end: 0, moreAbove: 0, moreBelow: 0, rows: 0 };
50
+ // Which options show when the option rows alone outgrow the pane (#856). Every option row can no
51
+ // longer always show — a dialog whose labels overflow is a frame as tall as the viewport, which is
52
+ // the scrollback wipe — but truncating a label to one row is worse than hiding options: these are
53
+ // full sentences, and the words that tell two of them apart sit past the first row. So the list is
54
+ // windowed around the selection, and the markers say how many are out of sight. Exported for unit
55
+ // tests.
56
+ export function fitOptionsToHeight(rowCosts, budget, selectedIndex) {
57
+ const n = rowCosts.length;
58
+ const whole = {
59
+ start: 0,
60
+ end: n,
61
+ moreAbove: 0,
62
+ moreBelow: 0,
63
+ rows: rowCosts.reduce((a, c) => a + c, 0),
64
+ };
65
+ if (n === 0 || whole.rows <= budget)
66
+ return whole;
67
+ // The markers are paid for out of the same budget they will be sized against, so each possible
68
+ // reservation is tried and the widest run whose markers fit inside it wins. Settling one
69
+ // reservation into the next does not converge: a freed row can let the run grow past an option
70
+ // that then keeps it off the end, and the loop stopped on the run that overran (#857). Reserving
71
+ // both rows always fits its own markers, so there is always a candidate.
72
+ let run = grow(rowCosts, Math.max(0, budget - 2), selectedIndex);
73
+ for (const reserved of [0, 1]) {
74
+ const candidate = grow(rowCosts, Math.max(0, budget - reserved), selectedIndex);
75
+ const markers = (candidate.start > 0 ? 1 : 0) + (candidate.end < n ? 1 : 0);
76
+ if (markers > reserved)
77
+ continue;
78
+ if (candidate.end - candidate.start > run.end - run.start)
79
+ run = candidate;
80
+ }
81
+ const moreAbove = run.start;
82
+ const moreBelow = n - run.end;
83
+ return {
84
+ start: run.start,
85
+ end: run.end,
86
+ moreAbove,
87
+ moreBelow,
88
+ rows: run.rows + (moreAbove > 0 ? 1 : 0) + (moreBelow > 0 ? 1 : 0),
89
+ };
90
+ }
91
+ // The longest run of options containing the selection that fits in `avail` rows: downward first,
92
+ // so the list reads in order from the row the cursor is on, then upward to fill what is left. A
93
+ // run always holds its selection, even when that row alone overruns: there is nothing smaller to
94
+ // draw, and the window is derived from the cursor's index every render — the 1-9 keys land wherever
95
+ // they name — so it never has to scroll a stale run into view.
96
+ function grow(rowCosts, avail, selectedIndex) {
97
+ const n = rowCosts.length;
98
+ let start = Math.min(Math.max(selectedIndex, 0), n - 1);
99
+ let end = start + 1;
100
+ let rows = rowCosts[start];
101
+ while (end < n && rows + rowCosts[end] <= avail)
102
+ rows += rowCosts[end++];
103
+ while (start > 0 && rows + rowCosts[start - 1] <= avail)
104
+ rows += rowCosts[--start];
105
+ return { start, end, rows };
106
+ }
39
107
  // Renders as the top half of one continuous frame whose bottom half is the input box (see
40
108
  // Approval/ModelSelect for the same `borderBottom={false}` + `attachedAbove` merge). Unlike those
41
109
  // two, the input stays LIVE underneath while typing — the question is a prompt for text, and
42
110
  // reusing Input gets editing, history and paste for free rather than rebuilding a field in here.
43
111
  export function Question({ request, selectedIndex, typing, width, rows = process.stdout.rows || 24, reservedRows = 0, }) {
44
112
  const liveWidth = useContentWidth(DIALOG_CHROME);
45
- const { labels, descriptions, ownAnswer, questionLines, typingLine, fit, hiddenQuestionRows } = layoutQuestion(request, typing ?? null, width ?? liveWidth, rows, reservedRows);
113
+ const { labels, descriptions, ownAnswer, questionLines, typingLine, fit, hiddenQuestionRows, hint, showHint, options, padRows, } = layoutQuestion(request, typing ?? null, width ?? liveWidth, rows, reservedRows, selectedIndex);
114
+ // Null only while typing, where the list is not drawn at all.
115
+ const shown = options ?? EMPTY_WINDOW;
46
116
  const hang = HANG;
47
- return (_jsxs(Box, { borderStyle: glyphs.border, borderBottom: false, flexDirection: "column", paddingX: 1, paddingY: 1, marginX: -1, marginTop: 1, children: [_jsx(Text, { color: theme.tool, children: `${DIALOG_MARKER} Question` }), _jsxs(Box, { marginTop: 1, flexDirection: "column", children: [_jsx(Text, { children: questionLines.slice(0, fit.questionRows).join('\n') }), hiddenQuestionRows > 0 ? (_jsx(Text, { color: theme.muted, children: `… ${hiddenQuestionRows} more lines` })) : null] }), typing ? (_jsx(Box, { flexDirection: "column", marginTop: 1, children: _jsx(Text, { color: theme.secondary, children: typingLine }) })) : (_jsxs(Box, { flexDirection: "column", marginTop: 1, children: [request.options.map((o, i) => {
117
+ return (_jsxs(Box, { borderStyle: glyphs.border, borderBottom: false, flexDirection: "column", paddingX: 1, paddingY: 1, marginX: -1, marginTop: 1, children: [_jsx(Text, { color: theme.tool, children: `${DIALOG_MARKER} Question` }), _jsxs(Box, { marginTop: 1, flexDirection: "column", children: [_jsx(Text, { children: questionLines.slice(0, fit.questionRows).join('\n') }), hiddenQuestionRows > 0 ? (_jsx(Text, { color: theme.muted, children: `… ${hiddenQuestionRows} more lines` })) : null] }), typing ? (_jsx(Box, { flexDirection: "column", marginTop: 1, children: _jsx(Text, { color: theme.secondary, children: typingLine }) })) : (_jsxs(Box, { flexDirection: "column", marginTop: 1, children: [shown.moreAbove > 0 ? (_jsx(Text, { color: theme.muted, children: ` ↑ ${shown.moreAbove} more` })) : null, request.options.slice(shown.start, shown.end).map((o, at) => {
118
+ const i = shown.start + at;
48
119
  const selected = i === selectedIndex;
49
120
  const num = `${i + 1}. `;
50
121
  // Wrapped as one string so the tag can't be pushed onto its own flush-left row, then
@@ -53,9 +124,7 @@ export function Question({ request, selectedIndex, typing, width, rows = process
53
124
  const tagAt = tag ? wrapped.lastIndexOf(tag.trimStart()) : -1;
54
125
  const label = tagAt >= 0 ? wrapped.slice(0, tagAt) : wrapped;
55
126
  return (_jsxs(Box, { flexDirection: "column", children: [_jsxs(Text, { children: [_jsx(Text, { color: selected ? theme.accent : undefined, children: selected ? '› ' : ' ' }), _jsx(Text, { color: selected ? theme.accent : theme.secondary, children: num }), _jsx(Text, { color: selected ? theme.accent : undefined, children: label }), tagAt >= 0 ? _jsx(Text, { color: theme.info, children: wrapped.slice(tagAt) }) : null] }), fit.showDescriptions && descriptions[i] ? (_jsx(Text, { color: theme.muted, children: ' '.repeat(hang) + descriptions[i] })) : null] }, i));
56
- }), _jsxs(Text, { children: [_jsx(Text, { color: selectedIndex === request.options.length ? theme.accent : undefined, children: selectedIndex === request.options.length ? '› ' : ' ' }), _jsx(Text, { color: selectedIndex === request.options.length ? theme.accent : theme.secondary, children: `${request.options.length + 1}. ` }), _jsx(Text, { color: selectedIndex === request.options.length ? theme.accent : theme.secondary, children: ownAnswer })] })] })), _jsx(Box, { marginTop: 1, children: _jsx(Text, { color: theme.muted, children: typing
57
- ? 'enter submit · ctrl-c back to the options'
58
- : '↑↓ or 1-9 navigate · enter select · tab add a note · ctrl-c abort' }) })] }));
127
+ }), shown.moreBelow > 0 ? (_jsx(Text, { color: theme.muted, children: ` ↓ ${shown.moreBelow} more` })) : null, _jsxs(Text, { children: [_jsx(Text, { color: selectedIndex === request.options.length ? theme.accent : undefined, children: selectedIndex === request.options.length ? '› ' : ' ' }), _jsx(Text, { color: selectedIndex === request.options.length ? theme.accent : theme.secondary, children: `${request.options.length + 1}. ` }), _jsx(Text, { color: selectedIndex === request.options.length ? theme.accent : theme.secondary, children: ownAnswer })] }), padRows > 0 ? _jsx(Box, { height: padRows }) : null] })), showHint ? (_jsx(Box, { marginTop: 1, children: _jsx(Text, { color: theme.muted, children: hint }) })) : null] }));
59
128
  }
60
129
  // Labels are full sentences and wrap on any ordinary terminal. Ink has no hanging indent, so a
61
130
  // continuation row would land flush left under the marker, detached from its number
@@ -63,7 +132,10 @@ export function Question({ request, selectedIndex, typing, width, rows = process
63
132
  const HANG = '› 1. '.length;
64
133
  // Everything the dialog draws, pre-wrapped and fitted to the viewport, plus the height it comes to.
65
134
  // App calls it too, so the input underneath knows how much room the dialog leaves it.
66
- export function layoutQuestion(request, typing, cols, rows, reservedRows) {
135
+ export function layoutQuestion(request, typing, cols, rows, reservedRows,
136
+ // Which row the cursor is on, so the option window on a short pane follows it. The own-answer row
137
+ // is index `options.length`.
138
+ selectedIndex = 0) {
67
139
  const hang = HANG;
68
140
  const noting = typing && typing.forIndex !== undefined ? request.options[typing.forIndex] : null;
69
141
  const labels = request.options.map(o => {
@@ -81,13 +153,70 @@ export function layoutQuestion(request, typing, cols, rows, reservedRows) {
81
153
  : labels.reduce((n, l) => n + rowsOf(l.wrapped), 0) + rowsOf(ownAnswer);
82
154
  const descriptionRows = typing ? 0 : descriptions.reduce((n, d) => n + (d ? rowsOf(d) : 0), 0);
83
155
  const below = BELOW_DIALOG_ROWS + (typing ? TYPING_INPUT_ROWS : 0);
84
- const fit = fitQuestionToHeight(questionLines.length, labelRows, descriptionRows, rows - DIALOG_FIXED_ROWS - below - reservedRows);
85
- const hiddenQuestionRows = questionLines.length - fit.questionRows;
86
- const height = DIALOG_FIXED_ROWS +
87
- fit.questionRows +
88
- (hiddenQuestionRows > 0 ? 1 : 0) +
156
+ // Pre-wrapped, like the labels: the rows counted here are then the rows drawn at any width the
157
+ // frame is laid out in, not just the one this happened to measure at.
158
+ const hint = hangingWrap(typing ? QUESTION_TYPING_HINT : QUESTION_HINT, Math.max(1, cols), 0);
159
+ const hintRows = HINT_GAP_ROWS + hint.split('\n').length;
160
+ // Everything that does not depend on the question: the frame, the header and the margins.
161
+ const chrome = FRAME_ROWS + LABEL_ROWS + GAP_ROWS;
162
+ const fixed = chrome + hintRows;
163
+ // `rows - 1`: Ink repaints the whole terminal once the frame is AT LEAST as tall as the viewport
164
+ // (build/ink.js), so a budget that lands exactly on `rows` still clears the scrollback.
165
+ const budget = (fixedRows) => rows - 1 - fixedRows - below - reservedRows;
166
+ const fitAt = (fixedRows) => fitQuestionToHeight(questionLines.length, labelRows, descriptionRows, budget(fixedRows));
167
+ let fit = fitAt(fixed);
168
+ let showHint = true;
169
+ // On a pane too short for the whole dialog, the HINT is what goes before the question is cut:
170
+ // the options are what the user acts on and the question is what they are answering, while the
171
+ // hint is keyboard help they learn once. It goes when dropping it shows the question whole, and
172
+ // also when the frame overflows with it: `fitQuestionToHeight` keeps a question row and its note
173
+ // past the budget, and keeping the hint there spends the scrollback on keyboard help.
174
+ const cut = (f) => f.questionRows < questionLines.length || (!f.showDescriptions && descriptionRows > 0);
175
+ const heightOf = (f, fixedRows) => fixedRows +
176
+ f.questionRows +
177
+ (f.questionRows < questionLines.length ? 1 : 0) +
89
178
  labelRows +
90
- (fit.showDescriptions ? descriptionRows : 0);
179
+ (f.showDescriptions ? descriptionRows : 0);
180
+ if (cut(fit)) {
181
+ const without = fitAt(chrome);
182
+ if (!cut(without) || heightOf(fit, fixed) > budget(0)) {
183
+ showHint = false;
184
+ fit = without;
185
+ }
186
+ }
187
+ const hiddenQuestionRows = questionLines.length - fit.questionRows;
188
+ const fixedRows = showHint ? fixed : chrome;
189
+ // What is left for the options once the fixed rows, the question and its note have taken theirs.
190
+ // The own-answer row is always drawn, so it comes off the budget before the window is picked —
191
+ // what is left is the option rows (descriptions included) plus their markers.
192
+ const optionBudget = rows -
193
+ 1 -
194
+ fixedRows -
195
+ below -
196
+ reservedRows -
197
+ fit.questionRows -
198
+ (hiddenQuestionRows > 0 ? 1 : 0) -
199
+ rowsOf(ownAnswer);
200
+ const optionCosts = labels.map((l, i) => {
201
+ const d = fit.showDescriptions ? descriptions[i] : null;
202
+ return rowsOf(l.wrapped) + (d ? rowsOf(d) : 0);
203
+ });
204
+ const options = typing ? null : fitOptionsToHeight(optionCosts, optionBudget, selectedIndex);
205
+ // A windowed list is padded to the tallest window any cursor position gives (capped at the
206
+ // budget), or the dialog — and the input App sizes under it — grew and shrank by a row as the
207
+ // user arrowed past labels that wrap to different heights. A whole list never moves.
208
+ let padRows = 0;
209
+ if (options && options.moreAbove + options.moreBelow > 0) {
210
+ let steady = 0;
211
+ for (let i = 0; i <= request.options.length; i++) {
212
+ steady = Math.max(steady, fitOptionsToHeight(optionCosts, optionBudget, i).rows);
213
+ }
214
+ padRows = Math.max(0, Math.min(steady, optionBudget) - options.rows);
215
+ }
216
+ // `options.rows` already carries the descriptions of the options on show, and while typing the
217
+ // list is replaced by the prompt line, so neither term is added again here.
218
+ const optionRows = typing || !options ? labelRows : options.rows + padRows + rowsOf(ownAnswer);
219
+ const height = fixedRows + fit.questionRows + (hiddenQuestionRows > 0 ? 1 : 0) + optionRows;
91
220
  return {
92
221
  labels,
93
222
  descriptions,
@@ -97,9 +226,13 @@ export function layoutQuestion(request, typing, cols, rows, reservedRows) {
97
226
  fit,
98
227
  hiddenQuestionRows,
99
228
  height,
229
+ hint,
230
+ showHint,
231
+ options,
232
+ padRows,
100
233
  };
101
234
  }
102
235
  // The dialog's height at the live terminal size, for the input underneath it.
103
- export function questionDialogHeight(request, typing, reservedRows) {
104
- return layoutQuestion(request, typing, contentWidth(DIALOG_CHROME), process.stdout.rows || 24, reservedRows).height;
236
+ export function questionDialogHeight(request, typing, reservedRows, selectedIndex = 0) {
237
+ return layoutQuestion(request, typing, contentWidth(DIALOG_CHROME), process.stdout.rows || 24, reservedRows, selectedIndex).height;
105
238
  }
@@ -22,8 +22,9 @@ export function ResumeSelect({ entries, selectedIndex, heading, }) {
22
22
  const selected = start + i === selectedIndex;
23
23
  const when = formatSavedAt(e.savedAt, now).padEnd(whenWidth);
24
24
  const label = e.title ?? '(untitled)';
25
- // The model is what tells apart two sessions opened with the same prompt.
26
- const tail = ` ${e.messageCount} msgs${e.model ? ` · ${e.model}` : ''}`;
25
+ // The model is what tells apart two sessions opened with the same prompt; `chat` marks a
26
+ // session holding a chat (#875), which otherwise reads like any other.
27
+ const tail = ` ${e.messageCount} msgs${e.chat ? ' · chat' : ''}${e.model ? ` · ${e.model}` : ''}`;
27
28
  const budget = Math.max(10, maxDisplay - when.length - tail.length - 2);
28
29
  // One Text with nested runs: on wrap Ink drops the char at a sibling boundary.
29
30
  return (_jsxs(Text, { children: [_jsx(Text, { color: selected ? theme.accent : undefined, children: selected ? '› ' : ' ' }), _jsx(Text, { color: theme.muted, children: `${when} ` }), _jsx(Text, { color: selected ? theme.accent : undefined, children: truncate(label, budget) }), _jsx(Text, { color: theme.muted, children: tail })] }, e.path));
package/dist/ui/Status.js CHANGED
@@ -6,8 +6,25 @@ import { supportsHyperlink } from 'supports-hyperlinks';
6
6
  import { theme } from './theme.js';
7
7
  import { contextFill, formatElapsed, formatShrink, formatTokensPerSecond, kFormat, } from './format.js';
8
8
  import { useContentWidth } from './layout.js';
9
- export function Status({ model, turns, status, elapsed, usage, contextTokens, contextWindow, contextUsable, sheds, folds, cachedTokens, decodeRate, pr, autoApprove, unattended, modeTag, exitArmed, }) {
9
+ // Rows the status bar takes at `width` — App budgets the live region with it, since a narrow
10
+ // pane wraps the bar onto several rows and an unbudgeted frame reaches the viewport height.
11
+ // A chip wider than the pane gets a line of its own that Ink hard-wraps, so it counts its rows.
12
+ export function statusRows(props, width) {
13
+ return packChips(statusChips(props), width).reduce((n, line) => {
14
+ const w = line.reduce((sum, chip) => sum + chipWidth(chip), 0) + SEP.length * (line.length - 1);
15
+ return n + Math.max(1, Math.ceil(w / Math.max(1, width)));
16
+ }, 0);
17
+ }
18
+ export function Status(props) {
10
19
  const width = useContentWidth();
20
+ // One <Text> per packed line, chips as nested runs rather than siblings: a row Box of sibling
21
+ // <Text>s hands each its own column when the row overflows, and every chip wraps in place into
22
+ // a stack of two-to-four-character shards (#295). Packing here is what decides where the line
23
+ // breaks; Ink's own wrap only ever sees a line that already fits, except for a single chip
24
+ // wider than the terminal, which it hard-wraps as a last resort.
25
+ return (_jsx(Box, { flexDirection: "column", children: packChips(statusChips(props), width).map((line, i) => (_jsx(Text, { children: line.map((chip, j) => (_jsxs(Fragment, { children: [j > 0 ? _jsx(Text, { color: theme.muted, children: SEP }) : null, chip.map((seg, k) => (_jsx(Text, { color: seg.color, underline: seg.underline, children: seg.text }, k)))] }, j))) }, i))) }));
26
+ }
27
+ export function statusChips({ model, turns, status, elapsed, usage, contextTokens, contextWindow, contextUsable, sheds, folds, cachedTokens, decodeRate, pr, autoApprove, unattended, modeTag, exitArmed, }) {
11
28
  const busy = elapsed !== null;
12
29
  const timer = busy ? ` · ${formatElapsed(elapsed)}` : '';
13
30
  const keys = busy ? 'ctrl-c to abort' : 'ctrl-c to exit';
@@ -68,12 +85,7 @@ export function Status({ model, turns, status, elapsed, usage, contextTokens, co
68
85
  chips.push(exitArmed
69
86
  ? [{ text: 'press ctrl-c again to exit', color: theme.tool }]
70
87
  : [{ text: keys, color: theme.muted }]);
71
- // One <Text> per packed line, chips as nested runs rather than siblings: a row Box of sibling
72
- // <Text>s hands each its own column when the row overflows, and every chip wraps in place into
73
- // a stack of two-to-four-character shards (#295). Packing here is what decides where the line
74
- // breaks; Ink's own wrap only ever sees a line that already fits, except for a single chip
75
- // wider than the terminal, which it hard-wraps as a last resort.
76
- return (_jsx(Box, { flexDirection: "column", children: packChips(chips, width).map((line, i) => (_jsx(Text, { children: line.map((chip, j) => (_jsxs(Fragment, { children: [j > 0 ? _jsx(Text, { color: theme.muted, children: SEP }) : null, chip.map((seg, k) => (_jsx(Text, { color: seg.color, underline: seg.underline, children: seg.text }, k)))] }, j))) }, i))) }));
88
+ return chips;
77
89
  }
78
90
  const SEP = ' · ';
79
91
  function muted(text) {
@@ -122,7 +122,7 @@ export const COMMANDS = [
122
122
  },
123
123
  {
124
124
  name: 'resume',
125
- desc: 'resume a saved session — this project auto-saves as you go (root: the /save files)',
125
+ desc: 'resume a saved session — this project auto-saves as you go (chat mode: chats; all; root: the /save files)',
126
126
  },
127
127
  { name: 'exit', desc: 'exit Reika' },
128
128
  { name: 'quit', desc: 'alias of /exit' },
@@ -0,0 +1,38 @@
1
+ // The dialogs' rows and specs, apart from the Ink components that draw them: headless asks the
2
+ // same questions on a terminal line (#872) and must not load Ink to do it.
3
+ // The last row declines with a reason the user types into the input box below. Last, not beside
4
+ // Decline, so the rows Approval-trained fingers already know keep their places.
5
+ export const APPROVAL_OPTIONS = [
6
+ 'Approve',
7
+ 'Decline',
8
+ 'Always (this session)',
9
+ 'Decline, and say what to do instead',
10
+ ];
11
+ export const APPROVAL_FEEDBACK_INDEX = 3;
12
+ // Row 0 is "send as typed" and starts selected — the inverse of Approval, where Approve is row 0.
13
+ // There the model has already committed to an action; here nothing has happened yet and the
14
+ // literal prompt is what was asked for. A wrong default that acts costs a turn (or a request
15
+ // nobody meant); a wrong default that doesn't costs a keystroke.
16
+ export const CONFIRM_DECLINE = 0;
17
+ export const CONFIRM_ACCEPT = 1;
18
+ export function skillConfirmSpec(match) {
19
+ return {
20
+ title: 'Skill',
21
+ subtitle: `/${match.skill.name} — ${match.skill.description}`,
22
+ details: [`matched: ${match.matched.join(', ')}`],
23
+ options: ['Send as typed', `Apply /${match.skill.name}`],
24
+ accept: 'apply',
25
+ };
26
+ }
27
+ // A long URL wraps the frame; the user just typed it, so the head is enough to recognize it.
28
+ const URL_DISPLAY_CHARS = 90;
29
+ export function pastedUrlConfirmSpec(urls) {
30
+ const n = urls.length;
31
+ return {
32
+ title: n > 1 ? 'Pasted links' : 'Pasted link',
33
+ subtitle: `the prompt doesn't read as a request to open ${n > 1 ? 'them' : 'it'} — fetch before the turn?`,
34
+ details: urls.map(u => u.length > URL_DISPLAY_CHARS ? `${u.slice(0, URL_DISPLAY_CHARS)}…` : u),
35
+ options: ['Send as typed', `Fetch ${n > 1 ? `${n} links` : 'the link'}`],
36
+ accept: 'fetch',
37
+ };
38
+ }
package/dist/ui/layout.js CHANGED
@@ -32,6 +32,124 @@ export function useContentWidth(indent = 0) {
32
32
  }, [indent]);
33
33
  return width;
34
34
  }
35
+ // Display rows `text` takes at `width` columns — the unit Ink measures a frame in when it decides
36
+ // the frame is as tall as the viewport. Wrapped with the exact options Ink wraps with
37
+ // (build/wrap-text.js), so a row count measured here is the row count that gets drawn.
38
+ export function wrappedRows(text, width) {
39
+ return wrapAnsi(text, Math.max(1, width), { trim: false, hard: true }).split('\n').length;
40
+ }
41
+ // Wrap styled text into rows that each carry every style active where they start (#852).
42
+ //
43
+ // wrap-ansi re-opens only ONE code at a break — the last it saw — so stacked styles lose all but
44
+ // the innermost: a comment is gray then italic, and its continuation rows came back italic in the
45
+ // default foreground; a changed word in a diff is a background then a foreground, and lost its
46
+ // highlight the same way. So the state at each row's end is replayed at the next row's start, and
47
+ // closed at the row's end so a row never leaks a style into whatever Ink draws after it. Same
48
+ // options as Ink's own wrap, so the break points and row count are unchanged.
49
+ export function wrapStyledRows(text, width) {
50
+ const rows = wrapAnsi(text, Math.max(1, width), { trim: false, hard: true }).split('\n');
51
+ let open = new Map();
52
+ return rows.map(row => {
53
+ const lead = [...open.values()].join('');
54
+ open = sgrStateAfter(row, open);
55
+ const close = [...open.keys()].map(slot => SGR_CLOSE[slot]).join('');
56
+ return lead + row + close;
57
+ });
58
+ }
59
+ // The styled text whose plain characters are `[start, end)`, opening with the styles active at
60
+ // `start` and closing what is still open at `end`, so the slice stands on its own. Lets a caller
61
+ // style a whole line in one pass and cut it afterwards: a fragment styled alone loses its context,
62
+ // as a run of words from the middle of a comment does without the `//` that made it one (#852).
63
+ export function sliceStyled(text, start, end) {
64
+ const sgr = /\x1b\[[0-9;]*m/y;
65
+ let open = new Map();
66
+ let out = '';
67
+ let plain = 0;
68
+ let i = 0;
69
+ while (i < text.length && plain < end) {
70
+ sgr.lastIndex = i;
71
+ const code = sgr.exec(text);
72
+ if (code) {
73
+ if (plain < start)
74
+ open = sgrStateAfter(code[0], open);
75
+ else
76
+ out += code[0];
77
+ i += code[0].length;
78
+ continue;
79
+ }
80
+ if (plain === start)
81
+ out = [...open.values()].join('') + out;
82
+ if (plain >= start)
83
+ out += text[i];
84
+ plain++;
85
+ i++;
86
+ }
87
+ const after = sgrStateAfter(out, new Map());
88
+ return out + [...after.keys()].map(slot => SGR_CLOSE[slot]).join('');
89
+ }
90
+ const SGR_CLOSE = {
91
+ fg: '\x1b[39m',
92
+ bg: '\x1b[49m',
93
+ weight: '\x1b[22m',
94
+ italic: '\x1b[23m',
95
+ underline: '\x1b[24m',
96
+ inverse: '\x1b[27m',
97
+ strike: '\x1b[29m',
98
+ };
99
+ const SIMPLE_SLOTS = {
100
+ 1: ['weight', true],
101
+ 2: ['weight', true],
102
+ 3: ['italic', true],
103
+ 4: ['underline', true],
104
+ 7: ['inverse', true],
105
+ 9: ['strike', true],
106
+ 22: ['weight', false],
107
+ 23: ['italic', false],
108
+ 24: ['underline', false],
109
+ 27: ['inverse', false],
110
+ 29: ['strike', false],
111
+ 39: ['fg', false],
112
+ 49: ['bg', false],
113
+ };
114
+ // Which styles are open after `row`, starting from `before`. Each open slot holds the sequence that
115
+ // re-opens it; a compound sequence (`38;2;r;g;b`) is split into its own per-slot sequence.
116
+ function sgrStateAfter(row, before) {
117
+ const state = new Map(before);
118
+ for (const match of row.matchAll(/\x1b\[([0-9;]*)m/g)) {
119
+ const params = match[1] === '' ? [0] : match[1].split(';').map(Number);
120
+ for (let i = 0; i < params.length; i++) {
121
+ const p = params[i];
122
+ if (p === 0) {
123
+ state.clear();
124
+ }
125
+ else if (p === 38 || p === 48) {
126
+ // 38;5;n and 38;2;r;g;b carry their color in the params that follow.
127
+ const span = params[i + 1] === 5 ? 2 : params[i + 1] === 2 ? 4 : 0;
128
+ const code = params.slice(i, i + 1 + span).join(';');
129
+ state.set(p === 38 ? 'fg' : 'bg', `\x1b[${code}m`);
130
+ i += span;
131
+ }
132
+ else if ((p >= 30 && p <= 37) || (p >= 90 && p <= 97)) {
133
+ state.set('fg', `\x1b[${p}m`);
134
+ }
135
+ else if ((p >= 40 && p <= 47) || (p >= 100 && p <= 107)) {
136
+ state.set('bg', `\x1b[${p}m`);
137
+ }
138
+ else if (SIMPLE_SLOTS[p]) {
139
+ const [slot, opens] = SIMPLE_SLOTS[p];
140
+ if (opens)
141
+ state.set(slot, `\x1b[${p}m`);
142
+ else
143
+ state.delete(slot);
144
+ }
145
+ }
146
+ }
147
+ return state;
148
+ }
149
+ // `hangingWrap`'s row count for the same text at the same width.
150
+ export function hangingRows(text, width, hang) {
151
+ return hangingWrap(text, width, hang).split('\n').length;
152
+ }
35
153
  // Wrap `text` so that a marker-prefixed line (" ↳ Ran: …", "$ …", "⏺︎ Bash(…)") keeps a HANGING
36
154
  // INDENT: every row after the first lands under the text, not back at column 0.
37
155
  //
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alexwkleung/reika",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "Coding agent CLI for local and hosted models, designed around small local models first.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Alex Leung",
File without changes