|
1 | 1 | import { createNav } from "@canonical/global-nav"; |
2 | 2 |
|
| 3 | +/** |
| 4 | + * Add custom listeners to control animation of dropdowns and be able to remove the |
| 5 | + * display of some hidden elements from global-nav that block clicks for underneath |
| 6 | + * elements (see WD-26684). |
| 7 | + * |
| 8 | + * We must set these listeners before the global-nav sets its own listeners for them |
| 9 | + * to work properly. |
| 10 | + */ |
| 11 | + |
| 12 | +const DROPDOWN_ANIMATION_DURATION = 333; |
| 13 | +const toggles = [ |
| 14 | + ...document.querySelectorAll( |
| 15 | + ".p-navigation__nav .p-navigation__link[aria-controls]:not(.js-back-button)", |
| 16 | + ), |
| 17 | +].filter((element) => element.id !== "all-canonical-link"); |
| 18 | + |
| 19 | +const toggleAnimationPlaying = (element: Element) => { |
| 20 | + const endAnimation = () => { |
| 21 | + element.classList.toggle("js-animation-playing", false); |
| 22 | + }; |
| 23 | + |
| 24 | + element.classList.toggle("js-animation-playing", true); |
| 25 | + setTimeout(endAnimation, DROPDOWN_ANIMATION_DURATION); |
| 26 | +}; |
| 27 | + |
| 28 | +const setAnimationPlaying = () => { |
| 29 | + // get all open toggles to add the animation playing to them |
| 30 | + toggles |
| 31 | + .filter( |
| 32 | + (toggle: Element): toggle is Element => |
| 33 | + toggle.parentElement != null && |
| 34 | + toggle.parentElement.classList.contains("is-active"), |
| 35 | + ) |
| 36 | + .forEach((toggle: Element) => { |
| 37 | + toggleAnimationPlaying(toggle.parentElement!); |
| 38 | + }); |
| 39 | +}; |
| 40 | + |
| 41 | +const handleToggle = (e: Event, toggle: Element) => { |
| 42 | + e.preventDefault(); |
| 43 | + |
| 44 | + const toggleParent = toggle.parentElement; |
| 45 | + if (toggleParent) { |
| 46 | + toggleAnimationPlaying(toggleParent); |
| 47 | + } |
| 48 | + |
| 49 | + e.stopPropagation(); |
| 50 | +}; |
| 51 | + |
| 52 | +toggles.forEach((toggle: Element) => { |
| 53 | + const handler = (e: Event) => handleToggle(e, toggle); |
| 54 | + toggle.addEventListener("click", handler); |
| 55 | +}); |
| 56 | + |
| 57 | +// when clicking outside navigation, set js-animation-playing on all open dropdowns |
| 58 | +document.addEventListener("click", setAnimationPlaying); |
| 59 | + |
| 60 | +// Once our listeners are added then we run global-nav, which will add others |
3 | 61 | window.addEventListener("DOMContentLoaded", function () { |
4 | 62 | createNav({ isSliding: true, closeMenuAnimationDuration: 200 }); |
5 | 63 | }); |
0 commit comments