Files
2026-09-15 10:35:56 +08:00

141 lines
4.0 KiB
JavaScript

define([
'jquery',
'Magento_Ui/js/modal/modal',
'Magento_Customer/js/customer-data',
'mage/translate'
], function ($, modal, customerData, $t) {
'use strict';
var DAY_IN_MILLISECONDS = 86400000;
return function (config, element) {
var $popup = $(element),
customer = customerData.get('customer'),
storageKey = [
'esunPromotionPopup',
String(config.websiteId),
String(config.campaignKey),
String(config.campaignVersion)
].join(':'),
timer = null,
opened = false;
function isLoggedIn() {
var data = customer() || {};
return Boolean(data.firstname || data.fullname || data.email);
}
function isCustomerAccountPage() {
return $('body').is('.account, .customer-account-index');
}
function readStorage(storage) {
try {
return storage.getItem(storageKey);
} catch (error) {
return null;
}
}
function writeStorage(storage, value) {
try {
storage.setItem(storageKey, value);
} catch (error) {
// Storage can be unavailable in private browsing; the popup should still work.
}
}
function wasAlreadyDisplayed() {
var value;
if (config.frequency === 'always') {
return false;
}
if (config.frequency === 'session') {
return Boolean(readStorage(window.sessionStorage));
}
value = readStorage(window.localStorage);
if (!value) {
return false;
}
return config.frequency === 'campaign' ||
Date.now() - parseInt(value, 10) < DAY_IN_MILLISECONDS;
}
function markDisplayed() {
var value = String(Date.now());
if (config.frequency === 'always') {
return;
}
if (config.frequency === 'session') {
writeStorage(window.sessionStorage, value);
return;
}
writeStorage(window.localStorage, value);
}
function isAudienceEligible() {
return config.audience !== 'guest' || !isLoggedIn();
}
function openPopup() {
if (opened || isCustomerAccountPage() || !isAudienceEligible() || wasAlreadyDisplayed()) {
return;
}
opened = true;
markDisplayed();
$popup.attr('aria-hidden', 'false').modal('openModal');
}
if (isCustomerAccountPage()) {
return;
}
modal({
type: 'popup',
responsive: true,
innerScroll: true,
modalClass: 'esun-promotion-popup-modal',
title: $t('Promotion'),
buttons: [],
clickableOverlay: true,
closed: function () {
$popup.attr('aria-hidden', 'true');
}
}, $popup);
function schedulePopup() {
if (!isAudienceEligible() || wasAlreadyDisplayed()) {
return;
}
timer = window.setTimeout(openPopup, Math.max(0, Number(config.displayDelay) || 0));
}
if (config.audience === 'guest') {
customer.subscribe(function () {
if (!isLoggedIn()) {
return;
}
window.clearTimeout(timer);
if (opened) {
$popup.modal('closeModal');
}
});
// Registration/login changes the server session before local customer-data is refreshed.
// Reload it before scheduling so authenticated customers never see a guest promotion.
customerData.reload(['customer'], false).always(schedulePopup);
return;
}
schedulePopup();
};
});