Skip to content

fix(slider): resolve step & snap floating point precision #10148

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Aug 27, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions packages/calcite-components/src/components/slider/slider.e2e.ts
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,17 @@ describe("calcite-slider", () => {
});
});

it("step floating point precision", async () => {
const page = await newE2EPage();
await page.setContent(
`<calcite-slider value="1.4" label-handles max="10" min="0.1" snap step="0.1"></calcite-slider>`,
);
const slider = await page.find("calcite-slider");

await page.waitForChanges();
expect((await slider.getProperty("value")).toString()).toBe("1.4");
});

it("only selects values on step interval when snap prop is passed", async () => {
const page = await newE2EPage();
await page.setContent(`
Expand Down
11 changes: 9 additions & 2 deletions packages/calcite-components/src/components/slider/slider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ import {
import { clamp, decimalPlaces } from "../../utils/math";
import { ColorStop, DataSeries } from "../graph/interfaces";
import { Scale } from "../interfaces";
import { BigDecimal } from "../../utils/number";
import { CSS, maxTickElementThreshold } from "./resources";
import { ActiveSliderProperty, SetValueProperty, SideOffset, ThumbType } from "./interfaces";

Expand Down Expand Up @@ -964,8 +965,14 @@ export class Slider
*/
private getClosestStep(value: number): number {
const { max, min, step } = this;
let snappedValue = Math.floor((value - min) / step) * step + min;
snappedValue = Math.min(Math.max(snappedValue, min), max);

// prevents floating point precision issues
const bigDecimalString = new BigDecimal(`${Math.round((value - min) / step)}`)
.multiply(`${step}`)
.add(`${min}`)
.toString();

let snappedValue = Math.min(Math.max(Number(bigDecimalString), min), max);

if (snappedValue > max) {
snappedValue -= step;
Expand Down
Loading