@iwascreatedtocreate/asciikit 0.2.0 → 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 CHANGED
@@ -1,24 +1,24 @@
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.
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
@@ -33,7 +33,7 @@ Live playground & font gallery: **https://asciikit.iwascreatedtocreate.com**
33
33
  - **Drawing canvas** — lines, boxes that merge into proper `┼ ├ ┬` junctions, circles, text; plus a braille pixel canvas with 8× resolution.
34
34
  - **Fancy Unicode text** — 𝐛𝐨𝐥𝐝, 𝔣𝔯𝔞𝔨𝔱𝔲𝔯, 𝓈𝒸𝓇𝒾𝓅𝓉, ⓒⓘⓡⓒⓛⓔⓓ, ꜱᴍᴀʟʟ ᴄᴀᴘꜱ, uʍop ǝpısdn and 20 more styles.
35
35
  - **Image → ASCII** — ramps, braille, edge tracing, Floyd–Steinberg / Atkinson / ordered dithering, color.
36
- - **Framework-free core** — everything works in Node, Bun, Deno, edge runtimes and CLIs.
36
+ - **Framework-free core** — everything works in Node, Bun, Deno, edge runtimes and CLIs, plus an `<ascii-text>` custom element for Vue, Svelte, Astro and plain HTML.
37
37
  - **Export** — `toSVG()` anywhere (OG images, READMEs), `toPNG()` / `toCanvas()` in the browser.
38
38
  - **CLI** — `npx @iwascreatedtocreate/asciikit "hello" -f slant -g sunset`.
39
39
  - **Wide characters** — emoji and CJK count as two columns, so borders and alignment stay straight.
@@ -63,6 +63,29 @@ const png = await toPNG(art, { color: '#fff', background: '#000' });
63
63
  downloadFile('hello.png', png);
64
64
  ```
65
65
 
66
+ ## Any framework: `<ascii-text>`
67
+
68
+ A custom element for plain HTML, Vue, Svelte, Astro, Angular and anything else that renders HTML. No build step needed:
69
+
70
+ ```html
71
+ <script type="module" src="https://cdn.jsdelivr.net/npm/@iwascreatedtocreate/asciikit/dist/element.js"></script>
72
+
73
+ <ascii-text font="slant" gradient="sunset" border="rounded">hello</ascii-text>
74
+ <ascii-text font="ANSI Shadow" color="#7cf" glow size="10" animate="scramble">boot</ascii-text>
75
+ ```
76
+
77
+ In a bundled app, `import '@iwascreatedtocreate/asciikit/element'` defines the tag. Fonts load on demand, one chunk each. Attributes: `font`, `text` (or the tag's content), `gradient` (preset or `#f00,#00f`), `direction`, `color`, `glow`, `size`, `line-height`, `border`, `border-title`, `shadow`, `fill`, `align`, `width`, `letter-spacing`, `layout`, `animate`, `duration`, `loop`, `trigger` (`mount` / `hover` / `visible`) and `label`. Changing an attribute or the text re-renders it. Style the inner `<pre>` with `ascii-text::part(art)`.
78
+
79
+ ## README banners
80
+
81
+ An SVG for GitHub READMEs, rendered on request. No install needed:
82
+
83
+ ```md
84
+ ![hello](https://asciikit.iwascreatedtocreate.com/api/banner?text=hello&font=slant&gradient=sunset)
85
+ ```
86
+
87
+ Query options: `text`, `font`, `gradient`, `color`, `dir`, `bg` (default transparent), `size`, `border`, `shadow`, `fill`, `align`. There's a banner maker on [the site](https://asciikit.iwascreatedtocreate.com/#banner).
88
+
66
89
  ## Tables, trees and bubbles
67
90
 
