@iwascreatedtocreate/asciikit 0.1.2 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +24 -24
- package/README.md +219 -122
- package/dist/animate.d.ts +1 -1
- package/dist/animate.js +38 -1
- package/dist/canvas.d.ts +101 -0
- package/dist/canvas.js +321 -0
- package/dist/charts.d.ts +133 -0
- package/dist/charts.js +178 -0
- package/dist/cli.js +48 -30
- package/dist/element.d.ts +32 -0
- package/dist/element.js +226 -0
- package/dist/export.d.ts +4 -1
- package/dist/export.js +63 -24
- package/dist/glyphs.d.ts +12 -0
- package/dist/glyphs.js +96 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +4 -0
- package/dist/layout.d.ts +307 -0
- package/dist/layout.js +194 -0
- package/dist/react/Ascii.d.ts +1 -1
- package/dist/react/AsciiImage.js +1 -1
- package/dist/react/index.d.ts +1 -0
- package/dist/react/index.js +1 -0
- package/dist/react/widgets.d.ts +56 -0
- package/dist/react/widgets.js +52 -0
- package/dist/text.d.ts +26 -0
- package/dist/text.js +230 -0
- package/package.json +93 -87
package/dist/cli.js
CHANGED
|
@@ -5,38 +5,44 @@ import { gradients } from './color.js';
|
|
|
5
5
|
import { ascii } from './compose.js';
|
|
6
6
|
import { boxStyles, toAnsi } from './effects.js';
|
|
7
7
|
import { toSVG } from './export.js';
|
|
8
|
+
import { critters, say } from './layout.js';
|
|
9
|
+
import { fancy, fancyStyles } from './text.js';
|
|
8
10
|
import { loadFont } from './fonts/lazy.js';
|
|
9
11
|
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
|
-
--
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
asciikit
|
|
12
|
+
const HELP = `asciikit — ASCII art in your terminal
|
|
13
|
+
|
|
14
|
+
usage
|
|
15
|
+
asciikit <text> [options]
|
|
16
|
+
echo "text" | asciikit [options]
|
|
17
|
+
|
|
18
|
+
options
|
|
19
|
+
-f, --font <name> font id or name (default: standard) e.g. slant, "ANSI Shadow"
|
|
20
|
+
-l, --list list all fonts (combine with --preview to render each one)
|
|
21
|
+
--preview <text> sample text for --list
|
|
22
|
+
-w, --width <n> wrap at n columns (default: terminal width)
|
|
23
|
+
-a, --align <a> left | center | right
|
|
24
|
+
--layout <l> default | full | fitted | smush | universal-smush
|
|
25
|
+
--letter-spacing <n> extra columns between characters
|
|
26
|
+
-b, --border [style] ${Object.keys(boxStyles).join(' | ')}
|
|
27
|
+
--title <text> border title
|
|
28
|
+
-s, --shadow drop shadow
|
|
29
|
+
--fill <char> replace every visible character
|
|
30
|
+
-g, --gradient <g> preset (${Object.keys(gradients).join(', ')}) or colors "#f00,#00f"
|
|
31
|
+
-d, --direction <d> horizontal | vertical | diagonal | radial
|
|
32
|
+
-c, --color <color> single text color
|
|
33
|
+
--no-color plain text, no ANSI colors
|
|
34
|
+
--fancy <style> unicode text instead of a font: bold, script, fraktur, circled, smallCaps, upsideDown…
|
|
35
|
+
--say <critter> put the text in a speech bubble (${Object.keys(critters).join(' | ')})
|
|
36
|
+
--svg <file> also write an SVG image
|
|
37
|
+
-v, --version print version
|
|
38
|
+
-h, --help show this help
|
|
39
|
+
|
|
40
|
+
examples
|
|
41
|
+
asciikit hello
|
|
42
|
+
asciikit "deploy ok" -f slant -g sunset -b rounded
|
|
43
|
+
asciikit --list --preview Hi
|
|
44
|
+
asciikit "ship it" --say robot
|
|
45
|
+
asciikit hello --fancy fraktur
|
|
40
46
|
`;
|
|
41
47
|
function fail(message) {
|
|
42
48
|
process.stderr.write(`asciikit: ${message}\n`);
|
|
@@ -71,6 +77,8 @@ async function main() {
|
|
|
71
77
|
direction: { type: 'string', short: 'd' },
|
|
72
78
|
color: { type: 'string', short: 'c' },
|
|
73
79
|
'no-color': { type: 'boolean' },
|
|
80
|
+
fancy: { type: 'string' },
|
|
81
|
+
say: { type: 'string' },
|
|
74
82
|
svg: { type: 'string' },
|
|
75
83
|
version: { type: 'boolean', short: 'v' },
|
|
76
84
|
help: { type: 'boolean', short: 'h' },
|
|
@@ -102,6 +110,16 @@ async function main() {
|
|
|
102
110
|
const text = positionals.length ? positionals.join(' ') : await readStdin();
|
|
103
111
|
if (!text)
|
|
104
112
|
return void process.stdout.write(HELP);
|
|
113
|
+
// these two skip FIGlet fonts entirely
|
|
114
|
+
if (o.fancy !== undefined || o.say !== undefined) {
|
|
115
|
+
if (o.fancy !== undefined && !fancyStyles.includes(o.fancy))
|
|
116
|
+
fail(`unknown --fancy style "${o.fancy}". Try: ${fancyStyles.join(', ')}`);
|
|
117
|
+
if (o.say && !Object.prototype.hasOwnProperty.call(critters, o.say))
|
|
118
|
+
fail(`unknown critter "${o.say}". Try: ${Object.keys(critters).join(', ')}`);
|
|
119
|
+
const styled = o.fancy !== undefined ? fancy(text, o.fancy) : text;
|
|
120
|
+
const out = o.say !== undefined ? say(styled, (o.say || 'cat')) : styled;
|
|
121
|
+
return void process.stdout.write(`${out}\n`);
|
|
122
|
+
}
|
|
105
123
|
let font;
|
|
106
124
|
try {
|
|
107
125
|
font = await loadFont(o.font ?? 'standard');
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
declare const Base: typeof HTMLElement;
|
|
2
|
+
export declare class AsciiTextElement extends Base {
|
|
3
|
+
static get observedAttributes(): readonly string[];
|
|
4
|
+
private pre?;
|
|
5
|
+
private token;
|
|
6
|
+
private art;
|
|
7
|
+
private raf;
|
|
8
|
+
private timer;
|
|
9
|
+
private observer?;
|
|
10
|
+
private io?;
|
|
11
|
+
connectedCallback(): void;
|
|
12
|
+
disconnectedCallback(): void;
|
|
13
|
+
attributeChangedCallback(): void;
|
|
14
|
+
/** The rendered art (empty until the font has loaded). */
|
|
15
|
+
get value(): string;
|
|
16
|
+
private onHover;
|
|
17
|
+
private options;
|
|
18
|
+
private applyStyle;
|
|
19
|
+
private update;
|
|
20
|
+
private effect;
|
|
21
|
+
private stop;
|
|
22
|
+
/** Start (or restart) the animation set by the `animate` attribute. */
|
|
23
|
+
play(): void;
|
|
24
|
+
}
|
|
25
|
+
/** Register the element under `tag` (default `ascii-text`). Safe to call more than once. */
|
|
26
|
+
export declare function defineAsciiText(tag?: string): void;
|
|
27
|
+
declare global {
|
|
28
|
+
interface HTMLElementTagNameMap {
|
|
29
|
+
'ascii-text': AsciiTextElement;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
export {};
|
package/dist/element.js
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `<ascii-text>`: a framework-free custom element. Works in plain HTML, Vue, Svelte,
|
|
3
|
+
* Astro, Angular, anything that renders HTML.
|
|
4
|
+
*
|
|
5
|
+
* ```html
|
|
6
|
+
* <script type="module" src="https://cdn.jsdelivr.net/npm/@iwascreatedtocreate/asciikit/dist/element.js"></script>
|
|
7
|
+
* <ascii-text font="slant" gradient="sunset" border="rounded" animate="scramble">hello</ascii-text>
|
|
8
|
+
* ```
|
|
9
|
+
*
|
|
10
|
+
* Importing this module defines the tag (once). Fonts load on demand, one chunk each.
|
|
11
|
+
*/
|
|
12
|
+
import { animationFrame, continuousEffects } from './animate.js';
|
|
13
|
+
import { gradients } from './color.js';
|
|
14
|
+
import { ascii } from './compose.js';
|
|
15
|
+
import { boxStyles } from './effects.js';
|
|
16
|
+
import { loadFont } from './fonts/lazy.js';
|
|
17
|
+
import { own, safeCssColor } from './util.js';
|
|
18
|
+
const OBSERVED = [
|
|
19
|
+
'text', 'font', 'gradient', 'direction', 'color', 'glow', 'size', 'line-height', 'border', 'border-title',
|
|
20
|
+
'shadow', 'fill', 'align', 'width', 'letter-spacing', 'layout', 'animate', 'duration', 'loop', 'trigger', 'label',
|
|
21
|
+
];
|
|
22
|
+
const MONO = 'ui-monospace, "SFMono-Regular", "JetBrains Mono", "Cascadia Mono", Menlo, Consolas, "Liberation Mono", monospace';
|
|
23
|
+
// note: extending HTMLElement at module scope would crash on the server, so fall back to a dummy base
|
|
24
|
+
const Base = (typeof HTMLElement === 'undefined' ? class {
|
|
25
|
+
} : HTMLElement);
|
|
26
|
+
const num = (v) => (v === null || v === '' || !Number.isFinite(Number(v)) ? undefined : Number(v));
|
|
27
|
+
const flag = (v) => v !== null && v !== 'false';
|
|
28
|
+
function gradientCss(value, direction) {
|
|
29
|
+
const stops = own(gradients, value) ?? value.split(',').map((s) => safeCssColor(s.trim())).filter(Boolean);
|
|
30
|
+
if (stops.length < 2)
|
|
31
|
+
return undefined;
|
|
32
|
+
const d = direction ?? 'horizontal';
|
|
33
|
+
if (d === 'radial')
|
|
34
|
+
return `radial-gradient(circle, ${stops.join(', ')})`;
|
|
35
|
+
const deg = /^-?\d+$/.test(d) ? Number(d) : d === 'vertical' ? 180 : d === 'diagonal' ? 135 : 90;
|
|
36
|
+
return `linear-gradient(${deg}deg, ${stops.join(', ')})`;
|
|
37
|
+
}
|
|
38
|
+
export class AsciiTextElement extends Base {
|
|
39
|
+
constructor() {
|
|
40
|
+
super(...arguments);
|
|
41
|
+
this.token = 0;
|
|
42
|
+
this.art = '';
|
|
43
|
+
this.raf = 0;
|
|
44
|
+
this.onHover = () => {
|
|
45
|
+
if (this.getAttribute('trigger') === 'hover')
|
|
46
|
+
this.play();
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
static get observedAttributes() {
|
|
50
|
+
return OBSERVED;
|
|
51
|
+
}
|
|
52
|
+
connectedCallback() {
|
|
53
|
+
if (!this.shadowRoot) {
|
|
54
|
+
const root = this.attachShadow({ mode: 'open' });
|
|
55
|
+
root.innerHTML =
|
|
56
|
+
'<style>:host{display:inline-block;max-width:100%}pre{margin:0;white-space:pre;font-variant-ligatures:none;overflow-x:auto;overflow-y:hidden}</style><pre part="art" role="img"></pre>';
|
|
57
|
+
this.pre = root.querySelector('pre');
|
|
58
|
+
}
|
|
59
|
+
// re-render when the text inside the tag changes (frameworks patch it in place)
|
|
60
|
+
this.observer ?? (this.observer = new MutationObserver(() => this.update()));
|
|
61
|
+
this.observer.observe(this, { childList: true, characterData: true, subtree: true });
|
|
62
|
+
this.addEventListener('mouseenter', this.onHover);
|
|
63
|
+
this.update();
|
|
64
|
+
}
|
|
65
|
+
disconnectedCallback() {
|
|
66
|
+
this.observer?.disconnect();
|
|
67
|
+
this.io?.disconnect();
|
|
68
|
+
this.removeEventListener('mouseenter', this.onHover);
|
|
69
|
+
this.stop();
|
|
70
|
+
}
|
|
71
|
+
attributeChangedCallback() {
|
|
72
|
+
if (this.isConnected)
|
|
73
|
+
this.update();
|
|
74
|
+
}
|
|
75
|
+
/** The rendered art (empty until the font has loaded). */
|
|
76
|
+
get value() {
|
|
77
|
+
return this.art;
|
|
78
|
+
}
|
|
79
|
+
options() {
|
|
80
|
+
const border = this.getAttribute('border');
|
|
81
|
+
const title = this.getAttribute('border-title') ?? undefined;
|
|
82
|
+
const style = border && own(boxStyles, border) ? border : 'single';
|
|
83
|
+
return {
|
|
84
|
+
width: num(this.getAttribute('width')),
|
|
85
|
+
align: this.getAttribute('align') ?? undefined,
|
|
86
|
+
letterSpacing: num(this.getAttribute('letter-spacing')),
|
|
87
|
+
horizontalLayout: this.getAttribute('layout') ?? undefined,
|
|
88
|
+
fill: this.getAttribute('fill') || undefined,
|
|
89
|
+
shadow: flag(this.getAttribute('shadow')),
|
|
90
|
+
border: border !== null || title ? { style, title, padding: { x: 1, y: 0 } } : undefined,
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
applyStyle() {
|
|
94
|
+
const pre = this.pre;
|
|
95
|
+
const s = pre.style;
|
|
96
|
+
s.cssText = '';
|
|
97
|
+
s.fontFamily = MONO;
|
|
98
|
+
s.lineHeight = this.getAttribute('line-height') ?? '1';
|
|
99
|
+
const size = this.getAttribute('size');
|
|
100
|
+
if (size)
|
|
101
|
+
s.fontSize = /^\d+(\.\d+)?$/.test(size) ? `${size}px` : size;
|
|
102
|
+
const color = safeCssColor(this.getAttribute('color') ?? undefined);
|
|
103
|
+
if (color)
|
|
104
|
+
s.color = color;
|
|
105
|
+
const gradient = this.getAttribute('gradient');
|
|
106
|
+
const image = gradient ? gradientCss(gradient, this.getAttribute('direction')) : undefined;
|
|
107
|
+
if (image) {
|
|
108
|
+
s.backgroundImage = image;
|
|
109
|
+
s.setProperty('-webkit-background-clip', 'text');
|
|
110
|
+
s.backgroundClip = 'text';
|
|
111
|
+
s.setProperty('-webkit-text-fill-color', 'transparent');
|
|
112
|
+
s.color = 'transparent';
|
|
113
|
+
s.width = 'fit-content';
|
|
114
|
+
}
|
|
115
|
+
const glow = this.getAttribute('glow');
|
|
116
|
+
if (glow !== null && glow !== 'false') {
|
|
117
|
+
const c = safeCssColor(glow) ?? 'currentColor';
|
|
118
|
+
s.textShadow = `0 0 4px ${c}, 0 0 12px ${c}`;
|
|
119
|
+
if (image)
|
|
120
|
+
s.filter = 'drop-shadow(0 0 6px rgba(255,255,255,.35))';
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
async update() {
|
|
124
|
+
if (!this.pre)
|
|
125
|
+
return;
|
|
126
|
+
const token = ++this.token;
|
|
127
|
+
const text = (this.getAttribute('text') ?? this.textContent ?? '').trim();
|
|
128
|
+
const label = this.getAttribute('label');
|
|
129
|
+
this.pre.setAttribute('aria-label', label ?? text);
|
|
130
|
+
this.applyStyle();
|
|
131
|
+
let font;
|
|
132
|
+
try {
|
|
133
|
+
font = await loadFont(this.getAttribute('font') || 'standard');
|
|
134
|
+
}
|
|
135
|
+
catch {
|
|
136
|
+
font = await loadFont('standard');
|
|
137
|
+
}
|
|
138
|
+
if (token !== this.token)
|
|
139
|
+
return; // a newer update won
|
|
140
|
+
this.art = text ? ascii(text, { font, ...this.options() }) : '';
|
|
141
|
+
this.stop();
|
|
142
|
+
const trigger = this.getAttribute('trigger');
|
|
143
|
+
const effect = this.effect();
|
|
144
|
+
if (effect && trigger === 'visible' && typeof IntersectionObserver !== 'undefined') {
|
|
145
|
+
this.pre.textContent = animationFrame(this.art, effect, 0, { time: 0 });
|
|
146
|
+
this.io?.disconnect();
|
|
147
|
+
this.io = new IntersectionObserver((entries) => {
|
|
148
|
+
if (entries.some((e) => e.isIntersecting)) {
|
|
149
|
+
this.io?.disconnect();
|
|
150
|
+
this.play();
|
|
151
|
+
}
|
|
152
|
+
});
|
|
153
|
+
this.io.observe(this);
|
|
154
|
+
}
|
|
155
|
+
else if (effect && trigger !== 'hover') {
|
|
156
|
+
this.play();
|
|
157
|
+
}
|
|
158
|
+
else {
|
|
159
|
+
this.pre.textContent = this.art;
|
|
160
|
+
}
|
|
161
|
+
this.dispatchEvent(new CustomEvent('render', { detail: { art: this.art } }));
|
|
162
|
+
}
|
|
163
|
+
effect() {
|
|
164
|
+
const e = this.getAttribute('animate');
|
|
165
|
+
if (!e)
|
|
166
|
+
return null;
|
|
167
|
+
if (typeof matchMedia !== 'undefined' && matchMedia('(prefers-reduced-motion: reduce)').matches)
|
|
168
|
+
return null;
|
|
169
|
+
return e;
|
|
170
|
+
}
|
|
171
|
+
stop() {
|
|
172
|
+
if (typeof cancelAnimationFrame !== 'undefined')
|
|
173
|
+
cancelAnimationFrame(this.raf);
|
|
174
|
+
if (this.timer)
|
|
175
|
+
clearTimeout(this.timer);
|
|
176
|
+
}
|
|
177
|
+
/** Start (or restart) the animation set by the `animate` attribute. */
|
|
178
|
+
play() {
|
|
179
|
+
const effect = this.effect();
|
|
180
|
+
if (!effect || !this.pre)
|
|
181
|
+
return;
|
|
182
|
+
this.stop();
|
|
183
|
+
const art = this.art;
|
|
184
|
+
const pre = this.pre;
|
|
185
|
+
const duration = num(this.getAttribute('duration')) ?? 1200;
|
|
186
|
+
const loopAttr = this.getAttribute('loop');
|
|
187
|
+
const loops = loopAttr === null ? 1 : loopAttr === '' || loopAttr === 'true' ? Infinity : (num(loopAttr) ?? 1);
|
|
188
|
+
const continuous = continuousEffects.includes(effect);
|
|
189
|
+
const seed = Math.floor(Math.random() * 1e6) + 2;
|
|
190
|
+
let start = 0;
|
|
191
|
+
let done = 0;
|
|
192
|
+
const step = (now) => {
|
|
193
|
+
if (!start)
|
|
194
|
+
start = now;
|
|
195
|
+
const elapsed = now - start;
|
|
196
|
+
if (continuous) {
|
|
197
|
+
pre.textContent = animationFrame(art, effect, 1, { time: elapsed, seed });
|
|
198
|
+
this.raf = requestAnimationFrame(step);
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
const p = Math.min(1, elapsed / duration);
|
|
202
|
+
pre.textContent = animationFrame(art, effect, p, { time: elapsed, seed: seed + done });
|
|
203
|
+
if (p < 1) {
|
|
204
|
+
this.raf = requestAnimationFrame(step);
|
|
205
|
+
}
|
|
206
|
+
else {
|
|
207
|
+
pre.textContent = art;
|
|
208
|
+
if (++done < loops) {
|
|
209
|
+
this.timer = setTimeout(() => {
|
|
210
|
+
start = 0;
|
|
211
|
+
this.raf = requestAnimationFrame(step);
|
|
212
|
+
}, 1500);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
};
|
|
216
|
+
this.raf = requestAnimationFrame(step);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
/** Register the element under `tag` (default `ascii-text`). Safe to call more than once. */
|
|
220
|
+
export function defineAsciiText(tag = 'ascii-text') {
|
|
221
|
+
if (typeof customElements === 'undefined' || customElements.get(tag))
|
|
222
|
+
return;
|
|
223
|
+
customElements.define(tag, class extends AsciiTextElement {
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
defineAsciiText();
|
package/dist/export.d.ts
CHANGED
|
@@ -18,11 +18,14 @@ export interface ImageExportOptions {
|
|
|
18
18
|
padding?: number;
|
|
19
19
|
/** Width of one character cell as a fraction of font size (default 0.6). */
|
|
20
20
|
cellWidth?: number;
|
|
21
|
+
/** Draw block and box-drawing characters as shapes so they tile without gaps (default true). */
|
|
22
|
+
vector?: boolean;
|
|
21
23
|
}
|
|
22
24
|
/**
|
|
23
25
|
* Render art as a standalone SVG string — crisp at any size, perfect for
|
|
24
26
|
* OG images, READMEs, slides or `<img src="data:image/svg+xml,…">`.
|
|
25
|
-
*
|
|
27
|
+
* Every character is pinned to its column and block / box-drawing characters are drawn
|
|
28
|
+
* as shapes, so alignment and solid fills survive any font.
|
|
26
29
|
*/
|
|
27
30
|
export declare function toSVG(art: Art, options?: ImageExportOptions): string;
|
|
28
31
|
/** Browser: draw the art onto a new canvas. `scale` defaults to devicePixelRatio. */
|
package/dist/export.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { gradients } from './color.js';
|
|
2
2
|
import { toLines } from './effects.js';
|
|
3
3
|
import { escapeHTML, own } from './util.js';
|
|
4
|
-
import {
|
|
4
|
+
import { cellRects } from './glyphs.js';
|
|
5
|
+
import { cells, charWidth, stringWidth } from './width.js';
|
|
5
6
|
const MONO = "ui-monospace, 'SFMono-Regular', 'JetBrains Mono', Menlo, Consolas, 'Liberation Mono', monospace";
|
|
6
7
|
function layout(art, o) {
|
|
7
8
|
const lines = toLines(art).map((l) => l.replace(/\s+$/, ''));
|
|
@@ -19,10 +20,40 @@ function layout(art, o) {
|
|
|
19
20
|
: null;
|
|
20
21
|
return { lines, fontSize, lineHeight, cell, padding, width, height, stops };
|
|
21
22
|
}
|
|
23
|
+
/** Every non-space cell, split into vector rectangles (blocks, box lines) and text glyphs. */
|
|
24
|
+
function plan(L, vector) {
|
|
25
|
+
const rects = [];
|
|
26
|
+
const glyphs = [];
|
|
27
|
+
L.lines.forEach((line, i) => {
|
|
28
|
+
const top = L.padding + i * L.lineHeight;
|
|
29
|
+
cells(line).forEach((c, col) => {
|
|
30
|
+
if (c === '' || c === ' ')
|
|
31
|
+
return;
|
|
32
|
+
const x = L.padding + col * L.cell;
|
|
33
|
+
const shapes = vector ? cellRects(c, x, top, L.cell, L.lineHeight, L.fontSize) : null;
|
|
34
|
+
if (shapes)
|
|
35
|
+
rects.push(...shapes);
|
|
36
|
+
else
|
|
37
|
+
glyphs.push({ x, y: top + 0.8 * L.lineHeight, c, w: charWidth(c) * L.cell });
|
|
38
|
+
});
|
|
39
|
+
});
|
|
40
|
+
// join neighbours in a row (█████ becomes one rect) so antialiasing can't draw seams between them
|
|
41
|
+
const merged = [];
|
|
42
|
+
for (const r of rects) {
|
|
43
|
+
const m = merged[merged.length - 1];
|
|
44
|
+
if (m && Math.abs(m[1] - r[1]) < 0.01 && Math.abs(m[3] - r[3]) < 0.01 && m[4] === r[4] && Math.abs(m[0] + m[2] - r[0]) < 0.01)
|
|
45
|
+
m[2] += r[2];
|
|
46
|
+
else
|
|
47
|
+
merged.push([...r]);
|
|
48
|
+
}
|
|
49
|
+
return { rects: merged, glyphs };
|
|
50
|
+
}
|
|
51
|
+
const n = (v) => String(Math.round(v * 100) / 100);
|
|
22
52
|
/**
|
|
23
53
|
* Render art as a standalone SVG string — crisp at any size, perfect for
|
|
24
54
|
* OG images, READMEs, slides or `<img src="data:image/svg+xml,…">`.
|
|
25
|
-
*
|
|
55
|
+
* Every character is pinned to its column and block / box-drawing characters are drawn
|
|
56
|
+
* as shapes, so alignment and solid fills survive any font.
|
|
26
57
|
*/
|
|
27
58
|
export function toSVG(art, options = {}) {
|
|
28
59
|
const L = layout(art, options);
|
|
@@ -33,25 +64,29 @@ export function toSVG(art, options = {}) {
|
|
|
33
64
|
const stopTags = L.stops
|
|
34
65
|
.map((c, i) => `<stop offset="${L.stops.length === 1 ? 0 : i / (L.stops.length - 1)}" stop-color="${escapeHTML(c)}"/>`)
|
|
35
66
|
.join('');
|
|
36
|
-
|
|
67
|
+
// fixed: gradients used the default objectBoundingBox units, so every line (and every shape)
|
|
68
|
+
// restarted the gradient. user space makes one gradient across the whole image.
|
|
69
|
+
const [x2, y2] = dir === 'vertical' ? [0, L.height] : dir === 'diagonal' ? [L.width, L.height] : [L.width, 0];
|
|
37
70
|
defs =
|
|
38
71
|
dir === 'radial'
|
|
39
|
-
? `<defs><radialGradient id="ak-g">${stopTags}</radialGradient></defs>`
|
|
40
|
-
: `<defs><linearGradient id="ak-g" x1="0" y1="0" x2="${x2}" y2="${y2}">${stopTags}</linearGradient></defs>`;
|
|
72
|
+
? `<defs><radialGradient id="ak-g" gradientUnits="userSpaceOnUse" cx="${n(L.width / 2)}" cy="${n(L.height / 2)}" r="${n(Math.max(L.width, L.height) / 2)}">${stopTags}</radialGradient></defs>`
|
|
73
|
+
: `<defs><linearGradient id="ak-g" gradientUnits="userSpaceOnUse" x1="0" y1="0" x2="${x2}" y2="${y2}">${stopTags}</linearGradient></defs>`;
|
|
41
74
|
fill = 'url(#ak-g)';
|
|
42
75
|
}
|
|
43
76
|
const bg = options.background ? `<rect width="100%" height="100%" fill="${escapeHTML(options.background)}"/>` : '';
|
|
44
|
-
const
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
77
|
+
const { rects, glyphs } = plan(L, options.vector ?? true);
|
|
78
|
+
const shapes = rects
|
|
79
|
+
.map(([x, y, w, h, o]) => `<rect x="${n(x)}" y="${n(y)}" width="${n(w)}" height="${n(h)}"${o < 1 ? ` fill-opacity="${o}"` : ''}/>`)
|
|
80
|
+
.join('');
|
|
81
|
+
// one <text> per row with an x for every glyph, so a fallback glyph can't shift its neighbours
|
|
82
|
+
const rows = new Map();
|
|
83
|
+
for (const g of glyphs)
|
|
84
|
+
rows.set(g.y, [...(rows.get(g.y) ?? []), g]);
|
|
85
|
+
const text = [...rows]
|
|
86
|
+
.map(([y, gs]) => `<text x="${gs.map((g) => n(g.x)).join(' ')}" y="${n(y)}">${escapeHTML(gs.map((g) => g.c).join(''))}</text>`)
|
|
52
87
|
.join('');
|
|
53
88
|
return (`<svg xmlns="http://www.w3.org/2000/svg" width="${L.width}" height="${L.height}" viewBox="0 0 ${L.width} ${L.height}">` +
|
|
54
|
-
`${defs}${bg}<g fill="${fill}" font-family="${escapeHTML(options.fontFamily ?? MONO)}" font-size="${L.fontSize}" xml:space="preserve">${text}</g></svg>`);
|
|
89
|
+
`${defs}${bg}<g fill="${fill}" font-family="${escapeHTML(options.fontFamily ?? MONO)}" font-size="${L.fontSize}" xml:space="preserve">${shapes}${text}</g></svg>`);
|
|
55
90
|
}
|
|
56
91
|
/** Browser: draw the art onto a new canvas. `scale` defaults to devicePixelRatio. */
|
|
57
92
|
export function toCanvas(art, options = {}) {
|
|
@@ -81,18 +116,22 @@ export function toCanvas(art, options = {}) {
|
|
|
81
116
|
else {
|
|
82
117
|
ctx.fillStyle = options.color ?? '#ededed';
|
|
83
118
|
}
|
|
84
|
-
L
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
119
|
+
const { rects, glyphs } = plan(L, options.vector ?? true);
|
|
120
|
+
for (const [x, y, w, h, o] of rects) {
|
|
121
|
+
ctx.globalAlpha = o;
|
|
122
|
+
ctx.fillRect(x, y, w, h);
|
|
123
|
+
}
|
|
124
|
+
ctx.globalAlpha = 1;
|
|
125
|
+
// fixed: same as toSVG, each glyph sits in its own cell instead of stretching whole lines
|
|
126
|
+
for (const g of glyphs) {
|
|
127
|
+
const natural = ctx.measureText(g.c).width || g.w;
|
|
90
128
|
ctx.save();
|
|
91
|
-
ctx.translate(
|
|
92
|
-
|
|
93
|
-
|
|
129
|
+
ctx.translate(g.x, g.y);
|
|
130
|
+
if (Math.abs(natural - g.w) > 0.5)
|
|
131
|
+
ctx.scale(g.w / natural, 1); // fallback glyphs fill their cell exactly
|
|
132
|
+
ctx.fillText(g.c, 0, 0);
|
|
94
133
|
ctx.restore();
|
|
95
|
-
}
|
|
134
|
+
}
|
|
96
135
|
return canvas;
|
|
97
136
|
}
|
|
98
137
|
/** Browser: render the art to a PNG Blob (e.g. for a download button). */
|
package/dist/glyphs.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Vector versions of block and box-drawing characters for image export. Fonts draw these
|
|
3
|
+
* with slightly different widths and heights, which leaves gaps (dashed lines, striped
|
|
4
|
+
* blocks). As rectangles they tile perfectly at any size.
|
|
5
|
+
*/
|
|
6
|
+
/** x, y, width, height, opacity */
|
|
7
|
+
export type Rect = [number, number, number, number, number];
|
|
8
|
+
/**
|
|
9
|
+
* Rectangles for one character cell at (x, y) of size w×h, or `null` when the
|
|
10
|
+
* character is not a block / box-drawing glyph and should be drawn as text.
|
|
11
|
+
*/
|
|
12
|
+
export declare function cellRects(c: string, x: number, y: number, w: number, h: number, fontSize: number): Rect[] | null;
|
package/dist/glyphs.js
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Vector versions of block and box-drawing characters for image export. Fonts draw these
|
|
3
|
+
* with slightly different widths and heights, which leaves gaps (dashed lines, striped
|
|
4
|
+
* blocks). As rectangles they tile perfectly at any size.
|
|
5
|
+
*/
|
|
6
|
+
const U = 1, R = 2, D = 4, L = 8;
|
|
7
|
+
// light and heavy lines as direction bits
|
|
8
|
+
const LIGHT = {
|
|
9
|
+
'─': R | L, '│': U | D, '┌': R | D, '┐': D | L, '└': U | R, '┘': U | L, '╭': R | D, '╮': D | L, '╰': U | R, '╯': U | L,
|
|
10
|
+
'├': U | D | R, '┤': U | D | L, '┬': R | D | L, '┴': U | R | L, '┼': U | R | D | L,
|
|
11
|
+
'╴': L, '╶': R, '╵': U, '╷': D,
|
|
12
|
+
};
|
|
13
|
+
const HEAVY = {
|
|
14
|
+
'━': R | L, '┃': U | D, '┏': R | D, '┓': D | L, '┗': U | R, '┛': U | L,
|
|
15
|
+
'┣': U | D | R, '┫': U | D | L, '┳': R | D | L, '┻': U | R | L, '╋': U | R | D | L,
|
|
16
|
+
'╸': L, '╺': R, '╹': U, '╻': D,
|
|
17
|
+
};
|
|
18
|
+
const DOUBLE = {
|
|
19
|
+
'═': R | L, '║': U | D, '╔': R | D, '╗': D | L, '╚': U | R, '╝': U | L,
|
|
20
|
+
'╠': U | D | R, '╣': U | D | L, '╦': R | D | L, '╩': U | R | L, '╬': U | R | D | L,
|
|
21
|
+
};
|
|
22
|
+
const SHADE = { '░': 0.25, '▒': 0.5, '▓': 0.75 };
|
|
23
|
+
const has = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
|
|
24
|
+
/**
|
|
25
|
+
* Rectangles for one character cell at (x, y) of size w×h, or `null` when the
|
|
26
|
+
* character is not a block / box-drawing glyph and should be drawn as text.
|
|
27
|
+
*/
|
|
28
|
+
export function cellRects(c, x, y, w, h, fontSize) {
|
|
29
|
+
if (c.length !== 1)
|
|
30
|
+
return null;
|
|
31
|
+
if (c === '█')
|
|
32
|
+
return [[x, y, w, h, 1]];
|
|
33
|
+
if (c === '▀')
|
|
34
|
+
return [[x, y, w, h / 2, 1]];
|
|
35
|
+
if (c === '▄')
|
|
36
|
+
return [[x, y + h / 2, w, h / 2, 1]];
|
|
37
|
+
if (c === '▌')
|
|
38
|
+
return [[x, y, w / 2, h, 1]];
|
|
39
|
+
if (c === '▐')
|
|
40
|
+
return [[x + w / 2, y, w / 2, h, 1]];
|
|
41
|
+
const rise = '▁▂▃▄▅▆▇'.indexOf(c);
|
|
42
|
+
if (rise >= 0) {
|
|
43
|
+
const f = (rise + 1) / 8;
|
|
44
|
+
return [[x, y + h * (1 - f), w, h * f, 1]];
|
|
45
|
+
}
|
|
46
|
+
const left = '▏▎▍▌▋▊▉'.indexOf(c);
|
|
47
|
+
if (left >= 0)
|
|
48
|
+
return [[x, y, (w * (left + 1)) / 8, h, 1]];
|
|
49
|
+
if (has(SHADE, c))
|
|
50
|
+
return [[x, y, w, h, SHADE[c]]];
|
|
51
|
+
const cx = x + w / 2;
|
|
52
|
+
const cy = y + h / 2;
|
|
53
|
+
const single = has(LIGHT, c) ? LIGHT[c] : has(HEAVY, c) ? HEAVY[c] : undefined;
|
|
54
|
+
if (single !== undefined) {
|
|
55
|
+
const t = Math.max(1, fontSize * (has(HEAVY, c) ? 0.16 : 0.08));
|
|
56
|
+
const out = [];
|
|
57
|
+
// each arm runs from the cell edge to just past the centre, so arms overlap cleanly
|
|
58
|
+
if (single & L)
|
|
59
|
+
out.push([x, cy - t / 2, w / 2 + t / 2, t, 1]);
|
|
60
|
+
if (single & R)
|
|
61
|
+
out.push([cx - t / 2, cy - t / 2, w / 2 + t / 2, t, 1]);
|
|
62
|
+
if (single & U)
|
|
63
|
+
out.push([cx - t / 2, y, t, h / 2 + t / 2, 1]);
|
|
64
|
+
if (single & D)
|
|
65
|
+
out.push([cx - t / 2, cy - t / 2, t, h / 2 + t / 2, 1]);
|
|
66
|
+
return out;
|
|
67
|
+
}
|
|
68
|
+
if (has(DOUBLE, c)) {
|
|
69
|
+
const bits = DOUBLE[c];
|
|
70
|
+
const t = Math.max(1, fontSize * 0.07);
|
|
71
|
+
const d = Math.max(t * 1.2, w * 0.17);
|
|
72
|
+
const out = [];
|
|
73
|
+
const hline = (x0, x1, yy) => out.push([Math.min(x0, x1), yy - t / 2, Math.abs(x1 - x0) + t / 2, t, 1]);
|
|
74
|
+
const vline = (y0, y1, xx) => out.push([xx - t / 2, Math.min(y0, y1), t, Math.abs(y1 - y0) + t / 2, 1]);
|
|
75
|
+
// note: each arm has two rails; a rail stops at the crossing arm's rail when there is one,
|
|
76
|
+
// otherwise it reaches the far rail so corners close (╗ ╔ …) and straight runs connect
|
|
77
|
+
if (bits & L) {
|
|
78
|
+
hline(x, bits & U ? cx - d : cx + d, cy - d);
|
|
79
|
+
hline(x, bits & D ? cx - d : cx + d, cy + d);
|
|
80
|
+
}
|
|
81
|
+
if (bits & R) {
|
|
82
|
+
hline(bits & U ? cx + d : cx - d, x + w, cy - d);
|
|
83
|
+
hline(bits & D ? cx + d : cx - d, x + w, cy + d);
|
|
84
|
+
}
|
|
85
|
+
if (bits & U) {
|
|
86
|
+
vline(y, bits & L ? cy - d : cy + d, cx - d);
|
|
87
|
+
vline(y, bits & R ? cy - d : cy + d, cx + d);
|
|
88
|
+
}
|
|
89
|
+
if (bits & D) {
|
|
90
|
+
vline(bits & L ? cy + d : cy - d, y + h, cx - d);
|
|
91
|
+
vline(bits & R ? cy + d : cy - d, y + h, cx + d);
|
|
92
|
+
}
|
|
93
|
+
return out;
|
|
94
|
+
}
|
|
95
|
+
return null;
|
|
96
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -10,3 +10,7 @@ export { animationFrame, continuousEffects, type AnimationEffect, type FrameOpti
|
|
|
10
10
|
export { spinners, type Spinner, type SpinnerName } from './spinners.js';
|
|
11
11
|
export { toSVG, toCanvas, toPNG, downloadFile, type ImageExportOptions } from './export.js';
|
|
12
12
|
export { graphemes, charWidth, stringWidth, cells } from './width.js';
|
|
13
|
+
export { wrapText, truncate, fancy, fancyStyles, type FancyStyle, type WrapOptions } from './text.js';
|
|
14
|
+
export { table, tableStyles, tree, treeStyles, divider, speechBubble, say, critters, type TableChars, type TableStyle, type TableCell, type TableOptions, type TreeNode, type TreeInput, type TreeStyle, type DividerOptions, type BubbleOptions, type CritterName, } from './layout.js';
|
|
15
|
+
export { sparkline, barChart, lineChart, progressBar, progressStyles, type SparklineOptions, type BarChartOptions, type LineChartOptions, type ProgressOptions, type ProgressStyle, type ChartData, } from './charts.js';
|
|
16
|
+
export { AsciiCanvas, BrailleCanvas, type RectOptions } from './canvas.js';
|
package/dist/index.js
CHANGED
|
@@ -9,3 +9,7 @@ export { animationFrame, continuousEffects } from './animate.js';
|
|
|
9
9
|
export { spinners } from './spinners.js';
|
|
10
10
|
export { toSVG, toCanvas, toPNG, downloadFile } from './export.js';
|
|
11
11
|
export { graphemes, charWidth, stringWidth, cells } from './width.js';
|
|
12
|
+
export { wrapText, truncate, fancy, fancyStyles } from './text.js';
|
|
13
|
+
export { table, tableStyles, tree, treeStyles, divider, speechBubble, say, critters, } from './layout.js';
|
|
14
|
+
export { sparkline, barChart, lineChart, progressBar, progressStyles, } from './charts.js';
|
|
15
|
+
export { AsciiCanvas, BrailleCanvas } from './canvas.js';
|