import type { SinkFunction } from "../types/sink"; import type { EventListenerObject, EventListener, EventListenerFunction } from "../types/dom"; import type { Consumer, MaybeFuture, Observable, Observer, ObserverErrorFunction, ObserverFunction } from "../types/futures"; import type { RenderingScheduler } from "../types/schedulers"; import { isObservable, isPromise } from "../types/futures"; import { subscriptions } from "../internal-state"; // import renderingScheduler from '../schedulers/ema-animation-frame'; import { toListener } from "../utils/to-listener"; // TODO: what if we have a promise resolving to an observable or the other way around? // Those atypical combinations may not be automatically flattened... /** * Return the "callable" part of an entity: * - the next method of an Observer * - the handleEvent method of an EventListenerObject * - the function itself, if it's a function */ export const callable = (x: (Observer | EventListenerObject | ObserverFunction)) => (x as Observer).next ? (x as Observer).next.bind(x) : (x as EventListenerObject).handleEvent ? (x as EventListenerObject).handleEvent.bind(x) : (x as (t: T)=>any) ; export const asap = (target: Consumer, source: MaybeFuture) => { (>source)?.subscribe?.(target) ?? (>source)?.then?.(((target as Observer).next as ObserverFunction)?.bind(target) ?? target) ?? (target as ObserverFunction)(source as T); }; /** * Connect an event source to a sink through any compatible interface on any optionally specified scheduler * @param node The node on which the binding is set * @param source A Promise, Observable or EventEmitter * @param next A "next" or "then" handler on the sink side * @param error? An error handler on the sink side * @param complete? a finalisation function */ export const subscribe = // TODO: rename to bindEvent or something that implies this is for element events (node: Node, source: MaybeFuture, next: EventListener, error?: ObserverErrorFunction, complete?: () => void, scheduler?: RenderingScheduler) => { // TODO: make this a plugin, in case people don't use handleEvent... const flattenedNext = toListener(next); const task = scheduler?.(node, flattenedNext) ?? flattenedNext; if (isObservable(source)) { // TODO: should we handle promise cancellations (cancellable promises?) too? const subscription = source.subscribe({ next: task, error, complete, }); subscriptions.get(node)?.push(subscription) ?? subscriptions.set(node, [subscription]); return subscription; } else if (isPromise(source)) { source.then(task, error).finally(complete); } else { // TODO: should we handle function cancellations (removeEventListener) too? (task)(source); } } ;