json-dropdown-tools
Version:
A tool to generate dropdown menus from JSON as HTML or JS modules
47 lines (35 loc) • 1.23 kB
JavaScript
import fs from "fs";
// Recursively collect all IDs from the JSON
function collectIds(obj, result = []) {
if (!obj) return result;
if (obj.type === "separator") return result;
const id = obj.id || obj.label?.toLowerCase().replace(/\s+/g, "-").replace(/[^a-z0-9\-]/g, "");
if (id) result.push(id);
if (obj.items) obj.items.forEach(child => collectIds(child, result));
return result;
}
// Generate CSS for all IDs plus default dropdown behavior
function generateCss(json) {
const ids = collectIds(json);
let css = "";
// Empty scaffold for each ID
ids.forEach(id => {
css += `#${id} {\n /* customize your styles here */\n}\n\n`;
});
// Default dropdown behavior
css += `
ul { list-style: none; padding-left: 20px; margin: 0; }
li { cursor: pointer; margin: 4px 0; }
li > ul { display: none; margin-top: 4px; }
li.open > ul { display: block; }
.separator { border-top: 1px solid #ccc; margin: 4px 0; }
`;
return css;
}
// Write CSS to file
function writeCssToFile(json, outputPath) {
const cssString = generateCss(json);
fs.writeFileSync(outputPath, cssString, "utf-8");
console.log(`✅ CSS file generated at ${outputPath}`);
}
export { collectIds, generateCss, writeCssToFile };