/* Скрипт отвечает за формы опроса и голосования После выбранного ответа и отправки данных приходит результат с кол-вом проголосовавших и процентом голосов относительно выбранных другими пользователями ответов Добавляет валидацию перед отправкой, были ли выбраны все ответы, при спаме на страницу добавляется google captcha для проверки на бота Формы с опросами и голосованием содержаться в блоках BF908, BF913, BF918 Блок BF908 позволяет выбранный ответ отменить при повторном нажатии и переопределить свой голос */ // global variables declaration window.t_vote__browserLang = (window.navigator.userLanguage || window.navigator.language).toUpperCase().slice(0, 2); /** * Language override based on attribute */ t_onReady(function() { var allrecords = document.getElementById('allrecords'); if (allrecords) { var projectLang = allrecords.getAttribute('data-tilda-project-lang'); } if (projectLang) { window.t_vote__browserLang = projectLang; } }); // All method for IE /** * Method remove() for IE * * @param {Node} el - remove el */ function t_removeEl(el) { if (el.parentNode) { el.parentNode.removeChild(el); } } /** * Init vote * * @param {string} recId - block id * @returns {void} */ function tvote__init(recId) { var allRecords = document.getElementById('allrecords'); if (allRecords.getAttribute('data-tilda-mode')) return; var rec = document.querySelector('#rec' + recId); if (window.tildaVoteObserver) { return window.tildaVoteObserver.observe(rec); } var observer = new IntersectionObserver(tvote__handleObserver, {threshold: 0.1}); window.tildaVoteObserver = observer; observer.observe(rec); } function tvote__handleObserver(entries, observer) { entries.forEach(function(entry) { if (entry.intersectionRatio === 0) return; var rec = entry.target; observer.unobserve(rec); var vote = rec.querySelector('.t-vote'); var fullID = tvote__makeFullVoteID(vote); var startDate = new Date(); var opts = { type: vote.getAttribute('data-vote-type'), voteID: fullID, voteEl: vote, voteVisibility: vote.getAttribute('data-vote-visibility'), startDate: startDate, }; t_vote__checkVoteCondition(opts); if (vote.getAttribute('data-vote-finished') === 'yes') { vote.classList.add('t-vote_sended'); return; } setTimeout(function () { t_vote__initOneVote(opts); }, 500); }); } /** * Make a full id for voting * * @param {Node} vote - block vote * @returns {string} - full voit id */ function tvote__makeFullVoteID(vote) { // TODO: jquery element if (!(vote instanceof Element)) vote = vote[0]; var voteID = vote.getAttribute('data-vote-id'); if (!voteID) return; var fullVoteID = document.querySelector('#allrecords').getAttribute('data-tilda-project-id') + voteID; fullVoteID = fullVoteID.replace('"', '').replace(''', '').replace(/[&/\\#,+()$~%.'":;*?!<>{}\-_\s]/g, ''); vote.setAttribute('data-vote-id', fullVoteID); return fullVoteID; } /** * Check vote condition * * @param {object} opts - data params vote */ function t_vote__checkVoteCondition(opts) { // get results if we need to show it var curVoteCookie = t_vote__getCookie('vote' + opts.voteID); var curVoteResult = t_vote__getCookie('voteresult' + opts.voteID); // show results, if settings let to do it if (opts.voteVisibility === 'yes' || (opts.voteVisibility === 'onclick' && curVoteCookie)) { var btnsResult = opts.voteEl.querySelectorAll('.t-vote__btn-res'); Array.prototype.forEach.call(btnsResult, function(result) { result.style.display = 'block'; }); } // add style, if you've already voted if (curVoteCookie) { opts.voteEl.classList.add('js-vote-sended'); opts.voteEl.classList.add('t-vote_sended'); } if (opts.type === 'single' && curVoteCookie && curVoteResult) { opts.voteEl.querySelector('[data-answer-id="' + curVoteResult + '"] .t-vote__btn-el').classList.add('t-vote__btn-el_active'); } // get results from server tvote__getResult(opts.voteID); } /** * Get cookie * * @param {string} name - name cookie key * @returns {string | undefined} - return cookie */ function t_vote__getCookie(name) { var matches = document.cookie.match(new RegExp( '(?:^|; )' + name.replace(/([.$?*|{}()[\]\\/+^])/g, '\\$1') + '=([^;]*)' )); return matches ? decodeURIComponent(matches[1]) : undefined; } /** * Get result in vote block * * @param {string} voteID - block vote id * @returns {void} */ function tvote__getResult(voteID) { var vote = document.querySelector('[data-vote-id="' + voteID + '"]'); var type = vote.getAttribute('data-vote-type'); if (type === 'single') { var url = 'https://vote.tildaapi.' + t_vote__getRootZone() + '/vote/1/getresult/'; } if (type === 'multi') { var url = 'https://vote.tildaapi.' + t_vote__getRootZone() + '/vote/2/getresult/'; } if (!type) return; var xhr = new XMLHttpRequest(); url += '?' + 'voteid=' + voteID + '&' + 'host=' + location.protocol + '//' + location.host; // TODO: async flag is set to false but the browser notifies about the bad tone https://xhr.spec.whatwg.org/ xhr.open('GET', url, true); xhr.setRequestHeader('Content-Type', 'text/plain;charset=UTF-8'); xhr.onload = function() { if (xhr.status >= 200 && xhr.status < 400) { var data = xhr.responseText; if (data) { var objData = JSON.parse(data); if (typeof objData === 'object') { if (!objData['error']) { if (type === 'single') { Array.prototype.forEach.call(Object.keys(objData[0]), function(key) { var counters = vote.querySelectorAll('[data-answer-id="' + key + '"] .js-vote-count'); if (counters.length) { Array.prototype.forEach.call(counters, function(counter) { counter.innerHTML = objData[0][key]; }); } }); } if (type === 'multi') { Array.prototype.forEach.call(Object.keys(objData[0]), function(vid) { var value = objData[0][vid]; vid = String(vid).replace(/\n/g, '').trim(); // count percentage per answer var sum = 0; Array.prototype.forEach.call(Object.keys(value), function(aid) { sum += value[aid] * 1; }); Array.prototype.forEach.call(Object.keys(value), function(aid) { var val = value[aid]; var percentage = Math.round((val * 100) / sum); var answerID = aid.slice(0, aid.indexOf('-')); var answerEls = vote.querySelectorAll('[data-question-id="' + vid + '"] [data-answer-id="' + answerID + '"]'); if (!answerEls.length) return; Array.prototype.forEach.call(answerEls, function(answerEl) { var counter = answerEl.querySelector('.js-vote-count'); var percent = answerEl.querySelector('.js-vote-percent'); if (counter) counter.innerHTML = val; if (percent) percent.innerHTML = percentage + '%'; }); }); }); setTimeout(function () { if (vote) t_triggerEvent(vote, 'tildavote:numberschanged'); }, 1000); } } else { var btnResult = vote.querySelectorAll('.t-vote__btn-res'); Array.prototype.forEach.call(btnResult, function(btn) { btn.style.display = 'none'; }); } } else { t_vote__showError(voteID, ''); } } else { t_vote__showError(voteID, ''); } } else { t_vote__showError(voteID, ''); } }; xhr.onerror = function() { console.log('Fatal error: ' + xhr); t_vote__showError(voteID, ''); return; }; xhr.send(); } /** * Init btn event in block vote * * @param {object} opts - data params vote */ function t_vote__initOneVote(opts) { var btns = opts.voteEl.querySelectorAll('.js-sendvote-btn'); Array.prototype.forEach.call(btns, function(btn) { btn.addEventListener('click', function(e) { // prevent from click at the time of waiting server respond if (opts.voteEl.classList.contains('js-vote-sending')) return; // check and write to sendvote, should we send answers to server or not var sendVote = true; if (opts.type === 'single') { opts.answerID = btn.closest('.js-vote-item').getAttribute('data-answer-id'); opts.clickedEl = btn; opts.url = 'https://vote.tildaapi.' + t_vote__getRootZone() + '/vote/1/'; sendVote = t_vote__handleClick_single(opts); } if (opts.type === 'multi') { opts.url = 'https://vote.tildaapi.' + t_vote__getRootZone() + '/vote/2/'; sendVote = t_vote__handleClick_multi(opts); } if (!sendVote) return; t_vote__itemSend(opts); e.preventDefault(); }); }); } /** * Handler click for single vote * * @param {object} opts - data params vote * @returns {boolean} - return true/false validation */ function t_vote__handleClick_single(opts) { // prevent from click on unactive items, when already voted if (!opts.clickedEl.classList.contains('t-vote__btn-el_active') && opts.voteEl.classList.contains('js-vote-sended')) { return false; } if (opts.clickedEl.classList.contains('t-vote__btn-el_active') && opts.voteEl.classList.contains('js-vote-sended')) { if (t_vote__getCookie('vote_candelete' + opts.voteID)) { t_vote__itemDelete_single(opts); } return false; } return true; } /** * Handler click for multu vote * * @param {object} opts - data params vote * @returns {boolean} - return true/false validation */ function t_vote__handleClick_multi(opts) { var result = []; var answeredVotes = opts.voteEl.querySelectorAll('.js-vote-question'); var votesNum = opts.voteEl.querySelectorAll('.js-vote-question').length; answeredVotes = Array.prototype.filter.call(answeredVotes, function(answeredVote) { if (answeredVote.querySelector('.js-vote-btn:checked')) return answeredVote; }); // don't send data, if already voted if (opts.voteEl.classList.contains('js-vote-sended')) { return false; } // don't send if not all the questions are answered if (answeredVotes.length != votesNum) { if (window.t_vote__browserLang === 'RU') { t_vote__showError(opts.voteID, 'Пожалуйста, ответьте на все вопросы.'); } else { t_vote__showError(opts.voteID, 'Please, answer all questions.'); } return false; } // get all answers and save in array Array.prototype.forEach.call(answeredVotes, function(vote) { var questionID = vote.getAttribute('data-question-id'); var questionAnswers = vote.querySelectorAll('.js-vote-btn:checked'); var questionResult = []; Array.prototype.forEach.call(questionAnswers, function(answer) { var answerId = answer.closest('.js-vote-item').getAttribute('data-answer-id'); questionResult.push(answerId + '-' + questionID + '-' + opts.voteID); }); result.push({ answer: questionResult, question: questionID, }); }); opts.answerArr = result; return true; } /** * Get key and session cookie * * @param {object} opts - data params vote */ function t_vote__itemSend(opts) { opts.seconds_fromStart = (new Date().getTime() - opts.startDate.getTime()) / 1000; t_vote__changeVoteCondition(opts, 'add'); opts.voteEl.classList.add('js-vote-sending'); opts.voteEl.classList.add('t-multivote_sended'); t_vote__addLoadingStyle(opts.voteEl); if (opts.voteVisibility === 'onclick') { var btnsResult = opts.voteEl.querySelectorAll('.t-vote__btn-res'); Array.prototype.forEach.call(btnsResult, function(result) { result.style.display = 'block'; }); } var formData = new FormData(); var xhr = new XMLHttpRequest(); formData.append('host', location.protocol + '//' + location.host); // TODO: async flag is set to false but the browser notifies about the bad tone https://xhr.spec.whatwg.org/ xhr.open('POST', opts.url + 'init/', true); xhr.onload = function() { if (xhr.status >= 200 && xhr.status < 400) { var data = xhr.responseText; if (data) { var objData = JSON.parse(data); if (typeof objData === 'object') { opts.sessionKey = objData['key']; opts.sessionCookie = objData['session']; opts.voteHash = opts.voteID + opts.sessionKey; t_vote__itemSend_continue(opts); } else { t_vote__showError(opts.voteID, ''); } } else { t_vote__showError(opts.voteID, ''); } } else { t_vote__showError(opts.voteID, ''); } }; xhr.onerror = function() { console.log('Fatal error: ' + xhr); t_vote__changeVoteCondition(opts, 'remove'); t_vote__showError(opts.voteID, ''); }; xhr.send(formData); } /** * Init result for vote form * * @param {object} opts - data params vote * @param {string | undefined} captchakey - str captcha key */ function t_vote__itemSend_continue(opts, captchakey) { var allRecords = document.querySelector('#allrecords'); var pageID = allRecords.getAttribute('data-tilda-page-id'); var projectID = allRecords.getAttribute('data-tilda-project-id'); var sendData = { hash: opts.voteHash, projectid: projectID, pageid: pageID, host: location.protocol + '//' + location.host, time: opts.seconds_fromStart, session: opts.sessionCookie, }; if (opts.type === 'single') { sendData.voteid = opts.voteID; sendData.answerid = opts.answerID; } if (opts.type === 'multi') { sendData.multivoteid = opts.voteID; sendData.answers = opts.answerArr; } if (captchakey) { sendData.votecaptcha = captchakey; t_vote__changeVoteCondition(opts, 'add'); } sendData = t_vote__getObjParams(sendData); var formData = new FormData(); Array.prototype.forEach.call(Object.keys(sendData), function(key) { formData.append(key, sendData[key]); }); var xhr = new XMLHttpRequest(); xhr.open('POST', opts.url + 'send/', true); xhr.onload = function() { if (xhr.status >= 200 && xhr.status < 400) { var data = xhr.responseText; if (data) { opts.voteEl.classList.remove('js-vote-sending'); opts.voteEl.classList.remove('t-vote_loading'); var objData = JSON.parse(data); if (typeof objData === 'object') { if (!objData['error']) { opts.voteEl.classList.add('js-vote-sended'); opts.voteEl.classList.add('t-vote_sended'); t_vote__writeSendCookie(objData, opts); var existingErrorEl = opts.voteEl.querySelector('.t-vote__errorbox'); if (existingErrorEl) t_removeEl(existingErrorEl); if (opts.voteEl) t_triggerEvent(opts.voteEl, 'tildavote:resultsended'); } else { t_vote__changeVoteCondition(opts, 'remove'); opts.voteEl.classList.remove('t-vote_sended'); t_vote__handleServerError(objData, opts); } } else { t_vote__showError(opts.voteID, ''); } } else { t_vote__showError(opts.voteID, ''); } } else { t_vote__showError(opts.voteID, ''); } }; xhr.onerror = function() { console.log('Fatal error: ' + xhr); t_vote__showError(opts.voteID, ''); }; xhr.send(formData); } /** * Converts a multi-level object to a single-level one with question and answer data to send * * @param {object} objData - object with data * @param {string | undefined} strKey - str array key + index * @returns {object} - return new object */ function t_vote__getObjParams(objData, strKey) { var newObj = {}; var strKey = strKey ? strKey : ''; Array.prototype.forEach.call(Object.keys(objData), function(key) { if (Array.isArray(objData[key])) { Array.prototype.forEach.call(objData[key], function(obj, ind) { if (obj instanceof Object) { strKey = key + '[' + ind + ']'; Object.assign(newObj, t_vote__getObjParams(obj, strKey)); strKey = ''; } else { var str = strKey + '[' + key + ']' + '[]'; newObj[str] = obj; } }); } else { if (strKey) { var str = strKey + '[' + key + ']'; newObj[str] = objData[key]; } else { newObj[key] = objData[key]; } } }); return newObj; } /** * Overwrites cookies on successful request * * @param {object} data - request result * @param {object} opts - data params vote */ function t_vote__writeSendCookie(data, opts) { if (data['message'] === 'ok') { t_vote__setCookie('vote' + data['voteid'], opts.voteHash, { expires: 3600 * 24, }); if (opts.type === 'single') { t_vote__setCookie('voteresult' + data['voteid'], opts.answerID, { expires: 3600 * 24, }); t_vote__setCookie('vote_candelete' + data['voteid'], 'yes', { expires: 1800, }); } } } /** * Overwrite the voice when you click on the selected voice again in a single vote * * @param {object} opts - data params vote */ function t_vote__itemDelete_single(opts) { opts.seconds_fromStart = (new Date().getTime() - opts.startDate.getTime()) / 1000; t_vote__changeVoteCondition(opts, 'remove'); opts.voteEl.classList.add('js-vote-sending'); opts.voteEl.classList.remove('t-vote_sended'); t_vote__addLoadingStyle(opts.voteEl); opts.voteHash = t_vote__getCookie('vote' + opts.voteID); var sendData = { voteid: opts.voteID, hash: opts.voteHash, host: location.protocol + '//' + location.host, }; var formData = new FormData(); Array.prototype.forEach.call(Object.keys(sendData), function(key) { formData.append(key, sendData[key]); }); var xhr = new XMLHttpRequest(); xhr.open('POST', opts.url + 'delete/', true); xhr.onload = function() { if (xhr.status >= 200 && xhr.status < 400) { var data = xhr.responseText; if (data) { opts.voteEl.classList.remove('js-vote-sending'); opts.voteEl.classList.remove('t-vote_loading'); var objData = JSON.parse(data); if (typeof objData === 'object') { if (!objData['error']) { opts.voteEl.classList.remove('js-vote-sended'); opts.voteEl.classList.remove('t-vote_sended'); t_vote__removeSendCookie(objData, opts); } else { t_vote__changeVoteCondition(opts, 'add'); opts.voteEl.classList.add('t-vote_sended'); t_vote__handleServerError(objData, opts); } } else { t_vote__showError(opts.voteID, ''); } } else { t_vote__showError(opts.voteID, ''); } } else { t_vote__showError(opts.voteID, ''); } }; xhr.onerror = function() { console.log('Fatal error: ' + xhr); t_vote__showError(opts.voteID, ''); }; xhr.send(formData); } /** * Remove cookie send * * @param {object} data - request result * @param {object} opts - data params vote */ function t_vote__removeSendCookie(data, opts) { if (data['message'] === 'ok') { var options = { expires: 1, }; t_vote__setCookie('vote' + data['voteid'], opts.voteHash, options); t_vote__setCookie('voteresult' + data['voteid'], '', options); t_vote__setCookie('vote_candelete' + data['voteid'], '', options); } } /** * Add loading class in vote block * * @param {Node} voteBlock - vote block */ function t_vote__addLoadingStyle(voteBlock) { setTimeout(function () { if (voteBlock.classList.contains('js-vote-sending')) { voteBlock.classList.add('t-vote_loading'); } }, 150); } /** * Text assignment depending on the error code * * @param {object} data - request result * @param {object} opts - data params vote * @returns {undefined} - exit function */ function t_vote__handleServerError(data, opts) { if (data['error'] == 6) { window.tvote_opts = opts; addTildaCaptcha(); return; } var errorText = ''; if (window.t_vote__browserLang === 'RU') { errorText = 'Что-то пошло не так и голосование не может корректно работать. Пожалуйста, попробуйте другой браузер, отключите режим инкогнито или обратитесь к владельцу сайта.'; } else { errorText = "Something went wrong and vote doesn't work correctly. Please, try another browser, unlock private mode or write to website owner."; } if (data['error'] == 1) { if (window.t_vote__browserLang === 'RU') { errorText = 'С этого IP недавно голосовали. Пожалуйста, подождите 10 минут и попробуйте еще раз.'; } else { errorText = 'Somebody has recently voted from this IP. Please wait 10 minutes and try again.'; } } if (data['error'] == 2) { if (window.t_vote__browserLang === 'RU') { errorText = 'С вашего IP адреса приходит слишком много запросов к серверу. Сервер временно не может принимать голоса с этого IP. Пожалуйста, попробуйте еще раз позже.'; } else { errorText = "There are too many votes from your IP. Server temporarily can't get votes from this IP. Please, try again later."; } } if (data['error'] == 4) { if (window.t_vote__browserLang === 'RU') { errorText = 'Извините, но голос удалить уже нельзя. Удалить голос можно только в течение 30 минут после активации.'; } else { errorText = "Sorry, but you can't delete vote now. You can delete votes just during 30 minutes after activation."; } } if (data['error'] == 5) { if (window.t_vote__browserLang === 'RU') { errorText = 'С вашего IP запросы приходят слишком часто. Пожалуйста, подождите 7 секунд прежде чем выбирать ответы в слудующих голосованиях на странице.'; } else { errorText = 'Votes are sended too often from your IP. Please wait 7 seconds between choosing answers in different votes.'; } } t_vote__showError(opts.voteID, errorText); } /** * Add in document captcha */ function addTildaCaptcha() { var voteCaptchaBox = document.querySelector('#tildavotecaptchabox'); if (voteCaptchaBox) t_removeEl(voteCaptchaBox); document.body.insertAdjacentHTML('beforebegin', '
'); window.removeEventListener('message', checkVerifyTildaVoteCaptcha); window.addEventListener('message', checkVerifyTildaVoteCaptcha); } /** * Checks captcha verification * * @param {MouseEvent} event - event * @returns {undefined} - exit function */ function checkVerifyTildaVoteCaptcha(event) { var voteCaptchaBox = document.querySelector('#tildavotecaptchabox'); if (event.origin.indexOf('vote.tildaapi.' + t_vote__getRootZone()) !== -1) { if (voteCaptchaBox) t_removeEl(voteCaptchaBox); if (event.data === 'closeiframe') return; t_vote__itemSend_continue(window.tvote_opts, event.data); } } /** * Show block with a text error * * @param {string} voteID - id group vote * @param {string} errorText - error text */ function t_vote__showError(voteID, errorText) { if (!errorText) { if (window.t_vote__browserLang === 'RU') { errorText = 'Что-то пошло не так и голосование может работать некорректно. Пожалуйста, проверьте соединение с интернетом или обратитесь к владельцу сайта.'; } else { errorText = "Something went wrong and vote doesn't work correctly. Please, check your internet connection or write to website owner."; } } var vote = document.querySelector('[data-vote-id="' + voteID + '"]'); var type = vote.getAttribute('data-vote-type'); if (!type || type === 'single') { var errorEl = "
" + errorText + '
'; vote.insertAdjacentHTML('afterend', errorEl); vote.style.display = 'none'; } if (type === 'multi') { var existingErrorEl = vote.querySelector('.t-vote__errorbox'); if (existingErrorEl) t_removeEl(existingErrorEl); var errorEl = "
" + errorText + '
'; var btnsSendVote = vote.querySelectorAll('.js-sendvote-btn'); btnsSendVote[btnsSendVote.length - 1].insertAdjacentHTML('beforebegin', errorEl); } } /** * Change the voting conditions * * @param {object} opts - data params vote * @param {string} action - completed action */ function t_vote__changeVoteCondition(opts, action) { if (opts.type === 'multi') { t_vote__changeStat(opts, action); } if (opts.type === 'single' && action === 'add') { t_vote__incrementAnswerNum(opts.voteID, opts.answerID); var actionElement = opts.voteEl.querySelector('[data-answer-id="' + opts.answerID + '"] .t-vote__btn-el'); actionElement.classList.add('t-vote__btn-el_active'); } if (opts.type === 'single' && action === 'remove') { t_vote__decrementAnswerNum(opts.voteID, opts.answerID); var actionElement = opts.voteEl.querySelector('.t-vote__btn-el_active'); actionElement.classList.remove('t-vote__btn-el_active'); } } /** * Changing stat in multiple voting * * @param {object} opts - data params vote * @param {string} action - completed action */ function t_vote__changeStat(opts, action) { var questions = opts.voteEl.querySelectorAll('.js-vote-question'); Array.prototype.forEach.call(questions, function(question) { var answers = question.querySelectorAll('.js-vote-item'); var sum = 0; Array.prototype.forEach.call(answers, function(answer) { var counter = answer.querySelector('.js-vote-count'); if (!counter) return; var amount = counter.textContent * 1; var checkedEl = answer.querySelectorAll('.js-vote-btn:checked').length; sum += amount; if (checkedEl !== 0 && action === 'add') { sum++; amount++; counter.innerHTML = amount; } if (checkedEl !== 0 && action === 'remove') { sum--; amount--; counter.innerHTML = amount; } }); // recalculate percantage Array.prototype.forEach.call(answers, function(answer) { var counter = answer.querySelector('.js-vote-count'); var percent = answer.querySelector('.js-vote-percent'); var amount = 0; if (counter) { amount = counter.textContent * 1; } var percentAge = Math.round((amount * 100) / sum); if (sum !== 0) { if (counter) { counter.innerHTML = amount; } if (percent) { percent.innerHTML = percentAge + '%'; } } else { if (counter) { counter.innerHTML = 0; } if (percent) { percent.innerHTML = '0%'; } } }); }); if (opts.voteEl) t_triggerEvent(opts.voteEl, 'tildavote:numberschanged'); } /** * Increment answer number in a single vote * * @param {string} voteID - id group vote * @param {string} answerId - id btn vote */ function t_vote__incrementAnswerNum(voteID, answerId) { var counter = document.querySelector('[data-vote-id="' + voteID + '"] [data-answer-id="' + answerId + '"] .js-vote-count'); if (counter) { var value = counter.textContent; counter.innerHTML = ++value * 1; } } /** * Decrement answer number in a single vote * * @param {string} voteID - id group vote * @param {string} answerId - id btn vote */ function t_vote__decrementAnswerNum(voteID, answerId) { var counter = document.querySelector('[data-vote-id="' + voteID + '"] [data-answer-id="' + answerId + '"] .js-vote-count'); if (counter) { var value = counter.textContent; counter.innerHTML = --value * 1; } } /** * Set observer for record, and send request for results when record is visible * @param {Node} recId - record element */ function t_vote__observeRecordForGettingStats(rec) { // данный слушатель необходим для редактора // для кейса когда у нас много блоков голосования // мы хотим не отправлять сразу все запросы за статистикой, // а делать это по мере отображения блока (BF913, BF908) if (window.tildaVoteEditorObserver) { window.tildaVoteEditorObserver.observe(rec); } else { var handleObserver = function(entries, observer) { entries.forEach(function(entry) { if (entry.intersectionRatio === 0) return; var rec = entry.target; observer.unobserve(rec); var answersEl = rec.querySelector('.t-vote'); if(!answersEl) return; window.tildaVoteQueue.push(answersEl); }); }; var observer = new IntersectionObserver(handleObserver, { threshold: 0.1, }); window.tildaVoteEditorObserver = observer; observer.observe(rec); // массив очереди для запроса результатов голосования window.tildaVoteQueue = []; setInterval(function() { t_vote__checkVoteQueue(); }, 1000); } } /** * Send requests for vote results when record added to queue */ function t_vote__checkVoteQueue() { if (!window.tildaVoteQueue || window.tildaVoteQueue.length === 0) return; // получаем первый элемент очереди // и запрашиваем результаты const answerEl = window.tildaVoteQueue.shift(); const voteID = tvote__makeFullVoteID(answerEl); tvote__getResult(voteID); } /** * Overwrites document cookies * * @param {string} name - key record * @param {string} value - record the value key * @param {object} options - expiration time of cookies by GMT */ function t_vote__setCookie(name, value, options) { options = options || {}; var expires = options.expires; if (typeof expires === 'number' && expires) { var date = new Date(); date.setTime(date.getTime() + expires * 1000); expires = options.expires = date; } if (expires && expires.toUTCString) { options.expires = expires.toUTCString(); } value = encodeURIComponent(value); var updatedCookie = name + '=' + value; for (var propName in options) { updatedCookie += '; ' + propName; var propValue = options[propName]; if (propValue !== true) { updatedCookie += '=' + propValue; } } document.cookie = updatedCookie + '; SameSite=Lax;'; } // Polyfill: Array.prototype.some if (!Array.prototype.some) { Array.prototype.some = function(fun/*, thisArg*/) { 'use strict'; if (this == null) { throw new TypeError('Array.prototype.some called on null or undefined'); } if (typeof fun !== 'function') { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i < len; i++) { if (i in t && fun.call(thisArg, t[i], i, t)) { return true; } } return false; }; } // Polyfill: Element.prototype.matches() (function(e) { var matches = e.matches || e.matchesSelector || e.webkitMatchesSelector || e.mozMatchesSelector || e.msMatchesSelector || e.oMatchesSelector; !matches ? (e.matches = e.matchesSelector = function matches(selector) { var matches = document.querySelectorAll(selector); var th = this; return Array.prototype.some.call(matches, function(e) { return e === th; }); }) : (e.matches = e.matchesSelector = matches); })(Element.prototype); // Polyfill: Element.prototype.closest() if (!Element.prototype.closest) { Element.prototype.closest = function (s) { var el = this; while (el && el.nodeType === 1) { if (Element.prototype.matches.call(el, s)) { return el; } el = el.parentElement || el.parentNode; } return null; }; } // Функция временно продублирована из tilda-scrits для избежания проблем с кэшем function t_triggerEvent(el, eventName) { var event; if (document.createEvent) { event = document.createEvent('HTMLEvents'); event.initEvent(eventName, true, false); } else if (document.createEventObject) { event = document.createEventObject(); event.eventType = eventName; } event.eventName = eventName; if (el.dispatchEvent) { el.dispatchEvent(event); } else if (el.fireEvent) { el.fireEvent('on' + event.eventType, event); } else if (el[eventName]) { el[eventName](); } else if (el['on' + eventName]) { el['on' + eventName](); } } function t_vote__getRootZone() { const allrecords = document.getElementById('allrecords'); const rootZone = allrecords && allrecords.getAttribute('data-tilda-root-zone'); return rootZone || 'one'; }