Initial commit

This commit is contained in:
Torsten Brendgen
2026-04-13 10:26:01 +02:00
commit bc1258ae76
116 changed files with 30409 additions and 0 deletions

10
src/services/IMenuItem.ts Normal file
View File

@@ -0,0 +1,10 @@
export interface IMenuItem {
id: string; // Guid;
label: string;
icon?: string;
hoverText: string;
url?: string;
pathDepth: number;
items?: IMenuItem[];
hasChildren: () => boolean;
}

View File

@@ -0,0 +1,9 @@
export interface IPickerTerm {
name: string;
key: string;
path: string;
termSet: string;
termSetName?: string;
}
export interface IPickerTerms extends Array<IPickerTerm> { }

View File

@@ -0,0 +1,94 @@
// tslint:disable:no-any
/**
* Interfaces for Term store, groups and term sets
* This code is a copy from the library @pnp/sp-dev-fx-controls-react
*/
export interface ITermStore {
_ObjectType_: string; // SP.Taxonomy.TermStore
_ObjectIdentity_: string;
Id: string;
Name: string;
Groups: IGroups;
}
export interface IGroups {
_ObjectType_: string; // SP.Taxonomy.TermGroupCollection
_Child_Items_: IGroup[];
}
export interface IGroup {
_ObjectType_: string; // SP.Taxonomy.TermGroup
_ObjectIdentity_: string;
TermSets: ITermSets;
Id: string;
Name: string;
IsSystemGroup: boolean;
}
export interface ITermSets {
_ObjectType_: string; // SP.Taxonomy.TermSetCollection
_Child_Items_: ITermSet[];
}
export interface ITermSet {
_ObjectType_: string; // SP.Taxonomy.TermSet
_ObjectIdentity_: string;
Id: string;
CustomSortOrder?: string;
Name: string;
Description: string;
Names: ITermSetNames;
Terms?: ITerm[];
}
export interface ITermSetMinimal {
_ObjectType_?: string; // SP.Taxonomy.TermSet
_ObjectIdentity_?: string;
Id: string;
Name: string;
}
export interface ITermSetNames {
[locale: string]: string;
}
/**
* Interfaces for the terms
*/
export interface ITerms {
_ObjectType_: string; // SP.Taxonomy.TermCollection
_Child_Items_: ITerm[];
}
/**
* Term
*/
export interface ITerm {
_ObjectType_: string; // SP.Taxonomy.Term
_ObjectIdentity_: string;
Id: string;
Name: string;
Description: string;
IsDeprecated: boolean;
IsAvailableForTagging: boolean;
IsRoot: boolean;
PathOfTerm: string;
TermSet: ITermSetMinimal;
CustomSortOrderIndex?: number;
PathDepth?: number;
ParentId?: string;
TermsCount?: number;
LocalCustomProperties?: {
[property: string]: any
};
}
export interface ISuggestTerm {
Id: string;
DefaultLabel: string;
Description: string;
IsKeyword: boolean;
IsSynonym: boolean;
Paths: Array<string>;
Synonyms: string;
}

View File

@@ -0,0 +1,7 @@
export interface ISPTermStorePickerServiceProps {
termsetNameOrID: string;
useSessionStorage: boolean;
hideDeprecatedTags: boolean;
hideTagsNotAvailableForTagging: boolean;
anchorId: string;
}

View File

@@ -0,0 +1,5 @@
import { IMenuItem } from './IMenuItem';
export interface ITaxonomyNavigationService {
getMenuItems(): Promise<IMenuItem[]>;
}

View File

@@ -0,0 +1,9 @@
export class ItemDictionary<T> {
public Get(key: string): T {
return this[key];
}
public Add(key: string, value: T): void {
this[key] = value;
}
}

View File

@@ -0,0 +1,26 @@
export function debugLog(enabled: boolean, source: string, message: string, ...args: any[]): void {
if (!enabled) {
return;
}
const output: any[] = ['[' + source + '] ' + message].concat(args || []);
console.log.apply(console, output);
}
export function debugWarn(enabled: boolean, source: string, message: string, ...args: any[]): void {
if (!enabled) {
return;
}
const output: any[] = ['[' + source + '] ' + message].concat(args || []);
console.warn.apply(console, output);
}
export function debugError(enabled: boolean, source: string, message: string, ...args: any[]): void {
if (!enabled) {
return;
}
const output: any[] = ['[' + source + '] ' + message].concat(args || []);
console.error.apply(console, output);
}

