src/html.ts
34 lines and 4 functions in DrDustinEdwards/enarratio, at commit 4c5695a on 2026-10-24. This file on GitHub.
Functions
| Function | Lines | Complexity | Covered | CRAP | Mutation |
|---|---|---|---|---|---|
| escapeHtml | 15 to 17 | 1 | 100% | OkCRAP 1 | Ok100% |
| <anonymous:16> | 16 to 16 | 2 | 100% | OkCRAP 2 | Ok100% |
| attributes | 23 to 30 | 5 | 100% | OkCRAP 5 | Watch72.2% |
| element | 33 to 39 | 1 | 100% | OkCRAP 1 | Ok100% |
Imports
It imports no other module of this repo. Imported by src/index.ts, src/lite/svg.ts, src/primitives/heat-strip.ts, src/primitives/progress-ring.ts, src/primitives/sparkline.ts, src/primitives/timeline.ts, src/primitives/uptime-strip.ts, src/render/figure.ts, src/render/plot.ts.
Source
/**
* HTML string building. Every chart returns a string so it can be written into any server
* template, and every piece of caller text that reaches that string passes through these helpers.
*/
const ESCAPES: Readonly<Record<string, string>> = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'",
};
/** Escapes text for use as HTML element content or as a double-quoted attribute value. */
export function escapeHtml(value: string): string {
return value.replace(/[&<>"']/g, (ch) => ESCAPES[ch] ?? ch);
}
/** An attribute value; `false` and `undefined` omit the attribute, `true` writes it bare. */
export type AttributeValue = string | number | boolean | undefined;
/** Serializes attributes in the order given, skipping omitted ones. */
function attributes(attrs: Readonly<Record<string, AttributeValue>>): string {
let out = "";
for (const [name, value] of Object.entries(attrs)) {
if (value === undefined || value === false) continue;
out += value === true ? ` ${name}` : ` ${name}="${escapeHtml(String(value))}"`;
}
return out;
}
/** One element as a string. `children` is trusted markup: callers escape text before passing it. */
export function element(
tag: string,
attrs: Readonly<Record<string, AttributeValue>>,
children = "",
): string {
return `<${tag}${attributes(attrs)}>${children}</${tag}>`;
}