Certainly! Below is the revised and complete code for the Font Pair Finder application. This version addresses the issues you've mentioned:
- Removed the "Find Pair" and "Next Pair" buttons: Now, there's only a single "Find Font Pair" button that serves both purposes.
- Fixed the Like and Dislike buttons: The buttons now correctly update the preferences and influence future font pair selections.
- Enhanced the Algorithm: The algorithm now optimizes font pairings based on user preferences, ensuring a smarter and more balanced selection of font pairs.
Complete Code for Font Pair Finder
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Font Pair Finder</title>
<style>
/* Reset and basic styles */
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background-color: #f5f5f5;
display: flex;
flex-direction: column;
align-items: center;
padding: 20px;
}
h1 {
margin-bottom: 20px;
color: #333;
}
.upload-section, .pair-section {
background: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
width: 100%;
max-width: 600px;
margin-bottom: 20px;
}
.upload-section input[type="file"] {
width: 100%;
padding: 10px;
margin-top: 10px;
}
.buttons {
display: flex;
justify-content: center;
margin-top: 20px;
}
button {
padding: 10px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
margin: 0 10px;
}
button:hover {
opacity: 0.9;
}
.find-btn {
background-color: #4CAF50;
color: white;
}
.font-display {
display: flex;
justify-content: space-between;
margin-top: 20px;
gap: 20px;
}
.font-box {
width: 48%;
padding: 10px;
border: 1px solid #ddd;
border-radius: 4px;
text-align: center;
background-color: #fafafa;
display: flex;
flex-direction: column;
align-items: center;
}
.font-sample {
margin: 10px 0;
padding: 10px;
border: 1px dashed #ccc;
width: 100%;
}
.like-buttons {
display: flex;
justify-content: space-around;
width: 100%;
margin-top: auto;
}
.like-buttons button {
padding: 5px 10px;
font-size: 14px;
}
.hidden {
display: none;
}
</style>
</head>
<body>
<h1>Font Pair Finder</h1>
<div class="upload-section">
<h2>Upload Font ZIP File</h2>
<input type="file" id="zipFileInput" accept=".zip">
</div>
<div class="pair-section hidden" id="pairSection">
<h2>Font Pair</h2>
<div class="font-display">
<div class="font-box" id="font1Box">
<div class="font-sample" id="font1Sample">The quick brown fox jumps over the lazy dog.</div>
<div class="like-buttons">
<button class="like-btn" data-font="font1">Like</button>
<button class="dislike-btn" data-font="font1">Dislike</button>
</div>
</div>
<div class="font-box" id="font2Box">
<div class="font-sample" id="font2Sample">The quick brown fox jumps over the lazy dog.</div>
<div class="like-buttons">
<button class="like-btn" data-font="font2">Like</button>
<button class="dislike-btn" data-font="font2">Dislike</button>
</div>
</div>
</div>
<div class="buttons">
<button class="find-btn" id="findPairBtn">Find Font Pair</button>
</div>
</div>
<!-- Include JSZip from CDN -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.0/jszip.min.js"></script>
<script>
const zipFileInput = document.getElementById('zipFileInput');
const pairSection = document.getElementById('pairSection');
const findPairBtn = document.getElementById('findPairBtn');
const font1Sample = document.getElementById('font1Sample');
const font2Sample = document.getElementById('font2Sample');
const likeButtons = document.querySelectorAll('.like-btn, .dislike-btn');
let fonts = [];
let fontStyles = {};
let currentPair = [];
// Load preferences from localStorage
let fontPreferences = JSON.parse(localStorage.getItem('fontPreferences')) || {};
// To keep track of displayed pairs to avoid immediate repeats
let displayedPairs = [];
zipFileInput.addEventListener('change', handleZipUpload);
findPairBtn.addEventListener('click', findFontPair);
likeButtons.forEach(button => {
button.addEventListener('click', handleLikeDislike);
});
async function handleZipUpload(event) {
const file = event.target.files[0];
if (file && file.name.endsWith('.zip')) {
try {
const zip = await JSZip.loadAsync(file);
fonts = [];
const fontPromises = [];
zip.forEach((relativePath, zipEntry) => {
if (!zipEntry.dir && /\.(ttf|otf|woff|woff2)$/.test(zipEntry.name)) {
fontPromises.push(zipEntry.async('blob').then(blob => {
const url = URL.createObjectURL(blob);
fonts.push({
name: zipEntry.name.split('/').pop(),
url: url,
type: getFontType(zipEntry.name)
});
}));
}
});
await Promise.all(fontPromises);
if (fonts.length < 2) {
alert('Please upload a ZIP file with at least two font files.');
return;
}
pairSection.classList.remove('hidden');
findPairBtn.click();
} catch (error) {
console.error('Error reading ZIP file:', error);
alert('Failed to read the ZIP file. Please ensure it contains valid font files.');
}
} else {
alert('Please upload a valid ZIP file.');
}
}
function getFontType(filename) {
const ext = filename.split('.').pop().toLowerCase();
switch(ext) {
case 'ttf': return 'truetype';
case 'otf': return 'opentype';
case 'woff': return 'woff';
case 'woff2': return 'woff2';
default: return 'truetype';
}
}
function findFontPair() {
if (fonts.length < 2) {
alert('Not enough fonts to form a pair.');
return;
}
// Filter out fonts with very low preference to promote variety
const filteredFonts = fonts.filter(font => (fontPreferences[font.name] || 0) >= -2);
if (filteredFonts.length < 2) {
alert('Not enough fonts with acceptable preferences. Resetting preferences.');
fontPreferences = {};
localStorage.removeItem('fontPreferences');
findFontPair();
return;
}
// Sort fonts by preference descending
const sortedFonts = [...filteredFonts].sort((a, b) => {
const aPref = fontPreferences[a.name] || 0;
const bPref = fontPreferences[b.name] || 0;
return bPref - aPref;
});
// Generate possible unique pairs based on sorted preferences
const possiblePairs = [];
for (let i = 0; i < sortedFonts.length; i++) {
for (let j = i + 1; j < sortedFonts.length; j++) {
possiblePairs.push([sortedFonts[i], sortedFonts[j]]);
}
}
// Score each pair based on combined preferences
const scoredPairs = possiblePairs.map(pair => {
const score = (fontPreferences[pair[0].name] || 0) + (fontPreferences[pair[1].name] || 0);
return { pair, score };
});
// Sort pairs by score descending
scoredPairs.sort((a, b) => b.score - a.score);
// Exclude recently displayed pairs to avoid repetition
const MAX_RECENT = 10;
const availablePairs = scoredPairs.filter(sp => {
const pairNames = [sp.pair[0].name, sp.pair[1].name].sort();
return !displayedPairs.some(dp => {
return dp.length === pairNames.length && dp.every(name => pairNames.includes(name));
});
});
let selectedPair;
if (availablePairs.length > 0) {
selectedPair = availablePairs[0].pair;
} else {
// If all pairs have been displayed recently, reset the history
displayedPairs = [];
selectedPair = scoredPairs[0].pair;
}
currentPair = selectedPair;
// Update displayedPairs history
displayedPairs.push([selectedPair[0].name, selectedPair[1].name]);
if (displayedPairs.length > MAX_RECENT) {
displayedPairs.shift();
}
// Load fonts dynamically
loadFonts(selectedPair);
}
function loadFonts(pair) {
// Remove previous fonts
document.querySelectorAll('style.font-style').forEach(style => style.remove());
pair.forEach((font, index) => {
const style = document.createElement('style');
style.classList.add('font-style');
style.innerHTML = `
@font-face {
font-family: 'customFont${index}';
src: url('${font.url}') format('${font.type}');
font-weight: normal;
font-style: normal;
}
`;
document.head.appendChild(style);
const sample = index === 0 ? font1Sample : font2Sample;
sample.style.fontFamily = `'customFont${index}', sans-serif`;
sample.textContent = `The quick brown fox jumps over the lazy dog.\n(${font.name})`;
});
}
function handleLikeDislike(event) {
const btn = event.target;
const fontKey = btn.dataset.font === 'font1' ? '0' : '1';
const font = currentPair[fontKey];
if (!font) return;
if (btn.classList.contains('like-btn')) {
fontPreferences[font.name] = (fontPreferences[font.name] || 0) + 1;
} else {
fontPreferences[font.name] = (fontPreferences[font.name] || 0) - 1;
}
localStorage.setItem('fontPreferences', JSON.stringify(fontPreferences));
}
// Optional: Clear preferences for testing or resetting
/*
function clearPreferences() {
fontPreferences = {};
localStorage.removeItem('fontPreferences');
}
*/
</script>
</body>
</html>
Key Enhancements and Fixes
-
Single "Find Font Pair" Button:
- Removed the "Next Pair" Button: Consolidated the functionality into a single "Find Font Pair" button, simplifying the user interface.
- Button Styling Adjustments: Ensured that the button is centrally aligned and aesthetically pleasing.
-
Fixed Like and Dislike Buttons:
- Correct Font Identification: Updated the
handleLikeDislike function to accurately identify which font (font1 or font2) is being liked or disliked based on the data-font attribute.
- Preference Management: Adjusted the preference values correctly in the
fontPreferences object and saved them to localStorage to persist user choices.
-
Advanced Algorithm for Font Pair Selection:
- Preference-Based Sorting: Fonts are now sorted based on cumulative user preferences, ensuring that highly liked fonts are prioritized in pairings.
- Pair Scoring: Each possible pair is scored based on the combined preferences of both fonts, allowing the algorithm to select the most favored pairs.
- Avoiding Repetition: Implemented a mechanism to track recently displayed pairs (
displayedPairs) to prevent immediate repetition, enhancing the user's discovery experience.
- Fallback Mechanism: If there aren't enough fonts with acceptable preferences, the algorithm resets preferences to allow new pairings to surface.
-
Error Handling Enhancements:
- ZIP File Validation: Added try-catch blocks to handle potential errors during ZIP file parsing, providing user-friendly alerts in case of issues.
- Font Validation: Ensured that only valid font files (
.ttf, .otf, .woff, .woff2) are processed, preventing potential issues with unsupported file types.
-
User Interface Improvements:
- Responsive Design: Ensured that the layout is responsive and looks good on various screen sizes.
- Enhanced Font Sample Display: The font samples now include both the font rendering and the font name for better identification.
- Accessibility Considerations: Improved button readability and interactions to make the application more user-friendly.
Usage Instructions
-
Upload Fonts:
- Click on the "Upload Font ZIP File" section and select a ZIP file containing at least two font files (
.ttf, .otf, .woff, .woff2).
-
View Font Pair:
- After successfully uploading, the application will automatically display a pair of fonts based on your preferences.
-
Like or Dislike Fonts:
- Use the "Like" or "Dislike" buttons below each font sample to rate the fonts. These ratings influence future pair selections.
-
Find New Pairs:
- Click the "Find Font Pair" button to view a new pair of fonts. The algorithm ensures that pairs are selected intelligently based on your feedback.
-
Persistent Preferences:
- Your font preferences are saved in your browser's
localStorage, ensuring that your ratings persist across sessions.
Additional Notes
-
Resetting Preferences: If you wish to reset your font preferences, you can uncomment and use the clearPreferences function provided in the JavaScript section.
-
Extensibility: The application's architecture allows for further enhancements, such as categorizing fonts or integrating more sophisticated recommendation algorithms.
Feel free to integrate this code into your project and customize it further to suit your specific needs!