2025-08-09 09:15:54 +03:00
|
|
|
import { useCallback, useContext, useEffect, useMemo, useRef, useState } from "preact/hooks";
|
2025-08-08 20:08:06 +03:00
|
|
|
import { EventData, EventNames } from "../../components/app_context";
|
|
|
|
|
import { ParentComponent } from "./ReactBasicWidget";
|
2025-08-08 23:23:07 +03:00
|
|
|
import SpacedUpdate from "../../services/spaced_update";
|
2025-08-08 20:08:06 +03:00
|
|
|
|
|
|
|
|
export default function useTriliumEvent<T extends EventNames>(eventName: T, handler: (data: EventData<T>) => void) {
|
|
|
|
|
const parentWidget = useContext(ParentComponent);
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
if (!parentWidget) {
|
|
|
|
|
console.warn("useTriliumEvent: No widget context found");
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Create a unique handler name for this specific event listener
|
|
|
|
|
const handlerName = `${eventName}Event`;
|
|
|
|
|
const originalHandler = parentWidget[handlerName];
|
|
|
|
|
|
|
|
|
|
// Override the event handler to call our handler
|
|
|
|
|
parentWidget[handlerName] = async function(data: EventData<T>) {
|
|
|
|
|
// Call original handler if it exists
|
|
|
|
|
if (originalHandler) {
|
|
|
|
|
await originalHandler.call(parentWidget, data);
|
|
|
|
|
}
|
|
|
|
|
// Call our React component's handler
|
|
|
|
|
handler(data);
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// Cleanup: restore original handler on unmount
|
|
|
|
|
return () => {
|
|
|
|
|
parentWidget[handlerName] = originalHandler;
|
|
|
|
|
};
|
|
|
|
|
}, [parentWidget]);
|
2025-08-08 23:23:07 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function useSpacedUpdate(callback: () => Promise<void>, interval = 1000) {
|
2025-08-09 09:15:54 +03:00
|
|
|
const callbackRef = useRef(callback);
|
|
|
|
|
const spacedUpdateRef = useRef<SpacedUpdate>();
|
2025-08-08 23:23:07 +03:00
|
|
|
|
2025-08-09 09:15:54 +03:00
|
|
|
// Update callback ref when it changes
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
callbackRef.current = callback;
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Create SpacedUpdate instance only once
|
|
|
|
|
if (!spacedUpdateRef.current) {
|
|
|
|
|
spacedUpdateRef.current = new SpacedUpdate(
|
|
|
|
|
() => callbackRef.current(),
|
|
|
|
|
interval
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Update interval if it changes
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
spacedUpdateRef.current?.setUpdateInterval(interval);
|
|
|
|
|
}, [interval]);
|
|
|
|
|
|
|
|
|
|
return spacedUpdateRef.current;
|
2025-08-08 20:08:06 +03:00
|
|
|
}
|