Skip to content

feat(specs): Provide the specs as JSON instead of react components #2650

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

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
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
17 changes: 15 additions & 2 deletions packages/charts/src/chart_types/xy_chart/specs/area_series.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,23 @@ export const AreaSeries = function <D extends BaseDatum = Datum>(
keyof (typeof buildProps)['requires']
>,
) {
const { defaults, overrides } = buildProps;
useSpecFactory<AreaSeriesSpec<D>>({ ...defaults, ...stripUndefined(props), ...overrides });
useSpecFactory<AreaSeriesSpec<D>>(getAreaSeriesSpec(props));
return null;
};

/** @public */
export type AreaSeriesProps = ComponentProps<typeof AreaSeries>;

/** @internal */
export function getAreaSeriesSpec<D extends BaseDatum = Datum>(
props: SFProps<
AreaSeriesSpec<D>,
keyof (typeof buildProps)['overrides'],
keyof (typeof buildProps)['defaults'],
keyof (typeof buildProps)['optionals'],
keyof (typeof buildProps)['requires']
>,
) {
const { defaults, overrides } = buildProps;
return { ...defaults, ...stripUndefined(props), ...overrides };
}
41 changes: 33 additions & 8 deletions packages/charts/src/chart_types/xy_chart/specs/axis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,13 @@ import type { ComponentProps } from 'react';

import { ChartType } from '../..';
import { SpecType } from '../../../specs/spec_type'; // kept as long-winded import on separate line otherwise import circularity emerges
import { specComponentFactory } from '../../../state/spec_factory';
import { Position } from '../../../utils/common';
import type { SFProps } from '../../../state/spec_factory';
import { buildSFProps, useSpecFactory } from '../../../state/spec_factory';
import { Position, stripUndefined } from '../../../utils/common';
import type { AxisSpec } from '../utils/specs';
import { DEFAULT_GLOBAL_ID } from '../utils/specs';

