Code clean up

This commit is contained in:
Stephan Porada 2020-03-19 13:59:31 +01:00
parent 25f54f1119
commit 7c9b9f0712

View File

@ -2,7 +2,8 @@
//function to get current queryData from a given queryFormElement //function to get current queryData from a given queryFormElement
function getQueryData(queryFormElement) { function getQueryData(queryFormElement) {
// Get query form element and save its data on submit and send this data via let formData
let queryData
formData = new FormData(queryFormElement); formData = new FormData(queryFormElement);
queryData = {"context": formData.get("context"), // global declaration queryData = {"context": formData.get("context"), // global declaration
"hits_per_page": formData.get("hits_per_page"), "hits_per_page": formData.get("hits_per_page"),
@ -12,9 +13,13 @@ function getQueryData(queryFormElement) {
// Function to send a query to the CQP server using queryData gatherd with getQueryData // Function to send a query to the CQP server using queryData gatherd with getQueryData
function sendQuery(event) { function sendQuery(event) {
result; // global declaration, holds query results as JSON
resultList; // global declaration, list.js object displaying the results
let queryData; // holds data of query form
let resultListOptions; // holding the options for the ResultList object
// checks if one query has been finished before // checks if one query has been finished before
// if true result download will be disabled again until query is finished // if true, result download will be disabled again until query is finished
// also shows progress bar again // also shows progress bar again
if (queryFinished) { if (queryFinished) {
exportQueryResultsElement.classList.add("disabled"); exportQueryResultsElement.classList.add("disabled");
@ -61,6 +66,15 @@ function sendQuery(event) {
// Function used when CQP server sends back the query results using socketio // Function used when CQP server sends back the query results using socketio
function recieveResults(response) { function recieveResults(response) {
let toolTipInfoElement; let toolTipInfoElement;
let chunk;
let countCorpusFiles;
let queryData;
let queryResultsElement;
let resultItems;
let queryResultsMetadataElement;
let queryResultsInteractionElement;
let queryResultsHeadElement;
let queryStatus;
queryFinished = false; queryFinished = false;
@ -82,7 +96,6 @@ function recieveResults(response) {
return; // no further code execution of this code block return; // no further code execution of this code block
} }
// logs the current recieved chunk // logs the current recieved chunk
chunk = {};
chunk = response["result"]; chunk = response["result"];
console.log("### corpus_analysis chunk ###"); console.log("### corpus_analysis chunk ###");
console.log(chunk); console.log(chunk);
@ -94,12 +107,13 @@ function recieveResults(response) {
Object.assign(result["text_lookup"], chunk["text_lookup"]); Object.assign(result["text_lookup"], chunk["text_lookup"]);
result["match_count"] = chunk["match_count"]; result["match_count"] = chunk["match_count"];
console.log("Before Current match count", result["loaded_match_count"]); console.log("Before Current match count", result["loaded_match_count"]);
queryData = getQueryData(queryFormElement);
result["query"] = queryData["query"]; result["query"] = queryData["query"];
console.log(result); console.log(result);
// Some hiding and showing of loading animations // Some hiding and showing of loading animations
queryLoadingElement.classList.add("hide"); queryLoadingElement.classList.add("hide");
queryResultsTableElement.classList.remove("hide"); queryResultsTableElement.classList.remove("hide");
let queryResultsElement = document.getElementById("query-results"); queryResultsElement = document.getElementById("query-results");
queryResultsElement.innerHTML = ""; queryResultsElement.innerHTML = "";
// check if query has any results // check if query has any results
@ -110,10 +124,9 @@ function recieveResults(response) {
} }
// List building/appending the chunks when query had results // List building/appending the chunks when query had results
match_count = chunk["match_count"]; countCorpusFiles = Object.keys(result["text_lookup"]).length;
let count_corpus_files = Object.keys(result["text_lookup"]).length;
let resultItems = []; // list for holding every row item resultItems = []; // list for holding every row item
// get infos for full match row // get infos for full match row
for (let [index, match] of chunk["matches"].entries()) { for (let [index, match] of chunk["matches"].entries()) {
resultItems.push({...match, ...{"index": index + result["loaded_match_count"]}}); resultItems.push({...match, ...{"index": index + result["loaded_match_count"]}});
@ -127,11 +140,11 @@ function recieveResults(response) {
}); });
result["loaded_match_count"] += Object.keys(chunk["matches"]).length; result["loaded_match_count"] += Object.keys(chunk["matches"]).length;
console.log("After current match count", result["loaded_match_count"]); console.log("After current match count", result["loaded_match_count"]);
let queryResultsMetadataElement = document.getElementById("query-results-metadata"); queryResultsMetadataElement = document.getElementById("query-results-metadata");
queryResultsMetadataElement.innerHTML = `<p>The query resulted in a total of ${chunk["match_count"]} matches. </p> <p> ${result["loaded_match_count"]} of ${result["match_count"]} matches in ${count_corpus_files} corpus files have been loaded.</p><p><i class="material-icons" id="tooltip-info">help</i>The Server is still sending your results. Functions like "Export Results" and "Match Inspect" will be available after all matches have been loaded.</p>`; queryResultsMetadataElement.innerHTML = `<p>The query resulted in a total of ${chunk["match_count"]} matches. </p> <p> ${result["loaded_match_count"]} of ${result["match_count"]} matches in ${countCorpusFiles} corpus files have been loaded.</p><p><i class="material-icons" id="tooltip-info">help</i>The Server is still sending your results. Functions like "Export Results" and "Match Inspect" will be available after all matches have been loaded.</p>`;
let queryResultsInteractionElement = document.getElementById("interaction-elements"); queryResultsInteractionElement = document.getElementById("interaction-elements");
queryResultsInteractionElement.appendChild(exportQueryResultsElement); queryResultsInteractionElement.appendChild(exportQueryResultsElement);
let queryResultsHeadElement = document.getElementById("query-results-head"); queryResultsHeadElement = document.getElementById("query-results-head");
queryResultsHeadElement.classList.remove("hide"); queryResultsHeadElement.classList.remove("hide");
queryStatus = result["loaded_match_count"] / result["match_count"] * 100; queryStatus = result["loaded_match_count"] / result["match_count"] * 100;
console.log(queryStatus); console.log(queryStatus);
@ -144,7 +157,7 @@ function recieveResults(response) {
queryFinished = true; // global declaration to set downlaod button and inspects buttons back to disabled for new queries queryFinished = true; // global declaration to set downlaod button and inspects buttons back to disabled for new queries
queryResultsDeterminateElement.parentNode.parentNode.classList.add("hide"); queryResultsDeterminateElement.parentNode.parentNode.classList.add("hide");
exportQueryResultsElement.classList.remove("disabled"); exportQueryResultsElement.classList.remove("disabled");
queryResultsMetadataElement.innerHTML = `<p>The query resulted in a total of ${chunk["match_count"]} matches. </p> <p> ${result["loaded_match_count"]} of ${result["match_count"]} matches in ${count_corpus_files} corpus files have been loaded.<i class="material-icons">check_circle</i></p>`; queryResultsMetadataElement.innerHTML = `<p>The query resulted in a total of ${chunk["match_count"]} matches. </p> <p> ${result["loaded_match_count"]} of ${result["match_count"]} matches in ${countCorpusFiles} corpus files have been loaded.<i class="material-icons">check_circle</i></p>`;
activateInspect(); activateInspect();
} }
} }
@ -154,8 +167,10 @@ function recieveResults(response) {
// activate inspect buttons if queryFinished is true // activate inspect buttons if queryFinished is true
function activateInspect() { function activateInspect() {
let inspectBtnElements;
if (queryFinished) { if (queryFinished) {
let inspectBtnElements = document.getElementsByClassName("inspect"); inspectBtnElements = document.getElementsByClassName("inspect");
for (let inspectBtn of inspectBtnElements) { for (let inspectBtn of inspectBtnElements) {
inspectBtn.classList.remove("disabled"); inspectBtn.classList.remove("disabled");
} }
@ -171,18 +186,20 @@ function inspect(dataIndex) {
} }
function showMatchContext(message) { function showMatchContext(message) {
let contextResultsElement;
let sentenceElement
let token;
let tokenElement;
console.log("### match_context ###"); console.log("### match_context ###");
console.log("Incoming data:", message); console.log("Incoming data:", message);
let contextResultsElement = document.getElementById("context-results"); contextResultsElement = document.getElementById("context-results");
contextResultsElement.innerHTML = "<p>&nbsp;</p>"; contextResultsElement.innerHTML = "<p>&nbsp;</p>";
document.getElementById("context-modal-loading").classList.add("hide"); document.getElementById("context-modal-loading").classList.add("hide");
document.getElementById("context-modal-ready").classList.remove("hide"); document.getElementById("context-modal-ready").classList.remove("hide");
let sentenceElement, token, tokenElement;
for (let [key, value] of Object.entries(message['context_s_cpos'])) { for (let [key, value] of Object.entries(message['context_s_cpos'])) {
sentenceElement = document.createElement("p"); sentenceElement = document.createElement("p");
for (cpos of value) { for (let cpos of value) {
token = message["cpos_lookup"][cpos]; token = message["cpos_lookup"][cpos];
tokenElement = document.createElement("span"); tokenElement = document.createElement("span");
tokenElement.classList.add("token"); tokenElement.classList.add("token");
@ -219,8 +236,10 @@ function changeHitsPerPage(event) {
// Event function triggered on context select change and also if pagination is clicked // Event function triggered on context select change and also if pagination is clicked
function changeContext(event) { function changeContext(event) {
// newValue = event.target.value; // cannot use this anymore due to reuse of this function in the above paginationElements eventListener let newContextValue;
console.log("Event", event); let lc;
let rc;
let array;
try { try {
if (event.type === "change") { if (event.type === "change") {
nopaque.toast("Updated context per match!"); nopaque.toast("Updated context per match!");
@ -229,26 +248,25 @@ function changeContext(event) {
console.log(e); console.log(e);
console.log("This error is expected."); console.log("This error is expected.");
} finally { } finally {
var contextPerItemElement = document.getElementById("context"); newContextValue = document.getElementById("context").value;
newValue = contextPerItemElement.value; console.log(newContextValue);
console.log(newValue); lc = document.getElementsByClassName("left-context");
var lc = document.getElementsByClassName("left-context"); rc = document.getElementsByClassName("right-context");
var rc = document.getElementsByClassName("right-context");
for (let element of lc) { for (let element of lc) {
array = Array.from(element.childNodes); array = Array.from(element.childNodes);
for (let element of array.slice(newValue)) { for (let element of array.slice(newContextValue)) {
element.classList.add("hide"); element.classList.add("hide");
} }
for (let element of array.slice(0, newValue)) { for (let element of array.slice(0, newContextValue)) {
element.classList.remove("hide"); element.classList.remove("hide");
} }
} }
for (let element of rc) { for (let element of rc) {
array = Array.from(element.childNodes); array = Array.from(element.childNodes);
for (let element of array.slice(newValue)) { for (let element of array.slice(newContextValue)) {
element.classList.add("hide"); element.classList.add("hide");
} }
for (let element of array.slice(0, newValue)) { for (let element of array.slice(0, newContextValue)) {
element.classList.remove("hide"); element.classList.remove("hide");
} }
} }
@ -275,8 +293,10 @@ function eventHandlerCheck(event) {
// function to apply extra information and animation to every token // function to apply extra information and animation to every token
function expertModeOn(tokenElements, result_lookup) { function expertModeOn(tokenElements, result_lookup) {
let token;
console.log("expertModeOn!"); console.log("expertModeOn!");
for (tokenElement of tokenElements) { for (let tokenElement of tokenElements) {
tokenElement.classList.add("chip"); tokenElement.classList.add("chip");
tokenElement.classList.add("hoverable"); tokenElement.classList.add("hoverable");
tokenElement.classList.add("expert-view"); tokenElement.classList.add("expert-view");
@ -286,7 +306,7 @@ function expertModeOn(tokenElements, result_lookup) {
console.log(event.target); console.log(event.target);
token = result_lookup["cpos_lookup"][event.target.dataset.cpos]; token = result_lookup["cpos_lookup"][event.target.dataset.cpos];
addToolTipToTokenElement(event.target, token); addToolTipToTokenElement(event.target, token);
}) });
} }
} }
@ -323,7 +343,7 @@ function addToolTipToTokenElement(tokenElement, token) {
// function to remove extra informations and animations from tokens // function to remove extra informations and animations from tokens
function expertModeOff(tokenElements) { function expertModeOff(tokenElements) {
console.log("expertModeOff!"); console.log("expertModeOff!");
for (tokenElement of tokenElements) { for (let tokenElement of tokenElements) {
tokenElement.classList.remove("chip"); tokenElement.classList.remove("chip");
tokenElement.classList.remove("hoverable"); tokenElement.classList.remove("hoverable");
tokenElement.classList.remove("expert-view"); tokenElement.classList.remove("expert-view");
@ -336,20 +356,27 @@ function expertModeOff(tokenElements) {
// function creates a unique and safe filename for the download // function creates a unique and safe filename for the download
function createDownloadFilename() { function createDownloadFilename() {
let today;
let currentDate;
let currentTime;
let safeFilename;
let resultFilename;
// get and create metadata // get and create metadata
console.log("Create Metadata!"); console.log("Create Metadata!");
var today = new Date(); today = new Date();
var currentDate = today.getUTCFullYear() + '-' + (today.getUTCMonth() +1) + '-' + today.getUTCDate(); currentDate = today.getUTCFullYear() + '-' + (today.getUTCMonth() +1) + '-' + today.getUTCDate();
var currentTime = today.getUTCHours() + ":" + today.getUTCMinutes() + ":" + today.getUTCSeconds(); currentTime = today.getUTCHours() + ":" + today.getUTCMinutes() + ":" + today.getUTCSeconds();
var safeFilename = result['query'].replace(/[^a-z0-9_-]/gi, "_"); safeFilename = result['query'].replace(/[^a-z0-9_-]/gi, "_");
var resultFilename = "UTC-" + currentDate + "_" + currentTime + "_" + safeFilename; resultFilename = "UTC-" + currentDate + "_" + currentTime + "_" + safeFilename;
return resultFilename return resultFilename
} }
// function to download the results as JSON // function to download the results as JSON
function downloadJSONRessource(resultFilename) { function downloadJSONRessource(resultFilename) {
let dataStr;
let downloadElement;
// stringify JSON object for json download // stringify JSON object for json download
var dataStr = JSON.stringify(result, undefined, "\t"); // use tabs to save some space dataStr = JSON.stringify(result, undefined, "\t"); // use tabs to save some space
// get downloadResultsElement // get downloadResultsElement
downloadElement = document.getElementById("download-results-json"); downloadElement = document.getElementById("download-results-json");
// start actual download // start actual download
@ -358,9 +385,10 @@ function downloadJSONRessource(resultFilename) {
// Function to download data as a Blob created from a string, should be multi purpose // Function to download data as a Blob created from a string, should be multi purpose
function download(downloadElem, dataStr, filename, type, filenameSlug) { function download(downloadElem, dataStr, filename, type, filenameSlug) {
let file;
console.log("Start Download!"); console.log("Start Download!");
filename += filenameSlug; filename += filenameSlug;
var file = new Blob([dataStr], {type: type}); file = new Blob([dataStr], {type: type});
if (window.navigator.msSaveOrOpenBlob) // IE10+ if (window.navigator.msSaveOrOpenBlob) // IE10+
window.navigator.msSaveOrOpenBlob(file, filename); window.navigator.msSaveOrOpenBlob(file, filename);
else { // Others else { // Others