From a45017ea7174df6739892f8b3b45ccd039e2909c Mon Sep 17 00:00:00 2001 From: Samuel Meuli Date: Wed, 29 May 2019 14:22:44 +0200 Subject: [PATCH] Add missing type annotations --- src/font-manager/FontManager.ts | 18 +++--- .../google-fonts/extractFontStyles.ts | 22 ++++---- src/font-manager/google-fonts/fontList.ts | 20 ++++--- .../google-fonts/fontStylesheet.ts | 8 ++- src/font-manager/loadFonts.ts | 36 +++++++----- src/font-manager/styles/declarations.ts | 4 +- src/font-manager/utils/request.ts | 36 ++++++------ src/font-picker/FontPicker.ts | 55 +++++++++++-------- 8 files changed, 112 insertions(+), 87 deletions(-) diff --git a/src/font-manager/FontManager.ts b/src/font-manager/FontManager.ts index 191eb5b..b8b0d23 100644 --- a/src/font-manager/FontManager.ts +++ b/src/font-manager/FontManager.ts @@ -44,7 +44,7 @@ export default class FontManager { variants = ["regular"], limit = 50, }: Options, - onChange: (font: Font) => void = () => {}, + onChange: (font: Font) => void = (): void => {}, ) { // Validate pickerId parameter validatePickerId(pickerId); @@ -90,9 +90,9 @@ export default class FontManager { // `categories` parameter: only keep fonts in categories from the provided array (this.options.categories.length === 0 || this.options.categories.includes(font.category)) && // `scripts` parameter: Only keep fonts which are available in all specified scripts - this.options.scripts.every((script: Script) => font.scripts.includes(script)) && + this.options.scripts.every((script: Script): boolean => font.scripts.includes(script)) && // `variants` parameter: Only keep fonts which contain all specified variants - this.options.variants.every((variant: Variant) => font.variants.includes(variant)) + this.options.variants.every((variant: Variant): boolean => font.variants.includes(variant)) ) { // Font fulfils all requirements: Add it to font map this.fonts.set(font.family, font); @@ -164,10 +164,12 @@ export default class FontManager { this.options.scripts, this.options.variants, this.selectorSuffix, - ).then(() => { - if (runOnChange) { - this.onChange(activeFont); - } - }); + ).then( + (): void => { + if (runOnChange) { + this.onChange(activeFont); + } + }, + ); } } diff --git a/src/font-manager/google-fonts/extractFontStyles.ts b/src/font-manager/google-fonts/extractFontStyles.ts index 0ba3bb7..89ffb18 100644 --- a/src/font-manager/google-fonts/extractFontStyles.ts +++ b/src/font-manager/google-fonts/extractFontStyles.ts @@ -14,16 +14,18 @@ export default function extractFontStyles(allFontStyles: string): Record = {}; - rules.forEach(rule => { - // Run regex to get font family - const fontFamily = getMatches(FONT_FAMILY_REGEX, rule)[0]; - const fontId = getFontId(fontFamily); + rules.forEach( + (rule): void => { + // Run regex to get font family + const fontFamily = getMatches(FONT_FAMILY_REGEX, rule)[0]; + const fontId = getFontId(fontFamily); - // Append rule to font font family's other rules - if (!(fontId in fontStyles)) { - fontStyles[fontId] = ""; - } - fontStyles[fontId] += `@font-face {\n${rule}\n}\n\n`; - }); + // Append rule to font font family's other rules + if (!(fontId in fontStyles)) { + fontStyles[fontId] = ""; + } + fontStyles[fontId] += `@font-face {\n${rule}\n}\n\n`; + }, + ); return fontStyles; } diff --git a/src/font-manager/google-fonts/fontList.ts b/src/font-manager/google-fonts/fontList.ts index afff90a..06cda9a 100644 --- a/src/font-manager/google-fonts/fontList.ts +++ b/src/font-manager/google-fonts/fontList.ts @@ -28,13 +28,15 @@ export default async function getFontList(apiKey: string): Promise { // - Generate fontId // Return the updated list const fontsOriginal = json.items; - return fontsOriginal.map((fontOriginal: FontResponse) => { - const { family, subsets, ...others } = fontOriginal; - return { - ...others, - family, - id: getFontId(family), - scripts: subsets, - }; - }); + return fontsOriginal.map( + (fontOriginal: FontResponse): Font => { + const { family, subsets, ...others } = fontOriginal; + return { + ...others, + family, + id: getFontId(family), + scripts: subsets, + }; + }, + ); } diff --git a/src/font-manager/google-fonts/fontStylesheet.ts b/src/font-manager/google-fonts/fontStylesheet.ts index c24477e..6e8ae0b 100644 --- a/src/font-manager/google-fonts/fontStylesheet.ts +++ b/src/font-manager/google-fonts/fontStylesheet.ts @@ -16,7 +16,9 @@ export default async function getStylesheet( ): Promise { // Build query URL for specified font families and variants const variantsEnc = variants.join(","); - const familiesEnc = fonts.map(font => `${encodeURIComponent(font.family)}:${variantsEnc}`); + const familiesEnc = fonts.map( + (font): string => `${encodeURIComponent(font.family)}:${variantsEnc}`, + ); let query = `?family=${familiesEnc.join("|")}`; // Query the fonts in the specified scripts @@ -25,11 +27,11 @@ export default async function getStylesheet( // If previewsOnly: Only query the characters contained in the font names if (previewsOnly) { // Concatenate the family names of all fonts - const familyNamesConcat = fonts.map(font => font.family).join(""); + const familyNamesConcat = fonts.map((font): string => font.family).join(""); // Create a string with all characters (listed once) contained in the font family names const downloadChars = familyNamesConcat .split("") - .filter((char, pos, self) => self.indexOf(char) === pos) + .filter((char, pos, self): boolean => self.indexOf(char) === pos) .join(""); // Query only the identified characters query += `&text=${downloadChars}`; diff --git a/src/font-manager/loadFonts.ts b/src/font-manager/loadFonts.ts index 9badbcc..df6cbe1 100644 --- a/src/font-manager/loadFonts.ts +++ b/src/font-manager/loadFonts.ts @@ -18,8 +18,10 @@ export async function loadFontPreviews( // Only load previews of fonts which don't have a stylesheet (for preview or full font) yet const fontsArray: Font[] = Array.from(fonts.values()); const fontsToFetch = fontsArray - .map((font: Font) => font.id) - .filter(fontId => !stylesheetExists(fontId, false) && !stylesheetExists(fontId, true)); + .map((font: Font): string => font.id) + .filter( + (fontId): boolean => !stylesheetExists(fontId, false) && !stylesheetExists(fontId, true), + ); // Get Google Fonts stylesheet containing all requested styles const response = await getStylesheet(fontsArray, scripts, variants, true); @@ -27,21 +29,25 @@ export async function loadFontPreviews( const fontStyles = extractFontStyles(response); // Create separate stylesheets for the fonts - fontsArray.forEach(font => { - applyFontPreview(font, selectorSuffix); + fontsArray.forEach( + (font): void => { + applyFontPreview(font, selectorSuffix); - // Add stylesheets for fonts which need to be downloaded - if (fontsToFetch.includes(font.id)) { - // Make sure response contains styles for the font - if (!(font.id in fontStyles)) { - console.error( - `Missing styles for font "${font.family}" (fontId "${font.id}") in Google Fonts response`, - ); - return; + // Add stylesheets for fonts which need to be downloaded + if (fontsToFetch.includes(font.id)) { + // Make sure response contains styles for the font + if (!(font.id in fontStyles)) { + console.error( + `Missing styles for font "${font.family}" (fontId "${ + font.id + }") in Google Fonts response`, + ); + return; + } + createStylesheet(font.id, fontStyles[font.id], true); } - createStylesheet(font.id, fontStyles[font.id], true); - } - }); + }, + ); } /** diff --git a/src/font-manager/styles/declarations.ts b/src/font-manager/styles/declarations.ts index 4e59227..40241e1 100644 --- a/src/font-manager/styles/declarations.ts +++ b/src/font-manager/styles/declarations.ts @@ -20,9 +20,9 @@ export function applyFontPreview(previewFont: Font, selectorSuffix: string): voi /** * Create/find and return the apply-font stylesheet for the provided selectorSuffix */ -function getActiveFontStylesheet(selectorSuffix: string) { +function getActiveFontStylesheet(selectorSuffix: string): HTMLStyleElement { const stylesheetId = `active-font-${selectorSuffix}`; - let activeFontStylesheet = document.getElementById(stylesheetId); + let activeFontStylesheet = document.getElementById(stylesheetId) as HTMLStyleElement; if (!activeFontStylesheet) { activeFontStylesheet = document.createElement("style"); activeFontStylesheet.id = stylesheetId; diff --git a/src/font-manager/utils/request.ts b/src/font-manager/utils/request.ts index 8523b9e..9146e44 100644 --- a/src/font-manager/utils/request.ts +++ b/src/font-manager/utils/request.ts @@ -2,22 +2,24 @@ * Execute a GET XMLHttpRequest and return the result */ export default function get(url: string): Promise { - return new Promise((resolve, reject) => { - const request = new XMLHttpRequest(); - request.overrideMimeType("application/json"); - request.open("GET", url, true); - request.onreadystatechange = () => { - // Request has completed - if (request.readyState === 4) { - if (request.status !== 200) { - // On error - reject(new Error(`Response has status code ${request.status}`)); - } else { - // On success - resolve(request.responseText); + return new Promise( + (resolve, reject): void => { + const request = new XMLHttpRequest(); + request.overrideMimeType("application/json"); + request.open("GET", url, true); + request.onreadystatechange = (): void => { + // Request has completed + if (request.readyState === 4) { + if (request.status !== 200) { + // On error + reject(new Error(`Response has status code ${request.status}`)); + } else { + // On success + resolve(request.responseText); + } } - } - }; - request.send(); - }); + }; + request.send(); + }, + ); } diff --git a/src/font-picker/FontPicker.ts b/src/font-picker/FontPicker.ts index 53cca7b..34b7c80 100644 --- a/src/font-picker/FontPicker.ts +++ b/src/font-picker/FontPicker.ts @@ -43,8 +43,12 @@ export default class FontPicker { limit = 50, sort = "alphabet", }: Options, - onChange: (font: Font) => void = () => {}, + onChange: (font: Font) => void = (): void => {}, ) { + // Function bindings + this.closeEventListener = this.closeEventListener.bind(this); + this.toggleExpanded = this.toggleExpanded.bind(this); + // Initialize FontManager and FontPicker UI const options = { pickerId, @@ -56,9 +60,6 @@ export default class FontPicker { }; this.fontManager = new FontManager(apiKey, defaultFamily, options, onChange); this.generateUI(sort); - - // Function bindings - this.closeEventListener = this.closeEventListener.bind(this); } /** @@ -77,8 +78,8 @@ export default class FontPicker { // Generate HTML for dropdown button (contains family of active font and dropdown icon) this.dropdownButton = document.createElement("button"); this.dropdownButton.classList.add("dropdown-button"); - this.dropdownButton.onclick = () => this.toggleExpanded(); - this.dropdownButton.onkeypress = () => this.toggleExpanded(); + this.dropdownButton.onclick = this.toggleExpanded; + this.dropdownButton.onkeypress = this.toggleExpanded; this.dropdownButton.type = "button"; this.fontPickerDiv.appendChild(this.dropdownButton); // Font family of active font @@ -94,20 +95,26 @@ export default class FontPicker { // Fetch and render font list this.fontManager .init() - .then((fontMap: FontList) => { - const fonts = Array.from(fontMap.values()); - if (sort === "alphabet") { - fonts.sort((font1: Font, font2: Font) => font1.family.localeCompare(font2.family)); - } - this.generateFontList(fonts); - dropdownIcon.classList.replace("loading", "finished"); - }) - .catch((err: Error) => { - // On error: Log error message - dropdownIcon.classList.replace("loading", "error"); - console.error("Error trying to fetch the list of available fonts"); - console.error(err); - }); + .then( + (fontMap: FontList): void => { + const fonts = Array.from(fontMap.values()); + if (sort === "alphabet") { + fonts.sort( + (font1: Font, font2: Font): number => font1.family.localeCompare(font2.family), + ); + } + this.generateFontList(fonts); + dropdownIcon.classList.replace("loading", "finished"); + }, + ) + .catch( + (err: Error): void => { + // On error: Log error message + dropdownIcon.classList.replace("loading", "error"); + console.error("Error trying to fetch the list of available fonts"); + console.error(err); + }, + ); } /** @@ -118,9 +125,11 @@ export default class FontPicker { this.ul = document.createElement("ul"); // Generate HTML for font list entries - fonts.forEach(font => { - this.addFontLi(font); - }); + fonts.forEach( + (font): void => { + this.addFontLi(font); + }, + ); this.fontPickerDiv.appendChild(this.ul); }