From ef3759449d630df81578cc4da2f86535477d4498 Mon Sep 17 00:00:00 2001 From: Bogdan Matei Date: Thu, 21 Nov 2024 11:52:39 +0200 Subject: [PATCH] Scopes: Refactor the way scope paths are created (#96712) --- .../features/scopes/internal/ScopesInput.tsx | 70 ++++++++----------- 1 file changed, 30 insertions(+), 40 deletions(-) diff --git a/public/app/features/scopes/internal/ScopesInput.tsx b/public/app/features/scopes/internal/ScopesInput.tsx index e440d38741f..922dbf19a3b 100644 --- a/public/app/features/scopes/internal/ScopesInput.tsx +++ b/public/app/features/scopes/internal/ScopesInput.tsx @@ -1,5 +1,4 @@ import { css } from '@emotion/css'; -import { groupBy } from 'lodash'; import { useEffect, useMemo, useState } from 'react'; import { GrafanaTheme2 } from '@grafana/data'; @@ -34,55 +33,46 @@ export function ScopesInput({ }, [scopes]); const scopesPaths = useMemo(() => { - const pathsTitles = scopes.map(({ scope, path }) => { + const pathsScopesMap = scopes.reduce>((acc, { scope, path }) => { let currentLevel = nodes; - let titles: string[]; - - if (path.length > 0) { - titles = path.reduce((acc, nodeName) => { - const cl = currentLevel[nodeName]; - - if (!cl) { - return acc; - } - - const { title, nodes } = cl; - - currentLevel = nodes; - - acc.push(title); + const titles = path.reduce((acc, nodeName) => { + const cl = currentLevel?.[nodeName]; + if (!cl) { return acc; - }, []); - - if (titles[0] === '') { - titles.splice(0, 1); } - } else { - titles = [scope.spec.title]; + + const { title, nodes } = cl; + + currentLevel = nodes; + + acc.push(title); + + return acc; + }, []); + + if (titles[0] === '') { + titles.splice(0, 1); } - const scopeName = titles.pop(); + const scopeName = titles.length > 0 ? titles.pop()! : scope.spec.title; + const titlesString = titles.length > 0 ? titles.join(' > ') : ''; - return [titles.join(' > '), scopeName]; - }); + acc[titlesString] = acc[titlesString] ? `${acc[titlesString]}, ${scopeName}` : scopeName; - const groupedByPath = groupBy(pathsTitles, ([path]) => path); + return acc; + }, {}); - const scopesPaths = Object.entries(groupedByPath) - .map(([path, pathScopes]) => { - const scopesTitles = pathScopes.map(([, scopeTitle]) => scopeTitle).join(', '); - - return (path ? [path, scopesTitles] : [scopesTitles]).join(' > '); - }) - .map((path) => ( -

- {path} -

- )); - - return <>{scopesPaths}; + return ( + <> + {Object.entries(pathsScopesMap).map(([path, scopesTitles]) => ( +

+ {path ? `${path} > ${scopesTitles}` : scopesTitles} +

+ ))} + + ); }, [nodes, scopes, styles]); const scopesTitles = useMemo(() => scopes.map(({ scope }) => scope.spec.title).join(', '), [scopes]);