feat: Enhance MegaMenu with localization, caching, and new properties

- Added localization support for loading states, empty navigation, and submenu actions in both German and English.
- Introduced new properties in IMenuItem for description, openInNewWindow, and external links.
- Updated SPTermStorePickerService to handle cache versioning and language-specific caching.
- Implemented a new MegaMenuCore service for handling term properties, cache management, and navigation URL resolution.
- Refactored TaxonomyNavigationService to build menu hierarchy and filter hidden terms.
- Added automated tests for MegaMenu core functionalities and static asset validation.
- Removed unused ItemDictionary service.
- Created a comprehensive ToDo document outlining the implementation status and future tasks.
This commit is contained in:
Torsten Brendgen
2026-07-20 21:34:24 +02:00
parent bc61166267
commit 50b85468f1
30 changed files with 1394 additions and 294 deletions

View File

@@ -19,6 +19,7 @@ Die Classic-Variante liest die `ClientSideComponentProperties` der zentralen Meg
"termSetId": "7948e6f9-7af4-431e-b6fe-328122f2746c",
"termSetName": "Global Navigation",
"cacheMinutes": 15,
"cacheVersion": "1",
"menuMode": "megaMenu",
"debug": false
}
@@ -26,6 +27,8 @@ Die Classic-Variante liest die `ClientSideComponentProperties` der zentralen Meg
`menuMode` erlaubt `megaMenu` oder `flyout`. `termSetId` hat Vorrang vor `termSetName`.
Die lokalen benutzerdefinierten Term-Eigenschaften `MegaMenu.Hidden`, `MegaMenu.OpenInNewWindow` und `MegaMenu.Description` werden wie in der modernen Variante ausgewertet. Der Cache ist nach Site Collection, Sprache und `cacheVersion` getrennt.
## Einbindung
Die drei Dateien beispielsweise nach `/SiteAssets/megamenu/` hochladen und in dieser Reihenfolge laden:

View File

