UNPKG

1.92 kBJavaScriptView Raw
1import { FONT_FORMATS, FontFormat } from '.';
2/* below from https://gist.github.com/viljamis/c4016ff88745a0846b94 */
3const CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
4export function base64Encode(str) {
5 let out = '';
6 let i = 0;
7 let len = str.length;
8 let c1;
9 let c2;
10 let c3;
11 // tslint:disable
12 while (i < len) {
13 c1 = str.charCodeAt(i++) & 0xff;
14 if (i === len) {
15 out += CHARS.charAt(c1 >> 2);
16 out += CHARS.charAt((c1 & 0x3) << 4);
17 out += '==';
18 break;
19 }
20 c2 = str.charCodeAt(i++);
21 if (i === len) {
22 out += CHARS.charAt(c1 >> 2);
23 out += CHARS.charAt(((c1 & 0x3) << 4) | ((c2 & 0xf0) >> 4));
24 out += CHARS.charAt((c2 & 0xf) << 2);
25 out += '=';
26 break;
27 }
28 c3 = str.charCodeAt(i++);
29 out += CHARS.charAt(c1 >> 2);
30 out += CHARS.charAt(((c1 & 0x3) << 4) | ((c2 & 0xf0) >> 4));
31 out += CHARS.charAt(((c2 & 0xf) << 2) | ((c3 & 0xc0) >> 6));
32 out += CHARS.charAt(c3 & 0x3f);
33 }
34 // tslint:enable
35 return out;
36}
37export async function dataURISrc(url, format = FontFormat.woff2) {
38 const pre = `data:${FONT_FORMATS[format]};charset=utf-8;base64`;
39 const base64Font = base64Encode(await getBinary(url));
40 const post = `format('${format}')`;
41 const src = `url('${pre},${base64Font}') ${post}`;
42 return src;
43}
44export function getBinary(url) {
45 return new Promise((resolve, reject) => {
46 const xhr = new XMLHttpRequest();
47 xhr.open('GET', url, true);
48 xhr.overrideMimeType('text/plain; charset=x-user-defined');
49 xhr.onreadystatechange = () => {
50 if (xhr.readyState === 4 && xhr.status === 200) {
51 resolve(xhr.responseText);
52 }
53 };
54 xhr.send();
55 });
56}
57//# sourceMappingURL=util.js.map
\No newline at end of file