Source: FontManager.js

FontManager.js

//-----------------------------------------------------------------------------
// FontManager
//
// The static class that loads font files.
/**
 * The static class that loads font files.
 *
 * @namespace
 */
function FontManager() {
    throw new Error("This is a static class");
}

FontManager._urls = {};
FontManager._states = {};

/**
 * Loads the given font family from the given filename
 *
 * @static
 * @param {string} family - The name of the font family to load
 * @param {string} filename - The name of the filename to load from
 */
FontManager.load = function(family, filename) {
    if (this._states[family] !== "loaded") {
        if (filename) {
            const url = this.makeUrl(filename);
            this.startLoading(family, url);
        } else {
            this._urls[family] = "";
            this._states[family] = "loaded";
        }
    }
};

/**
 * Loads the given font family from the given filename
 *
 * @static
 * @return {boolean} Whether all fonts are done loading
 */
FontManager.isReady = function() {
    for (const family in this._states) {
        const state = this._states[family];
        if (state === "loading") {
            return false;
        }
        if (state === "error") {
            this.throwLoadError(family);
        }
    }
    return true;
};

/**
 * Start the load process for the font family at the given url
 *
 * @static
 * @param {string} family - The name of the font family to start loading
 * @param {string} url - Full url of the font file, including folder + filename + extension
 */
FontManager.startLoading = function(family, url) {
    const source = "url(" + url + ")";
    const font = new FontFace(family, source);
    this._urls[family] = url;
    this._states[family] = "loading";
    font.load()
        .then(() => {
            document.fonts.add(font);
            this._states[family] = "loaded";
            return 0;
        })
        .catch(() => {
            this._states[family] = "error";
        });
};

/**
 * Throws a retry screen error if a font could not be loaded
 *
 * @static
 * @param {string} family - The font family that caused the error
 * @throws A retry screen error
 */
FontManager.throwLoadError = function(family) {
    const url = this._urls[family];
    const retry = () => this.startLoading(family, url);
    throw ["LoadError", url, retry];
};

/**
 * Makes a full url from filename with extension
 *
 * @static
 * @param {string} filename - The name of the font file
 * @return {string} Full url including folder + filename + extension
 */
FontManager.makeUrl = function(filename) {
    return "fonts/" + Utils.encodeURI(filename);
};