@@ -1,4 +1,4 @@
/* SharePoint MegaMenu 2.1.0 - Classic pages */
/* SharePoint MegaMenu 2.2.0 - Classic pages */
:root {
--megaMenuBarHeight: 44px;
--megaMenuContentWidth: 1200px;
@@ -28,6 +28,17 @@
color: #323130;
}
.mega-menu-status {
box-sizing: border-box;
padding: 10px 24px;
border-bottom: 1px solid #edebe9;
background: #f3f9fd;
color: #323130;
font-size: 13px;
}
.mega-menu-mobile-toggle { display: none; }
.mega-menu-top-level {
display: flex;
align-items: stretch;
@@ -71,19 +82,38 @@
outline: none;
}
.menu-item-text[aria-haspopup="true"]::after {
.menu-item-toggle {
position: relative;
display: flex;
align-items: center;
justify-content: center;
box-sizing: border-box;
width: 32px;
min-height: var(--megaMenuBarHeight);
margin: 0 8px 0 -10px;
padding: 0;
border: 0;
background: transparent;
color: #323130;
cursor: pointer;
}
.menu-item-toggle > span::after {
content: "";
display: block;
width: 6px;
height: 6px;
margin: -3px 0 0 10px;
border-right: 1px solid currentColor;
border-bottom: 1px solid currentColor;
transform: rotate(45deg);
}
.menu-item-toggle[aria-expanded="true"] > span::after { transform: rotate(225deg); }
.menu-item-link:hover,
.menu-item-text:hover,
.menu-item-text[aria-expanded="true"] {
.menu-item-toggle:hover,
.menu-item-toggle[aria-expanded="true"] {
background: #f3f2f1;
color: #323130;
text-decoration: none;
@@ -91,6 +121,8 @@
.menu-item-link:focus,
.menu-item-text:focus,
.menu-item-toggle:focus,
.mega-menu-mobile-toggle:focus,
.mega-menu-category a:focus,
.flyout-link:focus {
outline: 2px solid #0078d4;
@@ -132,6 +164,13 @@
padding-bottom: 8px;
}
.mega-menu-description {
margin: -4px 0 12px;
color: #605e5c;
font-size: 12px;
line-height: 18px;
}
.mega-menu-category h3 {
margin: 0 0 10px;
padding: 0 0 8px;
@@ -225,19 +264,34 @@
color: #323130;
}
.flyout-link-has-children::after {
content: "";
.flyout-toggle {
position: absolute;
top: 50%;
right: 18px;
top: 0;
right: 0;
display: flex;
align-items: center;
justify-content: center;
width: 36px;
height: 36px;
padding: 0;
border: 0;
background: transparent;
color: #323130;
cursor: pointer;
}
.flyout-toggle > span::after {
content: "";
display: block;
width: 6px;
height: 6px;
margin-top: -4px;
border-top: 1px solid currentColor;
border-right: 1px solid currentColor;
transform: rotate(45deg);
}
.flyout-toggle:focus { outline: 2px solid #0078d4; outline-offset: -2px; }
.flyout-level-3 {
position: absolute;
top: -9px;
@@ -250,7 +304,8 @@
}
.flyout-item:hover > .flyout-level-3,
.flyout-item:focus-within > .flyout-level-3 {
.flyout-item:focus-within > .flyout-level-3,
.flyout-item.is-open > .flyout-level-3 {
display: block;
}
@@ -267,9 +322,61 @@
}
@media (max-width: 767px) {
.mega-menu-mobile-toggle {
display: flex;
align-items: center;
width: 100%;
min-height: var(--megaMenuBarHeight);
padding: 0 16px;
border: 0;
background: #fff;
color: #323130;
cursor: pointer;
font: inherit;
font-weight: 600;
}
.mega-menu-mobile-icon,
.mega-menu-mobile-icon::before,
.mega-menu-mobile-icon::after {
display: block;
width: 18px;
height: 2px;
background: currentColor;
}
.mega-menu-mobile-icon { position: relative; margin-right: 12px; }
.mega-menu-mobile-icon::before,
.mega-menu-mobile-icon::after { content: ""; position: absolute; left: 0; }
.mega-menu-mobile-icon::before { top: -6px; }
.mega-menu-mobile-icon::after { top: 6px; }
.mega-menu-top-level {
flex-wrap: wrap;
padding: 0 8px;
display: none;
flex-direction: column;
padding: 0;
border-top: 1px solid #edebe9;
}
.mega-menu-main.is-mobile-open .mega-menu-top-level { display: flex; }
.mega-menu-top-item,
.mega-menu-mode-flyout .mega-menu-top-item {
position: relative;
display: grid;
grid-template-columns: minmax(0, 1fr) 44px;
border-bottom: 1px solid #edebe9;
}
.menu-item-toggle { width: 44px; margin: 0; border-left: 1px solid #edebe9; }
.mega-menu {
position: static;
grid-column: 1 / -1;
width: 100%;
border-right: 0;
border-left: 0;
box-shadow: none;
}
.mega-menu-grid {
@@ -279,12 +386,14 @@
.flyout-level-3 {
position: static;
display: block;
display: none;
width: 100%;
border: 0;
box-shadow: none;
padding-left: 16px;
}
.flyout-item.is-open > .flyout-level-3 { display: block; }
}
@media print {

View File

@@ -1,6 +1,6 @@
/**
* SharePoint MegaMenu for Classic Pages
* Version: 2.1.0
* Version: 2.2.0
*
* This version uses standalone services that replicate the SPFx logic
* without requiring the SharePoint Framework.
@@ -25,6 +25,41 @@
config.containerId = config.containerId || 's4-titlerow';
config.debug = config.debug === true;
function getLanguageLcid() {
return Number(window._spPageContextInfo && _spPageContextInfo.currentLanguage) || 1033;
}
function getStrings() {
return getLanguageLcid() === 1031 ? {
navigationLabel: 'Hauptnavigation', openNavigation: 'Hauptnavigation öffnen', closeNavigation: 'Hauptnavigation schließen',
openSubmenu: 'Untermenü öffnen für', closeSubmenu: 'Untermenü schließen für', submenuLabel: 'Untermenü',
externalLink: 'externer Link', loading: 'Navigation wird geladen…', missing: 'Die Navigation ist nicht konfiguriert.',
empty: 'Die Navigation enthält keine sichtbaren Einträge.', error: 'Die Navigation konnte nicht geladen werden.'
} : {
navigationLabel: 'Main navigation', openNavigation: 'Open main navigation', closeNavigation: 'Close main navigation',
openSubmenu: 'Open submenu for', closeSubmenu: 'Close submenu for', submenuLabel: 'submenu',
externalLink: 'external link', loading: 'Loading navigation…', missing: 'Navigation is not configured.',
empty: 'The navigation does not contain any visible entries.', error: 'Navigation could not be loaded.'
};
}
function showStatus(message) {
var existing = document.querySelector('.megamenu-classic-container');
var container = existing || document.createElement('div');
container.className = 'megamenu-classic-container';
container.innerHTML = '';
var status = document.createElement('div');
status.className = 'mega-menu-status';
status.setAttribute('role', 'status');
status.textContent = message;
container.appendChild(status);
if (!existing) {
var anchor = document.getElementById(config.containerId) || document.body.firstChild;
anchor.parentNode.insertBefore(container, anchor.nextSibling);
}
return container;
}
function log(message, data) {
if (config.debug && console && console.log) {
console.log('[MegaMenu Classic] ' + message, data || '');
@@ -94,16 +129,16 @@
callback(props);
} catch (e) {
log('Error parsing UserCustomAction properties: ' + e.message);
callback({ termSetName: 'Navigation', menuMode: 'megaMenu', debug: false });
callback({});
}
} else {
log('No UserCustomAction found - using defaults');
callback({ termSetName: 'Navigation', menuMode: 'megaMenu', debug: false });
callback({});
}
})
.catch(function(error) {
log('Error reading configuration: ' + error.message);
callback({ termSetName: 'Navigation', menuMode: 'megaMenu', debug: false });
callback({});
});
}
@@ -120,20 +155,39 @@
readMegaMenuConfiguration(function(props) {
config.debug = props.debug === true || config.debug === true;
log('Using configuration:', props);
var strings = getStrings();
var termSetIdentifier = props.termSetId || props.termSetName;
if (!termSetIdentifier) {
showStatus(strings.missing);
return;
}
var loadingContainer = showStatus(strings.loading);
// Create context
var context = createClassicContext();
// Create taxonomy service using standalone implementation
var taxonomyService = new window.MegaMenuServices.TaxonomyNavigationService(
context,
props.termSetId || props.termSetName
context,
termSetIdentifier,
{
cacheMinutes: props.cacheMinutes,
cacheVersion: props.cacheVersion,
languageLcid: getLanguageLcid()
}
);
// Load menu items
taxonomyService.getMenuItems()
.then(function(menuItems) {
log('Menu items loaded:', menuItems);
if (!menuItems || menuItems.length === 0) {
showStatus(strings.empty);
return;
}
if (loadingContainer && loadingContainer.parentNode) {
loadingContainer.parentNode.removeChild(loadingContainer);
}
// Find target container
var container = document.getElementById(config.containerId);
@@ -160,7 +214,8 @@
var renderer = new window.MegaMenuServices.MegaMenuRenderer(
context,
menuItems,
props.menuMode === 'flyout' ? 'flyout' : 'megaMenu'
props.menuMode === 'flyout' ? 'flyout' : 'megaMenu',
strings
);
// Render the menu
@@ -170,21 +225,7 @@
})
.catch(function(error) {
console.error('[MegaMenu] Error loading menu items:', error);
// Show error message to user
var container = document.getElementById(config.containerId);
if (container) {
var errorDiv = document.createElement('div');
errorDiv.style.cssText = 'background:#ffebee;color:#c62828;padding:10px;border:1px solid #ef5350;margin:5px 0;';
errorDiv.innerHTML = '<strong>MegaMenu Error:</strong> ' + error.message +
'<br><small>Check browser console for details.</small>';
if (container.nextSibling) {
container.parentNode.insertBefore(errorDiv, container.nextSibling);
} else {
container.parentNode.appendChild(errorDiv);
}
}
showStatus(strings.error);
});
});
}

View File

@@ -30,6 +30,10 @@
constructor(term, depth, siteCollectionUrl) {
this.title = term.Name;
this.url = this._getNavigationUrl(term, siteCollectionUrl);
const properties = term.LocalCustomProperties || {};
this.description = String(properties['MegaMenu.Description'] || '').trim();
this.openInNewWindow = this._asBoolean(properties['MegaMenu.OpenInNewWindow']);
this.external = this._isExternal(this.url, siteCollectionUrl);
this.items = [];
this.pathDepth = this._calculateDepth(term.PathOfTerm);
this.parentId = this._getParentId(term.PathOfTerm);
@@ -56,9 +60,27 @@
if (!rawUrl) {
return undefined;
}
return rawUrl.indexOf('~sitecollection') === 0
if (/[\u0000-\u001f\u007f]/.test(String(rawUrl))) {
return undefined;
}
const resolved = rawUrl.indexOf('~sitecollection') === 0
? siteCollectionUrl + rawUrl.substring('~sitecollection'.length)
: rawUrl;
const protocol = String(resolved).match(/^([a-z][a-z0-9+.-]*):/i);
if (protocol && ['http', 'https', 'mailto'].indexOf(protocol[1].toLowerCase()) < 0) {
return undefined;
}
return resolved;
}
_asBoolean(value) {
return value === true || ['true', '1', 'yes', 'ja'].indexOf(String(value || '').toLowerCase()) >= 0;
}
_isExternal(url, siteCollectionUrl) {
const target = String(url || '').match(/^(?:(https?):)?\/\/([^/]+)/i);
const current = String(siteCollectionUrl || '').match(/^(https?):\/\/([^/]+)/i);
return !!target && (!current || (target[1] || current[1]).toLowerCase() !== current[1].toLowerCase() || target[2].toLowerCase() !== current[2].toLowerCase());
}
}
@@ -67,21 +89,65 @@
// ===========================================
class TaxonomyNavigationService {
constructor(context, termSetIdentifier) {
constructor(context, termSetIdentifier, options) {
this.context = context;
this.termSetIdentifier = termSetIdentifier;
this.options = options || {};
this._siteCollectionUrl = context.pageContext.site.absoluteUrl;
this._languageLcid = Number(this.options.languageLcid) || 1033;
this._cacheMinutes = Math.min(Math.max(Number(this.options.cacheMinutes) || 15, 1), 1440);
this._cacheVersion = String(this.options.cacheVersion || '1');
}
async getMenuItems() {
console.log('[TaxonomyService] Loading terms for:', this.termSetIdentifier);
const cached = this._getCache(false);
if (cached) {
return this._processTerms(cached);
}
const stale = this._getCache(true);
try {
const termSet = await this._loadTermSet(this.termSetIdentifier);
this._setCache(termSet);
return this._processTerms(termSet);
} catch (error) {
console.error('[TaxonomyService] Error loading terms:', error);
return [this._createNoTermsItem()];
if (stale) {
console.warn('[TaxonomyService] Using stale cache after taxonomy error.');
return this._processTerms(stale);
}
throw error;
}
}
_cacheKey() {
const normalize = value => encodeURIComponent(String(value || '').trim().toLowerCase());
return 'MegaMenu:TermSet:v3:' + normalize(this._siteCollectionUrl) + ':' + normalize(this.termSetIdentifier) + ':' + this._languageLcid + ':' + normalize(this._cacheVersion);
}
_getCache(allowExpired) {
try {
const serialized = window.sessionStorage.getItem(this._cacheKey());
if (!serialized) return null;
const entry = JSON.parse(serialized);
if (!entry || !entry.value || !entry.expiresAt) {
window.sessionStorage.removeItem(this._cacheKey());
return null;
}
return entry.expiresAt > Date.now() || allowExpired ? entry.value : null;
} catch (error) {
return null;
}
}
_setCache(value) {
try {
window.sessionStorage.setItem(this._cacheKey(), JSON.stringify({
expiresAt: Date.now() + this._cacheMinutes * 60 * 1000,
value: value
}));
} catch (error) {
console.warn('[TaxonomyService] Cache could not be written.', error);
}
}
@@ -97,7 +163,7 @@
return;
}
const termSets = termStore.getTermSetsByName(termSetIdentifier, 1033);
const termSets = termStore.getTermSetsByName(termSetIdentifier, this._languageLcid);
context.load(termSets);
context.executeQueryAsync(
@@ -123,14 +189,15 @@
const enumerator = terms.getEnumerator();
while (enumerator.moveNext()) {
const term = enumerator.get_current();
if (!term.get_isAvailableForTagging() || term.get_isDeprecated()) {
const properties = this._getCustomProperties(term);
if (!term.get_isAvailableForTagging() || term.get_isDeprecated() || this._asBoolean(properties['MegaMenu.Hidden'])) {
continue;
}
processedTerms.push({
Id: term.get_id().toString(),
Name: term.get_name(),
PathOfTerm: term.get_pathOfTerm(),
LocalCustomProperties: this._getCustomProperties(term),
LocalCustomProperties: properties,
IsRoot: term.get_pathOfTerm().split(';').length === 1
});
}
@@ -147,13 +214,20 @@
return {
_Sys_Nav_SimpleLinkUrl: props._Sys_Nav_SimpleLinkUrl || null,
_Sys_Nav_TargetUrl: props._Sys_Nav_TargetUrl || null,
_Sys_Nav_HoverText: props._Sys_Nav_HoverText || null
_Sys_Nav_HoverText: props._Sys_Nav_HoverText || null,
'MegaMenu.Hidden': props['MegaMenu.Hidden'] || null,
'MegaMenu.OpenInNewWindow': props['MegaMenu.OpenInNewWindow'] || null,
'MegaMenu.Description': props['MegaMenu.Description'] || null
};
} catch (e) {
return {};
}
}
_asBoolean(value) {
return value === true || ['true', '1', 'yes', 'ja'].indexOf(String(value || '').toLowerCase()) >= 0;
}
_processTerms(termsData) {
const itemsDict = new ItemDictionary();
const itemsByPath = {};
@@ -202,10 +276,11 @@
// ===========================================
class MegaMenuRenderer {
constructor(context, menuItems, menuMode) {
constructor(context, menuItems, menuMode, strings) {
this.context = context;
this.menuItems = menuItems;
this.menuMode = menuMode === 'flyout' ? 'flyout' : 'megaMenu';
this.strings = strings || { navigationLabel: 'Main navigation', openNavigation: 'Open navigation', closeNavigation: 'Close navigation', openSubmenu: 'Open submenu for', closeSubmenu: 'Close submenu for', submenuLabel: 'submenu', externalLink: 'external link' };
}
render(container) {
@@ -215,12 +290,21 @@
nav.id = 'Mega-Menu';
nav.className = 'mega-menu-main mega-menu-mode-' + this.menuMode;
nav.setAttribute('data-menu-mode', this.menuMode);
nav.setAttribute('role', 'navigation');
nav.setAttribute('aria-label', 'Hauptnavigation');
nav.setAttribute('aria-label', this.strings.navigationLabel);
const mobileToggle = document.createElement('button');
mobileToggle.type = 'button';
mobileToggle.className = 'mega-menu-mobile-toggle';
mobileToggle.setAttribute('aria-expanded', 'false');
mobileToggle.setAttribute('aria-controls', 'Mega-Menu-Items');
mobileToggle.setAttribute('aria-label', this.strings.openNavigation);
mobileToggle.innerHTML = '<span class="mega-menu-mobile-icon" aria-hidden="true"></span><span class="mega-menu-mobile-label"></span>';
mobileToggle.querySelector('.mega-menu-mobile-label').textContent = this.strings.navigationLabel;
nav.appendChild(mobileToggle);
const topLevelUl = document.createElement('ul');
topLevelUl.className = 'mega-menu-top-level';
topLevelUl.setAttribute('role', 'menubar');
topLevelUl.id = 'Mega-Menu-Items';
this.menuItems.forEach(topLevelItem => {
const topLevelLi = this.createTopLevelItem(topLevelItem);
@@ -236,35 +320,42 @@
createTopLevelItem(item) {
const li = document.createElement('li');
li.className = 'mega-menu-top-item';
li.setAttribute('role', 'none');
const hasChildren = item.items && item.items.length > 0;
li.className = hasChildren ? 'mega-menu-top-item has-children' : 'mega-menu-top-item';
if (item.url && item.items.length === 0) {
// Simple link
if (item.url) {
const a = document.createElement('a');
a.href = item.url;
a.textContent = item.title;
a.className = 'menu-item-link';
a.setAttribute('role', 'menuitem');
a.setAttribute('tabindex', '0');
this.applyLinkBehavior(a, item);
li.appendChild(a);
} else {
// Menu with submenu
const span = document.createElement('span');
span.textContent = item.title;
span.className = 'menu-item-text';
span.setAttribute('role', 'menuitem');
span.setAttribute('tabindex', '0');
span.setAttribute('aria-haspopup', 'true');
span.setAttribute('aria-expanded', 'false');
if (!hasChildren) span.setAttribute('tabindex', '0');
li.appendChild(span);
}
if (item.items.length > 0) {
const megaMenu = this.menuMode === 'flyout'
? this.createFlyoutMenu(item.items)
: this.createMegaMenu(item.items);
li.appendChild(megaMenu);
}
if (hasChildren) {
const toggle = document.createElement('button');
const menuId = 'Mega-Menu-Panel-' + String(item.id).replace(/[^a-z0-9_-]/gi, '');
toggle.type = 'button';
toggle.className = 'menu-item-toggle';
toggle.setAttribute('aria-haspopup', 'true');
toggle.setAttribute('aria-expanded', 'false');
toggle.setAttribute('aria-controls', menuId);
toggle.setAttribute('aria-label', this.strings.openSubmenu + ' ' + item.title);
toggle.innerHTML = '<span aria-hidden="true"></span>';
li.appendChild(toggle);
const megaMenu = this.menuMode === 'flyout'
? this.createFlyoutMenu(item.items)
: this.createMegaMenu(item.items);
megaMenu.id = menuId;
megaMenu.setAttribute('aria-expanded', 'false');
megaMenu.setAttribute('aria-label', item.title + ' ' + this.strings.submenuLabel);
li.appendChild(megaMenu);
}
return li;
@@ -273,7 +364,6 @@
createMegaMenu(categories) {
const megaMenuDiv = document.createElement('div');
megaMenuDiv.className = 'mega-menu';
megaMenuDiv.setAttribute('role', 'menu');
const gridDiv = document.createElement('div');
gridDiv.className = 'mega-menu-grid';
@@ -297,7 +387,7 @@
const a = document.createElement('a');
a.href = category.url;
a.textContent = category.title;
a.setAttribute('tabindex', '0');
this.applyLinkBehavior(a, category);
h3.appendChild(a);
} else {
const span = document.createElement('span');
@@ -307,19 +397,23 @@
categoryDiv.appendChild(h3);
if (category.description) {
const description = document.createElement('p');
description.className = 'mega-menu-description';
description.textContent = category.description;
categoryDiv.appendChild(description);
}
if (category.items.length > 0) {
const ul = document.createElement('ul');
ul.setAttribute('role', 'group');
category.items.forEach(link => {
const li = document.createElement('li');
li.setAttribute('role', 'none');
const a = document.createElement('a');
a.href = link.url;
a.href = link.url || '#';
a.textContent = link.title;
a.setAttribute('role', 'menuitem');
a.setAttribute('tabindex', '0');
this.applyLinkBehavior(a, link);
li.appendChild(a);
ul.appendChild(li);
@@ -334,7 +428,6 @@
createFlyoutMenu(items) {
const flyout = document.createElement('div');
flyout.className = 'mega-menu mega-menu-flyout';
flyout.setAttribute('role', 'menu');
const list = document.createElement('ul');
list.className = 'flyout-list flyout-level-2';
@@ -352,21 +445,28 @@
const element = document.createElement(item.url ? 'a' : 'span');
if (item.url) {
element.href = item.url;
this.applyLinkBehavior(element, item);
} else {
element.setAttribute('tabindex', '0');
}
element.textContent = item.title;
element.className = hasChildren ? 'flyout-link flyout-link-has-children' : 'flyout-link';
element.setAttribute('role', 'menuitem');
if (hasChildren) {
element.setAttribute('aria-haspopup', 'true');
}
li.appendChild(element);
if (hasChildren) {
const toggle = document.createElement('button');
const childId = 'Mega-Menu-Flyout-' + String(item.id).replace(/[^a-z0-9_-]/gi, '');
toggle.type = 'button';
toggle.className = 'flyout-toggle';
toggle.setAttribute('aria-expanded', 'false');
toggle.setAttribute('aria-controls', childId);
toggle.setAttribute('aria-label', this.strings.openSubmenu + ' ' + item.title);
toggle.innerHTML = '<span aria-hidden="true"></span>';
li.appendChild(toggle);
const childList = document.createElement('ul');
childList.className = 'flyout-list flyout-level-3';
childList.setAttribute('role', 'menu');
childList.id = childId;
childList.setAttribute('aria-label', item.title + ' ' + this.strings.submenuLabel);
item.items.forEach(child => childList.appendChild(this.createFlyoutItem(child)));
li.appendChild(childList);
}
@@ -375,15 +475,78 @@
}
attachEventListeners() {
// Keyboard and mouse event handling (simplified)
const menuItems = document.querySelectorAll('#Mega-Menu [role="menuitem"]');
menuItems.forEach(item => {
item.addEventListener('keydown', this.handleKeyDown.bind(this));
const parent = item.parentElement;
if (parent && parent.querySelector('.mega-menu')) {
parent.addEventListener('mouseenter', this.showMegaMenu);
parent.addEventListener('mouseleave', this.hideMegaMenu);
const renderer = this;
const toggles = document.querySelectorAll('#Mega-Menu > ul > li > .menu-item-toggle');
Array.prototype.forEach.call(toggles, toggle => {
const parent = toggle.parentElement;
const panel = parent.querySelector('.mega-menu');
const setOpen = open => {
renderer.closeAll(panel);
toggle.setAttribute('aria-expanded', String(open));
toggle.setAttribute('aria-label', (open ? renderer.strings.closeSubmenu : renderer.strings.openSubmenu) + ' ' + renderer.getToggleLabel(toggle));
panel.setAttribute('aria-expanded', String(open));
panel.classList.toggle('js-open', open);
};
toggle.addEventListener('click', event => { event.preventDefault(); setOpen(toggle.getAttribute('aria-expanded') !== 'true'); });
toggle.addEventListener('keydown', event => {
if (event.key === 'ArrowDown') {
event.preventDefault(); setOpen(true);
const firstLink = panel.querySelector('a');
if (firstLink) firstLink.focus();
} else if (event.key === 'Escape' || event.key === 'ArrowUp') {
event.preventDefault(); setOpen(false); toggle.focus();
}
});
let closeTimer;
parent.addEventListener('mouseenter', () => { window.clearTimeout(closeTimer); setOpen(true); });
parent.addEventListener('mouseleave', () => { closeTimer = window.setTimeout(() => setOpen(false), 180); });
});
const flyoutToggles = document.querySelectorAll('#Mega-Menu .flyout-toggle');
Array.prototype.forEach.call(flyoutToggles, toggle => {
const parent = toggle.parentElement;
const setOpen = open => {
toggle.setAttribute('aria-expanded', String(open));
const label = parent.querySelector('.flyout-link');
toggle.setAttribute('aria-label', (open ? renderer.strings.closeSubmenu : renderer.strings.openSubmenu) + ' ' + (label ? label.textContent : ''));
parent.classList.toggle('is-open', open);
};
toggle.addEventListener('click', event => { event.preventDefault(); setOpen(toggle.getAttribute('aria-expanded') !== 'true'); });
toggle.addEventListener('keydown', event => { if (event.key === 'Escape') { event.preventDefault(); setOpen(false); toggle.focus(); } });
parent.addEventListener('mouseenter', () => setOpen(true));
parent.addEventListener('mouseleave', () => setOpen(false));
parent.addEventListener('focusin', () => setOpen(true));
parent.addEventListener('focusout', () => window.setTimeout(() => { if (!parent.contains(document.activeElement)) setOpen(false); }, 0));
});
const mobileToggle = document.querySelector('#Mega-Menu > .mega-menu-mobile-toggle');
if (mobileToggle) {
mobileToggle.addEventListener('click', () => {
const nav = mobileToggle.parentElement;
const open = mobileToggle.getAttribute('aria-expanded') !== 'true';
mobileToggle.setAttribute('aria-expanded', String(open));
mobileToggle.setAttribute('aria-label', open ? renderer.strings.closeNavigation : renderer.strings.openNavigation);
nav.classList.toggle('is-mobile-open', open);
if (!open) renderer.closeAll();
});
}
document.addEventListener('keydown', event => {
if (event.key === 'Escape') {
const openPanel = document.querySelector('#Mega-Menu .mega-menu.js-open');
if (openPanel) {
const toggle = openPanel.previousElementSibling;
renderer.closePanel(toggle, openPanel);
toggle.focus();
}
}
if ((event.key === 'ArrowLeft' || event.key === 'ArrowRight') && document.activeElement.closest('.mega-menu-top-item')) {
const items = Array.prototype.slice.call(document.querySelectorAll('#Mega-Menu > ul > .mega-menu-top-item'));
const current = document.activeElement.closest('.mega-menu-top-item');
const index = items.indexOf(current);
const target = items[(index + (event.key === 'ArrowRight' ? 1 : -1) + items.length) % items.length];
const focusTarget = target.querySelector('a, .menu-item-toggle');
if (focusTarget) { event.preventDefault(); focusTarget.focus(); }
}
});
}
@@ -398,49 +561,32 @@
document.body.appendChild(announcer);
}
showMegaMenu() {
const megaMenu = this.querySelector('.mega-menu');
if (megaMenu) {
megaMenu.classList.add('js-open');
const menuItem = this.querySelector('[role="menuitem"]');
if (menuItem) {
menuItem.setAttribute('aria-expanded', 'true');
}
}
closePanel(toggle, panel) {
toggle.setAttribute('aria-expanded', 'false');
toggle.setAttribute('aria-label', this.strings.openSubmenu + ' ' + this.getToggleLabel(toggle));
panel.setAttribute('aria-expanded', 'false');
panel.classList.remove('js-open');
}
hideMegaMenu() {
const megaMenu = this.querySelector('.mega-menu');
if (megaMenu) {
megaMenu.classList.remove('js-open');
const menuItem = this.querySelector('[role="menuitem"]');
if (menuItem) {
menuItem.setAttribute('aria-expanded', 'false');
}
}
closeAll(exceptPanel) {
const panels = document.querySelectorAll('#Mega-Menu .mega-menu.js-open');
Array.prototype.forEach.call(panels, panel => {
if (panel !== exceptPanel) this.closePanel(panel.previousElementSibling, panel);
});
}
handleKeyDown(e) {
// Keyboard navigation logic (simplified)
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
const parent = e.target.parentElement;
const megaMenu = parent.querySelector('.mega-menu');
if (megaMenu) {
megaMenu.classList.toggle('js-open');
e.target.setAttribute('aria-expanded',
megaMenu.classList.contains('js-open') ? 'true' : 'false');
}
} else if (e.key === 'Escape') {
const megaMenu = document.querySelector('.mega-menu.js-open');
if (megaMenu) {
megaMenu.classList.remove('js-open');
const menuItem = megaMenu.parentElement.querySelector('[role="menuitem"]');
if (menuItem) {
menuItem.setAttribute('aria-expanded', 'false');
menuItem.focus();
}
}
getToggleLabel(toggle) {
const label = toggle.parentElement.querySelector('.menu-item-link, .menu-item-text');
return label ? label.textContent : '';
}
applyLinkBehavior(link, item) {
if (item.openInNewWindow) {
link.target = '_blank';
link.rel = 'noopener noreferrer';
}
if (item.external) {
link.setAttribute('aria-label', item.title + ' (' + this.strings.externalLink + ')');
}
}