/
view-modal.js
78 lines (67 loc) · 2.21 KB
/
view-modal.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/**
* External dependencies
*/
import MicroModal from 'micromodal';
// Responsive navigation toggle.
function navigationToggleModal( modal ) {
const dialogContainer = modal.querySelector(
`.wp-block-navigation__responsive-dialog`
);
const isHidden = 'true' === modal.getAttribute( 'aria-hidden' );
modal.classList.toggle( 'has-modal-open', ! isHidden );
dialogContainer.toggleAttribute( 'aria-modal', ! isHidden );
if ( isHidden ) {
dialogContainer.removeAttribute( 'role' );
dialogContainer.removeAttribute( 'aria-modal' );
} else {
dialogContainer.setAttribute( 'role', 'dialog' );
dialogContainer.setAttribute( 'aria-modal', 'true' );
}
// Add a class to indicate the modal is open.
const htmlElement = document.documentElement;
htmlElement.classList.toggle( 'has-modal-open' );
}
function isLinkToAnchorOnCurrentPage( node ) {
return (
node.hash &&
node.protocol === window.location.protocol &&
node.host === window.location.host &&
node.pathname === window.location.pathname &&
node.search === window.location.search
);
}
window.addEventListener( 'load', () => {
MicroModal.init( {
onShow: navigationToggleModal,
onClose: navigationToggleModal,
openClass: 'is-menu-open',
} );
// Close modal automatically on clicking anchor links inside modal.
const navigationLinks = document.querySelectorAll(
'.wp-block-navigation-item__content'
);
navigationLinks.forEach( function ( link ) {
// Ignore non-anchor links and anchor links which open on a new tab.
if (
! isLinkToAnchorOnCurrentPage( link ) ||
link.attributes?.target === '_blank'
) {
return;
}
// Find the specific parent modal for this link
// since .close() won't work without an ID if there are
// multiple navigation menus in a post/page.
const modal = link.closest(
'.wp-block-navigation__responsive-container'
);
const modalId = modal?.getAttribute( 'id' );
link.addEventListener( 'click', () => {
// check if modal exists and is open before trying to close it
// otherwise Micromodal will toggle the `has-modal-open` class
// on the html tag which prevents scrolling
if ( modalId && modal.classList.contains( 'has-modal-open' ) ) {
MicroModal.close( modalId );
}
} );
} );
} );