70 lines
2.5 KiB
TypeScript
70 lines
2.5 KiB
TypeScript
import type { HmiPage } from './types';
|
|
|
|
export interface NavigationNode {
|
|
page: HmiPage;
|
|
children: NavigationNode[];
|
|
}
|
|
export interface NavigationRoot {
|
|
name: string;
|
|
children: NavigationNode[];
|
|
}
|
|
|
|
/** Independent pure helper. Handles missing parents and protects the UI from cyclic data. */
|
|
export function navigationRoots(pages: HmiPage[]): NavigationRoot[] {
|
|
const rootMap = new Map<string, NavigationRoot>();
|
|
const nodeMap = new Map<string, NavigationNode>();
|
|
for (const page of pages) {
|
|
if (!nodeMap.has(page.id)) nodeMap.set(page.id, {page,children:[]});
|
|
}
|
|
const isValidAncestor = (page: HmiPage):boolean => {
|
|
const visited = new Set<string>([page.id]);
|
|
let current = page.parentPageId;
|
|
while (current) {
|
|
if (visited.has(current)) return false;
|
|
visited.add(current);
|
|
const ancestor = nodeMap.get(current)?.page;
|
|
if (!ancestor || ancestor.menuGroup !== page.menuGroup) return false;
|
|
current = ancestor.parentPageId;
|
|
}
|
|
return true;
|
|
};
|
|
for (const page of pages) {
|
|
const group = page.menuGroup || 'Allgemein';
|
|
if (!rootMap.has(group)) rootMap.set(group, {name:group,children:[]});
|
|
const parent = page.parentPageId ? nodeMap.get(page.parentPageId) : undefined;
|
|
const node = nodeMap.get(page.id)!;
|
|
if (parent && isValidAncestor(page) && parent.page.menuGroup===group) parent.children.push(node);
|
|
else rootMap.get(group)!.children.push(node);
|
|
}
|
|
const order = (nodes: NavigationNode[], level=0) => {
|
|
if (level>32) return;
|
|
nodes.sort((a,b)=>a.page.order-b.page.order || a.page.title.localeCompare(b.page.title,'de'));
|
|
for (const node of nodes) order(node.children,level+1);
|
|
};
|
|
const roots=Array.from(rootMap.values());
|
|
for (const root of roots) order(root.children);
|
|
roots.sort((a,b)=>{
|
|
const aSort=Math.min(...a.children.map(n=>n.page.order),999999);
|
|
const bSort=Math.min(...b.children.map(n=>n.page.order),999999);
|
|
return aSort-bSort || a.name.localeCompare(b.name,'de');
|
|
});
|
|
return roots;
|
|
}
|
|
|
|
export function descendantPageIds(pages:HmiPage[],pageId:string):Set<string> {
|
|
const children = new Map<string,string[]>();
|
|
for(const p of pages) if(p.parentPageId){
|
|
const siblings=children.get(p.parentPageId)||[];
|
|
siblings.push(p.id);children.set(p.parentPageId,siblings);
|
|
}
|
|
const found = new Set<string>();
|
|
const pending=[pageId];
|
|
while(pending.length){
|
|
const id=pending.pop()!;
|
|
for(const next of children.get(id)||[]) {
|
|
if(!found.has(next)){found.add(next);pending.push(next);}
|
|
}
|
|
}
|
|
return found;
|
|
}
|