@iwascreatedtocreate/asciikit 0.1.1 → 0.1.2

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/LICENSE CHANGED
@@ -1,24 +1,24 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 iwascreatedtocreate
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
22
-
23
- FIGlet and TOIlet fonts included in dist/fonts are the work of their respective
24
- authors and are distributed under their original terms.
1
+ MIT License
2
+
3
+ Copyright (c) 2026 sia!
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
23
+ FIGlet and TOIlet fonts included in dist/fonts are the work of their respective
24
+ authors and are distributed under their original terms.
package/README.md CHANGED
@@ -1,92 +1,122 @@
1
- # asciikit
2
-
3
- ASCII art for React & Next.js. **332 FIGlet fonts you import like icons**, a full FIGfont smushing engine, borders, shadows, gradients, animations and image-to-ASCII.
4
-
5
- ```bash
6
- npm i @iwascreatedtocreate/asciikit
7
- ```
8
-
9
- ```tsx
10
- import { Ascii } from '@iwascreatedtocreate/asciikit/react';
11
- import { Slant } from '@iwascreatedtocreate/asciikit/fonts';
12
-
13
- export default function Page() {
14
- return <Ascii text="Hello" font={Slant} border="rounded" />;
15
- }
16
- ```
17
-
18
- Live playground & font gallery: **https://asciikit.iwascreatedtocreate.com**
19
-
20
- ## Why
21
-
22
- - **Import fonts like icons** — `import { Slant, Doom, AnsiShadow } from '@iwascreatedtocreate/asciikit/fonts'`. Every font is its own module, so you only ship what you use.
23
- - **Server Components first** — `<Ascii>` renders on the server with zero client JS. When you animate, only the final string goes to the browser, never the font.
24
- - **A real FIGlet engine** — full width, fitting, all 6 horizontal + 5 vertical smushing rules, universal smushing, word wrap, alignment, RTL, FIGlet & TOIlet (`.flf` / `.tlf`) fonts. Output matches figlet.js / TAAG for 97%+ of fonts.
25
- - **Effects** — borders (15 styles), shadow, fill, flip, rotate, scale, invert, join/stack/overlay, gradients, ANSI colors for terminals.
26
- - **Animations** — scramble, typewriter, reveal, fall, flicker, glitch, wave, rain. Respects `prefers-reduced-motion`.
27
- - **Image → ASCII** — ramps, braille, edge tracing, Floyd–Steinberg / Atkinson / ordered dithering, color.
28
- - **Framework-free core** — everything works in Node, Bun, Deno, edge runtimes and CLIs.
29
-
30
- ## React
31
-
32
- ```tsx
33
- import { Ascii, AsciiImage, AsciiSpinner, AsciiBox, createAscii, useFont } from '@iwascreatedtocreate/asciikit/react';
34
-
35
- <Ascii text="Hello" /> // Standard built in
36
- <Ascii text="Hello" font={Slant} gradient="silver" glow />
37
- <Ascii text="Hi" font={Slant} border={{ style: 'double', title: 'v1' }} shadow />
38
- <Ascii text="Boot" font={AnsiShadow} animate={{ effect: 'scramble', trigger: 'visible' }} />
39
- <AsciiImage src="/me.jpg" columns={100} mode="braille" dither="atkinson" />
40
- <AsciiSpinner spinner="dots" text="loading" />
41
- <AsciiBox variant="rounded" title="note">{'multi\nline'}</AsciiBox>
42
-
43
- export const Logo = createAscii('ACME', { font: Slant }); // lucide-style factory
44
- const { font } = useFont('ansi-shadow'); // code-split loading
45
- ```
46
-
47
- ### `<Ascii>` props
48
-
49
- | prop | type |
50
- | --- | --- |
51
- | `text` / `children` | `string` |
52
- | `font` | `FontDefinition \| string` (registered name or raw `.flf`) |
53
- | `horizontalLayout`, `verticalLayout` | `'default' \| 'full' \| 'fitted' \| 'smush' \| 'universal-smush'` |
54
- | `horizontalRules`, `verticalRules` | toggle individual smushing rules |
55
- | `width`, `whitespaceBreak`, `align` | wrapping & alignment |
56
- | `letterSpacing`, `wordSpacing`, `lineGap`, `direction`, `trim` | spacing & direction |
57
- | `fill`, `replace`, `flip`, `rotate`, `scale`, `invert`, `shadow`, `border`, `padding`, `transform` | effects |
58
- | `color`, `gradient`, `gradientDirection`, `size`, `lineHeight`, `glow`, `fontFamily` | styling |
59
- | `animate` | effect name or `{ effect, duration, delay, loop, loopDelay, trigger, intensity, noise }` |
60
- | `as`, `label` | element & accessible label |
61
-
62
- ## Core
63
-
64
- ```ts
65
- import { render, ascii, pipe, box, shadow, fill, join, toAnsi, pixelsToAscii } from '@iwascreatedtocreate/asciikit';
66
- import { Standard } from '@iwascreatedtocreate/asciikit/fonts';
67
-
68
- render('Hello', { font: Standard, width: 60, align: 'center' });
69
- ascii('OK', { font: Standard, fill: '█', shadow: true, border: 'rounded' });
70
- console.log(toAnsi(render('deploy'), { gradient: 'sunset' }));
71
- ```
72
-
73
- ## Fonts
74
-
75
- ```ts
76
- import { Slant } from '@iwascreatedtocreate/asciikit/fonts'; // barrel (tree-shaken)
77
- import Ghost from '@iwascreatedtocreate/asciikit/fonts/ghost'; // direct path
78
- import { loadFont } from '@iwascreatedtocreate/asciikit/fonts/lazy'; // async by id or name
79
- import { fontList } from '@iwascreatedtocreate/asciikit/fonts/meta'; // metadata only
80
- import { parseFont, registerFont, setDefaultFont } from '@iwascreatedtocreate/asciikit';
81
- ```
82
-
83
- Tip for Next.js dev speed when importing many fonts from the barrel:
84
-
85
- ```js
86
- // next.config.js
87
- experimental: { optimizePackageImports: ['@iwascreatedtocreate/asciikit'] }
88
- ```
89
-
90
- ## License
91
-
92
- MIT. FIGlet/TOIlet fonts are © their respective authors and distributed under their original terms (bundled via the [figlet](https://github.com/patorjk/figlet.js) font collection).
1
+ # asciikit
2
+
3
+ [![npm](https://img.shields.io/npm/v/@iwascreatedtocreate/asciikit?color=black)](https://www.npmjs.com/package/@iwascreatedtocreate/asciikit)
4
+ [![downloads](https://img.shields.io/npm/dm/@iwascreatedtocreate/asciikit?color=black)](https://www.npmjs.com/package/@iwascreatedtocreate/asciikit)
5
+ [![ci](https://github.com/iwascreatedtocreate/asciikit/actions/workflows/ci.yml/badge.svg)](https://github.com/iwascreatedtocreate/asciikit/actions/workflows/ci.yml)
6
+
7
+ ASCII art for React & Next.js. **332 FIGlet fonts you import like icons**, a full FIGfont smushing engine, borders, shadows, gradients, animations and image-to-ASCII.
8
+
9
+ ```bash
10
+ npm i @iwascreatedtocreate/asciikit
11
+ ```
12
+
13
+ ```tsx
14
+ import { Ascii } from '@iwascreatedtocreate/asciikit/react';
15
+ import { Slant } from '@iwascreatedtocreate/asciikit/fonts';
16
+
17
+ export default function Page() {
18
+ return <Ascii text="Hello" font={Slant} border="rounded" />;
19
+ }
20
+ ```
21
+
22
+ Live playground & font gallery: **https://asciikit.iwascreatedtocreate.com**
23
+
24
+ ## Why
25
+
26
+ - **Import fonts like icons** — `import { Slant, Doom, AnsiShadow } from '@iwascreatedtocreate/asciikit/fonts'`. Every font is its own module, so you only ship what you use.
27
+ - **Server Components first** — `<Ascii>` renders on the server with zero client JS. When you animate, only the final string goes to the browser, never the font.
28
+ - **A real FIGlet engine** — full width, fitting, all 6 horizontal + 5 vertical smushing rules, universal smushing, word wrap, alignment, RTL, FIGlet & TOIlet (`.flf` / `.tlf`) fonts. Output matches figlet.js / TAAG for 97%+ of fonts.
29
+ - **Effects** — borders (15 styles), shadow, fill, flip, rotate, scale, invert, join/stack/overlay, gradients, ANSI colors for terminals.
30
+ - **Animations** — scramble, typewriter, reveal, fall, flicker, glitch, wave, rain. Respects `prefers-reduced-motion`.
31
+ - **Image → ASCII** — ramps, braille, edge tracing, Floyd–Steinberg / Atkinson / ordered dithering, color.
32
+ - **Framework-free core** — everything works in Node, Bun, Deno, edge runtimes and CLIs.
33
+ - **Export** — `toSVG()` anywhere (OG images, READMEs), `toPNG()` / `toCanvas()` in the browser.
34
+ - **CLI** — `npx @iwascreatedtocreate/asciikit "hello" -f slant -g sunset`.
35
+ - **Wide characters** — emoji and CJK count as two columns, so borders and alignment stay straight.
36
+ - **Zero dependencies.**
37
+
38
+ ## CLI
39
+
40
+ ```bash
41
+ npx @iwascreatedtocreate/asciikit "deploy ok" -f slant -g sunset -b rounded
42
+ echo "piped" | npx @iwascreatedtocreate/asciikit -f small
43
+ npx @iwascreatedtocreate/asciikit --list --preview Hi # every font
44
+ npx @iwascreatedtocreate/asciikit logo --svg logo.svg # also write an SVG
45
+ ```
46
+
47
+ Run `--help` for all options (fonts, width, align, layout, border, shadow, fill, gradient, color).
48
+
49
+ ## Export
50
+
51
+ ```ts
52
+ import { ascii, toSVG, toPNG, downloadFile } from '@iwascreatedtocreate/asciikit';
53
+
54
+ const art = ascii('Hello', { font: Slant });
55
+ const svg = toSVG(art, { gradient: 'silver', background: '#000', fontSize: 20 }); // string, works on the server
56
+ const png = await toPNG(art, { color: '#fff', background: '#000' }); // Blob, browser only
57
+ downloadFile('hello.png', png);
58
+ ```
59
+
60
+ ## React
61
+
62
+ ```tsx
63
+ import { Ascii, AsciiImage, AsciiSpinner, AsciiBox, createAscii, useFont } from '@iwascreatedtocreate/asciikit/react';
64
+
65
+ <Ascii text="Hello" /> // Standard built in
66
+ <Ascii text="Hello" font={Slant} gradient="silver" glow />
67
+ <Ascii text="Hi" font={Slant} border={{ style: 'double', title: 'v1' }} shadow />
68
+ <Ascii text="Boot" font={AnsiShadow} animate={{ effect: 'scramble', trigger: 'visible' }} />
69
+ <AsciiImage src="/me.jpg" columns={100} mode="braille" dither="atkinson" />
70
+ <AsciiSpinner spinner="dots" text="loading" />
71
+ <AsciiBox variant="rounded" title="note">{'multi\nline'}</AsciiBox>
72
+
73
+ export const Logo = createAscii('ACME', { font: Slant }); // lucide-style factory
74
+ const { font } = useFont('ansi-shadow'); // code-split loading
75
+ ```
76
+
77
+ ### `<Ascii>` props
78
+
79
+ | prop | type |
80
+ | --- | --- |
81
+ | `text` / `children` | `string` |
82
+ | `font` | `FontDefinition \| string` (registered name or raw `.flf`) |
83
+ | `horizontalLayout`, `verticalLayout` | `'default' \| 'full' \| 'fitted' \| 'smush' \| 'universal-smush'` |
84
+ | `horizontalRules`, `verticalRules` | toggle individual smushing rules |
85
+ | `width`, `whitespaceBreak`, `align` | wrapping & alignment |
86
+ | `letterSpacing`, `wordSpacing`, `lineGap`, `direction`, `trim` | spacing & direction |
87
+ | `fill`, `replace`, `flip`, `rotate`, `scale`, `invert`, `shadow`, `border`, `padding`, `transform` | effects |
88
+ | `color`, `gradient`, `gradientDirection`, `size`, `lineHeight`, `glow`, `fontFamily` | styling |
89
+ | `animate` | effect name or `{ effect, duration, delay, loop, loopDelay, trigger, intensity, noise }` |
90
+ | `as`, `label` | element & accessible label |
91
+
92
+ ## Core
93
+
94
+ ```ts
95
+ import { render, ascii, pipe, box, shadow, fill, join, toAnsi, pixelsToAscii } from '@iwascreatedtocreate/asciikit';
96
+ import { Standard } from '@iwascreatedtocreate/asciikit/fonts';
97
+
98
+ render('Hello', { font: Standard, width: 60, align: 'center' });
99
+ ascii('OK', { font: Standard, fill: '█', shadow: true, border: 'rounded' });
100
+ console.log(toAnsi(render('deploy'), { gradient: 'sunset' }));
101
+ ```
102
+
103
+ ## Fonts
104
+
105
+ ```ts
106
+ import { Slant } from '@iwascreatedtocreate/asciikit/fonts'; // barrel (tree-shaken)
107
+ import Ghost from '@iwascreatedtocreate/asciikit/fonts/ghost'; // direct path
108
+ import { loadFont } from '@iwascreatedtocreate/asciikit/fonts/lazy'; // async by id or name
109
+ import { fontList } from '@iwascreatedtocreate/asciikit/fonts/meta'; // metadata only
110
+ import { parseFont, registerFont, setDefaultFont } from '@iwascreatedtocreate/asciikit';
111
+ ```
112
+
113
+ Tip for Next.js dev speed when importing many fonts from the barrel:
114
+
115
+ ```js
116
+ // next.config.js
117
+ experimental: { optimizePackageImports: ['@iwascreatedtocreate/asciikit'] }
118
+ ```
119
+
120
+ ## License
121
+
122
+ MIT. FIGlet/TOIlet fonts are © their respective authors and distributed under their original terms (bundled via the [figlet](https://github.com/patorjk/figlet.js) font collection).
package/dist/animate.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { normalize, toLines } from './effects.js';
2
+ import { cells, fixCells } from './width.js';
2
3
  /** Effects that run forever by default (time based rather than progress based). */
3
4
  export const continuousEffects = ['glitch', 'wave', 'rain'];
4
5
  const DEFAULT_NOISE = '!<>-_\\/[]{}—=+*^?#________';
@@ -16,7 +17,7 @@ const ease = (t) => 1 - Math.pow(1 - Math.max(0, Math.min(1, t)), 3);
16
17
  * @param progress 0…1 for one-shot effects. Ignored by continuous effects (use `time`).
17
18
  */
18
19
  export function animationFrame(art, effect, progress, options = {}) {
19
- const grid = toLines(normalize(art)).map((l) => Array.from(l));
20
+ const grid = toLines(normalize(art)).map((l) => cells(l));
20
21
  const h = grid.length;
21
22
  const w = grid[0]?.length ?? 0;
22
23
  const p = Math.max(0, Math.min(1, progress));
@@ -27,7 +28,7 @@ export function animationFrame(art, effect, progress, options = {}) {
27
28
  const tick = Math.floor(time / 50);
28
29
  const rnd = (r, c, k = 0) => hash(r + seed * 31, c + k * 7919, seed);
29
30
  const noiseChar = (r, c, k) => noise[Math.floor(hash(r, c, k + seed) * noise.length)];
30
- const map = (fn) => grid.map((row, r) => row.map((ch, c) => fn(ch, r, c)).join('')).join('\n');
31
+ const map = (fn) => grid.map((row, r) => fixCells(row.map((ch, c) => fn(ch, r, c))).join('')).join('\n');
31
32
  switch (effect) {
32
33
  case 'typewriter': {
33
34
  const edge = p * (w + 1);
@@ -65,8 +66,8 @@ export function animationFrame(art, effect, progress, options = {}) {
65
66
  return grid
66
67
  .map((row, r) => {
67
68
  const off = Math.round(amp * Math.sin(time / 180 + r * 0.7));
68
- const line = row.join('');
69
- return off >= 0 ? (' '.repeat(off) + line).slice(0, w + amp) : line.slice(-off);
69
+ const shifted = off >= 0 ? [...Array(off).fill(' '), ...row].slice(0, w + amp) : row.slice(-off);
70
+ return fixCells(shifted).join('');
70
71
  })
71
72
  .join('\n');
72
73
  }
@@ -79,7 +80,7 @@ export function animationFrame(art, effect, progress, options = {}) {
79
80
  const shift = Math.round((hash(r, tick, 3) - 0.5) * 6 * intensity);
80
81
  line = shift > 0 ? [...Array(shift).fill(' '), ...line].slice(0, w) : line.slice(-shift).concat(Array(-shift).fill(' '));
81
82
  }
82
- return line.join('');
83
+ return fixCells(line).join('');
83
84
  })
84
85
  .join('\n');
85
86
  }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,141 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync, writeFileSync } from 'node:fs';
3
+ import { parseArgs } from 'node:util';
4
+ import { gradients } from './color.js';
5
+ import { ascii } from './compose.js';
6
+ import { boxStyles, toAnsi } from './effects.js';
7
+ import { toSVG } from './export.js';
8
+ import { loadFont } from './fonts/lazy.js';
9
+ import { fontList } from './fonts/meta.js';
10
+ const HELP = `asciikit — ASCII art in your terminal
11
+
12
+ usage
13
+ asciikit <text> [options]
14
+ echo "text" | asciikit [options]
15
+
16
+ options
17
+ -f, --font <name> font id or name (default: standard) e.g. slant, "ANSI Shadow"
18
+ -l, --list list all fonts (combine with --preview to render each one)
19
+ --preview <text> sample text for --list
20
+ -w, --width <n> wrap at n columns (default: terminal width)
21
+ -a, --align <a> left | center | right
22
+ --layout <l> default | full | fitted | smush | universal-smush
23
+ --letter-spacing <n> extra columns between characters
24
+ -b, --border [style] ${Object.keys(boxStyles).join(' | ')}
25
+ --title <text> border title
26
+ -s, --shadow drop shadow
27
+ --fill <char> replace every visible character
28
+ -g, --gradient <g> preset (${Object.keys(gradients).join(', ')}) or colors "#f00,#00f"
29
+ -d, --direction <d> horizontal | vertical | diagonal | radial
30
+ -c, --color <color> single text color
31
+ --no-color plain text, no ANSI colors
32
+ --svg <file> also write an SVG image
33
+ -v, --version print version
34
+ -h, --help show this help
35
+
36
+ examples
37
+ asciikit hello
38
+ asciikit "deploy ok" -f slant -g sunset -b rounded
39
+ asciikit --list --preview Hi
40
+ `;
41
+ function fail(message) {
42
+ process.stderr.write(`asciikit: ${message}\n`);
43
+ process.exit(1);
44
+ }
45
+ async function readStdin() {
46
+ if (process.stdin.isTTY)
47
+ return '';
48
+ const chunks = [];
49
+ for await (const c of process.stdin)
50
+ chunks.push(c);
51
+ return Buffer.concat(chunks).toString('utf8').replace(/\s+$/, '');
52
+ }
53
+ async function main() {
54
+ let parsed;
55
+ try {
56
+ parsed = parseArgs({
57
+ allowPositionals: true,
58
+ options: {
59
+ font: { type: 'string', short: 'f' },
60
+ list: { type: 'boolean', short: 'l' },
61
+ preview: { type: 'string' },
62
+ width: { type: 'string', short: 'w' },
63
+ align: { type: 'string', short: 'a' },
64
+ layout: { type: 'string' },
65
+ 'letter-spacing': { type: 'string' },
66
+ border: { type: 'string', short: 'b' },
67
+ title: { type: 'string' },
68
+ shadow: { type: 'boolean', short: 's' },
69
+ fill: { type: 'string' },
70
+ gradient: { type: 'string', short: 'g' },
71
+ direction: { type: 'string', short: 'd' },
72
+ color: { type: 'string', short: 'c' },
73
+ 'no-color': { type: 'boolean' },
74
+ svg: { type: 'string' },
75
+ version: { type: 'boolean', short: 'v' },
76
+ help: { type: 'boolean', short: 'h' },
77
+ },
78
+ });
79
+ }
80
+ catch (e) {
81
+ fail(`${e.message}\nrun "asciikit --help" for usage`);
82
+ }
83
+ const { values: o, positionals } = parsed;
84
+ if (o.help)
85
+ return void process.stdout.write(HELP);
86
+ if (o.version) {
87
+ const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
88
+ return void process.stdout.write(`${pkg.version}\n`);
89
+ }
90
+ if (o.list) {
91
+ for (const meta of fontList) {
92
+ if (o.preview) {
93
+ const font = await loadFont(meta.id);
94
+ process.stdout.write(`\n${meta.name} (${meta.id})\n${ascii(o.preview, { font })}\n`);
95
+ }
96
+ else {
97
+ process.stdout.write(`${meta.id.padEnd(28)} ${meta.name}\n`);
98
+ }
99
+ }
100
+ return;
101
+ }
102
+ const text = positionals.length ? positionals.join(' ') : await readStdin();
103
+ if (!text)
104
+ return void process.stdout.write(HELP);
105
+ let font;
106
+ try {
107
+ font = await loadFont(o.font ?? 'standard');
108
+ }
109
+ catch {
110
+ fail(`unknown font "${o.font}". Run "asciikit --list" to see all fonts.`);
111
+ }
112
+ const width = o.width ? Number(o.width) : process.stdout.isTTY ? process.stdout.columns : undefined;
113
+ if (o.width && !(width > 0))
114
+ fail('--width must be a positive number');
115
+ const options = {
116
+ font,
117
+ width,
118
+ align: o.align,
119
+ horizontalLayout: o.layout,
120
+ letterSpacing: o['letter-spacing'] ? Number(o['letter-spacing']) : undefined,
121
+ fill: o.fill,
122
+ shadow: o.shadow,
123
+ border: o.border !== undefined || o.title
124
+ ? { style: (o.border || 'single'), title: o.title, padding: { x: 2, y: 1 } }
125
+ : undefined,
126
+ };
127
+ const art = ascii(text, options);
128
+ const gradient = o.gradient
129
+ ? Object.prototype.hasOwnProperty.call(gradients, o.gradient)
130
+ ? o.gradient
131
+ : o.gradient.split(',').map((s) => s.trim()).filter(Boolean)
132
+ : undefined;
133
+ const direction = o.direction;
134
+ const useColor = !o['no-color'] && process.stdout.isTTY && !process.env.NO_COLOR;
135
+ process.stdout.write(`${useColor ? toAnsi(art, { gradient, direction, color: o.color }) : art}\n`);
136
+ if (o.svg) {
137
+ writeFileSync(o.svg, toSVG(art, { gradient, gradientDirection: direction, color: o.color, background: '#000' }));
138
+ process.stderr.write(`asciikit: wrote ${o.svg}\n`);
139
+ }
140
+ }
141
+ main().catch((e) => fail(e instanceof Error ? e.message : String(e)));
package/dist/color.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { own } from './util.js';
1
2
  const NAMED = {
2
3
  black: '#000000', white: '#ffffff', red: '#ff0000', green: '#00ff00', blue: '#0000ff',
3
4
  yellow: '#ffff00', cyan: '#00ffff', magenta: '#ff00ff', gray: '#808080', grey: '#808080',
@@ -6,13 +7,14 @@ const NAMED = {
6
7
  /** Parse `#rgb`, `#rrggbb`, `rgb(r,g,b)` or a basic color name. */
7
8
  export function parseColor(input) {
8
9
  let s = input.trim().toLowerCase();
9
- if (NAMED[s])
10
- s = NAMED[s];
10
+ s = own(NAMED, s) ?? s;
11
11
  const rgb = s.match(/^rgba?\(\s*(\d+)[\s,]+(\d+)[\s,]+(\d+)/);
12
12
  if (rgb)
13
13
  return [+rgb[1], +rgb[2], +rgb[3]];
14
14
  if (s.startsWith('#'))
15
15
  s = s.slice(1);
16
+ if (!/^[0-9a-f]{3,8}$/.test(s))
17
+ return [255, 255, 255];
16
18
  if (s.length === 3 || s.length === 4)
17
19
  s = s.slice(0, 3).split('').map((c) => c + c).join('');
18
20
  const n = parseInt(s.slice(0, 6), 16);
package/dist/effects.js CHANGED
@@ -1,8 +1,11 @@
1
1
  import { sampleGradient, gradients } from './color.js';
2
+ import { escapeHTML, own, safeCssColor } from './util.js';
3
+ import { cells, fixCells, stringWidth } from './width.js';
2
4
  export const toLines = (art) => (typeof art === 'string' ? art.split('\n') : [...art]);
3
5
  const out = (lines) => lines.join('\n');
4
- const chars = (s) => Array.from(s);
5
- const len = (s) => chars(s).length;
6
+ // One entry per display column (wide chars are followed by a '' placeholder).
7
+ const chars = (s) => cells(s);
8
+ const len = (s) => stringWidth(s);
6
9
  /** Width (in columns) of the widest row. */
7
10
  export function measure(art) {
8
11
  const lines = toLines(art);
@@ -83,7 +86,7 @@ function edge(fill, width, label, labelAlign = 'left') {
83
86
  const text = ` ${label} `;
84
87
  const tl = len(text);
85
88
  if (tl >= width)
86
- return chars(text).slice(0, width).join('');
89
+ return fixCells(chars(text).slice(0, width)).join('');
87
90
  const free = width - tl;
88
91
  const left = labelAlign === 'center' ? Math.floor(free / 2) : labelAlign === 'right' ? free - 1 : Math.min(1, free);
89
92
  return fill.repeat(left) + text + fill.repeat(free - left);
@@ -91,7 +94,7 @@ function edge(fill, width, label, labelAlign = 'left') {
91
94
  /** Draw a box (border) around the art. */
92
95
  export function box(art, options = {}) {
93
96
  const o = typeof options === 'string' ? { style: options } : options;
94
- const s = typeof o.style === 'object' ? o.style : boxStyles[o.style ?? 'single'];
97
+ const s = typeof o.style === 'object' ? o.style : (own(boxStyles, o.style ?? 'single') ?? boxStyles.single);
95
98
  let inner = pad(art, o.padding ?? { x: 1, y: 0 });
96
99
  if (o.width)
97
100
  inner = normalize(align(inner, o.align ?? 'left', o.width));
@@ -154,7 +157,18 @@ const V_MIRROR = {
154
157
  /** Mirror left-to-right, swapping directional characters. */
155
158
  export function flipHorizontal(art) {
156
159
  const lines = toLines(normalize(art));
157
- return out(lines.map((l) => chars(l).reverse().map((c) => H_MIRROR[c] ?? c).join('').replace(/\s+$/, '')));
160
+ return out(lines.map((l) => {
161
+ const row = chars(l).reverse();
162
+ // Reversing puts each wide char's placeholder in front of it; swap them back.
163
+ for (let i = 0; i < row.length - 1; i++) {
164
+ if (row[i] === '' && row[i + 1] !== '') {
165
+ row[i] = row[i + 1];
166
+ row[i + 1] = '';
167
+ i++;
168
+ }
169
+ }
170
+ return row.map((c) => H_MIRROR[c] ?? c).join('').replace(/\s+$/, '');
171
+ }));
158
172
  }
159
173
  /** Mirror top-to-bottom, swapping directional characters. */
160
174
  export function flipVertical(art) {
@@ -170,12 +184,12 @@ export function rotate(art, degrees) {
170
184
  const w = grid[0]?.length ?? 0;
171
185
  const res = [];
172
186
  for (let c = 0; c < w; c++) {
173
- let row = '';
187
+ const row = [];
174
188
  for (let r = 0; r < h; r++) {
175
189
  const ch = degrees === 90 ? grid[h - 1 - r][c] : grid[r][w - 1 - c];
176
- row += ROT90[ch] ?? ch;
190
+ row.push(ROT90[ch] ?? ch);
177
191
  }
178
- res.push(row.replace(/\s+$/, ''));
192
+ res.push(fixCells(row).join('').replace(/\s+$/, ''));
179
193
  }
180
194
  return out(res);
181
195
  }
@@ -235,7 +249,7 @@ export function overlay(base, top, x = 0, y = 0) {
235
249
  row[k + x] = c;
236
250
  });
237
251
  });
238
- return out(b.map((r) => r.join('')));
252
+ return out(b.map((r) => fixCells(r).join('')));
239
253
  }
240
254
  /** Pipe art through a sequence of transforms: `pipe(art, a => box(a), fill('#'))`. */
241
255
  export function pipe(art, ...fns) {
@@ -243,7 +257,8 @@ export function pipe(art, ...fns) {
243
257
  }
244
258
  /** Compute a per-character color grid for a gradient. */
245
259
  export function gradientCells(art, colors, direction = 'horizontal') {
246
- const stops = typeof colors === 'string' ? gradients[colors] : colors;
260
+ // A preset name, or any other string treated as a single color.
261
+ const stops = typeof colors === 'string' ? (own(gradients, colors) ?? [colors]) : colors;
247
262
  const lines = toLines(art).map(chars);
248
263
  const h = lines.length;
249
264
  const w = Math.max(1, ...lines.map((l) => l.length));
@@ -291,13 +306,14 @@ export function toAnsi(art, options = {}) {
291
306
  }
292
307
  /** Escape art for safe insertion into HTML. */
293
308
  export function toHTML(art, options = {}) {
294
- const esc = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
295
309
  if (!options.gradient) {
296
- const style = options.color ? ` style="color:${options.color}"` : '';
297
- return `<pre${style}>${esc(typeof art === 'string' ? art : out([...art]))}</pre>`;
310
+ // Only well-formed CSS colors are emitted; anything else is dropped (prevents attribute injection).
311
+ const color = safeCssColor(options.color);
312
+ const style = color ? ` style="color:${escapeHTML(color)}"` : '';
313
+ return `<pre${style}>${escapeHTML(typeof art === 'string' ? art : out([...art]))}</pre>`;
298
314
  }
299
315
  const body = gradientCells(art, options.gradient, options.direction)
300
- .map((row) => row.map((c) => (c.color ? `<span style="color:${c.color}">${esc(c.char)}</span>` : c.char)).join(''))
316
+ .map((row) => row.map((c) => (c.color ? `<span style="color:${c.color}">${escapeHTML(c.char)}</span>` : escapeHTML(c.char))).join(''))
301
317
  .join('\n');
302
318
  return `<pre>${body}</pre>`;
303
319
  }
@@ -0,0 +1,37 @@
1
+ import { type GradientName } from './color.js';
2
+ import { type Art, type GradientDirection } from './effects.js';
3
+ export interface ImageExportOptions {
4
+ /** Font size in px (default 16). */
5
+ fontSize?: number;
6
+ /** Line height as a multiple of font size (default 1). */
7
+ lineHeight?: number;
8
+ /** Monospace font stack. */
9
+ fontFamily?: string;
10
+ /** Text color (default `#ededed`). Ignored when `gradient` is set. */
11
+ color?: string;
12
+ /** Gradient preset or color stops. */
13
+ gradient?: readonly string[] | GradientName;
14
+ gradientDirection?: GradientDirection;
15
+ /** Background color; omit for transparent. */
16
+ background?: string;
17
+ /** Space around the art in px (default 16). */
18
+ padding?: number;
19
+ /** Width of one character cell as a fraction of font size (default 0.6). */
20
+ cellWidth?: number;
21
+ }
22
+ /**
23
+ * Render art as a standalone SVG string — crisp at any size, perfect for
24
+ * OG images, READMEs, slides or `<img src="data:image/svg+xml,…">`.
25
+ * Each line is stretched to its exact column width, so alignment survives any font.
26
+ */
27
+ export declare function toSVG(art: Art, options?: ImageExportOptions): string;
28
+ /** Browser: draw the art onto a new canvas. `scale` defaults to devicePixelRatio. */
29
+ export declare function toCanvas(art: Art, options?: ImageExportOptions & {
30
+ scale?: number;
31
+ }): HTMLCanvasElement;
32
+ /** Browser: render the art to a PNG Blob (e.g. for a download button). */
33
+ export declare function toPNG(art: Art, options?: ImageExportOptions & {
34
+ scale?: number;
35
+ }): Promise<Blob>;
36
+ /** Browser: trigger a download of text, SVG or a Blob. */
37
+ export declare function downloadFile(filename: string, data: string | Blob, type?: string): void;