feat: polish release v2 experience (#6800)
This commit is contained in:
1 parent
925b0fb801
commit
a4a903d7c3
295 files changed
+10627
-7115
No files matched your search
@@ -8,6 +8,8 @@ import type { QueryClient } from "@tanstack/react-query";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { ReactQueryDevtoolsPanel } from "@tanstack/react-query-devtools";
|
||||
|
||||
import { useByteFormatter } from "@homarr/settings";
|
||||
|
||||
const valueStyle = { fontFamily: "monospace", overflowWrap: "anywhere" } as const;
|
||||
const metricStyle = {
|
||||
background: "color-mix(in srgb, currentColor 4%, transparent)",
|
||||
@@ -33,11 +35,9 @@ const readDiagnostics = (queryClient: QueryClient) => {
|
||||
total: queries.length,
|
||||
readyWidgets,
|
||||
widgetItems,
|
||||
scriptKiB: Math.round(
|
||||
resources
|
||||
.filter((resource) => resource.initiatorType === "script")
|
||||
.reduce((total, resource) => total + resource.decodedBodySize, 0) / 1024,
|
||||
),
|
||||
scriptBytes: resources
|
||||
.filter((resource) => resource.initiatorType === "script")
|
||||
.reduce((total, resource) => total + resource.decodedBodySize, 0),
|
||||
};
|
||||
};
|
||||
|
||||
@@ -51,6 +51,7 @@ const Metric = ({ label, value }: { label: string; value: number | string }) =>
|
||||
const HomarrDevtoolsPanel = ({ active }: { active: boolean }) => {
|
||||
const pathname = usePathname();
|
||||
const queryClient = useQueryClient();
|
||||
const { formatBytes } = useByteFormatter();
|
||||
const [diagnostics, setDiagnostics] = useState(() => readDiagnostics(queryClient));
|
||||
|
||||
useEffect(() => {
|
||||
@@ -95,7 +96,7 @@ const HomarrDevtoolsPanel = ({ active }: { active: boolean }) => {
|
||||
<Metric label="Errors" value={diagnostics.errors} />
|
||||
<Metric label="Mutations" value={diagnostics.pendingMutations} />
|
||||
<Metric label="Widgets ready" value={`${diagnostics.readyWidgets}/${diagnostics.widgetItems}`} />
|
||||
<Metric label="Script KiB" value={diagnostics.scriptKiB} />
|
||||
<Metric label="Script" value={formatBytes(diagnostics.scriptBytes)} />
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
|
||||
@@ -7,7 +7,6 @@ import type { z } from "zod/v4";
|
||||
import type { RouterOutputs } from "@homarr/api";
|
||||
import { useUpdateBoard } from "@homarr/boards/updater";
|
||||
import { revalidatePathActionAsync } from "@homarr/common/client";
|
||||
import { env } from "@homarr/common/env";
|
||||
import { useZodForm } from "@homarr/form";
|
||||
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
|
||||
import { useSettings } from "@homarr/settings";
|
||||
@@ -17,6 +16,7 @@ import { boardSaveLayoutsSchema, boardSavePartialSettingsSchema } from "@homarr/
|
||||
import { homarrLogoPath } from "~/components/layout/logo/constants";
|
||||
import { SectionCard } from "~/components/manage/section-card";
|
||||
import { UnsavedChangesBar } from "~/components/manage/unsaved-changes-bar";
|
||||
import { useUnsavedChangesGuard } from "~/components/manage/use-unsaved-changes-guard";
|
||||
|
||||
import type { Board } from "../../_types";
|
||||
import { ColorSettingsContent } from "./_appereance";
|
||||
@@ -107,8 +107,7 @@ export const BoardSettingsForm = ({ board, permissions, hasFullAccess, hideVisib
|
||||
const initialValuesRef = useRef(buildInitialValues(board));
|
||||
const lastSavedRef = useRef({ pageTitle: board.pageTitle, logoImageUrl: board.logoImageUrl });
|
||||
|
||||
const isDirtyRef = useRef(false);
|
||||
isDirtyRef.current = form.isDirty();
|
||||
useUnsavedChangesGuard(form.isDirty());
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
@@ -120,15 +119,6 @@ export const BoardSettingsForm = ({ board, permissions, hasFullAccess, hideVisib
|
||||
};
|
||||
}, [updateBoard]);
|
||||
|
||||
useEffect(() => {
|
||||
const handler = (event: BeforeUnloadEvent) => {
|
||||
if (env.NODE_ENV === "development") return;
|
||||
if (isDirtyRef.current) event.preventDefault();
|
||||
};
|
||||
window.addEventListener("beforeunload", handler);
|
||||
return () => window.removeEventListener("beforeunload", handler);
|
||||
}, []);
|
||||
|
||||
const saveSettingsAsync = async (values: FormValues): Promise<FormValues | null> => {
|
||||
const defaults = initialValuesRef.current;
|
||||
const changed = <TKey extends keyof FormValues>(...fields: TKey[]) =>
|
||||
|
||||
@@ -25,7 +25,7 @@ const searchParamsSchema = z.object({
|
||||
.string()
|
||||
.regex(/^[1-9]\d*$/u)
|
||||
.transform(Number)
|
||||
.pipe(z.number().int().positive())
|
||||
.pipe(z.number().int().positive().max(100))
|
||||
.catch(10),
|
||||
page: z
|
||||
.string()
|
||||
@@ -52,6 +52,13 @@ export default async function AppsPage(props: AppsPageProps) {
|
||||
const { items: apps, totalCount } = canManageAll
|
||||
? await api.app.getPaginated(searchParams)
|
||||
: { items: [], totalCount: 0 };
|
||||
const totalPages = Math.ceil(totalCount / searchParams.pageSize);
|
||||
|
||||
if (totalPages > 0 && searchParams.page > totalPages) {
|
||||
const params = createPaginationSearchParams(searchParams.search, searchParams.pageSize, totalPages);
|
||||
redirect(`/manage/apps?${params.toString()}`);
|
||||
}
|
||||
|
||||
const t = await getI18n("app");
|
||||
const tCommon = await getI18n("common");
|
||||
const hasSearch = canManageAll && Boolean(searchParams.search?.trim());
|
||||
@@ -104,11 +111,7 @@ export default async function AppsPage(props: AppsPageProps) {
|
||||
/>
|
||||
) : undefined
|
||||
}
|
||||
footer={
|
||||
totalCount > searchParams.pageSize ? (
|
||||
<TablePagination total={Math.ceil(totalCount / searchParams.pageSize)} />
|
||||
) : undefined
|
||||
}
|
||||
footer={totalPages > 1 ? <TablePagination total={totalPages} /> : undefined}
|
||||
floatingPrimaryAction={canCreate}
|
||||
>
|
||||
{apps.map((app) => (
|
||||
@@ -187,3 +190,12 @@ const AppItem = ({ app, canDelete, editLabel }: AppItemProps) => {
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
const createPaginationSearchParams = (search: string | undefined, pageSize: number, page: number) => {
|
||||
const params = new URLSearchParams({ page: page.toString() });
|
||||
|
||||
if (search) params.set("search", search);
|
||||
if (pageSize !== 10) params.set("pageSize", pageSize.toString());
|
||||
|
||||
return params;
|
||||
};
|
||||
@@ -11,11 +11,13 @@ import {
|
||||
IconDownload,
|
||||
IconPlayerPause,
|
||||
IconPlayerPlay,
|
||||
IconPlugConnected,
|
||||
IconSparkles,
|
||||
IconTrash,
|
||||
IconUpload,
|
||||
} from "@tabler/icons-react";
|
||||
|
||||
import type { RouterOutputs } from "@homarr/api";
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { revalidatePathActionAsync } from "@homarr/common/client";
|
||||
import { formatCustomWidgetImportIssues, parseCustomWidgetClipboardDetailed } from "@homarr/custom-widgets/core";
|
||||
@@ -29,15 +31,15 @@ import { downloadJson } from "~/components/custom-widgets/download";
|
||||
|
||||
const iconProps = { size: 16, stroke: 1.5 };
|
||||
|
||||
interface WidgetRef {
|
||||
id: string;
|
||||
name: string;
|
||||
enabled: boolean;
|
||||
valid: boolean;
|
||||
migrationRequired: boolean;
|
||||
type WidgetListItem = RouterOutputs["customWidget"]["list"][number];
|
||||
type WidgetRef = Pick<WidgetListItem, "id" | "name" | "enabled" | "valid" | "migrationRequired">;
|
||||
|
||||
interface CustomWidgetRowActionsProps {
|
||||
widget: WidgetRef;
|
||||
onConfigureSources(): void;
|
||||
}
|
||||
|
||||
export const CustomWidgetRowActions = ({ widget }: { widget: WidgetRef }) => {
|
||||
export const CustomWidgetRowActions = ({ widget, onConfigureSources }: CustomWidgetRowActionsProps) => {
|
||||
const t = useI18n("customWidget");
|
||||
const tCommon = useI18n("common");
|
||||
const deleteMutation = clientApi.customWidget.delete.useMutation();
|
||||
@@ -210,6 +212,9 @@ export const CustomWidgetRowActions = ({ widget }: { widget: WidgetRef }) => {
|
||||
>
|
||||
{widget.enabled ? t("action.disable") : t("action.enable")}
|
||||
</Menu.Item>
|
||||
<Menu.Item onClick={onConfigureSources} leftSection={<IconPlugConnected {...iconProps} />}>
|
||||
{t("action.configureSources")}
|
||||
</Menu.Item>
|
||||
<Menu.Divider />
|
||||
<Menu.Item
|
||||
onClick={handleDuplicate}
|
||||
|
||||
@@ -20,10 +20,10 @@ import {
|
||||
import { getCustomWidgetDefaultOptions } from "@homarr/custom-widgets/core";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
|
||||
import { useUnsavedChangesGuard } from "~/components/manage/use-unsaved-changes-guard";
|
||||
import { useCustomWidgetFormDocumentDirty } from "./_custom-widget-form-state";
|
||||
import { areCustomWidgetValuesEqual } from "./_custom-widget-value-equality";
|
||||
import { useCustomWidgetFormAnalysisField } from "./_use-custom-widget-form-analysis";
|
||||
import { useUnsavedChangesGuard } from "./_use-unsaved-changes-guard";
|
||||
import classes from "./_custom-widget-form.module.css";
|
||||
|
||||
const sectionLinks = [
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { fetchApi } from "@homarr/api/client";
|
||||
import { isRecord } from "@homarr/common";
|
||||
import {
|
||||
customWidgetDefinitionSchema,
|
||||
getCustomWidgetDefaultOptions,
|
||||
@@ -12,6 +13,8 @@ import type { UseFormReturnType } from "@mantine/form";
|
||||
|
||||
export type CustomWidgetWorkbenchForm = UseFormReturnType<CustomWidgetFormValues>;
|
||||
|
||||
export { isRecord };
|
||||
|
||||
const PREVIEW_QUERY_CONCURRENCY = 4;
|
||||
|
||||
export function buildDefinition(values: CustomWidgetFormValues) {
|
||||
@@ -83,10 +86,6 @@ export function parseJson(value: string): unknown {
|
||||
}
|
||||
}
|
||||
|
||||
export function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
|
||||
export function getCustomWidgetPreviewOptionIssues(definition: HomarrCustomWidgetV2, options: Record<string, unknown>) {
|
||||
return validateCustomWidgetOptions(definition.options, options);
|
||||
}
|
||||
|
||||
@@ -101,6 +101,7 @@ function CustomWidgetRow({ widget }: { widget: WidgetDef }) {
|
||||
</Button>
|
||||
)}
|
||||
<CustomWidgetRowActions
|
||||
onConfigureSources={sourceSetupControls.open}
|
||||
widget={{
|
||||
id: widget.id,
|
||||
name: widget.name,
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { isRecord } from "@homarr/common";
|
||||
|
||||
export interface CustomWidgetSaveIssue {
|
||||
path?: string;
|
||||
message: string;
|
||||
@@ -58,7 +60,5 @@ function uniqueIssues(issues: CustomWidgetSaveIssue[]) {
|
||||
}
|
||||
|
||||
function asRecord(value: unknown): Record<string, unknown> | null {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value)
|
||||
? (value as Record<string, unknown>)
|
||||
: null;
|
||||
return isRecord(value) ? value : null;
|
||||
}
|
||||
+2
-4
@@ -1,3 +1,5 @@
|
||||
import { isRecord } from "@homarr/common";
|
||||
|
||||
export function getDependentRequestIds(requestsJson: string, sourceId: string) {
|
||||
const requests = parseRequestRecord(requestsJson);
|
||||
return Object.entries(requests).flatMap(([requestId, request]) =>
|
||||
@@ -21,7 +23,3 @@ function parseRequestRecord(requestsJson: string): Record<string, unknown> {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
import { isRecord } from "@homarr/common";
|
||||
|
||||
export function areCustomWidgetValuesEqual(left: unknown, right: unknown): boolean {
|
||||
if (Object.is(left, right)) return true;
|
||||
|
||||
@@ -12,7 +14,3 @@ export function areCustomWidgetValuesEqual(left: unknown, right: unknown): boole
|
||||
if (leftKeys.length !== rightKeys.length) return false;
|
||||
return leftKeys.every((key) => Object.hasOwn(right, key) && areCustomWidgetValuesEqual(left[key], right[key]));
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { registerUnsavedChangesGuard } from "./_unsaved-changes-guard";
|
||||
import { registerUnsavedChangesGuard } from "~/components/manage/unsaved-changes-guard";
|
||||
|
||||
const cleanups: Array<() => void> = [];
|
||||
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
interface UnsavedChangesGuardOptions {
|
||||
isDirty(): boolean;
|
||||
confirmNavigation(href: string): void;
|
||||
}
|
||||
|
||||
export function registerUnsavedChangesGuard({ isDirty, confirmNavigation }: UnsavedChangesGuardOptions) {
|
||||
let currentHref = `${window.location.pathname}${window.location.search}${window.location.hash}`;
|
||||
const handleClick = (event: MouseEvent) => {
|
||||
if (!isDirty() || event.defaultPrevented || event.button !== 0) return;
|
||||
if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
|
||||
|
||||
const eventTarget = event.target instanceof Element ? event.target : null;
|
||||
const anchor = eventTarget?.closest<HTMLAnchorElement>("a[href]");
|
||||
if (!anchor || anchor.target === "_blank" || anchor.hasAttribute("download")) return;
|
||||
|
||||
const destination = new URL(anchor.href, window.location.href);
|
||||
const current = new URL(window.location.href);
|
||||
if (destination.origin !== current.origin) return;
|
||||
if (
|
||||
destination.pathname === current.pathname &&
|
||||
destination.search === current.search &&
|
||||
destination.hash !== current.hash
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
event.preventDefault();
|
||||
event.stopImmediatePropagation();
|
||||
confirmNavigation(`${destination.pathname}${destination.search}${destination.hash}`);
|
||||
};
|
||||
const handleBeforeUnload = (event: BeforeUnloadEvent) => {
|
||||
if (!isDirty()) return;
|
||||
event.preventDefault();
|
||||
event.returnValue = true;
|
||||
};
|
||||
const handlePopState = () => {
|
||||
const destination = `${window.location.pathname}${window.location.search}${window.location.hash}`;
|
||||
if (!isDirty()) {
|
||||
currentHref = destination;
|
||||
return;
|
||||
}
|
||||
window.history.pushState(window.history.state, "", currentHref);
|
||||
confirmNavigation(destination);
|
||||
};
|
||||
|
||||
document.addEventListener("click", handleClick, true);
|
||||
window.addEventListener("beforeunload", handleBeforeUnload);
|
||||
window.addEventListener("popstate", handlePopState);
|
||||
return () => {
|
||||
document.removeEventListener("click", handleClick, true);
|
||||
window.removeEventListener("beforeunload", handleBeforeUnload);
|
||||
window.removeEventListener("popstate", handlePopState);
|
||||
};
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
import { useConfirmModal } from "@homarr/modals";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import { registerUnsavedChangesGuard } from "./_unsaved-changes-guard";
|
||||
|
||||
export function useUnsavedChangesGuard(isDirty: boolean) {
|
||||
const tConfirmLeave = useI18n("board.action.edit.confirmLeave");
|
||||
const tCommon = useI18n("common");
|
||||
const router = useRouter();
|
||||
const { openConfirmModal } = useConfirmModal();
|
||||
const dirtyRef = useRef(isDirty);
|
||||
const confirmNavigationRef = useRef<(href: string) => void>(() => undefined);
|
||||
dirtyRef.current = isDirty;
|
||||
confirmNavigationRef.current = (href) => {
|
||||
openConfirmModal({
|
||||
title: tConfirmLeave("title"),
|
||||
children: tConfirmLeave("message"),
|
||||
confirmProps: { children: tCommon("action.discard") },
|
||||
onConfirm: () => router.push(href),
|
||||
});
|
||||
};
|
||||
|
||||
useEffect(
|
||||
() =>
|
||||
registerUnsavedChangesGuard({
|
||||
isDirty: () => dirtyRef.current,
|
||||
confirmNavigation: (href) => confirmNavigationRef.current(href),
|
||||
}),
|
||||
[],
|
||||
);
|
||||
}
|
||||
+6
-2
@@ -26,10 +26,11 @@ import {
|
||||
} from "@tabler/icons-react";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { useByteFormatter } from "@homarr/settings";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import { Link } from "@homarr/ui";
|
||||
import { useWorkshopCreateMutation } from "@homarr/workshop/backend";
|
||||
import { workshopScreenshotsSchema } from "@homarr/workshop/schema";
|
||||
import { MAX_WORKSHOP_SCREENSHOT_BYTES, workshopScreenshotsSchema } from "@homarr/workshop/schema";
|
||||
|
||||
import { ManagePageLayout } from "~/components/manage/manage-page-layout";
|
||||
import { ManageStickyFooter } from "~/components/manage/manage-sticky-footer";
|
||||
@@ -47,6 +48,7 @@ const listHref = "/manage/custom-widgets";
|
||||
export function WorkshopPublishForm({ widget }: { widget: { id: string; name: string } }) {
|
||||
const t = useI18n("workshop");
|
||||
const tCommon = useI18n("common");
|
||||
const { formatBytes } = useByteFormatter();
|
||||
const session = useWorkshopSession();
|
||||
const [title, setTitle] = useState(widget.name);
|
||||
const [description, setDescription] = useState("");
|
||||
@@ -70,7 +72,9 @@ export function WorkshopPublishForm({ widget }: { widget: { id: string; name: st
|
||||
setError(null);
|
||||
try {
|
||||
if (!definition.data) throw new Error(t("publish.error"));
|
||||
if (!workshopScreenshotsSchema.safeParse(screenshots).success) throw new Error(t("publish.invalidScreenshot"));
|
||||
if (!workshopScreenshotsSchema.safeParse(screenshots).success) {
|
||||
throw new Error(t("publish.invalidScreenshot", { maxSize: formatBytes(MAX_WORKSHOP_SCREENSHOT_BYTES) }));
|
||||
}
|
||||
|
||||
let submissionId: string | null = null;
|
||||
const result = await publishWorkshopDefinition({
|
||||
|
||||
@@ -12,6 +12,7 @@ interface CopyMediaProps {
|
||||
|
||||
export const CopyMedia = ({ media }: CopyMediaProps) => {
|
||||
const t = useI18n("media");
|
||||
const label = t("action.copy.labelNamed", { name: media.name });
|
||||
|
||||
const url = typeof window !== "undefined" ? `${window.location.origin}/api/user-medias/${media.id}` : "";
|
||||
|
||||
@@ -23,8 +24,8 @@ export const CopyMedia = ({ media }: CopyMediaProps) => {
|
||||
return (
|
||||
<CopyButton value={url}>
|
||||
{({ copy, copied }) => (
|
||||
<Tooltip label={t("action.copy.label")} openDelay={500}>
|
||||
<ActionIcon onClick={copy} color={copied ? "teal" : "gray"} variant="subtle">
|
||||
<Tooltip label={label} openDelay={500}>
|
||||
<ActionIcon aria-label={label} onClick={copy} color={copied ? "teal" : "gray"} variant="subtle">
|
||||
{copied ? <IconCheck size={16} stroke={1.5} /> : <IconCopy size={16} stroke={1.5} />}
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
|
||||
@@ -1,24 +1,28 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { notFound, redirect } from "next/navigation";
|
||||
import {
|
||||
ActionIcon,
|
||||
Anchor,
|
||||
Group,
|
||||
Image,
|
||||
Table,
|
||||
TableScrollContainer,
|
||||
TableTbody,
|
||||
TableTd,
|
||||
TableTh,
|
||||
TableThead,
|
||||
TableTr,
|
||||
Tooltip,
|
||||
VisuallyHidden,
|
||||
} from "@mantine/core";
|
||||
import { IconExternalLink, IconPhoto } from "@tabler/icons-react";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import type { RouterOutputs } from "@homarr/api";
|
||||
import { api } from "@homarr/api/server";
|
||||
import { getRscUserSettingsAsync } from "@homarr/api/user-server";
|
||||
import { auth } from "@homarr/auth/next";
|
||||
import { formatBytes } from "@homarr/common";
|
||||
import { defaultByteUnitSystem, formatBytes } from "@homarr/common";
|
||||
import type { ByteUnitSystem } from "@homarr/common";
|
||||
import type { inferSearchParamsFromSchema } from "@homarr/common/types";
|
||||
import { createLocalImageUrl } from "@homarr/icons/local";
|
||||
import { getI18n } from "@homarr/translation/server";
|
||||
@@ -36,11 +40,21 @@ const searchParamsSchema = z.object({
|
||||
search: z.string().optional(),
|
||||
includeFromAllUsers: z
|
||||
.string()
|
||||
.regex(/true|false/)
|
||||
.regex(/^(?:true|false)$/u)
|
||||
.catch("false")
|
||||
.transform((value) => value === "true"),
|
||||
pageSize: z.string().regex(/\d+/).transform(Number).catch(10),
|
||||
page: z.string().regex(/\d+/).transform(Number).catch(1),
|
||||
pageSize: z
|
||||
.string()
|
||||
.regex(/^[1-9]\d*$/u)
|
||||
.transform(Number)
|
||||
.pipe(z.number().int().positive().max(100))
|
||||
.catch(10),
|
||||
page: z
|
||||
.string()
|
||||
.regex(/^[1-9]\d*$/u)
|
||||
.transform(Number)
|
||||
.pipe(z.number().int().positive())
|
||||
.catch(1),
|
||||
});
|
||||
|
||||
interface MediaListPageProps {
|
||||
@@ -57,7 +71,17 @@ export default async function MediaListPage(props: MediaListPageProps) {
|
||||
const tMedia = await getI18n("media");
|
||||
const [tCommon, tEntities] = await Promise.all([getI18n("common"), getI18n("common.entity")]);
|
||||
const searchParams = searchParamsSchema.parse(await props.searchParams);
|
||||
const { items: medias, totalCount } = await api.media.getPaginated(searchParams);
|
||||
const [{ items: medias, totalCount }, userSettings] = await Promise.all([
|
||||
api.media.getPaginated(searchParams),
|
||||
getRscUserSettingsAsync(session.user.id),
|
||||
]);
|
||||
const totalPages = Math.ceil(totalCount / searchParams.pageSize);
|
||||
|
||||
if (totalPages > 0 && searchParams.page > totalPages) {
|
||||
const params = createPaginationSearchParams(searchParams, totalPages);
|
||||
redirect(`/manage/medias?${params.toString()}`);
|
||||
}
|
||||
|
||||
const canUpload = session.user.permissions.includes("media-upload");
|
||||
|
||||
return (
|
||||
@@ -82,27 +106,37 @@ export default async function MediaListPage(props: MediaListPageProps) {
|
||||
)}
|
||||
</Group>
|
||||
}
|
||||
footer={<TablePagination total={Math.ceil(totalCount / searchParams.pageSize)} />}
|
||||
footer={totalPages > 1 ? <TablePagination total={totalPages} /> : undefined}
|
||||
floatingPrimaryAction={canUpload}
|
||||
>
|
||||
{medias.length === 0 && <NoResults icon={IconPhoto} title={tMedia("noResults.title")} />}
|
||||
{medias.length > 0 && (
|
||||
<Table striped highlightOnHover>
|
||||
<TableThead>
|
||||
<TableTr>
|
||||
<TableTh></TableTh>
|
||||
<TableTh>{tCommon("field.name")}</TableTh>
|
||||
<TableTh>{tMedia("field.size")}</TableTh>
|
||||
<TableTh>{tMedia("field.creator")}</TableTh>
|
||||
<TableTh></TableTh>
|
||||
</TableTr>
|
||||
</TableThead>
|
||||
<TableTbody>
|
||||
{medias.map((media) => (
|
||||
<Row key={media.id} media={media} />
|
||||
))}
|
||||
</TableTbody>
|
||||
</Table>
|
||||
<TableScrollContainer minWidth={680}>
|
||||
<Table striped highlightOnHover>
|
||||
<TableThead>
|
||||
<TableTr>
|
||||
<TableTh>
|
||||
<VisuallyHidden>{tMedia("field.preview")}</VisuallyHidden>
|
||||
</TableTh>
|
||||
<TableTh>{tCommon("field.name")}</TableTh>
|
||||
<TableTh>{tMedia("field.size")}</TableTh>
|
||||
<TableTh>{tMedia("field.creator")}</TableTh>
|
||||
<TableTh>
|
||||
<VisuallyHidden>{tMedia("field.actions")}</VisuallyHidden>
|
||||
</TableTh>
|
||||
</TableTr>
|
||||
</TableThead>
|
||||
<TableTbody>
|
||||
{medias.map((media) => (
|
||||
<Row
|
||||
key={media.id}
|
||||
media={media}
|
||||
byteUnitSystem={userSettings?.byteUnitSystem ?? defaultByteUnitSystem}
|
||||
/>
|
||||
))}
|
||||
</TableTbody>
|
||||
</Table>
|
||||
</TableScrollContainer>
|
||||
)}
|
||||
</ManagePageLayout>
|
||||
);
|
||||
@@ -110,9 +144,10 @@ export default async function MediaListPage(props: MediaListPageProps) {
|
||||
|
||||
interface RowProps {
|
||||
media: RouterOutputs["media"]["getPaginated"]["items"][number];
|
||||
byteUnitSystem: ByteUnitSystem;
|
||||
}
|
||||
|
||||
const Row = async ({ media }: RowProps) => {
|
||||
const Row = async ({ media, byteUnitSystem }: RowProps) => {
|
||||
const session = await auth();
|
||||
const tMedia = await getI18n("media");
|
||||
const canDelete = media.creatorId === session?.user.id || session?.user.permissions.includes("media-full-all");
|
||||
@@ -129,8 +164,8 @@ const Row = async ({ media }: RowProps) => {
|
||||
fit="contain"
|
||||
/>
|
||||
</TableTd>
|
||||
<TableTd>{media.name}</TableTd>
|
||||
<TableTd>{formatBytes(media.size)}</TableTd>
|
||||
<TableTh scope="row">{media.name}</TableTh>
|
||||
<TableTd>{formatBytes(media.size, { unit: byteUnitSystem })}</TableTd>
|
||||
<TableTd>
|
||||
{media.creator ? (
|
||||
<Group gap="sm">
|
||||
@@ -146,11 +181,13 @@ const Row = async ({ media }: RowProps) => {
|
||||
<TableTd w={64}>
|
||||
<Group wrap="nowrap" gap="xs">
|
||||
<CopyMedia media={media} />
|
||||
<Tooltip label={tMedia("action.open.label")} openDelay={500}>
|
||||
<Tooltip label={tMedia("action.open.labelNamed", { name: media.name })} openDelay={500}>
|
||||
<ActionIcon
|
||||
aria-label={tMedia("action.open.labelNamed", { name: media.name })}
|
||||
component="a"
|
||||
href={createLocalImageUrl(media.id)}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
color="gray"
|
||||
variant="subtle"
|
||||
>
|
||||
@@ -163,3 +200,13 @@ const Row = async ({ media }: RowProps) => {
|
||||
</TableTr>
|
||||
);
|
||||
};
|
||||
|
||||
const createPaginationSearchParams = (searchParams: z.infer<typeof searchParamsSchema>, page: number) => {
|
||||
const params = new URLSearchParams({ page: page.toString() });
|
||||
|
||||
if (searchParams.search) params.set("search", searchParams.search);
|
||||
if (searchParams.includeFromAllUsers) params.set("includeFromAllUsers", "true");
|
||||
if (searchParams.pageSize !== 10) params.set("pageSize", searchParams.pageSize.toString());
|
||||
|
||||
return params;
|
||||
};
|
||||
@@ -18,8 +18,18 @@ import { SearchEngineDeleteButton } from "./_search-engine-delete-button";
|
||||
|
||||
const searchParamsSchema = z.object({
|
||||
search: z.string().optional(),
|
||||
pageSize: z.string().regex(/\d+/).transform(Number).catch(10),
|
||||
page: z.string().regex(/\d+/).transform(Number).catch(1),
|
||||
pageSize: z
|
||||
.string()
|
||||
.regex(/^[1-9]\d*$/u)
|
||||
.transform(Number)
|
||||
.pipe(z.number().int().positive().max(100))
|
||||
.catch(10),
|
||||
page: z
|
||||
.string()
|
||||
.regex(/^[1-9]\d*$/u)
|
||||
.transform(Number)
|
||||
.pipe(z.number().int().positive())
|
||||
.catch(1),
|
||||
});
|
||||
|
||||
interface SearchEnginesPageProps {
|
||||
@@ -32,6 +42,13 @@ export default async function SearchEnginesPage(props: SearchEnginesPageProps) {
|
||||
|
||||
const searchParams = searchParamsSchema.parse(await props.searchParams);
|
||||
const { items: searchEngines, totalCount } = await api.searchEngine.getPaginated(searchParams);
|
||||
const totalPages = Math.ceil(totalCount / searchParams.pageSize);
|
||||
|
||||
if (totalPages > 0 && searchParams.page > totalPages) {
|
||||
const params = createPaginationSearchParams(searchParams.search, searchParams.pageSize, totalPages);
|
||||
redirect(`/manage/search-engines?${params.toString()}`);
|
||||
}
|
||||
|
||||
const t = await getI18n("search.engine");
|
||||
const tCommon = await getI18n("common");
|
||||
const canCreate = session.user.permissions.includes("search-engine-create");
|
||||
@@ -80,11 +97,7 @@ export default async function SearchEnginesPage(props: SearchEnginesPageProps) {
|
||||
flexExpand
|
||||
/>
|
||||
}
|
||||
footer={
|
||||
totalCount > searchParams.pageSize ? (
|
||||
<TablePagination total={Math.ceil(totalCount / searchParams.pageSize)} />
|
||||
) : undefined
|
||||
}
|
||||
footer={totalPages > 1 ? <TablePagination total={totalPages} /> : undefined}
|
||||
floatingPrimaryAction={canCreate}
|
||||
>
|
||||
{searchEngines.map((searchEngine) => (
|
||||
@@ -172,3 +185,12 @@ const SearchEngineItem = async ({ searchEngine, canModify, canDelete }: SearchEn
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
const createPaginationSearchParams = (search: string | undefined, pageSize: number, page: number) => {
|
||||
const params = new URLSearchParams({ page: page.toString() });
|
||||
|
||||
if (search) params.set("search", search);
|
||||
if (pageSize !== 10) params.set("pageSize", pageSize.toString());
|
||||
|
||||
return params;
|
||||
};
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useRef, useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Button, Stack } from "@mantine/core";
|
||||
import { z } from "zod/v4";
|
||||
@@ -8,7 +8,6 @@ import { z } from "zod/v4";
|
||||
import type { RouterOutputs } from "@homarr/api";
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { revalidatePathActionAsync } from "@homarr/common/client";
|
||||
import { env } from "@homarr/common/env";
|
||||
import { colorSchemes } from "@homarr/definitions";
|
||||
import { useZodForm } from "@homarr/form";
|
||||
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
|
||||
@@ -17,6 +16,7 @@ import { brandingServerSettingsSchema } from "@homarr/server-settings";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
|
||||
import { UnsavedChangesBar } from "~/components/manage/unsaved-changes-bar";
|
||||
import { useUnsavedChangesGuard } from "~/components/manage/use-unsaved-changes-guard";
|
||||
import { AnalyticsSettings } from "./analytics.settings";
|
||||
import { AppearanceSettingsForm } from "./appearance-settings-form";
|
||||
import { BoardSettingsForm } from "./board-settings-form";
|
||||
@@ -80,8 +80,7 @@ export const SettingsForm = ({ initialData, selectableBoards, selectableSearchEn
|
||||
initialValues,
|
||||
});
|
||||
|
||||
const isDirtyRef = useRef(false);
|
||||
isDirtyRef.current = form.isDirty();
|
||||
useUnsavedChangesGuard(form.isDirty());
|
||||
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
|
||||
@@ -91,15 +90,6 @@ export const SettingsForm = ({ initialData, selectableBoards, selectableSearchEn
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const handler = (event: BeforeUnloadEvent) => {
|
||||
if (env.NODE_ENV === "development") return;
|
||||
if (isDirtyRef.current) event.preventDefault();
|
||||
};
|
||||
window.addEventListener("beforeunload", handler);
|
||||
return () => window.removeEventListener("beforeunload", handler);
|
||||
}, []);
|
||||
|
||||
const handleSubmitAsync = async (values: FormValues) => {
|
||||
const defaults = initialValuesRef.current;
|
||||
const changed = <TKey extends keyof FormValues>(...fields: TKey[]) =>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useState } from "react";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import {
|
||||
Accordion,
|
||||
AccordionControl,
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
ListItem,
|
||||
Stack,
|
||||
Text,
|
||||
TextInput,
|
||||
ThemeIcon,
|
||||
Title,
|
||||
} from "@mantine/core";
|
||||
@@ -29,6 +30,7 @@ import {
|
||||
IconLock,
|
||||
IconPlus,
|
||||
IconPlugConnected,
|
||||
IconSearch,
|
||||
IconSparkles,
|
||||
IconTerminal,
|
||||
IconTools,
|
||||
@@ -59,6 +61,8 @@ export function McpInstructions({ baseUrl, hasApiKeys, toolGroups, onApiKeyCreat
|
||||
const t = useI18n("management.page.tool.api.tab.mcp");
|
||||
const tCommon = useI18n("common");
|
||||
const [newApiKey, setNewApiKey] = useState<string | null>(null);
|
||||
const [toolSearch, setToolSearch] = useState("");
|
||||
const [openToolGroups, setOpenToolGroups] = useState<string[]>([]);
|
||||
const { mutate: createApiKey, isPending } = clientApi.apiKeys.create.useMutation({
|
||||
onSuccess(data) {
|
||||
setNewApiKey(data.apiKey);
|
||||
@@ -70,6 +74,25 @@ export function McpInstructions({ baseUrl, hasApiKeys, toolGroups, onApiKeyCreat
|
||||
await revalidatePathActionAsync("/manage/tools/api");
|
||||
}, []);
|
||||
const mcpUrl = `${baseUrl}/api/mcp`;
|
||||
const normalizedToolSearch = toolSearch.trim().toLowerCase();
|
||||
const filteredToolGroups = useMemo(() => {
|
||||
if (!normalizedToolSearch) return toolGroups;
|
||||
|
||||
return toolGroups.flatMap((group) => {
|
||||
const namespaceMatches = group.namespace.toLowerCase().includes(normalizedToolSearch);
|
||||
const tools = namespaceMatches
|
||||
? group.tools
|
||||
: group.tools.filter((tool) => `${tool.name} ${tool.description}`.toLowerCase().includes(normalizedToolSearch));
|
||||
|
||||
if (tools.length === 0) return [];
|
||||
return [{ ...group, tools }];
|
||||
});
|
||||
}, [normalizedToolSearch, toolGroups]);
|
||||
const filteredToolCount = filteredToolGroups.reduce((sum, group) => sum + group.tools.length, 0);
|
||||
const filteredToolGroupNames = filteredToolGroups.map((group) => group.namespace);
|
||||
const accordionStateProps = normalizedToolSearch
|
||||
? { defaultValue: filteredToolGroupNames }
|
||||
: { value: openToolGroups, onChange: setOpenToolGroups };
|
||||
|
||||
const streamableHttpConfig = JSON.stringify(
|
||||
{
|
||||
@@ -291,45 +314,64 @@ export function McpInstructions({ baseUrl, hasApiKeys, toolGroups, onApiKeyCreat
|
||||
</Group>
|
||||
</Title>
|
||||
<Text size="sm" c="dimmed" mb="sm">
|
||||
{t("availableTools.description", {
|
||||
count: String(toolGroups.reduce((sum, g) => sum + g.tools.length, 0)),
|
||||
})}
|
||||
{normalizedToolSearch
|
||||
? t("availableTools.filteredDescription", { count: String(filteredToolCount) })
|
||||
: t("availableTools.description", { count: String(filteredToolCount) })}
|
||||
</Text>
|
||||
<Accordion variant="separated" multiple>
|
||||
{toolGroups.map((group) => (
|
||||
<AccordionItem key={group.namespace} value={group.namespace}>
|
||||
<AccordionControl>
|
||||
<Group gap="xs">
|
||||
<Text size="sm" fw={600}>
|
||||
{group.namespace}
|
||||
</Text>
|
||||
<Badge size="xs" variant="light" circle>
|
||||
{group.tools.length}
|
||||
</Badge>
|
||||
</Group>
|
||||
</AccordionControl>
|
||||
<AccordionPanel>
|
||||
<Stack gap={6}>
|
||||
{group.tools.map((tool) => (
|
||||
<div key={tool.name} className={classes.toolRow}>
|
||||
<Badge size="sm" w={50} radius="xs" color={toolTypeDisplay[tool.type].color} variant="light">
|
||||
{toolTypeDisplay[tool.type].method}
|
||||
</Badge>
|
||||
<div>
|
||||
<Code fz="xs" fw={600}>
|
||||
{tool.name}
|
||||
</Code>
|
||||
<Text size="xs" c="dimmed" lh={1.4}>
|
||||
{tool.description}
|
||||
</Text>
|
||||
<TextInput
|
||||
value={toolSearch}
|
||||
onChange={(event) => setToolSearch(event.currentTarget.value)}
|
||||
leftSection={<IconSearch size={16} />}
|
||||
placeholder={t("availableTools.search")}
|
||||
aria-label={t("availableTools.search")}
|
||||
mb="sm"
|
||||
/>
|
||||
{filteredToolGroups.length === 0 ? (
|
||||
<Alert variant="light" color="gray" title={t("availableTools.noResults.title")}>
|
||||
<Stack gap="sm" align="flex-start">
|
||||
<Text size="sm">{t("availableTools.noResults.description", { search: toolSearch.trim() })}</Text>
|
||||
<Button size="compact-sm" variant="default" onClick={() => setToolSearch("")}>
|
||||
{tCommon("action.clearSearch")}
|
||||
</Button>
|
||||
</Stack>
|
||||
</Alert>
|
||||
) : (
|
||||
<Accordion key={normalizedToolSearch} variant="separated" multiple {...accordionStateProps}>
|
||||
{filteredToolGroups.map((group) => (
|
||||
<AccordionItem key={group.namespace} value={group.namespace}>
|
||||
<AccordionControl>
|
||||
<Group gap="xs">
|
||||
<Text size="sm" fw={600}>
|
||||
{group.namespace}
|
||||
</Text>
|
||||
<Badge size="xs" variant="light" circle>
|
||||
{group.tools.length}
|
||||
</Badge>
|
||||
</Group>
|
||||
</AccordionControl>
|
||||
<AccordionPanel>
|
||||
<Stack gap={6}>
|
||||
{group.tools.map((tool) => (
|
||||
<div key={tool.name} className={classes.toolRow}>
|
||||
<Badge size="sm" w={50} radius="xs" color={toolTypeDisplay[tool.type].color} variant="light">
|
||||
{toolTypeDisplay[tool.type].method}
|
||||
</Badge>
|
||||
<div>
|
||||
<Code fz="xs" fw={600}>
|
||||
{tool.name}
|
||||
</Code>
|
||||
<Text size="xs" c="dimmed" lh={1.4}>
|
||||
{tool.description}
|
||||
</Text>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</Stack>
|
||||
</AccordionPanel>
|
||||
</AccordionItem>
|
||||
))}
|
||||
</Accordion>
|
||||
))}
|
||||
</Stack>
|
||||
</AccordionPanel>
|
||||
</AccordionItem>
|
||||
))}
|
||||
</Accordion>
|
||||
)}
|
||||
</div>
|
||||
</Stack>
|
||||
);
|
||||
|
||||
@@ -19,13 +19,14 @@ import { MantineReactTable } from "mantine-react-table";
|
||||
|
||||
import type { RouterOutputs } from "@homarr/api";
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { formatBytes, useTimeAgo } from "@homarr/common";
|
||||
import { useTimeAgo } from "@homarr/common";
|
||||
import { invariantTechnicalLabels } from "@homarr/definitions";
|
||||
import type { ContainerState, DockerEndpointCapability } from "@homarr/docker";
|
||||
import { containerStateColorMap, cpuUsageColor, memoryUsageColor, safeValue } from "@homarr/docker/shared";
|
||||
import { useModalAction } from "@homarr/modals";
|
||||
import { AddDockerAppToHomarr, useDockerContainerRemovalConfirmation } from "@homarr/modals-collection";
|
||||
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
|
||||
import { useByteFormatter } from "@homarr/settings";
|
||||
import type { ScopedTranslationFunction } from "@homarr/translation";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import type { TablerIcon } from "@homarr/ui";
|
||||
@@ -72,6 +73,7 @@ const showContainerActionResult = (
|
||||
const createColumns = (
|
||||
tDocker: ScopedTranslationFunction<"docker">,
|
||||
tCommon: ScopedTranslationFunction<"common">,
|
||||
formatBytes: (bytes: number) => string,
|
||||
): MRT_ColumnDef<DockerContainer>[] => [
|
||||
{
|
||||
accessorKey: "name",
|
||||
@@ -194,6 +196,7 @@ export function DockerTable({ initialData }: DockerTableProps) {
|
||||
const tDocker = useI18n("docker");
|
||||
const tCommon = useI18n("common");
|
||||
const utils = clientApi.useUtils();
|
||||
const { formatBytes } = useByteFormatter();
|
||||
const { data, isFetching } = clientApi.docker.getContainers.useQuery(undefined, {
|
||||
initialData,
|
||||
refetchOnMount: false,
|
||||
@@ -282,7 +285,7 @@ export function DockerTable({ initialData }: DockerTableProps) {
|
||||
);
|
||||
},
|
||||
|
||||
columns: createColumns(tDocker, tCommon),
|
||||
columns: createColumns(tDocker, tCommon, formatBytes),
|
||||
});
|
||||
|
||||
return (
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { ActionIcon, Badge, Button, Group, Select, Text } from "@mantine/core";
|
||||
import { ActionIcon, Badge, Button, Group, Select, Text, Tooltip } from "@mantine/core";
|
||||
import { useMap } from "@mantine/hooks";
|
||||
import { IconPlayerPlay, IconPower, IconRefresh } from "@tabler/icons-react";
|
||||
import type { MRT_ColumnDef } from "mantine-react-table";
|
||||
@@ -84,6 +84,34 @@ type JobData = RouterOutputs["cronJobs"]["getJobs"][number] & {
|
||||
lastExecutionTime?: string;
|
||||
};
|
||||
|
||||
type TaskControl = "interval" | "toggle" | "trigger";
|
||||
|
||||
const restoreTaskControlFocus = (jobName: string, action: TaskControl, originalControl: HTMLElement | null) => {
|
||||
const focusWhenEnabled = (attemptsRemaining: number) => {
|
||||
if (document.activeElement && document.activeElement !== document.body) return;
|
||||
|
||||
let control: HTMLElement | null = null;
|
||||
if (originalControl?.isConnected && originalControl !== document.body) control = originalControl;
|
||||
if (!control) {
|
||||
const controls = document.querySelectorAll<HTMLElement>(`[data-task-action="${action}"]`);
|
||||
for (const candidate of controls) {
|
||||
if (candidate.dataset.taskName !== jobName) continue;
|
||||
control = candidate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (control && !control.matches(":disabled")) {
|
||||
control.focus();
|
||||
return;
|
||||
}
|
||||
if (attemptsRemaining <= 0) return;
|
||||
window.setTimeout(() => focusWhenEnabled(attemptsRemaining - 1), 100);
|
||||
};
|
||||
|
||||
window.setTimeout(() => focusWhenEnabled(50), 0);
|
||||
};
|
||||
|
||||
const createColumns = (
|
||||
tCommon: ScopedTranslationFunction<"common">,
|
||||
tTasks: ScopedTranslationFunction<"management.page.tool.tasks">,
|
||||
@@ -119,7 +147,7 @@ const createColumns = (
|
||||
Cell({ row }) {
|
||||
if (row.original.preventCustomInterval) return null;
|
||||
|
||||
const handleIntervalChange = (newCron: string | null) => {
|
||||
const handleIntervalChange = async (newCron: string | null, originalControl: HTMLElement | null) => {
|
||||
if (!newCron || newCron === row.original.cron) return;
|
||||
|
||||
const currentStates = loadingStates.get(row.original.name) ?? {
|
||||
@@ -133,10 +161,12 @@ const createColumns = (
|
||||
});
|
||||
|
||||
try {
|
||||
updateIntervalMutation.mutate({
|
||||
await updateIntervalMutation.mutateAsync({
|
||||
name: row.original.name,
|
||||
cron: newCron,
|
||||
});
|
||||
} catch {
|
||||
// The mutation callback displays the error notification.
|
||||
} finally {
|
||||
const updatedStates = loadingStates.get(row.original.name) ?? {
|
||||
toggle: false,
|
||||
@@ -147,17 +177,24 @@ const createColumns = (
|
||||
...updatedStates,
|
||||
interval: false,
|
||||
});
|
||||
restoreTaskControlFocus(row.original.name, "interval", originalControl);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Select
|
||||
value={row.original.cron}
|
||||
onChange={handleIntervalChange}
|
||||
onChange={(newCron) => {
|
||||
let originalControl: HTMLElement | null = null;
|
||||
if (document.activeElement instanceof HTMLElement) originalControl = document.activeElement;
|
||||
void handleIntervalChange(newCron, originalControl);
|
||||
}}
|
||||
data={cronExpressions.map(({ value, label }) => ({
|
||||
value,
|
||||
label: label(tTasks),
|
||||
}))}
|
||||
data-task-action="interval"
|
||||
data-task-name={row.original.name}
|
||||
size="sm"
|
||||
disabled={loadingStates.get(row.original.name)?.interval ?? false}
|
||||
style={{ minWidth: 180 }}
|
||||
@@ -188,8 +225,14 @@ const createColumns = (
|
||||
enableSorting: false,
|
||||
Cell({ row }) {
|
||||
const status = jobStatusMap.get(row.original.name);
|
||||
const jobLabel = tTasks(`job.${row.original.name}.label`);
|
||||
const triggerPending = loadingStates.get(row.original.name)?.trigger ?? false;
|
||||
const togglePending = loadingStates.get(row.original.name)?.toggle ?? false;
|
||||
const triggerLabel = tTasks("action.run", { name: jobLabel });
|
||||
let toggleLabel = tTasks("action.enable", { name: jobLabel });
|
||||
if (row.original.isEnabled) toggleLabel = tTasks("action.disable", { name: jobLabel });
|
||||
|
||||
const handleToggleEnabled = () => {
|
||||
const handleToggleEnabled = async (originalControl: HTMLButtonElement) => {
|
||||
const currentStates = loadingStates.get(row.original.name) ?? {
|
||||
toggle: false,
|
||||
trigger: false,
|
||||
@@ -201,10 +244,12 @@ const createColumns = (
|
||||
});
|
||||
try {
|
||||
if (row.original.isEnabled) {
|
||||
disableMutation.mutate(row.original.name);
|
||||
await disableMutation.mutateAsync(row.original.name);
|
||||
} else {
|
||||
enableMutation.mutate(row.original.name);
|
||||
await enableMutation.mutateAsync(row.original.name);
|
||||
}
|
||||
} catch {
|
||||
// The mutation callback displays the error notification.
|
||||
} finally {
|
||||
const updatedStates = loadingStates.get(row.original.name) ?? {
|
||||
toggle: false,
|
||||
@@ -215,11 +260,12 @@ const createColumns = (
|
||||
...updatedStates,
|
||||
toggle: false,
|
||||
});
|
||||
restoreTaskControlFocus(row.original.name, "toggle", originalControl);
|
||||
}
|
||||
};
|
||||
|
||||
const handleTrigger = () => {
|
||||
if (status?.status === "running") return;
|
||||
const handleTrigger = async (originalControl: HTMLButtonElement) => {
|
||||
if (status?.status === "running" || triggerPending) return;
|
||||
|
||||
const currentStates = loadingStates.get(row.original.name) ?? {
|
||||
toggle: false,
|
||||
@@ -231,7 +277,9 @@ const createColumns = (
|
||||
trigger: true,
|
||||
});
|
||||
try {
|
||||
triggerMutation.mutate(row.original.name);
|
||||
await triggerMutation.mutateAsync(row.original.name);
|
||||
} catch {
|
||||
// The mutation callback displays the error notification.
|
||||
} finally {
|
||||
const updatedStates = loadingStates.get(row.original.name) ?? {
|
||||
toggle: false,
|
||||
@@ -242,32 +290,44 @@ const createColumns = (
|
||||
...updatedStates,
|
||||
trigger: false,
|
||||
});
|
||||
restoreTaskControlFocus(row.original.name, "trigger", originalControl);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Group gap="xs">
|
||||
{!row.original.preventManualExecution && (
|
||||
<Tooltip label={triggerLabel} openDelay={500}>
|
||||
<ActionIcon
|
||||
aria-label={triggerLabel}
|
||||
onClick={(event) => void handleTrigger(event.currentTarget)}
|
||||
data-task-action="trigger"
|
||||
data-task-name={row.original.name}
|
||||
disabled={status?.status === "running" || triggerPending}
|
||||
loading={triggerPending}
|
||||
variant="light"
|
||||
color="green"
|
||||
size="md"
|
||||
>
|
||||
<IconPlayerPlay size={16} />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
)}
|
||||
<Tooltip label={toggleLabel} openDelay={500}>
|
||||
<ActionIcon
|
||||
onClick={handleTrigger}
|
||||
disabled={status?.status === "running"}
|
||||
loading={loadingStates.get(row.original.name)?.trigger ?? false}
|
||||
aria-label={toggleLabel}
|
||||
onClick={(event) => void handleToggleEnabled(event.currentTarget)}
|
||||
data-task-action="toggle"
|
||||
data-task-name={row.original.name}
|
||||
disabled={togglePending}
|
||||
loading={togglePending}
|
||||
variant="light"
|
||||
color="green"
|
||||
color={row.original.isEnabled ? "green" : "gray"}
|
||||
size="md"
|
||||
>
|
||||
<IconPlayerPlay size={16} />
|
||||
{row.original.isEnabled ? <IconPower size={16} /> : <IconPowerOff size={16} />}
|
||||
</ActionIcon>
|
||||
)}
|
||||
<ActionIcon
|
||||
onClick={handleToggleEnabled}
|
||||
loading={loadingStates.get(row.original.name)?.toggle ?? false}
|
||||
variant="light"
|
||||
color={row.original.isEnabled ? "green" : "gray"}
|
||||
size="md"
|
||||
>
|
||||
{row.original.isEnabled ? <IconPower size={16} /> : <IconPowerOff size={16} />}
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
</Group>
|
||||
);
|
||||
},
|
||||
|
||||
+37
-13
@@ -1,7 +1,8 @@
|
||||
"use client";
|
||||
|
||||
import type { ReactNode } from "react";
|
||||
import { useEffect, useMemo, useRef } from "react";
|
||||
import { useMemo, useRef } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import {
|
||||
Box,
|
||||
Button,
|
||||
@@ -26,13 +27,13 @@ import type { RouterOutputs } from "@homarr/api";
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import type { BoardPreviewData } from "@homarr/boards/layout-preview";
|
||||
import { revalidatePathActionAsync } from "@homarr/common/client";
|
||||
import { env } from "@homarr/common/env";
|
||||
import { useZodForm } from "@homarr/form";
|
||||
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import {
|
||||
headerPreferencesSchema,
|
||||
parseHeaderPreferences,
|
||||
userByteUnitSystemSchema,
|
||||
userChangeHomeBoardsSchema,
|
||||
userChangeSearchPreferencesSchema,
|
||||
userEditProfileSchema,
|
||||
@@ -43,6 +44,7 @@ import {
|
||||
|
||||
import { BoardSelect } from "~/components/board/board-select";
|
||||
import { CurrentLanguageCombobox } from "~/components/language/current-language-combobox";
|
||||
import { useUnsavedChangesGuard } from "~/components/manage/use-unsaved-changes-guard";
|
||||
import { HeaderComposer } from "./header-composer";
|
||||
|
||||
dayjs.extend(localeData);
|
||||
@@ -55,6 +57,7 @@ const userGeneralSettingsSchema = z.object({
|
||||
defaultSearchEngineId: userChangeSearchPreferencesSchema.shape.defaultSearchEngineId,
|
||||
openInNewTab: userChangeSearchPreferencesSchema.shape.openInNewTab,
|
||||
ddgBangsEnabled: userChangeSearchPreferencesSchema.shape.ddgBangsEnabled,
|
||||
byteUnitSystem: userByteUnitSystemSchema.shape.byteUnitSystem,
|
||||
firstDayOfWeek: userFirstDayOfWeekSchema.shape.firstDayOfWeek,
|
||||
pingIconsEnabled: userPingIconsEnabledSchema.shape.pingIconsEnabled,
|
||||
enableRightClickOnWidgets: userEnableRightClickOnWidgetsSchema.shape.enableRightClickOnWidgets,
|
||||
@@ -85,6 +88,7 @@ const buildInitialValues = (user: RouterOutputs["user"]["getById"]): FormValues
|
||||
defaultSearchEngineId: user.defaultSearchEngineId,
|
||||
openInNewTab: user.openSearchInNewTab,
|
||||
ddgBangsEnabled: user.ddgBangs,
|
||||
byteUnitSystem: user.byteUnitSystem,
|
||||
firstDayOfWeek: user.firstDayOfWeek as DayOfWeek,
|
||||
pingIconsEnabled: user.pingIconsEnabled,
|
||||
enableRightClickOnWidgets: user.enableRightClickOnWidgets,
|
||||
@@ -102,11 +106,13 @@ export const UserGeneralSettingsForm = ({
|
||||
const tCommon = useI18n("common");
|
||||
const tUserManagement = useI18n("management.page.user");
|
||||
const tGeneral = useI18n("management.page.user.setting.general");
|
||||
const router = useRouter();
|
||||
const isCredentialsUser = user.provider === "credentials";
|
||||
|
||||
const editProfileMutation = clientApi.user.editProfile.useMutation();
|
||||
const changeHomeBoardsMutation = clientApi.user.changeHomeBoards.useMutation();
|
||||
const changeSearchPreferencesMutation = clientApi.user.changeSearchPreferences.useMutation();
|
||||
const changeByteUnitSystemMutation = clientApi.user.changeByteUnitSystem.useMutation();
|
||||
const changeFirstDayOfWeekMutation = clientApi.user.changeFirstDayOfWeek.useMutation();
|
||||
const changePingIconsEnabledMutation = clientApi.user.changePingIconsEnabled.useMutation();
|
||||
const changeEnableRightClickOnWidgetsMutation = clientApi.user.changeEnableRightClickOnWidgets.useMutation();
|
||||
@@ -119,8 +125,7 @@ export const UserGeneralSettingsForm = ({
|
||||
initialValues,
|
||||
});
|
||||
|
||||
const isDirtyRef = useRef(false);
|
||||
isDirtyRef.current = form.isDirty();
|
||||
useUnsavedChangesGuard(form.isDirty());
|
||||
|
||||
const weekDays = useMemo(() => dayjs.weekdays(false), []);
|
||||
|
||||
@@ -128,6 +133,7 @@ export const UserGeneralSettingsForm = ({
|
||||
editProfileMutation,
|
||||
changeHomeBoardsMutation,
|
||||
changeSearchPreferencesMutation,
|
||||
changeByteUnitSystemMutation,
|
||||
changeFirstDayOfWeekMutation,
|
||||
changePingIconsEnabledMutation,
|
||||
changeEnableRightClickOnWidgetsMutation,
|
||||
@@ -135,15 +141,6 @@ export const UserGeneralSettingsForm = ({
|
||||
];
|
||||
const isPending = mutations.some((m) => m.isPending);
|
||||
|
||||
useEffect(() => {
|
||||
const handler = (e: BeforeUnloadEvent) => {
|
||||
if (env.NODE_ENV === "development") return;
|
||||
if (isDirtyRef.current) e.preventDefault();
|
||||
};
|
||||
window.addEventListener("beforeunload", handler);
|
||||
return () => window.removeEventListener("beforeunload", handler);
|
||||
}, []);
|
||||
|
||||
const handleSubmitAsync = async (values: FormValues) => {
|
||||
const parsed = userGeneralSettingsSchema.safeParse(values);
|
||||
if (!parsed.success) return;
|
||||
@@ -177,6 +174,14 @@ export const UserGeneralSettingsForm = ({
|
||||
ddgBangsEnabled: parsed.data.ddgBangsEnabled,
|
||||
}),
|
||||
},
|
||||
{
|
||||
when: changed("byteUnitSystem"),
|
||||
action: () =>
|
||||
changeByteUnitSystemMutation.mutateAsync({
|
||||
id: user.id,
|
||||
byteUnitSystem: parsed.data.byteUnitSystem,
|
||||
}),
|
||||
},
|
||||
{
|
||||
when: changed("firstDayOfWeek"),
|
||||
action: () =>
|
||||
@@ -215,6 +220,7 @@ export const UserGeneralSettingsForm = ({
|
||||
form.setInitialValues(newValues);
|
||||
form.resetDirty();
|
||||
await revalidatePathActionAsync(`/manage/users/${user.id}`);
|
||||
router.refresh();
|
||||
showSuccessNotification({
|
||||
title: tCommon("notification.update.success"),
|
||||
message: tCommon("notification.update.success"),
|
||||
@@ -344,6 +350,24 @@ export const UserGeneralSettingsForm = ({
|
||||
</Group>
|
||||
</Radio.Group>
|
||||
<Divider my="xs" />
|
||||
<Select
|
||||
label={tUser("field.byteUnitSystem.label")}
|
||||
description={tUser("field.byteUnitSystem.description")}
|
||||
data={[
|
||||
{
|
||||
value: "decimal",
|
||||
label: `${tUser("field.byteUnitSystem.options.decimal")} (KB, MB, GB)`,
|
||||
},
|
||||
{
|
||||
value: "binary",
|
||||
label: `${tUser("field.byteUnitSystem.options.binary")} (KiB, MiB, GiB)`,
|
||||
},
|
||||
]}
|
||||
allowDeselect={false}
|
||||
comboboxProps={{ withinPortal: true }}
|
||||
{...form.getInputProps("byteUnitSystem")}
|
||||
/>
|
||||
<Divider my="xs" />
|
||||
<Title order={4}>{tGeneral("item.accessibility")}</Title>
|
||||
<Switch
|
||||
label={tUser("field.pingIconsEnabled.label")}
|
||||
|
||||
+1
-1
@@ -52,7 +52,7 @@ export const UserProfileAvatarForm = ({ user }: UserProfileAvatarForm) => {
|
||||
if (error.shape?.data.code === "BAD_REQUEST") {
|
||||
showErrorNotification({
|
||||
title: tManageAvatar("changeImage.notification.toLarge.title"),
|
||||
message: tManageAvatar("changeImage.notification.toLarge.message", { size: "256KB" }),
|
||||
message: tManageAvatar("changeImage.notification.toLarge.message", { size: "256 KiB" }),
|
||||
});
|
||||
} else {
|
||||
showErrorNotification({
|
||||
|
||||
Reference in new issue
Block a user