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 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. // Set the `xmlns` attribute so that the files are displayable in standalone documents
  25. // The svg backend module will strip the attribute during startup for inline display
  26. const {data} = optimize(await readFile(file, 'utf8'), {
  27. plugins: [
  28. {name: 'preset-default'},
  29. {name: 'removeDimensions'},
  30. {name: 'prefixIds', params: {prefix: () => name}},
  31. {name: 'addClassesToSVGElement', params: {classNames: ['svg', name]}},
  32. {
  33. name: 'addAttributesToSVGElement', params: {
  34. attributes: [
  35. {'xmlns': 'http://www.w3.org/2000/svg'},
  36. {'width': '16'}, {'height': '16'}, {'aria-hidden': 'true'},
  37. ]
  38. }
  39. },
  40. ],
  41. });
  42. await writeFile(fileURLToPath(new URL(`../public/assets/img/svg/${name}.svg`, import.meta.url)), data);
  43. }
  44. function processFiles(pattern, opts) {
  45. return glob(pattern).map((file) => processFile(file, opts));
  46. }
  47. async function main() {
  48. try {
  49. await mkdir(fileURLToPath(new URL('../public/assets/img/svg', import.meta.url)), {recursive: true});
  50. } catch {}
  51. await Promise.all([
  52. ...processFiles('node_modules/@primer/octicons/build/svg/*-16.svg', {prefix: 'octicon'}),
  53. ...processFiles('web_src/svg/*.svg'),
  54. ...processFiles('public/assets/img/gitea.svg', {fullName: 'gitea-gitea'}),
  55. ]);
  56. }
  57. main().then(exit).catch(exit);