Files
Stirling-PDF/frontend/editor/scripts/generate-icons.js
T

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

250 lines
7.5 KiB
JavaScript
Raw Normal View History

#!/usr/bin/env node
const { icons } = require("@iconify-json/material-symbols");
const fs = require("fs");
const path = require("path");
// Check for verbose flag
2026-04-17 10:50:16 +01:00
const isVerbose =
process.argv.includes("--verbose") || process.argv.includes("-v");
// Logging functions
const info = (message) => console.log(message);
const debug = (message) => {
if (isVerbose) {
console.log(message);
}
};
// Function to scan codebase for LocalIcon usage
function scanForUsedIcons() {
const usedIcons = new Set();
const srcDir = path.join(__dirname, "..", "src");
info("🔍 Scanning codebase for LocalIcon usage...");
if (!fs.existsSync(srcDir)) {
console.error("❌ Source directory not found:", srcDir);
process.exit(1);
}
// Recursively scan all .tsx and .ts files
function scanDirectory(dir) {
const files = fs.readdirSync(dir);
files.forEach((file) => {
const filePath = path.join(dir, file);
const stat = fs.statSync(filePath);
if (stat.isDirectory()) {
scanDirectory(filePath);
} else if (file.endsWith(".tsx") || file.endsWith(".ts")) {
const content = fs.readFileSync(filePath, "utf8");
// Match LocalIcon usage: <LocalIcon icon="icon-name" ...>
2026-04-17 10:50:16 +01:00
const localIconMatches = content.match(
/<LocalIcon\s+[^>]*icon="([^"]+)"/g,
);
if (localIconMatches) {
localIconMatches.forEach((match) => {
const iconMatch = match.match(/icon="([^"]+)"/);
if (iconMatch) {
usedIcons.add(iconMatch[1]);
2026-04-17 10:50:16 +01:00
debug(
` Found: ${iconMatch[1]} in ${path.relative(srcDir, filePath)}`,
);
}
});
}
// Match LocalIcon usage: <LocalIcon icon='icon-name' ...>
2026-04-17 10:50:16 +01:00
const localIconSingleQuoteMatches = content.match(
/<LocalIcon\s+[^>]*icon='([^']+)'/g,
);
if (localIconSingleQuoteMatches) {
localIconSingleQuoteMatches.forEach((match) => {
const iconMatch = match.match(/icon='([^']+)'/);
if (iconMatch) {
usedIcons.add(iconMatch[1]);
2026-04-17 10:50:16 +01:00
debug(
` Found: ${iconMatch[1]} in ${path.relative(srcDir, filePath)}`,
);
}
});
}
// Match old material-symbols-rounded spans: <span className="material-symbols-rounded">icon-name</span>
2026-04-17 10:50:16 +01:00
const spanMatches = content.match(
/<span[^>]*className="[^"]*material-symbols-rounded[^"]*"[^>]*>([^<]+)<\/span>/g,
);
if (spanMatches) {
spanMatches.forEach((match) => {
const iconMatch = match.match(/>([^<]+)<\/span>/);
if (iconMatch && iconMatch[1].trim()) {
const iconName = iconMatch[1].trim();
usedIcons.add(iconName);
2026-04-17 10:50:16 +01:00
debug(
` Found (legacy): ${iconName} in ${path.relative(srcDir, filePath)}`,
);
}
});
}
// Match Icon component usage: <Icon icon="material-symbols:icon-name" ...>
2026-04-17 10:50:16 +01:00
const iconMatches = content.match(
/<Icon\s+[^>]*icon="material-symbols:([^"]+)"/g,
);
if (iconMatches) {
iconMatches.forEach((match) => {
const iconMatch = match.match(/icon="material-symbols:([^"]+)"/);
if (iconMatch) {
usedIcons.add(iconMatch[1]);
2026-04-17 10:50:16 +01:00
debug(
` Found (Icon): ${iconMatch[1]} in ${path.relative(srcDir, filePath)}`,
);
}
});
}
// Match icon config usage: icon: 'icon-name' or icon: "icon-name"
2026-04-17 10:50:16 +01:00
const iconPropertyMatches = content.match(
/icon:\s*(['"])([a-z0-9-]+)\1/g,
);
if (iconPropertyMatches) {
iconPropertyMatches.forEach((match) => {
const iconMatch = match.match(/icon:\s*(['"])([a-z0-9-]+)\1/);
if (iconMatch) {
usedIcons.add(iconMatch[2]);
2026-04-17 10:50:16 +01:00
debug(
` Found (config): ${iconMatch[2]} in ${path.relative(srcDir, filePath)}`,
);
}
});
}
}
});
}
scanDirectory(srcDir);
const iconArray = Array.from(usedIcons).sort();
info(`📋 Found ${iconArray.length} unique icons across codebase`);
return iconArray;
}
2025-08-26 15:30:58 +01:00
// Main async function
async function main() {
// Auto-detect used icons
const usedIcons = scanForUsedIcons();
2025-08-26 15:30:58 +01:00
// Check if we need to regenerate (compare with existing)
2026-04-17 10:50:16 +01:00
const outputPath = path.join(
__dirname,
"..",
"src",
"assets",
"material-symbols-icons.json",
);
2025-08-26 15:30:58 +01:00
let needsRegeneration = true;
2025-08-26 15:30:58 +01:00
if (fs.existsSync(outputPath)) {
try {
const existingSet = JSON.parse(fs.readFileSync(outputPath, "utf8"));
2025-08-26 15:30:58 +01:00
const existingIcons = Object.keys(existingSet.icons || {}).sort();
const currentIcons = [...usedIcons].sort();
2025-08-26 15:30:58 +01:00
if (JSON.stringify(existingIcons) === JSON.stringify(currentIcons)) {
needsRegeneration = false;
info(
`✅ Icon set already up-to-date (${usedIcons.length} icons, ${Math.round(fs.statSync(outputPath).size / 1024)}KB)`,
);
2025-08-26 15:30:58 +01:00
}
2025-09-05 12:16:17 +01:00
} catch {
2025-08-26 15:30:58 +01:00
// If we can't parse existing file, regenerate
needsRegeneration = true;
}
}
2025-08-26 15:30:58 +01:00
if (!needsRegeneration) {
info("🎉 No regeneration needed!");
2025-08-26 15:30:58 +01:00
process.exit(0);
}
2025-08-26 15:30:58 +01:00
info(`🔍 Extracting ${usedIcons.length} icons from Material Symbols...`);
2025-08-26 15:30:58 +01:00
// Dynamic import of ES module
const { getIcons } = await import("@iconify/utils");
2025-08-26 15:30:58 +01:00
// Extract only our used icons from the full set
const extractedIcons = getIcons(icons, usedIcons);
2025-08-26 15:30:58 +01:00
if (!extractedIcons) {
console.error("❌ Failed to extract icons");
2025-08-26 15:30:58 +01:00
process.exit(1);
}
2025-08-26 15:30:58 +01:00
// Check for missing icons
const extractedIconNames = Object.keys(extractedIcons.icons || {});
2026-04-17 10:50:16 +01:00
const missingIcons = usedIcons.filter(
(icon) => !extractedIconNames.includes(icon),
);
2025-08-26 15:30:58 +01:00
if (missingIcons.length > 0) {
2026-04-17 10:50:16 +01:00
info(
`⚠️ Missing icons (${missingIcons.length}): ${missingIcons.join(", ")}`,
);
info(
"💡 These icons don't exist in Material Symbols. Please use available alternatives.",
);
2025-08-26 15:30:58 +01:00
}
2025-08-26 15:30:58 +01:00
// Create output directory
const outputDir = path.join(__dirname, "..", "src", "assets");
2025-08-26 15:30:58 +01:00
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true });
}
2025-08-26 15:30:58 +01:00
// Write the extracted icon set to a file (outputPath already defined above)
fs.writeFileSync(outputPath, JSON.stringify(extractedIcons, null, 2));
2026-04-17 10:50:16 +01:00
info(
`✅ Successfully extracted ${Object.keys(extractedIcons.icons || {}).length} icons`,
);
info(
`📦 Bundle size: ${Math.round(JSON.stringify(extractedIcons).length / 1024)}KB`,
);
2025-08-26 15:30:58 +01:00
info(`💾 Saved to: ${outputPath}`);
2025-08-26 15:30:58 +01:00
// Generate TypeScript types
const typesContent = `// Auto-generated icon types
// This file is automatically generated by scripts/generate-icons.js
// Do not edit manually - changes will be overwritten
export type MaterialSymbolIcon = ${usedIcons.map((icon) => `'${icon}'`).join(" | ")};
export interface IconSet {
prefix: string;
icons: Record<string, unknown>;
width?: number;
height?: number;
}
// Re-export the icon set as the default export with proper typing
declare const iconSet: IconSet;
export default iconSet;
`;
const typesPath = path.join(outputDir, "material-symbols-icons.d.ts");
2025-08-26 15:30:58 +01:00
fs.writeFileSync(typesPath, typesContent);
info(`📝 Generated types: ${typesPath}`);
info(`🎉 Icon extraction complete!`);
}
2025-08-26 15:30:58 +01:00
// Run the main function
main().catch((error) => {
console.error("❌ Script failed:", error);
2025-08-26 15:30:58 +01:00
process.exit(1);
});