A modern and easy to use dashboard. 80+ integrations. 20K+ icons built in. Authentication out of the box. No YAML, drag and drop configuration.
feat(integrations): add Thingport integration and widgets (#7223)
Tautvydas Derzinskas47bacbfc5acf
diff --git a/apps/docs/docs/integrations/thingport/img/add-integration.png b/apps/docs/docs/integrations/thingport/img/add-integration.pngnew file mode 100644index 000000000..ef0914da3Binary files /dev/null and b/apps/docs/docs/integrations/thingport/img/add-integration.png differdiff --git a/apps/docs/docs/integrations/thingport/img/search-engine-list.png b/apps/docs/docs/integrations/thingport/img/search-engine-list.pngnew file mode 100644index 000000000..fadbf3c19Binary files /dev/null and b/apps/docs/docs/integrations/thingport/img/search-engine-list.png differdiff --git a/apps/docs/docs/integrations/thingport/img/spotlight-tport-dark.png b/apps/docs/docs/integrations/thingport/img/spotlight-tport-dark.pngnew file mode 100644index 000000000..79204c783Binary files /dev/null and b/apps/docs/docs/integrations/thingport/img/spotlight-tport-dark.png differdiff --git a/apps/docs/docs/integrations/thingport/img/spotlight-tport-light.png b/apps/docs/docs/integrations/thingport/img/spotlight-tport-light.pngnew file mode 100644index 000000000..5b1f74d8eBinary files /dev/null and b/apps/docs/docs/integrations/thingport/img/spotlight-tport-light.png differdiff --git a/apps/docs/docs/integrations/thingport/index.mdx b/apps/docs/docs/integrations/thingport/index.mdxnew file mode 100644index 000000000..f463deb1a--- /dev/null+++ b/apps/docs/docs/integrations/thingport/index.mdx@@ -0,0 +1,69 @@+---+title: "Thingport"+description: "Self-hosted library for organizing and previewing your 3D printing models."+hide_title: true+---++import { IntegrationHeader } from "@site/src/components/integrations/header";+import { IntegrationCapabilites } from "@site/src/components/integrations/widgets";+import { AddingIntegration } from "@site/src/components/integrations/adding";+import { IntegrationSecrets } from "@site/src/components/integrations/secrets";+import { IconSearch } from "@tabler/icons-react";+import { thingportIntegration } from ".";+import { thingportLibraryStatsWidget } from "@site/docs/widgets/thingport-library-stats";+import { thingportModelsWidget } from "@site/docs/widgets/thingport-models";+import { thingportFeaturedModelWidget } from "@site/docs/widgets/thingport-featured-model";+import { thingportActivityHeatmapWidget } from "@site/docs/widgets/thingport-activity-heatmap";++<IntegrationHeader integration={thingportIntegration} categories={["Miscellaneous"]} />++Thingport provides library totals, lists of your recently added, most viewed and most printed models, a featured model of the day and your activity history. Use the URL of the Thingport web interface, not the backend container.++### Widgets & Capabilities++<IntegrationCapabilites+ items={[+ { widget: thingportLibraryStatsWidget },+ { widget: thingportModelsWidget },+ { widget: thingportFeaturedModelWidget },+ { widget: thingportActivityHeatmapWidget },+ {+ capability: {+ icon: IconSearch,+ name: "Search",+ description: "Search models, collections and tags through the integration API.",+ path: "../../management/search-engines/#from-integration",+ },+ },+ ]}+/>++### Adding the integration++<AddingIntegration />++import addIntegration from "./img/add-integration.png";++<img src={addIntegration.src} alt="New Thingport integration form with name, URL and API key" width={640} />++### Secrets++<IntegrationSecrets+ secrets={[+ {+ credentials: ["apiKey"],+ steps: [+ "Open your Thingport instance",+ "Go to your profile",+ "Generate an API token",+ "Copy the token, it is shown only once",+ ],+ },+ ]}+/>++### Integration search++The integration search API supports models, collections and tags. Thingport can be selected as an integration search engine, but Spotlight currently does not display its results.++The API token is read-only and shows the library of the user who created it. The [Statistics widget](/docs/widgets/stats) can also combine Thingport totals with other sources.diff --git a/apps/docs/docs/integrations/thingport/index.ts b/apps/docs/docs/integrations/thingport/index.tsnew file mode 100644index 000000000..148ae8cd3--- /dev/null+++ b/apps/docs/docs/integrations/thingport/index.ts@@ -0,0 +1,8 @@+import { IntegrationDefinition } from "@site/src/types";++export const thingportIntegration: IntegrationDefinition = {+ name: "Thingport",+ description: "Self-hosted library for organizing and previewing your 3D printing models.",+ iconUrl: "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/thingport.svg",+ path: "../../integrations/thingport",+};diff --git a/apps/docs/docs/management/search-engines/index.mdx b/apps/docs/docs/management/search-engines/index.mdxindex 8fa2e9c96..deea05e0c 100644--- a/apps/docs/docs/management/search-engines/index.mdx+++ b/apps/docs/docs/management/search-engines/index.mdx@@ -52,6 +52,10 @@ Homarr will replace the `%s` with the term that the user entered.- Bing: `https://www.bing.com/search?q=%s`- YouTube: `https://www.youtube.com/results?search_query=%s`+#### From integration++Integration search engines can be configured for Jellyseerr, Overseerr, Seerr and [Thingport](../../integrations/thingport), but Spotlight currently does not display their results. Use the dedicated media request search mode below for Jellyseerr, Overseerr and Seerr.+## Media request searchJellyseerr, Overseerr, and Seerr integrations have a dedicated **Spotlight mode** for searching and requesting media.diff --git a/apps/docs/docs/widgets/thingport-activity-heatmap/img/day-tooltip.png b/apps/docs/docs/widgets/thingport-activity-heatmap/img/day-tooltip.pngnew file mode 100644index 000000000..6f1884a13Binary files /dev/null and b/apps/docs/docs/widgets/thingport-activity-heatmap/img/day-tooltip.png differdiff --git a/apps/docs/docs/widgets/thingport-activity-heatmap/img/sizes-dark.png b/apps/docs/docs/widgets/thingport-activity-heatmap/img/sizes-dark.pngnew file mode 100644index 000000000..b75a12eb7Binary files /dev/null and b/apps/docs/docs/widgets/thingport-activity-heatmap/img/sizes-dark.png differdiff --git a/apps/docs/docs/widgets/thingport-activity-heatmap/img/sizes-light.png b/apps/docs/docs/widgets/thingport-activity-heatmap/img/sizes-light.pngnew file mode 100644index 000000000..fb1e09849Binary files /dev/null and b/apps/docs/docs/widgets/thingport-activity-heatmap/img/sizes-light.png differdiff --git a/apps/docs/docs/widgets/thingport-activity-heatmap/index.mdx b/apps/docs/docs/widgets/thingport-activity-heatmap/index.mdxnew file mode 100644index 000000000..a0cb98805--- /dev/null+++ b/apps/docs/docs/widgets/thingport-activity-heatmap/index.mdx@@ -0,0 +1,56 @@+---+title: "Thingport Activity Heatmap"+description: "Shows a year of your Thingport activity as a heatmap, like your Thingport profile."+hide_title: true+---++import { WidgetInteractionGuide } from "@site/src/components/widgets/interactions";++import { WidgetHeader } from "@site/src/components/widgets/header";+import { AddingWidget } from "@site/src/components/widgets/adding";+import { WidgetConfig } from "@site/src/components/widgets/configuration";+import { WidgetIntegrations } from "@site/src/components/widgets/integrations";+import { thingportActivityHeatmapWidget } from ".";+import { thingportIntegration } from "@site/docs/integrations/thingport";++<WidgetHeader widget={thingportActivityHeatmapWidget} categories={["Miscellaneous"]} />++This widget shows your Thingport activity for the last 12 months, the same heatmap as on your Thingport profile. Each square is a day, and the busier the day, the darker the square. Hover over a day to see how many models you imported, uploaded, downloaded, opened in a slicer or deleted.++Use the year picker to show an earlier year. When the widget is too narrow for the whole year, it shows the most recent weeks.++### Screenshots++The widget at several grid sizes, in dark and light mode.++import sizesDark from "./img/sizes-dark.png";+import sizesLight from "./img/sizes-light.png";++<div className="flex gap-2 flex-wrap">+ <img src={sizesDark.src} alt="Thingport Activity Heatmap widget at several sizes in dark mode" width={720} />+ <img src={sizesLight.src} alt="Thingport Activity Heatmap widget at several sizes in light mode" width={720} />+</div>++Hovering over a day shows what happened on it.++import dayTooltip from "./img/day-tooltip.png";++<img+ src={dayTooltip.src}+ alt="Activity heatmap tooltip listing imported, uploaded and deleted models for one day"+ width={720}+/>++### Supported Integrations++<WidgetIntegrations items={[{ integration: thingportIntegration }]} />++<WidgetInteractionGuide advancedView={false} />++### Adding the widget++<AddingWidget />++### Configuration++<WidgetConfig configuration={thingportActivityHeatmapWidget.configuration} />diff --git a/apps/docs/docs/widgets/thingport-activity-heatmap/index.ts b/apps/docs/docs/widgets/thingport-activity-heatmap/index.tsnew file mode 100644index 000000000..652114b7c--- /dev/null+++ b/apps/docs/docs/widgets/thingport-activity-heatmap/index.ts@@ -0,0 +1,37 @@+import { WidgetDefinition } from "@site/src/types";+import { IconCalendarStats } from "@tabler/icons-react";++export const thingportActivityHeatmapWidget: WidgetDefinition = {+ icon: IconCalendarStats,+ name: "Thingport Activity Heatmap",+ description: "Shows a year of your Thingport activity as a heatmap, like your Thingport profile.",+ path: "../../widgets/thingport-activity-heatmap",+ configuration: {+ items: [+ {+ name: "Show title",+ description: "Displays the Thingport logo and a title above the widget",+ values: { type: "boolean" },+ defaultValue: "no",+ },+ {+ name: "First day of the week",+ description: "The weekday each column starts on",+ values: { type: "select", options: ["Sunday", "Monday"] },+ defaultValue: "Sunday",+ },+ {+ name: "Show total",+ description: "Displays the number of activities in the shown period",+ values: { type: "boolean" },+ defaultValue: "yes",+ },+ {+ name: "Show legend",+ description: "Displays the less-to-more color scale",+ values: { type: "boolean" },+ defaultValue: "yes",+ },+ ],+ },+};diff --git a/apps/docs/docs/widgets/thingport-featured-model/img/sizes-dark.png b/apps/docs/docs/widgets/thingport-featured-model/img/sizes-dark.pngnew file mode 100644index 000000000..a11c70dd2Binary files /dev/null and b/apps/docs/docs/widgets/thingport-featured-model/img/sizes-dark.png differdiff --git a/apps/docs/docs/widgets/thingport-featured-model/img/sizes-light.png b/apps/docs/docs/widgets/thingport-featured-model/img/sizes-light.pngnew file mode 100644index 000000000..23a49f0f4Binary files /dev/null and b/apps/docs/docs/widgets/thingport-featured-model/img/sizes-light.png differdiff --git a/apps/docs/docs/widgets/thingport-featured-model/index.mdx b/apps/docs/docs/widgets/thingport-featured-model/index.mdxnew file mode 100644index 000000000..465e4dc7a--- /dev/null+++ b/apps/docs/docs/widgets/thingport-featured-model/index.mdx@@ -0,0 +1,54 @@+---+title: "Thingport Featured Model"+description: "Shows one model from your Thingport library each day, spinning in 3D."+hide_title: true+---++import { WidgetInteractionGuide } from "@site/src/components/widgets/interactions";++import { WidgetHeader } from "@site/src/components/widgets/header";+import { AddingWidget } from "@site/src/components/widgets/adding";+import { WidgetConfig } from "@site/src/components/widgets/configuration";+import { WidgetIntegrations } from "@site/src/components/widgets/integrations";+import { thingportFeaturedModelWidget } from ".";+import { thingportIntegration } from "@site/docs/integrations/thingport";++<WidgetHeader widget={thingportFeaturedModelWidget} categories={["Miscellaneous"]} />++This widget shows the same featured model as the Thingport dashboard, a new one each day. Drag the model to turn it, and select it to open it in Thingport.++The 3D preview needs an STL model, or a 3MF model that Thingport has already prepared a preview for. Other models show their thumbnail instead.++### Screenshots++The widget at several grid sizes, in dark and light mode.++import sizesDark from "./img/sizes-dark.png";+import sizesLight from "./img/sizes-light.png";++<div className="flex gap-2 flex-wrap">+ <img+ src={sizesDark.src}+ alt="Thingport Featured Model widget showing a 3D model at several sizes in dark mode"+ width={720}+ />+ <img+ src={sizesLight.src}+ alt="Thingport Featured Model widget showing a 3D model at several sizes in light mode"+ width={720}+ />+</div>++### Supported Integrations++<WidgetIntegrations items={[{ integration: thingportIntegration }]} />++<WidgetInteractionGuide advancedView={false} />++### Adding the widget++<AddingWidget />++### Configuration++<WidgetConfig configuration={thingportFeaturedModelWidget.configuration} />diff --git a/apps/docs/docs/widgets/thingport-featured-model/index.ts b/apps/docs/docs/widgets/thingport-featured-model/index.tsnew file mode 100644index 000000000..56c648f13--- /dev/null+++ b/apps/docs/docs/widgets/thingport-featured-model/index.ts@@ -0,0 +1,37 @@+import { WidgetDefinition } from "@site/src/types";+import { IconRotate360 } from "@tabler/icons-react";++export const thingportFeaturedModelWidget: WidgetDefinition = {+ icon: IconRotate360,+ name: "Thingport Featured Model",+ description: "Shows one model from your Thingport library each day, spinning in 3D.",+ path: "../../widgets/thingport-featured-model",+ configuration: {+ items: [+ {+ name: "Show title",+ description: "Displays the Thingport logo and a title above the widget",+ values: { type: "boolean" },+ defaultValue: "no",+ },+ {+ name: "Spin the model",+ description: "Turns the model slowly on its own",+ values: { type: "boolean" },+ defaultValue: "yes",+ },+ {+ name: "Show model details",+ description: "Displays the model name, author, views and prints under the preview",+ values: { type: "boolean" },+ defaultValue: "yes",+ },+ {+ name: "Open model in new tab",+ description: "Opens the model in Thingport in a new browser tab",+ values: { type: "boolean" },+ defaultValue: "yes",+ },+ ],+ },+};diff --git a/apps/docs/docs/widgets/thingport-library-stats/img/sizes-dark.png b/apps/docs/docs/widgets/thingport-library-stats/img/sizes-dark.pngnew file mode 100644index 000000000..f4c11834cBinary files /dev/null and b/apps/docs/docs/widgets/thingport-library-stats/img/sizes-dark.png differdiff --git a/apps/docs/docs/widgets/thingport-library-stats/img/sizes-light.png b/apps/docs/docs/widgets/thingport-library-stats/img/sizes-light.pngnew file mode 100644index 000000000..6c935a049Binary files /dev/null and b/apps/docs/docs/widgets/thingport-library-stats/img/sizes-light.png differdiff --git a/apps/docs/docs/widgets/thingport-library-stats/index.mdx b/apps/docs/docs/widgets/thingport-library-stats/index.mdxnew file mode 100644index 000000000..f1f96ed18--- /dev/null+++ b/apps/docs/docs/widgets/thingport-library-stats/index.mdx@@ -0,0 +1,44 @@+---+title: "Thingport Library Stats"+description: "Displays model, collection, category and author totals from Thingport."+hide_title: true+---++import { WidgetInteractionGuide } from "@site/src/components/widgets/interactions";++import { WidgetHeader } from "@site/src/components/widgets/header";+import { AddingWidget } from "@site/src/components/widgets/adding";+import { WidgetConfig } from "@site/src/components/widgets/configuration";+import { WidgetIntegrations } from "@site/src/components/widgets/integrations";+import { thingportLibraryStatsWidget } from ".";+import { thingportIntegration } from "@site/docs/integrations/thingport";++<WidgetHeader widget={thingportLibraryStatsWidget} categories={["Miscellaneous"]} />++This widget displays the totals of your Thingport library: models, collections, categories and authors. Selecting models or collections opens that page in Thingport. Thingport has no page listing all categories or authors, so those open the Thingport dashboard.++### Screenshots++The widget at several grid sizes, in dark and light mode.++import sizesDark from "./img/sizes-dark.png";+import sizesLight from "./img/sizes-light.png";++<div className="flex gap-2 flex-wrap">+ <img src={sizesDark.src} alt="Thingport Library Stats widget at several sizes in dark mode" width={720} />+ <img src={sizesLight.src} alt="Thingport Library Stats widget at several sizes in light mode" width={720} />+</div>++### Supported Integrations++<WidgetIntegrations items={[{ integration: thingportIntegration }]} />++<WidgetInteractionGuide advancedView={false} />++### Adding the widget++<AddingWidget />++### Configuration++<WidgetConfig configuration={thingportLibraryStatsWidget.configuration} />diff --git a/apps/docs/docs/widgets/thingport-library-stats/index.ts b/apps/docs/docs/widgets/thingport-library-stats/index.tsnew file mode 100644index 000000000..2c222e670--- /dev/null+++ b/apps/docs/docs/widgets/thingport-library-stats/index.ts@@ -0,0 +1,49 @@+import { WidgetDefinition } from "@site/src/types";+import { IconCube } from "@tabler/icons-react";++export const thingportLibraryStatsWidget: WidgetDefinition = {+ icon: IconCube,+ name: "Thingport Library Stats",+ description: "Displays model, collection, category and author totals from Thingport.",+ path: "../../widgets/thingport-library-stats",+ configuration: {+ items: [+ {+ name: "Show title",+ description: "Displays the Thingport logo and a title above the widget",+ values: { type: "boolean" },+ defaultValue: "no",+ },+ {+ name: "Show models",+ description: "Displays the number of models",+ values: { type: "boolean" },+ defaultValue: "yes",+ },+ {+ name: "Show collections",+ description: "Displays the number of collections",+ values: { type: "boolean" },+ defaultValue: "yes",+ },+ {+ name: "Show categories",+ description: "Displays the number of categories",+ values: { type: "boolean" },+ defaultValue: "yes",+ },+ {+ name: "Show authors",+ description: "Displays the number of authors",+ values: { type: "boolean" },+ defaultValue: "yes",+ },+ {+ name: "Open links in new tab",+ description: "Opens Thingport in a new browser tab when a total is selected",+ values: { type: "boolean" },+ defaultValue: "yes",+ },+ ],+ },+};diff --git a/apps/docs/docs/widgets/thingport-models/img/sizes-dark.png b/apps/docs/docs/widgets/thingport-models/img/sizes-dark.pngnew file mode 100644index 000000000..d2f88a560Binary files /dev/null and b/apps/docs/docs/widgets/thingport-models/img/sizes-dark.png differdiff --git a/apps/docs/docs/widgets/thingport-models/img/sizes-light.png b/apps/docs/docs/widgets/thingport-models/img/sizes-light.pngnew file mode 100644index 000000000..9aaab562fBinary files /dev/null and b/apps/docs/docs/widgets/thingport-models/img/sizes-light.png differdiff --git a/apps/docs/docs/widgets/thingport-models/index.mdx b/apps/docs/docs/widgets/thingport-models/index.mdxnew file mode 100644index 000000000..9ccf2c148--- /dev/null+++ b/apps/docs/docs/widgets/thingport-models/index.mdx@@ -0,0 +1,44 @@+---+title: "Thingport Models"+description: "Lists recently added, most viewed and most printed models from Thingport."+hide_title: true+---++import { WidgetInteractionGuide } from "@site/src/components/widgets/interactions";++import { WidgetHeader } from "@site/src/components/widgets/header";+import { AddingWidget } from "@site/src/components/widgets/adding";+import { WidgetConfig } from "@site/src/components/widgets/configuration";+import { WidgetIntegrations } from "@site/src/components/widgets/integrations";+import { thingportModelsWidget } from ".";+import { thingportIntegration } from "@site/docs/integrations/thingport";++<WidgetHeader widget={thingportModelsWidget} categories={["Miscellaneous"]} />++This widget lists models from your Thingport library in three tabs: recently added, most viewed and most printed. Selecting a model opens it in Thingport.++### Screenshots++The widget at several grid sizes, in dark and light mode.++import sizesDark from "./img/sizes-dark.png";+import sizesLight from "./img/sizes-light.png";++<div className="flex gap-2 flex-wrap">+ <img src={sizesDark.src} alt="Thingport Models widget at several sizes in dark mode" width={720} />+ <img src={sizesLight.src} alt="Thingport Models widget at several sizes in light mode" width={720} />+</div>++### Supported Integrations++<WidgetIntegrations items={[{ integration: thingportIntegration }]} />++<WidgetInteractionGuide advancedView={false} />++### Adding the widget++<AddingWidget />++### Configuration++<WidgetConfig configuration={thingportModelsWidget.configuration} />diff --git a/apps/docs/docs/widgets/thingport-models/index.ts b/apps/docs/docs/widgets/thingport-models/index.tsnew file mode 100644index 000000000..86fbb62b3--- /dev/null+++ b/apps/docs/docs/widgets/thingport-models/index.ts@@ -0,0 +1,43 @@+import { WidgetDefinition } from "@site/src/types";+import { IconCube3dSphere } from "@tabler/icons-react";++export const thingportModelsWidget: WidgetDefinition = {+ icon: IconCube3dSphere,+ name: "Thingport Models",+ description: "Lists recently added, most viewed and most printed models from Thingport.",+ path: "../../widgets/thingport-models",+ configuration: {+ items: [+ {+ name: "Show title",+ description: "Displays the Thingport logo and a title above the widget",+ values: { type: "boolean" },+ defaultValue: "no",+ },+ {+ name: "Default tab",+ description: "Tab shown when the board loads",+ values: { type: "select", options: ["Recent", "Top viewed", "Top printed"] },+ defaultValue: "Recent",+ },+ {+ name: "Number of models",+ description: "Models listed per tab",+ values: "1-50",+ defaultValue: "10",+ },+ {+ name: "Show thumbnails",+ description: "Displays each model's preview image",+ values: { type: "boolean" },+ defaultValue: "yes",+ },+ {+ name: "Open models in new tab",+ description: "Opens the model in Thingport in a new browser tab",+ values: { type: "boolean" },+ defaultValue: "yes",+ },+ ],+ },+};diff --git a/apps/docs/public/api/open-api-schema.json b/apps/docs/public/api/open-api-schema.jsonindex 809a7db7c..5665963a2 100644--- a/apps/docs/public/api/open-api-schema.json+++ b/apps/docs/public/api/open-api-schema.json@@ -3132,6 +3132,10 @@"immich-serverStats","immich-albumCarousel","paperlessNgx",+ "thingport-libraryStats",+ "thingport-models",+ "thingport-featuredModel",+ "thingport-activityHeatmap","patchmon","bazarr","tracearr",@@ -3407,6 +3411,10 @@"immich-serverStats","immich-albumCarousel","paperlessNgx",+ "thingport-libraryStats",+ "thingport-models",+ "thingport-featuredModel",+ "thingport-activityHeatmap","patchmon","bazarr","tracearr",@@ -7479,6 +7487,7 @@"coolify","immich","paperlessNgx",+ "thingport","patchmon","tracearr","speedtestTracker",@@ -7655,6 +7664,7 @@"coolify","immich","paperlessNgx",+ "thingport","patchmon","tracearr","speedtestTracker",diff --git a/bun.lock b/bun.lockindex d5e622cd8..9559b35d4 100644--- a/bun.lock+++ b/bun.lock@@ -1019,11 +1019,13 @@"rehype-raw": "catalog:","rehype-sanitize": "catalog:","remark-gfm": "catalog:",+ "three": "catalog:","video.js": "catalog:","zod": "catalog:",},"devDependencies": {"@homarr/tsconfig": "workspace:^0.1.0",+ "@types/three": "catalog:","@types/video.js": "catalog:","typescript": "catalog:",},diff --git a/packages/api/src/router/integration/integration-router.ts b/packages/api/src/router/integration/integration-router.tsindex e44c76d9f..046ab2c20 100644--- a/packages/api/src/router/integration/integration-router.ts+++ b/packages/api/src/router/integration/integration-router.ts@@ -18,7 +18,12 @@ import {integrationSecrets,integrationUserPermissions,} from "@homarr/db/schema";-import type { GroupPermissionKey, IntegrationPermission, IntegrationSecretKind } from "@homarr/definitions";+import type {+ GroupPermissionKey,+ IntegrationKindByCategory,+ IntegrationPermission,+ IntegrationSecretKind,+} from "@homarr/definitions";import {getIntegrationKindsByCategory,getPermissionsWithParents,@@ -28,6 +33,7 @@ import {integrationSecretKindObject,} from "@homarr/definitions";import { createIntegrationAsync } from "@homarr/integrations/factory";+import type { IntegrationInstanceOfKind } from "@homarr/integrations/factory";import { invalidateIntegrationCacheAsync } from "@homarr/redis";import { mediaRequestListRequestHandler } from "@homarr/request-handler/media-request-list";import { mediaRequestStatsRequestHandler } from "@homarr/request-handler/media-request-stats";@@ -47,6 +53,11 @@ import { MissingSecretError, testConnectionAsync } from "./integration-test-connimport { integrationTestStoredConnectionProcedure } from "./integration-test-stored-connection";import { mapTestConnectionError } from "./map-test-connection-error";+// Calling `searchAsync` on a union of integration classes types the result as only one member's, so the union is+// spelled out per kind: Overseerr's results keep their media type, Thingport's keep their own shape.+type IntegrationSearchResult<TKind extends IntegrationKindByCategory<"search"> = IntegrationKindByCategory<"search">> =+ TKind extends unknown ? Awaited<ReturnType<IntegrationInstanceOfKind<TKind>["searchAsync"]>>[number] : never;+const logger = createLogger({ module: "integrationRouter" });const mediaRequestSearchKinds = getIntegrationKindsByCategory("mediaSearch");@@ -615,7 +626,7 @@ export const integrationRouter = createTRPCRouter({}).concat(createOneIntegrationMiddleware("query", ...getIntegrationKindsByCategory("search"))).input(z.object({ integrationId: z.string(), query: z.string() }))- .query(async ({ ctx, input }) => {+ .query(async ({ ctx, input }): Promise<IntegrationSearchResult[]> => {const integrationInstance = await createIntegrationAsync(ctx.integration);return await integrationInstance.searchAsync(encodeURI(input.query));}),diff --git a/packages/api/src/router/widgets/index.ts b/packages/api/src/router/widgets/index.tsindex f372c3d32..63cae9631 100644--- a/packages/api/src/router/widgets/index.ts+++ b/packages/api/src/router/widgets/index.ts@@ -10,6 +10,7 @@ export const widgetRouter = createTRPCRouter({coolify: lazy(() => import("./coolify").then((mod) => mod.coolifyRouter)),immich: lazy(() => import("./immich").then((mod) => mod.immichRouter)),paperlessNgx: lazy(() => import("./paperless-ngx").then((mod) => mod.paperlessNgxRouter)),+ thingport: lazy(() => import("./thingport").then((mod) => mod.thingportRouter)),patchmon: lazy(() => import("./patchmon").then((mod) => mod.patchmonRouter)),bazarr: lazy(() => import("./bazarr").then((mod) => mod.bazarrRouter)),notebook: lazy(() => import("./notebook").then((mod) => mod.notebookRouter)),diff --git a/packages/api/src/router/widgets/thingport.ts b/packages/api/src/router/widgets/thingport.tsnew file mode 100644index 000000000..8c9bb87e9--- /dev/null+++ b/packages/api/src/router/widgets/thingport.ts@@ -0,0 +1,68 @@+import { z } from "zod/v4";++import { createThingportMockActivity, mockWidgetData, thingportModelLists } from "@homarr/integrations";+import {+ thingportActivityRequestHandler,+ thingportFeaturedModelRequestHandler,+ thingportLibraryStatsRequestHandler,+ thingportModelsRequestHandler,+} from "@homarr/request-handler/thingport";++import { createOneWidgetIntegrationMiddleware } from "../../middlewares/integration";+import { createTRPCRouter, publicProcedure } from "../../trpc";++const isoDateSchema = z.string().regex(/^\d{4}-\d{2}-\d{2}$/);++// The heatmap shows at most a calendar year (366 days in a leap year), inclusive of both ends.+const MAX_ACTIVITY_DAYS = 366;+const DAY_MS = 24 * 60 * 60 * 1000;+const activityInputSchema = z+ .object({ from: isoDateSchema, to: isoDateSchema, timeZone: z.string().max(64) })+ .refine(({ from, to }) => {+ const days = (Date.parse(`${to}T00:00:00Z`) - Date.parse(`${from}T00:00:00Z`)) / DAY_MS + 1;+ return days >= 1 && days <= MAX_ACTIVITY_DAYS;+ }, `The range must run forwards and cover at most ${MAX_ACTIVITY_DAYS} days`);++export const thingportRouter = createTRPCRouter({+ getLibraryStats: publicProcedure+ .concat(createOneWidgetIntegrationMiddleware("query", "thingport-libraryStats"))+ .query(async ({ ctx }) => {+ if (ctx.integration.kind === "mock") return mockWidgetData.thingportLibraryStats;+ const innerHandler = thingportLibraryStatsRequestHandler.handler({ ...ctx.integration, kind: "thingport" }, {});+ const data = await innerHandler.getDataAsync();+ return data.data;+ }),++ getModels: publicProcedure+ .concat(createOneWidgetIntegrationMiddleware("query", "thingport-models"))+ .input(z.object({ list: z.enum(thingportModelLists), limit: z.number().int().min(1).max(50) }))+ .query(async ({ ctx, input }) => {+ if (ctx.integration.kind === "mock") return mockWidgetData.thingportModels[input.list].slice(0, input.limit);+ const innerHandler = thingportModelsRequestHandler.handler({ ...ctx.integration, kind: "thingport" }, input);+ const data = await innerHandler.getDataAsync();+ return data.data;+ }),++ getFeaturedModel: publicProcedure+ .concat(createOneWidgetIntegrationMiddleware("query", "thingport-featuredModel"))+ .input(z.object({ date: isoDateSchema }))+ .query(async ({ ctx, input }) => {+ if (ctx.integration.kind === "mock") return mockWidgetData.thingportFeaturedModel;+ const innerHandler = thingportFeaturedModelRequestHandler.handler(+ { ...ctx.integration, kind: "thingport" },+ input,+ );+ const data = await innerHandler.getDataAsync();+ return data.data;+ }),++ getActivity: publicProcedure+ .concat(createOneWidgetIntegrationMiddleware("query", "thingport-activityHeatmap"))+ .input(activityInputSchema)+ .query(async ({ ctx, input }) => {+ if (ctx.integration.kind === "mock") return createThingportMockActivity(input.from, input.to);+ const innerHandler = thingportActivityRequestHandler.handler({ ...ctx.integration, kind: "thingport" }, input);+ const data = await innerHandler.getDataAsync();+ return data.data;+ }),+});diff --git a/packages/definitions/src/docs/homarr-docs-sitemap.ts b/packages/definitions/src/docs/homarr-docs-sitemap.tsindex 254c01fc9..ddc6cedc5 100644--- a/packages/definitions/src/docs/homarr-docs-sitemap.ts+++ b/packages/definitions/src/docs/homarr-docs-sitemap.ts@@ -183,6 +183,7 @@ export type HomarrDocumentationPath =| "/docs/integrations/tandoor"| "/docs/integrations/tdarr"| "/docs/integrations/technitium-dns"+ | "/docs/integrations/thingport"| "/docs/integrations/tracearr"| "/docs/integrations/traefik"| "/docs/integrations/transmission"@@ -271,6 +272,10 @@ export type HomarrDocumentationPath =| "/docs/widgets/stock-price"| "/docs/widgets/system-disks"| "/docs/widgets/system-resources"+ | "/docs/widgets/thingport-activity-heatmap"+ | "/docs/widgets/thingport-featured-model"+ | "/docs/widgets/thingport-library-stats"+ | "/docs/widgets/thingport-models"| "/docs/widgets/timer"| "/docs/widgets/timetable"| "/docs/widgets/tracearr"diff --git a/packages/definitions/src/docs/sitemap-paths.json b/packages/definitions/src/docs/sitemap-paths.jsonindex e11df6dd6..31a8336ce 100644--- a/packages/definitions/src/docs/sitemap-paths.json+++ b/packages/definitions/src/docs/sitemap-paths.json@@ -179,6 +179,7 @@"/docs/integrations/tandoor","/docs/integrations/tdarr","/docs/integrations/technitium-dns",+ "/docs/integrations/thingport","/docs/integrations/tracearr","/docs/integrations/traefik","/docs/integrations/transmission",@@ -267,6 +268,10 @@"/docs/widgets/stock-price","/docs/widgets/system-disks","/docs/widgets/system-resources",+ "/docs/widgets/thingport-activity-heatmap",+ "/docs/widgets/thingport-featured-model",+ "/docs/widgets/thingport-library-stats",+ "/docs/widgets/thingport-models","/docs/widgets/timer","/docs/widgets/timetable","/docs/widgets/tracearr",diff --git a/packages/definitions/src/docs/widget-doc-slugs.ts b/packages/definitions/src/docs/widget-doc-slugs.tsindex 3dd3bbfd6..a3b502eb8 100644--- a/packages/definitions/src/docs/widget-doc-slugs.ts+++ b/packages/definitions/src/docs/widget-doc-slugs.ts@@ -43,6 +43,10 @@ export const widgetDocSlugs = {"immich-serverStats": "immich-server-stats","immich-albumCarousel": "immich-album-carousel",paperlessNgx: "paperless-ngx",+ "thingport-libraryStats": "thingport-library-stats",+ "thingport-models": "thingport-models",+ "thingport-featuredModel": "thingport-featured-model",+ "thingport-activityHeatmap": "thingport-activity-heatmap",patchmon: "patchmon",bazarr: "bazarr",tracearr: "tracearr",diff --git a/packages/definitions/src/integration.ts b/packages/definitions/src/integration.tsindex 780b7a597..373238bc6 100644--- a/packages/definitions/src/integration.ts+++ b/packages/definitions/src/integration.ts@@ -830,6 +830,17 @@ export const integrationDefs = {defaultPort: 8000,features: { docker: { aliases: ["paperless-ngx", "paperless"] } },},+ thingport: {+ httpAuth: { type: "bearer" },+ name: "Thingport",+ secretKinds: [["apiKey"]],+ iconUrl: "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/thingport.svg",+ category: ["miscellaneous", "search"],+ documentationSlug: "thingport",+ defaultPort: 80,+ apiKeySettingsPath: "/profile",+ features: { docker: { aliases: ["thingport", "thingport-frontend"] } },+ },patchmon: {httpAuth: { type: "basic", usernameKind: "patchmonApiKey", passwordKind: "patchmonApiSecret" },name: "PatchMon",diff --git a/packages/definitions/src/test/widget-integration-map.spec.ts b/packages/definitions/src/test/widget-integration-map.spec.tsindex a566ef56c..be2734267 100644--- a/packages/definitions/src/test/widget-integration-map.spec.ts+++ b/packages/definitions/src/test/widget-integration-map.spec.ts@@ -41,6 +41,10 @@ describe("widget integration config", () => {"immich-serverStats": 1,"immich-albumCarousel": 1,paperlessNgx: 1,+ "thingport-libraryStats": 1,+ "thingport-models": 1,+ "thingport-featuredModel": 1,+ "thingport-activityHeatmap": 1,patchmon: 1,bazarr: 1,audioStats: 1,diff --git a/packages/definitions/src/widget-integration-map.ts b/packages/definitions/src/widget-integration-map.tsindex 903d5e650..a5e2ab127 100644--- a/packages/definitions/src/widget-integration-map.ts+++ b/packages/definitions/src/widget-integration-map.ts@@ -104,6 +104,7 @@ export const statsIntegrationKinds = ["coolify","immich","paperlessNgx",+ "thingport","patchmon","tracearr","speedtestTracker",@@ -165,6 +166,10 @@ export const widgetIntegrationConfigs = {"immich-serverStats": { supportedIntegrations: ["immich", "mock"], maxIntegrations: 1 },"immich-albumCarousel": { supportedIntegrations: ["immich", "mock"], maxIntegrations: 1 },paperlessNgx: { supportedIntegrations: ["paperlessNgx", "mock"], maxIntegrations: 1 },+ "thingport-libraryStats": { supportedIntegrations: ["thingport", "mock"], maxIntegrations: 1 },+ "thingport-models": { supportedIntegrations: ["thingport", "mock"], maxIntegrations: 1 },+ "thingport-featuredModel": { supportedIntegrations: ["thingport", "mock"], maxIntegrations: 1 },+ "thingport-activityHeatmap": { supportedIntegrations: ["thingport", "mock"], maxIntegrations: 1 },patchmon: { supportedIntegrations: ["patchmon", "mock"], maxIntegrations: 1 },bazarr: { supportedIntegrations: ["bazarr", "mock"], maxIntegrations: 1 },tracearr: { supportedIntegrations: ["tracearr", "mock"] },diff --git a/packages/definitions/src/widget.ts b/packages/definitions/src/widget.tsindex 39d3ab0e1..f84fbbf74 100644--- a/packages/definitions/src/widget.ts+++ b/packages/definitions/src/widget.ts@@ -41,6 +41,10 @@ export const widgetKinds = ["immich-serverStats","immich-albumCarousel","paperlessNgx",+ "thingport-libraryStats",+ "thingport-models",+ "thingport-featuredModel",+ "thingport-activityHeatmap","patchmon","bazarr","tracearr",@@ -86,6 +90,10 @@ export const widgetDefaultSizes: Partial<Record<WidgetKind, { width: number; heiuptimeKuma: { width: 2, height: 3 },audioStats: { width: 2, height: 2 },paperlessNgx: { width: 2, height: 2 },+ "thingport-libraryStats": { width: 2, height: 2 },+ "thingport-models": { width: 3, height: 3 },+ "thingport-featuredModel": { width: 2, height: 2 },+ "thingport-activityHeatmap": { width: 6, height: 2 },patchmon: { width: 2, height: 2 },mediaServer: { width: 3, height: 2 },"mediaRequests-requestList": { width: 3, height: 2 },diff --git a/packages/integrations/src/base/creator.ts b/packages/integrations/src/base/creator.tsindex 97da0b6f4..7bd564968 100644--- a/packages/integrations/src/base/creator.ts+++ b/packages/integrations/src/base/creator.ts@@ -325,6 +325,8 @@ const integrationCreators = {new (await import("../immich/immich-integration")).ImmichIntegration(input),paperlessNgx: async (input: IntegrationInput) =>new (await import("../paperless-ngx/paperless-ngx-integration")).PaperlessNgxIntegration(input),+ thingport: async (input: IntegrationInput) =>+ new (await import("../thingport/thingport-integration")).ThingportIntegration(input),wazuh: async (input: IntegrationInput) => new (await import("../wazuh/wazuh-integration")).WazuhIntegration(input),patchmon: async (input: IntegrationInput) =>new (await import("../patchmon/patchmon-integration")).PatchMonIntegration(input),diff --git a/packages/integrations/src/factory.ts b/packages/integrations/src/factory.tsindex d86c96d6e..f2add2442 100644--- a/packages/integrations/src/factory.ts+++ b/packages/integrations/src/factory.ts@@ -1,2 +1,3 @@export { createIntegrationAsync, getIntegrationHttpAuthenticationAsync } from "./base/creator";+export type { IntegrationInstanceOfKind } from "./base/creator";export type { IntegrationHttpAuthentication } from "./http-auth";diff --git a/packages/integrations/src/index.ts b/packages/integrations/src/index.tsindex e7596fcec..acd141232 100644--- a/packages/integrations/src/index.ts+++ b/packages/integrations/src/index.ts@@ -49,7 +49,7 @@ export { UmamiIntegration } from "./umami/umami-integration";export { PeaNutIntegration } from "./peanut/peanut-integration";export { BazarrIntegration } from "./bazarr/bazarr-integration";export { TraefikIntegration } from "./traefik/traefik-integration";-export { mockWidgetData } from "./mock/widget-data";+export { createThingportMockActivity, mockWidgetData } from "./mock/widget-data";// Typesexport type { IntegrationInput } from "./base/integration";@@ -77,6 +77,17 @@ export type {export type { Notification } from "./interfaces/notifications/notification-types";export type { ImmichServerStats, ImmichAlbum, ImmichAsset } from "./immich/immich-integration";export type { PaperlessNgxStats } from "./paperless-ngx/paperless-ngx-types";+export type {+ ThingportActivity,+ ThingportActivityDay,+ ThingportActivityKind,+ ThingportFeaturedModel,+ ThingportLibraryStats,+ ThingportModel,+ ThingportModelList,+ ThingportSearchResult,+} from "./thingport/thingport-types";+export { thingportActivityKinds, thingportModelLists } from "./thingport/thingport-types";export type { PatchMonStats, PatchMonOsDistributionEntry } from "./patchmon/patchmon-types";export { toWazuhPublicError } from "./wazuh/wazuh-errors";export type { WazuhErrorReason, WazuhPublicError } from "./wazuh/wazuh-errors";diff --git a/packages/integrations/src/mock/widget-data.ts b/packages/integrations/src/mock/widget-data.tsindex 70f8d75f8..27b38d34a 100644--- a/packages/integrations/src/mock/widget-data.ts+++ b/packages/integrations/src/mock/widget-data.ts@@ -7,6 +7,14 @@ import type { NavidromeDashboardData } from "../navidrome/navidrome-types";import type { PaperlessNgxStats } from "../paperless-ngx/paperless-ngx-types";import type { PatchMonStats } from "../patchmon/patchmon-types";import type { SpeedtestTrackerDashboardData } from "../speedtest-tracker/speedtest-tracker-types";+import type {+ ThingportActivity,+ ThingportActivityDay,+ ThingportFeaturedModel,+ ThingportLibraryStats,+ ThingportModel,+ ThingportModelList,+} from "../thingport/thingport-types";import type { TracearrDashboardData } from "../tracearr/tracearr-types";import type { TraefikDashboardData } from "../traefik/traefik-types";import type { UmamiEventSeries, UmamiMetricItem, UmamiVisitorStats, UmamiWebsite } from "../umami/umami-types";@@ -178,6 +186,30 @@ export const mockWidgetData = {},],} satisfies ImmichAlbum,+ thingportLibraryStats: {+ modelCount: 1_284,+ collectionCount: 37,+ categoryCount: 52,+ authorCount: 412,+ links: {+ models: "https://thingport.net/models",+ collections: "https://thingport.net/models/collections",+ categories: "https://thingport.net/",+ authors: "https://thingport.net/",+ },+ } satisfies ThingportLibraryStats,+ thingportModels: createThingportMockModels(),+ thingportFeaturedModel: {+ id: "demo-model-1",+ name: "Articulated Dragon",+ href: "https://thingport.net/models/demo-model-1",+ thumbnailUrl: null,+ author: "McGybeer",+ category: "Toys & Games",+ viewCount: 214,+ printCount: 9,+ mesh: null,+ } satisfies ThingportFeaturedModel,paperlessNgx: {documentsTotal: 2_847,documentsInbox: 14,@@ -371,3 +403,60 @@ export const mockWidgetData = {},} satisfies LlamacppStats,} as const;++function createThingportMockModels(): Record<ThingportModelList, ThingportModel[]> {+ const models = [+ { name: "Articulated Dragon", viewCount: 214, printCount: 9 },+ { name: "Cable Management Clips", viewCount: 87, printCount: 23 },+ { name: "Gridfinity Baseplate 4x4", viewCount: 156, printCount: 17 },+ { name: "Benchy Calibration Boat", viewCount: 64, printCount: 31 },+ { name: "Planetary Gear Fidget", viewCount: 121, printCount: 6 },+ ].map((model, index) => ({+ id: `demo-model-${index + 1}`,+ name: model.name,+ href: `https://thingport.net/models/demo-model-${index + 1}`,+ thumbnailUrl: null,+ viewCount: model.viewCount,+ printCount: model.printCount,+ createdAt: new Date(Date.parse(demoTimestamp) - index * 36 * 60 * 60 * 1000).toISOString(),+ }));++ return {+ recentlyAdded: models,+ topViewed: models.toSorted((left, right) => right.viewCount - left.viewCount),+ topPrinted: models.toSorted((left, right) => right.printCount - left.printCount),+ };+}++/** A year and a half of made-up activity, the same on every load, filtered to the range a widget asks for. */+export function createThingportMockActivity(from: string, to: string): ThingportActivity {+ const days: ThingportActivityDay[] = [];+ const end = Date.parse(`${to}T00:00:00Z`);+ for (let time = Date.parse(`${from}T00:00:00Z`); time <= end; time += 24 * 60 * 60 * 1000) {+ const date = new Date(time).toISOString().slice(0, 10);+ // Cheap deterministic noise from the date, so the demo heatmap has busy streaks and quiet gaps.+ const seed = [...date].reduce((hash, char) => (hash * 31 + char.charCodeAt(0)) % 9973, 7);+ const weekday = new Date(time).getUTCDay();+ if (seed % 10 < (weekday === 0 || weekday === 6 ? 5 : 3)) continue;+ const download = seed % 5;+ const imported = seed % 7 === 0 ? 3 + (seed % 4) : seed % 3;+ const slicer = seed % 4 === 0 ? 1 + (seed % 3) : 0;+ const upload = seed % 11 === 0 ? 1 : 0;+ const counts: ThingportActivityDay["counts"] = {};+ if (imported) counts.import = imported;+ if (upload) counts.upload = upload;+ if (download) counts.download = download;+ if (slicer) counts.slicer = slicer;+ if (Object.keys(counts).length > 0) days.push({ date, counts });+ }++ return {+ days,+ total: days.reduce(+ (sum, day) => sum + Object.values(day.counts).reduce((daySum, count) => daySum + (count ?? 0), 0),+ 0,+ ),+ years: [2026, 2025, 2024],+ profileUrl: "https://thingport.net/profile",+ };+}diff --git a/packages/integrations/src/stats/existing.ts b/packages/integrations/src/stats/existing.tsindex a1ea7b8d6..bcdb916c5 100644--- a/packages/integrations/src/stats/existing.ts+++ b/packages/integrations/src/stats/existing.ts@@ -50,6 +50,22 @@ export const existingStatsProviders: Partial<Record<IntegrationKind, ExistingSta(client) => client.getStatsAsync(),(data) => ({ ...data }),),+ thingport: adapter(+ "thingport",+ [+ metric("modelCount", "Models"),+ metric("collectionCount", "Collections"),+ metric("categoryCount", "Categories"),+ metric("authorCount", "Authors"),+ ],+ (client) => client.getLibraryStatsAsync(),+ ({ modelCount, collectionCount, categoryCount, authorCount }) => ({+ modelCount,+ collectionCount,+ categoryCount,+ authorCount,+ }),+ ),navidrome: adapter("navidrome",[metric("artistCount", "Artists"), metric("albumCount", "Albums"), metric("songCount", "Songs")],diff --git a/packages/integrations/src/thingport/thingport-integration.ts b/packages/integrations/src/thingport/thingport-integration.tsnew file mode 100644index 000000000..ff6982960--- /dev/null+++ b/packages/integrations/src/thingport/thingport-integration.ts@@ -0,0 +1,245 @@+import { ResponseError } from "@homarr/common/server";+import { fetchWithTrustedCertificatesAsync } from "@homarr/core/infrastructure/http";+import { ImageProxy } from "@homarr/image-proxy";++import type { IntegrationTestingInput } from "../base/integration";+import type { ISearchableIntegration } from "../base/searchable-integration";+import { Integration } from "../base/integration";+import { TestConnectionError } from "../base/test-connection/test-connection-error";+import type { TestingResult } from "../base/test-connection/test-connection-service";+import type {+ ThingportActivity,+ ThingportActivityDay,+ ThingportFeaturedModel,+ ThingportLibraryStats,+ ThingportMeshFormat,+ ThingportModel,+ ThingportModelList,+ ThingportSearchResult,+} from "./thingport-types";+import {+ thingportActivityKinds,+ thingportActivitySchema,+ thingportFeaturedSchema,+ thingportModelSchema,+ thingportSearchSchema,+ thingportSummarySchema,+} from "./thingport-types";++// Thingport has no "recently added" dashboard list beyond the three in its summary, so that one is the library+// itself, newest first.+const modelListRequests = {+ recentlyAdded: (limit: number) => ({ path: "/api/prints", query: { orderBy: "newest", limit: String(limit) } }),+ topViewed: () => ({ path: "/api/dashboard/top-viewed", query: undefined }),+ topPrinted: () => ({ path: "/api/dashboard/top-printed", query: undefined }),+} as const satisfies Record<+ ThingportModelList,+ (limit: number) => { path: `/${string}`; query: Record<string, string> | undefined }+>;++// Thingport caps a search at 25; the search palette has room for fewer.+const SEARCH_MODEL_LIMIT = 10;++export class ThingportIntegration extends Integration implements ISearchableIntegration<ThingportSearchResult> {+ protected async testingAsync(input: IntegrationTestingInput): Promise<TestingResult> {+ // The health route is public, so only an authenticated route proves the API token works.+ const response = await input.fetchAsync(this.url("/api/dashboard/summary"), {+ headers: this.getAuthHeaders(),+ signal: AbortSignal.timeout(30_000),+ redirect: "error",+ });++ if (!response.ok) {+ return TestConnectionError.StatusResult(response);+ }++ return { success: true };+ }++ public async getLibraryStatsAsync(signal = AbortSignal.timeout(30_000)): Promise<ThingportLibraryStats> {+ const summary = thingportSummarySchema.parse(+ await this.fetchJsonAsync("/api/dashboard/summary", undefined, signal),+ );+ // Thingport has no category or author index page, so those open the dashboard, as its own count cards do.+ const dashboard = this.externalUrl("/").toString();++ return {+ modelCount: summary.model_count,+ collectionCount: summary.collection_count,+ categoryCount: summary.category_count,+ authorCount: summary.author_count,+ links: {+ models: this.externalUrl("/models").toString(),+ collections: this.externalUrl("/models/collections").toString(),+ categories: dashboard,+ authors: dashboard,+ },+ };+ }++ public async getModelsAsync(+ list: ThingportModelList,+ limit: number,+ signal = AbortSignal.timeout(30_000),+ ): Promise<ThingportModel[]> {+ const request = modelListRequests[list](limit);+ const models = thingportModelSchema+ .array()+ .parse(await this.fetchJsonAsync(request.path, request.query, signal))+ .slice(0, limit);++ // Thumbnails need the API token, which must never reach the browser, so they go through the image proxy.+ const thumbnailSources = models.flatMap((model) => (model.thumb_url ? [this.apiUrl(model.thumb_url)] : []));+ const thumbnailLinks = (await new ImageProxy().createImagesAsync(thumbnailSources, this.getAuthHeaders())).values();++ return models.map((model) => ({+ id: model.id,+ name: model.name,+ href: this.modelHref(model.id),+ thumbnailUrl: model.thumb_url ? (thumbnailLinks.next().value ?? null) : null,+ viewCount: model.view_count,+ printCount: model.print_count,+ createdAt: model.created_at,+ }));+ }++ /** Thingport picks one model a day; `date` is the viewer's local day, so it changes at their midnight. */+ public async getFeaturedModelAsync(+ date: string,+ signal = AbortSignal.timeout(30_000),+ ): Promise<ThingportFeaturedModel | null> {+ const { print } = thingportFeaturedSchema.parse(+ await this.fetchJsonAsync("/api/dashboard/featured", { date }, signal),+ );+ const plate = print?.plates[0];+ if (!print || !plate) return null;++ // The server pre-renders a GLB for 3MF plates; an STL plate is light enough to draw as it is.+ // STEP, OBJ and 3MF without a preview fall back to the thumbnail.+ let mesh: { source: string; format: ThingportMeshFormat } | null = null;+ if (plate.preview_glb_url) mesh = { source: plate.preview_glb_url, format: "glb" };+ else if (plate.filename.toLowerCase().endsWith(".stl")) mesh = { source: plate.url, format: "stl" };++ const thumbnail = plate.thumb_url ?? print.thumb_url ?? null;+ const imageProxy = new ImageProxy();+ const headers = this.getAuthHeaders();+ const [thumbnailUrl, meshUrl] = await Promise.all([+ thumbnail ? imageProxy.createImageAsync(this.apiUrl(thumbnail), headers) : null,+ mesh ? imageProxy.createImageAsync(this.apiUrl(mesh.source), headers) : null,+ ]);++ return {+ id: print.id,+ name: print.name,+ href: this.modelHref(print.id),+ thumbnailUrl,+ author: print.author?.name ?? print.author?.handle ?? null,+ category: print.category_name ?? null,+ viewCount: print.view_count,+ printCount: print.print_count,+ mesh: mesh && meshUrl ? { url: meshUrl, format: mesh.format } : null,+ };+ }++ /** `from`/`to` are inclusive YYYY-MM-DD days, counted in the `timeZone` the board is viewed in. */+ public async getActivityAsync(+ from: string,+ to: string,+ timeZone: string,+ signal = AbortSignal.timeout(30_000),+ ): Promise<ThingportActivity> {+ const activity = thingportActivitySchema.parse(+ await this.fetchJsonAsync("/api/activity", { from, to, tz: timeZone }, signal),+ );++ return {+ days: activity.days.map((day) => {+ const counts: ThingportActivityDay["counts"] = {};+ for (const kind of thingportActivityKinds) {+ const count = day.counts[kind];+ if (count) counts[kind] = count;+ }+ return { date: day.date, counts };+ }),+ total: activity.total,+ years: activity.years,+ profileUrl: this.externalUrl("/profile").toString(),+ };+ }++ /** Models first, as Thingport ranks them, then matching collections and tags. */+ public async searchAsync(query: string, signal = AbortSignal.timeout(30_000)): Promise<ThingportSearchResult[]> {+ // The search router hands over the query already passed through encodeURI; the URL builder encodes it again.+ const q = decodeURI(query).trim();+ if (!q) return [];++ const result = thingportSearchSchema.parse(+ await this.fetchJsonAsync("/api/search", { q, limit: String(SEARCH_MODEL_LIMIT) }, signal),+ );++ const thumbnailSources = result.models.flatMap((model) => (model.thumb_url ? [this.apiUrl(model.thumb_url)] : []));+ const thumbnailLinks = (await new ImageProxy().createImagesAsync(thumbnailSources, this.getAuthHeaders())).values();++ const models = result.models.map((model) => {+ const details = [model.author?.name ?? model.author?.handle, model.category_name].filter(Boolean).join(" · ");+ return {+ name: model.name,+ link: this.modelHref(model.id),+ image: model.thumb_url ? thumbnailLinks.next().value : undefined,+ text: details || undefined,+ };+ });+ const collections = result.collections.map((collection) => ({+ name: collection.name,+ link: this.externalUrl(`/models/collections/${encodeURIComponent(collection.id)}`).toString(),+ }));+ const tags = result.tags.map((tag) => ({+ name: `#${tag.tag}`,+ link: this.externalUrl(`/models/tags/${encodeURIComponent(tag.tag)}`).toString(),+ }));++ return [...models, ...collections, ...tags];+ }++ private apiUrl(relativePath: string): string {+ const target = this.url(`/api${relativePath}` as `/${string}`);+ const apiBase = this.url("/api");+ if (+ !relativePath.startsWith("/") ||+ relativePath.startsWith("//") ||+ relativePath.includes("\\") ||+ target.hash ||+ target.origin !== apiBase.origin ||+ !target.pathname.startsWith(`${apiBase.pathname}/`)+ ) {+ throw new Error("Thingport media must stay within the integration API path");+ }+ return target.toString();+ }++ private modelHref(id: string): string {+ return this.externalUrl(`/models/${encodeURIComponent(id)}`).toString();+ }++ private async fetchJsonAsync(+ path: `/${string}`,+ queryParams?: Record<string, string>,+ signal?: AbortSignal,+ ): Promise<unknown> {+ const response = await fetchWithTrustedCertificatesAsync(this.url(path, queryParams), {+ headers: this.getAuthHeaders(),+ signal,+ redirect: "error",+ });+ if (!response.ok) {+ throw new ResponseError(response);+ }+ return await response.json();+ }++ private getAuthHeaders(): Record<string, string> {+ return {+ Authorization: `Bearer ${this.getSecretValue("apiKey")}`,+ };+ }+}diff --git a/packages/integrations/src/thingport/thingport-types.ts b/packages/integrations/src/thingport/thingport-types.tsnew file mode 100644index 000000000..23ba51316--- /dev/null+++ b/packages/integrations/src/thingport/thingport-types.ts@@ -0,0 +1,131 @@+import { z } from "zod/v4";++export const thingportSummarySchema = z.object({+ model_count: z.number(),+ collection_count: z.number(),+ category_count: z.number(),+ author_count: z.number(),+});++export const thingportModelSchema = z.object({+ id: z.string(),+ name: z.string(),+ thumb_url: z.string().nullable(),+ view_count: z.number(),+ print_count: z.number(),+ created_at: z.string(),+});++export const thingportFeaturedSchema = z.object({+ print: z+ .object({+ id: z.string(),+ name: z.string(),+ thumb_url: z.string().nullish(),+ view_count: z.number(),+ print_count: z.number(),+ category_name: z.string().nullish(),+ author: z.object({ name: z.string().nullable(), handle: z.string().nullable() }).nullish(),+ plates: z+ .object({+ id: z.string(),+ filename: z.string(),+ url: z.string(),+ thumb_url: z.string().nullish(),+ preview_glb_url: z.string().nullish(),+ })+ .array(),+ })+ .nullable(),+});++export const thingportSearchSchema = z.object({+ models: z+ .object({+ id: z.string(),+ name: z.string(),+ thumb_url: z.string().nullish(),+ category_name: z.string().nullish(),+ author: z.object({ name: z.string().nullable(), handle: z.string().nullable() }).nullish(),+ })+ .array(),+ collections: z.object({ id: z.string(), name: z.string() }).array(),+ tags: z.object({ tag: z.string(), count: z.number() }).array(),+});++export const thingportActivityKinds = ["import", "upload", "download", "slicer", "delete"] as const;+export type ThingportActivityKind = (typeof thingportActivityKinds)[number];++export const thingportActivitySchema = z.object({+ days: z+ .object({+ date: z.string(),+ // Plain string keys, so a kind added to Thingport later is dropped instead of failing the parse.+ counts: z.record(z.string(), z.number()),+ })+ .array(),+ total: z.number(),+ years: z.number().array(),+});++export const thingportModelLists = ["recentlyAdded", "topViewed", "topPrinted"] as const;+export type ThingportModelList = (typeof thingportModelLists)[number];++export interface ThingportLibraryStats {+ modelCount: number;+ collectionCount: number;+ categoryCount: number;+ authorCount: number;+ links: {+ models: string;+ collections: string;+ categories: string;+ authors: string;+ };+}++export interface ThingportModel {+ id: string;+ name: string;+ href: string;+ thumbnailUrl: string | null;+ viewCount: number;+ printCount: number;+ createdAt: string;+}++export type ThingportMeshFormat = "glb" | "stl";++export interface ThingportFeaturedModel {+ id: string;+ name: string;+ href: string;+ thumbnailUrl: string | null;+ author: string | null;+ category: string | null;+ viewCount: number;+ printCount: number;+ /** A mesh the browser can draw: the server's pre-rendered GLB, or the plate itself when it is an STL. */+ mesh: { url: string; format: ThingportMeshFormat } | null;+}++export interface ThingportSearchResult {+ name: string;+ link: string;+ image?: string;+ text?: string;+}++export interface ThingportActivityDay {+ date: string;+ counts: Partial<Record<ThingportActivityKind, number>>;+}++export interface ThingportActivity {+ /** Only days with activity. */+ days: ThingportActivityDay[];+ total: number;+ /** From the year the user registered to this one, newest first. */+ years: number[];+ profileUrl: string;+}diff --git a/packages/integrations/src/types.ts b/packages/integrations/src/types.tsindex f96635ee6..344ab6f2a 100644--- a/packages/integrations/src/types.ts+++ b/packages/integrations/src/types.ts@@ -25,6 +25,7 @@ export * from "./uptime-kuma/uptime-kuma-summary";export * from "./audiobookshelf/audiobookshelf-types";export * from "./navidrome/navidrome-types";export * from "./paperless-ngx/paperless-ngx-types";+export * from "./thingport/thingport-types";export * from "./umami/umami-types";export * from "./gluetun/gluetun-types";export * from "./beszel/beszel-types";diff --git a/packages/request-handler/src/thingport.ts b/packages/request-handler/src/thingport.tsnew file mode 100644index 000000000..a7bda86fd--- /dev/null+++ b/packages/request-handler/src/thingport.ts@@ -0,0 +1,61 @@+import { createIntegrationAsync } from "@homarr/integrations/factory";+import type {+ ThingportActivity,+ ThingportFeaturedModel,+ ThingportLibraryStats,+ ThingportModel,+ ThingportModelList,+} from "@homarr/integrations";++import { createIntegrationRequestHandler } from "./lib/integration-request-handler";++export const thingportLibraryStatsRequestHandler = createIntegrationRequestHandler<+ ThingportLibraryStats,+ "thingport",+ Record<string, never>+>({+ cacheNamespace: "thingport:library-stats",+ async requestAsync(integration, _input, signal) {+ const integrationInstance = await createIntegrationAsync(integration);+ return await integrationInstance.getLibraryStatsAsync(signal);+ },+});++export const thingportModelsRequestHandler = createIntegrationRequestHandler<+ ThingportModel[],+ "thingport",+ { list: ThingportModelList; limit: number }+>({+ cacheNamespace: "thingport:models",+ async requestAsync(integration, input, signal) {+ const integrationInstance = await createIntegrationAsync(integration);+ return await integrationInstance.getModelsAsync(input.list, input.limit, signal);+ },+});++export const thingportFeaturedModelRequestHandler = createIntegrationRequestHandler<+ ThingportFeaturedModel | null,+ "thingport",+ { date: string }+>({+ cacheNamespace: "thingport:featured-model",+ // The pick only changes with the date, which is part of the cache key.+ cacheTtlMs: 60 * 60 * 1000,+ async requestAsync(integration, input, signal) {+ const integrationInstance = await createIntegrationAsync(integration);+ return await integrationInstance.getFeaturedModelAsync(input.date, signal);+ },+});++export const thingportActivityRequestHandler = createIntegrationRequestHandler<+ ThingportActivity,+ "thingport",+ { from: string; to: string; timeZone: string }+>({+ cacheNamespace: "thingport:activity",+ cacheTtlMs: 5 * 60 * 1000,+ async requestAsync(integration, input, signal) {+ const integrationInstance = await createIntegrationAsync(integration);+ return await integrationInstance.getActivityAsync(input.from, input.to, input.timeZone, signal);+ },+});diff --git a/packages/spotlight/src/modes/external/search-engines-search-group.tsx b/packages/spotlight/src/modes/external/search-engines-search-group.tsxindex 7d4092881..7a52b259d 100644--- a/packages/spotlight/src/modes/external/search-engines-search-group.tsx+++ b/packages/spotlight/src/modes/external/search-engines-search-group.tsx@@ -19,6 +19,8 @@ import { useRemoteQuery } from "../../lib/remote-query";type SearchEngine = RouterOutputs["searchEngine"]["catalog"][number];type FromIntegrationSearchResult = RouterOutputs["integration"]["searchInIntegration"][number];+// Only the media request integrations (Overseerr, Jellyseerr, Seerr) send a media type with their results.+type MediaSearchResult = Extract<FromIntegrationSearchResult, { type: unknown }>;type DuckDuckGoBang = RouterOutputs["bangs"]["search"][number];type ExternalOption =@@ -72,7 +74,7 @@ type MediaRequestChildrenProps = {export const useMediaRequestSearchInteraction = (integration: MediaRequestChildrenProps["integration"],- searchResult: FromIntegrationSearchResult,+ searchResult: MediaSearchResult,): inferSearchInteractionDefinition<"link" | "children"> => {const { openSearchInNewTab } = useSettings();diff --git a/packages/translation/src/lang/en.json b/packages/translation/src/lang/en.jsonindex aadb1756c..4a8c85fc0 100644--- a/packages/translation/src/lang/en.json+++ b/packages/translation/src/lang/en.json@@ -3980,6 +3980,109 @@"transcoding": "{count} transcoding"}},+ "thingport-libraryStats": {+ "name": "Thingport Library Stats",+ "description": "Totals for your Thingport 3D model library",+ "title": "Library",+ "option": {+ "showModels": {+ "label": "Show models"+ },+ "showCollections": {+ "label": "Show collections"+ },+ "showCategories": {+ "label": "Show categories"+ },+ "showAuthors": {+ "label": "Show authors"+ }+ },+ "models": "Models",+ "collections": "Collections",+ "categories": "Categories",+ "authors": "Authors"+ },+ "thingport-featuredModel": {+ "name": "Thingport Featured Model",+ "description": "One model from your Thingport library each day, spinning in 3D",+ "option": {+ "autoRotate": {+ "label": "Spin the model"+ },+ "showDetails": {+ "label": "Show model details"+ }+ },+ "title": "Featured model",+ "empty": "No 3D models to feature yet",+ "hint": "Drag to spin, click to open",+ "noPreview": "No 3D preview for this model yet",+ "views": "{count, plural, one {# view} other {# views}}",+ "prints": "{count, plural, one {# print} other {# prints}}"+ },+ "thingport-activityHeatmap": {+ "name": "Thingport Activity Heatmap",+ "description": "A year of imports, downloads and slicer opens from your Thingport profile",+ "title": "Activity",+ "option": {+ "weekStart": {+ "label": "First day of the week",+ "option": {+ "sunday": "Sunday",+ "monday": "Monday"+ }+ },+ "showTotal": {+ "label": "Show total"+ },+ "showLegend": {+ "label": "Show legend"+ }+ },+ "lastYear": "Last 12 months",+ "totalLastYear": "{count, plural, one {# activity in the last year} other {# activities in the last year}}",+ "totalInYear": "{count, plural, one {# activity in {year}} other {# activities in {year}}}",+ "dayTotal": "{count, plural, one {# activity on {date}} other {# activities on {date}}}",+ "dayEmpty": "No activity on {date}",+ "kinds": {+ "import": "Imported",+ "upload": "Uploaded",+ "download": "Downloaded",+ "slicer": "Opened in slicer",+ "delete": "Deleted"+ },+ "less": "Less",+ "more": "More"+ },+ "thingport-models": {+ "name": "Thingport Models",+ "description": "Recently added, most viewed and most printed models from Thingport",+ "title": "Models",+ "option": {+ "defaultTab": {+ "label": "Default tab"+ },+ "itemCount": {+ "label": "Number of models"+ },+ "showThumbnails": {+ "label": "Show thumbnails"+ }+ },+ "tab": {+ "recentlyAdded": "Recent",+ "topViewed": "Top viewed",+ "topPrinted": "Top printed"+ },+ "empty": {+ "recentlyAdded": "No models in your library yet",+ "topViewed": "No viewed models yet",+ "topPrinted": "No printed models yet"+ },+ "views": "{count, plural, one {# view} other {# views}}",+ "prints": "{count, plural, one {# print} other {# prints}}"+ },"paperlessNgx": {"description": "Overview of your Paperless-ngx document archive","documentsTotal": "Total Documents",diff --git a/packages/ui/src/widget-icons.ts b/packages/ui/src/widget-icons.tsindex e1eb2dc46..9cbb49748 100644--- a/packages/ui/src/widget-icons.ts+++ b/packages/ui/src/widget-icons.ts@@ -15,12 +15,15 @@ import {IconBuildingBank,IconBusStop,IconCalendar,+ IconCalendarStats,IconChartAreaLine,IconChartBar,IconClock,IconClockPlay,IconCloud,IconCpu,+ IconCube,+ IconCube3dSphere,IconDeviceCctv,IconDeviceGamepad,IconDownload,@@ -38,6 +41,7 @@ import {IconReportSearch,IconRocket,IconRobot,+ IconRotate360,IconRoute,IconRss,IconServer2,@@ -108,6 +112,10 @@ export const widgetCatalogIcons: Record<WidgetKind, TablerIcon> = {"immich-serverStats": IconGraphFilled,"immich-albumCarousel": IconPhoto,paperlessNgx: IconFileText,+ "thingport-libraryStats": IconCube,+ "thingport-models": IconCube3dSphere,+ "thingport-featuredModel": IconRotate360,+ "thingport-activityHeatmap": IconCalendarStats,patchmon: IconShieldCheck,bazarr: IconBadgeCc,tracearr: IconActivityHeartbeat,diff --git a/packages/widgets/package.json b/packages/widgets/package.jsonindex e1b7728ef..24af4e3e6 100644--- a/packages/widgets/package.json+++ b/packages/widgets/package.json@@ -110,11 +110,13 @@"rehype-raw": "catalog:","rehype-sanitize": "catalog:","remark-gfm": "catalog:",+ "three": "catalog:","video.js": "catalog:","zod": "catalog:"},"devDependencies": {"@homarr/tsconfig": "workspace:^0.1.0",+ "@types/three": "catalog:","@types/video.js": "catalog:","typescript": "catalog:"}diff --git a/packages/widgets/src/option-translation.ts b/packages/widgets/src/option-translation.tsindex 47084abfe..a93863b91 100644--- a/packages/widgets/src/option-translation.ts+++ b/packages/widgets/src/option-translation.ts@@ -46,6 +46,10 @@ const getSharedOptionProperty = (kind: WidgetKind, property: string): string =>};const getSharedOptionNamespace = (kind: WidgetKind, property: string): string | undefined => {+ if (kind.startsWith("thingport-") && (property === "showTitle" || property === "openInNewTab")) {+ return "widget.common";+ }+if ((kind === "beszelSystemTable" || kind === "beszelSystemGrid") && BESZEL_OPTION_PROPERTIES.has(property)) {return "widget.beszel.options";}diff --git a/packages/widgets/src/refetch-intervals.ts b/packages/widgets/src/refetch-intervals.tsindex 78cb086bd..c35a2ca59 100644--- a/packages/widgets/src/refetch-intervals.ts+++ b/packages/widgets/src/refetch-intervals.ts@@ -32,6 +32,10 @@ export const widgetQueryRefetchIntervals = [{ queryKey: [["widget", "minecraft", "getServerStatus"]], intervalSeconds: null },{ queryKey: [["widget", "networkController"]], intervalSeconds: null },{ queryKey: [["widget", "paperlessNgx"]], intervalSeconds: null },+ { queryKey: [["widget", "thingport", "getActivity"]], intervalSeconds: null },+ { queryKey: [["widget", "thingport", "getFeaturedModel"]], intervalSeconds: null },+ { queryKey: [["widget", "thingport", "getLibraryStats"]], intervalSeconds: null },+ { queryKey: [["widget", "thingport", "getModels"]], intervalSeconds: null },{ queryKey: [["widget", "releases", "getLatest"]], intervalSeconds: null },{ queryKey: [["widget", "releases", "getServiceVersions"]], intervalSeconds: null },{ queryKey: [["widget", "rssFeed", "getFeeds"]], intervalSeconds: null },diff --git a/packages/widgets/src/registry.ts b/packages/widgets/src/registry.tsindex a2ad8a024..8af84f511 100644--- a/packages/widgets/src/registry.ts+++ b/packages/widgets/src/registry.ts@@ -40,6 +40,10 @@ import type * as networkControllerSummary from "./network-controller/summary";import type * as notebook from "./notebook";import type * as notifications from "./notifications";import type * as paperlessNgx from "./paperless-ngx";+import type * as thingportLibraryStats from "./thingport/library-stats";+import type * as thingportModels from "./thingport/models";+import type * as thingportFeaturedModel from "./thingport/featured-model";+import type * as thingportActivityHeatmap from "./thingport/activity-heatmap";import type * as patchmon from "./patchmon";import type * as releases from "./releases";import type * as rssFeed from "./rssFeed";@@ -117,6 +121,10 @@ export const widgetModuleLoaders = {"immich-albumCarousel": () => import("./immich/album-carousel"),stats: () => import("./stats"),paperlessNgx: () => import("./paperless-ngx"),+ "thingport-libraryStats": () => import("./thingport/library-stats"),+ "thingport-models": () => import("./thingport/models"),+ "thingport-featuredModel": () => import("./thingport/featured-model"),+ "thingport-activityHeatmap": () => import("./thingport/activity-heatmap"),patchmon: () => import("./patchmon"),tracearr: () => import("./tracearr"),speedtestTracker: () => import("./speedtest-tracker"),@@ -189,6 +197,10 @@ export type WidgetImports = {"immich-albumCarousel": typeof immichAlbumCarousel;stats: typeof stats;paperlessNgx: typeof paperlessNgx;+ "thingport-libraryStats": typeof thingportLibraryStats;+ "thingport-models": typeof thingportModels;+ "thingport-featuredModel": typeof thingportFeaturedModel;+ "thingport-activityHeatmap": typeof thingportActivityHeatmap;patchmon: typeof patchmon;tracearr: typeof tracearr;speedtestTracker: typeof speedtestTracker;@@ -268,6 +280,10 @@ export const widgetComponentLoaders = {"immich-albumCarousel": () => import("./immich/album-carousel/component"),stats: () => import("./stats/component"),paperlessNgx: () => import("./paperless-ngx/component"),+ "thingport-libraryStats": () => import("./thingport/library-stats/component"),+ "thingport-models": () => import("./thingport/models/component"),+ "thingport-featuredModel": () => import("./thingport/featured-model/component"),+ "thingport-activityHeatmap": () => import("./thingport/activity-heatmap/component"),patchmon: () => import("./patchmon/component"),tracearr: () => import("./tracearr/component"),speedtestTracker: () => import("./speedtest-tracker/component"),diff --git a/packages/widgets/src/thingport/activity-heatmap/calendar.spec.ts b/packages/widgets/src/thingport/activity-heatmap/calendar.spec.tsnew file mode 100644index 000000000..ad034b39d--- /dev/null+++ b/packages/widgets/src/thingport/activity-heatmap/calendar.spec.ts@@ -0,0 +1,34 @@+import { describe, expect, test } from "vitest";++import { buildWeeks, lastYearRange, level, monthStarts, yearRange } from "./calendar";++describe("thingport activity calendar", () => {+ test("last year range ends today and starts the day after a year ago", () => {+ expect(lastYearRange("2026-10-18")).toEqual({ from: "2025-10-19", to: "2026-10-18" });+ });++ test("weeks start on the requested weekday and pad the edges out of range", () => {+ // 1 January 2026 was a Thursday.+ const sundayWeeks = buildWeeks(yearRange(2026), 0);+ expect(sundayWeeks[0]?.[0]).toEqual({ date: "2025-12-28", inRange: false });+ expect(sundayWeeks[0]?.[4]).toEqual({ date: "2026-01-01", inRange: true });++ const mondayWeeks = buildWeeks(yearRange(2026), 1);+ expect(mondayWeeks[0]?.[0]?.date).toBe("2025-12-29");+ expect(mondayWeeks.every((week) => week.length === 7)).toBe(true);+ expect(mondayWeeks.at(-1)?.some((cell) => cell.date === "2026-12-31" && cell.inRange)).toBe(true);+ });++ test("month labels skip a month too close to the next", () => {+ const weeks = buildWeeks({ from: "2026-01-30", to: "2026-03-31" }, 0);+ expect(monthStarts(weeks).map((start) => start.month)).toEqual([1, 2]);+ });++ test("levels shade by share of the busiest day", () => {+ expect(level(0, 10)).toBe(0);+ expect(level(1, 10)).toBe(1);+ expect(level(5, 10)).toBe(2);+ expect(level(10, 10)).toBe(4);+ expect(level(3, 0)).toBe(0);+ });+});diff --git a/packages/widgets/src/thingport/activity-heatmap/calendar.ts b/packages/widgets/src/thingport/activity-heatmap/calendar.tsnew file mode 100644index 000000000..46e1770fb--- /dev/null+++ b/packages/widgets/src/thingport/activity-heatmap/calendar.ts@@ -0,0 +1,74 @@+// Date arithmetic for the heatmap, ported from Thingport's profile page. Works on YYYY-MM-DD strings+// in UTC so no time zone or DST shift can move a day; "today" comes from the viewer's own zone.++const DAY_MS = 86_400_000;++const toDate = (iso: string) => new Date(`${iso}T00:00:00Z`);+const toIso = (date: Date) => date.toISOString().slice(0, 10);+const pad = (value: number) => String(value).padStart(2, "0");++export const addDays = (iso: string, days: number) => toIso(new Date(toDate(iso).getTime() + days * DAY_MS));++/** The viewer's date, in their own time zone. */+export const localToday = (now: Date) => `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;++export interface DateRange {+ from: string;+ to: string;+}++/** The year up to and including today. */+export function lastYearRange(today: string): DateRange {+ const [year = 0, month = 1, day = 1] = today.split("-").map(Number);+ return { from: addDays(toIso(new Date(Date.UTC(year - 1, month - 1, day))), 1), to: today };+}++export const yearRange = (year: number): DateRange => ({ from: `${year}-01-01`, to: `${year}-12-31` });++export interface Cell {+ date: string;+ inRange: boolean;+}++/**+ * The range as columns of 7 days, the first column starting on `weekStart` (0 = Sunday). The first+ * and last weeks are filled out with the days around the range, marked out of range.+ */+export function buildWeeks(range: DateRange, weekStart: 0 | 1): Cell[][] {+ const lead = (toDate(range.from).getUTCDay() - weekStart + 7) % 7;+ const weeks: Cell[][] = [];+ let date = addDays(range.from, -lead);+ while (date <= range.to) {+ const week: Cell[] = [];+ for (let index = 0; index < 7; index++) {+ week.push({ date, inRange: date >= range.from && date <= range.to });+ date = addDays(date, 1);+ }+ weeks.push(week);+ }+ return weeks;+}++// A label needs this many columns before the next one (or the edge), as on GitHub; a month that+// barely starts in the range goes unlabelled rather than overlapping.+const MIN_LABEL_COLUMNS = 3;++/** Where each month's label goes: the first week holding a day of it, by column index. */+export function monthStarts(weeks: Cell[][]): { column: number; month: number }[] {+ const starts: { column: number; month: number }[] = [];+ weeks.forEach((week, column) => {+ const first = week.find((cell) => cell.inRange);+ if (!first) return;+ const month = toDate(first.date).getUTCMonth();+ if (starts.at(-1)?.month !== month) starts.push({ column, month });+ });+ return starts.filter(+ (start, index) => (starts[index + 1]?.column ?? weeks.length) - start.column >= MIN_LABEL_COLUMNS,+ );+}++/** 0 for no activity, then 1-4 by share of the busiest day, as GitHub shades its graph. */+export function level(count: number, max: number): 0 | 1 | 2 | 3 | 4 {+ if (count <= 0 || max <= 0) return 0;+ return Math.min(4, Math.ceil((count / max) * 4)) as 1 | 2 | 3 | 4;+}diff --git a/packages/widgets/src/thingport/activity-heatmap/component.module.css b/packages/widgets/src/thingport/activity-heatmap/component.module.cssnew file mode 100644index 000000000..febc1bc02--- /dev/null+++ b/packages/widgets/src/thingport/activity-heatmap/component.module.css@@ -0,0 +1,131 @@+.root {+ display: flex;+ flex-direction: column;+ height: 100%;+ min-height: 0;+ padding: 8px;+ gap: 6px;+ overflow: hidden;+}++.header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 8px;+ min-width: 0;+ height: 30px;+ flex-shrink: 0;+}++.total {+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ font-size: var(--mantine-font-size-sm);+ font-weight: 600;+ color: inherit;+ text-decoration: none;+}++.total:hover {+ text-decoration: underline;+}++.body {+ flex: 1;+ min-height: 0;+ display: flex;+ align-items: center;+ justify-content: center;+}++.calendar {+ display: inline-grid;+ grid-template-columns: auto auto;+ column-gap: 6px;+ row-gap: 4px;+}++.months {+ position: relative;+ height: 14px;+}++.month,+.weekday,+.legendLabel {+ font-size: 10px;+ line-height: 14px;+ color: var(--mantine-color-dimmed);+ white-space: nowrap;+}++.month {+ position: absolute;+ top: 0;+}++.weekdays {+ display: grid;+ grid-template-rows: repeat(7, var(--cell));+ row-gap: var(--gap);+}++.weekday {+ line-height: var(--cell);+}++.grid {+ display: grid;+ grid-auto-flow: column;+ grid-template-rows: repeat(7, var(--cell));+ grid-auto-columns: var(--cell);+ gap: var(--gap);+}++.cell {+ width: var(--cell);+ height: var(--cell);+ border-radius: 2px;+ outline: 1px solid light-dark(rgba(0, 0, 0, 0.04), rgba(255, 255, 255, 0.04));+ outline-offset: -1px;+}++.cell[data-level="0"] {+ background-color: light-dark(rgba(0, 0, 0, 0.06), rgba(255, 255, 255, 0.06));+}++.cell[data-level="1"] {+ background-color: color-mix(in srgb, var(--mantine-primary-color-filled) 30%, transparent);+}++.cell[data-level="2"] {+ background-color: color-mix(in srgb, var(--mantine-primary-color-filled) 50%, transparent);+}++.cell[data-level="3"] {+ background-color: color-mix(in srgb, var(--mantine-primary-color-filled) 75%, transparent);+}++.cell[data-level="4"] {+ background-color: var(--mantine-primary-color-filled);+}++.cell[data-future] {+ opacity: 0.4;+}++.legend {+ display: flex;+ align-items: center;+ justify-content: flex-end;+ gap: 3px;+ flex-shrink: 0;+ --cell: 10px;+}++.legendLabel {+ margin-inline: 3px;+}diff --git a/packages/widgets/src/thingport/activity-heatmap/component.tsx b/packages/widgets/src/thingport/activity-heatmap/component.tsxnew file mode 100644index 000000000..76f37dfe5--- /dev/null+++ b/packages/widgets/src/thingport/activity-heatmap/component.tsx@@ -0,0 +1,260 @@+"use client";++import type { CSSProperties } from "react";+import { useMemo, useState } from "react";+import { Group, Select, Text, Tooltip } from "@mantine/core";+import { getQueryKey } from "@trpc/react-query";++import { clientApi } from "@homarr/api/client";+import { thingportActivityKinds } from "@homarr/integrations/types";+import type { ThingportActivityDay } from "@homarr/integrations/types";+import { useCurrentIntlLocale, useI18n } from "@homarr/translation/client";++import { getSafeApplicationUrl, SAFE_NEW_TAB_REL } from "../../common/application-url";+import { getUsableWidgetQueryData } from "../../common/query-state";+import { WidgetQueryLoadingState } from "../../common/query-state-indicator";+import { useWidgetNow } from "../../common/use-widget-now";+import type { WidgetComponentProps } from "../../definition";+import { useWidgetRuntimeQueries } from "../../runtime-hooks";+import { getRenderedSize } from "../common/rendered-size";+import { canShowThingportHeader, ThingportWidgetHeader } from "../common/widget-header";+import { buildWeeks, lastYearRange, level, localToday, monthStarts, yearRange } from "./calendar";+import classes from "./component.module.css";++const PADDING = 8;+const SECTION_GAP = 6;+// Fits the xs year picker.+const HEADER_HEIGHT = 30;+const MONTH_ROW_HEIGHT = 14 + 4;+const LEGEND_HEIGHT = 14;+const WEEKDAY_COLUMN_WIDTH = 26 + 6;+const MIN_CELL = 9;+const MAX_CELL = 18;+const LAST_YEAR = "last";++const gapFor = (cell: number) => (cell >= 14 ? 4 : 3);++const dayTotal = (counts: ThingportActivityDay["counts"]) =>+ Object.values(counts).reduce((sum, count) => sum + (count ?? 0), 0);++/** GitHub's contribution graph, as on the Thingport profile page: a column per week, darker the busier the day. */+export default function ThingportActivityHeatmapWidget({+ integrationIds,+ options,+ widgetRuntimeRef,+ ...sizeProps+}: WidgetComponentProps<"thingport-activityHeatmap">) {+ // Laid out in the widget's own (logical) pixels; only the cell size limits and the weekday cut-off are meant on+ // screen, so they are converted with the board's zoom.+ const { width, height } = sizeProps;+ const rendered = getRenderedSize(sizeProps);+ const { scale } = rendered;+ const t = useI18n("widget.thingport-activityHeatmap");+ const locale = useCurrentIntlLocale();+ const now = useWidgetNow("day");+ const today = now ? localToday(now) : null;+ // Null is the last 12 months; a year is that calendar year.+ const [year, setYear] = useState<number | null>(null);+ const range = useMemo(() => (year !== null ? yearRange(year) : today ? lastYearRange(today) : null), [year, today]);+ const input = {+ integrationId: integrationIds[0] ?? "",+ from: range?.from ?? "",+ to: range?.to ?? "",+ timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,+ };+ const query = clientApi.widget.thingport.getActivity.useQuery(input, {+ enabled: range !== null,+ placeholderData: (previous) => previous,+ });+ const activity = getUsableWidgetQueryData(query);+ useWidgetRuntimeQueries(widgetRuntimeRef, [getQueryKey(clientApi.widget.thingport.getActivity, input, "query")]);++ const weekStart = options.weekStart === "monday" ? 1 : 0;+ const allWeeks = useMemo(() => (range ? buildWeeks(range, weekStart) : []), [range, weekStart]);+ const byDate = useMemo(() => new Map((activity?.days ?? []).map((day) => [day.date, day.counts])), [activity?.days]);+ const max = useMemo(+ () => Math.max(0, ...(activity?.days ?? []).map((day) => dayTotal(day.counts))),+ [activity?.days],+ );+ const [hoveredDate, setHoveredDate] = useState<string | null>(null);++ if (!range || !today) return <WidgetQueryLoadingState />;++ const showLogo = options.showTitle && canShowThingportHeader(rendered.width, rendered.height);+ const showHeader = showLogo || options.showTotal || (activity?.years.length ?? 0) > 1;+ const availableHeight =+ height -+ PADDING * 2 -+ (showHeader ? HEADER_HEIGHT + SECTION_GAP : 0) -+ (options.showLegend ? LEGEND_HEIGHT + SECTION_GAP : 0) -+ MONTH_ROW_HEIGHT;+ const showWeekdays = rendered.width >= 240;+ const availableWidth = width - PADDING * 2 - (showWeekdays ? WEEKDAY_COLUMN_WIDTH : 0);++ // Square cells sized to the height; when every week can't fit across, the oldest are dropped, as GitHub+ // does on a narrow screen.+ // The gap grows with the cell on screen, so size for the larger gap and the cells never overrun the height.+ const minCell = MIN_CELL / scale;+ const maxCell = MAX_CELL / scale;+ const cellByHeight = (availableHeight - 6 * (4 / scale)) / 7;+ const cellAcrossAllWeeks = (availableWidth + 3 / scale) / allWeeks.length - 3 / scale;+ const cell = Math.max(+ 6 / scale,+ Math.min(maxCell, cellByHeight, cellAcrossAllWeeks >= minCell ? cellAcrossAllWeeks : maxCell),+ );+ const gap = gapFor(cell * scale) / scale;+ const visibleCount = Math.max(1, Math.min(allWeeks.length, Math.floor((availableWidth + gap) / (cell + gap))));+ const weeks = allWeeks.slice(-visibleCount);+ const months = monthStarts(weeks);++ const monthName = new Intl.DateTimeFormat(locale, { month: "short", timeZone: "UTC" });+ const weekdayName = new Intl.DateTimeFormat(locale, { weekday: "short", timeZone: "UTC" });+ const longDate = new Intl.DateTimeFormat(locale, { dateStyle: "long", timeZone: "UTC" });+ // Every other row is labelled, as on GitHub. 4 January 2026 was a Sunday.+ const rowLabel = (row: number) =>+ row % 2 === 1 ? weekdayName.format(new Date(Date.UTC(2026, 0, 4 + ((row + weekStart) % 7)))) : "";++ const profileUrl = getSafeApplicationUrl(activity?.profileUrl);+ const years = activity?.years ?? [];+ const totalLabel = activity+ ? year === null+ ? t("totalLastYear", { count: activity.total })+ : t("totalInYear", { count: activity.total, year })+ : "";++ const totalLink = (+ <a href={profileUrl} target="_blank" rel={SAFE_NEW_TAB_REL} className={classes.total}>+ {totalLabel}+ </a>+ );++ return (+ <div className={classes.root} style={{ "--cell": `${cell}px`, "--gap": `${gap}px` } as CSSProperties}>+ {showHeader && (+ <div className={classes.header}>+ {showLogo ? (+ <ThingportWidgetHeader title={options.showTotal ? totalLink : t("title")} />+ ) : options.showTotal ? (+ totalLink+ ) : (+ <span />+ )}+ {years.length > 1 && (+ <Select+ size="xs"+ w={130}+ allowDeselect={false}+ comboboxProps={{ withinPortal: true }}+ value={year === null ? LAST_YEAR : String(year)}+ onChange={(value) => {+ const next = value === null || value === LAST_YEAR ? null : Number(value);+ // This year is the default view, the last 12 months, as on Thingport.+ setYear(next === now?.getFullYear() ? null : next);+ }}+ data={[+ { value: LAST_YEAR, label: t("lastYear") },+ ...years+ .filter((option) => option !== now?.getFullYear())+ .map((option) => ({ value: String(option), label: String(option) })),+ ]}+ />+ )}+ </div>+ )}++ <div className={classes.body}>+ <div className={classes.calendar} style={{ gridTemplateColumns: showWeekdays ? "auto auto" : "auto" }}>+ {showWeekdays ? <div /> : null}+ <div className={classes.months} style={{ width: weeks.length * (cell + gap) - gap }}>+ {months.map(({ column, month }) => (+ <span key={`${column}-${month}`} className={classes.month} style={{ left: column * (cell + gap) }}>+ {monthName.format(new Date(Date.UTC(2026, month, 1)))}+ </span>+ ))}+ </div>+ {showWeekdays ? (+ <div className={classes.weekdays}>+ {Array.from({ length: 7 }, (_, row) => (+ <span key={row} className={classes.weekday}>+ {rowLabel(row)}+ </span>+ ))}+ </div>+ ) : null}+ {/* One tooltip for the whole grid, fed by whichever day is under the pointer. */}+ <Tooltip.Floating+ disabled={!hoveredDate}+ label={+ hoveredDate ? (+ <DayTooltip date={hoveredDate} counts={byDate.get(hoveredDate) ?? {}} format={longDate} />+ ) : null+ }+ >+ <div+ className={classes.grid}+ onPointerOver={(event) => {+ const date = (event.target as HTMLElement).dataset.date ?? null;+ if (date !== hoveredDate) setHoveredDate(date);+ }}+ onPointerLeave={() => setHoveredDate(null)}+ >+ {weeks.flat().map(({ date, inRange }) => {+ if (!inRange) return <span key={date} />;+ const total = dayTotal(byDate.get(date) ?? {});+ return (+ <span+ key={date}+ data-date={date}+ data-level={level(total, max)}+ data-future={date > today ? true : undefined}+ className={classes.cell}+ />+ );+ })}+ </div>+ </Tooltip.Floating>+ </div>+ </div>++ {options.showLegend && (+ <div className={classes.legend}>+ <span className={classes.legendLabel}>{t("less")}</span>+ {[0, 1, 2, 3, 4].map((value) => (+ <span key={value} data-level={value} className={classes.cell} />+ ))}+ <span className={classes.legendLabel}>{t("more")}</span>+ </div>+ )}+ </div>+ );+}++interface DayTooltipProps {+ date: string;+ counts: ThingportActivityDay["counts"];+ format: Intl.DateTimeFormat;+}++function DayTooltip({ date, counts, format }: DayTooltipProps) {+ const t = useI18n("widget.thingport-activityHeatmap");+ const total = dayTotal(counts);+ const label = format.format(new Date(`${date}T00:00:00Z`));++ return (+ <div>+ <Text size="xs" fw={700}>+ {total ? t("dayTotal", { count: total, date: label }) : t("dayEmpty", { date: label })}+ </Text>+ {thingportActivityKinds+ .filter((kind) => counts[kind])+ .map((kind) => (+ <Group key={kind} justify="space-between" gap="md" wrap="nowrap">+ <Text size="xs">{t(`kinds.${kind}`)}</Text>+ <Text size="xs" fw={600}>+ {counts[kind]}+ </Text>+ </Group>+ ))}+ </div>+ );+}diff --git a/packages/widgets/src/thingport/activity-heatmap/index.ts b/packages/widgets/src/thingport/activity-heatmap/index.tsnew file mode 100644index 000000000..2d3e33bf9--- /dev/null+++ b/packages/widgets/src/thingport/activity-heatmap/index.ts@@ -0,0 +1,35 @@+import { IconCalendarStats } from "@tabler/icons-react";++import { getWidgetIntegrationConfig } from "@homarr/definitions";++import { createWidgetDefinition, matchesWidgetRuntimeQuery } from "../../definition";+import { optionsBuilder } from "../../options";++export const { definition, componentLoader } = createWidgetDefinition("thingport-activityHeatmap", {+ icon: IconCalendarStats,+ supportsAdvancedFocus: false,+ queryKey: [["widget", "thingport", "getActivity"]],+ queryMatcher: matchesWidgetRuntimeQuery,+ refetchInterval: null,+ ...getWidgetIntegrationConfig("thingport-activityHeatmap"),+ createOptions() {+ return optionsBuilder.from((factory) => ({+ showTitle: factory.switch({ defaultValue: false }),+ weekStart: factory.select({+ options: [+ {+ label: (t) => t("widget.thingport-activityHeatmap.option.weekStart.option.sunday"),+ value: "sunday",+ },+ {+ label: (t) => t("widget.thingport-activityHeatmap.option.weekStart.option.monday"),+ value: "monday",+ },+ ] as const,+ defaultValue: "sunday",+ }),+ showTotal: factory.switch({ defaultValue: true }),+ showLegend: factory.switch({ defaultValue: true }),+ }));+ },+}).withDynamicImport(() => import("./component"));diff --git a/packages/widgets/src/thingport/common/rendered-size.ts b/packages/widgets/src/thingport/common/rendered-size.tsnew file mode 100644index 000000000..587155abb--- /dev/null+++ b/packages/widgets/src/thingport/common/rendered-size.ts@@ -0,0 +1,16 @@+import type { WidgetComponentProps } from "../../definition";++type SizeProps = Pick<+ WidgetComponentProps<"thingport-libraryStats">,+ "width" | "height" | "displayScale" | "displayMode"+>;++/**+ * The widget's size as the viewer sees it. The board zooms its whole canvas, so `width` and `height` are logical+ * pixels; size breakpoints compare against what is on screen, as the Paperless-ngx and UPS widgets do. The advanced+ * view is drawn unscaled.+ */+export function getRenderedSize({ width, height, displayScale = 1, displayMode = "compact" }: SizeProps) {+ const scale = displayMode === "compact" && Number.isFinite(displayScale) && displayScale > 0 ? displayScale : 1;+ return { width: width * scale, height: height * scale, scale };+}diff --git a/packages/widgets/src/thingport/common/widget-header.tsx b/packages/widgets/src/thingport/common/widget-header.tsxnew file mode 100644index 000000000..22c802788--- /dev/null+++ b/packages/widgets/src/thingport/common/widget-header.tsx@@ -0,0 +1,39 @@+"use client";++import type { ReactNode } from "react";+import { Group, Image, Text } from "@mantine/core";++import { getIconUrl } from "@homarr/definitions";++// Dashboard Icons' default logo has a near-black outline for light backgrounds; the "-dark" variant+// swaps it for white, for dark themes.+const darkIconUrl = "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/thingport-dark.svg";+const LOGO_SIZE = 20;++// Below these the header would crowd out the widget's own content, as WUD's title hides on a tiny widget.+const MIN_WIDTH = 160;+const MIN_HEIGHT = 120;++export const canShowThingportHeader = (width: number, height: number) => width >= MIN_WIDTH && height >= MIN_HEIGHT;++interface ThingportWidgetHeaderProps {+ title: ReactNode;+ rightSection?: ReactNode;+}++/** The optional title row shared by the Thingport widgets: the Thingport logo and a dimmed title. */+export function ThingportWidgetHeader({ title, rightSection }: ThingportWidgetHeaderProps) {+ return (+ <Group gap="xs" wrap="nowrap" justify="space-between" miw={0} style={{ flexShrink: 0 }}>+ <Group gap="xs" wrap="nowrap" miw={0}>+ {/* Both are rendered and CSS hides one, so the right logo shows from the first paint with no flash. */}+ <Image src={getIconUrl("thingport")} alt="" aria-hidden w={LOGO_SIZE} h={LOGO_SIZE} fit="contain" darkHidden />+ <Image src={darkIconUrl} alt="" aria-hidden w={LOGO_SIZE} h={LOGO_SIZE} fit="contain" lightHidden />+ <Text size="sm" c="dimmed" lineClamp={1}>+ {title}+ </Text>+ </Group>+ {rightSection}+ </Group>+ );+}diff --git a/packages/widgets/src/thingport/featured-model/component.module.css b/packages/widgets/src/thingport/featured-model/component.module.cssnew file mode 100644index 000000000..7240d7e80--- /dev/null+++ b/packages/widgets/src/thingport/featured-model/component.module.css@@ -0,0 +1,34 @@+.root {+ display: flex;+ flex-direction: column;+ height: 100%;+ min-height: 0;+ padding: var(--mantine-spacing-xs);+ gap: 6px;+}++.stage {+ position: relative;+ flex: 1;+ min-height: 0;+ border-radius: var(--mantine-radius-md);+ overflow: hidden;+}++.thumbnailLink {+ display: block;+ height: 100%;+}++.details {+ display: block;+ min-width: 0;+ padding: 2px 4px;+ border-radius: var(--mantine-radius-sm);+ color: inherit;+ text-decoration: none;+}++.details:hover {+ background-color: light-dark(var(--mantine-color-gray-1), var(--mantine-color-dark-5));+}diff --git a/packages/widgets/src/thingport/featured-model/component.tsx b/packages/widgets/src/thingport/featured-model/component.tsxnew file mode 100644index 000000000..545defd62--- /dev/null+++ b/packages/widgets/src/thingport/featured-model/component.tsx@@ -0,0 +1,137 @@+"use client";++import { useState } from "react";+import dynamic from "next/dynamic";+import {+ Center,+ Image,+ Loader,+ Stack,+ Text,+ parseThemeColor,+ useComputedColorScheme,+ useMantineTheme,+} from "@mantine/core";+import { IconCube } from "@tabler/icons-react";+import { getQueryKey } from "@trpc/react-query";++import { clientApi } from "@homarr/api/client";+import { useI18n } from "@homarr/translation/client";++import { getSafeApplicationUrl, SAFE_NEW_TAB_REL } from "../../common/application-url";+import { getUsableWidgetQueryData, isInitialWidgetQueryPending } from "../../common/query-state";+import { WidgetQueryLoadingState } from "../../common/query-state-indicator";+import { useWidgetNow } from "../../common/use-widget-now";+import type { WidgetComponentProps } from "../../definition";+import { useWidgetRuntimeQueries } from "../../runtime-hooks";+import { getRenderedSize } from "../common/rendered-size";+import { canShowThingportHeader, ThingportWidgetHeader } from "../common/widget-header";+import classes from "./component.module.css";++const ThingportModelViewer = dynamic(() => import("./model-viewer").then((module) => module.ThingportModelViewer), {+ ssr: false,+});++const pad = (value: number) => String(value).padStart(2, "0");+const toLocalDate = (date: Date) => `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;++export default function ThingportFeaturedModelWidget({+ integrationIds,+ options,+ isEditMode,+ widgetRuntimeRef,+ ...sizeProps+}: WidgetComponentProps<"thingport-featuredModel">) {+ const { width, height } = getRenderedSize(sizeProps);+ const t = useI18n("widget.thingport-featuredModel");+ const theme = useMantineTheme();+ const colorScheme = useComputedColorScheme("dark");+ // Thingport picks one model a day; asking with the viewer's date moves it on at their midnight.+ const now = useWidgetNow("day");+ const input = { integrationId: integrationIds[0] ?? "", date: now ? toLocalDate(now) : "" };+ const query = clientApi.widget.thingport.getFeaturedModel.useQuery(input, { enabled: now !== null });+ const model = getUsableWidgetQueryData(query);+ useWidgetRuntimeQueries(widgetRuntimeRef, [getQueryKey(clientApi.widget.thingport.getFeaturedModel, input, "query")]);+ const [failedMeshUrl, setFailedMeshUrl] = useState<string | null>(null);+ const [loadedMeshUrl, setLoadedMeshUrl] = useState<string | null>(null);++ if (now === null || isInitialWidgetQueryPending(query)) return <WidgetQueryLoadingState />;++ if (!model) {+ return (+ <Center h="100%" p="sm">+ <Text c="dimmed" size="sm" ta="center">+ {t("empty")}+ </Text>+ </Center>+ );+ }++ const href = getSafeApplicationUrl(model.href);+ const linkProps = {+ href,+ target: options.openInNewTab ? "_blank" : undefined,+ rel: options.openInNewTab ? SAFE_NEW_TAB_REL : undefined,+ };+ const open = () => {+ if (!href || isEditMode) return;+ if (options.openInNewTab) window.open(href, "_blank", "noopener,noreferrer");+ else window.location.assign(href);+ };+ const mesh = model.mesh && model.mesh.url !== failedMeshUrl ? model.mesh : null;+ const color = parseThemeColor({ color: theme.primaryColor, theme, colorScheme }).value;+ const meta = [model.author, t("views", { count: model.viewCount }), t("prints", { count: model.printCount })]+ .filter(Boolean)+ .join(" · ");++ return (+ <div className={classes.root}>+ {options.showTitle && canShowThingportHeader(width, height) && <ThingportWidgetHeader title={t("title")} />}++ <div className={classes.stage} title={mesh ? t("hint") : undefined}>+ {mesh ? (+ <>+ <ThingportModelViewer+ url={mesh.url}+ format={mesh.format}+ color={color}+ autoRotate={options.autoRotate}+ onOpen={open}+ onLoaded={() => setLoadedMeshUrl(mesh.url)}+ onError={() => setFailedMeshUrl(mesh.url)}+ />+ {loadedMeshUrl !== mesh.url && (+ <Center pos="absolute" inset={0} style={{ pointerEvents: "none" }}>+ <Loader size="sm" />+ </Center>+ )}+ </>+ ) : model.thumbnailUrl ? (+ <a {...linkProps} aria-label={model.name} className={classes.thumbnailLink}>+ <Image src={model.thumbnailUrl} alt="" fit="contain" h="100%" />+ </a>+ ) : (+ <Center h="100%">+ <Stack gap={4} align="center">+ <IconCube size={32} stroke={1.5} color="var(--mantine-color-dimmed)" />+ <Text c="dimmed" size="xs" ta="center">+ {t("noPreview")}+ </Text>+ </Stack>+ </Center>+ )}+ </div>++ {options.showDetails && (+ <a {...linkProps} className={classes.details}>+ <Text size="sm" fw={500} truncate="end" title={model.name}>+ {model.name}+ </Text>+ <Text size="xs" c="dimmed" truncate="end">+ {meta}+ </Text>+ </a>+ )}+ </div>+ );+}diff --git a/packages/widgets/src/thingport/featured-model/index.ts b/packages/widgets/src/thingport/featured-model/index.tsnew file mode 100644index 000000000..e85f0ff7f--- /dev/null+++ b/packages/widgets/src/thingport/featured-model/index.ts@@ -0,0 +1,23 @@+import { IconRotate360 } from "@tabler/icons-react";++import { getWidgetIntegrationConfig } from "@homarr/definitions";++import { createWidgetDefinition, matchesWidgetRuntimeQuery } from "../../definition";+import { optionsBuilder } from "../../options";++export const { definition, componentLoader } = createWidgetDefinition("thingport-featuredModel", {+ icon: IconRotate360,+ supportsAdvancedFocus: false,+ queryKey: [["widget", "thingport", "getFeaturedModel"]],+ queryMatcher: matchesWidgetRuntimeQuery,+ refetchInterval: null,+ ...getWidgetIntegrationConfig("thingport-featuredModel"),+ createOptions() {+ return optionsBuilder.from((factory) => ({+ showTitle: factory.switch({ defaultValue: false }),+ autoRotate: factory.switch({ defaultValue: true }),+ showDetails: factory.switch({ defaultValue: true }),+ openInNewTab: factory.switch({ defaultValue: true }),+ }));+ },+}).withDynamicImport(() => import("./component"));diff --git a/packages/widgets/src/thingport/featured-model/model-viewer.tsx b/packages/widgets/src/thingport/featured-model/model-viewer.tsxnew file mode 100644index 000000000..2ed727eba--- /dev/null+++ b/packages/widgets/src/thingport/featured-model/model-viewer.tsx@@ -0,0 +1,250 @@+"use client";++import { useEffect, useRef } from "react";+import * as THREE from "three";+import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";+import { RoomEnvironment } from "three/examples/jsm/environments/RoomEnvironment.js";+import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";+import { STLLoader } from "three/examples/jsm/loaders/STLLoader.js";++import type { ThingportMeshFormat } from "@homarr/integrations/types";++// Further than this between press and release is a spin, not a click to open the model.+const CLICK_SLOP_PX = 6;+// Thingport's featured card frames the model from above and in front.+const VIEW_DIRECTION = new THREE.Vector3(0, 1, 1).normalize();+const KEY_LIGHT_OFFSET = new THREE.Vector3(60, 260, 90).normalize();++interface ModelViewerProps {+ url: string;+ format: ThingportMeshFormat;+ color: string;+ autoRotate: boolean;+ onOpen: () => void;+ onLoaded: () => void;+ onError: () => void;+}++function disposeMaterials(materials: Iterable<THREE.Material>) {+ const textures = new Set<THREE.Texture>();+ for (const material of materials) {+ for (const value of Object.values(material)) {+ if (value instanceof THREE.Texture) textures.add(value);+ }+ material.dispose();+ }+ for (const texture of textures) {+ const image: unknown = texture.source.data;+ if (typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap) image.close();+ texture.dispose();+ }+}++function disposeObject(object: THREE.Object3D) {+ const materials = new Set<THREE.Material>();+ object.traverse((child) => {+ if (!(child instanceof THREE.Mesh)) return;+ child.geometry.dispose();+ for (const material of Array.isArray(child.material) ? child.material : [child.material]) {+ materials.add(material);+ }+ });+ disposeMaterials(materials);+}++async function loadObjectAsync(url: string, format: ThingportMeshFormat, signal: AbortSignal) {+ const response = await fetch(url, { signal });+ if (!response.ok) throw new Error(`Thingport model request failed with ${response.status}`);+ const buffer = await response.arrayBuffer();++ if (format === "glb") {+ const manager = new THREE.LoadingManager();+ // The preview is self-contained. Never let a model fetch arbitrary browser URLs.+ manager.setURLModifier((resourceUrl) => {+ signal.throwIfAborted();+ if (resourceUrl.startsWith("blob:") || resourceUrl.startsWith("data:")) return resourceUrl;+ throw new Error("Thingport previews cannot load external resources");+ });+ // The server's preview is already Y-up.+ const gltf = await new GLTFLoader(manager).parseAsync(buffer, "");+ return gltf.scene;+ }++ const mesh = new THREE.Mesh(new STLLoader().parse(buffer));+ // Print files are Z-up; three.js is Y-up.+ mesh.rotateX(-Math.PI / 2);+ return mesh;+}++/** A model spinning slowly in the primary colour; drag to turn it, click to open it. */+export function ThingportModelViewer({ url, format, color, autoRotate, onOpen, onLoaded, onError }: ModelViewerProps) {+ const mountRef = useRef<HTMLDivElement>(null);+ const materialRef = useRef<THREE.MeshStandardMaterial | null>(null);+ const controlsRef = useRef<OrbitControls | null>(null);+ // Read inside the effect without reloading the model when they change.+ const callbacksRef = useRef({ onOpen, onLoaded, onError });+ callbacksRef.current = { onOpen, onLoaded, onError };+ const initialRef = useRef({ color, autoRotate });++ useEffect(() => {+ const mount = mountRef.current;+ if (!mount) return;+ const abortController = new AbortController();++ let renderer: THREE.WebGLRenderer;+ try {+ renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });+ } catch (error) {+ // WebGL off (no hardware acceleration) or out of contexts: fall back to the thumbnail, not the error card.+ console.warn("WebGL is unavailable for the Thingport featured model", error);+ callbacksRef.current.onError();+ return;+ }+ renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));+ // Keeps saturated colours from clipping to white under the room lighting.+ renderer.toneMapping = THREE.ACESFilmicToneMapping;+ renderer.toneMappingExposure = 0.85;+ renderer.setClearColor(0x000000, 0);+ renderer.domElement.style.display = "block";+ mount.appendChild(renderer.domElement);++ const scene = new THREE.Scene();+ const pmrem = new THREE.PMREMGenerator(renderer);+ const room = new RoomEnvironment();+ const environment = pmrem.fromScene(room, 0.04);+ room.dispose();+ scene.environment = environment.texture;+ const keyLight = new THREE.DirectionalLight(0xffffff, 0.9);+ scene.add(keyLight);++ const camera = new THREE.PerspectiveCamera(45, 1, 0.1, 10_000);+ const controls = new OrbitControls(camera, renderer.domElement);+ controls.enableDamping = true;+ controls.enablePan = false;+ // The wheel scrolls the board, not the model.+ controls.enableZoom = false;+ controls.autoRotate = initialRef.current.autoRotate;+ controlsRef.current = controls;++ const material = new THREE.MeshStandardMaterial({+ color: initialRef.current.color,+ metalness: 0.2,+ roughness: 0.8,+ });+ materialRef.current = material;++ const pivot = new THREE.Group();+ scene.add(pivot);+ let radius = 0;++ const frame = () => {+ const width = mount.clientWidth || 1;+ const height = mount.clientHeight || 1;+ renderer.setSize(width, height, false);+ renderer.domElement.style.width = "100%";+ renderer.domElement.style.height = "100%";+ camera.aspect = width / height;+ if (radius > 0) {+ // Fits the bounding sphere against both field-of-view axes, so no spin angle crops it.+ const verticalFov = THREE.MathUtils.degToRad(camera.fov);+ const horizontalFov = 2 * Math.atan(Math.tan(verticalFov / 2) * camera.aspect);+ const distance = 1.15 * Math.max(radius / Math.sin(verticalFov / 2), radius / Math.sin(horizontalFov / 2));+ const direction = camera.position.lengthSq() > 0 ? camera.position.clone().normalize() : VIEW_DIRECTION;+ camera.position.copy(direction).multiplyScalar(distance);+ camera.near = Math.max(distance / 1000, 0.01);+ camera.far = distance + radius * 4;+ controls.target.set(0, 0, 0);+ }+ camera.updateProjectionMatrix();+ controls.update();+ };+ const resizeObserver = new ResizeObserver(frame);+ resizeObserver.observe(mount);++ const render = () => {+ controls.update();+ // The light turns with the camera, so the lit side stays facing the viewer while it spins.+ keyLight.position+ .copy(KEY_LIGHT_OFFSET)+ .applyQuaternion(camera.quaternion)+ .multiplyScalar(radius * 3 || 100);+ renderer.render(scene, camera);+ };+ // Only animate while the widget is on screen.+ const intersectionObserver = new IntersectionObserver(([entry]) => {+ renderer.setAnimationLoop(entry?.isIntersecting ? render : null);+ });+ intersectionObserver.observe(mount);++ void loadObjectAsync(url, format, abortController.signal)+ .then((object) => {+ if (abortController.signal.aborted) {+ disposeObject(object);+ return;+ }+ // One material in the primary colour, as Thingport's own featured card draws it.+ const replacedMaterials = new Set<THREE.Material>();+ object.traverse((child) => {+ if (!(child instanceof THREE.Mesh)) return;+ const previous: THREE.Material | THREE.Material[] = child.material;+ for (const replaced of Array.isArray(previous) ? previous : [previous]) replacedMaterials.add(replaced);+ child.material = material;+ });+ disposeMaterials(replacedMaterials);+ const box = new THREE.Box3().setFromObject(object);+ object.position.sub(box.getCenter(new THREE.Vector3()));+ radius = Math.max(box.getSize(new THREE.Vector3()).length() / 2, 0.001);+ pivot.add(object);+ camera.position.copy(VIEW_DIRECTION);+ frame();+ callbacksRef.current.onLoaded();+ })+ .catch((error: unknown) => {+ if (abortController.signal.aborted) return;+ console.warn("Failed to load the Thingport featured model", error);+ callbacksRef.current.onError();+ });++ let pressedAt: { x: number; y: number } | null = null;+ const handlePointerDown = (event: PointerEvent) => (pressedAt = { x: event.clientX, y: event.clientY });+ const handleClick = (event: MouseEvent) => {+ if (pressedAt && Math.hypot(event.clientX - pressedAt.x, event.clientY - pressedAt.y) < CLICK_SLOP_PX) {+ callbacksRef.current.onOpen();+ }+ };+ renderer.domElement.addEventListener("pointerdown", handlePointerDown);+ renderer.domElement.addEventListener("click", handleClick);++ return () => {+ abortController.abort();+ resizeObserver.disconnect();+ intersectionObserver.disconnect();+ renderer.setAnimationLoop(null);+ renderer.domElement.removeEventListener("pointerdown", handlePointerDown);+ renderer.domElement.removeEventListener("click", handleClick);+ controls.dispose();+ pivot.traverse((child) => {+ if (child instanceof THREE.Mesh) child.geometry.dispose();+ });+ material.dispose();+ environment.dispose();+ pmrem.dispose();+ // Frees the GL context now rather than at garbage collection; one is made per model or remount.+ renderer.forceContextLoss();+ renderer.dispose();+ renderer.domElement.remove();+ materialRef.current = null;+ controlsRef.current = null;+ };+ }, [url, format]);++ useEffect(() => {+ materialRef.current?.color.set(color);+ }, [color]);++ useEffect(() => {+ if (controlsRef.current) controlsRef.current.autoRotate = autoRotate;+ }, [autoRotate]);++ return <div ref={mountRef} style={{ position: "absolute", inset: 0, cursor: "grab" }} />;+}diff --git a/packages/widgets/src/thingport/library-stats/component.module.css b/packages/widgets/src/thingport/library-stats/component.module.cssnew file mode 100644index 000000000..bb9d0dc85--- /dev/null+++ b/packages/widgets/src/thingport/library-stats/component.module.css@@ -0,0 +1,102 @@+.wrapper {+ display: flex;+ flex-direction: column;+ height: 100%;+ min-height: 0;+ padding: 8px;+ gap: 6px;+}++.root {+ container-type: size;+ display: grid;+ flex: 1;+ min-height: 0;+ gap: clamp(4px, 2cqi, 8px);+ grid-template-columns: repeat(var(--stat-cols, 2), minmax(0, 1fr));+ grid-auto-rows: 1fr;+ overflow: hidden;+}++/* Each tile is its own container, so its contents scale with the tile rather than the whole widget:+ four tiles on a 1x1 widget are small, one tile on the same widget is not. */+.tile {+ container-type: size;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ min-height: 0;+ min-width: 0;+ gap: 2px;+ padding: clamp(2px, 1.5cqi, 8px);+ border-radius: var(--mantine-radius-md);+ background-color: rgb(+ from light-dark(var(--mantine-color-gray-0), var(--mantine-color-dark-6)) r g b / var(--opacity, 1)+ );+ overflow: hidden;+ color: inherit;+ text-decoration: none;+ transition: background-color 120ms ease;+}++.tile:hover {+ background-color: light-dark(var(--mantine-color-gray-1), var(--mantine-color-dark-5));+}++.tile:focus-visible {+ outline: 2px solid var(--mantine-primary-color-filled);+ outline-offset: -2px;+}++.icon {+ color: var(--mantine-color-dimmed);+ flex-shrink: 0;+ width: clamp(calc(12px * var(--board-canvas-ui-scale, 1)), 28cqh, calc(22px * var(--board-canvas-ui-scale, 1)));+ height: clamp(calc(12px * var(--board-canvas-ui-scale, 1)), 28cqh, calc(22px * var(--board-canvas-ui-scale, 1)));+}++/* Sized to whichever of the tile's sides runs out first; "12,345" is about 3.5em wide in bold. */+.value {+ flex-shrink: 0;+ font-size: clamp(+ calc(10px * var(--board-canvas-ui-scale, 1)),+ min(26cqi, 30cqh),+ calc(26px * var(--board-canvas-ui-scale, 1))+ );+ font-weight: 700;+ color: var(--mantine-primary-color-filled);+ line-height: 1.1;+ max-width: 100%;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.label {+ flex-shrink: 0;+ font-size: clamp(+ calc(8px * var(--board-canvas-ui-scale, 1)),+ min(12cqi, 16cqh),+ calc(12px * var(--board-canvas-ui-scale, 1))+ );+ color: var(--mantine-color-dimmed);+ line-height: 1.2;+ max-width: 100%;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++/* On a short tile the number matters most: the icon goes first, then the label. */+@container (max-height: 64px) {+ .icon {+ display: none;+ }+}++@container (max-height: 34px) {+ .label {+ display: none;+ }+}diff --git a/packages/widgets/src/thingport/library-stats/component.tsx b/packages/widgets/src/thingport/library-stats/component.tsxnew file mode 100644index 000000000..a789de645--- /dev/null+++ b/packages/widgets/src/thingport/library-stats/component.tsx@@ -0,0 +1,74 @@+"use client";++import type { CSSProperties } from "react";+import { IconCategory, IconCube, IconFolders, IconUsers } from "@tabler/icons-react";+import { getQueryKey } from "@trpc/react-query";++import { clientApi } from "@homarr/api/client";+import { useCurrentIntlLocale, useI18n } from "@homarr/translation/client";++import { getSafeApplicationUrl, SAFE_NEW_TAB_REL } from "../../common/application-url";+import { WidgetEmptyState } from "../../common/empty-state";+import { getUsableWidgetQueryData, isInitialWidgetQueryPending } from "../../common/query-state";+import { WidgetQueryLoadingState } from "../../common/query-state-indicator";+import type { WidgetComponentProps } from "../../definition";+import { useWidgetRuntimeQueries } from "../../runtime-hooks";+import { getRenderedSize } from "../common/rendered-size";+import { canShowThingportHeader, ThingportWidgetHeader } from "../common/widget-header";+import classes from "./component.module.css";++const stats = [+ { key: "models", option: "showModels", field: "modelCount", icon: IconCube },+ { key: "collections", option: "showCollections", field: "collectionCount", icon: IconFolders },+ { key: "categories", option: "showCategories", field: "categoryCount", icon: IconCategory },+ { key: "authors", option: "showAuthors", field: "authorCount", icon: IconUsers },+] as const;++// A widget shorter than this lays every total out in one row rather than stacking two rows of half-height tiles.+const SINGLE_ROW_MAX_HEIGHT = 120;++export default function ThingportLibraryStatsWidget({+ integrationIds,+ options,+ widgetRuntimeRef,+ ...sizeProps+}: WidgetComponentProps<"thingport-libraryStats">) {+ const { width, height } = getRenderedSize(sizeProps);+ const t = useI18n("widget.thingport-libraryStats");+ const locale = useCurrentIntlLocale();+ const input = { integrationId: integrationIds[0] ?? "" };+ const query = clientApi.widget.thingport.getLibraryStats.useQuery(input);+ const data = getUsableWidgetQueryData(query);+ useWidgetRuntimeQueries(widgetRuntimeRef, [getQueryKey(clientApi.widget.thingport.getLibraryStats, input, "query")]);++ if (isInitialWidgetQueryPending(query)) return <WidgetQueryLoadingState />;+ if (!data) return <WidgetEmptyState />;++ const visibleStats = stats.filter((stat) => options[stat.option]);+ if (visibleStats.length === 0) return <WidgetEmptyState />;++ const showHeader = options.showTitle && canShowThingportHeader(width, height);+ const singleRow = width >= 360 || (height < SINGLE_ROW_MAX_HEIGHT && width >= 200);+ const columns = visibleStats.length === 1 ? 1 : singleRow ? Math.min(visibleStats.length, 4) : 2;++ return (+ <div className={classes.wrapper}>+ {showHeader && <ThingportWidgetHeader title={t("title")} />}+ <div className={classes.root} style={{ "--stat-cols": columns } as CSSProperties}>+ {visibleStats.map(({ key, field, icon: Icon }) => (+ <a+ key={key}+ href={getSafeApplicationUrl(data.links[key])}+ target={options.openInNewTab ? "_blank" : undefined}+ rel={options.openInNewTab ? SAFE_NEW_TAB_REL : undefined}+ className={classes.tile}+ >+ <Icon className={classes.icon} stroke={1.5} />+ <span className={classes.value}>{data[field].toLocaleString(locale)}</span>+ <span className={classes.label}>{t(key)}</span>+ </a>+ ))}+ </div>+ </div>+ );+}diff --git a/packages/widgets/src/thingport/library-stats/index.ts b/packages/widgets/src/thingport/library-stats/index.tsnew file mode 100644index 000000000..726e38473--- /dev/null+++ b/packages/widgets/src/thingport/library-stats/index.ts@@ -0,0 +1,25 @@+import { IconCube } from "@tabler/icons-react";++import { getWidgetIntegrationConfig } from "@homarr/definitions";++import { createWidgetDefinition, matchesWidgetRuntimeQuery } from "../../definition";+import { optionsBuilder } from "../../options";++export const { definition, componentLoader } = createWidgetDefinition("thingport-libraryStats", {+ icon: IconCube,+ supportsAdvancedFocus: false,+ queryKey: [["widget", "thingport", "getLibraryStats"]],+ queryMatcher: matchesWidgetRuntimeQuery,+ refetchInterval: null,+ ...getWidgetIntegrationConfig("thingport-libraryStats"),+ createOptions() {+ return optionsBuilder.from((factory) => ({+ showTitle: factory.switch({ defaultValue: false }),+ showModels: factory.switch({ defaultValue: true }),+ showCollections: factory.switch({ defaultValue: true }),+ showCategories: factory.switch({ defaultValue: true }),+ showAuthors: factory.switch({ defaultValue: true }),+ openInNewTab: factory.switch({ defaultValue: true }),+ }));+ },+}).withDynamicImport(() => import("./component"));diff --git a/packages/widgets/src/thingport/models/component.module.css b/packages/widgets/src/thingport/models/component.module.cssnew file mode 100644index 000000000..4eb5603ed--- /dev/null+++ b/packages/widgets/src/thingport/models/component.module.css@@ -0,0 +1,19 @@+.row {+ display: block;+ padding: 4px 6px;+ border-radius: var(--mantine-radius-sm);+}++.row:hover {+ background-color: light-dark(var(--mantine-color-gray-1), var(--mantine-color-dark-5));+}++.thumbnail {+ flex-shrink: 0;+ width: 40px;+ height: 40px;+ border-radius: var(--mantine-radius-sm);+ object-fit: cover;+ color: var(--mantine-color-dimmed);+ background-color: light-dark(var(--mantine-color-gray-1), var(--mantine-color-dark-6));+}diff --git a/packages/widgets/src/thingport/models/component.tsx b/packages/widgets/src/thingport/models/component.tsxnew file mode 100644index 000000000..8c50651f5--- /dev/null+++ b/packages/widgets/src/thingport/models/component.tsx@@ -0,0 +1,167 @@+"use client";++import { useState } from "react";+import { Box, Center, Group, Image, ScrollArea, Stack, Tabs, Text, UnstyledButton } from "@mantine/core";+import { IconClockPlus, IconCube, IconEye, IconPrinter } from "@tabler/icons-react";+import { getQueryKey } from "@trpc/react-query";+import dayjs from "dayjs";+import relativeTime from "dayjs/plugin/relativeTime";++import { clientApi } from "@homarr/api/client";+import type { RouterOutputs } from "@homarr/api";+import { thingportModelLists } from "@homarr/integrations/types";+import type { ThingportModelList } from "@homarr/integrations/types";+import { useI18n } from "@homarr/translation/client";++import { getSafeApplicationUrl, SAFE_NEW_TAB_REL } from "../../common/application-url";+import { getUsableWidgetQueryData, isInitialWidgetQueryPending } from "../../common/query-state";+import { WidgetQueryLoadingState } from "../../common/query-state-indicator";+import type { WidgetComponentProps } from "../../definition";+import { useWidgetRuntimeQueries } from "../../runtime-hooks";+import { getRenderedSize } from "../common/rendered-size";+import { canShowThingportHeader, ThingportWidgetHeader } from "../common/widget-header";+import classes from "./component.module.css";++dayjs.extend(relativeTime);++type ThingportModel = RouterOutputs["widget"]["thingport"]["getModels"][number];++const tabIcons = {+ recentlyAdded: IconClockPlus,+ topViewed: IconEye,+ topPrinted: IconPrinter,+} as const satisfies Record<ThingportModelList, unknown>;++const isModelList = (value: string | null): value is ThingportModelList =>+ thingportModelLists.some((list) => list === value);++export default function ThingportModelsWidget({+ integrationIds,+ options,+ widgetRuntimeRef,+ ...sizeProps+}: WidgetComponentProps<"thingport-models">) {+ const { width, height } = getRenderedSize(sizeProps);+ const t = useI18n("widget.thingport-models");+ const [activeTab, setActiveTab] = useState<ThingportModelList>(options.defaultTab);+ const input = { integrationId: integrationIds[0] ?? "", list: activeTab, limit: options.itemCount };+ const query = clientApi.widget.thingport.getModels.useQuery(input);+ const models = getUsableWidgetQueryData(query);+ useWidgetRuntimeQueries(widgetRuntimeRef, [getQueryKey(clientApi.widget.thingport.getModels, input, "query")]);+ // Below this the three labelled tabs no longer fit on one line, so they show only their icons.+ const isNarrow = width < 380;+ const showHeader = options.showTitle && canShowThingportHeader(width, height);++ const tabs = (+ <Tabs+ value={activeTab}+ keepMounted={false}+ onChange={(value) => {+ if (isModelList(value)) setActiveTab(value);+ }}+ flex={1}+ mih={0}+ style={{ display: "flex", flexDirection: "column" }}+ >+ <Tabs.List grow style={{ flexWrap: "nowrap" }}>+ {thingportModelLists.map((list) => {+ const Icon = tabIcons[list];+ return (+ <Tabs.Tab+ key={list}+ value={list}+ px={isNarrow ? 6 : undefined}+ title={t(`tab.${list}`)}+ leftSection={<Icon size="var(--mantine-font-size-sm)" />}+ >+ {isNarrow ? null : t(`tab.${list}`)}+ </Tabs.Tab>+ );+ })}+ </Tabs.List>++ <Tabs.Panel value={activeTab} flex={1} mih={0}>+ {isInitialWidgetQueryPending(query) ? (+ <WidgetQueryLoadingState />+ ) : !models || models.length === 0 ? (+ <Center h="100%" p="sm">+ <Text c="dimmed" size="sm" ta="center">+ {t(`empty.${activeTab}`)}+ </Text>+ </Center>+ ) : (+ <ScrollArea h="100%">+ <Stack gap={2} p={4}>+ {models.map((model) => (+ <ModelRow+ key={model.id}+ model={model}+ list={activeTab}+ showThumbnail={options.showThumbnails}+ openInNewTab={options.openInNewTab}+ />+ ))}+ </Stack>+ </ScrollArea>+ )}+ </Tabs.Panel>+ </Tabs>+ );++ return (+ <Stack h="100%" gap={4} p={showHeader ? 4 : 0}>+ {showHeader && (+ <Box px={4} pt={4}>+ <ThingportWidgetHeader title={t("title")} />+ </Box>+ )}+ {tabs}+ </Stack>+ );+}++interface ModelRowProps {+ model: ThingportModel;+ list: ThingportModelList;+ showThumbnail: boolean;+ openInNewTab: boolean;+}++function ModelRow({ model, list, showThumbnail, openInNewTab }: ModelRowProps) {+ const t = useI18n("widget.thingport-models");+ const href = getSafeApplicationUrl(model.href);+ const detail = {+ recentlyAdded: dayjs(model.createdAt).fromNow(),+ topViewed: t("views", { count: model.viewCount }),+ topPrinted: t("prints", { count: model.printCount }),+ }[list];++ return (+ <UnstyledButton+ component="a"+ href={href}+ target={openInNewTab ? "_blank" : undefined}+ rel={openInNewTab ? SAFE_NEW_TAB_REL : undefined}+ className={classes.row}+ >+ <Group gap="sm" wrap="nowrap">+ {showThumbnail &&+ (model.thumbnailUrl ? (+ <Image src={model.thumbnailUrl} alt="" className={classes.thumbnail} loading="lazy" />+ ) : (+ <Center className={classes.thumbnail}>+ <IconCube size={18} stroke={1.5} />+ </Center>+ ))}+ <Stack gap={0} miw={0} flex={1}>+ <Text size="sm" fw={500} truncate="end" title={model.name}>+ {model.name}+ </Text>+ <Text size="xs" c="dimmed" truncate="end">+ {detail}+ </Text>+ </Stack>+ </Group>+ </UnstyledButton>+ );+}diff --git a/packages/widgets/src/thingport/models/index.ts b/packages/widgets/src/thingport/models/index.tsnew file mode 100644index 000000000..328a10954--- /dev/null+++ b/packages/widgets/src/thingport/models/index.ts@@ -0,0 +1,47 @@+import { IconClockPlus, IconCube3dSphere, IconEye, IconPrinter } from "@tabler/icons-react";+import { z } from "zod/v4";++import { getWidgetIntegrationConfig } from "@homarr/definitions";++import { createWidgetDefinition, matchesWidgetRuntimeQuery } from "../../definition";+import { optionsBuilder } from "../../options";++export const { definition, componentLoader } = createWidgetDefinition("thingport-models", {+ icon: IconCube3dSphere,+ supportsAdvancedFocus: false,+ queryKey: [["widget", "thingport", "getModels"]],+ queryMatcher: matchesWidgetRuntimeQuery,+ refetchInterval: null,+ ...getWidgetIntegrationConfig("thingport-models"),+ createOptions() {+ return optionsBuilder.from((factory) => ({+ showTitle: factory.switch({ defaultValue: false }),+ defaultTab: factory.select({+ options: [+ {+ label: (t) => t("widget.thingport-models.tab.recentlyAdded"),+ value: "recentlyAdded",+ icon: IconClockPlus,+ },+ {+ label: (t) => t("widget.thingport-models.tab.topViewed"),+ value: "topViewed",+ icon: IconEye,+ },+ {+ label: (t) => t("widget.thingport-models.tab.topPrinted"),+ value: "topPrinted",+ icon: IconPrinter,+ },+ ] as const,+ defaultValue: "recentlyAdded",+ }),+ itemCount: factory.number({+ defaultValue: 10,+ validate: z.number().int().min(1).max(50),+ }),+ showThumbnails: factory.switch({ defaultValue: true }),+ openInNewTab: factory.switch({ defaultValue: true }),+ }));+ },+}).withDynamicImport(() => import("./component"));