@ikona/cli
Version:
371 lines (352 loc) • 11.2 kB
JavaScript
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/icons/index.ts
var icons_exports = {};
__export(icons_exports, {
generateSprite: () => generateSprite
});
module.exports = __toCommonJS(icons_exports);
// src/icons/generate-sprite.ts
var import_fs_extra4 = __toESM(require("fs-extra"));
var import_glob = require("glob");
// src/icons/generate-icon-files.ts
var import_crypto = __toESM(require("crypto"));
var import_fs_extra3 = __toESM(require("fs-extra"));
var path2 = __toESM(require("path"));
// src/utils/validations.ts
var import_fs_extra = __toESM(require("fs-extra"));
var import_node_path = require("path");
// src/utils/hash.ts
function addHashToSpritePath(path4, hash) {
return path4.replace(/\.svg$/, `.${hash}.svg`);
}
// src/utils/validations.ts
function clear(folderPath) {
import_fs_extra.default.readdir(folderPath, (err, files) => {
if (err) {
console.error("Error reading folder:", err);
return;
}
const svgFiles = files.filter(
(file) => (0, import_node_path.extname)(file).toLowerCase() === ".svg" && file.startsWith("sprite")
);
svgFiles.forEach((svgFile) => {
const filePath = (0, import_node_path.join)(folderPath, svgFile);
import_fs_extra.default.unlink(filePath, (err2) => {
if (err2) {
console.error(`Error removing file ${filePath}:`, err2);
} else {
console.log(`Removed file: ${filePath}`);
}
});
});
});
}
async function writeIfChanged({
filepath,
newContent,
hash,
force
}) {
let _filepath = filepath;
if (hash) {
_filepath = addHashToSpritePath(filepath, hash);
}
const currentContent = await import_fs_extra.default.readFile(_filepath, "utf8").catch(() => "");
const shouldSkip = currentContent === newContent && force !== true;
if (shouldSkip)
return false;
if (hash) {
const folder = filepath.replace(/sprite\.svg$/, ``);
clear(folder);
}
await import_fs_extra.default.writeFile(_filepath, newContent, "utf8");
return true;
}
// src/utils/file.ts
function calculateFileSizeInKB(str) {
const buffer = Buffer.from(str, "utf-8");
const fileSizeInKB = buffer.length / 1024;
return fileSizeInKB;
}
// src/icons/templates/svg-sprite.ts
var import_node_html_parser = require("node-html-parser");
function svgSpriteTemplate(iconsData) {
const symbols = iconsData.map((iconData) => {
const input = iconData.content;
const root = (0, import_node_html_parser.parse)(input);
const svg = root.querySelector("svg");
if (!svg)
throw new Error("No SVG element found");
svg.tagName = "symbol";
svg.setAttribute("id", iconData.name);
svg.removeAttribute("xmlns");
svg.removeAttribute("xmlns:xlink");
svg.removeAttribute("version");
svg.removeAttribute("width");
svg.removeAttribute("height");
svg.removeAttribute("fill");
return svg.toString().trim();
});
return [
`<?xml version="1.0" encoding="UTF-8"?>`,
`<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 0 0" width="0" height="0">`,
`<defs>`,
// for semantics: https://developer.mozilla.org/en-US/docs/Web/SVG/Element/defs
...symbols,
`</defs>`,
`</svg>`,
""
// trailing newline
].join("\n");
}
// src/icons/icon-name.ts
function iconName(file) {
return file.replace(/\.svg$/, "").replace(/\\/g, "/");
}
// src/icons/get-icons-data.ts
var import_fs_extra2 = __toESM(require("fs-extra"));
var import_node_path2 = __toESM(require("path"));
function getIconsData({
files,
inputDir
}) {
return files.map((file) => {
const name = iconName(file);
const content = import_fs_extra2.default.readFileSync(import_node_path2.default.join(inputDir, file), "utf8");
return { name, content };
});
}
// src/icons/templates/type.ts
var typeTemplate = (iconNames) => `export type IconName =
| ${iconNames.join("\n | ").replace(/"/g, "'")};
`;
// src/icons/templates/icons.ts
var iconsTemplate = (iconNames) => `import { IconName } from './types/icon-name';
export const icons = [
${iconNames.join(",\n ")},
] satisfies Array<IconName>;
`;
// src/icons/templates/hash.ts
var hashTemplate = (hash) => `export const hash = '${hash}';
`;
// src/utils/optimize.ts
var import_svgo = require("svgo");
var defaultSVGOConfig = {
multipass: true,
plugins: [
{
name: "preset-default",
params: {
overrides: {
removeHiddenElems: false,
removeUselessDefs: false,
cleanupIds: false,
convertColors: {
currentColor: true
},
removeViewBox: false
}
}
}
],
js2svg: {
indent: 2,
pretty: true
}
};
function optimize(output, options = defaultSVGOConfig) {
return (0, import_svgo.optimize)(output, options).data;
}
// src/icons/generate-icon-files.ts
async function generateIconFiles({
files,
context
}) {
const {
spriteFilepath,
typeOutputFilepath,
iconsPath,
hashPath,
inputDir,
shouldOptimize,
shouldHash,
force
} = context;
const currentSprite = await import_fs_extra3.default.readFile(spriteFilepath, "utf8").catch(() => "");
const currentTypes = await import_fs_extra3.default.readFile(typeOutputFilepath, "utf8").catch(() => "");
const iconNames = files.map((file) => iconName(file));
const spriteUpToDate = iconNames.every(
(name) => currentSprite.includes(`id=${name}`)
);
const typesUpToDate = iconNames.every(
(name) => currentTypes.includes(`"${name}"`)
);
if (spriteUpToDate && typesUpToDate) {
console.log(`Icons are up to date`);
return {
hash: void 0
};
}
const iconsData = getIconsData({
files,
inputDir
});
if (shouldOptimize) {
for (const icon of iconsData) {
icon.content = optimize(icon.content, context.svgoConfig);
}
}
const output = svgSpriteTemplate(iconsData);
let hash;
if (shouldHash) {
hash = import_crypto.default.createHash("md5").update(output).digest("hex");
}
const spriteChanged = await writeIfChanged({
filepath: spriteFilepath,
newContent: output,
hash,
force
});
if (spriteChanged) {
console.log(`Generating sprite for ${inputDir}`);
for (const file of files) {
console.log("\u2705", file);
}
console.log(`File size: ${calculateFileSizeInKB(output)} KB`);
if (shouldHash) {
console.log(`Generated sprite with hash ${hash}`);
console.log(
`Saved to ${path2.relative(
process.cwd(),
addHashToSpritePath(spriteFilepath, hash)
)}`
);
} else {
console.log(`Saved to ${path2.relative(process.cwd(), spriteFilepath)}`);
}
}
const stringifiedIconNames = iconNames.map((name) => JSON.stringify(name));
const typeOutputContent = typeTemplate(stringifiedIconNames);
const typesChanged = await writeIfChanged({
filepath: typeOutputFilepath,
newContent: typeOutputContent,
force
});
if (typesChanged) {
console.log(
`Types saved to ${path2.relative(process.cwd(), typeOutputFilepath)}`
);
}
const iconsOutputFilepath = path2.join(iconsPath);
const iconsOutputContent = iconsTemplate(stringifiedIconNames);
const iconsChanged = await writeIfChanged({
filepath: iconsOutputFilepath,
newContent: iconsOutputContent,
force
});
if (iconsChanged) {
console.log(
`Icons names saved to ${path2.relative(
process.cwd(),
iconsOutputFilepath
)}`
);
}
if (shouldHash && hash) {
const hashOutputFilepath = path2.join(hashPath);
const hashFileContent = hashTemplate(hash);
const hashFileChanged = await writeIfChanged({
filepath: hashOutputFilepath,
newContent: hashFileContent,
force
});
if (hashFileChanged) {
console.log(
`Hash file saved to ${path2.relative(process.cwd(), hashOutputFilepath)}`
);
}
}
if (spriteChanged || typesChanged || iconsChanged) {
console.log(`Generated ${files.length} icons`);
} else {
console.log(`Icons are up to date`);
}
return {
hash
};
}
// src/icons/context.ts
var path3 = __toESM(require("path"));
var createIconsContext = (config) => {
const { outputDir, icons, force, cwd } = config;
const inputDirRelative = path3.join(cwd, icons.inputDir);
const outputDirRelative = path3.join(cwd, outputDir);
const spriteOutputDirRelative = path3.join(cwd, icons.spriteOutputDir);
const spriteFilepath = path3.join(cwd, icons.spriteOutputDir, "sprite.svg");
const typesDir = path3.join(cwd, outputDir, "types");
const typeOutputFilepath = path3.join(typesDir, "icon-name.d.ts");
const iconsPath = path3.join(cwd, outputDir, "icons.ts");
const hashPath = path3.join(cwd, outputDir, "hash.ts");
return {
inputDir: inputDirRelative,
outputDir: outputDirRelative,
spriteOutputDir: spriteOutputDirRelative,
spriteFilepath,
typesDir,
typeOutputFilepath,
iconsPath,
hashPath,
shouldOptimize: icons.optimize,
shouldHash: icons.hash,
force,
svgoConfig: icons.svgoConfig
};
};
// src/icons/generate-sprite.ts
async function generateSprite(config) {
const context = createIconsContext(config);
const files = import_glob.glob.sync("**/*.svg", {
cwd: context.inputDir
}).sort((a, b) => a.localeCompare(b));
if (files.length === 0) {
console.log(`No SVG files found in ${context.inputDir}`);
} else {
await Promise.all([
import_fs_extra4.default.ensureDir(context.outputDir),
import_fs_extra4.default.ensureDir(context.spriteOutputDir),
import_fs_extra4.default.ensureDir(context.typesDir)
]);
await generateIconFiles({ files, context });
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
generateSprite
});