-
Notifications
You must be signed in to change notification settings - Fork 2
/
glytter.js
96 lines (85 loc) · 2.98 KB
/
glytter.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// TODO: Add drag and drop?
// TODO: Make select menu for Google fonts?
//
// Thanks to Adam Twardoch (http://www.twardoch.com/) and Christian Genco (https://christian.gen.co/)
// For their tips on getting fontkit to work in the browser:
// https://github.com/foliojs/fontkit/issues/41
// https://github.com/foliojs/fontkit/issues/77
//
(function () {
const root = document.documentElement; // <html> element
const $fontfam = document.getElementById("fontfam");
const $charmap = document.getElementById("charmap");
function dir(m) {
if (console.dir && m) {
console.dir(m);
}
}
function log(m) {
if (console.log) {
m = m !== undefined ? m : "-----------------";
console.log(m);
}
}
function displayFontInfo(name, text) {
$fontfam.innerHTML = name;
$charmap.innerHTML = text;
}
function parseFontFile() {
const input = document.getElementById("fontinput");
const filename = input.files[0].name;
const reader = new FileReader();
reader.readAsArrayBuffer(input.files[0]);
reader.onload = function () {
let outputName = "";
let outputText = "";
let i = 0;
try {
const arrayBuffer = reader.result;
const fontkitBuffer = new Buffer(arrayBuffer);
const font = fontkit.create(fontkitBuffer);
const fontFace = new FontFace("TempFont", arrayBuffer);
fontFace.load().then(function (loadedFont) {
document.fonts.add(loadedFont);
root.style.setProperty("--font-family", "TempFont, AdobeBlank");
});
outputName = font.familyName;
while (i < font.characterSet.length) {
outputText = outputText.concat("&#" + font.characterSet[i] + "; ");
i++;
}
} catch (e) {
outputName = "None";
outputText = `Sorry. I couldn't read <strong>${filename}</strong>. `
+ `If you submitted a valid font, maybe it was in a `
+ `format this app doesn't understand (e.g., .eot).`;
root.style.setProperty("--font-family", "Firava");
log(e);
} finally {
displayFontInfo(outputName, outputText);
}
};
}
function loadDefaultFont() {
const fontPath = "fonts/Firava.woff2";
fetch(fontPath).then((response) => response.arrayBuffer()).then((arrayBuffer) => {
const font = fontkit.create(new Buffer(arrayBuffer));
let outputName = font.familyName;
let outputText = "";
const charSet = font.characterSet;
let i = 0;
while (i < charSet.length) {
outputText = outputText.concat("&#" + charSet[i] + "; ");
i++;
}
displayFontInfo(outputName, outputText);
});
}
function listenForFontChooser() {
document.getElementById("fontinput").addEventListener("change", parseFontFile, false);
}
window.addEventListener("DOMContentLoaded", function () {
loadDefaultFont();
listenForFontChooser();
});
}());