@amaui/utils
Version:
34 lines (30 loc) • 1.27 kB
JavaScript
import is from './is';
/**
* Example:
* Input:
* getGoogleFontsURL([
* { name: 'Roboto', weights: [400, 700] },
* { name: 'Source Sans 3', weights: ['italic 200', 400, 700] },
* ]);
* Output:
* 'https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&family=Source+Sans+3:ital,wght@0,200;0,700;1,200&display=swap'
*/
const getGoogleFontsURL = value => {
if (is('array', value)) {
let googleFontsLink = 'https://fonts.googleapis.com/css2?';
for (const font of value) {
if (!font.weights) font.weights = [];
const hasItalic = font.weights.some(weight => is('string', weight) && weight.indexOf('italic ') === 0);
if (!font.weights.length) font.weights.push(400);
font.weights = font.weights.map(weight => {
if (is('string', weight) && weight.indexOf('italic') === 0) return weight.replace('italic ', '1,').replace(/\s/g, '');
return "".concat(hasItalic ? '0,' : '').concat(String(weight));
});
font.weights.sort();
googleFontsLink += "family=".concat(font.name.replace(/\s/g, '+'), ":").concat(hasItalic ? 'ital,' : '', "wght@").concat(font.weights.join(';'), "&");
}
googleFontsLink += "display=swap";
return googleFontsLink;
}
};
export default getGoogleFontsURL;