Debian Codegraph @

frontend/src/svelte-custom-elements.ts

raw
1 /**
2 * A custom element that will render a Svelte component.
3 */
4
5 import { type Component, mount, unmount } from "svelte";
6 import { get as store_get } from "svelte/store";
7
8 import type { FavaChart } from "./charts";
9 import { parseChartData } from "./charts";
10 import ChartSwitcher from "./charts/ChartSwitcher.svelte";
11 import { chartContext } from "./charts/context";
12 import { domHelpers } from "./charts/tooltip";
13 import { type Result } from "./lib/result";
14 import { log_error } from "./log";
15 import { query_table_validator } from "./reports/query/query_table";
16 import QueryTable from "./reports/query/QueryTable.svelte";
17
18 /** This class pairs the components and their validation functions to use them in a type-safe way. */
19 class SvelteCustomElementComponent<T extends Record<string, unknown>> {
20 constructor(
21 readonly type: string,
22 private readonly Component: Component<T>,
23 private readonly validate: (data: unknown) => Result<T, Error>,
24 ) {}
25
26 /** Load data and render the component for this route to the given target. */
27 render(target: SvelteCustomElement, data: unknown): (() => void) | undefined {
28 const res = this.validate(data);
29 if (res.is_err) {
30 target.setError(
31 `Rendering component '${this.type}' failed due to invalid JSON data:`,
32 domHelpers.br(),
33 res.error.message,
34 );
35 log_error(res.error);
36 log_error("Invalid JSON for component:", data);
37 return undefined;
38 }
39 const instance = mount(this.Component, { target, props: res.value });
40 return () => {
41 void unmount(instance);
42 };
43 }
44 }
45
46 const components = [
47 new SvelteCustomElementComponent<{ charts: readonly FavaChart[] }>(
48 "charts",
49 ChartSwitcher,
50 (data) =>
51 parseChartData(data, store_get(chartContext)).map((charts) => ({
52 charts,
53 })),
54 ),
55 new SvelteCustomElementComponent("query-table", QueryTable, (data) =>
56 query_table_validator(data).map((table) => ({ table })),
57 ),
58 ];
59
60 /**
61 * A custom element that represents a Svelte component.
62 *
63 * The tag should have a `type` attribute with one
64 * of the valid values in the Map above.
65 */
66 export class SvelteCustomElement extends HTMLElement {
67 private destroy?: () => void;
68
69 /** Show some error content. */
70 setError(...nodes_or_strings: (Node | string)[]): void {
71 this.classList.add("error");
72 this.replaceChildren("Error: ", ...nodes_or_strings);
73 }
74
75 connectedCallback(): void {
76 if (this.destroy) {
77 return;
78 }
79 const type = this.getAttribute("type");
80 if (type == null) {
81 this.setError("Component is missing type");
82 return;
83 }
84 const comp = components.find((t) => t.type === type);
85 if (!comp) {
86 this.setError(`Unknown component type: '${type}'`);
87 return;
88 }
89 const script = this.querySelector("script");
90 this.destroy = comp.render(
91 this,
92 script && script.type === "application/json"
93 ? JSON.parse(script.innerHTML)
94 : null,
95 );
96 }
97
98 disconnectedCallback(): void {
99 try {
100 this.destroy?.();
101 this.destroy = undefined;
102 // eslint-disable-next-line @typescript-eslint/no-unused-vars
103 } catch (e) {
104 // pass
105 }
106 }
107 }