1
0
mirror of https://github.com/Unleash/unleash.git synced 2025-07-21 13:47:39 +02:00

Feat(1-3760)/filters per analytics section (#10039)

Splits the insights page into separate sections with their own separate
filters. Each filter is sticky to the top of the page, similar to how
the previous filters worked.

In doing this, I have also moved around a lot of code. Refer to the
inline comments for more specific examples, but on a high level, this
PR:
- Moves the flag check from InsightsCharts into Insights itself. Because
the old Insights had filters and state, and the new one does not, it
made sense to fork off higher up in the tree. Because the new version
doesn't have state, I have also simplified it and removed an
intermediate component (InsightsCharts) that doesn't feel necessary
anymore.
- Because InsightsCharts isn't used anymore, I've moved the
LegacyInsightsCharts file back into InsightsCharts. However, I'm happy
to move it back if we think that's useful.
- Instead of all charts living in InsightsCharts, I've split each
section into its own file in the new sections directory. Because the
sections have separate filters, they don't share any state anymore, so
there's nothing they share.
- I'm reusing the existing hook and endpoint. As it stands, the
performance insights use **most** of the data from that payload (but not
all of it). The user insights use some of it. Flag lifecycle insights
doesn't use anything, but I've wired it up to make the filters work. I
expect that we'll iterate on the API endpoints etc later.


![image](https://github.com/user-attachments/assets/8fcf5800-18be-4399-b7e2-e2b4b8565ea8)
This commit is contained in:
Thomas Heartman 2025-06-03 10:47:30 +02:00 committed by GitHub
parent 6d70265edd
commit f7c667e410
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
13 changed files with 704 additions and 564 deletions

View File

@ -42,7 +42,7 @@ type ITextFilterItem = IBaseFilterItem & {
pluralOperators: [string, ...string[]];
};
type IDateFilterItem = IBaseFilterItem & {
export type IDateFilterItem = IBaseFilterItem & {
dateOperators: [string, ...string[]];
fromFilterKey?: string;
toFilterKey?: string;

View File

@ -27,6 +27,9 @@ const setupApi = () => {
const currentTime = '2024-04-25T08:05:00.000Z';
// todo(lifecycleMetrics): this test won't be relevant anymore because the
// filters are on each section instead of the top-level component. Consider
// rewriting this for the individual section components instead.
test('Filter insights by project and date', async () => {
vi.setSystemTime(currentTime);
setupApi();

View File

@ -1,90 +1,32 @@
import { useState, type FC } from 'react';
import type { FC } from 'react';
import { styled } from '@mui/material';
import { usePersistentTableState } from 'hooks/usePersistentTableState';
import { allOption } from 'component/common/ProjectSelect/ProjectSelect';
import { useInsights } from 'hooks/api/getters/useInsights/useInsights';
import { InsightsHeader } from './components/InsightsHeader/InsightsHeader.tsx';
import { useInsightsData } from './hooks/useInsightsData.ts';
import { InsightsCharts } from './InsightsCharts.tsx';
import { Sticky } from 'component/common/Sticky/Sticky';
import { InsightsFilters } from './InsightsFilters.tsx';
import { FilterItemParam } from '../../utils/serializeQueryParams.ts';
import { format, subMonths } from 'date-fns';
import { withDefault } from 'use-query-params';
import { useUiFlag } from 'hooks/useUiFlag.ts';
import { LegacyInsights } from './LegacyInsights.tsx';
import { StyledContainer } from './InsightsCharts.styles.ts';
import { LifecycleInsights } from './sections/LifecycleInsights.tsx';
import { PerformanceInsights } from './sections/PerformanceInsights.tsx';
import { UserInsights } from './sections/UserInsights.tsx';
const StyledWrapper = styled('div')(({ theme }) => ({
paddingTop: theme.spacing(2),
}));
const StickyContainer = styled(Sticky)(({ theme }) => ({
position: 'sticky',
top: 0,
zIndex: theme.zIndex.sticky,
padding: theme.spacing(2, 0),
background: theme.palette.background.application,
transition: 'padding 0.3s ease',
}));
interface InsightsProps {
withCharts?: boolean;
}
export const Insights: FC<InsightsProps> = ({ withCharts = true }) => {
const [scrolled, setScrolled] = useState(false);
const stateConfig = {
project: FilterItemParam,
from: withDefault(FilterItemParam, {
values: [format(subMonths(new Date(), 1), 'yyyy-MM-dd')],
operator: 'IS',
}),
to: withDefault(FilterItemParam, {
values: [format(new Date(), 'yyyy-MM-dd')],
operator: 'IS',
}),
};
const [state, setState] = usePersistentTableState('insights', stateConfig, [
'from',
'to',
]);
const { insights, loading } = useInsights(
state.from?.values[0],
state.to?.values[0],
);
const projects = state.project?.values ?? [allOption.id];
const insightsData = useInsightsData(insights, projects);
const handleScroll = () => {
if (!scrolled && window.scrollY > 0) {
setScrolled(true);
} else if (scrolled && window.scrollY === 0) {
setScrolled(false);
}
};
if (typeof window !== 'undefined') {
window.addEventListener('scroll', handleScroll);
}
const NewInsights: FC = () => {
return (
<StyledWrapper>
<StickyContainer>
<InsightsHeader
actions={
<InsightsFilters state={state} onChange={setState} />
}
/>
</StickyContainer>
{withCharts && (
<InsightsCharts
loading={loading}
projects={projects}
{...insightsData}
/>
)}
<InsightsHeader />
<StyledContainer>
<LifecycleInsights />
<PerformanceInsights />
<UserInsights />
</StyledContainer>
</StyledWrapper>
);
};
export const Insights: FC<{ withCharts?: boolean }> = (props) => {
const useNewInsights = useUiFlag('lifecycleMetrics');
return useNewInsights ? <NewInsights /> : <LegacyInsights {...props} />;
};

View File

@ -0,0 +1,46 @@
import { Box, Paper, styled } from '@mui/material';
export const StyledContainer = styled(Box)(({ theme }) => ({
display: 'flex',
flexDirection: 'column',
gap: theme.spacing(4),
}));
export const StyledWidget = styled(Paper)(({ theme }) => ({
borderRadius: `${theme.shape.borderRadiusLarge}px`,
boxShadow: 'none',
display: 'flex',
flexWrap: 'wrap',
[theme.breakpoints.up('md')]: {
flexDirection: 'row',
flexWrap: 'nowrap',
},
}));
export const StyledWidgetContent = styled(Box)(({ theme }) => ({
padding: theme.spacing(3),
width: '100%',
}));
export const StyledWidgetStats = styled(Box)<{
width?: number;
padding?: number;
}>(({ theme, width = 300, padding = 3 }) => ({
display: 'flex',
flexDirection: 'column',
gap: theme.spacing(2),
padding: theme.spacing(padding),
minWidth: '100%',
[theme.breakpoints.up('md')]: {
minWidth: `${width}px`,
borderRight: `1px solid ${theme.palette.background.application}`,
},
}));
export const StyledChartContainer = styled(Box)(({ theme }) => ({
position: 'relative',
minWidth: 0, // bugfix, see: https://github.com/chartjs/Chart.js/issues/4156#issuecomment-295180128
flexGrow: 1,
margin: 'auto 0',
padding: theme.spacing(3),
}));

View File

@ -1,4 +1,4 @@
import type { FC, PropsWithChildren } from 'react';
import type { FC } from 'react';
import { Box, Paper, styled } from '@mui/material';
import { UserStats } from './componentsStat/UserStats/UserStats.tsx';
import { UsersChart } from './componentsChart/UsersChart/UsersChart.tsx';
@ -8,6 +8,8 @@ import { FlagsChart } from './componentsChart/FlagsChart/FlagsChart.tsx';
import { FlagsProjectChart } from './componentsChart/FlagsProjectChart/FlagsProjectChart.tsx';
import { HealthStats } from './componentsStat/HealthStats/HealthStats.tsx';
import { ProjectHealthChart } from './componentsChart/ProjectHealthChart/ProjectHealthChart.tsx';
import { TimeToProduction } from './componentsStat/TimeToProduction/TimeToProduction.tsx';
import { TimeToProductionChart } from './componentsChart/TimeToProductionChart/TimeToProductionChart.tsx';
import { MetricsSummaryChart } from './componentsChart/MetricsSummaryChart/MetricsSummaryChart.tsx';
import { UpdatesPerEnvironmentTypeChart } from './componentsChart/UpdatesPerEnvironmentTypeChart/UpdatesPerEnvironmentTypeChart.tsx';
import type { InstanceInsightsSchema } from 'openapi';
@ -15,8 +17,7 @@ import type { GroupedDataByProject } from './hooks/useGroupedProjectTrends.ts';
import { allOption } from 'component/common/ProjectSelect/ProjectSelect';
import useUiConfig from 'hooks/api/getters/useUiConfig/useUiConfig';
import { WidgetTitle } from './components/WidgetTitle/WidgetTitle.tsx';
import { useUiFlag } from 'hooks/useUiFlag.ts';
import { LegacyInsightsCharts } from './LegacyInsightsCharts.tsx';
import { ConditionallyRender } from 'component/common/ConditionallyRender/ConditionallyRender';
export interface IChartsProps {
flagTrends: InstanceInsightsSchema['flagTrends'];
@ -48,7 +49,7 @@ export interface IChartsProps {
const StyledContainer = styled(Box)(({ theme }) => ({
display: 'flex',
flexDirection: 'column',
gap: theme.spacing(4),
gap: theme.spacing(2),
}));
const StyledWidget = styled(Paper)(({ theme }) => ({
@ -89,23 +90,7 @@ const StyledChartContainer = styled(Box)(({ theme }) => ({
padding: theme.spacing(3),
}));
const StyledSection = styled('section')(({ theme }) => ({
display: 'flex',
flexDirection: 'column',
gap: theme.spacing(2),
}));
const Section: FC<PropsWithChildren<{ title: string }>> = ({
title,
children,
}) => (
<StyledSection>
<h2>{title}</h2>
{children}
</StyledSection>
);
const NewInsightsCharts: FC<IChartsProps> = ({
export const InsightsCharts: FC<IChartsProps> = ({
projects,
summary,
userTrends,
@ -137,74 +122,161 @@ const NewInsightsCharts: FC<IChartsProps> = ({
return (
<StyledContainer>
<Section title='Flags lifecycle currently' />
<Section title='Performance insights'>
{showAllProjects ? (
<StyledWidget>
<StyledWidgetStats width={275}>
<WidgetTitle title='Flags' />
<FlagStats
count={flagsTotal}
flagsPerUser={getFlagsPerUser(
flagsTotal,
usersTotal,
)}
isLoading={loading}
/>
</StyledWidgetStats>
<StyledChartContainer>
<FlagsChart
flagTrends={flagTrends}
isLoading={loading}
/>
</StyledChartContainer>
</StyledWidget>
) : (
<StyledWidget>
<StyledWidgetStats width={275}>
<WidgetTitle title='Flags' />
<FlagStats
count={summary.total}
flagsPerUser={''}
isLoading={loading}
/>
</StyledWidgetStats>
<StyledChartContainer>
<FlagsProjectChart
projectFlagTrends={groupedProjectsData}
isLoading={loading}
/>
</StyledChartContainer>
</StyledWidget>
)}
{isEnterprise() ? (
<StyledWidget>
<StyledWidgetStats width={350} padding={0}>
<HealthStats
value={summary.averageHealth}
healthy={summary.active}
stale={summary.stale}
potentiallyStale={summary.potentiallyStale}
title={
<WidgetTitle
title='Health'
tooltip={
'Percentage of flags that are not stale or potentially stale.'
}
/>
}
/>
</StyledWidgetStats>
<StyledChartContainer>
<ProjectHealthChart
projectFlagTrends={groupedProjectsData}
isAggregate={showAllProjects}
isLoading={loading}
/>
</StyledChartContainer>
</StyledWidget>
) : null}
{isEnterprise() ? (
<ConditionallyRender
condition={showAllProjects}
show={
<>
<StyledWidget>
<StyledWidgetStats>
<WidgetTitle title='Total users' />
<UserStats
count={usersTotal}
active={usersActive}
inactive={usersInactive}
isLoading={loading}
/>
</StyledWidgetStats>
<StyledChartContainer>
<UsersChart
userTrends={userTrends}
isLoading={loading}
/>
</StyledChartContainer>
</StyledWidget>
</>
}
elseShow={
<>
<StyledWidget>
<StyledWidgetStats>
<WidgetTitle
title={
isOneProjectSelected
? 'Users in project'
: 'Users per project on average'
}
tooltip={
isOneProjectSelected
? 'Number of users in selected projects.'
: 'Average number of users for selected projects.'
}
/>
<UserStats
count={summary.averageUsers}
isLoading={loading}
/>
</StyledWidgetStats>
<StyledChartContainer>
<UsersPerProjectChart
projectFlagTrends={groupedProjectsData}
isLoading={loading}
/>
</StyledChartContainer>
</StyledWidget>
</>
}
/>
<ConditionallyRender
condition={isEnterprise()}
show={
<>
<StyledWidget>
<StyledWidgetStats width={350} padding={0}>
<HealthStats
value={summary.averageHealth}
healthy={summary.active}
stale={summary.stale}
potentiallyStale={summary.potentiallyStale}
title={
<WidgetTitle
title='Health'
tooltip={
'Percentage of flags that are not stale or potentially stale.'
}
/>
}
/>
</StyledWidgetStats>
<StyledChartContainer>
<ProjectHealthChart
projectFlagTrends={groupedProjectsData}
isAggregate={showAllProjects}
isLoading={loading}
/>
</StyledChartContainer>
</StyledWidget>
<StyledWidget>
<StyledWidgetStats>
<WidgetTitle
title='Median time to production'
tooltip={`How long does it currently take on average from when a feature flag was created until it was enabled in a "production" type environment. This is calculated only from feature flags of the type "release" and is the median across the selected projects.`}
/>
<TimeToProduction
daysToProduction={
summary.medianTimeToProduction
}
/>
</StyledWidgetStats>
<StyledChartContainer>
<TimeToProductionChart
projectFlagTrends={groupedProjectsData}
isAggregate={showAllProjects}
isLoading={loading}
/>
</StyledChartContainer>
</StyledWidget>
</>
}
/>
<ConditionallyRender
condition={showAllProjects}
show={
<>
<StyledWidget>
<StyledWidgetStats width={275}>
<WidgetTitle title='Flags' />
<FlagStats
count={flagsTotal}
flagsPerUser={getFlagsPerUser(
flagsTotal,
usersTotal,
)}
isLoading={loading}
/>
</StyledWidgetStats>
<StyledChartContainer>
<FlagsChart
flagTrends={flagTrends}
isLoading={loading}
/>
</StyledChartContainer>
</StyledWidget>
</>
}
elseShow={
<>
<StyledWidget>
<StyledWidgetStats width={275}>
<WidgetTitle title='Flags' />
<FlagStats
count={summary.total}
flagsPerUser={''}
isLoading={loading}
/>
</StyledWidgetStats>
<StyledChartContainer>
<FlagsProjectChart
projectFlagTrends={groupedProjectsData}
isLoading={loading}
/>
</StyledChartContainer>
</StyledWidget>
</>
}
/>
<ConditionallyRender
condition={isEnterprise()}
show={
<>
<StyledWidget>
<StyledWidgetContent>
@ -241,67 +313,8 @@ const NewInsightsCharts: FC<IChartsProps> = ({
</StyledWidgetContent>
</StyledWidget>
</>
) : null}
</Section>
<Section title='User insights'>
{showAllProjects ? (
<StyledWidget>
<StyledWidgetStats>
<WidgetTitle title='Total users' />
<UserStats
count={usersTotal}
active={usersActive}
inactive={usersInactive}
isLoading={loading}
/>
</StyledWidgetStats>
<StyledChartContainer>
<UsersChart
userTrends={userTrends}
isLoading={loading}
/>
</StyledChartContainer>
</StyledWidget>
) : (
<StyledWidget>
<StyledWidgetStats>
<WidgetTitle
title={
isOneProjectSelected
? 'Users in project'
: 'Users per project on average'
}
tooltip={
isOneProjectSelected
? 'Number of users in selected projects.'
: 'Average number of users for selected projects.'
}
/>
<UserStats
count={summary.averageUsers}
isLoading={loading}
/>
</StyledWidgetStats>
<StyledChartContainer>
<UsersPerProjectChart
projectFlagTrends={groupedProjectsData}
isLoading={loading}
/>
</StyledChartContainer>
</StyledWidget>
)}
</Section>
}
/>
</StyledContainer>
);
};
export const InsightsCharts: FC<IChartsProps> = (props) => {
const useNewInsightsCharts = useUiFlag('lifecycleMetrics');
return useNewInsightsCharts ? (
<NewInsightsCharts {...props} />
) : (
<LegacyInsightsCharts {...props} />
);
};

View File

@ -3,19 +3,32 @@ import useProjects from 'hooks/api/getters/useProjects/useProjects';
import {
type FilterItemParamHolder,
Filters,
type IDateFilterItem,
type IFilterItem,
} from 'component/filter/Filters/Filters';
import { styled } from '@mui/material';
import { useUiFlag } from 'hooks/useUiFlag';
interface IFeatureToggleFiltersProps {
state: FilterItemParamHolder;
onChange: (value: FilterItemParamHolder) => void;
className?: string;
filterNamePrefix?: string;
}
const FiltersNoPadding = styled(Filters)({
padding: 0,
});
export const InsightsFilters: FC<IFeatureToggleFiltersProps> = ({
filterNamePrefix,
state,
onChange,
...filterProps
}) => {
const { projects } = useProjects();
const FilterComponent = useUiFlag('lifecycleMetrics')
? FiltersNoPadding
: Filters;
const [availableFilters, setAvailableFilters] = useState<IFilterItem[]>([]);
@ -27,49 +40,51 @@ export const InsightsFilters: FC<IFeatureToggleFiltersProps> = ({
const hasMultipleProjects = projectsOptions.length > 1;
const prefix = filterNamePrefix ?? '';
const availableFilters: IFilterItem[] = [
{
label: 'Date From',
icon: 'today',
options: [],
filterKey: 'from',
filterKey: `${prefix}from`,
dateOperators: ['IS'],
fromFilterKey: 'from',
toFilterKey: 'to',
fromFilterKey: `${prefix}from`,
toFilterKey: `${prefix}to`,
persistent: true,
},
} as IDateFilterItem,
{
label: 'Date To',
icon: 'today',
options: [],
filterKey: 'to',
filterKey: `${prefix}to`,
dateOperators: ['IS'],
fromFilterKey: 'from',
toFilterKey: 'to',
fromFilterKey: `${prefix}from`,
toFilterKey: `${prefix}to`,
persistent: true,
},
} as IDateFilterItem,
...(hasMultipleProjects
? ([
{
label: 'Project',
icon: 'topic',
options: projectsOptions,
filterKey: 'project',
filterKey: `${prefix}project`,
singularOperators: ['IS'],
pluralOperators: ['IS_ANY_OF'],
},
] as IFilterItem[])
: []),
];
].filter(({ filterKey }) => filterKey in state);
setAvailableFilters(availableFilters);
}, [JSON.stringify(projects)]);
return (
<Filters
availableFilters={availableFilters}
<FilterComponent
{...filterProps}
state={state}
onChange={onChange}
availableFilters={availableFilters}
/>
);
};

View File

@ -0,0 +1,76 @@
import type { FC } from 'react';
import { styled } from '@mui/material';
import { usePersistentTableState } from 'hooks/usePersistentTableState';
import { allOption } from 'component/common/ProjectSelect/ProjectSelect';
import { useInsights } from 'hooks/api/getters/useInsights/useInsights';
import { InsightsHeader } from './components/InsightsHeader/InsightsHeader.tsx';
import { useInsightsData } from './hooks/useInsightsData.ts';
import { Sticky } from 'component/common/Sticky/Sticky';
import { InsightsFilters } from './InsightsFilters.tsx';
import { FilterItemParam } from '../../utils/serializeQueryParams.ts';
import { format, subMonths } from 'date-fns';
import { withDefault } from 'use-query-params';
import { InsightsCharts } from './InsightsCharts.tsx';
const StyledWrapper = styled('div')(({ theme }) => ({
paddingTop: theme.spacing(2),
}));
const StickyContainer = styled(Sticky)(({ theme }) => ({
position: 'sticky',
top: 0,
zIndex: theme.zIndex.sticky,
padding: theme.spacing(2, 0),
background: theme.palette.background.application,
transition: 'padding 0.3s ease',
}));
interface InsightsProps {
withCharts?: boolean;
}
export const LegacyInsights: FC<InsightsProps> = ({ withCharts = true }) => {
const stateConfig = {
project: FilterItemParam,
from: withDefault(FilterItemParam, {
values: [format(subMonths(new Date(), 1), 'yyyy-MM-dd')],
operator: 'IS',
}),
to: withDefault(FilterItemParam, {
values: [format(new Date(), 'yyyy-MM-dd')],
operator: 'IS',
}),
};
const [state, setState] = usePersistentTableState('insights', stateConfig, [
'from',
'to',
]);
const { insights, loading } = useInsights(
state.from?.values[0],
state.to?.values[0],
);
const projects = state.project?.values ?? [allOption.id];
const insightsData = useInsightsData(insights, projects);
return (
<StyledWrapper>
<StickyContainer>
<InsightsHeader
actions={
<InsightsFilters state={state} onChange={setState} />
}
/>
</StickyContainer>
{withCharts && (
<InsightsCharts
loading={loading}
projects={projects}
{...insightsData}
/>
)}
</StyledWrapper>
);
};

View File

@ -1,320 +0,0 @@
import type { FC } from 'react';
import { Box, Paper, styled } from '@mui/material';
import { UserStats } from './componentsStat/UserStats/UserStats.tsx';
import { UsersChart } from './componentsChart/UsersChart/UsersChart.tsx';
import { UsersPerProjectChart } from './componentsChart/UsersPerProjectChart/UsersPerProjectChart.tsx';
import { FlagStats } from './componentsStat/FlagStats/FlagStats.tsx';
import { FlagsChart } from './componentsChart/FlagsChart/FlagsChart.tsx';
import { FlagsProjectChart } from './componentsChart/FlagsProjectChart/FlagsProjectChart.tsx';
import { HealthStats } from './componentsStat/HealthStats/HealthStats.tsx';
import { ProjectHealthChart } from './componentsChart/ProjectHealthChart/ProjectHealthChart.tsx';
import { TimeToProduction } from './componentsStat/TimeToProduction/TimeToProduction.tsx';
import { TimeToProductionChart } from './componentsChart/TimeToProductionChart/TimeToProductionChart.tsx';
import { MetricsSummaryChart } from './componentsChart/MetricsSummaryChart/MetricsSummaryChart.tsx';
import { UpdatesPerEnvironmentTypeChart } from './componentsChart/UpdatesPerEnvironmentTypeChart/UpdatesPerEnvironmentTypeChart.tsx';
import type { InstanceInsightsSchema } from 'openapi';
import type { GroupedDataByProject } from './hooks/useGroupedProjectTrends.ts';
import { allOption } from 'component/common/ProjectSelect/ProjectSelect';
import useUiConfig from 'hooks/api/getters/useUiConfig/useUiConfig';
import { WidgetTitle } from './components/WidgetTitle/WidgetTitle.tsx';
import { ConditionallyRender } from 'component/common/ConditionallyRender/ConditionallyRender';
export interface IChartsProps {
flagTrends: InstanceInsightsSchema['flagTrends'];
projectsData: InstanceInsightsSchema['projectFlagTrends'];
groupedProjectsData: GroupedDataByProject<
InstanceInsightsSchema['projectFlagTrends']
>;
metricsData: InstanceInsightsSchema['metricsSummaryTrends'];
groupedMetricsData: GroupedDataByProject<
InstanceInsightsSchema['metricsSummaryTrends']
>;
userTrends: InstanceInsightsSchema['userTrends'];
environmentTypeTrends: InstanceInsightsSchema['environmentTypeTrends'];
summary: {
total: number;
active: number;
stale: number;
potentiallyStale: number;
averageUsers: number;
averageHealth?: string;
flagsPerUser?: string;
medianTimeToProduction?: number;
};
loading: boolean;
projects: string[];
allMetricsDatapoints: string[];
}
const StyledContainer = styled(Box)(({ theme }) => ({
display: 'flex',
flexDirection: 'column',
gap: theme.spacing(2),
}));
const StyledWidget = styled(Paper)(({ theme }) => ({
borderRadius: `${theme.shape.borderRadiusLarge}px`,
boxShadow: 'none',
display: 'flex',
flexWrap: 'wrap',
[theme.breakpoints.up('md')]: {
flexDirection: 'row',
flexWrap: 'nowrap',
},
}));
const StyledWidgetContent = styled(Box)(({ theme }) => ({
padding: theme.spacing(3),
width: '100%',
}));
const StyledWidgetStats = styled(Box)<{ width?: number; padding?: number }>(
({ theme, width = 300, padding = 3 }) => ({
display: 'flex',
flexDirection: 'column',
gap: theme.spacing(2),
padding: theme.spacing(padding),
minWidth: '100%',
[theme.breakpoints.up('md')]: {
minWidth: `${width}px`,
borderRight: `1px solid ${theme.palette.background.application}`,
},
}),
);
const StyledChartContainer = styled(Box)(({ theme }) => ({
position: 'relative',
minWidth: 0, // bugfix, see: https://github.com/chartjs/Chart.js/issues/4156#issuecomment-295180128
flexGrow: 1,
margin: 'auto 0',
padding: theme.spacing(3),
}));
export const LegacyInsightsCharts: FC<IChartsProps> = ({
projects,
summary,
userTrends,
groupedProjectsData,
flagTrends,
groupedMetricsData,
environmentTypeTrends,
allMetricsDatapoints,
loading,
}) => {
const showAllProjects = projects[0] === allOption.id;
const isOneProjectSelected = projects.length === 1;
const { isEnterprise } = useUiConfig();
const lastUserTrend = userTrends[userTrends.length - 1];
const lastFlagTrend = flagTrends[flagTrends.length - 1];
const usersTotal = lastUserTrend?.total ?? 0;
const usersActive = lastUserTrend?.active ?? 0;
const usersInactive = lastUserTrend?.inactive ?? 0;
const flagsTotal = lastFlagTrend?.total ?? 0;
function getFlagsPerUser(flagsTotal: number, usersTotal: number) {
const flagsPerUserCalculation = flagsTotal / usersTotal;
return Number.isNaN(flagsPerUserCalculation)
? 'N/A'
: flagsPerUserCalculation.toFixed(2);
}
return (
<StyledContainer>
<ConditionallyRender
condition={showAllProjects}
show={
<>
<StyledWidget>
<StyledWidgetStats>
<WidgetTitle title='Total users' />
<UserStats
count={usersTotal}
active={usersActive}
inactive={usersInactive}
isLoading={loading}
/>
</StyledWidgetStats>
<StyledChartContainer>
<UsersChart
userTrends={userTrends}
isLoading={loading}
/>
</StyledChartContainer>
</StyledWidget>
</>
}
elseShow={
<>
<StyledWidget>
<StyledWidgetStats>
<WidgetTitle
title={
isOneProjectSelected
? 'Users in project'
: 'Users per project on average'
}
tooltip={
isOneProjectSelected
? 'Number of users in selected projects.'
: 'Average number of users for selected projects.'
}
/>
<UserStats
count={summary.averageUsers}
isLoading={loading}
/>
</StyledWidgetStats>
<StyledChartContainer>
<UsersPerProjectChart
projectFlagTrends={groupedProjectsData}
isLoading={loading}
/>
</StyledChartContainer>
</StyledWidget>
</>
}
/>
<ConditionallyRender
condition={isEnterprise()}
show={
<>
<StyledWidget>
<StyledWidgetStats width={350} padding={0}>
<HealthStats
value={summary.averageHealth}
healthy={summary.active}
stale={summary.stale}
potentiallyStale={summary.potentiallyStale}
title={
<WidgetTitle
title='Health'
tooltip={
'Percentage of flags that are not stale or potentially stale.'
}
/>
}
/>
</StyledWidgetStats>
<StyledChartContainer>
<ProjectHealthChart
projectFlagTrends={groupedProjectsData}
isAggregate={showAllProjects}
isLoading={loading}
/>
</StyledChartContainer>
</StyledWidget>
<StyledWidget>
<StyledWidgetStats>
<WidgetTitle
title='Median time to production'
tooltip={`How long does it currently take on average from when a feature flag was created until it was enabled in a "production" type environment. This is calculated only from feature flags of the type "release" and is the median across the selected projects.`}
/>
<TimeToProduction
daysToProduction={
summary.medianTimeToProduction
}
/>
</StyledWidgetStats>
<StyledChartContainer>
<TimeToProductionChart
projectFlagTrends={groupedProjectsData}
isAggregate={showAllProjects}
isLoading={loading}
/>
</StyledChartContainer>
</StyledWidget>
</>
}
/>
<ConditionallyRender
condition={showAllProjects}
show={
<>
<StyledWidget>
<StyledWidgetStats width={275}>
<WidgetTitle title='Flags' />
<FlagStats
count={flagsTotal}
flagsPerUser={getFlagsPerUser(
flagsTotal,
usersTotal,
)}
isLoading={loading}
/>
</StyledWidgetStats>
<StyledChartContainer>
<FlagsChart
flagTrends={flagTrends}
isLoading={loading}
/>
</StyledChartContainer>
</StyledWidget>
</>
}
elseShow={
<>
<StyledWidget>
<StyledWidgetStats width={275}>
<WidgetTitle title='Flags' />
<FlagStats
count={summary.total}
flagsPerUser={''}
isLoading={loading}
/>
</StyledWidgetStats>
<StyledChartContainer>
<FlagsProjectChart
projectFlagTrends={groupedProjectsData}
isLoading={loading}
/>
</StyledChartContainer>
</StyledWidget>
</>
}
/>
<ConditionallyRender
condition={isEnterprise()}
show={
<>
<StyledWidget>
<StyledWidgetContent>
<WidgetTitle
title='Flag evaluation metrics'
tooltip='Summary of all flag evaluations reported by SDKs.'
/>
<StyledChartContainer>
<MetricsSummaryChart
metricsSummaryTrends={
groupedMetricsData
}
allDatapointsSorted={
allMetricsDatapoints
}
isAggregate={showAllProjects}
isLoading={loading}
/>
</StyledChartContainer>
</StyledWidgetContent>
</StyledWidget>
<StyledWidget>
<StyledWidgetContent>
<WidgetTitle
title='Updates per environment type'
tooltip='Summary of all configuration updates per environment type.'
/>
<UpdatesPerEnvironmentTypeChart
environmentTypeTrends={
environmentTypeTrends
}
isLoading={loading}
/>
</StyledWidgetContent>
</StyledWidget>
</>
}
/>
</StyledContainer>
);
};

View File

@ -0,0 +1,34 @@
import { styled } from '@mui/material';
import type { FC, PropsWithChildren, ReactNode } from 'react';
const StyledSection = styled('section')(({ theme }) => ({
display: 'flex',
flexDirection: 'column',
gap: theme.spacing(2),
}));
const SectionTitleRow = styled('div')(({ theme }) => ({
position: 'sticky',
top: 0,
zIndex: theme.zIndex.sticky,
paddingBlock: theme.spacing(2),
background: theme.palette.background.application,
transition: 'padding 0.3s ease',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
flexFlow: 'row wrap',
rowGap: theme.spacing(2),
}));
export const InsightsSection: FC<
PropsWithChildren<{ title: string; filters?: ReactNode }>
> = ({ title, children, filters: HeaderActions }) => (
<StyledSection>
<SectionTitleRow>
<h2>{title}</h2>
{HeaderActions}
</SectionTitleRow>
{children}
</StyledSection>
);

View File

@ -0,0 +1,26 @@
import { usePersistentTableState } from 'hooks/usePersistentTableState';
import type { FC } from 'react';
import { FilterItemParam } from 'utils/serializeQueryParams';
import { InsightsSection } from 'component/insights/sections/InsightsSection';
import { InsightsFilters } from 'component/insights/InsightsFilters';
export const LifecycleInsights: FC = () => {
const statePrefix = 'lifecycle-';
const stateConfig = {
[`${statePrefix}project`]: FilterItemParam,
};
const [state, setState] = usePersistentTableState('insights', stateConfig);
return (
<InsightsSection
title='Flags lifecycle currently'
filters={
<InsightsFilters
state={state}
onChange={setState}
filterNamePrefix={statePrefix}
/>
}
/>
);
};

View File

@ -0,0 +1,186 @@
import { allOption } from 'component/common/ProjectSelect/ProjectSelect';
import { format, subMonths } from 'date-fns';
import { useInsights } from 'hooks/api/getters/useInsights/useInsights';
import useUiConfig from 'hooks/api/getters/useUiConfig/useUiConfig';
import { usePersistentTableState } from 'hooks/usePersistentTableState';
import type { FC } from 'react';
import { withDefault } from 'use-query-params';
import { FilterItemParam } from 'utils/serializeQueryParams';
import { WidgetTitle } from 'component/insights/components/WidgetTitle/WidgetTitle';
import { FlagsChart } from 'component/insights/componentsChart/FlagsChart/FlagsChart';
import { FlagsProjectChart } from 'component/insights/componentsChart/FlagsProjectChart/FlagsProjectChart';
import { MetricsSummaryChart } from 'component/insights/componentsChart/MetricsSummaryChart/MetricsSummaryChart';
import { ProjectHealthChart } from 'component/insights/componentsChart/ProjectHealthChart/ProjectHealthChart';
import { UpdatesPerEnvironmentTypeChart } from 'component/insights/componentsChart/UpdatesPerEnvironmentTypeChart/UpdatesPerEnvironmentTypeChart';
import { FlagStats } from 'component/insights/componentsStat/FlagStats/FlagStats';
import { HealthStats } from 'component/insights/componentsStat/HealthStats/HealthStats';
import { useInsightsData } from 'component/insights/hooks/useInsightsData';
import { InsightsSection } from 'component/insights/sections/InsightsSection';
import { InsightsFilters } from 'component/insights/InsightsFilters';
import {
StyledChartContainer,
StyledWidget,
StyledWidgetContent,
StyledWidgetStats,
} from '../InsightsCharts.styles';
export const PerformanceInsights: FC = () => {
const statePrefix = 'performance-';
const stateConfig = {
[`${statePrefix}project`]: FilterItemParam,
[`${statePrefix}from`]: withDefault(FilterItemParam, {
values: [format(subMonths(new Date(), 1), 'yyyy-MM-dd')],
operator: 'IS',
}),
[`${statePrefix}to`]: withDefault(FilterItemParam, {
values: [format(new Date(), 'yyyy-MM-dd')],
operator: 'IS',
}),
};
const [state, setState] = usePersistentTableState('insights', stateConfig, [
'performance-from',
'performance-to',
]);
const { insights, loading } = useInsights(
state[`${statePrefix}from`]?.values[0],
state[`${statePrefix}to`]?.values[0],
);
const projects = state[`${statePrefix}project`]?.values ?? [allOption.id];
const showAllProjects = projects[0] === allOption.id;
const {
flagTrends,
summary,
groupedProjectsData,
userTrends,
groupedMetricsData,
allMetricsDatapoints,
environmentTypeTrends,
} = useInsightsData(insights, projects);
const { isEnterprise } = useUiConfig();
const lastUserTrend = userTrends[userTrends.length - 1];
const usersTotal = lastUserTrend?.total ?? 0;
const lastFlagTrend = flagTrends[flagTrends.length - 1];
const flagsTotal = lastFlagTrend?.total ?? 0;
function getFlagsPerUser(flagsTotal: number, usersTotal: number) {
const flagsPerUserCalculation = flagsTotal / usersTotal;
return Number.isNaN(flagsPerUserCalculation)
? 'N/A'
: flagsPerUserCalculation.toFixed(2);
}
return (
<InsightsSection
title='Performance insights'
filters={
<InsightsFilters
state={state}
onChange={setState}
filterNamePrefix={statePrefix}
/>
}
>
{showAllProjects ? (
<StyledWidget>
<StyledWidgetStats width={275}>
<WidgetTitle title='Flags' />
<FlagStats
count={flagsTotal}
flagsPerUser={getFlagsPerUser(
flagsTotal,
usersTotal,
)}
isLoading={loading}
/>
</StyledWidgetStats>
<StyledChartContainer>
<FlagsChart
flagTrends={flagTrends}
isLoading={loading}
/>
</StyledChartContainer>
</StyledWidget>
) : (
<StyledWidget>
<StyledWidgetStats width={275}>
<WidgetTitle title='Flags' />
<FlagStats
count={summary.total}
flagsPerUser={''}
isLoading={loading}
/>
</StyledWidgetStats>
<StyledChartContainer>
<FlagsProjectChart
projectFlagTrends={groupedProjectsData}
isLoading={loading}
/>
</StyledChartContainer>
</StyledWidget>
)}
{isEnterprise() ? (
<StyledWidget>
<StyledWidgetStats width={350} padding={0}>
<HealthStats
value={summary.averageHealth}
healthy={summary.active}
stale={summary.stale}
potentiallyStale={summary.potentiallyStale}
title={
<WidgetTitle
title='Health'
tooltip={
'Percentage of flags that are not stale or potentially stale.'
}
/>
}
/>
</StyledWidgetStats>
<StyledChartContainer>
<ProjectHealthChart
projectFlagTrends={groupedProjectsData}
isAggregate={showAllProjects}
isLoading={loading}
/>
</StyledChartContainer>
</StyledWidget>
) : null}
{isEnterprise() ? (
<>
<StyledWidget>
<StyledWidgetContent>
<WidgetTitle
title='Flag evaluation metrics'
tooltip='Summary of all flag evaluations reported by SDKs.'
/>
<StyledChartContainer>
<MetricsSummaryChart
metricsSummaryTrends={groupedMetricsData}
allDatapointsSorted={allMetricsDatapoints}
isAggregate={showAllProjects}
isLoading={loading}
/>
</StyledChartContainer>
</StyledWidgetContent>
</StyledWidget>
<StyledWidget>
<StyledWidgetContent>
<WidgetTitle
title='Updates per environment type'
tooltip='Summary of all configuration updates per environment type.'
/>
<UpdatesPerEnvironmentTypeChart
environmentTypeTrends={environmentTypeTrends}
isLoading={loading}
/>
</StyledWidgetContent>
</StyledWidget>
</>
) : null}
</InsightsSection>
);
};

View File

@ -0,0 +1,119 @@
import { allOption } from 'component/common/ProjectSelect/ProjectSelect';
import { format, subMonths } from 'date-fns';
import { useInsights } from 'hooks/api/getters/useInsights/useInsights';
import { usePersistentTableState } from 'hooks/usePersistentTableState';
import type { FC } from 'react';
import { withDefault } from 'use-query-params';
import { FilterItemParam } from 'utils/serializeQueryParams';
import { WidgetTitle } from 'component/insights/components/WidgetTitle/WidgetTitle';
import { UsersChart } from 'component/insights/componentsChart/UsersChart/UsersChart';
import { UsersPerProjectChart } from 'component/insights/componentsChart/UsersPerProjectChart/UsersPerProjectChart';
import { UserStats } from 'component/insights/componentsStat/UserStats/UserStats';
import { useInsightsData } from 'component/insights/hooks/useInsightsData';
import {
StyledChartContainer,
StyledWidget,
StyledWidgetStats,
} from 'component/insights/InsightsCharts.styles';
import { InsightsSection } from 'component/insights/sections/InsightsSection';
import { InsightsFilters } from 'component/insights/InsightsFilters';
export const UserInsights: FC = () => {
const statePrefix = 'users-';
const stateConfig = {
[`${statePrefix}project`]: FilterItemParam,
[`${statePrefix}from`]: withDefault(FilterItemParam, {
values: [format(subMonths(new Date(), 1), 'yyyy-MM-dd')],
operator: 'IS',
}),
[`${statePrefix}to`]: withDefault(FilterItemParam, {
values: [format(new Date(), 'yyyy-MM-dd')],
operator: 'IS',
}),
};
const [state, setState] = usePersistentTableState(
'insights-users',
stateConfig,
['users-from', 'users-to'],
);
const { insights, loading } = useInsights(
state['users-from']?.values[0],
state['users-to']?.values[0],
);
const projects = state['users-project']?.values ?? [allOption.id];
const showAllProjects = projects[0] === allOption.id;
const { summary, groupedProjectsData, userTrends } = useInsightsData(
insights,
projects,
);
const lastUserTrend = userTrends[userTrends.length - 1];
const usersTotal = lastUserTrend?.total ?? 0;
const usersActive = lastUserTrend?.active ?? 0;
const usersInactive = lastUserTrend?.inactive ?? 0;
const isOneProjectSelected = projects.length === 1;
return (
<InsightsSection
title='User insights'
filters={
<InsightsFilters
state={state}
onChange={setState}
filterNamePrefix={statePrefix}
/>
}
>
{showAllProjects ? (
<StyledWidget>
<StyledWidgetStats>
<WidgetTitle title='Total users' />
<UserStats
count={usersTotal}
active={usersActive}
inactive={usersInactive}
isLoading={loading}
/>
</StyledWidgetStats>
<StyledChartContainer>
<UsersChart
userTrends={userTrends}
isLoading={loading}
/>
</StyledChartContainer>
</StyledWidget>
) : (
<StyledWidget>
<StyledWidgetStats>
<WidgetTitle
title={
isOneProjectSelected
? 'Users in project'
: 'Users per project on average'
}
tooltip={
isOneProjectSelected
? 'Number of users in selected projects.'
: 'Average number of users for selected projects.'
}
/>
<UserStats
count={summary.averageUsers}
isLoading={loading}
/>
</StyledWidgetStats>
<StyledChartContainer>
<UsersPerProjectChart
projectFlagTrends={groupedProjectsData}
isLoading={loading}
/>
</StyledChartContainer>
</StyledWidget>
)}
</InsightsSection>
);
};

View File

@ -34,7 +34,7 @@ const usePersistentSearchParams = <T extends QueryParamConfigMap>(
export const usePersistentTableState = <T extends QueryParamConfigMap>(
key: string,
queryParamsDefinition: T,
excludedFromStorage: string[] = ['offset'],
excludedFromStorage: (keyof T)[] = ['offset'],
) => {
const updateStoredParams = usePersistentSearchParams(
key,