Skip to content

Commit

Permalink
更新图标库
Browse files Browse the repository at this point in the history
  • Loading branch information
sengoku-f committed Sep 20, 2024
1 parent 1ee323d commit 503c6d3
Show file tree
Hide file tree
Showing 13 changed files with 253 additions and 90 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,9 @@ jobs:
run: |
rm -rf yarn.lock
yarn install
yarn compiler:icons
yarn build
yarn build:icons
yarn build:code
yarn build
# 检查版本
- name: Check version changes
Expand Down
198 changes: 123 additions & 75 deletions bin/build.mjs
Original file line number Diff line number Diff line change
@@ -1,103 +1,151 @@
import path from 'path';
import fs from 'fs';
import { fileURLToPath } from 'url';
import { processSvg } from './processSvg.mjs';
import parseName from './utils.mjs';
import { getElementCode } from './template.mjs';
import path from "path";
import fs from "fs";
import { fileURLToPath } from "url";
import { processSvg } from "./processSvg.mjs";
import parseName from "./utils.mjs";
import { getElementCode } from "./template.mjs";

// 获取当前模块文件的 URL (ES模块)
const __filename = fileURLToPath(import.meta.url);
// 获取当前模块目录的路径
const __dirname = path.dirname(__filename);
// 定义项目的根目录
const rootDir = path.join(__dirname, '..')
const rootDir = path.join(__dirname, "..");

// 定义源代码和图标代码的目录
const srcDir = path.join(rootDir, 'src')
const iconsDir = path.join(rootDir, 'src/icons')
const jsonOutputFile = path.join(rootDir, 'icons.json');

const iconDataList = [];

// 生成 index 和 d.ts 文件
const generateIndex = () => {
// 如果源代码目录不存在,则创建它和图标代码目录
if (!fs.existsSync(srcDir)) {
fs.mkdirSync(srcDir)
fs.mkdirSync(iconsDir)
} else if (!fs.existsSync(iconsDir)) {
// 如果图标代码目录不存在,则创建它
fs.mkdirSync(iconsDir)
const srcDir = path.join(rootDir, "src");
const iconsDir = path.join(rootDir, "src/icons");
const mapFile = path.join(rootDir, "src", "map.js");
const jsonOutputFile = path.join(rootDir, "icons.json");
const iconsConfigFile = path.join(rootDir, "icons-config.json");

// 读取 icons-config.json 文件
const iconsConfig = JSON.parse(fs.readFileSync(iconsConfigFile, "utf8"));

// 创建目录的辅助函数
const createDirIfNotExists = (dir) => {
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
}
};

// 创建一个空的 map.js 文件
fs.writeFileSync(path.join(rootDir, 'src', 'map.js'), '', 'utf-8');
}
// 生成 map.js
const generateMap = () => {
createDirIfNotExists(srcDir);
createDirIfNotExists(iconsDir);
fs.writeFileSync(path.join(srcDir, "map.js"), "", "utf-8");
};

// 创建图标数据的辅助函数
const createIconData = (config, id, ComponentName, name, stats) => ({
id,
name,
componentName: `Icon${ComponentName}`,
title: config?.title || "defaultTitle",
category: config?.category || "Default",
categoryCN: config?.categoryCN || "默认",
author: config?.author || "unknown",
modifiedTime: stats.mtime,
tag: config?.tag || [],
});

// 分别生成图标代码
const generateIconCode = async (name) => {
const names = parseName(name)
const location = path.join(rootDir, 'src/svg', `${names.name}.svg`)
const destination = path.join(rootDir, 'src/icons', `${names.name}.js`)
const names = parseName(name);
const location = path.join(rootDir, "src/svg", `${names.name}.svg`);
const destination = path.join(rootDir, "src/icons", `${names.name}.js`);
// 读取 SVG 文件
const code = fs.readFileSync(location)
// const code = fs.readFileSync(location)
const code = await fs.promises.readFile(location);
// 处理 SVG 文件
const svgCode = await processSvg(code, names.style) // 将样式传递给 processSvg
const ComponentName = names.componentName
const svgCode = await processSvg(code, names.style); // 将样式传递给 processSvg
const ComponentName = names.componentName;
// 获取组件代码
const component = await getElementCode(names, svgCode)
const component = await getElementCode(names, svgCode);

// 写入组件代码
fs.writeFileSync(destination, component, 'utf-8');
// fs.writeFileSync(destination, component, 'utf-8');
await fs.promises.writeFile(destination, component, "utf-8");

// 获取文件的修改日期
const stats = fs.statSync(location);
iconDataList.push({
name: `Icon${ComponentName}`,
modifiedTime: stats.mtime
});

console.log('成功构建:', ComponentName, '修改日期:', stats.mtime);
return {ComponentName, name: names.name}
}
// const stats = fs.statSync(location);
const stats = await fs.promises.stat(location);

