assets/js/wordfinder-home.js in word-games-theme-3.1.0 vs assets/js/wordfinder-home.js in word-games-theme-3.1.1

- old
+ new

@@ -5,17 +5,41 @@ let mustInclude = document.getElementById("mustInclude"); let endsWith = document.getElementById("endsWith"); let exculdeWith = document.getElementById("exculdeWith"); let inculdeWith = document.getElementById("inculdeWith"); let wordLength = document.getElementById("wordLength"); - -const serachSection = document.querySelector(".serachSection"); +let textBoxes = document.querySelectorAll('.textBoxes'); +let filterInputs = document.querySelectorAll('.filter_val'); +let formElement = document.querySelector("#form"); +let wordCount = document.querySelector(".wordCount"); +let main = document.querySelector(".main"); +let errorMsg = document.querySelector(".errorMsg"); +let serachBtn = document.querySelector(".serachBtn") +let tab_container = document.querySelector(".tab_container"); +let lengthSelect = document.querySelector(".length-select"); +let getScript = document.currentScript; +let siteUrl = getScript.dataset.url; +let serachSection = document.querySelector(".serachSection"); let rangeOfBlankTile = serachSection.dataset.range; +let letterLen = serachSection.dataset.letter +let ablank = serachSection.dataset.ablank +let featureContainer = document.querySelector("#featureContainer") +let howContainer = document.querySelector("#howContainer") +let faqsContainer = document.querySelector("#faqsContainer") +let infographicsContainer = document.querySelector("#infographicsContainer") +let theSelect = document.getElementById("select_dropDown"); +let sortingFilter = document.querySelector("#select_dropDown"); +let sortup = document.querySelector(".sortup-icon"); +let bool = false; +let authorsLists = document.querySelector(".authors-list") +let searchBtnContainer = document.querySelector(".search-btn-container") +let home_page_search_result +let homePageSearchResult +let sortValue; +let sortBool = false; +let ok = true; - - -const textBoxes = document.querySelectorAll('.textBoxes'); textBoxes.forEach(txtBox => { txtBox.addEventListener("input", () => { if (txtBox.value !== '') { txtBox.classList.add('blinkBoxShadow'); } else { @@ -25,14 +49,10 @@ txtBox.addEventListener('blur', () => { txtBox.classList.remove('blinkBoxShadow'); }); }); - - - -// // when typing on input txtBox.addEventListener('input', (e) => { if (e.target.value === "") { letterCloseButton.style.display = "none" } else { @@ -52,12 +72,10 @@ }) letterCloseButton.addEventListener("click", () => { txtBox.value = "" letterCloseButton.style.display = "none" }) -//tooltips for advanced filter -const filterInputs = document.querySelectorAll('.filter_val'); Array.from(filterInputs).forEach((item) => { item.addEventListener("input", (e) => { const inputValue = e.target.value; const parentElement = e.target.parentElement; const imgElement = parentElement.querySelector('img'); @@ -91,11 +109,52 @@ tooltipElement.style.setProperty('--tooltip-padding', '0.5rem'); tooltipElement.style.setProperty('--tooltip-border-style', 'soild'); }) }) +if (ablank) { + if (!serachValue.includes("?")) { + if (serachValue.length <= letterLen || serachValue.length >= letterLen) { + serachValue = serachValue + '?' + txtBox.value = serachValue + } + } +} +sortup.addEventListener("click", () => { + if (bool) { + theSelect.size = 0; + bool = false; + theSelect.style.display = "none"; + } else { + bool = true; + theSelect.size = 3; + theSelect.style.display = "block"; + } +}); +const getDiff = (text1, text2) => { + var diffRange = []; + var currentRange = undefined; + for (var i = 0; i < text1.length; i++) { + if (text1[i] != text2[i]) { + if (currentRange == undefined) { + currentRange = [i]; + } + } + if (currentRange != undefined && text1[i] == text2[i]) { + currentRange.push(i); + diffRange.push(currentRange); + currentRange = undefined; + } + } + if (currentRange != undefined) { + currentRange.push(i); + diffRange.push(currentRange); + } + return diffRange; +}; + const loadResource = (FILE_URL, data = {}, async = true, type = "text/javascript") => { return new Promise((resolve, reject) => { let resourceEle; if (type === "text/javascript") { @@ -139,18 +198,69 @@ } else if (type === "text/css") { document.head.appendChild(resourceEle); } }); }; -const formElement = document.querySelector("#form"); -formElement.addEventListener("submit", function (e) { +function sendPageViewEvent() { + gtag('event', 'page_view', { + page_location: window.location.pathname + location.search + }); +} + +function logSubmit(e) { e.preventDefault(); if (txtBox.value != "" || startsWith.value != "" || endsWith.value != "" || mustInclude.value != "" || exculdeWith.value != "" || inculdeWith.value != "" || wordLength.value != "") { + if (featureContainer) { + featureContainer.remove() + } + if (howContainer) { + howContainer.remove() + } + if (faqsContainer) { + faqsContainer.remove() + } + if (infographicsContainer) { + infographicsContainer.remove() + } + if (authorsLists) { + authorsLists.remove() + } + serachBtn.style.background = 'url(/assets/images/spinner.gif) no-repeat center center'; + main.innerHTML = `<main class="placeholder-loader"> + <ul class="o-vertical-spacing o-vertical-spacing--l"> + <li class="blog-post o-media"> + <div class="o-media__body"> + <div class="o-vertical-spacing"> + <p class="m-0"> + <span class="skeleton-box" style="width:40%;"></span> + </p> + </div> + </div> + </li> + <li class="blog-post o-media"> + <div class="o-media__figure"> + <span class="skeleton-box" style="width:900px;height:140px;"></span> + </div> + </li> + <li class="blog-post o-media"> + <div class="o-media__figure"> + <span class="skeleton-box" style="width:900px;height:140px;"></span> + </div> + </li> + <li class="blog-post o-media"> + <div class="o-media__figure"> + <span class="skeleton-box" style="width:900px;height:140px;"></span> + </div> + </li> + </ul> + </main>`; + + let quesMark = "?"; if (rangeOfBlankTile) { if (!txtBox.value.includes("?")) { - txtBox.value = txtBox.value + quesMark.repeat(rangeOfBlankTile); // + txtBox.value = txtBox.value + quesMark.repeat(rangeOfBlankTile); txtBox.value = txtBox.value; } } document.querySelector(".fillterWrapper").classList.add("hide") let selectedDictionary = document.querySelector(".select_dropDown2").value; @@ -202,73 +312,465 @@ exculdeValue = params.get("exclude"); includeValue = params.get("include"); lengthValue = params.get("length"); dictonary = params.get("dictionary"); - gtag("event", "page_view", { - page_location: window.location.pathname + location.search, - }); + getData(txtBox.value.toLowerCase()) + + setTimeout(sendPageViewEvent, 0); } const paramName = 'search'; if (new URLSearchParams(window.location.search).has(paramName)) { - const additionalData = { - url: "{{site.url}}", - range: "{{page.blanktilerange}}" - } + const additionalData = {} var loadJs = document.querySelector(".loaded-js"); if (loadJs == null) { loadResource("/assets/css/wordfinder-result.css", additionalData, true, "text/css") .then((data) => { console.log("CSS loaded:", data); }) - .then(() => { - // Load the JavaScript file after the CSS file has loaded - loadResource("/assets/js/wordfinder.js", additionalData, true, "text/javascript") - .then((data) => { - console.log("JavaScript loaded:", data); - getData(txtBox.value.toLowerCase()); - }) - .catch((error) => { - console.error("Error loading JavaScript:", error); - }); - }) .catch((error) => { console.error("Error loading CSS:", error); }); } } } else { console.log("Please Enter Valid Letters."); } +} +let selectedDictionary = document.querySelector(".select_dropDown2"); +selectedDictionary.addEventListener("change", (e) => { + logSubmit(e); }); -// Now you can use the loadScript function with additional data -function checkQueryParam() { - const urlParams = new URLSearchParams(window.location.search); - const paramName = 'search'; - if (urlParams.has(paramName)) { - const additionalData = { - url: "{{site.url}}", - range: "{{page.blanktilerange}}" - }; - loadResource("/assets/css/wordfinder-result.css", additionalData, true, "text/css") - .then((data) => { - console.log("CSS loaded:", data); - }) - .then(() => { - // Load the JavaScript file after the CSS file has loaded - loadResource("/assets/js/wordfinder.js", additionalData, true, "text/javascript") - .then((data) => { - console.log("JavaScript loaded:", data); - getData(txtBox.value.toLowerCase()); - }) - .catch((error) => { - console.error("Error loading JavaScript:", error); - }); - }) - .catch((error) => { - console.error("Error loading CSS:", error); - }); +formElement.addEventListener("submit", logSubmit); +sortingFilter.addEventListener("change", logSubmit); + +// getWords define +const worker = new Worker('/assets/js/wordfinder-worker.js'); +const getData = async (serachValue) => { + try { + let selectedDictionary = document.querySelector(".select_dropDown2").value; + + if (letterLen) { + home_page_search_result = document.querySelector("#home_page_search_result") + homePageSearchResult = `/?search=${serachValue}&dictionary=Dictionary&prefix=&contains=&suffix=&exculde=&inculde=&length=`; + } + document.querySelector(".main-header").style.height = "auto" + document.querySelector(".main-header").style.background = "#fff" + document.querySelector(".heading-h2").style.display = "none" + document.querySelector(".sortingFilters").style.display = "none" + + errorMsg.innerHTML = ""; + wordCount.innerHTML = ""; + + worker.postMessage({ + type: "api", + serachValue: serachValue, + selectedDictionary: selectedDictionary, + endpoint: `/.netlify/functions` + }); + worker.onmessage = (event) => { + main.innerHTML = ""; + serachBtn.style.background = 'url(/assets/images/search.svg) no-repeat center center'; + getWords(event.data.data); + } + } catch (error) { + console.log(error); } +}; + +let newUrl = window.location.href; +if (newUrl.includes("?")) { + const params = new URLSearchParams(window.location.search); + let serachValue = params.get("search").toLowerCase(); + let prefixValue = params.get("prefix"); + let containsValue = params.get("contains"); + let suffixValue = params.get("suffix"); + let exculdeValue = params.get("exclude"); + let includeValue = params.get("include"); + let lengthValue = params.get("length"); + let dictonary = params.get("dictionary"); + + txtBox.value = serachValue + startsWith.value = prefixValue + mustInclude.value = containsValue + endsWith.value = suffixValue + exculdeWith.value = exculdeValue + inculdeWith.value = includeValue + wordLength.value = lengthValue + document.querySelector(".select_dropDown2").value = dictonary + logSubmit(new Event('submit')) } -checkQueryParam(); +let previousDataIndex = null +let previousID = null; +let storepreviousIndex = [] +let moreData = [] +let data_index = 25; +function getWords(data) { + data_index = 25 + moreData = [] + storepreviousIndex = [] + main.innerHTML = ""; + lengthSelect.innerHTML = "" + if (typeof data === "string") { + errorMsg.innerHTML = "no words found"; + } else { + worker.postMessage({ + type: 'filterwords', + data: data, + serachValue: txtBox.value.toLowerCase(), + prefixValue: startsWith.value, + containsValue: mustInclude.value, + suffixValue: endsWith.value, + exculdeValue: exculdeWith.value, + includeValue: inculdeWith.value, + lengthValue: wordLength.value, + sortingFilter: sortingFilter.selectedIndex, + dictonary: document.querySelector(".select_dropDown2").value + }); + worker.onmessage = (event) => { + if (event.data.type === "filterwords") { + errorMsg.innerHTML = "" + document.querySelector(".sortingFilters").style.display = "flex" + let { prefixValue, containsValue, suffixValue, exculdeValue, includeValue, lengthValue, newdata, i, newWordsLength, result } = event.data + moreData.push(newdata) + if (prefixValue) { + startsWith.nextElementSibling.querySelector("img").src = "/assets/images/close-btn.svg" + startsWith.classList.add("tick"); + startsWith.value = startsWith.value; + } + if (suffixValue) { + endsWith.nextElementSibling.querySelector("img").src = "/assets/images/close-btn.svg" + endsWith.classList.add("tick"); + endsWith.value = endsWith.value; + } + if (containsValue) { + mustInclude.nextElementSibling.querySelector("img").src = "/assets/images/close-btn.svg" + mustInclude.classList.add("tick"); + mustInclude.value = mustInclude.value; + } + if (lengthValue) { + wordLength.nextElementSibling.querySelector("img").src = "/assets/images/close-btn.svg" + wordLength.classList.add("tick"); + wordLength.value = wordLength.value; + } + if (exculdeValue) { + exculdeWith.nextElementSibling.querySelector("img").src = "/assets/images/close-btn.svg" + exculdeWith.classList.add("tick"); + exculdeWith.value = exculdeWith.value; + } + if (includeValue) { + inculdeWith.nextElementSibling.querySelector("img").src = "/assets/images/close-btn.svg" + inculdeWith.classList.add("tick"); + inculdeWith.value = inculdeWith.value; + } + if (newdata.length === 0) { + main.innerHTML += ""; + } else { + if (result[0] !== undefined) { + if (wordLength.value) { + lengthSelect.style.display = "none" + } else { + var option = document.createElement("option"); + option.text = `${i} Letter`; + option.value = i; + lengthSelect.setAttribute("onchange", `Filtering(${i})`) + lengthSelect.add(option); + lengthSelect.style.display = "block" + } + if (letterLen) { + home_page_search_result.href = homePageSearchResult + home_page_search_result.innerHTML = `See words of any length with letters ${serachValue.split("")}` + } + main.innerHTML += ` + <div class="allGroupWords wordlistContainer" id="alpha_${i}"> + <h3 class="wordListHeading lead">${i} Letter Words</h3> + <div class="wordList">${result.join("")}</div> + <div class="w-100 text-center btn-container"> + <button + style="background: black; + padding: 1rem 2rem; + border-radius: 50px; + color: #fff; + font-size: 15px; + border: none;" + onclick="showMoreWords(this)" type="button" class="my-4 showmore_btn" id="${i}">More Words</button> + </div> + + </div>` + showMoreLimit() + } + } + if (newWordsLength === 0) { + console.log(newdata); + errorMsg.innerHTML = "No Words Found"; + document.querySelector(".sortingFilters").style.display = "none" + } else { + if (txtBox.value) { + wordCount.innerHTML = `<strong>Found ${newWordsLength} words with letters with ${txtBox.value.split("")}</strong>`; + } else { + let startwithMsg = "" + let endwithMsg = "" + let containsMsg = "" + let lengthMsg = "" + let inputVal = "" + if (txtBox.value) { + inputVal = `${input.value.split("")} ` + } + if (prefixValue) { + startwithMsg = `starting with ${prefixValue.split("")}` + } + if (suffixValue) { + endwithMsg = `ending with ${suffixValue.split("")} ` + } + if (containsValue) { + containsMsg = `containing with ${containsValue.split("")} ` + } + if (lengthValue) { + lengthMsg = `with ${lengthValue} letter words` + } + let msg = `<strong> Found ${newWordsLength} words with letters + ${lengthMsg} ${inputVal} ${startwithMsg} ${endwithMsg} ${containsMsg} </strong>` + + wordCount.innerHTML = `${msg} ` + } + } + } + } + } +} +async function getMoreWords() { + let flattenedArray = moreData.flat(); + let uniqueArray = [...new Set(flattenedArray)];; + return uniqueArray +} +async function showMoreWords(e) { + try { + let showmore = e.parentElement.children[0]; + let id = showmore.id; + + if (previousID !== null && parseInt(previousID) !== parseInt(id)) { + data_index = 25 + const filteredIndexes = storepreviousIndex.filter(item => item.id === id); + if (filteredIndexes.length > 0) { + const lastItem = filteredIndexes[filteredIndexes.length - 1]; + data_index = lastItem.data_index + 25; + lastItem.data_index = data_index; + } + } + previousID = id; + storepreviousIndex.push({ + data_index, + id + }) + console.log("Current data_index:", data_index); + + document.getElementById(id).innerHTML = `Loading...`; + let content_area = document.getElementById("alpha_" + id).getElementsByClassName("wordList")[0]; + const result = await getMoreWords(); + let full_words = result.filter((item) => item.length === Number(id)); + + if (data_index < full_words.length) { + for (let d = data_index; d < data_index + 25; d++) { + if (full_words[d] != undefined) { + let itemHtml = ""; + if (serachValue) { + var text1 = serachValue.replace("?", ""); + var text2 = full_words[d]; + var text3 = full_words[d]; + let chars = text1.split(""); + let indexs = []; + chars.map((i) => { + let findIndexes = findIndex(text3, i); + if (findIndexes.length > 0) { + text3 = text3.split(""); + text3[findIndexes] = "$"; + text3 = text3.join(""); + indexs = [...indexs, ...findIndexes]; + } + }); + text2.split("").map((itemValue, index) => { + let check = indexs.find((i) => i === index); + if (check !== undefined) { + itemHtml += `${itemValue}`; + } else { + itemHtml += `<span class='highlight'>${itemValue}</span>`; + } + }); + } else { + itemHtml = full_words[d] + } + let ScrabbleLetterScore = ScrabbleScore(); + let points = 0; + full_words[d] = full_words[d].toLowerCase(); + for (let i = 0; i < full_words[d].length; i++) { + points += ScrabbleLetterScore[full_words[d][i]] || 0; // for unknown characters + } + + let span = document.createElement("span"); + span.setAttribute("class", "points"); + span.setAttribute("value", `${points}`); + span.innerHTML = `${points}`; + + let a = document.createElement("a"); + a.setAttribute("class", "anchor__style"); + a.setAttribute("target", "_blank"); + a.setAttribute("href", "/word-meaning?search=" + full_words[d].replace(/<\/?[^>]+>/gi, '')); + a.setAttribute("data-original-title", `Lookup ${full_words[d].replace(/<\/?[^>]+>/gi, '')} in Dictionary`) + a.innerHTML = ` ${itemHtml} `; + a.appendChild(span) + content_area.appendChild(a); + } + } + document.getElementById(id).innerHTML = `More Words`; + data_index += 25; + } else { + document.getElementById(id).style.display = "none"; + } + } catch (error) { + console.error("Error fetching or processing data:", error); + } +} +const ScrabbleScore = (dictonary) => { + let twl06_sowpods = { + a: 1, + e: 1, + i: 1, + o: 1, + u: 1, + l: 1, + n: 1, + r: 1, + s: 1, + t: 1, + d: 2, + g: 2, + b: 3, + c: 3, + m: 3, + p: 3, + f: 4, + h: 4, + v: 4, + w: 4, + y: 4, + k: 5, + j: 8, + x: 8, + q: 10, + z: 10, + }; + let wwfScore = { + a: 1, + b: 4, + c: 4, + d: 2, + e: 1, + f: 4, + g: 3, + h: 3, + i: 1, + j: 10, + k: 5, + l: 2, + m: 4, + n: 2, + o: 1, + p: 4, + q: 10, + r: 1, + s: 1, + t: 1, + u: 2, + v: 5, + w: 4, + x: 8, + y: 3, + z: 10, + }; + + if (dictonary === "wwf") { + return wwfScore; + } else { + return twl06_sowpods; + } +}; +function showMoreLimit() { + let tableFooter = document.querySelectorAll(".btn-container") + let showmore = document.querySelectorAll(".showmore_btn"); + for (let i = 0; i < showmore.length; i++) { + let data_of_button = document.getElementById("alpha_" + showmore[i].getAttribute("id")); + let final_data = data_of_button.getElementsByClassName("anchor__style"); + if (final_data.length < 25) { + tableFooter[i].style.display = "none"; + } + } +} +window.onscroll = function () { + var section = document.querySelectorAll(".wordlistContainer"); + let new_sections = {}; + Array.prototype.forEach.call(section, function (e) { + if (document.body.clientWidth > 991) { + new_sections[e.id] = e.offsetTop - 10; + } else { + new_sections[e.id] = e.offsetTop - 10; + } + }); + var scrollPosition = + document.documentElement.scrollTop || document.body.scrollTop; + for (i in new_sections) { + let sort_val = document.querySelector(".sort-select").value; + if ( + i.split("_")[0] == sort_val && + new_sections[i] && + new_sections[i] <= scrollPosition + ) { + // document.querySelector(".active-tab").classList.remove("active-tab"); + // var active_now = document.querySelector("#Tab_" + i.split("_")[1]); + // active_now.classList.add("active-tab"); + // active_now.scrollIntoView({ block: "nearest" }); + } + } +}; +let sections = {}; +function Filtering(id) { + id = lengthSelect.value + + let tabs = document.getElementsByClassName("tab_link"); + tabs[0] ? tabs[0].classList.add("active-tab") : ""; + + Array.from(tabs).map((item) => { + item.classList.remove("active-tab"); + }); + main.innerHTML += ``; + let activeLetter = event.target; + activeLetter.classList.add("active-tab"); + + var section = document.querySelectorAll(".allGroupWords"); + var sort_val = "alpha"; + Array.prototype.forEach.call(section, function (e) { + if (document.body.clientWidth > 991) { + sections[e.id] = e.offsetTop - 10; + } else { + sections[e.id] = e.offsetTop - 10; + } + }); + document.documentElement.scrollTop = sections[sort_val + "_" + id] + 5; + + setTimeout(() => { + document.documentElement.scrollTop = sections[sort_val + "_" + id] + 5; + }, 150); +} +function findIndex(str, char) { + const strLength = str.length; + const indexes = []; + let newStr = str; + + while (newStr && newStr.indexOf(char) > -1) { + indexes.push(newStr.indexOf(char) + strLength - newStr.length); + newStr = newStr.substring(newStr.indexOf(char) + 5); + newStr = newStr.substring(newStr.indexOf(char) + 5); + } + + return indexes; +} \ No newline at end of file