| 1 |
/* global jQuery, beyondwordsData */ |
| 2 |
|
| 3 |
( function ( $ ) { |
| 4 |
'use strict'; |
| 5 |
|
| 6 |
const selectVoice = { |
| 7 |
|
| 8 |
/** |
| 9 |
* Init. |
| 10 |
* |
| 11 |
* @since 4.0.0 |
| 12 |
*/ |
| 13 |
init() { |
| 14 |
if ( ! beyondwordsData ) { |
| 15 |
console.log( '🔊 Unable to retrive WP REST API settings' ); |
| 16 |
return; |
| 17 |
} |
| 18 |
|
| 19 |
this.setupClickEvents(); |
| 20 |
this.setupAutosaveVariables(); |
| 21 |
}, |
| 22 |
|
| 23 |
/** |
| 24 |
* Setup click events. |
| 25 |
* |
| 26 |
* @since 4.0.0 |
| 27 |
*/ |
| 28 |
setupClickEvents() { |
| 29 |
$( document ).on( |
| 30 |
'change', |
| 31 |
'select#beyondwords_language_id', |
| 32 |
function () { |
| 33 |
selectVoice.getVoices( this.value ); |
| 34 |
} |
| 35 |
); |
| 36 |
}, |
| 37 |
|
| 38 |
/** |
| 39 |
* Add our checkbox value to the autosave POST vars (if it's checked). |
| 40 |
* |
| 41 |
* @since 4.0.0 |
| 42 |
*/ |
| 43 |
setupAutosaveVariables() { |
| 44 |
$( document ).ajaxSend( function ( event, request, settings ) { |
| 45 |
const languageId = $( '#beyondwords_language_id' ).find( ':selected' ).val(); |
| 46 |
const voiceId = $( '#beyondwords_voice_id' ).find( ':selected' ).val(); |
| 47 |
|
| 48 |
if ( languageId ) { |
| 49 |
settings.data += |
| 50 |
'&' + |
| 51 |
$.param( { |
| 52 |
beyondwords_language_id: languageId, |
| 53 |
} ); |
| 54 |
} |
| 55 |
|
| 56 |
if ( voiceId ) { |
| 57 |
settings.data += |
| 58 |
'&' + |
| 59 |
$.param( { |
| 60 |
beyondwords_voice_id: voiceId, |
| 61 |
} ); |
| 62 |
} |
| 63 |
} ); |
| 64 |
}, |
| 65 |
|
| 66 |
/** |
| 67 |
* Get voices for a language. |
| 68 |
* |
| 69 |
* @since 4.0.0 |
| 70 |
*/ |
| 71 |
getVoices( languageId ) { |
| 72 |
const $voicesSelect = $( '#beyondwords_voice_id' ); |
| 73 |
|
| 74 |
languageId = parseInt(languageId); |
| 75 |
|
| 76 |
if ( ! languageId ) { |
| 77 |
$voicesSelect.empty().attr( 'disabled', true ); |
| 78 |
return; |
| 79 |
} |
| 80 |
|
| 81 |
const endpoint = `${beyondwordsData.root}beyondwords/v1/languages/${languageId}/voices`; |
| 82 |
|
| 83 |
jQuery.ajax( { |
| 84 |
url: endpoint, |
| 85 |
method: 'GET', |
| 86 |
beforeSend: function ( xhr ) { |
| 87 |
xhr.setRequestHeader( 'X-WP-Nonce', beyondwordsData.nonce ); |
| 88 |
} |
| 89 |
} ).done( function( voices ) { |
| 90 |
$voicesSelect |
| 91 |
.empty() |
| 92 |
.append( '<option value=""></option>' ) |
| 93 |
.append( voices.map( ( voice ) => { |
| 94 |
return $( '<option></option>' ).val( voice.id ).text( voice.name ); |
| 95 |
} ) ) |
| 96 |
.attr( 'disabled', false ); |
| 97 |
} ).fail(function ( xhr ) { |
| 98 |
console.log( '🔊 Unable to load voices', xhr ); |
| 99 |
$voicesSelect.empty().attr( 'disabled', true ) |
| 100 |
} ); |
| 101 |
}, |
| 102 |
}; |
| 103 |
|
| 104 |
$( document ).ready( function () { |
| 105 |
selectVoice.init(); |
| 106 |
} ); |
| 107 |
} )( jQuery ); |
| 108 |
|