feat(custom-widgets): add extensible widget platform

This commit is contained in:
ajnart committed 2026-09-12 13:54:05 +02:00
1 parent 6cca757493
commit 8f152f1929
317 files changed
+32326 -1788

No files matched your search

+130
View File
@@ -0,0 +1,130 @@
# Homarr Widget SDK 1
The SDK is the shared host contract for trusted dashboard packages and native widgets. A package exports React components for its tile, optional advanced view, and optional configuration view. Server handlers run in an owner-trusted child process with Homarr-level access. The worker provides cancellation and process isolation; it is not a security sandbox.
Import client hooks from `@homarr/widget-sdk`, server helpers from `@homarr/widget-sdk/server`, and shared transport types from `@homarr/widget-sdk/shared`. React, React DOM, Mantine, Tabler, TanStack Query, and the SDK resolve to the host's existing modules. Package dependencies are compiled locally; never load another React copy from a CDN.
## Client contract
| Export | Purpose |
| ------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `useWidgetHost()` | Board/item/installation identity, actor, locale, timezone, theme, reduced motion, edit/preview state, visibility, compact/advanced mode, logical dimensions, display scale and visible dimensions. |
| `useWidgetOptions<T>()` | The active placement's options after applying installation defaults and migrations. |
| `useWidgetQuery<T>(name, input, options)` | Authorized server query with cancellation, shared query cache, optional polling, visibility suspension and transient stale-data retention. Authorization failures hide cached data. |
| `useWidgetAction<TOutput, TInput>(name)` | Authorized server mutation. Successful mutations invalidate this widget's queries. Actions are disabled during board editing; the preview transport simulates actions unless the owner enables live actions. |
| `useWidgetSubscription<T>(name, input, { enabled, maximumEvents })` | A bounded event buffer with `data`, `events`, `error`, `connected`, and `reconnect()`. The stream unsubscribes when hidden, replaced, or unmounted. |
| `useWidgetState<T>(key, initial)` | Transient instance state shared across tile, advanced and configuration surfaces. Use for selected rows, filters, chart windows, form drafts and zoom positions. |
| `useWidgetStorage<T>(scope, key, initial)` | Managed `user`, `instance`, or `installation` JSON storage. Returns query status, `data`, `set(value)`, `saving` and `saveError`. The server enforces the actor's storage rights. |
| `useWidgetCommands(commands)` | Named command descriptors registered with Homarr's tile context menu and command palette. Each descriptor has `id`, `label`, `run`, optional description/disabled/hidden/destructive metadata. |
| `useWidgetClock(intervalMs)` | A real-time clock that pauses updates while hidden and catches up on return. Returns `null` before the first client tick. |
| `useWidgetServices()` | Host notifications, navigation, `openAdvanced()`/`closeAdvanced()` for native focus, detail modal, confirmation modal, and `updateOptions(options)`. The configuration preview reports option changes to the workbench. |
| `WidgetScope` | Compose components with isolated state, query caches, managed storage keys and command IDs. `handlerPrefix` maps each component's handler names to the composed server manifest. |
React `useState` belongs to a rendered component and resets when the surface component is replaced. SDK state lives in the placement host and survives tile/advanced switches. It also survives package updates using the same SDK and configuration schema version. Server query/event caches remain revision-specific. Use managed storage when data must survive a reload or be shared with other viewers.
`useWidgetQuery` accepts `{ enabled, refetchInterval, staleTime }`; all durations are milliseconds. No polling occurs unless requested. The native widget Refresh command refreshes active SDK queries. Package lifecycle events deliver activation, connection changes, disablement and storage invalidation across viewers without polling the package definition. Transport permissions remain authoritative even when a UI hides or disables a control.
A source-free package needs no connections, handlers or server file. Clocks, calculators, SVG compositions and browser-local tools can render directly. Host-managed persistence still calls Homarr's storage API; it requires no external service.
## Server contract
```ts
import { defineWidgetServer, fetchWidgetConnection } from "@homarr/widget-sdk/server";
export default defineWidgetServer({
status: async (_input, context) => {
const response = await fetchWidgetConnection(context, {
connection: "service",
path: "/api/status",
});
if (!response.ok) throw new Error(`Service returned HTTP ${response.status}`);
return response.data;
},
});
```
Declare each handler in `manifest.handlers` as a query, action, subscription, or migration. Query handlers require view access by default; actions default to modify and migrations to full access. Anonymous access also requires the package's explicit handler opt-in and an owner-managed local guest grant. A handler receives `context.signal`, `instanceId`, `boardId`, optional `userId`, and `sdk.invoke(operation, input)`.
| Helper | Result |
| --------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `fetchWidgetConnection<T>(context, {connection, path?, method?, query?, headers?, body?, responseType?})` | `{data, ok, status, contentType, durationMs, updatedAt}`. Response type can be JSON, text, or base64. Bound credentials, local DNS, TLS policy, timeout and response bounds remain server-side. |
| `getWidgetConnection<TSettings>(context, {connection, serviceType?})` | `{configuration, secrets}` for server adapters using SQLite, MQTT, SSH, database drivers, local files or another native protocol. Service settings are typed with `TSettings`; an optional `serviceType` asserts the expected connection type. Never return this object to a browser handler result. |
| `getWidgetServerContext<TOptions>(context)` | `{options, installationId, bindingNames, isPreview}`. Use placement options for server-only filesystem paths and request configuration, and binding names for optional configured sources. |
| `callWidgetIntegration<T>(context, {connection, capability, input?})` | Versioned native adapter result. Reuses Homarr's normalization, integration credentials, caching and native query/interact authorization. |
| `subscribeWidgetIntegration<T>(context, {connection, capability, input?})` | Async generator that releases the native subscription when cancelled or completed. |
| `callWidgetRunner<T>(context, {connection, handler, input?})` | Runs a handler on an owner-configured remote runner through a named HTTP connection. |
| `subscribeWidgetRunner<T>(context, {connection, handler, input?})` | Bounded remote-runner subscription with cancellation. Remote packages use their own environment and do not inherit a Homarr SDK backchannel. |
`fetchWidgetConnection` returns non-2xx responses for the author to inspect. Network, TLS, timeout and parsing errors reject. Relative paths resolve against the configured base URL; a leading `/` addresses the origin root. Different origins require separate named connections. Private LAN, Docker service names and loopback addresses resolve from the Homarr process/container. A browser URL is distinct from that server address.
Trusted server code can import Node modules, read mounted files, use child processes and execute installed dependencies. Only the owner should install reviewed packages. Secrets may be read through the trusted server bridge and must not be returned to the browser or included in shared source. Queries should remain observational; keep state changes in declared actions so previews and guest policy can handle them correctly. Honor `context.signal` and release resources in `finally` for long-running work.
## Native capabilities v1
| Capability | Kind and input | Result |
| --------------------------------------------------------------------- | ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `beszel.systems` | Query, `{}` | `{data: BeszelSystemRow[], timestamp}` with normalized CPU/memory/disk percentages, byte rates, uptime, hostname, agent and hardware metadata. |
| `beszel.stats` | Query, `{systemId, timePeriod, includeDocker?}` | `{data:{systemStats,containerStats}, timestamp}`. Periods: `1m`, `1h`, `12h`, `24h`, `1w`, `30d`. Native Beszel history records retain their source units; the reference demonstrates conversion. |
| `beszel.containers` | Query, `{systemId}` | Native container inventory. |
| `beszel.alerts` | Query, `{includeHistory?, maxHistoryItems?}` | `{data:{alerts,history}, timestamp}`. |
| `beszel.live` | Subscription, `{systemId}` | Native live metric events. |
| `downloads.queue` | Query, `{limit?}` | `{data:{status,items}, timestamp}` for any native download-client integration. Item progress is `0..1`, speed is bytes/s and time is milliseconds. |
| `downloads.pause`, `downloads.resume` | Action, `{}` | `{ok:true}` after native queue control and cache invalidation. |
| `downloads.pauseItem`, `downloads.resumeItem`, `downloads.deleteItem` | Action, `{item, fromDisk?}` | `{ok:true}`. Pass the actual normalized item; deleting downloaded files requires explicit `fromDisk:true`. |
| `media.sessions` | Query, `{showOnlyPlaying?}` | `{data:StreamSession[], timestamp}`, including playback position/duration and available transcoding metadata. |
| `sonarr.calendar` | Query, `{start,end,includeUnmonitored?}` | Native calendar events; dates accept ISO strings. |
| `sonarr.missing`, `sonarr.queue` | Query, `{limit?}` | `{items,totalCount}` with native links, episode metadata and queue progress. |
## Composition
```tsx
<WidgetScope name="downloads" handlerPrefix="downloads.">
<Downloads />
</WidgetScope>
```
The child calls `useWidgetQuery("queue")`; its composed server manifest declares `downloads.queue`. A child command `pause` becomes `downloads:pause`. Scoped storage keys and SDK state keys cannot collide with sibling scopes. Options can be supplied to a scope explicitly. Author-defined configuration saves still operate on the parent placement; pass a deliberate parent option update when composing independent configuration components.
## Reference packages
Import `widgetReferencePackages` from `@homarr/widget-sdk/examples` or open an individual JSON package in `examples/`. Every reference includes source and can be compiled/imported through the same management flow as a shared package.
- `clock`: local/UTC/world time, native command, source-free tile and advanced surface.
- `timer`: deadline-based focus timer with shared selection and hidden-tab correctness.
- `beszel`: two attributable sources with partial-failure handling, persisted native table layouts, eight history panels and bounded live metrics.
- `checklist`: managed JSON persistence and user/instance/installation scopes.
- `downloads`: two independently queried torrent/Usenet clients, source-qualified controls and confirmed removal. Batch pause/resume reports each client's result; buttons and commands honor exact guest-approved inputs through `useWidgetCapabilities`.
- `sonarr`: upcoming episodes, missing releases and queue progress.
- `rack`: arbitrary SVG, keyboard interaction, package CSS and native system details.
- `backup`: Node filesystem metadata with no upstream API; requires a readable mounted backup directory.
- `household`: Home Assistant HTTP connection, confirmed controls and an executable configuration surface.
- `overview`: independently authored rack/download/media components composed using SDK scopes.
- `media`: responsive native media sessions with progress and host-native detail modals.
- `sqlite`: bounded read-only named SQL queries and optional local JSON through a URL-free service connection.
- `mqtt`: authenticated broker subscriptions, retained messages and allowed-topic publishing through a server adapter.
References use real adapter responses and empty/error states, without fabricated live metrics. They are implementation examples, not an assertion that every upstream application or deployment has been exercised. Native adapters and arbitrary trusted package code remain complementary extension paths.
## Shared native tables
`@homarr/widget-sdk/ui` exports `HomarrDataTable`, `usePersistedTableLayout`, and `useTableLayoutPersistence`. Native Beszel and other Homarr tables consume these same implementations through their existing import paths. Columns support ordering and resizing with the native proportional-width preview, sorting, selection, pagination and row actions. The Beszel reference persists each viewer's layout in browser storage and shows two source results with source-qualified row IDs, partial failures and source-specific history/live drilldowns.
For large datasets, `MantineReactTable` and `useTranslatedMantineReactTable` expose Homarr's existing localized table engine, including its row-virtualization options. Keep column definitions and rows memoized. Use SDK state for transient table state, browser-local persistence for viewer layout preferences, or managed storage for shared state. None of the table entrypoints import the database, integration executors or custom-widget compiler.
## Viewer capabilities and live connections
`useWidgetCapabilities()` returns query status and `canRun(handler, input)`. Use it to disable or hide controls before attempting a server action. It includes board permissions and exact approved guest inputs, and fails closed while unavailable. Scoped components resolve their handler prefix automatically. This is presentation guidance; the server checks authorization again on every invocation.
Subscriptions with the same viewer, placement, artifact, configuration, handler, and input share one connection. The host retains only the latest event for a newly mounted consumer, with a 500 ms release grace during native advanced-view transitions. Each SDK consumer controls its own bounded event history. Binding changes reconnect; authorization errors and disabling remove retained events immediately. A different viewer or artifact never reuses the connection.
A retained authoring preview sets `host.executionEnabled` to false and pauses SDK queries, clock updates, subscriptions and controls. Existing cached data remains visible while an invalid draft or replacement is being reviewed. The prior preview session and styles retire only after the replacement React surface commits successfully. Query freshness defaults to the requested polling interval, or one second without polling, so ordinary compact/advanced transitions reuse recent data; authors can override `staleTime`.
Optional host libraries load from the surface's compiled import list. New artifacts bundle only the Tabler icons actually imported by their source, and record the installed icon package version. Clocks without chart, table or legacy imports do not load those adapters. Older artifacts retain compatibility with their original host-module declarations.
## Converting Custom JSX v2
An administrator can convert a saved v2 definition into a separate disabled trusted package. The converter copies the JSX, request declarations, options, and dynamic option choices. Local source URLs and credentials become named encrypted connections; exported package source contains neither those connection values nor the original definition ID. Preview and explicit activation remain required.
`@homarr/widget-sdk/legacy` supplies `LegacyWidget` and `LegacyConfiguration` through the Homarr host. The compatibility tile reuses the existing interpreter and components, including bound inputs, manual/load queries, confirmations and invalidations. Bound input values use SDK state across compact and advanced views. Load queries respect the dashboard placement's refresh interval. Dynamic option queries run from the configuration surface against the selected local bindings. These adapters let an owner replace individual sections with ordinary React and SDK components without rewriting every behavior at once.
Conversion leaves all original definitions and placements unchanged. After activation, `customWidget.package.migrateV2Placement` explicitly changes one selected original placement to the converted package. It preserves its ID, geometry, refresh interval, existing options and materialized original defaults, rejects concurrent placement changes, and keeps the original definition readable. Local conversion provenance is installation metadata and is excluded from exported source.
+71
View File
@@ -0,0 +1,71 @@
{
"$schema": "homarr-widget-package-v3",
"manifest": {
"id": "homarr.reference.backup",
"version": "1.1.0",
"sdkVersion": "1",
"name": "Filesystem backup monitor",
"description": "Read backup files and a JSON status/history report without an API, with an optional owner-configured backup executable.",
"entrypoints": {
"tile": "widget.tsx",
"advanced": "widget.tsx",
"server": "server.ts"
},
"handlers": {
"files": {
"kind": "query",
"permission": "view"
},
"runBackup": {
"kind": "action",
"permission": "full",
"timeoutMs": 300000,
"inputSchema": {
"type": "object",
"properties": {},
"additionalProperties": false
}
}
}
},
"files": {
"widget.tsx": "import type { BackupOptions, BackupSnapshot, BackupRunResult } from \"./types\";\nimport { Alert, Badge, Button, Group, Loader, Stack, Table, Text } from \"@mantine/core\";\nimport { useWidgetAction, useWidgetClock, useWidgetHost, useWidgetOptions, useWidgetQuery, useWidgetServices } from \"@homarr/widget-sdk\";\nexport default function Backups() {\n const host = useWidgetHost();\n const services = useWidgetServices();\n const options = useWidgetOptions<BackupOptions>();\n const now = useWidgetClock(60000);\n const query = useWidgetQuery<BackupSnapshot>(\"files\", {}, {refetchInterval:60000});\n const run = useWidgetAction<BackupRunResult,Record<string,never>>(\"runBackup\");\n const files = query.data?.files ?? [];\n const latest = files[0];\n const status = query.data?.status;\n const finishedAt = status?.finishedAt ?? latest?.modifiedAt;\n const overdue = finishedAt && now !== null && now - finishedAt > options.maximumAgeHours * 3600000;\n let label = \"No backup report\";\n let color = \"gray\";\n if (finishedAt) { label = \"Recent backup activity\"; color = \"teal\"; }\n if (status?.status === \"success\") label = \"Backup succeeded\";\n if (overdue) { label = \"Backup overdue\"; color = \"orange\"; }\n if (status?.status === \"failure\") { label = \"Backup failed\"; color = \"red\"; }\n if (query.data?.running || run.isPending || status?.status === \"running\") { label = \"Backup running\"; color = \"blue\"; }\n const execute = async () => {\n if (await services.confirm({title:\"Run backup now?\",message:\"Run the owner-configured backup executable on the Homarr server?\"})) run.mutate({});\n };\n return <Stack p=\"md\" h=\"100%\" gap=\"sm\" style={{overflow:\"auto\"}}>\n <Group justify=\"space-between\"><Text fw={600}>{options.title}</Text><Badge color={color}>{label}</Badge></Group>\n {query.isPending && <Loader size=\"sm\" />}\n {query.error && <Alert color=\"red\">{query.error.message}</Alert>}\n {(query.data?.errors ?? []).map((error,index) => <Alert key={index} color=\"yellow\">{error}</Alert>)}\n {status?.message && <Text size=\"sm\">{status.message}</Text>}\n {finishedAt && <Text size=\"sm\">{new Date(finishedAt).toLocaleString(host.locale)}</Text>}\n {latest && <Text size=\"xs\" c=\"dimmed\">{latest.name} · {(latest.bytes/1048576).toFixed(1)} MiB</Text>}\n {status?.durationSeconds != null && <Text size=\"xs\">Last duration: {status.durationSeconds}s</Text>}\n <Group><Button size=\"xs\" variant=\"light\" onClick={() => void query.refetch()}>Refresh</Button>\n {host.displayMode === \"compact\" && <Button size=\"xs\" variant=\"subtle\" onClick={services.openAdvanced}>History and files</Button>}\n {query.data?.commandConfigured && <Button size=\"xs\" disabled={host.isEditMode || query.data.running} loading={run.isPending} onClick={() => void execute()}>Run backup</Button>}\n </Group>\n {run.error && <Alert color=\"red\">{run.error.message}</Alert>}\n {run.data?.completed && <Text size=\"xs\" c=\"teal\">Command completed in {run.data.durationSeconds}s. Refresh to read its status report.</Text>}\n {host.displayMode === \"advanced\" && <>\n <Text fw={600}>Run history</Text>\n {!(query.data?.history?.length) && <Text c=\"dimmed\" size=\"sm\">Add history entries to the configured JSON status report.</Text>}\n <Table><Table.Thead><Table.Tr><Table.Th>Finished</Table.Th><Table.Th>Status</Table.Th><Table.Th>Duration</Table.Th></Table.Tr></Table.Thead><Table.Tbody>{(query.data?.history ?? []).map((entry,index) => <Table.Tr key={index}><Table.Td>{entry.finishedAt ? new Date(entry.finishedAt).toLocaleString(host.locale) : \"Unknown\"}</Table.Td><Table.Td>{entry.status}</Table.Td><Table.Td>{entry.durationSeconds ?? \"—\"}s</Table.Td></Table.Tr>)}</Table.Tbody></Table>\n <Text fw={600}>Backup files</Text>\n <Table><Table.Thead><Table.Tr><Table.Th>File</Table.Th><Table.Th>Modified</Table.Th><Table.Th>MiB</Table.Th></Table.Tr></Table.Thead><Table.Tbody>{files.map((file) => <Table.Tr key={file.name}><Table.Td>{file.name}</Table.Td><Table.Td>{new Date(file.modifiedAt).toLocaleString(host.locale)}</Table.Td><Table.Td>{(file.bytes/1048576).toFixed(1)}</Table.Td></Table.Tr>)}</Table.Tbody></Table>\n </>}\n <Text size=\"xs\" c=\"dimmed\">Activity reports do not verify restore integrity. Test restores separately.</Text>\n </Stack>;\n}\n",
"server.ts": "import type { BackupOptions, BackupFile, BackupRecord } from \"./types\";\nimport { readdir, readFile, stat } from \"node:fs/promises\";\nimport { join, isAbsolute } from \"node:path\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { defineWidgetServer, getWidgetServerContext } from \"@homarr/widget-sdk/server\";\nimport { backupCommand } from \"./command\";\nconst execute = promisify(execFile);\nlet running = false;\nconst timestamp = (value:unknown):number|null => { let next=NaN; if(typeof value===\"number\") next=value; else if(typeof value===\"string\") next=Date.parse(value); return Number.isFinite(next) ? next : null; };\nconst record = (input:unknown):BackupRecord => {\n const value = input && typeof input === \"object\" ? input as Record<string,unknown> : {};\n const status = value.status;\n return {\n status: status === \"success\" || status === \"failure\" || status === \"running\" ? status : \"unknown\",\n finishedAt: timestamp(value.finishedAt),\n durationSeconds: typeof value.durationSeconds === \"number\" ? value.durationSeconds : null,\n bytes: typeof value.bytes === \"number\" ? value.bytes : null,\n message: typeof value.message === \"string\" ? value.message.slice(0,500) : \"\",\n };\n};\nexport default defineWidgetServer({\n files: async (_input, context) => {\n const { options } = await getWidgetServerContext<BackupOptions>(context);\n const errors = [];\n const files:BackupFile[] = [];\n let status:BackupRecord|null = null;\n let history:BackupRecord[] = [];\n try {\n if (typeof options.directory !== \"string\" || !isAbsolute(options.directory)) throw new Error(\"Choose an absolute backup directory inside Homarr\");\n const entries = await readdir(options.directory, {withFileTypes:true});\n const matches = entries.filter((entry) => entry.isFile() && (!options.suffix || entry.name.endsWith(options.suffix)));\n if (matches.length > 1000) errors.push(\"The directory has over 1,000 matching files; narrow the suffix to inspect the full set.\");\n for (const entry of matches.slice(0, 1000)) {\n context.signal.throwIfAborted();\n const info = await stat(join(options.directory, entry.name));\n files.push({name:entry.name, bytes:info.size, modifiedAt:info.mtimeMs});\n }\n files.sort((a,b) => b.modifiedAt - a.modifiedAt);\n } catch (error) { errors.push(error instanceof Error ? error.message : String(error)); }\n if (options.statusFile) {\n try {\n if (typeof options.statusFile !== \"string\" || !isAbsolute(options.statusFile)) throw new Error(\"Status file must use an absolute container path\");\n if ((await stat(options.statusFile)).size > 1048576) throw new Error(\"Status report exceeds 1 MiB\");\n const report:unknown = JSON.parse(await readFile(options.statusFile, \"utf8\"));\n status = record(report);\n if (report && typeof report === \"object\" && \"history\" in report && Array.isArray(report.history)) history = report.history.slice(-100).map(record).sort((a,b) => (b.finishedAt ?? 0) - (a.finishedAt ?? 0));\n } catch (error) { errors.push(error instanceof Error ? error.message : String(error)); }\n }\n return {files:files.slice(0,100),status,history,errors,running,commandConfigured:Boolean(backupCommand.executable)};\n },\n runBackup: async (_input, context) => {\n const {isPreview} = await getWidgetServerContext(context);\n if (isPreview) return {simulated:true};\n if (!backupCommand.executable || !isAbsolute(backupCommand.executable)) throw new Error(\"Configure an absolute executable in command.ts and activate the package first\");\n if (running) throw new Error(\"A backup command is already running\");\n running = true;\n const started = Date.now();\n try {\n await execute(backupCommand.executable, backupCommand.args, {shell:false,timeout:backupCommand.timeoutMs,maxBuffer:524288,signal:context.signal});\n return {completed:true,durationSeconds:Math.round((Date.now()-started)/1000)};\n } catch (error) {\n const code = error && typeof error === \"object\" && \"code\" in error ? error.code : \"unknown\";\n throw new Error(`The configured backup command failed (${code}). Check the backup service logs.`);\n } finally { running = false; }\n },\n});\n",
"command.ts": "// Owner configuration: edit this source file deliberately, then preview and activate.\n// The dashboard cannot supply executable paths or arguments. No shell is used.\nexport const backupCommand = {\n executable: \"\", // Example: \"/usr/local/bin/run-backup\"\n args: [] as string[],\n timeoutMs: 240000,\n};\n",
"README.md": "# Filesystem backup monitor\nMount your backup directory and optional status JSON into Homarr. No API connection is required.\n\nThe optional status file is written by your backup system. Example:\n```json\n{\"status\":\"success\",\"finishedAt\":\"2026-09-12T01:00:00Z\",\"durationSeconds\":92,\"bytes\":1048576,\"message\":\"Nightly backup completed\",\"history\":[{\"status\":\"success\",\"finishedAt\":\"2026-09-11T01:00:00Z\",\"durationSeconds\":88}]}\n```\n`status` is success, failure, running, or unknown. `finishedAt` accepts ISO timestamps or epoch milliseconds. The widget reads at most 1 MiB and 100 history records. File timestamps alone report activity, not backup success or restore integrity.\n\nTo enable Run backup, deliberately edit `command.ts` with an absolute executable and fixed argument array. The executable must exist inside Homarr. Activate the reviewed change. The browser supplies no command text; the named full-permission action uses execFile without a shell, bounded output and a timeout. It never runs from a query or in preview. stdout/stderr are not returned to dashboard viewers. The configured program should update the status report itself.\n",
"types.ts": "export type BackupOptions = {title:string;directory:string;suffix:string;maximumAgeHours:number;statusFile:string};\nexport interface BackupRecord {status:\"success\"|\"failure\"|\"running\"|\"unknown\";finishedAt:number|null;durationSeconds:number|null;bytes:number|null;message:string;}\nexport interface BackupFile {name:string;bytes:number;modifiedAt:number;}\nexport interface BackupSnapshot {files:BackupFile[];status:BackupRecord|null;history:BackupRecord[];errors:string[];running:boolean;commandConfigured:boolean;}\nexport interface BackupRunResult {simulated?:boolean;completed?:boolean;durationSeconds?:number;}\n"
},
"dependencies": {},
"connections": {},
"options": {
"title": {
"control": "text",
"label": "Title",
"default": "Backups"
},
"directory": {
"control": "text",
"label": "Directory in the Homarr container",
"description": "Mount the backup directory into Homarr and enter its absolute container path.",
"default": "/backups"
},
"suffix": {
"control": "text",
"label": "Filename suffix",
"default": ".gz"
},
"maximumAgeHours": {
"control": "number",
"label": "Maximum backup age (hours)",
"default": 24,
"min": 1,
"max": 8760
},
"statusFile": {
"control": "text",
"label": "Status report JSON file",
"description": "Optional absolute path to a backup status report inside Homarr. See README.md for the format.",
"default": ""
}
}
}
+48
View File
@@ -0,0 +1,48 @@
{
"$schema": "homarr-widget-package-v3",
"manifest": {
"id": "homarr.reference.beszel",
"version": "1.0.0",
"sdkVersion": "1",
"name": "Custom Beszel systems",
"description": "Two attributable Beszel sources, native persisted table layouts, eight history panels and bounded live metrics with partial-failure recovery.",
"entrypoints": {
"tile": "systems.tsx",
"advanced": "systems.tsx",
"server": "server.ts"
},
"handlers": {
"systems": {
"kind": "query",
"permission": "view"
},
"stats": {
"kind": "query",
"permission": "view"
},
"live": {
"kind": "subscription",
"permission": "view",
"timeoutMs": 300000
}
}
},
"files": {
"server.ts": "import type { AttributedSystem, NativeResult, SystemRow, StatsResult, StatsInput, LiveStatsEvent } from \"./beszel-types\";\nimport { callWidgetIntegration, defineWidgetServer, getWidgetServerContext, subscribeWidgetIntegration } from \"@homarr/widget-sdk/server\";\nconst declaredConnections = new Set([\"beszel\", \"secondary\"]);\nconst getConnection = (input: {connection?:string} | undefined) => {\n const connection = input?.connection ?? \"beszel\";\n if (!declaredConnections.has(connection)) throw new Error(\"Unknown Beszel connection\");\n return connection;\n};\nexport default defineWidgetServer({\n systems: async (_input, context) => {\n const {bindingNames} = await getWidgetServerContext(context);\n const names = [...declaredConnections].filter((name) => bindingNames.includes(name));\n if (!names.length) throw new Error(\"Bind a Beszel integration to this widget first\");\n const results = await Promise.allSettled(names.map((connection) => callWidgetIntegration<NativeResult<SystemRow[]>>(context, {connection, capability:\"beszel.systems\"})));\n const data: AttributedSystem[] = [];\n const sources = results.map((result, index) => {\n const connection = names[index]!;\n if (result.status === \"rejected\") return {connection,ok:false,error:result.reason instanceof Error ? result.reason.message : String(result.reason)};\n data.push(...result.value.data.map((system) => ({...system,connection,rowKey:`${connection}:${system.id}`})));\n return {connection,ok:true,timestamp:result.value.timestamp};\n });\n return {data,sources};\n },\n stats: (input: StatsInput, context) => callWidgetIntegration<NativeResult<StatsResult>>(context, {connection:getConnection(input),capability:\"beszel.stats\",input}),\n live: (input: StatsInput, context) => subscribeWidgetIntegration<LiveStatsEvent>(context, {connection:getConnection(input),capability:\"beszel.live\",input}),\n});",
"beszel-types.ts": "// Public result fields used from the Homarr Beszel capability adapter.\nexport interface SystemRow {\n id:string; name:string; status:\"up\"|\"down\"|\"paused\"|\"pending\";\n cpu:number; memory:number; disk:number; gpu:number; netBytes:number; uptime:number;\n hostname:string; cpuModel:string; cores:number; osName:string; agentVersion:string;\n}\nexport interface AttributedSystem extends SystemRow {connection:string;rowKey:string}\nexport interface NativeResult<T> {data:T;timestamp?:string}\nexport interface SystemStats {cpu:number;mu:number;mb:number;du:number;dio?:[number,number];dr?:number;dw?:number;b?:[number,number];ns?:number;nr?:number}\nexport interface ContainerStats {n:string;c:number;m:number;b?:[number,number];ns?:number;nr?:number}\nexport interface StatsRecord<T> {id:string;created:string;stats:T}\nexport type SystemRecord = StatsRecord<SystemStats>;\nexport type ContainerRecord = StatsRecord<ContainerStats[]>;\nexport interface StatsResult {systemStats:SystemRecord[];containerStats:ContainerRecord[]}\nexport type LiveStatsEvent = {type:\"system_stats\";record:SystemRecord}|{type:\"container_stats\";record:ContainerRecord};\nexport interface StatsInput {connection?:string;systemId:string;timePeriod?:string;includeDocker?:boolean}\n\nexport interface SystemsResult {data:AttributedSystem[];sources:{connection:string;ok:boolean;error?:string;timestamp?:string}[]}\n",
"systems.tsx": "import type { AttributedSystem, SystemStats, ContainerStats, LiveStatsEvent, SystemsResult, NativeResult, StatsResult } from \"./beszel-types\";\nimport type { DataTableColumn, DataTableSortStatus } from \"@homarr/widget-sdk/ui\";\ntype Layout = {columnOrder:string;columnWidths:string};\ntype Selection = {connection:string;id:string;name:string};\ntype ChartData = Array<{time:string} & Record<string,string|number>>;\nimport { useCallback, useMemo } from \"react\";\nimport { Alert, Badge, Button, Group, Loader, ScrollArea, SegmentedControl, SimpleGrid, Stack, Text, TextInput } from \"@mantine/core\";\nimport { LineChart } from \"@mantine/charts\";\nimport { useWidgetHost, useWidgetQuery, useWidgetServices, useWidgetState, useWidgetSubscription, useLocalWidgetState } from \"@homarr/widget-sdk\";\nimport { HomarrDataTable, usePersistedTableLayout } from \"@homarr/widget-sdk/ui\";\n\nconst columnAccessors = [\"name\", \"connection\", \"hostname\", \"cpu\", \"memory\", \"disk\", \"gpu\", \"netBytes\", \"uptime\", \"cpuModel\", \"cores\", \"osName\", \"agentVersion\"];\nconst colors = [\"teal.6\", \"blue.6\", \"grape.6\", \"orange.6\", \"pink.6\", \"cyan.6\"];\nconst mib = 1024 ** 2;\nconst gib = 1024 ** 3;\nconst rate = (bytes: number | undefined, legacy: number | undefined) => bytes ?? (legacy ?? 0) * mib;\nconst order = <T extends {created:string}>(records: readonly T[]) => [...records].sort((left, right) => Date.parse(left.created) - Date.parse(right.created));\n\nfunction Chart({ title, data, names, unit, locale }: {title:string;data:ChartData;names:string[];unit:string;locale:string}) {\n const formatter = (value:number) => {\n if (unit === \"%\") return new Intl.NumberFormat(locale, { maximumFractionDigits: 1 }).format(value) + \"%\";\n return new Intl.NumberFormat(locale, { notation: \"compact\", maximumFractionDigits: 1 }).format(value) + \" \" + unit;\n };\n return <Stack gap={4} style={{ minWidth: 0 }}>\n <Text size=\"sm\" fw={600}>{title}</Text>\n {data.length === 0 ? <Text c=\"dimmed\" size=\"xs\">Waiting for samples</Text> :\n <LineChart h={180} data={data} dataKey=\"time\" series={names.map((name, index) => ({ name, color: colors[index % colors.length] }))} curveType=\"linear\" valueFormatter={formatter} withDots={false} />}\n </Stack>;\n}\n\nexport default function Systems() {\n const host = useWidgetHost();\n const services = useWidgetServices();\n const systems = useWidgetQuery<SystemsResult>(\"systems\", {}, { refetchInterval: 10000 });\n const [selected, setSelected] = useWidgetState<Selection | null>(\"system\", null);\n const [period, setPeriod] = useWidgetState(\"period\", \"1h\");\n const [search, setSearch] = useWidgetState(\"search\", \"\");\n const [sort, setSort] = useWidgetState<DataTableSortStatus<AttributedSystem>>(\"sort\", { columnAccessor: \"name\", direction: \"asc\" });\n const advanced = host.displayMode === \"advanced\";\n const live = useWidgetSubscription<LiveStatsEvent>(\"live\", { connection: selected?.connection ?? \"beszel\", systemId: selected?.id ?? \"\" }, { enabled: advanced && selected !== null && period === \"live\", maximumEvents: 120 });\n const stats = useWidgetQuery<NativeResult<StatsResult>>(\"stats\", { connection: selected?.connection ?? \"beszel\", systemId: selected?.id ?? \"\", timePeriod: period === \"live\" ? \"1h\" : period, includeDocker: true }, { enabled: advanced && selected !== null && period !== \"live\", refetchInterval: 5000 });\n const records = systems.data?.data ?? [];\n const visible = records.filter((system) => `${system.name} ${system.connection} ${system.hostname}`.toLocaleLowerCase().includes(search.toLocaleLowerCase())).toSorted((a, b) => {\n const direction = sort.direction === \"asc\" ? 1 : -1;\n const left = a[sort.columnAccessor as keyof AttributedSystem];\n const right = b[sort.columnAccessor as keyof AttributedSystem];\n if (typeof left === \"number\" && typeof right === \"number\") return (left - right) * direction;\n return String(left ?? \"\").localeCompare(String(right ?? \"\")) * direction;\n });\n const inspect = useCallback((system: AttributedSystem) => {\n setSelected({connection: system.connection, id: system.id, name: system.name});\n if (!advanced) services.openAdvanced();\n }, [advanced, services, setSelected]);\n const [layout, setLayout] = useLocalWidgetState({\n key: host.isPreview ? undefined : `custom-widget:beszel-layout:${host.itemId}:${host.userId ?? \"guest\"}`,\n version: 1, defaultValue: {columnOrder: \"\", columnWidths: \"\"},\n validate: (value): value is Layout => Boolean(value && typeof value === \"object\" && \"columnOrder\" in value && \"columnWidths\" in value && typeof value.columnOrder === \"string\" && typeof value.columnWidths === \"string\"),\n });\n const persistLayout = useCallback((patch: Partial<Layout>) => setLayout((current) => ({...current, ...patch})), [setLayout]);\n const columns = useMemo<DataTLine truncated
},
"dependencies": {},
"connections": {
"beszel": {
"label": "Beszel integration",
"kind": "integration"
},
"secondary": {
"kind": "integration",
"label": "Secondary Beszel integration",
"optional": true
}
},
"options": {}
}
@@ -0,0 +1,46 @@
{
"$schema": "homarr-widget-package-v3",
"manifest": {
"id": "homarr.reference.checklist",
"version": "1.0.0",
"sdkVersion": "1",
"name": "Shared maintenance checklist",
"description": "A persistent dashboard checklist with user, placement, or installation storage and host-native commands.",
"entrypoints": {
"tile": "widget.tsx",
"advanced": "widget.tsx"
},
"handlers": {}
},
"files": {
"widget.tsx": "import type { FormEvent } from \"react\";\nimport type { WidgetStorageScope } from \"@homarr/widget-sdk\";\ntype ChecklistItem = {id:string;label:string;done:boolean};\nimport { Alert, Button, Checkbox, Group, Stack, Text, TextInput } from \"@mantine/core\";\nimport { useWidgetCommands, useWidgetHost, useWidgetOptions, useWidgetState, useWidgetStorage } from \"@homarr/widget-sdk\";\nexport default function Checklist() {\n const host = useWidgetHost();\n const options = useWidgetOptions<{title:string;scope:WidgetStorageScope}>();\n const [draft, setDraft] = useWidgetState(\"draft\", \"\");\n const stored = useWidgetStorage<ChecklistItem[]>(options.scope, \"checklist-v1\", []);\n const items = Array.isArray(stored.data) ? stored.data : [];\n const locked = host.isEditMode || stored.isPending || stored.saving;\n const save = (value:ChecklistItem[]) => { void stored.set(value).catch(() => undefined); };\n useWidgetCommands([{ id: \"clear-completed\", label: \"Clear completed items\", disabled: locked || !items.some((item) => item.done), run: () => save(items.filter((item) => !item.done)) }]);\n const add = (event:FormEvent<HTMLFormElement>) => { event.preventDefault(); if (!draft.trim() || locked) return; save([...items, { id: crypto.randomUUID(), label: draft.trim(), done: false }]); setDraft(\"\"); };\n return <Stack p=\"md\" gap=\"sm\" h=\"100%\" style={{ overflow: \"auto\" }}>\n <Group justify=\"space-between\"><Text fw={600}>{options.title}</Text><Text size=\"sm\" c=\"dimmed\">{items.filter((item) => item.done).length}/{items.length}</Text></Group>\n {(stored.error || stored.saveError) && <Alert color=\"red\">{stored.error?.message ?? stored.saveError?.message}</Alert>}\n {items.map((item) => <Checkbox key={item.id} label={item.label} checked={item.done} disabled={locked} onChange={() => save(items.map((row) => row.id === item.id ? { ...row, done: !row.done } : row))} />)}\n {!items.length && !stored.isPending && <Text c=\"dimmed\" size=\"sm\">Add your first maintenance task.</Text>}\n <form onSubmit={add}><Group wrap=\"nowrap\"><TextInput aria-label=\"New task\" placeholder=\"New task\" value={draft} onChange={(event) => setDraft(event.currentTarget.value)} style={{ flex: 1 }} /><Button type=\"submit\" disabled={locked || !draft.trim()}>Add</Button></Group></form>\n {host.displayMode === \"advanced\" && <Text size=\"xs\" c=\"dimmed\">Changes are saved to Homarr. The selected storage scope controls whether this checklist belongs to you, this tile, or every placement of this installation.</Text>}\n </Stack>;\n}"
},
"dependencies": {},
"connections": {},
"options": {
"title": {
"control": "text",
"label": "Title",
"default": "Maintenance"
},
"scope": {
"control": "select",
"label": "Storage scope",
"default": "instance",
"choices": [
{
"label": "This tile",
"value": "instance"
},
{
"label": "My checklist",
"value": "user"
},
{
"label": "All installation placements",
"value": "installation"
}
]
}
}
}
+27
View File
@@ -0,0 +1,27 @@
{
"$schema": "homarr-widget-package-v3",
"manifest": {
"id": "homarr.reference.clock",
"version": "1.0.0",
"sdkVersion": "1",
"name": "Custom world clock",
"description": "A source-free clock with shared compact and advanced state.",
"entrypoints": {
"tile": "clock.tsx",
"advanced": "clock.tsx"
},
"handlers": {}
},
"files": {
"clock.tsx": "import { Button, Group, Stack, Text } from \"@mantine/core\";\nimport { useWidgetClock, useWidgetCommands, useWidgetHost, useWidgetOptions, useWidgetState } from \"@homarr/widget-sdk\";\n\nexport default function Clock() {\n const now = useWidgetClock();\n const host = useWidgetHost();\n const options = useWidgetOptions<{title:string}>();\n const [showSeconds, setShowSeconds] = useWidgetState(\"showSeconds\", true);\n useWidgetCommands([{ id: \"seconds\", label: \"Toggle seconds\", run: () => setShowSeconds((value) => !value) }]);\n const zones = [host.timeZone, \"UTC\", \"America/New_York\", \"Asia/Tokyo\"];\n const time = (zone:string) => {\n if (now === null) return \"—\";\n return new Intl.DateTimeFormat(host.locale, { timeZone: zone, hour: \"2-digit\", minute: \"2-digit\", ...(showSeconds ? { second: \"2-digit\" } : {}) }).format(now);\n };\n return <Stack h=\"100%\" justify=\"center\" gap=\"sm\" p=\"md\">\n <Text size=\"sm\" c=\"dimmed\">{options.title}</Text>\n <Text size={host.displayMode === \"advanced\" ? \"3rem\" : \"2rem\"} fw={700}>{time(host.timeZone)}</Text>\n {host.displayMode === \"advanced\" && zones.filter((zone, index) => zones.indexOf(zone) === index).map((zone) =>\n <Group key={zone} justify=\"space-between\"><Text>{zone}</Text><Text ff=\"monospace\">{time(zone)}</Text></Group>\n )}\n <Button size=\"compact-xs\" variant=\"subtle\" onClick={() => setShowSeconds((value) => !value)}>Toggle seconds</Button>\n </Stack>;\n}\n"
},
"dependencies": {},
"connections": {},
"options": {
"title": {
"control": "text",
"label": "Title",
"default": "Local time"
}
}
}
+143
View File
@@ -0,0 +1,143 @@
{
"$schema": "homarr-widget-package-v3",
"manifest": {
"id": "homarr.reference.downloads",
"version": "1.0.0",
"sdkVersion": "1",
"name": "Unified downloads",
"description": "Two independent torrent or Usenet clients with attributable queues, source-specific actions, partial batch results and guest-aware controls.",
"entrypoints": {
"tile": "widget.tsx",
"advanced": "widget.tsx",
"server": "server.ts"
},
"handlers": {
"queue": {
"kind": "query",
"permission": "view",
"inputSchema": {
"type": "object",
"additionalProperties": false,
"required": [
"connection"
],
"properties": {
"connection": {
"type": "string",
"enum": [
"client",
"secondary"
]
}
}
}
},
"control": {
"kind": "action",
"permission": "modify",
"inputSchema": {
"type": "object",
"additionalProperties": false,
"required": [
"connection",
"operation"
],
"properties": {
"connection": {
"type": "string",
"enum": [
"client",
"secondary"
]
},
"operation": {
"type": "string",
"enum": [
"pause",
"resume",
"pauseItem",
"resumeItem",
"deleteItem"
]
},
"itemId": {
"type": "string",
"minLength": 1
}
}
},
"guestAccess": true
},
"sources": {
"kind": "query",
"permission": "view"
},
"controlBatch": {
"kind": "action",
"permission": "modify",
"guestAccess": true,
"inputSchema": {
"type": "object",
"additionalProperties": false,
"required": [
"connections",
"operation"
],
"properties": {
"connections": {
"type": "array",
"minItems": 1,
"maxItems": 2,
"uniqueItems": true,
"items": {
"type": "string",
"enum": [
"client",
"secondary"
]
}
},
"operation": {
"type": "string",
"enum": [
"pause",
"resume"
]
}
}
}
}
}
},
"files": {
"server.ts": "import type { BatchControl, BatchResult, ControlResult, DownloadConnection, DownloadControl, DownloadQueue, DownloadSource, SourceQueue } from \"./download-types\";\nimport type { WidgetServerContext } from \"@homarr/widget-sdk/server\";\nimport { callWidgetIntegration, defineWidgetServer, getWidgetServerContext } from \"@homarr/widget-sdk/server\";\n\nconst declared:DownloadConnection[] = [\"client\",\"secondary\"];\nconst allowed = new Set([\"pause\",\"resume\",\"pauseItem\",\"resumeItem\",\"deleteItem\"]);\nasync function sources(context:WidgetServerContext):Promise<DownloadSource[]> {\n const {bindingNames,options} = await getWidgetServerContext(context);\n return declared.filter((connection) => bindingNames.includes(connection)).map((connection) => {\n let label = options.primaryLabel;\n if (connection === \"secondary\") label = options.secondaryLabel;\n if (typeof label !== \"string\" || !label.trim()) label = connection === \"client\" ? \"Primary client\" : \"Second client\";\n return {connection,label:String(label)};\n });\n}\nasync function source(context:WidgetServerContext,connection:DownloadConnection) {\n const result = (await sources(context)).find((candidate) => candidate.connection === connection);\n if (!result) throw new Error(\"Choose a declared, bound download client\");\n return result;\n}\nasync function queue(context:WidgetServerContext,connection:DownloadConnection):Promise<SourceQueue> {\n const selected = await source(context,connection);\n const result = await callWidgetIntegration<DownloadQueue>(context,{connection,capability:\"downloads.queue\",input:{limit:100}});\n return {...selected,data:result.data};\n}\nasync function control(context:WidgetServerContext,input:DownloadControl):Promise<ControlResult> {\n if (!allowed.has(input?.operation)) throw new Error(\"Unknown download operation\");\n await source(context,input.connection);\n if (input.operation === \"pause\" || input.operation === \"resume\") {\n await callWidgetIntegration(context,{connection:input.connection,capability:`downloads.${input.operation}`,input:{}});\n } else {\n if (typeof input.itemId !== \"string\" || !input.itemId) throw new Error(\"Choose a download from this client\");\n const current = await queue(context,input.connection);\n const item = current.data.items.find((candidate) => candidate.id === input.itemId);\n if (!item) throw new Error(\"The download is no longer in this client's queue; refresh and try again\");\n // Resolve the canonical item in the selected client. Never trust a browser-supplied client index or item object.\n await callWidgetIntegration(context,{connection:input.connection,capability:`downloads.${input.operation}`,input:{item,fromDisk:false}});\n }\n return {connection:input.connection,operation:input.operation,ok:true};\n}\nexport default defineWidgetServer({\n sources: (_input:unknown,context) => sources(context),\n queue: (input:{connection:DownloadConnection},context) => queue(context,input.connection),\n control: (input:DownloadControl,context) => control(context,input),\n controlBatch: async (input:BatchControl,context):Promise<BatchResult> => {\n if (![\"pause\",\"resume\"].includes(input?.operation)) throw new Error(\"Batch actions support pause or resume only\");\n if (!Array.isArray(input.connections) || !input.connections.length || input.connections.length > 2 || new Set(input.connections).size !== input.connections.length)\n throw new Error(\"Choose one or two different download clients\");\n const available = await sources(context);\n if (input.connections.some((connection) => !available.some((candidate) => candidate.connection === connection)))\n throw new Error(\"Every batch target must be a declared, bound client\");\n const results = await Promise.all(input.connections.map(async (connection):Promise<ControlResult> => {\n try { return await control(context,{connection,operation:input.operation}); }\n catch (error) { return {connection,operation:input.operation,ok:false,error:error instanceof Error ? error.message : String(error)}; }\n }));\n const succeeded = results.filter((result) => result.ok).length;\n return {results,succeeded,failed:results.length-succeeded};\n },\n});\n",
"download-source.tsx": "import type { DownloadControl, DownloadItem, DownloadSource, SourceQueue, ControlResult } from \"./download-types\";\nimport { Alert, Badge, Button, Group, Progress, Stack, Text } from \"@mantine/core\";\nimport { useWidgetAction, useWidgetCapabilities, useWidgetHost, useWidgetQuery, useWidgetServices } from \"@homarr/widget-sdk\";\nconst rate = (value:number|undefined) => `${((value ?? 0)/1048576).toFixed(1)} MiB/s`;\nexport function DownloadSourceRegion({source,filter,sort}:{source:DownloadSource;filter:string;sort:string}) {\n const host = useWidgetHost();\n const services = useWidgetServices();\n const capabilities = useWidgetCapabilities();\n const query = useWidgetQuery<SourceQueue>(\"queue\",{connection:source.connection},{refetchInterval:10000});\n const action = useWidgetAction<ControlResult,DownloadControl>(\"control\");\n const status = query.data?.data.status;\n const error = query.error ?? action.error;\n const run = (input:DownloadControl) => {void action.mutateAsync(input).catch(() => undefined);};\n const canRun = (input:DownloadControl) => !host.isEditMode && !action.isPending && capabilities.canRun(\"control\",input);\n const remove = async (item:DownloadItem) => {\n const input:DownloadControl = {connection:source.connection,operation:\"deleteItem\",itemId:item.id};\n if (!canRun(input)) return;\n if (await services.confirm({title:\"Remove download\",message:`Remove ${item.name} from ${source.label}? Downloaded files will be kept.`,destructive:true})) run(input);\n };\n const rows = query.data?.data.items ?? [];\n let items = rows.filter((item) => item.name.toLocaleLowerCase().includes(filter.toLocaleLowerCase()));\n if (sort === \"progress\") items = items.toSorted((a,b) => b.progress-a.progress);\n if (sort === \"name\") items = items.toSorted((a,b) => a.name.localeCompare(b.name));\n if (host.displayMode === \"compact\") items = items.slice(0,3);\n const pause:DownloadControl = {connection:source.connection,operation:\"pause\"};\n const resume:DownloadControl = {connection:source.connection,operation:\"resume\"};\n return <Stack gap=\"xs\" component=\"section\" aria-label={source.label} style={{border:\"1px solid var(--mantine-color-default-border)\",borderRadius:8,padding:10}}>\n <Group justify=\"space-between\"><Text size=\"sm\" fw={600}>{source.label} \u00b7 {rows.length}</Text>{status && <Badge color={status.paused ? \"yellow\" : \"blue\"}>{status.paused ? \"Paused\" : rate(status.rates.down)}</Badge>}</Group>\n {error && <Alert color=\"yellow\" title={source.label}>{error.message}<Button size=\"compact-xs\" variant=\"subtle\" onClick={() => {action.reset();void query.refetch();}}>Retry this client</Button></Alert>}\n {action.isPending && <Text size=\"xs\" c=\"dimmed\" role=\"status\">Updating this client\u2026</Text>}\n {query.isPending && <Text size=\"xs\" c=\"dimmed\">Loading this client's queue\u2026</Text>}\n {host.displayMode === \"advanced\" && <Group gap=\"xs\"><Button size=\"compact-xs\" variant=\"light\" disabled={!canRun(pause)} onClick={() => run(pause)}>Pause this client</Button><Button size=\"compact-xs\" variant=\"light\" disabled={!canRun(resume)} onClick={() => run(resume)}>Resume this client</Button></Group>}\n {items.map((item) => {\n const toggle:DownloadControl = {connection:source.connection,operation:item.state === \"paused\" ? \"resumeItem\" : \"pauseItem\",itemId:item.id};\n const deletion:DownloadControl = {connection:source.connection,operation:\"deleteItem\",itemId:item.id};\n return <Stack key={`${source.connection}:${item.id}`} gap={4}>\n <Group justify=\"space-between\" wrap=\"nowrap\"><Text size=\"sm\" truncate>{item.name}</Text><Badge size=\"xs\">{item.state}</Badge></Group>\n <Progress aria-label={`${source.label}: ${item.name} progress`} value={item.progress*100} />\n <Group justify=\"space-between\"><Text size=\"xs\" c=\"dimmed\">{Math.round(item.progress*100)}% \u00b7 {rate(item.downSpeed)}</Text>{host.displayMode === \"advanced\" && <Group gap=\"xs\"><Button size=\"compact-xs\" variant=\"subtle\" disabled={!canRun(toggle)} onClick={() => run(toggle)}>{item.state === \"paused\" ? \"Resume\" : \"Pause\"}</Button><Button size=\"compact-xs\" color=\"red\" variant=\"subtle\" disabled={!canRun(deletion)} onClick={() => void remove(item)}>Remove</Button></Group>}</Group>\n </Stack>;\n })}\n {!query.isPending && !query.error && items.length === 0 && <Text size=\"xs\" c=\"dimmed\">No downloads match this client view.</Text>}\n {action.data?.ok && <Text size=\"xs\" c=\"green\">{source.label}: {action.data.operation} completed</Text>}\n </Stack>;\n}\n",
"download-types.ts": "export type DownloadConnection = \"client\" | \"secondary\";\nexport type DownloadOperation = \"pause\" | \"resume\" | \"pauseItem\" | \"resumeItem\" | \"deleteItem\";\nexport interface DownloadItem {\n id:string;name:string;state:string;progress:number;downSpeed?:number;\n index:number;type:\"torrent\"|\"usenet\"|\"miscellaneous\";size:number;time:number;\n}\nexport interface DownloadQueue {data:{items:DownloadItem[];status:{paused:boolean;rates:{down:number;up?:number}}}}\nexport interface DownloadSource {connection:DownloadConnection;label:string}\nexport interface SourceQueue extends DownloadSource {data:DownloadQueue[\"data\"]}\nexport interface DownloadControl {connection:DownloadConnection;operation:DownloadOperation;itemId?:string}\nexport interface BatchControl {connections:DownloadConnection[];operation:\"pause\"|\"resume\"}\nexport interface ControlResult {connection:DownloadConnection;operation:DownloadOperation;ok:boolean;error?:string}\nexport interface BatchResult {results:ControlResult[];succeeded:number;failed:number}\nexport interface DownloadOptions {primaryLabel:string;secondaryLabel:string}\n",
"widget.tsx": "import type { BatchControl, BatchResult, DownloadConnection, DownloadSource } from \"./download-types\";\nimport { Alert, Button, Group, MultiSelect, Select, Stack, Text, TextInput } from \"@mantine/core\";\nimport { useWidgetAction, useWidgetCapabilities, useWidgetCommands, useWidgetHost, useWidgetQuery, useWidgetState } from \"@homarr/widget-sdk\";\nimport { DownloadSourceRegion } from \"./download-source\";\nexport default function Downloads() {\n const host = useWidgetHost();\n const sources = useWidgetQuery<DownloadSource[]>(\"sources\",{}, {staleTime:60000});\n const capabilities = useWidgetCapabilities();\n const batch = useWidgetAction<BatchResult,BatchControl>(\"controlBatch\");\n const [filter,setFilter] = useWidgetState(\"filter\",\"\");\n const [sort,setSort] = useWidgetState(\"sort\",\"queue\");\n const [selection,setSelection] = useWidgetState<DownloadConnection[]>(\"batch-clients\",[]);\n const available = sources.data ?? [];\n const targets = selection.filter((name) => available.some((source) => source.connection === name));\n const all = available.map((source) => source.connection);\n const canRun = (input:BatchControl) => input.connections.length > 0 && !host.isEditMode && !batch.isPending && capabilities.canRun(\"controlBatch\",input);\n const run = (input:BatchControl) => {void batch.mutateAsync(input).catch(() => undefined);};\n const pauseAll:BatchControl = {connections:all,operation:\"pause\"};\n const resumeAll:BatchControl = {connections:all,operation:\"resume\"};\n const pauseSelected:BatchControl = {connections:targets,operation:\"pause\"};\n const resumeSelected:BatchControl = {connections:targets,operation:\"resume\"};\n useWidgetCommands([{id:\"pause-all\",label:\"Pause all download clients\",disabled:!canRun(pauseAll),run:() => run(pauseAll)},{id:\"resume-all\",label:\"Resume all download clients\",disabled:!canRun(resumeAll),run:() => run(resumeAll)}]);\n return <Stack p=\"sm\" gap=\"sm\" h=\"100%\" style={{overflow:\"auto\"}}>\n <Text fw={600}>Downloads \u00b7 {available.length} clients</Text>\n {sources.error && <Alert color=\"red\">{sources.error.message}<Button size=\"xs\" variant=\"subtle\" onClick={() => void sources.refetch()}>Retry setup</Button></Alert>}\n {host.displayMode === \"advanced\" && <>\n <Group><TextInput label=\"Filter downloads\" value={filter} onChange={(event) => setFilter(event.currentTarget.value)} /><Select label=\"Sort\" value={sort} onChange={(value) => setSort(value ?? \"queue\")} data={[{value:\"queue\",label:\"Queue\"},{value:\"progress\",label:\"Progress\"},{value:\"name\",label:\"Name\"}]} /></Group>\n <Group gap=\"xs\"><Button size=\"compact-xs\" disabled={!canRun(pauseAll)} onClick={() => run(pauseAll)}>Pause all clients</Button><Button size=\"compact-xs\" disabled={!canRun(resumeAll)} onClick={() => run(resumeAll)}>Resume all clients</Button></Group>\n {available.length > 1 && <Group align=\"end\"><MultiSelect label=\"Batch targets\" data={available.map((source) => ({value:source.connection,label:source.label}))} value={selection} onChange={(values) => setSelection(all.filter((connection) => values.includes(connection)))} /><Button size=\"compact-xs\" variant=\"light\" disabled={!canRun(pauseSelected)} onClick={() => run(pauseSelected)}>Pause selected</Button><Button size=\"compact-xs\" variant=\"light\" disabled={!canRun(resumeSelected)} onClick={() => run(resumeSelected)}>Resume selected</Button></Group>}\n </>}\n {batch.isPending && <Text size=\"xs\" c=\"dimmed\" role=\"status\">Updating selected clients\u2026</Text>}\n {batch.error && <Alert color=\"red\">{batch.error.message}</Alert>}\n {batch.data && <Alert color={batch.data.failed ? \"yellow\" : \"green\"} title={`${batch.data.succeeded} succeeded \u00b7 ${batch.data.failed} failed`}>\n {batch.data.results.map((result) => <Text size=\"xs\" key={result.connection}>{available.find((source) => source.connection === result.connection)?.label ?? result.connection}: {result.ok ? `${result.operation} completed` : result.error}</Text>)}\n </Alert>}\n {available.map((source) => <DownloadSourceRegion key={source.connection} source={source} filter={filter} sort={sort} />)}\n {!sources.isPending && !sources.error && available.length === 0 && <Text c=\"dimmed\">Bind a download client to get started.</Text>}\n </Stack>;\n}\n",
"README.md": "# Two download clients\n\nBind client and optionally secondary to existing Homarr download integrations. Set the two display labels in widget options. The tile renders independent queue queries and errors for each source; a failing or slow client does not hide its sibling. The same normalized native download capabilities support torrent and Usenet backends.\n\nEach per-item action includes the connection name and itemId. The server resolves the current item from that connection, preserving the native client index and never accepting a browser-provided item object. Removal asks for confirmation and keeps downloaded files. Per-source pause/resume work independently. Advanced view and commands can pause or resume all configured clients or selected targets. Every batch reports success/failure per client; failures do not roll back completed external actions. Retry only the failed client when needed.\n\nAll control buttons and commands consult useWidgetCapabilities. Guest controls remain disabled until the owner grants the named action and its exact source-qualified input. A narrow example grant is control with {\"connection\":\"secondary\",\"operation\":\"pause\"}. Batch grants explicitly name every target, for example controlBatch with {\"connections\":[\"client\",\"secondary\"],\"operation\":\"resume\"}. Changed bindings/code/resource options invalidate old grants. Native integration action permissions remain authoritative for signed-in users.\n\nFilters, sorting and target selection use shared SDK state across tile/advanced. Composed overview copies these modules and routes them through WidgetScope with the downloads. handler prefix.\n"
},
"dependencies": {},
"connections": {
"client": {
"kind": "integration",
"label": "Primary download client"
},
"secondary": {
"kind": "integration",
"label": "Second download client",
"optional": true
}
},
"options": {
"primaryLabel": {
"control": "text",
"label": "Primary client label",
"default": "Primary client"
},
"secondaryLabel": {
"control": "text",
"label": "Second client label",
"default": "Second client"
}
}
}
@@ -0,0 +1,64 @@
{
"$schema": "homarr-widget-package-v3",
"manifest": {
"id": "homarr.reference.household",
"version": "1.0.0",
"sdkVersion": "1",
"name": "Household controls",
"description": "A Home Assistant control panel with a live configuration surface, owner-bound credentials and confirmed device actions.",
"entrypoints": {
"tile": "widget.tsx",
"advanced": "widget.tsx",
"server": "server.ts",
"configuration": "configuration.tsx"
},
"handlers": {
"states": {
"kind": "query",
"permission": "view"
},
"toggle": {
"kind": "action",
"permission": "modify",
"inputSchema": {
"type": "object",
"additionalProperties": false,
"required": ["entityId"],
"properties": {
"entityId": {
"type": "string",
"pattern": "^(light|switch|input_boolean|fan)\\.[A-Za-z0-9_]+$"
}
}
},
"guestAccess": true
}
}
},
"files": {
"widget.tsx": "import type { HouseholdEntity, HouseholdOptions, ToggleInput } from \"./household-types\";\nimport { Alert, Badge, Button, Card, Group, SimpleGrid, Stack, Text } from \"@mantine/core\";\nimport { useWidgetAction, useWidgetCapabilities, useWidgetHost, useWidgetOptions, useWidgetQuery, useWidgetServices } from \"@homarr/widget-sdk\";\nexport default function Household() {\n const host = useWidgetHost();\n const options = useWidgetOptions<HouseholdOptions>();\n const services = useWidgetServices();\n const query = useWidgetQuery<HouseholdEntity[]>(\"states\", {}, {refetchInterval: 10000});\n const action = useWidgetAction<unknown, ToggleInput>(\"toggle\");\n const capabilities = useWidgetCapabilities();\n const error = query.error ?? action.error;\n const entities = Array.isArray(options.entities) ? options.entities : [];\n const rows = (query.data ?? []).filter((row) => entities.includes(row.entity_id));\n const toggle = async (row: HouseholdEntity) => { if (!await services.confirm({title:row.attributes.friendly_name ?? row.entity_id, message:`Toggle ${row.entity_id}?`})) return; await action.mutateAsync({entityId:row.entity_id}).catch(() => undefined); };\n return <Stack p=\"md\" h=\"100%\" style={{overflow:\"auto\"}}><Text fw={600}>{options.title}</Text>\n {error && <Alert color=\"red\">{error.message}<Button size=\"xs\" variant=\"subtle\" onClick={() => void query.refetch()}>Retry</Button></Alert>}\n <SimpleGrid cols={Math.max(1,Math.floor(host.visibleWidth / 180))}>{rows.map((row) => <Card key={row.entity_id} withBorder><Stack gap=\"xs\"><Text fw={500}>{row.attributes.friendly_name ?? row.entity_id}</Text><Group justify=\"space-between\"><Badge color={row.state === \"on\" ? \"teal\" : \"gray\"}>{row.state}</Badge><Button title={capabilities.canRun(\"toggle\", {entityId:row.entity_id}) ? undefined : \"Your dashboard permissions do not allow this control\"} size=\"compact-xs\" disabled={!capabilities.canRun(\"toggle\", {entityId:row.entity_id}) || action.isPending || ![\"on\",\"off\"].includes(row.state)} onClick={() => void toggle(row)}>Toggle</Button></Group>{host.displayMode === \"advanced\" && <Text size=\"xs\" c=\"dimmed\">Changed {new Date(row.last_changed).toLocaleString(host.locale)}</Text>}</Stack></Card>)}</SimpleGrid>\n {!entities.length && <Text c=\"dimmed\">Choose your lights and switches in the configuration preview.</Text>}\n </Stack>;\n}",
"server.ts": "import type { WidgetServerContext } from \"@homarr/widget-sdk/server\";\nimport type { HouseholdEntity, HouseholdOptions, ToggleInput } from \"./household-types\";\nimport { defineWidgetServer, fetchWidgetConnection, getWidgetServerContext } from \"@homarr/widget-sdk/server\";\nconst states = async (context: WidgetServerContext) => { const result = await fetchWidgetConnection<HouseholdEntity[]>(context, {connection:\"homeassistant\",path:\"/api/states\"}); if (!result.ok) throw new Error(`Home Assistant returned HTTP ${result.status}`); return result.data; };\nexport default defineWidgetServer({\n states: (_input: unknown, context) => states(context),\n toggle: async (input: ToggleInput, context) => {\n const {options} = await getWidgetServerContext<HouseholdOptions>(context);\n if (!Array.isArray(options.entities) || !options.entities.includes(input?.entityId)) throw new Error(\"Choose this entity in the widget configuration first\");\n const domain = input.entityId.split(\".\")[0] ?? \"\";\n if (![\"light\",\"switch\",\"input_boolean\",\"fan\"].includes(domain)) throw new Error(\"This entity does not support the toggle operation\");\n const result = await fetchWidgetConnection(context, {connection:\"homeassistant\",path:`/api/services/${domain}/toggle`,method:\"POST\",body:{entity_id:input.entityId}});\n if (!result.ok) throw new Error(`Home Assistant returned HTTP ${result.status}`);\n return result.data;\n },\n});",
"configuration.tsx": "import type { HouseholdEntity, HouseholdOptions } from \"./household-types\";\nimport { Alert, Button, MultiSelect, Stack, TextInput } from \"@mantine/core\";\nimport { useWidgetOptions, useWidgetQuery, useWidgetServices, useWidgetState } from \"@homarr/widget-sdk\";\nexport default function Configuration() {\n const options = useWidgetOptions<HouseholdOptions>();\n const services = useWidgetServices();\n const [title, setTitle] = useWidgetState(\"configuration-title\", options.title);\n const [entities, setEntities] = useWidgetState(\"configuration-entities\", options.entities);\n const [error, setError] = useWidgetState(\"configuration-error\", \"\");\n const query = useWidgetQuery<HouseholdEntity[]>(\"states\");\n const choices = (query.data ?? []).filter((row) => /^(light|switch|input_boolean|fan)\\./.test(row.entity_id)).map((row) => ({value:row.entity_id,label:row.attributes.friendly_name ?? row.entity_id}));\n const save = async () => { try { await services.updateOptions({...options,title,entities}); setError(\"\"); } catch (error) { setError(error instanceof Error ? error.message : String(error)); } };\n return <Stack p=\"md\">{query.error && <Alert color=\"red\">{query.error.message}</Alert>}{error && <Alert color=\"red\">{error}</Alert>}<TextInput label=\"Panel title\" value={title} onChange={(event) => setTitle(event.currentTarget.value)} /><MultiSelect label=\"Lights and switches\" searchable data={choices} value={entities} onChange={setEntities} /><Button onClick={() => void save()}>Use these options</Button></Stack>;\n}",
"household-types.ts": "export interface HouseholdOptions extends Record<string, unknown> { title: string; entities: string[] }\nexport interface HouseholdEntity { entity_id: string; state: string; last_changed: string; attributes: { friendly_name?: string } }\nexport interface ToggleInput { entityId: string }\n"
},
"dependencies": {},
"connections": {
"homeassistant": {
"kind": "http",
"label": "Home Assistant",
"description": "Use the Home Assistant base URL and bearer token authentication."
}
},
"options": {
"title": {
"control": "text",
"label": "Title",
"default": "Home"
},
"entities": {
"control": "json",
"label": "Entity IDs",
"default": []
}
}
}
+107
View File
@@ -0,0 +1,107 @@
{
"$schema": "homarr-widget-package-v3",
"manifest": {
"id": "homarr.reference.media",
"version": "1.1.0",
"sdkVersion": "1",
"name": "Media and camera wall",
"description": "Native playing sessions plus optional authenticated camera snapshots and an Immich gallery, with responsive tiles and shared advanced image selection.",
"entrypoints": {
"tile": "widget.tsx",
"advanced": "widget.tsx",
"server": "server.ts"
},
"handlers": {
"sessions": {
"kind": "query",
"permission": "view"
},
"gallery": {
"kind": "query",
"permission": "view"
},
"image": {
"kind": "query",
"permission": "view",
"inputSchema": {
"type": "object",
"required": ["kind", "id"],
"properties": {
"kind": {
"enum": ["camera", "immich"]
},
"id": {
"type": "string",
"maxLength": 128
}
},
"additionalProperties": false
}
}
}
},
"files": {
"widget.tsx": "import type { MediaOptions, GalleryItem } from \"./types\";\nimport { Alert, Badge, Button, Card, Group, Image, Loader, SimpleGrid, Stack, Text, UnstyledButton } from \"@mantine/core\";\nimport { useWidgetHost, useWidgetOptions, useWidgetQuery, useWidgetServices, useWidgetState } from \"@homarr/widget-sdk\";\nimport Sessions from \"./sessions\";\nexport default function MediaWall() {\n const host = useWidgetHost(); const options = useWidgetOptions<MediaOptions>(); const services = useWidgetServices();\n const [selected,setSelected] = useWidgetState<GalleryItem|null>(\"selectedImage\",null);\n const gallery = useWidgetQuery<{items:GalleryItem[];errors:string[];configured:boolean}>(\"gallery\",{}, {refetchInterval:60000});\n const columns = Math.max(1,Math.floor(host.visibleWidth/220));\n return <Stack p=\"sm\" h=\"100%\" gap=\"sm\" style={{overflow:\"auto\"}}>\n <Group justify=\"space-between\"><Text fw={600}>{options.title}</Text><Button size=\"compact-xs\" variant=\"subtle\" onClick={() => void gallery.refetch()}>Refresh gallery</Button></Group>\n {gallery.error && <Alert color=\"red\">{gallery.error.message}</Alert>}\n {(gallery.data?.errors ?? []).map((error,index) => <Alert key={index} color=\"yellow\">{error}</Alert>)}\n {host.displayMode === \"advanced\" && selected && <Card withBorder><Stack gap=\"xs\"><Group justify=\"space-between\"><Text fw={600}>{selected.name}</Text><Button size=\"compact-xs\" variant=\"subtle\" onClick={() => setSelected(null)}>Close image</Button></Group><Snapshot item={selected} large /></Stack></Card>}\n <SimpleGrid cols={columns}>{(gallery.data?.items ?? []).map((item) => <Card key={`${item.kind}:${item.id}`} withBorder p=\"xs\"><UnstyledButton onClick={() => {setSelected(item);services.openAdvanced();}}><Stack gap={4}><Snapshot item={item} /><Group justify=\"space-between\"><Text size=\"sm\">{item.name}</Text><Badge size=\"xs\" variant=\"light\">{item.kind}</Badge></Group>{item.takenAt && <Text size=\"xs\" c=\"dimmed\">{new Date(item.takenAt).toLocaleDateString(host.locale)}</Text>}</Stack></UnstyledButton></Card>)}</SimpleGrid>\n {gallery.data && !gallery.data.configured && <Text size=\"sm\" c=\"dimmed\">Bind a camera or Immich connection to add authenticated images.</Text>}\n {gallery.data?.configured && !gallery.data.items.length && <Text size=\"sm\" c=\"dimmed\">No configured snapshots or matching Immich images.</Text>}\n {options.showSessions && <Sessions />}\n </Stack>;\n}\nfunction Snapshot({item,large=false}:{item:GalleryItem;large?:boolean}) {\n const options = useWidgetOptions<MediaOptions>();\n const image = useWidgetQuery<{dataUrl:string;updatedAt:string}>(\"image\",{kind:item.kind,id:item.id},{refetchInterval:item.kind === \"camera\" ? Math.max(5,Number(options.snapshotInterval)||15)*1000 : 300000,staleTime:5000});\n if (image.isPending) return <Stack h={160} justify=\"center\" align=\"center\"><Loader size=\"sm\" /></Stack>;\n if (image.error) return <Alert color=\"yellow\">{image.error.message}</Alert>;\n return <Image src={image.data?.dataUrl} alt={item.name} h={large ? 420 : 160} fit={large ? \"contain\" : \"cover\"} radius=\"sm\" />;\n}\n",
"server.ts": "import type { Camera, MediaOptions, GalleryItem, GalleryImageInput, ImmichAsset, MediaSessions } from \"./types\";\nimport { callWidgetIntegration, defineWidgetServer, fetchWidgetConnection, getWidgetServerContext } from \"@homarr/widget-sdk/server\";\nconst cameras = (options:MediaOptions):Camera[] => Array.isArray(options.cameras) ? options.cameras.slice(0,8).filter((item) => item && typeof item.name === \"string\" && typeof item.path === \"string\") : [];\nexport default defineWidgetServer({\n sessions: async (_input,context) => {\n const {bindingNames} = await getWidgetServerContext<MediaOptions>(context);\n if (!bindingNames.includes(\"media\")) return {data:[],configured:false};\n return callWidgetIntegration<MediaSessions>(context,{connection:\"media\",capability:\"media.sessions\",input:{showOnlyPlaying:false}});\n },\n gallery: async (_input,context) => {\n const {bindingNames,options} = await getWidgetServerContext<MediaOptions>(context);\n const items:GalleryItem[] = []; const errors:string[] = [];\n if (bindingNames.includes(\"camera\")) items.push(...cameras(options).map<GalleryItem>((camera,index) => ({kind:\"camera\",id:String(index),name:camera.name})));\n if (bindingNames.includes(\"immich\")) {\n try {\n const response = await fetchWidgetConnection<{assets?:{items?:ImmichAsset[]}}>(context,{connection:\"immich\",path:\"/api/search/metadata\",method:\"POST\",body:{type:\"IMAGE\",size:Math.max(1,Math.min(12,Number(options.imageCount)||8))}});\n if (!response.ok) throw new Error(`Immich returned HTTP ${response.status}`);\n const assets = response.data?.assets?.items;\n if (!Array.isArray(assets)) throw new Error(\"Immich search returned an unexpected result\");\n items.push(...assets.slice(0,12).map<GalleryItem>((asset) => ({kind:\"immich\",id:asset.id,name:asset.originalFileName ?? \"Photo\",takenAt:asset.localDateTime ?? asset.fileCreatedAt})));\n } catch (error) { errors.push(error instanceof Error ? error.message : String(error)); }\n }\n return {items,errors,configured:bindingNames.includes(\"camera\") || bindingNames.includes(\"immich\")};\n },\n image: async (input:GalleryImageInput,context) => {\n const {options,bindingNames} = await getWidgetServerContext<MediaOptions>(context);\n let path; let connection;\n if (input?.kind === \"camera\") {\n const camera = cameras(options).find((_camera,index) => String(index) === input.id);\n if (!camera) throw new Error(\"Choose a configured camera snapshot\");\n path = camera.path; connection = \"camera\";\n } else if (input?.kind === \"immich\" && typeof input.id === \"string\" && /^[0-9a-f-]{36}$/i.test(input.id)) {\n path = `/api/assets/${encodeURIComponent(input.id)}/thumbnail?size=thumbnail`; connection = \"immich\";\n } else throw new Error(\"Unknown gallery image\");\n if (!bindingNames.includes(connection)) throw new Error(\"The image connection is not bound\");\n const response = await fetchWidgetConnection(context,{connection,path,responseType:\"base64\"});\n if (!response.ok) throw new Error(`Image returned HTTP ${response.status}. Check the configured endpoint and image permissions.`);\n const mime = response.contentType?.split(\";\")[0]?.trim().toLowerCase() ?? \"\";\n if (![\"image/jpeg\",\"image/png\",\"image/webp\",\"image/gif\",\"image/avif\"].includes(mime)) throw new Error(\"The endpoint must return a JPEG, PNG, WebP, GIF or AVIF snapshot\");\n if (typeof response.data !== \"string\" || response.data.length > 900000) throw new Error(\"Use a smaller snapshot or thumbnail (under 675 KiB)\");\n return {dataUrl:`data:${mime};base64,${response.data}`,updatedAt:response.updatedAt};\n },\n});\n",
"sessions.tsx": "import type { MediaSessions } from \"./types\";\nimport { Alert, Badge, Button, Card, Group, Progress, SimpleGrid, Stack, Text } from \"@mantine/core\";\nimport { useWidgetHost, useWidgetQuery, useWidgetServices } from \"@homarr/widget-sdk\";\nexport default function Sessions() {\n const host = useWidgetHost();\n const services = useWidgetServices();\n const query = useWidgetQuery<MediaSessions>(\"sessions\", {}, { refetchInterval: 10000 });\n const rows = query.data?.data ?? [];\n const columns = Math.max(1, Math.floor(host.visibleWidth / 240));\n return <Stack p=\"md\" style={{overflow:\"auto\"}}><Text fw={600}>Now playing · {rows.length}</Text>\n {query.error && <Alert color=\"red\">{query.error.message}<Button variant=\"subtle\" size=\"xs\" onClick={() => void query.refetch()}>Retry</Button></Alert>}\n <SimpleGrid cols={columns}>{rows.map((session) => { const playing = session.currentlyPlaying; const playback = playing?.playback; return <Card key={session.sessionId} withBorder padding=\"sm\"><Stack gap=\"xs\"><Group justify=\"space-between\"><Text size=\"sm\" fw={600}>{session.user.username}</Text><Badge size=\"xs\">{playback?.state ?? \"idle\"}</Badge></Group><Text>{playing?.name ?? session.sessionName}</Text>{playing?.episodeName && <Text size=\"xs\" c=\"dimmed\">{playing.episodeName}</Text>}{typeof playback?.durationMs === \"number\" && playback.durationMs > 0 && <Progress aria-label=\"Playback progress\" value={100 * (playback.positionMs ?? 0) / playback.durationMs} />}<Button size=\"compact-xs\" variant=\"light\" onClick={() => services.openDetail({title: session.sessionName, content: <Stack><Text>{session.user.username}</Text><Text>{playing?.name}</Text><Text size=\"sm\">{playing?.location ?? \"Unknown network\"} · {playing?.metadata?.bitrateKbps ?? \"Unknown\"} kbps</Text><Text size=\"sm\">Video direct: {String(playing?.metadata?.transcoding?.isVideoDirect ?? \"unknown\")}</Text><Text size=\"sm\">Audio direct: {String(playing?.metadata?.transcoding?.isAudioDirect ?? \"unknown\")}</Text></Stack>})}>Session details</Button></Stack></Card>; })}</SimpleGrid>\n {!query.isPending && !query.error && query.data?.configured !== false && rows.length === 0 && <Text c=\"dimmed\">No active media sessions.</Text>}\n {query.data?.configured === false && <Text c=\"dimmed\" size=\"sm\">Bind a media server integration to show now-playing sessions.</Text>}\n </Stack>;\n}",
"README.md": "# Media and camera wall\nAll connections are optional. Bind an existing Plex/Jellyfin/Emby-compatible integration for native now-playing sessions. Bind an HTTP camera snapshot server and configure up to eight name/path entries for authenticated JPEG/PNG/WebP/GIF/AVIF still images. This is snapshot polling, not RTSP or continuous video streaming.\n\nFor Immich, bind the server root URL and keep `x-api-key` in the local connection's secret headers. The key needs asset.read and asset.view. The package lists recent image assets through POST /api/search/metadata and retrieves each thumbnail through GET /api/assets/:id/thumbnail?size=thumbnail. Each image is fetched server-side; credentials are never sent to the browser. Each image is limited to 675 KiB before base64 encoding. If an endpoint redirects, configure a direct image endpoint supported by your service.\n\nTile and advanced views share the selected image. Clicking a thumbnail opens the advanced view; the media session panel retains playback progress and native session details. Images refresh independently, so one failed camera does not hide the others. The package does not promise lossless full-resolution originals or real-time video.\n\nOfficial API sources: https://github.com/immich-app/immich/blob/main/server/src/controllers/search.controller.ts and https://github.com/immich-app/immich/blob/main/server/src/controllers/asset-media.controller.ts\n",
"types.ts": "export type Camera = {name:string;path:string};\nexport type MediaOptions = {title:string;showSessions:boolean;cameras:Camera[];imageCount:number;snapshotInterval:number};\nexport interface GalleryItem {kind:\"camera\"|\"immich\";id:string;name:string;takenAt?:string;}\nexport type GalleryImageInput = Pick<GalleryItem,\"kind\"|\"id\">;\nexport interface ImmichAsset {id:string;originalFileName?:string;localDateTime?:string;fileCreatedAt?:string;}\nexport interface MediaSession {sessionId:string;sessionName:string;user:{username:string};currentlyPlaying:{name:string;episodeName?:string|null;location:\"lan\"|\"wan\"|null;playback:{state:\"playing\"|\"paused\"|\"buffering\"|null;positionMs:number|null;durationMs:number|null};metadata:{bitrateKbps:number|null;transcoding:{isVideoDirect:boolean;isAudioDirect:boolean}}|null}|null;}\nexport interface MediaSessions {data:MediaSession[];configured?:boolean;}\n"
},
"dependencies": {},
"connections": {
"media": {
"kind": "integration",
"label": "Media server",
"optional": true
},
"camera": {
"kind": "http",
"label": "Camera snapshot server",
"optional": true,
"description": "Basic, bearer or header authentication stays in this local connection."
},
"immich": {
"kind": "http",
"label": "Immich server",
"optional": true,
"description": "Use a secret x-api-key header with asset.read and asset.view permissions."
}
},
"options": {
"title": {
"control": "text",
"label": "Title",
"default": "Media wall"
},
"showSessions": {
"control": "switch",
"label": "Show media sessions",
"default": true
},
"cameras": {
"control": "json",
"label": "Camera snapshots",
"description": "Array of name/path objects on the camera connection. Up to eight snapshots. Paths stay on that connection’s origin.",
"default": [
{
"name": "Front door",
"path": "/snapshot.jpg"
}
]
},
"imageCount": {
"control": "number",
"label": "Immich image count",
"default": 8,
"min": 1,
"max": 12
},
"snapshotInterval": {
"control": "number",
"label": "Snapshot refresh seconds",
"default": 15,
"min": 5,
"max": 3600
}
}
}
+56
View File
@@ -0,0 +1,56 @@
{
"$schema": "homarr-widget-package-v3",
"manifest": {
"id": "homarr.reference.mqtt",
"version": "1.0.0",
"sdkVersion": "1",
"name": "MQTT live topics",
"description": "Live broker topics, retained values, recent message history and explicit owner-configured publishes.",
"entrypoints": {
"tile": "widget.tsx",
"advanced": "widget.tsx",
"server": "server.ts"
},
"handlers": {
"setup": {
"kind": "query",
"permission": "view"
},
"messages": {
"kind": "subscription",
"permission": "view"
},
"publish": {
"kind": "action",
"permission": "modify"
}
}
},
"files": {
"server.ts": "import type { BrokerMessage, BrokerEvent, PublishInput } from \"./mqtt-types\";\nimport type { WidgetJson } from \"@homarr/widget-sdk/server\";\nimport { defineWidgetServer } from \"@homarr/widget-sdk/server\";\nimport { brokerSettings, connectBroker } from \"./mqtt-adapter\";\n\nexport default defineWidgetServer({\n setup: async (_input,context) => {\n const {topics,publishTopics} = await brokerSettings(context);\n return {topics,publishTopics};\n },\n messages: async function* (_input,context):AsyncGenerator<BrokerEvent> {\n const configuration = await brokerSettings(context);\n const {client,close} = await connectBroker(context,configuration);\n const queue:BrokerMessage[] = [];\n let wake = () => {};\n let failure:Error|undefined;\n let dropped = 0;\n const onMessage = (topic:string,buffer:Buffer,packet:{retain:boolean}) => {\n const truncated = buffer.length > 65536;\n const text = buffer.subarray(0,65536).toString(\"utf8\");\n let payload:WidgetJson = text;\n try { payload = JSON.parse(text); } catch {}\n if (queue.length >= 64) {queue.shift();dropped++;}\n queue.push({kind:\"message\",topic,payload,truncated,retained:packet.retain,dropped,receivedAt:new Date().toISOString()});\n wake();\n };\n const onError = (error:Error) => {failure=error;wake();};\n const onClose = () => {if (!context.signal.aborted) onError(new Error(\"Broker connection closed; reconnect to resume\"));};\n const onAbort = () => wake();\n client.on(\"message\",onMessage);client.on(\"error\",onError);client.on(\"close\",onClose);\n context.signal.addEventListener(\"abort\",onAbort,{once:true});\n try {\n const grants = await client.subscribeAsync(configuration.topics,{qos:0});\n if (grants.some((grant) => grant.qos === 128)) throw new Error(\"The broker denied a configured topic subscription\");\n yield {kind:\"connected\",topics:configuration.topics,receivedAt:new Date().toISOString()};\n while (!context.signal.aborted) {\n if (failure) throw failure;\n if (queue.length) {yield queue.shift()!;continue;}\n await new Promise<void>((resolve) => {wake=resolve;if (context.signal.aborted || failure || queue.length) resolve();});\n }\n } finally {\n context.signal.removeEventListener(\"abort\",onAbort);\n client.off(\"message\",onMessage);client.off(\"error\",onError);client.off(\"close\",onClose);\n await close();\n }\n },\n publish: async (input:PublishInput,context) => {\n const configuration = await brokerSettings(context);\n if (!configuration.publishTopics.includes(input?.topic)) throw new Error(\"Choose an owner-configured publish topic\");\n if (typeof input.payload !== \"string\" || Buffer.byteLength(input.payload,\"utf8\") > 4096) throw new Error(\"The payload must be a string under 4 KiB\");\n const {client,close} = await connectBroker(context,configuration);\n try {\n await client.publishAsync(input.topic,input.payload,{qos:1,retain:false});\n return {published:true,topic:input.topic};\n } finally { await close(); }\n },\n});\n",
"mqtt-types.ts": "import type { WidgetJson } from \"@homarr/widget-sdk/server\";\nexport interface BrokerMessage {kind:\"message\";topic:string;payload:WidgetJson;truncated:boolean;retained:boolean;dropped:number;receivedAt:string}\nexport interface BrokerConnected {kind:\"connected\";topics:string[];receivedAt:string}\nexport type BrokerEvent = BrokerMessage | BrokerConnected;\nexport interface PublishInput {topic:string;payload:string}\n",
"mqtt.d.ts": "// Portable declarations for the exact MQTT.js 5.15.2 adapter API used here.\n// Draft checking does not fetch npm packages. Runtime code still comes from the pinned dependency.\ndeclare module \"mqtt/lib/client\" {\n import { EventEmitter } from \"node:events\";\n import type { Duplex } from \"node:stream\";\n interface Options {clientId:string;username?:string;password?:string;reconnectPeriod:number;connectTimeout:number;clean:boolean;manualConnect:boolean;log:(...values:unknown[])=>void}\n export default class MqttClient extends EventEmitter {\n constructor(streamBuilder:()=>Duplex,options:Options);\n connect():this;\n end(force?:boolean):this;\n endAsync(force?:boolean):Promise<void>;\n subscribeAsync(topics:string[],options:{qos:0|1|2}):Promise<{qos:0|1|2|128}[]>;\n publishAsync(topic:string,payload:string,options:{qos:0|1|2;retain:boolean}):Promise<void>;\n }\n}\n",
"README.md": "# MQTT live topics\n\nCreate a Service connection with serviceType `mqtt`. Nonsecret settings:\n\n```json\n{\"url\":\"mqtt://mosquitto:1883\",\"topics\":[\"homelab/status/#\",\"sensors/+/temperature\"],\"publishTopics\":[\"homelab/commands/refresh\"]}\n```\n\nEncrypted credentials: {\"username\":\"homarr\",\"password\":\"YOUR_BROKER_PASSWORD\"}. The browser never receives credentials through SDK connection APIs. TLS brokers use mqtts://. This adapter uses MQTT.js\u2019s client constructor with Node TCP/TLS streams. Optional nonsecret settings ca/cert/rejectUnauthorized configure TLS; keep tlsKey in encrypted credentials. Use a distinct connection when broker or credential sets differ.\n\nThe server adapter opens an authenticated subscription only while observed, disables hidden reconnect loops and closes on cancellation, errors and worker shutdown. The host shares matching subscriptions across surfaces. The browser retains 64 recent events; the worker queue is bounded to 64 messages and each payload to 64 KiB. The tile shows latest topic values; advanced view shows recent messages and a nonretained publish action. Only explicit publishTopics accept publishes, with 4 KiB payloads and QoS 1. Clear publishTopics for a read-only dashboard. Broker permissions still apply. Public guest actions are off by default.\n\nDiagnose verifies TCP reachability for mqtt:// and mqtts://. Run preview to validate TLS, broker credentials and topic authorization; use reconnect after fixing the service. Enabling live SDK actions is required to actually publish from preview. No HTTP URL or proxy is involved. This package pins mqtt@5.15.2 and supports-color@8.1.1 (debug\u2019s optional JavaScript dependency); review and trust installs its dependency tree with lifecycle scripts disabled. Source: https://github.com/mqttjs/MQTT.js\n",
"mqtt-adapter.ts": "import type { WidgetServerContext } from \"@homarr/widget-sdk/server\";\ninterface LocalMqttSettings {url?:string;topics?:unknown[];publishTopics?:unknown[];ca?:string;cert?:string;rejectUnauthorized?:boolean}\nimport MqttClient from \"mqtt/lib/client\";\nimport { createConnection, isIP } from \"node:net\";\nimport { connect as connectTls } from \"node:tls\";\nimport { randomUUID } from \"node:crypto\";\nimport { getWidgetConnection } from \"@homarr/widget-sdk/server\";\n\nexport async function brokerSettings(context:WidgetServerContext) {\n const {configuration,secrets} = await getWidgetConnection<LocalMqttSettings>(context,{connection:\"broker\",serviceType:\"mqtt\"});\n const settings = configuration.settings ?? {};\n if (typeof settings.url !== \"string\") throw new Error(\"Set the MQTT service url, for example mqtt://mosquitto:1883\");\n const url = new URL(settings.url);\n if (![\"mqtt:\",\"mqtts:\"].includes(url.protocol)) throw new Error(\"Choose an mqtt:// or mqtts:// broker URL\");\n if (url.username || url.password) throw new Error(\"Put the broker username and password in encrypted credentials, not the URL\");\n const topics = Array.isArray(settings.topics) ? settings.topics.filter((topic):topic is string => typeof topic === \"string\" && topic.length > 0).slice(0,32) : [];\n if (!topics.length) throw new Error(\"Set a nonempty topics array on the broker connection\");\n const publishTopics = Array.isArray(settings.publishTopics) ? settings.publishTopics.filter((topic):topic is string => typeof topic === \"string\" && topic.length > 0 && !/[+#]/.test(topic)).slice(0,32) : [];\n return {settings:{...settings,url:settings.url},secrets,topics,publishTopics,timeoutMs:Math.min(configuration.timeoutMs,15000)};\n}\n\nexport async function connectBroker(context:WidgetServerContext,configuration:Awaited<ReturnType<typeof brokerSettings>>) {\n context.signal.throwIfAborted();\n const {settings,secrets,timeoutMs} = configuration;\n const url = new URL(settings.url);\n const hostname = url.hostname.replace(/^\\[|\\]$/g, \"\");\n let port = url.protocol === \"mqtts:\" ? 8883 : 1883;\n if (url.port) port = Number(url.port);\n const stream = () => {\n if (url.protocol !== \"mqtts:\") return createConnection({host:hostname,port});\n return connectTls({host:hostname,port,servername:isIP(hostname) ? undefined : hostname,ca:settings.ca,cert:settings.cert,key:secrets.tlsKey,rejectUnauthorized:settings.rejectUnauthorized !== false});\n };\n const client = new MqttClient(stream,{\n clientId:`homarr-${randomUUID()}`,\n username:secrets.username || undefined,\n password:secrets.password || undefined,\n reconnectPeriod:0,\n connectTimeout:timeoutMs,\n clean:true,\n manualConnect:true,\n log:() => {},\n });\n const ignoreError = () => {};\n client.on(\"error\",ignoreError);\n const stop = () => { client.end(true); };\n context.signal.addEventListener(\"abort\",stop,{once:true});\n const close = async () => {\n context.signal.removeEventListener(\"abort\",stop);\n await client.endAsync(true).catch(() => undefined);\n client.removeListener(\"error\",ignoreError);\n };\n try {\n await new Promise<void>((resolve,reject) => {\n const cleanup = () => {client.off(\"connect\",ready);client.off(\"error\",failed);client.off(\"close\",closed);};\n const ready = () => {cleanup();resolve();};\n const failed = (error:unknown) => {cleanup();reject(error);};\n const closed = () => failed(context.signal.reason ?? new Error(\"Broker connection closed before authentication completed\"));\n client.once(\"connect\",ready);client.once(\"error\",failed);client.once(\"close\",closed);\n if (context.signal.aborted) closed();\n else client.connect();\n });\n context.signal.throwIfAborted();\n return {client,close};\n } catch (error) { await close(); throw error; }\n}\n",
"widget.tsx": "import type server from \"./server\";\nimport type { BrokerEvent, BrokerMessage, PublishInput } from \"./mqtt-types\";\nimport { Alert, Badge, Button, Group, Select, Stack, Text, Textarea, TextInput } from \"@mantine/core\";\nimport { useWidgetAction, useWidgetCapabilities, useWidgetHost, useWidgetServices, useWidgetOptions, useWidgetQuery, useWidgetState, useWidgetSubscription } from \"@homarr/widget-sdk\";\n\nexport default function MqttWidget() {\n const host = useWidgetHost();\n const services = useWidgetServices();\n const options = useWidgetOptions<{title:string}>();\n const setup = useWidgetQuery<Awaited<ReturnType<typeof server.setup>>>(\"setup\",{}, {staleTime:60000});\n const stream = useWidgetSubscription<BrokerEvent>(\"messages\",{}, {maximumEvents:64});\n const publish = useWidgetAction<Awaited<ReturnType<typeof server.publish>>,PublishInput>(\"publish\");\n const capabilities = useWidgetCapabilities();\n const [filter,setFilter] = useWidgetState(\"filter\",\"\");\n const [topic,setTopic] = useWidgetState(\"publishTopic\",\"\");\n const [payload,setPayload] = useWidgetState(\"payload\",\"\");\n const events = stream.events.filter((event):event is BrokerMessage => event.kind === \"message\" && event.topic.includes(filter)).slice().reverse();\n const latest = [...new Map(events.map((event) => [event.topic,event] as const).reverse()).values()].reverse();\n let visible = latest.slice(0,8);\n if (host.displayMode === \"advanced\") visible = events;\n const input = {topic,payload};\n const error = setup.error || stream.error || publish.error;\n return <Stack h=\"100%\" p=\"sm\" gap=\"xs\">\n <Group justify=\"space-between\"><Text fw={600}>{options.title}</Text><Badge color={stream.connected ? \"green\" : \"gray\"}>{stream.connected ? \"Live\" : \"Disconnected\"}</Badge></Group>\n {error && <Alert color=\"red\">{error.message}<Button size=\"compact-xs\" variant=\"subtle\" onClick={() => stream.reconnect()}>Reconnect</Button></Alert>}\n <TextInput size=\"xs\" aria-label=\"Filter MQTT topics\" placeholder=\"Filter topics\" value={filter} onChange={(event) => setFilter(event.currentTarget.value)} />\n <Stack gap=\"xs\" style={{flex:1,minHeight:0,overflow:\"auto\"}}>\n {!visible.length && <Text size=\"sm\" c=\"dimmed\">Waiting for messages on {setup.data?.topics.join(\", \") || \"configured topics\"}. Retained broker messages appear immediately.</Text>}\n {visible.map((event,index) => <Stack key={`${event.topic}:${event.receivedAt}:${index}`} gap={2} style={{borderBottom:\"1px solid var(--mantine-color-default-border)\",paddingBottom:6}}>\n <Group justify=\"space-between\"><Text size=\"xs\" fw={600}>{event.topic}</Text>{event.retained && <Badge size=\"xs\" variant=\"light\">Retained</Badge>}</Group>\n <Text component=\"pre\" size=\"xs\" style={{whiteSpace:\"pre-wrap\",margin:0}}>{typeof event.payload === \"string\" ? event.payload : JSON.stringify(event.payload,null,2)}</Text>\n <Text size=\"xs\" c=\"dimmed\">{new Date(event.receivedAt).toLocaleTimeString(host.locale)}{event.truncated ? \" \u00b7 payload truncated\" : \"\"}{event.dropped ? ` \u00b7 ${event.dropped} buffered messages dropped` : \"\"}</Text>\n </Stack>)}\n </Stack>\n {host.displayMode !== \"advanced\" && <Button size=\"compact-xs\" variant=\"subtle\" onClick={() => services.openAdvanced()}>Open message history</Button>}\n {host.displayMode === \"advanced\" && (setup.data?.publishTopics.length ?? 0) > 0 && <Stack gap=\"xs\">\n <Select label=\"Publish topic\" data={setup.data?.publishTopics ?? []} value={topic || null} onChange={(value) => setTopic(value || \"\")} />\n <Textarea label=\"Message payload\" value={payload} onChange={(event) => setPayload(event.currentTarget.value)} maxLength={4096} />\n <Button disabled={!topic || !capabilities.canRun(\"publish\",input)} loading={publish.isPending} onClick={async () => {if (await services.confirm({title:\"Publish MQTT message\",message:`Send this payload to ${topic}?`})) await publish.mutateAsync(input).catch(() => undefined);}}>Publish once (not retained)</Button>\n {publish.data?.published && <Text size=\"xs\" c=\"green\">Published to {publish.data.topic}</Text>}\n </Stack>}\n </Stack>;\n}\n"
},
"dependencies": {
"mqtt": "5.15.2",
"supports-color": "8.1.1"
},
"connections": {
"broker": {
"kind": "service",
"serviceType": "mqtt",
"label": "MQTT broker",
"description": "Settings: url, topics, optional publishTopics. Put username/password in encrypted credentials."
}
},
"options": {
"title": {
"control": "text",
"label": "Title",
"default": "MQTT topics"
}
}
}
+167
View File
@@ -0,0 +1,167 @@
{
"$schema": "homarr-widget-package-v3",
"manifest": {
"id": "homarr.reference.overview",
"version": "1.0.0",
"sdkVersion": "1",
"name": "Composed homelab overview",
"description": "Three independently authored components share one rich tile using SDK scopes for isolated state, commands, storage and handler routing.",
"entrypoints": {
"tile": "widget.tsx",
"advanced": "widget.tsx",
"server": "server.ts"
},
"handlers": {
"rack.systems": {
"kind": "query",
"permission": "view"
},
"downloads.queue": {
"kind": "query",
"permission": "view",
"inputSchema": {
"type": "object",
"additionalProperties": false,
"required": [
"connection"
],
"properties": {
"connection": {
"type": "string",
"enum": [
"client",
"secondary"
]
}
}
}
},
"downloads.control": {
"kind": "action",
"permission": "modify",
"inputSchema": {
"type": "object",
"additionalProperties": false,
"required": [
"connection",
"operation"
],
"properties": {
"connection": {
"type": "string",
"enum": [
"client",
"secondary"
]
},
"operation": {
"type": "string",
"enum": [
"pause",
"resume",
"pauseItem",
"resumeItem",
"deleteItem"
]
},
"itemId": {
"type": "string",
"minLength": 1
}
}
},
"guestAccess": true
},
"media.sessions": {
"kind": "query",
"permission": "view"
},
"downloads.sources": {
"kind": "query",
"permission": "view"
},
"downloads.controlBatch": {
"kind": "action",
"permission": "modify",
"guestAccess": true,
"inputSchema": {
"type": "object",
"additionalProperties": false,
"required": [
"connections",
"operation"
],
"properties": {
"connections": {
"type": "array",
"minItems": 1,
"maxItems": 2,
"uniqueItems": true,
"items": {
"type": "string",
"enum": [
"client",
"secondary"
]
}
},
"operation": {
"type": "string",
"enum": [
"pause",
"resume"
]
}
}
}
}
}
},
"files": {
"downloads-server.ts": "import type { BatchControl, BatchResult, ControlResult, DownloadConnection, DownloadControl, DownloadQueue, DownloadSource, SourceQueue } from \"./download-types\";\nimport type { WidgetServerContext } from \"@homarr/widget-sdk/server\";\nimport { callWidgetIntegration, defineWidgetServer, getWidgetServerContext } from \"@homarr/widget-sdk/server\";\n\nconst declared:DownloadConnection[] = [\"client\",\"secondary\"];\nconst allowed = new Set([\"pause\",\"resume\",\"pauseItem\",\"resumeItem\",\"deleteItem\"]);\nasync function sources(context:WidgetServerContext):Promise<DownloadSource[]> {\n const {bindingNames,options} = await getWidgetServerContext(context);\n return declared.filter((connection) => bindingNames.includes(connection)).map((connection) => {\n let label = options.primaryLabel;\n if (connection === \"secondary\") label = options.secondaryLabel;\n if (typeof label !== \"string\" || !label.trim()) label = connection === \"client\" ? \"Primary client\" : \"Second client\";\n return {connection,label:String(label)};\n });\n}\nasync function source(context:WidgetServerContext,connection:DownloadConnection) {\n const result = (await sources(context)).find((candidate) => candidate.connection === connection);\n if (!result) throw new Error(\"Choose a declared, bound download client\");\n return result;\n}\nasync function queue(context:WidgetServerContext,connection:DownloadConnection):Promise<SourceQueue> {\n const selected = await source(context,connection);\n const result = await callWidgetIntegration<DownloadQueue>(context,{connection,capability:\"downloads.queue\",input:{limit:100}});\n return {...selected,data:result.data};\n}\nasync function control(context:WidgetServerContext,input:DownloadControl):Promise<ControlResult> {\n if (!allowed.has(input?.operation)) throw new Error(\"Unknown download operation\");\n await source(context,input.connection);\n if (input.operation === \"pause\" || input.operation === \"resume\") {\n await callWidgetIntegration(context,{connection:input.connection,capability:`downloads.${input.operation}`,input:{}});\n } else {\n if (typeof input.itemId !== \"string\" || !input.itemId) throw new Error(\"Choose a download from this client\");\n const current = await queue(context,input.connection);\n const item = current.data.items.find((candidate) => candidate.id === input.itemId);\n if (!item) throw new Error(\"The download is no longer in this client's queue; refresh and try again\");\n // Resolve the canonical item in the selected client. Never trust a browser-supplied client index or item object.\n await callWidgetIntegration(context,{connection:input.connection,capability:`downloads.${input.operation}`,input:{item,fromDisk:false}});\n }\n return {connection:input.connection,operation:input.operation,ok:true};\n}\nexport default defineWidgetServer({\n sources: (_input:unknown,context) => sources(context),\n queue: (input:{connection:DownloadConnection},context) => queue(context,input.connection),\n control: (input:DownloadControl,context) => control(context,input),\n controlBatch: async (input:BatchControl,context):Promise<BatchResult> => {\n if (![\"pause\",\"resume\"].includes(input?.operation)) throw new Error(\"Batch actions support pause or resume only\");\n if (!Array.isArray(input.connections) || !input.connections.length || input.connections.length > 2 || new Set(input.connections).size !== input.connections.length)\n throw new Error(\"Choose one or two different download clients\");\n const available = await sources(context);\n if (input.connections.some((connection) => !available.some((candidate) => candidate.connection === connection)))\n throw new Error(\"Every batch target must be a declared, bound client\");\n const results = await Promise.all(input.connections.map(async (connection):Promise<ControlResult> => {\n try { return await control(context,{connection,operation:input.operation}); }\n catch (error) { return {connection,operation:input.operation,ok:false,error:error instanceof Error ? error.message : String(error)}; }\n }));\n const succeeded = results.filter((result) => result.ok).length;\n return {results,succeeded,failed:results.length-succeeded};\n },\n});\n",
"rack-server.ts": "import type { NativeResult, SystemRow } from \"./beszel-types\";\nimport { callWidgetIntegration, defineWidgetServer } from \"@homarr/widget-sdk/server\";\nexport default defineWidgetServer({ systems: (_input, context) => callWidgetIntegration<NativeResult<SystemRow[]>>(context, {connection:\"beszel\",capability:\"beszel.systems\"}) });",
"server.ts": "import type { WidgetServerHandler } from \"@homarr/widget-sdk/server\";\nimport { defineWidgetServer } from \"@homarr/widget-sdk/server\";\nimport rack from \"./rack-server.ts\";\nimport downloads from \"./downloads-server.ts\";\nimport media from \"./media-server.ts\";\nconst prefix = (name:string, handlers:Record<string,WidgetServerHandler<never>>) => Object.fromEntries(Object.entries(handlers).map(([key, handler]) => [`${name}.${key}`, handler]));\nexport default defineWidgetServer({...prefix(\"rack\", rack), ...prefix(\"downloads\", downloads), ...prefix(\"media\", media)});",
"download-types.ts": "export type DownloadConnection = \"client\" | \"secondary\";\nexport type DownloadOperation = \"pause\" | \"resume\" | \"pauseItem\" | \"resumeItem\" | \"deleteItem\";\nexport interface DownloadItem {\n id:string;name:string;state:string;progress:number;downSpeed?:number;\n index:number;type:\"torrent\"|\"usenet\"|\"miscellaneous\";size:number;time:number;\n}\nexport interface DownloadQueue {data:{items:DownloadItem[];status:{paused:boolean;rates:{down:number;up?:number}}}}\nexport interface DownloadSource {connection:DownloadConnection;label:string}\nexport interface SourceQueue extends DownloadSource {data:DownloadQueue[\"data\"]}\nexport interface DownloadControl {connection:DownloadConnection;operation:DownloadOperation;itemId?:string}\nexport interface BatchControl {connections:DownloadConnection[];operation:\"pause\"|\"resume\"}\nexport interface ControlResult {connection:DownloadConnection;operation:DownloadOperation;ok:boolean;error?:string}\nexport interface BatchResult {results:ControlResult[];succeeded:number;failed:number}\nexport interface DownloadOptions {primaryLabel:string;secondaryLabel:string}\n",
"media.tsx": "import type { MediaSessions } from \"./media-types\";\nimport { Alert, Badge, Button, Card, Group, Progress, SimpleGrid, Stack, Text } from \"@mantine/core\";\nimport { useWidgetHost, useWidgetQuery, useWidgetServices } from \"@homarr/widget-sdk\";\nexport default function Sessions() {\n const host = useWidgetHost();\n const services = useWidgetServices();\n const query = useWidgetQuery<MediaSessions>(\"sessions\", {}, { refetchInterval: 10000 });\n const rows = query.data?.data ?? [];\n const columns = Math.max(1, Math.floor(host.visibleWidth / 240));\n return <Stack p=\"md\" style={{overflow:\"auto\"}}><Text fw={600}>Now playing \u00b7 {rows.length}</Text>\n {query.error && <Alert color=\"red\">{query.error.message}<Button variant=\"subtle\" size=\"xs\" onClick={() => void query.refetch()}>Retry</Button></Alert>}\n <SimpleGrid cols={columns}>{rows.map((session) => { const playing = session.currentlyPlaying; const playback = playing?.playback; return <Card key={session.sessionId} withBorder padding=\"sm\"><Stack gap=\"xs\"><Group justify=\"space-between\"><Text size=\"sm\" fw={600}>{session.user.username}</Text><Badge size=\"xs\">{playback?.state ?? \"idle\"}</Badge></Group><Text>{playing?.name ?? session.sessionName}</Text>{playing?.episodeName && <Text size=\"xs\" c=\"dimmed\">{playing.episodeName}</Text>}{typeof playback?.durationMs === \"number\" && playback.durationMs > 0 && <Progress aria-label=\"Playback progress\" value={100 * (playback.positionMs ?? 0) / playback.durationMs} />}<Button size=\"compact-xs\" variant=\"light\" onClick={() => services.openDetail({title: session.sessionName, content: <Stack><Text>{session.user.username}</Text><Text>{playing?.name}</Text><Text size=\"sm\">{playing?.location ?? \"Unknown network\"} \u00b7 {playing?.metadata?.bitrateKbps ?? \"Unknown\"} kbps</Text><Text size=\"sm\">Video direct: {String(playing?.metadata?.transcoding?.isVideoDirect ?? \"unknown\")}</Text><Text size=\"sm\">Audio direct: {String(playing?.metadata?.transcoding?.isAudioDirect ?? \"unknown\")}</Text></Stack>})}>Session details</Button></Stack></Card>; })}</SimpleGrid>\n {!query.isPending && !query.error && query.data?.configured !== false && rows.length === 0 && <Text c=\"dimmed\">No active media sessions.</Text>}\n {query.data?.configured === false && <Text c=\"dimmed\" size=\"sm\">Bind a media server integration to show now-playing sessions.</Text>}\n </Stack>;\n}",
"widget.tsx": "import { SimpleGrid } from \"@mantine/core\";\nimport { useWidgetHost, WidgetScope } from \"@homarr/widget-sdk\";\nimport Rack from \"./rack.tsx\";\nimport Downloads from \"./downloads.tsx\";\nimport Media from \"./media.tsx\";\nexport default function Overview() {\n const host = useWidgetHost();\n return <SimpleGrid cols={host.visibleWidth >= 900 ? 3 : 1} h=\"100%\" style={{overflow:\"auto\"}}>\n <WidgetScope name=\"rack\" handlerPrefix=\"rack.\"><Rack /></WidgetScope>\n <WidgetScope name=\"downloads\" handlerPrefix=\"downloads.\"><Downloads /></WidgetScope>\n <WidgetScope name=\"media\" handlerPrefix=\"media.\"><Media /></WidgetScope>\n </SimpleGrid>;\n}",
"media-types.ts": "export type Camera = {name:string;path:string};\nexport type MediaOptions = {title:string;showSessions:boolean;cameras:Camera[];imageCount:number;snapshotInterval:number};\nexport interface GalleryItem {kind:\"camera\"|\"immich\";id:string;name:string;takenAt?:string;}\nexport type GalleryImageInput = Pick<GalleryItem,\"kind\"|\"id\">;\nexport interface ImmichAsset {id:string;originalFileName?:string;localDateTime?:string;fileCreatedAt?:string;}\nexport interface MediaSession {sessionId:string;sessionName:string;user:{username:string};currentlyPlaying:{name:string;episodeName?:string|null;location:\"lan\"|\"wan\"|null;playback:{state:\"playing\"|\"paused\"|\"buffering\"|null;positionMs:number|null;durationMs:number|null};metadata:{bitrateKbps:number|null;transcoding:{isVideoDirect:boolean;isAudioDirect:boolean}}|null}|null;}\nexport interface MediaSessions {data:MediaSession[];configured?:boolean;}\n",
"media-server.ts": "import type { MediaSessions } from \"./media-types\";\nimport { callWidgetIntegration, defineWidgetServer } from \"@homarr/widget-sdk/server\";\nexport default defineWidgetServer({ sessions: (_input, context) => callWidgetIntegration<MediaSessions>(context, { connection: \"media\", capability: \"media.sessions\", input: {showOnlyPlaying: false} }) });",
"rack.tsx": "import type { SystemRow, NativeResult } from \"./beszel-types\";\nimport { Alert, Button, Group, Stack, Text } from \"@mantine/core\";\nimport { useWidgetHost, useWidgetQuery, useWidgetServices, useWidgetState } from \"@homarr/widget-sdk\";\nimport \"./rack.css\";\nexport default function Rack() {\n const host = useWidgetHost();\n const services = useWidgetServices();\n const query = useWidgetQuery<NativeResult<SystemRow[]>>(\"systems\", {}, {refetchInterval: 15000});\n const [selected, setSelected] = useWidgetState(\"selected\", \"\");\n const systems = query.data?.data ?? [];\n const rows = host.displayMode === \"advanced\" ? systems : systems.slice(0, 8);\n const inspect = (system:SystemRow) => { setSelected(system.id); services.openDetail({title: system.name, content: <Stack><Text>{system.hostname} \u00b7 {system.osName}</Text><Text>CPU: {system.cpu.toFixed(1)}% \u00b7 Memory: {system.memory.toFixed(1)}% \u00b7 Disk: {system.disk.toFixed(1)}%</Text><Text>{system.cpuModel} \u00b7 {system.cores} cores</Text><Text>Uptime: {Math.floor(system.uptime / 3600)} hours</Text></Stack>}); };\n return <Stack className=\"reference-rack\" p=\"sm\" h=\"100%\" style={{overflow:\"auto\"}}>\n <Group justify=\"space-between\"><Text fw={600}>Server rack</Text><Text size=\"xs\" c=\"dimmed\">{systems.length} systems</Text></Group>\n {query.error && <Alert color=\"red\">{query.error.message}<Button size=\"xs\" variant=\"subtle\" onClick={() => void query.refetch()}>Retry</Button></Alert>}\n <svg viewBox={`0 0 420 ${Math.max(90, rows.length * 64 + 24)}`} role=\"group\" aria-label=\"Beszel server rack\" style={{width:\"100%\", flexShrink:0}}>\n <rect x=\"1\" y=\"1\" width=\"418\" height={Math.max(88, rows.length * 64 + 22)} rx=\"8\" fill=\"var(--mantine-color-default)\" stroke=\"var(--mantine-color-default-border)\" />\n {rows.map((system, index) => <g key={system.id} role=\"button\" tabIndex={0} aria-label={`Inspect ${system.name}, ${system.status}`} onClick={() => inspect(system)} onKeyDown={(event) => { if (event.key === \"Enter\" || event.key === \" \") { event.preventDefault(); inspect(system); } }} className=\"reference-rack__unit\">\n <rect x=\"14\" y={12 + index * 64} width=\"392\" height=\"54\" rx=\"4\" fill=\"var(--mantine-color-body)\" stroke={selected === system.id ? \"var(--mantine-color-blue-6)\" : \"var(--mantine-color-default-border)\"} />\n <circle cx=\"31\" cy={39 + index * 64} r=\"5\" fill={system.status === \"up\" ? \"var(--mantine-color-teal-6)\" : \"var(--mantine-color-red-6)\"} />\n <text x=\"47\" y={34 + index * 64} fill=\"var(--mantine-color-text)\" fontSize=\"14\">{system.name.slice(0, 35)}</text>\n <text x=\"47\" y={53 + index * 64} fill=\"var(--mantine-color-dimmed)\" fontSize=\"11\">CPU {system.cpu.toFixed(1)}% \u00b7 RAM {system.memory.toFixed(1)}% \u00b7 {system.status}</text>\n <rect x=\"345\" y={26 + index * 64} width=\"44\" height=\"24\" rx=\"3\" fill=\"var(--mantine-color-dark-5)\" />\n {[0,1,2,3].map((slot) => <path key={slot} d={`M${350 + slot * 10},${30 + index * 64}v16`} stroke=\"var(--mantine-color-gray-6)\" />)}\n </g>)}\n </svg>\n {!query.isPending && !query.error && !systems.length && <Text c=\"dimmed\">No Beszel systems are available.</Text>}\n </Stack>;\n}",
"beszel-types.ts": "// Public result fields used from the Homarr Beszel capability adapter.\nexport interface SystemRow {\n id:string; name:string; status:\"up\"|\"down\"|\"paused\"|\"pending\";\n cpu:number; memory:number; disk:number; gpu:number; netBytes:number; uptime:number;\n hostname:string; cpuModel:string; cores:number; osName:string; agentVersion:string;\n}\nexport interface AttributedSystem extends SystemRow {connection:string;rowKey:string}\nexport interface NativeResult<T> {data:T;timestamp?:string}\nexport interface SystemStats {cpu:number;mu:number;mb:number;du:number;dio?:[number,number];dr?:number;dw?:number;b?:[number,number];ns?:number;nr?:number}\nexport interface ContainerStats {n:string;c:number;m:number;b?:[number,number];ns?:number;nr?:number}\nexport interface StatsRecord<T> {id:string;created:string;stats:T}\nexport type SystemRecord = StatsRecord<SystemStats>;\nexport type ContainerRecord = StatsRecord<ContainerStats[]>;\nexport interface StatsResult {systemStats:SystemRecord[];containerStats:ContainerRecord[]}\nexport type LiveStatsEvent = {type:\"system_stats\";record:SystemRecord}|{type:\"container_stats\";record:ContainerRecord};\nexport interface StatsInput {connection?:string;systemId:string;timePeriod?:string;includeDocker?:boolean}\n",
"downloads.tsx": "import type { BatchControl, BatchResult, DownloadConnection, DownloadSource } from \"./download-types\";\nimport { Alert, Button, Group, MultiSelect, Select, Stack, Text, TextInput } from \"@mantine/core\";\nimport { useWidgetAction, useWidgetCapabilities, useWidgetCommands, useWidgetHost, useWidgetQuery, useWidgetState } from \"@homarr/widget-sdk\";\nimport { DownloadSourceRegion } from \"./download-source\";\nexport default function Downloads() {\n const host = useWidgetHost();\n const sources = useWidgetQuery<DownloadSource[]>(\"sources\",{}, {staleTime:60000});\n const capabilities = useWidgetCapabilities();\n const batch = useWidgetAction<BatchResult,BatchControl>(\"controlBatch\");\n const [filter,setFilter] = useWidgetState(\"filter\",\"\");\n const [sort,setSort] = useWidgetState(\"sort\",\"queue\");\n const [selection,setSelection] = useWidgetState<DownloadConnection[]>(\"batch-clients\",[]);\n const available = sources.data ?? [];\n const targets = selection.filter((name) => available.some((source) => source.connection === name));\n const all = available.map((source) => source.connection);\n const canRun = (input:BatchControl) => input.connections.length > 0 && !host.isEditMode && !batch.isPending && capabilities.canRun(\"controlBatch\",input);\n const run = (input:BatchControl) => {void batch.mutateAsync(input).catch(() => undefined);};\n const pauseAll:BatchControl = {connections:all,operation:\"pause\"};\n const resumeAll:BatchControl = {connections:all,operation:\"resume\"};\n const pauseSelected:BatchControl = {connections:targets,operation:\"pause\"};\n const resumeSelected:BatchControl = {connections:targets,operation:\"resume\"};\n useWidgetCommands([{id:\"pause-all\",label:\"Pause all download clients\",disabled:!canRun(pauseAll),run:() => run(pauseAll)},{id:\"resume-all\",label:\"Resume all download clients\",disabled:!canRun(resumeAll),run:() => run(resumeAll)}]);\n return <Stack p=\"sm\" gap=\"sm\" h=\"100%\" style={{overflow:\"auto\"}}>\n <Text fw={600}>Downloads \u00b7 {available.length} clients</Text>\n {sources.error && <Alert color=\"red\">{sources.error.message}<Button size=\"xs\" variant=\"subtle\" onClick={() => void sources.refetch()}>Retry setup</Button></Alert>}\n {host.displayMode === \"advanced\" && <>\n <Group><TextInput label=\"Filter downloads\" value={filter} onChange={(event) => setFilter(event.currentTarget.value)} /><Select label=\"Sort\" value={sort} onChange={(value) => setSort(value ?? \"queue\")} data={[{value:\"queue\",label:\"Queue\"},{value:\"progress\",label:\"Progress\"},{value:\"name\",label:\"Name\"}]} /></Group>\n <Group gap=\"xs\"><Button size=\"compact-xs\" disabled={!canRun(pauseAll)} onClick={() => run(pauseAll)}>Pause all clients</Button><Button size=\"compact-xs\" disabled={!canRun(resumeAll)} onClick={() => run(resumeAll)}>Resume all clients</Button></Group>\n {available.length > 1 && <Group align=\"end\"><MultiSelect label=\"Batch targets\" data={available.map((source) => ({value:source.connection,label:source.label}))} value={selection} onChange={(values) => setSelection(all.filter((connection) => values.includes(connection)))} /><Button size=\"compact-xs\" variant=\"light\" disabled={!canRun(pauseSelected)} onClick={() => run(pauseSelected)}>Pause selected</Button><Button size=\"compact-xs\" variant=\"light\" disabled={!canRun(resumeSelected)} onClick={() => run(resumeSelected)}>Resume selected</Button></Group>}\n </>}\n {batch.isPending && <Text size=\"xs\" c=\"dimmed\" role=\"status\">Updating selected clients\u2026</Text>}\n {batch.error && <Alert color=\"red\">{batch.error.message}</Alert>}\n {batch.data && <Alert color={batch.data.failed ? \"yellow\" : \"green\"} title={`${batch.data.succeeded} succeeded \u00b7 ${batch.data.failed} failed`}>\n {batch.data.results.map((result) => <Text size=\"xs\" key={result.connection}>{available.find((source) => source.connection === result.connection)?.label ?? result.connection}: {result.ok ? `${result.operation} completed` : result.error}</Text>)}\n </Alert>}\n {available.map((source) => <DownloadSourceRegion key={source.connection} source={source} filter={filter} sort={sort} />)}\n {!sources.isPending && !sources.error && available.length === 0 && <Text c=\"dimmed\">Bind a download client to get started.</Text>}\n </Stack>;\n}\n",
"rack.css": ".reference-rack__unit { cursor: pointer; outline: none; }\n.reference-rack__unit:focus-visible > rect:first-child { stroke: var(--mantine-color-blue-6); stroke-width: 3; }\n.reference-rack__unit:hover > rect:first-child { stroke: var(--mantine-color-blue-5); }\n",
"download-source.tsx": "import type { DownloadControl, DownloadItem, DownloadSource, SourceQueue, ControlResult } from \"./download-types\";\nimport { Alert, Badge, Button, Group, Progress, Stack, Text } from \"@mantine/core\";\nimport { useWidgetAction, useWidgetCapabilities, useWidgetHost, useWidgetQuery, useWidgetServices } from \"@homarr/widget-sdk\";\nconst rate = (value:number|undefined) => `${((value ?? 0)/1048576).toFixed(1)} MiB/s`;\nexport function DownloadSourceRegion({source,filter,sort}:{source:DownloadSource;filter:string;sort:string}) {\n const host = useWidgetHost();\n const services = useWidgetServices();\n const capabilities = useWidgetCapabilities();\n const query = useWidgetQuery<SourceQueue>(\"queue\",{connection:source.connection},{refetchInterval:10000});\n const action = useWidgetAction<ControlResult,DownloadControl>(\"control\");\n const status = query.data?.data.status;\n const error = query.error ?? action.error;\n const run = (input:DownloadControl) => {void action.mutateAsync(input).catch(() => undefined);};\n const canRun = (input:DownloadControl) => !host.isEditMode && !action.isPending && capabilities.canRun(\"control\",input);\n const remove = async (item:DownloadItem) => {\n const input:DownloadControl = {connection:source.connection,operation:\"deleteItem\",itemId:item.id};\n if (!canRun(input)) return;\n if (await services.confirm({title:\"Remove download\",message:`Remove ${item.name} from ${source.label}? Downloaded files will be kept.`,destructive:true})) run(input);\n };\n const rows = query.data?.data.items ?? [];\n let items = rows.filter((item) => item.name.toLocaleLowerCase().includes(filter.toLocaleLowerCase()));\n if (sort === \"progress\") items = items.toSorted((a,b) => b.progress-a.progress);\n if (sort === \"name\") items = items.toSorted((a,b) => a.name.localeCompare(b.name));\n if (host.displayMode === \"compact\") items = items.slice(0,3);\n const pause:DownloadControl = {connection:source.connection,operation:\"pause\"};\n const resume:DownloadControl = {connection:source.connection,operation:\"resume\"};\n return <Stack gap=\"xs\" component=\"section\" aria-label={source.label} style={{border:\"1px solid var(--mantine-color-default-border)\",borderRadius:8,padding:10}}>\n <Group justify=\"space-between\"><Text size=\"sm\" fw={600}>{source.label} \u00b7 {rows.length}</Text>{status && <Badge color={status.paused ? \"yellow\" : \"blue\"}>{status.paused ? \"Paused\" : rate(status.rates.down)}</Badge>}</Group>\n {error && <Alert color=\"yellow\" title={source.label}>{error.message}<Button size=\"compact-xs\" variant=\"subtle\" onClick={() => {action.reset();void query.refetch();}}>Retry this client</Button></Alert>}\n {action.isPending && <Text size=\"xs\" c=\"dimmed\" role=\"status\">Updating this client\u2026</Text>}\n {query.isPending && <Text size=\"xs\" c=\"dimmed\">Loading this client's queue\u2026</Text>}\n {host.displayMode === \"advanced\" && <Group gap=\"xs\"><Button size=\"compact-xs\" variant=\"light\" disabled={!canRun(pause)} onClick={() => run(pause)}>Pause this client</Button><Button size=\"compact-xs\" variant=\"light\" disabled={!canRun(resume)} onClick={() => run(resume)}>Resume this client</Button></Group>}\n {items.map((item) => {\n const toggle:DownloadControl = {connection:source.connection,operation:item.state === \"paused\" ? \"resumeItem\" : \"pauseItem\",itemId:item.id};\n const deletion:DownloadControl = {connection:source.connection,operation:\"deleteItem\",itemId:item.id};\n return <Stack key={`${source.connection}:${item.id}`} gap={4}>\n <Group justify=\"space-between\" wrap=\"nowrap\"><Text size=\"sm\" truncate>{item.name}</Text><Badge size=\"xs\">{item.state}</Badge></Group>\n <Progress aria-label={`${source.label}: ${item.name} progress`} value={item.progress*100} />\n <Group justify=\"space-between\"><Text size=\"xs\" c=\"dimmed\">{Math.round(item.progress*100)}% \u00b7 {rate(item.downSpeed)}</Text>{host.displayMode === \"advanced\" && <Group gap=\"xs\"><Button size=\"compact-xs\" variant=\"subtle\" disabled={!canRun(toggle)} onClick={() => run(toggle)}>{item.state === \"paused\" ? \"Resume\" : \"Pause\"}</Button><Button size=\"compact-xs\" color=\"red\" variant=\"subtle\" disabled={!canRun(deletion)} onClick={() => void remove(item)}>Remove</Button></Group>}</Group>\n </Stack>;\n })}\n {!query.isPending && !query.error && items.length === 0 && <Text size=\"xs\" c=\"dimmed\">No downloads match this client view.</Text>}\n {action.data?.ok && <Text size=\"xs\" c=\"green\">{source.label}: {action.data.operation} completed</Text>}\n </Stack>;\n}\n"
},
"dependencies": {},
"connections": {
"beszel": {
"kind": "integration",
"label": "Beszel integration"
},
"client": {
"kind": "integration",
"label": "Primary download client"
},
"media": {
"kind": "integration",
"label": "Media server"
},
"secondary": {
"kind": "integration",
"label": "Second download client",
"optional": true
}
},
"options": {
"primaryLabel": {
"control": "text",
"label": "Primary client label",
"default": "Primary client"
},
"secondaryLabel": {
"control": "text",
"label": "Second client label",
"default": "Second client"
}
}
}
+35
View File
@@ -0,0 +1,35 @@
{
"$schema": "homarr-widget-package-v3",
"manifest": {
"id": "homarr.reference.rack",
"version": "1.0.0",
"sdkVersion": "1",
"name": "Interactive server rack",
"description": "A keyboard-accessible SVG rack backed by real Beszel inventory, with selectable systems and host-native detail views.",
"entrypoints": {
"tile": "widget.tsx",
"advanced": "widget.tsx",
"server": "server.ts"
},
"handlers": {
"systems": {
"kind": "query",
"permission": "view"
}
}
},
"files": {
"server.ts": "import type { NativeResult, SystemRow } from \"./beszel-types\";\nimport { callWidgetIntegration, defineWidgetServer } from \"@homarr/widget-sdk/server\";\nexport default defineWidgetServer({ systems: (_input, context) => callWidgetIntegration<NativeResult<SystemRow[]>>(context, {connection:\"beszel\",capability:\"beszel.systems\"}) });",
"widget.tsx": "import type { SystemRow, NativeResult } from \"./beszel-types\";\nimport { Alert, Button, Group, Stack, Text } from \"@mantine/core\";\nimport { useWidgetHost, useWidgetQuery, useWidgetServices, useWidgetState } from \"@homarr/widget-sdk\";\nimport \"./rack.css\";\nexport default function Rack() {\n const host = useWidgetHost();\n const services = useWidgetServices();\n const query = useWidgetQuery<NativeResult<SystemRow[]>>(\"systems\", {}, {refetchInterval: 15000});\n const [selected, setSelected] = useWidgetState(\"selected\", \"\");\n const systems = query.data?.data ?? [];\n const rows = host.displayMode === \"advanced\" ? systems : systems.slice(0, 8);\n const inspect = (system:SystemRow) => { setSelected(system.id); services.openDetail({title: system.name, content: <Stack><Text>{system.hostname} \u00b7 {system.osName}</Text><Text>CPU: {system.cpu.toFixed(1)}% \u00b7 Memory: {system.memory.toFixed(1)}% \u00b7 Disk: {system.disk.toFixed(1)}%</Text><Text>{system.cpuModel} \u00b7 {system.cores} cores</Text><Text>Uptime: {Math.floor(system.uptime / 3600)} hours</Text></Stack>}); };\n return <Stack className=\"reference-rack\" p=\"sm\" h=\"100%\" style={{overflow:\"auto\"}}>\n <Group justify=\"space-between\"><Text fw={600}>Server rack</Text><Text size=\"xs\" c=\"dimmed\">{systems.length} systems</Text></Group>\n {query.error && <Alert color=\"red\">{query.error.message}<Button size=\"xs\" variant=\"subtle\" onClick={() => void query.refetch()}>Retry</Button></Alert>}\n <svg viewBox={`0 0 420 ${Math.max(90, rows.length * 64 + 24)}`} role=\"group\" aria-label=\"Beszel server rack\" style={{width:\"100%\", flexShrink:0}}>\n <rect x=\"1\" y=\"1\" width=\"418\" height={Math.max(88, rows.length * 64 + 22)} rx=\"8\" fill=\"var(--mantine-color-default)\" stroke=\"var(--mantine-color-default-border)\" />\n {rows.map((system, index) => <g key={system.id} role=\"button\" tabIndex={0} aria-label={`Inspect ${system.name}, ${system.status}`} onClick={() => inspect(system)} onKeyDown={(event) => { if (event.key === \"Enter\" || event.key === \" \") { event.preventDefault(); inspect(system); } }} className=\"reference-rack__unit\">\n <rect x=\"14\" y={12 + index * 64} width=\"392\" height=\"54\" rx=\"4\" fill=\"var(--mantine-color-body)\" stroke={selected === system.id ? \"var(--mantine-color-blue-6)\" : \"var(--mantine-color-default-border)\"} />\n <circle cx=\"31\" cy={39 + index * 64} r=\"5\" fill={system.status === \"up\" ? \"var(--mantine-color-teal-6)\" : \"var(--mantine-color-red-6)\"} />\n <text x=\"47\" y={34 + index * 64} fill=\"var(--mantine-color-text)\" fontSize=\"14\">{system.name.slice(0, 35)}</text>\n <text x=\"47\" y={53 + index * 64} fill=\"var(--mantine-color-dimmed)\" fontSize=\"11\">CPU {system.cpu.toFixed(1)}% \u00b7 RAM {system.memory.toFixed(1)}% \u00b7 {system.status}</text>\n <rect x=\"345\" y={26 + index * 64} width=\"44\" height=\"24\" rx=\"3\" fill=\"var(--mantine-color-dark-5)\" />\n {[0,1,2,3].map((slot) => <path key={slot} d={`M${350 + slot * 10},${30 + index * 64}v16`} stroke=\"var(--mantine-color-gray-6)\" />)}\n </g>)}\n </svg>\n {!query.isPending && !query.error && !systems.length && <Text c=\"dimmed\">No Beszel systems are available.</Text>}\n </Stack>;\n}",
"beszel-types.ts": "// Public result fields used from the Homarr Beszel capability adapter.\nexport interface SystemRow {\n id:string; name:string; status:\"up\"|\"down\"|\"paused\"|\"pending\";\n cpu:number; memory:number; disk:number; gpu:number; netBytes:number; uptime:number;\n hostname:string; cpuModel:string; cores:number; osName:string; agentVersion:string;\n}\nexport interface AttributedSystem extends SystemRow {connection:string;rowKey:string}\nexport interface NativeResult<T> {data:T;timestamp?:string}\nexport interface SystemStats {cpu:number;mu:number;mb:number;du:number;dio?:[number,number];dr?:number;dw?:number;b?:[number,number];ns?:number;nr?:number}\nexport interface ContainerStats {n:string;c:number;m:number;b?:[number,number];ns?:number;nr?:number}\nexport interface StatsRecord<T> {id:string;created:string;stats:T}\nexport type SystemRecord = StatsRecord<SystemStats>;\nexport type ContainerRecord = StatsRecord<ContainerStats[]>;\nexport interface StatsResult {systemStats:SystemRecord[];containerStats:ContainerRecord[]}\nexport type LiveStatsEvent = {type:\"system_stats\";record:SystemRecord}|{type:\"container_stats\";record:ContainerRecord};\nexport interface StatsInput {connection?:string;systemId:string;timePeriod?:string;includeDocker?:boolean}\n",
"rack.css": ".reference-rack__unit { cursor: pointer; outline: none; }\n.reference-rack__unit:focus-visible > rect:first-child { stroke: var(--mantine-color-blue-6); stroke-width: 3; }\n.reference-rack__unit:hover > rect:first-child { stroke: var(--mantine-color-blue-5); }\n"
},
"dependencies": {},
"connections": {
"beszel": {
"kind": "integration",
"label": "Beszel integration"
}
},
"options": {}
}
+86
View File
@@ -0,0 +1,86 @@
{
"$schema": "homarr-widget-package-v3",
"manifest": {
"id": "homarr.reference.sonarr",
"version": "1.1.0",
"sdkVersion": "1",
"name": "Sonarr operations",
"description": "Two-server Sonarr operations: upcoming episodes, missing releases, queue progress, filtered advanced views and confirmed episode search through the native adapter.",
"entrypoints": {
"tile": "widget.tsx",
"advanced": "widget.tsx",
"server": "server.ts"
},
"handlers": {
"overview": {
"kind": "query",
"permission": "view"
},
"searchEpisodes": {
"kind": "action",
"permission": "modify",
"inputSchema": {
"type": "object",
"required": ["connection", "episodeIds"],
"additionalProperties": false,
"properties": {
"connection": {
"enum": ["sonarr", "secondary"]
},
"episodeIds": {
"type": "array",
"minItems": 1,
"maxItems": 100,
"items": {
"type": "integer",
"minimum": 1
}
}
}
}
}
}
},
"files": {
"widget.tsx": "import { Alert, Badge, Button, Group, Loader, Progress, SegmentedControl, Select, Stack, Text, TextInput } from \"@mantine/core\";\nimport { useWidgetAction, useWidgetHost, useWidgetOptions, useWidgetQuery, useWidgetServices, useWidgetState } from \"@homarr/widget-sdk\";\nimport type { Connection, Overview, SonarrOptions } from \"./types\";\nexport default function Sonarr() {\n const host = useWidgetHost(); const services = useWidgetServices(); const options = useWidgetOptions<SonarrOptions>();\n const [tab,setTab] = useWidgetState(\"tab\",\"calendar\");\n const [source,setSource] = useWidgetState(\"source\",\"all\");\n const [filter,setFilter] = useWidgetState(\"filter\",\"\");\n const query = useWidgetQuery<Overview>(\"overview\",{}, {refetchInterval:60000});\n const search = useWidgetAction<{id:number;status:string},{connection:Connection;episodeIds:number[]}>(\"searchEpisodes\");\n const label = (connection:Connection) => connection === \"sonarr\" ? options.primaryName : options.secondaryName;\n const sources = query.data?.sources ?? [];\n const rows = sources.filter((entry) => source === \"all\" || source === entry.connection).flatMap((entry) => {\n let items = entry.calendar;\n if (tab === \"missing\") items = entry.missing.items;\n if (tab === \"queue\") items = entry.queue.items;\n return items.map((item,index) => ({...item,connection:entry.connection,rowKey:`${entry.connection}:${tab}:${item.id ?? index}`}));\n }).filter((item) => `${item.title} ${item.subTitle ?? item.seriesTitle ?? \"\"}`.toLowerCase().includes(filter.toLowerCase()));\n const visible = host.displayMode === \"advanced\" ? rows : rows.slice(0,4);\n const requestSearch = async (connection:Connection,id:number,title:string) => {\n if (await services.confirm({title:\"Search for this episode?\",message:`Ask ${label(connection)} to find and download an eligible release for ${title}?`})) search.mutate({connection,episodeIds:[id]});\n };\n return <Stack h=\"100%\" p=\"md\" gap=\"sm\" style={{overflow:\"auto\"}}>\n <Group justify=\"space-between\"><Text fw={600}>{options.title}</Text><Badge>{sources.reduce((sum,entry) => sum+entry.queue.totalCount,0)} queued</Badge></Group>\n <SegmentedControl value={tab} onChange={setTab} data={[{label:\"Upcoming\",value:\"calendar\"},{label:\"Missing\",value:\"missing\"},{label:\"Queue\",value:\"queue\"}]} />\n {sources.length > 1 && <Select aria-label=\"Sonarr server\" value={source} onChange={(value) => setSource(value ?? \"all\")} data={[{value:\"all\",label:\"All servers\"},...sources.map((entry) => ({value:entry.connection,label:label(entry.connection)}))]} />}\n {host.displayMode === \"advanced\" && <TextInput aria-label=\"Filter episodes\" placeholder=\"Filter series or episode…\" value={filter} onChange={(event) => setFilter(event.currentTarget.value)} />}\n {query.isPending && <Loader size=\"sm\" />}\n {query.error && <Alert color=\"red\">{query.error.message}</Alert>}\n {sources.filter((entry) => entry.error).map((entry) => <Alert key={entry.connection} color=\"red\" title={label(entry.connection)}>{entry.error}</Alert>)}\n {search.error && <Alert color=\"red\">{search.error.message}</Alert>}\n {search.data?.id && <Text size=\"xs\" c=\"teal\">Search command {search.data.id}: {search.data.status}. Sonarr will select an eligible release.</Text>}\n {visible.map((item) => <Stack key={item.rowKey} gap={4}><Group justify=\"space-between\"><Text fw={500} size=\"sm\">{item.subTitle ?? item.seriesTitle ?? item.title}</Text><Badge size=\"xs\" variant=\"light\">{label(item.connection)}</Badge></Group><Text size=\"xs\" c=\"dimmed\">{item.title}{item.seasonNumber !== undefined && ` · S${item.seasonNumber} E${item.episodeNumber ?? \"?\"}`}</Text>{item.startDate && <Text size=\"xs\">{new Date(item.startDate).toLocaleString(host.locale)}</Text>}{item.percentComplete !== undefined && <Progress value={item.percentComplete} aria-label={`${item.title} download progress`} />}<Group gap=\"xs\">{(item.link || item.links?.[0]?.href) && <Button size=\"compact-xs\" variant=\"subtle\" onClick={() => services.navigate(item.link ?? item.links?.[0]?.href ?? \"\")}>Open in Sonarr</Button>}{tab === \"missing\" && typeof item.id === \"number\" && <Button size=\"compact-xs\" disabled={host.isEditMode || search.isPending} onClick={() => void requestSearch(item.connection,item.id!,item.title)}>Search episode</Button>}</Group></Stack>)}\n {query.data && !rows.length && <Text c=\"dimmed\">No episodes match this view.</Text>}\n <Group><Button size=\"xs\" variant=\"light\" onClick={() => void query.refetch()}>Refresh</Button>{host.displayMode === \"compact\" && <Button size=\"xs\" variant=\"subtle\" onClick={services.openAdvanced}>All episodes and filters</Button>}</Group>\n </Stack>;\n}\n",
"server.ts": "import type { Connection, EpisodeRow, SearchInput, SonarrOptions } from \"./types\";\nimport { callWidgetIntegration, defineWidgetServer, getWidgetServerContext } from \"@homarr/widget-sdk/server\";\nconst connections:Connection[] = [\"sonarr\", \"secondary\"];\nexport default defineWidgetServer({\n overview: async (_input, context) => {\n const {bindingNames,options} = await getWidgetServerContext<SonarrOptions>(context);\n const start = new Date();\n const end = new Date(start.getTime()+Math.max(1,Math.min(90,Number(options.days)||7))*86400000);\n const names = connections.filter((name) => bindingNames.includes(name));\n if (!names.length) throw new Error(\"Bind at least one Sonarr integration\");\n const sources = await Promise.all(names.map(async (connection) => {\n const call = <T,>(capability:string,input:unknown) => callWidgetIntegration<T>(context,{connection,capability,input});\n try {\n const [calendar,missing,queue] = await Promise.all([\n call<EpisodeRow[]>(\"sonarr.calendar\",{start:start.toISOString(),end:end.toISOString()}),\n call<{items:EpisodeRow[];totalCount:number}>(\"sonarr.missing\",{limit:100}), call<{items:EpisodeRow[];totalCount:number}>(\"sonarr.queue\",{limit:100}),\n ]);\n return {connection,calendar,missing,queue};\n } catch (error) { return {connection,calendar:[],missing:{items:[],totalCount:0},queue:{items:[],totalCount:0},error:error instanceof Error ? error.message : String(error)}; }\n }));\n return {sources};\n },\n searchEpisodes: (input:SearchInput,context) => {\n if (!connections.includes(input?.connection) || !Array.isArray(input?.episodeIds) || !input.episodeIds.length || input.episodeIds.length > 100 || input.episodeIds.some((id) => !Number.isInteger(id) || id < 1)) throw new Error(\"Choose valid episode IDs from a declared Sonarr server\");\n return callWidgetIntegration(context,{connection:input.connection,capability:\"sonarr.searchEpisodes\",input:{episodeIds:input.episodeIds}});\n },\n});\n",
"types.ts": "export type Connection = \"sonarr\" | \"secondary\";\nexport interface EpisodeRow { id?:number; title:string; subTitle?:string; seriesTitle?:string; startDate?:string; seasonNumber?:number; episodeNumber?:number; percentComplete?:number; status?:string; timeLeft?:string|null; link?:string; links?:{href:string}[]; }\nexport interface Source { connection:Connection; calendar:EpisodeRow[]; missing:{items:EpisodeRow[];totalCount:number}; queue:{items:EpisodeRow[];totalCount:number}; error?:string; }\nexport interface Overview { sources:Source[]; }\nexport type SonarrOptions = {title:string;primaryName:string;secondaryName:string;days:number};\nexport type SearchInput = {connection:Connection;episodeIds:number[]};\n",
"README.md": "# Sonarr operations\nBind the primary Sonarr integration and optionally a second one. Existing Homarr native query and interaction permissions apply. Each result retains its connection identity, including when different servers use the same numeric episode ID.\n\nCompact view shows four episodes; advanced view includes all loaded rows, source selection and text filtering. The reference reads up to 100 missing and queued episodes per server. A failure on one server does not hide the other server's result.\n\nSearch episode is a named modify action. It confirms the target server and episode before submitting the native Sonarr EpisodeSearch command. A queued command does not prove a release was found or downloaded. Default previews simulate actions. The integration sends the API key server-side; no key is embedded in portable source.\n\nAPI reference: https://github.com/Sonarr/Sonarr/blob/develop/src/NzbDrone.Core/IndexerSearch/EpisodeSearchCommand.cs and https://github.com/Sonarr/Sonarr/blob/develop/src/Sonarr.Api.V3/Commands/CommandController.cs\n"
},
"dependencies": {},
"connections": {
"sonarr": {
"kind": "integration",
"label": "Sonarr integration"
},
"secondary": {
"kind": "integration",
"label": "Second Sonarr integration",
"optional": true
}
},
"options": {
"title": {
"control": "text",
"label": "Title",
"default": "Sonarr"
},
"primaryName": {
"control": "text",
"label": "Primary server label",
"default": "Primary"
},
"secondaryName": {
"control": "text",
"label": "Second server label",
"default": "Secondary"
},
"days": {
"control": "number",
"label": "Calendar days",
"default": 7,
"min": 1,
"max": 90
}
}
}
+64
View File
@@ -0,0 +1,64 @@
{
"$schema": "homarr-widget-package-v3",
"manifest": {
"id": "homarr.reference.sqlite",
"version": "1.0.0",
"sdkVersion": "1",
"name": "SQLite and local status",
"description": "Read-only named SQLite queries, rich data tables and optional local JSON status. No HTTP API required.",
"entrypoints": {
"tile": "widget.tsx",
"advanced": "widget.tsx",
"server": "server.ts"
},
"handlers": {
"catalog": {
"kind": "query",
"permission": "view"
},
"rows": {
"kind": "query",
"permission": "view"
},
"status": {
"kind": "query",
"permission": "view"
}
}
},
"files": {
"server.ts": "import type { WidgetServerContext } from \"@homarr/widget-sdk/server\";\ntype NamedQuery = {name:string;label?:string;sql:string};\ntype Cell = null|string|number;\nimport { DatabaseSync } from \"node:sqlite\";\nimport { open } from \"node:fs/promises\";\nimport { defineWidgetServer, getWidgetConnection, getWidgetServerContext } from \"@homarr/widget-sdk/server\";\n\nconst databaseSettings = async (context:WidgetServerContext) => {\n const {configuration} = await getWidgetConnection(context,{connection:\"database\",serviceType:\"sqlite\"});\n const settings = configuration.settings ?? {};\n if (typeof settings.path !== \"string\" || !settings.path.trim()) throw new Error(\"Set path on the SQLite service connection to a mounted database file\");\n if (!Array.isArray(settings.queries) || !settings.queries.length) throw new Error(\"Configure named queries on the SQLite service: queries:[{name,label,sql}]\");\n const queries = settings.queries.filter((query:unknown): query is NamedQuery => Boolean(query && typeof query === \"object\" && \"name\" in query && typeof query.name === \"string\" && \"sql\" in query && typeof query.sql === \"string\" && (!(\"label\" in query) || typeof query.label === \"string\")));\n if (!queries.length) throw new Error(\"At least one named SQL query is required\");\n return {path:settings.path,queries};\n};\nconst jsonValue = (value:null|string|number|bigint|Uint8Array):Cell => {\n if (typeof value === \"bigint\") return String(value);\n if (value instanceof Uint8Array) return `[${value.byteLength} binary bytes]`;\n return value;\n};\nexport default defineWidgetServer({\n catalog: async (_input,context) => {\n const settings = await databaseSettings(context);\n return settings.queries.map((query) => ({value:query.name,label:query.label || query.name}));\n },\n rows: async (input:{name?:string},context) => {\n const settings = await databaseSettings(context);\n const query = settings.queries.find((query) => query.name === input?.name);\n if (!query) throw new Error(\"Choose a configured query\");\n const {options} = await getWidgetServerContext(context);\n const limit = Math.max(1,Math.min(200,Number(options.rowLimit)||100));\n const database = new DatabaseSync(settings.path,{readOnly:true,timeout:1000,allowExtension:false});\n try {\n const statement = database.prepare(query.sql);\n statement.setReadBigInts(true);\n const rows: Record<string,Cell>[] = [];\n let truncated = false;\n for (const row of statement.iterate()) {\n context.signal.throwIfAborted();\n if (rows.length >= limit) { truncated = true; break; }\n rows.push(Object.fromEntries(Object.entries(row).map(([key,value]) => [key,jsonValue(value)])));\n }\n return {rows,columns:statement.columns().map((column) => column.name),truncated,updatedAt:new Date().toISOString()};\n } finally { database.close(); }\n },\n status: async (_input,context) => {\n const {bindingNames} = await getWidgetServerContext(context);\n if (!bindingNames.includes(\"status\")) return {configured:false};\n const {configuration} = await getWidgetConnection(context,{connection:\"status\",serviceType:\"file\"});\n const path = configuration.settings?.path;\n if (typeof path !== \"string\") throw new Error(\"Set path on the local file connection\");\n const file = await open(path,\"r\");\n try {\n const stat = await file.stat();\n if (!stat.isFile() || stat.size > 524288) throw new Error(\"Choose a regular JSON status file under 512 KiB\");\n const bytes = Buffer.alloc(524289);\n const {bytesRead} = await file.read(bytes,0,bytes.length,0);\n if (bytesRead > 524288) throw new Error(\"The status file exceeds 512 KiB\");\n return {configured:true,value:JSON.parse(bytes.subarray(0,bytesRead).toString(\"utf8\")),updatedAt:stat.mtime.toISOString()};\n } finally { await file.close(); }\n },\n});\n",
"README.md": "# SQLite and local status\n\nCreate a Service connection with serviceType `sqlite`. Nonsecret settings:\n\n```json\n{\"path\":\"/data/app.sqlite\",\"queries\":[{\"name\":\"recent\",\"label\":\"Recent jobs\",\"sql\":\"SELECT id, status, created_at FROM jobs ORDER BY created_at DESC LIMIT 100\"}]}\n```\n\nThe path is resolved inside the Homarr process/container. Mount the application's database (and SQLite WAL/SHM companions when applicable) read-only and ensure the Homarr user can read them. Prefer an application-supported backup/snapshot for a busy database. This adapter uses Node 24's built-in node:sqlite; no npm or HTTP connection is needed. Each invocation opens read-only and closes its own connection. Only owner-configured named queries are accepted from viewers, and results are bounded. Add an indexed LIMIT to expensive queries; the worker deadline cancels excessively slow handlers.\n\nOptionally bind a serviceType `file` connection to status with settings {\"path\":\"/data/status.json\"}. It reads bounded JSON, checks the file size, and closes the descriptor. The files and SQL remain local connection settings and are not exported with the widget.\n\nDiagnose checks file readability. Run preview to verify SQLite format, SQL and JSON parsing. Source: https://nodejs.org/docs/latest-v24.x/api/sqlite.html\n",
"widget.tsx": "type Row = Record<string,null|string|number> & {__row:number};\nimport type server from \"./server\";\nimport { Alert, Badge, Button, Group, Select, Stack, Text } from \"@mantine/core\";\nimport { useWidgetHost, useWidgetServices, useWidgetOptions, useWidgetQuery, useWidgetState } from \"@homarr/widget-sdk\";\nimport { HomarrDataTable } from \"@homarr/widget-sdk/ui\";\nexport default function DatabaseDashboard() {\n const host = useWidgetHost();\n const services = useWidgetServices();\n const options = useWidgetOptions<{title:string;rowLimit:number}>();\n const [selected,setSelected] = useWidgetState(\"query\",\"\");\n const catalog = useWidgetQuery<Awaited<ReturnType<typeof server.catalog>>>(\"catalog\",{}, {staleTime:60000});\n const name = selected || catalog.data?.[0]?.value || \"\";\n const rows = useWidgetQuery<Awaited<ReturnType<typeof server.rows>>>(\"rows\",{name},{enabled:Boolean(name),refetchInterval:30000});\n const status = useWidgetQuery<Awaited<ReturnType<typeof server.status>>>(\"status\",{}, {refetchInterval:30000});\n const error = catalog.error || rows.error;\n const records:Row[] = (rows.data?.rows ?? []).map((row,index) => ({...row,__row:index}));\n let visible = records.slice(0,10);\n if (host.displayMode === \"advanced\") visible = records;\n return <Stack h=\"100%\" gap=\"xs\" p=\"sm\">\n <Group justify=\"space-between\"><Text fw={600}>{options.title}</Text><Badge variant=\"light\">Read only</Badge></Group>\n <Select aria-label=\"Configured database query\" data={catalog.data ?? []} value={name || null} onChange={(value) => setSelected(value || \"\")} />\n {error && <Alert color=\"red\">{error.message}</Alert>}\n <div style={{flex:1,minHeight:0}}><HomarrDataTable<Row> isEditMode={host.isEditMode} cellPadding=\"6px\" idAccessor=\"__row\" records={visible} fetching={rows.isFetching} minHeight={100} columns={(rows.data?.columns ?? []).map((key) => ({accessor:key,title:key,resizable:true,render:(row:Row) => <Text size=\"xs\" lineClamp={2}>{String(row[key] ?? \"\u2014\")}</Text>}))} noRecordsText=\"This query has no rows\" /></div>\n <Group justify=\"space-between\"><Text size=\"xs\" c=\"dimmed\">{records.length} rows{rows.data?.truncated ? \" \u00b7 row limit reached\" : \"\"}</Text>{host.displayMode !== \"advanced\" && <Button size=\"compact-xs\" variant=\"subtle\" onClick={() => services.openAdvanced()}>Explore rows</Button>}</Group>\n {status.error && <Alert color=\"yellow\">Status file: {status.error.message}</Alert>}\n {status.data?.configured && <Text component=\"pre\" size=\"xs\" style={{whiteSpace:\"pre-wrap\",maxHeight:100,overflow:\"auto\"}}>{JSON.stringify(status.data.value,null,2).slice(0,4000)}</Text>}\n </Stack>;\n}\n"
},
"dependencies": {},
"connections": {
"database": {
"kind": "service",
"serviceType": "sqlite",
"label": "SQLite database",
"description": "Local settings: path and queries:[{name,label,sql}]. The database opens read-only."
},
"status": {
"kind": "service",
"serviceType": "file",
"label": "Local JSON status file",
"description": "Local settings: path to a JSON file mounted in the Homarr container.",
"optional": true
}
},
"options": {
"title": {
"control": "text",
"label": "Title",
"default": "Application database"
},
"rowLimit": {
"control": "number",
"label": "Maximum rows",
"default": 100,
"min": 1,
"max": 200
}
}
}
+34
View File
@@ -0,0 +1,34 @@
{
"$schema": "homarr-widget-package-v3",
"manifest": {
"id": "homarr.reference.timer",
"version": "1.0.0",
"sdkVersion": "1",
"name": "Focus timer",
"description": "A source-free deadline timer. Pausing, view changes and hidden tabs preserve the correct remaining time.",
"entrypoints": {
"tile": "widget.tsx",
"advanced": "widget.tsx"
},
"handlers": {}
},
"files": {
"widget.tsx": "import { Alert, Button, Group, NumberInput, Progress, Stack, Text } from \"@mantine/core\";\nimport { useWidgetClock, useWidgetCommands, useWidgetHost, useWidgetOptions, useWidgetState } from \"@homarr/widget-sdk\";\nexport default function Timer() {\n const host = useWidgetHost();\n const options = useWidgetOptions<{title:string;minutes:number}>();\n const now = useWidgetClock(100);\n const [minutes, setMinutes] = useWidgetState(\"minutes\", options.minutes);\n const [timer, setTimer] = useWidgetState<{remaining:number;deadline:number|null;duration:number}>(\"timer\", { remaining: options.minutes * 60000, deadline: null, duration: options.minutes * 60000 });\n const remaining = timer.deadline === null || now === null ? timer.remaining : Math.max(0, timer.deadline - now);\n const running = timer.deadline !== null && remaining > 0;\n const start = () => setTimer({ remaining, duration: timer.duration, deadline: Date.now() + remaining });\n const pause = () => setTimer({ ...timer, remaining, deadline: null });\n const reset = () => setTimer({ remaining: minutes * 60000, duration: minutes * 60000, deadline: null });\n useWidgetCommands([{ id: \"toggle\", label: running ? \"Pause timer\" : \"Start timer\", disabled: remaining <= 0, run: running ? pause : start }, { id: \"reset\", label: \"Reset timer\", run: reset }]);\n const seconds = Math.ceil(remaining / 1000);\n return <Stack h=\"100%\" justify=\"center\" p=\"md\" gap=\"sm\">\n <Text c=\"dimmed\" size=\"sm\">{options.title}</Text>\n <Text ff=\"monospace\" fw={700} fz={host.displayMode === \"advanced\" ? \"4rem\" : \"2rem\"} aria-live={remaining === 0 ? \"polite\" : \"off\"}>{Math.floor(seconds / 60)}:{String(seconds % 60).padStart(2, \"0\")}</Text>\n <Progress value={timer.duration ? 100 * (1 - remaining / timer.duration) : 0} aria-label=\"Elapsed timer duration\" />\n {remaining === 0 && <Alert color=\"teal\">Timer complete</Alert>}\n <Group><Button disabled={host.isEditMode || remaining <= 0} onClick={running ? pause : start}>{running ? \"Pause\" : \"Start\"}</Button><Button variant=\"light\" disabled={host.isEditMode} onClick={reset}>Reset</Button></Group>\n {host.displayMode === \"advanced\" && <NumberInput label=\"Minutes for next reset\" min={1} max={1440} value={minutes} onChange={(value) => { if (typeof value === \"number\") setMinutes(value); }} />}\n </Stack>;\n}\n"
},
"dependencies": {},
"connections": {},
"options": {
"title": {
"control": "text",
"label": "Title",
"default": "Focus"
},
"minutes": {
"control": "number",
"label": "Minutes",
"default": 25,
"min": 1,
"max": 1440
}
}
}
+41
View File
@@ -0,0 +1,41 @@
{
"name": "@homarr/widget-sdk",
"version": "0.1.0",
"private": true,
"license": "Apache-2.0",
"type": "module",
"exports": {
".": "./src/client.tsx",
"./client": "./src/client.tsx",
"./shared": "./src/shared.ts",
"./server": "./src/server.ts",
"./legacy": "./src/legacy.d.ts",
"./ui": "./src/ui.tsx",
"./examples/clock.json": "./examples/clock.json",
"./examples/beszel.json": "./examples/beszel.json",
"./examples": "./src/examples.ts",
"./examples/*.json": "./examples/*.json",
"./table": "./src/table.ts",
"./ui-settings": "./src/ui-settings.ts",
"./table/localization": "./src/table/use-translated-mantine-react-table.ts"
},
"scripts": {
"lint": "oxlint",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@homarr/common": "workspace:^0.1.0",
"@homarr/translation": "workspace:^0.1.0",
"@mantine/core": "catalog:",
"@tanstack/react-query": "catalog:",
"mantine-datatable": "catalog:",
"mantine-react-table": "catalog:",
"next": "catalog:",
"react": "catalog:"
},
"devDependencies": {
"@homarr/tsconfig": "workspace:^0.1.0",
"@types/react": "catalog:",
"typescript": "catalog:"
}
}
+360
View File
@@ -0,0 +1,360 @@
"use client";
import type { Context, Dispatch, PropsWithChildren, SetStateAction } from "react";
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useState,
useSyncExternalStore,
} from "react";
import { hashKey, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import type {
WidgetCommand,
WidgetHostContext,
WidgetHostServices,
WidgetStateStore,
WidgetStorageScope,
} from "./shared";
export type * from "./shared";
export { parseLocalWidgetState, serializeLocalWidgetState, useLocalWidgetState } from "./local-state";
interface WidgetRuntime {
context: WidgetHostContext;
services: WidgetHostServices;
options: Record<string, unknown>;
}
// The authorized module loader and Next route chunks must share one context even after HMR.
// Compiled package modules can outlive the chunk that originally supplied their SDK hooks.
const contextKey = Symbol.for("homarr.widget.context.v1");
const contextRegistry = globalThis as typeof globalThis & { [contextKey]?: Context<WidgetRuntime | null> };
const WidgetContext = (contextRegistry[contextKey] ??= createContext<WidgetRuntime | null>(null));
export function WidgetHostProvider({ children, ...runtime }: PropsWithChildren<WidgetRuntime>) {
return <WidgetContext.Provider value={runtime}>{children}</WidgetContext.Provider>;
}
/** Compose independently authored components without colliding state, storage, commands or query caches. */
export function WidgetScope({
name,
handlerPrefix = "",
options,
children,
}: PropsWithChildren<{
name: string;
handlerPrefix?: string;
options?: Record<string, unknown>;
}>) {
const runtime = useWidgetRuntime();
const parent = runtime.services;
const services = useMemo<WidgetHostServices>(() => {
const operation = (input: Parameters<WidgetHostServices["transport"]["query"]>[0]) => ({
...input,
name: input.name.startsWith("$") ? input.name : `${handlerPrefix}${input.name}`,
});
return {
...parent,
state: {
get: (key) => parent.state.get(`${name}:${key}`),
set: (key, value) => parent.state.set(`${name}:${key}`, value),
subscribe: parent.state.subscribe,
},
registerCommands: (commands) =>
parent.registerCommands(commands.map((command) => ({ ...command, id: `${name}:${command.id}` }))),
transport: {
query: (input, signal) => parent.transport.query(operation(input), signal),
action: (input) => parent.transport.action(operation(input)),
subscribe: (input, observer) => parent.transport.subscribe(operation(input), observer),
storageGet: (input, signal) => parent.transport.storageGet({ ...input, key: `${name}:${input.key}` }, signal),
storageSet: (input) => parent.transport.storageSet({ ...input, key: `${name}:${input.key}` }),
},
};
}, [handlerPrefix, name, parent]);
const scope = `${runtime.context.scope ?? ""}/${name}`;
return (
<WidgetContext.Provider
value={{
context: { ...runtime.context, scope, handlerPrefix: `${runtime.context.handlerPrefix ?? ""}${handlerPrefix}` },
services,
options: options ?? runtime.options,
}}
>
{children}
</WidgetContext.Provider>
);
}
function useWidgetRuntime() {
const runtime = useContext(WidgetContext);
if (!runtime) throw new Error("Widget SDK hooks require a Homarr widget host");
return runtime;
}
export function useWidgetHost() {
return useWidgetRuntime().context;
}
export function useWidgetServices() {
return useWidgetRuntime().services;
}
export function useWidgetOptions<T extends Record<string, unknown> = Record<string, unknown>>() {
return useWidgetRuntime().options as T;
}
function queryScope(context: WidgetHostContext) {
return ["custom-widget-sdk", context.revisionId, context.itemId ?? context.previewId, context.userId] as const;
}
interface WidgetQueryOptions {
enabled?: boolean;
refetchInterval?: number | false;
staleTime?: number;
}
export function useWidgetQuery<T = unknown>(name: string, input?: unknown, options: WidgetQueryOptions = {}) {
const { context, services } = useWidgetRuntime();
const itemId = context.itemId ?? context.previewId;
const query = useQuery<T>({
queryKey: [...queryScope(context), "query", context.scope, name, input],
queryFn: ({ signal }) => {
if (!itemId) throw new Error("Save this widget to run its server queries");
return services.transport.query({ itemId, name, input }, signal) as Promise<T>;
},
enabled: Boolean(itemId) && context.visible && options.enabled !== false,
refetchInterval: options.refetchInterval ?? false,
staleTime: options.staleTime ?? (typeof options.refetchInterval === "number" ? options.refetchInterval : 1_000),
retry: false,
});
if (isAccessError(query.error)) return { ...query, data: undefined };
return query;
}
function isAccessError(error: unknown) {
if (!error || typeof error !== "object" || !("data" in error)) return false;
const data = error.data;
if (!data || typeof data !== "object" || !("code" in data)) return false;
return data.code === "FORBIDDEN" || data.code === "UNAUTHORIZED" || data.code === "NOT_FOUND";
}
export function useWidgetAction<TOutput = unknown, TInput = unknown>(name: string) {
const { context, services } = useWidgetRuntime();
const queryClient = useQueryClient();
return useMutation<TOutput, Error, TInput>({
mutationFn: (input) => {
const itemId = context.itemId ?? context.previewId;
if (!itemId) throw new Error("Save this widget to run its server actions");
if (context.isEditMode || context.executionEnabled === false)
throw new Error("Widget actions are currently paused");
return services.transport.action({ itemId, name, input }) as Promise<TOutput>;
},
onSuccess: () => queryClient.invalidateQueries({ queryKey: queryScope(context) }),
});
}
/** Discover controls currently available to this viewer, including exact guest-approved inputs. */
export function useWidgetCapabilities() {
const host = useWidgetHost();
const query = useWidgetQuery<{ actions: Record<string, { allowed: boolean; allowedInputs?: unknown[] }> }>(
"$capabilities",
);
return {
...query,
canRun(name: string, input?: unknown) {
if (host.isEditMode || host.executionEnabled === false || query.error) return false;
const capability = query.data?.actions[`${host.handlerPrefix ?? ""}${name}`];
if (!capability?.allowed) return false;
if (!capability.allowedInputs) return true;
let effectiveInput = input;
if (effectiveInput === undefined) effectiveInput = {};
return capability.allowedInputs.some((allowed) => hashKey([allowed]) === hashKey([effectiveInput]));
},
};
}
export function useWidgetSubscription<T = unknown>(
name: string,
input?: unknown,
options: { enabled?: boolean; maximumEvents?: number } = {},
) {
const { context, services } = useWidgetRuntime();
const itemId = context.itemId ?? context.previewId;
const inputKey = hashKey([input]);
const inputRef = useRef(input);
inputRef.current = input;
let maximumEvents = 60;
if (options.maximumEvents !== undefined && Number.isFinite(options.maximumEvents))
maximumEvents = Math.max(1, Math.floor(options.maximumEvents));
const [attempt, setAttempt] = useState(0);
const enabled = Boolean(itemId) && context.visible && options.enabled !== false;
const [state, setState] = useWidgetState<{ data?: T; events: T[]; error?: Error; connected: boolean }>(
`subscription:${hashKey([context.revisionId, context.userId, name, inputKey])}`,
{ events: [], connected: false },
);
useEffect(() => {
setState((current) => ({ ...current, error: undefined, connected: false }));
if (!enabled || !itemId) return;
let active = true;
const unsubscribe = services.transport.subscribe(
{ itemId, name, input: inputRef.current },
{
next(value) {
if (!active) return;
setState((current) => ({
data: value as T,
events: Object.is(current.data, value)
? current.events
: [...current.events, value as T].slice(-maximumEvents),
connected: true,
}));
},
error(error) {
if (!active) return;
if (isAccessError(error)) setState({ events: [], error, connected: false });
else setState((current) => ({ ...current, error, connected: false }));
},
complete() {
if (active) setState((current) => ({ ...current, connected: false }));
},
},
);
return () => {
active = false;
unsubscribe();
};
}, [
attempt,
itemId,
context.revisionId,
context.userId,
enabled,
inputKey,
maximumEvents,
name,
services.transport,
setState,
]);
return { ...state, reconnect: () => setAttempt((current) => current + 1) };
}
export function createWidgetStateStore(values: Record<string, unknown> = {}): WidgetStateStore {
const listeners = new Set<() => void>();
return {
get: (key) => (Object.hasOwn(values, key) ? values[key] : undefined),
set(key, value) {
if (Object.hasOwn(values, key) && Object.is(values[key], value)) return;
Object.defineProperty(values, key, { value, enumerable: true, configurable: true, writable: true });
listeners.forEach((listener) => listener());
},
subscribe(listener) {
listeners.add(listener);
return () => listeners.delete(listener);
},
};
}
/** Instance state survives compact/advanced view changes without persisting secrets to a browser. */
export function useWidgetState<T>(key: string, initialValue: T | (() => T)): [T, Dispatch<SetStateAction<T>>] {
const { services } = useWidgetRuntime();
const [initial] = useState(initialValue);
const getSnapshot = useCallback(() => {
const value = services.state.get(key);
if (value === undefined) return initial;
return value as T;
}, [initial, key, services.state]);
const value = useSyncExternalStore(services.state.subscribe, getSnapshot, () => initial);
const setValue: Dispatch<SetStateAction<T>> = useCallback(
(next) => {
let nextValue = next;
if (typeof next === "function") nextValue = (next as (previous: T) => T)(getSnapshot());
services.state.set(key, nextValue);
},
[getSnapshot, key, services.state],
);
return [value, setValue];
}
/** Shared storage remains server-authorized; previews use an isolated temporary store. */
export function useWidgetStorage<T = unknown>(scope: WidgetStorageScope, key: string, initialValue: T) {
const { context, services } = useWidgetRuntime();
const itemId = context.itemId ?? context.previewId;
const queryClient = useQueryClient();
const queryKey = [...queryScope(context), "storage", context.scope, scope, key];
const query = useQuery({
queryKey,
queryFn: async ({ signal }) => {
if (!itemId) return initialValue;
const value = await services.transport.storageGet({ itemId, scope, key }, signal);
if (value === undefined || value === null) return initialValue;
return value as T;
},
enabled: Boolean(itemId) && context.executionEnabled !== false,
retry: false,
});
const mutation = useMutation({
mutationFn: (value: T) => {
if (!itemId || context.isEditMode || context.executionEnabled === false) {
throw new Error("Managed widget storage cannot be changed before saving or in board edit mode");
}
return services.transport.storageSet({ itemId, scope, key, value });
},
onSuccess: (_result, value) => queryClient.setQueryData(queryKey, value),
});
return {
...query,
data: isAccessError(query.error) ? initialValue : (query.data ?? initialValue),
set: mutation.mutateAsync,
saving: mutation.isPending,
saveError: mutation.error,
};
}
export function useWidgetCommands(commands: readonly WidgetCommand[]) {
const { services } = useWidgetRuntime();
const registerCommands = services.registerCommands;
const commandsRef = useRef(commands);
commandsRef.current = commands;
const descriptorKey = hashKey(commands.map(({ run: _run, ...command }) => command));
useEffect(
() =>
registerCommands(
commandsRef.current.map((command) => ({
...command,
run: () => commandsRef.current.find(({ id }) => id === command.id)?.run(),
})),
),
[descriptorKey, registerCommands],
);
}
/** Shared native/custom clock, aligned to real time boundaries to avoid accumulating drift. */
export function useWidgetNow(intervalMs = 1000, enabled = true) {
const [now, setNow] = useState<number | null>(null);
useEffect(() => {
if (!enabled) return;
let interval = 1000;
if (Number.isFinite(intervalMs)) interval = Math.max(16, intervalMs);
let timer: ReturnType<typeof setTimeout>;
const tick = () => {
setNow(Date.now());
timer = setTimeout(tick, interval - (Date.now() % interval));
};
setNow(Date.now());
timer = setTimeout(tick, interval - (Date.now() % interval));
return () => clearTimeout(timer);
}, [enabled, intervalMs]);
return now;
}
export function useWidgetClock(intervalMs = 1000) {
const { visible } = useWidgetHost();
return useWidgetNow(intervalMs, visible);
}
+29
View File
@@ -0,0 +1,29 @@
import sqlite from "../examples/sqlite.json";
import mqtt from "../examples/mqtt.json";
import clock from "../examples/clock.json";
import beszel from "../examples/beszel.json";
import timer from "../examples/timer.json";
import checklist from "../examples/checklist.json";
import downloads from "../examples/downloads.json";
import sonarr from "../examples/sonarr.json";
import rack from "../examples/rack.json";
import backup from "../examples/backup.json";
import household from "../examples/household.json";
import overview from "../examples/overview.json";
import media from "../examples/media.json";
export const widgetReferencePackages = {
sqlite,
mqtt,
clock,
beszel,
timer,
checklist,
downloads,
sonarr,
rack,
backup,
household,
overview,
media,
};
+5
View File
@@ -0,0 +1,5 @@
import type { ComponentType } from "react";
/** Compatibility exports are supplied by Homarr's host; new widgets should use the regular SDK. */
export declare const LegacyWidget: ComponentType<{ template: string; requestCapabilities?: unknown }>;
export declare const LegacyConfiguration: ComponentType<{ schema: unknown; parameterNames?: Record<string, string[]> }>;
+146
View File
@@ -0,0 +1,146 @@
"use client";
import type { Dispatch, SetStateAction } from "react";
import { useCallback, useEffect, useRef, useState } from "react";
interface StoredWidgetState {
version: number;
value: unknown;
}
interface UseLocalWidgetStateOptions<T> {
key: string | undefined;
version: number;
defaultValue: T | (() => T);
validate?: (value: unknown) => value is T;
migrate?: (value: unknown, storedVersion: number) => T | undefined;
}
const resolveDefaultValue = <T>(value: T | (() => T)): T =>
typeof value === "function" ? (value as () => T)() : value;
export const serializeLocalWidgetState = <T>(version: number, value: T): string => JSON.stringify({ version, value });
export const parseLocalWidgetState = <T>(
serialized: string,
version: number,
validate?: (value: unknown) => value is T,
migrate?: (value: unknown, storedVersion: number) => T | undefined,
): T | undefined => {
try {
const parsed: unknown = JSON.parse(serialized);
if (typeof parsed !== "object" || parsed === null || !("version" in parsed) || !("value" in parsed)) {
return undefined;
}
const stored = parsed as StoredWidgetState;
if (typeof stored.version !== "number") return undefined;
if (stored.version !== version) {
const migrated = migrate?.(stored.value, stored.version);
if (migrated === undefined || (validate && !validate(migrated))) return undefined;
return migrated;
}
if (validate && !validate(stored.value)) return undefined;
return stored.value as T;
} catch {
return undefined;
}
};
export const useLocalWidgetState = <T>({
key,
version,
defaultValue,
validate,
migrate,
}: UseLocalWidgetStateOptions<T>): [T, Dispatch<SetStateAction<T>>, () => void] => {
const defaultValueRef = useRef(defaultValue);
const validateRef = useRef(validate);
const migrateRef = useRef(migrate);
defaultValueRef.current = defaultValue;
validateRef.current = validate;
migrateRef.current = migrate;
const createDefaultValue = useCallback(() => resolveDefaultValue(defaultValueRef.current), []);
const [value, setValueState] = useState<T>(createDefaultValue);
const valueRef = useRef(value);
const setMemoryValue = useCallback((nextValue: T) => {
valueRef.current = nextValue;
setValueState(nextValue);
}, []);
const removeStoredValue = useCallback(() => {
if (!key) return;
try {
window.localStorage.removeItem(key);
} catch {
// Storage can be unavailable in private or restricted browser contexts.
}
}, [key]);
useEffect(() => {
if (!key) {
setMemoryValue(createDefaultValue());
return;
}
try {
const serialized = window.localStorage.getItem(key);
if (serialized === null) {
setMemoryValue(createDefaultValue());
return;
}
const parsed = parseLocalWidgetState(serialized, version, validateRef.current, migrateRef.current);
if (parsed === undefined) {
window.localStorage.removeItem(key);
setMemoryValue(createDefaultValue());
return;
}
setMemoryValue(parsed);
} catch {
setMemoryValue(createDefaultValue());
}
}, [createDefaultValue, key, setMemoryValue, version]);
useEffect(() => {
if (!key) return;
const handleStorage = (event: StorageEvent) => {
if (event.storageArea !== window.localStorage || event.key !== key) return;
if (event.newValue === null) {
setMemoryValue(createDefaultValue());
return;
}
const parsed = parseLocalWidgetState(event.newValue, version, validateRef.current, migrateRef.current);
if (parsed !== undefined) setMemoryValue(parsed);
};
window.addEventListener("storage", handleStorage);
return () => window.removeEventListener("storage", handleStorage);
}, [createDefaultValue, key, setMemoryValue, version]);
const setValue: Dispatch<SetStateAction<T>> = useCallback(
(nextValue) => {
const resolved =
typeof nextValue === "function" ? (nextValue as (previous: T) => T)(valueRef.current) : nextValue;
if (Object.is(resolved, valueRef.current)) return;
setMemoryValue(resolved);
if (key) {
try {
window.localStorage.setItem(key, serializeLocalWidgetState(version, resolved));
} catch {
// Keep the in-memory state usable when persistence is unavailable.
}
}
},
[key, setMemoryValue, version],
);
const resetValue = useCallback(() => {
removeStoredValue();
setMemoryValue(createDefaultValue());
}, [createDefaultValue, removeStoredValue, setMemoryValue]);
return [value, setValue, resetValue];
};
+173
View File
@@ -0,0 +1,173 @@
export type { WidgetJson, WidgetStorageScope } from "./shared";
export interface WidgetServerContext {
signal: AbortSignal;
instanceId: string;
boardId: string;
userId?: string;
sdk: {
invoke(operation: string, input: unknown): Promise<unknown>;
};
}
export type WidgetServerHandler<TInput = unknown, TOutput = unknown> = (
input: TInput,
context: WidgetServerContext,
) => TOutput | Promise<TOutput> | AsyncIterable<TOutput>;
/** The runtime invokes only manifest-declared handlers after authorizing the actor. */
export function defineWidgetServer<T extends Record<string, WidgetServerHandler<never>>>(handlers: T): T {
return handlers;
}
export interface WidgetIntegrationInput {
connection: string;
capability: string;
input?: unknown;
}
export interface WidgetConnectionRequest {
connection: string;
path?: string;
method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD";
query?: Record<string, string | number | boolean>;
headers?: Record<string, string>;
body?: unknown;
responseType?: "json" | "text" | "base64";
}
export interface WidgetConnectionResponse<T> {
data: T;
ok: boolean;
status: number;
contentType: string | null;
durationMs: number;
updatedAt: string;
}
/** Credentials, local DNS, timeout and TLS policy come from the named owner-bound connection. */
export function fetchWidgetConnection<T = unknown>(context: WidgetServerContext, input: WidgetConnectionRequest) {
return context.sdk.invoke("connection.fetch", input) as Promise<WidgetConnectionResponse<T>>;
}
export interface WidgetBoundConnection<TSettings = Record<string, unknown>> {
configuration: {
kind: "http" | "integration" | "service";
serviceType?: string;
settings?: TSettings;
baseUrl?: string;
browserUrl?: string;
timeoutMs: number;
tls?: { rejectUnauthorized: boolean; ca?: string; cert?: string };
[key: string]: unknown;
};
secrets: Record<string, string>;
}
/** Server handlers only. Use local connection settings and credentials with a Node library or native protocol. */
export async function getWidgetConnection<TSettings = Record<string, unknown>>(
context: WidgetServerContext,
input: { connection: string; serviceType?: string },
): Promise<WidgetBoundConnection<TSettings>> {
const connection = (await context.sdk.invoke("connection.get", {
connection: input.connection,
})) as WidgetBoundConnection<TSettings>;
if (
input.serviceType &&
(connection.configuration.kind !== "service" || connection.configuration.serviceType !== input.serviceType)
)
throw new Error(`Connection '${input.connection}' requires the '${input.serviceType}' service type`);
return connection;
}
export function getWidgetServerContext<TOptions extends Record<string, unknown> = Record<string, unknown>>(
context: WidgetServerContext,
) {
return context.sdk.invoke("widget.context", {}) as Promise<{
options: TOptions;
installationId: string;
bindingNames: string[];
isPreview: boolean;
}>;
}
export function callWidgetIntegration<T = unknown>(context: WidgetServerContext, input: WidgetIntegrationInput) {
return context.sdk.invoke("integration.call", input) as Promise<T>;
}
/** Bridges native streams across the worker boundary and releases them when the widget stops observing. */
export async function* subscribeWidgetIntegration<T = unknown>(
context: WidgetServerContext,
input: WidgetIntegrationInput,
): AsyncGenerator<T> {
context.signal.throwIfAborted();
const id = await context.sdk.invoke("integration.subscribe", input);
if (typeof id !== "string") throw new Error("The integration subscription returned an invalid identifier");
try {
while (!context.signal.aborted) {
const result = (await context.sdk.invoke("integration.next", { id })) as IteratorResult<T>;
if (result.done) return;
yield result.value;
}
} finally {
// Cleanup is best effort after a worker cancellation; preserve the original stream result/error.
await context.sdk.invoke("integration.unsubscribe", { id }).catch(() => undefined);
}
}
export interface WidgetRunnerInput {
connection: string;
handler: string;
input?: unknown;
}
async function runnerRequest<T>(context: WidgetServerContext, connection: string, path: string, body: unknown) {
const response = await fetchWidgetConnection<T & { error?: string }>(context, {
connection,
path,
method: "POST",
body,
});
if (!response.ok || response.data.error)
throw new Error(response.data.error ?? `Widget runner returned HTTP ${response.status}`);
return response.data;
}
/** Run an owner-installed package handler on a named remote runner connection. */
export async function callWidgetRunner<T = unknown>(context: WidgetServerContext, input: WidgetRunnerInput) {
const result = await runnerRequest<{ value: T }>(context, input.connection, "/invoke", {
handler: input.handler,
input: input.input,
instanceId: context.instanceId,
boardId: context.boardId,
userId: context.userId,
});
return result.value;
}
export async function* subscribeWidgetRunner<T = unknown>(
context: WidgetServerContext,
input: WidgetRunnerInput,
): AsyncGenerator<T> {
const { id } = await runnerRequest<{ id: string }>(context, input.connection, "/subscriptions/start", {
handler: input.handler,
input: input.input,
instanceId: context.instanceId,
boardId: context.boardId,
userId: context.userId,
});
try {
while (!context.signal.aborted) {
const result = await runnerRequest<{ done: boolean; values: T[] }>(
context,
input.connection,
"/subscriptions/next",
{ id },
);
for (const value of result.values) yield value;
if (result.done) return;
}
} finally {
await runnerRequest(context, input.connection, "/subscriptions/cancel", { id }).catch(() => undefined);
}
}
+96
View File
@@ -0,0 +1,96 @@
import type { ReactNode } from "react";
export type WidgetStorageScope = "user" | "instance" | "installation";
export type WidgetDisplayMode = "compact" | "advanced";
export type WidgetJson = null | boolean | number | string | WidgetJson[] | { [key: string]: WidgetJson };
export interface WidgetOperationInput {
itemId: string;
name: string;
input: unknown;
}
export interface WidgetStorageInput {
itemId: string;
scope: WidgetStorageScope;
key: string;
}
export interface WidgetSubscriptionObserver {
next(value: unknown): void;
error(error: Error): void;
complete(): void;
}
export interface WidgetTransport {
query(input: WidgetOperationInput, signal: AbortSignal): Promise<unknown>;
action(input: WidgetOperationInput): Promise<unknown>;
subscribe(input: WidgetOperationInput, observer: WidgetSubscriptionObserver): () => void;
storageGet(input: WidgetStorageInput, signal: AbortSignal): Promise<unknown>;
storageSet(input: WidgetStorageInput & { value: unknown }): Promise<unknown>;
}
export interface WidgetCommand {
id: string;
label: string;
description?: string;
disabled?: boolean;
hidden?: boolean;
destructive?: boolean;
run(): void | Promise<void>;
}
export interface WidgetHostContext {
sdkVersion: "1";
itemId?: string;
previewId?: string;
boardId?: string;
installationId?: string;
revisionId: string;
scope?: string;
handlerPrefix?: string;
displayMode: WidgetDisplayMode;
width: number;
height: number;
displayScale: number;
visibleWidth: number;
visibleHeight: number;
isEditMode: boolean;
isPreview: boolean;
visible: boolean;
/** False when an authoring preview preserves its last successful view without executing requests or controls. */
executionEnabled?: boolean;
/** Dashboard refresh setting; compatibility widgets use it for their declared load queries. */
refreshIntervalSeconds?: number;
locale: string;
timeZone: string;
colorScheme: "light" | "dark";
reducedMotion: boolean;
userId?: string;
}
export interface WidgetStateStore {
get(key: string): unknown;
set(key: string, value: unknown): void;
subscribe(listener: () => void): () => void;
}
export interface WidgetNotification {
title: string;
message?: string;
color?: string;
}
export interface WidgetHostServices {
transport: WidgetTransport;
state: WidgetStateStore;
registerCommands(commands: readonly WidgetCommand[]): () => void;
notify(notification: WidgetNotification): void;
navigate(href: string): void;
openAdvanced(): void;
closeAdvanced(): void;
openDetail(detail: { title: string; content: ReactNode }): void;
closeDetail(): void;
confirm(input: { title: string; message: string; destructive?: boolean }): Promise<boolean>;
updateOptions(options: Record<string, unknown>): Promise<void>;
}
+8
View File
@@ -0,0 +1,8 @@
export { HomarrDataTable } from "./table/homarr-data-table";
export {
parseColumnOrder,
parseColumnWidths,
usePersistedTableLayout,
useTableLayoutPersistence,
} from "./table/use-persisted-table-layout";
export type { DataTableColumn, DataTableProps, DataTableSortStatus } from "mantine-datatable";
@@ -0,0 +1,95 @@
.homarr-data-table,
.homarr-data-table .mantine-datatable-table,
.homarr-data-table .mantine-datatable-table thead,
.homarr-data-table .mantine-datatable-table tbody,
.homarr-data-table .mantine-datatable-table tfoot,
.homarr-data-table th,
.homarr-data-table td {
background-color: transparent !important;
}
.homarr-data-table .mantine-datatable-table tr {
background-color: transparent;
}
.homarr-data-table .mantine-datatable-table {
width: 100% !important;
max-width: 100%;
table-layout: fixed !important;
}
.homarr-data-table .mantine-datatable-table tbody tr:hover {
background-color: color-mix(in srgb, var(--mantine-color-default-hover) 40%, transparent) !important;
}
.homarr-data-table .mantine-datatable-scroll-area-scrollbar[data-state="visible"]:hover {
@mixin light {
background-color: var(--mantine-color-gray-0);
}
@mixin dark {
background-color: var(--mantine-color-dark-8);
}
}
.homarr-data-table th {
padding: 0;
white-space: nowrap;
background-color: color-mix(in srgb, var(--mantine-color-body) 60%, transparent) !important;
backdrop-filter: blur(8px);
}
.homarr-data-table td {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
/* Lets a cell's content (e.g. an oversized action icon) visually overflow its own box without
growing it - used to make a per-row icon look bigger without inflating row height, since the
icon is pulled out of flow via absolute positioning rather than actually being a bigger cell. */
.homarr-data-table td.docker-actions-cell {
overflow: visible;
}
.homarr-data-table td .mantine-Text-root,
.homarr-data-table td .mantine-Group-root {
white-space: nowrap;
flex-wrap: nowrap;
}
.homarr-data-table .mantine-datatable-header-cell-sortable-icon,
.homarr-data-table .mantine-datatable-header-cell-draggable-action-icon {
opacity: 0;
transition: opacity 150ms ease-out;
}
.homarr-data-table .mantine-datatable-header-cell-sortable-group {
gap: 0;
}
.homarr-data-table .mantine-datatable-header-cell-draggable-action-icon {
margin: 0;
}
.homarr-data-table .mantine-datatable-header-cell-sortable-unsorted-icon {
display: none;
}
.homarr-data-table .mantine-datatable-header-cell-draggable-action-icon svg,
.homarr-data-table .mantine-datatable-header-cell-sortable-text svg,
.homarr-data-table .mantine-datatable-header-cell-sortable-icon svg {
width: var(--mantine-font-size-md);
height: var(--mantine-font-size-md);
}
.homarr-data-table th:hover .mantine-datatable-header-cell-sortable-icon,
.homarr-data-table th:hover .mantine-datatable-header-cell-draggable-action-icon,
.homarr-data-table .mantine-datatable-header-cell-draggable-action-icon:focus-visible,
.homarr-data-table .mantine-datatable-header-cell-drag-over .mantine-datatable-header-cell-draggable-action-icon {
opacity: 1;
}
.homarr-data-table-row-cursor-default .mantine-datatable-context-menu-cursor {
cursor: default;
}
@@ -0,0 +1,2 @@
declare const stylesheet: string;
export default stylesheet;
@@ -0,0 +1,163 @@
"use client";
// Shared CSS is required by both native and package table consumers.
// eslint-disable-next-line import/no-unassigned-import
import "./homarr-data-table.css";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { DataTableColumn, DataTableProps } from "mantine-datatable";
import { DataTable } from "mantine-datatable";
import { scrollAreaDefaultProps } from "../ui-settings";
const fallbackColumnWidth = 60;
const getColumnWidth = (width: string | number | undefined): number => {
if (typeof width === "number" && Number.isFinite(width) && width > 0) return width;
if (typeof width === "string") {
const parsedWidth = Number.parseFloat(width);
if (Number.isFinite(parsedWidth) && parsedWidth > 0) return parsedWidth;
}
return fallbackColumnWidth;
};
type HomarrDataTableProps<T> = DataTableProps<T> & {
columns: DataTableColumn<T>[];
groups?: never;
isEditMode: boolean;
cellPadding: string;
rowCursor?: "auto" | "default";
};
export function HomarrDataTable<T>({
isEditMode,
cellPadding,
rowCursor = "auto",
className,
columns,
defaultColumnProps,
onMouseDownCapture,
scrollAreaProps,
style,
...props
}: HomarrDataTableProps<T>) {
const [resizePreviewWidths, setResizePreviewWidths] = useState<Record<string, number>>();
const removeResizeListeners = useRef<() => void>(() => undefined);
useEffect(() => () => removeResizeListeners.current(), []);
const handleMouseDownCapture = useCallback(
(event: React.MouseEvent<HTMLTableElement>) => {
onMouseDownCapture?.(event);
const target = event.target;
if (!(target instanceof Element)) return;
const handle = target.closest(".mantine-datatable-header-resizable-handle");
const currentCell = handle?.closest<HTMLTableCellElement>("th[data-accessor]");
const headerRow = currentCell?.parentElement;
if (!currentCell || !headerRow) return;
const cells = Array.from(headerRow.querySelectorAll<HTMLTableCellElement>("th[data-accessor]"));
const currentIndex = cells.indexOf(currentCell);
const nextCell = cells[currentIndex + 1];
const currentAccessor = currentCell.dataset.accessor;
const nextAccessor = nextCell?.dataset.accessor;
if (!nextCell || !currentAccessor || !nextAccessor) return;
const widths = Object.fromEntries(
cells.flatMap((cell) => {
const accessor = cell.dataset.accessor;
if (!accessor) return [];
return [[accessor, cell.getBoundingClientRect().width]];
}),
);
const currentWidth = widths[currentAccessor];
const nextWidth = widths[nextAccessor];
if (currentWidth === undefined || nextWidth === undefined) return;
const visualScale = currentCell.getBoundingClientRect().width / currentCell.offsetWidth;
const minimumWidth = fallbackColumnWidth * visualScale;
const startX = event.clientX;
removeResizeListeners.current();
const handleMouseMove = (moveEvent: MouseEvent) => {
const delta = Math.min(
nextWidth - minimumWidth,
Math.max(minimumWidth - currentWidth, moveEvent.clientX - startX),
);
setResizePreviewWidths({
...widths,
[currentAccessor]: currentWidth + delta,
[nextAccessor]: nextWidth - delta,
});
};
const handleResizeEnd = () => {
removeResizeListeners.current();
requestAnimationFrame(() => requestAnimationFrame(() => setResizePreviewWidths(undefined)));
};
removeResizeListeners.current = () => {
window.removeEventListener("mousemove", handleMouseMove);
window.removeEventListener("mouseup", handleResizeEnd);
window.removeEventListener("blur", handleResizeEnd);
};
window.addEventListener("mousemove", handleMouseMove);
window.addEventListener("mouseup", handleResizeEnd);
window.addEventListener("blur", handleResizeEnd);
},
[onMouseDownCapture],
);
const mergedClassName = [
"homarr-data-table",
rowCursor === "default" ? "homarr-data-table-row-cursor-default" : undefined,
className,
]
.filter(Boolean)
.join(" ");
const fittedColumns = useMemo(() => {
const visibleColumns = columns.filter(({ hidden }) => !hidden);
const getRenderedWidth = (column: DataTableColumn<T>) =>
resizePreviewWidths?.[String(column.accessor)] ?? getColumnWidth(column.width);
const totalWidth = visibleColumns.reduce((total, column) => total + getRenderedWidth(column), 0);
if (totalWidth <= 0) return columns;
return columns.map((column) => {
if (column.hidden) return column;
const width = `${(getRenderedWidth(column) / totalWidth) * 100}%`;
const fittedWidth = { width, minWidth: width, maxWidth: width };
const cellsStyle = column.cellsStyle ?? defaultColumnProps?.cellsStyle;
return {
...column,
titleStyle: [column.titleStyle, fittedWidth],
cellsStyle: (record: T, index: number) => [cellsStyle?.(record, index), fittedWidth, { padding: cellPadding }],
};
});
}, [cellPadding, columns, defaultColumnProps?.cellsStyle, resizePreviewWidths]);
return (
<DataTable<T>
withTableBorder={false}
borderRadius={0}
highlightOnHover
highlightOnHoverColor={{ dark: "dark.5", light: "gray.1" }}
verticalAlign="center"
loaderBackgroundBlur={2}
textSelectionDisabled
height="100%"
{...props}
striped={false}
columns={fittedColumns}
onMouseDownCapture={handleMouseDownCapture}
className={mergedClassName}
style={[{ pointerEvents: isEditMode ? "none" : undefined }, style]}
defaultColumnProps={{
...defaultColumnProps,
noWrap: defaultColumnProps?.noWrap ?? true,
draggable: true,
resizable: true,
cellsStyle: defaultColumnProps?.cellsStyle ?? (() => ({ padding: cellPadding })),
}}
scrollAreaProps={{ ...scrollAreaDefaultProps, ...scrollAreaProps }}
/>
);
}
@@ -0,0 +1,235 @@
"use client";
import { useCallback, useEffect, useMemo, useRef } from "react";
import type { DataTableColumn } from "mantine-datatable";
import { useDataTableColumns } from "mantine-datatable";
import { isRecord } from "@homarr/common";
interface TableLayoutOptions extends Record<string, unknown> {
columnOrder?: string;
columnWidths?: string;
}
interface PendingTableLayout {
layout: TableLayoutOptions;
onLayoutChange: (layout: TableLayoutOptions) => void;
storeKey: string;
}
interface UseTableLayoutPersistenceProps {
boardId: string | undefined;
hasChangeAccess: boolean;
itemId: string | undefined;
saveItemOptions: (input: { boardId: string; itemId: string; newOptions: TableLayoutOptions }) => void;
setOptions: (input: { newOptions: TableLayoutOptions }) => void;
}
interface UsePersistedTableLayoutProps<T> {
columns: DataTableColumn<T>[];
columnAccessors: readonly string[];
columnOrder: string;
columnWidths: string;
itemId: string | undefined;
storeKeyPrefix: string;
onLayoutChange: (layout: TableLayoutOptions) => void;
}
const layoutSaveDelay = 350;
export const useTableLayoutPersistence = ({
boardId,
hasChangeAccess,
itemId,
saveItemOptions,
setOptions,
}: UseTableLayoutPersistenceProps) =>
useCallback(
(newOptions: TableLayoutOptions) => {
setOptions({ newOptions });
if (hasChangeAccess && boardId && itemId) saveItemOptions({ boardId, itemId, newOptions });
},
[boardId, hasChangeAccess, itemId, saveItemOptions, setOptions],
);
const toPixelWidth = (width: string | number): number | undefined => {
if (typeof width === "number" && Number.isFinite(width) && width > 0) return width;
if (typeof width !== "string" || !width.endsWith("px")) return undefined;
const parsedWidth = Number.parseInt(width, 10);
return Number.isFinite(parsedWidth) && parsedWidth > 0 ? parsedWidth : undefined;
};
const getColumnWidthMap = (
columnsWidth: Record<string, string | number>[],
visibleAccessorSet: ReadonlySet<string>,
): Record<string, number> => {
const widths: Record<string, number> = {};
for (const entry of columnsWidth) {
for (const [accessor, width] of Object.entries(entry)) {
if (!visibleAccessorSet.has(accessor)) continue;
const pixelWidth = toPixelWidth(width);
if (pixelWidth !== undefined) widths[accessor] = pixelWidth;
}
}
return widths;
};
export const parseColumnOrder = (value: string, columnAccessors: readonly string[]): string[] => {
if (!value) return [];
try {
const parsed: unknown = JSON.parse(value);
if (!Array.isArray(parsed)) return [];
const allowed = new Set(columnAccessors);
return parsed.filter(
(accessor, index): accessor is string =>
typeof accessor === "string" && allowed.has(accessor) && parsed.indexOf(accessor) === index,
);
} catch {
return [];
}
};
export const parseColumnWidths = (value: string, columnAccessors: readonly string[]): Record<string, number> => {
if (!value) return {};
try {
const parsed: unknown = JSON.parse(value);
if (!isRecord(parsed)) return {};
const allowed = new Set(columnAccessors);
return Object.fromEntries(
Object.entries(parsed).filter(
(entry): entry is [string, number] =>
allowed.has(entry[0]) && typeof entry[1] === "number" && Number.isFinite(entry[1]) && entry[1] > 0,
),
);
} catch {
return {};
}
};
export const usePersistedTableLayout = <T>({
columns,
columnAccessors,
columnOrder,
columnWidths,
itemId,
storeKeyPrefix,
onLayoutChange,
}: UsePersistedTableLayoutProps<T>) => {
const savedOrder = useMemo(() => parseColumnOrder(columnOrder, columnAccessors), [columnAccessors, columnOrder]);
const savedWidths = useMemo(() => parseColumnWidths(columnWidths, columnAccessors), [columnAccessors, columnWidths]);
const visibleAccessors = useMemo(() => columns.map(({ accessor }) => String(accessor)), [columns]);
const visibleAccessorSet = useMemo(() => new Set(visibleAccessors), [visibleAccessors]);
const restoredOrder = useMemo(
() => [
...savedOrder.filter((accessor) => visibleAccessorSet.has(accessor)),
...visibleAccessors.filter((accessor) => !savedOrder.includes(accessor)),
],
[savedOrder, visibleAccessors, visibleAccessorSet],
);
const storeKey = `${storeKeyPrefix}-${itemId ?? "preview"}-${[...visibleAccessors].toSorted().join(",")}`;
const { effectiveColumns, columnsOrder, columnsWidth, setColumnsOrder, setMultipleColumnWidths } =
useDataTableColumns<T>({
key: storeKey,
columns,
});
const lastStoreKey = useRef(storeKey);
const hydrated = useRef(false);
const previousOrder = useRef(columnsOrder);
const previousWidths = useRef(columnsWidth);
useEffect(() => {
if (lastStoreKey.current !== storeKey) {
lastStoreKey.current = storeKey;
hydrated.current = false;
}
if (hydrated.current) return;
const orderMatches =
columnsOrder.length === restoredOrder.length &&
columnsOrder.every((accessor, index) => accessor === restoredOrder[index]);
const currentWidths = getColumnWidthMap(columnsWidth, visibleAccessorSet);
const visibleWidths = Object.entries(savedWidths).filter(([accessor]) => visibleAccessorSet.has(accessor));
const widthsMatch = visibleWidths.every(([accessor, width]) => currentWidths[accessor] === width);
if (orderMatches && widthsMatch) {
previousOrder.current = columnsOrder;
previousWidths.current = columnsWidth;
hydrated.current = true;
return;
}
if (!orderMatches) setColumnsOrder(restoredOrder);
if (!widthsMatch) {
setMultipleColumnWidths(visibleWidths.map(([accessor, width]) => ({ accessor, width })));
}
}, [
columnsOrder,
columnsWidth,
restoredOrder,
savedWidths,
setColumnsOrder,
setMultipleColumnWidths,
storeKey,
visibleAccessorSet,
]);
const pendingLayout = useRef<PendingTableLayout | undefined>(undefined);
const saveTimeout = useRef<number | undefined>(undefined);
const flushPendingLayout = useCallback(() => {
const pending = pendingLayout.current;
pendingLayout.current = undefined;
window.clearTimeout(saveTimeout.current);
saveTimeout.current = undefined;
if (pending) pending.onLayoutChange(pending.layout);
}, []);
useEffect(() => {
if (pendingLayout.current && pendingLayout.current.storeKey !== storeKey) flushPendingLayout();
}, [flushPendingLayout, storeKey]);
useEffect(() => () => flushPendingLayout(), [flushPendingLayout]);
useEffect(() => {
if (!hydrated.current) return;
const orderChanged = JSON.stringify(columnsOrder) !== JSON.stringify(previousOrder.current);
const widthsChanged = JSON.stringify(columnsWidth) !== JSON.stringify(previousWidths.current);
previousOrder.current = columnsOrder;
previousWidths.current = columnsWidth;
if (!orderChanged && !widthsChanged) return;
const newLayout: TableLayoutOptions = {};
if (orderChanged) {
const fullOrder = [...savedOrder, ...columnAccessors.filter((accessor) => !savedOrder.includes(accessor))];
const reorderedVisibleColumns = [...columnsOrder];
const mergedOrder = fullOrder.map((accessor) =>
visibleAccessorSet.has(accessor) ? (reorderedVisibleColumns.shift() ?? accessor) : accessor,
);
newLayout.columnOrder = JSON.stringify(mergedOrder);
}
if (widthsChanged) {
const widthMap: Record<string, number> = { ...savedWidths };
Object.assign(widthMap, getColumnWidthMap(columnsWidth, visibleAccessorSet));
newLayout.columnWidths = JSON.stringify(widthMap);
}
if (pendingLayout.current && pendingLayout.current.storeKey !== storeKey) flushPendingLayout();
pendingLayout.current = pendingLayout.current
? { ...pendingLayout.current, layout: { ...pendingLayout.current.layout, ...newLayout } }
: { layout: newLayout, onLayoutChange, storeKey };
window.clearTimeout(saveTimeout.current);
saveTimeout.current = window.setTimeout(flushPendingLayout, layoutSaveDelay);
}, [
columnAccessors,
columnsOrder,
columnsWidth,
flushPendingLayout,
onLayoutChange,
savedOrder,
savedWidths,
storeKey,
visibleAccessorSet,
]);
return { effectiveColumns, storeKey };
};
@@ -0,0 +1,27 @@
"use client";
import { useParams } from "next/navigation";
import { useSuspenseQuery } from "@tanstack/react-query";
import type { MRT_RowData, MRT_TableOptions } from "mantine-react-table";
import { useMantineReactTable } from "mantine-react-table";
import type { SupportedLanguage } from "@homarr/translation";
import { localeConfigurations } from "@homarr/translation";
export const useTranslatedMantineReactTable = <TData extends MRT_RowData>(
tableOptions: Omit<MRT_TableOptions<TData>, "localization">,
) => {
const { locale } = useParams<{ locale: SupportedLanguage }>();
const { data: mantineReactTable } = useSuspenseQuery({
queryKey: ["mantine-react-table-locale", locale],
// eslint-disable-next-line no-restricted-syntax
queryFn: async () => {
return await localeConfigurations[locale].importMrtLocalization();
},
});
return useMantineReactTable<TData>({
...tableOptions,
localization: mantineReactTable,
});
};
+6
View File
@@ -0,0 +1,6 @@
export const scrollAreaDefaultProps = {
type: "hover",
scrollbarSize: 2,
scrollHideDelay: 500,
offsetScrollbars: true,
} as const;
+42
View File
@@ -0,0 +1,42 @@
"use client";
import type { PropsWithChildren, ReactNode } from "react";
import { Alert, Center, Loader, Stack, Text } from "@mantine/core";
export { ActionIcon, Badge, Box, Button, Card, Group, SimpleGrid, Stack, Table, Text, Title } from "@mantine/core";
export function WidgetEmptyState({ children }: PropsWithChildren) {
return (
<Center h="100%">
<Text c="dimmed" size="sm" ta="center">
{children}
</Text>
</Center>
);
}
export function WidgetLoading({ label }: { label?: string }) {
return (
<Center h="100%">
<Stack align="center" gap="xs">
<Loader size="sm" />
{label && <Text size="sm">{label}</Text>}
</Stack>
</Center>
);
}
export function WidgetError({ children, title, action }: PropsWithChildren<{ title?: string; action?: ReactNode }>) {
return (
<Alert color="red" title={title}>
{children}
{action}
</Alert>
);
}
export { HomarrDataTable, usePersistedTableLayout, useTableLayoutPersistence } from "./table";
export type { DataTableColumn, DataTableProps, DataTableSortStatus } from "./table";
export { MantineReactTable } from "mantine-react-table";
export type { MRT_ColumnDef, MRT_TableOptions } from "mantine-react-table";
export { useTranslatedMantineReactTable } from "./table/use-translated-mantine-react-table";
+8
View File
@@ -0,0 +1,8 @@
{
"extends": "@homarr/tsconfig/base.json",
"compilerOptions": {
"tsBuildInfoFile": "node_modules/.cache/tsbuildinfo.json"
},
"include": ["src"],
"exclude": ["node_modules"]
}