diff --git a/.dockerignore b/.dockerignore index 521c55109..c0f2129a3 100644 --- a/.dockerignore +++ b/.dockerignore @@ -17,7 +17,8 @@ coverage dev .build e2e -apps/docs +apps/docs/* +!apps/docs/package.json apps/nextjs/.next .env .env.* diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 0d8b33a33..d4b730726 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -33,6 +33,7 @@ body: options: # The below comment is used to insert a new version with on-release.yml #NEXT_VERSION# + - 1.74.0 - 1.73.0 - 1.72.0 - 1.71.0 diff --git a/.github/workflows/automatic-approval.yml b/.github/workflows/automatic-approval.yml deleted file mode 100644 index 9e246f838..000000000 --- a/.github/workflows/automatic-approval.yml +++ /dev/null @@ -1,35 +0,0 @@ -name: "[Dependency Updates] Auto Approve" -on: - pull_request: - types: [opened, synchronize] - -permissions: {} - -jobs: - approve-automatic-prs: - runs-on: ubuntu-latest - timeout-minutes: 2 - # 158783068: homarr-renovate[bot] - # 190541745: homarr-crowdin[bot] - # 210161987: homarr-update-contributors[bot] - # 175486441: homarr-releases[bot] - # Extracted from https://api.github.com/users/ - if: github.actor_id == 158783068 || github.actor_id == 190541745 || github.actor_id == 210161987 || github.actor_id == 175486441 - steps: - - name: Checkout code - uses: actions/checkout@v7 - - name: Obtain token - id: obtainToken - uses: actions/create-github-app-token@v3 - with: - private-key: ${{ secrets.RENOVATE_APPROVE_PRIVATE_KEY }} - client-id: ${{ secrets.RENOVATE_APPROVE_APP_ID }} - permission-pull-requests: write # required to approve pull request - - - name: Install GitHub CLI - run: sudo apt-get install -y gh - - name: Approve automatic PRs - env: - GITHUB_TOKEN: ${{ steps.obtainToken.outputs.token }} - run: | - gh pr review ${{github.event.pull_request.number}} --approve --body "Automatically approved by GitHub Action" diff --git a/.github/workflows/bot-auto-merge-reconcile.yml b/.github/workflows/bot-auto-merge-reconcile.yml new file mode 100644 index 000000000..d82f759f5 --- /dev/null +++ b/.github/workflows/bot-auto-merge-reconcile.yml @@ -0,0 +1,43 @@ +name: "[Bots] Reconcile Auto-merge" + +on: + schedule: + - cron: "*/30 * * * *" + workflow_dispatch: + +permissions: {} + +jobs: + reconcile: + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - name: Checkout code + uses: actions/checkout@v7 + + - name: Obtain token + id: obtainToken + uses: actions/create-github-app-token@v3 + with: + private-key: ${{ secrets.RENOVATE_APPROVE_PRIVATE_KEY }} + client-id: ${{ secrets.RENOVATE_APPROVE_APP_ID }} + permission-pull-requests: write # required to enable auto-merge + + - name: Install GitHub CLI + run: sudo apt-get install -y gh + + - name: Re-enable auto-merge for prepared bot PRs + env: + GITHUB_TOKEN: ${{ steps.obtainToken.outputs.token }} + run: | + # 158783068: homarr-renovate[bot] + # 190541745: homarr-crowdin[bot] + # 210161987: homarr-update-contributors[bot] + # 175441: homarr-releases[bot] + gh pr list --repo "${{ github.repository }}" --base dev --state open --limit 100 \ + --json number,author,reviewDecision,mergeStateStatus,autoMergeRequest \ + --jq '.[] | select(.author.login as $login | ["app/homarr-renovate", "app/homarr-crowdin", "app/homarr-update-contributors", "app/homarr-releases"] | index($login)) | select(.reviewDecision == "APPROVED") | select(.mergeStateStatus == "CLEAN") | select(.autoMergeRequest == null) | .number' \ + | while read -r pr; do + echo "Re-enabling auto-merge on PR #$pr" + gh pr merge "$pr" --auto --squash + done diff --git a/.github/workflows/bot-pr-automerge.yml b/.github/workflows/bot-pr-automerge.yml new file mode 100644 index 000000000..35c5461fa --- /dev/null +++ b/.github/workflows/bot-pr-automerge.yml @@ -0,0 +1,47 @@ +name: "[Bots] Approve and Auto-merge" + +on: + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + +permissions: {} + +jobs: + approve-and-automerge: + runs-on: ubuntu-latest + timeout-minutes: 5 + # 158783068: homarr-renovate[bot] + # 190541745: homarr-crowdin[bot] + # 210161987: homarr-update-contributors[bot] + # 175441: homarr-releases[bot] + # Extracted from https://api.github.com/users/ + if: | + (github.actor_id == 158783068 || github.actor_id == 190541745 || github.actor_id == 210161987 || github.actor_id == 175441) && + github.event.pull_request.head.repo.full_name == github.repository && + github.event.pull_request.base.ref == 'dev' + steps: + - name: Checkout code + uses: actions/checkout@v7 + + - name: Obtain token + id: obtainToken + uses: actions/create-github-app-token@v3 + with: + private-key: ${{ secrets.RENOVATE_APPROVE_PRIVATE_KEY }} + client-id: ${{ secrets.RENOVATE_APPROVE_APP_ID }} + permission-pull-requests: write # required to approve a pull request and enable auto-merge + + - name: Install GitHub CLI + run: sudo apt-get install -y gh + + - name: Approve and enable auto-merge + env: + GITHUB_TOKEN: ${{ steps.obtainToken.outputs.token }} + run: | + PR_NUMBER="${{ github.event.pull_request.number }}" + if [ "$(gh pr view "$PR_NUMBER" --json reviewDecision --jq .reviewDecision)" != "APPROVED" ]; then + gh pr review "$PR_NUMBER" --approve --body "Automatically approved by Homarr bot policy" + fi + if [ "$(gh pr view "$PR_NUMBER" --json autoMergeRequest --jq '.autoMergeRequest != null')" != "true" ]; then + gh pr merge "$PR_NUMBER" --auto --squash + fi diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index dcbb352c3..dbb3d2a2d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -82,7 +82,7 @@ jobs: run: cp .env.example .env - name: Lint, typecheck, and build affected workspaces - run: pnpm turbo run lint typecheck build --affected --continue=dependencies-successful + run: pnpm turbo run lint typecheck build --affected --continue=dependencies-successful --concurrency=2 - name: Validate workspace configuration run: pnpm lint:ws diff --git a/.gitignore b/.gitignore index c22262f6d..71a27829a 100644 --- a/.gitignore +++ b/.gitignore @@ -78,3 +78,4 @@ skills-lock.json apps/docs/.docusaurus apps/docs/build .pnpm-store +benchmark-results diff --git a/CODEOWNERS b/CODEOWNERS index 7082b9bac..5565a85fc 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -206,6 +206,14 @@ packages/integrations/src/unraid @manuel-rw apps/docs/docs/integrations/uptime-kuma @ajnart packages/integrations/src/uptime-kuma @ajnart +# What's Up Docker (WUD) - introduced in https://github.com/homarr-labs/homarr/pull/6523 by @tiimonn +apps/docs/docs/integrations/whats-up-docker @tiimonn +apps/docs/docs/widgets/whats-up-docker @tiimonn +packages/api/src/router/widgets/wud.ts @tiimonn +packages/integrations/src/wud @tiimonn +packages/request-handler/src/wud.ts @tiimonn +packages/widgets/src/wud @tiimonn + # Traefik - by @Nerdy-Technician apps/docs/docs/integrations/traefik @Nerdy-Technician apps/docs/docs/widgets/traefik @Nerdy-Technician diff --git a/Dockerfile b/Dockerfile index 8f4c5e49a..f07fcae3b 100644 --- a/Dockerfile +++ b/Dockerfile @@ -3,12 +3,18 @@ FROM node:24.18.0-alpine AS base FROM base AS builder +ARG TARGETPLATFORM WORKDIR /app -RUN apk add --no-cache libc6-compat curl bash && apk update +# Native dependencies normally use prebuilds, but the build must remain +# reproducible when a prebuild download times out and compilation is required. +RUN apk add --no-cache libc6-compat curl bash python3 make g++ RUN corepack enable pnpm -COPY pnpm-lock.yaml pnpm-workspace.yaml package.json ./ +COPY .npmrc pnpm-lock.yaml pnpm-workspace.yaml package.json ./ COPY patches ./patches +COPY --parents ./apps/*/package.json ./packages/*/package.json ./tooling/*/package.json ./ +# @homarr/definitions generates documentation types during install. +COPY --parents ./packages/definitions/src ./ # Workaround for pnpm/pnpm#5268: pnpm fetch crashes when patchedDependencies # are configured with nodeLinker: hoisted. The applyPatchToDir function tries # to chdir into node_modules/ which doesn't exist during fetch (only the @@ -19,14 +25,16 @@ COPY patches ./patches RUN --mount=type=cache,id=pnpm-store,target=/pnpm/store \ pnpm config set store-dir /pnpm/store && \ sed -i 's/nodeLinker: hoisted/nodeLinker: isolated/' pnpm-workspace.yaml && \ - pnpm fetch && \ + pnpm fetch --ignore-scripts && \ sed -i 's/nodeLinker: isolated/nodeLinker: hoisted/' pnpm-workspace.yaml -COPY . . -# Follow the pnpm fetch pattern from https://pnpm.io/cli/fetch -# --frozen-lockfile is omitted as recommended by the pnpm fetch docs +# Install only from the fetched, committed lockfile so local and Docker builds +# resolve the same dependency graph. Serial lifecycle builds avoid esbuild's +# atomic binary replacement racing across the hoisted workspace (pnpm/pnpm#8200). RUN --mount=type=cache,id=pnpm-store,target=/pnpm/store \ - pnpm install --recursive + npm_config_nodedir=/usr/local pnpm install --recursive --offline --frozen-lockfile --child-concurrency=1 + +COPY . . ARG SKIP_ENV_VALIDATION='true' ARG CI='true' @@ -37,7 +45,9 @@ RUN --mount=type=secret,id=TURBO_API,env=TURBO_API \ --mount=type=secret,id=TURBO_TEAM,env=TURBO_TEAM \ --mount=type=secret,id=TURBO_TOKEN,env=TURBO_TOKEN \ --mount=type=secret,id=TURBO_REMOTE_CACHE_SIGNATURE_KEY,env=TURBO_REMOTE_CACHE_SIGNATURE_KEY \ - TURBO_PLATFORM="${TARGETPLATFORM:-linux/amd64}" pnpm build + --mount=type=cache,id=homarr-next-build-${TARGETPLATFORM},target=/app/apps/nextjs/.next/cache,sharing=locked \ + TURBO_PLATFORM="${TARGETPLATFORM:-linux/amd64}" \ + pnpm turbo build --filter=@homarr/nextjs... --filter=@homarr/cli FROM base AS runner WORKDIR /app @@ -85,5 +95,6 @@ ENV AUTH_PROVIDERS='credentials' ENV REDIS_IS_EXTERNAL='false' ENV NODE_ENV='production' +EXPOSE 7575 ENTRYPOINT [ "/app/entrypoint.sh" ] CMD ["sh", "run.sh"] diff --git a/apps/docs/README.md b/apps/docs/README.md index b66530488..118c04aef 100644 --- a/apps/docs/README.md +++ b/apps/docs/README.md @@ -55,8 +55,8 @@ pnpm typecheck docs/ ├── getting-started/ # Installation guides, glossary, prerequisites ├── management/ # Boards, apps, users, integrations, settings, tasks, API -├── integrations/ # 55 integration guides (one folder each) -├── widgets/ # 42 widget guides (one folder each) +├── integrations/ # 56 integration guides (one folder each) +├── widgets/ # 43 widget guides (one folder each) ├── advanced/ # SSO, env vars, proxy, styling, CLI, development └── community/ # FAQ, donate, license, translations, get-in-touch ``` diff --git a/apps/docs/docs/advanced/development/getting-started.mdx b/apps/docs/docs/advanced/development/getting-started.mdx index e8f68ea6d..1bad7be05 100644 --- a/apps/docs/docs/advanced/development/getting-started.mdx +++ b/apps/docs/docs/advanced/development/getting-started.mdx @@ -14,8 +14,8 @@ This guide will help you set up your development environment to start contributi ### Prerequisites -- **Node.js (lts)**: You can download it from the [official website](https://nodejs.org/). -- **pnpm (latest)**: You can install it by running `npm install -g pnpm`. +- **Node.js 24.18 or newer**: You can download it from the [official website](https://nodejs.org/). +- **Corepack**: Run `corepack enable` so the repository selects its pinned pnpm version. - **Git**: You can download it from the [official website](https://git-scm.com/). - **Docker or Docker Desktop**: Required for the Redis service and the developer Docker CLI. - **Go 1.25+**: Required only for the developer Docker CLI. You can download it from the [official website](https://go.dev/). @@ -49,7 +49,10 @@ This guide will help you set up your development environment to start contributi #### During development -- `pnpm dev`: Start the development server. +- `pnpm dev`: Start the Next.js development server. +- `pnpm dev:benchmark`: Run the local authenticated-board benchmark. Set `DEV_BENCHMARK_BOARD_URL` and + `DEV_BENCHMARK_STORAGE_STATE`; readiness-only measurements require the explicit `--smoke` flag and are not + suitable for performance claims. - `pnpm dev:cli -- dev`: Browse and run local images and remote pull-request images. - `pnpm dev:cli -- build `: Build the current checkout as `homarr:`. - `pnpm dev:cli -- build --pr `: Build a pull request locally from a temporary checkout. @@ -74,4 +77,5 @@ This guide will help you set up your development environment to start contributi - `pnpm build`: Build the project for production. - `pnpm dev:cli -- build `: Build a `homarr:` image and record its checkout for later rebuilds. +- `docker build -t homarr .`: Build a docker image for the project. - `docker run -p 7575:7575 -e SECRET_ENCRYPTION_KEY='your_64_character_hex_string' homarr:`: Run the created docker image. diff --git a/apps/docs/docs/advanced/environment-variables/index.mdx b/apps/docs/docs/advanced/environment-variables/index.mdx index ad249e734..f2ae41d4b 100644 --- a/apps/docs/docs/advanced/environment-variables/index.mdx +++ b/apps/docs/docs/advanced/environment-variables/index.mdx @@ -25,15 +25,14 @@ This is especially useful for [docker secrets](https://docs.docker.com/engine/sw Using the `PUID` and `PGID` will require you to set the correct permissions on the mounted volumes and if used the docker socket. See more in the [Running as a different user](/docs/advanced/running-as-different-user) documentation. ::: -| Environment Variable | Description | Possible values | Default | -| ------------------------ | ----------- | --------------- | ------- | -| ``PUID`` | User ID to run the container as | Any valid user ID | ``0`` | -| ``PGID`` | Group ID to run the container as | Any valid group ID | ``0`` | -| ``LOG_LEVEL`` | Log level to use | ``debug`` / ``info`` / ``warn`` / ``error`` | ``info`` | -| ``NO_EXTERNAL_CONNECTION`` | Disables some requests that need internet connection | `true` or `false` | `false` | -| ``ENABLE_DNS_CACHING`` | Enables dns caching. Enabled by default, but if you experience issues with IPv6 or static IPs, see [#4006](https://github.com/homarr-labs/homarr/issues/4006) or disable this flag | `true` or `false` | `true` | - - +| Environment Variable | Description | Possible values | Default | +| ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------- | ------- | +| `PUID` | User ID to run the container as | Any valid user ID | `0` | +| `PGID` | Group ID to run the container as | Any valid group ID | `0` | +| `LOG_LEVEL` | Log level to use | `debug` / `info` / `warn` / `error` | `info` | +| `NO_EXTERNAL_CONNECTION` | Disables Homarr's internet-backed requests, including update checks, weather, and RSS feeds | `true` or `false` | `false` | +| `ENABLE_DNS_CACHING` | Enables dns caching. Enabled by default, but if you experience issues with IPv6 or static IPs, see [#4006](https://github.com/homarr-labs/homarr/issues/4006) or disable this flag | `true` or `false` | `true` | +| `HOMARR_DISABLE_IPV6` | Disables the IPv6 listener of the internal nginx proxy, even when the host supports IPv6. IPv6 is normally disabled automatically when the host has no IPv6 configured. See [#4596](https://github.com/homarr-labs/homarr/issues/4596) | `true` or `false` | `false` | ## Authentication @@ -43,9 +42,9 @@ See [Single Sign-On](/docs/advanced/single-sign-on) for more informations. The `SECRET_ENCRYPTION_KEY` is required. If none is specified before starting the container, a random key will be shown in the error message and the container will exit. -| Environment Variable | Description | Possible values | Default | -| ------------------------ | ----------- | --------------- | ------- | -| ``SECRET_ENCRYPTION_KEY`` | Secret used to encrypt secrets in database. | 64 character hex string | - | +| Environment Variable | Description | Possible values | Default | +| ----------------------- | ------------------------------------------- | ----------------------- | ------- | +| `SECRET_ENCRYPTION_KEY` | Secret used to encrypt secrets in database. | 64 character hex string | - | :::info A random secret can be generated by using the following command: `openssl rand -hex 32` @@ -53,27 +52,27 @@ A random secret can be generated by using the following command: `openssl rand - ## Docker -| Environment Variable | Description | Possible values | Default | -| ------------------------ | ----------- | --------------- | ------- | -| ``DOCKER_HOSTNAMES`` | Comma-separated list of hostnames to connect to | For example `localhost,docker.example.com` | - | -| ``DOCKER_PORTS`` | Comma-separated list of ports to connect to | For example `2375,2376` | - | -| ``DOCKER_SOCKET_PATHS`` | Comma-separated list of mounted Docker-compatible socket paths. See the [Docker and Podman integration guide](/docs/integrations/docker) | For example `/var/run/docker.sock,/var/run/podman.sock` | - | +| Environment Variable | Description | Possible values | Default | +| --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------- | ------- | +| `DOCKER_HOSTNAMES` | Comma-separated list of hostnames to connect to | For example `localhost,docker.example.com` | - | +| `DOCKER_PORTS` | Comma-separated list of ports to connect to | For example `2375,2376` | - | +| `DOCKER_SOCKET_PATHS` | Comma-separated list of mounted Docker-compatible socket paths. See the [Docker and Podman integration guide](/docs/integrations/docker) | For example `/var/run/docker.sock,/var/run/podman.sock` | - | ## Database -| Environment Variable | Description | Possible values | Default | -| ------------------------ | ----------- | --------------- | ------- | -| ``DB_DRIVER`` | Database driver to use. Currently `better-sqlite3` is used for sqlite, `mysql2` for mysql and `node-postgres` for postgresql | ``better-sqlite3`` / ``mysql2`` / ``node-postgres`` | ``better-sqlite3`` | -| ``DB_DIALECT`` | Database dialect to use. | ``sqlite`` / ``mysql`` / ``postgresql`` | ``sqlite`` | -| ``DB_URL`` | Database URL to connect to. | Any valid database URL | ``/appdata/db/db.sqlite`` | -| ``DB_HOST`` | Database host to connect to. | Any valid database host | - | -| ``DB_PORT`` | Database port to connect to. | Any valid database port | - | -| ``DB_NAME`` | Database name to connect to. | Any valid database name | - | -| ``DB_USER`` | Database user to connect with. | Any valid database user | - | -| ``DB_PASSWORD`` | Database password to connect with. | Any valid database password | - | + +| Environment Variable | Description | Possible values | Default | +| -------------------- | ---------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------- | ----------------------- | +| `DB_DRIVER` | Database driver to use. Currently `better-sqlite3` is used for sqlite, `mysql2` for mysql and `node-postgres` for postgresql | `better-sqlite3` / `mysql2` / `node-postgres` | `better-sqlite3` | +| `DB_DIALECT` | Database dialect to use. | `sqlite` / `mysql` / `postgresql` | `sqlite` | +| `DB_URL` | Database URL to connect to. | Any valid database URL | `/appdata/db/db.sqlite` | +| `DB_HOST` | Database host to connect to. | Any valid database host | - | +| `DB_PORT` | Database port to connect to. | Any valid database port | - | +| `DB_NAME` | Database name to connect to. | Any valid database name | - | +| `DB_USER` | Database user to connect with. | Any valid database user | - | +| `DB_PASSWORD` | Database password to connect with. | Any valid database password | - | You can either use the url or host, port, name and credentials combined. The URL will be prioritized over the other values. - ## Redis By default Redis is running within the installation. (for example in Docker). @@ -83,25 +82,23 @@ However for example for K8s it can be useful to use an external Redis instance. External redis is currently not supported with Proxmox Community Scripts ::: -| Environment Variable | Description | Possible values | Default | -| ------------------------ | ----------- | --------------- | ------- | -| `REDIS_IS_EXTERNAL` | Whether Redis is running externally. | `true` / `false` | `false` | -| `REDIS_HOST` | Hostname of the Redis instance. | Any valid hostname | - | -| `REDIS_PORT` | Port of the Redis instance. | Any valid port | `6379` | -| `REDIS_USERNAME` | Username to connect to the Redis instance. | Any valid username | - | -| `REDIS_PASSWORD` | Password to connect to the Redis instance. | Any valid password | - | -| `REDIS_DATABASE_INDEX` | Select which database of your redis instance should be used. | Any numeric index | - | -| `REDIS_TLS_CA` | CA certificate for Redis TLS connections. If a certificate is specified the connection will use TLS. | Any valid CA certificate | - | - +| Environment Variable | Description | Possible values | Default | +| ---------------------- | ---------------------------------------------------------------------------------------------------- | ------------------------ | ------- | +| `REDIS_IS_EXTERNAL` | Whether Redis is running externally. | `true` / `false` | `false` | +| `REDIS_HOST` | Hostname of the Redis instance. | Any valid hostname | - | +| `REDIS_PORT` | Port of the Redis instance. | Any valid port | `6379` | +| `REDIS_USERNAME` | Username to connect to the Redis instance. | Any valid username | - | +| `REDIS_PASSWORD` | Password to connect to the Redis instance. | Any valid password | - | +| `REDIS_DATABASE_INDEX` | Select which database of your redis instance should be used. | Any numeric index | - | +| `REDIS_TLS_CA` | CA certificate for Redis TLS connections. If a certificate is specified the connection will use TLS. | Any valid CA certificate | - | ## Proxy -| Environment Variable | Description | Possible values | Default | -| ------------------------ | ----------- | --------------- | ------- | -| ``HTTP_PROXY`` | HTTP proxy to use | Any valid HTTP proxy URL | - | -| ``HTTPS_PROXY`` | HTTPS proxy to use | Any valid HTTPS proxy URL | - | -| ``NO_PROXY`` | Comma separated list of hosts that should be excluded from proxying | Any valid hostnames | - | - +| Environment Variable | Description | Possible values | Default | +| -------------------- | ------------------------------------------------------------------- | ------------------------- | ------- | +| `HTTP_PROXY` | HTTP proxy to use | Any valid HTTP proxy URL | - | +| `HTTPS_PROXY` | HTTPS proxy to use | Any valid HTTPS proxy URL | - | +| `NO_PROXY` | Comma separated list of hosts that should be excluded from proxying | Any valid hostnames | - | ## Advanced deployments @@ -109,6 +106,6 @@ External redis is currently not supported with Proxmox Community Scripts The advanced deployments environment variables should only be used if you know what you are doing. ::: -| Environment Variable | Description | -| ------------------------ | ----------- | -| ``DB_MIGRATIONS_DISABLED`` | Disable db migrations. For example for helm charts | +| Environment Variable | Description | +| ------------------------ | -------------------------------------------------- | +| `DB_MIGRATIONS_DISABLED` | Disable db migrations. For example for helm charts | diff --git a/apps/docs/docs/advanced/icons/index.mdx b/apps/docs/docs/advanced/icons/index.mdx index b73d49e02..0931c6e43 100644 --- a/apps/docs/docs/advanced/icons/index.mdx +++ b/apps/docs/docs/advanced/icons/index.mdx @@ -9,17 +9,19 @@ tags: --- ## Icon picker + Icons in Homarr are automatically requested from multiple sources: - - [Dashboard Icons](https://dashboardicons.com/) - Our recommended source with over 1888+ curated, high-quality icons - - [selfh.st icons](https://github.com/selfhst/icons) - - [Simple icons](https://github.com/simple-icons/simple-icons) - - [Tabler icons](https://tabler-icons.io/) - - [Papirus icons](https://github.com/PapirusDevelopmentTeam/papirus-icon-theme) - - [Homelab Svg assets](https://github.com/loganmarchione/homelab-svg-assets) - - **Local icons**: automatically fetched from the [medias feature](/docs/management/media/) + +- [Dashboard Icons](https://dashboardicons.com/) - Our recommended source with more than 1,888 curated, high-quality icons +- [selfh.st icons](https://github.com/selfhst/icons) +- [Simple icons](https://github.com/simple-icons/simple-icons) +- [Tabler icons](https://tabler-icons.io/) +- [Papirus icons](https://github.com/PapirusDevelopmentTeam/papirus-icon-theme) +- [Homelab Svg assets](https://github.com/loganmarchione/homelab-svg-assets) +- **Local icons**: automatically fetched from the [medias feature](/docs/management/media/) Using these icon sources, Homarr provides a total collection of over 11,000 icons at your fingertips. -The icon picker is a fast searcher that helps you to find your desired icon simply by entering a search term. +The image picker searches this collection after a short typing delay. When a name is available, such as an app or search engine name, the picker uses it as the initial search. Results show your locally uploaded images first, followed by SVG icons and then other image formats. ### Finding Missing Icons @@ -29,6 +31,13 @@ If you can't find the icon you're looking for in Homarr's built-in picker, we st Icons that are high quality and printable ([SVG](https://wikipedia.org/wiki/Scalable_Vector_Graphics)) are marked with a red badge "SVG" at the top right. +You can clear the selected image with the clear button or the usual keyboard shortcut for deleting a line (Command+Backspace on macOS or Control+Backspace on other platforms). Clearing the field does not restore the previous image. + ### Using external icons + If you don't find the icon you're looking for on Dashboard Icons or wish to use a different source, you can simply enter a URL that points to an icon. -Direct HTTP(S) image URLs are used as entered instead of being searched in the built-in repositories. It is important that the URL directly points to the file without any advertisements or elements around it. +Direct HTTP(S) image URLs are used as entered instead of being searched in the built-in repositories. The picker previews the image and shows whether it loaded successfully. It is important that the URL directly points to the file without any advertisements or elements around it. + +### Uploading a local image + +Users with media upload permission can select **Upload image** next to the field. After the upload finishes, the new local image is selected immediately and is available at the top of future searches. diff --git a/apps/docs/docs/advanced/proxy/index.mdx b/apps/docs/docs/advanced/proxy/index.mdx index ef4e41f1d..668031d9d 100644 --- a/apps/docs/docs/advanced/proxy/index.mdx +++ b/apps/docs/docs/advanced/proxy/index.mdx @@ -47,7 +47,6 @@ services: traefik.http.routers.homarr.rule: Host(`your.internal.dns.address.here.com`) traefik.http.routers.homarr.entrypoints: websecure traefik.http.routers.homarr-secure.app: homarr - traefik.http.apps.homarr.loadbalancer.server.port: 7575 networks: proxy: diff --git a/apps/docs/docs/getting-started/installation/helm.md b/apps/docs/docs/getting-started/installation/helm.md index 051c38955..bd969e5e5 100644 --- a/apps/docs/docs/getting-started/installation/helm.md +++ b/apps/docs/docs/getting-started/installation/helm.md @@ -2,9 +2,9 @@ homarr logo -![Version: 8.25.0](https://img.shields.io/badge/Version-8.25.0-informational?style=flat) +![Version: 8.26.0](https://img.shields.io/badge/Version-8.26.0-informational?style=flat) ![Type: application](https://img.shields.io/badge/Type-application-informational?style=flat) -![AppVersion: v1.73.0](https://img.shields.io/badge/AppVersion-v1.73.0-informational?style=flat) +![AppVersion: v1.74.0](https://img.shields.io/badge/AppVersion-v1.74.0-informational?style=flat) A Helm chart to deploy homarr for Kubernetes @@ -429,7 +429,7 @@ All available values are listed on the [artifacthub](https://artifacthub.io/pack | httproute.rules[0].matches[0].path.value | string | `"/"` | Path value to match | | image.pullPolicy | string | `"IfNotPresent"` | Image pull policy | | image.repository | string | `"ghcr.io/homarr-labs/homarr"` | Image repository | -| image.tag | string | `"v1.73.0"` | Overrides the image tag whose default is the chart appVersion | +| image.tag | string | `"v1.74.0"` | Overrides the image tag whose default is the chart appVersion | | imagePullSecrets | list | `[]` | Secrets for Docker registry | | ingress.annotations | object | `{}` | Ingress annotations | | ingress.enabled | bool | `false` | Enable ingress | diff --git a/apps/docs/docs/integrations/whats-up-docker/index.mdx b/apps/docs/docs/integrations/whats-up-docker/index.mdx new file mode 100644 index 000000000..31a0127f5 --- /dev/null +++ b/apps/docs/docs/integrations/whats-up-docker/index.mdx @@ -0,0 +1,48 @@ +--- +title: "What's Up Docker" +description: "What's Up Docker (WUD) watches your Docker containers and reports which ones have newer image versions available." +hide_title: true +--- + +import { IntegrationHeader } from "@site/src/components/integrations/header"; +import { IntegrationCapabilites } from "@site/src/components/integrations/widgets"; +import { AddingIntegration } from "@site/src/components/integrations/adding"; +import { IntegrationSecrets } from "@site/src/components/integrations/secrets"; +import { wudIntegration } from "."; +import { wudWidget } from "@site/docs/widgets/whats-up-docker"; + + + +The What's Up Docker integration lets Homarr connect to your [WUD](https://github.com/getwud/wud) instance so you can see how many of your watched containers have image updates available directly from your dashboard. + +### Widgets & Capabilities + + + +### Adding the integration + + + +:::info URL configuration +Use the root URL of your WUD instance, for example `https://wud.example.com`. Homarr calls the `/api/app` and `/api/containers` endpoints under that URL automatically. +::: + +### Secrets + +WUD does not require authentication by default. If your instance is protected with [Basic Authentication](https://github.com/getwud/wud/blob/main/docs/configuration/authentications/basic/README.md), you can provide a username and password. + + diff --git a/apps/docs/docs/integrations/whats-up-docker/index.ts b/apps/docs/docs/integrations/whats-up-docker/index.ts new file mode 100644 index 000000000..a69dcafa4 --- /dev/null +++ b/apps/docs/docs/integrations/whats-up-docker/index.ts @@ -0,0 +1,9 @@ +import { IntegrationDefinition } from "@site/src/types"; + +export const wudIntegration: IntegrationDefinition = { + name: "What's Up Docker", + description: + "What's Up Docker (WUD) watches your Docker containers and reports which ones have newer image versions available.", + iconUrl: "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/whats-up-docker.svg", + path: "../../integrations/whats-up-docker", +}; diff --git a/apps/docs/docs/management/apps/index.mdx b/apps/docs/docs/management/apps/index.mdx index 7c84df588..efd42277d 100644 --- a/apps/docs/docs/management/apps/index.mdx +++ b/apps/docs/docs/management/apps/index.mdx @@ -28,7 +28,7 @@ The name must be at least one character long and can be chosen freely. ### Icon URL This is the URL to the icon that will be displayed on the app widget. -You can paste a direct HTTP(S) URL to an image, search the included icon repositories by name, or upload a local file through the upload button. Direct image URLs are used as entered and are not searched in the icon repositories. +You can paste a direct HTTP(S) URL to an image, search the included icon repositories by name, or upload a local file through the upload button. The app name is pre-filled as the initial library search when no image is selected. Local images appear first, followed by SVG icons and other formats. Direct image URLs are previewed, used as entered, and are not searched in the icon repositories. ![Icon URL](./img/app-icon-url.png) diff --git a/apps/docs/docs/management/boards/index.mdx b/apps/docs/docs/management/boards/index.mdx index f1eb3c572..93bf78ae3 100644 --- a/apps/docs/docs/management/boards/index.mdx +++ b/apps/docs/docs/management/boards/index.mdx @@ -9,11 +9,11 @@ tags: - Layout --- -import iconColorImage from './img/icon-color.png' -import itemRadiusImage from './img/item-radius.png' -import layoutLargeImage from './img/layout-large.png' -import layoutMediumImage from './img/layout-medium.png' -import layoutSmallImage from './img/layout-small.png' +import iconColorImage from "./img/icon-color.png"; +import itemRadiusImage from "./img/item-radius.png"; +import layoutLargeImage from "./img/layout-large.png"; +import layoutMediumImage from "./img/layout-medium.png"; +import layoutSmallImage from "./img/layout-small.png"; Each dashboard is called a "board". You can create as many boards as you want. @@ -24,24 +24,29 @@ Other boards can be viewed by direct links (e.g. my-homarr.com/board/smart-home) Names of boards must be unique because this will be used in the URL to load the desired board. ## Create a new board + When creating a board, the availability of the board name will be checked for you. ![](./img/create-board-modal.png) ### Name + The name must not include any special characters and must be at least one character long. Underscores and hyphen-minus are allowed. ### Column count -Homarr has a complex drag and drop system that can be used from the browser. + +Homarr has a complex drag-and-drop system that can be used from the browser. The column count defines how many horizontal columns are available to drag and drop elements to. ### Public + This will enable public access for everyone - regardless of whether they are logged in or not. -This can be really useful if you want to have public boards in your company or for family and fiends. +This can be really useful if you want to have public boards in your company or for family and friends. Modifications for public boards must be allowed explicitly using user groups and their permissions. ## Board settings + You navigate to the board settings by clicking on these three dots: ![](./img/navigate-to-settings.png) @@ -50,8 +55,12 @@ Alternatively, you can also navigate from the board page itself using the cog ic ![](./img/navigate-to-settings-2.png) +All board settings are edited on a single page. Click the **Save changes** button in the save bar at the bottom to apply them, or **Discard** to restore the last saved values. The save bar only appears when you have unsaved changes. Access control and the Danger zone are independent sections and are applied immediately. + ### General + #### Page title + This is the title that will be visible at the top left in the navigation bar: ![](./img/page-title.png) @@ -59,6 +68,7 @@ This is the title that will be visible at the top left in the navigation bar: This field is optional and Homarr will fall back to "Homarr" if nothing is set. #### Meta title + This is the secondary title of the page that is not directly visible in the page itself. Browser will use it to set the title of tabs: @@ -67,10 +77,12 @@ Browser will use it to set the title of tabs: Homarr will fall back to the board name and a suffix if nothing is set. #### Logo image URL + This is the URL that is used for the image at the top left. Homarr will fall back to the Homarr logo if nothing is set. #### Favicon image URL + This is the URL that is used for the favicon in the tab title. Homarr will fall back to the Homarr logo if nothing is set. @@ -94,51 +106,65 @@ Amount of columns for this layout. Defines how many items can be placed in a row #### Breakpoint -Minimum width of the screen where the layout will be used. -Once the minmum of the next layout is reached the layout will change. +Minimum width of the screen where the layout will be used. +Once the minimum of the next layout is reached the layout will change. #### Preview - - - + + + ### Background + #### Background image URL + Homarr can display a background image behind apps and widgets. This URL can be used to define what image should be shown. #### Background image attachment + This defines whether the background should move when the user scrolls. #### Background image size + This defines whether the background should cover the entire page (and possibly be cropped) or never be cropped but may not cover the entire page. #### Background image repeat + This defines whether the background should be repeated if it cannot cover the entire page. This option can be useful if you have patterns that can be repeated easily (e.g. patterns): ![](./img/background-repeat.png) ### Appearance + #### Primary color + Color that can be chosen freely to give accents to active elements. + #### Secondary color + Color that can be chosen freely to give accents. + #### Opacity + Opacity of the colors. + #### Icon color + Change the color of your bookmark / app icons. - + #### Item radius + Change the radius of your items / categories. - - + ### Custom CSS + This is the field where you can enter custom CSS. The styling will only be applied on the respective board page. @@ -147,14 +173,16 @@ The styling will only be applied on the respective board page. ### Behaviour #### Disable app status + This will disable the status check for apps. ### Access control + With the access control, you can permit a single user or a group to your board. The users and groups can have one of these three levels of access: | **Permission Level** | View board | Edit mode | Settings | Danger zone (eg. delete) | -|----------------------|------------|-----------|----------|--------------------------| +| -------------------- | ---------- | --------- | -------- | ------------------------ | | View board | X | | | | | Modify board | X | X | X | | | Full access | X | X | X | X | @@ -173,22 +201,27 @@ After editing permissions, the save button below the table must be pressed. Otherwise, all changes will be discarded. ### Danger zone + #### Rename + Renaming a board will break all existing links to it permanently with no redirect. #### Board visibility + By default, boards will be private. This means only authenticated users that are authorized have access. Making a board public will expose it to everyone - including unauthenticated users. #### Delete + This will permanently delete the board. This action is irreversible and cannot be undone. ## Delete boards + The deletion of boards is permanent and cannot be undone. There are two ways to delete a board: -- Navigate to the settings of your board, open the "Danger zone" dropdown and click on the "delete this board" button. +- Navigate to the settings of your board, open the "Danger zone" section and click on the "delete this board" button. - Navigate to the list of boards in the management pages, click the three dots and click on "delete permanently". Both actions will execute the same deletion process. @@ -196,7 +229,7 @@ Both actions will execute the same deletion process. ## Duplicate boards :::note -Duplicating a board will not copy the users and groups that have access to the board +Duplicating a board will not copy the users and groups that have access to the board nor the integrations the user does not have access to. ::: @@ -206,47 +239,51 @@ You can duplicate a board by clicking on the three dots in the list of boards an ![](./img/duplicate-board-modal.png) ## Setting boards as your home board + The home board is the dashboard, that will be shown at the root path of Homarr or if no board name was passed in the URL. All the following paths will lead to the home board: -- ``my-homarr.com`` -- ``my-homarr.com/boards`` + +- `my-homarr.com` +- `my-homarr.com/boards` Your home board will have a special small badge at the top right in the list of boards: ![](./img/home-board-flag.png) ### For yourself + To set the home board yourself, the easiest option is to set it directly in the list of boards: ![](./img/set-as-home-board-menu.png) Alternatively, you can also define it via your user profile: + 1. Click on your user profile at the top right -2. Click on ``Your preferences`` -3. Change the home board in the ``home board`` dropdown and click on ``Save``. +2. Click on `Your preferences` +3. Change the home board in the `home board` dropdown and click on `Save`. ### For other users -1. Navigate to the users: ``Management`` > ``Users`` > ``Manage`` +1. Navigate to the users: `Management` > `Users` > `Manage` 2. Click on the username of the user that you want to adjust -3. Select the desired home board via the dropdown and click on ``Save`` \ -![](./img/set-home-board-other-user.png) +3. Select the desired home board via the dropdown and click on `Save` \ + ![](./img/set-home-board-other-user.png) ### For user groups -1. Navigate to the user groups: ``Management`` > ``Users`` > ``Groups`` > ``Manage`` -2. Go to tab ``Settings`` -3. Select the desired home board via the dropdown and click on ``Save`` \ -![](./img/set-home-board-user-group.png) +1. Navigate to the user groups: `Management` > `Users` > `Groups` > `Manage` +2. Go to tab `Settings` +3. Select the desired home board via the dropdown and click on `Save` \ + ![](./img/set-home-board-user-group.png) ### For whole server You can also set a global home board that will be used for all users that have not set a home board themselves. It will also be used for anonymous users. -1. Navigate to the settings: ``Management`` > ``Settings`` > ``Boards`` -2. Select the desired home board via the dropdown and click on ``Save`` \ -![](./img/set-home-board-global.png) +1. Navigate to the settings: `Management` > `Settings` > `Boards` +2. Select the desired home board via the dropdown and click on `Save` \ + ![](./img/set-home-board-global.png) :::note For the global home board you can only select boards that are public. @@ -255,4 +292,4 @@ For the global home board you can only select boards that are public. ### Mobile home board Same as the home board, you can also set a mobile home board. -It will be used for devices that are detected as mobile devices. (Using User-Agent header) \ No newline at end of file +It will be used for devices that are detected as mobile devices. (Using User-Agent header) diff --git a/apps/docs/docs/management/settings/index.mdx b/apps/docs/docs/management/settings/index.mdx index 016d56d10..8507d2b4f 100644 --- a/apps/docs/docs/management/settings/index.mdx +++ b/apps/docs/docs/management/settings/index.mdx @@ -13,6 +13,8 @@ tags: The settings page applies options to the whole Homarr application. Some changes need a full page reload before they take effect. +All changes are collected in a single form. Click the **Save changes** button in the save bar at the bottom of the page to apply them. The save bar only appears when you have unsaved changes, and the **Discard** button reverts your changes. + ## Analytics Homarr uses [PostHog](https://posthog.com/) to collect anonymous usage data. diff --git a/apps/docs/docs/widgets/whats-up-docker/index.mdx b/apps/docs/docs/widgets/whats-up-docker/index.mdx new file mode 100644 index 000000000..0786be36b --- /dev/null +++ b/apps/docs/docs/widgets/whats-up-docker/index.mdx @@ -0,0 +1,35 @@ +--- +title: "What's Up Docker" +description: "Displays how many watched containers have image updates available." +hide_title: true +--- + +import { WidgetHeader } from "@site/src/components/widgets/header"; +import { AddingWidget } from "@site/src/components/widgets/adding"; +import { WidgetConfig } from "@site/src/components/widgets/configuration"; +import { WidgetIntegrations } from "@site/src/components/widgets/integrations"; +import { wudWidget } from "."; +import { wudIntegration } from "@site/docs/integrations/whats-up-docker"; + + + +This widget shows two stats from your WUD instance: the total number of monitored containers, and how many of them currently have an image update available. Optionally, it can also list each outdated container with its current and new version, linking to the release notes when WUD provides one. + +### Supported Integrations + + + +### Adding the widget + + + +### Configuration + + diff --git a/apps/docs/docs/widgets/whats-up-docker/index.ts b/apps/docs/docs/widgets/whats-up-docker/index.ts new file mode 100644 index 000000000..80a516328 --- /dev/null +++ b/apps/docs/docs/widgets/whats-up-docker/index.ts @@ -0,0 +1,37 @@ +import { WidgetDefinition } from "@site/src/types"; +import { IconBrandDocker } from "@tabler/icons-react"; + +export const wudWidget: WidgetDefinition = { + icon: IconBrandDocker, + name: "What's Up Docker", + description: "Displays how many watched containers have image updates available.", + path: "../../widgets/whats-up-docker", + configuration: { + items: [ + { + name: "Show title", + description: "Displays the icon and \"What's Up Docker\" label above the stats", + values: { type: "boolean" }, + defaultValue: "yes", + }, + { + name: "Show update ring", + description: "Displays a ring showing the percentage of monitored containers with a pending update", + values: { type: "boolean" }, + defaultValue: "yes", + }, + { + name: "Layout", + description: "Arrange the two stats side by side (Horizontal) or stacked (Vertical)", + values: { type: "select", options: ["Horizontal", "Vertical"] }, + defaultValue: "Horizontal", + }, + { + name: "Show container update list", + description: "Lists each monitored container that has an image update available, linking to its release notes when known", + values: { type: "boolean" }, + defaultValue: "no", + }, + ], + }, +}; diff --git a/apps/nextjs/next.config.ts b/apps/nextjs/next.config.ts index 4ff31b9aa..2105259be 100644 --- a/apps/nextjs/next.config.ts +++ b/apps/nextjs/next.config.ts @@ -1,4 +1,6 @@ // Importing env files here to validate on build +import path from "node:path"; + import "@homarr/auth/env"; import "@homarr/core/infrastructure/db/env"; import "@homarr/common/env"; @@ -13,7 +15,21 @@ const withNextIntl = createNextIntlPlugin({ requestConfig: "../../packages/translation/src/request.ts", }); +const getDevelopmentServiceAliases = () => { + if (process.env.NODE_ENV !== "development") { + return undefined; + } + + return { + "@homarr/tasks": "./src/instrumentation-noop.ts", + "@homarr/websocket": "./src/instrumentation-noop.ts", + }; +}; + const nextConfig: NextConfig = { + // Next previews otherwise create agent instruction files in the application + // directory during development. + agentRules: false, env: { HOMARR_VERSION: process.env.HOMARR_VERSION ?? "unknown", }, @@ -30,19 +46,14 @@ const nextConfig: NextConfig = { serverExternalPackages: ["dockerode", "isomorphic-dompurify", "jsdom", "better-sqlite3"], experimental: { optimizePackageImports: ["@mantine/core", "@mantine/hooks", "@tabler/icons-react"], - turbopackFileSystemCacheForDev: true, - webpackMemoryOptimizations: true, + turbopackFileSystemCacheForBuild: true, + useTypeScriptCli: true, }, turbopack: { - // ponytail: known Turbopack NFT warning from path.join(process.cwd(), …) in - // src/app/api/backup/{route,shared}.ts. No working placement in 16.2.x - // (see vercel/next.js#95125). Suppress until upstream fix lands. - ignoreIssue: [ - { - path: "**/*", - title: "Encountered unexpected file in NFT list", - }, - ], + root: path.resolve(import.meta.dirname, "../.."), + // Development runs tasks and WebSocket as separate processes. These aliases + // keep their production-only instrumentation imports out of the dev graph. + resolveAlias: getDevelopmentServiceAliases(), }, transpilePackages: ["@homarr/ui", "@homarr/notifications", "@homarr/modals", "@homarr/spotlight", "@homarr/widgets"], images: { diff --git a/apps/nextjs/package.json b/apps/nextjs/package.json index 4a3e0dd3e..3c33a1545 100644 --- a/apps/nextjs/package.json +++ b/apps/nextjs/package.json @@ -59,11 +59,10 @@ "@modelcontextprotocol/sdk": "catalog:", "@scalar/api-reference-react": "catalog:", "@tabler/icons-react": "catalog:", - "@tanstack/query-async-storage-persister": "catalog:", + "@tanstack/react-devtools": "catalog:", "@tanstack/react-query": "catalog:", "@tanstack/react-query-devtools": "catalog:", "@tanstack/react-query-next-experimental": "catalog:", - "@tanstack/react-query-persist-client": "catalog:", "@trpc/client": "catalog:", "@trpc/next": "catalog:", "@trpc/react-query": "catalog:", diff --git a/apps/nextjs/src/app/[locale]/_client-providers/development-tools.tsx b/apps/nextjs/src/app/[locale]/_client-providers/development-tools.tsx new file mode 100644 index 000000000..a23164547 --- /dev/null +++ b/apps/nextjs/src/app/[locale]/_client-providers/development-tools.tsx @@ -0,0 +1,120 @@ +"use client"; + +import { useEffect, useState } from "react"; +import { usePathname } from "next/navigation"; +import { TanStackDevtools } from "@tanstack/react-devtools"; +import type { TanStackDevtoolsReactPlugin } from "@tanstack/react-devtools"; +import type { QueryClient } from "@tanstack/react-query"; +import { useQueryClient } from "@tanstack/react-query"; +import { ReactQueryDevtoolsPanel } from "@tanstack/react-query-devtools"; + +const valueStyle = { fontFamily: "monospace", overflowWrap: "anywhere" } as const; +const metricStyle = { + background: "color-mix(in srgb, currentColor 4%, transparent)", + border: "1px solid color-mix(in srgb, currentColor 18%, transparent)", + borderRadius: 8, + padding: 12, +} as const; + +const readDiagnostics = (queryClient: QueryClient) => { + const queries = queryClient.getQueryCache().getAll(); + const mutations = queryClient.getMutationCache().getAll(); + const board = document.querySelector("[data-homarr-dev-benchmark-board]"); + const widgetItems = board?.querySelectorAll('[data-type="item"]').length ?? 0; + const readyWidgets = board?.querySelectorAll("[data-homarr-widget-ready]").length ?? 0; + const resources = performance.getEntriesByType("resource") as PerformanceResourceTiming[]; + + return { + active: queries.filter((query) => query.getObserversCount() > 0).length, + errors: queries.filter((query) => query.state.status === "error").length, + fetching: queries.filter((query) => query.state.fetchStatus === "fetching").length, + pendingMutations: mutations.filter((mutation) => mutation.state.status === "pending").length, + stale: queries.filter((query) => query.isStale()).length, + total: queries.length, + readyWidgets, + widgetItems, + scriptKiB: Math.round( + resources + .filter((resource) => resource.initiatorType === "script") + .reduce((total, resource) => total + resource.decodedBodySize, 0) / 1024, + ), + }; +}; + +const Metric = ({ label, value }: { label: string; value: number | string }) => ( +
+
{label}
+ {value} +
+); + +const HomarrDevtoolsPanel = ({ active }: { active: boolean }) => { + const pathname = usePathname(); + const queryClient = useQueryClient(); + const [diagnostics, setDiagnostics] = useState(() => readDiagnostics(queryClient)); + + useEffect(() => { + if (!active) return; + + const update = () => setDiagnostics(readDiagnostics(queryClient)); + let frame: number | undefined; + const scheduleUpdate = () => { + if (frame !== undefined) return; + frame = window.requestAnimationFrame(() => { + frame = undefined; + update(); + }); + }; + const unsubscribeQueries = queryClient.getQueryCache().subscribe(scheduleUpdate); + const unsubscribeMutations = queryClient.getMutationCache().subscribe(scheduleUpdate); + const observer = new MutationObserver(scheduleUpdate); + observer.observe(document.body, { childList: true, subtree: true }); + update(); + + return () => { + unsubscribeQueries(); + unsubscribeMutations(); + observer.disconnect(); + if (frame !== undefined) window.cancelAnimationFrame(frame); + }; + }, [active, pathname, queryClient]); + + if (!active) return null; + + return ( +
+
+

Homarr performance

+

Live state for {pathname}

+
+
+ + + + + + + + +
+
+ ); +}; + +const developmentToolsPlugins = [ + { + id: "tanstack-query", + name: "TanStack Query", + render: () => , + }, + { + id: "homarr-performance", + name: "Homarr", + defaultOpen: true, + render: (_element, { devtoolsOpen }) => , + }, +] satisfies TanStackDevtoolsReactPlugin[]; + +export const DevelopmentTools = () => ( + +); diff --git a/apps/nextjs/src/app/[locale]/_client-providers/query-cache-persister.ts b/apps/nextjs/src/app/[locale]/_client-providers/query-cache-persister.ts deleted file mode 100644 index 3af24c508..000000000 --- a/apps/nextjs/src/app/[locale]/_client-providers/query-cache-persister.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { createAsyncStoragePersister } from "@tanstack/query-async-storage-persister"; -import superjson from "superjson"; - -import { fetchApi } from "@homarr/api/client"; -import { getActiveQueryCacheBoardId, queryCacheStoragePrefix } from "@homarr/api/query-cache"; - -const queryCacheStorage = { - getItem: (_key: string) => null as string | null, - async setItem(_key: string, value: string) { - const boardId = getActiveQueryCacheBoardId(); - if (!boardId) return; - await fetchApi.queryCache.setItem.mutate({ boardId, value }).catch((error) => { - console.warn("[query-cache] persist failed", error); - }); - }, - async removeItem(_key: string) { - const boardId = getActiveQueryCacheBoardId(); - if (!boardId) return; - await fetchApi.queryCache.removeItem.mutate({ boardId }).catch((error) => { - console.warn("[query-cache] remove failed", error); - }); - }, -}; - -export const createWidgetQueryPersister = () => - createAsyncStoragePersister({ - storage: typeof window === "undefined" ? undefined : queryCacheStorage, - key: queryCacheStoragePrefix, - throttleTime: 2000, - serialize: (data) => superjson.stringify(data), - deserialize: (data) => superjson.parse(data), - }); diff --git a/apps/nextjs/src/app/[locale]/_client-providers/query-retry.spec.ts b/apps/nextjs/src/app/[locale]/_client-providers/query-retry.spec.ts new file mode 100644 index 000000000..77aa7c918 --- /dev/null +++ b/apps/nextjs/src/app/[locale]/_client-providers/query-retry.spec.ts @@ -0,0 +1,27 @@ +import { describe, expect, it } from "vitest"; +import { TRPCClientError } from "@trpc/client"; + +import { createQueryRetry } from "./query-retry"; + +const createTrpcError = (code: string) => { + const error = Object.assign(new Error(code), { data: { code } }); + Object.setPrototypeOf(error, TRPCClientError.prototype); + return error; +}; + +describe("createQueryRetry", () => { + it.each(["BAD_REQUEST", "UNAUTHORIZED", "FORBIDDEN", "NOT_FOUND", "UNPROCESSABLE_CONTENT"])( + "does not retry the permanent %s response", + (code) => { + expect(createQueryRetry(3)(0, createTrpcError(code))).toBe(false); + }, + ); + + it("retries transient and network failures only up to the configured limit", () => { + const retry = createQueryRetry(3); + + expect(retry(0, createTrpcError("INTERNAL_SERVER_ERROR"))).toBe(true); + expect(retry(2, new Error("connection reset"))).toBe(true); + expect(retry(3, new Error("connection reset"))).toBe(false); + }); +}); diff --git a/apps/nextjs/src/app/[locale]/_client-providers/query-retry.ts b/apps/nextjs/src/app/[locale]/_client-providers/query-retry.ts new file mode 100644 index 000000000..09b5f19c3 --- /dev/null +++ b/apps/nextjs/src/app/[locale]/_client-providers/query-retry.ts @@ -0,0 +1,20 @@ +import { TRPCClientError } from "@trpc/client"; + +const nonRetryableTrpcCodes = new Set([ + "PARSE_ERROR", + "BAD_REQUEST", + "UNAUTHORIZED", + "FORBIDDEN", + "NOT_FOUND", + "METHOD_NOT_SUPPORTED", + "CONFLICT", + "PRECONDITION_FAILED", + "PAYLOAD_TOO_LARGE", + "UNPROCESSABLE_CONTENT", +]); + +export const createQueryRetry = (maxRetries: number) => (failureCount: number, error: unknown) => { + if (failureCount >= maxRetries) return false; + if (error instanceof TRPCClientError && error.data?.code && nonRetryableTrpcCodes.has(error.data.code)) return false; + return true; +}; diff --git a/apps/nextjs/src/app/[locale]/_client-providers/session-query-scope.spec.ts b/apps/nextjs/src/app/[locale]/_client-providers/session-query-scope.spec.ts new file mode 100644 index 000000000..f82001a5e --- /dev/null +++ b/apps/nextjs/src/app/[locale]/_client-providers/session-query-scope.spec.ts @@ -0,0 +1,52 @@ +// @vitest-environment jsdom + +import { act, createElement } from "react"; +import { createRoot } from "react-dom/client"; +import { describe, expect, it, vi } from "vitest"; + +import { getSessionQueryScope, SessionQueryScopeGuard } from "./session-query-scope"; + +describe("getSessionQueryScope", () => { + it("is stable when permission order changes", () => { + expect(getSessionQueryScope({ user: { id: "user-a", permissions: ["board-view", "integration-use"] } })).toBe( + getSessionQueryScope({ user: { id: "user-a", permissions: ["integration-use", "board-view"] } }), + ); + }); + + it("changes for a different user or permission set", () => { + const original = getSessionQueryScope({ user: { id: "user-a", permissions: ["board-view"] } }); + + expect(getSessionQueryScope({ user: { id: "user-b", permissions: ["board-view"] } })).not.toBe(original); + expect(getSessionQueryScope({ user: { id: "user-a", permissions: [] } })).not.toBe(original); + expect(getSessionQueryScope(null)).toBeNull(); + }); + + it("removes the previous session subtree before requesting a document reload", async () => { + const host = document.createElement("div"); + const root = createRoot(host); + const onScopeChange = vi.fn(); + const renderScope = async (currentScope: string) => { + await act(async () => { + root.render( + createElement( + SessionQueryScopeGuard, + { currentScope, initialScope: "a", onScopeChange }, + createElement("span", null, "session-a-secret"), + ), + ); + }); + }; + + try { + await renderScope("a"); + expect(host.textContent).toBe("session-a-secret"); + + await renderScope("b"); + expect(host.textContent).not.toContain("session-a-secret"); + expect(host.querySelector('[role="status"]')?.getAttribute("aria-busy")).toBe("true"); + expect(onScopeChange).toHaveBeenCalledOnce(); + } finally { + await act(async () => root.unmount()); + } + }); +}); diff --git a/apps/nextjs/src/app/[locale]/_client-providers/session-query-scope.ts b/apps/nextjs/src/app/[locale]/_client-providers/session-query-scope.ts new file mode 100644 index 000000000..d2fa1e732 --- /dev/null +++ b/apps/nextjs/src/app/[locale]/_client-providers/session-query-scope.ts @@ -0,0 +1,39 @@ +import type { PropsWithChildren } from "react"; +import { createElement, useEffect } from "react"; + +interface QuerySession { + user: { + id: string; + permissions: string[]; + }; +} + +export const getSessionQueryScope = (session: QuerySession | null | undefined) => + session ? JSON.stringify([session.user.id, session.user.permissions.toSorted()]) : null; + +interface SessionQueryScopeGuardProps { + initialScope: string | null; + currentScope: string | null; + onScopeChange: () => void; +} + +export const SessionQueryScopeGuard = ({ + initialScope, + currentScope, + onScopeChange, + children, +}: PropsWithChildren) => { + const hasScopeChanged = initialScope !== currentScope; + useEffect(() => { + if (hasScopeChanged) onScopeChange(); + }, [hasScopeChanged, onScopeChange]); + + if (!hasScopeChanged) return children; + + return createElement("div", { + "aria-busy": true, + "aria-label": "Refreshing session", + role: "status", + style: { minHeight: "100dvh" }, + }); +}; diff --git a/apps/nextjs/src/app/[locale]/_client-providers/trpc.tsx b/apps/nextjs/src/app/[locale]/_client-providers/trpc.tsx index 3e167dd8c..535d88e1c 100644 --- a/apps/nextjs/src/app/[locale]/_client-providers/trpc.tsx +++ b/apps/nextjs/src/app/[locale]/_client-providers/trpc.tsx @@ -1,12 +1,10 @@ "use client"; import type { PropsWithChildren } from "react"; -import { useState } from "react"; -import type { QueryKey } from "@tanstack/react-query"; -import { QueryClient } from "@tanstack/react-query"; -import { ReactQueryDevtools } from "@tanstack/react-query-devtools"; +import { useEffect, useMemo, useState } from "react"; +import dynamic from "next/dynamic"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { ReactQueryStreamedHydration } from "@tanstack/react-query-next-experimental"; -import { PersistQueryClientProvider } from "@tanstack/react-query-persist-client"; import { createWSClient, httpBatchStreamLink, @@ -25,18 +23,24 @@ import { TRPCClientError } from "@trpc/client"; import type { AppRouter } from "@homarr/api"; import { clientApi } from "@homarr/api/client"; import { - isPersistableWidgetQueryKey, - queryCacheBuster, + dashboardSupportingQueryPolicies, queryCacheDefaultGcTimeMs, queryCacheDefaultRefetchIntervalMs, queryCacheDefaultStaleTimeMs, } from "@homarr/api/query-cache"; import { createHeadersCallbackForSource, getTrpcUrl } from "@homarr/api/shared"; +import { useSession } from "@homarr/auth/client"; import { env } from "@homarr/common/env"; import { showWarningNotification } from "@homarr/notifications"; -import { widgetImports } from "@homarr/widgets"; +import { widgetQueryRefetchIntervals } from "@homarr/widgets/refetch-intervals"; -import { createWidgetQueryPersister } from "./query-cache-persister"; +import { getSessionQueryScope, SessionQueryScopeGuard } from "./session-query-scope"; +import { createQueryRetry } from "./query-retry"; + +const DevelopmentTools = + process.env.NODE_ENV === "development" + ? dynamic(() => import("./development-tools").then(({ DevelopmentTools: Tools }) => Tools), { ssr: false }) + : () => null; const getWebSocketProtocol = () => { if (typeof window === "undefined") { @@ -59,21 +63,46 @@ const constructWebsocketUrl = () => { return `${getWebSocketProtocol()}://${window.location.hostname}:${window.location.port}/websockets`; }; -const wsClient = createWSClient({ - url: constructWebsocketUrl(), -}); +export function TRPCReactProvider({ children }: PropsWithChildren) { + const { data: session } = useSession(); + const sessionQueryScope = getSessionQueryScope(session); + const [initialSessionQueryScope] = useState(() => sessionQueryScope); -export function TRPCReactProvider(props: PropsWithChildren) { - const [persister] = useState(() => createWidgetQueryPersister()); + return ( + + {children} + + ); +} + +const reloadPage = () => window.location.reload(); + +const ScopedTRPCReactProvider = ({ children }: PropsWithChildren) => { + const wsClient = useMemo( + () => + createWSClient({ + url: constructWebsocketUrl(), + lazy: { enabled: true, closeMs: 30_000 }, + }), + [], + ); + useEffect( + () => () => { + void wsClient.close(); + }, + [wsClient], + ); const [queryClient] = useState(() => { const client = new QueryClient({ defaultOptions: { queries: { staleTime: queryCacheDefaultStaleTimeMs, gcTime: queryCacheDefaultGcTimeMs, - refetchOnWindowFocus: false, - refetchOnReconnect: false, - retry: 3, + retry: createQueryRetry(env.NODE_ENV === "development" ? 1 : 3), }, mutations: { onError(error) { @@ -91,23 +120,29 @@ export function TRPCReactProvider(props: PropsWithChildren) { }, }, }); - client.setQueryDefaults([["widget"]], { refetchInterval: queryCacheDefaultRefetchIntervalMs }); - for (const { definition } of Object.values(widgetImports)) { - const def = definition as { refetchInterval?: number | null; queryKey?: QueryKey; kind: string }; - if (def.refetchInterval === undefined) continue; - const key = def.queryKey ?? [["widget", def.kind]]; - const interval = def.refetchInterval === null ? false : def.refetchInterval * 1000; - client.setQueryDefaults(key, { refetchInterval: interval }); + client.setQueryDefaults([["widget"]], { + refetchInterval: queryCacheDefaultRefetchIntervalMs, + refetchOnWindowFocus: false, + refetchOnReconnect: false, + }); + for (const { queryKey, intervalSeconds } of widgetQueryRefetchIntervals) { + client.setQueryDefaults(queryKey, { + refetchInterval: intervalSeconds === null ? false : intervalSeconds * 1000, + }); + } + for (const { queryKey, ...policy } of dashboardSupportingQueryPolicies) { + client.setQueryDefaults(queryKey, policy); } return client; }); - const [trpcClient] = useState(() => { + useEffect(() => () => queryClient.clear(), [queryClient]); + + const trpcClient = useMemo(() => { return clientApi.createClient({ links: [ loggerLink({ - enabled: (opts) => - env.NODE_ENV === "development" || (opts.direction === "down" && opts.result instanceof Error), + enabled: (opts) => opts.direction === "down" && opts.result instanceof Error, }), splitLink({ condition: ({ type }) => type === "subscription", @@ -147,25 +182,14 @@ export function TRPCReactProvider(props: PropsWithChildren) { }), ], }); - }); + }, [wsClient]); return ( - - query.state.status === "success" && isPersistableWidgetQueryKey(query.queryKey), - }, - }} - > - {props.children} - - + + {children} + {process.env.NODE_ENV === "development" && } + ); -} +}; diff --git a/apps/nextjs/src/app/[locale]/boards/(content)/(home)/_definition.ts b/apps/nextjs/src/app/[locale]/boards/(content)/(home)/_definition.ts index 2357d7424..d64fdb56e 100644 --- a/apps/nextjs/src/app/[locale]/boards/(content)/(home)/_definition.ts +++ b/apps/nextjs/src/app/[locale]/boards/(content)/(home)/_definition.ts @@ -1,9 +1,9 @@ -import { api } from "@homarr/api/server"; +import { getHomeBoardAsync } from "@homarr/api/board-server"; import { createBoardContentPage } from "../_creator"; export default createBoardContentPage<{ locale: string }>({ async getInitialBoardAsync() { - return await api.board.getHomeBoard(); + return await getHomeBoardAsync(); }, }); diff --git a/apps/nextjs/src/app/[locale]/boards/(content)/[name]/(board)/_definition.tsx b/apps/nextjs/src/app/[locale]/boards/(content)/[name]/(board)/_definition.tsx index d3b65a5e9..f0924bb6e 100644 --- a/apps/nextjs/src/app/[locale]/boards/(content)/[name]/(board)/_definition.tsx +++ b/apps/nextjs/src/app/[locale]/boards/(content)/[name]/(board)/_definition.tsx @@ -1,9 +1,9 @@ -import { api } from "@homarr/api/server"; +import { getBoardByNameAsync } from "@homarr/api/board-server"; import { createBoardContentPage } from "../../_creator"; export default createBoardContentPage<{ locale: string; name: string }>({ async getInitialBoardAsync({ name }) { - return await api.board.getBoardByName({ name }); + return await getBoardByNameAsync(name); }, }); diff --git a/apps/nextjs/src/app/[locale]/boards/(content)/_board-add-menu.tsx b/apps/nextjs/src/app/[locale]/boards/(content)/_board-add-menu.tsx new file mode 100644 index 000000000..e49fefe5e --- /dev/null +++ b/apps/nextjs/src/app/[locale]/boards/(content)/_board-add-menu.tsx @@ -0,0 +1,84 @@ +"use client"; + +import { useCallback } from "react"; +import { Group, Menu } from "@mantine/core"; +import { IconBox, IconBoxAlignTop, IconChevronDown, IconPlug, IconPlus, IconResize } from "@tabler/icons-react"; + +import { useSession } from "@homarr/auth/client"; +import { useModalAction } from "@homarr/modals"; +import { AppSelectModal } from "@homarr/modals-collection"; +import { useI18n } from "@homarr/translation/client"; + +import { useItemActions } from "~/components/board/items/item-actions"; +import { ItemSelectModal } from "~/components/board/items/item-select-modal"; +import { useCategoryActions } from "~/components/board/sections/category/category-actions"; +import { CategoryEditModal } from "~/components/board/sections/category/category-edit-modal"; +import { useDynamicSectionActions } from "~/components/board/sections/dynamic/dynamic-actions"; +import { IntegrationSelectModal } from "~/components/integration/integration-select-modal"; +import { HeaderButton } from "~/components/layout/header/button"; + +export const BoardAddMenu = () => { + const { data: session } = useSession(); + const { openModal: openCategoryEditModal } = useModalAction(CategoryEditModal); + const { openModal: openItemSelectModal } = useModalAction(ItemSelectModal); + const { openModal: openAppSelectModal } = useModalAction(AppSelectModal); + const { openModal: openIntegrationSelectModal } = useModalAction(IntegrationSelectModal); + const { addCategoryToEnd } = useCategoryActions(); + const { addDynamicSection } = useDynamicSectionActions(); + const { createItem } = useItemActions(); + const t = useI18n(); + + const handleAddCategory = useCallback( + () => + openCategoryEditModal( + { + category: { id: "new", name: "" }, + onSuccess({ name }) { + addCategoryToEnd({ name }); + }, + submitLabel: t("section.category.create.submit"), + }, + { title: (translate) => translate("section.category.create.title") }, + ), + [addCategoryToEnd, openCategoryEditModal, t], + ); + + return ( + + + + + + + + + + + } onClick={() => openItemSelectModal()}> + {t("item.action.create")} + + } + onClick={() => + openAppSelectModal({ + onSelect: (app) => createItem({ kind: "app", options: { appId: app.id } }), + withCreate: session?.user.permissions.includes("app-create") ?? false, + }) + } + > + {t("app.action.add")} + + } onClick={() => openIntegrationSelectModal({})}> + {t("integration.action.create")} + + + } onClick={handleAddCategory}> + {t("section.category.action.create")} + + } onClick={addDynamicSection}> + {t("section.dynamic.action.create")} + + + + ); +}; diff --git a/apps/nextjs/src/app/[locale]/boards/(content)/_client.tsx b/apps/nextjs/src/app/[locale]/boards/(content)/_client.tsx index 0ba502a9a..1b4308d38 100644 --- a/apps/nextjs/src/app/[locale]/boards/(content)/_client.tsx +++ b/apps/nextjs/src/app/[locale]/boards/(content)/_client.tsx @@ -14,10 +14,10 @@ export const ClientBoard = () => { const fullWidthSortedSections = board.sections .filter((section) => section.kind === "empty" || section.kind === "category") - .sort((sectionA, sectionB) => sectionA.yOffset - sectionB.yOffset); + .toSorted((sectionA, sectionB) => sectionA.yOffset - sectionB.yOffset); return ( - + {fullWidthSortedSections.map((section) => diff --git a/apps/nextjs/src/app/[locale]/boards/(content)/_creator.tsx b/apps/nextjs/src/app/[locale]/boards/(content)/_creator.tsx index 16be5c478..2bb868f7d 100644 --- a/apps/nextjs/src/app/[locale]/boards/(content)/_creator.tsx +++ b/apps/nextjs/src/app/[locale]/boards/(content)/_creator.tsx @@ -1,15 +1,12 @@ import type { Metadata } from "next"; -import { Suspense } from "react"; +import { cache } from "react"; import { TRPCError } from "@trpc/server"; // Placed here because gridstack styles are used for board content import "~/styles/gridstack.scss"; import { dehydrate, HydrationBoundary } from "@tanstack/react-query"; -import type { PersistedClient } from "@tanstack/react-query-persist-client"; -import superjson from "superjson"; -import { queryCacheBuster } from "@homarr/api/query-cache"; -import { getQueryClient } from "@homarr/api/server"; +import { makeQueryClient } from "@homarr/api/shared"; import { IntegrationProvider } from "@homarr/auth/client"; import { auth } from "@homarr/auth/next"; import { getIntegrationsWithPermissionsAsync } from "@homarr/auth/server"; @@ -17,7 +14,6 @@ import { isNullOrWhitespace } from "@homarr/common"; import { createLogger } from "@homarr/core/infrastructure/logs"; import { ErrorWithMetadata } from "@homarr/core/infrastructure/logs/error"; import type { WidgetKind } from "@homarr/definitions"; -import { getQueryCacheAsync } from "@homarr/redis"; import { getI18n } from "@homarr/translation/server"; import { prefetchForKindAsync } from "@homarr/widgets/prefetch"; @@ -29,6 +25,7 @@ import { DynamicClientBoard } from "./_dynamic-client"; import { BoardContentHeaderActions } from "./_header-actions"; const logger = createLogger({ module: "createBoardContentPage" }); +const getQueryClient = cache(makeQueryClient); export type Params = Record; @@ -61,7 +58,6 @@ export const createBoardContentPage = >( } return acc; }, new Map()); - const [integrations] = await Promise.all([ getIntegrationsWithPermissionsAsync(session), ...Array.from(itemsMap).map(([kind, items]) => @@ -77,19 +73,12 @@ export const createBoardContentPage = >( ), ]); - const userId = session?.user.id ?? "anonymous"; - return ( - <> - - - - - - - - - + + + + + ); }, generateMetadataAsync: async ({ params }: { params: Promise }): Promise => { @@ -120,19 +109,3 @@ export const createBoardContentPage = >( }, }; }; - -async function QueryCacheHydration({ userId, boardId }: { userId: string; boardId: string }) { - try { - const serialized = await getQueryCacheAsync(userId, boardId); - if (!serialized) return null; - - const persisted = superjson.parse(serialized); - if (!persisted || persisted.buster !== queryCacheBuster) return null; - if (!persisted.clientState?.queries?.length) return null; - - return ; - } catch (error) { - logger.warn(new ErrorWithMetadata("Failed to hydrate query cache", { userId, boardId }, { cause: error })); - return null; - } -} diff --git a/apps/nextjs/src/app/[locale]/boards/(content)/_dynamic-client.tsx b/apps/nextjs/src/app/[locale]/boards/(content)/_dynamic-client.tsx index 50b0aff66..44d0a77c6 100644 --- a/apps/nextjs/src/app/[locale]/boards/(content)/_dynamic-client.tsx +++ b/apps/nextjs/src/app/[locale]/boards/(content)/_dynamic-client.tsx @@ -1,7 +1,24 @@ "use client"; import dynamic from "next/dynamic"; +import { SimpleGrid, Skeleton, Stack } from "@mantine/core"; + +const BoardLoadingShell = () => ( + + + {[2, 1, 2, 2, 1, 2].map((rows, index) => ( + + ))} + + +); export const DynamicClientBoard = dynamic(() => import("./_client").then((mod) => mod.ClientBoard), { ssr: false, + loading: BoardLoadingShell, }); diff --git a/apps/nextjs/src/app/[locale]/boards/(content)/_header-actions.tsx b/apps/nextjs/src/app/[locale]/boards/(content)/_header-actions.tsx index 30c91de40..6036a4905 100644 --- a/apps/nextjs/src/app/[locale]/boards/(content)/_header-actions.tsx +++ b/apps/nextjs/src/app/[locale]/boards/(content)/_header-actions.tsx @@ -1,45 +1,36 @@ "use client"; -import { useCallback, useEffect } from "react"; +import { useCallback, useEffect, useState } from "react"; +import dynamic from "next/dynamic"; import { useRouter } from "next/navigation"; -import { OnboardingTour } from "@gfazioli/mantine-onboarding-tour"; -import { Box, Group, Menu, ScrollArea } from "@mantine/core"; +import { Box, Center, Loader, Menu, ScrollArea } from "@mantine/core"; import { useHotkeys } from "@mantine/hooks"; -import { - IconBox, - IconBoxAlignTop, - IconChevronDown, - IconLayoutBoard, - IconPencil, - IconPencilOff, - IconPlug, - IconPlus, - IconReplace, - IconResize, - IconSettings, -} from "@tabler/icons-react"; +import { IconLayoutBoard, IconPencil, IconPencilOff, IconPlus, IconReplace, IconSettings } from "@tabler/icons-react"; import { clientApi } from "@homarr/api/client"; -import { useSession } from "@homarr/auth/client"; import { useRequiredBoard } from "@homarr/boards/context"; import { useEditMode } from "@homarr/boards/edit-mode"; import { revalidatePathActionAsync } from "@homarr/common/client"; import { env } from "@homarr/common/env"; import { hotkeys } from "@homarr/definitions"; -import { useConfirmModal, useModalAction } from "@homarr/modals"; -import { AppSelectModal } from "@homarr/modals-collection"; +import { useConfirmModal } from "@homarr/modals"; import { showErrorNotification, showSuccessNotification } from "@homarr/notifications"; import { useI18n, useScopedI18n } from "@homarr/translation/client"; import { Link } from "@homarr/ui"; -import { useItemActions } from "~/components/board/items/item-actions"; -import { ItemSelectModal } from "~/components/board/items/item-select-modal"; import { useBoardPermissions } from "~/components/board/permissions/client"; -import { useCategoryActions } from "~/components/board/sections/category/category-actions"; -import { CategoryEditModal } from "~/components/board/sections/category/category-edit-modal"; -import { useDynamicSectionActions } from "~/components/board/sections/dynamic/dynamic-actions"; -import { IntegrationSelectModal } from "~/components/integration/integration-select-modal"; import { HeaderButton } from "~/components/layout/header/button"; +import { TourTarget } from "~/components/layout/header/tour-target"; + +const loadBoardAddMenu = () => import("./_board-add-menu"); +const preloadBoardAddMenu = () => void loadBoardAddMenu().catch(() => undefined); +const BoardAddMenu = dynamic(() => loadBoardAddMenu().then(({ BoardAddMenu: AddMenu }) => AddMenu), { + loading: () => ( + + + + ), +}); export const BoardContentHeaderActions = ({ demoReadOnly }: { demoReadOnly: boolean }) => { const [isEditMode] = useEditMode(); @@ -52,16 +43,16 @@ export const BoardContentHeaderActions = ({ demoReadOnly }: { demoReadOnly: bool return ( <> - {isEditMode && } + {isEditMode && } {!demoReadOnly && ( - + - + )} @@ -69,94 +60,6 @@ export const BoardContentHeaderActions = ({ demoReadOnly }: { demoReadOnly: bool ); }; -const AddMenu = () => { - const { data: session } = useSession(); - const { openModal: openCategoryEditModal } = useModalAction(CategoryEditModal); - const { openModal: openItemSelectModal } = useModalAction(ItemSelectModal); - const { openModal: openAppSelectModal } = useModalAction(AppSelectModal); - const { openModal: openIntegrationSelectModal } = useModalAction(IntegrationSelectModal); - const { addCategoryToEnd } = useCategoryActions(); - const { addDynamicSection } = useDynamicSectionActions(); - const { createItem } = useItemActions(); - const t = useI18n(); - - const handleAddCategory = useCallback( - () => - openCategoryEditModal( - { - category: { - id: "new", - name: "", - }, - onSuccess({ name }) { - addCategoryToEnd({ name }); - }, - submitLabel: t("section.category.create.submit"), - }, - { - title: (t) => t("section.category.create.title"), - }, - ), - [addCategoryToEnd, openCategoryEditModal, t], - ); - - const handleSelectItem = useCallback(() => { - openItemSelectModal(); - }, [openItemSelectModal]); - - const handleSelectApp = useCallback(() => { - openAppSelectModal({ - onSelect: (app) => { - createItem({ - kind: "app", - options: { appId: app.id }, - }); - }, - withCreate: session?.user.permissions.includes("app-create") ?? false, - }); - }, [openAppSelectModal, createItem]); - - const handleAddIntegration = useCallback(() => { - openIntegrationSelectModal({}); - }, [openIntegrationSelectModal]); - - return ( - - - - - - - - - - - } onClick={handleSelectItem}> - {t("item.action.create")} - - - } onClick={handleSelectApp}> - {t("app.action.add")} - - - } onClick={handleAddIntegration}> - {t("integration.action.create")} - - - - - } onClick={handleAddCategory}> - {t("section.category.action.create")} - - - } onClick={addDynamicSection}> - {t("section.dynamic.action.create")} - - - - ); -}; - const EditModeMenu = ({ demoReadOnly }: { demoReadOnly: boolean }) => { const [isEditMode, { open, close }] = useEditMode(); const board = useRequiredBoard(); @@ -197,21 +100,29 @@ const EditModeMenu = ({ demoReadOnly }: { demoReadOnly: boolean }) => { usePreventLeaveWithDirty(isEditMode); return ( - - + + {isEditMode ? : } - + ); }; const SelectBoardsMenu = () => { - const { data: boards = [] } = clientApi.board.getAllBoards.useQuery(); + const [isOpen, setIsOpen] = useState(false); + const utils = clientApi.useUtils(); + const { data: boards = [], isPending } = clientApi.board.getAllBoards.useQuery(undefined, { enabled: isOpen }); + const preloadBoards = () => void utils.board.getAllBoards.prefetch(); return ( - - - + + + @@ -219,6 +130,11 @@ const SelectBoardsMenu = () => { + {isPending && ( +
+ +
+ )} {boards.map((board) => ( {
- +
); }; @@ -246,15 +162,13 @@ const usePreventLeaveWithDirty = (isDirty: boolean) => { useEffect(() => { if (!isDirty) return; - const handleClick = (event: Event) => { - const target = (event.target as HTMLElement).closest("a"); - - if (!target) { - console.warn("No anchor element found for click event", event); - return; - } + const handleClick = (event: MouseEvent) => { + if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return; + const target = event.target instanceof Element ? event.target.closest(anchorSelector) : null; + if (!target) return; event.preventDefault(); + event.stopPropagation(); openConfirmModal({ title: t("board.action.edit.confirmLeave.title"), @@ -280,19 +194,14 @@ const usePreventLeaveWithDirty = (isDirty: boolean) => { event.returnValue = true; }; - const anchors = document.querySelectorAll(anchorSelector); - anchors.forEach((link) => { - link.addEventListener("click", handleClick); - }); + document.addEventListener("click", handleClick, true); window.addEventListener("popstate", handlePopState); window.addEventListener("beforeunload", handleBeforeUnload); return () => { - anchors.forEach((link) => { - link.removeEventListener("click", handleClick); - }); + document.removeEventListener("click", handleClick, true); window.removeEventListener("popstate", handlePopState); window.removeEventListener("beforeunload", handleBeforeUnload); }; - }, [isDirty]); + }, [isDirty, openConfirmModal, router, t]); }; diff --git a/apps/nextjs/src/app/[locale]/boards/[name]/layout.tsx b/apps/nextjs/src/app/[locale]/boards/[name]/layout.tsx index 1f129e4c1..0c5fd10e0 100644 --- a/apps/nextjs/src/app/[locale]/boards/[name]/layout.tsx +++ b/apps/nextjs/src/app/[locale]/boards/[name]/layout.tsx @@ -1,4 +1,4 @@ -import { api } from "@homarr/api/server"; +import { getBoardByNameAsync } from "@homarr/api/board-server"; import { BoardOtherHeaderActions } from "../_header-actions"; import { createBoardLayout } from "../_layout-creator"; @@ -6,6 +6,6 @@ import { createBoardLayout } from "../_layout-creator"; export default createBoardLayout<{ locale: string; name: string }>({ headerActions: , async getInitialBoardAsync({ name }) { - return await api.board.getBoardByName({ name }); + return await getBoardByNameAsync(name); }, }); diff --git a/apps/nextjs/src/app/[locale]/boards/[name]/settings/_appereance.tsx b/apps/nextjs/src/app/[locale]/boards/[name]/settings/_appereance.tsx index 4af4af15f..b03168912 100644 --- a/apps/nextjs/src/app/[locale]/boards/[name]/settings/_appereance.tsx +++ b/apps/nextjs/src/app/[locale]/boards/[name]/settings/_appereance.tsx @@ -19,130 +19,106 @@ import { import { useDisclosure } from "@mantine/hooks"; import { IconX } from "@tabler/icons-react"; -import { useZodForm } from "@homarr/form"; +import type { UseFormReturnType } from "@homarr/form"; import { useI18n } from "@homarr/translation/client"; -import { boardSavePartialSettingsSchema } from "@homarr/validation/board"; -import type { Board } from "../../_types"; +import { SectionCard } from "~/components/manage/section-card"; import { generateColors } from "../../(content)/_theme"; -import { useSavePartialSettingsMutation } from "./_shared"; +import type { FormValues } from "./_settings-form"; interface Props { - board: Board; + form: UseFormReturnType; } const hexRegex = /^#[0-9a-fA-F]{6}$/; const progressPercentageLabel = (value: number) => `${value}%`; -export const ColorSettingsContent = ({ board }: Props) => { - const form = useZodForm(boardSavePartialSettingsSchema, { - initialValues: { - primaryColor: board.primaryColor, - secondaryColor: board.secondaryColor, - opacity: board.opacity, - iconColor: board.iconColor ?? "", - itemRadius: board.itemRadius, - }, - }); +export const ColorSettingsContent = ({ form }: Props) => { const [showPreview, { toggle }] = useDisclosure(false); const t = useI18n(); const theme = useMantineTheme(); - const { mutate: savePartialSettings, isPending } = useSavePartialSettingsMutation(board); return ( -
{ - savePartialSettings({ - id: board.id, - ...values, - }); - })} - > - - - - - color[6])} - {...form.getInputProps("primaryColor")} - /> - - - + + + + color[6])} - {...form.getInputProps("secondaryColor")} + {...form.getInputProps("primaryColor")} /> - - - {showPreview ? t("common.preview.hide") : t("common.preview.show")} - - - - - - - - - - - - - - - - - color[6])} - flex={1} - {...form.getInputProps("iconColor")} - /> - - - - - + + + ); }; diff --git a/apps/nextjs/src/app/[locale]/boards/[name]/settings/_background.tsx b/apps/nextjs/src/app/[locale]/boards/[name]/settings/_background.tsx index 7b105fe9c..8a796560f 100644 --- a/apps/nextjs/src/app/[locale]/boards/[name]/settings/_background.tsx +++ b/apps/nextjs/src/app/[locale]/boards/[name]/settings/_background.tsx @@ -1,41 +1,32 @@ "use client"; import { startTransition } from "react"; -import { ActionIcon, Autocomplete, Button, Center, Grid, Group, Popover, Stack, Text } from "@mantine/core"; +import { ActionIcon, Autocomplete, Center, Grid, Group, Popover, Stack, Text } from "@mantine/core"; import { useDebouncedValue } from "@mantine/hooks"; import { IconPhotoOff, IconUpload } from "@tabler/icons-react"; import { clientApi } from "@homarr/api/client"; import { useSession } from "@homarr/auth/client"; import { backgroundImageAttachments, backgroundImageRepeats, backgroundImageSizes } from "@homarr/definitions"; -import { useZodForm } from "@homarr/form"; +import type { UseFormReturnType } from "@homarr/form"; import { UploadMedia } from "@homarr/forms-collection"; import type { TranslationObject } from "@homarr/translation"; import { useI18n } from "@homarr/translation/client"; import type { SelectItemWithDescriptionBadge } from "@homarr/ui"; import { SelectWithDescriptionBadge } from "@homarr/ui"; -import { boardSavePartialSettingsSchema } from "@homarr/validation/board"; -import type { Board } from "../../_types"; -import { useSavePartialSettingsMutation } from "./_shared"; +import { SectionCard } from "~/components/manage/section-card"; +import type { FormValues } from "./_settings-form"; interface Props { - board: Board; + form: UseFormReturnType; } -export const BackgroundSettingsContent = ({ board }: Props) => { + +export const BackgroundSettingsContent = ({ form }: Props) => { const t = useI18n(); const { data: session } = useSession(); - const { mutate: savePartialSettings, isPending } = useSavePartialSettingsMutation(board); - const form = useZodForm(boardSavePartialSettingsSchema, { - initialValues: { - backgroundImageUrl: board.backgroundImageUrl ?? "", - backgroundImageAttachment: board.backgroundImageAttachment, - backgroundImageRepeat: board.backgroundImageRepeat, - backgroundImageSize: board.backgroundImageSize, - }, - }); - const [debouncedSearch] = useDebouncedValue(form.values.backgroundImageUrl, 200); + const [debouncedSearch] = useDebouncedValue(form.values.backgroundImageUrl ?? "", 200); const medias = clientApi.media.getPaginated.useQuery({ page: 1, pageSize: 10, @@ -53,121 +44,106 @@ export const BackgroundSettingsContent = ({ board }: Props) => { const backgroundImageRepeatData = useBackgroundOptionData("backgroundImageRepeat", backgroundImageRepeats); return ( - { - savePartialSettings({ - id: board.id, - ...values, - }); - })} - > - - - - - = 2 && ( - - -
- -
-
- - - -
- ) - } - // We filter it on the server - filter={({ options }) => options} - label={t("board.field.backgroundImageUrl.label")} - placeholder={`${t("board.field.backgroundImageUrl.placeholder")}...`} - renderOption={({ option }) => { - const current = imageMap.get(option.value); - if (!current) return null; + + + + + = 2 && ( + + +
+ +
+
+ + + +
+ ) + } + // We filter it on the server + filter={({ options }) => options} + label={t("board.field.backgroundImageUrl.label")} + placeholder={`${t("board.field.backgroundImageUrl.placeholder")}...`} + renderOption={({ option }) => { + const current = imageMap.get(option.value); + if (!current) return null; - return ( - - - - {current.name} - - {option.value} - - - - ); + return ( + + + + {current.name} + + {option.value} + + + + ); + }} + data={[ + { + group: t("board.field.backgroundImageUrl.group.your"), + items: images + .filter((media) => media.creatorId === session?.user.id) + .map((media) => `/api/user-medias/${media.id}`), + }, + { + group: t("board.field.backgroundImageUrl.group.other"), + items: images + .filter((media) => media.creatorId !== session?.user.id) + .map((media) => `/api/user-medias/${media.id}`), + }, + ]} + {...form.getInputProps("backgroundImageUrl")} + /> + {session?.user.permissions.includes("media-upload") && ( + { + const first = uploadedMedias.at(0); + if (!first) return; + + startTransition(() => { + form.setFieldValue("backgroundImageUrl", first.url); + }); }} - data={[ - { - group: t("board.field.backgroundImageUrl.group.your"), - items: images - .filter((media) => media.creatorId === session?.user.id) - .map((media) => `/api/user-medias/${media.id}`), - }, - { - group: t("board.field.backgroundImageUrl.group.other"), - items: images - .filter((media) => media.creatorId !== session?.user.id) - .map((media) => `/api/user-medias/${media.id}`), - }, - ]} - {...form.getInputProps("backgroundImageUrl")} - /> - {session?.user.permissions.includes("media-upload") && ( - { - const first = medias.at(0); - if (!first) return; - - startTransition(() => { - form.setFieldValue("backgroundImageUrl", first.url); - }); - }} - > - {({ onClick, loading }) => ( - - - - )} - - )} -
-
- - - - - - - - - -
- - - - -
- + > + {({ onClick, loading }) => ( + + + + )} + + )} + +
+ + + + + + + + + +
+ ); }; diff --git a/apps/nextjs/src/app/[locale]/boards/[name]/settings/_behavior.tsx b/apps/nextjs/src/app/[locale]/boards/[name]/settings/_behavior.tsx index 9eded5ec4..563fb97eb 100644 --- a/apps/nextjs/src/app/[locale]/boards/[name]/settings/_behavior.tsx +++ b/apps/nextjs/src/app/[locale]/boards/[name]/settings/_behavior.tsx @@ -1,48 +1,27 @@ "use client"; -import { Button, Group, Stack, Switch } from "@mantine/core"; +import { Switch } from "@mantine/core"; -import { useForm } from "@homarr/form"; +import type { UseFormReturnType } from "@homarr/form"; import { useI18n } from "@homarr/translation/client"; -import type { Board } from "../../_types"; -import { useSavePartialSettingsMutation } from "./_shared"; +import { SectionCard } from "~/components/manage/section-card"; +import type { FormValues } from "./_settings-form"; interface Props { - board: Board; + form: UseFormReturnType; } -export const BehaviorSettingsContent = ({ board }: Props) => { +export const BehaviorSettingsContent = ({ form }: Props) => { const t = useI18n(); - const { mutate: savePartialSettings, isPending } = useSavePartialSettingsMutation(board); - const form = useForm({ - initialValues: { - disableStatus: board.disableStatus, - }, - }); return ( -
{ - savePartialSettings({ - id: board.id, - ...values, - }); - })} - > - - - - - - - -
+ + + ); }; diff --git a/apps/nextjs/src/app/[locale]/boards/[name]/settings/_customCss.tsx b/apps/nextjs/src/app/[locale]/boards/[name]/settings/_customCss.tsx index e0d8ec565..e5df59a9f 100644 --- a/apps/nextjs/src/app/[locale]/boards/[name]/settings/_customCss.tsx +++ b/apps/nextjs/src/app/[locale]/boards/[name]/settings/_customCss.tsx @@ -1,6 +1,6 @@ "use client"; -import { Alert, Button, Group, Input, Stack } from "@mantine/core"; +import { Alert, Input } from "@mantine/core"; import { highlight, languages } from "prismjs"; import Editor from "react-simple-code-editor"; @@ -8,59 +8,39 @@ import "~/styles/prismjs.scss"; import { IconInfoCircle } from "@tabler/icons-react"; -import { useForm } from "@homarr/form"; +import type { UseFormReturnType } from "@homarr/form"; import { useI18n, useScopedI18n } from "@homarr/translation/client"; -import type { Board } from "../../_types"; -import { useSavePartialSettingsMutation } from "./_shared"; +import { SectionCard } from "~/components/manage/section-card"; +import type { FormValues } from "./_settings-form"; import classes from "./customcss.module.css"; interface Props { - board: Board; + form: UseFormReturnType; } -export const CustomCssSettingsContent = ({ board }: Props) => { +export const CustomCssSettingsContent = ({ form }: Props) => { const t = useI18n(); const customCssT = useScopedI18n("board.field.customCss"); - const { mutate: savePartialSettings, isPending } = useSavePartialSettingsMutation(board); - const form = useForm({ - initialValues: { - customCss: board.customCss ?? "", - }, - }); return ( -
{ - savePartialSettings({ - id: board.id, - ...values, - }); - })} - > - - + + - }> - {customCssT("customClassesAlert.description")} - - - - - - -
+ }> + {customCssT("customClassesAlert.description")} + + ); }; interface CustomCssInputProps { value?: string; onChange: (value: string) => void; + error?: React.ReactNode; } -const CustomCssInput = ({ value, onChange }: CustomCssInputProps) => { +const CustomCssInput = ({ value, onChange, error }: CustomCssInputProps) => { const customCssT = useScopedI18n("board.field.customCss"); return ( @@ -70,6 +50,7 @@ const CustomCssInput = ({ value, onChange }: CustomCssInputProps) => { htmlFor: "custom-css", }} description={customCssT("description")} + error={error} inputWrapperOrder={["label", "description", "input", "error"]} >
diff --git a/apps/nextjs/src/app/[locale]/boards/[name]/settings/_danger.tsx b/apps/nextjs/src/app/[locale]/boards/[name]/settings/_danger.tsx index 699da6003..92454f20c 100644 --- a/apps/nextjs/src/app/[locale]/boards/[name]/settings/_danger.tsx +++ b/apps/nextjs/src/app/[locale]/boards/[name]/settings/_danger.tsx @@ -2,7 +2,7 @@ import { useCallback } from "react"; import { useRouter } from "next/navigation"; -import { Button, Divider, Group, Stack, Text } from "@mantine/core"; +import { Button } from "@mantine/core"; import { clientApi } from "@homarr/api/client"; import { useRequiredBoard } from "@homarr/boards/context"; @@ -10,7 +10,7 @@ import { useConfirmModal, useModalAction } from "@homarr/modals"; import { useScopedI18n } from "@homarr/translation/client"; import { BoardRenameModal } from "~/components/board/modals/board-rename-modal"; -import classes from "./danger.module.css"; +import { DangerZoneItem, DangerZoneRoot } from "~/components/manage/danger-zone"; export const DangerZoneSettingsContent = ({ hideVisibility }: { hideVisibility: boolean }) => { const board = useRequiredBoard(); @@ -82,60 +82,36 @@ export const DangerZoneSettingsContent = ({ hideVisibility }: { hideVisibility: }, [board.id, deleteBoard, router, t, openConfirmModal]); return ( - - - + + {t("section.dangerZone.action.rename.button")} + + } /> - {hideVisibility ? null : ( - <> - - - + {!hideVisibility && ( + + {t(`section.dangerZone.action.visibility.button.${visibility}`)} + + } + /> )} - - + {t("section.dangerZone.action.delete.button")} + + } /> - - ); -}; - -interface DangerZoneRowProps { - label: string; - description: string; - buttonText: string; - isPending?: boolean; - onClick: () => void; -} - -const DangerZoneRow = ({ label, description, buttonText, onClick, isPending }: DangerZoneRowProps) => { - return ( - - - - {label} - - {description} - - - - - + ); }; diff --git a/apps/nextjs/src/app/[locale]/boards/[name]/settings/_general.tsx b/apps/nextjs/src/app/[locale]/boards/[name]/settings/_general.tsx index 0bfc79173..2fcb119a0 100644 --- a/apps/nextjs/src/app/[locale]/boards/[name]/settings/_general.tsx +++ b/apps/nextjs/src/app/[locale]/boards/[name]/settings/_general.tsx @@ -1,128 +1,66 @@ "use client"; -import { useEffect, useRef } from "react"; -import { Button, Grid, Group, Loader, Stack, TextInput } from "@mantine/core"; +import { useEffect } from "react"; +import { Grid, Loader, TextInput } from "@mantine/core"; import { useDebouncedValue, useDocumentTitle } from "@mantine/hooks"; import { useUpdateBoard } from "@homarr/boards/updater"; -import { useZodForm } from "@homarr/form"; +import type { UseFormReturnType } from "@homarr/form"; import { IconPicker } from "@homarr/forms-collection"; import { useI18n } from "@homarr/translation/client"; -import { boardSavePartialSettingsSchema } from "@homarr/validation/board"; -import { homarrLogoPath } from "~/components/layout/logo/homarr-logo"; +import { SectionCard } from "~/components/manage/section-card"; import { createMetaTitle } from "~/metadata"; import type { Board } from "../../_types"; -import { useSavePartialSettingsMutation } from "./_shared"; +import type { FormValues } from "./_settings-form"; interface Props { board: Board; + form: UseFormReturnType; } -export const GeneralSettingsContent = ({ board }: Props) => { +export const GeneralSettingsContent = ({ board, form }: Props) => { const t = useI18n(); - const ref = useRef({ - pageTitle: board.pageTitle, - logoImageUrl: board.logoImageUrl, - }); - const { updateBoard } = useUpdateBoard(); - - const { mutate: savePartialSettings, isPending } = useSavePartialSettingsMutation(board); - const form = useZodForm( - boardSavePartialSettingsSchema - .pick({ - pageTitle: true, - logoImageUrl: true, - metaTitle: true, - faviconImageUrl: true, - }) - .required(), - { - initialValues: { - pageTitle: board.pageTitle ?? "", - logoImageUrl: board.logoImageUrl ?? "", - metaTitle: board.metaTitle ?? "", - faviconImageUrl: board.faviconImageUrl ?? "", - }, - onValuesChange({ pageTitle }) { - updateBoard((previous) => ({ - ...previous, - pageTitle, - })); - }, - }, - ); useLogoPreview(form.values.logoImageUrl); const metaTitleStatus = useMetaTitlePreview(form.values.metaTitle); - // Cleanup for not applied changes of the page title and logo image URL - useEffect(() => { - return () => { - updateBoard((previous) => ({ - ...previous, - pageTitle: ref.current.pageTitle, - logoImageUrl: ref.current.logoImageUrl, - })); - }; - }, [updateBoard]); - return ( -
{ - // Save the current values to the ref so that it does not reset if the form is submitted - ref.current = { - pageTitle: values.pageTitle, - logoImageUrl: values.logoImageUrl, - }; - updateFavicon(values.faviconImageUrl ?? homarrLogoPath); - savePartialSettings({ - id: board.id, - ...values, - }); - })} - > - - - - - - - } - {...form.getInputProps("metaTitle")} - /> - - - - - - - - - - - - -
+ + + + + + + } + {...form.getInputProps("metaTitle")} + /> + + + + + + + + + ); }; @@ -146,14 +84,3 @@ const useMetaTitlePreview = (title: string | null) => { isPending: (title ?? "") !== metaTitleDebounced, }; }; - -// Previously we used the useFavicon hook from Mantine -// However if the user tried to click on a link to a different page -// it caused an error "Cannot read properties of null (reading 'removeChild')" -// Probably because the head element was null (https://github.com/mantinedev/mantine/blob/b90d9b81031f45f5d15e75f25138ed6477f65bce/packages/%40mantine/hooks/src/use-favicon/use-favicon.ts#L21) -// See https://github.com/homarr-labs/homarr/issues/4905 -const updateFavicon = (url: string) => { - const link: HTMLLinkElement | null = document.querySelector('link[rel="icon"]'); - if (!link) return; - link.href = url; -}; diff --git a/apps/nextjs/src/app/[locale]/boards/[name]/settings/_layout.tsx b/apps/nextjs/src/app/[locale]/boards/[name]/settings/_layout.tsx index 97a576a30..c592381ff 100644 --- a/apps/nextjs/src/app/[locale]/boards/[name]/settings/_layout.tsx +++ b/apps/nextjs/src/app/[locale]/boards/[name]/settings/_layout.tsx @@ -2,114 +2,79 @@ import { Button, Fieldset, Grid, Group, Input, NumberInput, Slider, Stack, Text, TextInput } from "@mantine/core"; -import { clientApi } from "@homarr/api/client"; import { createId } from "@homarr/common"; -import { useZodForm } from "@homarr/form"; +import type { UseFormReturnType } from "@homarr/form"; import { useI18n } from "@homarr/translation/client"; -import { boardSaveLayoutsSchema } from "@homarr/validation/board"; -import type { Board } from "../../_types"; +import { SectionCard } from "~/components/manage/section-card"; +import type { FormValues } from "./_settings-form"; interface Props { - board: Board; + form: UseFormReturnType; } -export const LayoutSettingsContent = ({ board }: Props) => { + +export const LayoutSettingsContent = ({ form }: Props) => { const t = useI18n(); - const utils = clientApi.useUtils(); - const { mutate: saveLayouts, isPending } = clientApi.board.saveLayouts.useMutation({ - onSettled() { - void utils.board.getBoardByName.invalidate({ name: board.name }); - void utils.board.getHomeBoard.invalidate(); - }, - }); - const form = useZodForm(boardSaveLayoutsSchema.omit({ id: true }).required(), { - initialValues: { - layouts: board.layouts, - }, - }); return ( -
{ - saveLayouts({ - id: board.id, - ...values, - }); - })} - > - - - - {t("board.setting.section.layout.responsive.title")} - - - - {form.values.layouts.map((layout, index) => ( -
- - - - - - - - - - - - - - - - {form.values.layouts.length >= 2 && ( - - - - )} -
- ))} -
- - - + + {form.values.layouts.map((layout, index) => ( +
+ + + + + + + + + + + + + + + + {form.values.layouts.length >= 2 && ( + + + + )} +
+ ))}
-
+ ); }; diff --git a/apps/nextjs/src/app/[locale]/boards/[name]/settings/_settings-form.tsx b/apps/nextjs/src/app/[locale]/boards/[name]/settings/_settings-form.tsx new file mode 100644 index 000000000..b8e66cf4b --- /dev/null +++ b/apps/nextjs/src/app/[locale]/boards/[name]/settings/_settings-form.tsx @@ -0,0 +1,219 @@ +"use client"; + +import { useEffect, useRef } from "react"; +import { Button, Stack } from "@mantine/core"; +import type { z } from "zod/v4"; + +import type { RouterOutputs } from "@homarr/api"; +import { useUpdateBoard } from "@homarr/boards/updater"; +import { revalidatePathActionAsync } from "@homarr/common/client"; +import { env } from "@homarr/common/env"; +import { useZodForm } from "@homarr/form"; +import { showErrorNotification, showSuccessNotification } from "@homarr/notifications"; +import { useI18n, useScopedI18n } from "@homarr/translation/client"; +import { boardSaveLayoutsSchema, boardSavePartialSettingsSchema } from "@homarr/validation/board"; + +import { homarrLogoPath } from "~/components/layout/logo/homarr-logo"; +import { SectionCard } from "~/components/manage/section-card"; +import { UnsavedChangesBar } from "~/components/manage/unsaved-changes-bar"; + +import type { Board } from "../../_types"; +import { ColorSettingsContent } from "./_appereance"; +import { BackgroundSettingsContent } from "./_background"; +import { BehaviorSettingsContent } from "./_behavior"; +import { BoardAccessSettings } from "./_board-access"; +import { CustomCssSettingsContent } from "./_customCss"; +import { DangerZoneSettingsContent } from "./_danger"; +import { GeneralSettingsContent } from "./_general"; +import { LayoutSettingsContent } from "./_layout"; +import { useSaveLayoutsMutation, useSavePartialSettingsMutation } from "./_shared"; + +const boardSettingsFormSchema = boardSavePartialSettingsSchema + .extend({ + layouts: boardSaveLayoutsSchema.shape.layouts, + }) + .required(); + +export type FormValues = z.infer; + +const PARTIAL_FORM_KEYS = [ + "pageTitle", + "metaTitle", + "logoImageUrl", + "faviconImageUrl", + "backgroundImageUrl", + "backgroundImageAttachment", + "backgroundImageRepeat", + "backgroundImageSize", + "primaryColor", + "secondaryColor", + "opacity", + "iconColor", + "itemRadius", + "customCss", + "disableStatus", +] as const; + +const buildInitialValues = (board: Board): FormValues => ({ + pageTitle: board.pageTitle ?? "", + metaTitle: board.metaTitle ?? "", + logoImageUrl: board.logoImageUrl ?? "", + faviconImageUrl: board.faviconImageUrl ?? "", + backgroundImageUrl: board.backgroundImageUrl ?? "", + backgroundImageAttachment: board.backgroundImageAttachment, + backgroundImageRepeat: board.backgroundImageRepeat, + backgroundImageSize: board.backgroundImageSize, + primaryColor: board.primaryColor, + secondaryColor: board.secondaryColor, + opacity: board.opacity, + iconColor: board.iconColor ?? "", + itemRadius: board.itemRadius, + customCss: board.customCss ?? "", + disableStatus: board.disableStatus, + layouts: board.layouts, +}); + +interface BoardSettingsFormProps { + board: Board; + permissions: RouterOutputs["board"]["getBoardPermissions"]; + hasFullAccess: boolean; + hideVisibility: boolean; +} + +export const BoardSettingsForm = ({ board, permissions, hasFullAccess, hideVisibility }: BoardSettingsFormProps) => { + const t = useI18n(); + const tSection = useScopedI18n("board.setting.section"); + const { updateBoard } = useUpdateBoard(); + const savePartialSettings = useSavePartialSettingsMutation(board); + const saveLayouts = useSaveLayoutsMutation(board); + + const form = useZodForm(boardSettingsFormSchema, { + initialValues: buildInitialValues(board), + onValuesChange({ pageTitle }) { + updateBoard((previous) => ({ + ...previous, + pageTitle, + })); + }, + }); + + const initialValuesRef = useRef(buildInitialValues(board)); + const lastSavedRef = useRef({ pageTitle: board.pageTitle, logoImageUrl: board.logoImageUrl }); + + const isDirtyRef = useRef(false); + isDirtyRef.current = form.isDirty(); + + useEffect(() => { + return () => { + updateBoard((previous) => ({ + ...previous, + pageTitle: lastSavedRef.current.pageTitle, + logoImageUrl: lastSavedRef.current.logoImageUrl, + })); + }; + }, [updateBoard]); + + useEffect(() => { + const handler = (event: BeforeUnloadEvent) => { + if (env.NODE_ENV === "development") return; + if (isDirtyRef.current) event.preventDefault(); + }; + window.addEventListener("beforeunload", handler); + return () => window.removeEventListener("beforeunload", handler); + }, []); + + const handleSubmitAsync = async (values: FormValues) => { + const defaults = initialValuesRef.current; + const changed = (...fields: TKey[]) => + fields.some((field) => values[field] !== defaults[field]); + + const { layouts, ...partialSettings } = values; + + const saveActions: { when: boolean; action: () => Promise }[] = [ + { + when: changed(...PARTIAL_FORM_KEYS), + action: () => + savePartialSettings.mutateAsync({ id: board.id, ...partialSettings }).then(() => { + updateFavicon(values.faviconImageUrl ?? homarrLogoPath); + }), + }, + { + when: changed("layouts"), + action: () => saveLayouts.mutateAsync({ id: board.id, layouts }), + }, + ]; + + const promises = saveActions.filter((saveAction) => saveAction.when).map((saveAction) => saveAction.action()); + if (promises.length === 0) return; + + try { + await Promise.all(promises); + lastSavedRef.current = { pageTitle: values.pageTitle, logoImageUrl: values.logoImageUrl }; + initialValuesRef.current = values; + form.setInitialValues(values); + form.resetDirty(); + await revalidatePathActionAsync(`/boards/${board.name}/settings`); + showSuccessNotification({ + title: t("common.notification.update.success"), + message: t("common.notification.update.success"), + }); + } catch { + showErrorNotification({ + title: t("common.notification.update.error"), + message: t("common.notification.update.error"), + }); + } + }; + + const handleDiscard = () => { + form.setValues(initialValuesRef.current); + form.resetDirty(); + updateBoard((previous) => ({ + ...previous, + pageTitle: lastSavedRef.current.pageTitle, + logoImageUrl: lastSavedRef.current.logoImageUrl, + })); + }; + + const isPending = savePartialSettings.isPending || saveLayouts.isPending; + + return ( +
void handleSubmitAsync(values))}> + + + + + + + + + {hasFullAccess && ( + + + + )} + + {hasFullAccess && } + + {form.isDirty() && ( + + + + + )} + +
+ ); +}; + +// Previously part of the general settings section; applied on the unified save +// https://github.com/homarr-labs/homarr/issues/4905 +const updateFavicon = (url: string) => { + const link = document.querySelector('link[rel="icon"]'); + if (!link) return; + link.href = url; +}; diff --git a/apps/nextjs/src/app/[locale]/boards/[name]/settings/_shared.tsx b/apps/nextjs/src/app/[locale]/boards/[name]/settings/_shared.tsx index 9fa888be2..d0fedf522 100644 --- a/apps/nextjs/src/app/[locale]/boards/[name]/settings/_shared.tsx +++ b/apps/nextjs/src/app/[locale]/boards/[name]/settings/_shared.tsx @@ -11,3 +11,13 @@ export const useSavePartialSettingsMutation = (board: Board) => { }, }); }; + +export const useSaveLayoutsMutation = (board: Board) => { + const utils = clientApi.useUtils(); + return clientApi.board.saveLayouts.useMutation({ + onSettled() { + void utils.board.getBoardByName.invalidate({ name: board.name }); + void utils.board.getHomeBoard.invalidate(); + }, + }); +}; diff --git a/apps/nextjs/src/app/[locale]/boards/[name]/settings/danger.module.css b/apps/nextjs/src/app/[locale]/boards/[name]/settings/danger.module.css deleted file mode 100644 index 39a60b735..000000000 --- a/apps/nextjs/src/app/[locale]/boards/[name]/settings/danger.module.css +++ /dev/null @@ -1,5 +0,0 @@ -@media (min-width: 36em) { - .dangerZoneGroup { - --group-wrap: nowrap !important; - } -} diff --git a/apps/nextjs/src/app/[locale]/boards/[name]/settings/page.tsx b/apps/nextjs/src/app/[locale]/boards/[name]/settings/page.tsx index a728e8949..318d5196a 100644 --- a/apps/nextjs/src/app/[locale]/boards/[name]/settings/page.tsx +++ b/apps/nextjs/src/app/[locale]/boards/[name]/settings/page.tsx @@ -1,44 +1,20 @@ -import type { PropsWithChildren } from "react"; import { notFound } from "next/navigation"; -import { AccordionControl, AccordionItem, AccordionPanel, Container, Stack, Text, Title } from "@mantine/core"; -import { - IconAlertTriangle, - IconBrush, - IconClick, - IconFileTypeCss, - IconLayout, - IconPhoto, - IconSettings, - IconUser, -} from "@tabler/icons-react"; +import { Container, Stack, Title } from "@mantine/core"; import { TRPCError } from "@trpc/server"; import { api } from "@homarr/api/server"; import { capitalize } from "@homarr/common"; import { db } from "@homarr/db"; import { getServerSettingByKeyAsync } from "@homarr/db/queries"; -import type { TranslationObject } from "@homarr/translation"; import { getScopedI18n } from "@homarr/translation/server"; -import type { TablerIcon } from "@homarr/ui"; import { getBoardPermissionsAsync } from "~/components/board/permissions/server"; -import { ActiveTabAccordion } from "../../../../../components/active-tab-accordion"; -import { ColorSettingsContent } from "./_appereance"; -import { BackgroundSettingsContent } from "./_background"; -import { BehaviorSettingsContent } from "./_behavior"; -import { BoardAccessSettings } from "./_board-access"; -import { CustomCssSettingsContent } from "./_customCss"; -import { DangerZoneSettingsContent } from "./_danger"; -import { GeneralSettingsContent } from "./_general"; -import { LayoutSettingsContent } from "./_layout"; +import { BoardSettingsForm } from "./_settings-form"; interface Props { params: Promise<{ name: string; }>; - searchParams: Promise<{ - tab?: keyof TranslationObject["board"]["setting"]["section"]; - }>; } const getBoardAndPermissionsAsync = async (params: Awaited) => { @@ -57,11 +33,7 @@ const getBoardAndPermissionsAsync = async (params: Awaited) => } catch (error) { // Ignore not found errors and redirect to 404 // error is already logged in _layout-creator.tsx - if (error instanceof TRPCError && error.code === "NOT_FOUND") { - notFound(); - } - - if (error instanceof TRPCError && error.code === "BAD_REQUEST") { + if (error instanceof TRPCError && (error.code === "NOT_FOUND" || error.code === "BAD_REQUEST")) { notFound(); } @@ -70,7 +42,6 @@ const getBoardAndPermissionsAsync = async (params: Awaited) => }; export default async function BoardSettingsPage(props: Props) { - const searchParams = await props.searchParams; const params = await props.params; const { board, permissions } = await getBoardAndPermissionsAsync(params); const boardSettings = await getServerSettingByKeyAsync(db, "board"); @@ -85,76 +56,13 @@ export default async function BoardSettingsPage(props: Props) { {t("title", { boardName: capitalize(board.name) })} - - - - - - - - - - - - - - - - - - - - {hasFullAccess && ( - <> - - - - - - - - )} - + ); } - -type AccordionItemForProps = PropsWithChildren<{ - value: keyof TranslationObject["board"]["setting"]["section"]; - icon: TablerIcon; - danger?: boolean; - noPadding?: boolean; -}>; - -const AccordionItemFor = async ({ value, children, icon: Icon, danger, noPadding }: AccordionItemForProps) => { - const t = await getScopedI18n("board.setting.section"); - return ( - - }> - - {t(`${value}.title`)} - - - - {children} - - - ); -}; diff --git a/apps/nextjs/src/app/[locale]/boards/_layout-creator.tsx b/apps/nextjs/src/app/[locale]/boards/_layout-creator.tsx index 3cddc6685..24ebe3d03 100644 --- a/apps/nextjs/src/app/[locale]/boards/_layout-creator.tsx +++ b/apps/nextjs/src/app/[locale]/boards/_layout-creator.tsx @@ -3,6 +3,7 @@ import { notFound, redirect } from "next/navigation"; import { AppShellMain } from "@mantine/core"; import { TRPCError } from "@trpc/server"; +import { getRscUserSettingsAsync } from "@homarr/api/user-server"; import { auth } from "@homarr/auth/next"; import { BoardProvider } from "@homarr/boards/context"; import { EditModeProvider } from "@homarr/boards/edit-mode"; @@ -11,7 +12,8 @@ import { createLogger } from "@homarr/core/infrastructure/logs"; import { MainHeader } from "~/components/layout/header"; import { BoardLogoWithTitle } from "~/components/layout/logo/board-logo"; import { ClientShell } from "~/components/layout/shell"; -import { BoardTourProvider } from "~/components/onboarding/board-tour"; +import { BoardTourGate } from "~/components/onboarding/board-tour-gate"; +import { env } from "~/env"; import { getCurrentColorSchemeAsync } from "~/theme/color-scheme"; import type { Board } from "./_types"; import type { Params } from "./(content)/_creator"; @@ -21,11 +23,6 @@ import { BoardMantineProvider } from "./(content)/_theme"; const logger = createLogger({ module: "createBoardLayout" }); -const BoardTourWrapper = ({ hasSession, children }: PropsWithChildren<{ hasSession: boolean }>) => { - if (!hasSession) return <>{children}; - return {children}; -}; - interface CreateBoardLayoutProps { headerActions: JSX.Element; getInitialBoardAsync: (params: TParams) => Promise; @@ -43,8 +40,32 @@ export const createBoardLayout = ({ }: PropsWithChildren<{ params: Promise; }>) => { - const session = await auth(); - const initialBoard = await getInitialBoard(await params).catch((error) => { + const resolvedParams = await params; + const sessionPromise = auth(); + const initialBoardPromise = getInitialBoard(resolvedParams).then( + (board) => ({ status: "fulfilled", board }) as const, + (error: unknown) => ({ status: "rejected", error }) as const, + ); + const colorSchemePromise = getCurrentColorSchemeAsync(); + const shouldRunBoardTourPromise = sessionPromise.then(async (session) => { + if (!withTour || !session || env.DEMO_MODE) return false; + + try { + const user = await getRscUserSettingsAsync(session.user.id); + return user !== undefined && !user.completedBoardTour; + } catch (error) { + logger.error(new Error("Failed to load the board tour status", { cause: error })); + return false; + } + }); + const [session, initialBoardResult, colorScheme, shouldRunBoardTour] = await Promise.all([ + sessionPromise, + initialBoardPromise, + colorSchemePromise, + shouldRunBoardTourPromise, + ]); + if (initialBoardResult.status === "rejected") { + const { error } = initialBoardResult; if (error instanceof TRPCError && error.code === "NOT_FOUND") { if (!session) { logger.debug("No home board found for anonymous user, redirecting to login"); @@ -60,8 +81,8 @@ export const createBoardLayout = ({ } throw error; - }); - const colorScheme = await getCurrentColorSchemeAsync(); + } + const initialBoard = initialBoardResult.board; return ( @@ -69,7 +90,7 @@ export const createBoardLayout = ({ - + } @@ -78,7 +99,7 @@ export const createBoardLayout = ({ /> {children} - + diff --git a/apps/nextjs/src/app/[locale]/init/page.tsx b/apps/nextjs/src/app/[locale]/init/page.tsx index 212c74e73..0013c3170 100644 --- a/apps/nextjs/src/app/[locale]/init/page.tsx +++ b/apps/nextjs/src/app/[locale]/init/page.tsx @@ -1,8 +1,8 @@ import type { JSX } from "react"; import { Box, Center, Stack, Text, Title } from "@mantine/core"; -import { api } from "@homarr/api/server"; import type { MaybePromise } from "@homarr/common/types"; +import { db } from "@homarr/db"; import type { OnboardingStep } from "@homarr/definitions"; import { getScopedI18n } from "@homarr/translation/server"; @@ -29,9 +29,16 @@ const stepComponents: Record MaybePromise { + const value = await db.query.onboarding.findFirst(); + if (!value) return { current: "start" as const, previous: null }; + + return { current: value.step, previous: value.previousStep }; +}; + export default async function InitPage() { const t = await getScopedI18n("init.step"); - const currentStep = await api.onboard.currentStep(); + const currentStep = await getCurrentOnboardingStepAsync(); const CurrentComponent = stepComponents[currentStep.current]; diff --git a/apps/nextjs/src/app/[locale]/layout.tsx b/apps/nextjs/src/app/[locale]/layout.tsx index 2388e2812..ea62beadf 100644 --- a/apps/nextjs/src/app/[locale]/layout.tsx +++ b/apps/nextjs/src/app/[locale]/layout.tsx @@ -13,11 +13,11 @@ import { notFound } from "next/navigation"; import type { DayOfWeek } from "@mantine/dates"; import { NextIntlClientProvider } from "next-intl"; -import { api } from "@homarr/api/server"; +import { getRscServerSettingsAsync } from "@homarr/api/server-settings-server"; +import { getRscUserSettingsAsync } from "@homarr/api/user-server"; import { env } from "@homarr/auth/env"; import { auth } from "@homarr/auth/next"; -import { db } from "@homarr/db"; -import { getServerSettingsAsync } from "@homarr/db/queries"; +import { createLogger } from "@homarr/core/infrastructure/logs"; import { ModalProvider } from "@homarr/modals"; import { Notifications } from "@homarr/notifications"; import { SettingsProvider } from "@homarr/settings"; @@ -43,6 +43,8 @@ const fontSans = Inter({ variable: "--font-sans", }); +const logger = createLogger({ module: "rootLayout" }); + // eslint-disable-next-line no-restricted-syntax export const generateMetadata = async (): Promise => ({ title: "Homarr", @@ -78,15 +80,27 @@ export default async function Layout(props: { children: React.ReactNode; params: Promise<{ locale: SupportedLanguage }>; }) { - if (!isLocaleSupported((await props.params).locale)) { + const { locale } = await props.params; + if (!isLocaleSupported(locale)) { notFound(); } - const session = await auth(); - const user = session ? await api.user.getById({ userId: session.user.id }).catch(() => null) : null; - const serverSettings = await getServerSettingsAsync(db); - const colorScheme = await getCurrentColorSchemeAsync(); - const direction = isLocaleRTL((await props.params).locale) ? "rtl" : "ltr"; + const sessionPromise = auth(); + const userPromise = sessionPromise.then((session) => + session + ? getRscUserSettingsAsync(session.user.id).catch((error: unknown) => { + logger.error(new Error("Failed to load the authenticated user in the root layout", { cause: error })); + return null; + }) + : null, + ); + const [session, user, serverSettings, colorScheme] = await Promise.all([ + sessionPromise, + userPromise, + getRscServerSettingsAsync(), + getCurrentColorSchemeAsync(), + ]); + const direction = isLocaleRTL(locale) ? "rtl" : "ltr"; const StackedProvider = composeWrappers([ (innerProps) => { @@ -125,8 +139,6 @@ export default async function Layout(props: { (innerProps) => , ]); - const { locale } = await props.params; - return ( // Instead of ColorSchemScript we use data-mantine-color-scheme to prevent flickering