Creating a complete web application with the features you've described involves both frontend and backend development, as well as handling file uploads, processing, and implementing a recommendation algorithm. Below is a simplified version of how you can achieve this using React for the frontend and Node.js with Express for the backend. Additionally, we'll use MongoDB for storing user preferences.
Overview
-
Frontend (React)
- Upload ZIP file containing fonts.
- Display font pairs.
- Allow users to like/dislike font pairs.
- Modern UI similar to Notion.
-
Backend (Node.js + Express)
- Handle file uploads and unzip them.
- Extract font files.
- Serve fonts to the frontend.
- Store user preferences.
- Implement a simple recommendation algorithm.
-
Database (MongoDB)
- Store user preferences and font data.
Prerequisites
- Node.js and npm installed.
- MongoDB database setup.
- Basic knowledge of React, Node.js, and Express.
Step-by-Step Implementation
1. Backend Setup
a. Initialize the Backend Project
mkdir font-pairing-app
cd font-pairing-app
mkdir backend
cd backend
npm init -y
npm install express multer unzipper mongoose cors
b. Create the Server (backend/server.js)
const express = require('express');
const multer = require('multer');
const unzipper = require('unzipper');
const fs = require('fs');
const path = require('path');
const mongoose = require('mongoose');
const cors = require('cors');
const app = express();
app.use(cors());
app.use(express.json());
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/fontpair', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
// Define Schemas
const FontSchema = new mongoose.Schema({
name: String,
type: String,
path: String,
});
const PreferenceSchema = new mongoose.Schema({
preferredFont: String,
dislikedFont: String,
});
const Font = mongoose.model('Font', FontSchema);
const Preference = mongoose.model('Preference', PreferenceSchema);
// Set up multer for file uploads
const storage = multer.diskStorage({
destination: (req, file, cb) => {
const uploadPath = path.join(__dirname, 'uploads');
if (!fs.existsSync(uploadPath)) {
fs.mkdirSync(uploadPath);
}
cb(null, 'uploads/');
},
filename: (req, file, cb) => {
cb(null, file.originalname);
},
});
const upload = multer({ storage });
// Endpoint to upload ZIP file
app.post('/upload', upload.single('fontsZip'), async (req, res) => {
const zipPath = path.join(__dirname, req.file.path);
const extractPath = path.join(__dirname, 'fonts');
fs.createReadStream(zipPath)
.pipe(unzipper.Extract({ path: extractPath }))
.on('close', async () => {
// Extract font files and save to DB
const files = fs.readdirSync(extractPath);
for (const file of files) {
const ext = path.extname(file).toLowerCase();
if (['.ttf', '.otf', '.woff', '.woff2'].includes(ext)) {
const fontName = path.basename(file, ext);
const fontType = ext.substring(1);
const fontPath = `/fonts/${file}`;
const existing = await Font.findOne({ name: fontName });
if (!existing) {
const font = new Font({
name: fontName,
type: fontType,
path: fontPath,
});
await font.save();
}
}
}
res.json({ message: 'Fonts uploaded and processed successfully.' });
})
.on('error', (err) => {
res.status(500).json({ error: err.message });
});
});
// Serve font files
app.use('/fonts', express.static(path.join(__dirname, 'fonts')));
// Endpoint to get random font pair
app.get('/font-pair', async (req, res) => {
const fonts = await Font.find();
if (fonts.length < 2) {
return res.status(400).json({ error: 'Not enough fonts available.' });
}
const randomIndices = [];
while (randomIndices.length < 2) {
const rand = Math.floor(Math.random() * fonts.length);
if (!randomIndices.includes(rand)) {
randomIndices.push(rand);
}
}
const pair = [fonts[randomIndices[0]], fonts[randomIndices[1]]];
res.json(pair);
});
// Endpoint to like a font pair
app.post('/like', async (req, res) => {
const { preferredFont, dislikedFont } = req.body;
const preference = new Preference({ preferredFont, dislikedFont });
await preference.save();
res.json({ message: 'Preference saved.' });
});
// Start the server
const PORT = 5000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
c. Directory Structure
Make sure your backend directory has the following structure:
backend/
├── fonts/
├── uploads/
├── server.js
├── package.json
└── package-lock.json
2. Frontend Setup
a. Initialize the Frontend Project
Open a new terminal window/tab and navigate to the font-pairing-app directory.
npx create-react-app frontend
cd frontend
npm install axios
b. Create the UI (frontend/src/App.js)
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import './App.css';
function App() {
const [selectedFile, setSelectedFile] = useState(null);
const [fontPair, setFontPair] = useState([]);
const [message, setMessage] = useState('');
const handleFileChange = (e) => {
setSelectedFile(e.target.files[0]);
};
const handleUpload = async () => {
if (!selectedFile) {
alert('Please select a ZIP file.');
return;
}
const formData = new FormData();
formData.append('fontsZip', selectedFile);
try {
const res = await axios.post('http://localhost:5000/upload', formData);
setMessage(res.data.message);
} catch (err) {
console.error(err);
setMessage('Upload failed.');
}
};
const fetchFontPair = async () => {
try {
const res = await axios.get('http://localhost:5000/font-pair');
setFontPair(res.data);
} catch (err) {
console.error(err);
setMessage('Failed to fetch font pair.');
}
};
const handleLike = async (preferredFont, dislikedFont) => {
try {
await axios.post('http://localhost:5000/like', { preferredFont, dislikedFont });
fetchFontPair();
} catch (err) {
console.error(err);
}
};
useEffect(() => {
fetchFontPair();
}, []);
return (
<div className="App">
<h1>Font Pair Finder</h1>
<div className="upload-section">
<input type="file" accept=".zip" onChange={handleFileChange} />
<button onClick={handleUpload}>Upload Fonts</button>
<p>{message}</p>
</div>
<div className="font-pair-section">
{fontPair.length === 2 ? (
<div className="font-pair">
<div className="font-item">
<h3>{fontPair[0].name}</h3>
<p>Type: {fontPair[0].type}</p>
<p style={{ fontFamily: fontPair[0].name }}>{fontPair[0].name}</p>
</div>
<div className="font-item">
<h3>{fontPair[1].name}</h3>
<p>Type: {fontPair[1].type}</p>
<p style={{ fontFamily: fontPair[1].name }}>{fontPair[1].name}</p>
</div>
</div>
) : (
<p>Loading font pair...</p>
)}
<div className="actions">
{fontPair.length === 2 && (
<>
<button onClick={() => handleLike(fontPair[0].name, fontPair[1].name)}>Like</button>
<button onClick={() => handleLike(fontPair[1].name, fontPair[0].name)}>Dislike</button>
<button onClick={fetchFontPair}>Next</button>
</>
)}
</div>
</div>
</div>
);
}
export default App;
c. Add Some Styles (frontend/src/App.css)
.App {
text-align: center;
font-family: Arial, sans-serif;
padding: 20px;
}
.upload-section {
margin-bottom: 30px;
}
.upload-section input {
margin-right: 10px;
}
.font-pair-section {
display: flex;
flex-direction: column;
align-items: center;
}
.font-pair {
display: flex;
gap: 50px;
margin-bottom: 20px;
}
.font-item {
border: 1px solid #ccc;
padding: 20px;
border-radius: 8px;
width: 200px;
}
.actions button {
margin: 5px;
padding: 10px 20px;
border: none;
background-color: #4676D7;
color: white;
border-radius: 5px;
cursor: pointer;
}
.actions button:hover {
background-color: #345bb5;
}
d. Load Fonts Dynamically
To display fonts correctly, you need to load them dynamically based on the uploaded fonts. Modify the backend to serve a CSS file with @font-face declarations.
Update backend/server.js
Add the following endpoint to generate dynamic CSS:
app.get('/fonts.css', async (req, res) => {
const fonts = await Font.find();
let css = '';
fonts.forEach((font) => {
css += `
@font-face {
font-family: '${font.name}';
src: url('${font.path}') format('${font.type}');
font-weight: normal;
font-style: normal;
}
`;
});
res.setHeader('Content-Type', 'text/css');
res.send(css);
});
Modify frontend/public/index.html
Add a link to the dynamically generated CSS:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- ... existing tags ... -->
<link rel="stylesheet" href="http://localhost:5000/fonts.css" />
</head>
<body>
<div id="root"></div>
</body>
</html>
3. Run the Application
a. Start the Backend Server
Ensure you are in the backend directory.
node server.js
b. Start the Frontend Server
Open another terminal, navigate to the frontend directory, and run:
npm start
Your application should now be running with the frontend on http://localhost:3000 and the backend on http://localhost:5000.
Enhancements & Recommendations
- User Authentication: Implement user accounts to track individual preferences.
- Advanced Recommendation Algorithm: Use machine learning to better understand and predict font pairings based on user interactions.
- Styling: Enhance the UI to closely resemble modern applications like Notion using libraries like Material-UI or Styled Components.
- Error Handling: Improve error handling and feedback for better user experience.
- Scalability: Optimize file storage using services like AWS S3 and improve database schema for scalability.
Conclusion
This example provides a basic implementation of the requested features. Depending on your specific requirements and scale, you may need to expand and optimize each part accordingly. Integrating more sophisticated algorithms and enhancing the user interface will provide a better user experience and more intelligent font pairing suggestions.