Skip to content

Commit

Permalink
Add missing type annotations
Browse files Browse the repository at this point in the history
  • Loading branch information
samuelmeuli committed May 29, 2019
1 parent 64e18b0 commit a45017e
Show file tree
Hide file tree
Showing 8 changed files with 112 additions and 87 deletions.
18 changes: 10 additions & 8 deletions src/font-manager/FontManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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);
}
},
);
}
}
22 changes: 12 additions & 10 deletions src/font-manager/google-fonts/extractFontStyles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,18 @@ export default function extractFontStyles(allFontStyles: string): Record<string,

// Assign font-face rules to fontIds
const fontStyles: Record<string, string> = {};
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;
}
20 changes: 11 additions & 9 deletions src/font-manager/google-fonts/fontList.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,15 @@ export default async function getFontList(apiKey: string): Promise<Font[]> {
// - 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,
};
},
);
}
8 changes: 5 additions & 3 deletions src/font-manager/google-fonts/fontStylesheet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ export default async function getStylesheet(
): Promise<string> {
// 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
Expand All @@ -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}`;
Expand Down
36 changes: 21 additions & 15 deletions src/font-manager/loadFonts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,30 +18,36 @@ 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);
// Parse response and assign styles to the corresponding font
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);
}
});
},
);
}

/**
Expand Down
4 changes: 2 additions & 2 deletions src/font-manager/styles/declarations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
36 changes: 19 additions & 17 deletions src/font-manager/utils/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,24 @@
* Execute a GET XMLHttpRequest and return the result
*/
export default function get(url: string): Promise<string> {
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();
},
);
}
55 changes: 32 additions & 23 deletions src/font-picker/FontPicker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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);
}

/**
Expand All @@ -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
Expand All @@ -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);
},
);
}

/**
Expand All @@ -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);
}

Expand Down

0 comments on commit a45017e

Please sign in to comment.