import { Observable, Executable, Fn } from "../Kinds/Kinds"; type Noop = null undefined…
- User
import { Observable, Executable, Fn } from "../Kinds/Kinds";
type Noop = null | undefined | void;
type Hooks = | Observable<void, any, Function | unknown> | Executable<E | void, unknown> | Fn<[E], unknown> | Noop;
const Render = (thunk: () => E, hooks: Hooks[]): E | void => { let res: E;
try { res = thunk(); } catch (err) { console.error(err); return; }
let executables: Executable<E | void, unknown>[] = []; let unsubs: Function[] = [];
const CLEANUP = () => { for (let i = 0; i < unsubs.length; i++) unsubs[i]!(); res = void 0 as never; executables = void 0 as never; unsubs = void 0 as never; hooks = void 0 as never; thunk = void 0 as never; };
const DISCONNECTED = () => res instanceof Node && !res.isConnected;
const RUN_EFFECTS = () => { try { for (let i = 0; i < executables.length; i++) executables[i]?.ex(res); if (DISCONNECTED()) CLEANUP(); } catch (err) { console.error(err); } };
const RENDER = () => { try { if (DISCONNECTED()) { CLEANUP(); return; } const next = thunk(); if (next instanceof Node && res instanceof Node && res.parentNode) { res.parentNode.replaceChild(next, res); } res = next; queueMicrotask(RUN_EFFECTS); } catch (err) { console.error(err); } };
for (let i = 0; i < hooks.length; i++) { const h = hooks[i]!; if ("sub" in h && typeof h.sub === "function") { const unsub = h.sub(() => { requestAnimationFrame(RENDER); }); if (typeof unsub === "function") unsubs.push(unsub); } else if ("ex" in h && typeof h.ex === "function") { executables.push(h); } else if (typeof h === "function") { requestAnimationFrame(() => h(res)); } }
queueMicrotask(RUN_EFFECTS);
return res; };
export { Render };
- Assistant