import { speakNext } from './speakNext' ; import { getState } from './state' ; import { pendingQuestionColor } from '../pendingQuestionColor' ; export const queueUtterance = ( textToSpeak , questionId ? ) => { const { textToSpeakQueue } = getState ( ) ; if ( ! questionId ) { textToSpeakQueue . push ( { textToSpeak } ) ; if ( ! speechSynthesis . speaking ) { speakNext ( ) ; } return ; } const questionElement = document . getElementById ( `question-summary-${ questionId }` ) ! ; const channel = getState ( ) . channel ! ; if ( questionElement && questionId ) { questionElement . style . backgroundColor = pendingQuestionColor ; channel . postMessage ( { newQuestion : true , questionOuterHTML : questionElement . outerHTML } ) ; } const mouseoverHandler = ( ) => { channel . postMessage ( `Done with ${ questionId }` ) ; const foundIndex = textToSpeakQueue . findIndex ( item => 'questionElement' in item && item . questionElement === questionElement ) ; questionElement . style . removeProperty ( 'background-color' ) ; if ( foundIndex !== - 1 ) { textToSpeakQueue . splice ( foundIndex , 1 ) ; return ; } speechSynthesis . cancel ( ) ; if ( textToSpeakQueue . length ) { speakNext ( ) ; } } ; if ( questionElement ) { questionElement . addEventListener ( 'mouseover' , mouseoverHandler , { once : true } ) ; } textToSpeakQueue . push ( { textToSpeak , questionElement , mouseoverHandler } ) ; if ( ! speechSynthesis . speaking ) { speakNext ( ) ; } } ;