37
src/services/MenuItem.ts Normal file
View File

@@ -0,0 +1,37 @@
// tslint:disable:no-any no-string-literal max-line-length
import { IMenuItem } from './IMenuItem';
import { ITerm } from './ISPTermStorePickerService';
export class MenuItem implements IMenuItem {
public id: string;
public label: string;
public hoverText: string;
public pathDepth: number;
public url?: string;
public items?: IMenuItem[];
constructor(term: ITerm, public level: number, siteCollectionUrl?: string) {
this.id = term.Id;
this.label = term.Name;
this.hoverText = term.LocalCustomProperties['_Sys_Nav_HoverText'];
this.pathDepth = term.PathDepth;
const rawUrl: string = term.LocalCustomProperties['_Sys_Nav_SimpleLinkUrl'] || term.LocalCustomProperties['_Sys_Nav_TargetUrl'];
if (rawUrl) {
this.url = siteCollectionUrl && rawUrl.indexOf('~sitecollection') === 0
? siteCollectionUrl + rawUrl.substring('~sitecollection'.length)
: rawUrl;
}
this.items = [];
}
public hasChildren(): boolean {
return this.items && this.items.length > 0;
}
public command(): void {
if (this.url) {
(window as any).location.href = this.url;
}
}
}

View File

@@ -0,0 +1,106 @@
import { IMenuItem } from './IMenuItem';
import { ITaxonomyNavigationService } from './ITaxonomyNavigationService';
import * as uuid from 'uuid';
export default class MockTaxonomyNavigationService implements ITaxonomyNavigationService {
public getMenuItems(): Promise<IMenuItem[]> {
return new Promise<IMenuItem[]>((resolve) => {
resolve([
{
id: uuid.v4(),
label: 'Menu Item 1',
url: 'https://www.bing.com',
hoverText: 'Hover me!',
pathDepth: 1,
hasChildren: () => true,
items: [
{
id: uuid.v4(),
label: 'Submenu Item 1',
hoverText: 'Huch!',
url: 'https://www.bing.com',
pathDepth: 2,
hasChildren: () => false
},
{
id: uuid.v4(),
label: 'Submenu Item 2',
hoverText: 'Huch!',
url: 'https://www.bing.com',
pathDepth: 2,
hasChildren: () => false
}
]
},
{
id: uuid.v4(),
label: 'Menu Item 2',
hoverText: 'Huch!',
url: 'https://www.bing.com',
pathDepth: 1,
hasChildren: () => false
},
{
id: uuid.v4(),
label: 'Menu Item 3',
hoverText: 'Huch!',
url: 'https://www.bing.com',
pathDepth: 1,
hasChildren: () => true,
items: [
{
id: uuid.v4(),
label: 'Submenu Item 1',
hoverText: 'Huch!',
url: 'https://www.bing.com',
pathDepth: 2,
hasChildren: () => false
},
{
id: uuid.v4(),
label: 'Submenu Item 2',
hoverText: 'Huch!',
url: 'https://www.bing.com',
pathDepth: 2,
hasChildren: () => true,
items: [
{
id: uuid.v4(),
label: 'Submenu Item 1',
hoverText: 'Huch!',
url: 'https://www.bing.com',
pathDepth: 3,
hasChildren: () => false
},
{
id: uuid.v4(),
label: 'Submenu Item 2',
hoverText: 'Huch!',
url: 'https://www.bing.com',
pathDepth: 3,
hasChildren: () => false
}
]
},
{
id: uuid.v4(),
label: 'Submenu Item 3',
hoverText: 'Huch!',
url: 'https://www.bing.com',
pathDepth: 2,
hasChildren: () => false
},
{
id: uuid.v4(),
label: 'Submenu Item 4',
hoverText: 'Huch!',
url: 'https://www.bing.com',
pathDepth: 2,
hasChildren: () => false
}
]
}
]);
});
}
}

View File

