Skip to content

Commit

Permalink
feat(flame): expose search field text and search text change listener (
Browse files Browse the repository at this point in the history
…#2068)

This commit exposes the search text as a prop in the Flame component.
It also exposes a listener onSearchTextChange that is called whenever a change in the search text input provided by the chart happens. It always calls the function with a string, even if the clean button is clicked. There is no difference between passing an empty string or clearing the input, both of these actions result in cleaning the search and the API is anyway cleaner and doesn't need a union type.
  • Loading branch information
markov00 authored Jun 23, 2023
1 parent 69a655f commit c339947
Show file tree
Hide file tree
Showing 6 changed files with 51 additions and 15 deletions.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
9 changes: 9 additions & 0 deletions e2e/tests/flame_stories.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,13 @@ test.describe('Flame stories', () => {
},
);
});
test('should focus on searched terms', async ({ page }) => {
await common.expectChartAtUrlToMatchScreenshot(page)(
`http://localhost:9001/?path=/story/flame-alpha--cpu-profile-g-l-flame-chart&globals=theme:light&knob-Text%20to%20search=gotype`,
{
// replace this with render count selector when render count fixed
delay: 300, // wait for tweening and blinking to finish
},
);
});
});
8 changes: 7 additions & 1 deletion packages/charts/api/charts.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -1066,7 +1066,7 @@ export type FitConfig = {
};

// @public
export const Flame: <D extends BaseDatum = any>(props: SFProps<FlameSpec<D>, "chartType" | "specType", "animation" | "valueFormatter" | "valueGetter" | "valueAccessor", never, "id" | "columnarData" | "controlProviderCallback">) => null;
export const Flame: <D extends BaseDatum = any>(props: SFProps<FlameSpec<D>, "chartType" | "specType", "animation" | "valueFormatter" | "valueGetter" | "valueAccessor", "search" | "onSearchTextChange", "id" | "columnarData" | "controlProviderCallback">) => null;

// @public (undocumented)
export type FlameElementEvent = FlameLayerValue;
Expand Down Expand Up @@ -1110,6 +1110,12 @@ export interface FlameSpec<D extends BaseDatum = Datum> extends Spec, LegacyAnim
// (undocumented)
controlProviderCallback: Partial<ControlReceiverCallbacks>;
// (undocumented)
onSearchTextChange?: (text: string) => void;
// (undocumented)
search?: {
text: string;
};
// (undocumented)
specType: typeof SpecType.Series;
// (undocumented)
valueAccessor: ValueAccessor<D>;
Expand Down
2 changes: 2 additions & 0 deletions packages/charts/src/chart_types/flame_chart/flame_api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,8 @@ export interface FlameSpec<D extends BaseDatum = Datum> extends Spec, LegacyAnim
valueAccessor: ValueAccessor<D>;
valueFormatter: ValueFormatter;
valueGetter: (datumIndex: number) => number;
search?: { text: string };
onSearchTextChange?: (text: string) => void;
}

