Compare commits

..
Author SHA1 Message Date
ajnart fbde111f01 fix: avoid ESM lexer imports in migration bundles 2026-09-12 23:56:54 +02:00
ajnart a6bdbbb4ea feat: add custom widget flow workbench 2026-09-12 22:51:46 +02:00
Thomas c32a5317ca fix: remove apps multi-select toggle (#6834) 2026-09-12 16:34:03 +02:00
Thomas f18033ddaa fix: sync dev fixes into v2 and improve regression reports (#6821)
Co-authored-by: Homarr Update Contributors <210161987+homarr-update-contributors[bot]@users.noreply.github.com>
Co-authored-by: Crowdin Homarr <190541745+homarr-crowdin[bot]@users.noreply.github.com>
Co-authored-by: Releases Homarr <175486441+homarr-releases[bot]@users.noreply.github.com>
Co-authored-by: Thomas <thomas@ajnart.fr>
Co-authored-by: homarr-releases[bot] <175486441+homarr-releases[bot]@users.noreply.github.com>
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: homarr-update-contributors[bot] <210161987+homarr-update-contributors[bot]@users.noreply.github.com>
Co-authored-by: homarr-crowdin[bot] <190541745+homarr-crowdin[bot]@users.noreply.github.com>
Co-authored-by: Afonso Jorge Ramos <afonsojorgeramos@gmail.com>
Co-authored-by: Danura30082 <danura30082+github@gmail.com>
Co-authored-by: Kushie <122986913+kushiemoon-dev@users.noreply.github.com>
Closes #6604
2026-09-12 15:31:04 +02:00
Thomas ff2b589380 fix(board): refine container spacing and collapse layout (#6833) 2026-09-12 15:23:50 +02:00
Thomas 9bc3802b3b fix(wud): authenticate HTTP requests and validate container access (#6831) 2026-09-12 10:57:36 +02:00
Thomas 2049c6ade0 fix: tighten v2 setup and release safeguards (#6824) 2026-09-12 10:47:35 +02:00
ajnart e21a0bb6da fix: refresh OpenAPI widget kinds 2026-09-12 10:46:39 +02:00
Thomas 61f22c8e64 fix: show board removal confirmation in a dialog (#6829) 2026-09-12 10:36:36 +02:00
604 changed files with 43290 additions and 49520 deletions

No files matched your search

+1 -1
View File
@@ -37,4 +37,4 @@ Orient from the current checkout before editing. Treat package manifests, export
- Cron jobs: `packages/cron-jobs/src/jobs/`
- App routes: `apps/nextjs/src/app/[locale]/`
When a code change affects users, invoke `documentation-sync`. When exposing tRPC through MCP, invoke `mcp-integration`.
Invoke `documentation-sync` when hidden capabilities or information not evident to an advanced user change, or existing guidance becomes inaccurate; follow the Documentation Sync criteria in `AGENTS.md`. When exposing tRPC through MCP, invoke `mcp-integration`.
+9 -5
View File
@@ -1,13 +1,17 @@
---
name: documentation-sync
description: Keep Homarr's Docusaurus documentation aligned with user-facing code. Use when adding or changing integrations, widgets, APIs, environment variables, CLI commands, authentication, permissions, cron jobs, settings, or UI behavior that users must understand.
description: Write concise Homarr docs for advanced users, covering only hidden capabilities and information not evident from the UI. Use when that information changes or existing guidance becomes inaccurate; skip obvious controls and routine fixes.
---
# Documentation Sync
Update `apps/docs/` in the same change as user-facing behavior. Inspect adjacent pages and the docs types before copying a pattern; the source and docs evolve together.
Apply the audience and scope rules in `AGENTS.md` first. Before adding a passage, identify what an advanced user could not learn directly from the interface. If there is no such information, omit it.
## Map the change
For hidden capabilities such as the advanced widget feature, explain discovery, activation, and non-obvious behavior. For visible standard controls such as Delete, omit narration of what the label already conveys. Use the shortest explanation that preserves necessary technical detail; remove redundant prose in the passage being edited.
When an update is warranted, inspect adjacent pages for structure and types, not as a verbosity target. The mappings below locate needed information; they do not require a page for every feature or code change.
## Locate a needed update
| Code change | Documentation target |
| ----------------------------------- | -------------------------------------------------------------------- |
@@ -40,11 +44,11 @@ For a widget:
- Add or update `apps/docs/docs/widgets/<slug>/index.ts` with the local `WidgetDefinition` pattern.
- Add or update `index.mdx` with the established `WidgetHeader`, `WidgetConfig`, and `AddingWidget` components as applicable.
- Document options, required integrations, permissions, empty states, and changed behavior that affect setup or use.
- Explain only non-obvious option semantics, integration prerequisites, permission constraints, or behavior that the interface does not make clear.
## Completion criteria
1. Describe the shipped behavior, not an implementation plan.
1. Every passage adds information an advanced user cannot reasonably infer from the interface. Remove obvious, repetitive, or unnecessary prose.
2. Keep names, defaults, paths, screenshots, links, and prerequisites consistent with code.
3. Update every affected page and remove superseded guidance.
4. Run the narrowest useful docs validation. Use `pnpm turbo build --filter=@homarr/docs` when links, MDX, generated definitions, or navigation can fail; otherwise run the docs package formatter on touched files.
+7 -11
View File
@@ -1,20 +1,20 @@
---
name: homarr-custom-widget
description: Author, validate, preview, test, install, or configure static or API-backed Homarr Custom JSX v2 widgets.
description: Author, validate, preview, install, or configure Homarr Custom JSX v2/v3 widgets, including static and native integration widgets.
---
# Homarr Custom Widget
Author one widget or a coordinated set. Load release-matched context on demand. Run lifecycle tools alone; independent reads may run together. Finish each widget's validation, evidence, and persistence before the next.
Load release-matched context. Run lifecycle tools alone; independent reads may run together. For a set, research once, then validate, preview, and persist each widget before the next.
1. For connected widgets, read primary API documentation; use web search when it is missing or may have changed.
2. Create credential-free definitions with keyed `sources`, `requests`, optional `options`, and safe JSX `template`. Static widgets use empty `sources` and `requests`; an API is optional.
1. For HTTP widgets, read primary API documentation. For native capabilities, discover installed schemas. Static widgets need no service.
2. Create credential-free definitions with keyed `sources`, `requests`, optional `options`, and safe JSX `template`.
3. While drafting, use `customWidget_validateTemplate` for focused JSX diagnostics without resending the manifest.
4. Send the definition once to `customWidget_previewCreate` and test its queries/actions. For a JSX-only fix, validate, call `customWidget_previewReviseTemplate` with its session, and retest; it inherits the manifest and resets evidence. Create a preview only for source/request/option changes.
4. Send the definition once to `customWidget_previewCreate` and test its HTTP/native queries and simulated actions. For a JSX-only fix, validate, call `customWidget_previewReviseTemplate` with its session, and retest; it inherits the manifest and resets evidence. Other definition changes require a fresh preview.
5. Configure deployment-specific source URLs and credentials through Homarr; never repeat plaintext.
6. Persist each exact final tested preview with `customWidget_createFromPreview`. Do not resend a large definition through `customWidget_create` when a preview session is available.
Use supplied samples or preview responses as the data contract. Render requested fields and all returned items; guard optional nested values. Humanize numeric enums with label arrays, omit absent numbers, and label timestamp timezones. Give load errors and empty states a refresh or retry path.
Treat sample and preview responses as binding contracts. Render requested fields, guard optional values, humanize enums, and label timezones. Give errors and empty states a retry path.
Use `{option:name}` or `$option` for saved options. Use `{param:name}` or `$param` for values supplied by `SubFetch`, `ActionButton`, or `ToggleSwitch`. Load queries cannot use invocation parameters. Render load queries from `data` and `status` with `RefreshButton`; reserve `SubFetch` for manual parameterized queries. Templates read `data`, `status`, `options`, and temporary `inputs`.
@@ -24,11 +24,7 @@ For a bound control that depends on another input, declare its default and set `
Plan capabilities. Use one `customWidget_findComponents` search per job. Batch selected non-obvious binding or interaction documentation with `customWidget_getComponents`; reserve `customWidget_getComponent` for one unknown-prop repair. Failed validation reopens discovery; otherwise search only for a missing capability. The full catalog is for broad exploration; load at most one example. Context never limits composition. Prefer clear hierarchy, responsive grids, divided lists, and aligned actions over nested row cards.
Do not simplify a useful workflow merely because the template is interpreted. Freely compose any supported installed components with multiple sources, requests, options, `choicesFrom`, bound filters, charts, responsive detail areas, manual queries, and safe actions when they improve the user's job. Complexity must remain purposeful rather than decorative.
Use divided lists or responsive media grids, one primary metric/action, compact headers, quiet metadata, and one badge. Full-width artwork wraps at base and caps above xs.
Make initial states actionable and wrap variable labels/values on narrow tiles. Do not use an unlabeled decorative icon as an empty state.
Compose installed components freely around the requested workflow. Use responsive layouts, clear hierarchy, quiet metadata, and actionable initial states. Wrap variable labels on narrow tiles and label interactive icons.
Do not use imports, hooks, refs, raw HTML, raw event callbacks, browser requests, arbitrary functions, eval, bigint, npm packages, authored statement blocks, IIFEs, or recursion. Do not pretend MCP tools exist in an offline chat session.
@@ -12,7 +12,7 @@ Templates read `data.requestId`, `status.requestId`, `options.name`, and tempora
</SubFetch>
```
Manual queries require `trigger: "manual"` on request and `SubFetch`; otherwise they run automatically. `triggerContent` with `triggerAriaLabel` makes custom content the launcher. `SubFetch` owns loading/error/retry; its child receives success plus `{ ok, status, statusText, loading: false }`. Never author `onClick` or fetch callbacks.
Manual queries require `trigger: "manual"` on request and `SubFetch`. Use `triggerContent` and `triggerAriaLabel` for a custom launcher. `SubFetch` owns loading/error/retry; its child receives success plus `{ ok, status, statusText, loading: false }`.
`SubFetch`, `ActionButton`, and `ToggleSwitch` need literal `requestId`; validation rejects missing/computed IDs.
@@ -35,3 +35,5 @@ Every stateful control must use `bind`, and its `inputs.<name>` value must feed
Callback parameters must not shadow the reserved roots `data`, `status`, `options`, or `inputs`. Use `<Icon name="refresh" />` or `<TablerIcon name="refresh" />`; never invent components such as `<IconFoo />`.
Use expression callbacks for supported collections and trusted slots. No callback blocks, IIFEs, authored recursion, or raw events. Regex is limited to safe string operations.
V3 adds scoped `className` styles, `View` fragments, `WidgetModal`, `WidgetDrawer`, and `AppEmbed`. Bound controls use `persist` for declared browser preferences or `content` for shared drafts saved with `ContentSaveButton`. `NativeQuery` and `NativeActionButton` invoke declared native IDs; actions retain preview simulation and integration permissions. Fetch component contracts before using these helpers.
@@ -13,7 +13,7 @@ interface HomarrCustomWidgetV2 {
}
```
Static widgets use empty `sources` and `requests`. Each request must resolve to a defined source; omitting `source` uses `default` only when that ID exists. Source properties are `name?`, `baseUrl`, `networkScope`, and `auth?`:
Sources are keyed by ID. Empty `sources` and `requests` support static widgets. Each HTTP request must reference an existing source; omitting its source selects `default`. Source properties are `name?`, `baseUrl`, `networkScope`, and `auth?`:
```json
{
@@ -47,3 +47,5 @@ Use stable real URLs for public APIs and clear suggested URLs for self-hosted se
Paths use `{option:name}` and `{param:name}`; query/body references use `{ "$option": "name" }` and `{ "$param": "name" }`. Constants stay primitive (`take: 10`); `$param` is only for manual helpers, never load queries. Names and types are inferred.
Every option has `label`, `control`, and `default`. Optional fields are `description`, `choices`, `choicesFrom`, `min`, `max`, `step`, `advanced`, and `group`.
V3 uses `$schema: "homarr-custom-widget-v3"` and optional `extensions`: `stylesheet`, `fragments`, `preferences`, `content`, and `native`. Read `customWidget_schema` for their exact shapes. Integration options use `control: "integration"`, `default: ""`, and optional `integrationKinds`; installations choose local integrations. Discover native input schemas through `customWidget_nativeCapabilities`. Editor layout is separate from the manifest.
@@ -1,9 +1,7 @@
# Security
Private access includes LAN, Docker DNS, and Tailscale CGNAT addresses. Loopback means the Homarr server or container, not the viewer's browser.
All requests use Homarr's protected server executor. Source origin, network scope, DNS, redirects, SSRF, rate limits, permissions, size limits, timeouts, and encrypted credential injection remain enforced.
The JSX interpreter blocks imports, hooks, refs, raw event callbacks, browser requests, eval, arbitrary functions, prototype access, unsafe URLs, global CSS escape, arbitrary portals, bigint, statement blocks, IIFEs, and recursion. Regex literals must be bounded and reject backreferences, lookbehind, nested quantifiers, excessive length, and unsupported flags.
Credentials are stored separately and never exported or returned to an agent. A published self-hosted source URL is only a suggestion: installers must confirm or replace private and loopback URLs for their own Homarr deployment. Source origins cannot be controlled through widget options.
Credentials stay local and are never exported. Installers confirm or replace suggested private and loopback URLs for their deployment. Source origins are fixed by configuration.
+3 -8
View File
@@ -16,9 +16,10 @@ LOG_LEVEL='info'
# This is how you can use the sqlite driver:
DB_DRIVER='better-sqlite3'
# Safe local source-development path. SQLite files are ignored by Git.
# Set an absolute writable SQLite path so migrations and the app use the same file.
# Their working directories differ; do not use a relative path here.
# Container images use /appdata/db/db.sqlite by default instead.
DB_URL='./db.sqlite'
DB_URL=
# Those are the two ways to use the mysql2 driver:
# 1. Using the URL format:
@@ -93,9 +94,3 @@ HOMARR_WEBSITE_URL=https://homarr.dev
# Whether demo mode is read-only. Defaults to true (the public demo blocks all mutations).
# Set to false for writable preview deployments so the demo user can modify the dashboard.
# DEMO_READ_ONLY=false
# Persistent trusted-widget build cache; activated artifacts are also retained in the database.
# Defaults to /appdata/custom-widgets in production and ./appdata/custom-widgets in development.
# CUSTOM_WIDGET_PACKAGE_PATH=/appdata/custom-widgets
# Maximum concurrently active trusted widget server artifacts per Homarr process.
# CUSTOM_WIDGET_MAX_SERVER_PROCESSES=16
+13
View File
@@ -25,6 +25,18 @@ body:
attributes:
label: Additional information
description: Add any other information related to the bug here, screenshots if applicable.
- type: input
id: exactBuild
attributes:
label: Exact build or image
description: For preview or development builds, include the commit SHA or image digest. A moving tag such as v2 is not enough to identify the build.
placeholder: "Commit SHA, image digest, or release version"
- type: input
id: lastWorkingVersion
attributes:
label: Last working version
description: If this worked before, include the last version or build where you tried the same action. Leave blank if unknown.
placeholder: "Version or commit SHA"
- type: dropdown
id: version
attributes:
@@ -33,6 +45,7 @@ body:
options:
# The below comment is used to insert a new version with on-release.yml
#NEXT_VERSION#
- 1.77.0
- 1.76.2
- 1.76.1
- 1.76.0
+19 -8
View File
@@ -16,10 +16,10 @@ permissions:
jobs:
create-and-merge-pr:
runs-on: ubuntu-latest
timeout-minutes: 2
timeout-minutes: 10
steps:
- name: Discord notification
if: ${{ github.event.inputs.send-notifications }}
if: ${{ inputs.send-notifications }}
env:
DISCORD_WEBHOOK: ${{ secrets.DISCORD_WEBHOOK }}
uses: Ilshidur/action-discord@0.4.0
@@ -37,11 +37,22 @@ jobs:
branch: next
- name: Create pull request
id: create-pull-request
run: 'gh pr create --title "chore(release): release ${{ steps.semver.outputs.next }}-beta" --body "Detected change to be ``${{ steps.semver.outputs.bump }}``<br/>Bump version from ``${{ steps.semver.outputs.current }}`` to ``${{ steps.semver.outputs.next }}-beta``" --base beta --head next --label automerge'
run: |
pr_url="$(gh pr list --base beta --head next --state open --json url --jq '.[0].url // empty')"
if [[ -z "$pr_url" ]]; then
pr_url="$(gh pr create \
--title "chore(release): release ${{ steps.semver.outputs.next }}-beta" \
--body "Detected change to be ${{ steps.semver.outputs.bump }}<br/>Bump version from ${{ steps.semver.outputs.current }} to ${{ steps.semver.outputs.next }}-beta" \
--base beta \
--head next \
--label automerge)"
fi
echo "url=$pr_url" >> "$GITHUB_OUTPUT"
echo "pr_number=${pr_url##*/}" >> "$GITHUB_OUTPUT"
env:
GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}"
- name: Discord notification
if: ${{ github.event.inputs.send-notifications }}
if: ${{ inputs.send-notifications }}
env:
DISCORD_WEBHOOK: ${{ secrets.DISCORD_WEBHOOK }}
uses: Ilshidur/action-discord@0.4.0
@@ -58,7 +69,7 @@ jobs:
env:
GITHUB_TOKEN: ${{ steps.obtainApprovalToken.outputs.token }}
run: |
gh pr review --approve --body "Automatically approved by GitHub Action"
gh pr review "${{ steps.create-pull-request.outputs.url }}" --approve --body "Automatically approved by GitHub Action"
- name: Obtain token
id: obtainMergeToken
uses: actions/create-github-app-token@v3
@@ -82,21 +93,21 @@ jobs:
MERGE_REQUIRED_APPROVALS: 0 # do not require approvals
- name: Merged Discord notification
if: ${{ steps.automerge.outputs.mergeResult == 'merged' && github.event.inputs.send-notifications }}
if: ${{ steps.automerge.outputs.mergeResult == 'merged' && inputs.send-notifications }}
env:
DISCORD_WEBHOOK: ${{ secrets.DISCORD_WEBHOOK }}
uses: Ilshidur/action-discord@0.4.0
with:
args: "Merged PR ${{ steps.create-pull-request.outputs.url }} for release ${{ steps.semver.outputs.next }}-beta"
- name: Major Bump Discord notification
if: ${{ steps.semver.outputs.bump == 'major' && github.event.inputs.send-notifications }}
if: ${{ steps.semver.outputs.bump == 'major' && inputs.send-notifications }}
env:
DISCORD_WEBHOOK: ${{ secrets.DISCORD_WEBHOOK }}
uses: Ilshidur/action-discord@0.4.0
with:
args: "The release PR must be manually merged because the next version is a major version: ${{ steps.create-pull-request.outputs.url }} for release ${{ steps.semver.outputs.next }}-beta"
- name: Discord Fail Notification
if: failure() && github.event.inputs.send-notifications
if: ${{ failure() && inputs.send-notifications }}
env:
DISCORD_WEBHOOK: ${{ secrets.DISCORD_WEBHOOK }}
uses: Ilshidur/action-discord@0.4.0
-1
View File
@@ -69,7 +69,6 @@ e2e/shared/tmp
#personal backgrounds
apps/nextjs/public/images/background.png
apps/nextjs/public/__widget-editor/
+13 -3
View File
@@ -59,7 +59,13 @@ homarr/
The documentation site lives at `apps/docs/` (Docusaurus 3, `@homarr/docs`).
When modifying user-facing code, you MUST also update the corresponding documentation:
Write for smart, curious, advanced users. Documentation should contain only information they cannot reasonably discover or understand directly from the interface: hidden capabilities, non-obvious behavior, prerequisites, constraints, configuration contracts, and migration requirements.
Keep docs concise. Every paragraph must add knowledge beyond visible labels and standard UI conventions. Explain how to discover and use a hidden advanced widget feature; omit explanations that the Delete button deletes an item in edit mode. Avoid UI walkthroughs, exhaustive control descriptions, and repetition. When editing a passage, remove obvious or redundant prose rather than preserving verbosity as a precedent.
Update docs only when a change introduces or alters that non-obvious information, or makes existing guidance inaccurate. Routine fixes and self-explanatory UI changes need no docs update. A new feature alone does not require a page; apply the same reader-value test.
When documentation is needed, use these locations:
- New integration → `apps/docs/docs/integrations/<slug>/index.mdx` + `index.ts`
- New widget → `apps/docs/docs/widgets/<slug>/index.mdx` + `index.ts`
@@ -86,7 +92,7 @@ When modifying user-facing code, you MUST also update the corresponding document
- Lint: oxlint (not ESLint)
- Format: oxfmt (not Prettier)
- UI: Mantine (not Tailwind) — Tailwind is only used in docs app
- Mantine: use the project-scoped MCP server in `.mcp.json` for current v9 APIs, and check `packages/ui/` before creating a new primitive.
- Mantine: use the `mantine` MCP server in `.mcp.json` for current v9 APIs before writing component code. Prefer built-in primitives (`Combobox`/`useCombobox`, the polymorphic `component` prop, `@mantine/hooks`) and check `packages/ui/` for existing conventions first.
- Icons: @tabler/icons-react
- Docs app can import from `@homarr/definitions` for shared types
- Run `pnpm dev:cli -- dev` to browse local `homarr:*` images and remote PR images.
@@ -94,11 +100,15 @@ When modifying user-facing code, you MUST also update the corresponding document
- Run `pnpm dev:cli -- build --pr <number>` to build a PR locally from a temporary checkout.
- Run Go checks from `tools/homarr-dev` with `go test ./...` and `go vet ./...`.
## MCP servers
`.mcp.json` declares project-scoped MCP servers. Keep only keyless definitions there; credentials belong in local dotfiles. See [Mantine LLM tooling](https://mantine.dev/guides/llms/) for client-specific setup.
## Agent Skills
Portable skills live in `.agents/skills/`. Read the relevant `SKILL.md` before working in that domain; detailed references are loaded only when needed. Claude-compatible discovery is provided through `.claude/skills`.
- `codebase-context` — architecture, package boundaries, and shared utilities
- `documentation-sync` — required user-facing documentation updates
- `documentation-sync` — documentation for changes users need explained
- `mcp-integration` — safe tRPC-to-MCP exposure
- `homarr-custom-widget` — safe Custom JSX v2 authoring
+4
View File
@@ -1,3 +1,7 @@
## [1.77.1](https://github.com/homarr-labs/homarr/compare/v1.77.0...v1.77.1) (2026-09-11)
## [1.77.0](https://github.com/homarr-labs/homarr/compare/v1.76.2...v1.77.0) (2026-09-06)
## [1.76.2](https://github.com/homarr-labs/homarr/compare/v1.76.1...v1.76.2) (2026-08-27)
## [1.76.1](https://github.com/homarr-labs/homarr/compare/v1.76.0...v1.76.1) (2026-08-26)
+6 -14
View File
@@ -15,19 +15,13 @@ Many of you used the v2 demo when it was still rough, found bugs and came back t
We are also planning a small batch of **free, limited-edition Homarr swag** for Workshop contributors and a few randomly picked community members. It is not for sale and it is not for profit. No Homarr merch empire, sorry.
Homarr 2.0 is an upgrade, not a brand-new app wearing the same logo. Here is what actually changed.
Homarr 2.0 builds on the dashboard you already use. Here is what changed.
![A populated Homarr 2.0 dashboard with compact widgets, an Assistant, and an application rail](./img/homarr-v2-dashboard.webp)
<!-- truncate -->
:::warning Back up before upgrading
Database migrations run automatically when Homarr starts. Create a
[Homarr backup](/docs/management/backup) first. Do not test a prerelease image on your only production volume.
Backups are boring. Restores are worse.
:::
Update your Homarr image as usual. Homarr runs database migrations automatically when the updated container starts; no manual database migration or separate v2 upgrade procedure is needed. Workshop uses the production service by default, with no preview URL configuration required.
## Custom Widgets v2 and Workshop
@@ -150,9 +144,8 @@ Groups use a new Viewer, Editor and Admin matrix. The API, Assistant and MCP fol
Board startup work runs in parallel, heavy screens load when opened, and identical integration requests share work instead of doing it twice.
## Before upgrading
## Compatibility notes
- Keep a backup and use the final release image, not a prerelease tag.
- Legacy Custom JSX definitions enter a migration state. Homarr keeps encrypted credentials and an archived copy until the v2 definition validates.
- Mobile layouts place rail content in the main flow instead of displaying rails.
- Custom Widgets remain Beta.
@@ -160,8 +153,7 @@ Board startup work runs in parallel, heavy screens load when opened, and identic
## Links
- Try the [Homarr 2.0 preview](https://app-v2.preview.homarr.dev).
- Follow the [v2 beta setup guide](/docs/getting-started/upgrade-v2).
- Follow the [v2 release pull request](https://github.com/homarr-labs/homarr/pull/6545) and [public beta thread](https://github.com/homarr-labs/homarr/issues/6600).
- Compare [v1.76.2 with the release/v2 branch](https://github.com/homarr-labs/homarr/compare/v1.76.2...release/v2).
- Try the [live demo](https://demo.homarr.dev/).
- See [installation and update instructions](/docs/getting-started/installation/docker).
- Browse [Workshop](https://homarr.dev/workshop).
- Read the guides for [Boards](/docs/management/boards), [Custom Widgets](/docs/management/custom-widgets), [Assistant](/docs/management/assistant), [MCP](/docs/management/mcp) and [Docker labels](/docs/integrations/docker-labels).
@@ -90,7 +90,7 @@ homarr run dev
homarr run --detach dev
homarr run --pr 6441
homarr run --pr 6441 --demo
homarr --pr 6441 --env WORKSHOP_WEB_URL=https://app-v2.preview.homarr.dev/
homarr --pr 6441 --env WORKSHOP_WEB_URL=https://workshop.example.com/workshop
```
- `--pr <number>`: Pull and run a PR image from GHCR (shorthand: `homarr --pr <number>`).
+1 -143
View File
@@ -3,8 +3,7 @@
The Homarr image includes a recovery CLI for operations that cannot be completed in the web interface. It is not an
application API; use the [API](/docs/management/api) or [MCP endpoint](/docs/management/mcp) for automation.
Back up the database and stop Homarr before running a recovery command that changes database records directly.
Widget project commands and authenticated preview requests can run while Homarr is online.
Back up the database and stop Homarr before running a command that changes data.
Failed commands print an error and return a non-zero exit code, so shell scripts can stop safely.
## Run the recovery CLI
@@ -44,147 +43,6 @@ homarr <command>
See the pages in this section for available commands.
## Build and share custom widget packages
The `widgets` commands accept a project directory, a v3 package JSON file, or an offline archive. Scaffolding,
validation, compilation and packing do not need a running Homarr database.
Create a project to edit in your own IDE:
```sh
homarr widgets init my-clock --example clock --id example.my-clock --name "My clock"
homarr widgets validate my-clock
homarr widgets pack my-clock
```
`init` (also `scaffold`) creates a new directory with `homarr-widget.json` and normal TSX, TypeScript, CSS and asset
files. It refuses to overwrite an existing directory. Choose `clock`, `timer`, `beszel`, `checklist`, `downloads`,
`sonarr`, `rack`, `backup`, `household`, `overview`, `media`, `sqlite` or `mqtt` with `--example`; leaving out `--id` generates a unique
local package identity. Edit the manifest and files, then repeat validation and packing. The manifest carries entrypoints,
handlers, connection requirements, options and exact dependency versions; it does not embed the files map in this layout.
Directory loading skips hidden files, symlinks, `node_modules`, `dist`, `coverage`, generated archives and root-level
`package.json`, `package-lock.json` and `tsconfig.json`. Keep all widget source under supported TS/JS, JSON, CSS, SVG,
text, Markdown, image or font files. Build output defaults to `dist/widget.artifact.json`; packing defaults to
`dist/widget.homarr-widget.json`. Remove or rename an existing output before rebuilding, or pass a new `--output`.
The same commands also accept the single-file format:
```sh
homarr widgets validate widget.json
homarr widgets build widget.json --output widget.artifact.json
homarr widgets pack widget.json --output widget.homarr-widget.json
homarr widgets validate widget.homarr-widget.json
```
`validate` checks the package structure or an archive's source and artifact checksums. It does not execute widget code.
`build` compiles JSX/TSX, local modules, CSS and assets into browser and optional server output. `pack` includes the
source, compiled output and dependency lock in one JSON archive for offline installation. Output files must not already exist.
Packages with third-party dependencies need `--trust` to install their exact declared versions:
```sh
homarr widgets pack widget.json --trust
```
Dependency installations are cached in `.homarr-widgets` beside the input file. Installation scripts are disabled;
packages requiring native build steps are not supported by these commands. Compilation does not start the widget's
server handlers. Installed trusted widgets execute with Homarr's privileges; source and artifact checksums establish
integrity, not publisher authenticity. Local connection bindings, credentials and widget state are separate from the archive.
### Preview a local project in Homarr
Set `HOMARR_API_KEY` to an admin API key from your own Homarr instance, then run:
```sh
homarr widgets preview my-clock --url http://homarr.local:7575 --trust
```
The command creates a disabled installation on first use, compiles the current local source on that Homarr instance,
and prints a link to its exact preview session. Open the link while signed in as the API key owner. Repeating the command
replaces the previous preview; it does not activate or overwrite the installation's saved draft. Use `--save-draft` to
also save your local source. Use `--installation-id ID` to target an existing installation. The local
`.homarr-widget.local.json` file remembers installation and preview IDs and is excluded from scaffolded Git projects.
Pass `--bindings bindings.json` for a JSON object mapping declared connection names to existing Homarr connection IDs,
and `--options options.json` for preview option values. Credentials remain in Homarr. `--live-actions` explicitly allows
real mutations during this preview; queries and subscriptions can already execute trusted server code. `--trust` is
required on every invocation. Set `HOMARR_URL` instead of `--url`, or select a different secret variable with
`--api-key-env VARIABLE_NAME`. Preview compilation may install declared dependencies after this explicit trust choice.
Use `--scenario NAME` to select synthetic query data declared in the package's `previewScenarios`. This skips server
startup and configured service requests; unprovided query fixtures fail explicitly and subscriptions are unavailable.
SDK actions stay simulated, so `--scenario` cannot be combined with `--live-actions`. Trusted browser code and dependency
compilation keep their normal privileges. See [synthetic preview scenarios](../../management/custom-widgets/trusted-packages.mdx#synthetic-preview-scenarios).
### Publish the exact offline archive
Set `HOMARR_WORKSHOP_TOKEN` to an authenticated Workshop token, then publish the archive you reviewed:
```sh
homarr widgets publish my-clock/dist/widget.homarr-widget.json
homarr widgets publish next-release.homarr-widget.json --submission-id LISTING_ID --expected-revision 1
```
Use `--url` (or `WORKSHOP_API_URL`) for your own Workshop service, `--token-env` for another token variable,
`--changelog` for release notes, and `--forked-from RELEASE_ID` to attribute a new fork. Existing listings require their
current revision and a new package version. Forks need their own package identity. Published releases are immutable;
publication sends the archive without rebuilding it. You can also import the archive into Homarr and publish through
the package workspace.
### Run a package on another machine
Run an already packed archive on another machine with the optional widget runner:
```sh
export HOMARR_WIDGET_RUNNER_TOKEN="$(openssl rand -hex 32)"
homarr widgets serve widget.homarr-widget.json --trust --host 127.0.0.1 --port 8787
```
`serve` executes the installed package with that machine's operating system privileges. It never downloads packages
or accepts source uploads. Set a custom token variable with `--token-env VARIABLE_NAME`. The token must have at least
32 characters. Interrupting the command stops its worker and subscriptions. See [remote widget runners](../../management/custom-widgets/remote-runners.mdx)
for connection setup, local files, SQL, MQTT, and browser-service adapters.
### Share several widgets as a collection
A collection contains independent compiled widget packages and a shared connection blueprint. Write a collection
manifest with paths to already packed archives:
```json
{
"manifest": { "id": "example.home", "version": "1.0.0", "name": "Home dashboard" },
"connections": { "monitor": { "label": "Monitoring server", "kind": "integration" } },
"widgets": [
{ "key": "clock", "archive": "clock/dist/widget.homarr-widget.json" },
{
"key": "servers",
"archive": "beszel/dist/widget.homarr-widget.json",
"connections": { "beszel": "monitor" }
}
]
}
```
Pack and verify it without compiling or executing the member packages:
```sh
homarr widgets collection pack collection.json --output home.homarr-collection.json
homarr widgets collection validate home.homarr-collection.json
homarr widgets collection import home.homarr-collection.json --url http://homarr.local:7575
```
`import` uses `HOMARR_API_KEY`, or the variable selected with `--api-key-env`. Pass `--bindings bindings.json` to map
each collection slot to an existing local Homarr connection once; all members that reference that slot receive the
binding. Omitted connections can be configured later. Imports create every member as a disabled draft in one database
transaction and print their review links. Trust and activation are separate, explicit steps.
Collections support 1–32 members and up to 128 MiB. Package identities, compiled artifacts, dependency locks and
documented Workshop/fork attribution travel with the archive. The collection and each nested artifact have integrity
checksums. Local connection URLs, IDs and credentials, board placements, stored widget data and local configuration
are excluded. Authored `options` on a member are portable defaults: include only values you intend to share. Package
source is included verbatim, so embedded literals are still part of the archive.
## Build a local branch harness
The repository's host-side CLI can build the current checkout and run it as a named Docker harness:
@@ -31,9 +31,13 @@ pnpm install --frozen-lockfile
### Run the Homarr application
1. Copy `.env.example` to `.env`.
2. Set `DB_URL` to an absolute writable SQLite file path.
3. Keep Redis and the optional local databases running in one terminal.
4. Apply migrations and start Next.js in another terminal.
2. Run `openssl rand -hex 32` twice. Set `AUTH_SECRET` and `SECRET_ENCRYPTION_KEY` to the two different generated
values in `.env`; the example leaves both empty. Keep this file private and preserve `SECRET_ENCRYPTION_KEY`
when reusing a database.
3. Set `DB_URL` to an absolute writable SQLite file path. Migration and application commands run from different
workspace directories, so a relative path can point them at different databases.
4. Keep Redis and the optional local databases running in one terminal.
5. Apply migrations and start Next.js in another terminal.
```sh
cp .env.example .env
@@ -57,6 +61,20 @@ Homarr becomes the instance administrator.
Use `pnpm docker:dev:up` instead when you only need Redis in the background. Running the migration also seeds the
default data; use `pnpm db:seed` to seed it explicitly later.
`pnpm dev` starts only Next.js. When your work needs scheduled tasks or live subscriptions, run the relevant service
in a separate terminal alongside it:
```sh
pnpm --filter @homarr/tasks dev
```
```sh
pnpm --filter @homarr/websocket dev
```
The WebSocket service listens on port 3001. Production startup embeds both services, so these extra commands are
only needed for development.
Workshop contributors can set up PocketBase and Docusaurus with the dedicated
[Workshop development guide](./workshop).
@@ -80,8 +98,8 @@ Workshop contributors can set up PocketBase and Docusaurus with the dedicated
- `pnpm typecheck` — typecheck all workspaces.
- `pnpm test` — unit and contract suites.
- `pnpm build` — production monorepo build.
- `docker build -t homarr .` — build a production Docker image.
- `docker run -p 7575:7575 -e SECRET_ENCRYPTION_KEY='your_64_character_hex_string' homarr:<name>` — run it.
- `docker build -t homarr:local .` — build a production Docker image.
- `docker run -p 7575:7575 -e SECRET_ENCRYPTION_KEY='your_64_character_hex_string' homarr:local` — run it.
## CI and focused validation
@@ -140,14 +140,3 @@ The advanced deployments environment variables should only be used if you know w
All public URL variables reject non-HTTP protocols, embedded credentials, query strings, and fragments, and normalize
trailing slashes when Homarr or Docusaurus starts.
## Trusted widget packages
| Variable | Purpose | Default |
| ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| `CUSTOM_WIDGET_PACKAGE_PATH` | Persistent build and runtime artifact cache. Activated browser/server artifacts and their source are also retained in the database. | `/appdata/custom-widgets` in production; `./appdata/custom-widgets` in development |
| `CUSTOM_WIDGET_MAX_SERVER_PROCESSES` | Maximum active trusted widget server artifacts per Homarr process, from 1 to 128. Source-free packages do not start a server process. | `16` |
Each replica materializes an authorized installed artifact from the database into its own cache. Dashboard requests do
not install npm dependencies. Package dependencies are resolved and bundled when an owner previews or activates a new
source draft; importing a complete compiled archive supports offline activation. See [trusted widget packages](/docs/management/custom-widgets/trusted-packages).
@@ -13,7 +13,8 @@ You can change the user and group by using the `PUID` and `PGID` environment var
Important to note is, that you'll also need to change the permissions for the mounted directories accordingly.
:::info
When starting up an updated version of the container it will have about **10 seconds longer to start** as it has to change the permissions of the app directories
At startup, Homarr updates ownership of its data directories and runtime caches for the selected user and group.
Startup time depends on the amount of persistent data; application code and dependencies do not need ownership changes.
:::
## Without mounted Docker socket
@@ -24,6 +24,10 @@ see [Managing integrations](/docs/management/integrations#configuration).
### Update
Update the image and recreate the container with the same configuration. Homarr runs database migrations automatically
at startup, including when moving from v1 to v2; no separate upgrade procedure is needed. Keep the `/appdata` mount and
`SECRET_ENCRYPTION_KEY` unchanged. Workshop connects to the production service by default.
```sh
docker compose pull
docker compose up -d
@@ -21,8 +21,8 @@ This method is only useful, when you want to develop on Homarr or extend it with
## Prerequisites
- [Node.js](https://nodejs.org/en/download/)
- [pnpm](https://pnpm.io/installation)
- [Node.js](https://nodejs.org/en/download/) 24.18 or newer
- [pnpm](https://pnpm.io/installation) at the version pinned in the repository's `package.json`
- [Redis](https://redis.io/download)
## Steps
@@ -38,9 +38,9 @@ This method is only useful, when you want to develop on Homarr or extend it with
Install all dependencies using <code>pnpm install</code>
</li>
<li>
Copy the `.env.example` file to `.env`. Its `DB_URL='./db.sqlite'` value is ready for local use and stores the
database in the cloned repository. Replace it with an absolute writable path such as
`DB_URL='/home/username/homarr/db.sqlite'` if you want to store the database elsewhere.
Copy `.env.example` to `.env` and set `DB_URL` to an absolute writable path, such as
`DB_URL='/home/username/homarr/db.sqlite'`. Migration and application commands run from different workspace
directories, so a relative path can point them at different databases.
</li>
<li>
Run `openssl rand -hex 32` twice and set `AUTH_SECRET` and `SECRET_ENCRYPTION_KEY` to the two different generated
@@ -1,88 +0,0 @@
---
title: Try the v2 beta
sidebar_position: 2
tags:
- Getting started
- Upgrade
- Migration
- Backup
---
This page covers the temporary Homarr v2 public beta. Try the [live demo](https://app-v2.preview.homarr.dev/)
without installing anything, or run the beta image published in the
[public beta announcement](https://github.com/homarr-labs/homarr/issues/6600):
```sh
docker pull ghcr.io/homarr-labs/homarr-test:v2
```
For a fresh beta installation, follow the [Docker installation guide](/docs/getting-started/installation/docker),
use `ghcr.io/homarr-labs/homarr-test:v2` as the image, and use a separate `/appdata` volume.
Set `WORKSHOP_API_URL=https://v2.preview.homarr.dev` to use the preview Workshop.
Homarr runs database migrations automatically at startup; no manual database migration command is needed.
Once v2 is released, existing installations can use their normal update process. The beta image below is temporary.
:::danger Back up before starting v2
In Homarr v1, go to **Management → Tools → Backup**, export a backup, and keep the downloaded file somewhere safe
before starting v2. See [Backup and restore](/docs/management/backup) for details.
:::
## Try the beta with existing v1 data
1. Change the Homarr image to `ghcr.io/homarr-labs/homarr-test:v2`.
2. Keep the existing `/appdata` mount, database variables, Redis configuration, and `SECRET_ENCRYPTION_KEY` unchanged.
3. Start one Homarr replica and follow its logs. Startup must reach `Migration complete`; Homarr aborts startup when a
database migration fails.
4. Open Homarr and sign in. Confirm **Management → About** reports v2 before starting additional replicas.
5. Keep using the beta image for beta updates. To return to v1, restore the pre-beta backup as described below.
Keep your other existing Compose settings, including environment variables. For Docker Compose, update the image and preview Workshop URL before the usual update:
```yaml
services:
homarr:
image: ghcr.io/homarr-labs/homarr-test:v2
environment:
WORKSHOP_API_URL: https://v2.preview.homarr.dev
```
```sh
docker compose pull
docker compose up -d
docker compose logs --follow homarr
```
Do not add `-v` when stopping the Compose deployment; that can remove named volumes.
## What v2 migrates
The startup migration:
- creates the Custom Widget v2, Assistant, header preference, and branding storage;
- adds Base/Mobile layout roles and left/right board gutters;
- converts legacy Categories and dynamic sections into Containers and rails;
- preserves legacy Custom Widget definitions, encrypted secrets, and board references for explicit migration.
Legacy Custom Widgets are not silently rewritten. In **Management → Custom Widgets**, entries marked
**Migration required** provide a credential-free migration prompt. Review and test the resulting v2 definition before
removing the archived v1 version. See [Custom Widgets: Import and Workshop](/docs/management/custom-widgets#import-and-workshop).
## Verify the upgraded instance
- Sign in with each enabled authentication method and verify administrator access.
- Open every important board on desktop and mobile. Check Containers, former Categories, rails, item placement, and
home-board assignments.
- Test at least one read and one permitted action for each critical integration. Recheck integration and board access
for representative Viewer, Editor, and Admin groups.
- Check Docker or Podman endpoints, search engines, uploaded media, trusted certificates, scheduled tasks, WebSockets,
and external Redis when used.
- Review every legacy Custom Widget and migrate it only after its v2 preview and requests work.
- Restart Homarr once more and confirm the logs contain no migration, database, Redis, authentication, or task errors.
## Roll back
Use the backup exported before the upgrade if you need to restore your v1 installation. Do not reuse a database that
v2 has already migrated with v1.
@@ -28,6 +28,8 @@ import { smartHomeExecuteAutomationWidget } from "@site/docs/widgets/smart-home-
]}
/>
Entity toggles and automation triggers send JSON requests to Home Assistant. A rejected action is shown as a failure.
### Adding the integration
<AddingIntegration />
@@ -30,6 +30,8 @@ import { systemResourcesWidget } from "@site/docs/widgets/system-resources";
]}
/>
Disk temperatures are matched to filesystem partitions, including device names without the `/dev/` prefix.
### Adding the integration
<AddingIntegration />
@@ -32,10 +32,3 @@ import { calendarWidget } from "@site/docs/widgets/calendar";
},
]}
/>
### Trusted widget packages
The [Sonarr operations reference package](/docs/management/custom-widgets/trusted-packages) can combine two Sonarr
integrations, display upcoming and missing episodes and queue progress, and submit a confirmed search for a missing
episode. Search actions use the existing integration API key on Homarr's server and require interaction access.
A successful command submission means Sonarr queued the search, not that it found or downloaded a release.
@@ -19,6 +19,9 @@ import Alert from "@theme/Admonition";
<IntegrationCapabilites items={[{ widget: healthMonitoringWidget }, { widget: systemResourcesWidget }]} />
Disk space uses each pool's root dataset to account for RAIDZ parity and dataset limits. If dataset space is unavailable,
Homarr falls back to physical pool space, which reads higher on RAIDZ, and keeps reporting pool health.
### Adding the integration
<AddingIntegration />
@@ -23,6 +23,8 @@ import imgSelectApikeyPreset from "./imgs/unraid-select-api-key-preset.png";
<IntegrationCapabilites items={[{ widget: healthMonitoringWidget }, { widget: systemResourcesWidget }]} />
CPU usage is averaged across logical processors, including SMT threads.
### Adding the integration
<AddingIntegration />
@@ -24,12 +24,14 @@ The What's Up Docker integration lets Homarr connect to your [WUD](https://githu
<AddingIntegration />
:::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.
Use the root URL of your WUD instance, for example `https://wud.example.com`. Homarr uses `/api/containers` under that URL for both connection testing and widget data.
:::
### 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.
WUD 9 requires authentication. Enter your WUD username and password in Homarr; the initial admin credentials configured with `WUD_AUTH_ADMIN_USER` and `WUD_AUTH_ADMIN_PASSWORD` work with Basic authentication. Older WUD versions without authentication can leave both fields empty.
Credentials are sent to the configured URL over HTTP or HTTPS. Use HTTPS outside a trusted internal network.
<IntegrationSecrets
secrets={[
@@ -40,7 +42,7 @@ WUD does not require authentication by default. If your instance is protected wi
{
credentials: ["username", "password"],
steps: [
"Open your WUD instance's configuration and configure a WUD_AUTH_BASIC_* user as described in the WUD documentation",
"Use your WUD account credentials; older versions can use a configured WUD_AUTH_BASIC_* user",
"Enter that username and password in Homarr — Basic authentication is handled automatically",
],
},
+21 -34
View File
@@ -99,40 +99,27 @@ and focused references under `/api/custom-widgets/`.
Use [Custom Widget agent authoring](../custom-widgets/agent-authoring) for the lifecycle and
[MCP](../mcp) when the client supports Model Context Protocol.
## Trusted widget package lifecycle
Workshop installation through `customWidget.workshopInstall` and the in-app catalog uses the same server path. Supply
`expectedRevision` from `customWidget.workshopGet` to install only the package you reviewed. Source URL overrides and
credentials are local; the installed definition retains its Workshop provenance.
For native capabilities, pass local integration selections as `integrations: { "optionId": "integrationId" }`; portable
defaults do not carry another Homarr instance's integration IDs.
The `customWidget.package` tRPC namespace separates authoring from activation. Administrators can save incomplete
source with `saveDraft`, inspect `draftChanges`, run `preview`, and call `activate` after acknowledging trusted code.
`getRaw` and `repair` on `customWidget` recover existing v2 definitions without rendering their code.
When renaming a saved source through `customWidget.update` or `customWidget.previewCreate`, include
`sourceRenames: { "previousId": "newId" }` to preserve its credentials. The server checks the original and resulting
source bindings; changed origin, network scope, or authentication requires re-entered credentials. A rename moves
encrypted credentials transactionally and does not copy them into the portable definition.
The package API also manages named local connections, per-placement guest grants, retained collectors, immutable
archive import/export, forks, Workshop releases, staged updates, and rollback. `get` and `list` return management data
without evaluating submitted package modules. Connection secret values are accepted separately by `saveConnection`
and are not returned by connection listing or package export.
For an existing connection, `secretUpdates` patches only supplied credential keys while retaining the others;
`secrets` replaces the complete credential map. Supply only one. Credential patches require the saved connection
kind and authentication method to match the submitted configuration.
For a linked installation, `customWidget.workshopUpdateReview` returns the current and incoming definitions, source-binding
changes, local-modification status, and review tokens. Pass its `expectedFingerprint`, `expectedState`,
`upstreamFingerprint`, and `revision` unchanged to `customWidget.workshopUpdateInstall`. Both procedures require admin
access and are exposed through MCP with an underscore replacing the dot. An intervening edit or upstream revision
returns `CONFLICT`; fetch a fresh review instead of retrying the old update. Source/authentication changes and local
customizations require a separate installation.
`previewStorageGet` and `previewStorageSet` use the owning administrator's preview session and the same temporary
store as its server handlers. They accept `previewId`, `scope`, and `key`; writes also accept `value`.
Expired, discarded, and other users' sessions cannot read or write preview storage.
Connection configuration accepts `kind: "http" | "integration" | "service"`. A service connection supplies a
`serviceType` and a JSON `settings` object without requiring a URL; encrypted `secrets` remain a separate input.
Package requirements match both `kind` and `serviceType`. Server handlers access these settings through
`getWidgetConnection` in `@homarr/widget-sdk/server`. Service diagnostics distinguish file readability, TCP
reachability and settings-only checks; preview runs the adapter's actual database or protocol operation.
Installed widgets use `widget.customApi.packageQuery`, `packageAction`, `packageSubscription`, `packageStorageGet`,
and `packageStorageSet`. Each invocation is bound to an existing board item and a manifest-declared handler; the host
checks the current board and integration permissions. A public board does not grant action access automatically.
Guest grants name a handler and exact allowed inputs, and are invalidated by changes to server behavior, dependencies,
connection identity, or resource-selecting options.
Compiled surfaces are served through `/api/custom-widgets/artifacts/{itemId}/{digest}/{surface}` after board access
checks. The optional `?asset=css` selects the corresponding stylesheet. Preview surfaces use
`/api/custom-widgets/previews/{previewId}/{surface}` and require the administrator who created the preview.
These routes do not expose server source or connection credentials.
The full package format, SDK examples, trust boundary, and activation behavior are described in
[trusted widget packages](../custom-widgets/trusted-packages).
Shared widget content uses `customWidget.contentRead({ itemId })` and
`customWidget.contentWrite({ itemId, name, expectedRevision, value })`. Reads require access to the board; writes require
authentication and the declaration's `modify` or `full` board permission. Each value has an independent revision; `0`
means the declared default has not been saved. A stale revision returns `CONFLICT`; read again before saving. Content is
scoped to the placed item and its selected definition. Workbench previews keep content changes in memory and cannot
persist them through these procedures. These procedures are not exposed as MCP tools.
-14
View File
@@ -38,17 +38,3 @@ A backup can be restored on another Homarr instance. When its `SECRET_ENCRYPTION
integration secrets for the target instance. Version metadata is used to apply compatible migrations.
The same restore flow is available during first-run onboarding, before the target database contains user data.
## Custom widget packages
Database backups include installed v2 definitions and trusted v3 source, compiled artifacts, current and previous
activation metadata, local connections, placement bindings, guest grants, and managed widget storage/history.
Restoring an encrypted backup re-encrypts widget credentials with the destination instance's key alongside native
integration credentials. Compiled artifacts can be materialized again from the restored database without Workshop.
Keep `SECRET_ENCRYPTION_KEY` with database backups made using MySQL or PostgreSQL administration tools. The built-in
ZIP export/restore remains specific to SQLite. A package export is portable distribution material and deliberately
excludes local connections, credentials, stored values, and collected history; it is not a complete instance backup.
Files created directly by trusted Node code, external databases, remote-runner state, and changes already made to
other applications are outside Homarr's managed widget storage. Include those resources in your own backup process.
@@ -64,3 +64,8 @@ Below you can find instructions for some of the integrations.
Since version 6 of Pi-hole, the web interface can be accessed through HTTPS.
The certificate can be found in the path `/etc/pihole/tls_ca.crt`. To add the certificate, this file needs to be copied and uploaded to Homarr.
You can find more details regarding SSL / TLS for Pi-hole [here](https://docs.pi-hole.net/api/tls/).
### Proxmox
For the default Proxmox VE cluster certificates, trust the cluster CA from `/etc/pve/pve-root-ca.pem` on any node.
See [Proxmox certificate management](https://pve.proxmox.com/wiki/Certificate_Management).
@@ -26,7 +26,7 @@ Equivalent HTTP resources are available under `/api/custom-widgets/` for authent
## Authoring lifecycle
1. Load the skill and only the references needed for the design.
2. Read the external API documentation and build the definition.
2. Read the external API documentation or discover Homarr capabilities with `customWidget_nativeCapabilities`, then build the definition.
3. Validate the JSX, then create a preview from the complete definition.
4. Run every returned query and simulate every relevant action against the current preview revision.
5. Inspect the preview and redacted journal. Revise the existing preview for JSX-only changes.
@@ -34,7 +34,9 @@ Equivalent HTTP resources are available under `/api/custom-widgets/` for authent
7. Configure deployment-specific source URLs and credentials, then preview the saved definition again.
Use `templateLines` for multiline JSX tool input. A preview must have current evidence for every query and action before
it can be saved. Simulation counts as action evidence without performing the mutation.
it can be saved. Simulation counts as action evidence without performing the mutation. V3 native queries and actions use
`customWidget_nativeQuery` and `customWidget_nativeAction` with the owned preview session ID; their evidence is recorded
under `native:<id>`. Native capabilities must also have current evidence before preview-based persistence.
If the agent does not have a source URL or credential, it can request a short-lived Homarr configuration URL. An
authenticated administrator completes it in Homarr; the agent receives the status, never the plaintext credential.
@@ -43,3 +45,10 @@ Agents can also search, inspect, install, and configure existing Workshop widget
See [MCP](/docs/management/mcp) for client configuration and [requests and security](./requests-and-security) for the
runtime limits.
## Editing an open workbench
Homarr's built-in Assistant can use `workbench_read`, `workbench_patch`, and `workbench_preview` to change the visible draft.
Read before patching, supply the returned draft ID and revision, and describe one coherent change. Credentials are excluded from these
tools. The workbench validates the resulting definition and rejects stale patches; one Undo reverses an accepted patch.
Browser draft tools require an open workbench and do not grant permission to save, publish, or run live actions.
@@ -1,41 +1,67 @@
# Create a Custom Widget
The workbench provides editors for general metadata, API sources, requests, widget options, JSX, and preview data. Raw
JSON is available when direct editing is faster.
The definition remains the source of truth in the workbench. Existing widgets open without converting or rewriting their
JSX. Visual changes use targeted source edits; complex expressions remain editable in code.
## Workflow
## Definition and layout
1. Start with a static widget, or add API sources, network access, authentication, and credentials when needed.
2. Add named queries and actions for connected services. Values can reference widget options or invocation parameters.
3. Define widget options and their defaults.
4. Write JSX using `data`, `status`, `options`, and temporary `inputs`.
5. Run **Test and preview**, inspect the response data and redacted request journal, then save.
A static widget needs only a JSX template: set `sources` and `requests` to `{}`. It makes no service request.
Changing the definition, options, or credentials ends the previous API preview session. The last response remains visible
as a labelled snapshot while you edit JSX. Run **Test and preview** again to refresh data and enable API interactions.
Preview actions are simulated unless
**Run actions against the configured API** is enabled for that preview session.
HTTP requests run on the Homarr server. Native capabilities use Homarr's installed integrations and existing
permissions. Embeds open in the viewer's browser and need a URL reachable from that browser.
Use the workbench **Undo** and **Redo** buttons or `Ctrl/Cmd+Z` and `Ctrl/Cmd+Shift+Z` for changes across JSX, sources,
requests, options, and metadata. History is bounded to 100 entries and about two million characters. **Reset to saved**
restores the last saved definition. Credentials are excluded from this history and reset clears unsaved credential values.
Undo and Redo retain pending credentials only when the source origin, network scope, and authentication destination
are unchanged. Otherwise, enter the credentials again for the restored source.
Node positions and groups are stored separately from the runtime definition. Groups do not change execution. Source
associations, data references, action invocations, and cache invalidations are distinct relationships; an invalidation edge
does not create an execution dependency. Referenced objects cannot be removed until their dependants are resolved.
Homarr keeps one recovery draft per signed-in user in this browser, replacing the previous draft as you edit. On returning
to that widget, choose **Restore draft** or **Discard draft**. Saved credentials stay on the server; unsaved credentials must
be entered again. Browser storage is optional, and drafts larger than one million characters are not stored for recovery.
## Visual bindings
Widget options support text, textarea, number, switch, select, multi-select, slider, date, time, color, icon, URL,
duration, time zone, and JSON controls. Dynamic choices can come from a load query.
Connecting a query, option, or action to the Widget opens a binding configuration. Queries can insert text, JSON, lists,
or tables; request parameters can use options, temporary controls, or fixed values. Connecting options to a request changes
its parameter bindings. These edits do not run queries or actions.
See the [safe JSX runtime](./custom-jsx), [component reference](./component-reference), and
[request reference](./requests-and-security) for the authoring contract.
Generated JSX includes ownership comments. The canvas can disconnect or replace unchanged generated bindings as one Undo
operation. Editing a generated block or mixing it with authored references makes the relationship code-owned; resolve it
in JSX to preserve your changes. Removing ownership comments also removes visual ownership, without changing rendering.
## Create with another AI service
## Preview evidence
**Create or fix with any AI** copies a self-contained prompt for an ordinary ChatGPT or Claude conversation. The model
must return one fenced `json` block containing the complete definition. Paste that block into the workbench, add
credentials separately, and validate it against a real preview.
Moving nodes, zooming, and opening inspectors do not execute requests or invalidate the preview. Editing the definition,
options, or credentials marks execution evidence stale. Valid JSX renders against the last data; invalid JSX leaves the
last valid preview visible with a stale label. Queries run deliberately, not on every keystroke.
For an MCP-connected agent, use the [Homarr Custom Widget skill](./agent-authoring) instead.
Preview actions simulate by default. Enabling **Run actions against the configured API** applies only to that preview
session. Native actions also require declared confirmation and their normal integration permissions. Undo changes the draft;
it never undoes or repeats a service action.
## Undo and draft recovery
Undo/Redo covers code, structured edits, renames, node movement, and Assistant patches. Typing is grouped and a drag or
coherent Assistant change is one operation. The bounded history excludes credentials, responses, selection, and viewport
movement. **Reset to saved** restores the saved definition and layout. Saving from an outdated workbench tab reports a
conflict rather than overwriting a newer save.
Temporary test parameters and unfinished request-body JSON keep local input Undo, so editing them does not undo an unrelated
definition change. Credential fields also retain their own input history.
Optional browser draft recovery keeps a credential-free draft and editor layout. Recovery is local to the browser and
requires a valid recoverable configuration. It is not a revision archive or a backup of service data.
## Assistant changes
The Assistant reads the visible draft and selection, edits through shared draft commands, and can run preview queries. A stale patch is
rejected when the draft has changed. Saving, live service actions, and Workshop publication remain separate operations.
Form view retains **Create or fix with any AI** for external AI services. Configure credentials locally after importing
the returned definition and validate the result.
## Advanced capabilities
Native capabilities, scoped CSS, reusable view fragments, typed preferences, and shared content use
`homarr-custom-widget-v3`; ordinary HTTP and static widgets remain valid v2 definitions. Native input bindings must match
the installed capability's schema. See the [runtime](./custom-jsx) for the expression language and extension contracts.
V3 adds an integration picker with optional `integrationKinds`. The integration list respects the
current user's access. Portable exports clear local integration selections so installers choose their own services.
See the [runtime](./custom-jsx), [component reference](./component-reference),
[native capabilities](./native-capabilities), and [request reference](./requests-and-security).
@@ -6,14 +6,8 @@ Templates are JSX expressions interpreted inside a widget-local safety and rende
- `status.requestId` — `{ loading, ok, status, statusText, error }`
- `options.name` — saved widget configuration
- `inputs.name` — temporary values from declarative `bind`
- `host` — the widget's board context, dimensions, scale, and compact or advanced display mode
Existing callbacks may still use `host` as their parameter name, such as `data.hosts.map(host => host.name)`.
Inside that callback, `host` refers to the current item; outside it, `host` refers to the widget context.
The v2 manifest supports empty `sources` and `requests` for widgets that do not need an API. Connected widgets support
up to eight sources, 64 requests, and 64 options. Each request must reference a defined source; omitting `source` uses
`default` only when a source with that ID exists. Source IDs are
Manifests support up to eight sources, 64 requests, and 64 options. A static widget can use empty `sources` and `requests`; every HTTP request must name an existing source. Source IDs are
case-insensitively unique. Each request allows up to 32 static headers and 32 invalidation targets; a widget can contain
up to 24 secrets, each up to 8,192 characters, and templates are limited to 50,000 characters. Validation reports the
exact field when a limit is exceeded.
@@ -47,7 +41,7 @@ before it reaches `data`, so treat it as untrusted input even when the source is
</Stack>
```
Bound values live only in React memory while the widget is mounted. They are not saved to the database, board options, exports, browser storage, or `localStorage`. Remounting resets them. Components can share a binding when their adapter types agree.
Without an explicit v3 `persist` binding, bound values live only in React memory while the widget is mounted. They are not saved to the database, board options, exports, browser storage, or `localStorage`. Remounting resets them. Components can share a binding when their adapter types agree.
Bindable controls accept a scalar `resetKey`. When it changes, Homarr restores that control to its declared `defaultValue` or `defaultChecked` without running a request. This keeps dependent pagination correct while a manual `SubFetch` waits for the user to submit the new query.
@@ -80,3 +74,38 @@ than one variable quantifier are rejected.
- `Icon`/`TablerIcon` resolves installed safe icons.
Always include responsive loading, empty, error, and success states. Runtime failures remain inside the widget tile.
## Version 3 capabilities
Use `$schema: "homarr-custom-widget-v3"` for `extensions`, integration options, scoped classes, and the components below. Version 2 definitions continue to render; opening them in the workbench does not upgrade their runtime schema. Editor positions are Homarr metadata and are excluded from the portable definition.
`extensions.stylesheet` accepts up to 30,000 characters. `className` references local classes; selectors and keyframe names are scoped per widget instance, including content opened through `WidgetModal` and `WidgetDrawer`. Use flat rules, `@media`, `@supports`, `@container`, and local `@keyframes`. Resource-loading CSS (`url()`, imports, fonts), global registration rules, and unresolved animation names are rejected. Theme CSS variables remain available. Inline style restrictions still apply.
Templates can read `theme.colorScheme`, `theme.primaryColor`, `theme.colors`, `theme.spacing`, `theme.radius`, and `theme.fontFamily`. `container.width` and `container.height` report the widget content size in CSS pixels, so responsive composition can follow its tile rather than the browser viewport.
Declare reusable JSX in `extensions.fragments` and render it with `<View name="metric" values={{ label: "CPU" }} />`. The fragment reads `props.label` and inherits the normal data bindings. Fragment names are literal, recursion is rejected, and all expansions share the interpreter's existing operation budget. Up to 32 fragments and 100,000 combined JSX characters are supported.
```json
{
"preferences": {
"filter": { "type": "string", "defaultValue": "" }
}
}
```
The fragment above belongs under `extensions`. A matching `<TextInput bind="filter" persist="filter" label="Filter" />` exposes the value through both `inputs.filter` and `preferences.filter`. Preferences are typed, scoped to the board item, and saved only in that browser; another account or device gets its own values. Preview preferences remain in memory. Exports include the declarations and defaults, never the user's saved values. Storage-disabled browsers retain an in-memory fallback. `resetKey` resets a persisted control to its declared preference default.
`WidgetModal` and `WidgetDrawer` require `title` and `triggerLabel`; Homarr owns their open/close behavior, focus handling, and portal boundary. They allow detailed views without authored callbacks.
Supported selects, menus, tooltips, and popovers use Homarr-owned dropdown targets to escape tile clipping while preserving
widget styles and the preview theme. Nested dropdowns stay within their parent overlay. Authored event handlers, refs, and
portal targets remain blocked; Mantine's own trigger handlers work through the component adapters.
`AppEmbed` requires an absolute HTTP(S) `src` and an accessible `title`. Its URL is reached by the browser, whereas HTTP sources are reached by the Homarr server; a Docker service hostname usually cannot be used for both. The embedded service must permit framing. The iframe uses an isolated origin and restricts navigation; apps requiring same-origin storage or unrestricted browser capabilities need their normal external link instead. `allowForms` explicitly enables embedded form submission.
`extensions.native` maps local IDs to curated Homarr capabilities. Integration-backed entries reference a saved `integration` option through `integrationOption`; the server applies the existing integration and board permissions. `<NativeQuery nativeId="systems">{(systems, meta) => <Text>{systems.length}</Text>}</NativeQuery>` uses the same loading/error behavior as `SubFetch`. Use `trigger="manual"` for invocation parameters and `live` for a supported subscription. Automatic results populate `data` and `status` under their native ID; manual results remain local to the component.
Native action entries require `kind: "action"`, `trigger: "manual"`, a `modify` or `full` permission, and a `confirmation` object containing `title` and `message`. Invoke them through `NativeActionButton`. Preview actions use the existing simulation mode; declaring an action does not authorize a live mutation. Native capability IDs and HTTP request IDs must be distinct.
The [Beszel systems studio definition](/custom-widgets/beszel-systems-studio-v3.json) combines systems, configurable columns, a saved system selection, historical charts, and live detail views. Select a local Beszel integration after importing it. The example uses `preferences` directly for values needed before a control mounts; `inputs` appears only after its bound control mounts. Live failures keep the last received event and expose `meta.stale` alongside Retry.
Shared editable content uses a separate `extensions.content` declaration with the same types/defaults as preferences plus `permission: "modify"` or `"full"`. `<Textarea bind="note" content="note" />` edits a local draft. `<ContentSaveButton name="note">Save note</ContentSaveButton>` commits it to the board item; `<ContentResetButton name="note">Reload note</ContentResetButton>` discards the draft and reloads the current shared value. Templates read `content.note` and `contentStatus.note` (`loading`, `dirty`, `saving`, `error`). Saves use the last read revision, so a stale draft cannot silently replace another saved value. Preview saves stay in memory; exports include declarations/defaults but exclude saved board content.
@@ -15,11 +15,9 @@ Custom Widgets may change during the v2 release cycle. Share feedback in the
:::
Custom Widgets supports [trusted widget packages](./trusted-packages) with full TSX, CSS, modules, optional Node
handlers, and advanced views, alongside the restricted v2 authoring format. Both can work without an API.
A **v2 Custom Widget** is a validated `homarr-custom-widget-v2` definition containing optional API sources, queries and actions,
optional settings, and a safe JSX template.
A **Custom Widget** is a validated definition with a safe JSX template, optional settings, and optional HTTP sources,
queries and actions. Existing definitions use `homarr-custom-widget-v2`; advanced composition and native capabilities use
`homarr-custom-widget-v3`. Static widgets need no API source.
Homarr executes requests on the server and renders the template in a restricted runtime. Source credentials are
encrypted separately and are not included in exports, prompts, browser data, or Workshop submissions.
@@ -40,8 +38,6 @@ boards; actions require authentication and the permission declared by the reques
## Authoring
- [Build a trusted widget package](./trusted-packages), configure local connections, and manage its Workshop releases.
- [Create a Custom Widget](./authoring) in the workbench or from a copied AI prompt.
- [Use the safe JSX runtime](./custom-jsx) for data bindings, temporary inputs, and components.
- [Browse the component reference](./component-reference).
@@ -54,7 +50,7 @@ and simulate relevant actions before saving. Live preview actions are opt-in bec
## Import and Workshop
Use **Import from Workshop** while adding board content or import a v2 JSON definition directly. Review the source,
Use **Import from Workshop** while adding board content or import a supported v2 or v3 JSON definition directly. Review the source,
requested permissions, API hosts, and actions before installation, then configure deployment-specific URLs and
credentials in Homarr.
@@ -62,5 +58,5 @@ Legacy definitions show **Migration required**. The migration prompt excludes cr
describe the visible behavior separately, import the returned v2 definition, and verify it before removing the archived
version.
Back up the database and `SECRET_ENCRYPTION_KEY` before upgrading or rolling back. Multi-replica installations must use
the same Redis service so cached responses invalidate consistently.
Keep `SECRET_ENCRYPTION_KEY` unchanged when updating Homarr so existing credentials remain readable. Multi-replica
installations must use the same Redis service so cached responses invalidate consistently.
@@ -0,0 +1,98 @@
# Native capabilities
V3 Custom Widgets can call a curated set of Homarr capabilities through `NativeQuery` and `NativeActionButton`.
These use the same integration procedures, caches, partial-failure responses, and permissions as their native counterparts.
A definition declares each capability explicitly; JSX cannot call arbitrary tRPC procedures.
## Available capabilities
| Capability | Behavior | Required input |
| ----------------------------------------------- | ------------------------------------------------------------------------------- | ---------------------------------------------------------- |
| `beszel.systems` | Systems overview, status, CPU, memory, disk, network and other reported metrics | None |
| `beszel.history` | Historical system and optional container statistics | `systemId`; optional `timePeriod`, `includeDocker` |
| `beszel.alerts` | Alerts and optional history | Optional `includeHistory`, `maxHistoryItems` |
| `beszel.live` | Initial short history or a live statistics stream | `systemId` |
| `calendar.events` | Calendar events from supported integrations | `year`, `month`; optional `releaseType`, `showUnmonitored` |
| `media.requests` | Media requests and partial integration errors | Optional `statuses`, `recentDays` |
| `media.stats` | Request totals and users | None |
| `media.respond` | Approve or decline a media request | `requestId`, `answer` |
| `smartHome.state` | Home Assistant entity state | `entityId` |
| `smartHome.details` | Entity state, attributes and timestamps | `entityId` |
| `smartHome.switch` | Toggle an entity | `entityId` |
| `smartHome.automation` | Trigger an automation | `automationId` |
| `docker.containers` | Container inventory and resource use | Optional `endpointIds` |
| `docker.start`, `docker.stop`, `docker.restart` | Control a container | `endpointId`, `containerId` |
Use `customWidget_nativeCapabilities` to discover the exact input schema for the installed Homarr version.
Docker capabilities retain the existing administrator requirement and endpoint capability checks.
## Declare and select an integration
```json
{
"$schema": "homarr-custom-widget-v3",
"name": "My systems",
"sources": {},
"requests": {},
"options": {
"beszel": {
"label": "Beszel integration",
"control": "integration",
"integrationKinds": ["beszel"],
"default": ""
}
},
"extensions": {
"native": {
"systems": {
"capability": "beszel.systems",
"integrationOption": "beszel",
"kind": "query",
"trigger": "load",
"permission": "view",
"input": {}
}
}
},
"template": "<NativeQuery nativeId=\"systems\">{(services) => <Stack>{services.map((service) => <Stack key={service.integrationId}><Text fw={600}>{service.integrationName}</Text>{service.systems.map((system) => <Text key={system.id}>{system.name}</Text>)}</Stack>)}</Stack>}</NativeQuery>"
}
```
Choose a local integration in the workbench, during installation, or in board configuration. Portable exports clear the
local selection. `integrationOption` reads saved configuration, not invocation parameters; a browser cannot replace the
integration ID by sending a different runtime input. An integration still needs to be accessible to the viewer under
Homarr's integration permissions. Placing a custom widget does not grant general integration access.
## Inputs, detail views and live data
A capability's `input` supports the same recursive `$option` and `$param` references as HTTP request bodies. Invocation
parameters are primitive values. Use `trigger: "manual"` when an input depends on a selected row or a temporary input;
load capabilities cannot depend on invocation parameters.
The workbench reads each installed capability's input schema and offers fixed values, saved-option bindings, and invocation
parameters. Switching an input to a parameter also switches its trigger to manual. Complex nested inputs retain a JSON
editor; scalar and list inputs do not require editing the extensions manifest.
Use `<NativeQuery nativeId="details" trigger="manual" params={{ systemId: inputs.systemId }}>` for a selected-system
query. For a declared `beszel.live` capability, add `live` to receive events. Historical and live responses retain the
underlying Beszel response shapes; a live event contains its event type and record. Compose those results with supported
charts, tables, fragments, modals, or drawers. Live subscriptions reconnect periodically to renew authorization and bounded
request capacity, and stop when their widget unmounts or a preview session expires.
## Actions and preview
Native actions require `kind: "action"`, `trigger: "manual"`, `permission: "modify"` or `"full"`, and a `confirmation`
object containing `title` and `message`. Render them with `NativeActionButton`. The server checks both board permission and
the native integration's interaction permission; Docker retains its administrator policy.
**Test and preview** runs declared load queries. Manual queries and actions are exercised through preview controls. Native
actions simulate until live preview actions are explicitly enabled. The journal records native entries as `native:<id>`;
preview-based creation requires current evidence for every declared HTTP and native capability.
Individual capability tests use the current preview session. Their parameter values and responses remain local to the
editor and are not saved into the definition. Action tests in the capability inspector always simulate; they are disabled
while the preview has live actions enabled. Use the rendered preview's confirmation flow to exercise live actions.
This is the initial native capability library. Other self-hosted services can use HTTP sources or browser embeds. Services
without an accessible HTTP interface, supported embed, or curated Homarr capability need an external bridge. Custom Widgets
do not run authored backend code, shell commands, imports, or arbitrary event callbacks.
@@ -1,104 +0,0 @@
---
title: Remote widget runners
sidebar_position: 8
---
A trusted widget server normally runs beside Homarr. The optional runner executes one installed widget package on
another machine. Use it when the data lives on a NAS filesystem, a separate Docker network, or a host with a database
or browser service that Homarr cannot reach. The runner has the privileges of the account starting it; its child
process provides cancellation and restart, not security isolation.
## Install a runner
Build an archive using `homarr widgets pack widget.json --trust`, copy the archive to the target machine, and run:
```sh
export HOMARR_WIDGET_RUNNER_TOKEN="$(openssl rand -hex 32)"
homarr widgets serve widget.homarr-widget.json --trust --host 127.0.0.1 --port 8787
```
The runner uses the compiled artifact and bundled JavaScript dependencies. It does not contact an npm registry or
accept package uploads. Restart it with a different archive to update its installed version. Keep the token in the
runner environment and Homarr's encrypted connection store. Use a private interface or an HTTPS reverse proxy when
Homarr runs on another machine. `127.0.0.1` identifies the machine or container running the runner.
In Homarr, create an HTTP connection with the runner's base URL and bearer token. Bind it to the package's named
`runner` connection. Only declared query, action, and subscription handlers are remotely callable. Migration
handlers remain local lifecycle operations. Homarr still authorizes the dashboard placement and its named handler
before calling the runner; the runner token represents the trusted Homarr caller.
## Call a remote handler
The local package's `server.ts` can forward to a handler installed on the runner:
```ts
import { callWidgetRunner, defineWidgetServer, subscribeWidgetRunner } from "@homarr/widget-sdk/server";
export default defineWidgetServer({
status: (input, context) => callWidgetRunner(context, { connection: "runner", handler: "status", input }),
activity: async function* (input, context) {
yield* subscribeWidgetRunner(context, { connection: "runner", handler: "activity", input });
},
});
```
Declare `status` as a query and `activity` as a subscription in both manifests. The remote package accesses its own
environment and filesystem. It has no automatic backchannel to Homarr's storage, native integrations, or connection
credentials. Put those operations in the local forwarding handler when needed.
The pull subscription transport waits up to ten seconds per read, buffers at most 32 values or 8 MiB, and closes
subscriptions that are not read for sixty seconds. Returning from an async generator completes the stream. Use
`context.signal` to release connections and stop work on cancellation.
## Apps without an HTTP API
An API request is optional. A widget may use only JSX, local browser state, a timer, or static information. Trusted
server handlers can read files, speak other protocols, or query a database using the runner's location and account.
For an application that writes a JSON status file, a remote handler can read that file:
```ts
import { readFile } from "node:fs/promises";
import { defineWidgetServer } from "@homarr/widget-sdk/server";
export default defineWidgetServer({
status: async (_input, context) => {
const path = process.env.APP_STATUS_FILE;
if (!path) throw new Error("Set APP_STATUS_FILE on the runner");
return JSON.parse(await readFile(path, { encoding: "utf8", signal: context.signal }));
},
});
```
For an application's SQLite database, Node 24 provides a built-in driver:
```ts
import { DatabaseSync } from "node:sqlite";
import { defineWidgetServer } from "@homarr/widget-sdk/server";
export default defineWidgetServer({
recentJobs: () => {
const path = process.env.APP_DATABASE;
if (!path) throw new Error("Set APP_DATABASE on the runner");
const database = new DatabaseSync(path, { readOnly: true });
try {
return database.prepare("SELECT name, status FROM jobs ORDER BY id DESC LIMIT 20").all();
} finally {
database.close();
}
},
});
```
Adapt the query to the application's actual schema. For PostgreSQL, MySQL, or MQTT, declare an exact version of a
JavaScript client dependency, bundle it when packing, and use the runner environment for service credentials. MQTT
subscriptions fit async generator handlers; close the broker client when the handler's signal aborts. Persistent
history belongs in Homarr's collection and history APIs or the application's database.
A browser-only application can be adapted through an existing browser automation service reachable from the runner.
Call that service from a server handler and return structured data to the tile. Browser binaries and native addons
are not shipped inside portable widget archives. Directly bundling a library that requires native addon loading is
rejected; use an independently installed service for that runtime dependency.
These paths enable adapters for many self-hosted applications. The application must still expose something the
runner can read or control, such as HTTP, a socket, a file, a database, or a browser session.
@@ -1,21 +1,21 @@
# Configure requests and security
Widgets can use empty `sources` and `requests` objects when they do not need an API. Connected widgets may use a source
named `default` or explicitly name the source on every request. Extra keyed sources are available for widgets
that combine APIs. Source IDs are case-insensitively unique. Base URLs must use HTTP(S), contain no embedded credentials,
HTTP widgets often use a source named `default`. Every request must reference an existing source; an omitted request source
resolves to `default`. Static and native-only widgets can use empty `sources` and `requests`. Extra keyed sources let widgets
combine APIs. Source IDs are case-insensitively unique. Base URLs must use HTTP(S), contain no embedded credentials,
query string, or fragment, and sources can be `public`, `private`, or `loopback`. Authentication is `none`, `bearer`,
`basic`, an API-key header, or an API-key query parameter. Credentials belong to the widget but remain outside its manifest.
Source origins are fixed by the definition and source-setup flow; widget options and invocation parameters cannot redirect a
request to a different origin.
Use `private` for LAN addresses, Docker service names, and Tailscale's `100.64.0.0/10` range. Use `loopback` for
`127.0.0.1` or `::1`. Requests run from Homarr: in Docker, loopback addresses point to the Homarr container, while a
service name such as `http://sonarr:8989` must resolve on its Docker network. Public sources cannot reach private or
loopback addresses. Cloud metadata, link-local, multicast, and other reserved targets remain blocked.
Source URLs are fetched by the Homarr server. In a container, `127.0.0.1` refers to that container; Docker service names such
as `sonarr` must resolve from Homarr. LAN addresses and loopback services are supported with the appropriate explicit scope.
The workbench suggests a likely local scope from the hostname; server DNS and redirect checks remain authoritative.
Browser navigation and app embeds use browser-reachable URLs instead.
## Named requests
Requests are keyed by ID. With a source named `default`, a load query can be as small as:
Requests are keyed by ID. `source`, `kind`, `method`, `trigger`, `auth`, and `permission` have sensible defaults, so a load query can be as small as:
```json
{ "status": { "path": "/api/status" } }
@@ -1,426 +0,0 @@
---
title: Trusted widget packages
sidebar_position: 2
tags: [Custom Widgets, JSX, Workshop]
---
# Trusted widget packages
Trusted packages let administrators write complete React/TSX modules, import CSS and dependencies, and optionally run
Node server handlers. A package can provide a dashboard tile, an advanced widget view, and a custom configuration
view. Static content, clocks, interactive local state, and other source-free widgets need no API connection.
Open **Management → Custom Widgets → Packages**. The source-free world clock is the default starter. Thirteen reference starters cover clocks, timers, checklists,
downloads, Sonarr, racks, backups, household controls, service overview, media, Beszel, SQLite, and MQTT. Each new widget receives
its own local package identity. The Beszel
reference package demonstrates a connected widget using Homarr's shared SDK and integration data.
## Trust and execution
Packages are trusted installed code. Browser modules run within Homarr; Node handlers have Homarr's server
privileges. Review the complete source and dependency list before checking the trust acknowledgement. Both
**Run preview** and **Activate saved draft** execute package code. An action simulation is not a security sandbox:
trusted code can make direct network requests and external changes outside the SDK.
Workshop browsing displays screenshots, source text, dependencies, and immutable release metadata. It does not run
package code. Importing a package creates a disabled draft. Connection credentials are entered separately on your
Homarr installation.
A supplied archive can include compiled browser and server code. Its digest verifies that those bytes are intact;
it does not prove they were built from the displayed source. Inspect **Compiled artifact** and the dependency lock
as well as the source before activating a supplied build. Rebuilding from reviewed source produces a new local
artifact; dependency installation happens during that build, never while rendering a dashboard.
## Package, installation, and placement
| Concept | Contains |
| ------------ | ------------------------------------------------------------------------------------------------------------- |
| Package | Portable manifest, source files, exact dependency versions, named connection requirements, option definitions |
| Installation | Saved source draft, active compiled release, previous activation, local connection bindings, enabled state |
| Placement | A tile on a board, its option values, connection overrides, board permissions, widget state |
One installation can appear on several boards. Activating it updates all its placements. A placement's saved option
values survive updates; changing package defaults does not overwrite those saved values.
## Customize a native widget
Administrators can choose **Customize as a widget package** from supported native widget menus. Homarr prepares a
reference package and reuses its existing integration connections. The original native widget remains on the board.
Save the new package, preview and activate it, then add its placement to the board. The package has its own identity
and can be edited independently of the native widget.
## Author a package
The workspace has a file explorer, TSX/CSS/JSON editor, a connection panel, activation and board controls, and a
preview canvas with adjustable width and height. Use `widget.json` to edit package metadata. This is a virtual view
of the package envelope excluding `files`; each source file is edited separately in the explorer.
Use **Add**, **Rename**, and **Remove** to organize source files. When renaming a file, update its imports and any
manifest entrypoints that reference the old path. JSX imports and ordinary React hooks are supported by the trusted
package compiler; the restricted v2 interpreter does not process these files.
The package envelope uses `$schema: "homarr-widget-package-v3"` and contains:
| Field | Purpose |
| -------------- | ------------------------------------------------------------------------------------ |
| `manifest` | Package identity, release version, SDK version, entrypoints, handlers, and metadata |
| `files` | Relative file paths mapped to source text |
| `dependencies` | Additional npm dependencies pinned to exact versions |
| `connections` | Named HTTP, Homarr integration, or service requirements; local bindings are separate |
| `options` | Controls, labels, defaults, and constraints for placement settings |
`manifest.entrypoints.tile` is required. `advanced`, `configuration`, and `server` are optional. Entrypoints must
refer to files in the package. A package with named server handlers needs a server entrypoint. The `manifest.id`
identifies the package across releases; `manifest.version` uses a complete semantic version such as `1.0.0`.
Homarr provides React, Mantine, and `@homarr/widget-sdk` as shared host modules. Referenced Tabler icons are bundled
from Homarr's installed version, which is recorded in the artifact lock. The reference packages show how to use the SDK for host dimensions, theme and locale, options, state, commands, data queries, and advanced
views. Put additional dependencies in the package's dependency map rather than copying Homarr's internal source tree.
Production images include the widget compiler's JavaScript, native esbuild executable, and bundled icon sources.
When customizing Homarr's standalone build, retain these runtime assets and scope tracing includes to their files;
whole-package recursive globs can fail on pnpm dependency directory symlinks.
Use `WidgetScope` to compose components with independent state and command IDs. Commands registered through
`useWidgetCommands` remain registered across unrelated host updates and are removed when their component unmounts.
`useWidgetServices().confirm(...)` resolves to `true` on confirmation and `false` on cancellation or dismissal,
including Escape, a backdrop click, or the close button.
## Convert an existing Custom JSX widget
Choose **Convert to a widget package** from a valid Custom JSX widget's list row or editor. Conversion uses its saved
definition and creates a separate disabled package. The original definition and its board placements remain in
place. Local connections and encrypted credentials are copied on the server, keeping them out of portable source.
The initial package retains a compatible JSX surface and options. Converted dynamic options remain available through
the authored configuration surface. Extend the package with TSX modules, CSS, or an advanced
view in the workspace. Review the generated files, preview, and explicitly activate the package before adding it
to a board. Conversion itself does not execute or replace the original widget. After activation, **Replace an
existing Custom JSX tile** lets you choose one original placement and explicitly replace it. Position, size, refresh
interval and configured values are retained; the original definition and other placements stay available. Use
**Add to board** when you want a separate tile instead.
## Assistant authoring
Choose **Ask Assistant** in the workspace to describe a widget or request changes. Shortcuts help improve the
current widget, add an advanced view, or fix current errors. This opens Homarr's existing Assistant; it uses the
visible unsaved draft, public SDK guidance, reference packages, and source validation diagnostics.
The Assistant reads source on demand. Local connection settings, bindings, credential fields, preview option
values, and runtime response data are excluded. Recognized credential literals are redacted from source context;
keep secrets in local connections. Files with redacted credentials must be edited directly before the Assistant can
replace them. Files omitted because a response reached its context budget must be read separately before proposing changes.
Individual files over 180,000 characters and manifests over 60,000 characters require direct editing.
Proposals display each changed file before and after in the Assistant. **Apply to draft** applies the complete
proposal as one Undo step. If the draft changes while a proposal is waiting, the Assistant must read it again and
propose against the new revision. Applying a proposal does not save, trust, preview, activate, or publish it.
Preview evidence identifies only the exact current candidate that compiled and received a preview session.
Compilation does not prove successful browser rendering or live actions. Source, option, and binding changes
invalidate that evidence; use the preview canvas to verify the final result before activation.
## Save, preview, and activate
Drag the divider between source and preview to resize the workspace. The divider also supports arrow keys,
Home/End, and double-click to reset. The preference is saved in your browser. On smaller screens, switch between
Code and Preview without unmounting the working preview.
The preview offers compact, wide, phone, and tablet viewport presets, independent width/height controls, and a
25–200% display scale. Scaling changes both the visual surface and the SDK's visible dimensions. Light and dark
preview modes stay local to the preview; they do not change your Homarr theme. These presentation controls do not
rebuild code, clear query data, or require another preview session.
The source editor understands the package's TypeScript and TSX files together. Press **Ctrl+Space** for typed
completions, hover a symbol for its type and documentation, or press **F12** to open its definition. Definitions
inside the installed SDK or its dependencies open as read-only excerpts. **F2** renames a symbol across package
files; the complete rename is one Undo operation. **Format** uses TypeScript formatting for TS/TSX files.
Semantic diagnostics appear in the editor and its expandable issue list. They use declarations generated from this
Homarr installation's actual SDK, React, Mantine, and Node dependencies. Include `.d.ts` files when another package
needs declarations that are not installed with Homarr. These editor diagnostics do not block saving a draft or
replace the preview compiler's runtime compatibility checks. Analysis runs in a local browser worker, without
executing your source or downloading code or types from a CDN.
For Homarr development, `pnpm dev` and the Next.js build regenerate the worker and installed declarations. After
editing SDK source while the dev server is already running, run `pnpm --filter @homarr/custom-widgets generate:editor`
and reopen the workspace. Generated assets are included in the standalone image's public directory.
1. **Save draft** persists the current source without building or executing it. Incomplete TSX and metadata JSON can
be saved for later repair. Saving a draft leaves the active dashboard release running.
2. Review the code and dependencies, acknowledge trust, and choose **Run preview**. The preview builds the current
editor contents and runs them in a temporary session. Select tile, advanced, or configuration view when provided.
**Preview options** controls the configuration used for this session.
3. Save your final changes, review the activation's placement count, then choose **Activate saved draft**. The server
validates and builds the saved source before switching the installation. Activation enables the installation.
4. Choose a board and configure the new placement under **Activation & boards → Add to board**.
Changing source, options, local preview bindings, or the live-action mode invalidates execution evidence for the previous candidate.
The last successful view remains visible with a stale label and paused SDK activity while you edit or fix a failed
build. Its session is released after a replacement loads successfully or the workspace closes. Re-run preview to
inspect the changed inputs. Pausing SDK activity does not sandbox arbitrary effects inside trusted code. Preview widget storage is temporary:
frontend storage hooks and server handlers share the same preview-session values, isolated from dashboard storage
and other preview sessions. Completing an action refreshes queries and managed storage in that preview.
SDK named actions are simulated by default. Enable **Allow live SDK actions for this preview session** and run
preview again to operate the real service through SDK actions. The session label shows its mode. Changing source,
bindings, or connection settings turns this option off. Direct behavior inside trusted code remains the owner's responsibility.
## Synthetic preview scenarios
Authors can include `previewScenarios` in package source to review success, loading and partial failures with
synthetic data. A scenario maps declared query handler names to JSON results or errors:
```json
{
"previewScenarios": {
"partialFailure": {
"label": "Storage unavailable",
"queries": {
"memory": { "data": { "usedPercent": 38 } },
"storage": {
"error": { "message": "Synthetic storage collector timeout", "code": "TIMEOUT" },
"delayMs": 700
}
}
}
}
}
```
Select a scenario when creating a preview. Its ID and the exact compiled source are stored in that preview session;
changing the scenario requires a new preview. Required local connections can remain unbound. Fixture queries return
the authored JSON without starting the package's server module or calling a configured service. A query without a
fixture fails explicitly; it never falls back to live data. Each handler receives the same fixture regardless of its
input. Declared input validation still applies.
SDK actions are simulated in fixture mode, and enabling live actions together with a scenario is rejected.
Subscriptions are unavailable in this bounded query-fixture mode. The SDK capability helper remains available so
action controls can display their simulated state. Production dashboard queries always execute the active package's
normal handlers; a preview scenario never changes an installation or its placements.
[Download the complete example](/custom-widgets/preview-scenarios.json) for two independent local metrics with ready,
delayed and partial-failure scenarios. It needs no API or local connection. Import the source, review trust, and
preview its named scenarios. Its ordinary handlers read local memory and filesystem metrics when used without a scenario.
Scenarios support up to 16 names, 64 query fixtures each, 2 MiB of total fixture JSON, and delays of up to 30 seconds.
Errors can use `BAD_REQUEST`, `NOT_FOUND`, `TIMEOUT` or `INTERNAL_SERVER_ERROR`; the latter is the default. Request
cancellation and discarding the session cancel pending fixture delays.
Fixtures are explicitly authored package source and are included in source exports, offline archives and Workshop
releases. Homarr does not capture live responses into scenarios. Use invented values and review fixture contents
before sharing. This is SDK simulation, not a security sandbox: trusted browser code can still make direct requests,
and compiling uncached dependencies can require registry access. Review source and acknowledge trust as usual.
## Local connections
The **Unified downloads** starter accepts a primary and optional second download integration. Each source has its
own queue, loading state, error and retry control, so a failed client leaves the other queue usable. Advanced view
adds filtering, sorting, per-client and per-item controls, and pause/resume for all or selected clients. Batch
results identify successful and failed clients individually. Per-item actions resolve the current item from the
selected client, and confirmed removal keeps downloaded files. The composed overview reuses the same modules.
Controls consult the current viewer's capabilities. Guests need an explicit grant for an exact input such as
`{"connection":"secondary","operation":"pause"}` on `control`; batch grants additionally list every target in
`connections`. No guest action is enabled merely by installing the starter.
Choose **Service** for MQTT, SQLite, SSH, local files or another protocol. Service connections require a
`serviceType` matching the package requirement, arbitrary nonsecret JSON settings, and optional encrypted
credentials. They do not require an HTTP URL. For example, declare
`{kind: "service", serviceType: "sqlite", label: "Database"}` in a package and bind a local connection with
settings such as `{"path":"/data/app.sqlite"}`. MQTT commonly uses `{"url":"mqtt://mosquitto:1883","topics":["sensors/#"]}`;
put its username and password in the encrypted credentials field. Leave that field blank to keep existing
credentials, or select **Replace saved credentials** to clear them explicitly.
Server handlers call `getWidgetConnection(context, {connection: "database", serviceType: "sqlite"})` from
`@homarr/widget-sdk/server` to obtain the local settings and secrets for a Node library. These credentials are
never returned by the browser connection API. Authors must keep this object server-side and return only the
data their widget needs. File paths resolve inside Homarr's container/process; mount the required files there
and give the Homarr process access. Use a remote runner when the adapter must execute on another machine.
Diagnostics report what they actually verify: SQLite/file connections check regular-file readability, and MQTT
connections check TCP reachability. Neither check claims database-query validity or MQTT authentication. Run
preview to exercise the real query or authenticated subscription. Other service types report configured settings
and require their adapter's preview for a protocol check. The **SQLite and local status** and **MQTT live topics**
starters include complete adapters; MQTT pins its reviewed `mqtt` dependency, while SQLite uses Node's built-in
module. Their package READMEs document connection settings, limits, cancellation and deployment details.
Declare named requirements in the package and bind them to reusable local connections in **Connections**. A
connection can point to an existing Homarr integration or an HTTP endpoint. HTTP setup supports a separate server
and browser URL, Basic authentication, bearer tokens, secret headers or query parameters, cookies, TLS verification, and a timeout.
Server requests originate from Homarr's server or container. Examples include `http://sonarr:8989`,
`http://192.168.1.20:8080`, and a Tailscale address. `127.0.0.1` addresses the network namespace running Homarr; it does
not address the dashboard viewer's browser or a different container. Enter full URLs including the protocol. For a bare address such as `sonarr:7573`, the connection form offers an
explicit **Use http://sonarr:7573** suggestion. Choosing it adds the protocol while preserving the supplied host,
port, and path; use HTTPS when required by the service.
**Diagnose** shows the reached stage, resolved addresses, HTTP status and timing, and top-level JSON field names
without response values. The primary result distinguishes name resolution, network, TLS, HTTP and authentication
failures; expand **Technical details** for the full diagnostic. **Save installation bindings** changes the defaults inherited by every placement.
Individual placements can override connections in their board configuration. **Edit connection** updates a reusable
connection for every widget that uses it. Empty credential fields retain stored credentials; changing authentication
requires entering the credentials for the new method.
For Basic authentication, you can update the username or password independently: leaving the other field blank
preserves its saved value. Updating a bearer token, cookie, username, or password also preserves a saved TLS private key.
Connection credentials are encrypted in Homarr's database. Connection forms and their credential fields are not
included in the package editor's Undo/Redo or browser recovery. Keep credentials out of source files: source files
are portable and can be exported or published.
## Recovery and operational rollback
Disabling an enabled guest action does not depend on the validity of its edited input JSON. You can revoke access
immediately from the action's Disable control while repairing those inputs.
Activation also coordinates with widget settings, board saves, additions, and board duplication. If a package
changes while one of these saves is waiting, Homarr asks you to reload before saving again so an older
configuration cannot overwrite its migration. Changing a placement's connection overrides invalidates guest
action approvals tied to the previous bindings.
**Undo/Redo** covers the whole source document: metadata, files, and installation name. History is bounded to 100
entries and 2 MB in the current editor session. **Reset to saved** restores the saved draft. Homarr keeps one browser
recovery draft per signed-in owner, up to 1 MB, and offers to restore it when opening the matching package.
Recognized credential literals are redacted from recovery source; use connection fields for secrets.
Package release history is separate from editor Undo/Redo. **Roll back previous activation** restores the previous
compiled release and its activation snapshot of local bindings, placement options, and widget data. You must
acknowledge discarding newer widget data. Calls already made to an external service cannot be reversed by rollback.
Your source draft remains available for further work.
**Disable installation** stops that installation across all placements. It is independent of saving a source draft.
## Import, export, fork, and update
**Import package** accepts source JSON or a `homarr-widget-archive-v3` archive. Archives contain source plus a compiled
artifact; compatible matching artifacts can be activated without rebuilding dependencies. Imports create disabled
drafts for review. **Export source draft** exports current editor contents, including incomplete work.
**Export active archive** exports the activated release and its compiled artifact. Local connection credentials and
board placements are not part of these exports.
**Stage archive update** replaces the installation's saved draft after explicit acknowledgement and keeps its active
release running. **Review saved draft changes** shows changed files before and after, dependency changes, connection
requirements, and configuration changes. **Fork as a new package** copies saved source to a new disabled installation
with a new package identity; it does not change the original installation's board placements.
## Portable widget collections
A `homarr-widget-collection-v1` archive groups several independent packages with named shared connection slots.
Import binds a slot once and fans it out to every member that needs it. All imported packages start as disabled
drafts; importing does not install dependencies or execute widget code. Each package keeps its own identity,
activation, updates, settings and dashboard placements.
The complete collection is validated before creating installations. Invalid member code checksums, mismatched
connection types or invalid portable option defaults reject the import with no new installations. Installation
records are committed together; immutable artifact cache entries from a database failure may remain until cleanup.
Export uses the selected installations' activated archives. Shared local bindings become named requirements, while
their connection IDs, URLs and credentials stay local. Export also excludes placement settings and widget storage.
Only explicit authored defaults belong in the portable blueprint. Workshop and fork attribution is retained, and
normal package updates retain the collection's membership and connection mapping. Review code literals before
sharing, since package source is exported verbatim.
From the installed package library, choose **Collections** to export selected active packages or resume an imported
collection. Import its JSON archive using **Import**. The setup page asks for shared connections once, lets you
choose widgets and their options, and activates the selected packages after you acknowledge trust. **Activate and
add missing widgets** places them on the selected board. Each member reports its own result, and retrying skips
placements already present on that board. You can stop after the current member finishes.
See the [collection CLI commands](../../advanced/command-line/index.mdx#share-several-widgets-as-a-collection) for
packing, validation and importing through an admin API key. Collections support up to 32 widgets and 128 MiB.
## Workshop lifecycle
In Workshop, select a release, inspect source files and dependencies, and optionally bind its named connections.
**Import for review** opens the package workspace with a disabled local installation. Preview and activate it after
reviewing trust, then add it to a board.
The **Packages** library shows each installation’s version, author, and **View on Workshop** link. Choose
**Check for updates**, then **Review update** to load a release into the editor. If your saved draft has local
changes, confirm its replacement first. The active release continues running until you activate the reviewed draft.
Use **Duplicate** or export local changes you want to keep before replacing them.
Choose **Publish to Workshop** from the package’s action menu or its editor. Packages and Custom JSX widgets use the
same publishing form: sign in, add a title, description, and optional screenshots, then publish. The signed-in Workshop
account receives attribution. Homarr updates your existing listing or creates an attributed copy of another author’s
package automatically. **Release details** contains the version and optional release notes; updates suggest the next
patch version. Review source, dependencies, and fixtures before publishing. Local bindings and credentials remain
on the Homarr installation.
The management sidebar can collapse to icons using its toggle. It collapses automatically in the package editor to
leave more room for code and preview; expand it whenever you need the full labels. On mobile, use the header menu.
## Reference packages with local services
**Sonarr operations** supports two native Sonarr connections, upcoming and missing episodes, queue progress, source
filtering, and confirmed episode-search actions. Compact view shows four rows; the advanced view shows all loaded
rows with text filtering. Each server contributes up to 100 missing or queued episodes. An unavailable second
server does not hide the primary server's results. Searching requires native integration interaction access and
submits a Sonarr command; a queued command does not prove an eligible release was found or downloaded.
**Filesystem backup monitor** reads backup metadata and an optional JSON status report mounted into Homarr. Its
README contains the success/failure/running report format, timestamps, duration, size and retained run history.
The optional **Run backup** action uses a fixed executable and argument array deliberately configured in
`command.ts`. It runs through Node `execFile` without a shell, requires full placement permission, and never accepts
command text from the browser. Preview simulates it. Mount the executable into Homarr, then review and activate its
configuration. Backup activity and status reports do not verify restore integrity.
**Media and camera wall** combines native media sessions with optional authenticated camera snapshots and an Immich
image gallery. Camera paths share a bound HTTP connection; its credentials stay on the server. Immich uses a secret
`x-api-key` header with `asset.read` and `asset.view`. The package fetches images server-side and returns bounded
image data to the widget. It supports up to eight camera snapshots and twelve Immich thumbnails. Clicking an image
opens the advanced view with shared selection. Camera snapshots poll; this reference does not stream RTSP or other
continuous video, and individual images must remain under 675 KiB.
## Optional history collection
A placement’s **History collection** shows its latest retained sample and time. Expand the sampled-point table for
recent values or **Technical details** for the stored record.
Expand a placement’s **History collection** to select a named query handler, input JSON, value path, unit, sampling
interval, retention period, and maximum sample count. Collection is disabled by default. Enabling it runs the query
on Homarr’s server even when the dashboard is closed. Pause it without deleting samples, or explicitly discard
the collection and its history. The collection panel shows recent samples and request errors; package code can
consume retained history through the widget SDK.
## Guest actions
A package can declare a named action as available for guest grants. Under a placement's **Guest actions**, the owner
enables that specific handler for an explicit JSON array of permitted inputs. Other inputs remain denied. Changing
server code, dependencies, or bound connection configuration invalidates the grant and requires owner renewal.
Board access and the package's declared permissions still govern normal authenticated usage.
## Repair a v2 widget
The existing restricted v2 workbench remains available from the installed widgets tab. Invalid v2 definitions expose
**Repair widget**, which shows validation issues and editable source without changing the widget's dashboard ID.
Save repaired source or export a repair draft. Credentials are retained only when the original source and
authentication binding remain unchanged; configure credentials again when those bindings change.
## Build cache maintenance
Administrators can call `customWidget.package.cleanupArtifacts` through the authenticated API. Start with
`{ "dryRun": true }` to inspect candidate artifact IDs and local directories, then call it with `dryRun: false` to
remove those that are still unused. Cleanup preserves active and previous releases, every valid saved source draft
(including disabled offline imports), and artifacts leased by recent imports, builds or previews. Unreferenced data
must be at least seven days old. Preview sessions themselves expire after one hour.
Each call removes at most 100 database artifacts and 20 local directories by default. Adjust `maximumArtifacts`
(up to 500) and `maximumDirectories` (up to 100), or repeat when the result reports `limited: true`. Directory cleanup
applies to the current Homarr replica's runtime and dependency cache. Other replicas can clean their own local cache
through the same procedure. Cleanup coordinates reference changes across replicas and never invokes package code.
This is explicit maintenance; no automatic build-cache cleanup job is enabled.
For an external editor workflow with normal files, local previews and immutable release publishing, see the
[widget CLI commands](../../advanced/command-line/index.mdx#build-and-share-custom-widget-packages).
Each server worker runs at most eight handlers concurrently and queues at most 64 more for up to 30 seconds.
Extra requests receive a capacity error; one failing source does not block successful results from other requests.
## Webhook lifecycle and advanced links
Each placement can issue a separate token for a named action with an input schema. Homarr displays the POST URL and
bearer token once. Tokens stay outside source drafts, recovery and exports. Code or local binding changes invalidate
existing tokens; create a new one for the updated placement. Explicitly revoked tokens remain revoked after rollback.
The webhook accepts JSON matching the action schema, up to 1 MiB, and runs with its owner's current authorization.
A board URL can link directly to an installed widget's advanced view using `#widget=<placementId>`. The viewer still
needs access to the board and widget. This opens the dashboard widget surface rather than a standalone app route.
-12
View File
@@ -20,15 +20,3 @@ Each task exposes:
![The scheduled Tasks management page](../img/tasks.png)
Disabling a task stops scheduled runs but does not prevent a manual run.
## Widget history collectors
Trusted widget installations can opt into background sampling from their **Activation & boards** workspace tab.
Each collector names a declared query, input, optional response field, interval, and retention limit. Collection is
separate from viewer refresh; Redis admits one sampling run per interval across serving replicas. New collectors are
disabled until the owner enables them. The owner must retain administrator access for collection to continue.
The production application schedules enabled collectors while it is running, including when no dashboard is open.
Each series is bounded by its configured retention/sample count and a 1 MiB managed record limit. Pausing a collector
stops requests. Removing it explicitly removes its retained series. Application history APIs remain preferable when
available because Homarr cannot collect observations while it is offline.
+3 -2
View File
@@ -18,8 +18,9 @@ password. Decimal units are the default. Change them from the user form or **Com
Preferences → Data size units**. Byte rates follow the same preference; bit rates stay decimal and use labels such as
Mb/s. Deleting a user does not delete boards they created.
In demo mode (`DEMO_MODE=true`), user deletion and password changes are disabled for everyone, including administrators,
even when `DEMO_READ_ONLY=false` allows other changes. This applies to the UI and API.
In demo mode (`DEMO_MODE=true`), user deletion, password changes, and local username changes are disabled for everyone,
including administrators, even when `DEMO_READ_ONLY=false` allows other changes. With demo editing enabled, other
profile preferences remain editable. This applies to the UI and API.
![The Users management page](../img/users.png)
+1 -1
View File
@@ -12,7 +12,7 @@ import { appWidget } from ".";
<WidgetHeader widget={appWidget} categories={["Links", "Apps"]} />
The App widget opens an application or website and can show whether Homarr can reach it. Configure the target and status
check from the tile's edit actions.
check from the tile's edit actions. In view mode, right-click uses the browser's link menu; Homarr's widget menu remains available in edit mode.
### Adding the widget
@@ -22,6 +22,8 @@ one-row widgets. Horizontal, vertical, compact-grid, and icon-only layouts keep
preserves its configured columns when the dashboard is scaled. Bookmark cards, icons, text, and gaps keep the same
visual density when a low-column dashboard is enlarged to fill the screen.
Right-click a bookmark link in view mode to use the browser menu, including opening it in a new tab or copying its address.
### Screenshots
import gridIconsOnly from "./img/grid-icons-only.png";
@@ -41,6 +41,7 @@ import temperature from "./img/temperature.png";
### Interactions
- Toggle entity state by clicking on the entity (only when clickable enabled).
- After a successful toggle, the displayed state refreshes immediately.
- If Homarr cannot refresh an entity, the last known state stays visible but toggling is disabled until the connection recovers.
<WidgetInteractionGuide />
@@ -51,4 +51,6 @@ import withDisplayname from "./img/with-displayname.png";
### Configuration
Use the Home Assistant entity ID (for example, `automation.turn_on_lights`) in the **Automation ID** field, not the automation's internal ID.
<WidgetConfig configuration={smartHomeExecuteAutomationWidget.configuration} />
+27 -9
View File
@@ -31,19 +31,37 @@ from Custom Widget and CSS submissions.
- Install a Custom Widget from **Management → Custom Widgets → Import from Workshop**.
- Import dashboard CSS from **Board settings → Custom CSS → Import from Workshop**.
Custom Widget credentials are configured in your Homarr instance and are not part of the Workshop submission.
Custom Widget credentials stay in your Homarr instance. Ordinary installation does not load the workbench; **Remix in
workbench** installs a separate local widget and opens its draft. Widgets without data sources need no URL or credentials.
Installation records the Workshop endpoint, submission, revision, and content fingerprint. A JSON file import has no
Workshop identity, even when its name matches a submission. Editor layout and credentials are not part of the portable
definition. Native integration selections are also local: exports clear their default IDs, and installation binds them
to existing integrations in your instance. Leaving a selection empty defers setup to each board widget's configuration.
## Updates and rollback
The workbench's Workshop panel compares a linked installation with its latest revision. Applying an update preserves
local service URLs, network scopes, and credentials. Changed source identities or authentication destinations require
installing a separate copy. Locally modified definitions also require a separate copy; Homarr does not merge authored JSX.
Compatible native integration selections are retained; new options and options whose allowed integration kinds change
start unconfigured. The review also includes shared-content declarations and their write permissions. Stored board content
and each user's preferences remain in Homarr and are not included in a submission.
Each update retains one previous installed package for rollback. Rollback restores the definition, preserves current
service URLs and credentials, and works without contacting Workshop. It refuses changed source authentication bindings.
Changing the configured Workshop endpoint disables upstream updates for installations linked to the previous endpoint.
## Publish content
Publish a saved Custom Widget from its action menu under **Management → Custom Widgets**. Custom CSS and manual
submissions can be published from the Workshop website.
Trusted v3 packages use the same publishing form, with attribution from your signed-in Workshop account.
Homarr selects a new listing, an update to your listing, or an attributed copy automatically. Version and optional
release notes are under **Release details**. Find version indicators, **Check for updates**, and **View on Workshop**
in the **Packages** library.
Publish a saved Custom Widget from its action menu or workbench. The reviewed saved definition must still match when
publication starts. Updating a linked submission requires its Workshop author account and preserves its identity,
screenshots, votes, and comments. A remix creates a new submission with attribution. Publishing succeeds independently of
linking the resulting submission back to your local widget; a linking failure must not be retried as a new publication.
Trusted v3 packages publish immutable releases. When editing a release and its screenshots together, Homarr validates
the screenshot count before publishing, so an invalid screenshot edit does not consume the proposed package version.
Custom JSX v2 remains supported. Scoped styles, fragments, preferences, shared content, and native capabilities use
`homarr-custom-widget-v3`; Workshop clients and the Workshop service must support that schema before publishing or
updating such submissions. Custom CSS and manual submissions can be published from the Workshop website.
Sign in to the Workshop and open **Yours** to update or delete submissions and review reports. Signed-in users can vote,
comment, and report content; Workshop moderators can remove content. Workshop moderation is separate from administration
@@ -305,9 +305,7 @@ const MarketplaceDetail = ({ workshopUrl }: { workshopUrl: string }) => {
const widgetDefinition = useMemo<HomarrCustomWidgetV2 | null>(() => {
if (submission?.type !== "customWidget") return null;
const result = validateSubmissionContent("customWidget", submission.content);
if (!result.success || typeof result.data !== "object" || result.data.$schema !== "homarr-custom-widget-v2")
return null;
return result.data;
return result.success && typeof result.data === "object" ? result.data : null;
}, [submission]);
const handleVote = async (value: 1 | -1) => {
@@ -50,7 +50,7 @@ const placeholders: Record<SubmissionType, string> = {
customCss: ".grid-stack-item-content {\n border-radius: 16px;\n}",
};
const contentLabels: Record<SubmissionType, string> = {
customWidget: "Widget JSON (homarr-custom-widget-v2)",
customWidget: "Widget JSON (homarr-custom-widget-v2 or v3)",
customCss: "Custom CSS",
};
@@ -314,7 +314,7 @@ const typeCards: { type: SubmissionType; icon: typeof IconBraces; label: string;
type: "customWidget",
icon: IconBraces,
label: "Custom Widget",
desc: "A JSON-based widget using the homarr-custom-widget-v2 schema",
desc: "A JSON-based widget using the homarr-custom-widget-v2 or v3 schema",
},
{
type: "customCss",
+1 -2
View File
@@ -1,5 +1,4 @@
import { CUSTOM_WIDGET_SCHEMA, type HomarrCustomWidgetV2 } from "@homarr/custom-widgets/core";
import type { CustomWidgetPackage } from "@homarr/custom-widgets/package";
import {
MAX_WORKSHOP_CSS_LENGTH,
type WorkshopSubmissionType,
@@ -13,7 +12,7 @@ export const CSS_SCHEMA_VERSION = WORKSHOP_CSS_SCHEMA;
export const MAX_CSS_LENGTH = MAX_WORKSHOP_CSS_LENGTH;
export type WorkshopValidationResult =
| { success: true; data: HomarrCustomWidgetV2 | CustomWidgetPackage | string }
| { success: true; data: HomarrCustomWidgetV2 | string }
| { success: false; error: string };
export const schemaVersionByType = {
+2 -1
View File
@@ -2304,7 +2304,8 @@
"traefik",
"customApi",
"assistant",
"wud"
"wud",
"llamacpp"
]
},
"options": {
@@ -0,0 +1,75 @@
{
"$schema": "homarr-custom-widget-v3",
"name": "Beszel systems studio",
"description": "Systems overview, configurable columns, selected-system history and live details using your existing Beszel integration. No HTTP source or copied API token required.",
"sources": {},
"requests": {},
"options": {
"beszel": {
"label": "Beszel integration",
"control": "integration",
"integrationKinds": ["beszel"],
"default": ""
}
},
"extensions": {
"stylesheet": ".metric { padding: 14px; border-radius: 12px; background: var(--mantine-color-default-hover); } .system-table { font-variant-numeric: tabular-nums; }",
"preferences": {
"system": {
"type": "string",
"defaultValue": ""
},
"period": {
"type": "string",
"defaultValue": "1h"
},
"columns": {
"type": "string[]",
"defaultValue": ["cpu", "memory", "disk"]
}
},
"fragments": {
"metric": "<Stack className=\"metric\" gap={2}><Text size=\"xs\" c=\"dimmed\">{props.label}</Text><Text fw={700} size=\"xl\">{Number(props.value ?? 0).toFixed(1)}{props.suffix ?? \"%\"}</Text></Stack>",
"containers": "<Stack gap=\"xs\">\n <Text size=\"xs\" c=\"dimmed\">{props.items.length} containers \u00b7 {Date.toLocaleTimeString(props.updatedAt)}</Text>\n {!props.items.length && <Text c=\"dimmed\">No containers reported.</Text>}\n {props.items.length > 0 && <ScrollArea><Table striped highlightOnHover>\n <Table.Thead><Table.Tr><Table.Th>Container</Table.Th><Table.Th>CPU</Table.Th><Table.Th>Memory</Table.Th><Table.Th>Sent</Table.Th><Table.Th>Received</Table.Th></Table.Tr></Table.Thead>\n <Table.Tbody>{props.items.map((row) => <Table.Tr key={row.n}>\n <Table.Td><Text fw={500}>{row.n}</Text></Table.Td>\n <Table.Td>{Number(row.c ?? 0).toFixed(1)}%</Table.Td>\n <Table.Td>{Number(row.m ?? 0).toFixed(1)} MiB</Table.Td>\n <Table.Td>{Number((row.b?.[0] ?? (row.ns ?? 0) * 1048576) / 1024).toFixed(1)} KiB/s</Table.Td>\n <Table.Td>{Number((row.b?.[1] ?? (row.nr ?? 0) * 1048576) / 1024).toFixed(1)} KiB/s</Table.Td>\n </Table.Tr>)}</Table.Tbody>\n </Table></ScrollArea>}\n</Stack>"
},
"native": {
"systems": {
"capability": "beszel.systems",
"integrationOption": "beszel",
"kind": "query",
"permission": "view",
"trigger": "load",
"input": {}
},
"history": {
"capability": "beszel.history",
"integrationOption": "beszel",
"kind": "query",
"permission": "view",
"trigger": "manual",
"input": {
"systemId": {
"$param": "systemId"
},
"timePeriod": {
"$param": "period"
},
"includeDocker": true
}
},
"live": {
"capability": "beszel.live",
"integrationOption": "beszel",
"kind": "query",
"permission": "view",
"trigger": "manual",
"input": {
"systemId": {
"$param": "systemId"
}
}
}
}
},
"template": "<NativeQuery nativeId=\"systems\" refreshInterval={30}>{(services) => (\n <Stack p=\"md\" gap=\"md\">\n <Group justify=\"space-between\"><Title order={3}>Systems</Title><Badge variant=\"light\">{services.flatMap((service) => service.systems).length} hosts</Badge></Group>\n <Group grow align=\"flex-start\">\n <TextInput label=\"Filter systems\" bind=\"filter\" />\n <Select label=\"Selected system\" bind=\"system\" persist=\"system\" searchable clearable data={services.flatMap((service) => service.systems.map((system) => ({ value: system.id, label: system.name })))} />\n <MultiSelect label=\"Visible columns\" bind=\"columns\" persist=\"columns\" data={[{value:\"cpu\",label:\"CPU\"},{value:\"memory\",label:\"Memory\"},{value:\"disk\",label:\"Disk\"}]} />\n </Group>\n {services.map((service) => <Stack key={service.integrationId} gap=\"xs\">\n <Group justify=\"space-between\"><Text fw={600}>{service.integrationName}</Text><Text size=\"xs\" c=\"dimmed\">Updated {Date.toLocaleTimeString(service.updatedAt)}</Text></Group>\n {service.error && <Alert color=\"yellow\" title=\"Integration unavailable\">{service.error}</Alert>}\n <ScrollArea><Table className=\"system-table\" striped highlightOnHover>\n <Table.Thead><Table.Tr><Table.Th>System</Table.Th><Table.Th>Status</Table.Th>{preferences.columns.includes(\"cpu\") && <Table.Th>CPU</Table.Th>}{preferences.columns.includes(\"memory\") && <Table.Th>Memory</Table.Th>}{preferences.columns.includes(\"disk\") && <Table.Th>Disk</Table.Th>}</Table.Tr></Table.Thead>\n <Table.Tbody>{service.systems.filter((system) => !inputs.filter || system.name.toLowerCase().includes(inputs.filter.toLowerCase())).map((system) => <Table.Tr key={system.id}>\n <Table.Td><Text fw={600}>{system.name}</Text><Text size=\"xs\" c=\"dimmed\">{system.hostname}</Text></Table.Td>\n <Table.Td><Badge variant=\"light\">{system.status}</Badge></Table.Td>\n {preferences.columns.includes(\"cpu\") && <Table.Td>{Number(system.cpu ?? 0).toFixed(1)}%</Table.Td>}\n {preferences.columns.includes(\"memory\") && <Table.Td>{Number(system.memory ?? 0).toFixed(1)}%</Table.Td>}\n {preferences.columns.includes(\"disk\") && <Table.Td>{Number(system.disk ?? 0).toFixed(1)}%</Table.Td>}\n </Table.Tr>)}</Table.Tbody>\n </Table></ScrollArea>\n {!service.systems.length && !service.error && <Text c=\"dimmed\">No systems reported.</Text>}\n </Stack>)}\n {!preferences.system && <Text size=\"sm\" c=\"dimmed\">Select a system to open historical and live details.</Text>}\n {preferences.system && <WidgetDrawer title=\"Selected system\" triggerLabel=\"Open system details\" size=\"xl\">\n <Stack gap=\"md\">\n {services.flatMap((service) => service.systems).filter((system) => system.id === preferences.system).map((system) => <Stack key={system.id}>\n <Title order={3}>{system.name}</Title><Text size=\"sm\" c=\"dimmed\">{system.osName} \u00b7 {system.cpuModel} \u00b7 {system.cores} cores</Text>\n <SimpleGrid cols={{base:1,sm:3}}><View name=\"metric\" values={{label:\"CPU\",value:system.cpu}}/><View name=\"metric\" values={{label:\"Memory\",value:system.memory}}/><View name=\"metric\" values={{label:\"Disk\",value:system.disk}}/></SimpleGrid>\n </Stack>)}\n <Select label=\"History period\" bind=\"period\" persist=\"period\" data={[{value:\"1h\",label:\"Last hour\"},{value:\"12h\",label:\"12 hours\"},{value:\"24h\",label:\"24 hours\"},{value:\"1w\",label:\"Week\"},{value:\"30d\",label:\"30 days\"}]} />\n <NativeQuery nativeId=\"history\" params={{systemId:preferences.system,period:preferences.period}}>{(history) => <Stack>\n <Text fw={600}>Resource history</Text>\n {!history.systemStats.length && <Text c=\"dimmed\">No history in this period.</Text>}\n {history.systemStats.length > 0 && <LineChart h={230} data={history.systemStats.slice().sort((a,b) => a.created.localeCompare(b.created)).map((point) => ({time:Date.toLocaleTimeString(point.created),cpu:point.stats.cpu,memory:point.stats.mp,disk:point.stats.dp}))} dataKey=\"time\" series={[{name:\"cpu\",color:\"blue.6\"},{name:\"memory\",color:\"violet.6\"},{name:\"disk\",color:\"teal.6\"}]} withLegend unit=\"%\" />}\n <Text fw={600}>Latest container statistics</Text>\n {!history.containerStats.length && <Text c=\"dimmed\">No container history in this period.</Text>}\n {history.containerStats.slice().sort((a,b) => b.created.localeCompare(a.created)).slice(0,1).map((record) => <View key={record.id} name=\"containers\" values={{items:record.stats,updatedAt:record.created}} />)}\n </Stack>}</NativeQuery>\n <NativeQuery nativeId=\"live\" live params={{systemId:preferences.system}}>{(event,meta) => <Stack gap=\"xs\">\n <Group><Text fw={600}>Live event</Text>{meta.stale && <Badge color=\"yellow\">Last received data</Badge>}</Group>\n Line truncated
}
+1 -1
View File
@@ -1 +1 @@
{"schemaVersion":1,"mantineVersion":"9.6.0","customWidgetVersion":"2.0.0","types":["\"\" | \"anonymous\" | \"use-credentials\"","\"-moz-initial\" | \"inherit\" | \"initial\" | \"revert\" | \"revert-layer\" | \"unset\" | \"auto\" | \"fixed\"","\"-moz-initial\" | \"inherit\" | \"initial\" | \"revert\" | \"revert-layer\" | \"unset\" | \"none\" | \"auto\" | \"all\" | \"fill\" | \"stroke\" | \"painted\" | \"visible\" | \"visibleFill\" | \"visiblePainted\" | \"visibleStroke\"","\"-moz-initial\" | \"inherit\" | \"initial\" | \"revert\" | \"revert-layer\" | \"unset\" | \"none\" | \"block\" | \"inline\" | \"both\" | \"horizontal\" | \"vertical\"","\"-moz-initial\" | \"inherit\" | \"initial\" | \"revert\" | \"revert-layer\" | \"unset\" | \"none\" | \"contain\" | \"cover\" | \"fill\" | \"scale-down\"","\"-moz-initial\" | \"inherit\" | \"initial\" | \"revert\" | \"revert-layer\" | \"unset\" | \"wrap\" | \"nowrap\" | \"wrap-reverse\"","\"12h\" | \"24h\"","\"activity\" | \"display-none\"","\"all\" | \"parent\" | \"child\"","\"all\" | \"segment\"","\"always\" | \"hover\" | \"not-hover\" | \"never\"","\"area\" | \"radial\" | \"scatter\"","\"auto\" | \"scroll\" | \"always\" | \"hover\" | \"never\"","\"auto-fit\" | \"auto-fill\"","\"block\" | \"grid\"","\"both\" | \"rightSection\" | \"clear\"","\"bottom\" | \"top\"","\"bottom\" | \"top\" | \"baseline\" | \"middle\"","\"bottom\" | \"top\" | \"middle\"","\"bottom-end\" | \"bottom-start\" | \"top-end\" | \"top-start\" | \"bottom-center\" | \"top-center\" | \"middle-center\" | \"middle-end\" | \"middle-start\"","\"button\" | \"submit\" | \"reset\"","\"center\" | \"bottom\"","\"center\" | \"left\" | \"right\"","\"center\" | \"left\" | \"right\" | \"justify\" | \"char\"","\"center\" | \"side\" | \"merge\"","\"checkbox\" | \"radio\"","\"dashed\" | \"dotted\" | \"solid\"","\"default\" | \"gradient\"","\"default\" | \"responsive\"","\"default\" | \"stacked\" | \"percent\" | \"split\" | \"stream\"","\"default\" | \"stacked\" | \"percent\" | \"waterfall\"","\"div\" | \"label\"","\"end\" | \"start\"","\"filled\" | \"light\"","\"fixed\" | \"absolute\"","\"hex\" | \"hexa\" | \"rgba\" | \"rgb\" | \"hsl\" | \"hsla\"","\"horizontal\" | \"vertical\"","\"hover\" | \"click\"","\"hover\" | \"click\" | \"click-hover\"","\"inherit\" | \"auto\" | \"baseline\" | \"before-edge\" | \"text-before-edge\" | \"middle\" | \"central\" | \"after-edge\" | \"text-after-edge\" | \"ideographic\" | \"alphabetic\" | \"hanging\" | \"mathematical\"","\"inherit\" | \"auto\" | \"sRGB\" | \"linearRGB\"","\"inherit\" | \"auto\" | \"text-before-edge\" | \"middle\" | \"central\" | \"text-after-edge\" | \"ideographic\" | \"alphabetic\" | \"hanging\" | \"mathematical\" | \"use-script\" | \"no-change\" | \"reset-size\"","\"inherit\" | \"end\" | \"start\" | \"middle\"","\"inherit\" | \"nonzero\" | \"evenodd\"","\"inherit\" | \"round\" | \"butt\" | \"square\"","\"inherit\" | \"round\" | \"miter\" | \"bevel\"","\"initial\" | \"medial\" | \"terminal\" | \"isolated\"","\"inside\" | \"outside\"","\"left\" | \"right\"","\"left\" | \"right\" | \"bottom\" | \"top\"","\"left\" | \"right\" | \"bottom\" | \"top\" | \"left-end\" | \"left-start\" | \"right-end\" | \"right-start\" | \"bottom-end\" | \"bottom-start\" | \"top-end\" | \"top-start\"","\"left\" | \"right\" | \"inside\"","\"link\" | \"none\" | \"copy\" | \"execute\" | \"move\" | \"popup\"","\"media\" | \"container\"","\"month\" | \"year\" | \"decade\"","\"native\" | \"scrollarea\"","\"none\" | \"all\" | \"rows\" | \"groups\" | \"columns\"","\"none\" | \"all\" | \"with-indicators\"","\"none\" | \"ascending\" | \"descending\" | \"other\"","\"none\" | \"inline\" | \"list\" | \"both\"","\"none\" | \"strict\" | \"blur\"","\"none\" | \"sum\"","\"none\" | \"thousand\" | \"lakh\" | \"wan\"","\"none\" | \"x\" | \"y\" | \"xy\"","\"number\" | RegExp | \"alphanumeric\"","\"off\" | \"assertive\" | \"polite\"","\"off\" | \"on\"","\"ordered\" | \"unordered\"","\"right\" | \"bottom\"","\"right-to-left\" | \"left-to-right\"","\"right-to-left\" | \"left-to-right\" | \"top-to-bottom\" | \"bottom-to-top\"","\"search\" | \"enter\" | \"done\" | \"go\" | \"next\" | \"previous\" | \"send\"","\"search\" | \"text\" | \"none\" | \"tel\" | \"url\" | \"email\" | \"numeric\" | \"decimal\"","\"step\" | \"bump\" | \"linear\" | \"natural\" | \"monotone\" | \"stepBefore\" | \"stepAfter\"","\"stepInactive\" | \"stepProgress\" | \"stepCompleted\"","\"sum\" | \"replace\"","\"td\" | \"th\"","\"text\" | \"additions\" | \"additions removals\" | \"additions text\" | \"all\" | \"removals\" | \"removals additions\" | \"removals text\" | \"text additions\" | \"text removals\"","\"text\" | \"tel\" | \"password\"","\"time\" | \"duration\"","\"up\" | \"down\"","\"value\" | \"name\" | \"percent\"","\"viewport\"","\"wrap\" | \"nowrap\" | \"balance\" | \"pretty\" | \"stable\"","\"x\" | \"y\"","\"xs\" | \"sm\" | \"md\" | \"lg\" | \"xl\"","\"xs\" | \"sm\" | \"md\" | \"lg\" | \"xl\" | (string & {})","\"yes\" | \"no\"","'Text' | 'Line truncated
{"schemaVersion":1,"mantineVersion":"9.6.0","customWidgetVersion":"3.0.0","types":["\"\" | \"anonymous\" | \"use-credentials\"","\"-moz-initial\" | \"inherit\" | \"initial\" | \"revert\" | \"revert-layer\" | \"unset\" | \"auto\" | \"fixed\"","\"-moz-initial\" | \"inherit\" | \"initial\" | \"revert\" | \"revert-layer\" | \"unset\" | \"none\" | \"auto\" | \"all\" | \"fill\" | \"stroke\" | \"painted\" | \"visible\" | \"visibleFill\" | \"visiblePainted\" | \"visibleStroke\"","\"-moz-initial\" | \"inherit\" | \"initial\" | \"revert\" | \"revert-layer\" | \"unset\" | \"none\" | \"block\" | \"inline\" | \"both\" | \"horizontal\" | \"vertical\"","\"-moz-initial\" | \"inherit\" | \"initial\" | \"revert\" | \"revert-layer\" | \"unset\" | \"none\" | \"contain\" | \"cover\" | \"fill\" | \"scale-down\"","\"-moz-initial\" | \"inherit\" | \"initial\" | \"revert\" | \"revert-layer\" | \"unset\" | \"wrap\" | \"nowrap\" | \"wrap-reverse\"","\"12h\" | \"24h\"","\"activity\" | \"display-none\"","\"all\" | \"parent\" | \"child\"","\"all\" | \"segment\"","\"always\" | \"hover\" | \"not-hover\" | \"never\"","\"area\" | \"radial\" | \"scatter\"","\"auto\" | \"scroll\" | \"always\" | \"hover\" | \"never\"","\"auto-fit\" | \"auto-fill\"","\"block\" | \"grid\"","\"both\" | \"rightSection\" | \"clear\"","\"bottom\" | \"top\"","\"bottom\" | \"top\" | \"baseline\" | \"middle\"","\"bottom\" | \"top\" | \"middle\"","\"bottom-end\" | \"bottom-start\" | \"top-end\" | \"top-start\" | \"bottom-center\" | \"top-center\" | \"middle-center\" | \"middle-end\" | \"middle-start\"","\"button\" | \"submit\" | \"reset\"","\"center\" | \"bottom\"","\"center\" | \"left\" | \"right\"","\"center\" | \"left\" | \"right\" | \"justify\" | \"char\"","\"center\" | \"side\" | \"merge\"","\"checkbox\" | \"radio\"","\"dashed\" | \"dotted\" | \"solid\"","\"default\" | \"gradient\"","\"default\" | \"responsive\"","\"default\" | \"stacked\" | \"percent\" | \"split\" | \"stream\"","\"default\" | \"stacked\" | \"percent\" | \"waterfall\"","\"div\" | \"label\"","\"end\" | \"start\"","\"filled\" | \"light\"","\"fixed\" | \"absolute\"","\"hex\" | \"hexa\" | \"rgba\" | \"rgb\" | \"hsl\" | \"hsla\"","\"horizontal\" | \"vertical\"","\"hover\" | \"click\"","\"hover\" | \"click\" | \"click-hover\"","\"inherit\" | \"auto\" | \"baseline\" | \"before-edge\" | \"text-before-edge\" | \"middle\" | \"central\" | \"after-edge\" | \"text-after-edge\" | \"ideographic\" | \"alphabetic\" | \"hanging\" | \"mathematical\"","\"inherit\" | \"auto\" | \"sRGB\" | \"linearRGB\"","\"inherit\" | \"auto\" | \"text-before-edge\" | \"middle\" | \"central\" | \"text-after-edge\" | \"ideographic\" | \"alphabetic\" | \"hanging\" | \"mathematical\" | \"use-script\" | \"no-change\" | \"reset-size\"","\"inherit\" | \"end\" | \"start\" | \"middle\"","\"inherit\" | \"nonzero\" | \"evenodd\"","\"inherit\" | \"round\" | \"butt\" | \"square\"","\"inherit\" | \"round\" | \"miter\" | \"bevel\"","\"initial\" | \"medial\" | \"terminal\" | \"isolated\"","\"inside\" | \"outside\"","\"left\" | \"right\"","\"left\" | \"right\" | \"bottom\" | \"top\"","\"left\" | \"right\" | \"bottom\" | \"top\" | \"left-end\" | \"left-start\" | \"right-end\" | \"right-start\" | \"bottom-end\" | \"bottom-start\" | \"top-end\" | \"top-start\"","\"left\" | \"right\" | \"inside\"","\"link\" | \"none\" | \"copy\" | \"execute\" | \"move\" | \"popup\"","\"media\" | \"container\"","\"month\" | \"year\" | \"decade\"","\"native\" | \"scrollarea\"","\"none\" | \"all\" | \"rows\" | \"groups\" | \"columns\"","\"none\" | \"all\" | \"with-indicators\"","\"none\" | \"ascending\" | \"descending\" | \"other\"","\"none\" | \"inline\" | \"list\" | \"both\"","\"none\" | \"strict\" | \"blur\"","\"none\" | \"sum\"","\"none\" | \"thousand\" | \"lakh\" | \"wan\"","\"none\" | \"x\" | \"y\" | \"xy\"","\"number\" | RegExp | \"alphanumeric\"","\"off\" | \"assertive\" | \"polite\"","\"off\" | \"on\"","\"ordered\" | \"unordered\"","\"right\" | \"bottom\"","\"right-to-left\" | \"left-to-right\"","\"right-to-left\" | \"left-to-right\" | \"top-to-bottom\" | \"bottom-to-top\"","\"search\" | \"enter\" | \"done\" | \"go\" | \"next\" | \"previous\" | \"send\"","\"search\" | \"text\" | \"none\" | \"tel\" | \"url\" | \"email\" | \"numeric\" | \"decimal\"","\"step\" | \"bump\" | \"linear\" | \"natural\" | \"monotone\" | \"stepBefore\" | \"stepAfter\"","\"stepInactive\" | \"stepProgress\" | \"stepCompleted\"","\"sum\" | \"replace\"","\"td\" | \"th\"","\"text\" | \"additions\" | \"additions removals\" | \"additions text\" | \"all\" | \"removals\" | \"removals additions\" | \"removals text\" | \"text additions\" | \"text removals\"","\"text\" | \"tel\" | \"password\"","\"time\" | \"duration\"","\"up\" | \"down\"","\"value\" | \"name\" | \"percent\"","\"viewport\"","\"wrap\" | \"nowrap\" | \"balance\" | \"pretty\" | \"stable\"","\"x\" | \"y\"","\"xs\" | \"sm\" | \"md\" | \"lg\" | \"xl\"","\"xs\" | \"sm\" | \"md\" | \"lg\" | \"xl\" | (string & {})","\"yes\" | \"no\"","'Text' | 'Line truncated
-83
View File
@@ -1,83 +0,0 @@
{
"$schema": "homarr-widget-package-v3",
"manifest": {
"id": "homarr.example.preview-scenarios",
"version": "1.0.0",
"sdkVersion": "1",
"name": "Preview scenario example",
"description": "Two independent local metrics with synthetic success, loading and partial-failure scenarios.",
"entrypoints": {
"tile": "widget.tsx",
"advanced": "widget.tsx",
"server": "server.ts"
},
"handlers": {
"memory": {
"kind": "query"
},
"storage": {
"kind": "query"
}
}
},
"files": {
"widget.tsx": "import { Alert, Card, Group, Progress, Stack, Text } from \"@mantine/core\";\nimport { useWidgetQuery } from \"@homarr/widget-sdk\";\ninterface MetricData { usedPercent: number; }\ninterface MetricProps { title: string; query: ReturnType<typeof useWidgetQuery<MetricData>>; }\nfunction Metric({ title, query }: MetricProps) {\n return <Card withBorder><Stack gap=\"xs\"><Text fw={600}>{title}</Text>\n {query.isPending && <Text c=\"dimmed\">Loading…</Text>}\n {query.error && <Alert color=\"orange\">{query.error.message}</Alert>}\n {query.data && <><Group justify=\"space-between\"><Text>Used</Text><Text>{query.data.usedPercent}%</Text></Group><Progress value={query.data.usedPercent} /></>}\n </Stack></Card>;\n}\nexport default function LocalMetrics() {\n const memory = useWidgetQuery<MetricData>(\"memory\", {}, {refetchInterval: 10000});\n const storage = useWidgetQuery<MetricData>(\"storage\", {}, {refetchInterval: 10000});\n return <Stack p=\"md\"><Metric title=\"Memory\" query={memory} /><Metric title=\"Storage\" query={storage} /></Stack>;\n}\n",
"server.ts": "import { freemem, totalmem } from \"node:os\";\nimport { statfs } from \"node:fs/promises\";\nimport { defineWidgetServer } from \"@homarr/widget-sdk/server\";\nexport default defineWidgetServer({\n memory: () => ({usedPercent: Math.round(100 * (1 - freemem() / totalmem()))}),\n storage: async () => {const value = await statfs(process.cwd()); return {usedPercent: Math.round(100 * (1 - value.bavail / value.blocks))};},\n});\n"
},
"dependencies": {},
"connections": {},
"options": {},
"previewScenarios": {
"ready": {
"label": "Both metrics available",
"queries": {
"memory": {
"data": {
"usedPercent": 38
}
},
"storage": {
"data": {
"usedPercent": 72
}
}
}
},
"loading": {
"label": "Slow storage collector",
"description": "Memory appears first; storage stays loading for three seconds.",
"queries": {
"memory": {
"data": {
"usedPercent": 38
},
"delayMs": 100
},
"storage": {
"data": {
"usedPercent": 72
},
"delayMs": 3000
}
}
},
"partialFailure": {
"label": "Storage unavailable",
"description": "Memory still renders when the storage collector fails.",
"queries": {
"memory": {
"data": {
"usedPercent": 38
}
},
"storage": {
"error": {
"message": "Synthetic storage collector timeout",
"code": "TIMEOUT"
},
"delayMs": 700
}
}
}
}
}
+1 -12
View File
@@ -43,18 +43,7 @@ const nextConfig: NextConfig = {
* dockerode is required in the external server packages because of https://github.com/homarr-labs/homarr/issues/612
* isomorphic-dompurify and jsdom are required, see https://github.com/kkomelin/isomorphic-dompurify/issues/356
*/
serverExternalPackages: ["dockerode", "isomorphic-dompurify", "jsdom", "better-sqlite3", "esbuild"],
outputFileTracingRoot: path.resolve(import.meta.dirname, "../.."),
outputFileTracingIncludes: {
"/*": [
// esbuild is automatically traced as an external, preserving its platform binary links.
// Recursive package globs instead trace pnpm dependency directory symlinks as files.
"../../node_modules/@tabler/icons-react/package.json",
"../../node_modules/@tabler/icons-react/dist/**/*",
"../../packages/widget-sdk/package.json",
"../../packages/widget-sdk/src/**/*",
],
},
serverExternalPackages: ["dockerode", "isomorphic-dompurify", "jsdom", "better-sqlite3"],
experimental: {
optimizePackageImports: ["@mantine/core", "@mantine/hooks", "@tabler/icons-react"],
preloadEntriesOnStart: true,
+4 -3
View File
@@ -4,9 +4,9 @@
"private": true,
"type": "module",
"scripts": {
"build": "pnpm --filter @homarr/custom-widgets generate:editor && HOMARR_VERSION=$(node -p \"require('../../package.json').version\") pnpm with-env next build",
"build": "HOMARR_VERSION=$(node -p \"require('../../package.json').version\") pnpm with-env next build",
"clean": "git clean -xdf .next .turbo node_modules",
"dev": "pnpm --filter @homarr/custom-widgets generate:editor && pnpm with-env next dev",
"dev": "pnpm with-env next dev",
"format": "oxfmt .",
"lint": "oxlint",
"start": "pnpm with-env next start",
@@ -58,7 +58,6 @@
"@homarr/ui": "workspace:^0.1.0",
"@homarr/validation": "workspace:^0.1.0",
"@homarr/websocket": "workspace:^0.1.0",
"@homarr/widget-sdk": "workspace:^0.1.0",
"@homarr/widgets": "workspace:^0.1.0",
"@homarr/workshop": "workspace:^0.1.0",
"@mantine/colors-generator": "catalog:",
@@ -87,6 +86,7 @@
"@xterm/addon-canvas": "catalog:",
"@xterm/addon-fit": "catalog:",
"@xterm/xterm": "catalog:",
"@xyflow/react": "catalog:",
"adm-zip": "catalog:",
"ai": "catalog:",
"assistant-stream": "catalog:",
@@ -97,6 +97,7 @@
"dayjs": "catalog:",
"dotenv": "catalog:",
"drizzle-orm": "catalog:",
"elkjs": "catalog:",
"flag-icons": "catalog:",
"glob": "catalog:",
"isomorphic-dompurify": "catalog:",
@@ -171,7 +171,8 @@ const ScopedTRPCReactProvider = ({
splitLink({
condition: ({ type }) => type === "subscription",
true: splitLink({
condition: ({ path }) => path === "widget.beszel.subscribeSystemStats",
condition: ({ path }) =>
path === "widget.beszel.subscribeSystemStats" || path === "customWidget.nativeSubscribe",
true: httpSubscriptionLink({
url: getTrpcUrl(),
transformer: superjson,
@@ -1,6 +1,6 @@
"use client";
import { Alert, Anchor, Text } from "@mantine/core";
import { Anchor, Badge, Group } from "@mantine/core";
import { IconFlask } from "@tabler/icons-react";
import { useI18n } from "@homarr/translation/client";
@@ -11,14 +11,13 @@ export function CustomWidgetBetaBanner() {
const t = useI18n("customWidget.betaBanner");
return (
<Alert variant="light" color="yellow" title={t("title")} icon={<IconFlask />}>
<Text size="sm">
{t("description")}{" "}
<Anchor href={FEEDBACK_URL} target="_blank" fw={600}>
{t("discussionLink")}
</Anchor>{" "}
{t("closing")}
</Text>
</Alert>
<Group gap="xs">
<Badge variant="light" color="yellow" leftSection={<IconFlask size={12} />}>
{t("title")}
</Badge>
<Anchor size="xs" href={FEEDBACK_URL} target="_blank" rel="noopener noreferrer">
{t("discussionLink")}
</Anchor>
</Group>
);
}
@@ -1,15 +1,57 @@
"use client";
import { useSyncExternalStore, useState, useEffect, useCallback, useMemo } from "react";
import type { ComponentProps } from "react";
import { CodeEditor as SharedCodeEditor } from "~/components/custom-widgets/code-editor";
export function CodeEditor(props: ComponentProps<typeof SharedCodeEditor>) {
const localHistory =
props.id === "raw-widget-manifest" || props.id.endsWith("-request-body-editor") || props.id.startsWith("option-");
import { useOptionalCustomWidgetFormDocumentStore } from "./_custom-widget-form-state";
const subscribeEmpty = () => () => undefined;
const zero = () => 0;
export function CodeEditor({
localHistory = false,
...props
}: ComponentProps<typeof SharedCodeEditor> & { localHistory?: boolean }) {
const [insert, setInsert] = useState<{ text: string; key: number }>();
const [reveal, setReveal] = useState<{ index: number; key: number }>();
useEffect(() => {
const receive = (event: Event) => {
const detail = (event as CustomEvent<{ editorId: string; index: number }>).detail;
if (detail.editorId === props.id) setReveal({ index: detail.index, key: Date.now() });
};
const receiveInsert = (event: Event) => {
const detail = (event as CustomEvent<{ editorId: string; text: string }>).detail;
if (detail.editorId === props.id && !props.readOnly) setInsert({ text: detail.text, key: Date.now() });
};
window.addEventListener("homarr:widget-code-insert", receiveInsert);
window.addEventListener("homarr:widget-code-reveal", receive);
return () => {
window.removeEventListener("homarr:widget-code-reveal", receive);
window.removeEventListener("homarr:widget-code-insert", receiveInsert);
};
}, [props.id, props.readOnly]);
const store = useOptionalCustomWidgetFormDocumentStore();
const getHistoryState = useCallback(() => {
if (!store) return 0;
return Number(store.canUndo()) + 2 * Number(store.canRedo());
}, [store]);
const historyState = useSyncExternalStore(store?.subscribeEditor ?? subscribeEmpty, getHistoryState, zero);
const history = useMemo(() => {
if (!store || localHistory || props.readOnly || props.id.startsWith("preview-")) return undefined;
return {
canUndo: Boolean(historyState & 1),
canRedo: Boolean(historyState & 2),
undo: store.undo,
redo: store.redo,
};
}, [store, localHistory, props.readOnly, props.id, historyState]);
return (
<div data-custom-widget-local-history={localHistory || undefined}>
<SharedCodeEditor {...props} hideHistoryActions={!localHistory} />
<div data-workbench-local-input={localHistory || undefined}>
<SharedCodeEditor
{...props}
history={history}
insertText={insert?.text ?? props.insertText}
insertKey={insert?.key ?? props.insertKey}
revealIndex={reveal?.index}
revealKey={reveal?.key ?? props.revealKey}
/>
</div>
);
}
@@ -27,7 +27,7 @@ import { useI18n } from "@homarr/translation/client";
import { InlineConfirmMenuItem, Link } from "@homarr/ui";
import { CustomWidgetImportDialog } from "~/components/custom-widgets/custom-widget-import-dialog";
import { downloadJson } from "@homarr/common";
import { downloadJson } from "~/components/custom-widgets/download";
const iconProps = { size: 16, stroke: 1.5 };
@@ -1,104 +0,0 @@
import { redactCustomWidgetCredentialLiterals } from "@homarr/custom-widgets/core";
import type { CustomWidgetFormValues } from "@homarr/custom-widgets/workbench";
export type CustomWidgetDocumentContent = Omit<CustomWidgetFormValues, "secrets">;
export interface CustomWidgetDocumentHistoryState {
canUndo: boolean;
canRedo: boolean;
}
const MAX_HISTORY_ENTRIES = 100;
const MAX_HISTORY_CHARACTERS = 2_000_000;
const COALESCE_DELAY = 600;
const typingFields = new Set(["name", "description", "iconUrl", "template"]);
export function getCustomWidgetDocumentContent(values: CustomWidgetFormValues): CustomWidgetDocumentContent {
const { secrets: _secrets, ...content } = values;
return content;
}
export function getCustomWidgetRecoveryContent(values: CustomWidgetFormValues): CustomWidgetDocumentContent {
const content = getCustomWidgetDocumentContent(values);
for (const key of Object.keys(content) as Array<keyof CustomWidgetDocumentContent>) {
let value = content[key];
for (const secret of values.secrets) {
if (secret.value) value = value.replaceAll(secret.value, "[REDACTED]");
}
content[key] = redactCustomWidgetCredentialLiterals(value.replaceAll(/\b(https?:\/\/)[^\s/"'<>]+@/giu, "$1"));
}
return content;
}
export function createCustomWidgetDocumentHistory(initialValues: CustomWidgetFormValues) {
const initial = getCustomWidgetDocumentContent(initialValues);
let entries = [{ content: initial, size: JSON.stringify(initial).length }];
let position = 0;
let lastChangeAt = 0;
let lastTypingField: string | undefined;
let sameTurn = false;
let state: CustomWidgetDocumentHistoryState = { canUndo: false, canRedo: false };
const refreshState = () => {
state = { canUndo: position > 0, canRedo: position < entries.length - 1 };
};
const stopCoalescing = () => {
sameTurn = false;
lastChangeAt = 0;
lastTypingField = undefined;
};
return {
getState: () => state,
record(values: CustomWidgetFormValues) {
const next = getCustomWidgetDocumentContent(values);
const current = entries[position]?.content;
const changed = (Object.keys(next) as Array<keyof CustomWidgetDocumentContent>).filter(
(key) => next[key] !== current?.[key],
);
if (changed.length === 0) return;
const now = Date.now();
const field = changed[0];
const isTyping = changed.length === 1 && field !== undefined && typingFields.has(field);
const coalesce =
position > 0 &&
position === entries.length - 1 &&
(sameTurn || (isTyping && field === lastTypingField && now - lastChangeAt < COALESCE_DELAY));
entries = entries.slice(0, position + 1);
const entry = { content: next, size: JSON.stringify(next).length };
if (coalesce) entries[position] = entry;
else {
entries.push(entry);
position += 1;
}
let size = entries.reduce((total, item) => total + item.size, 0);
while (entries.length > 1 && (entries.length > MAX_HISTORY_ENTRIES || size > MAX_HISTORY_CHARACTERS)) {
const removed = entries.shift();
if (removed) size -= removed.size;
position -= 1;
}
lastChangeAt = now;
lastTypingField = undefined;
if (isTyping) lastTypingField = field;
sameTurn = true;
queueMicrotask(() => {
sameTurn = false;
});
refreshState();
},
undo() {
if (position === 0) return null;
position -= 1;
stopCoalescing();
refreshState();
return entries[position]?.content ?? null;
},
redo() {
if (position === entries.length - 1) return null;
position += 1;
stopCoalescing();
refreshState();
return entries[position]?.content ?? null;
},
stopCoalescing,
};
}
@@ -1,196 +0,0 @@
"use client";
import { useCallback, useEffect, useState, useSyncExternalStore } from "react";
import { Alert, Button, Group, Stack, Text } from "@mantine/core";
import { IconArrowBackUp, IconArrowForwardUp, IconRestore } from "@tabler/icons-react";
import { useSession } from "@homarr/auth/client";
import { isRecord } from "@homarr/common";
import { customWidgetFormSchema } from "@homarr/custom-widgets/workbench";
import { useI18n } from "@homarr/translation/client";
import { getCustomWidgetRecoveryContent } from "./_custom-widget-document-history";
import type { CustomWidgetDocumentContent } from "./_custom-widget-document-history";
import { useCustomWidgetFormDocumentStore } from "./_custom-widget-form-state";
import type { CustomWidgetWorkbenchForm } from "./_custom-widget-form-utils";
interface RecoveryDraft {
definitionId: string | null;
content: CustomWidgetDocumentContent;
}
const MAX_RECOVERY_CHARACTERS = 1_000_000;
export function CustomWidgetDraftControls({
form,
definitionId,
disabled,
}: {
form: CustomWidgetWorkbenchForm;
definitionId?: string;
disabled: boolean;
}) {
const t = useI18n("customWidget.workbench.history");
const store = useCustomWidgetFormDocumentStore();
const history = useSyncExternalStore(store.subscribe, store.getHistory, store.getHistory);
const dirty = useSyncExternalStore(store.subscribe, store.getDirty, store.getDirty);
const { data: session } = useSession();
const userId = session?.user.id;
const [recovery, setRecovery] = useState<RecoveryDraft | null>(null);
const storageKey = userId ? `homarr:custom-widget-recovery:${userId}` : null;
const restoreHistory = useCallback(
(direction: "undo" | "redo") => {
if (disabled) return;
const restored = store[direction]();
if (restored) form.setValues(restored);
},
[disabled, form, store],
);
useEffect(() => {
const onKeyDown = (event: KeyboardEvent) => {
if (!(event.ctrlKey || event.metaKey) || event.altKey || event.key.toLowerCase() !== "z") return;
const target = event.target;
if (!(target instanceof Element) || !target.closest("[data-custom-widget-workbench]")) return;
if (target.closest("[data-custom-widget-secret], [data-custom-widget-local-history], #preview")) return;
event.preventDefault();
event.stopPropagation();
if (event.shiftKey) restoreHistory("redo");
else restoreHistory("undo");
};
window.addEventListener("keydown", onKeyDown, true);
return () => window.removeEventListener("keydown", onKeyDown, true);
}, [restoreHistory]);
useEffect(() => {
if (!storageKey) return;
try {
const saved = localStorage.getItem(storageKey);
if (!saved || saved.length > MAX_RECOVERY_CHARACTERS) return;
const parsed = JSON.parse(saved) as RecoveryDraft;
if (!parsed || parsed.definitionId !== (definitionId ?? null)) return;
if (!isRecord(parsed.content)) return;
const keys = customWidgetFormSchema.keyof().options.filter((key) => key !== "secrets");
if (!keys.every((key) => typeof parsed.content[key] === "string")) return;
setRecovery({
definitionId: parsed.definitionId,
content: getCustomWidgetRecoveryContent({ ...parsed.content, secrets: [] }),
});
} catch {
// Browser storage is optional; editing and saving continue without it.
}
}, [definitionId, storageKey]);
useEffect(() => {
if (!storageKey || recovery) return;
let timeout: ReturnType<typeof setTimeout> | undefined;
const persist = () => {
clearTimeout(timeout);
if (!store.getDirty()) {
try {
const saved = localStorage.getItem(storageKey);
if (saved && (JSON.parse(saved) as RecoveryDraft).definitionId === (definitionId ?? null)) {
localStorage.removeItem(storageKey);
}
} catch {
/* Storage is optional. */
}
return;
}
timeout = setTimeout(() => {
try {
const draft = JSON.stringify({
definitionId: definitionId ?? null,
content: getCustomWidgetRecoveryContent(store.getValues()),
} satisfies RecoveryDraft);
if (draft.length <= MAX_RECOVERY_CHARACTERS) localStorage.setItem(storageKey, draft);
} catch {
// Quota limits and blocked storage must not interrupt the workbench.
}
}, 500);
};
const unsubscribe = store.subscribe(persist);
if (store.getDirty()) persist();
return () => {
clearTimeout(timeout);
unsubscribe();
};
}, [definitionId, recovery, storageKey, store]);
const dismissRecovery = () => {
if (storageKey) {
try {
localStorage.removeItem(storageKey);
} catch {
/* Storage is optional. */
}
}
setRecovery(null);
};
return (
<Stack gap="sm" mb="md">
{recovery && (
<Alert title={t("recoveryTitle")}>
<Stack gap="xs">
<Text size="sm">{t("recoveryDescription")}</Text>
<Group gap="xs">
<Button
size="xs"
type="button"
disabled={disabled}
onClick={() => {
form.setValues({ ...store.getValues(), ...recovery.content, secrets: [] });
dismissRecovery();
}}
>
{t("restore")}
</Button>
<Button size="xs" type="button" variant="subtle" onClick={dismissRecovery}>
{t("discard")}
</Button>
</Group>
</Stack>
</Alert>
)}
<Group gap="xs">
<Button
type="button"
size="compact-sm"
variant="subtle"
leftSection={<IconArrowBackUp size={16} />}
disabled={disabled || !history.canUndo}
onClick={() => restoreHistory("undo")}
aria-keyshortcuts="Control+Z Meta+Z"
>
{t("undo")}
</Button>
<Button
type="button"
size="compact-sm"
variant="subtle"
leftSection={<IconArrowForwardUp size={16} />}
disabled={disabled || !history.canRedo}
onClick={() => restoreHistory("redo")}
aria-keyshortcuts="Control+Shift+Z Meta+Shift+Z"
>
{t("redo")}
</Button>
<Button
type="button"
size="compact-sm"
variant="subtle"
leftSection={<IconRestore size={16} />}
disabled={disabled || !dirty}
onClick={() => form.setValues(store.resetToSaved())}
>
{t("reset")}
</Button>
<Text size="xs" c="dimmed">
{t("credentialsExcluded")}
</Text>
</Group>
</Stack>
);
}
@@ -3,7 +3,17 @@
import { useEffect, useRef } from "react";
import type { Dispatch, ReactNode, SetStateAction } from "react";
import type { Icon } from "@tabler/icons-react";
import { Button, Card, Group, Stack, Text, ThemeIcon } from "@mantine/core";
import {
Button,
Card,
getContrastColor,
Group,
Stack,
Text,
ThemeIcon,
useComputedColorScheme,
useMantineTheme,
} from "@mantine/core";
import {
IconAlertCircle,
IconAlertTriangle,
@@ -24,6 +34,7 @@ import { useUnsavedChangesGuard } from "~/components/manage/use-unsaved-changes-
import { useCustomWidgetFormDocumentDirty } from "./_custom-widget-form-state";
import { areCustomWidgetValuesEqual } from "./_custom-widget-value-equality";
import { useCustomWidgetFormAnalysisField } from "./_use-custom-widget-form-analysis";
import { useWorkbenchSelection } from "./_flow/selection";
import classes from "./_custom-widget-form.module.css";
const sectionLinks = [
@@ -46,10 +57,11 @@ export function EditorSection({
icon: Icon;
children: ReactNode;
}) {
const compact = useWorkbenchSelection() !== undefined;
return (
<Card id={id} component="section" withBorder p="lg" className={classes.editorSection}>
<Card id={id} component="section" withBorder={!compact} p={compact ? 0 : "lg"} className={classes.editorSection}>
<Stack gap="md">
<Group gap="sm">
<Group gap="sm" data-workbench-section-title>
<ThemeIcon variant="light" size="lg">
<SectionIcon size={18} />
</ThemeIcon>
@@ -64,6 +76,7 @@ export function EditorSection({
}
export function SaveActions({
formId,
dirty,
savePending,
previewPending,
@@ -71,6 +84,7 @@ export function SaveActions({
mode,
onPreview,
}: {
formId?: string;
dirty: boolean;
savePending: boolean;
previewPending: boolean;
@@ -80,6 +94,13 @@ export function SaveActions({
}) {
const t = useI18n("customWidget.workbench");
const tCommon = useI18n("common");
const theme = useMantineTheme();
const colorScheme = useComputedColorScheme();
const submitColor = getContrastColor({
color: theme.primaryColor,
colorScheme,
theme: { ...theme, luminanceThreshold: 0.179 },
});
return (
<Group justify="space-between" wrap="wrap">
<Group gap="xs">
@@ -103,7 +124,13 @@ export function SaveActions({
>
{previewPending ? t("action.previewLoading") : t("action.preview")}
</Button>
<Button type="submit" loading={savePending} disabled={invalid || previewPending}>
<Button
form={formId}
type="submit"
loading={savePending}
disabled={invalid || previewPending}
style={{ "--button-color": submitColor }}
>
{mode === "create" ? tCommon("action.create") : tCommon("action.save")}
</Button>
</Group>
@@ -143,11 +170,13 @@ export function CustomWidgetSectionNavigation({
}
export function CustomWidgetSaveActions({
formId,
mode,
savePending,
previewPending,
onPreview,
}: {
formId?: string;
mode: "create" | "edit";
savePending: boolean;
previewPending: boolean;
@@ -158,6 +187,7 @@ export function CustomWidgetSaveActions({
const hasDiagnostics = useCustomWidgetFormAnalysisField("hasDiagnostics");
return (
<SaveActions
formId={formId}
dirty={dirty}
savePending={savePending}
previewPending={previewPending}
@@ -201,7 +201,7 @@ interface CustomWidgetPreviewSectionProps {
onSizeChange(size: string): void;
optionsSnapshot: Record<string, unknown>;
onOptionsChange: Dispatch<SetStateAction<Record<string, unknown>>>;
onLiveActionsChange(enabled: boolean, sessionId: string): void;
onLiveActionsChange(enabled: boolean): void;
}
export function CustomWidgetPreviewSection(props: CustomWidgetPreviewSectionProps) {
@@ -13,111 +13,10 @@ import {
import type { ReactNode } from "react";
import type { UseFormReturnType } from "@mantine/form";
import {
customWidgetSourcesSchema,
getCustomWidgetRequiredSecretKinds,
hasSameCustomWidgetSourceBinding,
} from "@homarr/custom-widgets/core";
import { customWidgetFormSchema } from "@homarr/custom-widgets/workbench";
import type { CustomWidgetFormValues } from "@homarr/custom-widgets/workbench";
import { areCustomWidgetValuesEqual } from "./_custom-widget-value-equality";
import { createCustomWidgetDocumentHistory, getCustomWidgetDocumentContent } from "./_custom-widget-document-history";
import type { CustomWidgetDocumentContent, CustomWidgetDocumentHistoryState } from "./_custom-widget-document-history";
export interface CustomWidgetFormDocumentStore {
getValues(): CustomWidgetFormValues;
setValues(values: CustomWidgetFormValues): void;
getDirty(): boolean;
subscribe(listener: () => void): () => void;
markSaved(values: CustomWidgetFormValues): void;
getHistory(): CustomWidgetDocumentHistoryState;
undo(): CustomWidgetFormValues | null;
redo(): CustomWidgetFormValues | null;
resetToSaved(): CustomWidgetFormValues;
}
const documentValueKeys = customWidgetFormSchema.keyof().options;
function areDocumentValuesEqual(left: CustomWidgetFormValues, right: CustomWidgetFormValues) {
if (Object.keys(left).length !== documentValueKeys.length) return false;
if (Object.keys(right).length !== documentValueKeys.length) return false;
return documentValueKeys.every(
(key) => Object.hasOwn(left, key) && Object.hasOwn(right, key) && areCustomWidgetValuesEqual(left[key], right[key]),
);
}
export function createCustomWidgetFormDocumentStore(
initialValues: CustomWidgetFormValues,
): CustomWidgetFormDocumentStore {
let values = initialValues;
let persistedValues = initialValues;
let dirty = false;
const history = createCustomWidgetDocumentHistory(initialValues);
const listeners = new Set<() => void>();
const notify = () => listeners.forEach((listener) => listener());
const restore = (content: CustomWidgetDocumentContent | null): CustomWidgetFormValues | null => {
if (!content) return null;
let secrets: CustomWidgetFormValues["secrets"] = [];
try {
const sources = customWidgetSourcesSchema.parse(JSON.parse(content.sources));
const currentSources = customWidgetSourcesSchema.parse(JSON.parse(values.sources));
secrets = values.secrets.filter((secret) => {
const source = sources[secret.sourceId];
const currentSource = currentSources[secret.sourceId];
if (!source || !currentSource || !hasSameCustomWidgetSourceBinding(source, currentSource)) return false;
const auth = typeof source.auth === "string" ? source.auth : source.auth.type;
return getCustomWidgetRequiredSecretKinds(auth).some((kind) => kind === secret.kind);
});
} catch {
// An unfinished source document cannot safely retain credential bindings.
}
const restored = { ...content, secrets };
values = restored;
dirty = !areDocumentValuesEqual(restored, persistedValues);
notify();
return restored;
};
return {
getValues: () => values,
setValues: (nextValues) => {
if (Object.is(values, nextValues)) return;
history.record(nextValues);
values = nextValues;
dirty = !areDocumentValuesEqual(nextValues, persistedValues);
notify();
},
getDirty: () => dirty,
getHistory: history.getState,
undo: () => restore(history.undo()),
redo: () => restore(history.redo()),
resetToSaved: () => {
history.stopCoalescing();
const restored = {
...getCustomWidgetDocumentContent(persistedValues),
secrets: persistedValues.secrets.map((secret) => ({ ...secret, value: "" })),
};
history.record(restored);
values = restored;
dirty = !areDocumentValuesEqual(restored, persistedValues);
notify();
return restored;
},
subscribe: (listener) => {
listeners.add(listener);
return () => listeners.delete(listener);
},
markSaved: (savedValues) => {
const wasDirty = dirty;
persistedValues = savedValues;
history.stopCoalescing();
dirty = !areDocumentValuesEqual(values, persistedValues);
if (wasDirty !== dirty) notify();
},
};
}
import type { CustomWidgetFormDocumentStore } from "./_flow/document-store";
export { createCustomWidgetFormDocumentStore } from "./_flow/document-store";
export type { CustomWidgetFormDocumentStore } from "./_flow/document-store";
const CustomWidgetFormDocumentContext = createContext<CustomWidgetFormDocumentStore | null>(null);
@@ -131,6 +30,10 @@ export function CustomWidgetFormDocumentProvider({
return <CustomWidgetFormDocumentContext.Provider value={store}>{children}</CustomWidgetFormDocumentContext.Provider>;
}
export function useOptionalCustomWidgetFormDocumentStore() {
return useContext(CustomWidgetFormDocumentContext);
}
export function useCustomWidgetFormDocumentStore() {
const store = useContext(CustomWidgetFormDocumentContext);
if (!store) throw new Error("Custom widget form document provider is missing");
@@ -155,9 +58,14 @@ export function useDeferredCustomWidgetFormDocumentValues() {
}, 150);
};
const unsubscribe = store.subscribe(scheduleUpdate);
const unsubscribeRenames = store.onNodeRenames(() => {
clearTimeout(timeout);
setValues(store.getValues());
});
return () => {
clearTimeout(timeout);
unsubscribe();
unsubscribeRenames();
};
}, [store]);
return values;
@@ -171,7 +79,7 @@ export function useCustomWidgetFormDocumentField<Key extends keyof CustomWidgetF
export function useCustomWidgetFormDocumentDirty() {
const store = useCustomWidgetFormDocumentStore();
return useSyncExternalStore(store.subscribe, store.getDirty, store.getDirty);
return useSyncExternalStore(store.subscribeEditor, store.getDirty, store.getDirty);
}
export function useCustomWidgetFormDocumentBridge(
@@ -180,6 +88,7 @@ export function useCustomWidgetFormDocumentBridge(
) {
const formRef = useRef(form);
formRef.current = form;
useEffect(() => store.onRestore((values) => formRef.current.setValues(values)), [store]);
return useMemo(
() =>
new Proxy({} as UseFormReturnType<CustomWidgetFormValues>, {
@@ -19,7 +19,8 @@ const PREVIEW_QUERY_CONCURRENCY = 4;
export function buildDefinition(values: CustomWidgetFormValues) {
return customWidgetDefinitionSchema.safeParse({
$schema: "homarr-custom-widget-v2",
$schema: values.extensions?.trim() ? "homarr-custom-widget-v3" : "homarr-custom-widget-v2",
...(values.extensions?.trim() ? { extensions: parseJson(values.extensions) } : {}),
name: values.name,
description: values.description || undefined,
iconUrl: values.iconUrl || undefined,
@@ -59,6 +60,7 @@ export function applyDefinition(form: CustomWidgetWorkbenchForm, widget: HomarrC
requests: JSON.stringify(widget.requests, null, 2),
options: JSON.stringify(widget.options, null, 2),
template: widget.template,
extensions: widget.$schema === "homarr-custom-widget-v3" ? JSON.stringify(widget.extensions ?? {}, null, 2) : "",
});
}
@@ -104,9 +106,14 @@ export function isRuntimeParams(
}
export async function loadPreviewQueries(definition: HomarrCustomWidgetV2, sessionId: string) {
const requests = Object.entries(definition.requests).filter(
([, entry]) => entry.kind === "query" && entry.trigger === "load",
);
const requests = [
...Object.entries(definition.requests)
.filter(([, entry]) => entry.kind === "query" && entry.trigger === "load")
.map(([id]) => ({ id, native: false })),
...Object.entries(definition.extensions?.native ?? {})
.filter(([, entry]) => entry.kind === "query" && entry.trigger === "load")
.map(([id]) => ({ id, native: true })),
];
const results: Array<{
requestId: string;
data: unknown;
@@ -119,9 +126,11 @@ export async function loadPreviewQueries(definition: HomarrCustomWidgetV2, sessi
nextIndex += 1;
const request = requests[index];
if (!request) return;
const [requestId] = request;
const requestId = request.id;
try {
const result = await fetchApi.customWidget.previewQuery.query({ sessionId, requestId, params: {} });
const result = await (request.native
? fetchApi.customWidget.nativeQuery.query({ previewSessionId: sessionId, nativeId: requestId, params: {} })
: fetchApi.customWidget.previewQuery.query({ sessionId, requestId, params: {} }));
results[index] = { requestId, data: result.data, status: { loading: false, ...result } };
} catch (error) {
results[index] = {
@@ -1,8 +1,8 @@
"use client";
import { memo, useCallback, useLayoutEffect, useMemo, useRef, useState } from "react";
import { customWidgetEditorLayoutSchema, EMPTY_EDITOR_LAYOUT } from "@homarr/custom-widgets/core";
import { memo, useId, useCallback, useLayoutEffect, useMemo, useRef, useState } from "react";
import type { Dispatch, FormEventHandler, SetStateAction } from "react";
import { Box, Paper, SegmentedControl, Stack } from "@mantine/core";
import type { CustomWidgetAiDraft } from "@homarr/custom-widgets/authoring-prompt";
import { customWidgetFormSchema, DEFAULT_CUSTOM_WIDGET_FORM_VALUES } from "@homarr/custom-widgets/workbench";
@@ -11,11 +11,9 @@ import { useZodForm } from "@homarr/form";
import { useI18n } from "@homarr/translation/client";
import { CustomWidgetAdvancedManifest } from "./_custom-widget-advanced-manifest";
import { CustomWidgetDraftControls } from "./_custom-widget-draft-controls";
import {
CustomWidgetOptionsSnapshotSync,
CustomWidgetSaveActions,
CustomWidgetSectionNavigation,
CustomWidgetUnsavedChangesGuard,
} from "./_custom-widget-form-layout";
import {
@@ -41,12 +39,15 @@ import type { CustomWidgetSaveIssue } from "./_custom-widget-save-errors";
import { CustomWidgetSaveIssuesAlert } from "./_custom-widget-save-issues-alert";
import { useCustomWidgetFormActions } from "./_use-custom-widget-form-actions";
import { analyzeCustomWidgetAiDiagnostics, CustomWidgetFormAnalysisProvider } from "./_use-custom-widget-form-analysis";
import { FlowWorkbench } from "./_flow/workbench";
import classes from "./_custom-widget-form.module.css";
interface CustomWidgetFormProps {
mode: "create" | "edit";
initialValues?: Partial<CustomWidgetFormValues>;
definitionId?: string;
editorLayout?: string | null;
savedRevision?: string;
}
type MobilePane = "configure" | "preview";
@@ -70,7 +71,7 @@ interface CustomWidgetFormViewProps {
savePending: boolean;
previewPending: boolean;
onSubmit: FormEventHandler<HTMLFormElement>;
onPreview(): void;
onPreview(): Promise<unknown>;
onPasteAiResponse(): void;
}
@@ -82,100 +83,77 @@ function getAiDraft(values: CustomWidgetFormValues): CustomWidgetAiDraft {
sources: values.sources,
requests: values.requests,
options: values.options,
extensions: values.extensions,
template: values.template,
};
}
const CustomWidgetFormView = memo(function CustomWidgetFormView(props: CustomWidgetFormViewProps) {
const w = useI18n("customWidget.workbench");
const saveFormId = useId();
const documentStore = props.documentStore;
const form = props.form;
const setMobilePane = props.setMobilePane;
const setPreview = props.setPreview;
const { renameRequest, renameOption } = useMemo(
() =>
createCustomWidgetRenameHandlers({
form,
transaction: documentStore.transaction,
renameRequestBinding: documentStore.renameRequestBinding,
invalidWidgetMessage: w("invalidWidget"),
}),
[form, w],
[documentStore, form, w],
);
const readAiDraft = useCallback(() => getAiDraft(documentStore.getValues()), [documentStore]);
const readAiDiagnostics = useCallback(
() => analyzeCustomWidgetAiDiagnostics(documentStore.getValues()),
[documentStore],
);
const handleSectionSelect = useCallback(
(section: string) => {
setMobilePane(section === "preview" ? "preview" : "configure");
},
[setMobilePane],
);
const handleLiveActionsChange = useCallback(
(enabled: boolean, sessionId: string) =>
setPreview((current) => {
if (current.session?.id !== sessionId) return current;
return { ...current, session: { ...current.session, liveActions: enabled } };
}),
(enabled: boolean) =>
setPreview((current) => ({
...current,
session: current.session ? { ...current.session, liveActions: enabled } : null,
})),
[setPreview],
);
return (
<CustomWidgetFormDocumentProvider store={documentStore}>
<CustomWidgetFormAnalysisProvider>
<form onSubmit={props.onSubmit} className={classes.form} data-custom-widget-workbench>
<div className={classes.form}>
<form id={saveFormId} onSubmit={props.onSubmit} />
<CustomWidgetUnsavedChangesGuard />
<CustomWidgetDraftControls
form={form}
definitionId={props.definitionId}
disabled={props.savePending || props.previewPending}
/>
<CustomWidgetOptionsSnapshotSync setOptionsSnapshot={props.setOptionsSnapshot} />
<SegmentedControl
className={classes.paneSwitcher}
fullWidth
value={props.mobilePane}
onChange={(value) => {
if (value === "configure" || value === "preview") props.setMobilePane(value);
}}
data={[
{ value: "configure", label: w("configure") },
{ value: "preview", label: w("section.preview") },
]}
/>
<CustomWidgetSaveIssuesAlert issues={props.saveIssues} />
<CustomWidgetSectionNavigation onSelect={handleSectionSelect} />
<div className={classes.workbench} data-mobile-pane={props.mobilePane}>
<Stack gap="lg" className={classes.configuration}>
<FlowWorkbench
feedback={<CustomWidgetSaveIssuesAlert issues={props.saveIssues} />}
form={form}
onPreview={props.onPreview}
execution={props.preview}
definitionId={props.definitionId}
actions={
<CustomWidgetSaveActions
formId={saveFormId}
mode={props.mode}
savePending={props.savePending}
previewPending={props.previewPending}
onPreview={props.onPreview}
/>
}
general={<CustomWidgetGeneralSection form={form} formRevision={props.formRevision} mode={props.mode} />}
sources={<CustomWidgetSourcesSection form={form} definitionId={props.definitionId} />}
requests={<CustomWidgetRequestsSection form={form} onRename={renameRequest} />}
options={<CustomWidgetOptionsSection form={form} onRename={renameOption} />}
template={<CustomWidgetTemplateSection form={form} />}
assistant={
<CustomWidgetAiSection
getDraft={readAiDraft}
getDiagnostics={readAiDiagnostics}
onPaste={props.onPasteAiResponse}
/>
<CustomWidgetAdvancedManifest form={form} />
<CustomWidgetGeneralSection form={form} formRevision={props.formRevision} mode={props.mode} />
<CustomWidgetSourcesSection form={form} definitionId={props.definitionId} />
<CustomWidgetRequestsSection form={form} onRename={renameRequest} />
<CustomWidgetOptionsSection form={form} onRename={renameOption} />
<CustomWidgetTemplateSection form={form} />
<Paper p="md" className={classes.mobileSaveBar} shadow="sm">
<CustomWidgetSaveActions
mode={props.mode}
savePending={props.savePending}
previewPending={props.previewPending}
onPreview={props.onPreview}
/>
</Paper>
</Stack>
<Box id="preview" component="aside" className={classes.previewPane} aria-label={w("widgetPreview")}>
<Paper p="md" className={classes.actionBar} shadow="sm">
<CustomWidgetSaveActions
mode={props.mode}
savePending={props.savePending}
previewPending={props.previewPending}
onPreview={props.onPreview}
/>
</Paper>
}
advanced={<CustomWidgetAdvancedManifest form={form} />}
preview={
<CustomWidgetPreviewSection
preview={props.preview}
size={props.previewSize}
@@ -184,20 +162,32 @@ const CustomWidgetFormView = memo(function CustomWidgetFormView(props: CustomWid
onOptionsChange={props.setOptionsSnapshot}
onLiveActionsChange={handleLiveActionsChange}
/>
</Box>
</div>
</form>
}
/>
</div>
</CustomWidgetFormAnalysisProvider>
</CustomWidgetFormDocumentProvider>
);
});
export function CustomWidgetForm({ mode, initialValues, definitionId }: CustomWidgetFormProps) {
export function CustomWidgetForm({
mode,
initialValues,
definitionId,
editorLayout,
savedRevision,
}: CustomWidgetFormProps) {
const flowT = useI18n("customWidget.flow");
const [formInitialValues] = useState<CustomWidgetFormValues>(() => ({
...DEFAULT_CUSTOM_WIDGET_FORM_VALUES,
sources: "{}",
requests: "{}",
template: `<Stack align="center" justify="center" h="100%"><Text size="xl" fw={600}>{${JSON.stringify(flowT("welcomeTemplate"))}}</Text></Stack>`,
...initialValues,
}));
const [documentStore] = useState(() => createCustomWidgetFormDocumentStore(formInitialValues));
const [documentStore] = useState(() =>
createCustomWidgetFormDocumentStore(formInitialValues, parseEditorLayout(editorLayout)),
);
const mantineForm = useZodForm(customWidgetFormSchema, {
initialValues: formInitialValues,
mode: "uncontrolled",
@@ -214,6 +204,7 @@ export function CustomWidgetForm({ mode, initialValues, definitionId }: CustomWi
return initialDefinition.success ? getDefinitionDefaults(initialDefinition.data) : {};
});
const actions = useCustomWidgetFormActions({
savedRevision,
mode,
definitionId,
form,
@@ -228,7 +219,7 @@ export function CustomWidgetForm({ mode, initialValues, definitionId }: CustomWi
latestActions.current = actions;
}, [actions]);
const handleSubmit = useCallback<FormEventHandler<HTMLFormElement>>((event) => latestActions.current.save(event), []);
const handlePreview = useCallback(() => void latestActions.current.runPreview(), []);
const handlePreview = useCallback(() => latestActions.current.runPreview(), []);
const handlePasteAiResponse = useCallback(() => void latestActions.current.pasteAiResponse(), []);
return (
@@ -256,3 +247,11 @@ export function CustomWidgetForm({ mode, initialValues, definitionId }: CustomWi
/>
);
}
function parseEditorLayout(value?: string | null) {
try {
return customWidgetEditorLayoutSchema.parse(JSON.parse(value ?? "null"));
} catch {
return EMPTY_EDITOR_LAYOUT;
}
}
@@ -26,6 +26,7 @@ export function CustomWidgetIdentifierInput({
};
return (
<TextInput
data-workbench-local-input
label={label}
value={draft}
error={error}
@@ -89,7 +89,7 @@ function CustomWidgetRow({ widget }: { widget: WidgetDef }) {
}
actions={
<Group gap="xs" wrap="nowrap">
{!widget.migrationRequired && (
{widget.valid && (
<Button
component={Link}
href={`/manage/custom-widgets/edit/${widget.id}`}
@@ -97,17 +97,7 @@ function CustomWidgetRow({ widget }: { widget: WidgetDef }) {
size="sm"
leftSection={<IconPencil size={16} stroke={1.5} />}
>
{widget.valid ? tCommon("action.edit") : t("workbench.repair.title")}
</Button>
)}
{widget.valid && (
<Button
component={Link}
href={`/manage/custom-widgets/packages/convert/${widget.id}`}
variant="light"
size="sm"
>
{t("package.conversion.shortTitle")}
{tCommon("action.edit")}
</Button>
)}
<CustomWidgetRowActions
@@ -6,6 +6,8 @@ import { IconPlus, IconTrash } from "@tabler/icons-react";
import { useI18n } from "@homarr/translation/client";
import { CustomWidgetIntegrationOption } from "@homarr/widgets/custom-api/integration-option";
import { CodeEditor } from "./_code-editor";
export function DefaultValueEditor({
@@ -22,6 +24,8 @@ export function DefaultValueEditor({
onChange: (value: unknown) => void;
}) {
const t = useI18n("customWidget.workbench.builder");
if (control === "integration")
return <CustomWidgetIntegrationOption label={t("default")} value={value} onChange={onChange} />;
if (control === "switch")
return (
<Switch
@@ -6,7 +6,7 @@ interface PreviewSnapshot {
session: { id: string; liveActions: boolean } | null;
}
type PreviewCandidate = Pick<HomarrCustomWidgetV2, "requests" | "template">;
type PreviewCandidate = Pick<HomarrCustomWidgetV2, "requests" | "template" | "extensions">;
export function createPreviewDisplayData({
candidate,
@@ -23,15 +23,18 @@ export function createPreviewDisplayData({
}): Record<string, unknown> | null {
if (!candidate) return null;
const requests = Object.entries(candidate.requests);
const data = fixture === "empty" ? Object.fromEntries(requests.map(([id]) => [id, []])) : preview.data;
const queryIds = [...requests.map(([id]) => id), ...Object.keys(candidate.extensions?.native ?? {})];
const data =
fixture === "empty" ? Object.fromEntries(queryIds.map((id) => [id, emptyFixture(preview.data[id])])) : preview.data;
const status =
fixture === "loading"
? Object.fromEntries(requests.map(([id]) => [id, { loading: true }]))
? Object.fromEntries(queryIds.map((id) => [id, { loading: true }]))
: fixture === "error"
? Object.fromEntries(requests.map(([id]) => [id, { loading: false, ok: false, error: fixtureError }]))
? Object.fromEntries(queryIds.map((id) => [id, { loading: false, ok: false, error: fixtureError }]))
: preview.status;
return {
template: candidate.template,
extensions: candidate.extensions,
data,
status,
options,
@@ -47,7 +50,14 @@ export function createPreviewDisplayData({
})),
previewSessionId: preview.session?.id,
previewLiveActions: preview.session?.liveActions ?? false,
queriesDisabled: fixture !== "live" || !preview.session,
queriesDisabled: fixture !== "live",
isEditMode: fixture !== "live",
};
}
function emptyFixture(value: unknown, depth = 0): unknown {
if (depth > 10 || Array.isArray(value) || value === undefined) return [];
if (value && typeof value === "object")
return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, emptyFixture(entry, depth + 1)]));
return value;
}
@@ -0,0 +1,124 @@
"use client";
import { useMemo } from "react";
import { Alert, Group, Stack, Switch, Tabs, Text } from "@mantine/core";
import { analyzeCustomWidgetAccessibility } from "@homarr/custom-widgets/workbench";
import { useI18n } from "@homarr/translation/client";
import type { PreviewPanelProps } from "./_flow/preview-panel-types";
import { PreviewRequestData } from "./_flow/preview-request-data";
import { WorkbenchRequestJournal } from "./_flow/request-journal";
import { PreviewStatusDot } from "./_custom-widget-preview-status";
import { PreviewActionControl } from "./_custom-widget-preview-action";
import { JsonPreviewEditor } from "./_json-preview-editor";
export function PreviewTabList({
outcome,
widgetLabel,
}: {
outcome: PreviewPanelProps["preview"]["outcome"];
widgetLabel?: string;
}) {
const t = useI18n("customWidget.workbench.preview");
const flowT = useI18n("customWidget.flow");
return (
<Tabs.List grow>
{(["widget", "data", "options", "actions", "diagnostics"] as const).map((tab) => (
<Tabs.Tab key={tab} value={tab}>
<Group gap={6} wrap="nowrap" justify="center">
{tab === "widget" && widgetLabel ? widgetLabel : t(`tab.${tab}`)}
{tab === "data" && <PreviewStatusDot outcome={outcome} label={t(`status.${outcome}`)} />}
</Group>
</Tabs.Tab>
))}
<Tabs.Tab value="journal">{flowT("requestJournal")}</Tabs.Tab>
</Tabs.List>
);
}
export function PreviewDetailPanels(
props: PreviewPanelProps & {
requestId?: string;
onShowAll(): void;
liveActions: { pending: boolean; toggle(enabled: boolean): void };
},
) {
const t = useI18n("customWidget.workbench.preview");
const candidate = props.candidate;
const candidateTemplate = candidate?.template;
const accessibilityIssues = useMemo(() => {
if (candidateTemplate === undefined) return [];
return analyzeCustomWidgetAccessibility(candidateTemplate);
}, [candidateTemplate]);
return (
<>
<Tabs.Panel value="data" pt="sm">
<PreviewRequestData preview={props.preview} requestId={props.requestId} onShowAll={props.onShowAll} />
</Tabs.Panel>
<Tabs.Panel value="journal" pt="sm">
<WorkbenchRequestJournal />
</Tabs.Panel>
<Tabs.Panel value="options" pt="sm">
<JsonPreviewEditor
id="preview-options"
label={t("instanceOptions")}
value={props.optionsSnapshot}
onChange={props.onOptionsChange}
/>
</Tabs.Panel>
<Tabs.Panel value="actions" pt="sm">
<Stack gap="sm">
<Switch
label={t("liveActions")}
description={t("liveActionsDescription")}
checked={props.preview.session?.liveActions ?? false}
disabled={!props.preview.session || props.liveActions.pending}
onChange={(event) => props.liveActions.toggle(event.currentTarget.checked)}
/>
{Object.entries(candidate?.requests ?? {})
.filter(([, request]) => request.kind === "action")
.map(([id, request]) => (
<PreviewActionControl key={id} request={{ id, ...request }} sessionId={props.preview.session?.id} />
))}
{Object.values(candidate?.requests ?? {}).every((request) => request.kind !== "action") && (
<Text size="sm" c="dimmed">
{t("noActions")}
</Text>
)}
</Stack>
</Tabs.Panel>
<Tabs.Panel value="diagnostics" pt="sm">
<Stack gap="xs">
<Text size="sm" c="dimmed">
{t("containedFailures")}
</Text>
<Text size="sm" fw={600}>
{t("validation.title")}
</Text>
{props.validationIssues.length === 0 ? (
<Alert color="green">{t("validation.ready")}</Alert>
) : (
props.validationIssues.map((issue, index) => (
<Alert key={`${issue.path ?? "widget"}-${index}`} color="red" title={issue.path}>
{issue.message}
</Alert>
))
)}
<Text size="sm" fw={600}>
{t("accessibility.title")}
</Text>
{!candidate ? (
<Alert color="gray">{t("accessibility.pending")}</Alert>
) : accessibilityIssues.length === 0 ? (
<Alert color="green">{t("accessibility.ready")}</Alert>
) : (
accessibilityIssues.map((issue) => (
<Alert key={issue} color="yellow">
{t(`accessibility.${issue}`)}
</Alert>
))
)}
</Stack>
</Tabs.Panel>
</>
);
}
@@ -1,6 +1,7 @@
// @vitest-environment jsdom
import { act } from "react";
import type { ReactNode } from "react";
import { createRoot } from "react-dom/client";
import type { Root } from "react-dom/client";
import { MantineProvider } from "@mantine/core";
@@ -38,6 +39,9 @@ vi.mock("./_code-editor", () => ({
return <div>{props.label}</div>;
},
}));
vi.mock("./_flow/preview-theme", () => ({
WorkbenchPreviewSurface: ({ children }: { children: ReactNode }) => children,
}));
vi.mock("./_custom-widget-preview-action", () => ({ PreviewActionControl: () => <div>action-control</div> }));
let root: Root;
@@ -105,21 +109,21 @@ describe("Custom Widget preview panel", () => {
await act(async () => dataTab?.click());
expect(host.textContent).toContain("requestData");
expect(codeEditorProps).toHaveBeenCalledWith(expect.objectContaining({ label: "requestData", readOnly: true }));
expect(host.textContent).not.toContain("invalid");
expect(previewCanvas?.closest<HTMLElement>('[role="tabpanel"]')?.style.display).toBe("none");
const optionsTab = [...host.querySelectorAll<HTMLElement>('[role="tab"]')].find((element) =>
element.textContent?.includes("tab.options"),
);
await act(async () => optionsTab?.click());
expect(host.textContent).toContain("instanceOptions");
expect(host.textContent).not.toContain("invalid");
expect(previewCanvas?.closest<HTMLElement>('[role="tabpanel"]')?.style.display).toBe("none");
const actionsTab = [...host.querySelectorAll<HTMLElement>('[role="tab"]')].find((element) =>
element.textContent?.includes("tab.actions"),
);
await act(async () => actionsTab?.click());
expect(host.textContent).toContain("liveActions");
expect(host.textContent).not.toContain("invalid");
expect(previewCanvas?.closest<HTMLElement>('[role="tabpanel"]')?.style.display).toBe("none");
const diagnosticsTab = [...host.querySelectorAll<HTMLElement>('[role="tab"]')].find((element) =>
element.textContent?.includes("tab.diagnostics"),
@@ -1,71 +1,51 @@
"use client";
import { memo, useMemo, useState } from "react";
import { Alert, Box, Card, Group, Paper, SegmentedControl, Stack, Switch, Tabs, Text } from "@mantine/core";
import { clientApi } from "@homarr/api/client";
import type { HomarrCustomWidgetV2 } from "@homarr/custom-widgets/core";
import { analyzeCustomWidgetAccessibility, PreviewErrorBoundary } from "@homarr/custom-widgets/workbench";
import { showErrorNotification } from "@homarr/notifications";
import { memo, useMemo, useState, useRef, useEffect } from "react";
import { Box, Card, Group, Stack, Tabs, Text } from "@mantine/core";
import { useI18n } from "@homarr/translation/client";
import CustomJsxDisplay from "@homarr/widgets/custom-api/custom-jsx-display";
import { CodeEditor } from "./_code-editor";
import { WorkbenchPreviewWidget, workbenchPreviewWidth } from "./_flow/preview-widget";
import { WorkbenchPreviewControls, WorkbenchPreviewTools } from "./_flow/preview-controls";
import { useWorkbenchPreviewPresentation } from "./_flow/preview-presentation";
import { WorkbenchPreviewThemeControl } from "./_flow/preview-theme";
import type { PreviewPanelProps, PreviewFixture } from "./_flow/preview-panel-types";
import { usePreviewExecution } from "./_flow/preview-execution";
import { usePreviewLiveActions } from "./_flow/preview-live-actions";
import { getPreviewSummary, PreviewResult, PreviewStatusDot } from "./_custom-widget-preview-status";
import type { PreviewOutcome } from "./_custom-widget-preview-status";
import { PreviewActionControl } from "./_custom-widget-preview-action";
import { PreviewDetailPanels, PreviewTabList } from "./_custom-widget-preview-details";
import { createPreviewDisplayData } from "./_custom-widget-preview-data";
import { CustomWidgetPreviewSizeControl } from "./_custom-widget-preview-size-control";
import { JsonPreviewEditor } from "./_json-preview-editor";
import classes from "./_custom-widget-form.module.css";
const previewWidths: Record<string, number> = { compact: 320, standard: 480, wide: 720 };
export interface PreviewState {
data: Record<string, unknown>;
status: Record<string, unknown>;
session: { id: string; expiresAt: number; liveActions: boolean } | null;
outcome: PreviewOutcome;
stale?: boolean;
}
interface PreviewPanelProps {
candidate: HomarrCustomWidgetV2 | null;
validationIssues: Array<{ path?: string; message: string }>;
preview: PreviewState;
size: string;
onSizeChange(value: string): void;
optionsSnapshot: Record<string, unknown>;
onOptionsChange(value: Record<string, unknown>): void;
onLiveActionsChange(enabled: boolean, sessionId: string): void;
}
export type { PreviewState } from "./_flow/preview-state";
function CustomWidgetPreviewPanelContent(props: PreviewPanelProps) {
const t = useI18n("customWidget.workbench.preview");
const errorBoundaryMessages = useI18n("customWidget.editor.errorBoundary");
const actionT = useI18n("common.action");
const [fixture, setFixture] = useState<"live" | "loading" | "empty" | "error">("live");
const liveActionsMutation = clientApi.customWidget.setPreviewLiveActions.useMutation();
const journalQuery = clientApi.customWidget.previewJournal.useQuery(
{ sessionId: props.preview.session?.id ?? "" },
{ enabled: Boolean(props.preview.session), refetchInterval: props.preview.session ? 2_000 : false },
);
const candidate = props.candidate;
const [inspect, setInspect] = useState(false);
const [fixture, setFixture] = useState<PreviewFixture>("live");
const execution = usePreviewExecution();
const liveActions = usePreviewLiveActions(props);
const presentation = useWorkbenchPreviewPresentation();
const canvas = presentation === "canvas";
const lastValid = useRef(props.candidate);
useEffect(() => {
if (props.candidate) lastValid.current = props.candidate;
}, [props.candidate]);
const candidate = props.candidate ?? lastValid.current;
const flowT = useI18n("customWidget.flow");
const candidateExtensions = candidate?.extensions;
const candidateTemplate = candidate?.template;
const candidateRequests = candidate?.requests;
const hasActions =
Object.values(candidateRequests ?? {}).some((request) => request.kind === "action") ||
Object.values(candidateExtensions?.native ?? {}).some((capability) => capability.kind === "action");
const previewCandidate = useMemo(() => {
if (candidateTemplate === undefined || candidateRequests === undefined) return null;
return { template: candidateTemplate, requests: candidateRequests };
}, [candidateRequests, candidateTemplate]);
return { template: candidateTemplate, requests: candidateRequests, extensions: candidateExtensions };
}, [candidateRequests, candidateTemplate, candidateExtensions]);
const previewSnapshot = useMemo(
() => ({ data: props.preview.data, status: props.preview.status, session: props.preview.session }),
[props.preview.data, props.preview.session, props.preview.status],
);
const fixtureError = t("fixtureError");
const accessibilityIssues = useMemo(() => {
if (candidateTemplate === undefined) return [];
return analyzeCustomWidgetAccessibility(candidateTemplate);
}, [candidateTemplate]);
const displayData = useMemo(
() =>
createPreviewDisplayData({
@@ -83,6 +63,7 @@ function CustomWidgetPreviewPanelContent(props: PreviewPanelProps) {
JSON.stringify({
template: candidateTemplate,
requests: candidateRequests,
extensions: candidateExtensions,
fixture,
data: props.preview.data,
status: props.preview.status,
@@ -92,6 +73,7 @@ function CustomWidgetPreviewPanelContent(props: PreviewPanelProps) {
[
candidateRequests,
candidateTemplate,
candidateExtensions,
fixture,
props.optionsSnapshot,
props.preview.data,
@@ -114,163 +96,114 @@ function CustomWidgetPreviewPanelContent(props: PreviewPanelProps) {
? { title: t("result.loading.title"), description: t("result.loading.description") }
: { title: "", description: "" };
const controls = (
<WorkbenchPreviewControls
size={props.size}
onSizeChange={props.onSizeChange}
inspect={inspect}
onInspectChange={setInspect}
fixture={fixture}
onFixtureChange={setFixture}
disabled={!candidate}
/>
);
const result = candidate && (
<PreviewResult
outcome={props.preview.outcome}
title={previewResult.title}
description={previewResult.description}
/>
);
const details = (
<PreviewDetailPanels
{...props}
candidate={candidate}
requestId={execution.requestId}
onShowAll={execution.showAll}
liveActions={liveActions}
/>
);
return (
<Card withBorder p="md">
<Stack gap="md">
<Group gap="xs" justify="space-between">
<CustomWidgetPreviewSizeControl value={props.size} onChange={props.onSizeChange} />
<SegmentedControl
size="xs"
value={fixture}
disabled={!candidate}
onChange={(value) => setFixture(value as typeof fixture)}
data={[
{ value: "live", label: t("fixture.live") },
{ value: "loading", label: t("fixture.loading") },
{ value: "empty", label: t("fixture.empty") },
{ value: "error", label: t("fixture.error") },
]}
/>
</Group>
{props.preview.stale && <Alert color="yellow">{t("staleSnapshot")}</Alert>}
{candidate && (
<PreviewResult
outcome={props.preview.outcome}
title={previewResult.title}
description={previewResult.description}
/>
<Card
withBorder={!canvas}
p={canvas ? 0 : "xs"}
w={canvas ? workbenchPreviewWidth(props.size) : undefined}
data-preview-presentation={presentation}
className="nodrag nopan nowheel"
>
<Stack gap="xs">
{(props.preview.stale || !props.candidate) && (
<Text size="xs" c="dimmed" component="output">
{flowT("stalePreview")}
</Text>
)}
<Tabs defaultValue="widget" keepMounted={false}>
<Tabs.List grow>
{(["widget", "data", "options", "actions", "diagnostics"] as const).map((tab) => (
<Tabs.Tab key={tab} value={tab}>
<Group gap={6} wrap="nowrap" justify="center">
{t(`tab.${tab}`)}
{tab === "data" && (
<PreviewStatusDot outcome={props.preview.outcome} label={t(`status.${props.preview.outcome}`)} />
)}
</Group>
</Tabs.Tab>
))}
</Tabs.List>
<Tabs.Panel value="widget" pt="sm">
<Box className={classes.previewCanvas}>
<Paper
withBorder
p="sm"
h={360}
w={previewWidths[props.size] ?? 480}
maw="100%"
style={{ overflow: "auto" }}
>
{displayData ? (
<PreviewErrorBoundary
title={errorBoundaryMessages("title")}
description={t("containedFailures")}
retryLabel={actionT("tryAgain")}
resetKeys={[rendererResetKey]}
>
<CustomJsxDisplay data={displayData} />
</PreviewErrorBoundary>
) : (
<Alert color="yellow">{t("invalid")}</Alert>
)}
</Paper>
</Box>
</Tabs.Panel>
<Tabs.Panel value="data" pt="sm">
<CodeEditor
id="preview-data"
label={t("requestData")}
language="json"
value={JSON.stringify({ data: props.preview.data, status: props.preview.status }, null, 2)}
readOnly
onChange={() => undefined}
/>
</Tabs.Panel>
<Tabs.Panel value="options" pt="sm">
<JsonPreviewEditor
id="preview-options"
label={t("instanceOptions")}
value={props.optionsSnapshot}
onChange={props.onOptionsChange}
/>
</Tabs.Panel>
<Tabs.Panel value="actions" pt="sm">
<Stack gap="sm">
<Switch
label={t("liveActions")}
description={t("liveActionsDescription")}
checked={props.preview.session?.liveActions ?? false}
disabled={!props.preview.session || liveActionsMutation.isPending}
onChange={(event) => {
if (!props.preview.session) return;
const sessionId = props.preview.session.id;
const enabled = event.currentTarget.checked;
liveActionsMutation.mutate(
{ sessionId: props.preview.session.id, enabled },
{
onSuccess: () => props.onLiveActionsChange(enabled, sessionId),
onError: (error) => showErrorNotification({ title: t("liveActions"), message: error.message }),
},
);
}}
/>
{Object.entries(candidate?.requests ?? {})
.filter(([, request]) => request.kind === "action")
.map(([id, request]) => (
<PreviewActionControl key={id} request={{ id, ...request }} sessionId={props.preview.session?.id} />
))}
{Object.values(candidate?.requests ?? {}).every((request) => request.kind !== "action") && (
<Text size="sm" c="dimmed">
{t("noActions")}
{canvas && (
<Group gap="xs" justify="space-between" wrap="nowrap">
<Group gap={6} wrap="nowrap">
<PreviewStatusDot outcome={props.preview.outcome} label={t(`status.${props.preview.outcome}`)} />
{hasActions && (
<Text size="xs" c="dimmed">
{props.preview.session?.liveActions ? t("liveActions") : flowT("previewActionsSimulated")}
</Text>
)}
</Stack>
</Tabs.Panel>
<Tabs.Panel value="diagnostics" pt="sm">
<Stack gap="xs">
<Text size="sm" c="dimmed">
{t("containedFailures")}
</Text>
<Text size="sm" fw={600}>
{t("validation.title")}
</Text>
{props.validationIssues.length === 0 ? (
<Alert color="green">{t("validation.ready")}</Alert>
) : (
props.validationIssues.map((issue, index) => (
<Alert key={`${issue.path ?? "widget"}-${index}`} color="red" title={issue.path}>
{issue.message}
</Alert>
))
)}
<Text size="sm" fw={600}>
{t("accessibility.title")}
</Text>
{!candidate ? (
<Alert color="gray">{t("accessibility.pending")}</Alert>
) : accessibilityIssues.length === 0 ? (
<Alert color="green">{t("accessibility.ready")}</Alert>
) : (
accessibilityIssues.map((issue) => (
<Alert key={issue} color="yellow">
{t(`accessibility.${issue}`)}
</Alert>
))
)}
{props.preview.session && (
<CodeEditor
id="preview-journal"
label={t("journal")}
language="json"
value={JSON.stringify(journalQuery.data ?? [], null, 2)}
readOnly
onChange={() => undefined}
/>
)}
</Stack>
</Group>
<WorkbenchPreviewTools revealVersion={execution.revealVersion}>
<Tabs
value={execution.activeTab}
onChange={execution.setActiveTab}
keepMounted
keepMountedMode="display-none"
>
<PreviewTabList outcome={props.preview.outcome} widgetLabel={flowT("previewDisplay")} />
<Tabs.Panel value="widget" pt="sm">
<Stack gap="sm">
{controls}
<WorkbenchPreviewThemeControl />
{result}
</Stack>
</Tabs.Panel>
{details}
</Tabs>
</WorkbenchPreviewTools>
</Group>
)}
{!canvas && controls}
{!canvas && result}
<Tabs
value={canvas ? "widget" : execution.activeTab}
onChange={execution.setActiveTab}
keepMounted
keepMountedMode="display-none"
>
{!canvas && <PreviewTabList outcome={props.preview.outcome} />}
<Tabs.Panel
key="widget-renderer"
value="widget"
pt={canvas ? 0 : "sm"}
renderRoot={(attributes) => {
if (canvas) {
const canvasAttributes = { ...attributes };
delete canvasAttributes.role;
delete canvasAttributes["aria-labelledby"];
return <section {...canvasAttributes} aria-label={t("tab.widget")} />;
}
return <section {...attributes} />;
}}
>
<Box
className={classes.previewCanvas}
style={canvas ? { padding: 0, background: "none", overflow: "visible" } : undefined}
>
<WorkbenchPreviewWidget
data={displayData}
size={props.size}
inspect={inspect}
resetKey={rendererResetKey}
/>
</Box>
</Tabs.Panel>
{!canvas && details}
</Tabs>
</Stack>
</Card>
@@ -5,6 +5,8 @@ import type { CustomWidgetWorkbenchForm } from "./_custom-widget-form-utils";
interface RenameHandlersInput {
form: CustomWidgetWorkbenchForm;
transaction(action: () => void): void;
renameRequestBinding(previousId: string, nextId: string): void;
invalidWidgetMessage: string;
}
@@ -16,7 +18,11 @@ export function createCustomWidgetRenameHandlers(input: RenameHandlersInput) {
return;
}
try {
applyDefinition(input.form, renameCustomWidgetRequest(candidate.data, currentId, nextId));
input.transaction(() => {
const renamed = renameCustomWidgetRequest(candidate.data, currentId, nextId);
input.renameRequestBinding(currentId, nextId);
applyDefinition(input.form, renamed);
});
input.form.clearFieldError("requests");
} catch (error) {
input.form.setFieldError("requests", error instanceof Error ? error.message : input.invalidWidgetMessage);
@@ -29,7 +35,9 @@ export function createCustomWidgetRenameHandlers(input: RenameHandlersInput) {
return;
}
try {
applyDefinition(input.form, renameCustomWidgetOption(candidate.data, currentName, nextName));
input.transaction(() =>
applyDefinition(input.form, renameCustomWidgetOption(candidate.data, currentName, nextName)),
);
input.form.clearFieldError("options");
} catch (error) {
input.form.setFieldError("options", error instanceof Error ? error.message : input.invalidWidgetMessage);
@@ -1,92 +0,0 @@
"use client";
import { useState } from "react";
import { Alert, Button, Group, Stack, Text, Title } from "@mantine/core";
import { parse } from "superjson";
import type { RouterOutputs } from "@homarr/api";
import { clientApi } from "@homarr/api/client";
import { customWidgetDefinitionSchema } from "@homarr/custom-widgets/core";
import { useI18n } from "@homarr/translation/client";
import { CodeEditor } from "~/components/custom-widgets/code-editor";
function readStored(value: string): unknown {
try {
return parse(value);
} catch {
return value;
}
}
export function CustomWidgetRepair({ definition }: { definition: RouterOutputs["customWidget"]["getRaw"] }) {
const t = useI18n("customWidget.workbench.repair");
const [source, setSource] = useState(() =>
JSON.stringify(
{
$schema: "homarr-custom-widget-v2",
name: definition.name,
description: definition.description ?? undefined,
iconUrl: definition.iconUrl ?? undefined,
sources: readStored(definition.sources),
requests: readStored(definition.requests),
options: readStored(definition.options),
template: definition.template,
},
null,
2,
),
);
const [error, setError] = useState("");
const repair = clientApi.customWidget.repair.useMutation();
const save = async () => {
try {
const parsed: unknown = JSON.parse(source);
const widget = customWidgetDefinitionSchema.parse(parsed);
const result = await repair.mutateAsync({ id: definition.id, widget });
window.location.assign(result.managementPath);
} catch (cause) {
setError(cause instanceof Error ? cause.message : String(cause));
}
};
const download = () => {
const url = URL.createObjectURL(new Blob([source], { type: "application/json" }));
const anchor = document.createElement("a");
anchor.href = url;
anchor.download = `${definition.id}-repair.json`;
anchor.click();
URL.revokeObjectURL(url);
};
return (
<Stack>
<Title>
{t("title")}: {definition.name}
</Title>
<Alert color="yellow">
<Text>{t("description")}</Text>
{definition.issues.map((issue, index) => (
<Text size="sm" key={index}>
{issue.path}: {issue.message}
</Text>
))}
</Alert>
{error && <Alert color="red">{error}</Alert>}
<CodeEditor
id="repair-source"
label={t("source")}
language="json"
value={source}
onChange={setSource}
height="60vh"
/>
<Group>
<Button loading={repair.isPending} onClick={() => void save()}>
{t("save")}
</Button>
<Button variant="default" onClick={download}>
{t("export")}
</Button>
</Group>
</Stack>
);
}
@@ -157,11 +157,16 @@ export function RequestBodyEditor({
const [optionName, setOptionName] = useState<string | null>(optionNames[0] ?? null);
const [parameterName, setParameterName] = useState("");
const [insertion, setInsertion] = useState({ text: "", key: 0 });
useEffect(() => setDraft(serialized), [serialized]);
useEffect(() => {
setDraft(serialized);
setError(undefined);
}, [serialized]);
return (
<Stack gap="xs">
<CodeEditor
id={`${id}-request-body-editor`}
// Incomplete JSON is a local buffer; its undo must not change another document field.
localHistory
label={t("jsonBody")}
description={t("jsonBodyDescription")}
language="json"
@@ -182,7 +187,7 @@ export function RequestBodyEditor({
}
}}
/>
<Group align="end" wrap="wrap">
<Group align="end" wrap="wrap" data-workbench-local-input>
<Select label={t("option")} data={optionNames} value={optionName} searchable onChange={setOptionName} />
<Button
type="button"
@@ -1,5 +1,10 @@
"use client";
import { useConfirmModal } from "@homarr/modals";
import { projectWidgetGraph } from "./_flow/graph";
import { useCustomWidgetFormDocumentStore } from "./_custom-widget-form-state";
import { useWorkbenchSelection } from "./_flow/selection";
import { ActionIcon, Button, Fieldset, Group, Select, Stack, Switch, Text, TextInput } from "@mantine/core";
import { IconArrowDown, IconArrowUp, IconPlus, IconTrash } from "@tabler/icons-react";
@@ -20,11 +25,15 @@ export function CustomWidgetRequestsEditor({
form: CustomWidgetWorkbenchForm;
onRename(currentId: string, nextId: string): void;
}) {
const selection = useWorkbenchSelection();
const store = useCustomWidgetFormDocumentStore();
const flowT = useI18n("customWidget.flow");
const { openConfirmModal } = useConfirmModal();
const t = useI18n("customWidget.workbench.builder");
const parsed = parseJson(form.values.requests);
const entries = isRecord(parsed) ? Object.entries(parsed) : [];
const sources = parseJson(form.values.sources);
const sourceIds = isRecord(sources) ? Object.keys(sources) : [];
const sourceIds = isRecord(sources) ? Object.keys(sources) : ["default"];
const options = parseJson(form.values.options);
const optionNames = isRecord(options) ? Object.keys(options) : [];
@@ -32,7 +41,24 @@ export function CustomWidgetRequestsEditor({
form.setFieldValue("requests", JSON.stringify(Object.fromEntries(next), null, 2));
const update = (index: number, id: string, request: Record<string, unknown>) =>
commit(entries.map((entry, i) => (i === index ? [id, request] : entry)));
const remove = (index: number) => commit(entries.filter((_, i) => i !== index));
const remove = (index: number) => {
const id = entries[index]?.[0];
const graph = projectWidgetGraph(form.values, store.getLayout());
const references = graph.edges
.filter((edge) => edge.source === `request:${id}` || edge.target === `request:${id}`)
.filter((edge) => edge.data?.relationship !== "source")
.map((edge) => (edge.source === `request:${id}` ? edge.target : edge.source));
const apply = () => store.transaction(() => commit(entries.filter((_, i) => i !== index)));
if (!references.length) {
apply();
return;
}
openConfirmModal({
title: flowT("removeReferenced"),
children: flowT("removeReferencedDescription", { references: [...new Set(references)].join(", ") }),
onConfirm: apply,
});
};
const move = (index: number, direction: -1 | 1) => {
const next = [...entries];
const target = index + direction;
@@ -41,28 +67,22 @@ export function CustomWidgetRequestsEditor({
commit(next);
};
const add = () => {
const source = sourceIds[0];
if (!source) return;
let suffix = entries.length + 1;
while (entries.some(([id]) => id === `request-${suffix}`)) suffix += 1;
commit([...entries, [`request-${suffix}`, { source, path: "/api/data" }]]);
commit([...entries, [`request-${suffix}`, { path: "/api/data" }]]);
};
return (
<Stack gap="sm">
{sourceIds.length === 0 && (
<Text size="sm" c="dimmed">
{t("sourceRequired")}
</Text>
)}
{entries.map(([id, rawRequest], index) => {
if (selection && selection !== `request:${id}`) return null;
const request = isRecord(rawRequest) ? rawRequest : {};
const kind = request.kind === "action" ? "action" : "query";
const trigger = request.trigger === "manual" ? "manual" : "load";
return (
<Fieldset key={id} legend={id || t("request", { count: index + 1 })}>
<Fieldset key={id} legend={id || t("request", { count: index + 1 })} data-workbench-request={id}>
<Stack gap="sm">
<Group grow align="start">
<Group grow align="start" data-workbench-request-row>
<CustomWidgetIdentifierInput
label={t("requestId")}
value={id}
@@ -96,7 +116,7 @@ export function CustomWidgetRequestsEditor({
}
/>
</Group>
<Group grow align="start">
<Group grow align="start" data-workbench-request-row>
<Select
label={t("source")}
data={sourceIds}
@@ -128,6 +148,7 @@ export function CustomWidgetRequestsEditor({
</Group>
<TextInput
label={t("path")}
data-workbench-request-path
description={t("pathDescription")}
descriptionProps={{
style: { color: "light-dark(var(--mantine-color-gray-7), var(--mantine-color-gray-4))" },
@@ -219,13 +240,7 @@ export function CustomWidgetRequestsEditor({
</Fieldset>
);
})}
<Button
type="button"
variant="light"
leftSection={<IconPlus size={16} />}
onClick={add}
disabled={sourceIds.length === 0 || entries.length >= 64}
>
<Button type="button" variant="light" leftSection={<IconPlus size={16} />} onClick={add}>
{t("addRequest")}
</Button>
{form.errors.requests && (
@@ -1,30 +0,0 @@
import type { CustomWidgetFormValues } from "@homarr/custom-widgets/workbench";
import type { CustomWidgetFormDocumentStore } from "./_custom-widget-form-state";
import type { CustomWidgetWorkbenchForm } from "./_custom-widget-form-utils";
export function applyCustomWidgetSavedState(
form: CustomWidgetWorkbenchForm,
store: CustomWidgetFormDocumentStore,
submitted: CustomWidgetFormValues,
) {
const savedValues = {
...submitted,
secrets: submitted.secrets.map((secret) => {
if (!secret.value.trim()) return secret;
return { ...secret, value: "", hasValue: true };
}),
};
const currentValues = store.getValues();
form.setInitialValues(savedValues);
form.setValues({
...currentValues,
secrets: currentValues.secrets.map((secret) => {
const saved = submitted.secrets.find((entry) => entry.sourceId === secret.sourceId && entry.kind === secret.kind);
if (!saved?.value.trim() || saved.value !== secret.value) return secret;
return { ...secret, value: "", hasValue: true };
}),
});
form.resetDirty();
store.markSaved(savedValues);
}
@@ -0,0 +1,39 @@
import type { CustomWidgetFormValues } from "@homarr/custom-widgets/workbench";
type Secrets = CustomWidgetFormValues["secrets"];
export function getSourceSecretRenames(secrets: Secrets) {
return Object.fromEntries(
secrets.flatMap((secret) => {
if (!secret.hasValue || secret.value.trim() || !secret.savedSourceId || secret.savedSourceId === secret.sourceId)
return [];
return [[secret.savedSourceId, secret.sourceId]];
}),
);
}
/** A save changes where credentials live, including when the user renamed a
* source again while that save was in flight. Preserve newer input values. */
export function markSourceSecretsSaved(
submitted: Secrets,
current: Secrets,
presence?: Array<{ sourceId: string; kind: string }>,
): Secrets {
return current.map((secret) => {
const saved = submitted.find(
(candidate) =>
candidate.kind === secret.kind &&
(candidate.savedSourceId ?? candidate.sourceId) === (secret.savedSourceId ?? secret.sourceId),
);
if (!saved) return secret;
const { savedSourceId: _previousSourceId, ...next } = secret;
let hasValue = Boolean(saved.hasValue || saved.value.trim());
if (presence) hasValue = presence.some((entry) => entry.sourceId === saved.sourceId && entry.kind === saved.kind);
return {
...next,
hasValue,
value: secret.value === saved.value ? "" : secret.value,
...(hasValue && secret.sourceId !== saved.sourceId ? { savedSourceId: saved.sourceId } : {}),
};
});
}
@@ -3,14 +3,14 @@ import { isRecord } from "@homarr/common";
export function getDependentRequestIds(requestsJson: string, sourceId: string) {
const requests = parseRequestRecord(requestsJson);
return Object.entries(requests).flatMap(([requestId, request]) =>
isRecord(request) && (request.source ?? "default") === sourceId ? [requestId] : [],
isRecord(request) && request.source === sourceId ? [requestId] : [],
);
}
export function removeDependentRequests(requestsJson: string, sourceId: string) {
return Object.fromEntries(
Object.entries(parseRequestRecord(requestsJson)).filter(
([, request]) => !isRecord(request) || (request.source ?? "default") !== sourceId,
([, request]) => !isRecord(request) || request.source !== sourceId,
),
);
}
@@ -7,6 +7,8 @@ import { getCustomWidgetSourceUrlIssue } from "@homarr/custom-widgets/core";
import type { CustomWidgetSource, CustomWidgetSourceUrlIssue } from "@homarr/custom-widgets/core";
import { useI18n } from "@homarr/translation/client";
import { SourceNetworkHint } from "./_flow/source-network-hint";
import type { CustomWidgetWorkbenchForm } from "./_custom-widget-form-utils";
import { CustomWidgetIdentifierInput } from "./_custom-widget-identifier-input";
@@ -57,13 +59,13 @@ export function CustomWidgetSourceField({
const authType = typeof source.auth === "string" ? source.auth : source.auth.type;
return (
<Fieldset legend={source.name ?? source.id}>
<Fieldset legend={index === 0 ? t("primary") : source.name}>
<Stack gap="sm">
<Group grow align="start">
<CustomWidgetIdentifierInput
label={t("id")}
value={source.id}
disabled={Boolean(definitionId)}
disabled={source.id === "default" || Boolean(definitionId)}
error={form.errors.sources}
onCommit={(value) => onUpdate(index, { id: value })}
/>
@@ -98,6 +100,7 @@ export function CustomWidgetSourceField({
allowDeselect={false}
/>
</Group>
<SourceNetworkHint source={source} onChange={(networkScope) => onUpdate(index, { networkScope })} />
{typeof source.auth === "object" && source.auth.type === "apiKeyHeader" && (
<TextInput
label={t("headerName")}
@@ -116,9 +119,8 @@ export function CustomWidgetSourceField({
const secret = form.values.secrets.find((entry) => entry.sourceId === source.id && entry.kind === kind);
const Input = kind === "username" ? TextInput : PasswordInput;
return (
<Group key={kind} align="end" wrap="nowrap">
<Group key={kind} align="end" wrap="nowrap" data-workbench-credential>
<Input
data-custom-widget-secret
style={{ flex: 1 }}
label={tSecret(kind)}
value={secret?.value ?? ""}
@@ -132,6 +134,7 @@ export function CustomWidgetSourceField({
color="red"
variant="subtle"
loading={clearSecretPending}
disabled={form.submitting}
onClick={() => void onClearSecret(source.id, kind)}
>
{t("clear")}
@@ -140,15 +143,17 @@ export function CustomWidgetSourceField({
</Group>
);
})}
<Button
type="button"
color="red"
variant="subtle"
leftSection={<IconTrash size={16} />}
onClick={() => onRemove(index)}
>
{t("remove")}
</Button>
{
<Button
type="button"
color="red"
variant="subtle"
leftSection={<IconTrash size={16} />}
onClick={() => onRemove(index)}
>
{t("remove")}
</Button>
}
</Stack>
</Fieldset>
);
@@ -1,6 +1,9 @@
"use client";
import { Button, List, Stack, Text } from "@mantine/core";
import { useCustomWidgetFormDocumentStore } from "./_custom-widget-form-state";
import { useWorkbenchSelection } from "./_flow/selection";
import { Accordion, Button, List, Stack, Text } from "@mantine/core";
import { IconPlus } from "@tabler/icons-react";
import { clientApi } from "@homarr/api/client";
@@ -21,6 +24,8 @@ export function CustomWidgetSourcesEditor({
form: CustomWidgetWorkbenchForm;
definitionId?: string;
}) {
const selection = useWorkbenchSelection();
const store = useCustomWidgetFormDocumentStore();
const t = useI18n("customWidget.workbench.sources");
const w = useI18n("customWidget.workbench");
const { openConfirmModal } = useConfirmModal();
@@ -34,7 +39,16 @@ export function CustomWidgetSourcesEditor({
form.setFieldError("sources", t("duplicateSourceId"));
return;
}
let parsedRequests: unknown;
if (previousId !== nextId) {
parsedRequests = parseJson(form.values.requests);
if (!isRecord(parsedRequests)) {
form.setFieldError("sources", w("invalidWidget"));
return;
}
}
if (form.errors.sources === t("duplicateSourceId")) form.clearFieldError("sources");
if (previousId && nextId && previousId !== nextId) store.renameSourceBinding(previousId, nextId);
const sourceEntries = sources.map(({ id, ...source }) => [id, source] as const);
form.setFieldValue(
"sources",
@@ -50,7 +64,6 @@ export function CustomWidgetSourcesEditor({
),
);
if (previousId && nextId && previousId !== nextId) {
const parsedRequests = parseJson(form.values.requests);
const requests = isRecord(parsedRequests)
? Object.fromEntries(
Object.entries(parsedRequests).map(([id, request]) => [
@@ -65,7 +78,13 @@ export function CustomWidgetSourcesEditor({
form.setFieldValue(
"secrets",
form.values.secrets.map((secret) =>
secret.sourceId === previousId ? { ...secret, sourceId: nextId } : secret,
secret.sourceId === previousId
? {
...secret,
sourceId: nextId,
...(secret.hasValue ? { savedSourceId: secret.savedSourceId ?? previousId } : {}),
}
: secret,
),
);
}
@@ -86,7 +105,10 @@ export function CustomWidgetSourcesEditor({
const setSecret = (sourceId: string, kind: string, value: string) => {
const current = form.values.secrets.filter((secret) => !(secret.sourceId === sourceId && secret.kind === kind));
const existing = form.values.secrets.find((secret) => secret.sourceId === sourceId && secret.kind === kind);
form.setFieldValue("secrets", [...current, { sourceId, kind, value, hasValue: existing?.hasValue }]);
form.setFieldValue("secrets", [
...current,
{ sourceId, kind, value, hasValue: existing?.hasValue, savedSourceId: existing?.savedSourceId },
]);
};
const addSource = () => {
let suffix = sources.length + 1;
@@ -102,7 +124,7 @@ export function CustomWidgetSourcesEditor({
{
name: t("newName", { count: sources.length + 1 }),
baseUrl: "https://example.com",
networkScope: "private",
networkScope: sources.length === 0 ? "public" : "private",
auth: "none",
},
],
@@ -134,7 +156,7 @@ export function CustomWidgetSourcesEditor({
if (!removedId) return;
const dependentRequestIds = getDependentRequestIds(form.values.requests, removedId);
if (dependentRequestIds.length === 0) {
removeSourceAndDependents(index);
store.transaction(() => removeSourceAndDependents(index));
return;
}
openConfirmModal({
@@ -152,12 +174,16 @@ export function CustomWidgetSourcesEditor({
</Stack>
),
confirmProps: { children: t("remove") },
onConfirm: () => removeSourceAndDependents(index),
onConfirm: () => store.transaction(() => removeSourceAndDependents(index)),
});
};
const clearSecret = async (sourceId: string, kind: "apiKey" | "username" | "password") => {
if (form.submitting) return;
if (!definitionId) return;
await clearSecretMutation.mutateAsync({ definitionId, sourceId, kind });
const savedSourceId = form.values.secrets.find(
(secret) => secret.sourceId === sourceId && secret.kind === kind,
)?.savedSourceId;
await clearSecretMutation.mutateAsync({ definitionId, sourceId: savedSourceId ?? sourceId, kind });
const current = form.values.secrets.filter((secret) => !(secret.sourceId === sourceId && secret.kind === kind));
form.setFieldValue("secrets", [...current, { sourceId, kind, value: "", hasValue: false }]);
await utils.customWidget.get.invalidate({ id: definitionId });
@@ -166,12 +192,8 @@ export function CustomWidgetSourcesEditor({
return (
<Stack gap="sm">
{sources.length === 0 && (
<Text size="sm" c="dimmed">
{t("empty")}
</Text>
)}
{sources.map((source, index) => {
if (selection && selection !== `source:${source.id}`) return null;
return (
<CustomWidgetSourceField
key={source.id}
@@ -180,23 +202,24 @@ export function CustomWidgetSourcesEditor({
form={form}
definitionId={definitionId}
clearSecretPending={clearSecretMutation.isPending}
onUpdate={update}
onSetAuthentication={setAuth}
onUpdate={(sourceIndex, changes) => store.transaction(() => update(sourceIndex, changes))}
onSetAuthentication={(sourceIndex, type) => store.transaction(() => setAuth(sourceIndex, type))}
onSetSecret={setSecret}
onClearSecret={clearSecret}
onRemove={removeSource}
/>
);
})}
<Button
type="button"
variant="light"
leftSection={<IconPlus size={16} />}
onClick={addSource}
disabled={sources.length >= 8}
>
{t("add")}
</Button>
<Accordion variant="contained">
<Accordion.Item value="advanced">
<Accordion.Control>{t("advanced")}</Accordion.Control>
<Accordion.Panel>
<Button type="button" variant="light" leftSection={<IconPlus size={16} />} onClick={addSource}>
{t("add")}
</Button>
</Accordion.Panel>
</Accordion.Item>
</Accordion>
{form.errors.sources && (
<Text c="red" size="xs">
{form.errors.sources}
@@ -1,13 +1,12 @@
"use client";
import { Tabs } from "@mantine/core";
import { IconApi, IconBuildingStore, IconPackage } from "@tabler/icons-react";
import { IconApi, IconBuildingStore } from "@tabler/icons-react";
import { useI18n } from "@homarr/translation/client";
import { Link } from "@homarr/ui";
const tabs = {
packages: "/manage/custom-widgets/packages",
installed: "/manage/custom-widgets",
workshop: "/manage/custom-widgets/workshop",
} as const;
@@ -19,13 +18,6 @@ export const CustomWidgetTabs = ({ active }: { active: keyof typeof tabs }) => {
return (
<Tabs value={tabs[active]}>
<Tabs.List aria-label={t("ariaLabel")}>
<Tabs.Tab
value={tabs.packages}
leftSection={<IconPackage size={16} stroke={1.5} />}
renderRoot={(props) => <Link href={tabs.packages} {...props} />}
>
{t("packages")}
</Tabs.Tab>
<Tabs.Tab
value={tabs.installed}
leftSection={<IconApi size={16} stroke={1.5} />}
@@ -0,0 +1,83 @@
# Custom Widget workbench
The flow editor projects the existing Custom Widget definition. It does not execute a graph or replace the dashboard
runtime. The canvas is the default authoring surface; the complete form remains available from the More menu.
The workspace fills the management area by default, beside a collapsible icon rail. Optional immersive full-screen mode
hides management chrome through CSS and background focus isolation; it preserves the React tree, form association, draft,
and execution session. Save errors render inside the workspace.
## Ownership
- `document-store.ts` owns definition transactions and bounded Undo/Redo. Credentials stay in the live form;
`credential-bindings.ts` restores their association across source renames without putting values in history.
- `graph.ts` projects references into nodes and edges. `commands.ts` and the specialized editors change manifest fields.
Template edits use parser source ranges and preserve unrelated formatting and comments. Complex relationships are
inspectable in code rather than converted into a visual component tree.
- Layout metadata lives beside the persisted definition. Moving nodes does not notify definition subscribers, parse JSX,
invalidate preview evidence, or call the executor. ELK is loaded on demand for explicit arrangement.
- Selection, viewport, panes, response bodies, temporary parameters, and Assistant conversation state are session state.
Node data contains compact summaries and stable identifiers, not credentials or response bodies.
- `canvas-preview.tsx` mounts the live preview inside the Widget node. Its header drags the node; preview controls and
authored interactions use `nodrag`, `nopan`, and `nowheel`. CodeMirror and Assistant live in a contextual side pane,
outside canvas zoom, and remain mounted when hidden. Preview tools open in a portaled popup. The preview theme surface
isolates its styles and portal content from management chrome. Runtime-owned dropdown targets escape widget paint
containment while preserving scoped CSS, preview themes, and dialog focus traps. Nested menus and popovers retain
inline dropdowns; interpreter-authored events and portal targets remain blocked.
- Assistant draft commands use the existing conversation and client-tool infrastructure. Draft identity and generation
preconditions reject delayed patches. An accepted patch is one document transaction, not an implicit save or action.
## Compatibility and capabilities
Plain HTTP and static widgets retain the v2 schema. A definition with runtime extensions uses v3; strict v2 definitions
never acquire extension fields. Editor layout is not portable runtime content. Empty sources and requests support static
widgets without a placeholder service URL.
V3 adds scoped styles and keyframes, theme/container bindings, named views, supported detail overlays and embeds,
per-user browser preferences, permissioned shared board content, and curated native capabilities. The initial native
catalog covers Beszel systems/history/alerts/live data, calendars, media requests, Home Assistant, and Docker. It does not
expose arbitrary tRPC methods. Other services use HTTP or embeds; services without these interfaces need an external bridge.
The executable Beszel reference definition and current capability inventory are documented under
`apps/docs/docs/management/custom-widgets/`. The reference includes system selection, historical charts, container statistics,
live statistics, preferences, and partial failures. The catalog is an explicit coverage boundary, not a claim that every
native Homarr widget has a dedicated capability descriptor.
Workshop installation and MCP use the same install procedure. Provenance records endpoint, submission, revision, and
portable fingerprints. Update review retains local connections and secrets, rejects incompatible/local changes, and keeps
one previous package for rollback. Publication updates the existing owned submission or creates an attributed remix.
PocketBase schema validation and SQLite, MySQL, and PostgreSQL migrations ship with these changes.
## Authoring connections
`connection-planner.ts` validates the same operations for ports and the inspector picker. Source associations and action
invalidations update their manifest fields directly. Query, action, and option connections open a binding dialog: choose a
response field, display, or parameter mapping before applying a bounded JSX/manifest edit. Repeated connections can add
another field or display for the same relationship. Query and action creation never runs a remote operation implicitly.
`template-insertion.ts` preserves existing source text around inserted components. Generated bindings carry portable
comment markers for ownership checks. Only unchanged, wholly generated relationships can be removed or replaced visually;
authored or mixed references open in JSX. Replacement applies the removal and new binding in one document transaction.
A stale dialog cannot overwrite changes made after it opened.
## Acceptance evidence and limits
The current canvas presentation has been checked in the isolated SQLite development app with Chromium on Linux. Focused
browser checks cover real query/option/action bindings, repeated mappings, shared Undo, live JSX rendering, invalid-JSX
preview continuity, generated binding disconnect/reconnect and cancellation, compact controls, theme and size changes,
and recovery while the inspector is closed. The preview tools fit a 390px viewport. Real pointer movement and zoom retained the preview shadow tree and CodeMirror
without execution requests. Scoped light/dark accessibility scans found no violations; overlap prevents automated contrast
verification for some canvas elements. The 38 focused existing workbench/runtime/preview tests passed. Tests use local/sample data and simulated actions; these checks do not exercise a real external action
or public Workshop publication.
Earlier implementation passes covered local mock Beszel data and a deterministic Assistant provider, Workshop installation
and board rendering, scoped portals, focused runtime tests, and production builds. Earlier production canvas measurements
covered 16 nodes, 64 requests, and a template near 50,000 characters with zero execution requests or parser entries during
movement; board manifests excluded React Flow, ELK, and workbench chunks. Those measurements predate the preview-in-node
presentation and are not production performance or bundle proof for this final UI.
Physical touch/trackpad testing, a broader browser/device matrix, a fresh production performance pass, real external service
actions, and executing the MySQL/PostgreSQL migrations against live database servers remain separate acceptance work.
Schema snapshots and migration ancestry were checked for all three drivers. An existing demo-gallery test requires the
unavailable llama.cpp demo module. The current development acceptance uses repository routing unchanged; an earlier
production QA instance needed a temporary generated server-routing override.
@@ -0,0 +1,129 @@
"use client";
import { Button, Modal, Stack, Text } from "@mantine/core";
import type { Connection } from "@xyflow/react";
import { useI18n } from "@homarr/translation/client";
import { useCustomWidgetFormDocumentStore } from "../_custom-widget-form-state";
import type { CustomWidgetWorkbenchForm } from "../_custom-widget-form-utils";
import { createFlowCommands, isGraphEditable } from "./commands";
import { projectWidgetGraph, readObject, record } from "./graph";
import type { FlowKind } from "./graph";
import { placeAddedNodes } from "./node-placement";
import { useFlowConnection } from "./connection-provider";
import { connectionIssue, planFlowConnection } from "./connection-planner";
export interface PendingConnection {
nodeId: string;
handleType: "source" | "target";
position: { x: number; y: number };
}
export function AddNextStep({
pending,
form,
onClose,
onSelect,
}: {
pending: PendingConnection | null;
form: CustomWidgetWorkbenchForm;
onClose(): void;
onSelect(id: string): void;
}) {
const t = useI18n("customWidget.flow");
const store = useCustomWidgetFormDocumentStore();
const connect = useFlowConnection();
if (!pending) return null;
const graph = projectWidgetGraph(store.getValues(), store.getLayout());
const node = graph.nodes.find((entry) => entry.id === pending?.nodeId);
const kinds: FlowKind[] = [];
if (pending?.handleType === "source" && node?.data.kind === "source") kinds.push("query", "action");
if (pending?.handleType === "source" && node?.data.kind === "action") kinds.push("query");
if (pending?.handleType === "target" && node && ["query", "action"].includes(node.data.kind)) kinds.push("source");
if (node?.data.kind === "widget") {
kinds.push("query", "action");
if (pending.handleType === "target") kinds.push("options");
}
if (node?.data.kind === "options" && pending.handleType === "source") kinds.push("query", "action");
const existing = graph.nodes.filter((entry) => {
let source = pending.nodeId;
let target = entry.id;
if (pending.handleType === "target") {
source = entry.id;
target = pending.nodeId;
}
return !connectionIssue({ source, target }, graph.nodes);
});
const add = (kind: FlowKind) => {
if (!pending || !node || !isGraphEditable(store.getValues())) return;
let id = "widget";
let binding: Connection | undefined;
store.transaction(() => {
const previous = projectWidgetGraph(store.getValues(), store.getLayout()).nodes;
const commands = createFlowCommands(form, store);
let sourceId: string | undefined;
if (node.data.kind === "source") sourceId = node.data.identifier;
if (node.data.kind === "action") {
const source = record(readObject(store.getValues().requests)[node.data.identifier]).source;
if (typeof source === "string") sourceId = source;
}
id = commands.add(kind, sourceId);
const nextGraph = projectWidgetGraph(store.getValues(), store.getLayout());
let source = pending.nodeId;
let target = id;
if (pending.handleType === "target") {
source = id;
target = pending.nodeId;
}
const connection = { source, target, sourceHandle: "out", targetHandle: "in" };
if (planFlowConnection(connection, nextGraph.nodes, store.getValues()) === "direct")
commands.connect(connection, nextGraph.nodes);
else binding = connection;
store.setLayout({
...store.getLayout(),
nodes: { ...store.getLayout().nodes, ...placeAddedNodes(previous, nextGraph.nodes, id, pending.position) },
});
});
onClose();
onSelect(id);
if (binding) connect(binding, projectWidgetGraph(store.getValues(), store.getLayout()).nodes);
};
return (
<Modal
opened={!!pending}
onClose={onClose}
title={t("addNextStep")}
closeButtonProps={{ "aria-label": t("bindingCancel") }}
size="sm"
>
<Stack gap="xs">
<Text size="sm" c="dimmed">
{t("nextStepFor", { name: node?.data.label ?? "" })}
</Text>
{kinds.map((kind) => (
<Button key={kind} disabled={!isGraphEditable(store.getValues())} variant="light" onClick={() => add(kind)}>
{t(`kind.${kind}`)}
</Button>
))}
{existing.map((entry) => (
<Button
key={entry.id}
disabled={!isGraphEditable(store.getValues())}
variant="subtle"
onClick={() => {
let source = pending.nodeId;
let target = entry.id;
if (pending.handleType === "target") {
source = entry.id;
target = pending.nodeId;
}
const issue = connect({ source, target, sourceHandle: "out", targetHandle: "in" }, graph.nodes);
if (issue) return;
onClose();
onSelect(entry.id);
}}
>
{t("bindingConnectExisting", { name: entry.data.label })}
</Button>
))}
{kinds.length === 0 && existing.length === 0 && <Text size="sm">{t("codeOwned")}</Text>}
</Stack>
</Modal>
);
}
@@ -0,0 +1,127 @@
"use client";
import { useEffect, useState } from "react";
import { Alert, Stack, Text } from "@mantine/core";
import { useAuiState } from "@assistant-ui/react";
import { useI18n } from "@homarr/translation/client";
import { useOptionalHomarrAssistant, useAssistantPreferences } from "~/components/assistant/assistant-context";
import { AssistantConversationSurface } from "~/components/assistant/assistant-panel";
import { AssistantComposerSurfaceBoundary } from "~/components/assistant/assistant-runtime-provider";
import { getPendingAssistantAction } from "~/components/assistant/assistant-pending-action";
import {
applyWorkbenchTemplateEdits,
getWorkbenchDraftId,
registerAssistantWorkbench,
} from "~/components/assistant/assistant-workbench-bridge";
import type { CustomWidgetWorkbenchForm } from "../_custom-widget-form-utils";
import { buildDefinition } from "../_custom-widget-form-utils";
import { useCustomWidgetFormDocumentStore } from "../_custom-widget-form-state";
import { withoutCredentials } from "./history";
export function WorkbenchAssistant({
form,
selected,
onSelect,
onPreview,
}: {
form: CustomWidgetWorkbenchForm;
selected: string;
onSelect(id: string): void;
onPreview(): Promise<unknown>;
}) {
const store = useCustomWidgetFormDocumentStore();
const draftId = getWorkbenchDraftId(store);
const t = useI18n("customWidget.flow");
const assistant = useOptionalHomarrAssistant();
const [result, setResult] = useState("");
useEffect(
() =>
registerAssistantWorkbench({
read: () => {
const draft = buildDefinition(store.getValues());
if (!draft.success)
return {
success: false,
draftId,
revision: store.getRevision(),
selected,
fields: withoutCredentials(store.getValues()),
diagnostics: draft.error.issues.map((issue) => ({ path: issue.path, message: issue.message })),
};
return { success: true, draftId, revision: store.getRevision(), selected, definition: draft.data };
},
apply: (patch) => {
if (patch.draftId !== draftId || patch.revision !== store.getRevision())
return { success: false, error: "Draft changed. Read it again before applying changes." };
const next = { ...withoutCredentials(store.getValues()), ...patch.changes };
if (patch.templateEdits?.length) {
if (patch.changes.template !== undefined)
return { success: false, error: "Choose targeted edits or a complete template, not both." };
try {
next.template = applyWorkbenchTemplateEdits(next.template, patch.templateEdits);
} catch (error) {
return { success: false, error: error instanceof Error ? error.message : "Invalid template edit" };
}
}
const parsed = buildDefinition({ ...next, secrets: [] });
if (!parsed.success)
return {
success: false,
diagnostics: parsed.error.issues.map((issue) => ({ path: issue.path, message: issue.message })),
};
store.transaction(() => form.setValues({ ...next, secrets: store.getValues().secrets }));
setResult(patch.summary);
if (patch.focus) onSelect(patch.focus);
return { success: true, draftId, revision: store.getRevision(), summary: patch.summary };
},
preview: async (precondition) => {
if (precondition.draftId !== draftId || precondition.revision !== store.getRevision())
return { success: false, error: "Draft changed. Read it again before running queries." };
return onPreview();
},
}),
[draftId, form, onPreview, onSelect, selected, store],
);
return (
<Stack gap="sm">
{result && (
<Alert color="teal" aria-live="polite">
{result}
</Alert>
)}
{!assistant?.enabled && (
<Text size="xs" c="dimmed">
{assistant?.unavailableDescription ?? t("assistantUnavailable")}
</Text>
)}
{assistant?.enabled && (
<AssistantComposerSurfaceBoundary surfaceId="custom-widget-workbench">
<Conversation />
</AssistantComposerSurfaceBoundary>
)}
</Stack>
);
}
function Conversation() {
const assistant = useOptionalHomarrAssistant();
const preferences = useAssistantPreferences();
const messages = useAuiState((state) => state.thread.messages);
const last = messages.findLast((message) => message.role === "assistant");
if (!assistant) return null;
return (
<div style={{ height: 580, display: "flex", flexDirection: "column", minHeight: 0 }}>
<AssistantConversationSurface
isRunning={assistant.isRunning}
pendingAction={getPendingAssistantAction(last)}
modelId={preferences.modelId}
models={preferences.models}
modelOptionsLoading={preferences.isLoading}
reasoning={preferences.reasoning}
isRefreshing={assistant.isRefreshing}
onRefresh={assistant.refreshCurrentView}
onModelChange={preferences.setModelId}
onReasoningChange={preferences.setReasoning}
/>
</div>
);
}
@@ -0,0 +1,214 @@
import { collectCustomWidgetRequestReferences } from "@homarr/custom-widgets/core";
import {
collectTemplateReferences,
insertCustomWidgetTemplateContent,
markGeneratedBinding,
removeGeneratedBindings,
} from "@homarr/custom-widgets/workbench";
import type { GeneratedBindingDescriptor } from "@homarr/custom-widgets/workbench";
import type { CustomWidgetFormValues } from "@homarr/custom-widgets/workbench";
import { buildDefinition } from "../_custom-widget-form-utils";
import { readObject, record } from "./graph";
import type { FlowBindingIntent } from "./connection-planner";
import { isGeneratedConnectionCurrent } from "./connection-planner";
import { nativeLiteralDefault, nativeParameterFields } from "./native-editor-model";
import type { NativeInputSchema } from "./native-editor-model";
import { freshFlowIdentifier } from "./identifiers";
export interface BindingParameter {
mode: "control" | "input" | "option" | "literal";
name: string;
controlName: string;
value: unknown;
}
export interface BindingChoices {
format: "json" | "text" | "list" | "table";
path: string;
columns: string;
label: string;
option: string;
field: string;
location: "query" | "body" | "path" | "input";
params: Record<string, BindingParameter>;
}
export interface BindingLabels {
loading: string;
empty: string;
run: string;
error: string;
}
export function bindingDescriptor(intent: FlowBindingIntent) {
if (intent.native) return record(record(readObject(intent.snapshot.extensions).native)[intent.identifier]);
return record(readObject(intent.snapshot.requests)[intent.identifier]);
}
export function bindingParameters(intent: FlowBindingIntent, schema: NativeInputSchema) {
const descriptor = bindingDescriptor(intent);
if (intent.native) return nativeParameterFields(descriptor.input, schema);
const references = collectCustomWidgetRequestReferences({
path: String(descriptor.path ?? ""),
query: record(descriptor.query),
body: descriptor.body,
});
return [...references.params].map((name) => ({ name, schema: {} as NativeInputSchema }));
}
export function createBindingParameters(intent: FlowBindingIntent, schema: NativeInputSchema) {
const occupied = Object.fromEntries(
collectTemplateReferences(intent.snapshot.template)
.filter((ref) => ref.kind === "bind")
.map((ref) => [ref.name, true]),
);
return Object.fromEntries(
bindingParameters(intent, schema).map(({ name, schema: field }) => {
const binding = freshFlowIdentifier(occupied, `${intent.identifier}-${name}`);
occupied[binding] = true;
return [
name,
{
mode: "control",
name: binding,
controlName: binding,
value: nativeLiteralDefault(field),
} satisfies BindingParameter,
];
}),
);
}
const quote = JSON.stringify;
function propertyPath(root: string, path: string) {
const parts = path.trim().split(".").filter(Boolean);
if (parts.length > 16 || parts.some((part) => ["constructor", "prototype", "__proto__"].includes(part)))
throw new Error("Invalid data path");
return root + parts.map((part) => `?.[${quote(part)}]`).join("");
}
function parameterCode(choices: BindingChoices) {
const controls: string[] = [];
const entries = Object.entries(choices.params).map(([key, parameter]) => {
let expression = quote(parameter.value);
if (!["string", "number", "boolean"].includes(typeof parameter.value))
throw new Error("Parameters must be text, numbers, or booleans");
if (parameter.mode === "input" || parameter.mode === "control") expression = `inputs[${quote(parameter.name)}]`;
if (parameter.mode === "option") expression = `options[${quote(parameter.name)}]`;
if (parameter.mode === "control") {
let component = "TextInput";
let defaultProp = "defaultValue";
if (typeof parameter.value === "number") component = "NumberInput";
if (typeof parameter.value === "boolean") {
component = "Switch";
defaultProp = "defaultChecked";
}
controls.push(
`<${component} bind=${quote(parameter.name)} label={${quote(key)}} ${defaultProp}={${quote(parameter.value)}} />`,
);
}
return `${quote(key)}: ${expression}`;
});
return { controls, params: `params={{ ${entries.join(", ")} }}` };
}
function renderValue(root: string, choices: BindingChoices, labels: BindingLabels) {
const value = propertyPath(root, choices.path);
if (choices.format === "text") return `<Text>{String(${value} ?? ${quote(labels.empty)})}</Text>`;
if (choices.format === "json")
return `{(${value} ?? null) === null ? <Text c="dimmed">{${quote(labels.empty)}}</Text> : <Code block>{JSON.stringify(${value})}</Code>}`;
const rows = `(${value}).slice(0, 50)`;
let body = `${rows}.map((row, index) => <Text key={index} size="sm">{JSON.stringify(row)}</Text>)`;
if (choices.format === "table") {
const columns = choices.columns
.split(",")
.map((entry) => entry.trim())
.filter(Boolean)
.slice(0, 8);
if (!columns.length) throw new Error("Choose at least one table column");
const header = columns.map((column) => `<Table.Th>{${quote(column)}}</Table.Th>`).join("");
const cells = columns
.map((column) => `<Table.Td>{String(${propertyPath("row", column)} ?? "")}</Table.Td>`)
.join("");
body = `<Table.ScrollContainer minWidth={300}><Table><Table.Thead><Table.Tr>${header}</Table.Tr></Table.Thead><Table.Tbody>{${rows}.map((row, index) => <Table.Tr key={index}>${cells}</Table.Tr>)}</Table.Tbody></Table></Table.ScrollContainer>`;
} else body = `<Stack gap="xs">{${body}}</Stack>`;
return `{Array.isArray(${value}) && ${value}.length > 0 ? (${body}) : <Text c="dimmed">{${quote(labels.empty)}}</Text>}`;
}
export function createBindingSnippet(intent: FlowBindingIntent, choices: BindingChoices, labels: BindingLabels) {
if (intent.kind === "option") {
if (!record(readObject(intent.snapshot.options)[choices.option]).control)
throw new Error("Choose an existing option");
return `<Text>{String(options[${quote(choices.option)}] ?? "")}</Text>`;
}
const descriptor = bindingDescriptor(intent);
const { controls, params } = parameterCode(choices);
let content: string;
if (intent.kind === "action") {
let component = "ActionButton";
let idProp = "requestId";
if (intent.native) {
component = "NativeActionButton";
idProp = "nativeId";
}
content = `<${component} ${idProp}=${quote(intent.identifier)} ${params} variant="default">{${quote(choices.label || labels.run)}}</${component}>`;
} else if (descriptor.trigger === "manual" || descriptor.capability === "beszel.live") {
let component = "SubFetch";
let idProp = "requestId";
let live = "";
if (intent.native) {
component = "NativeQuery";
idProp = "nativeId";
}
if (descriptor.capability === "beszel.live") live = " live";
content = `<${component} ${idProp}=${quote(intent.identifier)} ${params} trigger="manual"${live}>{(result, meta) => (<Stack gap="xs">${renderValue("result", choices, labels)}</Stack>)}</${component}>`;
} else {
const status = `status[${quote(intent.identifier)}]`;
content = `<Stack gap="xs">\n{${status}?.loading ? <Text c="dimmed">{${quote(labels.loading)}}</Text> : ${status}?.error ? <Alert color="red">{String(${status}.error)}</Alert> : (${`<Stack gap="xs">${renderValue(`data[${quote(intent.identifier)}]`, choices, labels)}</Stack>`})}\n<RefreshButton />\n</Stack>`;
}
if (!controls.length) return content;
return `<Stack gap="xs">\n${controls.join("\n")}\n${content}\n</Stack>`;
}
export function bindingCandidate(
intent: FlowBindingIntent,
values: CustomWidgetFormValues,
choices: BindingChoices,
labels: BindingLabels,
) {
const options = readObject(values.options);
const bindings = collectTemplateReferences(values.template)
.filter((entry) => entry.kind === "bind")
.map((entry) => entry.name);
for (const parameter of Object.values(choices.params)) {
if (
parameter.mode === "option" &&
!["string", "number", "boolean"].includes(typeof record(options[parameter.name]).default)
)
throw new Error("Choose an option with a text, number, or boolean value");
if (parameter.mode === "input" && !bindings.includes(parameter.name))
throw new Error("Choose an existing widget input");
if (parameter.mode === "control" && bindings.includes(parameter.name))
throw new Error("A widget input with this name already exists");
}
const snippet = createBindingSnippet(intent, choices, labels);
let template = values.template;
if (intent.replaceGeneratedIds) {
if (!isGeneratedConnectionCurrent(values, intent.replaceEdgeId, intent.replaceGeneratedIds))
throw new Error("The original connection now includes code-owned references. Edit this relationship in code.");
const fragments = Object.values(record(readObject(values.extensions).fragments)).filter(
(value): value is string => typeof value === "string",
);
const removed = removeGeneratedBindings(template, intent.replaceGeneratedIds, fragments);
if (removed === null) throw new Error("The original binding changed. Edit this relationship in code.");
template = removed;
}
const descriptor: GeneratedBindingDescriptor = { source: intent.source, target: "widget", relationship: "data" };
if (intent.kind === "option") descriptor.relationship = "option";
if (intent.kind === "action" || (!intent.native && bindingDescriptor(intent).trigger === "manual")) {
descriptor.source = "widget";
descriptor.target = intent.source;
descriptor.relationship = "invoke";
}
const candidate = {
...values,
template: insertCustomWidgetTemplateContent(template, markGeneratedBinding(snippet, descriptor)),
};
const parsed = buildDefinition(candidate);
if (!parsed.success) throw new Error(parsed.error.issues[0]?.message ?? "Invalid widget definition");
return { patch: { template: candidate.template }, preview: snippet };
}
@@ -0,0 +1,252 @@
"use client";
import { useMemo, useState, useSyncExternalStore } from "react";
import {
Accordion,
Alert,
Autocomplete,
Button,
Code,
Group,
Modal,
Select,
Stack,
Text,
TextInput,
} from "@mantine/core";
import { clientApi } from "@homarr/api/client";
import { collectTemplateReferences } from "@homarr/custom-widgets/workbench";
import { useI18n } from "@homarr/translation/client";
import { useCustomWidgetFormDocumentStore } from "../_custom-widget-form-state";
import type { CustomWidgetWorkbenchForm } from "../_custom-widget-form-utils";
import { isFlowBindingCurrent } from "./connection-planner";
import type { FlowBindingIntent } from "./connection-planner";
import { bindingCandidate, bindingDescriptor, bindingParameters, createBindingParameters } from "./binding-code";
import type { BindingChoices } from "./binding-code";
import { BindingParameterEditor } from "./binding-parameter-editor";
import { BindingOptionEditor } from "./binding-option-editor";
import { requestOptionCandidate } from "./binding-request-option";
import { readObject } from "./graph";
import { useWorkbenchQuery } from "./execution";
import { nativeInputFields } from "./native-editor-model";
import type { NativeInputSchema } from "./native-editor-model";
export function FlowBindingDialog(props: {
intent: FlowBindingIntent;
form: CustomWidgetWorkbenchForm;
onClose(): void;
}) {
const t = useI18n("customWidget.flow");
const catalog = clientApi.customWidget.nativeCapabilities.useQuery(undefined, { enabled: props.intent.native });
const descriptor = bindingDescriptor(props.intent);
const schema = catalog.data?.find((entry) => entry.id === descriptor.capability)?.inputSchema;
let title = t("bindingTitle");
if (props.intent.kind === "requestOption") title = t("bindingConfigureRequest");
return (
<Modal
opened
onClose={props.onClose}
title={title}
closeButtonProps={{ "aria-label": t("bindingCancel") }}
size="lg"
>
{props.intent.native && !schema ? (
<Alert color="yellow">
{catalog.isError ? t("bindingCatalogError") : t("bindingCatalogLoading")}
{catalog.isError && (
<Button type="button" size="xs" onClick={() => void catalog.refetch()}>
{t("bindingRetry")}
</Button>
)}
</Alert>
) : (
<BindingEditor {...props} schema={schema ?? {}} />
)}
</Modal>
);
}
function BindingEditor({
intent,
form,
onClose,
schema,
}: {
intent: FlowBindingIntent;
form: CustomWidgetWorkbenchForm;
onClose(): void;
schema: NativeInputSchema;
}) {
const t = useI18n("customWidget.flow");
const store = useCustomWidgetFormDocumentStore();
useSyncExternalStore(store.subscribe, store.getRevision, store.getRevision);
const [choices, setChoices] = useState<BindingChoices>(() => ({
format: "json",
path: "",
columns: "name",
label: intent.identifier,
option: Object.keys(readObject(intent.snapshot.options))[0] ?? "",
field: nativeInputFields(schema)[0]?.name ?? "value",
location: intent.native ? "input" : "query",
params: createBindingParameters(intent, schema),
}));
const [applyError, setApplyError] = useState<string | null>(null);
const sample = useWorkbenchQuery(intent.identifier);
const paths = useMemo(() => samplePaths(sample?.data), [sample?.data]);
const options = readObject(intent.snapshot.options);
const inputs = [
...new Set(
collectTemplateReferences(intent.snapshot.template)
.filter((entry) => entry.kind === "bind")
.map((entry) => entry.name),
),
];
const params = bindingParameters(intent, schema);
const current = isFlowBindingCurrent(intent, store.getValues());
const change = (patch: Partial<BindingChoices>) => {
setChoices((value) => ({ ...value, ...patch }));
setApplyError(null);
};
const prepare = () => {
if (intent.kind === "requestOption") return requestOptionCandidate(intent, store.getValues(), choices, schema);
return bindingCandidate(intent, store.getValues(), choices, {
loading: t("bindingLoading"),
empty: t("bindingEmpty"),
run: t("bindingRun"),
error: t("bindingError"),
});
};
let candidate: ReturnType<typeof prepare> | undefined;
let error: string | null = null;
try {
if (current) candidate = prepare();
} catch (reason) {
error = reason instanceof Error ? reason.message : t("bindingError");
}
return (
<Stack gap="md" data-workbench-local-input>
<Text size="sm" c="dimmed">
{t("bindingDescription")}
</Text>
{(intent.kind === "option" || intent.kind === "requestOption") && (
<BindingOptionEditor intent={intent} choices={choices} schema={schema} onChange={change} />
)}
{intent.kind === "query" && (
<>
<Select
label={t("bindingDisplay")}
value={choices.format}
data={[
{ value: "json", label: t("bindingJson") },
{ value: "text", label: t("bindingText") },
{ value: "list", label: t("bindingList") },
{ value: "table", label: t("bindingTable") },
]}
onChange={(format) => format && change({ format: format as BindingChoices["format"] })}
/>
<Autocomplete
label={t("bindingDataPath")}
description={t("bindingDataPathHint")}
data={paths}
value={choices.path}
onChange={(path) => change({ path })}
/>
{choices.format === "table" && (
<TextInput
label={t("bindingColumns")}
description={t("bindingColumnsHint")}
value={choices.columns}
onChange={(event) => change({ columns: event.currentTarget.value })}
/>
)}
</>
)}
{intent.kind === "action" && (
<TextInput
label={t("bindingButtonLabel")}
value={choices.label}
onChange={(event) => change({ label: event.currentTarget.value })}
/>
)}
{(intent.kind === "query" || intent.kind === "action") && params.length > 0 && (
<Stack gap="sm">
<Text size="sm" c="dimmed">
{t("bindingParameterHint")}
</Text>
{params.map(
({ name, schema: fieldSchema }) =>
choices.params[name] && (
<BindingParameterEditor
key={name}
name={name}
schema={fieldSchema}
parameter={choices.params[name]}
options={options}
inputs={inputs}
onChange={(value) => change({ params: { ...choices.params, [name]: value } })}
/>
),
)}
</Stack>
)}
{!current && (
<Alert color="yellow" aria-live="polite">
{t("bindingStale")}
</Alert>
)}
{(error || applyError) && (
<Alert color="yellow" aria-live="polite">
{applyError ?? error}
</Alert>
)}
{candidate && (
<Accordion variant="contained">
<Accordion.Item value="code">
<Accordion.Control>{t("bindingReview")}</Accordion.Control>
<Accordion.Panel>
<Code block mah={240} style={{ overflow: "auto", whiteSpace: "pre-wrap" }}>
{candidate.preview}
</Code>
</Accordion.Panel>
</Accordion.Item>
</Accordion>
)}
<Group justify="end">
<Button type="button" variant="default" onClick={onClose}>
{t("bindingCancel")}
</Button>
<Button
type="button"
disabled={!current || !candidate}
onClick={() => {
try {
if (!isFlowBindingCurrent(intent, store.getValues())) throw new Error(t("bindingStale"));
const result = prepare();
store.transaction(() => form.setValues({ ...store.getValues(), ...result.patch }));
onClose();
} catch (reason) {
setApplyError(reason instanceof Error ? reason.message : t("bindingError"));
}
}}
>
{t("bindingApply")}
</Button>
</Group>
</Stack>
);
}
function samplePaths(value: unknown) {
const paths: string[] = [];
const visit = (entry: unknown, path: string, depth: number) => {
if (paths.length >= 100 || depth > 5 || !entry || typeof entry !== "object") return;
for (const [key, child] of Object.entries(entry).slice(0, 25)) {
if (key.includes(".")) continue;
let next = key;
if (path) next = `${path}.${key}`;
paths.push(next);
if (!Array.isArray(entry)) visit(child, next, depth + 1);
}
};
visit(value, "", 0);
return paths.slice(0, 100);
}
@@ -0,0 +1,87 @@
"use client";
import { Select, Stack, TextInput } from "@mantine/core";
import { useI18n } from "@homarr/translation/client";
import type { FlowBindingIntent } from "./connection-planner";
import { bindingDescriptor } from "./binding-code";
import type { BindingChoices } from "./binding-code";
import { readObject } from "./graph";
import { isCompatibleNativeOption, nativeInputFields } from "./native-editor-model";
import type { NativeInputSchema } from "./native-editor-model";
export function BindingOptionEditor({
intent,
choices,
schema,
onChange,
}: {
intent: FlowBindingIntent;
choices: BindingChoices;
schema: NativeInputSchema;
onChange(value: Partial<BindingChoices>): void;
}) {
const t = useI18n("customWidget.flow");
const fields = nativeInputFields(schema);
const fieldSchema = fields.find((field) => field.name === choices.field)?.schema ?? {};
let options = Object.entries(readObject(intent.snapshot.options));
if (intent.native) options = options.filter(([, option]) => isCompatibleNativeOption(option, fieldSchema));
const descriptor = bindingDescriptor(intent);
const pathFields = [...String(descriptor.path ?? "").matchAll(/\{param:([A-Za-z][A-Za-z0-9_-]*)\}/gu)].map(
(match) => match[1] ?? "",
);
return (
<Stack gap="sm">
<Select
label={t("bindingOption")}
searchable
value={choices.option}
data={options.map(([name]) => name)}
onChange={(value) => value && onChange({ option: value })}
/>
{intent.kind === "requestOption" && (
<>
{!intent.native && (
<Select
label={t("bindingRequestLocation")}
value={choices.location}
data={[
{ value: "query", label: t("bindingQueryParameter") },
{ value: "body", label: t("bindingBodyField") },
{ value: "path", label: t("bindingPathParameter"), disabled: pathFields.length === 0 },
]}
onChange={(value) => {
if (!value) return;
let field = choices.field;
if (value === "path") field = pathFields[0] ?? "";
onChange({ location: value as BindingChoices["location"], field });
}}
/>
)}
{intent.native && (
<Select
label={t("bindingRequestField")}
searchable
value={choices.field}
data={fields.map(({ name }) => name)}
onChange={(value) => value && onChange({ field: value })}
/>
)}
{!intent.native && choices.location === "path" && (
<Select
label={t("bindingRequestField")}
value={choices.field}
data={[...new Set(pathFields)]}
onChange={(value) => value && onChange({ field: value })}
/>
)}
{!intent.native && choices.location !== "path" && (
<TextInput
label={t("bindingRequestField")}
value={choices.field}
onChange={(event) => onChange({ field: event.currentTarget.value })}
/>
)}
</>
)}
</Stack>
);
}
@@ -0,0 +1,91 @@
"use client";
import { Group, Select, Stack, Text } from "@mantine/core";
import { useI18n } from "@homarr/translation/client";
import type { BindingParameter } from "./binding-code";
import type { NativeInputSchema } from "./native-editor-model";
import { isCompatibleNativeOption } from "./native-editor-model";
import { NativeLiteralInput } from "./native-literal-input";
export function BindingParameterEditor({
name,
parameter,
schema,
options,
inputs,
onChange,
}: {
name: string;
parameter: BindingParameter;
schema: NativeInputSchema;
options: Record<string, unknown>;
inputs: string[];
onChange(value: BindingParameter): void;
}) {
const t = useI18n("customWidget.flow");
const optionNames = Object.keys(options).filter((key) => isCompatibleNativeOption(options[key], schema));
let fieldSchema = schema;
if (!schema.type) fieldSchema = { ...schema, type: typeof parameter.value };
return (
<Stack gap={6}>
<Text size="sm" fw={500}>
{name}
</Text>
<Group grow align="start">
<Select
label={t("bindingParameterSource")}
value={parameter.mode}
data={[
{ value: "control", label: t("bindingNewControl") },
{ value: "literal", label: t("nativeLiteral") },
{ value: "option", label: t("nativeOptionBinding"), disabled: optionNames.length === 0 },
{ value: "input", label: t("bindingExistingInput"), disabled: inputs.length === 0 },
]}
onChange={(mode) => {
if (!mode) return;
let selected = parameter.name;
if (mode === "option") selected = optionNames[0] ?? "";
if (mode === "input") selected = inputs[0] ?? "";
if (mode === "control") selected = parameter.controlName;
onChange({ ...parameter, mode: mode as BindingParameter["mode"], name: selected });
}}
/>
{(parameter.mode === "option" || parameter.mode === "input") && (
<Select
label={t("bindingValue")}
value={parameter.name}
searchable
data={parameter.mode === "option" ? optionNames : inputs}
onChange={(value) => value && onChange({ ...parameter, name: value })}
/>
)}
{(parameter.mode === "literal" || parameter.mode === "control") && (
<NativeLiteralInput
label={t("bindingValue")}
value={parameter.value}
schema={fieldSchema}
required
disabled={false}
onChange={(value) => onChange({ ...parameter, value })}
/>
)}
</Group>
{!schema.type && (parameter.mode === "literal" || parameter.mode === "control") && (
<Select
label={t("bindingParameterType")}
value={typeof parameter.value}
data={[
{ value: "string", label: t("bindingText") },
{ value: "number", label: t("bindingNumber") },
{ value: "boolean", label: t("bindingBoolean") },
]}
onChange={(type) => {
let value: unknown = "";
if (type === "number") value = 0;
if (type === "boolean") value = false;
onChange({ ...parameter, value });
}}
/>
)}
</Stack>
);
}
@@ -0,0 +1,84 @@
import type { CustomWidgetFormValues } from "@homarr/custom-widgets/workbench";
import { collectTemplateReferences } from "@homarr/custom-widgets/workbench";
import { collectCustomWidgetRequestReferences } from "@homarr/custom-widgets/core";
import { buildDefinition, isRecord } from "../_custom-widget-form-utils";
import { readObject, record } from "./graph";
import type { FlowBindingIntent } from "./connection-planner";
import type { BindingChoices } from "./binding-code";
import { isCompatibleNativeOption, nativeInputFields } from "./native-editor-model";
import type { NativeInputSchema } from "./native-editor-model";
const parameters = (value: Record<string, unknown>) =>
collectCustomWidgetRequestReferences({
path: String(value.path ?? ""),
query: record(value.query),
body: value.body ?? value.input,
}).params;
export function requestOptionCandidate(
intent: FlowBindingIntent,
values: CustomWidgetFormValues,
choices: BindingChoices,
schema: NativeInputSchema = {},
) {
if (!Object.hasOwn(readObject(values.options), choices.option)) throw new Error("Choose an existing option");
const key = choices.field.trim();
if (intent.native) {
const fields = nativeInputFields(schema);
const target = fields.find((field) => field.name === key);
if (
fields.length &&
(!target || !isCompatibleNativeOption(readObject(values.options)[choices.option], target.schema))
)
throw new Error("Choose an option compatible with this capability field");
}
if (!key || key.length > 256 || ["__proto__", "constructor", "prototype"].includes(key))
throw new Error("Choose a valid request field");
const reference = { $option: choices.option };
if (intent.native && choices.location !== "input") throw new Error("Choose a native capability input");
if (!intent.native && choices.location === "input") throw new Error("Choose an HTTP request field");
const field = intent.native ? "extensions" : "requests";
const document = readObject(values[field]);
let entries = document;
if (intent.native) entries = record(document.native);
const descriptor = record(entries[intent.identifier]);
const updated = { ...descriptor };
if (choices.location === "path") {
const placeholder = `{param:${key}}`;
const path = String(descriptor.path ?? "");
if (!path.includes(placeholder)) throw new Error("Choose an existing path parameter");
updated.path = path.replaceAll(placeholder, `{option:${choices.option}}`);
} else {
const current = descriptor[choices.location];
if (current !== undefined && (!isRecord(current) || "$option" in current || "$param" in current))
throw new Error("This field is code-owned. Edit its existing binding before adding a named field.");
updated[choices.location] = { ...record(current), [key]: reference };
}
const nextEntries = { ...entries, [intent.identifier]: updated };
const remaining = parameters(updated);
if ([...parameters(descriptor)].some((name) => !remaining.has(name))) {
const templates = [
values.template,
...Object.values(record(readObject(values.extensions).fragments)).filter(
(value): value is string => typeof value === "string",
),
];
if (
templates.some((template) =>
collectTemplateReferences(template).some(
(entry) =>
["request", "native"].includes(entry.kind) && (entry.name === intent.identifier || entry.name === "*"),
),
)
)
throw new Error(
"This change removes an invocation parameter used by existing JSX. Update that control in code first.",
);
}
let nextDocument = nextEntries;
if (intent.native) nextDocument = { ...document, native: nextEntries };
const patch = { [field]: JSON.stringify(nextDocument, null, 2) };
const parsed = buildDefinition({ ...values, ...patch });
if (!parsed.success) throw new Error(parsed.error.issues[0]?.message ?? "Invalid widget definition");
return { patch, preview: JSON.stringify(updated, null, 2) };
}
@@ -0,0 +1,65 @@
"use client";
import { Controls } from "@xyflow/react";
import { Button, Group, Menu } from "@mantine/core";
import { IconArrowBackUp, IconChevronDown, IconFocus2, IconLayoutDistributeHorizontal } from "@tabler/icons-react";
import { useI18n } from "@homarr/translation/client";
import classes from "./workbench.module.css";
export function CanvasControls({
arranging,
selection,
branch,
arrange,
focus,
fit,
}: {
arranging: boolean;
selection: string[];
branch: boolean;
arrange(selectionOnly?: boolean): void;
focus(related: boolean): void;
fit(): void;
}) {
const t = useI18n("customWidget.flow");
return (
<Group className={classes.canvasTools} gap={4} p="xs">
<Menu position="bottom-start" withinPortal>
<Menu.Target>
<Button size="compact-sm" variant="default" rightSection={<IconChevronDown size={14} />} loading={arranging}>
{t("canvasOptions")}
</Button>
</Menu.Target>
<Menu.Dropdown>
<Menu.Item
leftSection={<IconLayoutDistributeHorizontal size={16} />}
disabled={arranging}
onClick={() => arrange()}
>
{t("arrange")}
</Menu.Item>
<Menu.Item disabled={!selection.length || arranging} onClick={() => arrange(true)}>
{t("arrangeSelection")}
</Menu.Item>
<Menu.Divider />
<Menu.Item leftSection={<IconFocus2 size={16} />} onClick={fit}>
{t("fit")}
</Menu.Item>
{selection.length > 0 && <Menu.Item onClick={() => focus(false)}>{t("focus")}</Menu.Item>}
{selection.length > 0 && <Menu.Item onClick={() => focus(true)}>{t("focusBranch")}</Menu.Item>}
</Menu.Dropdown>
</Menu>
{branch && (
<Button size="compact-sm" variant="default" leftSection={<IconArrowBackUp size={14} />} onClick={fit}>
{t("allNodes")}
</Button>
)}
</Group>
);
}
export function CanvasViewportControls() {
const t = useI18n("customWidget.flow");
return (
<fieldset aria-label={t("canvasControls")} style={{ border: 0, margin: 0, padding: 0, minInlineSize: 0 }}>
<Controls showInteractive={false} aria-label="" />
</fieldset>
);
}
@@ -0,0 +1,22 @@
import { useEffect } from "react";
import { useReducedMotion } from "@mantine/hooks";
import { useReactFlow } from "@xyflow/react";
/** Keep the rendered widget beside its JSX editor after the canvas gives the editor room. */
export function useCanvasEditorFocus(opened: boolean, selected: string) {
const { fitView } = useReactFlow();
const reducedMotion = useReducedMotion();
useEffect(() => {
if (!opened || selected !== "widget") return;
let frame = requestAnimationFrame(() => {
frame = requestAnimationFrame(() => {
void fitView({ nodes: [{ id: "widget" }], maxZoom: 1, padding: 0.2, duration: reducedMotion ? 0 : 180 });
});
});
return () => cancelAnimationFrame(frame);
}, [fitView, opened, selected, reducedMotion]);
}
export function isPreviewInteraction(target: EventTarget) {
return target instanceof Element && !!target.closest("[data-flow-preview], [data-mantine-portal]");
}
@@ -0,0 +1,166 @@
"use client";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { Dispatch, KeyboardEvent, SetStateAction } from "react";
import { applyNodeChanges } from "@xyflow/react";
import type { AriaLabelConfig, EdgeChange, NodeChange, NodeMouseHandler, EdgeMouseHandler } from "@xyflow/react";
import { useI18n } from "@homarr/translation/client";
import type { CustomWidgetFormDocumentStore } from "../_custom-widget-form-state";
import type { createFlowCommands } from "./commands";
import type { WidgetEdge, WidgetNode } from "./graph";
import { captureLayout } from "./layout";
import { isPreviewInteraction } from "./canvas-editor-focus";
interface Props {
edges: WidgetEdge[];
selection: string[];
store: CustomWidgetFormDocumentStore;
commands: ReturnType<typeof createFlowCommands>;
getNodes(): WidgetNode[];
setNodes: Dispatch<SetStateAction<WidgetNode[]>>;
onSelect(id: string): void;
onInspect(id: string): void;
onSelection(ids: string[]): void;
onIssue(issue: string | null): void;
}
/** Owns canvas selection and keyboard commands without putting transient selection into document history. */
export function useCanvasInteractions({
edges,
selection,
store,
commands,
getNodes,
setNodes,
onSelect,
onInspect,
onSelection,
onIssue,
}: Props) {
const t = useI18n("customWidget.flow");
const ariaLabelConfig = useMemo<Partial<AriaLabelConfig>>(
() => ({
"controls.zoomIn.ariaLabel": t("zoomIn"),
"controls.zoomOut.ariaLabel": t("zoomOut"),
"controls.fitView.ariaLabel": t("fit"),
"controls.ariaLabel": t("canvasControls"),
"handle.ariaLabel": t("connect"),
"node.a11yDescription.default": t("nodeKeyboardHelp"),
"node.a11yDescription.keyboardDisabled": t("nodePointerHelp"),
"node.a11yDescription.ariaLiveMessage": ({ x, y }) => t("nodeMoved", { x, y }),
"edge.a11yDescription.default": t("edgeKeyboardHelp"),
}),
[t],
);
const [selectedEdge, setSelectedEdge] = useState<string | null>(null);
const selectionRef = useRef(selection);
selectionRef.current = selection;
useEffect(() => {
setNodes((current) =>
current.map((node) => {
const next = selection.includes(node.id);
if (node.selected === next) return node;
return { ...node, selected: next };
}),
);
}, [selection, setNodes]);
const onNodesChange = useCallback(
(changes: NodeChange<WidgetNode>[]) => {
setNodes((current) =>
applyNodeChanges(
changes.filter((change) => change.type !== "remove"),
current,
),
);
const selectionChanges = changes.filter((change) => change.type === "select");
if (selectionChanges.length === 0) return;
const ids = new Set(selectionRef.current);
for (const change of selectionChanges) {
if (change.selected) ids.add(change.id);
else ids.delete(change.id);
}
onSelection([...ids]);
},
[onSelection, setNodes],
);
const onEdgesChange = useCallback((changes: EdgeChange<WidgetEdge>[]) => {
setSelectedEdge((current) => {
let next = current;
for (const change of changes) {
if (change.type !== "select") continue;
if (change.selected) next = change.id;
else if (next === change.id) next = null;
}
return next;
});
}, []);
const inspectEdge = useCallback(
(edge: WidgetEdge) => {
let id = edge.target;
if (edge.data?.relationship === "invalidates") id = edge.source;
setSelectedEdge(edge.id);
onSelection([]);
onInspect(id);
},
[onInspect, onSelection],
);
const onNodeClick: NodeMouseHandler<WidgetNode> = useCallback(
(event, node) => {
if (isPreviewInteraction(event.target)) return;
setSelectedEdge(null);
onInspect(node.id);
},
[onInspect],
);
const onEdgeClick: EdgeMouseHandler<WidgetEdge> = useCallback((_event, edge) => inspectEdge(edge), [inspectEdge]);
const onKeyDown = useCallback(
(event: KeyboardEvent) => {
if (!["Delete", "Backspace"].includes(event.key) || !(event.target instanceof Element)) return;
const edgeId = event.target.closest(".react-flow__edge")?.getAttribute("data-id");
const edge = edges.find((entry) => entry.id === edgeId);
if (!edge) return;
// A focused edge owns Delete; never forward it to the workbench's previous node selection.
event.preventDefault();
event.stopPropagation();
onSelection([]);
const result = commands.disconnect(edge);
onIssue(result);
if (!result) {
setSelectedEdge(null);
// The removed SVG cannot retain focus. Keep Undo and subsequent keyboard commands inside the workbench.
event.currentTarget
.querySelector<HTMLElement>(`.react-flow__node[data-id="${CSS.escape(edge.source)}"]`)
?.focus({ preventScroll: true });
}
},
[commands, edges, onIssue, onSelection],
);
const onKeyUp = useCallback(
(event: KeyboardEvent) => {
if (isPreviewInteraction(event.target)) return;
if (!(event.target instanceof Element)) return;
if (event.target.closest('input, textarea, button, [contenteditable="true"], [role="combobox"]')) return;
const nodeId = event.target.closest(".react-flow__node")?.getAttribute("data-id");
if (nodeId && event.key === "F2") {
event.preventDefault();
onSelect(nodeId);
return;
}
if (["Enter", " "].includes(event.key)) {
if (nodeId) {
setSelectedEdge(null);
onInspect(nodeId);
}
const edgeId = event.target.closest(".react-flow__edge")?.getAttribute("data-id");
const edge = edges.find((entry) => entry.id === edgeId);
if (edge) inspectEdge(edge);
return;
}
if (!["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"].includes(event.key)) return;
if (!event.target.closest(".react-flow__node, .react-flow__nodesselection")) return;
requestAnimationFrame(() => store.setLayout(captureLayout(getNodes(), store.getLayout())));
},
[edges, getNodes, inspectEdge, onInspect, onSelect, store],
);
return { selectedEdge, ariaLabelConfig, onNodesChange, onEdgesChange, onNodeClick, onEdgeClick, onKeyDown, onKeyUp };
}
@@ -0,0 +1,80 @@
"use client";
import { createContext, memo, useContext, useMemo } from "react";
import type { ReactNode } from "react";
import { Button, Group, Text } from "@mantine/core";
import { Position } from "@xyflow/react";
import type { NodeProps } from "@xyflow/react";
import { IconCode } from "@tabler/icons-react";
import { useI18n } from "@homarr/translation/client";
import type { WidgetNode } from "./graph";
import { FlowNode, FlowPort, useValidConnectionTarget } from "./node";
import { FlowGroup } from "./group";
import { WorkbenchPreviewTheme } from "./preview-theme";
import { WorkbenchPreviewPresentationProvider } from "./preview-presentation";
import classes from "./workbench.module.css";
const CanvasPreviewContext = createContext<{ preview: ReactNode; edit(id: string): void } | null>(null);
export function CanvasPreviewProvider({
preview,
edit,
children,
}: {
preview: ReactNode;
edit(id: string): void;
children: ReactNode;
}) {
const value = useMemo(() => ({ preview, edit }), [preview, edit]);
return <CanvasPreviewContext.Provider value={value}>{children}</CanvasPreviewContext.Provider>;
}
export const CanvasWidgetNode = memo(function CanvasWidgetNode({
id,
data,
selected,
isConnectable,
}: NodeProps<WidgetNode>) {
const context = useContext(CanvasPreviewContext);
const t = useI18n("customWidget.flow");
const validTarget = useValidConnectionTarget(id, isConnectable);
return (
<div className={classes.canvasWidgetNode} data-selected={selected} data-valid-target={validTarget}>
<FlowPort
id="in"
type="target"
position={Position.Left}
connectable={isConnectable}
label={`${t("input")} · ${data.label}`}
title={t("input")}
/>
<Group className="widget-node-drag" justify="space-between" wrap="nowrap" p="sm">
<Text size="sm" fw={600} truncate>
{data.label}
</Text>
<Button
className="nodrag nopan"
type="button"
variant="default"
size="compact-xs"
leftSection={<IconCode size={14} />}
onClick={() => context?.edit(id)}
>
{t("editJsx")}
</Button>
</Group>
<div className="nodrag nopan nowheel" data-flow-preview>
<WorkbenchPreviewTheme controls={false}>
<WorkbenchPreviewPresentationProvider mode="canvas">{context?.preview}</WorkbenchPreviewPresentationProvider>
</WorkbenchPreviewTheme>
</div>
<FlowPort
id="out"
type="source"
position={Position.Right}
connectable={isConnectable}
label={`${t("output")} · ${data.label}`}
title={t("output")}
/>
</div>
);
});
export const canvasNodeTypes = { widget: FlowNode, preview: CanvasWidgetNode, group: FlowGroup };
@@ -0,0 +1,16 @@
import type { ReactFlowInstance } from "@xyflow/react";
import type { CustomWidgetWorkbenchForm } from "../_custom-widget-form-utils";
import type { WidgetEdge, WidgetNode } from "./graph";
export const defaultEdgeOptions = { type: "smoothstep", selectable: true };
export const initialFitOptions = { maxZoom: 1 };
export interface CanvasProps {
form: CustomWidgetWorkbenchForm;
selected: string;
selection: string[];
inspectorOpened: boolean;
onSelect(id: string): void;
onInspect(id: string): void;
onSelection(ids: string[]): void;
onInit(instance: ReactFlowInstance<WidgetNode, WidgetEdge>): void;
}
@@ -0,0 +1,299 @@
"use client";
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Alert } from "@mantine/core";
import { useReducedMotion } from "@mantine/hooks";
import {
Background,
MarkerType,
ReactFlow,
ReactFlowProvider,
SelectionMode,
useReactFlow,
useNodesInitialized,
} from "@xyflow/react";
import type { Connection, OnConnectEnd } from "@xyflow/react";
import { useI18n } from "@homarr/translation/client";
import {
useDeferredCustomWidgetFormDocumentValues,
useCustomWidgetFormDocumentStore,
} from "../_custom-widget-form-state";
import { defaultEdgeOptions, initialFitOptions } from "./canvas-types";
import type { CanvasProps as Props } from "./canvas-types";
import { isPreviewInteraction, useCanvasEditorFocus } from "./canvas-editor-focus";
import { createFlowCommands, connectionIssue, isGraphEditable } from "./commands";
import { arrangeWidgetGraph, projectWidgetGraph } from "./graph";
import type { WidgetNode, WidgetEdge } from "./graph";
import { captureLayout, projectLayout, expandGroupSelection } from "./layout";
import { canvasNodeTypes } from "./canvas-preview";
import { useFlowConnection } from "./connection-provider";
import { CanvasControls, CanvasViewportControls } from "./canvas-controls";
import { useCanvasInteractions } from "./canvas-interactions";
import { AddNextStep } from "./add-next-step";
import type { PendingConnection } from "./add-next-step";
// oxlint-disable-next-line import/no-unassigned-import -- Canvas-only React Flow styles.
import "@xyflow/react/dist/style.css";
const Canvas = memo(function Canvas(props: Props) {
return (
<ReactFlowProvider>
<CanvasContent {...props} />
</ReactFlowProvider>
);
});
export default Canvas;
function CanvasContent({
form,
selected,
selection,
onSelect,
onInspect,
onSelection,
onInit,
inspectorOpened,
}: Props) {
useCanvasEditorFocus(inspectorOpened, selected);
const t = useI18n("customWidget.flow");
const actions = useI18n("common.action");
const store = useCustomWidgetFormDocumentStore();
const values = useDeferredCustomWidgetFormDocumentValues();
const graph = useMemo(() => projectWidgetGraph(values, store.getLayout()), [values, store]);
const graphEditable = useMemo(() => isGraphEditable(values), [values]);
const [nodes, setNodes] = useState<WidgetNode[]>(graph.nodes);
const [issue, setIssue] = useState<string | null>(null);
const [arranging, setArranging] = useState(false);
const [branch, setBranch] = useState<string[] | null>(null);
const [pending, setPending] = useState<PendingConnection | null>(null);
const initialized = useRef(false);
const nodesInitialized = useNodesInitialized();
const generation = useRef(0);
const layoutJob = useRef(0);
const reconnecting = useRef(false);
const selectionRef = useRef(selection);
selectionRef.current = selection;
const { fitView, getNodes, screenToFlowPosition } = useReactFlow<WidgetNode, WidgetEdge>();
const reducedMotion = useReducedMotion();
const commands = useMemo(() => createFlowCommands(form, store), [form, store]);
const connect = useFlowConnection();
const { selectedEdge, ...interactions } = useCanvasInteractions({
edges: graph.edges,
selection,
store,
commands,
getNodes,
setNodes,
onSelect,
onInspect,
onSelection,
onIssue: setIssue,
});
useEffect(() => {
generation.current += 1;
setNodes((current) => {
const measured = new Map(current.map((node) => [node.id, node]));
return graph.nodes.map((node) => ({
...measured.get(node.id),
...node,
selected: selectionRef.current.includes(node.id),
}));
});
}, [graph]);
useEffect(
() =>
store.subscribeEditor(() => {
generation.current += 1;
setNodes((current) => projectLayout(current, store.getLayout()));
}),
[store],
);
const arrange = useCallback(
async (selectionOnly = false, initial = false) => {
const token = ++generation.current;
const job = ++layoutJob.current;
setArranging(true);
const revision = store.getRevision();
try {
let targets = getNodes();
if (selectionOnly) targets = expandGroupSelection(targets, selectionRef.current);
if (targets.length === 0) return;
const arranged = await arrangeWidgetGraph(targets, graph.edges, selectionOnly);
if (token !== generation.current || revision !== store.getRevision()) return;
const current = store.getLayout();
const next = {
...current,
nodes: { ...current.nodes, ...arranged.nodes },
groups: { ...current.groups, ...arranged.groups },
};
if (initial) {
store.initializeLayout(next);
requestAnimationFrame(() =>
requestAnimationFrame(() => {
void fitView({ duration: 0, maxZoom: 1 });
}),
);
} else store.setLayout(next);
setIssue(null);
} catch {
if (token === generation.current) {
setIssue("layoutFailed");
}
} finally {
if (job === layoutJob.current) setArranging(false);
}
},
[getNodes, graph.edges, store, fitView],
);
useEffect(() => {
if (initialized.current || !nodesInitialized) return;
initialized.current = true;
if (!Object.keys(store.getLayout().nodes).length) void arrange(false, true);
}, [arrange, store, nodesInitialized]);
const onConnect = useCallback(
(connection: Connection) => setIssue(connect(connection, getNodes())),
[connect, getNodes],
);
const isValidConnection = useCallback(
(connection: Connection | WidgetEdge) => graphEditable && !connectionIssue(connection, getNodes()),
[graphEditable, getNodes],
);
const endConnection: OnConnectEnd = (event, state) => {
if (state.isValid || reconnecting.current || !state.fromNode) return;
if (state.toNode) {
setIssue("codeOwned");
return;
}
const pointer = "changedTouches" in event ? event.changedTouches[0] : event;
if (!pointer) return;
const target = document.elementFromPoint(pointer.clientX, pointer.clientY);
if (!target?.closest(".react-flow__pane")) return;
setPending({
nodeId: state.fromNode.id,
handleType: state.fromHandle?.type ?? "source",
position: screenToFlowPosition({ x: pointer.clientX, y: pointer.clientY }),
});
};
const focus = (related: boolean) => {
const ids = new Set(selectionRef.current);
if (related)
for (const edge of graph.edges) {
if (selectionRef.current.includes(edge.source)) ids.add(edge.target);
if (selectionRef.current.includes(edge.target)) ids.add(edge.source);
}
for (const node of getNodes()) if (ids.has(node.id) && node.parentId) ids.add(node.parentId);
if (related) setBranch([...ids]);
void fitView({ nodes: [...ids].map((id) => ({ id })), maxZoom: 1.1, duration: reducedMotion ? 0 : 200 });
};
const displayedNodes = useMemo(
() =>
nodes.map((node) => ({
...node,
dragHandle: ".widget-node-drag",
ariaLabel: `${t(`kind.${node.data.kind}`)}: ${node.data.label}`,
hidden: !!branch && !branch.includes(node.id),
})),
[nodes, branch, t],
);
const displayedEdges = useMemo(() => {
const labels = new Map(graph.nodes.map((node) => [node.id, node.data.label]));
return graph.edges.map((edge) => {
const related = edge.id === selectedEdge || edge.source === selected || edge.target === selected;
return {
...edge,
selected: edge.id === selectedEdge,
markerEnd: { type: MarkerType.ArrowClosed, color: edge.style?.stroke?.toString(), width: 18, height: 18 },
hidden: !!branch && (!branch.includes(edge.source) || !branch.includes(edge.target)),
ariaLabel: `${t(`relationship.${edge.data?.relationship ?? "data"}`)}: ${labels.get(edge.source)} → ${labels.get(edge.target)}`,
label: related ? t(`relationship.${edge.data?.relationship ?? "data"}`) : undefined,
labelStyle: { fontSize: 10 },
labelBgStyle: { fill: "var(--mantine-color-body)" },
style: { ...edge.style, opacity: related || !selected ? 1 : 0.4 },
};
});
}, [graph, selected, selectedEdge, branch, t]);
return (
<>
<CanvasControls
arranging={arranging}
selection={selection}
branch={!!branch}
arrange={arrange}
focus={focus}
fit={() => {
setBranch(null);
requestAnimationFrame(() => {
void fitView({ duration: reducedMotion ? 0 : 200 });
});
}}
/>
{issue && (
<Alert
color="yellow"
p="xs"
withCloseButton
closeButtonLabel={actions("close")}
onClose={() => setIssue(null)}
aria-live="polite"
>
{t(issue as "codeOwned")}
</Alert>
)}
<ReactFlow<WidgetNode, WidgetEdge>
onInit={onInit}
nodes={displayedNodes}
edges={displayedEdges}
nodeTypes={canvasNodeTypes}
defaultEdgeOptions={defaultEdgeOptions}
aria-label={t("canvas")}
{...interactions}
onConnect={onConnect}
onConnectEnd={endConnection}
onClickConnectEnd={endConnection}
onReconnectStart={() => {
reconnecting.current = true;
}}
onReconnect={(edge, connection) => setIssue(connect(connection, getNodes(), edge))}
onReconnectEnd={() => {
reconnecting.current = false;
}}
isValidConnection={isValidConnection}
nodesConnectable={graphEditable}
onNodeDoubleClick={(event, node) => {
if (!isPreviewInteraction(event.target)) onSelect(node.id);
}}
onNodeDragStart={() => {
generation.current += 1;
setArranging(false);
}}
onNodeDragStop={() => store.setLayout(captureLayout(getNodes(), store.getLayout()))}
onSelectionDragStart={() => {
generation.current += 1;
setArranging(false);
}}
onSelectionDragStop={() => store.setLayout(captureLayout(getNodes(), store.getLayout()))}
panOnScroll
selectionOnDrag
panOnDrag={false}
panActivationKeyCode="Space"
selectionMode={SelectionMode.Partial}
zoomOnScroll={false}
zoomActivationKeyCode={["Control", "Meta"]}
multiSelectionKeyCode={["Control", "Meta", "Shift"]}
zoomOnDoubleClick={false}
connectOnClick
connectionRadius={24}
reconnectRadius={18}
nodesFocusable
edgesFocusable
autoPanOnNodeFocus
disableKeyboardA11y={false}
deleteKeyCode={null}
minZoom={0.02}
maxZoom={1.5}
fitView
fitViewOptions={initialFitOptions}
>
<Background gap={24} />
<CanvasViewportControls />
</ReactFlow>
<AddNextStep pending={pending} form={form} onClose={() => setPending(null)} onSelect={onSelect} />
</>
);
}
@@ -0,0 +1,184 @@
import type { Connection } from "@xyflow/react";
import type { CustomWidgetFormValues } from "@homarr/custom-widgets/workbench";
import { removeGeneratedBindings } from "@homarr/custom-widgets/workbench";
import type { CustomWidgetFormDocumentStore } from "../_custom-widget-form-state";
import type { CustomWidgetWorkbenchForm } from "../_custom-widget-form-utils";
import { buildDefinition } from "../_custom-widget-form-utils";
import { readObject, record } from "./graph";
import type { FlowKind, WidgetNode, WidgetEdge } from "./graph";
import { freshFlowIdentifier as fresh } from "./identifiers";
import { createExtensionCommands, isExtensionKind } from "./extension-commands";
import { connectionIssue, isGeneratedConnectionCurrent, planFlowConnection } from "./connection-planner";
export { connectionIssue } from "./connection-planner";
export function isGraphEditable(
values: Pick<CustomWidgetFormValues, "sources" | "requests" | "options" | "extensions">,
) {
return [values.sources, values.requests, values.options, values.extensions || "{}"].every((value) => {
try {
const parsed: unknown = JSON.parse(value);
return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed);
} catch {
return false;
}
});
}
export function createFlowCommands(form: CustomWidgetWorkbenchForm, store: CustomWidgetFormDocumentStore) {
const extensionCommands = createExtensionCommands(form);
const write = (field: "sources" | "requests" | "options", value: Record<string, unknown>) =>
form.setFieldValue(field, JSON.stringify(value, null, 2));
const disconnect = (edge: WidgetEdge) => {
if (!isGraphEditable(form.values)) return "invalidGraphJson";
if (edge.data?.generatedBindingIds?.length) {
if (!isGeneratedConnectionCurrent(store.getValues(), edge.id, edge.data.generatedBindingIds)) return "codeOwned";
const fragments = Object.values(record(readObject(store.getValues().extensions).fragments)).filter(
(value): value is string => typeof value === "string",
);
const template = removeGeneratedBindings(store.getValues().template, edge.data.generatedBindingIds, fragments);
if (template === null || !buildDefinition({ ...store.getValues(), template }).success) return "codeOwned";
form.setFieldValue("template", template);
return null;
}
if (edge.data?.relationship !== "invalidates") return "codeOwned";
const requests = readObject(form.values.requests);
const source = edge.source.replace(/^request:/u, "");
const target = edge.target.replace(/^request:/u, "");
const request = record(requests[source]);
if (!Array.isArray(request.invalidates)) return null;
write("requests", {
...requests,
[source]: { ...request, invalidates: request.invalidates.filter((entry) => entry !== target) },
});
return null;
};
const connect = (connection: Connection, nodes: WidgetNode[]) => {
if (!isGraphEditable(form.values)) return "invalidGraphJson";
const issue = connectionIssue(connection, nodes);
if (issue) return issue;
if (planFlowConnection(connection, nodes, form.values) !== "direct") return "bindingRequired";
const source = nodes.find((node) => node.id === connection.source);
const target = nodes.find((node) => node.id === connection.target);
if (!source || !target) return "missing";
const requests = readObject(form.values.requests);
if (source.data.kind === "source") {
write("requests", {
...requests,
[target.data.identifier]: { ...record(requests[target.data.identifier]), source: source.data.identifier },
});
} else {
const request = record(requests[source.data.identifier]);
const invalidates = Array.isArray(request.invalidates) ? request.invalidates : [];
write("requests", {
...requests,
[source.data.identifier]: { ...request, invalidates: [...new Set([...invalidates, target.data.identifier])] },
});
}
return null;
};
return {
add(kind: FlowKind, preferredSource?: string) {
if (!isGraphEditable(form.values)) return "widget";
let id = "widget";
store.transaction(() => {
if (isExtensionKind(kind)) {
id = extensionCommands.add(kind);
return;
}
if (kind === "source") {
const sources = readObject(form.values.sources);
const key = fresh(sources, "source");
write("sources", {
...sources,
[key]: { baseUrl: "http://service:8080", networkScope: "private", auth: "none" },
});
id = `source:${key}`;
} else if (kind === "query" || kind === "action") {
const sources = readObject(form.values.sources);
let source = Object.keys(sources)[0];
if (preferredSource && sources[preferredSource]) source = preferredSource;
if (!source) {
source = "default";
write("sources", { default: { baseUrl: "http://service:8080", networkScope: "private", auth: "none" } });
}
const requests = readObject(form.values.requests);
const key = fresh({ ...requests, ...record(readObject(form.values.extensions).native) }, kind);
let trigger = "load";
if (kind === "action") trigger = "manual";
write("requests", { ...requests, [key]: { source, path: "/api/data", kind, method: "GET", trigger } });
id = `request:${key}`;
} else if (kind === "options") {
const options = readObject(form.values.options);
const key = fresh(options, "option");
write("options", { ...options, [key]: { control: "text", label: key, default: "" } });
id = "options";
}
});
return id;
},
connect,
disconnect,
reconnect(edge: WidgetEdge, connection: Connection, nodes: WidgetNode[]) {
if (!isGraphEditable(form.values)) return "invalidGraphJson";
const issue = connectionIssue(connection, nodes);
if (issue) return issue;
if (planFlowConnection(connection, nodes, form.values) !== "direct") return "codeOwned";
const source = nodes.find((node) => node.id === connection.source);
if (edge.data?.relationship === "source" && (edge.target !== connection.target || source?.data.kind !== "source"))
return "codeOwned";
if (edge.data?.relationship === "invalidates" && source?.data.kind !== "action") return "codeOwned";
if (!["source", "invalidates"].includes(edge.data?.relationship ?? "")) return "codeOwned";
store.transaction(() => {
if (edge.data?.relationship === "invalidates") disconnect(edge);
connect(connection, nodes);
});
return null;
},
duplicate(node: WidgetNode) {
if (!isGraphEditable(form.values)) return node.id;
if (isExtensionKind(node.data.kind)) return extensionCommands.duplicate(node);
let field: "sources" | "requests" = "requests";
let prefix = "request";
if (node.data.kind === "source") {
field = "sources";
prefix = "source";
}
if (!["source", "query", "action"].includes(node.data.kind)) return node.id;
const entries = readObject(form.values[field]);
let identifiers = entries;
if (field === "requests") identifiers = { ...entries, ...record(readObject(form.values.extensions).native) };
const key = fresh(identifiers, `${node.data.identifier}Copy`);
const copy = structuredClone(record(entries[node.data.identifier]));
if (Array.isArray(copy.invalidates))
copy.invalidates = copy.invalidates.map((id) => (id === node.data.identifier ? key : id));
write(field, { ...entries, [key]: copy });
return `${prefix}:${key}`;
},
remove(nodes: WidgetNode[]) {
if (nodes.every((node) => node.data.kind === "group")) return;
if (!isGraphEditable(form.values)) return;
store.transaction(() => {
const sources = readObject(form.values.sources);
const requests = readObject(form.values.requests);
let options = readObject(form.values.options);
const layout = structuredClone(store.getLayout());
for (const node of nodes) {
if (node.data.kind === "source") delete sources[node.data.identifier];
if (["query", "action"].includes(node.data.kind)) delete requests[node.data.identifier];
if (node.data.kind === "options") options = {};
delete layout.nodes[node.id];
delete layout.groups[node.id];
}
form.setValues({
...form.values,
sources: JSON.stringify(sources, null, 2),
requests: JSON.stringify(requests, null, 2),
options: JSON.stringify(options, null, 2),
extensions: form.values.extensions,
});
extensionCommands.remove(nodes);
store.setLayout(layout);
});
},
};
}
@@ -0,0 +1,83 @@
import type { Connection } from "@xyflow/react";
import type { CustomWidgetFormValues } from "@homarr/custom-widgets/workbench";
import { projectWidgetGraph, readObject, record } from "./graph";
import type { WidgetNode } from "./graph";
export interface FlowBindingIntent {
kind: "query" | "action" | "option" | "requestOption";
source: string;
target: string;
identifier: string;
native: boolean;
replaceGeneratedIds?: string[];
replaceEdgeId?: string;
snapshot: Pick<CustomWidgetFormValues, "template" | "requests" | "options" | "extensions">;
}
export function connectionIssue(connection: Pick<Connection, "source" | "target">, nodes: WidgetNode[]) {
const source = nodes.find((entry) => entry.id === connection.source);
const target = nodes.find((entry) => entry.id === connection.target);
if (!source || !target) return "missing";
if (source.data.kind === "widget" && ["query", "action", "native"].includes(target.data.kind)) return null;
if (source.data.kind === "source" && ["query", "action"].includes(target.data.kind)) return null;
if (source.data.kind === "action" && target.data.kind === "query") return null;
if (["query", "action", "native", "options"].includes(source.data.kind) && target.data.kind === "widget") return null;
if (source.data.kind === "options" && ["query", "action", "native"].includes(target.data.kind)) return null;
return "codeOwned";
}
export function planFlowConnection(
connection: Pick<Connection, "source" | "target">,
nodes: WidgetNode[],
values: CustomWidgetFormValues,
): FlowBindingIntent | "direct" | "missing" | "codeOwned" {
const issue = connectionIssue(connection, nodes);
if (issue) return issue;
const source = nodes.find((entry) => entry.id === connection.source);
const target = nodes.find((entry) => entry.id === connection.target);
if (!source || !target) return "missing";
if (source.data.kind === "widget") return planFlowConnection({ source: target.id, target: source.id }, nodes, values);
if (source.data.kind === "source" || (source.data.kind === "action" && target.data.kind === "query")) return "direct";
let kind: FlowBindingIntent["kind"] = "query";
let identifier = source.data.identifier;
let native = source.data.kind === "native";
if (source.data.kind === "options") {
kind = "option";
if (target.data.kind !== "widget") {
kind = "requestOption";
identifier = target.data.identifier;
native = target.data.kind === "native";
}
} else if (source.data.kind === "action") kind = "action";
else if (native && record(record(readObject(values.extensions).native)[identifier]).kind === "action")
kind = "action";
return {
kind,
source: source.id,
target: target.id,
identifier,
native,
snapshot: {
template: values.template,
requests: values.requests,
options: values.options,
extensions: values.extensions,
},
};
}
export function isFlowBindingCurrent(intent: FlowBindingIntent, values: CustomWidgetFormValues) {
return Object.entries(intent.snapshot).every(([key, value]) => values[key as keyof typeof intent.snapshot] === value);
}
/** Deferred graph props cannot authorize removal after a newer authored reference was added. */
export function isGeneratedConnectionCurrent(
values: CustomWidgetFormValues,
edgeId: string | undefined,
ids: readonly string[],
) {
const current = projectWidgetGraph(values, { version: 1, nodes: {}, groups: {} }).edges.find(
(edge) => edge.id === edgeId,
)?.data?.generatedBindingIds;
return !!current?.length && current.length === ids.length && current.every((id) => ids.includes(id));
}
@@ -0,0 +1,58 @@
"use client";
import { createContext, useCallback, useContext, useState } from "react";
import type { ReactNode } from "react";
import type { Connection } from "@xyflow/react";
import { useCustomWidgetFormDocumentStore } from "../_custom-widget-form-state";
import type { CustomWidgetWorkbenchForm } from "../_custom-widget-form-utils";
import { createFlowCommands, isGraphEditable } from "./commands";
import { isGeneratedConnectionCurrent, planFlowConnection } from "./connection-planner";
import type { FlowBindingIntent } from "./connection-planner";
import type { WidgetNode, WidgetEdge } from "./graph";
import { FlowBindingDialog } from "./binding-dialog";
type Connect = (connection: Connection, nodes: WidgetNode[], replacing?: WidgetEdge) => string | null;
const FlowConnectionContext = createContext<Connect | null>(null);
export function FlowConnectionProvider({ form, children }: { form: CustomWidgetWorkbenchForm; children: ReactNode }) {
const store = useCustomWidgetFormDocumentStore();
const [pending, setPending] = useState<FlowBindingIntent | null>(null);
const connect = useCallback<Connect>(
(connection, nodes, replacing) => {
if (!isGraphEditable(store.getValues())) return "invalidGraphJson";
if (replacing && !replacing.data?.generatedBindingIds?.length)
return createFlowCommands(form, store).reconnect(replacing, connection, nodes);
const plan = planFlowConnection(connection, nodes, store.getValues());
if (plan === "direct") {
if (replacing) return "codeOwned";
let issue: string | null = null;
store.transaction(() => {
issue = createFlowCommands(form, store).connect(connection, nodes);
});
return issue;
}
if (typeof plan === "string") return plan;
if (replacing) {
if (!replacing.data?.generatedBindingIds?.length) return "codeOwned";
if (!isGeneratedConnectionCurrent(store.getValues(), replacing.id, replacing.data.generatedBindingIds))
return "codeOwned";
plan.replaceGeneratedIds = replacing.data.generatedBindingIds;
plan.replaceEdgeId = replacing.id;
}
setPending(plan);
return null;
},
[form, store],
);
return (
<FlowConnectionContext.Provider value={connect}>
{children}
{pending && <FlowBindingDialog intent={pending} form={form} onClose={() => setPending(null)} />}
</FlowConnectionContext.Provider>
);
}
export function useFlowConnection() {
const connect = useContext(FlowConnectionContext);
if (!connect) throw new Error("Flow connections require FlowConnectionProvider");
return connect;
}
@@ -0,0 +1,151 @@
"use client";
import { useState } from "react";
import { ActionIcon, Alert, Button, Group, Select, Stack, Tooltip } from "@mantine/core";
import { IconArrowLeft, IconArrowRight, IconUnlink } from "@tabler/icons-react";
import { useI18n } from "@homarr/translation/client";
import { connectionIssue, createFlowCommands, isGraphEditable } from "./commands";
import type { WidgetNode, WidgetEdge } from "./graph";
import type { CustomWidgetWorkbenchForm } from "../_custom-widget-form-utils";
import { useCustomWidgetFormDocumentStore } from "../_custom-widget-form-state";
import { useFlowConnection } from "./connection-provider";
interface Props {
node: WidgetNode;
nodes: WidgetNode[];
edges: WidgetEdge[];
form: CustomWidgetWorkbenchForm;
onSelect(id: string): void;
}
export function Connections(props: Props) {
return <ConnectionEditor key={props.node.id} {...props} />;
}
function ConnectionEditor({ node, nodes, edges, form, onSelect }: Props) {
const t = useI18n("customWidget.flow");
const store = useCustomWidgetFormDocumentStore();
const connect = useFlowConnection();
const [target, setTarget] = useState<string | null>(null);
const [source, setSource] = useState<string | null>(null);
const [issue, setIssue] = useState<string | null>(null);
const editable = isGraphEditable(store.getValues());
const destinations = nodes.filter(
(other) =>
!connectionIssue({ source: node.id, target: other.id }, nodes) &&
(other.data.kind === "widget" ||
node.data.kind === "options" ||
!edges.some((edge) => edge.source === node.id && edge.target === other.id)),
);
const sources = nodes.filter(
(other) =>
!connectionIssue({ source: other.id, target: node.id }, nodes) &&
(node.data.kind === "widget" ||
other.data.kind === "options" ||
!edges.some((edge) => edge.source === other.id && edge.target === node.id)),
);
const related = edges.filter((edge) => edge.source === node.id || edge.target === node.id);
const commands = createFlowCommands(form, store);
return (
<Stack gap={6} mb="sm">
{(!editable || issue) && (
<Alert color="yellow" p="xs" aria-live="polite">
{t((issue ?? "invalidGraphJson") as "codeOwned")}
</Alert>
)}
{related.map((edge) => {
let otherId = edge.source;
if (edge.source === node.id) otherId = edge.target;
const other = nodes.find((entry) => entry.id === otherId);
let Direction = IconArrowLeft;
if (edge.source === node.id) Direction = IconArrowRight;
let disconnectLabel = t("disconnect");
if (edge.data?.generatedBindingIds?.length) disconnectLabel = t("bindingDisconnect");
return (
<Group key={edge.id} gap={4} wrap="nowrap">
<Button
type="button"
size="compact-xs"
variant="subtle"
leftSection={<Direction size={14} />}
onClick={() => other && onSelect(other.id)}
>
{t(`relationship.${edge.data?.relationship ?? "data"}`)} · {other?.data.label}
</Button>
{(edge.data?.relationship === "invalidates" || !!edge.data?.generatedBindingIds?.length) && (
<Tooltip label={disconnectLabel}>
<ActionIcon
type="button"
size="sm"
variant="subtle"
aria-label={disconnectLabel}
disabled={!editable}
onClick={() => setIssue(commands.disconnect(edge))}
>
<IconUnlink size={14} />
</ActionIcon>
</Tooltip>
)}
</Group>
);
})}
{sources.length > 0 && (
<Group align="end" wrap="nowrap">
<Select
label={t("connectFrom")}
size="xs"
value={source}
onChange={setSource}
disabled={!editable}
searchable
data={sources.map((entry) => ({
value: entry.id,
label: `${t(`kind.${entry.data.kind}`)} · ${entry.data.label}`,
}))}
/>
<Button
size="xs"
type="button"
disabled={!editable || !sources.some((entry) => entry.id === source)}
onClick={() => {
if (!source) return;
const result = connect({ source, target: node.id, sourceHandle: "out", targetHandle: "in" }, nodes);
setIssue(result);
if (!result) setSource(null);
}}
>
{t("connect")}
</Button>
</Group>
)}
{destinations.length > 0 && (
<Group align="end" wrap="nowrap">
<Select
label={t("connectTo")}
size="xs"
value={target}
onChange={setTarget}
disabled={!editable}
searchable
data={destinations.map((entry) => ({
value: entry.id,
label: `${t(`kind.${entry.data.kind}`)} · ${entry.data.label}`,
}))}
/>
<Button
size="xs"
type="button"
disabled={!editable || !destinations.some((entry) => entry.id === target)}
onClick={() => {
if (!target) return;
const result = connect({ source: node.id, target, sourceHandle: "out", targetHandle: "in" }, nodes);
setIssue(result);
if (!result) setTarget(null);
}}
>
{t("connect")}
</Button>
</Group>
)}
</Stack>
);
}
Loaded 100 of 604 files, more files were not shown because too many files have changed in this diff. Show more