Skip to content

A modern and easy to use dashboard. 80+ integrations. 20K+ icons built in. Authentication out of the box. No YAML, drag and drop configuration.

feat(widgets): rework downloads widget with mantine-datatable (#6430)

Thomas906c9f11faa3
diff --git a/.cursor/rules/mantine-datatable-migration.mdc b/.cursor/rules/mantine-datatable-migration.mdc
new file mode 100644
index 000000000..08d2b8202
--- /dev/null
+++ b/.cursor/rules/mantine-datatable-migration.mdc
@@ -0,0 +1,622 @@
+# Migrating Tables from mantine-react-table to mantine-datatable
+
+This document captures every pattern, fix, and decision from the downloads widget rework (PR #6430). Use it as a playbook when porting other tables.
+
+## Migration Candidates
+
+Current `mantine-react-table` consumers that could be migrated:
+
+**Widgets (in `packages/widgets/`):**
+- `docker/component.tsx` — Docker container table
+- `media-server/component.tsx` — Media server sessions
+
+**Admin pages (in `apps/nextjs/src/app/[locale]/manage/`):**
+- `tools/docker/docker-table.tsx`
+- `tools/tasks/_components/tasks-table.tsx`
+- `tools/api/components/api-keys.tsx`
+- `users/_components/user-list.tsx`
+- `users/invites/_components/invite-list.tsx`
+- `tools/kubernetes/` — 8 Kubernetes resource tables
+
+**Modals:**
+- `packages/modals-collection/src/search-engines/request-media-modal.tsx`
+
+**Shared hook to remove once all migrated:**
+- `packages/ui/src/hooks/use-translated-mantine-react-table.ts`
+
+---
+
+## 1. Core Migration: mantine-react-table → mantine-datatable
+
+### Import changes
+
+```typescript
+// BEFORE
+import { MantineReactTable, useMantineReactTable } from "mantine-react-table";
+import type { MRT_ColumnDef } from "mantine-react-table";
+
+// AFTER
+import { DataTable, useDataTableColumns } from "mantine-datatable";
+import type { DataTableColumn, DataTableSortStatus } from "mantine-datatable";
+```
+
+### Column definition shape
+
+```typescript
+// BEFORE (MRT)
+const columns: MRT_ColumnDef<MyRow>[] = [
+ {
+ accessorKey: "name",
+ header: "Name",
+ size: 200,
+ enableSorting: true,
+ Cell: ({ row }) => <Text>{row.original.name}</Text>,
+ },
+];
+
+// AFTER (mantine-datatable)
+const columns: DataTableColumn<MyRow>[] = [
+ {
+ accessor: "name", // not accessorKey
+ title: "Name", // not header
+ width: 200, // not size
+ sortable: true, // not enableSorting
+ render: (record) => <Text>{record.name}</Text>, // not Cell
+ },
+];
+```
+
+Key differences:
+- `accessorKey` → `accessor`
+- `header` → `title`
+- `size` → `width`
+- `Cell: ({ row }) =>` → `render: (record) =>`
+- `enableSorting` → `sortable`
+- `enableColumnActions` → does not exist (no column action menus)
+- `mantineTableBodyCellProps` → `cellsStyle` in `defaultColumnProps`
+
+### Table component
+
+```typescript
+// BEFORE
+const table = useTranslatedMantineReactTable({ columns, data, ... });
+return <MantineReactTable table={table} />;
+
+// AFTER
+return (
+ <DataTable
+ records={data}
+ columns={columns}
+ sortStatus={sortStatus}
+ onSortStatusChange={setSortStatus}
+ ...
+ />
+);
+```
+
+### Sorting is manual
+
+mantine-datatable does NOT sort for you. You must sort the data yourself:
+
+```typescript
+const [sortStatus, setSortStatus] = useState<DataTableSortStatus<MyRow>>({
+ columnAccessor: "name",
+ direction: "asc",
+});
+
+const sortedData = useMemo(() => {
+ const mult = sortStatus.direction === "desc" ? -1 : 1;
+ return [...data].toSorted((a, b) => {
+ const aVal = a[sortStatus.columnAccessor];
+ const bVal = b[sortStatus.columnAccessor];
+ if (typeof aVal === "string") return aVal.localeCompare(bVal as string) * mult;
+ return ((aVal as number) - (bVal as number)) * mult;
+ });
+}, [data, sortStatus]);
+
+// Pass sortedData to records, not data
+<DataTable records={sortedData} sortStatus={sortStatus} onSortStatusChange={setSortStatus} />
+```
+
+---
+
+## 2. Making Tables Transparent (Widget Context)
+
+Widgets sit inside board cards that have user-controlled opacity. The table must be fully transparent so the card background shows through. mantine-datatable defaults to `var(--mantine-color-body)` which is opaque.
+
+Create a CSS file alongside the component:
+
+```css
+/* styles.css */
+.my-table,
+.my-table .mantine-datatable-table,
+.my-table .mantine-datatable-table thead,
+.my-table .mantine-datatable-table tbody,
+.my-table .mantine-datatable-table tfoot,
+.my-table th,
+.my-table td {
+ background-color: transparent !important;
+}
+
+.my-table .mantine-datatable-table tr {
+ background-color: transparent;
+}
+
+/* Hover: translucent instead of opaque */
+.my-table .mantine-datatable-table tbody tr:hover {
+ background-color: color-mix(in srgb, var(--mantine-color-default-hover) 40%, transparent) !important;
+}
+
+/* Headers: frosted glass effect */
+.my-table th {
+ white-space: nowrap;
+ background-color: color-mix(in srgb, var(--mantine-color-body) 60%, transparent) !important;
+ backdrop-filter: blur(8px);
+}
+
+/* Cell overflow */
+.my-table td {
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+/* Hide sort icon until hover */
+.my-table .mantine-datatable-header-cell-sortable-icon {
+ opacity: 0;
+ transition: opacity 150ms;
+}
+.my-table th:hover .mantine-datatable-header-cell-sortable-icon {
+ opacity: 1;
+}
+
+/* Row expansion area */
+.my-table .mantine-datatable-row-expansion-cell {
+ background-color: color-mix(in srgb, var(--mantine-color-body) 40%, transparent) !important;
+}
+```
+
+Import it: `import "./styles.css";` and apply via `className="my-table"`.
+
+---
+
+## 3. Responsive Column Visibility
+
+Use a lookup table of width breakpoints instead of media queries. The widget receives `width` as a prop.
+
+```typescript
+interface SizeConfig {
+ fontSize: "xs" | "sm";
+ iconSize: number;
+ cellPadding: number;
+ showSpeedColumns: boolean;
+ showTimeColumn: boolean;
+ showStateColumn: boolean;
+}
+
+const SIZE_BREAKPOINTS: { maxWidth: number; config: SizeConfig }[] = [
+ { maxWidth: 300, config: { fontSize: "xs", iconSize: 12, cellPadding: 2, showSpeedColumns: false, showTimeColumn: false, showStateColumn: false } },
+ { maxWidth: 500, config: { fontSize: "xs", iconSize: 14, cellPadding: 4, showSpeedColumns: false, showTimeColumn: true, showStateColumn: false } },
+];
+
+const DEFAULT_SIZE_CONFIG: SizeConfig = { fontSize: "sm", iconSize: 14, cellPadding: 4, showSpeedColumns: true, showTimeColumn: true, showStateColumn: true };
+
+function getSizeConfig(width: number): SizeConfig {
+ for (const { maxWidth, config } of SIZE_BREAKPOINTS) {
+ if (width < maxWidth) return config;
+ }
+ return DEFAULT_SIZE_CONFIG;
+}
+
+// Usage: memoize it
+const size = useMemo(() => getSizeConfig(width), [width]);
+```
+
+Then use a visibility check lookup table for columns:
+
+```typescript
+const columnVisibilityChecks: Partial<Record<string, (ctx: ColumnContext) => boolean>> = {
+ upSpeed: (ctx) => ctx.hasTorrents && ctx.size.showSpeedColumns,
+ downSpeed: (ctx) => ctx.size.showSpeedColumns,
+ time: (ctx) => ctx.size.showTimeColumn,
+ state: (ctx) => ctx.size.showStateColumn,
+};
+
+function shouldIncludeColumn(accessor: string, ctx: ColumnContext): boolean {
+ if (!ctx.optionsColumnSet.has(accessor)) return false;
+ const check = columnVisibilityChecks[accessor];
+ if (check && !check(ctx)) return false;
+ return true;
+}
+```
+
+---
+
+## 4. Column Persistence (Drag/Resize → Server)
+
+`useDataTableColumns` stores column order and widths in localStorage by default. For widgets, this must persist server-side so it works across devices.
+
+### Hidden widget options
+
+In `index.ts`, add hidden text options:
+
+```typescript
+columnOrder: factory.text({ defaultValue: "" }),
+columnWidths: factory.text({ defaultValue: "" }),
+```
+
+With visibility override:
+
+```typescript
+{
+ columnOrder: { shouldHide: () => true },
+ columnWidths: { shouldHide: () => true },
+}
+```
+
+### Translation keys required
+
+Even hidden options need translation keys or the translation test fails:
+
+```json
+"widget.mywidget.option.columnOrder.label": "Column order",
+"widget.mywidget.option.columnWidths.label": "Column widths"
+```
+
+### Old-import mappings
+
+Add to `packages/old-import/src/widgets/options.ts`:
+
+```typescript
+columnOrder: () => undefined,
+columnWidths: () => undefined,
+```
+
+### Dynamic storeKey
+
+Use a key that includes `itemId` and sorted column names. This prevents cross-widget localStorage bleeding:
+
+```typescript
+const storeKey = `mytable-${itemId ?? "preview"}-${[...options.columns].toSorted().join(",")}`;
+```
+
+### Hydration from server → localStorage
+
+On mount, seed `useDataTableColumns` with server-persisted values. Use a `hydrated` ref to prevent the persist effect from immediately writing defaults back:
+
+```typescript
+const { effectiveColumns, columnsOrder, columnsWidth, setColumnsOrder, setMultipleColumnWidths } =
+ useDataTableColumns<MyRow>({ key: storeKey, columns });
+
+const lastStoreKey = useRef(storeKey);
+const hydrated = useRef(false);
+
+useEffect(() => {
+ if (lastStoreKey.current !== storeKey) {
+ lastStoreKey.current = storeKey;
+ hydrated.current = false;
+ }
+ if (hydrated.current) return;
+ if (savedOrder.length > 0) setColumnsOrder(savedOrder);
+ if (Object.keys(savedWidths).length > 0) {
+ setMultipleColumnWidths(
+ Object.entries(savedWidths).map(([accessor, w]) => ({ accessor, width: w })),
+ );
+ }
+ requestAnimationFrame(() => { hydrated.current = true; });
+}, [storeKey, savedOrder, savedWidths, setColumnsOrder, setMultipleColumnWidths]);
+```
+
+### Persist localStorage → server
+
+Watch for changes and write back:
+
+```typescript
+const prevOrder = useRef(columnsOrder);
+const prevWidths = useRef(columnsWidth);
+
+useEffect(() => {
+ if (!hydrated.current) return;
+ const orderChanged = JSON.stringify(columnsOrder) !== JSON.stringify(prevOrder.current);
+ const widthsChanged = JSON.stringify(columnsWidth) !== JSON.stringify(prevWidths.current);
+ prevOrder.current = columnsOrder;
+ prevWidths.current = columnsWidth;
+
+ if (!orderChanged && !widthsChanged) return;
+
+ if (orderChanged) persistOption({ columnOrder: JSON.stringify(columnsOrder) });
+ if (widthsChanged) {
+ const widthMap: Record<string, number> = {};
+ for (const entry of columnsWidth) {
+ const key = Object.keys(entry)[0];
+ if (!key) continue;
+ const w = entry[key as keyof typeof entry];
+ if (typeof w === "number") widthMap[key] = w;
+ else if (typeof w === "string" && w.endsWith("px")) widthMap[key] = parseInt(w, 10);
+ }
+ persistOption({ columnWidths: JSON.stringify(widthMap) });
+ }
+}, [columnsOrder, columnsWidth, persistOption]);
+```
+
+The `persistOption` helper calls both `setOptions` (local state) and `saveItemOptions` (server mutation).
+
+---
+
+## 5. Context Menu (Right-Click)
+
+Do NOT install `mantine-contextmenu`. Use Mantine's `Menu` + `Portal` directly:
+
+```typescript
+interface ContextMenuState {
+ x: number;
+ y: number;
+ item: MyRow;
+}
+
+const [contextMenu, setContextMenu] = useState<ContextMenuState | null>(null);
+
+const handleContextMenu = useCallback(
+ ({ record, event }: { record: MyRow; event: React.MouseEvent }) => {
+ event.preventDefault();
+ setContextMenu({ x: event.clientX, y: event.clientY, item: record });
+ },
+ [],
+);
+
+// On DataTable:
+<DataTable onRowContextMenu={handleContextMenu} />
+
+// Render:
+{contextMenu && <RowContextMenu state={contextMenu} onClose={closeContextMenu} />}
+```
+
+The menu component uses `Portal` for correct z-index:
+
+```tsx
+function RowContextMenu({ state, onClose }: { state: ContextMenuState; onClose: () => void }) {
+ return (
+ <Portal>
+ <Menu opened onClose={onClose} closeOnItemClick={false} position="right-start" offset={0}>
+ <Menu.Target>
+ <Box style={{ position: "fixed", left: state.x, top: state.y, width: 0, height: 0 }} />
+ </Menu.Target>
+ <Menu.Dropdown>
+ <Menu.Item onClick={() => { /* action */ onClose(); }}>Action</Menu.Item>
+ </Menu.Dropdown>
+ </Menu>
+ </Portal>
+ );
+}
+```
+
+**Key fix:** Use `closeOnItemClick={false}` if any menu item needs a two-step confirmation (like delete → confirm). Close the menu on scroll: `onScroll={() => { if (contextMenu) closeContextMenu(); }}`.
+
+---
+
+## 6. Row Expansion
+
+```typescript
+<DataTable
+ rowExpansion={{
+ trigger: "click",
+ allowMultiple: true,
+ collapseProps: {
+ transitionDuration: 200,
+ animateOpacity: true,
+ transitionTimingFunction: "ease-out",
+ },
+ content: ({ record, collapse }) => <ExpandedRow item={record} collapse={collapse} />,
+ }}
+/>
+```
+
+**Critical:** Do NOT set `onRowClick` when using `rowExpansion` with `trigger: "click"`. They conflict and the expansion won't work.
+
+---
+
+## 7. Common Pitfalls & Fixes
+
+### Status indicator dots
+
+Don't use `<Badge variant="dot" />` without children — it renders a pill with empty space. Use a plain `Box`:
+
+```tsx
+<Box
+ w={8}
+ h={8}
+ style={{
+ borderRadius: "50%",
+ backgroundColor: `var(--mantine-color-${color}-filled)`,
+ flexShrink: 0,
+ }}
+/>
+```
+
+### Tooltip overflow on long text columns
+
+When a column has `ellipsis: true`, the tooltip target element can still extend beyond the cell bounds if inner elements don't clip. Fix:
+
+```tsx
+<Tooltip position="bottom-start" ...>
+ <Group style={{ overflow: "hidden" }}>
+ ...
+ </Group>
+</Tooltip>
+```
+
+Use `position="bottom-start"` instead of `position="right"` so the tooltip never escapes the widget horizontally.
+
+### Dark mode tooltips
+
+Mantine tooltips default to the theme's tooltip color which may be white in light mode and stay white in dark mode. Always set `color="dark"` on informational tooltips inside widgets.
+
+### Division by zero
+
+Guard all ratio calculations:
+
+```typescript
+if (item.size > 0) ratio = item.sent / item.size;
+if (totalDown > 0) ratio = totalUp / totalDown;
+```
+
+### Composite idAccessor
+
+When rows can come from multiple integrations, IDs may collide. Use a composite key:
+
+```typescript
+idAccessor={(record) => `${record.integration.id}:${record.id}`}
+```
+
+### JSON option parsing
+
+Always wrap in try/catch:
+
+```typescript
+function parseJsonOption<T>(value: string | undefined, fallback: T): T {
+ if (!value) return fallback;
+ try { return JSON.parse(value) as T; }
+ catch { return fallback; }
+}
+```
+
+### Clipboard API
+
+`navigator.clipboard.writeText()` can throw in non-HTTPS contexts. Always catch:
+
+```typescript
+void navigator.clipboard.writeText(text).catch(() => {});
+```
+
+### Sync sortStatus with widget options
+
+If the widget has configurable default sort, sync it:
+
+```typescript
+useEffect(() => {
+ setSortStatus({ columnAccessor: options.defaultSort, direction: defaultSortDirection });
+}, [options.defaultSort, defaultSortDirection]);
+```
+
+---
+
+## 8. Accessibility
+
+- All `ActionIcon` components need `aria-label`
+- Filter toggles (client badges, status badges) need `aria-pressed={isActive}`
+- `textSelectionDisabled` on DataTable prevents accidental text selection during drag/resize
+
+---
+
+## 9. Error Handling
+
+- Every mutation needs an `onError` callback with `showErrorNotification`
+- The `saveItemOptions` mutation (column persistence) also needs `onError`
+- Check `isError` on the main query and show a fallback UI
+- Use a shared `mutationOptions` object to avoid repeating `onSettled`/`onError`:
+
+```typescript
+const mutationOptions = {
+ onSettled: () => void utils.myQuery.invalidate(),
+ onError: () => showErrorNotification({ title: t("errors.actionFailed"), message: t("errors.actionFailedMessage") }),
+};
+```
+
+---
+
+## 10. i18n
+
+- No hardcoded strings. Every user-visible string goes through `useScopedI18n`
+- Column titles: `t("items.{accessor}.columnTitle")`
+- Detail labels: `t("items.{accessor}.detailsTitle")`
+- States: `t("states.{state}")`
+- Actions: `t("actions.{action}")`
+- Errors: `t("errors.{errorKey}")`
+- Hidden options still need `.label` translation keys
+
+---
+
+## 11. Edit Mode
+
+Disable pointer events on the table during edit mode to prevent conflicts with the board's drag-and-drop:
+
+```typescript
+let tablePointerEvents: React.CSSProperties["pointerEvents"];
+if (isEditMode) tablePointerEvents = "none";
+
+let rowContextMenuHandler = handleContextMenu;
+if (isEditMode) rowContextMenuHandler = undefined;
+
+<DataTable style={{ pointerEvents: tablePointerEvents }} />
+```
+
+---
+
+## 12. DataTable Props Reference (Commonly Used)
+
+```typescript
+<DataTable
+ records={sortedData}
+ columns={effectiveColumns}
+ storeColumnsKey={storeKey}
+ withTableBorder={false}
+ borderRadius={0}
+ highlightOnHover
+ striped="odd"
+ stripedColor={{ dark: "dark.7", light: "gray.0" }}
+ highlightOnHoverColor={{ dark: "dark.5", light: "gray.1" }}
+ verticalAlign="center"
+ fetching={isFetching && data.length === 0}
+ loaderBackgroundBlur={2}
+ fz={size.fontSize}
+ textSelectionDisabled
+ sortStatus={sortStatus}
+ onSortStatusChange={setSortStatus}
+ noRecordsText={t("errors.noItems")}
+ idAccessor={(record) => record.uniqueKey}
+ height="100%"
+ className="my-table"
+ defaultColumnProps={{
+ noWrap: true,
+ draggable: true,
+ resizable: true,
+ cellsStyle: () => ({ padding: `${size.cellPadding}px 8px` }),
+ }}
+ scrollAreaProps={{ type: "auto", scrollbarSize: 6 }}
+ rowBackgroundColor={(record) => conditionalBgMap[record.state]}
+ onRowContextMenu={handleContextMenu}
+ rowExpansion={{ ... }}
+ onScroll={() => { if (contextMenu) closeContextMenu(); }}
+/>
+```
+
+---
+
+## 13. Layout Stability
+
+- Don't use `table-layout: fixed` — it fights mantine-datatable's resize logic
+- Give non-name columns explicit `width` values so only the name column flexes
+- Use `ellipsis: true` on the name column — it handles `text-overflow: ellipsis` internally
+- Names should truncate at the cell boundary, not a character count, so the layout is stable regardless of content length
+- `flexShrink: 0` on badges/icons prevents them from being squeezed by long names
+
+---
+
+## 14. Checklist for Each Migration
+
+1. Replace imports (`mantine-react-table` → `mantine-datatable`)
+2. Convert column definitions (`accessorKey` → `accessor`, `header` → `title`, `Cell` → `render`, etc.)
+3. Implement manual sorting with `useState` + `useMemo`
+4. Add CSS file for transparent backgrounds (if widget context)
+5. Add responsive column visibility (if widget context)
+6. Add hidden options + hydration logic (if column persistence needed)
+7. Add old-import mappings for new options
+8. Add translation keys (including hidden option labels)
+9. Add context menu if row actions exist
+10. Add row expansion if detail view exists
+11. Add error handling on all mutations
+12. Add accessibility attributes
+13. Test at multiple widget widths
+14. Update docs in `apps/docs/docs/widgets/` if applicable
+15. Run `pnpm turbo typecheck` — catches old-import mismatches
+16. Run translation spec — catches missing keys
diff --git a/apps/docs/docs/widgets/downloads/img/context-menu.png b/apps/docs/docs/widgets/downloads/img/context-menu.png
new file mode 100644
index 000000000..350051d00
Binary files /dev/null and b/apps/docs/docs/widgets/downloads/img/context-menu.png differ
diff --git a/apps/docs/docs/widgets/downloads/img/screenshot.png b/apps/docs/docs/widgets/downloads/img/screenshot.png
index c6cdde381..8ef3a1701 100644
Binary files a/apps/docs/docs/widgets/downloads/img/screenshot.png and b/apps/docs/docs/widgets/downloads/img/screenshot.png differ
diff --git a/apps/docs/docs/widgets/downloads/index.mdx b/apps/docs/docs/widgets/downloads/index.mdx
index 9242a84eb..000fd066b 100644
--- a/apps/docs/docs/widgets/downloads/index.mdx
+++ b/apps/docs/docs/widgets/downloads/index.mdx
@@ -4,6 +4,7 @@ description: 'Allows you to view and manage your Downloads from both Torrent and
hide_title: true
---
+import { aria2Integration } from '@site/docs/integrations/aria2';
import { delugeIntegration } from '@site/docs/integrations/deluge';
import { nzbgetIntegration } from '@site/docs/integrations/nzbget';
import { qBittorentIntegration } from '@site/docs/integrations/q-bittorent';
@@ -14,9 +15,6 @@ import { AddingWidget } from '@site/src/components/widgets/adding';
import { WidgetConfig } from '@site/src/components/widgets/configuration';
import { WidgetHeader } from '@site/src/components/widgets/header';
import { WidgetIntegrations } from '@site/src/components/widgets/integrations';
-import { IconAd } from "@tabler/icons-react";
-import TabItem from '@theme/TabItem';
-import Tabs from '@theme/Tabs';
import { downloadsWidget } from '.';
@@ -25,16 +23,37 @@ import { downloadsWidget } from '.';
categories={['Torrent client', 'Usenet client', 'Downloads']}
/>
-This widget displays a list of torrents or usenet-articles that are currently being downloaded, along with their progress and other relevant information.
+This widget displays a list of torrents or usenet-articles that are currently being downloaded, along with their progress and other relevant information. It supports 7 download client integrations and provides a rich, responsive table interface.
### Screenshots
import downloadsCard from './img/screenshot.png';
+import contextMenuImg from './img/context-menu.png';
<div>
- <img src={downloadsCard} alt="downloads" width={128 * 4} />
+ <img src={downloadsCard} alt="Downloads widget showing torrent and usenet items" width={128 * 4} />
</div>
+#### Right-click context menu
+
+<div>
+ <img src={contextMenuImg} alt="Downloads widget context menu with pause, delete, and copy actions" width={128 * 4} />
+</div>
+
+### Features
+
+- **Responsive table** — columns automatically adapt to widget width, hiding less important columns at smaller sizes
+- **Sortable columns** — click any column header to sort ascending/descending
+- **Column customization** — choose which columns to display via the widget options panel
+- **Right-click context menu** — pause, resume, delete downloads, or copy download names directly from the context menu
+- **Row expansion** — click any row to see full details inline without opening a separate modal
+- **Hover tooltips** — hover a download name to see size, speeds, ETA, ratio, and category
+- **Global stats bar** — toggle a summary bar showing queue progress, total size, speeds, ratio, and per-state counts
+- **Client filtering** — filter downloads by integration or status using the footer filter panel
+- **Global controls** — pause/resume all downloads across all clients from the footer bar
+- **Status indicators** — color-coded badges show download state at a glance
+- **Speed overview** — total download and upload speeds displayed in the footer
+
### Supported Integrations
<WidgetIntegrations items={[{
@@ -52,16 +71,23 @@ import downloadsCard from './img/screenshot.png';
}, {
integration: qBittorentIntegration,
note: "Torrent client"
+}, {
+ integration: aria2Integration,
+ note: "Multi-protocol download client"
}, {
integration: slskdIntegration,
- note: "Soulseek client"
+ note: "Soulseek client (read-only)"
}]} />
### Interactions
-- Pause / Resume one download by clicking on the according icon.
-- Delete one download by clicking on the trash icon. (Can also delete the files)
-- Pause / Resume all downloads by using the bottom button.
+- **Right-click** any download to open a context menu with pause/resume, delete, and copy actions
+- **Click** any row to expand it and see full download details inline
+- **Hover** a download name for a quick stats tooltip
+- **Stats toggle** — show or hide the global stats bar from the footer
+- **Pause / Resume** all downloads using the footer controls
+- **Filter** by integration or status using the filter button in the footer
+- **Sort** by clicking column headers (with persistent sort direction)
### Adding the widget
diff --git a/apps/docs/docs/widgets/downloads/index.ts b/apps/docs/docs/widgets/downloads/index.ts
index 4810aec89..4245af310 100644
--- a/apps/docs/docs/widgets/downloads/index.ts
+++ b/apps/docs/docs/widgets/downloads/index.ts
@@ -2,26 +2,23 @@ import { WidgetDefinition } from "@site/src/types";
import { IconDownload } from "@tabler/icons-react";
const columnsList = [
- "id",
- "actions",
- "added",
- "category",
- "downSpeed",
- "index",
- "integration",
"name",
"progress",
+ "size",
+ "downSpeed",
+ "upSpeed",
+ "time",
+ "state",
+ "added",
"ratio",
"received",
"sent",
- "size",
- "state",
- "time",
+ "category",
+ "integration",
+ "index",
"type",
- "upSpeed",
];
-const sortingExclusion = ["actions", "id", "state"];
-const columnsSort = columnsList.filter((column) => !sortingExclusion.some((exclusion) => exclusion === column));
+const sortColumns = columnsList.filter((c) => !["state", "category", "integration"].includes(c));
export const downloadsWidget: WidgetDefinition = {
icon: IconDownload,
@@ -32,25 +29,20 @@ export const downloadsWidget: WidgetDefinition = {
items: [
{
name: "Columns to show",
- description: "Select the columns you want to display in the widget.",
+ description:
+ "Select the columns you want to display in the widget. Columns automatically hide/show based on widget width.",
values: `List of columns: ${columnsList.join(", ")}`,
- defaultValue: ["integration", "name", "progress", "time", "actions"].join(", "),
- },
- {
- name: "Enable items sorting",
- description: "Enables the sorting in the table.",
- values: { type: "boolean" },
- defaultValue: "no",
+ defaultValue: ["name", "progress", "downSpeed", "time", "state"].join(", "),
},
{
- name: "Column used for sorting by default",
- description: "By default it will sort by this column.",
- defaultValue: "type",
- values: `List of columns: ${columnsSort.join(", ")}`,
+ name: "Default sort column",
+ description: "The column used for initial sorting when the widget loads.",
+ defaultValue: "progress",
+ values: `List of columns: ${sortColumns.join(", ")}`,
},
{
name: "Invert sorting",
- description: "This will invert the sorting order of the table.",
+ description: "This will invert the default sorting order.",
values: { type: "boolean" },
defaultValue: "no",
},
@@ -76,13 +68,13 @@ export const downloadsWidget: WidgetDefinition = {
name: "Hide completed torrent under this threshold (in kiB/s)",
description:
"This will hide completed torrent entries that have a download speed below the specified threshold.",
- values: "Any number above 1, 0 to disable",
+ values: "Any number above 0, 0 to disable",
defaultValue: "0",
},
{
- name: "Categories/names to filter",
- description: "You can filter the items by categories or names. Use a comma to separate multiple values.",
- values: "Comma-separated list of categories or names",
+ name: "Categories/labels to filter",
+ description: "You can filter the items by categories or labels. Use a comma to separate multiple values.",
+ values: "Comma-separated list of categories or labels",
defaultValue: "-",
},
{
@@ -94,13 +86,13 @@ export const downloadsWidget: WidgetDefinition = {
},
{
name: "Use filter to calculate Ratio",
- description: "This will use the filter to calculate the ratio of items shown in the widget.",
+ description: "This will use the category filter when calculating the global torrent ratio.",
values: { type: "boolean" },
defaultValue: "yes",
},
{
name: "Limit items per integration",
- description: "This will limit the number of items shown per integration, not globally",
+ description: "This will limit the number of items shown per integration, not globally.",
values: "Any number above 1",
defaultValue: "50",
},
diff --git a/packages/integrations/src/download-client/qbittorrent/qbittorrent-integration.ts b/packages/integrations/src/download-client/qbittorrent/qbittorrent-integration.ts
index edc071889..c08dd5848 100644
--- a/packages/integrations/src/download-client/qbittorrent/qbittorrent-integration.ts
+++ b/packages/integrations/src/download-client/qbittorrent/qbittorrent-integration.ts
@@ -30,7 +30,7 @@ export class QBitTorrentIntegration extends Integration implements IDownloadClie
public async getClientJobsAndStatusAsync(input: { limit: number }): Promise<DownloadClientJobsAndStatus> {
const type = "torrent";
const client = await this.getClientAsync();
- const torrents = await client.listTorrents({ limit: input.limit, sort: "progress", reverse: false });
+ const torrents = await client.listTorrents({ limit: input.limit });
const rates = torrents.reduce(
({ down, up }, { dlspeed, upspeed }) => ({ down: down + dlspeed, up: up + upspeed }),
{ down: 0, up: 0 },
diff --git a/packages/old-import/src/widgets/options.ts b/packages/old-import/src/widgets/options.ts
index 003696439..0cf84b493 100644
--- a/packages/old-import/src/widgets/options.ts
+++ b/packages/old-import/src/widgets/options.ts
@@ -77,15 +77,16 @@ const optionMapping: OptionMapping = {
categoryFilter: (oldOptions) => ("labelFilter" in oldOptions ? oldOptions.labelFilter : undefined),
filterIsWhitelist: (oldOptions) =>
"labelFilterIsWhitelist" in oldOptions ? oldOptions.labelFilterIsWhitelist : undefined,
- enableRowSorting: (oldOptions) => ("rowSorting" in oldOptions ? oldOptions.rowSorting : undefined),
showCompletedTorrent: (oldOptions) =>
"displayCompletedTorrents" in oldOptions ? oldOptions.displayCompletedTorrents : undefined,
- columns: () => ["integration", "name", "progress", "time", "actions"],
- defaultSort: () => "type",
+ columns: () => ["integration", "name", "progress", "time", "state"],
+ defaultSort: () => "progress",
descendingDefaultSort: () => false,
showCompletedUsenet: () => true,
showCompletedHttp: () => true,
limitPerIntegration: () => undefined,
+ columnOrder: () => undefined,
+ columnWidths: () => undefined,
},
weather: {
forecastDayCount: (oldOptions) => oldOptions.forecastDays,
diff --git a/packages/translation/src/lang/en.json b/packages/translation/src/lang/en.json
index 681166967..388dc4186 100644
--- a/packages/translation/src/lang/en.json
+++ b/packages/translation/src/lang/en.json
@@ -3079,11 +3079,20 @@
"limitPerIntegration": {
"label": "Limit items per integration",
"description": "This will limit the number of items shown per integration, not globally"
+ },
+ "columnOrder": {
+ "label": "Column order"
+ },
+ "columnWidths": {
+ "label": "Column widths"
}
},
"errors": {
"noColumns": "Select Columns in Items",
- "noCommunications": "Can't load data from integration"
+ "noCommunications": "Can't load data from integration",
+ "noItems": "No downloads found",
+ "actionFailed": "Action failed",
+ "actionFailedMessage": "The action could not be completed. Please try again."
},
"items": {
"actions": {
@@ -3106,7 +3115,8 @@
"detailsTitle": "Current index within client"
},
"id": {
- "columnTitle": "Id"
+ "columnTitle": "Id",
+ "detailsTitle": "Item ID"
},
"integration": {
"columnTitle": "Integration"
@@ -3140,7 +3150,8 @@
},
"time": {
"columnTitle": "Finish time",
- "detailsTitle": "Time since/to completion"
+ "detailsTitle": "Time since/to completion",
+ "eta": "ETA"
},
"type": {
"columnTitle": "Type",
@@ -3184,7 +3195,23 @@
}
}
},
- "globalRatio": "Global Ratio"
+ "globalRatio": "Global Ratio",
+ "contextMenu": {
+ "copyName": "Copy name",
+ "copyId": "Copy ID",
+ "clearFilters": "Clear filters"
+ },
+ "footer": {
+ "filter": "Filter downloads"
+ },
+ "stats": {
+ "show": "Show global stats",
+ "hide": "Hide global stats",
+ "overallProgress": "Overall queue progress",
+ "totalSize": "Total queue size",
+ "clients": "{count, plural, one {# client} other {# clients}}"
+ },
+ "disconnected": "(disconnected)"
},
"mediaReleases": {
"name": "Media releases",
diff --git a/packages/widgets/src/downloads/component.tsx b/packages/widgets/src/downloads/component.tsx
index ff9b71664..e03c937bf 100644
--- a/packages/widgets/src/downloads/component.tsx
+++ b/packages/widgets/src/downloads/component.tsx
@@ -3,922 +3,1444 @@
import "../widgets-common.css";
import "./styles.css";
-import { useCallback, useMemo, useState } from "react";
-import type { MantineStyleProp } from "@mantine/core";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
ActionIcon,
Avatar,
- AvatarGroup,
- Button,
+ Badge,
+ Box,
Center,
- Chip,
Divider,
Group,
- Modal,
- Paper,
- Popover,
+ Menu,
+ Portal,
Progress,
- Space,
+ RingProgress,
+ SimpleGrid,
Stack,
Text,
- Title,
Tooltip,
+ UnstyledButton,
} from "@mantine/core";
import { useDisclosure } from "@mantine/hooks";
import {
- IconAlertTriangle,
- IconCirclesRelation,
+ IconChevronDown,
+ IconChevronUp,
+ IconCopy,
+ IconDatabase,
+ IconDownload,
IconFilter,
- IconInfinity,
+ IconFilterOff,
IconInfoCircle,
IconPlayerPause,
IconPlayerPlay,
IconTrash,
- IconX,
+ IconTrashX,
+ IconUpload,
} from "@tabler/icons-react";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
-import type { MRT_ColumnDef, MRT_VisibilityState } from "mantine-react-table";
-import { MantineReactTable, useMantineReactTable } from "mantine-react-table";
+import type { DataTableColumn, DataTableSortStatus } from "mantine-datatable";
+import { DataTable, useDataTableColumns } from "mantine-datatable";
import { clientApi } from "@homarr/api/client";
import { useIntegrationsWithInteractAccess } from "@homarr/auth/client";
import { formatByteRate, formatBytes, useIntegrationConnected } from "@homarr/common";
import { getIconUrl, getIntegrationKindsByCategory } from "@homarr/definitions";
import type { ExtendedClientStatus, ExtendedDownloadClientItem } from "@homarr/integrations";
+import { showErrorNotification } from "@homarr/notifications";
import { useScopedI18n } from "@homarr/translation/client";
import type { WidgetComponentProps } from "../definition";
dayjs.extend(relativeTime);
-interface QuickFilter {
- integrationKinds: string[];
- statuses: ExtendedDownloadClientItem["state"][];
+type DownloadsT = ReturnType<typeof useScopedI18n<"widget.downloads">>;
+type DownloadState = ExtendedDownloadClientItem["state"];
+
+interface SizeConfig {
+ fontSize: "xs" | "sm";
+ iconSize: number;
+ cellPadding: number;
+ showSpeedColumns: boolean;
+ showTimeColumn: boolean;
+ showStateColumn: boolean;
+}
+
+interface ContextMenuState {
+ x: number;
+ y: number;
+ item: ExtendedDownloadClientItem;
+}
+
+interface ColumnContext {
+ optionsColumnSet: Set<string>;
+ hasTorrents: boolean;
+ hasMultipleClients: boolean;
+ hasMultipleTypes: boolean;
+ size: SizeConfig;
}
-//Ratio table for relative width between columns
-const columnsRatios: Record<keyof ExtendedDownloadClientItem, number> = {
- actions: 2,
- added: 4,
- category: 1,
- downSpeed: 3,
- id: 1,
- index: 1,
- integration: 1,
- name: 16,
- progress: 6,
- ratio: 2,
- received: 3,
- sent: 3,
- size: 3,
- state: 3,
- time: 4,
- type: 2,
- upSpeed: 3,
+const SIZE_BREAKPOINTS: { maxWidth: number; config: SizeConfig }[] = [
+ {
+ maxWidth: 300,
+ config: {
+ fontSize: "xs",
+ iconSize: 12,
+ cellPadding: 2,
+ showSpeedColumns: false,
+ showTimeColumn: false,
+ showStateColumn: false,
+ },
+ },
+ {
+ maxWidth: 500,
+ config: {
+ fontSize: "xs",
+ iconSize: 14,
+ cellPadding: 4,
+ showSpeedColumns: false,
+ showTimeColumn: true,
+ showStateColumn: false,
+ },
+ },
+];
+
+const DEFAULT_SIZE_CONFIG: SizeConfig = {
+ fontSize: "sm",
+ iconSize: 14,
+ cellPadding: 4,
+ showSpeedColumns: true,
+ showTimeColumn: true,
+ showStateColumn: true,
+};
+
+const stateColorMap: Record<DownloadState, string> = {
+ downloading: "blue",
+ leeching: "blue",
+ seeding: "green",
+ completed: "green",
+ processing: "cyan",
+ queued: "gray",
+ paused: "yellow",
+ stalled: "orange",
+ failed: "red",
+ unknown: "gray",
};
+const rowBgAlpha: Partial<Record<DownloadState, string>> = {
+ failed: "rgba(255, 0, 0, 0.04)",
+ paused: "rgba(255, 200, 0, 0.03)",
+};
+
+const columnVisibilityChecks: Partial<Record<string, (ctx: ColumnContext) => boolean>> = {
+ upSpeed: (ctx) => ctx.hasTorrents && ctx.size.showSpeedColumns,
+ ratio: (ctx) => ctx.hasTorrents,
+ sent: (ctx) => ctx.hasTorrents,
+ integration: (ctx) => ctx.hasMultipleClients,
+ type: (ctx) => ctx.hasMultipleTypes,
+ downSpeed: (ctx) => ctx.size.showSpeedColumns,
+ time: (ctx) => ctx.size.showTimeColumn,
+ state: (ctx) => ctx.size.showStateColumn,
+};
+
+const speedColumnConfig = {
+ down: { Icon: IconDownload, color: "blue" as const },
+ up: { Icon: IconUpload, color: "green" as const },
+} as const;
+
+function getSizeConfig(width: number): SizeConfig {
+ for (const { maxWidth, config } of SIZE_BREAKPOINTS) {
+ if (width < maxWidth) return config;
+ }
+ return DEFAULT_SIZE_CONFIG;
+}
+
+function progressColor(state: DownloadState, progress: number): string {
+ if (state === "paused") return "yellow";
+ if (progress >= 1) return "green";
+ return "blue";
+}
+
+function parseJsonOption<T>(value: string | undefined, fallback: T): T {
+ if (!value) return fallback;
+ try {
+ return JSON.parse(value) as T;
+ } catch {
+ return fallback;
+ }
+}
+
+function toCategoryArray(category: string | string[]): string[] {
+ if (Array.isArray(category)) return category;
+ return [category];
+}
+
+function matchesCategoryFilter(
+ category: string | string[] | undefined,
+ categoryFilter: string[],
+ filterIsWhitelist: boolean,
+): boolean {
+ if (categoryFilter.length === 0) return true;
+ const matches = categoryFilter.some((filter) => toCategoryArray(category ?? "").includes(filter));
+ return filterIsWhitelist === matches;
+}
+
+function formatCategoryDisplay(category: string | string[] | undefined): string | undefined {
+ if (!category) return undefined;
+ if (Array.isArray(category)) return category.join(", ");
+ return category;
+}
+
+function formatRatio(ratio: number): string {
+ if (ratio >= 100) return ratio.toFixed(0);
+ if (ratio >= 10) return ratio.toFixed(1);
+ return ratio.toFixed(2);
+}
+
+function showCompletedItem(
+ item: Pick<ExtendedDownloadClientItem, "type" | "progress" | "upSpeed">,
+ options: WidgetComponentProps<"downloads">["options"],
+): boolean {
+ if (item.progress < 1) return true;
+ if (item.type === "torrent") {
+ return options.showCompletedTorrent && (item.upSpeed ?? 0) >= Number(options.activeTorrentThreshold) * 1024;
+ }
+ if (item.type === "usenet") return options.showCompletedUsenet;
+ return options.showCompletedHttp;
+}
+
+function shouldIncludeColumn(accessor: string, ctx: ColumnContext): boolean {
+ if (!ctx.optionsColumnSet.has(accessor)) return false;
+ const check = columnVisibilityChecks[accessor];
+ if (check && !check(ctx)) return false;
+ return true;
+}
+
+function toggleArrayItem<T>(array: T[], value: T): T[] {
+ if (array.includes(value)) return array.filter((entry) => entry !== value);
+ return [...array, value];
+}
+
+function truncateText(text: string, maxLength: number): string {
+ if (text.length <= maxLength) return text;
+ return `${text.slice(0, maxLength)}…`;
+}
+
+function getSortMultiplier(direction: DataTableSortStatus<ExtendedDownloadClientItem>["direction"]): number {
+ if (direction === "desc") return -1;
+ return 1;
+}
+
+function compareSortValues(
+ accessor: keyof ExtendedDownloadClientItem,
+ aVal: ExtendedDownloadClientItem[keyof ExtendedDownloadClientItem],
+ bVal: ExtendedDownloadClientItem[keyof ExtendedDownloadClientItem],
+ multiplier: number,
+): number {
+ if (accessor === "time") {
+ let aTime = aVal as number;
+ let bTime = bVal as number;
+ if (aTime === 0) aTime = Infinity;
+ if (bTime === 0) bTime = Infinity;
+ return (aTime - bTime) * multiplier;
+ }
+ if (typeof aVal === "string" && typeof bVal === "string") return aVal.localeCompare(bVal) * multiplier;
+ if (typeof aVal === "number" && typeof bVal === "number") return (aVal - bVal) * multiplier;
+ return 0;
+}
+
+function buildProgressTooltip(record: ExtendedDownloadClientItem): string {
+ const parts = [`${formatBytes(record.received)} / ${formatBytes(record.size)}`];
+ if (record.downSpeed) parts.push(`↓ ${formatByteRate(record.downSpeed)}`);
+ if (record.time !== 0) parts.push(`ETA: ${dayjs().add(record.time, "milliseconds").fromNow(true)}`);
+ return parts.join(" · ");
+}
+
+function SpeedCell({
+ speed,
+ fontSize,
+ direction,
+}: {
+ speed: number | undefined;
+ fontSize: SizeConfig["fontSize"];
+ direction: keyof typeof speedColumnConfig;
+}) {
+ if (!speed) return null;
+ const { Icon, color } = speedColumnConfig[direction];
+ return (
+ <Group gap={4} wrap="nowrap">
+ <Icon size={12} style={{ flexShrink: 0, opacity: 0.5 }} />
+ <Text size={fontSize} c={color}>
+ {formatByteRate(speed)}
+ </Text>
+ </Group>
+ );
+}
+
export default function DownloadClientsWidget({
isEditMode,
integrationIds,
options,
setOptions,
+ boardId,
+ itemId,
+ width,
}: WidgetComponentProps<"downloads">) {
- const integrationsWithInteractions = useIntegrationsWithInteractAccess().flatMap(({ id }) =>
- integrationIds.includes(id) ? [id] : [],
+ const allInteractAccess = useIntegrationsWithInteractAccess();
+ const integrationInteractSet = useMemo(
+ () => new Set(allInteractAccess.filter(({ id }) => integrationIds.includes(id)).map(({ id }) => id)),
+ [allInteractAccess, integrationIds],
);
- const { data: currentItems = [] } = clientApi.widget.downloads.getJobsAndStatuses.useQuery({
+ const {
+ data: currentItems = [],
+ isFetching,
+ isError,
+ } = clientApi.widget.downloads.getJobsAndStatuses.useQuery({
integrationIds,
limitPerIntegration: options.limitPerIntegration,
});
const t = useScopedI18n("widget.downloads");
- const tCommon = useScopedI18n("common");
-
- //Item modal state and selection
- const [clickedIndex, setClickedIndex] = useState<number>(0);
- const [opened, { open, close }] = useDisclosure(false);
-
- //User quick settings for filters
- const [quickFilters, setQuickFilters] = useState<QuickFilter>({ integrationKinds: [], statuses: [] });
- const availableStatuses = useMemo<QuickFilter["statuses"]>(() => {
- //Redefine list of available statuses from current items
- const statuses = Array.from(new Set(currentItems.flatMap(({ data }) => data.items.map(({ state }) => state))));
- //Reset user filters accordingly to remove unavailable statuses
- setQuickFilters(({ integrationKinds: names, statuses: prevStatuses }) => {
- return { integrationKinds: names, statuses: prevStatuses.filter((status) => statuses.includes(status)) };
- });
- return statuses;
- }, [currentItems]);
+
+ const [clientFilter, setClientFilter] = useState<string[]>([]);
+ const [statusFilter, setStatusFilter] = useState<string[]>([]);
+ const [contextMenu, setContextMenu] = useState<ContextMenuState | null>(null);
+ const [showStats, { toggle: toggleStats }] = useDisclosure(false);
const utils = clientApi.useUtils();
- const invalidateDownloads = { onSettled: () => void utils.widget.downloads.getJobsAndStatuses.invalidate() };
- const { mutate: mutateResumeItem } = clientApi.widget.downloads.resumeItem.useMutation(invalidateDownloads);
- const { mutate: mutatePauseItem } = clientApi.widget.downloads.pauseItem.useMutation(invalidateDownloads);
- const { mutate: mutateDeleteItem } = clientApi.widget.downloads.deleteItem.useMutation(invalidateDownloads);
-
- //Flatten Data array for which each element has its integration, data (base + calculated) and actions
- const data = useMemo<ExtendedDownloadClientItem[]>(
- () =>
- currentItems
- //Insure it is only using selected integrations
- .filter(({ integration }) => integrationIds.includes(integration.id))
- //Construct normalized items list
- .flatMap((pair) =>
- //Apply user white/black list
- pair.data.items
- .filter(
- ({ category }) =>
- options.filterIsWhitelist ===
- options.categoryFilter.some((filter) =>
- (Array.isArray(category) ? category : [category]).includes(filter),
- ),
- )
- //Filter completed items following widget option
- .filter(
- ({ type, progress, upSpeed }) =>
- (type === "torrent" &&
- ((progress === 1 &&
- options.showCompletedTorrent &&
- (upSpeed ?? 0) >= Number(options.activeTorrentThreshold) * 1024) ||
- progress !== 1)) ||
- (type === "usenet" && ((progress === 1 && options.showCompletedUsenet) || progress !== 1)) ||
- (type === "miscellaneous" && ((progress === 1 && options.showCompletedHttp) || progress !== 1)),
- )
- //Filter following user quick setting
- .filter(
- ({ state }) =>
- (quickFilters.integrationKinds.length === 0 ||
- quickFilters.integrationKinds.includes(pair.integration.name)) &&
- (quickFilters.statuses.length === 0 || quickFilters.statuses.includes(state)),
- )
- //Add extrapolated data and actions if user is allowed interaction
- .map((item): ExtendedDownloadClientItem => {
- const received = item.received ?? Math.floor(item.size * item.progress);
- const integrationIds = [pair.integration.id];
- return {
- integration: pair.integration,
- ...item,
- category: item.category !== undefined && item.category.length > 0 ? item.category : undefined,
- received,
- ratio: item.sent !== undefined ? item.sent / item.size : undefined,
- //Only add if permission to use mutations
- actions: integrationsWithInteractions.includes(pair.integration.id)
- ? {
- resume: () => mutateResumeItem({ integrationIds, item }),
- pause: () => mutatePauseItem({ integrationIds, item }),
- delete: ({ fromDisk }) => mutateDeleteItem({ integrationIds, item, fromDisk }),
- }
- : undefined,
- };
- }),
- )
- //flatMap already sorts by integration by nature, add sorting by integration type (usenet | torrent)
- .sort(({ type: typeA }, { type: typeB }) => typeA.length - typeB.length),
- [
- currentItems,
- integrationIds,
- integrationsWithInteractions,
- mutateDeleteItem,
- mutatePauseItem,
- mutateResumeItem,
- options.activeTorrentThreshold,
- options.categoryFilter,
- options.filterIsWhitelist,
- options.showCompletedTorrent,
- options.showCompletedUsenet,
- options.showCompletedHttp,
- quickFilters,
- ],
+ const mutationOptions = {
+ onSettled: () => void utils.widget.downloads.getJobsAndStatuses.invalidate(),
+ onError: () => showErrorNotification({ title: t("errors.actionFailed"), message: t("errors.actionFailedMessage") }),
+ };
+ const { mutate: mutateResumeItem } = clientApi.widget.downloads.resumeItem.useMutation(mutationOptions);
+ const { mutate: mutatePauseItem } = clientApi.widget.downloads.pauseItem.useMutation(mutationOptions);
+ const { mutate: mutateDeleteItem } = clientApi.widget.downloads.deleteItem.useMutation(mutationOptions);
+ const { mutate: mutateResumeQueue } = clientApi.widget.downloads.resume.useMutation(mutationOptions);
+ const { mutate: mutatePauseQueue } = clientApi.widget.downloads.pause.useMutation(mutationOptions);
+
+ const { mutate: saveItemOptions } = clientApi.widget.options.saveItemOptions.useMutation({
+ onError: () => showErrorNotification({ title: t("errors.actionFailed"), message: t("errors.actionFailedMessage") }),
+ });
+ const persistOption = useCallback(
+ (newOptions: Partial<Record<string, string>>) => {
+ setOptions({ newOptions });
+ if (boardId && itemId) saveItemOptions({ boardId, itemId, newOptions });
+ },
+ [setOptions, boardId, itemId, saveItemOptions],
);
- //Flatten Clients Array for which each elements has the integration and general client infos.
- const clients = useMemo<ExtendedClientStatus[]>(
- () =>
- currentItems
- .filter(({ integration }) => integrationIds.includes(integration.id))
- .flatMap(({ integration, data }): ExtendedClientStatus => {
- const interact = integrationsWithInteractions.includes(integration.id);
- const isTorrent = getIntegrationKindsByCategory("torrent").some((kind) => kind === integration.kind);
- /** Derived from current items */
- const { totalUp, totalDown } = data.items
- .filter(
- ({ category }) =>
- !options.applyFilterToRatio ||
- !data.status.types.includes("torrent") ||
- options.filterIsWhitelist ===
- options.categoryFilter.some((filter) =>
- (Array.isArray(category) ? category : [category]).includes(filter),
- ),
- )
- .reduce(
- ({ totalUp, totalDown }, { sent, size, progress }) => ({
- totalUp: isTorrent ? (totalUp ?? 0) + (sent ?? 0) : undefined,
- totalDown: totalDown + size * progress,
- }),
- { totalDown: 0, totalUp: isTorrent ? 0 : undefined },
- );
- return {
- integration,
- interact,
- status: {
- totalUp,
- totalDown,
- ratio: totalUp === undefined ? undefined : totalUp / totalDown,
- ...data.status,
- },
- };
- })
- .sort(
- ({ status: statusA }, { status: statusB }) =>
- (statusA?.types.length ?? Infinity) - (statusB?.types.length ?? Infinity),
- ),
- [
- currentItems,
- integrationIds,
- integrationsWithInteractions,
- options.applyFilterToRatio,
- options.categoryFilter,
- options.filterIsWhitelist,
- ],
+ const savedOrder = useMemo(() => parseJsonOption(options.columnOrder, [] as string[]), [options.columnOrder]);
+ const savedWidths = useMemo(
+ () => parseJsonOption(options.columnWidths, {} as Record<string, number>),
+ [options.columnWidths],
);
- //Check existing types between torrents and usenet
- const integrationTypes: ExtendedDownloadClientItem["type"][] = [];
-
- if (data.some(({ type }) => type === "torrent")) integrationTypes.push("torrent");
- if (data.some(({ type }) => type === "usenet")) integrationTypes.push("usenet");
- if (data.some(({ type }) => type === "miscellaneous")) integrationTypes.push("miscellaneous");
-
- //Set the visibility of columns depending on widget settings and available data/integrations.
- const columnVisibility: MRT_VisibilityState = {
- id: options.columns.includes("id"),
- actions: options.columns.includes("actions") && integrationsWithInteractions.length > 0,
- added: options.columns.includes("added"),
- category: options.columns.includes("category"),
- downSpeed: options.columns.includes("downSpeed"),
- index: options.columns.includes("index"),
- integration: options.columns.includes("integration") && clients.length > 1,
- name: options.columns.includes("name"),
- progress: options.columns.includes("progress"),
- ratio: options.columns.includes("ratio") && integrationTypes.includes("torrent"),
- received: options.columns.includes("received"),
- sent: options.columns.includes("sent") && integrationTypes.includes("torrent"),
- size: options.columns.includes("size"),
- state: options.columns.includes("state"),
- time: options.columns.includes("time"),
- type: options.columns.includes("type") && integrationTypes.length > 1,
- upSpeed: options.columns.includes("upSpeed") && integrationTypes.includes("torrent"),
- } satisfies Record<keyof ExtendedDownloadClientItem, boolean>;
-
- //Default styling behavior for stopping interaction when editing. (Applied everywhere except the table header)
- const editStyle: MantineStyleProp = {
- pointerEvents: isEditMode ? "none" : undefined,
- };
+ let defaultSortDirection: DataTableSortStatus<ExtendedDownloadClientItem>["direction"] = "asc";
+ if (options.descendingDefaultSort) defaultSortDirection = "desc";
+ const [sortStatus, setSortStatus] = useState<DataTableSortStatus<ExtendedDownloadClientItem>>({
+ columnAccessor: options.defaultSort,
+ direction: defaultSortDirection,
+ });
+ useEffect(() => {
+ setSortStatus({ columnAccessor: options.defaultSort, direction: defaultSortDirection });
+ }, [options.defaultSort, defaultSortDirection]);
- //Base element in common with all columns
- const columnsDefBase = useCallback(
- ({
- key,
- showHeader,
- }: {
- key: keyof ExtendedDownloadClientItem;
- showHeader: boolean;
- }): MRT_ColumnDef<ExtendedDownloadClientItem> => {
- return {
- id: key,
- accessorKey: key,
- header: key,
- size: columnsRatios[key],
- Header: () =>
- showHeader ? (
- <Text fz="xs" fw={700}>
- {t(`items.${key}.columnTitle`)}
- </Text>
- ) : null,
- };
- },
- [t],
- );
+ const data = useMemo<ExtendedDownloadClientItem[]>(() => {
+ return currentItems
+ .filter(({ integration }) => integrationIds.includes(integration.id))
+ .flatMap((pair) =>
+ pair.data.items
+ .filter(({ category }) => matchesCategoryFilter(category, options.categoryFilter, options.filterIsWhitelist))
+ .filter((item) => showCompletedItem(item, options))
+ .filter(
+ ({ state }) =>
+ (clientFilter.length === 0 || clientFilter.includes(pair.integration.id)) &&
+ (statusFilter.length === 0 || statusFilter.includes(state)),
+ )
+ .map((item): ExtendedDownloadClientItem => {
+ const received = item.received ?? Math.floor(item.size * item.progress);
+ const ids = [pair.integration.id];
+ let category: string | string[] | undefined = item.category;
+ if (category !== undefined && category.length === 0) category = undefined;
- //Make columns and cell elements, Memoized to data with deps on data and EditMode
- const columns = useMemo<MRT_ColumnDef<ExtendedDownloadClientItem>[]>(
- () => [
- {
- ...columnsDefBase({ key: "actions", showHeader: false }),
- enableSorting: false,
- Cell: ({ cell, row }) => {
- const actions = cell.getValue<ExtendedDownloadClientItem["actions"]>();
- const pausedAction = row.original.state === "paused" ? "resume" : "pause";
- const [opened, { open, close }] = useDisclosure(false);
-
- return actions ? (
- <Group wrap="nowrap" gap="xs">
- <Tooltip label={t(`actions.item.${pausedAction}`)}>
- <ActionIcon size="xs" variant="light" radius="100%" onClick={actions[pausedAction]}>
- {pausedAction === "resume" ? <IconPlayerPlay /> : <IconPlayerPause />}
- </ActionIcon>
- </Tooltip>
- <Tooltip label={t("actions.item.delete.title")}>
- <ActionIcon size="xs" color="red" radius="100%" onClick={open}>
- <IconTrash />
- </ActionIcon>
- </Tooltip>
- <Modal opened={opened} onClose={close} title={t("actions.item.delete.modalTitle")} size="auto" centered>
- <Group>
- <Button
- color="red"
- onClick={() => {
- close();
- actions.delete({ fromDisk: false });
- }}
- >
- {t("actions.item.delete.entry")}
- </Button>
- <Button
- color="red"
- onClick={() => {
- close();
- actions.delete({ fromDisk: true });
- }}
- leftSection={<IconAlertTriangle />}
- >
- {t("actions.item.delete.entryAndFiles")}
- </Button>
- <Button color="green" onClick={close}>
- {tCommon("action.cancel")}
- </Button>
- </Group>
- </Modal>
- </Group>
- ) : (
- <ActionIcon size="xs" radius="100%" disabled>
- <IconX />
- </ActionIcon>
- );
- },
- },
- {
- ...columnsDefBase({ key: "added", showHeader: true }),
- sortUndefined: "last",
- Cell: ({ cell }) => {
- const added = cell.getValue<ExtendedDownloadClientItem["added"]>();
- return <Text size="xs">{added !== undefined ? dayjs(added).fromNow() : "unknown"}</Text>;
- },
- },
- {
- ...columnsDefBase({ key: "category", showHeader: false }),
- sortUndefined: "last",
- Cell: ({ cell }) => {
- const category = cell.getValue<ExtendedDownloadClientItem["category"]>();
- return (
- category !== undefined && (
- <Tooltip label={category}>
- <IconInfoCircle size={16} />
- </Tooltip>
- )
+ let ratio: number | undefined;
+ if (item.sent !== undefined && item.size > 0) ratio = item.sent / item.size;
+
+ let actions: ExtendedDownloadClientItem["actions"];
+ if (integrationInteractSet.has(pair.integration.id)) {
+ actions = {
+ resume: () => mutateResumeItem({ integrationIds: ids, item }),
+ pause: () => mutatePauseItem({ integrationIds: ids, item }),
+ delete: ({ fromDisk }) => mutateDeleteItem({ integrationIds: ids, item, fromDisk }),
+ };
+ }
+
+ return { integration: pair.integration, ...item, category, received, ratio, actions };
+ }),
+ );
+ }, [
+ currentItems,
+ integrationIds,
+ integrationInteractSet,
+ mutateDeleteItem,
+ mutatePauseItem,
+ mutateResumeItem,
+ options,
+ clientFilter,
+ statusFilter,
+ ]);
+
+ const sortedData = useMemo(() => {
+ const accessor = sortStatus.columnAccessor as keyof ExtendedDownloadClientItem;
+ const multiplier = getSortMultiplier(sortStatus.direction);
+ return [...data].toSorted((a, b) => {
+ const aVal = a[accessor] ?? 0;
+ const bVal = b[accessor] ?? 0;
+ return compareSortValues(accessor, aVal, bVal, multiplier);
+ });
+ }, [data, sortStatus]);
+
+ const clients = useMemo<ExtendedClientStatus[]>(() => {
+ return currentItems
+ .filter(({ integration }) => integrationIds.includes(integration.id))
+ .map(({ integration, data: clientData }): ExtendedClientStatus => {
+ const interact = integrationInteractSet.has(integration.id);
+ const isTorrent = getIntegrationKindsByCategory("torrent").some((kind) => kind === integration.kind);
+ const applyRatioFilter = options.applyFilterToRatio && clientData.status.types.includes("torrent");
+
+ let initialTotalUp: number | undefined;
+ if (isTorrent) initialTotalUp = 0;
+
+ const { totalUp, totalDown } = clientData.items
+ .filter(({ category }) => {
+ if (!applyRatioFilter) return true;
+ return matchesCategoryFilter(category, options.categoryFilter, options.filterIsWhitelist);
+ })
+ .reduce(
+ (acc, { sent, size, progress }) => {
+ let nextTotalUp: number | undefined;
+ if (isTorrent) nextTotalUp = (acc.totalUp ?? 0) + (sent ?? 0);
+ return {
+ totalUp: nextTotalUp,
+ totalDown: acc.totalDown + size * progress,
+ };
+ },
+ { totalDown: 0, totalUp: initialTotalUp },
);
- },
+
+ let ratio: number | undefined;
+ if (totalUp !== undefined && totalDown !== 0) ratio = totalUp / totalDown;
+
+ return {
+ integration,
+ interact,
+ status: { totalUp, totalDown, ratio, ...clientData.status },
+ };
+ });
+ }, [
+ currentItems,
+ integrationIds,
+ integrationInteractSet,
+ options.applyFilterToRatio,
+ options.categoryFilter,
+ options.filterIsWhitelist,
+ ]);
+
+ const hasTorrents = data.some(({ type }) => type === "torrent");
+ const hasMultipleClients = clients.length > 1;
+ const hasMultipleTypes = new Set(data.map(({ type }) => type)).size > 1;
+
+ const size = useMemo(() => getSizeConfig(width), [width]);
+ const optionsColumnSet = useMemo(() => new Set<string>(options.columns), [options.columns]);
+ const columnContext = useMemo<ColumnContext>(
+ () => ({ optionsColumnSet, hasTorrents, hasMultipleClients, hasMultipleTypes, size }),
+ [optionsColumnSet, hasTorrents, hasMultipleClients, hasMultipleTypes, size],
+ );
+
+ let progressColumnWidth = 120;
+ if (width < 400) progressColumnWidth = 80;
+
+ const columns = useMemo((): DataTableColumn<ExtendedDownloadClientItem>[] => {
+ const includeColumn = (accessor: string) => shouldIncludeColumn(accessor, columnContext);
+ const cols: (DataTableColumn<ExtendedDownloadClientItem> | false)[] = [
+ includeColumn("integration") && {
+ accessor: "integration",
+ title: "",
+ width: 36,
+ render: (record) => (
+ <Tooltip label={record.integration.name} withArrow>
+ <Avatar size={20} radius={0} src={getIconUrl(record.integration.kind)} />
+ </Tooltip>
+ ),
},
- {
- ...columnsDefBase({ key: "downSpeed", showHeader: true }),
- sortUndefined: "last",
- Cell: ({ cell }) => {
- const downSpeed = cell.getValue<ExtendedDownloadClientItem["downSpeed"]>();
- return downSpeed ? <Text size="xs">{formatByteRate(downSpeed)}</Text> : null;
- },
+ includeColumn("name") && {
+ accessor: "name",
+ title: t("items.name.columnTitle"),
+ sortable: true,
+ ellipsis: true,
+ render: (record) => (
+ <Tooltip
+ label={buildHoverTooltip(record, t)}
+ multiline
+ w={280}
+ withArrow
+ position="bottom-start"
+ openDelay={400}
+ transitionProps={{ transition: "fade", duration: 150 }}
+ color="dark"
+ >
+ <Group gap={6} wrap="nowrap" style={{ overflow: "hidden" }}>
+ <Box
+ w={8}
+ h={8}
+ style={{
+ borderRadius: "50%",
+ backgroundColor: `var(--mantine-color-${stateColorMap[record.state]}-filled)`,
+ flexShrink: 0,
+ }}
+ />
+ <Text size={size.fontSize} truncate fw={500}>
+ {record.name}
+ </Text>
+ </Group>
+ </Tooltip>
+ ),
},
- {
- ...columnsDefBase({ key: "id", showHeader: false }),
- enableSorting: false,
- Cell: ({ cell }) => {
- const id = cell.getValue<ExtendedDownloadClientItem["id"]>();
+ includeColumn("progress") && {
+ accessor: "progress",
+ title: t("items.progress.columnTitle"),
+ sortable: true,
+ width: progressColumnWidth,
+ render: (record) => {
+ const pct = Math.floor(record.progress * 100);
return (
- <Tooltip label={id}>
- <IconCirclesRelation size={16} />
+ <Tooltip label={buildProgressTooltip(record)} withArrow openDelay={300} position="top" color="dark">
+ <Group gap={4} wrap="nowrap" style={{ flex: 1 }}>
+ <Text size="xs" fw={500} w={36} ta="right" style={{ flexShrink: 0 }}>
+ {`${pct}%`}
+ </Text>
+ <Progress
+ value={pct}
+ color={progressColor(record.state, record.progress)}
+ size="sm"
+ style={{ flex: 1 }}
+ />
+ </Group>
</Tooltip>
);
},
},
- {
- ...columnsDefBase({ key: "index", showHeader: true }),
- Cell: ({ cell }) => {
- const index = cell.getValue<ExtendedDownloadClientItem["index"]>();
- return <Text size="xs">{index}</Text>;
- },
+ includeColumn("size") && {
+ accessor: "size",
+ title: t("items.size.columnTitle"),
+ sortable: true,
+ width: 80,
+ noWrap: true,
+ render: (record) => <Text size={size.fontSize}>{formatBytes(record.size)}</Text>,
},
- {
- ...columnsDefBase({ key: "integration", showHeader: false }),
- Cell: ({ cell }) => {
- const integration = cell.getValue<ExtendedDownloadClientItem["integration"]>();
- return (
- <Tooltip label={integration.name}>
- <Avatar size="xs" radius={0} src={getIconUrl(integration.kind)} />
- </Tooltip>
- );
- },
+ includeColumn("downSpeed") && {
+ accessor: "downSpeed",
+ title: t("items.downSpeed.columnTitle"),
+ sortable: true,
+ width: 90,
+ noWrap: true,
+ render: (record) => <SpeedCell speed={record.downSpeed} fontSize={size.fontSize} direction="down" />,
},
- {
- ...columnsDefBase({ key: "name", showHeader: true }),
- Cell: ({ cell }) => {
- const name = cell.getValue<ExtendedDownloadClientItem["name"]>();
- return (
- <Text size="xs" lineClamp={1} style={{ wordBreak: "break-all" }}>
- {name}
- </Text>
- );
- },
+ includeColumn("upSpeed") && {
+ accessor: "upSpeed",
+ title: t("items.upSpeed.columnTitle"),
+ sortable: true,
+ width: 90,
+ noWrap: true,
+ render: (record) => <SpeedCell speed={record.upSpeed} fontSize={size.fontSize} direction="up" />,
},
- {
- ...columnsDefBase({ key: "progress", showHeader: true }),
- Cell: ({ cell, row }) => {
- const progress = cell.getValue<ExtendedDownloadClientItem["progress"]>();
- return (
- <Group align="center" gap="xs" wrap="nowrap" w="100%">
- <Text size="xs">
- {new Intl.NumberFormat("en", {
- style: "percent",
- notation: "compact",
- unitDisplay: "narrow",
- roundingMode: "floor",
- }).format(progress)}
+ includeColumn("time") && {
+ accessor: "time",
+ title: t("items.time.columnTitle"),
+ sortable: true,
+ width: 100,
+ noWrap: true,
+ render: (record) => {
+ if (record.time === 0)
+ return (
+ <Text size={size.fontSize} c="dimmed">
+ ∞
</Text>
- <Progress
- w="100%"
- value={Math.floor(progress * 100)}
- color={row.original.state === "paused" ? "yellow" : progress === 1 ? "green" : "blue"}
- radius="lg"
- />
- </Group>
- );
+ );
+ return <Text size={size.fontSize}>{dayjs().add(record.time, "milliseconds").fromNow(true)}</Text>;
},
},
- {
- ...columnsDefBase({ key: "ratio", showHeader: true }),
- sortUndefined: "last",
- Cell: ({ cell }) => {
- const ratio = cell.getValue<ExtendedDownloadClientItem["ratio"]>();
- return ratio !== undefined && <Text size="xs">{ratio.toFixed(ratio >= 100 ? 0 : ratio >= 10 ? 1 : 2)}</Text>;
- },
+ includeColumn("state") && {
+ accessor: "state",
+ title: t("items.state.columnTitle"),
+ width: 90,
+ render: (record) => (
+ <Badge size="xs" variant="light" color={stateColorMap[record.state]}>
+ {t(`states.${record.state}`)}
+ </Badge>
+ ),
},
- {
- ...columnsDefBase({ key: "received", showHeader: true }),
- Cell: ({ cell }) => {
- const received = cell.getValue<ExtendedDownloadClientItem["received"]>();
- return <Text size="xs">{formatBytes(received)}</Text>;
+ includeColumn("added") && {
+ accessor: "added",
+ title: t("items.added.columnTitle"),
+ sortable: true,
+ width: 90,
+ noWrap: true,
+ render: (record) => {
+ if (!record.added) return <Text size={size.fontSize}>—</Text>;
+ return <Text size={size.fontSize}>{dayjs(record.added).fromNow()}</Text>;
},
},
- {
- ...columnsDefBase({ key: "sent", showHeader: true }),
- sortUndefined: "last",
- Cell: ({ cell }) => {
- const sent = cell.getValue<ExtendedDownloadClientItem["sent"]>();
- return sent && <Text size="xs">{formatBytes(sent)}</Text>;
+ includeColumn("ratio") && {
+ accessor: "ratio",
+ title: t("items.ratio.columnTitle"),
+ sortable: true,
+ width: 60,
+ render: (record) => {
+ if (record.ratio === undefined) return null;
+ return <Text size={size.fontSize}>{formatRatio(record.ratio)}</Text>;
},
},
- {
- ...columnsDefBase({ key: "size", showHeader: true }),
- Cell: ({ cell }) => {
- const size = cell.getValue<ExtendedDownloadClientItem["size"]>();
- return <Text size="xs">{formatBytes(size)}</Text>;
- },
+ includeColumn("received") && {
+ accessor: "received",
+ title: t("items.received.columnTitle"),
+ sortable: true,
+ width: 80,
+ noWrap: true,
+ render: (record) => <Text size={size.fontSize}>{formatBytes(record.received)}</Text>,
},
- {
- ...columnsDefBase({ key: "state", showHeader: true }),
- enableSorting: false,
- Cell: ({ cell }) => {
- const state = cell.getValue<ExtendedDownloadClientItem["state"]>();
- return <Text size="xs">{t(`states.${state}`)}</Text>;
+ includeColumn("sent") && {
+ accessor: "sent",
+ title: t("items.sent.columnTitle"),
+ sortable: true,
+ width: 80,
+ noWrap: true,
+ render: (record) => {
+ if (!record.sent) return null;
+ return <Text size={size.fontSize}>{formatBytes(record.sent)}</Text>;
},
},
- {
- ...columnsDefBase({ key: "time", showHeader: true }),
- sortingFn: (rowA, rowB) => {
- const timeA = rowA.getValue<ExtendedDownloadClientItem["time"]>("time");
- const timeB = rowB.getValue<ExtendedDownloadClientItem["time"]>("time");
- // Map time values to canonical sort keys:
- // positive = ETA in ms (sort as-is, smaller = sooner)
- // 0 = stalled/infinite (sort last in ascending = Infinity)
- // negative = time since completion in ms (sort first in ascending = very negative)
- const toSortKey = (time: number) => (time === 0 ? Infinity : time);
- return toSortKey(timeA) - toSortKey(timeB);
- },
- Cell: ({ cell }) => {
- const time = cell.getValue<ExtendedDownloadClientItem["time"]>();
- return time === 0 ? <IconInfinity size={16} /> : <Text size="xs">{dayjs().add(time).fromNow()}</Text>;
+ includeColumn("category") && {
+ accessor: "category",
+ title: t("items.category.columnTitle"),
+ width: 80,
+ ellipsis: true,
+ render: (record) => {
+ const display = formatCategoryDisplay(record.category);
+ if (!display) return null;
+ return (
+ <Text size={size.fontSize} truncate>
+ {display}
+ </Text>
+ );
},
},
- {
- ...columnsDefBase({ key: "type", showHeader: true }),
- Cell: ({ cell }) => {
- const type = cell.getValue<ExtendedDownloadClientItem["type"]>();
- return <Text size="xs">{type}</Text>;
- },
+ includeColumn("index") && {
+ accessor: "index",
+ title: t("items.index.columnTitle"),
+ sortable: true,
+ width: 40,
+ render: (record) => <Text size={size.fontSize}>{record.index}</Text>,
},
- {
- ...columnsDefBase({ key: "upSpeed", showHeader: true }),
- sortUndefined: "last",
- Cell: ({ cell }) => {
- const upSpeed = cell.getValue<ExtendedDownloadClientItem["upSpeed"]>();
- return upSpeed && <Text size="xs">{formatByteRate(upSpeed)}</Text>;
- },
+ includeColumn("type") && {
+ accessor: "type",
+ title: t("items.type.columnTitle"),
+ sortable: true,
+ width: 70,
+ render: (record) => (
+ <Text size={size.fontSize} tt="capitalize">
+ {record.type}
+ </Text>
+ ),
},
- ],
- [columnsDefBase, t, tCommon],
- );
+ ];
+ return cols.filter(Boolean) as DataTableColumn<ExtendedDownloadClientItem>[];
+ }, [columnContext, t, size, progressColumnWidth]);
- //Table build and config
- const table = useMantineReactTable({
- columns,
- data,
- enablePagination: false,
- enableTopToolbar: false,
- enableBottomToolbar: false,
- enableColumnActions: false,
- enableSorting: options.enableRowSorting && !isEditMode,
- enableMultiSort: true,
- enableStickyHeader: false,
- enableColumnOrdering: isEditMode,
- enableRowVirtualization: true,
- rowVirtualizerOptions: { overscan: 5 },
- mantinePaperProps: { flex: 1, withBorder: false, shadow: undefined, bg: "transparent" },
- mantineTableContainerProps: { style: { height: "100%" } },
- mantineTableProps: {
- className: "downloads-widget-table",
- },
- mantineTableBodyProps: { style: editStyle },
- mantineTableHeadCellProps: {
- p: 4,
- },
- mantineTableBodyCellProps: ({ cell, row }) => ({
- onClick: () => {
- setClickedIndex(row.index);
- if (cell.column.id !== "actions") open();
- },
- p: 4,
- }),
- onColumnOrderChange: (order) => {
- //Order has a tendency to add the disabled column at the end of the the real ordered array
- const columnOrder = (order as typeof options.columns).filter((column) => options.columns.includes(column));
- setOptions({ newOptions: { columns: columnOrder } });
- },
- initialState: {
- sorting: [{ id: options.defaultSort, desc: options.descendingDefaultSort }],
- columnVisibility: {
- actions: false,
- added: false,
- category: false,
- downSpeed: false,
- id: false,
- index: false,
- integration: false,
- name: false,
- progress: false,
- ratio: false,
- received: false,
- sent: false,
- size: false,
- state: false,
- time: false,
- type: false,
- upSpeed: false,
- } satisfies Record<keyof ExtendedDownloadClientItem, boolean>,
- columnOrder: options.columns,
- },
- state: {
- columnVisibility,
- columnOrder: options.columns,
+ const storeKey = `downloads-${itemId ?? "preview"}-${[...options.columns].toSorted().join(",")}`;
+ const { effectiveColumns, columnsOrder, columnsWidth, setColumnsOrder, setMultipleColumnWidths } =
+ useDataTableColumns<ExtendedDownloadClientItem>({
+ key: storeKey,
+ columns,
+ });
+
+ const lastStoreKey = useRef(storeKey);
+ const hydrated = useRef(false);
+ useEffect(() => {
+ if (lastStoreKey.current !== storeKey) {
+ lastStoreKey.current = storeKey;
+ hydrated.current = false;
+ }
+ if (hydrated.current) return;
+ if (savedOrder.length > 0) setColumnsOrder(savedOrder);
+ if (Object.keys(savedWidths).length > 0) {
+ setMultipleColumnWidths(Object.entries(savedWidths).map(([accessor, w]) => ({ accessor, width: w })));
+ }
+ // ponytail: defer hydrated flag so the persist effect skips the restore echo
+ requestAnimationFrame(() => {
+ hydrated.current = true;
+ });
+ }, [storeKey, savedOrder, savedWidths, setColumnsOrder, setMultipleColumnWidths]);
+
+ const prevOrder = useRef(columnsOrder);
+ const prevWidths = useRef(columnsWidth);
+ useEffect(() => {
+ if (!hydrated.current) return;
+ const orderChanged = JSON.stringify(columnsOrder) !== JSON.stringify(prevOrder.current);
+ const widthsChanged = JSON.stringify(columnsWidth) !== JSON.stringify(prevWidths.current);
+ prevOrder.current = columnsOrder;
+ prevWidths.current = columnsWidth;
+
+ if (!orderChanged && !widthsChanged) return;
+ if (orderChanged) persistOption({ columnOrder: JSON.stringify(columnsOrder) });
+ if (widthsChanged) {
+ const widthMap: Record<string, number> = {};
+ for (const entry of columnsWidth) {
+ const key = Object.keys(entry)[0];
+ if (!key) continue;
+ const w = entry[key as keyof typeof entry];
+ if (typeof w === "number") widthMap[key] = w;
+ else if (typeof w === "string" && w.endsWith("px")) widthMap[key] = parseInt(w, 10);
+ }
+ persistOption({ columnWidths: JSON.stringify(widthMap) });
+ }
+ }, [columnsOrder, columnsWidth, persistOption]);
+
+ const handleContextMenu = useCallback(
+ ({ record, event }: { record: ExtendedDownloadClientItem; event: React.MouseEvent }) => {
+ event.preventDefault();
+ setContextMenu({ x: event.clientX, y: event.clientY, item: record });
},
- });
+ [],
+ );
- //Used for Global Torrent Ratio
- const globalTraffic = clients
- .filter(({ integration: { kind } }) =>
- getIntegrationKindsByCategory("torrent").some((integrationKind) => integrationKind === kind),
- )
- .reduce(
- ({ up, down }, { status }) => ({
- up: up + (status?.totalUp ?? 0),
- down: down + (status?.totalDown ?? 0),
- }),
- { up: 0, down: 0 },
- );
+ const closeContextMenu = useCallback(() => setContextMenu(null), []);
+
+ const totalSpeed = clients.reduce((sum, c) => sum + (c.status?.rates.down ?? 0), 0);
+ const totalUpSpeed = clients.reduce((sum, c) => sum + (c.status?.rates.up ?? 0), 0);
+ const globalRatio = useMemo(() => {
+ const traffic = clients
+ .filter(({ integration: { kind } }) => getIntegrationKindsByCategory("torrent").some((k) => k === kind))
+ .reduce(
+ ({ up, down }, { status }) => ({ up: up + (status?.totalUp ?? 0), down: down + (status?.totalDown ?? 0) }),
+ { up: 0, down: 0 },
+ );
+ if (traffic.down <= 0) return 0;
+ return traffic.up / traffic.down;
+ }, [clients]);
+
+ const availableStatuses = useMemo(() => [...new Set(data.map(({ state }) => state))], [data]);
+
+ const queueStats = useMemo(() => {
+ const stateCounts: Record<string, number> = {};
+ let totalSize = 0;
+ let completedSize = 0;
+ for (const item of data) {
+ stateCounts[item.state] = (stateCounts[item.state] ?? 0) + 1;
+ totalSize += item.size;
+ completedSize += item.received ?? item.size * item.progress;
+ }
+ return { stateCounts, totalSize, completedSize, totalItems: data.length };
+ }, [data]);
- if (options.columns.length === 0)
+ if (options.columns.length === 0) {
return (
<Center h="100%">
<Text>{t("errors.noColumns")}</Text>
</Center>
);
+ }
+
+ if (isError && currentItems.length === 0) {
+ return (
+ <Center h="100%">
+ <Text c="red">{t("errors.noCommunications")}</Text>
+ </Center>
+ );
+ }
+
+ let tablePointerEvents: React.CSSProperties["pointerEvents"];
+ if (isEditMode) tablePointerEvents = "none";
+
+ let rowContextMenuHandler: typeof handleContextMenu | undefined = handleContextMenu;
+ if (isEditMode) rowContextMenuHandler = undefined;
- //The actual widget
return (
- <Stack gap={0} h="100%" display="flex">
- <MantineReactTable table={table} />
- <Group
- p={4}
- justify={integrationTypes.includes("torrent") ? "space-between" : "end"}
- style={{
- borderTop: "0.0625rem solid var(--border-color)",
- }}
- >
- {integrationTypes.includes("torrent") && (
- <Group>
- <Text size="xs" fw="bold">{`${t("globalRatio")}:`}</Text>
- <Text size="xs">{(globalTraffic.up / globalTraffic.down).toFixed(2)}</Text>
- </Group>
- )}
- <ClientsControl
+ <Stack gap={0} h="100%" style={{ overflow: "hidden" }}>
+ {showStats && (
+ <GlobalStatsBar
+ queueStats={queueStats}
+ totalSpeed={totalSpeed}
+ totalUpSpeed={totalUpSpeed}
+ globalRatio={globalRatio}
+ hasTorrents={hasTorrents}
clients={clients}
- filters={quickFilters}
- setFilters={setQuickFilters}
- availableStatuses={availableStatuses}
/>
- </Group>
- <ItemInfoModal items={data} currentIndex={clickedIndex} opened={opened} onClose={close} />
+ )}
+
+ <Box style={{ flex: 1, minHeight: 0, position: "relative" }}>
+ <DataTable
+ style={{ pointerEvents: tablePointerEvents }}
+ withTableBorder={false}
+ borderRadius={0}
+ highlightOnHover
+ striped="odd"
+ stripedColor={{ dark: "dark.7", light: "gray.0" }}
+ highlightOnHoverColor={{ dark: "dark.5", light: "gray.1" }}
+ verticalAlign="center"
+ fetching={isFetching && currentItems.length === 0}
+ loaderBackgroundBlur={2}
+ fz={size.fontSize}
+ records={sortedData}
+ columns={effectiveColumns}
+ storeColumnsKey={storeKey}
+ textSelectionDisabled
+ sortStatus={sortStatus}
+ onSortStatusChange={setSortStatus}
+ noRecordsText={t("errors.noItems")}
+ idAccessor={(record) => `${record.integration.id}:${record.id}`}
+ height="100%"
+ className="downloads-table"
+ defaultColumnProps={{
+ noWrap: true,
+ draggable: true,
+ resizable: true,
+ cellsStyle: () => ({ padding: `${size.cellPadding}px 8px` }),
+ }}
+ scrollAreaProps={{ type: "auto", scrollbarSize: 6 }}
+ customRowAttributes={(_, index) => ({ "data-row-index": index })}
+ onRowContextMenu={rowContextMenuHandler}
+ rowBackgroundColor={(record) => rowBgAlpha[record.state]}
+ rowExpansion={{
+ trigger: "click",
+ allowMultiple: true,
+ collapseProps: {
+ transitionDuration: 200,
+ animateOpacity: true,
+ transitionTimingFunction: "ease-out",
+ },
+ content: ({ record, collapse }) => <ExpandedRow item={record} collapse={collapse} />,
+ }}
+ onScroll={() => {
+ if (contextMenu) closeContextMenu();
+ }}
+ />
+ </Box>
+
+ <WidgetFooter
+ clients={clients}
+ totalSpeed={totalSpeed}
+ totalUpSpeed={totalUpSpeed}
+ globalRatio={globalRatio}
+ hasTorrents={hasTorrents}
+ clientFilter={clientFilter}
+ setClientFilter={setClientFilter}
+ statusFilter={statusFilter}
+ setStatusFilter={setStatusFilter}
+ availableStatuses={availableStatuses}
+ pauseQueue={mutatePauseQueue}
+ resumeQueue={mutateResumeQueue}
+ showStats={showStats}
+ toggleStats={toggleStats}
+ />
+
+ {contextMenu && <RowContextMenu state={contextMenu} onClose={closeContextMenu} t={t} />}
</Stack>
);
}
-interface ItemInfoModalProps {
- items: ExtendedDownloadClientItem[];
- currentIndex: number;
- opened: boolean;
- onClose: () => void;
-}
+function buildHoverTooltip(record: ExtendedDownloadClientItem, t: DownloadsT): React.ReactNode {
+ const lines: { label: string; value: string }[] = [
+ { label: t("items.size.detailsTitle"), value: `${formatBytes(record.received)} / ${formatBytes(record.size)}` },
+ { label: t("items.state.detailsTitle"), value: t(`states.${record.state}`) },
+ ];
+
+ if (record.downSpeed) {
+ lines.push({ label: t("items.downSpeed.detailsTitle"), value: formatByteRate(record.downSpeed) });
+ }
+ if (record.upSpeed) {
+ lines.push({ label: t("items.upSpeed.detailsTitle"), value: formatByteRate(record.upSpeed) });
+ }
+ if (record.time !== 0) {
+ lines.push({ label: t("items.time.eta"), value: dayjs().add(record.time, "milliseconds").fromNow() });
+ }
+ if (record.ratio !== undefined) {
+ lines.push({ label: t("items.ratio.detailsTitle"), value: record.ratio.toFixed(2) });
+ }
+ const categoryDisplay = formatCategoryDisplay(record.category);
+ if (categoryDisplay) {
+ lines.push({ label: t("items.category.detailsTitle"), value: categoryDisplay });
+ }
-const ItemInfoModal = ({ items, currentIndex, opened, onClose }: ItemInfoModalProps) => {
- const item = useMemo<ExtendedDownloadClientItem | undefined>(() => items[currentIndex], [items, currentIndex]);
- const t = useScopedI18n("widget.downloads.states");
- //The use case for "No item found" should be impossible, hence no translation
return (
- <Modal opened={opened} onClose={onClose} centered title={item?.id ?? "ERROR"} size="auto">
- {item === undefined ? (
- <Center>{"No item found"}</Center>
- ) : (
- <Stack align="center">
- <Title>{item.name}</Title>
- <Group>
- <Avatar src={getIconUrl(item.integration.kind)} />
- <Text>{`${item.integration.name} (${item.integration.kind})`}</Text>
- </Group>
- <NormalizedLine itemKey="index" values={item.index} />
- <NormalizedLine itemKey="type" values={item.type} />
- <NormalizedLine itemKey="state" values={t(item.state)} />
- {item.type !== "miscellaneous" && (
- <NormalizedLine
- itemKey="upSpeed"
- values={item.upSpeed === undefined ? undefined : formatByteRate(item.upSpeed)}
- />
- )}
+ <Stack gap={2}>
+ <Text size="xs" fw={600} style={{ wordBreak: "break-all" }}>
+ {record.name}
+ </Text>
+ <Divider my={2} />
+ {lines.map(({ label, value }) => (
+ <Group key={label} gap={4} justify="space-between">
+ <Text size="xs" c="dimmed">
+ {label}
+ </Text>
+ <Text size="xs" fw={500}>
+ {value}
+ </Text>
+ </Group>
+ ))}
+ </Stack>
+ );
+}
- <NormalizedLine
- itemKey="downSpeed"
- values={item.downSpeed === undefined ? undefined : formatByteRate(item.downSpeed)}
- />
+function ExpandedRow({ item, collapse }: { item: ExtendedDownloadClientItem; collapse: () => void }) {
+ const t = useScopedI18n("widget.downloads");
+ const progressPercent = Math.floor(item.progress * 100);
+ const categoryDisplay = formatCategoryDisplay(item.category);
- {item.type !== "miscellaneous" && (
- <NormalizedLine itemKey="sent" values={item.sent === undefined ? undefined : formatBytes(item.sent)} />
- )}
+ let timeDisplay = "∞";
+ if (item.time !== 0) timeDisplay = dayjs().add(item.time, "milliseconds").fromNow();
+
+ return (
+ <Box
+ px="sm"
+ py="xs"
+ style={{ borderBottom: "1px solid var(--mantine-color-default-border)", cursor: "pointer" }}
+ onClick={collapse}
+ >
+ <Group gap="md" align="flex-start" wrap="nowrap">
+ <RingProgress
+ size={52}
+ thickness={5}
+ roundCaps
+ sections={[{ value: progressPercent, color: progressColor(item.state, item.progress) }]}
+ label={<Text ta="center" fw={700} style={{ fontSize: 10 }}>{`${progressPercent}%`}</Text>}
+ />
+
+ <Stack gap={4} style={{ flex: 1 }}>
+ <Group gap="xs" wrap="nowrap">
+ <Avatar size={16} radius={0} src={getIconUrl(item.integration.kind)} />
+ <Text size="xs" fw={600} truncate>
+ {item.name}
+ </Text>
+ <Badge size="xs" variant="light" color={stateColorMap[item.state]} ml="auto" style={{ flexShrink: 0 }}>
+ {t(`states.${item.state}`)}
+ </Badge>
+ </Group>
- <NormalizedLine itemKey="received" values={formatBytes(item.received)} />
- <NormalizedLine itemKey="size" values={formatBytes(item.size)} />
- <NormalizedLine
- itemKey="progress"
- values={new Intl.NumberFormat("en", {
- style: "percent",
- notation: "compact",
- unitDisplay: "narrow",
- }).format(item.progress)}
- />
- {item.type !== "miscellaneous" && <NormalizedLine itemKey="ratio" values={item.ratio} />}
- <NormalizedLine itemKey="added" values={item.added === undefined ? "unknown" : dayjs(item.added).format()} />
- <NormalizedLine
- itemKey="time"
- values={item.time !== 0 ? dayjs().add(item.time, "milliseconds").fromNow() : "∞"}
- />
- <NormalizedLine itemKey="category" values={item.category} />
+ <SimpleGrid cols={3} spacing={4} verticalSpacing={2}>
+ <DetailPair
+ label={t("items.size.detailsTitle")}
+ value={`${formatBytes(item.received)} / ${formatBytes(item.size)}`}
+ />
+ {item.downSpeed !== undefined && item.downSpeed > 0 && (
+ <DetailPair
+ label={t("items.downSpeed.detailsTitle")}
+ value={formatByteRate(item.downSpeed)}
+ icon={<IconDownload size={10} />}
+ color="blue"
+ />
+ )}
+ {item.upSpeed !== undefined && item.upSpeed > 0 && (
+ <DetailPair
+ label={t("items.upSpeed.detailsTitle")}
+ value={formatByteRate(item.upSpeed)}
+ icon={<IconUpload size={10} />}
+ color="green"
+ />
+ )}
+ {item.ratio !== undefined && (
+ <DetailPair label={t("items.ratio.detailsTitle")} value={item.ratio.toFixed(2)} />
+ )}
+ <DetailPair label={t("items.time.detailsTitle")} value={timeDisplay} />
+ {item.sent !== undefined && (
+ <DetailPair label={t("items.sent.detailsTitle")} value={formatBytes(item.sent)} />
+ )}
+ {item.added !== undefined && (
+ <DetailPair label={t("items.added.detailsTitle")} value={dayjs(item.added).format("YYYY-MM-DD HH:mm")} />
+ )}
+ {categoryDisplay && <DetailPair label={t("items.category.detailsTitle")} value={categoryDisplay} />}
+ <DetailPair label={t("items.id.detailsTitle")} value={item.id} />
+ </SimpleGrid>
</Stack>
- )}
- </Modal>
+ </Group>
+ </Box>
);
-};
+}
-const NormalizedLine = ({
- itemKey,
- values,
+function DetailPair({
+ label,
+ value,
+ icon,
+ color,
}: {
- itemKey: Exclude<keyof ExtendedDownloadClientItem, "integration" | "actions" | "name" | "id">;
- values?: number | string | string[];
-}) => {
- const t = useScopedI18n("widget.downloads.items");
- if (typeof values !== "number" && (values === undefined || values.length === 0)) return null;
+ label: string;
+ value: string;
+ icon?: React.ReactNode;
+ color?: string;
+}) {
return (
- <Group w="100%" display="flex" align="top" justify="space-between" wrap="nowrap">
- <Text>{`${t(`${itemKey}.detailsTitle`)}:`}</Text>
- {Array.isArray(values) ? (
- <Stack>
- {values.map((value) => (
- <Text key={value}>{value}</Text>
- ))}
- </Stack>
- ) : (
- <Text>{values}</Text>
- )}
+ <Group gap={4} wrap="nowrap">
+ <Text size="xs" c="dimmed" style={{ whiteSpace: "nowrap", fontSize: 10 }}>
+ {label}:
+ </Text>
+ <Group gap={2} wrap="nowrap">
+ {icon}
+ <Text size="xs" fw={500} c={color} truncate style={{ fontSize: 10 }}>
+ {value}
+ </Text>
+ </Group>
</Group>
);
-};
+}
-interface ClientsControlProps {
+function GlobalStatsBar({
+ queueStats,
+ totalSpeed,
+ totalUpSpeed,
+ globalRatio,
+ hasTorrents,
+ clients,
+}: {
+ queueStats: { stateCounts: Record<string, number>; totalSize: number; completedSize: number; totalItems: number };
+ totalSpeed: number;
+ totalUpSpeed: number;
+ globalRatio: number;
+ hasTorrents: boolean;
clients: ExtendedClientStatus[];
- filters: QuickFilter;
- setFilters: (filters: QuickFilter) => void;
- availableStatuses: QuickFilter["statuses"];
+}) {
+ const t = useScopedI18n("widget.downloads");
+
+ let overallProgress = 0;
+ if (queueStats.totalSize > 0) overallProgress = queueStats.completedSize / queueStats.totalSize;
+ const overallProgressPct = Math.floor(overallProgress * 100);
+
+ return (
+ <Box px={8} py={6} style={{ borderBottom: "1px solid var(--mantine-color-default-border)" }}>
+ <Group justify="space-between" gap="xs">
+ <Group gap="md">
+ <Tooltip label={t("stats.overallProgress")} withArrow>
+ <Group gap={4}>
+ <Progress value={overallProgressPct} color="blue" size="xs" w={40} />
+ <Text size="xs" fw={600}>{`${overallProgressPct}%`}</Text>
+ </Group>
+ </Tooltip>
+
+ <Tooltip label={t("stats.totalSize")} withArrow>
+ <Group gap={4}>
+ <IconDatabase size={12} style={{ opacity: 0.6 }} />
+ <Text size="xs">{`${formatBytes(queueStats.completedSize)} / ${formatBytes(queueStats.totalSize)}`}</Text>
+ </Group>
+ </Tooltip>
+ </Group>
+
+ <Group gap="md">
+ <Group gap={4}>
+ <IconDownload size={12} style={{ opacity: 0.6 }} />
+ <Text size="xs" fw={600} c="blue">
+ {formatByteRate(totalSpeed)}
+ </Text>
+ </Group>
+ {totalUpSpeed > 0 && (
+ <Group gap={4}>
+ <IconUpload size={12} style={{ opacity: 0.6 }} />
+ <Text size="xs" fw={600} c="green">
+ {formatByteRate(totalUpSpeed)}
+ </Text>
+ </Group>
+ )}
+ {hasTorrents && globalRatio > 0 && (
+ <Text size="xs" c="dimmed">{`${t("globalRatio")}: ${globalRatio.toFixed(2)}`}</Text>
+ )}
+ </Group>
+
+ <Group gap={6}>
+ {Object.entries(queueStats.stateCounts).map(([state, count]) => (
+ <Tooltip key={state} label={t(`states.${state as DownloadState}`)} withArrow>
+ <Badge size="xs" variant="dot" color={stateColorMap[state as DownloadState]}>
+ {count}
+ </Badge>
+ </Tooltip>
+ ))}
+ <Text size="xs" c="dimmed">
+ {t("stats.clients", { count: clients.length })}
+ </Text>
+ </Group>
+ </Group>
+ </Box>
+ );
}
-const ClientsControl = ({ clients, filters, setFilters, availableStatuses }: ClientsControlProps) => {
- const integrationsStatuses = clients.reduce(
- (acc, { status, integration: { id }, interact }) =>
- status && interact ? (acc[status.paused ? "paused" : "active"].push(id), acc) : acc,
- { paused: [] as string[], active: [] as string[] },
+function RowContextMenu({ state, onClose, t }: { state: ContextMenuState; onClose: () => void; t: DownloadsT }) {
+ const { item } = state;
+ const isPaused = item.state === "paused";
+ const hasActions = !!item.actions;
+ const [showDeleteConfirm, { open: openDelete }] = useDisclosure(false);
+
+ let PauseResumeIcon = IconPlayerPause;
+ let pauseResumeInvoke = item.actions?.pause;
+ let pauseResumeLabel = t("actions.item.pause");
+ if (isPaused) {
+ PauseResumeIcon = IconPlayerPlay;
+ pauseResumeInvoke = item.actions?.resume;
+ pauseResumeLabel = t("actions.item.resume");
+ }
+
+ return (
+ <Portal>
+ <Box
+ pos="fixed"
+ top={0}
+ left={0}
+ w="100vw"
+ h="100vh"
+ style={{ zIndex: 1000 }}
+ onClick={onClose}
+ onContextMenu={(e) => {
+ e.preventDefault();
+ onClose();
+ }}
+ >
+ <Menu
+ opened
+ shadow="md"
+ position="bottom-start"
+ withinPortal={false}
+ onClose={onClose}
+ closeOnItemClick={false}
+ >
+ <Menu.Target>
+ <Box pos="fixed" style={{ left: state.x, top: state.y, width: 1, height: 1 }} />
+ </Menu.Target>
+ <Menu.Dropdown>
+ <Menu.Label>{truncateText(item.name, 40)}</Menu.Label>
+
+ <Menu.Item
+ leftSection={<IconInfoCircle size={14} />}
+ onClick={() => {
+ void navigator.clipboard.writeText(item.name).catch(() => {});
+ onClose();
+ }}
+ >
+ {t("contextMenu.copyName")}
+ </Menu.Item>
+
+ {item.id && (
+ <Menu.Item
+ leftSection={<IconCopy size={14} />}
+ onClick={() => {
+ void navigator.clipboard.writeText(item.id).catch(() => {});
+ onClose();
+ }}
+ >
+ {t("contextMenu.copyId")}
+ </Menu.Item>
+ )}
+
+ {hasActions && (
+ <>
+ <Menu.Divider />
+ <Menu.Item
+ leftSection={<PauseResumeIcon size={14} />}
+ onClick={() => {
+ pauseResumeInvoke?.();
+ onClose();
+ }}
+ >
+ {pauseResumeLabel}
+ </Menu.Item>
+
+ {!showDeleteConfirm && (
+ <Menu.Item
+ color="red"
+ leftSection={<IconTrash size={14} />}
+ onClick={(e) => {
+ e.stopPropagation();
+ openDelete();
+ }}
+ >
+ {t("actions.item.delete.title")}
+ </Menu.Item>
+ )}
+
+ {showDeleteConfirm && (
+ <>
+ <Menu.Item
+ color="red"
+ leftSection={<IconTrash size={14} />}
+ onClick={() => {
+ item.actions?.delete({ fromDisk: false });
+ onClose();
+ }}
+ >
+ {t("actions.item.delete.entry")}
+ </Menu.Item>
+ <Menu.Item
+ color="red"
+ leftSection={<IconTrashX size={14} />}
+ onClick={() => {
+ item.actions?.delete({ fromDisk: true });
+ onClose();
+ }}
+ >
+ {t("actions.item.delete.entryAndFiles")}
+ </Menu.Item>
+ </>
+ )}
+ </>
+ )}
+ </Menu.Dropdown>
+ </Menu>
+ </Box>
+ </Portal>
);
- const someInteract = clients.some(({ interact }) => interact);
- const totalSpeed = formatByteRate(clients.reduce((count, { status }) => count + (status?.rates.down ?? 0), 0));
+}
- const utils = clientApi.useUtils();
- const invalidateDownloads = { onSettled: () => void utils.widget.downloads.getJobsAndStatuses.invalidate() };
- const { mutate: mutateResumeQueue } = clientApi.widget.downloads.resume.useMutation(invalidateDownloads);
- const { mutate: mutatePauseQueue } = clientApi.widget.downloads.pause.useMutation(invalidateDownloads);
- const [opened, { open, close }] = useDisclosure(false);
+interface WidgetFooterProps {
+ clients: ExtendedClientStatus[];
+ totalSpeed: number;
+ totalUpSpeed: number;
+ globalRatio: number;
+ hasTorrents: boolean;
+ clientFilter: string[];
+ setClientFilter: (ids: string[]) => void;
+ statusFilter: string[];
+ setStatusFilter: (statuses: string[]) => void;
+ availableStatuses: ExtendedDownloadClientItem["state"][];
+ pauseQueue: (args: { integrationIds: string[] }) => void;
+ resumeQueue: (args: { integrationIds: string[] }) => void;
+ showStats: boolean;
+ toggleStats: () => void;
+}
+
+function WidgetFooter({
+ clients,
+ totalSpeed,
+ totalUpSpeed,
+ globalRatio,
+ hasTorrents,
+ clientFilter,
+ setClientFilter,
+ statusFilter,
+ setStatusFilter,
+ availableStatuses,
+ pauseQueue,
+ resumeQueue,
+ showStats,
+ toggleStats,
+}: WidgetFooterProps) {
const t = useScopedI18n("widget.downloads");
+ const [filterOpen, { toggle: toggleFilter }] = useDisclosure(false);
+ const someInteract = clients.some(({ interact }) => interact);
+ const hasActiveFilter = clientFilter.length > 0 || statusFilter.length > 0;
+
+ const integrationsStatuses = { paused: [] as string[], active: [] as string[] };
+ for (const {
+ status,
+ integration: { id },
+ interact,
+ } of clients) {
+ if (!status || !interact) continue;
+ if (status.paused) integrationsStatuses.paused.push(id);
+ else integrationsStatuses.active.push(id);
+ }
+
+ let filterTooltip = t("footer.filter");
+ if (hasActiveFilter) filterTooltip = t("contextMenu.clearFilters");
+
+ let filterIconVariant: "filled" | "subtle" = "subtle";
+ if (hasActiveFilter) filterIconVariant = "filled";
+
+ let statsTooltip = t("stats.show");
+ if (showStats) statsTooltip = t("stats.hide");
+
+ let statsIconVariant: "filled" | "subtle" = "subtle";
+ if (showStats) statsIconVariant = "filled";
+
+ let FilterIcon = IconFilter;
+ if (hasActiveFilter) FilterIcon = IconFilterOff;
+
+ let StatsIcon = IconChevronDown;
+ if (showStats) StatsIcon = IconChevronUp;
+
return (
- <Group gap={5}>
- <Popover withinPortal={false} offset={0}>
- <Popover.Target>
- <ActionIcon size="xs" radius="lg" variant="light">
- <IconFilter />
- </ActionIcon>
- </Popover.Target>
- <Popover.Dropdown>
- <Stack gap="md" align="center">
- <Text fw="700">{t("items.integration.columnTitle")}</Text>
- <Chip.Group
- multiple
- value={filters.integrationKinds}
- onChange={(names) => setFilters({ ...filters, integrationKinds: names })}
- >
- {clients.map(({ integration }) => (
- <Chip key={integration.id} value={integration.name}>
- {integration.name}
- </Chip>
- ))}
- </Chip.Group>
- <Text fw="700">{t("items.state.columnTitle")}</Text>
- <Chip.Group
- multiple
- value={filters.statuses}
- onChange={(statuses) => setFilters({ ...filters, statuses: statuses })}
- >
- {availableStatuses.map((status) => (
- <Chip key={status} value={status}>
- {t(`states.${status}`)}
- </Chip>
- ))}
- </Chip.Group>
+ <Box style={{ borderTop: "1px solid var(--mantine-color-default-border)" }}>
+ {filterOpen && (
+ <Box px={8} py={6} style={{ borderBottom: "1px solid var(--mantine-color-default-border)" }}>
+ <Stack gap={6}>
+ {clients.length > 1 && (
+ <Group gap={4}>
+ <Text size="xs" fw={600} style={{ flexShrink: 0 }}>
+ {t("items.integration.columnTitle")}:
+ </Text>
+ <Group gap={4} wrap="wrap">
+ {clients.map(({ integration }) => {
+ const active = clientFilter.includes(integration.id);
+ let variant: "filled" | "light" = "light";
+ if (active) variant = "filled";
+ return (
+ <UnstyledButton
+ key={integration.id}
+ aria-pressed={active}
+ aria-label={integration.name}
+ onClick={() => setClientFilter(toggleArrayItem(clientFilter, integration.id))}
+ >
+ <Badge
+ size="xs"
+ variant={variant}
+ leftSection={<Avatar size={12} radius={0} src={getIconUrl(integration.kind)} />}
+ >
+ {integration.name}
+ </Badge>
+ </UnstyledButton>
+ );
+ })}
+ </Group>
+ </Group>
+ )}
+ {availableStatuses.length > 1 && (
+ <Group gap={4}>
+ <Text size="xs" fw={600} style={{ flexShrink: 0 }}>
+ {t("items.state.columnTitle")}:
+ </Text>
+ <Group gap={4} wrap="wrap">
+ {availableStatuses.map((status) => {
+ const active = statusFilter.includes(status);
+ let variant: "filled" | "light" = "light";
+ if (active) variant = "filled";
+ return (
+ <UnstyledButton
+ key={status}
+ aria-pressed={active}
+ aria-label={t(`states.${status}`)}
+ onClick={() => setStatusFilter(toggleArrayItem(statusFilter, status))}
+ >
+ <Badge size="xs" variant={variant} color={stateColorMap[status]}>
+ {t(`states.${status}`)}
+ </Badge>
+ </UnstyledButton>
+ );
+ })}
+ </Group>
+ </Group>
+ )}
</Stack>
- </Popover.Dropdown>
- </Popover>
- <AvatarGroup>
- {clients.map((client) => (
- <ClientAvatar key={client.integration.id} client={client} />
- ))}
- </AvatarGroup>
- {someInteract && (
- <Tooltip label={t("actions.clients.resume")}>
- <ActionIcon
- size="xs"
- radius="lg"
- disabled={integrationsStatuses.paused.length === 0}
- variant="light"
- onClick={() => mutateResumeQueue({ integrationIds: integrationsStatuses.paused })}
- >
- <IconPlayerPlay />
- </ActionIcon>
- </Tooltip>
- )}
- <Button
- h={20}
- size="xs"
- variant="light"
- radius="lg"
- fw="500"
- onClick={open}
- styles={{ label: { height: "fit-content" } }}
- >
- {totalSpeed}
- </Button>
- {someInteract && (
- <Tooltip label={t("actions.clients.pause")}>
- <ActionIcon
- size="xs"
- radius="xl"
- disabled={integrationsStatuses.active.length === 0}
- variant="light"
- onClick={() => mutatePauseQueue({ integrationIds: integrationsStatuses.active })}
- >
- <IconPlayerPause />
- </ActionIcon>
- </Tooltip>
+ </Box>
)}
- <Modal opened={opened} onClose={close} title={t("actions.clients.modalTitle")} centered size="auto">
- <Stack gap="10px">
- {clients.map((client) => (
- <Stack key={client.integration.id} gap="10px">
- <Divider />
- <Group wrap="nowrap" w="100%">
- <Paper radius={999}>
- <Group gap={5} pl={10} pr={15} fz={16} w={275} justify="space-between" wrap="nowrap">
- <Avatar radius={0} src={getIconUrl(client.integration.kind)} />
- {client.status ? (
- <Tooltip disabled={client.status.ratio === undefined} label={client.status.ratio?.toFixed(2)}>
- <Stack gap={0} pt={5} h={60} justify="center" flex={1}>
- {client.status.rates.up !== undefined ? (
- <Group display="flex" justify="center" c="green" w="100%" gap={5}>
- <Text flex={1} ta="right">
- {`↑ ${formatByteRate(client.status.rates.up)}`}
- </Text>
- <Text>{"-"}</Text>
- <Text flex={1} ta="left">
- {formatBytes(client.status.totalUp ?? 0)}
- </Text>
- </Group>
- ) : undefined}
- <Group display="flex" justify="center" c="blue" w="100%" gap={5}>
- <Text flex={1} ta="right">
- {`↓ ${formatByteRate(client.status.rates.down)}`}
- </Text>
- <Text>{"-"}</Text>
- <Text flex={1} ta="left">
- {formatBytes(Math.floor(client.status.totalDown ?? 0))}
- </Text>
- </Group>
- </Stack>
- </Tooltip>
- ) : (
- <Text c="red" ta="center">
- {t("errors.noCommunications")}
- </Text>
- )}
- </Group>
- </Paper>
- <Text lineClamp={1} fz={22}>
- {client.integration.name}
+
+ <Group px={8} py={4} justify="space-between">
+ <Group gap={6}>
+ <Tooltip label={filterTooltip}>
+ <ActionIcon
+ size="xs"
+ variant={filterIconVariant}
+ aria-label={filterTooltip}
+ onClick={() => {
+ if (hasActiveFilter && !filterOpen) {
+ setClientFilter([]);
+ setStatusFilter([]);
+ } else {
+ toggleFilter();
+ }
+ }}
+ >
+ <FilterIcon size={14} />
+ </ActionIcon>
+ </Tooltip>
+
+ <Tooltip label={statsTooltip}>
+ <ActionIcon size="xs" variant={statsIconVariant} aria-label={statsTooltip} onClick={toggleStats}>
+ <StatsIcon size={14} />
+ </ActionIcon>
+ </Tooltip>
+
+ <Group gap={2}>
+ {clients.map(({ integration }) => (
+ <ClientIndicator key={integration.id} integration={integration} />
+ ))}
+ </Group>
+ </Group>
+
+ <Group gap={8}>
+ {!showStats && hasTorrents && globalRatio > 0 && (
+ <Text size="xs" c="dimmed">{`${t("globalRatio")}: ${globalRatio.toFixed(2)}`}</Text>
+ )}
+
+ <Group gap={4}>
+ {someInteract && (
+ <Tooltip label={t("actions.clients.resume")}>
+ <ActionIcon
+ size="xs"
+ variant="subtle"
+ color="green"
+ aria-label={t("actions.clients.resume")}
+ disabled={integrationsStatuses.paused.length === 0}
+ onClick={() => resumeQueue({ integrationIds: integrationsStatuses.paused })}
+ >
+ <IconPlayerPlay size={14} />
+ </ActionIcon>
+ </Tooltip>
+ )}
+
+ {!showStats && (
+ <Group gap={2}>
+ <Text size="xs" fw={600} c="blue">
+ <IconDownload size={10} style={{ verticalAlign: "middle", marginRight: 2 }} />
+ {formatByteRate(totalSpeed)}
</Text>
- <Space flex={1} />
- {client.status && client.interact ? (
- <Tooltip label={t(`actions.client.${client.status.paused ? "resume" : "pause"}`)}>
- <ActionIcon
- radius={999}
- variant="light"
- size="lg"
- onClick={() => {
- (client.status?.paused ? mutateResumeQueue : mutatePauseQueue)({
- integrationIds: [client.integration.id],
- });
- }}
- >
- {client.status.paused ? <IconPlayerPlay /> : <IconPlayerPause />}
- </ActionIcon>
- </Tooltip>
- ) : (
- <ActionIcon radius={999} variant="light" size="lg" disabled>
- <IconX />
- </ActionIcon>
+ {totalUpSpeed > 0 && (
+ <Text size="xs" fw={600} c="green">
+ <IconUpload size={10} style={{ verticalAlign: "middle", marginRight: 2 }} />
+ {formatByteRate(totalUpSpeed)}
+ </Text>
)}
</Group>
- </Stack>
- ))}
- </Stack>
- </Modal>
- </Group>
- );
-};
+ )}
-interface ClientAvatarProps {
- client: ExtendedClientStatus;
+ {someInteract && (
+ <Tooltip label={t("actions.clients.pause")}>
+ <ActionIcon
+ size="xs"
+ variant="subtle"
+ color="red"
+ aria-label={t("actions.clients.pause")}
+ disabled={integrationsStatuses.active.length === 0}
+ onClick={() => pauseQueue({ integrationIds: integrationsStatuses.active })}
+ >
+ <IconPlayerPause size={14} />
+ </ActionIcon>
+ </Tooltip>
+ )}
+ </Group>
+ </Group>
+ </Group>
+ </Box>
+ );
}
-const ClientAvatar = ({ client }: ClientAvatarProps) => {
- const isConnected = useIntegrationConnected(client.integration.updatedAt, { timeout: 30000 });
+function ClientIndicator({ integration }: { integration: ExtendedClientStatus["integration"] }) {
+ const isConnected = useIntegrationConnected(integration.updatedAt, { timeout: 30000 });
+
+ let tooltipLabel = integration.name;
+ const t = useScopedI18n("widget.downloads");
+ if (!isConnected) tooltipLabel = `${integration.name} ${t("disconnected")}`;
+
+ let avatarFilter: string | undefined;
+ let avatarOpacity = 1;
+ if (!isConnected) {
+ avatarFilter = "grayscale(100%)";
+ avatarOpacity = 0.5;
+ }
return (
- <Avatar
- key={client.integration.id}
- src={getIconUrl(client.integration.kind)}
- style={{ filter: !isConnected ? "grayscale(100%)" : undefined }}
- size="sm"
- p={5}
- />
+ <Tooltip label={tooltipLabel}>
+ <Avatar
+ size={18}
+ radius={0}
+ src={getIconUrl(integration.kind)}
+ style={{ filter: avatarFilter, opacity: avatarOpacity }}
+ />
+ </Tooltip>
);
-};
+}
diff --git a/packages/widgets/src/downloads/index.ts b/packages/widgets/src/downloads/index.ts
index 0d9c66ddd..cc8f9a5b0 100644
--- a/packages/widgets/src/downloads/index.ts
+++ b/packages/widgets/src/downloads/index.ts
@@ -8,28 +8,37 @@ import { createWidgetDefinition } from "../definition";
import { optionsBuilder } from "../options";
const columnsList = [
- "id",
- "actions",
+ "name",
+ "progress",
+ "size",
+ "downSpeed",
+ "upSpeed",
+ "time",
+ "state",
"added",
+ "ratio",
+ "received",
+ "sent",
"category",
- "downSpeed",
- "index",
"integration",
+ "index",
+ "type",
+] as const satisfies (keyof ExtendedDownloadClientItem)[];
+
+const sortColumns = [
"name",
"progress",
+ "size",
+ "downSpeed",
+ "upSpeed",
+ "time",
+ "added",
"ratio",
"received",
"sent",
- "size",
- "state",
- "time",
+ "index",
"type",
- "upSpeed",
-] as const satisfies (keyof ExtendedDownloadClientItem)[];
-const sortingExclusion = ["actions", "id", "state"] as const satisfies readonly (typeof columnsList)[number][];
-const columnsSort = columnsList.filter((column) =>
- sortingExclusion.every((exclusion) => exclusion !== column),
-) as Exclude<typeof columnsList, (typeof sortingExclusion)[number]>;
+] as const satisfies readonly (typeof columnsList)[number][];
export const { definition, componentLoader } = createWidgetDefinition("downloads", {
icon: IconDownload,
@@ -38,19 +47,16 @@ export const { definition, componentLoader } = createWidgetDefinition("downloads
return optionsBuilder.from(
(factory) => ({
columns: factory.multiSelect({
- defaultValue: ["integration", "name", "progress", "time", "actions"],
+ defaultValue: ["name", "progress", "downSpeed", "time", "state"],
options: columnsList.map((value) => ({
value,
label: (t) => t(`widget.downloads.items.${value}.columnTitle`),
})),
searchable: true,
}),
- enableRowSorting: factory.switch({
- defaultValue: false,
- }),
defaultSort: factory.select({
- defaultValue: "type",
- options: columnsSort.map((value) => ({
+ defaultValue: "progress",
+ options: sortColumns.map((value) => ({
value,
label: (t) => t(`widget.downloads.items.${value}.columnTitle`),
})),
@@ -68,7 +74,6 @@ export const { definition, componentLoader } = createWidgetDefinition("downloads
defaultValue: true,
}),
activeTorrentThreshold: factory.number({
- //in KiB/s
validate: z.number().min(0),
defaultValue: 0,
step: 1,
@@ -88,14 +93,12 @@ export const { definition, componentLoader } = createWidgetDefinition("downloads
validate: z.number().min(1),
withDescription: true,
}),
+ columnOrder: factory.text({ defaultValue: "" }),
+ columnWidths: factory.text({ defaultValue: "" }),
}),
{
- defaultSort: {
- shouldHide: (options) => !options.enableRowSorting,
- },
- descendingDefaultSort: {
- shouldHide: (options) => !options.enableRowSorting,
- },
+ columnOrder: { shouldHide: () => true },
+ columnWidths: { shouldHide: () => true },
showCompletedUsenet: {
shouldHide: (_, integrationKinds) =>
!getIntegrationKindsByCategory("usenet").some((kinds) => integrationKinds.includes(kinds)),
diff --git a/packages/widgets/src/downloads/styles.css b/packages/widgets/src/downloads/styles.css
index ae9bee8c1..98991c9f2 100644
--- a/packages/widgets/src/downloads/styles.css
+++ b/packages/widgets/src/downloads/styles.css
@@ -1,12 +1,52 @@
-/* Make the MantineReactTable transparent so the board card's opacity-controlled
- background shows through. MRT defaults to var(--mantine-color-body) which is opaque. */
-.downloads-widget-table,
-.downloads-widget-table .mantine-Table-table,
-.downloads-widget-table .mantine-Table-thead,
-.downloads-widget-table .mantine-Table-tbody,
-.downloads-widget-table .mantine-Table-tfoot,
-.downloads-widget-table .mantine-Table-tr,
-.downloads-widget-table th,
-.downloads-widget-table td {
+/* Make the DataTable transparent so the board card's opacity-controlled
+ background shows through. The mantine-datatable defaults to
+ var(--mantine-color-body) which is opaque. */
+.downloads-table,
+.downloads-table .mantine-datatable-table,
+.downloads-table .mantine-datatable-table thead,
+.downloads-table .mantine-datatable-table tbody,
+.downloads-table .mantine-datatable-table tfoot,
+.downloads-table th,
+.downloads-table td {
background-color: transparent !important;
}
+
+.downloads-table .mantine-datatable-table tr {
+ background-color: transparent;
+}
+
+.downloads-table .mantine-datatable-table tbody tr:hover {
+ background-color: color-mix(in srgb, var(--mantine-color-default-hover) 40%, transparent) !important;
+}
+
+.downloads-table th {
+ white-space: nowrap;
+ background-color: color-mix(in srgb, var(--mantine-color-body) 60%, transparent) !important;
+ backdrop-filter: blur(8px);
+}
+
+.downloads-table td {
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.downloads-table td .mantine-Text-root,
+.downloads-table td .mantine-Group-root {
+ white-space: nowrap;
+ flex-wrap: nowrap;
+}
+
+.downloads-table .mantine-datatable-header-cell-sortable-icon {
+ opacity: 0;
+ transition: opacity 150ms;
+}
+
+.downloads-table th:hover .mantine-datatable-header-cell-sortable-icon {
+ opacity: 1;
+}
+
+/* Row expansion styling */
+.downloads-table .mantine-datatable-row-expansion-cell {
+ background-color: color-mix(in srgb, var(--mantine-color-body) 40%, transparent) !important;
+}