2020-09-20 17:19:12 -06:00
const appListeners = ( app , state , emitter ) => {
2020-09-16 14:16:50 -06:00
emitter . on ( state . events . DOMCONTENTLOADED , ( ) => {
emitter . emit ( state . events . DOMTITLECHANGE , app . siteConfig . siteName ) ;
2020-09-16 14:00:45 -06:00
2019-09-25 12:32:52 -06:00
// Emitter listeners
2020-09-16 14:16:50 -06:00
emitter . on ( state . events . RENDER , callback => {
2019-09-25 12:32:52 -06:00
// This is a dirty hack to get the callback to call *after* re-rendering.
if ( callback && typeof callback === "function" ) {
setTimeout ( ( ) => {
callback ( ) ;
} , 50 ) ;
}
} ) ;
2020-09-16 14:16:50 -06:00
emitter . on ( state . events . SET _LANGUAGE , newLanguage => {
2019-09-25 12:32:52 -06:00
app . setSettingsItem ( 'lang' , newLanguage ) ;
state . language = newLanguage ;
2019-10-28 00:01:27 -06:00
state . i18n . fetchLocaleUI ( ) . then ( ( ) => {
2020-09-16 14:16:50 -06:00
emitter . emit ( state . events . RENDER ) ;
2019-10-28 00:01:27 -06:00
} ) ;
2019-09-25 12:32:52 -06:00
} ) ;
2019-09-26 12:56:28 -06:00
2020-09-16 16:54:29 -06:00
emitter . on ( state . events . ADD _TO _SHELF , async ( book , shelfId , callback = ( ) => { } ) => {
let bookId ;
if ( typeof book . source !== 'undefined' && typeof book . uri !== 'undefined' ) {
const bookSearchResult = await fetch ( '/api/books/getId' , {
method : 'POST' ,
headers : {
'Content-Type' : 'application/json' ,
} ,
body : JSON . stringify ( book ) ,
} ) . then ( response => response . json ( ) ) ;
if ( typeof bookSearchResult . error !== 'undefined' ) {
console . error ( bookSearchResult ) ;
return bookSearchResult ;
}
bookId = bookSearchResult ;
} else {
bookId = book . id ;
}
return fetch ( '/api/shelf/addItem' , {
method : 'POST' ,
headers : {
'Content-Type' : 'application/json' ,
} ,
body : JSON . stringify ( {
shelfId ,
bookId ,
} ) ,
} ) . then ( result => callback ( result ) ) ;
} ) ;
2020-09-20 17:19:12 -06:00
if ( typeof window !== 'undefined' ) {
state . i18n . fetchLocaleUI ( ) . then ( ( ) => {
app . checkIfLoggedIn ( state ) . then ( isLoggedIn => {
emitter . emit ( state . events . RENDER ) ; // This should hopefully only run once after the DOM is loaded. It prevents routing issues where 'render' hasn't been defined yet
} ) ;
2019-10-28 00:01:27 -06:00
} ) ;
2020-09-20 17:19:12 -06:00
}
2019-09-25 12:32:52 -06:00
} ) ;
2020-09-20 17:19:12 -06:00
}
module . exports = { appListeners } ;