import type * as d from '../declarations' ; import { consoleError } from './client-log' ; import { plt , promiseResolve } from './client-window' ; import { PLATFORM_FLAGS } from '../runtime/runtime-constants' ; import { BUILD } from '@app-data' ; let queueCongestion = 0 ; let queuePending = false ; const queueDomReads = [ ] ; const queueDomWrites = [ ] ; const queueDomWritesLow = [ ] ; const queueTask = ( queue , write ) => ( cb ) => { queue . push ( cb ) ; if ( ! queuePending ) { queuePending = true ; if ( write && plt . $flags$ & PLATFORM_FLAGS . queueSync ) { nextTick ( flush ) ; } else { plt . raf ( flush ) ; } } } ; const consume = ( queue ) => { for ( let i = 0 ; i < queue . length ; i ++ ) { try { queue [ i ] ( performance . now ( ) ) ; } catch ( e ) { consoleError ( e ) ; } } queue . length = 0 ; } ; const consumeTimeout = ( queue , timeout ) => { let i = 0 ; let ts = 0 ; while ( i < queue . length && ( ts = performance . now ( ) ) < timeout ) { try { queue [ i ++ ] ( ts ) ; } catch ( e ) { consoleError ( e ) ; } } if ( i === queue . length ) { queue . length = 0 ; } else if ( i !== 0 ) { queue . splice ( 0 , i ) ; } } ; const flush = ( ) => { if ( BUILD . asyncQueue ) { queueCongestion ++ ; } consume ( queueDomReads ) ; if ( BUILD . asyncQueue ) { const timeout = ( plt . $flags$ & PLATFORM_FLAGS . queueMask ) === PLATFORM_FLAGS . appLoaded ? performance . now ( ) + 14 * Math . ceil ( queueCongestion * ( 1.0 / 10.0 ) ) : Infinity ; consumeTimeout ( queueDomWrites , timeout ) ; consumeTimeout ( queueDomWritesLow , timeout ) ; if ( queueDomWrites . length > 0 ) { queueDomWritesLow . push ( ... queueDomWrites ) ; queueDomWrites . length = 0 ; } if ( ( queuePending = queueDomReads . length + queueDomWrites . length + queueDomWritesLow . length > 0 ) ) { plt . raf ( flush ) ; } else { queueCongestion = 0 ; } } else { consume ( queueDomWrites ) ; if ( ( queuePending = queueDomReads . length > 0 ) ) { plt . raf ( flush ) ; } } } ; export const nextTick = ( cb ) => promiseResolve ( ) . then ( cb ) ; export const readTask = queueTask ( queueDomReads , false ) ; export const writeTask = queueTask ( queueDomWrites , true ) ;