Compare commits
30
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6ec705db4a | ||
|
|
f6ca2a40c5 | ||
|
|
85c6eef016 | ||
|
|
f0cb7ab3c8 | ||
|
|
6bf37756b8 | ||
|
|
32f315b37c | ||
|
|
37365daccb | ||
|
|
7c3aee944d | ||
|
|
c3a5e92947 | ||
|
|
3d4bb25f49 | ||
|
|
df48246001 | ||
|
|
a2a22a89bc | ||
|
|
ea049066e1 | ||
|
|
70b868544f | ||
|
|
88a6f44d0d | ||
|
|
5226138186 | ||
|
|
5c71c1aede | ||
|
|
5acf6cef32 | ||
|
|
32aa26db65 | ||
|
|
47cfc5be6c | ||
|
|
27686e00f3 | ||
|
|
d21d67fc59 | ||
|
|
30e2e084a4 | ||
|
|
7f7af15fc5 | ||
|
|
6dffa4d2df | ||
|
|
0963885764 | ||
|
|
d53de7c641 | ||
|
|
9edf6ca99b | ||
|
|
fc0da8dedf | ||
|
|
b004186183 |
No files matched your search
@@ -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
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 210 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 21 KiB After Width: | Height: | Size: 122 KiB |
@@ -4,6 +4,7 @@ description: 'Allows you to view and manage your Downloads from both Torrent and
|
|||||||
hide_title: true
|
hide_title: true
|
||||||
---
|
---
|
||||||
|
|
||||||
|
import { aria2Integration } from '@site/docs/integrations/aria2';
|
||||||
import { delugeIntegration } from '@site/docs/integrations/deluge';
|
import { delugeIntegration } from '@site/docs/integrations/deluge';
|
||||||
import { nzbgetIntegration } from '@site/docs/integrations/nzbget';
|
import { nzbgetIntegration } from '@site/docs/integrations/nzbget';
|
||||||
import { qBittorentIntegration } from '@site/docs/integrations/q-bittorent';
|
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 { WidgetConfig } from '@site/src/components/widgets/configuration';
|
||||||
import { WidgetHeader } from '@site/src/components/widgets/header';
|
import { WidgetHeader } from '@site/src/components/widgets/header';
|
||||||
import { WidgetIntegrations } from '@site/src/components/widgets/integrations';
|
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 '.';
|
import { downloadsWidget } from '.';
|
||||||
|
|
||||||
|
|
||||||
@@ -25,16 +23,37 @@ import { downloadsWidget } from '.';
|
|||||||
categories={['Torrent client', 'Usenet client', 'Downloads']}
|
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
|
### Screenshots
|
||||||
|
|
||||||
import downloadsCard from './img/screenshot.png';
|
import downloadsCard from './img/screenshot.png';
|
||||||
|
import contextMenuImg from './img/context-menu.png';
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<img src={downloadsCard} alt="downloads" width={128 * 4} />
|
<img src={downloadsCard} alt="Downloads widget showing torrent and usenet items" width={128 * 4} />
|
||||||
</div>
|
</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
|
### Supported Integrations
|
||||||
|
|
||||||
<WidgetIntegrations items={[{
|
<WidgetIntegrations items={[{
|
||||||
@@ -52,16 +71,23 @@ import downloadsCard from './img/screenshot.png';
|
|||||||
}, {
|
}, {
|
||||||
integration: qBittorentIntegration,
|
integration: qBittorentIntegration,
|
||||||
note: "Torrent client"
|
note: "Torrent client"
|
||||||
|
}, {
|
||||||
|
integration: aria2Integration,
|
||||||
|
note: "Multi-protocol download client"
|
||||||
}, {
|
}, {
|
||||||
integration: slskdIntegration,
|
integration: slskdIntegration,
|
||||||
note: "Soulseek client"
|
note: "Soulseek client (read-only)"
|
||||||
}]} />
|
}]} />
|
||||||
|
|
||||||
### Interactions
|
### Interactions
|
||||||
|
|
||||||
- Pause / Resume one download by clicking on the according icon.
|
- **Right-click** any download to open a context menu with pause/resume, delete, and copy actions
|
||||||
- Delete one download by clicking on the trash icon. (Can also delete the files)
|
- **Click** any row to expand it and see full download details inline
|
||||||
- Pause / Resume all downloads by using the bottom button.
|
- **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
|
### Adding the widget
|
||||||
|
|
||||||
|
|||||||
@@ -2,26 +2,23 @@ import { WidgetDefinition } from "@site/src/types";
|
|||||||
import { IconDownload } from "@tabler/icons-react";
|
import { IconDownload } from "@tabler/icons-react";
|
||||||
|
|
||||||
const columnsList = [
|
const columnsList = [
|
||||||
"id",
|
|
||||||
"actions",
|
|
||||||
"added",
|
|
||||||
"category",
|
|
||||||
"downSpeed",
|
|
||||||
"index",
|
|
||||||
"integration",
|
|
||||||
"name",
|
"name",
|
||||||
"progress",
|
"progress",
|
||||||
|
"size",
|
||||||
|
"downSpeed",
|
||||||
|
"upSpeed",
|
||||||
|
"time",
|
||||||
|
"state",
|
||||||
|
"added",
|
||||||
"ratio",
|
"ratio",
|
||||||
"received",
|
"received",
|
||||||
"sent",
|
"sent",
|
||||||
"size",
|
"category",
|
||||||
"state",
|
"integration",
|
||||||
"time",
|
"index",
|
||||||
"type",
|
"type",
|
||||||
"upSpeed",
|
|
||||||
];
|
];
|
||||||
const sortingExclusion = ["actions", "id", "state"];
|
const sortColumns = columnsList.filter((c) => !["state", "category", "integration"].includes(c));
|
||||||
const columnsSort = columnsList.filter((column) => !sortingExclusion.some((exclusion) => exclusion === column));
|
|
||||||
|
|
||||||
export const downloadsWidget: WidgetDefinition = {
|
export const downloadsWidget: WidgetDefinition = {
|
||||||
icon: IconDownload,
|
icon: IconDownload,
|
||||||
@@ -32,25 +29,20 @@ export const downloadsWidget: WidgetDefinition = {
|
|||||||
items: [
|
items: [
|
||||||
{
|
{
|
||||||
name: "Columns to show",
|
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(", ")}`,
|
values: `List of columns: ${columnsList.join(", ")}`,
|
||||||
defaultValue: ["integration", "name", "progress", "time", "actions"].join(", "),
|
defaultValue: ["name", "progress", "downSpeed", "time", "state"].join(", "),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "Enable items sorting",
|
name: "Default sort column",
|
||||||
description: "Enables the sorting in the table.",
|
description: "The column used for initial sorting when the widget loads.",
|
||||||
values: { type: "boolean" },
|
defaultValue: "progress",
|
||||||
defaultValue: "no",
|
values: `List of columns: ${sortColumns.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: "Invert sorting",
|
name: "Invert sorting",
|
||||||
description: "This will invert the sorting order of the table.",
|
description: "This will invert the default sorting order.",
|
||||||
values: { type: "boolean" },
|
values: { type: "boolean" },
|
||||||
defaultValue: "no",
|
defaultValue: "no",
|
||||||
},
|
},
|
||||||
@@ -76,13 +68,13 @@ export const downloadsWidget: WidgetDefinition = {
|
|||||||
name: "Hide completed torrent under this threshold (in kiB/s)",
|
name: "Hide completed torrent under this threshold (in kiB/s)",
|
||||||
description:
|
description:
|
||||||
"This will hide completed torrent entries that have a download speed below the specified threshold.",
|
"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",
|
defaultValue: "0",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "Categories/names to filter",
|
name: "Categories/labels to filter",
|
||||||
description: "You can filter the items by categories or names. Use a comma to separate multiple values.",
|
description: "You can filter the items by categories or labels. Use a comma to separate multiple values.",
|
||||||
values: "Comma-separated list of categories or names",
|
values: "Comma-separated list of categories or labels",
|
||||||
defaultValue: "-",
|
defaultValue: "-",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -94,13 +86,13 @@ export const downloadsWidget: WidgetDefinition = {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "Use filter to calculate Ratio",
|
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" },
|
values: { type: "boolean" },
|
||||||
defaultValue: "yes",
|
defaultValue: "yes",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "Limit items per integration",
|
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",
|
values: "Any number above 1",
|
||||||
defaultValue: "50",
|
defaultValue: "50",
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
---
|
---
|
||||||
title: 'Immich Album Carousel'
|
title: 'Immich Album Carousel'
|
||||||
description: 'Shows a slideshow of pictures from an Immich album or your full library'
|
description: 'Shows a slideshow of your album pictures from Immich'
|
||||||
hide_title: true
|
hide_title: true
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -37,3 +37,4 @@ import screen from './img/screen.png';
|
|||||||
|
|
||||||
### Configuration
|
### Configuration
|
||||||
<WidgetConfig configuration={immichAlbumCarouselWidget.configuration} />
|
<WidgetConfig configuration={immichAlbumCarouselWidget.configuration} />
|
||||||
|
|
||||||
@@ -4,16 +4,15 @@ import { IconPhoto } from "@tabler/icons-react";
|
|||||||
export const immichAlbumCarouselWidget: WidgetDefinition = {
|
export const immichAlbumCarouselWidget: WidgetDefinition = {
|
||||||
icon: IconPhoto,
|
icon: IconPhoto,
|
||||||
name: "Immich Album",
|
name: "Immich Album",
|
||||||
description: "Shows a slideshow of pictures from an Immich album or your full library",
|
description: "Shows a slideshow of your album pictures from Immich",
|
||||||
path: "../../widgets/immich-album-carousel",
|
path: "../../widgets/immich-album-carousel",
|
||||||
configuration: {
|
configuration: {
|
||||||
items: [
|
items: [
|
||||||
{
|
{
|
||||||
name: "Album",
|
name: "Album",
|
||||||
description:
|
description: "Select the Immich album to show in the slideshow.",
|
||||||
"Select an Immich album or All photos. An empty selection also shows random photos from your full library.",
|
|
||||||
values: { type: "string" },
|
values: { type: "string" },
|
||||||
defaultValue: "All photos",
|
defaultValue: "",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "Interval in seconds",
|
name: "Interval in seconds",
|
||||||
|
|||||||
@@ -16,10 +16,7 @@ export default async function AppEditPage(props: AppEditPageProps) {
|
|||||||
const params = await props.params;
|
const params = await props.params;
|
||||||
const session = await auth();
|
const session = await auth();
|
||||||
|
|
||||||
if (
|
if (!session?.user.permissions.includes("app-modify-all")) {
|
||||||
!session?.user.permissions.includes("board-modify-all") ||
|
|
||||||
!session?.user.permissions.includes("app-modify-all")
|
|
||||||
) {
|
|
||||||
notFound();
|
notFound();
|
||||||
}
|
}
|
||||||
const app = await api.app.byId({ id: params.id });
|
const app = await api.app.byId({ id: params.id });
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import { DynamicBreadcrumb } from "~/components/navigation/dynamic-breadcrumb";
|
|||||||
export default async function AppNewPage() {
|
export default async function AppNewPage() {
|
||||||
const session = await auth();
|
const session = await auth();
|
||||||
|
|
||||||
if (!session?.user.permissions.includes("board-modify-all") || !session?.user.permissions.includes("app-create")) {
|
if (!session?.user.permissions.includes("app-create")) {
|
||||||
notFound();
|
notFound();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { Fragment } from "react";
|
import { Fragment } from "react";
|
||||||
import { notFound, redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
import { ActionIcon, ActionIconGroup, Anchor, Avatar, Card, Group, Stack, Text } from "@mantine/core";
|
import { ActionIcon, ActionIconGroup, Anchor, Avatar, Card, Group, Stack, Text } from "@mantine/core";
|
||||||
import { IconBox, IconPencil } from "@tabler/icons-react";
|
import { IconBox, IconPencil } from "@tabler/icons-react";
|
||||||
import { z } from "zod/v4";
|
import { z } from "zod/v4";
|
||||||
@@ -33,9 +33,6 @@ export default async function AppsPage(props: AppsPageProps) {
|
|||||||
if (!session) {
|
if (!session) {
|
||||||
redirect("/auth/login");
|
redirect("/auth/login");
|
||||||
}
|
}
|
||||||
if (!session.user.permissions.includes("board-modify-all")) {
|
|
||||||
notFound();
|
|
||||||
}
|
|
||||||
|
|
||||||
const searchParams = searchParamsSchema.parse(await props.searchParams);
|
const searchParams = searchParamsSchema.parse(await props.searchParams);
|
||||||
|
|
||||||
|
|||||||
@@ -61,7 +61,7 @@ export default async function ManageLayout({ children }: PropsWithChildren) {
|
|||||||
icon: IconBox,
|
icon: IconBox,
|
||||||
href: "/manage/apps",
|
href: "/manage/apps",
|
||||||
label: t("items.apps"),
|
label: t("items.apps"),
|
||||||
hidden: !session?.user.permissions.includes("board-modify-all"),
|
hidden: !session,
|
||||||
iconProps: {
|
iconProps: {
|
||||||
strokeWidth: 2.5,
|
strokeWidth: 2.5,
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -18,8 +18,7 @@ import { AppAccessControl } from "./app/app-access-control";
|
|||||||
const defaultIcon = "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/homarr.svg";
|
const defaultIcon = "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/homarr.svg";
|
||||||
|
|
||||||
export const appRouter = createTRPCRouter({
|
export const appRouter = createTRPCRouter({
|
||||||
getPaginated: permissionRequiredProcedure
|
getPaginated: protectedProcedure
|
||||||
.requiresPermission("board-modify-all")
|
|
||||||
.input(paginatedSchema)
|
.input(paginatedSchema)
|
||||||
.output(z.object({ items: z.array(selectAppSchema), totalCount: z.number() }))
|
.output(z.object({ items: z.array(selectAppSchema), totalCount: z.number() }))
|
||||||
.meta({
|
.meta({
|
||||||
|
|||||||
@@ -101,7 +101,7 @@ export const homeRouter = createTRPCRouter({
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (ctx.session?.user.permissions.includes("board-modify-all")) {
|
if (ctx.session?.user) {
|
||||||
statistics.push({
|
statistics.push({
|
||||||
titleKey: "app",
|
titleKey: "app",
|
||||||
subtitleKey: "resources",
|
subtitleKey: "resources",
|
||||||
|
|||||||
@@ -76,33 +76,6 @@ describe("all should return all apps", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("getPaginated should require board modification access", () => {
|
|
||||||
test("should throw FORBIDDEN without board-modify-all", async () => {
|
|
||||||
const caller = appRouter.createCaller({
|
|
||||||
db: createDb(),
|
|
||||||
deviceType: undefined,
|
|
||||||
session: createDefaultSession(),
|
|
||||||
});
|
|
||||||
|
|
||||||
await expect(caller.getPaginated({ page: 1, pageSize: 10 })).rejects.toThrow("Permission denied");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("should return apps with board-modify-all", async () => {
|
|
||||||
const db = createDb();
|
|
||||||
const caller = appRouter.createCaller({
|
|
||||||
db,
|
|
||||||
deviceType: undefined,
|
|
||||||
session: createDefaultSession(["board-modify-all"]),
|
|
||||||
});
|
|
||||||
await db.insert(apps).values({ id: "1", name: "Homarr", iconUrl: "https://homarr.dev/icon.svg" });
|
|
||||||
|
|
||||||
await expect(caller.getPaginated({ page: 1, pageSize: 10 })).resolves.toMatchObject({
|
|
||||||
totalCount: 1,
|
|
||||||
items: [{ id: "1" }],
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("byId should return an app by id", () => {
|
describe("byId should return an app by id", () => {
|
||||||
test("should return an app by id when canUserSeeAppAsync returns true", async () => {
|
test("should return an app by id when canUserSeeAppAsync returns true", async () => {
|
||||||
// Arrange
|
// Arrange
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ export const immichRouter = createTRPCRouter({
|
|||||||
.concat(createImmichIntegrationMiddleware("query"))
|
.concat(createImmichIntegrationMiddleware("query"))
|
||||||
.input(
|
.input(
|
||||||
z.object({
|
z.object({
|
||||||
albumId: z.string().optional(),
|
albumId: z.string(),
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
.query(async ({ ctx, input }) => {
|
.query(async ({ ctx, input }) => {
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ export class QBitTorrentIntegration extends Integration implements IDownloadClie
|
|||||||
public async getClientJobsAndStatusAsync(input: { limit: number }): Promise<DownloadClientJobsAndStatus> {
|
public async getClientJobsAndStatusAsync(input: { limit: number }): Promise<DownloadClientJobsAndStatus> {
|
||||||
const type = "torrent";
|
const type = "torrent";
|
||||||
const client = await this.getClientAsync();
|
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(
|
const rates = torrents.reduce(
|
||||||
({ down, up }, { dlspeed, upspeed }) => ({ down: down + dlspeed, up: up + upspeed }),
|
({ down, up }, { dlspeed, upspeed }) => ({ down: down + dlspeed, up: up + upspeed }),
|
||||||
{ down: 0, up: 0 },
|
{ down: 0, up: 0 },
|
||||||
|
|||||||
@@ -1,14 +1,11 @@
|
|||||||
import {
|
import {
|
||||||
AssetMediaSize,
|
AssetMediaSize,
|
||||||
AssetTypeEnum,
|
|
||||||
AssetVisibility,
|
|
||||||
getAlbumInfo,
|
getAlbumInfo,
|
||||||
getAllAlbums,
|
getAllAlbums,
|
||||||
getMyUser,
|
getMyUser,
|
||||||
getServerStatistics,
|
getServerStatistics,
|
||||||
init,
|
init,
|
||||||
searchAssets,
|
searchAssets,
|
||||||
searchRandom,
|
|
||||||
searchUsers,
|
searchUsers,
|
||||||
} from "@immich/sdk";
|
} from "@immich/sdk";
|
||||||
import type { AssetResponseDto, MetadataSearchDto } from "@immich/sdk";
|
import type { AssetResponseDto, MetadataSearchDto } from "@immich/sdk";
|
||||||
@@ -46,7 +43,6 @@ export interface ImmichAsset {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const logger = createLogger({ module: "immich-integration" });
|
const logger = createLogger({ module: "immich-integration" });
|
||||||
const randomPhotoCount = 50;
|
|
||||||
|
|
||||||
export class ImmichIntegration extends Integration {
|
export class ImmichIntegration extends Integration {
|
||||||
constructor(integration: IntegrationInput) {
|
constructor(integration: IntegrationInput) {
|
||||||
@@ -67,36 +63,38 @@ export class ImmichIntegration extends Integration {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
public async getAlbumAsync(albumId?: string): Promise<ImmichAlbum> {
|
public async getAlbumAsync(albumId: string): Promise<ImmichAlbum> {
|
||||||
this.initClient();
|
this.initClient();
|
||||||
const requestOptions = this.getRequestOptions();
|
const requestOptions = this.getRequestOptions();
|
||||||
|
|
||||||
if (!albumId) {
|
|
||||||
const assets = await searchRandom(
|
|
||||||
{
|
|
||||||
randomSearchDto: {
|
|
||||||
size: randomPhotoCount,
|
|
||||||
type: AssetTypeEnum.Image,
|
|
||||||
visibility: AssetVisibility.Timeline,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
requestOptions,
|
|
||||||
);
|
|
||||||
|
|
||||||
return {
|
|
||||||
id: "",
|
|
||||||
albumName: "",
|
|
||||||
assets: await this.createAssetsAsync(assets),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const [album, albumAssets] = await Promise.all([
|
const [album, albumAssets] = await Promise.all([
|
||||||
getAlbumInfo({ id: albumId }, requestOptions),
|
getAlbumInfo({ id: albumId }, requestOptions),
|
||||||
this.searchAlbumAssetsAsync(albumId),
|
this.searchAlbumAssetsAsync(albumId),
|
||||||
]);
|
]);
|
||||||
|
const imageProxy = new ImageProxy();
|
||||||
return {
|
return {
|
||||||
albumName: album.albumName,
|
albumName: album.albumName,
|
||||||
assets: await this.createAssetsAsync(albumAssets),
|
assets: await Promise.all(
|
||||||
|
albumAssets.map(async (asset) => {
|
||||||
|
const publicLink = await imageProxy.createImageAsync(
|
||||||
|
// This is the URL generated by the SDK's viewAsset call. Preview images are
|
||||||
|
// browser-compatible while avoiding the large original asset download.
|
||||||
|
this.url(`/api/assets/${asset.id}/thumbnail`, { size: AssetMediaSize.Preview }).toString(),
|
||||||
|
{
|
||||||
|
"x-api-key": this.getSecretValue("apiKey"),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
id: asset.id,
|
||||||
|
type: asset.type,
|
||||||
|
thumbhash: asset.thumbhash,
|
||||||
|
fileCreatedAt: asset.fileCreatedAt,
|
||||||
|
fileModifiedAt: asset.fileModifiedAt,
|
||||||
|
originalPath: asset.originalPath,
|
||||||
|
updatedAt: asset.updatedAt,
|
||||||
|
publicLink,
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
),
|
||||||
id: album.id,
|
id: album.id,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -138,32 +136,6 @@ export class ImmichIntegration extends Integration {
|
|||||||
return assets;
|
return assets;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async createAssetsAsync(assets: AssetResponseDto[]): Promise<ImmichAsset[]> {
|
|
||||||
const imageProxy = new ImageProxy();
|
|
||||||
return await Promise.all(
|
|
||||||
assets.map(async (asset) => {
|
|
||||||
const publicLink = await imageProxy.createImageAsync(
|
|
||||||
// This is the URL generated by the SDK's viewAsset call. Preview images are
|
|
||||||
// browser-compatible while avoiding the large original asset download.
|
|
||||||
this.url(`/api/assets/${asset.id}/thumbnail`, { size: AssetMediaSize.Preview }).toString(),
|
|
||||||
{
|
|
||||||
"x-api-key": this.getSecretValue("apiKey"),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
return {
|
|
||||||
id: asset.id,
|
|
||||||
type: asset.type,
|
|
||||||
thumbhash: asset.thumbhash,
|
|
||||||
fileCreatedAt: asset.fileCreatedAt,
|
|
||||||
fileModifiedAt: asset.fileModifiedAt,
|
|
||||||
originalPath: asset.originalPath,
|
|
||||||
updatedAt: asset.updatedAt,
|
|
||||||
publicLink,
|
|
||||||
};
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
private getRequestOptions(fetchAsync = fetchWithTrustedCertificatesAsync) {
|
private getRequestOptions(fetchAsync = fetchWithTrustedCertificatesAsync) {
|
||||||
return {
|
return {
|
||||||
// Undici and node types are not the same
|
// Undici and node types are not the same
|
||||||
|
|||||||
@@ -74,15 +74,16 @@ const optionMapping: OptionMapping = {
|
|||||||
categoryFilter: (oldOptions) => ("labelFilter" in oldOptions ? oldOptions.labelFilter : undefined),
|
categoryFilter: (oldOptions) => ("labelFilter" in oldOptions ? oldOptions.labelFilter : undefined),
|
||||||
filterIsWhitelist: (oldOptions) =>
|
filterIsWhitelist: (oldOptions) =>
|
||||||
"labelFilterIsWhitelist" in oldOptions ? oldOptions.labelFilterIsWhitelist : undefined,
|
"labelFilterIsWhitelist" in oldOptions ? oldOptions.labelFilterIsWhitelist : undefined,
|
||||||
enableRowSorting: (oldOptions) => ("rowSorting" in oldOptions ? oldOptions.rowSorting : undefined),
|
|
||||||
showCompletedTorrent: (oldOptions) =>
|
showCompletedTorrent: (oldOptions) =>
|
||||||
"displayCompletedTorrents" in oldOptions ? oldOptions.displayCompletedTorrents : undefined,
|
"displayCompletedTorrents" in oldOptions ? oldOptions.displayCompletedTorrents : undefined,
|
||||||
columns: () => ["integration", "name", "progress", "time", "actions"],
|
columns: () => ["integration", "name", "progress", "time", "state"],
|
||||||
defaultSort: () => "type",
|
defaultSort: () => "progress",
|
||||||
descendingDefaultSort: () => false,
|
descendingDefaultSort: () => false,
|
||||||
showCompletedUsenet: () => true,
|
showCompletedUsenet: () => true,
|
||||||
showCompletedHttp: () => true,
|
showCompletedHttp: () => true,
|
||||||
limitPerIntegration: () => undefined,
|
limitPerIntegration: () => undefined,
|
||||||
|
columnOrder: () => undefined,
|
||||||
|
columnWidths: () => undefined,
|
||||||
},
|
},
|
||||||
weather: {
|
weather: {
|
||||||
forecastDayCount: (oldOptions) => oldOptions.forecastDays,
|
forecastDayCount: (oldOptions) => oldOptions.forecastDays,
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ export const immichAlbumsRequestHandler = createIntegrationRequestHandler<
|
|||||||
export const immichAlbumRequestHandler = createIntegrationRequestHandler<
|
export const immichAlbumRequestHandler = createIntegrationRequestHandler<
|
||||||
ImmichAlbum,
|
ImmichAlbum,
|
||||||
IntegrationKindByCategory<"photoService">,
|
IntegrationKindByCategory<"photoService">,
|
||||||
{ albumId?: string }
|
{ albumId: string }
|
||||||
>({
|
>({
|
||||||
async requestAsync(integration, input) {
|
async requestAsync(integration, input) {
|
||||||
const integrationInstance = await createIntegrationAsync(integration);
|
const integrationInstance = await createIntegrationAsync(integration);
|
||||||
|
|||||||
@@ -16,6 +16,4 @@ export const mediaRequestStatsRequestHandler = createIntegrationRequestHandler<
|
|||||||
users: await integrationInstance.getUsersAsync(),
|
users: await integrationInstance.getUsersAsync(),
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
cacheTtlMs: 60_000,
|
|
||||||
fallbackToStaleOnError: true,
|
|
||||||
});
|
});
|
||||||
@@ -9,7 +9,7 @@ export const weatherRequestHandler = createWidgetRequestHandler({
|
|||||||
async requestAsync(input: { latitude: number; longitude: number }) {
|
async requestAsync(input: { latitude: number; longitude: number }) {
|
||||||
const res = await withTimeoutAsync(async (signal) => {
|
const res = await withTimeoutAsync(async (signal) => {
|
||||||
return await fetchWithTrustedCertificatesAsync(
|
return await fetchWithTrustedCertificatesAsync(
|
||||||
`https://api.open-meteo.com/v1/forecast?latitude=${input.latitude}&longitude=${input.longitude}&daily=weathercode,temperature_2m_max,temperature_2m_min,sunrise,sunset,wind_speed_10m_max,wind_gusts_10m_max,relative_humidity_2m_mean¤t_weather=true&timezone=auto`,
|
`https://api.open-meteo.com/v1/forecast?latitude=${input.latitude}&longitude=${input.longitude}&daily=weathercode,temperature_2m_max,temperature_2m_min,sunrise,sunset,wind_speed_10m_max,wind_gusts_10m_max¤t_weather=true&timezone=auto`,
|
||||||
{ signal },
|
{ signal },
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
@@ -27,7 +27,6 @@ export const weatherRequestHandler = createWidgetRequestHandler({
|
|||||||
sunset: weather.daily.sunset[index],
|
sunset: weather.daily.sunset[index],
|
||||||
maxWindSpeed: weather.daily.wind_speed_10m_max[index],
|
maxWindSpeed: weather.daily.wind_speed_10m_max[index],
|
||||||
maxWindGusts: weather.daily.wind_gusts_10m_max[index],
|
maxWindGusts: weather.daily.wind_gusts_10m_max[index],
|
||||||
humidity: weather.daily.relative_humidity_2m_mean[index],
|
|
||||||
};
|
};
|
||||||
}),
|
}),
|
||||||
} satisfies Weather;
|
} satisfies Weather;
|
||||||
@@ -49,7 +48,6 @@ const atLocationOutput = z.object({
|
|||||||
sunset: z.array(z.string()),
|
sunset: z.array(z.string()),
|
||||||
wind_speed_10m_max: z.array(z.number()),
|
wind_speed_10m_max: z.array(z.number()),
|
||||||
wind_gusts_10m_max: z.array(z.number()),
|
wind_gusts_10m_max: z.array(z.number()),
|
||||||
relative_humidity_2m_mean: z.array(z.number()),
|
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -68,6 +66,5 @@ export interface Weather {
|
|||||||
sunset: string | undefined;
|
sunset: string | undefined;
|
||||||
maxWindSpeed: number | undefined;
|
maxWindSpeed: number | undefined;
|
||||||
maxWindGusts: number | undefined;
|
maxWindGusts: number | undefined;
|
||||||
humidity: number | undefined;
|
|
||||||
}[];
|
}[];
|
||||||
}
|
}
|
||||||
@@ -17,10 +17,6 @@ export const appIntegrationBoardMode = {
|
|||||||
return groups;
|
return groups;
|
||||||
}
|
}
|
||||||
|
|
||||||
return groups.concat(
|
return groups.concat([appsSearchGroup, integrationsSearchGroup]);
|
||||||
session.user.permissions.includes("board-modify-all")
|
|
||||||
? [appsSearchGroup, integrationsSearchGroup]
|
|
||||||
: [integrationsSearchGroup],
|
|
||||||
);
|
|
||||||
},
|
},
|
||||||
} satisfies SearchMode;
|
} satisfies SearchMode;
|
||||||
@@ -87,8 +87,7 @@ export const globalCommandGroup = createGroup<Command>({
|
|||||||
icon: IconBox,
|
icon: IconBox,
|
||||||
name: tOption("newApp.label"),
|
name: tOption("newApp.label"),
|
||||||
useInteraction: interaction.link(() => ({ href: "/manage/apps/new" })),
|
useInteraction: interaction.link(() => ({ href: "/manage/apps/new" })),
|
||||||
hidden:
|
hidden: !session?.user.permissions.includes("app-create"),
|
||||||
!session?.user.permissions.includes("board-modify-all") || !session?.user.permissions.includes("app-create"),
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
commandKey: "newIntegration",
|
commandKey: "newIntegration",
|
||||||
|
|||||||
@@ -76,7 +76,7 @@ export const pagesSearchGroup = createGroup<{
|
|||||||
icon: IconBox,
|
icon: IconBox,
|
||||||
path: "/manage/apps",
|
path: "/manage/apps",
|
||||||
name: t("manageApp.label"),
|
name: t("manageApp.label"),
|
||||||
hidden: !session?.user.permissions.includes("board-modify-all"),
|
hidden: !session,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
icon: IconPlug,
|
icon: IconPlug,
|
||||||
|
|||||||
@@ -2257,8 +2257,7 @@
|
|||||||
"sunrise": "Sunrise",
|
"sunrise": "Sunrise",
|
||||||
"sunset": "Sunset",
|
"sunset": "Sunset",
|
||||||
"maxWindSpeed": "Max wind speed: {maxWindSpeed} {unit}",
|
"maxWindSpeed": "Max wind speed: {maxWindSpeed} {unit}",
|
||||||
"maxWindGusts": "Max wind gusts: {maxWindGusts} {unit}",
|
"maxWindGusts": "Max wind gusts: {maxWindGusts} {unit}"
|
||||||
"humidity": "Humidity: {humidity}%"
|
|
||||||
},
|
},
|
||||||
"kind": {
|
"kind": {
|
||||||
"clear": "Clear",
|
"clear": "Clear",
|
||||||
@@ -3007,11 +3006,10 @@
|
|||||||
},
|
},
|
||||||
"immich-albumCarousel": {
|
"immich-albumCarousel": {
|
||||||
"name": "Immich Album",
|
"name": "Immich Album",
|
||||||
"allPhotos": "All photos",
|
|
||||||
"option": {
|
"option": {
|
||||||
"albumId": {
|
"albumId": {
|
||||||
"label": "Album",
|
"label": "Album",
|
||||||
"description": "Select an Immich album or All photos. An empty selection also shows random photos from your full library."
|
"description": "Select the Immich album to show in the slideshow."
|
||||||
},
|
},
|
||||||
"rotationIntervalSeconds": {
|
"rotationIntervalSeconds": {
|
||||||
"label": "Interval in seconds",
|
"label": "Interval in seconds",
|
||||||
@@ -3026,8 +3024,9 @@
|
|||||||
"description": "Show photos in a random order instead of always starting with the same album order."
|
"description": "Show photos in a random order instead of always starting with the same album order."
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"description": "Slideshow of pictures from an Immich album or your full library",
|
"description": "Slideshow of pictures in your Immich album",
|
||||||
"noPhotos": "No photos found"
|
"noAlbumSelected": "No album selected, edit widget and choose an album",
|
||||||
|
"noPhotos": "No photos in this album"
|
||||||
},
|
},
|
||||||
"downloads": {
|
"downloads": {
|
||||||
"name": "Download Client",
|
"name": "Download Client",
|
||||||
@@ -3069,11 +3068,20 @@
|
|||||||
"limitPerIntegration": {
|
"limitPerIntegration": {
|
||||||
"label": "Limit items per integration",
|
"label": "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"
|
||||||
|
},
|
||||||
|
"columnOrder": {
|
||||||
|
"label": "Column order"
|
||||||
|
},
|
||||||
|
"columnWidths": {
|
||||||
|
"label": "Column widths"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"errors": {
|
"errors": {
|
||||||
"noColumns": "Select Columns in Items",
|
"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": {
|
"items": {
|
||||||
"actions": {
|
"actions": {
|
||||||
@@ -3096,7 +3104,8 @@
|
|||||||
"detailsTitle": "Current index within client"
|
"detailsTitle": "Current index within client"
|
||||||
},
|
},
|
||||||
"id": {
|
"id": {
|
||||||
"columnTitle": "Id"
|
"columnTitle": "Id",
|
||||||
|
"detailsTitle": "Item ID"
|
||||||
},
|
},
|
||||||
"integration": {
|
"integration": {
|
||||||
"columnTitle": "Integration"
|
"columnTitle": "Integration"
|
||||||
@@ -3130,7 +3139,8 @@
|
|||||||
},
|
},
|
||||||
"time": {
|
"time": {
|
||||||
"columnTitle": "Finish time",
|
"columnTitle": "Finish time",
|
||||||
"detailsTitle": "Time since/to completion"
|
"detailsTitle": "Time since/to completion",
|
||||||
|
"eta": "ETA"
|
||||||
},
|
},
|
||||||
"type": {
|
"type": {
|
||||||
"columnTitle": "Type",
|
"columnTitle": "Type",
|
||||||
@@ -3174,7 +3184,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": {
|
"mediaReleases": {
|
||||||
"name": "Media releases",
|
"name": "Media releases",
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -8,28 +8,37 @@ import { createWidgetDefinition } from "../definition";
|
|||||||
import { optionsBuilder } from "../options";
|
import { optionsBuilder } from "../options";
|
||||||
|
|
||||||
const columnsList = [
|
const columnsList = [
|
||||||
"id",
|
|
||||||
"actions",
|
|
||||||
"added",
|
|
||||||
"category",
|
|
||||||
"downSpeed",
|
|
||||||
"index",
|
|
||||||
"integration",
|
|
||||||
"name",
|
"name",
|
||||||
"progress",
|
"progress",
|
||||||
|
"size",
|
||||||
|
"downSpeed",
|
||||||
|
"upSpeed",
|
||||||
|
"time",
|
||||||
|
"state",
|
||||||
|
"added",
|
||||||
"ratio",
|
"ratio",
|
||||||
"received",
|
"received",
|
||||||
"sent",
|
"sent",
|
||||||
"size",
|
"category",
|
||||||
"state",
|
"integration",
|
||||||
"time",
|
"index",
|
||||||
"type",
|
"type",
|
||||||
"upSpeed",
|
|
||||||
] as const satisfies (keyof ExtendedDownloadClientItem)[];
|
] as const satisfies (keyof ExtendedDownloadClientItem)[];
|
||||||
const sortingExclusion = ["actions", "id", "state"] as const satisfies readonly (typeof columnsList)[number][];
|
|
||||||
const columnsSort = columnsList.filter((column) =>
|
const sortColumns = [
|
||||||
sortingExclusion.every((exclusion) => exclusion !== column),
|
"name",
|
||||||
) as Exclude<typeof columnsList, (typeof sortingExclusion)[number]>;
|
"progress",
|
||||||
|
"size",
|
||||||
|
"downSpeed",
|
||||||
|
"upSpeed",
|
||||||
|
"time",
|
||||||
|
"added",
|
||||||
|
"ratio",
|
||||||
|
"received",
|
||||||
|
"sent",
|
||||||
|
"index",
|
||||||
|
"type",
|
||||||
|
] as const satisfies readonly (typeof columnsList)[number][];
|
||||||
|
|
||||||
export const { definition, componentLoader } = createWidgetDefinition("downloads", {
|
export const { definition, componentLoader } = createWidgetDefinition("downloads", {
|
||||||
icon: IconDownload,
|
icon: IconDownload,
|
||||||
@@ -38,19 +47,16 @@ export const { definition, componentLoader } = createWidgetDefinition("downloads
|
|||||||
return optionsBuilder.from(
|
return optionsBuilder.from(
|
||||||
(factory) => ({
|
(factory) => ({
|
||||||
columns: factory.multiSelect({
|
columns: factory.multiSelect({
|
||||||
defaultValue: ["integration", "name", "progress", "time", "actions"],
|
defaultValue: ["name", "progress", "downSpeed", "time", "state"],
|
||||||
options: columnsList.map((value) => ({
|
options: columnsList.map((value) => ({
|
||||||
value,
|
value,
|
||||||
label: (t) => t(`widget.downloads.items.${value}.columnTitle`),
|
label: (t) => t(`widget.downloads.items.${value}.columnTitle`),
|
||||||
})),
|
})),
|
||||||
searchable: true,
|
searchable: true,
|
||||||
}),
|
}),
|
||||||
enableRowSorting: factory.switch({
|
|
||||||
defaultValue: false,
|
|
||||||
}),
|
|
||||||
defaultSort: factory.select({
|
defaultSort: factory.select({
|
||||||
defaultValue: "type",
|
defaultValue: "progress",
|
||||||
options: columnsSort.map((value) => ({
|
options: sortColumns.map((value) => ({
|
||||||
value,
|
value,
|
||||||
label: (t) => t(`widget.downloads.items.${value}.columnTitle`),
|
label: (t) => t(`widget.downloads.items.${value}.columnTitle`),
|
||||||
})),
|
})),
|
||||||
@@ -68,7 +74,6 @@ export const { definition, componentLoader } = createWidgetDefinition("downloads
|
|||||||
defaultValue: true,
|
defaultValue: true,
|
||||||
}),
|
}),
|
||||||
activeTorrentThreshold: factory.number({
|
activeTorrentThreshold: factory.number({
|
||||||
//in KiB/s
|
|
||||||
validate: z.number().min(0),
|
validate: z.number().min(0),
|
||||||
defaultValue: 0,
|
defaultValue: 0,
|
||||||
step: 1,
|
step: 1,
|
||||||
@@ -88,14 +93,12 @@ export const { definition, componentLoader } = createWidgetDefinition("downloads
|
|||||||
validate: z.number().min(1),
|
validate: z.number().min(1),
|
||||||
withDescription: true,
|
withDescription: true,
|
||||||
}),
|
}),
|
||||||
|
columnOrder: factory.text({ defaultValue: "" }),
|
||||||
|
columnWidths: factory.text({ defaultValue: "" }),
|
||||||
}),
|
}),
|
||||||
{
|
{
|
||||||
defaultSort: {
|
columnOrder: { shouldHide: () => true },
|
||||||
shouldHide: (options) => !options.enableRowSorting,
|
columnWidths: { shouldHide: () => true },
|
||||||
},
|
|
||||||
descendingDefaultSort: {
|
|
||||||
shouldHide: (options) => !options.enableRowSorting,
|
|
||||||
},
|
|
||||||
showCompletedUsenet: {
|
showCompletedUsenet: {
|
||||||
shouldHide: (_, integrationKinds) =>
|
shouldHide: (_, integrationKinds) =>
|
||||||
!getIntegrationKindsByCategory("usenet").some((kinds) => integrationKinds.includes(kinds)),
|
!getIntegrationKindsByCategory("usenet").some((kinds) => integrationKinds.includes(kinds)),
|
||||||
|
|||||||
@@ -1,12 +1,52 @@
|
|||||||
/* Make the MantineReactTable transparent so the board card's opacity-controlled
|
/* Make the DataTable transparent so the board card's opacity-controlled
|
||||||
background shows through. MRT defaults to var(--mantine-color-body) which is opaque. */
|
background shows through. The mantine-datatable defaults to
|
||||||
.downloads-widget-table,
|
var(--mantine-color-body) which is opaque. */
|
||||||
.downloads-widget-table .mantine-Table-table,
|
.downloads-table,
|
||||||
.downloads-widget-table .mantine-Table-thead,
|
.downloads-table .mantine-datatable-table,
|
||||||
.downloads-widget-table .mantine-Table-tbody,
|
.downloads-table .mantine-datatable-table thead,
|
||||||
.downloads-widget-table .mantine-Table-tfoot,
|
.downloads-table .mantine-datatable-table tbody,
|
||||||
.downloads-widget-table .mantine-Table-tr,
|
.downloads-table .mantine-datatable-table tfoot,
|
||||||
.downloads-widget-table th,
|
.downloads-table th,
|
||||||
.downloads-widget-table td {
|
.downloads-table td {
|
||||||
background-color: transparent !important;
|
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;
|
||||||
|
}
|
||||||
@@ -11,7 +11,6 @@ import { useI18n } from "@homarr/translation/client";
|
|||||||
import { WidgetEmptyState } from "../../common/empty-state";
|
import { WidgetEmptyState } from "../../common/empty-state";
|
||||||
import type { WidgetComponentProps } from "../../definition";
|
import type { WidgetComponentProps } from "../../definition";
|
||||||
import classes from "./component.module.css";
|
import classes from "./component.module.css";
|
||||||
import { ALL_PHOTOS_ALBUM_ID } from "./constants";
|
|
||||||
|
|
||||||
export default function ImmichAlbumCarouselWidget({
|
export default function ImmichAlbumCarouselWidget({
|
||||||
integrationIds,
|
integrationIds,
|
||||||
@@ -22,9 +21,9 @@ export default function ImmichAlbumCarouselWidget({
|
|||||||
const { data: album } = clientApi.widget.immich.getAlbum.useQuery(
|
const { data: album } = clientApi.widget.immich.getAlbum.useQuery(
|
||||||
{
|
{
|
||||||
integrationId: integrationIds[0] ?? "",
|
integrationId: integrationIds[0] ?? "",
|
||||||
albumId: options.albumId && options.albumId !== ALL_PHOTOS_ALBUM_ID ? options.albumId : undefined,
|
albumId: options.albumId ?? "",
|
||||||
},
|
},
|
||||||
{ enabled: integrationIds.length > 0 },
|
{ enabled: Boolean(options.albumId) },
|
||||||
);
|
);
|
||||||
|
|
||||||
const photoAssets = useMemo(() => {
|
const photoAssets = useMemo(() => {
|
||||||
@@ -36,6 +35,10 @@ export default function ImmichAlbumCarouselWidget({
|
|||||||
setCurrentPhotoIndex(0);
|
setCurrentPhotoIndex(0);
|
||||||
}, [photoAssets]);
|
}, [photoAssets]);
|
||||||
|
|
||||||
|
if (!options.albumId) {
|
||||||
|
return <NoAlbumSelected />;
|
||||||
|
}
|
||||||
|
|
||||||
if (!album) return <WidgetEmptyState />;
|
if (!album) return <WidgetEmptyState />;
|
||||||
|
|
||||||
if (album.assets.length === 0) {
|
if (album.assets.length === 0) {
|
||||||
@@ -114,6 +117,20 @@ function Carousel({ assets, currentIndex, setCurrentIndex, rotationInterval, sho
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function NoAlbumSelected() {
|
||||||
|
const t = useI18n();
|
||||||
|
return (
|
||||||
|
<Center h="100%">
|
||||||
|
<Stack align="center" gap="xs">
|
||||||
|
<IconAlertCircle size={32} />
|
||||||
|
<Text size="sm" fw={500}>
|
||||||
|
{t("widget.immich-albumCarousel.noAlbumSelected")}
|
||||||
|
</Text>
|
||||||
|
</Stack>
|
||||||
|
</Center>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function NoPhotosInAlbum() {
|
function NoPhotosInAlbum() {
|
||||||
const t = useI18n();
|
const t = useI18n();
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -1 +0,0 @@
|
|||||||
export const ALL_PHOTOS_ALBUM_ID = "all";
|
|
||||||
@@ -2,11 +2,9 @@ import { IconPhoto } from "@tabler/icons-react";
|
|||||||
import z from "zod";
|
import z from "zod";
|
||||||
|
|
||||||
import { clientApi } from "@homarr/api/client";
|
import { clientApi } from "@homarr/api/client";
|
||||||
import { useScopedI18n } from "@homarr/translation/client";
|
|
||||||
|
|
||||||
import { createWidgetDefinition } from "../../definition";
|
import { createWidgetDefinition } from "../../definition";
|
||||||
import { optionsBuilder } from "../../options";
|
import { optionsBuilder } from "../../options";
|
||||||
import { ALL_PHOTOS_ALBUM_ID } from "./constants";
|
|
||||||
|
|
||||||
export const { definition, componentLoader } = createWidgetDefinition("immich-albumCarousel", {
|
export const { definition, componentLoader } = createWidgetDefinition("immich-albumCarousel", {
|
||||||
icon: IconPhoto,
|
icon: IconPhoto,
|
||||||
@@ -17,11 +15,9 @@ export const { definition, componentLoader } = createWidgetDefinition("immich-al
|
|||||||
createOptions() {
|
createOptions() {
|
||||||
return optionsBuilder.from((factory) => ({
|
return optionsBuilder.from((factory) => ({
|
||||||
albumId: factory.integrationSelect({
|
albumId: factory.integrationSelect({
|
||||||
defaultValue: ALL_PHOTOS_ALBUM_ID,
|
|
||||||
withDescription: true,
|
withDescription: true,
|
||||||
clearable: true,
|
clearable: true,
|
||||||
useOptions: (integrationIds: string[]) => {
|
useOptions: (integrationIds: string[]) => {
|
||||||
const t = useScopedI18n("widget.immich-albumCarousel");
|
|
||||||
const {
|
const {
|
||||||
data = [],
|
data = [],
|
||||||
isPending,
|
isPending,
|
||||||
@@ -30,14 +26,7 @@ export const { definition, componentLoader } = createWidgetDefinition("immich-al
|
|||||||
{ integrationId: integrationIds[0] ?? "" },
|
{ integrationId: integrationIds[0] ?? "" },
|
||||||
{ enabled: integrationIds.length > 0, staleTime: 15 * 60 * 1000 },
|
{ enabled: integrationIds.length > 0, staleTime: 15 * 60 * 1000 },
|
||||||
);
|
);
|
||||||
return {
|
return { data: data.map((album) => ({ value: album.id, label: album.albumName })), isPending, isError };
|
||||||
data: [
|
|
||||||
{ value: ALL_PHOTOS_ALBUM_ID, label: t("allPhotos") },
|
|
||||||
...data.map((album) => ({ value: album.id, label: album.albumName })),
|
|
||||||
],
|
|
||||||
isPending,
|
|
||||||
isError,
|
|
||||||
};
|
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
rotationIntervalSeconds: factory.number({
|
rotationIntervalSeconds: factory.number({
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { Box, Group, HoverCard, Stack, Text } from "@mantine/core";
|
import { Box, Group, HoverCard, Stack, Text } from "@mantine/core";
|
||||||
import { IconArrowDownRight, IconArrowUpRight, IconDroplets, IconMapPin, IconWind } from "@tabler/icons-react";
|
import { IconArrowDownRight, IconArrowUpRight, IconMapPin, IconWind } from "@tabler/icons-react";
|
||||||
import combineClasses from "clsx";
|
import combineClasses from "clsx";
|
||||||
import dayjs from "dayjs";
|
import dayjs from "dayjs";
|
||||||
|
|
||||||
@@ -87,12 +87,6 @@ const DailyWeather = ({ options, weather }: WeatherProps) => {
|
|||||||
</Text>
|
</Text>
|
||||||
</Group>
|
</Group>
|
||||||
)}
|
)}
|
||||||
{weather.daily[0]?.humidity !== undefined && (
|
|
||||||
<Group className="weather-humidity-group" wrap="nowrap" gap="xs">
|
|
||||||
<IconDroplets size={16} />
|
|
||||||
<Text fz={16}>{t("dailyForecast.humidity", { humidity: weather.daily[0].humidity })}</Text>
|
|
||||||
</Group>
|
|
||||||
)}
|
|
||||||
<Group className="weather-max-min-temp-group" wrap="nowrap" gap="sm">
|
<Group className="weather-max-min-temp-group" wrap="nowrap" gap="sm">
|
||||||
<Group gap="xs" wrap="nowrap">
|
<Group gap="xs" wrap="nowrap">
|
||||||
<IconArrowUpRight size={16} />
|
<IconArrowUpRight size={16} />
|
||||||
@@ -210,7 +204,6 @@ function Forecast({ weather, options }: WeatherProps) {
|
|||||||
sunset={dayjs(dayWeather.sunset).format("HH:mm")}
|
sunset={dayjs(dayWeather.sunset).format("HH:mm")}
|
||||||
maxWindSpeed={dayWeather.maxWindSpeed}
|
maxWindSpeed={dayWeather.maxWindSpeed}
|
||||||
maxWindGusts={dayWeather.maxWindGusts}
|
maxWindGusts={dayWeather.maxWindGusts}
|
||||||
humidity={dayWeather.humidity}
|
|
||||||
/>
|
/>
|
||||||
</HoverCard.Dropdown>
|
</HoverCard.Dropdown>
|
||||||
</HoverCard>
|
</HoverCard>
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import {
|
|||||||
IconCloudRain,
|
IconCloudRain,
|
||||||
IconCloudSnow,
|
IconCloudSnow,
|
||||||
IconCloudStorm,
|
IconCloudStorm,
|
||||||
IconDroplets,
|
|
||||||
IconMoon,
|
IconMoon,
|
||||||
IconQuestionMark,
|
IconQuestionMark,
|
||||||
IconSnowflake,
|
IconSnowflake,
|
||||||
@@ -52,7 +51,6 @@ interface WeatherDescriptionProps {
|
|||||||
sunset?: string;
|
sunset?: string;
|
||||||
maxWindSpeed?: number;
|
maxWindSpeed?: number;
|
||||||
maxWindGusts?: number;
|
maxWindGusts?: number;
|
||||||
humidity?: number;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -80,7 +78,6 @@ export const WeatherDescription = ({
|
|||||||
sunset,
|
sunset,
|
||||||
maxWindSpeed,
|
maxWindSpeed,
|
||||||
maxWindGusts,
|
maxWindGusts,
|
||||||
humidity,
|
|
||||||
}: WeatherDescriptionProps) => {
|
}: WeatherDescriptionProps) => {
|
||||||
const t = useScopedI18n("widget.weather");
|
const t = useScopedI18n("widget.weather");
|
||||||
const tCommon = useScopedI18n("common");
|
const tCommon = useScopedI18n("common");
|
||||||
@@ -100,9 +97,6 @@ export const WeatherDescription = ({
|
|||||||
<List.Item icon={<IconTemperatureMinus size={15} />}>{`${tCommon("information.min")}: ${minTemp}`}</List.Item>
|
<List.Item icon={<IconTemperatureMinus size={15} />}>{`${tCommon("information.min")}: ${minTemp}`}</List.Item>
|
||||||
<List.Item icon={<IconSun size={15} />}>{`${t("dailyForecast.sunrise")}: ${sunrise}`}</List.Item>
|
<List.Item icon={<IconSun size={15} />}>{`${t("dailyForecast.sunrise")}: ${sunrise}`}</List.Item>
|
||||||
<List.Item icon={<IconMoon size={15} />}>{`${t("dailyForecast.sunset")}: ${sunset}`}</List.Item>
|
<List.Item icon={<IconMoon size={15} />}>{`${t("dailyForecast.sunset")}: ${sunset}`}</List.Item>
|
||||||
{humidity !== undefined && (
|
|
||||||
<List.Item icon={<IconDroplets size={15} />}>{t("dailyForecast.humidity", { humidity })}</List.Item>
|
|
||||||
)}
|
|
||||||
{maxWindSpeed !== undefined && (
|
{maxWindSpeed !== undefined && (
|
||||||
<List.Item icon={<IconWind size={15} />}>
|
<List.Item icon={<IconWind size={15} />}>
|
||||||
{t("dailyForecast.maxWindSpeed", {
|
{t("dailyForecast.maxWindSpeed", {
|
||||||
|
|||||||
Reference in new issue
Block a user