Skip to content

Commit

Permalink
fix: onRenderChange callback trigger on resize (#2228)
Browse files Browse the repository at this point in the history
  • Loading branch information
nickofthyme authored Nov 7, 2023
1 parent dafb528 commit be30c1b
Show file tree
Hide file tree
Showing 11 changed files with 157 additions and 21 deletions.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
12 changes: 11 additions & 1 deletion packages/charts/api/charts.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -2353,6 +2353,9 @@ export type RenderChangeListener = (isRendered: boolean) => void;
// @public (undocumented)
export type Rendering = 'canvas' | 'svg';

// @alpha
export type ResizeListener = () => void;

// @public (undocumented)
export type RGB = number;

Expand Down Expand Up @@ -2512,7 +2515,7 @@ export const Settings: (props: SFProps<SettingsSpec, keyof (typeof settingsBuild
// Warning: (ae-forgotten-export) The symbol "BuildProps" needs to be exported by the entry point index.d.ts
//
// @public (undocumented)
export const settingsBuildProps: BuildProps<SettingsSpec, "id" | "chartType" | "specType", "debug" | "locale" | "rotation" | "ariaLabelHeadingLevel" | "ariaUseDefaultSummary" | "legendPosition" | "flatLegend" | "legendMaxDepth" | "legendSize" | "showLegend" | "showLegendExtra" | "baseTheme" | "rendering" | "animateData" | "externalPointerEvents" | "pointBuffer" | "resizeDebounce" | "pointerUpdateTrigger" | "brushAxis" | "minBrushDelta" | "allowBrushingLastHistogramBin", "ariaLabel" | "xDomain" | "ariaDescription" | "ariaDescribedBy" | "ariaLabelledBy" | "ariaTableCaption" | "theme" | "legendAction" | "legendColorPicker" | "legendStrategy" | "onLegendItemClick" | "customLegend" | "onLegendItemMinusClick" | "onLegendItemOut" | "onLegendItemOver" | "onLegendItemPlusClick" | "orderOrdinalBinsBy" | "debugState" | "onProjectionClick" | "onElementClick" | "onElementOver" | "onElementOut" | "onBrushEnd" | "onPointerUpdate" | "onRenderChange" | "onProjectionAreaChange" | "onAnnotationClick" | "pointerUpdateDebounce" | "roundHistogramBrushValues" | "noResults" | "legendSort", never>;
export const settingsBuildProps: BuildProps<SettingsSpec, "id" | "chartType" | "specType", "debug" | "locale" | "rotation" | "ariaLabelHeadingLevel" | "ariaUseDefaultSummary" | "legendPosition" | "flatLegend" | "legendMaxDepth" | "legendSize" | "showLegend" | "showLegendExtra" | "baseTheme" | "rendering" | "animateData" | "externalPointerEvents" | "pointBuffer" | "resizeDebounce" | "pointerUpdateTrigger" | "brushAxis" | "minBrushDelta" | "allowBrushingLastHistogramBin", "ariaLabel" | "xDomain" | "ariaDescription" | "ariaDescribedBy" | "ariaLabelledBy" | "ariaTableCaption" | "theme" | "legendAction" | "legendColorPicker" | "legendStrategy" | "onLegendItemClick" | "customLegend" | "onLegendItemMinusClick" | "onLegendItemOut" | "onLegendItemOver" | "onLegendItemPlusClick" | "orderOrdinalBinsBy" | "debugState" | "onProjectionClick" | "onElementClick" | "onElementOver" | "onElementOut" | "onBrushEnd" | "onPointerUpdate" | "onResize" | "onRenderChange" | "onWillRender" | "onProjectionAreaChange" | "onAnnotationClick" | "pointerUpdateDebounce" | "roundHistogramBrushValues" | "noResults" | "legendSort", never>;

// @public (undocumented)
export type SettingsProps = ComponentProps<typeof Settings>;
Expand Down Expand Up @@ -2555,6 +2558,10 @@ export interface SettingsSpec extends Spec, LegendSpec {
onProjectionClick?: ProjectionClickListener;
// (undocumented)
onRenderChange?: RenderChangeListener;
// @alpha
onResize?: ResizeListener;
// (undocumented)
onWillRender?: WillRenderListener;
orderOrdinalBinsBy?: OrderBy;
pointBuffer: MarkBuffer;
pointerUpdateDebounce?: number;
Expand Down Expand Up @@ -3209,6 +3216,9 @@ export const WeightFn: Readonly<{
// @public (undocumented)
export type WeightFn = $Values<typeof WeightFn>;

// @public
export type WillRenderListener = () => void;

// @alpha
export const Wordcloud: FC<SFProps<WordcloudSpec, "chartType" | "specType", "data" | "fontFamily" | "fontStyle" | "fontWeight" | "padding" | "exponent" | "minFontSize" | "maxFontSize" | "startAngle" | "endAngle" | "angleCount" | "spiral" | "weightFn" | "outOfRoomCallback", never, "id">>;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@ exports[`Chart should render the legend name test 1`] = `
</ChartBackground>
</Connect(ChartBackground)>
<Connect(ChartStatusComponent)>
<ChartStatusComponent chartId="chart1" rendered={true} renderedCount={1} onRenderChange={[undefined]} debugState={{...}} dispatch={[Function: dispatch]}>
<ChartStatusComponent chartId="chart1" rendered={true} renderedCount={1} onWillRender={[undefined]} onRenderChange={[undefined]} debugState={{...}} dispatch={[Function: dispatch]}>
<div className="echChartStatus" data-ech-render-complete={true} data-ech-render-count={1} data-ech-debug-state={{...}} />
</ChartStatusComponent>
</Connect(ChartStatusComponent)>
<Connect(Resizer)>
<Resizer resizeDebounce={10} updateParentDimensions={[Function (anonymous)]}>
<Resizer resizeDebounce={10} onResize={[undefined]} updateParentDimensions={[Function (anonymous)]}>
<div className="echChartResizer" />
</Resizer>
</Connect(Resizer)>
Expand Down
31 changes: 20 additions & 11 deletions packages/charts/src/components/chart_resizer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,24 +11,25 @@ import { connect } from 'react-redux';
import { Dispatch, bindActionCreators } from 'redux';
import ResizeObserver from 'resize-observer-polyfill';

import { DEFAULT_RESIZE_DEBOUNCE } from '../specs/constants';
import { ResizeListener } from '../specs/settings';
import { updateParentDimensions } from '../state/actions/chart_settings';
import { GlobalChartState } from '../state/chart_state';
import { getSettingsSpecSelector } from '../state/selectors/get_settings_spec';
import { isFiniteNumber } from '../utils/common';
import { debounce, DebouncedFunction } from '../utils/debounce';
import { Dimensions } from '../utils/dimensions';

interface ResizerStateProps {
resizeDebounce: number;
onResize?: ResizeListener;
}

interface ResizerDispatchProps {
updateParentDimensions(dimension: Dimensions): void;
updateParentDimensions: typeof updateParentDimensions;
}

type ResizerProps = ResizerStateProps & ResizerDispatchProps;

const DEFAULT_RESIZE_DEBOUNCE = 200;
type ResizeFn = (entries: ResizeObserverEntry[]) => void;

class Resizer extends React.Component<ResizerProps> {
private initialResizeComplete = false;
Expand All @@ -39,10 +40,7 @@ class Resizer extends React.Component<ResizerProps> {

private animationFrameID: number;

private onResizeDebounced?: DebouncedFunction<
[entries: ResizeObserverEntry[]],
(entries: ResizeObserverEntry[]) => void
>;
private onResizeDebounced?: ResizeFn | DebouncedFunction<Parameters<ResizeFn>, ResizeFn>;

constructor(props: ResizerProps) {
super(props);
Expand All @@ -52,18 +50,27 @@ class Resizer extends React.Component<ResizerProps> {
}

componentDidMount() {
this.onResizeDebounced = debounce(this.onResize, this.props.resizeDebounce);
this.setupResizeDebounce();
if (this.containerRef.current) {
this.ro.observe(this.containerRef.current as Element);
}
}

componentDidUpdate({ resizeDebounce }: Readonly<ResizerProps>): void {
if (resizeDebounce !== this.props.resizeDebounce) this.setupResizeDebounce();
}

componentWillUnmount() {
window.cancelAnimationFrame(this.animationFrameID);
this.ro.disconnect();
}

onResize = (entries: ResizeObserverEntry[]) => {
setupResizeDebounce() {
this.onResizeDebounced =
this.props.resizeDebounce > 0 ? debounce(this.onResize, this.props.resizeDebounce) : this.onResize;
}

onResize: ResizeFn = (entries) => {
if (!Array.isArray(entries)) {
return;
}
Expand All @@ -73,6 +80,7 @@ class Resizer extends React.Component<ResizerProps> {
const { width, height } = entries[0].contentRect;
this.animationFrameID = window.requestAnimationFrame(() => {
this.props.updateParentDimensions({ width, height, top: 0, left: 0 });
this.props.onResize?.();
});
};

Expand All @@ -99,9 +107,10 @@ const mapDispatchToProps = (dispatch: Dispatch): ResizerDispatchProps =>
);

const mapStateToProps = (state: GlobalChartState): ResizerStateProps => {
const { resizeDebounce } = getSettingsSpecSelector(state);
const { resizeDebounce, onResize } = getSettingsSpecSelector(state);
return {
resizeDebounce: isFiniteNumber(resizeDebounce) ? resizeDebounce : DEFAULT_RESIZE_DEBOUNCE,
onResize,
};
};

Expand Down
10 changes: 7 additions & 3 deletions packages/charts/src/components/chart_status.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import React from 'react';
import { connect } from 'react-redux';

import { RenderChangeListener } from '../specs';
import { RenderChangeListener, WillRenderListener } from '../specs';
import { GlobalChartState } from '../state/chart_state';
import { globalSelectorCache } from '../state/create_selector';
import { getDebugStateSelector } from '../state/selectors/get_debug_state';
Expand All @@ -21,6 +21,7 @@ interface ChartStatusStateProps {
rendered: boolean;
renderedCount: number;
onRenderChange?: RenderChangeListener;
onWillRender?: WillRenderListener;
debugState: DebugState | null;
}

Expand All @@ -38,7 +39,9 @@ class ChartStatusComponent extends React.Component<ChartStatusStateProps> {
}

dispatchRenderChange = () => {
const { onRenderChange, rendered } = this.props;
const { onWillRender, onRenderChange, rendered } = this.props;
onWillRender?.();

if (onRenderChange) {
window.requestAnimationFrame(() => {
onRenderChange(rendered);
Expand All @@ -61,12 +64,13 @@ class ChartStatusComponent extends React.Component<ChartStatusStateProps> {
}

const mapStateToProps = (state: GlobalChartState): ChartStatusStateProps => {
const { onRenderChange, debugState } = getSettingsSpecSelector(state);
const { onWillRender, onRenderChange, debugState } = getSettingsSpecSelector(state);

return {
chartId: state.chartId,
rendered: state.chartRendered,
renderedCount: state.chartRenderedCount,
onWillRender,
onRenderChange,
debugState: debugState ? getDebugStateSelector(state) : null,
};
Expand Down
5 changes: 4 additions & 1 deletion packages/charts/src/specs/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,9 @@ export const TooltipStickTo = Object.freeze({
/** @public */
export type TooltipStickTo = $Values<typeof TooltipStickTo>;

/** @internal */
export const DEFAULT_RESIZE_DEBOUNCE = 10;

/**
* Default legend config
* @internal
Expand All @@ -151,7 +154,7 @@ export const settingsBuildProps = buildSFProps<SettingsSpec>()(
rendering: 'canvas' as const,
rotation: 0 as const,
animateData: true,
resizeDebounce: 10,
resizeDebounce: DEFAULT_RESIZE_DEBOUNCE,
debug: false,
pointerUpdateTrigger: PointerUpdateTrigger.X,
externalPointerEvents: {
Expand Down
15 changes: 15 additions & 0 deletions packages/charts/src/specs/settings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -205,13 +205,23 @@ export type LegendItemListener = (series: SeriesIdentifier[]) => void;
* @public
*/
export type PointerUpdateListener = (event: PointerEvent) => void;
/**
* Listener to be called when chart resizes
* @alpha
*/
export type ResizeListener = () => void;
/**
* Listener to be called when chart render state changes
*
* `isRendered` value is `true` when rendering is complete and `false` otherwise
* @public
*/
export type RenderChangeListener = (isRendered: boolean) => void;
/**
* Listener to be called *before* chart renders
* @public
*/
export type WillRenderListener = () => void;
/** @public */
export type BasicListener = () => undefined | void;
/** @public */
Expand Down Expand Up @@ -510,7 +520,12 @@ export interface SettingsSpec extends Spec, LegendSpec {
onElementOut?: BasicListener;
onBrushEnd?: BrushEndListener;
onPointerUpdate?: PointerUpdateListener;
/**
* @alpha subject to be removed in the future
*/
onResize?: ResizeListener;
onRenderChange?: RenderChangeListener;
onWillRender?: WillRenderListener;
onProjectionAreaChange?: ProjectionAreaChangeListener;

/**
Expand Down
5 changes: 3 additions & 2 deletions packages/charts/src/state/chart_state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -380,11 +380,11 @@ export const chartStoreReducer = (chartId: string, title?: string, description?:
},
};
case CHART_RENDERED:
const count = state.chartRendered ? state.chartRenderedCount : state.chartRenderedCount + 1;
const chartRenderedCount = state.chartRendered ? state.chartRenderedCount : state.chartRenderedCount + 1;
return {
...state,
chartRendered: true,
chartRenderedCount: count,
chartRenderedCount,
};
case UPDATE_PARENT_DIMENSION:
return {
Expand All @@ -401,6 +401,7 @@ export const chartStoreReducer = (chartId: string, title?: string, description?:
parentDimensions: {
...action.dimensions,
},
chartRendered: false,
};
case UPDATE_CHART_TITLES:
return {
Expand Down
93 changes: 93 additions & 0 deletions storybook/stories/test_cases/11_resize_debounce.story.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/*
* 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 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

import { action } from '@storybook/addon-actions';
import { number } from '@storybook/addon-knobs';
import moment from 'moment';
import React from 'react';

import { Axis, Chart, BarSeries, Position, ScaleType, Settings } from '@elastic/charts';
import { getRandomNumberGenerator } from '@elastic/charts/src/mocks/utils';

import { ChartsStory } from '../../types';
import { useBaseTheme } from '../../use_base_theme';

const rng = getRandomNumberGenerator();

const data: { t: number; values: { v: number; cat: string }[] }[] = [];
const end = moment(1699037055867);
const days = 3;
const maxCardinality = 100;
const start = end.clone().subtract(days, 'days');
const hours = 6;
while (start.isBefore(end)) {
const values = Array.from({ length: maxCardinality }, (_, i) => ({
v: rng(0, 100),
cat: `Category ${i + 1}`,
}));
data.push({ t: start.add(hours, 'hours').valueOf(), values });
}

export const Example: ChartsStory = (_, { title, description }) => {
const resizeDebounce = number('resizeDebounce (ms)', 10, { min: 0, step: 20 });
const cardinality = number('cardinality', 100, { min: 1, max: maxCardinality });
return (
<div
style={{
resize: 'both',
padding: '0px',
overflow: 'auto',
height: '100%',
width: '100%',
maxWidth: '100%',
maxHeight: '100vh',
}}
>
<Chart title={title} description={description}>
<Settings
showLegend
resizeDebounce={resizeDebounce}
onResize={action('onResize')}
onRenderChange={action('onRenderChange')}
baseTheme={useBaseTheme()}
/>
<Axis
id="bottom"
position={Position.Bottom}
style={{
tickLine: { visible: true, size: 0.0001, padding: 4 },
tickLabel: {
alignment: { horizontal: Position.Left, vertical: Position.Bottom },
padding: 0,
offset: { x: 0, y: 0 },
},
}}
timeAxisLayerCount={3}
/>
<Axis id="left" position={Position.Left} />

<BarSeries
id="Sensor 1"
enableHistogramMode
xScaleType={ScaleType.Time}
yScaleType={ScaleType.Linear}
xAccessor="t"
yAccessors={['v']}
splitSeriesAccessors={['cat']}
stackAccessors={['yes']}
data={data.flatMap(({ t, values }) => values.slice(0, cardinality).map(({ v, cat }) => ({ t, v, cat })))}
/>
</Chart>
</div>
);
};

Example.parameters = {
markdown: `The \`resizeDebounce\` option on the \`Settings\` spec provides control over the eagerness of the chart to re-render upon resize. A value of \`0\` will remove the debounce altogether.
You can play with the cardinality and debounce time to see how the debouncing affects the chart render timing`,
};
3 changes: 2 additions & 1 deletion storybook/stories/test_cases/test_cases.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,5 @@ export { Example as accessibilityCustomizations } from './6_a11y_custom_descript
export { Example as rtlText } from './7_rtl_text.story';
export { Example as testPointsOutsideOfDomain } from './8_test_points_outside_of_domain.story';
export { Example as duplicateLabelsInPartitionLegend } from './9_duplicate_labels_in_partition_legend.story';
export { Example as highlighterZIndex } from './20_highlighter_z_index.story';
export { Example as highlighterZIndex } from './10_highlighter_z_index.story';
export { Example as resizeDebounce } from './11_resize_debounce.story';

0 comments on commit be30c1b

Please sign in to comment.