You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

generate-svg.js 1.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #!/usr/bin/env node
  2. import fastGlob from 'fast-glob';
  3. import {optimize} from 'svgo';
  4. import {parse} from 'node:path';
  5. import {readFile, writeFile, mkdir} from 'node:fs/promises';
  6. import {fileURLToPath} from 'node:url';
  7. const glob = (pattern) => fastGlob.sync(pattern, {
  8. cwd: fileURLToPath(new URL('..', import.meta.url)),
  9. absolute: true,
  10. });
  11. function exit(err) {
  12. if (err) console.error(err);
  13. process.exit(err ? 1 : 0);
  14. }
  15. async function processFile(file, {prefix, fullName} = {}) {
  16. let name;
  17. if (fullName) {
  18. name = fullName;
  19. } else {
  20. name = parse(file).name;
  21. if (prefix) name = `${prefix}-${name}`;
  22. if (prefix === 'octicon') name = name.replace(/-[0-9]+$/, ''); // chop of '-16' on octicons
  23. }
  24. const {data} = optimize(await readFile(file, 'utf8'), {
  25. plugins: [
  26. {name: 'preset-default'},
  27. {name: 'removeXMLNS'},
  28. {name: 'removeDimensions'},
  29. {name: 'prefixIds', params: {prefix: () => name}},
  30. {name: 'addClassesToSVGElement', params: {classNames: ['svg', name]}},
  31. {name: 'addAttributesToSVGElement', params: {attributes: [{'width': '16'}, {'height': '16'}, {'aria-hidden': 'true'}]}},
  32. ],
  33. });
  34. await writeFile(fileURLToPath(new URL(`../public/img/svg/${name}.svg`, import.meta.url)), data);
  35. }
  36. function processFiles(pattern, opts) {
  37. return glob(pattern).map((file) => processFile(file, opts));
  38. }
  39. async function main() {
  40. try {
  41. await mkdir(fileURLToPath(new URL('../public/img/svg', import.meta.url)), {recursive: true});
  42. } catch {}
  43. await Promise.all([
  44. ...processFiles('node_modules/@primer/octicons/build/svg/*-16.svg', {prefix: 'octicon'}),
  45. ...processFiles('web_src/svg/*.svg'),
  46. ...processFiles('public/img/gitea.svg', {fullName: 'gitea-gitea'}),
  47. ]);
  48. }
  49. main().then(exit).catch(exit);