This commit is contained in:
parent
729704984c
commit
4bd975796e
148 changed files with 4865 additions and 27561 deletions
67
src/utils/useCurrentDate.ts
Normal file
67
src/utils/useCurrentDate.ts
Normal file
|
@ -0,0 +1,67 @@
|
|||
import { differenceInMilliseconds } from "date-fns";
|
||||
import { createRenderEffect, createSignal, onCleanup, untrack } from "solid-js";
|
||||
import { isServer } from "solid-js/web";
|
||||
|
||||
export enum DateRefreshPercision {
|
||||
seconds = 0,
|
||||
minutes = 1,
|
||||
hours,
|
||||
days,
|
||||
}
|
||||
|
||||
function useCurrentDate(
|
||||
percision:
|
||||
| (() => DateRefreshPercision)
|
||||
| DateRefreshPercision = DateRefreshPercision.minutes,
|
||||
) {
|
||||
const [current, setCurrent] = createSignal(new Date());
|
||||
|
||||
const updateInterval = () => {
|
||||
switch (typeof percision === "function" ? percision() : percision) {
|
||||
case DateRefreshPercision.seconds:
|
||||
return 1000;
|
||||
case DateRefreshPercision.minutes:
|
||||
return 15 * 1000;
|
||||
case DateRefreshPercision.hours:
|
||||
return 60 * 1000;
|
||||
case DateRefreshPercision.days:
|
||||
return 60 * 60 * 1000;
|
||||
}
|
||||
};
|
||||
|
||||
let id: undefined | number;
|
||||
|
||||
const update = () => setCurrent(new Date());
|
||||
|
||||
createRenderEffect(() => {
|
||||
if (typeof id !== "undefined") {
|
||||
window.clearInterval(id);
|
||||
id = undefined;
|
||||
}
|
||||
|
||||
const interval = updateInterval();
|
||||
|
||||
const now = new Date();
|
||||
if (differenceInMilliseconds(now, untrack(current)) <= interval) {
|
||||
update();
|
||||
}
|
||||
|
||||
id = window.setInterval(update, interval);
|
||||
});
|
||||
|
||||
onCleanup(() => {
|
||||
if (typeof id !== "undefined") {
|
||||
window.clearInterval(id);
|
||||
id = undefined;
|
||||
}
|
||||
});
|
||||
|
||||
return current;
|
||||
}
|
||||
|
||||
function useCurrentDateServer() {
|
||||
const now = new Date();
|
||||
return () => now;
|
||||
}
|
||||
|
||||
export default isServer ? useCurrentDateServer : useCurrentDate;
|
Loading…
Add table
Add a link
Reference in a new issue