the only good website on the internet
quaso.engineering
1<script lang="ts">
2 /* eslint svelte/no-at-html-tags: "off" */
3 import type { Component } from 'svelte';
4
5 interface Rule {
6 split: RegExp;
7 match: RegExp;
8 component: Component<any>;
9 props?: Record<string, unknown>;
10 }
11
12 interface Props {
13 html: string;
14 rules?: Rule[];
15 }
16
17 let { html, rules = [] }: Props = $props();
18
19 const partitionHtml = (html: string, rules: Rule[]) => {
20 return rules.reduce(
21 (acc, rule) => {
22 return acc.flatMap((substr) => substr.split(rule.split));
23 },
24 [html]
25 );
26 };
27
28 const findAndTransform = (
29 rules: Rule[],
30 predicate: (rule: Rule) => boolean,
31 transform: (rule: Rule) => Rule
32 ) => {
33 const foundElement = rules.find(predicate);
34 return foundElement ? transform(foundElement) : null;
35 };
36</script>
37
38{#each partitionHtml(html, rules) as part}
39 {@const match = findAndTransform(
40 rules,
41 (rule) => rule.split.test(part),
42 (rule) => ({
43 ...rule,
44 props: { ...rule.props, matches: [...(part.match(rule.match) ?? [])], html }
45 })
46 )}
47
48 {#if match}
49 <match.component {...match.props} />
50 {:else}
51 {@html part}
52 {/if}
53{/each}