Source: listeners/adjust-sub-intent.js

import Listener from "./listener";

export class AdjustSubIntentListener extends Listener {
    eventName = "adjust_sub_intent";

    /**
     * Novum uses a side-drawer modal to display edit forms.
     * @return {HTMLElement} The modal element
     */
    get modal() {
        return document.getElementById('te-modal');
    }

    /**
     * Is the modal open?
     * @return {boolean} True if the modal is open
     */
    get isModalOpen() {
        return this.modal.classList.contains('visible');
    }

    /**
     * Get the portal task from the modal content.
     * @return {string|null} The portal task, or null if the modal is not relevant
     * @see portalTaskMap
     * @see getButtonTask
     */
    get portalTask() {
        for (const selector of portalTaskMap.keys()) {
            if (this.modal.querySelector(selector) !== null) {
                return portalTaskMap.get(selector);
            }
        }
        return null;
    }

    listen() {

        this.onModalOpen(() => {
            if (this.portalTask) this.trigger();
        });

        // "Order Now" doesn't open the modal, so we handle the click directly.
        document.addEventListener('click', ({ target }) => {
            const task = this.getButtonTask(target);
            if (task) this.trigger(task);
        });
    }

    onModalOpen(callback) {
        const observer = new MutationObserver(() => {
            if (this.isModalOpen) callback();
        });
        observer.observe(this.modal, { attributes: true });
    }

    /**
     * Get the portal task from the clicked element
     * This handles direct clicks that don't open the modal.
     * @param {HTMLElement} target The clicked element
     * @return {string|null} The portal task, or null if the click is not relevant
     */
    getButtonTask(target) {
        if (target.getAttribute('amb-special-button') === "order_now") {
            return "get_order_now";
        }
        if (target.classList.contains('js-swap-product-btn')) {
            return "swap_product";
        }
        return null;
    }

    createPayload(portalTask) {
        return {
            portal_task: portalTask || this.portalTask
        };
    }
}

/**
 * Map of selectors to portal tasks.
 * @type {Map<string, string>}
 * @see getPortalTask
 */
const portalTaskMap = new Map([
    [`#ReChargeForm_variant img[alt="INCLUDED FREE - 10 Donations to"]`, "change_donation"],
    ["#ReChargeForm_variant", "change_variant"],
    ["#ReChargeForm_schedule", "change_frequency"],
    ["#ReChargeForm_date", "change_charge_date"],
    ["#subscriptionSkipForm", "skip_shipment"],
    ["#rc_cancellation_reasons_list", "cancel_subscription"],
]);