soliterminal 0.0.0-stage → 0.2.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.
@@ -0,0 +1,404 @@
1
+ import { colorOf, rankGlyph, rankLabel, suitGlyph, suitLabel } from '../core/card.js';
2
+ import { TABLEAU_COLUMNS, pile, samePile } from '../core/klondike.js';
3
+ import { keyLabel } from './keymap.js';
4
+ import { ScreenBuffer, textWidth } from './screen.js';
5
+ import { winRate } from '../stats.js';
6
+ import { formatTime, formatWhen } from './help.js';
7
+ function geometry(compact) {
8
+ const card = compact ? 4 : 6;
9
+ const pitch = card + 2;
10
+ return { card, pitch, board: pitch * (TABLEAU_COLUMNS - 1) + card };
11
+ }
12
+ export const LARGE = geometry(false); // board 54 wide
13
+ export const COMPACT = geometry(true); // board 40 wide
14
+ export const COLUMN_PITCH = LARGE.pitch;
15
+ export const BOARD_WIDTH = LARGE.board;
16
+ export const MIN_WIDTH = 56;
17
+ const ROW = { header: 0, topKeys: 2, topCards: 3, tableauKeys: 5, tableau: 6 };
18
+ const FOOTER_ROWS = 5; // blank, message, divider, two status lines
19
+ const BOX = {
20
+ tl: '╭', tr: '╮', bl: '╰', br: '╯', h: '─', v: '│',
21
+ recycle: '↺', none: '×', divider: '─', sep: '·', prompt: '›', yes: '✓', wait: '…', warn: '⚠', updown: '↑↓',
22
+ };
23
+ const ASCII = {
24
+ tl: '+', tr: '+', bl: '+', br: '+', h: '-', v: '|',
25
+ recycle: 'O', none: 'x', divider: '-', sep: '-', prompt: '>', yes: 'ok', wait: '..', warn: '!', updown: 'up/down',
26
+ };
27
+ /** Rows a column of face-down cards takes: one each, or one in total when folded. */
28
+ const downRows = (down, fold) => (fold && down > 1 ? 1 : down);
29
+ /** Rows the tableau needs: one per card. */
30
+ function tableauHeight(state, fold) {
31
+ return Math.max(1, ...state.tableau.map((c) => downRows(c.down.length, fold) + c.up.length));
32
+ }
33
+ /** Rows the screen needs, with face-down stacks drawn in full or folded. */
34
+ export function screenHeight(state, fold = false) {
35
+ return ROW.tableau + tableauHeight(state, fold) + FOOTER_ROWS;
36
+ }
37
+ /** The fewest rows this position can be drawn in. */
38
+ export function minScreenHeight(state) {
39
+ return screenHeight(state, true);
40
+ }
41
+ export function renderKlondike(state, view, options = {}) {
42
+ const ascii = options.ascii ?? false;
43
+ const compact = options.compact ?? false;
44
+ const geo = compact ? COMPACT : LARGE;
45
+ const look = { ascii, compact, card: geo.card };
46
+ const g = ascii ? ASCII : BOX;
47
+ const width = Math.max(options.width ?? MIN_WIDTH, MIN_WIDTH);
48
+ const fold = options.height !== undefined && screenHeight(state) > options.height;
49
+ const height = Math.max(screenHeight(state, fold), options.height ?? 0);
50
+ const buf = new ScreenBuffer(width, height);
51
+ const left = Math.floor((width - geo.board) / 2);
52
+ const colX = (i) => left + i * geo.pitch;
53
+ // --- card primitives -----------------------------------------------------
54
+ const suitFg = (card) => (colorOf(card) === 'red' ? 'red' : 'black');
55
+ // A card is one row: a white face with its rank and suit in bold, or a grey back.
56
+ // `edge` underlines a card that has another directly below it, which draws a
57
+ // hairline between stacked cards without spending a row. The only highlight on
58
+ // a card is `chosen`: the card the arrows are on.
59
+ const card = (x, y, c, edge = false, chosen = false) => {
60
+ const style = { fg: suitFg(c), bg: chosen ? 'chosen' : 'card', bold: true, edge };
61
+ buf.put(x, y, faceText(c, look), style);
62
+ };
63
+ /** A face-down card, optionally labelled with a count (the stock, or a folded stack). */
64
+ const back = (x, y, count, edge = false) => buf.put(x, y, count === undefined ? ' '.repeat(geo.card) : center(countText(count), geo.card), { fg: 'back', bg: 'back', edge });
65
+ /** Large cards write a one-digit count fullwidth, so it is as big as the ranks. */
66
+ const countText = (count) => (count < 10 && !compact && !ascii ? fullwidth(String(count)) : String(count).padStart(2));
67
+ /** An empty place, e.g. `[ A ]` (or compact `[A ]`) for a foundation waiting for an ace. */
68
+ const slot = (x, y, mark) => {
69
+ const inner = mark + ' '.repeat(Math.max(0, 2 - textWidth(mark)));
70
+ buf.put(x, y, compact ? '[' + inner + ']' : '[ ' + inner + ' ]', { fg: 'dim' });
71
+ };
72
+ const markRank = (rank) => (compact ? rankLabel(rank) : rankGlyph(rank, ascii));
73
+ /** The key label above the pile at `x` shows where cards are held (strong) and the cursor (weak). */
74
+ const key = (x, y, target) => {
75
+ let bg = 'none';
76
+ if (target.kind === 'stock') {
77
+ if (view.cursor.kind === 'stock')
78
+ bg = 'cursor';
79
+ }
80
+ else if (view.held && samePile(view.held.from, target)) {
81
+ bg = 'hold';
82
+ }
83
+ else if (view.cursor.kind !== 'stock' && samePile(view.cursor, target)) {
84
+ bg = 'cursor';
85
+ }
86
+ // Exact foundation keys stay quiet unless active; the status bar promotes i instead.
87
+ const fg = target.kind === 'foundation' && bg === 'none' ? 'dim' : 'key';
88
+ // With large cards, keys are fullwidth too (q w a…), as big as the ranks.
89
+ const plain = keyLabel(target);
90
+ const label = compact || ascii || plain.length > 1 ? plain : fullwidth(plain);
91
+ buf.put(x + Math.floor((geo.card - textWidth(label)) / 2), y, label, { fg, bg });
92
+ };
93
+ /**
94
+ * Which face-up card of column `i` is chosen, if any: the first of the cards
95
+ * the arrows chose, or of the exact cards in hand.
96
+ */
97
+ const chosenIn = (i) => {
98
+ const col = state.tableau[i];
99
+ const here = (p) => p.kind === 'tableau' && p.index === i;
100
+ const n = view.held ? (here(view.held.from) ? view.held.count : undefined) : here(view.cursor) ? view.selected : undefined;
101
+ return n === undefined ? undefined : col.up.length - n;
102
+ };
103
+ // --- header --------------------------------------------------------------
104
+ buf.put(1, ROW.header, `soliterminal ${g.sep} Klondike ${g.sep} Draw ${state.drawMode}`, { fg: 'header' });
105
+ const stats = `Moves ${state.moves}` + (view.elapsedMs === undefined ? '' : ` ${formatTime(view.elapsedMs)}`);
106
+ // Winnability: ✓ proven, … still checking, ? could not tell in time, 0% proven lost.
107
+ let verdict = view.status === undefined
108
+ ? undefined
109
+ : {
110
+ winnable: { text: g.yes, fg: 'key' },
111
+ checking: { text: g.wait, fg: 'dim' },
112
+ unclear: { text: '?', fg: 'message' }, // a warning: it may be lost
113
+ lost: { text: '0%', fg: 'red' },
114
+ }[view.status];
115
+ if (verdict && view.status === 'winnable') {
116
+ if (view.danger)
117
+ verdict = { text: g.warn, fg: 'red' };
118
+ else if (view.tight)
119
+ verdict = { text: `${g.yes}!`, fg: 'message' };
120
+ }
121
+ const tail = verdict ? ` Win ${verdict.text}` : '';
122
+ let hx = buf.put(width - 1 - textWidth(stats + tail), ROW.header, stats, { fg: 'dim' });
123
+ if (verdict) {
124
+ hx = buf.put(hx, ROW.header, ' Win ', { fg: 'dim' });
125
+ buf.put(hx, ROW.header, verdict.text, { fg: verdict.fg, bold: view.status === 'lost' || view.danger !== undefined || view.tight === true });
126
+ }
127
+ // --- top row: stock, waste, foundations ----------------------------------
128
+ key(colX(0), ROW.topKeys, { kind: 'stock' });
129
+ if (state.stock.length > 0)
130
+ back(colX(0), ROW.topCards, state.stock.length);
131
+ else
132
+ slot(colX(0), ROW.topCards, state.waste.length > 0 ? redealMark(state.redealsLeft, g) : ' ');
133
+ // Redeals left, always in view just under the stock: ↺3, red once none are left.
134
+ if (Number.isFinite(state.redealsLeft)) {
135
+ const mark = g.recycle + Math.min(state.redealsLeft, 99);
136
+ const none = state.redealsLeft <= 0;
137
+ buf.put(colX(0) + Math.floor((geo.card - textWidth(mark)) / 2), ROW.topCards + 1, mark, { fg: none ? 'red' : 'dim', bold: none });
138
+ }
139
+ key(colX(1), ROW.topKeys, pile.waste);
140
+ const fan = state.waste.slice(state.drawMode === 3 ? -3 : -1);
141
+ if (fan.length === 0)
142
+ slot(colX(1), ROW.topCards, ' ');
143
+ let fx = colX(1);
144
+ fanPieces(fan, look, colX(3) - colX(1) - 1).forEach((text, i) => {
145
+ fx = buf.put(fx, ROW.topCards, text, { fg: suitFg(fan[i]), bg: 'card', bold: true });
146
+ });
147
+ state.foundations.forEach((foundation, i) => {
148
+ const x = colX(3 + i);
149
+ key(x, ROW.topKeys, pile.foundation(i));
150
+ const top = foundation.at(-1);
151
+ if (top)
152
+ card(x, ROW.topCards, top);
153
+ else
154
+ slot(x, ROW.topCards, markRank(1));
155
+ });
156
+ // --- tableau -------------------------------------------------------------
157
+ state.tableau.forEach((col, i) => {
158
+ const x = colX(i);
159
+ key(x, ROW.tableauKeys, pile.tableau(i));
160
+ let y = ROW.tableau;
161
+ if (col.down.length === 0 && col.up.length === 0) {
162
+ slot(x, y, markRank(13));
163
+ return;
164
+ }
165
+ // Face-down cards always have something below them: more backs, or the face-up run.
166
+ if (downRows(col.down.length, fold) === 1 && col.down.length > 1)
167
+ back(x, y++, col.down.length, true);
168
+ else
169
+ for (let d = 0; d < col.down.length; d++)
170
+ back(x, y++, undefined, true);
171
+ const chosen = chosenIn(i);
172
+ col.up.forEach((c, j) => card(x, y++, c, j < col.up.length - 1, j === chosen));
173
+ });
174
+ // --- footer --------------------------------------------------------------
175
+ const footer = height - FOOTER_ROWS;
176
+ if (view.paused)
177
+ buf.put(1, footer + 1, `${g.prompt} Paused. The clock waits until you come back.`, { fg: 'dim' });
178
+ else if (view.message && view.danger?.message)
179
+ buf.put(1, footer + 1, `${g.warn} ${view.message}`, { fg: 'red', bold: true });
180
+ else if (view.message)
181
+ buf.put(1, footer + 1, `${g.prompt} ${view.message}`, { fg: 'message' });
182
+ buf.put(0, footer + 2, g.divider.repeat(width), { fg: 'dim' });
183
+ if (view.record)
184
+ drawRecord(buf, footer + 2, state.drawMode, view.record, view.lostBefore);
185
+ // The first items of each row fit MIN_WIDTH; the last one shows when the window has room.
186
+ const status = [
187
+ [['q', 'draw'], ['w', 'waste'], ['a-j', 'columns'], ['i', 'to foundation'], ['z', 'undo'], ['?', 'hint']],
188
+ [['arrows', 'select'], ['space', 'pick/drop'], ['tab', 'card size'], ['esc', 'menu'], ['x', 'quit']],
189
+ ];
190
+ status.forEach((items, row) => {
191
+ let x = 1;
192
+ items.forEach(([k, label], i) => {
193
+ if (i === items.length - 1 && x + k.length + 1 + label.length > width - 1)
194
+ return;
195
+ x = buf.put(x, footer + 3 + row, k, { fg: 'key' });
196
+ x = buf.put(x, footer + 3 + row, ` ${label} `, { fg: 'dim' });
197
+ });
198
+ });
199
+ if (view.celebration !== undefined)
200
+ drawConfetti(buf, view.celebration, footer, ascii);
201
+ if (view.defeat !== undefined)
202
+ drawDefeat(buf, view.defeat, footer);
203
+ if (view.dialog)
204
+ drawDialog(buf, view.dialog, g, left, geo.board, footer);
205
+ return buf;
206
+ }
207
+ /**
208
+ * The record for this draw mode, set into the divider line:
209
+ * `── Draw 1 won 12/20 (60%) streak 3 longest 5 best 03:10 ──`.
210
+ * Items drop off the end when the line is too narrow.
211
+ */
212
+ function drawRecord(buf, y, drawMode, m, lostBefore) {
213
+ const items = [
214
+ ['Draw', String(drawMode)],
215
+ // A deal lost before says so first after the mode, so it survives a narrow window.
216
+ ...(lostBefore === undefined ? [] : [['lost before', formatWhen(lostBefore)]]),
217
+ ['won', `${m.won}/${m.played} (${winRate(m)}%)`],
218
+ ['streak', String(m.streak)],
219
+ ['longest', String(m.bestStreak)],
220
+ ];
221
+ if (m.bestMs !== undefined)
222
+ items.push(['best', formatTime(m.bestMs)]);
223
+ const room = buf.width - 6;
224
+ const widthOf = (n) => items.slice(0, n).reduce((w, [k, v]) => w + k.length + v.length + 3, 0) - 2;
225
+ let n = items.length;
226
+ while (n > 1 && widthOf(n) > room)
227
+ n--;
228
+ let x = buf.put(2, y, ' ', { fg: 'dim' });
229
+ items.slice(0, n).forEach(([k, v], i) => {
230
+ if (i > 0)
231
+ x = buf.put(x, y, ' ', { fg: 'dim' });
232
+ x = buf.put(x, y, k + ' ', { fg: 'dim' });
233
+ x = buf.put(x, y, v, { fg: 'text' });
234
+ });
235
+ buf.put(x, y, ' ', { fg: 'dim' });
236
+ }
237
+ /** The empty stock: `↺` to redeal (with how many are left, if limited), or `×` when none are. */
238
+ function redealMark(left, g) {
239
+ if (!Number.isFinite(left))
240
+ return g.recycle;
241
+ return left > 0 ? g.recycle + Math.min(left, 9) : g.none;
242
+ }
243
+ /**
244
+ * The win ceremony: suits rain down over the board, each from its own column
245
+ * at its own speed, so the screen fills and then clears. `ms` is how far in
246
+ * it is. Purely a function of time, so every frame can be drawn on its own.
247
+ */
248
+ function drawConfetti(buf, ms, bottom, ascii) {
249
+ const glyphs = ascii ? ['S', 'H', 'D', 'C', '*'] : ['♠', '♥', '♦', '♣', '✦'];
250
+ const count = Math.round(buf.width * 0.9);
251
+ let seed = 0x9e3779b9;
252
+ const rand = () => {
253
+ seed = Math.imul(seed ^ (seed >>> 15), 0x2c1b3c6d) >>> 0;
254
+ seed = (seed + 0x6d2b79f5) >>> 0;
255
+ return seed / 2 ** 32;
256
+ };
257
+ for (let i = 0; i < count; i++) {
258
+ const x = Math.floor(rand() * buf.width);
259
+ const delay = rand() * 1_200;
260
+ const speed = bottom / (0.8 + rand() * 0.8); // rows per second: 0.8-1.6 s to cross, whatever the height
261
+ const kind = Math.floor(rand() * glyphs.length);
262
+ // Each piece falls, pauses out of sight for a moment, and falls again: it keeps raining.
263
+ const cycle = (bottom / speed) * 1000 + 300 + rand() * 1_200;
264
+ const t = ms - delay;
265
+ if (t < 0)
266
+ continue;
267
+ const y = Math.floor((((t % cycle) / 1000) * speed));
268
+ if (y < 1 || y >= bottom)
269
+ continue;
270
+ const red = kind === 1 || kind === 2;
271
+ // Over a card, keep the card and use its ink; elsewhere use the theme's colors.
272
+ const under = buf.get(x, y);
273
+ if (under.ch === '')
274
+ continue; // the right half of a wide character
275
+ const onCard = under.bg === 'card' || under.bg === 'back';
276
+ const fg = onCard ? (under.bg === 'back' ? 'back' : red ? 'red' : 'black') : red ? 'red' : kind === 4 ? 'message' : 'key';
277
+ buf.put(x, y, glyphs[kind], { fg, bg: onCard ? under.bg : 'none', bold: true });
278
+ // A faint trail just above.
279
+ if (y - 1 >= 1 && buf.get(x, y - 1).bg === 'none')
280
+ buf.put(x, y - 1, ascii ? '.' : '·', { fg: 'dim' });
281
+ }
282
+ }
283
+ /** Sideways offsets of the board while it shakes, one per 70 ms. */
284
+ const SHAKE = [2, -2, 2, -1, 1, -1, 0];
285
+ const SHAKE_STEP_MS = 70;
286
+ /** After the shake, the ink drains from the cards one column of cells at a time, left to right. */
287
+ const FADE_FROM_MS = SHAKE.length * SHAKE_STEP_MS;
288
+ const FADE_MS = 800;
289
+ /**
290
+ * A proven loss: the board shakes, then the cards lose their color from left
291
+ * to right and stay grey behind the dialog. Rows between the header and the
292
+ * footer move; the header and the footer stay put so the verdict stays readable.
293
+ * Purely a function of time, like the confetti.
294
+ */
295
+ function drawDefeat(buf, ms, bottom) {
296
+ const shift = ms < FADE_FROM_MS ? SHAKE[Math.floor(ms / SHAKE_STEP_MS)] : 0;
297
+ const faded = Math.max(0, Math.min(1, (ms - FADE_FROM_MS) / FADE_MS));
298
+ const reach = Math.round(faded * buf.width);
299
+ for (let y = 1; y < bottom; y++) {
300
+ const row = Array.from({ length: buf.width }, (_, x) => buf.get(x, y));
301
+ // A wide character split by the shift would leave half of itself behind: blank the row and redraw it whole.
302
+ buf.put(0, y, ' '.repeat(buf.width));
303
+ for (let x = 0; x < buf.width; x++) {
304
+ const cell = row[x];
305
+ if (cell.ch === '')
306
+ continue;
307
+ const to = x + shift;
308
+ if (to < 0 || to >= buf.width)
309
+ continue;
310
+ const grey = to < reach && (cell.fg === 'red' || cell.fg === 'black' || cell.fg === 'key' || cell.fg === 'message');
311
+ buf.put(to, y, cell.ch, { fg: grey ? 'dim' : cell.fg, bg: cell.bg, bold: grey ? false : cell.bold, edge: cell.edge });
312
+ }
313
+ }
314
+ }
315
+ /** ASCII to its fullwidth form: `q` → `q`, `1` → `1`, `` ` `` → ```. */
316
+ function fullwidth(text) {
317
+ return text.replace(/[!-~]/g, (ch) => String.fromCharCode(ch.charCodeAt(0) + 0xfee0));
318
+ }
319
+ function center(text, width) {
320
+ const pad = Math.max(0, width - textWidth(text));
321
+ return ' '.repeat(Math.ceil(pad / 2)) + text + ' '.repeat(Math.floor(pad / 2));
322
+ }
323
+ /** The rank alone, as this look draws it. */
324
+ function rankText(c, look) {
325
+ return look.compact ? rankLabel(c.rank) : rankGlyph(c.rank, look.ascii);
326
+ }
327
+ /**
328
+ * What a card face says, padded to the card width: ` K♠️ `, ` 10♠️ `, compact
329
+ * ` K♠ `, or in ascii ` KS ` / ` KS `.
330
+ */
331
+ function faceText(c, look) {
332
+ let text;
333
+ if (look.compact)
334
+ text = rankLabel(c.rank) + suitLabel(c.suit, look.ascii);
335
+ else if (look.ascii)
336
+ text = rankGlyph(c.rank, true).padStart(2) + c.suit + ' ';
337
+ else
338
+ text = rankGlyph(c.rank) + suitGlyph(c.suit);
339
+ return center(text, look.card);
340
+ }
341
+ /**
342
+ * The visible part of each Draw 3 waste card, left to right. Covered cards show
343
+ * their leading gap, rank and suit; the top card shows in full. To keep a blank
344
+ * cell before the foundations, padding goes first: the top card's trailing
345
+ * space, then the leftmost card's leading space, and as a last resort the
346
+ * leftmost card shows its rank alone.
347
+ */
348
+ function fanPieces(fan, look, room) {
349
+ const pieces = fan.map((c, i) => (i < fan.length - 1 ? faceText(c, look).trimEnd() : faceText(c, look)));
350
+ const total = () => pieces.reduce((w, p) => w + textWidth(p), 0);
351
+ const last = pieces.length - 1;
352
+ if (total() > room && last > 0 && pieces[last].endsWith(' '))
353
+ pieces[last] = pieces[last].slice(0, -1);
354
+ if (total() > room && pieces[0].startsWith(' '))
355
+ pieces[0] = pieces[0].slice(1);
356
+ if (total() > room && last > 0)
357
+ pieces[0] = rankText(fan[0], look);
358
+ return pieces;
359
+ }
360
+ /**
361
+ * A box over the tableau, exactly as wide as the board so no card peeks out
362
+ * beside it, with a blank row under it so none peeks out below either.
363
+ */
364
+ function drawDialog(buf, d, g, left, board, bottom) {
365
+ const hint = `${g.updown} or letter choose enter select esc back`;
366
+ // Each choice shows the letter that picks it: (N)ew game.
367
+ const rows = [...d.lines, ...(d.lines.length > 0 ? [''] : []), ...d.choices.map((label) => `${g.prompt} (${label[0]})${label.slice(1)}`), '', hint];
368
+ const needed = Math.max(textWidth(d.title) + 6, ...rows.map((r) => textWidth(r) + 4));
369
+ const boxWidth = Math.min(buf.width - 2, Math.max(board, needed));
370
+ const x = Math.max(1, Math.min(left - Math.floor((boxWidth - board) / 2), buf.width - 1 - boxWidth));
371
+ const y = Math.max(1, Math.min(ROW.tableauKeys, bottom - rows.length - 3));
372
+ const edge = { fg: d.danger ? 'red' : 'text' };
373
+ const first = d.lines.length > 0 ? d.lines.length + 1 : 0;
374
+ const titled = `${g.h} ${d.title} `;
375
+ buf.put(x, y, g.tl, edge);
376
+ buf.put(x + 1, y, g.h, edge);
377
+ const tx = buf.put(x + 2, y, ` ${d.title} `, { fg: d.danger ? 'red' : 'header', bold: true });
378
+ buf.put(tx, y, g.h.repeat(Math.max(0, boxWidth - 1 - textWidth(titled) - 1)), edge);
379
+ buf.put(x + boxWidth - 1, y, g.tr, edge);
380
+ rows.forEach((text, i) => {
381
+ const ry = y + 1 + i;
382
+ buf.put(x, ry, g.v + ' '.repeat(boxWidth - 2) + g.v, edge);
383
+ const choice = i - first;
384
+ if (choice >= 0 && choice < d.choices.length) {
385
+ const on = choice === d.selected;
386
+ // The chosen row is a bar across the box, its marker in the key color.
387
+ if (on)
388
+ buf.put(x + 1, ry, ' '.repeat(boxWidth - 2), { bg: 'cursor' });
389
+ const bg = on ? 'cursor' : 'none';
390
+ const mx = buf.put(x + 2, ry, on ? g.prompt : ' ', { fg: 'key', bold: true, bg });
391
+ const label = d.choices[choice];
392
+ let cx = buf.put(mx + 1, ry, '(', { fg: 'dim', bg });
393
+ cx = buf.put(cx, ry, label[0], { fg: 'key', bold: true, bg });
394
+ cx = buf.put(cx, ry, ')', { fg: 'dim', bg });
395
+ buf.put(cx, ry, label.slice(1), { fg: 'text', bold: on, bg });
396
+ }
397
+ else {
398
+ buf.put(x + 2, ry, text, { fg: i === rows.length - 1 ? 'dim' : 'text' });
399
+ }
400
+ });
401
+ buf.put(x, y + rows.length + 1, g.bl + g.h.repeat(boxWidth - 2) + g.br, edge);
402
+ if (y + rows.length + 2 < bottom)
403
+ buf.put(x, y + rows.length + 2, ' '.repeat(boxWidth));
404
+ }
@@ -0,0 +1,88 @@
1
+ const BLANK = { ch: ' ', fg: 'text', bg: 'none', bold: false, edge: false };
2
+ /** U+FE0F asks for emoji presentation; it joins the character before it. */
3
+ export const EMOJI = '\uFE0F';
4
+ /**
5
+ * A character drawn as emoji takes two cells here. Terminals disagree about
6
+ * that, so the renderer paints both cells and positions the cursor absolutely
7
+ * after it; see `ansi.ts`.
8
+ */
9
+ export function isEmoji(ch) {
10
+ return ch.length > 1 && ch.endsWith(EMOJI);
11
+ }
12
+ /** Hangul, CJK, fullwidth forms and emoji take two cells. Plain ♠♥♦♣ take one. */
13
+ export function charWidth(ch) {
14
+ return isEmoji(ch) || /[ᄀ-ᅟ⺀-〾ぁ-꓏가-힣豈-﫿︰-﹏＀-⦆¢-₩]/u.test(ch)
15
+ ? 2
16
+ : 1;
17
+ }
18
+ /** Splits text into cells' worth of characters, keeping U+FE0F with the one before it. */
19
+ export function units(text) {
20
+ const out = [];
21
+ for (const ch of text) {
22
+ if (ch === EMOJI && out.length > 0)
23
+ out[out.length - 1] += ch;
24
+ else
25
+ out.push(ch);
26
+ }
27
+ return out;
28
+ }
29
+ export function textWidth(text) {
30
+ let w = 0;
31
+ for (const ch of units(text))
32
+ w += charWidth(ch);
33
+ return w;
34
+ }
35
+ export function sameCell(a, b) {
36
+ return a.ch === b.ch && a.fg === b.fg && a.bg === b.bg && a.bold === b.bold && a.edge === b.edge;
37
+ }
38
+ /** A grid of styled cells. The layout draws into it and the renderer turns it into ANSI. */
39
+ export class ScreenBuffer {
40
+ width;
41
+ height;
42
+ #cells;
43
+ constructor(width, height) {
44
+ this.width = width;
45
+ this.height = height;
46
+ this.#cells = new Array(width * height).fill(BLANK);
47
+ }
48
+ get(x, y) {
49
+ if (x < 0 || y < 0 || x >= this.width || y >= this.height)
50
+ return BLANK;
51
+ return this.#cells[y * this.width + x];
52
+ }
53
+ #set(x, y, cell) {
54
+ const i = y * this.width + x;
55
+ // Writing over half of a wide character blanks the other half.
56
+ if (this.#cells[i].ch === '' && x > 0)
57
+ this.#cells[i - 1] = { ...this.#cells[i - 1], ch: ' ' };
58
+ if (x + 1 < this.width && this.#cells[i + 1].ch === '' && cell.ch !== '') {
59
+ this.#cells[i + 1] = { ...this.#cells[i + 1], ch: ' ' };
60
+ }
61
+ this.#cells[i] = cell;
62
+ }
63
+ /** Writes text starting at (x, y), clipped to the buffer. Returns the x after the text. */
64
+ put(x, y, text, style = {}) {
65
+ const base = { fg: style.fg ?? 'text', bg: style.bg ?? 'none', bold: style.bold ?? false, edge: style.edge ?? false };
66
+ for (const ch of units(text)) {
67
+ const w = charWidth(ch);
68
+ if (y >= 0 && y < this.height && x >= 0 && x + w <= this.width) {
69
+ this.#set(x, y, { ch, ...base });
70
+ if (w === 2)
71
+ this.#set(x + 1, y, { ch: '', ...base });
72
+ }
73
+ x += w;
74
+ }
75
+ return x;
76
+ }
77
+ /** Plain text, one line per row, trailing spaces trimmed. Handy for tests and logs. */
78
+ toText() {
79
+ const lines = [];
80
+ for (let y = 0; y < this.height; y++) {
81
+ let line = '';
82
+ for (let x = 0; x < this.width; x++)
83
+ line += this.get(x, y).ch;
84
+ lines.push(line.trimEnd());
85
+ }
86
+ return lines.join('\n');
87
+ }
88
+ }
@@ -0,0 +1,155 @@
1
+ /**
2
+ * Everything except the cards uses the 16 basic ANSI colors, so it follows the
3
+ * terminal's palette. One color family sets the theme: its strong (bright)
4
+ * shade for keys, held cards and the ✓, its weak (normal) shade for the
5
+ * header, messages and the cursor. Red stays red for bad news.
6
+ *
7
+ * Cards use fixed colors so they always look like cards.
8
+ */
9
+ export const ACCENTS = { green: 2, cyan: 6, blue: 4, magenta: 5, yellow: 3, red: 1, white: 7 };
10
+ export const DEFAULT_ACCENT = 'green';
11
+ function palette(accent) {
12
+ const n = ACCENTS[accent];
13
+ const weak = String(30 + n);
14
+ const strong = String(90 + n);
15
+ return {
16
+ fg: {
17
+ text: '39', // the terminal's own text color
18
+ black: '30',
19
+ red: '31',
20
+ back: '37',
21
+ dim: '90', // bright black, usually grey
22
+ key: strong,
23
+ header: weak,
24
+ message: weak,
25
+ },
26
+ bg: {
27
+ none: '',
28
+ card: '107',
29
+ back: '100',
30
+ hold: String(100 + n), // strong: cards in hand
31
+ cursor: String(40 + n), // weak: where the cursor is
32
+ chosen: String(100 + n), // strong: a card face the arrows have chosen
33
+ },
34
+ };
35
+ }
36
+ /**
37
+ * Fixed card colors, as truecolor and as the matching 256-color cube entries.
38
+ *
39
+ * Card edges are underlines. Truecolor terminals almost all support a separate
40
+ * underline color (SGR 58, written with colons so terminals that do not know it
41
+ * skip it whole), which makes the edge a faint grey hairline. Elsewhere the
42
+ * underline takes the text color.
43
+ */
44
+ const BACK = {
45
+ truecolor: { back: '48;2;108;108;108', backText: '38;2;198;198;198', backEdge: '4;58:2::70:70:70' },
46
+ // 242 = #6c6c6c, 251 = #c6c6c6
47
+ '256': { back: '48;5;242', backText: '38;5;251', backEdge: '4' },
48
+ };
49
+ /**
50
+ * Card faces to choose from with SOLITERMINAL_CARD. `ddd` (the default) is a
51
+ * soft grey-white that glares less, so the text reads bolder, with a darker red
52
+ * and edge so hearts and diamonds keep their contrast; `fff` is pure white
53
+ * with pure red.
54
+ */
55
+ const FACES = {
56
+ fff: {
57
+ // 231 = #ffffff, 16 = #000000, 196 = #ff0000
58
+ truecolor: { face: '48;2;255;255;255', black: '38;2;0;0;0', red: '38;2;255;0;0', faceEdge: '4;58:2::170:170:170' },
59
+ '256': { face: '48;5;231', black: '38;5;16', red: '38;5;196', faceEdge: '4' },
60
+ },
61
+ ddd: {
62
+ // 253 = #dadada, 160 = #d70000
63
+ truecolor: { face: '48;2;221;221;221', black: '38;2;0;0;0', red: '38;2;204;0;0', faceEdge: '4;58:2::153:153:153' },
64
+ '256': { face: '48;5;253', black: '38;5;16', red: '38;5;160', faceEdge: '4' },
65
+ },
66
+ };
67
+ export const CARD_FACES = Object.keys(FACES);
68
+ export function makeColorTheme(depth, face = 'ddd', accent = DEFAULT_ACCENT) {
69
+ const card = { ...FACES[face][depth], ...BACK[depth] };
70
+ const { fg: FG, bg: BG } = palette(accent);
71
+ return {
72
+ name: `color-${depth}-${face}-${accent}`,
73
+ sgr(cell) {
74
+ let fg = FG[cell.fg];
75
+ let bg = BG[cell.bg];
76
+ let bold = cell.bold;
77
+ let edge = cell.edge ? '4' : '';
78
+ if (cell.bg === 'card' || cell.bg === 'chosen') {
79
+ // A chosen card keeps the face's suit colors; only its background takes the theme.
80
+ if (cell.bg === 'card')
81
+ bg = card.face;
82
+ fg = cell.fg === 'red' ? card.red : card.black;
83
+ if (cell.edge)
84
+ edge = card.faceEdge;
85
+ }
86
+ else if (cell.bg === 'back') {
87
+ bg = card.back;
88
+ fg = card.backText;
89
+ if (cell.edge)
90
+ edge = card.backEdge;
91
+ }
92
+ else if (cell.bg === 'hold' || cell.bg === 'cursor') {
93
+ fg = '30';
94
+ bold = true;
95
+ }
96
+ return ['0', fg, bg, bold ? '1' : '', edge].filter(Boolean).join(';');
97
+ },
98
+ };
99
+ }
100
+ export const colorTheme = makeColorTheme('256');
101
+ export const truecolorTheme = makeColorTheme('truecolor');
102
+ /** Reads SOLITERMINAL_CARD (`ddd` or `fff`, with or without `#`); anything else means `ddd`. */
103
+ export function cardFaceFrom(env) {
104
+ const want = (env.SOLITERMINAL_CARD ?? '').trim().toLowerCase().replace(/^#/, '');
105
+ return CARD_FACES.includes(want) ? want : 'ddd';
106
+ }
107
+ /**
108
+ * No color at all, for NO_COLOR or dumb terminals. Card faces are reversed,
109
+ * backs are reversed and faint, the cursor is reversed, held cards reversed,
110
+ * bold and underlined. A chosen card is the one face not reversed.
111
+ */
112
+ export const monoTheme = {
113
+ name: 'mono',
114
+ sgr(cell) {
115
+ const codes = ['0'];
116
+ if (cell.fg === 'dim')
117
+ codes.push('2');
118
+ if (cell.bold || cell.fg === 'header')
119
+ codes.push('1');
120
+ if (cell.bg === 'card' || cell.bg === 'cursor')
121
+ codes.push('7');
122
+ if (cell.bg === 'back')
123
+ codes.push('7', '2');
124
+ if (cell.bg === 'hold')
125
+ codes.push('7', '1', '4');
126
+ // Every other card face is reversed; the chosen one stands out by not being.
127
+ if (cell.bg === 'chosen')
128
+ codes.push('4');
129
+ if (cell.edge)
130
+ codes.push('4');
131
+ return codes.join(';');
132
+ },
133
+ };
134
+ export function isAccent(name) {
135
+ return name !== undefined && Object.hasOwn(ACCENTS, name);
136
+ }
137
+ /**
138
+ * Follows https://no-color.org, falls back to mono when output is not a
139
+ * terminal, uses truecolor for the cards when the terminal says it can, picks
140
+ * the card face from SOLITERMINAL_CARD, and the color family from `accent`
141
+ * (the --theme option), else SOLITERMINAL_THEME, else green.
142
+ */
143
+ export function pickTheme(env, isTTY, accent) {
144
+ if (env.NO_COLOR !== undefined && env.NO_COLOR !== '')
145
+ return monoTheme;
146
+ if (!isTTY || env.TERM === 'dumb')
147
+ return monoTheme;
148
+ const depth = env.COLORTERM === 'truecolor' || env.COLORTERM === '24bit' ? 'truecolor' : '256';
149
+ const face = cardFaceFrom(env);
150
+ const fromEnv = env.SOLITERMINAL_THEME?.trim().toLowerCase();
151
+ const chosen = accent ?? (isAccent(fromEnv) ? fromEnv : DEFAULT_ACCENT);
152
+ if (face === 'ddd' && chosen === DEFAULT_ACCENT)
153
+ return depth === 'truecolor' ? truecolorTheme : colorTheme;
154
+ return makeColorTheme(depth, face, chosen);
155
+ }