@hncode/hncode 0.7.7 → 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
+ }