/** * highlight active links after page loading * * @param {string} selector - can be '.t456__list_item a' */ function t_menu__highlightActiveLinks(selector) { var url = window.location.href; var urlWithoutSlash; var path = window.location.pathname; if (url[url.length - 1] === '/') urlWithoutSlash = url.slice(0, -1); if (path[path.length - 1] === '/') path = path.slice(0, -1); if (path[0] === '/') path = path.slice(1); if (path === '') path = '/'; var shouldBeActiveElements = document.querySelectorAll(selector); // link parameter href returns full path, but href by getAttribute returns only part, placed in href // element.href = 'https://google.com/search' // element.getAttribute('href') = '/search' Array.prototype.forEach.call(shouldBeActiveElements, function (element) { var slicedPath = element.getAttribute('href'); if (!slicedPath) return; var fullPath = element.href; var pathWithoutFirstSlash = slicedPath[0] === '/' ? slicedPath.slice(1) : slicedPath; // обработка случая, когда ссылка ведет на отдельный пост фида var tpost; if (path.indexOf('tpost') !== -1) { tpost = '/' + path.slice(0, path.indexOf('tpost')); } if ( fullPath === url || fullPath === path || slicedPath === url || slicedPath === path || pathWithoutFirstSlash === path || urlWithoutSlash === url || urlWithoutSlash === path || slicedPath === tpost ) { element.classList.add('t-active'); } }); } /** * main function to update active links. * In this part only find navlinks and send them to the t_menu__updateActiveLinks * * @param {string} recid * @param {string} selector - can be '.t456__list_item a' */ function t_menu__findAnchorLinks(recid, selector) { var rec = document.getElementById('rec' + recid); if (!rec) return; if (!t_menu__isBlockVisible(rec)) return; var anchorSelector = selector + '[href*="#"]:not(.tooltipstered)'; var navLinks = rec ? rec.querySelectorAll(anchorSelector) : []; if (navLinks.length) t_menu__updateActiveLinks(navLinks, selector); } /** * update active links by scroll * * @param {any} navLinks * @param {string} selector */ function t_menu__updateActiveLinks(navLinks, selector) { var menuClassName = selector.slice(2); menuClassName = parseInt(menuClassName, 10); menuClassName = '.t' + menuClassName; navLinks = Array.prototype.slice.call(navLinks); var clickedSectionID = null; var sections = []; var sectionToNavigationLinkID = {}; navLinks = navLinks.reverse(); navLinks.forEach(function (link) { var currentSection = t_menu__getSectionByHref(link); if (currentSection && currentSection.id) { sections.push(currentSection); sectionToNavigationLinkID[currentSection.id] = link; } }); t_menu__updateSectionsOffsets(sections); sections.sort(function (a, b) { var firstTopOffset = parseInt(a.getAttribute('data-offset-top'), 10) || 0; var secondTopOffset = parseInt(b.getAttribute('data-offset-top'), 10) || 0; return secondTopOffset - firstTopOffset; }); window.addEventListener( 'resize', t_throttle(function () { t_menu__updateSectionsOffsets(sections); }, 200) ); var menuEls = document.querySelectorAll(menuClassName); Array.prototype.forEach.call(menuEls, function (menu) { menu.addEventListener('displayChanged', function () { t_menu__updateSectionsOffsets(sections); }); }); t_menu__highlightNavLinks(navLinks, sections, sectionToNavigationLinkID, clickedSectionID); navLinks.forEach(function (navLink, i) { navLink.addEventListener('click', function () { var clickedSection = t_menu__getSectionByHref(navLink); if (!navLink.classList.contains('tooltipstered') && clickedSection && clickedSection.id) { navLinks.forEach(function (link, index) { if (index === i) { link.classList.add('t-active'); } else { link.classList.remove('t-active'); } }); clickedSectionID = clickedSection.id; } }); }); window.addEventListener( 'scroll', t_throttle(function () { clickedSectionID = t_menu__highlightNavLinks( navLinks, sections, sectionToNavigationLinkID, clickedSectionID ); }, 100) ); // update sections offsets after page loading, me602/3 activating, etc. if ('ResizeObserver' in window) { setTimeout(function () { var documentResizeObserver = new ResizeObserver(function () { t_menu__updateSectionsOffsets(sections); }); documentResizeObserver.observe(document.body); }, 500); } } /** * update offset in resize * * @param {HTMLElement[]} sections */ function t_menu__updateSectionsOffsets(sections) { sections.forEach(function (section) { var sectionTopPos = section.getBoundingClientRect().top + window.pageYOffset; if (section.getAttribute('data-offset-top') !== sectionTopPos.toString()) { section.setAttribute('data-offset-top', sectionTopPos); } }); } /** * get section by hooklink in link * * @param {HTMLElement} curlink * @returns {HTMLElement|Element|null} - returned section */ function t_menu__getSectionByHref(curlink) { if (!curlink) return; var href = curlink.getAttribute('href'); var curLinkValue = href ? href.replace(/\s+/g, '') : ''; if (curLinkValue.indexOf('/') === 0) curLinkValue = curLinkValue.slice(1); if (href && curlink.matches('[href*="#rec"]')) { curLinkValue = curLinkValue.replace(/.*#/, ''); return document.getElementById(curLinkValue); } else { var selector = href ? href.trim() : ''; var slashIndex = selector.indexOf('#') !== -1 ? selector.indexOf('#') : false; if (typeof slashIndex === 'number') { selector = selector.slice(slashIndex + 1); } else { slashIndex = selector.indexOf('/') !== -1 ? selector.indexOf('/') : false; if (typeof slashIndex === 'number') selector = selector.slice(slashIndex + 1); } // ищем якорную ссылку var linkSelector = 'a[name="' + selector + '"]'; var linkEl = document.querySelector(linkSelector); if (!linkEl) return null; // проверяем являестя ли ссылка блоком Якорная ссылка // если да, то возвращаем рекорд var anchorLinkBlock = linkEl.closest('.r[data-record-type="215"], .r[data-parenttplid="215"]'); if (anchorLinkBlock) return anchorLinkBlock; // иначе мы имеем дело с якорной ссылкой вставленной через настройки блока // поэтому ищем близлежащий блок, прописываем ссылке айдишник и возвращаем элемент ссылки // (чтобы пройти дальнейшую проверку на айдишник) var recordBlock = document.querySelector(linkSelector + '+ .r'); if (recordBlock) { linkEl.id = recordBlock ? recordBlock.id + '_' + selector : ''; return linkEl; } return null; } } /** * find active link by connected section, placed in viewport and set to it class .t-active * * @param {HTMLElement[]} navLinks - nav links * @param {HTMLElement[]} sections - connected with navlinks sections by hooks * @param {Object} sectionToNavigationLinkID - object which placed id key and section value * @param {null | string} clickedSectionID - id of clicked hook (section) */ function t_menu__highlightNavLinks(navLinks, sections, sectionToNavigationLinkID, clickedSectionID) { if (document.documentElement.classList.contains('t-body_scroll-locked')) return null; var scrollPosition = window.pageYOffset; var scrollHeight = Math.max( document.body.scrollHeight, document.documentElement.scrollHeight, document.body.offsetHeight, document.documentElement.offsetHeight, document.body.clientHeight, document.documentElement.clientHeight ); var returnValue = clickedSectionID; var lastSection = sections.length ? sections[sections.length - 1] : null; var lastSectionTopPos = lastSection ? parseInt(lastSection.getAttribute('data-offset-top'), 10) || 0 : 0; // if first section is not at the page top (under first blocks) if (sections.length && clickedSectionID === null && lastSectionTopPos > scrollPosition + 300) { navLinks.forEach(function (link) { link.classList.remove('t-active'); }); return null; } for (var i = 0; i < sections.length; i++) { var sectionTopPos = parseInt(sections[i].getAttribute('data-offset-top'), 10); var navLink = sections[i].id ? sectionToNavigationLinkID[sections[i].id] : null; if (scrollPosition + 300 >= sectionTopPos || (i === 0 && scrollPosition >= scrollHeight - window.innerHeight)) { if (clickedSectionID === null && navLink && !navLink.classList.contains('t-active')) { navLinks.forEach(function (link) { link.classList.remove('t-active'); }); if (navLink) navLink.classList.add('t-active'); returnValue = null; } else if (clickedSectionID !== null && sections[i].id && clickedSectionID === sections[i].id) { returnValue = null; } break; } } return returnValue; } /** * set background color for menu from data-attribute * * @param {string} recid - record ID * @param {string} selector - '.t456' etc. */ function t_menu__setBGcolor(recid, selector) { var menuBlocks = document.querySelectorAll(selector); Array.prototype.forEach.call(menuBlocks, function (menu) { if (window.innerWidth > 980) { if (menu.getAttribute('data-bgcolor-setbyscript') === 'yes') { menu.style.backgroundColor = menu.getAttribute('data-bgcolor-rgba'); } } else { menu.style.backgroundColor = menu.getAttribute('data-bgcolor-hex'); menu.setAttribute('data-bgcolor-setbyscript', 'yes'); // show mobile menu after slideUp animation if (menu.style.transform) menu.style.transform = ''; if (menu.style.opacity) menu.style.opacity = ''; } }); } /** * show and hide fixed menu, if user set option 'menu appearing when scrolling through N pixels'. * Only for desktop, except some classes, placed inside exceptionClasses Array. * * @param {string} recid - record ID * @param {string} selector - '.t456' etc. */ function t_menu__showFixedMenu(recid, selector) { var exceptionClasses = ['.t280', '.t282', '.t450', '.t451', '.t466', '.t453']; var isHasExceptionClass = exceptionClasses.some(function (className) { return className === selector; }); if (window.innerWidth <= 980 && !isHasExceptionClass) return; var rec = document.getElementById('rec' + recid); if (!rec) return false; var menuBlocks = rec.querySelectorAll(selector); Array.prototype.forEach.call(menuBlocks, function (menu) { var appearOffset = menu.getAttribute('data-appearoffset'); if (appearOffset) { if (appearOffset.indexOf('vh') !== -1) { appearOffset = Math.floor(window.innerHeight * (parseInt(appearOffset) / 100)); } appearOffset = parseInt(appearOffset, 10); var menuHeight = menu.clientHeight; if (typeof appearOffset === 'number' && window.pageYOffset >= appearOffset) { if (menu.style.transform === 'translateY(-' + menuHeight + 'px)') { t_menu__slideElement(menu, menuHeight, 'toBottom'); } } else if (menu.style.transform === 'translateY(0px)') { t_menu__slideElement(menu, menuHeight, 'toTop'); } else { menu.style.transform = 'translateY(-' + menuHeight + 'px)'; menu.style.opacity = '0'; } } }); } /** * Change background opacity for menu. * Only for desktop. * * @param {string} recid - record ID * @param {string} selector - '.t456' etc. */ function t_menu__changeBgOpacity(recid, selector) { var exceptSelectorList = ['t280', 't282', 't451', 't466']; var isExceptSelector = exceptSelectorList.some(function (expectClass) { return selector.indexOf(expectClass) !== -1; }); if (window.innerWidth <= 980 && !isExceptSelector) return; var rec = document.getElementById('rec' + recid); if (!rec) return false; var menuBlocks = rec.querySelectorAll(selector); Array.prototype.forEach.call(menuBlocks, function (menu) { var bgColor = menu.getAttribute('data-bgcolor-rgba'); var bgColorAfterScroll = menu.getAttribute('data-bgcolor-rgba-afterscroll'); var bgOpacity = menu.getAttribute('data-bgopacity'); var bgOpacityTwo = menu.getAttribute('data-bgopacity-two'); var menuShadowOpacity = parseInt(menu.getAttribute('data-menushadow'), 10) || 0; menuShadowOpacity /= 100; var menuShadowCSS = menu.getAttribute('data-menushadow-css'); menu.style.backgroundColor = window.pageYOffset > 20 ? bgColorAfterScroll : bgColor; if ( (window.pageYOffset > 20 && bgOpacityTwo === '0') || (window.pageYOffset <= 20 && (bgOpacity === '0.0' || bgOpacity === '0')) || (!menuShadowOpacity && !menuShadowCSS) ) { menu.style.boxShadow = 'none'; } else if (menuShadowCSS) { menu.style.boxShadow = menuShadowCSS; } else if (menuShadowOpacity) { menu.style.boxShadow = '0px 1px 3px rgba(0,0,0,' + menuShadowOpacity + ')'; } }); } /** * Set event listener for burger menu and change its display by resize * * @param {string} recid - record ID * @param {string} selector - '.t456' etc. */ function t_menu__createMobileMenu(recid, selector) { var rec = document.getElementById('rec' + recid); if (!rec) return; var menu = rec.querySelector(selector); var menuMobileBurgerhook = menu ? menu.getAttribute('data-mobile-burgerhook') : ''; var oldMobileMenuSelector = rec.querySelector(selector + '__mobile'); var mobileMenu = oldMobileMenuSelector ? oldMobileMenuSelector : rec.querySelector('.tmenu-mobile'); var mobileMenuOpenClass = oldMobileMenuSelector ? selector.slice(1) + '_opened' : 'tmenu-mobile_opened'; var burgerOpenClass = 't-menuburger-opened'; if (mobileMenu) { if (menu && menu.classList.contains(selector.slice(1) + '__mobile_burgerhook') && menuMobileBurgerhook) { if (mobileMenu.querySelector('.tmenu-mobile__burger')) { var mobileBurger = mobileMenu.querySelector('.tmenu-mobile__burger'); } else if (mobileMenu.querySelector('.t-menuburger')) { var mobileBurger = mobileMenu.querySelector('.t-menuburger'); } if (mobileBurger) { var mobileBurgerParent = mobileBurger.parentElement; var link = document.createElement('a'); link.href = menuMobileBurgerhook; if (mobileBurgerParent) { link.appendChild(mobileBurger); mobileBurgerParent.appendChild(link); } } } else { var mobileBurger = mobileMenu.querySelector('.t-menuburger'); mobileMenu.addEventListener('click', function (event) { if (event.target.closest('a')) { return; } if (mobileMenu.classList.contains(mobileMenuOpenClass)) { t_menu__FadeOut(menu, 300); mobileMenu.classList.remove(mobileMenuOpenClass); mobileBurger.classList.remove(burgerOpenClass); mobileBurger.setAttribute('aria-expanded', 'false'); } else { t_menu__fadeIn(menu, 300, function () { if (menu.style.transform) menu.style.transform = ''; if (menu.style.opacity) menu.style.opacity = ''; }); mobileMenu.classList.add(mobileMenuOpenClass); mobileBurger.classList.add(burgerOpenClass); mobileBurger.setAttribute('aria-expanded', 'true'); if (menu.classList.contains('tmenu-mobile__menucontent_fixed')) { var burgerHeight = getComputedStyle(mobileMenu).height; var burgerBorderSize = getComputedStyle(mobileMenu).borderBottom || 0; menu.style.top = burgerHeight + burgerBorderSize; } } t_menu_checkOverflow(recid, selector); }); } } if (screen.width < 980) { rec.addEventListener('click', function (e) { if (!menu || !menu.classList.contains('tmenu-mobile__menucontent_fixed')) return; const menuHeadNode = menu.closest('.r')?.querySelector('.tmenu-mobile_positionfixed'); const menuHeadHeight = menuHeadNode?.offsetHeight || 0; if (menuHeadHeight) menu.style.top = menuHeadHeight + 'px'; // prettier-ignore var menuLink = e.target.closest('.t-menu__link-item, .t978__submenu-link, .t978__innermenu-link, .t966__menu-link, .t-menusub__link-item, .t-btn, .t794__link'); if (!menuLink) return; var submenuClassList = [ 't978__menu-link_hook', 't978__tm-link', 't966__tm-link', 't794__tm-link', 't-menusub__target-link', ]; var isSubmenuHook = submenuClassList.some(function (submenuClass) { return menuLink.classList.contains(submenuClass); }); if (isSubmenuHook) { menu.addEventListener('menuOverflow', function () { t_menu_checkOverflow(recid, selector); }); return; } t_menu__FadeOut(menu, 300); if (mobileMenu) mobileMenu.classList.remove(mobileMenuOpenClass); if (mobileMenu) mobileBurger.classList.remove(burgerOpenClass); }); } window.addEventListener( 'resize', t_throttle(function () { if (window.innerWidth > 980) { if (menu) menu.style.opacity = ''; if (menu) menu.style.display = ''; if (menu) { const customTopPosition = menu.getAttribute('data-top') || ''; menu.style.top = customTopPosition; } if (mobileMenu) mobileMenu.classList.remove(mobileMenuOpenClass); } t_menu_checkOverflow(recid, selector); }, 200) ); } function t_menu_checkOverflow(recid, selector) { var rec = document.getElementById('rec' + recid); var menu = rec ? rec.querySelector(selector) : null; if (!menu) return; var oldMobileMenuSelector = rec.querySelector(selector + '__mobile'); var burger = oldMobileMenuSelector ? oldMobileMenuSelector : rec.querySelector('.tmenu-mobile'); if (!burger) return; var burgerHeight = burger.offsetHeight; var windowHeight = document.documentElement.clientHeight; var menuPosition = menu.style.position || window.getComputedStyle(menu).position; var menuHeight = menu.offsetHeight; if (menuPosition === 'fixed' && menuHeight > windowHeight - burgerHeight) { menu.style.overflow = 'auto'; menu.style.maxHeight = 'calc(100% - ' + burgerHeight + 'px' + ')'; } } function t_menu__FadeOut(element, duration, callback) { if (!element) return false; var opacity = 1; duration = parseInt(duration, 10); var speed = duration > 0 ? duration / 10 : 40; var timer = setInterval(function () { element.style.opacity = opacity; opacity -= 0.1; if (opacity <= 0.1) { element.style.opacity = '0'; element.style.display = 'none'; if (typeof callback === 'function') { callback(); } clearInterval(timer); } }, speed); } function t_menu__fadeIn(element, duration, callback) { if (!element) return false; if ( (getComputedStyle(element).opacity === '1' || getComputedStyle(element).opacity === '') && getComputedStyle(element).display !== 'none' ) return false; var opacity = 0; duration = parseInt(duration, 10); var speed = duration > 0 ? duration / 10 : 40; element.style.opacity = opacity; element.style.display = 'block'; var timer = setInterval(function () { element.style.opacity = opacity; opacity += 0.1; if (opacity >= 1) { element.style.opacity = '1'; if (typeof callback === 'function') { callback(); } clearInterval(timer); } }, speed); } function t_menu__slideElement(menu, menuHeight, direction) { var diff = direction === 'toTop' ? 0 : menuHeight; var diffOpacity = direction === 'toTop' ? 1 : 0; var timerID = setInterval(function () { menu.style.transform = 'translateY(-' + diff + 'px)'; menu.style.opacity = diffOpacity.toString(); diffOpacity = direction === 'toTop' ? diffOpacity - 0.1 : diffOpacity + 0.1; diff = direction === 'toTop' ? diff + menuHeight / 20 : diff - menuHeight / 20; if (direction === 'toTop' && diff >= menuHeight) { menu.style.transform = 'translateY(-' + menuHeight + 'px)'; menu.style.opacity = '0'; clearInterval(timerID); } if (direction === 'toBottom' && diff <= 0) { menu.style.transform = 'translateY(0px)'; menu.style.opacity = '1'; clearInterval(timerID); } }, 10); } /** * a11y * Interact with menu and submenu from keyboard * @param {string} recid - record ID */ function t_menu__interactFromKeyboard(recid) { var rec = document.getElementById('rec' + recid); if (!rec) return; var menuItems = rec.querySelectorAll('.t-menu__list > li > a'); var submenuItems = rec.querySelectorAll('.t-menu__list > li li'); var keysCode = { tab: 9, enter: 13, esc: 27, space: 32, }; var menuCurrentIndex = 0; var submenuCurrentIndex; var t_menu__focusOnCurrentMenuItem = function (index) { if (index === menuItems.length) { index = 0; } else if (index < 0) { index = menuItems.length - 1; } menuItems[index].focus(); menuCurrentIndex = index; }; var t_menu__focusOnCurrentSubmenuItem = function (menu, index) { var items = menu.querySelectorAll('a'); if (index == items.length) { index = 0; } else if (index < 0) { index = items.length - 1; } items[index].focus(); submenuCurrentIndex = index; }; var t_menu__interactWithMenuFromKeyboard = function (menuItem) { menuItem.addEventListener('keydown', function (event) { var submenu = this.parentNode.querySelector('.t-menusub__list'); switch (event.keyCode) { case keysCode.tab: if (!event.shiftKey && menuCurrentIndex <= menuItems.length - 2) { t_menu__focusOnCurrentMenuItem(menuCurrentIndex + 1); } else if (event.shiftKey && menuCurrentIndex > 0) { t_menu__focusOnCurrentMenuItem(menuCurrentIndex - 1); } else { return; } break; case keysCode.enter: case keysCode.space: if (!submenu) return; this.click(); submenuCurrentIndex = 0; t_menu__focusOnCurrentSubmenuItem(submenu, 0); break; } event.preventDefault(); }); }; var t_menu__focusOnMenuItem = function (menuItem) { menuItem.addEventListener('focus', function () { submenuCurrentIndex = 0; }); }; var t_menu__clickOnMenuItem = function (menuItem) { var submenu = menuItem.parentNode.querySelector('.t-menusub__menu'); menuItem.addEventListener('click', function (event) { if (this.getAttribute('aria-expanded') == 'false' || this.getAttribute('aria-expanded') == null) { this.setAttribute('aria-expanded', 'true'); var menusubWrapper = menuItem.nextElementSibling; var marginValue = menusubWrapper ? menusubWrapper.getAttribute('data-submenu-margin') : 0; t_menusub__showSubmenu(menuItem, submenu, marginValue); } else { this.setAttribute('aria-expanded', 'false'); } event.preventDefault(); return false; }); }; var t_menu__interactWithSubmenuFromKeyboard = function (submenuItem) { var submenu = submenuItem.closest('.t-menusub__menu'); var prevent = false; submenuItem.addEventListener('keydown', function (event) { var submenuList = this.parentNode; switch (event.keyCode) { // Доходим до начала или конца подменю – переходим к следюущему пункту меню case keysCode.tab: prevent = true; var currentSubmenuItemsLength = submenuList.querySelectorAll('.t-menusub__link-item').length; if (event.shiftKey) { if (submenuCurrentIndex === 0) { t_menu__focusOnCurrentMenuItem(menuCurrentIndex); t_menusub__hideSubmenu(submenu); } else { t_menu__focusOnCurrentSubmenuItem(submenuList, submenuCurrentIndex - 1); } } else if (submenuCurrentIndex === currentSubmenuItemsLength - 1) { t_menusub__hideSubmenu(submenu); if (menuCurrentIndex === menuItems.length - 1) { return; } t_menu__focusOnCurrentMenuItem(menuCurrentIndex + 1); } else { t_menu__focusOnCurrentSubmenuItem(submenuList, submenuCurrentIndex + 1); } break; case keysCode.enter: case keysCode.space: prevent = false; t_menusub__hideSubmenu(submenu); break; case keysCode.esc: prevent = true; t_menu__focusOnCurrentMenuItem(menuCurrentIndex); t_menusub__hideSubmenu(submenu); break; } if (prevent) { event.preventDefault(); event.stopPropagation(); } }); }; Array.prototype.forEach.call(menuItems, function (menuItem) { t_menu__focusOnMenuItem(menuItem); t_menu__interactWithMenuFromKeyboard(menuItem); var submenu = menuItem.parentNode.querySelector('.t-menusub__menu'); if (submenu && !window.isMobile && !('ontouchend' in document)) { t_menu__clickOnMenuItem(menuItem); } }); Array.prototype.forEach.call(submenuItems, function (submenuItem) { t_menu__interactWithSubmenuFromKeyboard(submenuItem); }); } function t_menu__isBlockVisible(rec) { var windowWidth = window.innerWidth; var screenMin = rec.getAttribute('data-screen-min'); var screenMax = rec.getAttribute('data-screen-max'); if (screenMin && windowWidth < parseInt(screenMin, 10)) return false; if (screenMax && windowWidth > parseInt(screenMax, 10)) return false; return true; }