Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7f7ee3263c | ||
|
|
e49e53a32f | ||
|
|
25bd88f30a | ||
|
|
7e93380140 | ||
|
|
78da525883 | ||
|
|
3bbe7f2a98 | ||
|
|
6728d0a63d | ||
|
|
8caf00da79 | ||
|
|
930d9fc489 | ||
|
|
0839007431 | ||
|
|
2cfa806176 |
No files matched your search
@@ -58,12 +58,12 @@ A random secret can be generated by using the following command: `openssl rand -
|
||||
|
||||
## Docker
|
||||
|
||||
| Environment Variable | Description | Possible values | Default |
|
||||
| --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------- | ------- |
|
||||
| `DOCKER_SOCKET_PATHS` | Comma-separated mounted Docker-compatible socket paths. Homarr discovers each path as a selectable Docker environment | For example `/var/run/docker.sock,/var/run/podman.sock` | - |
|
||||
| `DOCKER_HOSTNAMES` | Comma-separated plaintext TCP hostnames. Pair each hostname with the port in the same position in `DOCKER_PORTS` | For example `localhost,docker.example.com` | - |
|
||||
| `DOCKER_PORTS` | Comma-separated plaintext TCP ports paired with `DOCKER_HOSTNAMES` | For example `2375,2376` | - |
|
||||
| `DOCKER_ENDPOINTS` | Optional advanced JSON configuration for custom names, TLS, or restricted capabilities. It takes precedence over the simple variables above. See the [Docker and Podman connection guide](/docs/integrations/docker) | A JSON array of endpoint descriptors | - |
|
||||
| Environment Variable | Description | Possible values | Default |
|
||||
| --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------- | ------- |
|
||||
| `DOCKER_ENDPOINTS` | JSON array of named, capability-scoped Docker or Podman endpoints. Supports socket, explicitly insecure TCP, and TLS transports. See the [Docker and Podman integration guide](/docs/integrations/docker) | A JSON array of endpoint descriptors | - |
|
||||
| `DOCKER_HOSTNAMES` | Legacy comma-separated list of plaintext TCP hostnames. Ignored when `DOCKER_ENDPOINTS` is set | For example `localhost,docker.example.com` | - |
|
||||
| `DOCKER_PORTS` | Legacy comma-separated list of plaintext TCP ports. Ignored when `DOCKER_ENDPOINTS` is set | For example `2375,2376` | - |
|
||||
| `DOCKER_SOCKET_PATHS` | Legacy comma-separated list of mounted Docker-compatible socket paths. Ignored when `DOCKER_ENDPOINTS` is set | For example `/var/run/docker.sock,/var/run/podman.sock` | - |
|
||||
|
||||
## Database
|
||||
|
||||
|
||||
@@ -24,11 +24,12 @@ import { dockerContainersWidget } from "@site/docs/widgets/docker-containers";
|
||||
]}
|
||||
/>
|
||||
|
||||
## Connecting Docker to Homarr
|
||||
## Enabling the Docker integration
|
||||
|
||||
Docker connections come directly from Homarr's environment variables. They are automatically available in the Docker management table and Docker widget; you do not create a Docker integration under **Management → Integrations**.
|
||||
|
||||
If Homarr runs directly on a host with Docker installed, it uses `/var/run/docker.sock` by default. When Homarr runs in a container, mount the [Docker socket](https://docs.docker.com/engine/security/protect-access/) into it so Homarr can interact with Docker.
|
||||
This integration must first be enabled.
|
||||
If you directly run on the host system and you have docker installed, it will be enabled by default.
|
||||
Otherwise, you'll need to mount the [docker socket](https://docs.docker.com/engine/security/protect-access/) to the Homarr container,
|
||||
so Homarr can interact with the Docker service.
|
||||
|
||||
In Docker Compose, you can simply add this line:
|
||||
|
||||
@@ -121,23 +122,7 @@ services:
|
||||
DOCKER_SOCKET_PATHS: /var/run/docker.sock,/var/run/podman.sock
|
||||
```
|
||||
|
||||
For remote socket proxies, list the hostnames and matching ports in the same order:
|
||||
|
||||
```yaml
|
||||
environment:
|
||||
DOCKER_HOSTNAMES: docker-proxy-home,docker-proxy-lab
|
||||
DOCKER_PORTS: 2375,2375
|
||||
```
|
||||
|
||||
Homarr automatically discovers each comma-separated entry as a separate Docker environment. All environments are selected by default; the Docker widget lets you select one or more without any additional setup.
|
||||
|
||||
:::warning[Plaintext TCP]
|
||||
Plaintext Docker TCP can grant unauthenticated control of the Docker host. Prefer a local socket, a least-privilege socket proxy on a private Docker network, or TLS.
|
||||
:::
|
||||
|
||||
### Advanced endpoint configuration
|
||||
|
||||
Most users should use the comma-separated variables above. Use `DOCKER_ENDPOINTS` only when you need custom names, TLS, or restricted capabilities. It is a JSON array where every endpoint declares its identity, transport, and capabilities:
|
||||
For named endpoints, transport security, or least-privilege actions, prefer `DOCKER_ENDPOINTS`. It is a JSON array where every endpoint declares its identity, transport, and capabilities:
|
||||
|
||||
```yaml
|
||||
services:
|
||||
@@ -178,12 +163,16 @@ Supported transports are:
|
||||
- `tls`: `host`, `port`, and an absolute `caPath`; add both `certPath` and `keyPath` for mutual TLS
|
||||
- `tcp`: `host`, `port`, and the explicit acknowledgement `allowInsecure: true`
|
||||
|
||||
The structured configuration refuses TCP unless `allowInsecure` is explicitly set to `true`. When `DOCKER_ENDPOINTS` is set, it takes precedence over `DOCKER_SOCKET_PATHS`, `DOCKER_HOSTNAMES`, and `DOCKER_PORTS`.
|
||||
:::warning[Plaintext TCP]
|
||||
Plaintext Docker TCP can grant unauthenticated control of the Docker host. Prefer a local socket, a least-privilege socket proxy, or TLS. The structured configuration refuses TCP unless `allowInsecure` is explicitly set to `true`.
|
||||
:::
|
||||
|
||||
When `DOCKER_ENDPOINTS` is set, it takes precedence over the legacy `DOCKER_SOCKET_PATHS`, `DOCKER_HOSTNAMES`, and `DOCKER_PORTS` variables.
|
||||
|
||||
### Managing your Docker containers within Homarr
|
||||
|
||||
Homarr allows you to interact with Docker containers running on your system.
|
||||
The collapsed **Assisted Docker setup** helper optionally compares visible containers with your existing Homarr apps and integrations. Open it only when you want setup suggestions; it never blocks normal container management. Every service stays distinct by Docker endpoint and container ID, including multiple containers that use the same integration type.
|
||||
The **Service setup** section compares the visible containers with your existing Homarr apps and integrations. It keeps every service distinct by Docker endpoint and container ID, including multiple containers that use the same integration type.
|
||||
|
||||
Homarr can show a service as:
|
||||
|
||||
@@ -192,15 +181,15 @@ Homarr can show a service as:
|
||||
- **Already represented** or **Linked** when an app or integration already matches
|
||||
- **Address changed** when a service appears to match an integration but its reachable address has changed
|
||||
|
||||
Set the usual server address once, then choose whether services normally use different ports, subdomains, or paths. Homarr uses that pattern to prefill every detected service. Each suggestion has one editable URL field with the generated and Docker-reported addresses available as autocomplete options, so you can select a suggestion or type any address directly.
|
||||
Suggested addresses are ranked and explain where they came from. A published address or Docker endpoint host is normally usable from a browser; a container-name address is server-only and requires Homarr to share the container network. Wildcard addresses such as `0.0.0.0` are never offered as browser destinations. You can edit every suggestion before continuing.
|
||||
|
||||
:::info[Review before changing]
|
||||
Service discovery is read-only. Homarr never creates or changes an app or integration automatically. **Set up integration** opens the standard prefilled integration form, while **Create app** opens the existing Docker app form, so you can review and confirm the final setup.
|
||||
Service discovery is read-only. Homarr never creates or changes an app or integration automatically; use the action on an individual suggestion to review and confirm its setup.
|
||||
:::
|
||||
|
||||
Suggestions appear as a compact task list. Expand an item only when you want to edit its URL or inspect relevant setup statuses. Use the filters to focus on services that need attention or those already represented in Homarr. Refresh runs discovery again. Dismissed suggestions are stored in the current browser using their endpoint-qualified service identity and can be restored from the same helper. If multiple existing items could match, Homarr marks the result as ambiguous and does not choose one automatically.
|
||||
Use the inbox filters to focus on services that need attention or those already represented in Homarr. Refresh runs discovery again. Dismissed suggestions are stored in the current browser using their endpoint-qualified service identity and can be restored from the same panel. If multiple existing items could match, Homarr marks the result as ambiguous and does not choose one automatically.
|
||||
|
||||
Compact status icons summarize the setup information Homarr can act on. Unknown and non-applicable runtime layers are omitted to keep the helper focused; use the integration form's connection test or the relevant board action for live diagnostics.
|
||||
The health badges are an evidence-based projection across Docker, integration configuration, app representation, and persisted widget links. Authentication, API request success, and widget query execution are labeled **Not observed** because Homarr does not currently retain trustworthy last-run results for these layers. Use the suggested integration test or board action to diagnose them live; **Not observed** is never presented as healthy.
|
||||
|
||||
If one Docker endpoint is unavailable, Homarr reports that endpoint while continuing to show services from healthy endpoints. An unavailable endpoint is not treated as an empty Docker installation.
|
||||
|
||||
@@ -227,10 +216,6 @@ This opens a dedicated page with an xterm.js terminal that streams the container
|
||||
The Docker management table supports optional **CPU usage** and **Memory usage** columns.
|
||||
These columns are hidden by default and can be toggled on from the table column visibility settings.
|
||||
|
||||
#### Choosing Docker environments in the widget
|
||||
|
||||
The Docker widget can show one or more configured Docker environments. Leave **Docker environments** empty to include every endpoint, which is also the default for existing widgets. Selecting one or more entries limits container and statistics requests to those endpoints.
|
||||
|
||||
#### Add apps from containers
|
||||
|
||||
Homarr also lets you add apps from containers. You can simply select all containers you want to add an app for and then click the `Add to Homarr` button.
|
||||
|
||||
@@ -138,10 +138,6 @@ Pass those pairs unchanged to `docker.startAll`, `docker.stopAll`, `docker.resta
|
||||
names use underscores, such as `docker_restartAll`. Endpoint qualification prevents identical container IDs on different
|
||||
Docker or Podman endpoints from targeting the wrong service.
|
||||
|
||||
`docker.getContainers` also accepts an optional `endpointIds` array. Omit it or pass an empty array to query every configured
|
||||
Docker environment, or pass one or more IDs returned by `docker.getEndpoints` to query only those Dockerode clients. The
|
||||
Docker widget uses the same behavior for its environment selector.
|
||||
|
||||
## Partial integration failures
|
||||
|
||||
Multi-integration widget queries keep data from integrations that remain available. Calendar and media-server results include
|
||||
|
||||
@@ -205,7 +205,7 @@ changes, Homarr asks whether to discard them. If the editor cannot load, the boa
|
||||
/>
|
||||
|
||||
While edit mode is active, **Add board content** opens the same Universal Create surface as the global header action and
|
||||
Spotlight. It lists the available actions directly and can add a widget, app, integration, Container, board, Workshop item, or Custom Widget when the
|
||||
Spotlight. It can add a widget, app, integration, Container, board, Workshop item, or Custom Widget when the
|
||||
current user and context allow it. Widget setup offers the main canvas, enabled rails, and existing Containers as
|
||||
destinations before the widget is created, so the common flow does not require a second move step.
|
||||
|
||||
|
||||
@@ -81,9 +81,9 @@ When you connect a service from a board, Homarr keeps you in the same setup flow
|
||||
confirms whether an application shortcut was linked and offers the widgets that support the new integration. Selecting a
|
||||
widget returns to its settings with the new integration already selected.
|
||||
|
||||
Users with full access can also test and update a selected integration directly in the **Edit widget → Edit integration**
|
||||
tab on a board. Failed tests keep the editor open and show the same connection diagnostics as the management page.
|
||||
Successful changes apply to every app and widget that uses the integration.
|
||||
Users with full access can also test and update a selected integration from **Edit widget → Edit integration** on a
|
||||
board. Failed tests keep the editor open and show the same connection diagnostics as the management page. Successful
|
||||
changes apply to every app and widget that uses the integration.
|
||||
|
||||
When app creation is not permitted, the setup form offers linking an existing accessible app instead of attempting to
|
||||
create one.
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
---
|
||||
title: "Air Quality & UV"
|
||||
description: "Displays air quality, ultraviolet index, pollutants and pollen for a location."
|
||||
hide_title: true
|
||||
---
|
||||
|
||||
import { WidgetInteractionGuide } from "@site/src/components/widgets/interactions";
|
||||
|
||||
import { AddingWidget } from "@site/src/components/widgets/adding";
|
||||
import { WidgetConfig } from "@site/src/components/widgets/configuration";
|
||||
import { WidgetHeader } from "@site/src/components/widgets/header";
|
||||
import { airQualityWidget } from ".";
|
||||
|
||||
<WidgetHeader widget={airQualityWidget} categories={["Health", "Weather"]} />
|
||||
|
||||
The Air Quality & UV widget shows the current air quality index for a selected location. It adds the UV index,
|
||||
dominant pollutant, particulate matter and the highest available pollen reading as space allows. Open the advanced
|
||||
view for a 24-hour AQI and UV chart, all available pollutant and pollen readings, and seven-day daily maxima.
|
||||
|
||||
Select the European or US AQI scale, or use the automatic setting. Automatic uses the US scale for viewers whose
|
||||
locale region is the United States and the European scale everywhere else. The selected scale stays in widget options
|
||||
instead of being repeated beside every reading. Pollen values are individual measured concentrations; the widget does
|
||||
not combine them into a single pollen index.
|
||||
|
||||
The categories and colors summarize published index bands and are not medical advice. Pollutant concentrations use
|
||||
micrograms per cubic meter (`µg/m³`), and pollen uses grains per cubic meter.
|
||||
|
||||
<WidgetInteractionGuide />
|
||||
|
||||
### Adding the widget
|
||||
|
||||
<AddingWidget />
|
||||
|
||||
### Configuration
|
||||
|
||||
<WidgetConfig configuration={airQualityWidget.configuration} />
|
||||
|
||||
### Data source
|
||||
|
||||
Homarr uses the free Open-Meteo Air Quality API. The widget refreshes active data every 15 minutes and requests a
|
||||
seven-day forecast for European AQI, US AQI, UV, particulate matter, ozone, nitrogen dioxide, sulphur dioxide, carbon
|
||||
monoxide, and available alder, birch, grass, mugwort, olive and ragweed pollen. Identical location requests reuse the
|
||||
server response for 15 minutes. If a refresh fails, Homarr can keep a recent successful response visible for up to 24
|
||||
hours instead of replacing it with an empty state.
|
||||
|
||||
Set `NO_EXTERNAL_CONNECTION=true` to disable this and other internet-backed requests. If you need to allowlist the
|
||||
service, use `https://air-quality-api.open-meteo.com`.
|
||||
@@ -1,43 +0,0 @@
|
||||
import type { WidgetDefinition } from "@site/src/types";
|
||||
import { IconWind } from "@tabler/icons-react";
|
||||
|
||||
export const airQualityWidget: WidgetDefinition = {
|
||||
icon: IconWind,
|
||||
name: "Air Quality & UV",
|
||||
description: "Displays air quality, ultraviolet index, pollutants and pollen for a location.",
|
||||
path: "../../widgets/air-quality",
|
||||
configuration: {
|
||||
items: [
|
||||
{
|
||||
name: "Air quality location",
|
||||
description: "Location used for air quality, UV and pollen data",
|
||||
values: "Select a location through search or longitude/latitude",
|
||||
defaultValue: "Paris / 48.85341, 2.3488",
|
||||
},
|
||||
{
|
||||
name: "AQI standard",
|
||||
description: "Choose the European or US air quality scale, or select one from the viewer's locale",
|
||||
values: { type: "select", options: ["Automatic for locale", "European AQI", "US AQI"] },
|
||||
defaultValue: "Automatic for locale",
|
||||
},
|
||||
{
|
||||
name: "Show UV index",
|
||||
description: "Display the current UV index and its forecast",
|
||||
values: { type: "boolean" },
|
||||
defaultValue: "yes",
|
||||
},
|
||||
{
|
||||
name: "Show pollutant concentrations",
|
||||
description: "Display particulate matter and gaseous pollutant concentrations",
|
||||
values: { type: "boolean" },
|
||||
defaultValue: "yes",
|
||||
},
|
||||
{
|
||||
name: "Show pollen concentrations",
|
||||
description: "Display available pollen concentrations",
|
||||
values: { type: "boolean" },
|
||||
defaultValue: "yes",
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
@@ -15,26 +15,6 @@ import { clockWidget } from ".";
|
||||
|
||||
The clock widget displays the current date and time in a customizable format.
|
||||
|
||||
Advanced view turns it into a World Clock. The configured primary timezone stays prominent while New York, Paris, and
|
||||
Tokyo are included as secondary defaults. You can add, rename, remove, and reorder up to six cities in widget options;
|
||||
London, Sydney, and UTC are also available as quick presets.
|
||||
|
||||
The digital advanced view keeps the primary timezone prominent and presents every secondary city as a concise,
|
||||
comparable card. The primary clock includes a segmented 24-hour rail with a current-time marker, elapsed and remaining
|
||||
time, six-hour ticks, and a legend for night, dawn, day, and dusk. These phases are based on local clock time and are not
|
||||
astronomical sunrise or sunset calculations. Secondary cards stop after their localized date and timezone offsets.
|
||||
|
||||
The compact widget remains a single numeric clock. The time-format selector shows common Day.js presets with live
|
||||
examples and applies to the primary clock. Choosing a format with seconds enables second-level updates; 12-hour and
|
||||
24-hour display are selected through those same formats. The date-format selector likewise
|
||||
shows live Day.js examples and their tokens. Secondary cities always include a short localized date and a
|
||||
Yesterday, Today, or Tomorrow label relative to the primary timezone. UTC and relative offsets follow current timezone
|
||||
rules, including daylight-saving changes.
|
||||
|
||||
Weather remains optional and uses its own configured location rather than a World Clock city. Its icon is static by
|
||||
default and can be animated explicitly; reduced-motion preferences always disable animation. An unsupported saved
|
||||
timezone is identified without preventing valid clocks from rendering.
|
||||
|
||||
### Screenshots
|
||||
|
||||
import localClock from "./img/local.png";
|
||||
@@ -47,7 +27,7 @@ import tokyoClock from "./img/tokyo-12-hour.png";
|
||||
<img src={tokyoClock} alt="clock format-12-hours timezone-tokyo" width={256} height={128} />
|
||||
</div>
|
||||
|
||||
<WidgetInteractionGuide />
|
||||
<WidgetInteractionGuide advancedView={false} />
|
||||
|
||||
### Adding the widget
|
||||
|
||||
|
||||
@@ -20,6 +20,18 @@ export const clockWidget: WidgetDefinition = {
|
||||
values: { type: "string" },
|
||||
defaultValue: "-",
|
||||
},
|
||||
{
|
||||
name: "24-hour format",
|
||||
description: "Use 24-hour format instead of 12-hour format.",
|
||||
values: { type: "boolean" },
|
||||
defaultValue: "yes",
|
||||
},
|
||||
{
|
||||
name: "Display seconds",
|
||||
description: "Whether to show seconds in the clock.",
|
||||
values: { type: "boolean" },
|
||||
defaultValue: "no",
|
||||
},
|
||||
{
|
||||
name: "Use fixed timezone",
|
||||
description: "Select custom timezone to display instead of the client timezone.",
|
||||
@@ -40,46 +52,21 @@ export const clockWidget: WidgetDefinition = {
|
||||
},
|
||||
{
|
||||
name: "Date format",
|
||||
description: "Choose a common Day.js date format with a live example and its tokens.",
|
||||
values: "YYYY-MM-DD, DD/MM/YYYY, MM/DD/YYYY, or common long and short date formats",
|
||||
description: "Format of the date displayed below the clock.",
|
||||
values: "A collection of date formats, e.g. 'DD/MM/YYYY', 'MM/DD/YYYY', etc.",
|
||||
defaultValue: "dddd, MMMM D",
|
||||
},
|
||||
{
|
||||
name: "Time format",
|
||||
description:
|
||||
"Choose a common Day.js time format with a live example. The format controls 12/24-hour display and seconds.",
|
||||
values: "HH:mm, HH:mm:ss, h:mm A, or h:mm:ss A",
|
||||
defaultValue: "HH:mm",
|
||||
name: "Custom time format",
|
||||
description: "Format of the time displayed in the clock.",
|
||||
values: 'ISO 8601 format, e.g. "HH:mm:ss", "hh:mm A", etc.',
|
||||
defaultValue: "-",
|
||||
},
|
||||
{
|
||||
name: "Show weather",
|
||||
description: "Show a compact weather summary from an independently configured location.",
|
||||
values: { type: "boolean" },
|
||||
defaultValue: "no",
|
||||
},
|
||||
{
|
||||
name: "Weather location",
|
||||
description: 'Location used by the weather summary. Only shown if "Show weather" is enabled.',
|
||||
values: "A searched city or custom latitude and longitude",
|
||||
defaultValue: "Brisbane",
|
||||
},
|
||||
{
|
||||
name: "Use Fahrenheit",
|
||||
description: 'Use Fahrenheit in the weather summary. Only shown if "Show weather" is enabled.',
|
||||
values: { type: "boolean" },
|
||||
defaultValue: "no",
|
||||
},
|
||||
{
|
||||
name: "Animate weather icon",
|
||||
description: "Animate the weather icon unless the device requests reduced motion.",
|
||||
values: { type: "boolean" },
|
||||
defaultValue: "no",
|
||||
},
|
||||
{
|
||||
name: "World clock cities",
|
||||
description: "Add, label, and order up to six IANA timezones for advanced view.",
|
||||
values: "Up to six labeled IANA timezones",
|
||||
defaultValue: "New York, Paris, and Tokyo",
|
||||
name: "Custom date format",
|
||||
description: "Format of the date displayed below the clock.",
|
||||
values: 'ISO 8601 format, e.g. "YYYY-MM-DD", "DD/MM/YYYY", etc.',
|
||||
defaultValue: "-",
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
---
|
||||
title: "Countdowns"
|
||||
description: "Tracks upcoming events and recurring anniversaries."
|
||||
hide_title: true
|
||||
---
|
||||
|
||||
import { WidgetInteractionGuide } from "@site/src/components/widgets/interactions";
|
||||
|
||||
import { AddingWidget } from "@site/src/components/widgets/adding";
|
||||
import { WidgetConfig } from "@site/src/components/widgets/configuration";
|
||||
import { WidgetHeader } from "@site/src/components/widgets/header";
|
||||
import { countdownWidget } from ".";
|
||||
|
||||
<WidgetHeader widget={countdownWidget} categories={["Time"]} />
|
||||
|
||||
The Countdowns widget tracks up to 20 events without an integration. Add each event in widget options, choose its local
|
||||
date and time, and select an IANA timezone. Events can be reordered by dragging them.
|
||||
|
||||
The compact widget shows the first configured event, so dragging an event to the top selects the countdown displayed on
|
||||
the board. Advanced view uses that same event for its larger summary and preserves the configured order within its
|
||||
upcoming and completed groups. List cards keep their occurrence date at the bottom, below the optional progress bar.
|
||||
|
||||
One-time events remain completed after their target. A yearly event keeps the same local date and wall-clock time in its
|
||||
configured timezone, including when daylight-saving offsets change. A February 29 event waits until the next leap year.
|
||||
If a configured local time falls in a daylight-saving gap, the first valid time afterward is used; if it occurs twice,
|
||||
the earlier occurrence is used.
|
||||
|
||||
Progress is optional. One-time events need a start date before a percentage can be calculated. Yearly events show
|
||||
progress from the previous occurrence to the next. When enabled, seconds remain visible for every upcoming event.
|
||||
|
||||
Browser notifications are an optional local preference in advanced view and are disabled by default. Permission is
|
||||
requested only after you enable notifications, and alerts can fire once per occurrence while Homarr is open. Browser
|
||||
storage uses the board and widget identifiers to keep preferences separate and prevent duplicate alerts; clearing site
|
||||
data resets them. Widget previews do not persist alert preferences.
|
||||
|
||||
<WidgetInteractionGuide />
|
||||
|
||||
### Adding the widget
|
||||
|
||||
<AddingWidget />
|
||||
|
||||
### Configuration
|
||||
|
||||
<WidgetConfig configuration={countdownWidget.configuration} />
|
||||
@@ -1,31 +0,0 @@
|
||||
import { WidgetDefinition } from "@site/src/types";
|
||||
import { IconHourglass } from "@tabler/icons-react";
|
||||
|
||||
export const countdownWidget: WidgetDefinition = {
|
||||
icon: IconHourglass,
|
||||
name: "Countdowns",
|
||||
description: "Tracks upcoming events and recurring anniversaries.",
|
||||
path: "../../widgets/countdown",
|
||||
configuration: {
|
||||
items: [
|
||||
{
|
||||
name: "Events",
|
||||
description: "Add, edit, and order one-time or yearly events with a date, time, and IANA timezone.",
|
||||
values: "Up to 20 events",
|
||||
defaultValue: "No events",
|
||||
},
|
||||
{
|
||||
name: "Show progress",
|
||||
description: "Show progress from an optional start date, or between yearly occurrences.",
|
||||
values: { type: "boolean" },
|
||||
defaultValue: "yes",
|
||||
},
|
||||
{
|
||||
name: "Show seconds",
|
||||
description: "Keep seconds visible for every upcoming event, including events more than a day away.",
|
||||
values: { type: "boolean" },
|
||||
defaultValue: "no",
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
@@ -7,15 +7,20 @@ hide_title: true
|
||||
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 { WidgetInteractionGuide } from "@site/src/components/widgets/interactions";
|
||||
import { IconAd } from "@tabler/icons-react";
|
||||
import Tabs from "@theme/Tabs";
|
||||
import TabItem from "@theme/TabItem";
|
||||
import { dockerContainersWidget } from ".";
|
||||
import { dockerIntegration } from "@site/docs/integrations/docker";
|
||||
|
||||
<WidgetHeader widget={dockerContainersWidget} categories={["Containers"]} />
|
||||
|
||||
This widget displays the resource usage of your Docker containers and allows you to manage them.
|
||||
|
||||
:::info
|
||||
This widget reads the Docker environments configured through environment variables. You do not need to create a Docker integration under **Management → Integrations**. The widget can only be used with administrator privileges.
|
||||
This widget can only be used with administrator privileges.
|
||||
:::
|
||||
|
||||
### Screenshots
|
||||
@@ -24,6 +29,16 @@ import dockerTable from "./img/table.png";
|
||||
|
||||
<img src={dockerTable} alt="docker-stats table docker-containers" width={128 * 3} height={128 * 2} />
|
||||
|
||||
### Supported Integrations
|
||||
|
||||
<WidgetIntegrations
|
||||
items={[
|
||||
{
|
||||
integration: dockerIntegration,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
|
||||
### Interactions
|
||||
|
||||
Hover a column header to reveal its grab handle, then drag it to reorder the table or drag the header's edge to resize it. The layout is saved automatically for each widget instance and restored after a reload. These controls are disabled while the board is in edit mode.
|
||||
|
||||
@@ -8,12 +8,6 @@ export const dockerContainersWidget: WidgetDefinition = {
|
||||
path: "../../widgets/docker-containers",
|
||||
configuration: {
|
||||
items: [
|
||||
{
|
||||
name: "Docker environments",
|
||||
description: "Select one or more automatically discovered Docker environments, or leave empty to show all",
|
||||
values: "Any Docker socket or host configured for Homarr",
|
||||
defaultValue: "All Docker environments",
|
||||
},
|
||||
{
|
||||
name: "Columns to show",
|
||||
description: "Select which columns are visible in the table",
|
||||
|
||||
@@ -22,7 +22,7 @@ import { plexIntegration } from "@site/docs/integrations/plex";
|
||||
<WidgetHeader widget={mediaServerWidget} categories={["Media server"]} />
|
||||
|
||||
The media server widget shows active sessions across your media servers.
|
||||
It shows playback progress, pause state, time remaining, the streaming resolution (e.g. `1080p`), and whether each session is direct play, direct stream, or transcoding audio or video. Location and bitrate can be toggled independently.
|
||||
It shows playback progress, pause state, time remaining, and whether each session is direct play, direct stream, or transcoding audio or video. Location and bitrate can be toggled independently.
|
||||
|
||||
Select a session to inspect its media metadata in an anchored popover. Advanced mode adds search, sorting, location, bitrate, and a summary of playing and transcoding sessions while keeping separate integration instances identifiable. Compact visibility switches do not hide location or bitrate from the complete advanced session view.
|
||||
If one selected server is unavailable, a warning indicator identifies the degraded result while sessions from healthy servers remain usable.
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
---
|
||||
title: "Timer / Pomodoro"
|
||||
description: "Runs a simple timer or a configurable Pomodoro sequence."
|
||||
hide_title: true
|
||||
---
|
||||
|
||||
import { WidgetInteractionGuide } from "@site/src/components/widgets/interactions";
|
||||
|
||||
import { AddingWidget } from "@site/src/components/widgets/adding";
|
||||
import { WidgetConfig } from "@site/src/components/widgets/configuration";
|
||||
import { WidgetHeader } from "@site/src/components/widgets/header";
|
||||
import { timerWidget } from ".";
|
||||
|
||||
<WidgetHeader widget={timerWidget} categories={["Productivity", "Time"]} />
|
||||
|
||||
The Timer / Pomodoro widget runs entirely in your browser and does not require an integration. The compact widget
|
||||
always keeps its start or pause button and reset button visible. A running timer uses a saved deadline, so reopening
|
||||
the board or returning to a background tab restores the correct remaining time instead of restarting the countdown.
|
||||
|
||||
Timer mode uses one configured duration. Pomodoro mode starts with a focus session, follows most completed focus
|
||||
sessions with a short break, and uses a long break after the configured number of focus sessions. Automatic break and
|
||||
focus starts are separate options and are disabled by default. When automatic starts are enabled, elapsed phases are
|
||||
reconciled from their original deadlines after the board returns to the foreground.
|
||||
|
||||
Advanced view shows the current sequence, configured durations, and local alert preferences. Browser notifications are
|
||||
requested only when enabled. Notification and sound preferences, live progress, deadlines, and cycle position are
|
||||
stored locally using the board and widget identifiers. They are separate for each browser or device, are available to
|
||||
guest viewers, and are removed by clearing site data. Widget previews are ephemeral and do not write local timer state.
|
||||
|
||||
Timer sounds are enabled by default and use the same low-volume Tiks sound system as onboarding: start and pause use
|
||||
rising and falling soft-theme cues, reset uses a short click, and phase completion uses the glass theme's resonant
|
||||
notification ding. You can disable them in advanced view. The cues respect the device's reduced-motion preference and
|
||||
supplement the visible timer state rather than replacing it.
|
||||
|
||||
When automatic start is disabled, a completed phase labels the next step as ready and flashes the widget edges with the
|
||||
board's secondary color. The border glow and completion chime run together as a five-beat alarm burst at
|
||||
300-millisecond intervals, then stop. Reduced-motion and forced-colors modes replace the flash with a static border.
|
||||
The current phase stays pinned to the compact widget's top-left corner and wraps when needed. Timer text and controls
|
||||
use the dashboard theme's responsive size scale, with secondary details hidden when the widget preview is narrow or
|
||||
short.
|
||||
|
||||
Alerts can fire while Homarr is open. Browser and operating-system notification settings may still suppress them.
|
||||
The timer's mode, durations, session count, and automatic-start behavior are permanent board settings and are edited
|
||||
from the widget context menu.
|
||||
|
||||
<WidgetInteractionGuide />
|
||||
|
||||
### Adding the widget
|
||||
|
||||
<AddingWidget />
|
||||
|
||||
### Configuration
|
||||
|
||||
<WidgetConfig configuration={timerWidget.configuration} />
|
||||
@@ -1,61 +0,0 @@
|
||||
import type { WidgetDefinition } from "@site/src/types";
|
||||
import { IconClockPlay } from "@tabler/icons-react";
|
||||
|
||||
export const timerWidget: WidgetDefinition = {
|
||||
icon: IconClockPlay,
|
||||
name: "Timer / Pomodoro",
|
||||
description: "Runs a simple timer or a configurable Pomodoro sequence.",
|
||||
path: "../../widgets/timer",
|
||||
configuration: {
|
||||
items: [
|
||||
{
|
||||
name: "Mode",
|
||||
description: "Run one reusable timer or a repeating focus and break sequence",
|
||||
values: { type: "select", options: ["Timer", "Pomodoro"] },
|
||||
defaultValue: "Pomodoro",
|
||||
},
|
||||
{
|
||||
name: "Timer minutes",
|
||||
description: "Duration of the reusable timer",
|
||||
values: "1-1440 minutes",
|
||||
defaultValue: "10",
|
||||
},
|
||||
{
|
||||
name: "Focus minutes",
|
||||
description: "Duration of each Pomodoro focus session",
|
||||
values: "1-180 minutes",
|
||||
defaultValue: "25",
|
||||
},
|
||||
{
|
||||
name: "Short break minutes",
|
||||
description: "Duration of breaks between most focus sessions",
|
||||
values: "1-60 minutes",
|
||||
defaultValue: "5",
|
||||
},
|
||||
{
|
||||
name: "Long break minutes",
|
||||
description: "Duration of the break at the end of a Pomodoro cycle",
|
||||
values: "1-180 minutes",
|
||||
defaultValue: "15",
|
||||
},
|
||||
{
|
||||
name: "Focus sessions before a long break",
|
||||
description: "Number of completed focus sessions in one Pomodoro cycle",
|
||||
values: "1-12 sessions",
|
||||
defaultValue: "4",
|
||||
},
|
||||
{
|
||||
name: "Automatically start breaks",
|
||||
description: "Start the next short or long break when a focus session completes",
|
||||
values: { type: "boolean" },
|
||||
defaultValue: "no",
|
||||
},
|
||||
{
|
||||
name: "Automatically start focus sessions",
|
||||
description: "Start the next focus session when a break completes",
|
||||
values: { type: "boolean" },
|
||||
defaultValue: "no",
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
@@ -1,34 +0,0 @@
|
||||
---
|
||||
title: "Today"
|
||||
description: "Displays the current date and progress through the calendar."
|
||||
hide_title: true
|
||||
---
|
||||
|
||||
import { WidgetInteractionGuide } from "@site/src/components/widgets/interactions";
|
||||
|
||||
import { AddingWidget } from "@site/src/components/widgets/adding";
|
||||
import { WidgetConfig } from "@site/src/components/widgets/configuration";
|
||||
import { WidgetHeader } from "@site/src/components/widgets/header";
|
||||
import { todayWidget } from ".";
|
||||
|
||||
<WidgetHeader widget={todayWidget} categories={["Date", "Time"]} />
|
||||
|
||||
The Today widget presents the current local date without duplicating a live clock. It progressively adds the week
|
||||
number, day of year, quarter, remaining days, and calendar progress as more space becomes available.
|
||||
|
||||
The advanced view shows week, month, and year progress together with a twelve-month overview. Week numbers can follow
|
||||
your locale or the ISO 8601 convention. “Days after today” excludes the current day to keep the remaining-day count
|
||||
unambiguous.
|
||||
|
||||
The widget runs entirely in your browser and does not send date or location data to an external service. It follows
|
||||
the timezone and locale of the device viewing the board, so viewers in different regions can see their own local date.
|
||||
|
||||
<WidgetInteractionGuide />
|
||||
|
||||
### Adding the widget
|
||||
|
||||
<AddingWidget />
|
||||
|
||||
### Configuration
|
||||
|
||||
<WidgetConfig configuration={todayWidget.configuration} />
|
||||
@@ -1,43 +0,0 @@
|
||||
import type { WidgetDefinition } from "@site/src/types";
|
||||
import { IconCalendarWeek } from "@tabler/icons-react";
|
||||
|
||||
export const todayWidget: WidgetDefinition = {
|
||||
icon: IconCalendarWeek,
|
||||
name: "Today",
|
||||
description: "Displays the current date and progress through the calendar.",
|
||||
path: "../../widgets/today",
|
||||
configuration: {
|
||||
items: [
|
||||
{
|
||||
name: "Week numbering",
|
||||
description: "Use locale-specific week numbering or ISO 8601 week numbers",
|
||||
values: { type: "select", options: ["Use locale rules", "ISO 8601"] },
|
||||
defaultValue: "Use locale rules",
|
||||
},
|
||||
{
|
||||
name: "Show week number",
|
||||
description: "Display the current week number when the widget has room",
|
||||
values: { type: "boolean" },
|
||||
defaultValue: "yes",
|
||||
},
|
||||
{
|
||||
name: "Show day of year",
|
||||
description: "Display the current day number within the year",
|
||||
values: { type: "boolean" },
|
||||
defaultValue: "yes",
|
||||
},
|
||||
{
|
||||
name: "Show quarter",
|
||||
description: "Display the current calendar quarter",
|
||||
values: { type: "boolean" },
|
||||
defaultValue: "yes",
|
||||
},
|
||||
{
|
||||
name: "Show year progress",
|
||||
description: "Display progress through the current year",
|
||||
values: { type: "boolean" },
|
||||
defaultValue: "yes",
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
@@ -13,21 +13,23 @@ import { weatherWidget } from ".";
|
||||
|
||||
<WidgetHeader widget={weatherWidget} categories={["Weather"]} />
|
||||
|
||||
The Weather Widget displays current conditions and a responsive forecast for a selected location. New widgets start
|
||||
with the city and a three-day forecast visible. As the widget gets smaller, it keeps the current condition and
|
||||
temperature readable before removing secondary details or forecast days.
|
||||
The Weather Widget uses your location to display the current, highest and lowest temperature.
|
||||
In the compact view, select a condition icon or forecast day to open details with a mouse, keyboard or touch.
|
||||
The compact forecast shows up to the configured number of days. The advanced view combines current conditions with the
|
||||
available daily forecast, including humidity, wind, gusts, sunrise and sunset. Both views reuse the same cached Open
|
||||
Meteo response.
|
||||
|
||||
Select a forecast day to inspect precipitation, apparent temperature, humidity, wind, UV index, sunrise, sunset and
|
||||
daylight duration with a mouse, keyboard or touch. Open the advanced view for a current-condition summary, a 24-hour
|
||||
temperature and precipitation chart, and the complete seven-day forecast. The chart has an equivalent data table for
|
||||
assistive technologies.
|
||||
### Screenshots
|
||||
|
||||
The **Show humidity** option controls humidity across the compact current-conditions view, advanced summary, hourly
|
||||
details, and daily forecast details. Forecast cards use a roomier adaptive grid in advanced view, with four columns on
|
||||
the standard desktop surface and fewer columns as the surface narrows.
|
||||
import forecastWeather from "./img/forecast.png";
|
||||
import currentWeather from "./img/current.png";
|
||||
import advancedWeather from "./img/advanced-view.png";
|
||||
|
||||
Weather icons are static by default. Animation can be enabled in the widget configuration, but the operating system's
|
||||
reduced-motion preference always disables it.
|
||||
<div className="flex flex-col gap-1">
|
||||
<img src={forecastWeather} alt="Weather compact forecast" width={238} height={112} />
|
||||
<img src={currentWeather} alt="Weather compact current conditions" width={198} height={93} />
|
||||
<img src={advancedWeather} alt="Weather advanced view with seven-day forecast details" width={800} height={484} />
|
||||
</div>
|
||||
|
||||
<WidgetInteractionGuide />
|
||||
|
||||
@@ -41,10 +43,5 @@ reduced-motion preference always disables it.
|
||||
|
||||
### Data source
|
||||
|
||||
We use the Open Meteo API to fetch the weather and locations. Active weather data refreshes every ten minutes, while
|
||||
identical location requests can reuse a server response for five minutes. A manual refresh may therefore return the
|
||||
same still-current server response. If a refresh fails, Homarr keeps the last successful data visible and shows an
|
||||
error indicator.
|
||||
|
||||
Set `NO_EXTERNAL_CONNECTION=true` to disable this and other internet-backed requests.
|
||||
We use the Open Meteo API to fetch the weather and locations.
|
||||
If you need to whitelist the api, please use the following URL: `https://open-meteo.com`
|
||||
@@ -28,24 +28,8 @@ export const weatherWidget: WidgetDefinition = {
|
||||
values: {
|
||||
type: "boolean",
|
||||
},
|
||||
defaultValue: "no",
|
||||
},
|
||||
{
|
||||
name: "Show humidity",
|
||||
description: "Display humidity in current conditions, hourly details, and daily forecasts",
|
||||
values: {
|
||||
type: "boolean",
|
||||
},
|
||||
defaultValue: "yes",
|
||||
},
|
||||
{
|
||||
name: "Animate weather icons",
|
||||
description: "Animate condition icons unless the operating system requests reduced motion",
|
||||
values: {
|
||||
type: "boolean",
|
||||
},
|
||||
defaultValue: "no",
|
||||
},
|
||||
{
|
||||
name: "Use imperial speed units",
|
||||
description: "Display wind speed in mph instead of km/h",
|
||||
@@ -75,7 +59,7 @@ export const weatherWidget: WidgetDefinition = {
|
||||
values: {
|
||||
type: "boolean",
|
||||
},
|
||||
defaultValue: "yes",
|
||||
defaultValue: "no",
|
||||
},
|
||||
{
|
||||
name: "Has forecast",
|
||||
@@ -83,13 +67,13 @@ export const weatherWidget: WidgetDefinition = {
|
||||
values: {
|
||||
type: "boolean",
|
||||
},
|
||||
defaultValue: "yes",
|
||||
defaultValue: "no",
|
||||
},
|
||||
{
|
||||
name: "Amount of forecast days",
|
||||
description: "Number of days to show in the forecast",
|
||||
values: "1-7",
|
||||
defaultValue: "3",
|
||||
defaultValue: "5",
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { IconCloud, IconCloudRain, IconSun } from "@tabler/icons-react";
|
||||
import { IconCloud, IconWind, IconArrowUpRight, IconArrowDownRight } from "@tabler/icons-react";
|
||||
import { CommonWidgetProps, WidgetCard } from "./card";
|
||||
import clsx from "clsx";
|
||||
|
||||
@@ -6,27 +6,21 @@ export const WeatherWidget = ({ className }: CommonWidgetProps) => {
|
||||
return (
|
||||
<WidgetCard width={1} className={clsx("gap-2", className)}>
|
||||
<div className="flex gap-2 justify-center items-center">
|
||||
<IconSun size={22} />
|
||||
<div className="flex flex-col leading-none">
|
||||
<span className="text-xl font-bold">18.4°C</span>
|
||||
<span className="text-xs text-muted-foreground">Paris</span>
|
||||
</div>
|
||||
<IconCloud size={20} />
|
||||
<span className="text-xl font-bold">10.8°C</span>
|
||||
</div>
|
||||
<div className="flex justify-evenly items-center w-full">
|
||||
<div className="flex flex-col items-center text-xs">
|
||||
<span>Mon</span>
|
||||
<IconSun size={16} />
|
||||
<span>21°</span>
|
||||
<div className="flex gap-2 justify-center items-center">
|
||||
<IconWind size={14} />
|
||||
<span className="text-sm">5 km/h</span>
|
||||
</div>
|
||||
<div className="flex gap-1 justify-center items-center">
|
||||
<div className="flex justify-center items-center">
|
||||
<IconArrowUpRight size={14} />
|
||||
<span className="text-sm">13.5°C</span>
|
||||
</div>
|
||||
<div className="flex flex-col items-center text-xs">
|
||||
<span>Tue</span>
|
||||
<IconCloud size={16} />
|
||||
<span>19°</span>
|
||||
</div>
|
||||
<div className="flex flex-col items-center text-xs">
|
||||
<span>Wed</span>
|
||||
<IconCloudRain size={16} />
|
||||
<span>16°</span>
|
||||
<div className="flex justify-center items-center">
|
||||
<IconArrowDownRight size={14} />
|
||||
<span className="text-sm">6.4°C</span>
|
||||
</div>
|
||||
</div>
|
||||
</WidgetCard>
|
||||
|
||||
-4
@@ -2106,10 +2106,6 @@
|
||||
"enum": [
|
||||
"clock",
|
||||
"weather",
|
||||
"today",
|
||||
"airQuality",
|
||||
"countdown",
|
||||
"timer",
|
||||
"app",
|
||||
"iframe",
|
||||
"video",
|
||||
|
||||
+120
-156
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useImperativeHandle, useRef, useState } from "react";
|
||||
import { useRef, useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Alert, Anchor, Button, ButtonGroup, Fieldset, Group, Stack, Text, TextInput } from "@mantine/core";
|
||||
import { IconInfoCircle, IconPencil, IconPlus, IconUnlink } from "@tabler/icons-react";
|
||||
@@ -27,14 +27,8 @@ import type { AnyMappedTestConnectionError } from "../../_components/test-connec
|
||||
|
||||
interface EditIntegrationFormProps {
|
||||
integration: RouterOutputs["integration"]["byId"];
|
||||
hideButtons?: boolean;
|
||||
embedded?: boolean;
|
||||
onSuccess?: () => void;
|
||||
formRef?: React.Ref<EditIntegrationFormHandle>;
|
||||
}
|
||||
|
||||
export interface EditIntegrationFormHandle {
|
||||
submit: () => Promise<boolean>;
|
||||
isDirty: () => boolean;
|
||||
}
|
||||
|
||||
const formSchema = integrationUpdateSchema.omit({ id: true, appId: true }).and(
|
||||
@@ -50,12 +44,7 @@ const formSchema = integrationUpdateSchema.omit({ id: true, appId: true }).and(
|
||||
}),
|
||||
);
|
||||
|
||||
export const EditIntegrationForm = ({
|
||||
integration,
|
||||
hideButtons = false,
|
||||
onSuccess,
|
||||
formRef,
|
||||
}: EditIntegrationFormProps) => {
|
||||
export const EditIntegrationForm = ({ integration, embedded = false, onSuccess }: EditIntegrationFormProps) => {
|
||||
const t = useI18n();
|
||||
const { openConfirmModal } = useConfirmModal();
|
||||
const allSecretKinds = getAllSecretKindOptions(integration.kind);
|
||||
@@ -93,172 +82,147 @@ export const EditIntegrationForm = ({
|
||||
|
||||
const secretsMap = new Map(integration.secrets.map((secret) => [secret.kind, secret]));
|
||||
|
||||
const handleSubmitAsync = useCallback(
|
||||
async ({ app, ...values }: FormType) => {
|
||||
setError(null);
|
||||
let url: string;
|
||||
try {
|
||||
url = hasUrlSecret
|
||||
? new URL(values.secrets.find((secret) => secret.kind === "url")?.value ?? values.url).origin
|
||||
: values.url;
|
||||
} catch {
|
||||
showErrorNotification({
|
||||
title: t("integration.page.edit.notification.error.title"),
|
||||
message: t("integration.page.edit.notification.error.message"),
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
const data = await mutateAsync({
|
||||
id: integration.id,
|
||||
...values,
|
||||
url,
|
||||
secrets: values.secrets.map((secret) => ({
|
||||
kind: secret.kind,
|
||||
value: secret.value === "" ? null : secret.value,
|
||||
})),
|
||||
appId: app?.id ?? null,
|
||||
const handleSubmitAsync = async ({ app, ...values }: FormType) => {
|
||||
setError(null);
|
||||
let url: string;
|
||||
try {
|
||||
url = hasUrlSecret
|
||||
? new URL(values.secrets.find((secret) => secret.kind === "url")?.value ?? values.url).origin
|
||||
: values.url;
|
||||
} catch {
|
||||
showErrorNotification({
|
||||
title: t("integration.page.edit.notification.error.title"),
|
||||
message: t("integration.page.edit.notification.error.message"),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// We do it this way as we are unable to send a typesafe error through onError
|
||||
if (data?.error) {
|
||||
setError(data.error);
|
||||
showErrorNotification({
|
||||
title: t("integration.page.edit.notification.error.title"),
|
||||
message: t("integration.page.edit.notification.error.message"),
|
||||
});
|
||||
requestAnimationFrame(() => errorRef.current?.focus());
|
||||
return false;
|
||||
}
|
||||
const data = await mutateAsync({
|
||||
id: integration.id,
|
||||
...values,
|
||||
url,
|
||||
secrets: values.secrets.map((secret) => ({
|
||||
kind: secret.kind,
|
||||
value: secret.value === "" ? null : secret.value,
|
||||
})),
|
||||
appId: app?.id ?? null,
|
||||
});
|
||||
|
||||
showSuccessNotification({
|
||||
title: t("integration.page.edit.notification.success.title"),
|
||||
message: t("integration.page.edit.notification.success.message"),
|
||||
// We do it this way as we are unable to send a typesafe error through onError
|
||||
if (data?.error) {
|
||||
setError(data.error);
|
||||
showErrorNotification({
|
||||
title: t("integration.page.edit.notification.error.title"),
|
||||
message: t("integration.page.edit.notification.error.message"),
|
||||
});
|
||||
void Promise.allSettled([utils.integration.invalidate(), utils.widget.invalidate()]);
|
||||
onSuccess?.();
|
||||
if (!hideButtons) {
|
||||
void revalidatePathActionAsync("/manage/integrations").then(() => router.push("/manage/integrations"));
|
||||
}
|
||||
return true;
|
||||
},
|
||||
[hasUrlSecret, hideButtons, integration.id, mutateAsync, onSuccess, router, t, utils.integration, utils.widget],
|
||||
);
|
||||
requestAnimationFrame(() => errorRef.current?.focus());
|
||||
return;
|
||||
}
|
||||
|
||||
useImperativeHandle(
|
||||
formRef,
|
||||
() => ({
|
||||
submit: () =>
|
||||
new Promise<boolean>((resolve) => {
|
||||
form.onSubmit(
|
||||
async (values) => {
|
||||
try {
|
||||
resolve(await handleSubmitAsync(values));
|
||||
} catch {
|
||||
resolve(false);
|
||||
}
|
||||
},
|
||||
() => resolve(false),
|
||||
)();
|
||||
}),
|
||||
isDirty: () => form.isDirty(),
|
||||
}),
|
||||
[form, handleSubmitAsync],
|
||||
);
|
||||
showSuccessNotification({
|
||||
title: t("integration.page.edit.notification.success.title"),
|
||||
message: t("integration.page.edit.notification.success.message"),
|
||||
});
|
||||
void Promise.allSettled([utils.integration.invalidate(), utils.widget.invalidate()]);
|
||||
onSuccess?.();
|
||||
if (!embedded) {
|
||||
void revalidatePathActionAsync("/manage/integrations").then(() => router.push("/manage/integrations"));
|
||||
}
|
||||
};
|
||||
|
||||
const isInitialSecretKinds =
|
||||
initialSecretsKinds.every((kind) => form.values.secrets.some((secret) => secret.kind === kind)) &&
|
||||
form.values.secrets.length === initialSecretsKinds.length;
|
||||
|
||||
const formFields = (
|
||||
<Stack>
|
||||
<TextInput withAsterisk label={t("integration.field.name.label")} {...form.getInputProps("name")} />
|
||||
return (
|
||||
<form onSubmit={form.onSubmit(async (values) => await handleSubmitAsync(values))}>
|
||||
<Stack>
|
||||
<TextInput withAsterisk label={t("integration.field.name.label")} {...form.getInputProps("name")} />
|
||||
|
||||
{hasUrlSecret ? null : (
|
||||
<TextInput withAsterisk label={t("integration.field.url.label")} {...form.getInputProps("url")} />
|
||||
)}
|
||||
{hasUrlSecret ? null : (
|
||||
<TextInput withAsterisk label={t("integration.field.url.label")} {...form.getInputProps("url")} />
|
||||
)}
|
||||
|
||||
<Fieldset legend={t("integration.secrets.title")}>
|
||||
<Stack gap="sm">
|
||||
{allSecretKinds.length > 1 && (
|
||||
<SecretKindsSegmentedControl defaultKinds={initialSecretsKinds} secretKinds={allSecretKinds} form={form} />
|
||||
)}
|
||||
{!isInitialSecretKinds
|
||||
? null
|
||||
: form.values.secrets.map((secret, index) => (
|
||||
<SecretCard
|
||||
key={secret.kind}
|
||||
secret={secretsMap.get(secret.kind) ?? { kind: secret.kind, value: null, updatedAt: null }}
|
||||
onCancel={() =>
|
||||
new Promise((resolve) => {
|
||||
// When nothing changed, just close the secret card
|
||||
if ((secret.value ?? "") === (secretsMap.get(secret.kind)?.value ?? "")) {
|
||||
return resolve(true);
|
||||
}
|
||||
openConfirmModal({
|
||||
title: t("integration.secrets.reset.title"),
|
||||
children: t("integration.secrets.reset.message"),
|
||||
onCancel: () => resolve(false),
|
||||
onConfirm: () => {
|
||||
form.setFieldValue(`secrets.${index}.value`, secretsMap.get(secret.kind)?.value ?? "");
|
||||
resolve(true);
|
||||
},
|
||||
});
|
||||
})
|
||||
}
|
||||
>
|
||||
<IntegrationSecretInput
|
||||
label={t(`integration.secrets.kind.${secret.kind}.newLabel`)}
|
||||
<Fieldset legend={t("integration.secrets.title")}>
|
||||
<Stack gap="sm">
|
||||
{allSecretKinds.length > 1 && (
|
||||
<SecretKindsSegmentedControl
|
||||
defaultKinds={initialSecretsKinds}
|
||||
secretKinds={allSecretKinds}
|
||||
form={form}
|
||||
/>
|
||||
)}
|
||||
{!isInitialSecretKinds
|
||||
? null
|
||||
: form.values.secrets.map((secret, index) => (
|
||||
<SecretCard
|
||||
key={secret.kind}
|
||||
kind={secret.kind}
|
||||
secret={secretsMap.get(secret.kind) ?? { kind: secret.kind, value: null, updatedAt: null }}
|
||||
onCancel={() =>
|
||||
new Promise((resolve) => {
|
||||
// When nothing changed, just close the secret card
|
||||
if ((secret.value ?? "") === (secretsMap.get(secret.kind)?.value ?? "")) {
|
||||
return resolve(true);
|
||||
}
|
||||
openConfirmModal({
|
||||
title: t("integration.secrets.reset.title"),
|
||||
children: t("integration.secrets.reset.message"),
|
||||
onCancel: () => resolve(false),
|
||||
onConfirm: () => {
|
||||
form.setFieldValue(`secrets.${index}.value`, secretsMap.get(secret.kind)?.value ?? "");
|
||||
resolve(true);
|
||||
},
|
||||
});
|
||||
})
|
||||
}
|
||||
>
|
||||
<IntegrationSecretInput
|
||||
label={t(`integration.secrets.kind.${secret.kind}.newLabel`)}
|
||||
key={secret.kind}
|
||||
kind={secret.kind}
|
||||
{...form.getInputProps(`secrets.${index}.value`)}
|
||||
/>
|
||||
</SecretCard>
|
||||
))}
|
||||
{isInitialSecretKinds
|
||||
? null
|
||||
: form.values.secrets.map(({ kind }, index) => (
|
||||
<IntegrationSecretInput
|
||||
withAsterisk
|
||||
key={kind}
|
||||
kind={kind}
|
||||
{...form.getInputProps(`secrets.${index}.value`)}
|
||||
/>
|
||||
</SecretCard>
|
||||
))}
|
||||
{isInitialSecretKinds
|
||||
? null
|
||||
: form.values.secrets.map(({ kind }, index) => (
|
||||
<IntegrationSecretInput
|
||||
withAsterisk
|
||||
key={kind}
|
||||
kind={kind}
|
||||
{...form.getInputProps(`secrets.${index}.value`)}
|
||||
/>
|
||||
))}
|
||||
{form.values.secrets.length === 0 && (
|
||||
<Alert icon={<IconInfoCircle size={"1rem"} />} color={"blue"}>
|
||||
<Text c={"blue"}>{t("integration.secrets.noSecretsRequired.text")}</Text>
|
||||
</Alert>
|
||||
)}
|
||||
</Stack>
|
||||
</Fieldset>
|
||||
))}
|
||||
{form.values.secrets.length === 0 && (
|
||||
<Alert icon={<IconInfoCircle size={"1rem"} />} color={"blue"}>
|
||||
<Text c={"blue"}>{t("integration.secrets.noSecretsRequired.text")}</Text>
|
||||
</Alert>
|
||||
)}
|
||||
</Stack>
|
||||
</Fieldset>
|
||||
|
||||
<IntegrationLinkApp value={form.values.app} onChange={(app) => form.setFieldValue("app", app)} />
|
||||
<IntegrationLinkApp value={form.values.app} onChange={(app) => form.setFieldValue("app", app)} />
|
||||
|
||||
{error !== null && (
|
||||
<div ref={errorRef} role="alert" tabIndex={-1}>
|
||||
<IntegrationTestConnectionError error={error} url={form.values.url} />
|
||||
</div>
|
||||
)}
|
||||
{error !== null && (
|
||||
<div ref={errorRef} role="alert" tabIndex={-1}>
|
||||
<IntegrationTestConnectionError error={error} url={form.values.url} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!hideButtons && (
|
||||
<Group justify="end" align="center">
|
||||
<Button variant="default" component={Link} href="/manage/integrations">
|
||||
{t("common.action.backToOverview")}
|
||||
</Button>
|
||||
{!embedded && (
|
||||
<Button variant="default" component={Link} href="/manage/integrations">
|
||||
{t("common.action.backToOverview")}
|
||||
</Button>
|
||||
)}
|
||||
<Button type="submit" loading={isPending}>
|
||||
{t("integration.testConnection.action.edit")}
|
||||
</Button>
|
||||
</Group>
|
||||
)}
|
||||
</Stack>
|
||||
</Stack>
|
||||
</form>
|
||||
);
|
||||
|
||||
if (hideButtons) {
|
||||
return formFields;
|
||||
}
|
||||
|
||||
return <form onSubmit={form.onSubmit(async (values) => await handleSubmitAsync(values))}>{formFields}</form>;
|
||||
};
|
||||
|
||||
type FormType = z.infer<typeof formSchema>;
|
||||
|
||||
+5
-40
@@ -3,7 +3,7 @@ import { describe, expect, test } from "vitest";
|
||||
import {
|
||||
dismissDockerReconciliationCandidate,
|
||||
filterDockerReconciliationInbox,
|
||||
getTemplateUrl,
|
||||
getValidDockerServiceUrl,
|
||||
} from "./docker-reconciliation-inbox";
|
||||
|
||||
const candidates = [
|
||||
@@ -37,44 +37,9 @@ describe("Docker reconciliation inbox", () => {
|
||||
expect(dismissDockerReconciliationCandidate(dismissed, "home:new")).toBe(dismissed);
|
||||
});
|
||||
|
||||
test("builds service URLs from the server origin and published ports", () => {
|
||||
expect(
|
||||
getTemplateUrl(
|
||||
{
|
||||
container: { name: "Custom service", ports: [{ PrivatePort: 3000, Type: "tcp" }] },
|
||||
match: null,
|
||||
},
|
||||
"home.lan",
|
||||
"hostPort",
|
||||
),
|
||||
).toBe("http://home.lan");
|
||||
|
||||
expect(
|
||||
getTemplateUrl(
|
||||
{
|
||||
container: {
|
||||
name: "Sonarr",
|
||||
ports: [
|
||||
{ PrivatePort: 3000, PublicPort: 3000, Type: "tcp" },
|
||||
{ PrivatePort: 8989, PublicPort: 9999, Type: "tcp" },
|
||||
],
|
||||
},
|
||||
match: { kind: "sonarr" },
|
||||
},
|
||||
"home.lan",
|
||||
"hostPort",
|
||||
),
|
||||
).toBe("http://home.lan:9999");
|
||||
|
||||
expect(
|
||||
getTemplateUrl(
|
||||
{
|
||||
container: { name: "Sonarr", ports: [{ PrivatePort: 8989, PublicPort: 9999, Type: "tcp" }] },
|
||||
match: { kind: "sonarr" },
|
||||
},
|
||||
"",
|
||||
"hostPort",
|
||||
),
|
||||
).toBe("");
|
||||
test("accepts only HTTP service URLs", () => {
|
||||
expect(getValidDockerServiceUrl("https://service.example.com")).toBe("https://service.example.com/");
|
||||
expect(getValidDockerServiceUrl("ftp://service.example.com")).toBeNull();
|
||||
expect(getValidDockerServiceUrl("service.example.com")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,3 @@
|
||||
import type { DockerServiceMatch, DockerServicePort, UrlTemplateMode } from "@homarr/definitions";
|
||||
import { buildAppUrl, buildIntegrationUrl, getIntegrationDefaultPort } from "@homarr/definitions";
|
||||
|
||||
export type DockerReconciliationInboxFilter = "attention" | "represented" | "all";
|
||||
|
||||
interface DockerReconciliationInboxCandidate {
|
||||
@@ -27,28 +24,11 @@ export const filterDockerReconciliationInbox = <Candidate extends DockerReconcil
|
||||
export const dismissDockerReconciliationCandidate = (dismissedCandidateKeys: string[], candidateKey: string) =>
|
||||
dismissedCandidateKeys.includes(candidateKey) ? dismissedCandidateKeys : [...dismissedCandidateKeys, candidateKey];
|
||||
|
||||
interface DockerTemplateCandidate {
|
||||
container: {
|
||||
name: string;
|
||||
ports?: DockerServicePort[];
|
||||
};
|
||||
match: Pick<DockerServiceMatch, "kind"> | null;
|
||||
}
|
||||
|
||||
export const getTemplateUrl = (candidate: DockerTemplateCandidate, serverOrigin: string, urlMode: UrlTemplateMode) => {
|
||||
if (!serverOrigin.trim()) return "";
|
||||
|
||||
const tcpPorts = candidate.container.ports?.filter(({ Type }) => Type.toLowerCase() === "tcp") ?? [];
|
||||
let publishedPort = tcpPorts.find(({ PublicPort }) => PublicPort)?.PublicPort;
|
||||
|
||||
if (candidate.match) {
|
||||
const defaultPort = getIntegrationDefaultPort(candidate.match.kind);
|
||||
const preferredPort = tcpPorts.find(
|
||||
({ PrivatePort, PublicPort }) => PrivatePort === defaultPort && PublicPort !== undefined,
|
||||
);
|
||||
publishedPort = preferredPort?.PublicPort ?? publishedPort;
|
||||
return buildIntegrationUrl(candidate.match.kind, serverOrigin, urlMode, publishedPort);
|
||||
export const getValidDockerServiceUrl = (value: string) => {
|
||||
try {
|
||||
const url = new URL(value);
|
||||
return url.protocol === "http:" || url.protocol === "https:" ? url.toString() : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
return buildAppUrl(candidate.container.name, serverOrigin, urlMode, publishedPort);
|
||||
};
|
||||
@@ -1,72 +1,46 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useId, useRef, useState } from "react";
|
||||
import { useEffect, useState } from "react";
|
||||
import {
|
||||
Accordion,
|
||||
ActionIcon,
|
||||
Alert,
|
||||
Autocomplete,
|
||||
Avatar,
|
||||
Badge,
|
||||
Button,
|
||||
Collapse,
|
||||
Divider,
|
||||
Card,
|
||||
Group,
|
||||
Paper,
|
||||
SegmentedControl,
|
||||
Select,
|
||||
SimpleGrid,
|
||||
Stack,
|
||||
Text,
|
||||
ThemeIcon,
|
||||
Tooltip,
|
||||
TextInput,
|
||||
} from "@mantine/core";
|
||||
import { useLocalStorage } from "@mantine/hooks";
|
||||
import {
|
||||
IconAlertTriangle,
|
||||
IconApps,
|
||||
IconCheck,
|
||||
IconChevronDown,
|
||||
IconEye,
|
||||
IconEyeOff,
|
||||
IconBrandDocker,
|
||||
IconMinus,
|
||||
IconPlugConnected,
|
||||
IconRefresh,
|
||||
IconSettings,
|
||||
} from "@tabler/icons-react";
|
||||
import { IconAlertTriangle, IconArrowRight, IconEyeOff, IconPlugConnected, IconRefresh } from "@tabler/icons-react";
|
||||
|
||||
import type { RouterOutputs } from "@homarr/api";
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import type { UrlTemplateMode } from "@homarr/definitions";
|
||||
import { getIntegrationName } from "@homarr/definitions";
|
||||
import { useModalAction } from "@homarr/modals";
|
||||
import { AddDockerAppToHomarr } from "@homarr/modals-collection";
|
||||
import { showErrorNotification } from "@homarr/notifications";
|
||||
import { normalizeServiceUrl, ServiceUrlTemplate } from "@homarr/onboarding";
|
||||
import { useI18n, useScopedI18n } from "@homarr/translation/client";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
import { Link } from "@homarr/ui";
|
||||
import { IntegrationSelectModal } from "~/components/integration/integration-select-modal";
|
||||
import type { DockerReconciliationInboxFilter } from "./docker-reconciliation-inbox";
|
||||
import {
|
||||
dismissDockerReconciliationCandidate,
|
||||
filterDockerReconciliationInbox,
|
||||
getTemplateUrl,
|
||||
getValidDockerServiceUrl,
|
||||
} from "./docker-reconciliation-inbox";
|
||||
|
||||
type ReconciliationCandidate = RouterOutputs["docker"]["reconcileServices"]["candidates"][number];
|
||||
type ServiceHealth = RouterOutputs["docker"]["getServiceHealth"]["services"][number];
|
||||
|
||||
export const DockerReconciliation = ({ defaultServerOrigin }: { defaultServerOrigin: string }) => {
|
||||
export const DockerReconciliation = () => {
|
||||
const t = useScopedI18n("docker.reconciliation");
|
||||
const tGlobal = useI18n();
|
||||
const utils = clientApi.useUtils();
|
||||
const panelId = useId();
|
||||
const [isOpen, setIsOpen] = useLocalStorage({
|
||||
key: "homarr-docker-reconciliation-open",
|
||||
defaultValue: false,
|
||||
});
|
||||
const reconciliation = clientApi.docker.reconcileServices.useQuery();
|
||||
const health = clientApi.docker.getServiceHealth.useQuery(undefined, { enabled: isOpen });
|
||||
const health = clientApi.docker.getServiceHealth.useQuery();
|
||||
const refreshInventory = clientApi.docker.refreshInventory.useMutation({
|
||||
async onSuccess() {
|
||||
await Promise.all([
|
||||
@@ -87,14 +61,6 @@ export const DockerReconciliation = ({ defaultServerOrigin }: { defaultServerOri
|
||||
key: "homarr-docker-reconciliation-dismissed",
|
||||
defaultValue: [],
|
||||
});
|
||||
const [serverOrigin, setServerOrigin] = useLocalStorage({
|
||||
key: "homarr-docker-service-origin",
|
||||
defaultValue: defaultServerOrigin,
|
||||
});
|
||||
const [urlMode, setUrlMode] = useLocalStorage<UrlTemplateMode>({
|
||||
key: "homarr-docker-service-url-mode",
|
||||
defaultValue: "hostPort",
|
||||
});
|
||||
|
||||
if (reconciliation.isError) {
|
||||
return (
|
||||
@@ -102,7 +68,7 @@ export const DockerReconciliation = ({ defaultServerOrigin }: { defaultServerOri
|
||||
<Stack gap="sm">
|
||||
<Text size="sm">{t("loadError.message")}</Text>
|
||||
<Button variant="light" color="red" size="xs" w="fit-content" onClick={() => void reconciliation.refetch()}>
|
||||
{tGlobal("common.action.tryAgain")}
|
||||
{t("action.retry")}
|
||||
</Button>
|
||||
</Stack>
|
||||
</Alert>
|
||||
@@ -113,274 +79,231 @@ export const DockerReconciliation = ({ defaultServerOrigin }: { defaultServerOri
|
||||
|
||||
const unavailableEndpoints = reconciliation.data.endpoints.filter(({ status }) => status === "unavailable");
|
||||
const candidates = filterDockerReconciliationInbox(reconciliation.data.candidates, filter, dismissedCandidateKeys);
|
||||
const attentionCount = reconciliation.data.candidates.filter(
|
||||
({ candidateKey, state }) =>
|
||||
["newRecognized", "newApp", "moved"].includes(state) && !dismissedCandidateKeys.includes(candidateKey),
|
||||
).length;
|
||||
const attentionCount = health.data
|
||||
? health.data.services.filter(
|
||||
({ key, status }) =>
|
||||
["newRecognized", "newApp", "moved"].includes(status) && !dismissedCandidateKeys.includes(key),
|
||||
).length
|
||||
: 0;
|
||||
const isRefreshing = refreshInventory.isPending || reconciliation.isFetching || health.isFetching;
|
||||
const toggleLabel = isOpen ? tGlobal("common.action.hide") : t("action.review");
|
||||
|
||||
return (
|
||||
<Paper withBorder p="sm">
|
||||
<Stack gap={isOpen ? "sm" : 0}>
|
||||
<Card withBorder>
|
||||
<Stack>
|
||||
<Group justify="space-between" align="start">
|
||||
<Group gap="sm" wrap="nowrap" style={{ minWidth: 0 }}>
|
||||
<ThemeIcon variant="light" size="lg" radius="md">
|
||||
<IconBrandDocker size={18} />
|
||||
</ThemeIcon>
|
||||
<div>
|
||||
<Group gap="xs">
|
||||
<Text fw={600}>{t("title")}</Text>
|
||||
<Badge variant="light" color={attentionCount > 0 ? "blue" : "gray"} aria-live="polite">
|
||||
{t("suggestions", { count: String(attentionCount) })}
|
||||
</Badge>
|
||||
</Group>
|
||||
</div>
|
||||
</Group>
|
||||
<Button
|
||||
variant="subtle"
|
||||
size="compact-sm"
|
||||
rightSection={
|
||||
<IconChevronDown
|
||||
size={15}
|
||||
style={{ transform: isOpen ? "rotate(180deg)" : undefined, transition: "transform 150ms ease" }}
|
||||
/>
|
||||
}
|
||||
aria-expanded={isOpen}
|
||||
aria-controls={panelId}
|
||||
onClick={() => setIsOpen((current) => !current)}
|
||||
>
|
||||
{toggleLabel}
|
||||
</Button>
|
||||
<div>
|
||||
<Group gap="xs">
|
||||
<IconPlugConnected size={20} />
|
||||
<Text fw={600}>{t("title")}</Text>
|
||||
</Group>
|
||||
<Text c="dimmed" size="sm">
|
||||
{t("description")}
|
||||
</Text>
|
||||
</div>
|
||||
{health.data && <Badge variant="light">{t("attention", { count: String(attentionCount) })}</Badge>}
|
||||
</Group>
|
||||
|
||||
<Collapse id={panelId} expanded={isOpen}>
|
||||
<Divider mb="sm" />
|
||||
<Stack gap="sm">
|
||||
<ServiceUrlTemplate
|
||||
serverOrigin={serverOrigin}
|
||||
onServerOriginChange={setServerOrigin}
|
||||
mode={urlMode}
|
||||
onModeChange={setUrlMode}
|
||||
/>
|
||||
<Group justify="space-between">
|
||||
<SegmentedControl
|
||||
value={filter}
|
||||
onChange={(value) => setFilter(value as DockerReconciliationInboxFilter)}
|
||||
data={[
|
||||
{ value: "attention", label: t("filter.attention") },
|
||||
{ value: "represented", label: t("filter.represented") },
|
||||
{ value: "all", label: t("filter.all") },
|
||||
]}
|
||||
/>
|
||||
<Group gap="xs">
|
||||
{dismissedCandidateKeys.length > 0 && (
|
||||
<Button variant="subtle" size="xs" onClick={() => setDismissedCandidateKeys([])}>
|
||||
{t("action.restoreDismissed", { count: String(dismissedCandidateKeys.length) })}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="light"
|
||||
size="xs"
|
||||
loading={isRefreshing}
|
||||
leftSection={<IconRefresh size={14} />}
|
||||
onClick={() => refreshInventory.mutate()}
|
||||
>
|
||||
{t("action.refresh")}
|
||||
</Button>
|
||||
</Group>
|
||||
</Group>
|
||||
|
||||
<Group justify="space-between">
|
||||
<SegmentedControl
|
||||
size="xs"
|
||||
value={filter}
|
||||
onChange={(value) => setFilter(value as DockerReconciliationInboxFilter)}
|
||||
data={[
|
||||
{ value: "attention", label: t("filter.attention") },
|
||||
{ value: "represented", label: t("filter.represented") },
|
||||
{ value: "all", label: t("filter.all") },
|
||||
]}
|
||||
{unavailableEndpoints.length > 0 && (
|
||||
<Alert color="yellow" icon={<IconAlertTriangle size={16} />}>
|
||||
{t("endpointUnavailable", { names: unavailableEndpoints.map(({ name }) => name).join(", ") })}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{candidates.length === 0 ? (
|
||||
<Text c="dimmed" size="sm">
|
||||
{reconciliation.data.candidates.length === 0 ? t("empty") : t("emptyFilter")}
|
||||
</Text>
|
||||
) : (
|
||||
<SimpleGrid cols={{ base: 1, lg: 2 }}>
|
||||
{candidates.map((candidate) => (
|
||||
<DockerReconciliationCandidate
|
||||
key={candidate.candidateKey}
|
||||
candidate={candidate}
|
||||
health={health.data?.services.find(({ key }) => key === candidate.candidateKey)}
|
||||
onDismiss={() =>
|
||||
setDismissedCandidateKeys((current) =>
|
||||
dismissDockerReconciliationCandidate(current, candidate.candidateKey),
|
||||
)
|
||||
}
|
||||
/>
|
||||
<Group gap="xs">
|
||||
{dismissedCandidateKeys.length > 0 && (
|
||||
<Button variant="subtle" size="compact-xs" onClick={() => setDismissedCandidateKeys([])}>
|
||||
{t("action.restoreDismissed", { count: String(dismissedCandidateKeys.length) })}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="light"
|
||||
size="compact-xs"
|
||||
loading={isRefreshing}
|
||||
leftSection={<IconRefresh size={14} />}
|
||||
onClick={() => refreshInventory.mutate()}
|
||||
>
|
||||
{tGlobal("docker.action.refresh.label")}
|
||||
</Button>
|
||||
</Group>
|
||||
</Group>
|
||||
|
||||
{unavailableEndpoints.length > 0 && (
|
||||
<Alert color="yellow" icon={<IconAlertTriangle size={16} />}>
|
||||
{t("endpointUnavailable", { names: unavailableEndpoints.map(({ name }) => name).join(", ") })}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{candidates.length === 0 ? (
|
||||
<Text c="dimmed" size="sm">
|
||||
{reconciliation.data.candidates.length === 0 ? t("empty") : t("emptyFilter")}
|
||||
</Text>
|
||||
) : (
|
||||
<Accordion multiple variant="separated" radius="sm" chevron={null}>
|
||||
{candidates.map((candidate) => (
|
||||
<DockerReconciliationCandidate
|
||||
key={candidate.candidateKey}
|
||||
candidate={candidate}
|
||||
health={health.data?.services.find(({ key }) => key === candidate.candidateKey)}
|
||||
serverOrigin={serverOrigin}
|
||||
urlMode={urlMode}
|
||||
onDismiss={() =>
|
||||
setDismissedCandidateKeys((current) =>
|
||||
dismissDockerReconciliationCandidate(current, candidate.candidateKey),
|
||||
)
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</Accordion>
|
||||
)}
|
||||
</Stack>
|
||||
</Collapse>
|
||||
))}
|
||||
</SimpleGrid>
|
||||
)}
|
||||
</Stack>
|
||||
</Paper>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
|
||||
const DockerReconciliationCandidate = ({
|
||||
candidate,
|
||||
health,
|
||||
serverOrigin,
|
||||
urlMode,
|
||||
onDismiss,
|
||||
}: {
|
||||
candidate: ReconciliationCandidate;
|
||||
health: ServiceHealth | undefined;
|
||||
serverOrigin: string;
|
||||
urlMode: UrlTemplateMode;
|
||||
onDismiss: () => void;
|
||||
}) => {
|
||||
const t = useScopedI18n("docker.reconciliation");
|
||||
const tGlobal = useI18n();
|
||||
const { openModal: openAppModal } = useModalAction(AddDockerAppToHomarr);
|
||||
const { openModal: openIntegrationModal } = useModalAction(IntegrationSelectModal);
|
||||
const templateUrl = getTemplateUrl(candidate, serverOrigin, urlMode);
|
||||
const urlSuggestions = Array.from(
|
||||
new Set([templateUrl, ...candidate.urlCandidates.map(({ url }) => url)].filter((url) => url.length > 0)),
|
||||
);
|
||||
const initialUrl = urlSuggestions[0] ?? "";
|
||||
const [url, setUrl] = useState(initialUrl);
|
||||
const isUrlEdited = useRef(false);
|
||||
const target = getCandidateTarget(candidate);
|
||||
const { openModal } = useModalAction(AddDockerAppToHomarr);
|
||||
const initialUrlCandidate =
|
||||
candidate.urlCandidates.find(
|
||||
({ url, scopes }) => url.length > 0 && (candidate.match ? true : scopes.includes("browser")),
|
||||
) ?? candidate.urlCandidates.find(({ source }) => source === "manual");
|
||||
const [selectedCandidateId, setSelectedCandidateId] = useState(initialUrlCandidate?.id ?? null);
|
||||
const [url, setUrl] = useState(initialUrlCandidate?.url ?? "");
|
||||
const selectedCandidate = candidate.urlCandidates.find(({ id }) => id === selectedCandidateId);
|
||||
const validatedUrl = getValidDockerServiceUrl(url);
|
||||
const isInvalidUrl = url.length > 0 && validatedUrl === null;
|
||||
const target = getCandidateTarget(candidate, validatedUrl ?? "");
|
||||
const actionNeedsUrl = target.kind === "createApp" || target.kind === "setupIntegration";
|
||||
const visibleHealthLayers =
|
||||
health?.layers.filter(({ status }) => status !== "notApplicable" && status !== "notObserved") ?? [];
|
||||
const isActionDisabled = actionNeedsUrl && validatedUrl === null;
|
||||
|
||||
useEffect(() => {
|
||||
if (isUrlEdited.current) return;
|
||||
setUrl(initialUrl);
|
||||
}, [initialUrl]);
|
||||
setSelectedCandidateId(initialUrlCandidate?.id ?? null);
|
||||
setUrl(initialUrlCandidate?.url ?? "");
|
||||
}, [initialUrlCandidate?.id, initialUrlCandidate?.url]);
|
||||
|
||||
return (
|
||||
<Accordion.Item value={candidate.candidateKey}>
|
||||
<Group wrap="nowrap" gap={4} pr="sm">
|
||||
<Accordion.Control
|
||||
style={{ flex: 1 }}
|
||||
icon={
|
||||
<Avatar src={candidate.container.iconUrl} radius="sm" size="sm">
|
||||
<Card withBorder padding="md">
|
||||
<Stack gap="sm">
|
||||
<Group justify="space-between" align="start" wrap="nowrap">
|
||||
<Group wrap="nowrap">
|
||||
<Avatar src={candidate.container.iconUrl} radius="sm">
|
||||
{candidate.container.name.at(0)?.toUpperCase()}
|
||||
</Avatar>
|
||||
}
|
||||
>
|
||||
<div style={{ minWidth: 0 }}>
|
||||
<Group gap="xs" wrap="nowrap">
|
||||
<Text fw={600} size="sm" truncate>
|
||||
<div>
|
||||
<Text fw={600} lineClamp={1}>
|
||||
{candidate.container.name}
|
||||
</Text>
|
||||
<Badge color={stateColor(candidate.state)} variant="light" size="xs">
|
||||
{t(`state.${candidate.state}`)}
|
||||
</Badge>
|
||||
</Group>
|
||||
<Text c="dimmed" size="xs">
|
||||
{candidate.endpointName}
|
||||
</Text>
|
||||
</div>
|
||||
</Group>
|
||||
<Badge color={stateColor(candidate.state)} variant="light">
|
||||
{t(`state.${candidate.state}`)}
|
||||
</Badge>
|
||||
</Group>
|
||||
|
||||
{candidate.match && (
|
||||
<Group gap="xs">
|
||||
<Badge variant="outline">{candidate.match.kind}</Badge>
|
||||
<Text c="dimmed" size="xs">
|
||||
{candidate.endpointName}
|
||||
{t("match", { confidence: t(`confidence.${candidate.match.confidence}`) })}
|
||||
</Text>
|
||||
</Group>
|
||||
)}
|
||||
|
||||
{candidate.representation.signals.ambiguous && (
|
||||
<Alert color="yellow" icon={<IconAlertTriangle size={16} />}>
|
||||
{t("ambiguous")}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{health && (
|
||||
<div>
|
||||
<Text c="dimmed" size="xs" mb={4}>
|
||||
{t("health.title")}
|
||||
</Text>
|
||||
<Group gap={4}>
|
||||
{health.layers.map((layer) => (
|
||||
<Badge key={layer.layer} color={healthStatusColor(layer.status)} variant="dot" size="sm">
|
||||
{t(`health.layer.${layer.layer}`)}: {t(`health.status.${layer.status}`)}
|
||||
</Badge>
|
||||
))}
|
||||
</Group>
|
||||
</div>
|
||||
</Accordion.Control>
|
||||
<Group gap={4} wrap="nowrap">
|
||||
{target.kind === "createApp" && (
|
||||
)}
|
||||
|
||||
<Select
|
||||
label={t("url.label")}
|
||||
description={selectedCandidate ? t(`reason.${selectedCandidate.reason}`) : t("reason.manualHostRequired")}
|
||||
value={selectedCandidateId}
|
||||
data={candidate.urlCandidates.map((item) => ({
|
||||
value: item.id,
|
||||
label: item.url || t("url.manual"),
|
||||
}))}
|
||||
onChange={(value) => {
|
||||
setSelectedCandidateId(value);
|
||||
setUrl(candidate.urlCandidates.find(({ id }) => id === value)?.url ?? "");
|
||||
}}
|
||||
/>
|
||||
<TextInput
|
||||
label={t("url.inputLabel")}
|
||||
aria-label={t("url.inputLabel")}
|
||||
value={url}
|
||||
placeholder="https://service.example.com"
|
||||
error={isInvalidUrl ? t("url.invalid") : undefined}
|
||||
onChange={(event) => setUrl(event.currentTarget.value)}
|
||||
/>
|
||||
|
||||
<Group justify="space-between">
|
||||
<Button variant="subtle" color="gray" leftSection={<IconEyeOff size={16} />} onClick={onDismiss}>
|
||||
{t("action.dismiss")}
|
||||
</Button>
|
||||
{target.kind === "createApp" ? (
|
||||
<Button
|
||||
variant="light"
|
||||
size="compact-xs"
|
||||
leftSection={<IconApps size={14} />}
|
||||
rightSection={<IconArrowRight size={16} />}
|
||||
disabled={isActionDisabled}
|
||||
onClick={() =>
|
||||
openAppModal({
|
||||
openModal({
|
||||
selectedContainers: [candidate.container],
|
||||
initialUrls: [(normalizeServiceUrl(url) ?? url) || null],
|
||||
initialUrls: validatedUrl ? [validatedUrl] : undefined,
|
||||
})
|
||||
}
|
||||
>
|
||||
{tGlobal("integration.field.createApp.label")}
|
||||
{t("action.createApp")}
|
||||
</Button>
|
||||
)}
|
||||
{target.kind === "setupIntegration" && (
|
||||
<Button
|
||||
variant="light"
|
||||
size="compact-xs"
|
||||
leftSection={<IconPlugConnected size={14} />}
|
||||
onClick={() =>
|
||||
openIntegrationModal({
|
||||
initialKind: target.integrationKind,
|
||||
initialName: candidate.container.name,
|
||||
initialUrl: normalizeServiceUrl(url) ?? url,
|
||||
})
|
||||
}
|
||||
>
|
||||
{t("action.setupIntegration")}
|
||||
</Button>
|
||||
)}
|
||||
{(target.kind === "reviewIntegration" || target.kind === "viewRepresentation") && (
|
||||
) : (
|
||||
<Button
|
||||
component={Link}
|
||||
href={target.href}
|
||||
variant="light"
|
||||
size="compact-xs"
|
||||
leftSection={target.kind === "reviewIntegration" ? <IconSettings size={14} /> : <IconEye size={14} />}
|
||||
rightSection={<IconArrowRight size={16} />}
|
||||
disabled={isActionDisabled}
|
||||
onClick={(event) => {
|
||||
if (isActionDisabled) event.preventDefault();
|
||||
}}
|
||||
>
|
||||
{t(`action.${target.kind}`)}
|
||||
</Button>
|
||||
)}
|
||||
<Tooltip label={t("action.dismiss")} events={{ hover: true, focus: true, touch: false }}>
|
||||
<ActionIcon variant="subtle" color="gray" size="sm" aria-label={t("action.dismiss")} onClick={onDismiss}>
|
||||
<IconEyeOff size={15} />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
</Group>
|
||||
</Group>
|
||||
|
||||
<Accordion.Panel>
|
||||
<Stack gap="sm">
|
||||
{candidate.representation.signals.ambiguous && (
|
||||
<Alert color="yellow" icon={<IconAlertTriangle size={16} />}>
|
||||
{t("ambiguous")}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{visibleHealthLayers.length > 0 && (
|
||||
<SimpleGrid cols={{ base: 1, sm: 2, lg: 3 }} spacing="xs">
|
||||
{visibleHealthLayers.map((layer) => (
|
||||
<Group key={layer.layer} gap="xs" wrap="nowrap">
|
||||
<HealthStatusIcon status={layer.status} />
|
||||
<Text size="xs">
|
||||
{t(`health.layer.${layer.layer}`)} ·{" "}
|
||||
<Text component="span" c="dimmed" inherit>
|
||||
{t(`health.status.${layer.status}`)}
|
||||
</Text>
|
||||
</Text>
|
||||
</Group>
|
||||
))}
|
||||
</SimpleGrid>
|
||||
)}
|
||||
|
||||
{actionNeedsUrl && (
|
||||
<Autocomplete
|
||||
label={tGlobal("integration.field.url.label")}
|
||||
value={url}
|
||||
data={urlSuggestions}
|
||||
placeholder={t("url.manual")}
|
||||
onChange={(value) => {
|
||||
isUrlEdited.current = true;
|
||||
setUrl(value);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</Stack>
|
||||
</Accordion.Panel>
|
||||
</Accordion.Item>
|
||||
</Stack>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
|
||||
const getCandidateTarget = (candidate: ReconciliationCandidate) => {
|
||||
const getCandidateTarget = (candidate: ReconciliationCandidate, url: string) => {
|
||||
if (candidate.representation.signals.ambiguous) {
|
||||
if (candidate.nextAction === "reviewIntegration" && candidate.match) {
|
||||
const params = new URLSearchParams({ search: getIntegrationName(candidate.match.kind) });
|
||||
@@ -389,7 +312,9 @@ const getCandidateTarget = (candidate: ReconciliationCandidate) => {
|
||||
return { kind: "viewRepresentation" as const, href: "/manage/apps" };
|
||||
}
|
||||
if (candidate.state === "newRecognized" && candidate.match) {
|
||||
return { kind: "setupIntegration" as const, integrationKind: candidate.match.kind };
|
||||
const params = new URLSearchParams({ kind: candidate.match.kind, name: candidate.container.name });
|
||||
if (url) params.set("url", url);
|
||||
return { kind: "setupIntegration" as const, href: `/manage/integrations/new?${params.toString()}` };
|
||||
}
|
||||
|
||||
if (candidate.state === "newApp") return { kind: "createApp" as const };
|
||||
@@ -412,21 +337,8 @@ const stateColor = (state: ReconciliationCandidate["state"]) => {
|
||||
return "blue";
|
||||
};
|
||||
|
||||
const HealthStatusIcon = ({ status }: { status: ServiceHealth["layers"][number]["status"] }) => {
|
||||
let color = "gray";
|
||||
let icon = <IconMinus size={12} />;
|
||||
|
||||
if (["available", "configured", "linked"].includes(status)) {
|
||||
color = "green";
|
||||
icon = <IconCheck size={12} />;
|
||||
} else if (["missing", "changed", "unused"].includes(status)) {
|
||||
color = "yellow";
|
||||
icon = <IconAlertTriangle size={12} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<ThemeIcon color={color} variant="light" radius="xl" size="sm">
|
||||
{icon}
|
||||
</ThemeIcon>
|
||||
);
|
||||
const healthStatusColor = (status: ServiceHealth["layers"][number]["status"]) => {
|
||||
if (["available", "configured", "linked"].includes(status)) return "green";
|
||||
if (["missing", "changed", "unused"].includes(status)) return "yellow";
|
||||
return "gray";
|
||||
};
|
||||
@@ -1,10 +1,8 @@
|
||||
import { headers } from "next/headers";
|
||||
import { notFound } from "next/navigation";
|
||||
import { Stack, Title } from "@mantine/core";
|
||||
|
||||
import { api } from "@homarr/api/server";
|
||||
import { auth } from "@homarr/auth/next";
|
||||
import { extractBaseUrlFromHeaders } from "@homarr/common";
|
||||
import { env } from "@homarr/docker/env";
|
||||
import { getScopedI18n } from "@homarr/translation/server";
|
||||
|
||||
@@ -18,10 +16,7 @@ export default async function DockerPage() {
|
||||
notFound();
|
||||
}
|
||||
|
||||
const [{ containers, endpoints, timestamp }, requestHeaders] = await Promise.all([
|
||||
api.docker.getContainers(),
|
||||
headers(),
|
||||
]);
|
||||
const { containers, endpoints, timestamp } = await api.docker.getContainers();
|
||||
const tDocker = await getScopedI18n("docker");
|
||||
|
||||
return (
|
||||
@@ -29,7 +24,7 @@ export default async function DockerPage() {
|
||||
<DynamicBreadcrumb />
|
||||
<Stack>
|
||||
<Title order={1}>{tDocker("title")}</Title>
|
||||
<DockerReconciliation defaultServerOrigin={extractBaseUrlFromHeaders(requestHeaders)} />
|
||||
<DockerReconciliation />
|
||||
<DockerTable initialData={{ containers, endpoints, timestamp }} />
|
||||
</Stack>
|
||||
</>
|
||||
|
||||
@@ -227,9 +227,7 @@ const LoadedBoardItemContent = ({
|
||||
(host: HTMLDivElement | null) => {
|
||||
if (!host || !surfacePortalTarget || isAdvanced) return;
|
||||
cancelPreviewEntrance();
|
||||
if (host.childNodes.length !== 1 || host.firstChild !== surfacePortalTarget) {
|
||||
host.replaceChildren(surfacePortalTarget);
|
||||
}
|
||||
host.append(surfacePortalTarget);
|
||||
},
|
||||
[cancelPreviewEntrance, isAdvanced, surfacePortalTarget],
|
||||
);
|
||||
|
||||
@@ -3,16 +3,16 @@
|
||||
import { Suspense, use } from "react";
|
||||
import { Center, Loader } from "@mantine/core";
|
||||
import { ErrorBoundary } from "react-error-boundary";
|
||||
import type { FallbackProps } from "react-error-boundary";
|
||||
|
||||
import type { WidgetKind } from "@homarr/definitions";
|
||||
import { createModal, modalSizeForm } from "@homarr/modals";
|
||||
import { useModalAction } from "@homarr/modals";
|
||||
import { WidgetError } from "@homarr/widgets/errors";
|
||||
import type * as WidgetModalsModule from "@homarr/widgets/modals";
|
||||
import type { WidgetEditModalProps } from "@homarr/widgets/modals";
|
||||
|
||||
import type * as IntegrationEditFormModule from "~/components/integration/embedded-integration-edit-form";
|
||||
import type { EmbeddedIntegrationEditFormProps } from "~/components/integration/embedded-integration-edit-form";
|
||||
import type * as IntegrationEditModalModule from "~/components/integration/embedded-integration-edit-modal";
|
||||
import type { EmbeddedIntegrationEditModalProps } from "~/components/integration/embedded-integration-edit-modal";
|
||||
|
||||
let widgetEditModalPromise: Promise<typeof WidgetModalsModule> | undefined;
|
||||
|
||||
@@ -29,38 +29,42 @@ export const loadWidgetEditModal = () => {
|
||||
|
||||
export const preloadWidgetEditModal = () => void loadWidgetEditModal().catch(() => undefined);
|
||||
|
||||
let integrationEditFormPromise: Promise<typeof IntegrationEditFormModule> | undefined;
|
||||
let integrationEditModalPromise: Promise<typeof IntegrationEditModalModule> | undefined;
|
||||
|
||||
const loadIntegrationEditForm = () => {
|
||||
if (integrationEditFormPromise) return integrationEditFormPromise;
|
||||
const loadIntegrationEditModal = () => {
|
||||
if (integrationEditModalPromise) return integrationEditModalPromise;
|
||||
|
||||
const currentPromise = import("~/components/integration/embedded-integration-edit-form");
|
||||
integrationEditFormPromise = currentPromise;
|
||||
const currentPromise = import("~/components/integration/embedded-integration-edit-modal");
|
||||
integrationEditModalPromise = currentPromise;
|
||||
void currentPromise.catch(() => {
|
||||
if (integrationEditFormPromise === currentPromise) integrationEditFormPromise = undefined;
|
||||
if (integrationEditModalPromise === currentPromise) integrationEditModalPromise = undefined;
|
||||
});
|
||||
return currentPromise;
|
||||
};
|
||||
|
||||
const LazyIntegrationEditFormContent = (props: EmbeddedIntegrationEditFormProps) => {
|
||||
const { EmbeddedIntegrationEditForm } = use(loadIntegrationEditForm());
|
||||
return <EmbeddedIntegrationEditForm {...props} />;
|
||||
const LazyIntegrationEditModalContent = (props: {
|
||||
actions: { closeModal: () => void };
|
||||
innerProps: EmbeddedIntegrationEditModalProps;
|
||||
}) => {
|
||||
const { EmbeddedIntegrationEditModal } = use(loadIntegrationEditModal());
|
||||
const Component = EmbeddedIntegrationEditModal.component;
|
||||
return <Component {...props} />;
|
||||
};
|
||||
|
||||
const IntegrationEditErrorFallback = ({ error, resetErrorBoundary }: FallbackProps) => (
|
||||
<Center py="xl">
|
||||
<WidgetError
|
||||
error={error}
|
||||
resetErrorBoundary={() => {
|
||||
integrationEditFormPromise = undefined;
|
||||
resetErrorBoundary();
|
||||
}}
|
||||
/>
|
||||
</Center>
|
||||
);
|
||||
|
||||
const LazyIntegrationEditForm = (props: EmbeddedIntegrationEditFormProps) => (
|
||||
<ErrorBoundary FallbackComponent={IntegrationEditErrorFallback}>
|
||||
const LazyIntegrationEditModal = createModal<EmbeddedIntegrationEditModalProps>((props) => (
|
||||
<ErrorBoundary
|
||||
fallbackRender={({ error, resetErrorBoundary }) => (
|
||||
<Center py="xl">
|
||||
<WidgetError
|
||||
error={error}
|
||||
resetErrorBoundary={() => {
|
||||
integrationEditModalPromise = undefined;
|
||||
resetErrorBoundary();
|
||||
}}
|
||||
/>
|
||||
</Center>
|
||||
)}
|
||||
>
|
||||
<Suspense
|
||||
fallback={
|
||||
<Center py="xl">
|
||||
@@ -68,10 +72,15 @@ const LazyIntegrationEditForm = (props: EmbeddedIntegrationEditFormProps) => (
|
||||
</Center>
|
||||
}
|
||||
>
|
||||
<LazyIntegrationEditFormContent {...props} />
|
||||
<LazyIntegrationEditModalContent {...props} />
|
||||
</Suspense>
|
||||
</ErrorBoundary>
|
||||
);
|
||||
)).withOptions({
|
||||
defaultTitle: (t) => t("item.edit.tab.integration"),
|
||||
size: modalSizeForm,
|
||||
presentation: "inspector",
|
||||
closeOnClickOutside: true,
|
||||
});
|
||||
|
||||
interface LazyWidgetEditModalContentProps {
|
||||
actions: { closeModal: () => void };
|
||||
@@ -81,12 +90,17 @@ interface LazyWidgetEditModalContentProps {
|
||||
const LazyWidgetEditModalContent = (props: LazyWidgetEditModalContentProps) => {
|
||||
const { WidgetEditModal } = use(loadWidgetEditModal());
|
||||
const Component = WidgetEditModal.component;
|
||||
const { openModal: openIntegrationEditModal } = useModalAction(LazyIntegrationEditModal);
|
||||
return (
|
||||
<Component
|
||||
{...props}
|
||||
innerProps={{
|
||||
...props.innerProps,
|
||||
integrationEditForm: LazyIntegrationEditForm,
|
||||
onEditIntegration: (integrationId) =>
|
||||
openIntegrationEditModal({
|
||||
integrationId,
|
||||
onSuccess: props.innerProps.onIntegrationSaved,
|
||||
}),
|
||||
}}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef } from "react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Group, Stack, Text, ThemeIcon, UnstyledButton } from "@mantine/core";
|
||||
import { Group, Stack, Text, TextInput, ThemeIcon, UnstyledButton } from "@mantine/core";
|
||||
import {
|
||||
IconApps,
|
||||
IconBox,
|
||||
@@ -26,7 +26,7 @@ import type {
|
||||
UniversalCreateActionGroup,
|
||||
UniversalCreateActionKey,
|
||||
} from "./universal-create-actions";
|
||||
import { getUniversalCreateActionDefinitions } from "./universal-create-actions";
|
||||
import { filterAndRankUniversalCreateActions, getUniversalCreateActionDefinitions } from "./universal-create-actions";
|
||||
import type { SetupMetricEntryPoint } from "./setup-analytics";
|
||||
import { useSetupAnalytics } from "./setup-analytics";
|
||||
|
||||
@@ -52,6 +52,7 @@ export const UniversalCreateModal = createModal<UniversalCreateModalProps>(({ ac
|
||||
const router = useRouter();
|
||||
const t = useScopedI18n("universalCreate");
|
||||
const { openModal: openAddBoardModal } = useModalAction(AddBoardModal);
|
||||
const [query, setQuery] = useState("");
|
||||
const trackedOpen = useRef(false);
|
||||
const boardActions = innerProps.boardActions;
|
||||
const entryPoint = innerProps.entryPoint ?? (boardActions ? "board" : "header");
|
||||
@@ -117,43 +118,58 @@ export const UniversalCreateModal = createModal<UniversalCreateModalProps>(({ ac
|
||||
keywords: t(`action.${definition.key}.keywords`).split(" "),
|
||||
}) satisfies RankedUniversalCreateAction,
|
||||
);
|
||||
const orderedActions = resolvedActions.toSorted((left, right) => right.priority - left.priority);
|
||||
const visibleActions = filterAndRankUniversalCreateActions(resolvedActions, query);
|
||||
const groups = ["currentBoard", "library", "boards"] satisfies UniversalCreateActionGroup[];
|
||||
|
||||
return (
|
||||
<Stack gap="md">
|
||||
{groups.map((group) => {
|
||||
const groupActions = orderedActions.filter((action) => action.group === group);
|
||||
if (groupActions.length === 0) return null;
|
||||
<TextInput
|
||||
data-autofocus
|
||||
value={query}
|
||||
onChange={(event) => setQuery(event.currentTarget.value)}
|
||||
leftSection={<IconSearch size={16} />}
|
||||
placeholder={t("search.placeholder")}
|
||||
aria-label={t("search.label")}
|
||||
/>
|
||||
|
||||
return (
|
||||
<Stack key={group} gap={4}>
|
||||
<Text c="dimmed" fw={600} size="xs" tt="uppercase" px="sm">
|
||||
{t(`group.${group}`)}
|
||||
</Text>
|
||||
{groupActions.map((action) => {
|
||||
const Icon = actionIcons[action.key];
|
||||
return (
|
||||
<UnstyledButton key={action.key} className={classes.action} onClick={() => invokeAction(action.key)}>
|
||||
<Group wrap="nowrap" align="flex-start">
|
||||
<ThemeIcon className={classes.actionIcon} variant="light" radius="md">
|
||||
<Icon size={18} stroke={1.5} />
|
||||
</ThemeIcon>
|
||||
<Stack gap={1}>
|
||||
<Text fw={600} size="sm">
|
||||
{action.name}
|
||||
</Text>
|
||||
<Text c="dimmed" size="xs">
|
||||
{action.description}
|
||||
</Text>
|
||||
</Stack>
|
||||
</Group>
|
||||
</UnstyledButton>
|
||||
);
|
||||
})}
|
||||
</Stack>
|
||||
);
|
||||
})}
|
||||
{visibleActions.length === 0 ? (
|
||||
<Text c="dimmed" ta="center" py="lg">
|
||||
{t("search.noResults")}
|
||||
</Text>
|
||||
) : (
|
||||
groups.map((group) => {
|
||||
const groupActions = visibleActions.filter((action) => action.group === group);
|
||||
if (groupActions.length === 0) return null;
|
||||
|
||||
return (
|
||||
<Stack key={group} gap={4}>
|
||||
<Text c="dimmed" fw={600} size="xs" tt="uppercase" px="sm">
|
||||
{t(`group.${group}`)}
|
||||
</Text>
|
||||
{groupActions.map((action) => {
|
||||
const Icon = actionIcons[action.key];
|
||||
return (
|
||||
<UnstyledButton key={action.key} className={classes.action} onClick={() => invokeAction(action.key)}>
|
||||
<Group wrap="nowrap" align="flex-start">
|
||||
<ThemeIcon className={classes.actionIcon} variant="light" radius="md">
|
||||
<Icon size={18} stroke={1.5} />
|
||||
</ThemeIcon>
|
||||
<Stack gap={1}>
|
||||
<Text fw={600} size="sm">
|
||||
{action.name}
|
||||
</Text>
|
||||
<Text c="dimmed" size="xs">
|
||||
{action.description}
|
||||
</Text>
|
||||
</Stack>
|
||||
</Group>
|
||||
</UnstyledButton>
|
||||
);
|
||||
})}
|
||||
</Stack>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</Stack>
|
||||
);
|
||||
}).withOptions({
|
||||
|
||||
@@ -1,90 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useImperativeHandle, useRef } from "react";
|
||||
import { Alert, Button, Group, Skeleton, Stack, Text } from "@mantine/core";
|
||||
import { IconInfoCircle } from "@tabler/icons-react";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { getIntegrationName } from "@homarr/definitions";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import { IntegrationAvatar } from "@homarr/ui";
|
||||
import type { EmbeddedIntegrationEditFormProps } from "@homarr/widgets/modals";
|
||||
|
||||
import type { EditIntegrationFormHandle } from "~/app/[locale]/manage/integrations/edit/[id]/_integration-edit-form";
|
||||
import { EditIntegrationForm } from "~/app/[locale]/manage/integrations/edit/[id]/_integration-edit-form";
|
||||
|
||||
export type { EmbeddedIntegrationEditFormProps } from "@homarr/widgets/modals";
|
||||
|
||||
export const EmbeddedIntegrationEditForm = ({
|
||||
integrationId,
|
||||
handleRef,
|
||||
onSuccess,
|
||||
}: EmbeddedIntegrationEditFormProps) => {
|
||||
const t = useI18n();
|
||||
const integrationFormRef = useRef<EditIntegrationFormHandle>(null);
|
||||
const {
|
||||
data: integration,
|
||||
isPending,
|
||||
isError,
|
||||
refetch,
|
||||
} = clientApi.integration.byId.useQuery({
|
||||
id: integrationId,
|
||||
});
|
||||
|
||||
useImperativeHandle(
|
||||
handleRef,
|
||||
() => ({
|
||||
submitIfDirty: async () => {
|
||||
if (!integrationFormRef.current?.isDirty()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return integrationFormRef.current.submit();
|
||||
},
|
||||
}),
|
||||
[],
|
||||
);
|
||||
|
||||
if (isPending) {
|
||||
return (
|
||||
<Stack gap="sm" aria-busy="true" aria-label={t("item.edit.integration.loading")}>
|
||||
<Skeleton height={36} width="60%" />
|
||||
<Skeleton height={60} />
|
||||
<Skeleton height={120} />
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
if (isError || !integration) {
|
||||
return (
|
||||
<Alert color="red" title={t("common.error")}>
|
||||
<Stack gap="sm">
|
||||
<Text size="sm">{t("item.edit.integration.loadError")}</Text>
|
||||
<Button variant="light" color="red" onClick={() => void refetch()}>
|
||||
{t("common.action.tryAgain")}
|
||||
</Button>
|
||||
</Stack>
|
||||
</Alert>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Stack>
|
||||
<Group gap="sm" wrap="nowrap">
|
||||
<IntegrationAvatar kind={integration.kind} size="sm" />
|
||||
<Stack gap={0} style={{ minWidth: 0 }}>
|
||||
<Text fw={600} truncate>
|
||||
{integration.name}
|
||||
</Text>
|
||||
<Text size="xs" c="dimmed">
|
||||
{getIntegrationName(integration.kind)}
|
||||
</Text>
|
||||
</Stack>
|
||||
</Group>
|
||||
<Alert icon={<IconInfoCircle size={16} />} color="blue" variant="light">
|
||||
{t("item.edit.integration.propagationNotice")}
|
||||
</Alert>
|
||||
<EditIntegrationForm integration={integration} hideButtons formRef={integrationFormRef} onSuccess={onSuccess} />
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,86 @@
|
||||
"use client";
|
||||
|
||||
import { Alert, Button, Group, Skeleton, Stack, Text } from "@mantine/core";
|
||||
import { IconInfoCircle } from "@tabler/icons-react";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { getIntegrationName } from "@homarr/definitions";
|
||||
import { createModal, modalSizeForm } from "@homarr/modals";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import { IntegrationAvatar } from "@homarr/ui";
|
||||
|
||||
import { EditIntegrationForm } from "~/app/[locale]/manage/integrations/edit/[id]/_integration-edit-form";
|
||||
|
||||
export interface EmbeddedIntegrationEditModalProps {
|
||||
integrationId: string;
|
||||
onSuccess?: () => void;
|
||||
}
|
||||
|
||||
export const EmbeddedIntegrationEditModal = createModal<EmbeddedIntegrationEditModalProps>(
|
||||
({ actions, innerProps }) => {
|
||||
const t = useI18n();
|
||||
const {
|
||||
data: integration,
|
||||
isPending,
|
||||
isError,
|
||||
refetch,
|
||||
} = clientApi.integration.byId.useQuery({
|
||||
id: innerProps.integrationId,
|
||||
});
|
||||
|
||||
if (isPending) {
|
||||
return (
|
||||
<Stack gap="sm" aria-busy="true" aria-label={t("item.edit.integration.loading")}>
|
||||
<Skeleton height={36} width="60%" />
|
||||
<Skeleton height={60} />
|
||||
<Skeleton height={120} />
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
if (isError || !integration) {
|
||||
return (
|
||||
<Alert color="red" title={t("common.error")}>
|
||||
<Stack gap="sm">
|
||||
<Text size="sm">{t("item.edit.integration.loadError")}</Text>
|
||||
<Button variant="light" color="red" onClick={() => void refetch()}>
|
||||
{t("common.action.tryAgain")}
|
||||
</Button>
|
||||
</Stack>
|
||||
</Alert>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Stack>
|
||||
<Group gap="sm" wrap="nowrap">
|
||||
<IntegrationAvatar kind={integration.kind} size="sm" />
|
||||
<Stack gap={0} style={{ minWidth: 0 }}>
|
||||
<Text fw={600} truncate>
|
||||
{integration.name}
|
||||
</Text>
|
||||
<Text size="xs" c="dimmed">
|
||||
{getIntegrationName(integration.kind)}
|
||||
</Text>
|
||||
</Stack>
|
||||
</Group>
|
||||
<Alert icon={<IconInfoCircle size={16} />} color="blue" variant="light">
|
||||
{t("item.edit.integration.propagationNotice")}
|
||||
</Alert>
|
||||
<EditIntegrationForm
|
||||
integration={integration}
|
||||
embedded
|
||||
onSuccess={() => {
|
||||
innerProps.onSuccess?.();
|
||||
actions.closeModal();
|
||||
}}
|
||||
/>
|
||||
</Stack>
|
||||
);
|
||||
},
|
||||
).withOptions({
|
||||
defaultTitle: (t) => t("item.edit.tab.integration"),
|
||||
size: modalSizeForm,
|
||||
presentation: "inspector",
|
||||
closeOnClickOutside: true,
|
||||
});
|
||||
@@ -1,13 +1,12 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Group, ScrollArea, Title, UnstyledButton } from "@mantine/core";
|
||||
import { IconArrowLeft, IconX } from "@tabler/icons-react";
|
||||
import { Group, ScrollArea, Title } from "@mantine/core";
|
||||
import { IconArrowLeft } from "@tabler/icons-react";
|
||||
|
||||
import type { IntegrationKind } from "@homarr/definitions";
|
||||
import { getIntegrationName } from "@homarr/definitions";
|
||||
import { createModal, modalSizeSelect, useModalAction } from "@homarr/modals";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import { IntegrationAvatar } from "@homarr/ui";
|
||||
|
||||
import { NewIntegrationForm } from "~/app/[locale]/manage/integrations/new/_integration-new-form";
|
||||
@@ -20,15 +19,11 @@ interface IntegrationSelectModalProps {
|
||||
enableMockIntegration?: boolean;
|
||||
allowedKinds?: readonly IntegrationKind[];
|
||||
completionBoardId?: string;
|
||||
initialKind?: IntegrationKind;
|
||||
initialUrl?: string;
|
||||
initialName?: string;
|
||||
}
|
||||
|
||||
export const IntegrationSelectModal = createModal<IntegrationSelectModalProps>(({ actions, innerProps }) => {
|
||||
const t = useI18n();
|
||||
const [step, setStep] = useState<"select" | "form">(innerProps.initialKind ? "form" : "select");
|
||||
const [selectedKind, setSelectedKind] = useState<IntegrationKind | null>(innerProps.initialKind ?? null);
|
||||
const [step, setStep] = useState<"select" | "form">("select");
|
||||
const [selectedKind, setSelectedKind] = useState<IntegrationKind | null>(null);
|
||||
const { openModal: openCompletionModal } = useModalAction(IntegrationCompletionModal);
|
||||
|
||||
const handleSelect = (kind: IntegrationKind) => {
|
||||
@@ -40,7 +35,6 @@ export const IntegrationSelectModal = createModal<IntegrationSelectModalProps>((
|
||||
setStep("select");
|
||||
setSelectedKind(null);
|
||||
};
|
||||
const handleFormBack = innerProps.initialKind ? actions.closeModal : handleBack;
|
||||
|
||||
const handleSuccess = (result?: CreatedIntegrationResult) => {
|
||||
actions.closeModal();
|
||||
@@ -52,29 +46,14 @@ export const IntegrationSelectModal = createModal<IntegrationSelectModalProps>((
|
||||
};
|
||||
|
||||
if (step === "form" && selectedKind) {
|
||||
let HeaderIcon = IconArrowLeft;
|
||||
let headerLabel = t("common.action.previous");
|
||||
if (innerProps.initialKind) {
|
||||
HeaderIcon = IconX;
|
||||
headerLabel = t("common.action.close");
|
||||
}
|
||||
|
||||
return (
|
||||
<ScrollArea.Autosize mah="80vh">
|
||||
<UnstyledButton mb="md" onClick={handleFormBack} aria-label={headerLabel}>
|
||||
<Group gap="xs">
|
||||
<HeaderIcon size={18} />
|
||||
<IntegrationAvatar kind={selectedKind} size="sm" />
|
||||
<Title order={4}>{getIntegrationName(selectedKind)}</Title>
|
||||
</Group>
|
||||
</UnstyledButton>
|
||||
<NewIntegrationForm
|
||||
kind={selectedKind}
|
||||
initialUrl={innerProps.initialUrl}
|
||||
initialName={innerProps.initialName}
|
||||
onSuccess={handleSuccess}
|
||||
onCancel={handleFormBack}
|
||||
/>
|
||||
<Group gap="xs" mb="md" style={{ cursor: "pointer" }} onClick={handleBack}>
|
||||
<IconArrowLeft size={18} />
|
||||
<IntegrationAvatar kind={selectedKind} size="sm" />
|
||||
<Title order={4}>{getIntegrationName(selectedKind)}</Title>
|
||||
</Group>
|
||||
<NewIntegrationForm kind={selectedKind} onSuccess={handleSuccess} onCancel={handleBack} />
|
||||
</ScrollArea.Autosize>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -12,7 +12,6 @@ import { iconsRouter } from "./router/icons";
|
||||
import { infoRouter } from "./router/info";
|
||||
import { integrationRouter } from "./router/integration/integration-router";
|
||||
import { inviteRouter } from "./router/invite";
|
||||
import { airQualityRouter } from "./router/widgets/air-quality";
|
||||
import { bazarrRouter } from "./router/widgets/bazarr";
|
||||
import { serverSettingsRouter } from "./router/serverSettings";
|
||||
import { beszelRouter } from "./router/widgets/beszel";
|
||||
@@ -36,7 +35,6 @@ export const mcpRouter = createTRPCRouter({
|
||||
info: infoRouter,
|
||||
integration: integrationRouter,
|
||||
invite: inviteRouter,
|
||||
airQuality: airQualityRouter,
|
||||
bazarr: bazarrRouter,
|
||||
serverSettings: serverSettingsRouter,
|
||||
beszel: beszelRouter,
|
||||
|
||||
@@ -23,11 +23,6 @@ const dockerContainerTargetSchema = z.object({
|
||||
});
|
||||
const dockerContainerTargetsSchema = z.array(dockerContainerTargetSchema).min(1).max(100);
|
||||
|
||||
const normalizeGetContainersInput = (input: { endpointIds?: string[] } | undefined) => {
|
||||
if (!input?.endpointIds || input.endpointIds.length === 0) return {};
|
||||
return input;
|
||||
};
|
||||
|
||||
export const dockerRouter = createTRPCRouter({
|
||||
reconcileServices: permissionRequiredProcedure
|
||||
.requiresPermission("admin")
|
||||
@@ -70,14 +65,12 @@ export const dockerRouter = createTRPCRouter({
|
||||
.meta({
|
||||
mcp: {
|
||||
enabled: true,
|
||||
description:
|
||||
"List Docker containers with their state, image, CPU/memory usage, and ports. Optionally filter by endpoint IDs; omitted or empty means all endpoints.",
|
||||
description: "List all Docker containers with their state, image, CPU/memory usage, and ports",
|
||||
},
|
||||
})
|
||||
.concat(dockerMiddleware())
|
||||
.input(z.object({ endpointIds: z.array(z.string().min(1)).max(100).optional() }).optional())
|
||||
.query(async ({ input }) => {
|
||||
const innerHandler = dockerContainersRequestHandler.handler(normalizeGetContainersInput(input));
|
||||
.query(async () => {
|
||||
const innerHandler = dockerContainersRequestHandler.handler({});
|
||||
const result = await innerHandler.getDataAsync();
|
||||
|
||||
const { data, timestamp } = result;
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { env } from "@homarr/common/env";
|
||||
import { airQualityRequestHandler } from "@homarr/request-handler/air-quality";
|
||||
|
||||
import { createTRPCRouter, publicProcedure } from "../../trpc";
|
||||
|
||||
const atLocationInput = z.object({
|
||||
longitude: z.number().min(-180).max(180),
|
||||
latitude: z.number().min(-90).max(90),
|
||||
});
|
||||
|
||||
export const airQualityRouter = createTRPCRouter({
|
||||
atLocation: publicProcedure
|
||||
.meta({
|
||||
mcp: {
|
||||
enabled: true,
|
||||
description:
|
||||
"Get current and forecast air quality, UV, pollutant, and pollen data for geographic coordinates. REQUIRED: latitude (-90 to 90) and longitude (-180 to 180).",
|
||||
},
|
||||
})
|
||||
.input(atLocationInput)
|
||||
.query(async ({ input }) => {
|
||||
if (env.NO_EXTERNAL_CONNECTION) return null;
|
||||
|
||||
const handler = airQualityRequestHandler.handler(input);
|
||||
return await handler.getDataAsync().then((result) => result.data);
|
||||
}),
|
||||
});
|
||||
@@ -13,7 +13,6 @@ export const widgetRouter = createTRPCRouter({
|
||||
bazarr: lazy(() => import("./bazarr").then((mod) => mod.bazarrRouter)),
|
||||
notebook: lazy(() => import("./notebook").then((mod) => mod.notebookRouter)),
|
||||
weather: lazy(() => import("./weather").then((mod) => mod.weatherRouter)),
|
||||
airQuality: lazy(() => import("./air-quality").then((mod) => mod.airQualityRouter)),
|
||||
app: lazy(() => import("./app").then((mod) => mod.appRouter)),
|
||||
dnsHole: lazy(() => import("./dns-hole").then((mod) => mod.dnsHoleRouter)),
|
||||
smartHome: lazy(() => import("./smart-home").then((mod) => mod.smartHomeRouter)),
|
||||
|
||||
@@ -6,8 +6,8 @@ import { weatherRequestHandler } from "@homarr/request-handler/weather";
|
||||
import { createTRPCRouter, publicProcedure } from "../../trpc";
|
||||
|
||||
const atLocationInput = z.object({
|
||||
longitude: z.number().min(-180).max(180),
|
||||
latitude: z.number().min(-90).max(90),
|
||||
longitude: z.number(),
|
||||
latitude: z.number(),
|
||||
});
|
||||
|
||||
export const weatherRouter = createTRPCRouter({
|
||||
|
||||
@@ -9,7 +9,6 @@ vi.mock("@homarr/auth", () => ({}));
|
||||
|
||||
const MCP_TOOL_ALLOWLIST = {
|
||||
query: [
|
||||
"airQuality_atLocation",
|
||||
"apiKeys_getAll",
|
||||
"app_all",
|
||||
"app_byId",
|
||||
|
||||
@@ -336,10 +336,6 @@ export type HomarrDocumentationPath =
|
||||
| "/docs/integrations/whats-up-docker"
|
||||
| "/docs/widgets/clock"
|
||||
| "/docs/widgets/weather"
|
||||
| "/docs/widgets/today"
|
||||
| "/docs/widgets/air-quality"
|
||||
| "/docs/widgets/countdown"
|
||||
| "/docs/widgets/timer"
|
||||
| "/docs/widgets/app"
|
||||
| "/docs/widgets/iframe"
|
||||
| "/docs/widgets/video"
|
||||
|
||||
@@ -3,10 +3,6 @@ import type { WidgetKind } from "../widget";
|
||||
export const widgetDocSlugs: Record<WidgetKind, string | null> = {
|
||||
clock: "clock",
|
||||
weather: "weather",
|
||||
today: "today",
|
||||
airQuality: "air-quality",
|
||||
countdown: "countdown",
|
||||
timer: "timer",
|
||||
app: "app",
|
||||
iframe: "iframe",
|
||||
video: "video",
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
export const widgetKinds = [
|
||||
"clock",
|
||||
"weather",
|
||||
"today",
|
||||
"airQuality",
|
||||
"countdown",
|
||||
"timer",
|
||||
"app",
|
||||
"iframe",
|
||||
"video",
|
||||
@@ -63,10 +59,6 @@ export const widgetKinds = [
|
||||
export type WidgetKind = (typeof widgetKinds)[number];
|
||||
|
||||
export const widgetDefaultSizes: Partial<Record<WidgetKind, { width: number; height: number }>> = {
|
||||
today: { width: 2, height: 1 },
|
||||
airQuality: { width: 2, height: 1 },
|
||||
countdown: { width: 2, height: 1 },
|
||||
timer: { width: 2, height: 1 },
|
||||
uptimeKuma: { width: 2, height: 3 },
|
||||
audioStats: { width: 2, height: 2 },
|
||||
paperlessNgx: { width: 2, height: 2 },
|
||||
|
||||
@@ -112,15 +112,13 @@ export class EmbyIntegration extends Integration implements IMediaServerIntegrat
|
||||
let currentlyPlaying: StreamSession["currentlyPlaying"] | null = null;
|
||||
|
||||
if (sessionInfo.NowPlayingItem) {
|
||||
const isEpisode = sessionInfo.NowPlayingItem.Type === BaseItemKind.Episode;
|
||||
|
||||
currentlyPlaying = {
|
||||
type: convertJellyfinType(sessionInfo.NowPlayingItem.Type),
|
||||
name: sessionInfo.NowPlayingItem.SeriesName ?? sessionInfo.NowPlayingItem.Name ?? "",
|
||||
seasonName: sessionInfo.NowPlayingItem.SeasonName ?? "",
|
||||
seasonNumber: isEpisode ? (sessionInfo.NowPlayingItem.ParentIndexNumber ?? null) : null,
|
||||
episodeName: isEpisode ? sessionInfo.NowPlayingItem.EpisodeTitle : null,
|
||||
episodeNumber: isEpisode ? (sessionInfo.NowPlayingItem.IndexNumber ?? null) : null,
|
||||
seasonNumber: sessionInfo.NowPlayingItem.ParentIndexNumber ?? null,
|
||||
episodeName: sessionInfo.NowPlayingItem.EpisodeTitle,
|
||||
episodeNumber: sessionInfo.NowPlayingItem.IndexNumber ?? null,
|
||||
albumName: sessionInfo.NowPlayingItem.Album ?? "",
|
||||
episodeCount: sessionInfo.NowPlayingItem.EpisodeCount,
|
||||
playback: {
|
||||
|
||||
@@ -1,65 +0,0 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import { extractHost, parseLocation } from "./jellyfin-integration";
|
||||
|
||||
describe("extractHost", () => {
|
||||
test("strips the port from an IPv4 endpoint", () => {
|
||||
expect(extractHost("192.168.1.100:54321")).toBe("192.168.1.100");
|
||||
});
|
||||
|
||||
test("returns an IPv4 address unchanged when there's no port", () => {
|
||||
expect(extractHost("8.8.8.8")).toBe("8.8.8.8");
|
||||
});
|
||||
|
||||
test("strips brackets and the port from a bracketed IPv6 endpoint", () => {
|
||||
expect(extractHost("[::1]:8096")).toBe("::1");
|
||||
});
|
||||
|
||||
test("returns a bare IPv6 address unchanged when there's no port", () => {
|
||||
expect(extractHost("::1")).toBe("::1");
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseLocation", () => {
|
||||
test("returns null when there's no endpoint to classify", () => {
|
||||
expect(parseLocation(null)).toBeNull();
|
||||
expect(parseLocation(undefined)).toBeNull();
|
||||
expect(parseLocation("")).toBeNull();
|
||||
});
|
||||
|
||||
test("returns null for a value that isn't an IP", () => {
|
||||
expect(parseLocation("not-an-ip:1234")).toBeNull();
|
||||
});
|
||||
|
||||
test("classifies private IPv4 ranges as lan", () => {
|
||||
expect(parseLocation("192.168.1.100:54321")).toBe("lan");
|
||||
expect(parseLocation("10.0.0.5:1234")).toBe("lan");
|
||||
expect(parseLocation("172.16.5.5:1234")).toBe("lan");
|
||||
expect(parseLocation("127.0.0.1:8096")).toBe("lan");
|
||||
});
|
||||
|
||||
test("classifies a public IPv4 address as wan", () => {
|
||||
expect(parseLocation("8.8.8.8:1234")).toBe("wan");
|
||||
});
|
||||
|
||||
test("classifies IPv6 loopback and unique-local addresses as lan", () => {
|
||||
expect(parseLocation("[::1]:8096")).toBe("lan");
|
||||
expect(parseLocation("[fd12:3456:789a::1]:8096")).toBe("lan");
|
||||
});
|
||||
|
||||
test("classifies a public IPv6 address as wan", () => {
|
||||
expect(parseLocation("[2606:4700:4700::1111]:8096")).toBe("wan");
|
||||
});
|
||||
|
||||
test("unwraps an IPv4-mapped IPv6 address before classifying it", () => {
|
||||
expect(parseLocation("[::ffff:192.168.1.5]:8096")).toBe("lan");
|
||||
expect(parseLocation("[::ffff:8.8.8.8]:8096")).toBe("wan");
|
||||
});
|
||||
|
||||
test("classifies link-local addresses as lan", () => {
|
||||
// Link-local traffic can't traverse a router, so it's always LAN even though
|
||||
// it isn't a private range in the traditional (RFC 1918 / ULA) sense.
|
||||
expect(parseLocation("169.254.1.5:8096")).toBe("lan");
|
||||
expect(parseLocation("[fe80::1]:8096")).toBe("lan");
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,3 @@
|
||||
import { BlockList, isIP } from "node:net";
|
||||
import { Jellyfin } from "@jellyfin/sdk";
|
||||
import { BaseItemKind } from "@jellyfin/sdk/lib/generated-client/models";
|
||||
import { getSessionApi } from "@jellyfin/sdk/lib/utils/api/session-api";
|
||||
@@ -22,42 +21,6 @@ function ticksToMs(ticks: number | null | undefined): number | null {
|
||||
return ticks ? Math.round(ticks / 10_000) : null;
|
||||
}
|
||||
|
||||
// Unlike Plex, Jellyfin doesn't report a session's network location directly - only the
|
||||
// client's RemoteEndPoint (an IP, optionally with a port). Classify it ourselves.
|
||||
const privateAddresses = new BlockList();
|
||||
privateAddresses.addSubnet("10.0.0.0", 8, "ipv4");
|
||||
privateAddresses.addSubnet("172.16.0.0", 12, "ipv4");
|
||||
privateAddresses.addSubnet("192.168.0.0", 16, "ipv4");
|
||||
privateAddresses.addSubnet("127.0.0.0", 8, "ipv4");
|
||||
privateAddresses.addSubnet("169.254.0.0", 16, "ipv4");
|
||||
privateAddresses.addSubnet("fc00::", 7, "ipv6");
|
||||
privateAddresses.addSubnet("fe80::", 10, "ipv6");
|
||||
privateAddresses.addAddress("::1", "ipv6");
|
||||
|
||||
export function extractHost(remoteEndPoint: string): string {
|
||||
if (remoteEndPoint.startsWith("[")) {
|
||||
const end = remoteEndPoint.indexOf("]");
|
||||
return end === -1 ? remoteEndPoint : remoteEndPoint.slice(1, end);
|
||||
}
|
||||
// A bare IPv6 address (no brackets, no port) has more than one colon.
|
||||
const isIPv4WithPort = remoteEndPoint.split(":").length === 2;
|
||||
return isIPv4WithPort ? remoteEndPoint.slice(0, remoteEndPoint.lastIndexOf(":")) : remoteEndPoint;
|
||||
}
|
||||
|
||||
export function parseLocation(remoteEndPoint: string | null | undefined): "lan" | "wan" | null {
|
||||
if (!remoteEndPoint) return null;
|
||||
let host = extractHost(remoteEndPoint);
|
||||
let family = isIP(host);
|
||||
// A dual-stack server can report an IPv4 client as an IPv4-mapped IPv6 address
|
||||
// (e.g. "::ffff:192.168.1.5") - unwrap it so the IPv4 private ranges still apply.
|
||||
if (family === 6 && host.toLowerCase().startsWith("::ffff:") && isIP(host.slice(7)) === 4) {
|
||||
host = host.slice(7);
|
||||
family = 4;
|
||||
}
|
||||
if (!family) return null;
|
||||
return privateAddresses.check(host, family === 4 ? "ipv4" : "ipv6") ? "lan" : "wan";
|
||||
}
|
||||
|
||||
@HandleIntegrationErrors([integrationAxiosHttpErrorHandler])
|
||||
export class JellyfinIntegration extends Integration implements IMediaServerIntegration, IMediaReleasesIntegration {
|
||||
private readonly jellyfin: Jellyfin = new Jellyfin({
|
||||
@@ -93,27 +56,17 @@ export class JellyfinIntegration extends Integration implements IMediaServerInte
|
||||
if (sessionInfo.NowPlayingItem) {
|
||||
const positionMs = ticksToMs(sessionInfo.PlayState?.PositionTicks);
|
||||
const durationMs = ticksToMs(sessionInfo.NowPlayingItem.RunTimeTicks);
|
||||
// Jellyfin only reliably fills in MediaSources[].Bitrate for a transcoding session -
|
||||
// /Sessions has no `fields` selector to force it, so fall back to summing the individual
|
||||
// media streams' own bitrates (populated from the source file's metadata) for direct play.
|
||||
const mediaStreamsBitrateBps = sessionInfo.NowPlayingItem.MediaStreams?.reduce(
|
||||
(sum, stream) => sum + (stream.BitRate ?? 0),
|
||||
0,
|
||||
);
|
||||
const bitrateBps =
|
||||
sessionInfo.TranscodingInfo?.Bitrate ??
|
||||
sessionInfo.NowPlayingItem.MediaSources?.[0]?.Bitrate ??
|
||||
(mediaStreamsBitrateBps || null);
|
||||
sessionInfo.TranscodingInfo?.Bitrate ?? sessionInfo.NowPlayingItem.MediaSources?.[0]?.Bitrate ?? null;
|
||||
const bitrateKbps = bitrateBps !== null ? Math.round(bitrateBps / 1000) : null;
|
||||
const isEpisode = sessionInfo.NowPlayingItem.Type === BaseItemKind.Episode;
|
||||
|
||||
currentlyPlaying = {
|
||||
type: convertJellyfinType(sessionInfo.NowPlayingItem.Type),
|
||||
name: sessionInfo.NowPlayingItem.SeriesName ?? sessionInfo.NowPlayingItem.Name ?? "",
|
||||
seasonName: sessionInfo.NowPlayingItem.SeasonName ?? "",
|
||||
seasonNumber: isEpisode ? (sessionInfo.NowPlayingItem.ParentIndexNumber ?? null) : null,
|
||||
episodeName: isEpisode ? sessionInfo.NowPlayingItem.EpisodeTitle : null,
|
||||
episodeNumber: isEpisode ? (sessionInfo.NowPlayingItem.IndexNumber ?? null) : null,
|
||||
seasonNumber: sessionInfo.NowPlayingItem.ParentIndexNumber ?? null,
|
||||
episodeName: sessionInfo.NowPlayingItem.EpisodeTitle,
|
||||
episodeNumber: sessionInfo.NowPlayingItem.IndexNumber ?? null,
|
||||
albumName: sessionInfo.NowPlayingItem.Album ?? "",
|
||||
episodeCount: sessionInfo.NowPlayingItem.EpisodeCount,
|
||||
playback: {
|
||||
@@ -121,7 +74,7 @@ export class JellyfinIntegration extends Integration implements IMediaServerInte
|
||||
positionMs,
|
||||
durationMs,
|
||||
},
|
||||
location: parseLocation(sessionInfo.RemoteEndPoint),
|
||||
location: null,
|
||||
metadata: {
|
||||
video: {
|
||||
resolution:
|
||||
|
||||
@@ -115,9 +115,9 @@ export class PlexIntegration extends Integration implements IMediaServerIntegrat
|
||||
type: mediaElement.$.live === "1" ? "tv" : PlexIntegration.getCurrentlyPlayingType(mediaElement.$.type),
|
||||
name: mediaElement.$.grandparentTitle ?? mediaElement.$.title ?? "Unknown",
|
||||
seasonName: mediaElement.$.parentTitle,
|
||||
seasonNumber: mediaElement.$.type === "episode" ? parseOptionalNumber(mediaElement.$.parentIndex) : null,
|
||||
episodeName: mediaElement.$.type === "episode" ? (mediaElement.$.title ?? null) : null,
|
||||
episodeNumber: mediaElement.$.type === "episode" ? parseOptionalNumber(mediaElement.$.index) : null,
|
||||
seasonNumber: parseOptionalNumber(mediaElement.$.parentIndex),
|
||||
episodeName: mediaElement.$.title ?? null,
|
||||
episodeNumber: parseOptionalNumber(mediaElement.$.index),
|
||||
albumName: mediaElement.$.type === "track" ? (mediaElement.$.parentTitle ?? null) : null,
|
||||
episodeCount: parseOptionalNumber(mediaElement.$.index),
|
||||
playback: {
|
||||
|
||||
@@ -8,35 +8,35 @@ import { useZodForm } from "@homarr/form";
|
||||
import { createModal } from "@homarr/modals";
|
||||
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import { appHrefSchema } from "@homarr/validation/app";
|
||||
|
||||
interface AddDockerAppToHomarrProps {
|
||||
selectedContainers: RouterOutputs["docker"]["getContainers"]["containers"];
|
||||
initialUrls?: (string | null)[];
|
||||
initialUrls?: string[];
|
||||
}
|
||||
|
||||
const formSchema = z.object({
|
||||
containerUrls: z.array(appHrefSchema),
|
||||
});
|
||||
|
||||
export const AddDockerAppToHomarrModal = createModal<AddDockerAppToHomarrProps>(({ actions, innerProps }) => {
|
||||
const t = useI18n();
|
||||
const form = useZodForm(formSchema, {
|
||||
initialValues: {
|
||||
containerUrls: innerProps.selectedContainers.map((container, index) => {
|
||||
const initialUrl = innerProps.initialUrls?.[index];
|
||||
if (initialUrl !== undefined) return initialUrl;
|
||||
const form = useZodForm(
|
||||
z.object({
|
||||
containerUrls: z.array(z.string().url().nullable()),
|
||||
}),
|
||||
{
|
||||
initialValues: {
|
||||
containerUrls: innerProps.selectedContainers.map((container, index) => {
|
||||
const initialUrl = innerProps.initialUrls?.[index];
|
||||
if (initialUrl) return initialUrl;
|
||||
|
||||
const candidates = buildDockerServiceUrlCandidates({
|
||||
containerName: container.name,
|
||||
endpointHost: container.host,
|
||||
ports: container.ports,
|
||||
}).filter(({ url }) => url.length > 0);
|
||||
const candidates = buildDockerServiceUrlCandidates({
|
||||
containerName: container.name,
|
||||
endpointHost: container.host,
|
||||
ports: container.ports,
|
||||
}).filter(({ url }) => url.length > 0);
|
||||
|
||||
return candidates.find(({ scopes }) => scopes.includes("browser"))?.url ?? candidates[0]?.url ?? null;
|
||||
}),
|
||||
return candidates.find(({ scopes }) => scopes.includes("browser"))?.url ?? candidates[0]?.url ?? null;
|
||||
}),
|
||||
},
|
||||
},
|
||||
});
|
||||
);
|
||||
const { mutate, isPending } = clientApi.app.createMany.useMutation({
|
||||
onSuccess() {
|
||||
actions.closeModal();
|
||||
@@ -52,13 +52,13 @@ export const AddDockerAppToHomarrModal = createModal<AddDockerAppToHomarrProps>(
|
||||
});
|
||||
},
|
||||
});
|
||||
const handleSubmit = ({ containerUrls }: z.infer<typeof formSchema>) => {
|
||||
const handleSubmit = () => {
|
||||
mutate(
|
||||
innerProps.selectedContainers.map((container, index) => ({
|
||||
name: container.name,
|
||||
iconUrl: container.iconUrl,
|
||||
description: null,
|
||||
href: containerUrls[index] || null,
|
||||
href: form.values.containerUrls[index] ?? null,
|
||||
pingUrl: null,
|
||||
})),
|
||||
);
|
||||
@@ -68,31 +68,28 @@ export const AddDockerAppToHomarrModal = createModal<AddDockerAppToHomarrProps>(
|
||||
<LoadingOverlay visible={isPending} />
|
||||
<Stack>
|
||||
<List spacing={"xs"}>
|
||||
{innerProps.selectedContainers.map((container, index) => {
|
||||
const inputProps = form.getInputProps(`containerUrls.${index}`);
|
||||
return (
|
||||
<List.Item
|
||||
styles={{ itemWrapper: { width: "100%" }, itemLabel: { flex: 1 } }}
|
||||
icon={
|
||||
<Avatar
|
||||
variant="outline"
|
||||
radius={container.iconUrl ? "sm" : "md"}
|
||||
size={30}
|
||||
styles={{ image: { objectFit: "contain" } }}
|
||||
src={container.iconUrl}
|
||||
>
|
||||
{container.name.at(0)?.toUpperCase()}
|
||||
</Avatar>
|
||||
}
|
||||
key={container.id}
|
||||
>
|
||||
<Group justify="space-between" wrap={"nowrap"}>
|
||||
<Text lineClamp={1}>{container.name}</Text>
|
||||
<TextInput {...inputProps} value={inputProps.value ?? ""} />
|
||||
</Group>
|
||||
</List.Item>
|
||||
);
|
||||
})}
|
||||
{innerProps.selectedContainers.map((container, index) => (
|
||||
<List.Item
|
||||
styles={{ itemWrapper: { width: "100%" }, itemLabel: { flex: 1 } }}
|
||||
icon={
|
||||
<Avatar
|
||||
variant="outline"
|
||||
radius={container.iconUrl ? "sm" : "md"}
|
||||
size={30}
|
||||
styles={{ image: { objectFit: "contain" } }}
|
||||
src={container.iconUrl}
|
||||
>
|
||||
{container.name.at(0)?.toUpperCase()}
|
||||
</Avatar>
|
||||
}
|
||||
key={container.id}
|
||||
>
|
||||
<Group justify="space-between" wrap={"nowrap"}>
|
||||
<Text lineClamp={1}>{container.name}</Text>
|
||||
<TextInput {...form.getInputProps(`containerUrls.${index}`)} />
|
||||
</Group>
|
||||
</List.Item>
|
||||
))}
|
||||
</List>
|
||||
<Group justify="end">
|
||||
<Button onClick={actions.closeModal} variant="light" px={"xl"}>
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
export { OnboardingAuthShell } from "./onboarding-auth-shell";
|
||||
export { OnboardingStudio } from "./onboarding-studio";
|
||||
export { normalizeServiceUrl } from "./discovery-selection";
|
||||
export { ServiceUrlTemplate } from "./service-url-template";
|
||||
export type { OnboardingEnvironment, OnboardingStudioProps } from "./types";
|
||||
@@ -358,7 +358,6 @@
|
||||
display: flex;
|
||||
width: max-content;
|
||||
min-width: 100%;
|
||||
margin: 0;
|
||||
padding: 0.2rem;
|
||||
border-radius: var(--mantine-radius-md);
|
||||
background: var(--mantine-color-default);
|
||||
|
||||
@@ -1,106 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import type { ReactNode } from "react";
|
||||
import { useRef, useState } from "react";
|
||||
import { FloatingIndicator, Stack, TextInput, UnstyledButton } from "@mantine/core";
|
||||
|
||||
import type { UrlTemplateMode } from "@homarr/definitions";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import { useOnboardingSounds } from "./use-onboarding-sounds";
|
||||
import classes from "./onboarding-studio.module.css";
|
||||
|
||||
interface FloatingControlProps<T extends string> {
|
||||
value: T;
|
||||
onChange: (value: T) => void;
|
||||
options: readonly { value: T; label: ReactNode }[];
|
||||
ariaLabel: string;
|
||||
}
|
||||
|
||||
export const OnboardingFloatingControl = <T extends string>({
|
||||
value,
|
||||
onChange,
|
||||
options,
|
||||
ariaLabel,
|
||||
}: FloatingControlProps<T>) => {
|
||||
const [rootRef, setRootRef] = useState<HTMLFieldSetElement | null>(null);
|
||||
const controlRefs = useRef<Record<string, HTMLButtonElement | null>>({});
|
||||
const sounds = useOnboardingSounds();
|
||||
|
||||
return (
|
||||
<div className={classes.floatingControlScroller}>
|
||||
<fieldset ref={setRootRef} className={classes.floatingControlRoot} aria-label={ariaLabel}>
|
||||
<FloatingIndicator
|
||||
target={controlRefs.current[value] ?? null}
|
||||
parent={rootRef}
|
||||
className={classes.floatingControlIndicator}
|
||||
/>
|
||||
{options.map((option) => {
|
||||
const selected = value === option.value;
|
||||
return (
|
||||
<UnstyledButton
|
||||
key={option.value}
|
||||
ref={(node) => {
|
||||
controlRefs.current[option.value] = node;
|
||||
}}
|
||||
type="button"
|
||||
className={classes.floatingControl}
|
||||
data-active={selected}
|
||||
aria-pressed={selected}
|
||||
onClick={() => {
|
||||
sounds.click();
|
||||
onChange(option.value);
|
||||
}}
|
||||
>
|
||||
{option.label}
|
||||
</UnstyledButton>
|
||||
);
|
||||
})}
|
||||
</fieldset>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
interface ServiceUrlTemplateProps {
|
||||
serverOrigin: string;
|
||||
onServerOriginChange: (value: string) => void;
|
||||
mode: UrlTemplateMode;
|
||||
onModeChange: (value: UrlTemplateMode) => void;
|
||||
readOnly?: boolean;
|
||||
required?: boolean;
|
||||
}
|
||||
|
||||
export const ServiceUrlTemplate = ({
|
||||
serverOrigin,
|
||||
onServerOriginChange,
|
||||
mode,
|
||||
onModeChange,
|
||||
readOnly,
|
||||
required,
|
||||
}: ServiceUrlTemplateProps) => {
|
||||
const t = useScopedI18n("common.serviceUrlTemplate");
|
||||
|
||||
return (
|
||||
<Stack gap="sm">
|
||||
<TextInput
|
||||
label={t("serverTitle")}
|
||||
placeholder="home.lan · 192.168.1.10 · https://homarr.example.com"
|
||||
value={serverOrigin}
|
||||
onChange={(event) => onServerOriginChange(event.currentTarget.value)}
|
||||
readOnly={readOnly}
|
||||
required={required}
|
||||
withAsterisk={required}
|
||||
/>
|
||||
<OnboardingFloatingControl
|
||||
ariaLabel={t("urlModeLabel")}
|
||||
value={mode}
|
||||
onChange={onModeChange}
|
||||
options={[
|
||||
{ value: "hostPort", label: t("hostPort") },
|
||||
{ value: "subdomain", label: t("subdomain") },
|
||||
{ value: "path", label: t("path") },
|
||||
]}
|
||||
/>
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
ColorSwatch,
|
||||
CopyButton,
|
||||
Fieldset,
|
||||
FloatingIndicator,
|
||||
Group,
|
||||
Paper,
|
||||
PasswordInput,
|
||||
@@ -98,7 +99,6 @@ import type { OnboardingStudioProps } from "./types";
|
||||
import { getBoardValidationErrors } from "./board-validation";
|
||||
import { OnboardingBackdrop } from "./onboarding-backdrop";
|
||||
import { OnboardingWordmark } from "./onboarding-wordmark";
|
||||
import { OnboardingFloatingControl, ServiceUrlTemplate } from "./service-url-template";
|
||||
import { useOnboardingSounds } from "./use-onboarding-sounds";
|
||||
import {
|
||||
normalizeServiceUrl,
|
||||
@@ -152,6 +152,57 @@ const initialSecondaryColor = "#fd7e14";
|
||||
const emptyDiscoveredIntegrations: DockerDiscoveryData["integrations"] = [];
|
||||
const emptyDiscoveredApps: DockerDiscoveryData["apps"] = [];
|
||||
|
||||
interface OnboardingFloatingControlProps<T extends string> {
|
||||
value: T;
|
||||
onChange: (value: T) => void;
|
||||
options: readonly { value: T; label: ReactNode }[];
|
||||
ariaLabel: string;
|
||||
}
|
||||
|
||||
const OnboardingFloatingControl = <T extends string>({
|
||||
value,
|
||||
onChange,
|
||||
options,
|
||||
ariaLabel,
|
||||
}: OnboardingFloatingControlProps<T>) => {
|
||||
const [rootRef, setRootRef] = useState<HTMLDivElement | null>(null);
|
||||
const controlRefs = useRef<Record<string, HTMLButtonElement | null>>({});
|
||||
const sounds = useOnboardingSounds();
|
||||
|
||||
return (
|
||||
<div className={classes.floatingControlScroller}>
|
||||
<div ref={setRootRef} className={classes.floatingControlRoot} role="group" aria-label={ariaLabel}>
|
||||
<FloatingIndicator
|
||||
target={controlRefs.current[value] ?? null}
|
||||
parent={rootRef}
|
||||
className={classes.floatingControlIndicator}
|
||||
/>
|
||||
{options.map((option) => {
|
||||
const selected = value === option.value;
|
||||
return (
|
||||
<UnstyledButton
|
||||
key={option.value}
|
||||
ref={(node) => {
|
||||
controlRefs.current[option.value] = node;
|
||||
}}
|
||||
type="button"
|
||||
className={classes.floatingControl}
|
||||
data-active={selected}
|
||||
aria-pressed={selected}
|
||||
onClick={() => {
|
||||
sounds.click();
|
||||
onChange(option.value);
|
||||
}}
|
||||
>
|
||||
{option.label}
|
||||
</UnstyledButton>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export const SetupStudio = ({ environment, assistantConfiguration }: OnboardingStudioProps) => {
|
||||
const t = useScopedI18n("init.studio");
|
||||
const tCommon = useScopedI18n("common.action");
|
||||
@@ -873,13 +924,24 @@ const Essentials = (props: StudioSectionProps) => {
|
||||
<Alert variant="light" icon={<IconInfoCircle size={18} />} my="xs">
|
||||
{t("serverOriginHelp")}
|
||||
</Alert>
|
||||
<ServiceUrlTemplate
|
||||
serverOrigin={props.serverOrigin}
|
||||
onServerOriginChange={props.setServerOrigin}
|
||||
mode={props.urlMode}
|
||||
onModeChange={props.setUrlMode}
|
||||
<TextInput
|
||||
label={t("serverTitle")}
|
||||
placeholder="home.lan · 192.168.1.10 · https://homarr.example.com"
|
||||
value={props.serverOrigin}
|
||||
onChange={(event) => props.setServerOrigin(event.currentTarget.value)}
|
||||
readOnly={!isHydrated}
|
||||
required
|
||||
withAsterisk
|
||||
/>
|
||||
<OnboardingFloatingControl
|
||||
ariaLabel={t("urlModeLabel")}
|
||||
value={props.urlMode}
|
||||
onChange={props.setUrlMode}
|
||||
options={[
|
||||
{ value: "hostPort", label: t("hostPort") },
|
||||
{ value: "subdomain", label: t("subdomain") },
|
||||
{ value: "path", label: t("path") },
|
||||
]}
|
||||
/>
|
||||
{props.serverOrigin ? (
|
||||
<Code block>{buildIntegrationUrl("sonarr", props.serverOrigin, props.urlMode)}</Code>
|
||||
|
||||
@@ -1,101 +0,0 @@
|
||||
import { Response } from "undici";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { fetchWithTrustedCertificatesAsync } from "@homarr/core/infrastructure/http";
|
||||
|
||||
import { airQualityRequestHandler } from "./air-quality";
|
||||
|
||||
vi.mock("@homarr/core/infrastructure/http", () => ({
|
||||
fetchWithTrustedCertificatesAsync: vi.fn(),
|
||||
}));
|
||||
|
||||
const mockFetch = vi.mocked(fetchWithTrustedCertificatesAsync);
|
||||
|
||||
const makeAirQualityResponse = () => {
|
||||
const times = ["2026-07-01T00:00", "2026-07-01T01:00", "2026-07-02T00:00"];
|
||||
const values = [10, 20, 30];
|
||||
const fields = [
|
||||
"european_aqi",
|
||||
"us_aqi",
|
||||
"uv_index",
|
||||
"pm10",
|
||||
"pm2_5",
|
||||
"carbon_monoxide",
|
||||
"nitrogen_dioxide",
|
||||
"sulphur_dioxide",
|
||||
"ozone",
|
||||
"european_aqi_pm2_5",
|
||||
"european_aqi_pm10",
|
||||
"european_aqi_nitrogen_dioxide",
|
||||
"european_aqi_ozone",
|
||||
"european_aqi_sulphur_dioxide",
|
||||
"us_aqi_pm2_5",
|
||||
"us_aqi_pm10",
|
||||
"us_aqi_nitrogen_dioxide",
|
||||
"us_aqi_carbon_monoxide",
|
||||
"us_aqi_ozone",
|
||||
"us_aqi_sulphur_dioxide",
|
||||
"alder_pollen",
|
||||
"birch_pollen",
|
||||
"grass_pollen",
|
||||
"mugwort_pollen",
|
||||
"olive_pollen",
|
||||
"ragweed_pollen",
|
||||
] as const;
|
||||
|
||||
return {
|
||||
timezone: "Europe/Berlin",
|
||||
utc_offset_seconds: 7200,
|
||||
current: {
|
||||
time: "2026-07-01T12:00",
|
||||
...Object.fromEntries(fields.map((field) => [field, field === "ragweed_pollen" ? null : 12])),
|
||||
},
|
||||
hourly: {
|
||||
time: times,
|
||||
...Object.fromEntries(fields.map((field) => [field, field === "ragweed_pollen" ? [null, null, null] : values])),
|
||||
},
|
||||
fields,
|
||||
};
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
airQualityRequestHandler.invalidateCache();
|
||||
});
|
||||
|
||||
describe("air quality request handler", () => {
|
||||
it("requests and normalizes the full useful forecast field set", async () => {
|
||||
const fixture = makeAirQualityResponse();
|
||||
mockFetch.mockResolvedValue(new Response(JSON.stringify(fixture)));
|
||||
|
||||
const first = await airQualityRequestHandler.handler({ latitude: 48.85, longitude: 2.35 }).getDataAsync();
|
||||
const second = await airQualityRequestHandler.handler({ latitude: 48.85, longitude: 2.35 }).getDataAsync();
|
||||
|
||||
expect(first.data.current.observedAt).toBe("2026-07-01T10:00:00.000Z");
|
||||
expect(first.data.current.pollutants.pm2_5).toBe(12);
|
||||
expect(first.data.current.pollen.ragweed).toBeNull();
|
||||
expect(first.data.hourly[0]?.observedAt).toBe("2026-06-30T22:00:00.000Z");
|
||||
expect(first.data.daily).toEqual([
|
||||
{ date: "2026-07-01", europeanAqiMax: 20, usAqiMax: 20, uvIndexMax: 20, pm2_5Max: 20, pm10Max: 20 },
|
||||
{ date: "2026-07-02", europeanAqiMax: 30, usAqiMax: 30, uvIndexMax: 30, pm2_5Max: 30, pm10Max: 30 },
|
||||
]);
|
||||
expect(second.data).toStrictEqual(first.data);
|
||||
expect(mockFetch).toHaveBeenCalledOnce();
|
||||
|
||||
const requestUrl = new URL(String(mockFetch.mock.calls[0]?.[0]));
|
||||
expect(requestUrl.origin).toBe("https://air-quality-api.open-meteo.com");
|
||||
expect(requestUrl.searchParams.get("forecast_days")).toBe("7");
|
||||
expect(requestUrl.searchParams.get("timezone")).toBe("auto");
|
||||
expect(requestUrl.searchParams.get("current")).toContain("european_aqi_pm2_5");
|
||||
expect(requestUrl.searchParams.get("hourly")).toContain("us_aqi_carbon_monoxide");
|
||||
expect(requestUrl.searchParams.get("hourly")).toContain("ragweed_pollen");
|
||||
});
|
||||
|
||||
it("rejects unsuccessful Open-Meteo responses", async () => {
|
||||
mockFetch.mockResolvedValue(new Response("unavailable", { status: 503 }));
|
||||
|
||||
await expect(
|
||||
airQualityRequestHandler.handler({ latitude: 48.85, longitude: 2.35 }).getDataAsync(),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -1,283 +0,0 @@
|
||||
import dayjs from "dayjs";
|
||||
import timezone from "dayjs/plugin/timezone";
|
||||
import utc from "dayjs/plugin/utc";
|
||||
import { z } from "zod";
|
||||
|
||||
import { ResponseError } from "@homarr/common/server";
|
||||
import { fetchWithTrustedCertificatesAsync } from "@homarr/core/infrastructure/http";
|
||||
import { withTimeoutAsync } from "@homarr/core/infrastructure/http/timeout";
|
||||
|
||||
import { createWidgetRequestHandler } from "./lib/widget-request-handler";
|
||||
|
||||
dayjs.extend(utc);
|
||||
dayjs.extend(timezone);
|
||||
|
||||
const FORECAST_DAYS = 7;
|
||||
|
||||
const requestedVariables = [
|
||||
"european_aqi",
|
||||
"us_aqi",
|
||||
"uv_index",
|
||||
"pm10",
|
||||
"pm2_5",
|
||||
"carbon_monoxide",
|
||||
"nitrogen_dioxide",
|
||||
"sulphur_dioxide",
|
||||
"ozone",
|
||||
"european_aqi_pm2_5",
|
||||
"european_aqi_pm10",
|
||||
"european_aqi_nitrogen_dioxide",
|
||||
"european_aqi_ozone",
|
||||
"european_aqi_sulphur_dioxide",
|
||||
"us_aqi_pm2_5",
|
||||
"us_aqi_pm10",
|
||||
"us_aqi_nitrogen_dioxide",
|
||||
"us_aqi_carbon_monoxide",
|
||||
"us_aqi_ozone",
|
||||
"us_aqi_sulphur_dioxide",
|
||||
"alder_pollen",
|
||||
"birch_pollen",
|
||||
"grass_pollen",
|
||||
"mugwort_pollen",
|
||||
"olive_pollen",
|
||||
"ragweed_pollen",
|
||||
] as const;
|
||||
|
||||
export const airQualityRequestHandler = createWidgetRequestHandler({
|
||||
cacheTtlMs: 15 * 60 * 1000,
|
||||
fallbackToStaleOnError: true,
|
||||
staleIfErrorTtlMs: 24 * 60 * 60 * 1000,
|
||||
async requestAsync(input: { latitude: number; longitude: number }) {
|
||||
const url = new URL("https://air-quality-api.open-meteo.com/v1/air-quality");
|
||||
url.searchParams.set("latitude", input.latitude.toString());
|
||||
url.searchParams.set("longitude", input.longitude.toString());
|
||||
url.searchParams.set("current", requestedVariables.join(","));
|
||||
url.searchParams.set("hourly", requestedVariables.join(","));
|
||||
url.searchParams.set("forecast_days", FORECAST_DAYS.toString());
|
||||
url.searchParams.set("timezone", "auto");
|
||||
|
||||
const response = await withTimeoutAsync(async (signal) => {
|
||||
return await fetchWithTrustedCertificatesAsync(url.toString(), { signal });
|
||||
});
|
||||
if (!response.ok) throw new ResponseError(response);
|
||||
|
||||
const json: unknown = await response.json();
|
||||
const airQuality = await atLocationOutput.parseAsync(json);
|
||||
const hourly = airQuality.hourly.time.map((value, index) => {
|
||||
return normalizePoint(airQuality.hourly, index, toUtcInstant(value, airQuality.timezone));
|
||||
});
|
||||
|
||||
return {
|
||||
timezone: airQuality.timezone,
|
||||
utcOffsetSeconds: airQuality.utc_offset_seconds,
|
||||
current: normalizePoint(
|
||||
airQuality.current,
|
||||
undefined,
|
||||
toUtcInstant(airQuality.current.time, airQuality.timezone),
|
||||
),
|
||||
hourly,
|
||||
daily: getDailyMaximums(airQuality.hourly),
|
||||
} satisfies AirQuality;
|
||||
},
|
||||
});
|
||||
|
||||
const nullableNumber = z.number().nullable();
|
||||
const nullableNumberArray = z.array(nullableNumber);
|
||||
|
||||
const currentValues = z.object({
|
||||
time: z.string(),
|
||||
european_aqi: nullableNumber,
|
||||
us_aqi: nullableNumber,
|
||||
uv_index: nullableNumber,
|
||||
pm10: nullableNumber,
|
||||
pm2_5: nullableNumber,
|
||||
carbon_monoxide: nullableNumber,
|
||||
nitrogen_dioxide: nullableNumber,
|
||||
sulphur_dioxide: nullableNumber,
|
||||
ozone: nullableNumber,
|
||||
european_aqi_pm2_5: nullableNumber,
|
||||
european_aqi_pm10: nullableNumber,
|
||||
european_aqi_nitrogen_dioxide: nullableNumber,
|
||||
european_aqi_ozone: nullableNumber,
|
||||
european_aqi_sulphur_dioxide: nullableNumber,
|
||||
us_aqi_pm2_5: nullableNumber,
|
||||
us_aqi_pm10: nullableNumber,
|
||||
us_aqi_nitrogen_dioxide: nullableNumber,
|
||||
us_aqi_carbon_monoxide: nullableNumber,
|
||||
us_aqi_ozone: nullableNumber,
|
||||
us_aqi_sulphur_dioxide: nullableNumber,
|
||||
alder_pollen: nullableNumber,
|
||||
birch_pollen: nullableNumber,
|
||||
grass_pollen: nullableNumber,
|
||||
mugwort_pollen: nullableNumber,
|
||||
olive_pollen: nullableNumber,
|
||||
ragweed_pollen: nullableNumber,
|
||||
});
|
||||
|
||||
const hourlyValues = z.object({
|
||||
time: z.array(z.string()),
|
||||
european_aqi: nullableNumberArray,
|
||||
us_aqi: nullableNumberArray,
|
||||
uv_index: nullableNumberArray,
|
||||
pm10: nullableNumberArray,
|
||||
pm2_5: nullableNumberArray,
|
||||
carbon_monoxide: nullableNumberArray,
|
||||
nitrogen_dioxide: nullableNumberArray,
|
||||
sulphur_dioxide: nullableNumberArray,
|
||||
ozone: nullableNumberArray,
|
||||
european_aqi_pm2_5: nullableNumberArray,
|
||||
european_aqi_pm10: nullableNumberArray,
|
||||
european_aqi_nitrogen_dioxide: nullableNumberArray,
|
||||
european_aqi_ozone: nullableNumberArray,
|
||||
european_aqi_sulphur_dioxide: nullableNumberArray,
|
||||
us_aqi_pm2_5: nullableNumberArray,
|
||||
us_aqi_pm10: nullableNumberArray,
|
||||
us_aqi_nitrogen_dioxide: nullableNumberArray,
|
||||
us_aqi_carbon_monoxide: nullableNumberArray,
|
||||
us_aqi_ozone: nullableNumberArray,
|
||||
us_aqi_sulphur_dioxide: nullableNumberArray,
|
||||
alder_pollen: nullableNumberArray,
|
||||
birch_pollen: nullableNumberArray,
|
||||
grass_pollen: nullableNumberArray,
|
||||
mugwort_pollen: nullableNumberArray,
|
||||
olive_pollen: nullableNumberArray,
|
||||
ragweed_pollen: nullableNumberArray,
|
||||
});
|
||||
|
||||
const atLocationOutput = z.object({
|
||||
timezone: z.string().min(1),
|
||||
utc_offset_seconds: z.number(),
|
||||
current: currentValues,
|
||||
hourly: hourlyValues,
|
||||
});
|
||||
|
||||
type CurrentValues = z.infer<typeof currentValues>;
|
||||
type HourlyValues = z.infer<typeof hourlyValues>;
|
||||
|
||||
const getValue = (values: CurrentValues | HourlyValues, field: keyof Omit<CurrentValues, "time">, index?: number) => {
|
||||
const value = values[field];
|
||||
if (Array.isArray(value)) return value[index ?? 0] ?? null;
|
||||
return value;
|
||||
};
|
||||
|
||||
const normalizePoint = (
|
||||
values: CurrentValues | HourlyValues,
|
||||
index: number | undefined,
|
||||
observedAt: string,
|
||||
): AirQualityPoint => ({
|
||||
observedAt,
|
||||
europeanAqi: getValue(values, "european_aqi", index),
|
||||
usAqi: getValue(values, "us_aqi", index),
|
||||
uvIndex: getValue(values, "uv_index", index),
|
||||
pollutants: {
|
||||
pm2_5: getValue(values, "pm2_5", index),
|
||||
pm10: getValue(values, "pm10", index),
|
||||
ozone: getValue(values, "ozone", index),
|
||||
nitrogenDioxide: getValue(values, "nitrogen_dioxide", index),
|
||||
sulphurDioxide: getValue(values, "sulphur_dioxide", index),
|
||||
carbonMonoxide: getValue(values, "carbon_monoxide", index),
|
||||
},
|
||||
europeanSubIndices: {
|
||||
pm2_5: getValue(values, "european_aqi_pm2_5", index),
|
||||
pm10: getValue(values, "european_aqi_pm10", index),
|
||||
ozone: getValue(values, "european_aqi_ozone", index),
|
||||
nitrogenDioxide: getValue(values, "european_aqi_nitrogen_dioxide", index),
|
||||
sulphurDioxide: getValue(values, "european_aqi_sulphur_dioxide", index),
|
||||
carbonMonoxide: null,
|
||||
},
|
||||
usSubIndices: {
|
||||
pm2_5: getValue(values, "us_aqi_pm2_5", index),
|
||||
pm10: getValue(values, "us_aqi_pm10", index),
|
||||
ozone: getValue(values, "us_aqi_ozone", index),
|
||||
nitrogenDioxide: getValue(values, "us_aqi_nitrogen_dioxide", index),
|
||||
sulphurDioxide: getValue(values, "us_aqi_sulphur_dioxide", index),
|
||||
carbonMonoxide: getValue(values, "us_aqi_carbon_monoxide", index),
|
||||
},
|
||||
pollen: {
|
||||
alder: getValue(values, "alder_pollen", index),
|
||||
birch: getValue(values, "birch_pollen", index),
|
||||
grass: getValue(values, "grass_pollen", index),
|
||||
mugwort: getValue(values, "mugwort_pollen", index),
|
||||
olive: getValue(values, "olive_pollen", index),
|
||||
ragweed: getValue(values, "ragweed_pollen", index),
|
||||
},
|
||||
});
|
||||
|
||||
const getDailyMaximums = (hourly: HourlyValues): AirQuality["daily"] => {
|
||||
const grouped = new Map<string, AirQuality["daily"][number]>();
|
||||
|
||||
hourly.time.forEach((time, index) => {
|
||||
const date = time.slice(0, 10);
|
||||
const existing = grouped.get(date) ?? {
|
||||
date,
|
||||
europeanAqiMax: null,
|
||||
usAqiMax: null,
|
||||
uvIndexMax: null,
|
||||
pm2_5Max: null,
|
||||
pm10Max: null,
|
||||
};
|
||||
|
||||
existing.europeanAqiMax = maxNullable(existing.europeanAqiMax, hourly.european_aqi[index]);
|
||||
existing.usAqiMax = maxNullable(existing.usAqiMax, hourly.us_aqi[index]);
|
||||
existing.uvIndexMax = maxNullable(existing.uvIndexMax, hourly.uv_index[index]);
|
||||
existing.pm2_5Max = maxNullable(existing.pm2_5Max, hourly.pm2_5[index]);
|
||||
existing.pm10Max = maxNullable(existing.pm10Max, hourly.pm10[index]);
|
||||
grouped.set(date, existing);
|
||||
});
|
||||
|
||||
return Array.from(grouped.values()).slice(0, FORECAST_DAYS);
|
||||
};
|
||||
|
||||
const maxNullable = (current: number | null, candidate: number | null | undefined): number | null => {
|
||||
if (candidate === null || candidate === undefined) return current;
|
||||
if (current === null) return candidate;
|
||||
return Math.max(current, candidate);
|
||||
};
|
||||
|
||||
const toUtcInstant = (value: string, timeZone: string): string => {
|
||||
const parsed = dayjs.tz(value, timeZone);
|
||||
if (!parsed.isValid()) throw new Error(`Invalid air quality timestamp: ${value}`);
|
||||
return parsed.utc().toISOString();
|
||||
};
|
||||
|
||||
export interface AirQualityPollutants {
|
||||
pm2_5: number | null;
|
||||
pm10: number | null;
|
||||
ozone: number | null;
|
||||
nitrogenDioxide: number | null;
|
||||
sulphurDioxide: number | null;
|
||||
carbonMonoxide: number | null;
|
||||
}
|
||||
|
||||
export interface AirQualityPoint {
|
||||
observedAt: string;
|
||||
europeanAqi: number | null;
|
||||
usAqi: number | null;
|
||||
uvIndex: number | null;
|
||||
pollutants: AirQualityPollutants;
|
||||
europeanSubIndices: AirQualityPollutants;
|
||||
usSubIndices: AirQualityPollutants;
|
||||
pollen: {
|
||||
alder: number | null;
|
||||
birch: number | null;
|
||||
grass: number | null;
|
||||
mugwort: number | null;
|
||||
olive: number | null;
|
||||
ragweed: number | null;
|
||||
};
|
||||
}
|
||||
|
||||
export interface AirQuality {
|
||||
timezone: string;
|
||||
utcOffsetSeconds: number;
|
||||
current: AirQualityPoint;
|
||||
hourly: AirQualityPoint[];
|
||||
daily: {
|
||||
date: string;
|
||||
europeanAqiMax: number | null;
|
||||
usAqiMax: number | null;
|
||||
uvIndexMax: number | null;
|
||||
pm2_5Max: number | null;
|
||||
pm10Max: number | null;
|
||||
}[];
|
||||
}
|
||||
@@ -195,24 +195,9 @@ const mockContainers: {
|
||||
},
|
||||
];
|
||||
|
||||
const demoDockerEndpoint = {
|
||||
id: "demo",
|
||||
name: "Demo Docker",
|
||||
status: "available",
|
||||
kind: "docker",
|
||||
transport: "socket",
|
||||
capabilities: ["inventory"],
|
||||
source: "default",
|
||||
scope: "admin",
|
||||
} satisfies DockerEndpointStatus;
|
||||
|
||||
export const dockerContainersRequestHandler = createWidgetRequestHandler({
|
||||
async requestAsync({ endpointIds }: { endpointIds?: string[] }) {
|
||||
async requestAsync() {
|
||||
if (isDemoMode()) {
|
||||
const includesDemoEndpoint =
|
||||
endpointIds === undefined || endpointIds.length === 0 || endpointIds.includes("demo");
|
||||
if (!includesDemoEndpoint) return { containers: [], endpoints: [] };
|
||||
|
||||
return {
|
||||
containers: mockContainers.map((container) => ({
|
||||
...container,
|
||||
@@ -220,10 +205,21 @@ export const dockerContainersRequestHandler = createWidgetRequestHandler({
|
||||
endpointName: "Demo Docker",
|
||||
resourceId: `demo:${container.id}`,
|
||||
})),
|
||||
endpoints: [demoDockerEndpoint],
|
||||
endpoints: [
|
||||
{
|
||||
id: "demo",
|
||||
name: "Demo Docker",
|
||||
status: "available",
|
||||
kind: "docker",
|
||||
transport: "socket",
|
||||
capabilities: ["inventory"],
|
||||
source: "default",
|
||||
scope: "admin",
|
||||
},
|
||||
] satisfies DockerEndpointStatus[],
|
||||
};
|
||||
}
|
||||
return await getContainersWithStatsAsync(dockerWidgetEndpointTimeoutMs, endpointIds);
|
||||
return await getContainersWithStatsAsync();
|
||||
},
|
||||
});
|
||||
|
||||
@@ -308,8 +304,6 @@ export const streamContainerLogsAsync = async (
|
||||
};
|
||||
|
||||
export const getDockerEndpointsAsync = (): DockerEndpointStatus[] => {
|
||||
if (isDemoMode()) return [demoDockerEndpoint];
|
||||
|
||||
const dockerInstances = DockerSingleton.getInstances();
|
||||
const initializationFailures = DockerSingleton.getInitializationFailures();
|
||||
|
||||
@@ -337,18 +331,9 @@ export const getDockerEndpointsAsync = (): DockerEndpointStatus[] => {
|
||||
];
|
||||
};
|
||||
|
||||
export async function getContainersWithStatsAsync(
|
||||
timeoutMs = dockerWidgetEndpointTimeoutMs,
|
||||
endpointIds: string[] = [],
|
||||
) {
|
||||
const selectedEndpointIds = new Set(endpointIds);
|
||||
const includesAllEndpoints = selectedEndpointIds.size === 0;
|
||||
const dockerInstances = DockerSingleton.getInstances().filter(
|
||||
({ endpointId }) => includesAllEndpoints || selectedEndpointIds.has(endpointId),
|
||||
);
|
||||
const initializationFailures = DockerSingleton.getInitializationFailures().filter(
|
||||
({ descriptor }) => includesAllEndpoints || selectedEndpointIds.has(descriptor.id),
|
||||
);
|
||||
export async function getContainersWithStatsAsync(timeoutMs = dockerWidgetEndpointTimeoutMs) {
|
||||
const dockerInstances = DockerSingleton.getInstances();
|
||||
const initializationFailures = DockerSingleton.getInitializationFailures();
|
||||
const results = await Promise.allSettled(
|
||||
dockerInstances.map(async ({ instance, host, endpointId, endpointName }) => {
|
||||
const instanceContainers = await withDockerTimeoutAsync(
|
||||
|
||||
@@ -2,14 +2,11 @@ import { createRequestHandler } from "./request-handler";
|
||||
|
||||
interface Options<TData, TInput extends Record<string, unknown>> {
|
||||
requestAsync: (input: TInput) => Promise<TData>;
|
||||
cacheTtlMs?: number;
|
||||
fallbackToStaleOnError?: boolean;
|
||||
staleIfErrorTtlMs?: number;
|
||||
}
|
||||
|
||||
export const createWidgetRequestHandler = <TData, TInput extends Record<string, unknown>>(
|
||||
options: Options<TData, TInput>,
|
||||
) => {
|
||||
const inner = createRequestHandler<TData, TInput>(options);
|
||||
const inner = createRequestHandler<TData, TInput>({ requestAsync: options.requestAsync });
|
||||
return inner;
|
||||
};
|
||||
@@ -7,8 +7,6 @@ import { DockerSingleton } from "@homarr/docker";
|
||||
import {
|
||||
calculateCpuUsage,
|
||||
calculateMemoryUsage,
|
||||
dockerContainersRequestHandler,
|
||||
getDockerEndpointsAsync,
|
||||
getContainersWithStatsAsync,
|
||||
hasDockerEndpointCapability,
|
||||
} from "../docker";
|
||||
@@ -129,31 +127,6 @@ describe("calculateMemoryUsage", () => {
|
||||
});
|
||||
|
||||
describe("getContainersWithStatsAsync", () => {
|
||||
test("queries only selected Docker endpoints and leaves an empty selection as all", async () => {
|
||||
const firstListContainers = vi.fn(async () => []);
|
||||
const secondListContainers = vi.fn(async () => []);
|
||||
vi.spyOn(DockerSingleton, "getInstances").mockReturnValue([
|
||||
createDockerInstance("first", firstListContainers),
|
||||
createDockerInstance("second", secondListContainers),
|
||||
] as never);
|
||||
vi.spyOn(DockerSingleton, "getInitializationFailures").mockReturnValue([]);
|
||||
|
||||
try {
|
||||
const selectedResult = await getContainersWithStatsAsync(50, ["second"]);
|
||||
|
||||
expect(firstListContainers).not.toHaveBeenCalled();
|
||||
expect(secondListContainers).toHaveBeenCalledOnce();
|
||||
expect(selectedResult.endpoints.map(({ id }) => id)).toEqual(["second"]);
|
||||
|
||||
await getContainersWithStatsAsync(50, []);
|
||||
|
||||
expect(firstListContainers).toHaveBeenCalledOnce();
|
||||
expect(secondListContainers).toHaveBeenCalledTimes(2);
|
||||
} finally {
|
||||
vi.restoreAllMocks();
|
||||
}
|
||||
});
|
||||
|
||||
test("marks a timed-out endpoint unavailable without blocking healthy endpoints", async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
@@ -238,26 +211,14 @@ describe("getContainersWithStatsAsync", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("demo mode advertises and filters the same inventory-only endpoint", async () => {
|
||||
test("demo capabilities match the advertised inventory-only endpoint", () => {
|
||||
const previousDemoMode = process.env.DEMO_MODE;
|
||||
process.env.DEMO_MODE = "true";
|
||||
try {
|
||||
expect(getDockerEndpointsAsync()).toEqual([
|
||||
expect.objectContaining({ id: "demo", name: "Demo Docker", capabilities: ["inventory"] }),
|
||||
]);
|
||||
|
||||
const selected = await dockerContainersRequestHandler.handler({ endpointIds: ["demo"] }).getDataAsync();
|
||||
expect(selected.data.endpoints).toEqual([expect.objectContaining({ id: "demo" })]);
|
||||
expect(selected.data.containers.length).toBeGreaterThan(0);
|
||||
|
||||
const excluded = await dockerContainersRequestHandler.handler({ endpointIds: ["other"] }).getDataAsync();
|
||||
expect(excluded.data).toEqual({ containers: [], endpoints: [] });
|
||||
|
||||
expect(hasDockerEndpointCapability("demo", "inventory")).toBe(true);
|
||||
expect(hasDockerEndpointCapability("demo", "logs")).toBe(false);
|
||||
expect(hasDockerEndpointCapability("other", "inventory")).toBe(false);
|
||||
} finally {
|
||||
dockerContainersRequestHandler.invalidateCache();
|
||||
if (previousDemoMode === undefined) delete process.env.DEMO_MODE;
|
||||
else process.env.DEMO_MODE = previousDemoMode;
|
||||
}
|
||||
|
||||
@@ -1,112 +0,0 @@
|
||||
import { Response } from "undici";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { fetchWithTrustedCertificatesAsync } from "@homarr/core/infrastructure/http";
|
||||
|
||||
import { weatherRequestHandler } from "./weather";
|
||||
|
||||
vi.mock("@homarr/core/infrastructure/http", () => ({
|
||||
fetchWithTrustedCertificatesAsync: vi.fn(),
|
||||
}));
|
||||
|
||||
const mockFetch = vi.mocked(fetchWithTrustedCertificatesAsync);
|
||||
|
||||
const makeWeatherResponse = () => {
|
||||
const hours = Array.from({ length: 25 }, (_, index) => `2026-07-01T${String(index % 24).padStart(2, "0")}:00`);
|
||||
const days = [
|
||||
"2026-06-30",
|
||||
...Array.from({ length: 7 }, (_, index) => `2026-07-${String(index + 1).padStart(2, "0")}`),
|
||||
];
|
||||
const hourlyValues = hours.map<number | null>((_, index) => index);
|
||||
const dailyValues = days.map<number | null>((_, index) => index);
|
||||
const sunrise = days.map<string | null>((day) => `${day}T05:00`);
|
||||
|
||||
return {
|
||||
timezone: "Europe/Berlin",
|
||||
utc_offset_seconds: 7200,
|
||||
current: {
|
||||
time: "2026-07-01T12:00",
|
||||
temperature_2m: 24,
|
||||
relative_humidity_2m: 55,
|
||||
apparent_temperature: 25,
|
||||
is_day: 1,
|
||||
precipitation: 0,
|
||||
weather_code: 1,
|
||||
wind_speed_10m: 12,
|
||||
wind_gusts_10m: 20,
|
||||
},
|
||||
hourly: {
|
||||
time: hours,
|
||||
temperature_2m: hourlyValues,
|
||||
apparent_temperature: hourlyValues,
|
||||
precipitation_probability: hourlyValues,
|
||||
precipitation: hourlyValues,
|
||||
weather_code: hourlyValues,
|
||||
relative_humidity_2m: hourlyValues,
|
||||
wind_speed_10m: hourlyValues,
|
||||
wind_gusts_10m: hourlyValues,
|
||||
},
|
||||
daily: {
|
||||
time: days,
|
||||
weather_code: dailyValues,
|
||||
temperature_2m_max: dailyValues,
|
||||
temperature_2m_min: dailyValues,
|
||||
apparent_temperature_max: dailyValues,
|
||||
apparent_temperature_min: dailyValues,
|
||||
precipitation_probability_max: dailyValues,
|
||||
precipitation_sum: dailyValues,
|
||||
relative_humidity_2m_mean: dailyValues,
|
||||
wind_speed_10m_max: dailyValues,
|
||||
wind_gusts_10m_max: dailyValues,
|
||||
uv_index_max: dailyValues,
|
||||
sunrise,
|
||||
sunset: days.map((day) => `${day}T21:00`),
|
||||
daylight_duration: dailyValues,
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
weatherRequestHandler.invalidateCache();
|
||||
});
|
||||
|
||||
describe("weather request handler", () => {
|
||||
it("requests bounded useful forecasts and normalizes location times", async () => {
|
||||
const response = makeWeatherResponse();
|
||||
response.hourly.temperature_2m = [null];
|
||||
Reflect.deleteProperty(response.hourly, "wind_gusts_10m");
|
||||
response.daily.sunrise[1] = null;
|
||||
mockFetch.mockResolvedValue(new Response(JSON.stringify(response)));
|
||||
|
||||
const first = await weatherRequestHandler.handler({ latitude: 48.85, longitude: 2.35 }).getDataAsync();
|
||||
const second = await weatherRequestHandler.handler({ latitude: 48.85, longitude: 2.35 }).getDataAsync();
|
||||
|
||||
expect(first.data.current.observedAt).toBe("2026-07-01T10:00:00.000Z");
|
||||
expect(first.data.hourly).toHaveLength(24);
|
||||
expect(first.data.daily).toHaveLength(7);
|
||||
expect(first.data.daily[0]?.date).toBe("2026-07-01");
|
||||
expect(first.data.hourly[0]?.temperature).toBeNull();
|
||||
expect(first.data.hourly[1]?.temperature).toBeNull();
|
||||
expect(first.data.hourly[0]?.windGusts).toBeNull();
|
||||
expect(first.data.daily[0]?.sunriseAt).toBeNull();
|
||||
expect(first.data.daily[1]?.sunriseAt).toBe("2026-07-02T03:00:00.000Z");
|
||||
expect(second.data).toStrictEqual(first.data);
|
||||
expect(mockFetch).toHaveBeenCalledOnce();
|
||||
|
||||
const requestUrl = new URL(String(mockFetch.mock.calls[0]?.[0]));
|
||||
expect(requestUrl.searchParams.get("forecast_hours")).toBe("24");
|
||||
expect(requestUrl.searchParams.get("forecast_days")).toBe("7");
|
||||
expect(requestUrl.searchParams.has("past_days")).toBe(false);
|
||||
expect(requestUrl.searchParams.get("timezone")).toBe("auto");
|
||||
expect(requestUrl.searchParams.get("current")).toContain("apparent_temperature");
|
||||
expect(requestUrl.searchParams.get("hourly")).toContain("precipitation_probability");
|
||||
expect(requestUrl.searchParams.get("daily")).toContain("uv_index_max");
|
||||
});
|
||||
|
||||
it("rejects unsuccessful Open-Meteo responses", async () => {
|
||||
mockFetch.mockResolvedValue(new Response("unavailable", { status: 503 }));
|
||||
|
||||
await expect(weatherRequestHandler.handler({ latitude: 48.85, longitude: 2.35 }).getDataAsync()).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -1,255 +1,73 @@
|
||||
import dayjs from "dayjs";
|
||||
import timezone from "dayjs/plugin/timezone";
|
||||
import utc from "dayjs/plugin/utc";
|
||||
import { z } from "zod";
|
||||
|
||||
import { ResponseError } from "@homarr/common/server";
|
||||
import { fetchWithTrustedCertificatesAsync } from "@homarr/core/infrastructure/http";
|
||||
import { withTimeoutAsync } from "@homarr/core/infrastructure/http/timeout";
|
||||
|
||||
import { createWidgetRequestHandler } from "./lib/widget-request-handler";
|
||||
|
||||
dayjs.extend(utc);
|
||||
dayjs.extend(timezone);
|
||||
|
||||
const HOURLY_FORECAST_LENGTH = 24;
|
||||
const DAILY_FORECAST_LENGTH = 7;
|
||||
|
||||
const requestWeatherAsync = async (input: { latitude: number; longitude: number }): Promise<Weather> => {
|
||||
const url = new URL("https://api.open-meteo.com/v1/forecast");
|
||||
url.searchParams.set("latitude", input.latitude.toString());
|
||||
url.searchParams.set("longitude", input.longitude.toString());
|
||||
url.searchParams.set(
|
||||
"current",
|
||||
[
|
||||
"temperature_2m",
|
||||
"relative_humidity_2m",
|
||||
"apparent_temperature",
|
||||
"is_day",
|
||||
"precipitation",
|
||||
"weather_code",
|
||||
"wind_speed_10m",
|
||||
"wind_gusts_10m",
|
||||
].join(","),
|
||||
);
|
||||
url.searchParams.set(
|
||||
"hourly",
|
||||
[
|
||||
"temperature_2m",
|
||||
"apparent_temperature",
|
||||
"precipitation_probability",
|
||||
"precipitation",
|
||||
"weather_code",
|
||||
"relative_humidity_2m",
|
||||
"wind_speed_10m",
|
||||
"wind_gusts_10m",
|
||||
].join(","),
|
||||
);
|
||||
url.searchParams.set(
|
||||
"daily",
|
||||
[
|
||||
"weather_code",
|
||||
"temperature_2m_max",
|
||||
"temperature_2m_min",
|
||||
"apparent_temperature_max",
|
||||
"apparent_temperature_min",
|
||||
"precipitation_probability_max",
|
||||
"precipitation_sum",
|
||||
"relative_humidity_2m_mean",
|
||||
"wind_speed_10m_max",
|
||||
"wind_gusts_10m_max",
|
||||
"uv_index_max",
|
||||
"sunrise",
|
||||
"sunset",
|
||||
"daylight_duration",
|
||||
].join(","),
|
||||
);
|
||||
url.searchParams.set("timezone", "auto");
|
||||
url.searchParams.set("forecast_hours", HOURLY_FORECAST_LENGTH.toString());
|
||||
url.searchParams.set("forecast_days", DAILY_FORECAST_LENGTH.toString());
|
||||
|
||||
const res = await withTimeoutAsync(async (signal) => {
|
||||
return await fetchWithTrustedCertificatesAsync(url.toString(), { signal });
|
||||
});
|
||||
if (!res.ok) throw new ResponseError(res);
|
||||
|
||||
const json: unknown = await res.json();
|
||||
const weather = await atLocationOutput.parseAsync(json);
|
||||
const currentLocalDate = weather.current.time.slice(0, 10);
|
||||
const matchedCurrentDayIndex = weather.daily.time.indexOf(currentLocalDate);
|
||||
const currentDayIndex = matchedCurrentDayIndex < 0 ? 0 : matchedCurrentDayIndex;
|
||||
const dailyIndexes = weather.daily.time
|
||||
.map((_, index) => index)
|
||||
.slice(currentDayIndex, currentDayIndex + DAILY_FORECAST_LENGTH);
|
||||
return {
|
||||
timezone: weather.timezone,
|
||||
utcOffsetSeconds: weather.utc_offset_seconds,
|
||||
current: {
|
||||
observedAt: toUtcInstant(weather.current.time, weather.timezone),
|
||||
temperature: weather.current.temperature_2m,
|
||||
apparentTemperature: weather.current.apparent_temperature,
|
||||
relativeHumidity: weather.current.relative_humidity_2m,
|
||||
precipitation: weather.current.precipitation,
|
||||
weatherCode: weather.current.weather_code,
|
||||
weathercode: weather.current.weather_code,
|
||||
windSpeed: weather.current.wind_speed_10m,
|
||||
windspeed: weather.current.wind_speed_10m,
|
||||
windGusts: weather.current.wind_gusts_10m,
|
||||
isDay: weather.current.is_day === 1,
|
||||
},
|
||||
hourly: weather.hourly.time.slice(0, HOURLY_FORECAST_LENGTH).map((value, index) => {
|
||||
return {
|
||||
observedAt: toUtcInstant(value, weather.timezone),
|
||||
temperature: weather.hourly.temperature_2m[index] ?? null,
|
||||
apparentTemperature: weather.hourly.apparent_temperature[index] ?? null,
|
||||
precipitationProbability: weather.hourly.precipitation_probability[index] ?? null,
|
||||
precipitation: weather.hourly.precipitation[index] ?? null,
|
||||
weatherCode: weather.hourly.weather_code[index] ?? null,
|
||||
relativeHumidity: weather.hourly.relative_humidity_2m[index] ?? null,
|
||||
windSpeed: weather.hourly.wind_speed_10m[index] ?? null,
|
||||
windGusts: weather.hourly.wind_gusts_10m[index] ?? null,
|
||||
};
|
||||
}),
|
||||
daily: dailyIndexes.map((index) => {
|
||||
const value = weather.daily.time[index] ?? currentLocalDate;
|
||||
return {
|
||||
date: value,
|
||||
time: value,
|
||||
weatherCode: weather.daily.weather_code[index] ?? 404,
|
||||
maxTemperature: weather.daily.temperature_2m_max[index] ?? null,
|
||||
maxTemp: weather.daily.temperature_2m_max[index] ?? undefined,
|
||||
minTemperature: weather.daily.temperature_2m_min[index] ?? null,
|
||||
minTemp: weather.daily.temperature_2m_min[index] ?? undefined,
|
||||
maxApparentTemperature: weather.daily.apparent_temperature_max[index] ?? null,
|
||||
minApparentTemperature: weather.daily.apparent_temperature_min[index] ?? null,
|
||||
precipitationProbability: weather.daily.precipitation_probability_max[index] ?? null,
|
||||
precipitation: weather.daily.precipitation_sum[index] ?? null,
|
||||
averageHumidity: weather.daily.relative_humidity_2m_mean[index] ?? null,
|
||||
humidity: weather.daily.relative_humidity_2m_mean[index] ?? undefined,
|
||||
maxWindSpeed: weather.daily.wind_speed_10m_max[index] ?? null,
|
||||
maxWindGusts: weather.daily.wind_gusts_10m_max[index] ?? null,
|
||||
uvIndex: weather.daily.uv_index_max[index] ?? null,
|
||||
sunriseAt: toOptionalUtcInstant(weather.daily.sunrise[index], weather.timezone),
|
||||
sunrise: weather.daily.sunrise[index] ?? undefined,
|
||||
sunsetAt: toOptionalUtcInstant(weather.daily.sunset[index], weather.timezone),
|
||||
sunset: weather.daily.sunset[index] ?? undefined,
|
||||
daylightDuration: weather.daily.daylight_duration[index] ?? null,
|
||||
};
|
||||
}),
|
||||
} satisfies Weather;
|
||||
};
|
||||
|
||||
export const weatherRequestHandler = createWidgetRequestHandler({
|
||||
cacheTtlMs: 5 * 60 * 1000,
|
||||
requestAsync: requestWeatherAsync,
|
||||
async requestAsync(input: { latitude: number; longitude: number }) {
|
||||
const res = await withTimeoutAsync(async (signal) => {
|
||||
return await fetchWithTrustedCertificatesAsync(
|
||||
`https://api.open-meteo.com/v1/forecast?latitude=${input.latitude}&longitude=${input.longitude}&daily=weathercode,temperature_2m_max,temperature_2m_min,sunrise,sunset,wind_speed_10m_max,wind_gusts_10m_max,relative_humidity_2m_mean¤t_weather=true&timezone=auto`,
|
||||
{ signal },
|
||||
);
|
||||
});
|
||||
const json: unknown = await res.json();
|
||||
const weather = await atLocationOutput.parseAsync(json);
|
||||
return {
|
||||
current: weather.current_weather,
|
||||
daily: weather.daily.time.map((value, index) => {
|
||||
return {
|
||||
time: value,
|
||||
weatherCode: weather.daily.weathercode[index] ?? 404,
|
||||
maxTemp: weather.daily.temperature_2m_max[index],
|
||||
minTemp: weather.daily.temperature_2m_min[index],
|
||||
sunrise: weather.daily.sunrise[index],
|
||||
sunset: weather.daily.sunset[index],
|
||||
maxWindSpeed: weather.daily.wind_speed_10m_max[index],
|
||||
maxWindGusts: weather.daily.wind_gusts_10m_max[index],
|
||||
humidity: weather.daily.relative_humidity_2m_mean[index],
|
||||
};
|
||||
}),
|
||||
} satisfies Weather;
|
||||
},
|
||||
});
|
||||
|
||||
const nullableNumberArray = z.array(z.number().nullable()).default([]);
|
||||
const nullableStringArray = z.array(z.string().nullable()).default([]);
|
||||
|
||||
const atLocationOutput = z.object({
|
||||
timezone: z.string().min(1),
|
||||
utc_offset_seconds: z.number(),
|
||||
current: z.object({
|
||||
time: z.string(),
|
||||
temperature_2m: z.number(),
|
||||
relative_humidity_2m: z.number(),
|
||||
apparent_temperature: z.number(),
|
||||
is_day: z.number(),
|
||||
precipitation: z.number(),
|
||||
weather_code: z.number(),
|
||||
wind_speed_10m: z.number(),
|
||||
wind_gusts_10m: z.number(),
|
||||
}),
|
||||
hourly: z.object({
|
||||
time: z.array(z.string()),
|
||||
temperature_2m: nullableNumberArray,
|
||||
apparent_temperature: nullableNumberArray,
|
||||
precipitation_probability: nullableNumberArray,
|
||||
precipitation: nullableNumberArray,
|
||||
weather_code: nullableNumberArray,
|
||||
relative_humidity_2m: nullableNumberArray,
|
||||
wind_speed_10m: nullableNumberArray,
|
||||
wind_gusts_10m: nullableNumberArray,
|
||||
current_weather: z.object({
|
||||
weathercode: z.number(),
|
||||
temperature: z.number(),
|
||||
windspeed: z.number(),
|
||||
}),
|
||||
daily: z.object({
|
||||
time: z.array(z.string()),
|
||||
weather_code: nullableNumberArray,
|
||||
temperature_2m_max: nullableNumberArray,
|
||||
temperature_2m_min: nullableNumberArray,
|
||||
apparent_temperature_max: nullableNumberArray,
|
||||
apparent_temperature_min: nullableNumberArray,
|
||||
precipitation_probability_max: nullableNumberArray,
|
||||
precipitation_sum: nullableNumberArray,
|
||||
relative_humidity_2m_mean: nullableNumberArray,
|
||||
wind_speed_10m_max: nullableNumberArray,
|
||||
wind_gusts_10m_max: nullableNumberArray,
|
||||
uv_index_max: nullableNumberArray,
|
||||
sunrise: nullableStringArray,
|
||||
sunset: nullableStringArray,
|
||||
daylight_duration: nullableNumberArray,
|
||||
weathercode: z.array(z.number()),
|
||||
temperature_2m_max: z.array(z.number()),
|
||||
temperature_2m_min: z.array(z.number()),
|
||||
sunrise: z.array(z.string()),
|
||||
sunset: z.array(z.string()),
|
||||
wind_speed_10m_max: z.array(z.number()),
|
||||
wind_gusts_10m_max: z.array(z.number()),
|
||||
relative_humidity_2m_mean: z.array(z.number()),
|
||||
}),
|
||||
});
|
||||
|
||||
const toUtcInstant = (value: string, timeZone: string): string => {
|
||||
const parsed = dayjs.tz(value, timeZone);
|
||||
if (!parsed.isValid()) throw new Error(`Invalid weather timestamp: ${value}`);
|
||||
return parsed.utc().toISOString();
|
||||
};
|
||||
|
||||
const toOptionalUtcInstant = (value: string | null | undefined, timeZone: string): string | null => {
|
||||
if (!value) return null;
|
||||
return toUtcInstant(value, timeZone);
|
||||
};
|
||||
|
||||
export interface Weather {
|
||||
timezone: string;
|
||||
utcOffsetSeconds: number;
|
||||
current: {
|
||||
temperature: number;
|
||||
apparentTemperature: number;
|
||||
relativeHumidity: number;
|
||||
precipitation: number;
|
||||
weatherCode: number;
|
||||
weathercode: number;
|
||||
windSpeed: number;
|
||||
temperature: number;
|
||||
windspeed: number;
|
||||
windGusts: number;
|
||||
isDay: boolean;
|
||||
observedAt: string;
|
||||
};
|
||||
hourly: {
|
||||
observedAt: string;
|
||||
temperature: number | null;
|
||||
apparentTemperature: number | null;
|
||||
precipitationProbability: number | null;
|
||||
precipitation: number | null;
|
||||
weatherCode: number | null;
|
||||
relativeHumidity: number | null;
|
||||
windSpeed: number | null;
|
||||
windGusts: number | null;
|
||||
}[];
|
||||
daily: {
|
||||
date: string;
|
||||
time: string;
|
||||
weatherCode: number;
|
||||
maxTemperature: number | null;
|
||||
maxTemp: number | undefined;
|
||||
minTemperature: number | null;
|
||||
minTemp: number | undefined;
|
||||
maxApparentTemperature: number | null;
|
||||
minApparentTemperature: number | null;
|
||||
precipitationProbability: number | null;
|
||||
precipitation: number | null;
|
||||
averageHumidity: number | null;
|
||||
humidity: number | undefined;
|
||||
maxWindSpeed: number | null;
|
||||
maxWindGusts: number | null;
|
||||
uvIndex: number | null;
|
||||
sunriseAt: string | null;
|
||||
sunrise: string | undefined;
|
||||
sunsetAt: string | null;
|
||||
sunset: string | undefined;
|
||||
daylightDuration: number | null;
|
||||
maxWindSpeed: number | undefined;
|
||||
maxWindGusts: number | undefined;
|
||||
humidity: number | undefined;
|
||||
}[];
|
||||
}
|
||||
@@ -66,10 +66,15 @@
|
||||
"themeAuto": "System",
|
||||
"themeLight": "Light",
|
||||
"themeDark": "Dark",
|
||||
"serverTitle": "Usual server address",
|
||||
"serverOriginHelp": "Homarr uses this address to prefill detected service URLs. You can still edit every service individually.",
|
||||
"serverDescription": "This is a shortcut, not a restriction. Every detected service remains editable.",
|
||||
"serverOrigin": "Domain, IP, or reverse-proxy path",
|
||||
"serverOriginDescription": "Examples: home.lan, 192.168.1.10, or https://home.example.com/services. Choose how each service is appended below.",
|
||||
"urlModeLabel": "Service address pattern",
|
||||
"hostPort": "Same host, different ports",
|
||||
"subdomain": "One subdomain per service",
|
||||
"path": "One path per service",
|
||||
"analytics": "Share anonymous product analytics",
|
||||
"analyticsDescription": "Helps Homarr improve feature reliability. No service credentials or dashboard content are sent."
|
||||
},
|
||||
@@ -2166,13 +2171,6 @@
|
||||
"undo": "Undo"
|
||||
},
|
||||
"here": "here",
|
||||
"serviceUrlTemplate": {
|
||||
"serverTitle": "Usual server address",
|
||||
"urlModeLabel": "Service address pattern",
|
||||
"hostPort": "Same host, different ports",
|
||||
"subdomain": "One subdomain per service",
|
||||
"path": "One path per service"
|
||||
},
|
||||
"iconPicker": {
|
||||
"label": "Icon URL",
|
||||
"description": "Search the library, paste an image URL, or upload a file.",
|
||||
@@ -3153,6 +3151,9 @@
|
||||
"label": "24-hour format",
|
||||
"description": "Use 24-hour format instead of 12-hour format"
|
||||
},
|
||||
"showSeconds": {
|
||||
"label": "Display seconds"
|
||||
},
|
||||
"useCustomTimezone": {
|
||||
"label": "Use a fixed timezone"
|
||||
},
|
||||
@@ -3164,12 +3165,16 @@
|
||||
"label": "Show the date"
|
||||
},
|
||||
"dateFormat": {
|
||||
"label": "Date format",
|
||||
"description": "Choose a Day.js preset. Each option shows a live example and its format tokens."
|
||||
"label": "Date Format",
|
||||
"description": "How the date should look like"
|
||||
},
|
||||
"customTimeFormat": {
|
||||
"label": "Time format",
|
||||
"description": "Choose a Day.js preset. The selected format controls 12/24-hour display and whether the clock updates every second."
|
||||
"label": "Custom time format",
|
||||
"description": "Use ISO 8601 to format time (this will override other options)"
|
||||
},
|
||||
"customDateFormat": {
|
||||
"label": "Custom date format",
|
||||
"description": "Use ISO 8601 to format date (this will override other options)"
|
||||
},
|
||||
"showWeather": {
|
||||
"label": "Show weather",
|
||||
@@ -3180,317 +3185,7 @@
|
||||
},
|
||||
"isWeatherFormatFahrenheit": {
|
||||
"label": "Use Fahrenheit"
|
||||
},
|
||||
"animateWeatherIcon": {
|
||||
"label": "Animate weather icon",
|
||||
"description": "Animate the weather icon. Disabled by default and always disabled when reduced motion is requested."
|
||||
},
|
||||
"worldClockCities": {
|
||||
"label": "World clock cities",
|
||||
"description": "Add and order up to six cities for advanced view."
|
||||
}
|
||||
},
|
||||
"timezoneList": {
|
||||
"timezone": "Timezone",
|
||||
"cityLabel": "City label",
|
||||
"searchPlaceholder": "Search timezones",
|
||||
"noResults": "No timezones found",
|
||||
"unsupportedOption": "Unsupported: {timeZone}",
|
||||
"add": "Add city",
|
||||
"remove": "Remove {city}",
|
||||
"reorder": "Reorder {city}",
|
||||
"limit": "{count} of {maximum} cities configured"
|
||||
},
|
||||
"worldClock": {
|
||||
"primary": "Primary clock",
|
||||
"local": "Local time",
|
||||
"today": "Today",
|
||||
"tomorrow": "Tomorrow",
|
||||
"yesterday": "Yesterday",
|
||||
"noSecondaryCities": "Add cities in widget options to compare them here.",
|
||||
"unsupportedPrimaryTitle": "Primary timezone is unavailable",
|
||||
"unsupportedPrimary": "{timeZone} is not supported in this browser. Showing UTC as a clearly marked fallback.",
|
||||
"unsupportedTimeZone": "Unsupported timezone: {timeZone}",
|
||||
"accessibleTime": "{city}: {time}, {date}, {timeZone}",
|
||||
"advancedLabel": "Advanced world clock",
|
||||
"cities": "World clocks",
|
||||
"cityCount": "{count} timezones",
|
||||
"timeBarLabel": "24-hour time-of-day position for {city}",
|
||||
"dayProgress": "{percent}% elapsed · {hours}h {minutes}m remaining",
|
||||
"phaseLegend": "Time-of-day legend",
|
||||
"tick": {
|
||||
"midnight": "00",
|
||||
"morning": "06",
|
||||
"noon": "12",
|
||||
"evening": "18",
|
||||
"end": "24"
|
||||
},
|
||||
"phaseRange": {
|
||||
"night": "00–05 · 21–24",
|
||||
"dawn": "05–08",
|
||||
"day": "08–18",
|
||||
"dusk": "18–21"
|
||||
},
|
||||
"phase": {
|
||||
"night": "Night",
|
||||
"dawn": "Dawn",
|
||||
"day": "Day",
|
||||
"dusk": "Dusk"
|
||||
}
|
||||
}
|
||||
},
|
||||
"airQuality": {
|
||||
"name": "Air Quality & UV",
|
||||
"description": "Displays air quality, ultraviolet index, pollutants and pollen for a location.",
|
||||
"option": {
|
||||
"location": {
|
||||
"label": "Air quality location"
|
||||
},
|
||||
"aqiStandard": {
|
||||
"label": "AQI standard",
|
||||
"options": {
|
||||
"auto": "Automatic for locale",
|
||||
"european": "European AQI",
|
||||
"us": "US AQI"
|
||||
}
|
||||
},
|
||||
"showUv": {
|
||||
"label": "Show UV index"
|
||||
},
|
||||
"showPollutants": {
|
||||
"label": "Show pollutant concentrations"
|
||||
},
|
||||
"showPollen": {
|
||||
"label": "Show pollen concentrations"
|
||||
}
|
||||
},
|
||||
"category": {
|
||||
"good": "Good",
|
||||
"fair": "Fair",
|
||||
"moderate": "Moderate",
|
||||
"unhealthySensitive": "Unhealthy for sensitive groups",
|
||||
"unhealthy": "Unhealthy",
|
||||
"poor": "Poor",
|
||||
"veryPoor": "Very poor",
|
||||
"veryUnhealthy": "Very unhealthy",
|
||||
"extremelyPoor": "Extremely poor",
|
||||
"hazardous": "Hazardous",
|
||||
"unknown": "No AQI reading"
|
||||
},
|
||||
"uv": {
|
||||
"label": "UV index",
|
||||
"category": {
|
||||
"low": "Low",
|
||||
"moderate": "Moderate",
|
||||
"high": "High",
|
||||
"veryHigh": "Very high",
|
||||
"extreme": "Extreme",
|
||||
"unknown": "No reading"
|
||||
}
|
||||
},
|
||||
"dominantPollutant": "Dominant pollutant",
|
||||
"aqiLabel": "AQI",
|
||||
"strongestPollen": "Highest pollen",
|
||||
"unit": {
|
||||
"concentration": "{value} µg/m³",
|
||||
"pollen": "{value} grains/m³"
|
||||
},
|
||||
"pollutant": {
|
||||
"pm2_5": "PM2.5",
|
||||
"pm10": "PM10",
|
||||
"ozone": "Ozone",
|
||||
"nitrogenDioxide": "Nitrogen dioxide",
|
||||
"sulphurDioxide": "Sulphur dioxide",
|
||||
"carbonMonoxide": "Carbon monoxide"
|
||||
},
|
||||
"pollen": {
|
||||
"alder": "Alder",
|
||||
"birch": "Birch",
|
||||
"grass": "Grass",
|
||||
"mugwort": "Mugwort",
|
||||
"olive": "Olive",
|
||||
"ragweed": "Ragweed"
|
||||
},
|
||||
"compact": {
|
||||
"sixHourTrend": "AQI trend for the next six hours"
|
||||
},
|
||||
"advanced": {
|
||||
"observedAt": "Updated at {time}",
|
||||
"next24Hours": "Next 24 hours",
|
||||
"pollutants": "Pollutant concentrations",
|
||||
"pollen": "Pollen concentrations",
|
||||
"sevenDayForecast": "7-day maximum forecast",
|
||||
"aqiValue": "AQI {value}",
|
||||
"uvValue": "UV {value}",
|
||||
"uvShort": "UV {value}",
|
||||
"noForecast": "No forecast data available"
|
||||
}
|
||||
},
|
||||
"countdown": {
|
||||
"name": "Countdowns",
|
||||
"description": "Tracks upcoming events and recurring anniversaries.",
|
||||
"option": {
|
||||
"events": {
|
||||
"label": "Events",
|
||||
"description": "Add and order up to 20 one-time or yearly countdowns. Dates are entered in the selected timezone."
|
||||
},
|
||||
"showProgress": {
|
||||
"label": "Show progress"
|
||||
},
|
||||
"showSeconds": {
|
||||
"label": "Show seconds",
|
||||
"description": "Keep seconds visible for every upcoming event."
|
||||
}
|
||||
},
|
||||
"dateTimeEventList": {
|
||||
"newEvent": "New event",
|
||||
"add": "Add event",
|
||||
"remove": "Remove {event}",
|
||||
"reorder": "Reorder {event}",
|
||||
"eventLabel": "Event label",
|
||||
"timezone": "Timezone",
|
||||
"unsupportedOption": "Unsupported: {timeZone}",
|
||||
"recurrence": "Repeats",
|
||||
"recurrenceOption": {
|
||||
"none": "Does not repeat",
|
||||
"yearly": "Every year"
|
||||
},
|
||||
"target": "Event date and time",
|
||||
"trackProgress": "Track progress from a start date",
|
||||
"start": "Progress start date and time",
|
||||
"confirmDateTime": "Confirm date and time",
|
||||
"limit": "{count} of {maximum} events configured"
|
||||
},
|
||||
"empty": {
|
||||
"title": "No countdowns yet",
|
||||
"description": "Add an event in widget options to start counting down."
|
||||
},
|
||||
"completed": "Completed",
|
||||
"yearly": "Yearly",
|
||||
"progress": "Event progress",
|
||||
"upcoming": "Upcoming",
|
||||
"completedEvents": "Completed events",
|
||||
"invalid": {
|
||||
"title": "Some events cannot be displayed",
|
||||
"description": "{count, plural, one {One event has an invalid date or unsupported timezone.} other {# events have an invalid date or unsupported timezone.}}",
|
||||
"value": "Unavailable"
|
||||
},
|
||||
"alert": {
|
||||
"notifications": "Browser notifications",
|
||||
"permissionDenied": "Notifications are blocked in this browser.",
|
||||
"reached": "The countdown has reached its target."
|
||||
}
|
||||
},
|
||||
"timer": {
|
||||
"name": "Timer / Pomodoro",
|
||||
"description": "Runs a simple timer or a configurable Pomodoro sequence.",
|
||||
"option": {
|
||||
"mode": {
|
||||
"label": "Mode",
|
||||
"options": {
|
||||
"timer": "Timer",
|
||||
"pomodoro": "Pomodoro"
|
||||
}
|
||||
},
|
||||
"timerMinutes": {
|
||||
"label": "Timer minutes"
|
||||
},
|
||||
"focusMinutes": {
|
||||
"label": "Focus minutes"
|
||||
},
|
||||
"shortBreakMinutes": {
|
||||
"label": "Short break minutes"
|
||||
},
|
||||
"longBreakMinutes": {
|
||||
"label": "Long break minutes"
|
||||
},
|
||||
"sessionsBeforeLongBreak": {
|
||||
"label": "Focus sessions before a long break"
|
||||
},
|
||||
"autoStartBreaks": {
|
||||
"label": "Automatically start breaks"
|
||||
},
|
||||
"autoStartFocus": {
|
||||
"label": "Automatically start focus sessions"
|
||||
}
|
||||
},
|
||||
"phase": {
|
||||
"timer": "Timer",
|
||||
"focus": "Focus",
|
||||
"shortBreak": "Short break",
|
||||
"longBreak": "Long break"
|
||||
},
|
||||
"action": {
|
||||
"start": "Start",
|
||||
"pause": "Pause",
|
||||
"reset": "Reset"
|
||||
},
|
||||
"attention": {
|
||||
"timerComplete": "Timer complete",
|
||||
"phaseReady": "{phase} ready"
|
||||
},
|
||||
"progress": "Timer progress: {progress}%",
|
||||
"compact": {
|
||||
"completedFocus": "{count, plural, =0 {No focus sessions completed} one {# focus session completed} other {# focus sessions completed}}"
|
||||
},
|
||||
"alert": {
|
||||
"title": "Timer complete",
|
||||
"completed": "{phase} completed."
|
||||
},
|
||||
"advanced": {
|
||||
"sequence": "Pomodoro sequence",
|
||||
"focusSession": "Focus {session}",
|
||||
"settings": "Permanent settings",
|
||||
"settingsHint": "Use the widget context menu to edit these board settings.",
|
||||
"localAlerts": "Local alerts",
|
||||
"notifications": "Browser notifications",
|
||||
"sound": "Timer sounds",
|
||||
"localAlertsHint": "Timer sounds are enabled by default. Sounds and notifications apply only to this widget in this browser.",
|
||||
"notificationsDenied": "Notifications are blocked in this browser."
|
||||
}
|
||||
},
|
||||
"today": {
|
||||
"name": "Today",
|
||||
"description": "Displays the current date and progress through the calendar.",
|
||||
"option": {
|
||||
"weekConvention": {
|
||||
"label": "Week numbering",
|
||||
"options": {
|
||||
"locale": "Use locale rules",
|
||||
"iso": "ISO 8601"
|
||||
}
|
||||
},
|
||||
"showWeekNumber": {
|
||||
"label": "Show week number"
|
||||
},
|
||||
"showDayOfYear": {
|
||||
"label": "Show day of year"
|
||||
},
|
||||
"showQuarter": {
|
||||
"label": "Show quarter"
|
||||
},
|
||||
"showYearProgress": {
|
||||
"label": "Show year progress"
|
||||
}
|
||||
},
|
||||
"weekNumber": "Week {week}",
|
||||
"dayOfYear": "Day {day} of {total}",
|
||||
"quarter": "Quarter {quarter}",
|
||||
"daysAfterToday": "{days, plural, =0 {Last day of the year} one {# day after today} other {# days after today}}",
|
||||
"weekProgressLabel": "Week progress",
|
||||
"monthProgressLabel": "Month progress",
|
||||
"yearProgressLabel": "Year progress",
|
||||
"yearProgress": "Year progress: {progress}%",
|
||||
"weekConvention": {
|
||||
"locale": "Week numbers follow your locale",
|
||||
"iso": "ISO 8601 week numbers"
|
||||
},
|
||||
"advanced": {
|
||||
"week": "Week number",
|
||||
"dayOfYear": "Day of year",
|
||||
"quarter": "Quarter",
|
||||
"quarterValue": "Q{quarter}",
|
||||
"daysRemaining": "Days after today"
|
||||
}
|
||||
},
|
||||
"minecraftServerStatus": {
|
||||
@@ -3836,10 +3531,6 @@
|
||||
"label": "1 Month"
|
||||
}
|
||||
}
|
||||
},
|
||||
"showDetails": {
|
||||
"label": "Show details",
|
||||
"description": "Show the name, change, and time range in the compact view. Turn off for just the symbol and price."
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -3886,13 +3577,6 @@
|
||||
"disableTemperatureDecimals": {
|
||||
"label": "Disable temperature decimals"
|
||||
},
|
||||
"animateIcons": {
|
||||
"label": "Animate weather icons"
|
||||
},
|
||||
"showHumidity": {
|
||||
"label": "Show humidity",
|
||||
"description": "Display humidity in current conditions, hourly details and daily forecasts"
|
||||
},
|
||||
"showCurrentWindSpeed": {
|
||||
"label": "Show current wind speed",
|
||||
"description": "Only on current weather"
|
||||
@@ -3946,40 +3630,11 @@
|
||||
"detailsFor": "Show weather details for {date}",
|
||||
"advanced": {
|
||||
"forecast": "7-day forecast",
|
||||
"hourlyForecast": "Next 24 hours",
|
||||
"day": "Day",
|
||||
"time": "Time",
|
||||
"conditions": "Conditions",
|
||||
"temperature": "Temperature",
|
||||
"feelsLike": "Feels like {temperature}",
|
||||
"feelsLikeLabel": "Feels like",
|
||||
"feelsLikeRange": "Feels like: {maximum} / {minimum}",
|
||||
"highLow": "High {maximum} · low {minimum}",
|
||||
"observedAt": "Updated at {time}",
|
||||
"temperature": "High / low",
|
||||
"humidity": "Humidity",
|
||||
"averageHumidity": "Average humidity: {humidity}%",
|
||||
"currentHumidity": "Current humidity",
|
||||
"wind": "Wind / gusts ({unit})",
|
||||
"currentWind": "Current wind / gusts",
|
||||
"windValue": "{speed} / {gusts} {unit}",
|
||||
"windDetail": "Max wind / gusts: {speed} / {gusts} {unit}",
|
||||
"nextHourPrecipitation": "Precipitation next hour",
|
||||
"precipitationChance": "Precipitation chance",
|
||||
"precipitationValue": "{probability}% · {amount} mm",
|
||||
"precipitationDetail": "Precipitation: {probability}% · {amount} mm",
|
||||
"todayUv": "Today's max UV index",
|
||||
"uvIndex": "Max UV index: {value}",
|
||||
"daylight": "Daylight: {duration}",
|
||||
"hourlyTooltip": "Feels like {feelsLike}{temperatureUnit} · {amount} mm · {humidity}% humidity · {speed} {speedUnit} wind",
|
||||
"hourlyTooltipWithoutHumidity": "Feels like {feelsLike}{temperatureUnit} · {amount} mm · {speed} {speedUnit} wind",
|
||||
"detailLabel": {
|
||||
"feelsLike": "Feels like",
|
||||
"precipitation": "Precipitation",
|
||||
"humidity": "Average humidity",
|
||||
"wind": "Max wind / gusts",
|
||||
"uv": "Max UV index",
|
||||
"daylight": "Daylight"
|
||||
},
|
||||
"sun": "Sunrise / sunset",
|
||||
"noForecast": "No forecast data available"
|
||||
}
|
||||
@@ -4116,11 +3771,6 @@
|
||||
"name": "Docker stats",
|
||||
"description": "Stats of your containers (This widget can only be added with administrator privileges)",
|
||||
"option": {
|
||||
"endpointIds": {
|
||||
"label": "Docker environments",
|
||||
"description": "Leave empty to show containers from every Docker environment",
|
||||
"placeholder": "All Docker environments"
|
||||
},
|
||||
"columns": {
|
||||
"label": "Columns to show"
|
||||
},
|
||||
@@ -6069,7 +5719,6 @@
|
||||
},
|
||||
"dynamicSelect": {
|
||||
"noResults": "No results found",
|
||||
"loading": "Loading...",
|
||||
"loadError": "Failed to load options"
|
||||
},
|
||||
"assistant": {
|
||||
@@ -7458,18 +7107,23 @@
|
||||
"docker": {
|
||||
"title": "Containers",
|
||||
"reconciliation": {
|
||||
"title": "Assisted Docker setup",
|
||||
"suggestions": "{count, plural, =0 {No suggestions} one {# suggestion} other {# suggestions}}",
|
||||
"title": "Service setup",
|
||||
"description": "Docker services are compared with your apps and integrations. Review every suggestion before Homarr changes anything.",
|
||||
"attention": "{count} need attention",
|
||||
"endpointUnavailable": "Some services could not be checked because these endpoints are unavailable: {names}",
|
||||
"empty": "No visible Docker services were found.",
|
||||
"emptyFilter": "No services match this view.",
|
||||
"ambiguous": "More than one existing item could match this service. Homarr will not choose one automatically.",
|
||||
"match": "{confidence} confidence match",
|
||||
"filter": {
|
||||
"attention": "Needs attention",
|
||||
"represented": "Already set up",
|
||||
"all": "All"
|
||||
},
|
||||
"confidence": {
|
||||
"high": "High",
|
||||
"medium": "Medium"
|
||||
},
|
||||
"state": {
|
||||
"newRecognized": "Ready to connect",
|
||||
"newApp": "New service",
|
||||
@@ -7478,9 +7132,19 @@
|
||||
"moved": "Address changed"
|
||||
},
|
||||
"url": {
|
||||
"manual": "Enter an address manually"
|
||||
"label": "Service address",
|
||||
"inputLabel": "Service URL",
|
||||
"manual": "Enter an address manually",
|
||||
"invalid": "Enter a valid HTTP or HTTPS URL"
|
||||
},
|
||||
"reason": {
|
||||
"publishedAddress": "Published address reported by Docker",
|
||||
"dockerEndpointHost": "Docker endpoint host combined with the published port",
|
||||
"sharedContainerNetwork": "Server-only address for services sharing the container network",
|
||||
"manualHostRequired": "Enter the address that your browser or Homarr server can reach"
|
||||
},
|
||||
"health": {
|
||||
"title": "Observed service layers",
|
||||
"layer": {
|
||||
"docker": "Docker",
|
||||
"integrationConfiguration": "Integration",
|
||||
@@ -7502,15 +7166,17 @@
|
||||
}
|
||||
},
|
||||
"action": {
|
||||
"review": "Review",
|
||||
"refresh": "Refresh",
|
||||
"retry": "Try again",
|
||||
"dismiss": "Dismiss",
|
||||
"restoreDismissed": "Restore dismissed ({count})",
|
||||
"setupIntegration": "Set up integration",
|
||||
"createApp": "Create app",
|
||||
"reviewIntegration": "Review integration",
|
||||
"viewRepresentation": "View setup"
|
||||
},
|
||||
"loadError": {
|
||||
"title": "Docker setup assistant could not be loaded",
|
||||
"title": "Service setup could not be loaded",
|
||||
"message": "Docker service information is unavailable. Try again without leaving this page."
|
||||
},
|
||||
"refreshError": {
|
||||
|
||||
@@ -65,7 +65,6 @@
|
||||
"@mantine/dates": "catalog:",
|
||||
"@mantine/form": "catalog:",
|
||||
"@mantine/hooks": "catalog:",
|
||||
"@rexa-developer/tiks": "catalog:",
|
||||
"@tabler/icons-react": "catalog:",
|
||||
"@tiptap/extension-color": "catalog:",
|
||||
"@tiptap/extension-highlight": "catalog:",
|
||||
|
||||
@@ -3,9 +3,7 @@ import { WidgetAnchorNoteInput } from "./widget-anchor-note-input";
|
||||
import { WidgetAppInput } from "./widget-app-input";
|
||||
import { WidgetCustomWidgetSelectInput } from "./widget-custom-widget-select-input";
|
||||
import { WidgetCustomWidgetConfigurationInput } from "./widget-custom-widget-configuration-input";
|
||||
import { WidgetDateTimeEventListInput } from "./widget-date-time-event-list-input";
|
||||
import { WidgetDynamicSelectInput } from "./widget-dynamic-select-input";
|
||||
import { WidgetDynamicMultiSelectInput } from "./widget-dynamic-multiselect-input";
|
||||
import { WidgetLocationInput } from "./widget-location-input";
|
||||
import { WidgetMultiTextInput } from "./widget-multi-text-input";
|
||||
import { WidgetMultiReleasesRepositoriesInput } from "./widget-multiReleasesRepositories-input";
|
||||
@@ -16,7 +14,6 @@ import { WidgetSliderInput } from "./widget-slider-input";
|
||||
import { WidgetSortedItemListInput } from "./widget-sortable-item-list-input";
|
||||
import { WidgetSwitchInput } from "./widget-switch-input";
|
||||
import { WidgetTextInput } from "./widget-text-input";
|
||||
import { WidgetTimezoneListInput } from "./widget-timezone-list-input";
|
||||
import { WidgetUmamiEventInput } from "./widget-umami-event-input";
|
||||
import { WidgetUmamiEventNamesInput } from "./widget-umami-event-names-input";
|
||||
import { WidgetUmamiWebsiteInput } from "./widget-umami-website-input";
|
||||
@@ -28,8 +25,6 @@ const mapping = {
|
||||
internal: WidgetInternalInput,
|
||||
anchorNote: WidgetAnchorNoteInput,
|
||||
text: WidgetTextInput,
|
||||
dateTimeEventList: WidgetDateTimeEventListInput,
|
||||
timezoneList: WidgetTimezoneListInput,
|
||||
location: WidgetLocationInput,
|
||||
multiSelect: WidgetMultiSelectInput,
|
||||
multiText: WidgetMultiTextInput,
|
||||
@@ -41,7 +36,6 @@ const mapping = {
|
||||
sortableItemList: WidgetSortedItemListInput,
|
||||
multiReleasesRepositories: WidgetMultiReleasesRepositoriesInput,
|
||||
dynamicSelect: WidgetDynamicSelectInput,
|
||||
dynamicMultiSelect: WidgetDynamicMultiSelectInput,
|
||||
umamiEventName: WidgetUmamiEventInput,
|
||||
umamiEventNames: WidgetUmamiEventNamesInput,
|
||||
umamiWebsite: WidgetUmamiWebsiteInput,
|
||||
|
||||
@@ -1,317 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import {
|
||||
closestCenter,
|
||||
DndContext,
|
||||
KeyboardSensor,
|
||||
MouseSensor,
|
||||
TouchSensor,
|
||||
useSensor,
|
||||
useSensors,
|
||||
} from "@dnd-kit/core";
|
||||
import {
|
||||
arrayMove,
|
||||
SortableContext,
|
||||
sortableKeyboardCoordinates,
|
||||
useSortable,
|
||||
verticalListSortingStrategy,
|
||||
} from "@dnd-kit/sortable";
|
||||
import { ActionIcon, Button, Card, Fieldset, Group, Select, Stack, Switch, Text, TextInput } from "@mantine/core";
|
||||
import { DateTimePicker } from "@mantine/dates";
|
||||
import { IconGripVertical, IconPlus, IconTrash } from "@tabler/icons-react";
|
||||
import dayjs from "dayjs";
|
||||
|
||||
import { createId } from "@homarr/common";
|
||||
import type { WidgetKind } from "@homarr/definitions";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import { formatWallDateTime, resolveWallDateTimeString } from "../countdown/recurrence";
|
||||
import type { DateTimeEventRecurrence, OptionDateTimeEvent } from "../options";
|
||||
import type { CommonWidgetInputProps } from "./common";
|
||||
import { useWidgetInputTranslation } from "./common";
|
||||
import { useFormContext } from "./form";
|
||||
|
||||
export const WidgetDateTimeEventListInput = ({
|
||||
property,
|
||||
kind,
|
||||
options,
|
||||
}: CommonWidgetInputProps<"dateTimeEventList">) => {
|
||||
const t = useWidgetInputTranslation(kind, property);
|
||||
const tEditor = useEventListTranslation(kind);
|
||||
const form = useFormContext();
|
||||
const fieldPath = `options.${property}`;
|
||||
const currentValue = form.values.options[property];
|
||||
const values = Array.isArray(currentValue) ? (currentValue as OptionDateTimeEvent[]) : options.defaultValue;
|
||||
const sensors = useSensors(
|
||||
useSensor(MouseSensor),
|
||||
useSensor(TouchSensor),
|
||||
useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (Array.isArray(currentValue)) return;
|
||||
form.setFieldValue(fieldPath, options.defaultValue);
|
||||
}, [currentValue, fieldPath, form, options.defaultValue]);
|
||||
|
||||
const setValues = (nextValues: OptionDateTimeEvent[]) => form.setFieldValue(fieldPath, nextValues);
|
||||
const addEvent = () => {
|
||||
if (values.length >= options.maxValues) return;
|
||||
const localTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
|
||||
const target = dayjs().add(1, "day").minute(0).second(0).millisecond(0);
|
||||
setValues([
|
||||
...values,
|
||||
{
|
||||
id: createId(),
|
||||
label: tEditor("newEvent"),
|
||||
targetUtc: target.toISOString(),
|
||||
timeZone: localTimeZone,
|
||||
recurrence: "none",
|
||||
},
|
||||
]);
|
||||
};
|
||||
|
||||
return (
|
||||
<Fieldset legend={t("label")}>
|
||||
<Stack gap="sm">
|
||||
{options.withDescription && (
|
||||
<Text size="sm" c="dimmed">
|
||||
{t("description")}
|
||||
</Text>
|
||||
)}
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
variant="light"
|
||||
leftSection={<IconPlus size="var(--mantine-font-size-md)" />}
|
||||
onClick={addEvent}
|
||||
disabled={values.length >= options.maxValues}
|
||||
>
|
||||
{tEditor("add")}
|
||||
</Button>
|
||||
|
||||
<DndContext
|
||||
sensors={sensors}
|
||||
collisionDetection={closestCenter}
|
||||
onDragEnd={({ active, over }) => {
|
||||
if (!over || active.id === over.id) return;
|
||||
const activeIndex = values.findIndex(({ id }) => id === active.id);
|
||||
const overIndex = values.findIndex(({ id }) => id === over.id);
|
||||
if (activeIndex < 0 || overIndex < 0) return;
|
||||
setValues(arrayMove(values, activeIndex, overIndex));
|
||||
}}
|
||||
>
|
||||
<SortableContext items={values.map(({ id }) => id)} strategy={verticalListSortingStrategy}>
|
||||
<Stack gap="xs">
|
||||
{values.map((event) => (
|
||||
<SortableEvent
|
||||
key={event.id}
|
||||
kind={kind}
|
||||
event={event}
|
||||
timeZoneOptions={options.timeZoneOptions}
|
||||
onChange={(nextEvent) =>
|
||||
setValues(values.map((candidate) => (candidate.id === event.id ? nextEvent : candidate)))
|
||||
}
|
||||
onRemove={() => setValues(values.filter((candidate) => candidate.id !== event.id))}
|
||||
/>
|
||||
))}
|
||||
</Stack>
|
||||
</SortableContext>
|
||||
</DndContext>
|
||||
|
||||
<Text size="xs" c="dimmed">
|
||||
{tEditor("limit", { count: values.length, maximum: options.maxValues })}
|
||||
</Text>
|
||||
</Stack>
|
||||
</Fieldset>
|
||||
);
|
||||
};
|
||||
|
||||
interface SortableEventProps {
|
||||
kind: WidgetKind;
|
||||
event: OptionDateTimeEvent;
|
||||
timeZoneOptions: readonly { value: string; label: string }[];
|
||||
onChange: (event: OptionDateTimeEvent) => void;
|
||||
onRemove: () => void;
|
||||
}
|
||||
|
||||
const SortableEvent = ({ kind, event, timeZoneOptions, onChange, onRemove }: SortableEventProps) => {
|
||||
const t = useEventListTranslation(kind);
|
||||
const { attributes, listeners, setActivatorNodeRef, setNodeRef, transform, transition, isDragging } = useSortable({
|
||||
id: event.id,
|
||||
});
|
||||
const style = {
|
||||
transform: transform ? `translate3d(${Math.round(transform.x)}px, ${Math.round(transform.y)}px, 0)` : undefined,
|
||||
transition,
|
||||
opacity: isDragging ? 0.6 : undefined,
|
||||
zIndex: isDragging ? 1 : undefined,
|
||||
};
|
||||
const hasCurrentTimeZone = timeZoneOptions.some(({ value }) => value === event.timeZone);
|
||||
const selectableTimeZones = hasCurrentTimeZone
|
||||
? timeZoneOptions
|
||||
: [{ value: event.timeZone, label: t("unsupportedOption", { timeZone: event.timeZone }) }, ...timeZoneOptions];
|
||||
const targetValue = formatWallDateTime(event.targetUtc, event.timeZone);
|
||||
const startValue = event.startUtc ? formatWallDateTime(event.startUtc, event.timeZone) : null;
|
||||
|
||||
const changeTimeZone = (timeZone: string) => {
|
||||
const target = resolveWallDateTimeString(targetValue, timeZone);
|
||||
const start = startValue ? resolveWallDateTimeString(startValue, timeZone) : null;
|
||||
onChange({
|
||||
...event,
|
||||
timeZone,
|
||||
targetUtc: target?.toISOString() ?? event.targetUtc,
|
||||
startUtc: event.startUtc ? (start?.toISOString() ?? event.startUtc) : undefined,
|
||||
});
|
||||
};
|
||||
|
||||
const updateWallDateTime = (value: string | null, field: "targetUtc" | "startUtc") => {
|
||||
if (!value) return;
|
||||
const resolved = resolveWallDateTimeString(value, event.timeZone);
|
||||
if (!resolved) return;
|
||||
onChange({ ...event, [field]: resolved.toISOString() });
|
||||
};
|
||||
|
||||
return (
|
||||
<Card ref={setNodeRef} withBorder p="sm" style={style}>
|
||||
<Stack gap="xs">
|
||||
<Group gap="xs" wrap="nowrap" align="end">
|
||||
<ActionIcon
|
||||
ref={setActivatorNodeRef}
|
||||
{...attributes}
|
||||
{...listeners}
|
||||
variant="subtle"
|
||||
color="gray"
|
||||
size="lg"
|
||||
aria-label={t("reorder", { event: event.label })}
|
||||
style={{ cursor: "grab" }}
|
||||
>
|
||||
<IconGripVertical size="var(--mantine-font-size-lg)" />
|
||||
</ActionIcon>
|
||||
<TextInput
|
||||
flex={1}
|
||||
label={t("eventLabel")}
|
||||
value={event.label}
|
||||
maxLength={64}
|
||||
onChange={(changeEvent) => onChange({ ...event, label: changeEvent.currentTarget.value })}
|
||||
/>
|
||||
<ActionIcon
|
||||
color="red"
|
||||
variant="subtle"
|
||||
size="lg"
|
||||
aria-label={t("remove", { event: event.label })}
|
||||
onClick={onRemove}
|
||||
>
|
||||
<IconTrash size="var(--mantine-font-size-lg)" />
|
||||
</ActionIcon>
|
||||
</Group>
|
||||
|
||||
<Group align="end" grow>
|
||||
<Select
|
||||
label={t("timezone")}
|
||||
searchable
|
||||
data={selectableTimeZones}
|
||||
value={event.timeZone}
|
||||
onChange={(timeZone) => {
|
||||
if (timeZone) changeTimeZone(timeZone);
|
||||
}}
|
||||
/>
|
||||
<Select
|
||||
label={t("recurrence")}
|
||||
value={event.recurrence}
|
||||
data={(["none", "yearly"] as const).map((value) => ({ value, label: t(`recurrenceOption.${value}`) }))}
|
||||
onChange={(value) => {
|
||||
if (value) onChange({ ...event, recurrence: value as DateTimeEventRecurrence });
|
||||
}}
|
||||
/>
|
||||
</Group>
|
||||
|
||||
<ConfirmedDateTimePicker
|
||||
label={t("target")}
|
||||
value={targetValue || null}
|
||||
onChange={(value) => updateWallDateTime(value, "targetUtc")}
|
||||
confirmLabel={t("confirmDateTime")}
|
||||
/>
|
||||
|
||||
{event.recurrence === "none" && (
|
||||
<>
|
||||
<Switch
|
||||
label={t("trackProgress")}
|
||||
checked={event.startUtc !== undefined}
|
||||
onChange={(changeEvent) => {
|
||||
if (!changeEvent.currentTarget.checked) {
|
||||
const nextEvent = { ...event };
|
||||
delete nextEvent.startUtc;
|
||||
onChange(nextEvent);
|
||||
return;
|
||||
}
|
||||
onChange({ ...event, startUtc: new Date().toISOString() });
|
||||
}}
|
||||
/>
|
||||
{event.startUtc && (
|
||||
<ConfirmedDateTimePicker
|
||||
label={t("start")}
|
||||
value={startValue}
|
||||
onChange={(value) => updateWallDateTime(value, "startUtc")}
|
||||
confirmLabel={t("confirmDateTime")}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</Stack>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
|
||||
interface ConfirmedDateTimePickerProps {
|
||||
label: string;
|
||||
value: string | null;
|
||||
confirmLabel: string;
|
||||
onChange: (value: string | null) => void;
|
||||
}
|
||||
|
||||
const ConfirmedDateTimePicker = ({ label, value, confirmLabel, onChange }: ConfirmedDateTimePickerProps) => {
|
||||
const [draftValue, setDraftValue] = useState(value);
|
||||
|
||||
useEffect(() => setDraftValue(value), [value]);
|
||||
|
||||
const resetDraft = () => setDraftValue(value);
|
||||
const confirmDraft = () => {
|
||||
if (!draftValue) return;
|
||||
onChange(draftValue);
|
||||
};
|
||||
|
||||
return (
|
||||
<DateTimePicker
|
||||
label={label}
|
||||
value={draftValue}
|
||||
valueFormat="YYYY-MM-DD HH:mm"
|
||||
timePickerProps={{ withDropdown: true, popoverProps: { withinPortal: false } }}
|
||||
popoverProps={{ withinPortal: true }}
|
||||
submitButtonProps={{ "aria-label": confirmLabel, onClick: confirmDraft }}
|
||||
onChange={setDraftValue}
|
||||
onDropdownClose={resetDraft}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
type EventListTranslationKey =
|
||||
| "newEvent"
|
||||
| "add"
|
||||
| "remove"
|
||||
| "reorder"
|
||||
| "eventLabel"
|
||||
| "timezone"
|
||||
| "unsupportedOption"
|
||||
| "recurrence"
|
||||
| "recurrenceOption.none"
|
||||
| "recurrenceOption.yearly"
|
||||
| "target"
|
||||
| "trackProgress"
|
||||
| "start"
|
||||
| "confirmDateTime"
|
||||
| "limit";
|
||||
|
||||
type EventListTranslation = (key: EventListTranslationKey, values?: Record<string, string | number>) => string;
|
||||
|
||||
const useEventListTranslation = (kind: WidgetKind) =>
|
||||
useScopedI18n(`widget.${kind}.dateTimeEventList` as never) as unknown as EventListTranslation;
|
||||
@@ -1,45 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { Loader, MultiSelect } from "@mantine/core";
|
||||
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import type { CommonWidgetInputProps } from "./common";
|
||||
import { useWidgetInputTranslation } from "./common";
|
||||
import { useFormContext } from "./form";
|
||||
|
||||
export const WidgetDynamicMultiSelectInput = ({
|
||||
property,
|
||||
kind,
|
||||
options,
|
||||
}: CommonWidgetInputProps<"dynamicMultiSelect">) => {
|
||||
const t = useScopedI18n("widget.dynamicSelect");
|
||||
const tInput = useWidgetInputTranslation(kind, property);
|
||||
const form = useFormContext();
|
||||
const inputProps = form.getInputProps(`options.${property}`);
|
||||
const selectedValues = (inputProps.value as string[] | undefined) ?? [];
|
||||
const { data: selectData, isPending, isError } = options.useOptions();
|
||||
const data = [
|
||||
...selectData,
|
||||
...selectedValues
|
||||
.filter((selectedValue) => !selectData.some((option) => option.value === selectedValue))
|
||||
.map((selectedValue) => ({ value: selectedValue, label: selectedValue })),
|
||||
];
|
||||
|
||||
return (
|
||||
<MultiSelect
|
||||
{...inputProps}
|
||||
label={tInput("label")}
|
||||
description={options.withDescription ? tInput("description") : undefined}
|
||||
placeholder={isPending ? t("loading") : tInput("placeholder")}
|
||||
leftSection={isPending ? <Loader size="xs" /> : undefined}
|
||||
searchable
|
||||
clearable
|
||||
maxValues={options.maxValues}
|
||||
nothingFoundMessage={t("noResults")}
|
||||
data={data}
|
||||
disabled={isError}
|
||||
error={isError ? t("loadError") : inputProps.error}
|
||||
/>
|
||||
);
|
||||
};
|
||||
@@ -72,7 +72,6 @@ export const WidgetSelectInput = ({ property, kind, options }: CommonWidgetInput
|
||||
);
|
||||
}}
|
||||
description={options.withDescription ? tWidget("description") : undefined}
|
||||
placeholder={options.withPlaceholder ? tWidget("placeholder") : undefined}
|
||||
searchable={options.searchable}
|
||||
{...inputProps}
|
||||
/>
|
||||
|
||||
@@ -1,249 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import {
|
||||
closestCenter,
|
||||
DndContext,
|
||||
KeyboardSensor,
|
||||
MouseSensor,
|
||||
TouchSensor,
|
||||
useSensor,
|
||||
useSensors,
|
||||
} from "@dnd-kit/core";
|
||||
import {
|
||||
arrayMove,
|
||||
SortableContext,
|
||||
sortableKeyboardCoordinates,
|
||||
useSortable,
|
||||
verticalListSortingStrategy,
|
||||
} from "@dnd-kit/sortable";
|
||||
import { ActionIcon, Button, Card, Fieldset, Group, Select, Stack, Text, TextInput } from "@mantine/core";
|
||||
import { IconGripVertical, IconPlus, IconTrash } from "@tabler/icons-react";
|
||||
|
||||
import { createId } from "@homarr/common";
|
||||
import type { WidgetKind } from "@homarr/definitions";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import type { OptionTimezone } from "../options";
|
||||
import type { CommonWidgetInputProps } from "./common";
|
||||
import { useWidgetInputTranslation } from "./common";
|
||||
import { useFormContext } from "./form";
|
||||
|
||||
export const WidgetTimezoneListInput = ({ property, kind, options }: CommonWidgetInputProps<"timezoneList">) => {
|
||||
const t = useWidgetInputTranslation(kind, property);
|
||||
const tEditor = useTimezoneListTranslation(kind);
|
||||
const form = useFormContext();
|
||||
const fieldPath = `options.${property}`;
|
||||
const currentValue = form.values.options[property];
|
||||
const values = Array.isArray(currentValue) ? (currentValue as OptionTimezone[]) : options.defaultValue;
|
||||
const [selectedTimeZone, setSelectedTimeZone] = useState<string | null>(null);
|
||||
const sensors = useSensors(
|
||||
useSensor(MouseSensor),
|
||||
useSensor(TouchSensor),
|
||||
useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (Array.isArray(currentValue)) return;
|
||||
form.setFieldValue(fieldPath, options.defaultValue);
|
||||
}, [currentValue, fieldPath, form, options.defaultValue]);
|
||||
|
||||
const usedTimeZones = useMemo(() => new Set(values.map(({ timeZone }) => timeZone)), [values]);
|
||||
const availableOptions = options.timeZoneOptions.map((option) => ({
|
||||
...option,
|
||||
disabled: usedTimeZones.has(option.value),
|
||||
}));
|
||||
const isFull = values.length >= options.maxValues;
|
||||
|
||||
const setValues = (nextValues: OptionTimezone[]) => form.setFieldValue(fieldPath, nextValues);
|
||||
const addCity = (city: OptionTimezone) => {
|
||||
if (isFull || usedTimeZones.has(city.timeZone)) return;
|
||||
setValues([...values, city]);
|
||||
};
|
||||
const addSelectedTimeZone = () => {
|
||||
if (!selectedTimeZone) return;
|
||||
const option = options.timeZoneOptions.find(({ value }) => value === selectedTimeZone);
|
||||
if (!option) return;
|
||||
const label = option.label.replace(` (${option.value})`, "");
|
||||
addCity({ id: createId(), label, timeZone: option.value });
|
||||
setSelectedTimeZone(null);
|
||||
};
|
||||
|
||||
return (
|
||||
<Fieldset legend={t("label")}>
|
||||
<Stack gap="sm">
|
||||
{options.withDescription && (
|
||||
<Text size="sm" c="dimmed">
|
||||
{t("description")}
|
||||
</Text>
|
||||
)}
|
||||
|
||||
<Group gap="xs" align="end" wrap="nowrap">
|
||||
<Select
|
||||
flex={1}
|
||||
label={tEditor("timezone")}
|
||||
placeholder={tEditor("searchPlaceholder")}
|
||||
searchable
|
||||
clearable
|
||||
data={availableOptions}
|
||||
value={selectedTimeZone}
|
||||
onChange={setSelectedTimeZone}
|
||||
disabled={isFull}
|
||||
nothingFoundMessage={tEditor("noResults")}
|
||||
/>
|
||||
<Button
|
||||
leftSection={<IconPlus size="var(--mantine-font-size-md)" />}
|
||||
onClick={addSelectedTimeZone}
|
||||
disabled={isFull || selectedTimeZone === null}
|
||||
>
|
||||
{tEditor("add")}
|
||||
</Button>
|
||||
</Group>
|
||||
|
||||
<Group gap="xs">
|
||||
{options.presets.map((preset) => (
|
||||
<Button
|
||||
key={preset.timeZone}
|
||||
size="compact-xs"
|
||||
variant="light"
|
||||
disabled={isFull || usedTimeZones.has(preset.timeZone)}
|
||||
onClick={() => addCity({ ...preset, id: createId() })}
|
||||
>
|
||||
{preset.label}
|
||||
</Button>
|
||||
))}
|
||||
</Group>
|
||||
|
||||
<DndContext
|
||||
sensors={sensors}
|
||||
collisionDetection={closestCenter}
|
||||
onDragEnd={({ active, over }) => {
|
||||
if (!over || active.id === over.id) return;
|
||||
const activeIndex = values.findIndex(({ id }) => id === active.id);
|
||||
const overIndex = values.findIndex(({ id }) => id === over.id);
|
||||
if (activeIndex < 0 || overIndex < 0) return;
|
||||
setValues(arrayMove(values, activeIndex, overIndex));
|
||||
}}
|
||||
>
|
||||
<SortableContext items={values.map(({ id }) => id)} strategy={verticalListSortingStrategy}>
|
||||
<Stack gap="xs">
|
||||
{values.map((city) => (
|
||||
<SortableTimezone
|
||||
key={city.id}
|
||||
kind={kind}
|
||||
city={city}
|
||||
timeZoneOptions={options.timeZoneOptions}
|
||||
usedTimeZones={usedTimeZones}
|
||||
onChange={(nextCity) =>
|
||||
setValues(values.map((candidate) => (candidate.id === city.id ? nextCity : candidate)))
|
||||
}
|
||||
onRemove={() => setValues(values.filter((candidate) => candidate.id !== city.id))}
|
||||
/>
|
||||
))}
|
||||
</Stack>
|
||||
</SortableContext>
|
||||
</DndContext>
|
||||
|
||||
<Text size="xs" c="dimmed">
|
||||
{tEditor("limit", { count: values.length, maximum: options.maxValues })}
|
||||
</Text>
|
||||
</Stack>
|
||||
</Fieldset>
|
||||
);
|
||||
};
|
||||
|
||||
interface SortableTimezoneProps {
|
||||
kind: WidgetKind;
|
||||
city: OptionTimezone;
|
||||
timeZoneOptions: readonly { value: string; label: string }[];
|
||||
usedTimeZones: ReadonlySet<string>;
|
||||
onChange: (city: OptionTimezone) => void;
|
||||
onRemove: () => void;
|
||||
}
|
||||
|
||||
const SortableTimezone = ({
|
||||
kind,
|
||||
city,
|
||||
timeZoneOptions,
|
||||
usedTimeZones,
|
||||
onChange,
|
||||
onRemove,
|
||||
}: SortableTimezoneProps) => {
|
||||
const t = useTimezoneListTranslation(kind);
|
||||
const { attributes, listeners, setActivatorNodeRef, setNodeRef, transform, transition, isDragging } = useSortable({
|
||||
id: city.id,
|
||||
});
|
||||
const style = {
|
||||
transform: transform ? `translate3d(${Math.round(transform.x)}px, ${Math.round(transform.y)}px, 0)` : undefined,
|
||||
transition,
|
||||
opacity: isDragging ? 0.6 : undefined,
|
||||
zIndex: isDragging ? 1 : undefined,
|
||||
};
|
||||
const hasCurrentTimeZone = timeZoneOptions.some(({ value }) => value === city.timeZone);
|
||||
const selectableTimeZones = hasCurrentTimeZone
|
||||
? timeZoneOptions
|
||||
: [{ value: city.timeZone, label: t("unsupportedOption", { timeZone: city.timeZone }) }, ...timeZoneOptions];
|
||||
|
||||
return (
|
||||
<Card ref={setNodeRef} withBorder p="xs" style={style}>
|
||||
<Group gap="xs" wrap="wrap" align="end">
|
||||
<ActionIcon
|
||||
ref={setActivatorNodeRef}
|
||||
{...attributes}
|
||||
{...listeners}
|
||||
variant="subtle"
|
||||
color="gray"
|
||||
size="lg"
|
||||
aria-label={t("reorder", { city: city.label })}
|
||||
style={{ cursor: "grab" }}
|
||||
>
|
||||
<IconGripVertical size="var(--mantine-font-size-lg)" />
|
||||
</ActionIcon>
|
||||
<TextInput
|
||||
flex={1}
|
||||
label={t("cityLabel")}
|
||||
value={city.label}
|
||||
onChange={(event) => onChange({ ...city, label: event.currentTarget.value })}
|
||||
/>
|
||||
<Select
|
||||
flex={2}
|
||||
label={t("timezone")}
|
||||
searchable
|
||||
data={selectableTimeZones.map((option) => ({
|
||||
...option,
|
||||
disabled: option.value !== city.timeZone && usedTimeZones.has(option.value),
|
||||
}))}
|
||||
value={city.timeZone}
|
||||
onChange={(timeZone) => {
|
||||
if (timeZone) onChange({ ...city, timeZone });
|
||||
}}
|
||||
/>
|
||||
<ActionIcon
|
||||
color="red"
|
||||
variant="subtle"
|
||||
size="lg"
|
||||
aria-label={t("remove", { city: city.label })}
|
||||
onClick={onRemove}
|
||||
>
|
||||
<IconTrash size="var(--mantine-font-size-lg)" />
|
||||
</ActionIcon>
|
||||
</Group>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
|
||||
type TimezoneListTranslationKey =
|
||||
| "timezone"
|
||||
| "cityLabel"
|
||||
| "searchPlaceholder"
|
||||
| "noResults"
|
||||
| "unsupportedOption"
|
||||
| "add"
|
||||
| "remove"
|
||||
| "reorder"
|
||||
| "limit";
|
||||
|
||||
type TimezoneListTranslation = (key: TimezoneListTranslationKey, values?: Record<string, string | number>) => string;
|
||||
|
||||
const useTimezoneListTranslation = (kind: WidgetKind) =>
|
||||
useScopedI18n(`widget.${kind}.timezoneList` as never) as unknown as TimezoneListTranslation;
|
||||
@@ -1,399 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useId } from "react";
|
||||
import { CompositeChart, Sparkline } from "@mantine/charts";
|
||||
import { Box, Group, Paper, ScrollArea, SimpleGrid, Stack, Text, VisuallyHidden } from "@mantine/core";
|
||||
import { IconMapPin } from "@tabler/icons-react";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { useCurrentIntlLocale, useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import { WidgetEmptyState } from "../common/empty-state";
|
||||
import { formatLocalizedDate, formatLocalizedTime } from "../common/locale";
|
||||
import { getUsableWidgetQueryData, isInitialWidgetQueryPending } from "../common/query-state";
|
||||
import { WidgetQueryErrorIndicator, WidgetQueryLoadingState } from "../common/query-state-indicator";
|
||||
import type { WidgetComponentProps } from "../definition";
|
||||
import type { AirQualityData, PollutantKey, PollenKey } from "./display";
|
||||
import {
|
||||
getAqiCategory,
|
||||
getAqiColor,
|
||||
getAqiStandard,
|
||||
getAqiValue,
|
||||
getCompactAirQualityLayout,
|
||||
getDailyAqiValue,
|
||||
getDominantPollutant,
|
||||
getStrongestPollen,
|
||||
getUpcomingHours,
|
||||
getUvCategory,
|
||||
} from "./display";
|
||||
|
||||
export default function AirQualityWidget({ options, width, height, displayMode }: WidgetComponentProps<"airQuality">) {
|
||||
const t = useScopedI18n("widget.airQuality");
|
||||
const query = clientApi.widget.airQuality.atLocation.useQuery({
|
||||
latitude: options.location.latitude,
|
||||
longitude: options.location.longitude,
|
||||
});
|
||||
const airQuality = getUsableWidgetQueryData(query);
|
||||
|
||||
if (isInitialWidgetQueryPending(query)) return <WidgetQueryLoadingState />;
|
||||
if (!airQuality) return <WidgetEmptyState />;
|
||||
|
||||
return (
|
||||
<Box h="100%" w="100%" pos="relative">
|
||||
{displayMode === "advanced" ? (
|
||||
<AdvancedAirQuality airQuality={airQuality} options={options} width={width} />
|
||||
) : (
|
||||
<CompactAirQuality airQuality={airQuality} height={height} options={options} width={width} />
|
||||
)}
|
||||
{query.error && (
|
||||
<Box pos="absolute" top={4} right={4}>
|
||||
<WidgetQueryErrorIndicator error={query.error} label={t("name")} />
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
interface AirQualityViewProps {
|
||||
airQuality: AirQualityData;
|
||||
options: WidgetComponentProps<"airQuality">["options"];
|
||||
}
|
||||
|
||||
const CompactAirQuality = ({
|
||||
airQuality,
|
||||
height,
|
||||
options,
|
||||
width,
|
||||
}: AirQualityViewProps & { height: number; width: number }) => {
|
||||
const locale = useCurrentIntlLocale();
|
||||
const t = useScopedI18n("widget.airQuality");
|
||||
const layout = getCompactAirQualityLayout(width, height);
|
||||
const standard = getAqiStandard(options.aqiStandard, locale);
|
||||
const value = getAqiValue(airQuality.current, standard);
|
||||
const category = getAqiCategory(value, standard);
|
||||
const dominant = getDominantPollutant(airQuality.current, standard);
|
||||
const strongestPollen = getStrongestPollen(airQuality.current);
|
||||
const labels = useAirQualityLabels();
|
||||
const sixHours = getUpcomingHours(airQuality, 6)
|
||||
.map((hour) => getAqiValue(hour, standard))
|
||||
.filter((hour): hour is number => hour !== null);
|
||||
|
||||
return (
|
||||
<Stack
|
||||
h="100%"
|
||||
w="100%"
|
||||
justify="center"
|
||||
align="center"
|
||||
gap={layout.tiny ? 2 : "xs"}
|
||||
p="xs"
|
||||
style={{ overflow: "hidden" }}
|
||||
>
|
||||
<Group gap="xs" wrap="nowrap" align="center">
|
||||
<Text fz={layout.tiny ? 34 : 42} fw={700} lh={1} c={getAqiColor(category)}>
|
||||
{formatAqi(value, locale)}
|
||||
</Text>
|
||||
<Stack gap={1} align="flex-start">
|
||||
<Text size={layout.tiny ? "xs" : "sm"} fw={600}>
|
||||
{t(`category.${category}`)}
|
||||
</Text>
|
||||
</Stack>
|
||||
</Group>
|
||||
|
||||
{!layout.tiny && (
|
||||
<Group gap="md" justify="center" wrap="wrap">
|
||||
{options.showUv && (
|
||||
<MetricLine
|
||||
label={t("uv.label")}
|
||||
value={`${formatDecimal(airQuality.current.uvIndex, locale)} · ${t(`uv.category.${getUvCategory(airQuality.current.uvIndex)}`)}`}
|
||||
/>
|
||||
)}
|
||||
{options.showPollutants && dominant && (
|
||||
<MetricLine label={t("dominantPollutant")} value={labels.pollutants[dominant.key]} />
|
||||
)}
|
||||
</Group>
|
||||
)}
|
||||
|
||||
{!layout.tiny && layout.showParticulatesAndPollen && (
|
||||
<Group gap="md" justify="center" wrap="wrap">
|
||||
{options.showPollutants && (
|
||||
<>
|
||||
<MetricLine
|
||||
label={labels.pollutants.pm2_5}
|
||||
value={formatConcentration(airQuality.current.pollutants.pm2_5, locale, t)}
|
||||
/>
|
||||
<MetricLine
|
||||
label={labels.pollutants.pm10}
|
||||
value={formatConcentration(airQuality.current.pollutants.pm10, locale, t)}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
{options.showPollen && strongestPollen && (
|
||||
<MetricLine
|
||||
label={t("strongestPollen")}
|
||||
value={`${labels.pollen[strongestPollen.key]} · ${formatPollen(strongestPollen.value, locale, t)}`}
|
||||
/>
|
||||
)}
|
||||
</Group>
|
||||
)}
|
||||
|
||||
{!layout.tiny && layout.showSparkline && sixHours.length > 1 && (
|
||||
<Box component="figure" w="100%" h={34} m={0}>
|
||||
<Sparkline
|
||||
aria-hidden
|
||||
h="100%"
|
||||
w="100%"
|
||||
data={sixHours}
|
||||
color={getAqiColor(category)}
|
||||
curveType="monotone"
|
||||
fillOpacity={0.2}
|
||||
strokeWidth={2}
|
||||
/>
|
||||
<VisuallyHidden component="figcaption">{t("compact.sixHourTrend")}</VisuallyHidden>
|
||||
</Box>
|
||||
)}
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
const AdvancedAirQuality = ({ airQuality, options, width }: AirQualityViewProps & { width: number }) => {
|
||||
const chartId = useId();
|
||||
const locale = useCurrentIntlLocale();
|
||||
const t = useScopedI18n("widget.airQuality");
|
||||
const standard = getAqiStandard(options.aqiStandard, locale);
|
||||
const value = getAqiValue(airQuality.current, standard);
|
||||
const category = getAqiCategory(value, standard);
|
||||
const labels = useAirQualityLabels();
|
||||
const upcoming = getUpcomingHours(airQuality, 24);
|
||||
const chartData = upcoming.map((hour) => ({
|
||||
observedAt: hour.observedAt,
|
||||
aqi: getAqiValue(hour, standard) ?? Number.NaN,
|
||||
uv: hour.uvIndex ?? Number.NaN,
|
||||
}));
|
||||
const series = [
|
||||
{ name: "aqi", label: t("aqiLabel"), color: getAqiColor(category), type: "line" as const },
|
||||
...(options.showUv
|
||||
? [{ name: "uv", label: t("uv.label"), color: "yellow.7", type: "line" as const, yAxisId: "right" as const }]
|
||||
: []),
|
||||
];
|
||||
|
||||
return (
|
||||
<ScrollArea h="100%" w="100%" type="auto" offsetScrollbars scrollbarSize={6}>
|
||||
<Stack gap="md" p="md">
|
||||
<Group justify="space-between" align="flex-start" wrap="wrap">
|
||||
<Stack gap={2}>
|
||||
<Text fz={38} fw={700} lh={1} c={getAqiColor(category)}>
|
||||
{formatAqi(value, locale)}
|
||||
</Text>
|
||||
<Text fw={600}>{t(`category.${category}`)}</Text>
|
||||
</Stack>
|
||||
<Stack gap={2} align="flex-end">
|
||||
<Group gap={5} wrap="nowrap">
|
||||
<IconMapPin size="var(--mantine-font-size-md)" aria-hidden />
|
||||
<Text size="sm" fw={600}>
|
||||
{options.location.name}
|
||||
</Text>
|
||||
</Group>
|
||||
<Text size="xs" c="dimmed">
|
||||
{t("advanced.observedAt", {
|
||||
time: formatLocalizedTime(airQuality.current.observedAt, locale, { timeZone: airQuality.timezone }),
|
||||
})}
|
||||
</Text>
|
||||
</Stack>
|
||||
</Group>
|
||||
|
||||
<SimpleGrid cols={{ base: 2, sm: 4 }} spacing="xs">
|
||||
<MetricCard label={t("aqiLabel")} value={formatAqi(value, locale)} />
|
||||
{options.showUv && (
|
||||
<MetricCard label={t("uv.label")} value={formatDecimal(airQuality.current.uvIndex, locale)} />
|
||||
)}
|
||||
{options.showPollutants && (
|
||||
<>
|
||||
<MetricCard
|
||||
label={labels.pollutants.pm2_5}
|
||||
value={formatConcentration(airQuality.current.pollutants.pm2_5, locale, t)}
|
||||
/>
|
||||
<MetricCard
|
||||
label={labels.pollutants.pm10}
|
||||
value={formatConcentration(airQuality.current.pollutants.pm10, locale, t)}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</SimpleGrid>
|
||||
|
||||
<SimpleGrid cols={width >= 800 ? 2 : 1} spacing="md">
|
||||
<Paper withBorder p="sm">
|
||||
<Text id={chartId} size="sm" fw={600} mb="xs">
|
||||
{t("advanced.next24Hours")}
|
||||
</Text>
|
||||
{chartData.length > 0 ? (
|
||||
<>
|
||||
<Box aria-hidden>
|
||||
<CompositeChart
|
||||
h={220}
|
||||
data={chartData}
|
||||
dataKey="observedAt"
|
||||
series={series}
|
||||
curveType="monotone"
|
||||
gridAxis="y"
|
||||
tickLine="none"
|
||||
withDots={false}
|
||||
withLegend
|
||||
withRightYAxis={options.showUv}
|
||||
rightYAxisProps={{ width: 34 }}
|
||||
xAxisProps={{
|
||||
tickFormatter: (time: string) =>
|
||||
formatLocalizedTime(time, locale, { timeZone: airQuality.timezone }),
|
||||
}}
|
||||
/>
|
||||
</Box>
|
||||
<VisuallyHidden>
|
||||
<ul aria-labelledby={chartId}>
|
||||
{upcoming.map((hour) => (
|
||||
<li key={hour.observedAt}>
|
||||
{formatLocalizedTime(hour.observedAt, locale, { timeZone: airQuality.timezone })}:{" "}
|
||||
{t("advanced.aqiValue", {
|
||||
value: formatAqi(getAqiValue(hour, standard), locale),
|
||||
})}
|
||||
{options.showUv
|
||||
? `, ${t("advanced.uvValue", { value: formatDecimal(hour.uvIndex, locale) })}`
|
||||
: ""}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</VisuallyHidden>
|
||||
</>
|
||||
) : (
|
||||
<Text size="sm" c="dimmed">
|
||||
{t("advanced.noForecast")}
|
||||
</Text>
|
||||
)}
|
||||
</Paper>
|
||||
|
||||
<Stack gap="md">
|
||||
{options.showPollutants && (
|
||||
<Paper withBorder p="sm">
|
||||
<Text size="sm" fw={600} mb="xs">
|
||||
{t("advanced.pollutants")}
|
||||
</Text>
|
||||
<SimpleGrid cols={2} spacing="xs">
|
||||
{pollutantKeys.map((key) => (
|
||||
<MetricLine
|
||||
key={key}
|
||||
label={labels.pollutants[key]}
|
||||
value={formatConcentration(airQuality.current.pollutants[key], locale, t)}
|
||||
/>
|
||||
))}
|
||||
</SimpleGrid>
|
||||
</Paper>
|
||||
)}
|
||||
|
||||
{options.showPollen && hasAvailableValue(airQuality.current.pollen) && (
|
||||
<Paper withBorder p="sm">
|
||||
<Text size="sm" fw={600} mb="xs">
|
||||
{t("advanced.pollen")}
|
||||
</Text>
|
||||
<SimpleGrid cols={2} spacing="xs">
|
||||
{pollenKeys.map((key) => {
|
||||
const pollen = airQuality.current.pollen[key];
|
||||
if (pollen === null) return null;
|
||||
return <MetricLine key={key} label={labels.pollen[key]} value={formatPollen(pollen, locale, t)} />;
|
||||
})}
|
||||
</SimpleGrid>
|
||||
</Paper>
|
||||
)}
|
||||
</Stack>
|
||||
</SimpleGrid>
|
||||
|
||||
<Paper withBorder p="sm">
|
||||
<Text size="sm" fw={600} mb="xs">
|
||||
{t("advanced.sevenDayForecast")}
|
||||
</Text>
|
||||
<SimpleGrid cols={{ base: 2, sm: 4, md: 7 }} spacing="xs">
|
||||
{airQuality.daily.map((day) => {
|
||||
const dailyAqi = getDailyAqiValue(day, standard);
|
||||
return (
|
||||
<Stack key={day.date} gap={2} align="center">
|
||||
<Text size="xs" c="dimmed">
|
||||
{formatLocalizedDate(day.date, locale, { weekday: "short" })}
|
||||
</Text>
|
||||
<Text fw={700} c={getAqiColor(getAqiCategory(dailyAqi, standard))}>
|
||||
{formatAqi(dailyAqi, locale)}
|
||||
</Text>
|
||||
{options.showUv && (
|
||||
<Text size="xs">{t("advanced.uvShort", { value: formatDecimal(day.uvIndexMax, locale) })}</Text>
|
||||
)}
|
||||
</Stack>
|
||||
);
|
||||
})}
|
||||
</SimpleGrid>
|
||||
</Paper>
|
||||
</Stack>
|
||||
</ScrollArea>
|
||||
);
|
||||
};
|
||||
|
||||
const MetricCard = ({ label, value }: { label: string; value: string }) => (
|
||||
<Paper withBorder p="xs">
|
||||
<Text size="xs" c="dimmed">
|
||||
{label}
|
||||
</Text>
|
||||
<Text fz="lg" fw={700}>
|
||||
{value}
|
||||
</Text>
|
||||
</Paper>
|
||||
);
|
||||
|
||||
const MetricLine = ({ label, value }: { label: string; value: string }) => (
|
||||
<Stack gap={0} miw={0}>
|
||||
<Text size="xs" c="dimmed" truncate>
|
||||
{label}
|
||||
</Text>
|
||||
<Text size="sm" fw={600} truncate>
|
||||
{value}
|
||||
</Text>
|
||||
</Stack>
|
||||
);
|
||||
|
||||
const pollutantKeys: PollutantKey[] = ["pm2_5", "pm10", "ozone", "nitrogenDioxide", "sulphurDioxide", "carbonMonoxide"];
|
||||
const pollenKeys: PollenKey[] = ["alder", "birch", "grass", "mugwort", "olive", "ragweed"];
|
||||
|
||||
const useAirQualityLabels = () => {
|
||||
const t = useScopedI18n("widget.airQuality");
|
||||
return {
|
||||
pollutants: {
|
||||
pm2_5: t("pollutant.pm2_5"),
|
||||
pm10: t("pollutant.pm10"),
|
||||
ozone: t("pollutant.ozone"),
|
||||
nitrogenDioxide: t("pollutant.nitrogenDioxide"),
|
||||
sulphurDioxide: t("pollutant.sulphurDioxide"),
|
||||
carbonMonoxide: t("pollutant.carbonMonoxide"),
|
||||
} satisfies Record<PollutantKey, string>,
|
||||
pollen: {
|
||||
alder: t("pollen.alder"),
|
||||
birch: t("pollen.birch"),
|
||||
grass: t("pollen.grass"),
|
||||
mugwort: t("pollen.mugwort"),
|
||||
olive: t("pollen.olive"),
|
||||
ragweed: t("pollen.ragweed"),
|
||||
} satisfies Record<PollenKey, string>,
|
||||
};
|
||||
};
|
||||
|
||||
const formatAqi = (value: number | null, locale: string) => {
|
||||
if (value === null) return "—";
|
||||
return new Intl.NumberFormat(locale, { maximumFractionDigits: 0 }).format(value);
|
||||
};
|
||||
|
||||
const formatDecimal = (value: number | null, locale: string) => {
|
||||
if (value === null) return "—";
|
||||
return new Intl.NumberFormat(locale, { maximumFractionDigits: 1 }).format(value);
|
||||
};
|
||||
|
||||
type ScopedAirQualityTranslator = ReturnType<typeof useScopedI18n<"widget.airQuality">>;
|
||||
|
||||
const formatConcentration = (value: number | null, locale: string, t: ScopedAirQualityTranslator) =>
|
||||
t("unit.concentration", { value: formatDecimal(value, locale) });
|
||||
const formatPollen = (value: number | null, locale: string, t: ScopedAirQualityTranslator) =>
|
||||
t("unit.pollen", { value: formatDecimal(value, locale) });
|
||||
const hasAvailableValue = (values: Record<string, number | null>) =>
|
||||
Object.values(values).some((value) => value !== null);
|
||||
@@ -1,64 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
getAqiCategory,
|
||||
getAqiStandard,
|
||||
getCompactAirQualityLayout,
|
||||
getDominantPollutant,
|
||||
getStrongestPollen,
|
||||
} from "./display";
|
||||
|
||||
const point = {
|
||||
observedAt: "2026-07-01T10:00:00.000Z",
|
||||
europeanAqi: 42,
|
||||
usAqi: 60,
|
||||
uvIndex: 4,
|
||||
pollutants: { pm2_5: 12, pm10: 20, ozone: 30, nitrogenDioxide: 4, sulphurDioxide: 3, carbonMonoxide: 100 },
|
||||
europeanSubIndices: {
|
||||
pm2_5: 20,
|
||||
pm10: 31,
|
||||
ozone: 42,
|
||||
nitrogenDioxide: 10,
|
||||
sulphurDioxide: 5,
|
||||
carbonMonoxide: null,
|
||||
},
|
||||
usSubIndices: {
|
||||
pm2_5: 50,
|
||||
pm10: 40,
|
||||
ozone: 30,
|
||||
nitrogenDioxide: 20,
|
||||
sulphurDioxide: 10,
|
||||
carbonMonoxide: 60,
|
||||
},
|
||||
pollen: { alder: null, birch: 12, grass: 20, mugwort: 5, olive: null, ragweed: 2 },
|
||||
};
|
||||
|
||||
describe("air quality display", () => {
|
||||
it("uses the US scale only for US locales in automatic mode", () => {
|
||||
expect(getAqiStandard("auto", "en-US")).toBe("us");
|
||||
expect(getAqiStandard("auto", "fr-FR")).toBe("european");
|
||||
expect(getAqiStandard("auto", "en")).toBe("european");
|
||||
expect(getAqiStandard("us", "fr-FR")).toBe("us");
|
||||
});
|
||||
|
||||
it("uses the defined AQI band boundaries", () => {
|
||||
expect(getAqiCategory(20, "european")).toBe("good");
|
||||
expect(getAqiCategory(21, "european")).toBe("fair");
|
||||
expect(getAqiCategory(101, "european")).toBe("extremelyPoor");
|
||||
expect(getAqiCategory(50, "us")).toBe("good");
|
||||
expect(getAqiCategory(51, "us")).toBe("moderate");
|
||||
expect(getAqiCategory(301, "us")).toBe("hazardous");
|
||||
});
|
||||
|
||||
it("finds dominant subindices and raw pollen without combining them", () => {
|
||||
expect(getDominantPollutant(point, "european")).toEqual({ key: "ozone", value: 42 });
|
||||
expect(getDominantPollutant(point, "us")).toEqual({ key: "carbonMonoxide", value: 60 });
|
||||
expect(getStrongestPollen(point)).toEqual({ key: "grass", value: 20 });
|
||||
});
|
||||
|
||||
it("progressively reveals compact details", () => {
|
||||
expect(getCompactAirQualityLayout(149, 200)).toMatchObject({ tiny: true });
|
||||
expect(getCompactAirQualityLayout(250, 150)).toMatchObject({ showParticulatesAndPollen: true });
|
||||
expect(getCompactAirQualityLayout(300, 170)).toMatchObject({ showSparkline: true });
|
||||
});
|
||||
});
|
||||
@@ -1,144 +0,0 @@
|
||||
export interface AirQualityPollutants {
|
||||
pm2_5: number | null;
|
||||
pm10: number | null;
|
||||
ozone: number | null;
|
||||
nitrogenDioxide: number | null;
|
||||
sulphurDioxide: number | null;
|
||||
carbonMonoxide: number | null;
|
||||
}
|
||||
|
||||
export interface AirQualityPoint {
|
||||
observedAt: string;
|
||||
europeanAqi: number | null;
|
||||
usAqi: number | null;
|
||||
uvIndex: number | null;
|
||||
pollutants: AirQualityPollutants;
|
||||
europeanSubIndices: AirQualityPollutants;
|
||||
usSubIndices: AirQualityPollutants;
|
||||
pollen: Record<"alder" | "birch" | "grass" | "mugwort" | "olive" | "ragweed", number | null>;
|
||||
}
|
||||
|
||||
export interface AirQualityData {
|
||||
timezone: string;
|
||||
utcOffsetSeconds: number;
|
||||
current: AirQualityPoint;
|
||||
hourly: AirQualityPoint[];
|
||||
daily: {
|
||||
date: string;
|
||||
europeanAqiMax: number | null;
|
||||
usAqiMax: number | null;
|
||||
uvIndexMax: number | null;
|
||||
pm2_5Max: number | null;
|
||||
pm10Max: number | null;
|
||||
}[];
|
||||
}
|
||||
|
||||
export type AqiStandard = "european" | "us";
|
||||
export type AqiStandardOption = "auto" | AqiStandard;
|
||||
export type AqiCategory =
|
||||
| "good"
|
||||
| "fair"
|
||||
| "moderate"
|
||||
| "unhealthySensitive"
|
||||
| "unhealthy"
|
||||
| "poor"
|
||||
| "veryPoor"
|
||||
| "veryUnhealthy"
|
||||
| "extremelyPoor"
|
||||
| "hazardous"
|
||||
| "unknown";
|
||||
export type UvCategory = "low" | "moderate" | "high" | "veryHigh" | "extreme" | "unknown";
|
||||
export type PollutantKey = keyof AirQualityPoint["pollutants"];
|
||||
export type PollenKey = keyof AirQualityPoint["pollen"];
|
||||
|
||||
export const getAqiStandard = (option: AqiStandardOption, locale: string): AqiStandard => {
|
||||
if (option !== "auto") return option;
|
||||
try {
|
||||
return new Intl.Locale(locale).region === "US" ? "us" : "european";
|
||||
} catch {
|
||||
return "european";
|
||||
}
|
||||
};
|
||||
|
||||
export const getAqiValue = (point: AirQualityPoint, standard: AqiStandard): number | null => {
|
||||
if (standard === "us") return point.usAqi;
|
||||
return point.europeanAqi;
|
||||
};
|
||||
|
||||
export const getDailyAqiValue = (day: AirQualityData["daily"][number], standard: AqiStandard): number | null => {
|
||||
if (standard === "us") return day.usAqiMax;
|
||||
return day.europeanAqiMax;
|
||||
};
|
||||
|
||||
export const getAqiCategory = (value: number | null, standard: AqiStandard): AqiCategory => {
|
||||
if (value === null) return "unknown";
|
||||
|
||||
if (standard === "us") {
|
||||
if (value <= 50) return "good";
|
||||
if (value <= 100) return "moderate";
|
||||
if (value <= 150) return "unhealthySensitive";
|
||||
if (value <= 200) return "unhealthy";
|
||||
if (value <= 300) return "veryUnhealthy";
|
||||
return "hazardous";
|
||||
}
|
||||
|
||||
if (value <= 20) return "good";
|
||||
if (value <= 40) return "fair";
|
||||
if (value <= 60) return "moderate";
|
||||
if (value <= 80) return "poor";
|
||||
if (value <= 100) return "veryPoor";
|
||||
return "extremelyPoor";
|
||||
};
|
||||
|
||||
export const getAqiColor = (category: AqiCategory): string => {
|
||||
if (category === "good") return "green.6";
|
||||
if (category === "fair") return "lime.7";
|
||||
if (category === "moderate") return "yellow.7";
|
||||
if (category === "unhealthySensitive" || category === "poor") return "orange.7";
|
||||
if (category === "unhealthy" || category === "veryPoor") return "red.7";
|
||||
if (category === "veryUnhealthy" || category === "extremelyPoor") return "grape.7";
|
||||
if (category === "hazardous") return "dark.6";
|
||||
return "gray.6";
|
||||
};
|
||||
|
||||
export const getUvCategory = (value: number | null): UvCategory => {
|
||||
if (value === null) return "unknown";
|
||||
if (value < 3) return "low";
|
||||
if (value < 6) return "moderate";
|
||||
if (value < 8) return "high";
|
||||
if (value < 11) return "veryHigh";
|
||||
return "extreme";
|
||||
};
|
||||
|
||||
export const getDominantPollutant = (
|
||||
point: AirQualityPoint,
|
||||
standard: AqiStandard,
|
||||
): { key: PollutantKey; value: number } | null => {
|
||||
const values = standard === "us" ? point.usSubIndices : point.europeanSubIndices;
|
||||
return getHighestValue(values);
|
||||
};
|
||||
|
||||
export const getStrongestPollen = (point: AirQualityPoint): { key: PollenKey; value: number } | null =>
|
||||
getHighestValue(point.pollen);
|
||||
|
||||
const getHighestValue = <TKey extends string>(
|
||||
values: Record<TKey, number | null>,
|
||||
): { key: TKey; value: number } | null => {
|
||||
let highest: { key: TKey; value: number } | null = null;
|
||||
for (const [key, value] of Object.entries(values) as [TKey, number | null][]) {
|
||||
if (value === null) continue;
|
||||
if (highest === null || value > highest.value) highest = { key, value };
|
||||
}
|
||||
return highest;
|
||||
};
|
||||
|
||||
export const getCompactAirQualityLayout = (width: number, height: number) => ({
|
||||
tiny: width < 150 || height < 96,
|
||||
showParticulatesAndPollen: width >= 240 && height >= 140,
|
||||
showSparkline: width >= 300 && height >= 170,
|
||||
});
|
||||
|
||||
export const getUpcomingHours = (data: AirQualityData, count: number): AirQualityData["hourly"] => {
|
||||
const currentTime = Date.parse(data.current.observedAt);
|
||||
return data.hourly.filter((hour) => Date.parse(hour.observedAt) >= currentTime).slice(0, count);
|
||||
};
|
||||
@@ -1,43 +0,0 @@
|
||||
import { IconWind } from "@tabler/icons-react";
|
||||
|
||||
import { createWidgetDefinition, widgetQueryInputMatches } from "../definition";
|
||||
import { optionsBuilder } from "../options";
|
||||
|
||||
export const { definition, componentLoader } = createWidgetDefinition("airQuality", {
|
||||
icon: IconWind,
|
||||
supportsAdvancedFocus: true,
|
||||
queryKey: [["widget", "airQuality", "atLocation"]],
|
||||
refetchInterval: 900,
|
||||
queryMatcher: ({ input }, scope) => {
|
||||
const location = scope.options.location;
|
||||
if (location === null || typeof location !== "object" || !("latitude" in location) || !("longitude" in location)) {
|
||||
return false;
|
||||
}
|
||||
return widgetQueryInputMatches(input, {
|
||||
latitude: location.latitude,
|
||||
longitude: location.longitude,
|
||||
});
|
||||
},
|
||||
createOptions() {
|
||||
return optionsBuilder.from((factory) => ({
|
||||
location: factory.location({
|
||||
defaultValue: {
|
||||
name: "Paris",
|
||||
latitude: 48.85341,
|
||||
longitude: 2.3488,
|
||||
},
|
||||
}),
|
||||
aqiStandard: factory.select({
|
||||
defaultValue: "auto",
|
||||
options: [
|
||||
{ value: "auto", label: (t) => t("widget.airQuality.option.aqiStandard.options.auto") },
|
||||
{ value: "european", label: (t) => t("widget.airQuality.option.aqiStandard.options.european") },
|
||||
{ value: "us", label: (t) => t("widget.airQuality.option.aqiStandard.options.us") },
|
||||
],
|
||||
}),
|
||||
showUv: factory.switch({ defaultValue: true }),
|
||||
showPollutants: factory.switch({ defaultValue: true }),
|
||||
showPollen: factory.switch({ defaultValue: true }),
|
||||
}));
|
||||
},
|
||||
}).withDynamicImport(() => import("./component"));
|
||||
@@ -15,18 +15,15 @@ import {
|
||||
IconBuildingBank,
|
||||
IconBusStop,
|
||||
IconCalendar,
|
||||
IconCalendarWeek,
|
||||
IconChartAreaLine,
|
||||
IconChartBar,
|
||||
IconClock,
|
||||
IconClockPlay,
|
||||
IconCloud,
|
||||
IconDeviceCctv,
|
||||
IconDeviceGamepad,
|
||||
IconDownload,
|
||||
IconFileText,
|
||||
IconGraphFilled,
|
||||
IconHourglass,
|
||||
IconHeadphones,
|
||||
IconHeartRateMonitor,
|
||||
IconHeartbeat,
|
||||
@@ -50,7 +47,6 @@ import {
|
||||
IconTransform,
|
||||
IconVideo,
|
||||
IconWall,
|
||||
IconWind,
|
||||
IconZoomQuestion,
|
||||
} from "@tabler/icons-react";
|
||||
|
||||
@@ -60,10 +56,6 @@ import type { TablerIcon } from "@homarr/ui";
|
||||
export const widgetCatalogIcons: Record<WidgetKind, TablerIcon> = {
|
||||
clock: IconClock,
|
||||
weather: IconCloud,
|
||||
today: IconCalendarWeek,
|
||||
airQuality: IconWind,
|
||||
countdown: IconHourglass,
|
||||
timer: IconClockPlay,
|
||||
app: IconApps,
|
||||
assistant: IconRobot,
|
||||
iframe: IconBrowser,
|
||||
|
||||
@@ -1,329 +0,0 @@
|
||||
import {
|
||||
Alert,
|
||||
Badge,
|
||||
Box,
|
||||
Divider,
|
||||
Group,
|
||||
Paper,
|
||||
ScrollArea,
|
||||
SimpleGrid,
|
||||
Stack,
|
||||
Text,
|
||||
ThemeIcon,
|
||||
Title,
|
||||
} from "@mantine/core";
|
||||
import { IconAlertTriangle, IconClock } from "@tabler/icons-react";
|
||||
import type { Dayjs } from "dayjs";
|
||||
|
||||
import { useCurrentIntlLocale, useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import { formatLocalizedDate, formatLocalizedTime } from "../common/locale";
|
||||
import type { WidgetComponentProps } from "../definition";
|
||||
import { clockTimeFormatShowsSeconds, clockTimeFormatUses12Hours, resolveClockTimeFormat } from "./format";
|
||||
import { TimeOfDayBar } from "./time-of-day-bar";
|
||||
import { ClockWeatherSummary } from "./weather-summary";
|
||||
import {
|
||||
createWorldClockTime,
|
||||
formatRelativeOffset,
|
||||
formatUtcOffset,
|
||||
getTimeOfDayPhase,
|
||||
humanizeTimeZone,
|
||||
maximumWorldClockCities,
|
||||
} from "./world-clock";
|
||||
import type { TimeOfDayPhase, WorldClockTime } from "./world-clock";
|
||||
|
||||
interface AdvancedClockViewProps {
|
||||
now: Date;
|
||||
options: WidgetComponentProps<"clock">["options"];
|
||||
primaryTime: Dayjs;
|
||||
primaryTimeZone: string;
|
||||
primaryTimeZoneInvalid: boolean;
|
||||
}
|
||||
|
||||
export const AdvancedClockView = ({
|
||||
now,
|
||||
options,
|
||||
primaryTime,
|
||||
primaryTimeZone,
|
||||
primaryTimeZoneInvalid,
|
||||
}: AdvancedClockViewProps) => {
|
||||
const t = useScopedI18n("widget.clock");
|
||||
const primaryLabel = getPrimaryLabel(options, t);
|
||||
const primary: WorldClockTime = {
|
||||
id: "primary",
|
||||
label: primaryLabel,
|
||||
timeZone: primaryTimeZone,
|
||||
zonedTime: primaryTime,
|
||||
phase: getTimeOfDayPhase(primaryTime.hour()),
|
||||
minuteOfDay: primaryTime.hour() * 60 + primaryTime.minute() + primaryTime.second() / 60,
|
||||
utcOffset: primaryTime.utcOffset(),
|
||||
dayDifference: 0,
|
||||
};
|
||||
const cities = options.worldClockCities
|
||||
.slice(0, maximumWorldClockCities)
|
||||
.filter(({ timeZone }) => timeZone !== primaryTimeZone)
|
||||
.map((city) => createWorldClockTime({ city, now, primaryTime }));
|
||||
|
||||
return (
|
||||
<ScrollArea
|
||||
h="100%"
|
||||
w="100%"
|
||||
type="auto"
|
||||
offsetScrollbars
|
||||
scrollbarSize={6}
|
||||
aria-label={t("worldClock.advancedLabel")}
|
||||
>
|
||||
<Stack gap="md" p={{ base: "sm", sm: "md" }}>
|
||||
{primaryTimeZoneInvalid && (
|
||||
<Alert icon={<IconAlertTriangle />} color="yellow" title={t("worldClock.unsupportedPrimaryTitle")}>
|
||||
{t("worldClock.unsupportedPrimary", { timeZone: options.timezone })}
|
||||
</Alert>
|
||||
)}
|
||||
<PrimaryClock now={now} options={options} primary={primary} />
|
||||
<OverviewMode now={now} options={options} primary={primary} cities={cities} />
|
||||
</Stack>
|
||||
</ScrollArea>
|
||||
);
|
||||
};
|
||||
|
||||
interface ModeProps {
|
||||
now: Date;
|
||||
options: WidgetComponentProps<"clock">["options"];
|
||||
primary: WorldClockTime;
|
||||
cities: WorldClockTime[];
|
||||
}
|
||||
|
||||
const PrimaryClock = ({ now, options, primary }: Pick<ModeProps, "now" | "options" | "primary">) => {
|
||||
const locale = useCurrentIntlLocale();
|
||||
const t = useScopedI18n("widget.clock");
|
||||
const primaryTime = primary.zonedTime;
|
||||
if (!primaryTime || primary.phase === null || primary.minuteOfDay === null) return null;
|
||||
|
||||
return (
|
||||
<Paper withBorder radius="md" p="md">
|
||||
<Group justify="space-between" align="flex-start" gap="lg" wrap="wrap">
|
||||
<Stack gap={5} miw={0}>
|
||||
<Group gap="xs" wrap="nowrap">
|
||||
<ThemeIcon color={getPhaseColor(primary.phase)} variant="light" radius="xl" size="md">
|
||||
<IconClock size={16} />
|
||||
</ThemeIcon>
|
||||
<Title order={2} size="h4" fw={600}>
|
||||
{primary.label}
|
||||
</Title>
|
||||
</Group>
|
||||
<ClockTime entry={primary} now={now} options={options} primary />
|
||||
{options.showDate && (
|
||||
<Text size="sm" c="dimmed">
|
||||
{formatLocalizedDate(now, locale, { dateStyle: "full", timeZone: primary.timeZone })}
|
||||
</Text>
|
||||
)}
|
||||
<Group gap="xs" wrap="wrap">
|
||||
<Badge color="gray" variant="light" tt="none">
|
||||
{primary.timeZone}
|
||||
</Badge>
|
||||
<Badge color="gray" variant="outline" tt="none">
|
||||
{formatUtcOffset(primaryTime.utcOffset())}
|
||||
</Badge>
|
||||
</Group>
|
||||
</Stack>
|
||||
{options.showWeather && (
|
||||
<Paper withBorder radius="md" p="sm">
|
||||
<ClockWeatherSummary
|
||||
latitude={options.weatherLocation.latitude}
|
||||
longitude={options.weatherLocation.longitude}
|
||||
locationName={options.weatherLocation.name}
|
||||
isFahrenheit={options.isWeatherFormatFahrenheit}
|
||||
animateIcon={options.animateWeatherIcon}
|
||||
detailed
|
||||
/>
|
||||
</Paper>
|
||||
)}
|
||||
</Group>
|
||||
<Divider my="sm" />
|
||||
<TimeOfDayBar
|
||||
minuteOfDay={primary.minuteOfDay}
|
||||
phase={primary.phase}
|
||||
showLegend
|
||||
showTicks
|
||||
label={t("worldClock.timeBarLabel", { city: primary.label })}
|
||||
/>
|
||||
</Paper>
|
||||
);
|
||||
};
|
||||
|
||||
const OverviewMode = ({ now, options, primary, cities }: ModeProps) => {
|
||||
const t = useScopedI18n("widget.clock");
|
||||
if (cities.length === 0) return <EmptyCities />;
|
||||
|
||||
return (
|
||||
<Stack gap="xs">
|
||||
<Group justify="space-between" align="baseline">
|
||||
<Title order={3} size="h5">
|
||||
{t("worldClock.cities")}
|
||||
</Title>
|
||||
<Text size="xs" c="dimmed">
|
||||
{t("worldClock.cityCount", { count: cities.length })}
|
||||
</Text>
|
||||
</Group>
|
||||
<SimpleGrid component="ul" cols={{ base: 1, sm: 2 }} spacing="sm" p={0} m={0} style={{ listStyle: "none" }}>
|
||||
{cities.map((city) => (
|
||||
<WorldClockCard
|
||||
key={city.id}
|
||||
entry={city}
|
||||
now={now}
|
||||
options={options}
|
||||
primaryOffset={primary.utcOffset ?? 0}
|
||||
/>
|
||||
))}
|
||||
</SimpleGrid>
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
interface ClockEntryProps {
|
||||
entry: WorldClockTime;
|
||||
now: Date;
|
||||
options: WidgetComponentProps<"clock">["options"];
|
||||
primaryOffset: number;
|
||||
}
|
||||
|
||||
const WorldClockCard = ({ entry, now, options, primaryOffset }: ClockEntryProps) => {
|
||||
if (!entry.zonedTime || entry.utcOffset === null) {
|
||||
return <InvalidTimeZone entry={entry} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<Paper component="li" withBorder radius="md" p="md">
|
||||
<Stack gap="sm">
|
||||
<Stack gap={0} miw={0}>
|
||||
<Text fw={600} truncate>
|
||||
{entry.label}
|
||||
</Text>
|
||||
<Text size="xs" c="dimmed" truncate>
|
||||
{entry.timeZone}
|
||||
</Text>
|
||||
</Stack>
|
||||
<ClockTime entry={entry} now={now} options={options} compact />
|
||||
<DayAndOffset entry={entry} now={now} primaryOffset={primaryOffset} />
|
||||
</Stack>
|
||||
</Paper>
|
||||
);
|
||||
};
|
||||
|
||||
const ClockTime = ({
|
||||
entry,
|
||||
now,
|
||||
options,
|
||||
primary = false,
|
||||
compact = false,
|
||||
}: Omit<ClockEntryProps, "primaryOffset"> & { primary?: boolean; compact?: boolean }) => {
|
||||
const locale = useCurrentIntlLocale();
|
||||
const t = useScopedI18n("widget.clock");
|
||||
if (!entry.zonedTime) return null;
|
||||
let formattedTime = formatLocalizedTime(now, locale, {
|
||||
hour12: clockTimeFormatUses12Hours(options.customTimeFormat, options.is24HourFormat),
|
||||
includeSeconds: clockTimeFormatShowsSeconds(options.customTimeFormat),
|
||||
timeZone: entry.timeZone,
|
||||
});
|
||||
if (primary) {
|
||||
formattedTime = entry.zonedTime.format(resolveClockTimeFormat(options.customTimeFormat, options.is24HourFormat));
|
||||
}
|
||||
const accessibleDate = formatLocalizedDate(now, locale, {
|
||||
dateStyle: "medium",
|
||||
timeZone: entry.timeZone,
|
||||
});
|
||||
const fontSize = compact ? { base: 30, sm: 34 } : { base: 44, sm: 56 };
|
||||
|
||||
return (
|
||||
<Text
|
||||
component="time"
|
||||
dateTime={now.toISOString()}
|
||||
fz={fontSize}
|
||||
fw={700}
|
||||
ff="var(--mantine-font-family-monospace)"
|
||||
lh={1}
|
||||
lts="-0.04em"
|
||||
aria-label={t("worldClock.accessibleTime", {
|
||||
city: entry.label,
|
||||
time: formattedTime,
|
||||
date: accessibleDate,
|
||||
timeZone: entry.timeZone,
|
||||
})}
|
||||
>
|
||||
{formattedTime}
|
||||
</Text>
|
||||
);
|
||||
};
|
||||
|
||||
const DayAndOffset = ({ entry, now, primaryOffset }: Pick<ClockEntryProps, "entry" | "now" | "primaryOffset">) => {
|
||||
const locale = useCurrentIntlLocale();
|
||||
const t = useScopedI18n("widget.clock");
|
||||
if (entry.dayDifference === null || entry.utcOffset === null) return null;
|
||||
const dayRelation = getDayRelation(entry.dayDifference, t);
|
||||
const date = formatLocalizedDate(now, locale, {
|
||||
weekday: "short",
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
timeZone: entry.timeZone,
|
||||
});
|
||||
|
||||
return (
|
||||
<Group gap="xs" wrap="wrap">
|
||||
<Badge color="gray" variant="light" size="sm" tt="none">
|
||||
{date} · {dayRelation}
|
||||
</Badge>
|
||||
<Text size="xs" c="dimmed">
|
||||
{formatRelativeOffset(entry.utcOffset - primaryOffset)} · {formatUtcOffset(entry.utcOffset)}
|
||||
</Text>
|
||||
</Group>
|
||||
);
|
||||
};
|
||||
|
||||
const InvalidTimeZone = ({ entry }: { entry: WorldClockTime }) => {
|
||||
const t = useScopedI18n("widget.clock");
|
||||
return (
|
||||
<Paper component="li" withBorder radius="md" p="md">
|
||||
<Group gap="xs" wrap="nowrap">
|
||||
<IconAlertTriangle color="var(--mantine-color-yellow-6)" aria-hidden />
|
||||
<Box>
|
||||
<Text fw={600}>{entry.label}</Text>
|
||||
<Text size="xs" c="dimmed">
|
||||
{t("worldClock.unsupportedTimeZone", { timeZone: entry.timeZone })}
|
||||
</Text>
|
||||
</Box>
|
||||
</Group>
|
||||
</Paper>
|
||||
);
|
||||
};
|
||||
|
||||
const EmptyCities = () => {
|
||||
const t = useScopedI18n("widget.clock");
|
||||
return (
|
||||
<Paper withBorder radius="md" p="xl">
|
||||
<Text c="dimmed" ta="center">
|
||||
{t("worldClock.noSecondaryCities")}
|
||||
</Text>
|
||||
</Paper>
|
||||
);
|
||||
};
|
||||
|
||||
type ScopedClockTranslator = ReturnType<typeof useScopedI18n<"widget.clock">>;
|
||||
|
||||
const getDayRelation = (difference: number, t: ScopedClockTranslator) => {
|
||||
if (difference < 0) return t("worldClock.yesterday");
|
||||
if (difference > 0) return t("worldClock.tomorrow");
|
||||
return t("worldClock.today");
|
||||
};
|
||||
|
||||
const getPrimaryLabel = (options: ModeProps["options"], t: ScopedClockTranslator) => {
|
||||
if (options.customTitleToggle) return options.customTitle || t("worldClock.primary");
|
||||
if (options.useCustomTimezone) return humanizeTimeZone(options.timezone);
|
||||
return t("worldClock.local");
|
||||
};
|
||||
|
||||
const getPhaseColor = (phase: TimeOfDayPhase) => {
|
||||
if (phase === "night") return "indigo";
|
||||
if (phase === "dawn") return "orange";
|
||||
if (phase === "day") return "cyan";
|
||||
return "grape";
|
||||
};
|
||||
@@ -1,62 +1,51 @@
|
||||
"use client";
|
||||
|
||||
import { Box, Center, Stack, Text, Title } from "@mantine/core";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Box, Group, Loader, Stack, Text, Title } from "@mantine/core";
|
||||
import dayjs from "dayjs";
|
||||
import advancedFormat from "dayjs/plugin/advancedFormat";
|
||||
import timezones from "dayjs/plugin/timezone";
|
||||
import utc from "dayjs/plugin/utc";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { metricToImperial } from "@homarr/common";
|
||||
import { useI18n, useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import { isInitialWidgetQueryPending } from "../common/query-state";
|
||||
import { WidgetQueryErrorIndicator } from "../common/query-state-indicator";
|
||||
import type { WidgetComponentProps } from "../definition";
|
||||
import { AdvancedClockView } from "./advanced-view";
|
||||
import { clockTimeFormatShowsSeconds, resolveClockTimeFormat } from "./format";
|
||||
import { useCurrentTime } from "./use-current-time";
|
||||
import { ClockWeatherSummary } from "./weather-summary";
|
||||
import { getResolvedLocalTimeZone, isTimeZoneSupported } from "./world-clock";
|
||||
import { AnimatedWeatherIcon } from "../weather/animated-icon";
|
||||
import { WeatherDescription } from "../weather/icon";
|
||||
|
||||
dayjs.extend(advancedFormat);
|
||||
dayjs.extend(utc);
|
||||
dayjs.extend(timezones);
|
||||
|
||||
export default function ClockWidget({ options, width, height, displayMode }: WidgetComponentProps<"clock">) {
|
||||
const isAdvanced = displayMode === "advanced";
|
||||
const showSeconds = clockTimeFormatShowsSeconds(options.customTimeFormat);
|
||||
const time = useCurrentTime({ showSeconds });
|
||||
const requestedTimeZone = options.useCustomTimezone ? options.timezone : getResolvedLocalTimeZone();
|
||||
const primaryTimeZoneInvalid = !isTimeZoneSupported(requestedTimeZone);
|
||||
const primaryTimeZone = primaryTimeZoneInvalid ? "UTC" : requestedTimeZone;
|
||||
const zonedTime = time === null ? null : dayjs(time).tz(primaryTimeZone);
|
||||
const secondsFormat = options.showSeconds || isAdvanced ? ":ss" : "";
|
||||
const timeFormat = options.is24HourFormat ? `HH:mm${secondsFormat}` : `hh:mm${secondsFormat} A`;
|
||||
const dateFormat = options.dateFormat;
|
||||
const customTimeFormat = options.customTimeFormat;
|
||||
const customDateFormat = options.customDateFormat;
|
||||
const timezone = options.useCustomTimezone ? options.timezone : Intl.DateTimeFormat().resolvedOptions().timeZone;
|
||||
const time = useCurrentTime({ showSeconds: options.showSeconds || isAdvanced });
|
||||
const zonedTime = time === null ? null : dayjs(time).tz(timezone);
|
||||
|
||||
if (isAdvanced) {
|
||||
if (time && zonedTime) {
|
||||
return (
|
||||
<AdvancedClockView
|
||||
now={time}
|
||||
options={options}
|
||||
primaryTime={zonedTime}
|
||||
primaryTimeZone={primaryTimeZone}
|
||||
primaryTimeZoneInvalid={primaryTimeZoneInvalid}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return <Center h="100%">--:--</Center>;
|
||||
}
|
||||
|
||||
const resolvedTimeFormat = resolveClockTimeFormat(options.customTimeFormat, options.is24HourFormat);
|
||||
const minimumAxis = Math.min(width, height * 1.5);
|
||||
let sizing: "xs" | "sm" | "md" = "md";
|
||||
if (minimumAxis < 128) sizing = "xs";
|
||||
else if (minimumAxis < 196) sizing = "sm";
|
||||
const sizing = minimumAxis < 128 ? "xs" : minimumAxis < 196 ? "sm" : "md";
|
||||
const showWeatherCorner = options.showWeather && sizing !== "xs";
|
||||
|
||||
return (
|
||||
<Box className="clock-widget-container" h="100%" pos="relative">
|
||||
{showWeatherCorner && (
|
||||
<Box pos="absolute" top={4} left={4}>
|
||||
<ClockWeatherSummary
|
||||
latitude={options.weatherLocation.latitude}
|
||||
longitude={options.weatherLocation.longitude}
|
||||
locationName={options.weatherLocation.name}
|
||||
isFahrenheit={options.isWeatherFormatFahrenheit}
|
||||
animateIcon={options.animateWeatherIcon}
|
||||
detailed={false}
|
||||
/>
|
||||
</Box>
|
||||
<ClockWeatherCorner
|
||||
latitude={options.weatherLocation.latitude}
|
||||
longitude={options.weatherLocation.longitude}
|
||||
locationName={options.weatherLocation.name}
|
||||
isFahrenheit={options.isWeatherFormatFahrenheit}
|
||||
showDetails={isAdvanced}
|
||||
/>
|
||||
)}
|
||||
<Stack className="clock-text-stack" h="100%" align="center" justify="center" gap={sizing}>
|
||||
{options.customTitleToggle && (
|
||||
@@ -64,14 +53,19 @@ export default function ClockWidget({ options, width, height, displayMode }: Wid
|
||||
{options.customTitle}
|
||||
</Text>
|
||||
)}
|
||||
<Title className="clock-time-text" fw={700} order={getTitleOrder(sizing)} lh="1">
|
||||
<Title className="clock-time-text" fw={700} order={sizing === "md" ? 2 : sizing === "sm" ? 4 : 6} lh="1">
|
||||
<time dateTime={zonedTime?.toISOString()}>
|
||||
{zonedTime === null ? "--:--" : zonedTime.format(resolvedTimeFormat)}
|
||||
{zonedTime === null ? "--:--" : zonedTime.format(options.customTimeFormat ? customTimeFormat : timeFormat)}
|
||||
</time>
|
||||
</Title>
|
||||
{options.showDate && (
|
||||
{(isAdvanced || options.showDate) && (
|
||||
<Text className="clock-date-text" size={sizing} lineClamp={1}>
|
||||
{zonedTime?.format(options.dateFormat)}
|
||||
{zonedTime?.format(options.customDateFormat ? customDateFormat : dateFormat)}
|
||||
</Text>
|
||||
)}
|
||||
{isAdvanced && (
|
||||
<Text size="xs" c="dimmed" lineClamp={1}>
|
||||
{zonedTime === null ? null : `${timezone} · UTC${zonedTime.format("Z")}`}
|
||||
</Text>
|
||||
)}
|
||||
</Stack>
|
||||
@@ -79,8 +73,117 @@ export default function ClockWidget({ options, width, height, displayMode }: Wid
|
||||
);
|
||||
}
|
||||
|
||||
const getTitleOrder = (sizing: "xs" | "sm" | "md") => {
|
||||
if (sizing === "md") return 2;
|
||||
if (sizing === "sm") return 4;
|
||||
return 6;
|
||||
interface ClockWeatherCornerProps {
|
||||
latitude: number;
|
||||
longitude: number;
|
||||
locationName: string;
|
||||
isFahrenheit: boolean;
|
||||
showDetails: boolean;
|
||||
}
|
||||
|
||||
const ClockWeatherCorner = ({
|
||||
latitude,
|
||||
longitude,
|
||||
locationName,
|
||||
isFahrenheit,
|
||||
showDetails,
|
||||
}: ClockWeatherCornerProps) => {
|
||||
const t = useI18n();
|
||||
const tCommon = useScopedI18n("common");
|
||||
const weatherQuery = clientApi.widget.weather.atLocation.useQuery({ latitude, longitude });
|
||||
const weather = weatherQuery.data;
|
||||
|
||||
if (!weather) {
|
||||
return (
|
||||
<Box pos="absolute" top={4} left={4}>
|
||||
{isInitialWidgetQueryPending(weatherQuery) ? (
|
||||
<Loader size="xs" aria-label={tCommon("action.loading")} />
|
||||
) : (
|
||||
<WidgetQueryErrorIndicator error={weatherQuery.error} label={t("widget.weather.name")} />
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
const temp = isFahrenheit ? weather.current.temperature * (9 / 5) + 32 : weather.current.temperature;
|
||||
const unit = isFahrenheit ? "°F" : "°C";
|
||||
const today = weather.daily[0];
|
||||
const formatTemperature = (value: number | undefined) => {
|
||||
if (value === undefined) return "—";
|
||||
const preferred = isFahrenheit ? value * (9 / 5) + 32 : value;
|
||||
return `${Math.round(preferred)}${unit}`;
|
||||
};
|
||||
|
||||
return (
|
||||
<Stack
|
||||
className="clock-weather-corner"
|
||||
pos="absolute"
|
||||
top={4}
|
||||
left={4}
|
||||
gap={showDetails ? 4 : 0}
|
||||
align="flex-start"
|
||||
>
|
||||
<Group gap={4} wrap="nowrap">
|
||||
<AnimatedWeatherIcon code={weather.current.weathercode} size={22} />
|
||||
<Text className="clock-weather-corner-temp" size="xs" c="dimmed">
|
||||
{Math.round(temp)}
|
||||
{unit}
|
||||
</Text>
|
||||
{showDetails && <WeatherDescription weatherOnly weatherCode={weather.current.weathercode} />}
|
||||
</Group>
|
||||
{showDetails && (
|
||||
<Stack gap={1}>
|
||||
<Text size="xs" fw={600}>
|
||||
{locationName}
|
||||
</Text>
|
||||
<Text size="xs" c="dimmed">
|
||||
{formatTemperature(today?.maxTemp)} / {formatTemperature(today?.minTemp)} · {today?.humidity ?? "—"}%
|
||||
</Text>
|
||||
<Text size="xs" c="dimmed">
|
||||
{Math.round(isFahrenheit ? metricToImperial(weather.current.windspeed) : weather.current.windspeed)}{" "}
|
||||
{isFahrenheit ? tCommon("unit.speed.milesPerHour") : tCommon("unit.speed.kilometersPerHour")}
|
||||
</Text>
|
||||
<Text size="xs" c="dimmed">
|
||||
{t("widget.weather.dailyForecast.sunrise")}: {formatClockWeatherTime(today?.sunrise)} ·{" "}
|
||||
{t("widget.weather.dailyForecast.sunset")}: {formatClockWeatherTime(today?.sunset)}
|
||||
</Text>
|
||||
</Stack>
|
||||
)}
|
||||
<WidgetQueryErrorIndicator error={weatherQuery.error} label={t("widget.weather.name")} />
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
const formatClockWeatherTime = (value: string | undefined) => value?.split("T")[1] ?? "—";
|
||||
|
||||
interface UseCurrentTimeProps {
|
||||
showSeconds: boolean;
|
||||
}
|
||||
|
||||
const useCurrentTime = ({ showSeconds }: UseCurrentTimeProps) => {
|
||||
const [time, setTime] = useState<Date | null>(null);
|
||||
const timeoutRef = useRef<NodeJS.Timeout>(null);
|
||||
const intervalRef = useRef<NodeJS.Timeout>(null);
|
||||
const intervalMultiplier = useMemo(() => (showSeconds ? 1 : 60), [showSeconds]);
|
||||
|
||||
useEffect(() => {
|
||||
setTime(new Date());
|
||||
timeoutRef.current = setTimeout(
|
||||
() => {
|
||||
setTime(new Date());
|
||||
|
||||
intervalRef.current = setInterval(() => {
|
||||
setTime(new Date());
|
||||
}, intervalMultiplier * 1000);
|
||||
},
|
||||
intervalMultiplier * 1000 - (1000 * (showSeconds ? 0 : dayjs().second()) + dayjs().millisecond()),
|
||||
);
|
||||
|
||||
return () => {
|
||||
if (timeoutRef.current) clearTimeout(timeoutRef.current);
|
||||
if (intervalRef.current) clearInterval(intervalRef.current);
|
||||
};
|
||||
}, [intervalMultiplier, showSeconds]);
|
||||
|
||||
return time;
|
||||
};
|
||||
@@ -1,19 +0,0 @@
|
||||
export const automaticTimeFormat = "automatic";
|
||||
|
||||
export const resolveClockTimeFormat = (format: string, legacyIs24HourFormat: boolean) => {
|
||||
if (format && format !== automaticTimeFormat) return format;
|
||||
if (legacyIs24HourFormat) return "HH:mm";
|
||||
return "hh:mm A";
|
||||
};
|
||||
|
||||
export const clockTimeFormatUses12Hours = (format: string, legacyIs24HourFormat: boolean) => {
|
||||
if (!format || format === automaticTimeFormat) return !legacyIs24HourFormat;
|
||||
const formatWithoutLiterals = format.replace(/\[[^\]]*\]/g, "");
|
||||
return /h{1,2}/.test(formatWithoutLiterals);
|
||||
};
|
||||
|
||||
export const clockTimeFormatShowsSeconds = (format: string) => {
|
||||
if (!format || format === automaticTimeFormat) return false;
|
||||
const formatWithoutLiterals = format.replace(/\[[^\]]*\]/g, "");
|
||||
return /s{1,2}/.test(formatWithoutLiterals);
|
||||
};
|
||||
@@ -3,18 +3,9 @@ import dayjs from "dayjs";
|
||||
|
||||
import { createWidgetDefinition, widgetQueryInputMatches } from "../definition";
|
||||
import { optionsBuilder } from "../options";
|
||||
import {
|
||||
defaultWorldClockCities,
|
||||
getTimeZoneOptions,
|
||||
maximumWorldClockCities,
|
||||
worldClockCityPresets,
|
||||
} from "./world-clock";
|
||||
|
||||
const timeZoneOptions = getTimeZoneOptions();
|
||||
|
||||
export const { definition, componentLoader } = createWidgetDefinition("clock", {
|
||||
icon: IconClock,
|
||||
supportsAdvancedFocus: true,
|
||||
queryKey: [["widget", "weather", "atLocation"]],
|
||||
queryMatcher: ({ input }, scope) => {
|
||||
const location = scope.options.weatherLocation;
|
||||
@@ -46,9 +37,12 @@ export const { definition, componentLoader } = createWidgetDefinition("clock", {
|
||||
defaultValue: true,
|
||||
withDescription: true,
|
||||
}),
|
||||
showSeconds: factory.switch({
|
||||
defaultValue: false,
|
||||
}),
|
||||
useCustomTimezone: factory.switch({ defaultValue: false }),
|
||||
timezone: factory.select({
|
||||
options: timeZoneOptions,
|
||||
options: Intl.supportedValuesOf("timeZone").map((value) => value),
|
||||
defaultValue: "Europe/London",
|
||||
searchable: true,
|
||||
withDescription: true,
|
||||
@@ -58,29 +52,24 @@ export const { definition, componentLoader } = createWidgetDefinition("clock", {
|
||||
}),
|
||||
dateFormat: factory.select({
|
||||
options: [
|
||||
{ value: "YYYY-MM-DD", label: `${dayjs().format("YYYY-MM-DD")} · YYYY-MM-DD` },
|
||||
{ value: "DD/MM/YYYY", label: `${dayjs().format("DD/MM/YYYY")} · DD/MM/YYYY` },
|
||||
{ value: "MM/DD/YYYY", label: `${dayjs().format("MM/DD/YYYY")} · MM/DD/YYYY` },
|
||||
{ value: "dddd, MMMM D", label: `${dayjs().format("dddd, MMMM D")} · dddd, MMMM D` },
|
||||
{ value: "dddd, D MMMM", label: `${dayjs().format("dddd, D MMMM")} · dddd, D MMMM` },
|
||||
{ value: "MMM D, YYYY", label: `${dayjs().format("MMM D, YYYY")} · MMM D, YYYY` },
|
||||
{ value: "D MMM YYYY", label: `${dayjs().format("D MMM YYYY")} · D MMM YYYY` },
|
||||
{ value: "MMM D", label: `${dayjs().format("MMM D")} · MMM D` },
|
||||
{ value: "D MMM", label: `${dayjs().format("D MMM")} · D MMM` },
|
||||
{ value: "DD/MM", label: `${dayjs().format("DD/MM")} · DD/MM` },
|
||||
{ value: "MM/DD", label: `${dayjs().format("MM/DD")} · MM/DD` },
|
||||
{ value: "dddd, MMMM D", label: dayjs().format("dddd, MMMM D") },
|
||||
{ value: "dddd, D MMMM", label: dayjs().format("dddd, D MMMM") },
|
||||
{ value: "MMM D", label: dayjs().format("MMM D") },
|
||||
{ value: "D MMM", label: dayjs().format("D MMM") },
|
||||
{ value: "DD/MM/YYYY", label: dayjs().format("DD/MM/YYYY") },
|
||||
{ value: "MM/DD/YYYY", label: dayjs().format("MM/DD/YYYY") },
|
||||
{ value: "DD/MM", label: dayjs().format("DD/MM") },
|
||||
{ value: "MM/DD", label: dayjs().format("MM/DD") },
|
||||
],
|
||||
defaultValue: "dddd, MMMM D",
|
||||
withDescription: true,
|
||||
}),
|
||||
customTimeFormat: factory.select({
|
||||
options: [
|
||||
{ value: "HH:mm", label: `${dayjs().format("HH:mm")} · HH:mm` },
|
||||
{ value: "HH:mm:ss", label: `${dayjs().format("HH:mm:ss")} · HH:mm:ss` },
|
||||
{ value: "h:mm A", label: `${dayjs().format("h:mm A")} · h:mm A` },
|
||||
{ value: "h:mm:ss A", label: `${dayjs().format("h:mm:ss A")} · h:mm:ss A` },
|
||||
],
|
||||
defaultValue: "HH:mm",
|
||||
customTimeFormat: factory.text({
|
||||
defaultValue: "",
|
||||
withDescription: true,
|
||||
}),
|
||||
customDateFormat: factory.text({
|
||||
defaultValue: "",
|
||||
withDescription: true,
|
||||
}),
|
||||
showWeather: factory.switch({
|
||||
@@ -97,22 +86,8 @@ export const { definition, componentLoader } = createWidgetDefinition("clock", {
|
||||
isWeatherFormatFahrenheit: factory.switch({
|
||||
defaultValue: false,
|
||||
}),
|
||||
animateWeatherIcon: factory.switch({
|
||||
defaultValue: false,
|
||||
withDescription: true,
|
||||
}),
|
||||
worldClockCities: factory.timezoneList({
|
||||
defaultValue: defaultWorldClockCities.map((city) => ({ ...city })),
|
||||
maxValues: maximumWorldClockCities,
|
||||
presets: worldClockCityPresets,
|
||||
timeZoneOptions,
|
||||
withDescription: true,
|
||||
}),
|
||||
}),
|
||||
{
|
||||
is24HourFormat: {
|
||||
shouldHide: () => true,
|
||||
},
|
||||
customTitle: {
|
||||
shouldHide: (options) => !options.customTitleToggle,
|
||||
},
|
||||
@@ -128,9 +103,6 @@ export const { definition, componentLoader } = createWidgetDefinition("clock", {
|
||||
isWeatherFormatFahrenheit: {
|
||||
shouldHide: (options) => !options.showWeather,
|
||||
},
|
||||
animateWeatherIcon: {
|
||||
shouldHide: (options) => !options.showWeather,
|
||||
},
|
||||
},
|
||||
);
|
||||
},
|
||||
|
||||
@@ -1,108 +0,0 @@
|
||||
import { Badge, Box, Group, Progress, Stack, Text } from "@mantine/core";
|
||||
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import type { TimeOfDayPhase } from "./world-clock";
|
||||
|
||||
interface TimeOfDayBarProps {
|
||||
minuteOfDay: number;
|
||||
phase: TimeOfDayPhase;
|
||||
showLegend?: boolean;
|
||||
showTicks?: boolean;
|
||||
label: string;
|
||||
}
|
||||
|
||||
const phaseSections = [
|
||||
{ key: "nightStart", value: 20.833, color: "indigo.8" },
|
||||
{ key: "dawn", value: 12.5, color: "orange.6" },
|
||||
{ key: "day", value: 41.667, color: "cyan.6" },
|
||||
{ key: "dusk", value: 12.5, color: "grape.6" },
|
||||
{ key: "nightEnd", value: 12.5, color: "indigo.8" },
|
||||
] as const;
|
||||
|
||||
const phaseLegend = [
|
||||
{ key: "night", color: "indigo.8" },
|
||||
{ key: "dawn", color: "orange.6" },
|
||||
{ key: "day", color: "cyan.6" },
|
||||
{ key: "dusk", color: "grape.6" },
|
||||
] as const;
|
||||
|
||||
const timeTicks = ["midnight", "morning", "noon", "evening", "end"] as const;
|
||||
|
||||
export const TimeOfDayBar = ({
|
||||
minuteOfDay,
|
||||
phase,
|
||||
showLegend = false,
|
||||
showTicks = false,
|
||||
label,
|
||||
}: TimeOfDayBarProps) => {
|
||||
const t = useScopedI18n("widget.clock");
|
||||
const progress = Math.max(0, Math.min(100, (minuteOfDay / 1440) * 100));
|
||||
const remainingMinutes = Math.max(0, 1440 - Math.floor(minuteOfDay));
|
||||
const remainingHours = Math.floor(remainingMinutes / 60);
|
||||
const remainder = remainingMinutes % 60;
|
||||
|
||||
return (
|
||||
<Stack component="figure" gap={6} m={0} aria-label={label}>
|
||||
<Group justify="space-between" align="center" gap="xs" wrap="nowrap">
|
||||
<Badge color={getPhaseColor(phase)} variant="dot" size="sm">
|
||||
{t(`worldClock.phase.${phase}`)}
|
||||
</Badge>
|
||||
<Text size="xs" c="dimmed" ta="right">
|
||||
{t("worldClock.dayProgress", {
|
||||
percent: Math.round(progress),
|
||||
hours: remainingHours,
|
||||
minutes: remainder.toString().padStart(2, "0"),
|
||||
})}
|
||||
</Text>
|
||||
</Group>
|
||||
<Box pos="relative">
|
||||
<Progress.Root size="md" radius="xl" aria-hidden>
|
||||
{phaseSections.map((section) => (
|
||||
<Progress.Section key={section.key} value={section.value} color={section.color} withAria={false} />
|
||||
))}
|
||||
</Progress.Root>
|
||||
<Box
|
||||
pos="absolute"
|
||||
top="50%"
|
||||
left={`${progress}%`}
|
||||
w={4}
|
||||
h={24}
|
||||
bg="var(--mantine-color-text)"
|
||||
style={{ borderRadius: "var(--mantine-radius-xl)", transform: "translate(-50%, -50%)" }}
|
||||
/>
|
||||
</Box>
|
||||
{showTicks && (
|
||||
<Group justify="space-between" wrap="nowrap">
|
||||
{timeTicks.map((tick) => (
|
||||
<Text key={tick} size="xs" c="dimmed" aria-hidden>
|
||||
{t(`worldClock.tick.${tick}`)}
|
||||
</Text>
|
||||
))}
|
||||
</Group>
|
||||
)}
|
||||
{showLegend && (
|
||||
<Group gap="md" mt={4} align="center" wrap="wrap">
|
||||
<Text size="xs" fw={600}>
|
||||
{t("worldClock.phaseLegend")}
|
||||
</Text>
|
||||
{phaseLegend.map((item) => (
|
||||
<Group key={item.key} gap={6} wrap="nowrap">
|
||||
<Box w={9} h={9} bg={item.color} style={{ borderRadius: "var(--mantine-radius-xl)" }} />
|
||||
<Text size="xs" c="dimmed">
|
||||
{t(`worldClock.phase.${item.key}`)} · {t(`worldClock.phaseRange.${item.key}`)}
|
||||
</Text>
|
||||
</Group>
|
||||
))}
|
||||
</Group>
|
||||
)}
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
const getPhaseColor = (phase: TimeOfDayPhase) => {
|
||||
if (phase === "night") return "indigo";
|
||||
if (phase === "dawn") return "orange";
|
||||
if (phase === "day") return "cyan";
|
||||
return "grape";
|
||||
};
|
||||
@@ -1,27 +0,0 @@
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import dayjs from "dayjs";
|
||||
|
||||
export const useCurrentTime = ({ showSeconds }: { showSeconds: boolean }) => {
|
||||
const [time, setTime] = useState<Date | null>(null);
|
||||
const timeoutRef = useRef<ReturnType<typeof setTimeout>>(null);
|
||||
const intervalRef = useRef<ReturnType<typeof setInterval>>(null);
|
||||
const intervalMultiplier = useMemo(() => (showSeconds ? 1 : 60), [showSeconds]);
|
||||
|
||||
useEffect(() => {
|
||||
setTime(new Date());
|
||||
timeoutRef.current = setTimeout(
|
||||
() => {
|
||||
setTime(new Date());
|
||||
intervalRef.current = setInterval(() => setTime(new Date()), intervalMultiplier * 1000);
|
||||
},
|
||||
intervalMultiplier * 1000 - (1000 * (showSeconds ? 0 : dayjs().second()) + dayjs().millisecond()),
|
||||
);
|
||||
|
||||
return () => {
|
||||
if (timeoutRef.current) clearTimeout(timeoutRef.current);
|
||||
if (intervalRef.current) clearInterval(intervalRef.current);
|
||||
};
|
||||
}, [intervalMultiplier, showSeconds]);
|
||||
|
||||
return time;
|
||||
};
|
||||
@@ -1,78 +0,0 @@
|
||||
import { Box, Group, Loader, Stack, Text } from "@mantine/core";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { useI18n, useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import { isInitialWidgetQueryPending } from "../common/query-state";
|
||||
import { WidgetQueryErrorIndicator } from "../common/query-state-indicator";
|
||||
import { AnimatedWeatherIcon } from "../weather/animated-icon";
|
||||
import { WeatherDescription } from "../weather/icon";
|
||||
|
||||
interface ClockWeatherSummaryProps {
|
||||
latitude: number;
|
||||
longitude: number;
|
||||
locationName: string;
|
||||
isFahrenheit: boolean;
|
||||
animateIcon: boolean;
|
||||
detailed: boolean;
|
||||
}
|
||||
|
||||
export const ClockWeatherSummary = ({
|
||||
latitude,
|
||||
longitude,
|
||||
locationName,
|
||||
isFahrenheit,
|
||||
animateIcon,
|
||||
detailed,
|
||||
}: ClockWeatherSummaryProps) => {
|
||||
const t = useI18n();
|
||||
const tCommon = useScopedI18n("common");
|
||||
const weatherQuery = clientApi.widget.weather.atLocation.useQuery({ latitude, longitude });
|
||||
const weather = weatherQuery.data;
|
||||
|
||||
if (!weather) {
|
||||
return isInitialWidgetQueryPending(weatherQuery) ? (
|
||||
<Loader size="xs" aria-label={tCommon("action.loading")} />
|
||||
) : (
|
||||
<WidgetQueryErrorIndicator error={weatherQuery.error} label={t("widget.weather.name")} />
|
||||
);
|
||||
}
|
||||
|
||||
const temperature = isFahrenheit ? weather.current.temperature * (9 / 5) + 32 : weather.current.temperature;
|
||||
const unit = isFahrenheit ? "°F" : "°C";
|
||||
const today = weather.daily[0];
|
||||
const formatTemperature = (value: number | null | undefined) => {
|
||||
if (value === undefined || value === null) return "—";
|
||||
const preferred = isFahrenheit ? value * (9 / 5) + 32 : value;
|
||||
return `${Math.round(preferred)}${unit}`;
|
||||
};
|
||||
|
||||
return (
|
||||
<Stack gap={detailed ? 3 : 0} align="flex-start">
|
||||
<Group gap={5} wrap="nowrap">
|
||||
<AnimatedWeatherIcon
|
||||
animated={animateIcon}
|
||||
code={weather.current.weatherCode}
|
||||
isDay={weather.current.isDay}
|
||||
size={detailed ? 28 : 22}
|
||||
/>
|
||||
<Text size={detailed ? "sm" : "xs"} fw={detailed ? 600 : undefined} c={detailed ? undefined : "dimmed"}>
|
||||
{Math.round(temperature)}
|
||||
{unit}
|
||||
</Text>
|
||||
{detailed && <WeatherDescription weatherOnly weatherCode={weather.current.weatherCode} />}
|
||||
</Group>
|
||||
{detailed && (
|
||||
<Box>
|
||||
<Text size="xs" fw={600} lineClamp={1}>
|
||||
{locationName}
|
||||
</Text>
|
||||
<Text size="xs" c="dimmed">
|
||||
{formatTemperature(today?.maxTemperature)} / {formatTemperature(today?.minTemperature)}
|
||||
</Text>
|
||||
</Box>
|
||||
)}
|
||||
<WidgetQueryErrorIndicator error={weatherQuery.error} label={t("widget.weather.name")} />
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
@@ -1,63 +0,0 @@
|
||||
import dayjs from "dayjs";
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import {
|
||||
createWorldClockTime,
|
||||
formatRelativeOffset,
|
||||
formatUtcOffset,
|
||||
getTimeOfDayPhase,
|
||||
getTimeZoneOptions,
|
||||
} from "./world-clock";
|
||||
|
||||
describe("world clock helpers", () => {
|
||||
test("adds UTC to the available timezone options", () => {
|
||||
expect(getTimeZoneOptions()).toContainEqual({ value: "UTC", label: "UTC (UTC)" });
|
||||
});
|
||||
|
||||
test("classifies the fixed time-of-day phases at their boundaries", () => {
|
||||
expect([0, 4, 5, 7, 8, 17, 18, 20, 21, 23].map(getTimeOfDayPhase)).toEqual([
|
||||
"night",
|
||||
"night",
|
||||
"dawn",
|
||||
"dawn",
|
||||
"day",
|
||||
"day",
|
||||
"dusk",
|
||||
"dusk",
|
||||
"night",
|
||||
"night",
|
||||
]);
|
||||
});
|
||||
|
||||
test("formats whole-hour and fractional offsets", () => {
|
||||
expect(formatUtcOffset(345)).toBe("UTC+05:45");
|
||||
expect(formatRelativeOffset(-210)).toBe("−3h 30m");
|
||||
expect(formatRelativeOffset(0)).toBe("±0h");
|
||||
});
|
||||
|
||||
test("compares civil dates across the date line from one instant", () => {
|
||||
const now = new Date("2026-01-01T02:30:00.000Z");
|
||||
const primaryTime = dayjs(now).tz("America/New_York");
|
||||
const tokyo = createWorldClockTime({
|
||||
city: { id: "tokyo", label: "Tokyo", timeZone: "Asia/Tokyo" },
|
||||
now,
|
||||
primaryTime,
|
||||
});
|
||||
|
||||
expect(primaryTime.format("YYYY-MM-DD")).toBe("2025-12-31");
|
||||
expect(tokyo.zonedTime?.format("YYYY-MM-DD")).toBe("2026-01-01");
|
||||
expect(tokyo.dayDifference).toBe(1);
|
||||
});
|
||||
|
||||
test("isolates unsupported timezones", () => {
|
||||
const now = new Date("2026-01-01T00:00:00.000Z");
|
||||
const result = createWorldClockTime({
|
||||
city: { id: "invalid", label: "Invalid", timeZone: "Invalid/Timezone" },
|
||||
now,
|
||||
primaryTime: dayjs(now).tz("UTC"),
|
||||
});
|
||||
|
||||
expect(result.zonedTime).toBeNull();
|
||||
expect(result.utcOffset).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,127 +0,0 @@
|
||||
import dayjs from "dayjs";
|
||||
import type { Dayjs } from "dayjs";
|
||||
import timezone from "dayjs/plugin/timezone";
|
||||
import utc from "dayjs/plugin/utc";
|
||||
|
||||
import type { OptionTimezone } from "../options";
|
||||
|
||||
dayjs.extend(utc);
|
||||
dayjs.extend(timezone);
|
||||
|
||||
export const maximumWorldClockCities = 6;
|
||||
|
||||
export const worldClockCityPresets = [
|
||||
{ id: "new-york", label: "New York", timeZone: "America/New_York" },
|
||||
{ id: "london", label: "London", timeZone: "Europe/London" },
|
||||
{ id: "paris", label: "Paris", timeZone: "Europe/Paris" },
|
||||
{ id: "tokyo", label: "Tokyo", timeZone: "Asia/Tokyo" },
|
||||
{ id: "sydney", label: "Sydney", timeZone: "Australia/Sydney" },
|
||||
{ id: "utc", label: "UTC", timeZone: "UTC" },
|
||||
] as const satisfies readonly OptionTimezone[];
|
||||
|
||||
export const defaultWorldClockCities = worldClockCityPresets.filter(({ id }) =>
|
||||
["new-york", "paris", "tokyo"].includes(id),
|
||||
);
|
||||
|
||||
export const getTimeZoneOptions = () => {
|
||||
const timeZones = Intl.supportedValuesOf("timeZone");
|
||||
if (!timeZones.includes("UTC")) timeZones.push("UTC");
|
||||
|
||||
return timeZones.map((timeZone) => ({
|
||||
value: timeZone,
|
||||
label: `${humanizeTimeZone(timeZone)} (${timeZone})`,
|
||||
}));
|
||||
};
|
||||
|
||||
export const humanizeTimeZone = (timeZone: string) => {
|
||||
if (timeZone === "UTC") return "UTC";
|
||||
const segments = timeZone.split("/");
|
||||
return (segments.at(-1) ?? timeZone).replaceAll("_", " ");
|
||||
};
|
||||
|
||||
export const isTimeZoneSupported = (timeZone: string) => {
|
||||
try {
|
||||
new Intl.DateTimeFormat("en", { timeZone }).format(0);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
export type TimeOfDayPhase = "night" | "dawn" | "day" | "dusk";
|
||||
|
||||
export interface WorldClockTime {
|
||||
id: string;
|
||||
label: string;
|
||||
timeZone: string;
|
||||
zonedTime: Dayjs | null;
|
||||
phase: TimeOfDayPhase | null;
|
||||
minuteOfDay: number | null;
|
||||
utcOffset: number | null;
|
||||
dayDifference: number | null;
|
||||
}
|
||||
|
||||
export const getResolvedLocalTimeZone = () => {
|
||||
const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
||||
return timeZone && isTimeZoneSupported(timeZone) ? timeZone : "UTC";
|
||||
};
|
||||
|
||||
export const createWorldClockTime = ({
|
||||
city,
|
||||
now,
|
||||
primaryTime,
|
||||
}: {
|
||||
city: OptionTimezone;
|
||||
now: Date;
|
||||
primaryTime: Dayjs;
|
||||
}): WorldClockTime => {
|
||||
if (!isTimeZoneSupported(city.timeZone)) {
|
||||
return {
|
||||
...city,
|
||||
zonedTime: null,
|
||||
phase: null,
|
||||
minuteOfDay: null,
|
||||
utcOffset: null,
|
||||
dayDifference: null,
|
||||
};
|
||||
}
|
||||
|
||||
const zonedTime = dayjs(now).tz(city.timeZone);
|
||||
return {
|
||||
...city,
|
||||
zonedTime,
|
||||
phase: getTimeOfDayPhase(zonedTime.hour()),
|
||||
minuteOfDay: zonedTime.hour() * 60 + zonedTime.minute() + zonedTime.second() / 60,
|
||||
utcOffset: zonedTime.utcOffset(),
|
||||
dayDifference: getCivilDayNumber(zonedTime) - getCivilDayNumber(primaryTime),
|
||||
};
|
||||
};
|
||||
|
||||
export const getTimeOfDayPhase = (hour: number): TimeOfDayPhase => {
|
||||
if (hour < 5 || hour >= 21) return "night";
|
||||
if (hour < 8) return "dawn";
|
||||
if (hour < 18) return "day";
|
||||
return "dusk";
|
||||
};
|
||||
|
||||
export const formatUtcOffset = (minutes: number) => {
|
||||
if (minutes === 0) return "UTC±00:00";
|
||||
const sign = minutes < 0 ? "−" : "+";
|
||||
const absoluteMinutes = Math.abs(minutes);
|
||||
const hours = Math.floor(absoluteMinutes / 60)
|
||||
.toString()
|
||||
.padStart(2, "0");
|
||||
const remainingMinutes = (absoluteMinutes % 60).toString().padStart(2, "0");
|
||||
return `UTC${sign}${hours}:${remainingMinutes}`;
|
||||
};
|
||||
|
||||
export const formatRelativeOffset = (minutes: number) => {
|
||||
if (minutes === 0) return "±0h";
|
||||
const sign = minutes < 0 ? "−" : "+";
|
||||
const absoluteMinutes = Math.abs(minutes);
|
||||
const hours = Math.floor(absoluteMinutes / 60);
|
||||
const remainingMinutes = absoluteMinutes % 60;
|
||||
return remainingMinutes === 0 ? `${sign}${hours}h` : `${sign}${hours}h ${remainingMinutes}m`;
|
||||
};
|
||||
|
||||
const getCivilDayNumber = (value: Dayjs) => Date.UTC(value.year(), value.month(), value.date()) / 86_400_000;
|
||||
@@ -1,38 +0,0 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { addRememberedBrowserAlert, requestBrowserNotificationPermission } from "./browser-alert";
|
||||
|
||||
const originalNotification = window.Notification;
|
||||
|
||||
afterEach(() => {
|
||||
if (originalNotification === undefined) {
|
||||
Reflect.deleteProperty(window, "Notification");
|
||||
return;
|
||||
}
|
||||
Object.defineProperty(window, "Notification", { configurable: true, value: originalNotification });
|
||||
});
|
||||
|
||||
describe("browser alert occurrence history", () => {
|
||||
it("moves a repeated occurrence to the end without duplicating it", () => {
|
||||
expect(addRememberedBrowserAlert(["first", "second"], "first")).toEqual(["second", "first"]);
|
||||
});
|
||||
|
||||
it("bounds remembered occurrences", () => {
|
||||
const values = Array.from({ length: 110 }, (_, index) => String(index));
|
||||
const result = addRememberedBrowserAlert(values, "next");
|
||||
expect(result).toHaveLength(100);
|
||||
expect(result.at(-1)).toBe("next");
|
||||
});
|
||||
|
||||
it("keeps the current permission when the browser rejects a permission request", async () => {
|
||||
Object.defineProperty(window, "Notification", {
|
||||
configurable: true,
|
||||
value: {
|
||||
permission: "default",
|
||||
requestPermission: vi.fn().mockRejectedValue(new Error("blocked")),
|
||||
},
|
||||
});
|
||||
|
||||
await expect(requestBrowserNotificationPermission()).resolves.toBe("default");
|
||||
});
|
||||
});
|
||||
@@ -1,87 +0,0 @@
|
||||
export type BrowserNotificationPermission = NotificationPermission | "unsupported";
|
||||
|
||||
export interface BrowserNotificationOptions {
|
||||
title: string;
|
||||
body?: string;
|
||||
icon?: string;
|
||||
tag?: string;
|
||||
}
|
||||
|
||||
const maxRememberedOccurrences = 100;
|
||||
|
||||
export const getBrowserNotificationPermission = (): BrowserNotificationPermission => {
|
||||
if (typeof window === "undefined" || !("Notification" in window)) return "unsupported";
|
||||
return window.Notification.permission;
|
||||
};
|
||||
|
||||
export const requestBrowserNotificationPermission = async (): Promise<BrowserNotificationPermission> => {
|
||||
if (typeof window === "undefined" || !("Notification" in window)) return "unsupported";
|
||||
try {
|
||||
return await window.Notification.requestPermission();
|
||||
} catch {
|
||||
return getBrowserNotificationPermission();
|
||||
}
|
||||
};
|
||||
|
||||
export const showBrowserNotification = ({ title, body, icon, tag }: BrowserNotificationOptions): boolean => {
|
||||
if (typeof window === "undefined" || !("Notification" in window) || window.Notification.permission !== "granted") {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const notification = new window.Notification(title, { body, icon, tag });
|
||||
void notification;
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
export const playBrowserAlertSound = (): boolean => {
|
||||
if (typeof window === "undefined") return false;
|
||||
const AudioContextConstructor =
|
||||
window.AudioContext ?? (window as typeof window & { webkitAudioContext?: typeof AudioContext }).webkitAudioContext;
|
||||
if (!AudioContextConstructor) return false;
|
||||
|
||||
try {
|
||||
const context = new AudioContextConstructor();
|
||||
const oscillator = context.createOscillator();
|
||||
const gain = context.createGain();
|
||||
const start = context.currentTime;
|
||||
oscillator.type = "sine";
|
||||
oscillator.frequency.setValueAtTime(880, start);
|
||||
gain.gain.setValueAtTime(0.0001, start);
|
||||
gain.gain.exponentialRampToValueAtTime(0.18, start + 0.01);
|
||||
gain.gain.exponentialRampToValueAtTime(0.0001, start + 0.3);
|
||||
oscillator.connect(gain);
|
||||
gain.connect(context.destination);
|
||||
oscillator.start(start);
|
||||
oscillator.stop(start + 0.32);
|
||||
oscillator.addEventListener("ended", () => void context.close(), { once: true });
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
export const addRememberedBrowserAlert = (occurrences: string[], occurrence: string): string[] => {
|
||||
const withoutDuplicate = occurrences.filter((value) => value !== occurrence);
|
||||
return [...withoutDuplicate, occurrence].slice(-maxRememberedOccurrences);
|
||||
};
|
||||
|
||||
export const claimBrowserAlertOccurrence = (storageKey: string, occurrence: string): boolean => {
|
||||
if (typeof window === "undefined") return false;
|
||||
|
||||
try {
|
||||
const serialized = window.localStorage.getItem(storageKey);
|
||||
const parsed: unknown = serialized === null ? [] : JSON.parse(serialized);
|
||||
const occurrences = Array.isArray(parsed)
|
||||
? parsed.filter((value): value is string => typeof value === "string")
|
||||
: [];
|
||||
if (occurrences.includes(occurrence)) return false;
|
||||
window.localStorage.setItem(storageKey, JSON.stringify(addRememberedBrowserAlert(occurrences, occurrence)));
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
@@ -1,28 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { parseLocalWidgetState, serializeLocalWidgetState } from "./use-local-widget-state";
|
||||
|
||||
const isCounterState = (value: unknown): value is { count: number } =>
|
||||
typeof value === "object" && value !== null && "count" in value && typeof value.count === "number";
|
||||
|
||||
describe("local widget state serialization", () => {
|
||||
it("round trips validated state", () => {
|
||||
const serialized = serializeLocalWidgetState(1, { count: 3 });
|
||||
expect(parseLocalWidgetState(serialized, 1, isCounterState)).toEqual({ count: 3 });
|
||||
});
|
||||
|
||||
it("rejects malformed and invalid state", () => {
|
||||
expect(parseLocalWidgetState("not-json", 1, isCounterState)).toBeUndefined();
|
||||
expect(parseLocalWidgetState('{"version":1,"value":{"count":"3"}}', 1, isCounterState)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("uses the supplied migration for old versions", () => {
|
||||
const serialized = serializeLocalWidgetState(1, { oldCount: 4 });
|
||||
expect(
|
||||
parseLocalWidgetState(serialized, 2, isCounterState, (value) => {
|
||||
if (typeof value !== "object" || value === null || !("oldCount" in value)) return undefined;
|
||||
return { count: Number(value.oldCount) };
|
||||
}),
|
||||
).toEqual({ count: 4 });
|
||||
});
|
||||
});
|
||||
@@ -1,146 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import type { Dispatch, SetStateAction } from "react";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
interface StoredWidgetState {
|
||||
version: number;
|
||||
value: unknown;
|
||||
}
|
||||
|
||||
interface UseLocalWidgetStateOptions<T> {
|
||||
key: string | undefined;
|
||||
version: number;
|
||||
defaultValue: T | (() => T);
|
||||
validate?: (value: unknown) => value is T;
|
||||
migrate?: (value: unknown, storedVersion: number) => T | undefined;
|
||||
}
|
||||
|
||||
const resolveDefaultValue = <T>(value: T | (() => T)): T =>
|
||||
typeof value === "function" ? (value as () => T)() : value;
|
||||
|
||||
export const serializeLocalWidgetState = <T>(version: number, value: T): string => JSON.stringify({ version, value });
|
||||
|
||||
export const parseLocalWidgetState = <T>(
|
||||
serialized: string,
|
||||
version: number,
|
||||
validate?: (value: unknown) => value is T,
|
||||
migrate?: (value: unknown, storedVersion: number) => T | undefined,
|
||||
): T | undefined => {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(serialized);
|
||||
if (typeof parsed !== "object" || parsed === null || !("version" in parsed) || !("value" in parsed)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const stored = parsed as StoredWidgetState;
|
||||
if (typeof stored.version !== "number") return undefined;
|
||||
if (stored.version !== version) {
|
||||
const migrated = migrate?.(stored.value, stored.version);
|
||||
if (migrated === undefined || (validate && !validate(migrated))) return undefined;
|
||||
return migrated;
|
||||
}
|
||||
if (validate && !validate(stored.value)) return undefined;
|
||||
return stored.value as T;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
export const useLocalWidgetState = <T>({
|
||||
key,
|
||||
version,
|
||||
defaultValue,
|
||||
validate,
|
||||
migrate,
|
||||
}: UseLocalWidgetStateOptions<T>): [T, Dispatch<SetStateAction<T>>, () => void] => {
|
||||
const defaultValueRef = useRef(defaultValue);
|
||||
const validateRef = useRef(validate);
|
||||
const migrateRef = useRef(migrate);
|
||||
defaultValueRef.current = defaultValue;
|
||||
validateRef.current = validate;
|
||||
migrateRef.current = migrate;
|
||||
|
||||
const createDefaultValue = useCallback(() => resolveDefaultValue(defaultValueRef.current), []);
|
||||
const [value, setValueState] = useState<T>(createDefaultValue);
|
||||
const valueRef = useRef(value);
|
||||
|
||||
const setMemoryValue = useCallback((nextValue: T) => {
|
||||
valueRef.current = nextValue;
|
||||
setValueState(nextValue);
|
||||
}, []);
|
||||
|
||||
const removeStoredValue = useCallback(() => {
|
||||
if (!key) return;
|
||||
try {
|
||||
window.localStorage.removeItem(key);
|
||||
} catch {
|
||||
// Storage can be unavailable in private or restricted browser contexts.
|
||||
}
|
||||
}, [key]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!key) {
|
||||
setMemoryValue(createDefaultValue());
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const serialized = window.localStorage.getItem(key);
|
||||
if (serialized === null) {
|
||||
setMemoryValue(createDefaultValue());
|
||||
return;
|
||||
}
|
||||
const parsed = parseLocalWidgetState(serialized, version, validateRef.current, migrateRef.current);
|
||||
if (parsed === undefined) {
|
||||
window.localStorage.removeItem(key);
|
||||
setMemoryValue(createDefaultValue());
|
||||
return;
|
||||
}
|
||||
setMemoryValue(parsed);
|
||||
} catch {
|
||||
setMemoryValue(createDefaultValue());
|
||||
}
|
||||
}, [createDefaultValue, key, setMemoryValue, version]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!key) return;
|
||||
|
||||
const handleStorage = (event: StorageEvent) => {
|
||||
if (event.storageArea !== window.localStorage || event.key !== key) return;
|
||||
if (event.newValue === null) {
|
||||
setMemoryValue(createDefaultValue());
|
||||
return;
|
||||
}
|
||||
|
||||
const parsed = parseLocalWidgetState(event.newValue, version, validateRef.current, migrateRef.current);
|
||||
if (parsed !== undefined) setMemoryValue(parsed);
|
||||
};
|
||||
window.addEventListener("storage", handleStorage);
|
||||
return () => window.removeEventListener("storage", handleStorage);
|
||||
}, [createDefaultValue, key, setMemoryValue, version]);
|
||||
|
||||
const setValue: Dispatch<SetStateAction<T>> = useCallback(
|
||||
(nextValue) => {
|
||||
const resolved =
|
||||
typeof nextValue === "function" ? (nextValue as (previous: T) => T)(valueRef.current) : nextValue;
|
||||
if (Object.is(resolved, valueRef.current)) return;
|
||||
setMemoryValue(resolved);
|
||||
if (key) {
|
||||
try {
|
||||
window.localStorage.setItem(key, serializeLocalWidgetState(version, resolved));
|
||||
} catch {
|
||||
// Keep the in-memory state usable when persistence is unavailable.
|
||||
}
|
||||
}
|
||||
},
|
||||
[key, setMemoryValue, version],
|
||||
);
|
||||
|
||||
const resetValue = useCallback(() => {
|
||||
removeStoredValue();
|
||||
setMemoryValue(createDefaultValue());
|
||||
}, [createDefaultValue, removeStoredValue, setMemoryValue]);
|
||||
|
||||
return [value, setValue, resetValue];
|
||||
};
|
||||
@@ -1,16 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { getNextWidgetTickDelay } from "./use-widget-now";
|
||||
|
||||
describe("getNextWidgetTickDelay", () => {
|
||||
it("aligns second and minute ticks", () => {
|
||||
const now = new Date(2026, 7, 20, 12, 34, 45, 250);
|
||||
expect(getNextWidgetTickDelay(now, "second")).toBe(750);
|
||||
expect(getNextWidgetTickDelay(now, "minute")).toBe(14_750);
|
||||
});
|
||||
|
||||
it("aligns day ticks to the next local midnight", () => {
|
||||
const now = new Date(2026, 7, 20, 23, 59, 59, 500);
|
||||
expect(getNextWidgetTickDelay(now, "day")).toBe(500);
|
||||
});
|
||||
});
|
||||
@@ -1,54 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
export type WidgetClockPrecision = "second" | "minute" | "day";
|
||||
|
||||
const minimumDelayMs = 10;
|
||||
|
||||
export const getNextWidgetTickDelay = (now: Date, precision: WidgetClockPrecision): number => {
|
||||
let next: number;
|
||||
if (precision === "second") {
|
||||
next = now.getTime() - now.getMilliseconds() + 1_000;
|
||||
} else if (precision === "minute") {
|
||||
next = now.getTime() - now.getSeconds() * 1_000 - now.getMilliseconds() + 60_000;
|
||||
} else {
|
||||
next = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1).getTime();
|
||||
}
|
||||
|
||||
return Math.max(minimumDelayMs, next - now.getTime());
|
||||
};
|
||||
|
||||
export const useWidgetNow = (precision: WidgetClockPrecision = "minute"): Date | null => {
|
||||
const [now, setNow] = useState<Date | null>(null);
|
||||
const timeoutRef = useRef<ReturnType<typeof setTimeout>>(undefined);
|
||||
|
||||
const cancelTick = useCallback(() => {
|
||||
if (timeoutRef.current === undefined) return;
|
||||
clearTimeout(timeoutRef.current);
|
||||
timeoutRef.current = undefined;
|
||||
}, []);
|
||||
|
||||
const scheduleTick = useCallback(() => {
|
||||
cancelTick();
|
||||
const current = new Date();
|
||||
setNow(current);
|
||||
timeoutRef.current = setTimeout(scheduleTick, getNextWidgetTickDelay(current, precision));
|
||||
}, [cancelTick, precision]);
|
||||
|
||||
useEffect(() => {
|
||||
scheduleTick();
|
||||
|
||||
const handleVisibilityChange = () => {
|
||||
if (document.visibilityState === "visible") scheduleTick();
|
||||
};
|
||||
document.addEventListener("visibilitychange", handleVisibilityChange);
|
||||
|
||||
return () => {
|
||||
document.removeEventListener("visibilitychange", handleVisibilityChange);
|
||||
cancelTick();
|
||||
};
|
||||
}, [cancelTick, scheduleTick]);
|
||||
|
||||
return now;
|
||||
};
|
||||
@@ -1,42 +0,0 @@
|
||||
.root {
|
||||
container-type: size;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.duration {
|
||||
font-variant-numeric: tabular-nums;
|
||||
letter-spacing: -0.04em;
|
||||
}
|
||||
|
||||
.compactDuration {
|
||||
font-size: var(--mantine-font-size-xl);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.compactProgress {
|
||||
width: 100%;
|
||||
max-width: 14rem;
|
||||
}
|
||||
|
||||
.eventCard {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
@container (max-width: 10.625rem) {
|
||||
.compactStatus,
|
||||
.compactTarget {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
@container (max-width: 8.75rem) {
|
||||
.compactDuration {
|
||||
font-size: clamp(var(--mantine-font-size-sm), 15cqw, var(--mantine-font-size-md));
|
||||
}
|
||||
}
|
||||
|
||||
@container (max-height: 6.5625rem) {
|
||||
.compactTarget {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
@@ -1,361 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
Alert,
|
||||
Badge,
|
||||
Group,
|
||||
Paper,
|
||||
Progress,
|
||||
ScrollArea,
|
||||
SimpleGrid,
|
||||
Stack,
|
||||
Switch,
|
||||
Text,
|
||||
ThemeIcon,
|
||||
Title,
|
||||
} from "@mantine/core";
|
||||
import { IconBell, IconBellOff, IconHourglass } from "@tabler/icons-react";
|
||||
|
||||
import { useCurrentIntlLocale, useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import {
|
||||
claimBrowserAlertOccurrence,
|
||||
getBrowserNotificationPermission,
|
||||
requestBrowserNotificationPermission,
|
||||
showBrowserNotification,
|
||||
} from "../common/browser-alert";
|
||||
import { useLocalWidgetState } from "../common/use-local-widget-state";
|
||||
import { useWidgetNow } from "../common/use-widget-now";
|
||||
import type { WidgetComponentProps } from "../definition";
|
||||
import { formatCountdownDuration } from "./display";
|
||||
import styles from "./component.module.css";
|
||||
import { getCountdownEventState, getCountdownProgress, groupCountdownStates } from "./recurrence";
|
||||
import type { CountdownEventState } from "./recurrence";
|
||||
|
||||
interface AlertPreferences {
|
||||
notifications: boolean;
|
||||
}
|
||||
|
||||
const defaultAlertPreferences: AlertPreferences = { notifications: false };
|
||||
|
||||
const isAlertPreferences = (value: unknown): value is AlertPreferences => {
|
||||
if (typeof value !== "object" || value === null) return false;
|
||||
return "notifications" in value && typeof value.notifications === "boolean";
|
||||
};
|
||||
|
||||
const migrateAlertPreferences = (value: unknown, storedVersion: number): AlertPreferences | undefined => {
|
||||
if (storedVersion !== 1 || !isAlertPreferences(value)) return undefined;
|
||||
return { notifications: value.notifications };
|
||||
};
|
||||
|
||||
export default function CountdownWidget({
|
||||
boardId,
|
||||
displayMode,
|
||||
isEditMode,
|
||||
itemId,
|
||||
options,
|
||||
width,
|
||||
}: WidgetComponentProps<"countdown">) {
|
||||
const now = useWidgetNow(options.showSeconds ? "second" : "minute");
|
||||
const locale = useCurrentIntlLocale();
|
||||
const t = useScopedI18n("widget.countdown");
|
||||
const storagePrefix = boardId && itemId ? `homarr:countdown:${boardId}:${itemId}` : undefined;
|
||||
const [preferences, setPreferences] = useLocalWidgetState<AlertPreferences>({
|
||||
key: storagePrefix ? `${storagePrefix}:alert-preferences` : undefined,
|
||||
version: 2,
|
||||
defaultValue: defaultAlertPreferences,
|
||||
validate: isAlertPreferences,
|
||||
migrate: migrateAlertPreferences,
|
||||
});
|
||||
const [notificationPermission, setNotificationPermission] = useState(() => getBrowserNotificationPermission());
|
||||
const previousNowRef = useRef<Date | null>(null);
|
||||
const states = useMemo(() => {
|
||||
if (!now) return [];
|
||||
return options.events.map((event) => getCountdownEventState(event, now));
|
||||
}, [now, options.events]);
|
||||
const grouped = useMemo(() => groupCountdownStates(states), [states]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!now || !storagePrefix) return;
|
||||
const previousNow = previousNowRef.current;
|
||||
previousNowRef.current = now;
|
||||
if (!previousNow || !preferences.notifications) return;
|
||||
|
||||
states.forEach((state) => {
|
||||
const occurrence = state.previousOccurrence;
|
||||
if (!occurrence || occurrence <= previousNow || occurrence > now) return;
|
||||
const claimKey = `${storagePrefix}:alerted-occurrences`;
|
||||
const occurrenceKey = `${state.event.id}:${occurrence.toISOString()}`;
|
||||
if (!claimBrowserAlertOccurrence(claimKey, occurrenceKey)) return;
|
||||
showBrowserNotification({
|
||||
title: state.event.label,
|
||||
body: t("alert.reached"),
|
||||
tag: occurrenceKey,
|
||||
});
|
||||
});
|
||||
}, [now, preferences.notifications, states, storagePrefix, t]);
|
||||
|
||||
if (!now) {
|
||||
return (
|
||||
<Stack h="100%" align="center" justify="center">
|
||||
<Text c="dimmed">—</Text>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
const hero = states[0];
|
||||
if (!hero) {
|
||||
return (
|
||||
<Stack h="100%" align="center" justify="center" gap="xs" p="md">
|
||||
<ThemeIcon variant="light" size="xl" radius="xl">
|
||||
<IconHourglass />
|
||||
</ThemeIcon>
|
||||
<Text fw={600}>{t("empty.title")}</Text>
|
||||
<Text size="sm" c="dimmed" ta="center">
|
||||
{t("empty.description")}
|
||||
</Text>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
let heroStatus: string | null = null;
|
||||
if (hero.invalid) heroStatus = t("invalid.value");
|
||||
else if (hero.completed) heroStatus = t("completed");
|
||||
|
||||
if (displayMode !== "advanced") {
|
||||
return (
|
||||
<Stack className={styles.root} h="100%" justify="center" align="center" gap={6} p="sm">
|
||||
<Group gap="xs" wrap="nowrap" maw="100%">
|
||||
{heroStatus && (
|
||||
<Badge className={styles.compactStatus} variant="outline" size="xs" flex="0 0 auto">
|
||||
{heroStatus}
|
||||
</Badge>
|
||||
)}
|
||||
<Text size="sm" fw={600} truncate>
|
||||
{hero.event.label}
|
||||
</Text>
|
||||
</Group>
|
||||
<CountdownValue state={hero} now={now} locale={locale} showSeconds={options.showSeconds} compact />
|
||||
<Text className={styles.compactTarget} size="xs" c="dimmed" truncate maw="100%">
|
||||
{formatOccurrence(hero, locale)}
|
||||
</Text>
|
||||
{options.showProgress && (
|
||||
<ProgressBar className={styles.compactProgress} state={hero} now={now} label={t("progress")} />
|
||||
)}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
const setNotifications = async (enabled: boolean) => {
|
||||
if (!enabled) {
|
||||
setPreferences((current) => ({ ...current, notifications: false }));
|
||||
return;
|
||||
}
|
||||
const permission = await requestBrowserNotificationPermission();
|
||||
setNotificationPermission(permission);
|
||||
if (permission === "granted") setPreferences((current) => ({ ...current, notifications: true }));
|
||||
};
|
||||
const eventColumns = width >= 700 ? 2 : 1;
|
||||
|
||||
return (
|
||||
<Stack className={styles.root} h="100%" gap="md" p="md">
|
||||
<Paper withBorder p="lg" radius="md">
|
||||
<Stack gap="md">
|
||||
<Group gap="xs" wrap="nowrap">
|
||||
{heroStatus && <Badge variant="outline">{heroStatus}</Badge>}
|
||||
<Text size="sm" c="dimmed" truncate>
|
||||
{formatOccurrence(hero, locale)}
|
||||
</Text>
|
||||
</Group>
|
||||
<Title order={2} lineClamp={1}>
|
||||
{hero.event.label}
|
||||
</Title>
|
||||
<CountdownValue state={hero} now={now} locale={locale} showSeconds={options.showSeconds} />
|
||||
</Stack>
|
||||
{options.showProgress && <ProgressBar state={hero} now={now} label={t("progress")} />}
|
||||
</Paper>
|
||||
|
||||
<AlertControls
|
||||
disabled={isEditMode}
|
||||
persistent={storagePrefix !== undefined}
|
||||
preferences={preferences}
|
||||
notificationPermission={notificationPermission}
|
||||
onNotificationsChange={setNotifications}
|
||||
/>
|
||||
|
||||
<ScrollArea type="auto" style={{ flex: 1, minHeight: 0 }}>
|
||||
<Stack gap="md" pb="xs">
|
||||
<EventSection
|
||||
title={t("upcoming")}
|
||||
states={grouped.upcoming}
|
||||
now={now}
|
||||
locale={locale}
|
||||
showSeconds={options.showSeconds}
|
||||
showProgress={options.showProgress}
|
||||
columns={eventColumns}
|
||||
/>
|
||||
<EventSection
|
||||
title={t("completedEvents")}
|
||||
states={grouped.completed}
|
||||
now={now}
|
||||
locale={locale}
|
||||
showSeconds={options.showSeconds}
|
||||
showProgress={options.showProgress}
|
||||
columns={eventColumns}
|
||||
/>
|
||||
{grouped.invalid.length > 0 && (
|
||||
<Alert color="yellow" title={t("invalid.title")}>
|
||||
{t("invalid.description", { count: grouped.invalid.length })}
|
||||
</Alert>
|
||||
)}
|
||||
</Stack>
|
||||
</ScrollArea>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
const CountdownValue = ({
|
||||
state,
|
||||
now,
|
||||
locale,
|
||||
showSeconds,
|
||||
compact = false,
|
||||
}: {
|
||||
state: CountdownEventState;
|
||||
now: Date;
|
||||
locale: string;
|
||||
showSeconds: boolean;
|
||||
compact?: boolean;
|
||||
}) => {
|
||||
const t = useScopedI18n("widget.countdown");
|
||||
let value = t("invalid.value");
|
||||
if (state.completed) value = t("completed");
|
||||
else if (state.nextOccurrence)
|
||||
value = formatCountdownDuration(state, now, showSeconds, locale, compact ? "narrow" : "short");
|
||||
return (
|
||||
<Text
|
||||
className={compact ? `${styles.duration} ${styles.compactDuration}` : styles.duration}
|
||||
fz={compact ? undefined : 42}
|
||||
fw={750}
|
||||
lh={1.05}
|
||||
ta={compact ? "center" : undefined}
|
||||
>
|
||||
{value}
|
||||
</Text>
|
||||
);
|
||||
};
|
||||
|
||||
const ProgressBar = ({
|
||||
className,
|
||||
state,
|
||||
now,
|
||||
label,
|
||||
}: {
|
||||
className?: string;
|
||||
state: CountdownEventState;
|
||||
now: Date;
|
||||
label: string;
|
||||
}) => {
|
||||
const progress = getCountdownProgress(state, now);
|
||||
if (progress === null) return null;
|
||||
return (
|
||||
<Progress
|
||||
className={className}
|
||||
mt="xs"
|
||||
value={progress}
|
||||
aria-label={`${label}: ${Math.round(progress)}%`}
|
||||
animated={false}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
const EventSection = ({
|
||||
title,
|
||||
states,
|
||||
now,
|
||||
locale,
|
||||
showSeconds,
|
||||
showProgress,
|
||||
columns,
|
||||
}: {
|
||||
title: string;
|
||||
states: CountdownEventState[];
|
||||
now: Date;
|
||||
locale: string;
|
||||
showSeconds: boolean;
|
||||
showProgress: boolean;
|
||||
columns: number;
|
||||
}) => {
|
||||
const t = useScopedI18n("widget.countdown");
|
||||
if (states.length === 0) return null;
|
||||
return (
|
||||
<Stack gap="xs">
|
||||
<Text fw={700}>{title}</Text>
|
||||
<SimpleGrid cols={columns} spacing="xs">
|
||||
{states.map((state) => (
|
||||
<Paper className={styles.eventCard} key={state.event.id} withBorder p="sm">
|
||||
<Stack gap={4} h="100%">
|
||||
<Group justify="space-between" wrap="nowrap">
|
||||
<Text fw={600} truncate>
|
||||
{state.event.label}
|
||||
</Text>
|
||||
{state.event.recurrence === "yearly" && <Badge variant="outline">{t("yearly")}</Badge>}
|
||||
</Group>
|
||||
<CountdownValue state={state} now={now} locale={locale} showSeconds={showSeconds} compact />
|
||||
<Stack gap={4} mt="auto">
|
||||
{showProgress && <ProgressBar state={state} now={now} label={title} />}
|
||||
<Text size="xs" c="dimmed">
|
||||
{formatOccurrence(state, locale)}
|
||||
</Text>
|
||||
</Stack>
|
||||
</Stack>
|
||||
</Paper>
|
||||
))}
|
||||
</SimpleGrid>
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
const AlertControls = ({
|
||||
disabled,
|
||||
persistent,
|
||||
preferences,
|
||||
notificationPermission,
|
||||
onNotificationsChange,
|
||||
}: {
|
||||
disabled: boolean;
|
||||
persistent: boolean;
|
||||
preferences: AlertPreferences;
|
||||
notificationPermission: ReturnType<typeof getBrowserNotificationPermission>;
|
||||
onNotificationsChange: (enabled: boolean) => Promise<void>;
|
||||
}) => {
|
||||
const t = useScopedI18n("widget.countdown.alert");
|
||||
if (!persistent) return null;
|
||||
return (
|
||||
<Paper withBorder p="sm" radius="md">
|
||||
<Switch
|
||||
checked={preferences.notifications && notificationPermission === "granted"}
|
||||
disabled={disabled || notificationPermission === "unsupported" || notificationPermission === "denied"}
|
||||
onChange={(event) => void onNotificationsChange(event.currentTarget.checked)}
|
||||
label={t("notifications")}
|
||||
thumbIcon={preferences.notifications ? <IconBell size={12} /> : <IconBellOff size={12} />}
|
||||
/>
|
||||
{notificationPermission === "denied" && (
|
||||
<Text size="xs" c="dimmed" mt="xs">
|
||||
{t("permissionDenied")}
|
||||
</Text>
|
||||
)}
|
||||
</Paper>
|
||||
);
|
||||
};
|
||||
|
||||
const formatOccurrence = (state: CountdownEventState, locale: string) => {
|
||||
const occurrence = state.nextOccurrence ?? state.previousOccurrence;
|
||||
if (!occurrence) return state.event.timeZone;
|
||||
return new Intl.DateTimeFormat(locale, {
|
||||
dateStyle: "medium",
|
||||
timeStyle: "short",
|
||||
timeZone: state.event.timeZone,
|
||||
}).format(occurrence);
|
||||
};
|
||||
@@ -1,64 +0,0 @@
|
||||
import type { CountdownEventState } from "./recurrence";
|
||||
|
||||
const secondMs = 1_000;
|
||||
const minuteMs = 60 * secondMs;
|
||||
const hourMs = 60 * minuteMs;
|
||||
const dayMs = 24 * hourMs;
|
||||
|
||||
export interface CountdownDurationPart {
|
||||
unit: Intl.NumberFormatOptions["unit"];
|
||||
value: number;
|
||||
}
|
||||
|
||||
export const getCountdownDurationParts = (
|
||||
state: CountdownEventState,
|
||||
now: Date,
|
||||
showSeconds: boolean,
|
||||
): CountdownDurationPart[] => {
|
||||
const occurrence = state.nextOccurrence;
|
||||
if (!occurrence) return [];
|
||||
const remaining = Math.max(0, occurrence.getTime() - now.getTime());
|
||||
const days = Math.floor(remaining / dayMs);
|
||||
const hours = Math.floor((remaining % dayMs) / hourMs);
|
||||
const minutes = Math.floor((remaining % hourMs) / minuteMs);
|
||||
const seconds = Math.floor((remaining % minuteMs) / secondMs);
|
||||
|
||||
if (showSeconds) {
|
||||
const parts: CountdownDurationPart[] = [];
|
||||
if (days > 0) parts.push({ unit: "day", value: days });
|
||||
if (days > 0 || hours > 0) parts.push({ unit: "hour", value: hours });
|
||||
if (days > 0 || hours > 0 || minutes > 0) parts.push({ unit: "minute", value: minutes });
|
||||
parts.push({ unit: "second", value: seconds });
|
||||
return parts;
|
||||
}
|
||||
|
||||
if (days > 0)
|
||||
return compactParts([
|
||||
{ unit: "day", value: days },
|
||||
{ unit: "hour", value: hours },
|
||||
]);
|
||||
if (hours > 0)
|
||||
return compactParts([
|
||||
{ unit: "hour", value: hours },
|
||||
{ unit: "minute", value: minutes },
|
||||
]);
|
||||
if (minutes > 0) return [{ unit: "minute", value: minutes }];
|
||||
return [{ unit: "minute", value: 0 }];
|
||||
};
|
||||
|
||||
const compactParts = (parts: CountdownDurationPart[]) => {
|
||||
const nonZero = parts.filter(({ value }) => value > 0);
|
||||
return nonZero.length > 0 ? nonZero : parts.slice(0, 1);
|
||||
};
|
||||
|
||||
export const formatCountdownDuration = (
|
||||
state: CountdownEventState,
|
||||
now: Date,
|
||||
showSeconds: boolean,
|
||||
locale: string,
|
||||
unitDisplay: Intl.NumberFormatOptions["unitDisplay"] = "short",
|
||||
) => {
|
||||
return getCountdownDurationParts(state, now, showSeconds)
|
||||
.map(({ unit, value }) => new Intl.NumberFormat(locale, { style: "unit", unit, unitDisplay }).format(value))
|
||||
.join(" ");
|
||||
};
|
||||
@@ -1,24 +0,0 @@
|
||||
import { IconHourglass } from "@tabler/icons-react";
|
||||
|
||||
import { createWidgetDefinition } from "../definition";
|
||||
import { optionsBuilder } from "../options";
|
||||
import { getTimeZoneOptions } from "../clock/world-clock";
|
||||
|
||||
const maximumCountdownEvents = 20;
|
||||
|
||||
export const { definition, componentLoader } = createWidgetDefinition("countdown", {
|
||||
icon: IconHourglass,
|
||||
supportsAdvancedFocus: true,
|
||||
createOptions() {
|
||||
return optionsBuilder.from((factory) => ({
|
||||
events: factory.dateTimeEventList({
|
||||
defaultValue: [],
|
||||
maxValues: maximumCountdownEvents,
|
||||
timeZoneOptions: getTimeZoneOptions(),
|
||||
withDescription: true,
|
||||
}),
|
||||
showProgress: factory.switch({ defaultValue: true }),
|
||||
showSeconds: factory.switch({ defaultValue: false, withDescription: true }),
|
||||
}));
|
||||
},
|
||||
}).withDynamicImport(() => import("./component"));
|
||||
@@ -1,101 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { OptionDateTimeEvent } from "../options";
|
||||
import { getCountdownDurationParts } from "./display";
|
||||
import {
|
||||
getCountdownEventState,
|
||||
getCountdownProgress,
|
||||
resolveWallDateTimeString,
|
||||
groupCountdownStates,
|
||||
} from "./recurrence";
|
||||
|
||||
const event = (overrides: Partial<OptionDateTimeEvent> = {}): OptionDateTimeEvent => ({
|
||||
id: "event",
|
||||
label: "Event",
|
||||
targetUtc: "2026-07-15T13:00:00.000Z",
|
||||
timeZone: "America/New_York",
|
||||
recurrence: "none",
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe("countdown recurrence", () => {
|
||||
it("preserves a yearly event's wall-clock time across DST offsets", () => {
|
||||
const recurring = event({ recurrence: "yearly" });
|
||||
const winterState = getCountdownEventState(recurring, new Date("2027-01-01T00:00:00.000Z"));
|
||||
|
||||
expect(winterState.nextOccurrence?.toISOString()).toBe("2027-07-15T13:00:00.000Z");
|
||||
});
|
||||
|
||||
it("skips non-leap years for a February 29 recurrence", () => {
|
||||
const recurring = event({
|
||||
recurrence: "yearly",
|
||||
targetUtc: "2024-02-29T12:00:00.000Z",
|
||||
timeZone: "UTC",
|
||||
});
|
||||
const state = getCountdownEventState(recurring, new Date("2025-01-01T00:00:00.000Z"));
|
||||
|
||||
expect(state.nextOccurrence?.toISOString()).toBe("2028-02-29T12:00:00.000Z");
|
||||
expect(state.previousOccurrence?.toISOString()).toBe("2024-02-29T12:00:00.000Z");
|
||||
});
|
||||
|
||||
it("selects the first valid time after a DST gap", () => {
|
||||
const resolved = resolveWallDateTimeString("2026-03-08 02:30:45", "America/New_York");
|
||||
expect(resolved?.toISOString()).toBe("2026-03-08T07:00:00.000Z");
|
||||
});
|
||||
|
||||
it("selects the earlier occurrence when a wall-clock time repeats", () => {
|
||||
const resolved = resolveWallDateTimeString("2026-11-01 01:30:00", "America/New_York");
|
||||
expect(resolved?.toISOString()).toBe("2026-11-01T05:30:00.000Z");
|
||||
});
|
||||
});
|
||||
|
||||
describe("countdown ordering and progress", () => {
|
||||
const now = new Date("2026-06-01T12:00:00.000Z");
|
||||
|
||||
it("preserves configured order within event groups", () => {
|
||||
const states = [
|
||||
getCountdownEventState(event({ id: "later", targetUtc: "2026-06-03T12:00:00.000Z" }), now),
|
||||
getCountdownEventState(event({ id: "older", targetUtc: "2026-05-01T12:00:00.000Z" }), now),
|
||||
getCountdownEventState(event({ id: "sooner", targetUtc: "2026-06-02T12:00:00.000Z" }), now),
|
||||
getCountdownEventState(event({ id: "newer", targetUtc: "2026-05-31T12:00:00.000Z" }), now),
|
||||
];
|
||||
|
||||
const grouped = groupCountdownStates(states);
|
||||
expect(grouped.upcoming.map(({ event: item }) => item.id)).toEqual(["later", "sooner"]);
|
||||
expect(grouped.completed.map(({ event: item }) => item.id)).toEqual(["older", "newer"]);
|
||||
});
|
||||
|
||||
it("clamps one-time progress and omits it without a start", () => {
|
||||
const withStart = getCountdownEventState(
|
||||
event({ targetUtc: "2026-06-02T12:00:00.000Z", startUtc: "2026-05-31T12:00:00.000Z" }),
|
||||
now,
|
||||
);
|
||||
const withoutStart = getCountdownEventState(event({ targetUtc: "2026-06-02T12:00:00.000Z" }), now);
|
||||
|
||||
expect(getCountdownProgress(withStart, now)).toBe(50);
|
||||
expect(getCountdownProgress(withStart, new Date("2026-06-04T12:00:00.000Z"))).toBe(100);
|
||||
expect(getCountdownProgress(withoutStart, now)).toBeNull();
|
||||
});
|
||||
|
||||
it("uses the previous and next occurrence for yearly progress", () => {
|
||||
const state = getCountdownEventState(
|
||||
event({ recurrence: "yearly", targetUtc: "2024-01-01T00:00:00.000Z", timeZone: "UTC" }),
|
||||
new Date("2026-07-02T12:00:00.000Z"),
|
||||
);
|
||||
const progress = getCountdownProgress(state, new Date("2026-07-02T12:00:00.000Z"));
|
||||
|
||||
expect(progress).not.toBeNull();
|
||||
if (progress === null) throw new Error("Expected yearly progress");
|
||||
expect(progress).toBeGreaterThan(49);
|
||||
expect(progress).toBeLessThan(51);
|
||||
});
|
||||
|
||||
it("keeps seconds visible at every duration when enabled", () => {
|
||||
const longState = getCountdownEventState(event({ targetUtc: "2026-06-03T13:00:00.000Z" }), now);
|
||||
const shortState = getCountdownEventState(event({ targetUtc: "2026-06-02T11:30:45.000Z" }), now);
|
||||
|
||||
expect(getCountdownDurationParts(longState, now, true).some(({ unit }) => unit === "second")).toBe(true);
|
||||
expect(getCountdownDurationParts(shortState, now, true).some(({ unit }) => unit === "second")).toBe(true);
|
||||
expect(getCountdownDurationParts(longState, now, false).some(({ unit }) => unit === "second")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,232 +0,0 @@
|
||||
import dayjs from "dayjs";
|
||||
import timezone from "dayjs/plugin/timezone";
|
||||
import utc from "dayjs/plugin/utc";
|
||||
|
||||
import type { OptionDateTimeEvent } from "../options";
|
||||
|
||||
dayjs.extend(utc);
|
||||
dayjs.extend(timezone);
|
||||
|
||||
const minuteMs = 60_000;
|
||||
const dayMs = 86_400_000;
|
||||
const timeZoneSupportCache = new Map<string, boolean>();
|
||||
|
||||
export interface WallDateTime {
|
||||
year: number;
|
||||
month: number;
|
||||
day: number;
|
||||
hour: number;
|
||||
minute: number;
|
||||
second: number;
|
||||
}
|
||||
|
||||
export interface CountdownEventState {
|
||||
event: OptionDateTimeEvent;
|
||||
nextOccurrence: Date | null;
|
||||
previousOccurrence: Date | null;
|
||||
completed: boolean;
|
||||
invalid: boolean;
|
||||
}
|
||||
|
||||
export const isCountdownTimeZoneSupported = (timeZone: string) => {
|
||||
const cached = timeZoneSupportCache.get(timeZone);
|
||||
if (cached !== undefined) return cached;
|
||||
try {
|
||||
new Intl.DateTimeFormat("en", { timeZone }).format(0);
|
||||
timeZoneSupportCache.set(timeZone, true);
|
||||
return true;
|
||||
} catch {
|
||||
timeZoneSupportCache.set(timeZone, false);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
export const parseWallDateTime = (value: string): WallDateTime | null => {
|
||||
const match = /^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})(?::(\d{2}))?$/.exec(value);
|
||||
if (!match) return null;
|
||||
const parts: WallDateTime = {
|
||||
year: Number(match[1]),
|
||||
month: Number(match[2]),
|
||||
day: Number(match[3]),
|
||||
hour: Number(match[4]),
|
||||
minute: Number(match[5]),
|
||||
second: Number(match[6] ?? 0),
|
||||
};
|
||||
const validationDate = new Date(
|
||||
Date.UTC(parts.year, parts.month - 1, parts.day, parts.hour, parts.minute, parts.second),
|
||||
);
|
||||
if (
|
||||
validationDate.getUTCFullYear() !== parts.year ||
|
||||
validationDate.getUTCMonth() !== parts.month - 1 ||
|
||||
validationDate.getUTCDate() !== parts.day ||
|
||||
validationDate.getUTCHours() !== parts.hour ||
|
||||
validationDate.getUTCMinutes() !== parts.minute ||
|
||||
validationDate.getUTCSeconds() !== parts.second
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return parts;
|
||||
};
|
||||
|
||||
export const formatWallDateTime = (instant: string | Date, timeZone: string) => {
|
||||
if (!isCountdownTimeZoneSupported(timeZone)) return "";
|
||||
const value = dayjs(instant);
|
||||
if (!value.isValid()) return "";
|
||||
return value.tz(timeZone).format("YYYY-MM-DD HH:mm:ss");
|
||||
};
|
||||
|
||||
const wallDateTimeEquals = (value: WallDateTime, candidate: dayjs.Dayjs) =>
|
||||
candidate.year() === value.year &&
|
||||
candidate.month() + 1 === value.month &&
|
||||
candidate.date() === value.day &&
|
||||
candidate.hour() === value.hour &&
|
||||
candidate.minute() === value.minute &&
|
||||
candidate.second() === value.second;
|
||||
|
||||
const resolveExactWallDateTime = (value: WallDateTime, timeZone: string): Date[] => {
|
||||
const naiveUtc = Date.UTC(value.year, value.month - 1, value.day, value.hour, value.minute, value.second);
|
||||
const offsets = new Set<number>();
|
||||
for (const dayOffset of [-2, -1, 0, 1, 2]) {
|
||||
offsets.add(
|
||||
dayjs
|
||||
.utc(naiveUtc + dayOffset * dayMs)
|
||||
.tz(timeZone)
|
||||
.utcOffset(),
|
||||
);
|
||||
}
|
||||
|
||||
const matches: Date[] = [];
|
||||
for (const offset of offsets) {
|
||||
const candidate = new Date(naiveUtc - offset * minuteMs);
|
||||
if (wallDateTimeEquals(value, dayjs(candidate).tz(timeZone))) matches.push(candidate);
|
||||
}
|
||||
// oxlint-disable-next-line unicorn/no-array-sort -- Array.toSorted is not supported in all target browsers.
|
||||
return [...matches].sort((left, right) => left.getTime() - right.getTime());
|
||||
};
|
||||
|
||||
/** Resolves a local wall-clock value, preferring the earlier repeated time and the first valid time after a DST gap. */
|
||||
export const resolveWallDateTime = (value: WallDateTime, timeZone: string): Date | null => {
|
||||
if (!isCountdownTimeZoneSupported(timeZone)) return null;
|
||||
const exactMatches = resolveExactWallDateTime(value, timeZone);
|
||||
if (exactMatches[0]) return exactMatches[0];
|
||||
|
||||
const naiveUtc = Date.UTC(value.year, value.month - 1, value.day, value.hour, value.minute);
|
||||
for (let minuteOffset = 1; minuteOffset <= 180; minuteOffset += 1) {
|
||||
const candidateWallDate = new Date(naiveUtc + minuteOffset * minuteMs);
|
||||
const candidateWall: WallDateTime = {
|
||||
year: candidateWallDate.getUTCFullYear(),
|
||||
month: candidateWallDate.getUTCMonth() + 1,
|
||||
day: candidateWallDate.getUTCDate(),
|
||||
hour: candidateWallDate.getUTCHours(),
|
||||
minute: candidateWallDate.getUTCMinutes(),
|
||||
second: candidateWallDate.getUTCSeconds(),
|
||||
};
|
||||
const matches = resolveExactWallDateTime(candidateWall, timeZone);
|
||||
if (matches[0]) return matches[0];
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
export const resolveWallDateTimeString = (value: string, timeZone: string) => {
|
||||
const wallDateTime = parseWallDateTime(value);
|
||||
if (!wallDateTime) return null;
|
||||
return resolveWallDateTime(wallDateTime, timeZone);
|
||||
};
|
||||
|
||||
const isLeapYear = (year: number) => year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
|
||||
|
||||
const occurrenceForYear = (target: WallDateTime, year: number, timeZone: string) => {
|
||||
if (target.month === 2 && target.day === 29 && !isLeapYear(year)) return null;
|
||||
return resolveWallDateTime({ ...target, year }, timeZone);
|
||||
};
|
||||
|
||||
const findYearlyOccurrence = (
|
||||
target: WallDateTime,
|
||||
timeZone: string,
|
||||
startYear: number,
|
||||
direction: 1 | -1,
|
||||
predicate: (date: Date) => boolean,
|
||||
) => {
|
||||
for (let index = 0; index < 12; index += 1) {
|
||||
const occurrence = occurrenceForYear(target, startYear + index * direction, timeZone);
|
||||
if (occurrence && predicate(occurrence)) return occurrence;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
export const getCountdownEventState = (event: OptionDateTimeEvent, now: Date): CountdownEventState => {
|
||||
const target = dayjs(event.targetUtc);
|
||||
if (!target.isValid() || !isCountdownTimeZoneSupported(event.timeZone)) {
|
||||
return { event, nextOccurrence: null, previousOccurrence: null, completed: false, invalid: true };
|
||||
}
|
||||
|
||||
if (event.recurrence === "none") {
|
||||
const targetDate = target.toDate();
|
||||
const completed = targetDate.getTime() <= now.getTime();
|
||||
return {
|
||||
event,
|
||||
nextOccurrence: completed ? null : targetDate,
|
||||
previousOccurrence: completed ? targetDate : null,
|
||||
completed,
|
||||
invalid: false,
|
||||
};
|
||||
}
|
||||
|
||||
const targetWall = parseWallDateTime(formatWallDateTime(event.targetUtc, event.timeZone));
|
||||
if (!targetWall) {
|
||||
return { event, nextOccurrence: null, previousOccurrence: null, completed: false, invalid: true };
|
||||
}
|
||||
const currentYear = dayjs(now).tz(event.timeZone).year();
|
||||
const nextOccurrence = findYearlyOccurrence(
|
||||
targetWall,
|
||||
event.timeZone,
|
||||
currentYear,
|
||||
1,
|
||||
(occurrence) => occurrence.getTime() > now.getTime(),
|
||||
);
|
||||
const previousOccurrence = findYearlyOccurrence(
|
||||
targetWall,
|
||||
event.timeZone,
|
||||
currentYear,
|
||||
-1,
|
||||
(occurrence) => occurrence.getTime() <= now.getTime(),
|
||||
);
|
||||
return {
|
||||
event,
|
||||
nextOccurrence,
|
||||
previousOccurrence,
|
||||
completed: false,
|
||||
invalid: nextOccurrence === null,
|
||||
};
|
||||
};
|
||||
|
||||
export const getCountdownProgress = (state: CountdownEventState, now: Date): number | null => {
|
||||
let start: Date | null = null;
|
||||
let end: Date | null = null;
|
||||
|
||||
if (state.event.recurrence === "yearly") {
|
||||
start = state.previousOccurrence;
|
||||
end = state.nextOccurrence;
|
||||
} else if (state.event.startUtc) {
|
||||
const parsedStart = dayjs(state.event.startUtc);
|
||||
const parsedEnd = dayjs(state.event.targetUtc);
|
||||
if (parsedStart.isValid() && parsedEnd.isValid()) {
|
||||
start = parsedStart.toDate();
|
||||
end = parsedEnd.toDate();
|
||||
}
|
||||
}
|
||||
|
||||
if (!start || !end || end.getTime() <= start.getTime()) return null;
|
||||
const progress = ((now.getTime() - start.getTime()) / (end.getTime() - start.getTime())) * 100;
|
||||
return Math.min(100, Math.max(0, progress));
|
||||
};
|
||||
|
||||
export const groupCountdownStates = (states: CountdownEventState[]) => {
|
||||
const upcoming = states.filter((state) => state.nextOccurrence !== null && !state.invalid);
|
||||
const completed = states.filter((state) => state.completed && state.previousOccurrence !== null && !state.invalid);
|
||||
const invalid = states.filter((state) => state.invalid);
|
||||
return { upcoming, completed, invalid };
|
||||
};
|
||||
|
||||
export const getLatestReachedOccurrence = (event: OptionDateTimeEvent, now: Date) =>
|
||||
getCountdownEventState(event, now).previousOccurrence;
|
||||
@@ -38,6 +38,7 @@ describe("supportsAdvancedFocus", () => {
|
||||
beszelSystemGridDefinition,
|
||||
beszelSystemStatsDefinition,
|
||||
beszelSystemTableDefinition,
|
||||
clockDefinition,
|
||||
customApiDefinition,
|
||||
dockerDefinition,
|
||||
indexerManagerDefinition,
|
||||
@@ -48,7 +49,6 @@ describe("supportsAdvancedFocus", () => {
|
||||
|
||||
test("requires an explicit opt-in", () => {
|
||||
expect(supportsAdvancedFocus({})).toBe(false);
|
||||
expect(supportsAdvancedFocus(clockDefinition)).toBe(true);
|
||||
expect(supportsAdvancedFocus(downloadsDefinition)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -74,11 +74,6 @@ const createContainerLogsPath = (container: Pick<DockerContainer, "endpointId" |
|
||||
|
||||
const getContainerTarget = ({ endpointId, id }: DockerContainer) => ({ endpointId, id });
|
||||
|
||||
const getContainersQueryInput = (endpointIds: string[]) => {
|
||||
if (endpointIds.length === 0) return undefined;
|
||||
return { endpointIds };
|
||||
};
|
||||
|
||||
const ContainerStateBadge = ({ state }: { state: ContainerState }) => {
|
||||
const t = useScopedI18n("docker.field.state.option");
|
||||
|
||||
@@ -253,7 +248,7 @@ export default function DockerWidget({
|
||||
const isAdvanced = displayMode === "advanced";
|
||||
|
||||
const utils = clientApi.useUtils();
|
||||
const containersQuery = clientApi.docker.getContainers.useQuery(getContainersQueryInput(options.endpointIds));
|
||||
const containersQuery = clientApi.docker.getContainers.useQuery();
|
||||
const data = getUsableWidgetQueryData(containersQuery);
|
||||
const { isFetching } = containersQuery;
|
||||
const refreshInventory = clientApi.docker.refreshInventory.useMutation({
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { IconBrandDocker, IconServerOff } from "@tabler/icons-react";
|
||||
|
||||
import type { RouterOutputs } from "@homarr/api";
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
|
||||
import { createWidgetDefinition } from "../definition";
|
||||
import { optionsBuilder } from "../options";
|
||||
@@ -31,19 +30,6 @@ export const { definition, componentLoader } = createWidgetDefinition("dockerCon
|
||||
createOptions() {
|
||||
return optionsBuilder.from(
|
||||
(factory) => ({
|
||||
endpointIds: factory.dynamicMultiSelect({
|
||||
defaultValue: [],
|
||||
maxValues: 100,
|
||||
withDescription: true,
|
||||
useOptions: () => {
|
||||
const { data = [], isPending, isError } = clientApi.docker.getEndpoints.useQuery();
|
||||
return {
|
||||
data: data.map((endpoint) => ({ value: endpoint.id, label: endpoint.name })),
|
||||
isPending,
|
||||
isError,
|
||||
};
|
||||
},
|
||||
}),
|
||||
columns: factory.multiSelect({
|
||||
defaultValue: [...allColumnsList],
|
||||
options: allColumnsList.map((value) => ({
|
||||
|
||||
@@ -63,10 +63,6 @@ import * as beszelAlerts from "./beszel-alerts";
|
||||
import * as beszelSystemStats from "./beszel-system-stats";
|
||||
import * as video from "./video";
|
||||
import * as weather from "./weather";
|
||||
import * as today from "./today";
|
||||
import * as airQuality from "./air-quality";
|
||||
import * as countdown from "./countdown";
|
||||
import * as timer from "./timer";
|
||||
import * as customApi from "./custom-api";
|
||||
import * as assistant from "./assistant";
|
||||
import * as wud from "./wud";
|
||||
@@ -98,10 +94,6 @@ export { AssistantWidgetRendererProvider } from "./assistant/context";
|
||||
export const widgetImports = {
|
||||
clock,
|
||||
weather,
|
||||
today,
|
||||
airQuality,
|
||||
countdown,
|
||||
timer,
|
||||
app,
|
||||
archiveTeamWarrior,
|
||||
anchorNote,
|
||||
|
||||
@@ -17,8 +17,6 @@ import { widgetQueryRefetchIntervals } from "./refetch-intervals";
|
||||
import { widgetCatalogIcons } from "./catalog";
|
||||
import { getWidgetQueryKeys } from "./definition";
|
||||
|
||||
const serializePollingPolicy = (entry: { queryKey: QueryKey; intervalSeconds: number | null }) => JSON.stringify(entry);
|
||||
|
||||
describe("widget manifest promise stability", () => {
|
||||
it("returns the same module promise for every render", () => {
|
||||
expect(loadWidgetModule("clock")).toBe(loadWidgetModule("clock"));
|
||||
@@ -147,8 +145,9 @@ describe("widget manifest promise stability", () => {
|
||||
}
|
||||
}
|
||||
|
||||
expect(widgetQueryRefetchIntervals.map(serializePollingPolicy).toSorted()).toEqual(
|
||||
[...expectedByQueryKey.values()].map(serializePollingPolicy).toSorted(),
|
||||
const serializePolicy = (entry: PollingPolicy) => JSON.stringify(entry);
|
||||
expect(widgetQueryRefetchIntervals.map(serializePolicy).toSorted()).toEqual(
|
||||
[...expectedByQueryKey.values()].map(serializePolicy).toSorted(),
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -24,10 +24,6 @@ export type WidgetResources = {
|
||||
const moduleLoaders: Record<WidgetKind, () => Promise<WidgetModule>> = {
|
||||
clock: () => import("./clock") as Promise<WidgetModule>,
|
||||
weather: () => import("./weather") as Promise<WidgetModule>,
|
||||
today: () => import("./today") as Promise<WidgetModule>,
|
||||
airQuality: () => import("./air-quality") as Promise<WidgetModule>,
|
||||
countdown: () => import("./countdown") as Promise<WidgetModule>,
|
||||
timer: () => import("./timer") as Promise<WidgetModule>,
|
||||
app: () => import("./app") as Promise<WidgetModule>,
|
||||
assistant: () => import("./assistant") as Promise<WidgetModule>,
|
||||
archiveTeamWarrior: () => import("./archive-team-warrior") as Promise<WidgetModule>,
|
||||
@@ -89,10 +85,6 @@ const moduleLoaders: Record<WidgetKind, () => Promise<WidgetModule>> = {
|
||||
const componentLoaders: Record<WidgetKind, () => Promise<WidgetComponentModule>> = {
|
||||
clock: () => import("./clock/component") as Promise<WidgetComponentModule>,
|
||||
weather: () => import("./weather/component") as Promise<WidgetComponentModule>,
|
||||
today: () => import("./today/component") as Promise<WidgetComponentModule>,
|
||||
airQuality: () => import("./air-quality/component") as Promise<WidgetComponentModule>,
|
||||
countdown: () => import("./countdown/component") as Promise<WidgetComponentModule>,
|
||||
timer: () => import("./timer/component") as Promise<WidgetComponentModule>,
|
||||
app: () => import("./app/component") as Promise<WidgetComponentModule>,
|
||||
assistant: () => import("./assistant/component") as Promise<WidgetComponentModule>,
|
||||
archiveTeamWarrior: () => import("./archive-team-warrior/component") as Promise<WidgetComponentModule>,
|
||||
|
||||
@@ -31,7 +31,6 @@
|
||||
|
||||
.tableViewport :global(th) {
|
||||
background-color: var(--background-color);
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.sortButton {
|
||||
|
||||
@@ -9,12 +9,7 @@ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
|
||||
|
||||
import type { StreamSession } from "@homarr/integrations";
|
||||
|
||||
import {
|
||||
getMediaServerColumnVisibility,
|
||||
getResolutionLabel,
|
||||
getSeasonEpisodeParams,
|
||||
SessionDetailsPopover,
|
||||
} from "./component";
|
||||
import { getMediaServerColumnVisibility, getSeasonEpisodeParams, SessionDetailsPopover } from "./component";
|
||||
|
||||
vi.mock("@homarr/translation/client", () => ({
|
||||
useScopedI18n: () => (key: string) => key,
|
||||
@@ -109,8 +104,7 @@ describe("getMediaServerColumnVisibility", () => {
|
||||
test("keeps a stable responsive column model from the zero-sized first render", () => {
|
||||
expect(getMediaServerColumnVisibility(0, false)).toEqual({ user: false, status: false });
|
||||
expect(getMediaServerColumnVisibility(300, false)).toEqual({ user: true, status: false });
|
||||
expect(getMediaServerColumnVisibility(420, false)).toEqual({ user: true, status: false });
|
||||
expect(getMediaServerColumnVisibility(540, false)).toEqual({ user: true, status: true });
|
||||
expect(getMediaServerColumnVisibility(420, false)).toEqual({ user: true, status: true });
|
||||
expect(getMediaServerColumnVisibility(0, true)).toEqual({ user: true, status: true });
|
||||
});
|
||||
});
|
||||
@@ -130,30 +124,3 @@ describe("getSeasonEpisodeParams", () => {
|
||||
expect(getSeasonEpisodeParams(null, undefined)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("getResolutionLabel", () => {
|
||||
test("labels a standard 16:9 resolution by its exact height", () => {
|
||||
expect(getResolutionLabel(1920, 1080)).toBe("1080p");
|
||||
expect(getResolutionLabel(1280, 720)).toBe("720p");
|
||||
});
|
||||
|
||||
test("classifies a cinemascope source by its width, not its cropped height", () => {
|
||||
// A 1920x804 encode (2.35:1, cropped top and bottom) is still a 1080p source.
|
||||
expect(getResolutionLabel(1920, 804)).toBe("1080p");
|
||||
expect(getResolutionLabel(1280, 640)).toBe("720p");
|
||||
});
|
||||
|
||||
test("rounds a near-standard resolution up to its nearest tier", () => {
|
||||
expect(getResolutionLabel(1912, 796)).toBe("1080p");
|
||||
});
|
||||
|
||||
test("falls back to the raw height when it doesn't clear any known tier", () => {
|
||||
expect(getResolutionLabel(100, 100)).toBe("100p");
|
||||
});
|
||||
|
||||
test("classifies a portrait video by its width, not its long-axis height", () => {
|
||||
// A 1080x1920 portrait phone recording is still a 1080p source, not a 1440p one.
|
||||
expect(getResolutionLabel(1080, 1920)).toBe("1080p");
|
||||
expect(getResolutionLabel(720, 1280)).toBe("720p");
|
||||
});
|
||||
});
|
||||
@@ -51,9 +51,7 @@ type SortState = { column: SortColumn; descending: boolean } | null;
|
||||
|
||||
export const getMediaServerColumnVisibility = (width: number, isAdvanced: boolean) => ({
|
||||
user: isAdvanced || width >= 300,
|
||||
// The user (200px) and status (190px) columns together need a floor here, otherwise the
|
||||
// currentlyPlaying column - the primary content - gets squeezed to almost nothing.
|
||||
status: isAdvanced || width >= 540,
|
||||
status: isAdvanced || width >= 420,
|
||||
});
|
||||
|
||||
function getPlaybackStatus(transcoding: TranscodingDecision | undefined): PlaybackStatus {
|
||||
@@ -79,21 +77,6 @@ function formatBitrate(bitrateKbps: number | null | undefined): string | null {
|
||||
return bitrateKbps >= 1000 ? `${(bitrateKbps / 1000).toFixed(1)} Mbps` : `${Math.round(bitrateKbps)} kbps`;
|
||||
}
|
||||
|
||||
const RESOLUTION_TIER_HEIGHTS = [4320, 2160, 1440, 1080, 720, 480, 360, 240] as const;
|
||||
|
||||
export function getResolutionLabel(width: number, height: number): string {
|
||||
// Classify off the short axis (height for landscape, width for portrait) so orientation
|
||||
// doesn't flip which dimension drives the label. Letterboxed/cinemascope sources are cropped
|
||||
// shorter than their nominal resolution class (a 1920x804 encode is still "1080p"), so derive
|
||||
// a floor for the short axis from the long axis assuming 16:9 - matches how Plex/Jellyfin label these themselves.
|
||||
const isPortrait = height > width;
|
||||
const shortAxis = isPortrait ? width : height;
|
||||
const longAxis = isPortrait ? height : width;
|
||||
const effectiveShortAxis = Math.max(shortAxis, Math.round((longAxis * 9) / 16));
|
||||
const tier = RESOLUTION_TIER_HEIGHTS.find((candidate) => effectiveShortAxis >= candidate * 0.9);
|
||||
return `${tier ?? effectiveShortAxis}p`;
|
||||
}
|
||||
|
||||
export function getSeasonEpisodeParams(
|
||||
seasonNumber: number | null | undefined,
|
||||
episodeNumber: number | null | undefined,
|
||||
@@ -134,33 +117,27 @@ function StreamTableHeader({
|
||||
sortable,
|
||||
sort,
|
||||
onSort,
|
||||
width,
|
||||
}: {
|
||||
column: SortColumn;
|
||||
label: string;
|
||||
sortable: boolean;
|
||||
sort: SortState;
|
||||
onSort: (column: SortColumn) => void;
|
||||
width?: number;
|
||||
}) {
|
||||
const active = sort?.column === column;
|
||||
const SortIcon = !active ? IconArrowsSort : sort.descending ? IconChevronDown : IconChevronUp;
|
||||
|
||||
return (
|
||||
<Table.Th w={width} aria-sort={active ? (sort.descending ? "descending" : "ascending") : "none"}>
|
||||
<Table.Th aria-sort={active ? (sort.descending ? "descending" : "ascending") : "none"}>
|
||||
{sortable ? (
|
||||
<UnstyledButton className={classes.sortButton} onClick={() => onSort(column)}>
|
||||
<Text component="span" size="xs" fw={600} c="dimmed" style={{ letterSpacing: "0.02em" }} truncate>
|
||||
<Text component="span" size="xs" fw={600} truncate>
|
||||
{label}
|
||||
</Text>
|
||||
<SortIcon
|
||||
size="var(--mantine-font-size-xs)"
|
||||
aria-hidden
|
||||
color={active ? undefined : "var(--mantine-color-dimmed)"}
|
||||
/>
|
||||
<SortIcon size="var(--mantine-font-size-xs)" aria-hidden />
|
||||
</UnstyledButton>
|
||||
) : (
|
||||
<Text size="xs" fw={600} c="dimmed" style={{ letterSpacing: "0.02em" }} truncate>
|
||||
<Text size="xs" fw={600} truncate>
|
||||
{label}
|
||||
</Text>
|
||||
)}
|
||||
@@ -218,14 +195,12 @@ export default function MediaServerWidget({
|
||||
current?.column === column ? { column, descending: !current.descending } : { column, descending: false },
|
||||
);
|
||||
|
||||
const uniqueIntegrations = currentStreams
|
||||
.filter((stream) => stream.sessions.length > 0)
|
||||
.map((stream) => ({
|
||||
integrationId: stream.integrationId,
|
||||
integrationKind: stream.integrationKind,
|
||||
integrationIcon: getIconUrl(stream.integrationKind),
|
||||
integrationName: stream.integrationName,
|
||||
}));
|
||||
const uniqueIntegrations = currentStreams.map((stream) => ({
|
||||
integrationId: stream.integrationId,
|
||||
integrationKind: stream.integrationKind,
|
||||
integrationIcon: getIconUrl(stream.integrationKind),
|
||||
integrationName: stream.integrationName,
|
||||
}));
|
||||
|
||||
const playingCount = flatSessions.filter(
|
||||
(session) => session.currentlyPlaying && session.currentlyPlaying.playback?.state !== "paused",
|
||||
@@ -288,7 +263,6 @@ export default function MediaServerWidget({
|
||||
sortable={isAdvanced}
|
||||
sort={sort}
|
||||
onSort={toggleSort}
|
||||
width={200}
|
||||
/>
|
||||
)}
|
||||
<StreamTableHeader
|
||||
@@ -305,7 +279,6 @@ export default function MediaServerWidget({
|
||||
sortable={isAdvanced}
|
||||
sort={sort}
|
||||
onSort={toggleSort}
|
||||
width={190}
|
||||
/>
|
||||
)}
|
||||
</Table.Tr>
|
||||
@@ -317,12 +290,6 @@ export default function MediaServerWidget({
|
||||
const status = getPlaybackStatus(currentlyPlaying?.metadata?.transcoding);
|
||||
const location = showLocation ? currentlyPlaying?.location : null;
|
||||
const bitrateLabel = showBitrate ? formatBitrate(currentlyPlaying?.metadata?.bitrateKbps) : null;
|
||||
// The transcoding resolution reflects what's actually being streamed - fall back to the
|
||||
// source's own resolution when it isn't set (direct play, or a transcode that only
|
||||
// touches audio/container and leaves the video resolution untouched).
|
||||
const resolution =
|
||||
currentlyPlaying?.metadata?.transcoding.resolution ?? currentlyPlaying?.metadata?.video.resolution;
|
||||
const resolutionLabel = resolution ? getResolutionLabel(resolution.width, resolution.height) : null;
|
||||
const toggleDetails = () => setSelectedRowId((current) => (current === rowId ? null : rowId));
|
||||
|
||||
return (
|
||||
@@ -348,7 +315,7 @@ export default function MediaServerWidget({
|
||||
{columnVisibility.user && (
|
||||
<Table.Td>
|
||||
<Group gap="xs" wrap="nowrap" w="100%">
|
||||
<Avatar size={28} src={session.user?.profilePictureUrl} style={{ flexShrink: 0 }} />
|
||||
<Avatar size={28} src={session.user?.profilePictureUrl} />
|
||||
<Stack gap={2} className={classes.cellContent}>
|
||||
<Text size="xs" truncate>
|
||||
{session.user?.username ?? t("items.unknownUser")}
|
||||
@@ -373,30 +340,24 @@ export default function MediaServerWidget({
|
||||
<Table.Td>
|
||||
{currentlyPlaying && (
|
||||
<Stack gap={4} align="flex-start" w="100%" className={classes.cellContent}>
|
||||
<Group gap={4} align="center" justify="space-between" wrap="nowrap" w="100%">
|
||||
<Badge size="xs" variant="light" color={playbackStatusColorMap[status]}>
|
||||
{t(`items.${status}` as never)}
|
||||
</Badge>
|
||||
{location && (
|
||||
<Group gap={4} align="center" wrap="nowrap">
|
||||
{location === "lan" ? (
|
||||
<IconWifi size="var(--mantine-font-size-xs)" />
|
||||
) : (
|
||||
<IconWorld size="var(--mantine-font-size-xs)" />
|
||||
)}
|
||||
<Text size="xs" c="dimmed" tt="uppercase">
|
||||
{location}
|
||||
</Text>
|
||||
</Group>
|
||||
)}
|
||||
</Group>
|
||||
{(resolutionLabel ?? bitrateLabel) && (
|
||||
<Badge size="xs" variant="light" color={playbackStatusColorMap[status]}>
|
||||
{t(`items.${status}` as never)}
|
||||
</Badge>
|
||||
{(location ?? bitrateLabel) && (
|
||||
<Group gap={4} align="center" justify="space-between" wrap="nowrap" w="100%">
|
||||
{resolutionLabel && (
|
||||
<Text size="xs" c="dimmed" style={{ whiteSpace: "nowrap" }}>
|
||||
{resolutionLabel}
|
||||
</Text>
|
||||
)}
|
||||
<Group gap={4} align="center" wrap="nowrap">
|
||||
{location &&
|
||||
(location === "lan" ? (
|
||||
<IconWifi size="var(--mantine-font-size-xs)" />
|
||||
) : (
|
||||
<IconWorld size="var(--mantine-font-size-xs)" />
|
||||
))}
|
||||
{location && (
|
||||
<Text size="xs" c="dimmed" tt="uppercase">
|
||||
{location}
|
||||
</Text>
|
||||
)}
|
||||
</Group>
|
||||
{bitrateLabel && (
|
||||
<Text size="xs" c="dimmed" style={{ whiteSpace: "nowrap" }}>
|
||||
{bitrateLabel}
|
||||
@@ -425,42 +386,25 @@ export default function MediaServerWidget({
|
||||
borderTop: "1px solid var(--border-color)",
|
||||
}}
|
||||
>
|
||||
<Group gap={6} wrap="nowrap">
|
||||
<Group gap={4} wrap="nowrap">
|
||||
<IconVideo size="var(--mantine-font-size-xs)" style={{ flexShrink: 0 }} />
|
||||
<Text size="sm" fw={500} style={{ whiteSpace: "nowrap" }}>
|
||||
<Text size="sm" style={{ whiteSpace: "nowrap" }}>
|
||||
{(t as unknown as (key: string, params?: { count: number }) => string)("footer.streams", {
|
||||
count: flatSessions.length,
|
||||
})}
|
||||
</Text>
|
||||
{totalBitrateLabel && (isAdvanced || width >= 300) && (
|
||||
<>
|
||||
<Text size="sm" c="dimmed" style={{ whiteSpace: "nowrap" }}>
|
||||
•
|
||||
</Text>
|
||||
<Text size="sm" c="dimmed" style={{ whiteSpace: "nowrap" }}>
|
||||
{t("footer.totalBitrate", { bitrate: totalBitrateLabel })}
|
||||
</Text>
|
||||
</>
|
||||
<Text size="sm" c="dimmed" style={{ whiteSpace: "nowrap" }}>
|
||||
{t("footer.totalBitrate", { bitrate: totalBitrateLabel })}
|
||||
</Text>
|
||||
)}
|
||||
</Group>
|
||||
<Group gap={6}>
|
||||
<Group gap="xs">
|
||||
{uniqueIntegrations.map((integration) => (
|
||||
<Group
|
||||
key={integration.integrationId}
|
||||
gap={6}
|
||||
align="center"
|
||||
wrap="nowrap"
|
||||
pl={2}
|
||||
pr={8}
|
||||
py={2}
|
||||
style={{
|
||||
backgroundColor: "var(--mantine-color-default-hover)",
|
||||
borderRadius: 999,
|
||||
}}
|
||||
>
|
||||
<Avatar className="media-server-icon" src={integration.integrationIcon} radius="xl" size={18} />
|
||||
<Group key={integration.integrationId} gap="xs" align="center">
|
||||
<Avatar className="media-server-icon" src={integration.integrationIcon} radius={"xs"} size="xs" />
|
||||
{(isAdvanced || width >= 480) && (
|
||||
<Text className="media-server-name" size="xs" fw={500} truncate="end">
|
||||
<Text className="media-server-name" size="sm" truncate="end">
|
||||
{integration.integrationName}
|
||||
</Text>
|
||||
)}
|
||||
|
||||
Loaded 100 of 126 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user