# All files / components Brush.tsx

47.22% Statements 17/36
27.78% Branches 5/18
100% Functions 2/2
53.13% Lines 17/32

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
    1x
    1x

    1x

    1x

    1x
    5x
    5x
    5x
    5x
    5x

    5x

    5x
    5x
    5x

    5x
    5x

    1x
     // Libraries
    import * as React from 'react'
    import {useLayoutEffect, FunctionComponent, CSSProperties} from 'react'

    import {DragEvent} from '../utils/useDragEvent'
    import {getRectDimensions} from '../utils/brush'

    const MIN_SELECTION_SIZE = 5 // pixels

    interface Props {
      event: DragEvent | null
      width: number
      height: number
      onXBrushEnd: (xRange: number[]) => void
      onYBrushEnd: (yRange: number[]) => void
    }

    export const Brush: FunctionComponent<Props> = ({
      event,
      width,
      height,
      onXBrushEnd,
      onYBrushEnd,
    }) => {
      const isBrushing = event && event.direction

      useLayoutEffect(() => {
        Eif (!isBrushing || event.type !== 'dragend') {
          return
        }

        let p0
        let p1
        let callback

        if (event.direction === 'x') {
          p0 = Math.min(event.initialX, event.x)
          p1 = Math.max(event.initialX, event.x)
          callback = onXBrushEnd
        } else if (event.direction === 'y') {
          p0 = Math.min(event.initialY, event.y)
          p1 = Math.max(event.initialY, event.y)
          callback = onYBrushEnd
        } else {
          return
        }

        if (p1 - p0 < MIN_SELECTION_SIZE) {
          return
        }

        callback([p0, p1])
      })

      Eif (!isBrushing || event.type === 'dragend') {
        return null
      }

      const {x, y, width: brushWidth, height: brushHeight} = getRectDimensions(
        event,
        width,
        height
      )

      const selectionStyle: CSSProperties = {
        display: event.initialX === null ? 'none' : 'inherit',
        position: 'absolute',
        left: `${x}px`,
        width: `${brushWidth}px`,
        top: `${y}px`,
        height: `${brushHeight}px`,
        opacity: 0.1,
        backgroundColor: 'aliceblue',
      }

      return <div className="giraffe-brush-selection" style={selectionStyle} />
    }

    Brush.displayName = 'Brush'