@hncode/hncode 0.7.8 → 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.
package/src/animate.js ADDED
@@ -0,0 +1,371 @@
1
+ // The travelling-light animation, and the spinner that goes with it.
2
+ //
3
+ // Everything here is geometry: a phase in milliseconds becomes a brightness per character. No module here knows what
4
+ // a transcript is, which is what lets the same sweep drive the Working row and a pending tool row without the two
5
+ // drifting apart — they were once two hand-written copies of the same loop, and one of them stepped at a different
6
+ // rate until its light never finished a round.
7
+
8
+ import { lerpColor } from './colors.js';
9
+ import { col } from './text.js';
10
+
11
+ // Braille spinner frames for the "Working" indicator (orange).
12
+ export const SPINNER = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
13
+
14
+ // The REDUCED-MOTION spinner: a single dot that breathes on a slow cycle rather than rotating a glyph. A fully static
15
+ // glyph reads as "hung", so the slow brightness change is what says "still working" without any motion. Two seconds
16
+ // is slow enough not to draw the eye.
17
+ export const REDUCED_MOTION_DOT = '●';
18
+ export const REDUCED_MOTION_CYCLE_MS = 2000;
19
+
20
+ // Stand-in for the LIVE spinner glyph inside a CACHED row. A pending thinking block must not be re-wrapped by the
21
+ // spin tick, so its preview is cached with this sentinel and the real frame is substituted afterwards. It occupies
22
+ // zero columns, so the swap never disturbs the layout.
23
+ export const SPIN_PLACEHOLDER = '\u0000';
24
+
25
+ /** Is reduced motion on for this session? Read from the state, or the env override. */
26
+ export function reducedMotionOn(state) {
27
+ if (!state) return false;
28
+ if (state.reducedMotion !== undefined) return !!state.reducedMotion;
29
+ const env = process.env.HNCODE_REDUCED_MOTION;
30
+ if (env !== undefined) return /^(1|true|yes|on)$/i.test(env);
31
+ return !!(state.cfg && state.cfg.reducedMotion);
32
+ }
33
+
34
+ /**
35
+ * The frames a SPINNER-style animation shows: { glyph, dim }.
36
+ *
37
+ * In normal mode the glyph rotates and is never dim. In reduced motion the glyph is a constant dot whose brightness
38
+ * flips once per second. Returning both pieces means every caller — the Working row, a pending tool, a thinking
39
+ * preview — gets the same treatment from one place.
40
+ */
41
+ export function spinnerFrame(state, tick) {
42
+ if (reducedMotionOn(state)) {
43
+ const t = tick !== undefined ? tick : (state && state.spin) || 0;
44
+ return { glyph: REDUCED_MOTION_DOT, dim: Math.floor(t / (REDUCED_MOTION_CYCLE_MS / 80)) % 2 === 1 };
45
+ }
46
+ const n = SPINNER.length;
47
+ const i = ((tick !== undefined ? tick : (state && state.spin) || 0) % n + n) % n;
48
+ return { glyph: SPINNER[i], dim: false };
49
+ }
50
+
51
+ /**
52
+ * A sweep that SETTLES: a character the band has passed stays at 1.
53
+ *
54
+ * The shape the Working row's colour phase needs, and two earlier attempts got it wrong by reusing a travelling
55
+ * PULSE: a ramp DOWN as the head passes makes a character light up and then go dark again, so the phrase never
56
+ * becomes orange at all.
57
+ *
58
+ * The convention, stated once:
59
+ *
60
+ * `dist >= 0` the band is past this character -> 1 (settled)
61
+ * `-half < dist < 0` the band is on it -> ramp 0 -> 1
62
+ * `dist <= -half` not reached yet -> 0
63
+ *
64
+ * `dist` is `head - position`, so a LARGER `dist` means "further behind the head". `edge` shapes only the transition:
65
+ * `cosine` keeps both ends gentle, `linear` is sharpest at the settle point.
66
+ */
67
+ export function sweepSettle(dist, half, edge = 'cosine') {
68
+ const h = Math.max(1e-6, half);
69
+ if (dist >= 0) return 1; // passed: stays lit
70
+ if (dist <= -h) return 0; // not yet reached
71
+ const x = (dist + h) / h; // 0 at the far edge, 1 at the settle point
72
+ return edge === 'linear' ? x : 0.5 * (1 - Math.cos(Math.PI * x));
73
+ }
74
+
75
+ /**
76
+ * A sweep that PASSES: a character lights up under the band and returns to 0 after it.
77
+ *
78
+ * The counterpart to `sweepSettle`, and the difference is the whole point:
79
+ *
80
+ * sweepSettle a character the band has passed STAYS at 1 — paint being laid down
81
+ * sweepPulse a character returns to 0 once the band leaves — a light moving over
82
+ *
83
+ * `half` is the HALF-width of the light, so `2 * half` is its full width, and `flat` is the half-width of its FULLY
84
+ * LIT CORE:
85
+ *
86
+ * |dist| <= flat the core, at 1
87
+ * flat < |dist| < half a shoulder, falling from 1 to 0
88
+ *
89
+ * Both outer ends reach 0, which is what makes the light arrive and leave without a seam. `flat = 0` ramps across
90
+ * the whole width leaving a single bright point; `flat = half` is a solid block with no fade.
91
+ */
92
+ export function sweepPulse(dist, half, edge = 'cosine', flat = 0) {
93
+ const h = Math.max(1e-6, half);
94
+ if (dist <= -h || dist >= h) return 0; // outside the light
95
+ const core = Math.max(0, Math.min(h, flat));
96
+ const a = Math.abs(dist);
97
+ if (a <= core) return 1;
98
+ const x = (a - core) / (h - core); // 0 where the core ends, 1 at the outer edge
99
+ if (edge === 'linear') return 1 - x;
100
+ return 0.5 * (1 + Math.cos(Math.PI * x)); // raised cosine from 1 down to 0
101
+ }
102
+
103
+ /**
104
+ * The light's CORE width as a fraction of the row.
105
+ *
106
+ * Claude Code's shimmer has no core at all — a single index is bright. A glint is a point travelling along the row,
107
+ * not a wash sweeping over it.
108
+ */
109
+ export const LIGHT_FRACTION = 1 / 4;
110
+
111
+ /** Milliseconds per unit of `state.spin`. The spinner advances every 80ms, so a caller holding a tick count needs
112
+ * this to convert — named here so the timer and the geometry cannot drift apart. */
113
+ export const SPIN_TICK_MS = 80;
114
+
115
+ /**
116
+ * The light's FULLY LIT CORE, in characters: a quarter of the row, rounded down.
117
+ *
118
+ * Rounding down is deliberate: `Working...` is ten characters, so its core is two. A fractional width is something
119
+ * no terminal draws. The floor of 2 keeps a short row visible — a one-character core with a fade either side barely
120
+ * registers.
121
+ *
122
+ * This is the core, NOT the total extent: `TAIL_CHARS` of fade is added either side.
123
+ */
124
+ export function lightWidth(n) {
125
+ return Math.max(2, Math.floor(n * LIGHT_FRACTION));
126
+ }
127
+
128
+ /** The fade either side of the core, in characters. Two, not one: a band of one character is wide enough in
129
+ * truecolor but vanishes under 256 colours, where a single lit cell is a blink. */
130
+ export const TAIL_CHARS = 4;
131
+
132
+ /**
133
+ * The light's half-width, INCLUDING the fade. This is the extent `lightAt` sweeps.
134
+ *
135
+ * THE TAILS ARE CAPPED so the light stays narrower than the row: the total is held to `n - 1`, which keeps at least
136
+ * one dark column at each end. Those dark columns are what make the light read as an object with edges instead of as
137
+ * a row that brightens and dims.
138
+ *
139
+ * The CORE gives way first — `coreHalf` shrinks with the cap — because the fade is what makes the light arrive and
140
+ * leave smoothly, and a short row needs that more than a wide middle.
141
+ */
142
+ function totalHalf(n) {
143
+ const want = lightWidth(n) + 2 * TAIL_CHARS;
144
+ const capped = Math.min(want, Math.max(2, n - 1));
145
+ return capped / 2;
146
+ }
147
+
148
+ /** The half-width of the fully lit core, for `sweepPulse`'s `flat` parameter. */
149
+ function coreHalf(n) {
150
+ return Math.min(lightWidth(n), totalHalf(n) * 2) / 2;
151
+ }
152
+
153
+ /** The animation's frame rate: 30fps, the whole program's rate for animated rows. */
154
+ export const ANIM_FPS = 30;
155
+ export const FRAME_MS = 1000 / ANIM_FPS;
156
+
157
+ /**
158
+ * How long one step of the light lasts, in milliseconds.
159
+ *
160
+ * FIXED, rather than following the output rate. That was tried and dropped: a model writing slowly got a sweep so
161
+ * slow it looked stuck, a fast one got a blur, and the same row changed pace between turns for no reason the reader
162
+ * could see. One rate is calmer and predictable, which is what an ambient indicator needs to be.
163
+ */
164
+ export const STEP_MS = 65;
165
+
166
+ /**
167
+ * The step for a TOOL name, slower than the Working row's.
168
+ *
169
+ * A tool name is short — `Read` is four characters — so at the Working row's rate the light crosses it quickly and
170
+ * the row is dark for the rest of the cycle, which reads as a single flash rather than as movement.
171
+ */
172
+ export const TOOL_STEP_MS = 150;
173
+
174
+ /**
175
+ * How far outside the row the light starts and ends, in characters.
176
+ *
177
+ * TEN, exactly as Claude Code's `messageWidth + 20` splits into ten either side. This is what sets the pace of a
178
+ * round: a 10-character row travels 30 cells, so a round is 1500ms. A shorter margin made the sweep finish sooner and
179
+ * read as a twitch. It must not be shorter than the light's own half-width either, or the light would still be
180
+ * lighting the last characters when the round ended; `lightMargin` takes the larger of the two.
181
+ */
182
+ export const ENTRY_EXIT_CHARS = 10;
183
+
184
+ /**
185
+ * The margin for a row of `n` characters: the target ten, or the light's half-width if that is larger — but CAPPED so
186
+ * the light reaches the text in reasonable time.
187
+ *
188
+ * Ten cells either side is what makes the timing match on a long row. On a SHORT row it is most of the cycle: `Edit`
189
+ * is four characters, so the light spends its first several steps still outside the text, showing nothing. A row that
190
+ * looks frozen and then blinks once reads as broken.
191
+ */
192
+ export function lightMargin(n) {
193
+ const half = totalHalf(Math.max(1, n));
194
+ return Math.max(1, Math.min(ENTRY_EXIT_CHARS, Math.max(half, Math.ceil(Math.max(1, n) / 4))));
195
+ }
196
+
197
+ /**
198
+ * The crossing time for a row of `count` characters — ONE FULL ROUND, entry and exit included.
199
+ *
200
+ * `SWEEP_TICKS` IS THE RESOLUTION KNOB. At a lower value a ten-character row crossed in too few frames, and the light
201
+ * traversed its own band in a third of that, so each glyph took only a handful of distinct brightness values and the
202
+ * fade read as a step. Every doubling of the tick count doubles the frames each glyph is under the light, which is
203
+ * the only way to make the fade finer without changing its shape or its speed across the row.
204
+ */
205
+ export function crossMs(count, stepMs = STEP_MS) {
206
+ const cells = Math.max(1, count) + 2 * lightMargin(count);
207
+ return cells * stepMs * (SWEEP_TICKS / 10);
208
+ }
209
+
210
+ /**
211
+ * The rest between rounds, in milliseconds.
212
+ *
213
+ * NOT zero. With `REST_MS = 0` the sweep wrapped straight back to the start the instant it left the right edge, so
214
+ * the row went from "light on the last letter" to "light on nothing" to "light on the first letter" within two frames
215
+ * — which reads as the animation resetting rather than restarting.
216
+ */
217
+ export const REST_MS = 300;
218
+
219
+ /** The full cycle for a row: one crossing, then the rest. `count` enters into it, because a longer row has more
220
+ * characters to light. */
221
+ export function cycleMs(count, stepMs = STEP_MS) {
222
+ return crossMs(count, stepMs) + REST_MS;
223
+ }
224
+
225
+ /**
226
+ * The wall-clock time the light's animation began, for a row anchored at this tick.
227
+ *
228
+ * `spin` advances every SPIN_TICK_MS while the render path redraws far more often, so a phase taken straight from the
229
+ * tick count steps in 80ms jumps. Converting the anchor ONCE to a wall-clock origin lets every later frame measure
230
+ * real elapsed time instead.
231
+ *
232
+ * The store is MODULE-LEVEL, and deliberately not a field on `state`: the caller for a pending tool row is
233
+ * `formatToolLine`, which has no access to `state`, and reading it there threw "state is not defined" and took the
234
+ * whole TUI down through the unhandledRejection handler. The key is the anchor tick, so a new turn gets a new origin.
235
+ */
236
+ const lightOrigins = new Map();
237
+
238
+ /**
239
+ * @param {string} key identifies the animation — `tool:12`, `work:12` — so two rows anchored on the same tick
240
+ * keep separate origins.
241
+ * @param {number} anchor the tick the animation began on.
242
+ * @param {number} now the tick it is being drawn at.
243
+ *
244
+ * `key` and `anchor` are separate arguments on purpose. An earlier version took only the anchor and derived the key
245
+ * from it, so a caller passing an already-prefixed `tool:0` produced `(0 - 'tool:0') * 80` — arithmetic on a string,
246
+ * which is NaN. The origin became NaN, every colour became an invalid escape, and the terminal drew the row in the
247
+ * default colour: a silent failure that looked like the animation simply not running.
248
+ */
249
+ export function lightOrigin(key, anchor, now) {
250
+ let origin = lightOrigins.get(key);
251
+ if (origin === undefined) {
252
+ // THE ORIGIN IS "NOW", NOT BACK-DATED FROM THE TICK COUNT.
253
+ //
254
+ // Back-dating picked up the phase the anchor implied, but the first frame a row is DRAWN is not the tick its
255
+ // anchor was set on — the start animation runs first, several ticks earlier. That made the sweep begin part-way
256
+ // across, so the light appeared to jump forward and then restart from the left.
257
+ //
258
+ // `anchor` and `now` stay in the signature because callers pass them and the shape is part of the contract.
259
+ void anchor;
260
+ void now;
261
+ origin = Date.now();
262
+ if (!Number.isFinite(origin)) origin = Date.now();
263
+ // EVICT THE OLDEST, never clear the map. Clearing dropped the origin of the row currently on screen, which was
264
+ // then recreated with a fresh timestamp — the light restarted from the left edge roughly once a second.
265
+ if (lightOrigins.size > 64) {
266
+ const oldest = lightOrigins.keys().next().value;
267
+ lightOrigins.delete(oldest);
268
+ }
269
+ lightOrigins.set(key, origin);
270
+ }
271
+ return origin;
272
+ }
273
+
274
+ /**
275
+ * How lit one character is, given its index and the row length.
276
+ *
277
+ * Returns 0..1. The position arrives as an INDEX and the row length rather than a pre-divided fraction, because the
278
+ * light's width is itself a fraction of the row — both are then in the same unit of "characters", so the light cannot
279
+ * be scaled twice by accident.
280
+ *
281
+ * `phaseMs` is MILLISECONDS within the cycle, not a tick count. Time is the right unit because the light's smoothness
282
+ * depends on how far it moves per RENDERED frame, and the frame rate is not the caller's spinner tick. Stepping by
283
+ * that tick forced a many-second crossing on a long row.
284
+ */
285
+ export function lightAt(phaseMs, index, count, edge = 'cosine', stepMs = STEP_MS) {
286
+ const n = Math.max(1, count);
287
+ // `half` is the OUTER edge (core plus the fade either side) and `core` is the part that stays at full brightness.
288
+ const half = totalHalf(n);
289
+ const core = coreHalf(n);
290
+ // The character's centre. Measuring against the left edge would make the light peak BETWEEN characters, so each
291
+ // would flash at less than full strength.
292
+ const centre = index + 0.5;
293
+ // The centre crosses from fully off the left of the row to fully off its right, so the light slides in and out
294
+ // rather than popping into existence on the first character.
295
+ //
296
+ // THE REST HALF NEEDS NO SPECIAL CASE. Past the crossing the progress exceeds 1 and the head travels further past
297
+ // the row's right edge — where `sweepPulse` is already 0 — so the light is dark by the same arithmetic that makes it
298
+ // leave.
299
+ const margin = lightMargin(n);
300
+ const travel = n + 2 * margin;
301
+ // THE HEAD IS CONTINUOUS, NOT QUANTISED TO WHOLE STEPS. Rounding here made a ten-character row offer the light
302
+ // about twenty distinct positions, so each glyph saw a handful of brightness values — a visible step ramp. The
303
+ // position is a FLOAT: the pulse is already continuous in `dist`, so every frame lands the light somewhere between
304
+ // two cells and the fade is as fine as the frame rate allows.
305
+ const progress = Math.max(0, Math.min(1, phaseMs / crossMs(n, stepMs)));
306
+ const head = (-margin + progress * travel) * STEP_CHARS;
307
+ // `edge` shapes the shoulder: a raised cosine leaves its outer end gentle, a linear one is sharpest where it meets
308
+ // the core. It arrives as a PARAMETER rather than being read from config, because this is a module-level function
309
+ // and the TUI state lives in a closure — the trap that once made a pending tool row throw and take the TUI down.
310
+ return sweepPulse(head - centre, half, edge, core);
311
+ }
312
+
313
+ /**
314
+ * Paint `text` with the travelling light already mixed into each glyph.
315
+ *
316
+ * ONE FUNCTION FOR BOTH ANIMATED ROWS — the Working row and a pending tool's "Using <Tool>" — because they were two
317
+ * hand-written copies of the same loop. That is how they drifted: one stepped at a different rate inside a different
318
+ * cycle length, and the slow one could not finish a round before its own modulus wrapped.
319
+ *
320
+ * Everything about the light is decided here — the rate, the shoulder shape, the band width — so a change lands on
321
+ * both rows at once.
322
+ *
323
+ * @param {string} text the row's text
324
+ * @param {number} phaseMs milliseconds into the cycle
325
+ * @param {number[]} base resting colour, [r, g, b]
326
+ * @param {number[]} glint the colour the light lifts the text toward
327
+ * @param {string} edge shoulder shape: 'cosine' (default) or 'linear'
328
+ * @returns {string} ANSI, ready to splice into a row
329
+ */
330
+ export function shimmerText(text, phaseMs, base, glint, edge = 'cosine', stepMs = STEP_MS) {
331
+ const s = String(text == null ? '' : text);
332
+ const n = s.length;
333
+ if (!n) return '';
334
+ const out = [];
335
+ for (let i = 0; i < n; i++) {
336
+ const t = Math.max(0, Math.min(1, lightAt(phaseMs, i, n, edge, stepMs)));
337
+ const r = Math.round(base[0] + (glint[0] - base[0]) * t);
338
+ const g = Math.round(base[1] + (glint[1] - base[1]) * t);
339
+ const b = Math.round(base[2] + (glint[2] - base[2]) * t);
340
+ out.push(col(s[i], lerpColor(r, g, b, r, g, b, 0)));
341
+ }
342
+ return out.join('');
343
+ }
344
+
345
+ /** How far the light advances in one step, in characters. One is the most literal reading of "move by letters": the
346
+ * light lands on a glyph, lights it and its neighbours, then moves on. A larger step reads as a coarser crawl. */
347
+ export const STEP_CHARS = 1;
348
+
349
+ export const SWEEP_TICKS = 20; // ticks per half-sweep
350
+
351
+ /** How far past the band the head travels, in band widths. The Working row computes its own head and needs this too, so
352
+ * it is exported rather than kept private — two copies of the constant would drift. */
353
+ export const SWEEP_TRAVEL_PAD = 1; // head runs from -BAND to 1
354
+
355
+ /**
356
+ * Band width in characters, scaled to the row so every row is equally smooth.
357
+ *
358
+ * HALF THE ROW, with a floor of 3 characters. Because the band is then always `n/2`, `BAND = 0.5` for every row of 6+
359
+ * characters, so frames-per-character — and therefore the visual smoothness — is the SAME for a short tool name and a
360
+ * long phrase. An earlier version capped the band at 6 characters, which made BAND shrink as the row grew: a long row
361
+ * got fewer frames per character, so the cap defeated the very scaling it was part of.
362
+ */
363
+ export function bandCharsFor(n) {
364
+ return Math.max(3, n / 2);
365
+ }
366
+
367
+ /** Frames each character spends inside the band — the smoothness measure. */
368
+ export function framesPerChar(n, ticks = SWEEP_TICKS) {
369
+ const BAND = bandCharsFor(n) / n;
370
+ return (BAND * ticks) / (1 + BAND * SWEEP_TRAVEL_PAD);
371
+ }
package/src/colors.js CHANGED
@@ -522,14 +522,21 @@ export function setTheme(name) {
522
522
  // Towards BLACK on a dark theme and towards the foreground on a light one: mixing a dark page further towards its
523
523
  // own foreground would make it lighter, which is `codeBg`'s job, not this one.
524
524
  C.termBg = brgb(...mix(t.bg, [0, 0, 0], isLight ? 0.925 : 0.78));
525
- // THE COMPOSER SURFACE: NEUTRAL, and derived from the page. Neutral because a hue here reads as "more page"
526
- // rather than as an input field; derived because a fixed grey meant every theme drew the default dark theme's
527
- // input box. The three channels are set to the page's own LUMINANCE plus a step, so the field is grey while
528
- // still belonging to the palette it sits in. A theme may override it with its own `composer` triple.
529
- const pageLum = (t.bg[0] + t.bg[1] + t.bg[2]) / 3;
530
- const neutral = Math.max(0, Math.min(255, Math.round(pageLum + (isLight ? -14 : 14))));
531
- C.composerBg = brgb(...(t.composer || [neutral, neutral, neutral + (isLight ? 0 : 2)]));
532
-
525
+ // THE INPUT SURFACE IS A THEMED SURFACE, not a neutral one.
526
+ //
527
+ // It used to be three equal channels — a true grey — on the reasoning that an input field should not look like
528
+ // "more page". On the dark theme that produced the opposite: the page is a dark TEAL, and a neutral grey beside
529
+ // it does not read as a field on this page, it reads as a panel from some other program. Every other surface
530
+ // here carries the palette hue, so this one does too: the step is the same mix as `codeBg`, which raises the
531
+ // brightness while keeping the colour, and a sent message and a steered one sit on the SAME surface as the
532
+ // composer because they are the same kind of thing. A theme may still override it with its own `composer`
533
+ // triple.
534
+ C.composerBg = brgb(...(t.composer || mix(t.bg, t.fg, isLight ? 0.90 : 0.88)));
535
+ // THE MODE SURFACES. The composer is otherwise unfilled, and a line typed while a mode is on goes somewhere
536
+ // other than the model — so the FIELD says so, not one character at the far left. Each is the theme's own
537
+ // accent mixed mostly towards the page, so text on it stays readable; a saturated fill would not be.
538
+ C.stdinBg = brgb(...mix(t.bg, t.orange || [203, 75, 22], isLight ? 0.72 : 0.74));
539
+ C.shellBg = brgb(...mix(t.bg, t.shellMode || t.teal, isLight ? 0.72 : 0.74));
533
540
  // A comment: the palette's foreground, pulled most of the way towards its background so it reads as quiet. A dark
534
541
  // page can afford a looser mix; a light one cannot — solar's foreground is already a muted blue-grey, and at the
535
542
  // dark theme's ratio its comments came within 8 of the removal wash.
@@ -0,0 +1,182 @@
1
+ // The input line: its prompt, its collapsed pastes, and its selection.
2
+ //
3
+ // Nothing here paints a screen or reads a session. A caller hands in the state object and gets back the prefix, the
4
+ // marker text, or a row with a span recoloured — which is what lets the same rules serve the TUI's composer and any
5
+ // other front end that wants them.
6
+
7
+ import { C } from './colors.js';
8
+
9
+ /**
10
+ * What the composer shows for this state: the buffer, the caret, and the prompt prefix.
11
+ *
12
+ * SHELL MODE (`!`) is modelled on kimi-code's editor. Typing `!` on an EMPTY composer flips a mode flag instead of
13
+ * inserting the character; the `!` is rendered as the PREFIX. That is what keeps it from appearing twice: the buffer
14
+ * holds only the command, the caret never has to step over a marker it is not editing, and submit never has to strip
15
+ * anything.
16
+ *
17
+ * STDIN MODE takes `▸`, the same glyph the hint row under a running command uses, so one idea has one symbol.
18
+ */
19
+ export function composerInput(state) {
20
+ const shell = state.inputMode === 'bash';
21
+ const prefix = state.stdinMode ? '▸ ' : (shell ? '! ' : '> ');
22
+ return { text: state.input || '', caret: state.caret || 0, prefix };
23
+ }
24
+
25
+ /**
26
+ * Marker text for a collapsed paste.
27
+ *
28
+ * Only a multi-line TEXT paste collapses; an IMAGE always collapses, because its payload is a temp file path that
29
+ * should never be shown as if the user typed it.
30
+ *
31
+ * text, multi-line : [paste #1 +12 lines]
32
+ * text, one line : [paste #1 1 lines]
33
+ * image : [paste #1 image]
34
+ *
35
+ * The `image` form keeps the same `paste #N` prefix on purpose: expansion, chipping and caret movement all key off
36
+ * it, so images get the styling and atomic behaviour for free.
37
+ */
38
+ export function pasteMarker(id, lineCount, kind = 'paste') {
39
+ if (kind === 'image') return `[paste #${id} image]`;
40
+ return lineCount > 1 ? `[paste #${id} +${lineCount} lines]` : `[paste #${id} ${lineCount} lines]`;
41
+ }
42
+
43
+ /** The tail of any collapsed-paste marker: `+L lines`, `L lines`, or `image`. */
44
+ export const PASTE_MARKER_RE = /\[paste #(\d+) (?:\+\d+ lines|\d+ lines|image)\]/g;
45
+
46
+ const MARKER_LEFT_RE = /\[paste #(\d+) (?:\+\d+ lines|\d+ lines|image)\]$/;
47
+ const MARKER_RIGHT_RE = /^\[paste #(\d+) (?:\+\d+ lines|\d+ lines|image)\]/;
48
+
49
+ /** Expand every `[paste #N …]` marker in `text` back to its real content. */
50
+ export function expandPastes(text, pastes) {
51
+ if (!pastes || !text || !text.includes('[paste #')) return text;
52
+ return text.replace(PASTE_MARKER_RE, (whole, id) => {
53
+ const entry = pastes.get(Number(id));
54
+ return entry ? entry.text : whole;
55
+ });
56
+ }
57
+
58
+ /**
59
+ * Chip each collapsed-paste marker with a selection background, leaving non-marker text untouched.
60
+ *
61
+ * The chip ends with `C.bgReset` and then the caller's SURFACE, not with a bare reset: `ESC[0m` clears EVERY style, so
62
+ * it also wiped the foreground the caller had applied to the text after the chip — the rest of the line came out in
63
+ * the terminal's default grey instead of the prompt's colour. `ESC[49m` gives the background back to the terminal
64
+ * rather than to the theme, so the caller's own surface has to follow it immediately or the rest of the row shows
65
+ * whatever background the user's terminal happens to have.
66
+ *
67
+ * `hoverId` is the paste number the pointer is over, when it is over one; that chip keeps the hover accent.
68
+ * `surface` is the background the caller is about to paint under this row, or '' when the row has none.
69
+ */
70
+ export function highlightPasteMarkers(row, hoverId = null, surface = C.bg) {
71
+ const s = String(row);
72
+ if (!s.includes('[paste #')) return s;
73
+ return s.replace(PASTE_MARKER_RE, (m, id) => {
74
+ const after = C.bgReset + surface;
75
+ if (Number(id) === hoverId) return C.hover + C.selBg + m + after;
76
+ return C.selBg + m + after;
77
+ });
78
+ }
79
+
80
+ /**
81
+ * Which paste number, if any, occupies this input index. Returns null when none does.
82
+ *
83
+ * The companion to `expandPasteMarkerAt`: that one acts on the chip under the pointer, this one merely names it so the
84
+ * row can be drawn differently. Both need the same bounds, and a chip is inclusive of its end because the caret index
85
+ * rounds to the position after the last character.
86
+ */
87
+ export function pasteMarkerIdAt(input, idx) {
88
+ const cur = String(input == null ? '' : input);
89
+ if (!cur.includes('[paste #')) return null;
90
+ for (const m of cur.matchAll(PASTE_MARKER_RE)) {
91
+ const at = m.index;
92
+ if (idx >= at && idx <= at + m[0].length) return Number(m[1]);
93
+ }
94
+ return null;
95
+ }
96
+
97
+ /**
98
+ * Expand the collapsed paste the caret index lands on, in place. Returns true when one was expanded.
99
+ *
100
+ * `onChanged` is called after a successful expansion so the host can re-run whatever menu or completion refresh it
101
+ * owns — this module does not know about menus.
102
+ *
103
+ * Takes the ALREADY-CONVERTED index. An earlier version took the row and column and converted itself, which
104
+ * double-subtracted the row's prefix width — every click landed two columns left of the pointer and a click on the
105
+ * chip's first character expanded nothing.
106
+ *
107
+ * `state.pastes` keeps its entry: expansion is a no-op for text with no marker, so leaving it costs nothing, and
108
+ * dropping it would break a later marker that still refers to the same paste.
109
+ */
110
+ export function expandPasteMarkerAt(state, idx, onChanged) {
111
+ const cur = state.input || '';
112
+ if (!cur.includes('[paste #')) return false;
113
+
114
+ for (const m of cur.matchAll(PASTE_MARKER_RE)) {
115
+ const at = m.index;
116
+ const end = at + m[0].length;
117
+ // Clicking any character of the chip targets it — including the character after the last one, which is where a
118
+ // click on the closing bracket rounds to.
119
+ if (idx < at || idx > end) continue;
120
+ const entry = state.pastes && state.pastes.get(Number(m[1]));
121
+ if (!entry) return false;
122
+ state.input = cur.slice(0, at) + entry.text + cur.slice(end);
123
+ // The caret goes AFTER the expanded text, so the next keystroke continues where it ends rather than landing in the
124
+ // middle of the paste the user just revealed.
125
+ state.caret = at + entry.text.length;
126
+ state.composerSel = null;
127
+ if (typeof onChanged === 'function') onChanged();
128
+ return true;
129
+ }
130
+ return false;
131
+ }
132
+
133
+ /**
134
+ * Apply a selection background to the text portion of a composer row.
135
+ *
136
+ * `text` is the visible text on this row (after the prefix), `textStart` is the character offset of `text[0]` in the
137
+ * full input string, and `[selAnchor, selHead]` is the selection range in the full input.
138
+ *
139
+ * Selection changes only the BACKGROUND; the foreground keeps its own colour. Leaving the selection restores the
140
+ * PAGE instead of emitting a full reset, for two reasons: a bare reset also kills the foreground, and `ESC[49m` hands
141
+ * the background back to the TERMINAL — which showed its own colour for the rest of the line.
142
+ */
143
+ export function highlightSelection(text, textStart, selAnchor, selHead) {
144
+ if (!text) return text;
145
+ const a = Math.min(selAnchor, selHead);
146
+ const h = Math.max(selAnchor, selHead);
147
+ let out = '';
148
+ let inSel = false;
149
+ for (let i = 0; i < text.length; i++) {
150
+ const globalIdx = textStart + i;
151
+ const want = globalIdx >= a && globalIdx < h;
152
+ if (want && !inSel) { out += C.selBg; inSel = true; }
153
+ else if (!want && inSel) { out += C.bg; inSel = false; }
154
+ out += text[i];
155
+ }
156
+ if (inSel) out += C.reset;
157
+ return out;
158
+ }
159
+
160
+ /**
161
+ * The collapsed-paste marker adjacent to the caret, in the given direction.
162
+ *
163
+ * The composer treats a marker as ONE atomic unit: moving the caret across it jumps over the whole thing, and
164
+ * deleting it removes the entire marker.
165
+ *
166
+ * @param {string} text the buffer
167
+ * @param {number} caret character index
168
+ * @param {number} dir -1 looks left of the caret, +1 looks right
169
+ * @returns {{start:number, end:number, id:number}|null}
170
+ */
171
+ export function adjacentPasteMarker(text, caret, dir) {
172
+ const s = String(text || '');
173
+ const c = Math.max(0, Math.min(s.length, caret));
174
+ if (dir < 0) {
175
+ const m = MARKER_LEFT_RE.exec(s.slice(0, c));
176
+ if (m) return { start: c - m[0].length, end: c, id: Number(m[1]) };
177
+ } else {
178
+ const m = MARKER_RIGHT_RE.exec(s.slice(c));
179
+ if (m) return { start: c, end: c + m[0].length, id: Number(m[1]) };
180
+ }
181
+ return null;
182
+ }