first commit

This commit is contained in:
User A0264400
2026-04-01 23:20:16 +03:00
commit a766acdc90
23071 changed files with 4933189 additions and 0 deletions

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
UAGBContainer={init(t){const n=document.querySelector(t+".uagb-is-root-container:not(.alignwide)");var e;n&&(t=n.clientWidth,e=getComputedStyle(n).getPropertyValue("--inner-content-custom-width"),n.style.setProperty("--inner-content-custom-width-final",`min(${t}px,${e})`),n.style.setProperty("--root-container-full-width",t+"px"),t<=parseInt(e)?(n.style.setProperty("padding-left","calc( ( var(--root-container-full-width) - var( --inner-content-custom-width-final ) ) / 2 + var(--padding-left) )"),n.style.setProperty("padding-right","calc( ( var(--root-container-full-width) - var( --inner-content-custom-width-final ) ) / 2 + var(--padding-right) )")):(n.style.setProperty("padding-left","calc( ( var(--root-container-full-width) - var( --inner-content-custom-width-final ) ) / 2 )"),n.style.setProperty("padding-right","calc( ( var(--root-container-full-width) - var( --inner-content-custom-width-final ) ) / 2 )")))}};

View File

@@ -0,0 +1 @@
!function(t,i){"object"==typeof exports&&"undefined"!=typeof module?i(exports):"function"==typeof define&&define.amd?define(["exports"],i):i((t=t||self).countUp={})}(this,function(t){"use strict";var i=function(){return(i=Object.assign||function(t){for(var i,a=1,s=arguments.length;a<s;a++)for(var n in i=arguments[a])Object.prototype.hasOwnProperty.call(i,n)&&(t[n]=i[n]);return t}).apply(this,arguments)},a=function(){function t(t,a,s){var n=this;this.target=t,this.endVal=a,this.options=s,this.version="2.0.7",this.defaults={startVal:0,decimalPlaces:0,duration:2,useEasing:!0,useGrouping:!0,smartEasingThreshold:999,smartEasingAmount:333,separator:",",decimal:".",prefix:"",suffix:""},this.finalEndVal=null,this.useEasing=!0,this.countDown=!1,this.error="",this.startVal=0,this.paused=!0,this.count=function(t){n.startTime||(n.startTime=t);var i=t-n.startTime;n.remaining=n.duration-i,n.useEasing?n.countDown?n.frameVal=n.startVal-n.easingFn(i,0,n.startVal-n.endVal,n.duration):n.frameVal=n.easingFn(i,n.startVal,n.endVal-n.startVal,n.duration):n.countDown?n.frameVal=n.startVal-(n.startVal-n.endVal)*(i/n.duration):n.frameVal=n.startVal+(n.endVal-n.startVal)*(i/n.duration),n.countDown?n.frameVal=n.frameVal<n.endVal?n.endVal:n.frameVal:n.frameVal=n.frameVal>n.endVal?n.endVal:n.frameVal,n.frameVal=Number(n.frameVal.toFixed(n.options.decimalPlaces)),n.printValue(n.frameVal),i<n.duration?n.rAF=requestAnimationFrame(n.count):null!==n.finalEndVal?n.update(n.finalEndVal):n.callback&&n.callback()},this.formatNumber=function(t){var i,a,s,e,r,o=t<0?"-":"";if(i=Math.abs(t).toFixed(n.options.decimalPlaces),s=(a=(i+="").split("."))[0],e=a.length>1?n.options.decimal+a[1]:"",n.options.useGrouping){r="";for(var l=0,u=s.length;l<u;++l)0!==l&&l%3==0&&(r=n.options.separator+r),r=s[u-l-1]+r;s=r}return n.options.numerals&&n.options.numerals.length&&(s=s.replace(/[0-9]/g,function(t){return n.options.numerals[+t]}),e=e.replace(/[0-9]/g,function(t){return n.options.numerals[+t]})),o+n.options.prefix+s+e+n.options.suffix},this.easeOutExpo=function(t,i,a,s){return a*(1-Math.pow(2,-10*t/s))*1024/1023+i},this.options=i(i({},this.defaults),s),this.formattingFn=this.options.formattingFn?this.options.formattingFn:this.formatNumber,this.easingFn=this.options.easingFn?this.options.easingFn:this.easeOutExpo,this.startVal=this.validateValue(this.options.startVal),this.frameVal=this.startVal,this.endVal=this.validateValue(a),this.options.decimalPlaces=Math.max(this.options.decimalPlaces),this.resetDuration(),this.options.separator=String(this.options.separator),this.useEasing=this.options.useEasing,""===this.options.separator&&(this.options.useGrouping=!1),this.el="string"==typeof t?document.getElementById(t):t,this.el?this.printValue(this.startVal):this.error="[CountUp] target is null or undefined"}return t.prototype.determineDirectionAndSmartEasing=function(){var t=this.finalEndVal?this.finalEndVal:this.endVal;this.countDown=this.startVal>t;var i=t-this.startVal;if(Math.abs(i)>this.options.smartEasingThreshold){this.finalEndVal=t;var a=this.countDown?1:-1;this.endVal=t+a*this.options.smartEasingAmount,this.duration=this.duration/2}else this.endVal=t,this.finalEndVal=null;this.finalEndVal?this.useEasing=!1:this.useEasing=this.options.useEasing},t.prototype.start=function(t){this.error||(this.callback=t,this.duration>0?(this.determineDirectionAndSmartEasing(),this.paused=!1,this.rAF=requestAnimationFrame(this.count)):this.printValue(this.endVal))},t.prototype.pauseResume=function(){this.paused?(this.startTime=null,this.duration=this.remaining,this.startVal=this.frameVal,this.determineDirectionAndSmartEasing(),this.rAF=requestAnimationFrame(this.count)):cancelAnimationFrame(this.rAF),this.paused=!this.paused},t.prototype.reset=function(){cancelAnimationFrame(this.rAF),this.paused=!0,this.resetDuration(),this.startVal=this.validateValue(this.options.startVal),this.frameVal=this.startVal,this.printValue(this.startVal)},t.prototype.update=function(t){cancelAnimationFrame(this.rAF),this.startTime=null,this.endVal=this.validateValue(t),this.endVal!==this.frameVal&&(this.startVal=this.frameVal,this.finalEndVal||this.resetDuration(),this.finalEndVal=null,this.determineDirectionAndSmartEasing(),this.rAF=requestAnimationFrame(this.count))},t.prototype.printValue=function(t){var i=this.formattingFn(t);"INPUT"===this.el.tagName?this.el.value=i:"text"===this.el.tagName||"tspan"===this.el.tagName?this.el.textContent=i:this.el.innerHTML=i},t.prototype.ensureNumber=function(t){return"number"==typeof t&&!isNaN(t)},t.prototype.validateValue=function(t){var i=Number(t);return this.ensureNumber(i)?i:(this.error="[CountUp] invalid start or end value: "+t,null)},t.prototype.resetDuration=function(){this.startTime=null,this.duration=1e3*Number(this.options.duration),this.remaining=this.duration},t}();t.CountUp=a,Object.defineProperty(t,"__esModule",{value:!0})});

View File

@@ -0,0 +1,184 @@
/**
* Created by dagan on 07/04/2014.
*/
'use strict';
window.XgUtils =
window.XgUtils ||
( function () {
function extend( object, defaultObject ) {
const result = defaultObject || {};
let key;
for ( key in object ) {
if ( object.hasOwnProperty( key ) ) {
result[ key ] = object[ key ];
}
}
return result;
}
//public interface
return {
extend,
};
} )();
window.xsLocalStorage =
window.xsLocalStorage ||
( function () {
const MESSAGE_NAMESPACE = 'cross-domain-local-message-uag';
let options = {
iframeId: 'cross-domain-iframe-uag',
iframeUrl: undefined,
initCallback() {},
};
let requestId = -1;
let iframe;
const requests = {};
let wasInit = false;
let iframeReady = true;
function applyCallback( data ) {
if ( requests[ data.id ] ) {
requests[ data.id ]( data );
delete requests[ data.id ];
}
}
function receiveMessage( event ) {
let data;
try {
data = JSON.parse( event.data );
} catch ( err ) {
//not our message, can ignore
}
if ( data && data.namespace === MESSAGE_NAMESPACE ) {
if ( data.id === 'iframe-ready' ) {
iframeReady = true;
options.initCallback();
} else {
applyCallback( data );
}
}
}
function buildMessage( action, key, value, callback ) {
requestId++;
requests[ requestId ] = callback;
const data = {
namespace: MESSAGE_NAMESPACE,
id: requestId,
action,
key,
value,
};
iframe?.contentWindow.postMessage( JSON.stringify( data ), '*' );
}
function init( customOptions ) {
/* eslint-disable no-undef */
options = XgUtils.extend( customOptions, options );
const temp = document.createElement( 'div' );
if ( window.addEventListener ) {
window.addEventListener( 'message', receiveMessage, false );
} else {
window.attachEvent( 'onmessage', receiveMessage );
}
temp.innerHTML =
'<iframe id="' + options.iframeId + '" src=' + options.iframeUrl + ' style="display: none;"></iframe>';
document.body.appendChild( temp );
iframe = document.getElementById( options.iframeId );
}
function isApiReady() {
if ( ! wasInit ) {
return false;
}
if ( ! iframeReady ) {
return false;
}
return true;
}
function isDomReady() {
return document.readyState === 'complete';
}
return {
//callback is optional for cases you use the api before window load.
init( customOptions ) {
if ( ! customOptions.iframeUrl ) {
throw 'Please specify the iframe URL';
}
if ( wasInit ) {
return;
}
wasInit = true;
if ( isDomReady() ) {
init( customOptions );
} else if ( document.addEventListener ) {
// All browsers expect IE < 9
document.addEventListener( 'readystatechange', function () {
if ( isDomReady() ) {
init( customOptions );
}
} );
} else {
// IE < 9
document.attachEvent( 'readystatechange', function () {
if ( isDomReady() ) {
init( customOptions );
}
} );
}
},
setItem( key, value, callback ) {
if ( ! isApiReady() ) {
return;
}
buildMessage( 'set', key, value, callback );
},
getItem( key, callback ) {
if ( ! isApiReady() ) {
return;
}
buildMessage( 'get', key, null, callback );
},
removeItem( key, callback ) {
if ( ! isApiReady() ) {
return;
}
buildMessage( 'remove', key, null, callback );
},
key( index, callback ) {
if ( ! isApiReady() ) {
return;
}
buildMessage( 'key', index, null, callback );
},
getSize( callback ) {
if ( ! isApiReady() ) {
return;
}
buildMessage( 'size', null, null, callback );
},
getLength( callback ) {
if ( ! isApiReady() ) {
return;
}
buildMessage( 'length', null, null, callback );
},
clear( callback ) {
if ( ! isApiReady() ) {
return;
}
buildMessage( 'clear', null, null, callback );
},
wasInit() {
return wasInit;
},
};
} )();

View File

@@ -0,0 +1 @@
"use strict";window.XgUtils=window.XgUtils||{extend:function(e,t){const n=t||{};let i;for(i in e)e.hasOwnProperty(i)&&(n[i]=e[i]);return n}},window.xsLocalStorage=window.xsLocalStorage||function(){const a="cross-domain-local-message-uag";let n={iframeId:"cross-domain-iframe-uag",iframeUrl:void 0,initCallback(){}},r=-1,o;const d={};let t=!1,u=!0;function m(e){let t;try{t=JSON.parse(e.data)}catch(e){}t&&t.namespace===a&&("iframe-ready"===t.id?(u=!0,n.initCallback()):(e=t,d[e.id]&&(d[e.id](e),delete d[e.id])))}function i(e,t,n,i){r++,d[r]=i;i={namespace:a,id:r,action:e,key:t,value:n};o?.contentWindow.postMessage(JSON.stringify(i),"*")}function l(e){n=XgUtils.extend(e,n);const t=document.createElement("div");window.addEventListener?window.addEventListener("message",m,!1):window.attachEvent("onmessage",m),t.innerHTML='<iframe id="'+n.iframeId+'" src='+n.iframeUrl+' style="display: none;"></iframe>',document.body.appendChild(t),o=document.getElementById(n.iframeId)}function c(){return t&&!!u}function s(){return"complete"===document.readyState}return{init(e){if(!e.iframeUrl)throw"Please specify the iframe URL";t||(t=!0,s()?l(e):document.addEventListener?document.addEventListener("readystatechange",function(){s()&&l(e)}):document.attachEvent("readystatechange",function(){s()&&l(e)}))},setItem(e,t,n){c()&&i("set",e,t,n)},getItem(e,t){c()&&i("get",e,null,t)},removeItem(e,t){c()&&i("remove",e,null,t)},key(e,t){c()&&i("key",e,null,t)},getSize(e){c()&&i("size",null,null,e)},getLength(e){c()&&i("length",null,null,e)},clear(e){c()&&i("clear",null,null,e)},wasInit(){return t}}}();

View File

@@ -0,0 +1,172 @@
function slideUp( target, duration ) {
target.style.transitionProperty = 'height, margin, padding';
target.style.transitionDuration = duration + 'ms';
target.style.boxSizing = 'border-box';
target.style.height = target.offsetHeight + 'px';
target.offsetHeight; // eslint-disable-line no-unused-expressions
target.style.overflow = 'hidden';
target.style.height = 0;
target.style.paddingTop = 0;
target.style.paddingBottom = 0;
target.style.marginTop = 0;
target.style.marginBottom = 0;
window.setTimeout( function () {
target.style.display = 'none';
target.style.removeProperty( 'height' );
target.style.removeProperty( 'padding-top' );
target.style.removeProperty( 'padding-bottom' );
target.style.removeProperty( 'margin-top' );
target.style.removeProperty( 'margin-bottom' );
target.style.removeProperty( 'overflow' );
target.style.removeProperty( 'transition-duration' );
target.style.removeProperty( 'transition-property' );
}, duration );
}
function slideDown( target, duration ) {
target.style.removeProperty( 'display' );
let display = window.getComputedStyle( target ).display;
if ( display === 'none' ) display = 'block';
target.style.display = display;
const height = target.offsetHeight;
target.style.overflow = 'hidden';
target.style.height = 0;
target.style.paddingTop = 0;
target.style.paddingBottom = 0;
target.style.marginTop = 0;
target.style.marginBottom = 0;
target.offsetHeight; // eslint-disable-line no-unused-expressions
target.style.boxSizing = 'border-box';
target.style.transitionProperty = 'height, margin, padding';
target.style.transitionDuration = duration + 'ms';
target.style.height = height + 'px';
target.style.removeProperty( 'padding-top' );
target.style.removeProperty( 'padding-bottom' );
target.style.removeProperty( 'margin-top' );
target.style.removeProperty( 'margin-bottom' );
window.setTimeout( function () {
target.style.removeProperty( 'height' );
target.style.removeProperty( 'overflow' );
target.style.removeProperty( 'transition-duration' );
target.style.removeProperty( 'transition-property' );
}, duration );
}
function setupFAQ() {
const pattern = new RegExp( '^[\\w\\-]+$' );
const hashval = window.location.hash.substring( 1 );
const expandFirstelements = document.getElementsByClassName( 'uagb-faq-expand-first-true' );
const inactiveOtherelements = document.getElementsByClassName( 'uagb-faq-inactive-other-false' );
if (
document.getElementById( hashval ) !== undefined &&
document.getElementById( hashval ) !== null &&
document.getElementById( hashval ) !== '' &&
pattern.test( hashval )
) {
const elementToOpen = document.getElementById( hashval );
if ( elementToOpen !== undefined ) {
elementToOpen.classList.add( 'uagb-faq-item-active' );
elementToOpen.setAttribute( 'aria-expanded', true );
const faqContent = elementToOpen.getElementsByClassName( 'uagb-faq-content' )[ 0 ];
if ( faqContent ) {
slideDown( faqContent, 500 );
}
}
} else {
for ( let item = 0; item < expandFirstelements.length; item++ ) {
if ( true === expandFirstelements[ item ].classList.contains( 'uagb-faq-layout-accordion' ) ) {
let faqItem = expandFirstelements[ item ].querySelectorAll(
'.uagb-faq-child__outer-wrap.uagb-faq-item'
)[ 0 ];
if ( ! faqItem ) {
faqItem = expandFirstelements[ item ].querySelectorAll(
'.uagb-faq-child__outer-wrap .uagb-faq-item'
)[ 0 ];
}
faqItem.classList.add( 'uagb-faq-item-active' );
faqItem.setAttribute( 'aria-expanded', true );
faqItem.querySelectorAll( '.uagb-faq-content' )[ 0 ].style.display = 'block';
}
}
}
for ( let item = 0; item < inactiveOtherelements.length; item++ ) {
if ( true === inactiveOtherelements[ item ].classList.contains( 'uagb-faq-layout-accordion' ) ) {
let otherItems = inactiveOtherelements[ item ].querySelectorAll(
'.uagb-faq-child__outer-wrap.uagb-faq-item'
);
if ( ! otherItems || 0 === otherItems.length ) {
otherItems = inactiveOtherelements[ item ].querySelectorAll(
'.uagb-faq-child__outer-wrap .uagb-faq-item'
);
}
for ( let childItem = 0; childItem < otherItems.length; childItem++ ) {
otherItems[ childItem ].classList.add( 'uagb-faq-item-active' );
otherItems[ childItem ].setAttribute( 'aria-expanded', true );
otherItems[ childItem ].querySelectorAll( '.uagb-faq-content' )[ 0 ].style.display = 'block';
}
}
}
}
window.addEventListener( 'load', function () {
setupFAQ();
const accordionElements = document.getElementsByClassName( 'uagb-faq-layout-accordion' );
for ( let item = 0; item < accordionElements.length; item++ ) {
const questionButtons = accordionElements[ item ].querySelectorAll( '.uagb-faq-questions-button' );
const faqItems = accordionElements[ item ].querySelectorAll( '.uagb-faq-item' );
for ( let button = 0; button < questionButtons.length; button++ ) {
questionButtons[ button ].addEventListener( 'click', function ( e ) {
faqClick( e, this.parentElement, questionButtons );
} );
}
for ( let button = 0; button < faqItems.length; button++ ) {
faqItems[ button ].addEventListener( 'keyup', function ( e ) {
faqClick( e, this, questionButtons );
} );
}
}
} );
function faqClick( e, faqItem, questionButtons ) {
if ( e.keyCode === 13 || e.keyCode === 32 || e.button === 0 ) {
// enter || spacebar || left mouse click.
if ( faqItem.classList.contains( 'uagb-faq-item-active' ) ) {
faqItem.classList.remove( 'uagb-faq-item-active' );
faqItem.setAttribute( 'aria-expanded', false );
slideUp( faqItem.getElementsByClassName( 'uagb-faq-content' )[ 0 ], 500 );
} else {
const parent = e.currentTarget.closest( '.wp-block-uagb-faq' );
let faqToggle = 'true';
if ( parent.classList.contains( 'wp-block-uagb-faq' ) ) {
faqToggle = parent.getAttribute( 'data-faqtoggle' );
}
faqItem.classList.add( 'uagb-faq-item-active' );
faqItem.setAttribute( 'aria-expanded', true );
slideDown( faqItem.getElementsByClassName( 'uagb-faq-content' )[ 0 ], 500 );
if ( 'true' === faqToggle ) {
questionButtons = parent.querySelectorAll( '.uagb-faq-content' );
for ( let buttonChild = 0; buttonChild < questionButtons.length; buttonChild++ ) {
const buttonItem = questionButtons[ buttonChild ].parentElement;
if ( buttonItem === faqItem ) {
continue;
}
buttonItem.classList.remove( 'uagb-faq-item-active' );
buttonItem.setAttribute( 'aria-expanded', false );
slideUp( buttonItem.getElementsByClassName( 'uagb-faq-content' )[ 0 ], 500 );
}
}
}
}
}

View File

@@ -0,0 +1 @@
function slideUp(e,t){e.style.transitionProperty="height, margin, padding",e.style.transitionDuration=t+"ms",e.style.boxSizing="border-box",e.style.height=e.offsetHeight+"px",e.offsetHeight,e.style.overflow="hidden",e.style.height=0,e.style.paddingTop=0,e.style.paddingBottom=0,e.style.marginTop=0,e.style.marginBottom=0,window.setTimeout(function(){e.style.display="none",e.style.removeProperty("height"),e.style.removeProperty("padding-top"),e.style.removeProperty("padding-bottom"),e.style.removeProperty("margin-top"),e.style.removeProperty("margin-bottom"),e.style.removeProperty("overflow"),e.style.removeProperty("transition-duration"),e.style.removeProperty("transition-property")},t)}function slideDown(e,t){e.style.removeProperty("display");let o=window.getComputedStyle(e).display;"none"===o&&(o="block"),e.style.display=o;var a=e.offsetHeight;e.style.overflow="hidden",e.style.height=0,e.style.paddingTop=0,e.style.paddingBottom=0,e.style.marginTop=0,e.style.marginBottom=0,e.offsetHeight,e.style.boxSizing="border-box",e.style.transitionProperty="height, margin, padding",e.style.transitionDuration=t+"ms",e.style.height=a+"px",e.style.removeProperty("padding-top"),e.style.removeProperty("padding-bottom"),e.style.removeProperty("margin-top"),e.style.removeProperty("margin-bottom"),window.setTimeout(function(){e.style.removeProperty("height"),e.style.removeProperty("overflow"),e.style.removeProperty("transition-duration"),e.style.removeProperty("transition-property")},t)}function setupFAQ(){const e=new RegExp("^[\\w\\-]+$");var t=window.location.hash.substring(1);const o=document.getElementsByClassName("uagb-faq-expand-first-true"),a=document.getElementsByClassName("uagb-faq-inactive-other-false");if(void 0!==document.getElementById(t)&&null!==document.getElementById(t)&&""!==document.getElementById(t)&&e.test(t)){const i=document.getElementById(t);void 0!==i&&(i.classList.add("uagb-faq-item-active"),i.setAttribute("aria-expanded",!0),(t=i.getElementsByClassName("uagb-faq-content")[0])&&slideDown(t,500))}else for(let t=0;t<o.length;t++)if(!0===o[t].classList.contains("uagb-faq-layout-accordion")){let e=o[t].querySelectorAll(".uagb-faq-child__outer-wrap.uagb-faq-item")[0];(e=e||o[t].querySelectorAll(".uagb-faq-child__outer-wrap .uagb-faq-item")[0]).classList.add("uagb-faq-item-active"),e.setAttribute("aria-expanded",!0),e.querySelectorAll(".uagb-faq-content")[0].style.display="block"}for(let e=0;e<a.length;e++)if(!0===a[e].classList.contains("uagb-faq-layout-accordion")){let t=a[e].querySelectorAll(".uagb-faq-child__outer-wrap.uagb-faq-item");t&&0!==t.length||(t=a[e].querySelectorAll(".uagb-faq-child__outer-wrap .uagb-faq-item"));for(let e=0;e<t.length;e++)t[e].classList.add("uagb-faq-item-active"),t[e].setAttribute("aria-expanded",!0),t[e].querySelectorAll(".uagb-faq-content")[0].style.display="block"}}function faqClick(t,o,a){if(13===t.keyCode||32===t.keyCode||0===t.button)if(o.classList.contains("uagb-faq-item-active"))o.classList.remove("uagb-faq-item-active"),o.setAttribute("aria-expanded",!1),slideUp(o.getElementsByClassName("uagb-faq-content")[0],500);else{const i=t.currentTarget.closest(".wp-block-uagb-faq");let e="true";if(i.classList.contains("wp-block-uagb-faq")&&(e=i.getAttribute("data-faqtoggle")),o.classList.add("uagb-faq-item-active"),o.setAttribute("aria-expanded",!0),slideDown(o.getElementsByClassName("uagb-faq-content")[0],500),"true"===e){a=i.querySelectorAll(".uagb-faq-content");for(let e=0;e<a.length;e++){const l=a[e].parentElement;l!==o&&(l.classList.remove("uagb-faq-item-active"),l.setAttribute("aria-expanded",!1),slideUp(l.getElementsByClassName("uagb-faq-content")[0],500))}}}}window.addEventListener("load",function(){setupFAQ();const t=document.getElementsByClassName("uagb-faq-layout-accordion");for(let e=0;e<t.length;e++){const o=t[e].querySelectorAll(".uagb-faq-questions-button"),a=t[e].querySelectorAll(".uagb-faq-item");for(let e=0;e<o.length;e++)o[e].addEventListener("click",function(e){faqClick(e,this.parentElement,o)});for(let e=0;e<a.length;e++)a[e].addEventListener("keyup",function(e){faqClick(e,this,o)})}});

