// window.onload = function() { // Particles.init({ // selector: '.background', // maxParticles: 100, // color: '#ffffff', //['#DA0463', '#404B69', '#DBEDF3'] // minDistance: 120, // speed: 0.3, // connectParticles: true // // responsive: [{ // // breakpoint: 1000, // // options: { // // color: '#00C9B1', // // maxParticles: 200, // // minDistance: 120, // // speed: 0.3, // // connectParticles: true // // } // // }] // }); // }; const EventBus = new Vue(); let vm2 = new Vue({ el: '#footer', data() { return { urlLogoLarge: "static/images/LogoKM.png", showTran: 1, isOffscreen: false } }, mounted() { setTimeout(() => { if(this.showTran == 1){ this.hideTran(2) } }, 2000); }, methods: { ResetLanguage(){ document.getElementById(':2.container').contentWindow.document.getElementById(':2.restore').click() //EventBus.$emit('refreshViews'); console.log('Refreshing after language change 2'); }, created() { EventBus.$on('ResetLanguage', this.ResetLanguage); }, hideTran(h) { this.showTran = h this.refreshViews() if(h == 2){ this.isOffscreen = true setTimeout(() => { if(this.showTran == 1){ this.hideTran(2) } }, 10000); }else{ this.isOffscreen = false } }, refreshViews(){ if(document.getElementById('html').className){ let tranView = this.showTran if(this.showTran != 0) {this.showTran = 0} setTimeout(() => { if(tranView != 0) {this.showTran = tranView} }, 500) } } } }) let vm = new Vue({ el: '#app', data() { return { globalTime : 0, timeStartQuote: 0, timeStartWord : 0, actualTimerQuote : 0, actualTimerWord : 0, isFullscreen: false, urlLogo: "static/images/LogoKM.png", //urlLogoLarge: "static/images/LogoKML.png", urlLogoLarge: "static/images/WeisUp.png", BoxBckgPath: 'static/images/boxBckg/IMG_2', BoxBckgLength : 49, BoxBckg : '', BoxBckgNb : 1, message : "Hello world", //fname : "Weis Mind", fname : "Weis Mind", wordId : "1", selectedBook : ["All Books"], selectedAuthor : ["All Authors"], age : "", error : "", res : {}, resQuote : {}, resBooks : [{bookId: 0, title: "", authors: ""}], resBookStats : [{bookId: 0, Title: "", Author: "", density: 0, ptscore: 0}], definition : null, definitionView: 0, language: 'en', explanation : "Select Authors and Books", modeDark:0, wordIdNum :0, quoteIdNum : 0, showSearch : 0, showIntro : 1, showWord : 1, showQuote : 1, showBooks : 1, showBookStats : 1, hrefVueWord : "", hrefVueQuote : "", timerWord : 0, timerWordInterval : 0, timerQuote : 1000, timerQuoteInterval : 0, showPlayWord : 0, showPlayQuote : 0, showPlayText : 'stop', maxWords : 0, maxQuotes : 0, resQuoteUsage : "", timeStamp : 12, timeStampQuote : 12, showRate : 0, showTags : 0, rate : null, fontSize: 20, quoteTransition : 0, dialogVisible: false, dialogVisibleVoices: false, voices: [], // List of all voices from SpeechSynthesis //selectedLang: "en", // Default language filteredVoices: [], // Voices filtered by selectedLang selectedVoice: null, // The selected voice object voiceRate: 0.8, contentLang : 'xx', nbButVisible : true, nbVisible : false, observer: null, //cardHeight: 0, currentUtterance : null, isPaused : false, showNavBar : true, originalStyles : new WeakMap(), colors: [ {color: '#5cb87a', percentage: 20}, {color: '#1989fa', percentage: 40}, {color: '#6f7ad3', percentage: 60}, {color: '#e6a23c', percentage: 80}, {color: '#f56c6c', percentage: 100} ], options: [{ value: 'Litterature', label: 'Litterature' }, { value: 'Philosophy', label: 'Philosophy' }, { value: 'Social', label: 'Social' }, { value: 'Business', label: 'Business' }], value: [] }; }, created() { this.openFullScreen(); }, mounted() { this.getDataBooks(); this.getDataBookStats(); this.showBooks = 0; this.showBookStats = 0; this.getDataCheck(1); this.getDataQuoteCheck(1); this.setupLanguageChangeObserver(); this.currentUtterance = new SpeechSynthesisUtterance("Hello Wise Mind"); // setTimeout(() => { // if(this.showIntro == 1){ // this.showIntro = 2 // } // }, 20000); // setTimeout(() => { // if(this.showSearch == 2){ // this.showSearch = 1 // } // }, 22000); setInterval(() => { this.globalTime = Date.now(); }, 300); //this.BoxBckg = this.listBoxBckg[this.BoxBckgNb].value; this.BoxBckg = 'static/images/boxBckg/IMG_2' + (600 +this.BoxBckgNb) + '.jpg' // setInterval(() => { // this.BoxBckg = this.listBoxBckg[this.BoxBckgNb].value; // this.BoxBckgNb = (this.BoxBckgNb + 1) % this.listBoxBckg.length // }, 5000); document.addEventListener('fullscreenchange', this.onFullscreenChange); document.addEventListener('webkitfullscreenchange', this.onFullscreenChange); document.addEventListener('mozfullscreenchange', this.onFullscreenChange); document.addEventListener('MSFullscreenChange', this.onFullscreenChange); this.preloadImage() }, beforeDestroy() { document.removeEventListener('fullscreenchange', this.onFullscreenChange); document.removeEventListener('webkitfullscreenchange', this.onFullscreenChange); document.removeEventListener('mozfullscreenchange', this.onFullscreenChange); document.removeEventListener('MSFullscreenChange', this.onFullscreenChange); }, computed:{ CPTsetSelectedAuthor: function () { //this.selectedAuthor = author this.getDataCheck(1) this.getDataQuoteCheck(1) return this.selectedAuthor }, CPTsetSelectedBook: function (){ //this.selectedBook = book this.getDataCheck(1) this.getDataQuoteCheck(1) return this.selectedBook }, getUniques: function (){ let tempArray = []; for (let item of this.resBooks) { (tempItem => { if (!(tempItem.length > 0 && tempItem.find(x => x.title === item.title))) tempArray.push(item); })(tempArray.filter(x => x.authors === item.authors)) } return tempArray; }, getUniquesAuthors: function (){ let result = [] let tempArray = [] if(this.selectedBook.toString() != "All Books" && this.selectedBook.toString() != ''){ const index = this.selectedBook.indexOf("All Books"); if (index > -1) { this.selectedBook.splice(index, 1); } for (let i = 0; i < this.selectedBook.length; i++) { tempArray = this.resBooks.filter(x => x.title === this.selectedBook[i]); result.push(...tempArray) } } else { result = this.resBooks this.selectedBook = ["All Books"] } // if(this.selectedBook.toString() != "All Books" && this.selectedBook.toString() != ''){ // tempArray = tempArray.filter(x => x.title === this.selectedBook.toString()); // } return result.map(x => x.authors).filter((v,i,s) => s.indexOf(v) === i).sort() // for (let item of this.resBooks) { // (tempItem => { // if (!(tempItem.length > 0 && tempItem.find(x => x.title === item.title))) tempArray.push(item); // })(tempArray.filter(x => x.authors === item.authors)) // } // return tempArray; }, getUniquesTitles: function (){ let result = [] let tempArray = [] if(this.selectedAuthor != "All Authors" && this.selectedAuthor.toString() != ''){ const index = this.selectedAuthor.indexOf("All Authors"); if (index > -1) { this.selectedAuthor.splice(index, 1); } for (let i = 0; i < this.selectedAuthor.length; i++) { tempArray = this.resBooks.filter(x => x.authors === this.selectedAuthor[i]); result.push(...tempArray) } } else { result = this.resBooks this.selectedAuthor = ["All Authors"] } // if(this.selectedBook != "All Books" && this.selectedBook.toString() != ''){ // tempArray = tempArray.filter(x => x.title === this.selectedBook.toString()); // } return result.map(x => x.title).filter((v,i,s) => s.indexOf(v) === i).sort() }, forWatch: function(){ if(this.$refs.quoteContainer){ return this.$refs.quoteContainer.children[0].children[0].textContent }else { return "E" } }, highlightedText() { // Escape special characters for HTML let escapedText = this.res.usage; const word = this.res.wordCtxt; //.trim(); // If the word exists, replace it with a tag if (word) { const regex = new RegExp(`(${word})`, 'gi'); // case-insensitive escapedText = escapedText.replace(regex, '$1'); } return escapedText; } } , watch: { forWatch: function (val) { this.refreshViews() //console.log(val) } }, methods: { openFullScreen() { console.log("openFullScreen") const loading = this.$loading({ lock: true, text: 'WeisUp is Loading', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 1)', target: document.body }); setTimeout(() => { loading.close(); }, 2500); }, simulateFullscreen(element) { console.log("simulateFullscreen") // Store original styles before modifying this.originalStyles.set(element, { position: element.style.position, top: element.style.top, left: element.style.left, width: element.style.width, height: element.style.height, zIndex: element.style.zIndex, background: element.style.background }); // Apply fullscreen styles element.style.position = 'fixed'; element.style.top = '0'; element.style.left = '0'; element.style.width = '100%'; element.style.height = '100%'; element.style.zIndex = '9999'; element.style.background = '#000'; // or any color you prefer //element.style.boxSizing= 'border-box'; //scroll bar this.isFullscreen = !this.isFullscreen // Optionally hide the address bar window.scrollTo(0, 1); }, exitSimulatedFullscreen(element) { console.log("exitSimulatedFullscreen") // Retrieve original styles const original = this.originalStyles.get(element); if (original) { // Restore original styles element.style.position = original.position; element.style.top = original.top; element.style.left = original.left; element.style.width = original.width; element.style.height = original.height; element.style.zIndex = original.zIndex; element.style.background = original.background; // Remove the stored styles this.originalStyles.delete(element); this.isFullscreen = ! this.isFullscreen } // Scroll back to top window.scrollTo(0, 0); }, toggleFullscreen(a) { console.log("toggleFullscreen") let element = document.getElementById('content-to-fullscreen'); if (a==0) {element = document.getElementById('content-to-fullscreen-word');} console.log("0") if (!document.fullscreenElement && !this.isFullscreen) { if (element.requestFullscreen) { element.requestFullscreen(); console.log("1") } else if (element.mozRequestFullScreen) { // Firefox element.mozRequestFullScreen(); console.log("2") } else if (element.webkitRequestFullscreen) { // Chrome, Safari and Opera element.webkitRequestFullscreen(); console.log("3") } else if (element.msRequestFullscreen) { // IE/Edge element.msRequestFullscreen(); console.log("4") } else { // Other this.simulateFullscreen(element); console.log("5") } } else { console.log("toggleFullscreenELSE") if (document.exitFullscreen) { document.exitFullscreen(); this.refreshViewsChange(); } else if (document.mozCancelFullScreen) { // Firefox document.mozCancelFullScreen(); this.refreshViewsChange(); } else if (document.webkitExitFullscreen) { // Chrome, Safari and Opera document.webkitExitFullscreen(); this.refreshViewsChange(); } else if (document.msExitFullscreen) { // IE/Edge document.msExitFullscreen(); this.refreshViewsChange(); } else { // Other this.exitSimulatedFullscreen(element); this.refreshViewsChange(); console.log("5") } } }, onFullscreenChange() { console.log("onFullscreenChange") //this.isFullscreen = !!document.fullscreenElement; this.isFullscreen = !this.isFullscreen }, getData() { axios.post("/data",{ fname : this.fname, age : "", wordId : this.wordId, selectedBook : this.objToText(this.selectedBook), selectedAuthor : this.objToText(this.selectedAuthor), error : "" }).then((data)=>{ //console.log(data) this.res = data.data this.error = "" this.setEmailContent("Word",("A new word 🎯 " + this.res.word + " 🎯"),("Hi πŸ‘‹ \n\nI discovered this word in the following context πŸ‘‰ \n\n πŸ”»πŸ”ΈπŸ”»πŸ”ΈπŸ”»πŸ”ΈπŸ”»πŸ”ΈπŸ”»πŸ”ΈπŸ”»πŸ”ΈπŸ”»πŸ”ΈπŸ”»πŸ”Έ \n\n" + this.res.usage + "\n\nπŸ”ΊπŸ”ΈπŸ”ΊπŸ”ΈπŸ”ΊπŸ”ΈπŸ”ΊπŸ”ΈπŸ”ΊπŸ”ΈπŸ”ΊπŸ”ΈπŸ”ΊπŸ”ΈπŸ”ΊπŸ”Έ \n\nFrom πŸ“– " + this.res.bookTitle + " πŸ“– by πŸ–‹ " + this.SplitAuthorsInLabel(this.res.bookAuthors) + "πŸ–‹ \n\n🎊 πŸŽ‰ 🎊 πŸŽ‰ 🎊"),this.age) this.message = `${this.fname} ${this.wordId}` this.wordIdNum = parseInt(this.wordId); this.showWord = 1 this.showIntro = 0 this.refreshViews() if(this.res.lang != this.contentLang || this.filteredVoices.length == 0){ this.fetchVoices(this.res.lang); this.contentLang = this.res.lang } if(this.definitionView == 1){ console.log(data) this.fetchDefinition(this.res.word,this.res.lang) } }).catch(err=>{ this.error = "Oups.. This Word identifier was not valid" this.showMessage("Oups.. This Word identifier was not valid") console.log(err) this.wordId = 1 }) }, getDataCheck(id) { axios.post("/data",{ fname : this.fname, age : "", wordId : id, selectedBook : this.objToText(this.selectedBook), selectedAuthor : this.objToText(this.selectedAuthor), error : "" }).then((data)=>{ //console.log(data) this.maxWords = data.data.nbItems this.refreshViews() }).catch(err=>{ this.maxWords = 0 }) }, getDataQuote() { this.quoteTransition = 0 axios.post("/dataQuote",{ fname : this.fname, age : "", wordId : this.wordId, selectedBook : this.objToText(this.selectedBook), selectedAuthor : this.objToText(this.selectedAuthor), error : "" }).then((data)=>{ //console.log(data) this.resQuote = data.data this.error = "" this.setEmailContent("Quote",("A quote from πŸ“– " + this.resQuote.bookTitle + " πŸ“–"),("Hi πŸ‘‹ \n\nHere is the quote I want to share, it says πŸ‘‰ \n\n πŸ”»πŸ”ΈπŸ”»πŸ”ΈπŸ”»πŸ”ΈπŸ”»πŸ”ΈπŸ”»πŸ”ΈπŸ”»πŸ”ΈπŸ”»πŸ”ΈπŸ”»πŸ”Έ \n\n" + this.resQuote.usage + "\n\nπŸ”ΊπŸ”ΈπŸ”ΊπŸ”ΈπŸ”ΊπŸ”ΈπŸ”ΊπŸ”ΈπŸ”ΊπŸ”ΈπŸ”ΊπŸ”ΈπŸ”ΊπŸ”ΈπŸ”ΊπŸ”Έ\n\nFrom πŸ“– " + this.resQuote.bookTitle + " πŸ“– \n\n By πŸ–‹ " + this.SplitAuthorsInLabel(this.resQuote.bookAuthors) + " πŸ–‹ At loc πŸ‘‰ " + this.resQuote.word + " \n\n 🎊 πŸŽ‰ 🎊 πŸŽ‰ 🎊"),this.age) this.message = `${this.fname} ${this.wordId}` this.quoteIdNum = parseInt(this.wordId); this.showQuote = 1 this.showIntro = 0 //this.resQuoteUsage = data.data.usage //console.log("at change before : " + this.timerQuote) this.changeTimerQuote() this.refreshViews() if(this.resQuote.lang != this.contentLang || this.filteredVoices.length == 0){ this.fetchVoices(this.resQuote.lang) this.contentLang = this.resQuote.lang } }).catch(err=>{ this.showMessage("Oups.. This Quote identifier was not valid") this.error = "Oups.. This Quote identifier was not valid" console.log(err) this.wordId = 1 }) setTimeout(() => { this.quoteTransition = 1 }, 300); }, getDataQuoteCheck(id) { axios.post("/dataQuote",{ fname : this.fname, age : "", wordId : id, selectedBook : this.objToText(this.selectedBook), selectedAuthor : this.objToText(this.selectedAuthor), error : "" }).then((data)=>{ //console.log(data) this.maxQuotes = data.data.nbItems this.resQuoteUsage = data.data.usage this.refreshViews() }).catch(err=>{ this.getDataQuoteCheckFirst() }) }, getDataQuoteCheckFirst() { axios.post("/dataQuote",{ fname : this.fname, age : "", wordId : 1, selectedBook : this.objToText(this.selectedBook), selectedAuthor : this.objToText(this.selectedAuthor), error : "" }).then((data)=>{ //console.log(data) this.maxQuotes = data.data.nbItems this.resQuoteUsage = data.data.usage this.refreshViews() }).catch(err=>{ console.log("err") this.maxQuotes = 0 }) }, getDataBooks() { axios.post("/dataBooks",{ fname : this.fname, age : "", wordId : this.wordId, error : "" }).then((data)=>{ //console.log(data) this.resBooks = JSON.parse(JSON.stringify(data.data)) this.error = "" }).catch(err=>{ this.showMessage("Oups.. There is no Book") this.error = "Oups.. There is no Book" console.log(err) }) this.message = `${this.fname} ${this.wordId}` this.quoteIdNum = parseInt(this.wordId); this.showBooks = 1 }, getDataBookStats() { axios.post("/dataBookStats",{ fname : this.fname, age : "", wordId : this.wordId, error : "" }).then((data)=>{ //console.log(data) this.resBookStats = JSON.parse(JSON.stringify(data.data)) this.error = "" }).catch(err=>{ this.error = "Oups.. There is no Book" this.showMessage("Oups.. There is no Book") console.log(err) }) this.message = `${this.fname} ${this.wordId}` this.quoteIdNum = parseInt(this.wordId); this.showBookStats = 1 }, async fetchDefinition(wordIn,lanIn) { try { const response = await fetch(`https://en.wiktionary.org/api/rest_v1/page/definition/${wordIn}?uselang=${lanIn}`); const data = await response.json(); // this.definition = data[this.res.a][0].definitions //this.definition = data[this.res.lang][0].definitions this.definition = this.replaceHrefWithOnClick(data[lanIn][0].definitions) } catch (error) { console.error('Error fetching definition:', error); this.definition = 'Failed to fetch definition'; } }, replaceHrefWithOnClick(data) { // Loop through each object in the array return data.map(item => { // Parse the definition HTML into a DOM structure const parser = new DOMParser(); const doc = parser.parseFromString(item.definition, 'text/html'); // Find all anchor tags with href starting with "/wiki/" const anchors = doc.querySelectorAll('a[href^="/wiki/"]'); // Loop through each anchor and replace the href with an onClick handler anchors.forEach(anchor => { const word = anchor.getAttribute('href').replace('/wiki/', ''); // Extract word from href anchor.removeAttribute('href'); // Remove the href attribute anchor.setAttribute('onClick', `vm.fetchDefinition("${word}","en")`); // Add the onClick handler anchor.style.cursor = 'pointer'; anchor.style.color = 'blue'; }); // Serialize the DOM back to an HTML string item.definition = doc.body.innerHTML; return item; // Return the modified item }); }, // async fetchDefinition(word) { // try { // const response = await fetch(`https://en.wiktionary.org/api/rest_v1/page/definition/${word}?uselang=${this.language}`); // const data = await response.json(); // this.definition = data['en'][0].definitions[0].definition // // = data.definitions?.[0]?.definition || 'Definition not found'; // } catch (error) { // console.error('Error fetching definition:', error); // this.definition = 'Failed to fetch definition'; // } // }, showDefinition() { this.fetchDefinition(this.res.word,this.res.lang) this.definitionView = 1 }, explainWord() { this.explanation = "Click to show your Words.." //console.log(this.explanation) }, explainQuote() { this.explanation = "Get inspired by your Quotes.." //console.log(this.explanation) }, explainReset(){ this.explanation = "Reset your filters.." //console.log(this.explanation) }, explainBooks() { this.explanation = "Here are the Books you started." //console.log(this.explanation) }, explainBookStats() { this.explanation = "Some computed statistics." //console.log(this.explanation) }, resetExplain() { this.explanation = "Select Authors and Books" }, PreviousBck() { this.BoxBckgNb = (this.BoxBckgNb - 1) % this.BoxBckgLength this.BoxBckg = this.BoxBckgPath + (600 + this.BoxBckgNb) + '.jpg' }, NextBck() { this.BoxBckgNb = (this.BoxBckgNb + 1) % this.BoxBckgLength this.BoxBckg = this.BoxBckgPath + (600 + this.BoxBckgNb) + '.jpg' this.preloadImage() }, preloadImage() { const img = new Image(); let Nb = (this.BoxBckgNb + 1) % this.BoxBckgLength let url = this.BoxBckgPath + (600 + Nb) + '.jpg' img.src = url; return new Promise((resolve, reject) => { img.onload = () => resolve(img); img.onerror = () => reject(new Error(`Failed to load image: ${url}`)); }); }, readTextBrowser(txt,lng) { const readAloudBtn = document.getElementById('readAloudBtn'); const podcastBtn = document.getElementById('podcastBtn'); const pauseBtn = document.getElementById('pauseBtn'); const stopBtn = document.getElementById('stopBtn'); if (this.currentUtterance) { window.speechSynthesis.cancel(); } let text = String(''); this.currentUtterance = new SpeechSynthesisUtterance(text); text = String(txt); this.currentUtterance = new SpeechSynthesisUtterance(text); this.currentUtterance.lang = lng; // Specify language //'fr-FR' this.currentUtterance.rate = this.voiceRate; // Speaking rate (0.1 to 10) this.currentUtterance.pitch = 1; // Voice pitch (0 to 2) (sound frequency) this.currentUtterance.volume = 1; // Volume (0 to 1) //this.currentUtterance.pitch = 0.5; // Pitch (sound frequency) const voices = window.speechSynthesis.getVoices(); this.currentUtterance.voice = voices.findLast(voice => voice.lang.substring(0,2) === lng); this.currentUtterance.voice = this.selectedVoice // if (a==0.5){ //word // Configure utterance // text = String(text); // this.currentUtterance = new SpeechSynthesisUtterance(text); // this.currentUtterance.lang = language; // Specify language // this.currentUtterance.rate = 0.6; // Speaking rate (0.1 to 10) // this.currentUtterance.pitch = 1; // Voice pitch (0 to 2) // this.currentUtterance.volume = 1; // Volume (0 to 1) // } else if (a==0){ //word // Configure utterance // text = String(vm.res.usage); // this.currentUtterance = new SpeechSynthesisUtterance(text); // this.currentUtterance.lang = this.res.lang; // Specify language // this.currentUtterance.rate = 0.6; // Speaking rate (0.1 to 10) // this.currentUtterance.pitch = 1; // Voice pitch (0 to 2) // this.currentUtterance.volume = 1; // Volume (0 to 1) // } else if (a==1) { //quote // Configure utterance // text = String(vm.resQuote.usage); // this.currentUtterance = new SpeechSynthesisUtterance(text); // this.currentUtterance.lang = 'en'; // Specify language // this.currentUtterance.rate = 0.6; // Speaking rate (0.1 to 10) // this.currentUtterance.pitch = 1; // Voice pitch (0 to 2) // this.currentUtterance.volume = 1; // Volume (0 to 1) // } // Event listeners for speech lifecycle this.currentUtterance.onstart = () => { console.log('Speech started'); // readAloudBtn.style.display = 'none'; // podcastBtn.style.display = 'none'; // pauseBtn.style.display = ''; // stopBtn.style.display = ''; this.showPlayText = 'play' }; this.currentUtterance.onend = () => { console.log('Speech finished'); // readAloudBtn.style.display = ''; // podcastBtn.style.display = ''; // pauseBtn.style.display = 'none'; // stopBtn.style.display = 'none'; this.showPlayText = 'stop' this.currentUtterance = null; isPaused = false; }; this.currentUtterance.onerror = (event) => { console.error('Speech error:', event); // readAloudBtn.style.display = ''; // podcastBtn.style.display = ''; // pauseBtn.style.display = 'none'; // stopBtn.style.display = 'none'; this.showPlayText = 'stop' }; window.speechSynthesis.speak(this.currentUtterance); }, pauseReadTextBrowser() { if (this.currentUtterance) { if (this.isPaused) { // Resume speech window.speechSynthesis.resume(); this.isPaused = false; // pauseBtn.textContent = 'Pause'; //pauseBtn.style.backgroundColor= '#a97a02' } else { // Pause speech window.speechSynthesis.pause(); this.isPaused = true; //pauseBtn.textContent = 'Resume'; //pauseBtn.style.backgroundColor= '#026814' } } }, stopReadTextBrowser() { if (this.currentUtterance) { window.speechSynthesis.cancel(); this.currentUtterance = null; // readAloudBtn.style.display = ''; // podcastBtn.style.display = ''; // pauseBtn.style.display = 'none'; // stopBtn.style.display = 'none'; this.showPlayText = 'stop' // pauseBtn.textContent = 'Pause'; this.isPaused = false; } }, // waitForSpeechToFinishBrowser(text) { // return new Promise((resolve) => { // const utterance = new SpeechSynthesisUtterance(text); // utterance.onend = () => { // resolve(); // Resolve the promise when speech ends // }; // window.speechSynthesis.speak(utterance); // }); // }, waitForSpeechToFinishBrowser(txt,lng) { return new Promise((resolve) => { this.readTextBrowser(txt,lng); this.currentUtterance.onend = () => { this.showPlayText = 'stop' this.currentUtterance = null; isPaused = false; resolve(); // Resolve the promise when speech ends }; }); }, // async readTextsSequentially(texts, language) { // for (const text of texts) { // await waitForSpeechToFinish(text, language); // await new Promise(resolve => setTimeout(resolve, 1000)); // 1-second delay // } // }, makeCunksOfText (text){ const maxLength = 150; let speechChunks = []; // Split the text into chunks of maximum length maxLength without breaking words while (text.length > 0) { if (text.length <= maxLength) { speechChunks.push(text); break; } let chunk = text.substring(0, maxLength + 1); let lastSpaceIndex = chunk.lastIndexOf(' '); if (lastSpaceIndex !== -1) { speechChunks.push(text.substring(0, lastSpaceIndex)); text = text.substring(lastSpaceIndex + 1); } else { // If there are no spaces in the chunk, split at the maxLength speechChunks.push(text.substring(0, maxLength)); text = text.substring(maxLength); } } return speechChunks }, async readWithContext(a) { if (a==0){ const sentences = this.res.usage.split('.').filter((sentence) => sentence.trim() !== ''); // Read the word first await this.waitForSpeechToFinishBrowser(this.res.word, this.res.lang); this.showPlayText = 'play' // Wait for 1 second after word await new Promise(resolve => setTimeout(resolve, 1000)); // Read the context/usage after the delay //await this.waitForSpeechToFinishBrowser(this.res.usage, this.res.lang); //reading chunks for google voices that timeout --> Add a condition on current voice contains "google" for (let i = 0; i < sentences.length; i++) { //i < sentences.length forcing vocabulary usage sentences to 1 console.log('nb sentences' + sentences.length) const sentence = sentences[i].trim(); // Trim leading/trailing spaces if (sentence) { const speechChunks = this.makeCunksOfText(sentence) for (let j = 0; j < speechChunks.length; j++) { window.speechSynthesis.cancel(); //canceling the speechSynthesis before calling the next chunks to make sure it play smoothly. await this.waitForSpeechToFinishBrowser(speechChunks[j],this.res.lang); // Apply the function to the current sentence this.showPlayText = 'play' console.log('chunk v' + j) } await new Promise(resolve => setTimeout(resolve, 500*0.8/this.voiceRate)); // Wait for 0.5 seconds } } this.showPlayText = 'stop' } else if (a==1) { const sentences = this.resQuote.usage.split('.').filter((sentence) => sentence.trim() !== ''); // Read the athors first await this.waitForSpeechToFinishBrowser(this.resQuote.bookAuthors,this.resQuote.lang); this.showPlayText = 'play' // Wait for 1 second after word await new Promise(resolve => setTimeout(resolve, 1000)); // Read the context/usage after the delay //await this.waitForSpeechToFinishBrowser(this.resQuote.usage,this.resQuote.lang); for (let i = 0; i < sentences.length; i++) { const sentence = sentences[i].trim(); // Trim leading/trailing spaces if (sentence) { const speechChunks = this.makeCunksOfText(sentence) for (let j = 0; j < speechChunks.length; j++) { await this.waitForSpeechToFinishBrowser(speechChunks[j],this.resQuote.lang); // Apply the function to the current sentence this.showPlayText = 'play' console.log('chunk h' + j) } await new Promise(resolve => setTimeout(resolve, 500*0.8/this.voiceRate)); // Wait for 0.5 seconds } } this.showPlayText = 'stop' } }, async podcastBrowser(a) { console.log('point 0'); await this.readWithContext(a) this.showPlayText = 'play' // Wait for 2 seconds before moving to next word await new Promise(resolve => setTimeout(resolve, 1000)); // // Move to next word // this.NextWord(); //Check if the window is on word or quote if (this.res.word && this.showWord!= 0){ a = 0; } else if (this.resQuote.word && this.showQuote!= 0) { a = 1; } console.log('point 1'); if (a==0){ this.NextWord() // Wait for 2 seconds before moving to next word await new Promise(resolve => setTimeout(resolve, 2000)); this.podcastBrowser(a) } else if (a==1) { this.NextQuote() // Wait for 2 seconds before moving to next quote await new Promise(resolve => setTimeout(resolve, 2000)); this.podcastBrowser(a) } }, fetchVoices(lng) { // Fetch voices and populate the voices array const synth = window.speechSynthesis; const loadVoices = () => { this.voices = synth.getVoices(); this.updateVoices(lng); // Ensure dropdown is updated }; if (synth.onvoiceschanged !== undefined) { synth.onvoiceschanged = loadVoices(); } else { loadVoices(); } console.log("fetched voices") }, updateVoices(lng) { // Filter voices based on selectedLang this.filteredVoices = this.voices.filter( (voice) => voice.lang.substring(0, 2) === lng ); if (this.filteredVoices.length > 0) { this.selectedVoice = this.filteredVoices[this.filteredVoices.length-1]; // Set default voice //this.filteredVoices.length-1 } else { this.selectedVoice = null; // No voices available for the language } }, async NextWord() { if(this.error == '' && this.wordId == this.wordIdNum.toString()){ this.wordIdNum++ this.wordId = this.wordIdNum.toString() } if(this.error == '' && this.wordId != this.wordIdNum.toString()){ this.wordIdNum = this.wordId } this.definitionView = 0 this.getData() setTimeout(() => { this.showSearch = 2 }, 5000) this.showNavBar = false this.definition = null // this.BoxBckgNb = (this.BoxBckgNb + 1) % this.BoxBckgLength // //this.BoxBckg = this.listBoxBckg[this.BoxBckgNb].value; // this.BoxBckg = this.BoxBckgPath + (600 + this.BoxBckgNb) + '.jpg' this.NextBck() if(this.res.lang != this.contentLang){ this.fetchVoices(this.res.lang) this.contentLang = this.res.lang } // preloadImage() }, PreviousWord() { if(this.error == ''){ this.wordIdNum-- this.wordId = this.wordIdNum.toString() } this.definitionView = 0 this.getData() setTimeout(() => { this.showSearch = 2 }, 5000) this.showNavBar = false this.definition = null if(this.res.lang != this.contentLang){ this.fetchVoices(this.res.lang) this.contentLang = this.res.lang } }, NextQuote() { if(this.error == '' && this.wordId == this.quoteIdNum.toString()){ this.quoteIdNum++ this.wordId = this.quoteIdNum.toString() } if(this.error == '' && this.wordId != this.quoteIdNum.toString()){ this.quoteIdNum = this.wordId } this.getDataQuote() setTimeout(() => { this.showSearch = 2 }, 5000) this.showNavBar = false // this.BoxBckgNb = (this.BoxBckgNb + 1) % this.BoxBckgLength // //this.BoxBckg = this.listBoxBckg[this.BoxBckgNb].value; // this.BoxBckg = this.BoxBckgPath + (600 + this.BoxBckgNb) + '.jpg' // preloadImage() this.NextBck() if(this.resQuote.lang != this.contentLang){ this.fetchVoices(this.resQuote.lang) this.contentLang = this.resQuote.lang } //this.readTextBrowser(1) }, PreviousQuote() { if(this.error == ''){ this.quoteIdNum-- this.wordId = this.quoteIdNum.toString() } this.getDataQuote() if(this.resQuote.lang != this.contentLang){ this.fetchVoices(this.resQuote.lang) this.contentLang = this.resQuote.lang } }, switchMode(h) { this.modeDark = h }, hideIntro(h) { this.showIntro = h this.hideSearch(h) this.hideWord(h) this.hideQuote(h) this.refreshViews() }, hideSearch(h) { this.showSearch = h if(h==2){ this.showNavBar = false } if(h==1){ this.showNavBar = true } this.refreshViews() }, hideWord(h) { this.showWord = h this.refreshViews() }, hideQuote(h) { this.showQuote = h this.refreshViews() }, hideBooks(h) { this.showBooks = h this.refreshViews() }, hideBookStats(h) { this.showBookStats = h this.refreshViews() }, setEmailContent(id,subject,body,email){ //var subject = "This is a subject"; var subjectEncoded = encodeURIComponent(subject); //console.log(subjectEncoded); var bodyEncoded = encodeURIComponent(body); //console.log(bodyEncoded); //document.getElementById(id).href if (id=="Word") { this.hrefVueWord = "mailto:" + email + "?subject=" + subjectEncoded + "&body=" + bodyEncoded; } else if (id=="Quote") { this.hrefVueQuote = "mailto:" + email + "?subject=" + subjectEncoded + "&body=" + bodyEncoded; } }, setEmailContentForTra(){ //let transQuote = document.getElementById('quote').children[0].children[0].textContent let transQuote = "" let myElement = document.getElementById('quote').children[1] for (let i = 0; i < myElement.children.length; i++) { transQuote = transQuote + myElement.children[i].textContent + "\n" } transQuote = document.getElementById('quote').children[0].textContent + transQuote this.setEmailContent("Quote",("A quote from πŸ“– " + this.resQuote.bookTitle + " πŸ“–"),("Hi πŸ‘‹ \n\nHere is the quote I want to share, it says πŸ‘‰ \n\n πŸ”»πŸ”ΈπŸ”»πŸ”ΈπŸ”»πŸ”ΈπŸ”»πŸ”ΈπŸ”»πŸ”ΈπŸ”»πŸ”ΈπŸ”»πŸ”ΈπŸ”»πŸ”Έ \n\n" + this.resQuote.usage + "\n\nπŸ”ΊπŸ”ΈπŸ”ΊπŸ”ΈπŸ”ΊπŸ”ΈπŸ”ΊπŸ”ΈπŸ”ΊπŸ”ΈπŸ”ΊπŸ”ΈπŸ”ΊπŸ”ΈπŸ”ΊπŸ”Έ\n\n" + transQuote + "\n\nπŸ”ΊπŸ”ΈπŸ”ΊπŸ”ΈπŸ”ΊπŸ”ΈπŸ”ΊπŸ”ΈπŸ”ΊπŸ”ΈπŸ”ΊπŸ”ΈπŸ”ΊπŸ”ΈπŸ”ΊπŸ”Έ\n\n" + "From πŸ“– " + this.resQuote.bookTitle + " πŸ“– \n\n By πŸ–‹ " + this.SplitAuthorsInLabel(this.resQuote.bookAuthors) + " πŸ–‹ At loc πŸ‘‰ " + this.resQuote.word + " \n\n 🎊 πŸŽ‰ 🎊 πŸŽ‰ 🎊"),this.age) }, hrefVue(id){ if (id=="Word") { window.location = this.hrefVueWord } else if (id=="Quote") { window.location = this.hrefVueQuote console.log("here") } }, setSelectedBook(book){ this.selectedBook = book this.getDataCheck(1) this.getDataQuoteCheck(1) }, setSelectedAuthor(author){ this.selectedAuthor = author this.getDataCheck(1) this.getDataQuoteCheck(1) }, onlyUnique(value, index, self) { return self.indexOf(value) === index; }, showTimerWord(){ this.showPlayWord = 1 }, startTimerWord() { this.showPlayWord = 2 this.actualTimerWord = (this.timeStamp+6)*(this.timeStamp+6)*30 this.timeStartWord = Date.now() // if(this.timeStamp<6){ // this.timeStamp = 6 // } setTimeout(() => { this.showSearch = 2 }, 5000) this.timerWord = setInterval(() => { this.timeStartWord = Date.now() this.NextWord() }, (this.timeStamp+6)*(this.timeStamp+6)*30); this.refreshViews(); }, stopTimerWord() { this.showPlayWord = 0 clearInterval(this.timerWord); this.refreshViews(); }, showTimerQuote(){ this.showPlayQuote = 1 }, async changeTimerQuote(){ await this.getDataQuoteCheck(this.quoteIdNum+2) nbWords = this.resQuoteUsage.split(' ').length if(nbWords<10){ nbWords = 10 } this.timerQuote = parseInt(((this.timeStampQuote/4)+1))*nbWords*100 //console.log("at change : " + this.timerQuote) }, startTimerQuoteElapse(){ setTimeout(() => { this.showSearch = 2 }, 5000) this.showNavBar = false this.startTimerQuote() }, async startTimerQuote() { // await setTimeout(() => { // console.log("out timeout : " + this.timerQuote); // }, 1000) // //await this.changeTimerQuote() // await console.log("out : " + this.timerQuote); this.timeStartQuote = Date.now() this.actualTimerQuote = this.timerQuote if(this.showPlayQuote != 0){ this.showPlayQuote = 2 this.timerQuoteInterval = setTimeout(async () => { //await console.log("in : " + this.timerQuote); if(this.showPlayQuote != 0){ await this.NextQuote() //await this.changeTimerQuote() await this.startTimerQuote() } }, this.timerQuote); this.refreshViews(); } }, // reStartTimerQuote(timer){ // clearInterval(this.timerQuoteInterval) // this.timerQuoteInterval = setInterval(() => { // console.log(timer); // this.startTimerQuote() // }, timer); // }, stopTimerQuote() { this.showPlayQuote = 0 clearTimeout(this.timerQuoteInterval); this.refreshViews(); }, formatTooltip(val) { return parseInt((val/4)+1); }, setRate(h){ this.showRate = h }, setTag(h){ this.showTags = h }, resetFilters(){ this.selectedBook = ["All Books"]; this.setSelectedBook(["All Books"]) this.selectedAuthor = ["All Authors"] this.setSelectedAuthor(["All Authors"]) }, showMessage(msg) { this.$message.error(msg); // this.$message({ // message: 'Warning, this is a warning message.', // type: 'warning' // }); }, getUniqueAuthor(data){ return [...new Set(data.map(item => item.authors))]; }, getUniqueBook(data){ return [...new Set(data.map(item => item.title))]; }, getUniqueByKey(data,key){ return [...new Map(data.map(item => [item[key], item])).values()]; }, objToText(obj) { var text = '' for (let i = 0; i < obj.length; i++) { text += "'" + obj[i] + "'," ; } //return text.slice(0, -1) return obj }, SplitAuthorsInLabel(author) { if(!author){author="Unknown"} let re = /;/gi; let authorSplit = author.replace(re, ' & '); return authorSplit; }, // ResetLanguage(){ // document.getElementById(':2.container').contentWindow.document.getElementById(':2.restore').click() // }, setupLanguageChangeObserver() { // Create a new MutationObserver this.observer = new MutationObserver((mutations) => { mutations.forEach((mutation) => { if (mutation.type === 'attributes' && mutation.attributeName === 'lang') { const newLang = document.documentElement.lang; console.log('Language changed to:', newLang); this.refreshViewsChange() } }); }); // Configure the observer to watch for attribute changes on the element const config = { attributes: true, attributeFilter: ['lang'] }; // Start observing this.observer.observe(document.documentElement, config); }, refreshViews(){ console.log("refreshViews"); if(document.getElementById('html').className && !this.isFullscreen){ let introView = this.showIntro let searchView = this.showSearch let wordView = this.showWord let quoteView = this.showQuote let booksView = this.showBooks let statsView = this.showBookStats // let fullscreenView = this.isFullscreen if(this.showIntro != 0) {this.showIntro = 0} if(this.showSearch != 0) {this.showSearch = 0} if(this.showWord != 0) {this.showWord = 0} if(this.showQuote != 0) {this.showQuote = 0} if(this.showBooks != 0) {this.showBooks = 0} if(this.showBookStats != 0) {this.showBookStats = 0} setTimeout(() => { if(introView != 0) {this.showIntro = introView} if(searchView != 0) {this.showSearch = searchView} if(wordView != 0) {this.showWord = wordView} if(quoteView != 0) {this.showQuote = quoteView} if(booksView != 0) {this.showBooks = booksView} if(statsView != 0) {this.showBookStats = statsView} if(statsView != 0) {this.showBookStats = statsView} // if(fullscreenView) {this.toggleFullscreen()} }, 500) setTimeout(() => { this.setEmailContentForTra() }, 1000) } }, refreshViewsChange(){ console.log("refreshViewsChange " + this.isFullscreen); let introView = this.showIntro let searchView = this.showSearch let wordView = this.showWord let quoteView = this.showQuote let booksView = this.showBooks let statsView = this.showBookStats let fullscreenView = this.isFullscreen if(this.showIntro != 0) {this.showIntro = 0} if(this.showSearch != 0) {this.showSearch = 0} if(this.showWord != 0) {this.showWord = 0} if(this.showQuote != 0) {this.showQuote = 0} if(this.showBooks != 0) {this.showBooks = 0} if(this.showBookStats != 0) {this.showBookStats = 0} //if(this.isFullscreen) {this.toggleFullscreen()} //this.toggleFullscreen() setTimeout(() => { if(introView != 0) {this.showIntro = introView} if(searchView != 0) {this.showSearch = searchView} if(wordView != 0) {this.showWord = wordView} if(quoteView != 0) {this.showQuote = quoteView} if(booksView != 0) {this.showBooks = booksView} if(statsView != 0) {this.showBookStats = statsView} //if(fullscreenView) {this.toggleFullscreen()} }, 500) if(document.documentElement.lang != "auto"){ setTimeout(() => { this.setEmailContentForTra() }, 1000) } else {this.setEmailContent("Quote",("A quote from πŸ“– " + this.resQuote.bookTitle + " πŸ“–"),("Hi πŸ‘‹ \n\nHere is the quote I want to share, it says πŸ‘‰ \n\n πŸ”»πŸ”ΈπŸ”»πŸ”ΈπŸ”»πŸ”ΈπŸ”»πŸ”ΈπŸ”»πŸ”ΈπŸ”»πŸ”ΈπŸ”»πŸ”ΈπŸ”»πŸ”Έ \n\n" + this.resQuote.usage + "\n\nπŸ”ΊπŸ”ΈπŸ”ΊπŸ”ΈπŸ”ΊπŸ”ΈπŸ”ΊπŸ”ΈπŸ”ΊπŸ”ΈπŸ”ΊπŸ”ΈπŸ”ΊπŸ”ΈπŸ”ΊπŸ”Έ\n\nFrom πŸ“– " + this.resQuote.bookTitle + " πŸ“– \n\n By πŸ–‹ " + this.SplitAuthorsInLabel(this.resQuote.bookAuthors) + " πŸ–‹ At loc πŸ‘‰ " + this.resQuote.word + " \n\n 🎊 πŸŽ‰ 🎊 πŸŽ‰ 🎊"),this.age)} }, resetDialog(){ console.log("resetDialog " + this.isFullscreen); this.dialogVisible = false; this.dialogVisibleVoices = false; console.log("resetDialog " + this.isFullscreen); document.getElementById('share-buttons').style.display = 'none'; console.log("resetDialog " + this.isFullscreen); document.getElementById('instructions').style.display = 'none'; console.log("resetDialog " + this.isFullscreen); if(this.isFullscreen == false) {this.refreshViewsChange()} console.log("resetDialog " + this.isFullscreen); // this.onFullscreenChange() }, handleClose(done) { console.log("handleClose " + this.isFullscreen); this.resetDialog(); //this.refreshViewsChange() // this.$confirm('Are you sure to close this dialog?') // .then(_ => { // done(); // }) // .catch(_ => {}); } }, filters: { percentTime: function (a,b){ let value = parseInt(a/b) return value } } })