va-tracker/src/ui/hooks/useActiveAppTracker.tsx

52 lines
1.5 KiB
TypeScript

// src/hooks/useActiveAppTracker.ts
import { useEffect, useRef } from "react";
import { useDispatch } from "react-redux";
import { setActiveWindow, WindowInfo } from "../store/windowSlice";
export const useActiveAppTracker = (
isTracking: boolean,
projectId: string,
projectName: string
) => {
const dispatch = useDispatch();
const lastActiveRef = useRef<WindowInfo | null>(null);
useEffect(() => {
if (!isTracking || !projectId) {
console.log(" Tracking not active or project not selected");
return;
}
console.log(` Tracking started for project: ${projectName}`);
const fetchActiveApp = async () => {
try {
const details = (await window.electron.getActiveAppDetails()) as WindowInfo;
if (!details || !details.id) return;
const prev = lastActiveRef.current;
const hasChanged =
!prev ||
prev.title !== details.title ||
prev.owner.processId !== details.owner.processId;
if (hasChanged) {
console.log("🪟 Window changed:", details.title);
dispatch(setActiveWindow({ window: details, projectId, projectName }));
lastActiveRef.current = details;
}
} catch (error) {
console.error("❌ Failed to fetch active app:", error);
}
};
fetchActiveApp();
const intervalId = setInterval(fetchActiveApp, 5000);
return () => {
console.log("🛑 Stopping active window tracker");
clearInterval(intervalId);
};
}, [isTracking, dispatch, projectId, projectName]);
};