@cssints/fonts 0.0.0-stage → 0.2.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 +21 -0
- package/README.md +149 -2
- package/dist/index.d.mts +96 -0
- package/dist/index.mjs +289 -0
- package/package.json +33 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Alexei Accio
|
|
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,150 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @cssints/fonts
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Web fonts for [cssints](../../README.md): `font()` reads the font files at build time and gives two members of a
|
|
4
|
+
`cssints/plugin` `scope()`. `family()` emits the `@font-face` rules, a fallback face whose metrics match the font, and
|
|
5
|
+
`font-family`. `trim()` removes the space above the cap height and below the baseline. The metrics come from the files
|
|
6
|
+
(fontkitten). No script ships.
|
|
7
|
+
|
|
8
|
+
```ts
|
|
9
|
+
// fonts.ts: a build-time module (it runs while the build runs, and never reaches the browser)
|
|
10
|
+
import { font } from "@cssints/fonts" with { type: "cssints" };
|
|
11
|
+
|
|
12
|
+
export const body = font("Atkinson Hyperlegible", { provider: "fontsource", weights: [400, 700] });
|
|
13
|
+
export const brand = font("Brand", {
|
|
14
|
+
provider: "fs",
|
|
15
|
+
files: ["src/fonts/brand.woff2"],
|
|
16
|
+
fallback: "serif",
|
|
17
|
+
});
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
// a component imports them from there
|
|
22
|
+
import { cn } from "cssints" with { type: "cssints" };
|
|
23
|
+
import { body } from "./fonts.ts" with { type: "cssints" };
|
|
24
|
+
|
|
25
|
+
export const text = body.family();
|
|
26
|
+
export const heading = cn(body.family(), body.trim({ lineHeight: 1.2 }));
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
```css
|
|
30
|
+
@layer _.k {
|
|
31
|
+
/* fontaine's formula (capsize's createFontStack): Arial scaled to the average width of the font, the vertical
|
|
32
|
+
metrics of the font */
|
|
33
|
+
@font-face {
|
|
34
|
+
font-family: "Atkinson Hyperlegible Fallback";
|
|
35
|
+
src: local("Arial"), local("Arimo"), local("Liberation Sans");
|
|
36
|
+
size-adjust: 99.3717%;
|
|
37
|
+
ascent-override: 95.6006%;
|
|
38
|
+
descent-override: 29.1833%;
|
|
39
|
+
line-gap-override: 0%;
|
|
40
|
+
}
|
|
41
|
+
/* one face per weight and subset of the package; Vite emits the files as assets */
|
|
42
|
+
@font-face {
|
|
43
|
+
font-family: "Atkinson Hyperlegible";
|
|
44
|
+
font-style: normal;
|
|
45
|
+
font-weight: 400;
|
|
46
|
+
font-display: swap;
|
|
47
|
+
src: url("/…/atkinson-hyperlegible-latin-400-normal.woff2") format("woff2");
|
|
48
|
+
unicode-range: U+0000-00FF, …;
|
|
49
|
+
}
|
|
50
|
+
/* … latin-ext 400, latin 700, latin-ext 700 */
|
|
51
|
+
._fonts-native {
|
|
52
|
+
text-box: trim-both cap alphabetic;
|
|
53
|
+
}
|
|
54
|
+
/* only when a target lacks text-box */
|
|
55
|
+
@supports not (text-box: trim-both cap alphabetic) {
|
|
56
|
+
._fonts-native::before,
|
|
57
|
+
._fonts-native::after {
|
|
58
|
+
content: "";
|
|
59
|
+
display: table;
|
|
60
|
+
}
|
|
61
|
+
._fonts-native::before {
|
|
62
|
+
margin-bottom: var(--fonts-t);
|
|
63
|
+
}
|
|
64
|
+
._fonts-native::after {
|
|
65
|
+
margin-top: var(--fonts-b);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
@layer _.a {
|
|
70
|
+
._a {
|
|
71
|
+
font-family: "Atkinson Hyperlegible", "Atkinson Hyperlegible Fallback", sans-serif;
|
|
72
|
+
}
|
|
73
|
+
._b {
|
|
74
|
+
line-height: 1.2;
|
|
75
|
+
}
|
|
76
|
+
._c {
|
|
77
|
+
--fonts-t: -0.262em;
|
|
78
|
+
}
|
|
79
|
+
._d {
|
|
80
|
+
--fonts-b: -0.27em;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## Rules
|
|
86
|
+
|
|
87
|
+
- **Providers.** `fontsource` reads the `@fontsource/<family>` package from the `node_modules` of the working directory
|
|
88
|
+
(`"Atkinson Hyperlegible"` is `@fontsource/atkinson-hyperlegible`): its `.woff2` files, one face per weight, style
|
|
89
|
+
and subset, each with the subset's `unicode-range`. `weights` and `styles` must be among those of the package (400 and
|
|
90
|
+
`normal` by default). `fs` takes font files (`.woff2`, `.woff`, `.ttf`, `.otf`, relative to the working directory),
|
|
91
|
+
one face each, with the weight and style read from the file.
|
|
92
|
+
- **URLs.** A face's `src` is the absolute path of the file. Vite's CSS pipeline turns it into an asset in a build
|
|
93
|
+
(`/assets/…-[hash].woff2`) and into `/@fs/…` in dev.
|
|
94
|
+
- **Fallback face.** `fallback` is a generic family (`sans-serif`, `serif` or `monospace`; by default the category of
|
|
95
|
+
the fontsource package, else `sans-serif`). Its local fonts are Arial, Times New Roman or Courier New, with their
|
|
96
|
+
metric-compatible clones (Arimo, Tinos, Cousine, the Liberation fonts). The face scales them to the font's average
|
|
97
|
+
latin width (`size-adjust`) and overrides `ascent`, `descent` and `line-gap` with the font's. This is fontaine's
|
|
98
|
+
formula. The numbers are those of `@capsizecss/core` `createFontStack` (checked in the test). The metrics come from
|
|
99
|
+
the 400 normal face (else the first) of the latin subset.
|
|
100
|
+
- **trim().** `trim()` sets `line-height` (`normal`, or the number given) and the class of the kernel
|
|
101
|
+
`text-box: trim-both cap alphabetic` (Chrome 133, Safari 18.2, Firefox 154). When a target lacks `text-box`, the
|
|
102
|
+
sheet gets capsize's fallback: `::before` and `::after` with negative margins, in `em`, from the metrics of the font
|
|
103
|
+
and the line height (the numbers of `@capsizecss/core` `createStyleObject`, checked in the test). The fallback is
|
|
104
|
+
plain CSS, so every target gets it (Firefox 120 too), and there is no build warning. It is inside `@supports not`,
|
|
105
|
+
so a browser with `text-box` does not trim twice. When every target has `text-box`, the fallback is not in the sheet.
|
|
106
|
+
- **Errors**, at build time: a package that is not installed (the message names it), a weight or a style the
|
|
107
|
+
package does not have, a file that cannot be read, a font collection, and a `lineHeight` that is not a number
|
|
108
|
+
(also a type error).
|
|
109
|
+
- **Cache.** A file is parsed once per modification time in a process.
|
|
110
|
+
|
|
111
|
+
## Limits
|
|
112
|
+
|
|
113
|
+
- `lineHeight` is a number (a multiple of the font size). A length would make the trim depend on the font size.
|
|
114
|
+
- The trim is right for the web font. The fallback face matches ascent and descent, but not the cap height, so the
|
|
115
|
+
trim is off by a little until the font loads.
|
|
116
|
+
- Not yet: variable fonts (`@fontsource-variable/*`), remote providers (unifont, Google Fonts), the subsets option,
|
|
117
|
+
and `font-display` other than `swap`.
|
|
118
|
+
- In dev, an edited file of `fs` updates the CSS of the modules that use it (`dependsOn` of `cssints/plugin`). The files
|
|
119
|
+
of `fontsource` are in `node_modules`, which Vite does not watch.
|
|
120
|
+
|
|
121
|
+
```bash
|
|
122
|
+
cd packages/fonts && bun run test # fixtures through the engine (output, errors, warnings, a build), and the type test via bun run typecheck
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
## Credits
|
|
126
|
+
|
|
127
|
+
Copied, with the notice below:
|
|
128
|
+
|
|
129
|
+
- The characters and weights of the average width (`xWidthAvg`): the latin table of
|
|
130
|
+
[`@capsizecss/unpack`](https://github.com/seek-oss/capsize) (MIT, SEEK).
|
|
131
|
+
- The metrics of Arial, Times New Roman and Courier New from `@capsizecss/metrics` (MIT, SEEK).
|
|
132
|
+
|
|
133
|
+
Followed, not copied: the fallback face and the trim formulas of `@capsizecss/core` (the test checks the numbers
|
|
134
|
+
against it), and [fontaine](https://github.com/unjs/fontaine) (MIT, Daniel Roe) for the fallback face. The font files
|
|
135
|
+
are read with [fontkitten](https://github.com/delucis/fontkitten) (MIT), a dependency.
|
|
136
|
+
|
|
137
|
+
The MIT notice of Capsize, Copyright (c) 2021 SEEK:
|
|
138
|
+
|
|
139
|
+
> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
|
|
140
|
+
> documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
|
|
141
|
+
> rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
|
|
142
|
+
> persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
143
|
+
>
|
|
144
|
+
> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
|
|
145
|
+
> Software.
|
|
146
|
+
>
|
|
147
|
+
> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
|
|
148
|
+
> WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
|
149
|
+
> COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
|
|
150
|
+
> OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
//#region src/index.d.ts
|
|
2
|
+
/** What the fallback face and `trim()` are computed from, in font units (capsize's names). */
|
|
3
|
+
export interface Metrics {
|
|
4
|
+
ascent: number;
|
|
5
|
+
descent: number;
|
|
6
|
+
lineGap: number;
|
|
7
|
+
unitsPerEm: number;
|
|
8
|
+
capHeight: number;
|
|
9
|
+
/** The advance width of the latin letters, weighted by their frequency in English text (capsize's `xWidthAvg`). */
|
|
10
|
+
xWidthAvg: number;
|
|
11
|
+
}
|
|
12
|
+
/** A generic family: its local fonts (metric-compatible clones of one font) stand in until the web font loads. */
|
|
13
|
+
export type Fallback = "sans-serif" | "serif" | "monospace";
|
|
14
|
+
/**
|
|
15
|
+
* Where the files come from: the `@fontsource/<family>` package installed in the project (its `files/*.woff2`, every
|
|
16
|
+
* subset with its `unicode-range`), or font files (paths relative to the working directory; weight and style are read
|
|
17
|
+
* from each file).
|
|
18
|
+
*/
|
|
19
|
+
export type Options = {
|
|
20
|
+
fallback?: Fallback;
|
|
21
|
+
} & ({
|
|
22
|
+
provider: "fontsource";
|
|
23
|
+
weights?: number[];
|
|
24
|
+
styles?: ("normal" | "italic")[];
|
|
25
|
+
} | {
|
|
26
|
+
provider: "fs";
|
|
27
|
+
files: string[];
|
|
28
|
+
});
|
|
29
|
+
interface Face {
|
|
30
|
+
file: string;
|
|
31
|
+
weight: number;
|
|
32
|
+
style: string;
|
|
33
|
+
unicodeRange?: string;
|
|
34
|
+
}
|
|
35
|
+
interface Source {
|
|
36
|
+
faces: Face[];
|
|
37
|
+
/** The face the metrics come from: 400 normal, else the first. */
|
|
38
|
+
metrics: Metrics;
|
|
39
|
+
category: Fallback;
|
|
40
|
+
}
|
|
41
|
+
declare const fonts: (family: string, fallback: string, source: Source, globals: {
|
|
42
|
+
css: string;
|
|
43
|
+
}[]) => import("cssints/plugin").Members<{
|
|
44
|
+
readonly "#native": {
|
|
45
|
+
readonly css: "&{text-box:trim-both cap alphabetic}";
|
|
46
|
+
readonly requires: ["css.properties.text-box"];
|
|
47
|
+
};
|
|
48
|
+
readonly "#capsize": {
|
|
49
|
+
readonly polyfills: ["css.properties.text-box"];
|
|
50
|
+
readonly css: string;
|
|
51
|
+
};
|
|
52
|
+
readonly family: {
|
|
53
|
+
readonly args: readonly [];
|
|
54
|
+
};
|
|
55
|
+
readonly trim: {
|
|
56
|
+
readonly args: readonly [{
|
|
57
|
+
readonly "lineHeight?": "<number [0,∞]>";
|
|
58
|
+
}];
|
|
59
|
+
readonly uses: readonly ["native", "capsize"];
|
|
60
|
+
};
|
|
61
|
+
}>;
|
|
62
|
+
/**
|
|
63
|
+
* What `font()` gives: call its members where the style is used. `family()` is `font-family` with the fallback face and
|
|
64
|
+
* carries the @font-face rules; `trim({ lineHeight? })` trims the space above the cap height and below the baseline.
|
|
65
|
+
*/
|
|
66
|
+
export type Font = ReturnType<typeof fonts>;
|
|
67
|
+
/**
|
|
68
|
+
* A web font from the `@fontsource/<family>` package installed in the project (`provider: "fontsource"`, `weights`
|
|
69
|
+
* and `styles` among those it has, 400 normal by default), or from font files (`provider: "fs"`, paths relative to the
|
|
70
|
+
* working directory). The files are read when the module runs. Call `font()` in a module of its own, imported with the
|
|
71
|
+
* attribute, and its members where the style is used.
|
|
72
|
+
*
|
|
73
|
+
* @param {string} family the CSS family name (for fontsource, also the package: "Atkinson Hyperlegible" is `@fontsource/atkinson-hyperlegible`)
|
|
74
|
+
* @param {Options} options where the files come from, and the generic family of the fallback face (by default the font's category)
|
|
75
|
+
* @returns {Font} the members `family()` and `trim()`
|
|
76
|
+
*/
|
|
77
|
+
export declare const font: (family: string, options: Options) => import("cssints/plugin").Members<{
|
|
78
|
+
readonly "#native": {
|
|
79
|
+
readonly css: "&{text-box:trim-both cap alphabetic}";
|
|
80
|
+
readonly requires: ["css.properties.text-box"];
|
|
81
|
+
};
|
|
82
|
+
readonly "#capsize": {
|
|
83
|
+
readonly polyfills: ["css.properties.text-box"];
|
|
84
|
+
readonly css: string;
|
|
85
|
+
};
|
|
86
|
+
readonly family: {
|
|
87
|
+
readonly args: readonly [];
|
|
88
|
+
};
|
|
89
|
+
readonly trim: {
|
|
90
|
+
readonly args: readonly [{
|
|
91
|
+
readonly "lineHeight?": "<number [0,∞]>";
|
|
92
|
+
}];
|
|
93
|
+
readonly uses: readonly ["native", "capsize"];
|
|
94
|
+
};
|
|
95
|
+
}>;
|
|
96
|
+
//#endregion
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
import { readFileSync, statSync } from "node:fs";
|
|
3
|
+
import { dirname, extname, join, resolve } from "node:path";
|
|
4
|
+
import { create } from "fontkitten";
|
|
5
|
+
import { dependsOn, scope } from "cssints/plugin";
|
|
6
|
+
//#region src/index.ts
|
|
7
|
+
const FALLBACKS = {
|
|
8
|
+
"sans-serif": {
|
|
9
|
+
locals: [
|
|
10
|
+
"Arial",
|
|
11
|
+
"Arimo",
|
|
12
|
+
"Liberation Sans"
|
|
13
|
+
],
|
|
14
|
+
metrics: {
|
|
15
|
+
ascent: 1854,
|
|
16
|
+
descent: -434,
|
|
17
|
+
lineGap: 67,
|
|
18
|
+
unitsPerEm: 2048,
|
|
19
|
+
capHeight: 1467,
|
|
20
|
+
xWidthAvg: 913
|
|
21
|
+
}
|
|
22
|
+
},
|
|
23
|
+
serif: {
|
|
24
|
+
locals: [
|
|
25
|
+
"Times New Roman",
|
|
26
|
+
"Tinos",
|
|
27
|
+
"Liberation Serif"
|
|
28
|
+
],
|
|
29
|
+
metrics: {
|
|
30
|
+
ascent: 1825,
|
|
31
|
+
descent: -443,
|
|
32
|
+
lineGap: 87,
|
|
33
|
+
unitsPerEm: 2048,
|
|
34
|
+
capHeight: 1356,
|
|
35
|
+
xWidthAvg: 832
|
|
36
|
+
}
|
|
37
|
+
},
|
|
38
|
+
monospace: {
|
|
39
|
+
locals: [
|
|
40
|
+
"Courier New",
|
|
41
|
+
"Cousine",
|
|
42
|
+
"Liberation Mono"
|
|
43
|
+
],
|
|
44
|
+
metrics: {
|
|
45
|
+
ascent: 1705,
|
|
46
|
+
descent: -615,
|
|
47
|
+
lineGap: 0,
|
|
48
|
+
unitsPerEm: 2048,
|
|
49
|
+
capHeight: 1170,
|
|
50
|
+
xWidthAvg: 1229
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
const SAMPLE = "0123456789, theofPpl'sRubicCnadywBrzGjT.Lkm]JFvgAN-HDMIE\"S()xWQYqVáKU=[Oé$:|/%Z;X";
|
|
55
|
+
const WEIGHTS = [
|
|
56
|
+
.0053,
|
|
57
|
+
.0023,
|
|
58
|
+
.0026,
|
|
59
|
+
.001,
|
|
60
|
+
8e-4,
|
|
61
|
+
.0015,
|
|
62
|
+
7e-4,
|
|
63
|
+
5e-4,
|
|
64
|
+
7e-4,
|
|
65
|
+
6e-4,
|
|
66
|
+
.0083,
|
|
67
|
+
.154,
|
|
68
|
+
.0672,
|
|
69
|
+
.0351,
|
|
70
|
+
.0922,
|
|
71
|
+
.0571,
|
|
72
|
+
.017,
|
|
73
|
+
.0023,
|
|
74
|
+
.0163,
|
|
75
|
+
.0304,
|
|
76
|
+
.0014,
|
|
77
|
+
.0469,
|
|
78
|
+
.0015,
|
|
79
|
+
.0207,
|
|
80
|
+
.0114,
|
|
81
|
+
.0588,
|
|
82
|
+
.0232,
|
|
83
|
+
.0031,
|
|
84
|
+
.0578,
|
|
85
|
+
.0668,
|
|
86
|
+
.0298,
|
|
87
|
+
.0123,
|
|
88
|
+
.011,
|
|
89
|
+
.002,
|
|
90
|
+
.0526,
|
|
91
|
+
.0011,
|
|
92
|
+
.0011,
|
|
93
|
+
9e-4,
|
|
94
|
+
.0041,
|
|
95
|
+
.0079,
|
|
96
|
+
.0012,
|
|
97
|
+
.0046,
|
|
98
|
+
.0181,
|
|
99
|
+
7e-4,
|
|
100
|
+
9e-4,
|
|
101
|
+
.0015,
|
|
102
|
+
.0076,
|
|
103
|
+
.0155,
|
|
104
|
+
.004,
|
|
105
|
+
.0014,
|
|
106
|
+
.0018,
|
|
107
|
+
.0013,
|
|
108
|
+
.0013,
|
|
109
|
+
.0025,
|
|
110
|
+
.0022,
|
|
111
|
+
.0011,
|
|
112
|
+
.0012,
|
|
113
|
+
.0041,
|
|
114
|
+
.001,
|
|
115
|
+
.001,
|
|
116
|
+
.0025,
|
|
117
|
+
.0012,
|
|
118
|
+
1e-4,
|
|
119
|
+
3e-4,
|
|
120
|
+
8e-4,
|
|
121
|
+
5e-4,
|
|
122
|
+
1e-4,
|
|
123
|
+
7e-4,
|
|
124
|
+
.0016,
|
|
125
|
+
7e-4,
|
|
126
|
+
.0021,
|
|
127
|
+
9e-4,
|
|
128
|
+
1e-4,
|
|
129
|
+
2e-4,
|
|
130
|
+
8e-4,
|
|
131
|
+
.0038,
|
|
132
|
+
1e-4,
|
|
133
|
+
1e-4,
|
|
134
|
+
2e-4,
|
|
135
|
+
1e-4,
|
|
136
|
+
1e-4
|
|
137
|
+
];
|
|
138
|
+
const FORMATS = /* @__PURE__ */ new Map([
|
|
139
|
+
[".woff2", "woff2"],
|
|
140
|
+
[".woff", "woff"],
|
|
141
|
+
[".ttf", "truetype"],
|
|
142
|
+
[".otf", "opentype"]
|
|
143
|
+
]);
|
|
144
|
+
const fail = (message, cause) => {
|
|
145
|
+
throw new Error(`cssints: fonts: ${message}`, { cause });
|
|
146
|
+
};
|
|
147
|
+
const attempt = (f, message) => {
|
|
148
|
+
try {
|
|
149
|
+
return f();
|
|
150
|
+
} catch (e) {
|
|
151
|
+
return fail(message, e);
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
const g = globalThis;
|
|
155
|
+
const read = (file) => {
|
|
156
|
+
const mtime = attempt(() => statSync(file).mtimeMs, `cannot read ${file}`);
|
|
157
|
+
const cache = g.__cssintsFonts ??= /* @__PURE__ */ new Map();
|
|
158
|
+
const hit = cache.get(file);
|
|
159
|
+
if (hit?.mtime === mtime) return hit.read;
|
|
160
|
+
const font = create(readFileSync(file));
|
|
161
|
+
if (font.isCollection) return fail(`${file} is a font collection: give one font file`);
|
|
162
|
+
const xWidthAvg = Math.round(font.glyphsForString(SAMPLE).reduce((sum, glyph, i) => glyph.isMark ? sum : sum + glyph.advanceWidth * WEIGHTS[i], 0));
|
|
163
|
+
const { ascent, descent, lineGap, unitsPerEm, capHeight } = font;
|
|
164
|
+
const out = {
|
|
165
|
+
metrics: {
|
|
166
|
+
ascent,
|
|
167
|
+
descent,
|
|
168
|
+
lineGap,
|
|
169
|
+
unitsPerEm,
|
|
170
|
+
capHeight,
|
|
171
|
+
xWidthAvg
|
|
172
|
+
},
|
|
173
|
+
weight: font["OS/2"].usWeightClass,
|
|
174
|
+
style: font["OS/2"].fsSelection.italic || font.italicAngle !== 0 ? "italic" : "normal"
|
|
175
|
+
};
|
|
176
|
+
cache.set(file, {
|
|
177
|
+
mtime,
|
|
178
|
+
read: out
|
|
179
|
+
});
|
|
180
|
+
return out;
|
|
181
|
+
};
|
|
182
|
+
const fontsource = (family, weights, styles = ["normal"]) => {
|
|
183
|
+
const pkg = `@fontsource/${family.toLowerCase().replace(/\s+/g, "-")}`;
|
|
184
|
+
const dir = attempt(() => dirname(createRequire(join(process.cwd(), "_")).resolve(pkg)), `cannot read ${pkg} from ${process.cwd()}: install ${pkg}`);
|
|
185
|
+
const meta = JSON.parse(readFileSync(join(dir, "metadata.json"), "utf8"));
|
|
186
|
+
const ranges = JSON.parse(readFileSync(join(dir, "unicode.json"), "utf8"));
|
|
187
|
+
const ws = weights ?? [meta.weights.includes(400) ? 400 : meta.weights[0]];
|
|
188
|
+
for (const w of ws) if (!meta.weights.includes(w)) fail(`${pkg} has no weight ${w} (it has ${meta.weights.join(", ")})`);
|
|
189
|
+
for (const s of styles) if (!meta.styles.includes(s)) fail(`${pkg} has no style ${s} (it has ${meta.styles.join(", ")})`);
|
|
190
|
+
const file = (subset, w, s) => join(dir, "files", `${meta.id}-${subset.replace(/^\[(\d+)\]$/, "$1")}-${w}-${s}.woff2`);
|
|
191
|
+
const faces = ws.flatMap((weight) => styles.flatMap((style) => Object.entries(ranges).map(([subset, unicodeRange]) => ({
|
|
192
|
+
file: file(subset, weight, style),
|
|
193
|
+
weight,
|
|
194
|
+
style,
|
|
195
|
+
unicodeRange
|
|
196
|
+
}))));
|
|
197
|
+
const main = file(meta.defSubset, ws.includes(400) ? 400 : ws[0], styles[0]);
|
|
198
|
+
return {
|
|
199
|
+
faces,
|
|
200
|
+
metrics: read(main).metrics,
|
|
201
|
+
category: meta.category === "serif" || meta.category === "monospace" ? meta.category : "sans-serif"
|
|
202
|
+
};
|
|
203
|
+
};
|
|
204
|
+
const files = (list) => {
|
|
205
|
+
if (!list.length) fail("fs takes at least one file");
|
|
206
|
+
const faces = list.map((f) => {
|
|
207
|
+
const file = resolve(f);
|
|
208
|
+
if (!FORMATS.has(extname(file))) fail(`${f}: not a .woff2, .woff, .ttf or .otf file`);
|
|
209
|
+
dependsOn(file);
|
|
210
|
+
const { weight, style } = read(file);
|
|
211
|
+
return {
|
|
212
|
+
file,
|
|
213
|
+
weight,
|
|
214
|
+
style
|
|
215
|
+
};
|
|
216
|
+
});
|
|
217
|
+
const main = faces.find((f) => f.weight === 400 && f.style === "normal") ?? faces[0];
|
|
218
|
+
return {
|
|
219
|
+
faces,
|
|
220
|
+
metrics: read(main.file).metrics,
|
|
221
|
+
category: "sans-serif"
|
|
222
|
+
};
|
|
223
|
+
};
|
|
224
|
+
const quote = (s) => `"${s.replace(/["\\]/g, "\\$&")}"`;
|
|
225
|
+
const round = (n) => Number.parseFloat(n.toFixed(4));
|
|
226
|
+
const percent = (n) => `${round(n * 100)}%`;
|
|
227
|
+
const faceRule = (family, f) => `@font-face{font-family:${quote(family)};font-style:${f.style};font-weight:${f.weight};font-display:swap;src:url(${quote(f.file)}) format(${quote(FORMATS.get(extname(f.file)))})${f.unicodeRange ? `;unicode-range:${f.unicodeRange}` : ""}}`;
|
|
228
|
+
const fallbackFace = (name, metrics, fallback) => {
|
|
229
|
+
const { locals, metrics: local } = FALLBACKS[fallback];
|
|
230
|
+
const sizeAdjust = metrics.xWidthAvg / metrics.unitsPerEm / (local.xWidthAvg / local.unitsPerEm);
|
|
231
|
+
const em = metrics.unitsPerEm * sizeAdjust;
|
|
232
|
+
return `@font-face{font-family:${quote(name)};src:${locals.map((l) => `local(${quote(l)})`).join(",")};size-adjust:${percent(sizeAdjust)};ascent-override:${percent(metrics.ascent / em)};descent-override:${percent(Math.abs(metrics.descent) / em)};line-gap-override:${percent(metrics.lineGap / em)}}`;
|
|
233
|
+
};
|
|
234
|
+
const trims = (m, lineHeight) => {
|
|
235
|
+
const scale = (n) => n / m.unitsPerEm;
|
|
236
|
+
const offset = lineHeight ? (scale(m.ascent + m.lineGap + Math.abs(m.descent)) - lineHeight) / 2 : 0;
|
|
237
|
+
const top = scale(m.ascent) - scale(m.capHeight) + scale(m.lineGap) / 2 - offset;
|
|
238
|
+
const bottom = scale(Math.abs(m.descent)) + scale(m.lineGap) / 2 - offset;
|
|
239
|
+
return {
|
|
240
|
+
top: `${round(-top)}em`,
|
|
241
|
+
bottom: `${round(-bottom)}em`
|
|
242
|
+
};
|
|
243
|
+
};
|
|
244
|
+
const NATIVE = "text-box:trim-both cap alphabetic";
|
|
245
|
+
const fonts = (family, fallback, source, globals) => scope("fonts", {
|
|
246
|
+
"#native": {
|
|
247
|
+
css: `&{${NATIVE}}`,
|
|
248
|
+
requires: ["css.properties.text-box"]
|
|
249
|
+
},
|
|
250
|
+
"#capsize": {
|
|
251
|
+
polyfills: ["css.properties.text-box"],
|
|
252
|
+
css: `@supports not (${NATIVE}){&::before,&::after{content:"";display:table}&::before{margin-bottom:var(--_t)}&::after{margin-top:var(--_b)}}`
|
|
253
|
+
},
|
|
254
|
+
family: { args: [] },
|
|
255
|
+
trim: {
|
|
256
|
+
args: [{ "lineHeight?": "<number [0,∞]>" }],
|
|
257
|
+
uses: ["native", "capsize"]
|
|
258
|
+
}
|
|
259
|
+
}).build({
|
|
260
|
+
family: () => ({
|
|
261
|
+
decls: [["font-family", `${quote(family)}, ${quote(`${family} Fallback`)}, ${fallback}`]],
|
|
262
|
+
globals
|
|
263
|
+
}),
|
|
264
|
+
trim: (o) => {
|
|
265
|
+
const { top, bottom } = trims(source.metrics, o.lineHeight ? Number(o.lineHeight) : void 0);
|
|
266
|
+
return { decls: [
|
|
267
|
+
["line-height", o.lineHeight ?? "normal"],
|
|
268
|
+
["--_t", top],
|
|
269
|
+
["--_b", bottom]
|
|
270
|
+
] };
|
|
271
|
+
}
|
|
272
|
+
}).export();
|
|
273
|
+
/**
|
|
274
|
+
* A web font from the `@fontsource/<family>` package installed in the project (`provider: "fontsource"`, `weights`
|
|
275
|
+
* and `styles` among those it has, 400 normal by default), or from font files (`provider: "fs"`, paths relative to the
|
|
276
|
+
* working directory). The files are read when the module runs. Call `font()` in a module of its own, imported with the
|
|
277
|
+
* attribute, and its members where the style is used.
|
|
278
|
+
*
|
|
279
|
+
* @param {string} family the CSS family name (for fontsource, also the package: "Atkinson Hyperlegible" is `@fontsource/atkinson-hyperlegible`)
|
|
280
|
+
* @param {Options} options where the files come from, and the generic family of the fallback face (by default the font's category)
|
|
281
|
+
* @returns {Font} the members `family()` and `trim()`
|
|
282
|
+
*/
|
|
283
|
+
const font = (family, options) => {
|
|
284
|
+
const source = options.provider === "fs" ? files(options.files) : fontsource(family, options.weights, options.styles);
|
|
285
|
+
const fallback = options.fallback ?? source.category;
|
|
286
|
+
return fonts(family, fallback, source, [...source.faces.map((f) => ({ css: faceRule(family, f) })), { css: fallbackFace(`${family} Fallback`, source.metrics, fallback) }]);
|
|
287
|
+
};
|
|
288
|
+
//#endregion
|
|
289
|
+
export { font };
|
package/package.json
CHANGED
|
@@ -1,6 +1,35 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cssints/fonts",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Fonts for cssints: @font-face rules with a metric-matched fallback face, and cap-height trimming",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/alexeiaccio/css-in-ts-compiler.git",
|
|
9
|
+
"directory": "packages/fonts"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://cssints.dev",
|
|
12
|
+
"files": [
|
|
13
|
+
"dist"
|
|
14
|
+
],
|
|
15
|
+
"type": "module",
|
|
16
|
+
"sideEffects": false,
|
|
17
|
+
"exports": {
|
|
18
|
+
".": {
|
|
19
|
+
"types": "./dist/index.d.mts",
|
|
20
|
+
"default": "./dist/index.mjs"
|
|
21
|
+
}
|
|
22
|
+
},
|
|
23
|
+
"dependencies": {
|
|
24
|
+
"fontkitten": "^1.0.3"
|
|
25
|
+
},
|
|
26
|
+
"peerDependencies": {
|
|
27
|
+
"cssints": "^0.2.0"
|
|
28
|
+
},
|
|
29
|
+
"engines": {
|
|
30
|
+
"node": ">=22"
|
|
31
|
+
},
|
|
32
|
+
"publishConfig": {
|
|
33
|
+
"access": "public"
|
|
34
|
+
}
|
|
35
|
+
}
|