π A self-hostable personal dashboard built for you. Includes status-checking, widgets, themes, icon packs, a UI editor and tons more!
Vue awesomedashboarddockerhomelabhomepagemitnodejsorganizationproductivitypwaself-hostedstartpagevue
β¨ Adds scale, prefix and remap for custom-api widget (#2232)
Alicia Sykesb2e887162292
diff --git a/docs/widgets.md b/docs/widgets.mdindex ebca4c47..87804dc7 100644--- a/docs/widgets.md+++ b/docs/widgets.md@@ -3346,10 +3346,11 @@ 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`, `bytes`, `bitrate`, `date`, `relativeDate` or `size`+**`format`** | `string` | _Optional_ | One of `text` (default), `number`, `percent`, `bytes`, `bitrate`, `duration`, `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+**`remap`** | `array` | _Optional_ | Swap raw values for display text, e.g. `0` β `Down`. Each entry has `value` and `to`; an entry with `any: true` matches everything else**`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`@@ -3360,6 +3361,7 @@ 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`+- **`duration`** shows seconds as a compact time: `3665` β `1h 1m`- **`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 proxydiff --git a/src/utils/CustomApiHelpers.js b/src/utils/CustomApiHelpers.jsindex e4aa7e36..e9e1fdc7 100644--- a/src/utils/CustomApiHelpers.js+++ b/src/utils/CustomApiHelpers.js@@ -1,5 +1,5 @@/* Field resolution and value formatting for the CustomApi widget */-import { convertBytes, convertBitrate } from '@/utils/MiscHelpers';+import { convertBytes, convertBitrate, convertDuration } 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) => {@@ -50,6 +50,13 @@ const applyScale = (raw, scale) => {return (Number.isNaN(n) || !Number.isFinite(factor)) ? raw : n * factor;};+/* Swap a value for a matching remap entry's `to`, e.g. 0 β 'Down'. `any: true` matches all */+const applyRemap = (raw, remaps) => {+ if (!Array.isArray(remaps)) return raw;+ const match = remaps.find((r) => r && r.to !== undefined && (r.any || String(r.value) === String(raw)));+ return match ? match.to : raw;+};+/* Format a raw value per a mapping's `format`. `root` is the full response, used by `size` */const applyFormat = (raw, mapping, root) => {const format = mapping.format || 'text';@@ -64,10 +71,11 @@ const applyFormat = (raw, mapping, root) => {}if (raw == null) return '';- const value = applyScale(raw, mapping.scale);+ const value = applyScale(applyRemap(raw, mapping.remap), mapping.scale);switch (format) {- case 'number': {+ case 'number':+ case 'float': {const n = Number(value);return Number.isNaN(n) ? String(value) : new Intl.NumberFormat(locale).format(n);}@@ -82,6 +90,10 @@ const applyFormat = (raw, mapping, root) => {if (Number.isNaN(n)) return String(value);return format === 'bytes' ? convertBytes(n) : convertBitrate(n);}+ case 'duration': {+ const n = Number(value);+ return Number.isNaN(n) ? String(value) : convertDuration(n);+ }case 'date': {const date = new Date(value);if (Number.isNaN(date.getTime())) return String(value);diff --git a/src/utils/MiscHelpers.js b/src/utils/MiscHelpers.jsindex 67366894..be40c7cc 100644--- a/src/utils/MiscHelpers.js+++ b/src/utils/MiscHelpers.js@@ -114,6 +114,18 @@ export const convertBitrate = (bits, decimals = 2) => (convertToUnit(bits, 1000, ['bps', 'Kbps', 'Mbps', 'Gbps', 'Tbps', 'Pbps'], decimals));+/* Given a number of seconds returns more human duration, like '6d 9h' or '4m 20s' */+export const convertDuration = (seconds) => {+ let rest = Math.round(Math.abs(seconds));+ const parts = [];+ [['d', 86400], ['h', 3600], ['m', 60], ['s', 1]].forEach(([unit, size]) => {+ const amount = Math.floor(rest / size);+ rest -= amount * size;+ if (amount) parts.push(`${amount}${unit}`);+ });+ return parts.slice(0, 2).join(' ') || '0s';+};+/* 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.jsindex 0f31f547..ed586893 100644--- a/tests/unit/customapi-helpers.test.js+++ b/tests/unit/customapi-helpers.test.js@@ -42,6 +42,10 @@ describe('CustomApiHelpers - formatValue', () => {expect(formatValue('abc', { format: 'number', locale: 'en-US' })).toBe('abc');});+ it('float: is an alias of number', () => {+ expect(formatValue(1234.5, { format: 'float', locale: 'en-US' })).toBe('1,234.5');+ });+it('percent: treats the value as an already-computed percentage', () => {expect(formatValue(42, { format: 'percent', locale: 'en-US' })).toBe('42%');});@@ -84,6 +88,31 @@ describe('CustomApiHelpers - formatValue', () => {expect(formatValue(2500000, { format: 'bitrate' })).toBe('2.5 Mbps');});+ it('duration: shows seconds as a compact time', () => {+ expect(formatValue(93784, { format: 'duration' })).toBe('1d 2h');+ expect(formatValue(330, { format: 'duration' })).toBe('5m 30s');+ expect(formatValue(0, { format: 'duration' })).toBe('0s');+ });++ it('duration: passes through non-numeric input', () => {+ expect(formatValue('abc', { format: 'duration' })).toBe('abc');+ });++ it('remap: swaps a matching value', () => {+ const remap = [{ value: 0, to: 'Down' }, { value: 1, to: 'Up' }];+ expect(formatValue(1, { format: 'text', remap })).toBe('Up');+ expect(formatValue('1', { format: 'text', remap })).toBe('Up');+ });++ it('remap: `any` acts as a catch-all', () => {+ const remap = [{ value: 0, to: 'Down' }, { any: true, to: 'Unknown' }];+ expect(formatValue(7, { format: 'text', remap })).toBe('Unknown');+ });++ it('remap: leaves unmatched values alone', () => {+ expect(formatValue(7, { format: 'text', remap: [{ value: 0, to: 'Down' }] })).toBe('7');+ });+it('scale: multiplies by a numeric factor before formatting', () => {expect(formatValue(2, { format: 'number', scale: 1024, locale: 'en-US' })).toBe('2,048');});