From 0cfe5819d5e3b8efdc7f35e4437d9bcb88c6e8ee Mon Sep 17 00:00:00 2001 From: Jimmy Andrade Date: Sat, 5 Jun 2021 15:19:25 -0300 Subject: [PATCH] feat: add standalone glyphs data getter --- src/standalone/glyphsData.ts | 73 ++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 src/standalone/glyphsData.ts diff --git a/src/standalone/glyphsData.ts b/src/standalone/glyphsData.ts new file mode 100644 index 00000000..7e832167 --- /dev/null +++ b/src/standalone/glyphsData.ts @@ -0,0 +1,73 @@ +import type {GlyphData, WebfontOptions} from "../types"; +import { createReadStream } from "fs"; +import fileSorter from "svgicons2svgfont/src/filesorter"; +import getMetadataService from "svgicons2svgfont/src/metadata"; +import pLimit from "p-limit"; +import xml2js from "xml2js"; + +// eslint-disable-next-line no-unused-vars +type GlyphsDataGetter = (files: Array, options: WebfontOptions) => unknown; + +export const getGlyphsData : GlyphsDataGetter = (files, options) => { + const metadataProvider = + options.metadataProvider || + getMetadataService({ + prependUnicode: options.prependUnicode, + startUnicode: options.startUnicode, + }); + + const xmlParser = new xml2js.Parser(); + const throttle = pLimit(options.maxConcurrency); + + return Promise.all(files.map((srcPath: GlyphData["srcPath"]) => throttle(() => new Promise((resolve, reject) => { + const glyph = createReadStream(srcPath); + let glyphContents = ""; + + // eslint-disable-next-line no-promise-executor-return + return glyph. + on("error", (glyphError) => reject(glyphError)). + on("data", (data) => { + glyphContents += data.toString(); + }). + on("end", () => { + // Maybe bug in xml2js + if (glyphContents.length === 0) { + return reject(new Error(`Empty file ${srcPath}`)); + } + + return xmlParser.parseString(glyphContents, (error) => { + if (error) { + return reject(error); + } + + const glyphData: GlyphData = { + contents: glyphContents, + srcPath, + }; + + return resolve(glyphData); + }); + }); + })))).then((glyphsData) => { + + let sortedGlyphsData = glyphsData; + + if (options.sort) { + const sortCallback = (fileA: GlyphData, fileB: GlyphData) => fileSorter(fileA.srcPath, fileB.srcPath); + sortedGlyphsData = glyphsData.sort(sortCallback); + } + + return Promise.all(sortedGlyphsData.map((glyphData: GlyphData) => new Promise((resolve, reject) => { + metadataProvider(glyphData.srcPath, (error, metadata) => { + if (error) { + return reject(error); + } + + metadata.unicode.push(metadata.name.replace(/-/gu, "_")); + glyphData.metadata = metadata; + + return resolve(glyphData); + }); + }))); + }); +};