aboutsummaryrefslogtreecommitdiff
path: root/apps/website/src/components/logos/Logo.astro
blob: 6b085fac3fdec254ef3a47b0cba065aa8860e4dc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
---
import { readFile } from 'node:fs/promises';
import { join } from 'node:path';
import type { LogoType } from '@webtypes/Config';
import type { HTMLAttributes } from 'astro/types';

export interface Props extends HTMLAttributes<'svg'> {
	logo: LogoType
	size?: number | [number, number]
	silent?: boolean
}

const {
	logo,
	size = undefined,
	...attr
} = Astro.props;
let svg: string | undefined;

try {
	if (logo === undefined)
		return;

	const dir = new URL(join('..', '..', '..', 'public', 'media'), import.meta.url).pathname;
	svg = (await readFile(`${dir}/${logo.replaceAll('.', '/')}.svg`, { encoding: 'utf8' }));

	if (svg === undefined)
		return;

	if (typeof size == 'number' || Array.isArray(size)) {
		// SVG main element regex
		const svgElementRegex = /<svg[^>]*>/;

		svg = svg.replace(svgElementRegex, (match) => {
			let newMatch = match;
			if (typeof size == 'number') {
				newMatch = newMatch.replace(/width="[^"]*"/, `width="${size}"`);
				newMatch = newMatch.replace(/height="[^"]*"/, `height="${size}"`);
			}
			else if (Array.isArray(size)) {
				newMatch = newMatch.replace(/width="[^"]*"/, `width="${size[0]}"`);
				newMatch = newMatch.replace(/height="[^"]*"/, `height="${size[1]}"`);
			}
			return newMatch;
		});
	}

	svg = svg.replace(/<svg/, `<svg ${Object.entries(attr).map(([key, value]) => `${key}="${value}"`).join(' ')}`);
}
catch (err) {
	console.error(`Error occurred while loading SVG. Logo name is ${logo}.`);
	console.error(err);
}

---

<Fragment set:html={svg}/>