Skip to content

Commit

Permalink
feat(scales): add option to clamp scales
Browse files Browse the repository at this point in the history
Optional ability to tell a scale to clamp. use case e.g. setting bar
value below zero

fixes plouc#1188
  • Loading branch information
Sam Jones committed Dec 11, 2020
1 parent 26069a2 commit 093841e
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 1 deletion.
1 change: 1 addition & 0 deletions packages/scales/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ declare module '@nivo/scales' {
max?: 'auto' | number
stacked?: boolean
reverse?: boolean
clamp?: boolean
}

export interface PointScale {
Expand Down
4 changes: 3 additions & 1 deletion packages/scales/src/linearScale.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { scaleLinear } from 'd3-scale'
import PropTypes from 'prop-types'

export const linearScale = (
{ axis, min = 0, max = 'auto', stacked = false, reverse = false },
{ axis, min = 0, max = 'auto', stacked = false, reverse = false, clamp = false },
xy,
width,
height
Expand All @@ -34,6 +34,7 @@ export const linearScale = (

scale.type = 'linear'
scale.stacked = stacked
scale.clamp(clamp)

return scale
}
Expand All @@ -44,4 +45,5 @@ export const linearScalePropTypes = {
max: PropTypes.oneOfType([PropTypes.oneOf(['auto']), PropTypes.number]),
stacked: PropTypes.bool,
reverse: PropTypes.bool,
clamp: PropTypes.bool,
}
9 changes: 9 additions & 0 deletions packages/scales/tests/linearScale.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,12 @@ it(`should allow to reverse domain`, () => {
expect(scale(0.5)).toBe(50)
expect(scale(1)).toBe(100)
})

it(`should allow to clamping`, () => {
const scale = linearScale({ axis: 'y', clamp: true, min: 0.5 }, { y: { min: 0, max: 1 } }, 100, 100)

expect(scale.domain()[0]).toBe(0.5)
expect(scale(0)).toBe(100)
expect(scale(0.5)).toBe(100)
expect(scale(1)).toBe(0)
})

0 comments on commit 093841e

Please sign in to comment.