import type { Inputs, RimmelComponent, SourceBindingConfiguration, SinkBindingConfiguration } from './types/internal'; import type { Future } from './types/futures'; import type { Sink } from './types/sink'; import { isSinkBindingConfiguration, isSourceBindingConfiguration } from './types/internal'; import { Rimmel_Mount } from "./lifecycle/data-binding"; import { subscribe } from "./lib/drain"; import { waitingElementHandlers } from "./internal-state"; import { BehaviorSubject, Subject } from "rxjs"; import { camelCase } from './utils/camelCase'; 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()) ); } }); }; const SubjectProxy2 = (initials: Record = {}, sources: Record> = {}) => { //const subjects = | Subject>>; const subjects = new Map>(); return new Proxy(sources, { get(_target, prop) { return ( _target[prop] ?? subjects.get(prop) ?? subjects.set(prop, prop in initials ? new BehaviorSubject(initials[prop]) : new Subject()).get(prop) ); } }); }; const SubjectProxyN = (initials: Record = {}, sources: Record>[] = []) => { const subjects = new Map>(); return new Proxy({}, { get(_target, prop) { return ( (sources.find(s => s[prop])?.[prop]) ?? subjects.get(prop) ?? subjects.set(prop, prop in initials ? new BehaviorSubject(initials[prop]) : new Subject()) .get(prop) ); } }); }; type AmbientEffectFunction = (el: Element, attrs: Record) => void; class EffectElement extends HTMLElement { component?: RimmelComponent; attrs: Inputs; #externalMutationObserver?: MutationObserver; #lightMutationObserver?: MutationObserver; #shadowMutationObserver?: MutationObserver; extSinks?: Record>; /** * Attributes on the external HTML element */ externalSourceAttributes?: Record>; bindings?: {}; constructor(initFn: AmbientEffectFunction) { super(); 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]; // FIXME: b.nodeValue would be [object Object] for objects that we're sinking... any better way to represent them? t[isEvent ? b.nodeName : camelCase(b.nodeName)] = b.nodeValue!; return acc; }, [{}, {}] as [Record, Record]); const refs = waitingElementHandlers.get((this.attributes as RMLNamedNodeMap).resolve?.nodeValue ?? '') ?? []; this.attrs = SubjectProxy(attrs); 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) }) ; // // TODO: lose this // const sinkBindingConfigurations = refs.filter(r => isSinkBindingConfiguration(r)); // this.extSinks = Object.fromEntries( // sinkBindingConfigurations // // .map(s => {[s.t]: s.sink = hijack?... // .map((s: SinkBindingConfiguration) => [camelCase(s.t), s.source]) // ); // // Inbound Attributes // 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) ? [camelCase(s.t), s.source ] : [`on${(s as SourceBindingConfiguration).eventName}`, (s as SourceBindingConfiguration).listener ] ) ); } //initFn?.(this, this.attrs, extSinks); // FIXME: maybe too much stuff is merged in? const attributeProxy = SubjectProxy2(attrs, this.bindings); initFn(this, attributeProxy); // initFn?.(this, { ...attrs, ...this.attrs, ...this.extSinks }); } connectedCallback() { // Monitor for attribute changes on the custom element this.#externalMutationObserver = new MutationObserver((mutations) => { mutations.forEach(mutation => { // FIXME: we're getting callbacks for Rimmel.s own "resolve" // attribute changes too. That's an internal thing and shouldn't // be exposed like ordinary attributes. const k = mutation.attributeName; const v = this.getAttribute(k); this.attrs[camelCase(k)].next(v); //this.bindings[k]?.next?.(v); // debugger; // this.externalSourceAttributes?.[k]?.next?.(v); // --- // Set the attribute on the custom element // Actually, don't, as it would cause an infinite loop // with this same mutationObserver... // Shall we just make it ignore self-originated changes // or should we just not set the attribute? // const sink = this.externalSourceAttributes?.[k]; // sink?.(this)(v); }); }); this.#externalMutationObserver.observe(this, { attributes: true, childList: false, subtree: false }); // Monitor for 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 }); } disconnectedCallback() { // AKA: unmount this.#externalMutationObserver?.disconnect(); this.#lightMutationObserver?.disconnect(); this.#shadowMutationObserver?.disconnect(); } }; /** * Register an Effect Handler as a Custom Element in the DOM * * ## Examples * * ### Create a simple effect handler * ```ts * import { AmbientEffect, asap } from 'rimmel'; * * AmbientEffect('browser-console', (el, { log }) => { * asap(log, console.log); * } * ``` **/ export const AmbientEffect = (tagName: string, initFn: AmbientEffectFunction) => { // FIXME: prevent redefinition... // TODO: UnregisterElement? customElements.define(tagName, class extends EffectElement { constructor() { super(initFn); } }); };