Refactor Label component for consistency and clarity in format handling

This commit is contained in:
Supertiger
2025-08-02 08:40:37 +01:00
parent 40ac8c5eb4
commit c3c9d99967

View File

@@ -8,14 +8,14 @@ interface LabelOpts {
states: string[]; states: string[];
"format-icons"?: string[]; "format-icons"?: string[];
}; };
module: Module module: Module;
interval?: number; interval?: number;
update: () => void; update: () => void;
} }
export const createLabel = (opts: LabelOpts) => { export const createLabel = (opts: LabelOpts) => {
let format = ""; let format = "";
const getMarkup = () => { const getFormat = () => {
if (!opts.config) return undefined; if (!opts.config) return undefined;
if (!format) { if (!format) {
return opts.config?.format || undefined; return opts.config?.format || undefined;
@@ -29,12 +29,12 @@ export const createLabel = (opts: LabelOpts) => {
} }
const set = (data: Record<string, any>) => { const set = (data: Record<string, any>) => {
const markup = getMarkup() as string | undefined; const format = getFormat() as string | undefined;
if (!markup) { if (!format) {
console.error("No format found"); console.error("No format found");
return "N/A"; return "N/A";
} }
const result = markup.replace(/\{(\w+)\}/g, (match, key) => { const result = format.replace(/\{(\w+)\}/g, (match, key) => {
return data[key] !== undefined ? data[key] : match; return data[key] !== undefined ? data[key] : match;
}); });
@@ -62,9 +62,8 @@ export const createLabel = (opts: LabelOpts) => {
return ""; return "";
} }
const entries = Object.entries(states) as unknown as [string, number][]; const entries = Object.entries(states) as unknown as [string, number][];
entries.sort((a, b) => {
entries.sort((a, b) => {
if (lesser) { if (lesser) {
return a[1] - b[1]; return a[1] - b[1];
} }
@@ -78,15 +77,14 @@ export const createLabel = (opts: LabelOpts) => {
} else { } else {
opts.module.element.classList.remove(state[0]); opts.module.element.classList.remove(state[0]);
} }
}) });
return valid_state; return valid_state;
};
}
return { return {
element, element,
set, set,
getIcon, getIcon,
getState getState,
}; };
}; };