nixos-configs/modules/ags/config/widgets/misc/persist.ts
matt1432 7d64a1fe25
All checks were successful
Discord / discord commits (push) Has been skipped
feat(ags): transfer remaining bar stuff from v1
2025-02-28 00:59:30 -05:00

49 lines
1.2 KiB
TypeScript

import { execAsync, readFileAsync, timeout, GLib, type Variable } from 'astal';
const { get_home_dir } = GLib;
export default <T>({
name,
variable,
condition = true,
whenTrue = condition,
whenFalse = false,
}: {
name: string
variable: Variable<T>
condition?: boolean | string
whenTrue?: boolean | string
whenFalse?: boolean | string
}) => {
const cacheFile = `${get_home_dir()}/.cache/ags/.${name}`;
const stateCmd = () => ['bash', '-c',
`echo ${variable.get() === condition} > ${cacheFile}`];
const monitorState = () => {
variable.subscribe(() => {
execAsync(stateCmd()).catch(print);
});
};
readFileAsync(cacheFile)
.then((content) => {
// JSON.parse was the only way I found to reliably
// convert a string of 'true' or 'false' into a bool
const value = (JSON.parse(content) ? whenTrue : whenFalse) as T;
variable.set(value);
timeout(1000, () => {
monitorState();
});
})
.catch(() => {
execAsync(stateCmd())
.then(() => {
monitorState();
})
.catch(print);
});
};