import classNames from "classnames"; import { useTranslation } from "next-i18next/pages"; import { formatValue, getColor, getValue } from "./utils"; import Block from "components/services/widget/block"; import Container from "components/services/widget/container"; import * as shvl from "utils/config/shvl"; import useWidgetAPI from "utils/proxy/use-widget-api"; export default function Component({ service }) { const { t } = useTranslation(); const { widget } = service; const { mappings = [], refreshInterval = 10000, display = "block" } = widget; const { data: customData, error: customError } = useWidgetAPI(widget, null, { refreshInterval: Math.max(1000, refreshInterval), }); // if mappings includes an error field and the data contains an error field then show data even if there is an error const mappingsIncludesError = Array.isArray(mappings) && mappings.find((mapping) => mapping.field === "error"); const errorIsData = customData && typeof customData === "object" && "error" in customData; if (customError && !(mappingsIncludesError && errorIsData)) { return ; } if (!customData) { switch (display) { case "dynamic-list": return (
Loading...
); case "list": return (
{mappings.map((mapping) => (
{mapping.label}
-
))}
); default: return ( {mappings.slice(0, 4).map((item) => ( ))} ); } } switch (display) { case "dynamic-list": let listItems = customData; if (mappings.items) listItems = shvl.get(customData, mappings.items, null); let error; if (!listItems || !Array.isArray(listItems)) { error = { message: "Unable to find items" }; } const name = mappings.name; const label = mappings.label; if (!name || !label) { error = { message: "Name and label properties are required" }; } if (error) { return ; } const target = mappings.target; if (mappings.limit && parseInt(mappings.limit, 10) > 0) { listItems.splice(mappings.limit); } return (
{listItems.length === 0 ? (
No items found
) : ( listItems.map((item, index) => { const itemName = shvl.get(item, name, item[name]) ?? ""; const itemLabel = shvl.get(item, label, item[label]) ?? ""; const itemUrl = target ? [...target.matchAll(/\{(.*?)\}/g)] .map((match) => match[1]) .reduce((url, targetTemplate) => { const value = shvl.get(item, targetTemplate, item[targetTemplate]) ?? ""; return url.replaceAll(`{${targetTemplate}}`, value); }, target) : null; const className = "bg-theme-200/50 dark:bg-theme-900/20 rounded-sm m-1 flex-1 flex flex-row items-center justify-between p-1 text-xs"; return itemUrl ? (
{itemName}
{formatValue(t, mappings, itemLabel)}
) : (
{itemName}
{formatValue(t, mappings, itemLabel)}
); }) )}
); case "list": return (
{mappings.map((mapping) => (
{mapping.label}
{formatValue(t, mapping, getValue(mapping.field, customData))}
{mapping.additionalField && (
{formatValue(t, mapping.additionalField, getValue(mapping.additionalField.field, customData))}
)}
))}
); default: return ( {mappings.slice(0, 4).map((mapping) => ( ))} ); } }