mirror of
https://github.com/gethomepage/homepage.git
synced 2026-08-31 09:25:52 -07:00
Compare commits
24 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f6dca0c5ad | |||
| e6ad43a76c | |||
| c46b3e6cff | |||
| e913243149 | |||
| 99e16c6da0 | |||
| c0b6eb3501 | |||
| a17763ca9f | |||
| bd39fb48b9 | |||
| f2dc80e39e | |||
| 7d48b7ea78 | |||
| 4c361422ca | |||
| 7c26cf6d97 | |||
| f0bd255adb | |||
| 728c6fbe18 | |||
| 6a96289717 | |||
| fa47a2d86c | |||
| cc22d04429 | |||
| a414f376b9 | |||
| bdd77342d8 | |||
| 63d2172ef7 | |||
| 85e4e439bc | |||
| 36aa241689 | |||
| 0933ba015a | |||
| c57117daae |
@@ -10,6 +10,7 @@ version-resolver:
|
||||
- 'breaking-change'
|
||||
minor:
|
||||
labels:
|
||||
- 'minor'
|
||||
- 'enhancement'
|
||||
- 'feature'
|
||||
patch:
|
||||
|
||||
@@ -10,6 +10,10 @@ on:
|
||||
]
|
||||
branches: [ dev ]
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
synchronize-with-crowdin:
|
||||
name: Crowdin Sync
|
||||
@@ -19,7 +23,7 @@ jobs:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: crowdin action
|
||||
uses: crowdin/github-action@c7af9bc98b01694653031fef2a0dc6c7888ce9bc # v2
|
||||
uses: crowdin/github-action@8f01d54f70f1713ee3f09d82c2bbb2daeac28689 # v2
|
||||
with:
|
||||
upload_translations: false
|
||||
download_translations: true
|
||||
|
||||
@@ -17,6 +17,8 @@ on:
|
||||
env:
|
||||
IMAGE_NAME: ${{ github.repository }}
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
|
||||
|
||||
@@ -27,7 +29,6 @@ jobs:
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
id-token: write
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
@@ -101,7 +102,7 @@ jobs:
|
||||
uses: docker/setup-qemu-action@96fe6ef7f33517b61c61be40b68a1882f3264fb8 # v4.2.0
|
||||
|
||||
- name: Setup Docker buildx
|
||||
uses: docker/setup-buildx-action@bb05f3f5519dd87d3ba754cc423b652a5edd6d2c # v4
|
||||
uses: docker/setup-buildx-action@37fe631027851001ddb9b187196cc803df7f5f0e # v4
|
||||
|
||||
- name: Build and push Docker image
|
||||
id: build-and-push
|
||||
|
||||
@@ -10,8 +10,6 @@ on:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pages: write
|
||||
id-token: write
|
||||
|
||||
jobs:
|
||||
|
||||
@@ -25,7 +23,7 @@ jobs:
|
||||
with:
|
||||
python-version-file: ".python-version"
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@ae62891fec2bb8e7d6c99fc78c9fec3a63790f8d # v10.0.0
|
||||
uses: astral-sh/setup-uv@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1
|
||||
- run: sudo apt-get install pngquant
|
||||
- name: Test Docs Build
|
||||
run: uv run --frozen zensical build --clean
|
||||
@@ -33,6 +31,10 @@ jobs:
|
||||
name: Build & Deploy Docs
|
||||
if: github.repository == 'gethomepage/homepage' && github.event_name != 'pull_request' && github.ref == 'refs/heads/main'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
pages: write
|
||||
id-token: write
|
||||
environment:
|
||||
name: github-pages
|
||||
url: ${{ steps.deployment.outputs.page_url }}
|
||||
@@ -43,7 +45,7 @@ jobs:
|
||||
with:
|
||||
python-version-file: ".python-version"
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@ae62891fec2bb8e7d6c99fc78c9fec3a63790f8d # v10.0.0
|
||||
uses: astral-sh/setup-uv@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1
|
||||
- run: sudo apt-get install pngquant
|
||||
- name: Build Docs
|
||||
run: uv run --frozen zensical build --clean
|
||||
|
||||
@@ -6,15 +6,15 @@ on:
|
||||
discussion:
|
||||
types: [labeled]
|
||||
|
||||
permissions:
|
||||
discussions: write
|
||||
issues: write
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
close-needs-discussion:
|
||||
name: Issues Need Discussion
|
||||
if: github.event_name == 'issues' && github.event.label.name == 'needs-discussion'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
issues: write
|
||||
steps:
|
||||
- uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
with:
|
||||
@@ -49,6 +49,8 @@ jobs:
|
||||
name: Discussions Need Information
|
||||
if: github.event_name == 'discussion' && github.event.label.name == 'needs-information'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
discussions: write
|
||||
steps:
|
||||
- uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
with:
|
||||
|
||||
@@ -6,6 +6,9 @@ on:
|
||||
workflow_dispatch:
|
||||
merge_group:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
name: Linting Checks
|
||||
|
||||
@@ -2,7 +2,6 @@ name: PR Quality
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
issues: read
|
||||
pull-requests: write
|
||||
|
||||
on:
|
||||
|
||||
@@ -5,7 +5,6 @@ on:
|
||||
types: [labeled]
|
||||
|
||||
permissions:
|
||||
issues: write
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
|
||||
@@ -5,10 +5,7 @@ on:
|
||||
- cron: '0 3 * * *'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
issues: write
|
||||
pull-requests: write
|
||||
discussions: write
|
||||
permissions: {}
|
||||
|
||||
concurrency:
|
||||
group: lock
|
||||
@@ -17,6 +14,9 @@ jobs:
|
||||
stale:
|
||||
name: 'Stale'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
issues: write
|
||||
pull-requests: write
|
||||
steps:
|
||||
- uses: actions/stale@1e223db275d687790206a7acac4d1a11bd6fe629 # v10
|
||||
with:
|
||||
@@ -31,6 +31,10 @@ jobs:
|
||||
lock-threads:
|
||||
name: 'Lock Old Threads'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
discussions: write
|
||||
issues: write
|
||||
pull-requests: write
|
||||
steps:
|
||||
- uses: dessant/lock-threads@89ae32b08ed1a541efecbab17912962a5e38981c # v6.0.2
|
||||
with:
|
||||
@@ -56,6 +60,8 @@ jobs:
|
||||
close-answered-discussions:
|
||||
name: 'Close Answered Discussions'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
discussions: write
|
||||
steps:
|
||||
- uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
with:
|
||||
@@ -112,6 +118,8 @@ jobs:
|
||||
close-outdated-discussions:
|
||||
name: 'Close Outdated Discussions'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
discussions: write
|
||||
steps:
|
||||
- uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
with:
|
||||
@@ -203,6 +211,8 @@ jobs:
|
||||
close-unsupported-feature-requests:
|
||||
name: 'Close Unsupported Feature Requests'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
discussions: write
|
||||
steps:
|
||||
- uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
with:
|
||||
|
||||
@@ -5,6 +5,9 @@ on:
|
||||
push:
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
vitest:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
@@ -49,6 +49,23 @@ environment:
|
||||
HOMEPAGE_MCP_TOKEN: "generate-with-openssl-rand-base64-32"
|
||||
```
|
||||
|
||||
## Connecting Claude Desktop
|
||||
|
||||
Claude Desktop can use [`mcp-remote`](https://www.npmjs.com/package/mcp-remote) to communicate with the homepage MCP endpoint in `claude_desktop_config.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"homepage": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "mcp-remote", "http://localhost:3000/api/mcp", "--header", "X-Homepage-MCP-Token: your-token"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The **Add custom connector** option will not work: remote connectors authenticate with OAuth and cannot supply `HOMEPAGE_MCP_TOKEN`.
|
||||
|
||||
## Read-only by default
|
||||
|
||||
The MCP endpoint exposes tools for reading and validating supported Homepage config files. File writes are disabled unless you opt in with:
|
||||
|
||||
@@ -85,6 +85,7 @@ To ensure cohesiveness of various widgets, the following should be used as a gui
|
||||
- Note that we reserve the right to decline widgets for projects that are very young (eg < ~1y) or those with a small reach (eg low GitHub stars). Again, this is in an effort to keep overall widget maintenance under control.
|
||||
- Widgets should be only one row of blocks
|
||||
- Widgets should be no more than 4 blocks wide and generally conform to the styling / design choices of other widgets
|
||||
- Use `withWidgetFields(service, defaultFields)` from `utils/widget-fields` to apply default fields and cap configured fields without mutating the service. The helper limits widgets to 4 fields.
|
||||
- Minimize the number of API calls
|
||||
- Avoid the use of custom proxy unless absolutely necessary
|
||||
- Widgets should be 'read-only', as in they should not make write changes using the relevant tool's API. Homepage widgets are designed to surface information, not to be a (usually worse) replacement for the tool itself.
|
||||
|
||||
@@ -9,7 +9,9 @@ See the [crowdsec docs](https://docs.crowdsec.net/docs/local_api/intro/#machines
|
||||
in most instances you can use the default credentials (`/etc/crowdsec/local_api_credentials.yaml`).
|
||||
|
||||
!!! note
|
||||
Without the `limit24h` option, the widget will fetch all alerts which is limited to 100 by the API to avoid performance issues.
|
||||
|
||||
`alerts` counts alerts raised by your own engine in the last 24 hours. Alerts originating from the
|
||||
CrowdSec community blocklist are excluded.
|
||||
|
||||
Allowed fields: `["alerts", "bans"]`.
|
||||
|
||||
@@ -19,5 +21,4 @@ widget:
|
||||
url: http://crowdsechostorip:port
|
||||
username: localhost # machine_id in crowdsec
|
||||
password: password
|
||||
limit24h: true # optional, limits alerts to last 24h. Default: false
|
||||
```
|
||||
|
||||
@@ -15,5 +15,5 @@ widget:
|
||||
url: https://proxmoxbackupserver.host:port
|
||||
username: api_token_id
|
||||
password: api_token_secret
|
||||
datastore: datastore_name #optional; if ommitted, will display a combination of all datastores used / total
|
||||
datastore: datastore_name #optional; if omitted, will display a combination of all datastores used / total
|
||||
```
|
||||
|
||||
+5
-5
@@ -15,7 +15,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@headlessui/react": "^2.2.10",
|
||||
"@kubernetes/client-node": "^1.4.0",
|
||||
"@kubernetes/client-node": "^2.0.0",
|
||||
"classnames": "^2.5.1",
|
||||
"compare-versions": "^6.1.1",
|
||||
"dockerode": "^5.0.0",
|
||||
@@ -23,7 +23,7 @@
|
||||
"gamedig": "^5.3.3",
|
||||
"i18next": "^26.3.6",
|
||||
"ical.js": "^2.2.1",
|
||||
"js-yaml": "^4.3.1",
|
||||
"js-yaml": "^5.3.0",
|
||||
"json-rpc-2.0": "^1.7.1",
|
||||
"luxon": "^3.7.2",
|
||||
"memory-cache": "^0.2.0",
|
||||
@@ -39,7 +39,7 @@
|
||||
"react-i18next": "^17.0.11",
|
||||
"react-icons": "^5.6.0",
|
||||
"recharts": "^3.1.2",
|
||||
"swr": "^2.4.2",
|
||||
"swr": "^2.5.1",
|
||||
"systeminformation": "^5.33.1",
|
||||
"tough-cookie": "^6.0.2",
|
||||
"urbackup-server-api": "^0.92.2",
|
||||
@@ -53,7 +53,7 @@
|
||||
"@eslint/js": "^9.39.4",
|
||||
"@tailwindcss/forms": "^0.5.11",
|
||||
"@tailwindcss/postcss": "^4.3.3",
|
||||
"@testing-library/jest-dom": "^7.0.0",
|
||||
"@testing-library/jest-dom": "^7.0.1",
|
||||
"@testing-library/react": "^16.3.0",
|
||||
"@vitest/coverage-v8": "^4.1.10",
|
||||
"eslint": "^9.25.1",
|
||||
@@ -63,7 +63,7 @@
|
||||
"eslint-plugin-jsx-a11y": "^6.10.2",
|
||||
"eslint-plugin-prettier": "^5.5.6",
|
||||
"eslint-plugin-react": "^7.37.4",
|
||||
"eslint-plugin-react-hooks": "^5.2.0",
|
||||
"eslint-plugin-react-hooks": "^7.1.1",
|
||||
"jsdom": "^30.0.1",
|
||||
"postcss": "^8.5.26",
|
||||
"prettier": "^3.8.4",
|
||||
|
||||
Generated
+504
-294
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"><circle cx="5" cy="5" r="4"/></svg>
|
||||
|
After Width: | Height: | Size: 96 B |
@@ -39,7 +39,9 @@
|
||||
"wait": "Please wait"
|
||||
},
|
||||
"search": {
|
||||
"placeholder": "Search…"
|
||||
"placeholder": "Search…",
|
||||
"provider": "Search engine: {{name}}",
|
||||
"select_provider": "Select search engine"
|
||||
},
|
||||
"resources": {
|
||||
"cpu": "CPU",
|
||||
|
||||
@@ -472,7 +472,7 @@
|
||||
"users": "Usuarios",
|
||||
"loginsLast24H": "Inicios de sesión (24h)",
|
||||
"failedLoginsLast24H": "Inicios de sesión fallidos (24h)",
|
||||
"authorizationsLast24H": "Auths (24h)"
|
||||
"authorizationsLast24H": "Autenticaciones (24 h)"
|
||||
},
|
||||
"proxmox": {
|
||||
"mem": "MEM",
|
||||
|
||||
@@ -73,6 +73,7 @@ describe("pages/api/auth/[...nextauth]", () => {
|
||||
it("routes sanitized NextAuth logs through the Homepage logger", async () => {
|
||||
const mod = await import("pages/api/auth/[...nextauth]");
|
||||
const sensitiveMetadata = {
|
||||
error: Object.assign(new Error("State cookie was missing."), { access_token: "sensitive-access-token" }),
|
||||
clientSecret: "sensitive-client-secret",
|
||||
access_token: "sensitive-access-token",
|
||||
id_token: "sensitive-id-token",
|
||||
@@ -82,7 +83,7 @@ describe("pages/api/auth/[...nextauth]", () => {
|
||||
mod.authOptions.logger.warn("NEXTAUTH_URL", sensitiveMetadata);
|
||||
mod.authOptions.logger.debug("OAUTH_CALLBACK_RESPONSE", sensitiveMetadata);
|
||||
|
||||
expect(errorMock).toHaveBeenCalledWith("%s", "OAUTH_CALLBACK_ERROR");
|
||||
expect(errorMock).toHaveBeenCalledWith("%s: %s", "OAUTH_CALLBACK_ERROR", "State cookie was missing.");
|
||||
expect(warnMock).toHaveBeenCalledWith("%s", "NEXTAUTH_URL");
|
||||
expect(debugMock).toHaveBeenCalledWith("%s", "OAUTH_CALLBACK_RESPONSE");
|
||||
expect(JSON.stringify([...errorMock.mock.calls, ...warnMock.mock.calls, ...debugMock.mock.calls])).not.toContain(
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { ColorContext } from "utils/contexts/color";
|
||||
@@ -25,6 +25,7 @@ const {
|
||||
throwIn: null,
|
||||
validateData: [],
|
||||
hashData: null,
|
||||
hashConfig: null,
|
||||
mutateHash: vi.fn(),
|
||||
servicesData: [],
|
||||
bookmarksData: [],
|
||||
@@ -59,9 +60,12 @@ const {
|
||||
const serverSideTranslations = vi.fn(async (language) => ({ _translations: language }));
|
||||
const logger = { error: vi.fn() };
|
||||
|
||||
const useSWR = vi.fn((key) => {
|
||||
const useSWR = vi.fn((key, config) => {
|
||||
if (key === "/api/validate") return { data: state.validateData };
|
||||
if (key === "/api/hash") return { data: state.hashData, mutate: state.mutateHash };
|
||||
if (key === "/api/hash") {
|
||||
state.hashConfig = config;
|
||||
return { data: state.hashData, mutate: state.mutateHash };
|
||||
}
|
||||
if (key === "/api/services") return { data: state.servicesData };
|
||||
if (key === "/api/bookmarks") return { data: state.bookmarksData };
|
||||
if (key === "/api/widgets") return { data: state.widgetsData };
|
||||
@@ -172,6 +176,7 @@ describe("pages/index getStaticProps", () => {
|
||||
state.throwIn = null;
|
||||
state.validateData = [];
|
||||
state.hashData = null;
|
||||
state.hashConfig = null;
|
||||
state.servicesData = [];
|
||||
state.bookmarksData = [];
|
||||
state.widgetsData = [];
|
||||
@@ -351,6 +356,7 @@ describe("pages/index Index routing + SWR branches", () => {
|
||||
}
|
||||
|
||||
await renderIndex({ initialSettings: { title: "Homepage", layout: {} }, settings: { layout: {} } });
|
||||
act(() => state.hashConfig.onSuccess(state.hashData));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(fetchSpy).toHaveBeenCalledWith("/api/revalidate");
|
||||
@@ -379,11 +385,24 @@ describe("pages/index Index routing + SWR branches", () => {
|
||||
localStorage.removeItem("hash");
|
||||
|
||||
await renderIndex({ initialSettings: { title: "Homepage", layout: {} }, settings: { layout: {} } });
|
||||
act(() => state.hashConfig.onSuccess(state.hashData));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(localStorage.getItem("hash")).toBe("first-hash");
|
||||
});
|
||||
});
|
||||
|
||||
it("ignores a hash response without a hash", async () => {
|
||||
state.validateData = [];
|
||||
localStorage.setItem("hash", "old-hash");
|
||||
|
||||
await renderIndex({ initialSettings: { title: "Homepage", layout: {} }, settings: { layout: {} } });
|
||||
|
||||
expect(() => act(() => state.hashConfig.onSuccess(null))).not.toThrow();
|
||||
expect(() => act(() => state.hashConfig.onSuccess({}))).not.toThrow();
|
||||
expect(localStorage.getItem("hash")).toBe("old-hash");
|
||||
expect(document.querySelector(".animate-spin")).toBeFalsy();
|
||||
});
|
||||
});
|
||||
|
||||
describe("pages/index Home behavior", () => {
|
||||
@@ -419,11 +438,27 @@ describe("pages/index Home behavior", () => {
|
||||
|
||||
fireEvent.keyDown(document.body, { key: "a" });
|
||||
expect(screen.getByTestId("quicklaunch")).toHaveTextContent("open:3");
|
||||
expect(state.quickLaunchProps.searchString).toBe("a");
|
||||
|
||||
fireEvent.keyDown(document.body, { key: "Escape" });
|
||||
expect(screen.getByTestId("quicklaunch")).toHaveTextContent("closed:3");
|
||||
});
|
||||
|
||||
it("opens search on space without seeding the query with whitespace", async () => {
|
||||
await renderIndex({
|
||||
initialSettings: { title: "Homepage", layout: {} },
|
||||
settings: { title: "Homepage", layout: {}, language: "en" },
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(state.quickLaunchProps).toBeTruthy();
|
||||
});
|
||||
|
||||
fireEvent.keyDown(document.body, { key: " " });
|
||||
expect(screen.getByTestId("quicklaunch")).toHaveTextContent("open:3");
|
||||
expect(state.quickLaunchProps.searchString).toBe("");
|
||||
});
|
||||
|
||||
it("renders services and bookmark groups when present", async () => {
|
||||
await renderIndex({
|
||||
initialSettings: { title: "Homepage", layout: {} },
|
||||
@@ -489,7 +524,7 @@ describe("pages/index Home behavior", () => {
|
||||
state.widgetsData = [];
|
||||
|
||||
const { setTheme, setColor, setSettings } = await renderIndex({
|
||||
initialSettings: { title: "Homepage", layout: {} },
|
||||
initialSettings: { title: "Homepage", layout: {}, favicon: "/x.ico" },
|
||||
settings: {
|
||||
title: "Homepage",
|
||||
layout: {},
|
||||
@@ -498,7 +533,6 @@ describe("pages/index Home behavior", () => {
|
||||
color: "emerald",
|
||||
disableIndexing: true,
|
||||
base: "/base/",
|
||||
favicon: "/x.ico",
|
||||
},
|
||||
theme: "dark",
|
||||
color: "slate",
|
||||
@@ -516,6 +550,20 @@ describe("pages/index Home behavior", () => {
|
||||
expect(document.querySelector('link[rel="icon"]')?.getAttribute("href")).toBe("/x.ico");
|
||||
});
|
||||
|
||||
// Safari reads the head without running JS, so the favicon has to be there before the
|
||||
// settings context is populated, and mask-icon must not be
|
||||
it("renders a custom favicon before the settings context is populated", async () => {
|
||||
await renderIndex({
|
||||
initialSettings: { title: "Homepage", layout: {}, favicon: "/x.ico" },
|
||||
settings: {},
|
||||
});
|
||||
|
||||
expect(document.querySelector('link[rel="icon"]')?.getAttribute("href")).toBe("/x.ico");
|
||||
expect(document.querySelector('link[rel="apple-touch-icon"]')?.getAttribute("href")).toBe("/x.ico");
|
||||
expect(document.querySelector('link[rel="mask-icon"]')).toBeNull();
|
||||
expect(document.querySelector('link[rel="shortcut icon"]')).toBeNull();
|
||||
});
|
||||
|
||||
it("marks information widgets as right-aligned for known widget types", async () => {
|
||||
await renderIndex({
|
||||
initialSettings: { title: "Homepage", layout: {} },
|
||||
|
||||
+129
-110
@@ -15,6 +15,69 @@ const MOBILE_BUTTON_POSITIONS = {
|
||||
"bottom-right": "bottom-4 right-4",
|
||||
};
|
||||
|
||||
function parseUrl(searchString) {
|
||||
if (!/.+[.:].+/.test(searchString)) return null; // basic test for probably a url
|
||||
|
||||
try {
|
||||
return new URL(searchString.toLowerCase().startsWith("http") ? searchString : `https://${searchString}`);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function getSearchResults({
|
||||
hideVisitURL,
|
||||
searchDescriptions,
|
||||
searchProvider,
|
||||
searchString,
|
||||
searchSuggestions,
|
||||
servicesAndBookmarks,
|
||||
t,
|
||||
url,
|
||||
}) {
|
||||
if (searchString.trim().length === 0) return [];
|
||||
|
||||
const results = servicesAndBookmarks.flatMap((result) => {
|
||||
const nameMatch = result.name.toLowerCase().includes(searchString);
|
||||
const descriptionMatch = searchDescriptions && result.description?.toLowerCase().includes(searchString);
|
||||
|
||||
if (!nameMatch && !descriptionMatch) return [];
|
||||
return [{ ...result, ...(searchDescriptions && { priority: nameMatch ? 2 : +descriptionMatch }) }];
|
||||
});
|
||||
|
||||
if (searchDescriptions) {
|
||||
results.sort((a, b) => b.priority - a.priority);
|
||||
}
|
||||
|
||||
if (searchProvider) {
|
||||
results.push({
|
||||
href: searchProvider.url + encodeURIComponent(searchString),
|
||||
name: `${searchProvider.name ?? t("quicklaunch.custom")} ${t("quicklaunch.search")}`,
|
||||
type: "search",
|
||||
});
|
||||
|
||||
if (searchProvider.showSearchSuggestions && searchProvider.suggestionUrl && searchSuggestions[1]) {
|
||||
results.push(
|
||||
...searchSuggestions[1].map((suggestion) => ({
|
||||
href: searchProvider.url + encodeURIComponent(suggestion),
|
||||
name: suggestion,
|
||||
type: "searchSuggestion",
|
||||
})),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (!hideVisitURL && url) {
|
||||
results.unshift({
|
||||
href: url.toString(),
|
||||
name: `${t("quicklaunch.visit")} URL`,
|
||||
type: "url",
|
||||
});
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
export default function QuickLaunch({ servicesAndBookmarks, searchString, setSearchString, isOpen, setSearching }) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
@@ -23,9 +86,8 @@ export default function QuickLaunch({ servicesAndBookmarks, searchString, setSea
|
||||
|
||||
const searchField = useRef();
|
||||
|
||||
const [results, setResults] = useState([]);
|
||||
const [currentItemIndex, setCurrentItemIndex] = useState(null);
|
||||
const [url, setUrl] = useState(null);
|
||||
const url = parseUrl(searchString);
|
||||
const [searchSuggestions, setSearchSuggestions] = useState([]);
|
||||
|
||||
const { data: widgets } = useSWR("/api/widgets");
|
||||
@@ -62,7 +124,7 @@ export default function QuickLaunch({ servicesAndBookmarks, searchString, setSea
|
||||
: null;
|
||||
|
||||
function openCurrentItem(newWindow) {
|
||||
const result = results[currentItemIndex];
|
||||
const result = results[activeItemIndex];
|
||||
window.open(
|
||||
result.href,
|
||||
newWindow ? "_blank" : (result.target ?? searchProvider?.target ?? settings.target ?? "_blank"),
|
||||
@@ -81,17 +143,9 @@ export default function QuickLaunch({ servicesAndBookmarks, searchString, setSea
|
||||
|
||||
function handleSearchChange(event) {
|
||||
const rawSearchString = event.target.value;
|
||||
try {
|
||||
if (!/.+[.:].+/g.test(rawSearchString)) throw new Error(); // basic test for probably a url
|
||||
let urlString = rawSearchString;
|
||||
if (urlString.toLowerCase().indexOf("http") !== 0) urlString = `https://${rawSearchString}`;
|
||||
setUrl(new URL(urlString)); // basic validation
|
||||
setSearchString(rawSearchString);
|
||||
return;
|
||||
} catch (e) {
|
||||
setUrl(null);
|
||||
}
|
||||
setSearchString(rawSearchString.toLowerCase());
|
||||
setCurrentItemIndex(null);
|
||||
// urls keep their casing, everything else is lowercased for matching
|
||||
setSearchString(parseUrl(rawSearchString) ? rawSearchString : rawSearchString.toLowerCase());
|
||||
}
|
||||
|
||||
function handleSearchKeyDown(event) {
|
||||
@@ -103,18 +157,19 @@ export default function QuickLaunch({ servicesAndBookmarks, searchString, setSea
|
||||
} else if (event.key === "Enter" && results.length) {
|
||||
closeAndReset();
|
||||
openCurrentItem(event.metaKey);
|
||||
} else if (event.key === "ArrowDown" && results[currentItemIndex + 1]) {
|
||||
setCurrentItemIndex(currentItemIndex + 1);
|
||||
} else if (event.key === "ArrowDown" && results[activeItemIndex + 1]) {
|
||||
setCurrentItemIndex(activeItemIndex + 1);
|
||||
event.preventDefault();
|
||||
} else if (event.key === "ArrowUp" && currentItemIndex > 0) {
|
||||
setCurrentItemIndex(currentItemIndex - 1);
|
||||
} else if (event.key === "ArrowUp" && activeItemIndex > 0) {
|
||||
setCurrentItemIndex(activeItemIndex - 1);
|
||||
event.preventDefault();
|
||||
} else if (
|
||||
event.key === "ArrowRight" &&
|
||||
results[currentItemIndex] &&
|
||||
results[currentItemIndex].type === "searchSuggestion"
|
||||
results[activeItemIndex] &&
|
||||
results[activeItemIndex].type === "searchSuggestion"
|
||||
) {
|
||||
setSearchString(results[currentItemIndex].name);
|
||||
setCurrentItemIndex(null);
|
||||
setSearchString(results[activeItemIndex].name);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -138,88 +193,51 @@ export default function QuickLaunch({ servicesAndBookmarks, searchString, setSea
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
const abortController = new AbortController();
|
||||
|
||||
if (searchString.trim().length === 0) setResults([]);
|
||||
else {
|
||||
let newResults = servicesAndBookmarks.filter((r) => {
|
||||
const nameMatch = r.name.toLowerCase().includes(searchString);
|
||||
let descriptionMatch;
|
||||
if (searchDescriptions) {
|
||||
descriptionMatch = r.description?.toLowerCase().includes(searchString);
|
||||
r.priority = nameMatch ? 2 * +nameMatch : +descriptionMatch;
|
||||
}
|
||||
return nameMatch || descriptionMatch;
|
||||
});
|
||||
|
||||
if (searchDescriptions) {
|
||||
newResults = newResults.sort((a, b) => b.priority - a.priority);
|
||||
}
|
||||
|
||||
if (searchProvider) {
|
||||
newResults.push({
|
||||
href: searchProvider.url + encodeURIComponent(searchString),
|
||||
name: `${searchProvider.name ?? t("quicklaunch.custom")} ${t("quicklaunch.search")}`,
|
||||
type: "search",
|
||||
});
|
||||
|
||||
if (searchProvider.showSearchSuggestions && searchProvider.suggestionUrl) {
|
||||
if (searchString.trim() !== searchSuggestions[0]?.trim()) {
|
||||
fetch(
|
||||
`/api/search/searchSuggestion?query=${encodeURIComponent(searchString)}&providerName=${
|
||||
searchProvider.name ?? "Custom"
|
||||
}`,
|
||||
{ signal: abortController.signal },
|
||||
)
|
||||
.then(async (searchSuggestionResult) => {
|
||||
const newSearchSuggestions = await searchSuggestionResult.json();
|
||||
|
||||
if (newSearchSuggestions) {
|
||||
if (newSearchSuggestions[1].length > 4) {
|
||||
newSearchSuggestions[1] = newSearchSuggestions[1].splice(0, 4);
|
||||
}
|
||||
setSearchSuggestions(newSearchSuggestions);
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
// If there is an error, just ignore it. There just will be no search suggestions.
|
||||
});
|
||||
}
|
||||
|
||||
if (searchSuggestions[1]) {
|
||||
newResults = newResults.concat(
|
||||
searchSuggestions[1].map((suggestion) => ({
|
||||
href: searchProvider.url + encodeURIComponent(suggestion),
|
||||
name: suggestion,
|
||||
type: "searchSuggestion",
|
||||
})),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!hideVisitURL && url) {
|
||||
newResults.unshift({
|
||||
href: url.toString(),
|
||||
name: `${t("quicklaunch.visit")} URL`,
|
||||
type: "url",
|
||||
});
|
||||
}
|
||||
|
||||
setResults(newResults);
|
||||
|
||||
if (newResults.length) {
|
||||
setCurrentItemIndex(0);
|
||||
}
|
||||
if (
|
||||
searchString.trim().length === 0 ||
|
||||
!searchProvider?.showSearchSuggestions ||
|
||||
!searchProvider.suggestionUrl ||
|
||||
searchString.trim() === searchSuggestions[0]?.trim()
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return () => {
|
||||
abortController.abort();
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [searchString, servicesAndBookmarks, searchDescriptions, hideVisitURL, searchSuggestions, searchProvider, url]);
|
||||
const abortController = new AbortController();
|
||||
|
||||
fetch(
|
||||
`/api/search/searchSuggestion?query=${encodeURIComponent(searchString)}&providerName=${
|
||||
searchProvider.name ?? "Custom"
|
||||
}`,
|
||||
{ signal: abortController.signal },
|
||||
)
|
||||
.then(async (searchSuggestionResult) => {
|
||||
const newSearchSuggestions = await searchSuggestionResult.json();
|
||||
|
||||
if (newSearchSuggestions) {
|
||||
setCurrentItemIndex(null);
|
||||
setSearchSuggestions([newSearchSuggestions[0], newSearchSuggestions[1].slice(0, 4)]);
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
// If there is an error, just ignore it. There just will be no search suggestions.
|
||||
});
|
||||
|
||||
return () => abortController.abort();
|
||||
}, [searchProvider, searchString, searchSuggestions]);
|
||||
|
||||
const results = getSearchResults({
|
||||
hideVisitURL,
|
||||
searchDescriptions,
|
||||
searchProvider,
|
||||
searchString,
|
||||
searchSuggestions,
|
||||
servicesAndBookmarks,
|
||||
t,
|
||||
url,
|
||||
});
|
||||
|
||||
const activeItemIndex = currentItemIndex ?? (results.length ? 0 : null);
|
||||
|
||||
const [hidden, setHidden] = useState(true);
|
||||
useEffect(() => {
|
||||
function handleBackdropClick(event) {
|
||||
if (event.target?.tagName === "DIV") closeAndReset();
|
||||
@@ -228,14 +246,11 @@ export default function QuickLaunch({ servicesAndBookmarks, searchString, setSea
|
||||
if (isOpen) {
|
||||
searchField.current.focus();
|
||||
document.body.addEventListener("click", handleBackdropClick);
|
||||
setHidden(false);
|
||||
} else {
|
||||
document.body.removeEventListener("click", handleBackdropClick);
|
||||
searchField.current.blur();
|
||||
setTimeout(() => {
|
||||
setHidden(true);
|
||||
}, 300); // disable on close
|
||||
}
|
||||
|
||||
return () => document.body.removeEventListener("click", handleBackdropClick);
|
||||
}, [isOpen, closeAndReset]);
|
||||
|
||||
function highlightText(text) {
|
||||
@@ -259,13 +274,17 @@ export default function QuickLaunch({ servicesAndBookmarks, searchString, setSea
|
||||
<>
|
||||
<div
|
||||
className={classNames(
|
||||
"relative z-40 ease-in-out duration-300 transition-opacity",
|
||||
hidden && !isOpen && "hidden",
|
||||
!hidden && isOpen && "opacity-100",
|
||||
!isOpen && "opacity-0",
|
||||
"relative z-40 ease-in-out",
|
||||
isOpen ? "visible opacity-100" : "invisible opacity-0 pointer-events-none",
|
||||
)}
|
||||
style={{
|
||||
transitionProperty: "opacity, visibility",
|
||||
transitionDuration: "300ms, 0s",
|
||||
transitionDelay: isOpen ? "0s, 0s" : "0s, 300ms",
|
||||
}}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-hidden={!isOpen}
|
||||
>
|
||||
<div className="fixed inset-0 bg-gray-500 opacity-50" />
|
||||
<div className="fixed inset-0 z-20 overflow-y-auto">
|
||||
@@ -297,7 +316,7 @@ export default function QuickLaunch({ servicesAndBookmarks, searchString, setSea
|
||||
onKeyDown={handleItemKeyDown}
|
||||
className={classNames(
|
||||
"flex flex-row w-full items-center justify-between rounded-md text-sm md:text-xl py-2 px-4 cursor-pointer text-theme-700 dark:text-theme-200",
|
||||
i === currentItemIndex && "bg-theme-300/50 dark:bg-theme-700/50",
|
||||
i === activeItemIndex && "bg-theme-300/50 dark:bg-theme-700/50",
|
||||
)}
|
||||
>
|
||||
<div className="flex flex-row items-center mr-4 pointer-events-none">
|
||||
|
||||
@@ -46,13 +46,25 @@ function Wrapper({ servicesAndBookmarks = [], initialOpen = true } = {}) {
|
||||
const [isOpen, setSearching] = useState(initialOpen);
|
||||
|
||||
return (
|
||||
<QuickLaunch
|
||||
servicesAndBookmarks={servicesAndBookmarks}
|
||||
searchString={searchString}
|
||||
setSearchString={setSearchString}
|
||||
isOpen={isOpen}
|
||||
setSearching={setSearching}
|
||||
/>
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
data-testid="seed-key"
|
||||
onClick={() => {
|
||||
setSearchString((current) => `${current}g`);
|
||||
setSearching(true);
|
||||
}}
|
||||
>
|
||||
seed
|
||||
</button>
|
||||
<QuickLaunch
|
||||
servicesAndBookmarks={servicesAndBookmarks}
|
||||
searchString={searchString}
|
||||
setSearchString={setSearchString}
|
||||
isOpen={isOpen}
|
||||
setSearching={setSearching}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -151,6 +163,35 @@ describe("components/quicklaunch", () => {
|
||||
openSpy.mockRestore();
|
||||
});
|
||||
|
||||
it("does not carry a previous url result into a search seeded by a keypress", async () => {
|
||||
renderWithProviders(<Wrapper />, {
|
||||
settings: {
|
||||
target: "_self",
|
||||
quicklaunch: {
|
||||
provider: "duckduckgo",
|
||||
showSearchSuggestions: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const input = screen.getByPlaceholderText("Search");
|
||||
await waitFor(() => expect(input).toHaveFocus());
|
||||
|
||||
fireEvent.change(input, { target: { value: "example.com" } });
|
||||
expect(await screen.findByText("quicklaunch.visit URL")).toBeInTheDocument();
|
||||
|
||||
fireEvent.keyDown(input, { key: "Escape" });
|
||||
await act(async () => {
|
||||
await new Promise((r) => setTimeout(r, 350));
|
||||
});
|
||||
|
||||
// reopen by "typing" a character, the way pages/index does
|
||||
fireEvent.click(screen.getByTestId("seed-key"));
|
||||
|
||||
expect(input).toHaveValue("g");
|
||||
expect(screen.queryByText("quicklaunch.visit URL")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("closes on Escape and clears the search string after the timeout", async () => {
|
||||
renderWithProviders(<Wrapper />, {
|
||||
settings: {
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { useTranslation } from "next-i18next/pages";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useMemo } from "react";
|
||||
|
||||
import Container from "../widget/container";
|
||||
import Raw from "../widget/raw";
|
||||
|
||||
import useCurrentTime from "utils/hooks/use-current-time";
|
||||
|
||||
const textSizes = {
|
||||
"4xl": "text-4xl",
|
||||
"3xl": "text-3xl",
|
||||
@@ -18,17 +20,10 @@ const textSizes = {
|
||||
export default function DateTime({ options }) {
|
||||
const { text_size: textSize, locale, format } = options;
|
||||
const { i18n } = useTranslation();
|
||||
const [date, setDate] = useState("");
|
||||
const dateLocale = locale ?? i18n.language;
|
||||
|
||||
useEffect(() => {
|
||||
const dateFormat = new Intl.DateTimeFormat(dateLocale, { ...format });
|
||||
setDate(dateFormat.format(new Date()));
|
||||
const interval = setInterval(() => {
|
||||
setDate(dateFormat.format(new Date()));
|
||||
}, 1000);
|
||||
return () => clearInterval(interval);
|
||||
}, [date, setDate, dateLocale, format]);
|
||||
const currentTime = useCurrentTime(1000);
|
||||
const dateFormatter = useMemo(() => new Intl.DateTimeFormat(dateLocale, { ...format }), [dateLocale, format]);
|
||||
const date = currentTime === null ? "" : dateFormatter.format(new Date(currentTime));
|
||||
|
||||
return (
|
||||
<Container options={options} additionalClassNames="information-widget-datetime">
|
||||
|
||||
@@ -7,9 +7,9 @@ import Resource from "../widget/resource";
|
||||
|
||||
export default function Network({ options, refresh = 1500 }) {
|
||||
const { t } = useTranslation();
|
||||
if (options.network === true) options.network = "default";
|
||||
const network = options.network === true ? "default" : options.network;
|
||||
|
||||
const { data, error } = useSWR(`/api/widgets/resources?type=network&interfaceName=${options.network}`, {
|
||||
const { data, error } = useSWR(`/api/widgets/resources?type=network&interfaceName=${network}`, {
|
||||
refreshInterval: refresh,
|
||||
});
|
||||
|
||||
|
||||
@@ -22,10 +22,12 @@ describe("components/widgets/resources/network", () => {
|
||||
|
||||
it("normalizes options.network=true to default interfaceName in the request", () => {
|
||||
useSWR.mockReturnValue({ data: undefined, error: undefined });
|
||||
const options = Object.freeze({ network: true });
|
||||
|
||||
render(<Network options={{ network: true }} />);
|
||||
render(<Network options={options} />);
|
||||
|
||||
expect(useSWR).toHaveBeenCalledWith(expect.stringContaining("interfaceName=default"), expect.any(Object));
|
||||
expect(options.network).toBe(true);
|
||||
});
|
||||
|
||||
it("renders rates and usage percentage when data is present", () => {
|
||||
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
} from "@headlessui/react";
|
||||
import classNames from "classnames";
|
||||
import { useTranslation } from "next-i18next/pages";
|
||||
import { Fragment, useEffect, useMemo, useState } from "react";
|
||||
import { Fragment, useEffect, useMemo, useState, useSyncExternalStore } from "react";
|
||||
import { BiLogoBing } from "react-icons/bi";
|
||||
import { FiSearch } from "react-icons/fi";
|
||||
import { SiBaidu, SiBrave, SiDuckduckgo, SiGoogle } from "react-icons/si";
|
||||
@@ -79,24 +79,32 @@ export function getStoredProvider() {
|
||||
return null;
|
||||
}
|
||||
|
||||
function subscribeToStoredProvider(onStoreChange) {
|
||||
const handleStorage = (event) => {
|
||||
if (event.key === localStorageKey) onStoreChange();
|
||||
};
|
||||
|
||||
window.addEventListener("storage", handleStorage);
|
||||
return () => window.removeEventListener("storage", handleStorage);
|
||||
}
|
||||
|
||||
export default function Search({ options }) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
// options is a fresh object each render, so memo on provider itself
|
||||
const availableProviderIds = useMemo(() => getAvailableProviderIds(options.provider) ?? [], [options.provider]);
|
||||
const storedProvider = useSyncExternalStore(subscribeToStoredProvider, getStoredProvider, () => null);
|
||||
const storedProviderId = Object.keys(searchProviders).find(
|
||||
(providerId) => searchProviders[providerId] === storedProvider,
|
||||
);
|
||||
const initialProvider = availableProviderIds.includes(storedProviderId)
|
||||
? storedProvider
|
||||
: searchProviders[availableProviderIds[0] ?? "google"];
|
||||
|
||||
const [query, setQuery] = useState("");
|
||||
const [selectedProvider, setSelectedProvider] = useState(searchProviders[availableProviderIds[0] ?? "google"]);
|
||||
const [providerOverride, setProviderOverride] = useState(null);
|
||||
const [searchSuggestions, setSearchSuggestions] = useState([]);
|
||||
|
||||
useEffect(() => {
|
||||
const storedProvider = getStoredProvider();
|
||||
let storedProviderKey = null;
|
||||
storedProviderKey = Object.keys(searchProviders).find((pkey) => searchProviders[pkey] === storedProvider);
|
||||
if (storedProvider && availableProviderIds.includes(storedProviderKey)) {
|
||||
setSelectedProvider(storedProvider);
|
||||
}
|
||||
}, [availableProviderIds]);
|
||||
const selectedProvider = providerOverride ?? initialProvider;
|
||||
|
||||
useEffect(() => {
|
||||
const abortController = new AbortController();
|
||||
@@ -130,8 +138,6 @@ export default function Search({ options }) {
|
||||
};
|
||||
}, [selectedProvider, options, query, searchSuggestions]);
|
||||
|
||||
let currentSuggestion;
|
||||
|
||||
function doSearch(value) {
|
||||
const q = encodeURIComponent(value);
|
||||
const { url } = selectedProvider;
|
||||
@@ -142,13 +148,11 @@ export default function Search({ options }) {
|
||||
}
|
||||
|
||||
setQuery("");
|
||||
currentSuggestion = null;
|
||||
}
|
||||
|
||||
const handleSearchKeyDown = (event) => {
|
||||
const useSuggestion = searchSuggestions.length && currentSuggestion;
|
||||
if (event.key === "Enter") {
|
||||
doSearch(useSuggestion ? currentSuggestion : event.target.value);
|
||||
if (event.key === "Enter" && !searchSuggestions[1]?.length) {
|
||||
doSearch(event.target.value);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -157,7 +161,7 @@ export default function Search({ options }) {
|
||||
}
|
||||
|
||||
const onChangeProvider = (provider) => {
|
||||
setSelectedProvider(provider);
|
||||
setProviderOverride(provider);
|
||||
localStorage.setItem(localStorageKey, provider.name);
|
||||
};
|
||||
|
||||
@@ -166,7 +170,7 @@ export default function Search({ options }) {
|
||||
<Raw>
|
||||
<div className="flex-col relative h-8 my-4 min-w-fit z-20">
|
||||
<div className="flex absolute inset-y-0 left-0 items-center pl-3 pointer-events-none w-full text-theme-800 dark:text-white" />
|
||||
<Combobox value={query}>
|
||||
<Combobox value={query} onChange={doSearch}>
|
||||
<ComboboxInput
|
||||
type="text"
|
||||
className="
|
||||
@@ -178,6 +182,7 @@ export default function Search({ options }) {
|
||||
focus:border-theme-500 dark:focus:border-white/50
|
||||
border border-theme-300 dark:border-theme-200/50"
|
||||
placeholder={t("search.placeholder")}
|
||||
aria-label={t("search.placeholder")}
|
||||
onChange={(event) => {
|
||||
setQuery(event.target.value);
|
||||
}}
|
||||
@@ -204,8 +209,8 @@ export default function Search({ options }) {
|
||||
bg-theme-600/40 dark:bg-white/10
|
||||
focus:ring-theme-500 dark:focus:ring-white/50"
|
||||
>
|
||||
<selectedProvider.icon className="text-white w-3 h-3" />
|
||||
<span className="sr-only">{t("search.search")}</span>
|
||||
<selectedProvider.icon className="text-white w-3 h-3" aria-hidden="true" />
|
||||
<span className="sr-only">{t("search.provider", { name: selectedProvider.name })}</span>
|
||||
</ListboxButton>
|
||||
</div>
|
||||
<Transition
|
||||
@@ -218,6 +223,7 @@ export default function Search({ options }) {
|
||||
leaveTo="transform opacity-0 scale-95"
|
||||
>
|
||||
<ListboxOptions
|
||||
aria-label={t("search.select_provider")}
|
||||
className="absolute right-0 z-10 mt-1 origin-top-right rounded-md
|
||||
bg-theme-100 dark:bg-theme-600 shadow-lg
|
||||
ring-1 ring-black ring-opacity-5 focus:outline-hidden"
|
||||
@@ -234,7 +240,8 @@ export default function Search({ options }) {
|
||||
active ? "bg-theme-600/10 dark:bg-white/10 dark:text-gray-900" : "dark:text-gray-100",
|
||||
)}
|
||||
>
|
||||
<p.icon className="h-4 w-4 mx-4 my-2" />
|
||||
<p.icon className="h-4 w-4 mx-4 my-2" aria-hidden="true" />
|
||||
<span className="sr-only">{p.name}</span>
|
||||
</li>
|
||||
)}
|
||||
</ListboxOption>
|
||||
@@ -248,32 +255,24 @@ export default function Search({ options }) {
|
||||
{searchSuggestions[1]?.length > 0 && (
|
||||
<ComboboxOptions className="mt-1 rounded-md bg-theme-50 dark:bg-theme-800 border border-theme-300 dark:border-theme-200/30 cursor-pointer shadow-lg">
|
||||
<div className="p-1 bg-white/50 dark:bg-white/10 text-theme-900/90 dark:text-white/90 text-xs">
|
||||
<ComboboxOption key={query} value={query} />
|
||||
<ComboboxOption key={query} value={query}>
|
||||
<span className="sr-only">{query}</span>
|
||||
</ComboboxOption>
|
||||
{searchSuggestions[1].map((suggestion) => (
|
||||
<ComboboxOption
|
||||
key={suggestion}
|
||||
value={suggestion}
|
||||
onMouseDown={() => {
|
||||
doSearch(suggestion);
|
||||
}}
|
||||
className="flex w-full"
|
||||
>
|
||||
{({ active }) => {
|
||||
if (active) currentSuggestion = suggestion;
|
||||
return (
|
||||
<div
|
||||
className={classNames(
|
||||
"px-2 py-1 rounded-md w-full flex-nowrap",
|
||||
active ? "bg-theme-300/20 dark:bg-white/10" : "",
|
||||
)}
|
||||
>
|
||||
<span className="whitespace-pre">{suggestion.indexOf(query) === 0 ? query : ""}</span>
|
||||
<span className="mr-4 whitespace-pre opacity-50">
|
||||
{suggestion.indexOf(query) === 0 ? suggestion.substring(query.length) : suggestion}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}}
|
||||
<ComboboxOption key={suggestion} value={suggestion} className="flex w-full">
|
||||
{({ active }) => (
|
||||
<div
|
||||
className={classNames(
|
||||
"px-2 py-1 rounded-md w-full flex-nowrap",
|
||||
active ? "bg-theme-300/20 dark:bg-white/10" : "",
|
||||
)}
|
||||
>
|
||||
<span className="whitespace-pre">{suggestion.indexOf(query) === 0 ? query : ""}</span>
|
||||
<span className="mr-4 whitespace-pre opacity-50">
|
||||
{suggestion.indexOf(query) === 0 ? suggestion.substring(query.length) : suggestion}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</ComboboxOption>
|
||||
))}
|
||||
</div>
|
||||
|
||||
@@ -9,6 +9,7 @@ import { renderWithProviders } from "test-utils/render-with-providers";
|
||||
vi.mock("@headlessui/react", async () => {
|
||||
const React = await import("react");
|
||||
const { Fragment, createContext, useContext } = React;
|
||||
const ComboboxContext = createContext(null);
|
||||
const ListboxContext = createContext(null);
|
||||
|
||||
function passthrough({ as: As = "div", children, ...props }) {
|
||||
@@ -18,9 +19,21 @@ vi.mock("@headlessui/react", async () => {
|
||||
}
|
||||
|
||||
return {
|
||||
Combobox: passthrough,
|
||||
Combobox: ({ onChange, children }) => (
|
||||
<ComboboxContext.Provider value={{ onChange }}>
|
||||
<div>{children}</div>
|
||||
</ComboboxContext.Provider>
|
||||
),
|
||||
ComboboxInput: (props) => <input {...props} />,
|
||||
ComboboxOption: passthrough,
|
||||
ComboboxOption: ({ as: As = "div", value, children, ...props }) => {
|
||||
const ctx = useContext(ComboboxContext);
|
||||
const content = typeof children === "function" ? children({ active: false }) : children;
|
||||
return (
|
||||
<As value={value} onMouseDown={() => ctx?.onChange?.(value)} {...props}>
|
||||
{content}
|
||||
</As>
|
||||
);
|
||||
},
|
||||
ComboboxOptions: passthrough,
|
||||
Listbox: ({ value, onChange, children, ...props }) => (
|
||||
<ListboxContext.Provider value={{ value, onChange }}>
|
||||
@@ -165,6 +178,28 @@ describe("components/widgets/search", () => {
|
||||
openSpy.mockRestore();
|
||||
});
|
||||
|
||||
it("gives every provider option an accessible name", () => {
|
||||
renderWithProviders(
|
||||
<Search options={{ provider: ["google", "duckduckgo", "brave"], showSearchSuggestions: false }} />,
|
||||
{ settings: {} },
|
||||
);
|
||||
|
||||
expect(screen.getAllByRole("option").map((option) => option.textContent)).toEqual([
|
||||
"Google",
|
||||
"DuckDuckGo",
|
||||
"Brave",
|
||||
]);
|
||||
});
|
||||
|
||||
it("labels the search input and the provider button", () => {
|
||||
renderWithProviders(<Search options={{ provider: ["google", "duckduckgo"], showSearchSuggestions: false }} />, {
|
||||
settings: {},
|
||||
});
|
||||
|
||||
expect(screen.getByRole("textbox")).toHaveAccessibleName("search.placeholder");
|
||||
expect(screen.getByRole("button")).toHaveAccessibleName(/search\.provider/);
|
||||
});
|
||||
|
||||
it("fetches search suggestions and triggers a search when a suggestion is selected", async () => {
|
||||
const openSpy = vi.spyOn(window, "open").mockImplementation(() => null);
|
||||
|
||||
|
||||
@@ -14,11 +14,11 @@ import useWidgetAPI from "utils/proxy/use-widget-api";
|
||||
export default function Widget({ options }) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
options.service_group = options.service_name = "unifi_console";
|
||||
const { data: statsData, error: statsError } = useWidgetAPI(options, "stat/sites", { index: options.index });
|
||||
const widgetOptions = { ...options, service_group: "unifi_console", service_name: "unifi_console" };
|
||||
const { data: statsData, error: statsError } = useWidgetAPI(widgetOptions, "stat/sites", { index: options.index });
|
||||
|
||||
if (statsError) {
|
||||
return <Error options={options} />;
|
||||
return <Error options={widgetOptions} />;
|
||||
}
|
||||
|
||||
const defaultSite = options.site
|
||||
@@ -27,27 +27,27 @@ export default function Widget({ options }) {
|
||||
|
||||
if (!defaultSite) {
|
||||
return (
|
||||
<Container options={options} additionalClassNames="information-widget-unifi-console">
|
||||
<Container options={widgetOptions} additionalClassNames="information-widget-unifi-console">
|
||||
<PrimaryText>{t("unifi.wait")}</PrimaryText>
|
||||
<WidgetIcon icon={SiUbiquiti} />
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
|
||||
const wan = defaultSite.health.find((h) => h.subsystem === "wan");
|
||||
const lan = defaultSite.health.find((h) => h.subsystem === "lan");
|
||||
const wlan = defaultSite.health.find((h) => h.subsystem === "wlan");
|
||||
[wan, lan, wlan].forEach((s) => {
|
||||
s.up = s.status === "ok";
|
||||
s.show = s.status !== "unknown";
|
||||
});
|
||||
const getHealth = (subsystem) => {
|
||||
const health = defaultSite.health.find((item) => item.subsystem === subsystem) ?? { status: "unknown" };
|
||||
return { ...health, up: health.status === "ok", show: health.status !== "unknown" };
|
||||
};
|
||||
const wan = getHealth("wan");
|
||||
const lan = getHealth("lan");
|
||||
const wlan = getHealth("wlan");
|
||||
const name = wan.gw_name ?? defaultSite.desc;
|
||||
const uptime = wan["gw_system-stats"] ? wan["gw_system-stats"].uptime : null;
|
||||
|
||||
const dataEmpty = !(wan.show || lan.show || wlan.show || uptime);
|
||||
|
||||
return (
|
||||
<Container options={options} additionalClassNames="information-widget-unifi-console">
|
||||
<Container options={widgetOptions} additionalClassNames="information-widget-unifi-console">
|
||||
<Raw>
|
||||
<div className="flex-none flex flex-row items-center mr-3 py-1.5">
|
||||
<div className="flex flex-col">
|
||||
|
||||
@@ -40,32 +40,41 @@ describe("components/widgets/unifi_console", () => {
|
||||
|
||||
it("renders a wait state when no site is available yet", () => {
|
||||
useWidgetAPI.mockReturnValue({ data: undefined, error: undefined });
|
||||
const options = Object.freeze({ index: 0 });
|
||||
|
||||
renderWithProviders(<UnifiConsole options={{ index: 0 }} />, { settings: { target: "_self" } });
|
||||
renderWithProviders(<UnifiConsole options={options} />, { settings: { target: "_self" } });
|
||||
|
||||
expect(screen.getByText("unifi.wait")).toBeInTheDocument();
|
||||
expect(useWidgetAPI).toHaveBeenCalledWith(
|
||||
{ index: 0, service_group: "unifi_console", service_name: "unifi_console" },
|
||||
"stat/sites",
|
||||
{ index: 0 },
|
||||
);
|
||||
expect(options).toEqual({ index: 0 });
|
||||
});
|
||||
|
||||
it("renders site name and uptime when data is available", () => {
|
||||
const data = {
|
||||
data: [
|
||||
{
|
||||
name: "default",
|
||||
desc: "Home",
|
||||
health: [
|
||||
{
|
||||
subsystem: "wan",
|
||||
status: "ok",
|
||||
gw_name: "Router",
|
||||
"gw_system-stats": { uptime: 172800 },
|
||||
},
|
||||
{ subsystem: "lan", status: "unknown" },
|
||||
{ subsystem: "wlan", status: "unknown" },
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
const originalData = structuredClone(data);
|
||||
useWidgetAPI.mockReturnValue({
|
||||
data: {
|
||||
data: [
|
||||
{
|
||||
name: "default",
|
||||
desc: "Home",
|
||||
health: [
|
||||
{
|
||||
subsystem: "wan",
|
||||
status: "ok",
|
||||
gw_name: "Router",
|
||||
"gw_system-stats": { uptime: 172800 },
|
||||
},
|
||||
{ subsystem: "lan", status: "unknown" },
|
||||
{ subsystem: "wlan", status: "unknown" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
data,
|
||||
error: undefined,
|
||||
});
|
||||
|
||||
@@ -75,6 +84,7 @@ describe("components/widgets/unifi_console", () => {
|
||||
// common.number is mocked to return the numeric value as a string.
|
||||
expect(screen.getByText("2")).toBeInTheDocument();
|
||||
expect(screen.getByText("unifi.days")).toBeInTheDocument();
|
||||
expect(data).toEqual(originalData);
|
||||
});
|
||||
|
||||
it("selects a site by description when options.site is set", () => {
|
||||
|
||||
@@ -71,6 +71,16 @@ function logFailedPasswordSignIn() {
|
||||
createLogger("nextauth").warn("Failed password sign-in attempt");
|
||||
}
|
||||
|
||||
function logNextAuthError(code, metadata) {
|
||||
const error = metadata instanceof Error ? metadata : metadata?.error;
|
||||
|
||||
if (error?.message) {
|
||||
createLogger("nextauth").error("%s: %s", code, error.message);
|
||||
} else {
|
||||
createLogger("nextauth").error("%s", code);
|
||||
}
|
||||
}
|
||||
|
||||
let providers = [];
|
||||
if (authEnabled) {
|
||||
if (hasOidcConfig) {
|
||||
@@ -140,7 +150,7 @@ export const authOptions = {
|
||||
signIn: "/auth/signin",
|
||||
},
|
||||
logger: {
|
||||
error: (code) => createLogger("nextauth").error("%s", code),
|
||||
error: logNextAuthError,
|
||||
warn: (code) => createLogger("nextauth").warn("%s", code),
|
||||
debug: (code) => createLogger("nextauth").debug("%s", code),
|
||||
},
|
||||
|
||||
@@ -15,6 +15,12 @@ export default async function handler(req, res) {
|
||||
return res.status(404).end("Not Found");
|
||||
}
|
||||
|
||||
// Method check precedes auth so CORS preflights aren't answered with a 401.
|
||||
if (req.method !== "POST") {
|
||||
res.setHeader("Allow", "POST");
|
||||
return res.status(405).end("Method Not Allowed");
|
||||
}
|
||||
|
||||
const tokenError = mcpTokenConfigError();
|
||||
if (tokenError) {
|
||||
createLogger("mcp").error(tokenError);
|
||||
@@ -25,11 +31,6 @@ export default async function handler(req, res) {
|
||||
return res.status(401).json({ error: "Unauthorized" });
|
||||
}
|
||||
|
||||
if (req.method !== "POST") {
|
||||
res.setHeader("Allow", "POST");
|
||||
return res.status(405).end("Method Not Allowed");
|
||||
}
|
||||
|
||||
const response = handleMcpRequest(req.body);
|
||||
if (!response) {
|
||||
return res.status(202).end();
|
||||
|
||||
@@ -214,4 +214,38 @@ describe("pages/api/mcp", () => {
|
||||
expect(res.status).toHaveBeenCalledWith(405);
|
||||
expect(res.setHeader).toHaveBeenCalledWith("Allow", "POST");
|
||||
});
|
||||
|
||||
it("answers unauthenticated CORS preflights with 405 rather than 401", async () => {
|
||||
process.env.HOMEPAGE_MCP_ENABLED = "true";
|
||||
process.env.HOMEPAGE_MCP_TOKEN = "mcp-tok-0123456789abcdefghijklmnopqrstuv";
|
||||
const handler = await loadHandler();
|
||||
const res = mockResponse();
|
||||
|
||||
// a preflight never carries the Authorization header the browser strips
|
||||
await handler(
|
||||
{
|
||||
method: "OPTIONS",
|
||||
headers: {
|
||||
origin: "https://claude.ai",
|
||||
"access-control-request-method": "POST",
|
||||
"access-control-request-headers": "authorization,content-type",
|
||||
},
|
||||
},
|
||||
res,
|
||||
);
|
||||
|
||||
expect(res.status).toHaveBeenCalledWith(405);
|
||||
expect(res.setHeader).toHaveBeenCalledWith("Allow", "POST");
|
||||
expect(getServerSession).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("still returns 404 for non-POST requests while disabled", async () => {
|
||||
delete process.env.HOMEPAGE_MCP_ENABLED;
|
||||
const handler = await loadHandler();
|
||||
const res = mockResponse();
|
||||
|
||||
await handler({ method: "OPTIONS", headers: {} }, res);
|
||||
|
||||
expect(res.status).toHaveBeenCalledWith(404);
|
||||
});
|
||||
});
|
||||
|
||||
+35
-28
@@ -12,7 +12,7 @@ import dynamic from "next/dynamic";
|
||||
import Head from "next/head";
|
||||
import { useRouter } from "next/router";
|
||||
import Script from "next/script";
|
||||
import { useContext, useEffect, useMemo, useState } from "react";
|
||||
import { useCallback, useContext, useEffect, useMemo, useState } from "react";
|
||||
import { BiError } from "react-icons/bi";
|
||||
import useSWR, { SWRConfig } from "swr";
|
||||
import { ColorContext } from "utils/contexts/color";
|
||||
@@ -102,7 +102,29 @@ function Index({ initialSettings, fallback }) {
|
||||
const [stale, setStale] = useState(false);
|
||||
const { data: errorsData } = useSWR("/api/validate");
|
||||
const { error: validateError } = errorsData || {};
|
||||
const { data: hashData, mutate: mutateHash } = useSWR("/api/hash");
|
||||
|
||||
const handleHashData = useCallback((hashData) => {
|
||||
if (typeof window === "undefined" || !hashData?.hash) return;
|
||||
|
||||
const previousHash = localStorage.getItem("hash");
|
||||
|
||||
if (!previousHash) {
|
||||
localStorage.setItem("hash", hashData.hash);
|
||||
}
|
||||
|
||||
if (previousHash && previousHash !== hashData.hash) {
|
||||
setStale(true);
|
||||
localStorage.setItem("hash", hashData.hash);
|
||||
|
||||
fetch("/api/revalidate").then((res) => {
|
||||
if (res.ok) {
|
||||
window.location.reload();
|
||||
}
|
||||
});
|
||||
}
|
||||
}, []);
|
||||
|
||||
const { mutate: mutateHash } = useSWR("/api/hash", { onSuccess: handleHashData });
|
||||
|
||||
useEffect(() => {
|
||||
if (windowFocused) {
|
||||
@@ -110,29 +132,6 @@ function Index({ initialSettings, fallback }) {
|
||||
}
|
||||
}, [windowFocused, mutateHash]);
|
||||
|
||||
useEffect(() => {
|
||||
if (hashData) {
|
||||
if (typeof window !== "undefined") {
|
||||
const previousHash = localStorage.getItem("hash");
|
||||
|
||||
if (!previousHash) {
|
||||
localStorage.setItem("hash", hashData.hash);
|
||||
}
|
||||
|
||||
if (previousHash && previousHash !== hashData.hash) {
|
||||
setStale(true);
|
||||
localStorage.setItem("hash", hashData.hash);
|
||||
|
||||
fetch("/api/revalidate").then((res) => {
|
||||
if (res.ok) {
|
||||
window.location.reload();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}, [hashData]);
|
||||
|
||||
if (validateError) {
|
||||
return (
|
||||
<div className="w-full h-screen container m-auto justify-center p-10 pointer-events-none">
|
||||
@@ -264,6 +263,13 @@ function Home({ initialSettings }) {
|
||||
e.key.match(/([à-ü]|[À-Ü]|!)/g) ||
|
||||
(e.key === "v" && (e.ctrlKey || e.metaKey))
|
||||
) {
|
||||
if (e.key.length === 1 && !(e.key === "v" && (e.ctrlKey || e.metaKey))) {
|
||||
e.preventDefault();
|
||||
// whitespace opens the search but shouldn't be in it
|
||||
if (e.key.trim()) {
|
||||
setSearchString((currentSearchString) => currentSearchString + e.key);
|
||||
}
|
||||
}
|
||||
setSearching(true);
|
||||
} else if (e.key === "Escape") {
|
||||
setSearchString("");
|
||||
@@ -420,10 +426,11 @@ function Home({ initialSettings }) {
|
||||
/>
|
||||
{settings.disableIndexing && <meta name="robots" content="noindex, nofollow" />}
|
||||
{settings.base && <base href={settings.base} />}
|
||||
{settings.favicon ? (
|
||||
{/* from props, not context so its set before running JS */}
|
||||
{initialSettings.favicon ? (
|
||||
<>
|
||||
<link rel="icon" href={settings.favicon} />
|
||||
<link rel="apple-touch-icon" sizes="180x180" href={settings.favicon} />
|
||||
<link rel="icon" href={initialSettings.favicon} />
|
||||
<link rel="apple-touch-icon" sizes="180x180" href={initialSettings.favicon} />
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import { promises as fs } from "fs";
|
||||
import path from "path";
|
||||
|
||||
import yaml from "js-yaml";
|
||||
|
||||
import checkAndCopyConfig, { CONF_DIR, getSettings, substituteEnvironmentVars } from "utils/config/config";
|
||||
import {
|
||||
cleanServiceGroups,
|
||||
@@ -12,6 +10,7 @@ import {
|
||||
servicesFromKubernetes,
|
||||
} from "utils/config/service-helpers";
|
||||
import { cleanWidgetGroups, widgetsFromConfig } from "utils/config/widget-helpers";
|
||||
import { loadYaml } from "utils/config/yaml";
|
||||
|
||||
/**
|
||||
* Compares services by weight then by name.
|
||||
@@ -30,7 +29,7 @@ export async function bookmarksResponse() {
|
||||
const bookmarksYaml = path.join(CONF_DIR, "bookmarks.yaml");
|
||||
const rawFileContents = await fs.readFile(bookmarksYaml, "utf8");
|
||||
const fileContents = substituteEnvironmentVars(rawFileContents);
|
||||
const bookmarks = yaml.load(fileContents);
|
||||
const bookmarks = loadYaml(fileContents);
|
||||
|
||||
if (!bookmarks) return [];
|
||||
|
||||
|
||||
@@ -30,10 +30,7 @@ vi.mock("fs", () => ({
|
||||
promises: fs,
|
||||
}));
|
||||
|
||||
vi.mock("js-yaml", () => ({
|
||||
default: yaml,
|
||||
...yaml,
|
||||
}));
|
||||
vi.mock("utils/config/yaml", () => ({ loadYaml: yaml.load }));
|
||||
|
||||
vi.mock("utils/config/config", () => config);
|
||||
vi.mock("utils/config/widget-helpers", () => widgetHelpers);
|
||||
|
||||
@@ -13,7 +13,7 @@ const { fs, yaml } = vi.hoisted(() => ({
|
||||
}));
|
||||
|
||||
vi.mock("fs", () => fs);
|
||||
vi.mock("js-yaml", () => ({ default: yaml, ...yaml }));
|
||||
vi.mock("utils/config/yaml", () => ({ loadYaml: yaml.load }));
|
||||
|
||||
describe("utils/config/config checkAndCopyConfig", () => {
|
||||
const originalEnv = process.env;
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { copyFileSync, existsSync, mkdirSync, readFileSync } from "fs";
|
||||
import { join } from "path";
|
||||
|
||||
import yaml from "js-yaml";
|
||||
import cache from "memory-cache";
|
||||
|
||||
import { loadYaml } from "utils/config/yaml";
|
||||
|
||||
const cacheKey = "homepageEnvironmentVariables";
|
||||
const homepageVarPrefix = "HOMEPAGE_VAR_";
|
||||
const homepageFilePrefix = "HOMEPAGE_FILE_";
|
||||
@@ -42,7 +43,7 @@ export default function checkAndCopyConfig(config) {
|
||||
}
|
||||
|
||||
try {
|
||||
yaml.load(readFileSync(configYaml, "utf8"));
|
||||
loadYaml(readFileSync(configYaml, "utf8"));
|
||||
return true;
|
||||
} catch (e) {
|
||||
return { ...e, config };
|
||||
@@ -85,7 +86,7 @@ export function getSettings() {
|
||||
const settingsYaml = join(CONF_DIR, "settings.yaml");
|
||||
const rawFileContents = readFileSync(settingsYaml, "utf8");
|
||||
const fileContents = substituteEnvironmentVars(rawFileContents);
|
||||
const initialSettings = yaml.load(fileContents) ?? {};
|
||||
const initialSettings = loadYaml(fileContents) ?? {};
|
||||
|
||||
if (initialSettings.layout) {
|
||||
// support yaml list but old spec was object so convert to that
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import { readFileSync } from "fs";
|
||||
import path from "path";
|
||||
|
||||
import yaml from "js-yaml";
|
||||
|
||||
import checkAndCopyConfig, { CONF_DIR, substituteEnvironmentVars } from "utils/config/config";
|
||||
import { loadYaml } from "utils/config/yaml";
|
||||
|
||||
export function getDefaultDockerArgs(platform = process.platform) {
|
||||
if (platform !== "win32" && platform !== "darwin") {
|
||||
@@ -19,7 +18,7 @@ export default function getDockerArguments(server) {
|
||||
const configFile = path.join(CONF_DIR, "docker.yaml");
|
||||
const rawConfigData = readFileSync(configFile, "utf8");
|
||||
const configData = substituteEnvironmentVars(rawConfigData);
|
||||
const servers = yaml.load(configData);
|
||||
const servers = loadYaml(configData);
|
||||
|
||||
if (!server) {
|
||||
return getDefaultDockerArgs();
|
||||
|
||||
@@ -21,10 +21,7 @@ vi.mock("fs", () => ({
|
||||
readFileSync: fs.readFileSync,
|
||||
}));
|
||||
|
||||
vi.mock("js-yaml", () => ({
|
||||
default: yaml,
|
||||
...yaml,
|
||||
}));
|
||||
vi.mock("utils/config/yaml", () => ({ loadYaml: yaml.load }));
|
||||
|
||||
vi.mock("utils/config/config", () => ({
|
||||
default: checkAndCopyConfig,
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
import { readFileSync } from "fs";
|
||||
import { isIPv6 } from "net";
|
||||
import path from "path";
|
||||
|
||||
import { ApiextensionsV1Api, KubeConfig } from "@kubernetes/client-node";
|
||||
import yaml from "js-yaml";
|
||||
|
||||
import checkAndCopyConfig, { CONF_DIR, substituteEnvironmentVars } from "utils/config/config";
|
||||
import { loadYaml } from "utils/config/yaml";
|
||||
|
||||
export function getKubernetes() {
|
||||
checkAndCopyConfig("kubernetes.yaml");
|
||||
const configFile = path.join(CONF_DIR, "kubernetes.yaml");
|
||||
const rawConfigData = readFileSync(configFile, "utf8");
|
||||
const configData = substituteEnvironmentVars(rawConfigData);
|
||||
return yaml.load(configData);
|
||||
return loadYaml(configData);
|
||||
}
|
||||
|
||||
export const getKubeConfig = () => {
|
||||
@@ -21,6 +22,10 @@ export const getKubeConfig = () => {
|
||||
switch (config?.mode) {
|
||||
case "cluster":
|
||||
kc.loadFromCluster();
|
||||
// node < 26 can't match an IPv6 host against an IP SAN, so verify against the DNS SAN instead (nodejs/node#64032)
|
||||
if (isIPv6(process.env.KUBERNETES_SERVICE_HOST ?? "")) {
|
||||
kc.clusters = kc.clusters.map((cluster) => ({ ...cluster, tlsServerName: "kubernetes.default.svc" }));
|
||||
}
|
||||
break;
|
||||
case "default":
|
||||
kc.loadFromDefault();
|
||||
|
||||
@@ -32,10 +32,7 @@ vi.mock("fs", () => ({
|
||||
readFileSync: fs.readFileSync,
|
||||
}));
|
||||
|
||||
vi.mock("js-yaml", () => ({
|
||||
default: yaml,
|
||||
...yaml,
|
||||
}));
|
||||
vi.mock("utils/config/yaml", () => ({ loadYaml: yaml.load }));
|
||||
|
||||
vi.mock("utils/config/config", () => ({
|
||||
default: checkAndCopyConfig,
|
||||
@@ -46,6 +43,7 @@ vi.mock("@kubernetes/client-node", () => ({
|
||||
ApiextensionsV1Api: class ApiextensionsV1Api {},
|
||||
KubeConfig: class KubeConfig {
|
||||
loadFromCluster() {
|
||||
this.clusters = [{ name: "inCluster", server: "https://host:443", skipTLSVerify: false }];
|
||||
return kube.loadFromCluster();
|
||||
}
|
||||
loadFromDefault() {
|
||||
@@ -88,6 +86,27 @@ describe("utils/config/kubernetes", () => {
|
||||
expect(kc2).not.toBeNull();
|
||||
});
|
||||
|
||||
it("getKubeConfig sets tlsServerName when the in-cluster host is IPv6", () => {
|
||||
vi.stubEnv("KUBERNETES_SERVICE_HOST", "fd00:1018:2000::1");
|
||||
yaml.load.mockReturnValueOnce({ mode: "cluster" });
|
||||
|
||||
expect(getKubeConfig().clusters[0]).toMatchObject({
|
||||
name: "inCluster",
|
||||
tlsServerName: "kubernetes.default.svc",
|
||||
});
|
||||
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
it("getKubeConfig leaves tlsServerName unset for non-IPv6 in-cluster hosts", () => {
|
||||
vi.stubEnv("KUBERNETES_SERVICE_HOST", "10.43.0.1");
|
||||
yaml.load.mockReturnValueOnce({ mode: "cluster" });
|
||||
|
||||
expect(getKubeConfig().clusters[0].tlsServerName).toBeUndefined();
|
||||
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
it("checkCRD returns true when the CRD exists", async () => {
|
||||
apiExt.readCustomResourceDefinitionStatus.mockResolvedValueOnce({ ok: true });
|
||||
const logger = { error: vi.fn() };
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
import { readFileSync } from "fs";
|
||||
import path from "path";
|
||||
|
||||
import yaml from "js-yaml";
|
||||
|
||||
import checkAndCopyConfig, { CONF_DIR, substituteEnvironmentVars } from "utils/config/config";
|
||||
import { loadYaml } from "utils/config/yaml";
|
||||
|
||||
export function getProxmoxConfig() {
|
||||
checkAndCopyConfig("proxmox.yaml");
|
||||
const configFile = path.join(CONF_DIR, "proxmox.yaml");
|
||||
const rawConfigData = readFileSync(configFile, "utf8");
|
||||
const configData = substituteEnvironmentVars(rawConfigData);
|
||||
return yaml.load(configData);
|
||||
return loadYaml(configData);
|
||||
}
|
||||
|
||||
@@ -18,10 +18,7 @@ vi.mock("fs", () => ({
|
||||
readFileSync: fs.readFileSync,
|
||||
}));
|
||||
|
||||
vi.mock("js-yaml", () => ({
|
||||
default: yaml,
|
||||
...yaml,
|
||||
}));
|
||||
vi.mock("utils/config/yaml", () => ({ loadYaml: yaml.load }));
|
||||
|
||||
vi.mock("utils/config/config", () => ({
|
||||
default: checkAndCopyConfig,
|
||||
|
||||
@@ -2,12 +2,12 @@ import { promises as fs } from "fs";
|
||||
import path from "path";
|
||||
|
||||
import Docker from "dockerode";
|
||||
import yaml from "js-yaml";
|
||||
|
||||
import checkAndCopyConfig, { CONF_DIR, getSettings, substituteEnvironmentVars } from "utils/config/config";
|
||||
import getDockerArguments from "utils/config/docker";
|
||||
import { getKubeConfig } from "utils/config/kubernetes";
|
||||
import * as shvl from "utils/config/shvl";
|
||||
import { loadYaml } from "utils/config/yaml";
|
||||
import kubernetes from "utils/kubernetes/export";
|
||||
import createLogger from "utils/logger";
|
||||
import { parseVersionForUrl } from "utils/proxy/api-helpers";
|
||||
@@ -56,7 +56,7 @@ export async function servicesFromConfig() {
|
||||
const servicesYaml = path.join(CONF_DIR, "services.yaml");
|
||||
const rawFileContents = await fs.readFile(servicesYaml, "utf8");
|
||||
const fileContents = substituteEnvironmentVars(rawFileContents);
|
||||
const services = yaml.load(fileContents);
|
||||
const services = loadYaml(fileContents);
|
||||
return parseServicesToGroups(services);
|
||||
}
|
||||
|
||||
@@ -66,7 +66,7 @@ export async function servicesFromDocker() {
|
||||
const dockerYaml = path.join(CONF_DIR, "docker.yaml");
|
||||
const rawDockerFileContents = await fs.readFile(dockerYaml, "utf8");
|
||||
const dockerFileContents = substituteEnvironmentVars(rawDockerFileContents);
|
||||
const servers = yaml.load(dockerFileContents);
|
||||
const servers = loadYaml(dockerFileContents);
|
||||
|
||||
if (!servers) {
|
||||
return [];
|
||||
|
||||
@@ -70,10 +70,7 @@ vi.mock("fs", () => ({
|
||||
promises: fs,
|
||||
}));
|
||||
|
||||
vi.mock("js-yaml", () => ({
|
||||
default: yaml,
|
||||
...yaml,
|
||||
}));
|
||||
vi.mock("utils/config/yaml", () => ({ loadYaml: yaml.load }));
|
||||
|
||||
vi.mock("utils/config/config", () => config);
|
||||
vi.mock("dockerode", () => ({ default: Docker }));
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import { promises as fs } from "fs";
|
||||
import path from "path";
|
||||
|
||||
import yaml from "js-yaml";
|
||||
|
||||
import checkAndCopyConfig, { CONF_DIR, substituteEnvironmentVars } from "utils/config/config";
|
||||
import { loadYaml } from "utils/config/yaml";
|
||||
|
||||
export async function widgetsFromConfig() {
|
||||
checkAndCopyConfig("widgets.yaml");
|
||||
@@ -11,7 +10,7 @@ export async function widgetsFromConfig() {
|
||||
const widgetsYaml = path.join(CONF_DIR, "widgets.yaml");
|
||||
const rawFileContents = await fs.readFile(widgetsYaml, "utf8");
|
||||
const fileContents = substituteEnvironmentVars(rawFileContents);
|
||||
const widgets = yaml.load(fileContents);
|
||||
const widgets = loadYaml(fileContents);
|
||||
|
||||
if (!widgets) return [];
|
||||
|
||||
|
||||
@@ -18,10 +18,7 @@ vi.mock("fs", () => ({
|
||||
promises: fs,
|
||||
}));
|
||||
|
||||
vi.mock("js-yaml", () => ({
|
||||
default: yaml,
|
||||
...yaml,
|
||||
}));
|
||||
vi.mock("utils/config/yaml", () => ({ loadYaml: yaml.load }));
|
||||
|
||||
vi.mock("utils/config/config", () => config);
|
||||
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import * as yaml from "js-yaml";
|
||||
|
||||
const EMPTY_DOCUMENT_ERROR = "expected a document, but the input is empty";
|
||||
const DEFAULT_SCHEMA = yaml.CORE_SCHEMA.withTags(yaml.timestampTag, yaml.mergeTag, yaml.legacyMapTag);
|
||||
|
||||
export function loadYaml(input, options) {
|
||||
try {
|
||||
return yaml.load(input, { schema: DEFAULT_SCHEMA, ...options });
|
||||
} catch (error) {
|
||||
// js-yaml v4 returned undefined for empty and comment-only documents.
|
||||
if (error?.reason === EMPTY_DOCUMENT_ERROR) return undefined;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { loadYaml } from "./yaml";
|
||||
|
||||
describe("utils/config/yaml", () => {
|
||||
it.each(["", " \n", "# comment only\n"])("loads an empty document from %j as undefined", (input) => {
|
||||
expect(loadYaml(input)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("loads a populated document", () => {
|
||||
expect(loadYaml("title: Homepage\n")).toEqual({ title: "Homepage" });
|
||||
});
|
||||
|
||||
it("preserves v4 merge key behavior", () => {
|
||||
expect(loadYaml("defaults: &defaults\n href: https://example.com\nservice:\n <<: *defaults\n")).toEqual({
|
||||
defaults: { href: "https://example.com" },
|
||||
service: { href: "https://example.com" },
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves v4 timestamp behavior without enabling YAML 1.1 booleans", () => {
|
||||
expect(loadYaml("date: 2026-08-21\nenabled: yes\n")).toEqual({
|
||||
date: new Date("2026-08-21T00:00:00.000Z"),
|
||||
enabled: "yes",
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves v4 handling of non-string keys", () => {
|
||||
// an unsubstituted {{HOMEPAGE_VAR_*}} parses as a flow mapping key
|
||||
expect(loadYaml("- Plex:\n widget:\n key: {{HOMEPAGE_VAR_PLEX_KEY}}\n")).toEqual([
|
||||
{ Plex: { widget: { key: { "[object Object]": null } } } },
|
||||
]);
|
||||
expect(loadYaml("- Backups:\n - 2024-01-01:\n href: http://x\n")).toEqual([
|
||||
{ Backups: [{ [String(new Date("2024-01-01T00:00:00.000Z"))]: { href: "http://x" } }] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("still rejects invalid YAML", () => {
|
||||
expect(() => loadYaml("value: [\n")).toThrow();
|
||||
});
|
||||
});
|
||||
@@ -30,10 +30,6 @@ export function ColorProvider({ initialTheme, children }) {
|
||||
lastColor = rawColor;
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (initialTheme !== undefined) setColor(initialTheme ?? getInitialColor());
|
||||
}, [initialTheme]);
|
||||
|
||||
useEffect(() => {
|
||||
rawSetColor(color);
|
||||
}, [color]);
|
||||
|
||||
@@ -1,14 +1,10 @@
|
||||
import { createContext, useEffect, useMemo, useState } from "react";
|
||||
import { createContext, useMemo, useState } from "react";
|
||||
|
||||
export const SettingsContext = createContext();
|
||||
|
||||
export function SettingsProvider({ initialSettings, children }) {
|
||||
const [settings, setSettings] = useState(() => initialSettings ?? {});
|
||||
|
||||
useEffect(() => {
|
||||
if (initialSettings !== undefined) setSettings(initialSettings ?? {});
|
||||
}, [initialSettings]);
|
||||
|
||||
const value = useMemo(() => ({ settings, setSettings }), [settings]);
|
||||
|
||||
return <SettingsContext.Provider value={value}>{children}</SettingsContext.Provider>;
|
||||
|
||||
@@ -1,14 +1,10 @@
|
||||
import { createContext, useEffect, useMemo, useState } from "react";
|
||||
import { createContext, useMemo, useState } from "react";
|
||||
|
||||
export const TabContext = createContext();
|
||||
|
||||
export function TabProvider({ initialTab, children }) {
|
||||
const [activeTab, setActiveTab] = useState(() => initialTab ?? false);
|
||||
|
||||
useEffect(() => {
|
||||
if (initialTab !== undefined) setActiveTab(initialTab ?? false);
|
||||
}, [initialTab]);
|
||||
|
||||
const value = useMemo(() => ({ activeTab, setActiveTab }), [activeTab]);
|
||||
|
||||
return <TabContext.Provider value={value}>{children}</TabContext.Provider>;
|
||||
|
||||
@@ -31,10 +31,6 @@ export function ThemeProvider({ initialTheme, children }) {
|
||||
localStorage.setItem("theme-mode", rawTheme);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (initialTheme !== undefined) setTheme(initialTheme ?? getInitialTheme());
|
||||
}, [initialTheme]);
|
||||
|
||||
useEffect(() => {
|
||||
rawSetTheme(theme);
|
||||
}, [theme]);
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { useSyncExternalStore } from "react";
|
||||
|
||||
const MINUTE = 60_000;
|
||||
const stores = new Map();
|
||||
|
||||
function getStore(refreshInterval) {
|
||||
const existing = stores.get(refreshInterval);
|
||||
if (existing) return existing;
|
||||
|
||||
const listeners = new Set();
|
||||
let now = null; // null until mounted, so SSR and hydration render the same thing
|
||||
let timer = null;
|
||||
|
||||
const store = {
|
||||
getSnapshot: () => now,
|
||||
subscribe: (onStoreChange) => {
|
||||
listeners.add(onStoreChange);
|
||||
|
||||
if (!timer) {
|
||||
now = Date.now();
|
||||
timer = setInterval(() => {
|
||||
now = Date.now();
|
||||
listeners.forEach((listener) => listener());
|
||||
}, refreshInterval);
|
||||
}
|
||||
|
||||
return () => {
|
||||
listeners.delete(onStoreChange);
|
||||
if (!listeners.size) {
|
||||
clearInterval(timer);
|
||||
timer = null;
|
||||
}
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
stores.set(refreshInterval, store);
|
||||
return store;
|
||||
}
|
||||
|
||||
// Returns null on the server and during hydration, then the current time.
|
||||
export default function useCurrentTime(refreshInterval = MINUTE) {
|
||||
const { subscribe, getSnapshot } = getStore(refreshInterval);
|
||||
return useSyncExternalStore(subscribe, getSnapshot, () => null);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { act, render, screen } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import useCurrentTime from "./use-current-time";
|
||||
|
||||
function CurrentTime({ refreshInterval }) {
|
||||
return <span>{useCurrentTime(refreshInterval)}</span>;
|
||||
}
|
||||
|
||||
describe("utils/hooks/use-current-time", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(1_000);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("updates at the requested interval", () => {
|
||||
render(<CurrentTime refreshInterval={5_000} />);
|
||||
expect(screen.getByText("1000")).toBeInTheDocument();
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(5_000);
|
||||
});
|
||||
|
||||
expect(screen.getByText("6000")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -1,26 +1,17 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useSyncExternalStore } from "react";
|
||||
|
||||
const hasFocus = () => typeof document !== "undefined" && document.hasFocus();
|
||||
|
||||
const useWindowFocus = () => {
|
||||
const [focused, setFocused] = useState(hasFocus);
|
||||
const subscribe = (onFocusChange) => {
|
||||
window.addEventListener("focus", onFocusChange);
|
||||
window.addEventListener("blur", onFocusChange);
|
||||
|
||||
useEffect(() => {
|
||||
setFocused(hasFocus());
|
||||
|
||||
const onFocus = () => setFocused(true);
|
||||
const onBlur = () => setFocused(false);
|
||||
|
||||
window.addEventListener("focus", onFocus);
|
||||
window.addEventListener("blur", onBlur);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener("focus", onFocus);
|
||||
window.removeEventListener("blur", onBlur);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return focused;
|
||||
return () => {
|
||||
window.removeEventListener("focus", onFocusChange);
|
||||
window.removeEventListener("blur", onFocusChange);
|
||||
};
|
||||
};
|
||||
|
||||
const useWindowFocus = () => useSyncExternalStore(subscribe, hasFocus, () => false);
|
||||
|
||||
export default useWindowFocus;
|
||||
|
||||
@@ -12,15 +12,17 @@ function Fixture() {
|
||||
|
||||
describe("utils/hooks/window-focus", () => {
|
||||
it("tracks focus/blur events", async () => {
|
||||
vi.spyOn(document, "hasFocus").mockReturnValue(true);
|
||||
const hasFocus = vi.spyOn(document, "hasFocus").mockReturnValue(true);
|
||||
|
||||
render(<Fixture />);
|
||||
|
||||
expect(screen.getByTestId("focused")).toHaveTextContent("true");
|
||||
|
||||
hasFocus.mockReturnValue(false);
|
||||
window.dispatchEvent(new Event("blur"));
|
||||
await waitFor(() => expect(screen.getByTestId("focused")).toHaveTextContent("false"));
|
||||
|
||||
hasFocus.mockReturnValue(true);
|
||||
window.dispatchEvent(new Event("focus"));
|
||||
await waitFor(() => expect(screen.getByTestId("focused")).toHaveTextContent("true"));
|
||||
});
|
||||
|
||||
+6
-13
@@ -18,23 +18,16 @@ function combineMessageAndSplat() {
|
||||
}
|
||||
|
||||
function messageFormatter(logInfo) {
|
||||
if (logInfo.label) {
|
||||
if (logInfo.stack) {
|
||||
return `[${logInfo.timestamp}] ${logInfo.level}: <${logInfo.label}> ${logInfo.stack}`;
|
||||
}
|
||||
return `[${logInfo.timestamp}] ${logInfo.level}: <${logInfo.label}> ${logInfo.message}`;
|
||||
}
|
||||
|
||||
if (logInfo.stack) {
|
||||
return `[${logInfo.timestamp}] ${logInfo.level}: ${logInfo.stack}`;
|
||||
}
|
||||
return `[${logInfo.timestamp}] ${logInfo.level}: ${logInfo.message}`;
|
||||
const label = logInfo.label ? `<${logInfo.label}> ` : "";
|
||||
// e.g. fetch errors say nothing useful without the cause
|
||||
const cause = logInfo.cause ? `\ncaused by: ${logInfo.cause.stack ?? logInfo.cause}` : "";
|
||||
return `[${logInfo.timestamp}] ${logInfo.level}: ${label}${logInfo.stack || logInfo.message}${cause}`;
|
||||
}
|
||||
|
||||
function getConsoleLogger() {
|
||||
return new winston.transports.Console({
|
||||
format: winston.format.combine(
|
||||
winston.format.errors({ stack: true }),
|
||||
winston.format.errors({ stack: true, cause: true }),
|
||||
combineMessageAndSplat(),
|
||||
winston.format.timestamp(),
|
||||
winston.format.colorize(),
|
||||
@@ -51,7 +44,7 @@ function getFileLogger() {
|
||||
|
||||
return new winston.transports.File({
|
||||
format: winston.format.combine(
|
||||
winston.format.errors({ stack: true }),
|
||||
winston.format.errors({ stack: true, cause: true }),
|
||||
combineMessageAndSplat(),
|
||||
winston.format.timestamp(),
|
||||
winston.format.printf(messageFormatter),
|
||||
|
||||
@@ -170,6 +170,16 @@ describe("utils/logger", () => {
|
||||
});
|
||||
expect(plainMsg).toBe("[t] info: hello");
|
||||
|
||||
const causeMsg = formatter({
|
||||
timestamp: "t",
|
||||
level: "error",
|
||||
label: "x",
|
||||
stack: "STACK",
|
||||
message: "fetch failed",
|
||||
cause: { stack: "CAUSE STACK" },
|
||||
});
|
||||
expect(causeMsg).toBe("[t] error: <x> STACK\ncaused by: CAUSE STACK");
|
||||
|
||||
const out = splat.transform(
|
||||
{
|
||||
message: "Hello %s",
|
||||
|
||||
@@ -2,9 +2,10 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
|
||||
import { createHash, timingSafeEqual } from "node:crypto";
|
||||
import { join } from "path";
|
||||
|
||||
import yaml from "js-yaml";
|
||||
import * as yaml from "js-yaml";
|
||||
|
||||
import { CONF_DIR } from "utils/config/config";
|
||||
import { loadYaml } from "utils/config/yaml";
|
||||
|
||||
const PROTOCOL_VERSION = "2025-11-25";
|
||||
const SERVER_INFO = {
|
||||
@@ -118,7 +119,7 @@ function readConfig(file) {
|
||||
}
|
||||
|
||||
function parseYamlConfig(file) {
|
||||
const parsed = yaml.load(readConfig(file) || "");
|
||||
const parsed = loadYaml(readConfig(file) || "");
|
||||
return parsed ?? [];
|
||||
}
|
||||
|
||||
@@ -128,7 +129,7 @@ function validateYaml(file, content) {
|
||||
}
|
||||
|
||||
try {
|
||||
yaml.load(content || "");
|
||||
loadYaml(content || "");
|
||||
return { valid: true };
|
||||
} catch (error) {
|
||||
return {
|
||||
|
||||
@@ -2,13 +2,13 @@ import useSWR from "swr";
|
||||
|
||||
import { formatProxyUrl } from "./api-helpers";
|
||||
|
||||
export default function useWidgetAPI(widget, ...options) {
|
||||
const config = {};
|
||||
if (options && options[1]?.refreshInterval) {
|
||||
config.refreshInterval = options[1].refreshInterval;
|
||||
export default function useWidgetAPI(widget, endpoint, queryParams, swrConfig = {}) {
|
||||
const config = { ...swrConfig };
|
||||
if (queryParams?.refreshInterval) {
|
||||
config.refreshInterval = queryParams.refreshInterval;
|
||||
}
|
||||
let url = formatProxyUrl(widget, ...options);
|
||||
if (options[0] === "") {
|
||||
let url = formatProxyUrl(widget, endpoint, queryParams);
|
||||
if (endpoint === "") {
|
||||
url = null;
|
||||
}
|
||||
const { data, error, mutate } = useSWR(url, config);
|
||||
|
||||
@@ -28,6 +28,18 @@ describe("utils/proxy/use-widget-api", () => {
|
||||
expect(result.mutate).toBe("m");
|
||||
});
|
||||
|
||||
it("passes additional SWR configuration separately from the proxy query", () => {
|
||||
useSWR.mockReturnValue({ data: undefined, error: undefined, mutate: vi.fn() });
|
||||
|
||||
const widget = { service_group: "g", service_name: "s", index: 0 };
|
||||
const onSuccess = vi.fn();
|
||||
useWidgetAPI(widget, "status", { refreshInterval: 123 }, { onSuccess });
|
||||
|
||||
const [url, config] = useSWR.mock.calls[0];
|
||||
expect(url).not.toContain("onSuccess");
|
||||
expect(config).toEqual({ refreshInterval: 123, onSuccess });
|
||||
});
|
||||
|
||||
it("returns data.error as the top-level error", () => {
|
||||
const dataError = { message: "nope" };
|
||||
useSWR.mockReturnValue({ data: { error: dataError }, error: undefined, mutate: vi.fn() });
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
export default function withWidgetFields(service, defaultFields, maxFields = 4) {
|
||||
const configuredFields = service.widget.fields;
|
||||
const fields = (configuredFields?.length ? configuredFields : defaultFields).slice(0, maxFields);
|
||||
|
||||
return {
|
||||
...service,
|
||||
widget: {
|
||||
...service.widget,
|
||||
fields,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import withWidgetFields from "./widget-fields";
|
||||
|
||||
describe("utils/widget-fields", () => {
|
||||
it("applies defaults without modifying the service", () => {
|
||||
const service = { name: "Example", widget: { type: "example" } };
|
||||
|
||||
const normalizedService = withWidgetFields(service, ["one", "two"]);
|
||||
|
||||
expect(normalizedService).toEqual({
|
||||
name: "Example",
|
||||
widget: { type: "example", fields: ["one", "two"] },
|
||||
});
|
||||
expect(service).toEqual({ name: "Example", widget: { type: "example" } });
|
||||
});
|
||||
|
||||
it("treats an explicitly empty fields list as unset", () => {
|
||||
const service = { widget: { type: "example", fields: [] } };
|
||||
|
||||
const normalizedService = withWidgetFields(service, ["one", "two"]);
|
||||
|
||||
expect(normalizedService.widget.fields).toEqual(["one", "two"]);
|
||||
});
|
||||
|
||||
it("copies and limits configured fields", () => {
|
||||
const service = { widget: { type: "example", fields: ["one", "two", "three"] } };
|
||||
|
||||
const normalizedService = withWidgetFields(service, ["default"], 2);
|
||||
|
||||
expect(normalizedService.widget.fields).toEqual(["one", "two"]);
|
||||
expect(normalizedService.widget.fields).not.toBe(service.widget.fields);
|
||||
expect(service.widget.fields).toEqual(["one", "two", "three"]);
|
||||
});
|
||||
});
|
||||
@@ -3,19 +3,15 @@ import Container from "components/services/widget/container";
|
||||
import { useTranslation } from "next-i18next/pages";
|
||||
|
||||
import useWidgetAPI from "utils/proxy/use-widget-api";
|
||||
import withWidgetFields from "utils/widget-fields";
|
||||
|
||||
const MAX_FIELDS = 4;
|
||||
const DEFAULT_FIELDS = ["running", "stopped", "total", "image_updates"];
|
||||
|
||||
export default function Component({ service }) {
|
||||
export default function Component({ service: configuredService }) {
|
||||
const { t } = useTranslation();
|
||||
const service = withWidgetFields(configuredService, DEFAULT_FIELDS);
|
||||
const { widget } = service;
|
||||
|
||||
if (!widget.fields) {
|
||||
widget.fields = ["running", "stopped", "total", "image_updates"];
|
||||
} else if (widget.fields.length > MAX_FIELDS) {
|
||||
widget.fields = widget.fields.slice(0, MAX_FIELDS);
|
||||
}
|
||||
|
||||
const envNotSet = widget.env == null || widget.env === "";
|
||||
|
||||
const { data: containers, error: containersError } = useWidgetAPI(widget, envNotSet ? "" : "containers");
|
||||
|
||||
@@ -57,7 +57,7 @@ describe("widgets/arcane/component", () => {
|
||||
expect(screen.getByText("arcane.image_updates")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("truncates custom fields to the max allowed", () => {
|
||||
it("renders only the first four custom fields without mutating the input", () => {
|
||||
useWidgetAPI.mockImplementation(() => ({ data: undefined, error: undefined }));
|
||||
|
||||
const service = {
|
||||
@@ -65,7 +65,8 @@ describe("widgets/arcane/component", () => {
|
||||
};
|
||||
const { container } = renderWithProviders(<Component service={service} />, { settings: { hideErrors: false } });
|
||||
|
||||
// sliced to first four entries
|
||||
// The helper caps the copied fields used for rendering and leaves the configured service unchanged.
|
||||
expect(service.widget.fields).toEqual(["running", "stopped", "total", "images", "images_unused"]);
|
||||
expect(container.querySelectorAll(".service-block")).toHaveLength(4);
|
||||
expect(screen.getByText("docker.running")).toBeInTheDocument();
|
||||
expect(screen.getByText("dockhand.stopped")).toBeInTheDocument();
|
||||
|
||||
@@ -2,19 +2,14 @@ import Block from "components/services/widget/block";
|
||||
import Container from "components/services/widget/container";
|
||||
|
||||
import useWidgetAPI from "utils/proxy/use-widget-api";
|
||||
import withWidgetFields from "utils/widget-fields";
|
||||
|
||||
export default function Component({ service }) {
|
||||
const DEFAULT_FIELDS = ["apps", "synced", "outOfSync", "healthy"];
|
||||
|
||||
export default function Component({ service: configuredService }) {
|
||||
const service = withWidgetFields(configuredService, DEFAULT_FIELDS);
|
||||
const { widget } = service;
|
||||
|
||||
if (!widget.fields) {
|
||||
widget.fields = ["apps", "synced", "outOfSync", "healthy"];
|
||||
}
|
||||
|
||||
const MAX_ALLOWED_FIELDS = 4;
|
||||
if (widget.fields.length > MAX_ALLOWED_FIELDS) {
|
||||
widget.fields = widget.fields.slice(0, MAX_ALLOWED_FIELDS);
|
||||
}
|
||||
|
||||
const { data: appsData, error: appsError } = useWidgetAPI(widget, "applications");
|
||||
|
||||
const appCounts = widget.fields.map((status) => {
|
||||
|
||||
@@ -25,7 +25,7 @@ describe("widgets/argocd/component", () => {
|
||||
const service = { widget: { type: "argocd", fields: ["apps", "synced", "outOfSync", "healthy", "extra"] } };
|
||||
const { container } = renderWithProviders(<Component service={service} />, { settings: { hideErrors: false } });
|
||||
|
||||
expect(service.widget.fields).toEqual(["apps", "synced", "outOfSync", "healthy"]);
|
||||
expect(service.widget.fields).toEqual(["apps", "synced", "outOfSync", "healthy", "extra"]);
|
||||
expect(container.querySelectorAll(".service-block")).toHaveLength(4);
|
||||
expect(screen.getByText("argocd.apps")).toBeInTheDocument();
|
||||
expect(screen.getByText("argocd.synced")).toBeInTheDocument();
|
||||
|
||||
@@ -2,10 +2,14 @@ import Block from "components/services/widget/block";
|
||||
import Container from "components/services/widget/container";
|
||||
import { useTranslation } from "next-i18next/pages";
|
||||
|
||||
import useCurrentTime from "utils/hooks/use-current-time";
|
||||
import useWidgetAPI from "utils/proxy/use-widget-api";
|
||||
|
||||
const DAY = 24 * 60 * 60 * 1000;
|
||||
|
||||
export default function Component({ service }) {
|
||||
const { t } = useTranslation();
|
||||
const currentTime = useCurrentTime();
|
||||
|
||||
const { widget } = service;
|
||||
const isV2 = widget.version === 2;
|
||||
@@ -45,7 +49,7 @@ export default function Component({ service }) {
|
||||
switch (widget.version) {
|
||||
// v1 is default
|
||||
default:
|
||||
const yesterday = new Date(Date.now()).setHours(-24);
|
||||
const yesterday = currentTime - DAY;
|
||||
loginsLast24H = loginsData.reduce(
|
||||
(total, current) => (current.x_cord >= yesterday ? total + current.y_cord : total),
|
||||
0,
|
||||
|
||||
@@ -71,7 +71,8 @@ describe("widgets/authentik/component", () => {
|
||||
|
||||
it("computes v1 login/failed counts for entries within the last 24h window", () => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date("2026-01-02T00:00:00Z"));
|
||||
// Use midday so a mistaken previous-midnight cutoff would include the 25-hour-old entries.
|
||||
vi.setSystemTime(new Date("2026-01-02T12:00:00Z"));
|
||||
|
||||
const now = Date.now();
|
||||
const oneHourAgo = now - 60 * 60 * 1000;
|
||||
|
||||
@@ -3,13 +3,14 @@ import Container from "components/services/widget/container";
|
||||
import { useTranslation } from "next-i18next/pages";
|
||||
|
||||
import useWidgetAPI from "utils/proxy/use-widget-api";
|
||||
import withWidgetFields from "utils/widget-fields";
|
||||
|
||||
const BACKREST_DEFAULT_FIELDS = ["num_success_latest", "num_failure_latest", "num_failure_30", "bytes_added_30"];
|
||||
const MAX_ALLOWED_FIELDS = 4;
|
||||
|
||||
export default function Component({ service }) {
|
||||
export default function Component({ service: configuredService }) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const service = withWidgetFields(configuredService, BACKREST_DEFAULT_FIELDS);
|
||||
const { widget } = service;
|
||||
|
||||
const { data, error } = useWidgetAPI(widget, "summary");
|
||||
@@ -18,12 +19,6 @@ export default function Component({ service }) {
|
||||
return <Container service={service} error={error} />;
|
||||
}
|
||||
|
||||
if (!widget.fields?.length) {
|
||||
widget.fields = BACKREST_DEFAULT_FIELDS;
|
||||
} else if (widget.fields.length > MAX_ALLOWED_FIELDS) {
|
||||
widget.fields = widget.fields.slice(0, MAX_ALLOWED_FIELDS);
|
||||
}
|
||||
|
||||
if (!data) {
|
||||
return (
|
||||
<Container service={service}>
|
||||
|
||||
@@ -24,12 +24,7 @@ describe("widgets/backrest/component", () => {
|
||||
const service = { widget: { type: "backrest" } };
|
||||
const { container } = renderWithProviders(<Component service={service} />, { settings: { hideErrors: false } });
|
||||
|
||||
expect(service.widget.fields).toEqual([
|
||||
"num_success_latest",
|
||||
"num_failure_latest",
|
||||
"num_failure_30",
|
||||
"bytes_added_30",
|
||||
]);
|
||||
expect(service.widget.fields).toBeUndefined();
|
||||
expect(container.querySelectorAll(".service-block")).toHaveLength(4);
|
||||
|
||||
expect(screen.getByText("backrest.num_success_latest")).toBeInTheDocument();
|
||||
@@ -48,7 +43,7 @@ describe("widgets/backrest/component", () => {
|
||||
|
||||
renderWithProviders(<Component service={service} />, { settings: { hideErrors: false } });
|
||||
|
||||
expect(service.widget.fields).toEqual(["a", "b", "c", "d"]);
|
||||
expect(service.widget.fields).toEqual(["a", "b", "c", "d", "e"]);
|
||||
});
|
||||
|
||||
it("renders values and respects field filtering", () => {
|
||||
|
||||
@@ -3,23 +3,21 @@ import Container from "components/services/widget/container";
|
||||
import { useTranslation } from "next-i18next/pages";
|
||||
|
||||
import useWidgetAPI from "utils/proxy/use-widget-api";
|
||||
import withWidgetFields from "utils/widget-fields";
|
||||
|
||||
export default function Component({ service }) {
|
||||
const SUMMARY_FIELDS = ["systems", "up"];
|
||||
const SYSTEM_FIELDS = ["name", "status", "cpu", "memory"];
|
||||
|
||||
export default function Component({ service: configuredService }) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const defaultFields = configuredService.widget.systemId ? SYSTEM_FIELDS : SUMMARY_FIELDS;
|
||||
const service = withWidgetFields(configuredService, defaultFields);
|
||||
const { widget } = service;
|
||||
const { systemId } = widget;
|
||||
|
||||
const { data: systems, error: systemsError } = useWidgetAPI(widget, "systems");
|
||||
|
||||
const MAX_ALLOWED_FIELDS = 4;
|
||||
if (!widget.fields?.length > 0) {
|
||||
widget.fields = systemId ? ["name", "status", "cpu", "memory"] : ["systems", "up"];
|
||||
}
|
||||
if (widget.fields?.length > MAX_ALLOWED_FIELDS) {
|
||||
widget.fields = widget.fields.slice(0, MAX_ALLOWED_FIELDS);
|
||||
}
|
||||
|
||||
let system = null;
|
||||
let finalError = systemsError;
|
||||
|
||||
|
||||
@@ -23,7 +23,7 @@ describe("widgets/beszel/component", () => {
|
||||
const service = { widget: { type: "beszel" } };
|
||||
const { container } = renderWithProviders(<Component service={service} />, { settings: { hideErrors: false } });
|
||||
|
||||
expect(service.widget.fields).toEqual(["systems", "up"]);
|
||||
expect(service.widget.fields).toBeUndefined();
|
||||
expect(container.querySelectorAll(".service-block")).toHaveLength(2);
|
||||
expect(screen.getByText("beszel.systems")).toBeInTheDocument();
|
||||
expect(screen.getByText("beszel.up")).toBeInTheDocument();
|
||||
@@ -66,7 +66,7 @@ describe("widgets/beszel/component", () => {
|
||||
const service = { widget: { type: "beszel", systemId: "sys1" } };
|
||||
const { container } = renderWithProviders(<Component service={service} />, { settings: { hideErrors: false } });
|
||||
|
||||
expect(service.widget.fields).toEqual(["name", "status", "cpu", "memory"]);
|
||||
expect(service.widget.fields).toBeUndefined();
|
||||
expect(container.querySelectorAll(".service-block")).toHaveLength(4);
|
||||
|
||||
expectBlockValue(container, "beszel.name", "MySystem");
|
||||
|
||||
@@ -38,16 +38,16 @@ const colorVariants = {
|
||||
export default function Component({ service }) {
|
||||
const { widget } = service;
|
||||
const { i18n } = useTranslation();
|
||||
const [showDate, setShowDate] = useState(null);
|
||||
const [events, setEvents] = useState({});
|
||||
const nowDate = DateTime.now().setLocale(i18n.language);
|
||||
const currentDate = widget?.timezone ? nowDate.setZone(widget?.timezone).startOf("day") : nowDate;
|
||||
const [showDate, setShowDate] = useState(null);
|
||||
const { settings } = useContext(SettingsContext);
|
||||
|
||||
useEffect(() => {
|
||||
if (!showDate) {
|
||||
setShowDate(currentDate);
|
||||
}
|
||||
// seeded after mount, not during render: "today" is client-only and would break hydration
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
if (!showDate) setShowDate(currentDate);
|
||||
}, [showDate, currentDate]);
|
||||
|
||||
// params for API fetch
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import ICAL from "ical.js";
|
||||
import { DateTime } from "luxon";
|
||||
import { useTranslation } from "next-i18next/pages";
|
||||
import { useEffect } from "react";
|
||||
import { useEffect, useMemo } from "react";
|
||||
|
||||
import Error from "../../../components/services/widget/error";
|
||||
import useWidgetAPI from "../../../utils/proxy/use-widget-api";
|
||||
@@ -17,65 +17,67 @@ function simpleHash(str) {
|
||||
return Math.abs(hash).toString(36);
|
||||
}
|
||||
|
||||
function buildEvent(event, type) {
|
||||
return {
|
||||
id: event.getFirstPropertyValue("uid"),
|
||||
type,
|
||||
title: event.getFirstPropertyValue("summary"),
|
||||
rrule: event.getFirstPropertyValue("rrule"),
|
||||
dtstart:
|
||||
event.getFirstPropertyValue("dtstart") ||
|
||||
event.getFirstPropertyValue("due") ||
|
||||
event.getFirstPropertyValue("completed") ||
|
||||
ICAL.Time.now(), // handles events without a date
|
||||
dtend:
|
||||
event.getFirstPropertyValue("dtend") ||
|
||||
event.getFirstPropertyValue("due") ||
|
||||
event.getFirstPropertyValue("completed") ||
|
||||
ICAL.Time.now(), // handles events without a date
|
||||
location: event.getFirstPropertyValue("location"),
|
||||
status: event.getFirstPropertyValue("status"),
|
||||
url: event.getFirstPropertyValue("url"),
|
||||
};
|
||||
}
|
||||
|
||||
export default function Integration({ config, params, setEvents, hideErrors, timezone }) {
|
||||
const { t } = useTranslation();
|
||||
const { data: icalData, error: icalError } = useWidgetAPI(config, config.name, {
|
||||
refreshInterval: 300000, // 5 minutes
|
||||
});
|
||||
|
||||
const { events, dataError } = useMemo(() => {
|
||||
if (icalError || !icalData || icalData.error) {
|
||||
return { events: [], dataError: undefined };
|
||||
}
|
||||
|
||||
if (!icalData.data) {
|
||||
return {
|
||||
events: [],
|
||||
dataError: { message: `'${config.name}': ${t("calendar.errorWhenLoadingData")}` },
|
||||
};
|
||||
}
|
||||
|
||||
const jCal = ICAL.parse(icalData.data);
|
||||
const vCalendar = new ICAL.Component(jCal);
|
||||
const parsedEvents = [
|
||||
...vCalendar.getAllSubcomponents("vevent").map((event) => buildEvent(event, "vevent")),
|
||||
...vCalendar.getAllSubcomponents("vtodo").map((todo) => buildEvent(todo, "vtodo")),
|
||||
];
|
||||
|
||||
return {
|
||||
events: parsedEvents,
|
||||
dataError:
|
||||
parsedEvents.length === 0 ? { message: `'${config.name}': ${t("calendar.noEventsFound")}` } : undefined,
|
||||
};
|
||||
}, [icalData, icalError, config.name, t]);
|
||||
|
||||
useEffect(() => {
|
||||
const { showName = false } = config?.params || {};
|
||||
let events = [];
|
||||
|
||||
if (!icalError && icalData && !icalData.error) {
|
||||
if (!icalData.data) {
|
||||
icalData.error = { message: `'${config.name}': ${t("calendar.errorWhenLoadingData")}` };
|
||||
return;
|
||||
}
|
||||
|
||||
const jCal = ICAL.parse(icalData.data);
|
||||
const vCalendar = new ICAL.Component(jCal);
|
||||
|
||||
const buildEvent = (event, type) => {
|
||||
return {
|
||||
id: event.getFirstPropertyValue("uid"),
|
||||
type,
|
||||
title: event.getFirstPropertyValue("summary"),
|
||||
rrule: event.getFirstPropertyValue("rrule"),
|
||||
dtstart:
|
||||
event.getFirstPropertyValue("dtstart") ||
|
||||
event.getFirstPropertyValue("due") ||
|
||||
event.getFirstPropertyValue("completed") ||
|
||||
ICAL.Time.now(), // handles events without a date
|
||||
dtend:
|
||||
event.getFirstPropertyValue("dtend") ||
|
||||
event.getFirstPropertyValue("due") ||
|
||||
event.getFirstPropertyValue("completed") ||
|
||||
ICAL.Time.now(), // handles events without a date
|
||||
location: event.getFirstPropertyValue("location"),
|
||||
status: event.getFirstPropertyValue("status"),
|
||||
url: event.getFirstPropertyValue("url"),
|
||||
};
|
||||
};
|
||||
|
||||
const getEvents = () => {
|
||||
const vEvents = vCalendar.getAllSubcomponents("vevent").map((event) => buildEvent(event, "vevent"));
|
||||
|
||||
const vTodos = vCalendar.getAllSubcomponents("vtodo").map((todo) => buildEvent(todo, "vtodo"));
|
||||
|
||||
return [...vEvents, ...vTodos];
|
||||
};
|
||||
|
||||
events = getEvents();
|
||||
if (events.length === 0) {
|
||||
icalData.error = { message: `'${config.name}': ${t("calendar.noEventsFound")}` };
|
||||
}
|
||||
}
|
||||
|
||||
const startDate = DateTime.fromISO(params.start);
|
||||
const endDate = DateTime.fromISO(params.end);
|
||||
|
||||
if (icalError || events.length === 0 || !startDate.isValid || !endDate.isValid) {
|
||||
if (events.length === 0 || !startDate.isValid || !endDate.isValid) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -113,7 +115,7 @@ export default function Integration({ config, params, setEvents, hideErrors, tim
|
||||
return occurrences;
|
||||
};
|
||||
|
||||
const eventsToAdd = [];
|
||||
const eventsToAdd = {};
|
||||
events.forEach((event) => {
|
||||
const occurrences = getOcurrencesFromRange(event);
|
||||
|
||||
@@ -154,8 +156,8 @@ export default function Integration({ config, params, setEvents, hideErrors, tim
|
||||
});
|
||||
|
||||
setEvents((prevEvents) => ({ ...prevEvents, ...eventsToAdd }));
|
||||
}, [icalData, icalError, config, params, setEvents, timezone, t]);
|
||||
}, [events, config, params, setEvents, timezone]);
|
||||
|
||||
const error = icalError ?? icalData?.error;
|
||||
const error = icalError ?? icalData?.error ?? dataError;
|
||||
return error && !hideErrors && <Error error={{ message: `${config.type}: ${error.message ?? error}` }} />;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { render, waitFor } from "@testing-library/react";
|
||||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
const { useWidgetAPI } = vi.hoisted(() => ({
|
||||
@@ -12,6 +12,45 @@ vi.mock("utils/proxy/use-widget-api", () => ({ default: useWidgetAPI }));
|
||||
import Integration from "./ical";
|
||||
|
||||
describe("widgets/calendar/integrations/ical", () => {
|
||||
it("reports a missing calendar payload without mutating the response", () => {
|
||||
const data = {};
|
||||
useWidgetAPI.mockReturnValue({ data, error: undefined });
|
||||
|
||||
render(
|
||||
<Integration
|
||||
config={{ name: "Work", type: "ical" }}
|
||||
params={{ start: "2099-01-01", end: "2099-01-02" }}
|
||||
setEvents={vi.fn()}
|
||||
hideErrors={false}
|
||||
timezone="utc"
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.getByText(/'Work': calendar\.errorWhenLoadingData/)).toBeInTheDocument();
|
||||
expect(data).toEqual({});
|
||||
});
|
||||
|
||||
it("reports a calendar with no events without mutating the response", () => {
|
||||
const data = {
|
||||
data: ["BEGIN:VCALENDAR", "VERSION:2.0", "PRODID:-//Test//EN", "END:VCALENDAR", ""].join("\n"),
|
||||
};
|
||||
const originalData = structuredClone(data);
|
||||
useWidgetAPI.mockReturnValue({ data, error: undefined });
|
||||
|
||||
render(
|
||||
<Integration
|
||||
config={{ name: "Empty", type: "ical" }}
|
||||
params={{ start: "2099-01-01", end: "2099-01-02" }}
|
||||
setEvents={vi.fn()}
|
||||
hideErrors={false}
|
||||
timezone="utc"
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.getByText(/'Empty': calendar\.noEventsFound/)).toBeInTheDocument();
|
||||
expect(data).toEqual(originalData);
|
||||
});
|
||||
|
||||
it("adds parsed events within the date range", async () => {
|
||||
useWidgetAPI.mockReturnValue({
|
||||
data: {
|
||||
|
||||
@@ -4,14 +4,19 @@ import { useTranslation } from "next-i18next/pages";
|
||||
|
||||
import useWidgetAPI from "utils/proxy/use-widget-api";
|
||||
|
||||
const ALERTS_LIMIT = 500;
|
||||
|
||||
export default function Component({ service }) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const { widget } = service;
|
||||
|
||||
const { data: alerts, error: alertsError } = useWidgetAPI(widget, !!widget.limit24h ? "alerts24h" : "alerts");
|
||||
const { data: alerts, error: alertsError } = useWidgetAPI(widget, "alerts");
|
||||
const { data: bans, error: bansError } = useWidgetAPI(widget, "bans");
|
||||
|
||||
const alertsCount = alerts?.length ?? 0;
|
||||
const alertsValue = t("common.number", { value: alertsCount });
|
||||
|
||||
if (alertsError || bansError) {
|
||||
return <Container service={service} error={alertsError ?? bansError} />;
|
||||
}
|
||||
@@ -27,7 +32,7 @@ export default function Component({ service }) {
|
||||
|
||||
return (
|
||||
<Container service={service}>
|
||||
<Block label="crowdsec.alerts" value={t("common.number", { value: alerts?.length ?? 0 })} />
|
||||
<Block label="crowdsec.alerts" value={alertsCount >= ALERTS_LIMIT ? `${alertsValue}+` : alertsValue} />
|
||||
<Block label="crowdsec.bans" value={t("common.number", { value: bans?.length ?? 0 })} />
|
||||
</Container>
|
||||
);
|
||||
|
||||
@@ -17,15 +17,25 @@ describe("widgets/crowdsec/component", () => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("selects alerts24h endpoint when limit24h is enabled", () => {
|
||||
it("requests the alerts and bans endpoints", () => {
|
||||
useWidgetAPI.mockImplementation(() => ({ data: undefined, error: undefined }));
|
||||
|
||||
renderWithProviders(<Component service={{ widget: { type: "crowdsec" } }} />, {
|
||||
settings: { hideErrors: false },
|
||||
});
|
||||
|
||||
expect(useWidgetAPI).toHaveBeenNthCalledWith(1, expect.any(Object), "alerts");
|
||||
expect(useWidgetAPI).toHaveBeenNthCalledWith(2, expect.any(Object), "bans");
|
||||
});
|
||||
|
||||
it("ignores the deprecated limit24h option", () => {
|
||||
useWidgetAPI.mockImplementation(() => ({ data: undefined, error: undefined }));
|
||||
|
||||
renderWithProviders(<Component service={{ widget: { type: "crowdsec", limit24h: true } }} />, {
|
||||
settings: { hideErrors: false },
|
||||
});
|
||||
|
||||
expect(useWidgetAPI).toHaveBeenNthCalledWith(1, expect.any(Object), "alerts24h");
|
||||
expect(useWidgetAPI).toHaveBeenNthCalledWith(2, expect.any(Object), "bans");
|
||||
expect(useWidgetAPI).toHaveBeenNthCalledWith(1, expect.any(Object), "alerts");
|
||||
});
|
||||
|
||||
it("renders placeholders when both alerts and bans are missing", () => {
|
||||
@@ -52,4 +62,28 @@ describe("widgets/crowdsec/component", () => {
|
||||
expectBlockValue(container, "crowdsec.alerts", 0);
|
||||
expectBlockValue(container, "crowdsec.bans", 0);
|
||||
});
|
||||
|
||||
it("marks the alert count as truncated at the API limit", () => {
|
||||
useWidgetAPI
|
||||
.mockReturnValueOnce({ data: new Array(500).fill({}), error: undefined })
|
||||
.mockReturnValueOnce({ data: [], error: undefined });
|
||||
|
||||
renderWithProviders(<Component service={{ widget: { type: "crowdsec" } }} />, {
|
||||
settings: { hideErrors: false },
|
||||
});
|
||||
|
||||
expect(screen.getByText("500+")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("does not mark the alert count below the API limit", () => {
|
||||
useWidgetAPI
|
||||
.mockReturnValueOnce({ data: new Array(499).fill({}), error: undefined })
|
||||
.mockReturnValueOnce({ data: [], error: undefined });
|
||||
|
||||
const { container } = renderWithProviders(<Component service={{ widget: { type: "crowdsec" } }} />, {
|
||||
settings: { hideErrors: false },
|
||||
});
|
||||
|
||||
expectBlockValue(container, "crowdsec.alerts", 499);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -7,13 +7,10 @@ const widget = {
|
||||
|
||||
mappings: {
|
||||
alerts: {
|
||||
endpoint: "alerts",
|
||||
},
|
||||
alerts24h: {
|
||||
endpoint: "alerts?limit=0&since=24h",
|
||||
endpoint: "alerts?limit=500&since=24h&with_decisions=false&include_capi=false",
|
||||
},
|
||||
bans: {
|
||||
endpoint: "alerts?decision_type=ban&origin=crowdsec&has_active_decision=1",
|
||||
endpoint: "alerts?decision_type=ban&include_capi=false&has_active_decision=1&with_decisions=false",
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -3,19 +3,15 @@ import Container from "components/services/widget/container";
|
||||
import { useTranslation } from "next-i18next/pages";
|
||||
|
||||
import useWidgetAPI from "utils/proxy/use-widget-api";
|
||||
import withWidgetFields from "utils/widget-fields";
|
||||
|
||||
const MAX_FIELDS = 4;
|
||||
const DEFAULT_FIELDS = ["running", "total", "cpu", "memory"];
|
||||
|
||||
export default function Component({ service }) {
|
||||
export default function Component({ service: configuredService }) {
|
||||
const { t } = useTranslation();
|
||||
const service = withWidgetFields(configuredService, DEFAULT_FIELDS);
|
||||
const { widget } = service;
|
||||
|
||||
if (!widget.fields) {
|
||||
widget.fields = ["running", "total", "cpu", "memory"];
|
||||
} else if (widget.fields.length > MAX_FIELDS) {
|
||||
widget.fields = widget.fields.slice(0, MAX_FIELDS);
|
||||
}
|
||||
|
||||
const { data: stats, error: statsError } = useWidgetAPI(widget, "dashboard/stats");
|
||||
|
||||
if (statsError) {
|
||||
|
||||
@@ -22,7 +22,11 @@ describe("widgets/dockhand/component", () => {
|
||||
const service = { widget: { type: "dockhand" } };
|
||||
const { container } = renderWithProviders(<Component service={service} />, { settings: { hideErrors: false } });
|
||||
|
||||
expect(service.widget.fields).toEqual(["running", "total", "cpu", "memory"]);
|
||||
expect(service.widget.fields).toBeUndefined();
|
||||
expect(useWidgetAPI).toHaveBeenCalledWith(
|
||||
{ type: "dockhand", fields: ["running", "total", "cpu", "memory"] },
|
||||
"dashboard/stats",
|
||||
);
|
||||
expect(container.querySelectorAll(".service-block")).toHaveLength(4);
|
||||
expect(screen.getByText("dockhand.running")).toBeInTheDocument();
|
||||
expect(screen.getByText("dockhand.total")).toBeInTheDocument();
|
||||
|
||||
@@ -3,19 +3,15 @@ import Container from "components/services/widget/container";
|
||||
import { useTranslation } from "next-i18next/pages";
|
||||
|
||||
import useWidgetAPI from "utils/proxy/use-widget-api";
|
||||
import withWidgetFields from "utils/widget-fields";
|
||||
|
||||
const DEFAULT_FIELDS = ["jobs", "errors", "lastBackup", "nextRun"];
|
||||
|
||||
export default function Component({ service }) {
|
||||
export default function Component({ service: configuredService }) {
|
||||
const { t } = useTranslation();
|
||||
const service = withWidgetFields(configuredService, DEFAULT_FIELDS);
|
||||
const { widget } = service;
|
||||
|
||||
if (!widget.fields?.length) {
|
||||
widget.fields = DEFAULT_FIELDS;
|
||||
} else if (widget.fields?.length > 4) {
|
||||
widget.fields = widget.fields.slice(0, 4);
|
||||
}
|
||||
|
||||
const { data, error } = useWidgetAPI(widget);
|
||||
|
||||
if (error) {
|
||||
|
||||
@@ -3,10 +3,14 @@ import Container from "components/services/widget/container";
|
||||
import { useTranslation } from "next-i18next/pages";
|
||||
|
||||
import useWidgetAPI from "utils/proxy/use-widget-api";
|
||||
import withWidgetFields from "utils/widget-fields";
|
||||
|
||||
export default function Component({ service }) {
|
||||
const DEFAULT_FIELDS = ["online", "offline", "offline_alt", "total"];
|
||||
|
||||
export default function Component({ service: configuredService }) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const service = withWidgetFields(configuredService, DEFAULT_FIELDS);
|
||||
const { widget } = service;
|
||||
const { data: resultData, error: resultError } = useWidgetAPI(widget);
|
||||
|
||||
@@ -14,12 +18,6 @@ export default function Component({ service }) {
|
||||
return <Container service={service} error={resultError} />;
|
||||
}
|
||||
|
||||
if (!widget.fields || widget.fields.length === 0) {
|
||||
widget.fields = ["online", "offline", "offline_alt", "total"];
|
||||
} else if (widget.fields.length > 4) {
|
||||
widget.fields = widget.fields.slice(0, 4);
|
||||
}
|
||||
|
||||
if (!resultData) {
|
||||
return (
|
||||
<Container service={service}>
|
||||
|
||||
@@ -22,7 +22,7 @@ describe("widgets/esphome/component", () => {
|
||||
const service = { widget: { type: "esphome" } };
|
||||
const { container } = renderWithProviders(<Component service={service} />, { settings: { hideErrors: false } });
|
||||
|
||||
expect(service.widget.fields).toEqual(["online", "offline", "offline_alt", "total"]);
|
||||
expect(service.widget.fields).toBeUndefined();
|
||||
expect(container.querySelectorAll(".service-block")).toHaveLength(4);
|
||||
expect(screen.getByText("esphome.online")).toBeInTheDocument();
|
||||
expect(screen.getByText("esphome.offline")).toBeInTheDocument();
|
||||
|
||||
@@ -3,11 +3,13 @@ import Container from "components/services/widget/container";
|
||||
import { useTranslation } from "next-i18next/pages";
|
||||
|
||||
import useWidgetAPI from "utils/proxy/use-widget-api";
|
||||
import withWidgetFields from "utils/widget-fields";
|
||||
|
||||
export const fritzboxDefaultFields = ["connectionStatus", "uptime", "maxDown", "maxUp"];
|
||||
|
||||
export default function Component({ service }) {
|
||||
export default function Component({ service: configuredService }) {
|
||||
const { t } = useTranslation();
|
||||
const service = withWidgetFields(configuredService, fritzboxDefaultFields);
|
||||
const { widget } = service;
|
||||
const { data: fritzboxData, error: fritzboxError } = useWidgetAPI(widget, "status");
|
||||
|
||||
@@ -15,16 +17,6 @@ export default function Component({ service }) {
|
||||
return <Container service={service} error={fritzboxError} />;
|
||||
}
|
||||
|
||||
// Default fields
|
||||
if (!widget.fields?.length > 0) {
|
||||
widget.fields = fritzboxDefaultFields;
|
||||
}
|
||||
const MAX_ALLOWED_FIELDS = 4;
|
||||
// Limits max number of displayed fields
|
||||
if (widget.fields?.length > MAX_ALLOWED_FIELDS) {
|
||||
widget.fields = widget.fields.slice(0, MAX_ALLOWED_FIELDS);
|
||||
}
|
||||
|
||||
if (!fritzboxData) {
|
||||
return (
|
||||
<Container service={service}>
|
||||
|
||||
@@ -9,7 +9,7 @@ import { expectBlockValue } from "test-utils/widget-assertions";
|
||||
const { useWidgetAPI } = vi.hoisted(() => ({ useWidgetAPI: vi.fn() }));
|
||||
vi.mock("utils/proxy/use-widget-api", () => ({ default: useWidgetAPI }));
|
||||
|
||||
import Component, { fritzboxDefaultFields } from "./component";
|
||||
import Component from "./component";
|
||||
|
||||
describe("widgets/fritzbox/component", () => {
|
||||
beforeEach(() => {
|
||||
@@ -22,7 +22,7 @@ describe("widgets/fritzbox/component", () => {
|
||||
const service = { widget: { type: "fritzbox", url: "http://x" } };
|
||||
const { container } = renderWithProviders(<Component service={service} />, { settings: { hideErrors: false } });
|
||||
|
||||
expect(service.widget.fields).toEqual(fritzboxDefaultFields);
|
||||
expect(service.widget.fields).toBeUndefined();
|
||||
expect(container.querySelectorAll(".service-block")).toHaveLength(4);
|
||||
expect(screen.getByText("fritzbox.connectionStatus")).toBeInTheDocument();
|
||||
expect(screen.getByText("fritzbox.uptime")).toBeInTheDocument();
|
||||
@@ -43,7 +43,14 @@ describe("widgets/fritzbox/component", () => {
|
||||
|
||||
const { container } = renderWithProviders(<Component service={service} />, { settings: { hideErrors: false } });
|
||||
|
||||
expect(service.widget.fields).toEqual(["down", "up", "received", "sent"]);
|
||||
expect(service.widget.fields).toEqual([
|
||||
"down",
|
||||
"up",
|
||||
"received",
|
||||
"sent",
|
||||
"externalIPAddress",
|
||||
"externalIPv6Prefix",
|
||||
]);
|
||||
expect(container.querySelectorAll(".service-block")).toHaveLength(4);
|
||||
expect(screen.getByText("fritzbox.down")).toBeInTheDocument();
|
||||
expect(screen.getByText("fritzbox.up")).toBeInTheDocument();
|
||||
|
||||
@@ -3,8 +3,12 @@ import Container from "components/services/widget/container";
|
||||
import { useTranslation } from "next-i18next/pages";
|
||||
|
||||
import useWidgetAPI from "utils/proxy/use-widget-api";
|
||||
import withWidgetFields from "utils/widget-fields";
|
||||
|
||||
export default function Component({ service }) {
|
||||
const DEFAULT_FIELDS = ["map", "currentPlayers", "ping"];
|
||||
|
||||
export default function Component({ service: configuredService }) {
|
||||
const service = withWidgetFields(configuredService, DEFAULT_FIELDS);
|
||||
const { widget } = service;
|
||||
const { data: serverData, error: serverError } = useWidgetAPI(widget, "status");
|
||||
const { t } = useTranslation();
|
||||
@@ -13,16 +17,6 @@ export default function Component({ service }) {
|
||||
return <Container service={service} error={serverError} />;
|
||||
}
|
||||
|
||||
// Default fields
|
||||
if (widget.fields == null || widget.fields.length === 0) {
|
||||
widget.fields = ["map", "currentPlayers", "ping"];
|
||||
}
|
||||
const MAX_ALLOWED_FIELDS = 4;
|
||||
// Limits max number of displayed fields
|
||||
if (widget.fields != null && widget.fields.length > MAX_ALLOWED_FIELDS) {
|
||||
widget.fields = widget.fields.slice(0, MAX_ALLOWED_FIELDS);
|
||||
}
|
||||
|
||||
if (!serverData) {
|
||||
return (
|
||||
<Container service={service}>
|
||||
|
||||
@@ -22,7 +22,7 @@ describe("widgets/gamedig/component", () => {
|
||||
const service = { widget: { type: "gamedig", url: "http://x" } };
|
||||
const { container } = renderWithProviders(<Component service={service} />, { settings: { hideErrors: false } });
|
||||
|
||||
expect(service.widget.fields).toEqual(["map", "currentPlayers", "ping"]);
|
||||
expect(service.widget.fields).toBeUndefined();
|
||||
expect(container.querySelectorAll(".service-block")).toHaveLength(3);
|
||||
expect(screen.getByText("gamedig.map")).toBeInTheDocument();
|
||||
expect(screen.getByText("gamedig.currentPlayers")).toBeInTheDocument();
|
||||
@@ -54,7 +54,7 @@ describe("widgets/gamedig/component", () => {
|
||||
|
||||
const { container } = renderWithProviders(<Component service={service} />, { settings: { hideErrors: false } });
|
||||
|
||||
expect(service.widget.fields).toEqual(["status", "name", "map", "currentPlayers"]);
|
||||
expect(service.widget.fields).toEqual(["status", "name", "map", "currentPlayers", "ping"]);
|
||||
expect(container.querySelectorAll(".service-block")).toHaveLength(4);
|
||||
|
||||
expectBlockValue(container, "gamedig.status", "gamedig.online");
|
||||
|
||||
@@ -3,7 +3,7 @@ export default function Tooltip({ active, payload, formatter }) {
|
||||
return (
|
||||
<div className="bg-theme-800/80 rounded-md text-theme-200 px-2 py-0">
|
||||
{payload.map((pld, id) => (
|
||||
<div key={Math.random()} className="first-of-type:pt-0 pt-0.5">
|
||||
<div key={`${pld.dataKey ?? pld.name ?? "series"}-${id}`} className="first-of-type:pt-0 pt-0.5">
|
||||
<div>
|
||||
{formatter(pld.value)} {payload[id].name}
|
||||
</div>
|
||||
|
||||
@@ -41,7 +41,7 @@ export default function Component({ service }) {
|
||||
);
|
||||
}
|
||||
|
||||
data.splice(chart ? 5 : 1);
|
||||
const visibleData = data.slice(0, chart ? 5 : 1);
|
||||
let headerYPosition = "top-4";
|
||||
let listYPosition = "bottom-4";
|
||||
if (chart) {
|
||||
@@ -61,7 +61,7 @@ export default function Component({ service }) {
|
||||
|
||||
<Block position={`${listYPosition} right-3 left-3`}>
|
||||
<div className="pointer-events-none text-theme-900 dark:text-theme-200">
|
||||
{data.map((item) => (
|
||||
{visibleData.map((item) => (
|
||||
<div key={item[idKey]} className="text-[0.75rem] h-[0.8rem]">
|
||||
<div className="flex items-center">
|
||||
<div className="w-3 h-3 mr-1.5 opacity-50">{statusMap[item[statusKey]]}</div>
|
||||
|
||||
@@ -103,5 +103,6 @@ describe("widgets/glances/metrics/containers", () => {
|
||||
expect(screen.getByText("item-0")).toBeInTheDocument();
|
||||
expect(screen.getByText("item-4")).toBeInTheDocument();
|
||||
expect(screen.queryByText("item-5")).not.toBeInTheDocument();
|
||||
expect(data).toHaveLength(6);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { useTranslation } from "next-i18next/pages";
|
||||
import dynamic from "next/dynamic";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useCallback } from "react";
|
||||
|
||||
import Block from "../components/block";
|
||||
import Container from "../components/container";
|
||||
|
||||
import useDataPoints from "./use-data-points";
|
||||
|
||||
import { parseVersionForUrl } from "utils/proxy/api-helpers";
|
||||
import useWidgetAPI from "utils/proxy/use-widget-api";
|
||||
|
||||
@@ -19,26 +21,26 @@ export default function Component({ service }) {
|
||||
const { chart, refreshInterval = defaultInterval, pointsLimit = defaultPointsLimit, version = 3 } = widget;
|
||||
const apiVersion = parseVersionForUrl(version, 3);
|
||||
|
||||
const [dataPoints, setDataPoints] = useState(new Array(pointsLimit).fill({ value: 0 }, 0, pointsLimit));
|
||||
const [dataPoints, addDataPoint] = useDataPoints(pointsLimit, { value: 0 });
|
||||
|
||||
const { data, error } = useWidgetAPI(service.widget, `${apiVersion}/cpu`, {
|
||||
refreshInterval: Math.max(defaultInterval, refreshInterval),
|
||||
});
|
||||
const handleData = useCallback(
|
||||
(newData) => {
|
||||
if (newData) addDataPoint({ value: newData.total });
|
||||
},
|
||||
[addDataPoint],
|
||||
);
|
||||
|
||||
const { data, error } = useWidgetAPI(
|
||||
service.widget,
|
||||
`${apiVersion}/cpu`,
|
||||
{
|
||||
refreshInterval: Math.max(defaultInterval, refreshInterval),
|
||||
},
|
||||
{ onSuccess: handleData },
|
||||
);
|
||||
|
||||
const { data: quicklookData, error: quicklookError } = useWidgetAPI(service.widget, `${apiVersion}/quicklook`);
|
||||
|
||||
useEffect(() => {
|
||||
if (data) {
|
||||
setDataPoints((prevDataPoints) => {
|
||||
const newDataPoints = [...prevDataPoints, { value: data.total }];
|
||||
if (newDataPoints.length > pointsLimit) {
|
||||
newDataPoints.shift();
|
||||
}
|
||||
return newDataPoints;
|
||||
});
|
||||
}
|
||||
}, [data, pointsLimit]);
|
||||
|
||||
if (error) {
|
||||
return <Container error={error} widget={widget} />;
|
||||
}
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { useTranslation } from "next-i18next/pages";
|
||||
import dynamic from "next/dynamic";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useCallback } from "react";
|
||||
|
||||
import Block from "../components/block";
|
||||
import Container from "../components/container";
|
||||
|
||||
import useDataPoints from "./use-data-points";
|
||||
|
||||
import { parseVersionForUrl } from "utils/proxy/api-helpers";
|
||||
import useWidgetAPI from "utils/proxy/use-widget-api";
|
||||
|
||||
@@ -20,39 +22,37 @@ export default function Component({ service }) {
|
||||
const apiVersion = parseVersionForUrl(version, 3);
|
||||
const [, diskName] = widget.metric.split(":");
|
||||
|
||||
const [dataPoints, setDataPoints] = useState(
|
||||
new Array(pointsLimit).fill({ read_bytes: 0, write_bytes: 0, time_since_update: 0 }, 0, pointsLimit),
|
||||
);
|
||||
const [ratePoints, setRatePoints] = useState(new Array(pointsLimit).fill({ a: 0, b: 0 }, 0, pointsLimit));
|
||||
|
||||
const { data, error } = useWidgetAPI(service.widget, `${apiVersion}/diskio`, {
|
||||
refreshInterval: Math.max(defaultInterval, refreshInterval),
|
||||
const [dataPoints, addDataPoint] = useDataPoints(pointsLimit, {
|
||||
read_bytes: 0,
|
||||
write_bytes: 0,
|
||||
time_since_update: 0,
|
||||
});
|
||||
|
||||
const handleData = useCallback(
|
||||
(newData) => {
|
||||
if (!newData?.error) {
|
||||
const diskData = newData.find((item) => item.disk_name === diskName);
|
||||
if (diskData) addDataPoint(diskData);
|
||||
}
|
||||
},
|
||||
[addDataPoint, diskName],
|
||||
);
|
||||
|
||||
const { data, error } = useWidgetAPI(
|
||||
service.widget,
|
||||
`${apiVersion}/diskio`,
|
||||
{
|
||||
refreshInterval: Math.max(defaultInterval, refreshInterval),
|
||||
},
|
||||
{ onSuccess: handleData },
|
||||
);
|
||||
|
||||
const calculateRates = (d) =>
|
||||
d.map((item) => ({
|
||||
a: item.read_bytes / item.time_since_update,
|
||||
b: item.write_bytes / item.time_since_update,
|
||||
}));
|
||||
|
||||
useEffect(() => {
|
||||
if (data && !data.error) {
|
||||
const diskData = data.find((item) => item.disk_name === diskName);
|
||||
|
||||
setDataPoints((prevDataPoints) => {
|
||||
const newDataPoints = [...prevDataPoints, diskData];
|
||||
if (newDataPoints.length > pointsLimit) {
|
||||
newDataPoints.shift();
|
||||
}
|
||||
return newDataPoints;
|
||||
});
|
||||
}
|
||||
}, [data, diskName, pointsLimit]);
|
||||
|
||||
useEffect(() => {
|
||||
setRatePoints(calculateRates(dataPoints));
|
||||
}, [dataPoints]);
|
||||
|
||||
if (error || (data && data.error)) {
|
||||
const finalError = error || data.error;
|
||||
return <Container error={finalError} widget={widget} />;
|
||||
@@ -83,7 +83,7 @@ export default function Component({ service }) {
|
||||
<Container chart={chart}>
|
||||
{chart && (
|
||||
<ChartDual
|
||||
dataPoints={ratePoints}
|
||||
dataPoints={diskRates}
|
||||
label={[t("glances.read"), t("glances.write")]}
|
||||
max={diskData.critical}
|
||||
formatter={(value) =>
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { useTranslation } from "next-i18next/pages";
|
||||
import dynamic from "next/dynamic";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useCallback } from "react";
|
||||
|
||||
import Block from "../components/block";
|
||||
import Container from "../components/container";
|
||||
|
||||
import useDataPoints from "./use-data-points";
|
||||
|
||||
import { parseVersionForUrl } from "utils/proxy/api-helpers";
|
||||
import useWidgetAPI from "utils/proxy/use-widget-api";
|
||||
|
||||
@@ -20,27 +22,26 @@ export default function Component({ service }) {
|
||||
const apiVersion = parseVersionForUrl(version, 3);
|
||||
const [, gpuName] = widget.metric.split(":");
|
||||
|
||||
const [dataPoints, setDataPoints] = useState(new Array(pointsLimit).fill({ a: 0, b: 0 }, 0, pointsLimit));
|
||||
const [dataPoints, addDataPoint] = useDataPoints(pointsLimit, { a: 0, b: 0 });
|
||||
|
||||
const { data, error } = useWidgetAPI(widget, `${apiVersion}/gpu`, {
|
||||
refreshInterval: Math.max(defaultInterval, refreshInterval),
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (data && !data.error) {
|
||||
const gpuData = data.find((item) => item[item.key] == gpuName);
|
||||
|
||||
if (gpuData) {
|
||||
setDataPoints((prevDataPoints) => {
|
||||
const newDataPoints = [...prevDataPoints, { a: gpuData.mem, b: gpuData.proc }];
|
||||
if (newDataPoints.length > pointsLimit) {
|
||||
newDataPoints.shift();
|
||||
}
|
||||
return newDataPoints;
|
||||
});
|
||||
const handleData = useCallback(
|
||||
(newData) => {
|
||||
if (!newData?.error) {
|
||||
const gpuData = newData.find((item) => item[item.key] == gpuName);
|
||||
if (gpuData) addDataPoint({ a: gpuData.mem, b: gpuData.proc });
|
||||
}
|
||||
}
|
||||
}, [data, gpuName, pointsLimit]);
|
||||
},
|
||||
[addDataPoint, gpuName],
|
||||
);
|
||||
|
||||
const { data, error } = useWidgetAPI(
|
||||
widget,
|
||||
`${apiVersion}/gpu`,
|
||||
{
|
||||
refreshInterval: Math.max(defaultInterval, refreshInterval),
|
||||
},
|
||||
{ onSuccess: handleData },
|
||||
);
|
||||
|
||||
if (error || (data && data.error)) {
|
||||
const finalError = error || data.error;
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { useTranslation } from "next-i18next/pages";
|
||||
import dynamic from "next/dynamic";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useCallback } from "react";
|
||||
|
||||
import Block from "../components/block";
|
||||
import Container from "../components/container";
|
||||
|
||||
import useDataPoints from "./use-data-points";
|
||||
|
||||
import { parseVersionForUrl } from "utils/proxy/api-helpers";
|
||||
import useWidgetAPI from "utils/proxy/use-widget-api";
|
||||
|
||||
@@ -20,23 +22,23 @@ export default function Component({ service }) {
|
||||
const { refreshInterval = defaultInterval(chart), pointsLimit = defaultPointsLimit, version = 3 } = widget;
|
||||
const apiVersion = parseVersionForUrl(version, 3);
|
||||
|
||||
const [dataPoints, setDataPoints] = useState(new Array(pointsLimit).fill({ value: 0 }, 0, pointsLimit));
|
||||
const [dataPoints, addDataPoint] = useDataPoints(pointsLimit, { a: 0, b: 0 });
|
||||
|
||||
const { data, error } = useWidgetAPI(service.widget, `${apiVersion}/mem`, {
|
||||
refreshInterval: Math.max(defaultInterval(chart), refreshInterval),
|
||||
});
|
||||
const handleData = useCallback(
|
||||
(newData) => {
|
||||
if (newData) addDataPoint({ a: newData.used, b: newData.available });
|
||||
},
|
||||
[addDataPoint],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (data) {
|
||||
setDataPoints((prevDataPoints) => {
|
||||
const newDataPoints = [...prevDataPoints, { a: data.used, b: data.available }];
|
||||
if (newDataPoints.length > pointsLimit) {
|
||||
newDataPoints.shift();
|
||||
}
|
||||
return newDataPoints;
|
||||
});
|
||||
}
|
||||
}, [data, pointsLimit]);
|
||||
const { data, error } = useWidgetAPI(
|
||||
service.widget,
|
||||
`${apiVersion}/mem`,
|
||||
{
|
||||
refreshInterval: Math.max(defaultInterval(chart), refreshInterval),
|
||||
},
|
||||
{ onSuccess: handleData },
|
||||
);
|
||||
|
||||
if (error) {
|
||||
return <Container error={error} widget={widget} />;
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { useTranslation } from "next-i18next/pages";
|
||||
import dynamic from "next/dynamic";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useCallback } from "react";
|
||||
|
||||
import Block from "../components/block";
|
||||
import Container from "../components/container";
|
||||
|
||||
import useDataPoints from "./use-data-points";
|
||||
|
||||
import { parseVersionForUrl } from "utils/proxy/api-helpers";
|
||||
import useWidgetAPI from "utils/proxy/use-widget-api";
|
||||
|
||||
@@ -25,33 +27,32 @@ export default function Component({ service }) {
|
||||
|
||||
const [, interfaceName] = metric.split(":");
|
||||
|
||||
const [dataPoints, setDataPoints] = useState(new Array(pointsLimit).fill({ value: 0 }, 0, pointsLimit));
|
||||
const [dataPoints, addDataPoint] = useDataPoints(pointsLimit, { a: 0, b: 0 });
|
||||
|
||||
const { data, error } = useWidgetAPI(widget, `${apiVersion}/network`, {
|
||||
refreshInterval: Math.max(defaultInterval(chart), refreshInterval),
|
||||
});
|
||||
const handleData = useCallback(
|
||||
(newData) => {
|
||||
if (!newData?.error) {
|
||||
const interfaceData = newData.find((item) => item[item.key] === interfaceName);
|
||||
|
||||
useEffect(() => {
|
||||
if (data && !data.error) {
|
||||
const interfaceData = data.find((item) => item[item.key] === interfaceName);
|
||||
|
||||
if (interfaceData) {
|
||||
setDataPoints((prevDataPoints) => {
|
||||
const newDataPoints = [
|
||||
...prevDataPoints,
|
||||
{
|
||||
a: (interfaceData[rxKey] * 8) / interfaceData.time_since_update,
|
||||
b: (interfaceData[txKey] * 8) / interfaceData.time_since_update,
|
||||
},
|
||||
];
|
||||
if (newDataPoints.length > pointsLimit) {
|
||||
newDataPoints.shift();
|
||||
}
|
||||
return newDataPoints;
|
||||
});
|
||||
if (interfaceData) {
|
||||
addDataPoint({
|
||||
a: (interfaceData[rxKey] * 8) / interfaceData.time_since_update,
|
||||
b: (interfaceData[txKey] * 8) / interfaceData.time_since_update,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}, [data, interfaceName, pointsLimit, rxKey, txKey]);
|
||||
},
|
||||
[addDataPoint, interfaceName, rxKey, txKey],
|
||||
);
|
||||
|
||||
const { data, error } = useWidgetAPI(
|
||||
widget,
|
||||
`${apiVersion}/network`,
|
||||
{
|
||||
refreshInterval: Math.max(defaultInterval(chart), refreshInterval),
|
||||
},
|
||||
{ onSuccess: handleData },
|
||||
);
|
||||
|
||||
if (error || (data && data.error)) {
|
||||
const finalError = error || data.error;
|
||||
|
||||
@@ -43,7 +43,7 @@ export default function Component({ service }) {
|
||||
);
|
||||
}
|
||||
|
||||
data.splice(chart ? 5 : 1);
|
||||
const visibleData = data.slice(0, chart ? 5 : 1);
|
||||
let headerYPosition = "top-4";
|
||||
let listYPosition = "bottom-4";
|
||||
if (chart) {
|
||||
@@ -63,7 +63,7 @@ export default function Component({ service }) {
|
||||
|
||||
<Block position={`${listYPosition} right-3 left-3`}>
|
||||
<div className="pointer-events-none text-theme-900 dark:text-theme-200">
|
||||
{data.map((item) => (
|
||||
{visibleData.map((item) => (
|
||||
<div key={item.pid} className="text-[0.75rem] h-[0.8rem]">
|
||||
<div className="flex items-center">
|
||||
<div className="w-3 h-3 mr-1.5 opacity-50">{statusMap[item.status]}</div>
|
||||
|
||||
@@ -19,4 +19,20 @@ describe("widgets/glances/metrics/process", () => {
|
||||
});
|
||||
expect(screen.getByText("-")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("limits displayed processes without modifying the response", () => {
|
||||
const data = [
|
||||
{ pid: 1, status: "R", name: "first", cpu_percent: 1, memory_info: [100] },
|
||||
{ pid: 2, status: "S", name: "second", cpu_percent: 2, memory_info: [200] },
|
||||
];
|
||||
useWidgetAPI.mockReturnValue({ data, error: undefined });
|
||||
|
||||
renderWithProviders(<Component service={{ widget: { chart: false, version: 3 } }} />, {
|
||||
settings: { hideErrors: false },
|
||||
});
|
||||
|
||||
expect(screen.getByText("first")).toBeInTheDocument();
|
||||
expect(screen.queryByText("second")).not.toBeInTheDocument();
|
||||
expect(data).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user