// 查找 icons-config.json 中的配置
const config = iconsConfig.find(
(icon) => icon.name.trim() === names.name.trim()
);

console.log("成功构建:", ComponentName, "修改日期:", stats.mtime);
return { ComponentName, name: names.name, config, stats };
};

// 将导出代码追加到 map.js
const appendToIndex = ({ComponentName, name}) => {
const appendToIndex = async ({ ComponentName, name }) => {
const exportString = `export { default as Icon${ComponentName} } from './icons/${name}';\r\n`;
fs.appendFileSync(
path.join(rootDir, 'src', 'map.js'),
await fs.promises.appendFile(
path.join(rootDir, "src", "map.js"),
exportString,
'utf-8',
"utf-8"
);
};

async function processFiles() {
// 从 src/svg 目录读取 SVG 文件
const svgDir = path.join(rootDir, "src/svg");
try {
const files = await fs.promises.readdir(svgDir);
// 过滤出所有的 SVG 文件
const svgFiles = files.filter((file) => path.extname(file) === ".svg");
// 对文件名进行排序
svgFiles.sort((a, b) => a.localeCompare(b));

// 使用 Promise.all 处理所有 SVG 文件并按索引排序
const results = await Promise.all(
svgFiles.map((file, index) => processFile(file, index))
);

// 提取 iconData 并写入 JSON 文件
const iconDataList = results
.sort((a, b) => a.index - b.index)
.map((result) => result.iconData);

await fs.promises.writeFile(
jsonOutputFile,
JSON.stringify(iconDataList, null, 2),
"utf-8"
);
console.log("成功生成 JSON 文件:", jsonOutputFile);

// 生成 map.js 文件
const exportStrings = results
.map(
({ iconData }) =>
`export { default as ${iconData.componentName} } from './icons/${iconData.name}';\r\n`
)
.join("");
await fs.promises.writeFile(mapFile, exportStrings, "utf-8");
console.log("成功生成 map.js 文件:", mapFile);
} catch (err) {
console.error("生成图标代码时出错:", err);
}
}

// 生成 index 文件
generateIndex()

// 从 src/svg 目录读取 SVG 文件
const svgDir = path.join(rootDir, 'src/svg')
fs.readdir(svgDir, (err, files) => {
if (err) {
console.error('无法列出目录:', err);
process.exit(1);
async function processFile(file, index) {
const name = path.basename(file, ".svg");
try {
const { ComponentName, config, stats } = await generateIconCode(name);
// 创建 icon 数据,确保字段顺序一致
const iconData = createIconData(config, index, ComponentName, name, stats);
// await appendToIndex({ ComponentName, name });
return { index, iconData };
} catch (err) {
console.error(`处理SVG ${file} 时出错:`, err);
return { index, iconData: null };
}
// 过滤出所有的 SVG 文件
const svgFiles = files.filter(file => path.extname(file) === '.svg');
// 遍历所有 SVG 文件,生成图标代码并记录数据
const promises = svgFiles.map(file => {
const name = path.basename(file, '.svg');
return generateIconCode(name)
.then(({ ComponentName, name }) => {
// 将图标代码追加到 map.js
appendToIndex({ ComponentName, name });
});
});
// 等待所有的图标代码生成完毕
Promise.all(promises).then(() => {
// 将 iconDataList 写入 JSON 文件
fs.writeFileSync(jsonOutputFile, JSON.stringify(iconDataList, null, 2), 'utf-8');
console.log('成功生成 JSON 文件:', jsonOutputFile);
}).catch(err => {
console.error('生成图标代码时出错:', err);
});
});
}

// 生成 index 文件
generateMap();
// 执行主函数
processFiles();
7 changes: 5 additions & 2 deletions bin/processSvg.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ function convertStroke(node, style) {
delete node.attributes["fill"]
}
// 如果 style 为 color 则使得 stroke 为当前颜色 否则为 currentColor
const strokeColor = style === "color" ? node.attributes["stroke"] : "currentColor";
const strokeColor = style === "color" ? node.attributes["stroke"] : "props.color";
// 对匹配到的节点执行处理逻辑
Object.assign(node.attributes, {
"stroke": strokeColor,
Expand Down Expand Up @@ -167,12 +167,15 @@ function processAttributes(attributes) {
return processedAttrs; // 返回处理后的属性对象
}

// 将属性对象转换为字符串形式
// 节点属性对象转换为字符串形式
function attributesToString(attributes) {
const attrsString = Object.entries(attributes).map(([key, value]) => {
if (key === 'ref') {
return `${key}: ${value}`; // ref 属性值不用双引号
}
if (key === 'stroke' && typeof value === 'string' && value.startsWith('props.')) {
return `"${key}": ${value}`; // stroke 属性值以 props. 开头不用双引号
}
// 属性值添加引号
return `"${key}": "${value}"`;
}).join(", ");
Expand Down
34 changes: 34 additions & 0 deletions icons-config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
[
{
"name": " add",
"title": "添加",
"category": "Character",
"categoryCN": "符号标识",
"author": "KRPOM",
"tag": ["新建", "增加", "创建"]
},
{
"name": "SZYGGL",
"title": "数字员工管理",
"category": "Menu",
"categoryCN": "菜单",
"author": "KRPOM",
"tag": ["数字员工", "管理", "上海银行"]
},
{
"name": "SZYGZY",
"title": "数字员工资源",
"category": "Menu",
"categoryCN": "菜单",
"author": "KRPOM",
"tag": ["数字员工", "资源", "上海银行"]
},
{
"name": "WDSZYG",
"title": "我的数字员工",
"category": "Menu",
"categoryCN": "菜单",
"author": "KRPOM",
"tag": ["数字员工", "资源", "上海银行"]
}
]
71 changes: 67 additions & 4 deletions icons.json
Original file line number Diff line number Diff line change
@@ -1,10 +1,73 @@
[
{
"name": "IconAdd",
"modifiedTime": "2024-06-20T12:39:37.622Z"
"id": 0,
"name": "add",
"componentName": "IconAdd",
"title": "添加",
"category": "Character",
"categoryCN": "符号标识",
"author": "KRPOM",
"modifiedTime": "2024-06-20T12:39:37.622Z",
"tag": [
"新建",
"增加",
"创建"
]
},
{
"name": "IconCalendarColor",
"modifiedTime": "2024-08-12T07:00:10.017Z"
"id": 1,
"name": "calendar-color",
"componentName": "IconCalendarColor",
"title": "defaultTitle",
"category": "Default",
"categoryCN": "默认",
"author": "unknown",
"modifiedTime": "2024-08-12T07:00:10.017Z",
"tag": []
},
{
"id": 2,
"name": "SZYGGL",
"componentName": "IconSZYGGL",
"title": "数字员工管理",
"category": "Menu",
"categoryCN": "菜单",
"author": "KRPOM",
"modifiedTime": "2024-09-19T09:55:02.333Z",
"tag": [
"数字员工",
"管理",
"上海银行"
]
},
{
"id": 3,
"name": "SZYGZY",
"componentName": "IconSZYGZY",
"title": "数字员工资源",
"category": "Menu",
"categoryCN": "菜单",
"author": "KRPOM",
"modifiedTime": "2024-09-19T09:55:02.343Z",
"tag": [
"数字员工",
"资源",
"上海银行"
]
},
{
"id": 4,
"name": "WDSZYG",
"componentName": "IconWDSZYG",
"title": "我的数字员工",
"category": "Menu",
"categoryCN": "菜单",
"author": "KRPOM",
"modifiedTime": "2024-09-19T09:55:02.348Z",
"tag": [
"数字员工",
"资源",
"上海银行"
]
}
]
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "ksw-rpom-icon-vue",
"version": "0.1.2",
"version": "0.1.3",
"license": "ISC",
"description": "KSW RPOM ICON",
"main": "packages/cjs/index.js",
Expand All @@ -14,9 +14,9 @@
"packages/*/*/*.d.ts"
],
"scripts": {
"compiler:icons": "rm -rf src/icons && node bin/build.mjs",
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"build:icons": "rm -rf src/icons && node bin/build.mjs",
"build:code": "rollup -c",
"lint": "vue-cli-service lint",
"clean-publish": "clean-publish"
Expand Down
Loading

0 comments on commit 503c6d3

Please sign in to comment.