@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/dist/export.js ADDED
@@ -0,0 +1,112 @@
1
+ import { gradients } from './color.js';
2
+ import { toLines } from './effects.js';
3
+ import { escapeHTML, own } from './util.js';
4
+ import { stringWidth } from './width.js';
5
+ const MONO = "ui-monospace, 'SFMono-Regular', 'JetBrains Mono', Menlo, Consolas, 'Liberation Mono', monospace";
6
+ function layout(art, o) {
7
+ const lines = toLines(art).map((l) => l.replace(/\s+$/, ''));
8
+ const fontSize = o.fontSize ?? 16;
9
+ const lineHeight = (o.lineHeight ?? 1) * fontSize;
10
+ const cell = (o.cellWidth ?? 0.6) * fontSize;
11
+ const padding = o.padding ?? 16;
12
+ const cols = lines.reduce((m, l) => Math.max(m, stringWidth(l)), 0);
13
+ const width = Math.ceil(cols * cell + padding * 2);
14
+ const height = Math.ceil(lines.length * lineHeight + padding * 2);
15
+ const stops = o.gradient
16
+ ? typeof o.gradient === 'string'
17
+ ? (own(gradients, o.gradient) ?? [o.gradient])
18
+ : o.gradient
19
+ : null;
20
+ return { lines, fontSize, lineHeight, cell, padding, width, height, stops };
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 function toSVG(art, options = {}) {
28
+ const L = layout(art, options);
29
+ const dir = options.gradientDirection ?? 'horizontal';
30
+ let defs = '';
31
+ let fill = escapeHTML(options.color ?? '#ededed');
32
+ if (L.stops && L.stops.length) {
33
+ const stopTags = L.stops
34
+ .map((c, i) => `<stop offset="${L.stops.length === 1 ? 0 : i / (L.stops.length - 1)}" stop-color="${escapeHTML(c)}"/>`)
35
+ .join('');
36
+ const [x2, y2] = dir === 'vertical' ? [0, 1] : dir === 'diagonal' ? [1, 1] : [1, 0];
37
+ defs =
38
+ 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>`;
41
+ fill = 'url(#ak-g)';
42
+ }
43
+ 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
+ })
52
+ .join('');
53
+ 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>`);
55
+ }
56
+ /** Browser: draw the art onto a new canvas. `scale` defaults to devicePixelRatio. */
57
+ export function toCanvas(art, options = {}) {
58
+ if (typeof document === 'undefined')
59
+ throw new Error('asciikit: toCanvas() needs a browser. Use toSVG() on the server.');
60
+ const L = layout(art, options);
61
+ const scale = options.scale ?? (typeof window !== 'undefined' ? window.devicePixelRatio || 1 : 1);
62
+ const canvas = document.createElement('canvas');
63
+ canvas.width = Math.ceil(L.width * scale);
64
+ canvas.height = Math.ceil(L.height * scale);
65
+ const ctx = canvas.getContext('2d');
66
+ ctx.scale(scale, scale);
67
+ if (options.background) {
68
+ ctx.fillStyle = options.background;
69
+ ctx.fillRect(0, 0, L.width, L.height);
70
+ }
71
+ ctx.font = `${L.fontSize}px ${options.fontFamily ?? MONO}`;
72
+ ctx.textBaseline = 'alphabetic';
73
+ if (L.stops && L.stops.length) {
74
+ const dir = options.gradientDirection ?? 'horizontal';
75
+ const g = dir === 'radial'
76
+ ? ctx.createRadialGradient(L.width / 2, L.height / 2, 0, L.width / 2, L.height / 2, Math.max(L.width, L.height) / 2)
77
+ : ctx.createLinearGradient(0, 0, dir === 'vertical' ? 0 : L.width, dir === 'horizontal' ? 0 : L.height);
78
+ L.stops.forEach((c, i) => g.addColorStop(L.stops.length === 1 ? 0 : i / (L.stops.length - 1), c));
79
+ ctx.fillStyle = g;
80
+ }
81
+ else {
82
+ ctx.fillStyle = options.color ?? '#ededed';
83
+ }
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;
90
+ 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);
94
+ ctx.restore();
95
+ });
96
+ return canvas;
97
+ }
98
+ /** Browser: render the art to a PNG Blob (e.g. for a download button). */
99
+ export function toPNG(art, options = {}) {
100
+ const canvas = toCanvas(art, options);
101
+ return new Promise((resolve, reject) => canvas.toBlob((b) => (b ? resolve(b) : reject(new Error('asciikit: PNG encoding failed'))), 'image/png'));
102
+ }
103
+ /** Browser: trigger a download of text, SVG or a Blob. */
104
+ export function downloadFile(filename, data, type = 'text/plain;charset=utf-8') {
105
+ const blob = typeof data === 'string' ? new Blob([data], { type }) : data;
106
+ const url = URL.createObjectURL(blob);
107
+ const a = document.createElement('a');
108
+ a.href = url;
109
+ a.download = filename;
110
+ a.click();
111
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
112
+ }
@@ -340,7 +340,7 @@ const byLoose = new Map(Object.keys(fontLoaders).map((id) => [normalise(id), id]
340
340
  * Load a bundled font on demand by id ("ansi-shadow") or name ("ANSI Shadow").
341
341
  */
342
342
  export function loadFont(idOrName) {
343
- const id = (idOrName in fontLoaders ? idOrName : byLoose.get(normalise(idOrName)));
343
+ const id = (Object.prototype.hasOwnProperty.call(fontLoaders, idOrName) ? idOrName : byLoose.get(normalise(idOrName)));
344
344
  if (!id)
345
345
  return Promise.reject(new Error(`asciikit: unknown font "${idOrName}"`));
346
346
  let p = cache.get(id);
package/dist/image.d.ts CHANGED
@@ -1,3 +1,6 @@
1
+ /** Upper bounds for output size (characters), regardless of options. */
2
+ export declare const MAX_COLUMNS = 1000;
3
+ export declare const MAX_ROWS = 1000;
1
4
  /** Character ramps ordered from dark (empty) to bright (dense). */
2
5
  export declare const charsets: {
3
6
  standard: string;
package/dist/image.js CHANGED
@@ -1,3 +1,7 @@
1
+ import { clamp, own } from './util.js';
2
+ /** Upper bounds for output size (characters), regardless of options. */
3
+ export const MAX_COLUMNS = 1000;
4
+ export const MAX_ROWS = 1000;
1
5
  /** Character ramps ordered from dark (empty) to bright (dense). */
2
6
  export const charsets = {
3
7
  standard: ' .:-=+*#%@',
@@ -122,9 +126,10 @@ const BRAILLE_BITS = [
122
126
  */
123
127
  export function pixelsToAscii(src, options = {}) {
124
128
  const mode = options.mode ?? 'ramp';
125
- const cellAspect = options.cellAspect ?? 2;
126
- const cols = Math.max(1, Math.floor(options.columns ?? 80));
127
- const rows = Math.max(1, Math.floor(options.rows ?? Math.round((src.height / src.width) * cols / cellAspect)));
129
+ const cellAspect = clamp(options.cellAspect, 0.1, 10, 2);
130
+ // Hard limits keep a bad or hostile `columns`/`rows` from allocating hundreds of MB.
131
+ const cols = Math.floor(clamp(options.columns, 1, MAX_COLUMNS, 80));
132
+ const rows = Math.floor(clamp(options.rows ?? Math.round(((src.height || 1) / (src.width || 1)) * cols / cellAspect), 1, MAX_ROWS, 1));
128
133
  const threshold = options.threshold ?? 0.5;
129
134
  if (mode === 'braille') {
130
135
  const pc = cols * 2;
@@ -187,7 +192,10 @@ export function pixelsToAscii(src, options = {}) {
187
192
  }
188
193
  }
189
194
  else {
190
- const ramp = Array.from(charsets[options.charset] ?? options.charset ?? charsets.standard);
195
+ const preset = options.charset === undefined ? charsets.standard : own(charsets, options.charset);
196
+ let ramp = Array.from(preset ?? options.charset ?? charsets.standard);
197
+ if (ramp.length < 2)
198
+ ramp = Array.from(charsets.standard);
191
199
  const q = quantize(lum, cols, rows, ramp.length, options.dither ?? 'none');
192
200
  lines = [];
193
201
  for (let y = 0; y < rows; y++) {
@@ -225,9 +233,14 @@ export async function imageToAscii(source, options = {}) {
225
233
  img.crossOrigin = 'anonymous';
226
234
  img.decoding = 'async';
227
235
  img.src = url;
228
- await img.decode();
229
- if (typeof source !== 'string')
230
- URL.revokeObjectURL(url);
236
+ try {
237
+ await img.decode();
238
+ }
239
+ finally {
240
+ // Release the blob URL even when decoding fails.
241
+ if (typeof source !== 'string')
242
+ URL.revokeObjectURL(url);
243
+ }
231
244
  el = img;
232
245
  w = img.naturalWidth;
233
246
  h = img.naturalHeight;
package/dist/index.d.ts CHANGED
@@ -5,6 +5,8 @@ export { render, renderLines, textSync, horizontalMode, verticalMode } from './r
5
5
  export { ascii, transform, type AsciiOptions, type TransformOptions } from './compose.js';
6
6
  export { toLines, measure, normalize, pad, trim, align, box, boxStyles, shadow, fill, replaceChars, invert, flipHorizontal, flipVertical, rotate, scale, join, stack, overlay, pipe, gradientCells, toAnsi, toHTML, type Art, type Spacing, type BoxChars, type BoxStyle, type BoxOptions, type ShadowOptions, type JoinOptions, type GradientDirection, type ColorCell, } from './effects.js';
7
7
  export { parseColor, toHex, sampleGradient, gradients, type RGB, type GradientName } from './color.js';
8
- export { pixelsToAscii, imageToAscii, charsets, type CharsetName, type PixelSource, type ImageToAsciiOptions, type AsciiImageResult, } from './image.js';
8
+ export { pixelsToAscii, imageToAscii, MAX_COLUMNS, MAX_ROWS, charsets, type CharsetName, type PixelSource, type ImageToAsciiOptions, type AsciiImageResult, } from './image.js';
9
9
  export { animationFrame, continuousEffects, type AnimationEffect, type FrameOptions } from './animate.js';
10
10
  export { spinners, type Spinner, type SpinnerName } from './spinners.js';
11
+ export { toSVG, toCanvas, toPNG, downloadFile, type ImageExportOptions } from './export.js';
12
+ export { graphemes, charWidth, stringWidth, cells } from './width.js';
package/dist/index.js CHANGED
@@ -4,6 +4,8 @@ export { render, renderLines, textSync, horizontalMode, verticalMode } from './r
4
4
  export { ascii, transform } from './compose.js';
5
5
  export { toLines, measure, normalize, pad, trim, align, box, boxStyles, shadow, fill, replaceChars, invert, flipHorizontal, flipVertical, rotate, scale, join, stack, overlay, pipe, gradientCells, toAnsi, toHTML, } from './effects.js';
6
6
  export { parseColor, toHex, sampleGradient, gradients } from './color.js';
7
- export { pixelsToAscii, imageToAscii, charsets, } from './image.js';
7
+ export { pixelsToAscii, imageToAscii, MAX_COLUMNS, MAX_ROWS, charsets, } from './image.js';
8
8
  export { animationFrame, continuousEffects } from './animate.js';
9
9
  export { spinners } from './spinners.js';
10
+ export { toSVG, toCanvas, toPNG, downloadFile } from './export.js';
11
+ export { graphemes, charWidth, stringWidth, cells } from './width.js';
@@ -51,6 +51,14 @@ export function AsciiAnimator({ art, animate, as: Tag = 'pre', label, color, gra
51
51
  return () => io.disconnect();
52
52
  }
53
53
  }, [trigger, reduced, finalArt]);
54
+ // Geometry check (not IntersectionObserver, whose first report can be wrong in background tabs).
55
+ const isOnScreen = () => {
56
+ const el = ref.current;
57
+ if (!el || typeof window === 'undefined')
58
+ return true;
59
+ const r = el.getBoundingClientRect();
60
+ return r.bottom > 0 && r.right > 0 && r.top < window.innerHeight && r.left < window.innerWidth;
61
+ };
54
62
  // Animation loop
55
63
  useEffect(() => {
56
64
  if (run === 0 || reduced)
@@ -62,7 +70,24 @@ export function AsciiAnimator({ art, animate, as: Tag = 'pre', label, color, gra
62
70
  let iteration = 0;
63
71
  let start = 0;
64
72
  const maxLoops = loop === true ? Infinity : typeof loop === 'number' ? loop : 1;
73
+ let frames = 0;
65
74
  const step = (now) => {
75
+ // Every 15 frames, pause while off screen: no work and no re-renders until it scrolls back in.
76
+ if (frames++ % 15 === 0 && !isOnScreen()) {
77
+ const pausedAt = now;
78
+ const poll = () => {
79
+ if (isOnScreen()) {
80
+ if (start)
81
+ start += performance.now() - pausedAt;
82
+ raf = requestAnimationFrame(step);
83
+ }
84
+ else {
85
+ timer = setTimeout(poll, 250);
86
+ }
87
+ };
88
+ timer = setTimeout(poll, 250);
89
+ return;
90
+ }
66
91
  if (!start)
67
92
  start = now;
68
93
  const elapsed = now - start;
@@ -1,4 +1,5 @@
1
1
  import { gradients } from '../color.js';
2
+ import { own } from '../util.js';
2
3
  export const DEFAULT_MONO = 'ui-monospace, "SFMono-Regular", "JetBrains Mono", "Cascadia Mono", Menlo, Consolas, "Liberation Mono", monospace';
3
4
  export function asciiStyle(p, extra) {
4
5
  const style = {
@@ -11,7 +12,7 @@ export function asciiStyle(p, extra) {
11
12
  color: p.color,
12
13
  };
13
14
  if (p.gradient) {
14
- const stops = (typeof p.gradient === 'string' ? gradients[p.gradient] : p.gradient).join(', ');
15
+ const stops = (typeof p.gradient === 'string' ? (own(gradients, p.gradient) ?? [p.gradient, p.gradient]) : p.gradient).join(', ');
15
16
  const d = p.gradientDirection ?? 'horizontal';
16
17
  const image = d === 'radial'
17
18
  ? `radial-gradient(circle, ${stops})`
package/dist/render.js CHANGED
@@ -110,16 +110,19 @@ function smushChars(l, r, c) {
110
110
  }
111
111
  return null;
112
112
  }
113
- function smushAmount(out, glyph, c) {
113
+ /**
114
+ * How far the next glyph can slide left. `lastNonSpace[row]` is maintained by the caller,
115
+ * so this is O(glyph width) instead of rescanning the whole output row (which made long
116
+ * lines quadratic).
117
+ */
118
+ function smushAmount(out, glyph, c, lastNonSpace) {
114
119
  if ((c.mode & (H_SMUSH | H_KERN)) === 0)
115
120
  return 0;
116
121
  let max = Math.min(c.curWidth, out[0].length);
117
122
  for (let row = 0; row < glyph.length; row++) {
118
123
  const line = out[row];
119
124
  const g = glyph[row];
120
- let lb = line.length;
121
- while (lb > 0 && (lb >= line.length || line[lb] === ' '))
122
- lb--;
125
+ const lb = Math.max(0, lastNonSpace[row] ?? -1);
123
126
  let cb = 0;
124
127
  while (cb < g.length && g[cb] === ' ')
125
128
  cb++;
@@ -164,6 +167,8 @@ function renderSingleLine(text, ctx) {
164
167
  const out = Array.from({ length: height }, () => []);
165
168
  const spacing = Math.max(0, Math.floor(opts.letterSpacing ?? 0));
166
169
  const c = { mode: ctx.mode, hardblank: font.hardblank, rtl: ctx.rtl, prevWidth: 0, curWidth: 0 };
170
+ // Index of the last non-space character in each output row (-1 = none yet).
171
+ const lastNonSpace = Array.from({ length: height }, () => -1);
167
172
  for (const cp of cps) {
168
173
  let glyph;
169
174
  if (cp === 32 && opts.wordSpacing !== undefined) {
@@ -179,12 +184,14 @@ function renderSingleLine(text, ctx) {
179
184
  let amt = 0;
180
185
  if (out[0].length > 0) {
181
186
  if (spacing > 0) {
182
- for (const row of out)
187
+ out.forEach((row, r) => {
183
188
  for (let i = 0; i < spacing; i++)
184
189
  row.push(font.hardblank);
190
+ lastNonSpace[r] = row.length - 1;
191
+ });
185
192
  }
186
193
  else {
187
- amt = smushAmount(out, glyph, c);
194
+ amt = smushAmount(out, glyph, c, lastNonSpace);
188
195
  }
189
196
  }
190
197
  for (let r = 0; r < height; r++) {
@@ -198,6 +205,13 @@ function renderSingleLine(text, ctx) {
198
205
  }
199
206
  for (let k = amt; k < g.length; k++)
200
207
  row.push(g[k]);
208
+ // Smushing never turns a visible char into a space, so only the touched tail can move the marker.
209
+ for (let k = row.length - 1; k >= Math.max(0, len - amt) && k > lastNonSpace[r]; k--) {
210
+ if (row[k] !== ' ') {
211
+ lastNonSpace[r] = k;
212
+ break;
213
+ }
214
+ }
201
215
  }
202
216
  c.prevWidth = width;
203
217
  }
package/dist/util.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Safe lookup in a plain record: only the object's own keys count, so inputs
3
+ * like "constructor" or "__proto__" never resolve to Object.prototype members.
4
+ */
5
+ export declare function own<T>(record: Readonly<Record<string, T>>, key: string): T | undefined;
6
+ /** Clamp a number into [min, max]; NaN/undefined fall back to `fallback`. */
7
+ export declare function clamp(value: number | undefined, min: number, max: number, fallback: number): number;
8
+ /** Escape text for HTML element content and double-quoted attributes. */
9
+ export declare function escapeHTML(s: string): string;
10
+ /**
11
+ * Accepts only values that are safe to embed as a CSS color: hex, rgb()/rgba()/hsl()/hsla()
12
+ * with numeric arguments, or a bare color keyword. Anything else returns `undefined`.
13
+ */
14
+ export declare function safeCssColor(value: string | undefined): string | undefined;
package/dist/util.js ADDED
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Safe lookup in a plain record: only the object's own keys count, so inputs
3
+ * like "constructor" or "__proto__" never resolve to Object.prototype members.
4
+ */
5
+ export function own(record, key) {
6
+ return Object.prototype.hasOwnProperty.call(record, key) ? record[key] : undefined;
7
+ }
8
+ /** Clamp a number into [min, max]; NaN/undefined fall back to `fallback`. */
9
+ export function clamp(value, min, max, fallback) {
10
+ const v = typeof value === 'number' && Number.isFinite(value) ? value : fallback;
11
+ return Math.min(max, Math.max(min, v));
12
+ }
13
+ /** Escape text for HTML element content and double-quoted attributes. */
14
+ export function escapeHTML(s) {
15
+ return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;');
16
+ }
17
+ /**
18
+ * Accepts only values that are safe to embed as a CSS color: hex, rgb()/rgba()/hsl()/hsla()
19
+ * with numeric arguments, or a bare color keyword. Anything else returns `undefined`.
20
+ */
21
+ export function safeCssColor(value) {
22
+ if (!value)
23
+ return undefined;
24
+ const v = value.trim();
25
+ if (/^#[0-9a-f]{3,8}$/i.test(v))
26
+ return v;
27
+ if (/^(rgb|rgba|hsl|hsla)\(\s*[-\d.%\s,/deg]+\)$/i.test(v))
28
+ return v;
29
+ if (/^[a-z]{3,30}$/i.test(v))
30
+ return v;
31
+ return undefined;
32
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Display-width helpers. Terminals and monospace fonts draw CJK characters and
3
+ * emoji two columns wide, and combining marks zero wide. These helpers let every
4
+ * effect (box, pad, align, flip, …) line things up correctly.
5
+ */
6
+ /** Split text into user-perceived characters (grapheme clusters). */
7
+ export declare function graphemes(text: string): string[];
8
+ /** Columns a single grapheme occupies: 0, 1 or 2. */
9
+ export declare function charWidth(grapheme: string): 0 | 1 | 2;
10
+ /** Display width of a string in columns. */
11
+ export declare function stringWidth(text: string): number;
12
+ /**
13
+ * Split a string into one entry per terminal column. A wide character is followed
14
+ * by an empty-string placeholder, so `cells(s).join('') === s` and `cells(s).length`
15
+ * is the display width. Zero-width graphemes are dropped from the grid.
16
+ */
17
+ export declare function cells(text: string): string[];
18
+ /**
19
+ * Repair a cell row after cells were moved or replaced: a placeholder must follow a
20
+ * wide char, and a wide char must be followed by its placeholder.
21
+ */
22
+ export declare function fixCells(row: string[]): string[];
package/dist/width.js ADDED
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Display-width helpers. Terminals and monospace fonts draw CJK characters and
3
+ * emoji two columns wide, and combining marks zero wide. These helpers let every
4
+ * effect (box, pad, align, flip, …) line things up correctly.
5
+ */
6
+ let segmenter;
7
+ function getSegmenter() {
8
+ if (segmenter === undefined) {
9
+ const Seg = Intl.Segmenter;
10
+ segmenter = Seg ? new Seg(undefined, { granularity: 'grapheme' }) : null;
11
+ }
12
+ return segmenter;
13
+ }
14
+ /** Split text into user-perceived characters (grapheme clusters). */
15
+ export function graphemes(text) {
16
+ if (!/[^\x20-\x7e]/.test(text))
17
+ return text.split(''); // ASCII fast path
18
+ const seg = getSegmenter();
19
+ if (!seg)
20
+ return Array.from(text);
21
+ const out = [];
22
+ for (const s of seg.segment(text))
23
+ out.push(s.segment);
24
+ return out;
25
+ }
26
+ function isWideCodePoint(cp) {
27
+ return ((cp >= 0x1100 && cp <= 0x115f) || // Hangul Jamo
28
+ (cp >= 0x2e80 && cp <= 0x303e) || // CJK radicals, punctuation
29
+ (cp >= 0x3041 && cp <= 0x33ff) || // Kana, CJK compat
30
+ (cp >= 0x3400 && cp <= 0x4dbf) || // CJK ext A
31
+ (cp >= 0x4e00 && cp <= 0x9fff) || // CJK unified
32
+ (cp >= 0xa000 && cp <= 0xa4cf) || // Yi
33
+ (cp >= 0xac00 && cp <= 0xd7a3) || // Hangul syllables
34
+ (cp >= 0xf900 && cp <= 0xfaff) || // CJK compat ideographs
35
+ (cp >= 0xfe30 && cp <= 0xfe4f) || // CJK compat forms
36
+ (cp >= 0xff00 && cp <= 0xff60) || // Fullwidth forms
37
+ (cp >= 0xffe0 && cp <= 0xffe6) ||
38
+ (cp >= 0x1f300 && cp <= 0x1f64f) || // Misc symbols & pictographs, emoticons
39
+ (cp >= 0x1f680 && cp <= 0x1f6ff) || // Transport & map
40
+ (cp >= 0x1f900 && cp <= 0x1f9ff) || // Supplemental symbols & pictographs
41
+ (cp >= 0x1fa70 && cp <= 0x1faff) ||
42
+ (cp >= 0x20000 && cp <= 0x3fffd) // CJK ext B+
43
+ );
44
+ }
45
+ const ZERO_WIDTH = /^[\p{Mn}\p{Me}\p{Cf}]+$/u;
46
+ const EMOJI_PRESENTATION = /\p{Emoji_Presentation}|️/u;
47
+ /** Columns a single grapheme occupies: 0, 1 or 2. */
48
+ export function charWidth(grapheme) {
49
+ if (grapheme.length === 1) {
50
+ const c = grapheme.charCodeAt(0);
51
+ if (c >= 0x20 && c < 0x7f)
52
+ return 1;
53
+ if (c < 0x20 || (c >= 0x7f && c < 0xa0))
54
+ return 0;
55
+ }
56
+ if (!grapheme || ZERO_WIDTH.test(grapheme))
57
+ return 0;
58
+ if (EMOJI_PRESENTATION.test(grapheme))
59
+ return 2;
60
+ return isWideCodePoint(grapheme.codePointAt(0)) ? 2 : 1;
61
+ }
62
+ /** Display width of a string in columns. */
63
+ export function stringWidth(text) {
64
+ if (!/[^\x20-\x7e]/.test(text))
65
+ return text.length;
66
+ let w = 0;
67
+ for (const g of graphemes(text))
68
+ w += charWidth(g);
69
+ return w;
70
+ }
71
+ /**
72
+ * Split a string into one entry per terminal column. A wide character is followed
73
+ * by an empty-string placeholder, so `cells(s).join('') === s` and `cells(s).length`
74
+ * is the display width. Zero-width graphemes are dropped from the grid.
75
+ */
76
+ export function cells(text) {
77
+ if (!/[^\x20-\x7e]/.test(text))
78
+ return text.split('');
79
+ const out = [];
80
+ for (const g of graphemes(text)) {
81
+ const w = charWidth(g);
82
+ if (w === 0) {
83
+ if (out.length)
84
+ out[out.length - 1] += g; // keep marks attached
85
+ continue;
86
+ }
87
+ out.push(g);
88
+ if (w === 2)
89
+ out.push('');
90
+ }
91
+ return out;
92
+ }
93
+ /**
94
+ * Repair a cell row after cells were moved or replaced: a placeholder must follow a
95
+ * wide char, and a wide char must be followed by its placeholder.
96
+ */
97
+ export function fixCells(row) {
98
+ const out = row.slice();
99
+ for (let i = 0; i < out.length; i++) {
100
+ const c = out[i];
101
+ if (c === '') {
102
+ const prev = out[i - 1];
103
+ if (prev === undefined || prev === '' || charWidth(prev) !== 2)
104
+ out[i] = ' ';
105
+ }
106
+ else if (charWidth(c) === 2 && out[i + 1] !== '') {
107
+ out[i] = ' ';
108
+ }
109
+ }
110
+ return out;
111
+ }