Debian Codegraph @

frontend/src/lib/dom.ts

raw
1 import { parseJSON } from "./json";
2 import type { Result } from "./result";
3 import { err } from "./result";
4 import type { ValidationError, Validator } from "./validation";
5
6 class ScriptTagNotFoundError extends Error {
7 constructor(selector: string) {
8 super(`<script> tag not found for selector '${selector}'`);
9 }
10 }
11
12 /**
13 * Get the parsed content of a script tag containing JSON.
14 * @param selector A DOM selector string.
15 */
16 function getScriptTagJSON(
17 selector: string,
18 ): Result<unknown, ScriptTagNotFoundError | SyntaxError> {
19 const el = document.querySelector(selector);
20 if (!el) {
21 return err(new ScriptTagNotFoundError(selector));
22 }
23 return parseJSON(el.textContent ?? "");
24 }
25
26 /**
27 * Get the parsed content of a script tag containing JSON.
28 * @param selector - A DOM selector string.
29 * @param validator - Validator for the contents of the <script> tag.
30 */
31 export function getScriptTagValue<T>(
32 selector: string,
33 validator: Validator<T>,
34 ): Result<T, ScriptTagNotFoundError | SyntaxError | ValidationError> {
35 return getScriptTagJSON(selector).and_then(validator);
36 }