@@ -0,0 +1,532 @@
/* tslint:disable:no-null-keyword max-line-length typedef no-any no-string-literal variable-name */
/**
* This code is a copy from the library @pnp/sp-dev-fx-controls-react
*/
import { SPHttpClient, SPHttpClientResponse, ISPHttpClientOptions } from '@microsoft/sp-http';
import { ITermStore, ITerms, ITerm, IGroup, ITermSet, ISuggestTerm } from './ISPTermStorePickerService';
import { findIndex } from '@microsoft/sp-lodash-subset';
import { ISPTermStorePickerServiceProps } from './ISPTermStorePickerServiceProps';
import { IPickerTerm } from './IPickerTerm';
import { ApplicationCustomizerContext } from '@microsoft/sp-application-base';
import { debugError } from './MegaMenuDebug';
const EmptyGuid: string = '00000000-0000-0000-0000-000000000000';
/**
* Service implementation to manage term stores in SharePoint
*/
export default class SPTermStorePickerService {
private clientServiceUrl: string;
private suggestionServiceUrl: string;
/**
* Service constructor
*/
constructor(private props: ISPTermStorePickerServiceProps, private context: ApplicationCustomizerContext, private debug: boolean = false) {
this.clientServiceUrl = this.context.pageContext.web.absoluteUrl + '/_vti_bin/client.svc/ProcessQuery';
this.suggestionServiceUrl = this.context.pageContext.web.absoluteUrl + '/_vti_bin/TaxonomyInternalService.json/GetSuggestions';
}
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 reqHeaders = new Headers();
reqHeaders.append('accept', 'application/json');
reqHeaders.append('content-type', 'application/xml');
const httpPostOptions: ISPHttpClientOptions = {
headers: reqHeaders,
body: data
};
const callResult = await this.context.spHttpClient.post(this.clientServiceUrl, SPHttpClient.configurations.v1, httpPostOptions);
const jsonResult = await callResult.json();
const node = jsonResult.find(x => x._ObjectType_ === 'SP.Taxonomy.Term');
if (node && node.Labels && node.Labels._Child_Items_) {
result = node.Labels._Child_Items_.map(termLabel => termLabel.Value);
}
} catch (error) {
result = null;
debugError(this.debug, 'SPTermStorePickerService', 'Error reading term labels.', error);
}
return result;
}
/**
* Gets the collection of term stores in the current SharePoint env
*/
public getTermStores(): Promise<ITermStore[]> {
// Retrieve the term store name, groups, and term sets
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="2" ObjectPathId="1" /><ObjectIdentityQuery Id="3" ObjectPathId="1" /><ObjectPath Id="5" ObjectPathId="4" /><ObjectIdentityQuery Id="6" ObjectPathId="4" /><Query Id="7" ObjectPathId="4"><Query SelectAllProperties="false"><Properties><Property Name="Id" ScalarProperty="true" /><Property Name="Name" ScalarProperty="true" /><Property Name="Groups"><Query SelectAllProperties="false"><Properties /></Query><ChildItemQuery SelectAllProperties="false"><Properties><Property Name="Name" ScalarProperty="true" /><Property Name="Id" ScalarProperty="true" /><Property Name="IsSystemGroup" ScalarProperty="true" /><Property Name="TermSets"><Query SelectAllProperties="false"><Properties /></Query><ChildItemQuery SelectAllProperties="false"><Properties><Property Name="Name" ScalarProperty="true" /><Property Name="Id" ScalarProperty="true" /><Property Name="Description" ScalarProperty="true" /><Property Name="Names" ScalarProperty="true" /></Properties></ChildItemQuery></Property></Properties></ChildItemQuery></Property></Properties></Query></Query></Actions><ObjectPaths><StaticMethod Id="1" Name="GetTaxonomySession" TypeId="{981cbc68-9edc-4f8d-872f-71146fcbb84f}" /><Method Id="4" ParentId="1" Name="GetDefaultSiteCollectionTermStore" /></ObjectPaths></Request>';
const reqHeaders = new Headers();
reqHeaders.append('accept', 'application/json');
reqHeaders.append('content-type', 'application/xml');
const httpPostOptions: ISPHttpClientOptions = {
headers: reqHeaders,
body: data
};
return this.context.spHttpClient.post(this.clientServiceUrl, SPHttpClient.configurations.v1, httpPostOptions).then((serviceResponse: SPHttpClientResponse) => {
return serviceResponse.json().then((serviceJSONResponse: any) => {
// Construct results
const termStoreResult: ITermStore[] = serviceJSONResponse.filter((r: { [x: string]: string; }) => r['_ObjectType_'] === 'SP.Taxonomy.TermStore');
// Check if term store was retrieved
if (termStoreResult.length > 0) {
// Check if the termstore needs to be filtered or limited
if (this.props.termsetNameOrID) {
return termStoreResult.map(termstore => {
let termGroups = termstore.Groups._Child_Items_;
// Check if the groups have to be limited to a specific term set
if (this.props.termsetNameOrID) {
const termsetNameOrId = this.props.termsetNameOrID;
termGroups = termGroups.map((group: IGroup) => {
group.TermSets._Child_Items_ = group.TermSets._Child_Items_.filter((termSet: ITermSet) => termSet.Name === termsetNameOrId || this.cleanGuid(termSet.Id).toLowerCase() === this.cleanGuid(termsetNameOrId).toLowerCase());
return group;
});
}
// Filter out all systen groups
termGroups = termGroups.filter(group => !group.IsSystemGroup);
// Filter out empty groups
termGroups = termGroups.filter((group: IGroup) => group.TermSets._Child_Items_.length > 0);
// Map the new groups
termstore.Groups._Child_Items_ = termGroups;
return termstore;
});
}
// Return the term store results
return termStoreResult;
}
return [];
});
});
}
/**
* Gets the current term set
*/
public async getTermSet(): Promise<ITermSet> {
const termStore = await this.getTermStores();
return this.getTermSetId(termStore, this.props.termsetNameOrID);
}
/**
* Retrieve all terms for the given term set
* @param termset
*/
public async getAllTerms(termset: string, hideDeprecatedTags?: boolean, hideTagsNotAvailableForTagging?: boolean, useSessionStorage: boolean = true): Promise<ITermSet> {
let termsetId: string = termset;
// Check if the provided term set property is a GUID or string
if (!this.isGuid(termset)) {
// Fetch the term store information
const termStore = await this.getTermStores();
// Get the ID of the provided term set name
const crntTermSet = this.getTermSetId(termStore, termset);
if (crntTermSet) {
termsetId = this.cleanGuid(crntTermSet.Id);
} else {
return null;
}
}
const childTerms = this.getTermsById(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 reqHeaders = new Headers();
reqHeaders.append('accept', 'application/json');
reqHeaders.append('content-type', 'application/xml');
const httpPostOptions: ISPHttpClientOptions = {
headers: reqHeaders,
body: data
};
return this.context.spHttpClient.post(this.clientServiceUrl, SPHttpClient.configurations.v1, httpPostOptions).then((serviceResponse: SPHttpClientResponse) => {
return serviceResponse.json().then((serviceJSONResponse: any) => {
const termStoreResultTermSets: ITermSet[] = serviceJSONResponse.filter((r: { [x: string]: string; }) => r['_ObjectType_'] === 'SP.Taxonomy.TermSet');
if (termStoreResultTermSets.length > 0) {
const termStoreResultTermSet = termStoreResultTermSets[0];
termStoreResultTermSet.Terms = [];
// Retrieve the term collection results
const termStoreResultTerms: ITerms[] = serviceJSONResponse.filter((r: { [x: string]: string; }) => r['_ObjectType_'] === 'SP.Taxonomy.TermCollection');
if (termStoreResultTerms.length > 0) {
// Retrieve all terms
let terms = termStoreResultTerms[0]._Child_Items_;
if (hideDeprecatedTags === true) {
terms = terms.filter(d => d.IsDeprecated === false);
}
if (hideTagsNotAvailableForTagging === true) {
terms = terms.filter(d => d.IsAvailableForTagging === true);
}
// Clean the term ID and specify the path depth
terms = terms.map(term => {
if (term.IsRoot) {
term.CustomSortOrderIndex = (termStoreResultTermSet.CustomSortOrder) ? termStoreResultTermSet.CustomSortOrder.split(':').indexOf(this.cleanGuid(term.Id)) : -1;
} else {
term.CustomSortOrderIndex = (term['Parent'].CustomSortOrder) ? term['Parent'].CustomSortOrder.split(':').indexOf(this.cleanGuid(term.Id)) : -1;
}
term.Id = this.cleanGuid(term.Id);
term['PathDepth'] = term.PathOfTerm.split(';').length;
term.TermSet = { Id: this.cleanGuid(termStoreResultTermSet.Id), Name: termStoreResultTermSet.Name };
if (term['Parent']) {
term.ParentId = this.cleanGuid(term['Parent'].Id);
}
return term;
});
// Check if the term set was not empty
if (terms.length > 0) {
// Sort the terms by PathOfTerm and their depth
terms = this.sortTerms(terms);
termStoreResultTermSet.Terms = terms;
}
}
try {
if (useSessionStorage && window.sessionStorage) {
window.sessionStorage.setItem(termsetId, JSON.stringify(termStoreResultTermSet));
}
} catch (error) {
// Do nothing, sometimes "storage quota exceeded" error if too many items
}
return termStoreResultTermSet;
}
return null;
});
});
}
/**
* Retrieve all terms that starts with the searchText
* @param searchText
*/
public searchTermsByName(searchText: string): Promise<IPickerTerm[]> {
return this.searchTermsByTermSet(searchText);
}
public async searchTermsByTermId(searchText: string, termId: string): Promise<IPickerTerm[]> {
const { useSessionStorage } = this.props;
const childTerms = this.getTermsById(termId, useSessionStorage);
if (childTerms) {
return this.searchTermsBySearchText(childTerms, searchText);
} else {
const {
termsetNameOrID,
hideDeprecatedTags,
hideTagsNotAvailableForTagging
} = this.props;
const terms = await this.getAllTermsByAnchorId(
termsetNameOrID,
termId,
hideDeprecatedTags,
hideTagsNotAvailableForTagging,
useSessionStorage);
if (terms) {
return this.searchTermsBySearchText(terms, searchText);
}
}
return null;
}
/**
* Retrieve all terms for the given term set and anchorId
*/
public async getAllTermsByAnchorId(termsetNameOrID: string, anchorId: string, hideDeprecatedTags?: boolean, hideTagsNotAvailableForTagging?: boolean, useSessionStorage: boolean = true): Promise<IPickerTerm[]> {
const returnTerms: IPickerTerm[] = [];
const childTerms = this.getTermsById(anchorId, useSessionStorage);
if (childTerms) {
return childTerms;
}
const termSet = await this.getAllTerms(termsetNameOrID, hideDeprecatedTags, hideTagsNotAvailableForTagging);
const terms = termSet.Terms;
if (anchorId) {
const anchorTerm = terms.filter(t => t.Id.toLowerCase() === anchorId.toLowerCase()).shift();
if (anchorTerm) {
// Append ';' separator, as a suffix to anchor term path.
const anchorTermPath = `${anchorTerm.PathOfTerm};`;
const anchorTerms: ITerm[] = terms.filter(t => t.PathOfTerm.substring(0, anchorTermPath.length) === anchorTermPath && t.Id !== anchorTerm.Id);
anchorTerms.forEach(term => {
returnTerms.push(this.convertTermToPickerTerm(term));
});
try {
if (useSessionStorage && window.sessionStorage) {
window.sessionStorage.setItem(anchorId, JSON.stringify(returnTerms));
}
} catch (error) {
// Do nothing
}
}
} else {
terms.forEach(term => {
returnTerms.push(this.convertTermToPickerTerm(term));
});
}
return returnTerms;
}
/**
* Clean the Guid from the Web Service response
* @param guid
*/
public cleanGuid(guid: string): string {
if (guid !== undefined) {
return guid.replace('/Guid(', '').replace('/', '').replace(')', '');
} else {
return '';
}
}
/**
* Get the term set ID by its name
* @param termstore
* @param termset
*/
private getTermSetId(termstore: ITermStore[], termsetName: string): ITermSet {
if (termstore && termstore.length > 0 && termsetName) {
// Get the first term store
const ts = termstore[0];
// Check if the term store contains groups
if (ts.Groups && ts.Groups._Child_Items_) {
for (const group of ts.Groups._Child_Items_) {
// Check if the group contains term sets
if (group.TermSets && group.TermSets._Child_Items_) {
for (const termSet of group.TermSets._Child_Items_) {
// Check if the term set is found
if (termSet.Name === termsetName) {
return termSet;
}
}
}
}
}
}
return null;
}
private getTermsById(termId, useSessionStorage: boolean = true) {
try {
if (useSessionStorage && window.sessionStorage) {
const terms = window.sessionStorage.getItem(termId);
if (terms) {
return JSON.parse(terms);
} else {
return null;
}
} else {
return null;
}
} catch (error) {
return null;
}
}
private searchTermsBySearchText(terms, searchText) {
if (terms) {
return terms.filter((t) => { return t.name.toLowerCase().indexOf(searchText.toLowerCase()) > -1; });
} else {
return [];
}
}
/**
* Searches terms for the given term set
* @param searchText
* @param termsetId
*/
private searchTermsByTermSet(searchText: string): Promise<IPickerTerm[]> {
return new Promise<IPickerTerm[]>(resolve => {
this.getTermStores().then(termStore => {
let termSetId = this.props.termsetNameOrID;
if (!this.isGuid(termSetId)) {
// Get the ID of the provided term set name
const crntTermSet = this.getTermSetId(termStore, termSetId);
if (crntTermSet) {
termSetId = this.cleanGuid(crntTermSet.Id);
} else {
resolve(null);
return;
}
}
if (termStore === undefined || termStore.length === 0) {
resolve(null);
return;
}
const loc: number = this.context.pageContext.cultureInfo.currentUICultureName === 'de-de' ? 1031 : 1033;
const data: any = {
start: searchText,
lcid: loc !== 0 ? loc : this.context.pageContext.web.language,
sspList: this.cleanGuid(termStore[0].Id),
termSetList: termSetId,
anchorId: this.props.anchorId ? this.props.anchorId : EmptyGuid,
isSpanTermStores: false,
isSpanTermSets: false,
isIncludeUnavailable: this.props.hideTagsNotAvailableForTagging === true,
isIncludeDeprecated: this.props.hideDeprecatedTags === true,
isAddTerms: false,
isIncludePathData: false,
excludeKeyword: false,
excludedTermset: EmptyGuid
};
const reqHeaders: Headers = new Headers();
reqHeaders.append('accept', 'application/json');
reqHeaders.append('content-type', 'application/json');
const httpPostOptions: ISPHttpClientOptions = {
headers: reqHeaders,
body: JSON.stringify(data)
};
return this.context.spHttpClient.post(this.suggestionServiceUrl, SPHttpClient.configurations.v1, httpPostOptions).then((serviceResponse: SPHttpClientResponse) => {
return serviceResponse.json().then((serviceJSONResponse: any) => {
const groups = serviceJSONResponse.d.Groups;
if (groups && groups.length > 0) {
// Retrieve the term collection results
const terms: ISuggestTerm[] = groups[0].Suggestions;
if (terms.length > 0) {
// Retrieve all terms
const returnTerms: IPickerTerm[] = terms.map((term: ISuggestTerm) => this.convertSuggestTermToPickerTerm(term));
resolve(returnTerms);
return;
}
}
resolve([]);
});
});
});
});
}
private isGuid(strGuid: 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(strGuid);
}
/**
* Sorting terms based on their path and depth
*
* @param terms
*/
private sortTerms(terms: ITerm[]) {
// Start sorting by depth
let newTermsOrder: ITerm[] = [];
let itemsToSort: boolean = true;
let pathLevel: number = 1;
while (itemsToSort) {
// Get terms for the current level
let crntTerms = terms.filter(term => term.PathDepth === pathLevel);
if (crntTerms && crntTerms.length > 0) {
crntTerms = crntTerms.sort(this.sortTermByPath);
if (pathLevel !== 1) {
crntTerms = crntTerms.reverse();
for (const crntTerm of crntTerms) {
const pathElms: string[] = crntTerm.PathOfTerm.split(';');
// Last item is not needed for parent path
pathElms.pop();
// Find the parent item and add the new item
const idx: number = findIndex(newTermsOrder, term => term.PathOfTerm === pathElms.join(';'));
if (idx !== -1) {
newTermsOrder.splice(idx + 1, 0, crntTerm);
} else {
// Push the item at the end if the parent couldn't be found
newTermsOrder.push(crntTerm);
}
}
} else {
newTermsOrder = crntTerms;
}
++pathLevel;
} else {
itemsToSort = false;
}
}
return newTermsOrder;
}
/**
* Sort the terms by their path
*
* @param a term 2
* @param b term 2
*/
private sortTermByPath(a: ITerm, b: ITerm) {
if (a.CustomSortOrderIndex === -1) {
if (a.PathOfTerm.toLowerCase() < b.PathOfTerm.toLowerCase()) {
return -1;
}
if (a.PathOfTerm.toLowerCase() > b.PathOfTerm.toLowerCase()) {
return 1;
}
return 0;
} else {
if (a.CustomSortOrderIndex < b.CustomSortOrderIndex) {
return -1;
}
if (a.CustomSortOrderIndex > b.CustomSortOrderIndex) {
return 1;
}
return 0;
}
}
private convertTermToPickerTerm(term: ITerm): IPickerTerm {
return {
key: this.cleanGuid(term.Id),
name: term.Name,
path: term.PathOfTerm,
termSet: this.cleanGuid(term.TermSet.Id),
termSetName: term.TermSet.Name
};
}
private convertSuggestTermToPickerTerm(term: ISuggestTerm): IPickerTerm {
let path: string = '';
let termSetName: string = '';
if (term.Paths && term.Paths.length > 0) {
const fullPath: string = term.Paths[0].replace(/^\[/, '').replace(/\]$/, '');
const fullPathParts: string[] = fullPath.split(':');
path = fullPathParts.join(';') + ';' + term.DefaultLabel;
termSetName = fullPathParts[0];
}
return {
key: this.cleanGuid(term.Id),
name: term.DefaultLabel,
path: path,
termSet: EmptyGuid, // TermSet Guid is not given with suggestion
termSetName: termSetName
};
}
}

