/
subsetFonts.js
1272 lines (1119 loc) · 37.8 KB
/
subsetFonts.js
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const _ = require('lodash');
const url = require('url');
const Promise = require('bluebird');
const memoizeSync = require('memoizesync');
const urltools = require('urltools');
const compileQuery = require('../compileQuery');
const AssetGraph = require('../../');
const getTextByFontProperties = require('../util/fonts/getTextByFontProperties');
const getGoogleIdForFontProps = require('../util/fonts/getGoogleIdForFontProps');
const snapToAvailableFontProperties = require('../util/fonts/snapToAvailableFontProperties');
const findCustomPropertyDefinitions = require('../util/fonts/findCustomPropertyDefinitions');
const extractReferencedCustomPropertyNames = require('../util/fonts/extractReferencedCustomPropertyNames');
const stripLocalTokens = require('../util/fonts/stripLocalTokens');
const injectSubsetDefinitions = require('../util/fonts/injectSubsetDefinitions');
const cssFontParser = require('css-font-parser');
const cssListHelpers = require('css-list-helpers');
const LinesAndColumns = require('lines-and-columns').default;
const fontkit = require('fontkit');
const unquote = require('../util/fonts/unquote');
const normalizeFontPropertyValue = require('../util/fonts/normalizeFontPropertyValue');
const getCssRulesByProperty = require('../util/fonts/getCssRulesByProperty');
const unicodeRange = require('../util/fonts/unicode-range');
const googleFontsCssUrlRegex = /^(?:https?:)?\/\/fonts\.googleapis\.com\/css/;
const initialValueByProp = _.pick(require('../util/fonts/initialValueByProp'), [
'font-style',
'font-weight',
'font-stretch'
]);
function cssQuoteIfNecessary(value) {
if (/^\w+$/.test(value)) {
return value;
} else {
return `'${value.replace(/'/g, "\\'")}'`;
}
}
function getGoogleFontSubsetCssUrl(fontProps, text) {
const googleFontId = getGoogleIdForFontProps(fontProps);
return `https://fonts.googleapis.com/css?family=${googleFontId}&text=${encodeURIComponent(
text
)}`;
}
function getPreferredFontUrl(cssFontFaceSrcRelations = []) {
const formatOrder = ['woff2', 'woff', 'truetype', 'opentype'];
const typeOrder = ['Woff2', 'Woff', 'Ttf', 'Otf'];
for (const format of formatOrder) {
const relation = cssFontFaceSrcRelations.find(
r => r.format && r.format.toLowerCase() === format
);
if (relation) {
return relation.to.url;
}
}
for (const assetType of typeOrder) {
const relation = cssFontFaceSrcRelations.find(r => r.to.type === assetType);
if (relation) {
return relation.to.url;
}
}
}
// Takes the output of util/fonts/getTextByFontProperties
function groupTextsByFontFamilyProps(
textByPropsArray,
availableFontFaceDeclarations
) {
const snappedTexts = textByPropsArray
.map(textAndProps => {
const activeFontFaceDeclaration = snapToAvailableFontProperties(
availableFontFaceDeclarations,
textAndProps.props
);
if (!activeFontFaceDeclaration) {
return null;
}
const { relations, ...props } = activeFontFaceDeclaration;
const fontUrl = getPreferredFontUrl(relations);
return {
text: textAndProps.text,
props,
fontRelations: relations,
fontUrl
};
})
.filter(textByProps => textByProps && textByProps.fontUrl);
const textsByFontUrl = _.groupBy(snappedTexts, 'fontUrl');
return _.map(textsByFontUrl, (textsPropsArray, fontUrl) => {
const texts = textsPropsArray.map(obj => obj.text);
const fontFamilies = new Set(
textsPropsArray.map(obj => obj.props['font-family'])
);
const pageText = _.uniq(texts.join(''))
.sort()
.join('');
let smallestOriginalSize;
let smallestOriginalFormat;
for (const relation of textsPropsArray[0].fontRelations) {
if (relation.to.isLoaded) {
const size = relation.to.rawSrc.length;
if (smallestOriginalSize === undefined || size < smallestOriginalSize) {
smallestOriginalSize = size;
smallestOriginalFormat = relation.to.type.toLowerCase();
}
}
}
return {
smallestOriginalSize,
smallestOriginalFormat,
texts,
pageText,
text: pageText,
props: { ...textsPropsArray[0].props },
fontUrl,
fontFamilies
};
});
}
function getParents(assetGraph, asset, assetQuery) {
const assetMatcher = compileQuery(assetQuery);
const seenAssets = new Set();
const parents = [];
(function visit(asset) {
if (seenAssets.has(asset)) {
return;
}
seenAssets.add(asset);
for (const incomingRelation of asset.incomingRelations) {
if (assetMatcher(incomingRelation.from)) {
parents.push(incomingRelation.from);
} else {
visit(incomingRelation.from);
}
}
})(asset);
return parents;
}
function asyncLoadStyleRelationWithFallback(
htmlAsset,
originalRelation,
insertPoint
) {
const injectionPointRelation = insertPoint || htmlAsset.outgoingRelations[0];
// Resource hint: prefetch google font stylesheet
const fontDomainPreconnect = htmlAsset.addRelation(
{
type: 'HtmlPreconnectLink',
hrefType: 'absolute',
to: { url: 'https://fonts.gstatic.com' }
},
'after',
injectionPointRelation
);
// Resource hint: prefetch google font stylesheet
const parsedOriginalUrl = url.parse(originalRelation.to.url);
htmlAsset.addRelation(
{
type: 'HtmlPreconnectLink',
hrefType: 'absolute',
to: { url: `https://${parsedOriginalUrl.host}` }
},
'before',
fontDomainPreconnect
);
// Async load google font stylesheet
// Insert async CSS loading <script>
const asyncCssLoadingRelation = htmlAsset.addRelation(
{
type: 'HtmlScript',
hrefType: 'inline',
to: {
type: 'JavaScript',
text: `
(function () {
var el = document.createElement('link');
el.href = '${originalRelation.to.url}'.toString('url');
el.rel = 'stylesheet';
${
originalRelation.media
? `el.media = '${originalRelation.media}';`
: ''
}
document.body.appendChild(el);
}())
`
}
},
'lastInBody'
);
// Insert <noscript> fallback sync CSS loading
const noScriptFallbackRelation = htmlAsset.addRelation(
{
type: 'HtmlNoscript',
to: {
type: 'Html',
text: ''
}
},
'lastInBody'
);
noScriptFallbackRelation.to.addRelation(
{
type: 'HtmlStyle',
media: originalRelation.media,
to: originalRelation.to
},
'last'
);
noScriptFallbackRelation.inline();
// Clean up
originalRelation.detach();
asyncCssLoadingRelation.to.minify();
htmlAsset.markDirty();
}
function getSubsetPromiseId(fontUsage, format) {
return [fontUsage.text, fontUsage.fontUrl, format].join('\x1d');
}
async function getSubsetsForFontUsage(
assetGraph,
htmlAssetTextsWithProps,
formats
) {
let subsetLocalFont;
try {
subsetLocalFont = require('../util/fonts/subsetLocalFont');
} catch (err) {
assetGraph.info(
new Error(
'Local subsetting is not possible because fonttools are not installed. Falling back to only subsetting Google Fonts. Run `pip install fonttools brotli zopfli` to enable local font subsetting'
)
);
}
const allFonts = [];
for (const item of htmlAssetTextsWithProps) {
for (const fontUsage of item.fontUsages) {
if (!fontUsage.fontUrl) {
continue;
}
if (!allFonts.includes(fontUsage.fontUrl)) {
allFonts.push(fontUsage.fontUrl);
}
}
}
if (subsetLocalFont) {
await assetGraph.populate({
followRelations: {
to: { url: { $or: allFonts } }
}
});
const originalFontBuffers = allFonts.reduce((result, fontUrl) => {
const fontAsset = assetGraph.findAssets({
url: fontUrl,
isLoaded: true
})[0];
if (fontAsset) {
result[fontUrl] = fontAsset.rawSrc;
}
return result;
}, {});
const subsetPromiseMap = {};
for (const item of htmlAssetTextsWithProps) {
for (const fontUsage of item.fontUsages) {
const fontBuffer = originalFontBuffers[fontUsage.fontUrl];
const text = fontUsage.text;
for (const format of formats) {
const promiseId = getSubsetPromiseId(fontUsage, format);
if (!subsetPromiseMap[promiseId]) {
subsetPromiseMap[promiseId] = subsetLocalFont(
fontBuffer,
format,
text
).catch(err => {
const error = new Error(err.message);
error.asset = assetGraph.findAssets({
url: fontUsage.fontUrl
})[0];
assetGraph.warn(error);
});
}
subsetPromiseMap[promiseId].then(fontBuffer => {
if (fontBuffer) {
if (!fontUsage.subsets) {
fontUsage.subsets = {};
}
fontUsage.subsets[format] = fontBuffer;
const size = fontBuffer.length;
if (
!fontUsage.smallestSubsetSize ||
size < fontUsage.smallestSubsetSize
) {
fontUsage.smallestSubsetSize = size;
fontUsage.smallestSubsetFormat = format;
}
}
});
}
}
}
await Promise.all(Object.values(subsetPromiseMap));
} else {
const fontCssUrlMap = {};
for (const item of htmlAssetTextsWithProps) {
for (const fontUsage of item.fontUsages) {
if (!fontUsage.fontUrl) {
continue;
}
const fontAsset = assetGraph.findAssets({ url: fontUsage.fontUrl })[0];
if (fontAsset.hostname !== 'fonts.gstatic.com') {
continue;
}
for (const format of formats) {
const mapId = getSubsetPromiseId(fontUsage, format);
if (!fontCssUrlMap[mapId]) {
fontCssUrlMap[mapId] = `${getGoogleFontSubsetCssUrl(
fontUsage.props,
fontUsage.text
)}&format=${format}`;
}
}
}
}
const assetGraphForLoadingFonts = new AssetGraph();
for (const format of formats) {
assetGraphForLoadingFonts.teepee.headers['User-Agent'] =
fontFormatUA[format];
const formatUrls = _.uniq(
Object.values(fontCssUrlMap).filter(url =>
url.endsWith(`format=${format}`)
)
);
await assetGraphForLoadingFonts.loadAssets(Object.values(formatUrls));
}
await assetGraphForLoadingFonts.populate({
followRelations: {
type: 'CssFontFaceSrc'
}
});
for (const item of htmlAssetTextsWithProps) {
for (const fontUsage of item.fontUsages) {
for (const format of formats) {
const cssUrl = fontCssUrlMap[getSubsetPromiseId(fontUsage, format)];
const cssAsset = assetGraphForLoadingFonts.findAssets({
url: cssUrl,
isLoaded: true
})[0];
if (cssAsset) {
const fontRelation = cssAsset.outgoingRelations[0];
const fontAsset = fontRelation.to;
if (fontAsset.isLoaded) {
if (!fontUsage.subsets) {
fontUsage.subsets = {};
}
fontUsage.subsets[format] = fontAsset.rawSrc;
}
}
}
}
}
}
}
const fontContentTypeMap = {
woff: 'font/woff', // https://tools.ietf.org/html/rfc8081#section-4.4.5
woff2: 'font/woff2'
};
const fontOrder = ['woff2', 'woff'];
const getFontFaceForFontUsage = memoizeSync(
(assetGraph, fontUsage) => {
const subsets = fontOrder
.filter(format => fontUsage.subsets[format])
.map(format => {
const fontAsset = assetGraph.addAsset({
contentType: fontContentTypeMap[format],
rawSrc: fontUsage.subsets[format]
});
const extension = fontAsset.contentType.split('/').pop();
const nameProps = ['font-family', 'font-weight', 'font-style'].map(
prop => fontUsage.props[prop]
);
const fileNamePreFix = `${unquote(nameProps[0])
.replace(/__subset$/, '')
.replace(/ /g, '_')}-${normalizeFontPropertyValue(
'font-weight',
nameProps[1]
)}${nameProps[2] === 'italic' ? 'i' : ''}`;
const fontFileName = `${fileNamePreFix}-${fontAsset.md5Hex.slice(
0,
10
)}.${extension}`;
fontAsset.fileName = fontFileName;
return {
format,
font: fontAsset,
url: `data:${fontContentTypeMap[format]};base64,`
};
});
const src = subsets
.map(subset => `url(${subset.font.fileName}) format(${subset.format})`)
.join(', ');
const {
'font-family': family,
'font-weight': weight,
'font-style': style,
'font-stretch': stretch,
'font-display': display
} = fontUsage.props;
const cssText = `@font-face {
font-family: ${cssQuoteIfNecessary(`${family}__subset`)};
font-weight: ${weight};
font-style: ${style};
font-stretch: ${stretch};
font-display: ${display || 'auto'};
src: ${src};
unicode-range: ${unicodeRange(fontUsage.codepoints.used)};
}`;
return cssText;
},
{
argumentsStringifier: args => {
return [args[1].text, args[1].props]
.map(arg => JSON.stringify(arg))
.join('\x1d');
}
}
);
function getFontUsageStylesheet(
assetGraph,
fontUsages,
accumulatedFontFaceDeclarations
) {
// Find the available @font-face declarations where the font-family is used
// (so there will be subsets created), but the specific variant isn't used.
const unusedFontFaceDeclarations = accumulatedFontFaceDeclarations.filter(
decl =>
fontUsages.some(fontUsage =>
fontUsage.fontFamilies.has(decl['font-family'])
) &&
!fontUsages.some(
({ props }) =>
props['font-style'] === decl['font-style'] &&
props['font-weight'] === decl['font-weight'] &&
props['font-stretch'] === decl['font-stretch'] &&
props['font-family'].toLowerCase() ===
decl['font-family'].toLowerCase()
)
);
return fontUsages
.filter(fontUsage => fontUsage.subsets)
.map(fontUsage => getFontFaceForFontUsage(assetGraph, fontUsage))
.concat(
unusedFontFaceDeclarations.map(props => {
let src = stripLocalTokens(props.src);
if (props.relations.length > 0) {
const targets = props.relations.map(relation => relation.to.url);
src = src.replace(
props.relations[0].tokenRegExp,
() => `url('${targets.shift().replace(/'/g, "\\'")}')`
);
}
return `@font-face{font-family:${
props['font-family']
}__subset;font-stretch:${props['font-stretch']};font-style:${
props['font-style']
};font-weight:${props['font-weight']};src:${src}}`;
})
)
.join('\n\n');
}
const fontFormatUA = {
woff:
'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0',
woff2:
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36'
};
const validFontDisplayValues = [
'auto',
'block',
'swap',
'fallback',
'optional'
];
module.exports = ({
formats = ['woff2', 'woff'],
subsetPath = 'subfont/',
subsetPerPage,
inlineSubsets,
inlineCss,
fontDisplay
} = {}) => {
if (!validFontDisplayValues.includes(fontDisplay)) {
fontDisplay = undefined;
}
return async function subsetFonts(assetGraph) {
const htmlAssetTextsWithProps = [];
const subsetUrl = urltools.ensureTrailingSlash(
assetGraph.root + subsetPath
);
await assetGraph.populate({
followRelations: {
$or: [
{
to: {
url: googleFontsCssUrlRegex
}
},
{
type: 'CssFontFaceSrc',
from: {
url: googleFontsCssUrlRegex
}
}
]
}
});
// Collect texts by page
const memoizedGetCssRulesByProperty = memoizeSync(getCssRulesByProperty);
const htmlAssets = assetGraph.findAssets({ type: 'Html', isInline: false });
const traversalRelationQuery = {
$or: [
{
type: { $in: ['HtmlStyle', 'CssImport'] }
},
{
to: {
type: 'Html',
isInline: true
}
}
]
};
// Keep track of the injected CSS assets that should eventually be minified
// Minifying them along the way currently doesn't work because some of the
// manipulation is sensitive to the exact text contents. We should fix that.
const subsetFontsToBeMinified = new Set();
for (const htmlAsset of htmlAssets) {
const accumulatedFontFaceDeclarations = [];
assetGraph.eachAssetPreOrder(htmlAsset, traversalRelationQuery, asset => {
if (asset.type === 'Css' && asset.isLoaded) {
const seenNodes = new Set();
const fontRelations = asset.outgoingRelations.filter(
relation => relation.type === 'CssFontFaceSrc'
);
for (const fontRelation of fontRelations) {
const node = fontRelation.node;
if (!seenNodes.has(node)) {
seenNodes.add(node);
const fontFaceDeclaration = {
relations: fontRelations.filter(r => r.node === node)
};
for (const prop of Object.keys(initialValueByProp)) {
fontFaceDeclaration[prop] = normalizeFontPropertyValue(
prop,
initialValueByProp[prop]
);
}
node.walkDecls(declaration => {
const propName = declaration.prop.toLowerCase();
fontFaceDeclaration[propName] = normalizeFontPropertyValue(
propName,
declaration.value
);
});
accumulatedFontFaceDeclarations.push(fontFaceDeclaration);
}
}
}
});
if (accumulatedFontFaceDeclarations.length > 0) {
const seenFontFaceCombos = new Set();
for (const fontFace of accumulatedFontFaceDeclarations) {
const key = `${fontFace['font-family']}/${fontFace['font-style']}/${
fontFace['font-weight']
}`;
if (seenFontFaceCombos.has(key)) {
throw new Error(
`Multiple @font-face with the same font-family/font-style/font-weight (maybe with different unicode-range?) is not supported yet: ${key}`
);
}
seenFontFaceCombos.add(key);
}
const textByProps = getTextByFontProperties(
htmlAsset,
memoizedGetCssRulesByProperty
);
htmlAssetTextsWithProps.push({
htmlAsset,
fontUsages: groupTextsByFontFamilyProps(
textByProps,
accumulatedFontFaceDeclarations
),
accumulatedFontFaceDeclarations
});
}
}
if (htmlAssetTextsWithProps.length <= 1) {
subsetPerPage = false;
}
if (!subsetPerPage) {
const globalFontUsage = {};
// Gather all texts
for (const htmlAssetTextWithProps of htmlAssetTextsWithProps) {
for (const fontUsage of htmlAssetTextWithProps.fontUsages) {
if (!globalFontUsage[fontUsage.fontUrl]) {
globalFontUsage[fontUsage.fontUrl] = [];
}
globalFontUsage[fontUsage.fontUrl].push(fontUsage.text);
}
}
// Merge subset values, unique glyphs, sort
for (const htmlAssetTextWithProps of htmlAssetTextsWithProps) {
for (const fontUsage of htmlAssetTextWithProps.fontUsages) {
fontUsage.text = _.uniq(globalFontUsage[fontUsage.fontUrl].join(''))
.sort()
.join('');
}
}
}
if (fontDisplay) {
for (const htmlAssetTextWithProps of htmlAssetTextsWithProps) {
for (const fontUsage of htmlAssetTextWithProps.fontUsages) {
fontUsage.props['font-display'] = fontDisplay;
}
}
}
// Generate codepoint sets for original font, the used subset and the unused subset
for (const htmlAssetTextWithProps of htmlAssetTextsWithProps) {
for (const fontUsage of htmlAssetTextWithProps.fontUsages) {
const originalFont = assetGraph.findAssets({
url: fontUsage.fontUrl
})[0];
if (originalFont.isLoaded) {
let originalCodepoints;
try {
// Guard against 'Unknown font format' errors
originalCodepoints = fontkit.create(originalFont.rawSrc)
.characterSet;
} catch (err) {}
if (originalCodepoints) {
const usedCodepoints = fontUsage.text
.split('')
.map(c => c.codePointAt(0));
const unusedCodepoints = originalCodepoints.filter(
n => !usedCodepoints.includes(n)
);
fontUsage.codepoints = {
original: originalCodepoints,
used: usedCodepoints,
unused: unusedCodepoints
};
}
}
}
}
// Generate subsets:
await getSubsetsForFontUsage(assetGraph, htmlAssetTextsWithProps, formats);
// Warn about missing glyphs
const missingGlyphsErrors = [];
for (const { htmlAsset, fontUsages } of htmlAssetTextsWithProps) {
for (const fontUsage of fontUsages) {
if (fontUsage.subsets) {
const characterSet = fontkit.create(fontUsage.subsets.woff)
.characterSet;
for (const char of [...fontUsage.pageText]) {
// Turns out that browsers don't mind that these are missing:
if (char === '\t' || char === '\n') {
continue;
}
const codePoint = char.codePointAt(0);
const isMissing = !characterSet.includes(codePoint);
if (isMissing) {
let location;
const charIdx = htmlAsset.text.indexOf(char);
if (charIdx === -1) {
location = `${htmlAsset.urlOrDescription} (generated content)`;
} else {
const position = new LinesAndColumns(
htmlAsset.text
).locationForIndex(charIdx);
location = `${htmlAsset.urlOrDescription}:${position.line +
1}:${position.column + 1}`;
}
missingGlyphsErrors.push({
codePoint,
char,
htmlAsset,
fontUsage,
location
});
}
}
}
}
}
if (missingGlyphsErrors.length) {
const errorLog = missingGlyphsErrors.map(
({ char, fontUsage, location }) =>
`- \\u{${char
.charCodeAt(0)
.toString(16)}} (${char}) in font-family '${
fontUsage.props['font-family']
}' (${fontUsage.props['font-weight']}/${
fontUsage.props['font-style']
}) at ${location}`
);
const message = `Missing glyph fallback detected.
When your primary webfont doesn't contain the glyphs you use, your browser will load your fallback fonts, which will be a potential waste of bandwidth.
These glyphs are used on your site, but they don't exist in the font you applied to them:`;
assetGraph.warn(new Error(`${message}\n${errorLog.join('\n')}`));
}
// Insert subsets:
for (const {
htmlAsset,
fontUsages,
accumulatedFontFaceDeclarations
} of htmlAssetTextsWithProps) {
const insertionPoint = assetGraph.findRelations({
type: 'HtmlStyle',
from: htmlAsset
})[0];
const subsetFontUsages = fontUsages.filter(
fontUsage => fontUsage.subsets
);
const unsubsettedFontUsages = fontUsages.filter(
fontUsage => !subsetFontUsages.includes(fontUsage)
);
// Remove all existing preload hints to fonts that might have new subsets
for (const fontUsage of fontUsages) {
for (const relation of assetGraph.findRelations({
type: { $or: ['HtmlPrefetchLink', 'HtmlPreloadLink'] },
from: htmlAsset,
to: {
url: fontUsage.fontUrl
}
})) {
if (relation.type === 'HtmlPrefetchLink') {
const err = new Error(
`Detached ${
relation.node.outerHTML
}. Will be replaced with preload with JS fallback.\nIf you feel this is wrong, open an issue at https://github.com/assetgraph/assetgraph/issues`
);
err.asset = relation.from;
err.relation = relation;
assetGraph.info(err);
}
relation.detach();
}
}
if (unsubsettedFontUsages.length > 0) {
// Insert <link rel="preload">
const preloadRelations = unsubsettedFontUsages.map(fontUsage => {
// Always preload unsubsetted font files, they might be any format, so can't be clever here
return htmlAsset.addRelation(
{
type: 'HtmlPreloadLink',
hrefType: 'rootRelative',
to: fontUsage.fontUrl,
as: 'font'
},
'before',
insertionPoint
);
});
// Generate JS fallback for browser that don't support <link rel="preload">
const preloadData = unsubsettedFontUsages.map((fontUsage, idx) => {
const preloadRelation = preloadRelations[idx];
const formatMap = {
'.woff': 'woff',
'.woff2': 'woff2',
'.ttf': 'truetype',
'.svg': 'svg',
'.eot': 'embedded-opentype'
};
const name = fontUsage.props['font-family'];
const props = Object.keys(initialValueByProp).reduce(
(result, prop) => {
if (
fontUsage.props[prop] !==
normalizeFontPropertyValue(prop, initialValueByProp[prop])
) {
result[prop] = fontUsage.props[prop];
}
return result;
},
{}
);
return `new FontFace(
"${name}",
"url('" + "${preloadRelation.href}".toString('url') + "') format('${
formatMap[preloadRelation.to.extension]
}')",
${JSON.stringify(props)}
).load();`;
});
const originalFontJsPreloadAsset = htmlAsset.addRelation(
{
type: 'HtmlScript',
hrefType: 'inline',
to: {
type: 'JavaScript',
text: `try{${preloadData.join('')}}catch(e){}`
}
},
'before',
insertionPoint
).to;
for (const [
idx,
relation
] of originalFontJsPreloadAsset.outgoingRelations.entries()) {
relation.hrefType = 'rootRelative';
relation.to = preloadRelations[idx].to;
relation.refreshHref();
}
originalFontJsPreloadAsset.minify();
}
if (subsetFontUsages.length < 1) {
return { fontInfo: [] };
}
const subsetCssText = getFontUsageStylesheet(
assetGraph,
subsetFontUsages,
accumulatedFontFaceDeclarations
);
let cssAsset = assetGraph.addAsset({
type: 'Css',
url: `${subsetUrl}subfontTemp.css`,
text: subsetCssText
});
for (const fontRelation of cssAsset.outgoingRelations) {
const fontAsset = fontRelation.to;
fontAsset.path = subsetPath;
if (inlineSubsets) {
fontRelation.inline();
} else {
if (inlineCss) {
fontRelation.hrefType = 'rootRelative';
} else {
fontRelation.hrefType = 'relative';
}
if (fontAsset.contentType === 'font/woff2') {
// Only <link rel="preload"> for woff2 files
// Preload support is a subset of woff2 support:
// - https://caniuse.com/#search=woff2
// - https://caniuse.com/#search=preload
htmlAsset.addRelation(
{
type: 'HtmlPreloadLink',
hrefType: 'rootRelative',
to: fontAsset,
as: 'font'
},
'before',
insertionPoint
);
}
}
}
const cssFileName = `fonts-${cssAsset.md5Hex.slice(0, 10)}.css`;
const cssUrl = subsetUrl + cssFileName;
const [identicalAsset] = assetGraph.findAssets({ url: cssUrl });
if (identicalAsset) {
assetGraph.removeAsset(cssAsset);
cssAsset = identicalAsset;
}
subsetFontsToBeMinified.add(cssAsset);
cssAsset.url = cssUrl;
const cssRelation = htmlAsset.addRelation(
{
type: 'HtmlStyle',