@nbtca/prompt 1.5.22 → 1.5.24

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.
Files changed (38) hide show
  1. package/dist/app/ambient.js +98 -0
  2. package/dist/app/app.js +3 -2
  3. package/dist/app/chrome.js +6 -2
  4. package/dist/app/views/docs-render.js +23 -15
  5. package/dist/app/views/docs.js +3 -0
  6. package/dist/app/views/events-render.js +57 -21
  7. package/dist/app/views/events.js +62 -9
  8. package/dist/app/views/home.js +66 -31
  9. package/dist/app/views/schedule-render.js +9 -2
  10. package/dist/app/views/schedule.js +7 -1
  11. package/dist/app/views/settings-render.js +13 -2
  12. package/dist/app/views/settings.js +27 -1
  13. package/dist/art/bitmaps.js +76 -0
  14. package/dist/art/glyphs.js +101 -0
  15. package/dist/art/motifs.js +198 -0
  16. package/dist/art/noise.js +43 -0
  17. package/dist/art/planet.js +184 -0
  18. package/dist/art/scene.js +446 -0
  19. package/dist/config/preferences.js +8 -1
  20. package/dist/core/components/empty-state.js +50 -0
  21. package/dist/core/components/menu.js +2 -2
  22. package/dist/core/components/picture.js +18 -0
  23. package/dist/core/logo.js +65 -43
  24. package/dist/core/pixel-art-fine.js +157 -0
  25. package/dist/core/pixel-art.js +223 -0
  26. package/dist/core/theme.js +1 -1
  27. package/dist/features/calendar-heatmap.js +35 -10
  28. package/dist/features/calendar.js +2 -2
  29. package/dist/features/event-art.js +16 -0
  30. package/dist/features/schedule-view.js +10 -0
  31. package/dist/i18n/locales/en.json +14 -5
  32. package/dist/i18n/locales/zh.json +13 -4
  33. package/dist/logo/ascii-emblem-large.txt +26 -0
  34. package/dist/logo/ascii-emblem-medium.txt +19 -0
  35. package/dist/logo/ascii-emblem-small.txt +12 -0
  36. package/dist/logo/ascii-emblem-tiny.txt +9 -0
  37. package/package.json +4 -4
  38. package/dist/logo/ascii-logo.txt +0 -12
package/dist/core/logo.js CHANGED
@@ -5,8 +5,8 @@ import chalk from 'chalk';
5
5
  import { useUnicodeIcons } from './icons.js';
6
6
  import { APP_INFO } from '../config/data.js';
7
7
  import { typeReveal, materializeBraille, sleep } from './motion.js';
8
- import { brandGradient as brand, c, frameLeft, space } from './theme.js';
9
- import { visualWidth } from './text.js';
8
+ import { brandGradient as brand, c } from './theme.js';
9
+ import { visualWidth, wrapAnsiWithIndent } from './text.js';
10
10
  const __dirname = dirname(fileURLToPath(import.meta.url));
11
11
  const TAGLINE = 'To be at the intersection of technology and liberal arts.';
12
12
  const FINAL_FRAME_MS = 400;
@@ -23,47 +23,55 @@ const LOGO_TIERS = [
23
23
  { file: 'ca-dotmatrix.txt', minCols: 44, minRows: 24 },
24
24
  { file: 'ca-dotmatrix-small.txt', minCols: 0, minRows: 0 },
25
25
  ];
26
- function dotmatrixFile() {
27
- const cols = process.stdout.columns;
28
- const rows = process.stdout.rows;
29
- const tier = LOGO_TIERS.find((t) => cols >= t.minCols && rows >= t.minRows);
30
- return tier?.file ?? 'ca-dotmatrix-small.txt';
31
- }
26
+ const ASCII_EMBLEMS = [
27
+ 'ascii-emblem-large.txt',
28
+ 'ascii-emblem-medium.txt',
29
+ 'ascii-emblem-small.txt',
30
+ 'ascii-emblem-tiny.txt',
31
+ ];
32
32
  function paint(text, color) {
33
33
  return color ? brand(text) : text;
34
34
  }
