@paragraf/font-engine 0.0.0-stage → 0.7.1
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 +21 -0
- package/README.md +66 -2
- package/dist/index.d.ts +129 -0
- package/dist/index.js +268 -0
- package/package.json +60 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 paragraf contributors
|
|
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.
|
package/README.md
CHANGED
|
@@ -1,3 +1,67 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @paragraf/font-engine
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Font metrics abstraction + fontkit adapter + measurer factory.
|
|
4
|
+
Bridges the layout algorithm (which needs widths and metrics) to real font data.
|
|
5
|
+
|
|
6
|
+
## Install
|
|
7
|
+
|
|
8
|
+
```bash
|
|
9
|
+
npm install @paragraf/font-engine @paragraf/types
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
## Usage
|
|
13
|
+
|
|
14
|
+
### Load fonts and create a measurer
|
|
15
|
+
|
|
16
|
+
```ts
|
|
17
|
+
import { createMeasurer } from '@paragraf/font-engine';
|
|
18
|
+
import { FontRegistry } from '@paragraf/types';
|
|
19
|
+
|
|
20
|
+
const registry: FontRegistry = new Map([
|
|
21
|
+
['regular', { id: 'regular', family: 'SourceSerif4', filePath: './fonts/SourceSerif4-Regular.ttf' }],
|
|
22
|
+
['bold', { id: 'bold', family: 'SourceSerif4', filePath: './fonts/SourceSerif4-Bold.ttf' }],
|
|
23
|
+
]);
|
|
24
|
+
|
|
25
|
+
const measurer = createMeasurer(registry);
|
|
26
|
+
// measurer.measure(text, font) → width in points
|
|
27
|
+
// measurer.space(font) → { width, stretch, shrink }
|
|
28
|
+
// measurer.metrics(font) → FontMetrics
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
### `FontkitEngine` — direct access
|
|
32
|
+
|
|
33
|
+
```ts
|
|
34
|
+
import { FontkitEngine } from '@paragraf/font-engine';
|
|
35
|
+
|
|
36
|
+
const engine = new FontkitEngine();
|
|
37
|
+
await engine.loadFont('regular', './fonts/SourceSerif4-Regular.ttf');
|
|
38
|
+
|
|
39
|
+
const glyphs = engine.glyphsForString('regular', 'Hello');
|
|
40
|
+
const path = engine.getGlyphPath('regular', glyph, x, y, fontSize);
|
|
41
|
+
const metrics = engine.getFontMetrics('regular', fontSize);
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
### `FontEngine` interface
|
|
45
|
+
|
|
46
|
+
Both `FontkitEngine` (TypeScript) and `WasmFontEngine` (`@paragraf/shaping-wasm`) implement this interface:
|
|
47
|
+
|
|
48
|
+
```ts
|
|
49
|
+
interface FontEngine {
|
|
50
|
+
loadFont(id: string, path: string): Promise<void>;
|
|
51
|
+
glyphsForString(fontId: string, text: string, font?: Font): Glyph[];
|
|
52
|
+
glyphForCodePoint?(fontId: string, codePoint: number): Glyph | null; // only this is optional
|
|
53
|
+
applyLigatures(fontId: string, glyphs: Glyph[]): Glyph[];
|
|
54
|
+
applySingleSubstitution(fontId: string, glyphs: Glyph[], featureTag: 'sups' | 'subs'): Glyph[];
|
|
55
|
+
getKerning(fontId: string, glyph1: Glyph, glyph2: Glyph): number;
|
|
56
|
+
getGlyphPath(fontId: string, glyph: Glyph, x: number, y: number, fontSize: number): GlyphPath;
|
|
57
|
+
getFontMetrics(fontId: string, fontSize: number, variant?: 'normal' | 'superscript' | 'subscript'): FontMetrics;
|
|
58
|
+
}
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
### Test utilities
|
|
62
|
+
|
|
63
|
+
```ts
|
|
64
|
+
import { mockMeasure, mockSpace, mockMetrics } from '@paragraf/font-engine';
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Same mock functions exported by `@paragraf/linebreak` — use whichever is convenient.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import * as _paragraf_types from '@paragraf/types';
|
|
2
|
+
import { Font, FontMetrics, FontRegistry, MeasureText, GlueSpaceFn, GetFontMetrics, Measurer } from '@paragraf/types';
|
|
3
|
+
|
|
4
|
+
interface PathCommand {
|
|
5
|
+
command: 'moveTo' | 'lineTo' | 'quadraticCurveTo' | 'bezierCurveTo' | 'closePath';
|
|
6
|
+
args: number[];
|
|
7
|
+
}
|
|
8
|
+
interface GlyphPath {
|
|
9
|
+
commands: PathCommand[];
|
|
10
|
+
toSVG(precision?: number): string;
|
|
11
|
+
boundingBox?: {
|
|
12
|
+
minX: number;
|
|
13
|
+
minY: number;
|
|
14
|
+
maxX: number;
|
|
15
|
+
maxY: number;
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* A Glyph is an opaque handle to a specific glyph in a font.
|
|
20
|
+
* Different font engines may represent this differently.
|
|
21
|
+
*/
|
|
22
|
+
interface Glyph {
|
|
23
|
+
index: number;
|
|
24
|
+
advanceWidth: number;
|
|
25
|
+
xOffset?: number;
|
|
26
|
+
yOffset?: number;
|
|
27
|
+
codePoints?: number[];
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* FontEngine: pluggable abstraction for font access.
|
|
31
|
+
* Implementations: FontkitEngine, WasmFontEngine, HarfbuzzWasmEngine, etc.
|
|
32
|
+
*
|
|
33
|
+
* Separation of concerns:
|
|
34
|
+
* - FontEngine provides glyphs and metrics
|
|
35
|
+
* - Renderers (SVG/Canvas/PDF) consume FontEngine to draw
|
|
36
|
+
* - Neither renderers nor this interface care about the underlying library
|
|
37
|
+
*/
|
|
38
|
+
interface FontEngine {
|
|
39
|
+
/**
|
|
40
|
+
* Load a font from file path and register it by id.
|
|
41
|
+
* Called once per font during initialization.
|
|
42
|
+
*/
|
|
43
|
+
loadFont(id: string, path: string): Promise<void>;
|
|
44
|
+
/**
|
|
45
|
+
* Convert text to glyphs, applying layout and shaping.
|
|
46
|
+
* GSUB features (ligatures, sups/subs) are applied by the engine internally
|
|
47
|
+
* at shaping time — callers do not need to call applyLigatures() or
|
|
48
|
+
* applySingleSubstitution() separately.
|
|
49
|
+
* Pass `font` so engines that apply GSUB at shape time (e.g. WasmFontEngine)
|
|
50
|
+
* can access Font.variant for sups/subs.
|
|
51
|
+
*/
|
|
52
|
+
glyphsForString(fontId: string, text: string, font?: Font): Glyph[];
|
|
53
|
+
/**
|
|
54
|
+
* Get a single glyph for a Unicode code point.
|
|
55
|
+
* Returns null if not found.
|
|
56
|
+
* Optional — engines that shape full strings (e.g. WasmFontEngine) need not implement this.
|
|
57
|
+
* Callers must guard: engine.glyphForCodePoint?.(fontId, cp)
|
|
58
|
+
*/
|
|
59
|
+
glyphForCodePoint?(fontId: string, codePoint: number): Glyph | null;
|
|
60
|
+
/**
|
|
61
|
+
* Apply GSUB ligature substitution (liga, rlig features).
|
|
62
|
+
* @deprecated GSUB is now applied inside glyphsForString. This method is a
|
|
63
|
+
* no-op on all built-in engines and will be removed in a future release.
|
|
64
|
+
* Optional — custom engines need not implement this.
|
|
65
|
+
*/
|
|
66
|
+
applyLigatures?(fontId: string, glyphs: Glyph[]): Glyph[];
|
|
67
|
+
/**
|
|
68
|
+
* Apply GSUB single substitution (sups, subs features).
|
|
69
|
+
* @deprecated GSUB is now applied inside glyphsForString. This method is a
|
|
70
|
+
* no-op on all built-in engines and will be removed in a future release.
|
|
71
|
+
* Optional — custom engines need not implement this.
|
|
72
|
+
*/
|
|
73
|
+
applySingleSubstitution?(fontId: string, glyphs: Glyph[], featureTag: 'sups' | 'subs'): Glyph[];
|
|
74
|
+
/**
|
|
75
|
+
* Get kerning offset between two glyphs in a font.
|
|
76
|
+
* Returns 0 if no kern pair exists or kerning not supported.
|
|
77
|
+
* Result is in font units (scale by fontSize / unitsPerEm).
|
|
78
|
+
*/
|
|
79
|
+
getKerning(fontId: string, glyph1: Glyph, glyph2: Glyph): number;
|
|
80
|
+
/**
|
|
81
|
+
* Get glyph outline (path) for rendering.
|
|
82
|
+
* Position (x, y) and fontSize are applied; returned path is ready to draw.
|
|
83
|
+
*/
|
|
84
|
+
getGlyphPath(fontId: string, glyph: Glyph, x: number, y: number, fontSize: number): GlyphPath;
|
|
85
|
+
/**
|
|
86
|
+
* Get font-level metrics (ascender, descender, x-height, cap-height, line gap, baseline shift).
|
|
87
|
+
* Result is scaled to fontSize. Pass variant to get the correct baselineShift for
|
|
88
|
+
* superscript (positive) or subscript (negative) positioning.
|
|
89
|
+
*/
|
|
90
|
+
getFontMetrics(fontId: string, fontSize: number, variant?: 'normal' | 'superscript' | 'subscript'): FontMetrics;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
declare class FontkitEngine implements FontEngine {
|
|
94
|
+
private fontCache;
|
|
95
|
+
private fontPathCache;
|
|
96
|
+
loadFont(id: string, path: string): Promise<void>;
|
|
97
|
+
glyphsForString(fontId: string, text: string, font?: Font): Glyph[];
|
|
98
|
+
glyphForCodePoint(fontId: string, codePoint: number): Glyph | null;
|
|
99
|
+
applyLigatures(_fontId: string, glyphs: Glyph[]): Glyph[];
|
|
100
|
+
applySingleSubstitution(_fontId: string, glyphs: Glyph[], _featureTag: 'sups' | 'subs'): Glyph[];
|
|
101
|
+
getKerning(_fontId: string, _glyph1: Glyph, _glyph2: Glyph): number;
|
|
102
|
+
getGlyphPath(fontId: string, glyph: Glyph, x: number, y: number, fontSize: number): GlyphPath;
|
|
103
|
+
getFontMetrics(fontId: string, fontSize: number, variant?: 'normal' | 'superscript' | 'subscript'): FontMetrics;
|
|
104
|
+
private getFont;
|
|
105
|
+
private featuresFor;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
declare const loadFontkitFont: (filePath: string, fontId: string) => any;
|
|
109
|
+
declare const resolveFontkitFont: (font: Font, registry: FontRegistry) => any;
|
|
110
|
+
declare const createMeasurer: (registry: FontRegistry, measure?: MeasureText, space?: GlueSpaceFn, metrics?: GetFontMetrics) => Measurer;
|
|
111
|
+
/**
|
|
112
|
+
* Build a validated `FontRegistry` (`Map<FontId, FontDescriptor>`) from an
|
|
113
|
+
* array of descriptors.
|
|
114
|
+
*
|
|
115
|
+
* Validates at construction time:
|
|
116
|
+
* - `id` is a non-empty string
|
|
117
|
+
* - `family` is a non-empty string
|
|
118
|
+
* - `filePath` is a non-empty string
|
|
119
|
+
* - No duplicate `id` values
|
|
120
|
+
*
|
|
121
|
+
* @throws {Error} on the first validation failure.
|
|
122
|
+
*/
|
|
123
|
+
declare function createFontRegistry(descriptors: _paragraf_types.FontDescriptor[]): FontRegistry;
|
|
124
|
+
|
|
125
|
+
declare const mockMeasure: MeasureText;
|
|
126
|
+
declare const mockSpace: GlueSpaceFn;
|
|
127
|
+
declare const mockMetrics: GetFontMetrics;
|
|
128
|
+
|
|
129
|
+
export { type FontEngine, FontkitEngine, type Glyph, type GlyphPath, type PathCommand, createFontRegistry, createMeasurer, loadFontkitFont, mockMeasure, mockMetrics, mockSpace, resolveFontkitFont };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
// src/engines/fontkit-engine.ts
|
|
2
|
+
import { openSync as fontkitOpenSync } from "fontkit";
|
|
3
|
+
var FontkitEngine = class {
|
|
4
|
+
fontCache = /* @__PURE__ */ new Map();
|
|
5
|
+
fontPathCache = /* @__PURE__ */ new Map();
|
|
6
|
+
async loadFont(id, path) {
|
|
7
|
+
if (this.fontCache.has(id)) {
|
|
8
|
+
const existing = this.fontPathCache.get(id);
|
|
9
|
+
if (existing !== void 0 && existing !== path) {
|
|
10
|
+
console.warn(
|
|
11
|
+
`[paragraf] loadFont(): font id "${id}" is already registered with path "${existing}". Ignoring re-registration with path "${path}". Use a unique id per font file.`
|
|
12
|
+
);
|
|
13
|
+
}
|
|
14
|
+
return;
|
|
15
|
+
}
|
|
16
|
+
try {
|
|
17
|
+
const font = fontkitOpenSync(path);
|
|
18
|
+
this.fontCache.set(id, font);
|
|
19
|
+
this.fontPathCache.set(id, path);
|
|
20
|
+
} catch (err) {
|
|
21
|
+
throw new Error(
|
|
22
|
+
`Failed to load font "${id}" from "${path}": ${err instanceof Error ? err.message : String(err)}`
|
|
23
|
+
);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
glyphsForString(fontId, text, font) {
|
|
27
|
+
const fkFont = this.getFont(fontId);
|
|
28
|
+
const run = fkFont.layout(text, this.featuresFor(font));
|
|
29
|
+
return run.glyphs.map((g, i) => ({
|
|
30
|
+
index: g.id,
|
|
31
|
+
advanceWidth: run.positions[i].xAdvance,
|
|
32
|
+
xOffset: run.positions[i].xOffset || void 0,
|
|
33
|
+
yOffset: run.positions[i].yOffset || void 0,
|
|
34
|
+
codePoints: g.codePoints
|
|
35
|
+
}));
|
|
36
|
+
}
|
|
37
|
+
glyphForCodePoint(fontId, codePoint) {
|
|
38
|
+
const fkFont = this.getFont(fontId);
|
|
39
|
+
try {
|
|
40
|
+
const g = fkFont.glyphForCodePoint(codePoint);
|
|
41
|
+
if (!g) return null;
|
|
42
|
+
return { index: g.id, advanceWidth: g.advanceWidth };
|
|
43
|
+
} catch {
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
// No-op: GSUB (liga/rlig/sups/subs) is applied at layout() time in glyphsForString
|
|
48
|
+
applyLigatures(_fontId, glyphs) {
|
|
49
|
+
return glyphs;
|
|
50
|
+
}
|
|
51
|
+
// No-op: single substitution is applied at layout() time in glyphsForString
|
|
52
|
+
applySingleSubstitution(_fontId, glyphs, _featureTag) {
|
|
53
|
+
return glyphs;
|
|
54
|
+
}
|
|
55
|
+
// No-op: GPOS kern is already included in advanceWidth from layout() positions
|
|
56
|
+
getKerning(_fontId, _glyph1, _glyph2) {
|
|
57
|
+
return 0;
|
|
58
|
+
}
|
|
59
|
+
getGlyphPath(fontId, glyph, x, y, fontSize) {
|
|
60
|
+
const fkFont = this.getFont(fontId);
|
|
61
|
+
const fkGlyph = fkFont.getGlyph(glyph.index);
|
|
62
|
+
if (!fkGlyph) {
|
|
63
|
+
throw new Error(`Glyph ${glyph.index} not found in font "${fontId}"`);
|
|
64
|
+
}
|
|
65
|
+
const scale = fontSize / fkFont.unitsPerEm;
|
|
66
|
+
const path = fkGlyph.path.transform(scale, 0, 0, -scale, x, y);
|
|
67
|
+
const commands = path.commands;
|
|
68
|
+
const d = path.toSVG();
|
|
69
|
+
return {
|
|
70
|
+
commands,
|
|
71
|
+
toSVG: (_precision) => d.length > 0 ? `<path d="${d}"/>` : "",
|
|
72
|
+
boundingBox: path.bbox
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
getFontMetrics(fontId, fontSize, variant) {
|
|
76
|
+
const fkFont = this.getFont(fontId);
|
|
77
|
+
const scale = fontSize / fkFont.unitsPerEm;
|
|
78
|
+
const os2 = fkFont["OS/2"];
|
|
79
|
+
const ascender = (os2?.typoAscender ?? fkFont.ascent ?? 800) * scale;
|
|
80
|
+
const descender = (os2?.typoDescender ?? fkFont.descent ?? -200) * scale;
|
|
81
|
+
const lineGap = (os2?.typoLineGap ?? 0) * scale;
|
|
82
|
+
const xHeight = (os2?.xHeight ?? 0) * scale;
|
|
83
|
+
const capHeight = (os2?.capHeight ?? 0) * scale;
|
|
84
|
+
let baselineShift = 0;
|
|
85
|
+
if (variant === "superscript") {
|
|
86
|
+
baselineShift = (os2?.ySuperscriptYOffset ?? 0) * scale;
|
|
87
|
+
} else if (variant === "subscript") {
|
|
88
|
+
baselineShift = -((os2?.ySubscriptYOffset ?? 0) * scale);
|
|
89
|
+
}
|
|
90
|
+
return {
|
|
91
|
+
unitsPerEm: fkFont.unitsPerEm,
|
|
92
|
+
ascender,
|
|
93
|
+
descender,
|
|
94
|
+
xHeight: xHeight > 0 ? xHeight : ascender * 0.5,
|
|
95
|
+
capHeight: capHeight > 0 ? capHeight : ascender * 0.7,
|
|
96
|
+
lineGap,
|
|
97
|
+
baselineShift
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
getFont(fontId) {
|
|
101
|
+
const font = this.fontCache.get(fontId);
|
|
102
|
+
if (!font) {
|
|
103
|
+
const registered = [...this.fontCache.keys()].join(", ") || "(none)";
|
|
104
|
+
throw new Error(
|
|
105
|
+
`Font id "${fontId}" not loaded. Registered fonts: ${registered}`
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
return font;
|
|
109
|
+
}
|
|
110
|
+
featuresFor(font) {
|
|
111
|
+
const features = ["calt"];
|
|
112
|
+
if (font?.ligatures !== false) features.push("liga", "rlig");
|
|
113
|
+
if (font?.variant === "superscript") features.push("sups");
|
|
114
|
+
else if (font?.variant === "subscript") features.push("subs");
|
|
115
|
+
return features;
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
// src/measure.ts
|
|
120
|
+
import { openSync as fontkitOpenSync2 } from "fontkit";
|
|
121
|
+
var fontCache = /* @__PURE__ */ new Map();
|
|
122
|
+
var loadFontkitFont = (filePath, fontId) => {
|
|
123
|
+
if (fontCache.has(fontId)) return fontCache.get(fontId);
|
|
124
|
+
let loaded;
|
|
125
|
+
try {
|
|
126
|
+
loaded = fontkitOpenSync2(filePath);
|
|
127
|
+
} catch (err) {
|
|
128
|
+
throw new Error(
|
|
129
|
+
`Failed to load font "${fontId}" from "${filePath}": ${err instanceof Error ? err.message : String(err)}`
|
|
130
|
+
);
|
|
131
|
+
}
|
|
132
|
+
fontCache.set(fontId, loaded);
|
|
133
|
+
return loaded;
|
|
134
|
+
};
|
|
135
|
+
var resolveFontkitFont = (font, registry) => {
|
|
136
|
+
const descriptor = registry.get(font.id);
|
|
137
|
+
if (!descriptor) {
|
|
138
|
+
const registered = [...registry.keys()].join(", ") || "(none)";
|
|
139
|
+
throw new Error(
|
|
140
|
+
`Font id "${font.id}" not found in registry. Registered fonts: ${registered}`
|
|
141
|
+
);
|
|
142
|
+
}
|
|
143
|
+
return loadFontkitFont(descriptor.filePath, font.id);
|
|
144
|
+
};
|
|
145
|
+
var featuresFor = (font) => {
|
|
146
|
+
const features = ["calt"];
|
|
147
|
+
if (font.ligatures !== false) features.push("liga", "rlig");
|
|
148
|
+
if (font.variant === "superscript") features.push("sups");
|
|
149
|
+
else if (font.variant === "subscript") features.push("subs");
|
|
150
|
+
return features;
|
|
151
|
+
};
|
|
152
|
+
var realMeasure = (registry) => (content, font) => {
|
|
153
|
+
const fkFont = resolveFontkitFont(font, registry);
|
|
154
|
+
const scale = font.size / fkFont.unitsPerEm;
|
|
155
|
+
const run = fkFont.layout(content, featuresFor(font));
|
|
156
|
+
let width = 0;
|
|
157
|
+
for (const pos of run.positions) {
|
|
158
|
+
width += pos.xAdvance;
|
|
159
|
+
}
|
|
160
|
+
const letterSpacing = font.letterSpacing ?? 0;
|
|
161
|
+
if (letterSpacing !== 0 && run.positions.length > 1) {
|
|
162
|
+
width += (run.positions.length - 1) * (letterSpacing / scale);
|
|
163
|
+
}
|
|
164
|
+
return width * scale;
|
|
165
|
+
};
|
|
166
|
+
var realSpace = (registry) => (font) => {
|
|
167
|
+
const fkFont = resolveFontkitFont(font, registry);
|
|
168
|
+
const scale = font.size / fkFont.unitsPerEm;
|
|
169
|
+
const spaceGlyph = fkFont.glyphForCodePoint(32);
|
|
170
|
+
const spaceWidth = (spaceGlyph?.advanceWidth ?? 0) * scale;
|
|
171
|
+
const em = font.size;
|
|
172
|
+
const safeWidth = spaceWidth > 0 ? spaceWidth : em / 3;
|
|
173
|
+
return {
|
|
174
|
+
width: safeWidth,
|
|
175
|
+
stretch: em / 6,
|
|
176
|
+
shrink: em / 9
|
|
177
|
+
};
|
|
178
|
+
};
|
|
179
|
+
var realMetrics = (registry) => (font) => {
|
|
180
|
+
const fkFont = resolveFontkitFont(font, registry);
|
|
181
|
+
const scale = font.size / fkFont.unitsPerEm;
|
|
182
|
+
const os2 = fkFont["OS/2"];
|
|
183
|
+
const ascender = (os2?.typoAscender ?? fkFont.ascent ?? 800) * scale;
|
|
184
|
+
const descender = (os2?.typoDescender ?? fkFont.descent ?? -200) * scale;
|
|
185
|
+
const lineGap = (os2?.typoLineGap ?? 0) * scale;
|
|
186
|
+
const xHeight = (os2?.xHeight ?? 0) * scale;
|
|
187
|
+
const capHeight = (os2?.capHeight ?? 0) * scale;
|
|
188
|
+
let baselineShift = 0;
|
|
189
|
+
if (font.variant === "superscript") {
|
|
190
|
+
baselineShift = (os2?.ySuperscriptYOffset ?? 0) * scale;
|
|
191
|
+
} else if (font.variant === "subscript") {
|
|
192
|
+
baselineShift = -((os2?.ySubscriptYOffset ?? 0) * scale);
|
|
193
|
+
}
|
|
194
|
+
return {
|
|
195
|
+
unitsPerEm: fkFont.unitsPerEm,
|
|
196
|
+
ascender,
|
|
197
|
+
descender,
|
|
198
|
+
xHeight: xHeight > 0 ? xHeight : ascender * 0.5,
|
|
199
|
+
capHeight: capHeight > 0 ? capHeight : ascender * 0.7,
|
|
200
|
+
lineGap,
|
|
201
|
+
baselineShift
|
|
202
|
+
};
|
|
203
|
+
};
|
|
204
|
+
var createMeasurer = (registry, measure, space, metrics) => ({
|
|
205
|
+
measure: measure ?? realMeasure(registry),
|
|
206
|
+
space: space ?? realSpace(registry),
|
|
207
|
+
metrics: metrics ?? realMetrics(registry),
|
|
208
|
+
registry
|
|
209
|
+
});
|
|
210
|
+
function createFontRegistry(descriptors) {
|
|
211
|
+
const registry = /* @__PURE__ */ new Map();
|
|
212
|
+
for (const desc of descriptors) {
|
|
213
|
+
if (!desc.id || typeof desc.id !== "string") {
|
|
214
|
+
throw new Error(
|
|
215
|
+
`createFontRegistry: descriptor has an empty or missing 'id' field.`
|
|
216
|
+
);
|
|
217
|
+
}
|
|
218
|
+
if (!desc.family || typeof desc.family !== "string") {
|
|
219
|
+
throw new Error(
|
|
220
|
+
`createFontRegistry: descriptor "${desc.id}" has an empty or missing 'family' field.`
|
|
221
|
+
);
|
|
222
|
+
}
|
|
223
|
+
if (!desc.filePath || typeof desc.filePath !== "string") {
|
|
224
|
+
throw new Error(
|
|
225
|
+
`createFontRegistry: descriptor "${desc.id}" has an empty or missing 'filePath' field.`
|
|
226
|
+
);
|
|
227
|
+
}
|
|
228
|
+
if (registry.has(desc.id)) {
|
|
229
|
+
throw new Error(
|
|
230
|
+
`createFontRegistry: duplicate font id "${desc.id}". Each descriptor must have a unique id.`
|
|
231
|
+
);
|
|
232
|
+
}
|
|
233
|
+
registry.set(desc.id, desc);
|
|
234
|
+
}
|
|
235
|
+
return registry;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
// src/testing.ts
|
|
239
|
+
var mockMeasure = (content, font) => {
|
|
240
|
+
const base = content.length * font.size * 0.6;
|
|
241
|
+
const spacing = (font.letterSpacing ?? 0) * Math.max(0, content.length - 1);
|
|
242
|
+
return base + spacing;
|
|
243
|
+
};
|
|
244
|
+
var mockSpace = (font) => {
|
|
245
|
+
const width = font.size * 0.25;
|
|
246
|
+
const stretch = width * 0.5;
|
|
247
|
+
const shrink = width * 0.3;
|
|
248
|
+
return { width, stretch, shrink };
|
|
249
|
+
};
|
|
250
|
+
var mockMetrics = (font) => ({
|
|
251
|
+
unitsPerEm: 1e3,
|
|
252
|
+
ascender: font.size * 0.8,
|
|
253
|
+
descender: -font.size * 0.2,
|
|
254
|
+
xHeight: font.size * 0.5,
|
|
255
|
+
capHeight: font.size * 0.7,
|
|
256
|
+
lineGap: 0,
|
|
257
|
+
baselineShift: font.variant === "superscript" ? font.size * 0.35 : font.variant === "subscript" ? -font.size * 0.15 : 0
|
|
258
|
+
});
|
|
259
|
+
export {
|
|
260
|
+
FontkitEngine,
|
|
261
|
+
createFontRegistry,
|
|
262
|
+
createMeasurer,
|
|
263
|
+
loadFontkitFont,
|
|
264
|
+
mockMeasure,
|
|
265
|
+
mockMetrics,
|
|
266
|
+
mockSpace,
|
|
267
|
+
resolveFontkitFont
|
|
268
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,62 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@paragraf/font-engine",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.7.1",
|
|
4
|
+
"description": "Font metrics abstraction, fontkit adapter, and measurer factory for the paragraf typesetter.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "https://github.com/kadetr/paragraf.git",
|
|
9
|
+
"directory": "1b-font-engine"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/kadetr/paragraf/tree/main/1b-font-engine#readme",
|
|
12
|
+
"keywords": [
|
|
13
|
+
"typography",
|
|
14
|
+
"typesetting",
|
|
15
|
+
"font",
|
|
16
|
+
"fontkit",
|
|
17
|
+
"paragraf"
|
|
18
|
+
],
|
|
19
|
+
"type": "module",
|
|
20
|
+
"engines": {
|
|
21
|
+
"node": ">=22"
|
|
22
|
+
},
|
|
23
|
+
"files": [
|
|
24
|
+
"dist/",
|
|
25
|
+
"README.md"
|
|
26
|
+
],
|
|
27
|
+
"exports": {
|
|
28
|
+
".": {
|
|
29
|
+
"types": "./dist/index.d.ts",
|
|
30
|
+
"default": "./dist/index.js"
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
"publishConfig": {
|
|
34
|
+
"access": "public",
|
|
35
|
+
"exports": {
|
|
36
|
+
".": {
|
|
37
|
+
"types": "./dist/index.d.ts",
|
|
38
|
+
"default": "./dist/index.js"
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
"scripts": {
|
|
43
|
+
"build": "tsup",
|
|
44
|
+
"prepublishOnly": "npm run build",
|
|
45
|
+
"test": "vitest run --passWithNoTests",
|
|
46
|
+
"test:watch": "vitest",
|
|
47
|
+
"typecheck": "tsc --noEmit",
|
|
48
|
+
"prepack": "node ../scripts/publishconfig-swap.mjs apply",
|
|
49
|
+
"postpack": "node ../scripts/publishconfig-swap.mjs restore"
|
|
50
|
+
},
|
|
51
|
+
"dependencies": {
|
|
52
|
+
"@paragraf/types": "^0.7.1",
|
|
53
|
+
"fontkit": "^2.0.4"
|
|
54
|
+
},
|
|
55
|
+
"devDependencies": {
|
|
56
|
+
"@types/fontkit": "^2.0.9",
|
|
57
|
+
"@types/node": "^22.19.15",
|
|
58
|
+
"tsx": "^4.21.0",
|
|
59
|
+
"typescript": "^5.4.0",
|
|
60
|
+
"vitest": "^3.2.4"
|
|
61
|
+
}
|
|
62
|
+
}
|