spacedrive/interface/hooks/useCounter.ts

91 lines
2 KiB
TypeScript
Raw Normal View History

import { useEffect, useMemo } from 'react';
2022-07-30 10:05:08 +00:00
import { useCountUp } from 'use-count-up';
2022-10-18 13:52:00 +00:00
import { proxy, useSnapshot } from 'valtio';
2022-07-30 10:05:08 +00:00
2022-10-18 13:52:00 +00:00
const counterStore = proxy({
2022-07-30 10:05:08 +00:00
counterLastValue: new Map<string, number>(),
2022-10-18 13:52:00 +00:00
setCounterLastValue: (name: string, lastValue: number) =>
counterStore.counterLastValue.set(name, lastValue)
});
2022-07-30 10:05:08 +00:00
const useCounterState = (key: string) => {
2022-10-18 13:52:00 +00:00
const { counterLastValue, setCounterLastValue } = useSnapshot(counterStore);
2022-07-30 10:05:08 +00:00
return {
lastValue: counterLastValue.get(key),
setLastValue: setCounterLastValue
};
};
type UseCounterProps = {
name: string;
start?: number;
end: number;
/**
* Duration of the counter animation in seconds
* default: `2s`
*/
duration?: number;
/**
* If `true`, counter will only count up/down once per app session.
* default: `true`
*/
saveState?: boolean;
/**
* Number of decimal places. Defaults to `1`.
*/
precision?: number;
/**
* The locale to use for number formatting (e.g. `'de-DE'`).
* Defaults to your system locale. Passed directed into [Intl.NumberFormat()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat).
*/
locales?: string | string[];
2022-07-30 10:05:08 +00:00
};
export const useCounter = ({
name,
start = 0,
end,
locales,
duration = 2,
precision = 1,
saveState = true
}: UseCounterProps) => {
2022-07-30 10:05:08 +00:00
const { lastValue, setLastValue } = useCounterState(name);
if (saveState && lastValue) {
start = lastValue;
}
const formatter = useMemo(
() =>
new Intl.NumberFormat(locales, {
style: 'decimal',
minimumFractionDigits: precision,
maximumFractionDigits: precision
}),
[locales, precision]
);
2022-07-30 10:05:08 +00:00
const { value } = useCountUp({
isCounting: !(start === end),
start,
end,
duration,
easing: 'easeOutCubic',
formatter: (value) => formatter.format(value)
2022-07-30 10:05:08 +00:00
});
2022-08-01 13:43:01 +00:00
useEffect(() => {
if (saveState && value == end) {
setLastValue(name, end);
}
}, [end, name, saveState, setLastValue, value]);
2022-07-30 10:05:08 +00:00
if (start === end) return end;
if (saveState && lastValue && lastValue === end) return end;
return value;
};