| ... | @@ -0,0 +1,300 @@ | ... | @@ -0,0 +1,300 @@ |
| | 1 | // Clover's Rendering Engine is the backbone of her website generator. It
|
| | 2 | // converts objects and components (functions returning 'Node') into HTML. The
|
| | 3 | // engine is simple and self-contained, with integrations for JSX and Marko
|
| | 4 | // (which can interop with each-other) are provided next to this file.
|
| | 5 | //
|
| | 6 | // Add-ons to the rendering engine can provide opaque data, And retrieve it
|
| | 7 | // within component calls with 'getAddonData'. For example, 'sitegen' uses this
|
| | 8 | // to track needed client scripts without introducing patches to the engine.
|
| | 9 |
|
| | 10 | type AddonData = Record<string | symbol, unknown>;
|
| | 11 | export function ssrSync(node: Node): Result;
|
| | 12 | export function ssrSync<A extends AddonData>(
|
| | 13 | node: Node,
|
| | 14 | addon: AddonData,
|
| | 15 | ): Result<A>;
|
| | 16 | export function ssrSync(node: Node, addon: AddonData = {}) {
|
| | 17 | const r = initRender(false, addon);
|
| | 18 | const resolved = resolveNode(r, node);
|
| | 19 | return { text: renderNode(resolved), addon };
|
| | 20 | }
|
| | 21 | export function ssrAsync(node: Node): Promise<Result>;
|
| | 22 | export function ssrAsync<A extends AddonData>(
|
| | 23 | node: Node,
|
| | 24 | addon: AddonData,
|
| | 25 | ): Promise<Result<A>>;
|
| | 26 | export function ssrAsync(node: Node, addon: AddonData = {}) {
|
| | 27 | const r = initRender(true, addon);
|
| | 28 | const resolved = resolveNode(r, node);
|
| | 29 | if (r.async === 0) {
|
| | 30 | return Promise.resolve({ text: renderNode(resolved), addon });
|
| | 31 | }
|
| | 32 | const { resolve, reject, promise } = Promise.withResolvers<Result>();
|
| | 33 | r.asyncDone = () => {
|
| | 34 | const rejections = r.rejections;
|
| | 35 | if (!rejections) return resolve({ text: renderNode(resolved), addon });
|
| | 36 | if (rejections.length === 1) return reject(rejections[0]);
|
| | 37 | return reject(new AggregateError(rejections));
|
| | 38 | };
|
| | 39 | return promise;
|
| | 40 | }
|
| | 41 |
|
| | 42 | /** Inline HTML into a render without escaping it */
|
| | 43 | export function html(rawText: string) {
|
| | 44 | return [kDirectHtml, rawText];
|
| | 45 | }
|
| | 46 |
|
| | 47 | interface Result<A extends AddonData = AddonData> {
|
| | 48 | text: string;
|
| | 49 | addon: A;
|
| | 50 | }
|
| | 51 |
|
| | 52 | export interface Render {
|
| | 53 | /**
|
| | 54 | * Set to '-1' if rendering synchronously
|
| | 55 | * Number of async promises the render is waiting on.
|
| | 56 | */
|
| | 57 | async: number | -1;
|
| | 58 | asyncDone: null | (() => void);
|
| | 59 | /** When components reject, those are logged here */
|
| | 60 | rejections: unknown[] | null;
|
| | 61 | /** Add-ons to the rendering engine store state here */
|
| | 62 | addon: AddonData;
|
| | 63 | }
|
| | 64 |
|
| | 65 | export const kElement = Symbol("Element");
|
| | 66 | export const kDirectHtml = Symbol("DirectHtml");
|
| | 67 |
|
| | 68 | /** Node represents a webpage that can be 'rendered' into HTML. */
|
| | 69 | export type Node =
|
| | 70 | | number
|
| | 71 | | string // Escape HTML
|
| | 72 | | Node[] // Concat
|
| | 73 | | Element // Render
|
| | 74 | | DirectHtml // Insert
|
| | 75 | | Promise<Node> // Await
|
| | 76 | // Ignore
|
| | 77 | | undefined
|
| | 78 | | null
|
| | 79 | | boolean;
|
| | 80 | export type Element = [
|
| | 81 | tag: typeof kElement,
|
| | 82 | type: string | Component,
|
| | 83 | props: Record<string, unknown>,
|
| | 84 | ];
|
| | 85 | export type DirectHtml = [tag: typeof kDirectHtml, html: string];
|
| | 86 | /**
|
| | 87 | * Components must return a value; 'undefined' is prohibited here
|
| | 88 | * to avoid functions that are missing a return statement.
|
| | 89 | */
|
| | 90 | export type Component = (
|
| | 91 | props: Record<string, unknown>,
|
| | 92 | ) => Exclude<Node, undefined>;
|
| | 93 |
|
| | 94 | /**
|
| | 95 | * Resolution narrows the type 'Node' into 'ResolvedNode'. Async trees are
|
| | 96 | * marked in the 'Render'. This operation performs everything besides the final
|
| | 97 | * string concatenation. This function is agnostic across async/sync modes.
|
| | 98 | */
|
| | 99 | export function resolveNode(r: Render, node: unknown): ResolvedNode {
|
| | 100 | if (!node && node !== 0) return ""; // falsy, non numeric
|
| | 101 | if (typeof node !== "object") {
|
| | 102 | if (node === true) return ""; // booleans are ignored
|
| | 103 | if (typeof node === "string") return escapeHTML(node);
|
| | 104 | if (typeof node === "number") return String(node); // no escaping ever
|
| | 105 | throw new Error(`Cannot render ${inspect(node)} to HTML`);
|
| | 106 | }
|
| | 107 | if (node instanceof Promise) {
|
| | 108 | if (r.async === -1) {
|
| | 109 | throw new Error(`Asynchronous rendering is not supported here.`);
|
| | 110 | }
|
| | 111 | const placeholder: InsertionPoint = [null];
|
| | 112 | r.async += 1;
|
| | 113 | node
|
| | 114 | .then((result) => void (placeholder[0] = resolveNode(r, result)))
|
| | 115 | // Intentionally catching errors in `resolveNode`
|
| | 116 | .catch((e) => (r.rejections ??= []).push(e))
|
| | 117 | .finally(() => {
|
| | 118 | if (--r.async == 0) {
|
| | 119 | if (r.asyncDone == null) throw new Error("r.asyncDone == null");
|
| | 120 | r.asyncDone();
|
| | 121 | r.asyncDone = null;
|
| | 122 | }
|
| | 123 | });
|
| | 124 | // This lie is checked with an assertion in `renderNode`
|
| | 125 | return placeholder as [ResolvedNode];
|
| | 126 | }
|
| | 127 | if (!Array.isArray(node)) {
|
| | 128 | throw new Error(`Invalid node type: ${inspect(node)}`);
|
| | 129 | }
|
| | 130 | const type = node[0];
|
| | 131 | if (type === kElement) {
|
| | 132 | const { 1: tag, 2: props } = node;
|
| | 133 | if (typeof tag === "function") {
|
| | 134 | currentRender = r;
|
| | 135 | const result = tag(props);
|
| | 136 | currentRender = null;
|
| | 137 | return resolveNode(r, result);
|
| | 138 | }
|
| | 139 | if (typeof tag !== "string") throw new Error("Unexpected " + typeof type);
|
| | 140 | const children = props?.children;
|
| | 141 | if (children) return [kElement, tag, props, resolveNode(r, children)];
|
| | 142 | return node;
|
| | 143 | }
|
| | 144 | if (type === kDirectHtml) return node[1];
|
| | 145 | return node.map((elem) => resolveNode(r, elem));
|
| | 146 | }
|
| | 147 |
|
| | 148 | export type ResolvedNode =
|
| | 149 | | ResolvedNode[] // Concat
|
| | 150 | | ResolvedElement // Render
|
| | 151 | | string; // Direct HTML
|
| | 152 | export type ResolvedElement = [
|
| | 153 | tag: typeof kElement,
|
| | 154 | type: string,
|
| | 155 | props: Record<string, unknown>,
|
| | 156 | children: ResolvedNode,
|
| | 157 | ];
|
| | 158 | /**
|
| | 159 | * Async rendering is done by creating an array of one item,
|
| | 160 | * which is already a valid 'Node', but the element is written
|
| | 161 | * once the data is available. The 'Render' contains a count
|
| | 162 | * of how many async jobs are left.
|
| | 163 | */
|
| | 164 | export type InsertionPoint = [null | ResolvedNode];
|
| | 165 |
|
| | 166 | /**
|
| | 167 | * Convert 'ResolvedNode' into HTML text. This operation happens after all
|
| | 168 | * async work is settled. The HTML is emitted as concisely as possible.
|
| | 169 | */
|
| | 170 | export function renderNode(node: ResolvedNode): string {
|
| | 171 | if (typeof node === "string") return node;
|
| | 172 | ASSERT(node, "Unresolved Render Node");
|
| | 173 | const type = node[0];
|
| | 174 | if (type === kElement) {
|
| | 175 | return renderElement(node as ResolvedElement);
|
| | 176 | }
|
| | 177 | node = node as ResolvedNode[]; // TS cannot infer.
|
| | 178 | let out = type ? renderNode(type) : "";
|
| | 179 | let len = node.length;
|
| | 180 | for (let i = 1; i < len; i++) {
|
| | 181 | const elem = node[i];
|
| | 182 | if (elem) out += renderNode(elem);
|
| | 183 | }
|
| | 184 | return out;
|
| | 185 | }
|
| | 186 | function renderElement(element: ResolvedElement) {
|
| | 187 | const { 1: tag, 2: props, 3: children } = element;
|
| | 188 | let out = "<" + tag;
|
| | 189 | let needSpace = true;
|
| | 190 | for (const prop in props) {
|
| | 191 | const value = props[prop];
|
| | 192 | if (!value || typeof value === "function") continue;
|
| | 193 | let attr;
|
| | 194 | switch (prop) {
|
| | 195 | default:
|
| | 196 | attr = `${prop}=${quoteIfNeeded(escapeHTML(String(value)))}`;
|
| | 197 | break;
|
| | 198 | case "className":
|
| | 199 | // Legacy React Compat
|
| | 200 | case "class":
|
| | 201 | attr = `class=${quoteIfNeeded(escapeHTML(clsx(value)))}`;
|
| | 202 | break;
|
| | 203 | case "htmlFor":
|
| | 204 | throw new Error("Do not use the `htmlFor` attribute. Use `for`");
|
| | 205 | // Do not process these
|
| | 206 | case "children":
|
| | 207 | case "ref":
|
| | 208 | case "dangerouslySetInnerHTML":
|
| | 209 | case "key":
|
| | 210 | continue;
|
| | 211 | }
|
| | 212 | if (needSpace) out += " ", needSpace = !attr.endsWith('"');
|
| | 213 | out += attr;
|
| | 214 | }
|
| | 215 | out += ">";
|
| | 216 | if (children) out += renderNode(children);
|
| | 217 | if (
|
| | 218 | tag !== "br" && tag !== "img" && tag !== "input" && tag !== "meta" &&
|
| | 219 | tag !== "link" && tag !== "hr"
|
| | 220 | ) {
|
| | 221 | out += `</${tag}>`;
|
| | 222 | }
|
| | 223 | return out;
|
| | 224 | }
|
| | 225 | export function renderStyleAttribute(style: Record<string, string>) {
|
| | 226 | let out = ``;
|
| | 227 | for (const styleName in style) {
|
| | 228 | if (out) out += ";";
|
| | 229 | out += `${styleName.replace(/[A-Z]/g, "-$&").toLowerCase()}:${
|
| | 230 | escapeHTML(String(style[styleName]))
|
| | 231 | }`;
|
| | 232 | }
|
| | 233 | return "style=" + quoteIfNeeded(out);
|
| | 234 | }
|
| | 235 | export function quoteIfNeeded(text) {
|
| | 236 | if (text.includes(" ")) return '"' + text + '"';
|
| | 237 | return text;
|
| | 238 | }
|
| | 239 |
|
| | 240 | // -- utility functions --
|
| | 241 |
|
| | 242 | export function initRender(allowAsync: boolean, addon: AddonData): Render {
|
| | 243 | return {
|
| | 244 | async: allowAsync ? 0 : -1,
|
| | 245 | rejections: null,
|
| | 246 | asyncDone: null,
|
| | 247 | addon,
|
| | 248 | };
|
| | 249 | }
|
| | 250 |
|
| | 251 | let currentRender: Render | null = null;
|
| | 252 | export function getCurrentRender() {
|
| | 253 | if (!currentRender) throw new Error("No Render Active");
|
| | 254 | return currentRender;
|
| | 255 | }
|
| | 256 | export function setCurrentRender(r?: Render | null) {
|
| | 257 | currentRender = r ?? null;
|
| | 258 | }
|
| | 259 | export function getUserData<T>(namespace: PropertyKey, def: () => T): T {
|
| | 260 | return (getCurrentRender().addon[namespace] ??= def()) as T;
|
| | 261 | }
|
| | 262 |
|
| | 263 | export function inspect(object: unknown) {
|
| | 264 | try {
|
| | 265 | return require("node:util").inspect(object);
|
| | 266 | } catch {
|
| | 267 | return typeof object;
|
| | 268 | }
|
| | 269 | }
|
| | 270 |
|
| | 271 | export type ClsxInput = string | Record<string, boolean | null> | ClsxInput[];
|
| | 272 | export function clsx(mix: ClsxInput) {
|
| | 273 | var k, y, str;
|
| | 274 | if (typeof mix === "string") {
|
| | 275 | return mix;
|
| | 276 | } else if (typeof mix === "object") {
|
| | 277 | str = "";
|
| | 278 | if (Array.isArray(mix)) {
|
| | 279 | for (k = 0; k < mix.length; k++) {
|
| | 280 | if (mix[k] && (y = clsx(mix[k]))) {
|
| | 281 | str && (str += " ");
|
| | 282 | str += y;
|
| | 283 | }
|
| | 284 | }
|
| | 285 | } else {
|
| | 286 | for (k in mix) {
|
| | 287 | if (mix[k]) {
|
| | 288 | str && (str += " ");
|
| | 289 | str += k;
|
| | 290 | }
|
| | 291 | }
|
| | 292 | }
|
| | 293 | }
|
| | 294 | return str;
|
| | 295 | }
|
| | 296 |
|
| | 297 | export const escapeHTML = (unsafeText: string) =>
|
| | 298 | String(unsafeText)
|
| | 299 | .replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")
|
| | 300 | .replace(/"/g, "&quot;").replace(/'/g, "&#x27;").replace(/`/g, "&#x60;");
|