import GLib from 'gi://GLib?version=2.0'; import { GenericFunction } from 'lib/types/customModules/generic'; import { Bind } from 'lib/types/variable'; import { Variable as VariableType } from 'types/variable'; /** * @param {VariableType} targetVariable - The Variable to update with the function's result. * @param {Array} trackers - Array of trackers to watch. * @param {Bind} pollingInterval - The polling interval in milliseconds. * @param {GenericFunction} someFunc - The function to execute at each interval, which updates the Variable. * @param {...P} params - Parameters to pass to someFunc. */ export const pollVariable = >( targetVariable: VariableType, trackers: Array, pollingInterval: Bind, someFunc: F, ...params: P ): void => { let intervalInstance: number | null = null; const intervalFn = (pollIntrvl: number): void => { if (intervalInstance !== null) { GLib.source_remove(intervalInstance); } intervalInstance = Utils.interval(pollIntrvl, () => { targetVariable.value = someFunc(...params); }); }; Utils.merge([pollingInterval, ...trackers], (pollIntrvl: number) => { intervalFn(pollIntrvl); }); }; /** * @param {VariableType} targetVariable - The Variable to update with the result of the command. * @param {Array} trackers - Array of trackers to watch. * @param {Bind} pollingInterval - The polling interval in milliseconds. * @param {string} someCommand - The bash command to execute. * @param {GenericFunction} someFunc - The function to execute after processing the command result; * with the first argument being the result of the command execution. * @param {...P} params - Additional parameters to pass to someFunc. */ export const pollVariableBash = >( targetVariable: VariableType, trackers: Array, pollingInterval: Bind, someCommand: string, someFunc: F, ...params: P ): void => { let intervalInstance: number | null = null; const intervalFn = (pollIntrvl: number): void => { if (intervalInstance !== null) { GLib.source_remove(intervalInstance); } intervalInstance = Utils.interval(pollIntrvl, () => { Utils.execAsync(`bash -c "${someCommand}"`) .then((res: string) => { try { targetVariable.value = someFunc(res, ...params); } catch (error) { console.warn(`An error occurred when running interval bash function: ${error}`); } }) .catch((err) => console.error(`Error running command "${someCommand}": ${err}`)); }); }; Utils.merge([pollingInterval, ...trackers], (pollIntrvl: number) => { intervalFn(pollIntrvl); }); };