Refactor the code

This commit is contained in:
Daniel Dudzic 2024-06-07 00:35:55 +02:00
parent 0ba33e9bb8
commit 0a06a913e7
No known key found for this signature in database
GPG key ID: 31B40D33E3465483
4 changed files with 108 additions and 230 deletions

View file

@ -12,8 +12,11 @@
} }
} }
.email-submit-button { #ppcp-axo-billing-email-submit-button {
margin-top: 0;
position: relative; position: relative;
transition: opacity 0.3s ease;
.loader:before { .loader:before {
display: inline; display: inline;
height: 12px; height: 12px;
@ -103,30 +106,35 @@
} }
} }
.ppcp-axo-billing-email-submit-button-hidden {
opacity: 0;
}
.ppcp-axo-billing-email-submit-button-loaded:not([disabled]) {
opacity: 1;
}
#billing_email_field .woocommerce-input-wrapper { #billing_email_field .woocommerce-input-wrapper {
display: flex; display: flex;
align-items: center; align-items: center;
}
#billing_email_field .woocommerce-input-wrapper input { input {
flex: 1; flex: 1;
margin-right: 10px; margin-right: 10px;
} }
.email-submit-button {
padding: 5px 20px;
background-color: #007cba;
color: white;
border: none;
border-radius: 3px;
cursor: pointer;
flex-shrink: 0;
opacity: 0;
transition: opacity 0.3s ease; /* Add transition for opacity */
} }
#billing_email_field .woocommerce-input-wrapper.show-button .email-submit-button { @media screen and (max-width: 719px) {
opacity: 1; /* Show the button */ #ppcp-axo-billing-email-submit-button {
width: 100%;
margin-top: 0.5rem;
}
#billing_email_field .woocommerce-input-wrapper {
display: block;
input {
margin-right: 0;
}
}
} }

View file

