Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor usage of sparkline chart styles #179503

Merged
merged 15 commits into from
Apr 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/plugins/charts/public/mocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import { activeCursorMock } from './services/active_cursor/mock';
import { colorsServiceMock } from './services/legacy_colors/mock';
import { getPaletteRegistry, paletteServiceMock } from './services/palettes/mock';

export { MOCK_SPARKLINE_THEME } from './services/theme/mock';

export type Setup = jest.Mocked<ReturnType<ChartsPlugin['setup']>>;
export type Start = jest.Mocked<ReturnType<ChartsPlugin['start']>>;

Expand Down
20 changes: 19 additions & 1 deletion src/plugins/charts/public/services/theme/mock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,26 @@
* Side Public License, v 1.
*/

import { LIGHT_THEME } from '@elastic/charts';
import { LIGHT_THEME, PartialTheme } from '@elastic/charts';
import { ThemeService } from './theme';

export const MOCK_SPARKLINE_THEME: PartialTheme = {
lineSeriesStyle: {
point: {
visible: false,
strokeWidth: 1,
radius: 1,
},
},
areaSeriesStyle: {
point: {
visible: false,
strokeWidth: 1,
radius: 1,
},
},
};

export const themeServiceMock: ThemeService = {
chartsDefaultBaseTheme: LIGHT_THEME,
chartsBaseTheme$: jest.fn(() => ({
Expand All @@ -19,4 +36,5 @@ export const themeServiceMock: ThemeService = {
})),
useDarkMode: jest.fn().mockReturnValue(false),
useChartsBaseTheme: jest.fn().mockReturnValue(LIGHT_THEME),
useSparklineOverrides: jest.fn().mockReturnValue(MOCK_SPARKLINE_THEME),
} as any;
30 changes: 29 additions & 1 deletion src/plugins/charts/public/services/theme/theme.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,30 @@ export class ThemeService {
return {};
};

/**
* A react hook to return shared sparkline chart overrides
*
* Replacement for `EUI_SPARKLINE_THEME_PARTIAL`
*/
public useSparklineOverrides = (): PartialTheme => {
return {
lineSeriesStyle: {
point: {
visible: false,
strokeWidth: 1,
radius: 1,
},
},
areaSeriesStyle: {
point: {
visible: false,
strokeWidth: 1,
radius: 1,
},
},
};
};

/** A React hook for consuming the charts theme */
public useChartsBaseTheme = (): Theme => {
const [value, update] = useState(this._chartsBaseTheme$.getValue());
Expand All @@ -70,7 +94,11 @@ export class ThemeService {
return value;
};

/** initialize service with uiSettings */
/**
* Initialize theme service with dark mode
*
* Meant to be called by charts plugin setup method
*/
public init(theme: CoreSetup['theme']) {
this.theme$ = theme.theme$;
this.theme$.subscribe(({ darkMode }) => {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import { useKibanaContextForPlugin } from './use_kibana';

export const useChartThemes = () => {
const { services } = useKibanaContextForPlugin();

return {
baseTheme: services.charts.theme.useChartsBaseTheme(),
sparklineTheme: services.charts.theme.useSparklineOverrides(),
};
};
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,11 @@
*/

import React, { useMemo } from 'react';
import {
Chart,
Settings,
AreaSeries,
ScaleType,
TooltipType,
Tooltip,
LIGHT_THEME,
DARK_THEME,
} from '@elastic/charts';
import { EUI_SPARKLINE_THEME_PARTIAL } from '@elastic/eui/dist/eui_charts_theme';
import { Chart, Settings, AreaSeries, ScaleType, TooltipType, Tooltip } from '@elastic/charts';
import { i18n } from '@kbn/i18n';
import { useIsDarkMode } from '../../../../../hooks/use_is_dark_mode';
import { useKibanaTimeZoneSetting } from '../../../../../hooks/use_kibana_time_zone_setting';
import { TimeRange } from '../../../../../../common/time';
import { useChartThemes } from '../../../../../hooks/use_chart_themes';

interface TimeSeriesPoint {
timestamp: number;
Expand All @@ -38,9 +28,8 @@ export const SingleMetricSparkline: React.FunctionComponent<{
metric: TimeSeriesPoint[];
timeRange: TimeRange;
}> = ({ metric, timeRange }) => {
const isDarkMode = useIsDarkMode();
const timeZone = useKibanaTimeZoneSetting();
const baseTheme = useMemo(() => (isDarkMode ? DARK_THEME : LIGHT_THEME), [isDarkMode]);
const { baseTheme, sparklineTheme } = useChartThemes();

const xDomain = useMemo(
() => ({
Expand All @@ -55,7 +44,7 @@ export const SingleMetricSparkline: React.FunctionComponent<{
<Tooltip type={TooltipType.None} />
<Settings
showLegend={false}
theme={EUI_SPARKLINE_THEME_PARTIAL}
theme={sparklineTheme}
baseTheme={baseTheme}
xDomain={xDomain}
locale={i18n.getLocale()}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import { useKibana } from '../utils/kibana_react';

export const useChartThemes = () => {
const { charts } = useKibana().services;

return {
baseTheme: charts.theme.useChartsBaseTheme(),
sparklineTheme: charts.theme.useSparklineOverrides(),
};
};
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,14 @@
* 2.0.
*/

import {
Chart,
Settings,
AreaSeries,
TooltipType,
Tooltip,
LIGHT_THEME,
DARK_THEME,
} from '@elastic/charts';
import { Chart, Settings, AreaSeries, TooltipType, Tooltip } from '@elastic/charts';
import { EuiFlexItem, EuiFlexGroup, EuiIcon, EuiTextColor } from '@elastic/eui';
import React, { useContext } from 'react';
import React from 'react';
import { FormattedMessage } from '@kbn/i18n-react';
import { EUI_SPARKLINE_THEME_PARTIAL } from '@elastic/eui/dist/eui_charts_theme';
import { ThemeContext } from 'styled-components';

import { i18n } from '@kbn/i18n';
import { NumberOrNull } from '../../../../..';
import { useChartThemes } from '../../../../../hooks/use_chart_themes';

interface Props {
id: string;
Expand All @@ -31,11 +22,7 @@ interface Props {
color: number;
}
export function MetricWithSparkline({ id, formatter, value, timeseries, color }: Props) {
const themeCTX = useContext(ThemeContext);
const isDarkTheme = (themeCTX && themeCTX.darkMode) || false;
const theme = [EUI_SPARKLINE_THEME_PARTIAL];
const baseTheme = isDarkTheme ? DARK_THEME : LIGHT_THEME;

const { baseTheme, sparklineTheme } = useChartThemes();
nickofthyme marked this conversation as resolved.
Show resolved Hide resolved
const colors = baseTheme.colors?.vizColors ?? [];

if (!value) {
Expand All @@ -57,7 +44,7 @@ export function MetricWithSparkline({ id, formatter, value, timeseries, color }:
<Tooltip type={TooltipType.None} />
<Settings
baseTheme={baseTheme}
theme={theme}
theme={sparklineTheme}
showLegend={false}
locale={i18n.getLocale()}
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ const ALERTS_TABLE_ID = 'xpack.observability.overview.alert.table';

export function OverviewPage() {
const {
charts,
http,
triggersActionsUi: {
alertsTableConfigurationRegistry,
Expand Down Expand Up @@ -103,10 +102,6 @@ export function OverviewPage() {
[bucketSize, relativeEnd, relativeStart]
);

const chartProps = {
baseTheme: charts.theme.useChartsBaseTheme(),
};

useEffect(() => {
setEsQuery(
buildEsQuery({
Expand Down Expand Up @@ -184,7 +179,6 @@ export function OverviewPage() {
hasError={false}
>
<AlertSummaryWidget
chartProps={chartProps}
featureIds={observabilityAlertFeatureIds}
filter={esQuery}
fullSize
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,6 @@ interface RuleDetailsPathParams {
export function RuleDetailsPage() {
const {
application: { capabilities, navigateToUrl },
charts: {
theme: { useChartsBaseTheme },
},
http: { basePath },
share: {
url: { locators },
Expand All @@ -69,9 +66,6 @@ export function RuleDetailsPage() {

const { ruleId } = useParams<RuleDetailsPathParams>();
const { search } = useLocation();

const baseTheme = useChartsBaseTheme();

const { rule, isLoading, isError, refetch } = useFetchRule({ ruleId });
const filteredRuleTypes = useGetFilteredRuleTypes();
const { ruleTypes } = useFetchRuleTypes({
Expand Down Expand Up @@ -233,7 +227,6 @@ export function RuleDetailsPage() {

<EuiFlexItem style={{ minWidth: 350 }}>
<AlertSummaryWidget
chartProps={{ baseTheme }}
featureIds={featureIds}
onClick={handleAlertSummaryWidgetClick}
timeRange={alertSummaryWidgetTimeRange}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ export function SloAlertsSummary({
showAllGroupByInstances,
}: Props) {
const {
charts,
triggersActionsUi: { getAlertSummaryWidget: AlertSummaryWidget },
} = deps;

Expand Down Expand Up @@ -64,16 +63,11 @@ export function SloAlertsSummary({
[timeRange.from, timeRange.to, bucketSize]
);

const chartProps = {
theme: charts.theme.useChartsTheme(),
baseTheme: charts.theme.useChartsBaseTheme(),
};
return (
<AlertSummaryWidget
featureIds={observabilityAlertFeatureIds}
filter={esQuery}
timeRange={alertSummaryTimeRange}
chartProps={chartProps}
fullSize
onLoaded={() => {
if (onLoaded) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ import {
} from '@elastic/charts';
import React from 'react';
import { EuiLoadingChart, useEuiTheme } from '@elastic/eui';
import { EUI_SPARKLINE_THEME_PARTIAL } from '@elastic/eui/dist/eui_charts_theme';

import { i18n } from '@kbn/i18n';
import { useKibana } from '../../../utils/kibana_react';
Expand All @@ -42,6 +41,7 @@ export interface Props {
export function SloSparkline({ chart, data, id, isLoading, size, state }: Props) {
const charts = useKibana().services.charts;
const baseTheme = charts.theme.useChartsBaseTheme();
const sparklineTheme = charts.theme.useSparklineOverrides();

const { euiTheme } = useEuiTheme();

Expand All @@ -60,7 +60,7 @@ export function SloSparkline({ chart, data, id, isLoading, size, state }: Props)
<Settings
baseTheme={baseTheme}
showLegend={false}
theme={[EUI_SPARKLINE_THEME_PARTIAL]}
theme={sparklineTheme}
locale={i18n.getLocale()}
/>
<Tooltip type={TooltipType.None} />
Expand Down
22 changes: 22 additions & 0 deletions x-pack/plugins/triggers_actions_ui/.storybook/decorator.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { KibanaThemeProvider, KibanaServices } from '@kbn/kibana-react-plugin/pu
import { EuiThemeProvider } from '@kbn/kibana-react-plugin/common';
import type { NotificationsStart, ApplicationStart } from '@kbn/core/public';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { DARK_THEME, LIGHT_THEME } from '@elastic/charts';
import { KibanaContextProvider } from '../public/common/lib/kibana';
import { ExperimentalFeaturesService } from '../public/common/experimental_features_service';
import { getHttp } from './context/http';
Expand Down Expand Up @@ -92,6 +93,27 @@ export const StorybookContextDecorator: React.FC<StorybookContextDecoratorProps>
http: getHttp(context),
actionTypeRegistry: getActionTypeRegistry(),
ruleTypeRegistry: getRuleTypeRegistry(),
charts: {
theme: {
useChartsBaseTheme: () => (darkMode ? DARK_THEME : LIGHT_THEME),
useSparklineOverrides: () => ({
lineSeriesStyle: {
point: {
visible: false,
strokeWidth: 1,
radius: 1,
},
},
areaSeriesStyle: {
point: {
visible: false,
strokeWidth: 1,
radius: 1,
},
},
}),
},
},
...servicesOverride,
}}
>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
* 2.0.
*/

import { LIGHT_THEME } from '@elastic/charts';
import { AlertSummaryTimeRange, ChartProps } from '../../sections/alert_summary_widget/types';

export const mockedAlertSummaryResponse = {
Expand Down Expand Up @@ -38,6 +37,4 @@ export const mockedAlertSummaryTimeRange: AlertSummaryTimeRange = {
title: 'mockedTitle',
};

export const mockedChartProps: ChartProps = {
baseTheme: LIGHT_THEME,
};
export const mockedChartProps: ChartProps = {};
Loading