View File

@@ -0,0 +1,319 @@
UAGBForms = {
getElement: ( id ) => {
// Check if the script has run once already on the given element (required for homepage sidebar usage case).
const getJsELement = document.querySelector( `${ id }:not(.uagb-activated-script)` );
if ( ! getJsELement ) return null;
// Ensures that the script only runs once on the given element (required for homepage sidebar usage case).
getJsELement.classList.add( 'uagb-activated-script' );
return getJsELement;
},
init( attr, id, post_id ) {
const scope = UAGBForms.getElement( id );
if ( ! scope ) {
return;
}
const form = scope.querySelector( '.uagb-forms-main-form' );
const phoneinput = form.querySelectorAll( '.uagb-forms-phone-input' );
if ( phoneinput.length !== 0 ) {
for ( let i = 0; i < phoneinput.length; i++ ) {
phoneinput[ i ].addEventListener( 'keypress', function ( e ) {
const charCode = e.which ? e.which : e.keyCode;
if ( charCode === 45 ) {
return true;
}
if ( charCode > 31 && ( charCode < 48 || charCode > 57 ) ) {
return false;
}
return true;
} );
}
}
const toggleinput = form.querySelectorAll( '.uagb-forms-toggle-input' );
if ( toggleinput.length !== 0 ) {
for ( let j = 0; j < toggleinput.length; j++ ) {
toggleinput[ j ].addEventListener( 'change', function () {
if ( toggleinput[ j ].checked ) {
const truestate = toggleinput[ j ].getAttribute( 'data-truestate' );
toggleinput[ j ].setAttribute( 'value', truestate );
} else {
const falsestate = toggleinput[ j ].getAttribute( 'data-falsestate' );
toggleinput[ j ].setAttribute( 'value', falsestate );
}
} );
}
}
// validation for checkbox if required.
const requiredCheckboxes = scope.querySelectorAll( '.uagb-forms-checkbox-wrap' );
if ( requiredCheckboxes.length !== 0 ) {
for ( let k = 0; k < requiredCheckboxes.length; k++ ) {
const checkboxes = requiredCheckboxes[ k ].querySelectorAll( 'input[type=checkbox]' );
if ( checkboxes.length > 0 ) {
for ( let l = 0; l < checkboxes.length; l++ ) {
checkboxes[ l ].addEventListener( 'change', function () {
const isChecked = checkboxes[ l ].checked;
const name = checkboxes[ l ].getAttribute( 'name' );
const check = document.querySelectorAll( '[name="' + name + '"]' );
for ( let i = 0; i < check.length; i++ ) {
if ( isChecked ) {
check[ i ].required = false;
} else {
check[ i ].required = true;
}
}
} );
}
}
}
}
let reCaptchaSiteKeyV2 = '',
reCaptchaSiteKeyV3 = '';
//append recaptcha js when enabled.
if ( attr.reCaptchaEnable === true && attr.reCaptchaType === 'v2' ) {
reCaptchaSiteKeyV2 = uagb_forms_data.recaptcha_site_key_v2;
if ( reCaptchaSiteKeyV2 ) {
if ( null === document.querySelector( '.uagb-forms-field-set' ).getAttribute( 'data-sitekey' ) ) {
document.querySelector( '.g-recaptcha ' ).setAttribute( 'data-sitekey', reCaptchaSiteKeyV2 );
}
const recaptchaLink = document.createElement( 'script' );
recaptchaLink.type = 'text/javascript';
recaptchaLink.src = 'https://www.google.com/recaptcha/api.js';
document.head.appendChild( recaptchaLink );
}
} else if ( attr.reCaptchaEnable === true && attr.reCaptchaType === 'v3' ) {
reCaptchaSiteKeyV3 = uagb_forms_data.recaptcha_site_key_v3;
if ( reCaptchaSiteKeyV3 ) {
if ( attr.hidereCaptchaBatch ) {
setTimeout( function(){
const badge = document.getElementsByClassName( 'grecaptcha-badge' )[0];
if( badge ){
badge.style.visibility = 'hidden';
}
}, 500 );
}
const api = document.createElement( 'script' );
api.type = 'text/javascript';
api.src = 'https://www.google.com/recaptcha/api.js?render=' + reCaptchaSiteKeyV3;
document.head.appendChild( api );
}
}
//Ready Classes.
const formscope = document.getElementsByClassName( 'uagb-block-' + attr.block_id );
if ( formscope?.[ 0 ] ) {
const formWrapper = formscope[ 0 ].children;
const sibling = formWrapper[ 0 ].children;
for ( let index = 0; index < sibling.length; index++ ) {
if (
sibling[ index ].classList.contains( 'uag-col-2' ) &&
sibling[ index + 1 ].classList.contains( 'uag-col-2' )
) {
const div = document.createElement( 'div' );
div.className = 'uag-col-2-wrap uag-col-wrap-' + index;
sibling[ index + 1 ].after( div );
const wrapper_div = formscope[ 0 ].getElementsByClassName( 'uag-col-wrap-' + index );
wrapper_div[ 0 ].appendChild( sibling[ index ] );
wrapper_div[ 0 ].appendChild( sibling[ index ] );
}
if (
sibling[ index ].classList.contains( 'uag-col-3' ) &&
sibling[ index + 1 ].classList.contains( 'uag-col-3' ) &&
sibling[ index + 2 ].classList.contains( 'uag-col-3' )
) {
const div = document.createElement( 'div' );
div.className = 'uag-col-3-wrap uag-col-wrap-' + index;
sibling[ index + 2 ].after( div );
const wrapper_div = formscope[ 0 ].getElementsByClassName( 'uag-col-wrap-' + index );
wrapper_div[ 0 ].appendChild( sibling[ index ] );
wrapper_div[ 0 ].appendChild( sibling[ index ] );
wrapper_div[ 0 ].appendChild( sibling[ index ] );
}
if (
sibling[ index ].classList.contains( 'uag-col-4' ) &&
sibling[ index + 1 ].classList.contains( 'uag-col-4' ) &&
sibling[ index + 2 ].classList.contains( 'uag-col-4' ) &&
sibling[ index + 3 ].classList.contains( 'uag-col-4' )
) {
const div = document.createElement( 'div' );
div.className = 'uag-col-4-wrap uag-col-wrap-' + index;
sibling[ index + 3 ].after( div );
const wrapper_div = formscope[ 0 ].getElementsByClassName( 'uag-col-wrap-' + index );
wrapper_div[ 0 ].appendChild( sibling[ index ] );
wrapper_div[ 0 ].appendChild( sibling[ index ] );
wrapper_div[ 0 ].appendChild( sibling[ index ] );
wrapper_div[ 0 ].appendChild( sibling[ index ] );
}
}
}
form.addEventListener( 'submit', function ( e ) {
e.preventDefault();
if ( attr.reCaptchaEnable === true && attr.reCaptchaType === 'v3' && reCaptchaSiteKeyV3 ) {
if ( document.getElementsByClassName( 'grecaptcha-logo' ).length === 0 ) {
document.querySelector( '.uagb-form-reacaptcha-error-' + attr.block_id ).innerHTML =
'<p style="color:red !important" class="error-captcha">Invalid Google reCAPTCHA Site Key.</p>';
return false;
}
// eslint-disable-next-line no-undef
grecaptcha.ready( function () {
// eslint-disable-next-line no-undef
grecaptcha.execute( reCaptchaSiteKeyV3, { action: 'submit' } ).then( function ( token ) {
if ( token ) {
if ( document.getElementsByClassName( 'uagb-forms-recaptcha' ).length !== 0 ) {
document.getElementById( 'g-recaptcha-response' ).value = token;
window.UAGBForms._formSubmit(
e,
form,
attr,
reCaptchaSiteKeyV2,
reCaptchaSiteKeyV3,
post_id
);
} else {
document.querySelector( '.uagb-form-reacaptcha-error-' + attr.block_id ).innerHTML =
'<p style="color:red !important" class="error-captcha">Google reCAPTCHA Response not found.</p>';
return false;
}
}
} );
} );
} else {
window.UAGBForms._formSubmit( e, this, attr, reCaptchaSiteKeyV2, reCaptchaSiteKeyV3, post_id );
}
} );
},
_formSubmit( e, form, attr, reCaptchaSiteKeyV2, reCaptchaSiteKeyV3, post_id ) {
e.preventDefault();
let captcha_response;
if ( '' === attr.afterSubmitToEmail || null === attr.afterSubmitToEmail ) {
const hideForm = document.querySelector( '[name="uagb-form-' + attr.block_id + '"]' );
hideForm.style.display = 'none';
const errorMsg = document.querySelector( '.uagb-forms-failed-message-' + attr.block_id );
errorMsg?.classList?.remove( 'uagb-forms-submit-message-hide' );
errorMsg?.classList?.add( 'uagb-forms-failed-message' );
return false;
}
if ( attr.reCaptchaEnable === true ) {
if ( attr.reCaptchaType === 'v2' && reCaptchaSiteKeyV2 ) {
if ( document.getElementsByClassName( 'uagb-forms-recaptcha' ).length !== 0 ) {
captcha_response = document.getElementById( 'g-recaptcha-response' ).value;
if ( ! captcha_response ) {
document.querySelector( '.uagb-form-reacaptcha-error-' + attr.block_id ).innerHTML =
'<p style="color:red !important" class="error-captcha">' + attr.captchaMessage + '</p>';
return false;
}
document.querySelector( '.uagb-form-reacaptcha-error-' + attr.block_id ).innerHTML = '';
} else {
document.querySelector( '.uagb-form-reacaptcha-error-' + attr.block_id ).innerHTML =
'<p style="color:red !important" class="error-captcha"> Google reCAPTCHA Response not found.</p>';
return false;
}
} else if ( attr.reCaptchaType === 'v3' && reCaptchaSiteKeyV3 ) {
captcha_response = document.getElementById( 'g-recaptcha-response' ).value;
}
}
const originalSerialized = window.UAGBForms._serializeIt( form );
const postData = {};
postData.id = attr.block_id;
for ( let i = 0; i < originalSerialized.length; i++ ) {
const inputname = document.getElementById( originalSerialized[ i ].name );
if ( originalSerialized[ i ].name.endsWith( '[]' ) ) {
const name = originalSerialized[ i ].name.replace( /[\[\]']+/g, '' );
//For checkbox element
if ( ! ( name in postData ) ) {
postData[ name ] = [];
}
postData[ name ].push( originalSerialized[ i ].value );
} else if ( inputname !== null ) {
postData[ inputname.innerHTML ] = originalSerialized[ i ].value;
}
const hiddenField = document.getElementById( 'hidden' );
if ( hiddenField !== null && hiddenField !== undefined ) {
postData[ hiddenField.getAttribute( 'name' ) ] = hiddenField.getAttribute( 'value' );
}
}
// eslint-disable-next-line no-undef
fetch( uagb_forms_data.ajax_url, {
method: 'POST',
headers: new Headers( { 'Content-Type': 'application/x-www-form-urlencoded' } ), // eslint-disable-line no-undef
body: new URLSearchParams( {
action: 'uagb_process_forms',
nonce: uagb_forms_data.uagb_forms_ajax_nonce,
form_data: JSON.stringify( postData ),
sendAfterSubmitEmail: attr.sendAfterSubmitEmail,
captcha_version: attr.reCaptchaType,
captcha_response,
post_id,
block_id: attr.block_id,
} ),
} )
.then( ( resp ) => resp.json() )
.then( function ( data ) {
const hideForm = document.querySelector( '[name="uagb-form-' + attr.block_id + '"]' );
hideForm.style.display = 'none';
if ( 200 === data.data ) {
if ( 'message' === attr.confirmationType ) {
const errorMsg = document.querySelector( '.uagb-forms-success-message-' + attr.block_id );
errorMsg.classList.remove( 'uagb-forms-submit-message-hide' );
errorMsg.classList.add( 'uagb-forms-success-message' );
}
if ( 'url' === attr.confirmationType ) {
window.location.replace( attr.confirmationUrl );
}
} else if ( 400 === data.data ) {
if ( 'message' === attr.confirmationType ) {
const successMsg = document.querySelector( '.uagb-forms-failed-message-' + attr.block_id );
successMsg.classList.remove( 'uagb-forms-submit-message-hide' );
successMsg.classList.add( 'uagb-forms-failed-message' );
}
}
} )
.catch( function ( error ) {
console.log( JSON.stringify( error ) ); // eslint-disable-line no-console
} );
},
_serializeIt( form ) {
return Array.apply( 0, form.elements )
.map( ( x ) =>
( ( obj ) =>
// eslint-disable-next-line no-nested-ternary
x.type === 'radio' || x.type === 'checkbox' ? ( x.checked ? obj : null ) : obj )( {
name: x.name,
value: x.value,
} )
)
.filter( ( x ) => x );
},
};

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,589 @@
let spectraImageGalleryLoadStatus = true;
let clickedImageId = null;
const UAGBImageGalleryMasonry = {
initByOffset( $selector, instance ){
// Verify $selector and instance.
if ( ! $selector || ! instance ) {
return;
}
// Add class for scroll not init.
$selector.classList.add( 'scroll-not-init' );
// Add class for last image not loaded.
$selector.classList.add( 'last-image-not-loaded' );
const getAllImages = $selector.querySelectorAll( 'img' );
if( getAllImages.length ){
// Get last image.
const getLastImage = getAllImages[ getAllImages.length - 1 ];
// Add event listener for last image.
getLastImage.addEventListener( 'load', () => {
// You can perform additional actions here once the image has loaded.
// Remove class for last image not loaded.
$selector.classList.remove( 'last-image-not-loaded' );
setTimeout( function() {
instance.layout();
}, 100 );
}
);
}
let timeOutInstance = null;
// Get scroll position dynamically.
window.addEventListener( 'scroll', function() {
if ( ! $selector.classList.contains( 'scroll-not-init' ) ) {
return;
}
// Clear timeout instance.
clearTimeout( timeOutInstance );
if ( UAGBImageGalleryMasonry.presentInViewport( $selector ) ) {
// If $selector comes in view port then init masonry.
$selector.classList.remove( 'scroll-not-init' );
// Init masonry.
timeOutInstance = setTimeout( function() {
instance.layout();
}, 100 );
}
} );
},
init( $attr, $selector, lightboxSettings, thumbnailSettings ) {
let count = 2;
const windowHeight50 = window.innerHeight / 1.25;
const $scope = document.querySelector( $selector );
let thumbnailSwiper = null;
if ( $attr.lightboxThumbnails ) {
thumbnailSwiper = new Swiper( `${$selector}+.spectra-image-gallery__control-lightbox .spectra-image-gallery__control-lightbox--thumbnails`,
thumbnailSettings
);
lightboxSettings = {
...lightboxSettings,
thumbs: {
swiper: thumbnailSwiper,
},
}
}
const lightboxSwiper = new Swiper( `${$selector}+.spectra-image-gallery__control-lightbox .spectra-image-gallery__control-lightbox--main`,
lightboxSettings
)
lightboxSwiper.lazy.load();
loadLightBoxImages( $scope, lightboxSwiper, null, $attr, thumbnailSwiper );
const loader = $scope?.querySelector( '.spectra-image-gallery__control-loader' );
const loadButton = $scope?.querySelector( '.spectra-image-gallery__control-button' );
if ( $attr.feedPagination && $attr.paginateUseLoader ) {
window.addEventListener( 'scroll', function () {
let mediaItem = $scope?.querySelector( '.spectra-image-gallery__media-wrapper' );
if ( ! mediaItem ) {
mediaItem = $scope;
}
const boundingClientRect = mediaItem.lastElementChild.getBoundingClientRect();
const offsetTop = boundingClientRect.top + window.scrollY;
if ( window.pageYOffset + windowHeight50 >= offsetTop ) {
const $args = {
page_number: count,
};
const total = $attr.gridPages;
if ( spectraImageGalleryLoadStatus ) {
if ( count > total ) {
loader.style.display = 'none';
}
if ( count <= total ) {
UAGBImageGalleryMasonry.callAjax( $scope, $args, $attr, false, count, $selector, lightboxSwiper, thumbnailSwiper );
count++;
spectraImageGalleryLoadStatus = false;
}
}
}
} );
} else if ( $attr.feedPagination && ! $attr.paginateUseLoader ) {
loadButton.onclick = function () {
const total = $attr.gridPages;
const $args = {
total,
page_number: count,
};
loadButton.classList.add( 'disabled' );
if ( spectraImageGalleryLoadStatus ) {
if ( count <= total ) {
UAGBImageGalleryMasonry.callAjax( $scope, $args, $attr, false, count, $selector, lightboxSwiper, thumbnailSwiper );
count++;
spectraImageGalleryLoadStatus = false;
}
}
};
}
},
createElementFromHTML( htmlString ) {
const htmlElement = document.createElement( 'div' );
const htmlCleanString = htmlString.replace( /\s+/gm, ' ' ).replace( /( )+/gm, ' ' ).trim();
htmlElement.innerHTML = htmlCleanString;
return htmlElement;
},
getCustomURL( image, $attr ) {
const urlValidRegex = new RegExp(
'^((http|https)://)(www.)?[a-zA-Z0-9@:%._\\+~#?&//=]{2,256}\\.[a-z]{2,6}\\b([-a-zA-Z0-9@:%._\\+~#?&//=]*)$'
);
const imageID = parseInt( image.getAttribute( 'data-spectra-gallery-image-id' ) );
return urlValidRegex.test( $attr?.customLinks[ imageID ] ) ? $attr.customLinks[ imageID ] : undefined;
},
openCustomURL( customURL ) {
window.open( customURL, '_blank' );
},
addClickEvents( element, $attr ) {
const imageElements = element?.querySelectorAll( '.spectra-image-gallery__media-wrapper' );
imageElements.forEach( ( image ) => {
const imageURL = UAGBImageGalleryMasonry.getCustomURL( image, $attr );
if ( imageURL ) {
image.style.cursor = 'pointer';
image.addEventListener( 'click', () => UAGBImageGalleryMasonry.openCustomURL( imageURL ) );
image.addEventListener( 'keydown', ( event ) => {
if ( 13 === event.keyCode || 32 === event.keyCode ) {
event.preventDefault();
UAGBImageGalleryMasonry.openCustomURL( imageURL );
}
} );
}
} );
},
callAjax( $scope, $obj, $attr, append = false, count, $selector, lightboxSwiper, thumbnailSwiper ) {
const mediaData = new FormData();
mediaData.append( 'action', 'uag_load_image_gallery_masonry' );
mediaData.append( 'nonce', uagb_image_gallery.uagb_image_gallery_masonry_ajax_nonce );
mediaData.append( 'page_number', $obj.page_number );
mediaData.append( 'attr', JSON.stringify( $attr ) );
fetch( uagb_image_gallery.ajax_url, {
method: 'POST',
credentials: 'same-origin',
body: mediaData,
} )
.then( ( resp ) => resp.json() )
.then( function ( data ) {
let element = $scope?.querySelector( '.spectra-image-gallery__layout--masonry' );
if ( ! element ) {
element = $scope;
}
setTimeout( function () {
const isotope = new Isotope( element, {
itemSelector: '.spectra-image-gallery__media-wrapper--isotope',
stagger: 10,
} );
isotope.insert( UAGBImageGalleryMasonry.createElementFromHTML( data.data ) );
imagesLoaded( element ).on( 'progress', function () {
isotope.layout();
} );
imagesLoaded( element ).on( 'always', function () {
const currentScope = document.querySelector( $selector );
const loadButton = currentScope?.querySelector( '.spectra-image-gallery__control-button' )
loadButton?.classList?.remove( 'disabled' );
loadLightBoxImages( currentScope, lightboxSwiper, null, $attr, thumbnailSwiper );
} );
if ( 'url' === $attr.imageClickEvent && $attr.customLinks ) {
UAGBImageGalleryMasonry.addClickEvents( element, $attr );
}
spectraImageGalleryLoadStatus = true;
if ( true === append ) {
$scope?.querySelector( '.spectra-image-gallery__control-button' ).classList.toggle( 'disabled' );
}
if ( count === parseInt( $obj.total ) ) {
$scope.querySelector( '.spectra-image-gallery__control-button' ).style.opacity = 0;
setTimeout( () => {
$scope.querySelector( '.spectra-image-gallery__control-button' ).parentElement.style.display =
'none';
}, 2000 );
}
}, 500 );
} );
},
presentInViewport( element ) {
const rect = element.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= ( window.innerHeight || document.documentElement.clientHeight ) &&
rect.right <= ( window.innerWidth || document.documentElement.clientWidth )
);
},
};
const UAGBImageGalleryPagedGrid = {
init( $attr, $selector, lightboxSettings, thumbnailSettings ) {
let count = 1;
const $scope = document.querySelector( $selector );
let thumbnailSwiper = null;
if ( $attr.lightboxThumbnails ){
thumbnailSwiper = new Swiper( `${$selector}+.spectra-image-gallery__control-lightbox .spectra-image-gallery__control-lightbox--thumbnails`,
thumbnailSettings
);
lightboxSettings = {
...lightboxSettings,
thumbs: {
swiper: thumbnailSwiper,
},
}
}
const lightboxSwiper = new Swiper( `${$selector}+.spectra-image-gallery__control-lightbox .spectra-image-gallery__control-lightbox--main`,
lightboxSettings
)
lightboxSwiper.lazy.load();
loadLightBoxImages( $scope, lightboxSwiper, count, $attr, thumbnailSwiper );
const arrows = $scope?.querySelectorAll( '.spectra-image-gallery__control-arrows--grid' );
const dots = $scope?.querySelectorAll( '.spectra-image-gallery__control-dot' );
for ( let i = 0; i < arrows.length; i++ ) {
arrows[ i ].addEventListener( 'click', ( event ) => {
const thisArrow = event.currentTarget;
let page = count;
switch ( thisArrow.getAttribute( 'data-direction' ) ) {
case 'Prev':
--page;
break;
case 'Next':
++page;
break;
}
let mediaItem = $scope?.querySelector( '.spectra-image-gallery__media-wrapper' );
if ( ! mediaItem ) {
mediaItem = $scope;
}
const total = $attr.gridPages;
const $args = {
page_number: page,
total,
};
if ( page === total || page === 1 ) {
thisArrow.disabled = true;
} else {
arrows.forEach( ( ele ) => {
ele.disabled = false;
} );
}
if ( page <= total && page >= 1 ) {
UAGBImageGalleryPagedGrid.callAjax( $scope, $args, $attr, arrows, $selector, lightboxSwiper, thumbnailSwiper );
count = page;
}
} );
}
for ( let i = 0; i < dots.length; i++ ) {
dots[ i ].addEventListener( 'click', ( event ) => {
const thisDot = event.currentTarget;
const page = thisDot.getAttribute( 'data-go-to' );
let mediaItem = $scope?.querySelector( '.spectra-image-gallery__media-wrapper' );
if ( ! mediaItem ) {
mediaItem = $scope;
}
const $args = {
page_number: page,
total: $attr.gridPages,
};
UAGBImageGalleryPagedGrid.callAjax( $scope, $args, $attr, arrows, $selector, lightboxSwiper, thumbnailSwiper );
count = page;
} );
}
},
createElementFromHTML( htmlString ) {
const htmlElement = document.createElement( 'div' );
const htmlCleanString = htmlString.replace( /\s+/gm, ' ' ).replace( /( )+/gm, ' ' ).trim();
htmlElement.innerHTML = htmlCleanString;
return htmlElement;
},
getCustomURL( image, $attr ) {
const urlValidRegex = new RegExp(
'^((http|https)://)(www.)?[a-zA-Z0-9@:%._\\+~#?&//=\\-]{2,256}\\.[a-z]{2,6}\\b([-a-zA-Z0-9@:%._\\+~#?&//=]*)$'
);
const imageID = parseInt( image.getAttribute( 'data-spectra-gallery-image-id' ) );
return urlValidRegex.test( $attr?.customLinks[ imageID ] ) ? $attr.customLinks[ imageID ] : undefined;
},
openCustomURL( customURL ) {
window.open( customURL, '_blank' );
},
addClickEvents( element, $attr ) {
const imageElements = element?.querySelectorAll( '.spectra-image-gallery__media-wrapper' );
imageElements.forEach( ( image ) => {
const imageURL = UAGBImageGalleryPagedGrid.getCustomURL( image, $attr );
if ( imageURL ) {
image.style.cursor = 'pointer';
image.setAttribute( 'tabindex', '0' );
image.addEventListener( 'click', () => UAGBImageGalleryPagedGrid.openCustomURL( imageURL ) );
image.addEventListener( 'keydown', ( event ) => {
if ( 13 === event.keyCode || 32 === event.keyCode ) {
UAGBImageGalleryPagedGrid.openCustomURL( imageURL );
}
} );
}
} );
},
callAjax( $scope, $obj, $attr, arrows, $selector, lightboxSwiper, thumbnailSwiper ) {
const mediaData = new FormData();
mediaData.append( 'action', 'uag_load_image_gallery_grid_pagination' );
mediaData.append( 'nonce', uagb_image_gallery.uagb_image_gallery_grid_pagination_ajax_nonce );
mediaData.append( 'page_number', $obj.page_number );
mediaData.append( 'attr', JSON.stringify( $attr ) );
fetch( uagb_image_gallery.ajax_url, {
method: 'POST',
credentials: 'same-origin',
body: mediaData,
} )
.then( ( resp ) => resp.json() )
.then( function ( data ) {
if ( data.success === false ) {
return;
}
setTimeout( function () {
let element = $scope?.querySelector( '.spectra-image-gallery__layout--isogrid' );
if ( ! element ) {
element = $scope;
}
const mediaElements = element.querySelectorAll( '.spectra-image-gallery__media-wrapper--isotope' );
const isotope = new Isotope( element, {
itemSelector: '.spectra-image-gallery__media-wrapper--isotope',
layoutMode: 'fitRows',
} );
mediaElements.forEach( ( mediaEle ) => {
isotope.remove( mediaEle );
isotope.layout();
} );
isotope.insert( UAGBImageGalleryPagedGrid.createElementFromHTML( data.data ) );
imagesLoaded( element ).on( 'progress', function () {
isotope.layout();
} );
imagesLoaded( element ).on( 'always', function () {
const currentScope = document.querySelector( $selector );
loadLightBoxImages( currentScope, lightboxSwiper, parseInt( $obj.page_number ), $attr, thumbnailSwiper );
} );
if ( $attr.customLinks ) {
UAGBImageGalleryPagedGrid.addClickEvents( element, $attr );
}
if ( parseInt( $obj.page_number ) === 1 ) {
arrows.forEach( ( arrow ) => {
arrow.disabled = arrow.getAttribute( 'data-direction' ) === 'Prev';
} );
} else if ( parseInt( $obj.page_number ) === parseInt( $obj.total ) ) {
arrows.forEach( ( arrow ) => {
arrow.disabled = arrow.getAttribute( 'data-direction' ) === 'Next';
} );
} else {
arrows.forEach( ( arrow ) => {
arrow.disabled = false;
} );
}
$scope
?.querySelector( '.spectra-image-gallery__control-dot--active' )
.classList.toggle( 'spectra-image-gallery__control-dot--active' );
const $activeDot = $scope?.querySelectorAll( '.spectra-image-gallery__control-dot' );
$activeDot[ parseInt( $obj.page_number ) - 1 ].classList.toggle(
'spectra-image-gallery__control-dot--active'
);
}, 500 );
} );
},
};
const cycleInLightbox = ( selector, e ) => {
// Check if Tab key was pressed
if ( e.key === 'Tab' ) {
const focusableElements = selector.querySelectorAll( 'button, div[data-role="button"], [href], [tabindex]:not([tabindex="-1"])' );
const firstFocusableElement = focusableElements[0];
const lastFocusableElement = focusableElements[focusableElements.length - 1];
// Get the active element using ownerDocument
const activeElement = e.target.ownerDocument.activeElement;
// Check if Shift + Tab was pressed and if the current active element is the first one
if ( e.shiftKey && activeElement === firstFocusableElement ) {
e.preventDefault();
lastFocusableElement.focus();
}
// Check if Tab was pressed and if the current active element is the last one
else if ( !e.shiftKey && activeElement === lastFocusableElement ) {
e.preventDefault();
firstFocusableElement.focus();
}
}
}
const loadLightBoxImages = ( blockScope, lightboxSwiper, pageNum, attr, thumbnailSwiper ) => {
if ( ! blockScope ) {
return;
}
const pageLimit = attr.paginateLimit;
const theBody = document.querySelector( 'body' );
const updateCounter = ( curPage ) => {
const lightbox = blockScope?.nextElementSibling;
const counter = lightbox.querySelector( '.spectra-image-gallery__control-lightbox--count-page' );
if ( counter ) {
counter.innerHTML = parseInt( curPage ) + 1;
}
};
lightboxSwiper.on( 'activeIndexChange', ( swiperInstance ) => {
if ( attr.lightboxThumbnails ) {
thumbnailSwiper.slideTo( swiperInstance.activeIndex );
}
if ( attr.lightboxDisplayCount ) {
updateCounter( swiperInstance.activeIndex );
}
lightboxSwiper.lazy.load();
} )
if ( attr.lightboxThumbnails ) {
thumbnailSwiper.on( 'activeIndexChange', ( swiperInstance ) => {
lightboxSwiper.slideTo( swiperInstance.activeIndex );
} );
}
const lightbox = blockScope?.nextElementSibling;
let lightboxHandlers = {};
if ( lightbox && lightbox?.classList.contains( 'spectra-image-gallery__control-lightbox' ) ) {
// create a lightbox cycle listeners.
const createListeners = () => {
const cycleInLightboxWithID = cycleInLightbox.bind( null, lightbox );
// Function to add the event listener
function addEventListener() {
lightbox.addEventListener( 'keydown', cycleInLightboxWithID );
}
// Function to remove the event listener
function removeEventListener() {
lightbox.removeEventListener( 'keydown', cycleInLightboxWithID );
}
return { addEventListener, removeEventListener };
};
lightboxHandlers = createListeners();
lightbox.addEventListener( 'keydown', ( event ) => {
if ( 27 === event.keyCode ) {
theBody.style.overflow = '';
lightbox.style.opacity = 0;
setTimeout( () => {
lightbox.style.display = 'none';
lightboxHandlers.removeEventListener();
if ( clickedImageId ) {
const clickedImage = document.querySelector( `[data-spectra-gallery-image-id="${clickedImageId}"]` );
clickedImage?.focus();
clickedImageId = null;
}
}, 250 );
}
} );
lightbox.style.display = 'none';
if ( attr.lightboxCloseIcon ) {
const closeButton = lightbox.querySelector( '.spectra-image-gallery__control-lightbox--close' );
if ( closeButton ) {
closeButton.addEventListener( 'click', () => {
theBody.style.overflow = '';
lightbox.style.opacity = 0;
setTimeout( () => {
lightbox.style.display = 'none';
if ( clickedImageId ) {
const clickedImage = document.querySelector( `[data-spectra-gallery-image-id="${clickedImageId}"]` );
clickedImage?.focus();
clickedImageId = null;
}
lightboxHandlers.removeEventListener();
}, 250 );
} );
}
}
if ( attr.lightboxDisplayCount ) {
const lightboxTotal = lightbox.querySelector( '.spectra-image-gallery__control-lightbox--count-total' );
lightboxTotal.innerHTML = attr.mediaGallery.length;
}
}
const enableLightbox = ( goTo, clickedImage ) => {
if ( ! lightboxSwiper || !lightbox ) {
return;
}
clickedImageId = clickedImage.getAttribute( 'data-spectra-gallery-image-id' );
lightbox.style.display = '';
lightbox.focus();
setTimeout( () => {
lightboxSwiper.slideTo( goTo );
}, 100 );
setTimeout( () => {
lightbox.style.opacity = 1;
if ( lightbox?.classList.contains( 'spectra-image-gallery__control-lightbox' ) ) {
theBody.style.overflow = 'hidden';
}
lightboxHandlers.addEventListener();
}, 250 );
}
if ( pageNum !== null ) {
setTimeout( () => {
addClickListeners( blockScope, pageNum, enableLightbox, pageLimit, attr );
}, 1000 );
} else {
addClickListeners( blockScope, null, enableLightbox, null, attr );
}
};
const generateUniqueId = ( index ) => `image-${index}-${Date.now()}`;
const addClickListeners = ( $scope, pageNum, enableLightbox, pageLimit, attr ) => {
const images = $scope.querySelectorAll( '.spectra-image-gallery__media-wrapper' );
const imageUrls = {};
if ( 'image' === attr.imageClickEvent ) {
const mediaGallery = attr.mediaGallery;
mediaGallery.forEach( media => {
imageUrls[ media.id ] = media.url;
} );
}
images.forEach( ( image, index ) => {
image.style.cursor = 'pointer';
const uniqueId = generateUniqueId( index );
if( 'lightbox' === attr.imageClickEvent ) {
image.setAttribute( 'data-spectra-gallery-image-id', uniqueId );
};
if ( 'image' === attr.imageClickEvent ) {
const imgId = image.getAttribute( 'data-spectra-gallery-image-id' );
const imgURL = imageUrls[ imgId ];
image.addEventListener( 'click', () => {
openImageInWindow( imgURL ); // To avoid opening multiple tab at same when Popup and redirect is enabled.
} );
image.addEventListener( 'keydown', ( event ) => {
if ( 13 === event.keyCode || 32 === event.keyCode ) {
openImageInWindow( imgURL );
}
} );
} else {
const nextImg = pageNum !== null ? index + ( pageNum - 1 ) * pageLimit : index;
image.addEventListener( 'click', () => enableLightbox( nextImg, image ) );
image.addEventListener( 'keydown', ( event ) => {
if ( 13 === event.keyCode || 32 === event.keyCode ) {
event.preventDefault();
enableLightbox( nextImg, image );
}
} );
}
} );
}
let imageWindow = null;
const openImageInWindow = ( imageUrl ) => {
// Check if the window is already open
if ( imageWindow && !imageWindow.closed ) {
// If open, focus on the existing window
imageWindow.focus();
} else {
// If not open or closed, open a new window
imageWindow = window.open( imageUrl, '_blank' );
}
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,47 @@
// eslint-disable-next-line no-undef
UAGBInlineNotice = {
init( attr, id ) {
const main = document.querySelectorAll( id );
if ( main.length === 0 ) {
return;
}
const uniqueId = attr.c_id;
const isCookie = attr.cookies;
const cookiesDays = attr.close_cookie_days;
const currentCookie = Cookies.get( 'uagb-notice-' + uniqueId );
for ( const mainWrap of main ) {
if ( 'undefined' === typeof currentCookie && true === isCookie ) {
mainWrap.style.display = 'block';
}
const noticeDismissClass = mainWrap.querySelector( '.uagb-notice-dismiss' ) || mainWrap.querySelector( 'svg' );
const closeBtn = noticeDismissClass ? noticeDismissClass : mainWrap.querySelector( 'button[type="button"] svg' );
if ( '' !== attr.noticeDismiss && '' !== attr.icon ) {
closeBtn.addEventListener( 'click', function () {
dismissClick( isCookie, currentCookie, uniqueId, cookiesDays, main );
} );
main[0].addEventListener( 'keydown', function ( e ) {
if ( e.keyCode === 13 || e.keyCode === 32 ) {
const focusedVisibleElement = document.querySelector( id + ' :focus-visible' );
dismissClick( isCookie, currentCookie, uniqueId, cookiesDays, main, focusedVisibleElement );
}
} );
}
}
},
};
function dismissClick( isCookie, currentCookie, uniqueId, cookiesDays, main, focusedVisibleElement ) {
if ( true === isCookie && 'undefined' === typeof currentCookie ) {
Cookies.set( 'uagb-notice-' + uniqueId, true, { expires: cookiesDays } );
}
main[0]?.classList?.add( 'uagb-notice__active' );
if ( focusedVisibleElement ) {
const closeDismiss = focusedVisibleElement?.parentElement;
closeDismiss.style.display = 'none';
} else {
main[0].style.display = 'none';
}
}

View File

@@ -0,0 +1 @@
function dismissClick(e,i,o,s,t,n){if(!0===e&&void 0===i&&Cookies.set("uagb-notice-"+o,!0,{expires:s}),t[0]?.classList?.add("uagb-notice__active"),n){const c=n?.parentElement;c.style.display="none"}else t[0].style.display="none"}UAGBInlineNotice={init(e,i){const o=document.querySelectorAll(i);if(0!==o.length){const t=e.c_id,n=e.cookies,c=e.close_cookie_days,l=Cookies.get("uagb-notice-"+t);for(const d of o){void 0===l&&!0===n&&(d.style.display="block");var s=d.querySelector(".uagb-notice-dismiss")||d.querySelector("svg");const u=s||d.querySelector('button[type="button"] svg');""!==e.noticeDismiss&&""!==e.icon&&(u.addEventListener("click",function(){dismissClick(n,l,t,c,o)}),o[0].addEventListener("keydown",function(e){13!==e.keyCode&&32!==e.keyCode||(e=document.querySelector(i+" :focus-visible"),dismissClick(n,l,t,c,o,e))}))}}}};

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,9 @@
/*!
* JavaScript Cookie v2.2.1
* https://github.com/js-cookie/js-cookie
*
* Copyright 2006, 2015 Klaus Hartl & Fagner Brack
* Released under the MIT license
*/
!function(a){var b;if("function"==typeof define&&define.amd&&(define(a),b=!0),"object"==typeof exports&&(module.exports=a(),b=!0),!b){var c=window.Cookies,d=window.Cookies=a();d.noConflict=function(){return window.Cookies=c,d}}}(function(){function a(){for(var a=0,b={};a<arguments.length;a++){var c=arguments[a];for(var d in c)b[d]=c[d]}return b}function b(a){return a.replace(/(%[0-9A-Z]{2})+/g,decodeURIComponent)}function c(d){function e(){}function f(b,c,f){if("undefined"!=typeof document){f=a({path:"/"},e.defaults,f),"number"==typeof f.expires&&(f.expires=new Date(1*new Date+864e5*f.expires)),f.expires=f.expires?f.expires.toUTCString():"";try{var g=JSON.stringify(c);/^[\{\[]/.test(g)&&(c=g)}catch(j){}c=d.write?d.write(c,b):encodeURIComponent(c+"").replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent),b=encodeURIComponent(b+"").replace(/%(23|24|26|2B|5E|60|7C)/g,decodeURIComponent).replace(/[\(\)]/g,escape);var h="";for(var i in f)f[i]&&(h+="; "+i,!0!==f[i]&&(h+="="+f[i].split(";")[0]));return document.cookie=b+"="+c+h}}function g(a,c){if("undefined"!=typeof document){for(var e={},f=document.cookie?document.cookie.split("; "):[],g=0;g<f.length;g++){var h=f[g].split("="),i=h.slice(1).join("=");c||'"'!==i.charAt(0)||(i=i.slice(1,-1));try{var j=b(h[0]);if(i=(d.read||d)(i,j)||b(i),c)try{i=JSON.parse(i)}catch(k){}if(e[j]=i,a===j)break}catch(k){}}return a?e[a]:e}}return e.set=f,e.get=function(a){return g(a,!1)},e.getJSON=function(a){return g(a,!0)},e.remove=function(b,c){f(b,"",a(c,{expires:-1}))},e.defaults={},e.withConverter=c,e}return c(function(){})});

View File

@@ -0,0 +1,54 @@
UAGBLottie = {
getElement : ( id ) => {
// Check if the script has run once already on the given element (required for homepage sidebar usage case).
const getJsELement = document.querySelector( `.${id}:not(.uagb-activated-script)` );
if( ! getJsELement ) return null;
// Ensures that the script only runs once on the given element (required for homepage sidebar usage case).
getJsELement.classList.add( 'uagb-activated-script' );
return getJsELement;
},
_run( attr, id ) {
const getLottieElement = UAGBLottie.getElement( id );
if( ! getLottieElement ){
return;
}
const animation = bodymovin.loadAnimation( {
container: getLottieElement,
renderer: 'svg',
loop: attr.loop,
autoplay: 'none' === attr.playOn ? true : false,
path: attr.lottieURl,
rendererSettings: {
preserveAspectRatio: 'xMidYMid',
className: 'uagb-lottie-inner-wrap',
},
} );
animation.setSpeed( attr.speed );
const reversedir = attr.reverse && attr.loop ? -1 : 1;
animation.setDirection( reversedir );
if ( 'hover' === attr.playOn ) {
getLottieElement.addEventListener( 'mouseenter', function () {
animation.play();
} );
getLottieElement.addEventListener( 'mouseleave', function () {
animation.stop();
} );
} else if ( 'click' === attr.playOn ) {
getLottieElement.addEventListener( 'click', function () {
animation.stop();
animation.play();
} );
} else if ( 'scroll' === attr.playOn ) {
window.addEventListener( 'scroll', function () {
animation.stop();
animation.play();
} );
}
},
};

View File

@@ -0,0 +1 @@
UAGBLottie={getElement:e=>{const t=document.querySelector(`.${e}:not(.uagb-activated-script)`);return t?(t.classList.add("uagb-activated-script"),t):null},_run(e,t){const n=UAGBLottie.getElement(t);if(n){const o=bodymovin.loadAnimation({container:n,renderer:"svg",loop:e.loop,autoplay:"none"===e.playOn,path:e.lottieURl,rendererSettings:{preserveAspectRatio:"xMidYMid",className:"uagb-lottie-inner-wrap"}});o.setSpeed(e.speed);t=e.reverse&&e.loop?-1:1;o.setDirection(t),"hover"===e.playOn?(n.addEventListener("mouseenter",function(){o.play()}),n.addEventListener("mouseleave",function(){o.stop()})):"click"===e.playOn?n.addEventListener("click",function(){o.stop(),o.play()}):"scroll"===e.playOn&&window.addEventListener("scroll",function(){o.stop(),o.play()})}}};

View File

@@ -0,0 +1,126 @@
document.addEventListener( 'UAGModalEditor', function ( e ) {
UAGBModal.init( '.uagb-block-' + e.detail.block_id, true );
} );
document.addEventListener( 'AstraQuickViewForModal', function ( e ) {
UAGBModal.init( e.detail.class_name, false );
} );
window.UAGBModal = {
init( mainSelector, isAdmin ) {
const document_element = UAGBModal._getDocumentElement();
const modalWrapper = document_element.querySelectorAll( mainSelector );
const siteEditTheme = document_element.getElementsByClassName( 'edit-site' );
const pageTemplate = document_element.getElementsByClassName( 'block-editor-iframe__body' );
if ( modalWrapper?.length ) {
for ( const modalWrapperEl of modalWrapper ) {
const modalTrigger = modalWrapperEl.querySelector( '.uagb-modal-trigger' );
const closeOverlayClick = modalWrapperEl.dataset.overlayclick;
if ( modalTrigger ) {
modalTrigger.style.pointerEvents = 'auto';
const innerModal = modalWrapperEl?.querySelector( '.uagb-modal-popup' );
if ( ! innerModal ) {
continue;
}
if ( ! isAdmin ) {
document_element.body?.appendChild( innerModal );
}
const bodyWrap = document_element.querySelector( 'body' );
if ( ! bodyWrap ) {
continue;
}
modalTrigger.addEventListener( 'click', function ( e ) {
e.preventDefault();
if ( ! innerModal.classList.contains( 'active' ) ) {
innerModal.classList.add( 'active' );
// Once this modal is active, create a focusable element to add focus onto the modal and then remove it.
const focusElement = document.createElement( 'button' );
focusElement.style.position = 'absolute';
focusElement.style.opacity = '0';
const modalFocus = innerModal.insertBefore( focusElement, innerModal.firstChild );
modalFocus.focus();
modalFocus.remove();
if (
! bodyWrap.classList.contains( 'hide-scroll' ) &&
! siteEditTheme?.length &&
! pageTemplate?.length &&
! bodyWrap.classList.contains( 'wp-admin' )
) {
bodyWrap.classList.add( 'hide-scroll' );
}
}
} );
if ( '.uagb-modal-wrapper' === mainSelector ) { // When we get mainSelector as a uagb-modal-wrapper from AstraQuickViewForModal event we get null for closeModal. So avoid this we need to use uagb-modal-popup as mainSelector.
mainSelector = '.uagb-modal-popup';
}
const closeModal = innerModal.querySelector( `${ mainSelector } .uagb-modal-popup-close` );
if ( closeModal ) {
closeModal.addEventListener( 'click', function () {
if ( innerModal.classList.contains( 'active' ) ) {
innerModal.classList.remove( 'active' );
modalTrigger?.focus();
}
if ( bodyWrap.classList.contains( 'hide-scroll' ) ) {
UAGBModal.closeModalScrollCheck( bodyWrap, document_element );
}
} );
}
if ( 'disable' !== closeOverlayClick ) {
innerModal.addEventListener( 'click', function ( e ) {
// Don't close modal if clicking on buttons or form elements
if ( e.target.matches( 'button, input[type="submit"], input[type="button"]' ) || e.target.closest( 'button' ) ) {
return;
}
if (
'enable' === closeOverlayClick &&
innerModal.classList.contains( 'active' ) &&
! innerModal.querySelector( '.uagb-modal-popup-wrap' ).contains( e.target )
) {
innerModal.classList.remove( 'active' );
}
if ( bodyWrap.classList.contains( 'hide-scroll' ) ) {
UAGBModal.closeModalScrollCheck( bodyWrap, document_element );
}
} );
}
document.addEventListener( 'keyup', function ( e ) {
const closeOnEsc = modalWrapperEl.dataset.escpress;
if ( 27 === e.keyCode && 'enable' === closeOnEsc ) {
if ( innerModal.classList.contains( 'active' ) ) {
innerModal.classList.remove( 'active' );
modalTrigger?.focus();
}
if ( bodyWrap.classList.contains( 'hide-scroll' ) ) {
UAGBModal.closeModalScrollCheck( bodyWrap, document_element );
}
}
} );
}
}
}
},
// Get the Document element if it's inside an iFrame.
_getDocumentElement() {
let document_element = document;
const getEditorIframe = document.querySelectorAll( 'iframe[name="editor-canvas"]' );
if ( getEditorIframe?.length ) {
const iframeDocument = getEditorIframe[0]?.contentWindow?.document || getEditorIframe[0]?.contentDocument;
if ( iframeDocument ) {
document_element = iframeDocument;
}
}
return document_element;
},
// Close the Modal and check if the Scrollbar needs to be reactivated.
closeModalScrollCheck( bodyWrapper, document_element ) {
const allActiveModals = document_element.querySelectorAll( '.uagb-modal-popup.active' );
if ( ! allActiveModals?.length ) {
bodyWrapper.classList.remove( 'hide-scroll' );
}
},
};

View File

@@ -0,0 +1 @@
document.addEventListener("UAGModalEditor",function(e){UAGBModal.init(".uagb-block-"+e.detail.block_id,!0)}),document.addEventListener("AstraQuickViewForModal",function(e){UAGBModal.init(e.detail.class_name,!1)}),window.UAGBModal={init(e,t){const o=UAGBModal._getDocumentElement();var s=o.querySelectorAll(e);const r=o.getElementsByClassName("edit-site"),u=o.getElementsByClassName("block-editor-iframe__body");if(s?.length)for(const c of s){const l=c.querySelector(".uagb-modal-trigger"),a=c.dataset.overlayclick;if(l){l.style.pointerEvents="auto";const n=c?.querySelector(".uagb-modal-popup");if(n){t||o.body?.appendChild(n);const i=o.querySelector("body");if(i){l.addEventListener("click",function(e){if(e.preventDefault(),!n.classList.contains("active")){n.classList.add("active");const t=document.createElement("button"),o=(t.style.position="absolute",t.style.opacity="0",n.insertBefore(t,n.firstChild));o.focus(),o.remove(),i.classList.contains("hide-scroll")||r?.length||u?.length||i.classList.contains("wp-admin")||i.classList.add("hide-scroll")}}),".uagb-modal-wrapper"===e&&(e=".uagb-modal-popup");const d=n.querySelector(e+" .uagb-modal-popup-close");d&&d.addEventListener("click",function(){n.classList.contains("active")&&(n.classList.remove("active"),l?.focus()),i.classList.contains("hide-scroll")&&UAGBModal.closeModalScrollCheck(i,o)}),"disable"!==a&&n.addEventListener("click",function(e){e.target.matches('button, input[type="submit"], input[type="button"]')||e.target.closest("button")||("enable"===a&&n.classList.contains("active")&&!n.querySelector(".uagb-modal-popup-wrap").contains(e.target)&&n.classList.remove("active"),i.classList.contains("hide-scroll")&&UAGBModal.closeModalScrollCheck(i,o))}),document.addEventListener("keyup",function(e){var t=c.dataset.escpress;27===e.keyCode&&"enable"===t&&(n.classList.contains("active")&&(n.classList.remove("active"),l?.focus()),i.classList.contains("hide-scroll")&&UAGBModal.closeModalScrollCheck(i,o))})}}}}},_getDocumentElement(){let e=document;var t=document.querySelectorAll('iframe[name="editor-canvas"]');return!t?.length||(t=t[0]?.contentWindow?.document||t[0]?.contentDocument)&&(e=t),e},closeModalScrollCheck(e,t){t.querySelectorAll(".uagb-modal-popup.active")?.length||e.classList.remove("hide-scroll")}};

View File

@@ -0,0 +1,283 @@
let loadStatus = true;
window.UAGBPostCarousel = {
_setHeight( scope ) {
if ( scope.length > 0 ) {
const postWrapper = scope[ 0 ].querySelectorAll( '.slick-slide' ),
postActive = scope[ 0 ].querySelectorAll( '.slick-slide.slick-active' );
let maxHeight = -1,
wrapperHeight = -1,
postActiveHeight = -1;
Object.keys( postActive ).forEach( ( key ) => {
const thisHeight = postActive[ key ].offsetHeight,
blogPost = postActive[ key ].querySelector( '.uagb-post__inner-wrap' ),
blogPostHeight = blogPost?.offsetHeight;
if ( maxHeight < blogPostHeight ) {
maxHeight = blogPostHeight;
postActiveHeight = maxHeight + 15;
}
if ( wrapperHeight < thisHeight ) {
wrapperHeight = thisHeight;
}
} );
Object.keys( postActive ).forEach( ( key ) => {
const selector = postActive[ key ].querySelector( '.uagb-post__inner-wrap' );
if ( selector ) {
selector.style.height = maxHeight + 'px';
}
} );
let selector = scope[ 0 ].querySelector( '.slick-list' );
if ( selector ) {
selector.style.height = postActiveHeight + 'px';
}
maxHeight = -1;
wrapperHeight = -1;
Object.keys( postWrapper ).forEach( ( key ) => {
const $this = postWrapper[ key ];
if ( $this.classList.contains( 'slick-active' ) ) {
return true;
}
selector = $this.querySelector( '.uagb-post__inner-wrap' );
const blogPostHeight = selector?.offsetHeight;
if ( blogPostHeight ) {
selector.style.height = blogPostHeight + 'px';
}
} );
}
},
_unSetHeight( scope ) {
if ( scope.length > 0 ) {
const postWrapper = scope[ 0 ].querySelectorAll( '.slick-slide' ),
postActive = scope[ 0 ].querySelectorAll( '.slick-slide.slick-active' );
Object.keys( postActive ).forEach( ( key ) => {
const selector = postActive[ key ].querySelector( '.uagb-post__inner-wrap' );
selector.style.height = 'auto';
} );
Object.keys( postActive ).forEach( ( key ) => {
const $this = postWrapper[ key ];
if ( $this.classList.contains( 'slick-active' ) ) {
return true;
}
const selector = $this.querySelector( '.uagb-post__inner-wrap' );
selector.style.height = 'auto';
} );
}
},
};
window.UAGBPostMasonry = {
_init( $attr, $selector ) {
let count = 2;
const windowHeight50 = window.innerHeight / 1.25;
let $scope = document.querySelector( $selector );
const loader = $scope?.querySelectorAll( '.uagb-post-inf-loader' );
if ( 'none' !== $attr.paginationType && 'scroll' === $attr.paginationEventType ) {
window.addEventListener( 'scroll', function () {
let postItems = $scope.querySelector( '.uagb-post__items' );
if ( ! postItems ) {
postItems = $scope;
}
const boundingClientRect = postItems.lastElementChild.getBoundingClientRect();
const offsetTop = boundingClientRect.top + window.scrollY;
if ( window.pageYOffset + windowHeight50 >= offsetTop ) {
const $args = {
page_number: count,
};
const total = $scope.getAttribute( 'data-total' );
if ( true === loadStatus ) {
if ( count <= total ) {
if ( loader.length > 0 ) {
loader[ 0 ].style.display = 'none';
}
window.UAGBPostMasonry._callAjax( $scope, $args, $attr, loader, false, count );
count++;
loadStatus = false;
}
}
}
} );
}
if ( 'button' === $attr.paginationEventType ) {
if ( $scope?.querySelector( '.uagb-post-pagination-button' ) ) {
$scope.style.marginBottom = '40px';
$scope.querySelector( '.uagb-post-pagination-button' ).onclick = function () {
$scope = this.closest( '.uagb-post-grid' );
const total = $scope.getAttribute( 'data-total' );
const $args = {
total,
page_number: count,
};
$scope.querySelector( '.uagb-post__load-more-wrap' ).style.display = 'none';
if ( true === loadStatus ) {
if ( count <= total ) {
if ( loader.length > 0 ) {
loader[ 0 ].style.display = 'none';
}
$scope.querySelector( '.uagb-post__load-more-wrap' ).style.display = 'block';
window.UAGBPostMasonry._callAjax( $scope, $args, $attr, loader, true, count );
count++;
loadStatus = false;
}
}
};
}
}
},
createElementFromHTML( htmlString ) {
const HTMLElement = document.createElement( 'div' );
HTMLElement.innerHTML = htmlString.trim();
// Change this to div.childNodes to support multiple top-level nodes
return HTMLElement;
},
_callAjax( $scope, $obj, $attr, loader, append = false, count ) {
const PostData = new FormData(); // eslint-disable-line no-undef
PostData.append( 'action', 'uagb_get_posts' );
PostData.append( 'nonce', uagb_data.uagb_masonry_ajax_nonce );
PostData.append( 'page_number', $obj.page_number );
PostData.append( 'attr', JSON.stringify( $attr ) );
// eslint-disable-next-line no-undef
fetch( uagb_data.ajax_url, {
method: 'POST',
credentials: 'same-origin',
body: PostData,
} )
.then( ( resp ) => resp.json() )
.then( function ( data ) {
let element = $scope.querySelector( '.is-masonry' );
if ( ! element ) {
element = $scope;
}
setTimeout( function () {
// eslint-disable-next-line no-undef
const isotope = new Isotope( element, {
itemSelector: 'article',
} );
isotope.insert( window.UAGBPostMasonry.createElementFromHTML( data.data ) );
loadStatus = true;
if ( loader.length > 0 ) {
loader[ 0 ].style.display = 'none';
}
if ( true === append ) {
$scope.querySelector( '.uagb-post__load-more-wrap' ).style.display = 'block';
}
if ( count === parseInt( $obj.total ) ) {
$scope.querySelector( '.uagb-post__load-more-wrap' ).style.display = 'none';
}
// This CSS is for Post BG Image Spacing
const articles = document.querySelectorAll(
'.uagb-post__image-position-background .uagb-post__inner-wrap'
);
for ( const article of articles ) {
const articleWidth = article.offsetWidth;
const rowGap = $attr.rowGap;
const imageWidth = 100 - ( rowGap / articleWidth ) * 100;
const image = article.getElementsByClassName( 'uagb-post__image' );
if ( image[ 0 ] ) {
image[ 0 ].style.width = imageWidth + '%';
image[ 0 ].style.marginLeft = rowGap / 2 + 'px';
}
}
}, 500 );
} )
.catch( function ( error ) {
console.log( JSON.stringify( error ) ); // eslint-disable-line no-console
} );
},
};
window.UAGBPostGrid = {
_callAjax( $attr, $page_number, block_id ) {
// Create new FormData object with necessary data to send in AJAX call.
const PostData = new FormData();
PostData.append( 'action', 'uagb_post_pagination_grid' );
PostData.append( 'nonce', uagb_data.uagb_grid_ajax_nonce );
PostData.append( 'page_number', $page_number );
PostData.append( 'attr', JSON.stringify( $attr ) );
// Send AJAX call with PostData object.
fetch( uagb_data.ajax_url, {
method: 'POST',
credentials: 'same-origin',
body: PostData,
} )
.then( ( resp ) => resp.json() )
.then( function( data ) {
// Get the relevant DOM elements to replace.
const grid_element = document.querySelector( '.uagb-block-'+ block_id );
if( ! grid_element ) {
return;
}
// Remove the old elements and replace them with the updated markup received from the AJAX response.
const html = data.data.replace( /\n|\t/g, '' );
grid_element.outerHTML = html;
// Get the new block ID to use for future pagination requests.
const new_blockId = html.match( /uagb-block-([\w-]+)/ )?.[1] || '';
addClickListeners( new_blockId );
} );
function addClickListeners( new_blockId ) {
// Add click event listener to each pagination link in the updated markup.
const elements = document.querySelectorAll( `.uagb-post-grid.uagb-block-${new_blockId} .uagb-post-pagination-wrap a` );
elements.forEach( element => {
element.addEventListener( 'click', event => {
// Prevent default link behavior and extract the new page number to send in the next AJAX call
event.preventDefault();
const link = event.target.getAttribute( 'href' ).match( /admin-ajax.*/ )?.[0] || '';
const pageNumber = link.match( /\d+/ )?.[0] || 1;
// Call _callAjax again with updated page number and block ID
window.UAGBPostGrid._callAjax( $attr, parseInt( pageNumber ), new_blockId );
} );
} );
}
}
};
// Set Carousel Height for Customiser.
// eslint-disable-next-line no-unused-vars
function uagb_carousel_height( id ) {
const wrap = document.querySelector( '#wpwrap .is-carousel.uagb-block-' + id );
if ( wrap ) {
window.UAGBPostCarousel._setHeight( wrap );
}
}
// Unset Carousel Height for Customiser.
// eslint-disable-next-line no-unused-vars
function uagb_carousel_unset_height( id ) {
const wrap = document.querySelector( '#wpwrap .is-carousel.uagb-block-' + id );
if ( wrap ) {
window.UAGBPostCarousel._unSetHeight( wrap );
}
}

View File

@@ -0,0 +1 @@
let loadStatus=!0;function uagb_carousel_height(e){e=document.querySelector("#wpwrap .is-carousel.uagb-block-"+e);e&&window.UAGBPostCarousel._setHeight(e)}function uagb_carousel_unset_height(e){e=document.querySelector("#wpwrap .is-carousel.uagb-block-"+e);e&&window.UAGBPostCarousel._unSetHeight(e)}window.UAGBPostCarousel={_setHeight(e){if(0<e.length){const s=e[0].querySelectorAll(".slick-slide"),l=e[0].querySelectorAll(".slick-slide.slick-active");let a=-1,o=-1,n=-1,r=(Object.keys(l).forEach(e=>{var t=l[e].offsetHeight,e=l[e].querySelector(".uagb-post__inner-wrap")?.offsetHeight;a<e&&(a=e,n=a+15),o<t&&(o=t)}),Object.keys(l).forEach(e=>{const t=l[e].querySelector(".uagb-post__inner-wrap");t&&(t.style.height=a+"px")}),e[0].querySelector(".slick-list"));r&&(r.style.height=n+"px"),a=-1,o=-1,Object.keys(s).forEach(e=>{const t=s[e];if(t.classList.contains("slick-active"))return!0;e=(r=t.querySelector(".uagb-post__inner-wrap"))?.offsetHeight;e&&(r.style.height=e+"px")})}},_unSetHeight(e){if(0<e.length){const o=e[0].querySelectorAll(".slick-slide"),a=e[0].querySelectorAll(".slick-slide.slick-active");Object.keys(a).forEach(e=>{const t=a[e].querySelector(".uagb-post__inner-wrap");t.style.height="auto"}),Object.keys(a).forEach(e=>{const t=o[e];if(t.classList.contains("slick-active"))return!0;const a=t.querySelector(".uagb-post__inner-wrap");a.style.height="auto"})}}},window.UAGBPostMasonry={_init(o,e){let n=2;const r=window.innerHeight/1.25;let s=document.querySelector(e);const l=s?.querySelectorAll(".uagb-post-inf-loader");"none"!==o.paginationType&&"scroll"===o.paginationEventType&&window.addEventListener("scroll",function(){let e=s.querySelector(".uagb-post__items");var t,a=(e=e||s).lastElementChild.getBoundingClientRect().top+window.scrollY;window.pageYOffset+r>=a&&(a={page_number:n},t=s.getAttribute("data-total"),!0===loadStatus&&n<=t&&(0<l.length&&(l[0].style.display="none"),window.UAGBPostMasonry._callAjax(s,a,o,l,!1,n),n++,loadStatus=!1))}),"button"===o.paginationEventType&&s?.querySelector(".uagb-post-pagination-button")&&(s.style.marginBottom="40px",s.querySelector(".uagb-post-pagination-button").onclick=function(){var e=(s=this.closest(".uagb-post-grid")).getAttribute("data-total"),t={total:e,page_number:n};s.querySelector(".uagb-post__load-more-wrap").style.display="none",!0===loadStatus&&n<=e&&(0<l.length&&(l[0].style.display="none"),s.querySelector(".uagb-post__load-more-wrap").style.display="block",window.UAGBPostMasonry._callAjax(s,t,o,l,!0,n),n++,loadStatus=!1)})},createElementFromHTML(e){const t=document.createElement("div");return t.innerHTML=e.trim(),t},_callAjax(l,i,c,u,g=!1,p){const e=new FormData;e.append("action","uagb_get_posts"),e.append("nonce",uagb_data.uagb_masonry_ajax_nonce),e.append("page_number",i.page_number),e.append("attr",JSON.stringify(c)),fetch(uagb_data.ajax_url,{method:"POST",credentials:"same-origin",body:e}).then(e=>e.json()).then(function(r){let s=l.querySelector(".is-masonry");s=s||l,setTimeout(function(){const e=new Isotope(s,{itemSelector:"article"});e.insert(window.UAGBPostMasonry.createElementFromHTML(r.data)),loadStatus=!0,0<u.length&&(u[0].style.display="none"),!0===g&&(l.querySelector(".uagb-post__load-more-wrap").style.display="block"),p===parseInt(i.total)&&(l.querySelector(".uagb-post__load-more-wrap").style.display="none");for(const o of document.querySelectorAll(".uagb-post__image-position-background .uagb-post__inner-wrap")){var t=o.offsetWidth,a=c.rowGap,t=100-a/t*100;const n=o.getElementsByClassName("uagb-post__image");n[0]&&(n[0].style.width=t+"%",n[0].style.marginLeft=a/2+"px")}},500)}).catch(function(e){})}},window.UAGBPostGrid={_callAjax(r,e,s){const t=new FormData;t.append("action","uagb_post_pagination_grid"),t.append("nonce",uagb_data.uagb_grid_ajax_nonce),t.append("page_number",e),t.append("attr",JSON.stringify(r)),fetch(uagb_data.ajax_url,{method:"POST",credentials:"same-origin",body:t}).then(e=>e.json()).then(function(e){const t=document.querySelector(".uagb-block-"+s);if(t){const o=e.data.replace(/\n|\t/g,"");e=(t.outerHTML=o).match(/uagb-block-([\w-]+)/)?.[1]||"";{var a=e;const n=document.querySelectorAll(`.uagb-post-grid.uagb-block-${a} .uagb-post-pagination-wrap a`);n.forEach(e=>{e.addEventListener("click",e=>{e.preventDefault();const t=e.target.getAttribute("href").match(/admin-ajax.*/)?.[0]||"";e=t.match(/\d+/)?.[0]||1;window.UAGBPostGrid._callAjax(r,parseInt(e),a)})})}}else;})}};

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,5 @@
window.addEventListener( 'load', function() {
setTimeout( function() {
AOS.init();
}, 0 );
} );

View File

@@ -0,0 +1 @@
window.addEventListener("load",function(){setTimeout(function(){AOS.init()},0)});

View File

@@ -0,0 +1,201 @@
const UAGBBlockPositioning = {
// Initialize the required positioning functionality.
init( attr, selector ) {
const element = document.querySelector( selector );
if ( element?.classList.contains( 'uagb-position__sticky' ) ) {
UAGBBlockPositioning.handleSticky( element, attr );
}
},
// Function to handle the sticky positioned element.
handleSticky( element, attr ) {
// Add the Adminbar height if needed.
const getAdminbarHeight = () => {
const adminBar = document.querySelector( '#wpadminbar' );
return adminBar?.offsetHeight || 0;
}
// Create a filler element for sticky.
const createStickyFiller = ( elementNode, elementDimensions, elementParent ) => {
const fillerElement = document.createElement( 'div' );
fillerElement.style.height = `${ elementDimensions.height }px`;
fillerElement.style.boxSizing = 'border-box';
const elementStyles = window.getComputedStyle( elementNode );
// If the sticky element is not restricted to the parent container, then set the width and margin.
if ( ! elementParent ) {
fillerElement.style.width = `${ elementDimensions.width }px`;
fillerElement.style.margin = elementStyles.getPropertyValue( 'margin' ) || 0;
// If the sticky element is restricted to the parent container, then set the maxWidth as was intended for the stuck element.
} else {
fillerElement.style.width = '100%';
fillerElement.style.maxWidth = elementStyles.getPropertyValue( 'max-width' ) || `${ elementDimensions.width }px`;
fillerElement.style.padding = elementStyles.getPropertyValue( 'padding' ) || 0;
fillerElement.style.margin = elementStyles.getPropertyValue( 'margin' ) || 0;
fillerElement.style.border = elementStyles.getPropertyValue( 'border' ) || 0;
fillerElement.style.borderColor = 'transparent';
}
return fillerElement;
};
// Add the animation attributes to the element and refresh the animations if this was an animated element.
const applyAnimationData = () => {
if ( 'undefined' === typeof AOS || ! attr?.UAGAnimationType ) {
return;
}
element.dataset.aos = attr?.UAGAnimationType;
element.dataset.aosDuration = attr?.UAGAnimationTime;
element.dataset.aosDelay = attr?.UAGAnimationDelay;
element.dataset.aosEasing = attr?.UAGAnimationEasing;
element.dataset.aosOnce = true;
setTimeout( () => {
AOS.refreshHard();
}, 100 );
}
// Get the dimensions of the sticky element.
const stickyDimensions = element.getBoundingClientRect();
const parentContainer = ! attr?.isBlockRootParent ? element.parentElement : null;
const fillerElement = createStickyFiller( element, stickyDimensions, parentContainer );
let haltAt, haltAtPosition, scrollPosition, parentRect;
// Create the ParentHaltAt and ParentInnerPositions variables.
const parentHaltAt = { top: 0, bottom: 0 };
const parentInnerPositions = { top: 0, right: 0, bottom: 0, left: 0 };
if ( attr?.UAGStickyRestricted ) {
parentRect = parentContainer.getBoundingClientRect();
const parentStyles = window.getComputedStyle( parentContainer );
parentInnerPositions.top = parseInt( parentStyles.getPropertyValue( 'padding-top' ) || 0, 10 );
parentInnerPositions.bottom = parseInt( parentStyles.getPropertyValue( 'padding-bottom' ) || 0, 10 );
// To calculate the top position needed for the inner sticky container:
// Start with the parent's top position.
// Add the current scroll offset.
// Add the parent's top padding if any.
parentHaltAt.top = parentRect.top + ( window.pageYOffset || 0 ) + parentInnerPositions.top;
// To calculate the top position needed for the inner sticky container:
// Start with the parent's bottom position.
// Add the current scroll offset.
// Subtract the parent's bottom padding if any.
// Subtract the sticky element's height.
// Subtract the adminbar height if it exists.
// Subtract the offset.
parentHaltAt.bottom = parentRect.bottom + ( window.pageYOffset || 0 ) - parentInnerPositions.bottom - stickyDimensions.height - getAdminbarHeight() - ( attr?.UAGStickyOffset || 0 );
}
// Handle the sticky element when it is positioned at the bottom, else handle top.
if ( 'bottom' === attr?.UAGStickyLocation ) {
// Stop whn the scroll makes the entire element visible on the current screen.
haltAt = stickyDimensions.top + ( window.pageYOffset || 0 ) - window.innerHeight + stickyDimensions.height + ( attr?.UAGStickyOffset || 0 );
// Position the element to the bottom, considering the adminbar.
haltAtPosition = `${ ( attr?.UAGStickyOffset || 0 ) }px`;
scrollPosition = ( window.pageYOffset !== undefined ) ? window.pageYOffset : document.body.scrollTop;
if ( scrollPosition <= haltAt && ! element.classList.contains( 'uagb-position__sticky--stuck' ) ) {
element.parentNode.insertBefore( fillerElement, element );
element.classList.add( 'uagb-position__sticky--stuck' );
element.style.bottom = `calc(${ haltAtPosition } - ${ window.innerHeight }px)`;
element.style.left = `${ stickyDimensions.left }px`;
element.style.width = `${ stickyDimensions.width }px`;
element.style.zIndex = '999';
setTimeout( () => {
element.style.bottom = haltAtPosition;
}, 50 );
}
// Check if this sticky container was animated.
applyAnimationData();
// Check when this needsto be stuck on the bottom, and when it doesn't.
window.addEventListener( 'scroll', () => {
scrollPosition = ( window.pageYOffset !== undefined ) ? window.pageYOffset : document.body.scrollTop;
if ( scrollPosition <= haltAt ) {
if ( ! element.classList.contains( 'uagb-position__sticky--stuck' ) ) {
element.parentNode.insertBefore( fillerElement, element );
element.classList.add( 'uagb-position__sticky--stuck' );
element.style.bottom = haltAtPosition;
element.style.left = `${ stickyDimensions.left }px`;
element.style.width = `${ stickyDimensions.width }px`;
element.style.zIndex = '999';
}
} else if ( scrollPosition > haltAt && element.classList.contains( 'uagb-position__sticky--stuck' ) ) {
element.parentNode.removeChild( fillerElement );
element.classList.remove( 'uagb-position__sticky--stuck' );
element.style.bottom = '';
element.style.left = '';
element.style.width = '';
element.style.zIndex = '';
}
} );
} else {
// Stop whn the scroll is at the top of the element.
haltAt = stickyDimensions.top + ( window.pageYOffset || 0 ) - getAdminbarHeight() - ( attr?.UAGStickyOffset || 0 );
// Position the element to the top, considering the adminbar.
haltAtPosition = `${ getAdminbarHeight() + ( attr?.UAGStickyOffset || 0 ) }px`;
scrollPosition = ( window.pageYOffset !== undefined ) ? window.pageYOffset : document.body.scrollTop;
if ( scrollPosition >= haltAt && ! element.classList.contains( 'uagb-position__sticky--stuck' ) ) {
element.parentNode.insertBefore( fillerElement, element );
// Add and Remove Opacity for Sticky Containers.
element.classList.add( 'uagb-position__sticky--stuck' );
// If this restricted container has crossed the bottom of the parent container on load, then restrict it.
if ( attr?.UAGStickyRestricted && scrollPosition >= parentHaltAt.bottom ) {
element.classList.remove( 'uagb-position__sticky--stuck' );
element.classList.add( 'uagb-position__sticky--restricted' );
element.style.top = '';
element.style.bottom = `${ parentInnerPositions.bottom }px`;
element.style.left = `${ fillerElement?.offsetLeft || 0 }px`;
// Else, just stick it to the top and transition it to the halt position.
} else {
element.style.top = `calc(${ haltAtPosition } - ${ window.innerHeight }px)`
element.style.left = `${ stickyDimensions.left }px`;
element.style.top = haltAtPosition;
}
element.style.width = `${ stickyDimensions.width }px`;
element.style.zIndex = '999';
}
// Check if this sticky container was animated.
applyAnimationData();
// Check when this needsto be stuck on the top, and when it doesn't.
window.addEventListener( 'scroll', () => {
scrollPosition = ( window.pageYOffset !== undefined ) ? window.pageYOffset : document.body.scrollTop;
// If the scroll position is greater than the current sticky height.
if ( scrollPosition >= haltAt ) {
// If the sticky class doesn't yet exist, add the filler and the sticky class.
if ( ! element.classList.contains( 'uagb-position__sticky--stuck' ) && ! element.classList.contains( 'uagb-position__sticky--restricted' ) ) {
element.parentNode.insertBefore( fillerElement, element );
element.classList.add( 'uagb-position__sticky--stuck' );
element.style.top = haltAtPosition;
element.style.left = `${ stickyDimensions.left }px`;
element.style.width = `${ stickyDimensions.width }px`;
element.style.zIndex = '999';
// Else if the container is struck and the scroll is at the parent bottom, restrict it there.
} else if ( attr?.UAGStickyRestricted && ! element.classList.contains( 'uagb-position__sticky--restricted' ) && scrollPosition >= parentHaltAt.bottom ) {
element.classList.remove( 'uagb-position__sticky--stuck' );
element.classList.add( 'uagb-position__sticky--restricted' );
element.style.top = '';
element.style.bottom = `${ parentInnerPositions.bottom }px`;
element.style.left = `${ fillerElement?.offsetLeft || 0 }px`;
// Else if the container is already restricted and the scroll has returned above the parent bottom, stick it again.
} else if ( element.classList.contains( 'uagb-position__sticky--restricted' ) && scrollPosition < parentHaltAt.bottom ) {
element.classList.remove( 'uagb-position__sticky--restricted' );
element.classList.add( 'uagb-position__sticky--stuck' );
element.style.top = haltAtPosition;
element.style.bottom = '';
element.style.left = `${ stickyDimensions.left }px`;
element.style.width = `${ stickyDimensions.width }px`;
element.style.zIndex = '999';
}
} else if ( scrollPosition < haltAt && element.classList.contains( 'uagb-position__sticky--stuck' ) ) {
element.parentNode.removeChild( fillerElement );
element.classList.remove( 'uagb-position__sticky--stuck' );
element.style.top = '';
element.style.left = '';
element.style.width = '';
element.style.zIndex = '';
}
} );
}
},
};

View File

@@ -0,0 +1 @@
const UAGBBlockPositioning={init(t,e){const s=document.querySelector(e);s?.classList.contains("uagb-position__sticky")&&UAGBBlockPositioning.handleSticky(s,t)},handleSticky(t,e){var s=()=>{return document.querySelector("#wpadminbar")?.offsetHeight||0},p=()=>{"undefined"!=typeof AOS&&e?.UAGAnimationType&&(t.dataset.aos=e?.UAGAnimationType,t.dataset.aosDuration=e?.UAGAnimationTime,t.dataset.aosDelay=e?.UAGAnimationDelay,t.dataset.aosEasing=e?.UAGAnimationEasing,t.dataset.aosOnce=!0,setTimeout(()=>{AOS.refreshHard()},100))};const o=t.getBoundingClientRect(),y=e?.isBlockRootParent?null:t.parentElement,i=((t,e,s)=>{const o=document.createElement("div"),i=(o.style.height=e.height+"px",o.style.boxSizing="border-box",window.getComputedStyle(t));return s?(o.style.width="100%",o.style.maxWidth=i.getPropertyValue("max-width")||e.width+"px",o.style.padding=i.getPropertyValue("padding")||0,o.style.margin=i.getPropertyValue("margin")||0,o.style.border=i.getPropertyValue("border")||0,o.style.borderColor="transparent"):(o.style.width=e.width+"px",o.style.margin=i.getPropertyValue("margin")||0),o})(t,o,y);let n,a,l,r;const c={top:0,bottom:0},d={top:0,right:0,bottom:0,left:0};if(e?.UAGStickyRestricted){r=y.getBoundingClientRect();const g=window.getComputedStyle(y);d.top=parseInt(g.getPropertyValue("padding-top")||0,10),d.bottom=parseInt(g.getPropertyValue("padding-bottom")||0,10),c.top=r.top+(window.pageYOffset||0)+d.top,c.bottom=r.bottom+(window.pageYOffset||0)-d.bottom-o.height-s()-(e?.UAGStickyOffset||0)}"bottom"===e?.UAGStickyLocation?(n=o.top+(window.pageYOffset||0)-window.innerHeight+o.height+(e?.UAGStickyOffset||0),a=`${e?.UAGStickyOffset||0}px`,(l=void 0!==window.pageYOffset?window.pageYOffset:document.body.scrollTop)<=n&&!t.classList.contains("uagb-position__sticky--stuck")&&(t.parentNode.insertBefore(i,t),t.classList.add("uagb-position__sticky--stuck"),t.style.bottom=`calc(${a} - ${window.innerHeight}px)`,t.style.left=o.left+"px",t.style.width=o.width+"px",t.style.zIndex="999",setTimeout(()=>{t.style.bottom=a},50)),p(),window.addEventListener("scroll",()=>{(l=void 0!==window.pageYOffset?window.pageYOffset:document.body.scrollTop)<=n?t.classList.contains("uagb-position__sticky--stuck")||(t.parentNode.insertBefore(i,t),t.classList.add("uagb-position__sticky--stuck"),t.style.bottom=a,t.style.left=o.left+"px",t.style.width=o.width+"px",t.style.zIndex="999"):l>n&&t.classList.contains("uagb-position__sticky--stuck")&&(t.parentNode.removeChild(i),t.classList.remove("uagb-position__sticky--stuck"),t.style.bottom="",t.style.left="",t.style.width="",t.style.zIndex="")})):(n=o.top+(window.pageYOffset||0)-s()-(e?.UAGStickyOffset||0),a=s()+(e?.UAGStickyOffset||0)+"px",(l=void 0!==window.pageYOffset?window.pageYOffset:document.body.scrollTop)>=n&&!t.classList.contains("uagb-position__sticky--stuck")&&(t.parentNode.insertBefore(i,t),t.classList.add("uagb-position__sticky--stuck"),e?.UAGStickyRestricted&&l>=c.bottom?(t.classList.remove("uagb-position__sticky--stuck"),t.classList.add("uagb-position__sticky--restricted"),t.style.top="",t.style.bottom=d.bottom+"px",t.style.left=`${i?.offsetLeft||0}px`):(t.style.top=`calc(${a} - ${window.innerHeight}px)`,t.style.left=o.left+"px",t.style.top=a),t.style.width=o.width+"px",t.style.zIndex="999"),p(),window.addEventListener("scroll",()=>{(l=void 0!==window.pageYOffset?window.pageYOffset:document.body.scrollTop)>=n?t.classList.contains("uagb-position__sticky--stuck")||t.classList.contains("uagb-position__sticky--restricted")?e?.UAGStickyRestricted&&!t.classList.contains("uagb-position__sticky--restricted")&&l>=c.bottom?(t.classList.remove("uagb-position__sticky--stuck"),t.classList.add("uagb-position__sticky--restricted"),t.style.top="",t.style.bottom=d.bottom+"px",t.style.left=`${i?.offsetLeft||0}px`):t.classList.contains("uagb-position__sticky--restricted")&&l<c.bottom&&(t.classList.remove("uagb-position__sticky--restricted"),t.classList.add("uagb-position__sticky--stuck"),t.style.top=a,t.style.bottom="",t.style.left=o.left+"px",t.style.width=o.width+"px",t.style.zIndex="999"):(t.parentNode.insertBefore(i,t),t.classList.add("uagb-position__sticky--stuck"),t.style.top=a,t.style.left=o.left+"px",t.style.width=o.width+"px",t.style.zIndex="999"):l<n&&t.classList.contains("uagb-position__sticky--stuck")&&(t.parentNode.removeChild(i),t.classList.remove("uagb-position__sticky--stuck"),t.style.top="",t.style.left="",t.style.width="",t.style.zIndex="")}))}};

View File

@@ -0,0 +1,198 @@
UAGBCounter = {
elements: {},
init( mainSelector, data = {} ) {
this.elements = this.getDefaultElements( mainSelector );
const elements = document.querySelectorAll( `.wp-block-uagb-counter${mainSelector}` );
if ( elements && elements.length > 1 ) {
for( const element of elements ) {
this.elements.counterWrapper = element;
this.handleCounterWrapper( data );
}
} else {
this.handleCounterWrapper( data );
}
},
handleCounterWrapper( data ) {
data = this._getCounterData( this.elements.counterWrapper, data );
if( !data.isFrontend ){
this.elements.counterWrapper.removeAttribute( 'played' );
}
if ( typeof this.elements.counterWrapper !== 'undefined' && this.elements.counterWrapper ) {
const numberCount = this._numberCount( data );
this._inViewInit( numberCount, data );
}
},
getDefaultElements( mainSelector ) {
const counterWrapper = this.getElement( mainSelector );
return {
counterWrapper,
};
},
getElement( selector, childSelector = null ) {
let domElement = document.querySelector( selector );
if ( domElement ) {
if ( childSelector ) {
return domElement.querySelector( childSelector );
}
} else {
const editorCanvas = document.querySelector( 'iframe[name="editor-canvas"]' );
if ( editorCanvas && editorCanvas.contentDocument ) {
domElement = editorCanvas.contentDocument.querySelector( selector );
if ( childSelector ) {
return ( domElement = domElement.querySelector( childSelector ) );
}
}
}
return domElement;
},
_inViewInit( countUp, data ) {
const that = this;
const callback = ( entries ) => {
entries.forEach( ( entry ) => {
const el = entry.target;
const hasPlayed = el.hasAttribute( 'played' ); // Check if an animation has played; If played already, do mot re-trigger it.
if ( entry.isIntersecting && ! hasPlayed ) {
if ( ! countUp.error ) {
if ( data.layout === 'bars' ) {
that._triggerBar( el, data );
} else if ( data.layout === 'circle' ) {
that._triggerCircle( el, data );
}
countUp.start();
} else {
console.error( countUp.error ); // eslint-disable-line no-console
}
}
} );
};
const IO = new IntersectionObserver( callback, { threshold: 0.75 } );
IO.observe( that.elements.counterWrapper );
},
_numberCount( data ) {
const that = this;
const el = this.elements.counterWrapper.querySelector( '.uagb-counter-block-number' );
if ( typeof el !== 'undefined' && el ) {
const countUp = new window.countUp.CountUp( el, that._getEndNumber( data ), {
startVal: that._getStartNumber( data ),
duration: that._getAnimationDuration( data ),
separator: data.thousandSeparator,
useEasing: false,
decimalPlaces: data.decimalPlaces,
} );
return countUp;
}
},
_triggerBar( el, data ) {
const that = this;
const parentWrapClass = 'wp-block-uagb-counter--bars';
const numberWrap = el.querySelector( '.wp-block-uagb-counter__number' );
const duration = that._getAnimationDurationForCSS( data );
const startWidth =
that._getStartNumber( data ) < that._getTotalNumber( data )
? Math.ceil( ( that._getStartNumber( data ) / that._getTotalNumber( data ) ) * 100 )
: 100;
const endWidth =
that._getEndNumber( data ) <= that._getTotalNumber( data )
? Math.ceil( ( that._getEndNumber( data ) / that._getTotalNumber( data ) ) * 100 )
: 100;
const animationKeyframes = [ { width: startWidth + '%' }, { width: endWidth + '%' } ];
const animationProperties = {
duration,
fill: 'forwards',
};
// Condition to prevent an edge case bug where number layout gets animated like bar layout.
if ( el.classList.contains( parentWrapClass ) ) {
numberWrap?.animate( animationKeyframes, animationProperties );
}
el.setAttribute( 'played', true ); // Set: animation has played once.
},
_triggerCircle( el, data ) {
const that = this;
const circleWrap = el.querySelector(
'.wp-block-uagb-counter-circle-container svg .uagb-counter-circle__progress'
);
const diameter = data.circleSize - data.circleStokeSize;
const circumference = Math.PI * diameter;
const totalNumber = that._getTotalNumber( data );
let startPoint = 100 * ( that._getStartNumber( data ) / totalNumber );
startPoint = startPoint < 100 ? startPoint : 100;
startPoint = 100 - startPoint;
startPoint = ( startPoint / 100 ) * circumference;
let endPoint = 100 * ( that._getEndNumber( data ) / totalNumber );
endPoint = endPoint < 100 ? endPoint : 100;
endPoint = 100 - endPoint;
endPoint = ( endPoint / 100 ) * circumference;
const duration = that._getAnimationDurationForCSS( data );
const animationKeyframes = [ { strokeDashoffset: startPoint + 'px' }, { strokeDashoffset: endPoint + 'px' } ];
const animationProperties = {
duration,
fill: 'forwards',
};
circleWrap?.animate( animationKeyframes, animationProperties );
el.setAttribute( 'played', true ); // Set: animation has played once.
},
_getAnimationDuration( data ) {
return data.animationDuration / 1000;
},
_getAnimationDurationForCSS( data ) {
return data.animationDuration;
},
_getStartNumber( data ) {
if ( isNaN( data.startNumber ) ) {
return parseFloat( 0 );
}
return data.startNumber || parseFloat( data.startNumber ) === parseFloat( 0 )
? parseFloat( data.startNumber )
: parseFloat( 0 );
},
_getEndNumber( data ) {
if ( isNaN( data.endNumber ) ) {
return parseFloat( 80 );
}
return data.endNumber || parseFloat( data.startNumber ) === parseFloat( 0 )
? parseFloat( data.endNumber )
: parseFloat( 80 );
},
_getTotalNumber( data ) {
if ( isNaN( data.startNumber ) ) {
return parseFloat( 0 );
}
return ( data.totalNumber || parseFloat( data.startNumber ) === parseFloat( 0 ) ) ? parseFloat( data.totalNumber ) : parseFloat( 100 );
},
_getCounterData( element,data ){
// Getting data from html attribute data-counter and overwrite data which comes from php.
let getCounterData = element?.getAttribute( 'data-counter' );
if( ! getCounterData ){
return data;
}
getCounterData = JSON.parse( getCounterData );
if( getCounterData ){
data = { ...data, ...getCounterData};
}
return data;
}
};

View File

@@ -0,0 +1 @@
UAGBCounter={elements:{},init(e,t={}){this.elements=this.getDefaultElements(e);e=document.querySelectorAll(".wp-block-uagb-counter"+e);if(e&&1<e.length)for(const r of e)this.elements.counterWrapper=r,this.handleCounterWrapper(t);else this.handleCounterWrapper(t)},handleCounterWrapper(e){var t;(e=this._getCounterData(this.elements.counterWrapper,e)).isFrontend||this.elements.counterWrapper.removeAttribute("played"),void 0!==this.elements.counterWrapper&&this.elements.counterWrapper&&(t=this._numberCount(e),this._inViewInit(t,e))},getDefaultElements(e){return{counterWrapper:this.getElement(e)}},getElement(e,t=null){let r=document.querySelector(e);if(r){if(t)return r.querySelector(t)}else{const a=document.querySelector('iframe[name="editor-canvas"]');if(a&&a.contentDocument&&(r=a.contentDocument.querySelector(e),t))return r=r.querySelector(t)}return r},_inViewInit(a,n){const o=this;const e=new IntersectionObserver(e=>{e.forEach(e=>{const t=e.target;var r=t.hasAttribute("played");e.isIntersecting&&!r&&(a.error||("bars"===n.layout?o._triggerBar(t,n):"circle"===n.layout&&o._triggerCircle(t,n),a.start()))})},{threshold:.75});e.observe(o.elements.counterWrapper)},_numberCount(e){var t=this,r=this.elements.counterWrapper.querySelector(".uagb-counter-block-number");if(void 0!==r&&r)return new window.countUp.CountUp(r,t._getEndNumber(e),{startVal:t._getStartNumber(e),duration:t._getAnimationDuration(e),separator:e.thousandSeparator,useEasing:!1,decimalPlaces:e.decimalPlaces})},_triggerBar(e,t){var r=this;const a=e.querySelector(".wp-block-uagb-counter__number");var n=r._getAnimationDurationForCSS(t),r=[{width:(r._getStartNumber(t)<r._getTotalNumber(t)?Math.ceil(r._getStartNumber(t)/r._getTotalNumber(t)*100):100)+"%"},{width:(r._getEndNumber(t)<=r._getTotalNumber(t)?Math.ceil(r._getEndNumber(t)/r._getTotalNumber(t)*100):100)+"%"}],t={duration:n,fill:"forwards"};e.classList.contains("wp-block-uagb-counter--bars")&&a?.animate(r,t),e.setAttribute("played",!0)},_triggerCircle(e,t){var r=this;const a=e.querySelector(".wp-block-uagb-counter-circle-container svg .uagb-counter-circle__progress");var n=t.circleSize-t.circleStokeSize,n=Math.PI*n,o=r._getTotalNumber(t);let u=r._getStartNumber(t)/o*100,i=(u=(u=100-(u=u<100?u:100))/100*n,r._getEndNumber(t)/o*100);i=(i=100-(i=i<100?i:100))/100*n;o=r._getAnimationDurationForCSS(t),n=[{strokeDashoffset:u+"px"},{strokeDashoffset:i+"px"}];a?.animate(n,{duration:o,fill:"forwards"}),e.setAttribute("played",!0)},_getAnimationDuration(e){return e.animationDuration/1e3},_getAnimationDurationForCSS(e){return e.animationDuration},_getStartNumber(e){return!isNaN(e.startNumber)&&(e.startNumber||parseFloat(e.startNumber)===parseFloat(0))?parseFloat(e.startNumber):parseFloat(0)},_getEndNumber(e){return!isNaN(e.endNumber)&&(e.endNumber||parseFloat(e.startNumber)===parseFloat(0))?parseFloat(e.endNumber):parseFloat(80)},_getTotalNumber(e){return isNaN(e.startNumber)?parseFloat(0):e.totalNumber||parseFloat(e.startNumber)===parseFloat(0)?parseFloat(e.totalNumber):parseFloat(100)},_getCounterData(e,t){e=e?.getAttribute("data-counter");return(e=e&&JSON.parse(e))?{...t,...e}:t}};

View File

@@ -0,0 +1,41 @@
// Spectra Popup JS Actions Needed in the Admin CPT Page.
// Click Event to Enable or Disable Related Popup.
const UAGBToggelSwitch = ( event ) => {
const element = event.target;
// If the current toggle is on, this is false - else this is true.
const updatedStatus = element.classList.contains( 'spectra-popup-builder__switch--active' ) ? 'false' : 'true';
const mediaData = new FormData();
mediaData.append( 'action', 'uag_update_popup_status' );
mediaData.append( 'nonce', uagb_popup_builder_admin.uagb_popup_builder_admin_nonce );
mediaData.append( 'post_id', element.dataset.post_id );
mediaData.append( 'enabled', updatedStatus );
fetch( uagb_popup_builder_admin.ajax_url, {
method: 'POST',
credentials: 'same-origin',
body: mediaData,
} )
.then( ( resp ) => resp.json() )
.then( ( data ) => {
if ( false === data.success ) {
return;
}
// If the API Fetch was successful, invert the toggle.
if ( 'false' === updatedStatus ) {
element.classList.remove( 'spectra-popup-builder__switch--active' );
} else {
element.classList.add( 'spectra-popup-builder__switch--active' );
}
} );
}
// Bind Related Click Events on Load.
document.addEventListener( 'DOMContentLoaded', () => {
// Bind all the Toggles.
const spectraToggles = document.querySelectorAll( '.spectra-popup-builder__switch' );
for ( let spectraToggleCount = 0; spectraToggleCount < spectraToggles.length; spectraToggleCount++ ) {
spectraToggles[ spectraToggleCount ].addEventListener( 'click', ( event ) => UAGBToggelSwitch( event ), false );
}
} );

View File

@@ -0,0 +1 @@
const UAGBToggelSwitch=e=>{const t=e.target,a=t.classList.contains("spectra-popup-builder__switch--active")?"false":"true",p=new FormData;p.append("action","uag_update_popup_status"),p.append("nonce",uagb_popup_builder_admin.uagb_popup_builder_admin_nonce),p.append("post_id",t.dataset.post_id),p.append("enabled",a),fetch(uagb_popup_builder_admin.ajax_url,{method:"POST",credentials:"same-origin",body:p}).then(e=>e.json()).then(e=>{!1!==e.success&&("false"==a?t.classList.remove("spectra-popup-builder__switch--active"):t.classList.add("spectra-popup-builder__switch--active"))})};document.addEventListener("DOMContentLoaded",()=>{const t=document.querySelectorAll(".spectra-popup-builder__switch");for(let e=0;e<t.length;e++)t[e].addEventListener("click",e=>UAGBToggelSwitch(e),!1)});

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,635 @@
let scrollData = true;
let scrollOffset = 30;
let scrolltoTop = false;
let scrollElement = null;
let uagbTOCCollapseListener = true;
UAGBTableOfContents = {
_getDocumentElement() {
let document_element = document;
const getEditorIframe = document.querySelectorAll( 'iframe[name="editor-canvas"]' );
if( getEditorIframe?.length ){
const iframeDocument = getEditorIframe?.[0]?.contentWindow?.document || getEditorIframe?.[0]?.contentDocument;
if ( iframeDocument ) {
document_element = iframeDocument;
}
}
return document_element;
},
_setCollapseIconMargin ( id, attr ) {
const document_collapsable = UAGBTableOfContents._getDocumentElement();
const block_element = document_collapsable.querySelector( id );
const uagbLoader = block_element.querySelector( '.uagb-toc__loader' );
// Get the first list item to compute the ::marker styles.
const firstListItem = block_element.querySelector( 'li.uagb-toc__list:not(.uagb-toc__list--expandable)' );
if( firstListItem ) {
const listFontSize = window.getComputedStyle( firstListItem ).fontSize;
const listWrap = block_element.querySelector( '.uagb-toc__list-wrap' );
// Calculate the width for ::before pseudo-elements
const widthValue = `calc(${listFontSize} / 3)`;
// Check if a previous style element exists and remove it.
// Escape periods in the id for use in querySelector or CSS.
const escapedId = id?.replace( /\./g, '' );
// Ensure no existing stylesheets target the ID
const existingStyleSheet = document_collapsable.querySelector( `#${escapedId}-toc-style` );
if ( existingStyleSheet ) {
existingStyleSheet.remove(); // Remove the existing stylesheet if it exists.
}
// Create or append to the <style> element.
const styleSheet = document_collapsable.createElement( 'style' );
styleSheet.id = `${escapedId}-toc-style`; // Assign an ID to the style element for future reference.
// check if the browser is Safari or Firefox.
const userAgent = navigator.userAgent.toLowerCase();
const isSafari = /^((?!chrome|android|crios|fxios).)*safari/i.test( userAgent ) && !userAgent.includes( 'edge' );
const isFirefox = userAgent.includes( 'firefox' );
const isFirefoxOrSafari = isSafari || isFirefox;
// Function to calculate margin-right based on font size.
const calculateMarginRightDisc = ( fontSize ) => {
const baseFontSize = 8; // Base font size for margin calculation.
const baseMargin = 5; // Base margin for font size 8px.
const increment = 5; // Increment for each additional 8px font size.
// Parse font size to number.
const fontSizeNumeric = parseFloat( fontSize );
// Calculate number of 8px increments.
const increments = ( ( fontSizeNumeric - baseFontSize ) / 8 );
const marginRight = baseMargin + ( increments * increment );
return `${marginRight}px`;
};
const calculateMarginRightDecimal = ( ListFontSize ) => {
const fontSize = parseFloat( ListFontSize );
// Base margin calculated as one-fourth of the font size.
const baseMargin = ( 1 / 4 ) * fontSize;
// Additional margin added for font sizes greater than 16px.
const additionalMargin = Math.max( 0, ( fontSize - 16 ) / 8 ) * 2;
return ( baseMargin + additionalMargin );
};
let marginRight;
let marginLeft = '-0.5px';
// Check if markerView is 'disc'
if ( 'disc' === attr?.markerView ) {
if ( isFirefoxOrSafari ) {
marginRight = calculateMarginRightDisc( listFontSize );
marginLeft = isFirefox ? '1px' : '-0.5px';
} else {
marginRight = listFontSize;
}
}
if ( 'decimal' === attr?.markerView ) {
// For non-'disc' marker view
const marginRightDeducting = calculateMarginRightDecimal( listFontSize )
marginRight = `${parseFloat( listFontSize ) - marginRightDeducting}px`;
marginLeft = '1px'
}
// First apply the width to the marker pseudo elements.
// Them update the margins of the markers.
// Them update the RTL based margins of the markers. Basically inverted version of the LTR margins.
styleSheet.innerHTML += `
${ id } .list-open::before,
${ id } .list-collapsed::before {
width: ${ widthValue };
}
${ id } .list-open,
${ id } .list-collapsed {
margin-right: ${ marginRight };
margin-left: ${ marginLeft };
}
[dir="rtl"] ${ id } .list-open,
[dir="rtl"] ${ id } .list-collapsed {
margin-right: ${ marginLeft };
margin-left: ${ marginRight };
}
`;
// Append the <style> element to the document's head.
document_collapsable.head.appendChild( styleSheet );
setTimeout( () => {
block_element.style.opacity = '';
uagbLoader?.remove();
listWrap?.classList.remove( 'uagb-toc__list-hidden' );
}, 300 ); // Duration to match the transition duration.
}
},
_initCollapsableList( id, attr ) {
const document_collapsable = UAGBTableOfContents._getDocumentElement();
const block_element = document_collapsable.querySelector( id );
// Run only if toc-content-collapsable class is present and script hasn't run before
if ( attr?.isFrontend && attr?.enableCollapsableList && ! block_element.classList.contains( 'init-collapsed-script' ) ) {
block_element.classList.add( 'init-collapsed-script' ); // Mark script as executed.
const ulElements = block_element.querySelectorAll( 'ul.uagb-toc__list' );
// Set margins for collapsible icon in editor and frontend
if ( 'function' === typeof UAGBTableOfContents._setCollapseIconMargin ) {
UAGBTableOfContents._setCollapseIconMargin( id, attr );
}
ulElements.forEach( ( ul ) => {
const spanElement = ul.parentElement.querySelector( '.list-open' );
// Apply initial transition and max height settings
ul.classList.add( 'transition' );
ul.dataset.originalMaxHeight = ul.scrollHeight + 'px';
if ( spanElement ) {
const isExpanded = spanElement.getAttribute( 'aria-expanded' ) === 'true';
ul.style.maxHeight = isExpanded ? ul.dataset.originalMaxHeight : '0px';
ul.style.overflow = isExpanded ? 'visible' : 'hidden';
ul.addEventListener( 'transitionend', () => {
if ( ul.style.maxHeight !== '0px' ) {
ul.style.overflow = 'visible';
}
} );
} else {
ul.style.maxHeight = ul.dataset.originalMaxHeight;
ul.style.overflow = 'visible';
}
} );
// Initialize event listeners for each span with class .list-open.
const spanList = Array.from( block_element.getElementsByClassName( 'list-open' ) );
spanList.forEach( ( ele ) => {
const handleToggle = () => {
const ulElement = ele.parentElement.querySelector( 'ul' );
if ( ! ulElement ) {
return;
}
const isExpanded = ele.getAttribute( 'aria-expanded' ) === 'true';
ele.setAttribute( 'aria-expanded', ! isExpanded );
// If the list was not expanded, remove the display-none class before animating.
if ( ! isExpanded ) {
ulElement.classList.remove( 'uagb-toc__list--hidden-child' );
}
// All the rest should happen after the display is updated.
setTimeout( () => {
if ( isExpanded ) {
ulElement.style.maxHeight = '0px';
ulElement.style.overflow = 'hidden';
} else {
ulElement.style.maxHeight = ulElement.dataset.originalMaxHeight;
}
ele.classList.toggle( 'list-open', ! isExpanded );
ele.classList.toggle( 'list-collapsed', isExpanded );
// If this was expanded, add a class to remove the padding inside the UL of the collapsible list after it has collapsed. Else just remove that class.
ulElement.classList.toggle( 'uagb-toc__list--child-of-closed-list' );
}, 0 );
// If the list was expanded, add the display-none class after animating.
if ( isExpanded ) {
setTimeout( () => {
ulElement.classList.add( 'uagb-toc__list--hidden-child' );
}, 300 );
}
};
// Add click and keydown event listeners
ele.addEventListener( 'click', handleToggle );
ele.addEventListener( 'keydown', ( event ) => {
if ( event.key === 'Enter' || event.key === ' ' ) {
event.preventDefault();
handleToggle( event );
}
} );
ele.setAttribute( 'aria-expanded', ele.classList.contains( 'list-open' ) );
} );
// Initial collapse state handling
if ( attr?.initiallyCollapseList ) {
ulElements.forEach( ( ul ) => {
// Check if there's a span sibling at the same level
const hasSiblingSpan = ul.parentElement.querySelector( 'span' );
if ( hasSiblingSpan ) {
ul.style.maxHeight = '0px';
ul.style.overflow = 'hidden';
// If this is initially collapsed, then add the closed padding class.
ul.classList.add( 'uagb-toc__list--child-of-closed-list' );
// After the animation has ended, set display to none so that screenreaders avoide the hidden content.
setTimeout( () => {
ul.classList.add( 'uagb-toc__list--hidden-child' );
}, 300 );
const spanElement = ul.parentElement.querySelector( '.list-open' );
if ( spanElement ) {
spanElement.setAttribute( 'aria-expanded', 'false' );
spanElement.classList.remove( 'list-open' );
spanElement.classList.add( 'list-collapsed' );
}
}
} );
}
}
},
init( id, attr ) {
if ( ( attr?.makeCollapsible && ! attr?.initialCollapse ) || ! attr?.makeCollapsible ) {
UAGBTableOfContents._initCollapsableList( id, attr );
}
const document_element = UAGBTableOfContents._getDocumentElement();
if ( document.querySelector( '.uagb-toc__list' ) !== null ) {
document.querySelector( '.uagb-toc__list' ).addEventListener(
'click',
UAGBTableOfContents._scroll
);
}
if ( document.querySelector( '.uagb-toc__scroll-top' ) !== null ) {
document.querySelector( '.uagb-toc__scroll-top' ).addEventListener(
'click',
UAGBTableOfContents._scrollTop
);
}
if( attr?.makeCollapsible ){
const elementToOpen = document_element.querySelector( id );
/* We need the following fail-safe click listener cause an usual click-listener
* will fail in case the 'Make TOC Collapsible' is not enabled right from the start/page-load.
*/
if ( uagbTOCCollapseListener ) {
document_element.addEventListener( 'click', collapseListener );
uagbTOCCollapseListener = false;
}
function collapseListener( event ) {
const element = event.target;
// These two conditions help us target the required element (collapsible icon beside TOC heading).
const condition1 = element?.tagName === 'path' || element?.tagName === 'svg' || element?.tagName === 'DIV'; // Check if the clicked element type is either path or SVG or Title DIV.
const condition2 = element?.className === 'uagb-toc__title' || element?.parentNode?.className === 'uagb-toc__title' || element?.parentNode?.tagName === 'svg'; // Check if the clicked element's parent has the required class.
if ( condition1 && condition2 ) {
const $root = element?.closest( `.wp-block-uagb-table-of-contents${id}` );
const tocListWrapEl = elementToOpen?.querySelector( '.wp-block-uagb-table-of-contents .uagb-toc__list-wrap' );
// If not have the tocListWrapEl then return false!
if ( ! tocListWrapEl ) {
return;
}
if ( $root?.classList?.contains( 'uagb-toc__collapse' ) ) {
$root?.classList?.remove( 'uagb-toc__collapse' );
UAGBTableOfContents._slideDown(
tocListWrapEl,
500,
id,
attr
);
} else {
$root?.classList?.add( 'uagb-toc__collapse' );
UAGBTableOfContents._slideUp(
tocListWrapEl,
500
);
}
}
}
}
document.addEventListener(
'scroll',
UAGBTableOfContents._showHideScroll
);
},
_slideUp( target, duration ) {
target.style.transitionProperty = 'height, margin, padding';
target.style.transitionDuration = duration + 'ms';
target.style.boxSizing = 'border-box';
target.style.height = target.offsetHeight + 'px';
target.offsetHeight; // eslint-disable-line no-unused-expressions
target.style.overflow = 'hidden';
target.style.height = 0;
target.style.paddingTop = 0;
target.style.paddingBottom = 0;
target.style.marginTop = 0;
target.style.marginBottom = 0;
window.setTimeout( () => {
target.style.display = 'none';
target.style.removeProperty( 'height' );
target.style.removeProperty( 'padding-top' );
target.style.removeProperty( 'padding-bottom' );
target.style.removeProperty( 'margin-top' );
target.style.removeProperty( 'margin-bottom' );
target.style.removeProperty( 'overflow' );
target.style.removeProperty( 'transition-duration' );
target.style.removeProperty( 'transition-property' );
}, duration );
},
_slideDown( target, duration, id, attr ) {
target.style?.removeProperty( 'display' );
let display = window?.getComputedStyle( target ).display;
if ( display === 'none' ) display = 'block';
target.style.display = display;
const height = target.offsetHeight;
target.style.overflow = 'hidden';
target.style.height = 0;
target.style.paddingTop = 0;
target.style.paddingBottom = 0;
target.style.marginTop = 0;
target.style.marginBottom = 0;
target.offsetHeight; // eslint-disable-line no-unused-expressions
target.style.boxSizing = 'border-box';
target.style.transitionProperty = 'height, margin, padding';
target.style.transitionDuration = duration + 'ms';
target.style.height = height + 'px';
target.style.removeProperty( 'padding-top' );
target.style.removeProperty( 'padding-bottom' );
target.style.removeProperty( 'margin-top' );
target.style.removeProperty( 'margin-bottom' );
window.setTimeout( () => {
target.style.removeProperty( 'height' );
target.style.removeProperty( 'overflow' );
target.style.removeProperty( 'transition-duration' );
target.style.removeProperty( 'transition-property' );
UAGBTableOfContents._initCollapsableList( id, attr );
}, duration );
},
hyperLinks() {
const hash = window.location.hash.substring( 0 );
if ( '' === hash || /[^a-z0-9_-]$/.test( hash ) ) {
return;
}
function escapeSelector( selector ) {
return selector.replace( /([.#$+\^*[\](){}|\\])/g, '\\$1' );
}
let hashId = encodeURI( hash.substring( 0 ) );
hashId = escapeSelector( hash );
const selectedAnchor = document?.querySelector( hashId );
if ( null === selectedAnchor ) {
return;
}
const node = document.querySelector( '.wp-block-uagb-table-of-contents' );
scrollOffset = node.getAttribute( 'data-offset' );
const offset = document.querySelector( hash ).offsetTop;
if ( null !== offset ) {
scroll( {
top: offset - scrollOffset,
behavior: 'smooth',
} );
}
},
_showHideScroll() {
scrollElement = document.querySelector( '.uagb-toc__scroll-top' );
if ( null !== scrollElement ) {
if ( window.scrollY > 300 ) {
if ( scrolltoTop ) {
scrollElement.classList.add( 'uagb-toc__show-scroll' );
} else {
scrollElement.classList.remove( 'uagb-toc__show-scroll' );
}
} else {
scrollElement.classList.remove( 'uagb-toc__show-scroll' );
}
}
},
_scrollTop() {
window.scrollTo( {
top: 0,
behavior: 'smooth',
} );
},
_scroll( e ) {
e.preventDefault();
let hash = e.target.getAttribute( 'href' );
/*
* There may be instances where we don't receive the hash value from the href attribute.
* This can occur when the click event's target is not an anchor tag.
* However, the target element might be nested within an anchor tag.
* In these cases, we need to check if the parent element has an available hash value.
*/
if ( ! hash && e.target.tagName && e.target.tagName !== 'A' ) {
const getHash = e.target.closest( 'a' );
// Add a null check for getHash to prevent errors
if ( getHash ) {
hash = getHash.getAttribute( 'href' );
}
}
if ( hash ) {
const node = document.querySelector( '.wp-block-uagb-table-of-contents' );
scrollData = node.getAttribute( 'data-scroll' );
scrollOffset = node.getAttribute( 'data-offset' );
let offset = null;
hash = hash.substring( 1 );
if ( document?.querySelector( "[id='" + hash + "']" ) ) {
offset = document.querySelector( "[id='" + hash + "']" )?.getBoundingClientRect().top + window.scrollY;
}
if ( scrollData ) {
if ( null !== offset ) {
scroll( {
top: offset - scrollOffset,
behavior: 'smooth',
} );
}
} else {
scroll( {
top: offset,
behavior: 'auto',
} );
}
}
},
selectDomElement( id ){
// Select id class but not with script init class.
const thisScope = document.querySelector( `${ id }:not(.script-init)` );
if ( ! thisScope ) {
return null;
}
// Add script init class to avoid reinit.
thisScope.classList.add( 'script-init' );
return thisScope;
},
parseTocSlug( slug ) {
// If not have the element then return false!
if ( ! slug ) {
return slug;
}
const parsedSlug = slug
.toString()
.toLowerCase()
.replace( /\…+/g, '' ) // Remove multiple …
.replace( /\u2013|\u2014/g, '' ) // Remove long dash
.replace( /&(amp;)/g, '' ) // Remove &
.replace( /[&]nbsp[;]/gi, '-' ) // Replace inseccable spaces
.replace( /[^a-zA-Z0-9\u00C0-\u017F _-]/g, '' ) // Keep only alphnumeric, space, -, _ and latin characters.
.replace( /&(mdash;)/g, '' ) // Remove long dash
.replace( /\s+/g, '-' ) // Replace spaces with -
.replace( /[&\/\\#,^!+()$~%.\[\]'":*?;-_<>{}@‘’”“|]/g, '' ) // Remove special chars
.replace( /\-\-+/g, '-' ) // Replace multiple - with single -
.replace( /^-+/, '' ) // Trim - from start of text
.replace( /-+$/, '' ); // Trim - from end of text
return decodeURI( encodeURIComponent( parsedSlug ) );
},
mapTocAnchorsForHref( anchors ) {
for ( const anchor of anchors ) {
// Update the href attribute with text content and text content should be parsed.
const href = anchor.textContent;
const parsedHref = UAGBTableOfContents.parseTocSlug( href );
anchor.setAttribute( 'href', `#${parsedHref}` );
}
},
/**
* Alter the_content.
*
* @param {Object} attr
* @param {string} id
*/
_run( attr, id ) {
// Add setTime
setTimeout( function () {
UAGBTableOfContents._runWithTimeOut( attr, id );
}, 500 );
},
_runWithTimeOut( attr, id ) {
const $thisScope = UAGBTableOfContents.selectDomElement( id );
if ( ! $thisScope ) {
return;
}
if ( $thisScope.querySelector( '.uag-toc__collapsible-wrap' ) !== null ) {
if ( $thisScope.querySelector( '.uag-toc__collapsible-wrap' ).length > 0 ) {
$thisScope.querySelector( '.uagb-toc__title-wrap' ).classList.add( 'uagb-toc__is-collapsible' );
}
}
const allowedHTags = [];
let allowedHTagStr;
if ( undefined !== attr.mappingHeaders ) {
attr.mappingHeaders.forEach( function ( h_tag, index ) {
// eslint-disable-next-line no-unused-expressions
h_tag === true ? allowedHTags.push( 'h' + ( index + 1 ) ) : null;
} );
allowedHTagStr = null !== allowedHTags ? allowedHTags.join( ',' ) : '';
}
const allHeader =
undefined !== allowedHTagStr && '' !== allowedHTagStr
? document.body.querySelectorAll( allowedHTagStr )
: document.body.querySelectorAll( 'h1, h2, h3, h4, h5, h6' );
if ( 0 !== allHeader.length ) {
const tocListWrap = $thisScope.querySelector( '.uagb-toc__list-wrap' );
if ( ! tocListWrap ) {
return;
}
const divsArr = Array.from( allHeader );
const aTags = tocListWrap.getElementsByTagName( 'a' );
// Map the anchors to their hrefs to ensure that the hrefs are is correct.
UAGBTableOfContents.mapTocAnchorsForHref( aTags );
/* Logic for Remove duplicate heading with same HTML tag and create an new array with duplicate entries start here. */
const ArrayOfDuplicateElements = function ( headingArray = [] ) {
const arrayWithDuplicateEntries = [];
headingArray.reduce( ( temporaryArray, currentVal ) => {
if ( ! temporaryArray.some( ( item ) => item.innerText === currentVal.innerText ) ) {
temporaryArray.push( currentVal );
} else {
arrayWithDuplicateEntries.push( currentVal );
}
return temporaryArray;
}, [] );
return arrayWithDuplicateEntries;
};
const duplicateHeadings = ArrayOfDuplicateElements( divsArr );
/* Logic for Remove duplicate heading with same HTML tag and create an new array with duplicate entries ends here. */
for ( let i = 0; i < divsArr.length; i++ ) {
let headerText = UAGBTableOfContents.parseTocSlug( divsArr[ i ].innerText );
if ( '' !== divsArr[ i ].innerText ) {
if ( headerText.length < 1 ) {
const searchText = divsArr[ i ].innerText;
for ( let j = 0; j < aTags.length; j++ ) {
if ( aTags[ j ].textContent === searchText ) {
const randomID = '#toc_' + Math.random();
aTags[ j ].setAttribute( 'href', randomID );
headerText = randomID.substring( 1 );
}
}
}
}
const span = document.createElement( 'span' );
span.id = headerText;
span.className = 'uag-toc__heading-anchor';
divsArr[ i ].prepend( span );
/* Logic for Create an unique Id for duplicate heading start here. */
for ( let k = 0; k < duplicateHeadings.length; k++ ) {
const randomID = '#toc_' + Math.random();
duplicateHeadings[ k ]
?.querySelector( '.uag-toc__heading-anchor' )
?.setAttribute( 'id', randomID.substring( 1 ) );
const anchorElements = Array.from( tocListWrap.getElementsByTagName( 'a' ) );
const duplicateHeadingsInTOC = ArrayOfDuplicateElements( anchorElements );
for ( let l = 0; l < duplicateHeadingsInTOC.length; l++ ) {
duplicateHeadingsInTOC[ k ]?.setAttribute( 'href', randomID );
}
}
/* Logic for Create an unique Id for duplicate heading ends here. */
}
}
scrolltoTop = attr.scrollToTop;
const scrollToTopSvg =
'<svg xmlns="https://www.w3.org/2000/svg" xmlns:xlink="https://www.w3.org/1999/xlink" version="1.1" id="Layer_1" x="0px" y="0px" width="26px" height="16.043px" viewBox="57 35.171 26 16.043" enable-background="new 57 35.171 26 16.043" xml:space="preserve"><path d="M57.5,38.193l12.5,12.5l12.5-12.5l-2.5-2.5l-10,10l-10-10L57.5,38.193z"/></svg>';
scrollElement = document.querySelector( '.uagb-toc__scroll-top' );
if ( scrollElement === null ) {
const scrollToTopDiv = document.createElement( 'div' );
scrollToTopDiv.classList.add( 'uagb-toc__scroll-top' );
scrollToTopDiv.innerHTML = scrollToTopSvg;
document.body.appendChild( scrollToTopDiv );
}
if ( scrollElement !== null ) {
scrollElement.classList.add( 'uagb-toc__show-scroll' );
}
UAGBTableOfContents._showHideScroll();
UAGBTableOfContents.hyperLinks();
UAGBTableOfContents.init( id, attr );
},
};

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,219 @@
UAGBTabs = {
init( $selector ) {
const tabsWrap = document.querySelectorAll( $selector );
if ( ! tabsWrap ) {
return;
}
for ( let i = 0; i < tabsWrap.length; i++ ) {
UAGBTabs.addEvents( tabsWrap[ i ], $selector );
}
},
addEvents( tabsWrap, $selector ) {
// Tabs wrap has two child elements, one is tabs list (.uagb-tabs__panel) and another is tabs body (.uagb-tabs__body-wrap).
const tabsWrapChildren = tabsWrap.children;
// Verify if tabsWrapChildren has two child elements.
if ( 2 !== tabsWrapChildren.length ) {
return;
}
const tabActive = tabsWrap.getAttribute( 'data-tab-active' );
// Select tabs list (.uagb-tabs__panel) from tabsWrapChildren.
const tabLi = tabsWrapChildren[0].querySelectorAll( 'li.uagb-tab' );
// Select tabs body (.uagb-tabs__body-wrap) from tabsWrapChildren and children will be tab body container (.uagb-tabs__body-container).
const tabBody = tabsWrapChildren[1].children;
for ( let i = 0; i < tabBody.length; i++ ) {
tabBody[ i ].setAttribute( 'tabindex', '0' );
tabBody[ i ].setAttribute( 'role', 'tabpanel' );
};
// Set initial active class to Tabs body.
tabBody[ tabActive ].classList.add( 'uagb-tabs-body__active' );
// Set initial active class to Tabs li.
tabLi[ tabActive ].classList.add( 'uagb-tabs__active' );
for ( let i = 0; i < tabLi.length; i++ ) {
const tabsAnchor = tabLi[ i ].getElementsByTagName( 'a' )[ 0 ];
// Set initial li ids.
tabLi[ i ].setAttribute( 'id', 'uagb-tabs__tab' + i );
// Set initial aria attributes true for anchor tags.
tabsAnchor.setAttribute( 'aria-selected', true );
// Selected tab gets tabindex="0".
tabsAnchor.setAttribute( 'tabindex', '0' );
if ( ! tabLi[ i ].classList.contains( 'uagb-tabs__active' ) ) {
// Set aria attributes for anchor tags as false where needed.
tabsAnchor.setAttribute( 'aria-selected', false );
// Other non selected tabs get tabindex="-1".
tabsAnchor.setAttribute( 'tabindex', '-1' );
}
// Set initial data attribute for anchor tags.
tabsAnchor.setAttribute( 'data-tab', i );
tabsAnchor.mainWrapClass = $selector;
// Add Click event listener
tabsAnchor.addEventListener( 'click', function ( e ) {
UAGBTabs.tabClickEvent( e, this, this.parentElement );
} );
}
// Enable arrow navigation between tabs in the tab list
const tabsRole = tabsWrapChildren[0].querySelectorAll( '.uagb-tab a[role="tab"]' );
tabsRole.forEach( tab => {
tab.addEventListener( 'keydown', function ( e ) {
let newIndex;
const currentIndex = Array.prototype.indexOf.call( tabsRole, e.target );
if ( e.key === 'ArrowRight' ) {
// Move to the next tab, loop back to the first if at the last
newIndex = ( currentIndex + 1 ) % tabsRole.length;
tabsRole[newIndex].focus();
tabsRole[currentIndex].setAttribute( 'aria-selected', 'false' );
tabsRole[newIndex].setAttribute( 'aria-selected', 'true' );
UAGBTabs.tabClickEvent( e, tabsRole[newIndex], tabsRole[newIndex].parentElement );
e.preventDefault();
} else if ( e.key === 'ArrowLeft' ) {
// Move to the previous tab, loop to the last if at the first
newIndex = ( currentIndex - 1 + tabsRole.length ) % tabsRole.length;
tabsRole[newIndex].focus();
tabsRole[currentIndex].setAttribute( 'aria-selected', 'false' );
tabsRole[newIndex].setAttribute( 'aria-selected', 'true' );
UAGBTabs.tabClickEvent( e, tabsRole[newIndex], tabsRole[newIndex].parentElement );
e.preventDefault();
}
} );
} );
},
tabClickEvent( e, tabName, selectedLi ) {
e.preventDefault();
const tabId = tabName.getAttribute( 'data-tab' );
const tabPanel = selectedLi.closest( '.uagb-tabs__panel' );
const tabContainer = tabName.closest( '.uagb-tabs__wrap' );
const tabBodyWrap = tabContainer.querySelector( '.uagb-tabs__body-wrap' );
const tabBodyChildren = tabBodyWrap.children;
const tabSelectedBody = UAGBTabs.getChildrenWithClass( tabBodyChildren, 'uagb-inner-tab-' + tabId );
const allLi = tabPanel.querySelectorAll( 'a.uagb-tabs-list' );
// Remove old li active class.
tabPanel.querySelector( '.uagb-tabs__active' )?.classList.remove( 'uagb-tabs__active' );
//Remove old tab body active class.
UAGBTabs.getChildrenWithClass( tabBodyChildren, 'uagb-tabs-body__active' )?.classList.remove( 'uagb-tabs-body__active' );
// Set aria-selected attribute as false for old active tab.
for ( let i = 0; i < allLi.length; i++ ) {
allLi[ i ].setAttribute( 'aria-selected', false );
// Other non selected tabs get tabindex="-1".
allLi[i].setAttribute( 'tabindex', '-1' );
}
// Set selected li active class.
selectedLi.classList.add( 'uagb-tabs__active' );
// Set aria-selected attribute as true for new active tab.
tabName.setAttribute( 'aria-selected', true );
// Selected tab gets tabindex="0".
tabName.setAttribute( 'tabindex', '0' );
// Set selected tab body active class.
tabSelectedBody?.classList.add( 'uagb-tabs-body__active' );
// Set aria-hidden attribute false for selected tab body.
tabSelectedBody?.setAttribute( 'aria-hidden', false );
// Set aria-hidden attribute true for all unselected tab body.
for ( let i = 0; i < tabBodyChildren.length; i++ ) {
// If tabBodyChildren[i] has .uagb-inner-tab-' + tabId + ' then continue.
if ( tabBodyChildren[ i ].classList.contains( 'uagb-inner-tab-' + tabId ) ) {
continue;
}
tabBodyChildren[ i ].setAttribute( 'aria-hidden', true );
}
},
anchorTabId( $selector ) {
const tabsHash = window.location.hash;
if ( '' !== tabsHash && /^#uagb-tabs__tab\d$/.test( tabsHash ) ) {
const mainWrapClass = $selector;
const tabId = escape( tabsHash.substring( 1 ) );
const selectedLi = document.querySelector( '#' + tabId );
const topPos = selectedLi.getBoundingClientRect().top + window.pageYOffset;
window.scrollTo( {
top: topPos,
behavior: 'smooth',
} );
const tabNum = selectedLi.querySelector( 'a.uagb-tabs-list' ).getAttribute( 'data-tab' );
const listPanel = selectedLi.closest( '.uagb-tabs__panel' );
const tabSelectedBody = document.querySelector(
mainWrapClass + ' > .uagb-tabs__body-wrap > .uagb-inner-tab-' + tabNum
);
const tabUnselectedBody = document.querySelectorAll(
mainWrapClass +
' > .uagb-tabs__body-wrap > .uagb-tabs__body-container:not(.uagb-inner-tab-' +
tabNum +
')'
);
const allLi = selectedLi.querySelectorAll( 'a.uagb-tabs-list' );
const selectedAnchor = selectedLi.querySelector( 'a.uagb-tabs-list' );
// Remove old li active class.
listPanel.querySelector( '.uagb-tabs__active' ).classList.remove( 'uagb-tabs__active' );
// Remove old tab body active class.
document
.querySelector( mainWrapClass + ' > .uagb-tabs__body-wrap > .uagb-tabs-body__active' )
.classList.remove( 'uagb-tabs-body__active' );
// Set aria-selected attribute as false for old active tab.
for ( let i = 0; i < allLi.length; i++ ) {
allLi[ i ].setAttribute( 'tabindex', '-1' ); // Old active tab gets tabindex="-1".
allLi[ i ].setAttribute( 'aria-selected', false );
}
// Set selected li active class.
selectedLi.classList.add( 'uagb-tabs__active' );
// Set aria-selected attribute as true for new active tab.
selectedAnchor.setAttribute( 'aria-selected', true );
selectedAnchor.setAttribute( 'tabindex', '0' ); // New active tab gets tabindex="0".
// Set selected tab body active class.
tabSelectedBody.classList.add( 'uagb-tabs-body__active' );
// Set aria-hidden attribute false for selected tab body.
tabSelectedBody.setAttribute( 'aria-hidden', false );
// Set aria-hidden attribute true for all unselected tab body.
for ( let i = 0; i < tabUnselectedBody.length; i++ ) {
tabUnselectedBody[ i ].setAttribute( 'aria-hidden', true );
}
}
},
getChildrenWithClass( children, className ) {
let child = null;
for ( let i = 0; i < children.length; i++ ) {
if ( children[ i ].classList.contains( className ) ) {
child = children[ i ];
break;
}
}
return child;
}
};

View File

@@ -0,0 +1 @@
UAGBTabs={init(e){var a=document.querySelectorAll(e);if(a)for(let t=0;t<a.length;t++)UAGBTabs.addEvents(a[t],e)},addEvents(t,e){const a=t.children;if(2===a.length){t=t.getAttribute("data-tab-active");const s=a[0].querySelectorAll("li.uagb-tab"),b=a[1].children;for(let t=0;t<b.length;t++)b[t].setAttribute("tabindex","0"),b[t].setAttribute("role","tabpanel");b[t].classList.add("uagb-tabs-body__active"),s[t].classList.add("uagb-tabs__active");for(let t=0;t<s.length;t++){const r=s[t].getElementsByTagName("a")[0];s[t].setAttribute("id","uagb-tabs__tab"+t),r.setAttribute("aria-selected",!0),r.setAttribute("tabindex","0"),s[t].classList.contains("uagb-tabs__active")||(r.setAttribute("aria-selected",!1),r.setAttribute("tabindex","-1")),r.setAttribute("data-tab",t),r.mainWrapClass=e,r.addEventListener("click",function(t){UAGBTabs.tabClickEvent(t,this,this.parentElement)})}const i=a[0].querySelectorAll('.uagb-tab a[role="tab"]');i.forEach(t=>{t.addEventListener("keydown",function(t){let e;var a=Array.prototype.indexOf.call(i,t.target);"ArrowRight"===t.key?(e=(a+1)%i.length,i[e].focus(),i[a].setAttribute("aria-selected","false"),i[e].setAttribute("aria-selected","true"),UAGBTabs.tabClickEvent(t,i[e],i[e].parentElement),t.preventDefault()):"ArrowLeft"===t.key&&(e=(a-1+i.length)%i.length,i[e].focus(),i[a].setAttribute("aria-selected","false"),i[e].setAttribute("aria-selected","true"),UAGBTabs.tabClickEvent(t,i[e],i[e].parentElement),t.preventDefault())})})}},tabClickEvent(t,e,a){t.preventDefault();var s=e.getAttribute("data-tab");const b=a.closest(".uagb-tabs__panel"),i=e.closest(".uagb-tabs__wrap"),r=i.querySelector(".uagb-tabs__body-wrap").children,l=UAGBTabs.getChildrenWithClass(r,"uagb-inner-tab-"+s),n=b.querySelectorAll("a.uagb-tabs-list");b.querySelector(".uagb-tabs__active")?.classList.remove("uagb-tabs__active"),UAGBTabs.getChildrenWithClass(r,"uagb-tabs-body__active")?.classList.remove("uagb-tabs-body__active");for(let t=0;t<n.length;t++)n[t].setAttribute("aria-selected",!1),n[t].setAttribute("tabindex","-1");a.classList.add("uagb-tabs__active"),e.setAttribute("aria-selected",!0),e.setAttribute("tabindex","0"),l?.classList.add("uagb-tabs-body__active"),l?.setAttribute("aria-hidden",!1);for(let t=0;t<r.length;t++)r[t].classList.contains("uagb-inner-tab-"+s)||r[t].setAttribute("aria-hidden",!0)},anchorTabId(t){const e=window.location.hash;if(""!==e&&/^#uagb-tabs__tab\d$/.test(e)){var a=escape(e.substring(1));const s=document.querySelector("#"+a);a=s.getBoundingClientRect().top+window.pageYOffset,a=(window.scrollTo({top:a,behavior:"smooth"}),s.querySelector("a.uagb-tabs-list").getAttribute("data-tab"));const b=s.closest(".uagb-tabs__panel"),i=document.querySelector(t+" > .uagb-tabs__body-wrap > .uagb-inner-tab-"+a),r=document.querySelectorAll(t+" > .uagb-tabs__body-wrap > .uagb-tabs__body-container:not(.uagb-inner-tab-"+a+")"),l=s.querySelectorAll("a.uagb-tabs-list"),n=s.querySelector("a.uagb-tabs-list");b.querySelector(".uagb-tabs__active").classList.remove("uagb-tabs__active"),document.querySelector(t+" > .uagb-tabs__body-wrap > .uagb-tabs-body__active").classList.remove("uagb-tabs-body__active");for(let t=0;t<l.length;t++)l[t].setAttribute("tabindex","-1"),l[t].setAttribute("aria-selected",!1);s.classList.add("uagb-tabs__active"),n.setAttribute("aria-selected",!0),n.setAttribute("tabindex","0"),i.classList.add("uagb-tabs-body__active"),i.setAttribute("aria-hidden",!1);for(let t=0;t<r.length;t++)r[t].setAttribute("aria-hidden",!0)}},getChildrenWithClass(e,a){let s=null;for(let t=0;t<e.length;t++)if(e[t].classList.contains(a)){s=e[t];break}return s}};

View File

@@ -0,0 +1,84 @@
window.UAGBTestimonialCarousel = {
_setHeight( scope ) {
if ( scope.length > 0 ) {
const postWrapper = scope[ 0 ].querySelectorAll( '.slick-slide' ),
postActive = scope[ 0 ].querySelectorAll( '.slick-slide.slick-active' );
let maxHeight = -1,
wrapperHeight = -1,
postActiveHeight = -1;
Object.keys( postActive ).forEach( ( key ) => {
const thisHeight = postActive[ key ].offsetHeight,
blogPost = postActive[ key ].querySelector( '.uagb-testimonial__wrap' ),
blogPostHeight = blogPost.offsetHeight;
if ( maxHeight < blogPostHeight ) {
maxHeight = blogPostHeight;
postActiveHeight = maxHeight + 15;
}
if ( wrapperHeight < thisHeight ) {
wrapperHeight = thisHeight;
}
} );
Object.keys( postActive ).forEach( ( key ) => {
const selector = postActive[ key ].querySelector( '.uagb-testimonial__wrap' );
selector.style.height = maxHeight + 'px';
} );
let selector = scope[ 0 ].querySelector( '.slick-list' );
selector.style.height = postActiveHeight + 'px';
maxHeight = -1;
wrapperHeight = -1;
Object.keys( postWrapper ).forEach( ( key ) => {
const $this = postWrapper[ key ];
if ( $this.classList.contains( 'slick-active' ) ) {
return true;
}
selector = $this.querySelector( '.uagb-testimonial__wrap' );
const blogPostHeight = selector.offsetHeight;
selector.style.height = blogPostHeight + 'px';
} );
}
},
_unSetHeight( scope ) {
if ( scope.length > 0 ) {
const postWrapper = scope[ 0 ].querySelectorAll( '.slick-slide' ),
postActive = scope[ 0 ].querySelectorAll( '.slick-slide.slick-active' );
Object.keys( postActive ).forEach( ( key ) => {
const selector = postActive[ key ].querySelector( '.uagb-tm__content' );
selector.style.height = 'auto';
} );
Object.keys( postActive ).forEach( ( key ) => {
const $this = postWrapper[ key ];
if ( $this.classList.contains( 'slick-active' ) ) {
return true;
}
const selector = $this.querySelector( '.uagb-tm__content' );
selector.style.height = 'auto';
} );
}
},
};
// Set Carousel Height for Customiser.
// eslint-disable-next-line no-unused-vars
function uagb_carousel_height( id ) {
const wrap = document.querySelector( '#wpwrap .uagb-block-' + id + ' .is-carousel' );
if ( wrap ) {
window.UAGBTestimonialCarousel._setHeight( wrap );
}
}
// Unset Carousel Height for Customiser.
// eslint-disable-next-line no-unused-vars
function uagb_carousel_unset_height( id ) {
const wrap = document.querySelector( '#wpwrap .uagb-slick-carousel.uagb-block-' + id );
if ( wrap ) {
window.UAGBTestimonialCarousel._unSetHeight( wrap );
}
}

View File

@@ -0,0 +1 @@
function uagb_carousel_height(e){e=document.querySelector("#wpwrap .uagb-block-"+e+" .is-carousel");e&&window.UAGBTestimonialCarousel._setHeight(e)}function uagb_carousel_unset_height(e){e=document.querySelector("#wpwrap .uagb-slick-carousel.uagb-block-"+e);e&&window.UAGBTestimonialCarousel._unSetHeight(e)}window.UAGBTestimonialCarousel={_setHeight(e){if(0<e.length){const o=e[0].querySelectorAll(".slick-slide"),r=e[0].querySelectorAll(".slick-slide.slick-active");let l=-1,s=-1,c=-1,i=(Object.keys(r).forEach(e=>{var t=r[e].offsetHeight,e=r[e].querySelector(".uagb-testimonial__wrap").offsetHeight;l<e&&(l=e,c=l+15),s<t&&(s=t)}),Object.keys(r).forEach(e=>{const t=r[e].querySelector(".uagb-testimonial__wrap");t.style.height=l+"px"}),e[0].querySelector(".slick-list"));i.style.height=c+"px",l=-1,s=-1,Object.keys(o).forEach(e=>{const t=o[e];if(t.classList.contains("slick-active"))return!0;e=(i=t.querySelector(".uagb-testimonial__wrap")).offsetHeight;i.style.height=e+"px"})}},_unSetHeight(e){if(0<e.length){const s=e[0].querySelectorAll(".slick-slide"),l=e[0].querySelectorAll(".slick-slide.slick-active");Object.keys(l).forEach(e=>{const t=l[e].querySelector(".uagb-tm__content");t.style.height="auto"}),Object.keys(l).forEach(e=>{const t=s[e];if(t.classList.contains("slick-active"))return!0;const l=t.querySelector(".uagb-tm__content");l.style.height="auto"})}}};

View File

@@ -0,0 +1,196 @@
window.addEventListener( 'DOMContentLoaded', uagbTimelineInit );
window.addEventListener( 'resize', uagbTimelineInit );
window.addEventListener( 'scroll', uagbTimelineInit );
document.addEventListener( 'UAGTimelineEditor', uagbTimelineInit );
// Callback function for all event listeners.
function uagbTimelineInit() {
const iframeEl = document.querySelector( `iframe[name='editor-canvas']` );
let mainDiv;
if ( iframeEl ) {
mainDiv = iframeEl.contentDocument.querySelectorAll( '.uagb-timeline' );
} else {
mainDiv = document.querySelectorAll( '.uagb-timeline' );
}
const timeline = mainDiv;
if ( timeline.length === 0 ) {
return;
}
for ( const content of timeline ) {
const lineInner = content.querySelector( '.uagb-timeline__line__inner' );
const lineOuter = content.querySelector( '.uagb-timeline__line' );
const iconClass = content.querySelectorAll( '.uagb-timeline__marker' );
const timelineField = content.querySelector( '.uagb-timeline__field:nth-last-child(2)' );
const cardLast = timelineField
? timelineField
: content.querySelector( '.block-editor-block-list__block:last-child' );
const timelineStartIcon = iconClass[ 0 ];
const timelineEndIcon = iconClass[ iconClass.length - 1 ];
setTimeout( () => {
lineOuter.style.top = timelineStartIcon?.offsetTop + 'px';
}, 300 );
const timelineCardHeight = cardLast?.offsetHeight;
if ( content.classList.contains( 'uagb-timeline__arrow-center' ) ) {
lineOuter.style.bottom = timelineEndIcon?.offsetTop + 'px';
} else if ( content.classList.contains( 'uagb-timeline__arrow-top' ) ) {
const topHeight = timelineCardHeight - timelineEndIcon?.offsetTop;
lineOuter.style.bottom = topHeight + 'px';
} else if ( content.classList.contains( 'uagb-timeline__arrow-bottom' ) ) {
const bottomHeight = timelineCardHeight - timelineEndIcon?.offsetTop;
lineOuter.style.bottom = bottomHeight + 'px';
}
const connectorHeight = 3 * iconClass[ 0 ]?.offsetHeight;
const viewportHeight = document?.documentElement?.clientHeight;
const viewportHeightHalf = viewportHeight / 2 + connectorHeight;
const body = document.body;
const html = document.documentElement;
const height = Math.max(
body.scrollHeight,
body.offsetHeight,
html.clientHeight,
html.scrollHeight,
html.offsetHeight
);
const timelineEndIconOffsetBottom = height - timelineEndIcon?.getBoundingClientRect()?.top;
const totalTimelineLineHeight =
height - timelineStartIcon?.getBoundingClientRect()?.top - timelineEndIconOffsetBottom;
const startFlag =
timelineStartIcon?.getBoundingClientRect()?.top +
window?.scrollY -
( window?.innerHeight - window?.innerHeight / 3 );
if ( startFlag < document?.documentElement?.scrollTop ) {
const tscrollPerc =
( ( document?.documentElement?.scrollTop - startFlag ) / totalTimelineLineHeight ) * 100;
const percHeight = ( totalTimelineLineHeight / 100 ) * tscrollPerc;
if ( percHeight < totalTimelineLineHeight + 60 ) {
lineInner.style.height = percHeight + 'px';
}
}
// Icon bg color and icon color
let timelineIconPos, timelineCardPos;
let timelineIconTop, timelineCardTop;
const timelineIcon = content.querySelectorAll( '.uagb-timeline__marker' );
let animateBorder = content.querySelectorAll( '.uagb-timeline__field' );
if ( animateBorder.length === 0 ) {
animateBorder = content.querySelectorAll( '.uagb-timeline__animate-border' );
}
for ( let j = 0; j < timelineIcon.length; j++ ) {
timelineIconPos = timelineIcon[ j ].lastElementChild.getBoundingClientRect().top + window.scrollY;
timelineCardPos = animateBorder[ j ].lastElementChild.getBoundingClientRect().top + window.scrollY;
timelineIconTop = timelineIconPos - document.documentElement.scrollTop;
timelineCardTop = timelineCardPos - document.documentElement.scrollTop;
if ( timelineCardTop < viewportHeightHalf ) {
animateBorder[ j ].classList.remove( 'out-view' );
animateBorder[ j ].classList.add( 'in-view' );
} else {
// Remove classes if element is below than half of viewport.
animateBorder[ j ].classList.add( 'out-view' );
animateBorder[ j ].classList.remove( 'in-view' );
}
if ( timelineIconTop < viewportHeightHalf ) {
// Add classes if element is above than half of viewport.
timelineIcon[ j ].classList.remove( 'uagb-timeline__out-view-icon' );
timelineIcon[ j ].classList.add( 'uagb-timeline__in-view-icon' );
} else {
// Remove classes if element is below than half of viewport.
timelineIcon[ j ].classList.add( 'uagb-timeline__out-view-icon' );
timelineIcon[ j ].classList.remove( 'uagb-timeline__in-view-icon' );
}
}
}
}
// eslint-disable-next-line no-unused-vars
function UAGBTimelineClasses( attributes, id ) {
const timeline = document.querySelectorAll( id );
if ( timeline.length === 0 ) {
return;
}
const deviceWidth = Math.max( window.screen.width, window.innerWidth );
for ( const content of timeline ) {
content.classList.remove(
'uagb-timeline__left-block',
'uagb-timeline__right-block',
'uagb-timeline__center-block'
);
let device = '';
if ( deviceWidth <= uagb_timeline_data.mobile_breakpoint ) {
device = 'Mobile';
} else if ( deviceWidth <= uagb_timeline_data.tablet_breakpoint ) {
device = 'Tablet';
}
if ( 'left' === attributes[ 'timelinAlignment' + device ] ) {
content.classList.add( 'uagb-timeline__left-block' );
} else if ( 'right' === attributes[ 'timelinAlignment' + device ] ) {
content.classList.add( 'uagb-timeline__right-block' );
} else {
content.classList.add( 'uagb-timeline__center-block' );
}
let timelineChild = content.querySelectorAll( '.wp-block-uagb-content-timeline-child' );
let childIndex = 0;
if ( 0 === timelineChild.length ) {
timelineChild = content.querySelectorAll( '.uagb-timeline__field' );
}
for ( const child of timelineChild ) {
child.classList.remove( 'uagb-timeline__left', 'uagb-timeline__right' );
const timelineMarker = child.querySelectorAll( '.uagb-timeline__marker' )[ 0 ];
timelineMarker.classList.remove( 'uagb-timeline__left', 'uagb-timeline__right' );
const timeLineEventInner = child.querySelectorAll( '.uagb-timeline__events-inner-new' )[ 0 ];
timeLineEventInner.classList.remove( 'uagb-timeline__day-right', 'uagb-timeline__day-left' );
if ( 'left' === attributes[ 'timelinAlignment' + device ] ) {
child.classList.add( 'uagb-timeline__left' );
timelineMarker.classList.add( 'uagb-timeline__left' );
timeLineEventInner.classList.add( 'uagb-timeline__day-left' );
} else if ( 'right' === attributes[ 'timelinAlignment' + device ] ) {
child.classList.add( 'uagb-timeline__right' );
timelineMarker.classList.add( 'uagb-timeline__left' );
timeLineEventInner.classList.add( 'uagb-timeline__day-right' );
} else if ( 'center' === attributes[ 'timelinAlignment' + device ] ) {
if ( childIndex % 2 === 0 ) {
child.classList.add( 'uagb-timeline__right' );
timelineMarker.classList.add( 'uagb-timeline__right' );
timeLineEventInner.classList.add( 'uagb-timeline__day-right' );
} else {
child.classList.add( 'uagb-timeline__left' );
timelineMarker.classList.add( 'uagb-timeline__left' );
timeLineEventInner.classList.add( 'uagb-timeline__day-left' );
}
}
childIndex++;
}
}
}

View File

@@ -0,0 +1 @@
function uagbTimelineInit(){const e=document.querySelector("iframe[name='editor-canvas']");let t;var r=t=(e?e.contentDocument:document).querySelectorAll(".uagb-timeline");if(0!==r.length)for(const a of r){const _=a.querySelector(".uagb-timeline__line__inner"),s=a.querySelector(".uagb-timeline__line");var i=a.querySelectorAll(".uagb-timeline__marker"),l=a.querySelector(".uagb-timeline__field:nth-last-child(2)"),l=l||a.querySelector(".block-editor-block-list__block:last-child");const c=i[0],m=i[i.length-1];setTimeout(()=>{s.style.top=c?.offsetTop+"px"},300);var n,u,o,l=l?.offsetHeight,l=(a.classList.contains("uagb-timeline__arrow-center")?s.style.bottom=m?.offsetTop+"px":a.classList.contains("uagb-timeline__arrow-top")?(n=l-m?.offsetTop,s.style.bottom=n+"px"):a.classList.contains("uagb-timeline__arrow-bottom")&&(n=l-m?.offsetTop,s.style.bottom=n+"px"),3*i[0]?.offsetHeight),g=document?.documentElement?.clientHeight/2+l,i=document.body,l=document.documentElement,i=Math.max(i.scrollHeight,i.offsetHeight,l.clientHeight,l.scrollHeight,l.offsetHeight),l=i-m?.getBoundingClientRect()?.top,i=i-c?.getBoundingClientRect()?.top-l,l=c?.getBoundingClientRect()?.top+window?.scrollY-(window?.innerHeight-window?.innerHeight/3);l<document?.documentElement?.scrollTop&&((l=i/100*((document?.documentElement?.scrollTop-l)/i*100))<60+i&&(_.style.height=l+"px"));const d=a.querySelectorAll(".uagb-timeline__marker");let t=a.querySelectorAll(".uagb-timeline__field");0===t.length&&(t=a.querySelectorAll(".uagb-timeline__animate-border"));for(let e=0;e<d.length;e++)o=d[e].lastElementChild.getBoundingClientRect().top+window.scrollY,u=t[e].lastElementChild.getBoundingClientRect().top+window.scrollY,o=o-document.documentElement.scrollTop,u-document.documentElement.scrollTop<g?(t[e].classList.remove("out-view"),t[e].classList.add("in-view")):(t[e].classList.add("out-view"),t[e].classList.remove("in-view")),o<g?(d[e].classList.remove("uagb-timeline__out-view-icon"),d[e].classList.add("uagb-timeline__in-view-icon")):(d[e].classList.add("uagb-timeline__out-view-icon"),d[e].classList.remove("uagb-timeline__in-view-icon"))}}function UAGBTimelineClasses(l,e){e=document.querySelectorAll(e);if(0!==e.length){var n=Math.max(window.screen.width,window.innerWidth);for(const o of e){o.classList.remove("uagb-timeline__left-block","uagb-timeline__right-block","uagb-timeline__center-block");let e="",t=(n<=uagb_timeline_data.mobile_breakpoint?e="Mobile":n<=uagb_timeline_data.tablet_breakpoint&&(e="Tablet"),"left"===l["timelinAlignment"+e]?o.classList.add("uagb-timeline__left-block"):"right"===l["timelinAlignment"+e]?o.classList.add("uagb-timeline__right-block"):o.classList.add("uagb-timeline__center-block"),o.querySelectorAll(".wp-block-uagb-content-timeline-child")),i=0;for(const a of t=0===t.length?o.querySelectorAll(".uagb-timeline__field"):t){a.classList.remove("uagb-timeline__left","uagb-timeline__right");const s=a.querySelectorAll(".uagb-timeline__marker")[0],c=(s.classList.remove("uagb-timeline__left","uagb-timeline__right"),a.querySelectorAll(".uagb-timeline__events-inner-new")[0]);c.classList.remove("uagb-timeline__day-right","uagb-timeline__day-left"),"left"===l["timelinAlignment"+e]?(a.classList.add("uagb-timeline__left"),s.classList.add("uagb-timeline__left"),c.classList.add("uagb-timeline__day-left")):"right"===l["timelinAlignment"+e]?(a.classList.add("uagb-timeline__right"),s.classList.add("uagb-timeline__left"),c.classList.add("uagb-timeline__day-right")):"center"===l["timelinAlignment"+e]&&(i%2==0?(a.classList.add("uagb-timeline__right"),s.classList.add("uagb-timeline__right"),c.classList.add("uagb-timeline__day-right")):(a.classList.add("uagb-timeline__left"),s.classList.add("uagb-timeline__left"),c.classList.add("uagb-timeline__day-left"))),i++}}}}window.addEventListener("DOMContentLoaded",uagbTimelineInit),window.addEventListener("resize",uagbTimelineInit),window.addEventListener("scroll",uagbTimelineInit),document.addEventListener("UAGTimelineEditor",uagbTimelineInit);

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,25 @@
UAGBButtonChild = {
init( $selector ) {
const block = document.querySelector( $selector );
if ( ! block ) {
return;
}
block.addEventListener( 'focusin', () => {
document.addEventListener( 'keydown', this.handleKeyDown );
} );
block.addEventListener( 'focusout', () => {
document.removeEventListener( 'keydown', this.handleKeyDown );
} );
},
handleKeyDown( e ) {
if ( e.key === ' ' || e.key === 'Spacebar' ) {
// Checks if the target is an <a> tag with the uagb specific class
if ( e.target.tagName === 'A' && e.target.classList.contains( 'uagb-buttons-repeater' ) ) {
e.preventDefault();
e.target.click();
}
}
},
};

View File

@@ -0,0 +1 @@
UAGBButtonChild={init(e){const t=document.querySelector(e);t&&(t.addEventListener("focusin",()=>{document.addEventListener("keydown",this.handleKeyDown)}),t.addEventListener("focusout",()=>{document.removeEventListener("keydown",this.handleKeyDown)}))},handleKeyDown(e){" "!==e.key&&"Spacebar"!==e.key||"A"===e.target.tagName&&e.target.classList.contains("uagb-buttons-repeater")&&(e.preventDefault(),e.target.click())}};

View File

@@ -0,0 +1,258 @@
// Global uagb_countdown_data.
UAGBCountdown = {
elements: {},
countdownInterval: {},
cookie_slug: uagb_countdown_data.site_name_slug,
cache: {},
editorInit( mainSelector, data = {}, countdownRef ) {
// When a new Countdown timer block is added, the timeModified value received is 'false',
// even though it's attribute has been set to 'true'.
// Hence, we need to ensure here that the dynamic defaults are followed.
if ( ! data.timeModified ) {
const d = new Date();
// Set the default end time to 7 days later.
d.setMilliseconds( d.getMilliseconds() + 7 * 24 * 60 * 60 * 1000 );
data.endDateTime = d;
}
this.elements[ mainSelector ] = this.getElement( mainSelector );
this.countdownInterval[ mainSelector ] = setInterval( () => {
this.updateCountdown( mainSelector, data, countdownRef );
}, 1000 );
},
createCookie( name, value, expire_days, unit ) {
let expires = '';
if ( expire_days ) {
const date = new Date();
if ( 'minutes' === unit ) {
date.setTime( date.getTime() + expire_days * 60 * 1000 );
} else if ( 'hours' === unit ) {
date.setTime( date.getTime() + expire_days * 60 * 60 * 1000 );
} else {
date.setTime( date.getTime() + expire_days * 24 * 60 * 60 * 1000 );
}
expires = '; expires=' + date.toGMTString();
}
document.cookie = this.cookie_slug + '-' + name + '=' + value + expires + '; path=/';
},
getCookie( name ) {
const value = '; ' + document.cookie;
const parts = value.split( '; ' + this.cookie_slug + '-' + name + '=' );
if ( parts.length === 2 ) {
return parts.pop().split( ';' ).shift();
}
return '';
},
init( mainSelector, data = {} ) {
this.elements[ mainSelector ] = this.getElement( mainSelector );
// If global flag variable does not exists, create it.
// This is used like a signal for usage in Pro code.
if( ! window?.UAGBCountdownTimeSignal ) {
window.UAGBCountdownTimeSignal = {};
}
// Set flag variable to false, till it's overtime.
window.UAGBCountdownTimeSignal[ mainSelector ] = false;
if ( typeof this.elements[ mainSelector ] !== 'undefined' ) {
if ( 'evergreen' === data?.timerType ) {
const CampaignID =
'' !== data?.campaignID && null !== data?.campaignID ? data.campaignID : data.block_id;
this.cache.cookie = this.getCookie( CampaignID );
//Check for saved cookie.
if ( '' !== this.cache.cookie ) {
const currentTimeStamp = new Date();
const diff = Math.floor( this.cache.cookie - currentTimeStamp.getTime() );
const endTimeStamp = currentTimeStamp.getTime() + diff;
const totalDate = new Date( endTimeStamp );
// Setting enddate as per cookie timestamp.
data.endDateTime = totalDate.toISOString().replace( /\.\d{3}Z$/, 'Z' );
} else {
data.endDateTime = this.getEvergreenEndDate(
data.evergreenDays,
data.evergreenHrs,
data.evergreenMinutes
);
/**
* Setting timestamp and cookie after initial load.
* We are getting values of Hrs. and Minutes. and adding to the current timestamp to get endtime.
*/
const newDate = new Date();
newDate.setTime( newDate.getTime() + Math.floor( data.evergreenDays ) * 24 * 60 * 60 * 1000 );
newDate.setTime( newDate.getTime() + Math.floor( data.evergreenHrs ) * 60 * 60 * 1000 );
newDate.setTime( newDate.getTime() + Math.floor( data.evergreenMinutes ) * 60 * 1000 );
// Setting value for cache.
this.cache.evergreen = newDate.getTime() + 100;
const resetDays = '' !== data?.resetDays && 0 < data.resetDays ? data.resetDays : 30;
// Create the cookie for evergreen time.
this.createCookie( CampaignID, this.cache.evergreen, resetDays, 'days' );
}
}
// Slider block may create duplicate instances of it's slides, which may contain instances of the same countdowns.
const allSameCountdownInstances = document.querySelectorAll( mainSelector );
for( let i = 0; i < allSameCountdownInstances.length; i++ ) {
// Ensures instantaneous load/firing of countdown functionality.
this.updateCountdown( mainSelector, data, allSameCountdownInstances[i] );
this.countdownInterval[ mainSelector ] = setInterval( () => {
this.updateCountdown( mainSelector, data, allSameCountdownInstances[i] );
}, 1000 );
}
}
},
changeEndTime( mainSelector, data = {}, ref ) {
clearInterval( this.countdownInterval[ mainSelector ] );
if ( typeof this.elements[ mainSelector ] !== 'undefined' ) {
// Ensures instantaneous refresh of value.
this.updateCountdown( mainSelector, data, ref );
this.countdownInterval[ mainSelector ] = setInterval( () => {
this.updateCountdown( mainSelector, data, ref );
}, 1000 );
}
},
getElement( selector ) {
let domElement = document.querySelector( selector );
const editorCanvas = document.querySelector( 'iframe[name="editor-canvas"]' );
if ( editorCanvas && editorCanvas.contentDocument ) {
domElement = editorCanvas.contentDocument.querySelector( selector );
}
return domElement;
},
updateCountdown( mainSelector, data, ref = null ) {
if( ! ref ){
return;
}
// Wrappers.
let daysWrap;
let hoursWrap;
let minutesWrap;
const secondsWrap = ref.querySelector( '.wp-block-uagb-countdown__time-seconds' );
if ( data?.showDays ) {
daysWrap = ref.querySelector( '.wp-block-uagb-countdown__time-days' );
}
if ( data?.showHours ) {
hoursWrap = ref.querySelector( '.wp-block-uagb-countdown__time-hours' );
}
if ( data?.showMinutes ) {
minutesWrap = ref.querySelector( '.wp-block-uagb-countdown__time-minutes' );
}
// Calculations.
const currentTime = new Date();
const endDateTime = new Date( data.endDateTime );
const diff = endDateTime - currentTime;
const isOvertime = diff < 0;
// Calculations for each unit.
const days = Math.floor( diff / 1000 / 60 / 60 / 24 );
let hours = Math.floor( diff / 1000 / 60 / 60 ) % 24;
let minutes = Math.floor( diff / 1000 / 60 ) % 60;
let seconds = Math.floor( diff / 1000 ) % 60;
if ( ! data?.showDays ) {
hours = hours + days * 24;
}
if ( ! data?.showHours ) {
minutes = minutes + hours * 60;
}
if ( ! data?.showMinutes ) {
seconds = seconds + minutes * 60;
}
// Update the markup - Also, we check if the wrappers exist to avoid potential console errors.
if ( data?.showDays && daysWrap ) {
daysWrap.innerHTML = ! isOvertime ? days : 0;
}
if ( data?.showHours && hoursWrap ) {
hoursWrap.innerHTML = ! isOvertime ? hours : 0;
}
if ( data?.showMinutes && minutesWrap ) {
minutesWrap.innerHTML = ! isOvertime ? minutes : 0;
}
if ( secondsWrap ) {
secondsWrap.innerHTML = ! isOvertime ? seconds : 0;
}
// If it's overtime, stop updating the markup and clear the interval.
if ( isOvertime ) {
clearInterval( this.countdownInterval[ mainSelector ] );
// Set flag variable to true, for usage in Countdown Pro code (like a signal).
if( ( 'redirect' === data?.timerEndAction || 'hide' === data?.timerEndAction ) && data?.isFrontend ) {
window.UAGBCountdownTimeSignal[ mainSelector ] = true;
}
}
// Check if the page is reloaded by checking the presence of a specific cookie
const reloadCookieName = 'spectraPageReloaded_' + mainSelector;
const isPageReloaded = this.getCookie( reloadCookieName ) === 'true';
const resetDays = '' !== data?.resetDays && 0 < data.resetDays ? data.resetDays : 30;
if ( data?.isFrontend ) {
// Execute the code only in front-end.
if( isPageReloaded && ! isOvertime && this.getCookie( reloadCookieName ) !== 'false' ) {
this.createCookie( reloadCookieName, 'false', 0, 'days' );
}
if ( !isPageReloaded && isOvertime && 'content' === data?.timerEndAction && data?.reloadOnExpire && data?.autoReload ) {
location.reload();
this.createCookie( reloadCookieName, 'true', resetDays, 'days' );
}
if ( isOvertime && 'content' === data?.timerEndAction && ! data?.reloadOnExpire && ! data?.autoReload ) {
const timeUnits = [ 'days', 'hours', 'minutes', 'seconds' ];
const countdownSelectors = timeUnits.map( unit => ref.querySelector( `.wp-block-uagb-countdown__box-${unit}` ) );
const innerBlocksWrapper = ref.querySelector( `.uagb-block-countdown-innerblocks-${data.block_id}` );
innerBlocksWrapper.style.display = 'block';
countdownSelectors.forEach( selector => {
if ( selector ) {
selector.style.display = 'none';
}
} );
}
}
},
getEvergreenEndDate( days, hours, minutes ) {
const now = new Date();
const newDate = new Date( now.getTime() + ( days * 24 * 60 + hours * 60 + minutes ) * 60 * 1000 );
return newDate.toISOString().replace( /\.\d{3}Z$/, 'Z' );
},
};

View File

@@ -0,0 +1 @@
UAGBCountdown={elements:{},countdownInterval:{},cookie_slug:uagb_countdown_data.site_name_slug,cache:{},editorInit(e,t={},o){if(!t.timeModified){const n=new Date;n.setMilliseconds(n.getMilliseconds()+6048e5),t.endDateTime=n}this.elements[e]=this.getElement(e),this.countdownInterval[e]=setInterval(()=>{this.updateCountdown(e,t,o)},1e3)},createCookie(e,t,o,n){let i="";if(o){const s=new Date;"minutes"===n?s.setTime(s.getTime()+60*o*1e3):"hours"===n?s.setTime(s.getTime()+60*o*60*1e3):s.setTime(s.getTime()+24*o*60*60*1e3),i="; expires="+s.toGMTString()}document.cookie=this.cookie_slug+"-"+e+"="+t+i+"; path=/"},getCookie(e){const t="; "+document.cookie,o=t.split("; "+this.cookie_slug+"-"+e+"=");return 2===o.length?o.pop().split(";").shift():""},init(t,o={}){if(this.elements[t]=this.getElement(t),window?.UAGBCountdownTimeSignal||(window.UAGBCountdownTimeSignal={}),window.UAGBCountdownTimeSignal[t]=!1,void 0!==this.elements[t]){if("evergreen"===o?.timerType){var e=""!==o?.campaignID&&null!==o?.campaignID?o.campaignID:o.block_id;if(this.cache.cookie=this.getCookie(e),""!==this.cache.cookie){const s=new Date;var n=Math.floor(this.cache.cookie-s.getTime()),n=s.getTime()+n;const r=new Date(n);o.endDateTime=r.toISOString().replace(/\.\d{3}Z$/,"Z")}else{o.endDateTime=this.getEvergreenEndDate(o.evergreenDays,o.evergreenHrs,o.evergreenMinutes);const a=new Date;a.setTime(a.getTime()+24*Math.floor(o.evergreenDays)*60*60*1e3),a.setTime(a.getTime()+60*Math.floor(o.evergreenHrs)*60*1e3),a.setTime(a.getTime()+60*Math.floor(o.evergreenMinutes)*1e3),this.cache.evergreen=a.getTime()+100;n=""!==o?.resetDays&&0<o.resetDays?o.resetDays:30;this.createCookie(e,this.cache.evergreen,n,"days")}}const i=document.querySelectorAll(t);for(let e=0;e<i.length;e++)this.updateCountdown(t,o,i[e]),this.countdownInterval[t]=setInterval(()=>{this.updateCountdown(t,o,i[e])},1e3)}},changeEndTime(e,t={},o){clearInterval(this.countdownInterval[e]),void 0!==this.elements[e]&&(this.updateCountdown(e,t,o),this.countdownInterval[e]=setInterval(()=>{this.updateCountdown(e,t,o)},1e3))},getElement(e){let t=document.querySelector(e);const o=document.querySelector('iframe[name="editor-canvas"]');return t=o&&o.contentDocument?o.contentDocument.querySelector(e):t},updateCountdown(r,a,c=null){if(c){let e,t,o;const h=c.querySelector(".wp-block-uagb-countdown__time-seconds");a?.showDays&&(e=c.querySelector(".wp-block-uagb-countdown__time-days")),a?.showHours&&(t=c.querySelector(".wp-block-uagb-countdown__time-hours")),a?.showMinutes&&(o=c.querySelector(".wp-block-uagb-countdown__time-minutes"));var l=new Date,l=new Date(a.endDateTime)-l,d=l<0,u=Math.floor(l/1e3/60/60/24);let n=Math.floor(l/1e3/60/60)%24,i=Math.floor(l/1e3/60)%60,s=Math.floor(l/1e3)%60;a?.showDays||(n+=24*u),a?.showHours||(i+=60*n),a?.showMinutes||(s+=60*i),a?.showDays&&e&&(e.innerHTML=d?0:u),a?.showHours&&t&&(t.innerHTML=d?0:n),a?.showMinutes&&o&&(o.innerHTML=d?0:i),h&&(h.innerHTML=d?0:s),d&&(clearInterval(this.countdownInterval[r]),"redirect"!==a?.timerEndAction&&"hide"!==a?.timerEndAction||!a?.isFrontend||(window.UAGBCountdownTimeSignal[r]=!0));l="spectraPageReloaded_"+r,u="true"===this.getCookie(l),r=""!==a?.resetDays&&0<a.resetDays?a.resetDays:30;if(a?.isFrontend&&(u&&!d&&"false"!==this.getCookie(l)&&this.createCookie(l,"false",0,"days"),!u&&d&&"content"===a?.timerEndAction&&a?.reloadOnExpire&&a?.autoReload&&(location.reload(),this.createCookie(l,"true",r,"days")),d&&"content"===a?.timerEndAction&&!a?.reloadOnExpire&&!a?.autoReload)){const m=["days","hours","minutes","seconds"],g=m.map(e=>c.querySelector(".wp-block-uagb-countdown__box-"+e)),w=c.querySelector(".uagb-block-countdown-innerblocks-"+a.block_id);w.style.display="block",g.forEach(e=>{e&&(e.style.display="none")})}}},getEvergreenEndDate(e,t,o){const n=new Date,i=new Date(n.getTime()+60*(24*e*60+60*t+o)*1e3);return i.toISOString().replace(/\.\d{3}Z$/,"Z")}};