View File

@@ -0,0 +1,83 @@
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;
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
) {
sp.setup({
spfxContext: context
});
this._taxonomyPickerService = new SPTermStorePickerService(
{
anchorId: '',
termsetNameOrID: termSetName,
useSessionStorage: true,
hideDeprecatedTags: true,
hideTagsNotAvailableForTagging: false
},
this.context,
this.debug
);
}
public async getMenuItems(): Promise<IMenuItem[]> {
const siteCollectionUrl: string = this.context.pageContext.site.absoluteUrl;
const termset: ITermSet = await this._taxonomyPickerService.getAllTerms(this.termSetName);
const itemsDict: ItemDictionary<IMenuItem> = new ItemDictionary<IMenuItem>();
const menuItems: IMenuItem[] = [];
if (!termset || !termset.Terms) {
debugWarn(this.debug, LOG_SOURCE, 'No terms found in the term set.');
return [new MenuItem(this._noTerm, 0, siteCollectionUrl)];
}
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;
}
}

View File

@@ -0,0 +1,21 @@
export interface IUserCustomActionProps {
Id?: string;
Title: string;
Name?: string;
Description?: string;
Location: string;
ScriptSrc?: string;
ScriptBlock?: string;
Url?: string;
Sequence?: number;
Group?: string;
ImageUrl?: string;
CommandUIExtension?: string;
RegistrationType?: number;
RegistrationId?: string;
Rights?: {};
Scope?: number;
ClientSideComponentId?: string;
ClientSideComponentProperties?: string;
}

