Creating a fully functional font pairing tool that involves uploading and unzipping files, extracting font types, and implementing a smart algorithm typically requires both frontend and backend components. However, I can provide you with a simplified version using only HTML, CSS, and JavaScript. This version will handle the zip file extraction on the client side using the JSZip library and allow users to like/dislike fonts to simulate the algorithm’s learning process.
Here's a complete HTML file that includes the necessary functionality:
<!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: space-between;
margin-top: 20px;
}
button {
padding: 10px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
}
button:hover {
opacity: 0.9;
}
.find-btn {
background-color: #4CAF50;
color: white;
}
.next-btn {
background-color: #2196F3;
color: white;
}
.font-display {
display: flex;
justify-content: space-between;
margin-top: 20px;
}
.font-box {
width: 45%;
padding: 10px;
border: 1px solid #ddd;
border-radius: 4px;
text-align: center;
background-color: #fafafa;
}
.font-sample {
margin: 10px 0;
padding: 10px;
border: 1px dashed #ccc;
}
.like-buttons {
display: flex;
justify-content: space-around;
margin-top: 10px;
}
.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>Find Font Pair</h2>
<div class="font-display">
<div class="font-box" id="font1Box">
<div class="font-sample" id="font1Sample">The quick brown fox</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</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>
<button class="next-btn hidden" id="nextPairBtn">Next 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 nextPairBtn = document.getElementById('nextPairBtn');
const font1Sample = document.getElementById('font1Sample');
const font2Sample = document.getElementById('font2Sample');
const font1Box = document.getElementById('font1Box');
const font2Box = document.getElementById('font2Box');
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')) || {};
zipFileInput.addEventListener('change', handleZipUpload);
findPairBtn.addEventListener('click', findFontPair);
nextPairBtn.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')) {
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();
} 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;
}
// Simple algorithm: sort fonts by preference and pick top two
const sortedFonts = [...fonts].sort((a, b) => {
const aPref = fontPreferences[a.name] || 0;
const bPref = fontPreferences[b.name] || 0;
return bPref - aPref;
});
// If no preferences, shuffle
if (sortedFonts.every(f => fontPreferences[f.name] === 0)) {
shuffleArray(sortedFonts);
}
// Select first two as the pair
const pair = sortedFonts.slice(0, 2);
currentPair = pair;
// Load fonts dynamically
loadFonts(pair);
// Show Next button
nextPairBtn.classList.remove('hidden');
}
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}');
}
`;
document.head.appendChild(style);
const sample = index === 0 ? font1Sample : font2Sample;
sample.style.fontFamily = `customFont${index}`;
sample.textContent = `The quick brown fox jumps over the lazy dog. (${font.name})`;
});
}
function handleLikeDislike(event) {
const btn = event.target;
const fontBox = btn.dataset.font === 'font1' ? currentPair[0] : currentPair[1];
if (btn.classList.contains('like-btn')) {
fontPreferences[fontBox.name] = (fontPreferences[fontBox.name] || 0) + 1;
} else {
fontPreferences[fontBox.name] = (fontPreferences[fontBox.name] || 0) - 1;
}
localStorage.setItem('fontPreferences', JSON.stringify(fontPreferences));
}
// Utility functions
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
}
</script>
</body>
</html>
Explanation of the Code
-
HTML Structure:
- Upload Section: Allows users to upload a ZIP file containing font files.
- Pair Section: Hidden by default and becomes visible after a successful upload. It displays two font samples with like and dislike buttons.
- Buttons:
- Find Font Pair: Selects and displays a pair of fonts.
- Next Pair: Fetches a new pair of fonts based on user preferences.
-
CSS Styling:
- The CSS is designed to be clean and modern, resembling applications like Notion. It includes responsive design elements and styling for the various components.
-
JavaScript Functionality:
- JSZip Integration: The
JSZip library is used to handle the unzipping of the uploaded file on the client side.
- Font Extraction: After unzipping, the script filters out font files (
.ttf, .otf, .woff, .woff2) and creates object URLs for them.
- Font Pair Selection:
- Initially, fonts are sorted based on user preferences stored in
localStorage.
- If no preferences are set, the fonts are shuffled randomly.
- The top two fonts are selected as the current pair.
- Dynamic Font Loading: The selected fonts are dynamically loaded using
@font-face and applied to the sample text.
- Like/Dislike Mechanism: Users can like or dislike individual fonts. Their preferences are stored in
localStorage to influence future font pair selections.
- Next Pair Button: Allows users to fetch a new font pair based on updated preferences.
Notes and Limitations
- Client-Side Only: This implementation is entirely client-side. For persistent storage and more advanced algorithms, a backend server would be necessary.
- Security Considerations: Handling fonts and unzipping files on the client side might have security implications. Ensure that you trust the sources of the fonts being uploaded.
- Algorithm Simplification: The pairing algorithm here is simplistic. For more intelligent pairing, you'd likely need a more sophisticated approach, possibly involving machine learning models or predefined compatibility rules.
- Browser Support: Ensure that the users have modern browsers that support the features used, especially the
@font-face rules and the JSZip library.
Enhancements
To make this tool more robust and feature-rich, consider the following enhancements:
- Backend Integration: Implement a backend server to handle file uploads, storage, and more complex processing.
- Advanced Pairing Logic: Develop a more intelligent algorithm that considers font characteristics to suggest compatible pairs.
- User Accounts: Allow users to create accounts so their preferences and font collections can be saved and accessed across devices.
- UI Improvements: Enhance the UI with better animations, transitions, and possibly integrating a framework like React or Vue.js for a more dynamic experience.
- Error Handling: Add comprehensive error handling to manage issues like corrupt ZIP files, unsupported font formats, and more.
This implementation provides a foundational structure for a font pairing tool. Depending on your specific requirements and resources, you can expand and refine it further.