35
- function loadArt() {
36
- const art = useUnicodeIcons() ? readArt(dotmatrixFile()) : readArt('ascii-logo.txt');
37
- return art ?? 'NBTCA';
38
- }
39
- export function startupFitsTerminal(rows, cols, art) {
40
- const lines = art.split('\n');
41
- const fitsRows = rows === undefined || rows >= lines.length + 5;
42
- const fitsCols = cols === undefined || lines.every((line) => visualWidth(line) <= cols);
43
- return fitsRows && fitsCols;
35
+ function logoContent() {
36
+ const cols = Number.isFinite(process.stdout.columns) ? process.stdout.columns : undefined;
37
+ const rows = Number.isFinite(process.stdout.rows) ? process.stdout.rows : undefined;
38
+ const width = cols === undefined ? Number.POSITIVE_INFINITY : Math.max(1, cols);
39
+ const color = !process.env['NO_COLOR'];
40
+ const metadata = [
41
+ ...wrapAnsiWithIndent(TAGLINE, width, '').map((line) => paint(line, color)),
42
+ ...wrapAnsiWithIndent(`@nbtca/prompt v${APP_INFO.version}`, width, '').map((line) => chalk.dim(line)),
43
+ ];
44
+ const files = [
45
+ ...(useUnicodeIcons()
46
+ ? LOGO_TIERS.filter((tier) => (cols ?? 0) >= tier.minCols && (rows ?? 0) >= tier.minRows).map((tier) => tier.file)
47
+ : []),
48
+ ...ASCII_EMBLEMS,
49
+ undefined,
50
+ ];
51
+ for (const file of files) {
52
+ const art = file ? readArt(file) : 'NBTCA';
53
+ if (!art)
54
+ continue;
55
+ const lines = art.split('\n');
56
+ if (lines.every((line) => visualWidth(line) <= width) &&
57
+ (rows === undefined || lines.length + metadata.length + 3 <= rows)) {
58
+ return { art, metadata };
59
+ }
60
+ }
61
+ return undefined;
44
62
  }
45
63
  export function buildLogoLines() {
46
- const color = !process.env['NO_COLOR'];
47
- const paintedArt = paint(loadArt(), color).split('\n');
64
+ const content = logoContent();
65
+ if (!content)
66
+ return [];
48
67
  return [
49
68
  '',
50
- ...paintedArt,
69
+ ...paint(content.art, !process.env['NO_COLOR']).split('\n'),
51
70
  '',
52
- color ? brand(TAGLINE) : TAGLINE,
53
- chalk.dim(`@nbtca/prompt v${APP_INFO.version}`),
71
+ ...content.metadata,
54
72
  '',
55
73
  ];
56
74
  }
57
- export function startupOffset(cols, width) {
58
- if (cols === undefined)
59
- return 0;
60
- return Math.max(0, Math.min(frameLeft(cols) + space.indent.length, cols - width));
61
- }
62
- function indentBlock(text, cols) {
63
- const lines = text.split('\n');
64
- const pad = ' '.repeat(startupOffset(cols, Math.max(...lines.map(visualWidth))));
65
- return lines.map((line) => pad + line).join('\n');
66
- }
67
75
  function skipOnKeypress() {
68
76
  const controller = new AbortController();
69
77
  const stdin = process.stdin;
@@ -92,27 +100,41 @@ function skipOnKeypress() {
92
100
  export async function runStartup() {
93
101
  if (!process.stdout.isTTY)
94
102
  return;
95
- const art = loadArt();
96
- if (!startupFitsTerminal(process.stdout.rows, process.stdout.columns, art))
103
+ const content = logoContent();
104
+ if (!content)
97
105
  return;
98
- const cols = process.stdout.columns;
99
106
  const color = !process.env['NO_COLOR'];
100
107
  const skip = skipOnKeypress();
101
108
  process.stdout.write('\n');
102
109
  try {
103
- await materializeBraille(art, (s) => indentBlock(paint(s, color), cols), {
104
- paintProgress: (s) => indentBlock(color ? c.brand(s) : s, cols),
110
+ await materializeBraille(content.art, (s) => paint(s, color), {
111
+ paintProgress: (s) => (color ? c.brand(s) : s),
112
+ signal: skip.signal,
113
+ });
114
+ await typeReveal(['', ...content.metadata, ''], {
105
115
  signal: skip.signal,
106
116
  });
107
- await typeReveal([
108
- '',
109
- indentBlock(color ? brand(TAGLINE) : TAGLINE, cols),
110
- indentBlock(chalk.dim(`@nbtca/prompt v${APP_INFO.version}`), cols),
111
- '',
112
- ], { signal: skip.signal });
113
117
  await sleep(FINAL_FRAME_MS, skip.signal);
114
118
  }
115
119
  finally {
116
120
  skip.release();
117
121
  }
118
122
  }
123
+ const EMBLEM_FILES = {
124
+ unicode: ['ca-dotmatrix-large.txt', 'ca-dotmatrix.txt', 'ca-dotmatrix-small.txt'],
125
+ ascii: ASCII_EMBLEMS,
126
+ };
127
+ /** The largest emblem that fits the box, painted with the brand gradient; undefined when none fits. */
128
+ export function emblemLines(maxCols, maxRows) {
129
+ const files = EMBLEM_FILES[useUnicodeIcons() ? 'unicode' : 'ascii'];
130
+ for (const file of files) {
131
+ const art = readArt(file);
132
+ if (!art)
133
+ continue;
134
+ const lines = art.split('\n');
135
+ if (lines.length <= maxRows && lines.every((line) => visualWidth(line) <= maxCols)) {
136
+ return paint(art, !process.env['NO_COLOR']).split('\n');
137
+ }
138
+ }
139
+ return undefined;
140
+ }
@@ -0,0 +1,157 @@
1
+ import chalk from 'chalk';
2
+ const HALF_BLOCK_DENSITY = { x: 1, y: 2 };
3
+ const BRAILLE_ROWS = 4;
4
+ const BRAILLE_BASE = 0x2800;
5
+ // Dot order of a Braille cell as [column, row]: bits 0 to 7.
6
+ const BRAILLE_DOTS = [
7
+ [0, 0],
8
+ [0, 1],
9
+ [0, 2],
10
+ [1, 0],
11
+ [1, 1],
12
+ [1, 2],
13
+ [0, 3],
14
+ [1, 3],
15
+ ];
16
+ function rgb(hex) {
17
+ return [1, 3, 5].map((index) => Number.parseInt(hex.slice(index, index + 2), 16));
18
+ }
19
+ function hex(value) {
20
+ return `#${value.map((channel) => Math.round(channel).toString(16).padStart(2, '0')).join('')}`;
21
+ }
22
+ function luminance(color) {
23
+ return (0.2126 * color[0] + 0.7152 * color[1] + 0.0722 * color[2]) / 255;
24
+ }
25
+ function average(colors) {
26
+ const sum = colors.reduce((total, color) => [total[0] + color[0], total[1] + color[1], total[2] + color[2]], [0, 0, 0]);
27
+ return [sum[0] / colors.length, sum[1] / colors.length, sum[2] / colors.length];
28
+ }
29
+ function distance(a, b) {
30
+ return (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2;
31
+ }
32
+ function solid(pixels) {
33
+ return pixels.filter((pixel) => pixel !== undefined);
34
+ }
35
+ function pixelAt(bitmap, x, y) {
36
+ const symbol = bitmap.rows[y]?.[x];
37
+ const color = symbol === undefined || symbol === ' ' ? undefined : bitmap.palette[symbol];
38
+ return color === undefined ? undefined : rgb(color);
39
+ }
40
+ function cellPixels(bitmap, col, row) {
41
+ const { x, y } = bitmap.density ?? HALF_BLOCK_DENSITY;
42
+ return Array.from({ length: y }, (_, dy) => Array.from({ length: x }, (_, dx) => pixelAt(bitmap, col * x + dx, row * y + dy)));
43
+ }
44
+ function blend(pixels) {
45
+ const present = solid(pixels);
46
+ return present.length > 0 && present.length * 2 >= pixels.length ? average(present) : undefined;
47
+ }
48
+ function halfBlockCell(pixels) {
49
+ const middle = Math.ceil(pixels.length / 2);
50
+ const top = blend(pixels.slice(0, middle).flat());
51
+ const bottom = blend(pixels.slice(middle).flat());
52
+ if (top === undefined && bottom === undefined)
53
+ return ' ';
54
+ if (bottom === undefined)
55
+ return chalk.hex(hex(top ?? [0, 0, 0]))('▀');
56
+ if (top === undefined)
57
+ return chalk.hex(hex(bottom))('▄');
58
+ return chalk.hex(hex(top)).bgHex(hex(bottom))('▀');
59
+ }
60
+ const QUADRANTS = [
61
+ ' ',
62
+ '▘',
63
+ '▝',
64
+ '▀',
65
+ '▖',
66
+ '▌',
67
+ '▞',
68
+ '▛',
69
+ '▗',
70
+ '▚',
71
+ '▐',
72
+ '▜',
73
+ '▄',
74
+ '▙',
75
+ '▟',
76
+ '█',
77
+ ];
78
+ // Cells whose two colours differ by less than this are drawn as one smooth colour.
79
+ const FLAT_CONTRAST = 0.07;
80
+ // A solid quadrant glyph is kept over Braille dots while its error stays within this factor of theirs.
81
+ const QUADRANT_TOLERANCE = 1.8;
82
+ function splitTwoColors(pixels) {
83
+ let dark = pixels.reduce((best, pixel) => (luminance(pixel) < luminance(best) ? pixel : best));
84
+ let light = pixels.reduce((best, pixel) => (luminance(pixel) > luminance(best) ? pixel : best));
85
+ let lit = pixels.map(() => false);
86
+ for (let round = 0; round < 3; round++) {
87
+ lit = pixels.map((pixel) => distance(pixel, light) < distance(pixel, dark));
88
+ const lights = pixels.filter((_, index) => lit[index] === true);
89
+ const darks = pixels.filter((_, index) => lit[index] === false);
90
+ if (lights.length > 0)
91
+ light = average(lights);
92
+ if (darks.length > 0)
93
+ dark = average(darks);
94
+ }
95
+ return { light, dark, lit };
96
+ }
97
+ /**
98
+ * One cell of a fine bitmap. Flat areas become a single smooth colour, edges that follow the 2 × 2 grid
99
+ * become solid quadrant blocks, and everything else, such as thin lines and slopes, uses Braille dots.
100
+ */
101
+ function fineCell(pixels) {
102
+ const grid = BRAILLE_DOTS.map(([column, row]) => {
103
+ const source = pixels[Math.min(pixels.length - 1, Math.floor((row * pixels.length) / BRAILLE_ROWS))];
104
+ return source?.[Math.min(source.length - 1, Math.floor((column * source.length) / 2))];
105
+ });
106
+ const present = solid(grid);
107
+ if (present.length === 0)
108
+ return ' ';
109
+ const hasGap = present.length < grid.length;
110
+ const { light, dark } = splitTwoColors(present);
111
+ const lit = grid.map((pixel) => pixel !== undefined && distance(pixel, light) < distance(pixel, dark));
112
+ if (!hasGap && Math.abs(luminance(light) - luminance(dark)) < FLAT_CONTRAST) {
113
+ return chalk.hex(hex(average(present)))('█');
114
+ }
115
+ if (!hasGap) {
116
+ const quadrantOf = (index) => {
117
+ const [column, row] = BRAILLE_DOTS[index] ?? [0, 0];
118
+ return (row >= 2 ? 2 : 0) + column;
119
+ };
120
+ const mask = grid.reduce((bits, pixel, index) => {
121
+ if (pixel === undefined)
122
+ return bits;
123
+ const nearLight = distance(pixel, light) < distance(pixel, dark);
124
+ return nearLight ? bits | (1 << quadrantOf(index)) : bits;
125
+ }, 0);
126
+ const quadrantLit = (index) => ((mask >> quadrantOf(index)) & 1) === 1;
127
+ const error = (isLit) => grid.reduce((sum, pixel, index) => pixel === undefined ? sum : sum + distance(pixel, isLit(index) ? light : dark), 0);
128
+ if (error(quadrantLit) <= error((index) => lit[index] === true) * QUADRANT_TOLERANCE + 1) {
129
+ const glyph = QUADRANTS[mask] ?? '█';
130
+ if (mask === 0)
131
+ return chalk.hex(hex(dark))('█');
132
+ if (mask === 15)
133
+ return chalk.hex(hex(light))('█');
134
+ return chalk.hex(hex(light)).bgHex(hex(dark))(glyph);
135
+ }
136
+ }
137
+ const mask = lit.reduce((bits, on, index) => (on ? bits | (1 << index) : bits), 0);
138
+ const glyph = String.fromCodePoint(BRAILLE_BASE + mask);
139
+ const hasDark = grid.some((pixel, index) => pixel !== undefined && !lit[index]);
140
+ if (!lit.some(Boolean))
141
+ return hasGap ? ' ' : chalk.hex(hex(dark))('█');
142
+ if (!hasDark || hasGap)
143
+ return chalk.hex(hex(light))(glyph);
144
+ return chalk.hex(hex(light)).bgHex(hex(dark))(glyph);
145
+ }
146
+ /** Braille dots for fine 2 × 4 bitmaps, half blocks for chunky 1 × 2 ones. */
147
+ export function renderFine(bitmap, cols, rows) {
148
+ const fine = (bitmap.density?.y ?? 2) >= BRAILLE_ROWS;
149
+ return Array.from({ length: rows }, (_, row) => {
150
+ let line = '';
151
+ for (let col = 0; col < cols; col++) {
152
+ const pixels = cellPixels(bitmap, col, row);
153
+ line += fine ? fineCell(pixels) : halfBlockCell(pixels);
154
+ }
155
+ return line;
156
+ });
157
+ }
@@ -0,0 +1,223 @@
1
+ import chalk from 'chalk';
2
+ import { GLYPHS, GLYPH_COLS, GLYPH_ROWS } from '../art/glyphs.js';
3
+ import { getCapabilities } from './capabilities.js';
4
+ import { loadPreferences } from '../config/preferences.js';
5
+ import { renderFine } from './pixel-art-fine.js';
6
+ const DEFAULT_DENSITY = { x: 1, y: 2 };
7
+ const SAMPLES = GLYPH_COLS * GLYPH_ROWS;
8
+ // Terminals are mostly dark; transparent pixels count as this colour when a cell is only partly covered.
9
+ const BACKDROP = [20, 22, 28];
10
+ // Weight of matching a cell's average brightness against matching its shape.
11
+ const TONE_WEIGHT = 8;
12
+ // The densest glyph covers about this much of its cell, so full brightness maps to it.
13
+ const MAX_INK = 0.32;
14
+ // Share of a cell's average colour kept as its background tint.
15
+ const TINT = 0.3;
16
+ // Punctuation and shapes only: letters and digits read as noise inside a picture.
17
+ const ART_CHARS = ' .,:;-_~=+*^"|/\\()[]{}<>?#%&@$';
18
+ // Glyphs that differ mainly in density: flat areas switch between these without looking noisy.
19
+ const RAMP_CHARS = ' .:-=+*#%@';
20
+ // Brightness variance below which a cell counts as flat.
21
+ const FLAT_VARIANCE = 0.0004;
22
+ const GLYPH_TABLE = GLYPHS.map((hex, index) => {
23
+ const cover = Float32Array.from({ length: SAMPLES }, (_, sample) => Number.parseInt(hex.slice(sample * 2, sample * 2 + 2), 16) / 255);
24
+ return {
25
+ char: String.fromCharCode(0x20 + index),
26
+ cover,
27
+ ink: cover.reduce((sum, value) => sum + value, 0),
28
+ };
29
+ }).filter((glyph) => ART_CHARS.includes(glyph.char));
30
+ const RAMP_TABLE = GLYPH_TABLE.filter((glyph) => RAMP_CHARS.includes(glyph.char));
31
+ export function bitmapSize(bitmap) {
32
+ const { x, y } = bitmap.density ?? DEFAULT_DENSITY;
33
+ return {
34
+ cols: Math.ceil(Math.max(0, ...bitmap.rows.map((row) => row.length)) / x),
35
+ rows: Math.ceil(bitmap.rows.length / y),
36
+ };
37
+ }
38
+ /** The finest picture the terminal can show and the user allows, falling back to plain ASCII. */
39
+ export function pictureMode() {
40
+ const caps = getCapabilities();
41
+ if (!caps.color || chalk.level === 0)
42
+ return 'tone';
43
+ if (caps.unicode && chalk.level >= 3 && loadPreferences().pictureDetail === 'fine')
44
+ return 'fine';
45
+ return 'color';
46
+ }
47
+ const parsed = new Map();
48
+ function rgbOf(hex) {
49
+ let value = parsed.get(hex);
50
+ if (!value) {
51
+ value = [1, 3, 5].map((index) => Number.parseInt(hex.slice(index, index + 2), 16));
52
+ parsed.set(hex, value);
53
+ }
54
+ return value;
55
+ }
56
+ function colorAt(bitmap, x, y) {
57
+ const symbol = bitmap.rows[y]?.[x];
58
+ const color = symbol === undefined || symbol === ' ' ? undefined : bitmap.palette[symbol];
59
+ return color === undefined ? undefined : rgbOf(color);
60
+ }
61
+ /** The colour at a fractional position, blended from the four nearest pixels. */
62
+ function smoothAt(bitmap, fx, fy) {
63
+ const x0 = Math.floor(fx);
64
+ const y0 = Math.floor(fy);
65
+ const tx = fx - x0;
66
+ const ty = fy - y0;
67
+ const corners = [
68
+ [colorAt(bitmap, x0, y0), (1 - tx) * (1 - ty)],
69
+ [colorAt(bitmap, x0 + 1, y0), tx * (1 - ty)],
70
+ [colorAt(bitmap, x0, y0 + 1), (1 - tx) * ty],
71
+ [colorAt(bitmap, x0 + 1, y0 + 1), tx * ty],
72
+ ];
73
+ if (corners.some(([color, weight]) => color === undefined && weight > 0.05)) {
74
+ return colorAt(bitmap, Math.round(fx), Math.round(fy));
75
+ }
76
+ const out = [0, 0, 0];
77
+ let total = 0;
78
+ for (const [color, weight] of corners) {
79
+ if (color === undefined)
80
+ continue;
81
+ out[0] += color[0] * weight;
82
+ out[1] += color[1] * weight;
83
+ out[2] += color[2] * weight;
84
+ total += weight;
85
+ }
86
+ return total === 0 ? undefined : [out[0] / total, out[1] / total, out[2] / total];
87
+ }
88
+ /** The pixels of one cell, sampled onto the 4 × 8 grid the glyph table uses. */
89
+ function sampleCell(bitmap, col, row) {
90
+ const { x: dx, y: dy } = bitmap.density ?? DEFAULT_DENSITY;
91
+ const cell = {
92
+ r: new Float32Array(SAMPLES),
93
+ g: new Float32Array(SAMPLES),
94
+ b: new Float32Array(SAMPLES),
95
+ filled: 0,
96
+ };
97
+ for (let j = 0; j < GLYPH_ROWS; j++) {
98
+ for (let i = 0; i < GLYPH_COLS; i++) {
99
+ const color = bitmap.smooth
100
+ ? smoothAt(bitmap, col * dx + ((i + 0.5) * dx) / GLYPH_COLS - 0.5, row * dy + ((j + 0.5) * dy) / GLYPH_ROWS - 0.5)
101
+ : colorAt(bitmap, col * dx + Math.min(dx - 1, Math.floor((i * dx) / GLYPH_COLS)), row * dy + Math.min(dy - 1, Math.floor((j * dy) / GLYPH_ROWS)));
102
+ const index = j * GLYPH_COLS + i;
103
+ const [r, g, b] = color ?? BACKDROP;
104
+ cell.r[index] = r;
105
+ cell.g[index] = g;
106
+ cell.b[index] = b;
107
+ if (color !== undefined)
108
+ cell.filled++;
109
+ }
110
+ }
111
+ return cell;
112
+ }
113
+ const luma = (r, g, b) => (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;
114
+ const clamp = (value) => Math.round(Math.min(255, Math.max(0, value)));
115
+ /**
116
+ * The glyph whose ink best matches the brightness of each part of the cell. `carry` is error diffused in from
117
+ * neighbouring cells; it shifts the target brightness, not the shape.
118
+ */
119
+ function pickGlyph(cell, gamma, carry) {
120
+ const bright = new Float32Array(SAMPLES);
121
+ let total = 0;
122
+ for (let index = 0; index < SAMPLES; index++) {
123
+ const value = MAX_INK * Math.pow(luma(cell.r[index] ?? 0, cell.g[index] ?? 0, cell.b[index] ?? 0), gamma);
124
+ bright[index] = value;
125
+ total += value;
126
+ }
127
+ if (total / SAMPLES < 0.004)
128
+ return undefined;
129
+ const mean = Math.max(0, total / SAMPLES + carry);
130
+ const shift = mean - total / SAMPLES;
131
+ let variance = 0;
132
+ for (let index = 0; index < SAMPLES; index++)
133
+ variance += ((bright[index] ?? 0) - total / SAMPLES) ** 2 / SAMPLES;
134
+ const candidates = variance < FLAT_VARIANCE ? RAMP_TABLE : GLYPH_TABLE;
135
+ let best;
136
+ let bestCost = Number.POSITIVE_INFINITY;
137
+ for (const glyph of candidates) {
138
+ const glyphMean = glyph.ink / SAMPLES;
139
+ let cost = TONE_WEIGHT * SAMPLES * (mean - glyphMean) ** 2;
140
+ for (let index = 0; index < SAMPLES; index++)
141
+ cost += ((bright[index] ?? 0) + shift - mean - ((glyph.cover[index] ?? 0) - glyphMean)) ** 2;
142
+ if (cost < bestCost) {
143
+ bestCost = cost;
144
+ best = glyph;
145
+ }
146
+ }
147
+ return best && { glyph: best, error: mean - best.ink / SAMPLES };
148
+ }
149
+ /** Plain characters only. */
150
+ function toneCell(cell, gamma, carry) {
151
+ const pick = pickGlyph(cell, gamma, carry);
152
+ return { text: pick?.glyph.char ?? ' ', error: pick?.error ?? 0 };
153
+ }
154
+ /**
155
+ * Characters follow the brightness and shape of the picture; the colour lives in the characters themselves, on
156
+ * the terminal's own dark background with only a faint tint.
157
+ */
158
+ function colorCell(cell, gamma, carry) {
159
+ const pick = pickGlyph(cell, gamma, carry);
160
+ if (!pick || pick.glyph.char === ' ')
161
+ return { text: ' ', error: pick?.error ?? 0 };
162
+ const { glyph, error } = pick;
163
+ const mean = [0, 0, 0];
164
+ const ink = [0, 0, 0];
165
+ for (let index = 0; index < SAMPLES; index++) {
166
+ const weight = glyph.cover[index] ?? 0;
167
+ const pixel = [cell.r[index] ?? 0, cell.g[index] ?? 0, cell.b[index] ?? 0];
168
+ for (let channel = 0; channel < 3; channel++) {
169
+ mean[channel] = (mean[channel] ?? 0) + (pixel[channel] ?? 0) / SAMPLES;
170
+ ink[channel] = (ink[channel] ?? 0) + (weight * (pixel[channel] ?? 0)) / glyph.ink;
171
+ }
172
+ }
173
+ const peak = Math.max(1, ...ink);
174
+ const level = 0.4 + 0.6 * Math.pow(luma(...ink), 0.6);
175
+ const fg = ink.map((value) => clamp((value / peak) * 255 * level));
176
+ const text = chalk.rgb(fg[0] ?? 0, fg[1] ?? 0, fg[2] ?? 0);
177
+ if (chalk.level < 3)
178
+ return { text: text(glyph.char), error };
179
+ const bg = mean.map((value) => clamp(value * TINT));
180
+ return { text: text.bgRgb(bg[0] ?? 0, bg[1] ?? 0, bg[2] ?? 0)(glyph.char), error };
181
+ }
182
+ // Floyd–Steinberg weights for the cell to the right, and below-behind, below, below-ahead. Passing on only
183
+ // part of the error, as Atkinson dithering does, keeps flat areas calm.
184
+ const DIFFUSION = 0.8;
185
+ const DIFFUSE = [7 / 16, 3 / 16, 5 / 16, 1 / 16].map((weight) => weight * DIFFUSION);
186
+ const MAX_CARRY = 0.12;
187
+ /**
188
+ * Draws a bitmap as ASCII art, one character per terminal cell. With colour the characters carry the picture's
189
+ * hue on a tinted background; without it they carry only brightness, like a classic density ramp.
190
+ * Brightness error is diffused to neighbouring cells in serpentine order, as libcaca and AAlib do, so gradients
191
+ * mix the two nearest densities instead of stepping.
192
+ */
193
+ export function renderBitmap(bitmap, mode = pictureMode(),
194
+ /** Below 1 lifts dark pixels so small icons stay visible; above 1 leaves broad backgrounds empty. */
195
+ gamma = 0.7) {
196
+ const { cols, rows } = bitmapSize(bitmap);
197
+ if (mode === 'fine')
198
+ return renderFine(bitmap, cols, rows);
199
+ let carry = new Float32Array(cols + 2);
200
+ let ahead = new Float32Array(cols + 2);
201
+ return Array.from({ length: rows }, (_, row) => {
202
+ const forward = row % 2 === 0;
203
+ const direction = forward ? 1 : -1;
204
+ const cells = Array.from({ length: cols }, () => ' ');
205
+ for (let step = 0; step < cols; step++) {
206
+ const col = forward ? step : cols - 1 - step;
207
+ const cell = sampleCell(bitmap, col, row);
208
+ if (cell.filled === 0)
209
+ continue;
210
+ const carried = Math.max(-MAX_CARRY, Math.min(MAX_CARRY, carry[col + 1] ?? 0));
211
+ const drawn = mode === 'color' ? colorCell(cell, gamma, carried) : toneCell(cell, gamma, carried);
212
+ cells[col] = drawn.text;
213
+ const error = drawn.error;
214
+ carry[col + 1 + direction] = (carry[col + 1 + direction] ?? 0) + error * DIFFUSE[0];
215
+ ahead[col + 1 - direction] = (ahead[col + 1 - direction] ?? 0) + error * DIFFUSE[1];
216
+ ahead[col + 1] = (ahead[col + 1] ?? 0) + error * DIFFUSE[2];
217
+ ahead[col + 1 + direction] = (ahead[col + 1 + direction] ?? 0) + error * DIFFUSE[3];
218
+ }
219
+ [carry, ahead] = [ahead, new Float32Array(cols + 2)];
220
+ const line = cells.join('');
221
+ return mode === 'tone' ? line.replace(/\s+$/, '') : line;
222
+ });
223
+ }
@@ -82,7 +82,7 @@ export const type = {
82
82
  heading: (s) => chalk.bold(s),
83
83
  label: (s) => s,
84
84
  body: (s) => s,
85
- hint: (s) => chalk.dim(s),
85
+ hint: (s) => s,
86
86
  active: (s) => chalk.bold(c.brand(s)),
87
87
  cursor: (s) => chalk.bgHex('#0ea5e9').black(s),
88
88
  };
@@ -1,5 +1,6 @@
1
+ import chalk from 'chalk';
1
2
  import { pickIcon } from '../core/icons.js';
2
- import { bodyWidth, c, space, type } from '../core/theme.js';
3
+ import { bodyWidth, c, glyph, space, type } from '../core/theme.js';
3
4
  import { t, getCurrentLanguage } from '../i18n/index.js';
4
5
  import { visualWidth } from '../core/text.js';
5
6
  function parseBucketDate(date) {
@@ -27,7 +28,7 @@ function levelCell(count, useColor) {
27
28
  const cell = pickIcon(unicode, ascii);
28
29
  if (!useColor)
29
30
  return cell;
30
- return level === 0 ? type.hint(cell) : c.success(cell);
31
+ return level === 0 ? c.muted(cell) : c.success(cell);
31
32
  }
32
33
  function placeMonthLabels(anchors, width, format, strict) {
33
34
  let line = '';
@@ -46,21 +47,43 @@ function placeMonthLabels(anchors, width, format, strict) {
46
47
  }
47
48
  return line;
48
49
  }
50
+ const DAY_MS = 86_400_000;
51
+ function isoDate(ms) {
52
+ const d = new Date(ms);
53
+ return `${d.getUTCFullYear()}-${String(d.getUTCMonth() + 1).padStart(2, '0')}-${String(d.getUTCDate()).padStart(2, '0')}`;
54
+ }
55
+ function gridGeometry(today, cols) {
56
+ const cellWidth = cols < GRID_PREFIX_WIDTH + MAX_WEEK_COLUMNS * 2 ? 1 : 2;
57
+ const availableColumns = Math.floor((cols - GRID_PREFIX_WIDTH) / cellWidth);
58
+ const numCols = Math.max(1, Math.min(MAX_WEEK_COLUMNS, availableColumns));
59
+ const todayMs = Date.UTC(today.getFullYear(), today.getMonth(), today.getDate());
60
+ const gridEndMs = todayMs + (6 - utcDayToMonIndex(new Date(todayMs).getUTCDay())) * DAY_MS;
61
+ return { cellWidth, numCols, todayMs, gridStartMs: gridEndMs - (numCols * 7 - 1) * DAY_MS };
62
+ }
63
+ /** First and last selectable day of the grid drawn at this width; days after today are not selectable. */
64
+ export function heatmapRange(today, cols = Number.POSITIVE_INFINITY) {
65
+ const { gridStartMs, todayMs } = gridGeometry(today, bodyWidth(cols));
66
+ return { start: isoDate(gridStartMs), end: isoDate(todayMs) };
67
+ }
68
+ export function shiftHeatmapDay(date, days) {
69
+ return isoDate(parseBucketDate(date).getTime() + days * DAY_MS);
70
+ }
71
+ function cursorCell(count, useColor) {
72
+ if (!useColor || chalk.level === 0)
73
+ return glyph.dot();
74
+ const level = Math.max(0, Math.min(count, LEVEL_GLYPHS.length - 1));
75
+ const [unicode, ascii] = LEVEL_GLYPHS[level] ?? LEVEL_GLYPHS[0];
76
+ return type.cursor(pickIcon(unicode, ascii));
77
+ }
49
78
  export function renderHeatmap(buckets, today, options) {
50
79
  const useColor = options?.color === true;
51
80
  const trans = t();
52
81
  const cols = bodyWidth(options?.cols ?? Number.POSITIVE_INFINITY);
53
- const cellWidth = cols < GRID_PREFIX_WIDTH + MAX_WEEK_COLUMNS * 2 ? 1 : 2;
54
- const availableColumns = Math.floor((cols - GRID_PREFIX_WIDTH) / cellWidth);
55
- const numCols = Math.max(1, Math.min(MAX_WEEK_COLUMNS, availableColumns));
82
+ const { cellWidth, numCols, gridStartMs } = gridGeometry(today, cols);
56
83
  const countByDate = new Map();
57
84
  for (const b of buckets) {
58
85
  countByDate.set(b.date, b.count);
59
86
  }
60
- const todayProxy = new Date(Date.UTC(today.getFullYear(), today.getMonth(), today.getDate()));
61
- const todayMonIndex = utcDayToMonIndex(todayProxy.getUTCDay());
62
- const gridEndMs = todayProxy.getTime() + (6 - todayMonIndex) * 86400000; // Sunday of today's week
63
- const gridStartMs = gridEndMs - (numCols * 7 - 1) * 86400000;
64
87
  const gridStart = new Date(gridStartMs);
65
88
  const columns = [];
66
89
  let cursor = new Date(gridStart.getTime());
@@ -127,7 +150,9 @@ export function renderHeatmap(buckets, today, options) {
127
150
  const cell = col[row];
128
151
  if (cell === null || cell === undefined)
129
152
  return ' ';
130
- return levelCell(cell.count, useColor);
153
+ return cell.date === options?.cursor
154
+ ? cursorCell(cell.count, useColor)
155
+ : levelCell(cell.count, useColor);
131
156
  });
132
157
  lines.push(`${space.indent}${wdLabel} ${cells.join(cellWidth === 2 ? ' ' : '')}`);
133
158
  }
@@ -201,7 +201,7 @@ function styleTitle(title, style) {
201
201
  const match = SOURCE_TAG.exec(title);
202
202
  if (!match?.[1] || !match[2])
203
203
  return style(title);
204
- return `${type.hint(match[1])}${match[2]}${style(title.slice(match[0].length))}`;
204
+ return `${c.muted(match[1])}${match[2]}${style(title.slice(match[0].length))}`;
205
205
  }
206
206
  const TIME_COLUMN = ' 00:00'.length;
207
207
  export function eventWhen(e) {
@@ -227,7 +227,7 @@ export function renderEventBriefLines(e, now, cols = Number.POSITIVE_INFINITY) {
227
227
  ? c.brand
228
228
  : proximity === 'week'
229
229
  ? type.body
230
- : type.hint;
230
+ : c.muted;
231
231
  const marker = proximity === 'today' ? type.active(pickIcon('●', '*')) : dateStyle(glyph.sep());
232
232
  const titleStyled = styleTitle(e.title, proximity === 'today' ? type.active : type.body);
233
233
  const content = `${dateStyle(eventWhen(e))} ${type.hint(dot)} ${titleStyled}${type.hint(recurringMark(e))}`;
@@ -0,0 +1,16 @@
1
+ import { eventIconConference, eventIconDefault, eventIconMeeting, eventIconRepair, eventIconWorkshop, } from '../art/bitmaps.js';
2
+ const RULES = [
3
+ [/维修|义诊|修电脑|repair/i, eventIconRepair],
4
+ [/工作坊|培训|workshop|training|hands-?on/i, eventIconWorkshop],
5
+ [/大会|conference|nwdc|summit|meetup/i, eventIconConference],
6
+ [/例会|周会|会议|meeting|standup/i, eventIconMeeting],
7
+ ];
8
+ /** Picks the picture from the title first, then the description, so a description cannot override the title. */
9
+ export function eventIcon(title, description = '') {
10
+ for (const text of [title, description]) {
11
+ const rule = RULES.find(([pattern]) => pattern.test(text));
12
+ if (rule)
13
+ return rule[1];
14
+ }
15
+ return eventIconDefault;
16
+ }
@@ -56,6 +56,16 @@ export function todayLines(cached, now = new Date(), cols = Number.POSITIVE_INFI
56
56
  return [];
57
57
  }
58
58
  }
59
+ /** True when the saved timetable has no class today; false on any other answer, including a broken cache. */
60
+ export function isRestDay(cached, now = new Date()) {
61
+ try {
62
+ const schedule = scheduleOf(cached);
63
+ return schedule.meetingsOnDay(schedule.weekAt(now), schedule.weekdayAt(now)).length === 0;
64
+ }
65
+ catch {
66
+ return false;
67
+ }
68
+ }
59
69
  export function weekAheadInfo(cached, now = new Date()) {
60
70
  try {
61
71
  const schedule = scheduleOf(cached);