|
| 1 | +// font parsing based on https://github.com/tsayen/dom-to-image |
| 2 | +import { parse } from 'opentype.js'; |
| 3 | +// eslint is bullshitting here. woff2-encoder/decompress is valid (see https://github.com/itskyedo/woff2-encoder) |
| 4 | +// eslint-disable-next-line import/no-unresolved |
| 5 | +import decompress from 'woff2-encoder/decompress'; |
| 6 | + |
| 7 | +// will download and fetch fonts that are loaded, usable for drawing! |
| 8 | +const URL_REGEX = /url\(['"]?([^'"]+?)['"]?\)/g |
| 9 | + |
| 10 | +export class FontRepo { |
| 11 | + |
| 12 | + |
| 13 | + constructor() { |
| 14 | + this.fonts = {} |
| 15 | + } |
| 16 | + |
| 17 | + |
| 18 | + |
| 19 | + async refresh() { |
| 20 | + // this can only run on the client! |
| 21 | + if (typeof document === 'undefined') { |
| 22 | + return |
| 23 | + } |
| 24 | + |
| 25 | + |
| 26 | + const stylesheets = Array.from(document.styleSheets) |
| 27 | + |
| 28 | + const fontData = [] |
| 29 | + // fetch all the fonts |
| 30 | + for (const sheet of stylesheets) { |
| 31 | + try { |
| 32 | + const rules = sheet.cssRules |
| 33 | + for (const rule of rules) { |
| 34 | + if (rule.constructor.name == 'CSSFontFaceRule' && rule.style.getPropertyValue('src').includes('url')) { |
| 35 | + const font = rule.style.getPropertyValue('font-family').toLowerCase().replace(/['"]/g, '') |
| 36 | + |
| 37 | + // check the global font repo if we already have this font |
| 38 | + if (this.fonts[font] !== undefined) { |
| 39 | + continue |
| 40 | + } |
| 41 | + |
| 42 | + const src = rule.style.getPropertyValue('src') |
| 43 | + const regexResult = src.match(URL_REGEX) |
| 44 | + if (regexResult == undefined) { |
| 45 | + continue; |
| 46 | + } |
| 47 | + const url = src.match(URL_REGEX)[0].replace(URL_REGEX, '$1') |
| 48 | + // TODO: dom-to-image has a edge case where the stylesheet has a different url or somehting? check there if this blows up |
| 49 | + fontData.push({ font, url }) |
| 50 | + } |
| 51 | + } |
| 52 | + } catch (e) { |
| 53 | + //console.error(e) |
| 54 | + // not all the css rules can be read and this is fine! |
| 55 | + // (it's not that important, as long as we get the fonts we don't care) |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + |
| 60 | + const uInt8FontData = await Promise.all(fontData.map(async ({ font, url }) => { |
| 61 | + // if it is a data url, just convert to a Uint8Array |
| 62 | + if (url.startsWith('data:')) { |
| 63 | + const base64 = url.split(',')[1] |
| 64 | + const binary = atob(base64) |
| 65 | + const bytes = new Uint8Array(binary.length) |
| 66 | + for (let i = 0; i < binary.length; i++) { |
| 67 | + bytes[i] = binary.charCodeAt(i) |
| 68 | + } |
| 69 | + return { font, data: bytes } |
| 70 | + } |
| 71 | + |
| 72 | + // if it is a url, fetch it |
| 73 | + const response = await fetch(url) |
| 74 | + const blob = await response.blob() |
| 75 | + const buffer = await blob.arrayBuffer() |
| 76 | + return { font, data: new Uint8Array(buffer) } |
| 77 | + })) |
| 78 | + const toAddFonts = await Promise.all(uInt8FontData.map(async ({ font, data }) => { |
| 79 | + const format = FontRepo.detectFontFormat(data); |
| 80 | + let openTypeFont = null; |
| 81 | + try { |
| 82 | + if (format === 'WOFF2') { |
| 83 | + const decompressed = await decompress(data); |
| 84 | + openTypeFont = parse(decompressed.buffer); |
| 85 | + } else if (format !== null) { |
| 86 | + openTypeFont = parse(data.buffer) |
| 87 | + } |
| 88 | + } catch (e) { |
| 89 | + //console.error('Failed to parse font', font, e) |
| 90 | + } |
| 91 | + |
| 92 | + return { font, openTypeFont } |
| 93 | + })) |
| 94 | + |
| 95 | + toAddFonts.forEach(({ font, openTypeFont }) => { |
| 96 | + if (openTypeFont === null) { |
| 97 | + return; |
| 98 | + } |
| 99 | + this.fonts[font] = openTypeFont |
| 100 | + }) |
| 101 | + //console.log(this.fonts); |
| 102 | + } |
| 103 | + |
| 104 | + static detectFontFormat(uint8Array) { |
| 105 | + |
| 106 | + const first4BytesHex = Array.from(uint8Array.slice(0, 4)) // Extract first 4 bytes |
| 107 | + .map(byte => byte.toString(16).padStart(2, '0')) // Convert to hex, pad to 2 digits |
| 108 | + .join(''); // Combine into a single string |
| 109 | + |
| 110 | + switch (first4BytesHex) { |
| 111 | + case '774f4632': // WOFF2 |
| 112 | + return 'WOFF2'; |
| 113 | + case '774f4646': // WOFF |
| 114 | + return 'WOFF'; |
| 115 | + case '00010000': // TTF |
| 116 | + case '4f54544f': // OTF |
| 117 | + return 'TTF/OTF'; |
| 118 | + default: |
| 119 | + throw new Error(`Unknown font format: ${first4BytesHex}`); |
| 120 | + } |
| 121 | + } |
| 122 | + |
| 123 | + getFont(fontFamily) { |
| 124 | + // split the font family by comma and go through each font, if we have it, return it else zero |
| 125 | + const fonts = fontFamily.split(',').map(font => font.trim().toLowerCase()).map(font => font.replace(/['"]/g, '').toLowerCase()) |
| 126 | + for (const font of fonts) { |
| 127 | + if (this.fonts[font] !== undefined) { |
| 128 | + return this.fonts[font] |
| 129 | + } |
| 130 | + } |
| 131 | + return null |
| 132 | + } |
| 133 | + |
| 134 | +} |
| 135 | + |
0 commit comments