const buildProps = buildSFProps<FlameSpec>()(
Expand Down
24 changes: 22 additions & 2 deletions packages/charts/src/chart_types/flame_chart/flame_chart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,8 @@ interface StateProps {
a11ySettings: ReturnType<typeof getA11ySettingsSelector>;
tooltipRequired: boolean;
canPinTooltip: boolean;
search: NonNullable<FlameSpec['search']>;
onSeachTextChange: (text: string) => void;
onElementOver: NonNullable<SettingsSpec['onElementOver']>;
onElementClick: NonNullable<SettingsSpec['onElementClick']>;
onElementOut: NonNullable<SettingsSpec['onElementOut']>;
Expand Down Expand Up @@ -248,6 +250,7 @@ class FlameComponent extends React.Component<FlameProps> {
throw new Error('flame error: Mismatch between position1 (xy) and label length');

this.targetFocus = this.getFocusOnRoot();

this.bindControls();
this.currentFocus = { ...this.targetFocus };

Expand Down Expand Up @@ -384,6 +387,12 @@ class FlameComponent extends React.Component<FlameProps> {
* so we could use a couple of ! non-null assertions but no big plus
*/
this.tryCanvasContext();

if (this.props.search.text.length > 0 && this.searchInputRef.current) {
this.searchInputRef.current.value = this.props.search.text;
this.searchForText(false);
}

this.drawCanvas();
this.props.onChartRendered();
this.setupDevicePixelRatioChangeListener();
Expand All @@ -403,12 +412,17 @@ class FlameComponent extends React.Component<FlameProps> {
return this.props.chartDimensions.height !== height || this.props.chartDimensions.width !== width;
}

componentDidUpdate = ({ chartDimensions }: FlameProps) => {
componentDidUpdate = ({ chartDimensions, search }: FlameProps) => {
if (!this.ctx) this.tryCanvasContext();
if (this.tooltipPinned && this.chartDimensionsChanged(chartDimensions)) {
this.unpinTooltip();
}
this.bindControls();
if (search.text !== this.props.search.text && this.searchInputRef.current) {
this.searchInputRef.current.value = this.props.search.text;
this.searchForText(false);
}

this.ensureTextureAndDraw();

// eg. due to chartDimensions (parentDimensions) change
Expand Down Expand Up @@ -993,7 +1007,10 @@ class FlameComponent extends React.Component<FlameProps> {
placeholder="Search string"
onKeyPress={this.handleSearchFieldKeyPress}
onKeyUp={this.handleEscapeKey}
onChange={() => this.searchForText(false)}
onChange={(e) => {
this.searchForText(false);
this.props.onSeachTextChange(e.currentTarget.value);
}}
style={{
border: 'none',
padding: 3,
Expand Down Expand Up @@ -1022,6 +1039,7 @@ class FlameComponent extends React.Component<FlameProps> {
onClick={() => {
if (this.currentSearchString && this.searchInputRef.current) {
this.clearSearchText();
this.props.onSeachTextChange('');
}
}}
style={{ display: 'none' }}
Expand Down Expand Up @@ -1358,6 +1376,8 @@ const mapStateToProps = (state: GlobalChartState): StateProps => {
a11ySettings: getA11ySettingsSelector(state),
tooltipRequired: tooltipSpec.type !== TooltipType.None,
canPinTooltip: isPinnableTooltip(state),
search: flameSpec?.search ?? { text: '' },
onSeachTextChange: flameSpec?.onSearchTextChange ?? (() => {}),
// mandatory charts API protocol; todo extract these mappings once there are other charts like Flame
onElementOver: settingsSpec.onElementOver ?? (() => {}),
onElementClick: settingsSpec.onElementClick ?? (() => {}),
Expand Down
23 changes: 11 additions & 12 deletions storybook/stories/icicle/04_cpu_profile_gl_flame.story.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

import { action } from '@storybook/addon-actions';
import { boolean, button, text } from '@storybook/addon-knobs';
import React from 'react';
import React, { useState, useEffect } from 'react';

import {
Chart,
Expand All @@ -26,9 +26,6 @@ import { getRandomNumberGenerator } from '@elastic/charts/src/mocks/utils';
import { ChartsStory } from '../../types';
import { useBaseTheme } from '../../use_base_theme';

const position = new Float32Array(columnarMock.position);
const size = new Float32Array(columnarMock.size);

const rng = getRandomNumberGenerator();

const paletteColorBrewerCat12 = [
Expand All @@ -46,16 +43,19 @@ const paletteColorBrewerCat12 = [
[255, 237, 111],
];

const position = new Float32Array(columnarMock.position);
const size = new Float32Array(columnarMock.size);

const columnarData: ColumnarViewModel = {
label: columnarMock.label.map((index: number) => columnarMock.dictionary[index]), // reversing the dictionary encoding
value: new Float64Array(columnarMock.value),
// color: new Float32Array((columnarMock.color.match(/.{2}/g) ?? []).map((hex: string) => Number.parseInt(hex, 16) / 255)),
color: new Float32Array(
columnarMock.label.flatMap(() => [...paletteColorBrewerCat12[rng(0, 11)].map((c) => c / 255), 1]),
),
position0: position.map((p, i) => (i % 2 === 0 ? 1 - p - size[i / 2] : p)), //.map((p, i) => (i % 2 === 0 ? 1 - p - size[i / 2] : p)), // new Float32Array([...position].slice(1)), // try with the wrong array length
position0: position, //position.map((p, i) => (i % 2 === 0 ? 1 - p - size[i / 2] : p)), //.map((p, i) => (i % 2 === 0 ? 1 - p - size[i / 2] : p)), // new Float32Array([...position].slice(1)), // try with the wrong array length
position1: position,
size0: size.map((s) => 0.8 * s),
size0: size, //size.map((s) => 0.8 * s),
size1: size,
};

Expand All @@ -64,7 +64,6 @@ const noop = () => {};
export const Example: ChartsStory = (_, { title, description }) => {
let resetFocusControl: FlameGlobalControl = noop; // initial value
let focusOnNodeControl: FlameNodeControl = noop; // initial value
let searchText: FlameSearchControl = noop; // initial value

const onElementListeners = {
onElementClick: action('onElementClick'),
Expand All @@ -77,10 +76,9 @@ export const Example: ChartsStory = (_, { title, description }) => {
button('Set focus on random node', () => {
focusOnNodeControl(rng(0, 19));
});
const textSearch = text('Text to search', 'github');
button('Search', () => {
searchText(textSearch);
});
const textSearch = text('Text to search', '');
const textChangeAction = action('Text change');

const debug = boolean('Debug history', false);
return (
<Chart title={title} description={description}>
Expand All @@ -91,10 +89,11 @@ export const Example: ChartsStory = (_, { title, description }) => {
valueAccessor={(d: Datum) => d.value as number}
valueFormatter={(value) => `${value}`}
animation={{ duration: 500 }}
search={{ text: textSearch }}
onSearchTextChange={(text) => textChangeAction(`text changed to: [${text}]`)}
controlProviderCallback={{
resetFocus: (control) => (resetFocusControl = control),
focusOnNode: (control) => (focusOnNodeControl = control),
search: (control) => (searchText = control),
}}
/>
</Chart>
Expand Down

0 comments on commit c339947

Please sign in to comment.