Feature: Add size formatter

The `size` formatter returns the length of an array or string, or the
number of keys in an object.

Some APIs do not return a summary of their contents but only the full
list of contents. The `size` formatter can be used to still show such
count on a widget.
This commit is contained in:
Jacobo de Vera
2024-08-26 19:36:53 +01:00
parent 8ff68dd6bf
commit 4318cd6537
2 changed files with 23 additions and 1 deletions

View File

@@ -54,12 +54,17 @@ widget:
time: other key
color: theme # optional - defaults to "". Allowed values: `["theme", "adaptive", "black", "white"]`.
format: date # optional
- field: key
label: Number of things in array
format: size
```
Supported formats for the values are `text`, `number`, `float`, `percent`, `bytes`, `bitrate`, `date` and `relativeDate`.
Supported formats for the values are `text`, `number`, `float`, `percent`, `bytes`, `bitrate`, `size`, `date` and `relativeDate`.
The `dateStyle` and `timeStyle` options of the `date` format are passed directly to [Intl.DateTimeFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) and the `style` and `numeric` options of `relativeDate` are passed to [Intl.RelativeTimeFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat).
The `size` format will return the length of the array or string, or the number of keys in an object. This is then formatted as `number`.
## Example
For the following JSON object from the API:
@@ -100,6 +105,9 @@ mappings:
locations:
1: name # Citadel of Ricks
label: Location
- field: locations
label: Location count
format: size # 2
```
## Data Transformation

View File

@@ -4,6 +4,16 @@ import Container from "components/services/widget/container";
import Block from "components/services/widget/block";
import useWidgetAPI from "utils/proxy/use-widget-api";
function getLength(data) {
if ('length' in data) {
return data.length;
} else if (typeof data === 'object' && data !== null) {
return Object.keys(data).length;
} else {
return NaN;
}
}
function getValue(field, data) {
let value = data;
let lastField = field;
@@ -85,6 +95,10 @@ function formatValue(t, mapping, rawValue) {
numeric: mapping?.numeric,
});
break;
case "size":
value = getLength(value);
value = t("common.number", { value });
break;
case "text":
default:
// nothing