|
| 1 | +function computeMenuTranslation(switcher, optionsElement) { |
| 2 | + // Calculate the position of a language options element. |
| 3 | + const switcherRect = switcher.getBoundingClientRect(); |
| 4 | + |
| 5 | + // Must be called before optionsElement.clientWidth. |
| 6 | + optionsElement.style.minWidth = `${Math.max(switcherRect.width, 50)}px`; |
| 7 | + |
| 8 | + const isOnTop = switcher.dataset.location === 'top'; |
| 9 | + const isOnBottom = switcher.dataset.location === 'bottom'; |
| 10 | + const isOnBottomRight = switcher.dataset.location === 'bottom-right'; |
| 11 | + const isRTL = document.body.dir === 'rtl' |
| 12 | + |
| 13 | + // Stuck on the left side of the switcher. |
| 14 | + let x = switcherRect.left; |
| 15 | + |
| 16 | + if (isOnTop && !isRTL || isOnBottom && isRTL || isOnBottomRight && !isRTL) { |
| 17 | + // Stuck on the right side of the switcher. |
| 18 | + x = switcherRect.right - optionsElement.clientWidth; |
| 19 | + } |
| 20 | + |
| 21 | + // Stuck on the top of the switcher. |
| 22 | + let y = switcherRect.top - window.innerHeight - 10; |
| 23 | + |
| 24 | + if (isOnTop) { |
| 25 | + // Stuck on the bottom of the switcher. |
| 26 | + y = switcherRect.top - window.innerHeight + optionsElement.clientHeight + switcher.clientHeight + 4; |
| 27 | + } |
| 28 | + |
| 29 | + return { x: x, y: y }; |
| 30 | +} |
| 31 | + |
| 32 | +function toggleMenu(switcher) { |
| 33 | + const optionsElement = switcher.nextElementSibling; |
| 34 | + |
| 35 | + optionsElement.classList.toggle('hx:hidden'); |
| 36 | + |
| 37 | + // Calculate the position of a language options element. |
| 38 | + const translate = computeMenuTranslation(switcher, optionsElement); |
| 39 | + |
| 40 | + optionsElement.style.transform = `translate3d(${translate.x}px, ${translate.y}px, 0)`; |
| 41 | +} |
| 42 | + |
| 43 | +function resizeMenu(switcher) { |
| 44 | + const optionsElement = switcher.nextElementSibling; |
| 45 | + |
| 46 | + if (optionsElement.classList.contains('hx:hidden')) return; |
| 47 | + |
| 48 | + // Calculate the position of a language options element. |
| 49 | + const translate = computeMenuTranslation(switcher, optionsElement); |
| 50 | + |
| 51 | + optionsElement.style.transform = `translate3d(${translate.x}px, ${translate.y}px, 0)`; |
| 52 | +} |
0 commit comments