View File

@@ -0,0 +1,12 @@
/* tslint:disable:max-line-length */
import { UserCustomActionScope } from './UserCustomActionScope';
import { IUserCustomActionProps } from './IUserCustomActionProps';
import { UserCustomActionAddResult, UserCustomActionUpdateResult } from '@pnp/sp';
export interface IUserCustomActionService {
getUserCustomActions(scope: UserCustomActionScope, listId?: string): Promise<IUserCustomActionProps[]>;
getUserCustomActionById(scope: UserCustomActionScope, id: string, listId?: string): Promise<IUserCustomActionProps>;
addUserCustomAction(scope: UserCustomActionScope, customAction: IUserCustomActionProps, listId?: string): Promise<UserCustomActionAddResult>;
updateUserCustomAction(scope: UserCustomActionScope, id: string, props: {}, listId?: string): Promise<UserCustomActionUpdateResult>;
deleteUserCustomAction(scope: UserCustomActionScope, customAction: IUserCustomActionProps, listId?: string): Promise<void>;
}

View File

@@ -0,0 +1,5 @@
export enum UserCustomActionScope {
Web = 'web',
Site = 'site',
List = 'list'
}

View File

@@ -0,0 +1,134 @@
// tslint:disable:max-line-length
// tslint:disable:export-name
import { UserCustomActionAddResult, UserCustomActions, UserCustomActionUpdateResult } from '@pnp/sp/src/usercustomactions';
import { IUserCustomActionService } from './IUserCustomActionService';
import { sp } from '@pnp/sp';
import { UserCustomActionScope } from './UserCustomActionScope';
import { IUserCustomActionProps } from './IUserCustomActionProps';
import { ApplicationCustomizerContext } from '@microsoft/sp-application-base';
import { debugError } from '../MegaMenuDebug';
const LOG_SOURCE: string = 'UserCustomActionService';
export class UserCustomActionService implements IUserCustomActionService {
constructor(context: ApplicationCustomizerContext, private debug: boolean = false) {
sp.setup({
spfxContext: context
});
}
public async getUserCustomActions(scope: UserCustomActionScope, listId?: string): Promise<IUserCustomActionProps[]> {
try {
let actions: UserCustomActions | IUserCustomActionProps[];
switch (scope) {
case UserCustomActionScope.Web:
actions = await sp.web.userCustomActions.get();
break;
case UserCustomActionScope.Site:
actions = await sp.site.userCustomActions.get();
break;
case UserCustomActionScope.List:
if (!listId) {
throw new Error('List ID is required for List scope');
}
actions = await sp.web.lists.getById(listId).userCustomActions.get();
break;
default:
throw new Error('Invalid scope');
}
return actions as IUserCustomActionProps[];
} catch (error) {
debugError(this.debug, LOG_SOURCE, 'Error getting user custom actions.', error);
throw error;
}
}
public async getUserCustomActionById(scope: UserCustomActionScope, id: string, listId?: string): Promise<IUserCustomActionProps> {
try {
switch (scope) {
case UserCustomActionScope.Web:
return sp.web.userCustomActions.getById(id) as {} as IUserCustomActionProps;
case UserCustomActionScope.Site:
return sp.site.userCustomActions.getById(id) as {} as IUserCustomActionProps;
case UserCustomActionScope.List:
if (!listId) {
throw new Error('List ID is required for List scope');
}
return sp.web.lists.getById(listId).userCustomActions.getById(id) as {} as IUserCustomActionProps;
default:
throw new Error('Invalid scope');
}
} catch (error) {
debugError(this.debug, LOG_SOURCE, 'Error getting user custom action by ID.', error);
throw error;
}
}
public async addUserCustomAction(scope: UserCustomActionScope, customAction: IUserCustomActionProps, listId?: string): Promise<UserCustomActionAddResult> {
try {
switch (scope) {
case UserCustomActionScope.Web:
return sp.web.userCustomActions.add(customAction);
case UserCustomActionScope.Site:
return sp.site.userCustomActions.add(customAction);
case UserCustomActionScope.List:
if (!listId) {
throw new Error('List ID is required for List scope');
}
return sp.web.lists.getById(listId).userCustomActions.add(customAction);
default:
throw new Error('Invalid scope');
}
} catch (error) {
debugError(this.debug, LOG_SOURCE, 'Error adding user custom action.', error);
throw error;
}
}
public async updateUserCustomAction(scope: UserCustomActionScope, id: string, props: {}, listId?: string): Promise<UserCustomActionUpdateResult> {
try {
let result: UserCustomActionUpdateResult;
switch (scope) {
case UserCustomActionScope.Web:
result = await sp.web.userCustomActions.getById(id).update(props);
break;
case UserCustomActionScope.Site:
result = await sp.site.userCustomActions.getById(id).update(props);
break;
case UserCustomActionScope.List:
if (!listId) {
throw new Error('List ID is required for List scope');
}
result = await sp.web.lists.getById(listId).userCustomActions.getById(id).update(props);
break;
default:
throw new Error('Invalid scope');
}
return result;
} catch (error) {
debugError(this.debug, LOG_SOURCE, 'Error updating user custom action.', error);
throw error;
}
}
public async deleteUserCustomAction(scope: UserCustomActionScope, customAction: IUserCustomActionProps, listId?: string): Promise<void> {
try {
switch (scope) {
case UserCustomActionScope.Web:
return sp.web.userCustomActions.getById(customAction.Id).delete();
case UserCustomActionScope.Site:
return sp.site.userCustomActions.getById(customAction.Id).delete();
case UserCustomActionScope.List:
if (!listId) {
throw new Error('List ID is required for List scope');
}
return sp.web.lists.getById(listId).userCustomActions.getById(customAction.Id).delete();
default:
throw new Error('Invalid scope');
}
} catch (error) {
debugError(this.debug, LOG_SOURCE, 'Error deleting user custom action.', error);
throw error;
}
}
}