import { NODE, NodeTarget } from "./element-common.js"; import { ENV } from "./env.js"; import { createText } from "./internals/create-text.js"; import { createMapArrayState, MapArrayFn, MapArrayKeyFn, mapArrayUpdate } from "./internals/map-array.js"; import { NOOP } from "./internals/noop.js"; import { $, capture, computed, Expression, get, isolate, Signal, teardown, TeardownHook, watch } from "./signals.js"; import type { Component, Content, Falsy } from "./types.js"; import type { Attach, For, Index, Nest, Show } from "./view-jsx.js"; /** * Internal utility to create placeholder comments. */ function createPlaceholder(env: typeof globalThis): Node { return env.document.createComment("g"); } /** * Internal utility to create an arbitrary parent node. */ function createParent(env: typeof globalThis): Node { return env.document.createDocumentFragment(); } /** * Move all nodes from first to last (inclusive) to the specified parent. */ function moveNodes(first: Node, last: Node, parent: Node, ref: Node | null): void { let node = first; for (;;) { const next = node.nextSibling; if (ref === null) { parent.appendChild(node); } else { parent.insertBefore(node, ref); } if (node === last) { break; } node = next!; } } /** * Internal shorthand for creating the boundary comment of an empty view. * * @returns The created placeholder node. */ function emptyBoundary(setBoundary: ViewSetBoundaryFn, env: typeof globalThis): Node { const node = createPlaceholder(env); setBoundary(node, node); return node; } /** * Initialize a view's boundary and take ownership of future boundary changes. */ function adoptBoundary(view: View, setBoundary: ViewSetBoundaryFn): void { setBoundary(view.first, view.last); view.setBoundaryOwner(setBoundary); } /** * Internal shorthand for using the children of a node as boundary. */ function use(setBoundary: ViewSetBoundaryFn, node: Node, env: typeof globalThis): void { if (node.firstChild === null) { emptyBoundary(setBoundary, env); } else { setBoundary(node.firstChild, node.lastChild!); } } /** * Render arbitrary content. * * Supported content types are: * + Null and undefined (not displayed). * + Arbitrarily nested arrays/fragments of content. * + DOM nodes. Children will be removed from document fragments. * + {@link View Views}. * + Anything created with rvx's jsx runtime. * + Anything else is displayed as text. * * @param content The content to render. * @returns A view instance or the `content` parameter itself if it's already a view. * * @example * ```tsx * import { $, render } from "rvx"; * * // Not displayed: * render(null); * render(undefined); * * // Arbitrarily nested arrays/fragments of content: * render([["Hello"], " World!"]); * render(<>{<>"Hello"}{" World!"}); * * // DOM nodes: * render(

Hello World!

); * render(document.createElement("input")); * render(document.createTextNode("Hello World!")); * render(someTemplate.content.cloneNode(true)); * * // Views: * render(render("Hello World!")); * render(when(true, () => "Hello World!")); * render({() => "Hello World!"}); * * // Text: * render("Hello World!"); * render(() => "Hello World!"); * render(42); * render($(42)); * ``` */ export function render(content: Content): View { if (content instanceof View) { return content; } return new View(setBoundary => { const env = ENV.current; if (Array.isArray(content)) { const flat = content.flat(Infinity) as Content[]; if (flat.length > 1) { const parent = createParent(env); for (let i = 0; i < flat.length; i++) { let part = flat[i]; if (part === null || part === undefined) { parent.appendChild(createPlaceholder(env)); } else { if (typeof part === "object" && NODE in part) { part = (part as NodeTarget)[NODE]; } if (part instanceof env.Node) { if (part.nodeType === 11 && part.childNodes.length === 0) { parent.appendChild(createPlaceholder(env)); } else { parent.appendChild(part); } } else if (part instanceof View) { part.move(parent); if (i === 0) { part.setBoundaryOwner((first, _last) => setBoundary(first, undefined)); } else if (i === flat.length - 1) { part.setBoundaryOwner((_first, last) => setBoundary(undefined, last)); } } else { parent.appendChild(createText(part, env)); } } } use(setBoundary, parent, env); return; } content = flat[0]; } if (content === null || content === undefined) { emptyBoundary(setBoundary, env); } else { if (typeof content === "object" && NODE in content) { content = (content as NodeTarget)[NODE]; } if (content instanceof env.Node) { if (content.nodeType === 11) { use(setBoundary, content, env); } else { setBoundary(content, content); } } else if (content instanceof View) { adoptBoundary(content, setBoundary); } else { const text = createText(content, env); setBoundary(text, text); } } }); } /** * Render arbitrary content and append it to the specified parent until the current lifecycle is disposed. * * @param parent The parent node. * @param content The content to render. See {@link render} for supported types. * @returns The view instance. * * @example * ```tsx * import { mount } from "rvx"; * * mount( * document.body, *

Hello World!

* ); * ``` * * Since the content is removed when the current lifecycle is disposed, this can also be used to temporarily append * content to different elements while some component is rendered: * ```tsx * import { mount, Content } from "rvx"; * * function Popover(props: { text: Content, children: Content }) { * const visible = $(false); * * mount( * document.body, * * {props.children} * * ); * * return ; * } * * mount( * document.body, * * Hello World! * * ); * ``` */ export function mount(parent: Node, content: Content): View { const view = render(content); view.move(parent); teardown(() => view.detach()); return view; } /** * A function that is called when the view boundary may have been changed. */ export interface ViewBoundaryOwner { /** * @param first The current first node. * @param last The current last node. */ (first: Node, last: Node): void; } /** * A function that must be called after the view boundary has been changed. */ export interface ViewSetBoundaryFn { /** * @param first The first node if changed. * @param last The last node if changed. */ (first: Node | undefined, last: Node | undefined): void; } interface UninitViewProps { /** * The current first node of this view. * * + This may be undefined while the view is not fully initialized. * + This property is not reactive. */ get first(): Node | undefined; /** * The current last node of this view. * * + This may be undefined while the view is not fully initialized. * + This property is not reactive. */ get last(): Node | undefined; } export type UninitView = UninitViewProps & Omit; /** * A function that is called once to initialize a view instance. * * View creation will fail if no first or last node has been set during initialization. */ export interface ViewInitFn { /** * @param setBoundary A function that must be called after the view boundary has been changed. * @param self The current view itself. This can be used to keep track of the current boundary and parent nodes. */ (setBoundary: ViewSetBoundaryFn, self: UninitView): void; } /** * Represents a sequence of at least one DOM node. * * Consumers of the view API need to guarantee that: * + The sequence of nodes is not modified from the outside. * + If there are multiple nodes, all nodes must have a common parent node at all time. */ export class View { #first!: Node; #last!: Node; #owner: ViewBoundaryOwner | undefined; /** * Create a new view. * * View implementations need to guarantee that: * + The view doesn't break when the parent node is replaced or when a view consisting of only a single node is detached from its parent. * + The boundary is updated immediately after the first or last node has been updated. * + If there are multiple nodes, all nodes remain in the current parent. * + If there are multiple nodes, the initial nodes must have a common parent. */ constructor(init: ViewInitFn) { init((first, last) => { if (first) { this.#first = first; } if (last) { this.#last = last; } this.#owner?.(this.#first, this.#last); }, this); if (!this.#first || !this.#last) { // View boundary was not completely initialized: throw new Error("G1"); } } /** * The current first node of this view. * * Note, that this property is not reactive. */ get first(): Node { return this.#first; } /** * The current last node of this view. * * Note, that this property is not reactive. */ get last(): Node { return this.#last; } /** * The current parent node or undefined if there is none. * * Note, that this property is not reactive. */ get parent(): Node | undefined { return this.#first?.parentNode ?? undefined; } /** * Set the boundary owner for this view until the current lifecycle is disposed. * * @throws An error if there currently is a boundary owner. */ setBoundaryOwner(owner: ViewBoundaryOwner): void { if (this.#owner !== undefined) { // View already has a boundary owner: throw new Error("G2"); } this.#owner = owner; teardown(() => this.#owner = undefined); } /** * Append all nodes of this view to the specified parent. * * @param parent The parent to append to. * @deprecated Use {@link move} instead. */ appendTo(parent: Node): void { this.move(parent); } /** * Insert all nodes of this view before a reference child of the specified parent. * * @param parent The parent to insert into. * @param ref The reference child to insert before. If this is null, the nodes are appended to the parent. * @deprecated Use {@link move} instead. */ insertBefore(parent: Node, ref: Node | null): void { this.move(parent, ref); } /** * Move all nodes of this view into the specified parent. * * @param parent The parent to move into. * @param before A child of the specified parent to insert before, or null or undefined to append. */ move(parent: Node, before: Node | null = null) { moveNodes(this.#first, this.#last, parent, before); } /** * Detach all nodes of this view from the current parent if there is one. * * If there are multiple nodes, they are moved into a new document fragment to allow the view implementation to stay alive. * * @returns The single removed node or the document fragment they have been moved into. */ detach(): Node | DocumentFragment { const first = this.#first; const last = this.#last; if (first === last) { first.parentNode?.removeChild(first); return first; } else { const fragment = createParent(ENV.current); this.move(fragment); return fragment; } } } /** * Get an iterator over all current top level nodes of a view. * * @param view The view. * @returns The iterator. * * @example * ```tsx * import { render, viewNodes } from "rvx"; * * const view = render(<> *

Hello World!

* ); * * for (const node of viewNodes(view)) { * console.log(node); * } * ``` */ export function * viewNodes(view: View): IterableIterator { let node = view.first; for (;;) { const next = node.nextSibling!; yield node; if (node === view.last) { break; } node = next; } } const _nestDefault = ((component: Component | null | undefined) => component?.()) as Component; /** * Watch an expression and render content from its result. * * + If an error is thrown during initialization, the error is re-thrown. * + If an error is thrown during a signal update, the previously rendered content is kept in place and the error is re-thrown. * + Content returned from the component can be directly reused within the same `nest` instance. * * See {@link Nest ``} when using JSX. * * @param expr The expression to watch. * @param component The component to render with the expression result. If the expression returns a component, null or undefined, this can be omitted. * * @example * ```tsx * import { $, nest, e } from "rvx"; * * const count = $(0); * * // Using the expression result in a component: * nest(count, count => { * switch (count) { * case 0: return e("h1").append("Hello World!"); * case 1: return "Something else..."; * } * }) * * // Or directly returning a component from the expression: * nest(() => { * switch (count.value) { * case 0: return () => e("h1").append("Hello World!"); * case 1: return () => "Something else..."; * } * }) * ``` */ export function nest(expr: Expression): View; export function nest(expr: Expression, component: Component>): View; export function nest(expr: Expression, component: Component = _nestDefault): View { return new View((setBoundary, self) => { watch(expr, value => { const last: Node | undefined = self.last; const parent = last?.parentNode; let view: View; if (parent) { const anchor = last.nextSibling; self.detach(); view = render(component(value)); view.move(parent, anchor); } else { view = render(component(value)); } adoptBoundary(view, setBoundary); }); }); } /** * Render conditional content. * * + Content is only re-rendered if the expression result is not strictly equal to the previous one. If this behavior is undesired, use {@link nest} instead. * + If an error is thrown by the expression or component during initialization, the error is re-thrown. * + If an error is thrown by the expression or component during a signal update, the previously rendered content is kept and the error is re-thrown. * * See {@link Show ``} when using JSX. * * @param condition The condition to watch. * @param truthy The component to render when the condition result is truthy. * @param falsy An optional component to render when the condition is falsy. * * @example * ```tsx * import { $, when, e } from "rvx"; * * const message = $("Hello World!"); * * when(message, value => e("h1").append(value), () => "No message...") * ``` */ export function when(condition: Expression, truthy: Component>, falsy?: Component): View { return nest(computed(condition), value => value ? truthy(value) : falsy?.()); } export interface ForContentFn { /** * @param value The value. * @param index An expression to get the current index. * @returns The content. */ (value: T, index: () => number): Content; } /** * Render content for each entry in an iterable. * * Errors thrown by the component or while updating an index result in undefined behavior. * * See {@link For ``} for use with JSX. * * @param each The expression to watch. Note, that observables accessed during iteration will also trigger updates. * @param component The component to render for each entry. * @param keyFn A function to get the key for a given value. If not specified, the value is used as key. * * @example * ```tsx * import { $, forEach, e } from "rvx"; * * const items = $([1, 2, 3]); * * forEach(items, value => e("li").append(value)) * ``` */ export function forEach(each: Expression>, component: ForContentFn>, keyFn?: MapArrayKeyFn>): View { return new View(setBoundary => { const env = ENV.current; const first = emptyBoundary(setBoundary, env); const mapFn: MapArrayFn = (input, index) => render(component(input, index)); const state = createMapArrayState(); watch(() => { const update = mapArrayUpdate(state, get(each), mapFn, keyFn); if (update !== null) { let parent = first.parentNode as Node | null; if (parent === null) { parent = createParent(env); parent.appendChild(first); } for (let i = 0; i < update.p.length; i++) { const entry = update.p[i]; if (entry.r) { entry.o.detach(); } } let prev = update.s > 0 ? state[update.s - 1].o.last : first; for (let i = 0; i < update.n.length; i++) { const view = update.n[i].o; if (prev.nextSibling !== view.first) { view.move(parent, prev.nextSibling); } prev = view.last; } if (update.e === state.length) { setBoundary(undefined, prev); } } }); }); } export interface IndexContentFn { /** * @param value An expression to get the current value. * @param index The index. * @returns The content. */ (value: () => T, index: number): Content; } /** * Render content for each index in an iterable. * * Errors thrown by the component or while updating a value result in undefined behavior. * * See {@link Index ``} when using JSX. * * @param each The expression to watch. Note, that observables accessed during iteration will also trigger updates. * @param component The component to render for each index. * * @example * ```tsx * import { $, indexEach, e } from "rvx"; * * const items = $([1, 2, 3]); * * indexEach(items, value => e("li").append(value)) * ``` */ export function indexEach(each: Expression>, component: IndexContentFn>): View { return new View((setBoundary, self) => { interface Instance { /** input value */ i: Signal; /** view */ v: View; /** dispose */ d: TeardownHook; } const env = ENV.current; const state: Instance[] = []; const first = emptyBoundary(setBoundary, env); teardown(() => { for (let i = state.length - 1; i >= 0; i--) { state[i].d(); } }); watch(() => { let parent = first.parentNode as Node | null; if (!parent) { parent = createParent(env); parent.appendChild(first); } let index = 0; for (const value of get(each)) { if (index < state.length) { const instance = state[index]; instance.i.value = value; } else { const signal = $(value); let view!: View; const dispose = isolate(capture, () => { view = render(component(() => signal.value, index)); }); state.push({ i: signal, v: view, d: dispose, }); const prev = index > 0 ? state[index - 1].v.last : first; view.move(parent, prev.nextSibling); } index++; } while (state.length > index) { const instance = state.pop()!; instance.d(); instance.v.detach(); } const last = state.length > 0 ? state[state.length - 1].v.last : first; if (self.last !== last) { setBoundary(undefined, last); } }); }); } /** * Create a component for safely moving or reusing already rendered content. * * @example * ```tsx * const content = movable(

Hello World!

); * * * {content} * * * {content} * * ``` */ export function movable(content: Content): Component { const env = ENV.current; const inner = render(content); let dispose: TeardownHook = NOOP; return () => new View((setBoundary, self) => { dispose(); dispose = capture(() => { teardown(() => { const removed = createPlaceholder(env); self.parent?.insertBefore(removed, self.first!); self.detach(); setBoundary(removed, removed); }); adoptBoundary(inner, setBoundary); }); }); } /** * Attach or detach content depending on an expression. * * Content is kept alive when detached. * * See {@link Attach ``} when using JSX. * * @param condition The condition to watch. * @param content The content to attach when the condition result is truthy. * * @example * ```tsx * import { $, attachWhen } from "rvx"; * * const showMessage = $(true); * * attachWhen(showMessage, e("h1").append("Hello World!")) * ``` */ export function attachWhen(condition: Expression, content: Content): View { return nest(condition, value => value ? content : undefined); }