diff --git a/frontend/src/lib/react-utils.ts b/frontend/src/lib/react-utils.ts index 6a16890..029d2f7 100644 --- a/frontend/src/lib/react-utils.ts +++ b/frontend/src/lib/react-utils.ts @@ -1,15 +1,14 @@ import { ActionCreatorWithOptionalPayload, AsyncThunk } from '@reduxjs/toolkit'; -import { useEffect } from 'react'; +import { useEffect, useState } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { KilovoltMessage, SubscriptionHandler, } from '@strimertul/kilovolt-client'; import { RootState } from '../store'; -import apiReducer, { - getUserPoints, -} from '../store/api/reducer'; -import {APIState, LoyaltyStorage} from "../store/api/types"; +import apiReducer, { getUserPoints } from '../store/api/reducer'; +import { APIState, LoyaltyStorage } from '../store/api/types'; +import { getInterval } from './time-utils'; export function useModule({ key, @@ -63,7 +62,30 @@ export function useUserPoints(): LoyaltyStorage { return data; } +export function useInterval( + initialValue: number, +): [ + number, + number, + number, + (newNum: number) => void, + (newMult: number) => void, +] { + const [value, setValue] = useState(initialValue); + + const [numInitialValue, multInitialValue] = getInterval(value); + const [num, setNum] = useState(numInitialValue); + const [mult, setMult] = useState(multInitialValue); + + useEffect(() => { + setValue(num * mult); + }, [num, mult]); + + return [value, num, mult, setNum, setMult]; +} + export default { useModule, useUserPoints, + useInterval, }; diff --git a/frontend/src/ui/components/Interval.tsx b/frontend/src/ui/components/Interval.tsx new file mode 100644 index 0000000..222b39b --- /dev/null +++ b/frontend/src/ui/components/Interval.tsx @@ -0,0 +1,59 @@ +import React, { useEffect } from 'react'; +import { useTranslation } from 'react-i18next'; +import { useInterval } from '../../lib/react-utils'; + +export interface IntervalProps { + active: boolean; + value: number; + onChange?: (value: number) => void; +} + +function Field({ active, value, onChange }: IntervalProps) { + const { t } = useTranslation(); + const [valueNum, num, mult, setNum, setMult] = useInterval(value); + useEffect(() => { + onChange(valueNum); + }, [valueNum]); + + return ( + <> +

+ { + const intNum = parseInt(ev.target.value, 10); + if (Number.isNaN(intNum)) { + return; + } + setNum(intNum); + }} + /> +

+

+ + + +

+ + ); +} + +export default React.memo(Field);