import { noop } from 'lodash-unified' ; import { ValueRef } from '@dimensiondev/holoflows-kit' ; import type { Subscription } from 'use-subscription' ; export function createConstantSubscription < T > ( value ) { return { getCurrentValue : ( ) => value , subscribe : ( ) => noop , } ; } export function createSubscriptionFromAsync < T > ( f , defaultValue , onChange ) { let beats = 0 ; let state = defaultValue ; const { subscribe , trigger } = getEventTarget ( ) ; f ( ) . then ( ( v ) => ( state = v ) ) . finally ( trigger ) ; const flush = async ( ) => { state = await f ( ) ; beats -= 1 ; if ( beats > 0 ) { beats = 1 ; setTimeout ( flush , 0 ) ; } else if ( beats < 0 ) { beats = 0 ; } trigger ( ) ; } ; return { getCurrentValue : ( ) => state , subscribe : ( sub ) => { const a = subscribe ( sub ) ; const b = onChange ( async ( ) => { beats += 1 ; if ( beats === 1 ) flush ( ) ; } ) ; return ( ) => void [ a ( ) , b ( ) ] ; } , } ; } function getEventTarget ( ) { const event = new EventTarget ( ) ; const EVENT = 'event' ; let timer ; function trigger ( ) { clearTimeout ( timer ) ; timer = setTimeout ( ( ) => event . dispatchEvent ( new Event ( EVENT ) ) , 600 ) ; } function subscribe ( f ) { event . addEventListener ( EVENT , f ) ; return ( ) => event . removeEventListener ( EVENT , f ) ; } return { trigger , subscribe } ; } export function mapSubscription < T , Q > ( sub , mapper ) { return { getCurrentValue ( ) { return mapper ( sub . getCurrentValue ( ) ) ; } , subscribe : sub . subscribe , } ; } export function SubscriptionFromValueRef < T > ( ref ) { return SubscriptionDebug ( { getCurrentValue : ( ) => ref . value , subscribe : ( sub ) => ref . addListener ( sub ) , } ) ; } export function SubscriptionDebug < T > ( x ) { Object . defineProperty ( x , '_value' , { configurable : true , get : ( ) => x . getCurrentValue ( ) , } ) ; return x ; } export function ValueRefFromSubscription < T > ( sub , eq ? ) { const ref = new ValueRef ( sub . getCurrentValue ( ) , eq ) ; sub . subscribe ( ( ) => ( ref . value = sub . getCurrentValue ( ) ) ) ; return ref ; }