import { IApi } from '@umijs/types'; import * as http from 'http'; type IIconfontOpts = { /** iconfront的version,如font_1907125_qo7hz1tkges */ version: string; /** 彩色图标。默认的色相旋转角度 */ defaultHueRotate: number; }; type IconfontSvgItem = { name: string; attrs: string; key: string; path: string; fills?: string[]; }; const parseIconfont = function (svgString: string): IconfontSvgItem[] { let svgStartIdx = svgString.indexOf('"'); let svgEndStr = '"'; if (svgStartIdx === -1) { svgStartIdx = svgString.indexOf("'"); svgEndStr = "'"; } const svgEndIdx = svgString.indexOf(svgEndStr); const svgExpression = `return (${svgString.substring( svgStartIdx, svgEndIdx + svgEndStr.length, )})`; const fn = new Function(svgExpression); const svgContent = fn(); const items: IconfontSvgItem[] = []; const SYMBOL_REG = /(.+?)<\/symbol>/gm; let execResult: ReturnType = null; while ((execResult = SYMBOL_REG.exec(svgContent))) { const [_, key, attrs, path] = execResult; const name = key // .replace(/^[a-z]/, c => c.toLocaleUpperCase()) // .replace(/[_\-]([a-z])/g, (all, c: string) => c.toLocaleUpperCase()) .replace(/[\s]/g, ''); const item: IconfontSvgItem = { key, path, name, attrs }; if (path.includes('fill=')) { const FILL_REG = /fill=\\?"([\w#]+)\\?"/g; const fillSet: Set = new Set(); let fillExecResult: ReturnType = null; while ((fillExecResult = FILL_REG.exec(path))) { const [_, color] = fillExecResult; fillSet.add(color); } // 将只有一种填充色的图标处理为非彩色图标 if (fillSet.size < 2) { item.path = path.replace(FILL_REG, ''); } else { item.fills = Array.from(fillSet); } } items.push(item); } return items; }; const getJsContent = function ( items: IconfontSvgItem[], defaultHueRotate?: number, ) { const arr: string[] = [ "import React from 'react';", `const DEFAULT_HUE_ROTATE = ${defaultHueRotate || 'undefined'};`, ]; let mapStr = 'const IconMap = {'; for (const item of items) { mapStr += `"${item.name}":function(props){ const className = \`iconfont-plugin ${item.fills ? 'iconfont-colored' : ''} \`; props = Object.assign({},props); if(props.className){ props.className = className + props.className; } else{ props.className = className; } if(props.hueRotate || DEFAULT_HUE_ROTATE){ const style = { filter:'hue-rotate('+(props.hueRotate||DEFAULT_HUE_ROTATE)+'deg)' } delete props.hueRotate; if(props.style){ props.style = Object.assign(style,props.style); } else{ props.style = style; } } return ( ); },`; } mapStr += '}'; arr.push(mapStr); arr.push(`export const MyIcon = function(props) { const type = props.type; const Icon = IconMap[type]; if(!Icon){ return IconMap[Object.keys(IconMap)[0]] || null; } return ( ); };`); return arr.join('\n'); }; const getDTSContent = function (items: IconfontSvgItem[], projectId: string) { const arr: string[] = [ "import React from 'react';", ` type IconfontProps = { /**指定外侧svg的className*/ className?:string, type:string } & React.SVGProps; type IconfontColordProps = { /**彩色图标的色相旋转角度,0-360之间的数字*/ hueRotate?:number|string } `, ]; // for(const item of items){ // arr.push( // ` // /** // * 图标${item.key}。${item.fills?'多彩图标':''} // * @see https://www.iconfont.cn/manage/index?manage_type=myprojects&projectId=${projectId} // */ // export var Icon${item.name}:React.SFC; // `); // } arr.push('export var MyIcon:React.SFC;'); return arr.join('\n'); }; const downloadIconfont = function (version: string): Promise { return new Promise((resolve, reject) => { http.get(`http://at.alicdn.com/t/${version}.js`, (res) => { const arr: string[] = []; res.setEncoding('utf8'); res.on('data', (d) => arr.push(d)); res.on('end', () => { const str = arr.join(''); resolve(parseIconfont(str)); }); res.on('error', reject); }); }); }; export default function (api: IApi) { const opts: IIconfontOpts = api.userConfig.iconfont; if (!opts) return; api.describe({ key: 'iconfont', config: { schema(joi) { return joi.object({ version: joi.string().required(), defaultHueRotate: joi.number(), }); }, onChange: api.ConfigChangeType.regenerateTmpFiles, }, }); api.onGenerateFiles(async () => { const opts: IIconfontOpts = api.userConfig.iconfont; const versionMatchResult = opts.version.match(/font_(\d+)_(\w+)/); if (!versionMatchResult) { console.error('Iconfont version error:', opts.version); return; } const iconfontResult = await downloadIconfont(opts.version); api.writeTmpFile({ path: 'plugin-iconfont/index.jsx', content: getJsContent(iconfontResult, opts.defaultHueRotate), }); api.writeTmpFile({ path: 'plugin-iconfont/index.d.ts', content: getDTSContent(iconfontResult, versionMatchResult[1]), }); }); api.addHTMLStyles(() => { return [ { content: '.iconfont-plugin {width: 1em; height: 1em; vertical-align: -0.15em; fill: currentColor; overflow: hidden;}', }, ]; }); api.addUmiExports(() => { return { source: '../plugin-iconfont', exportAll: true, }; }); }