/* # Custom View / Push !!! tip This example exists solely to demonstrate what's possible with the view API. You will most likely never need to implement a custom view, except in cases with extreme performance requirements. This example shows a custom view that pushes elements onto itself. This can be useful when you only ever append or prepend elements and you require the absolute best performance possible. */ import { $obj, capture, Component, Emitter, Event, Nest, render, teardown, TeardownHook, View } from "rvx"; export function Example() { const reset = $obj(); const actions = new Emitter<[Action, number]>(); return
; } type Action = "prepend" | "append"; function PushView(props: { children: Component; actions: Event<[Action, T]>; }) { return new View((setBoundary, self) => { // Keep an array of teardown hooks to dispose instances later: const dispose: TeardownHook[] = []; teardown(() => dispose.forEach(h => h())); // Create an initial anchor element: const anchor = document.createComment(""); setBoundary(anchor, anchor); // Handle action events: props.actions((action, item) => { let parent: Node | null = anchor.parentElement; if (!parent) { // Create a parent if there is none: parent = document.createDocumentFragment(); parent.appendChild(anchor); } // Render the item into a view & capture its lifecycle: let view!: View; dispose.push(capture(() => { view = render(props.children(item)); })); // Append or prepend the item view to this one: if (action === "append") { view.move(parent, self.last!.nextSibling); setBoundary(undefined, view.last); } else { view.move(parent, self.first!); setBoundary(view.first, undefined); } }); }); }