Feature: customapi info widget (#7168)

This commit is contained in:
shamoon
2026-09-22 21:03:51 -07:00
committed by GitHub
parent b8ed72a03f
commit e0be80085e
15 changed files with 629 additions and 153 deletions
@@ -0,0 +1,53 @@
import classNames from "classnames";
import { useTranslation } from "next-i18next/pages";
import { TbApi } from "react-icons/tb";
import useSWR from "swr";
import Container from "../widget/container";
import Error from "../widget/error";
import Raw from "../widget/raw";
import WidgetLabel from "../widget/widget_label";
import ResolvedIcon from "components/resolvedicon";
import { formatValue, getValue } from "widgets/customapi/utils";
export default function CustomApi({ options }) {
const { t } = useTranslation();
const { index, icon, label, mappings = [], refreshInterval = 10000 } = options;
const { data, error } = useSWR(`/api/widgets/customapi?${new URLSearchParams({ index }).toString()}`, {
refreshInterval: Math.max(1000, refreshInterval),
});
if (error || (data?.error && !mappings.some((mapping) => mapping.field === "error"))) {
return <Error options={options} />;
}
return (
<Container options={options} additionalClassNames="information-widget-customapi">
<Raw>
<div className="flex flex-row items-center">
<div className="flex-none mr-2">
{icon ? (
<ResolvedIcon icon={icon} width={24} height={24} />
) : (
<TbApi className="w-6 h-6 text-theme-800 dark:text-theme-200" />
)}
</div>
<div className={classNames("flex flex-wrap items-center gap-0.5", !data && "animate-pulse")}>
{mappings.map((mapping) => (
<div key={mapping.label} className="flex flex-col items-center justify-center px-1 text-xs">
<span className="text-theme-800 dark:text-theme-200">{mapping.label}</span>
<span className="text-theme-800/70 dark:text-theme-200/50">
{data ? formatValue(t, mapping, getValue(mapping.field, data)) : "-"}
</span>
</div>
))}
</div>
</div>
{label && <WidgetLabel label={label} />}
</Raw>
</Container>
);
}
@@ -0,0 +1,117 @@
// @vitest-environment jsdom
import { screen } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { renderWithProviders } from "test-utils/render-with-providers";
const { useSWR } = vi.hoisted(() => ({ useSWR: vi.fn() }));
vi.mock("swr", () => ({ default: useSWR }));
vi.mock("components/resolvedicon", () => ({
default: ({ icon }) => <div data-testid="resolved-icon" data-icon={icon} />,
}));
import CustomApi from "./customapi";
const settings = { settings: { target: "_self" } };
describe("components/widgets/customapi", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("shows GitHub repo stats once loaded, with the fallback icon and a label", () => {
const options = {
index: 6,
label: "Homepage",
refreshInterval: 300000,
mappings: [
{ field: "stargazers_count", label: "Stars", format: "number" },
{ field: "open_issues_count", label: "Open", format: "number" },
{ field: "forks_count", label: "Forks", format: "number" },
],
};
useSWR.mockReturnValue({ data: undefined, error: undefined });
const { container, rerender } = renderWithProviders(<CustomApi options={options} />, settings);
expect(useSWR).toHaveBeenCalledWith("/api/widgets/customapi?index=6", { refreshInterval: 300000 });
expect(screen.getAllByText("-")).toHaveLength(3);
expect(screen.queryByTestId("resolved-icon")).toBeNull();
expect(container.querySelector("svg")).not.toBeNull();
useSWR.mockReturnValue({
data: { stargazers_count: 32809, open_issues_count: 1, forks_count: 2127, owner: { login: "gethomepage" } },
error: undefined,
});
rerender(<CustomApi options={options} />);
expect(screen.queryByText("-")).toBeNull();
expect(screen.getByText("Stars").nextSibling).toHaveTextContent("32809");
expect(screen.getByText("Open").nextSibling).toHaveTextContent("1");
expect(screen.getByText("Forks").nextSibling).toHaveTextContent("2127");
expect(screen.getByText("Homepage")).toHaveClass("information-widget-label");
});
it("shows a nested weather value with a configured icon and suffix", () => {
useSWR.mockReturnValue({
data: { current: { time: "2026-09-22T20:15", temperature_2m: 7.8, wind_speed_10m: 12.4 } },
error: undefined,
});
renderWithProviders(
<CustomApi
options={{
index: 7,
icon: "mdi-thermometer",
mappings: [{ field: "current.temperature_2m", label: "Temp", format: "float", suffix: "°C" }],
}}
/>,
settings,
);
expect(useSWR).toHaveBeenCalledWith("/api/widgets/customapi?index=7", { refreshInterval: 10000 });
expect(screen.getByTestId("resolved-icon")).toHaveAttribute("data-icon", "mdi-thermometer");
expect(screen.getByText("7.8 °C")).toBeInTheDocument();
});
it("shows a status API's error field as data when it is mapped", () => {
useSWR.mockReturnValue({ data: { error: "E_NONE", pending: 3 }, error: undefined });
renderWithProviders(
<CustomApi
options={{
index: 0,
mappings: [
{ field: "error", label: "Status", remap: [{ value: "E_NONE", to: "OK" }] },
{ field: "pending", label: "Queue", format: "number" },
],
}}
/>,
settings,
);
expect(screen.queryByText("widget.api_error")).toBeNull();
expect(screen.getByText("OK")).toBeInTheDocument();
expect(screen.getByText("3")).toBeInTheDocument();
});
it("shows the error state when the upstream API fails, clamping a too-fast refresh", () => {
useSWR.mockReturnValue({
data: { error: { message: "HTTP Error", url: "api.github.com (see logs for details)" } },
error: undefined,
});
renderWithProviders(
<CustomApi
options={{ index: 6, refreshInterval: 500, mappings: [{ field: "stargazers_count", label: "Stars" }] }}
/>,
settings,
);
expect(useSWR).toHaveBeenCalledWith("/api/widgets/customapi?index=6", { refreshInterval: 1000 });
expect(screen.getByText("widget.api_error")).toBeInTheDocument();
expect(screen.queryByText("Stars")).toBeNull();
});
});
+1
View File
@@ -16,6 +16,7 @@ const widgetMappings = {
longhorn: dynamic(() => import("components/widgets/longhorn/longhorn")),
kubernetes: dynamic(() => import("components/widgets/kubernetes/kubernetes")),
stocks: dynamic(() => import("components/widgets/stocks/stocks")),
customapi: dynamic(() => import("components/widgets/customapi/customapi")),
};
export default function Widget({ widget, style }) {