MCPcopy
hub / github.com/qq15725/modern-screenshot / embedWebFont

Function embedWebFont

src/embed-web-font.ts:6–120  ·  view source on GitHub ↗
(
  clone: T,
  context: Context,
)

Source from the content-addressed store, hash-verified

4import { isCssFontFaceRule, isCSSImportRule, isLayerBlockRule, resolveUrl, splitFontFamily } from './utils'
5
6export async function embedWebFont<T extends Element>(
7 clone: T,
8 context: Context,
9): Promise<void> {
10 const {
11 ownerDocument,
12 svgStyleElement,
13 fontFamilies,
14 fontCssTexts,
15 tasks,
16 font,
17 } = context
18
19 if (
20 !ownerDocument
21 || !svgStyleElement
22 || !fontFamilies.size
23 ) {
24 return
25 }
26
27 if (font && font.cssText) {
28 const cssText = filterPreferredFormat(font.cssText, context)
29 svgStyleElement.appendChild(ownerDocument.createTextNode(`${cssText}\n`))
30 }
31 else {
32 const styleSheets = Array.from(ownerDocument.styleSheets).filter((styleSheet) => {
33 try {
34 return 'cssRules' in styleSheet && Boolean(styleSheet.cssRules.length)
35 }
36 catch (error) {
37 context.log.warn(`Error while reading CSS rules from ${styleSheet.href}`, error)
38 return false
39 }
40 })
41
42 // Collect rules from @import declarations into a detached stylesheet
43 // to avoid mutating the live document's stylesheets via insertRule().
44 const tempDoc = ownerDocument.implementation.createHTMLDocument('')
45 const tempStyleEl = tempDoc.createElement('style')
46 tempDoc.head.appendChild(tempStyleEl)
47 const tempStyleSheet = tempStyleEl.sheet!
48
49 await Promise.all(
50 styleSheets.flatMap((styleSheet) => {
51 return Array.from(styleSheet.cssRules).map(async (cssRule) => {
52 if (isCSSImportRule(cssRule)) {
53 const baseUrl = cssRule.href
54 let cssText = ''
55 try {
56 cssText = await contextFetch(context, {
57 url: baseUrl,
58 requestType: 'text',
59 responseType: 'text',
60 })
61 }
62 catch (error) {
63 context.log.warn(`Error fetch remote css import from ${baseUrl}`, error)

Callers 1

domToForeignObjectSvgFunction · 0.90

Calls 10

isCSSImportRuleFunction · 0.90
contextFetchFunction · 0.90
resolveUrlFunction · 0.90
isCssFontFaceRuleFunction · 0.90
hasCssUrlFunction · 0.90
splitFontFamilyFunction · 0.90
replaceCssUrlToDataUrlFunction · 0.90
filterPreferredFormatFunction · 0.85
parseCssFunction · 0.85
unwrapCssLayersFunction · 0.85

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…