-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
433 lines (367 loc) · 12.7 KB
/
script.js
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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
// API URL to fetch Google Fonts via serverless function
const apiURL = `/api/fonts`;
// Choose which URL to use
// const finalApiURL = apiKey ? apiURL : apiCache;
const finalApiURL = apiURL;
// Function to adjust the margin of the fonts container
function adjustFontsContainerMargin() {
const controlsDiv = document.getElementById("controls");
const fontsContainer = document.getElementById("fonts-container");
const controlsHeight = controlsDiv.offsetHeight;
fontsContainer.style.marginTop = `${controlsHeight + 20}px`; // 20px extra for some spacing
}
// Create a MutationObserver instance
const observer = new MutationObserver(adjustFontsContainerMargin);
// Configuration of the observer
const config = { attributes: true, childList: true, subtree: true };
// Start observing the target node for configured mutations
const controlsDiv = document.getElementById("controls");
observer.observe(controlsDiv, config);
var cachedResponses = {};
// Function to initialize font samples
async function initFontSamples() {
const container = document.getElementById("fonts-container");
try {
if (!cachedResponses[finalApiURL]) {
// Fetch font list from API or cache
const response = await fetch(finalApiURL);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
const fontList = data.items;
cachedResponses[finalApiURL] = fontList;
}
// Get selected filters
const selectedFeatures = Array.from(
document.querySelectorAll('input[name="filter"]:checked')
).map((input) => input.value);
const selectedCategories = Array.from(
document.querySelectorAll('input[name="category"]:checked')
).map((input) => input.value);
// radio select with options - any, variable, color
const selectedTechnology = Array.from(
document.querySelectorAll('input[name="technology"]:checked')
).map((input) => input.value);
// Define filter criteria
const filter = {
features: selectedFeatures,
category: selectedCategories,
variants: ["regular", "italic"],
subsets: ["latin"],
variable: selectedTechnology.includes("variable"),
};
// Filter fonts based on criteria
const fontListFiltered = await getFilteredGoogleFonts(
cachedResponses[finalApiURL],
filter
);
// update #filter-count
document.getElementById("filter-count").textContent =
fontListFiltered.length;
if (fontListFiltered.length === 0) {
throw new Error("No fonts matched the filter criteria.");
}
// Extract font family names
const families = fontListFiltered.map((font) => font.family);
// Load the filtered fonts using Web Font Loader
WebFont.load({
google: {
families: families.map((font) => `${font}:400`),
},
active: function () {
// Once fonts are loaded, create samples
fontListFiltered.forEach((font) => {
createFontSample(font, container);
});
},
inactive: function () {
container.innerHTML = "<p>Failed to load fonts.</p>";
},
});
} catch (error) {
console.error("Error fetching or processing font list:", error);
container.innerHTML = `<p>Error: ${error.message}</p>`;
}
}
function createFontSample(font, container) {
const textSampleContainer = document.createElement("div");
textSampleContainer.className = "text-sample-container";
const fontDiv = document.createElement("div");
fontDiv.className = "font-sample";
const fontName = document.createElement("div");
fontName.className = "font-name";
fontName.textContent = font.family;
textSampleContainer.appendChild(fontName);
const sampleText = document.createElement("div");
sampleText.className = "sample-text";
sampleText.style.fontFamily = `'${font.family}', sans-serif`;
sampleText.textContent = document.getElementById("sample-textarea").value;
textSampleContainer.appendChild(sampleText);
fontDiv.appendChild(textSampleContainer);
const table = createSampleTable();
table.style.fontFamily = `'${font.family}', sans-serif`;
fontDiv.appendChild(table);
container.appendChild(fontDiv);
updateTableWidthDivs(table);
}
const tableDef = {
rows: 2,
cols: 2,
};
const inputs = ["input1", "input2", "input3", "input4"];
function createSampleTable() {
const table = document.createElement("table");
table.className = "sample-table";
for (let i = 0; i < tableDef.rows; i++) {
const row = table.insertRow();
for (let j = 0; j < tableDef.cols; j++) {
const cell = row.insertCell();
// set to 50% width
cell.style.width = "50%";
// cell.position = "relative";
const container = document.createElement("div");
container.style.display = "flex";
container.style.justifyContent = "space-between";
container.style.width = "100%";
container.className = "table-cell-container";
cell.appendChild(container);
// create div to show the width of the text
const widthDiv = document.createElement("div");
widthDiv.className = "width-div";
widthDiv.style.color = "gray";
widthDiv.style.fontSize = "10px";
widthDiv.style.fontFamily = "monospace";
widthDiv.textContent = cell.textContent.length * 10;
container.appendChild(widthDiv);
//create div for the text
const textDiv = document.createElement("div");
textDiv.className = "table-text";
// set the text content
textDiv.textContent = document.getElementById(
inputs[i * tableDef.cols + j]
).value;
// append the text div to the cell
container.appendChild(textDiv);
// const textWidth = textDiv.
widthDiv.textContent = `${textDiv.offsetWidth}px x ${textDiv.offsetHeight}px`;
}
}
return table;
}
const textChangeObserver = new MutationObserver(updateWidthDivs);
function addEventListeners() {
document.querySelectorAll(".table-text").forEach((textDiv) => {
textChangeObserver.observe(textDiv, { childList: true });
});
}
// Function to update text in the samples based on input
function updateSampleText() {
const text = document.getElementById("sample-textarea").value;
const samples = document.querySelectorAll(".sample-text");
samples.forEach((sample) => {
sample.textContent = text;
});
}
// Function to update the sample tables
function updateSampleTables() {
const tables = document.querySelectorAll(".sample-table");
tables.forEach((table) => {
let i = 0;
for (let row of table.rows) {
for (let cell of row.cells) {
const container = cell.querySelector(".table-cell-container");
const textDiv = container.querySelector(".table-text");
textDiv.textContent = document.getElementById(inputs[i]).value;
const widthDiv = container.querySelector(".width-div");
i++;
}
}
});
}
function updateTableWidthDivs(table) {
for (let row of table.rows) {
for (let cell of row.cells) {
const container = cell.querySelector(".table-cell-container");
const textDiv = container.querySelector(".table-text");
const widthDiv = container.querySelector(".width-div");
widthDiv.textContent = `${textDiv.offsetWidth}px x ${textDiv.offsetHeight}px`;
}
}
}
function updateWidthDivs() {
const tables = document.querySelectorAll(".sample-table");
tables.forEach((table) => {
for (let row of table.rows) {
for (let cell of row.cells) {
const container = cell.querySelector(".table-cell-container");
const textDiv = container.querySelector(".table-text");
const widthDiv = container.querySelector(".width-div");
widthDiv.textContent = `${textDiv.offsetWidth}px x ${textDiv.offsetHeight}px`;
}
}
});
}
// Function to apply font feature settings
function applyFeatureSettings() {
const selectedFeatures = Array.from(
document.querySelectorAll('input[name="feature"]:checked')
).map((input) => input.value);
const featureString = selectedFeatures
.map((feature) => `"${feature}" 1`)
.join(", ");
// set body font feature settings
document.body.style.fontFeatureSettings = featureString;
updateWidthDivs();
}
// Function to filter Google Fonts based on criteria
async function getFilteredGoogleFonts(fontList, filter = {}) {
const fontListFiltered = [];
// Merge with defaults
filter = {
...{
family: [],
category: [],
features: [],
variants: [],
subsets: [],
axes: [],
variable: null,
},
...filter,
};
for (let i = 0; i < fontList.length; i++) {
const font = fontList[i];
const {
family,
category,
files,
subsets,
variants,
axes = [],
colorCapabilities = [],
} = font;
if (font.family === "Raleway") {
// always include Raleway
fontListFiltered.push(font);
continue;
}
// Apply family filter
if (filter.family.length && !filter.family.includes(family)) continue;
// Apply category filter
if (filter.category.length && !filter.category.includes(category)) continue;
// Apply variable filter
if (filter.variable !== false && axes.length === 0) continue;
// Apply axes filter
const axesNames = axes.map((item) => item.tag);
if (filter.axes.length) {
if (!axesNames.length) continue;
const hasAxes = filter.axes.every((axis) => axesNames.includes(axis));
if (!hasAxes) continue;
}
// Apply category filter
if (filter.category.length && !filter.category.includes(category)) continue;
// Apply variants filter
if (filter.variants.length) {
const hasVariants = filter.variants.every((variant) =>
variants.includes(variant)
);
if (!hasVariants) continue;
}
// Apply subsets filter
if (filter.subsets.length) {
const hasSubset = filter.subsets.every((subset) =>
subsets.includes(subset)
);
if (!hasSubset) continue;
}
if (filter.features.length > 0) {
// Get the font features via lib.font
let fontUrl = files.regular ? files.regular : Object.values(files)[0];
if (!cachedResponses[fontUrl]) {
let features = await getFontFeatures(fontUrl);
cachedResponses[fontUrl] = features;
}
let features = cachedResponses[fontUrl];
// Check if font matches the features filter
let hasFeatures =
features &&
filter.features.every((feature) => features.includes(feature));
if (!hasFeatures) continue;
}
// If the font matches all criteria, add it to the filtered list
fontListFiltered.push(font);
}
return fontListFiltered;
}
/**
* get font features via lib.font
* by parsing fonts and reading data tables
* https://github.com/Pomax/lib-font
*/
async function getFontFeatures(fontUrl) {
return new Promise((resolve, reject) => {
let font = new Font("fontFamily", {
skipStyleSheet: true,
});
font.src = fontUrl;
let features;
//let features = [], GSUB;
font.onload = (evt) => {
try {
let font = evt.detail.font;
let otTables = font.opentype.tables;
// skip fonts without features
let featureCount = otTables.GSUB
? otTables.GSUB.featureList.featureCount
: 0;
if (featureCount) {
GSUB = otTables.GSUB.featureList.featureRecords;
features = [
...new Set(
GSUB.map((rec) => {
return rec.featureTag;
})
),
];
}
resolve(features);
} catch (error) {
reject(error);
}
};
font.onerror = (err) => {
reject(err);
};
});
}
// Event listeners
document.querySelectorAll('input[name="category"]').forEach((input) => {
input.addEventListener("change", initFontSamples);
});
// radio select with options - any, variable, color
const technologyInputs = document.querySelectorAll('input[name="technology"]');
technologyInputs.forEach((input) => {
input.addEventListener("change", initFontSamples);
});
document
.getElementById("sample-textarea")
.addEventListener("input", updateSampleText);
document.querySelectorAll(".input-grid input").forEach((input) => {
input.addEventListener("input", updateSampleTables);
});
document.querySelectorAll('input[name="filter"]').forEach((input) => {
input.addEventListener("change", initFontSamples);
});
document.querySelectorAll('input[name="feature"]').forEach((input) => {
input.addEventListener("change", applyFeatureSettings);
});
// Initialize on page load
window.onload = () => {
initFontSamples();
adjustFontsContainerMargin(); // Initial adjustment
updateWidthDivs();
addEventListeners();
};
// Adjust margin on window resize
window.addEventListener("resize", adjustFontsContainerMargin);