Certainly! Below is the complete updated HTML code for your Font Organizer application. The primary changes focus on the ZIP download functionality to ensure that:
- All font files are placed directly at the root of the ZIP file, eliminating any nested folders.
- Only supported font file types are included in the ZIP, excluding any non-font files.
Key Changes:
- Download Functionality: Modified the ZIP generation logic to add all font files directly to the root of the ZIP, irrespective of their collections.
- File Validation: Enhanced the file filtering to ensure only supported font types are included when generating the ZIP.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Font Organizer</title>
<!-- JSZip Library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.0/jszip.min.js"></script>
<style>
/* Resetting default styles */
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
background-color: #f5f5f5;
color: #333;
height: 100vh;
display: flex;
flex-direction: column;
}
/* Container for main app content */
#app-container {
flex: 1;
display: flex;
overflow: hidden;
transition: filter 0.3s ease;
}
/* Blurred Background when modal is active */
#app-container.blurred {
filter: blur(5px);
}
header {
background-color: #fff;
padding: 20px 40px;
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
display: flex;
align-items: center;
justify-content: space-between;
z-index: 1;
}
header h1 {
font-size: 24px;
color: #111;
}
main {
flex: 1;
display: flex;
overflow: hidden;
position: relative;
z-index: 0;
}
/* Sidebar Styles */
.sidebar {
width: 250px;
background-color: #fff;
border-right: 1px solid #ddd;
padding: 20px;
overflow-y: auto;
}
.sidebar h2 {
font-size: 18px;
margin-bottom: 10px;
}
.sidebar ul {
list-style: none;
}
.sidebar li {
padding: 10px;
margin-bottom: 5px;
background-color: #f0f0f0;
cursor: pointer;
border-radius: 4px;
display: flex;
justify-content: space-between;
align-items: center;
}
.sidebar li.active {
background-color: #d0d0d0;
}
.sidebar li:hover {
background-color: #e0e0e0;
}
.sidebar button {
background-color: #007bff;
color: #fff;
border: none;
padding: 8px 12px;
border-radius: 4px;
cursor: pointer;
margin-top: 10px;
width: 100%;
}
.sidebar button:hover {
background-color: #0056b3;
}
/* Content Area Styles */
.content {
flex: 1;
padding: 20px;
overflow-y: auto;
}
.upload-section {
margin-bottom: 20px;
padding: 20px;
background-color: #fff;
border: 2px dashed #ccc;
border-radius: 6px;
text-align: center;
cursor: pointer;
transition: background-color 0.3s;
}
.upload-section.dragover {
background-color: #e6f7ff;
border-color: #1890ff;
}
.upload-section input {
display: none;
}
.fonts-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
gap: 15px;
}
.font-card {
background-color: #fff;
padding: 10px;
border-radius: 4px;
box-shadow: 0 1px 2px rgba(0,0,0,0.1);
word-break: break-word;
position: relative;
cursor: pointer;
transition: transform 0.2s;
}
.font-card:hover {
transform: scale(1.02);
}
.font-card.dragging {
opacity: 0.5;
}
.delete-btn {
position: absolute;
top: 5px;
right: 5px;
background: none;
border: none;
color: #e74c3c;
font-size: 16px;
cursor: pointer;
display: none;
}
.font-card:hover .delete-btn {
display: block;
}
.collections {
margin-bottom: 20px;
}
.collections h3 {
margin-bottom: 10px;
font-size: 16px;
color: #555;
}
.collections ul {
list-style: none;
}
.collections li {
padding: 6px 10px;
background-color: #f9f9f9;
margin-bottom: 5px;
border-radius: 4px;
display: flex;
justify-content: space-between;
align-items: center;
}
.collections li span {
flex: 1;
}
.collections li button {
background: none;
border: none;
color: #888;
cursor: pointer;
margin-left: 5px;
}
.download-section {
padding: 20px;
background-color: #fff;
border-top: 1px solid #ddd;
text-align: center;
}
.download-section button {
background-color: #28a745;
color: #fff;
border: none;
padding: 12px 20px;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
}
.download-section button:hover {
background-color: #218838;
}
.instructions {
margin-top: 10px;
font-size: 14px;
color: #555;
}
/* Modal Styles */
.modal {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.5);
display: none;
align-items: center;
justify-content: center;
padding: 20px;
z-index: 10;
}
.modal-content {
background-color: #fff;
padding: 20px;
width: 100%;
max-width: 500px;
border-radius: 6px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
position: relative;
}
.modal-content h3 {
margin-bottom: 15px;
font-size: 18px;
}
.modal-content input {
width: 100%;
padding: 10px;
margin-bottom: 15px;
border: 1px solid #ccc;
border-radius: 4px;
}
.modal-content button {
background-color: #007bff;
color: #fff;
border: none;
padding: 10px 16px;
border-radius: 4px;
cursor: pointer;
}
.modal-content button:hover {
background-color: #0056b3;
}
.close-modal {
position: absolute;
top: 10px;
right: 15px;
background: none;
border: none;
font-size: 20px;
cursor: pointer;
color: #aaa;
}
.close-modal:hover {
color: #000;
}
/* Preview Modal Styles */
.preview-modal-content {
background-color: #fff;
padding: 30px;
width: 90%;
max-width: 600px;
border-radius: 8px;
box-shadow: 0 2px 15px rgba(0,0,0,0.3);
text-align: center;
position: relative;
}
.preview-modal-content h3 {
margin-bottom: 20px;
font-size: 24px;
}
.preview-sample {
margin-top: 20px;
padding: 20px;
border: 2px dashed #ccc;
border-radius: 6px;
font-size: 24px;
display: inline-block;
min-width: 100%;
word-wrap: break-word;
}
.close-preview-btn {
position: absolute;
top: 15px;
right: 20px;
background: none;
border: none;
font-size: 24px;
cursor: pointer;
color: #aaa;
}
.close-preview-btn:hover {
color: #000;
}
/* Type Mode Input */
.type-mode-input {
margin-top: 20px;
display: flex;
flex-direction: column;
align-items: center;
}
.type-mode-input input {
width: 80%;
max-width: 400px;
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 16px;
}
/* Responsive Adjustments */
@media (max-width: 768px) {
.sidebar {
width: 200px;
}
.modal-content, .preview-modal-content {
padding: 20px;
}
}
@media (max-width: 480px) {
.sidebar {
display: none;
}
main {
flex-direction: column;
}
.content {
padding: 10px;
}
.fonts-grid {
grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
gap: 10px;
}
}
</style>
</head>
<body>
<header>
<h1>Font Organizer</h1>
</header>
<div id="app-container">
<main>
<!-- Sidebar -->
<div class="sidebar">
<h2>Collections</h2>
<ul id="collection-list">
<!-- Dynamic Collections -->
</ul>
<button id="add-collection-btn">+ Add Collection</button>
</div>
<!-- Content Area -->
<div class="content">
<div class="upload-section" id="upload-section">
<p>Drag & Drop Fonts Here or Click to Upload</p>
<input type="file" id="font-input" multiple accept=".ttf,.otf,.woff,.woff2,.eot,.svg">
</div>
<div class="collections" id="current-collection">
<h3>Select a collection to organize fonts</h3>
</div>
<div class="fonts-grid" id="fonts-grid">
<!-- Uploaded Fonts -->
</div>
</div>
</main>
<!-- Download Section -->
<div class="download-section">
<button id="download-zip-btn">Download Organized Fonts as ZIP</button>
<div class="instructions" id="instructions" style="display: none;">
<p>After downloading, right-click the ZIP file and select "Extract All" or use your preferred unzipping tool.</p>
</div>
</div>
</div>
<!-- Modal for Adding Collection -->
<div class="modal" id="modal">
<div class="modal-content">
<button class="close-modal" id="close-modal-btn">×</button>
<h3>Add New Collection</h3>
<input type="text" id="collection-name-input" placeholder="Collection Name">
<button id="save-collection-btn">Save</button>
</div>
</div>
<!-- Modal for Font Preview -->
<div class="modal" id="preview-modal">
<div class="preview-modal-content">
<button class="close-preview-btn" id="close-preview-btn">×</button>
<h3 id="preview-font-name">Font Preview</h3>
<div class="preview-sample" id="preview-sample">
The quick brown fox jumps over the lazy dog.
</div>
<div class="type-mode-input">
<input type="text" id="custom-text-input" placeholder="Type your custom text here..." />
</div>
</div>
</div>
<script>
// JavaScript Code for Functionality
// DOM Elements
const uploadSection = document.getElementById('upload-section');
const fontInput = document.getElementById('font-input');
const fontsGrid = document.getElementById('fonts-grid');
const addCollectionBtn = document.getElementById('add-collection-btn');
const modal = document.getElementById('modal');
const saveCollectionBtn = document.getElementById('save-collection-btn');
const collectionNameInput = document.getElementById('collection-name-input');
const collectionList = document.getElementById('collection-list');
const currentCollection = document.getElementById('current-collection');
const downloadZipBtn = document.getElementById('download-zip-btn');
const instructions = document.getElementById('instructions');
const closeModalBtn = document.getElementById('close-modal-btn');
// Preview Modal Elements
const previewModal = document.getElementById('preview-modal');
const closePreviewBtn = document.getElementById('close-preview-btn');
const previewFontName = document.getElementById('preview-font-name');
const previewSample = document.getElementById('preview-sample');
const customTextInput = document.getElementById('custom-text-input');
let collections = {};
let currentColl = null;
let fonts = [];
let fontUrls = {}; // To store dynamically generated font URLs
// Initialize with Default Collection
collections['Uncategorized'] = [];
currentColl = 'Uncategorized';
renderCollections();
// Event Listeners for Upload
uploadSection.addEventListener('click', () => {
fontInput.click();
});
fontInput.addEventListener('change', (e) => {
handleFiles(e.target.files);
});
// Drag & Drop Events
uploadSection.addEventListener('dragover', (e) => {
e.preventDefault();
uploadSection.classList.add('dragover');
});
uploadSection.addEventListener('dragleave', (e) => {
e.preventDefault();
uploadSection.classList.remove('dragover');
});
uploadSection.addEventListener('drop', (e) => {
e.preventDefault();
uploadSection.classList.remove('dragover');
if (e.dataTransfer.files) {
handleFiles(e.dataTransfer.files);
}
});
// Handle Uploaded Files
function handleFiles(files) {
[...files].forEach(file => {
if (isFontFile(file)) {
const reader = new FileReader();
reader.onload = (e) => {
const fontData = {
id: generateUUID(),
name: file.name,
file: file,
data: e.target.result,
collection: currentColl
};
fonts.push(fontData);
collections[currentColl].push(fontData);
renderFonts();
};
reader.readAsArrayBuffer(file);
} else {
alert(`${file.name} is not a supported font file.`);
}
});
}
function isFontFile(file) {
const fontExtensions = ['.ttf', '.otf', '.woff', '.woff2', '.eot', '.svg'];
return fontExtensions.some(ext => file.name.toLowerCase().endsWith(ext));
}
// Generate UUID for each font
function generateUUID() {
// Simple UUID generator
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
const r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
// Render Collections in Sidebar
function renderCollections() {
collectionList.innerHTML = '';
for (let coll in collections) {
const li = document.createElement('li');
li.textContent = coll;
if (coll === currentColl) {
li.classList.add('active');
}
// Switch Collection on Click
li.addEventListener('click', () => {
currentColl = coll;
renderCollections();
renderFonts();
renderCurrentCollection();
});
collectionList.appendChild(li);
}
}
// Render Fonts in Content Area
function renderFonts() {
fontsGrid.innerHTML = '';
collections[currentColl].forEach((font, index) => {
const card = document.createElement('div');
card.classList.add('font-card');
card.draggable = true;
card.textContent = font.name;
// Assign unique ID for each card
card.setAttribute('data-id', font.id);
// Create Delete Button
const deleteBtn = document.createElement('button');
deleteBtn.classList.add('delete-btn');
deleteBtn.innerHTML = '×';
card.appendChild(deleteBtn);
// Delete Font Event
deleteBtn.addEventListener('click', (e) => {
e.stopPropagation(); // Prevent triggering other events
deleteFont(font.id);
});
// Drag Events
card.addEventListener('dragstart', (e) => {
e.dataTransfer.setData('text/plain', font.id);
setTimeout(() => {
card.classList.add('dragging');
}, 0);
});
card.addEventListener('dragend', () => {
card.classList.remove('dragging');
});
// Double-Click Event for Preview
card.addEventListener('dblclick', () => {
toggleFontPreview(font);
});
fontsGrid.appendChild(card);
});
}
// Toggle Font Preview
let currentPreviewFontId = null;
function toggleFontPreview(font) {
if (currentPreviewFontId === font.id) {
// Hide Preview
closePreview();
} else {
// Show Preview
showPreview(font);
}
}
function showPreview(font) {
// If another preview is open, close it first
if (currentPreviewFontId) {
closePreview();
}
currentPreviewFontId = font.id;
// Generate a Blob URL for the font
const blob = new Blob([font.file], { type: getMimeType(font.file.name) });
const fontURL = URL.createObjectURL(blob);
fontUrls[font.id] = fontURL;
// Create @font-face dynamically
const fontFace = `
@font-face {
font-family: 'preview-${font.id}';
src: url('${fontURL}') format('${getFontFormat(font.file.name)}');
}
`;
// Append to head
const style = document.createElement('style');
style.id = `font-style-${font.id}`;
style.innerHTML = fontFace;
document.head.appendChild(style);
// Apply font to preview sample
previewSample.style.fontFamily = `'preview-${font.id}'`;
previewSample.textContent = 'The quick brown fox jumps over the lazy dog.';
previewFontName.textContent = font.name;
// Show Modal and Blur Background
previewModal.style.display = 'flex';
document.getElementById('app-container').classList.add('blurred');
// Set focus to custom text input
customTextInput.value = '';
customTextInput.focus();
}
function closePreview() {
if (currentPreviewFontId) {
// Remove @font-face
const style = document.getElementById(`font-style-${currentPreviewFontId}`);
if (style) {
style.remove();
}
// Revoke Object URL
if (fontUrls[currentPreviewFontId]) {
URL.revokeObjectURL(fontUrls[currentPreviewFontId]);
delete fontUrls[currentPreviewFontId];
}
currentPreviewFontId = null;
}
// Reset preview sample
previewSample.style.fontFamily = '';
previewSample.textContent = 'The quick brown fox jumps over the lazy dog.';
previewFontName.textContent = 'Font Preview';
// Hide Modal and Remove Blur
previewModal.style.display = 'none';
document.getElementById('app-container').classList.remove('blurred');
// Clear custom text input
customTextInput.value = '';
}
// Utility to get MIME type based on file extension
function getMimeType(filename) {
const ext = filename.split('.').pop().toLowerCase();
const mimeTypes = {
'ttf': 'font/ttf',
'otf': 'font/otf',
'woff': 'font/woff',
'woff2': 'font/woff2',
'eot': 'application/vnd.ms-fontobject',
'svg': 'image/svg+xml'
};
return mimeTypes[ext] || 'application/octet-stream';
}
// Utility to get font format
function getFontFormat(filename) {
const ext = filename.split('.').pop().toLowerCase();
const formats = {
'ttf': 'truetype',
'otf': 'opentype',
'woff': 'woff',
'woff2': 'woff2',
'eot': 'embedded-opentype',
'svg': 'svg'
};
return formats[ext] || 'truetype';
}
// Close Preview Modal Event
closePreviewBtn.addEventListener('click', () => {
closePreview();
});
// Close Preview Modal when clicking outside content
previewModal.addEventListener('click', (e) => {
if (e.target === previewModal) {
closePreview();
}
});
// Handle Custom Text Input for Type Mode
customTextInput.addEventListener('input', (e) => {
const text = e.target.value.trim() || 'The quick brown fox jumps over the lazy dog.';
previewSample.textContent = text;
});
// Render Current Collection Info
function renderCurrentCollection() {
currentCollection.innerHTML = '';
if (currentColl === 'Uncategorized') {
currentCollection.innerHTML = '<h3>Uncategorized Fonts</h3>';
} else {
const heading = document.createElement('h3');
heading.textContent = `Collection: ${currentColl}`;
currentCollection.appendChild(heading);
}
}
// Add Collection
addCollectionBtn.addEventListener('click', () => {
modal.style.display = 'flex';
collectionNameInput.value = '';
collectionNameInput.focus();
});
saveCollectionBtn.addEventListener('click', () => {
const name = collectionNameInput.value.trim();
if (name && !collections[name]) {
collections[name] = [];
currentColl = name;
renderCollections();
renderFonts();
renderCurrentCollection();
modal.style.display = 'none';
} else if (collections[name]) {
alert('Collection name already exists.');
} else {
alert('Please enter a valid collection name.');
}
});
// Close Modal when clicking outside content or on close button
window.addEventListener('click', (e) => {
if (e.target === modal) {
modal.style.display = 'none';
}
});
closeModalBtn.addEventListener('click', () => {
modal.style.display = 'none';
});
// Delete Font from Collection
function deleteFont(fontId) {
// Find the collection containing this font
for (let coll in collections) {
const index = collections[coll].findIndex(font => font.id === fontId);
if (index !== -1) {
// Remove from fonts array
fonts = fonts.filter(font => font.id !== fontId);
// Remove from collection
collections[coll].splice(index, 1);
break;
}
}
renderFonts();
}
// Download ZIP
downloadZipBtn.addEventListener('click', async () => {
if (fonts.length === 0) {
alert('No fonts to download.');
return;
}
const zip = new JSZip();
// Supported font extensions
const supportedExtensions = ['.ttf', '.otf', '.woff', '.woff2', '.eot', '.svg'];
// Create a set to track unique file names to avoid duplicates in the ZIP
const fileNamesSet = new Set();
fonts.forEach((font) => {
const ext = '.' + font.name.split('.').pop().toLowerCase();
if (supportedExtensions.includes(ext)) {
let uniqueName = font.name;
// Ensure unique file names in the ZIP
let counter = 1;
while (fileNamesSet.has(uniqueName)) {
const nameWithoutExt = font.name.substring(0, font.name.lastIndexOf('.')) || font.name;
uniqueName = `${nameWithoutExt} (${counter})${ext}`;
counter++;
}
fileNamesSet.add(uniqueName);
zip.file(uniqueName, font.file);
}
});
try {
const content = await zip.generateAsync({ type: "blob" });
const a = document.createElement('a');
a.href = URL.createObjectURL(content);
a.download = "organized_fonts.zip";
a.click();
instructions.style.display = 'block';
setTimeout(() => {
instructions.style.display = 'none';
}, 5000);
} catch (error) {
console.error('Error generating ZIP:', error);
alert('There was an error generating the ZIP file.');
}
});
// Initial Render
renderFonts();
renderCurrentCollection();
</script>
</body>
</html>
Explanation of Changes:
-
Download ZIP Functionality:
- Removed Folder Structure: Instead of creating separate folders for each collection within the ZIP, all font files are now added directly to the root of the ZIP.
- File Type Filtering: Although the upload section already restricts file types to fonts, an additional check ensures that only supported font file extensions are included in the ZIP.
- Unique File Names: To prevent duplicate file names which can cause conflicts within the ZIP, a mechanism is added to rename files if duplicates are detected by appending a counter (e.g.,
FontName (1).ttf).
// Download ZIP
downloadZipBtn.addEventListener('click', async () => {
if (fonts.length === 0) {
alert('No fonts to download.');
return;
}
const zip = new JSZip();
// Supported font extensions
const supportedExtensions = ['.ttf', '.otf', '.woff', '.woff2', '.eot', '.svg'];
// Create a set to track unique file names to avoid duplicates in the ZIP
const fileNamesSet = new Set();
fonts.forEach((font) => {
const ext = '.' + font.name.split('.').pop().toLowerCase();
if (supportedExtensions.includes(ext)) {
let uniqueName = font.name;
// Ensure unique file names in the ZIP
let counter = 1;
while (fileNamesSet.has(uniqueName)) {
const nameWithoutExt = font.name.substring(0, font.name.lastIndexOf('.')) || font.name;
uniqueName = `${nameWithoutExt} (${counter})${ext}`;
counter++;
}
fileNamesSet.add(uniqueName);
zip.file(uniqueName, font.file);
}
});
try {
const content = await zip.generateAsync({ type: "blob" });
const a = document.createElement('a');
a.href = URL.createObjectURL(content);
a.download = "organized_fonts.zip";
a.click();
instructions.style.display = 'block';
setTimeout(() => {
instructions.style.display = 'none';
}, 5000);
} catch (error) {
console.error('Error generating ZIP:', error);
alert('There was an error generating the ZIP file.');
}
});
-
Enhanced User Experience:
- Instructions Display: After downloading, a temporary instruction message appears to guide the user on how to extract the ZIP file.
- Unique File Naming: Helps prevent overwriting files with the same name by ensuring each file in the ZIP is uniquely named.
-
Code Clean-Up and Optimization:
- Removed the section that creates folders for each collection within the ZIP.
Final Notes:
- Font Previews: The preview functionality remains unchanged, allowing users to preview fonts within the application before downloading.
- Collections Management: Users can still organize their fonts into collections for better management within the application, but these collections do not affect the structure of the downloaded ZIP file.
Feel free to integrate this updated code into your project. This should meet your requirements of having a ZIP file containing only the font files at the root level without any nested folders.