Skip to content

Commit

Permalink
fix to make html ids unique for each component instance for DualBrush
Browse files Browse the repository at this point in the history
  • Loading branch information
walterra committed Oct 10, 2024
1 parent 6f54631 commit 75ca4ca
Showing 1 changed file with 11 additions and 4 deletions.
15 changes: 11 additions & 4 deletions x-pack/packages/ml/aiops_components/src/dual_brush/dual_brush.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@
*/

import { isEqual } from 'lodash';
import React, { useEffect, useRef, type FC } from 'react';
import React, { useEffect, useMemo, useRef, type FC } from 'react';

import { htmlIdGenerator } from '@elastic/eui';

import * as d3Brush from 'd3-brush';
import * as d3Scale from 'd3-scale';
Expand Down Expand Up @@ -100,6 +102,10 @@ export const DualBrush: FC<DualBrushProps> = (props) => {
const d3BrushContainer = useRef(null);
const brushes = useRef<DualBrush[]>([]);

// id to prefix html ids for the brushes since this component can be used
// multiple times within dashboard and embedded charts.
const htmlId = useMemo(() => htmlIdGenerator()(), []);

// We need to pass props to refs here because the d3-brush code doesn't consider
// native React prop changes. The brush code does its own check whether these props changed then.
// The initialized brushes might otherwise act on stale data.
Expand Down Expand Up @@ -135,10 +141,10 @@ export const DualBrush: FC<DualBrushProps> = (props) => {
const xMax = x(maxRef.current) ?? 0;
const minExtentPx = Math.round((xMax - xMin) / 100);

const baselineBrush = d3.select('#aiops-brush-baseline');
const baselineBrush = d3.select(`#aiops-brush-baseline-${htmlId}`);
const baselineSelection = d3.brushSelection(baselineBrush.node() as SVGGElement);

const deviationBrush = d3.select('#aiops-brush-deviation');
const deviationBrush = d3.select(`#aiops-brush-deviation-${htmlId}`);
const deviationSelection = d3.brushSelection(deviationBrush.node() as SVGGElement);

if (!isBrushXSelection(deviationSelection) || !isBrushXSelection(baselineSelection)) {
Expand Down Expand Up @@ -260,7 +266,7 @@ export const DualBrush: FC<DualBrushProps> = (props) => {
.insert('g', '.brush')
.attr('class', 'brush')
.attr('id', (b: DualBrush) => {
return 'aiops-brush-' + b.id;
return `aiops-brush-${b.id}-${htmlId}`;
})
.attr('data-test-subj', (b: DualBrush) => {
// Uppercase the first character of the `id` so we get aiopsBrushBaseline/aiopsBrushDeviation.
Expand Down Expand Up @@ -339,6 +345,7 @@ export const DualBrush: FC<DualBrushProps> = (props) => {
drawBrushes();
}
}, [
htmlId,
min,
max,
width,
Expand Down

0 comments on commit 75ca4ca

Please sign in to comment.