@suzhou-numerals/core 0.0.0-stage → 0.0.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Karl Norling
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software or 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.
package/README.md CHANGED
@@ -1,3 +1,28 @@
1
- # Temporary Holding Version
1
+ # @suzhou-numerals/core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Render any number as [Suzhou numerals](https://en.wikipedia.org/wiki/Suzhou_numerals) in SVG. No dependencies; works in Node and the browser.
4
+
5
+ <img src="https://raw.githubusercontent.com/karlnorling/suzhou-numerals/main/examples/1993.svg" alt="1993" height="80"> <img src="https://raw.githubusercontent.com/karlnorling/suzhou-numerals/main/examples/21.svg" alt="21" height="80"> <img src="https://raw.githubusercontent.com/karlnorling/suzhou-numerals/main/examples/rainbow.svg" alt="1234567 in rainbow colours" height="80">
6
+
7
+ ```sh
8
+ npm install @suzhou-numerals/core
9
+ ```
10
+
11
+ ```js
12
+ import { toSvg } from '@suzhou-numerals/core';
13
+
14
+ document.body.innerHTML = toSvg(1993, { size: 200 });
15
+
16
+ // Colours and backgrounds take CSS gradients too.
17
+ toSvg('1234567', {
18
+ color: 'linear-gradient(to right, #e03131, #f76707, #fab005, #40c057, #228be6, #7048e8, #be4bdb)',
19
+ });
20
+ ```
21
+
22
+ Neighbouring 1s, 2s and 3s alternate upright and flat, a dot marks the decimal point, and negatives get a diagonal stroke. For PNG, JPEG or WebP, use [`@suzhou-numerals/raster`](https://www.npmjs.com/package/@suzhou-numerals/raster).
23
+
24
+ See the [docs and playground](https://karlnorling.github.io/suzhou-numerals/) for every option and how numbers are drawn.
25
+
26
+ ## License
27
+
28
+ MIT
@@ -0,0 +1,33 @@
1
+ /** Suzhou numerals are decimal: each place holds a digit from 0 to 9. */
2
+ export declare const BASE = 10;
3
+ /** One digit fills a cell this wide and tall, in viewBox units, centred on the origin. */
4
+ export declare const CELL_WIDTH = 44;
5
+ export declare const CELL_HEIGHT = 60;
6
+ /** A stroke from one point to another, or a circle. Coordinates are centred on the cell. */
7
+ export type Stroke = {
8
+ kind: 'line';
9
+ x1: number;
10
+ y1: number;
11
+ x2: number;
12
+ y2: number;
13
+ } | {
14
+ kind: 'circle';
15
+ cx: number;
16
+ cy: number;
17
+ r: number;
18
+ };
19
+ /**
20
+ * The strokes for one digit from 0 to 9, in a cell `CELL_WIDTH` × `CELL_HEIGHT` centred on
21
+ * (0, 0).
22
+ *
23
+ * 0 is 〇, 1 to 3 are bars and 4 is a cross (〤). 5 to 9 are 0 to 4 with an upright bar on top:
24
+ * a circle (〥), one to three flat bars (〦〧〨) or the cross (〩). `flat` turns 1, 2 and 3 on
25
+ * their side, the form writers switch to when two of them sit next to each other.
26
+ */
27
+ export declare function digitStrokes(digit: number, flat?: boolean): Stroke[];
28
+ /**
29
+ * Which digits to write flat. In a run of neighbouring 1s, 2s and 3s every second one turns
30
+ * on its side, so 21 reads 〢一 and can't be mistaken for 〣.
31
+ */
32
+ export declare function flatDigits(digits: readonly number[]): boolean[];
33
+ //# sourceMappingURL=glyph.d.ts.map
package/dist/glyph.js ADDED
@@ -0,0 +1,73 @@
1
+ /** Suzhou numerals are decimal: each place holds a digit from 0 to 9. */
2
+ export const BASE = 10;
3
+ /** One digit fills a cell this wide and tall, in viewBox units, centred on the origin. */
4
+ export const CELL_WIDTH = 44;
5
+ export const CELL_HEIGHT = 60;
6
+ const TOP = -CELL_HEIGHT / 2 + 2;
7
+ const BOTTOM = CELL_HEIGHT / 2 - 2;
8
+ const line = (x1, y1, x2, y2) => ({
9
+ kind: 'line',
10
+ x1,
11
+ y1,
12
+ x2,
13
+ y2,
14
+ });
15
+ /** One, two or three bars, upright (〡〢〣) or flat (一二三). */
16
+ function bars(count, flat, top = TOP, bottom = BOTTOM) {
17
+ const spacing = 14;
18
+ const offsets = Array.from({ length: count }, (_, i) => (i - (count - 1) / 2) * spacing);
19
+ if (!flat)
20
+ return offsets.map((x) => line(x, top, x, bottom));
21
+ const mid = (top + bottom) / 2;
22
+ return offsets.map((y) => line(-18, mid + y, 18, mid + y));
23
+ }
24
+ /**
25
+ * The strokes for one digit from 0 to 9, in a cell `CELL_WIDTH` × `CELL_HEIGHT` centred on
26
+ * (0, 0).
27
+ *
28
+ * 0 is 〇, 1 to 3 are bars and 4 is a cross (〤). 5 to 9 are 0 to 4 with an upright bar on top:
29
+ * a circle (〥), one to three flat bars (〦〧〨) or the cross (〩). `flat` turns 1, 2 and 3 on
30
+ * their side, the form writers switch to when two of them sit next to each other.
31
+ */
32
+ export function digitStrokes(digit, flat = false) {
33
+ if (!Number.isInteger(digit) || digit < 0 || digit > 9) {
34
+ throw new RangeError(`A Suzhou digit runs from 0 to 9, got ${digit}`);
35
+ }
36
+ switch (digit) {
37
+ case 0:
38
+ return [{ kind: 'circle', cx: 0, cy: 0, r: 15 }];
39
+ case 1:
40
+ case 2:
41
+ case 3:
42
+ return bars(digit, flat);
43
+ case 4:
44
+ return [line(-15, TOP + 4, 15, BOTTOM - 4), line(15, TOP + 4, -15, BOTTOM - 4)];
45
+ case 5:
46
+ return [line(0, TOP, 0, 2), { kind: 'circle', cx: 0, cy: 15, r: 13 }];
47
+ case 6:
48
+ case 7:
49
+ case 8: {
50
+ const below = bars(digit - 5, true, 2, BOTTOM);
51
+ const first = below[0];
52
+ return [line(0, TOP, 0, first.kind === 'line' ? first.y1 : 0), ...below];
53
+ }
54
+ default:
55
+ return [line(0, TOP, 0, 14), line(-14, 2, 14, BOTTOM), line(14, 2, -14, BOTTOM)];
56
+ }
57
+ }
58
+ /**
59
+ * Which digits to write flat. In a run of neighbouring 1s, 2s and 3s every second one turns
60
+ * on its side, so 21 reads 〢一 and can't be mistaken for 〣.
61
+ */
62
+ export function flatDigits(digits) {
63
+ let run = 0;
64
+ return digits.map((digit) => {
65
+ if (digit < 1 || digit > 3) {
66
+ run = 0;
67
+ return false;
68
+ }
69
+ run++;
70
+ return run % 2 === 0;
71
+ });
72
+ }
73
+ //# sourceMappingURL=glyph.js.map
@@ -0,0 +1,6 @@
1
+ export type { NumberInput, ParsedNumber } from './parse.js';
2
+ export { parse, format } from './number.js';
3
+ export { BASE, CELL_HEIGHT, CELL_WIDTH, digitStrokes, flatDigits, type Stroke } from './glyph.js';
4
+ export { toSvg, digitSvg, type SvgOptions } from './svg.js';
5
+ export { parseGradient, type Gradient, type GradientStop, type Paint } from './paint.js';
6
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export { parse, format } from './number.js';
2
+ export { BASE, CELL_HEIGHT, CELL_WIDTH, digitStrokes, flatDigits } from './glyph.js';
3
+ export { toSvg, digitSvg } from './svg.js';
4
+ export { parseGradient } from './paint.js';
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,6 @@
1
+ import { type NumberInput, type ParsedNumber } from './parse.js';
2
+ /** Splits a number into its decimal digits, one per place. */
3
+ export declare function parse(value: NumberInput): ParsedNumber;
4
+ /** Writes parsed digits back as a canonical decimal string, e.g. `-12.5`. */
5
+ export declare function format(number: ParsedNumber): string;
6
+ //# sourceMappingURL=number.d.ts.map
package/dist/number.js ADDED
@@ -0,0 +1,11 @@
1
+ import { BASE } from './glyph.js';
2
+ import { formatInBase, parseInBase } from './parse.js';
3
+ /** Splits a number into its decimal digits, one per place. */
4
+ export function parse(value) {
5
+ return parseInBase(value, BASE);
6
+ }
7
+ /** Writes parsed digits back as a canonical decimal string, e.g. `-12.5`. */
8
+ export function format(number) {
9
+ return formatInBase(number, BASE);
10
+ }
11
+ //# sourceMappingURL=number.js.map
@@ -0,0 +1,51 @@
1
+ /** A colour stop. `offset` runs from 0 to 1; leave it out to space stops evenly. */
2
+ export interface GradientStop {
3
+ color: string;
4
+ offset?: number;
5
+ }
6
+ /** A gradient across the whole image, for `color` or `background`. */
7
+ export interface Gradient {
8
+ /** Default `linear`. */
9
+ type?: 'linear' | 'radial';
10
+ /** At least one stop. Plain strings are spaced evenly. */
11
+ stops: ReadonlyArray<string | GradientStop>;
12
+ /**
13
+ * Direction of a linear gradient in degrees, as in CSS: 0 runs bottom to top, 90 left to
14
+ * right and the default, 180, top to bottom.
15
+ */
16
+ angle?: number;
17
+ /**
18
+ * Repeat the stops, like CSS `repeating-linear-gradient()`: the pattern from the first stop
19
+ * to the last one repeats across the image. Use it for stripes.
20
+ */
21
+ repeat?: boolean;
22
+ }
23
+ /** A colour, a CSS gradient string such as `linear-gradient(90deg, red, blue)`, or a gradient. */
24
+ export type Paint = string | Gradient;
25
+ export interface Box {
26
+ x: number;
27
+ y: number;
28
+ width: number;
29
+ height: number;
30
+ }
31
+ /** A resolved paint: the value for a `fill` or `stroke` attribute and any `<defs>` it needs. */
32
+ export interface ResolvedPaint {
33
+ value: string;
34
+ def: string;
35
+ }
36
+ /**
37
+ * Turns a CSS `linear-gradient()`, `radial-gradient()` or their `repeating-` forms into a
38
+ * {@link Gradient}. Stop positions are percentages, and a stop can have two
39
+ * (`red 10% 20%`) to make a hard-edged band.
40
+ */
41
+ export declare function parseGradient(css: string): Gradient | undefined;
42
+ /**
43
+ * Resolves a paint to an attribute value. Gradients become a `<linearGradient>` or
44
+ * `<radialGradient>` in user space over `box`, so they span the whole image the same way
45
+ * whether they paint one stroke or the background. The id is a hash of the definition, so
46
+ * two inline SVGs only share an id when they share the gradient too.
47
+ */
48
+ export declare function resolvePaint(paint: Paint, box: Box, prefix: string): ResolvedPaint;
49
+ export declare function num(value: number): string;
50
+ export declare function escapeAttr(text: string): string;
51
+ //# sourceMappingURL=paint.d.ts.map
package/dist/paint.js ADDED
@@ -0,0 +1,182 @@
1
+ const GRADIENT = /^\s*(repeating-)?(linear|radial)-gradient\(([\s\S]*)\)\s*$/i;
2
+ /**
3
+ * Turns a CSS `linear-gradient()`, `radial-gradient()` or their `repeating-` forms into a
4
+ * {@link Gradient}. Stop positions are percentages, and a stop can have two
5
+ * (`red 10% 20%`) to make a hard-edged band.
6
+ */
7
+ export function parseGradient(css) {
8
+ const match = GRADIENT.exec(css);
9
+ if (!match)
10
+ return undefined;
11
+ const repeat = match[1] !== undefined;
12
+ const type = match[2].toLowerCase();
13
+ const parts = splitTopLevel(match[3]);
14
+ let angle;
15
+ if (type === 'linear' && parts.length > 0) {
16
+ angle = parseDirection(parts[0]);
17
+ if (angle !== undefined)
18
+ parts.shift();
19
+ }
20
+ else if (type === 'radial' &&
21
+ parts.length > 0 &&
22
+ /^(circle|ellipse|closest|farthest|at)\b/i.test(parts[0])) {
23
+ // Shape and position are accepted but always drawn as a circle from the centre.
24
+ parts.shift();
25
+ }
26
+ if (parts.length === 0)
27
+ throw new SyntaxError(`A gradient needs at least one colour: ${css}`);
28
+ const stops = parts.flatMap((part) => {
29
+ const stop = /^([\s\S]*?\S)\s+(-?[\d.]+%|0)(?:\s+(-?[\d.]+%|0))?$/.exec(part);
30
+ if (!stop)
31
+ return [{ color: part }];
32
+ const color = stop[1];
33
+ const offsets = [stop[2], stop[3]].filter((o) => o !== undefined);
34
+ return offsets.map((o) => ({ color, offset: Number.parseFloat(o) / 100 }));
35
+ });
36
+ return {
37
+ type,
38
+ stops,
39
+ ...(angle === undefined ? {} : { angle }),
40
+ ...(repeat ? { repeat } : {}),
41
+ };
42
+ }
43
+ /**
44
+ * Resolves a paint to an attribute value. Gradients become a `<linearGradient>` or
45
+ * `<radialGradient>` in user space over `box`, so they span the whole image the same way
46
+ * whether they paint one stroke or the background. The id is a hash of the definition, so
47
+ * two inline SVGs only share an id when they share the gradient too.
48
+ */
49
+ export function resolvePaint(paint, box, prefix) {
50
+ const gradient = typeof paint === 'string' ? parseGradient(paint) : paint;
51
+ if (gradient === undefined)
52
+ return { value: paint, def: '' };
53
+ if (gradient.stops.length === 0)
54
+ throw new RangeError('A gradient needs at least one stop');
55
+ let spaced = spaceStops(gradient.stops);
56
+ // A repeating gradient draws one period, from the first stop to the last, and lets
57
+ // spreadMethod="repeat" tile it along the line.
58
+ let [from, to] = [0, 1];
59
+ if (gradient.repeat) {
60
+ from = spaced[0].offset;
61
+ to = spaced.at(-1).offset;
62
+ if (!(to > from))
63
+ throw new RangeError('A repeating gradient needs stops that span some distance');
64
+ spaced = spaced.map((s) => ({ ...s, offset: (s.offset - from) / (to - from) }));
65
+ }
66
+ const spread = gradient.repeat ? ' spreadMethod="repeat"' : '';
67
+ // Built on use, since a radial gradient adjusts the offsets first.
68
+ const stops = () => spaced
69
+ .map(({ color, offset }) => `<stop offset="${num(offset)}" stop-color="${escapeAttr(color)}"/>`)
70
+ .join('');
71
+ const cx = box.x + box.width / 2;
72
+ const cy = box.y + box.height / 2;
73
+ let body;
74
+ if ((gradient.type ?? 'linear') === 'radial') {
75
+ // A repeating radial pattern starts at the centre, so only the last stop sets its size.
76
+ const r = (Math.hypot(box.width, box.height) / 2) * (gradient.repeat ? to : 1);
77
+ if (gradient.repeat && from !== 0) {
78
+ spaced = spaced.map((s) => ({ ...s, offset: from / to + s.offset * (1 - from / to) }));
79
+ }
80
+ body = `radialGradient gradientUnits="userSpaceOnUse"${spread} cx="${num(cx)}" cy="${num(cy)}" r="${num(r)}">${stops()}</radialGradient>`;
81
+ }
82
+ else {
83
+ // The CSS gradient line: through the centre, long enough that the corners get the end colours.
84
+ const radians = ((gradient.angle ?? 180) * Math.PI) / 180;
85
+ const dx = Math.sin(radians);
86
+ const dy = -Math.cos(radians);
87
+ const half = (Math.abs(box.width * dx) + Math.abs(box.height * dy)) / 2;
88
+ const at = (t) => [cx + dx * half * (2 * t - 1), cy + dy * half * (2 * t - 1)];
89
+ const [x1, y1] = at(from);
90
+ const [x2, y2] = at(to);
91
+ body = `linearGradient gradientUnits="userSpaceOnUse"${spread} x1="${num(x1)}" y1="${num(y1)}" x2="${num(x2)}" y2="${num(y2)}">${stops()}</linearGradient>`;
92
+ }
93
+ const id = `${prefix}-${hash(body)}`;
94
+ return { value: `url(#${id})`, def: `<${body.replace(' ', ` id="${id}" `)}` };
95
+ }
96
+ /** Fills in missing offsets the way CSS does: ends at 0 and 1, gaps spread evenly, never backwards. */
97
+ function spaceStops(input) {
98
+ const stops = input.map((s) => (typeof s === 'string' ? { color: s } : { ...s }));
99
+ if (stops[0].offset === undefined)
100
+ stops[0].offset = 0;
101
+ if (stops.at(-1).offset === undefined)
102
+ stops.at(-1).offset = stops.length === 1 ? 0 : 1;
103
+ let max = 0;
104
+ for (const stop of stops) {
105
+ if (stop.offset !== undefined)
106
+ stop.offset = max = Math.max(max, stop.offset);
107
+ }
108
+ for (let i = 1; i < stops.length; i++) {
109
+ if (stops[i].offset !== undefined)
110
+ continue;
111
+ let j = i;
112
+ while (stops[j].offset === undefined)
113
+ j++;
114
+ const from = stops[i - 1].offset;
115
+ const step = (stops[j].offset - from) / (j - i + 1);
116
+ for (let k = i; k < j; k++)
117
+ stops[k].offset = from + step * (k - i + 1);
118
+ }
119
+ return stops;
120
+ }
121
+ const SIDES = {
122
+ top: [0, -1],
123
+ bottom: [0, 1],
124
+ left: [-1, 0],
125
+ right: [1, 0],
126
+ };
127
+ function parseDirection(part) {
128
+ const angle = /^(-?[\d.]+)(deg|turn|rad|grad)$/i.exec(part);
129
+ if (angle) {
130
+ const value = Number(angle[1]);
131
+ const unit = angle[2].toLowerCase();
132
+ if (unit === 'turn')
133
+ return value * 360;
134
+ if (unit === 'rad')
135
+ return (value * 180) / Math.PI;
136
+ if (unit === 'grad')
137
+ return value * 0.9;
138
+ return value;
139
+ }
140
+ const to = /^to\s+(top|bottom|left|right)(?:\s+(top|bottom|left|right))?$/i.exec(part);
141
+ if (!to)
142
+ return undefined;
143
+ const [x1, y1] = SIDES[to[1].toLowerCase()];
144
+ const [x2, y2] = to[2] ? SIDES[to[2].toLowerCase()] : [0, 0];
145
+ // Corners point along the diagonal of a square; close to CSS for the tall images drawn here.
146
+ return (Math.atan2(x1 + x2, -(y1 + y2)) * 180) / Math.PI;
147
+ }
148
+ /** Splits on commas that aren't inside parentheses, so `rgb(1, 2, 3)` stays whole. */
149
+ function splitTopLevel(text) {
150
+ const parts = [];
151
+ let depth = 0;
152
+ let current = '';
153
+ for (const char of text) {
154
+ if (char === '(')
155
+ depth++;
156
+ else if (char === ')')
157
+ depth--;
158
+ if (char === ',' && depth === 0) {
159
+ parts.push(current.trim());
160
+ current = '';
161
+ }
162
+ else
163
+ current += char;
164
+ }
165
+ if (current.trim())
166
+ parts.push(current.trim());
167
+ return parts;
168
+ }
169
+ /** FNV-1a, as a short base-36 string. */
170
+ function hash(text) {
171
+ let h = 0x811c9dc5;
172
+ for (let i = 0; i < text.length; i++)
173
+ h = Math.imul(h ^ text.charCodeAt(i), 0x01000193);
174
+ return (h >>> 0).toString(36);
175
+ }
176
+ export function num(value) {
177
+ return String(Math.round(value * 1000) / 1000);
178
+ }
179
+ export function escapeAttr(text) {
180
+ return text.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
181
+ }
182
+ //# sourceMappingURL=paint.js.map
@@ -0,0 +1,18 @@
1
+ /** Anything that can be written as a plain decimal number. */
2
+ export type NumberInput = number | bigint | string;
3
+ /** A number as digits in the numeral system's base, most significant first. */
4
+ export interface ParsedNumber {
5
+ negative: boolean;
6
+ /** Integer digits. Always holds at least one digit; zero is `[0]`. */
7
+ integer: number[];
8
+ /** Fraction digits after the point. Empty when the number is whole. */
9
+ fraction: number[];
10
+ }
11
+ /**
12
+ * Converts a decimal number to digits in `base`, exactly. Every finite decimal fraction is
13
+ * also finite in bases 10, 20 and 60, because 10ⁿ divides them all to the nth power.
14
+ */
15
+ export declare function parseInBase(value: NumberInput, base: number): ParsedNumber;
16
+ /** Writes digits in `base` back as a canonical decimal string, e.g. `-12.5`. */
17
+ export declare function formatInBase({ negative, integer, fraction }: ParsedNumber, base: number): string;
18
+ //# sourceMappingURL=parse.d.ts.map
package/dist/parse.js ADDED
@@ -0,0 +1,104 @@
1
+ const DECIMAL = /^([+-]?)(\d*)(?:\.(\d*))?(?:e([+-]?\d+))?$/i;
2
+ /** Larger exponents would mean building strings of millions of digits. */
3
+ const MAX_EXPONENT = 100_000;
4
+ /**
5
+ * Converts a decimal number to digits in `base`, exactly. Every finite decimal fraction is
6
+ * also finite in bases 10, 20 and 60, because 10ⁿ divides them all to the nth power.
7
+ */
8
+ export function parseInBase(value, base) {
9
+ const { negative, integer, fraction } = parseDecimal(value);
10
+ return {
11
+ negative,
12
+ integer: integerDigits(BigInt(integer || '0'), base),
13
+ fraction: fractionDigits(fraction, base),
14
+ };
15
+ }
16
+ /** Writes digits in `base` back as a canonical decimal string, e.g. `-12.5`. */
17
+ export function formatInBase({ negative, integer, fraction }, base) {
18
+ const b = BigInt(base);
19
+ const whole = integer.reduce((sum, digit) => sum * b + BigInt(digit), 0n);
20
+ // The fraction is numerator / base^length; long division gives its decimal digits.
21
+ let numerator = fraction.reduce((sum, digit) => sum * b + BigInt(digit), 0n);
22
+ const denominator = b ** BigInt(fraction.length);
23
+ let decimals = '';
24
+ for (let i = 0; numerator !== 0n && i < 10_000; i++) {
25
+ numerator *= 10n;
26
+ decimals += String(numerator / denominator);
27
+ numerator %= denominator;
28
+ }
29
+ const zero = whole === 0n && decimals === '';
30
+ return `${negative && !zero ? '-' : ''}${whole}${decimals ? `.${decimals}` : ''}`;
31
+ }
32
+ function parseDecimal(value) {
33
+ const text = toText(value);
34
+ const match = DECIMAL.exec(text);
35
+ const [, sign = '', rawInteger = '', rawFraction = '', rawExponent] = match ?? [];
36
+ if (!match || (rawInteger === '' && rawFraction === '')) {
37
+ throw new TypeError(`Not a decimal number: ${JSON.stringify(String(value))}`);
38
+ }
39
+ let integer = rawInteger;
40
+ let fraction = rawFraction;
41
+ if (rawExponent !== undefined) {
42
+ const exponent = Number(rawExponent);
43
+ if (Math.abs(exponent) > MAX_EXPONENT) {
44
+ throw new RangeError(`Exponent out of range: ${rawExponent}`);
45
+ }
46
+ [integer, fraction] = shiftPoint(integer, fraction, exponent);
47
+ }
48
+ integer = integer.replace(/^0+/, '');
49
+ fraction = fraction.replace(/0+$/, '');
50
+ return { negative: sign === '-' && (integer !== '' || fraction !== ''), integer, fraction };
51
+ }
52
+ function toText(value) {
53
+ switch (typeof value) {
54
+ case 'number':
55
+ if (!Number.isFinite(value))
56
+ throw new RangeError(`Not a finite number: ${value}`);
57
+ // Shortest round-trip form, so 0.1 stays "0.1". Very large or small values come
58
+ // back in exponent form, which parseDecimal() expands.
59
+ return String(value);
60
+ case 'bigint':
61
+ return value.toString();
62
+ case 'string':
63
+ return value.trim().replaceAll('_', '');
64
+ default:
65
+ throw new TypeError(`Expected a number, bigint or string, got ${typeof value}`);
66
+ }
67
+ }
68
+ function shiftPoint(integer, fraction, exponent) {
69
+ const digits = integer + fraction;
70
+ const point = integer.length + exponent;
71
+ if (point <= 0)
72
+ return ['', '0'.repeat(-point) + digits];
73
+ if (point >= digits.length)
74
+ return [digits + '0'.repeat(point - digits.length), ''];
75
+ return [digits.slice(0, point), digits.slice(point)];
76
+ }
77
+ function integerDigits(value, base) {
78
+ const b = BigInt(base);
79
+ const digits = [];
80
+ do {
81
+ digits.unshift(Number(value % b));
82
+ value /= b;
83
+ } while (value > 0n);
84
+ return digits;
85
+ }
86
+ function fractionDigits(fraction, base) {
87
+ if (fraction === '')
88
+ return [];
89
+ const b = BigInt(base);
90
+ const denominator = 10n ** BigInt(fraction.length);
91
+ let numerator = BigInt(fraction);
92
+ const digits = [];
93
+ // Terminates within fraction.length steps for bases that 10 divides into evenly.
94
+ for (let i = 0; numerator !== 0n; i++) {
95
+ if (i > fraction.length * 4 + 8) {
96
+ throw new RangeError(`${fraction} has no finite expansion in base ${base}`);
97
+ }
98
+ numerator *= b;
99
+ digits.push(Number(numerator / denominator));
100
+ numerator %= denominator;
101
+ }
102
+ return digits;
103
+ }
104
+ //# sourceMappingURL=parse.js.map
package/dist/svg.d.ts ADDED
@@ -0,0 +1,41 @@
1
+ import { type Paint } from './paint.js';
2
+ import type { NumberInput } from './parse.js';
3
+ export interface SvgOptions {
4
+ /** Height of the image in pixels. The width follows from the number of places. Default 100. */
5
+ size?: number;
6
+ /**
7
+ * Stroke colour. Default `currentColor`, so the SVG takes the surrounding text colour.
8
+ * Also takes a CSS gradient such as `linear-gradient(to right, gold, crimson)`, or a
9
+ * gradient object.
10
+ */
11
+ color?: Paint;
12
+ /** Fills the image behind the numeral: a colour or a gradient. Default: transparent. */
13
+ background?: Paint;
14
+ /** Stroke width in viewBox units, where a digit is 60 tall. Default 5. */
15
+ strokeWidth?: number;
16
+ /** Space between places in viewBox units. Default 12. */
17
+ gap?: number;
18
+ /** Space around the numeral in viewBox units. Default 20. */
19
+ padding?: number;
20
+ /**
21
+ * Turn every second 1, 2 or 3 in a run on its side, as Suzhou writers do, so 21 is 〢一
22
+ * rather than 〢〡. Default true.
23
+ */
24
+ alternate?: boolean;
25
+ /**
26
+ * Accessible name, rendered as `<title>`. Defaults to the number written in decimal.
27
+ * Pass `false` to leave it out and hide the image from assistive technology.
28
+ */
29
+ title?: string | false;
30
+ }
31
+ /**
32
+ * Renders a number as an SVG string of Suzhou numerals (蘇州碼子).
33
+ *
34
+ * Digits run left to right, most significant first. A dot on the baseline marks the
35
+ * decimal point, and a negative number has a diagonal stroke across its last digit,
36
+ * as on the counting rods Suzhou numerals grew out of.
37
+ */
38
+ export declare function toSvg(value: NumberInput, options?: SvgOptions): string;
39
+ /** One digit from 0 to 9 on its own, upright. `place` is unused here. */
40
+ export declare function digitSvg(digit: number, _place?: number, options?: SvgOptions): string;
41
+ //# sourceMappingURL=svg.d.ts.map
package/dist/svg.js ADDED
@@ -0,0 +1,90 @@
1
+ import { CELL_HEIGHT, CELL_WIDTH, digitStrokes, flatDigits } from './glyph.js';
2
+ import { format, parse } from './number.js';
3
+ import { escapeAttr as escape, num, resolvePaint } from './paint.js';
4
+ /**
5
+ * Renders a number as an SVG string of Suzhou numerals (蘇州碼子).
6
+ *
7
+ * Digits run left to right, most significant first. A dot on the baseline marks the
8
+ * decimal point, and a negative number has a diagonal stroke across its last digit,
9
+ * as on the counting rods Suzhou numerals grew out of.
10
+ */
11
+ export function toSvg(value, options = {}) {
12
+ const number = parse(value);
13
+ const { gap = 12, strokeWidth = 5, alternate = true } = options;
14
+ const digits = [...number.integer, ...number.fraction];
15
+ const flat = alternate ? flatDigits(digits) : digits.map(() => false);
16
+ const cells = [];
17
+ let x = 0;
18
+ let dot;
19
+ digits.forEach((digit, i) => {
20
+ if (i === number.integer.length) {
21
+ const r = strokeWidth;
22
+ x += gap / 2 + r;
23
+ dot = x;
24
+ x += r + gap / 2;
25
+ }
26
+ else if (i > 0) {
27
+ x += gap;
28
+ }
29
+ cells.push({ strokes: digitStrokes(digit, flat[i]), x });
30
+ x += CELL_WIDTH;
31
+ });
32
+ return render(cells, x, number.negative, dot, options, format(number));
33
+ }
34
+ /** One digit from 0 to 9 on its own, upright. `place` is unused here. */
35
+ export function digitSvg(digit, _place = 0, options = {}) {
36
+ return render([{ strokes: digitStrokes(digit), x: 0 }], CELL_WIDTH, false, undefined, options, String(digit));
37
+ }
38
+ function render(cells, width, negative, dot, options, defaultTitle) {
39
+ const { size = 100, color = 'currentColor', background, strokeWidth = 5, padding = 20 } = options;
40
+ if (!(size > 0))
41
+ throw new RangeError(`size must be positive, got ${size}`);
42
+ if (!(strokeWidth > 0))
43
+ throw new RangeError(`strokeWidth must be positive, got ${strokeWidth}`);
44
+ const title = options.title ?? defaultTitle;
45
+ const box = {
46
+ x: -padding,
47
+ y: -padding,
48
+ width: width + 2 * padding,
49
+ height: CELL_HEIGHT + 2 * padding,
50
+ };
51
+ const paint = resolvePaint(color, box, 'suzhou-color');
52
+ const fill = background === undefined ? undefined : resolvePaint(background, box, 'suzhou-background');
53
+ const defs = [...new Set([fill?.def, paint.def].filter(Boolean))].join('');
54
+ const p = escape(paint.value);
55
+ const d = [];
56
+ const circles = [];
57
+ const cy = CELL_HEIGHT / 2;
58
+ for (const cell of cells) {
59
+ const cx = cell.x + CELL_WIDTH / 2;
60
+ for (const s of cell.strokes) {
61
+ if (s.kind === 'line')
62
+ d.push(`M${num(cx + s.x1)} ${num(cy + s.y1)}L${num(cx + s.x2)} ${num(cy + s.y2)}`);
63
+ else
64
+ circles.push(`<circle cx="${num(cx + s.cx)}" cy="${num(cy + s.cy)}" r="${num(s.r)}"/>`);
65
+ }
66
+ }
67
+ if (negative) {
68
+ const last = cells.at(-1);
69
+ d.push(`M${num(last.x - 4)} ${CELL_HEIGHT + 4}L${num(last.x + CELL_WIDTH + 4)} -4`);
70
+ }
71
+ const pixelWidth = (size * box.width) / box.height;
72
+ const label = title === false ? 'aria-hidden="true"' : `role="img" aria-label="${escape(title)}"`;
73
+ return [
74
+ `<svg xmlns="http://www.w3.org/2000/svg" viewBox="${[box.x, box.y, box.width, box.height].map(num).join(' ')}" width="${num(pixelWidth)}" height="${num(size)}" ${label}>`,
75
+ title === false ? '' : `<title>${escape(title)}</title>`,
76
+ defs ? `<defs>${defs}</defs>` : '',
77
+ fill === undefined
78
+ ? ''
79
+ : `<rect x="${num(box.x)}" y="${num(box.y)}" width="${num(box.width)}" height="${num(box.height)}" fill="${escape(fill.value)}"/>`,
80
+ `<g fill="none" stroke="${p}" stroke-width="${num(strokeWidth)}" stroke-linecap="round" stroke-linejoin="round">`,
81
+ d.length ? `<path d="${d.join('')}"/>` : '',
82
+ circles.join(''),
83
+ '</g>',
84
+ dot === undefined
85
+ ? ''
86
+ : `<circle cx="${num(dot)}" cy="${CELL_HEIGHT}" r="${num(strokeWidth)}" fill="${p}"/>`,
87
+ '</svg>',
88
+ ].join('');
89
+ }
90
+ //# sourceMappingURL=svg.js.map
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
2
  "name": "@suzhou-numerals/core",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.0",
4
+ "description": "Render any number as Suzhou numerals in SVG, with zero dependencies",
5
+ "keywords": [
6
+ "chinese",
7
+ "decimal",
8
+ "hangzhou-numerals",
9
+ "huama",
10
+ "number",
11
+ "numerals",
12
+ "suzhou",
13
+ "suzhou-numerals",
14
+ "svg"
15
+ ],
16
+ "homepage": "https://karlnorling.github.io/suzhou-numerals/",
17
+ "bugs": {
18
+ "url": "https://github.com/karlnorling/suzhou-numerals/issues"
19
+ },
20
+ "license": "MIT",
21
+ "author": {
22
+ "name": "Karl Norling",
23
+ "url": "https://github.com/karlnorling"
24
+ },
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "git+https://github.com/karlnorling/suzhou-numerals.git",
28
+ "directory": "packages/@suzhou-numerals/core"
29
+ },
30
+ "files": [
31
+ "dist",
32
+ "!dist/**/*.map",
33
+ "!dist/**/*.tsbuildinfo",
34
+ "README.md",
35
+ "LICENSE"
36
+ ],
37
+ "type": "module",
38
+ "sideEffects": false,
39
+ "exports": {
40
+ ".": {
41
+ "types": "./dist/index.d.ts",
42
+ "default": "./dist/index.js"
43
+ },
44
+ "./package.json": "./package.json"
45
+ },
46
+ "scripts": {
47
+ "build": "rm -rf dist && tsc -p tsconfig.build.json",
48
+ "prepack": "yarn build"
49
+ },
50
+ "devDependencies": {
51
+ "typescript": "^6.0.2"
52
+ },
53
+ "engines": {
54
+ "node": ">= 20.0.0"
55
+ }
56
+ }