import type { Inputs, RimmelComponent, SourceBindingConfiguration, SinkBindingConfiguration } from './types/internal'; import type { Sink } from './types/sink'; import { RESOLVE_SELECTOR } from "./constants"; import { isSinkBindingConfiguration, isSourceBindingConfiguration } from './types/internal'; import { Rimmel_Bind_Subtree, Rimmel_Mount } from "./lifecycle/data-binding"; import { asap, subscribe } from "./lib/drain"; import { waitingElementHandlers } from "./internal-state"; import { BehaviorSubject, Subject } from "rxjs"; import { camelCase } from './utils/camelCase'; import { InnerHTMLSink } from './sinks/inner-html-sink'; export type CustomElementDefinition = { observedAttributes?: string[] render?: (this: HTMLElement, props: Record) => void; connectedCallback?: (this: HTMLElement) => void; disconnectedCallback?: (this: HTMLElement) => void; attributeChangedCallback?: (this: HTMLElement, name: string, oldValue: string, newValue: string) => void; } interface RMLNamedNodeMap extends NamedNodeMap { resolve: Attr; } const SubjectProxy = (defaults: Record = {}) => { const subjects = | Subject>>{}; return new Proxy({}, { get(_target, prop) { return subjects[prop] ?? (subjects[prop] = prop in defaults ? new BehaviorSubject(defaults[prop]) : new Subject()); } }); }; class RimmelElement extends HTMLElement { component: RimmelComponent | null | undefined; attrs: Inputs; #externalMutationObserver?: MutationObserver; #lightMutationObserver?: MutationObserver; #shadowMutationObserver?: MutationObserver; extSinks?: Record; /** * Attributes on the external HTML element */ externalSourceAttributes?: Record>; bindings?: {}; constructor(component: RimmelComponent | null | undefined, initFn?: Function) { super(); if(component) { this.component = component; this.attachShadow({ mode: 'open' }); } const [attrs, events] = [...(this.attributes)].reduce((acc, b) => { // FIXME: REF0000266279391633 this is an awful way to look up leftover event handlers from the parser. const isEvent = <0 | 1>+/^_?on/.test(b.nodeName); const t = acc[isEvent]; t[isEvent ? b.nodeName : camelCase(b.nodeName)] = b.nodeValue!; return acc; }, [{}, {}] as [Record, Record]); const bindingRef = (this.attributes as RMLNamedNodeMap).resolve?.nodeValue ?? ''; const refs = waitingElementHandlers.get(bindingRef) ?? []; const sinkBindingConfigurations = refs.filter(isSinkBindingConfiguration); sinkBindingConfigurations .map((s: SinkBindingConfiguration) => camelCase(s.t)) .forEach(name => delete attrs[name]) ; this.attrs = SubjectProxy(attrs); // This condition holds for non-virtual custom elements. Won't be needed anymore if we split web components from virtual web components if(refs.length) { // Connect/Bind Outbound Events Object.keys(events) .map(name => ([]>refs).find(x => isSourceBindingConfiguration(x))) .filter(f=>!!f) .forEach(f => { // TODO: store subscription for later removal const subscription = subscribe(this, this.attrs[`on${f.eventName}`], f.listener) }) ; this.extSinks = Object.fromEntries( sinkBindingConfigurations // .map(s => {[s.t]: s.sink = hijack?... .map((s: SinkBindingConfiguration) => [camelCase(s.t), s.source]) ); // Inbound Attributes Object.entries(this.extSinks).forEach(([name, source]) => { subscribe(this, source, this.attrs[name]); }); this.externalSourceAttributes = Object.fromEntries( sinkBindingConfigurations // .map(s => {[s.t]: s.sink = hijack?... .map((s: SinkBindingConfiguration) => [s.t, s.sink]) ); // Outbound Events this.bindings = Object.fromEntries( refs.map(s => isSinkBindingConfiguration(s) ? [s.t, s.source ] : [(s as SourceBindingConfiguration).eventName, (s as SourceBindingConfiguration).listener ] ) ); const sourceBindingConfigurations = refs.filter(isSourceBindingConfiguration); if(sourceBindingConfigurations.length) { waitingElementHandlers.set(bindingRef, sourceBindingConfigurations); } else { waitingElementHandlers.delete(bindingRef); } } initFn?.(this, this.attrs); } render() { // this.shadowRoot!.innerHTML = this.component!(this.attrs); if(this.shadowRoot) { const sink = InnerHTMLSink(this.shadowRoot); asap(sink, this.component!(this.attrs)); } } connectedCallback() { // Monitor attribute changes on the custom element this.#externalMutationObserver = new MutationObserver((mutations) => { mutations.forEach(mutation => { const attrName = mutation.attributeName; const key = camelCase(attrName); const v = this.getAttribute(attrName); this.attrs[key].next(v); }); }); this.#externalMutationObserver.observe(this, { attributes: true, childList: false, subtree: false }); // Monitor all other (RML) changes within the custom element, for data binding this.#lightMutationObserver = new MutationObserver(Rimmel_Mount); this.#lightMutationObserver.observe(this, { attributes: false, childList: true, subtree: true }); if(this.shadowRoot) { this.#shadowMutationObserver = new MutationObserver(Rimmel_Mount); this.#shadowMutationObserver.observe(this.shadowRoot, { attributes: false, childList: true, subtree: true }); } if(this.component) { this.render(); [...this.shadowRoot?.children ?? [], ...this.shadowRoot!.querySelectorAll(RESOLVE_SELECTOR)] .forEach(s => { Rimmel_Bind_Subtree(s) }) ; } } disconnectedCallback() { // AKA: unmount this.#externalMutationObserver?.disconnect(); this.#lightMutationObserver?.disconnect(); this.#shadowMutationObserver?.disconnect(); } }; /** * Register a Rimmel Component as a Custom Element in the DOM * * ## Examples * * ### Create a simple "Hello, World" web component * ```ts * import { rml, RegisterElement } from 'rimmel'; * * RegisterElement('custom-element', () => { * return rml` *

Hello, world

* `; * } * ``` **/ export const RegisterElement = (tagName: string, component: RimmelComponent | null | undefined, initFn?: Function) => { // FIXME: prevent redefinition... // TODO: UnregisterElement? customElements.define(tagName, class extends RimmelElement { constructor() { super(component, initFn); } }); };