Skip to content

Commit

Permalink
fix(ui): Reset preset slider if value wasn't applied after 1s
Browse files Browse the repository at this point in the history
  • Loading branch information
Hypfer committed Oct 28, 2022
1 parent 3c9b469 commit c6cbdc2
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
14 changes: 13 additions & 1 deletion frontend/src/hooks/useCommittingSlider.ts
@@ -1,4 +1,5 @@
import React from "react";
import {useGetter} from "../utils";

export const useCommittingSlider = (initialValue: number, onChange: (value: number) => void): [
number,
Expand All @@ -7,12 +8,23 @@ export const useCommittingSlider = (initialValue: number, onChange: (value: numb
] => {
const [sliderValue, setSliderValue] = React.useState(initialValue);
const [adoptedValue, setAdoptedValue] = React.useState(initialValue);
const [resetTimeout, setResetTimeout] = React.useState<any>();
const getResetTimeout = useGetter(resetTimeout);

React.useEffect(() => {
if (adoptedValue !== initialValue) {
clearTimeout(getResetTimeout());

setSliderValue(initialValue);
setAdoptedValue(initialValue);
} else if (initialValue !== sliderValue) {
clearTimeout(getResetTimeout());

setResetTimeout(setTimeout(() => {
setSliderValue(initialValue);
}, 1000));
}
}, [sliderValue, initialValue, adoptedValue]);
}, [sliderValue, initialValue, adoptedValue, getResetTimeout]);

const handleSliderChange = React.useCallback(
(_event: unknown, value: number | number[]) => {
Expand Down
12 changes: 12 additions & 0 deletions frontend/src/utils.ts
@@ -1,5 +1,6 @@
//Adapted from https://stackoverflow.com/a/34270811/10951033
import {ValetudoDataPoint} from "./api";
import {useCallback, useLayoutEffect, useRef} from "react";

export function convertSecondsToHumans(seconds: number, showSeconds = true, showDays = true): string {
let levels;
Expand Down Expand Up @@ -221,3 +222,14 @@ export function adjustColorBrightness(hexInput: string, percent: number) : strin
return result;
}

//adapted from https://stackoverflow.com/a/69331524
export const useGetter = <S>(value: S): (() => S) => {
const ref = useRef(value);
useLayoutEffect(() => {
ref.current = value;
});
return useCallback(() => {
return ref.current;
}, [ref]);
};

0 comments on commit c6cbdc2

Please sign in to comment.