import { EventStream, EventStreamSeed, isEventStream, isProperty, isPropertySeed, Observer, Property, PropertySeed, Scope, Subscribe, } from "./abstractions" import { applyScopeMaybe } from "./applyscope" import { mapSubscribe } from "./map" import { PropertySeedImpl, StatelessProperty } from "./property" import { globalScope } from "./scope" export interface ToStatelessPropertyOp { (stream: EventStream | Subscribe): Property } export function toStatelessProperty(get: () => A): ToStatelessPropertyOp export function toStatelessProperty(get: () => A) { return (streamOrSubscribe: any) => { if (isEventStream(streamOrSubscribe)) { return new StatelessProperty( streamOrSubscribe.desc, get, mapSubscribe(streamOrSubscribe.subscribe.bind(streamOrSubscribe), get), streamOrSubscribe.getScope() ) } else { return new StatelessProperty( [streamOrSubscribe, "toStatelessProperty", [get]], get, mapSubscribe(streamOrSubscribe, get), globalScope ) } } } export interface ToPropertyOp { (stream: EventStream | EventStreamSeed): PropertySeed } export interface ToPropertyOpScoped { (stream: EventStream | EventStreamSeed): Property } export function toProperty(initial: A): ToPropertyOp export function toProperty(initial: A, scope: Scope): ToPropertyOpScoped export function toProperty(initial: any, scope?: Scope) { return (seed: EventStream | EventStreamSeed) => { const source = seed.consume() return applyScopeMaybe( new PropertySeedImpl( [seed, "toProperty", [initial]], () => initial, (onValue, onEnd) => { return source.subscribe(onValue, onEnd) } ), scope ) } } export function toPropertySeed( property: Property | PropertySeed ): PropertySeed { if (!isProperty(property)) { if (!isPropertySeed(property)) { throw Error("Assertion fail") } return property } return new PropertySeedImpl( property.desc, property.get.bind(property), property.onChange.bind(property) ) }