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.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. import {exit} from 'node:process';
  8. const glob = (pattern) => fastGlob.sync(pattern, {
  9. cwd: fileURLToPath(new URL('..', import.meta.url)),
  10. absolute: true,
  11. });
  12. function doExit(err) {
  13. if (err) console.error(err);
  14. exit(err ? 1 : 0);
  15. }
  16. async function processFile(file, {prefix, fullName} = {}) {
  17. let name;
  18. if (fullName) {
  19. name = fullName;
  20. } else {
  21. name = parse(file).name;
  22. if (prefix) name = `${prefix}-${name}`;
  23. if (prefix === 'octicon') name = name.replace(/-[0-9]+$/, ''); // chop of '-16' on octicons
  24. }
  25. // Set the `xmlns` attribute so that the files are displayable in standalone documents
  26. // The svg backend module will strip the attribute during startup for inline display
  27. const {data} = optimize(await readFile(file, 'utf8'), {
  28. plugins: [
  29. {name: 'preset-default'},
  30. {name: 'removeDimensions'},
  31. {name: 'prefixIds', params: {prefix: () => name}},
  32. {name: 'addClassesToSVGElement', params: {classNames: ['svg', name]}},
  33. {
  34. name: 'addAttributesToSVGElement', params: {
  35. attributes: [
  36. {'xmlns': 'http://www.w3.org/2000/svg'},
  37. {'width': '16'}, {'height': '16'}, {'aria-hidden': 'true'},
  38. ],
  39. },
  40. },
  41. ],
  42. });
  43. await writeFile(fileURLToPath(new URL(`../public/assets/img/svg/${name}.svg`, import.meta.url)), data);
  44. }
  45. function processFiles(pattern, opts) {
  46. return glob(pattern).map((file) => processFile(file, opts));
  47. }
  48. async function main() {
  49. try {
  50. await mkdir(fileURLToPath(new URL('../public/assets/img/svg', import.meta.url)), {recursive: true});
  51. } catch {}
  52. await Promise.all([
  53. ...processFiles('node_modules/@primer/octicons/build/svg/*-16.svg', {prefix: 'octicon'}),
  54. ...processFiles('web_src/svg/*.svg'),
  55. ...processFiles('public/assets/img/gitea.svg', {fullName: 'gitea-gitea'}),
  56. ]);
  57. }
  58. try {
  59. doExit(await main());
  60. } catch (err) {
  61. doExit(err);
  62. }