@ -9,6 +9,7 @@ import { disable, enable } from "../../../ppcp-button/resources/js/modules/Helpe
import {getCurrentPaymentMethod} from "../../../ppcp-button/resources/js/modules/Helper/CheckoutMethodState"; import {getCurrentPaymentMethod} from "../../../ppcp-button/resources/js/modules/Helper/CheckoutMethodState";
class AxoManager { class AxoManager {
constructor(axoConfig, ppcpConfig) { constructor(axoConfig, ppcpConfig) {
this.axoConfig = axoConfig; this.axoConfig = axoConfig;
this.ppcpConfig = ppcpConfig; this.ppcpConfig = ppcpConfig;
@ -63,9 +64,9 @@ class AxoManager {
} }
if ( if (
this.axoConfig?.insights?.enabled && this.axoConfig?.insights?.enabled
this.axoConfig?.insights?.client_id && && this.axoConfig?.insights?.client_id
this.axoConfig?.insights?.session_id && this.axoConfig?.insights?.session_id
) { ) {
PayPalInsights.config(this.axoConfig?.insights?.client_id, { debug: true }); PayPalInsights.config(this.axoConfig?.insights?.client_id, { debug: true });
PayPalInsights.setSessionId(this.axoConfig?.insights?.session_id); PayPalInsights.setSessionId(this.axoConfig?.insights?.session_id);
@ -87,6 +88,7 @@ class AxoManager {
} }
registerEventHandlers() { registerEventHandlers() {
this.$(document).on('change', 'input[name=payment_method]', (ev) => { this.$(document).on('change', 'input[name=payment_method]', (ev) => {
const map = { const map = {
'ppcp-axo-gateway': 'card', 'ppcp-axo-gateway': 'card',
@ -99,6 +101,7 @@ class AxoManager {
}); });
}); });
// Listen to Gateway Radio button changes. // Listen to Gateway Radio button changes.
this.el.gatewayRadioButton.on('change', (ev) => { this.el.gatewayRadioButton.on('change', (ev) => {
if (ev.target.checked) { if (ev.target.checked) {
@ -170,6 +173,12 @@ class AxoManager {
} }
}); });
this.$('form.woocommerce-checkout input').on('click', async (ev) => {
if (document.querySelector(this.el.billingEmailSubmitButton.selector).hasAttribute('disabled')) {
document.querySelector(this.el.billingEmailSubmitButton.selector).removeAttribute('disabled');
}
});
// Clear last email checked identity when email field is focused. // Clear last email checked identity when email field is focused.
this.$('#billing_email_field input').on('focus', (ev) => { this.$('#billing_email_field input').on('focus', (ev) => {
log(`Clear the last email checked: ${this.lastEmailCheckedIdentity}`); log(`Clear the last email checked: ${this.lastEmailCheckedIdentity}`);
@ -246,9 +255,6 @@ class AxoManager {
this.$(this.el.fieldBillingEmail.selector).append( this.$(this.el.fieldBillingEmail.selector).append(
this.$(this.el.watermarkContainer.selector) this.$(this.el.watermarkContainer.selector)
); );
// Add the submit button to the email field container.
this.renderEmailSubmitNew();
} else { } else {
this.el.emailWidgetContainer.hide(); this.el.emailWidgetContainer.hide();
if (!scenario.defaultEmailField) { if (!scenario.defaultEmailField) {
@ -257,6 +263,7 @@ class AxoManager {
} }
if (scenario.axoProfileViews) { if (scenario.axoProfileViews) {
this.shippingView.activate(); this.shippingView.activate();
this.cardView.activate(); this.cardView.activate();
@ -270,6 +277,7 @@ class AxoManager {
); );
this.el.watermarkContainer.show(); this.el.watermarkContainer.show();
} else { } else {
this.shippingView.deactivate(); this.shippingView.deactivate();
this.billingView.deactivate(); this.billingView.deactivate();
@ -279,6 +287,7 @@ class AxoManager {
if (scenario.axoPaymentContainer) { if (scenario.axoPaymentContainer) {
this.el.paymentContainer.show(); this.el.paymentContainer.show();
this.el.gatewayDescription.hide(); this.el.gatewayDescription.hide();
document.querySelector(this.el.billingEmailSubmitButton.selector).setAttribute('disabled', 'disabled');
} else { } else {
this.el.paymentContainer.hide(); this.el.paymentContainer.hide();
} }
@ -445,6 +454,7 @@ class AxoManager {
} }
if (this.useEmailWidget()) { if (this.useEmailWidget()) {
// Display email widget. // Display email widget.
const ec = this.el.emailWidgetContainer; const ec = this.el.emailWidgetContainer;
if (!document.querySelector(ec.selector)) { if (!document.querySelector(ec.selector)) {
@ -456,6 +466,7 @@ class AxoManager {
} }
} else { } else {
// Move email to the AXO container. // Move email to the AXO container.
let emailRow = document.querySelector(this.el.fieldBillingEmail.selector); let emailRow = document.querySelector(this.el.fieldBillingEmail.selector);
wrapperElement.prepend(emailRow); wrapperElement.prepend(emailRow);
@ -469,9 +480,8 @@ class AxoManager {
this.initialized = true; this.initialized = true;
await this.connect(); await this.connect();
await this.renderWatermark(true, () => { await this.renderWatermark();
this.renderEmailSubmit(); this.renderEmailSubmitButton();
});
this.watchEmail(); this.watchEmail();
} }
@ -492,174 +502,38 @@ class AxoManager {
this.el.gatewayRadioButton.trigger('change'); this.el.gatewayRadioButton.trigger('change');
} }
async renderWatermark(includeAdditionalInfo = true, callback) { async renderWatermark(includeAdditionalInfo = true) {
(await this.fastlane.FastlaneWatermarkComponent({ (await this.fastlane.FastlaneWatermarkComponent({
includeAdditionalInfo includeAdditionalInfo
})).render(this.el.watermarkContainer.selector); })).render(this.el.watermarkContainer.selector);
this.toggleWatermarkLoading(this.el.watermarkContainer, 'ppcp-axo-watermark-loading', 'loader'); this.toggleWatermarkLoading(this.el.watermarkContainer, 'ppcp-axo-watermark-loading', 'loader');
// Call the callback if provided
if (callback) {
callback();
}
} }
async renderEmailSubmitNew() { renderEmailSubmitButton() {
const billingEmailSubmitButton = this.el.billingEmailSubmitButton; const billingEmailSubmitButton = this.el.billingEmailSubmitButton;
const billingEmailSubmitButtonSpinner = this.el.billingEmailSubmitButtonSpinner;
if (!document.querySelector(billingEmailSubmitButton.selector)) { if (!document.querySelector(billingEmailSubmitButton.selector)) {
this.emailInput.insertAdjacentHTML('afterend', `
<button type="button" id="${billingEmailSubmitButton.id}" class="${billingEmailSubmitButton.className}">
${this.axoConfig.billing_email_button_text}
<span id="${billingEmailSubmitButtonSpinner.id}"></span>
</button>
`);
document.querySelector(this.el.billingEmailSubmitButton.selector).offsetHeight;
document.querySelector(this.el.billingEmailSubmitButton.selector).classList.remove('ppcp-axo-billing-email-submit-button-hidden');
document.querySelector(this.el.billingEmailSubmitButton.selector).offsetHeight;
document.querySelector(this.el.billingEmailSubmitButton.selector).classList.add('ppcp-axo-billing-email-submit-button-loaded'); }
} }
const submitButton = this.el.billingEmailSubmitButton.selector;
// submitButton.innerText = this.axoConfig.billing_email_button_text;
const submitButtonSpinner = this.el.billingEmailSubmitButtonSpinner.selector;
console.log(submitButton);
}
async renderEmailSubmit() {
// Create the submit button element
const submitButton = document.createElement('button');
submitButton.type = 'button';
submitButton.innerText = this.axoConfig.billing_email_button_text;
submitButton.className = 'email-submit-button'; // Add a class for styling if needed
// Create the spinner element
const spinner = document.createElement('span');
spinner.className = 'loader ppcp-axo-overlay'; // Use the native loader class
spinner.style.display = 'none'; // Initially hidden
// Append the spinner to the button
submitButton.appendChild(spinner);
// Add an event listener to handle the button click
submitButton.addEventListener('click', async () => {
const emailInput = document.querySelector(this.el.fieldBillingEmail.selector + ' input');
if (emailInput && emailInput.checkValidity()) {
if (this.lastEmailCheckedIdentity !== emailInput.value) {
log(`Submit button clicked - emailInput: ${emailInput.value}`);
// Show the spinner, add the class to adjust padding and disable the button
spinner.style.display = 'inline-block';
submitButton.disabled = true;
try {
await this.onChangeEmail();
} finally {
// Hide the spinner and re-enable the button after the lookup is complete
spinner.style.display = 'none';
submitButton.disabled = false;
}
}
} else {
emailInput.reportValidity(); // Trigger the HTML5 validation message
log('Invalid or empty email input.');
}
});
// Append the button inside the wrapper of the billing email input field
const emailFieldContainer = document.querySelector(this.el.fieldBillingEmail.selector);
if (emailFieldContainer) {
const inputWrapper = emailFieldContainer.querySelector('.woocommerce-input-wrapper');
if (inputWrapper) {
// Ensure the email input has the required attribute
const emailInput = inputWrapper.querySelector('input');
emailInput.setAttribute('required', 'required');
emailInput.style.flex = '1'; // Make the input take the remaining space
emailInput.style.marginRight = '10px'; // Ensure the spacing is consistent
// Remove any existing loader if present
const existingLoader = inputWrapper.querySelector('.loader');
if (existingLoader) {
existingLoader.remove();
}
// Append the submit button to the input wrapper
inputWrapper.appendChild(submitButton);
// Force a reflow to apply the transition
submitButton.offsetHeight;
// Add the class to trigger the animation
inputWrapper.classList.add('show-button');
}
}
}
async onChangeEmail() {
this.clearData();
if (!this.status.active) {
log('Email checking skipped, AXO not active.');
return;
}
if (!this.emailInput) {
log('Email field not initialized.');
return;
}
log(`Email changed: ${this.emailInput ? this.emailInput.value : '<empty>'}`);
this.$(this.el.paymentContainer.selector + '-detail').html('');
this.$(this.el.paymentContainer.selector + '-form').html('');
this.setStatus('validEmail', false);
this.setStatus('hasProfile', false);
this.hideGatewaySelection = false;
this.lastEmailCheckedIdentity = this.emailInput.value;
if (!this.emailInput.value || !this.emailInput.checkValidity()) {
log('The email address is not valid.');
return;
}
this.data.email = this.emailInput.value;
this.billingView.setData(this.data);
if (!this.fastlane.identity) {
log('Not initialized.');
return;
}
PayPalInsights.trackSubmitCheckoutEmail({
page_type: 'checkout'
});
this.disableGatewaySelection();
const submitButton = document.querySelector('.email-submit-button');
const spinner = submitButton.querySelector('.loader');
if (submitButton && spinner) {
// Show the spinner and disable the button
spinner.style.display = 'inline-block';
submitButton.classList.add('show-spinner');
submitButton.disabled = true;
}
setTimeout(async () => {
console.log("Delayed for 1 milisecond.");
await this.lookupCustomerByEmail();
// Hide the spinner and re-enable the button after the lookup is complete
if (submitButton && spinner) {
spinner.style.display = 'none';
submitButton.classList.remove('show-spinner');
submitButton.disabled = false;
}
this.enableGatewaySelection();
}, 1);
}
watchEmail() { watchEmail() {
if (this.useEmailWidget()) { if (this.useEmailWidget()) {
// TODO // TODO
} else { } else {
this.emailInput.addEventListener('change', async ()=> { this.emailInput.addEventListener('change', async ()=> {
log(`Change event attempt - emailInput: ${this.emailInput.value}`); log(`Change event attempt - emailInput: ${this.emailInput.value}`);
@ -719,28 +593,12 @@ class AxoManager {
page_type: 'checkout' page_type: 'checkout'
}); });
this.disableGatewaySelection(); this.disableGatewaySelection();
this.spinnerToggleLoaderAndOverlay(this.el.billingEmailSubmitButtonSpinner, 'loader', 'ppcp-axo-overlay');
const submitButton = document.querySelector('.email-submit-button');
const spinner = submitButton.querySelector('.loader');
if (submitButton && spinner) {
// Show the spinner and disable the button
spinner.style.display = 'inline-block';
submitButton.disabled = true;
}
setTimeout(async () => {
console.log("Delayed for 1 milisecond.");
await this.lookupCustomerByEmail(); await this.lookupCustomerByEmail();
this.spinnerToggleLoaderAndOverlay(this.el.billingEmailSubmitButtonSpinner, 'loader', 'ppcp-axo-overlay');
// Hide the spinner and re-enable the button after the lookup is complete
if (submitButton && spinner) {
spinner.style.display = 'none';
submitButton.disabled = false;
}
this.enableGatewaySelection(); this.enableGatewaySelection();
}, 1);
} }
async lookupCustomerByEmail() { async lookupCustomerByEmail() {
@ -942,6 +800,7 @@ class AxoManager {
}); });
if (data) { if (data) {
// Ryan flow. // Ryan flow.
const form = document.querySelector('form.woocommerce-checkout'); const form = document.querySelector('form.woocommerce-checkout');
const formData = new FormData(form); const formData = new FormData(form);
@ -1049,6 +908,14 @@ class AxoManager {
} }
} }
spinnerToggleLoaderAndOverlay(element, loaderClass, overlayClass) {
const spinner = document.querySelector(`${element.selector}`);
if (spinner) {
spinner.classList.toggle(loaderClass);
spinner.classList.toggle(overlayClass);
}
}
toggleWatermarkLoading(container, loadingClass, loaderClass) { toggleWatermarkLoading(container, loadingClass, loaderClass) {
const watermarkLoading = document.querySelector(`${container.selector}.${loadingClass}`); const watermarkLoading = document.querySelector(`${container.selector}.${loadingClass}`);
const watermarkLoader = document.querySelector(`${container.selector}.${loaderClass}`); const watermarkLoader = document.querySelector(`${container.selector}.${loaderClass}`);

View file

@ -61,11 +61,14 @@ class DomElementCollection {
}); });
this.billingEmailSubmitButton = new DomElement({ this.billingEmailSubmitButton = new DomElement({
id: 'ppcp-axo-billing-email-submit-button',
selector: '#ppcp-axo-billing-email-submit-button', selector: '#ppcp-axo-billing-email-submit-button',
className: 'ppcp-axo-billing-email-submit-button-hidden button alt wp-element-button wc-block-components-button'
}); });
this.billingEmailSubmitButtonSpinner = new DomElement({ this.billingEmailSubmitButtonSpinner = new DomElement({
selector: '#ppcp-axo-billing-email-submit-spinner', id: 'ppcp-axo-billing-email-submit-button-spinner',
selector: '#ppcp-axo-billing-email-submit-button-spinner',
className: 'loader ppcp-axo-overlay' className: 'loader ppcp-axo-overlay'
}); });