2024-10-28 05:56:50 +00:00
|
|
|
import { usePageVisibility } from "@solid-primitives/page-visibility";
|
2024-07-14 12:28:44 +00:00
|
|
|
import {
|
|
|
|
Accessor,
|
|
|
|
createContext,
|
|
|
|
createRenderEffect,
|
|
|
|
createSignal,
|
|
|
|
onCleanup,
|
|
|
|
untrack,
|
|
|
|
useContext,
|
|
|
|
} from "solid-js";
|
|
|
|
|
|
|
|
const TimeSourceContext = createContext<Accessor<Date>>();
|
|
|
|
|
|
|
|
export const TimeSourceProvider = TimeSourceContext.Provider;
|
|
|
|
|
|
|
|
export function createTimeSource() {
|
2024-07-22 14:04:56 +00:00
|
|
|
let id: ReturnType<typeof setTimeout> | undefined;
|
2024-07-14 12:28:44 +00:00
|
|
|
const [get, set] = createSignal(new Date());
|
2024-10-28 05:56:50 +00:00
|
|
|
const visible = usePageVisibility();
|
2024-07-14 12:28:44 +00:00
|
|
|
|
2024-10-28 05:56:50 +00:00
|
|
|
const cancelTimer = () => {
|
2024-07-14 12:28:44 +00:00
|
|
|
if (typeof id !== "undefined") {
|
|
|
|
clearInterval(id);
|
|
|
|
}
|
2024-10-28 05:56:50 +00:00
|
|
|
id = undefined;
|
|
|
|
};
|
|
|
|
|
|
|
|
const resetTimer = () => {
|
|
|
|
cancelTimer();
|
|
|
|
set(new Date());
|
|
|
|
id = setTimeout(() => {
|
|
|
|
set(new Date());
|
|
|
|
}, 30 * 1000); // refresh rate: 30s
|
|
|
|
};
|
|
|
|
|
|
|
|
createRenderEffect(() => {
|
|
|
|
onCleanup(cancelTimer);
|
|
|
|
if (visible()) {
|
|
|
|
resetTimer();
|
|
|
|
} else {
|
|
|
|
console.debug("createTimeSource: page is invisible, cancel the timer")
|
|
|
|
}
|
2024-07-14 12:28:44 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
return get;
|
|
|
|
}
|
|
|
|
|
|
|
|
export function useTimeSource() {
|
|
|
|
return (
|
|
|
|
useContext(TimeSourceContext) ??
|
|
|
|
(console.warn("useTimeSource() is used but no source is provided"),
|
|
|
|
createTimeSource())
|
|
|
|
);
|
|
|
|
}
|