Skip to content

Commit

Permalink
MWPW-164084 [Catalog] Page position not preserved after closing the m…
Browse files Browse the repository at this point in the history
…odal
  • Loading branch information
Bozo Jovicic committed Dec 26, 2024
1 parent d15c6d4 commit 871b7a7
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
18 changes: 17 additions & 1 deletion libs/blocks/merch/merch.js
Original file line number Diff line number Diff line change
Expand Up @@ -489,7 +489,7 @@ export async function openModal(e, url, offerType, hash, extraOptions) {
const prevHash = window.location.hash.replace('#', '') === hash ? '' : window.location.hash;
window.location.hash = hash;
window.addEventListener('milo:modal:closed', () => {
window.history.replaceState({}, document.title, `#${prevHash}`);
window.history.pushState({}, document.title, `#${prevHash}`);
}, { once: true });
}
if (isInternalModal(url)) {
Expand Down Expand Up @@ -747,3 +747,19 @@ export default async function init(el) {
log.warn('Failed to get context:', { el });
return null;
}

export async function handleHashChange() {
const modalDialog = document.querySelector('.dialog-modal');
if (window.location.hash) {
const modalId = window.location.hash.replace('#', '');
const cta = document.querySelector(`.con-button[data-modal-id="${modalId}"]`);
if (cta && !modalDialog) {
reopenModal(cta);
}
} else if (modalDialog) {
const { closeModal } = await import('../modal/modal.js');
closeModal(modalDialog);
}
}

window.addEventListener('hashchange', handleHashChange);
30 changes: 30 additions & 0 deletions test/blocks/merch/merch.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import merch, {
reopenModal,
setCtaHash,
openModal,
handleHashChange,
} from '../../../libs/blocks/merch/merch.js';

import { mockFetch, unmockFetch, readMockText } from './mocks/fetch.js';
Expand Down Expand Up @@ -471,6 +472,35 @@ describe('Merch Block', () => {
});
});

describe('function "handleHashChange"', () => {
afterEach(() => {
document.querySelector('.dialog-modal')?.remove();
document.querySelector('.con-button')?.remove();
});

it('reopen modal after hash change', () => {
const cta = document.createElement('a');
cta.classList.add('con-button');
cta.setAttribute('data-modal-id', 'try-phsp');
const clickSpy = sinon.spy(cta, 'click');
document.body.append(cta);
window.location.hash = 'try-phsp';

handleHashChange();
expect(clickSpy.called).to.be.true;
window.location.hash = '';
});

it('close modal after hash change', () => {
const div = document.createElement('div');
div.classList.add('dialog-modal');
div.setAttribute('id', 'try-phsp');
document.body.append(div);

handleHashChange();
});
});

describe('function "buildCta"', () => {
it('returns null if context params do not have osi', async () => {
const el = document.createElement('a');
Expand Down

0 comments on commit 871b7a7

Please sign in to comment.