-
Notifications
You must be signed in to change notification settings - Fork 37
/
createFontStack.ts
295 lines (257 loc) · 8.85 KB
/
createFontStack.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
import type { AtRule } from 'csstype';
import { round } from './round';
import type { FontMetrics, SupportedSubset } from './types';
const toPercentString = (value: number) => `${round(value * 100)}%`;
const fromPercentString = (value: string) => parseFloat(value) / 100;
export const toCssProperty = (property: string) =>
property.replace(/([A-Z])/g, (property) => `-${property.toLowerCase()}`);
type Optional<T, K extends keyof T> = Pick<Partial<T>, K> & Omit<T, K>;
/*
Making `fullName` and `postscriptName` optional for the `createFontStack` API.
MDN recommends using these when accessing local fonts to ensure the best
matching across platforms. This also enables selecting a single font face
within a larger family, e.g. `Arial Bold` or `Arial-BoldMT` within `Arial`.
See MDN for details: https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/src#localfont-face-name
Falling back to `familyName` (original behaviour) if these are not available,
which will default to the `regular` font face within the family.
*/
type FontStackMetrics = Optional<
Pick<
FontMetrics,
| 'familyName'
| 'fullName'
| 'postscriptName'
| 'ascent'
| 'descent'
| 'lineGap'
| 'unitsPerEm'
| 'xWidthAvg'
| 'subsets'
>,
'fullName' | 'postscriptName'
>;
const resolveLocalFallbackSource = (metrics: FontStackMetrics) => {
const sources: string[] = [];
if (metrics.fullName) {
sources.push(`local('${metrics.fullName}')`);
}
if (metrics.postscriptName && metrics.postscriptName !== metrics.fullName) {
sources.push(`local('${metrics.postscriptName}')`);
}
if (sources.length > 0) {
return sources.join(', ');
}
return `local('${metrics.familyName}')`;
};
// Support old metrics pre-`subsets` alongside the newer core package with `subset` support.
const resolveXWidthAvg = (
metrics: FontStackMetrics,
subset: SupportedSubset,
) => {
if ('subsets' in metrics && metrics?.subsets?.[subset]) {
return metrics.subsets[subset].xWidthAvg;
}
if (subset !== 'latin') {
throw new Error(
`The subset "${subset}" is not available in the metrics provided for "${metrics.familyName}"`,
);
}
return metrics.xWidthAvg;
};
interface OverrideValuesParams {
metrics: FontStackMetrics;
fallbackMetrics: FontStackMetrics;
subset: SupportedSubset;
sizeAdjust?: AtRule.FontFace['sizeAdjust'];
}
const calculateOverrideValues = ({
metrics,
fallbackMetrics,
subset,
sizeAdjust: sizeAdjustOverride,
}: OverrideValuesParams): AtRule.FontFace => {
// Calculate size adjust
const preferredFontXAvgRatio =
resolveXWidthAvg(metrics, subset) / metrics.unitsPerEm;
const fallbackFontXAvgRatio =
resolveXWidthAvg(fallbackMetrics, subset) / fallbackMetrics.unitsPerEm;
const calculatedSizeAdjust =
preferredFontXAvgRatio && fallbackFontXAvgRatio
? preferredFontXAvgRatio / fallbackFontXAvgRatio
: 1;
const sizeAdjust = sizeAdjustOverride
? fromPercentString(sizeAdjustOverride)
: calculatedSizeAdjust;
const adjustedEmSquare = metrics.unitsPerEm * sizeAdjust;
// Calculate metric overrides for preferred font
const ascentOverride = metrics.ascent / adjustedEmSquare;
const descentOverride = Math.abs(metrics.descent) / adjustedEmSquare;
const lineGapOverride = metrics.lineGap / adjustedEmSquare;
// Calculate metric overrides for fallback font
const fallbackAscentOverride = fallbackMetrics.ascent / adjustedEmSquare;
const fallbackDescentOverride =
Math.abs(fallbackMetrics.descent) / adjustedEmSquare;
const fallbackLineGapOverride = fallbackMetrics.lineGap / adjustedEmSquare;
// Conditionally populate font face properties and format to percent
const fontFace: AtRule.FontFace = {};
if (ascentOverride && ascentOverride !== fallbackAscentOverride) {
fontFace['ascentOverride'] = toPercentString(ascentOverride);
}
if (descentOverride && descentOverride !== fallbackDescentOverride) {
fontFace['descentOverride'] = toPercentString(descentOverride);
}
if (lineGapOverride !== fallbackLineGapOverride) {
fontFace['lineGapOverride'] = toPercentString(lineGapOverride);
}
if (sizeAdjust && sizeAdjust !== 1) {
fontFace['sizeAdjust'] = toPercentString(sizeAdjust);
}
return fontFace;
};
export const quoteIfNeeded = (name: string) => {
const quotedMatch = name.match(/^['"](?<name>.*)['"]$/);
if (quotedMatch && quotedMatch.groups?.name) {
// Escape double quotes in middle of name
return `"${quotedMatch.groups.name.split(`"`).join(`\"`)}"`;
}
if (/^"/.test(name)) {
// Complete double quotes if incomplete and escape double quotes in middle
const [, ...restName] = name;
return `"${restName.map((x) => (x === `"` ? `\"` : x)).join('')}"`;
}
if (!/^[a-zA-Z\d\-_]+$/.test(name)) {
// Wrap in quotes if contains any characters that are not letters,
// numbers, hyphens or underscores
return `"${name.split(`"`).join(`\"`)}"`;
}
return name;
};
type FontFace = {
'@font-face': Omit<AtRule.FontFace, 'src' | 'fontFamily'> &
Required<Pick<AtRule.FontFace, 'src' | 'fontFamily'>>;
};
const toCssString = (fontFaces: FontFace[]) => {
return fontFaces
.map(({ '@font-face': { fontFamily, src, ...restFontFaceProperties } }) => {
const fontFace = [
'@font-face {',
` font-family: ${quoteIfNeeded(fontFamily)};`,
` src: ${src};`,
];
Object.keys(restFontFaceProperties).forEach((property) => {
fontFace.push(
` ${toCssProperty(property)}: ${
restFontFaceProperties[
property as keyof typeof restFontFaceProperties
]
};`,
);
});
fontFace.push('}');
return fontFace.join('\n');
})
.join('\n');
};
type AdditionalFontFaceProperties = Omit<
AtRule.FontFace,
| 'src'
| 'fontFamily'
| 'ascentOverride'
| 'descentOverride'
| 'lineGapOverride'
>;
type CreateFontStackOptions = {
/**
* Additional properties to add to the generated `@font-face` declarations.
*
* Accepts all valid `@font-face` properties except the following which are
* generated by Capsize: `src`, `fontFamily`, `ascentOverride`,
* `descentOverride`, `lineGapOverride`, although allows `size-adjust` to
* support explicit overrides.
*/
fontFaceProperties?: AdditionalFontFaceProperties;
/**
* The unicode subset to generate the fallback font for.
*
* The fallback font is scaled according to the average character width,
* calculated from weighted character frequencies in written text that
* uses the specified subset, e.g. `latin` from English, `thai` from Thai.
*
* Default: `latin`
*/
subset?: SupportedSubset;
};
type FontFaceFormatString = {
/**
* Choose between returning CSS as a string for stylesheets or `style` tags,
* or as a style object for CSS-in-JS integration.
*
* Default: `styleString`
*/
fontFaceFormat?: 'styleString';
};
type FontFaceFormatObject = {
fontFaceFormat?: 'styleObject';
};
const resolveOptions = (options: Parameters<typeof createFontStack>[1]) => {
const fontFaceFormat = options?.fontFaceFormat ?? 'styleString';
const subset = options?.subset ?? 'latin';
const { sizeAdjust, ...fontFaceProperties } =
options?.fontFaceProperties ?? {};
return {
fontFaceFormat,
subset,
fontFaceProperties,
sizeAdjust,
} as const;
};
export function createFontStack(
fontStackMetrics: FontStackMetrics[],
options?: CreateFontStackOptions & FontFaceFormatString,
): { fontFamily: string; fontFaces: string };
export function createFontStack(
fontStackMetrics: FontStackMetrics[],
options?: CreateFontStackOptions & FontFaceFormatObject,
): { fontFamily: string; fontFaces: FontFace[] };
export function createFontStack(
[metrics, ...fallbackMetrics]: FontStackMetrics[],
optionsArg: CreateFontStackOptions = {},
) {
const { fontFaceFormat, fontFaceProperties, sizeAdjust, subset } =
resolveOptions(optionsArg);
const { familyName } = metrics;
const fontFamilies: string[] = [quoteIfNeeded(familyName)];
const fontFaces: FontFace[] = [];
fallbackMetrics.forEach((fallback) => {
const fontFamily = quoteIfNeeded(
`${familyName} Fallback${
fallbackMetrics.length > 1 ? `: ${fallback.familyName}` : ''
}`,
);
fontFamilies.push(fontFamily);
fontFaces.push({
'@font-face': {
...fontFaceProperties,
fontFamily,
src: resolveLocalFallbackSource(fallback),
...calculateOverrideValues({
metrics,
fallbackMetrics: fallback,
subset,
sizeAdjust,
}),
},
});
});
// Include original fallback font families after generated fallbacks
fallbackMetrics.forEach((fallback) => {
fontFamilies.push(quoteIfNeeded(fallback.familyName));
});
return {
fontFamily: fontFamilies.join(', '),
fontFaces: {
styleString: toCssString(fontFaces),
styleObject: fontFaces,
}[fontFaceFormat],
};
}