/**
* Add axis spec to chart
* @public
*/
export const Axis = specComponentFactory<AxisSpec>()(
const buildProps = buildSFProps<AxisSpec>()(
{
chartType: ChartType.XYAxis,
specType: SpecType.Axis,
Expand All @@ -34,5 +31,33 @@ export const Axis = specComponentFactory<AxisSpec>()(
},
);

/** @public */
/** @internal */
export const Axis = function (
props: SFProps<
AxisSpec,
keyof (typeof buildProps)['overrides'],
keyof (typeof buildProps)['defaults'],
keyof (typeof buildProps)['optionals'],
keyof (typeof buildProps)['requires']
>,
) {
useSpecFactory<AxisSpec>(getAxisSpec(props));
return null;
};

/** @internal */
export type AxisProps = ComponentProps<typeof Axis>;

/** @internal */
export function getAxisSpec(
props: SFProps<
AxisSpec,
keyof (typeof buildProps)['overrides'],
keyof (typeof buildProps)['defaults'],
keyof (typeof buildProps)['optionals'],
keyof (typeof buildProps)['requires']
>,
): AxisSpec {
const { defaults, overrides } = buildProps;
return { ...defaults, ...stripUndefined(props), ...overrides };
}
49 changes: 21 additions & 28 deletions packages/charts/src/components/chart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@
*/

import classNames from 'classnames';
import type { CSSProperties, ReactNode } from 'react';
import type { CSSProperties } from 'react';
import React, { createRef } from 'react';
import { Provider } from 'react-redux';
import type { Unsubscribe, Store } from 'redux';
import type { Store } from 'redux';
import type { OptionalKeys } from 'utility-types';
import { v4 as uuidv4 } from 'uuid';

Expand All @@ -23,18 +23,17 @@ import { getElementZIndex } from './portal/utils';
import { chartTypeSelectors } from '../chart_types/chart_type_selectors';
import { Colors } from '../common/colors';
import type { LegendPositionConfig, PointerEvent } from '../specs';
import type { Spec } from '../specs/spec_type';
import { SpecsParser } from '../specs/specs_parser';
import { updateChartTitles, updateParentDimensions } from '../state/actions/chart_settings';
import { onExternalPointerEvent } from '../state/actions/events';
import { specParsed, upsertSpec } from '../state/actions/specs';
import { onComputedZIndex } from '../state/actions/z_index';
import { createChartStore, type GlobalChartState } from '../state/chart_state';
import { getChartContainerUpdateStateSelector } from '../state/selectors/chart_container_updates';
import { getInternalChartStateSelector, chartSelectorsRegistry } from '../state/selectors/get_internal_chart_state';
import { getInternalIsInitializedSelector, InitStatus } from '../state/selectors/get_internal_is_intialized';
import { chartSelectorsRegistry } from '../state/selectors/get_internal_chart_state';
import type { ChartSize } from '../utils/chart_size';
import { getChartSize, getFixedChartSize } from '../utils/chart_size';
import { LayoutDirection } from '../utils/common';
import { deepEqual } from '../utils/fast_deep_equal';
import { LIGHT_THEME } from '../utils/themes/light_theme';

/** @public */
Expand All @@ -49,7 +48,7 @@ export interface ChartProps {
id?: string;
title?: string;
description?: string;
children?: ReactNode;
config?: Spec[];
}

interface ChartState {
Expand All @@ -65,8 +64,6 @@ export class Chart extends React.Component<ChartProps, ChartState> {
renderer: 'canvas',
};

private unsubscribeToStore: Unsubscribe;

private chartStore: Store<GlobalChartState>;

private chartContainerRef: React.RefObject<HTMLDivElement>;
Expand All @@ -90,31 +87,20 @@ export class Chart extends React.Component<ChartProps, ChartState> {
paddingRight: LIGHT_THEME.chartMargins.right,
displayTitles: true,
};
this.unsubscribeToStore = this.chartStore.subscribe(() => {
const state = this.chartStore.getState();
const internalChartState = getInternalChartStateSelector(state);
if (getInternalIsInitializedSelector(state) !== InitStatus.Initialized) {
return;
}

const newState = getChartContainerUpdateStateSelector(state);
if (!deepEqual(this.state, newState)) this.setState(newState);

if (internalChartState) {
internalChartState.eventCallbacks(state);
}
});
}

componentDidMount() {
if (this.chartContainerRef.current) {
const zIndex = getElementZIndex(this.chartContainerRef.current, document.body);
this.chartStore.dispatch(onComputedZIndex(zIndex));
}
}

componentWillUnmount() {
this.unsubscribeToStore();
if (this.props.config) {
for (const spec of this.props.config) {
// align specs with default
this.chartStore.dispatch(upsertSpec(spec));
}
this.chartStore.dispatch(specParsed());
}
}

componentDidUpdate({ title, description, size }: Readonly<ChartProps>) {
Expand All @@ -127,6 +113,13 @@ export class Chart extends React.Component<ChartProps, ChartState> {
if (newChartSize && (newChartSize.width !== prevChartSize.width || newChartSize.height !== prevChartSize.height)) {
this.chartStore.dispatch(updateParentDimensions({ ...newChartSize, top: 0, left: 0 }));
}
if (this.props.config) {
for (const spec of this.props.config) {
// align specs with default
this.chartStore.dispatch(upsertSpec(spec));
}
this.chartStore.dispatch(specParsed());
}
}

getPNGSnapshot(
Expand Down Expand Up @@ -187,7 +180,7 @@ export class Chart extends React.Component<ChartProps, ChartState> {
<ChartStatus />
<ChartResizer />
<Legend />
<SpecsParser>{this.props.children}</SpecsParser>
{(this.props.config ?? []).length === 0 && <SpecsParser>{this.props.children}</SpecsParser>}
<div className="echContainer" ref={this.chartContainerRef}>
<ChartContainer getChartContainerRef={this.getChartContainerRef} forwardStageRef={this.chartStageRef} />
</div>
Expand Down
2 changes: 2 additions & 0 deletions packages/charts/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,8 @@ export { LEGACY_LIGHT_THEME } from './utils/themes/legacy_light_theme';
export { LEGACY_DARK_THEME } from './utils/themes/legacy_dark_theme';
export { AMSTERDAM_LIGHT_THEME } from './utils/themes/amsterdam_light_theme';
export { AMSTERDAM_DARK_THEME } from './utils/themes/amsterdam_dark_theme';
export { getAreaSeriesSpec } from './chart_types/xy_chart/specs/area_series';
export { getAxisSpec } from './chart_types/xy_chart/specs/axis';

// wordcloud
export { WordcloudViewModel } from './chart_types/wordcloud/layout/types/viewmodel_types';
Expand Down
17 changes: 15 additions & 2 deletions packages/charts/src/specs/settings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -632,8 +632,7 @@ export const Settings = function (
keyof (typeof settingsBuildProps)['requires']
>,
) {
const { defaults, overrides } = settingsBuildProps;
useSpecFactory<SettingsSpec>({ ...defaults, ...stripUndefined(props), ...overrides });
useSpecFactory<SettingsSpec>(getSettingsSpec(props));
return null;
};

Expand All @@ -649,3 +648,17 @@ export function isPointerOutEvent(event: PointerEvent | null | undefined): event
export function isPointerOverEvent(event: PointerEvent | null | undefined): event is PointerOverEvent {
return event?.type === PointerEventType.Over;
}

/** @internal */
export function getSettingsSpec(
props: SFProps<
SettingsSpec,
keyof (typeof settingsBuildProps)['overrides'],
keyof (typeof settingsBuildProps)['defaults'],
keyof (typeof settingsBuildProps)['optionals'],
keyof (typeof settingsBuildProps)['requires']
>,
): SettingsSpec {
const { defaults, overrides } = settingsBuildProps;
return { ...defaults, ...stripUndefined(props), ...overrides };
}
27 changes: 20 additions & 7 deletions packages/charts/src/specs/tooltip.ts
Original file line number Diff line number Diff line change
Expand Up @@ -289,13 +289,7 @@ export const Tooltip = function <D extends BaseDatum = Datum, SI extends SeriesI
keyof (typeof tooltipBuildProps)['requires']
>,
) {
const { defaults, overrides } = tooltipBuildProps;
// @ts-ignore - default generic value
useSpecFactory<TooltipSpec<D, SI>>({
...defaults,
...stripUndefined(props),
...overrides,
});
useSpecFactory(getTooltipSpec(props));
return null;
};

Expand All @@ -310,3 +304,22 @@ export type TooltipProps<D extends BaseDatum = Datum, SI extends SeriesIdentifie
keyof (typeof tooltipBuildProps)['optionals'],
keyof (typeof tooltipBuildProps)['requires']
>;

/** @internal */
export function getTooltipSpec<D extends BaseDatum = Datum, SI extends SeriesIdentifier = SeriesIdentifier>(
props: SFProps<
TooltipSpec<D, SI>,
keyof (typeof tooltipBuildProps)['overrides'],
keyof (typeof tooltipBuildProps)['defaults'],
keyof (typeof tooltipBuildProps)['optionals'],
keyof (typeof tooltipBuildProps)['requires']
>,
): TooltipSpec<D, SI> {
const { defaults, overrides } = tooltipBuildProps;
// @ts-ignore - default generic value
return {
...defaults,
...stripUndefined(props),
...overrides,
};
}
21 changes: 19 additions & 2 deletions packages/charts/src/state/chart_state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
*/

import type { ActionReducerMapBuilder } from '@reduxjs/toolkit';
import { configureStore, createSlice } from '@reduxjs/toolkit';
import { configureStore, createListenerMiddleware, createSlice } from '@reduxjs/toolkit';

import { onChartRendered } from './actions/chart';
import { updateParentDimensions, updateChartTitles } from './actions/chart_settings';
Expand All @@ -24,6 +24,8 @@ import {
handleDOMElementActions,
handleTooltipActions,
} from './reducers/interactions';
import { getInternalChartStateSelector } from './selectors/get_internal_chart_state';
import { getInternalIsInitializedSelector, InitStatus } from './selectors/get_internal_is_intialized';
import { getInitialPointerState } from './utils/get_initial_pointer_state';
import { getInitialTooltipState } from './utils/get_initial_tooltip_state';
import type { Color } from '../common/colors';
Expand Down Expand Up @@ -165,6 +167,21 @@ const createChartSlice = (initialState: ChartSliceState) =>
},
});

// provides a middleware to send events to callbacks
const callbackListenerMiddleware = createListenerMiddleware<ChartSliceState>();
callbackListenerMiddleware.startListening({
predicate: (_, currentState) => {
return getInternalIsInitializedSelector(currentState) === InitStatus.Initialized;
},
effect: (_, listenerApi) => {
const state = listenerApi.getOriginalState();
const internalChartState = getInternalChartStateSelector(state);
if (internalChartState) {
internalChartState.eventCallbacks(state);
}
},
});

/** @internal */
export const createChartStore = (chartId: string, title?: string, description?: string) => {
const initialState = getInitialState(chartId, title, description);
Expand All @@ -175,7 +192,7 @@ export const createChartStore = (chartId: string, title?: string, description?:
getDefaultMiddleware({
// TODO https://github.com/elastic/elastic-charts/issues/2078
serializableCheck: false,
}),
}).prepend(callbackListenerMiddleware.middleware),
});
};

