Navigation: Correctly set active nested plugin pages (#76526)

* correctly set active nested plugin pages

* add recursion depth limit
This commit is contained in:
Ashley Harrison 2023-10-13 16:01:22 +01:00 committed by GitHub
parent 8bf0143908
commit ed4c9bb487
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 27 additions and 4 deletions

View File

@ -18,6 +18,16 @@ describe('buildPluginSectionNav', () => {
text: 'page2',
url: '/a/plugin1/page2',
},
{
text: 'page3',
url: '/a/plugin1/page3',
children: [
{
text: 'page4',
url: '/a/plugin1/page3/page4',
},
],
},
],
};
@ -77,4 +87,10 @@ describe('buildPluginSectionNav', () => {
expect(result?.main.text).toBe('Admin');
expect(result?.node.text).toBe('Standalone page');
});
it('Should set nested active page', () => {
const result = buildPluginSectionNav(appsSection, null, '/a/plugin1/page3/page4');
expect(result?.main.children![0].children![2].children![0].active).toBe(true);
expect(result?.node.text).toBe('page4');
});
});

View File

@ -35,6 +35,7 @@ export function buildPluginSectionNav(
currentUrl: string
): NavModel | undefined {
// shallow clone as we set active flag
const MAX_RECURSION_DEPTH = 10;
let copiedPluginNavSection = { ...pluginNavSection };
let activePage: NavModelItem | undefined;
@ -58,12 +59,15 @@ export function buildPluginSectionNav(
return activePage;
}
// Find and set active page
copiedPluginNavSection.children = (copiedPluginNavSection?.children ?? []).map((child) => {
function findAndSetActivePage(child: NavModelItem, depth = 0): NavModelItem {
if (depth > MAX_RECURSION_DEPTH) {
return child;
}
if (child.children) {
// Doing this here to make sure that first we check if any of the children is active
// (In case yes, then the check for the parent will not mark it as active)
const children = child.children.map((pluginPage) => setPageToActive(pluginPage, currentUrl));
const children = child.children.map((pluginPage) => findAndSetActivePage(pluginPage, depth + 1));
return {
...setPageToActive(child, currentUrl),
@ -72,7 +76,10 @@ export function buildPluginSectionNav(
}
return setPageToActive(child, currentUrl);
});
}
// Find and set active page
copiedPluginNavSection.children = (copiedPluginNavSection?.children ?? []).map(findAndSetActivePage);
return { main: copiedPluginNavSection, node: activePage ?? copiedPluginNavSection };
}