|
| 1 | +import FileStorage from "../../utils/file-storage"; |
| 2 | +import * as Notifications from "../notifications"; |
| 3 | +import { applyFontFamily } from "../../controllers/theme-controller"; |
| 4 | + |
| 5 | +const parentEl = document.querySelector( |
| 6 | + ".pageSettings .section[data-config-name='fontFamily']" |
| 7 | +); |
| 8 | +const usingLocalFontEl = parentEl?.querySelector(".usingLocalFont"); |
| 9 | +const separatorEl = parentEl?.querySelector(".separator"); |
| 10 | +const uploadContainerEl = parentEl?.querySelector(".uploadContainer"); |
| 11 | +const inputAndButtonEl = parentEl?.querySelector(".buttons"); |
| 12 | + |
| 13 | +async function readFileAsDataURL(file: File): Promise<string> { |
| 14 | + return new Promise((resolve, reject) => { |
| 15 | + const reader = new FileReader(); |
| 16 | + reader.onload = () => resolve(reader.result as string); |
| 17 | + reader.onerror = reject; |
| 18 | + reader.readAsDataURL(file); |
| 19 | + }); |
| 20 | +} |
| 21 | + |
| 22 | +export async function updateUI(): Promise<void> { |
| 23 | + if (await FileStorage.hasFile("LocalFontFamilyFile")) { |
| 24 | + usingLocalFontEl?.classList.remove("hidden"); |
| 25 | + separatorEl?.classList.add("hidden"); |
| 26 | + uploadContainerEl?.classList.add("hidden"); |
| 27 | + inputAndButtonEl?.classList.add("hidden"); |
| 28 | + } else { |
| 29 | + usingLocalFontEl?.classList.add("hidden"); |
| 30 | + separatorEl?.classList.remove("hidden"); |
| 31 | + uploadContainerEl?.classList.remove("hidden"); |
| 32 | + inputAndButtonEl?.classList.remove("hidden"); |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +usingLocalFontEl |
| 37 | + ?.querySelector("button") |
| 38 | + ?.addEventListener("click", async () => { |
| 39 | + await FileStorage.deleteFile("LocalFontFamilyFile"); |
| 40 | + await updateUI(); |
| 41 | + await applyFontFamily(); |
| 42 | + }); |
| 43 | + |
| 44 | +uploadContainerEl |
| 45 | + ?.querySelector("input[type='file']") |
| 46 | + ?.addEventListener("change", async (e) => { |
| 47 | + const fileInput = e.target as HTMLInputElement; |
| 48 | + const file = fileInput.files?.[0]; |
| 49 | + |
| 50 | + if (!file) { |
| 51 | + return; |
| 52 | + } |
| 53 | + |
| 54 | + // check type |
| 55 | + if (!file.type.match(/font\/(woff|woff2|ttf|otf)/)) { |
| 56 | + Notifications.add( |
| 57 | + "Unsupported font format, must be woff, woff2, ttf or otf.", |
| 58 | + 0 |
| 59 | + ); |
| 60 | + fileInput.value = ""; |
| 61 | + return; |
| 62 | + } |
| 63 | + |
| 64 | + const dataUrl = await readFileAsDataURL(file); |
| 65 | + await FileStorage.storeFile("LocalFontFamilyFile", dataUrl); |
| 66 | + |
| 67 | + await updateUI(); |
| 68 | + await applyFontFamily(); |
| 69 | + |
| 70 | + fileInput.value = ""; |
| 71 | + }); |
0 commit comments