From a301f5c88edfbfbbf19846812b49a2b6a2b4afd1 Mon Sep 17 00:00:00 2001 From: Miguel Peixe Date: Mon, 9 Oct 2023 16:17:15 -0300 Subject: [PATCH] fix(donate): reset "other" value when switching tiers --- src/blocks/donate/frequency-based/index.ts | 56 ++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/src/blocks/donate/frequency-based/index.ts b/src/blocks/donate/frequency-based/index.ts index 6a6dda317..2ebb40cbd 100644 --- a/src/blocks/donate/frequency-based/index.ts +++ b/src/blocks/donate/frequency-based/index.ts @@ -2,3 +2,59 @@ * Internal dependencies */ import './style.scss'; + +/** + * Specify a function to execute when the DOM is fully loaded. + * + * @see https://github.com/WordPress/gutenberg/blob/trunk/packages/dom-ready/ + * + * @param {Function} callback A function to execute after the DOM is ready. + * @return {void} + */ +function domReady( callback: () => void ): void { + if ( typeof document === 'undefined' ) { + return; + } + if ( + document.readyState === 'complete' || // DOMContentLoaded + Images/Styles/etc loaded, so we call directly. + document.readyState === 'interactive' // DOMContentLoaded fires at this point, so we call directly. + ) { + return void callback(); + } + // DOMContentLoaded has not fired yet, delay callback until then. + document.addEventListener( 'DOMContentLoaded', callback ); +} + +const resetOtherValue = ( container: HTMLElement ) => { + const frequencies = container.querySelectorAll( '.tiers' ); + if ( ! frequencies?.length ) { + return; + } + frequencies.forEach( frequency => { + const tiers = frequency.querySelectorAll( 'input[type="radio"]' ); + const input = frequency.querySelector( '.money-input input' ); + if ( ! tiers?.length || ! input ) { + return; + } + const originalValue = input.getAttribute( 'value' ); + const reset = () => { + input.value = originalValue || ''; + }; + tiers.forEach( tierInput => { + tierInput.addEventListener( 'change', reset ); + } ); + } ); +}; + +export const processFrequencyBasedElements = ( parentEl = document ) => { + const elements = parentEl.querySelectorAll( + '.wpbnbd--frequency-based' + ) as NodeListOf< HTMLElement >; + elements.forEach( container => { + resetOtherValue( container ); + } ); +}; + +if ( typeof window !== 'undefined' ) { + domReady( () => processFrequencyBasedElements() ); +}