68
91
  ```ts
@@ -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 {};
@@ -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
- * Each line is stretched to its exact column width, so alignment survives any font.
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 { stringWidth } from './width.js';
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
- * Each line is stretched to its exact column width, so alignment survives any font.
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
- const [x2, y2] = dir === 'vertical' ? [0, 1] : dir === 'diagonal' ? [1, 1] : [1, 0];
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 text = L.lines
45
- .map((line, i) => {
46
- if (!line)
47
- return '';
48
- const y = L.padding + (i + 0.8) * L.lineHeight;
49
- const len = (stringWidth(line) * L.cell).toFixed(2);
50
- return `<text x="${L.padding}" y="${y.toFixed(2)}" textLength="${len}" lengthAdjust="spacingAndGlyphs">${escapeHTML(line)}</text>`;
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.lines.forEach((line, i) => {
85
- if (!line)
86
- return;
87
- const y = L.padding + (i + 0.8) * L.lineHeight;
88
- const target = stringWidth(line) * L.cell;
89
- const natural = ctx.measureText(line).width || target;
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(L.padding, y);
92
- ctx.scale(target / natural, 1); // keep columns aligned whatever the font's advance width is
93
- ctx.fillText(line, 0, 0);
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). */
@@ -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/package.json CHANGED
@@ -1,87 +1,93 @@
1
- {
2
- "name": "@iwascreatedtocreate/asciikit",
3
- "version": "0.2.0",
4
- "description": "The advanced ASCII art toolkit for React & Next.js — 300+ FIGlet fonts, full smushing engine, effects, animations and image-to-ASCII. Import fonts like icons.",
5
- "keywords": [
6
- "ascii",
7
- "ascii-art",
8
- "figlet",
9
- "react",
10
- "nextjs",
11
- "banner",
12
- "text-art",
13
- "fonts",
14
- "terminal"
15
- ],
16
- "homepage": "https://asciikit.iwascreatedtocreate.com",
17
- "repository": {
18
- "type": "git",
19
- "url": "git+https://github.com/iwascreatedtocreate/asciikit.git"
20
- },
21
- "bugs": {
22
- "url": "https://github.com/iwascreatedtocreate/asciikit/issues"
23
- },
24
- "license": "MIT",
25
- "type": "module",
26
- "sideEffects": false,
27
- "main": "./dist/index.js",
28
- "module": "./dist/index.js",
29
- "types": "./dist/index.d.ts",
30
- "exports": {
31
- ".": {
32
- "types": "./dist/index.d.ts",
33
- "default": "./dist/index.js"
34
- },
35
- "./react": {
36
- "types": "./dist/react/index.d.ts",
37
- "default": "./dist/react/index.js"
38
- },
39
- "./fonts": {
40
- "types": "./dist/fonts/index.d.ts",
41
- "default": "./dist/fonts/index.js"
42
- },
43
- "./fonts/lazy": {
44
- "types": "./dist/fonts/lazy.d.ts",
45
- "default": "./dist/fonts/lazy.js"
46
- },
47
- "./fonts/meta": {
48
- "types": "./dist/fonts/meta.d.ts",
49
- "default": "./dist/fonts/meta.js"
50
- },
51
- "./fonts/*": {
52
- "types": "./dist/fonts/*.d.ts",
53
- "default": "./dist/fonts/*.js"
54
- },
55
- "./package.json": "./package.json"
56
- },
57
- "files": [
58
- "dist",
59
- "README.md",
60
- "LICENSE"
61
- ],
62
- "scripts": {
63
- "build": "node scripts/generate-fonts.mjs && tsc -p tsconfig.json",
64
- "test": "node --test test/core.test.mjs"
65
- },
66
- "peerDependencies": {
67
- "react": ">=18"
68
- },
69
- "peerDependenciesMeta": {
70
- "react": {
71
- "optional": true
72
- }
73
- },
74
- "devDependencies": {
75
- "@types/node": "^24.19.4",
76
- "@types/react": "^19.3.3",
77
- "figlet": "^1.13.0",
78
- "react": "^19.3.1",
79
- "typescript": "^7.0.2"
80
- },
81
- "bin": {
82
- "asciikit": "./dist/cli.js"
83
- },
84
- "engines": {
85
- "node": ">=18.3"
86
- }
87
- }
1
+ {
2
+ "name": "@iwascreatedtocreate/asciikit",
3
+ "version": "0.3.0",
4
+ "description": "The advanced ASCII art toolkit for React & Next.js — 300+ FIGlet fonts, full smushing engine, effects, animations and image-to-ASCII. Import fonts like icons.",
5
+ "keywords": [
6
+ "ascii",
7
+ "ascii-art",
8
+ "figlet",
9
+ "react",
10
+ "nextjs",
11
+ "banner",
12
+ "text-art",
13
+ "fonts",
14
+ "terminal"
15
+ ],
16
+ "homepage": "https://asciikit.iwascreatedtocreate.com",
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/iwascreatedtocreate/asciikit.git"
20
+ },
21
+ "bugs": {
22
+ "url": "https://github.com/iwascreatedtocreate/asciikit/issues"
23
+ },
24
+ "license": "MIT",
25
+ "type": "module",
26
+ "sideEffects": [
27
+ "./dist/element.js"
28
+ ],
29
+ "main": "./dist/index.js",
30
+ "module": "./dist/index.js",
31
+ "types": "./dist/index.d.ts",
32
+ "exports": {
33
+ ".": {
34
+ "types": "./dist/index.d.ts",
35
+ "default": "./dist/index.js"
36
+ },
37
+ "./react": {
38
+ "types": "./dist/react/index.d.ts",
39
+ "default": "./dist/react/index.js"
40
+ },
41
+ "./element": {
42
+ "types": "./dist/element.d.ts",
43
+ "default": "./dist/element.js"
44
+ },
45
+ "./fonts": {
46
+ "types": "./dist/fonts/index.d.ts",
47
+ "default": "./dist/fonts/index.js"
48
+ },
49
+ "./fonts/lazy": {
50
+ "types": "./dist/fonts/lazy.d.ts",
51
+ "default": "./dist/fonts/lazy.js"
52
+ },
53
+ "./fonts/meta": {
54
+ "types": "./dist/fonts/meta.d.ts",
55
+ "default": "./dist/fonts/meta.js"
56
+ },
57
+ "./fonts/*": {
58
+ "types": "./dist/fonts/*.d.ts",
59
+ "default": "./dist/fonts/*.js"
60
+ },
61
+ "./package.json": "./package.json"
62
+ },
63
+ "files": [
64
+ "dist",
65
+ "README.md",
66
+ "LICENSE"
67
+ ],
68
+ "scripts": {
69
+ "build": "node scripts/generate-fonts.mjs && tsc -p tsconfig.json",
70
+ "test": "node --test test/core.test.mjs"
71
+ },
72
+ "peerDependencies": {
73
+ "react": ">=18"
74
+ },
75
+ "peerDependenciesMeta": {
76
+ "react": {
77
+ "optional": true
78
+ }
79
+ },
80
+ "devDependencies": {
81
+ "@types/node": "^24.19.4",
82
+ "@types/react": "^19.3.3",
83
+ "figlet": "^1.13.0",
84
+ "react": "^19.3.1",
85
+ "typescript": "^7.0.2"
86
+ },
87
+ "bin": {
88
+ "asciikit": "./dist/cli.js"
89
+ },
90
+ "engines": {
91
+ "node": ">=18.3"
92
+ }
93
+ }