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