From 684b3d594f749b644fd5705df707f35f0722d68e Mon Sep 17 00:00:00 2001 From: Benoit Alessandroni <benoit@happy-dev.fr> Date: Fri, 16 Oct 2020 00:17:06 +0200 Subject: [PATCH] bugfix: allowing to properly call the checkVoteCapability on each poll access --- js/main.js | 22 +++-- js/math.js | 229 ++++++++++++++++++++++++++--------------------------- 2 files changed, 128 insertions(+), 123 deletions(-) diff --git a/js/main.js b/js/main.js index a5da1ba..5b0ce3a 100644 --- a/js/main.js +++ b/js/main.js @@ -17,7 +17,7 @@ export function mainFirstLoad(idPrefix) { //Listener for voting form baseElement.querySelector("solid-form.poll-votes-form").addEventListener("populate",() => { setTimeout( function() { - disableVotes(baseElement); + checkVoteCapability(baseElement); }); }); } @@ -69,12 +69,9 @@ window.showHideBlocks = function ( /*********** disable voting if the startdate hasn't arrived or if the enddate has passed ***********/ -function disableVotes(baseElement) { +function checkVoteCapability(baseElement) { //get start date & end date setTimeout(async function() { - const errorMessage = baseElement.querySelector("div.unavailablePoll"); - if (errorMessage) return; - const dateSeparator = "/"; const isoStartDate = baseElement.querySelector("solid-display-date-value[name=startDate]").attributes['value'].value; const isoEndDate = baseElement.querySelector("solid-display-date-value[name=endDate]").attributes['value'].value; @@ -95,13 +92,19 @@ function disableVotes(baseElement) { //get the submit button const votingSection = baseElement.querySelector(".poll-votes-form"); const submitButton = votingSection.querySelector("input[type=submit]"); + if (submitButton.nextElementSibling) { + submitButton.nextElementSibling.remove(); + } + submitButton.removeAttribute("disabled"); if (comparisonStartDate > date) { const errorMessage = "This poll hasn't started yet, you can start voting on : " + cleanStartDate + "."; deactivateButton(submitButton, errorMessage); + return; } else if(comparisonEndDate < date) { const errorMessage = "This poll is closed since : " + cleanEndDate + "."; deactivateButton(submitButton, errorMessage); + return; } else if(comparisonEndDate === date) { const errorMessage = "Today is the last day to vote!"; activateButton(submitButton, errorMessage); @@ -112,7 +115,6 @@ function disableVotes(baseElement) { const pollPage = baseElement.parentElement.querySelector(".pollPage"); const pageTitle = pollPage.querySelector("solid-display[class=title]"); - //get the data src node of first sib display & extract the url const dataSrc = pageTitle.dataset.src || (pageTitle.component.resource && await pageTitle.component.resource['@id']); if (dataSrc) { @@ -124,6 +126,7 @@ function disableVotes(baseElement) { const sibAuth = document.querySelector('sib-auth'); const idToken = await sibAuth.getUserIdToken(); const headers = new Headers(); + if (idToken != null) { headers.set('Authorization', `Bearer ${idToken}`); headers.set('Accept', '*/*'); @@ -146,16 +149,19 @@ function disableVotes(baseElement) { //add deactivate attribute if needed function deactivateButton(submitButton, errorMessage) { submitButton.setAttribute("disabled", true); + if (submitButton.nextElementSibling) { + submitButton.nextElementSibling.remove(); + } submitButton.insertAdjacentHTML('afterend', '<div class="unavailablePoll">'+errorMessage+'</div>'); } //activate button & remove message function activateButton(submitButton, errorMessage) { - submitButton.setAttribute("enabled",true); + submitButton.removeAttribute("disabled"); if (submitButton.nextElementSibling) { submitButton.nextElementSibling.remove(); } - submitButton.insertAdjacentHTML('afterend', '<div class="unavailablePoll">'+errorMessage+'</div>'); + submitButton.insertAdjacentHTML('afterend', '<div class="informationNotice">'+errorMessage+'</div>'); } /* diff --git a/js/math.js b/js/math.js index 9f71b78..a6875d8 100644 --- a/js/math.js +++ b/js/math.js @@ -60,137 +60,136 @@ export function mathFirstLoad(baseElementId){ baseElement.parentElement.querySelector("solid-form.poll-votes-form").addEventListener("save",()=> { refreshVoteDataSrc(baseElement); }); + } +} - /********* - * Get info on the current poll - *********/ - async function getPollTotalInfo(baseElement, dataSourceDomain){ - //get value of data-scr linked to poll page - if (baseElement.parentElement) { - const pollPage = baseElement.parentElement.querySelector(".pollPage"); - const pageTitle = pollPage.querySelector("solid-display[class=title]"); - - //get the data src node of first sib display & extract the url - const dataSrc = pageTitle.dataset.src || (pageTitle.component.resource && await pageTitle.component.resource['@id']); - if (dataSrc) { - //extract current poll ID from the data src - const pollId = dataSrc.match(/\/([0-9]+)\/$/)[1]; - /*push to function that will take the value of ID - & - push it to the poll option data range - push it to the total polls data-src - */ - setCurrentPollOptions(dataSourceDomain,pollPage,pollId); - setTotalResultId(dataSourceDomain,pollPage,pollId); - } - } - } - - /** - * push poll ID into data-scr url of current poll - */ - function setTotalResultId(dataSourceDomain,currentPage,currentId){ - //get the vote blocks - //console.log("setting currnt source"); - const currentPollValues = currentPage.querySelector("[class=poll-votes-values]"); - //add the poll number - const currentPollSrc = dataSourceDomain + "/polls/total_votes/" + currentId + "/"; - //push the reconstructed data src to the HTML - currentPollValues.dataset.src = currentPollSrc; - } - - /** - * push poll ID into data-scr url poll options - */ - function setCurrentPollOptions(dataSourceDomain, currentPage, currentId){ - //add the poll option number within the URL of the options - //get the form block - const formContent = currentPage.querySelector("[class=poll-votes-form]"); - if (formContent == null) { - throw "there's no formContent with the id poll-votes-form"; - } else { - //get the range for option choices - const newOptionRange = dataSourceDomain+"/polls/"+currentId+"/pollOptions/"; - //push new - formContent.setAttribute('range-chosenoption',newOptionRange); - //console.log("form is now",formContent); - formContent.dataset.src += "?" + Date.now(); - } +/********* + * Get info on the current poll + *********/ +async function getPollTotalInfo(baseElement, dataSourceDomain){ + //get value of data-scr linked to poll page + if (baseElement.parentElement) { + const pollPage = baseElement.parentElement.querySelector(".pollPage"); + const pageTitle = pollPage.querySelector("solid-display[class=title]"); + + //get the data src node of first sib display & extract the url + const dataSrc = pageTitle.dataset.src || (pageTitle.component.resource && await pageTitle.component.resource['@id']); + if (dataSrc) { + //extract current poll ID from the data src + const pollId = dataSrc.match(/\/([0-9]+)\/$/)[1]; + /*push to function that will take the value of ID + & + push it to the poll option data range + push it to the total polls data-src + */ + setCurrentPollOptions(dataSourceDomain,pollPage,pollId); + setTotalResultId(dataSourceDomain,pollPage,pollId); } + } +} +/** + * push poll ID into data-scr url of current poll + */ +function setTotalResultId(dataSourceDomain,currentPage,currentId){ + //get the vote blocks + //console.log("setting currnt source"); + const currentPollValues = currentPage.querySelector("[class=poll-votes-values]"); + //add the poll number + const currentPollSrc = dataSourceDomain + "/polls/total_votes/" + currentId + "/"; + //push the reconstructed data src to the HTML + currentPollValues.dataset.src = currentPollSrc; +} - /*********************************************************** - * BELOW SCRIPT TO UPDATE VALUES WITHIN A POLL - * - 1. Get the values of the displayed totals of each poll options - calculate the percentage & display them - - 2. Functions that take advantage of process done in 1 in order to - personnalise content & css within the vote tab - ***********************************************************/ - function refreshTotalVotes(baseElement){ - //get all the polls - if (baseElement) { - const pollVoteValues = baseElement.querySelectorAll(".poll-votes-values"); - for (let i = 0; i < pollVoteValues.length; i++) { - //for each poll get the totals of each option - const voteOptionResults = pollVoteValues[i].querySelectorAll("[name=total_votes]"); - let totalCount = 0; - let choiceNumber = 0; +/** + * push poll ID into data-scr url poll options + */ +function setCurrentPollOptions(dataSourceDomain, currentPage, currentId){ + //add the poll option number within the URL of the options + //get the form block + const formContent = currentPage.querySelector("[class=poll-votes-form]"); + if (formContent == null) { + throw "there's no formContent with the id poll-votes-form"; + } else { + //get the range for option choices + const newOptionRange = dataSourceDomain+"/polls/"+currentId+"/pollOptions/"; + //push new + formContent.setAttribute('range-chosenoption',newOptionRange); + //console.log("form is now",formContent); + formContent.dataset.src += "?" + Date.now(); + } +} - //add option total to the global tally - for(let j = 0; j < voteOptionResults.length; j++) { - let currentValue = parseInt(voteOptionResults[j].attributes['value'].value); - if (!Number.isNaN(currentValue)) { - totalCount = totalCount + currentValue; - } else { - // console.log("it's Cheese NaN"); - } - } - //launch function to display the number of votes in HTML - displayTotalVotes(pollVoteValues[i], totalCount); - /*** - now that we have the values & the totals we can calculate the %ge of each option - we will also take advantage of this step to launch the functions that set - the background color and the choice number - **/ +/*********************************************************** + * BELOW SCRIPT TO UPDATE VALUES WITHIN A POLL + * + 1. Get the values of the displayed totals of each poll options + calculate the percentage & display them + + 2. Functions that take advantage of process done in 1 in order to + personnalise content & css within the vote tab +***********************************************************/ +function refreshTotalVotes(baseElement){ + //get all the polls + if (baseElement) { + const pollVoteValues = baseElement.querySelectorAll(".poll-votes-values"); + for (let i = 0; i < pollVoteValues.length; i++) { + //for each poll get the totals of each option + const voteOptionResults = pollVoteValues[i].querySelectorAll("[name=total_votes]"); + let totalCount = 0; + let choiceNumber = 0; - for(let j = 0; j < voteOptionResults.length; j++) { - const currentValue = parseInt(voteOptionResults[j].attributes['value'].value); - const percentageBarField = voteOptionResults[j].nextElementSibling; - if (!percentageBarField) continue; - const progressBar = percentageBarField.querySelector(".progressBarValue"); - if (!progressBar) continue; - let percent = (totalCount && currentValue / totalCount * 100).toFixed(2) + "%"; - progressBar.innerHTML = percent; - progressBar.style.width = percent; - setChoiceColor(percentageBarField, choiceNumber); - choiceNumber++; - if (choiceNumber > 3) choiceNumber = 1; - } - //launch the function that will display the choice number - setChoiceNumber(pollVoteValues[i]); + //add option total to the global tally + for(let j = 0; j < voteOptionResults.length; j++) { + let currentValue = parseInt(voteOptionResults[j].attributes['value'].value); + if (!Number.isNaN(currentValue)) { + totalCount = totalCount + currentValue; + } else { + // console.log("it's Cheese NaN"); } } - } + //launch function to display the number of votes in HTML + displayTotalVotes(pollVoteValues[i], totalCount); - /********************** - Refresh vote results when someone submits a vote - ***********************/ + /*** + now that we have the values & the totals we can calculate the %ge of each option + we will also take advantage of this step to launch the functions that set + the background color and the choice number + **/ - function refreshVoteDataSrc(baseElement){ - let pollTotalVotes = baseElement.querySelector("solid-display.poll-votes-values"); - pollTotalVotes.dataset.src = pollTotalVotes.dataset.src+"?"+Date.now(); - //math.random() to break sib cache and actually get now values - if (baseElement) { - getPollTotalInfo(baseElement, dataSourceDomain); - refreshTotalVotes(baseElement); + for(let j = 0; j < voteOptionResults.length; j++) { + const currentValue = parseInt(voteOptionResults[j].attributes['value'].value); + const percentageBarField = voteOptionResults[j].nextElementSibling; + if (!percentageBarField) continue; + const progressBar = percentageBarField.querySelector(".progressBarValue"); + if (!progressBar) continue; + let percent = (totalCount && currentValue / totalCount * 100).toFixed(2) + "%"; + progressBar.innerHTML = percent; + progressBar.style.width = percent; + setChoiceColor(percentageBarField, choiceNumber); + choiceNumber++; + if (choiceNumber > 3) choiceNumber = 1; } + //launch the function that will display the choice number + setChoiceNumber(pollVoteValues[i]); } } } +/********************** + Refresh vote results when someone submits a vote +***********************/ +function refreshVoteDataSrc(baseElement){ + let pollTotalVotes = baseElement.querySelector("solid-display.poll-votes-values"); + pollTotalVotes.dataset.src = pollTotalVotes.dataset.src+"?"+Date.now(); + //math.random() to break sib cache and actually get now values + if (baseElement) { + getPollTotalInfo(baseElement, dataSourceDomain); + refreshTotalVotes(baseElement); + } +} + function updateFormSource(baseElement){ //get the vote section of the page const pollSection = baseElement.querySelectorAll(".vote-section"); -- GitLab