Update MegaMenu Application Customizer: Version bump to 1.1.0, localization support added, and unnecessary files removed

- Deleted obsolete localization file for English (en-us).
- Updated version number from 1.0.4 to 1.1.0 in manifests.js and manifests.json.
- Added localization support for German (de-de) in a new localization file.
- Removed unnecessary dependencies from manifests.
- Added .gitignore to exclude build artifacts and temporary files.
This commit is contained in:
Torsten Brendgen
2026-07-16 22:43:31 +02:00
parent a2b8165262
commit 97d2b6b5d2
53 changed files with 1071 additions and 1065 deletions

View File

@@ -103,6 +103,14 @@ $mm-layer-index: var(--megaMenuZIndex, 6000);
z-index: $mm-layer-index;
}
.mega-menu-status {
padding: 8px 14px;
border-bottom: 1px solid $mm-panel-border;
background: $mm-focus-soft;
color: $mm-text;
font-size: 13px;
}
.mega-menu-main {
position: relative;
width: 100%;
@@ -145,7 +153,7 @@ $mm-layer-index: var(--megaMenuZIndex, 6000);
}
.mega-menu-main > ul > li > a,
.mega-menu-main > ul > li > span[role="menuitem"],
.mega-menu-main > ul > li > .menu-item-text,
.menu-item-link,
.menu-item-text {
position: relative;
@@ -199,7 +207,7 @@ $mm-layer-index: var(--megaMenuZIndex, 6000);
}
.mega-menu-main > ul > li:hover > a,
.mega-menu-main > ul > li:hover > span[role="menuitem"],
.mega-menu-main > ul > li:hover > .menu-item-text,
.mega-menu-main > ul > li > a[aria-expanded="true"],
.mega-menu-main > ul > li > span[aria-expanded="true"],
.menu-item-link:hover,
@@ -214,7 +222,7 @@ $mm-layer-index: var(--megaMenuZIndex, 6000);
}
.mega-menu-main > ul > li > a:focus,
.mega-menu-main > ul > li > span[role="menuitem"]:focus,
.mega-menu-main > ul > li > .menu-item-text:focus,
.menu-item-link:focus,
.menu-item-text:focus {
color: $mm-nav-text;
@@ -416,7 +424,7 @@ $mm-layer-index: var(--megaMenuZIndex, 6000);
}
.mega-menu-main > ul > li > a,
.mega-menu-main > ul > li > span[role="menuitem"],
.mega-menu-main > ul > li > .menu-item-text,
.menu-item-link,
.menu-item-text {
min-height: 36px;
@@ -448,7 +456,7 @@ $mm-layer-index: var(--megaMenuZIndex, 6000);
.skip-link,
.menu-item-has-children::after,
.mega-menu-main > ul > li > a,
.mega-menu-main > ul > li > span[role="menuitem"],
.mega-menu-main > ul > li > .menu-item-text,
.menu-item-link,
.menu-item-text,
.mega-menu,
@@ -460,7 +468,7 @@ $mm-layer-index: var(--megaMenuZIndex, 6000);
@media (prefers-contrast: high) {
.mega-menu-main > ul > li > a:focus,
.mega-menu-main > ul > li > span[role="menuitem"]:focus,
.mega-menu-main > ul > li > .menu-item-text:focus,
.menu-item-link:focus,
.menu-item-text:focus,
.mega-menu-category > h3 > a:focus,

View File

@@ -1,8 +1,6 @@
/* tslint:disable */
require('./MegaMenu.module.css');
const styles = {
mmSlideIn: 'mmSlideIn_09a8e1a7',
mmFadeIn: 'mmFadeIn_09a8e1a7',
};
export default styles;

View File

@@ -22,7 +22,9 @@ const LOG_SOURCE: string = 'MegaMenuApplicationCustomizer';
export const UserCustomActionMegaMenuId: string = 'abc3361f-bb2d-491f-aba3-cd51c19a299b';
export interface IMegaMenuApplicationCustomizerProperties {
termSetName: string;
termSetName?: string;
termSetId?: string;
cacheMinutes?: number;
cssUrl?: string;
debug?: boolean;
}
@@ -31,6 +33,8 @@ export default class MegaMenuApplicationCustomizer
extends BaseApplicationCustomizer<IMegaMenuApplicationCustomizerProperties> {
private _topPlaceholder: PlaceholderContent | undefined;
private _menuContainer: HTMLElement | undefined;
private _renderer: MegaMenuRenderer | undefined;
@override
public onInit(): Promise<void> {
@@ -64,16 +68,18 @@ export default class MegaMenuApplicationCustomizer
return;
}
if (!this.properties.termSetName) {
debugWarn(this._isDebugEnabled(), LOG_SOURCE, 'No termSetName configured. Mega Menu rendering is skipped.');
const termSetIdentifier: string = this._getTermSetIdentifier();
if (!termSetIdentifier) {
debugWarn(this._isDebugEnabled(), LOG_SOURCE, 'No termSetId or termSetName configured. Mega Menu rendering is skipped.');
this._renderStatus(strings.ConfigurationMissing);
return;
}
this._renderMegaMenu(this.properties.termSetName);
this._renderMegaMenu(termSetIdentifier);
}
}
private async _renderMegaMenu(termSetName: string, debug: boolean = this._isDebugEnabled()): Promise<void> {
private async _renderMegaMenu(termSetIdentifier: string, debug: boolean = this._isDebugEnabled()): Promise<void> {
if (!this._topPlaceholder) {
return;
}
@@ -81,28 +87,34 @@ export default class MegaMenuApplicationCustomizer
try {
const taxonomyService: TaxonomyNavigationService = new TaxonomyNavigationService(
this.context,
termSetName,
debug
termSetIdentifier,
debug,
this._getCacheMinutes()
);
const menuItems: IMenuItem[] = await taxonomyService.getMenuItems();
const renderer: MegaMenuRenderer = new MegaMenuRenderer(
if (this._renderer) {
this._renderer.dispose();
}
this._renderer = new MegaMenuRenderer(
menuItems,
debug
);
const container = this._getOrCreateContainer('CustomHeader', this._topPlaceholder);
this._menuContainer = this._getOrCreateContainer('CustomHeader', this._topPlaceholder);
if (container) {
renderer.render(container);
if (this._menuContainer) {
this._renderer.render(this._menuContainer);
} else {
renderer.render(this._topPlaceholder.domElement);
this._renderer.render(this._topPlaceholder.domElement);
}
debugLog(debug, LOG_SOURCE, 'MegaMenu rendered successfully with ' + menuItems.length + ' top-level items.');
} catch (error) {
debugError(debug, LOG_SOURCE, 'Error rendering MegaMenu.', error);
this._renderStatus(strings.LoadError);
}
}
@@ -110,9 +122,13 @@ export default class MegaMenuApplicationCustomizer
const container = document.getElementById(id);
if (container) {
const div = document.createElement('div');
container.appendChild(div);
return div;
let host: HTMLElement = document.getElementById('MegaMenuHost');
if (!host) {
host = document.createElement('div');
host.id = 'MegaMenuHost';
container.appendChild(host);
}
return host;
}
return placeholder.domElement;
@@ -123,6 +139,15 @@ export default class MegaMenuApplicationCustomizer
let link: HTMLLinkElement = document.getElementById(externalCssLinkId) as HTMLLinkElement;
if (cssUrl && cssUrl.trim() !== '') {
const validatedUrl: string | undefined = this._validateCssUrl(cssUrl);
if (!validatedUrl) {
debugWarn(debug, LOG_SOURCE, 'Rejected unsafe external CSS URL:', cssUrl);
if (link) {
link.remove();
}
return;
}
if (!link) {
const head: HTMLHeadElement = document.getElementsByTagName('head')[0];
link = document.createElement('link');
@@ -138,16 +163,76 @@ export default class MegaMenuApplicationCustomizer
head.appendChild(link);
}
link.href = cssUrl;
link.href = validatedUrl;
} else if (link) {
link.remove();
}
}
private _onDispose = (): void => {
this.context.placeholderProvider.changedEvent.remove(this, this._renderPlaceHolders);
if (this._renderer) {
this._renderer.dispose();
this._renderer = undefined;
}
const externalCssLink: HTMLElement = document.getElementById('mega-menu-additional-css-34FAB720');
if (externalCssLink) {
externalCssLink.remove();
}
this._menuContainer = undefined;
this._topPlaceholder = undefined;
debugLog(this._isDebugEnabled(), LOG_SOURCE, 'Disposed custom top placeholder.');
}
private _getTermSetIdentifier(): string {
const termSetId: string = this.properties && this.properties.termSetId
? this.properties.termSetId.trim()
: '';
if (termSetId && this._isGuid(termSetId)) {
return termSetId;
}
return this.properties && this.properties.termSetName
? this.properties.termSetName.trim()
: '';
}
private _getCacheMinutes(): number {
const value: number = this.properties ? Number(this.properties.cacheMinutes) : 15;
return isFinite(value) ? Math.min(Math.max(Math.floor(value), 1), 1440) : 15;
}
private _validateCssUrl(cssUrl: string): string | undefined {
try {
const parsed: URL = new URL(cssUrl.trim(), window.location.origin);
const isHttp: boolean = parsed.protocol === 'http:' || parsed.protocol === 'https:';
const isSameOrigin: boolean = parsed.origin === window.location.origin;
if (!isHttp || (!isSameOrigin && parsed.protocol !== 'https:')) {
return undefined;
}
return parsed.href;
} catch (error) {
return undefined;
}
}
private _renderStatus(message: string): void {
if (!this._topPlaceholder) {
return;
}
this._menuContainer = this._getOrCreateContainer('CustomHeader', this._topPlaceholder);
const container: HTMLElement = this._menuContainer || this._topPlaceholder.domElement;
container.innerHTML = '';
const status: HTMLElement = document.createElement('div');
status.className = 'mega-menu-status';
status.setAttribute('role', 'status');
status.textContent = message;
container.appendChild(status);
}
private _isGuid(value: string): boolean {
return /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(value);
}
private _isDebugEnabled(debugOverride?: boolean): boolean {
if (typeof debugOverride === 'boolean') {
return debugOverride;
@@ -155,4 +240,4 @@ export default class MegaMenuApplicationCustomizer
return !!(this.properties && this.properties.debug === true);
}
}
}

View File

@@ -13,25 +13,29 @@ const LOG_SOURCE: string = 'MegaMenuRenderer';
export class MegaMenuRenderer {
private static readonly hoverOpenDelayMs: number = 140;
private static readonly hoverCloseDelayMs: number = 180;
private _container: HTMLElement | undefined;
private _documentKeydownHandler: ((event: KeyboardEvent) => void) | undefined;
private _documentClickHandler: ((event: MouseEvent) => void) | undefined;
private _announcer: HTMLElement | undefined;
constructor(
private menuItems: IMenuItem[],
private debug: boolean = false
) { }
public render(container: HTMLElement) {
public render(container: HTMLElement): void {
this.dispose();
this._container = container;
container.innerHTML = '';
container.id = 'CustomNavigation';
const nav = document.createElement('nav');
nav.id = 'Mega-Menu';
nav.className = 'mega-menu-main';
nav.setAttribute('role', 'navigation');
nav.setAttribute('aria-label', 'Hauptnavigation');
const topLevelUl = document.createElement('ul');
topLevelUl.className = 'mega-menu-top-level';
topLevelUl.setAttribute('role', 'menubar');
this.menuItems.forEach(topLevelItem => {
const topLevelLi = this.createTopLevelItem(topLevelItem);
@@ -45,6 +49,25 @@ export class MegaMenuRenderer {
this.createScreenReaderAnnouncer();
}
public dispose(): void {
if (this._documentKeydownHandler) {
document.removeEventListener('keydown', this._documentKeydownHandler);
this._documentKeydownHandler = undefined;
}
if (this._documentClickHandler) {
document.removeEventListener('click', this._documentClickHandler);
this._documentClickHandler = undefined;
}
if (this._announcer && this._announcer.parentElement) {
this._announcer.parentElement.removeChild(this._announcer);
}
this._announcer = undefined;
if (this._container) {
this._container.innerHTML = '';
}
this._container = undefined;
}
private createTopLevelItem(item: IMenuItem): HTMLLIElement {
const li = document.createElement('li');
const hasChildren = item.hasChildren() && item.items && item.items.length > 0;
@@ -57,7 +80,6 @@ export class MegaMenuRenderer {
isActive ? 'is-active' : undefined,
isCurrent ? 'is-current' : undefined
);
li.setAttribute('role', 'none');
const topElement = this.createTopLevelElement(item, hasChildren, isActive, isCurrent);
li.appendChild(topElement);
@@ -83,7 +105,6 @@ export class MegaMenuRenderer {
element.setAttribute('tabindex', '0');
}
element.setAttribute('role', 'menuitem');
element.textContent = item.label;
element.className = this.joinClasses(
element.className,
@@ -111,7 +132,6 @@ export class MegaMenuRenderer {
private createMegaMenu(parentItem: IMenuItem): HTMLDivElement {
const megaMenuDiv = document.createElement('div');
megaMenuDiv.className = 'mega-menu';
megaMenuDiv.setAttribute('role', 'menu');
megaMenuDiv.setAttribute('aria-expanded', 'false');
megaMenuDiv.setAttribute('aria-label', parentItem.label + ' Unterkategorien');
@@ -213,7 +233,7 @@ export class MegaMenuRenderer {
}
private attachEventListeners(): void {
const headings = document.querySelectorAll('#Mega-Menu > ul > li > a, #Mega-Menu > ul > li > span[role="menuitem"]');
const headings = document.querySelectorAll('#Mega-Menu > ul > li > a, #Mega-Menu > ul > li > .menu-item-text');
for (let i = 0; i < headings.length; i++) {
const heading = headings[i] as HTMLElement;
@@ -336,7 +356,7 @@ export class MegaMenuRenderer {
}
private attachGlobalKeyboardNavigation(): void {
document.addEventListener('keydown', (e: KeyboardEvent) => {
this._documentKeydownHandler = (e: KeyboardEvent): void => {
const activeElement = document.activeElement as HTMLElement;
if (e.key === 'Escape') {
@@ -380,11 +400,12 @@ export class MegaMenuRenderer {
}
}
}
});
};
document.addEventListener('keydown', this._documentKeydownHandler);
}
private attachGlobalClickOutsideHandler(): void {
document.addEventListener('click', (e: MouseEvent) => {
this._documentClickHandler = (e: MouseEvent): void => {
const eventTarget = e.target as Element;
const isInsideNavigation = !!(eventTarget && typeof eventTarget.closest === 'function' &&
eventTarget.closest('#CustomNavigation'));
@@ -399,7 +420,8 @@ export class MegaMenuRenderer {
debugLog(this.debug, LOG_SOURCE, 'Closing menu because of outside click.');
this.closeAllMegaMenus();
}
});
};
document.addEventListener('click', this._documentClickHandler);
}
private openMegaMenu(trigger: HTMLElement, menu: HTMLElement): void {
@@ -407,6 +429,7 @@ export class MegaMenuRenderer {
trigger.setAttribute('aria-expanded', 'true');
menu.setAttribute('aria-expanded', 'true');
menu.classList.add('js-open');
this.announce((trigger.textContent || '') + ' geöffnet');
debugLog(this.debug, LOG_SOURCE, 'Menu opened:', trigger.textContent);
}
@@ -414,6 +437,7 @@ export class MegaMenuRenderer {
trigger.setAttribute('aria-expanded', 'false');
menu.setAttribute('aria-expanded', 'false');
menu.classList.remove('js-open');
this.announce((trigger.textContent || '') + ' geschlossen');
debugLog(this.debug, LOG_SOURCE, 'Menu closed:', trigger.textContent);
}
@@ -514,7 +538,9 @@ export class MegaMenuRenderer {
}
private createScreenReaderAnnouncer(): void {
if (document.getElementById('mega-menu-sr-announcer')) {
const existingAnnouncer: HTMLElement = document.getElementById('mega-menu-sr-announcer');
if (existingAnnouncer) {
this._announcer = existingAnnouncer;
return;
}
@@ -524,7 +550,19 @@ export class MegaMenuRenderer {
srAnnouncer.setAttribute('aria-atomic', 'true');
srAnnouncer.className = 'sr-only';
document.body.appendChild(srAnnouncer);
this._announcer = srAnnouncer;
debugLog(this.debug, LOG_SOURCE, 'Screen reader announcer is ready.');
}
private announce(message: string): void {
if (this._announcer) {
this._announcer.textContent = '';
window.setTimeout((): void => {
if (this._announcer) {
this._announcer.textContent = message;
}
}, 20);
}
}
}

View File

@@ -1,210 +0,0 @@
// tslint:disable:max-line-length export-name
import { ApplicationCustomizerContext } from '@microsoft/sp-application-base';
import { IMegaMenuApplicationCustomizerProperties, UserCustomActionMegaMenuId } from './MegaMenuApplicationCustomizer';
import { UserCustomActionService } from '../../services/UserCustomActionService/UserCustomActionService';
import { UserCustomActionScope } from '../../services/UserCustomActionService/UserCustomActionScope';
import { IUserCustomActionProps } from '../../services/UserCustomActionService/IUserCustomActionProps';
import { debugError } from '../../services/MegaMenuDebug';
const LOG_SOURCE: string = 'MegaMenuSettingsPanel';
export class MegaMenuSettingsPanel {
private _service: UserCustomActionService;
private _ucaId: string;
private _panelElement: HTMLElement | undefined = undefined;
private _overlayElement: HTMLElement | undefined = undefined;
constructor(
private context: ApplicationCustomizerContext,
private dataUpdated: (data: IMegaMenuApplicationCustomizerProperties) => void,
private debug: boolean = false
) {
this._service = new UserCustomActionService(this.context, this.debug);
}
public async open(): Promise<void> {
if (this._panelElement) {
return;
}
const currentProps: IMegaMenuApplicationCustomizerProperties = await this.readApplicationCustomizerProps();
this._createPanel(currentProps);
}
public close(): void {
if (this._panelElement) {
this._panelElement.remove();
this._panelElement = undefined;
}
if (this._overlayElement) {
this._overlayElement.remove();
this._overlayElement = undefined;
}
document.body.focus();
document.body.blur();
}
private async readApplicationCustomizerProps(): Promise<IMegaMenuApplicationCustomizerProperties> {
const ucas: IUserCustomActionProps[] = await this._service.getUserCustomActions(UserCustomActionScope.Site);
const candidates: IUserCustomActionProps[] = ucas.filter(uca => uca.ClientSideComponentId === UserCustomActionMegaMenuId);
if (candidates.length) {
const uca: IUserCustomActionProps = candidates[0];
this._ucaId = uca.Id;
if (uca.ClientSideComponentProperties) {
return JSON.parse(uca.ClientSideComponentProperties) as IMegaMenuApplicationCustomizerProperties;
}
return {
termSetName: '',
cssUrl: '',
debug: false
};
}
debugError(this.debug, LOG_SOURCE, 'UserCustomAction for the MegaMenu was not found.');
return {
termSetName: '',
cssUrl: '',
debug: false
};
}
private async saveApplicationCustomizerProps(componentProps: IMegaMenuApplicationCustomizerProperties): Promise<void> {
try {
const newUserCustomActionsProperty: {} = {
ClientSideComponentProperties: JSON.stringify(componentProps)
};
await this._service.updateUserCustomAction(UserCustomActionScope.Site, this._ucaId, newUserCustomActionsProperty);
this.debug = componentProps.debug === true;
this._service = new UserCustomActionService(this.context, this.debug);
this.dataUpdated(componentProps);
} catch (e) {
debugError(this.debug, LOG_SOURCE, 'Error saving MegaMenu settings.', e);
}
}
private _createPanel(props: IMegaMenuApplicationCustomizerProperties): void {
const overlay: HTMLElement = document.createElement('div');
overlay.className = 'mm-settings-overlay';
overlay.tabIndex = -1;
overlay.onclick = () => this.close();
this._overlayElement = overlay;
const panel: HTMLElement = document.createElement('div');
panel.className = 'mm-settings-panel';
panel.setAttribute('role', 'dialog');
panel.setAttribute('aria-modal', 'true');
panel.setAttribute('aria-label', 'MegaMenu Einstellungen');
panel.innerHTML = this._getMarkup(props.termSetName, props.cssUrl || '', props.debug === true);
this._panelElement = panel;
document.body.appendChild(overlay);
document.body.appendChild(panel);
const closeBtn: HTMLButtonElement = panel.querySelector('.mm-settings-close') as HTMLButtonElement;
const cancelBtn: HTMLButtonElement = panel.querySelector('.mm-settings-cancel') as HTMLButtonElement;
const saveBtn: HTMLButtonElement = panel.querySelector('.mm-settings-save') as HTMLButtonElement;
const firstInput: HTMLInputElement = panel.querySelector('#mm-setting-termset') as HTMLInputElement;
if (closeBtn) { closeBtn.onclick = () => this.close(); }
if (cancelBtn) { cancelBtn.onclick = () => this.close(); }
if (saveBtn) { saveBtn.onclick = () => this._save(); }
panel.addEventListener('keydown', (e: KeyboardEvent) => {
if (e.key === 'Escape') {
e.preventDefault();
this.close();
} else if (e.key === 'Tab') {
this._trapFocus(e);
}
});
setTimeout(() => {
if (firstInput) {
firstInput.focus();
}
}, 0);
}
private _getMarkup(termSet: string, cssUrl: string, debug: boolean): string {
return `<div class='mm-settings-header'>
<h2 class='mm-settings-title'>Einstellungen</h2>
<button type='button' class='mm-settings-close' aria-label='Schliessen'>&times;</button>
</div>
<div class='mm-settings-body'>
<div class='mm-settings-field'>
<label for='mm-setting-termset'>Name des Navigations-Termsets</label>
<input id='mm-setting-termset' type='text' value='${this._escape(termSet)}' />
</div>
<div class='mm-settings-field'>
<label for='mm-setting-css'>Pfad zu zusaetzlicher CSS-Datei</label>
<input id='mm-setting-css' type='text' value='${this._escape(cssUrl)}' />
</div>
<div class='mm-settings-field'>
<label for='mm-setting-debug'>
<input id='mm-setting-debug' type='checkbox' ${debug ? 'checked' : ''} />
Debug-Ausgaben in der Browser-Konsole aktivieren
</label>
</div>
</div>
<div class='mm-settings-footer'>
<button type='button' class='mm-settings-save ms-Button ms-Button--primary'><span>Speichern</span></button>
<button type='button' class='mm-settings-cancel ms-Button'><span>Abbrechen</span></button>
</div>`;
}
private _save(): void {
if (!this._panelElement) {
return;
}
const termSetInput: HTMLInputElement = this._panelElement.querySelector('#mm-setting-termset') as HTMLInputElement;
const cssInput: HTMLInputElement = this._panelElement.querySelector('#mm-setting-css') as HTMLInputElement;
const debugInput: HTMLInputElement = this._panelElement.querySelector('#mm-setting-debug') as HTMLInputElement;
this.saveApplicationCustomizerProps({
termSetName: termSetInput && termSetInput.value ? termSetInput.value : '',
cssUrl: cssInput && cssInput.value ? cssInput.value : '',
debug: !!(debugInput && debugInput.checked)
});
this.close();
}
private _trapFocus(e: KeyboardEvent): void {
if (!this._panelElement) {
return;
}
const focusable: NodeListOf<Element> = this._panelElement.querySelectorAll('button, input');
if (!focusable || focusable.length === 0) {
return;
}
const first: HTMLElement = focusable[0] as HTMLElement;
const last: HTMLElement = focusable[focusable.length - 1] as HTMLElement;
const active: HTMLElement = document.activeElement as HTMLElement;
if (e.shiftKey && active === first) {
e.preventDefault();
last.focus();
} else if (!e.shiftKey && active === last) {
e.preventDefault();
first.focus();
}
}
private _escape(value: string): string {
if (value) {
return value.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
return '';
}
}

View File

@@ -0,0 +1,7 @@
define([], function() {
return {
"Title": "MegaMenuApplicationCustomizer",
"ConfigurationMissing": "Die Navigation ist nicht konfiguriert.",
"LoadError": "Die Navigation konnte nicht geladen werden."
};
});

View File

@@ -1,5 +1,7 @@
define([], function() {
return {
"Title": "MegaMenuApplicationCustomizer"
"Title": "MegaMenuApplicationCustomizer",
"ConfigurationMissing": "Navigation is not configured.",
"LoadError": "Navigation could not be loaded."
}
});
});

View File

@@ -1,5 +1,7 @@
declare interface IMegaMenuApplicationCustomizerStrings {
Title: string;
ConfigurationMissing: string;
LoadError: string;
}
declare module 'MegaMenuApplicationCustomizerStrings' {

View File

@@ -4,4 +4,5 @@ export interface ISPTermStorePickerServiceProps {
hideDeprecatedTags: boolean;
hideTagsNotAvailableForTagging: boolean;
anchorId: string;
}
cacheMinutes: number;
}

View File

@@ -1,4 +1,5 @@
export function debugLog(enabled: boolean, source: string, message: string, ...args: any[]): void {
// tslint:disable:no-any
export function debugLog(enabled: boolean, source: string, message: string, ...args: any[]): void {
if (!enabled) {
return;
}
@@ -23,4 +24,4 @@ export function debugError(enabled: boolean, source: string, message: string, ..
const output: any[] = ['[' + source + '] ' + message].concat(args || []);
console.error.apply(console, output);
}
}

View File

@@ -12,6 +12,18 @@ import { ApplicationCustomizerContext } from '@microsoft/sp-application-base';
import { debugError } from './MegaMenuDebug';
const EmptyGuid: string = '00000000-0000-0000-0000-000000000000';
const TermCachePrefix: string = 'MegaMenu:TermSet:';
const PickerCachePrefix: string = 'MegaMenu:PickerTerms:';
interface ITermCacheEntry {
expiresAt: number;
value: ITermSet;
}
interface IPickerTermCacheEntry {
expiresAt: number;
value: IPickerTerm[];
}
/**
* Service implementation to manage term stores in SharePoint
@@ -31,7 +43,7 @@ export default class SPTermStorePickerService {
public async getTermLabels(termId: string): Promise<string[]> {
let result: string[] = null;
try {
const data = `<Request AddExpandoFieldTypeSuffix="true" SchemaVersion="15.0.0.0" LibraryVersion="16.0.0.0" ApplicationName=".NET Library" xmlns="http://schemas.microsoft.com/sharepoint/clientquery/2009"><Actions><ObjectPath Id="8" ObjectPathId="7" /><ObjectIdentityQuery Id="9" ObjectPathId="7" /><ObjectPath Id="11" ObjectPathId="10" /><ObjectIdentityQuery Id="12" ObjectPathId="10" /><ObjectPath Id="14" ObjectPathId="13" /><ObjectIdentityQuery Id="15" ObjectPathId="13" /><Query Id="16" ObjectPathId="13"><Query SelectAllProperties="false"><Properties><Property Name="Labels" SelectAll="true"><Query SelectAllProperties="false"><Properties /></Query></Property></Properties></Query></Query></Actions><ObjectPaths><StaticMethod Id="7" Name="GetTaxonomySession" TypeId="{981cbc68-9edc-4f8d-872f-71146fcbb84f}" /><Method Id="10" ParentId="7" Name="GetDefaultKeywordsTermStore" /><Method Id="13" ParentId="10" Name="GetTerm"><Parameters><Parameter Type="Guid">${termId}</Parameter></Parameters></Method></ObjectPaths></Request>`;
const data = `<Request AddExpandoFieldTypeSuffix="true" SchemaVersion="15.0.0.0" LibraryVersion="16.0.0.0" ApplicationName=".NET Library" xmlns="http://schemas.microsoft.com/sharepoint/clientquery/2009"><Actions><ObjectPath Id="8" ObjectPathId="7" /><ObjectIdentityQuery Id="9" ObjectPathId="7" /><ObjectPath Id="11" ObjectPathId="10" /><ObjectIdentityQuery Id="12" ObjectPathId="10" /><ObjectPath Id="14" ObjectPathId="13" /><ObjectIdentityQuery Id="15" ObjectPathId="13" /><Query Id="16" ObjectPathId="13"><Query SelectAllProperties="false"><Properties><Property Name="Labels" SelectAll="true"><Query SelectAllProperties="false"><Properties /></Query></Property></Properties></Query></Query></Actions><ObjectPaths><StaticMethod Id="7" Name="GetTaxonomySession" TypeId="{981cbc68-9edc-4f8d-872f-71146fcbb84f}" /><Method Id="10" ParentId="7" Name="GetDefaultSiteCollectionTermStore" /><Method Id="13" ParentId="10" Name="GetTerm"><Parameters><Parameter Type="Guid">${termId}</Parameter></Parameters></Method></ObjectPaths></Request>`;
const reqHeaders = new Headers();
reqHeaders.append('accept', 'application/json');
@@ -43,6 +55,7 @@ export default class SPTermStorePickerService {
};
const callResult = await this.context.spHttpClient.post(this.clientServiceUrl, SPHttpClient.configurations.v1, httpPostOptions);
this.ensureSuccessfulResponse(callResult, 'Term labels');
const jsonResult = await callResult.json();
const node = jsonResult.find(x => x._ObjectType_ === 'SP.Taxonomy.Term');
@@ -73,6 +86,7 @@ export default class SPTermStorePickerService {
};
return this.context.spHttpClient.post(this.clientServiceUrl, SPHttpClient.configurations.v1, httpPostOptions).then((serviceResponse: SPHttpClientResponse) => {
this.ensureSuccessfulResponse(serviceResponse, 'Term stores');
return serviceResponse.json().then((serviceJSONResponse: any) => {
// Construct results
const termStoreResult: ITermStore[] = serviceJSONResponse.filter((r: { [x: string]: string; }) => r['_ObjectType_'] === 'SP.Taxonomy.TermStore');
@@ -124,7 +138,13 @@ export default class SPTermStorePickerService {
* Retrieve all terms for the given term set
* @param termset
*/
public async getAllTerms(termset: string, hideDeprecatedTags?: boolean, hideTagsNotAvailableForTagging?: boolean, useSessionStorage: boolean = true): Promise<ITermSet> {
public async getAllTerms(
termset: string,
hideDeprecatedTags?: boolean,
hideTagsNotAvailableForTagging?: boolean,
useSessionStorage: boolean = true,
cacheMinutes: number = 15
): Promise<ITermSet> {
let termsetId: string = termset;
// Check if the provided term set property is a GUID or string
if (!this.isGuid(termset)) {
@@ -139,14 +159,14 @@ export default class SPTermStorePickerService {
}
}
const childTerms = this.getTermsById(termsetId, useSessionStorage);
const childTerms = this.getCachedTermSet(termsetId, useSessionStorage);
if (childTerms) {
return childTerms;
}
// Request body to retrieve all terms for the given term set
const data = `<Request xmlns="http://schemas.microsoft.com/sharepoint/clientquery/2009" SchemaVersion="15.0.0.0" LibraryVersion="16.0.0.0" ApplicationName="Javascript Library"><Actions><ObjectPath Id="1" ObjectPathId="0" /><ObjectIdentityQuery Id="2" ObjectPathId="0" /><ObjectPath Id="4" ObjectPathId="3" /><ObjectIdentityQuery Id="5" ObjectPathId="3" /><ObjectPath Id="7" ObjectPathId="6" /><ObjectIdentityQuery Id="8" ObjectPathId="6" /><ObjectPath Id="10" ObjectPathId="9" /><Query Id="11" ObjectPathId="6"><Query SelectAllProperties="true"><Properties /></Query></Query><Query Id="12" ObjectPathId="9"><Query SelectAllProperties="false"><Properties /></Query><ChildItemQuery SelectAllProperties="false"><Properties><Property Name="IsRoot" SelectAll="true" /><Property Name="Labels" SelectAll="true" /><Property Name="TermsCount" SelectAll="true" /><Property Name="CustomSortOrder" SelectAll="true" /><Property Name="Id" SelectAll="true" /><Property Name="Name" SelectAll="true" /><Property Name="PathOfTerm" SelectAll="true" /><Property Name="Parent" SelectAll="true" /><Property Name="LocalCustomProperties" SelectAll="true" /><Property Name="IsDeprecated" ScalarProperty="true" /><Property Name="IsAvailableForTagging" ScalarProperty="true" /></Properties></ChildItemQuery></Query></Actions><ObjectPaths><StaticMethod Id="0" Name="GetTaxonomySession" TypeId="{981cbc68-9edc-4f8d-872f-71146fcbb84f}" /><Method Id="3" ParentId="0" Name="GetDefaultKeywordsTermStore" /><Method Id="6" ParentId="3" Name="GetTermSet"><Parameters><Parameter Type="Guid">${termsetId}</Parameter></Parameters></Method><Method Id="9" ParentId="6" Name="GetAllTerms" /></ObjectPaths></Request>`;
const data = `<Request xmlns="http://schemas.microsoft.com/sharepoint/clientquery/2009" SchemaVersion="15.0.0.0" LibraryVersion="16.0.0.0" ApplicationName="Javascript Library"><Actions><ObjectPath Id="1" ObjectPathId="0" /><ObjectIdentityQuery Id="2" ObjectPathId="0" /><ObjectPath Id="4" ObjectPathId="3" /><ObjectIdentityQuery Id="5" ObjectPathId="3" /><ObjectPath Id="7" ObjectPathId="6" /><ObjectIdentityQuery Id="8" ObjectPathId="6" /><ObjectPath Id="10" ObjectPathId="9" /><Query Id="11" ObjectPathId="6"><Query SelectAllProperties="true"><Properties /></Query></Query><Query Id="12" ObjectPathId="9"><Query SelectAllProperties="false"><Properties /></Query><ChildItemQuery SelectAllProperties="false"><Properties><Property Name="IsRoot" SelectAll="true" /><Property Name="Labels" SelectAll="true" /><Property Name="TermsCount" SelectAll="true" /><Property Name="CustomSortOrder" SelectAll="true" /><Property Name="Id" SelectAll="true" /><Property Name="Name" SelectAll="true" /><Property Name="PathOfTerm" SelectAll="true" /><Property Name="Parent" SelectAll="true" /><Property Name="LocalCustomProperties" SelectAll="true" /><Property Name="IsDeprecated" ScalarProperty="true" /><Property Name="IsAvailableForTagging" ScalarProperty="true" /></Properties></ChildItemQuery></Query></Actions><ObjectPaths><StaticMethod Id="0" Name="GetTaxonomySession" TypeId="{981cbc68-9edc-4f8d-872f-71146fcbb84f}" /><Method Id="3" ParentId="0" Name="GetDefaultSiteCollectionTermStore" /><Method Id="6" ParentId="3" Name="GetTermSet"><Parameters><Parameter Type="Guid">${termsetId}</Parameter></Parameters></Method><Method Id="9" ParentId="6" Name="GetAllTerms" /></ObjectPaths></Request>`;
const reqHeaders = new Headers();
reqHeaders.append('accept', 'application/json');
@@ -158,7 +178,11 @@ export default class SPTermStorePickerService {
};
return this.context.spHttpClient.post(this.clientServiceUrl, SPHttpClient.configurations.v1, httpPostOptions).then((serviceResponse: SPHttpClientResponse) => {
this.ensureSuccessfulResponse(serviceResponse, 'Terms');
return serviceResponse.json().then((serviceJSONResponse: any) => {
if (!Array.isArray(serviceJSONResponse)) {
throw new Error('The taxonomy service returned an unexpected response.');
}
const termStoreResultTermSets: ITermSet[] = serviceJSONResponse.filter((r: { [x: string]: string; }) => r['_ObjectType_'] === 'SP.Taxonomy.TermSet');
if (termStoreResultTermSets.length > 0) {
@@ -203,7 +227,12 @@ export default class SPTermStorePickerService {
try {
if (useSessionStorage && window.sessionStorage) {
window.sessionStorage.setItem(termsetId, JSON.stringify(termStoreResultTermSet));
const ttlMinutes: number = this.normalizeCacheMinutes(cacheMinutes);
const cacheEntry: ITermCacheEntry = {
expiresAt: Date.now() + ttlMinutes * 60 * 1000,
value: termStoreResultTermSet
};
window.sessionStorage.setItem(TermCachePrefix + termsetId, JSON.stringify(cacheEntry));
}
} catch (error) {
// Do nothing, sometimes "storage quota exceeded" error if too many items
@@ -225,7 +254,7 @@ export default class SPTermStorePickerService {
public async searchTermsByTermId(searchText: string, termId: string): Promise<IPickerTerm[]> {
const { useSessionStorage } = this.props;
const childTerms = this.getTermsById(termId, useSessionStorage);
const childTerms = this.getCachedPickerTerms(termId, useSessionStorage);
if (childTerms) {
return this.searchTermsBySearchText(childTerms, searchText);
} else {
@@ -257,12 +286,18 @@ export default class SPTermStorePickerService {
const returnTerms: IPickerTerm[] = [];
const childTerms = this.getTermsById(anchorId, useSessionStorage);
const childTerms = this.getCachedPickerTerms(anchorId, useSessionStorage);
if (childTerms) {
return childTerms;
}
const termSet = await this.getAllTerms(termsetNameOrID, hideDeprecatedTags, hideTagsNotAvailableForTagging);
const termSet = await this.getAllTerms(
termsetNameOrID,
hideDeprecatedTags,
hideTagsNotAvailableForTagging,
useSessionStorage,
this.props.cacheMinutes
);
const terms = termSet.Terms;
if (anchorId) {
const anchorTerm = terms.filter(t => t.Id.toLowerCase() === anchorId.toLowerCase()).shift();
@@ -277,7 +312,11 @@ export default class SPTermStorePickerService {
try {
if (useSessionStorage && window.sessionStorage) {
window.sessionStorage.setItem(anchorId, JSON.stringify(returnTerms));
const cacheEntry: IPickerTermCacheEntry = {
expiresAt: Date.now() + this.normalizeCacheMinutes(this.props.cacheMinutes) * 60 * 1000,
value: returnTerms
};
window.sessionStorage.setItem(PickerCachePrefix + anchorId, JSON.stringify(cacheEntry));
}
} catch (error) {
// Do nothing
@@ -332,15 +371,21 @@ export default class SPTermStorePickerService {
return null;
}
private getTermsById(termId, useSessionStorage: boolean = true) {
private getCachedTermSet(termId: string, useSessionStorage: boolean = true): ITermSet {
try {
if (useSessionStorage && window.sessionStorage) {
const terms = window.sessionStorage.getItem(termId);
if (terms) {
return JSON.parse(terms);
} else {
const key: string = TermCachePrefix + termId;
const terms: string = window.sessionStorage.getItem(key);
if (!terms) {
return null;
}
const cacheEntry: ITermCacheEntry = JSON.parse(terms) as ITermCacheEntry;
if (!cacheEntry || !cacheEntry.value || !cacheEntry.expiresAt || cacheEntry.expiresAt <= Date.now()) {
window.sessionStorage.removeItem(key);
return null;
}
return cacheEntry.value;
} else {
return null;
}
@@ -349,6 +394,42 @@ export default class SPTermStorePickerService {
}
}
private getCachedPickerTerms(termId: string, useSessionStorage: boolean = true): IPickerTerm[] {
try {
if (!useSessionStorage || !window.sessionStorage) {
return null;
}
const key: string = PickerCachePrefix + termId;
const serialized: string = window.sessionStorage.getItem(key);
if (!serialized) {
return null;
}
const cacheEntry: IPickerTermCacheEntry = JSON.parse(serialized) as IPickerTermCacheEntry;
if (!cacheEntry || !cacheEntry.value || !cacheEntry.expiresAt || cacheEntry.expiresAt <= Date.now()) {
window.sessionStorage.removeItem(key);
return null;
}
return cacheEntry.value;
} catch (error) {
return null;
}
}
private normalizeCacheMinutes(value: number): number {
if (typeof value !== 'number' || !isFinite(value)) {
return 15;
}
return Math.min(Math.max(Math.floor(value), 1), 1440);
}
private ensureSuccessfulResponse(response: SPHttpClientResponse, operation: string): void {
if (!response.ok) {
throw new Error(operation + ' request failed (' + response.status + ' ' + response.statusText + ').');
}
}
private searchTermsBySearchText(terms, searchText) {
if (terms) {
return terms.filter((t) => { return t.name.toLowerCase().indexOf(searchText.toLowerCase()) > -1; });

View File

@@ -12,29 +12,11 @@ const LOG_SOURCE: string = 'TaxonomyNavigationService';
export class TaxonomyNavigationService implements ITaxonomyNavigationService {
private _taxonomyPickerService: SPTermStorePickerService;
private _noTerm: ITerm = {
_ObjectType_: '',
_ObjectIdentity_: '',
CustomSortOrderIndex: 0,
Description: '',
Id: '',
IsAvailableForTagging: false,
IsDeprecated: false,
IsRoot: true,
LocalCustomProperties: {
_Sys_Nav_HoverText: 'Es wurden keine Terms gefunden. Bitte ueberpruefen Sie Ihre Einstellungen.',
_Sys_Nav_ExcludedProviders: undefined,
_Sys_Nav_SimpleLinkUrl: undefined
},
Name: 'Es wurden keine Terms gefunden. Bitte ueberpruefen Sie Ihre Einstellungen.',
PathOfTerm: '',
TermSet: undefined
};
constructor(
private context: ApplicationCustomizerContext,
private termSetName: string,
private debug: boolean = false
private termSetNameOrId: string,
private debug: boolean = false,
private cacheMinutes: number = 15
) {
sp.setup({
spfxContext: context
@@ -42,10 +24,11 @@ export class TaxonomyNavigationService implements ITaxonomyNavigationService {
this._taxonomyPickerService = new SPTermStorePickerService(
{
anchorId: '',
termsetNameOrID: termSetName,
termsetNameOrID: termSetNameOrId,
useSessionStorage: true,
hideDeprecatedTags: true,
hideTagsNotAvailableForTagging: false
hideTagsNotAvailableForTagging: false,
cacheMinutes: cacheMinutes
},
this.context,
this.debug
@@ -54,13 +37,19 @@ export class TaxonomyNavigationService implements ITaxonomyNavigationService {
public async getMenuItems(): Promise<IMenuItem[]> {
const siteCollectionUrl: string = this.context.pageContext.site.absoluteUrl;
const termset: ITermSet = await this._taxonomyPickerService.getAllTerms(this.termSetName);
const termset: ITermSet = await this._taxonomyPickerService.getAllTerms(
this.termSetNameOrId,
true,
false,
true,
this.cacheMinutes
);
const itemsDict: ItemDictionary<IMenuItem> = new ItemDictionary<IMenuItem>();
const menuItems: IMenuItem[] = [];
if (!termset || !termset.Terms) {
if (!termset || !termset.Terms || termset.Terms.length === 0) {
debugWarn(this.debug, LOG_SOURCE, 'No terms found in the term set.');
return [new MenuItem(this._noTerm, 0, siteCollectionUrl)];
throw new Error('The configured navigation term set was not found or contains no terms.');
}
termset.Terms.forEach((term: ITerm) => {
@@ -80,4 +69,4 @@ export class TaxonomyNavigationService implements ITaxonomyNavigationService {
return menuItems;
}
}
}