helpers.mjs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. import fs from 'fs'
  2. import path, { resolve, basename } from 'path'
  3. import { fileURLToPath } from 'url'
  4. import svgParse from 'parse-svg-path'
  5. import svgpath from 'svgpath'
  6. import cheerio from 'cheerio';
  7. import { minify } from 'html-minifier';
  8. import { parseSync } from 'svgson'
  9. import { optimize } from 'svgo'
  10. import cp from 'child_process'
  11. import minimist from 'minimist'
  12. import glob from 'glob'
  13. import matter from 'gray-matter'
  14. const defaultProps = {
  15. xmlns: "http://www.w3.org/2000/svg",
  16. className: "icon icon-tabler",
  17. width: "24",
  18. height: "24",
  19. viewBox: "0 0 24 24",
  20. strokeWidth: "2",
  21. stroke: "currentColor",
  22. fill: "none",
  23. strokeLinecap: "round",
  24. strokeLinejoin: "round"
  25. }
  26. export const getCurrentDirPath = () => {
  27. return path.dirname(fileURLToPath(import.meta.url));
  28. }
  29. export const HOME_DIR = resolve(getCurrentDirPath(), '..')
  30. export const ICONS_SRC_DIR = resolve(HOME_DIR, 'src/_icons')
  31. export const ICONS_DIR = resolve(HOME_DIR, 'icons')
  32. export const PACKAGES_DIR = resolve(HOME_DIR, 'packages')
  33. export const getArgvs = () => {
  34. return minimist(process.argv.slice(2))
  35. }
  36. export const getPackageDir = (packageName) => {
  37. return `${PACKAGES_DIR}/${packageName}`
  38. }
  39. /**
  40. * Return project package.json
  41. * @returns {any}
  42. */
  43. export const getPackageJson = () => {
  44. return JSON.parse(fs.readFileSync(resolve(HOME_DIR, 'package.json'), 'utf-8'))
  45. }
  46. /**
  47. * Reads SVGs from directory
  48. *
  49. * @param directory
  50. * @returns {string[]}
  51. */
  52. export const readSvgDirectory = (directory) => {
  53. return fs.readdirSync(directory).filter((file) => path.extname(file) === '.svg')
  54. }
  55. export const readSvgs = () => {
  56. const svgFiles = readSvgDirectory(ICONS_DIR)
  57. return svgFiles.map(svgFile => {
  58. const name = basename(svgFile, '.svg'),
  59. namePascal = toPascalCase(`icon ${name}`),
  60. contents = readSvg(svgFile, ICONS_DIR).trim(),
  61. path = resolve(ICONS_DIR, svgFile),
  62. obj = parseSync(contents.replace('<path stroke="none" d="M0 0h24v24H0z" fill="none"/>', ''));
  63. return {
  64. name,
  65. namePascal,
  66. contents,
  67. obj,
  68. path
  69. };
  70. });
  71. }
  72. /**
  73. * Read SVG
  74. *
  75. * @param fileName
  76. * @param directory
  77. * @returns {string}
  78. */
  79. export const readSvg = (fileName, directory) => {
  80. return fs.readFileSync(path.join(directory, fileName), 'utf-8')
  81. }
  82. /**
  83. * Create directory if not exists
  84. * @param dir
  85. */
  86. export const createDirectory = (dir) => {
  87. if (!fs.existsSync(dir)) {
  88. fs.mkdirSync(dir);
  89. }
  90. };
  91. /**
  92. * Get SVG name
  93. * @param fileName
  94. * @returns {string}
  95. */
  96. export const getSvgName = (fileName) => {
  97. return path.basename(fileName, '.svg')
  98. }
  99. /**
  100. * Convert string to CamelCase
  101. * @param string
  102. * @returns {*}
  103. */
  104. export const toCamelCase = (string) => {
  105. return string.replace(/^([A-Z])|[\s-_]+(\w)/g, (match, p1, p2) => p2 ? p2.toUpperCase() : p1.toLowerCase())
  106. }
  107. export const toPascalCase = (string) => {
  108. const camelCase = toCamelCase(string);
  109. return camelCase.charAt(0).toUpperCase() + camelCase.slice(1);
  110. }
  111. export const addFloats = function(n1, n2) {
  112. return Math.round((parseFloat(n1) + parseFloat(n2)) * 1000) / 1000
  113. }
  114. export const optimizePath = function(path) {
  115. let transformed = svgpath(path).rel().round(3).toString()
  116. return svgParse(transformed).map(function(a) {
  117. return a.join(' ')
  118. }).join('')
  119. }
  120. export const optimizeSVG = (data) => {
  121. return optimize(data, {
  122. js2svg: {
  123. indent: 2,
  124. pretty: true
  125. },
  126. plugins: [
  127. {
  128. name: 'preset-default',
  129. params: {
  130. overrides: {
  131. mergePaths: false
  132. }
  133. }
  134. }]
  135. }).data
  136. }
  137. export function buildIconsObject(svgFiles, getSvg) {
  138. return svgFiles
  139. .map(svgFile => {
  140. const name = path.basename(svgFile, '.svg');
  141. const svg = getSvg(svgFile);
  142. const contents = getSvgContents(svg);
  143. return { name, contents };
  144. })
  145. .reduce((icons, icon) => {
  146. icons[icon.name] = icon.contents;
  147. return icons;
  148. }, {});
  149. }
  150. function getSvgContents(svg) {
  151. const $ = cheerio.load(svg);
  152. return minify($('svg').html(), { collapseWhitespace: true });
  153. }
  154. export const asyncForEach = async (array, callback) => {
  155. for (let index = 0; index < array.length; index++) {
  156. await callback(array[index], index, array)
  157. }
  158. }
  159. export const createScreenshot = async (filePath) => {
  160. await cp.exec(`rsvg-convert -x 2 -y 2 ${filePath} > ${filePath.replace('.svg', '.png')}`)
  161. await cp.exec(`rsvg-convert -x 4 -y 4 ${filePath} > ${filePath.replace('.svg', '@2x.png')}`)
  162. }
  163. export const generateIconsPreview = async function(files, destFile, {
  164. columnsCount = 19,
  165. paddingOuter = 7,
  166. color = '#354052',
  167. background = '#fff'
  168. } = {}) {
  169. const padding = 20,
  170. iconSize = 24
  171. const iconsCount = files.length,
  172. rowsCount = Math.ceil(iconsCount / columnsCount),
  173. width = columnsCount * (iconSize + padding) + 2 * paddingOuter - padding,
  174. height = rowsCount * (iconSize + padding) + 2 * paddingOuter - padding
  175. let svgContentSymbols = '',
  176. svgContentIcons = '',
  177. x = paddingOuter,
  178. y = paddingOuter
  179. files.forEach(function(file, i) {
  180. let name = path.basename(file, '.svg')
  181. let svgFile = fs.readFileSync(file),
  182. svgFileContent = svgFile.toString()
  183. svgFileContent = svgFileContent.replace('<svg xmlns="http://www.w3.org/2000/svg"', `<symbol id="${name}"`)
  184. .replace(' width="24" height="24"', '')
  185. .replace('</svg>', '</symbol>')
  186. .replace(/\n\s+/g, '')
  187. svgContentSymbols += `\t${svgFileContent}\n`
  188. svgContentIcons += `\t<use xlink:href="#${name}" x="${x}" y="${y}" width="${iconSize}" height="${iconSize}" />\n`
  189. x += padding + iconSize
  190. if (i % columnsCount === columnsCount - 1) {
  191. x = paddingOuter
  192. y += padding + iconSize
  193. }
  194. })
  195. const svgContent = `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 ${width} ${height}" width="${width}" height="${height}" style="color: ${color}"><rect x="0" y="0" width="${width}" height="${height}" fill="${background}"></rect>\n${svgContentSymbols}\n${svgContentIcons}\n</svg>`
  196. fs.writeFileSync(destFile, svgContent)
  197. await createScreenshot(destFile)
  198. }
  199. export const printChangelog = function(newIcons, modifiedIcons, renamedIcons, pretty = false) {
  200. if (newIcons.length > 0) {
  201. if (pretty) {
  202. console.log(`### ${newIcons.length} new icons:\n`)
  203. newIcons.forEach(function(icon, i) {
  204. console.log(`- \`${icon}\``)
  205. })
  206. } else {
  207. let str = ''
  208. str += `${newIcons.length} new icons: `
  209. newIcons.forEach(function(icon, i) {
  210. str += `\`${icon}\``
  211. if ((i + 1) <= newIcons.length - 1) {
  212. str += ', '
  213. }
  214. })
  215. console.log(str)
  216. }
  217. console.log('')
  218. }
  219. if (modifiedIcons.length > 0) {
  220. let str = ''
  221. str += `Fixed icons: `
  222. modifiedIcons.forEach(function(icon, i) {
  223. str += `\`${icon}\``
  224. if ((i + 1) <= modifiedIcons.length - 1) {
  225. str += ', '
  226. }
  227. })
  228. console.log(str)
  229. console.log('')
  230. }
  231. if (renamedIcons.length > 0) {
  232. console.log(`Renamed icons: `)
  233. renamedIcons.forEach(function(icon, i) {
  234. console.log(`- \`${icon[0]}\` renamed to \`${icon[1]}\``)
  235. })
  236. }
  237. }
  238. export const getCompileOptions = () => {
  239. const compileOptions = {
  240. includeIcons: [],
  241. strokeWidth: null,
  242. fontForge: 'fontforge'
  243. }
  244. if (fs.existsSync('../compile-options.json')) {
  245. try {
  246. const tempOptions = require('../compile-options.json')
  247. if (typeof tempOptions !== 'object') {
  248. throw 'Compile options file does not contain an json object'
  249. }
  250. if (typeof tempOptions.includeIcons !== 'undefined') {
  251. if (!Array.isArray(tempOptions.includeIcons)) {
  252. throw 'property inludeIcons is not an array'
  253. }
  254. compileOptions.includeIcons = tempOptions.includeIcons
  255. }
  256. if (typeof tempOptions.includeCategories !== 'undefined') {
  257. if (typeof tempOptions.includeCategories === 'string') {
  258. tempOptions.includeCategories = tempOptions.includeCategories.split(' ')
  259. }
  260. if (!Array.isArray(tempOptions.includeCategories)) {
  261. throw 'property includeCategories is not an array or string'
  262. }
  263. const tags = Object.entries(require('./tags.json'))
  264. tempOptions.includeCategories.forEach(function(category) {
  265. category = category.charAt(0).toUpperCase() + category.slice(1)
  266. for (const [icon, data] of tags) {
  267. if (data.category === category && compileOptions.includeIcons.indexOf(icon) === -1) {
  268. compileOptions.includeIcons.push(icon)
  269. }
  270. }
  271. })
  272. }
  273. if (typeof tempOptions.excludeIcons !== 'undefined') {
  274. if (!Array.isArray(tempOptions.excludeIcons)) {
  275. throw 'property excludeIcons is not an array'
  276. }
  277. compileOptions.includeIcons = compileOptions.includeIcons.filter(function(icon) {
  278. return tempOptions.excludeIcons.indexOf(icon) === -1
  279. })
  280. }
  281. if (typeof tempOptions.excludeOffIcons !== 'undefined' && tempOptions.excludeOffIcons) {
  282. // Exclude `*-off` icons
  283. compileOptions.includeIcons = compileOptions.includeIcons.filter(function(icon) {
  284. return !icon.endsWith('-off')
  285. })
  286. }
  287. if (typeof tempOptions.strokeWidth !== 'undefined') {
  288. if (typeof tempOptions.strokeWidth !== 'string' && typeof tempOptions.strokeWidth !== 'number') {
  289. throw 'property strokeWidth is not a string or number'
  290. }
  291. compileOptions.strokeWidth = tempOptions.strokeWidth.toString()
  292. }
  293. if (typeof tempOptions.fontForge !== 'undefined') {
  294. if (typeof tempOptions.fontForge !== 'string') {
  295. throw 'property fontForge is not a string'
  296. }
  297. compileOptions.fontForge = tempOptions.fontForge
  298. }
  299. } catch (error) {
  300. throw `Error reading compile-options.json: ${error}`
  301. }
  302. }
  303. return compileOptions
  304. }