import { h } from 'haptic/dom' ; import { wire , wireAdopt , wirePause , wireResume } from 'haptic/state' ; import type { Wire , SubToken } from 'haptic/state' ; import type { El } from 'haptic/dom' ; /** Switches DOM content by creating a wire responds to a changing condition. */ const when = < T extends string > ( condition , views ) : Wire < El | undefined > => { type ActiveMeta = { elementRoot : El | undefined ; wireRoot : Wire < void > ; } ; const active = { } as { [ k in T ] ? : ActiveMeta ; } ; let condRendered ; return wire ( ( $ ) => { const cond = condition ( $ ) ; if ( cond === condRendered ) { return active [ condRendered ] ! . elementRoot ; } condRendered = cond ; let a ; if ( ( a = active [ condRendered ] ) ) { wirePause ( a . wireRoot ) ; } if ( ( a = active [ cond ] ) ) { const stale = wireResume ( a . wireRoot ) ; if ( stale ) a . wireRoot ( ) ; return a . elementRoot ; } wireAdopt ( undefined , ( ) => { const wireRoot = wire ( ( ) => { } ) ; wireAdopt ( wireRoot , ( ) => { a = active [ cond ] = { elementRoot : h ( views [ cond ] ! ) , wireRoot } ; } ) ; } ) ; return a ! . elementRoot ; } ) ; } ; export { when } ;