Implemented strict linting standards and prettier formatting config. (#248)

* Implemented strict linting standards and prettier formatting config.

* More linter fixes and type updates.

* More linter updates and type fixes

* Remove noisy comments

* Linter and type updates

* Linter, formatting and type updates.

* Linter updates

* Type updates

* Type updates

* fixed all linter errors

* Fixed all linting, formatting and type issues.

* Resolve merge conflicts.
This commit is contained in:
Jas Singh
2024-09-14 16:20:05 -07:00
committed by GitHub
parent ff13e3dd3c
commit 2c72cc66d8
222 changed files with 13141 additions and 8433 deletions

View File

@@ -1,26 +1,25 @@
import GLib from "gi://GLib?version=2.0";
import { Binding } from "types/service";
import { Variable as VariableType } from "types/variable";
type GenericFunction = (...args: any[]) => any;
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<T>} targetVariable - The Variable to update with the function's result.
* @param {Array<VariableType<any>>} trackers - Array of trackers to watch.
* @param {Binding<any, any, unknown>} pollingInterval - The polling interval in milliseconds.
* @param {GenericFunction} someFunc - The function to execute at each interval, which updates the Variable.
* @param {...any} params - Parameters to pass to someFunc.
* @param {Array<Bind>} trackers - Array of trackers to watch.
* @param {Bind} pollingInterval - The polling interval in milliseconds.
* @param {GenericFunction<T, P>} someFunc - The function to execute at each interval, which updates the Variable.
* @param {...P} params - Parameters to pass to someFunc.
*/
export const pollVariable = <T>(
export const pollVariable = <T, P extends unknown[], F extends GenericFunction<T, P>>(
targetVariable: VariableType<T>,
trackers: Array<Binding<any, any, unknown>>,
pollingInterval: Binding<any, any, unknown>,
someFunc: GenericFunction,
...params: any[]
trackers: Array<Bind>,
pollingInterval: Bind,
someFunc: F,
...params: P
): void => {
let intervalInstance: number | null = null;
const intervalFn = (pollIntrvl: number) => {
const intervalFn = (pollIntrvl: number): void => {
if (intervalInstance !== null) {
GLib.source_remove(intervalInstance);
}
@@ -37,34 +36,37 @@ export const pollVariable = <T>(
/**
* @param {VariableType<T>} targetVariable - The Variable to update with the result of the command.
* @param {Binding<any, any, unknown>} pollingInterval - The polling interval in milliseconds.
* @param {Array<Bind>} 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.
* @param {...any} params - Parameters to pass to someFunc.
* @param {GenericFunction<T, [unknown, ...P]>} 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 = <T>(
export const pollVariableBash = <T, P extends unknown[], F extends GenericFunction<T, [string, ...P]>>(
targetVariable: VariableType<T>,
trackers: Array<Binding<any, any, unknown>>,
pollingInterval: Binding<any, any, unknown>,
trackers: Array<Bind>,
pollingInterval: Bind,
someCommand: string,
someFunc: (res: any, ...params: any[]) => T,
...params: any[]
someFunc: F,
...params: P
): void => {
let intervalInstance: number | null = null;
const intervalFn = (pollIntrvl: number) => {
const intervalFn = (pollIntrvl: number): void => {
if (intervalInstance !== null) {
GLib.source_remove(intervalInstance);
}
intervalInstance = Utils.interval(pollIntrvl, () => {
Utils.execAsync(`bash -c "${someCommand}"`).then((res: any) => {
try {
targetVariable.value = someFunc(res, ...params);
} catch (error) {
console.warn(`An error occurred when running interval bash function: ${error}`);
}
})
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}`));
});
};

View File

@@ -2,8 +2,10 @@ import { Option } from 'widget/settings/shared/Option';
import { Header } from 'widget/settings/shared/Header';
import options from 'options';
import Scrollable from 'types/widgets/scrollable';
import { Attribute, GtkWidget } from 'lib/types/widget';
export const CustomModuleSettings = () =>
export const CustomModuleSettings = (): Scrollable<GtkWidget, Attribute> =>
Widget.Scrollable({
vscroll: 'automatic',
hscroll: 'automatic',
@@ -12,11 +14,11 @@ export const CustomModuleSettings = () =>
class_name: 'menu-theme-page paged-container',
vertical: true,
children: [
/*
************************************
* GENERAL *
************************************
*/
/*
************************************
* GENERAL *
************************************
*/
Header('General'),
Option({
opt: options.bar.customModules.scrollSpeed,
@@ -24,11 +26,11 @@ export const CustomModuleSettings = () =>
type: 'number',
}),
/*
************************************
* RAM *
************************************
*/
/*
************************************
* RAM *
************************************
*/
Header('RAM'),
Option({
opt: options.bar.customModules.ram.label,
@@ -75,11 +77,11 @@ export const CustomModuleSettings = () =>
type: 'string',
}),
/*
************************************
* CPU *
************************************
*/
/*
************************************
* CPU *
************************************
*/
Header('CPU'),
Option({
opt: options.bar.customModules.cpu.label,
@@ -130,11 +132,11 @@ export const CustomModuleSettings = () =>
type: 'string',
}),
/*
************************************
* STORAGE *
************************************
*/
/*
************************************
* STORAGE *
************************************
*/
Header('Storage'),
Option({
opt: options.bar.customModules.storage.icon,
@@ -187,11 +189,11 @@ export const CustomModuleSettings = () =>
type: 'string',
}),
/*
************************************
* NETSTAT *
************************************
*/
/*
************************************
* NETSTAT *
************************************
*/
Header('Netstat'),
Option({
opt: options.bar.customModules.netstat.networkInterface,
@@ -204,17 +206,7 @@ export const CustomModuleSettings = () =>
opt: options.bar.customModules.netstat.icon,
title: 'Netstat Icon',
type: 'enum',
enums: [
'󰖟',
'󰇚',
'󰕒',
'󰛳',
'',
'󰣺',
'󰖩',
'',
'󰈀',
],
enums: ['󰖟', '󰇚', '󰕒', '󰛳', '', '󰣺', '󰖩', '', '󰈀'],
}),
Option({
opt: options.bar.customModules.netstat.label,
@@ -267,11 +259,11 @@ export const CustomModuleSettings = () =>
type: 'string',
}),
/*
************************************
* KEYBOARD LAYOUT *
************************************
*/
/*
************************************
* KEYBOARD LAYOUT *
************************************
*/
Header('Keyboard Layout'),
Option({
opt: options.bar.customModules.kbLayout.icon,
@@ -321,11 +313,11 @@ export const CustomModuleSettings = () =>
type: 'string',
}),
/*
************************************
* UPDATES *
************************************
*/
/*
************************************
* UPDATES *
************************************
*/
Header('Updates'),
Option({
opt: options.bar.customModules.updates.updateCommand,
@@ -336,17 +328,7 @@ export const CustomModuleSettings = () =>
opt: options.bar.customModules.updates.icon,
title: 'Updates Icon',
type: 'enum',
enums: [
'󰚰',
'󰇚',
'',
'󱑢',
'󱑣',
'󰏖',
'',
'󰏔',
'󰏗',
],
enums: ['󰚰', '󰇚', '', '󱑢', '󱑣', '󰏖', '', '󰏔', '󰏗'],
}),
Option({
opt: options.bar.customModules.updates.label,
@@ -367,7 +349,7 @@ export const CustomModuleSettings = () =>
opt: options.bar.customModules.updates.pollingInterval,
title: 'Polling Interval',
type: 'number',
subtitle: "WARNING: Be careful of your package manager\'s rate limit.",
subtitle: "WARNING: Be careful of your package manager's rate limit.",
min: 100,
max: 60 * 24 * 1000,
increment: 1000,
@@ -398,11 +380,11 @@ export const CustomModuleSettings = () =>
type: 'string',
}),
/*
************************************
* WEATHER *
************************************
*/
/*
************************************
* WEATHER *
************************************
*/
Header('Weather'),
Option({
opt: options.bar.customModules.weather.label,
@@ -446,11 +428,11 @@ export const CustomModuleSettings = () =>
type: 'string',
}),
/*
************************************
* POWER *
************************************
*/
/*
************************************
* POWER *
************************************
*/
Header('Power'),
Option({
opt: options.theme.bar.buttons.modules.power.spacing,
@@ -491,4 +473,3 @@ export const CustomModuleSettings = () =>
],
}),
});

View File

@@ -1,10 +1,10 @@
// @ts-expect-error
// @ts-expect-error: This import is a special directive that tells the compiler to use the GTop library
import GTop from 'gi://GTop';
let previousCpuData = new GTop.glibtop_cpu();
GTop.glibtop_get_cpu(previousCpuData);
export const computeCPU = () => {
export const computeCPU = (): number => {
const currentCpuData = new GTop.glibtop_cpu();
GTop.glibtop_get_cpu(currentCpuData);
@@ -17,5 +17,4 @@ export const computeCPU = () => {
previousCpuData = currentCpuData;
return cpuUsagePercentage;
}
};

View File

@@ -1,28 +1,21 @@
import options from "options";
import options from 'options';
// Module initializer
import { module } from "../module"
import { module } from '../module';
// import { CpuData } from "lib/types/customModules/cpu";
import Button from "types/widgets/button";
import Gtk from "types/@girs/gtk-3.0/gtk-3.0";
import Button from 'types/widgets/button';
import Gtk from 'types/@girs/gtk-3.0/gtk-3.0';
// Utility Methods
import { inputHandler } from "customModules/utils";
import { computeCPU } from "./computeCPU";
import { pollVariable } from "customModules/PollVar";
import { inputHandler } from 'customModules/utils';
import { computeCPU } from './computeCPU';
import { pollVariable } from 'customModules/PollVar';
import { Module } from 'lib/types/bar';
// All the user configurable options for the cpu module that are needed
const {
label,
round,
leftClick,
rightClick,
middleClick,
scrollUp,
scrollDown,
pollingInterval
} = options.bar.customModules.cpu;
const { label, round, leftClick, rightClick, middleClick, scrollUp, scrollDown, pollingInterval } =
options.bar.customModules.cpu;
export const cpuUsage = Variable(0);
@@ -37,21 +30,19 @@ pollVariable(
computeCPU,
);
export const Cpu = () => {
const renderLabel = (cpuUsg: number, rnd: boolean) => {
export const Cpu = (): Module => {
const renderLabel = (cpuUsg: number, rnd: boolean): string => {
return rnd ? `${Math.round(cpuUsg)}%` : `${cpuUsg.toFixed(2)}%`;
}
};
const cpuModule = module({
textIcon: "",
label: Utils.merge(
[cpuUsage.bind("value"), round.bind("value")],
(cpuUsg, rnd) => {
return renderLabel(cpuUsg, rnd);
}),
tooltipText: "CPU",
boxClass: "cpu",
showLabelBinding: label.bind("value"),
textIcon: '',
label: Utils.merge([cpuUsage.bind('value'), round.bind('value')], (cpuUsg, rnd) => {
return renderLabel(cpuUsg, rnd);
}),
tooltipText: 'CPU',
boxClass: 'cpu',
showLabelBinding: label.bind('value'),
props: {
setup: (self: Button<Gtk.Widget, Gtk.Widget>) => {
inputHandler(self, {
@@ -72,9 +63,8 @@ export const Cpu = () => {
},
});
},
}
},
});
return cpuModule;
}
};

View File

@@ -1,12 +1,18 @@
import { HyprctlDeviceLayout, HyprctlKeyboard, KbLabelType, LayoutKeys, LayoutValues } from "lib/types/customModules/kbLayout";
import { layoutMap } from "./layouts";
import {
HyprctlDeviceLayout,
HyprctlKeyboard,
KbLabelType,
LayoutKeys,
LayoutValues,
} from 'lib/types/customModules/kbLayout';
import { layoutMap } from './layouts';
export const getKeyboardLayout = (obj: string, format: KbLabelType) => {
let hyprctlDevices: HyprctlDeviceLayout = JSON.parse(obj);
let keyboards = hyprctlDevices['keyboards'];
export const getKeyboardLayout = (obj: string, format: KbLabelType): LayoutKeys | LayoutValues => {
const hyprctlDevices: HyprctlDeviceLayout = JSON.parse(obj);
const keyboards = hyprctlDevices['keyboards'];
if (keyboards.length === 0) {
return "No KB!"
return format === 'code' ? 'Unknown' : 'Unknown Layout';
}
let mainKb = keyboards.find((kb: HyprctlKeyboard) => kb.main);
@@ -15,8 +21,8 @@ export const getKeyboardLayout = (obj: string, format: KbLabelType) => {
mainKb = keyboards[keyboards.length - 1];
}
let layout: LayoutKeys = mainKb['active_keymap'] as LayoutKeys;
const layout: LayoutKeys = mainKb['active_keymap'] as LayoutKeys;
const foundLayout: LayoutValues = layoutMap[layout];
return format === "code" ? foundLayout || layout : layout;
}
return format === 'code' ? foundLayout || layout : layout;
};

View File

@@ -1,49 +1,50 @@
const hyprland = await Service.import("hyprland");
const hyprland = await Service.import('hyprland');
import options from "options";
import { module } from "../module"
import options from 'options';
import { module } from '../module';
import { inputHandler } from "customModules/utils";
import Gtk from "types/@girs/gtk-3.0/gtk-3.0";
import Button from "types/widgets/button";
import Label from "types/widgets/label";
import { getKeyboardLayout } from "./getLayout";
import { inputHandler } from 'customModules/utils';
import Gtk from 'types/@girs/gtk-3.0/gtk-3.0';
import Button from 'types/widgets/button';
import Label from 'types/widgets/label';
import { getKeyboardLayout } from './getLayout';
import { Module } from 'lib/types/bar';
const {
label,
labelType,
icon,
leftClick,
rightClick,
middleClick,
scrollUp,
scrollDown,
} = options.bar.customModules.kbLayout;
const { label, labelType, icon, leftClick, rightClick, middleClick, scrollUp, scrollDown } =
options.bar.customModules.kbLayout;
export const KbInput = () => {
export const KbInput = (): Module => {
const keyboardModule = module({
textIcon: icon.bind("value"),
tooltipText: "",
textIcon: icon.bind('value'),
tooltipText: '',
labelHook: (self: Label<Gtk.Widget>): void => {
self.hook(hyprland, () => {
Utils.execAsync('hyprctl devices -j')
.then((obj) => {
self.label = getKeyboardLayout(obj, labelType.value);
})
.catch((err) => { console.error(err); });
}, "keyboard-layout");
self.hook(
hyprland,
() => {
Utils.execAsync('hyprctl devices -j')
.then((obj) => {
self.label = getKeyboardLayout(obj, labelType.value);
})
.catch((err) => {
console.error(err);
});
},
'keyboard-layout',
);
self.hook(labelType, () => {
Utils.execAsync('hyprctl devices -j')
.then((obj) => {
self.label = getKeyboardLayout(obj, labelType.value);
})
.catch((err) => { console.error(err); });
.catch((err) => {
console.error(err);
});
});
},
boxClass: "kblayout",
showLabelBinding: label.bind("value"),
boxClass: 'kblayout',
showLabelBinding: label.bind('value'),
props: {
setup: (self: Button<Gtk.Widget, Gtk.Widget>) => {
inputHandler(self, {
@@ -68,6 +69,4 @@ export const KbInput = () => {
});
return keyboardModule;
}
};

File diff suppressed because it is too large Load Diff

View File

@@ -1,9 +1,9 @@
import { Module } from "lib/types/bar";
import { BarButtonStyles } from "lib/types/options";
import options from "options";
import Gtk from "types/@girs/gtk-3.0/gtk-3.0";
import { Binding } from "types/service";
import { Variable as VariableType } from "types/variable";
import { BarBoxChild, Module } from 'lib/types/bar';
import { BarButtonStyles } from 'lib/types/options';
import { Bind } from 'lib/types/variable';
import { GtkWidget } from 'lib/types/widget';
import options from 'options';
import Gtk from 'types/@girs/gtk-3.0/gtk-3.0';
const { style } = options.theme.bar.buttons;
@@ -16,69 +16,69 @@ export const module = ({
tooltipText,
boxClass,
props = {},
showLabelBinding = undefinedVar.bind("value"),
showLabelBinding = undefinedVar.bind('value'),
showLabel,
labelHook,
hook
}: Module) => {
const getIconWidget = () => {
hook,
}: Module): BarBoxChild => {
const getIconWidget = (): GtkWidget | undefined => {
let iconWidget: Gtk.Widget | undefined;
if (icon !== undefined) {
iconWidget = Widget.Icon({
class_name: `txt-icon bar-button-icon module-icon ${boxClass}`,
icon: icon
icon: icon,
}) as unknown as Gtk.Widget;
} else if (textIcon !== undefined) {
iconWidget = Widget.Label({
class_name: `txt-icon bar-button-icon module-icon ${boxClass}`,
label: textIcon
label: textIcon,
}) as unknown as Gtk.Widget;
}
return iconWidget;
}
};
return {
component: Widget.Box({
className: Utils.merge([style.bind("value"), showLabelBinding], (style: BarButtonStyles, shwLabel: boolean) => {
const shouldShowLabel = shwLabel || showLabel;
const styleMap = {
default: "style1",
split: "style2",
wave: "style3",
wave2: "style3",
};
return `${boxClass} ${styleMap[style]} ${!shouldShowLabel ? "no-label" : ""}`;
}),
className: Utils.merge(
[style.bind('value'), showLabelBinding],
(style: BarButtonStyles, shwLabel: boolean) => {
const shouldShowLabel = shwLabel || showLabel;
const styleMap = {
default: 'style1',
split: 'style2',
wave: 'style3',
wave2: 'style3',
};
return `${boxClass} ${styleMap[style]} ${!shouldShowLabel ? 'no-label' : ''}`;
},
),
tooltip_text: tooltipText,
children: Utils.merge(
[showLabelBinding],
(showLabelBinding): Gtk.Widget[] => {
const childrenArray: Gtk.Widget[] = [];
const iconWidget = getIconWidget();
children: Utils.merge([showLabelBinding], (showLabelBinding): Gtk.Widget[] => {
const childrenArray: Gtk.Widget[] = [];
const iconWidget = getIconWidget();
if (iconWidget !== undefined) {
childrenArray.push(iconWidget);
}
if (showLabelBinding) {
childrenArray.push(
Widget.Label({
class_name: `bar-button-label module-label ${boxClass}`,
label: label,
setup: labelHook,
}) as unknown as Gtk.Widget
);
}
return childrenArray;
if (iconWidget !== undefined) {
childrenArray.push(iconWidget);
}
) as Binding<VariableType<Gtk.Widget[]>, any, Gtk.Widget[]>,
if (showLabelBinding) {
childrenArray.push(
Widget.Label({
class_name: `bar-button-label module-label ${boxClass}`,
label: label,
setup: labelHook,
}) as unknown as Gtk.Widget,
);
}
return childrenArray;
}) as Bind,
setup: hook,
}),
tooltip_text: tooltipText,
isVisible: true,
boxClass,
props
props,
};
};

View File

@@ -71,7 +71,11 @@ const getNetworkUsage = (interfaceName: string = ''): NetworkUsage => {
return { name: '', rx: 0, tx: 0 };
};
export const computeNetwork = (round: VariableType<boolean>, interfaceNameVar: VariableType<string>, dataType: VariableType<RateUnit>): NetworkResourceData => {
export const computeNetwork = (
round: VariableType<boolean>,
interfaceNameVar: VariableType<string>,
dataType: VariableType<RateUnit>,
): NetworkResourceData => {
const rateUnit = dataType.value;
const interfaceName = interfaceNameVar ? interfaceNameVar.value : '';

View File

@@ -2,7 +2,7 @@ import options from 'options';
import { module } from '../module';
import { inputHandler } from 'customModules/utils';
import { computeNetwork } from './computeNetwork';
import { NetstatLabelType } from 'lib/types/bar';
import { Module, NetstatLabelType } from 'lib/types/bar';
import Gtk from 'types/@girs/gtk-3.0/gtk-3.0';
import Button from 'types/widgets/button';
import { NetworkResourceData } from 'lib/types/customModules/network';
@@ -23,9 +23,7 @@ const {
pollingInterval,
} = options.bar.customModules.netstat;
export const networkUsage = Variable<NetworkResourceData>(
GET_DEFAULT_NETSTAT_DATA(rateUnit.value),
);
export const networkUsage = Variable<NetworkResourceData>(GET_DEFAULT_NETSTAT_DATA(rateUnit.value));
pollVariable(
// Variable to poll and update with the result of the function passed in
@@ -48,11 +46,8 @@ pollVariable(
rateUnit,
);
export const Netstat = () => {
const renderNetworkLabel = (
lblType: NetstatLabelType,
network: NetworkResourceData,
): string => {
export const Netstat = (): Module => {
const renderNetworkLabel = (lblType: NetstatLabelType, network: NetworkResourceData): string => {
switch (lblType) {
case 'in':
return `${network.in}`;
@@ -88,19 +83,17 @@ export const Netstat = () => {
},
onScrollUp: {
fn: () => {
labelType.value =
NETWORK_LABEL_TYPES[
labelType.value = NETWORK_LABEL_TYPES[
(NETWORK_LABEL_TYPES.indexOf(labelType.value) + 1) % NETWORK_LABEL_TYPES.length
] as NetstatLabelType;
] as NetstatLabelType;
},
},
onScrollDown: {
fn: () => {
labelType.value =
NETWORK_LABEL_TYPES[
labelType.value = NETWORK_LABEL_TYPES[
(NETWORK_LABEL_TYPES.indexOf(labelType.value) - 1 + NETWORK_LABEL_TYPES.length) %
NETWORK_LABEL_TYPES.length
] as NetstatLabelType;
NETWORK_LABEL_TYPES.length
] as NetstatLabelType;
},
},
});
@@ -110,4 +103,3 @@ export const Netstat = () => {
return netstatModule;
};

View File

@@ -1,24 +1,18 @@
import options from "options";
import { module } from "../module"
import options from 'options';
import { module } from '../module';
import { inputHandler } from "customModules/utils";
import Gtk from "types/@girs/gtk-3.0/gtk-3.0";
import Button from "types/widgets/button";
import { inputHandler } from 'customModules/utils';
import Gtk from 'types/@girs/gtk-3.0/gtk-3.0';
import Button from 'types/widgets/button';
import { Module } from 'lib/types/bar';
const {
icon,
leftClick,
rightClick,
middleClick,
scrollUp,
scrollDown,
} = options.bar.customModules.power;
const { icon, leftClick, rightClick, middleClick, scrollUp, scrollDown } = options.bar.customModules.power;
export const Power = () => {
export const Power = (): Module => {
const powerModule = module({
tooltipText: "Power Menu",
textIcon: icon.bind("value"),
boxClass: "powermodule",
tooltipText: 'Power Menu',
textIcon: icon.bind('value'),
boxClass: 'powermodule',
props: {
setup: (self: Button<Gtk.Widget, Gtk.Widget>) => {
inputHandler(self, {
@@ -43,4 +37,4 @@ export const Power = () => {
});
return powerModule;
}
};

View File

@@ -1,9 +1,10 @@
const GLib = imports.gi.GLib;
import { divide } from 'customModules/utils';
import { GenericResourceData } from 'lib/types/customModules/generic';
import { Variable as VariableType } from 'types/variable';
export const calculateRamUsage = (round: VariableType<boolean>) => {
export const calculateRamUsage = (round: VariableType<boolean>): GenericResourceData => {
try {
const [success, meminfoBytes] = GLib.file_get_contents('/proc/meminfo');
@@ -26,17 +27,14 @@ export const calculateRamUsage = (round: VariableType<boolean>) => {
let usedRam = totalRamInBytes - availableRamInBytes;
usedRam = isNaN(usedRam) || usedRam < 0 ? 0 : usedRam;
return {
percentage: divide([totalRamInBytes, usedRam], round.value),
total: totalRamInBytes,
used: usedRam,
free: availableRamInBytes,
};
} catch (error) {
console.error('Error calculating RAM usage:', error);
return { total: 0, used: 0, percentage: 0 };
return { total: 0, used: 0, percentage: 0, free: 0 };
}
};

View File

@@ -1,62 +1,48 @@
import options from "options";
import options from 'options';
// Module initializer
import { module } from "../module"
import { module } from '../module';
// Types
import { GenericResourceData } from "lib/types/customModules/generic";
import Button from "types/widgets/button";
import Gtk from "types/@girs/gtk-3.0/gtk-3.0";
import { GenericResourceData } from 'lib/types/customModules/generic';
import Button from 'types/widgets/button';
import Gtk from 'types/@girs/gtk-3.0/gtk-3.0';
// Helper Methods
import { calculateRamUsage } from "./computeRam";
import { calculateRamUsage } from './computeRam';
// Utility Methods
import { formatTooltip, inputHandler, renderResourceLabel } from "customModules/utils";
import { ResourceLabelType } from "lib/types/bar";
import { formatTooltip, inputHandler, renderResourceLabel } from 'customModules/utils';
import { Module, ResourceLabelType } from 'lib/types/bar';
// Global Constants
import { LABEL_TYPES } from "lib/types/defaults/bar";
import { pollVariable } from "customModules/PollVar";
import { LABEL_TYPES } from 'lib/types/defaults/bar';
import { pollVariable } from 'customModules/PollVar';
// All the user configurable options for the ram module that are needed
const {
label,
labelType,
round,
leftClick,
rightClick,
middleClick,
pollingInterval
} = options.bar.customModules.ram;
const { label, labelType, round, leftClick, rightClick, middleClick, pollingInterval } = options.bar.customModules.ram;
const defaultRamData: GenericResourceData = { total: 0, used: 0, percentage: 0, free: 0 };
const ramUsage = Variable(defaultRamData);
const ramUsage = Variable<GenericResourceData>(defaultRamData);
pollVariable(
ramUsage,
[round.bind('value')],
pollingInterval.bind('value'),
calculateRamUsage,
round,
);
export const Ram = () => {
pollVariable(ramUsage, [round.bind('value')], pollingInterval.bind('value'), calculateRamUsage, round);
export const Ram = (): Module => {
const ramModule = module({
textIcon: "",
textIcon: '',
label: Utils.merge(
[ramUsage.bind("value"), labelType.bind("value"), round.bind("value")],
[ramUsage.bind('value'), labelType.bind('value'), round.bind('value')],
(rmUsg: GenericResourceData, lblTyp: ResourceLabelType, round: boolean) => {
const returnValue = renderResourceLabel(lblTyp, rmUsg, round);
return returnValue;
}),
tooltipText: labelType.bind("value").as(lblTyp => {
},
),
tooltipText: labelType.bind('value').as((lblTyp) => {
return formatTooltip('RAM', lblTyp);
}),
boxClass: "ram",
showLabelBinding: label.bind("value"),
boxClass: 'ram',
showLabelBinding: label.bind('value'),
props: {
setup: (self: Button<Gtk.Widget, Gtk.Widget>) => {
inputHandler(self, {
@@ -71,18 +57,22 @@ export const Ram = () => {
},
onScrollUp: {
fn: () => {
labelType.value = LABEL_TYPES[(LABEL_TYPES.indexOf(labelType.value) + 1) % LABEL_TYPES.length] as ResourceLabelType;
}
labelType.value = LABEL_TYPES[
(LABEL_TYPES.indexOf(labelType.value) + 1) % LABEL_TYPES.length
] as ResourceLabelType;
},
},
onScrollDown: {
fn: () => {
labelType.value = LABEL_TYPES[(LABEL_TYPES.indexOf(labelType.value) - 1 + LABEL_TYPES.length) % LABEL_TYPES.length] as ResourceLabelType;
}
labelType.value = LABEL_TYPES[
(LABEL_TYPES.indexOf(labelType.value) - 1 + LABEL_TYPES.length) % LABEL_TYPES.length
] as ResourceLabelType;
},
},
});
},
}
},
});
return ramModule;
}
};

View File

@@ -1,23 +1,20 @@
// @ts-expect-error
// @ts-expect-error is a special directive that tells the compiler to use the GTop library
import GTop from 'gi://GTop';
import { divide } from 'customModules/utils';
import { Variable as VariableType } from 'types/variable';
import { GenericResourceData } from 'lib/types/customModules/generic';
let previousFsUsage = new GTop.glibtop_fsusage();
export const computeStorage = (round: VariableType<boolean>) => {
export const computeStorage = (round: VariableType<boolean>): GenericResourceData => {
try {
const currentFsUsage = new GTop.glibtop_fsusage();
GTop.glibtop_get_fsusage(currentFsUsage, "/");
GTop.glibtop_get_fsusage(currentFsUsage, '/');
const total = currentFsUsage.blocks * currentFsUsage.block_size;
const available = currentFsUsage.bavail * currentFsUsage.block_size;
const used = total - available;
previousFsUsage = currentFsUsage;
return {
total,
used,
@@ -26,7 +23,6 @@ export const computeStorage = (round: VariableType<boolean>) => {
};
} catch (error) {
console.error('Error calculating RAM usage:', error);
return { total: 0, used: 0, percentage: 0 };
return { total: 0, used: 0, percentage: 0, free: 0 };
}
};

View File

@@ -1,52 +1,38 @@
import options from "options";
import { module } from "../module"
import options from 'options';
import { module } from '../module';
import { formatTooltip, inputHandler, renderResourceLabel } from "customModules/utils";
import { computeStorage } from "./computeStorage";
import { ResourceLabelType } from "lib/types/bar";
import { GenericResourceData } from "lib/types/customModules/generic";
import Gtk from "types/@girs/gtk-3.0/gtk-3.0";
import Button from "types/widgets/button";
import { LABEL_TYPES } from "lib/types/defaults/bar";
import { pollVariable } from "customModules/PollVar";
import { formatTooltip, inputHandler, renderResourceLabel } from 'customModules/utils';
import { computeStorage } from './computeStorage';
import { Module, ResourceLabelType } from 'lib/types/bar';
import { GenericResourceData } from 'lib/types/customModules/generic';
import Gtk from 'types/@girs/gtk-3.0/gtk-3.0';
import Button from 'types/widgets/button';
import { LABEL_TYPES } from 'lib/types/defaults/bar';
import { pollVariable } from 'customModules/PollVar';
const {
label,
labelType,
icon,
round,
leftClick,
rightClick,
middleClick,
pollingInterval
} = options.bar.customModules.storage;
const { label, labelType, icon, round, leftClick, rightClick, middleClick, pollingInterval } =
options.bar.customModules.storage;
const defaultStorageData = { total: 0, used: 0, percentage: 0, free: 0 };
const storageUsage = Variable(defaultStorageData);
const storageUsage = Variable<GenericResourceData>(defaultStorageData);
pollVariable(
storageUsage,
[round.bind('value')],
pollingInterval.bind('value'),
computeStorage,
round,
);
pollVariable(storageUsage, [round.bind('value')], pollingInterval.bind('value'), computeStorage, round);
export const Storage = () => {
export const Storage = (): Module => {
const storageModule = module({
textIcon: icon.bind("value"),
textIcon: icon.bind('value'),
label: Utils.merge(
[storageUsage.bind("value"), labelType.bind("value"), round.bind("value")],
[storageUsage.bind('value'), labelType.bind('value'), round.bind('value')],
(storage: GenericResourceData, lblTyp: ResourceLabelType, round: boolean) => {
return renderResourceLabel(lblTyp, storage, round);
}),
tooltipText: labelType.bind("value").as(lblTyp => {
},
),
tooltipText: labelType.bind('value').as((lblTyp) => {
return formatTooltip('Storage', lblTyp);
}),
boxClass: "storage",
showLabelBinding: label.bind("value"),
boxClass: 'storage',
showLabelBinding: label.bind('value'),
props: {
setup: (self: Button<Gtk.Widget, Gtk.Widget>) => {
inputHandler(self, {
@@ -61,18 +47,22 @@ export const Storage = () => {
},
onScrollUp: {
fn: () => {
labelType.value = LABEL_TYPES[(LABEL_TYPES.indexOf(labelType.value) + 1) % LABEL_TYPES.length] as ResourceLabelType;
}
labelType.value = LABEL_TYPES[
(LABEL_TYPES.indexOf(labelType.value) + 1) % LABEL_TYPES.length
] as ResourceLabelType;
},
},
onScrollDown: {
fn: () => {
labelType.value = LABEL_TYPES[(LABEL_TYPES.indexOf(labelType.value) - 1 + LABEL_TYPES.length) % LABEL_TYPES.length] as ResourceLabelType;
}
labelType.value = LABEL_TYPES[
(LABEL_TYPES.indexOf(labelType.value) - 1 + LABEL_TYPES.length) % LABEL_TYPES.length
] as ResourceLabelType;
},
},
});
},
}
},
});
return storageModule;
}
};

View File

@@ -1,106 +1,146 @@
import { Option } from "widget/settings/shared/Option";
import { Header } from "widget/settings/shared/Header";
import { Option } from 'widget/settings/shared/Option';
import { Header } from 'widget/settings/shared/Header';
import options from "options";
import options from 'options';
import Scrollable from 'types/widgets/scrollable';
import { Attribute, GtkWidget } from 'lib/types/widget';
export const CustomModuleTheme = () => {
export const CustomModuleTheme = (): Scrollable<GtkWidget, Attribute> => {
return Widget.Scrollable({
vscroll: "automatic",
hscroll: "automatic",
class_name: "menu-theme-page customModules paged-container",
vscroll: 'automatic',
hscroll: 'automatic',
class_name: 'menu-theme-page customModules paged-container',
child: Widget.Box({
class_name: "bar-theme-page paged-container",
class_name: 'bar-theme-page paged-container',
vertical: true,
children: [
Header('RAM'),
Option({ opt: options.theme.bar.buttons.modules.ram.text, title: 'Text', type: 'color' }),
Option({ opt: options.theme.bar.buttons.modules.ram.icon, title: 'Icon', type: 'color' }),
Option({ opt: options.theme.bar.buttons.modules.ram.background, title: 'Label Background', type: 'color' }),
Option({
opt: options.theme.bar.buttons.modules.ram.background,
title: 'Label Background',
type: 'color',
}),
Option({
opt: options.theme.bar.buttons.modules.ram.icon_background,
title: 'Icon Background',
subtitle: 'Applies a background color to the icon section of the button.\nRequires \'split\' button styling.',
type: 'color'
subtitle:
"Applies a background color to the icon section of the button.\nRequires 'split' button styling.",
type: 'color',
}),
Header('CPU'),
Option({ opt: options.theme.bar.buttons.modules.cpu.text, title: 'Text', type: 'color' }),
Option({ opt: options.theme.bar.buttons.modules.cpu.icon, title: 'Icon', type: 'color' }),
Option({ opt: options.theme.bar.buttons.modules.cpu.background, title: 'Label Background', type: 'color' }),
Option({
opt: options.theme.bar.buttons.modules.cpu.background,
title: 'Label Background',
type: 'color',
}),
Option({
opt: options.theme.bar.buttons.modules.cpu.icon_background,
title: 'Icon Background',
subtitle: 'Applies a background color to the icon section of the button.\nRequires \'split\' button styling.',
type: 'color'
subtitle:
"Applies a background color to the icon section of the button.\nRequires 'split' button styling.",
type: 'color',
}),
Header('Storage'),
Option({ opt: options.theme.bar.buttons.modules.storage.text, title: 'Text', type: 'color' }),
Option({ opt: options.theme.bar.buttons.modules.storage.icon, title: 'Icon', type: 'color' }),
Option({ opt: options.theme.bar.buttons.modules.storage.background, title: 'Label Background', type: 'color' }),
Option({
opt: options.theme.bar.buttons.modules.storage.background,
title: 'Label Background',
type: 'color',
}),
Option({
opt: options.theme.bar.buttons.modules.storage.icon_background,
title: 'Icon Background',
subtitle: 'Applies a background color to the icon section of the button.\nRequires \'split\' button styling.',
type: 'color'
subtitle:
"Applies a background color to the icon section of the button.\nRequires 'split' button styling.",
type: 'color',
}),
Header('Netstat'),
Option({ opt: options.theme.bar.buttons.modules.netstat.text, title: 'Text', type: 'color' }),
Option({ opt: options.theme.bar.buttons.modules.netstat.icon, title: 'Icon', type: 'color' }),
Option({ opt: options.theme.bar.buttons.modules.netstat.background, title: 'Label Background', type: 'color' }),
Option({
opt: options.theme.bar.buttons.modules.netstat.background,
title: 'Label Background',
type: 'color',
}),
Option({
opt: options.theme.bar.buttons.modules.netstat.icon_background,
title: 'Icon Background',
subtitle: 'Applies a background color to the icon section of the button.\nRequires \'split\' button styling.',
type: 'color'
subtitle:
"Applies a background color to the icon section of the button.\nRequires 'split' button styling.",
type: 'color',
}),
Header('Keyboard Layout'),
Option({ opt: options.theme.bar.buttons.modules.kbLayout.text, title: 'Text', type: 'color' }),
Option({ opt: options.theme.bar.buttons.modules.kbLayout.icon, title: 'Icon', type: 'color' }),
Option({ opt: options.theme.bar.buttons.modules.kbLayout.background, title: 'Label Background', type: 'color' }),
Option({
opt: options.theme.bar.buttons.modules.kbLayout.background,
title: 'Label Background',
type: 'color',
}),
Option({
opt: options.theme.bar.buttons.modules.kbLayout.icon_background,
title: 'Icon Background',
subtitle: 'Applies a background color to the icon section of the button.\nRequires \'split\' button styling.',
type: 'color'
subtitle:
"Applies a background color to the icon section of the button.\nRequires 'split' button styling.",
type: 'color',
}),
Header('Updates'),
Option({ opt: options.theme.bar.buttons.modules.updates.text, title: 'Text', type: 'color' }),
Option({ opt: options.theme.bar.buttons.modules.updates.icon, title: 'Icon', type: 'color' }),
Option({ opt: options.theme.bar.buttons.modules.updates.background, title: 'Label Background', type: 'color' }),
Option({
opt: options.theme.bar.buttons.modules.updates.background,
title: 'Label Background',
type: 'color',
}),
Option({
opt: options.theme.bar.buttons.modules.updates.icon_background,
title: 'Icon Background',
subtitle: 'Applies a background color to the icon section of the button.\nRequires \'split\' button styling.',
type: 'color'
subtitle:
"Applies a background color to the icon section of the button.\nRequires 'split' button styling.",
type: 'color',
}),
Header('Weather'),
Option({ opt: options.theme.bar.buttons.modules.weather.icon, title: 'Icon', type: 'color' }),
Option({ opt: options.theme.bar.buttons.modules.weather.text, title: 'Text', type: 'color' }),
Option({ opt: options.theme.bar.buttons.modules.weather.background, title: 'Label Background', type: 'color' }),
Option({
opt: options.theme.bar.buttons.modules.weather.background,
title: 'Label Background',
type: 'color',
}),
Option({
opt: options.theme.bar.buttons.modules.weather.icon_background,
title: 'Icon Background',
subtitle: 'Applies a background color to the icon section of the button.\nRequires \'split\' button styling.',
type: 'color'
subtitle:
"Applies a background color to the icon section of the button.\nRequires 'split' button styling.",
type: 'color',
}),
Header('Power'),
Option({ opt: options.theme.bar.buttons.modules.power.icon, title: 'Icon', type: 'color' }),
Option({ opt: options.theme.bar.buttons.modules.power.background, title: 'Label Background', type: 'color' }),
Option({
opt: options.theme.bar.buttons.modules.power.background,
title: 'Label Background',
type: 'color',
}),
Option({
opt: options.theme.bar.buttons.modules.power.icon_background,
title: 'Icon Background',
subtitle: 'Applies a background color to the icon section of the button.\nRequires \'split\' button styling.',
type: 'color'
subtitle:
"Applies a background color to the icon section of the button.\nRequires 'split' button styling.",
type: 'color',
}),
]
})
})
}
],
}),
});
};

View File

@@ -1,11 +1,12 @@
import options from "options";
import { module } from "../module"
import options from 'options';
import { module } from '../module';
import { inputHandler } from "customModules/utils";
import Gtk from "types/@girs/gtk-3.0/gtk-3.0";
import Button from "types/widgets/button";
import { Variable as VariableType } from "types/variable";
import { pollVariableBash } from "customModules/PollVar";
import { inputHandler } from 'customModules/utils';
import Gtk from 'types/@girs/gtk-3.0/gtk-3.0';
import Button from 'types/widgets/button';
import { Variable as VariableType } from 'types/variable';
import { pollVariableBash } from 'customModules/PollVar';
import { Module } from 'lib/types/bar';
const {
updateCommand,
@@ -20,12 +21,12 @@ const {
scrollDown,
} = options.bar.customModules.updates;
const pendingUpdates: VariableType<string> = Variable(" 0");
const pendingUpdates: VariableType<string> = Variable(' 0');
const processUpdateCount = (updateCount: string) => {
const processUpdateCount = (updateCount: string): string => {
if (!padZero.value) return updateCount;
return `${updateCount.padStart(2, '0')}`;
}
};
pollVariableBash(
pendingUpdates,
@@ -35,13 +36,13 @@ pollVariableBash(
processUpdateCount,
);
export const Updates = () => {
export const Updates = (): Module => {
const updatesModule = module({
textIcon: icon.bind("value"),
tooltipText: pendingUpdates.bind("value").as(v => `${v} updates available`),
boxClass: "updates",
label: pendingUpdates.bind("value"),
showLabelBinding: label.bind("value"),
textIcon: icon.bind('value'),
tooltipText: pendingUpdates.bind('value').as((v) => `${v} updates available`),
boxClass: 'updates',
label: pendingUpdates.bind('value'),
showLabelBinding: label.bind('value'),
props: {
setup: (self: Button<Gtk.Widget, Gtk.Widget>) => {
inputHandler(self, {
@@ -66,7 +67,4 @@ export const Updates = () => {
});
return updatesModule;
}
};

View File

@@ -1,6 +1,8 @@
import { ResourceLabelType } from 'lib/types/bar';
import { GenericResourceData } from 'lib/types/customModules/generic';
import { GenericResourceData, Postfix } from 'lib/types/customModules/generic';
import { InputHandlerEvents } from 'lib/types/customModules/utils';
import { ThrottleFn, ThrottleFnCallback } from 'lib/types/utils';
import { GtkWidget } from 'lib/types/widget';
import { Binding } from 'lib/utils';
import { openMenu } from 'modules/bar/utils';
import options from 'options';
@@ -13,14 +15,11 @@ const { scrollSpeed } = options.bar.customModules;
export const runAsyncCommand = (
cmd: string,
fn: Function,
events: { clicked: any; event: Gdk.Event }
fn: (output: string) => void,
events: { clicked: Button<GtkWidget, GtkWidget>; event: Gdk.Event },
): void => {
if (cmd.startsWith('menu:')) {
// if the command starts with 'menu:', then it is a menu command
// and we should App.toggleMenu("menuName") based on the input menu:menuName. Ignoring spaces and case
const menuName = cmd.split(':')[1].trim().toLowerCase();
openMenu(events.clicked, events.event, `${menuName}menu`);
return;
@@ -32,15 +31,10 @@ export const runAsyncCommand = (
fn(output);
}
})
.catch((err) =>
console.error(`Error running command "${cmd}": ${err})`)
);
.catch((err) => console.error(`Error running command "${cmd}": ${err})`));
};
export function throttle<T extends (...args: any[]) => void>(
func: T,
limit: number
): T {
export function throttle<T extends ThrottleFn>(func: T, limit: number): T {
let inThrottle: boolean;
return function (this: ThisParameterType<T>, ...args: Parameters<T>) {
if (!inThrottle) {
@@ -53,31 +47,23 @@ export function throttle<T extends (...args: any[]) => void>(
} as T;
}
export const throttledScrollHandler = (interval: number) =>
throttle((cmd: string, fn: Function | undefined) => {
export const throttledScrollHandler = (interval: number): ThrottleFn =>
throttle((cmd: string, fn: ThrottleFnCallback) => {
Utils.execAsync(`bash -c "${cmd}"`)
.then((output) => {
if (fn !== undefined) {
fn(output);
}
})
.catch((err) =>
console.error(`Error running command "${cmd}": ${err}`)
);
.catch((err) => console.error(`Error running command "${cmd}": ${err}`));
}, 200 / interval);
const dummyVar = Variable('');
export const inputHandler = (
self: Button<Gtk.Widget, Gtk.Widget>,
{
onPrimaryClick,
onSecondaryClick,
onMiddleClick,
onScrollUp,
onScrollDown,
}: InputHandlerEvents
) => {
{ onPrimaryClick, onSecondaryClick, onMiddleClick, onScrollUp, onScrollDown }: InputHandlerEvents,
): void => {
const sanitizeInput = (input: VariableType<string>): string => {
if (input === undefined) {
return '';
@@ -89,46 +75,25 @@ export const inputHandler = (
const interval = scrollSpeed.value;
const throttledHandler = throttledScrollHandler(interval);
self.on_primary_click = (clicked: any, event: Gdk.Event) =>
runAsyncCommand(
sanitizeInput(onPrimaryClick?.cmd || dummyVar),
onPrimaryClick.fn,
{ clicked, event }
);
self.on_primary_click = (clicked: Button<GtkWidget, GtkWidget>, event: Gdk.Event): void =>
runAsyncCommand(sanitizeInput(onPrimaryClick?.cmd || dummyVar), onPrimaryClick.fn, { clicked, event });
self.on_secondary_click = (clicked: any, event: Gdk.Event) =>
runAsyncCommand(
sanitizeInput(onSecondaryClick?.cmd || dummyVar),
onSecondaryClick.fn,
{ clicked, event }
);
self.on_secondary_click = (clicked: Button<GtkWidget, GtkWidget>, event: Gdk.Event): void =>
runAsyncCommand(sanitizeInput(onSecondaryClick?.cmd || dummyVar), onSecondaryClick.fn, { clicked, event });
self.on_middle_click = (clicked: any, event: Gdk.Event) =>
runAsyncCommand(
sanitizeInput(onMiddleClick?.cmd || dummyVar),
onMiddleClick.fn,
{ clicked, event }
);
self.on_middle_click = (clicked: Button<GtkWidget, GtkWidget>, event: Gdk.Event): void =>
runAsyncCommand(sanitizeInput(onMiddleClick?.cmd || dummyVar), onMiddleClick.fn, { clicked, event });
self.on_scroll_up = () =>
throttledHandler(
sanitizeInput(onScrollUp?.cmd || dummyVar),
onScrollUp.fn
);
self.on_scroll_up = (): void => throttledHandler(sanitizeInput(onScrollUp?.cmd || dummyVar), onScrollUp.fn);
self.on_scroll_down = () =>
throttledHandler(
sanitizeInput(onScrollDown?.cmd || dummyVar),
onScrollDown.fn
);
self.on_scroll_down = (): void =>
throttledHandler(sanitizeInput(onScrollDown?.cmd || dummyVar), onScrollDown.fn);
};
// Initial setup of event handlers
updateHandlers();
const sanitizeVariable = (
someVar: VariableType<string> | undefined
): Binding<string> => {
const sanitizeVariable = (someVar: VariableType<string> | undefined): Binding<string> => {
if (someVar === undefined || typeof someVar.bind !== 'function') {
return dummyVar.bind('value');
}
@@ -145,37 +110,36 @@ export const inputHandler = (
sanitizeVariable(onScrollUp),
sanitizeVariable(onScrollDown),
],
updateHandlers
updateHandlers,
);
};
export const divide = ([total, used]: number[], round: boolean) => {
export const divide = ([total, used]: number[], round: boolean): number => {
const percentageTotal = (used / total) * 100;
if (round) {
return total > 0 ? Math.round(percentageTotal) : 0;
}
return total > 0 ? parseFloat(percentageTotal.toFixed(2)) : 0;
};
export const formatSizeInKiB = (sizeInBytes: number, round: boolean) => {
const sizeInGiB = sizeInBytes / (1024 ** 1);
export const formatSizeInKiB = (sizeInBytes: number, round: boolean): number => {
const sizeInGiB = sizeInBytes / 1024 ** 1;
return round ? Math.round(sizeInGiB) : parseFloat(sizeInGiB.toFixed(2));
};
export const formatSizeInMiB = (sizeInBytes: number, round: boolean) => {
const sizeInGiB = sizeInBytes / (1024 ** 2);
export const formatSizeInMiB = (sizeInBytes: number, round: boolean): number => {
const sizeInGiB = sizeInBytes / 1024 ** 2;
return round ? Math.round(sizeInGiB) : parseFloat(sizeInGiB.toFixed(2));
};
export const formatSizeInGiB = (sizeInBytes: number, round: boolean) => {
const sizeInGiB = sizeInBytes / (1024 ** 3);
export const formatSizeInGiB = (sizeInBytes: number, round: boolean): number => {
const sizeInGiB = sizeInBytes / 1024 ** 3;
return round ? Math.round(sizeInGiB) : parseFloat(sizeInGiB.toFixed(2));
};
export const formatSizeInTiB = (sizeInBytes: number, round: boolean) => {
const sizeInGiB = sizeInBytes / (1024 ** 4);
export const formatSizeInTiB = (sizeInBytes: number, round: boolean): number => {
const sizeInGiB = sizeInBytes / 1024 ** 4;
return round ? Math.round(sizeInGiB) : parseFloat(sizeInGiB.toFixed(2));
};
export const autoFormatSize = (sizeInBytes: number, round: boolean) => {
export const autoFormatSize = (sizeInBytes: number, round: boolean): number => {
// auto convert to GiB, MiB, KiB, TiB, or bytes
if (sizeInBytes >= 1024 ** 4) return formatSizeInTiB(sizeInBytes, round);
if (sizeInBytes >= 1024 ** 3) return formatSizeInGiB(sizeInBytes, round);
@@ -183,22 +147,18 @@ export const autoFormatSize = (sizeInBytes: number, round: boolean) => {
if (sizeInBytes >= 1024 ** 1) return formatSizeInKiB(sizeInBytes, round);
return sizeInBytes;
}
};
export const getPostfix = (sizeInBytes: number) => {
export const getPostfix = (sizeInBytes: number): Postfix => {
if (sizeInBytes >= 1024 ** 4) return 'TiB';
if (sizeInBytes >= 1024 ** 3) return 'GiB';
if (sizeInBytes >= 1024 ** 2) return 'MiB';
if (sizeInBytes >= 1024 ** 1) return 'KiB';
return 'B';
}
};
export const renderResourceLabel = (
lblType: ResourceLabelType,
rmUsg: GenericResourceData,
round: boolean
) => {
export const renderResourceLabel = (lblType: ResourceLabelType, rmUsg: GenericResourceData, round: boolean): string => {
const { used, total, percentage, free } = rmUsg;
const formatFunctions = {
@@ -206,7 +166,7 @@ export const renderResourceLabel = (
GiB: formatSizeInGiB,
MiB: formatSizeInMiB,
KiB: formatSizeInKiB,
B: (size: number, _: boolean) => size
B: (size: number): number => size,
};
// Get them datas in proper GiB, MiB, KiB, TiB, or bytes
@@ -218,20 +178,20 @@ export const renderResourceLabel = (
const formatUsed = formatFunctions[postfix] || formatFunctions['B'];
const usedSizeFormatted = formatUsed(used, round);
if (lblType === "used/total") {
if (lblType === 'used/total') {
return `${usedSizeFormatted}/${totalSizeFormatted} ${postfix}`;
}
if (lblType === "used") {
if (lblType === 'used') {
return `${autoFormatSize(used, round)} ${getPostfix(used)}`;
}
if (lblType === "free") {
if (lblType === 'free') {
return `${autoFormatSize(free, round)} ${getPostfix(free)}`;
}
return `${percentage}%`;
};
export const formatTooltip = (dataType: string, lblTyp: ResourceLabelType) => {
export const formatTooltip = (dataType: string, lblTyp: ResourceLabelType): string => {
switch (lblTyp) {
case 'used':
return `Used ${dataType}`;
@@ -244,4 +204,4 @@ export const formatTooltip = (dataType: string, lblTyp: ResourceLabelType) => {
default:
return '';
}
}
};

View File

@@ -1,40 +1,30 @@
import options from "options";
import { module } from "../module"
import options from 'options';
import { module } from '../module';
import { inputHandler } from "customModules/utils";
import Gtk from "types/@girs/gtk-3.0/gtk-3.0";
import Button from "types/widgets/button";
import { getWeatherStatusTextIcon, globalWeatherVar } from "globals/weather";
import { inputHandler } from 'customModules/utils';
import Gtk from 'types/@girs/gtk-3.0/gtk-3.0';
import Button from 'types/widgets/button';
import { getWeatherStatusTextIcon, globalWeatherVar } from 'globals/weather';
import { Module } from 'lib/types/bar';
const {
label,
unit,
leftClick,
rightClick,
middleClick,
scrollUp,
scrollDown,
} = options.bar.customModules.weather;
const { label, unit, leftClick, rightClick, middleClick, scrollUp, scrollDown } = options.bar.customModules.weather;
export const Weather = () => {
export const Weather = (): Module => {
const weatherModule = module({
textIcon: Utils.merge([globalWeatherVar.bind("value")], (wthr) => {
textIcon: Utils.merge([globalWeatherVar.bind('value')], (wthr) => {
const weatherStatusIcon = getWeatherStatusTextIcon(wthr);
return weatherStatusIcon;
}),
tooltipText: globalWeatherVar.bind("value").as(v => `Weather Status: ${v.current.condition.text}`),
boxClass: "weather-custom",
label: Utils.merge(
[globalWeatherVar.bind("value"), unit.bind("value")],
(wthr, unt) => {
if (unt === "imperial") {
return `${Math.ceil(wthr.current.temp_f)}° F`;
} else {
return `${Math.ceil(wthr.current.temp_c)}° C`;
}
},
),
showLabelBinding: label.bind("value"),
tooltipText: globalWeatherVar.bind('value').as((v) => `Weather Status: ${v.current.condition.text}`),
boxClass: 'weather-custom',
label: Utils.merge([globalWeatherVar.bind('value'), unit.bind('value')], (wthr, unt) => {
if (unt === 'imperial') {
return `${Math.ceil(wthr.current.temp_f)}° F`;
} else {
return `${Math.ceil(wthr.current.temp_c)}° C`;
}
}),
showLabelBinding: label.bind('value'),
props: {
setup: (self: Button<Gtk.Widget, Gtk.Widget>) => {
inputHandler(self, {
@@ -59,8 +49,4 @@ export const Weather = () => {
});
return weatherModule;
}
};