Skip to content

Commit

Permalink
fix(Range): ticks fix (#438)
Browse files Browse the repository at this point in the history
* Add component arguments

* Add default values for displayTicks and ticksStep

* Fix number of ticks calculation

* Condition displaying ticks on the displayTicks logic

* Fix problem with negative step sizes

* Remove usage of useMemo
  • Loading branch information
itaiperi committed Jan 1, 2024
1 parent 13c8db2 commit e6f46a3
Showing 1 changed file with 12 additions and 9 deletions.
21 changes: 12 additions & 9 deletions src/Range/Range.tsx
Expand Up @@ -15,10 +15,12 @@ export type RangeProps = Omit<
IComponentBaseProps & {
color?: ComponentColor
size?: ComponentSize
displayTicks?: boolean
ticksStep: number
}

const Range = forwardRef<HTMLInputElement, RangeProps>(
({ color, size, step, dataTheme, className, ...props }, ref): JSX.Element => {
({ color, size, step, displayTicks, ticksStep, dataTheme, className, ...props }, ref): JSX.Element => {
const classes = twMerge(
'range',
className,
Expand All @@ -37,13 +39,14 @@ const Range = forwardRef<HTMLInputElement, RangeProps>(
})
)

const isNumeric = (n: any): n is number =>
!isNaN(parseFloat(n)) && isFinite(n)
const calculatedDisplayTicks = displayTicks ?? (step !== undefined);
const calculatedStep = step !== undefined ? Number(step) : 1; // default value per HTML standard
const calculatedTicksStep = ticksStep ?? calculatedStep;
const min = props.min !== undefined ? Number(props.min) : 0; // default value per HTML standard
const max = props.max !== undefined ? Number(props.max) : 100; // default value per HTML standard

const numSteps = useMemo(() => {
const safeStep = Math.max(1, Number(step))
return Math.ceil(100 / safeStep) ?? 1
}, [props.max, step])
// use Math.max to solve multiple issues with negative numbers throwing errors
const numTicks = Math.max(Math.ceil((max - min) / calculatedTicksStep), 1) + 1;

return (
<>
Expand All @@ -55,9 +58,9 @@ const Range = forwardRef<HTMLInputElement, RangeProps>(
data-theme={dataTheme}
className={classes}
/>
{isNumeric(step) && (
{calculatedDisplayTicks && (
<div className="w-full flex justify-between text-xs px-2">
{[...Array(numSteps + 1)].map((_, i) => {
{[...Array(numTicks)].map((_, i) => {
return <span key={i}>|</span>
})}
</div>
Expand Down

0 comments on commit e6f46a3

Please sign in to comment.