import { Page } from "../types/api"; export default class PageTree { items: Page[] = []; constructor(pageList: Page[]) { this.items = this.sortPages(this.parsePageTree(pageList)); } parsePageTree(pageList: Page[]): Page[] { pageList.forEach(page => page.path = page.parentId ? '/' + page.name : ''); const getSubPagesById = (id: string) => pageList.filter(page => page.parentId === id); pageList.forEach((page) => { page.children = getSubPagesById(page.id); page.children.forEach((subPage: any) => { subPage.path = page.path + subPage.path; // Mark subpages as child so we can remove them later. subPage.isChild = true; }); page.path = page.path || '/'; }); return pageList.filter(page => !page.isChild); } sortPages(pageTree: Page[]): Page[] { const sortByName = (a: any, b: any) => { if(a.name < b.name) { return -1; } if(a.name > b.name) { return 1; } return 0; }; const pageSorter = (a: any, b: any) => { if(a.children && a.children.length && b.children && b.children.length) { // Both have child pages. return sortByName(a, b); } if(a.children && a.children.length) { return -1; } if(b.children && b.children.length) { return 1; } // Both pages do not have child pages, only use name to sort. return sortByName(a, b); }; pageTree = pageTree.sort(pageSorter); // Apply recursive sorting on sub arrays. pageTree.forEach(page => { if(page.children && page.children.length) { page.children = this.sortPages(page.children); } }); return pageTree; } }