# All files / utils getTicks.ts

95.7% Statements 89/93
89.06% Branches 57/64
100% Functions 9/9
95.29% Lines 81/85

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
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    2x
    2x
    2x

    2x

    2x
    2x

    2x
    2x

    2x

    72x
    72x
    72x
    6x
    6x
    6x

    66x
    5x
    3x

    2x
    61x

    4x

    57x

    2x
    8x

    8x
    8x

    8x
    8x

    25x

    8x

    2x
    7x

    7x

    7x
    7x

    7x
    7x

    34x

    7x

    2x

    15x
    74x

    2x

    43x
    86x
    43x

    43x
    43x

    18x
    18x

    43x

    43x
    43x

    43x

    28x

    10150x
    148x
    51x

    97x

    10150x
    10150x

    43x

    2x

    16x
    8x

    8x

    8x

    2x
    2x

    5x
    5x

    5x
    5x

    5x

    5x

    2x
    2x

    3x
    3x

    3x

    3x

     // Libraries
    import {scaleUtc} from 'd3-scale'
    import {ticks} from 'd3-array'
    import memoizeOne from 'memoize-one'

    // Types
    import {AxisTicks, Formatter, FormatterType} from '../types'

    // Constants
    import {TIME, VALUE} from '../constants/columnKeys'
    import {TICK_COUNT_LIMIT} from '../constants'

    // Utils
    import {getTextMetrics} from './getTextMetrics'
    import {isFiniteNumber} from './isFiniteNumber'

    /*
      Minimum spacing defined as:
        I. when there are less than 4 ticks:
          for each tick, spacing is one-quarter of the length of a tick
          thusly: 0.25, 0.50, 0.75 of a tick's length as spacing for 1, 2, and 3 ticks respectively
        II. when there are 4 to 10 ticks:
          sum of all tick lengths is shorter than total available space by at least one tick's length
        III. when there are more than 10 ticks:
          for every group of up to 10 ticks there is spacing equal at least 1 tick's length
        IV. length of a tick is:
             vertical axis - the average of the height and width of a span that wraps the formatted last tick in the range
             horizontal axis - the width of a span that wraps the formatted last tick in the range
    */
    const hasMinimumSpacing = (
      rangeLength: number,
      timeTickLength: number,
      ticks: AxisTicks
    ): boolean => {
      const fractionalSpaceAsPadding = 0.25
      const totalLength = ticks.length * timeTickLength
      if (ticks.length < 4) {
        const padding = totalLength * fractionalSpaceAsPadding
        Eif (totalLength < rangeLength - padding) {
          return true
        }
        return false
      } else if (ticks.length <= 10) {
        if (totalLength < rangeLength - timeTickLength) {
          return true
        }
        return false
      } else if (
        totalLength <
        rangeLength - Math.ceil(ticks.length / 10) * timeTickLength
      ) {
        return true
      }
      return false
    }

    /*
      Optimal number of ticks is defined as:
      I. allow d3 to choose the ticks and
      II. meets minimum spacing requirements checked by hasMinimumSpacing
    */
    const getOptimalTicks = (
      [d0, d1]: number[],
      rangeLength: number,
      tickLength: number
    ): number[] => {
      const maxNumTicks = Math.floor(rangeLength / tickLength)
      let optimalTicks = ticks(d0, d1, maxNumTicks)

      for (
        let counter = 1;
        counter < maxNumTicks &&
        !hasMinimumSpacing(rangeLength, tickLength, optimalTicks);
        counter += 1
      ) {
        optimalTicks = ticks(d0, d1, maxNumTicks - counter)
      }
      return optimalTicks
    }

    /*
      Similar to getOptimalTicks but for Date objects
    */
    const getOptimalTimeTicks = (
      [d0, d1]: number[],
      rangeLength: number,
      timeTickLength: number
    ): Date[] => {
      const scaledTime = scaleUtc()
        .domain([d0, d1])
        .range([0, rangeLength])
      const maxNumTicks = Math.floor(rangeLength / timeTickLength)
      let optimalTicks = scaledTime.ticks(maxNumTicks)

      for (
        let counter = 1;
        counter < maxNumTicks &&
        !hasMinimumSpacing(rangeLength, timeTickLength, optimalTicks);
        counter += 1
      ) {
        optimalTicks = scaledTime.ticks(maxNumTicks - counter)
      }
      return optimalTicks
    }

    // calculateTicks adheres to spacing requirements as described in helper functions above
    export const calculateTicks = (
      domain: number[],
      rangeLength: number,
      tickSize: number,
      columnKey: string
    ): number[] => {
      return columnKey === TIME
        ? getOptimalTimeTicks(domain, rangeLength, tickSize).map(d => d.getTime())
        : getOptimalTicks(domain, rangeLength, tickSize)
    }

    /*
      generateTicks gives control to the user over placement, number, and interval of ticks
        defers to the user's judgement on spacing (tick labels may overlap)
    */
    export const generateTicks = (
      domain: number[],
      columnKey: string,
      totalTicks: number,
      tickStart: number,
      tickStep: number
    ): number[] => {
      const generatedTicks = []
      const [start = 0, end = 0] = domain
      const stepStart = isFiniteNumber(tickStart) ? tickStart : start

      let step = tickStep
      if (!isFiniteNumber(tickStep)) {
        const parts =
          isFiniteNumber(totalTicks) && totalTicks !== 0 ? totalTicks : 1
        step = (end - stepStart) / (isFiniteNumber(tickStart) ? parts : parts + 1)
      }

      const tickCountLimit = isFiniteNumber(totalTicks)
        ? Math.min(totalTicks, TICK_COUNT_LIMIT)
        : TICK_COUNT_LIMIT

      let counter = isFiniteNumber(tickStart) ? 0 : 1
      let generatedTick = stepStart + step * counter

      if (
        tickStep !== 0 &&
        (isFiniteNumber(totalTicks) || isFiniteNumber(tickStep))
      ) {
        /*
          - When 'step' marks the ticks to the right (or up) on the axis
            it is a positive number and should stop at 'end'
          - When 'step' marks the ticks to the left (or down) on the axis
            it is a negative number and should stop at 'start'
        */
        while (
          ((step > 0 && generatedTick <= end) ||
            (step < 0 && generatedTick >= start)) &&
          generatedTicks.length < tickCountLimit
        ) {
          if (generatedTick >= start && generatedTick <= end) {
            if (columnKey === TIME) {
              generatedTicks.push(new Date(generatedTick))
            } else {
              generatedTicks.push(generatedTick)
            }
          }
          counter += 1
          generatedTick = stepStart + step * counter
        }
      }
      return generatedTicks
    }

    /*
      ticks can be either
        - generated: user's defined parameters and judgmenet for spacing
        - calculated: Giraffe's determination and spacing requirements
    */
    const getTicks = (
      domain: number[],
      rangeLength: number,
      tickSize: number,
      columnKey: string,
      totalTicks?: number,
      tickStart?: number,
      tickStep?: number
    ) => {
      const [start = 0, end = 0] = domain
      Iif (isFiniteNumber(totalTicks) || isFiniteNumber(tickStep)) {
        return generateTicks(domain, columnKey, totalTicks, tickStart, tickStep)
      }
      Iif (isFiniteNumber(tickStart)) {
        const specifiedTickStart = Math.min(Math.max(tickStart, start), end)
        return calculateTicks(
          [specifiedTickStart, end],
          rangeLength,
          tickSize,
          columnKey
        )
      }
      return calculateTicks(domain, rangeLength, tickSize, columnKey)
    }

    /*
      for performance memoize both the original arguments and calculated arguments
        keep this separate from a memoized horizontal version
    */
    const getMemoizedVerticalTicks = memoizeOne(getTicks)
    export const getVerticalTicks = memoizeOne(
      (
        domain: number[],
        rangeLength: number,
        tickFont: string,
        formatter: Formatter,
        totalTicks?: number,
        tickStart?: number,
        tickStep?: number
      ): number[] => {
        const sampleTick = formatter(domain[1])
        const tickTextMetrics = getTextMetrics(tickFont, sampleTick)

        const maxTickHeight = 5 * tickTextMetrics.height
        const tickHeight = Math.min(
          tickTextMetrics.height + tickTextMetrics.width / 2,
          maxTickHeight
        )
        const columnKey =
          formatter._GIRAFFE_FORMATTER_TYPE === FormatterType.Time ? TIME : VALUE

        return getMemoizedVerticalTicks(
          domain,
          rangeLength,
          tickHeight,
          columnKey,
          totalTicks,
          tickStart,
          tickStep
        )
      }
    )

    /*
      for performance memoize both the original arguments and calculated arguments
        keep this separate from a memoized vertical version
    */
    const getMemoizedHorizontalTicks = memoizeOne(getTicks)
    export const getHorizontalTicks = memoizeOne(
      (
        domain: number[],
        rangeLength: number,
        tickFont: string,
        formatter: Formatter,
        totalTicks?: number,
        tickStart?: number,
        tickStep?: number
      ): number[] => {
        const sampleTick = formatter(domain[1])
        const tickTextMetrics = getTextMetrics(tickFont, sampleTick)

        const columnKey =
          formatter._GIRAFFE_FORMATTER_TYPE === FormatterType.Time ? TIME : VALUE

        return getMemoizedHorizontalTicks(
          domain,
          rangeLength,
          tickTextMetrics.width,
          columnKey,
          totalTicks,
          tickStart,
          tickStep
        )
      }
    )