import * as fs from 'fs'; import * as globby from 'globby'; import * as meow from 'meow'; import * as path from 'path'; import { SVGPath } from './svg-path'; import { KanjiVGStroke } from './kanjivg-stroke'; const cli = meow(` Usage $ ts-node minify-kanjivg `); if (cli.input.length < 0) { throw new Error('`source` and `destination` required'); } const source = cli.input; const destination = cli.input.pop() as string; const PATH_REG_EXP = //g; if (!fs.existsSync(destination)) { fs.mkdirSync(destination, { recursive: true }); } globby.sync(source).forEach(file => { const svgPaths = extractSvgPaths(file); if(svgPaths.map(i => i.start).some(i => !i.x || !i.y)){ console.log(file); } const svgContent = buildSvgContent(svgPaths); const destFile = path.join(destination, path.basename(file)); fs.writeFileSync(destFile, svgContent); const destFileInfo = destFile.replace(/\.svg$/, '.json'); const strokes: KanjiVGStroke[] = svgPaths.map(path => ({id: path.id, start: path.start})); fs.writeFileSync(destFileInfo, JSON.stringify(strokes)); }); function extractSvgPaths(file: string): SVGPath[] { const content = fs.readFileSync(file, 'utf8'); return Array.from(content.matchAll(PATH_REG_EXP), m => { const result = Array.from(m[2].matchAll(/^[M|m]\s*([^,|\s]*)[,|\s]([^c|C]*)/))[0]; return { id: m[1], d: m[2], start: { x: Number(result[1].trim()), y: Number(result[2].trim()) }, }; }); } function buildSvgContent(svgPaths: SVGPath[]): string { const svgPathNodes = svgPaths .map(path => ``) .join('\n'); return ` ${svgPathNodes} `.trim(); }