Expand Down
30 changes: 18 additions & 12 deletions storybook/stories/area/1_basic.story.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

import React from 'react';

import { AreaSeries, Chart, ScaleType, Settings } from '@elastic/charts';
import { Chart, ScaleType, getAreaSeriesSpec, getSettingsSpec } from '@elastic/charts';
import { KIBANA_METRICS } from '@elastic/charts/src/utils/data_samples/test_dataset_kibana';

import type { ChartsStory } from '../../types';
Expand All @@ -17,16 +17,22 @@ import { useBaseTheme } from '../../use_base_theme';
export const Example: ChartsStory = (_, { title, description }) => {
const { data } = KIBANA_METRICS.metrics.kibana_os_load.v1;
return (
<Chart title={title} description={description}>
<Settings baseTheme={useBaseTheme()} />
<AreaSeries
id="area"
xScaleType={ScaleType.Time}
yScaleType={ScaleType.Linear}
xAccessor={0}
yAccessors={[1]}
data={data}
/>
</Chart>
<Chart
title={title}
description={description}
config={[
getSettingsSpec({
baseTheme: useBaseTheme(),
}),
getAreaSeriesSpec({
id: 'area',
xScaleType: ScaleType.Time,
yScaleType: ScaleType.Linear,
xAccessor: 0,
yAccessors: [1],
data,
}),
]}
></Chart>
);
};
Loading