File size: 12,858 Bytes
eebc40f |
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 |
#!/usr/bin/env node
import fs from 'fs/promises';
import path from 'path';
import { fileURLToPath } from 'url';
import opentype from 'opentype.js';
import cliProgress from 'cli-progress';
import chalk from 'chalk';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Configuration
const FONTS_DIR = path.join(__dirname, 'output', 'fonts');
const SVGS_DIR = path.join(__dirname, 'output', 'svgs');
const FONT_INDEX_PATH = path.join(__dirname, 'input', 'font-index.json');
// Progress bar configuration
const progressBar = new cliProgress.SingleBar({
format: chalk.cyan('{bar}') + ' | {percentage}% | {value}/{total} | {fontName}',
barCompleteChar: '\u2588',
barIncompleteChar: '\u2591',
hideCursor: true
});
/**
* Valide la qualité d'un SVG
*/
function validateSVGQuality(svg, fontFamily) {
const issues = [];
if (!svg || svg.trim().length === 0) {
issues.push('Empty SVG');
return { valid: false, issues };
}
if (!svg.includes('<path')) {
issues.push('No path elements found');
return { valid: false, issues };
}
const pathMatch = svg.match(/<path[^>]*d=["']([^"']+)["']/);
if (!pathMatch || !pathMatch[1] || pathMatch[1].trim().length === 0) {
issues.push('Empty path data');
return { valid: false, issues };
}
const pathData = pathMatch[1];
if (pathData.length < 10) {
issues.push('Path data too simple');
return { valid: false, issues };
}
if (!svg.includes('xmlns="http://www.w3.org/2000/svg"')) {
issues.push('Structure SVG invalide');
return { valid: false, issues };
}
return { valid: true, issues: [] };
}
/**
* Génère un SVG de la lettre A à partir d'une police
*/
async function generateLetterASVG(fontPath, fontFamily) {
try {
const fontBuffer = await fs.readFile(fontPath);
const font = opentype.parse(fontBuffer.buffer);
const glyph = font.charToGlyph('A');
if (!glyph || !glyph.path) {
throw new Error('Glyph A not found or without path');
}
const SVG_SIZE = 80;
const fontSize = 60;
const tempPath = glyph.getPath(0, 0, fontSize);
const bbox = tempPath.getBoundingBox();
if (!bbox || bbox.x1 === undefined || bbox.x2 === undefined ||
bbox.y1 === undefined || bbox.y2 === undefined) {
throw new Error('Bounding box invalide');
}
const glyphWidth = bbox.x2 - bbox.x1;
const glyphHeight = bbox.y2 - bbox.y1;
if (glyphWidth <= 0 || glyphHeight <= 0) {
throw new Error('Dimensions de glyphe invalides');
}
if (glyphWidth < 5 || glyphHeight < 5) {
throw new Error('Glyphe trop petit (possiblement vide)');
}
const centerX = SVG_SIZE / 2;
const centerY = SVG_SIZE / 2;
const offsetX = centerX - (bbox.x1 + glyphWidth / 2);
const offsetY = centerY - (bbox.y1 + glyphHeight / 2);
const adjustedPath = glyph.getPath(offsetX, offsetY, fontSize);
const svgPathData = adjustedPath.toPathData(2);
if (!svgPathData || svgPathData.trim().length === 0) {
throw new Error('Empty path data après génération');
}
const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${SVG_SIZE} ${SVG_SIZE}" width="${SVG_SIZE}" height="${SVG_SIZE}">
<path d="${svgPathData}" fill="currentColor"/>
</svg>`;
const validation = validateSVGQuality(svg, fontFamily);
if (!validation.valid) {
throw new Error(`SVG de mauvaise qualité: ${validation.issues.join(', ')}`);
}
return {
svg,
width: SVG_SIZE,
height: SVG_SIZE,
fontMetrics: {
unitsPerEm: font.unitsPerEm,
ascender: font.ascender,
descender: font.descender
}
};
} catch (error) {
console.error(`❌ Error generating SVG for ${fontFamily}:`, error.message);
return null;
}
}
/**
* Génère un SVG de phrase à partir d'une police (vectorisé)
*/
async function generateSentenceSVG(fontPath, fontFamily) {
try {
const fontBuffer = await fs.readFile(fontPath);
const font = opentype.parse(fontBuffer.buffer);
const loremText = 'Lorem Ipsum';
const fontSize = 24;
const padding = 10;
// Vectoriser le texte complet en une seule opération
const textPath = font.getPath(loremText, 0, 0, fontSize);
const bbox = textPath.getBoundingBox();
if (!bbox || bbox.x1 === undefined || bbox.x2 === undefined ||
bbox.y1 === undefined || bbox.y2 === undefined) {
throw new Error('Bounding box invalide pour le texte');
}
const textWidth = bbox.x2 - bbox.x1;
const textHeight = bbox.y2 - bbox.y1;
if (textWidth <= 0 || textHeight <= 0) {
throw new Error('Dimensions de texte invalides');
}
// Calculer les dimensions du SVG avec padding
const margin = padding;
const svgWidth = Math.ceil(textWidth) + (margin * 2);
const svgHeight = Math.ceil(textHeight) + (margin * 2);
// Centrer le texte dans le SVG
const offsetX = margin - bbox.x1;
const offsetY = margin - bbox.y1;
// Ajuster le chemin avec les offsets
const adjustedPath = font.getPath(loremText, offsetX, offsetY, fontSize);
const svgPathData = adjustedPath.toPathData(2);
if (!svgPathData || svgPathData.trim().length === 0) {
throw new Error('Empty path data après génération');
}
const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${svgWidth} ${svgHeight}" width="${svgWidth}" height="${svgHeight}">
<path d="${svgPathData}" fill="currentColor"/>
</svg>`;
// Valider la qualité du SVG
const validation = validateSVGQuality(svg, fontFamily);
if (!validation.valid) {
throw new Error(`SVG de mauvaise qualité: ${validation.issues.join(', ')}`);
}
return {
svg,
width: svgWidth,
height: svgHeight,
text: loremText,
measuredWidth: textWidth,
fontMetrics: {
unitsPerEm: font.unitsPerEm,
ascender: font.ascender,
descender: font.descender
}
};
} catch (error) {
console.error(`❌ Error generating sentence SVG for ${fontFamily}:`, error.message);
return null;
}
}
/**
* Traite une famille de polices
*/
async function processFontFamily(fontId, fontData, currentIndex, totalFamilies) {
const fontDir = path.join(FONTS_DIR, fontId);
try {
// Chercher le fichier TTF principal (peut être .ttf ou .truetype)
const files = await fs.readdir(fontDir);
const ttfFile = files.find(f => f.endsWith('.ttf') || f.endsWith('.truetype'));
if (!ttfFile) {
throw new Error('TTF file not found');
}
const fontPath = path.join(fontDir, ttfFile);
// Générer le SVG de la lettre A
const letterResult = await generateLetterASVG(fontPath, fontData.family);
if (!letterResult) {
throw new Error('Failed de génération du SVG de la lettre A');
}
// Sauvegarder le SVG de la lettre A
const letterSvgPath = path.join(SVGS_DIR, `${fontId}_a.svg`);
await fs.writeFile(letterSvgPath, letterResult.svg, 'utf-8');
// Générer le SVG de la phrase
const sentenceResult = await generateSentenceSVG(fontPath, fontData.family);
if (!sentenceResult) {
throw new Error('Failed de génération du SVG de la phrase');
}
// Sauvegarder le SVG de la phrase
const sentenceSvgPath = path.join(SVGS_DIR, `${fontId}_sentence.svg`);
await fs.writeFile(sentenceSvgPath, sentenceResult.svg, 'utf-8');
return {
success: true,
fontId,
fontFamily: fontData.family,
letterSvg: letterSvgPath,
sentenceSvg: sentenceSvgPath,
letterDimensions: {
width: letterResult.width,
height: letterResult.height
},
sentenceDimensions: {
width: sentenceResult.width,
height: sentenceResult.height,
measuredWidth: sentenceResult.measuredWidth
},
fontMetrics: letterResult.fontMetrics,
sentenceFontMetrics: sentenceResult.fontMetrics
};
} catch (error) {
return {
success: false,
fontId,
fontFamily: fontData.family,
error: error.message
};
}
}
/**
* Fonction principale
*/
async function main() {
try {
console.log(chalk.blue.bold('🎨 Generating SVGs pour toutes les polices...\n'));
// Check that file d'index existe
try {
await fs.access(FONT_INDEX_PATH);
} catch {
throw new Error(`Fichier d'index non trouvé : ${FONT_INDEX_PATH}`);
}
// Create output directory
await fs.mkdir(SVGS_DIR, { recursive: true });
console.log(chalk.green(`📁 Directory created : ${SVGS_DIR}`));
// Read file d'index des polices
console.log(chalk.yellow('📖 Reading file font-index.json...'));
const fontIndexData = JSON.parse(await fs.readFile(FONT_INDEX_PATH, 'utf8'));
const fontIds = Object.keys(fontIndexData);
console.log(chalk.cyan(`📊 ${fontIds.length} familles de polices trouvées\n`));
const results = [];
let successCount = 0;
let errorCount = 0;
// Traiter chaque famille de polices
for (let i = 0; i < fontIds.length; i++) {
const fontId = fontIds[i];
const fontData = fontIndexData[fontId];
console.log(chalk.magenta(`\n🔤 [${i + 1}/${fontIds.length}] Traitement de "${fontData.family}" (${fontId})`));
// Démarrer la barre de progression
progressBar.start(2, 0, { fontName: fontData.family });
const result = await processFontFamily(fontId, fontData, i, fontIds.length);
progressBar.update(2, { fontName: fontData.family });
progressBar.stop();
results.push(result);
if (result.success) {
successCount++;
console.log(chalk.green(`✅ SVGs générés pour "${fontData.family}"`));
console.log(chalk.blue(` - Lettre A: ${result.letterDimensions.width}x${result.letterDimensions.height}`));
console.log(chalk.blue(` - Phrase: ${result.sentenceDimensions.width}x${result.sentenceDimensions.height} (largeur mesurée: ${result.sentenceDimensions.measuredWidth.toFixed(1)}px)`));
} else {
errorCount++;
console.log(chalk.red(`❌ Error for "${fontData.family}": ${result.error}`));
}
// Afficher le progrès global
const progress = ((i + 1) / fontIds.length) * 100;
console.log(chalk.blue(`📈 Progrès global : ${i + 1}/${fontIds.length} familles (${progress.toFixed(1)}%)`));
console.log(chalk.blue(`📊 Success: ${successCount}, Erreurs: ${errorCount}\n`));
}
// Créer le manifest des résultats
const manifest = {};
const successfulResults = results.filter(r => r.success);
for (const result of successfulResults) {
manifest[result.fontFamily] = {
id: result.fontId,
family: 'sans-serif', // Par défaut
images: {
A: `svgs/${result.fontId}_a.svg`,
sentence: `svgs/${result.fontId}_sentence.svg`
},
svg: {
A: {
path: `svgs/${result.fontId}_a.svg`,
width: result.letterDimensions.width,
height: result.letterDimensions.height,
viewBox: `0 0 ${result.letterDimensions.width} ${result.letterDimensions.height}`
},
sentence: {
path: `svgs/${result.fontId}_sentence.svg`,
width: result.sentenceDimensions.width,
height: result.sentenceDimensions.height,
viewBox: `0 0 ${result.sentenceDimensions.width} ${result.sentenceDimensions.height}`,
measuredWidth: result.sentenceDimensions.measuredWidth
}
},
fontMetrics: result.fontMetrics,
sentenceFontMetrics: result.sentenceFontMetrics
};
}
// Sauvegarder le manifest
const manifestPath = path.join(__dirname, 'output', 'font_manifest.json');
await fs.writeFile(manifestPath, JSON.stringify(manifest, null, 2), 'utf-8');
console.log(chalk.green.bold('🎉 Génération des SVGs terminée !'));
console.log(chalk.cyan('📊 Summary :'));
console.log(chalk.white(` - ${successCount} familles traitées avec succès`));
console.log(chalk.white(` - ${errorCount} erreurs`));
console.log(chalk.white(` - ${successCount * 2} fichiers SVG générés`));
console.log(chalk.white(` - Dossier de sortie : ${SVGS_DIR}`));
console.log(chalk.white(` - Manifest : ${manifestPath}`));
if (errorCount > 0) {
console.log(chalk.red('\n❌ Polices avec erreurs :'));
results
.filter(r => !r.success)
.forEach(r => console.log(chalk.red(` - ${r.fontFamily}: ${r.error}`)));
}
} catch (error) {
console.error(chalk.red('❌ Erreur :'), error.message);
process.exit(1);
}
}
// Lancer le script
main();
|