# All files / src/components histogram-filter.tsx

84.61% Statements 44/52
70% Branches 21/30
100% Functions 11/11
84.31% Lines 43/51

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224

    7x

    10x
    10x
    10x

    10x
    10x

    10x

    2x

    2x
    2x

    10x
    10x

    10x
    10x

    10x

    20x
    30x

    30x

    10x

    10x
    10x

    10x

    10x

    10x

    10x
    10x

    10x

    10x
    3x

    7x

    10x

    2x

    2x
    2x

    2x

    1x

    1x

    2x

    2x
    2x

    2x

    1x

    1x

     import {
      useState,
      useMemo,
      useRef,
      type HTMLAttributes,
      useEffect,
    } from 'react';
    import cn from 'classnames';
    import { brushX, select, event, scaleLinear, type BrushBehavior } from 'd3';

    import Histogram, { type Range } from './histogram';

    import useSize from '../hooks/useSize';

    import '../styles/components/histogram-filter.scss';

    type Props = {
      /**
       * The left-most, smallest, value the histogram starts at irrespective of the
       * array values. Defaults to min(values).
       */
      min?: number;
      /**
       * The right-most, largest, value the histogram ends at irrespective of the
       * array values. Defaults to max(values).
       */
      max?: number;
      /**
       * An array of values which the histogram is based on.
       */
      values: number[];
      /**
       * An array of unfiltered values which the histogram is based on.
       * (useful to calculate max bin height)
       */
      unfilteredValues?: number[];
      /**
       * A value which specifies the start and end points selected by the user.
       */
      selectedRange: Range;
      /**
       * A callback that returns the selected and final (ie after drag) range.
       */
      onChange: (range: Range) => unknown;
      /**
       * Number of bins (intervals) which the values are allocated to.
       * Each interval is of the size (max - min) / nBins. Defaults to 50.
       */
      nBins?: number;
      /**
       * The height in pixels of the bin with the most values. Defaults to 300.
       */
      height?: number;
      /**
       * Display a shadow of the unfiltered data (opacity value)
       */
      unfilteredValuesShadow?: number;
      /**
       * Additional CSS classnames to apply (eg secondary, tertiary)
       */
      className?: string;
    };

    const HistogramFilter = ({
      min: minOrUndef,
      max: maxOrUndef,
      values,
      unfilteredValues,
      unfilteredValuesShadow,
      selectedRange,
      onChange,
      nBins = 30,
      height = 50,
      className,
      ...props
    }: Props & Omit<HTMLAttributes<HTMLDivElement>, 'onChange'>) => {
      const d3Container = useRef<SVGSVGElement>(null);
      const [size] = useSize(d3Container);
      const brushRef = useRef<BrushBehavior<unknown> | null>(null);

      const onChangeRef = useRef(onChange);
      onChangeRef.current = onChange;

      const [min, max] = useMemo(() => {
        // Assign sensible default values if not provided
        const innerMin =
          minOrUndef === undefined ? Math.min(...values) : minOrUndef;
        const innerMax =
          maxOrUndef === undefined ? Math.max(...values) : maxOrUndef;
        return [innerMin, innerMax];
      }, [maxOrUndef, minOrUndef, values]);

      const [startInput, setStartInput] = useState(`${min}`);
      const [endInput, setEndInput] = useState(`${max}`);

      useEffect(() => {
        Iif (!size) {
          return; // Can't position the brush correctly until we have a size
        }

        // Scale
        const scale = scaleLinear().domain([min, max]).range([0, size.width]);

        // On brush event
        const getOnBrush = (type?: string) => () => {
          const range = event.selection;
          // Update only if an event caused this to be called (not programmatic)
          Iif (event.sourceEvent && range) {
            const start = +`${scale.invert(range[0]).toPrecision(4)}`;
            const end = +`${scale.invert(range[1]).toPrecision(4)}`;
            setStartInput(`${start}`);
            setEndInput(`${end}`);
            if (type === 'end') {
              // Only when user stops brushing, send the new values
              onChangeRef.current([start, end]);
            }
          }
        };

        // Brush
        brushRef.current = brushX()
          .extent([
            [0, 0],
            [size.width, size.height],
          ])
          .on('start brush', getOnBrush())
          .on('end', getOnBrush('end'));

        // Tie the brush to the DOM
        const selection = select(d3Container.current).append('g');
        brushRef.current(selection);

        // eslint-disable-next-line consistent-return
        return () => {
          // Unbind listeners
          brushRef.current?.on('start brush end', null);
          // Remove selection
          selection.remove();
        };
      }, [size, min, max]);

      // Update the brush programatically when props are changed
      useEffect(() => {
        Iif (!size) {
          return; // Can't position the brush correctly until we have a size
        }
        const scale = scaleLinear().domain([min, max]).range([0, size.width]);
        // If the brush corresponds to the full range, remove it completely
        if (selectedRange[0] === min && selectedRange[1] === max) {
          brushRef.current?.move(select(d3Container.current).select('g'), null);
        } else {
          brushRef.current?.move(select(d3Container.current).select('g'), [
            scale(selectedRange[0])!,
            scale(selectedRange[1])!,
          ]);
        }
      }, [min, max, selectedRange, size]);

      return (
        <div className={cn('histogram-filter', className)} {...props}>
          <Histogram
            values={values}
            unfilteredValues={unfilteredValues}
            unfilteredValuesShadow={unfilteredValuesShadow}
            selectedRange={selectedRange}
            nBins={nBins}
            min={min}
            max={max}
            height={height}
          >
            {/* Brush container */}
            <svg ref={d3Container} width="100%" height="100%" />
          </Histogram>
          <div className="histogram-filter__text-input-container">
            <input
              type="text"
              onChange={(e) => {
                const textValue = e.target.value;
                // Always update the input text state, regardless of if valid or not
                setStartInput(e.target.value);
                const numberValue = +textValue;
                // Only if the number if valid do we keep it in the range state
                if (
                  !Number.isNaN(numberValue) &&
                  numberValue < selectedRange[1] &&
                  numberValue >= min
                ) {
                  onChange([numberValue, selectedRange[1]]);
                }
              }}
              // On blur, set the input text state to whatever value is in range
              // state and move the brush
              onBlur={() => setStartInput(`${selectedRange[0]}`)}
              value={startInput}
              style={{ width: `${startInput.length + 2}ch` }}
            />
            <input
              type="text"
              onChange={(e) => {
                const textValue = e.target.value;
                // Always update the input text state, regardless of if valid or not
                setEndInput(e.target.value);
                const numberValue = +textValue;
                // Only if the number if valid do we keep it in the range state
                if (
                  !Number.isNaN(numberValue) &&
                  numberValue > selectedRange[0] &&
                  numberValue <= max
                ) {
                  onChange([selectedRange[0], numberValue]);
                }
              }}
              // On blur, reset the input text state to whatever value is in range
              onBlur={() => setEndInput(`${selectedRange[1]}`)}
              value={endInput}
              style={{ width: `${endInput.length + 2}ch` }}
            />
          </div>
        </div>
      );
    };

    export default HistogramFilter;