harmonink 0.0.0-stage → 0.1.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.
@@ -0,0 +1,171 @@
1
+ export const DEFAULTS = {
2
+ baseSize: 16,
3
+ xTarget: 0.54,
4
+ deadband: 0.04,
5
+ sizeFloor: 0.90,
6
+ lineRatio: 1.5,
7
+ leadingBias: 2,
8
+ minLeading: 5,
9
+ lineMode: 'follow',
10
+ gridBox: 24,
11
+ trackClamp: 0.025,
12
+ trackDeadband: 0.03,
13
+ trackFloor: 0.003,
14
+ bounceCutoff: 0.15,
15
+ capGate: 0.90,
16
+ capOverX: 1.39,
17
+ capsAscX: 1.15,
18
+ stemMedian: 0.1687,
19
+ weightBase: 400,
20
+ };
21
+
22
+ // stem-band sidebearing over x-height — what letters cramped at mid-height are opened up towards
23
+ export const GAP_IDEAL = {
24
+ 'sans-serif': 0.397,
25
+ serif: 0.483,
26
+ monospace: 0.603,
27
+ handwriting: 0.295,
28
+ };
29
+
30
+ // the point past which terminals crowd; tightening never goes below it
31
+ export const GAP_FLOOR = {
32
+ 'sans-serif': 0.130,
33
+ serif: 0.078,
34
+ monospace: 0.223,
35
+ handwriting: -0.140,
36
+ };
37
+
38
+ // median gapBox of the faces in each category that have any air at all
39
+ export const BOX_IDEAL = {
40
+ 'sans-serif': 0.1947,
41
+ serif: 0.1111,
42
+ monospace: 0.2833,
43
+ handwriting: 0.0797,
44
+ };
45
+
46
+ // median cap height, against which a face is judged a cap outlier
47
+ export const CAP_MEDIAN = {
48
+ 'sans-serif': 0.705,
49
+ serif: 0.700,
50
+ monospace: 0.700,
51
+ handwriting: 0.7344,
52
+ };
53
+
54
+ const STEPS = [100, 200, 300, 400, 500, 600, 700, 800, 900];
55
+ const clamp = (lo, v, hi) => Math.min(hi, Math.max(lo, v));
56
+
57
+ // Applies the weight multiplier to a weight you picked. A variable font can land
58
+ // anywhere in its axis; anything else has to snap to a step it actually ships.
59
+ // Pass `steps` when you know which weights the family really has.
60
+ export function weightFor(rules, baseWeight = 400, steps) {
61
+ const want = baseWeight * rules.weightScale;
62
+ const axis = rules.weightAxis;
63
+ if (axis && !steps) return Math.round(clamp(axis[0], want, axis[1]));
64
+ const grid = steps?.length ? steps : STEPS;
65
+ return grid.reduce((a, b) => Math.abs(b - want) < Math.abs(a - want) ? b : a);
66
+ }
67
+
68
+ // spread of flat-topped letters plus spread of flat feet; a face drawn for reading scores 0
69
+ export function bounce(m) {
70
+ return m.topSpread == null || m.footSpread == null ? null : m.topSpread + m.footSpread;
71
+ }
72
+
73
+ export function classify(m, opts = {}) {
74
+ if (m.monospace) return 'monospace';
75
+ const b = bounce(m);
76
+ if (b != null && b > (opts.bounceCutoff ?? DEFAULTS.bounceCutoff)) return 'handwriting';
77
+ const r = m.gapStem === 0 ? 1 : m.gapBox / m.gapStem;
78
+ if (!Number.isFinite(r) || r < 0 || r > 1) return 'handwriting';
79
+ return r < 0.32 ? 'serif' : 'sans-serif';
80
+ }
81
+
82
+ const defined = o => Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined));
83
+
84
+ export function normalize(m, opts = {}) {
85
+ opts = defined(opts);
86
+ const o = { ...DEFAULTS, ...opts };
87
+ const category = opts.category || classify(m, o);
88
+ if (!Object.hasOwn(GAP_IDEAL, category))
89
+ throw new Error(`unknown category "${category}" — use one of ${Object.keys(GAP_IDEAL).join(', ')}`);
90
+ const base = o.baseSize;
91
+ if (!(base > 0 && Number.isFinite(base))) throw new Error(`baseSize must be a positive number, got ${base}`);
92
+ const floorPx = base * o.sizeFloor;
93
+
94
+ const lo = o.xTarget - o.deadband, hi = o.xTarget + o.deadband;
95
+ const target = o.deadband > 0
96
+ ? (m.xHeightRatio < lo ? lo : m.xHeightRatio > hi ? hi : m.xHeightRatio)
97
+ : o.xTarget;
98
+
99
+ let px = Math.max(floorPx, (base * target) / m.xHeightRatio);
100
+
101
+ // a face whose lowercase are capital forms, or whose capitals fall far below its category,
102
+ // is aimed at cap height instead — x-height alone leaves it looking small
103
+ const capsForward = m.ascLetterRatio != null && m.ascLetterRatio < o.capsAscX;
104
+ const capOutlier = m.capHeightRatio != null
105
+ && m.capHeightRatio < (CAP_MEDIAN[category] ?? Infinity) * o.capGate;
106
+ let capAnchored = false;
107
+ if (m.capHeightRatio && (capsForward || capOutlier)) {
108
+ const pxCap = Math.max(floorPx, (base * o.xTarget * o.capOverX) / m.capHeightRatio);
109
+ if (pxCap > px) { px = pxCap; capAnchored = true; }
110
+ }
111
+
112
+ const scale = px / base;
113
+ const inkPx = px * m.inkRatio;
114
+
115
+ // follow: leading is measured, and grows with the face. hold: leading is a fixed
116
+ // box the ink floor is still allowed to break, for callers who need one rhythm
117
+ const floorLine = inkPx + o.minLeading;
118
+ const wanted = o.lineMode === 'hold'
119
+ ? o.gridBox
120
+ : base * o.lineRatio * ((o.leadingBias * scale + m.xHeightRatio) / (o.leadingBias + o.xTarget));
121
+ const lineHeight = Math.round(Math.max(wanted, floorLine));
122
+ const gridBroken = o.lineMode === 'hold' && lineHeight > Math.round(o.gridBox);
123
+
124
+ // loosening comes from the stem band; tightening only from air inside the character box
125
+ const idealStem = GAP_IDEAL[category];
126
+ const openAt = idealStem * (1 - o.trackDeadband);
127
+ const looser = m.gapStem < openAt ? (openAt - m.gapStem) * m.xHeightRatio : 0;
128
+
129
+ const idealBox = BOX_IDEAL[category];
130
+ const tightAt = idealBox == null ? null : idealBox * (1 + o.trackDeadband);
131
+ const tighter = tightAt != null && m.gapBox > 0 && m.gapBox > tightAt
132
+ ? (tightAt - m.gapBox) * m.xHeightRatio : 0;
133
+
134
+ const raw = looser + tighter;
135
+ let letterSpacing = clamp(-o.trackClamp, raw, o.trackClamp);
136
+ if (letterSpacing < 0)
137
+ letterSpacing = Math.max(letterSpacing, -Math.max(0, (m.gapBox - GAP_FLOOR[category]) * m.xHeightRatio));
138
+ // Below the floor the correction cannot be seen: 0.003em moves a 78-character line by
139
+ // 3.7px in 519, and no single gap shifts even half a pixel at any value we emit. A
140
+ // declaration that small still overrides whatever the consumer inherited, so it costs
141
+ // them cascade control and returns nothing. trackDeadband is relative to the category
142
+ // ideal and works on the input; this is absolute and works on what actually ships.
143
+ if (Math.abs(letterSpacing) < o.trackFloor) letterSpacing = 0;
144
+
145
+ // a scaled-up face draws heavier at the same nominal weight, so the weight comes down
146
+ // in proportion. Exposed as a multiplier so it applies to whatever weight you chose,
147
+ // not only to 400
148
+ const weightScale = Number((1 / scale).toFixed(4));
149
+ const weightAxis = m.weightAxis ?? null;
150
+ const weight = weightFor({ weightScale, weightAxis }, o.weightBase);
151
+
152
+ return {
153
+ family: m.family,
154
+ category,
155
+ sizeAdjust: Number((scale * 100).toFixed(2)),
156
+ fontSize: base,
157
+ lineHeight,
158
+ lineMode: o.lineMode,
159
+ gridBroken,
160
+ letterSpacing: Number(letterSpacing.toFixed(4)),
161
+ fontWeight: weight,
162
+ weightScale,
163
+ weightAxis,
164
+ weightExact: !!weightAxis,
165
+ weightClamped: !!weightAxis && weight !== Math.round(o.weightBase * weightScale),
166
+ renderedSize: Number(px.toFixed(2)),
167
+ leading: Number((lineHeight - inkPx).toFixed(2)),
168
+ capAnchored,
169
+ trackClamped: Math.abs(raw) > o.trackClamp + 1e-4,
170
+ };
171
+ }
package/src/outline.js ADDED
@@ -0,0 +1,74 @@
1
+ export function pathOf(glyph) {
2
+ const segs = [];
3
+ for (const c of glyph.contours) {
4
+ if (!c.length) continue;
5
+ let pts = c;
6
+ let start = pts.find(p => p.on);
7
+ if (!start) {
8
+ const a = pts[0], b = pts[pts.length - 1];
9
+ start = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2, on: true };
10
+ pts = [start, ...pts];
11
+ } else {
12
+ const i = pts.indexOf(start);
13
+ pts = pts.slice(i).concat(pts.slice(0, i));
14
+ }
15
+ let cur = pts[0], ctrl = null;
16
+ for (let k = 1; k <= pts.length; k++) {
17
+ const p = pts[k % pts.length];
18
+ if (p.on) {
19
+ if (ctrl) { segs.push([cur, ctrl, p]); ctrl = null; }
20
+ else segs.push([cur, null, p]);
21
+ cur = p;
22
+ } else {
23
+ if (ctrl) {
24
+ const mid = { x: (ctrl.x + p.x) / 2, y: (ctrl.y + p.y) / 2 };
25
+ segs.push([cur, ctrl, mid]);
26
+ cur = mid;
27
+ }
28
+ ctrl = p;
29
+ }
30
+ }
31
+ }
32
+ return segs;
33
+ }
34
+
35
+ const qp = (a, b, c, t) => { const m = 1 - t; return m * m * a + 2 * m * t * b + t * t * c; };
36
+
37
+ export function bounds(segs) {
38
+ if (!segs.length) return null;
39
+ let xMin = Infinity, yMin = Infinity, xMax = -Infinity, yMax = -Infinity;
40
+ const hit = (x, y) => {
41
+ if (x < xMin) xMin = x; if (x > xMax) xMax = x;
42
+ if (y < yMin) yMin = y; if (y > yMax) yMax = y;
43
+ };
44
+ for (const [p0, c, p1] of segs) {
45
+ hit(p0.x, p0.y); hit(p1.x, p1.y);
46
+ if (!c) continue;
47
+ for (const ax of ['x', 'y']) {
48
+ const d = p0[ax] - 2 * c[ax] + p1[ax];
49
+ if (d === 0) continue;
50
+ const t = (p0[ax] - c[ax]) / d;
51
+ if (t > 0 && t < 1) hit(qp(p0.x, c.x, p1.x, t), qp(p0.y, c.y, p1.y, t));
52
+ }
53
+ }
54
+ return { xMin, yMin, xMax, yMax };
55
+ }
56
+
57
+ export function crossingsAt(segs, y) {
58
+ const xs = [];
59
+ for (const [p0, c, p1] of segs) {
60
+ if (!c) {
61
+ if ((p0.y - y) * (p1.y - y) <= 0 && p0.y !== p1.y)
62
+ xs.push(p0.x + (p1.x - p0.x) * (y - p0.y) / (p1.y - p0.y));
63
+ continue;
64
+ }
65
+ const a = p0.y - 2 * c.y + p1.y, b = 2 * (c.y - p0.y), cc = p0.y - y;
66
+ const push = t => { if (t >= 0 && t <= 1) xs.push(qp(p0.x, c.x, p1.x, t)); };
67
+ if (Math.abs(a) < 1e-9) { if (b !== 0) push(-cc / b); }
68
+ else {
69
+ const disc = b * b - 4 * a * cc;
70
+ if (disc >= 0) { const s = Math.sqrt(disc); push((-b + s) / (2 * a)); push((-b - s) / (2 * a)); }
71
+ }
72
+ }
73
+ return xs;
74
+ }
package/src/sfnt.js ADDED
@@ -0,0 +1,97 @@
1
+ import { brotliDecompressSync, inflateSync } from 'node:zlib';
2
+
3
+ const KNOWN = ["cmap","head","hhea","hmtx","maxp","name","OS/2","post","cvt ","fpgm","glyf","loca","prep","CFF ","VORG","EBDT","EBLC","gasp","hdmx","kern","LTSH","PCLT","VDMX","vhea","vmtx","BASE","GDEF","GPOS","GSUB","EBSC","JSTF","MATH","CBDT","CBLC","COLR","CPAL","SVG ","sbix","acnt","avar","bdat","bloc","bsln","cvar","fdsc","feat","fmtx","fvar","gvar","hsty","just","lcar","mort","morx","opbd","prop","trak","Zapf","Silf","Glat","Gloc","Feat","Sill"];
4
+
5
+ export class Reader {
6
+ constructor(b, p = 0) { this.b = b; this.p = p; }
7
+ u8() { return this.b[this.p++]; }
8
+ i8() { const v = this.u8(); return v > 127 ? v - 256 : v; }
9
+ u16() { const v = (this.b[this.p] << 8) | this.b[this.p + 1]; this.p += 2; return v; }
10
+ i16() { const v = this.u16(); return v & 0x8000 ? v - 0x10000 : v; }
11
+ u32() { const v = ((this.b[this.p] << 24) | (this.b[this.p+1] << 16) | (this.b[this.p+2] << 8) | this.b[this.p+3]) >>> 0; this.p += 4; return v; }
12
+ tag() { const v = String.fromCharCode(this.b[this.p], this.b[this.p+1], this.b[this.p+2], this.b[this.p+3]); this.p += 4; return v; }
13
+ base128() {
14
+ let v = 0;
15
+ for (let i = 0; i < 5; i++) {
16
+ const x = this.b[this.p++];
17
+ v = (v << 7) | (x & 0x7f);
18
+ if (!(x & 0x80)) return v;
19
+ }
20
+ throw new Error('bad base128');
21
+ }
22
+ u255() {
23
+ const c = this.u8();
24
+ if (c === 253) return this.u16();
25
+ if (c === 254) return this.u8() + 506;
26
+ if (c === 255) return this.u8() + 253;
27
+ return c;
28
+ }
29
+ }
30
+
31
+ function sfntTables(b) {
32
+ const r = new Reader(b, 4);
33
+ const n = r.u16();
34
+ r.p = 12;
35
+ const t = {};
36
+ for (let i = 0; i < n; i++) {
37
+ const tag = r.tag(); r.u32();
38
+ const off = r.u32(), len = r.u32();
39
+ t[tag] = b.subarray(off, off + len);
40
+ }
41
+ return t;
42
+ }
43
+
44
+ function woff1Tables(b) {
45
+ const r = new Reader(b, 12);
46
+ const n = r.u16();
47
+ r.p = 44;
48
+ const t = {};
49
+ for (let i = 0; i < n; i++) {
50
+ const tag = r.tag();
51
+ const off = r.u32(), comp = r.u32(), orig = r.u32(); r.u32();
52
+ const raw = b.subarray(off, off + comp);
53
+ t[tag] = comp === orig ? raw : inflateSync(raw);
54
+ }
55
+ return t;
56
+ }
57
+
58
+ function woff2Tables(b) {
59
+ const r = new Reader(b, 12);
60
+ const numTables = r.u16(); r.u16();
61
+ r.u32();
62
+ const totalCompressed = r.u32();
63
+ r.p = 48;
64
+ const dir = [];
65
+ for (let i = 0; i < numTables; i++) {
66
+ const flags = r.u8();
67
+ const idx = flags & 0x3f;
68
+ const tag = idx === 0x3f ? r.tag() : KNOWN[idx];
69
+ const tv = (flags >> 6) & 0x3;
70
+ const origLength = r.base128();
71
+ const transformed =
72
+ (tag === 'glyf' || tag === 'loca') ? tv === 0 :
73
+ tag === 'hmtx' ? tv === 1 : tv !== 0;
74
+ const transformLength = transformed ? r.base128() : origLength;
75
+ dir.push({ tag, origLength, transformLength, transformed });
76
+ }
77
+ const data = brotliDecompressSync(b.subarray(r.p, r.p + totalCompressed));
78
+ const t = {};
79
+ let off = 0;
80
+ for (const d of dir) {
81
+ const slice = data.subarray(off, off + d.transformLength);
82
+ t[d.tag] = slice;
83
+ t[`__t_${d.tag}`] = d.transformed;
84
+ off += d.transformLength;
85
+ }
86
+ return t;
87
+ }
88
+
89
+ export function readTables(buf) {
90
+ const magic = buf.readUInt32BE(0);
91
+ if (magic === 0x774f4632) return { tables: woff2Tables(buf), container: 'woff2' };
92
+ if (magic === 0x774f4646) return { tables: woff1Tables(buf), container: 'woff' };
93
+ if (magic === 0x00010000 || magic === 0x74727565 || magic === 0x4f54544f)
94
+ return { tables: sfntTables(buf), container: 'sfnt' };
95
+ if (magic === 0x74746366) throw new Error('TrueType Collections (.ttc) are not supported');
96
+ throw new Error('unrecognised font container');
97
+ }