import { ITaxonomyNavigationService } from './ITaxonomyNavigationService'; import { IMenuItem } from './IMenuItem'; import { sp } from '@pnp/sp'; import { MenuItem } from './MenuItem'; import { ApplicationCustomizerContext } from '@microsoft/sp-application-base'; import SPTermStorePickerService from './SPTermStorePickerService'; import { ITerm, ITermSet } from './ISPTermStorePickerService'; import { ItemDictionary } from './ItemDictionary'; import { debugWarn } from './MegaMenuDebug'; const LOG_SOURCE: string = 'TaxonomyNavigationService'; export class TaxonomyNavigationService implements ITaxonomyNavigationService { private _taxonomyPickerService: SPTermStorePickerService; constructor( private context: ApplicationCustomizerContext, private termSetNameOrId: string, private debug: boolean = false, private cacheMinutes: number = 15 ) { sp.setup({ spfxContext: context }); this._taxonomyPickerService = new SPTermStorePickerService( { anchorId: '', termsetNameOrID: termSetNameOrId, useSessionStorage: true, hideDeprecatedTags: true, hideTagsNotAvailableForTagging: false, cacheMinutes: cacheMinutes }, this.context, this.debug ); } public async getMenuItems(): Promise { const siteCollectionUrl: string = this.context.pageContext.site.absoluteUrl; const termset: ITermSet = await this._taxonomyPickerService.getAllTerms( this.termSetNameOrId, true, false, true, this.cacheMinutes ); const itemsDict: ItemDictionary = new ItemDictionary(); const menuItems: IMenuItem[] = []; if (!termset || !termset.Terms || termset.Terms.length === 0) { debugWarn(this.debug, LOG_SOURCE, 'No terms found in the term set.'); throw new Error('The configured navigation term set was not found or contains no terms.'); } termset.Terms.forEach((term: ITerm) => { const menuItem: IMenuItem = new MenuItem(term, 0, siteCollectionUrl); itemsDict.Add(term.Id, menuItem); if (menuItem.pathDepth === 1) { menuItems.push(menuItem); } else { const parentItem: IMenuItem = itemsDict.Get(term.ParentId); if (parentItem) { parentItem.items.push(menuItem); } else { debugWarn(this.debug, LOG_SOURCE, 'Item without parent:', term.PathOfTerm); } } }); return menuItems; } }