1 | import { batchProcessAllSourcesAsync, shouldProcess } from './ProcessSources.web';
|
2 | export async function batchResolveAllFontsAsync(element) {
|
3 | const fontCSSStyles = await findAllFontsForDocumentAsync();
|
4 | const styleNode = document.createElement('style');
|
5 | element.appendChild(styleNode);
|
6 | styleNode.appendChild(document.createTextNode(fontCSSStyles.join('\n')));
|
7 | return element;
|
8 | }
|
9 | async function findAllFontsForDocumentAsync() {
|
10 | const styleSheets = document.styleSheets;
|
11 | const sheets = Array.from(styleSheets);
|
12 | const cssRules = getCSSRules(sheets);
|
13 | const rulesToProcess = cssRules
|
14 | .filter(({ type }) => type === CSSRule.FONT_FACE_RULE)
|
15 | .filter(({ style }) => shouldProcess(style.getPropertyValue('src')));
|
16 | return await Promise.all(rulesToProcess.map(item => createNewFontForCSSRule(item)));
|
17 | }
|
18 | async function createNewFontForCSSRule({ parentStyleSheet, cssText, }) {
|
19 | let initialURL;
|
20 | if (parentStyleSheet && parentStyleSheet.href != null) {
|
21 | initialURL = parentStyleSheet.href;
|
22 | }
|
23 | return await batchProcessAllSourcesAsync(cssText, initialURL);
|
24 | }
|
25 | function getCSSRules(styleSheets) {
|
26 | const cssRules = [];
|
27 | for (const sheet of styleSheets) {
|
28 | try {
|
29 | const rules = Array.from(sheet.cssRules);
|
30 | cssRules.push(...rules);
|
31 | }
|
32 | catch ({ message }) {
|
33 | throw new Error(`Error while reading CSS rules from ${sheet.href}: ${message}`);
|
34 | }
|
35 | }
|
36 | return cssRules;
|
37 | }
|
38 |
|
\ | No newline at end of file |