forked from WordPress/google-fonts-to-wordpress-collection
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathget_google_fonts.js
More file actions
159 lines (139 loc) · 3.93 KB
/
get_google_fonts.js
File metadata and controls
159 lines (139 loc) · 3.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
/**
* External dependencies
*/
const fs = require('fs');
const crypto = require('crypto');
/**
* Internal dependencies
*/
const {
API_URL,
API_KEY,
GOOGLE_FONTS_CAPABILITY,
GOOGLE_FONTS_FILE_PATH,
FONT_COLLECTION_SCHEMA_URL,
FONT_COLLECTION_SCHEMA_VERSION,
} = require('./constants');
function formatCategoryName(slug) {
return slug
// Split the string into an array of words
.split('-')
// Capitalize the first letter of each word
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
// Join the words back into a single string, separated by spaces
.join(' ');
}
function getCategories(fonts) {
const category_slugs = new Set();
fonts.forEach((font) => {
category_slugs.add( font.category );
});
// Returs an array of categories
const categories = [...category_slugs].map((slug) => (
{
name: formatCategoryName( slug ),
slug,
}
));
return categories;
}
function calculateHash(somestring) {
return crypto
.createHash('md5')
.update(somestring)
.digest('hex')
.toString();
}
// Google Fonts API categories mappping to fallback system fonts
const GOOGLE_FONT_FALLBACKS = {
display: 'system-ui',
'sans-serif': 'sans-serif',
serif: 'serif',
handwriting: 'cursive',
monospace: 'monospace',
};
function getStyleFromGoogleVariant(variant) {
return variant.includes('italic') ? 'italic' : 'normal';
}
function getWeightFromGoogleVariant(variant) {
return variant === 'regular' || variant === 'italic'
? '400'
: variant.replace('italic', '');
}
function getFallbackForGoogleFont(googleFontCategory) {
return GOOGLE_FONT_FALLBACKS[googleFontCategory] || 'system-ui';
}
function httpToHttps(url) {
return url.replace('http://', 'https://');
}
function getFontFamilyFromGoogleFont(font) {
return {
font_family_settings: {
name: font.family,
fontFamily: `${font.family}, ${getFallbackForGoogleFont(
font.category
)}`,
slug: font.family.replace(/\s+/g, '-').toLowerCase(),
fontFace: font.variants.map((variant) => ({
src: httpToHttps(font.files?.[variant]),
fontWeight: getWeightFromGoogleVariant(variant),
fontStyle: getStyleFromGoogleVariant(variant),
fontFamily: font.family,
})),
},
categories: [ font.category ],
};
}
async function updateFiles() {
let newApiData;
let newData;
let response;
try {
newApiData = await fetch(`${API_URL}${API_KEY}&capability=${GOOGLE_FONTS_CAPABILITY}`);
response = await newApiData.json();
} catch (error) {
// TODO: show in UI and remove console statement
// eslint-disable-next-line
console.error('❎ Error fetching the Google Fonts API:', error);
process.exit(1);
}
const fontFamilies = response.items.map(getFontFamilyFromGoogleFont);
const categories = getCategories(response.items);
// The data to be written to the file
newData = {
"$schema": FONT_COLLECTION_SCHEMA_URL,
"version": FONT_COLLECTION_SCHEMA_VERSION,
categories,
font_families:fontFamilies,
};
if (response.items) {
const newDataString = JSON.stringify(newData, null, 2);
// If the file doesn't exist, create it
if ( ! fs.existsSync( GOOGLE_FONTS_FILE_PATH ) ) {
fs.writeFileSync(GOOGLE_FONTS_FILE_PATH, '{}');
}
const oldFileData = fs.readFileSync(GOOGLE_FONTS_FILE_PATH, 'utf8');
const oldData = JSON.parse(oldFileData);
const oldDataString = JSON.stringify(oldData, null, 2);
if (
calculateHash(newDataString) !== calculateHash(oldDataString)
) {
fs.writeFileSync(GOOGLE_FONTS_FILE_PATH, newDataString);
// TODO: show in UI and remove console statement
// eslint-disable-next-line
console.info('✅ Google Fonts JSON file updated');
} else {
// TODO: show in UI and remove console statement
// eslint-disable-next-line
console.info('ℹ️ Google Fonts JSON file is up to date');
}
} else {
// TODO: show in UI and remove console statement
// eslint-disable-next-line
console.error(
'❎ No new data to check. Check the Google Fonts API key.'
);
process.exit(1);
}
}
updateFiles();