Skip to content

armgit / dashy

Public Imported from GitHub
0

πŸš€ A self-hostable personal dashboard built for you. Includes status-checking, widgets, themes, icon packs, a UI editor and tons more!

✨ Configurable number formatting for custom-api (#2232)

Alicia Sykes3c4a9446e4c5
diff --git a/docs/widgets.md b/docs/widgets.md
index 17f07cde..ebca4c47 100644
--- a/docs/widgets.md
+++ b/docs/widgets.md
@@ -3346,7 +3346,10 @@ Each item in `mappings` accepts:
--- | --- | --- | ---
**`field`** | `string` | _Optional_ | Dot-path to the value, e.g. `path.to.key` or `items.0.name`. Omit to use the response root (useful with `size`)
**`label`** | `string` | _Optional_ | Label shown beside the value
-**`format`** | `string` | _Optional_ | One of `text` (default), `number`, `percent`, `date`, `relativeDate` or `size`
+**`format`** | `string` | _Optional_ | One of `text` (default), `number`, `percent`, `bytes`, `bitrate`, `date`, `relativeDate` or `size`
+**`scale`** | `number` or `string` | _Optional_ | Multiply the value before formatting. A number or fraction string, e.g. `1024` or `1/16`
+**`prefix`** | `string` | _Optional_ | Text prepended to the formatted value
+**`suffix`** | `string` | _Optional_ | Text appended to the formatted value
**`locale`** | `string` | _Optional_ | Locale for `number`/`percent`/`date`/`relativeDate`, e.g. `nl`. Defaults to the browser locale
**`dateStyle`** | `string` | _Optional_ | For `date` format. One of `full`, `long` (default), `medium`, `short`
**`timeStyle`** | `string` | _Optional_ | For `date` format. One of `full`, `long`, `medium`, `short`
@@ -3356,6 +3359,8 @@ Each item in `mappings` accepts:
Notes:
- **`percent`** treats the value as an already-computed percentage, so `42` is shown as `42%`
+- **`bytes`** and **`bitrate`** auto-select a unit: `1073741824` β†’ `1 GB`, `2500000` β†’ `2.5 Mbps`
+- **`scale`** is applied before formatting, useful for unit conversions β€” e.g. for an API reporting kilobytes, `scale: 1024` with `format: bytes`
- **`size`** returns the number of items in an array (or keys in an object) β€” pair it with an omitted `field` to count the response root
- For APIs that don't send CORS headers (most self-hosted services), set the widget-level `useProxy: true` to route the request through Dashy's server-side proxy
@@ -3378,6 +3383,24 @@ Notes:
format: relativeDate
```
+Or, human-readable disk usage from a [Glances](https://nicolargo.github.io/glances/) instance:
+
+```yaml
+- type: customapi
+ useProxy: true
+ options:
+ url: http://192.168.0.1:61208/api/4/fs
+ mappings:
+ - field: 0.mnt_point
+ label: Mount
+ - field: 0.used
+ label: Used
+ format: bytes
+ - field: 0.percent
+ label: Used %
+ format: percent
+```
+
#### Info
- **CORS**: 🟠 Depends on target API (use `useProxy: true` if blocked)
diff --git a/src/utils/CustomApiHelpers.js b/src/utils/CustomApiHelpers.js
index a0d8ff4d..e4aa7e36 100644
--- a/src/utils/CustomApiHelpers.js
+++ b/src/utils/CustomApiHelpers.js
@@ -1,4 +1,5 @@
/* Field resolution and value formatting for the CustomApi widget */
+import { convertBytes, convertBitrate } from '@/utils/MiscHelpers';
/* Get a nested value from an object by dot-path, e.g. 'a.b.0.c'. Empty path returns the root */
export const resolveField = (obj, path) => {
@@ -40,8 +41,17 @@ const formatRelativeDate = (raw, mapping, locale) => {
return rtf.format(Math.round(diffSecs / period.secs), period.unit);
};
+/* Multiply a numeric value by a mapping's `scale` β€” a number or fraction string like '1/16' */
+const applyScale = (raw, scale) => {
+ if (!scale) return raw;
+ const n = Number(raw);
+ const [top, bottom = 1] = String(scale).split('/').map(Number);
+ const factor = top / bottom;
+ return (Number.isNaN(n) || !Number.isFinite(factor)) ? raw : n * factor;
+};
+
/* Format a raw value per a mapping's `format`. `root` is the full response, used by `size` */
-export const formatValue = (raw, mapping = {}, root) => {
+const applyFormat = (raw, mapping, root) => {
const format = mapping.format || 'text';
const locale = mapping.locale || navigator.language;
@@ -54,27 +64,40 @@ export const formatValue = (raw, mapping = {}, root) => {
}
if (raw == null) return '';
+ const value = applyScale(raw, mapping.scale);
switch (format) {
case 'number': {
- const n = Number(raw);
- return Number.isNaN(n) ? String(raw) : new Intl.NumberFormat(locale).format(n);
+ const n = Number(value);
+ return Number.isNaN(n) ? String(value) : new Intl.NumberFormat(locale).format(n);
}
case 'percent': {
- const n = Number(raw);
- return Number.isNaN(n) ? String(raw)
+ const n = Number(value);
+ return Number.isNaN(n) ? String(value)
: new Intl.NumberFormat(locale, { style: 'percent', maximumFractionDigits: 2 }).format(n / 100);
}
+ case 'bytes':
+ case 'bitrate': {
+ const n = Number(value);
+ if (Number.isNaN(n)) return String(value);
+ return format === 'bytes' ? convertBytes(n) : convertBitrate(n);
+ }
case 'date': {
- const date = new Date(raw);
- if (Number.isNaN(date.getTime())) return String(raw);
+ const date = new Date(value);
+ if (Number.isNaN(date.getTime())) return String(value);
const opts = { dateStyle: mapping.dateStyle || 'long' };
if (mapping.timeStyle) opts.timeStyle = mapping.timeStyle;
return new Intl.DateTimeFormat(locale, opts).format(date);
}
case 'relativeDate':
- return formatRelativeDate(raw, mapping, locale);
+ return formatRelativeDate(value, mapping, locale);
default:
- return String(raw);
+ return String(value);
}
};
+
+/* Formatted value, wrapped with any `prefix`/`suffix` */
+export const formatValue = (raw, mapping = {}, root) => {
+ const out = applyFormat(raw, mapping, root);
+ return out === '' ? out : `${mapping.prefix || ''}${out}${mapping.suffix || ''}`;
+};
diff --git a/src/utils/MiscHelpers.js b/src/utils/MiscHelpers.js
index 71501231..67366894 100644
--- a/src/utils/MiscHelpers.js
+++ b/src/utils/MiscHelpers.js
@@ -97,15 +97,23 @@ export const capitalize = (str) => {
return words.replace(/\w\S*/g, (w) => (w.replace(/^\w/, (c) => c.toUpperCase())));
};
-/* Given a mem size in bytes, will return it in appropriate unit */
-export const convertBytes = (bytes, decimals = 2) => {
- if (bytes === 0) return '0 Bytes';
- const k = 1024;
- const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
- const i = Math.floor(Math.log(bytes) / Math.log(k));
- return `${parseFloat((bytes / (k ** i)).toFixed(decimals))} ${sizes[i]}`;
+/* Scales a value into the largest fitting unit from `sizes`, at base `k` */
+const convertToUnit = (value, k, sizes, decimals) => {
+ const magnitude = Math.floor(Math.log(Math.abs(value)) / Math.log(k));
+ const i = Math.min(Math.max(magnitude, 0), sizes.length - 1);
+ return `${parseFloat((value / (k ** i)).toFixed(decimals))} ${sizes[i]}`;
};
+/* Given a mem size in bytes, will return it in appropriate unit */
+export const convertBytes = (bytes, decimals = 2) => (
+ convertToUnit(bytes, 1024, ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'], decimals)
+);
+
+/* Given a rate in bits per second, will return it in appropriate unit */
+export const convertBitrate = (bits, decimals = 2) => (
+ convertToUnit(bits, 1000, ['bps', 'Kbps', 'Mbps', 'Gbps', 'Tbps', 'Pbps'], decimals)
+);
+
/* Round a number to thousands, millions, billions or trillions and suffix
* with K, M, B or T respectively, e.g. 4_294_967_295 => 4.3B */
export const formatNumber = (number, decimals = 1) => {
diff --git a/tests/unit/customapi-helpers.test.js b/tests/unit/customapi-helpers.test.js
index 171c44fe..0f31f547 100644
--- a/tests/unit/customapi-helpers.test.js
+++ b/tests/unit/customapi-helpers.test.js
@@ -62,6 +62,48 @@ describe('CustomApiHelpers - formatValue', () => {
it('size: counts object keys', () => {
expect(formatValue({ a: 1, b: 2 }, { format: 'size' }, { a: 1, b: 2 })).toBe('2');
});
+
+ it('bytes: auto-selects a readable unit', () => {
+ expect(formatValue(1073741824, { format: 'bytes' })).toBe('1 GB');
+ });
+
+ it('bytes: passes through non-numeric input', () => {
+ expect(formatValue('abc', { format: 'bytes' })).toBe('abc');
+ });
+
+ it('bytes: handles zero and values below one unit', () => {
+ expect(formatValue(0, { format: 'bytes' })).toBe('0 Bytes');
+ expect(formatValue(0.5, { format: 'bytes' })).toBe('0.5 Bytes');
+ });
+
+ it('bytes: keeps the sign of negative values', () => {
+ expect(formatValue(-1073741824, { format: 'bytes' })).toBe('-1 GB');
+ });
+
+ it('bitrate: auto-selects a readable unit', () => {
+ expect(formatValue(2500000, { format: 'bitrate' })).toBe('2.5 Mbps');
+ });
+
+ it('scale: multiplies by a numeric factor before formatting', () => {
+ expect(formatValue(2, { format: 'number', scale: 1024, locale: 'en-US' })).toBe('2,048');
+ });
+
+ it('scale: accepts a fraction string', () => {
+ expect(formatValue(32, { format: 'number', scale: '1/16', locale: 'en-US' })).toBe('2');
+ });
+
+ it('scale: ignores an invalid factor', () => {
+ expect(formatValue(5, { format: 'number', scale: 'abc', locale: 'en-US' })).toBe('5');
+ expect(formatValue(5, { format: 'number', scale: '1/0', locale: 'en-US' })).toBe('5');
+ });
+
+ it('prefix and suffix wrap the formatted value', () => {
+ expect(formatValue(42, { format: 'number', prefix: '$', suffix: ' USD', locale: 'en-US' })).toBe('$42 USD');
+ });
+
+ it('prefix/suffix are skipped when the value is empty', () => {
+ expect(formatValue(null, { format: 'text', suffix: ' TB' })).toBe('');
+ });
});
describe('CustomApiHelpers - adaptiveColor', () => {