Skip to content

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

chore: update prettier configuration for print width (#519)

Thomas Camlongf1b1ec59ecda
diff --git a/.gitignore b/.gitignore
index 6b4c33b50..8327c8b84 100644
--- a/.gitignore
+++ b/.gitignore
@@ -51,4 +51,7 @@ yarn-error.log*
db.sqlite
# logs
-*.log
\ No newline at end of file
+*.log
+
+apps/tasks/tasks.cjs
+apps/websocket/wssServer.cjs
\ No newline at end of file
diff --git a/.vscode/settings.json b/.vscode/settings.json
index b59ae4f97..53c760db0 100644
--- a/.vscode/settings.json
+++ b/.vscode/settings.json
@@ -6,9 +6,10 @@
],
"typescript.tsdk": "node_modules\\typescript\\lib",
"js/ts.implicitProjectConfig.experimentalDecorators": true,
+ "prettier.configPath": "./tooling/prettier/index.mjs",
"cSpell.words": [
"superjson",
"homarr",
"trpc"
]
-}
+}
\ No newline at end of file
diff --git a/apps/nextjs/next.config.mjs b/apps/nextjs/next.config.mjs
index 26bb9d9c1..fcf1321a4 100644
--- a/apps/nextjs/next.config.mjs
+++ b/apps/nextjs/next.config.mjs
@@ -10,19 +10,9 @@ const config = {
eslint: { ignoreDuringBuilds: true },
typescript: { ignoreBuildErrors: true },
experimental: {
- optimizePackageImports: [
- "@mantine/core",
- "@mantine/hooks",
- "@tabler/icons-react",
- ],
+ optimizePackageImports: ["@mantine/core", "@mantine/hooks", "@tabler/icons-react"],
},
- transpilePackages: [
- "@homarr/ui",
- "@homarr/notifications",
- "@homarr/modals",
- "@homarr/spotlight",
- "@homarr/widgets",
- ],
+ transpilePackages: ["@homarr/ui", "@homarr/notifications", "@homarr/modals", "@homarr/spotlight", "@homarr/widgets"],
images: {
domains: ["cdn.jsdelivr.net"],
},
diff --git a/apps/nextjs/src/app/[locale]/_client-providers/next-international.tsx b/apps/nextjs/src/app/[locale]/_client-providers/next-international.tsx
index 626296d69..8297a73bb 100644
--- a/apps/nextjs/src/app/[locale]/_client-providers/next-international.tsx
+++ b/apps/nextjs/src/app/[locale]/_client-providers/next-international.tsx
@@ -3,10 +3,7 @@ import type { PropsWithChildren } from "react";
import { defaultLocale } from "@homarr/translation";
import { I18nProviderClient } from "@homarr/translation/client";
-export const NextInternationalProvider = ({
- children,
- locale,
-}: PropsWithChildren<{ locale: string }>) => {
+export const NextInternationalProvider = ({ children, locale }: PropsWithChildren<{ locale: string }>) => {
return (
<I18nProviderClient locale={locale} fallback={defaultLocale}>
{children}
diff --git a/apps/nextjs/src/app/[locale]/_client-providers/session.tsx b/apps/nextjs/src/app/[locale]/_client-providers/session.tsx
index 5ed469e1c..d4e0538db 100644
--- a/apps/nextjs/src/app/[locale]/_client-providers/session.tsx
+++ b/apps/nextjs/src/app/[locale]/_client-providers/session.tsx
@@ -9,9 +9,6 @@ interface AuthProviderProps {
session: Session | null;
}
-export const AuthProvider = ({
- children,
- session,
-}: PropsWithChildren<AuthProviderProps>) => {
+export const AuthProvider = ({ children, session }: PropsWithChildren<AuthProviderProps>) => {
return <SessionProvider session={session}>{children}</SessionProvider>;
};
diff --git a/apps/nextjs/src/app/[locale]/_client-providers/trpc.tsx b/apps/nextjs/src/app/[locale]/_client-providers/trpc.tsx
index 00a923407..db34ced95 100644
--- a/apps/nextjs/src/app/[locale]/_client-providers/trpc.tsx
+++ b/apps/nextjs/src/app/[locale]/_client-providers/trpc.tsx
@@ -5,12 +5,7 @@ import { useState } from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
import { ReactQueryStreamedHydration } from "@tanstack/react-query-next-experimental";
-import {
- createWSClient,
- loggerLink,
- unstable_httpBatchStreamLink,
- wsLink,
-} from "@trpc/client";
+import { createWSClient, loggerLink, unstable_httpBatchStreamLink, wsLink } from "@trpc/client";
import superjson from "superjson";
import type { AppRouter } from "@homarr/api";
@@ -37,8 +32,7 @@ export function TRPCReactProvider(props: PropsWithChildren) {
links: [
loggerLink({
enabled: (opts) =>
- process.env.NODE_ENV === "development" ||
- (opts.direction === "down" && opts.result instanceof Error),
+ process.env.NODE_ENV === "development" || (opts.direction === "down" && opts.result instanceof Error),
}),
(args) => {
return ({ op, next }) => {
@@ -69,9 +63,7 @@ export function TRPCReactProvider(props: PropsWithChildren) {
return (
<clientApi.Provider client={trpcClient} queryClient={queryClient}>
<QueryClientProvider client={queryClient}>
- <ReactQueryStreamedHydration transformer={superjson}>
- {props.children}
- </ReactQueryStreamedHydration>
+ <ReactQueryStreamedHydration transformer={superjson}>{props.children}</ReactQueryStreamedHydration>
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>
</clientApi.Provider>
diff --git a/apps/nextjs/src/app/[locale]/auth/invite/[id]/_registration-form.tsx b/apps/nextjs/src/app/[locale]/auth/invite/[id]/_registration-form.tsx
index 9baf60958..e91e78de0 100644
--- a/apps/nextjs/src/app/[locale]/auth/invite/[id]/_registration-form.tsx
+++ b/apps/nextjs/src/app/[locale]/auth/invite/[id]/_registration-form.tsx
@@ -5,10 +5,7 @@ import { Button, PasswordInput, Stack, TextInput } from "@mantine/core";
import { clientApi } from "@homarr/api/client";
import { useZodForm } from "@homarr/form";
-import {
- showErrorNotification,
- showSuccessNotification,
-} from "@homarr/notifications";
+import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import { useScopedI18n } from "@homarr/translation/client";
import type { z } from "@homarr/validation";
import { validation } from "@homarr/validation";
@@ -32,9 +29,7 @@ export const RegistrationForm = ({ invite }: RegistrationFormProps) => {
},
});
- const handleSubmit = (
- values: z.infer<typeof validation.user.registration>,
- ) => {
+ const handleSubmit = (values: z.infer<typeof validation.user.registration>) => {
mutate(
{
...values,
@@ -63,11 +58,7 @@ export const RegistrationForm = ({ invite }: RegistrationFormProps) => {
<Stack gap="xl">
<form onSubmit={form.onSubmit(handleSubmit)}>
<Stack gap="lg">
- <TextInput
- label={t("field.username.label")}
- autoComplete="off"
- {...form.getInputProps("username")}
- />
+ <TextInput label={t("field.username.label")} autoComplete="off" {...form.getInputProps("username")} />
<PasswordInput
label={t("field.password.label")}
autoComplete="new-password"
diff --git a/apps/nextjs/src/app/[locale]/auth/invite/[id]/page.tsx b/apps/nextjs/src/app/[locale]/auth/invite/[id]/page.tsx
index a7441022d..989406228 100644
--- a/apps/nextjs/src/app/[locale]/auth/invite/[id]/page.tsx
+++ b/apps/nextjs/src/app/[locale]/auth/invite/[id]/page.tsx
@@ -18,18 +18,12 @@ interface InviteUsagePageProps {
};
}
-export default async function InviteUsagePage({
- params,
- searchParams,
-}: InviteUsagePageProps) {
+export default async function InviteUsagePage({ params, searchParams }: InviteUsagePageProps) {
const session = await auth();
if (session) notFound();
const invite = await db.query.invites.findFirst({
- where: and(
- eq(invites.id, params.id),
- eq(invites.token, searchParams.token),
- ),
+ where: and(eq(invites.id, params.id), eq(invites.token, searchParams.token)),
columns: {
id: true,
token: true,
diff --git a/apps/nextjs/src/app/[locale]/auth/login/_login-form.tsx b/apps/nextjs/src/app/[locale]/auth/login/_login-form.tsx
index d98d387b0..d0345ec72 100644
--- a/apps/nextjs/src/app/[locale]/auth/login/_login-form.tsx
+++ b/apps/nextjs/src/app/[locale]/auth/login/_login-form.tsx
@@ -2,22 +2,12 @@
import { useState } from "react";
import { useRouter } from "next/navigation";
-import {
- Alert,
- Button,
- PasswordInput,
- rem,
- Stack,
- TextInput,
-} from "@mantine/core";
+import { Alert, Button, PasswordInput, rem, Stack, TextInput } from "@mantine/core";
import { IconAlertTriangle } from "@tabler/icons-react";
import { signIn } from "@homarr/auth/client";
import { useZodForm } from "@homarr/form";
-import {
- showErrorNotification,
- showSuccessNotification,
-} from "@homarr/notifications";
+import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import { useScopedI18n } from "@homarr/translation/client";
import type { z } from "@homarr/validation";
import { validation } from "@homarr/validation";
@@ -34,9 +24,7 @@ export const LoginForm = () => {
},
});
- const handleSubmitAsync = async (
- values: z.infer<typeof validation.user.signIn>,
- ) => {
+ const handleSubmitAsync = async (values: z.infer<typeof validation.user.signIn>) => {
setIsLoading(true);
setError(undefined);
await signIn("credentials", {
@@ -67,18 +55,10 @@ export const LoginForm = () => {
return (
<Stack gap="xl">
- <form
- onSubmit={form.onSubmit((values) => void handleSubmitAsync(values))}
- >
+ <form onSubmit={form.onSubmit((values) => void handleSubmitAsync(values))}>
<Stack gap="lg">
- <TextInput
- label={t("field.username.label")}
- {...form.getInputProps("name")}
- />
- <PasswordInput
- label={t("field.password.label")}
- {...form.getInputProps("password")}
- />
+ <TextInput label={t("field.username.label")} {...form.getInputProps("name")} />
+ <PasswordInput label={t("field.password.label")} {...form.getInputProps("password")} />
<Button type="submit" fullWidth loading={isLoading}>
{t("action.login.label")}
</Button>
diff --git a/apps/nextjs/src/app/[locale]/boards/(content)/_client.tsx b/apps/nextjs/src/app/[locale]/boards/(content)/_client.tsx
index 1a7fe0cc1..ea80dc68b 100644
--- a/apps/nextjs/src/app/[locale]/boards/(content)/_client.tsx
+++ b/apps/nextjs/src/app/[locale]/boards/(content)/_client.tsx
@@ -18,9 +18,7 @@ export const updateBoardName = (name: string | null) => {
boardName = name;
};
-type UpdateCallback = (
- prev: RouterOutputs["board"]["getHomeBoard"],
-) => RouterOutputs["board"]["getHomeBoard"];
+type UpdateCallback = (prev: RouterOutputs["board"]["getHomeBoard"]) => RouterOutputs["board"]["getHomeBoard"];
export const useUpdateBoard = () => {
const utils = clientApi.useUtils();
@@ -46,9 +44,7 @@ export const ClientBoard = () => {
const board = useRequiredBoard();
const isReady = useIsBoardReady();
- const sortedSections = board.sections.sort(
- (sectionA, sectionB) => sectionA.position - sectionB.position,
- );
+ const sortedSections = board.sections.sort((sectionA, sectionB) => sectionA.position - sectionB.position);
const ref = useRef<HTMLDivElement>(null);
@@ -61,24 +57,12 @@ export const ClientBoard = () => {
loaderProps={{ size: "lg" }}
h={fullHeightWithoutHeaderAndFooter}
/>
- <Stack
- ref={ref}
- h="100%"
- style={{ visibility: isReady ? "visible" : "hidden" }}
- >
+ <Stack ref={ref} h="100%" style={{ visibility: isReady ? "visible" : "hidden" }}>
{sortedSections.map((section) =>
section.kind === "empty" ? (
- <BoardEmptySection
- key={section.id}
- section={section}
- mainRef={ref}
- />
+ <BoardEmptySection key={section.id} section={section} mainRef={ref} />
) : (
- <BoardCategorySection
- key={section.id}
- section={section}
- mainRef={ref}
- />
+ <BoardCategorySection key={section.id} section={section} mainRef={ref} />
),
)}
</Stack>
diff --git a/apps/nextjs/src/app/[locale]/boards/(content)/_context.tsx b/apps/nextjs/src/app/[locale]/boards/(content)/_context.tsx
index ae12b472f..a5ab76c03 100644
--- a/apps/nextjs/src/app/[locale]/boards/(content)/_context.tsx
+++ b/apps/nextjs/src/app/[locale]/boards/(content)/_context.tsx
@@ -1,13 +1,7 @@
"use client";
import type { PropsWithChildren } from "react";
-import {
- createContext,
- useCallback,
- useContext,
- useEffect,
- useState,
-} from "react";
+import { createContext, useCallback, useContext, useEffect, useState } from "react";
import { usePathname } from "next/navigation";
import type { RouterOutputs } from "@homarr/api";
@@ -52,18 +46,12 @@ export const BoardProvider = ({
}, [pathname, utils, initialBoard.name]);
useEffect(() => {
- setReadySections((previous) =>
- previous.filter((id) =>
- data.sections.some((section) => section.id === id),
- ),
- );
+ setReadySections((previous) => previous.filter((id) => data.sections.some((section) => section.id === id)));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [data.sections.length, setReadySections]);
const markAsReady = useCallback((id: string) => {
- setReadySections((previous) =>
- previous.includes(id) ? previous : [...previous, id],
- );
+ setReadySections((previous) => (previous.includes(id) ? previous : [...previous, id]));
}, []);
return (
diff --git a/apps/nextjs/src/app/[locale]/boards/(content)/_creator.tsx b/apps/nextjs/src/app/[locale]/boards/(content)/_creator.tsx
index 55eada4b2..fe56c11ea 100644
--- a/apps/nextjs/src/app/[locale]/boards/(content)/_creator.tsx
+++ b/apps/nextjs/src/app/[locale]/boards/(content)/_creator.tsx
@@ -18,9 +18,7 @@ interface Props<TParams extends Params> {
getInitialBoardAsync: (params: TParams) => Promise<Board>;
}
-export const createBoardContentPage = <
- TParams extends Record<string, unknown>,
->({
+export const createBoardContentPage = <TParams extends Record<string, unknown>>({
getInitialBoardAsync: getInitialBoard,
}: Props<TParams>) => {
return {
@@ -32,21 +30,13 @@ export const createBoardContentPage = <
page: () => {
return <ClientBoard />;
},
- generateMetadataAsync: async ({
- params,
- }: {
- params: TParams;
- }): Promise<Metadata> => {
+ generateMetadataAsync: async ({ params }: { params: TParams }): Promise<Metadata> => {
try {
const board = await getInitialBoard(params);
const t = await getI18n();
return {
- title:
- board.metaTitle ??
- createMetaTitle(
- t("board.content.metaTitle", { boardName: board.name }),
- ),
+ title: board.metaTitle ?? createMetaTitle(t("board.content.metaTitle", { boardName: board.name })),
icons: {
icon: board.faviconImageUrl ? board.faviconImageUrl : undefined,
},
diff --git a/apps/nextjs/src/app/[locale]/boards/(content)/_header-actions.tsx b/apps/nextjs/src/app/[locale]/boards/(content)/_header-actions.tsx
index 33abb0661..79c019dad 100644
--- a/apps/nextjs/src/app/[locale]/boards/(content)/_header-actions.tsx
+++ b/apps/nextjs/src/app/[locale]/boards/(content)/_header-actions.tsx
@@ -16,10 +16,7 @@ import { useAtom, useAtomValue } from "jotai";
import { clientApi } from "@homarr/api/client";
import { useModalAction } from "@homarr/modals";
-import {
- showErrorNotification,
- showSuccessNotification,
-} from "@homarr/notifications";
+import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import { useI18n, useScopedI18n } from "@homarr/translation/client";
import { revalidatePathActionAsync } from "~/app/revalidatePathAction";
@@ -54,8 +51,7 @@ export const BoardContentHeaderActions = () => {
};
const AddMenu = () => {
- const { openModal: openCategoryEditModal } =
- useModalAction(CategoryEditModal);
+ const { openModal: openCategoryEditModal } = useModalAction(CategoryEditModal);
const { openModal: openItemSelectModal } = useModalAction(ItemSelectModal);
const { addCategoryToEnd } = useCategoryActions();
const t = useI18n();
@@ -95,22 +91,14 @@ const AddMenu = () => {
</HeaderButton>
</Menu.Target>
<Menu.Dropdown style={{ transform: "translate(-3px, 0)" }}>
- <Menu.Item
- leftSection={<IconBox size={20} />}
- onClick={handleSelectItem}
- >
+ <Menu.Item leftSection={<IconBox size={20} />} onClick={handleSelectItem}>
{t("item.action.create")}
</Menu.Item>
- <Menu.Item leftSection={<IconPackageImport size={20} />}>
- {t("item.action.import")}
- </Menu.Item>
+ <Menu.Item leftSection={<IconPackageImport size={20} />}>{t("item.action.import")}</Menu.Item>
<Menu.Divider />
- <Menu.Item
- leftSection={<IconBoxAlignTop size={20} />}
- onClick={handleAddCategory}
- >
+ <Menu.Item leftSection={<IconBoxAlignTop size={20} />} onClick={handleAddCategory}>
{t("section.category.action.create")}
</Menu.Item>
</Menu.Dropdown>
@@ -123,24 +111,23 @@ const EditModeMenu = () => {
const board = useRequiredBoard();
const utils = clientApi.useUtils();
const t = useScopedI18n("board.action.edit");
- const { mutate: saveBoard, isPending } =
- clientApi.board.saveBoard.useMutation({
- onSuccess() {
- showSuccessNotification({
- title: t("notification.success.title"),
- message: t("notification.success.message"),
- });
- void utils.board.getBoardByName.invalidate({ name: board.name });
- void revalidatePathActionAsync(`/boards/${board.name}`);
- setEditMode(false);
- },
- onError() {
- showErrorNotification({
- title: t("notification.error.title"),
- message: t("notification.error.message"),
- });
- },
- });
+ const { mutate: saveBoard, isPending } = clientApi.board.saveBoard.useMutation({
+ onSuccess() {
+ showSuccessNotification({
+ title: t("notification.success.title"),
+ message: t("notification.success.message"),
+ });
+ void utils.board.getBoardByName.invalidate({ name: board.name });
+ void revalidatePathActionAsync(`/boards/${board.name}`);
+ setEditMode(false);
+ },
+ onError() {
+ showErrorNotification({
+ title: t("notification.error.title"),
+ message: t("notification.error.message"),
+ });
+ },
+ });
const toggle = useCallback(() => {
if (isEditMode) return saveBoard(board);
@@ -149,11 +136,7 @@ const EditModeMenu = () => {
return (
<HeaderButton onClick={toggle} loading={isPending}>
- {isEditMode ? (
- <IconPencilOff stroke={1.5} />
- ) : (
- <IconPencil stroke={1.5} />
- )}
+ {isEditMode ? <IconPencilOff stroke={1.5} /> : <IconPencil stroke={1.5} />}
</HeaderButton>
);
};
diff --git a/apps/nextjs/src/app/[locale]/boards/(content)/_theme.tsx b/apps/nextjs/src/app/[locale]/boards/(content)/_theme.tsx
index 48c8a829d..bf68bb902 100644
--- a/apps/nextjs/src/app/[locale]/boards/(content)/_theme.tsx
+++ b/apps/nextjs/src/app/[locale]/boards/(content)/_theme.tsx
@@ -22,9 +22,7 @@ export const BoardMantineProvider = ({ children }: PropsWithChildren) => {
};
export const generateColors = (hex: string) => {
- const lightnessForColors = [
- -0.25, -0.2, -0.15, -0.1, -0.05, 0, 0.05, 0.1, 0.15, 0.2,
- ] as const;
+ const lightnessForColors = [-0.25, -0.2, -0.15, -0.1, -0.05, 0, 0.05, 0.1, 0.15, 0.2] as const;
const rgbaColors = lightnessForColors.map((lightness) => {
if (lightness < 0) {
return lighten(hex, -lightness);
diff --git a/apps/nextjs/src/app/[locale]/boards/[name]/settings/_access.tsx b/apps/nextjs/src/app/[locale]/boards/[name]/settings/_access.tsx
index c90192bfa..5739e98b6 100644
--- a/apps/nextjs/src/app/[locale]/boards/[name]/settings/_access.tsx
+++ b/apps/nextjs/src/app/[locale]/boards/[name]/settings/_access.tsx
@@ -44,11 +44,7 @@ export const AccessSettingsContent = ({ board, initialPermissions }: Props) => {
<Tabs.List grow>
<TabItem value="user" count={counts.user} icon={IconUser} />
<TabItem value="group" count={counts.group} icon={IconUsersGroup} />
- <TabItem
- value="inherited"
- count={initialPermissions.inherited.length}
- icon={IconUserDown}
- />
+ <TabItem value="inherited" count={initialPermissions.inherited.length} icon={IconUserDown} />
</Tabs.List>
<Tabs.Panel value="user">
diff --git a/apps/nextjs/src/app/[locale]/boards/[name]/settings/_access/board-access-table-rows.tsx b/apps/nextjs/src/app/[locale]/boards/[name]/settings/_access/board-access-table-rows.tsx
index 392e5a36d..4a370051a 100644
--- a/apps/nextjs/src/app/[locale]/boards/[name]/settings/_access/board-access-table-rows.tsx
+++ b/apps/nextjs/src/app/[locale]/boards/[name]/settings/_access/board-access-table-rows.tsx
@@ -1,21 +1,8 @@
import { useCallback } from "react";
import type { ReactNode } from "react";
import type { SelectProps } from "@mantine/core";
-import {
- Button,
- Flex,
- Group,
- Select,
- TableTd,
- TableTr,
- Text,
-} from "@mantine/core";
-import {
- IconCheck,
- IconEye,
- IconPencil,
- IconSettings,
-} from "@tabler/icons-react";
+import { Button, Flex, Group, Select, TableTd, TableTr, Text } from "@mantine/core";
+import { IconCheck, IconEye, IconPencil, IconSettings } from "@tabler/icons-react";
import type { BoardPermission } from "@homarr/definitions";
import { boardPermissions } from "@homarr/definitions";
@@ -38,12 +25,7 @@ interface BoardAccessSelectRowProps {
onCountChange: OnCountChange;
}
-export const BoardAccessSelectRow = ({
- itemContent,
- permission,
- index,
- onCountChange,
-}: BoardAccessSelectRowProps) => {
+export const BoardAccessSelectRow = ({ itemContent, permission, index, onCountChange }: BoardAccessSelectRowProps) => {
const tRoot = useI18n();
const tPermissions = useScopedI18n("board.setting.section.access.permission");
const form = useFormContext();
@@ -61,11 +43,7 @@ export const BoardAccessSelectRow = ({
<TableTr>
<TableTd w={{ sm: 128, lg: 256 }}>{itemContent}</TableTd>
<TableTd>
- <Flex
- direction={{ base: "column", xs: "row" }}
- align={{ base: "end", xs: "center" }}
- wrap="nowrap"
- >
+ <Flex direction={{ base: "column", xs: "row" }} align={{ base: "end", xs: "center" }} wrap="nowrap">
<Select
allowDeselect={false}
flex="1"
@@ -93,10 +71,7 @@ interface BoardAccessDisplayRowProps {
permission: BoardPermission | "board-full";
}
-export const BoardAccessDisplayRow = ({
- itemContent,
- permission,
-}: BoardAccessDisplayRowProps) => {
+export const BoardAccessDisplayRow = ({ itemContent, permission }: BoardAccessDisplayRowProps) => {
const tPermissions = useScopedI18n("board.setting.section.access.permission");
const Icon = icons[permission];
@@ -106,10 +81,7 @@ export const BoardAccessDisplayRow = ({
<TableTd>
<Group gap={0}>
<Flex w={34} h={34} align="center" justify="center">
- <Icon
- size="1rem"
- color="var(--input-section-color, var(--mantine-color-dimmed))"
- />
+ <Icon size="1rem" color="var(--input-section-color, var(--mantine-color-dimmed))" />
</Flex>
<Text size="sm">{tPermissions(`item.${permission}.label`)}</Text>
</Group>
@@ -131,9 +103,7 @@ const RenderOption: SelectProps["renderOption"] = ({ option, checked }) => {
<Group flex="1" gap="xs" wrap="nowrap">
<Icon {...iconProps} />
{option.label}
- {checked && (
- <IconCheck style={{ marginInlineStart: "auto" }} {...iconProps} />
- )}
+ {checked && <IconCheck style={{ marginInlineStart: "auto" }} {...iconProps} />}
</Group>
);
};
diff --git a/apps/nextjs/src/app/[locale]/boards/[name]/settings/_access/form.ts b/apps/nextjs/src/app/[locale]/boards/[name]/settings/_access/form.ts
index 874376fc0..08520b9d5 100644
--- a/apps/nextjs/src/app/[locale]/boards/[name]/settings/_access/form.ts
+++ b/apps/nextjs/src/app/[locale]/boards/[name]/settings/_access/form.ts
@@ -8,7 +8,6 @@ export interface BoardAccessFormType {
}[];
}
-export const [FormProvider, useFormContext, useForm] =
- createFormContext<BoardAccessFormType>();
+export const [FormProvider, useFormContext, useForm] = createFormContext<BoardAccessFormType>();
export type OnCountChange = (callback: (prev: number) => number) => void;
diff --git a/apps/nextjs/src/app/[locale]/boards/[name]/settings/_access/group-access.tsx b/apps/nextjs/src/app/[locale]/boards/[name]/settings/_access/group-access.tsx
index 4ea047eca..f465b6c08 100644
--- a/apps/nextjs/src/app/[locale]/boards/[name]/settings/_access/group-access.tsx
+++ b/apps/nextjs/src/app/[locale]/boards/[name]/settings/_access/group-access.tsx
@@ -1,16 +1,6 @@
import { useCallback, useState } from "react";
import Link from "next/link";
-import {
- Anchor,
- Button,
- Group,
- Stack,
- Table,
- TableTbody,
- TableTh,
- TableThead,
- TableTr,
-} from "@mantine/core";
+import { Anchor, Button, Group, Stack, Table, TableTbody, TableTh, TableThead, TableTr } from "@mantine/core";
import { IconPlus } from "@tabler/icons-react";
import type { RouterOutputs } from "@homarr/api";
@@ -24,30 +14,21 @@ import { FormProvider, useForm } from "./form";
import { GroupSelectModal } from "./group-select-modal";
import type { FormProps } from "./user-access";
-export const GroupsForm = ({
- board,
- initialPermissions,
- onCountChange,
-}: FormProps) => {
- const { mutate, isPending } =
- clientApi.board.saveGroupBoardPermissions.useMutation();
+export const GroupsForm = ({ board, initialPermissions, onCountChange }: FormProps) => {
+ const { mutate, isPending } = clientApi.board.saveGroupBoardPermissions.useMutation();
const utils = clientApi.useUtils();
const [groups, setGroups] = useState<Map<string, Group>>(
- new Map(
- initialPermissions.groupPermissions.map(({ group }) => [group.id, group]),
- ),
+ new Map(initialPermissions.groupPermissions.map(({ group }) => [group.id, group])),
);
const { openModal } = useModalAction(GroupSelectModal);
const t = useI18n();
const tPermissions = useScopedI18n("board.setting.section.access.permission");
const form = useForm({
initialValues: {
- items: initialPermissions.groupPermissions.map(
- ({ group, permission }) => ({
- itemId: group.id,
- permission,
- }),
- ),
+ items: initialPermissions.groupPermissions.map(({ group, permission }) => ({
+ itemId: group.id,
+ permission,
+ })),
},
});
@@ -92,9 +73,7 @@ export const GroupsForm = ({
<Table>
<TableThead>
<TableTr>
- <TableTh style={{ whiteSpace: "nowrap" }}>
- {tPermissions("field.group.label")}
- </TableTh>
+ <TableTh style={{ whiteSpace: "nowrap" }}>{tPermissions("field.group.label")}</TableTh>
<TableTh>{tPermissions("field.permission.label")}</TableTh>
</TableTr>
</TableThead>
@@ -102,9 +81,7 @@ export const GroupsForm = ({
{form.values.items.map((row, index) => (
<BoardAccessSelectRow
key={row.itemId}
- itemContent={
- <GroupItemContent group={groups.get(row.itemId)!} />
- }
+ itemContent={<GroupItemContent group={groups.get(row.itemId)!} />}
permission={row.permission}
index={index}
onCountChange={onCountChange}
@@ -114,11 +91,7 @@ export const GroupsForm = ({
</Table>
<Group justify="space-between">
- <Button
- rightSection={<IconPlus size="1rem" />}
- variant="light"
- onClick={handleAddUser}
- >
+ <Button rightSection={<IconPlus size="1rem" />} variant="light" onClick={handleAddUser}>
{t("common.action.add")}
</Button>
<Button type="submit" loading={isPending} color="teal">
@@ -133,16 +106,10 @@ export const GroupsForm = ({
export const GroupItemContent = ({ group }: { group: Group }) => {
return (
- <Anchor
- component={Link}
- href={`/manage/users/groups/${group.id}`}
- size="sm"
- style={{ whiteSpace: "nowrap" }}
- >
+ <Anchor component={Link} href={`/manage/users/groups/${group.id}`} size="sm" style={{ whiteSpace: "nowrap" }}>
{group.name}
</Anchor>
);
};
-type Group =
- RouterOutputs["board"]["getBoardPermissions"]["groupPermissions"][0]["group"];
+type Group = RouterOutputs["board"]["getBoardPermissions"]["groupPermissions"][0]["group"];
diff --git a/apps/nextjs/src/app/[locale]/boards/[name]/settings/_access/group-select-modal.tsx b/apps/nextjs/src/app/[locale]/boards/[name]/settings/_access/group-select-modal.tsx
index 27a76627c..ef7ff2d5e 100644
--- a/apps/nextjs/src/app/[locale]/boards/[name]/settings/_access/group-select-modal.tsx
+++ b/apps/nextjs/src/app/[locale]/boards/[name]/settings/_access/group-select-modal.tsx
@@ -16,59 +16,52 @@ interface GroupSelectFormType {
groupId: string;
}
-export const GroupSelectModal = createModal<InnerProps>(
- ({ actions, innerProps }) => {
- const t = useI18n();
- const { data: groups, isPending } = clientApi.group.selectable.useQuery();
- const [loading, setLoading] = useState(false);
- const form = useForm<GroupSelectFormType>();
- const handleSubmitAsync = async (values: GroupSelectFormType) => {
- const currentGroup = groups?.find((group) => group.id === values.groupId);
- if (!currentGroup) return;
- setLoading(true);
- await innerProps.onSelect({
- id: currentGroup.id,
- name: currentGroup.name,
- });
+export const GroupSelectModal = createModal<InnerProps>(({ actions, innerProps }) => {
+ const t = useI18n();
+ const { data: groups, isPending } = clientApi.group.selectable.useQuery();
+ const [loading, setLoading] = useState(false);
+ const form = useForm<GroupSelectFormType>();
+ const handleSubmitAsync = async (values: GroupSelectFormType) => {
+ const currentGroup = groups?.find((group) => group.id === values.groupId);
+ if (!currentGroup) return;
+ setLoading(true);
+ await innerProps.onSelect({
+ id: currentGroup.id,
+ name: currentGroup.name,
+ });
- setLoading(false);
- actions.closeModal();
- };
+ setLoading(false);
+ actions.closeModal();
+ };
- const confirmLabel = innerProps.confirmLabel ?? t("common.action.add");
+ const confirmLabel = innerProps.confirmLabel ?? t("common.action.add");
- return (
- <form
- onSubmit={form.onSubmit((values) => void handleSubmitAsync(values))}
- >
- <Stack>
- <Select
- {...form.getInputProps("groupId")}
- label={t("group.action.select.label")}
- clearable
- searchable
- leftSection={isPending ? <Loader size="xs" /> : undefined}
- nothingFoundMessage={t("group.action.select.notFound")}
- limit={5}
- data={groups
- ?.filter(
- (group) => !innerProps.presentGroupIds.includes(group.id),
- )
- .map((group) => ({ value: group.id, label: group.name }))}
- />
- <Group justify="end">
- <Button variant="default" onClick={actions.closeModal}>
- {t("common.action.cancel")}
- </Button>
- <Button type="submit" loading={loading}>
- {confirmLabel}
- </Button>
- </Group>
- </Stack>
- </form>
- );
- },
-).withOptions({
- defaultTitle: (t) =>
- t("board.setting.section.access.permission.groupSelect.title"),
+ return (
+ <form onSubmit={form.onSubmit((values) => void handleSubmitAsync(values))}>
+ <Stack>
+ <Select
+ {...form.getInputProps("groupId")}
+ label={t("group.action.select.label")}
+ clearable
+ searchable
+ leftSection={isPending ? <Loader size="xs" /> : undefined}
+ nothingFoundMessage={t("group.action.select.notFound")}
+ limit={5}
+ data={groups
+ ?.filter((group) => !innerProps.presentGroupIds.includes(group.id))
+ .map((group) => ({ value: group.id, label: group.name }))}
+ />
+ <Group justify="end">
+ <Button variant="default" onClick={actions.closeModal}>
+ {t("common.action.cancel")}
+ </Button>
+ <Button type="submit" loading={loading}>
+ {confirmLabel}
+ </Button>
+ </Group>
+ </Stack>
+ </form>
+ );
+}).withOptions({
+ defaultTitle: (t) => t("board.setting.section.access.permission.groupSelect.title"),
});
diff --git a/apps/nextjs/src/app/[locale]/boards/[name]/settings/_access/inherit-access.tsx b/apps/nextjs/src/app/[locale]/boards/[name]/settings/_access/inherit-access.tsx
index 6cd45b821..d887ee696 100644
--- a/apps/nextjs/src/app/[locale]/boards/[name]/settings/_access/inherit-access.tsx
+++ b/apps/nextjs/src/app/[locale]/boards/[name]/settings/_access/inherit-access.tsx
@@ -1,11 +1,4 @@
-import {
- Stack,
- Table,
- TableTbody,
- TableTh,
- TableThead,
- TableTr,
-} from "@mantine/core";
+import { Stack, Table, TableTbody, TableTh, TableThead, TableTr } from "@mantine/core";
import type { RouterOutputs } from "@homarr/api";
import { getPermissionsWithChildren } from "@homarr/definitions";
@@ -41,9 +34,7 @@ export const InheritTable = ({ initialPermissions }: InheritTableProps) => {
const boardPermission =
permission in mapPermissions
? mapPermissions[permission as keyof typeof mapPermissions]
- : getPermissionsWithChildren([permission]).includes(
- "board-full-access",
- )
+ : getPermissionsWithChildren([permission]).includes("board-full-access")
? "board-full"
: null;
diff --git a/apps/nextjs/src/app/[locale]/boards/[name]/settings/_access/user-access.tsx b/apps/nextjs/src/app/[locale]/boards/[name]/settings/_access/user-access.tsx
index 6699a220b..8ed7e98ee 100644
--- a/apps/nextjs/src/app/[locale]/boards/[name]/settings/_access/user-access.tsx
+++ b/apps/nextjs/src/app/[locale]/boards/[name]/settings/_access/user-access.tsx
@@ -1,17 +1,6 @@
import { useCallback, useState } from "react";
import Link from "next/link";
-import {
- Anchor,
- Box,
- Button,
- Group,
- Stack,
- Table,
- TableTbody,
- TableTh,
- TableThead,
- TableTr,
-} from "@mantine/core";
+import { Anchor, Box, Button, Group, Stack, Table, TableTbody, TableTh, TableThead, TableTr } from "@mantine/core";
import { IconPlus } from "@tabler/icons-react";
import type { RouterOutputs } from "@homarr/api";
@@ -21,10 +10,7 @@ import { useI18n, useScopedI18n } from "@homarr/translation/client";
import { UserAvatar } from "@homarr/ui";
import type { Board } from "../../../_types";
-import {
- BoardAccessDisplayRow,
- BoardAccessSelectRow,
-} from "./board-access-table-rows";
+import { BoardAccessDisplayRow, BoardAccessSelectRow } from "./board-access-table-rows";
import type { BoardAccessFormType, OnCountChange } from "./form";
import { FormProvider, useForm } from "./form";
import { UserSelectModal } from "./user-select-modal";
@@ -35,18 +21,11 @@ export interface FormProps {
onCountChange: OnCountChange;
}
-export const UsersForm = ({
- board,
- initialPermissions,
- onCountChange,
-}: FormProps) => {
- const { mutate, isPending } =
- clientApi.board.saveUserBoardPermissions.useMutation();
+export const UsersForm = ({ board, initialPermissions, onCountChange }: FormProps) => {
+ const { mutate, isPending } = clientApi.board.saveUserBoardPermissions.useMutation();
const utils = clientApi.useUtils();
const [users, setUsers] = useState<Map<string, User>>(
- new Map(
- initialPermissions.userPermissions.map(({ user }) => [user.id, user]),
- ),
+ new Map(initialPermissions.userPermissions.map(({ user }) => [user.id, user])),
);
const { openModal } = useModalAction(UserSelectModal);
const t = useI18n();
@@ -81,9 +60,7 @@ export const UsersForm = ({
const presentUserIds = form.values.items.map(({ itemId: id }) => id);
openModal({
- presentUserIds: board.creatorId
- ? presentUserIds.concat(board.creatorId)
- : presentUserIds,
+ presentUserIds: board.creatorId ? presentUserIds.concat(board.creatorId) : presentUserIds,
onSelect: (user) => {
setUsers((prev) => new Map(prev).set(user.id, user));
form.setFieldValue("items", [
@@ -111,17 +88,12 @@ export const UsersForm = ({
</TableThead>
<TableTbody>
{board.creator && (
- <BoardAccessDisplayRow
- itemContent={<UserItemContent user={board.creator} />}
- permission="board-full"
- />
+ <BoardAccessDisplayRow itemContent={<UserItemContent user={board.creator} />} permission="board-full" />
)}
{form.values.items.map((row, index) => (
<BoardAccessSelectRow
key={row.itemId}
- itemContent={
- <UserItemContent user={users.get(row.itemId)!} />
- }
+ itemContent={<UserItemContent user={users.get(row.itemId)!} />}
permission={row.permission}
index={index}
onCountChange={onCountChange}
@@ -131,11 +103,7 @@ export const UsersForm = ({
</Table>
<Group justify="space-between">
- <Button
- rightSection={<IconPlus size="1rem" />}
- variant="light"
- onClick={handleAddUser}
- >
+ <Button rightSection={<IconPlus size="1rem" />} variant="light" onClick={handleAddUser}>
{t("common.action.add")}
</Button>
<Button type="submit" loading={isPending} color="teal">
@@ -154,12 +122,7 @@ const UserItemContent = ({ user }: { user: User }) => {
<Box visibleFrom="xs">
<UserAvatar user={user} size="sm" />
</Box>
- <Anchor
- component={Link}
- href={`/manage/users/${user.id}`}
- size="sm"
- style={{ whiteSpace: "nowrap" }}
- >
+ <Anchor component={Link} href={`/manage/users/${user.id}`} size="sm" style={{ whiteSpace: "nowrap" }}>
{user.name}
</Anchor>
</Group>
diff --git a/apps/nextjs/src/app/[locale]/boards/[name]/settings/_access/user-select-modal.tsx b/apps/nextjs/src/app/[locale]/boards/[name]/settings/_access/user-select-modal.tsx
index ae4bebfd7..d4c4946ff 100644
--- a/apps/nextjs/src/app/[locale]/boards/[name]/settings/_access/user-select-modal.tsx
+++ b/apps/nextjs/src/app/[locale]/boards/[name]/settings/_access/user-select-modal.tsx
@@ -12,11 +12,7 @@ import { UserAvatar } from "@homarr/ui";
interface InnerProps {
presentUserIds: string[];
- onSelect: (props: {
- id: string;
- name: string;
- image: string;
- }) => void | Promise<void>;
+ onSelect: (props: { id: string; name: string; image: string }) => void | Promise<void>;
confirmLabel?: string;
}
@@ -24,68 +20,59 @@ interface UserSelectFormType {
userId: string;
}
-export const UserSelectModal = createModal<InnerProps>(
- ({ actions, innerProps }) => {
- const t = useI18n();
- const { data: users, isPending } = clientApi.user.selectable.useQuery();
- const [loading, setLoading] = useState(false);
- const form = useForm<UserSelectFormType>();
- const handleSubmitAsync = async (values: UserSelectFormType) => {
- const currentUser = users?.find((user) => user.id === values.userId);
- if (!currentUser) return;
- setLoading(true);
- await innerProps.onSelect({
- id: currentUser.id,
- name: currentUser.name ?? "",
- image: currentUser.image ?? "",
- });
+export const UserSelectModal = createModal<InnerProps>(({ actions, innerProps }) => {
+ const t = useI18n();
+ const { data: users, isPending } = clientApi.user.selectable.useQuery();
+ const [loading, setLoading] = useState(false);
+ const form = useForm<UserSelectFormType>();
+ const handleSubmitAsync = async (values: UserSelectFormType) => {
+ const currentUser = users?.find((user) => user.id === values.userId);
+ if (!currentUser) return;
+ setLoading(true);
+ await innerProps.onSelect({
+ id: currentUser.id,
+ name: currentUser.name ?? "",
+ image: currentUser.image ?? "",
+ });
- setLoading(false);
- actions.closeModal();
- };
+ setLoading(false);
+ actions.closeModal();
+ };
- const confirmLabel = innerProps.confirmLabel ?? t("common.action.add");
- const currentUser = users?.find((user) => user.id === form.values.userId);
+ const confirmLabel = innerProps.confirmLabel ?? t("common.action.add");
+ const currentUser = users?.find((user) => user.id === form.values.userId);
- return (
- <form
- onSubmit={form.onSubmit((values) => void handleSubmitAsync(values))}
- >
- <Stack>
- <Select
- {...form.getInputProps("userId")}
- label={t("user.action.select.label")}
- searchable
- clearable
- leftSection={
- isPending ? (
- <Loader size="xs" />
- ) : currentUser ? (
- <UserAvatar user={currentUser} size="xs" />
- ) : undefined
- }
- nothingFoundMessage={t("user.action.select.notFound")}
- renderOption={createRenderOption(users ?? [])}
- limit={5}
- data={users
- ?.filter((user) => !innerProps.presentUserIds.includes(user.id))
- .map((user) => ({ value: user.id, label: user.name ?? "" }))}
- />
- <Group justify="end">
- <Button variant="default" onClick={actions.closeModal}>
- {t("common.action.cancel")}
- </Button>
- <Button type="submit" loading={loading}>
- {confirmLabel}
- </Button>
- </Group>
- </Stack>
- </form>
- );
- },
-).withOptions({
- defaultTitle: (t) =>
- t("board.setting.section.access.permission.userSelect.title"),
+ return (
+ <form onSubmit={form.onSubmit((values) => void handleSubmitAsync(values))}>
+ <Stack>
+ <Select
+ {...form.getInputProps("userId")}
+ label={t("user.action.select.label")}
+ searchable
+ clearable
+ leftSection={
+ isPending ? <Loader size="xs" /> : currentUser ? <UserAvatar user={currentUser} size="xs" /> : undefined
+ }
+ nothingFoundMessage={t("user.action.select.notFound")}
+ renderOption={createRenderOption(users ?? [])}
+ limit={5}
+ data={users
+ ?.filter((user) => !innerProps.presentUserIds.includes(user.id))
+ .map((user) => ({ value: user.id, label: user.name ?? "" }))}
+ />
+ <Group justify="end">
+ <Button variant="default" onClick={actions.closeModal}>
+ {t("common.action.cancel")}
+ </Button>
+ <Button type="submit" loading={loading}>
+ {confirmLabel}
+ </Button>
+ </Group>
+ </Stack>
+ </form>
+ );
+}).withOptions({
+ defaultTitle: (t) => t("board.setting.section.access.permission.userSelect.title"),
});
const iconProps = {
@@ -95,9 +82,7 @@ const iconProps = {
size: "1rem",
};
-const createRenderOption = (
- users: RouterOutputs["user"]["selectable"],
-): SelectProps["renderOption"] =>
+const createRenderOption = (users: RouterOutputs["user"]["selectable"]): SelectProps["renderOption"] =>
function InnerRenderRoot({ option, checked }) {
const user = users.find((user) => user.id === option.value);
if (!user) return null;
@@ -106,9 +91,7 @@ const createRenderOption = (
<Group flex="1" gap="xs">
<UserAvatar user={user} size="xs" />
{option.label}
- {checked && (
- <IconCheck style={{ marginInlineStart: "auto" }} {...iconProps} />
- )}
+ {checked && <IconCheck style={{ marginInlineStart: "auto" }} {...iconProps} />}
</Group>
);
};
diff --git a/apps/nextjs/src/app/[locale]/boards/[name]/settings/_background.tsx b/apps/nextjs/src/app/[locale]/boards/[name]/settings/_background.tsx
index a60f81395..9f790cf7c 100644
--- a/apps/nextjs/src/app/[locale]/boards/[name]/settings/_background.tsx
+++ b/apps/nextjs/src/app/[locale]/boards/[name]/settings/_background.tsx
@@ -2,11 +2,7 @@
import { Button, Grid, Group, Stack, TextInput } from "@mantine/core";
-import {
- backgroundImageAttachments,
- backgroundImageRepeats,
- backgroundImageSizes,
-} from "@homarr/definitions";
+import { backgroundImageAttachments, backgroundImageRepeats, backgroundImageSizes } from "@homarr/definitions";
import { useZodForm } from "@homarr/form";
import type { TranslationObject } from "@homarr/translation";
import { useI18n } from "@homarr/translation/client";
@@ -22,8 +18,7 @@ interface Props {
}
export const BackgroundSettingsContent = ({ board }: Props) => {
const t = useI18n();
- const { mutate: savePartialSettings, isPending } =
- useSavePartialSettingsMutation(board);
+ const { mutate: savePartialSettings, isPending } = useSavePartialSettingsMutation(board);
const form = useZodForm(validation.board.savePartialSettings, {
initialValues: {
backgroundImageUrl: board.backgroundImageUrl ?? "",
@@ -37,14 +32,8 @@ export const BackgroundSettingsContent = ({ board }: Props) => {
"backgroundImageAttachment",
backgroundImageAttachments,
);
- const backgroundImageSizeData = useBackgroundOptionData(
- "backgroundImageSize",
- backgroundImageSizes,
- );
- const backgroundImageRepeatData = useBackgroundOptionData(
- "backgroundImageRepeat",
- backgroundImageRepeats,
- );
+ const backgroundImageSizeData = useBackgroundOptionData("backgroundImageSize", backgroundImageSizes);
+ const backgroundImageRepeatData = useBackgroundOptionData("backgroundImageRepeat", backgroundImageRepeats);
return (
<form
@@ -96,13 +85,9 @@ export const BackgroundSettingsContent = ({ board }: Props) => {
);
};
-type BackgroundImageKey =
- | "backgroundImageAttachment"
- | "backgroundImageSize"
- | "backgroundImageRepeat";
+type BackgroundImageKey = "backgroundImageAttachment" | "backgroundImageSize" | "backgroundImageRepeat";
-type inferOptions<TKey extends BackgroundImageKey> =
- TranslationObject["board"]["field"][TKey]["option"];
+type inferOptions<TKey extends BackgroundImageKey> = TranslationObject["board"]["field"][TKey]["option"];
const useBackgroundOptionData = <
TKey extends BackgroundImageKey,
@@ -120,9 +105,7 @@ const useBackgroundOptionData = <
(value) =>
({
label: t(`board.field.${key}.option.${value as string}.label` as never),
- description: t(
- `board.field.${key}.option.${value as string}.description` as never,
- ),
+ description: t(`board.field.${key}.option.${value as string}.description` as never),
value: value as string,
badge:
data.defaultValue === value
diff --git a/apps/nextjs/src/app/[locale]/boards/[name]/settings/_colors.tsx b/apps/nextjs/src/app/[locale]/boards/[name]/settings/_colors.tsx
index f80511d06..4f12e28ad 100644
--- a/apps/nextjs/src/app/[locale]/boards/[name]/settings/_colors.tsx
+++ b/apps/nextjs/src/app/[locale]/boards/[name]/settings/_colors.tsx
@@ -44,8 +44,7 @@ export const ColorSettingsContent = ({ board }: Props) => {
const [showPreview, { toggle }] = useDisclosure(false);
const t = useI18n();
const theme = useMantineTheme();
- const { mutate: savePartialSettings, isPending } =
- useSavePartialSettingsMutation(board);
+ const { mutate: savePartialSettings, isPending } = useSavePartialSettingsMutation(board);
return (
<form
@@ -77,11 +76,7 @@ export const ColorSettingsContent = ({ board }: Props) => {
/>
</Grid.Col>
<Grid.Col span={12}>
- <Anchor onClick={toggle}>
- {showPreview
- ? t("common.preview.hide")
- : t("common.preview.show")}
- </Anchor>
+ <Anchor onClick={toggle}>{showPreview ? t("common.preview.hide") : t("common.preview.show")}</Anchor>
</Grid.Col>
<Grid.Col span={12}>
<Collapse in={showPreview}>
@@ -121,10 +116,7 @@ interface ColorsPreviewProps {
const ColorsPreview = ({ previewColor }: ColorsPreviewProps) => {
const theme = useMantineTheme();
- const colors =
- previewColor && hexRegex.test(previewColor)
- ? generateColors(previewColor)
- : generateColors("#000000");
+ const colors = previewColor && hexRegex.test(previewColor) ? generateColors(previewColor) : generateColors("#000000");
return (
<Group gap={0} wrap="nowrap">
diff --git a/apps/nextjs/src/app/[locale]/boards/[name]/settings/_danger.tsx b/apps/nextjs/src/app/[locale]/boards/[name]/settings/_danger.tsx
index a54b65e58..fa1c05bd3 100644
--- a/apps/nextjs/src/app/[locale]/boards/[name]/settings/_danger.tsx
+++ b/apps/nextjs/src/app/[locale]/boards/[name]/settings/_danger.tsx
@@ -20,8 +20,7 @@ export const DangerZoneSettingsContent = () => {
const { openModal } = useModalAction(BoardRenameModal);
const { mutate: changeVisibility, isPending: isChangeVisibilityPending } =
clientApi.board.changeBoardVisibility.useMutation();
- const { mutate: deleteBoard, isPending: isDeletePending } =
- clientApi.board.deleteBoard.useMutation();
+ const { mutate: deleteBoard, isPending: isDeletePending } = clientApi.board.deleteBoard.useMutation();
const utils = clientApi.useUtils();
const visibility = board.isPublic ? "public" : "private";
@@ -37,12 +36,8 @@ export const DangerZoneSettingsContent = () => {
const onVisibilityClick = useCallback(() => {
openConfirmModal({
- title: t(
- `section.dangerZone.action.visibility.confirm.${visibility}.title`,
- ),
- children: t(
- `section.dangerZone.action.visibility.confirm.${visibility}.description`,
- ),
+ title: t(`section.dangerZone.action.visibility.confirm.${visibility}.title`),
+ children: t(`section.dangerZone.action.visibility.confirm.${visibility}.description`),
onConfirm: () => {
changeVisibility(
{
@@ -98,12 +93,8 @@ export const DangerZoneSettingsContent = () => {
<Divider />
<DangerZoneRow
label={t("section.dangerZone.action.visibility.label")}
- description={t(
- `section.dangerZone.action.visibility.description.${visibility}`,
- )}
- buttonText={t(
- `section.dangerZone.action.visibility.button.${visibility}`,
- )}
+ description={t(`section.dangerZone.action.visibility.description.${visibility}`)}
+ buttonText={t(`section.dangerZone.action.visibility.button.${visibility}`)}
onClick={onVisibilityClick}
isPending={isChangeVisibilityPending}
/>
@@ -127,13 +118,7 @@ interface DangerZoneRowProps {
onClick: () => void;
}
-const DangerZoneRow = ({
- label,
- description,
- buttonText,
- onClick,
- isPending,
-}: DangerZoneRowProps) => {
+const DangerZoneRow = ({ label, description, buttonText, onClick, isPending }: DangerZoneRowProps) => {
return (
<Group justify="space-between" px="md" className={classes.dangerZoneGroup}>
<Stack gap={0}>
@@ -143,12 +128,7 @@ const DangerZoneRow = ({
<Text size="sm">{description}</Text>
</Stack>
<Group justify="end" w={{ base: "100%", xs: "auto" }}>
- <Button
- variant="subtle"
- color="red"
- loading={isPending}
- onClick={onClick}
- >
+ <Button variant="subtle" color="red" loading={isPending} onClick={onClick}>
{buttonText}
</Button>
</Group>
diff --git a/apps/nextjs/src/app/[locale]/boards/[name]/settings/_general.tsx b/apps/nextjs/src/app/[locale]/boards/[name]/settings/_general.tsx
index 9ecc9141b..0303be98d 100644
--- a/apps/nextjs/src/app/[locale]/boards/[name]/settings/_general.tsx
+++ b/apps/nextjs/src/app/[locale]/boards/[name]/settings/_general.tsx
@@ -1,20 +1,8 @@
"use client";
import { useEffect, useRef } from "react";
-import {
- Button,
- Grid,
- Group,
- Loader,
- Stack,
- TextInput,
- Tooltip,
-} from "@mantine/core";
-import {
- useDebouncedValue,
- useDocumentTitle,
- useFavicon,
-} from "@mantine/hooks";
+import { Button, Grid, Group, Loader, Stack, TextInput, Tooltip } from "@mantine/core";
+import { useDebouncedValue, useDocumentTitle, useFavicon } from "@mantine/hooks";
import { IconAlertTriangle } from "@tabler/icons-react";
import { useZodForm } from "@homarr/form";
@@ -38,8 +26,7 @@ export const GeneralSettingsContent = ({ board }: Props) => {
});
const { updateBoard } = useUpdateBoard();
- const { mutate: savePartialSettings, isPending } =
- useSavePartialSettingsMutation(board);
+ const { mutate: savePartialSettings, isPending } = useSavePartialSettingsMutation(board);
const form = useZodForm(
validation.board.savePartialSettings
.pick({
@@ -106,9 +93,7 @@ export const GeneralSettingsContent = ({ board }: Props) => {
<Grid.Col span={{ xs: 12, md: 6 }}>
<TextInput
label={t("board.field.metaTitle.label")}
- placeholder={createMetaTitle(
- t("board.content.metaTitle", { boardName: board.name }),
- )}
+ placeholder={createMetaTitle(t("board.content.metaTitle", { boardName: board.name }))}
rightSection={<PendingOrInvalidIndicator {...metaTitleStatus} />}
{...form.getInputProps("metaTitle")}
/>
@@ -140,22 +125,12 @@ export const GeneralSettingsContent = ({ board }: Props) => {
);
};
-const PendingOrInvalidIndicator = ({
- isPending,
- isInvalid,
-}: {
- isPending: boolean;
- isInvalid?: boolean;
-}) => {
+const PendingOrInvalidIndicator = ({ isPending, isInvalid }: { isPending: boolean; isInvalid?: boolean }) => {
const t = useI18n();
if (isInvalid) {
return (
- <Tooltip
- multiline
- w={220}
- label={t("board.setting.section.general.unrecognizedLink")}
- >
+ <Tooltip multiline w={220} label={t("board.setting.section.general.unrecognizedLink")}>
<IconAlertTriangle size="1rem" color="red" />
</Tooltip>
);
@@ -197,8 +172,7 @@ const useMetaTitlePreview = (title: string | null) => {
const validFaviconExtensions = ["ico", "png", "svg", "gif"];
const isValidUrl = (url: string) =>
- url.includes("/") &&
- validFaviconExtensions.some((extension) => url.endsWith(`.${extension}`));
+ url.includes("/") && validFaviconExtensions.some((extension) => url.endsWith(`.${extension}`));
const useFaviconPreview = (url: string | null) => {
const [faviconDebounced] = useDebouncedValue(url ?? "", 500);
diff --git a/apps/nextjs/src/app/[locale]/boards/[name]/settings/_layout.tsx b/apps/nextjs/src/app/[locale]/boards/[name]/settings/_layout.tsx
index c4ed09d4c..f0c2eeb9f 100644
--- a/apps/nextjs/src/app/[locale]/boards/[name]/settings/_layout.tsx
+++ b/apps/nextjs/src/app/[locale]/boards/[name]/settings/_layout.tsx
@@ -14,16 +14,12 @@ interface Props {
}
export const LayoutSettingsContent = ({ board }: Props) => {
const t = useI18n();
- const { mutate: savePartialSettings, isPending } =
- useSavePartialSettingsMutation(board);
- const form = useZodForm(
- validation.board.savePartialSettings.pick({ columnCount: true }).required(),
- {
- initialValues: {
- columnCount: board.columnCount,
- },
+ const { mutate: savePartialSettings, isPending } = useSavePartialSettingsMutation(board);
+ const form = useZodForm(validation.board.savePartialSettings.pick({ columnCount: true }).required(), {
+ initialValues: {
+ columnCount: board.columnCount,
},
- );
+ });
return (
<form
@@ -38,13 +34,7 @@ export const LayoutSettingsContent = ({ board }: Props) => {
<Grid>
<Grid.Col span={{ sm: 12, md: 6 }}>
<Input.Wrapper label={t("board.field.columnCount.label")}>
- <Slider
- mt="xs"
- min={1}
- max={24}
- step={1}
- {...form.getInputProps("columnCount")}
- />
+ <Slider mt="xs" min={1} max={24} step={1} {...form.getInputProps("columnCount")} />
</Input.Wrapper>
</Grid.Col>
</Grid>
diff --git a/apps/nextjs/src/app/[locale]/boards/[name]/settings/page.tsx b/apps/nextjs/src/app/[locale]/boards/[name]/settings/page.tsx
index 1f3dfeaeb..cfafacf85 100644
--- a/apps/nextjs/src/app/[locale]/boards/[name]/settings/page.tsx
+++ b/apps/nextjs/src/app/[locale]/boards/[name]/settings/page.tsx
@@ -1,14 +1,6 @@
import type { PropsWithChildren } from "react";
import { notFound } from "next/navigation";
-import {
- AccordionControl,
- AccordionItem,
- AccordionPanel,
- Container,
- Stack,
- Text,
- Title,
-} from "@mantine/core";
+import { AccordionControl, AccordionItem, AccordionPanel, Container, Stack, Text, Title } from "@mantine/core";
import {
IconAlertTriangle,
IconBrush,
@@ -69,10 +61,7 @@ const getBoardAndPermissionsAsync = async (params: Props["params"]) => {
}
};
-export default async function BoardSettingsPage({
- params,
- searchParams,
-}: Props) {
+export default async function BoardSettingsPage({ params, searchParams }: Props) {
const { board, permissions } = await getBoardAndPermissionsAsync(params);
const { hasFullAccess } = await getBoardPermissionsAsync(board);
const t = await getScopedI18n("board.setting");
@@ -81,10 +70,7 @@ export default async function BoardSettingsPage({
<Container>
<Stack>
<Title>{t("title", { boardName: capitalize(board.name) })}</Title>
- <ActiveTabAccordion
- variant="separated"
- defaultValue={searchParams.tab ?? "general"}
- >
+ <ActiveTabAccordion variant="separated" defaultValue={searchParams.tab ?? "general"}>
<AccordionItemFor value="general" icon={IconSettings}>
<GeneralSettingsContent board={board} />
</AccordionItemFor>
@@ -103,17 +89,9 @@ export default async function BoardSettingsPage({
{hasFullAccess && (
<>
<AccordionItemFor value="access" icon={IconUser}>
- <AccessSettingsContent
- board={board}
- initialPermissions={permissions}
- />
+ <AccessSettingsContent board={board} initialPermissions={permissions} />
</AccordionItemFor>
- <AccordionItemFor
- value="dangerZone"
- icon={IconAlertTriangle}
- danger
- noPadding
- >
+ <AccordionItemFor value="dangerZone" icon={IconAlertTriangle} danger noPadding>
<DangerZoneSettingsContent />
</AccordionItemFor>
</>
@@ -131,13 +109,7 @@ type AccordionItemForProps = PropsWithChildren<{
noPadding?: boolean;
}>;
-const AccordionItemFor = async ({
- value,
- children,
- icon: Icon,
- danger,
- noPadding,
-}: AccordionItemForProps) => {
+const AccordionItemFor = async ({ value, children, icon: Icon, danger, noPadding }: AccordionItemForProps) => {
const t = await getScopedI18n("board.setting.section");
return (
<AccordionItem
@@ -158,13 +130,7 @@ const AccordionItemFor = async ({
{t(`${value}.title`)}
</Text>
</AccordionControl>
- <AccordionPanel
- styles={
- noPadding
- ? { content: { paddingRight: 0, paddingLeft: 0 } }
- : undefined
- }
- >
+ <AccordionPanel styles={noPadding ? { content: { paddingRight: 0, paddingLeft: 0 } } : undefined}>
{children}
</AccordionPanel>
</AccordionItem>
diff --git a/apps/nextjs/src/app/[locale]/boards/_layout-creator.tsx b/apps/nextjs/src/app/[locale]/boards/_layout-creator.tsx
index a4559b33b..9dd31a049 100644
--- a/apps/nextjs/src/app/[locale]/boards/_layout-creator.tsx
+++ b/apps/nextjs/src/app/[locale]/boards/_layout-creator.tsx
@@ -41,10 +41,7 @@ export const createBoardLayout = <TParams extends Params>({
});
return (
- <GlobalItemServerDataRunner
- board={initialBoard}
- shouldRun={isBoardContentPage}
- >
+ <GlobalItemServerDataRunner board={initialBoard} shouldRun={isBoardContentPage}>
<BoardProvider initialBoard={initialBoard}>
<BoardMantineProvider>
<ClientShell hasNavigation={false}>
diff --git a/apps/nextjs/src/app/[locale]/boards/_types.ts b/apps/nextjs/src/app/[locale]/boards/_types.ts
index 4596bff1a..4d841d1ac 100644
--- a/apps/nextjs/src/app/[locale]/boards/_types.ts
+++ b/apps/nextjs/src/app/[locale]/boards/_types.ts
@@ -8,7 +8,4 @@ export type Item = Section["items"][number];
export type CategorySection = Extract<Section, { kind: "category" }>;
export type EmptySection = Extract<Section, { kind: "empty" }>;
-export type ItemOfKind<TKind extends WidgetKind> = Extract<
- Item,
- { kind: TKind }
->;
+export type ItemOfKind<TKind extends WidgetKind> = Extract<Item, { kind: TKind }>;
diff --git a/apps/nextjs/src/app/[locale]/compose.tsx b/apps/nextjs/src/app/[locale]/compose.tsx
index cddd9dcda..6997ca986 100644
--- a/apps/nextjs/src/app/[locale]/compose.tsx
+++ b/apps/nextjs/src/app/[locale]/compose.tsx
@@ -5,14 +5,12 @@ type PropsWithChildren = Required<React.PropsWithChildren>;
export const composeWrappers = (
wrappers: React.FunctionComponent<PropsWithChildren>[],
): React.FunctionComponent<PropsWithChildren> => {
- return wrappers
- .reverse()
- .reduce((Acc, Current): React.FunctionComponent<PropsWithChildren> => {
- // eslint-disable-next-line react/display-name
- return (props) => (
- <Current>
- <Acc {...props} />
- </Current>
- );
- });
+ return wrappers.reverse().reduce((Acc, Current): React.FunctionComponent<PropsWithChildren> => {
+ // eslint-disable-next-line react/display-name
+ return (props) => (
+ <Current>
+ <Acc {...props} />
+ </Current>
+ );
+ });
};
diff --git a/apps/nextjs/src/app/[locale]/init/user/_init-user-form.tsx b/apps/nextjs/src/app/[locale]/init/user/_init-user-form.tsx
index da373e9aa..516b3b898 100644
--- a/apps/nextjs/src/app/[locale]/init/user/_init-user-form.tsx
+++ b/apps/nextjs/src/app/[locale]/init/user/_init-user-form.tsx
@@ -5,10 +5,7 @@ import { Button, PasswordInput, Stack, TextInput } from "@mantine/core";
import { clientApi } from "@homarr/api/client";
import { useZodForm } from "@homarr/form";
-import {
- showErrorNotification,
- showSuccessNotification,
-} from "@homarr/notifications";
+import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import { useScopedI18n } from "@homarr/translation/client";
import type { z } from "@homarr/validation";
import { validation } from "@homarr/validation";
@@ -16,8 +13,7 @@ import { validation } from "@homarr/validation";
export const InitUserForm = () => {
const router = useRouter();
const t = useScopedI18n("user");
- const { mutateAsync, error, isPending } =
- clientApi.user.initUser.useMutation();
+ const { mutateAsync, error, isPending } = clientApi.user.initUser.useMutation();
const form = useZodForm(validation.user.init, {
initialValues: {
username: "",
@@ -53,18 +49,9 @@ export const InitUserForm = () => {
)}
>
<Stack gap="lg">
- <TextInput
- label={t("field.username.label")}
- {...form.getInputProps("username")}
- />
- <PasswordInput
- label={t("field.password.label")}
- {...form.getInputProps("password")}
- />
- <PasswordInput
- label={t("field.passwordConfirm.label")}
- {...form.getInputProps("confirmPassword")}
- />
+ <TextInput label={t("field.username.label")} {...form.getInputProps("username")} />
+ <PasswordInput label={t("field.password.label")} {...form.getInputProps("password")} />
+ <PasswordInput label={t("field.passwordConfirm.label")} {...form.getInputProps("confirmPassword")} />
<Button type="submit" fullWidth loading={isPending}>
{t("action.create")}
</Button>
diff --git a/apps/nextjs/src/app/[locale]/layout.tsx b/apps/nextjs/src/app/[locale]/layout.tsx
index 4a5d6c616..35414e252 100644
--- a/apps/nextjs/src/app/[locale]/layout.tsx
+++ b/apps/nextjs/src/app/[locale]/layout.tsx
@@ -48,10 +48,7 @@ export const viewport: Viewport = {
],
};
-export default function Layout(props: {
- children: React.ReactNode;
- params: { locale: string };
-}) {
+export default function Layout(props: { children: React.ReactNode; params: { locale: string } }) {
const colorScheme = "dark";
const StackedProvider = composeWrappers([
@@ -61,9 +58,7 @@ export default function Layout(props: {
},
(innerProps) => <JotaiProvider {...innerProps} />,
(innerProps) => <TRPCReactProvider {...innerProps} />,
- (innerProps) => (
- <NextInternationalProvider {...innerProps} locale={props.params.locale} />
- ),
+ (innerProps) => <NextInternationalProvider {...innerProps} locale={props.params.locale} />,
(innerProps) => (
<MantineProvider
{...innerProps}
diff --git a/apps/nextjs/src/app/[locale]/manage/_components/hero-banner.tsx b/apps/nextjs/src/app/[locale]/manage/_components/hero-banner.tsx
index be82bdf1a..35943bcf9 100644
--- a/apps/nextjs/src/app/[locale]/manage/_components/hero-banner.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/_components/hero-banner.tsx
@@ -48,13 +48,7 @@ export const HeroBanner = () => {
<Title>Homarr Dashboard</Title>
</Group>
</Stack>
- <Box
- className={classes.scrollContainer}
- w={"30%"}
- top={0}
- right={0}
- pos="absolute"
- >
+ <Box className={classes.scrollContainer} w={"30%"} top={0} right={0} pos="absolute">
<Grid>
{Array(countIconGroups)
.fill(0)
@@ -67,24 +61,12 @@ export const HeroBanner = () => {
}}
>
{arrayInChunks[columnIndex]?.map((icon, index) => (
- <Image
- key={`grid-column-${columnIndex}-scroll-1-${index}`}
- src={icon}
- radius="md"
- w={50}
- h={50}
- />
+ <Image key={`grid-column-${columnIndex}-scroll-1-${index}`} src={icon} radius="md" w={50} h={50} />
))}
{/* This is used for making the animation seem seamless */}
{arrayInChunks[columnIndex]?.map((icon, index) => (
- <Image
- key={`grid-column-${columnIndex}-scroll-2-${index}`}
- src={icon}
- radius="md"
- w={50}
- h={50}
- />
+ <Image key={`grid-column-${columnIndex}-scroll-2-${index}`} src={icon} radius="md" w={50} h={50} />
))}
</Stack>
</GridCol>
diff --git a/apps/nextjs/src/app/[locale]/manage/about/about.module.css b/apps/nextjs/src/app/[locale]/manage/about/about.module.css
index ccb8e9a98..c1d362c48 100644
--- a/apps/nextjs/src/app/[locale]/manage/about/about.module.css
+++ b/apps/nextjs/src/app/[locale]/manage/about/about.module.css
@@ -1,6 +1,3 @@
.contributorCard {
- background-color: light-dark(
- var(--mantine-color-gray-1),
- var(--mantine-color-dark-5)
- );
+ background-color: light-dark(var(--mantine-color-gray-1), var(--mantine-color-dark-5));
}
diff --git a/apps/nextjs/src/app/[locale]/manage/about/page.tsx b/apps/nextjs/src/app/[locale]/manage/about/page.tsx
index 170fa7f1e..a1dadf037 100644
--- a/apps/nextjs/src/app/[locale]/manage/about/page.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/about/page.tsx
@@ -55,9 +55,7 @@ export default async function AboutPage({ params: { locale } }: PageProps) {
<Title order={1} tt="uppercase">
Homarr
</Title>
- <Title order={2}>
- {t("version", { version: attributes.version })}
- </Title>
+ <Title order={2}>{t("version", { version: attributes.version })}</Title>
</Stack>
</Group>
</Center>
@@ -150,20 +148,10 @@ interface GenericContributorLinkCardProps {
image: string;
}
-const GenericContributorLinkCard = ({
- name,
- image,
- link,
-}: GenericContributorLinkCardProps) => {
+const GenericContributorLinkCard = ({ name, image, link }: GenericContributorLinkCardProps) => {
return (
<AspectRatio ratio={1}>
- <Card
- className={classes.contributorCard}
- component="a"
- href={link}
- target="_blank"
- w={100}
- >
+ <Card className={classes.contributorCard} component="a" href={link} target="_blank" w={100}>
<Stack align="center">
<Avatar src={image} alt={name} size={40} display="block" />
<Text lineClamp={1} size="sm">
diff --git a/apps/nextjs/src/app/[locale]/manage/apps/_app-delete-button.tsx b/apps/nextjs/src/app/[locale]/manage/apps/_app-delete-button.tsx
index 210185589..0f81cde48 100644
--- a/apps/nextjs/src/app/[locale]/manage/apps/_app-delete-button.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/apps/_app-delete-button.tsx
@@ -7,10 +7,7 @@ import { IconTrash } from "@tabler/icons-react";
import type { RouterOutputs } from "@homarr/api";
import { clientApi } from "@homarr/api/client";
import { useConfirmModal } from "@homarr/modals";
-import {
- showErrorNotification,
- showSuccessNotification,
-} from "@homarr/notifications";
+import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import { useScopedI18n } from "@homarr/translation/client";
import { revalidatePathActionAsync } from "../../../revalidatePathAction";
@@ -52,13 +49,7 @@ export const AppDeleteButton = ({ app }: AppDeleteButtonProps) => {
}, [app, mutate, t, openConfirmModal]);
return (
- <ActionIcon
- loading={isPending}
- variant="subtle"
- color="red"
- onClick={onClick}
- aria-label="Delete app"
- >
+ <ActionIcon loading={isPending} variant="subtle" color="red" onClick={onClick} aria-label="Delete app">
<IconTrash color="red" size={16} stroke={1.5} />
</ActionIcon>
);
diff --git a/apps/nextjs/src/app/[locale]/manage/apps/_form.tsx b/apps/nextjs/src/app/[locale]/manage/apps/_form.tsx
index 0b0162659..2cb6b6a47 100644
--- a/apps/nextjs/src/app/[locale]/manage/apps/_form.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/apps/_form.tsx
@@ -21,8 +21,7 @@ interface AppFormProps {
}
export const AppForm = (props: AppFormProps) => {
- const { submitButtonTranslation, handleSubmit, initialValues, isPending } =
- props;
+ const { submitButtonTranslation, handleSubmit, initialValues, isPending } = props;
const t = useI18n();
const form = useZodForm(validation.app.manage, {
@@ -38,10 +37,7 @@ export const AppForm = (props: AppFormProps) => {
<form onSubmit={form.onSubmit(handleSubmit)}>
<Stack>
<TextInput {...form.getInputProps("name")} withAsterisk label="Name" />
- <IconPicker
- initialValue={initialValues?.iconUrl}
- {...form.getInputProps("iconUrl")}
- />
+ <IconPicker initialValue={initialValues?.iconUrl} {...form.getInputProps("iconUrl")} />
<Textarea {...form.getInputProps("description")} label="Description" />
<TextInput {...form.getInputProps("href")} label="URL" />
diff --git a/apps/nextjs/src/app/[locale]/manage/apps/edit/[id]/_app-edit-form.tsx b/apps/nextjs/src/app/[locale]/manage/apps/edit/[id]/_app-edit-form.tsx
index 870411a14..5fda90040 100644
--- a/apps/nextjs/src/app/[locale]/manage/apps/edit/[id]/_app-edit-form.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/apps/edit/[id]/_app-edit-form.tsx
@@ -5,10 +5,7 @@ import { useRouter } from "next/navigation";
import type { RouterOutputs } from "@homarr/api";
import { clientApi } from "@homarr/api/client";
-import {
- showErrorNotification,
- showSuccessNotification,
-} from "@homarr/notifications";
+import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import type { TranslationFunction } from "@homarr/translation";
import { useScopedI18n } from "@homarr/translation/client";
import type { validation, z } from "@homarr/validation";
@@ -52,10 +49,7 @@ export const AppEditForm = ({ app }: AppEditFormProps) => {
[mutate, app.id],
);
- const submitButtonTranslation = useCallback(
- (t: TranslationFunction) => t("common.action.save"),
- [],
- );
+ const submitButtonTranslation = useCallback((t: TranslationFunction) => t("common.action.save"), []);
return (
<AppForm
diff --git a/apps/nextjs/src/app/[locale]/manage/apps/new/_app-new-form.tsx b/apps/nextjs/src/app/[locale]/manage/apps/new/_app-new-form.tsx
index 733a350de..171dec027 100644
--- a/apps/nextjs/src/app/[locale]/manage/apps/new/_app-new-form.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/apps/new/_app-new-form.tsx
@@ -4,10 +4,7 @@ import { useCallback } from "react";
import { useRouter } from "next/navigation";
import { clientApi } from "@homarr/api/client";
-import {
- showErrorNotification,
- showSuccessNotification,
-} from "@homarr/notifications";
+import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import type { TranslationFunction } from "@homarr/translation";
import { useScopedI18n } from "@homarr/translation/client";
import type { validation, z } from "@homarr/validation";
@@ -44,16 +41,9 @@ export const AppNewForm = () => {
[mutate],
);
- const submitButtonTranslation = useCallback(
- (t: TranslationFunction) => t("common.action.create"),
- [],
- );
+ const submitButtonTranslation = useCallback((t: TranslationFunction) => t("common.action.create"), []);
return (
- <AppForm
- submitButtonTranslation={submitButtonTranslation}
- handleSubmit={handleSubmit}
- isPending={isPending}
- />
+ <AppForm submitButtonTranslation={submitButtonTranslation} handleSubmit={handleSubmit} isPending={isPending} />
);
};
diff --git a/apps/nextjs/src/app/[locale]/manage/apps/page.tsx b/apps/nextjs/src/app/[locale]/manage/apps/page.tsx
index 2b5a6574e..6aab6ae37 100644
--- a/apps/nextjs/src/app/[locale]/manage/apps/page.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/apps/page.tsx
@@ -107,9 +107,7 @@ const AppNoResults = async () => {
<Text fw={500} size="lg">
{t("app.page.list.noResults.title")}
</Text>
- <Anchor href="/manage/apps/new">
- {t("app.page.list.noResults.description")}
- </Anchor>
+ <Anchor href="/manage/apps/new">{t("app.page.list.noResults.description")}</Anchor>
</Stack>
</Card>
);
diff --git a/apps/nextjs/src/app/[locale]/manage/boards/_components/board-card-menu-dropdown.tsx b/apps/nextjs/src/app/[locale]/manage/boards/_components/board-card-menu-dropdown.tsx
index 51709545e..0da1a442d 100644
--- a/apps/nextjs/src/app/[locale]/manage/boards/_components/board-card-menu-dropdown.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/boards/_components/board-card-menu-dropdown.tsx
@@ -21,18 +21,11 @@ const iconProps = {
interface BoardCardMenuDropdownProps {
board: Pick<
RouterOutputs["board"]["getAllBoards"][number],
- | "id"
- | "name"
- | "creator"
- | "userPermissions"
- | "groupPermissions"
- | "isPublic"
+ "id" | "name" | "creator" | "userPermissions" | "groupPermissions" | "isPublic"
>;
}
-export const BoardCardMenuDropdown = ({
- board,
-}: BoardCardMenuDropdownProps) => {
+export const BoardCardMenuDropdown = ({ board }: BoardCardMenuDropdownProps) => {
const t = useScopedI18n("management.page.board.action");
const tCommon = useScopedI18n("common");
@@ -73,10 +66,7 @@ export const BoardCardMenuDropdown = ({
return (
<Menu.Dropdown>
- <Menu.Item
- onClick={handleSetHomeBoard}
- leftSection={<IconHome {...iconProps} />}
- >
+ <Menu.Item onClick={handleSetHomeBoard} leftSection={<IconHome {...iconProps} />}>
{t("setHomeBoard.label")}
</Menu.Item>
{hasChangeAccess && (
diff --git a/apps/nextjs/src/app/[locale]/manage/boards/_components/create-board-button.tsx b/apps/nextjs/src/app/[locale]/manage/boards/_components/create-board-button.tsx
index 1c0331da6..4bd24a346 100644
--- a/apps/nextjs/src/app/[locale]/manage/boards/_components/create-board-button.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/boards/_components/create-board-button.tsx
@@ -37,11 +37,7 @@ export const CreateBoardButton = ({ boardNames }: CreateBoardButtonProps) => {
}, [mutateAsync, boardNames, openModal]);
return (
- <Button
- leftSection={<IconCategoryPlus size="1rem" />}
- onClick={onClick}
- loading={isPending}
- >
+ <Button leftSection={<IconCategoryPlus size="1rem" />} onClick={onClick} loading={isPending}>
{t("management.page.board.action.new.label")}
</Button>
);
diff --git a/apps/nextjs/src/app/[locale]/manage/boards/page.tsx b/apps/nextjs/src/app/[locale]/manage/boards/page.tsx
index b4bec8053..5dc4c79d7 100644
--- a/apps/nextjs/src/app/[locale]/manage/boards/page.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/boards/page.tsx
@@ -14,12 +14,7 @@ import {
Title,
Tooltip,
} from "@mantine/core";
-import {
- IconDotsVertical,
- IconHomeFilled,
- IconLock,
- IconWorld,
-} from "@tabler/icons-react";
+import { IconDotsVertical, IconHomeFilled, IconLock, IconWorld } from "@tabler/icons-react";
import type { RouterOutputs } from "@homarr/api";
import { api } from "@homarr/api/server";
@@ -59,8 +54,7 @@ interface BoardCardProps {
const BoardCard = async ({ board }: BoardCardProps) => {
const t = await getScopedI18n("management.page.board");
- const { hasChangeAccess: isMenuVisible } =
- await getBoardPermissionsAsync(board);
+ const { hasChangeAccess: isMenuVisible } = await getBoardPermissionsAsync(board);
const visibility = board.isPublic ? "public" : "private";
const VisibilityIcon = board.isPublic ? IconWorld : IconLock;
@@ -80,12 +74,7 @@ const BoardCard = async ({ board }: BoardCardProps) => {
<Group>
{board.isHome && (
<Tooltip label={t("action.setHomeBoard.badge.tooltip")}>
- <Badge
- tt="none"
- color="yellow"
- variant="light"
- leftSection={<IconHomeFilled size=".7rem" />}
- >
+ <Badge tt="none" color="yellow" variant="light" leftSection={<IconHomeFilled size=".7rem" />}>
{t("action.setHomeBoard.badge.label")}
</Badge>
</Tooltip>
@@ -103,12 +92,7 @@ const BoardCard = async ({ board }: BoardCardProps) => {
<CardSection p="sm">
<Group wrap="nowrap">
- <Button
- component={Link}
- href={`/boards/${board.name}`}
- variant="default"
- fullWidth
- >
+ <Button component={Link} href={`/boards/${board.name}`} variant="default" fullWidth>
{t("action.open.label")}
</Button>
{isMenuVisible && (
diff --git a/apps/nextjs/src/app/[locale]/manage/integrations/_integration-buttons.tsx b/apps/nextjs/src/app/[locale]/manage/integrations/_integration-buttons.tsx
index a2d4a7ad2..2f31cb169 100644
--- a/apps/nextjs/src/app/[locale]/manage/integrations/_integration-buttons.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/integrations/_integration-buttons.tsx
@@ -6,10 +6,7 @@ import { IconTrash } from "@tabler/icons-react";
import { clientApi } from "@homarr/api/client";
import { useConfirmModal } from "@homarr/modals";
-import {
- showErrorNotification,
- showSuccessNotification,
-} from "@homarr/notifications";
+import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import { useScopedI18n } from "@homarr/translation/client";
import { revalidatePathActionAsync } from "../../../revalidatePathAction";
@@ -19,10 +16,7 @@ interface DeleteIntegrationActionButtonProps {
integration: { id: string; name: string };
}
-export const DeleteIntegrationActionButton = ({
- count,
- integration,
-}: DeleteIntegrationActionButtonProps) => {
+export const DeleteIntegrationActionButton = ({ count, integration }: DeleteIntegrationActionButtonProps) => {
const t = useScopedI18n("integration.page.delete");
const router = useRouter();
const { openConfirmModal } = useConfirmModal();
diff --git a/apps/nextjs/src/app/[locale]/manage/integrations/_integration-secret-card.tsx b/apps/nextjs/src/app/[locale]/manage/integrations/_integration-secret-card.tsx
index 2c8b77b4f..b23fd148a 100644
--- a/apps/nextjs/src/app/[locale]/manage/integrations/_integration-secret-card.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/integrations/_integration-secret-card.tsx
@@ -2,17 +2,7 @@
import { useState } from "react";
import { useParams } from "next/navigation";
-import {
- ActionIcon,
- Avatar,
- Button,
- Card,
- Collapse,
- Group,
- Kbd,
- Stack,
- Text,
-} from "@mantine/core";
+import { ActionIcon, Avatar, Button, Card, Collapse, Group, Kbd, Stack, Text } from "@mantine/core";
import { useDisclosure } from "@mantine/hooks";
import { IconEye, IconEyeOff } from "@tabler/icons-react";
import dayjs from "dayjs";
@@ -36,8 +26,7 @@ export const SecretCard = ({ secret, children, onCancel }: SecretCardProps) => {
const params = useParams<{ locale: string }>();
const t = useI18n();
const { isPublic } = integrationSecretKindObject[secret.kind];
- const [publicSecretDisplayOpened, { toggle: togglePublicSecretDisplay }] =
- useDisclosure(false);
+ const [publicSecretDisplayOpened, { toggle: togglePublicSecretDisplay }] = useDisclosure(false);
const [editMode, setEditMode] = useState(false);
const DisplayIcon = publicSecretDisplayOpened ? IconEye : IconEyeOff;
const KindIcon = integrationSecretIcons[secret.kind];
@@ -50,9 +39,7 @@ export const SecretCard = ({ secret, children, onCancel }: SecretCardProps) => {
<Avatar>
<KindIcon size={16} />
</Avatar>
- <Text fw={500}>
- {t(`integration.secrets.kind.${secret.kind}.label`)}
- </Text>
+ <Text fw={500}>{t(`integration.secrets.kind.${secret.kind}.label`)}</Text>
{publicSecretDisplayOpened ? <Kbd>{secret.value}</Kbd> : null}
</Group>
<Group>
@@ -62,11 +49,7 @@ export const SecretCard = ({ secret, children, onCancel }: SecretCardProps) => {
})}
</Text>
{isPublic ? (
- <ActionIcon
- color="gray"
- variant="subtle"
- onClick={togglePublicSecretDisplay}
- >
+ <ActionIcon color="gray" variant="subtle" onClick={togglePublicSecretDisplay}>
<DisplayIcon size={16} stroke={1.5} />
</ActionIcon>
) : null}
diff --git a/apps/nextjs/src/app/[locale]/manage/integrations/_integration-secret-inputs.tsx b/apps/nextjs/src/app/[locale]/manage/integrations/_integration-secret-inputs.tsx
index 76fb9ae01..f73e8516b 100644
--- a/apps/nextjs/src/app/[locale]/manage/integrations/_integration-secret-inputs.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/integrations/_integration-secret-inputs.tsx
@@ -42,10 +42,7 @@ const PublicSecretInput = ({ kind, ...props }: IntegrationSecretInputProps) => {
);
};
-const PrivateSecretInput = ({
- kind,
- ...props
-}: IntegrationSecretInputProps) => {
+const PrivateSecretInput = ({ kind, ...props }: IntegrationSecretInputProps) => {
const t = useI18n();
const Icon = integrationSecretIcons[kind];
diff --git a/apps/nextjs/src/app/[locale]/manage/integrations/_integration-test-connection.tsx b/apps/nextjs/src/app/[locale]/manage/integrations/_integration-test-connection.tsx
index e3181828b..2ae512edd 100644
--- a/apps/nextjs/src/app/[locale]/manage/integrations/_integration-test-connection.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/integrations/_integration-test-connection.tsx
@@ -6,10 +6,7 @@ import { IconCheck, IconInfoCircle, IconX } from "@tabler/icons-react";
import type { RouterInputs } from "@homarr/api";
import { clientApi } from "@homarr/api/client";
-import {
- showErrorNotification,
- showSuccessNotification,
-} from "@homarr/notifications";
+import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import { useI18n, useScopedI18n } from "@homarr/translation/client";
interface UseTestConnectionDirtyProps {
@@ -20,10 +17,7 @@ interface UseTestConnectionDirtyProps {
};
}
-export const useTestConnectionDirty = ({
- defaultDirty,
- initialFormValue,
-}: UseTestConnectionDirtyProps) => {
+export const useTestConnectionDirty = ({ defaultDirty, initialFormValue }: UseTestConnectionDirtyProps) => {
const [isDirty, setIsDirty] = useState(defaultDirty);
const prevFormValueRef = useRef(initialFormValue);
@@ -36,10 +30,7 @@ export const useTestConnectionDirty = ({
prevFormValueRef.current.url !== values.url ||
!prevFormValueRef.current.secrets
.map((secret) => secret.value)
- .every(
- (secretValue, index) =>
- values.secrets[index]?.value === secretValue,
- )
+ .every((secretValue, index) => values.secrets[index]?.value === secretValue)
) {
setIsDirty(true);
return;
@@ -62,14 +53,9 @@ interface TestConnectionProps {
integration: RouterInputs["integration"]["testConnection"] & { name: string };
}
-export const TestConnection = ({
- integration,
- removeDirty,
- isDirty,
-}: TestConnectionProps) => {
+export const TestConnection = ({ integration, removeDirty, isDirty }: TestConnectionProps) => {
const t = useScopedI18n("integration.testConnection");
- const { mutateAsync, ...mutation } =
- clientApi.integration.testConnection.useMutation();
+ const { mutateAsync, ...mutation } = clientApi.integration.testConnection.useMutation();
return (
<Group>
@@ -125,13 +111,7 @@ interface TestConnectionIconProps {
size: number;
}
-const TestConnectionIcon = ({
- isDirty,
- isPending,
- isSuccess,
- isError,
- size,
-}: TestConnectionIconProps) => {
+const TestConnectionIcon = ({ isDirty, isPending, isSuccess, isError, size }: TestConnectionIconProps) => {
if (isPending) return <Loader color="blue" size={size} />;
if (isDirty) return null;
if (isSuccess) return <IconCheck size={size} stroke={1.5} color="green" />;
@@ -142,12 +122,7 @@ const TestConnectionIcon = ({
export const TestConnectionNoticeAlert = () => {
const t = useI18n();
return (
- <Alert
- variant="light"
- color="yellow"
- title="Test Connection"
- icon={<IconInfoCircle />}
- >
+ <Alert variant="light" color="yellow" title="Test Connection" icon={<IconInfoCircle />}>
{t("integration.testConnection.alertNotice")}
</Alert>
);
diff --git a/apps/nextjs/src/app/[locale]/manage/integrations/edit/[id]/_integration-edit-form.tsx b/apps/nextjs/src/app/[locale]/manage/integrations/edit/[id]/_integration-edit-form.tsx
index 7630622d9..e1521abd2 100644
--- a/apps/nextjs/src/app/[locale]/manage/integrations/edit/[id]/_integration-edit-form.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/integrations/edit/[id]/_integration-edit-form.tsx
@@ -6,16 +6,10 @@ import { Button, Fieldset, Group, Stack, TextInput } from "@mantine/core";
import type { RouterOutputs } from "@homarr/api";
import { clientApi } from "@homarr/api/client";
-import {
- getAllSecretKindOptions,
- getDefaultSecretKinds,
-} from "@homarr/definitions";
+import { getAllSecretKindOptions, getDefaultSecretKinds } from "@homarr/definitions";
import { useZodForm } from "@homarr/form";
import { useConfirmModal } from "@homarr/modals";
-import {
- showErrorNotification,
- showSuccessNotification,
-} from "@homarr/notifications";
+import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import { useI18n } from "@homarr/translation/client";
import type { z } from "@homarr/validation";
import { validation } from "@homarr/validation";
@@ -23,11 +17,7 @@ import { validation } from "@homarr/validation";
import { revalidatePathActionAsync } from "~/app/revalidatePathAction";
import { SecretCard } from "../../_integration-secret-card";
import { IntegrationSecretInput } from "../../_integration-secret-inputs";
-import {
- TestConnection,
- TestConnectionNoticeAlert,
- useTestConnectionDirty,
-} from "../../_integration-test-connection";
+import { TestConnection, TestConnectionNoticeAlert, useTestConnectionDirty } from "../../_integration-test-connection";
interface EditIntegrationForm {
integration: RouterOutputs["integration"]["byId"];
@@ -45,8 +35,7 @@ export const EditIntegrationForm = ({ integration }: EditIntegrationForm) => {
url: integration.url,
secrets: secretsKinds.map((kind) => ({
kind,
- value:
- integration.secrets.find((secret) => secret.kind === kind)?.value ?? "",
+ value: integration.secrets.find((secret) => secret.kind === kind)?.value ?? "",
})),
};
const { isDirty, onValuesChange, removeDirty } = useTestConnectionDirty({
@@ -61,9 +50,7 @@ export const EditIntegrationForm = ({ integration }: EditIntegrationForm) => {
});
const { mutateAsync, isPending } = clientApi.integration.update.useMutation();
- const secretsMap = new Map(
- integration.secrets.map((secret) => [secret.kind, secret]),
- );
+ const secretsMap = new Map(integration.secrets.map((secret) => [secret.kind, secret]));
const handleSubmitAsync = async (values: FormType) => {
if (isDirty) return;
@@ -82,9 +69,7 @@ export const EditIntegrationForm = ({ integration }: EditIntegrationForm) => {
title: t("integration.page.edit.notification.success.title"),
message: t("integration.page.edit.notification.success.message"),
});
- void revalidatePathActionAsync("/manage/integrations").then(() =>
- router.push("/manage/integrations"),
- );
+ void revalidatePathActionAsync("/manage/integrations").then(() => router.push("/manage/integrations"));
},
onError: () => {
showErrorNotification({
@@ -101,17 +86,9 @@ export const EditIntegrationForm = ({ integration }: EditIntegrationForm) => {
<Stack>
<TestConnectionNoticeAlert />
- <TextInput
- withAsterisk
- label={t("integration.field.name.label")}
- {...form.getInputProps("name")}
- />
+ <TextInput withAsterisk label={t("integration.field.name.label")} {...form.getInputProps("name")} />
- <TextInput
- withAsterisk
- label={t("integration.field.url.label")}
- {...form.getInputProps("url")}
- />
+ <TextInput withAsterisk label={t("integration.field.url.label")} {...form.getInputProps("url")} />
<Fieldset legend={t("integration.secrets.title")}>
<Stack gap="sm">
@@ -122,10 +99,7 @@ export const EditIntegrationForm = ({ integration }: EditIntegrationForm) => {
onCancel={() =>
new Promise((res) => {
// When nothing changed, just close the secret card
- if (
- (form.values.secrets[index]?.value ?? "") ===
- (secretsMap.get(kind)?.value ?? "")
- ) {
+ if ((form.values.secrets[index]?.value ?? "") === (secretsMap.get(kind)?.value ?? "")) {
return res(true);
}
openConfirmModal({
@@ -133,10 +107,7 @@ export const EditIntegrationForm = ({ integration }: EditIntegrationForm) => {
children: t("integration.secrets.reset.message"),
onCancel: () => res(false),
onConfirm: () => {
- form.setFieldValue(
- `secrets.${index}.value`,
- secretsMap.get(kind)!.value ?? "",
- );
+ form.setFieldValue(`secrets.${index}.value`, secretsMap.get(kind)!.value ?? "");
res(true);
},
});
@@ -165,11 +136,7 @@ export const EditIntegrationForm = ({ integration }: EditIntegrationForm) => {
}}
/>
<Group>
- <Button
- variant="default"
- component={Link}
- href="/manage/integrations"
- >
+ <Button variant="default" component={Link} href="/manage/integrations">
{t("common.action.backToOverview")}
</Button>
<Button type="submit" loading={isPending} disabled={isDirty}>
diff --git a/apps/nextjs/src/app/[locale]/manage/integrations/edit/[id]/page.tsx b/apps/nextjs/src/app/[locale]/manage/integrations/edit/[id]/page.tsx
index 9a2d1293a..bebf34626 100644
--- a/apps/nextjs/src/app/[locale]/manage/integrations/edit/[id]/page.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/integrations/edit/[id]/page.tsx
@@ -11,9 +11,7 @@ interface EditIntegrationPageProps {
params: { id: string };
}
-export default async function EditIntegrationPage({
- params,
-}: EditIntegrationPageProps) {
+export default async function EditIntegrationPage({ params }: EditIntegrationPageProps) {
const t = await getScopedI18n("integration.page.edit");
const integration = await api.integration.byId({ id: params.id });
@@ -22,9 +20,7 @@ export default async function EditIntegrationPage({
<Stack>
<Group align="center">
<IntegrationAvatar kind={integration.kind} size="md" />
- <Title>
- {t("title", { name: getIntegrationName(integration.kind) })}
- </Title>
+ <Title>{t("title", { name: getIntegrationName(integration.kind) })}</Title>
</Group>
<EditIntegrationForm integration={integration} />
</Stack>
diff --git a/apps/nextjs/src/app/[locale]/manage/integrations/new/_integration-new-dropdown.tsx b/apps/nextjs/src/app/[locale]/manage/integrations/new/_integration-new-dropdown.tsx
index 4d6e4d7dd..8f03a39ff 100644
--- a/apps/nextjs/src/app/[locale]/manage/integrations/new/_integration-new-dropdown.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/integrations/new/_integration-new-dropdown.tsx
@@ -16,9 +16,7 @@ export const IntegrationCreateDropdownContent = () => {
const [search, setSearch] = useState("");
const filteredKinds = useMemo(() => {
- return integrationKinds.filter((kind) =>
- kind.includes(search.toLowerCase()),
- );
+ return integrationKinds.filter((kind) => kind.includes(search.toLowerCase()));
}, [search]);
const handleSearch = React.useCallback(
@@ -38,11 +36,7 @@ export const IntegrationCreateDropdownContent = () => {
{filteredKinds.length > 0 ? (
<ScrollArea.Autosize mah={384}>
{filteredKinds.map((kind) => (
- <Menu.Item
- component={Link}
- href={`/manage/integrations/new?kind=${kind}`}
- key={kind}
- >
+ <Menu.Item component={Link} href={`/manage/integrations/new?kind=${kind}`} key={kind}>
<Group>
<IntegrationAvatar kind={kind} size="sm" />
<Text size="sm">{getIntegrationName(kind)}</Text>
diff --git a/apps/nextjs/src/app/[locale]/manage/integrations/new/_integration-new-form.tsx b/apps/nextjs/src/app/[locale]/manage/integrations/new/_integration-new-form.tsx
index 44223330f..524b2efb9 100644
--- a/apps/nextjs/src/app/[locale]/manage/integrations/new/_integration-new-form.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/integrations/new/_integration-new-form.tsx
@@ -3,37 +3,20 @@
import { useCallback } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
-import {
- Button,
- Fieldset,
- Group,
- SegmentedControl,
- Stack,
- TextInput,
-} from "@mantine/core";
+import { Button, Fieldset, Group, SegmentedControl, Stack, TextInput } from "@mantine/core";
import { clientApi } from "@homarr/api/client";
-import type {
- IntegrationKind,
- IntegrationSecretKind,
-} from "@homarr/definitions";
+import type { IntegrationKind, IntegrationSecretKind } from "@homarr/definitions";
import { getAllSecretKindOptions } from "@homarr/definitions";
import type { UseFormReturnType } from "@homarr/form";
import { useZodForm } from "@homarr/form";
-import {
- showErrorNotification,
- showSuccessNotification,
-} from "@homarr/notifications";
+import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import { useI18n, useScopedI18n } from "@homarr/translation/client";
import type { z } from "@homarr/validation";
import { validation } from "@homarr/validation";
import { IntegrationSecretInput } from "../_integration-secret-inputs";
-import {
- TestConnection,
- TestConnectionNoticeAlert,
- useTestConnectionDirty,
-} from "../_integration-test-connection";
+import { TestConnection, TestConnectionNoticeAlert, useTestConnectionDirty } from "../_integration-test-connection";
import { revalidatePathActionAsync } from "../../../../revalidatePathAction";
interface NewIntegrationFormProps {
@@ -42,9 +25,7 @@ interface NewIntegrationFormProps {
};
}
-export const NewIntegrationForm = ({
- searchParams,
-}: NewIntegrationFormProps) => {
+export const NewIntegrationForm = ({ searchParams }: NewIntegrationFormProps) => {
const t = useI18n();
const secretKinds = getAllSecretKindOptions(searchParams.kind);
const initialFormValues = {
@@ -79,9 +60,7 @@ export const NewIntegrationForm = ({
title: t("integration.page.create.notification.success.title"),
message: t("integration.page.create.notification.success.message"),
});
- void revalidatePathActionAsync("/manage/integrations").then(() =>
- router.push("/manage/integrations"),
- );
+ void revalidatePathActionAsync("/manage/integrations").then(() => router.push("/manage/integrations"));
},
onError: () => {
showErrorNotification({
@@ -98,26 +77,13 @@ export const NewIntegrationForm = ({
<Stack>
<TestConnectionNoticeAlert />
- <TextInput
- withAsterisk
- label={t("integration.field.name.label")}
- {...form.getInputProps("name")}
- />
+ <TextInput withAsterisk label={t("integration.field.name.label")} {...form.getInputProps("name")} />
- <TextInput
- withAsterisk
- label={t("integration.field.url.label")}
- {...form.getInputProps("url")}
- />
+ <TextInput withAsterisk label={t("integration.field.url.label")} {...form.getInputProps("url")} />
<Fieldset legend={t("integration.secrets.title")}>
<Stack gap="sm">
- {secretKinds.length > 1 && (
- <SecretKindsSegmentedControl
- secretKinds={secretKinds}
- form={form}
- />
- )}
+ {secretKinds.length > 1 && <SecretKindsSegmentedControl secretKinds={secretKinds} form={form} />}
{form.values.secrets.map(({ kind }, index) => (
<IntegrationSecretInput
withAsterisk
@@ -141,11 +107,7 @@ export const NewIntegrationForm = ({
/>
<Group>
- <Button
- variant="default"
- component={Link}
- href="/manage/integrations"
- >
+ <Button variant="default" component={Link} href="/manage/integrations">
{t("common.action.backToOverview")}
</Button>
<Button type="submit" loading={isPending} disabled={isDirty}>
@@ -163,10 +125,7 @@ interface SecretKindsSegmentedControlProps {
form: UseFormReturnType<FormType, (values: FormType) => FormType>;
}
-const SecretKindsSegmentedControl = ({
- secretKinds,
- form,
-}: SecretKindsSegmentedControlProps) => {
+const SecretKindsSegmentedControl = ({ secretKinds, form }: SecretKindsSegmentedControlProps) => {
const t = useScopedI18n("integration.secrets");
const secretKindGroups = secretKinds.map((kinds) => ({
@@ -186,13 +145,7 @@ const SecretKindsSegmentedControl = ({
[form],
);
- return (
- <SegmentedControl
- fullWidth
- data={secretKindGroups}
- onChange={onChange}
- ></SegmentedControl>
- );
+ return <SegmentedControl fullWidth data={secretKindGroups} onChange={onChange}></SegmentedControl>;
};
type FormType = Omit<z.infer<typeof validation.integration.create>, "kind">;
diff --git a/apps/nextjs/src/app/[locale]/manage/integrations/new/page.tsx b/apps/nextjs/src/app/[locale]/manage/integrations/new/page.tsx
index 83f2e11bb..23eb474f5 100644
--- a/apps/nextjs/src/app/[locale]/manage/integrations/new/page.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/integrations/new/page.tsx
@@ -16,12 +16,8 @@ interface NewIntegrationPageProps {
};
}
-export default async function IntegrationsNewPage({
- searchParams,
-}: NewIntegrationPageProps) {
- const result = z
- .enum([integrationKinds[0]!, ...integrationKinds.slice(1)])
- .safeParse(searchParams.kind);
+export default async function IntegrationsNewPage({ searchParams }: NewIntegrationPageProps) {
+ const result = z.enum([integrationKinds[0]!, ...integrationKinds.slice(1)]).safeParse(searchParams.kind);
if (!result.success) {
notFound();
}
diff --git a/apps/nextjs/src/app/[locale]/manage/integrations/page.tsx b/apps/nextjs/src/app/[locale]/manage/integrations/page.tsx
index 032e72e9b..07b4c894d 100644
--- a/apps/nextjs/src/app/[locale]/manage/integrations/page.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/integrations/page.tsx
@@ -43,9 +43,7 @@ interface IntegrationsPageProps {
};
}
-export default async function IntegrationsPage({
- searchParams,
-}: IntegrationsPageProps) {
+export default async function IntegrationsPage({ searchParams }: IntegrationsPageProps) {
const integrations = await api.integration.all();
const t = await getScopedI18n("integration");
@@ -54,18 +52,9 @@ export default async function IntegrationsPage({
<Stack>
<Group justify="space-between" align="center">
<Title>{t("page.list.title")}</Title>
- <Menu
- width={256}
- trapFocus
- position="bottom-start"
- withinPortal
- shadow="md"
- keepMounted={false}
- >
+ <Menu width={256} trapFocus position="bottom-start" withinPortal shadow="md" keepMounted={false}>
<MenuTarget>
- <Button rightSection={<IconChevronDown size={16} stroke={1.5} />}>
- {t("action.create")}
- </Button>
+ <Button rightSection={<IconChevronDown size={16} stroke={1.5} />}>{t("action.create")}</Button>
</MenuTarget>
<MenuDropdown>
<IntegrationCreateDropdownContent />
@@ -73,10 +62,7 @@ export default async function IntegrationsPage({
</Menu>
</Group>
- <IntegrationList
- integrations={integrations}
- activeTab={searchParams.tab}
- />
+ <IntegrationList integrations={integrations} activeTab={searchParams.tab} />
</Stack>
</Container>
);
@@ -87,10 +73,7 @@ interface IntegrationListProps {
activeTab?: IntegrationKind;
}
-const IntegrationList = async ({
- integrations,
- activeTab,
-}: IntegrationListProps) => {
+const IntegrationList = async ({ integrations, activeTab }: IntegrationListProps) => {
const t = await getScopedI18n("integration");
if (integrations.length === 0) {
@@ -134,12 +117,7 @@ const IntegrationList = async ({
<TableTr key={integration.id}>
<TableTd>{integration.name}</TableTd>
<TableTd>
- <Anchor
- href={integration.url}
- target="_blank"
- rel="noreferrer"
- size="sm"
- >
+ <Anchor href={integration.url} target="_blank" rel="noreferrer" size="sm">
{integration.url}
</Anchor>
</TableTd>
@@ -155,10 +133,7 @@ const IntegrationList = async ({
>
<IconPencil size={16} stroke={1.5} />
</ActionIcon>
- <DeleteIntegrationActionButton
- integration={integration}
- count={integrations.length}
- />
+ <DeleteIntegrationActionButton integration={integration} count={integrations.length} />
</ActionIconGroup>
</Group>
</TableTd>
diff --git a/apps/nextjs/src/app/[locale]/manage/page.tsx b/apps/nextjs/src/app/[locale]/manage/page.tsx
index d16a8184b..711a2e3a3 100644
--- a/apps/nextjs/src/app/[locale]/manage/page.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/page.tsx
@@ -71,12 +71,7 @@ export default async function ManagementPage() {
<Space h="md" />
<SimpleGrid cols={{ xs: 1, sm: 2, md: 3 }}>
{links.map((link, index) => (
- <Card
- component={Link}
- href={link.href}
- key={`link-${index}`}
- withBorder
- >
+ <Card component={Link} href={link.href} key={`link-${index}`} withBorder>
<Group justify="space-between">
<Group>
<Text size="2.4rem" fw="bolder">
diff --git a/apps/nextjs/src/app/[locale]/manage/settings/_components/analytics.settings.tsx b/apps/nextjs/src/app/[locale]/manage/settings/_components/analytics.settings.tsx
index e3244c153..dfe86b363 100644
--- a/apps/nextjs/src/app/[locale]/manage/settings/_components/analytics.settings.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/settings/_components/analytics.settings.tsx
@@ -3,16 +3,7 @@
import type { ReactNode } from "react";
import React from "react";
import type { MantineSpacing } from "@mantine/core";
-import {
- Card,
- Group,
- LoadingOverlay,
- Stack,
- Switch,
- Text,
- Title,
- UnstyledButton,
-} from "@mantine/core";
+import { Card, Group, LoadingOverlay, Stack, Switch, Text, Title, UnstyledButton } from "@mantine/core";
import { clientApi } from "@homarr/api/client";
import type { UseFormReturnType } from "@homarr/form";
@@ -37,9 +28,7 @@ export const AnalyticsSettings = ({ initialData }: AnalyticsSettingsProps) => {
if (
!updatedValues.enableGeneral &&
- (updatedValues.enableWidgetData ||
- updatedValues.enableIntegrationData ||
- updatedValues.enableUserData)
+ (updatedValues.enableWidgetData || updatedValues.enableIntegrationData || updatedValues.enableUserData)
) {
updatedValues.enableIntegrationData = false;
updatedValues.enableUserData = false;
@@ -53,30 +42,20 @@ export const AnalyticsSettings = ({ initialData }: AnalyticsSettingsProps) => {
},
});
- const { mutateAsync, isPending } =
- clientApi.serverSettings.saveSettings.useMutation({
- onSettled: async () => {
- await revalidatePathActionAsync("/manage/settings");
- },
- });
+ const { mutateAsync, isPending } = clientApi.serverSettings.saveSettings.useMutation({
+ onSettled: async () => {
+ await revalidatePathActionAsync("/manage/settings");
+ },
+ });
return (
<>
<Title order={2}>{t("title")}</Title>
<Card pos="relative" withBorder>
- <LoadingOverlay
- visible={isPending}
- zIndex={1000}
- overlayProps={{ radius: "sm", blur: 2 }}
- />
+ <LoadingOverlay visible={isPending} zIndex={1000} overlayProps={{ radius: "sm", blur: 2 }} />
<Stack>
- <SwitchSetting
- form={form}
- formKey="enableGeneral"
- title={t("general.title")}
- text={t("general.text")}
- />
+ <SwitchSetting form={form} formKey="enableGeneral" title={t("general.title")} text={t("general.text")} />
<SwitchSetting
form={form}
formKey="enableIntegrationData"
@@ -122,13 +101,7 @@ const SwitchSetting = ({
}, [form, formKey]);
return (
<UnstyledButton onClick={handleClick}>
- <Group
- ms={ms}
- justify="space-between"
- gap="lg"
- align="center"
- wrap="nowrap"
- >
+ <Group ms={ms} justify="space-between" gap="lg" align="center" wrap="nowrap">
<Stack gap={0}>
<Text fw="bold">{title}</Text>
<Text c="gray.5">{text}</Text>
diff --git a/apps/nextjs/src/app/[locale]/manage/tools/logs/page.tsx b/apps/nextjs/src/app/[locale]/manage/tools/logs/page.tsx
index d6cf53924..4b6373764 100644
--- a/apps/nextjs/src/app/[locale]/manage/tools/logs/page.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/tools/logs/page.tsx
@@ -23,12 +23,7 @@ const ClientSideTerminalComponent = dynamic(() => import("./terminal"), {
export default function LogsManagementPage() {
return (
- <Box
- style={{ borderRadius: 6 }}
- h={fullHeightWithoutHeaderAndFooter}
- p="md"
- bg="black"
- >
+ <Box style={{ borderRadius: 6 }} h={fullHeightWithoutHeaderAndFooter} p="md" bg="black">
<ClientSideTerminalComponent />
</Box>
);
diff --git a/apps/nextjs/src/app/[locale]/manage/tools/logs/terminal.tsx b/apps/nextjs/src/app/[locale]/manage/tools/logs/terminal.tsx
index 43b105156..428f1f300 100644
--- a/apps/nextjs/src/app/[locale]/manage/tools/logs/terminal.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/tools/logs/terminal.tsx
@@ -16,9 +16,7 @@ export default function TerminalComponent() {
const terminalRef = useRef<Terminal>();
clientApi.log.subscribe.useSubscription(undefined, {
onData(data) {
- terminalRef.current?.writeln(
- `${data.timestamp} ${data.level} ${data.message}`,
- );
+ terminalRef.current?.writeln(`${data.timestamp} ${data.level} ${data.message}`);
terminalRef.current?.refresh(0, terminalRef.current.rows - 1);
},
onError(err) {
@@ -55,12 +53,5 @@ export default function TerminalComponent() {
canvasAddon.dispose();
};
}, []);
- return (
- <Box
- ref={ref}
- id="terminal"
- className={classes.outerTerminal}
- h="100%"
- ></Box>
- );
+ return <Box ref={ref} id="terminal" className={classes.outerTerminal} h="100%"></Box>;
}
diff --git a/apps/nextjs/src/app/[locale]/manage/users/[userId]/access.ts b/apps/nextjs/src/app/[locale]/manage/users/[userId]/access.ts
index c5ed1ac30..8e5664911 100644
--- a/apps/nextjs/src/app/[locale]/manage/users/[userId]/access.ts
+++ b/apps/nextjs/src/app/[locale]/manage/users/[userId]/access.ts
@@ -1,9 +1,6 @@
import type { Session } from "@homarr/auth";
-export const canAccessUserEditPage = (
- session: Session | null,
- userId: string,
-) => {
+export const canAccessUserEditPage = (session: Session | null, userId: string) => {
if (!session) {
return false;
}
diff --git a/apps/nextjs/src/app/[locale]/manage/users/[userId]/general/_components/_delete-user-button.tsx b/apps/nextjs/src/app/[locale]/manage/users/[userId]/general/_components/_delete-user-button.tsx
index 9f501d5c7..c23202e79 100644
--- a/apps/nextjs/src/app/[locale]/manage/users/[userId]/general/_components/_delete-user-button.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/users/[userId]/general/_components/_delete-user-button.tsx
@@ -18,14 +18,11 @@ interface DeleteUserButtonProps {
export const DeleteUserButton = ({ user }: DeleteUserButtonProps) => {
const t = useI18n();
const router = useRouter();
- const { mutateAsync: mutateUserDeletionAsync } =
- clientApi.user.delete.useMutation({
- async onSuccess() {
- await revalidatePathActionAsync("/manage/users").then(() =>
- router.push("/manage/users"),
- );
- },
- });
+ const { mutateAsync: mutateUserDeletionAsync } = clientApi.user.delete.useMutation({
+ async onSuccess() {
+ await revalidatePathActionAsync("/manage/users").then(() => router.push("/manage/users"));
+ },
+ });
const { openConfirmModal } = useConfirmModal();
const handleDelete = useCallback(
diff --git a/apps/nextjs/src/app/[locale]/manage/users/[userId]/general/_components/_profile-avatar-form.tsx b/apps/nextjs/src/app/[locale]/manage/users/[userId]/general/_components/_profile-avatar-form.tsx
index df7f974b0..0e819d163 100644
--- a/apps/nextjs/src/app/[locale]/manage/users/[userId]/general/_components/_profile-avatar-form.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/users/[userId]/general/_components/_profile-avatar-form.tsx
@@ -8,10 +8,7 @@ import { IconPencil, IconPhotoEdit, IconPhotoX } from "@tabler/icons-react";
import type { RouterOutputs } from "@homarr/api";
import { clientApi } from "@homarr/api/client";
import { useConfirmModal } from "@homarr/modals";
-import {
- showErrorNotification,
- showSuccessNotification,
-} from "@homarr/notifications";
+import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import { useI18n, useScopedI18n } from "@homarr/translation/client";
import { UserAvatar } from "@homarr/ui";
@@ -46,25 +43,18 @@ export const UserProfileAvatarForm = ({ user }: UserProfileAvatarForm) => {
// Revalidate all as the avatar is used in multiple places
await revalidatePathActionAsync("/");
showSuccessNotification({
- message: tManageAvatar(
- "changeImage.notification.success.message",
- ),
+ message: tManageAvatar("changeImage.notification.success.message"),
});
},
onError(error) {
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: "256KB" }),
});
} else {
showErrorNotification({
- message: tManageAvatar(
- "changeImage.notification.error.message",
- ),
+ message: tManageAvatar("changeImage.notification.error.message"),
});
}
},
@@ -89,16 +79,12 @@ export const UserProfileAvatarForm = ({ user }: UserProfileAvatarForm) => {
// Revalidate all as the avatar is used in multiple places
await revalidatePathActionAsync("/");
showSuccessNotification({
- message: tManageAvatar(
- "removeImage.notification.success.message",
- ),
+ message: tManageAvatar("removeImage.notification.success.message"),
});
},
onError() {
showErrorNotification({
- message: tManageAvatar(
- "removeImage.notification.error.message",
- ),
+ message: tManageAvatar("removeImage.notification.error.message"),
});
},
},
@@ -109,13 +95,7 @@ export const UserProfileAvatarForm = ({ user }: UserProfileAvatarForm) => {
return (
<Box pos="relative">
- <Menu
- opened={opened}
- keepMounted
- onChange={toggle}
- position="bottom-start"
- withArrow
- >
+ <Menu opened={opened} keepMounted onChange={toggle} position="bottom-start" withArrow>
<Menu.Target>
<UnstyledButton onClick={toggle}>
<UserAvatar user={user} size={200} />
@@ -134,24 +114,15 @@ export const UserProfileAvatarForm = ({ user }: UserProfileAvatarForm) => {
</UnstyledButton>
</Menu.Target>
<Menu.Dropdown>
- <FileButton
- onChange={handleAvatarChange}
- accept="image/png,image/jpeg,image/webp,image/gif"
- >
+ <FileButton onChange={handleAvatarChange} accept="image/png,image/jpeg,image/webp,image/gif">
{(props) => (
- <Menu.Item
- {...props}
- leftSection={<IconPhotoEdit size={16} stroke={1.5} />}
- >
+ <Menu.Item {...props} leftSection={<IconPhotoEdit size={16} stroke={1.5} />}>
{tManageAvatar("changeImage.label")}
</Menu.Item>
)}
</FileButton>
{user.image && (
- <Menu.Item
- onClick={handleRemoveAvatar}
- leftSection={<IconPhotoX size={16} stroke={1.5} />}
- >
+ <Menu.Item onClick={handleRemoveAvatar} leftSection={<IconPhotoX size={16} stroke={1.5} />}>
{tManageAvatar("removeImage.label")}
</Menu.Item>
)}
diff --git a/apps/nextjs/src/app/[locale]/manage/users/[userId]/general/_components/_profile-form.tsx b/apps/nextjs/src/app/[locale]/manage/users/[userId]/general/_components/_profile-form.tsx
index c94f0a67e..54f45526b 100644
--- a/apps/nextjs/src/app/[locale]/manage/users/[userId]/general/_components/_profile-form.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/users/[userId]/general/_components/_profile-form.tsx
@@ -6,10 +6,7 @@ import { Button, Group, Stack, TextInput } from "@mantine/core";
import type { RouterInputs, RouterOutputs } from "@homarr/api";
import { clientApi } from "@homarr/api/client";
import { useZodForm } from "@homarr/form";
-import {
- showErrorNotification,
- showSuccessNotification,
-} from "@homarr/notifications";
+import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import { useI18n } from "@homarr/translation/client";
import { validation } from "@homarr/validation";
@@ -58,15 +55,8 @@ export const UserProfileForm = ({ user }: UserProfileFormProps) => {
return (
<form onSubmit={form.onSubmit(handleSubmit)}>
<Stack>
- <TextInput
- label={t("user.field.username.label")}
- withAsterisk
- {...form.getInputProps("name")}
- />
- <TextInput
- label={t("user.field.email.label")}
- {...form.getInputProps("email")}
- />
+ <TextInput label={t("user.field.username.label")} withAsterisk {...form.getInputProps("name")} />
+ <TextInput label={t("user.field.email.label")} {...form.getInputProps("email")} />
<Group justify="end">
<Button type="submit" color="teal" loading={isPending}>
diff --git a/apps/nextjs/src/app/[locale]/manage/users/[userId]/general/page.tsx b/apps/nextjs/src/app/[locale]/manage/users/[userId]/general/page.tsx
index 9b964dd45..82d3a6f89 100644
--- a/apps/nextjs/src/app/[locale]/manage/users/[userId]/general/page.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/users/[userId]/general/page.tsx
@@ -5,10 +5,7 @@ import { api } from "@homarr/api/server";
import { auth } from "@homarr/auth/next";
import { getI18n, getScopedI18n } from "@homarr/translation/server";
-import {
- DangerZoneItem,
- DangerZoneRoot,
-} from "~/components/manage/danger-zone";
+import { DangerZoneItem, DangerZoneRoot } from "~/components/manage/danger-zone";
import { catchTrpcNotFound } from "~/errors/trpc-not-found";
import { createMetaTitle } from "~/metadata";
import { canAccessUserEditPage } from "../access";
diff --git a/apps/nextjs/src/app/[locale]/manage/users/[userId]/layout.tsx b/apps/nextjs/src/app/[locale]/manage/users/[userId]/layout.tsx
index ae0a58692..be6c0f71a 100644
--- a/apps/nextjs/src/app/[locale]/manage/users/[userId]/layout.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/users/[userId]/layout.tsx
@@ -1,16 +1,7 @@
import type { PropsWithChildren } from "react";
import Link from "next/link";
import { notFound } from "next/navigation";
-import {
- Button,
- Container,
- Grid,
- GridCol,
- Group,
- Stack,
- Text,
- Title,
-} from "@mantine/core";
+import { Button, Container, Grid, GridCol, Group, Stack, Text, Title } from "@mantine/core";
import { IconSettings, IconShieldLock } from "@tabler/icons-react";
import { api } from "@homarr/api/server";
@@ -26,16 +17,11 @@ interface LayoutProps {
params: { userId: string };
}
-export default async function Layout({
- children,
- params,
-}: PropsWithChildren<LayoutProps>) {
+export default async function Layout({ children, params }: PropsWithChildren<LayoutProps>) {
const session = await auth();
const t = await getI18n();
const tUser = await getScopedI18n("management.page.user");
- const user = await api.user
- .getById({ userId: params.userId })
- .catch(catchTrpcNotFound);
+ const user = await api.user.getById({ userId: params.userId }).catch(catchTrpcNotFound);
if (!canAccessUserEditPage(session, user.id)) {
notFound();
@@ -54,12 +40,7 @@ export default async function Layout({
</Stack>
</Group>
{session?.user.permissions.includes("admin") && (
- <Button
- component={Link}
- href="/manage/users"
- color="gray"
- variant="light"
- >
+ <Button component={Link} href="/manage/users" color="gray" variant="light">
{tUser("back")}
</Button>
)}
diff --git a/apps/nextjs/src/app/[locale]/manage/users/[userId]/security/_components/_change-password-form.tsx b/apps/nextjs/src/app/[locale]/manage/users/[userId]/security/_components/_change-password-form.tsx
index 4d26599d6..199e225cf 100644
--- a/apps/nextjs/src/app/[locale]/manage/users/[userId]/security/_components/_change-password-form.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/users/[userId]/security/_components/_change-password-form.tsx
@@ -6,10 +6,7 @@ import type { RouterInputs, RouterOutputs } from "@homarr/api";
import { clientApi } from "@homarr/api/client";
import { useSession } from "@homarr/auth/client";
import { useZodForm } from "@homarr/form";
-import {
- showErrorNotification,
- showSuccessNotification,
-} from "@homarr/notifications";
+import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import { useI18n } from "@homarr/translation/client";
import { validation } from "@homarr/validation";
@@ -74,11 +71,7 @@ export const ChangePasswordForm = ({ user }: ChangePasswordFormProps) => {
/>
)}
- <PasswordInput
- withAsterisk
- label={t("user.field.password.label")}
- {...form.getInputProps("password")}
- />
+ <PasswordInput withAsterisk label={t("user.field.password.label")} {...form.getInputProps("password")} />
<PasswordInput
withAsterisk
diff --git a/apps/nextjs/src/app/[locale]/manage/users/[userId]/security/page.tsx b/apps/nextjs/src/app/[locale]/manage/users/[userId]/security/page.tsx
index f111714a8..0145520de 100644
--- a/apps/nextjs/src/app/[locale]/manage/users/[userId]/security/page.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/users/[userId]/security/page.tsx
@@ -17,9 +17,7 @@ interface Props {
export default async function UserSecurityPage({ params }: Props) {
const session = await auth();
- const tSecurity = await getScopedI18n(
- "management.page.user.setting.security",
- );
+ const tSecurity = await getScopedI18n("management.page.user.setting.security");
const user = await api.user
.getById({
userId: params.userId,
diff --git a/apps/nextjs/src/app/[locale]/manage/users/_components/user-list.component.tsx b/apps/nextjs/src/app/[locale]/manage/users/_components/user-list.component.tsx
index 299c669f1..8759f5d8d 100644
--- a/apps/nextjs/src/app/[locale]/manage/users/_components/user-list.component.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/users/_components/user-list.component.tsx
@@ -15,18 +15,14 @@ interface UserListComponentProps {
initialUserList: RouterOutputs["user"]["getAll"];
}
-export const UserListComponent = ({
- initialUserList,
-}: UserListComponentProps) => {
+export const UserListComponent = ({ initialUserList }: UserListComponentProps) => {
const tUserList = useScopedI18n("management.page.user.list");
const t = useI18n();
const { data, isLoading } = clientApi.user.getAll.useQuery(undefined, {
initialData: initialUserList,
});
- const columns = useMemo<
- MRT_ColumnDef<RouterOutputs["user"]["getAll"][number]>[]
- >(
+ const columns = useMemo<MRT_ColumnDef<RouterOutputs["user"]["getAll"][number]>[]>(
() => [
{
accessorKey: "name",
diff --git a/apps/nextjs/src/app/[locale]/manage/users/create/_components/create-user-stepper.tsx b/apps/nextjs/src/app/[locale]/manage/users/create/_components/create-user-stepper.tsx
index b2f711030..5a27d206c 100644
--- a/apps/nextjs/src/app/[locale]/manage/users/create/_components/create-user-stepper.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/users/create/_components/create-user-stepper.tsx
@@ -1,16 +1,7 @@
"use client";
import { useCallback, useMemo, useState } from "react";
-import {
- Avatar,
- Card,
- PasswordInput,
- Stack,
- Stepper,
- Text,
- TextInput,
- Title,
-} from "@mantine/core";
+import { Avatar, Card, PasswordInput, Stack, Stepper, Text, TextInput, Title } from "@mantine/core";
import { IconUserCheck } from "@tabler/icons-react";
import { clientApi } from "@homarr/api/client";
@@ -28,14 +19,10 @@ export const UserCreateStepperComponent = () => {
const stepperMax = 4;
const [active, setActive] = useState(0);
const nextStep = useCallback(
- () =>
- setActive((current) => (current < stepperMax ? current + 1 : current)),
- [setActive],
- );
- const prevStep = useCallback(
- () => setActive((current) => (current > 0 ? current - 1 : current)),
+ () => setActive((current) => (current < stepperMax ? current + 1 : current)),
[setActive],
);
+ const prevStep = useCallback(() => setActive((current) => (current > 0 ? current - 1 : current)), [setActive]);
const hasNext = active < stepperMax;
const hasPrevious = active > 0;
@@ -72,14 +59,9 @@ export const UserCreateStepperComponent = () => {
},
);
- const allForms = useMemo(
- () => [generalForm, securityForm],
- [generalForm, securityForm],
- );
+ const allForms = useMemo(() => [generalForm, securityForm], [generalForm, securityForm]);
- const isCurrentFormValid = allForms[active]
- ? (allForms[active]!.isValid satisfies () => boolean)
- : () => true;
+ const isCurrentFormValid = allForms[active] ? (allForms[active]!.isValid satisfies () => boolean) : () => true;
const canNavigateToNextStep = isCurrentFormValid();
const controlledGoToNextStep = useCallback(async () => {
@@ -104,12 +86,7 @@ export const UserCreateStepperComponent = () => {
return (
<>
<Title mb="md">{t("title")}</Title>
- <Stepper
- active={active}
- onStepClick={setActive}
- allowNextStepsSelect={false}
- mb="md"
- >
+ <Stepper active={active} onStepClick={setActive} allowNextStepsSelect={false} mb="md">
<Stepper.Step
label={t("step.personalInformation.label")}
allowStepSelect={false}
@@ -126,20 +103,12 @@ export const UserCreateStepperComponent = () => {
{...generalForm.getInputProps("username")}
/>
- <TextInput
- label={tUserField("email.label")}
- variant="filled"
- {...generalForm.getInputProps("email")}
- />
+ <TextInput label={tUserField("email.label")} variant="filled" {...generalForm.getInputProps("email")} />
</Stack>
</Card>
</form>
</Stepper.Step>
- <Stepper.Step
- label={t("step.security.label")}
- allowStepSelect={false}
- allowStepClick={false}
- >
+ <Stepper.Step label={t("step.security.label")} allowStepSelect={false} allowStepClick={false}>
<form>
<Card p="xl">
<Stack gap="md">
@@ -167,11 +136,7 @@ export const UserCreateStepperComponent = () => {
>
3
</Stepper.Step>
- <Stepper.Step
- label={t("step.review.label")}
- allowStepSelect={false}
- allowStepClick={false}
- >
+ <Stepper.Step label={t("step.review.label")} allowStepSelect={false} allowStepClick={false}>
<Card p="xl">
<Stack maw={300} align="center" mx="auto">
<Avatar size="xl">{generalForm.values.username}</Avatar>
diff --git a/apps/nextjs/src/app/[locale]/manage/users/create/_components/stepper-navigation.component.tsx b/apps/nextjs/src/app/[locale]/manage/users/create/_components/stepper-navigation.component.tsx
index 5511eeaf5..9a277f8b1 100644
--- a/apps/nextjs/src/app/[locale]/manage/users/create/_components/stepper-navigation.component.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/users/create/_components/stepper-navigation.component.tsx
@@ -1,11 +1,6 @@
import Link from "next/link";
import { Button, Card, Group } from "@mantine/core";
-import {
- IconArrowBackUp,
- IconArrowLeft,
- IconArrowRight,
- IconRotate,
-} from "@tabler/icons-react";
+import { IconArrowBackUp, IconArrowLeft, IconArrowRight, IconRotate } from "@tabler/icons-react";
import { useI18n } from "@homarr/translation/client";
@@ -51,18 +46,10 @@ export const StepperNavigationComponent = ({
</Group>
) : (
<Group justify="end" wrap="nowrap">
- <Button
- variant="light"
- leftSection={<IconRotate size="1rem" />}
- onClick={reset}
- >
+ <Button variant="light" leftSection={<IconRotate size="1rem" />} onClick={reset}>
{t("management.page.user.create.action.createAnother")}
</Button>
- <Button
- leftSection={<IconArrowBackUp size="1rem" />}
- component={Link}
- href="/manage/users"
- >
+ <Button leftSection={<IconArrowBackUp size="1rem" />} component={Link} href="/manage/users">
{t("management.page.user.create.action.back")}
</Button>
</Group>
diff --git a/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/_delete-group.tsx b/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/_delete-group.tsx
index a0dfe6cbb..5941a31a2 100644
--- a/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/_delete-group.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/_delete-group.tsx
@@ -6,10 +6,7 @@ import { Button } from "@mantine/core";
import { clientApi } from "@homarr/api/client";
import { useConfirmModal } from "@homarr/modals";
-import {
- showErrorNotification,
- showSuccessNotification,
-} from "@homarr/notifications";
+import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import { useI18n, useScopedI18n } from "@homarr/translation/client";
import { revalidatePathActionAsync } from "~/app/revalidatePathAction";
@@ -63,15 +60,7 @@ export const DeleteGroup = ({ group }: DeleteGroupProps) => {
);
},
});
- }, [
- tDelete,
- tRoot,
- openConfirmModal,
- group.id,
- group.name,
- mutateAsync,
- router,
- ]);
+ }, [tDelete, tRoot, openConfirmModal, group.id, group.name, mutateAsync, router]);
return (
<Button variant="subtle" color="red" onClick={handleDeletion}>
diff --git a/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/_navigation.tsx b/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/_navigation.tsx
index cef6b6a11..8b7f0004c 100644
--- a/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/_navigation.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/_navigation.tsx
@@ -14,13 +14,5 @@ interface NavigationLinkProps {
export const NavigationLink = ({ href, icon, label }: NavigationLinkProps) => {
const pathName = usePathname();
- return (
- <NavLink
- component={Link}
- href={href}
- active={pathName === href}
- label={label}
- leftSection={icon}
- />
- );
+ return <NavLink component={Link} href={href} active={pathName === href} label={label} leftSection={icon} />;
};
diff --git a/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/_rename-group-form.tsx b/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/_rename-group-form.tsx
index da9c5be58..fea242030 100644
--- a/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/_rename-group-form.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/_rename-group-form.tsx
@@ -5,10 +5,7 @@ import { Button, Group, Stack, TextInput } from "@mantine/core";
import { clientApi } from "@homarr/api/client";
import { useZodForm } from "@homarr/form";
-import {
- showErrorNotification,
- showSuccessNotification,
-} from "@homarr/notifications";
+import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import { useI18n } from "@homarr/translation/client";
import { validation } from "@homarr/validation";
@@ -64,10 +61,7 @@ export const RenameGroupForm = ({ group }: RenameGroupFormProps) => {
return (
<form onSubmit={form.onSubmit(handleSubmit)}>
<Stack>
- <TextInput
- label={t("group.field.name")}
- {...form.getInputProps("name")}
- />
+ <TextInput label={t("group.field.name")} {...form.getInputProps("name")} />
<Group justify="end">
<Button type="submit" color="teal" loading={isPending}>
diff --git a/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/_transfer-group-ownership.tsx b/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/_transfer-group-ownership.tsx
index 89bafb3e5..a350b3236 100644
--- a/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/_transfer-group-ownership.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/_transfer-group-ownership.tsx
@@ -5,10 +5,7 @@ import { Button } from "@mantine/core";
import { clientApi } from "@homarr/api/client";
import { useConfirmModal, useModalAction } from "@homarr/modals";
-import {
- showErrorNotification,
- showSuccessNotification,
-} from "@homarr/notifications";
+import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import { useI18n, useScopedI18n } from "@homarr/translation/client";
import { UserSelectModal } from "~/app/[locale]/boards/[name]/settings/_access/user-select-modal";
@@ -21,9 +18,7 @@ interface TransferGroupOwnershipProps {
};
}
-export const TransferGroupOwnership = ({
- group,
-}: TransferGroupOwnershipProps) => {
+export const TransferGroupOwnership = ({ group }: TransferGroupOwnershipProps) => {
const tTransfer = useScopedI18n("group.action.transfer");
const tRoot = useI18n();
const [innerOwnerId, setInnerOwnerId] = useState(group.ownerId);
@@ -77,16 +72,7 @@ export const TransferGroupOwnership = ({
title: tTransfer("label"),
},
);
- }, [
- group.id,
- group.name,
- innerOwnerId,
- mutateAsync,
- openConfirmModal,
- openModal,
- tRoot,
- tTransfer,
- ]);
+ }, [group.id, group.name, innerOwnerId, mutateAsync, openConfirmModal, openModal, tRoot, tTransfer]);
return (
<Button variant="subtle" color="red" onClick={handleTransfer}>
diff --git a/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/layout.tsx b/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/layout.tsx
index ee0f8e5e1..e512c13b5 100644
--- a/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/layout.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/layout.tsx
@@ -1,15 +1,6 @@
import type { PropsWithChildren } from "react";
import Link from "next/link";
-import {
- Button,
- Container,
- Grid,
- GridCol,
- Group,
- Stack,
- Text,
- Title,
-} from "@mantine/core";
+import { Button, Container, Grid, GridCol, Group, Stack, Text, Title } from "@mantine/core";
import { IconLock, IconSettings, IconUsersGroup } from "@tabler/icons-react";
import { api } from "@homarr/api/server";
@@ -21,10 +12,7 @@ interface LayoutProps {
params: { id: string };
}
-export default async function Layout({
- children,
- params,
-}: PropsWithChildren<LayoutProps>) {
+export default async function Layout({ children, params }: PropsWithChildren<LayoutProps>) {
const t = await getI18n();
const tGroup = await getScopedI18n("management.page.group");
const group = await api.group.getById({ id: params.id });
@@ -38,12 +26,7 @@ export default async function Layout({
<Title order={3}>{group.name}</Title>
<Text c="gray.5">{t("group.name")}</Text>
</Stack>
- <Button
- component={Link}
- href="/manage/users/groups"
- color="gray"
- variant="light"
- >
+ <Button component={Link} href="/manage/users/groups" color="gray" variant="light">
{tGroup("back")}
</Button>
</Group>
diff --git a/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/members/_add-group-member.tsx b/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/members/_add-group-member.tsx
index b1b585629..2d7d2941d 100644
--- a/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/members/_add-group-member.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/members/_add-group-member.tsx
@@ -15,10 +15,7 @@ interface AddGroupMemberProps {
presentUserIds: string[];
}
-export const AddGroupMember = ({
- groupId,
- presentUserIds,
-}: AddGroupMemberProps) => {
+export const AddGroupMember = ({ groupId, presentUserIds }: AddGroupMemberProps) => {
const tMembersAdd = useScopedI18n("group.action.addMember");
const { mutateAsync } = clientApi.group.addMember.useMutation();
const { openModal } = useModalAction(UserSelectModal);
@@ -32,9 +29,7 @@ export const AddGroupMember = ({
userId: id,
groupId,
});
- await revalidatePathActionAsync(
- `/manage/users/groups/${groupId}}/members`,
- );
+ await revalidatePathActionAsync(`/manage/users/groups/${groupId}}/members`);
},
presentUserIds,
},
diff --git a/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/members/_remove-group-member.tsx b/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/members/_remove-group-member.tsx
index 6c8ea272e..be9b9ff78 100644
--- a/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/members/_remove-group-member.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/members/_remove-group-member.tsx
@@ -14,10 +14,7 @@ interface RemoveGroupMemberProps {
user: { id: string; name: string | null };
}
-export const RemoveGroupMember = ({
- groupId,
- user,
-}: RemoveGroupMemberProps) => {
+export const RemoveGroupMember = ({ groupId, user }: RemoveGroupMemberProps) => {
const t = useI18n();
const tRemoveMember = useScopedI18n("group.action.removeMember");
const { mutateAsync } = clientApi.group.removeMember.useMutation();
@@ -35,27 +32,13 @@ export const RemoveGroupMember = ({
groupId,
userId: user.id,
});
- await revalidatePathActionAsync(
- `/manage/users/groups/${groupId}/members`,
- );
+ await revalidatePathActionAsync(`/manage/users/groups/${groupId}/members`);
},
});
- }, [
- openConfirmModal,
- mutateAsync,
- groupId,
- user.id,
- user.name,
- tRemoveMember,
- ]);
+ }, [openConfirmModal, mutateAsync, groupId, user.id, user.name, tRemoveMember]);
return (
- <Button
- variant="subtle"
- color="red.9"
- size="compact-sm"
- onClick={handleRemove}
- >
+ <Button variant="subtle" color="red.9" size="compact-sm" onClick={handleRemove}>
{t("common.action.remove")}
</Button>
);
diff --git a/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/members/page.tsx b/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/members/page.tsx
index a9bdea5f4..7f694ba6b 100644
--- a/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/members/page.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/members/page.tsx
@@ -1,16 +1,5 @@
import Link from "next/link";
-import {
- Anchor,
- Center,
- Group,
- Stack,
- Table,
- TableTbody,
- TableTd,
- TableTr,
- Text,
- Title,
-} from "@mantine/core";
+import { Anchor, Center, Group, Stack, Table, TableTbody, TableTd, TableTr, Text, Title } from "@mantine/core";
import type { RouterOutputs } from "@homarr/api";
import { api } from "@homarr/api/server";
@@ -29,20 +18,13 @@ interface GroupsDetailPageProps {
};
}
-export default async function GroupsDetailPage({
- params,
- searchParams,
-}: GroupsDetailPageProps) {
+export default async function GroupsDetailPage({ params, searchParams }: GroupsDetailPageProps) {
const t = await getI18n();
const tMembers = await getScopedI18n("management.page.group.setting.members");
const group = await api.group.getById({ id: params.id });
const filteredMembers = searchParams.search
- ? group.members.filter((member) =>
- member.name
- ?.toLowerCase()
- .includes(searchParams.search!.trim().toLowerCase()),
- )
+ ? group.members.filter((member) => member.name?.toLowerCase().includes(searchParams.search!.trim().toLowerCase()))
: group.members;
return (
@@ -56,10 +38,7 @@ export default async function GroupsDetailPage({
})}
defaultValue={searchParams.search}
/>
- <AddGroupMember
- groupId={group.id}
- presentUserIds={group.members.map((member) => member.id)}
- />
+ <AddGroupMember groupId={group.id} presentUserIds={group.members.map((member) => member.id)} />
</Group>
{filteredMembers.length === 0 && (
<Center py="sm">
diff --git a/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/page.tsx b/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/page.tsx
index 2c8e1fa4d..cc3496520 100644
--- a/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/page.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/page.tsx
@@ -3,10 +3,7 @@ import { Stack, Title } from "@mantine/core";
import { api } from "@homarr/api/server";
import { getScopedI18n } from "@homarr/translation/server";
-import {
- DangerZoneItem,
- DangerZoneRoot,
-} from "~/components/manage/danger-zone";
+import { DangerZoneItem, DangerZoneRoot } from "~/components/manage/danger-zone";
import { DeleteGroup } from "./_delete-group";
import { RenameGroupForm } from "./_rename-group-form";
import { TransferGroupOwnership } from "./_transfer-group-ownership";
@@ -17,9 +14,7 @@ interface GroupsDetailPageProps {
};
}
-export default async function GroupsDetailPage({
- params,
-}: GroupsDetailPageProps) {
+export default async function GroupsDetailPage({ params }: GroupsDetailPageProps) {
const group = await api.group.getById({ id: params.id });
const tGeneral = await getScopedI18n("management.page.group.setting.general");
const tGroupAction = await getScopedI18n("group.action");
diff --git a/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/permissions/_group-permission-form.tsx b/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/permissions/_group-permission-form.tsx
index 38dddc0f9..ef5906354 100644
--- a/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/permissions/_group-permission-form.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/permissions/_group-permission-form.tsx
@@ -9,10 +9,7 @@ import { objectEntries } from "@homarr/common";
import type { GroupPermissionKey } from "@homarr/definitions";
import { groupPermissionKeys } from "@homarr/definitions";
import { createFormContext } from "@homarr/form";
-import {
- showErrorNotification,
- showSuccessNotification,
-} from "@homarr/notifications";
+import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import { useI18n, useScopedI18n } from "@homarr/translation/client";
const [FormProvider, useFormContext, useForm] = createFormContext<FormType>();
@@ -21,10 +18,7 @@ interface PermissionFormProps {
initialPermissions: GroupPermissionKey[];
}
-export const PermissionForm = ({
- children,
- initialPermissions,
-}: PropsWithChildren<PermissionFormProps>) => {
+export const PermissionForm = ({ children, initialPermissions }: PropsWithChildren<PermissionFormProps>) => {
const form = useForm({
initialValues: groupPermissionKeys.reduce((acc, key) => {
acc[key] = initialPermissions.includes(key);
@@ -73,9 +67,7 @@ interface SaveAffixProps {
export const SaveAffix = ({ groupId }: SaveAffixProps) => {
const t = useI18n();
const tForm = useScopedI18n("management.page.group.setting.permissions.form");
- const tNotification = useScopedI18n(
- "group.action.changePermissions.notification",
- );
+ const tNotification = useScopedI18n("group.action.changePermissions.notification");
const form = useFormContext();
const { mutate, isPending } = clientApi.group.savePermissions.useMutation();
diff --git a/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/permissions/page.tsx b/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/permissions/page.tsx
index 98acc2c11..21f89c5e9 100644
--- a/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/permissions/page.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/users/groups/[id]/permissions/page.tsx
@@ -1,13 +1,5 @@
import React from "react";
-import {
- Card,
- CardSection,
- Divider,
- Group,
- Stack,
- Text,
- Title,
-} from "@mantine/core";
+import { Card, CardSection, Divider, Group, Stack, Text, Title } from "@mantine/core";
import { api } from "@homarr/api/server";
import { objectKeys } from "@homarr/common";
@@ -15,11 +7,7 @@ import type { GroupPermissionKey } from "@homarr/definitions";
import { groupPermissions } from "@homarr/definitions";
import { getI18n, getScopedI18n } from "@homarr/translation/server";
-import {
- PermissionForm,
- PermissionSwitch,
- SaveAffix,
-} from "./_group-permission-form";
+import { PermissionForm, PermissionSwitch, SaveAffix } from "./_group-permission-form";
interface GroupPermissionsPageProps {
params: {
@@ -27,9 +15,7 @@ interface GroupPermissionsPageProps {
};
}
-export default async function GroupPermissionsPage({
- params,
-}: GroupPermissionsPageProps) {
+export default async function GroupPermissionsPage({ params }: GroupPermissionsPageProps) {
const group = await api.group.getById({ id: params.id });
const tPermissions = await getScopedI18n("group.permission");
const t = await getI18n();
@@ -99,10 +85,7 @@ const PermissionCard = async ({ group, isDanger }: PermissionCardProps) => {
);
};
-const createGroupPermissionKey = (
- group: keyof typeof groupPermissions,
- permission: string,
-): GroupPermissionKey => {
+const createGroupPermissionKey = (group: keyof typeof groupPermissions, permission: string): GroupPermissionKey => {
if (typeof groupPermissions[group] === "boolean") {
return group as GroupPermissionKey;
}
diff --git a/apps/nextjs/src/app/[locale]/manage/users/groups/_add-group.tsx b/apps/nextjs/src/app/[locale]/manage/users/groups/_add-group.tsx
index 77dc2b009..b28ddccd0 100644
--- a/apps/nextjs/src/app/[locale]/manage/users/groups/_add-group.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/users/groups/_add-group.tsx
@@ -6,10 +6,7 @@ import { Button, Group, Stack, TextInput } from "@mantine/core";
import { clientApi } from "@homarr/api/client";
import { useZodForm } from "@homarr/form";
import { createModal, useModalAction } from "@homarr/modals";
-import {
- showErrorNotification,
- showSuccessNotification,
-} from "@homarr/notifications";
+import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import { useI18n } from "@homarr/translation/client";
import { validation } from "@homarr/validation";
@@ -61,11 +58,7 @@ const AddGroupModal = createModal<void>(({ actions }) => {
})}
>
<Stack>
- <TextInput
- label={t("group.field.name")}
- data-autofocus
- {...form.getInputProps("name")}
- />
+ <TextInput label={t("group.field.name")} data-autofocus {...form.getInputProps("name")} />
<Group justify="right">
<Button onClick={actions.closeModal} variant="subtle" color="gray">
{t("common.action.cancel")}
diff --git a/apps/nextjs/src/app/[locale]/manage/users/groups/page.tsx b/apps/nextjs/src/app/[locale]/manage/users/groups/page.tsx
index d41d98d1c..410fe57ed 100644
--- a/apps/nextjs/src/app/[locale]/manage/users/groups/page.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/users/groups/page.tsx
@@ -27,25 +27,18 @@ const searchParamsSchema = z.object({
page: z.string().regex(/\d+/).transform(Number).catch(1),
});
-type SearchParamsSchemaInputFromSchema<
- TSchema extends Record<string, unknown>,
-> = Partial<{
- [K in keyof TSchema]: Exclude<TSchema[K], undefined> extends unknown[]
- ? string[]
- : string;
+type SearchParamsSchemaInputFromSchema<TSchema extends Record<string, unknown>> = Partial<{
+ [K in keyof TSchema]: Exclude<TSchema[K], undefined> extends unknown[] ? string[] : string;
}>;
interface GroupsListPageProps {
- searchParams: SearchParamsSchemaInputFromSchema<
- z.infer<typeof searchParamsSchema>
- >;
+ searchParams: SearchParamsSchemaInputFromSchema<z.infer<typeof searchParamsSchema>>;
}
export default async function GroupsListPage(props: GroupsListPageProps) {
const t = await getI18n();
const searchParams = searchParamsSchema.parse(props.searchParams);
- const { items: groups, totalCount } =
- await api.group.getPaginated(searchParams);
+ const { items: groups, totalCount } = await api.group.getPaginated(searchParams);
return (
<Container size="xl">
@@ -76,9 +69,7 @@ export default async function GroupsListPage(props: GroupsListPageProps) {
</Table>
<Group justify="end">
- <TablePagination
- total={Math.ceil(totalCount / searchParams.pageSize)}
- />
+ <TablePagination total={Math.ceil(totalCount / searchParams.pageSize)} />
</Group>
</Stack>
</Container>
diff --git a/apps/nextjs/src/app/[locale]/manage/users/invites/_components/invite-copy-modal.tsx b/apps/nextjs/src/app/[locale]/manage/users/invites/_components/invite-copy-modal.tsx
index 359402cf4..2fa3890a3 100644
--- a/apps/nextjs/src/app/[locale]/manage/users/invites/_components/invite-copy-modal.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/users/invites/_components/invite-copy-modal.tsx
@@ -6,9 +6,7 @@ import type { RouterOutputs } from "@homarr/api";
import { createModal } from "@homarr/modals";
import { useScopedI18n } from "@homarr/translation/client";
-export const InviteCopyModal = createModal<
- RouterOutputs["invite"]["createInvite"]
->(({ actions, innerProps }) => {
+export const InviteCopyModal = createModal<RouterOutputs["invite"]["createInvite"]>(({ actions, innerProps }) => {
const t = useScopedI18n("management.page.user.invite");
const inviteUrl = useInviteUrl(innerProps);
@@ -50,13 +48,9 @@ export const InviteCopyModal = createModal<
},
});
-const createPath = ({ id, token }: RouterOutputs["invite"]["createInvite"]) =>
- `/auth/invite/${id}?token=${token}`;
+const createPath = ({ id, token }: RouterOutputs["invite"]["createInvite"]) => `/auth/invite/${id}?token=${token}`;
-const useInviteUrl = ({
- id,
- token,
-}: RouterOutputs["invite"]["createInvite"]) => {
+const useInviteUrl = ({ id, token }: RouterOutputs["invite"]["createInvite"]) => {
const pathname = usePathname();
return window.location.href.replace(pathname, createPath({ id, token }));
diff --git a/apps/nextjs/src/app/[locale]/manage/users/invites/_components/invite-list.tsx b/apps/nextjs/src/app/[locale]/manage/users/invites/_components/invite-list.tsx
index 8a512818e..accc23982 100644
--- a/apps/nextjs/src/app/[locale]/manage/users/invites/_components/invite-list.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/users/invites/_components/invite-list.tsx
@@ -21,9 +21,7 @@ interface InviteListComponentProps {
initialInvites: RouterOutputs["invite"]["getAll"];
}
-export const InviteListComponent = ({
- initialInvites,
-}: InviteListComponentProps) => {
+export const InviteListComponent = ({ initialInvites }: InviteListComponentProps) => {
const t = useScopedI18n("management.page.user.invite");
const { data, isLoading } = clientApi.invite.getAll.useQuery(undefined, {
initialData: initialInvites,
@@ -32,9 +30,7 @@ export const InviteListComponent = ({
refetchOnReconnect: false,
});
- const columns = useMemo<
- MRT_ColumnDef<RouterOutputs["invite"]["getAll"][number]>[]
- >(
+ const columns = useMemo<MRT_ColumnDef<RouterOutputs["invite"]["getAll"][number]>[]>(
() => [
{
accessorKey: "id",
@@ -100,11 +96,7 @@ const RenderTopToolbarCustomActions = () => {
);
};
-const RenderRowActions = ({
- row,
-}: {
- row: MRT_Row<RouterOutputs["invite"]["getAll"][number]>;
-}) => {
+const RenderRowActions = ({ row }: { row: MRT_Row<RouterOutputs["invite"]["getAll"][number]> }) => {
const t = useScopedI18n("management.page.user.invite");
const { mutate, isPending } = clientApi.invite.deleteInvite.useMutation();
const utils = clientApi.useUtils();
@@ -121,12 +113,7 @@ const RenderRowActions = ({
}, [openConfirmModal, row.original.id, mutate, utils, t]);
return (
- <ActionIcon
- variant="subtle"
- color="red"
- onClick={handleDelete}
- loading={isPending}
- >
+ <ActionIcon variant="subtle" color="red" onClick={handleDelete} loading={isPending}>
<IconTrash color="red" size={20} stroke={1.5} />
</ActionIcon>
);
diff --git a/apps/nextjs/src/app/[locale]/widgets/[kind]/_content.tsx b/apps/nextjs/src/app/[locale]/widgets/[kind]/_content.tsx
index 8f76fda4f..3c1ad6ba7 100644
--- a/apps/nextjs/src/app/[locale]/widgets/[kind]/_content.tsx
+++ b/apps/nextjs/src/app/[locale]/widgets/[kind]/_content.tsx
@@ -2,12 +2,7 @@
import { useCallback, useMemo, useState } from "react";
import { ActionIcon, Affix, Card } from "@mantine/core";
-import {
- IconDimensions,
- IconPencil,
- IconToggleLeft,
- IconToggleRight,
-} from "@tabler/icons-react";
+import { IconDimensions, IconPencil, IconToggleLeft, IconToggleRight } from "@tabler/icons-react";
import type { IntegrationKind, WidgetKind } from "@homarr/definitions";
import { useModalAction } from "@homarr/modals";
@@ -34,19 +29,11 @@ interface WidgetPreviewPageContentProps {
}[];
}
-export const WidgetPreviewPageContent = ({
- kind,
- integrationData,
-}: WidgetPreviewPageContentProps) => {
+export const WidgetPreviewPageContent = ({ kind, integrationData }: WidgetPreviewPageContentProps) => {
const t = useScopedI18n("widgetPreview");
const { openModal: openWidgetEditModal } = useModalAction(WidgetEditModal);
- const { openModal: openPreviewDimensionsModal } = useModalAction(
- PreviewDimensionsModal,
- );
- const currentDefinition = useMemo(
- () => widgetImports[kind].definition,
- [kind],
- );
+ const { openModal: openPreviewDimensionsModal } = useModalAction(PreviewDimensionsModal);
+ const currentDefinition = useMemo(() => widgetImports[kind].definition, [kind]);
const [editMode, setEditMode] = useState(false);
const [dimensions, setDimensions] = useState<Dimensions>({
width: 128,
@@ -70,9 +57,7 @@ export const WidgetPreviewPageContent = ({
integrationData: integrationData.filter(
(integration) =>
"supportedIntegrations" in currentDefinition &&
- (currentDefinition.supportedIntegrations as string[]).some(
- (kind) => kind === integration.kind,
- ),
+ (currentDefinition.supportedIntegrations as string[]).some((kind) => kind === integration.kind),
),
integrationSupport: "supportedIntegrations" in currentDefinition,
});
@@ -96,19 +81,11 @@ export const WidgetPreviewPageContent = ({
return (
<>
- <Card
- withBorder
- w={dimensions.width}
- h={dimensions.height}
- p={dimensions.height >= 96 ? undefined : 4}
- >
+ <Card withBorder w={dimensions.width} h={dimensions.height} p={dimensions.height >= 96 ? undefined : 4}>
<Comp
options={state.options as never}
integrations={state.integrations.map(
- (stateIntegration) =>
- integrationData.find(
- (integration) => integration.id === stateIntegration.id,
- )!,
+ (stateIntegration) => integrationData.find((integration) => integration.id === stateIntegration.id)!,
)}
width={dimensions.width}
height={dimensions.height}
@@ -118,36 +95,17 @@ export const WidgetPreviewPageContent = ({
/>
</Card>
<Affix bottom={12} right={72}>
- <ActionIcon
- size={48}
- variant="default"
- radius="xl"
- onClick={handleOpenEditWidgetModal}
- >
+ <ActionIcon size={48} variant="default" radius="xl" onClick={handleOpenEditWidgetModal}>
<IconPencil size={24} />
</ActionIcon>
</Affix>
<Affix bottom={12} right={72 + 60}>
- <ActionIcon
- size={48}
- variant="default"
- radius="xl"
- onClick={toggleEditMode}
- >
- {editMode ? (
- <IconToggleLeft size={24} />
- ) : (
- <IconToggleRight size={24} />
- )}
+ <ActionIcon size={48} variant="default" radius="xl" onClick={toggleEditMode}>
+ {editMode ? <IconToggleLeft size={24} /> : <IconToggleRight size={24} />}
</ActionIcon>
</Affix>
<Affix bottom={12} right={72 + 120}>
- <ActionIcon
- size={48}
- variant="default"
- radius="xl"
- onClick={openDimensionsModal}
- >
+ <ActionIcon size={48} variant="default" radius="xl" onClick={openDimensionsModal}>
<IconDimensions size={24} />
</ActionIcon>
</Affix>
diff --git a/apps/nextjs/src/app/[locale]/widgets/[kind]/_dimension-modal.tsx b/apps/nextjs/src/app/[locale]/widgets/[kind]/_dimension-modal.tsx
index 964330fe7..1077de04a 100644
--- a/apps/nextjs/src/app/[locale]/widgets/[kind]/_dimension-modal.tsx
+++ b/apps/nextjs/src/app/[locale]/widgets/[kind]/_dimension-modal.tsx
@@ -11,48 +11,36 @@ interface InnerProps {
setDimensions: (dimensions: Dimensions) => void;
}
-export const PreviewDimensionsModal = createModal<InnerProps>(
- ({ actions, innerProps }) => {
- const t = useI18n();
- const form = useForm({
- initialValues: innerProps.dimensions,
- });
+export const PreviewDimensionsModal = createModal<InnerProps>(({ actions, innerProps }) => {
+ const t = useI18n();
+ const form = useForm({
+ initialValues: innerProps.dimensions,
+ });
- const handleSubmit = (values: Dimensions) => {
- innerProps.setDimensions(values);
- actions.closeModal();
- };
+ const handleSubmit = (values: Dimensions) => {
+ innerProps.setDimensions(values);
+ actions.closeModal();
+ };
- return (
- <form onSubmit={form.onSubmit(handleSubmit)}>
- <Stack>
- <InputWrapper label={t("item.move.field.width.label")}>
- <Slider
- min={64}
- max={1024}
- step={64}
- {...form.getInputProps("width")}
- />
- </InputWrapper>
- <InputWrapper label={t("item.move.field.height.label")}>
- <Slider
- min={64}
- max={1024}
- step={64}
- {...form.getInputProps("height")}
- />
- </InputWrapper>
- <Group justify="end">
- <Button variant="subtle" color="gray" onClick={actions.closeModal}>
- {t("common.action.cancel")}
- </Button>
- <Button type="submit">{t("common.action.confirm")}</Button>
- </Group>
- </Stack>
- </form>
- );
- },
-).withOptions({
+ return (
+ <form onSubmit={form.onSubmit(handleSubmit)}>
+ <Stack>
+ <InputWrapper label={t("item.move.field.width.label")}>
+ <Slider min={64} max={1024} step={64} {...form.getInputProps("width")} />
+ </InputWrapper>
+ <InputWrapper label={t("item.move.field.height.label")}>
+ <Slider min={64} max={1024} step={64} {...form.getInputProps("height")} />
+ </InputWrapper>
+ <Group justify="end">
+ <Button variant="subtle" color="gray" onClick={actions.closeModal}>
+ {t("common.action.cancel")}
+ </Button>
+ <Button type="submit">{t("common.action.confirm")}</Button>
+ </Group>
+ </Stack>
+ </form>
+ );
+}).withOptions({
defaultTitle: (t) => t("widgetPreview.dimensions.title"),
});
diff --git a/apps/nextjs/src/app/api/trpc/[trpc]/route.ts b/apps/nextjs/src/app/api/trpc/[trpc]/route.ts
index e4682239b..7d1ae50d5 100644
--- a/apps/nextjs/src/app/api/trpc/[trpc]/route.ts
+++ b/apps/nextjs/src/app/api/trpc/[trpc]/route.ts
@@ -28,12 +28,9 @@ const handler = auth(async (req) => {
endpoint: "/api/trpc",
router: appRouter,
req,
- createContext: () =>
- createTRPCContext({ session: req.auth, headers: req.headers }),
+ createContext: () => createTRPCContext({ session: req.auth, headers: req.headers }),
onError({ error, path, type }) {
- logger.error(
- `tRPC Error with ${type} on '${path}': (${error.code}) - ${error.message}`,
- );
+ logger.error(`tRPC Error with ${type} on '${path}': (${error.code}) - ${error.message}`);
},
});
diff --git a/apps/nextjs/src/components/active-tab-accordion.tsx b/apps/nextjs/src/components/active-tab-accordion.tsx
index bd000a0df..d52c987b4 100644
--- a/apps/nextjs/src/components/active-tab-accordion.tsx
+++ b/apps/nextjs/src/components/active-tab-accordion.tsx
@@ -7,28 +7,16 @@ import type { AccordionProps } from "@mantine/core";
import { Accordion } from "@mantine/core";
import { useShallowEffect } from "@mantine/hooks";
-type ActiveTabAccordionProps = PropsWithChildren<
- Omit<AccordionProps<false>, "onChange">
->;
+type ActiveTabAccordionProps = PropsWithChildren<Omit<AccordionProps<false>, "onChange">>;
// Replace state without fetchign new data
const replace = (newUrl: string) => {
- window.history.replaceState(
- { ...window.history.state, as: newUrl, url: newUrl },
- "",
- newUrl,
- );
+ window.history.replaceState({ ...window.history.state, as: newUrl, url: newUrl }, "", newUrl);
};
-export const ActiveTabAccordion = ({
- children,
- ...props
-}: ActiveTabAccordionProps) => {
+export const ActiveTabAccordion = ({ children, ...props }: ActiveTabAccordionProps) => {
const pathname = usePathname();
- const onChange = useCallback(
- (tab: string | null) => (tab ? replace(`?tab=${tab}`) : replace(pathname)),
- [pathname],
- );
+ const onChange = useCallback((tab: string | null) => (tab ? replace(`?tab=${tab}`) : replace(pathname)), [pathname]);
useShallowEffect(() => {
if (props.defaultValue) {
diff --git a/apps/nextjs/src/components/board/items/item-actions.tsx b/apps/nextjs/src/components/board/items/item-actions.tsx
index 83df3aaa8..1f3650d9c 100644
--- a/apps/nextjs/src/components/board/items/item-actions.tsx
+++ b/apps/nextjs/src/components/board/items/item-actions.tsx
@@ -47,12 +47,8 @@ export const useItemActions = () => {
({ kind }: CreateItem) => {
updateBoard((previous) => {
const lastSection = previous.sections
- .filter(
- (section): section is EmptySection => section.kind === "empty",
- )
- .sort(
- (sectionA, sectionB) => sectionB.position - sectionA.position,
- )[0];
+ .filter((section): section is EmptySection => section.kind === "empty")
+ .sort((sectionA, sectionB) => sectionB.position - sectionA.position)[0];
if (!lastSection) return previous;
@@ -91,8 +87,7 @@ export const useItemActions = () => {
...previous,
sections: previous.sections.map((section) => {
// Return same section if item is not in it
- if (!section.items.some((item) => item.id === itemId))
- return section;
+ if (!section.items.some((item) => item.id === itemId)) return section;
return {
...section,
items: section.items.map((item) => {
@@ -119,8 +114,7 @@ export const useItemActions = () => {
...previous,
sections: previous.sections.map((section) => {
// Return same section if item is not in it
- if (!section.items.some((item) => item.id === itemId))
- return section;
+ if (!section.items.some((item) => item.id === itemId)) return section;
return {
...section,
items: section.items.map((item) => {
@@ -128,9 +122,7 @@ export const useItemActions = () => {
if (item.id !== itemId) return item;
return {
...item,
- ...("integrations" in item
- ? { integrations: newIntegrations }
- : {}),
+ ...("integrations" in item ? { integrations: newIntegrations } : {}),
};
}),
};
@@ -168,18 +160,14 @@ export const useItemActions = () => {
const moveItemToSection = useCallback(
({ itemId, sectionId, ...positionProps }: MoveItemToSection) => {
updateBoard((previous) => {
- const currentSection = previous.sections.find((section) =>
- section.items.some((item) => item.id === itemId),
- );
+ const currentSection = previous.sections.find((section) => section.items.some((item) => item.id === itemId));
// If item is in the same section (on initial loading) don't do anything
if (!currentSection) {
return previous;
}
- const currentItem = currentSection.items.find(
- (item) => item.id === itemId,
- );
+ const currentItem = currentSection.items.find((item) => item.id === itemId);
if (!currentItem) {
return previous;
}
diff --git a/apps/nextjs/src/components/board/items/item-select-modal.tsx b/apps/nextjs/src/components/board/items/item-select-modal.tsx
index f01b09322..64d7c4a5f 100644
--- a/apps/nextjs/src/components/board/items/item-select-modal.tsx
+++ b/apps/nextjs/src/components/board/items/item-select-modal.tsx
@@ -13,14 +13,7 @@ export const ItemSelectModal = createModal<void>(({ actions }) => {
return (
<Grid>
{objectEntries(widgetImports).map(([key, value]) => {
- return (
- <WidgetItem
- key={key}
- kind={key}
- definition={value.definition}
- closeModal={actions.closeModal}
- />
- );
+ return <WidgetItem key={key} kind={key} definition={value.definition} closeModal={actions.closeModal} />;
})}
</Grid>
);
@@ -56,13 +49,7 @@ const WidgetItem = ({
<Text lh={1.2} style={{ whiteSpace: "normal" }} ta="center">
{t(`widget.${kind}.name`)}
</Text>
- <Text
- lh={1.2}
- style={{ whiteSpace: "normal" }}
- size="xs"
- ta="center"
- c="dimmed"
- >
+ <Text lh={1.2} style={{ whiteSpace: "normal" }} size="xs" ta="center" c="dimmed">
{t(`widget.${kind}.description`)}
</Text>
</Stack>
diff --git a/apps/nextjs/src/components/board/modals/board-rename-modal.tsx b/apps/nextjs/src/components/board/modals/board-rename-modal.tsx
index d77d76fd0..c627aab05 100644
--- a/apps/nextjs/src/components/board/modals/board-rename-modal.tsx
+++ b/apps/nextjs/src/components/board/modals/board-rename-modal.tsx
@@ -15,62 +15,55 @@ interface InnerProps {
onSuccess?: (name: string) => void;
}
-export const BoardRenameModal = createModal<InnerProps>(
- ({ actions, innerProps }) => {
- const utils = clientApi.useUtils();
- const t = useI18n();
- const { mutate, isPending } = clientApi.board.renameBoard.useMutation({
- onSettled() {
- void utils.board.getBoardByName.invalidate({
- name: innerProps.previousName,
- });
- void utils.board.getHomeBoard.invalidate();
- },
- });
- const form = useZodForm(validation.board.rename.omit({ id: true }), {
- initialValues: {
+export const BoardRenameModal = createModal<InnerProps>(({ actions, innerProps }) => {
+ const utils = clientApi.useUtils();
+ const t = useI18n();
+ const { mutate, isPending } = clientApi.board.renameBoard.useMutation({
+ onSettled() {
+ void utils.board.getBoardByName.invalidate({
name: innerProps.previousName,
- },
- });
+ });
+ void utils.board.getHomeBoard.invalidate();
+ },
+ });
+ const form = useZodForm(validation.board.rename.omit({ id: true }), {
+ initialValues: {
+ name: innerProps.previousName,
+ },
+ });
- const handleSubmit = (values: FormType) => {
- mutate(
- {
- id: innerProps.id,
- name: values.name,
- },
- {
- onSuccess: () => {
- actions.closeModal();
- innerProps.onSuccess?.(values.name);
- },
+ const handleSubmit = (values: FormType) => {
+ mutate(
+ {
+ id: innerProps.id,
+ name: values.name,
+ },
+ {
+ onSuccess: () => {
+ actions.closeModal();
+ innerProps.onSuccess?.(values.name);
},
- );
- };
-
- return (
- <form onSubmit={form.onSubmit(handleSubmit)}>
- <Stack>
- <TextInput
- label={t("board.field.name.label")}
- {...form.getInputProps("name")}
- data-autofocus
- />
- <Group justify="end">
- <Button variant="subtle" color="gray" onClick={actions.closeModal}>
- {t("common.action.cancel")}
- </Button>
- <Button type="submit" loading={isPending}>
- {t("common.action.confirm")}
- </Button>
- </Group>
- </Stack>
- </form>
+ },
);
- },
-).withOptions({
- defaultTitle: (t) =>
- t("board.setting.section.dangerZone.action.rename.modal.title"),
+ };
+
+ return (
+ <form onSubmit={form.onSubmit(handleSubmit)}>
+ <Stack>
+ <TextInput label={t("board.field.name.label")} {...form.getInputProps("name")} data-autofocus />
+ <Group justify="end">
+ <Button variant="subtle" color="gray" onClick={actions.closeModal}>
+ {t("common.action.cancel")}
+ </Button>
+ <Button type="submit" loading={isPending}>
+ {t("common.action.confirm")}
+ </Button>
+ </Group>
+ </Stack>
+ </form>
+ );
+}).withOptions({
+ defaultTitle: (t) => t("board.setting.section.dangerZone.action.rename.modal.title"),
});
type FormType = Omit<z.infer<(typeof validation)["board"]["rename"]>, "id">;
diff --git a/apps/nextjs/src/components/board/permissions/server.ts b/apps/nextjs/src/components/board/permissions/server.ts
index 7a8294509..d51dd4200 100644
--- a/apps/nextjs/src/components/board/permissions/server.ts
+++ b/apps/nextjs/src/components/board/permissions/server.ts
@@ -2,9 +2,7 @@ import { auth } from "@homarr/auth/next";
import type { BoardPermissionsProps } from "@homarr/auth/shared";
import { constructBoardPermissions } from "@homarr/auth/shared";
-export const getBoardPermissionsAsync = async (
- board: BoardPermissionsProps,
-) => {
+export const getBoardPermissionsAsync = async (board: BoardPermissionsProps) => {
const session = await auth();
return constructBoardPermissions(board, session);
};
diff --git a/apps/nextjs/src/components/board/sections/category-section.tsx b/apps/nextjs/src/components/board/sections/category-section.tsx
index bbf9f54de..f47f2e8ff 100644
--- a/apps/nextjs/src/components/board/sections/category-section.tsx
+++ b/apps/nextjs/src/components/board/sections/category-section.tsx
@@ -1,12 +1,5 @@
import type { RefObject } from "react";
-import {
- Card,
- Collapse,
- Group,
- Stack,
- Title,
- UnstyledButton,
-} from "@mantine/core";
+import { Card, Collapse, Group, Stack, Title, UnstyledButton } from "@mantine/core";
import { useDisclosure } from "@mantine/hooks";
import { IconChevronDown, IconChevronUp } from "@tabler/icons-react";
@@ -30,23 +23,14 @@ export const BoardCategorySection = ({ section, mainRef }: Props) => {
<Group wrap="nowrap" gap="sm">
<UnstyledButton w="100%" p="sm" onClick={toggle}>
<Group wrap="nowrap">
- {opened ? (
- <IconChevronUp size={20} />
- ) : (
- <IconChevronDown size={20} />
- )}
+ {opened ? <IconChevronUp size={20} /> : <IconChevronDown size={20} />}
<Title order={3}>{section.name}</Title>
</Group>
</UnstyledButton>
<CategoryMenu category={section} />
</Group>
<Collapse in={opened} p="sm" pt={0}>
- <div
- className="grid-stack grid-stack-category"
- data-category
- data-section-id={section.id}
- ref={refs.wrapper}
- >
+ <div className="grid-stack grid-stack-category" data-category data-section-id={section.id} ref={refs.wrapper}>
<SectionContent items={section.items} refs={refs} />
</div>
</Collapse>
diff --git a/apps/nextjs/src/components/board/sections/category/category-actions.ts b/apps/nextjs/src/components/board/sections/category/category-actions.ts
index 1bd715439..f78144536 100644
--- a/apps/nextjs/src/components/board/sections/category/category-actions.ts
+++ b/apps/nextjs/src/components/board/sections/category/category-actions.ts
@@ -2,11 +2,7 @@ import { useCallback } from "react";
import { createId } from "@homarr/db/client";
-import type {
- CategorySection,
- EmptySection,
- Section,
-} from "~/app/[locale]/boards/_types";
+import type { CategorySection, EmptySection, Section } from "~/app/[locale]/boards/_types";
import { useUpdateBoard } from "~/app/[locale]/boards/(content)/_client";
interface AddCategory {
@@ -41,9 +37,7 @@ export const useCategoryActions = () => {
sections: [
// Place sections before the new category
...previous.sections.filter(
- (section) =>
- (section.kind === "category" || section.kind === "empty") &&
- section.position < position,
+ (section) => (section.kind === "category" || section.kind === "empty") && section.position < position,
),
{
id: createId(),
@@ -62,8 +56,7 @@ export const useCategoryActions = () => {
...previous.sections
.filter(
(section): section is CategorySection | EmptySection =>
- (section.kind === "category" || section.kind === "empty") &&
- section.position >= position,
+ (section.kind === "category" || section.kind === "empty") && section.position >= position,
)
.map((section) => ({
...section,
@@ -134,29 +127,19 @@ export const useCategoryActions = () => {
({ id, direction }: MoveCategory) => {
updateBoard((previous) => {
const currentCategory = previous.sections.find(
- (section): section is CategorySection =>
- section.kind === "category" && section.id === id,
+ (section): section is CategorySection => section.kind === "category" && section.id === id,
);
if (!currentCategory) return previous;
- if (currentCategory?.position === 1 && direction === "up")
- return previous;
- if (
- currentCategory?.position === previous.sections.length - 2 &&
- direction === "down"
- )
- return previous;
+ if (currentCategory?.position === 1 && direction === "up") return previous;
+ if (currentCategory?.position === previous.sections.length - 2 && direction === "down") return previous;
return {
...previous,
sections: previous.sections.map((section) => {
- if (section.kind !== "category" && section.kind !== "empty")
- return section;
+ if (section.kind !== "category" && section.kind !== "empty") return section;
const offset = direction === "up" ? -2 : 2;
// Move category and empty section
- if (
- section.position === currentCategory.position ||
- section.position - 1 === currentCategory.position
- ) {
+ if (section.position === currentCategory.position || section.position - 1 === currentCategory.position) {
return {
...section,
position: section.position + offset,
@@ -165,8 +148,7 @@ export const useCategoryActions = () => {
if (
direction === "up" &&
- (section.position === currentCategory.position - 2 ||
- section.position === currentCategory.position - 1)
+ (section.position === currentCategory.position - 2 || section.position === currentCategory.position - 1)
) {
return {
...section,
@@ -176,8 +158,7 @@ export const useCategoryActions = () => {
if (
direction === "down" &&
- (section.position === currentCategory.position + 2 ||
- section.position === currentCategory.position + 3)
+ (section.position === currentCategory.position + 2 || section.position === currentCategory.position + 3)
) {
return {
...section,
@@ -197,21 +178,18 @@ export const useCategoryActions = () => {
({ id: categoryId }: RemoveCategory) => {
updateBoard((previous) => {
const currentCategory = previous.sections.find(
- (section): section is CategorySection =>
- section.kind === "category" && section.id === categoryId,
+ (section): section is CategorySection => section.kind === "category" && section.id === categoryId,
);
if (!currentCategory) return previous;
const aboveWrapper = previous.sections.find(
(section): section is EmptySection =>
- section.kind === "empty" &&
- section.position === currentCategory.position - 1,
+ section.kind === "empty" && section.position === currentCategory.position - 1,
);
const removedWrapper = previous.sections.find(
(section): section is EmptySection =>
- section.kind === "empty" &&
- section.position === currentCategory.position + 1,
+ section.kind === "empty" && section.position === currentCategory.position + 1,
);
if (!aboveWrapper || !removedWrapper) return previous;
@@ -232,16 +210,10 @@ export const useCategoryActions = () => {
return {
...previous,
sections: [
- ...previous.sections.filter(
- (section) => section.position < currentCategory.position - 1,
- ),
+ ...previous.sections.filter((section) => section.position < currentCategory.position - 1),
{
...aboveWrapper,
- items: [
- ...aboveWrapper.items,
- ...previousCategoryItems,
- ...previousBelowWrapperItems,
- ],
+ items: [...aboveWrapper.items, ...previousCategoryItems, ...previousBelowWrapperItems],
},
...previous.sections
.filter(
diff --git a/apps/nextjs/src/components/board/sections/category/category-edit-modal.tsx b/apps/nextjs/src/components/board/sections/category/category-edit-modal.tsx
index ff01ac19a..16d25c4ce 100644
--- a/apps/nextjs/src/components/board/sections/category/category-edit-modal.tsx
+++ b/apps/nextjs/src/components/board/sections/category/category-edit-modal.tsx
@@ -16,41 +16,35 @@ interface InnerProps {
onSuccess: (category: Category) => void;
}
-export const CategoryEditModal = createModal<InnerProps>(
- ({ actions, innerProps }) => {
- const t = useI18n();
- const form = useZodForm(z.object({ name: z.string().min(1) }), {
- initialValues: {
- name: innerProps.category.name,
- },
- });
+export const CategoryEditModal = createModal<InnerProps>(({ actions, innerProps }) => {
+ const t = useI18n();
+ const form = useZodForm(z.object({ name: z.string().min(1) }), {
+ initialValues: {
+ name: innerProps.category.name,
+ },
+ });
- return (
- <form
- onSubmit={form.onSubmit((values) => {
- void innerProps.onSuccess({
- ...innerProps.category,
- name: values.name,
- });
- actions.closeModal();
- })}
- >
- <Stack>
- <TextInput
- label={t("section.category.field.name.label")}
- data-autofocus
- {...form.getInputProps("name")}
- />
- <Group justify="right">
- <Button onClick={actions.closeModal} variant="subtle" color="gray">
- {t("common.action.cancel")}
- </Button>
- <Button type="submit" color="teal">
- {innerProps.submitLabel}
- </Button>
- </Group>
- </Stack>
- </form>
- );
- },
-).withOptions({});
+ return (
+ <form
+ onSubmit={form.onSubmit((values) => {
+ void innerProps.onSuccess({
+ ...innerProps.category,
+ name: values.name,
+ });
+ actions.closeModal();
+ })}
+ >
+ <Stack>
+ <TextInput label={t("section.category.field.name.label")} data-autofocus {...form.getInputProps("name")} />
+ <Group justify="right">
+ <Button onClick={actions.closeModal} variant="subtle" color="gray">
+ {t("common.action.cancel")}
+ </Button>
+ <Button type="submit" color="teal">
+ {innerProps.submitLabel}
+ </Button>
+ </Group>
+ </Stack>
+ </form>
+ );
+}).withOptions({});
diff --git a/apps/nextjs/src/components/board/sections/category/category-menu-actions.tsx b/apps/nextjs/src/components/board/sections/category/category-menu-actions.tsx
index 8106334f7..fc7610deb 100644
--- a/apps/nextjs/src/components/board/sections/category/category-menu-actions.tsx
+++ b/apps/nextjs/src/components/board/sections/category/category-menu-actions.tsx
@@ -11,8 +11,7 @@ import { CategoryEditModal } from "./category-edit-modal";
export const useCategoryMenuActions = (category: CategorySection) => {
const { openModal } = useModalAction(CategoryEditModal);
const { openConfirmModal } = useConfirmModal();
- const { addCategory, moveCategory, removeCategory, renameCategory } =
- useCategoryActions();
+ const { addCategory, moveCategory, removeCategory, renameCategory } = useCategoryActions();
const t = useI18n();
const createCategoryAtPosition = useCallback(
diff --git a/apps/nextjs/src/components/board/sections/category/category-menu.tsx b/apps/nextjs/src/components/board/sections/category/category-menu.tsx
index e82326cda..be67285ff 100644
--- a/apps/nextjs/src/components/board/sections/category/category-menu.tsx
+++ b/apps/nextjs/src/components/board/sections/category/category-menu.tsx
@@ -67,14 +67,8 @@ const useActions = (category: CategorySection) => {
};
const useEditModeActions = (category: CategorySection) => {
- const {
- addCategoryAbove,
- addCategoryBelow,
- moveCategoryUp,
- moveCategoryDown,
- edit,
- remove,
- } = useCategoryMenuActions(category);
+ const { addCategoryAbove, addCategoryBelow, moveCategoryUp, moveCategoryDown, edit, remove } =
+ useCategoryMenuActions(category);
return [
{
diff --git a/apps/nextjs/src/components/board/sections/content.tsx b/apps/nextjs/src/components/board/sections/content.tsx
index 2d042f27b..85c9d35d8 100644
--- a/apps/nextjs/src/components/board/sections/content.tsx
+++ b/apps/nextjs/src/components/board/sections/content.tsx
@@ -5,12 +5,7 @@ import { useMemo } from "react";
import type { RefObject } from "react";
import { ActionIcon, Card, Menu } from "@mantine/core";
import { useElementSize } from "@mantine/hooks";
-import {
- IconDotsVertical,
- IconLayoutKanban,
- IconPencil,
- IconTrash,
-} from "@tabler/icons-react";
+import { IconDotsVertical, IconLayoutKanban, IconPencil, IconTrash } from "@tabler/icons-react";
import combineClasses from "clsx";
import { useAtomValue } from "jotai";
@@ -43,12 +38,7 @@ export const SectionContent = ({ items, refs }: Props) => {
return (
<>
{items.map((item) => (
- <BoardItem
- key={item.id}
- refs={refs}
- item={item}
- opacity={board.opacity}
- />
+ <BoardItem key={item.id} refs={refs} item={item} opacity={board.opacity} />
))}
</>
);
@@ -133,14 +123,9 @@ const ItemMenu = ({ offset, item }: { offset: number; item: Item }) => {
const { openModal } = useModalAction(WidgetEditModal);
const { openConfirmModal } = useConfirmModal();
const isEditMode = useAtomValue(editModeAtom);
- const { updateItemOptions, updateItemIntegrations, removeItem } =
- useItemActions();
- const { data: integrationData, isPending } =
- clientApi.integration.all.useQuery();
- const currentDefinition = useMemo(
- () => widgetImports[item.kind].definition,
- [item.kind],
- );
+ const { updateItemOptions, updateItemIntegrations, removeItem } = useItemActions();
+ const { data: integrationData, isPending } = clientApi.integration.all.useQuery();
+ const currentDefinition = useMemo(() => widgetImports[item.kind].definition, [item.kind]);
if (!isEditMode || isPending) return null;
@@ -164,9 +149,7 @@ const ItemMenu = ({ offset, item }: { offset: number; item: Item }) => {
integrationData: (integrationData ?? []).filter(
(integration) =>
"supportedIntegrations" in currentDefinition &&
- (currentDefinition.supportedIntegrations as string[]).some(
- (kind) => kind === integration.kind,
- ),
+ (currentDefinition.supportedIntegrations as string[]).some((kind) => kind === integration.kind),
),
integrationSupport: "supportedIntegrations" in currentDefinition,
});
@@ -185,34 +168,19 @@ const ItemMenu = ({ offset, item }: { offset: number; item: Item }) => {
return (
<Menu withinPortal withArrow position="right-start" arrowPosition="center">
<Menu.Target>
- <ActionIcon
- variant="transparent"
- pos="absolute"
- top={offset}
- right={offset}
- style={{ zIndex: 1 }}
- >
+ <ActionIcon variant="transparent" pos="absolute" top={offset} right={offset} style={{ zIndex: 1 }}>
<IconDotsVertical />
</ActionIcon>
</Menu.Target>
<Menu.Dropdown miw={128}>
<Menu.Label>{tItem("menu.label.settings")}</Menu.Label>
- <Menu.Item
- leftSection={<IconPencil size={16} />}
- onClick={openEditModal}
- >
+ <Menu.Item leftSection={<IconPencil size={16} />} onClick={openEditModal}>
{tItem("action.edit")}
</Menu.Item>
- <Menu.Item leftSection={<IconLayoutKanban size={16} />}>
- {tItem("action.move")}
- </Menu.Item>
+ <Menu.Item leftSection={<IconLayoutKanban size={16} />}>{tItem("action.move")}</Menu.Item>
<Menu.Divider />
<Menu.Label c="red.6">{t("common.dangerZone")}</Menu.Label>
- <Menu.Item
- c="red.6"
- leftSection={<IconTrash size={16} />}
- onClick={openRemoveModal}
- >
+ <Menu.Item c="red.6" leftSection={<IconTrash size={16} />} onClick={openRemoveModal}>
{tItem("action.remove")}
</Menu.Item>
</Menu.Dropdown>
diff --git a/apps/nextjs/src/components/board/sections/empty-section.tsx b/apps/nextjs/src/components/board/sections/empty-section.tsx
index 268a7ec88..0f011c153 100644
--- a/apps/nextjs/src/components/board/sections/empty-section.tsx
+++ b/apps/nextjs/src/components/board/sections/empty-section.tsx
@@ -19,11 +19,7 @@ export const BoardEmptySection = ({ section, mainRef }: Props) => {
return (
<div
- className={
- section.items.length > 0 || isEditMode
- ? defaultClasses
- : `${defaultClasses} gridstack-empty-wrapper`
- }
+ className={section.items.length > 0 || isEditMode ? defaultClasses : `${defaultClasses} gridstack-empty-wrapper`}
style={{ transitionDuration: "0s" }}
data-empty
data-section-id={section.id}
diff --git a/apps/nextjs/src/components/board/sections/gridstack/init-gridstack.ts b/apps/nextjs/src/components/board/sections/gridstack/init-gridstack.ts
index 310f7aadb..84378fc7f 100644
--- a/apps/nextjs/src/components/board/sections/gridstack/init-gridstack.ts
+++ b/apps/nextjs/src/components/board/sections/gridstack/init-gridstack.ts
@@ -15,20 +15,14 @@ interface InitializeGridstackProps {
sectionColumnCount: number;
}
-export const initializeGridstack = ({
- section,
- refs,
- sectionColumnCount,
-}: InitializeGridstackProps) => {
+export const initializeGridstack = ({ section, refs, sectionColumnCount }: InitializeGridstackProps) => {
if (!refs.wrapper.current) return false;
// initialize gridstack
const newGrid = refs.gridstack;
newGrid.current = GridStack.init(
{
column: sectionColumnCount,
- margin: Math.round(
- Math.max(Math.min(refs.wrapper.current.offsetWidth / 100, 10), 1),
- ),
+ margin: Math.round(Math.max(Math.min(refs.wrapper.current.offsetWidth / 100, 10), 1)),
cellHeight: 128,
float: true,
alwaysShowResizeHandle: true,
diff --git a/apps/nextjs/src/components/board/sections/gridstack/use-gridstack.ts b/apps/nextjs/src/components/board/sections/gridstack/use-gridstack.ts
index 0db33be04..36673d95b 100644
--- a/apps/nextjs/src/components/board/sections/gridstack/use-gridstack.ts
+++ b/apps/nextjs/src/components/board/sections/gridstack/use-gridstack.ts
@@ -2,17 +2,10 @@ import type { MutableRefObject, RefObject } from "react";
import { createRef, useCallback, useEffect, useMemo, useRef } from "react";
import { useAtomValue } from "jotai";
-import type {
- GridItemHTMLElement,
- GridStack,
- GridStackNode,
-} from "@homarr/gridstack";
+import type { GridItemHTMLElement, GridStack, GridStackNode } from "@homarr/gridstack";
import type { Section } from "~/app/[locale]/boards/_types";
-import {
- useMarkSectionAsReady,
- useRequiredBoard,
-} from "~/app/[locale]/boards/(content)/_context";
+import { useMarkSectionAsReady, useRequiredBoard } from "~/app/[locale]/boards/(content)/_context";
import { editModeAtom } from "../../editMode";
import { useItemActions } from "../../items/item-actions";
import { initializeGridstack } from "./init-gridstack";
@@ -32,10 +25,7 @@ interface UseGridstackProps {
mainRef?: RefObject<HTMLDivElement>;
}
-export const useGridstack = ({
- section,
- mainRef,
-}: UseGridstackProps): UseGristackReturnType => {
+export const useGridstack = ({ section, mainRef }: UseGridstackProps): UseGristackReturnType => {
const isEditMode = useAtomValue(editModeAtom);
const markAsReady = useMarkSectionAsReady();
const { moveAndResizeItem, moveItemToSection } = useItemActions();
@@ -157,10 +147,7 @@ interface UseCssVariableConfiguration {
* @param mainRef reference to the main div wrapping all sections
* @param gridRef reference to the gridstack object
*/
-const useCssVariableConfiguration = ({
- mainRef,
- gridRef,
-}: UseCssVariableConfiguration) => {
+const useCssVariableConfiguration = ({ mainRef, gridRef }: UseCssVariableConfiguration) => {
const board = useRequiredBoard();
// Get reference to the :root element
@@ -177,10 +164,7 @@ const useCssVariableConfiguration = ({
if (!mainRef?.current) return;
const widgetWidth = mainRef.current.clientWidth / board.columnCount;
// widget width is used to define sizes of gridstack items within global.scss
- root?.style.setProperty(
- "--gridstack-widget-width",
- widgetWidth.toString(),
- );
+ root?.style.setProperty("--gridstack-widget-width", widgetWidth.toString());
gridRef.current?.cellHeight(widgetWidth);
};
onResize();
@@ -194,9 +178,6 @@ const useCssVariableConfiguration = ({
// Define column count by using the sectionColumnCount
useEffect(() => {
- root?.style.setProperty(
- "--gridstack-column-count",
- board.columnCount.toString(),
- );
+ root?.style.setProperty("--gridstack-column-count", board.columnCount.toString());
}, [board.columnCount, root]);
};
diff --git a/apps/nextjs/src/components/icons/picker/icon-picker.tsx b/apps/nextjs/src/components/icons/picker/icon-picker.tsx
index b23027937..1406b20e5 100644
--- a/apps/nextjs/src/components/icons/picker/icon-picker.tsx
+++ b/apps/nextjs/src/components/icons/picker/icon-picker.tsx
@@ -1,14 +1,6 @@
import type { FocusEventHandler } from "react";
import { useState } from "react";
-import {
- Combobox,
- Group,
- Image,
- InputBase,
- Skeleton,
- Text,
- useCombobox,
-} from "@mantine/core";
+import { Combobox, Group, Image, InputBase, Skeleton, Text, useCombobox } from "@mantine/core";
import { clientApi } from "@homarr/api/client";
import { useScopedI18n } from "@homarr/translation/client";
@@ -21,13 +13,7 @@ interface IconPickerProps {
onBlur?: FocusEventHandler;
}
-export const IconPicker = ({
- initialValue,
- onChange,
- error,
- onFocus,
- onBlur,
-}: IconPickerProps) => {
+export const IconPicker = ({ initialValue, onChange, error, onFocus, onBlur }: IconPickerProps) => {
const [value, setValue] = useState<string>(initialValue ?? "");
const [search, setSearch] = useState(initialValue ?? "");
@@ -43,10 +29,7 @@ export const IconPicker = ({
const notNullableData = data?.icons ?? [];
- const totalOptions = notNullableData.reduce(
- (acc, group) => acc + group.icons.length,
- 0,
- );
+ const totalOptions = notNullableData.reduce((acc, group) => acc + group.icons.length, 0);
const groups = notNullableData.map((group) => {
const options = group.icons.map((item) => (
@@ -104,9 +87,7 @@ export const IconPicker = ({
<Combobox.Dropdown>
<Combobox.Header>
- <Text c="dimmed">
- {t("iconPicker.header", { countIcons: data?.countIcons })}
- </Text>
+ <Text c="dimmed">{t("iconPicker.header", { countIcons: data?.countIcons })}</Text>
</Combobox.Header>
<Combobox.Options mah={350} style={{ overflowY: "auto" }}>
{totalOptions > 0 ? (
@@ -117,11 +98,7 @@ export const IconPicker = ({
Array(15)
.fill(0)
.map((_, index: number) => (
- <Combobox.Option
- value={`skeleton-${index}`}
- key={index}
- disabled
- >
+ <Combobox.Option value={`skeleton-${index}`} key={index} disabled>
<Skeleton height={25} visible />
</Combobox.Option>
))
diff --git a/apps/nextjs/src/components/language/language-combobox.tsx b/apps/nextjs/src/components/language/language-combobox.tsx
index 0b7fbb3fc..6bd362591 100644
--- a/apps/nextjs/src/components/language/language-combobox.tsx
+++ b/apps/nextjs/src/components/language/language-combobox.tsx
@@ -51,11 +51,7 @@ export const LanguageCombobox = () => {
<Combobox.Options>
{supportedLanguages.map((languageKey) => (
<Combobox.Option value={languageKey} key={languageKey}>
- <OptionItem
- currentLocale={currentLocale}
- localeKey={languageKey}
- showCheck
- />
+ <OptionItem currentLocale={currentLocale} localeKey={languageKey} showCheck />
</Combobox.Option>
))}
</Combobox.Options>
@@ -76,9 +72,7 @@ const OptionItem = ({
return (
<Group wrap="nowrap" justify="space-between">
<Group wrap="nowrap">
- <span
- className={`fi fi-${localeAttributes[localeKey].flagIcon} ${classes.flagIcon}`}
- ></span>
+ <span className={`fi fi-${localeAttributes[localeKey].flagIcon} ${classes.flagIcon}`}></span>
<Group wrap="nowrap" gap="xs">
<Text>{localeAttributes[localeKey].name}</Text>
<Text size="xs" c="dimmed" inherit>
@@ -86,9 +80,7 @@ const OptionItem = ({
</Text>
</Group>
</Group>
- {showCheck && localeKey === currentLocale && (
- <IconCheck color="currentColor" size={16} />
- )}
+ {showCheck && localeKey === currentLocale && <IconCheck color="currentColor" size={16} />}
</Group>
);
};
diff --git a/apps/nextjs/src/components/layout/background.tsx b/apps/nextjs/src/components/layout/background.tsx
index c6158dfca..1c5b7c8b4 100644
--- a/apps/nextjs/src/components/layout/background.tsx
+++ b/apps/nextjs/src/components/layout/background.tsx
@@ -4,10 +4,7 @@ import type { AppShellProps } from "@mantine/core";
import { useOptionalBoard } from "~/app/[locale]/boards/(content)/_context";
const supportedVideoFormats = ["mp4", "webm", "ogg"];
-const isVideo = (url: string) =>
- supportedVideoFormats.some((format) =>
- url.toLowerCase().endsWith(`.${format}`),
- );
+const isVideo = (url: string) => supportedVideoFormats.some((format) => url.toLowerCase().endsWith(`.${format}`));
export const useOptionalBackgroundProps = (): Partial<AppShellProps> => {
const board = useOptionalBoard();
diff --git a/apps/nextjs/src/components/layout/header.tsx b/apps/nextjs/src/components/layout/header.tsx
index 996d78ab5..dd5d51243 100644
--- a/apps/nextjs/src/components/layout/header.tsx
+++ b/apps/nextjs/src/components/layout/header.tsx
@@ -26,13 +26,7 @@ export const MainHeader = ({ logo, actions, hasNavigation = true }: Props) => {
</UnstyledButton>
</Group>
<DesktopSearchInput />
- <Group
- h="100%"
- align="center"
- justify="end"
- style={{ flex: 1 }}
- wrap="nowrap"
- >
+ <Group h="100%" align="center" justify="end" style={{ flex: 1 }} wrap="nowrap">
{actions}
<MobileSearchButton />
<UserButton />
diff --git a/apps/nextjs/src/components/layout/header/burger.tsx b/apps/nextjs/src/components/layout/header/burger.tsx
index 3622ba116..03ad0851a 100644
--- a/apps/nextjs/src/components/layout/header/burger.tsx
+++ b/apps/nextjs/src/components/layout/header/burger.tsx
@@ -9,12 +9,7 @@ export const navigationCollapsedAtom = atom(true);
export const ClientBurger = () => {
const [collapsed, setCollapsed] = useAtom(navigationCollapsedAtom);
- const toggle = useCallback(
- () => setCollapsed((collapsed) => !collapsed),
- [setCollapsed],
- );
+ const toggle = useCallback(() => setCollapsed((collapsed) => !collapsed), [setCollapsed]);
- return (
- <Burger opened={!collapsed} onClick={toggle} hiddenFrom="sm" size="sm" />
- );
+ return <Burger opened={!collapsed} onClick={toggle} hiddenFrom="sm" size="sm" />;
};
diff --git a/apps/nextjs/src/components/layout/header/button.tsx b/apps/nextjs/src/components/layout/header/button.tsx
index 20636d8a3..0604c137b 100644
--- a/apps/nextjs/src/components/layout/header/button.tsx
+++ b/apps/nextjs/src/components/layout/header/button.tsx
@@ -23,24 +23,22 @@ const headerButtonActionIconProps: ActionIconProps = {
};
// eslint-disable-next-line react/display-name
-export const HeaderButton = forwardRef<HTMLButtonElement, HeaderButtonProps>(
- (props, ref) => {
- if ("href" in props) {
- return (
- <ActionIcon
- ref={ref as ForwardedRef<HTMLAnchorElement>}
- component={Link}
- {...props}
- {...headerButtonActionIconProps}
- >
- {props.children}
- </ActionIcon>
- );
- }
+export const HeaderButton = forwardRef<HTMLButtonElement, HeaderButtonProps>((props, ref) => {
+ if ("href" in props) {
return (
- <ActionIcon ref={ref} {...props} {...headerButtonActionIconProps}>
+ <ActionIcon
+ ref={ref as ForwardedRef<HTMLAnchorElement>}
+ component={Link}
+ {...props}
+ {...headerButtonActionIconProps}
+ >
{props.children}
</ActionIcon>
);
- },
-);
+ }
+ return (
+ <ActionIcon ref={ref} {...props} {...headerButtonActionIconProps}>
+ {props.children}
+ </ActionIcon>
+ );
+});
diff --git a/apps/nextjs/src/components/layout/logo/board-logo.tsx b/apps/nextjs/src/components/layout/logo/board-logo.tsx
index 584c9a01a..096709431 100644
--- a/apps/nextjs/src/components/layout/logo/board-logo.tsx
+++ b/apps/nextjs/src/components/layout/logo/board-logo.tsx
@@ -28,10 +28,7 @@ interface CommonLogoWithTitleProps {
hideTitleOnMobile?: boolean;
}
-export const BoardLogoWithTitle = ({
- size,
- hideTitleOnMobile,
-}: CommonLogoWithTitleProps) => {
+export const BoardLogoWithTitle = ({ size, hideTitleOnMobile }: CommonLogoWithTitleProps) => {
const board = useRequiredBoard();
const imageOptions = useImageOptions();
return (
diff --git a/apps/nextjs/src/components/layout/logo/homarr-logo.tsx b/apps/nextjs/src/components/layout/logo/homarr-logo.tsx
index 5d863ec71..bdfe0086f 100644
--- a/apps/nextjs/src/components/layout/logo/homarr-logo.tsx
+++ b/apps/nextjs/src/components/layout/logo/homarr-logo.tsx
@@ -14,16 +14,12 @@ const imageOptions = {
shouldUseNextImage: true,
};
-export const HomarrLogo = ({ size }: LogoProps) => (
- <Logo size={size} {...imageOptions} />
-);
+export const HomarrLogo = ({ size }: LogoProps) => <Logo size={size} {...imageOptions} />;
interface CommonLogoWithTitleProps {
size: LogoWithTitleProps["size"];
}
export const HomarrLogoWithTitle = ({ size }: CommonLogoWithTitleProps) => {
- return (
- <LogoWithTitle size={size} title={homarrPageTitle} image={imageOptions} />
- );
+ return <LogoWithTitle size={size} title={homarrPageTitle} image={imageOptions} />;
};
diff --git a/apps/nextjs/src/components/layout/logo/logo.tsx b/apps/nextjs/src/components/layout/logo/logo.tsx
index f8ba3757e..beb3f493c 100644
--- a/apps/nextjs/src/components/layout/logo/logo.tsx
+++ b/apps/nextjs/src/components/layout/logo/logo.tsx
@@ -9,12 +9,7 @@ interface LogoProps {
shouldUseNextImage?: boolean;
}
-export const Logo = ({
- size = 60,
- shouldUseNextImage = false,
- src,
- alt,
-}: LogoProps) =>
+export const Logo = ({ size = 60, shouldUseNextImage = false, src, alt }: LogoProps) =>
shouldUseNextImage ? (
<Image src={src} alt={alt} width={size} height={size} />
) : (
@@ -36,22 +31,13 @@ export interface LogoWithTitleProps {
hideTitleOnMobile?: boolean;
}
-export const LogoWithTitle = ({
- size,
- title,
- image,
- hideTitleOnMobile,
-}: LogoWithTitleProps) => {
+export const LogoWithTitle = ({ size, title, image, hideTitleOnMobile }: LogoWithTitleProps) => {
const { logoSize, titleOrder } = logoWithTitleSizes[size];
return (
<Group gap="xs" wrap="nowrap">
<Logo {...image} size={logoSize} />
- <Title
- order={titleOrder}
- visibleFrom={hideTitleOnMobile ? "sm" : undefined}
- textWrap="nowrap"
- >
+ <Title order={titleOrder} visibleFrom={hideTitleOnMobile ? "sm" : undefined} textWrap="nowrap">
{title}
</Title>
</Group>
diff --git a/apps/nextjs/src/components/layout/navigation-link.tsx b/apps/nextjs/src/components/layout/navigation-link.tsx
index e0a9f5c60..c65f9381c 100644
--- a/apps/nextjs/src/components/layout/navigation-link.tsx
+++ b/apps/nextjs/src/components/layout/navigation-link.tsx
@@ -6,11 +6,7 @@ import { usePathname } from "next/navigation";
import { NavLink } from "@mantine/core";
export const CommonNavLink = (props: ClientNavigationLink) =>
- "href" in props ? (
- <NavLinkHref {...props} />
- ) : (
- <NavLinkWithItems {...props} />
- );
+ "href" in props ? <NavLinkHref {...props} /> : <NavLinkWithItems {...props} />;
const NavLinkHref = (props: NavigationLinkHref) => {
const pathname = usePathname();
diff --git a/apps/nextjs/src/components/layout/navigation.tsx b/apps/nextjs/src/components/layout/navigation.tsx
index 751c55cb1..c9a53aaad 100644
--- a/apps/nextjs/src/components/layout/navigation.tsx
+++ b/apps/nextjs/src/components/layout/navigation.tsx
@@ -11,11 +11,7 @@ interface MainNavigationProps {
links: NavigationLink[];
}
-export const MainNavigation = ({
- headerSection,
- footerSection,
- links,
-}: MainNavigationProps) => {
+export const MainNavigation = ({ headerSection, footerSection, links }: MainNavigationProps) => {
return (
<AppShellNavbar p="md">
{headerSection && <AppShellSection>{headerSection}</AppShellSection>}
diff --git a/apps/nextjs/src/components/manage/boards/add-board-modal.tsx b/apps/nextjs/src/components/manage/boards/add-board-modal.tsx
index ffb67f80e..bdc225a1f 100644
--- a/apps/nextjs/src/components/manage/boards/add-board-modal.tsx
+++ b/apps/nextjs/src/components/manage/boards/add-board-modal.tsx
@@ -12,50 +12,41 @@ interface InnerProps {
onSuccess: ({ name }: { name: string }) => Promise<void>;
}
-export const AddBoardModal = createModal<InnerProps>(
- ({ actions, innerProps }) => {
- const t = useI18n();
- const form = useZodForm(
- z.object({
- name: boardSchemas.byName.shape.name.refine(
- (value) => !innerProps.boardNames.includes(value),
- {
- params: createCustomErrorParams("boardAlreadyExists"),
- },
- ),
+export const AddBoardModal = createModal<InnerProps>(({ actions, innerProps }) => {
+ const t = useI18n();
+ const form = useZodForm(
+ z.object({
+ name: boardSchemas.byName.shape.name.refine((value) => !innerProps.boardNames.includes(value), {
+ params: createCustomErrorParams("boardAlreadyExists"),
}),
- {
- initialValues: {
- name: "",
- },
+ }),
+ {
+ initialValues: {
+ name: "",
},
- );
+ },
+ );
- return (
- <form
- onSubmit={form.onSubmit((values) => {
- void innerProps.onSuccess(values);
- actions.closeModal();
- })}
- >
- <Stack>
- <TextInput
- label={t("board.field.name.label")}
- data-autofocus
- {...form.getInputProps("name")}
- />
- <Group justify="right">
- <Button onClick={actions.closeModal} variant="subtle" color="gray">
- {t("common.action.cancel")}
- </Button>
- <Button disabled={!form.isValid()} type="submit" color="teal">
- {t("common.action.create")}
- </Button>
- </Group>
- </Stack>
- </form>
- );
- },
-).withOptions({
+ return (
+ <form
+ onSubmit={form.onSubmit((values) => {
+ void innerProps.onSuccess(values);
+ actions.closeModal();
+ })}
+ >
+ <Stack>
+ <TextInput label={t("board.field.name.label")} data-autofocus {...form.getInputProps("name")} />
+ <Group justify="right">
+ <Button onClick={actions.closeModal} variant="subtle" color="gray">
+ {t("common.action.cancel")}
+ </Button>
+ <Button disabled={!form.isValid()} type="submit" color="teal">
+ {t("common.action.create")}
+ </Button>
+ </Group>
+ </Stack>
+ </form>
+ );
+}).withOptions({
defaultTitle: (t) => t("management.page.board.action.new.label"),
});
diff --git a/apps/nextjs/src/components/manage/danger-zone.tsx b/apps/nextjs/src/components/manage/danger-zone.tsx
index 7359ca62e..5c515b4a0 100644
--- a/apps/nextjs/src/components/manage/danger-zone.tsx
+++ b/apps/nextjs/src/components/manage/danger-zone.tsx
@@ -1,13 +1,5 @@
import { Fragment } from "react";
-import {
- Card,
- CardSection,
- Divider,
- Group,
- Stack,
- Text,
- Title,
-} from "@mantine/core";
+import { Card, CardSection, Divider, Group, Stack, Text, Title } from "@mantine/core";
import { getI18n } from "@homarr/translation/server";
@@ -49,11 +41,7 @@ interface DangerZoneItemProps {
action: React.ReactNode;
}
-export const DangerZoneItem = ({
- label,
- description,
- action,
-}: DangerZoneItemProps) => {
+export const DangerZoneItem = ({ label, description, action }: DangerZoneItemProps) => {
return (
<Group justify="space-between" px="md">
<Stack gap={0}>
diff --git a/apps/nextjs/src/components/user-avatar-menu.tsx b/apps/nextjs/src/components/user-avatar-menu.tsx
index 06033c9a0..0cd5e0726 100644
--- a/apps/nextjs/src/components/user-avatar-menu.tsx
+++ b/apps/nextjs/src/components/user-avatar-menu.tsx
@@ -4,13 +4,7 @@ import type { ReactNode } from "react";
import { useCallback, useEffect } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
-import {
- Center,
- Menu,
- Stack,
- Text,
- useMantineColorScheme,
-} from "@mantine/core";
+import { Center, Menu, Stack, Text, useMantineColorScheme } from "@mantine/core";
import { useTimeout } from "@mantine/hooks";
import {
IconCheck,
@@ -41,8 +35,7 @@ export const UserAvatarMenu = ({ children }: UserAvatarMenuProps) => {
const ColorSchemeIcon = colorScheme === "dark" ? IconSun : IconMoon;
- const colorSchemeText =
- colorScheme === "dark" ? t("switchToLightMode") : t("switchToDarkMode");
+ const colorSchemeText = colorScheme === "dark" ? t("switchToLightMode") : t("switchToDarkMode");
const session = useSession();
const router = useRouter();
@@ -63,17 +56,10 @@ export const UserAvatarMenu = ({ children }: UserAvatarMenuProps) => {
return (
<Menu width={300} withArrow withinPortal>
<Menu.Dropdown>
- <Menu.Item
- onClick={toggleColorScheme}
- leftSection={<ColorSchemeIcon size="1rem" />}
- >
+ <Menu.Item onClick={toggleColorScheme} leftSection={<ColorSchemeIcon size="1rem" />}>
{colorSchemeText}
</Menu.Item>
- <Menu.Item
- component={Link}
- href="/boards"
- leftSection={<IconHome size="1rem" />}
- >
+ <Menu.Item component={Link} href="/boards" leftSection={<IconHome size="1rem" />}>
{t("homeBoard")}
</Menu.Item>
<Menu.Divider />
@@ -92,29 +78,18 @@ export const UserAvatarMenu = ({ children }: UserAvatarMenuProps) => {
{t("preferences")}
</Menu.Item>
- <Menu.Item
- component={Link}
- href="/manage"
- leftSection={<IconTool size="1rem" />}
- >
+ <Menu.Item component={Link} href="/manage" leftSection={<IconTool size="1rem" />}>
{t("management")}
</Menu.Item>
</>
)}
<Menu.Divider />
{session.status === "authenticated" ? (
- <Menu.Item
- onClick={handleSignout}
- leftSection={<IconLogout size="1rem" />}
- color="red"
- >
+ <Menu.Item onClick={handleSignout} leftSection={<IconLogout size="1rem" />} color="red">
{t("logout")}
</Menu.Item>
) : (
- <Menu.Item
- onClick={() => router.push("/auth/login")}
- leftSection={<IconLogin size="1rem" />}
- >
+ <Menu.Item onClick={() => router.push("/auth/login")} leftSection={<IconLogin size="1rem" />}>
{t("login")}
</Menu.Item>
)}
@@ -124,30 +99,28 @@ export const UserAvatarMenu = ({ children }: UserAvatarMenuProps) => {
);
};
-const LogoutModal = createModal<{ onTimeout: () => void }>(
- ({ actions, innerProps }) => {
- const t = useScopedI18n("common.userAvatar.menu");
- const { start } = useTimeout(() => {
- actions.closeModal();
- innerProps.onTimeout();
- }, 1500);
-
- useEffect(() => {
- start();
- }, [start]);
-
- return (
- <Center h={200 - 2 * 16}>
- <Stack align="center" c="green">
- <IconCheck size={50} />
- <Text ta="center" fw="bold">
- {t("loggedOut")}
- </Text>
- </Stack>
- </Center>
- );
- },
-).withOptions({
+const LogoutModal = createModal<{ onTimeout: () => void }>(({ actions, innerProps }) => {
+ const t = useScopedI18n("common.userAvatar.menu");
+ const { start } = useTimeout(() => {
+ actions.closeModal();
+ innerProps.onTimeout();
+ }, 1500);
+
+ useEffect(() => {
+ start();
+ }, [start]);
+
+ return (
+ <Center h={200 - 2 * 16}>
+ <Stack align="center" c="green">
+ <IconCheck size={50} />
+ <Text ta="center" fw="bold">
+ {t("loggedOut")}
+ </Text>
+ </Stack>
+ </Center>
+ );
+}).withOptions({
centered: true,
withCloseButton: false,
transitionProps: {
diff --git a/apps/nextjs/src/components/user-avatar.tsx b/apps/nextjs/src/components/user-avatar.tsx
index dd30dc647..d75606caf 100644
--- a/apps/nextjs/src/components/user-avatar.tsx
+++ b/apps/nextjs/src/components/user-avatar.tsx
@@ -17,17 +17,7 @@ export const UserAvatar = async ({ size }: UserAvatarProps) => {
if (!currentSession?.user) return <Avatar {...commonProps} />;
if (currentSession.user.image)
- return (
- <Avatar
- {...commonProps}
- src={currentSession.user.image}
- alt={currentSession.user.name!}
- />
- );
+ return <Avatar {...commonProps} src={currentSession.user.image} alt={currentSession.user.name!} />;
- return (
- <Avatar {...commonProps}>
- {currentSession.user.name!.substring(0, 2).toUpperCase()}
- </Avatar>
- );
+ return <Avatar {...commonProps}>{currentSession.user.name!.substring(0, 2).toUpperCase()}</Avatar>;
};
diff --git a/apps/nextjs/src/env.mjs b/apps/nextjs/src/env.mjs
index 14e02551c..2e4452340 100644
--- a/apps/nextjs/src/env.mjs
+++ b/apps/nextjs/src/env.mjs
@@ -12,9 +12,7 @@ export const env = createEnv({
.optional()
.transform((url) => (url ? `https://${url}` : undefined)),
PORT: z.coerce.number().default(3000),
- NODE_ENV: z
- .enum(["development", "production", "test"])
- .default("development"),
+ NODE_ENV: z.enum(["development", "production", "test"]).default("development"),
},
/**
* Specify your server-side environment variables schema here. This way you can ensure the app isn't
@@ -25,9 +23,7 @@ export const env = createEnv({
// If the DB_HOST is set, the DB_URL is optional
DB_URL: isUsingDbHost ? z.string().optional() : z.string(),
DB_HOST: isUsingDbUrl ? z.string().optional() : z.string(),
- DB_PORT: isUsingDbUrl
- ? z.number().optional()
- : z.number().min(1).default(3306),
+ DB_PORT: isUsingDbUrl ? z.number().optional() : z.number().min(1).default(3306),
DB_USER: isUsingDbCredentials ? z.string() : z.string().optional(),
DB_PASSWORD: isUsingDbCredentials ? z.string() : z.string().optional(),
DB_NAME: isUsingDbUrl ? z.string().optional() : z.string(),
@@ -56,7 +52,5 @@ export const env = createEnv({
// NEXT_PUBLIC_CLIENTVAR: process.env.NEXT_PUBLIC_CLIENTVAR,
},
skipValidation:
- Boolean(process.env.CI) ||
- Boolean(process.env.SKIP_ENV_VALIDATION) ||
- process.env.npm_lifecycle_event === "lint",
+ Boolean(process.env.CI) || Boolean(process.env.SKIP_ENV_VALIDATION) || process.env.npm_lifecycle_event === "lint",
});
diff --git a/apps/nextjs/src/versions/package-reader.ts b/apps/nextjs/src/versions/package-reader.ts
index 0862c711c..c61da286b 100644
--- a/apps/nextjs/src/versions/package-reader.ts
+++ b/apps/nextjs/src/versions/package-reader.ts
@@ -10,14 +10,9 @@ const getDependenciesAsync = async (): Promise<PackageJsonDependencies> => {
cwd: "../../",
absolute: true,
});
- const packageContents = await Promise.all(
- pathNames.map(async (path) => await fsPromises.readFile(path, "utf-8")),
- );
+ const packageContents = await Promise.all(pathNames.map(async (path) => await fsPromises.readFile(path, "utf-8")));
const packageDependencies = packageContents
- .map(
- (packageContent) =>
- (JSON.parse(packageContent) as PackageJson).dependencies,
- )
+ .map((packageContent) => (JSON.parse(packageContent) as PackageJson).dependencies)
.filter((dependencies) => dependencies !== undefined);
let dependencies = {};
diff --git a/apps/tasks/src/jobs/icons-updater.ts b/apps/tasks/src/jobs/icons-updater.ts
index 820b3602c..7fd274dd0 100644
--- a/apps/tasks/src/jobs/icons-updater.ts
+++ b/apps/tasks/src/jobs/icons-updater.ts
@@ -43,9 +43,7 @@ export const iconsUpdaterJob = createCronJob(EVERY_WEEK, {
continue;
}
- const repositoryInDb = databaseIconGroups.find(
- (dbIconGroup) => dbIconGroup.slug === repositoryIconGroup.slug,
- );
+ const repositoryInDb = databaseIconGroups.find((dbIconGroup) => dbIconGroup.slug === repositoryIconGroup.slug);
const repositoryIconGroupId: string = repositoryInDb?.id ?? createId();
if (!repositoryInDb?.id) {
newIconRepositories.push({
@@ -55,11 +53,7 @@ export const iconsUpdaterJob = createCronJob(EVERY_WEEK, {
}
for (const icon of repositoryIconGroup.icons) {
- if (
- databaseIconGroups
- .flatMap((group) => group.icons)
- .some((dbIcon) => dbIcon.checksum === icon.checksum)
- ) {
+ if (databaseIconGroups.flatMap((group) => group.icons).some((dbIcon) => dbIcon.checksum === icon.checksum)) {
skippedChecksums.push(icon.checksum);
continue;
}
@@ -99,7 +93,5 @@ export const iconsUpdaterJob = createCronJob(EVERY_WEEK, {
countDeleted += deadIcons.length;
});
- logger.info(
- `Updated database within ${stopWatch.getElapsedInHumanWords()} (-${countDeleted}, +${countInserted})`,
- );
+ logger.info(`Updated database within ${stopWatch.getElapsedInHumanWords()} (-${countDeleted}, +${countInserted})`);
});
diff --git a/apps/tasks/src/lib/cron-job/creator.ts b/apps/tasks/src/lib/cron-job/creator.ts
index 8f7b304be..1dcb59fcc 100644
--- a/apps/tasks/src/lib/cron-job/creator.ts
+++ b/apps/tasks/src/lib/cron-job/creator.ts
@@ -6,10 +6,7 @@ interface CreateCronJobOptions {
runOnStart?: boolean;
}
-export const createCronJob = (
- cronExpression: string,
- options: CreateCronJobOptions = { runOnStart: false },
-) => {
+export const createCronJob = (cronExpression: string, options: CreateCronJobOptions = { runOnStart: false }) => {
return {
withCallback: (callback: () => MaybePromise<void>) => {
if (options.runOnStart) {
diff --git a/apps/tasks/src/lib/cron-job/group.ts b/apps/tasks/src/lib/cron-job/group.ts
index 17b7ff204..0854259df 100644
--- a/apps/tasks/src/lib/cron-job/group.ts
+++ b/apps/tasks/src/lib/cron-job/group.ts
@@ -3,10 +3,7 @@ import { objectEntries } from "@homarr/common";
import type { createCronJob } from "./creator";
import { jobRegistry } from "./registry";
-type Jobs = Record<
- string,
- ReturnType<ReturnType<typeof createCronJob>["withCallback"]>
->;
+type Jobs = Record<string, ReturnType<ReturnType<typeof createCronJob>["withCallback"]>>;
export const createJobGroup = <TJobs extends Jobs>(jobs: TJobs) => {
for (const [name, job] of objectEntries(jobs)) {
diff --git a/apps/tasks/src/lib/queue/client.ts b/apps/tasks/src/lib/queue/client.ts
index 6b65885e0..b67cb968d 100644
--- a/apps/tasks/src/lib/queue/client.ts
+++ b/apps/tasks/src/lib/queue/client.ts
@@ -11,10 +11,7 @@ interface Queue<TInput extends z.ZodType = z.ZodType> {
inputValidator: TInput;
}
-type Queues = Record<
- string,
- ReturnType<ReturnType<typeof createQueue>["withCallback"]>
->;
+type Queues = Record<string, ReturnType<ReturnType<typeof createQueue>["withCallback"]>>;
export const createQueueClient = <TQueues extends Queues>(queues: TQueues) => {
const queueRegistry = new Map<string, Queue>();
@@ -31,10 +28,7 @@ export const createQueueClient = <TQueues extends Queues>(queues: TQueues) => {
queueRegistry,
client: objectKeys(queues).reduce(
(acc, name) => {
- acc[name] = async (
- data: z.infer<TQueues[typeof name]["_input"]>,
- options,
- ) => {
+ acc[name] = async (data: z.infer<TQueues[typeof name]["_input"]>, options) => {
if (typeof name !== "string") return;
const queue = queueRegistry.get(name);
if (!queue) return;
@@ -42,10 +36,7 @@ export const createQueueClient = <TQueues extends Queues>(queues: TQueues) => {
await queueChannel.addAsync({
name,
data,
- executionDate:
- typeof options === "object" && options.executionDate
- ? options.executionDate
- : new Date(),
+ executionDate: typeof options === "object" && options.executionDate ? options.executionDate : new Date(),
});
};
return acc;
diff --git a/apps/tasks/src/seed-server-settings.ts b/apps/tasks/src/seed-server-settings.ts
index 56ad3980a..885d4e64c 100644
--- a/apps/tasks/src/seed-server-settings.ts
+++ b/apps/tasks/src/seed-server-settings.ts
@@ -4,19 +4,14 @@ import { db } from "@homarr/db";
import { serverSettings } from "@homarr/db/schema/sqlite";
import { logger } from "@homarr/log";
-import {
- defaultServerSettings,
- defaultServerSettingsKeys,
-} from "../../../packages/server-settings";
+import { defaultServerSettings, defaultServerSettingsKeys } from "../../../packages/server-settings";
export const seedServerSettingsAsync = async () => {
const serverSettingsData = await db.query.serverSettings.findMany();
let insertedSettingsCount = 0;
for (const settingsKey of defaultServerSettingsKeys) {
- if (
- serverSettingsData.some((setting) => setting.settingKey === settingsKey)
- ) {
+ if (serverSettingsData.some((setting) => setting.settingKey === settingsKey)) {
return;
}
diff --git a/apps/websocket/src/main.ts b/apps/websocket/src/main.ts
index 0b4e8d166..ee742c58c 100644
--- a/apps/websocket/src/main.ts
+++ b/apps/websocket/src/main.ts
@@ -18,11 +18,7 @@ const handler = applyWSSHandler({
createContext: async ({ req }) => {
try {
const headers = Object.entries(req.headers).map(
- ([key, value]) =>
- [key, typeof value === "string" ? value : value?.[0]] as [
- string,
- string,
- ],
+ ([key, value]) => [key, typeof value === "string" ? value : value?.[0]] as [string, string],
);
const nextHeaders = new Headers(headers);
@@ -46,13 +42,9 @@ const handler = applyWSSHandler({
});
wss.on("connection", (websocket, incomingMessage) => {
- logger.info(
- `➕ Connection (${wss.clients.size}) ${incomingMessage.method} ${incomingMessage.url}`,
- );
+ logger.info(`➕ Connection (${wss.clients.size}) ${incomingMessage.method} ${incomingMessage.url}`);
websocket.once("close", (code, reason) => {
- logger.info(
- `➖ Connection (${wss.clients.size}) ${code} ${reason.toString()}`,
- );
+ logger.info(`➖ Connection (${wss.clients.size}) ${code} ${reason.toString()}`);
});
});
logger.info("✅ WebSocket Server listening on ws://localhost:3001");
diff --git a/packages/api/src/router/app.ts b/packages/api/src/router/app.ts
index 24198bf04..38171a946 100644
--- a/packages/api/src/router/app.ts
+++ b/packages/api/src/router/app.ts
@@ -22,60 +22,52 @@ export const appRouter = createTRPCRouter({
orderBy: asc(apps.name),
});
}),
- byId: publicProcedure
- .input(validation.app.byId)
- .query(async ({ ctx, input }) => {
- const app = await ctx.db.query.apps.findFirst({
- where: eq(apps.id, input.id),
+ byId: publicProcedure.input(validation.app.byId).query(async ({ ctx, input }) => {
+ const app = await ctx.db.query.apps.findFirst({
+ where: eq(apps.id, input.id),
+ });
+
+ if (!app) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "App not found",
});
+ }
+
+ return app;
+ }),
+ create: publicProcedure.input(validation.app.manage).mutation(async ({ ctx, input }) => {
+ await ctx.db.insert(apps).values({
+ id: createId(),
+ name: input.name,
+ description: input.description,
+ iconUrl: input.iconUrl,
+ href: input.href,
+ });
+ }),
+ update: publicProcedure.input(validation.app.edit).mutation(async ({ ctx, input }) => {
+ const app = await ctx.db.query.apps.findFirst({
+ where: eq(apps.id, input.id),
+ });
- if (!app) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "App not found",
- });
- }
+ if (!app) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "App not found",
+ });
+ }
- return app;
- }),
- create: publicProcedure
- .input(validation.app.manage)
- .mutation(async ({ ctx, input }) => {
- await ctx.db.insert(apps).values({
- id: createId(),
+ await ctx.db
+ .update(apps)
+ .set({
name: input.name,
description: input.description,
iconUrl: input.iconUrl,
href: input.href,
- });
- }),
- update: publicProcedure
- .input(validation.app.edit)
- .mutation(async ({ ctx, input }) => {
- const app = await ctx.db.query.apps.findFirst({
- where: eq(apps.id, input.id),
- });
-
- if (!app) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "App not found",
- });
- }
-
- await ctx.db
- .update(apps)
- .set({
- name: input.name,
- description: input.description,
- iconUrl: input.iconUrl,
- href: input.href,
- })
- .where(eq(apps.id, input.id));
- }),
- delete: publicProcedure
- .input(validation.app.byId)
- .mutation(async ({ ctx, input }) => {
- await ctx.db.delete(apps).where(eq(apps.id, input.id));
- }),
+ })
+ .where(eq(apps.id, input.id));
+ }),
+ delete: publicProcedure.input(validation.app.byId).mutation(async ({ ctx, input }) => {
+ await ctx.db.delete(apps).where(eq(apps.id, input.id));
+ }),
});
diff --git a/packages/api/src/router/board.ts b/packages/api/src/router/board.ts
index e9287b821..1e5067a78 100644
--- a/packages/api/src/router/board.ts
+++ b/packages/api/src/router/board.ts
@@ -16,50 +16,34 @@ import {
} from "@homarr/db/schema/sqlite";
import type { WidgetKind } from "@homarr/definitions";
import { getPermissionsWithParents, widgetKinds } from "@homarr/definitions";
-import {
- createSectionSchema,
- sharedItemSchema,
- validation,
- z,
-} from "@homarr/validation";
+import { createSectionSchema, sharedItemSchema, validation, z } from "@homarr/validation";
import { zodUnionFromArray } from "../../../validation/src/enums";
-import {
- createTRPCRouter,
- permissionRequiredProcedure,
- protectedProcedure,
- publicProcedure,
-} from "../trpc";
+import { createTRPCRouter, permissionRequiredProcedure, protectedProcedure, publicProcedure } from "../trpc";
import { throwIfActionForbiddenAsync } from "./board/board-access";
export const boardRouter = createTRPCRouter({
getAllBoards: publicProcedure.query(async ({ ctx }) => {
const userId = ctx.session?.user.id;
- const permissionsOfCurrentUserWhenPresent =
- await ctx.db.query.boardUserPermissions.findMany({
- where: eq(boardUserPermissions.userId, userId ?? ""),
- });
+ const permissionsOfCurrentUserWhenPresent = await ctx.db.query.boardUserPermissions.findMany({
+ where: eq(boardUserPermissions.userId, userId ?? ""),
+ });
- const permissionsOfCurrentUserGroupsWhenPresent =
- await ctx.db.query.groupMembers.findMany({
- where: eq(groupMembers.userId, userId ?? ""),
- with: {
- group: {
- with: {
- boardPermissions: {},
- },
+ const permissionsOfCurrentUserGroupsWhenPresent = await ctx.db.query.groupMembers.findMany({
+ where: eq(groupMembers.userId, userId ?? ""),
+ with: {
+ group: {
+ with: {
+ boardPermissions: {},
},
},
- });
+ },
+ });
const boardIds = permissionsOfCurrentUserWhenPresent
.map((permission) => permission.boardId)
.concat(
permissionsOfCurrentUserGroupsWhenPresent
- .map((groupMember) =>
- groupMember.group.boardPermissions.map(
- (permission) => permission.boardId,
- ),
- )
+ .map((groupMember) => groupMember.group.boardPermissions.map((permission) => permission.boardId))
.flat(),
);
@@ -89,9 +73,7 @@ export const boardRouter = createTRPCRouter({
permissionsOfCurrentUserGroupsWhenPresent.length >= 1
? inArray(
boardGroupPermissions.groupId,
- permissionsOfCurrentUserGroupsWhenPresent.map(
- (groupMember) => groupMember.groupId,
- ),
+ permissionsOfCurrentUserGroupsWhenPresent.map((groupMember) => groupMember.groupId),
)
: undefined,
},
@@ -129,61 +111,33 @@ export const boardRouter = createTRPCRouter({
});
});
}),
- renameBoard: protectedProcedure
- .input(validation.board.rename)
- .mutation(async ({ ctx, input }) => {
- await throwIfActionForbiddenAsync(
- ctx,
- eq(boards.id, input.id),
- "full-access",
- );
+ renameBoard: protectedProcedure.input(validation.board.rename).mutation(async ({ ctx, input }) => {
+ await throwIfActionForbiddenAsync(ctx, eq(boards.id, input.id), "full-access");
- await noBoardWithSimilarNameAsync(ctx.db, input.name, [input.id]);
+ await noBoardWithSimilarNameAsync(ctx.db, input.name, [input.id]);
- await ctx.db
- .update(boards)
- .set({ name: input.name })
- .where(eq(boards.id, input.id));
- }),
+ await ctx.db.update(boards).set({ name: input.name }).where(eq(boards.id, input.id));
+ }),
changeBoardVisibility: protectedProcedure
.input(validation.board.changeVisibility)
.mutation(async ({ ctx, input }) => {
- await throwIfActionForbiddenAsync(
- ctx,
- eq(boards.id, input.id),
- "full-access",
- );
+ await throwIfActionForbiddenAsync(ctx, eq(boards.id, input.id), "full-access");
await ctx.db
.update(boards)
.set({ isPublic: input.visibility === "public" })
.where(eq(boards.id, input.id));
}),
- deleteBoard: protectedProcedure
- .input(z.object({ id: z.string() }))
- .mutation(async ({ ctx, input }) => {
- await throwIfActionForbiddenAsync(
- ctx,
- eq(boards.id, input.id),
- "full-access",
- );
+ deleteBoard: protectedProcedure.input(z.object({ id: z.string() })).mutation(async ({ ctx, input }) => {
+ await throwIfActionForbiddenAsync(ctx, eq(boards.id, input.id), "full-access");
- await ctx.db.delete(boards).where(eq(boards.id, input.id));
- }),
- setHomeBoard: protectedProcedure
- .input(z.object({ id: z.string() }))
- .mutation(async ({ ctx, input }) => {
- await throwIfActionForbiddenAsync(
- ctx,
- eq(boards.id, input.id),
- "board-view",
- );
+ await ctx.db.delete(boards).where(eq(boards.id, input.id));
+ }),
+ setHomeBoard: protectedProcedure.input(z.object({ id: z.string() })).mutation(async ({ ctx, input }) => {
+ await throwIfActionForbiddenAsync(ctx, eq(boards.id, input.id), "board-view");
- await ctx.db
- .update(users)
- .set({ homeBoardId: input.id })
- .where(eq(users.id, ctx.session.user.id));
- }),
+ await ctx.db.update(users).set({ homeBoardId: input.id }).where(eq(users.id, ctx.session.user.id));
+ }),
getHomeBoard: publicProcedure.query(async ({ ctx }) => {
const userId = ctx.session?.user.id;
const user = userId
@@ -192,39 +146,21 @@ export const boardRouter = createTRPCRouter({
})
: null;
- const boardWhere = user?.homeBoardId
- ? eq(boards.id, user.homeBoardId)
- : eq(boards.name, "home");
+ const boardWhere = user?.homeBoardId ? eq(boards.id, user.homeBoardId) : eq(boards.name, "home");
await throwIfActionForbiddenAsync(ctx, boardWhere, "board-view");
- return await getFullBoardWithWhereAsync(
- ctx.db,
- boardWhere,
- ctx.session?.user.id ?? null,
- );
+ return await getFullBoardWithWhereAsync(ctx.db, boardWhere, ctx.session?.user.id ?? null);
+ }),
+ getBoardByName: publicProcedure.input(validation.board.byName).query(async ({ input, ctx }) => {
+ const boardWhere = eq(boards.name, input.name);
+ await throwIfActionForbiddenAsync(ctx, boardWhere, "board-view");
+
+ return await getFullBoardWithWhereAsync(ctx.db, boardWhere, ctx.session?.user.id ?? null);
}),
- getBoardByName: publicProcedure
- .input(validation.board.byName)
- .query(async ({ input, ctx }) => {
- const boardWhere = eq(boards.name, input.name);
- await throwIfActionForbiddenAsync(ctx, boardWhere, "board-view");
-
- return await getFullBoardWithWhereAsync(
- ctx.db,
- boardWhere,
- ctx.session?.user.id ?? null,
- );
- }),
savePartialBoardSettings: protectedProcedure
- .input(
- validation.board.savePartialSettings.and(z.object({ id: z.string() })),
- )
+ .input(validation.board.savePartialSettings.and(z.object({ id: z.string() })))
.mutation(async ({ ctx, input }) => {
- await throwIfActionForbiddenAsync(
- ctx,
- eq(boards.id, input.id),
- "board-change",
- );
+ await throwIfActionForbiddenAsync(ctx, eq(boards.id, input.id), "board-change");
await ctx.db
.update(boards)
@@ -254,271 +190,222 @@ export const boardRouter = createTRPCRouter({
})
.where(eq(boards.id, input.id));
}),
- saveBoard: protectedProcedure
- .input(validation.board.save)
- .mutation(async ({ input, ctx }) => {
- await throwIfActionForbiddenAsync(
- ctx,
- eq(boards.id, input.id),
- "board-change",
- );
-
- await ctx.db.transaction(async (transaction) => {
- const dbBoard = await getFullBoardWithWhereAsync(
- transaction,
- eq(boards.id, input.id),
- ctx.session.user.id,
- );
-
- const addedSections = filterAddedItems(
- input.sections,
- dbBoard.sections,
+ saveBoard: protectedProcedure.input(validation.board.save).mutation(async ({ input, ctx }) => {
+ await throwIfActionForbiddenAsync(ctx, eq(boards.id, input.id), "board-change");
+
+ await ctx.db.transaction(async (transaction) => {
+ const dbBoard = await getFullBoardWithWhereAsync(transaction, eq(boards.id, input.id), ctx.session.user.id);
+
+ const addedSections = filterAddedItems(input.sections, dbBoard.sections);
+
+ if (addedSections.length > 0) {
+ await transaction.insert(sections).values(
+ addedSections.map((section) => ({
+ id: section.id,
+ kind: section.kind,
+ position: section.position,
+ name: "name" in section ? section.name : null,
+ boardId: dbBoard.id,
+ })),
);
+ }
- if (addedSections.length > 0) {
- await transaction.insert(sections).values(
- addedSections.map((section) => ({
- id: section.id,
- kind: section.kind,
- position: section.position,
- name: "name" in section ? section.name : null,
- boardId: dbBoard.id,
- })),
- );
- }
+ const inputItems = input.sections.flatMap((section) =>
+ section.items.map((item) => ({ ...item, sectionId: section.id })),
+ );
+ const dbItems = dbBoard.sections.flatMap((section) =>
+ section.items.map((item) => ({ ...item, sectionId: section.id })),
+ );
- const inputItems = input.sections.flatMap((section) =>
- section.items.map((item) => ({ ...item, sectionId: section.id })),
- );
- const dbItems = dbBoard.sections.flatMap((section) =>
- section.items.map((item) => ({ ...item, sectionId: section.id })),
+ const addedItems = filterAddedItems(inputItems, dbItems);
+
+ if (addedItems.length > 0) {
+ await transaction.insert(items).values(
+ addedItems.map((item) => ({
+ id: item.id,
+ kind: item.kind,
+ height: item.height,
+ width: item.width,
+ xOffset: item.xOffset,
+ yOffset: item.yOffset,
+ options: superjson.stringify(item.options),
+ sectionId: item.sectionId,
+ })),
);
+ }
- const addedItems = filterAddedItems(inputItems, dbItems);
-
- if (addedItems.length > 0) {
- await transaction.insert(items).values(
- addedItems.map((item) => ({
- id: item.id,
- kind: item.kind,
- height: item.height,
- width: item.width,
- xOffset: item.xOffset,
- yOffset: item.yOffset,
- options: superjson.stringify(item.options),
- sectionId: item.sectionId,
- })),
- );
- }
+ const inputIntegrationRelations = inputItems.flatMap(({ integrations, id: itemId }) =>
+ integrations.map((integration) => ({
+ integrationId: integration.id,
+ itemId,
+ })),
+ );
+ const dbIntegrationRelations = dbItems.flatMap(({ integrations, id: itemId }) =>
+ integrations.map((integration) => ({
+ integrationId: integration.id,
+ itemId,
+ })),
+ );
+ const addedIntegrationRelations = inputIntegrationRelations.filter(
+ (inputRelation) =>
+ !dbIntegrationRelations.some(
+ (dbRelation) =>
+ dbRelation.itemId === inputRelation.itemId && dbRelation.integrationId === inputRelation.integrationId,
+ ),
+ );
- const inputIntegrationRelations = inputItems.flatMap(
- ({ integrations, id: itemId }) =>
- integrations.map((integration) => ({
- integrationId: integration.id,
- itemId,
- })),
- );
- const dbIntegrationRelations = dbItems.flatMap(
- ({ integrations, id: itemId }) =>
- integrations.map((integration) => ({
- integrationId: integration.id,
- itemId,
- })),
- );
- const addedIntegrationRelations = inputIntegrationRelations.filter(
- (inputRelation) =>
- !dbIntegrationRelations.some(
- (dbRelation) =>
- dbRelation.itemId === inputRelation.itemId &&
- dbRelation.integrationId === inputRelation.integrationId,
- ),
+ if (addedIntegrationRelations.length > 0) {
+ await transaction.insert(integrationItems).values(
+ addedIntegrationRelations.map((relation) => ({
+ itemId: relation.itemId,
+ integrationId: relation.integrationId,
+ })),
);
+ }
- if (addedIntegrationRelations.length > 0) {
- await transaction.insert(integrationItems).values(
- addedIntegrationRelations.map((relation) => ({
- itemId: relation.itemId,
- integrationId: relation.integrationId,
- })),
- );
- }
-
- const updatedItems = filterUpdatedItems(inputItems, dbItems);
-
- for (const item of updatedItems) {
- await transaction
- .update(items)
- .set({
- kind: item.kind,
- height: item.height,
- width: item.width,
- xOffset: item.xOffset,
- yOffset: item.yOffset,
- options: superjson.stringify(item.options),
- sectionId: item.sectionId,
- })
- .where(eq(items.id, item.id));
- }
-
- const updatedSections = filterUpdatedItems(
- input.sections,
- dbBoard.sections,
- );
+ const updatedItems = filterUpdatedItems(inputItems, dbItems);
- for (const section of updatedSections) {
- const prev = dbBoard.sections.find(
- (dbSection) => dbSection.id === section.id,
- );
- await transaction
- .update(sections)
- .set({
- position: section.position,
- name:
- prev?.kind === "category" && "name" in section
- ? section.name
- : null,
- })
- .where(eq(sections.id, section.id));
- }
+ for (const item of updatedItems) {
+ await transaction
+ .update(items)
+ .set({
+ kind: item.kind,
+ height: item.height,
+ width: item.width,
+ xOffset: item.xOffset,
+ yOffset: item.yOffset,
+ options: superjson.stringify(item.options),
+ sectionId: item.sectionId,
+ })
+ .where(eq(items.id, item.id));
+ }
+
+ const updatedSections = filterUpdatedItems(input.sections, dbBoard.sections);
+
+ for (const section of updatedSections) {
+ const prev = dbBoard.sections.find((dbSection) => dbSection.id === section.id);
+ await transaction
+ .update(sections)
+ .set({
+ position: section.position,
+ name: prev?.kind === "category" && "name" in section ? section.name : null,
+ })
+ .where(eq(sections.id, section.id));
+ }
+
+ const removedIntegrationRelations = dbIntegrationRelations.filter(
+ (dbRelation) =>
+ !inputIntegrationRelations.some(
+ (inputRelation) =>
+ dbRelation.itemId === inputRelation.itemId && dbRelation.integrationId === inputRelation.integrationId,
+ ),
+ );
- const removedIntegrationRelations = dbIntegrationRelations.filter(
- (dbRelation) =>
- !inputIntegrationRelations.some(
- (inputRelation) =>
- dbRelation.itemId === inputRelation.itemId &&
- dbRelation.integrationId === inputRelation.integrationId,
+ for (const relation of removedIntegrationRelations) {
+ await transaction
+ .delete(integrationItems)
+ .where(
+ and(
+ eq(integrationItems.itemId, relation.itemId),
+ eq(integrationItems.integrationId, relation.integrationId),
),
- );
-
- for (const relation of removedIntegrationRelations) {
- await transaction
- .delete(integrationItems)
- .where(
- and(
- eq(integrationItems.itemId, relation.itemId),
- eq(integrationItems.integrationId, relation.integrationId),
- ),
- );
- }
+ );
+ }
- const removedItems = filterRemovedItems(inputItems, dbItems);
+ const removedItems = filterRemovedItems(inputItems, dbItems);
- const itemIds = removedItems.map((item) => item.id);
- if (itemIds.length > 0) {
- await transaction.delete(items).where(inArray(items.id, itemIds));
- }
+ const itemIds = removedItems.map((item) => item.id);
+ if (itemIds.length > 0) {
+ await transaction.delete(items).where(inArray(items.id, itemIds));
+ }
- const removedSections = filterRemovedItems(
- input.sections,
- dbBoard.sections,
- );
- const sectionIds = removedSections.map((section) => section.id);
+ const removedSections = filterRemovedItems(input.sections, dbBoard.sections);
+ const sectionIds = removedSections.map((section) => section.id);
- if (sectionIds.length > 0) {
- await transaction
- .delete(sections)
- .where(inArray(sections.id, sectionIds));
- }
- });
- }),
+ if (sectionIds.length > 0) {
+ await transaction.delete(sections).where(inArray(sections.id, sectionIds));
+ }
+ });
+ }),
- getBoardPermissions: protectedProcedure
- .input(validation.board.permissions)
- .query(async ({ input, ctx }) => {
- await throwIfActionForbiddenAsync(
- ctx,
- eq(boards.id, input.id),
- "full-access",
- );
+ getBoardPermissions: protectedProcedure.input(validation.board.permissions).query(async ({ input, ctx }) => {
+ await throwIfActionForbiddenAsync(ctx, eq(boards.id, input.id), "full-access");
- const dbGroupPermissions = await ctx.db.query.groupPermissions.findMany({
- where: inArray(
- groupPermissions.permission,
- getPermissionsWithParents([
- "board-view-all",
- "board-modify-all",
- "board-full-access",
- ]),
- ),
- columns: {
- groupId: false,
- },
- with: {
- group: {
- columns: {
- id: true,
- name: true,
- },
+ const dbGroupPermissions = await ctx.db.query.groupPermissions.findMany({
+ where: inArray(
+ groupPermissions.permission,
+ getPermissionsWithParents(["board-view-all", "board-modify-all", "board-full-access"]),
+ ),
+ columns: {
+ groupId: false,
+ },
+ with: {
+ group: {
+ columns: {
+ id: true,
+ name: true,
},
},
- });
+ },
+ });
- const userPermissions = await ctx.db.query.boardUserPermissions.findMany({
- where: eq(boardUserPermissions.boardId, input.id),
- with: {
- user: {
- columns: {
- id: true,
- name: true,
- image: true,
- },
+ const userPermissions = await ctx.db.query.boardUserPermissions.findMany({
+ where: eq(boardUserPermissions.boardId, input.id),
+ with: {
+ user: {
+ columns: {
+ id: true,
+ name: true,
+ image: true,
},
},
- });
+ },
+ });
- const dbGroupBoardPermission =
- await ctx.db.query.boardGroupPermissions.findMany({
- where: eq(boardGroupPermissions.boardId, input.id),
- with: {
- group: {
- columns: {
- id: true,
- name: true,
- },
- },
+ const dbGroupBoardPermission = await ctx.db.query.boardGroupPermissions.findMany({
+ where: eq(boardGroupPermissions.boardId, input.id),
+ with: {
+ group: {
+ columns: {
+ id: true,
+ name: true,
},
- });
+ },
+ },
+ });
- return {
- inherited: dbGroupPermissions.sort((permissionA, permissionB) => {
+ return {
+ inherited: dbGroupPermissions.sort((permissionA, permissionB) => {
+ return permissionA.group.name.localeCompare(permissionB.group.name);
+ }),
+ userPermissions: userPermissions
+ .map(({ user, permission }) => ({
+ user,
+ permission,
+ }))
+ .sort((permissionA, permissionB) => {
+ return (permissionA.user.name ?? "").localeCompare(permissionB.user.name ?? "");
+ }),
+ groupPermissions: dbGroupBoardPermission
+ .map(({ group, permission }) => ({
+ group: {
+ id: group.id,
+ name: group.name,
+ },
+ permission,
+ }))
+ .sort((permissionA, permissionB) => {
return permissionA.group.name.localeCompare(permissionB.group.name);
}),
- userPermissions: userPermissions
- .map(({ user, permission }) => ({
- user,
- permission,
- }))
- .sort((permissionA, permissionB) => {
- return (permissionA.user.name ?? "").localeCompare(
- permissionB.user.name ?? "",
- );
- }),
- groupPermissions: dbGroupBoardPermission
- .map(({ group, permission }) => ({
- group: {
- id: group.id,
- name: group.name,
- },
- permission,
- }))
- .sort((permissionA, permissionB) => {
- return permissionA.group.name.localeCompare(permissionB.group.name);
- }),
- };
- }),
+ };
+ }),
saveUserBoardPermissions: protectedProcedure
.input(validation.board.savePermissions)
.mutation(async ({ input, ctx }) => {
- await throwIfActionForbiddenAsync(
- ctx,
- eq(boards.id, input.id),
- "full-access",
- );
+ await throwIfActionForbiddenAsync(ctx, eq(boards.id, input.id), "full-access");
await ctx.db.transaction(async (transaction) => {
- await transaction
- .delete(boardUserPermissions)
- .where(eq(boardUserPermissions.boardId, input.id));
+ await transaction.delete(boardUserPermissions).where(eq(boardUserPermissions.boardId, input.id));
if (input.permissions.length === 0) {
return;
}
@@ -534,16 +421,10 @@ export const boardRouter = createTRPCRouter({
saveGroupBoardPermissions: protectedProcedure
.input(validation.board.savePermissions)
.mutation(async ({ input, ctx }) => {
- await throwIfActionForbiddenAsync(
- ctx,
- eq(boards.id, input.id),
- "full-access",
- );
+ await throwIfActionForbiddenAsync(ctx, eq(boards.id, input.id), "full-access");
await ctx.db.transaction(async (transaction) => {
- await transaction
- .delete(boardGroupPermissions)
- .where(eq(boardGroupPermissions.boardId, input.id));
+ await transaction.delete(boardGroupPermissions).where(eq(boardGroupPermissions.boardId, input.id));
if (input.permissions.length === 0) {
return;
}
@@ -558,11 +439,7 @@ export const boardRouter = createTRPCRouter({
}),
});
-const noBoardWithSimilarNameAsync = async (
- db: Database,
- name: string,
- ignoredIds: string[] = [],
-) => {
+const noBoardWithSimilarNameAsync = async (db: Database, name: string, ignoredIds: string[] = []) => {
const boards = await db.query.boards.findMany({
columns: {
id: true,
@@ -571,9 +448,7 @@ const noBoardWithSimilarNameAsync = async (
});
const board = boards.find(
- (board) =>
- board.name.toLowerCase() === name.toLowerCase() &&
- !ignoredIds.includes(board.id),
+ (board) => board.name.toLowerCase() === name.toLowerCase() && !ignoredIds.includes(board.id),
);
if (board) {
@@ -584,11 +459,7 @@ const noBoardWithSimilarNameAsync = async (
}
};
-const getFullBoardWithWhereAsync = async (
- db: Database,
- where: SQL<unknown>,
- userId: string | null,
-) => {
+const getFullBoardWithWhereAsync = async (db: Database, where: SQL<unknown>, userId: string | null) => {
const groupsOfCurrentUser = await db.query.groupMembers.findMany({
where: eq(groupMembers.userId, userId ?? ""),
});
@@ -622,10 +493,7 @@ const getFullBoardWithWhereAsync = async (
},
},
groupPermissions: {
- where: inArray(
- boardGroupPermissions.groupId,
- groupsOfCurrentUser.map((group) => group.groupId).concat(""),
- ),
+ where: inArray(boardGroupPermissions.groupId, groupsOfCurrentUser.map((group) => group.groupId).concat("")),
},
},
});
@@ -660,9 +528,7 @@ const forKind = <T extends WidgetKind>(kind: T) =>
options: z.record(z.unknown()),
});
-const outputItemSchema = zodUnionFromArray(
- widgetKinds.map((kind) => forKind(kind)),
-).and(sharedItemSchema);
+const outputItemSchema = zodUnionFromArray(widgetKinds.map((kind) => forKind(kind))).and(sharedItemSchema);
const parseSection = (section: unknown) => {
const result = createSectionSchema(outputItemSchema).safeParse(section);
@@ -672,26 +538,11 @@ const parseSection = (section: unknown) => {
return result.data;
};
-const filterAddedItems = <TInput extends { id: string }>(
- inputArray: TInput[],
- dbArray: TInput[],
-) =>
- inputArray.filter(
- (inputItem) => !dbArray.some((dbItem) => dbItem.id === inputItem.id),
- );
+const filterAddedItems = <TInput extends { id: string }>(inputArray: TInput[], dbArray: TInput[]) =>
+ inputArray.filter((inputItem) => !dbArray.some((dbItem) => dbItem.id === inputItem.id));
-const filterRemovedItems = <TInput extends { id: string }>(
- inputArray: TInput[],
- dbArray: TInput[],
-) =>
- dbArray.filter(
- (dbItem) => !inputArray.some((inputItem) => dbItem.id === inputItem.id),
- );
+const filterRemovedItems = <TInput extends { id: string }>(inputArray: TInput[], dbArray: TInput[]) =>
+ dbArray.filter((dbItem) => !inputArray.some((inputItem) => dbItem.id === inputItem.id));
-const filterUpdatedItems = <TInput extends { id: string }>(
- inputArray: TInput[],
- dbArray: TInput[],
-) =>
- inputArray.filter((inputItem) =>
- dbArray.some((dbItem) => dbItem.id === inputItem.id),
- );
+const filterUpdatedItems = <TInput extends { id: string }>(inputArray: TInput[], dbArray: TInput[]) =>
+ inputArray.filter((inputItem) => dbArray.some((dbItem) => dbItem.id === inputItem.id));
diff --git a/packages/api/src/router/board/board-access.ts b/packages/api/src/router/board/board-access.ts
index b66866b98..d27d1cbe5 100644
--- a/packages/api/src/router/board/board-access.ts
+++ b/packages/api/src/router/board/board-access.ts
@@ -4,11 +4,7 @@ import type { Session } from "@homarr/auth";
import { constructBoardPermissions } from "@homarr/auth/shared";
import type { Database, SQL } from "@homarr/db";
import { eq, inArray } from "@homarr/db";
-import {
- boardGroupPermissions,
- boardUserPermissions,
- groupMembers,
-} from "@homarr/db/schema/sqlite";
+import { boardGroupPermissions, boardUserPermissions, groupMembers } from "@homarr/db/schema/sqlite";
import type { BoardPermission } from "@homarr/definitions";
/**
@@ -38,10 +34,7 @@ export const throwIfActionForbiddenAsync = async (
where: eq(boardUserPermissions.userId, session?.user.id ?? ""),
},
groupPermissions: {
- where: inArray(
- boardGroupPermissions.groupId,
- groupsOfCurrentUser.map((group) => group.groupId).concat(""),
- ),
+ where: inArray(boardGroupPermissions.groupId, groupsOfCurrentUser.map((group) => group.groupId).concat("")),
},
},
});
@@ -50,8 +43,7 @@ export const throwIfActionForbiddenAsync = async (
notAllowed();
}
- const { hasViewAccess, hasChangeAccess, hasFullAccess } =
- constructBoardPermissions(board, session);
+ const { hasViewAccess, hasChangeAccess, hasFullAccess } = constructBoardPermissions(board, session);
if (hasFullAccess) {
return; // As full access is required and user has full access, allow
diff --git a/packages/api/src/router/group.ts b/packages/api/src/router/group.ts
index 19785b32d..17a7749d1 100644
--- a/packages/api/src/router/group.ts
+++ b/packages/api/src/router/group.ts
@@ -2,98 +2,86 @@ import { TRPCError } from "@trpc/server";
import type { Database } from "@homarr/db";
import { and, createId, eq, like, not, sql } from "@homarr/db";
-import {
- groupMembers,
- groupPermissions,
- groups,
-} from "@homarr/db/schema/sqlite";
+import { groupMembers, groupPermissions, groups } from "@homarr/db/schema/sqlite";
import { validation } from "@homarr/validation";
import { createTRPCRouter, protectedProcedure } from "../trpc";
export const groupRouter = createTRPCRouter({
- getPaginated: protectedProcedure
- .input(validation.group.paginated)
- .query(async ({ input, ctx }) => {
- const whereQuery = input.search
- ? like(groups.name, `%${input.search.trim()}%`)
- : undefined;
- const groupCount = await ctx.db
- .select({
- count: sql<number>`count(*)`,
- })
- .from(groups)
- .where(whereQuery);
-
- const dbGroups = await ctx.db.query.groups.findMany({
- with: {
- members: {
- with: {
- user: {
- columns: {
- id: true,
- name: true,
- email: true,
- image: true,
- },
+ getPaginated: protectedProcedure.input(validation.group.paginated).query(async ({ input, ctx }) => {
+ const whereQuery = input.search ? like(groups.name, `%${input.search.trim()}%`) : undefined;
+ const groupCount = await ctx.db
+ .select({
+ count: sql<number>`count(*)`,
+ })
+ .from(groups)
+ .where(whereQuery);
+
+ const dbGroups = await ctx.db.query.groups.findMany({
+ with: {
+ members: {
+ with: {
+ user: {
+ columns: {
+ id: true,
+ name: true,
+ email: true,
+ image: true,
},
},
},
},
- limit: input.pageSize,
- offset: (input.page - 1) * input.pageSize,
- where: whereQuery,
- });
+ },
+ limit: input.pageSize,
+ offset: (input.page - 1) * input.pageSize,
+ where: whereQuery,
+ });
- return {
- items: dbGroups.map((group) => ({
- ...group,
- members: group.members.map((member) => member.user),
- })),
- totalCount: groupCount[0]!.count,
- };
- }),
- getById: protectedProcedure
- .input(validation.group.byId)
- .query(async ({ input, ctx }) => {
- const group = await ctx.db.query.groups.findFirst({
- where: eq(groups.id, input.id),
- with: {
- members: {
- with: {
- user: {
- columns: {
- id: true,
- name: true,
- email: true,
- image: true,
- },
+ return {
+ items: dbGroups.map((group) => ({
+ ...group,
+ members: group.members.map((member) => member.user),
+ })),
+ totalCount: groupCount[0]!.count,
+ };
+ }),
+ getById: protectedProcedure.input(validation.group.byId).query(async ({ input, ctx }) => {
+ const group = await ctx.db.query.groups.findFirst({
+ where: eq(groups.id, input.id),
+ with: {
+ members: {
+ with: {
+ user: {
+ columns: {
+ id: true,
+ name: true,
+ email: true,
+ image: true,
},
},
},
- permissions: {
- columns: {
- permission: true,
- },
+ },
+ permissions: {
+ columns: {
+ permission: true,
},
},
- });
+ },
+ });
- if (!group) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Group not found",
- });
- }
+ if (!group) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Group not found",
+ });
+ }
- return {
- ...group,
- members: group.members.map((member) => member.user),
- permissions: group.permissions.map(
- (permission) => permission.permission,
- ),
- };
- }),
+ return {
+ ...group,
+ members: group.members.map((member) => member.user),
+ permissions: group.permissions.map((permission) => permission.permission),
+ };
+ }),
selectable: protectedProcedure.query(async ({ ctx }) => {
return await ctx.db.query.groups.findMany({
columns: {
@@ -102,120 +90,92 @@ export const groupRouter = createTRPCRouter({
},
});
}),
- createGroup: protectedProcedure
- .input(validation.group.create)
- .mutation(async ({ input, ctx }) => {
- const normalizedName = normalizeName(input.name);
- await checkSimilarNameAndThrowAsync(ctx.db, normalizedName);
-
- const id = createId();
- await ctx.db.insert(groups).values({
- id,
- name: normalizedName,
- ownerId: ctx.session.user.id,
- });
+ createGroup: protectedProcedure.input(validation.group.create).mutation(async ({ input, ctx }) => {
+ const normalizedName = normalizeName(input.name);
+ await checkSimilarNameAndThrowAsync(ctx.db, normalizedName);
+
+ const id = createId();
+ await ctx.db.insert(groups).values({
+ id,
+ name: normalizedName,
+ ownerId: ctx.session.user.id,
+ });
- return id;
- }),
- updateGroup: protectedProcedure
- .input(validation.group.update)
- .mutation(async ({ input, ctx }) => {
- await throwIfGroupNotFoundAsync(ctx.db, input.id);
-
- const normalizedName = normalizeName(input.name);
- await checkSimilarNameAndThrowAsync(ctx.db, normalizedName, input.id);
-
- await ctx.db
- .update(groups)
- .set({
- name: normalizedName,
- })
- .where(eq(groups.id, input.id));
- }),
- savePermissions: protectedProcedure
- .input(validation.group.savePermissions)
- .mutation(async ({ input, ctx }) => {
- await throwIfGroupNotFoundAsync(ctx.db, input.groupId);
-
- await ctx.db
- .delete(groupPermissions)
- .where(eq(groupPermissions.groupId, input.groupId));
-
- await ctx.db.insert(groupPermissions).values(
- input.permissions.map((permission) => ({
- groupId: input.groupId,
- permission,
- })),
- );
- }),
- transferOwnership: protectedProcedure
- .input(validation.group.groupUser)
- .mutation(async ({ input, ctx }) => {
- await throwIfGroupNotFoundAsync(ctx.db, input.groupId);
-
- await ctx.db
- .update(groups)
- .set({
- ownerId: input.userId,
- })
- .where(eq(groups.id, input.groupId));
- }),
- deleteGroup: protectedProcedure
- .input(validation.group.byId)
- .mutation(async ({ input, ctx }) => {
- await throwIfGroupNotFoundAsync(ctx.db, input.id);
-
- await ctx.db.delete(groups).where(eq(groups.id, input.id));
- }),
- addMember: protectedProcedure
- .input(validation.group.groupUser)
- .mutation(async ({ input, ctx }) => {
- await throwIfGroupNotFoundAsync(ctx.db, input.groupId);
-
- const user = await ctx.db.query.users.findFirst({
- where: eq(groups.id, input.userId),
- });
+ return id;
+ }),
+ updateGroup: protectedProcedure.input(validation.group.update).mutation(async ({ input, ctx }) => {
+ await throwIfGroupNotFoundAsync(ctx.db, input.id);
+
+ const normalizedName = normalizeName(input.name);
+ await checkSimilarNameAndThrowAsync(ctx.db, normalizedName, input.id);
- if (!user) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "User not found",
- });
- }
+ await ctx.db
+ .update(groups)
+ .set({
+ name: normalizedName,
+ })
+ .where(eq(groups.id, input.id));
+ }),
+ savePermissions: protectedProcedure.input(validation.group.savePermissions).mutation(async ({ input, ctx }) => {
+ await throwIfGroupNotFoundAsync(ctx.db, input.groupId);
- await ctx.db.insert(groupMembers).values({
+ await ctx.db.delete(groupPermissions).where(eq(groupPermissions.groupId, input.groupId));
+
+ await ctx.db.insert(groupPermissions).values(
+ input.permissions.map((permission) => ({
groupId: input.groupId,
- userId: input.userId,
+ permission,
+ })),
+ );
+ }),
+ transferOwnership: protectedProcedure.input(validation.group.groupUser).mutation(async ({ input, ctx }) => {
+ await throwIfGroupNotFoundAsync(ctx.db, input.groupId);
+
+ await ctx.db
+ .update(groups)
+ .set({
+ ownerId: input.userId,
+ })
+ .where(eq(groups.id, input.groupId));
+ }),
+ deleteGroup: protectedProcedure.input(validation.group.byId).mutation(async ({ input, ctx }) => {
+ await throwIfGroupNotFoundAsync(ctx.db, input.id);
+
+ await ctx.db.delete(groups).where(eq(groups.id, input.id));
+ }),
+ addMember: protectedProcedure.input(validation.group.groupUser).mutation(async ({ input, ctx }) => {
+ await throwIfGroupNotFoundAsync(ctx.db, input.groupId);
+
+ const user = await ctx.db.query.users.findFirst({
+ where: eq(groups.id, input.userId),
+ });
+
+ if (!user) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "User not found",
});
- }),
- removeMember: protectedProcedure
- .input(validation.group.groupUser)
- .mutation(async ({ input, ctx }) => {
- await throwIfGroupNotFoundAsync(ctx.db, input.groupId);
-
- await ctx.db
- .delete(groupMembers)
- .where(
- and(
- eq(groupMembers.groupId, input.groupId),
- eq(groupMembers.userId, input.userId),
- ),
- );
- }),
+ }
+
+ await ctx.db.insert(groupMembers).values({
+ groupId: input.groupId,
+ userId: input.userId,
+ });
+ }),
+ removeMember: protectedProcedure.input(validation.group.groupUser).mutation(async ({ input, ctx }) => {
+ await throwIfGroupNotFoundAsync(ctx.db, input.groupId);
+
+ await ctx.db
+ .delete(groupMembers)
+ .where(and(eq(groupMembers.groupId, input.groupId), eq(groupMembers.userId, input.userId)));
+ }),
});
const normalizeName = (name: string) => name.trim();
-const checkSimilarNameAndThrowAsync = async (
- db: Database,
- name: string,
- ignoreId?: string,
-) => {
+const checkSimilarNameAndThrowAsync = async (db: Database, name: string, ignoreId?: string) => {
const similar = await db.query.groups.findFirst({
- where: and(
- like(groups.name, `${name}`),
- not(eq(groups.id, ignoreId ?? "")),
- ),
+ where: and(like(groups.name, `${name}`), not(eq(groups.id, ignoreId ?? ""))),
});
if (similar) {
diff --git a/packages/api/src/router/home.ts b/packages/api/src/router/home.ts
index 9bcabf029..191698566 100644
--- a/packages/api/src/router/home.ts
+++ b/packages/api/src/router/home.ts
@@ -1,31 +1,17 @@
import { count } from "@homarr/db";
-import {
- apps,
- boards,
- groups,
- integrations,
- invites,
- users,
-} from "@homarr/db/schema/sqlite";
+import { apps, boards, groups, integrations, invites, users } from "@homarr/db/schema/sqlite";
import { createTRPCRouter, protectedProcedure } from "../trpc";
export const homeRouter = createTRPCRouter({
getStats: protectedProcedure.query(async ({ ctx }) => {
return {
- countBoards:
- (await ctx.db.select({ count: count() }).from(boards))[0]?.count ?? 0,
- countUsers:
- (await ctx.db.select({ count: count() }).from(users))[0]?.count ?? 0,
- countGroups:
- (await ctx.db.select({ count: count() }).from(groups))[0]?.count ?? 0,
- countInvites:
- (await ctx.db.select({ count: count() }).from(invites))[0]?.count ?? 0,
- countIntegrations:
- (await ctx.db.select({ count: count() }).from(integrations))[0]
- ?.count ?? 0,
- countApps:
- (await ctx.db.select({ count: count() }).from(apps))[0]?.count ?? 0,
+ countBoards: (await ctx.db.select({ count: count() }).from(boards))[0]?.count ?? 0,
+ countUsers: (await ctx.db.select({ count: count() }).from(users))[0]?.count ?? 0,
+ countGroups: (await ctx.db.select({ count: count() }).from(groups))[0]?.count ?? 0,
+ countInvites: (await ctx.db.select({ count: count() }).from(invites))[0]?.count ?? 0,
+ countIntegrations: (await ctx.db.select({ count: count() }).from(integrations))[0]?.count ?? 0,
+ countApps: (await ctx.db.select({ count: count() }).from(apps))[0]?.count ?? 0,
};
}),
});
diff --git a/packages/api/src/router/icons.ts b/packages/api/src/router/icons.ts
index 88b514462..e0c3c9a7c 100644
--- a/packages/api/src/router/icons.ts
+++ b/packages/api/src/router/icons.ts
@@ -5,28 +5,22 @@ import { validation } from "@homarr/validation";
import { createTRPCRouter, publicProcedure } from "../trpc";
export const iconsRouter = createTRPCRouter({
- findIcons: publicProcedure
- .input(validation.icons.findIcons)
- .query(async ({ ctx, input }) => {
- return {
- icons: await ctx.db.query.iconRepositories.findMany({
- with: {
- icons: {
- columns: {
- id: true,
- name: true,
- url: true,
- },
- where:
- input.searchText?.length ?? 0 > 0
- ? like(icons.name, `%${input.searchText}%`)
- : undefined,
- limit: 5,
+ findIcons: publicProcedure.input(validation.icons.findIcons).query(async ({ ctx, input }) => {
+ return {
+ icons: await ctx.db.query.iconRepositories.findMany({
+ with: {
+ icons: {
+ columns: {
+ id: true,
+ name: true,
+ url: true,
},
+ where: input.searchText?.length ?? 0 > 0 ? like(icons.name, `%${input.searchText}%`) : undefined,
+ limit: 5,
},
- }),
- countIcons:
- (await ctx.db.select({ count: count() }).from(icons))[0]?.count ?? 0,
- };
- }),
+ },
+ }),
+ countIcons: (await ctx.db.select({ count: count() }).from(icons))[0]?.count ?? 0,
+ };
+ }),
});
diff --git a/packages/api/src/router/integration.ts b/packages/api/src/router/integration.ts
index f0b27f99d..ae807ef97 100644
--- a/packages/api/src/router/integration.ts
+++ b/packages/api/src/router/integration.ts
@@ -5,11 +5,7 @@ import type { Database } from "@homarr/db";
import { and, createId, eq } from "@homarr/db";
import { integrations, integrationSecrets } from "@homarr/db/schema/sqlite";
import type { IntegrationSecretKind } from "@homarr/definitions";
-import {
- getAllSecretKindOptions,
- integrationKinds,
- integrationSecretKindObject,
-} from "@homarr/definitions";
+import { getAllSecretKindOptions, integrationKinds, integrationSecretKindObject } from "@homarr/definitions";
import { validation } from "@homarr/validation";
import { createTRPCRouter, publicProcedure } from "../trpc";
@@ -26,231 +22,198 @@ export const integrationRouter = createTRPCRouter({
}))
.sort(
(integrationA, integrationB) =>
- integrationKinds.indexOf(integrationA.kind) -
- integrationKinds.indexOf(integrationB.kind),
+ integrationKinds.indexOf(integrationA.kind) - integrationKinds.indexOf(integrationB.kind),
);
}),
- byId: publicProcedure
- .input(validation.integration.byId)
- .query(async ({ ctx, input }) => {
- const integration = await ctx.db.query.integrations.findFirst({
- where: eq(integrations.id, input.id),
- with: {
- secrets: {
- columns: {
- kind: true,
- value: true,
- updatedAt: true,
- },
+ byId: publicProcedure.input(validation.integration.byId).query(async ({ ctx, input }) => {
+ const integration = await ctx.db.query.integrations.findFirst({
+ where: eq(integrations.id, input.id),
+ with: {
+ secrets: {
+ columns: {
+ kind: true,
+ value: true,
+ updatedAt: true,
},
},
+ },
+ });
+
+ if (!integration) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Integration not found",
});
+ }
- if (!integration) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Integration not found",
- });
- }
+ return {
+ id: integration.id,
+ name: integration.name,
+ kind: integration.kind,
+ url: integration.url,
+ secrets: integration.secrets.map((secret) => ({
+ kind: secret.kind,
+ // Only return the value if the secret is public, so for example the username
+ value: integrationSecretKindObject[secret.kind].isPublic ? decryptSecret(secret.value) : null,
+ updatedAt: secret.updatedAt,
+ })),
+ };
+ }),
+ create: publicProcedure.input(validation.integration.create).mutation(async ({ ctx, input }) => {
+ const integrationId = createId();
+ await ctx.db.insert(integrations).values({
+ id: integrationId,
+ name: input.name,
+ url: input.url,
+ kind: input.kind,
+ });
- return {
- id: integration.id,
- name: integration.name,
- kind: integration.kind,
- url: integration.url,
- secrets: integration.secrets.map((secret) => ({
- kind: secret.kind,
- // Only return the value if the secret is public, so for example the username
- value: integrationSecretKindObject[secret.kind].isPublic
- ? decryptSecret(secret.value)
- : null,
- updatedAt: secret.updatedAt,
- })),
- };
- }),
- create: publicProcedure
- .input(validation.integration.create)
- .mutation(async ({ ctx, input }) => {
- const integrationId = createId();
- await ctx.db.insert(integrations).values({
- id: integrationId,
+ for (const secret of input.secrets) {
+ await ctx.db.insert(integrationSecrets).values({
+ kind: secret.kind,
+ value: encryptSecret(secret.value),
+ updatedAt: new Date(),
+ integrationId,
+ });
+ }
+ }),
+ update: publicProcedure.input(validation.integration.update).mutation(async ({ ctx, input }) => {
+ const integration = await ctx.db.query.integrations.findFirst({
+ where: eq(integrations.id, input.id),
+ with: {
+ secrets: true,
+ },
+ });
+
+ if (!integration) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Integration not found",
+ });
+ }
+
+ await ctx.db
+ .update(integrations)
+ .set({
name: input.name,
url: input.url,
- kind: input.kind,
- });
+ })
+ .where(eq(integrations.id, input.id));
- for (const secret of input.secrets) {
- await ctx.db.insert(integrationSecrets).values({
- kind: secret.kind,
- value: encryptSecret(secret.value),
- updatedAt: new Date(),
- integrationId,
- });
+ const decryptedSecrets = integration.secrets.map((secret) => ({
+ ...secret,
+ value: decryptSecret(secret.value),
+ }));
+
+ const changedSecrets = input.secrets.filter(
+ (secret): secret is { kind: IntegrationSecretKind; value: string } =>
+ secret.value !== null && // only update secrets that have a value
+ !decryptedSecrets.find((dSecret) => dSecret.kind === secret.kind && dSecret.value === secret.value),
+ );
+
+ if (changedSecrets.length > 0) {
+ for (const changedSecret of changedSecrets) {
+ const secretInput = {
+ integrationId: input.id,
+ value: changedSecret.value,
+ kind: changedSecret.kind,
+ };
+ if (!decryptedSecrets.some((secret) => secret.kind === changedSecret.kind)) {
+ await addSecretAsync(ctx.db, secretInput);
+ } else {
+ await updateSecretAsync(ctx.db, secretInput);
+ }
}
- }),
- update: publicProcedure
- .input(validation.integration.update)
- .mutation(async ({ ctx, input }) => {
+ }
+ }),
+ delete: publicProcedure.input(validation.integration.delete).mutation(async ({ ctx, input }) => {
+ const integration = await ctx.db.query.integrations.findFirst({
+ where: eq(integrations.id, input.id),
+ });
+
+ if (!integration) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Integration not found",
+ });
+ }
+
+ await ctx.db.delete(integrations).where(eq(integrations.id, input.id));
+ }),
+ testConnection: publicProcedure.input(validation.integration.testConnection).mutation(async ({ ctx, input }) => {
+ const secrets = input.secrets.filter((secret): secret is { kind: IntegrationSecretKind; value: string } =>
+ Boolean(secret.value),
+ );
+
+ // Find any matching secret kinds
+ let secretKinds = getAllSecretKindOptions(input.kind).find((secretKinds) =>
+ secretKinds.every((secretKind) => secrets.some((secret) => secret.kind === secretKind)),
+ );
+
+ if (!secretKinds && input.id === null) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: "SECRETS_NOT_DEFINED",
+ });
+ }
+
+ if (!secretKinds && input.id !== null) {
const integration = await ctx.db.query.integrations.findFirst({
where: eq(integrations.id, input.id),
with: {
secrets: true,
},
});
-
if (!integration) {
throw new TRPCError({
- code: "NOT_FOUND",
- message: "Integration not found",
+ code: "BAD_REQUEST",
+ message: "SECRETS_NOT_DEFINED",
});
}
-
- await ctx.db
- .update(integrations)
- .set({
- name: input.name,
- url: input.url,
- })
- .where(eq(integrations.id, input.id));
-
const decryptedSecrets = integration.secrets.map((secret) => ({
...secret,
value: decryptSecret(secret.value),
}));
- const changedSecrets = input.secrets.filter(
- (secret): secret is { kind: IntegrationSecretKind; value: string } =>
- secret.value !== null && // only update secrets that have a value
- !decryptedSecrets.find(
- (dSecret) =>
- dSecret.kind === secret.kind && dSecret.value === secret.value,
- ),
- );
-
- if (changedSecrets.length > 0) {
- for (const changedSecret of changedSecrets) {
- const secretInput = {
- integrationId: input.id,
- value: changedSecret.value,
- kind: changedSecret.kind,
- };
- if (
- !decryptedSecrets.some(
- (secret) => secret.kind === changedSecret.kind,
- )
- ) {
- await addSecretAsync(ctx.db, secretInput);
- } else {
- await updateSecretAsync(ctx.db, secretInput);
- }
+ // Add secrets that are not defined in the input from the database
+ for (const dbSecret of decryptedSecrets) {
+ if (!secrets.find((secret) => secret.kind === dbSecret.kind)) {
+ secrets.push({
+ kind: dbSecret.kind,
+ value: dbSecret.value,
+ });
}
}
- }),
- delete: publicProcedure
- .input(validation.integration.delete)
- .mutation(async ({ ctx, input }) => {
- const integration = await ctx.db.query.integrations.findFirst({
- where: eq(integrations.id, input.id),
- });
-
- if (!integration) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Integration not found",
- });
- }
- await ctx.db.delete(integrations).where(eq(integrations.id, input.id));
- }),
- testConnection: publicProcedure
- .input(validation.integration.testConnection)
- .mutation(async ({ ctx, input }) => {
- const secrets = input.secrets.filter(
- (secret): secret is { kind: IntegrationSecretKind; value: string } =>
- Boolean(secret.value),
+ secretKinds = getAllSecretKindOptions(input.kind).find((secretKinds) =>
+ secretKinds.every((secretKind) => secrets.some((secret) => secret.kind === secretKind)),
);
- // Find any matching secret kinds
- let secretKinds = getAllSecretKindOptions(input.kind).find(
- (secretKinds) =>
- secretKinds.every((secretKind) =>
- secrets.some((secret) => secret.kind === secretKind),
- ),
- );
-
- if (!secretKinds && input.id === null) {
+ if (!secretKinds) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "SECRETS_NOT_DEFINED",
});
}
+ }
- if (!secretKinds && input.id !== null) {
- const integration = await ctx.db.query.integrations.findFirst({
- where: eq(integrations.id, input.id),
- with: {
- secrets: true,
- },
- });
- if (!integration) {
- throw new TRPCError({
- code: "BAD_REQUEST",
- message: "SECRETS_NOT_DEFINED",
- });
- }
- const decryptedSecrets = integration.secrets.map((secret) => ({
- ...secret,
- value: decryptSecret(secret.value),
- }));
-
- // Add secrets that are not defined in the input from the database
- for (const dbSecret of decryptedSecrets) {
- if (!secrets.find((secret) => secret.kind === dbSecret.kind)) {
- secrets.push({
- kind: dbSecret.kind,
- value: dbSecret.value,
- });
- }
- }
-
- secretKinds = getAllSecretKindOptions(input.kind).find((secretKinds) =>
- secretKinds.every((secretKind) =>
- secrets.some((secret) => secret.kind === secretKind),
- ),
- );
-
- if (!secretKinds) {
- throw new TRPCError({
- code: "BAD_REQUEST",
- message: "SECRETS_NOT_DEFINED",
- });
- }
- }
-
- // TODO: actually test the connection
- // Probably by calling a function on the integration class
- // getIntegration(input.kind).testConnection(secrets)
- // getIntegration(kind: IntegrationKind): Integration
- // interface Integration {
- // testConnection(): Promise<void>;
- // }
- }),
+ // TODO: actually test the connection
+ // Probably by calling a function on the integration class
+ // getIntegration(input.kind).testConnection(secrets)
+ // getIntegration(kind: IntegrationKind): Integration
+ // interface Integration {
+ // testConnection(): Promise<void>;
+ // }
+ }),
});
const algorithm = "aes-256-cbc"; //Using AES encryption
-const key = Buffer.from(
- "1d71cceced68159ba59a277d056a66173613052cbeeccbfbd15ab1c909455a4d",
- "hex",
-); // TODO: generate with const data = crypto.randomBytes(32).toString('hex')
+const key = Buffer.from("1d71cceced68159ba59a277d056a66173613052cbeeccbfbd15ab1c909455a4d", "hex"); // TODO: generate with const data = crypto.randomBytes(32).toString('hex')
//Encrypting text
export function encryptSecret(text: string): `${string}.${string}` {
const initializationVector = crypto.randomBytes(16);
- const cipher = crypto.createCipheriv(
- algorithm,
- Buffer.from(key),
- initializationVector,
- );
+ const cipher = crypto.createCipheriv(algorithm, Buffer.from(key), initializationVector);
let encrypted = cipher.update(text);
encrypted = Buffer.concat([encrypted, cipher.final()]);
return `${encrypted.toString("hex")}.${initializationVector.toString("hex")}`;
@@ -261,11 +224,7 @@ function decryptSecret(value: `${string}.${string}`) {
const [data, dataIv] = value.split(".") as [string, string];
const initializationVector = Buffer.from(dataIv, "hex");
const encryptedText = Buffer.from(data, "hex");
- const decipher = crypto.createDecipheriv(
- algorithm,
- Buffer.from(key),
- initializationVector,
- );
+ const decipher = crypto.createDecipheriv(algorithm, Buffer.from(key), initializationVector);
let decrypted = decipher.update(encryptedText);
decrypted = Buffer.concat([decrypted, decipher.final()]);
return decrypted.toString();
@@ -283,12 +242,7 @@ const updateSecretAsync = async (db: Database, input: UpdateSecretInput) => {
value: encryptSecret(input.value),
updatedAt: new Date(),
})
- .where(
- and(
- eq(integrationSecrets.integrationId, input.integrationId),
- eq(integrationSecrets.kind, input.kind),
- ),
- );
+ .where(and(eq(integrationSecrets.integrationId, input.integrationId), eq(integrationSecrets.kind, input.kind)));
};
interface AddSecretInput {
diff --git a/packages/api/src/router/location.ts b/packages/api/src/router/location.ts
index faeb82e42..11e6e6770 100644
--- a/packages/api/src/router/location.ts
+++ b/packages/api/src/router/location.ts
@@ -8,11 +8,7 @@ export const locationRouter = createTRPCRouter({
.input(validation.location.searchCity.input)
.output(validation.location.searchCity.output)
.query(async ({ input }) => {
- const res = await fetch(
- `https://geocoding-api.open-meteo.com/v1/search?name=${input.query}`,
- );
- return (await res.json()) as z.infer<
- typeof validation.location.searchCity.output
- >;
+ const res = await fetch(`https://geocoding-api.open-meteo.com/v1/search?name=${input.query}`);
+ return (await res.json()) as z.infer<typeof validation.location.searchCity.output>;
}),
});
diff --git a/packages/api/src/router/serverSettings.ts b/packages/api/src/router/serverSettings.ts
index 176c05776..8766836ca 100644
--- a/packages/api/src/router/serverSettings.ts
+++ b/packages/api/src/router/serverSettings.ts
@@ -14,9 +14,7 @@ export const serverSettingsRouter = createTRPCRouter({
const data = {} as ServerSettings;
defaultServerSettingsKeys.forEach((key) => {
- const settingValue = settings.find(
- (setting) => setting.settingKey === key,
- )?.value;
+ const settingValue = settings.find((setting) => setting.settingKey === key)?.value;
if (!settingValue) {
return;
}
diff --git a/packages/api/src/router/test/board.spec.ts b/packages/api/src/router/test/board.spec.ts
index 4b62008a9..092aca3cb 100644
--- a/packages/api/src/router/test/board.spec.ts
+++ b/packages/api/src/router/test/board.spec.ts
@@ -155,10 +155,7 @@ describe("getAllBoards should return all boards accessable to the current user",
// Assert
expect(result.length).toBe(2);
- expect(result.map(({ name }) => name)).toStrictEqual([
- "public",
- "private2",
- ]);
+ expect(result.map(({ name }) => name)).toStrictEqual(["public", "private2"]);
});
test.each([["board-view"], ["board-change"]] satisfies [BoardPermission][])(
@@ -221,10 +218,7 @@ describe("getAllBoards should return all boards accessable to the current user",
// Assert
expect(result.length).toBe(2);
- expect(result.map(({ name }) => name)).toStrictEqual([
- "public",
- "private1",
- ]);
+ expect(result.map(({ name }) => name)).toStrictEqual(["public", "private1"]);
},
);
@@ -277,10 +271,7 @@ describe("getAllBoards should return all boards accessable to the current user",
// Assert
expect(result.length).toBe(2);
- expect(result.map(({ name }) => name)).toStrictEqual([
- "public",
- "private1",
- ]);
+ expect(result.map(({ name }) => name)).toStrictEqual(["public", "private1"]);
},
);
});
@@ -356,11 +347,7 @@ describe("rename board should rename board", () => {
});
expect(dbBoard).toBeDefined();
expect(dbBoard?.name).toBe("newName");
- expect(spy).toHaveBeenCalledWith(
- expect.anything(),
- expect.anything(),
- "full-access",
- );
+ expect(spy).toHaveBeenCalledWith(expect.anything(), expect.anything(), "full-access");
});
test("should throw error when similar board name exists", async () => {
@@ -384,13 +371,10 @@ describe("rename board should rename board", () => {
});
// Act
- const actAsync = async () =>
- await caller.renameBoard({ id: boardId, name: "Newname" });
+ const actAsync = async () => await caller.renameBoard({ id: boardId, name: "Newname" });
// Assert
- await expect(actAsync()).rejects.toThrowError(
- "Board with similar name already exists",
- );
+ await expect(actAsync()).rejects.toThrowError("Board with similar name already exists");
});
test("should throw error when board not found", async () => {
@@ -399,8 +383,7 @@ describe("rename board should rename board", () => {
const caller = boardRouter.createCaller({ db, session: defaultSession });
// Act
- const actAsync = async () =>
- await caller.renameBoard({ id: "nonExistentBoardId", name: "newName" });
+ const actAsync = async () => await caller.renameBoard({ id: "nonExistentBoardId", name: "newName" });
// Assert
await expect(actAsync()).rejects.toThrowError("Board not found");
@@ -439,11 +422,7 @@ describe("changeBoardVisibility should change board visibility", () => {
});
expect(dbBoard).toBeDefined();
expect(dbBoard?.isPublic).toBe(visibility === "public");
- expect(spy).toHaveBeenCalledWith(
- expect.anything(),
- expect.anything(),
- "full-access",
- );
+ expect(spy).toHaveBeenCalledWith(expect.anything(), expect.anything(), "full-access");
},
);
});
@@ -473,11 +452,7 @@ describe("deleteBoard should delete board", () => {
where: eq(boards.id, boardId),
});
expect(dbBoard).toBeUndefined();
- expect(spy).toHaveBeenCalledWith(
- expect.anything(),
- expect.anything(),
- "full-access",
- );
+ expect(spy).toHaveBeenCalledWith(expect.anything(), expect.anything(), "full-access");
});
test("should throw error when board not found", async () => {
@@ -486,8 +461,7 @@ describe("deleteBoard should delete board", () => {
const caller = boardRouter.createCaller({ db, session: defaultSession });
// Act
- const actAsync = async () =>
- await caller.deleteBoard({ id: "nonExistentBoardId" });
+ const actAsync = async () => await caller.deleteBoard({ id: "nonExistentBoardId" });
// Assert
await expect(actAsync()).rejects.toThrowError("Board not found");
@@ -511,40 +485,29 @@ describe("getHomeBoard should return home board", () => {
name: "home",
...fullBoardProps,
});
- expect(spy).toHaveBeenCalledWith(
- expect.anything(),
- expect.anything(),
- "board-view",
- );
+ expect(spy).toHaveBeenCalledWith(expect.anything(), expect.anything(), "board-view");
});
});
describe("getBoardByName should return board by name", () => {
- it.each([["default"], ["something"]])(
- "should return board by name %s when present",
- async (name) => {
- // Arrange
- const spy = vi.spyOn(boardAccess, "throwIfActionForbiddenAsync");
- const db = createDb();
- const caller = boardRouter.createCaller({ db, session: defaultSession });
+ it.each([["default"], ["something"]])("should return board by name %s when present", async (name) => {
+ // Arrange
+ const spy = vi.spyOn(boardAccess, "throwIfActionForbiddenAsync");
+ const db = createDb();
+ const caller = boardRouter.createCaller({ db, session: defaultSession });
- const fullBoardProps = await createFullBoardAsync(db, name);
+ const fullBoardProps = await createFullBoardAsync(db, name);
- // Act
- const result = await caller.getBoardByName({ name });
+ // Act
+ const result = await caller.getBoardByName({ name });
- // Assert
- expectInputToBeFullBoardWithName(result, {
- name,
- ...fullBoardProps,
- });
- expect(spy).toHaveBeenCalledWith(
- expect.anything(),
- expect.anything(),
- "board-view",
- );
- },
- );
+ // Assert
+ expectInputToBeFullBoardWithName(result, {
+ name,
+ ...fullBoardProps,
+ });
+ expect(spy).toHaveBeenCalledWith(expect.anything(), expect.anything(), "board-view");
+ });
it("should throw error when not present", async () => {
// Arrange
@@ -553,8 +516,7 @@ describe("getBoardByName should return board by name", () => {
await createFullBoardAsync(db, "default");
// Act
- const actAsync = async () =>
- await caller.getBoardByName({ name: "nonExistentBoard" });
+ const actAsync = async () => await caller.getBoardByName({ name: "nonExistentBoard" });
// Assert
await expect(actAsync()).rejects.toThrowError("Board not found");
@@ -611,9 +573,7 @@ describe("savePartialBoardSettings should save general settings", () => {
expect(dbBoard?.metaTitle).toBe(newMetaTitle);
expect(dbBoard?.logoImageUrl).toBe(newLogoImageUrl);
expect(dbBoard?.faviconImageUrl).toBe(newFaviconImageUrl);
- expect(dbBoard?.backgroundImageAttachment).toBe(
- newBackgroundImageAttachment,
- );
+ expect(dbBoard?.backgroundImageAttachment).toBe(newBackgroundImageAttachment);
expect(dbBoard?.backgroundImageRepeat).toBe(newBackgroundImageRepeat);
expect(dbBoard?.backgroundImageSize).toBe(newBackgroundImageSize);
expect(dbBoard?.backgroundImageUrl).toBe(newBackgroundImageUrl);
@@ -623,11 +583,7 @@ describe("savePartialBoardSettings should save general settings", () => {
expect(dbBoard?.primaryColor).toBe(newPrimaryColor);
expect(dbBoard?.secondaryColor).toBe(newSecondaryColor);
- expect(spy).toHaveBeenCalledWith(
- expect.anything(),
- expect.anything(),
- "board-change",
- );
+ expect(spy).toHaveBeenCalledWith(expect.anything(), expect.anything(), "board-change");
});
it("should throw error when board not found", async () => {
@@ -682,21 +638,14 @@ describe("saveBoard should save full board", () => {
expect(definedBoard.sections.length).toBe(1);
expect(definedBoard.sections[0]?.id).not.toBe(sectionId);
expect(section).toBeUndefined();
- expect(spy).toHaveBeenCalledWith(
- expect.anything(),
- expect.anything(),
- "board-change",
- );
+ expect(spy).toHaveBeenCalledWith(expect.anything(), expect.anything(), "board-change");
});
it("should remove item when not present in input", async () => {
const spy = vi.spyOn(boardAccess, "throwIfActionForbiddenAsync");
const db = createDb();
const caller = boardRouter.createCaller({ db, session: defaultSession });
- const { boardId, itemId, sectionId } = await createFullBoardAsync(
- db,
- "default",
- );
+ const { boardId, itemId, sectionId } = await createFullBoardAsync(db, "default");
await caller.saveBoard({
id: boardId,
@@ -742,11 +691,7 @@ describe("saveBoard should save full board", () => {
expect(firstSection.items.length).toBe(1);
expect(firstSection.items[0]?.id).not.toBe(itemId);
expect(item).toBeUndefined();
- expect(spy).toHaveBeenCalledWith(
- expect.anything(),
- expect.anything(),
- "board-change",
- );
+ expect(spy).toHaveBeenCalledWith(expect.anything(), expect.anything(), "board-change");
});
it("should remove integration reference when not present in input", async () => {
const spy = vi.spyOn(boardAccess, "throwIfActionForbiddenAsync");
@@ -759,8 +704,7 @@ describe("saveBoard should save full board", () => {
url: "http://localhost:3000",
} as const;
- const { boardId, itemId, integrationId, sectionId } =
- await createFullBoardAsync(db, "default");
+ const { boardId, itemId, integrationId, sectionId } = await createFullBoardAsync(db, "default");
await db.insert(integrations).values(anotherIntegration);
await caller.saveBoard({
@@ -813,71 +757,61 @@ describe("saveBoard should save full board", () => {
expect(firstItem.integrations.length).toBe(1);
expect(firstItem.integrations[0]?.integrationId).not.toBe(integrationId);
expect(integration).toBeUndefined();
- expect(spy).toHaveBeenCalledWith(
- expect.anything(),
- expect.anything(),
- "board-change",
- );
+ expect(spy).toHaveBeenCalledWith(expect.anything(), expect.anything(), "board-change");
});
- it.each([
- [{ kind: "empty" as const }],
- [{ kind: "category" as const, name: "My first category" }],
- ])("should add section when present in input", async (partialSection) => {
- const spy = vi.spyOn(boardAccess, "throwIfActionForbiddenAsync");
- const db = createDb();
- const caller = boardRouter.createCaller({ db, session: defaultSession });
+ it.each([[{ kind: "empty" as const }], [{ kind: "category" as const, name: "My first category" }]])(
+ "should add section when present in input",
+ async (partialSection) => {
+ const spy = vi.spyOn(boardAccess, "throwIfActionForbiddenAsync");
+ const db = createDb();
+ const caller = boardRouter.createCaller({ db, session: defaultSession });
- const { boardId, sectionId } = await createFullBoardAsync(db, "default");
+ const { boardId, sectionId } = await createFullBoardAsync(db, "default");
- const newSectionId = createId();
- await caller.saveBoard({
- id: boardId,
- sections: [
- {
- id: newSectionId,
- position: 1,
- items: [],
- ...partialSection,
- },
- {
- id: sectionId,
- kind: "empty",
- position: 0,
- items: [],
- },
- ],
- });
+ const newSectionId = createId();
+ await caller.saveBoard({
+ id: boardId,
+ sections: [
+ {
+ id: newSectionId,
+ position: 1,
+ items: [],
+ ...partialSection,
+ },
+ {
+ id: sectionId,
+ kind: "empty",
+ position: 0,
+ items: [],
+ },
+ ],
+ });
- const board = await db.query.boards.findFirst({
- where: eq(boards.id, boardId),
- with: {
- sections: true,
- },
- });
+ const board = await db.query.boards.findFirst({
+ where: eq(boards.id, boardId),
+ with: {
+ sections: true,
+ },
+ });
- const section = await db.query.sections.findFirst({
- where: eq(sections.id, newSectionId),
- });
+ const section = await db.query.sections.findFirst({
+ where: eq(sections.id, newSectionId),
+ });
- const definedBoard = expectToBeDefined(board);
- expect(definedBoard.sections.length).toBe(2);
- const addedSection = expectToBeDefined(
- definedBoard.sections.find((section) => section.id === newSectionId),
- );
- expect(addedSection).toBeDefined();
- expect(addedSection.id).toBe(newSectionId);
- expect(addedSection.kind).toBe(partialSection.kind);
- expect(addedSection.position).toBe(1);
- if ("name" in partialSection) {
- expect(addedSection.name).toBe(partialSection.name);
- }
- expect(section).toBeDefined();
- expect(spy).toHaveBeenCalledWith(
- expect.anything(),
- expect.anything(),
- "board-change",
- );
- });
+ const definedBoard = expectToBeDefined(board);
+ expect(definedBoard.sections.length).toBe(2);
+ const addedSection = expectToBeDefined(definedBoard.sections.find((section) => section.id === newSectionId));
+ expect(addedSection).toBeDefined();
+ expect(addedSection.id).toBe(newSectionId);
+ expect(addedSection.kind).toBe(partialSection.kind);
+ expect(addedSection.position).toBe(1);
+ if ("name" in partialSection) {
+ expect(addedSection.name).toBe(partialSection.name);
+ }
+ expect(section).toBeDefined();
+ expect(spy).toHaveBeenCalledWith(expect.anything(), expect.anything(), "board-change");
+ },
+ );
it("should add item when present in input", async () => {
const spy = vi.spyOn(boardAccess, "throwIfActionForbiddenAsync");
const db = createDb();
@@ -928,25 +862,17 @@ describe("saveBoard should save full board", () => {
expect(definedBoard.sections.length).toBe(1);
const firstSection = expectToBeDefined(definedBoard.sections[0]);
expect(firstSection.items.length).toBe(1);
- const addedItem = expectToBeDefined(
- firstSection.items.find((item) => item.id === newItemId),
- );
+ const addedItem = expectToBeDefined(firstSection.items.find((item) => item.id === newItemId));
expect(addedItem).toBeDefined();
expect(addedItem.id).toBe(newItemId);
expect(addedItem.kind).toBe("clock");
- expect(addedItem.options).toBe(
- SuperJSON.stringify({ is24HourFormat: true }),
- );
+ expect(addedItem.options).toBe(SuperJSON.stringify({ is24HourFormat: true }));
expect(addedItem.height).toBe(1);
expect(addedItem.width).toBe(1);
expect(addedItem.xOffset).toBe(3);
expect(addedItem.yOffset).toBe(2);
expect(item).toBeDefined();
- expect(spy).toHaveBeenCalledWith(
- expect.anything(),
- expect.anything(),
- "board-change",
- );
+ expect(spy).toHaveBeenCalledWith(expect.anything(), expect.anything(), "board-change");
});
it("should add integration reference when present in input", async () => {
const spy = vi.spyOn(boardAccess, "throwIfActionForbiddenAsync");
@@ -959,10 +885,7 @@ describe("saveBoard should save full board", () => {
url: "http://plex.local",
} as const;
- const { boardId, itemId, sectionId } = await createFullBoardAsync(
- db,
- "default",
- );
+ const { boardId, itemId, sectionId } = await createFullBoardAsync(db, "default");
await db.insert(integrations).values(integration);
await caller.saveBoard({
@@ -1011,17 +934,11 @@ describe("saveBoard should save full board", () => {
expect(definedBoard.sections.length).toBe(1);
const firstSection = expectToBeDefined(definedBoard.sections[0]);
expect(firstSection.items.length).toBe(1);
- const firstItem = expectToBeDefined(
- firstSection.items.find((item) => item.id === itemId),
- );
+ const firstItem = expectToBeDefined(firstSection.items.find((item) => item.id === itemId));
expect(firstItem.integrations.length).toBe(1);
expect(firstItem.integrations[0]?.integrationId).toBe(integration.id);
expect(integrationItem).toBeDefined();
- expect(spy).toHaveBeenCalledWith(
- expect.anything(),
- expect.anything(),
- "board-change",
- );
+ expect(spy).toHaveBeenCalledWith(expect.anything(), expect.anything(), "board-change");
});
it("should update section when present in input", async () => {
const db = createDb();
@@ -1066,16 +983,12 @@ describe("saveBoard should save full board", () => {
const definedBoard = expectToBeDefined(board);
expect(definedBoard.sections.length).toBe(2);
- const firstSection = expectToBeDefined(
- definedBoard.sections.find((section) => section.id === sectionId),
- );
+ const firstSection = expectToBeDefined(definedBoard.sections.find((section) => section.id === sectionId));
expect(firstSection.id).toBe(sectionId);
expect(firstSection.kind).toBe("empty");
expect(firstSection.position).toBe(1);
expect(firstSection.name).toBe(null);
- const secondSection = expectToBeDefined(
- definedBoard.sections.find((section) => section.id === newSectionId),
- );
+ const secondSection = expectToBeDefined(definedBoard.sections.find((section) => section.id === newSectionId));
expect(secondSection.id).toBe(newSectionId);
expect(secondSection.kind).toBe("category");
expect(secondSection.position).toBe(0);
@@ -1086,10 +999,7 @@ describe("saveBoard should save full board", () => {
const db = createDb();
const caller = boardRouter.createCaller({ db, session: defaultSession });
- const { boardId, itemId, sectionId } = await createFullBoardAsync(
- db,
- "default",
- );
+ const { boardId, itemId, sectionId } = await createFullBoardAsync(db, "default");
await caller.saveBoard({
id: boardId,
@@ -1129,24 +1039,15 @@ describe("saveBoard should save full board", () => {
expect(definedBoard.sections.length).toBe(1);
const firstSection = expectToBeDefined(definedBoard.sections[0]);
expect(firstSection.items.length).toBe(1);
- const firstItem = expectToBeDefined(
- firstSection.items.find((item) => item.id === itemId),
- );
+ const firstItem = expectToBeDefined(firstSection.items.find((item) => item.id === itemId));
expect(firstItem.id).toBe(itemId);
expect(firstItem.kind).toBe("clock");
- expect(
- SuperJSON.parse<{ is24HourFormat: boolean }>(firstItem.options)
- .is24HourFormat,
- ).toBe(false);
+ expect(SuperJSON.parse<{ is24HourFormat: boolean }>(firstItem.options).is24HourFormat).toBe(false);
expect(firstItem.height).toBe(3);
expect(firstItem.width).toBe(2);
expect(firstItem.xOffset).toBe(7);
expect(firstItem.yOffset).toBe(5);
- expect(spy).toHaveBeenCalledWith(
- expect.anything(),
- expect.anything(),
- "board-change",
- );
+ expect(spy).toHaveBeenCalledWith(expect.anything(), expect.anything(), "board-change");
});
it("should fail when board not found", async () => {
const db = createDb();
@@ -1216,9 +1117,7 @@ describe("getBoardPermissions should return board permissions", () => {
const result = await caller.getBoardPermissions({ id: boardId });
// Assert
- expect(result.groupPermissions).toEqual([
- { group: { id: groupId, name: "group1" }, permission: "board-view" },
- ]);
+ expect(result.groupPermissions).toEqual([{ group: { id: groupId, name: "group1" }, permission: "board-view" }]);
expect(result.userPermissions).toEqual(
expect.arrayContaining([
{
@@ -1231,14 +1130,8 @@ describe("getBoardPermissions should return board permissions", () => {
},
]),
);
- expect(result.inherited).toEqual([
- { group: { id: groupId, name: "group1" }, permission: "admin" },
- ]);
- expect(spy).toHaveBeenCalledWith(
- expect.anything(),
- expect.anything(),
- "full-access",
- );
+ expect(result.inherited).toEqual([{ group: { id: groupId, name: "group1" }, permission: "admin" }]);
+ expect(spy).toHaveBeenCalledWith(expect.anything(), expect.anything(), "full-access");
});
});
@@ -1279,11 +1172,7 @@ describe("saveUserBoardPermissions should save user board permissions", () => {
where: eq(boardUserPermissions.userId, user1),
});
expect(dbUserPermission).toBeDefined();
- expect(spy).toHaveBeenCalledWith(
- expect.anything(),
- expect.anything(),
- "full-access",
- );
+ expect(spy).toHaveBeenCalledWith(expect.anything(), expect.anything(), "full-access");
},
);
});
@@ -1330,11 +1219,7 @@ describe("saveGroupBoardPermissions should save group board permissions", () =>
where: eq(boardGroupPermissions.groupId, groupId),
});
expect(dbGroupPermission).toBeDefined();
- expect(spy).toHaveBeenCalledWith(
- expect.anything(),
- expect.anything(),
- "full-access",
- );
+ expect(spy).toHaveBeenCalledWith(expect.anything(), expect.anything(), "full-access");
},
);
});
diff --git a/packages/api/src/router/test/board/board-access.spec.ts b/packages/api/src/router/test/board/board-access.spec.ts
index 6a9a8b520..a9072f7e6 100644
--- a/packages/api/src/router/test/board/board-access.spec.ts
+++ b/packages/api/src/router/test/board/board-access.spec.ts
@@ -9,10 +9,7 @@ import { throwIfActionForbiddenAsync } from "../../board/board-access";
const defaultCreatorId = createId();
-const expectActToBeAsync = async (
- act: () => Promise<void>,
- success: boolean,
-) => {
+const expectActToBeAsync = async (act: () => Promise<void>, success: boolean) => {
if (!success) {
await expect(act()).rejects.toThrow("Board not found");
return;
@@ -29,161 +26,124 @@ describe("throwIfActionForbiddenAsync should check access to board and return bo
["full-access" as const, true],
["board-change" as const, true],
["board-view" as const, true],
- ])(
- "with permission %s should return %s when hasFullAccess is true",
- async (permission, expectedResult) => {
- // Arrange
- const db = createDb();
- const spy = vi.spyOn(authShared, "constructBoardPermissions");
- spy.mockReturnValue({
- hasFullAccess: true,
- hasChangeAccess: false,
- hasViewAccess: false,
- });
-
- await db.insert(users).values({ id: defaultCreatorId });
- const boardId = createId();
- await db.insert(boards).values({
- id: boardId,
- name: "test",
- creatorId: defaultCreatorId,
- });
-
- // Act
- const act = () =>
- throwIfActionForbiddenAsync(
- { db, session: null },
- eq(boards.id, boardId),
- permission,
- );
-
- // Assert
- await expectActToBeAsync(act, expectedResult);
- },
- );
+ ])("with permission %s should return %s when hasFullAccess is true", async (permission, expectedResult) => {
+ // Arrange
+ const db = createDb();
+ const spy = vi.spyOn(authShared, "constructBoardPermissions");
+ spy.mockReturnValue({
+ hasFullAccess: true,
+ hasChangeAccess: false,
+ hasViewAccess: false,
+ });
+
+ await db.insert(users).values({ id: defaultCreatorId });
+ const boardId = createId();
+ await db.insert(boards).values({
+ id: boardId,
+ name: "test",
+ creatorId: defaultCreatorId,
+ });
+
+ // Act
+ const act = () => throwIfActionForbiddenAsync({ db, session: null }, eq(boards.id, boardId), permission);
+
+ // Assert
+ await expectActToBeAsync(act, expectedResult);
+ });
test.each([
["full-access" as const, false],
["board-change" as const, true],
["board-view" as const, true],
- ])(
- "with permission %s should return %s when hasChangeAccess is true",
- async (permission, expectedResult) => {
- // Arrange
- const db = createDb();
- const spy = vi.spyOn(authShared, "constructBoardPermissions");
- spy.mockReturnValue({
- hasFullAccess: false,
- hasChangeAccess: true,
- hasViewAccess: false,
- });
-
- await db.insert(users).values({ id: defaultCreatorId });
- const boardId = createId();
- await db.insert(boards).values({
- id: boardId,
- name: "test",
- creatorId: defaultCreatorId,
- });
-
- // Act
- const act = () =>
- throwIfActionForbiddenAsync(
- { db, session: null },
- eq(boards.id, boardId),
- permission,
- );
-
- // Assert
- await expectActToBeAsync(act, expectedResult);
- },
- );
+ ])("with permission %s should return %s when hasChangeAccess is true", async (permission, expectedResult) => {
+ // Arrange
+ const db = createDb();
+ const spy = vi.spyOn(authShared, "constructBoardPermissions");
+ spy.mockReturnValue({
+ hasFullAccess: false,
+ hasChangeAccess: true,
+ hasViewAccess: false,
+ });
+
+ await db.insert(users).values({ id: defaultCreatorId });
+ const boardId = createId();
+ await db.insert(boards).values({
+ id: boardId,
+ name: "test",
+ creatorId: defaultCreatorId,
+ });
+
+ // Act
+ const act = () => throwIfActionForbiddenAsync({ db, session: null }, eq(boards.id, boardId), permission);
+
+ // Assert
+ await expectActToBeAsync(act, expectedResult);
+ });
test.each([
["full-access" as const, false],
["board-change" as const, false],
["board-view" as const, true],
- ])(
- "with permission %s should return %s when hasViewAccess is true",
- async (permission, expectedResult) => {
- // Arrange
- const db = createDb();
- const spy = vi.spyOn(authShared, "constructBoardPermissions");
- spy.mockReturnValue({
- hasFullAccess: false,
- hasChangeAccess: false,
- hasViewAccess: true,
- });
-
- await db.insert(users).values({ id: defaultCreatorId });
- const boardId = createId();
- await db.insert(boards).values({
- id: boardId,
- name: "test",
- creatorId: defaultCreatorId,
- });
-
- // Act
- const act = () =>
- throwIfActionForbiddenAsync(
- { db, session: null },
- eq(boards.id, boardId),
- permission,
- );
-
- // Assert
- await expectActToBeAsync(act, expectedResult);
- },
- );
+ ])("with permission %s should return %s when hasViewAccess is true", async (permission, expectedResult) => {
+ // Arrange
+ const db = createDb();
+ const spy = vi.spyOn(authShared, "constructBoardPermissions");
+ spy.mockReturnValue({
+ hasFullAccess: false,
+ hasChangeAccess: false,
+ hasViewAccess: true,
+ });
+
+ await db.insert(users).values({ id: defaultCreatorId });
+ const boardId = createId();
+ await db.insert(boards).values({
+ id: boardId,
+ name: "test",
+ creatorId: defaultCreatorId,
+ });
+
+ // Act
+ const act = () => throwIfActionForbiddenAsync({ db, session: null }, eq(boards.id, boardId), permission);
+
+ // Assert
+ await expectActToBeAsync(act, expectedResult);
+ });
test.each([
["full-access" as const, false],
["board-change" as const, false],
["board-view" as const, false],
- ])(
- "with permission %s should return %s when hasViewAccess is false",
- async (permission, expectedResult) => {
- // Arrange
- const db = createDb();
- const spy = vi.spyOn(authShared, "constructBoardPermissions");
- spy.mockReturnValue({
- hasFullAccess: false,
- hasChangeAccess: false,
- hasViewAccess: false,
- });
-
- await db.insert(users).values({ id: defaultCreatorId });
- const boardId = createId();
- await db.insert(boards).values({
- id: boardId,
- name: "test",
- creatorId: defaultCreatorId,
- });
-
- // Act
- const act = () =>
- throwIfActionForbiddenAsync(
- { db, session: null },
- eq(boards.id, boardId),
- permission,
- );
-
- // Assert
- await expectActToBeAsync(act, expectedResult);
- },
- );
+ ])("with permission %s should return %s when hasViewAccess is false", async (permission, expectedResult) => {
+ // Arrange
+ const db = createDb();
+ const spy = vi.spyOn(authShared, "constructBoardPermissions");
+ spy.mockReturnValue({
+ hasFullAccess: false,
+ hasChangeAccess: false,
+ hasViewAccess: false,
+ });
+
+ await db.insert(users).values({ id: defaultCreatorId });
+ const boardId = createId();
+ await db.insert(boards).values({
+ id: boardId,
+ name: "test",
+ creatorId: defaultCreatorId,
+ });
+
+ // Act
+ const act = () => throwIfActionForbiddenAsync({ db, session: null }, eq(boards.id, boardId), permission);
+
+ // Assert
+ await expectActToBeAsync(act, expectedResult);
+ });
test("should throw when board is not found", async () => {
// Arrange
const db = createDb();
// Act
- const act = () =>
- throwIfActionForbiddenAsync(
- { db, session: null },
- eq(boards.id, createId()),
- "full-access",
- );
+ const act = () => throwIfActionForbiddenAsync({ db, session: null }, eq(boards.id, createId()), "full-access");
// Assert
await expect(act()).rejects.toThrow("Board not found");
diff --git a/packages/api/src/router/test/group.spec.ts b/packages/api/src/router/test/group.spec.ts
index 130040a09..2901ec32b 100644
--- a/packages/api/src/router/test/group.spec.ts
+++ b/packages/api/src/router/test/group.spec.ts
@@ -2,12 +2,7 @@ import { describe, expect, test, vi } from "vitest";
import type { Session } from "@homarr/auth";
import { createId, eq } from "@homarr/db";
-import {
- groupMembers,
- groupPermissions,
- groups,
- users,
-} from "@homarr/db/schema/sqlite";
+import { groupMembers, groupPermissions, groups, users } from "@homarr/db/schema/sqlite";
import { createDb } from "@homarr/db/test";
import { groupRouter } from "../group";
@@ -103,9 +98,7 @@ describe("paginated should return a list of groups with pagination", () => {
expect(item?.members.length).toBe(1);
const userKeys = Object.keys(item?.members[0] ?? {});
expect(userKeys.length).toBe(4);
- expect(
- ["id", "name", "email", "image"].some((key) => userKeys.includes(key)),
- );
+ expect(["id", "name", "email", "image"].some((key) => userKeys.includes(key)));
});
test.each([
@@ -178,9 +171,7 @@ describe("byId should return group by id including members and permissions", ()
const userKeys = Object.keys(result?.members[0] ?? {});
expect(userKeys.length).toBe(4);
- expect(
- ["id", "name", "email", "image"].some((key) => userKeys.includes(key)),
- );
+ expect(["id", "name", "email", "image"].some((key) => userKeys.includes(key)));
expect(result.permissions.length).toBe(1);
expect(result.permissions[0]).toBe("admin");
});
@@ -249,98 +240,88 @@ describe("create should create group in database", () => {
["test", "Test "],
["test", "test"],
["test", " TeSt"],
- ])(
- "with similar name %s it should fail to create %s",
- async (similarName, nameToCreate) => {
- // Arrange
- const db = createDb();
- const caller = groupRouter.createCaller({ db, session: defaultSession });
+ ])("with similar name %s it should fail to create %s", async (similarName, nameToCreate) => {
+ // Arrange
+ const db = createDb();
+ const caller = groupRouter.createCaller({ db, session: defaultSession });
- await db.insert(groups).values({
- id: createId(),
- name: similarName,
- });
+ await db.insert(groups).values({
+ id: createId(),
+ name: similarName,
+ });
- // Act
- const actAsync = async () =>
- await caller.createGroup({ name: nameToCreate });
+ // Act
+ const actAsync = async () => await caller.createGroup({ name: nameToCreate });
- // Assert
- await expect(actAsync()).rejects.toThrow("similar name");
- },
- );
+ // Assert
+ await expect(actAsync()).rejects.toThrow("similar name");
+ });
});
describe("update should update name with value that is no duplicate", () => {
test.each([
["first", "second ", "second"],
["first", " first", "first"],
- ])(
- "update should update name from %s to %s normalized",
- async (initialValue, updateValue, expectedValue) => {
- // Arrange
- const db = createDb();
- const caller = groupRouter.createCaller({ db, session: defaultSession });
-
- const groupId = createId();
- await db.insert(groups).values([
- {
- id: groupId,
- name: initialValue,
- },
- {
- id: createId(),
- name: "Third",
- },
- ]);
+ ])("update should update name from %s to %s normalized", async (initialValue, updateValue, expectedValue) => {
+ // Arrange
+ const db = createDb();
+ const caller = groupRouter.createCaller({ db, session: defaultSession });
- // Act
- await caller.updateGroup({
+ const groupId = createId();
+ await db.insert(groups).values([
+ {
id: groupId,
- name: updateValue,
- });
+ name: initialValue,
+ },
+ {
+ id: createId(),
+ name: "Third",
+ },
+ ]);
- // Assert
- const value = await db.query.groups.findFirst({
- where: eq(groups.id, groupId),
- });
- expect(value?.name).toBe(expectedValue);
- },
- );
+ // Act
+ await caller.updateGroup({
+ id: groupId,
+ name: updateValue,
+ });
+
+ // Assert
+ const value = await db.query.groups.findFirst({
+ where: eq(groups.id, groupId),
+ });
+ expect(value?.name).toBe(expectedValue);
+ });
test.each([
["Second ", "second"],
[" seCond", "second"],
- ])(
- "with similar name %s it should fail to update %s",
- async (updateValue, initialDuplicate) => {
- // Arrange
- const db = createDb();
- const caller = groupRouter.createCaller({ db, session: defaultSession });
+ ])("with similar name %s it should fail to update %s", async (updateValue, initialDuplicate) => {
+ // Arrange
+ const db = createDb();
+ const caller = groupRouter.createCaller({ db, session: defaultSession });
- const groupId = createId();
- await db.insert(groups).values([
- {
- id: groupId,
- name: "Something",
- },
- {
- id: createId(),
- name: initialDuplicate,
- },
- ]);
+ const groupId = createId();
+ await db.insert(groups).values([
+ {
+ id: groupId,
+ name: "Something",
+ },
+ {
+ id: createId(),
+ name: initialDuplicate,
+ },
+ ]);
- // Act
- const actAsync = async () =>
- await caller.updateGroup({
- id: groupId,
- name: updateValue,
- });
+ // Act
+ const actAsync = async () =>
+ await caller.updateGroup({
+ id: groupId,
+ name: updateValue,
+ });
- // Assert
- await expect(actAsync()).rejects.toThrow("similar name");
- },
- );
+ // Assert
+ await expect(actAsync()).rejects.toThrow("similar name");
+ });
test("with non existing id it should throw not found error", async () => {
// Arrange
@@ -392,10 +373,7 @@ describe("savePermissions should save permissions for group", () => {
});
expect(permissions.length).toBe(2);
- expect(permissions.map(({ permission }) => permission)).toEqual([
- "integration-use-all",
- "board-full-access",
- ]);
+ expect(permissions.map(({ permission }) => permission)).toEqual(["integration-use-all", "board-full-access"]);
});
test("with non existing group it should throw not found error", async () => {
diff --git a/packages/api/src/router/test/integration.spec.ts b/packages/api/src/router/test/integration.spec.ts
index ca6d0eb3f..2a68a8c39 100644
--- a/packages/api/src/router/test/integration.spec.ts
+++ b/packages/api/src/router/test/integration.spec.ts
@@ -118,17 +118,11 @@ describe("byId should return an integration by id", () => {
const result = await caller.byId({ id: "1" });
expect(result.secrets.length).toBe(3);
- const username = expectToBeDefined(
- result.secrets.find((secret) => secret.kind === "username"),
- );
+ const username = expectToBeDefined(result.secrets.find((secret) => secret.kind === "username"));
expect(username.value).not.toBeNull();
- const password = expectToBeDefined(
- result.secrets.find((secret) => secret.kind === "password"),
- );
+ const password = expectToBeDefined(result.secrets.find((secret) => secret.kind === "password"));
expect(password.value).toBeNull();
- const apiKey = expectToBeDefined(
- result.secrets.find((secret) => secret.kind === "apiKey"),
- );
+ const apiKey = expectToBeDefined(result.secrets.find((secret) => secret.kind === "apiKey"));
expect(apiKey.value).toBeNull();
});
});
@@ -200,9 +194,7 @@ describe("update should update an integration", () => {
integrationId,
updatedAt: lastWeek,
};
- await db
- .insert(integrationSecrets)
- .values([usernameToInsert, passwordToInsert]);
+ await db.insert(integrationSecrets).values([usernameToInsert, passwordToInsert]);
const input = {
id: integrationId,
@@ -231,15 +223,9 @@ describe("update should update an integration", () => {
expect(dbIntegration!.url).toBe(input.url);
expect(dbSecrets.length).toBe(3);
- const username = expectToBeDefined(
- dbSecrets.find((secret) => secret.kind === "username"),
- );
- const password = expectToBeDefined(
- dbSecrets.find((secret) => secret.kind === "password"),
- );
- const apiKey = expectToBeDefined(
- dbSecrets.find((secret) => secret.kind === "apiKey"),
- );
+ const username = expectToBeDefined(dbSecrets.find((secret) => secret.kind === "username"));
+ const password = expectToBeDefined(dbSecrets.find((secret) => secret.kind === "password"));
+ const apiKey = expectToBeDefined(dbSecrets.find((secret) => secret.kind === "apiKey"));
expect(username.value).toMatch(/^[a-f0-9]+.[a-f0-9]+$/);
expect(password.value).toMatch(/^[a-f0-9]+.[a-f0-9]+$/);
expect(apiKey.value).toMatch(/^[a-f0-9]+.[a-f0-9]+$/);
@@ -327,26 +313,23 @@ describe("testConnection should test the connection to an integration", () => {
{ kind: "password" as const, value: "Password123!" },
],
],
- ])(
- "should fail when a required secret is missing when creating %s integration",
- async (kind, secrets) => {
- const db = createDb();
- const caller = integrationRouter.createCaller({
- db,
- session: null,
- });
+ ])("should fail when a required secret is missing when creating %s integration", async (kind, secrets) => {
+ const db = createDb();
+ const caller = integrationRouter.createCaller({
+ db,
+ session: null,
+ });
- const input: RouterInputs["integration"]["testConnection"] = {
- id: null,
- kind,
- url: `http://${kind}.local`,
- secrets,
- };
+ const input: RouterInputs["integration"]["testConnection"] = {
+ id: null,
+ kind,
+ url: `http://${kind}.local`,
+ secrets,
+ };
- const actAsync = async () => await caller.testConnection(input);
- await expect(actAsync()).rejects.toThrow("SECRETS_NOT_DEFINED");
- },
- );
+ const actAsync = async () => await caller.testConnection(input);
+ await expect(actAsync()).rejects.toThrow("SECRETS_NOT_DEFINED");
+ });
it.each([
[
diff --git a/packages/api/src/router/test/serverSettings.spec.ts b/packages/api/src/router/test/serverSettings.spec.ts
index 9db8d1578..331631229 100644
--- a/packages/api/src/router/test/serverSettings.spec.ts
+++ b/packages/api/src/router/test/serverSettings.spec.ts
@@ -5,10 +5,7 @@ import type { Session } from "@homarr/auth";
import { createId } from "@homarr/db";
import { serverSettings } from "@homarr/db/schema/sqlite";
import { createDb } from "@homarr/db/test";
-import {
- defaultServerSettings,
- defaultServerSettingsKeys,
-} from "@homarr/server-settings";
+import { defaultServerSettings, defaultServerSettingsKeys } from "@homarr/server-settings";
import { serverSettingsRouter } from "../serverSettings";
diff --git a/packages/api/src/router/test/user.spec.ts b/packages/api/src/router/test/user.spec.ts
index 9dfee320c..59c58436f 100644
--- a/packages/api/src/router/test/user.spec.ts
+++ b/packages/api/src/router/test/user.spec.ts
@@ -218,10 +218,7 @@ describe("editProfile shoud update user", () => {
});
// assert
- const user = await db
- .select()
- .from(schema.users)
- .where(eq(schema.users.id, id));
+ const user = await db.select().from(schema.users).where(eq(schema.users.id, id));
expect(user).toHaveLength(1);
expect(user[0]).toStrictEqual({
@@ -261,10 +258,7 @@ describe("editProfile shoud update user", () => {
});
// assert
- const user = await db
- .select()
- .from(schema.users)
- .where(eq(schema.users.id, id));
+ const user = await db.select().from(schema.users).where(eq(schema.users.id, id));
expect(user).toHaveLength(1);
expect(user[0]).toStrictEqual({
diff --git a/packages/api/src/router/user.ts b/packages/api/src/router/user.ts
index 07a8fe298..edffc2ae5 100644
--- a/packages/api/src/router/user.ts
+++ b/packages/api/src/router/user.ts
@@ -11,55 +11,46 @@ import { validation, z } from "@homarr/validation";
import { createTRPCRouter, protectedProcedure, publicProcedure } from "../trpc";
export const userRouter = createTRPCRouter({
- initUser: publicProcedure
- .input(validation.user.init)
- .mutation(async ({ ctx, input }) => {
- const firstUser = await ctx.db.query.users.findFirst({
- columns: {
- id: true,
- },
+ initUser: publicProcedure.input(validation.user.init).mutation(async ({ ctx, input }) => {
+ const firstUser = await ctx.db.query.users.findFirst({
+ columns: {
+ id: true,
+ },
+ });
+
+ if (firstUser) {
+ throw new TRPCError({
+ code: "FORBIDDEN",
+ message: "User already exists",
});
+ }
- if (firstUser) {
- throw new TRPCError({
- code: "FORBIDDEN",
- message: "User already exists",
- });
- }
+ await createUserAsync(ctx.db, input);
+ }),
+ register: publicProcedure.input(validation.user.registrationApi).mutation(async ({ ctx, input }) => {
+ const inviteWhere = and(eq(invites.id, input.inviteId), eq(invites.token, input.token));
+ const dbInvite = await ctx.db.query.invites.findFirst({
+ columns: {
+ id: true,
+ expirationDate: true,
+ },
+ where: inviteWhere,
+ });
- await createUserAsync(ctx.db, input);
- }),
- register: publicProcedure
- .input(validation.user.registrationApi)
- .mutation(async ({ ctx, input }) => {
- const inviteWhere = and(
- eq(invites.id, input.inviteId),
- eq(invites.token, input.token),
- );
- const dbInvite = await ctx.db.query.invites.findFirst({
- columns: {
- id: true,
- expirationDate: true,
- },
- where: inviteWhere,
+ if (!dbInvite || dbInvite.expirationDate < new Date()) {
+ throw new TRPCError({
+ code: "FORBIDDEN",
+ message: "Invalid invite",
});
+ }
- if (!dbInvite || dbInvite.expirationDate < new Date()) {
- throw new TRPCError({
- code: "FORBIDDEN",
- message: "Invalid invite",
- });
- }
-
- await createUserAsync(ctx.db, input);
- // Delete invite as it's used
- await ctx.db.delete(invites).where(inviteWhere);
- }),
- create: publicProcedure
- .input(validation.user.create)
- .mutation(async ({ ctx, input }) => {
- await createUserAsync(ctx.db, input);
- }),
+ await createUserAsync(ctx.db, input);
+ // Delete invite as it's used
+ await ctx.db.delete(invites).where(inviteWhere);
+ }),
+ create: publicProcedure.input(validation.user.create).mutation(async ({ ctx, input }) => {
+ await createUserAsync(ctx.db, input);
+ }),
setProfileImage: protectedProcedure
.input(
z.object({
@@ -74,10 +65,7 @@ export const userRouter = createTRPCRouter({
)
.mutation(async ({ input, ctx }) => {
// Only admins can change other users profile images
- if (
- ctx.session.user.id !== input.userId &&
- !ctx.session.user.permissions.includes("admin")
- ) {
+ if (ctx.session.user.id !== input.userId && !ctx.session.user.permissions.includes("admin")) {
throw new TRPCError({
code: "FORBIDDEN",
message: "You are not allowed to change other users profile images",
@@ -126,112 +114,103 @@ export const userRouter = createTRPCRouter({
},
});
}),
- getById: publicProcedure
- .input(z.object({ userId: z.string() }))
- .query(async ({ input, ctx }) => {
- const user = await ctx.db.query.users.findFirst({
+ getById: publicProcedure.input(z.object({ userId: z.string() })).query(async ({ input, ctx }) => {
+ const user = await ctx.db.query.users.findFirst({
+ columns: {
+ id: true,
+ name: true,
+ email: true,
+ emailVerified: true,
+ image: true,
+ },
+ where: eq(users.id, input.userId),
+ });
+
+ if (!user) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "User not found",
+ });
+ }
+
+ return user;
+ }),
+ editProfile: publicProcedure.input(validation.user.editProfile).mutation(async ({ input, ctx }) => {
+ const user = await ctx.db.query.users.findFirst({
+ columns: { email: true },
+ where: eq(users.id, input.id),
+ });
+
+ if (!user) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "User not found",
+ });
+ }
+
+ const emailDirty = input.email && user.email !== input.email;
+ await ctx.db
+ .update(users)
+ .set({
+ name: input.name,
+ email: emailDirty === true ? input.email : undefined,
+ emailVerified: emailDirty === true ? null : undefined,
+ })
+ .where(eq(users.id, input.id));
+ }),
+ delete: publicProcedure.input(z.string()).mutation(async ({ input, ctx }) => {
+ await ctx.db.delete(users).where(eq(users.id, input));
+ }),
+ changePassword: protectedProcedure.input(validation.user.changePasswordApi).mutation(async ({ ctx, input }) => {
+ const user = ctx.session.user;
+ // Only admins can change other users' passwords
+ if (!user.permissions.includes("admin") && user.id !== input.userId) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "User not found",
+ });
+ }
+
+ // Admins can change the password of other users without providing the previous password
+ const isPreviousPasswordRequired = ctx.session.user.id === input.userId;
+
+ if (isPreviousPasswordRequired) {
+ const dbUser = await ctx.db.query.users.findFirst({
columns: {
id: true,
- name: true,
- email: true,
- emailVerified: true,
- image: true,
+ password: true,
+ salt: true,
},
where: eq(users.id, input.userId),
});
- if (!user) {
+ if (!dbUser) {
throw new TRPCError({
code: "NOT_FOUND",
message: "User not found",
});
}
- return user;
- }),
- editProfile: publicProcedure
- .input(validation.user.editProfile)
- .mutation(async ({ input, ctx }) => {
- const user = await ctx.db.query.users.findFirst({
- columns: { email: true },
- where: eq(users.id, input.id),
- });
+ const previousPasswordHash = await hashPasswordAsync(input.previousPassword, dbUser.salt ?? "");
+ const isValid = previousPasswordHash === dbUser.password;
- if (!user) {
+ if (!isValid) {
throw new TRPCError({
- code: "NOT_FOUND",
- message: "User not found",
+ code: "FORBIDDEN",
+ message: "Invalid password",
});
}
-
- const emailDirty = input.email && user.email !== input.email;
- await ctx.db
- .update(users)
- .set({
- name: input.name,
- email: emailDirty === true ? input.email : undefined,
- emailVerified: emailDirty === true ? null : undefined,
- })
- .where(eq(users.id, input.id));
- }),
- delete: publicProcedure.input(z.string()).mutation(async ({ input, ctx }) => {
- await ctx.db.delete(users).where(eq(users.id, input));
+ }
+
+ const salt = await createSaltAsync();
+ const hashedPassword = await hashPasswordAsync(input.password, salt);
+ await ctx.db
+ .update(users)
+ .set({
+ password: hashedPassword,
+ })
+ .where(eq(users.id, input.userId));
}),
- changePassword: protectedProcedure
- .input(validation.user.changePasswordApi)
- .mutation(async ({ ctx, input }) => {
- const user = ctx.session.user;
- // Only admins can change other users' passwords
- if (!user.permissions.includes("admin") && user.id !== input.userId) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "User not found",
- });
- }
-
- // Admins can change the password of other users without providing the previous password
- const isPreviousPasswordRequired = ctx.session.user.id === input.userId;
-
- if (isPreviousPasswordRequired) {
- const dbUser = await ctx.db.query.users.findFirst({
- columns: {
- id: true,
- password: true,
- salt: true,
- },
- where: eq(users.id, input.userId),
- });
-
- if (!dbUser) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "User not found",
- });
- }
-
- const previousPasswordHash = await hashPasswordAsync(
- input.previousPassword,
- dbUser.salt ?? "",
- );
- const isValid = previousPasswordHash === dbUser.password;
-
- if (!isValid) {
- throw new TRPCError({
- code: "FORBIDDEN",
- message: "Invalid password",
- });
- }
- }
-
- const salt = await createSaltAsync();
- const hashedPassword = await hashPasswordAsync(input.password, salt);
- await ctx.db
- .update(users)
- .set({
- password: hashedPassword,
- })
- .where(eq(users.id, input.userId));
- }),
setMessage: publicProcedure.input(z.string()).mutation(async ({ input }) => {
await exampleChannel.publishAsync({ message: input });
}),
@@ -244,10 +223,7 @@ export const userRouter = createTRPCRouter({
}),
});
-const createUserAsync = async (
- db: Database,
- input: z.infer<typeof validation.user.create>,
-) => {
+const createUserAsync = async (db: Database, input: z.infer<typeof validation.user.create>) => {
const salt = await createSaltAsync();
const hashedPassword = await hashPasswordAsync(input.password, salt);
diff --git a/packages/api/src/trpc.ts b/packages/api/src/trpc.ts
index 0f64c9ff8..a15612a2a 100644
--- a/packages/api/src/trpc.ts
+++ b/packages/api/src/trpc.ts
@@ -27,17 +27,11 @@ import { ZodError } from "@homarr/validation";
*
* @see https://trpc.io/docs/server/context
*/
-export const createTRPCContext = (opts: {
- headers: Headers;
- session: Session | null;
-}) => {
+export const createTRPCContext = (opts: { headers: Headers; session: Session | null }) => {
const session = opts.session;
const source = opts.headers.get("x-trpc-source") ?? "unknown";
- logger.info(
- `tRPC request from ${source} by user '${session?.user.id}'`,
- session?.user,
- );
+ logger.info(`tRPC request from ${source} by user '${session?.user.id}'`, session?.user);
return {
session,
diff --git a/packages/auth/callbacks.ts b/packages/auth/callbacks.ts
index ddad44996..3fdeb0c54 100644
--- a/packages/auth/callbacks.ts
+++ b/packages/auth/callbacks.ts
@@ -7,17 +7,9 @@ import { eq, inArray } from "@homarr/db";
import { groupMembers, groupPermissions } from "@homarr/db/schema/sqlite";
import { getPermissionsWithChildren } from "@homarr/definitions";
-import {
- expireDateAfter,
- generateSessionToken,
- sessionMaxAgeInSeconds,
- sessionTokenCookieName,
-} from "./session";
+import { expireDateAfter, generateSessionToken, sessionMaxAgeInSeconds, sessionTokenCookieName } from "./session";
-export const getCurrentUserPermissionsAsync = async (
- db: Database,
- userId: string,
-) => {
+export const getCurrentUserPermissionsAsync = async (db: Database, userId: string) => {
const dbGroupMembers = await db.query.groupMembers.findMany({
where: eq(groupMembers.userId, userId),
});
@@ -27,19 +19,13 @@ export const getCurrentUserPermissionsAsync = async (
permission: groupPermissions.permission,
})
.from(groupPermissions)
- .where(
- groupIds.length > 0
- ? inArray(groupPermissions.groupId, groupIds)
- : undefined,
- );
+ .where(groupIds.length > 0 ? inArray(groupPermissions.groupId, groupIds) : undefined);
const permissionKeys = dbGroupPermissions.map(({ permission }) => permission);
return getPermissionsWithChildren(permissionKeys);
};
-export const createSessionCallback = (
- db: Database,
-): NextAuthCallbackOf<"session"> => {
+export const createSessionCallback = (db: Database): NextAuthCallbackOf<"session"> => {
return async ({ session, user }) => {
return {
...session,
@@ -54,10 +40,7 @@ export const createSessionCallback = (
};
export const createSignInCallback =
- (
- adapter: Adapter,
- isCredentialsRequest: boolean,
- ): NextAuthCallbackOf<"signIn"> =>
+ (adapter: Adapter, isCredentialsRequest: boolean): NextAuthCallbackOf<"signIn"> =>
async ({ user }) => {
if (!isCredentialsRequest) return true;
@@ -89,5 +72,7 @@ export const createSignInCallback =
};
type NextAuthCallbackRecord = Exclude<NextAuthConfig["callbacks"], undefined>;
-export type NextAuthCallbackOf<TKey extends keyof NextAuthCallbackRecord> =
- Exclude<NextAuthCallbackRecord[TKey], undefined>;
+export type NextAuthCallbackOf<TKey extends keyof NextAuthCallbackRecord> = Exclude<
+ NextAuthCallbackRecord[TKey],
+ undefined
+>;
diff --git a/packages/auth/configuration.ts b/packages/auth/configuration.ts
index 2c8c4459f..290df5f10 100644
--- a/packages/auth/configuration.ts
+++ b/packages/auth/configuration.ts
@@ -28,10 +28,7 @@ export const createConfiguration = (isCredentialsRequest: boolean) =>
},
trustHost: true,
adapter,
- providers: [
- Credentials(createCredentialsConfiguration(db)),
- EmptyNextAuthProvider(),
- ],
+ providers: [Credentials(createCredentialsConfiguration(db)), EmptyNextAuthProvider()],
callbacks: {
session: createSessionCallback(db),
signIn: createSignInCallback(adapter, isCredentialsRequest),
diff --git a/packages/auth/env.mjs b/packages/auth/env.mjs
index 3bcd30f32..2e7ddcad0 100644
--- a/packages/auth/env.mjs
+++ b/packages/auth/env.mjs
@@ -3,15 +3,11 @@ import { z } from "zod";
export const env = createEnv({
server: {
- AUTH_SECRET:
- process.env.NODE_ENV === "production"
- ? z.string().min(1)
- : z.string().min(1).optional(),
+ AUTH_SECRET: process.env.NODE_ENV === "production" ? z.string().min(1) : z.string().min(1).optional(),
},
client: {},
runtimeEnv: {
AUTH_SECRET: process.env.AUTH_SECRET,
},
- skipValidation:
- Boolean(process.env.CI) || Boolean(process.env.SKIP_ENV_VALIDATION),
+ skipValidation: Boolean(process.env.CI) || Boolean(process.env.SKIP_ENV_VALIDATION),
});
diff --git a/packages/auth/index.ts b/packages/auth/index.ts
index 0a555056c..eed6a80b9 100644
--- a/packages/auth/index.ts
+++ b/packages/auth/index.ts
@@ -17,10 +17,6 @@ declare module "@auth/core/types" {
export * from "./security";
-export const createHandlers = (isCredentialsRequest: boolean) =>
- createConfiguration(isCredentialsRequest);
+export const createHandlers = (isCredentialsRequest: boolean) => createConfiguration(isCredentialsRequest);
-export {
- getSessionFromTokenAsync as getSessionFromToken,
- sessionTokenCookieName,
-} from "./session";
+export { getSessionFromTokenAsync as getSessionFromToken, sessionTokenCookieName } from "./session";
diff --git a/packages/auth/permissions/board-permissions.ts b/packages/auth/permissions/board-permissions.ts
index a67b988b5..a3adbe8f6 100644
--- a/packages/auth/permissions/board-permissions.ts
+++ b/packages/auth/permissions/board-permissions.ts
@@ -19,24 +19,15 @@ export type BoardPermissionsProps = (
isPublic: boolean;
};
-export const constructBoardPermissions = (
- board: BoardPermissionsProps,
- session: Session | null,
-) => {
+export const constructBoardPermissions = (board: BoardPermissionsProps, session: Session | null) => {
const creatorId = "creator" in board ? board.creator?.id : board.creatorId;
return {
- hasFullAccess:
- session?.user?.id === creatorId ||
- session?.user.permissions.includes("board-full-access"),
+ hasFullAccess: session?.user?.id === creatorId || session?.user.permissions.includes("board-full-access"),
hasChangeAccess:
session?.user?.id === creatorId ||
- board.userPermissions.some(
- ({ permission }) => permission === "board-change",
- ) ||
- board.groupPermissions.some(
- ({ permission }) => permission === "board-change",
- ) ||
+ board.userPermissions.some(({ permission }) => permission === "board-change") ||
+ board.groupPermissions.some(({ permission }) => permission === "board-change") ||
session?.user.permissions.includes("board-modify-all"),
hasViewAccess:
session?.user?.id === creatorId ||
diff --git a/packages/auth/providers/credentials.ts b/packages/auth/providers/credentials.ts
index edfd5eb62..ecc101078 100644
--- a/packages/auth/providers/credentials.ts
+++ b/packages/auth/providers/credentials.ts
@@ -35,13 +35,8 @@ export const createCredentialsConfiguration = (db: Database) =>
return null;
}
- console.log(
- `user ${user.name} is trying to log in. checking password...`,
- );
- const isValidPassword = await bcrypt.compare(
- data.password,
- user.password,
- );
+ console.log(`user ${user.name} is trying to log in. checking password...`);
+ const isValidPassword = await bcrypt.compare(data.password, user.password);
if (!isValidPassword) {
console.log(`password for user ${user.name} was incorrect`);
diff --git a/packages/auth/providers/test/credentials.spec.ts b/packages/auth/providers/test/credentials.spec.ts
index 09b42d32d..0f7c7c98b 100644
--- a/packages/auth/providers/test/credentials.spec.ts
+++ b/packages/auth/providers/test/credentials.spec.ts
@@ -26,13 +26,7 @@ describe("Credentials authorization", () => {
expect(result).toEqual({ id: userId, name: "test" });
});
- const passwordsThatShouldNotAuthorize = [
- "wrong",
- "Test",
- "test ",
- " test",
- " test ",
- ];
+ const passwordsThatShouldNotAuthorize = ["wrong", "Test", "test ", " test", " test "];
passwordsThatShouldNotAuthorize.forEach((password) => {
it(`should not authorize user with incorrect credentials (${password})`, async () => {
diff --git a/packages/auth/session.ts b/packages/auth/session.ts
index 40dbf874c..3e893db04 100644
--- a/packages/auth/session.ts
+++ b/packages/auth/session.ts
@@ -16,10 +16,7 @@ export const generateSessionToken = () => {
return randomUUID();
};
-export const getSessionFromTokenAsync = async (
- db: Database,
- token: string | undefined,
-): Promise<Session | null> => {
+export const getSessionFromTokenAsync = async (db: Database, token: string | undefined): Promise<Session | null> => {
if (!token) {
return null;
}
diff --git a/packages/auth/test/callbacks.spec.ts b/packages/auth/test/callbacks.spec.ts
index 679669627..1dced2115 100644
--- a/packages/auth/test/callbacks.spec.ts
+++ b/packages/auth/test/callbacks.spec.ts
@@ -6,20 +6,11 @@ import type { Account, User } from "next-auth";
import type { JWT } from "next-auth/jwt";
import { describe, expect, it, test, vi } from "vitest";
-import {
- groupMembers,
- groupPermissions,
- groups,
- users,
-} from "@homarr/db/schema/sqlite";
+import { groupMembers, groupPermissions, groups, users } from "@homarr/db/schema/sqlite";
import { createDb } from "@homarr/db/test";
import * as definitions from "@homarr/definitions";
-import {
- createSessionCallback,
- createSignInCallback,
- getCurrentUserPermissionsAsync,
-} from "../callbacks";
+import { createSessionCallback, createSignInCallback, getCurrentUserPermissionsAsync } from "../callbacks";
describe("getCurrentUserPermissions", () => {
test("should return empty permissions when non existing user requested", async () => {
@@ -96,9 +87,7 @@ describe("session callback", () => {
});
});
-type AdapterSessionInput = Parameters<
- Exclude<Adapter["createSession"], undefined>
->[0];
+type AdapterSessionInput = Parameters<Exclude<Adapter["createSession"], undefined>>[0];
const createAdapter = () => {
const result = {
@@ -131,8 +120,7 @@ vi.mock("next/headers", async (importOriginal) => {
const mod = await importOriginal<HeadersExport>();
const result = {
- set: (name: string, value: string, options: Partial<ResponseCookie>) =>
- options as ResponseCookie,
+ set: (name: string, value: string, options: Partial<ResponseCookie>) => options as ResponseCookie,
} as unknown as ReadonlyRequestCookies;
vi.spyOn(result, "set");
@@ -145,10 +133,7 @@ vi.mock("next/headers", async (importOriginal) => {
describe("createSignInCallback", () => {
it("should return true if not credentials request", async () => {
const isCredentialsRequest = false;
- const signInCallback = createSignInCallback(
- createAdapter(),
- isCredentialsRequest,
- );
+ const signInCallback = createSignInCallback(createAdapter(), isCredentialsRequest);
const result = await signInCallback({
user: { id: "1", emailVerified: new Date("2023-01-13") },
account: {} as Account,
@@ -158,10 +143,7 @@ describe("createSignInCallback", () => {
it("should return true if no user", async () => {
const isCredentialsRequest = true;
- const signInCallback = createSignInCallback(
- createAdapter(),
- isCredentialsRequest,
- );
+ const signInCallback = createSignInCallback(createAdapter(), isCredentialsRequest);
const result = await signInCallback({
user: undefined as unknown as User,
account: {} as Account,
@@ -195,16 +177,12 @@ describe("createSignInCallback", () => {
userId: user.id,
expires: mockSessionExpiry,
});
- expect(cookies().set).toHaveBeenCalledWith(
- "next-auth.session-token",
- mockSessionToken,
- {
- path: "/",
- expires: mockSessionExpiry,
- httpOnly: true,
- sameSite: "lax",
- secure: true,
- },
- );
+ expect(cookies().set).toHaveBeenCalledWith("next-auth.session-token", mockSessionToken, {
+ path: "/",
+ expires: mockSessionExpiry,
+ httpOnly: true,
+ sameSite: "lax",
+ secure: true,
+ });
});
});
diff --git a/packages/auth/test/session.spec.ts b/packages/auth/test/session.spec.ts
index 2d2ced596..27adfef2a 100644
--- a/packages/auth/test/session.spec.ts
+++ b/packages/auth/test/session.spec.ts
@@ -20,14 +20,11 @@ describe("expireDateAfter should calculate date after specified seconds", () =>
["2023-07-01T00:00:00Z", 60 * 60 * 24 * 30, "2023-07-31T00:00:00Z"], // 30 days
["2023-07-01T00:00:00Z", 60 * 60 * 24 * 365, "2024-06-30T00:00:00Z"], // 1 year
["2023-07-01T00:00:00Z", 60 * 60 * 24 * 365 * 10, "2033-06-28T00:00:00Z"], // 10 years
- ])(
- "should calculate date %s and after %i seconds to equal %s",
- (initialDate, seconds, expectedDate) => {
- vi.setSystemTime(new Date(initialDate));
- const result = expireDateAfter(seconds);
- expect(result).toEqual(new Date(expectedDate));
- },
- );
+ ])("should calculate date %s and after %i seconds to equal %s", (initialDate, seconds, expectedDate) => {
+ vi.setSystemTime(new Date(initialDate));
+ const result = expireDateAfter(seconds);
+ expect(result).toEqual(new Date(expectedDate));
+ });
});
describe("generateSessionToken should return a random UUID", () => {
diff --git a/packages/common/src/object.ts b/packages/common/src/object.ts
index 6bcb87a62..7e0ccde7f 100644
--- a/packages/common/src/object.ts
+++ b/packages/common/src/object.ts
@@ -6,5 +6,4 @@ type Entries<T> = {
[K in keyof T]: [K, T[K]];
}[keyof T][];
-export const objectEntries = <T extends object>(obj: T) =>
- Object.entries(obj) as Entries<T>;
+export const objectEntries = <T extends object>(obj: T) => Object.entries(obj) as Entries<T>;
diff --git a/packages/common/src/test/object.spec.ts b/packages/common/src/test/object.spec.ts
index 02a1ed241..d99ebd7cf 100644
--- a/packages/common/src/test/object.spec.ts
+++ b/packages/common/src/test/object.spec.ts
@@ -2,12 +2,7 @@ import { describe, expect, it } from "vitest";
import { objectEntries, objectKeys } from "../object";
-const testObjects = [
- { a: 1, c: 3, b: 2 },
- { a: 1, b: 2 },
- { a: 1 },
- {},
-] as const;
+const testObjects = [{ a: 1, c: 3, b: 2 }, { a: 1, b: 2 }, { a: 1 }, {}] as const;
describe("objectKeys should return all keys of an object", () => {
testObjects.forEach((obj) => {
diff --git a/packages/db/schema/mysql.ts b/packages/db/schema/mysql.ts
index 4596d25bb..8b9d70bf9 100644
--- a/packages/db/schema/mysql.ts
+++ b/packages/db/schema/mysql.ts
@@ -1,16 +1,7 @@
import type { AdapterAccount } from "@auth/core/adapters";
import { relations } from "drizzle-orm";
import type { AnyMySqlColumn } from "drizzle-orm/mysql-core";
-import {
- boolean,
- index,
- int,
- mysqlTable,
- primaryKey,
- text,
- timestamp,
- varchar,
-} from "drizzle-orm/mysql-core";
+import { boolean, index, int, mysqlTable, primaryKey, text, timestamp, varchar } from "drizzle-orm/mysql-core";
import type {
BackgroundImageAttachment,
@@ -23,11 +14,7 @@ import type {
SectionKind,
WidgetKind,
} from "@homarr/definitions";
-import {
- backgroundImageAttachments,
- backgroundImageRepeats,
- backgroundImageSizes,
-} from "@homarr/definitions";
+import { backgroundImageAttachments, backgroundImageRepeats, backgroundImageSizes } from "@homarr/definitions";
export const users = mysqlTable("user", {
id: varchar("id", { length: 64 }).notNull().primaryKey(),
@@ -37,12 +24,9 @@ export const users = mysqlTable("user", {
image: text("image"),
password: text("password"),
salt: text("salt"),
- homeBoardId: varchar("homeBoardId", { length: 64 }).references(
- (): AnyMySqlColumn => boards.id,
- {
- onDelete: "set null",
- },
- ),
+ homeBoardId: varchar("homeBoardId", { length: 64 }).references((): AnyMySqlColumn => boards.id, {
+ onDelete: "set null",
+ }),
});
export const accounts = mysqlTable(
@@ -73,9 +57,7 @@ export const accounts = mysqlTable(
export const sessions = mysqlTable(
"session",
{
- sessionToken: varchar("sessionToken", { length: 512 })
- .notNull()
- .primaryKey(),
+ sessionToken: varchar("sessionToken", { length: 512 }).notNull().primaryKey(),
userId: varchar("userId", { length: 64 })
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
@@ -157,9 +139,7 @@ export const integrations = mysqlTable(
export const integrationSecrets = mysqlTable(
"integrationSecret",
{
- kind: varchar("kind", { length: 16 })
- .$type<IntegrationSecretKind>()
- .notNull(),
+ kind: varchar("kind", { length: 16 }).$type<IntegrationSecretKind>().notNull(),
value: text("value").$type<`${string}.${string}`>().notNull(),
updatedAt: timestamp("updated_at").notNull(),
integrationId: varchar("integration_id", { length: 64 })
@@ -171,9 +151,7 @@ export const integrationSecrets = mysqlTable(
columns: [integrationSecret.integrationId, integrationSecret.kind],
}),
kindIdx: index("integration_secret__kind_idx").on(integrationSecret.kind),
- updatedAtIdx: index("integration_secret__updated_at_idx").on(
- integrationSecret.updatedAt,
- ),
+ updatedAtIdx: index("integration_secret__updated_at_idx").on(integrationSecret.updatedAt),
}),
);
@@ -217,9 +195,7 @@ export const boardUserPermissions = mysqlTable(
userId: varchar("user_id", { length: 64 })
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
- permission: varchar("permission", { length: 128 })
- .$type<BoardPermission>()
- .notNull(),
+ permission: varchar("permission", { length: 128 }).$type<BoardPermission>().notNull(),
},
(table) => ({
compoundKey: primaryKey({
@@ -237,9 +213,7 @@ export const boardGroupPermissions = mysqlTable(
groupId: varchar("group_id", { length: 64 })
.notNull()
.references(() => groups.id, { onDelete: "cascade" }),
- permission: varchar("permission", { length: 128 })
- .$type<BoardPermission>()
- .notNull(),
+ permission: varchar("permission", { length: 128 }).$type<BoardPermission>().notNull(),
},
(table) => ({
compoundKey: primaryKey({
@@ -339,12 +313,9 @@ export const iconRelations = relations(icons, ({ one }) => ({
}),
}));
-export const iconRepositoryRelations = relations(
- iconRepositories,
- ({ many }) => ({
- icons: many(icons),
- }),
-);
+export const iconRepositoryRelations = relations(iconRepositories, ({ many }) => ({
+ icons: many(icons),
+}));
export const inviteRelations = relations(invites, ({ one }) => ({
creator: one(users, {
@@ -381,58 +352,46 @@ export const groupRelations = relations(groups, ({ one, many }) => ({
}),
}));
-export const groupPermissionRelations = relations(
- groupPermissions,
- ({ one }) => ({
- group: one(groups, {
- fields: [groupPermissions.groupId],
- references: [groups.id],
- }),
+export const groupPermissionRelations = relations(groupPermissions, ({ one }) => ({
+ group: one(groups, {
+ fields: [groupPermissions.groupId],
+ references: [groups.id],
}),
-);
+}));
-export const boardUserPermissionRelations = relations(
- boardUserPermissions,
- ({ one }) => ({
- user: one(users, {
- fields: [boardUserPermissions.userId],
- references: [users.id],
- }),
- board: one(boards, {
- fields: [boardUserPermissions.boardId],
- references: [boards.id],
- }),
+export const boardUserPermissionRelations = relations(boardUserPermissions, ({ one }) => ({
+ user: one(users, {
+ fields: [boardUserPermissions.userId],
+ references: [users.id],
}),
-);
+ board: one(boards, {
+ fields: [boardUserPermissions.boardId],
+ references: [boards.id],
+ }),
+}));
-export const boardGroupPermissionRelations = relations(
- boardGroupPermissions,
- ({ one }) => ({
- group: one(groups, {
- fields: [boardGroupPermissions.groupId],
- references: [groups.id],
- }),
- board: one(boards, {
- fields: [boardGroupPermissions.boardId],
- references: [boards.id],
- }),
+export const boardGroupPermissionRelations = relations(boardGroupPermissions, ({ one }) => ({
+ group: one(groups, {
+ fields: [boardGroupPermissions.groupId],
+ references: [groups.id],
}),
-);
+ board: one(boards, {
+ fields: [boardGroupPermissions.boardId],
+ references: [boards.id],
+ }),
+}));
export const integrationRelations = relations(integrations, ({ many }) => ({
secrets: many(integrationSecrets),
items: many(integrationItems),
}));
-export const integrationSecretRelations = relations(
- integrationSecrets,
- ({ one }) => ({
- integration: one(integrations, {
- fields: [integrationSecrets.integrationId],
- references: [integrations.id],
- }),
+export const integrationSecretRelations = relations(integrationSecrets, ({ one }) => ({
+ integration: one(integrations, {
+ fields: [integrationSecrets.integrationId],
+ references: [integrations.id],
}),
-);
+}));
export const boardRelations = relations(boards, ({ many, one }) => ({
sections: many(sections),
@@ -460,16 +419,13 @@ export const itemRelations = relations(items, ({ one, many }) => ({
integrations: many(integrationItems),
}));
-export const integrationItemRelations = relations(
- integrationItems,
- ({ one }) => ({
- integration: one(integrations, {
- fields: [integrationItems.integrationId],
- references: [integrations.id],
- }),
- item: one(items, {
- fields: [integrationItems.itemId],
- references: [items.id],
- }),
+export const integrationItemRelations = relations(integrationItems, ({ one }) => ({
+ integration: one(integrations, {
+ fields: [integrationItems.integrationId],
+ references: [integrations.id],
}),
-);
+ item: one(items, {
+ fields: [integrationItems.itemId],
+ references: [items.id],
+ }),
+}));
diff --git a/packages/db/schema/sqlite.ts b/packages/db/schema/sqlite.ts
index 2a67b0502..905225ad2 100644
--- a/packages/db/schema/sqlite.ts
+++ b/packages/db/schema/sqlite.ts
@@ -2,20 +2,9 @@ import type { AdapterAccount } from "@auth/core/adapters";
import type { InferSelectModel } from "drizzle-orm";
import { relations } from "drizzle-orm";
import type { AnySQLiteColumn } from "drizzle-orm/sqlite-core";
-import {
- index,
- int,
- integer,
- primaryKey,
- sqliteTable,
- text,
-} from "drizzle-orm/sqlite-core";
-
-import {
- backgroundImageAttachments,
- backgroundImageRepeats,
- backgroundImageSizes,
-} from "@homarr/definitions";
+import { index, int, integer, primaryKey, sqliteTable, text } from "drizzle-orm/sqlite-core";
+
+import { backgroundImageAttachments, backgroundImageRepeats, backgroundImageSizes } from "@homarr/definitions";
import type {
BackgroundImageAttachment,
BackgroundImageRepeat,
@@ -36,12 +25,9 @@ export const users = sqliteTable("user", {
image: text("image"),
password: text("password"),
salt: text("salt"),
- homeBoardId: text("homeBoardId").references(
- (): AnySQLiteColumn => boards.id,
- {
- onDelete: "set null",
- },
- ),
+ homeBoardId: text("homeBoardId").references((): AnySQLiteColumn => boards.id, {
+ onDelete: "set null",
+ }),
});
export const accounts = sqliteTable(
@@ -168,9 +154,7 @@ export const integrationSecrets = sqliteTable(
columns: [integrationSecret.integrationId, integrationSecret.kind],
}),
kindIdx: index("integration_secret__kind_idx").on(integrationSecret.kind),
- updatedAtIdx: index("integration_secret__updated_at_idx").on(
- integrationSecret.updatedAt,
- ),
+ updatedAtIdx: index("integration_secret__updated_at_idx").on(integrationSecret.updatedAt),
}),
);
@@ -332,12 +316,9 @@ export const iconRelations = relations(icons, ({ one }) => ({
}),
}));
-export const iconRepositoryRelations = relations(
- iconRepositories,
- ({ many }) => ({
- icons: many(icons),
- }),
-);
+export const iconRepositoryRelations = relations(iconRepositories, ({ many }) => ({
+ icons: many(icons),
+}));
export const inviteRelations = relations(invites, ({ one }) => ({
creator: one(users, {
@@ -374,58 +355,46 @@ export const groupRelations = relations(groups, ({ one, many }) => ({
}),
}));
-export const groupPermissionRelations = relations(
- groupPermissions,
- ({ one }) => ({
- group: one(groups, {
- fields: [groupPermissions.groupId],
- references: [groups.id],
- }),
+export const groupPermissionRelations = relations(groupPermissions, ({ one }) => ({
+ group: one(groups, {
+ fields: [groupPermissions.groupId],
+ references: [groups.id],
}),
-);
+}));
-export const boardUserPermissionRelations = relations(
- boardUserPermissions,
- ({ one }) => ({
- user: one(users, {
- fields: [boardUserPermissions.userId],
- references: [users.id],
- }),
- board: one(boards, {
- fields: [boardUserPermissions.boardId],
- references: [boards.id],
- }),
+export const boardUserPermissionRelations = relations(boardUserPermissions, ({ one }) => ({
+ user: one(users, {
+ fields: [boardUserPermissions.userId],
+ references: [users.id],
}),
-);
+ board: one(boards, {
+ fields: [boardUserPermissions.boardId],
+ references: [boards.id],
+ }),
+}));
-export const boardGroupPermissionRelations = relations(
- boardGroupPermissions,
- ({ one }) => ({
- group: one(groups, {
- fields: [boardGroupPermissions.groupId],
- references: [groups.id],
- }),
- board: one(boards, {
- fields: [boardGroupPermissions.boardId],
- references: [boards.id],
- }),
+export const boardGroupPermissionRelations = relations(boardGroupPermissions, ({ one }) => ({
+ group: one(groups, {
+ fields: [boardGroupPermissions.groupId],
+ references: [groups.id],
}),
-);
+ board: one(boards, {
+ fields: [boardGroupPermissions.boardId],
+ references: [boards.id],
+ }),
+}));
export const integrationRelations = relations(integrations, ({ many }) => ({
secrets: many(integrationSecrets),
items: many(integrationItems),
}));
-export const integrationSecretRelations = relations(
- integrationSecrets,
- ({ one }) => ({
- integration: one(integrations, {
- fields: [integrationSecrets.integrationId],
- references: [integrations.id],
- }),
+export const integrationSecretRelations = relations(integrationSecrets, ({ one }) => ({
+ integration: one(integrations, {
+ fields: [integrationSecrets.integrationId],
+ references: [integrations.id],
}),
-);
+}));
export const boardRelations = relations(boards, ({ many, one }) => ({
sections: many(sections),
@@ -453,19 +422,16 @@ export const itemRelations = relations(items, ({ one, many }) => ({
integrations: many(integrationItems),
}));
-export const integrationItemRelations = relations(
- integrationItems,
- ({ one }) => ({
- integration: one(integrations, {
- fields: [integrationItems.integrationId],
- references: [integrations.id],
- }),
- item: one(items, {
- fields: [integrationItems.itemId],
- references: [items.id],
- }),
+export const integrationItemRelations = relations(integrationItems, ({ one }) => ({
+ integration: one(integrations, {
+ fields: [integrationItems.integrationId],
+ references: [integrations.id],
}),
-);
+ item: one(items, {
+ fields: [integrationItems.itemId],
+ references: [items.id],
+ }),
+}));
export type User = InferSelectModel<typeof users>;
export type Account = InferSelectModel<typeof accounts>;
diff --git a/packages/db/test/schema.spec.ts b/packages/db/test/schema.spec.ts
index cbce0f745..78b8363e2 100644
--- a/packages/db/test/schema.spec.ts
+++ b/packages/db/test/schema.spec.ts
@@ -1,12 +1,6 @@
import type { Column, InferSelectModel } from "drizzle-orm";
-import type {
- ForeignKey as MysqlForeignKey,
- MySqlTableWithColumns,
-} from "drizzle-orm/mysql-core";
-import type {
- ForeignKey as SqliteForeignKey,
- SQLiteTableWithColumns,
-} from "drizzle-orm/sqlite-core";
+import type { ForeignKey as MysqlForeignKey, MySqlTableWithColumns } from "drizzle-orm/mysql-core";
+import type { ForeignKey as SqliteForeignKey, SQLiteTableWithColumns } from "drizzle-orm/sqlite-core";
import { expect, expectTypeOf, test } from "vitest";
import { objectEntries } from "@homarr/common";
@@ -21,54 +15,44 @@ test("schemas should match", () => {
expectTypeOf<MysqlConfig>().toEqualTypeOf<SqliteConfig>();
objectEntries(sqliteSchema).forEach(([tableName, sqliteTable]) => {
- Object.entries(sqliteTable).forEach(
- ([columnName, sqliteColumn]: [string, object]) => {
- if (!("isUnique" in sqliteColumn)) return;
- if (!("uniqueName" in sqliteColumn)) return;
- if (!("primary" in sqliteColumn)) return;
+ Object.entries(sqliteTable).forEach(([columnName, sqliteColumn]: [string, object]) => {
+ if (!("isUnique" in sqliteColumn)) return;
+ if (!("uniqueName" in sqliteColumn)) return;
+ if (!("primary" in sqliteColumn)) return;
- const mysqlTable = mysqlSchema[tableName];
+ const mysqlTable = mysqlSchema[tableName];
- const mysqlColumn = mysqlTable[
- columnName as keyof typeof mysqlTable
- ] as object;
- if (!("isUnique" in mysqlColumn)) return;
- if (!("uniqueName" in mysqlColumn)) return;
- if (!("primary" in mysqlColumn)) return;
+ const mysqlColumn = mysqlTable[columnName as keyof typeof mysqlTable] as object;
+ if (!("isUnique" in mysqlColumn)) return;
+ if (!("uniqueName" in mysqlColumn)) return;
+ if (!("primary" in mysqlColumn)) return;
- expect(
- sqliteColumn.isUnique,
- `expect unique of column ${columnName} in table ${tableName} to be the same for both schemas`,
- ).toEqual(mysqlColumn.isUnique);
- expect(
- sqliteColumn.uniqueName,
- `expect uniqueName of column ${columnName} in table ${tableName} to be the same for both schemas`,
- ).toEqual(mysqlColumn.uniqueName);
- expect(
- sqliteColumn.primary,
- `expect primary of column ${columnName} in table ${tableName} to be the same for both schemas`,
- ).toEqual(mysqlColumn.primary);
- },
- );
+ expect(
+ sqliteColumn.isUnique,
+ `expect unique of column ${columnName} in table ${tableName} to be the same for both schemas`,
+ ).toEqual(mysqlColumn.isUnique);
+ expect(
+ sqliteColumn.uniqueName,
+ `expect uniqueName of column ${columnName} in table ${tableName} to be the same for both schemas`,
+ ).toEqual(mysqlColumn.uniqueName);
+ expect(
+ sqliteColumn.primary,
+ `expect primary of column ${columnName} in table ${tableName} to be the same for both schemas`,
+ ).toEqual(mysqlColumn.primary);
+ });
const mysqlTable = mysqlSchema[tableName];
- const sqliteForeignKeys = sqliteTable[
- Symbol.for("drizzle:SQLiteInlineForeignKeys") as keyof typeof sqliteTable
- ] as SqliteForeignKey[] | undefined;
- const mysqlForeignKeys = mysqlTable[
- Symbol.for("drizzle:MySqlInlineForeignKeys") as keyof typeof mysqlTable
- ] as MysqlForeignKey[] | undefined;
+ const sqliteForeignKeys = sqliteTable[Symbol.for("drizzle:SQLiteInlineForeignKeys") as keyof typeof sqliteTable] as
+ | SqliteForeignKey[]
+ | undefined;
+ const mysqlForeignKeys = mysqlTable[Symbol.for("drizzle:MySqlInlineForeignKeys") as keyof typeof mysqlTable] as
+ | MysqlForeignKey[]
+ | undefined;
if (!sqliteForeignKeys && !mysqlForeignKeys) return;
- expect(
- mysqlForeignKeys,
- `mysql foreign key for ${tableName} to be defined`,
- ).toBeDefined();
- expect(
- sqliteForeignKeys,
- `sqlite foreign key for ${tableName} to be defined`,
- ).toBeDefined();
+ expect(mysqlForeignKeys, `mysql foreign key for ${tableName} to be defined`).toBeDefined();
+ expect(sqliteForeignKeys, `sqlite foreign key for ${tableName} to be defined`).toBeDefined();
expect(
sqliteForeignKeys!.length,
@@ -77,9 +61,7 @@ test("schemas should match", () => {
sqliteForeignKeys?.forEach((sqliteForeignKey) => {
sqliteForeignKey.getName();
- const mysqlForeignKey = mysqlForeignKeys!.find(
- (key) => key.getName() === sqliteForeignKey.getName(),
- );
+ const mysqlForeignKey = mysqlForeignKeys!.find((key) => key.getName() === sqliteForeignKey.getName());
expect(
mysqlForeignKey,
`expect foreign key ${sqliteForeignKey.getName()} to be defined in mysql schema`,
@@ -97,9 +79,7 @@ test("schemas should match", () => {
sqliteForeignKey.reference().foreignColumns.forEach((column) => {
expect(
- mysqlForeignKey!
- .reference()
- .foreignColumns.map((column) => column.name),
+ mysqlForeignKey!.reference().foreignColumns.map((column) => column.name),
`expect foreign key (${sqliteForeignKey.getName()}) columns to be the same for both schemas`,
).toContainEqual(column.name);
});
@@ -127,9 +107,7 @@ type MysqlTables = {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type InferColumnConfig<T extends Column<any, object>> =
- T extends Column<infer C, object>
- ? Omit<C, "columnType" | "enumValues" | "driverParam">
- : never;
+ T extends Column<infer C, object> ? Omit<C, "columnType" | "enumValues" | "driverParam"> : never;
type SqliteConfig = {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
diff --git a/packages/definitions/src/_definition.ts b/packages/definitions/src/_definition.ts
index 41c63f4c8..a99ecb382 100644
--- a/packages/definitions/src/_definition.ts
+++ b/packages/definitions/src/_definition.ts
@@ -1,7 +1,4 @@
-export const createDefinition = <
- const TKeys extends string[],
- TOptions extends { defaultValue: TKeys[number] } | void,
->(
+export const createDefinition = <const TKeys extends string[], TOptions extends { defaultValue: TKeys[number] } | void>(
values: TKeys,
options: TOptions,
) => ({
diff --git a/packages/definitions/src/board.ts b/packages/definitions/src/board.ts
index e27490a59..302008550 100644
--- a/packages/definitions/src/board.ts
+++ b/packages/definitions/src/board.ts
@@ -1,24 +1,14 @@
import type { inferDefinitionType } from "./_definition";
import { createDefinition } from "./_definition";
-export const backgroundImageAttachments = createDefinition(
- ["fixed", "scroll"],
- { defaultValue: "fixed" },
-);
-export const backgroundImageRepeats = createDefinition(
- ["repeat", "repeat-x", "repeat-y", "no-repeat"],
- { defaultValue: "no-repeat" },
-);
+export const backgroundImageAttachments = createDefinition(["fixed", "scroll"], { defaultValue: "fixed" });
+export const backgroundImageRepeats = createDefinition(["repeat", "repeat-x", "repeat-y", "no-repeat"], {
+ defaultValue: "no-repeat",
+});
export const backgroundImageSizes = createDefinition(["cover", "contain"], {
defaultValue: "cover",
});
-export type BackgroundImageAttachment = inferDefinitionType<
- typeof backgroundImageAttachments
->;
-export type BackgroundImageRepeat = inferDefinitionType<
- typeof backgroundImageRepeats
->;
-export type BackgroundImageSize = inferDefinitionType<
- typeof backgroundImageSizes
->;
+export type BackgroundImageAttachment = inferDefinitionType<typeof backgroundImageAttachments>;
+export type BackgroundImageRepeat = inferDefinitionType<typeof backgroundImageRepeats>;
+export type BackgroundImageSize = inferDefinitionType<typeof backgroundImageSizes>;
diff --git a/packages/definitions/src/integration.ts b/packages/definitions/src/integration.ts
index 6f2b5c58f..3f5650af4 100644
--- a/packages/definitions/src/integration.ts
+++ b/packages/definitions/src/integration.ts
@@ -12,113 +12,97 @@ export const integrationDefs = {
sabNzbd: {
name: "SABnzbd",
secretKinds: [["apiKey"]],
- iconUrl:
- "https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons@master/png/sabnzbd.png",
+ iconUrl: "https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons@master/png/sabnzbd.png",
category: ["useNetClient"],
},
nzbGet: {
name: "NZBGet",
secretKinds: [["username", "password"]],
- iconUrl:
- "https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons@master/png/nzbget.png",
+ iconUrl: "https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons@master/png/nzbget.png",
category: ["useNetClient"],
},
deluge: {
name: "Deluge",
secretKinds: [["password"]],
- iconUrl:
- "https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons@master/png/deluge.png",
+ iconUrl: "https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons@master/png/deluge.png",
category: ["downloadClient"],
},
transmission: {
name: "Transmission",
secretKinds: [["username", "password"]],
- iconUrl:
- "https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons@master/png/transmission.png",
+ iconUrl: "https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons@master/png/transmission.png",
category: ["downloadClient"],
},
qBittorrent: {
name: "qBittorrent",
secretKinds: [["username", "password"]],
- iconUrl:
- "https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons@master/png/qbittorrent.png",
+ iconUrl: "https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons@master/png/qbittorrent.png",
category: ["downloadClient"],
},
sonarr: {
name: "Sonarr",
secretKinds: [["apiKey"]],
- iconUrl:
- "https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons@master/png/sonarr.png",
+ iconUrl: "https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons@master/png/sonarr.png",
category: ["calendar"],
},
radarr: {
name: "Radarr",
secretKinds: [["apiKey"]],
- iconUrl:
- "https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons@master/png/radarr.png",
+ iconUrl: "https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons@master/png/radarr.png",
category: ["calendar"],
},
lidarr: {
name: "Lidarr",
secretKinds: [["apiKey"]],
- iconUrl:
- "https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons@master/png/lidarr.png",
+ iconUrl: "https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons@master/png/lidarr.png",
category: ["calendar"],
},
readarr: {
name: "Readarr",
secretKinds: [["apiKey"]],
- iconUrl:
- "https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons@master/png/readarr.png",
+ iconUrl: "https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons@master/png/readarr.png",
category: ["calendar"],
},
jellyfin: {
name: "Jellyfin",
secretKinds: [["username", "password"], ["apiKey"]],
- iconUrl:
- "https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons@master/png/jellyfin.png",
+ iconUrl: "https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons@master/png/jellyfin.png",
category: ["mediaService"],
},
plex: {
name: "Plex",
secretKinds: [["apiKey"]],
- iconUrl:
- "https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons@master/png/plex.png",
+ iconUrl: "https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons@master/png/plex.png",
category: ["mediaService"],
},
jellyseerr: {
name: "Jellyseerr",
secretKinds: [["apiKey"]],
- iconUrl:
- "https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons@master/png/jellyseerr.png",
+ iconUrl: "https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons@master/png/jellyseerr.png",
category: ["mediaSearch", "mediaRequest"],
},
overseerr: {
name: "Overseerr",
secretKinds: [["apiKey"]],
- iconUrl:
- "https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons@master/png/overseerr.png",
+ iconUrl: "https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons@master/png/overseerr.png",
category: ["mediaSearch", "mediaRequest"],
},
piHole: {
name: "Pi-hole",
secretKinds: [["apiKey"]],
- iconUrl:
- "https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons@master/png/pi-hole.png",
+ iconUrl: "https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons@master/png/pi-hole.png",
category: ["dnsHole"],
},
adGuardHome: {
name: "AdGuard Home",
secretKinds: [["username", "password"]],
- iconUrl:
- "https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons@master/png/adguard-home.png",
+ iconUrl: "https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons@master/png/adguard-home.png",
category: ["dnsHole"],
},
homeAssistant: {
name: "Home Assistant",
secretKinds: [["apiKey"]],
- iconUrl:
- "https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons@master/png/home-assistant.png",
+ iconUrl: "https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons@master/png/home-assistant.png",
category: [],
},
} satisfies Record<
@@ -131,20 +115,16 @@ export const integrationDefs = {
}
>;
-export const getIconUrl = (integration: IntegrationKind) =>
- integrationDefs[integration]?.iconUrl ?? null;
+export const getIconUrl = (integration: IntegrationKind) => integrationDefs[integration]?.iconUrl ?? null;
-export const getIntegrationName = (integration: IntegrationKind) =>
- integrationDefs[integration].name;
+export const getIntegrationName = (integration: IntegrationKind) => integrationDefs[integration].name;
-export const getDefaultSecretKinds = (
- integration: IntegrationKind,
-): IntegrationSecretKind[] => integrationDefs[integration]?.secretKinds[0];
+export const getDefaultSecretKinds = (integration: IntegrationKind): IntegrationSecretKind[] =>
+ integrationDefs[integration]?.secretKinds[0];
export const getAllSecretKindOptions = (
integration: IntegrationKind,
-): [IntegrationSecretKind[], ...IntegrationSecretKind[][]] =>
- integrationDefs[integration]?.secretKinds;
+): [IntegrationSecretKind[], ...IntegrationSecretKind[][]] => integrationDefs[integration]?.secretKinds;
export const integrationKinds = objectKeys(integrationDefs);
diff --git a/packages/definitions/src/permissions.ts b/packages/definitions/src/permissions.ts
index a3a25f31d..827c78df9 100644
--- a/packages/definitions/src/permissions.ts
+++ b/packages/definitions/src/permissions.ts
@@ -20,14 +20,10 @@ const groupPermissionParents = {
admin: ["board-full-access", "integration-full-access"],
} satisfies Partial<Record<GroupPermissionKey, GroupPermissionKey[]>>;
-export const getPermissionsWithParents = (
- permissions: GroupPermissionKey[],
-): GroupPermissionKey[] => {
+export const getPermissionsWithParents = (permissions: GroupPermissionKey[]): GroupPermissionKey[] => {
const res = permissions.map((permission) => {
return objectEntries(groupPermissionParents)
- .filter(([_key, value]: [string, GroupPermissionKey[]]) =>
- value.includes(permission),
- )
+ .filter(([_key, value]: [string, GroupPermissionKey[]]) => value.includes(permission))
.map(([key]) => getPermissionsWithParents([key]))
.flat();
});
@@ -35,13 +31,9 @@ export const getPermissionsWithParents = (
return permissions.concat(res.flat());
};
-const getPermissionsInner = (
- permissionSet: Set<GroupPermissionKey>,
- permissions: GroupPermissionKey[],
-) => {
+const getPermissionsInner = (permissionSet: Set<GroupPermissionKey>, permissions: GroupPermissionKey[]) => {
permissions.forEach((permission) => {
- const children =
- groupPermissionParents[permission as keyof typeof groupPermissionParents];
+ const children = groupPermissionParents[permission as keyof typeof groupPermissionParents];
if (children) {
getPermissionsInner(permissionSet, children);
}
@@ -50,9 +42,7 @@ const getPermissionsInner = (
});
};
-export const getPermissionsWithChildren = (
- permissions: GroupPermissionKey[],
-) => {
+export const getPermissionsWithChildren = (permissions: GroupPermissionKey[]) => {
const permissionSet = new Set<GroupPermissionKey>();
getPermissionsInner(permissionSet, permissions);
return Array.from(permissionSet);
@@ -66,19 +56,14 @@ export type GroupPermissionKey = {
: key;
}[keyof GroupPermissions];
-export const groupPermissionKeys = objectKeys(groupPermissions).reduce(
- (acc, key) => {
- const item = groupPermissions[key];
- if (typeof item !== "boolean") {
- acc.push(
- ...item.map((subKey) => `${key}-${subKey}` as GroupPermissionKey),
- );
- } else {
- acc.push(key as GroupPermissionKey);
- }
- return acc;
- },
- [] as GroupPermissionKey[],
-);
+export const groupPermissionKeys = objectKeys(groupPermissions).reduce((acc, key) => {
+ const item = groupPermissions[key];
+ if (typeof item !== "boolean") {
+ acc.push(...item.map((subKey) => `${key}-${subKey}` as GroupPermissionKey));
+ } else {
+ acc.push(key as GroupPermissionKey);
+ }
+ return acc;
+}, [] as GroupPermissionKey[]);
export type BoardPermission = (typeof boardPermissions)[number];
diff --git a/packages/definitions/src/test/permissions.spec.ts b/packages/definitions/src/test/permissions.spec.ts
index abc581476..1a3572c45 100644
--- a/packages/definitions/src/test/permissions.spec.ts
+++ b/packages/definitions/src/test/permissions.spec.ts
@@ -1,47 +1,22 @@
import { describe, expect, test } from "vitest";
import type { GroupPermissionKey } from "../permissions";
-import {
- getPermissionsWithChildren,
- getPermissionsWithParents,
-} from "../permissions";
+import { getPermissionsWithChildren, getPermissionsWithParents } from "../permissions";
describe("getPermissionsWithParents should return the correct permissions", () => {
test.each([
- [
- ["board-view-all"],
- ["board-view-all", "board-modify-all", "board-full-access", "admin"],
- ],
+ [["board-view-all"], ["board-view-all", "board-modify-all", "board-full-access", "admin"]],
[["board-modify-all"], ["board-modify-all", "board-full-access", "admin"]],
[["board-create"], ["board-create", "board-full-access", "admin"]],
[["board-full-access"], ["board-full-access", "admin"]],
- [
- ["integration-use-all"],
- [
- "integration-use-all",
- "integration-interact-all",
- "integration-full-access",
- "admin",
- ],
- ],
- [
- ["integration-create"],
- ["integration-create", "integration-full-access", "admin"],
- ],
- [
- ["integration-interact-all"],
- ["integration-interact-all", "integration-full-access", "admin"],
- ],
+ [["integration-use-all"], ["integration-use-all", "integration-interact-all", "integration-full-access", "admin"]],
+ [["integration-create"], ["integration-create", "integration-full-access", "admin"]],
+ [["integration-interact-all"], ["integration-interact-all", "integration-full-access", "admin"]],
[["integration-full-access"], ["integration-full-access", "admin"]],
[["admin"], ["admin"]],
- ] satisfies [GroupPermissionKey[], GroupPermissionKey[]][])(
- "expect %s to return %s",
- (input, expectedOutput) => {
- expect(getPermissionsWithParents(input)).toEqual(
- expect.arrayContaining(expectedOutput),
- );
- },
- );
+ ] satisfies [GroupPermissionKey[], GroupPermissionKey[]][])("expect %s to return %s", (input, expectedOutput) => {
+ expect(getPermissionsWithParents(input)).toEqual(expect.arrayContaining(expectedOutput));
+ });
});
describe("getPermissionsWithChildren should return the correct permissions", () => {
@@ -49,24 +24,11 @@ describe("getPermissionsWithChildren should return the correct permissions", ()
[["board-view-all"], ["board-view-all"]],
[["board-modify-all"], ["board-view-all", "board-modify-all"]],
[["board-create"], ["board-create"]],
- [
- ["board-full-access"],
- ["board-full-access", "board-modify-all", "board-view-all"],
- ],
+ [["board-full-access"], ["board-full-access", "board-modify-all", "board-view-all"]],
[["integration-use-all"], ["integration-use-all"]],
[["integration-create"], ["integration-create"]],
- [
- ["integration-interact-all"],
- ["integration-interact-all", "integration-use-all"],
- ],
- [
- ["integration-full-access"],
- [
- "integration-full-access",
- "integration-interact-all",
- "integration-use-all",
- ],
- ],
+ [["integration-interact-all"], ["integration-interact-all", "integration-use-all"]],
+ [["integration-full-access"], ["integration-full-access", "integration-interact-all", "integration-use-all"]],
[
["admin"],
[
@@ -79,12 +41,7 @@ describe("getPermissionsWithChildren should return the correct permissions", ()
"integration-use-all",
],
],
- ] satisfies [GroupPermissionKey[], GroupPermissionKey[]][])(
- "expect %s to return %s",
- (input, expectedOutput) => {
- expect(getPermissionsWithChildren(input)).toEqual(
- expect.arrayContaining(expectedOutput),
- );
- },
- );
+ ] satisfies [GroupPermissionKey[], GroupPermissionKey[]][])("expect %s to return %s", (input, expectedOutput) => {
+ expect(getPermissionsWithChildren(input)).toEqual(expect.arrayContaining(expectedOutput));
+ });
});
diff --git a/packages/definitions/src/widget.ts b/packages/definitions/src/widget.ts
index 7cd6ac962..a095f01f1 100644
--- a/packages/definitions/src/widget.ts
+++ b/packages/definitions/src/widget.ts
@@ -1,9 +1,2 @@
-export const widgetKinds = [
- "clock",
- "weather",
- "app",
- "iframe",
- "video",
- "notebook",
-] as const;
+export const widgetKinds = ["clock", "weather", "app", "iframe", "video", "notebook"] as const;
export type WidgetKind = (typeof widgetKinds)[number];
diff --git a/packages/form/src/index.ts b/packages/form/src/index.ts
index 1dd155c45..60a2f425e 100644
--- a/packages/form/src/index.ts
+++ b/packages/form/src/index.ts
@@ -2,18 +2,11 @@ import { useForm, zodResolver } from "@mantine/form";
import { useI18n } from "@homarr/translation/client";
import { z } from "@homarr/validation";
-import type {
- AnyZodObject,
- ZodEffects,
- ZodIntersection,
-} from "@homarr/validation";
+import type { AnyZodObject, ZodEffects, ZodIntersection } from "@homarr/validation";
import { zodErrorMap } from "@homarr/validation/form";
export const useZodForm = <
- TSchema extends
- | AnyZodObject
- | ZodEffects<AnyZodObject>
- | ZodIntersection<AnyZodObject, AnyZodObject>,
+ TSchema extends AnyZodObject | ZodEffects<AnyZodObject> | ZodIntersection<AnyZodObject, AnyZodObject>,
>(
schema: TSchema,
options: Omit<
diff --git a/packages/form/src/messages.ts b/packages/form/src/messages.ts
index 96c0402d7..51983fff1 100644
--- a/packages/form/src/messages.ts
+++ b/packages/form/src/messages.ts
@@ -1,10 +1,5 @@
import type { TranslationObject } from "@homarr/translation";
-import type {
- ErrorMapCtx,
- z,
- ZodTooBigIssue,
- ZodTooSmallIssue,
-} from "@homarr/validation";
+import type { ErrorMapCtx, z, ZodTooBigIssue, ZodTooSmallIssue } from "@homarr/validation";
import { ZodIssueCode } from "@homarr/validation";
const handleStringError = (issue: z.ZodInvalidStringIssue) => {
@@ -71,10 +66,7 @@ const handleTooBigError = (issue: ZodTooBigIssue) => {
} as const;
};
-export const handleZodError = (
- issue: z.ZodIssueOptionalMessage,
- ctx: ErrorMapCtx,
-) => {
+export const handleZodError = (issue: z.ZodIssueOptionalMessage, ctx: ErrorMapCtx) => {
if (ctx.defaultError === "Required") {
return {
key: "errors.required",
diff --git a/packages/icons/src/icons-fetcher.ts b/packages/icons/src/icons-fetcher.ts
index dd3389102..32ba31af8 100644
--- a/packages/icons/src/icons-fetcher.ts
+++ b/packages/icons/src/icons-fetcher.ts
@@ -8,9 +8,7 @@ const repositories = [
"walkxcode/dashboard-icons",
undefined,
new URL("https://github.com/walkxcode/dashboard-icons"),
- new URL(
- "https://api.github.com/repos/walkxcode/dashboard-icons/git/trees/main?recursive=true",
- ),
+ new URL("https://api.github.com/repos/walkxcode/dashboard-icons/git/trees/main?recursive=true"),
"https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons/{0}",
),
new JsdelivrIconRepository(
@@ -18,9 +16,7 @@ const repositories = [
"PapirusDevelopmentTeam/papirus-icon-theme",
"GPL-3.0",
new URL("https://github.com/PapirusDevelopmentTeam/papirus-icon-theme"),
- new URL(
- "https://data.jsdelivr.com/v1/packages/gh/PapirusDevelopmentTeam/papirus_icons@master?structure=flat",
- ),
+ new URL("https://data.jsdelivr.com/v1/packages/gh/PapirusDevelopmentTeam/papirus_icons@master?structure=flat"),
"https://cdn.jsdelivr.net/gh/PapirusDevelopmentTeam/papirus_icons/{0}",
),
new JsdelivrIconRepository(
@@ -28,15 +24,11 @@ const repositories = [
"loganmarchione/homelab-svg-assets",
"MIT",
new URL("https://github.com/loganmarchione/homelab-svg-assets"),
- new URL(
- "https://data.jsdelivr.com/v1/packages/gh/loganmarchione/homelab-svg-assets@main?structure=flat",
- ),
+ new URL("https://data.jsdelivr.com/v1/packages/gh/loganmarchione/homelab-svg-assets@main?structure=flat"),
"https://cdn.jsdelivr.net/gh/loganmarchione/homelab-svg-assets/{0}",
),
];
export const fetchIconsAsync = async (): Promise<RepositoryIconGroup[]> => {
- return await Promise.all(
- repositories.map(async (repository) => await repository.getAllIconsAsync()),
- );
+ return await Promise.all(repositories.map(async (repository) => await repository.getAllIconsAsync()));
};
diff --git a/packages/icons/src/repositories/github.icon-repository.ts b/packages/icons/src/repositories/github.icon-repository.ts
index a3f8a8ea7..3523bf930 100644
--- a/packages/icons/src/repositories/github.icon-repository.ts
+++ b/packages/icons/src/repositories/github.icon-repository.ts
@@ -11,14 +11,7 @@ export class GitHubIconRepository extends IconRepository {
public readonly repositoryIndexingUrl?: URL,
public readonly repositoryBlobUrlTemplate?: string,
) {
- super(
- name,
- slug,
- license,
- repositoryUrl,
- repositoryIndexingUrl,
- repositoryBlobUrlTemplate,
- );
+ super(name, slug, license, repositoryUrl, repositoryIndexingUrl, repositoryBlobUrlTemplate);
}
protected async getAllIconsInternalAsync(): Promise<RepositoryIconGroup> {
@@ -33,18 +26,13 @@ export class GitHubIconRepository extends IconRepository {
success: true,
icons: listOfFiles.tree
.filter((treeItem) =>
- this.allowedImageFileTypes.some((allowedExtension) =>
- treeItem.path.includes(allowedExtension),
- ),
+ this.allowedImageFileTypes.some((allowedExtension) => treeItem.path.includes(allowedExtension)),
)
.map((treeItem) => {
- const fileNameWithExtension =
- this.getFileNameWithoutExtensionFromPath(treeItem.path);
+ const fileNameWithExtension = this.getFileNameWithoutExtensionFromPath(treeItem.path);
return {
- imageUrl: new URL(
- this.repositoryBlobUrlTemplate!.replace("{0}", treeItem.path),
- ),
+ imageUrl: new URL(this.repositoryBlobUrlTemplate!.replace("{0}", treeItem.path)),
fileNameWithExtension: fileNameWithExtension,
local: false,
sizeInBytes: treeItem.size,
diff --git a/packages/icons/src/repositories/icon-repository.ts b/packages/icons/src/repositories/icon-repository.ts
index f6eaac46a..358e48dfa 100644
--- a/packages/icons/src/repositories/icon-repository.ts
+++ b/packages/icons/src/repositories/icon-repository.ts
@@ -19,9 +19,7 @@ export abstract class IconRepository {
try {
return await this.getAllIconsInternalAsync();
} catch (err) {
- logger.error(
- `Unable to request icons from repository "${this.slug}": ${JSON.stringify(err)}`,
- );
+ logger.error(`Unable to request icons from repository "${this.slug}": ${JSON.stringify(err)}`);
return {
success: false,
icons: [],
diff --git a/packages/icons/src/repositories/jsdelivr.icon-repository.ts b/packages/icons/src/repositories/jsdelivr.icon-repository.ts
index fe0638ccb..919cdd2ba 100644
--- a/packages/icons/src/repositories/jsdelivr.icon-repository.ts
+++ b/packages/icons/src/repositories/jsdelivr.icon-repository.ts
@@ -11,14 +11,7 @@ export class JsdelivrIconRepository extends IconRepository {
public readonly repositoryIndexingUrl: URL,
public readonly repositoryBlobUrlTemplate: string,
) {
- super(
- name,
- slug,
- license,
- repositoryUrl,
- repositoryIndexingUrl,
- repositoryBlobUrlTemplate,
- );
+ super(name, slug, license, repositoryUrl, repositoryIndexingUrl, repositoryBlobUrlTemplate);
}
protected async getAllIconsInternalAsync(): Promise<RepositoryIconGroup> {
@@ -29,18 +22,13 @@ export class JsdelivrIconRepository extends IconRepository {
success: true,
icons: listOfFiles.files
.filter((file) =>
- this.allowedImageFileTypes.some((allowedImageFileType) =>
- file.name.includes(allowedImageFileType),
- ),
+ this.allowedImageFileTypes.some((allowedImageFileType) => file.name.includes(allowedImageFileType)),
)
.map((file) => {
- const fileNameWithExtension =
- this.getFileNameWithoutExtensionFromPath(file.name);
+ const fileNameWithExtension = this.getFileNameWithoutExtensionFromPath(file.name);
return {
- imageUrl: new URL(
- this.repositoryBlobUrlTemplate.replace("{0}", file.name),
- ),
+ imageUrl: new URL(this.repositoryBlobUrlTemplate.replace("{0}", file.name)),
fileNameWithExtension: fileNameWithExtension,
local: false,
sizeInBytes: file.size,
diff --git a/packages/log/src/index.mjs b/packages/log/src/index.mjs
index c1fa71f42..1ef0b09d2 100644
--- a/packages/log/src/index.mjs
+++ b/packages/log/src/index.mjs
@@ -7,11 +7,7 @@ const logMessageFormat = format.printf(({ level, message, timestamp }) => {
});
const logger = winston.createLogger({
- format: format.combine(
- format.colorize(),
- format.timestamp(),
- logMessageFormat,
- ),
+ format: format.combine(format.colorize(), format.timestamp(), logMessageFormat),
transports: [new transports.Console(), new RedisTransport()],
});
diff --git a/packages/modals/src/confirm-modal.tsx b/packages/modals/src/confirm-modal.tsx
index 9bf3242db..d1434b874 100644
--- a/packages/modals/src/confirm-modal.tsx
+++ b/packages/modals/src/confirm-modal.tsx
@@ -3,10 +3,7 @@ import type { ComponentPropsWithoutRef, ReactNode } from "react";
import type { ButtonProps, GroupProps } from "@mantine/core";
import { Box, Button, Group } from "@mantine/core";
-import type {
- stringOrTranslation,
- TranslationFunction,
-} from "@homarr/translation";
+import type { stringOrTranslation, TranslationFunction } from "@homarr/translation";
import { translateIfNecessary } from "@homarr/translation";
import { useI18n } from "@homarr/translation/client";
@@ -31,70 +28,50 @@ export interface ConfirmModalProps {
};
}
-export const ConfirmModal = createModal<Omit<ConfirmModalProps, "title">>(
- ({ actions, innerProps }) => {
- const [loading, setLoading] = useState(false);
- const t = useI18n();
- const {
- children,
- onConfirm,
- onCancel,
- cancelProps,
- confirmProps,
- groupProps,
- labels,
- } = innerProps;
+export const ConfirmModal = createModal<Omit<ConfirmModalProps, "title">>(({ actions, innerProps }) => {
+ const [loading, setLoading] = useState(false);
+ const t = useI18n();
+ const { children, onConfirm, onCancel, cancelProps, confirmProps, groupProps, labels } = innerProps;
- const closeOnConfirm = innerProps.closeOnConfirm ?? true;
- const closeOnCancel = innerProps.closeOnCancel ?? true;
+ const closeOnConfirm = innerProps.closeOnConfirm ?? true;
+ const closeOnCancel = innerProps.closeOnCancel ?? true;
- const cancelLabel =
- labels?.cancel ?? ((t: TranslationFunction) => t("common.action.cancel"));
- const confirmLabel =
- labels?.confirm ??
- ((t: TranslationFunction) => t("common.action.confirm"));
+ const cancelLabel = labels?.cancel ?? ((t: TranslationFunction) => t("common.action.cancel"));
+ const confirmLabel = labels?.confirm ?? ((t: TranslationFunction) => t("common.action.confirm"));
- const handleCancel = useCallback(
- async (event: React.MouseEvent<HTMLButtonElement>) => {
- typeof cancelProps?.onClick === "function" &&
- cancelProps?.onClick(event);
- typeof onCancel === "function" && (await onCancel());
- closeOnCancel && actions.closeModal();
- },
- [cancelProps?.onClick, onCancel, actions.closeModal],
- );
+ const handleCancel = useCallback(
+ async (event: React.MouseEvent<HTMLButtonElement>) => {
+ typeof cancelProps?.onClick === "function" && cancelProps?.onClick(event);
+ typeof onCancel === "function" && (await onCancel());
+ closeOnCancel && actions.closeModal();
+ },
+ [cancelProps?.onClick, onCancel, actions.closeModal],
+ );
- const handleConfirm = useCallback(
- async (event: React.MouseEvent<HTMLButtonElement>) => {
- setLoading(true);
- typeof confirmProps?.onClick === "function" &&
- confirmProps?.onClick(event);
- typeof onConfirm === "function" && (await onConfirm());
- closeOnConfirm && actions.closeModal();
- setLoading(false);
- },
- [confirmProps?.onClick, onConfirm, actions.closeModal],
- );
+ const handleConfirm = useCallback(
+ async (event: React.MouseEvent<HTMLButtonElement>) => {
+ setLoading(true);
+ typeof confirmProps?.onClick === "function" && confirmProps?.onClick(event);
+ typeof onConfirm === "function" && (await onConfirm());
+ closeOnConfirm && actions.closeModal();
+ setLoading(false);
+ },
+ [confirmProps?.onClick, onConfirm, actions.closeModal],
+ );
- return (
- <>
- {children && <Box mb="md">{children}</Box>}
+ return (
+ <>
+ {children && <Box mb="md">{children}</Box>}
- <Group justify="flex-end" {...groupProps}>
- <Button variant="default" {...cancelProps} onClick={handleCancel}>
- {cancelProps?.children || translateIfNecessary(t, cancelLabel)}
- </Button>
+ <Group justify="flex-end" {...groupProps}>
+ <Button variant="default" {...cancelProps} onClick={handleCancel}>
+ {cancelProps?.children || translateIfNecessary(t, cancelLabel)}
+ </Button>
- <Button
- {...confirmProps}
- onClick={handleConfirm}
- color="red.9"
- loading={loading}
- >
- {confirmProps?.children || translateIfNecessary(t, confirmLabel)}
- </Button>
- </Group>
- </>
- );
- },
-).withOptions({});
+ <Button {...confirmProps} onClick={handleConfirm} color="red.9" loading={loading}>
+ {confirmProps?.children || translateIfNecessary(t, confirmLabel)}
+ </Button>
+ </Group>
+ </>
+ );
+}).withOptions({});
diff --git a/packages/modals/src/creator.ts b/packages/modals/src/creator.ts
index 362032033..ab91d378f 100644
--- a/packages/modals/src/creator.ts
+++ b/packages/modals/src/creator.ts
@@ -1,8 +1,6 @@
import type { CreateModalOptions, ModalComponent } from "./type";
-export const createModal = <TInnerProps>(
- component: ModalComponent<TInnerProps>,
-) => {
+export const createModal = <TInnerProps>(component: ModalComponent<TInnerProps>) => {
return {
withOptions: (options: Partial<CreateModalOptions>) => {
return {
diff --git a/packages/modals/src/index.tsx b/packages/modals/src/index.tsx
index 16e99c4b6..26265c7bb 100644
--- a/packages/modals/src/index.tsx
+++ b/packages/modals/src/index.tsx
@@ -1,15 +1,7 @@
"use client";
import type { PropsWithChildren } from "react";
-import {
- createContext,
- useCallback,
- useContext,
- useEffect,
- useReducer,
- useRef,
- useState,
-} from "react";
+import { createContext, useCallback, useContext, useEffect, useReducer, useRef, useState } from "react";
import { getDefaultZIndex, Modal } from "@mantine/core";
import { randomId } from "@mantine/hooks";
@@ -76,19 +68,12 @@ export const ModalProvider = ({ children }: PropsWithChildren) => {
[closeModal, state.current?.id],
);
- const activeModals = state.modals.filter(
- (modal) => modal.id === state.current?.id || modal.props.keepMounted,
- );
+ const activeModals = state.modals.filter((modal) => modal.id === state.current?.id || modal.props.keepMounted);
return (
<ModalContext.Provider value={{ openModalInner, closeModal }}>
{activeModals.map((modal) => (
- <ActiveModal
- key={modal.id}
- modal={modal}
- state={state}
- handleCloseModal={handleCloseModal}
- />
+ <ActiveModal key={modal.id} modal={modal} state={state} handleCloseModal={handleCloseModal} />
))}
{children}
@@ -112,8 +97,7 @@ const ActiveModal = ({ modal, state, handleCloseModal }: ActiveModalProps) => {
setTimeout(() => setOpened(true), 0);
}, []);
- const { defaultTitle: _ignored, ...otherModalProps } =
- modal.reference.modalProps;
+ const { defaultTitle: _ignored, ...otherModalProps } = modal.reference.modalProps;
return (
<Modal
@@ -145,18 +129,13 @@ interface OpenModalOptions {
title?: stringOrTranslation;
}
-export const useModalAction = <TModal extends ModalDefinition>(
- modal: TModal,
-) => {
+export const useModalAction = <TModal extends ModalDefinition>(modal: TModal) => {
const context = useContext(ModalContext);
if (!context) throw new Error("ModalContext is not provided");
return {
- openModal: (
- innerProps: inferInnerProps<TModal>,
- options: OpenModalOptions | void,
- ) => {
+ openModal: (innerProps: inferInnerProps<TModal>, options: OpenModalOptions | void) => {
context.openModalInner({ modal, innerProps, options: options ?? {} });
},
};
@@ -166,7 +145,6 @@ export const useConfirmModal = () => {
const { openModal } = useModalAction(ConfirmModal);
return {
- openConfirmModal: (props: ConfirmModalProps) =>
- openModal(props, { title: props.title }),
+ openConfirmModal: (props: ConfirmModalProps) => openModal(props, { title: props.title }),
};
};
diff --git a/packages/modals/src/reducer.tsx b/packages/modals/src/reducer.tsx
index 10bbd93ce..ab45cb386 100644
--- a/packages/modals/src/reducer.tsx
+++ b/packages/modals/src/reducer.tsx
@@ -39,10 +39,7 @@ interface CloseAllAction {
canceled?: boolean;
}
-export const modalReducer = (
- state: ModalsState,
- action: OpenAction | CloseAction | CloseAllAction,
-): ModalsState => {
+export const modalReducer = (state: ModalsState, action: OpenAction | CloseAction | CloseAllAction): ModalsState => {
switch (action.type) {
case "OPEN": {
const newModal = {
@@ -62,9 +59,7 @@ export const modalReducer = (
modal.props.onClose?.();
- const remainingModals = state.modals.filter(
- (modal) => modal.id !== action.modalId,
- );
+ const remainingModals = state.modals.filter((modal) => modal.id !== action.modalId);
return {
current: remainingModals[remainingModals.length - 1] || state.current,
@@ -95,9 +90,7 @@ export const modalReducer = (
}
};
-const getModal = <TModal extends ModalDefinition>(
- modal: ModalState<TModal>,
-) => {
+const getModal = <TModal extends ModalDefinition>(modal: ModalState<TModal>) => {
const ModalContent = modal.modal.component;
const { innerProps, ...rest } = modal.props;
diff --git a/packages/redis/src/index.ts b/packages/redis/src/index.ts
index 71c6dca99..06ec8006b 100644
--- a/packages/redis/src/index.ts
+++ b/packages/redis/src/index.ts
@@ -1,8 +1,6 @@
import { createQueueChannel, createSubPubChannel } from "./lib/channel";
-export const exampleChannel = createSubPubChannel<{ message: string }>(
- "example",
-);
+export const exampleChannel = createSubPubChannel<{ message: string }>("example");
export const queueChannel = createQueueChannel<{
name: string;
executionDate: Date;
diff --git a/packages/redis/src/lib/channel.ts b/packages/redis/src/lib/channel.ts
index bb41f10cc..eeb4d13ba 100644
--- a/packages/redis/src/lib/channel.ts
+++ b/packages/redis/src/lib/channel.ts
@@ -32,9 +32,7 @@ export const createSubPubChannel = <TData>(name: string) => {
if (!err) {
return;
}
- logger.error(
- `Error with channel '${channelName}': ${err.name} (${err.message})`,
- );
+ logger.error(`Error with channel '${channelName}': ${err.name} (${err.message})`);
});
subscriber.on("message", (channel, message) => {
if (channel !== channelName) return; // TODO: check if this is necessary - it should be handled by the redis client
diff --git a/packages/spotlight/ReadMe.md b/packages/spotlight/ReadMe.md
index 7705d3373..ac4122282 100644
--- a/packages/spotlight/ReadMe.md
+++ b/packages/spotlight/ReadMe.md
@@ -130,8 +130,7 @@ const ColorSchemeButton = () => {
{
id: "toggle-color-scheme",
title: (t) => t("common.colorScheme.toggle.title"),
- description: (t) =>
- t(`common.colorScheme.toggle.${colorScheme}.description`),
+ description: (t) => t(`common.colorScheme.toggle.${colorScheme}.description`),
icon: colorScheme === "light" ? IconSun : IconMoon,
group: "action",
type: "button",
diff --git a/packages/spotlight/src/chip-group.tsx b/packages/spotlight/src/chip-group.tsx
index 36437f348..d2cc08cc9 100644
--- a/packages/spotlight/src/chip-group.tsx
+++ b/packages/spotlight/src/chip-group.tsx
@@ -2,17 +2,10 @@ import { Chip } from "@mantine/core";
import { useScopedI18n } from "@homarr/translation/client";
-import {
- selectNextAction,
- selectPreviousAction,
- spotlightStore,
- triggerSelectedAction,
-} from "./spotlight-store";
+import { selectNextAction, selectPreviousAction, spotlightStore, triggerSelectedAction } from "./spotlight-store";
import type { SpotlightActionGroup } from "./type";
-const disableArrowUpAndDown = (
- event: React.KeyboardEvent<HTMLInputElement>,
-) => {
+const disableArrowUpAndDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
if (event.key === "ArrowDown") {
selectNextAction(spotlightStore);
event.preventDefault();
@@ -27,8 +20,7 @@ const disableArrowUpAndDown = (
const focusActiveByDefault = (event: React.FocusEvent<HTMLInputElement>) => {
const relatedTarget = event.relatedTarget;
- const isPreviousTargetRadio =
- relatedTarget && "type" in relatedTarget && relatedTarget.type === "radio";
+ const isPreviousTargetRadio = relatedTarget && "type" in relatedTarget && relatedTarget.type === "radio";
if (isPreviousTargetRadio) return;
const group = event.currentTarget.parentElement?.parentElement;
@@ -45,12 +37,7 @@ interface Props {
export const GroupChip = ({ group }: Props) => {
const t = useScopedI18n("common.search.group");
return (
- <Chip
- key={group}
- value={group}
- onFocus={focusActiveByDefault}
- onKeyDown={disableArrowUpAndDown}
- >
+ <Chip key={group} value={group} onFocus={focusActiveByDefault} onKeyDown={disableArrowUpAndDown}>
{t(group)}
</Chip>
);
diff --git a/packages/spotlight/src/component.tsx b/packages/spotlight/src/component.tsx
index 043b7e780..59f67ef20 100644
--- a/packages/spotlight/src/component.tsx
+++ b/packages/spotlight/src/component.tsx
@@ -3,10 +3,7 @@
import { useCallback, useState } from "react";
import Link from "next/link";
import { Center, Chip, Divider, Flex, Group, Text } from "@mantine/core";
-import {
- Spotlight as MantineSpotlight,
- SpotlightAction,
-} from "@mantine/spotlight";
+import { Spotlight as MantineSpotlight, SpotlightAction } from "@mantine/spotlight";
import { IconSearch } from "@tabler/icons-react";
import { useAtomValue } from "jotai";
@@ -41,11 +38,7 @@ export const Spotlight = () => {
const renderRoot =
item.type === "link"
? (props: Record<string, unknown>) => (
- <Link
- href={prepareHref(item.href, query)}
- target={item.openInNewTab ? "_blank" : undefined}
- {...props}
- />
+ <Link href={prepareHref(item.href, query)} target={item.openInNewTab ? "_blank" : undefined} {...props} />
)
: undefined;
@@ -60,14 +53,7 @@ export const Spotlight = () => {
{item.icon && (
<Center w={50} h={50}>
{typeof item.icon !== "string" && <item.icon size={24} />}
- {typeof item.icon === "string" && (
- <img
- src={item.icon}
- alt={item.title}
- width={24}
- height={24}
- />
- )}
+ {typeof item.icon === "string" && <img src={item.icon} alt={item.title} width={24} height={24} />}
</Center>
)}
@@ -94,11 +80,7 @@ export const Spotlight = () => {
);
return (
- <MantineSpotlight.Root
- query={query}
- onQueryChange={setQuery}
- store={spotlightStore}
- >
+ <MantineSpotlight.Root query={query} onQueryChange={setQuery} store={spotlightStore}>
<MantineSpotlight.Search
placeholder={t("common.rtl", {
value: t("common.search.placeholder"),
@@ -119,13 +101,7 @@ export const Spotlight = () => {
</Group>
<MantineSpotlight.ActionsList>
- {items.length > 0 ? (
- items
- ) : (
- <MantineSpotlight.Empty>
- {t("common.search.nothingFound")}
- </MantineSpotlight.Empty>
- )}
+ {items.length > 0 ? items : <MantineSpotlight.Empty>{t("common.search.nothingFound")}</MantineSpotlight.Empty>}
</MantineSpotlight.ActionsList>
</MantineSpotlight.Root>
);
@@ -135,10 +111,7 @@ const prepareHref = (href: string, query: string) => {
return href.replace("%s", query);
};
-const translateIfNecessary = (
- value: string | ((t: TranslationFunction) => string),
- t: TranslationFunction,
-) => {
+const translateIfNecessary = (value: string | ((t: TranslationFunction) => string), t: TranslationFunction) => {
if (typeof value === "function") {
return value(t);
}
@@ -146,10 +119,7 @@ const translateIfNecessary = (
return value;
};
-const prepareAction = (
- action: SpotlightActionData,
- t: TranslationFunction,
-) => ({
+const prepareAction = (action: SpotlightActionData, t: TranslationFunction) => ({
...action,
title: translateIfNecessary(action.title, t),
description: translateIfNecessary(action.description, t),
diff --git a/packages/spotlight/src/data-store.ts b/packages/spotlight/src/data-store.ts
index f217ae2ee..0a2dbd52d 100644
--- a/packages/spotlight/src/data-store.ts
+++ b/packages/spotlight/src/data-store.ts
@@ -7,9 +7,7 @@ import type { SpotlightActionData, SpotlightActionGroup } from "./type";
const defaultGroups = ["all", "web", "action"] as const;
const reversedDefaultGroups = [...defaultGroups].reverse() as string[];
const actionsAtom = atom<Record<string, readonly SpotlightActionData[]>>({});
-export const actionsAtomRead = atom((get) =>
- Object.values(get(actionsAtom)).flatMap((item) => item),
-);
+export const actionsAtomRead = atom((get) => Object.values(get(actionsAtom)).flatMap((item) => item));
export const groupsAtomRead = atom((get) =>
Array.from(
@@ -43,8 +41,7 @@ export const useRegisterSpotlightActions = (
const setActions = useSetAtom(actionsAtom);
// Use deep compare effect if there are dependencies for the actions, this supports deep compare of the action dependencies
- const useSpecificEffect =
- dependencies.length >= 1 ? useDeepCompareEffect : useEffect;
+ const useSpecificEffect = dependencies.length >= 1 ? useDeepCompareEffect : useEffect;
useSpecificEffect(() => {
if (!registrations.has(key) || dependencies.length >= 1) {
diff --git a/packages/spotlight/src/spotlight-store.ts b/packages/spotlight/src/spotlight-store.ts
index 3e8659de4..052ac59cb 100644
--- a/packages/spotlight/src/spotlight-store.ts
+++ b/packages/spotlight/src/spotlight-store.ts
@@ -13,12 +13,9 @@ export const setSelectedAction = (index: number, store: SpotlightStore) => {
export const selectAction = (index: number, store: SpotlightStore): number => {
const state = store.getState();
const actionsList = document.getElementById(state.listId);
- const selected =
- actionsList?.querySelector<HTMLButtonElement>("[data-selected]");
- const actions =
- actionsList?.querySelectorAll<HTMLButtonElement>("[data-action]") ?? [];
- const nextIndex =
- index === -1 ? actions.length - 1 : index === actions.length ? 0 : index;
+ const selected = actionsList?.querySelector<HTMLButtonElement>("[data-selected]");
+ const actions = actionsList?.querySelectorAll<HTMLButtonElement>("[data-action]") ?? [];
+ const nextIndex = index === -1 ? actions.length - 1 : index === actions.length ? 0 : index;
const selectedIndex = clamp(nextIndex, 0, actions.length - 1);
selected?.removeAttribute("data-selected");
@@ -38,8 +35,6 @@ export const selectPreviousAction = (store: SpotlightStore) => {
};
export const triggerSelectedAction = (store: SpotlightStore) => {
const state = store.getState();
- const selected = document.querySelector<HTMLButtonElement>(
- `#${state.listId} [data-selected]`,
- );
+ const selected = document.querySelector<HTMLButtonElement>(`#${state.listId} [data-selected]`);
selected?.click();
};
diff --git a/packages/spotlight/src/type.ts b/packages/spotlight/src/type.ts
index d8cb6b683..25f96c2c7 100644
--- a/packages/spotlight/src/type.ts
+++ b/packages/spotlight/src/type.ts
@@ -1,11 +1,7 @@
-import type {
- TranslationFunction,
- TranslationObject,
-} from "@homarr/translation";
+import type { TranslationFunction, TranslationObject } from "@homarr/translation";
import type { TablerIcon } from "@homarr/ui";
-export type SpotlightActionGroup =
- keyof TranslationObject["common"]["search"]["group"];
+export type SpotlightActionGroup = keyof TranslationObject["common"]["search"]["group"];
interface BaseSpotlightAction {
id: string;
diff --git a/packages/translation/src/client.ts b/packages/translation/src/client.ts
index 0fea0644c..8cbb49e73 100644
--- a/packages/translation/src/client.ts
+++ b/packages/translation/src/client.ts
@@ -5,12 +5,9 @@ import { createI18nClient } from "next-international/client";
import { languageMapping } from "./lang";
import enTranslation from "./lang/en";
-export const {
- useI18n,
- useScopedI18n,
- useCurrentLocale,
- useChangeLocale,
- I18nProviderClient,
-} = createI18nClient(languageMapping(), {
- fallbackLocale: enTranslation,
-});
+export const { useI18n, useScopedI18n, useCurrentLocale, useChangeLocale, I18nProviderClient } = createI18nClient(
+ languageMapping(),
+ {
+ fallbackLocale: enTranslation,
+ },
+);
diff --git a/packages/translation/src/index.ts b/packages/translation/src/index.ts
index faf24851a..805b3e873 100644
--- a/packages/translation/src/index.ts
+++ b/packages/translation/src/index.ts
@@ -9,10 +9,7 @@ export type SupportedLanguage = (typeof supportedLanguages)[number];
export const defaultLocale = "en";
export { languageMapping } from "./lang";
-export const translateIfNecessary = (
- t: TranslationFunction,
- value: stringOrTranslation | undefined,
-) => {
+export const translateIfNecessary = (t: TranslationFunction, value: stringOrTranslation | undefined) => {
if (typeof value === "function") {
return value(t);
}
diff --git a/packages/translation/src/lang.ts b/packages/translation/src/lang.ts
index 42f624c12..7765d1cce 100644
--- a/packages/translation/src/lang.ts
+++ b/packages/translation/src/lang.ts
@@ -6,12 +6,8 @@ export const languageMapping = () => {
const mapping: Record<string, unknown> = {};
for (const language of supportedLanguages) {
- mapping[language] = () =>
- import(`./lang/${language}`) as ReturnType<typeof enTranslations>;
+ mapping[language] = () => import(`./lang/${language}`) as ReturnType<typeof enTranslations>;
}
- return mapping as Record<
- (typeof supportedLanguages)[number],
- () => ReturnType<typeof enTranslations>
- >;
+ return mapping as Record<(typeof supportedLanguages)[number], () => ReturnType<typeof enTranslations>>;
};
diff --git a/packages/translation/src/lang/de.ts b/packages/translation/src/lang/de.ts
index db314a4a8..e0cbe8b72 100644
--- a/packages/translation/src/lang/de.ts
+++ b/packages/translation/src/lang/de.ts
@@ -93,8 +93,7 @@ export default {
},
testConnection: {
action: "Verbindung überprüfen",
- alertNotice:
- "Der Button zum Speichern wird aktiviert, sobald die Verbindung erfolgreich überprüft wurde",
+ alertNotice: "Der Button zum Speichern wird aktiviert, sobald die Verbindung erfolgreich überprüft wurde",
notification: {
success: {
title: "Verbindung erfolgreich",
@@ -121,8 +120,7 @@ export default {
secrets: {
title: "Zugangsdaten",
lastUpdated: "Zuletzt geändert {date}",
- secureNotice:
- "Diese Zugangsdaten können nach der Erstellung nicht mehr ausgelesen werden",
+ secureNotice: "Diese Zugangsdaten können nach der Erstellung nicht mehr ausgelesen werden",
reset: {
title: "Zugangsdaten zurücksetzen",
message: "Möchtest du diese Zugangsdaten wirklich zurücksetzen?",
@@ -172,8 +170,7 @@ export default {
option: {
is24HourFormat: {
label: "24-Stunden Format",
- description:
- "Verwende das 24-Stunden Format anstelle des 12-Stunden Formats",
+ description: "Verwende das 24-Stunden Format anstelle des 12-Stunden Formats",
},
isLocaleTime: {
label: "Lokale Zeit verwenden",
diff --git a/packages/translation/src/lang/en.ts b/packages/translation/src/lang/en.ts
index c83851cd6..fc382d453 100644
--- a/packages/translation/src/lang/en.ts
+++ b/packages/translation/src/lang/en.ts
@@ -118,8 +118,7 @@ export default {
label: "Delete user permanently",
description:
"Deletes this user including their preferences. Will not delete any boards. User will not be notified.",
- confirm:
- "Are you sure, that you want to delete the user {username} with his preferences?",
+ confirm: "Are you sure, that you want to delete the user {username} with his preferences?",
},
select: {
label: "Select user",
@@ -144,8 +143,7 @@ export default {
item: {
admin: {
label: "Administrator",
- description:
- "Members with this permission have full access to all features and settings",
+ description: "Members with this permission have full access to all features and settings",
},
},
},
@@ -162,8 +160,7 @@ export default {
},
"modify-all": {
label: "Modify all boards",
- description:
- "Allow members to modify all boards (Does not include access control and danger zone)",
+ description: "Allow members to modify all boards (Does not include access control and danger zone)",
},
"full-access": {
label: "Full board access",
@@ -181,8 +178,7 @@ export default {
},
"use-all": {
label: "Use all integrations",
- description:
- "Allows members to add any integrations to their boards",
+ description: "Allows members to add any integrations to their boards",
},
"interact-all": {
label: "Interact with any integration",
@@ -190,8 +186,7 @@ export default {
},
"full-access": {
label: "Full integration access",
- description:
- "Allow members to manage, use and interact with any integration",
+ description: "Allow members to manage, use and interact with any integration",
},
},
},
@@ -211,8 +206,7 @@ export default {
transfer: {
label: "Transfer ownership",
description: "Transfer ownership of this group to another user.",
- confirm:
- "Are you sure you want to transfer ownership for the group {name} to {username}?",
+ confirm: "Are you sure you want to transfer ownership for the group {name} to {username}?",
notification: {
success: {
message: "Transfered group {group} successfully to {user}",
@@ -231,8 +225,7 @@ export default {
},
delete: {
label: "Delete group",
- description:
- "Once you delete a group, there is no going back. Please be certain.",
+ description: "Once you delete a group, there is no going back. Please be certain.",
confirm: "Are you sure you want to delete the group {name}?",
notification: {
success: {
@@ -383,8 +376,7 @@ export default {
},
testConnection: {
action: "Test connection",
- alertNotice:
- "The Save button is enabled once a successful connection is established",
+ alertNotice: "The Save button is enabled once a successful connection is established",
notification: {
success: {
title: "Connection successful",
@@ -454,8 +446,7 @@ export default {
checkoutDocs: "Check out the documentation",
},
iconPicker: {
- header:
- "Type name or objects to filter for icons... Homarr will search through {countIcons} icons for you.",
+ header: "Type name or objects to filter for icons... Homarr will search through {countIcons} icons for you.",
},
notification: {
create: {
@@ -642,8 +633,7 @@ export default {
option: {
customTitleToggle: {
label: "Custom Title/City display",
- description:
- "Show off a custom title or the name of the city/country on top of the clock.",
+ description: "Show off a custom title or the name of the city/country on top of the clock.",
},
customTitle: {
label: "Title",
@@ -734,8 +724,7 @@ export default {
},
iframe: {
name: "iFrame",
- description:
- "Embed any content from the internet. Some websites may restrict access.",
+ description: "Embed any content from the internet. Some websites may restrict access.",
option: {
embedUrl: {
label: "Embed URL",
@@ -767,14 +756,12 @@ export default {
},
error: {
noUrl: "No iFrame URL provided",
- noBrowerSupport:
- "Your Browser does not support iframes. Please update your browser.",
+ noBrowerSupport: "Your Browser does not support iframes. Please update your browser.",
},
},
weather: {
name: "Weather",
- description:
- "Displays the current weather information of a set location.",
+ description: "Displays the current weather information of a set location.",
option: {
isFormatFahrenheit: {
label: "Temperature in Fahrenheit",
@@ -790,8 +777,7 @@ export default {
},
forecastDayCount: {
label: "Amount of forecast days",
- description:
- "When the widget is not wide enough, less days are shown",
+ description: "When the widget is not wide enough, less days are shown",
},
},
kind: {
@@ -844,8 +830,7 @@ export default {
},
hasAutoPlay: {
label: "Autoplay",
- description:
- "Autoplay only works when muted because of browser restrictions",
+ description: "Autoplay only works when muted because of browser restrictions",
},
isMuted: {
label: "Muted",
@@ -918,13 +903,11 @@ export default {
option: {
repeat: {
label: "Repeat",
- description:
- "The image is repeated as much as needed to cover the whole background image painting area.",
+ description: "The image is repeated as much as needed to cover the whole background image painting area.",
},
"no-repeat": {
label: "No repeat",
- description:
- "The image is not repeated and may not fill the entire space.",
+ description: "The image is not repeated and may not fill the entire space.",
},
"repeat-x": {
label: "Repeat X",
@@ -978,8 +961,7 @@ export default {
section: {
general: {
title: "General",
- unrecognizedLink:
- "The provided link is not recognized and won't preview, it might still work.",
+ unrecognizedLink: "The provided link is not recognized and won't preview, it might still work.",
},
layout: {
title: "Layout",
@@ -1036,8 +1018,7 @@ export default {
action: {
rename: {
label: "Rename board",
- description:
- "Changing the name will break any links to this board.",
+ description: "Changing the name will break any links to this board.",
button: "Change name",
modal: {
title: "Rename board",
@@ -1068,8 +1049,7 @@ export default {
},
delete: {
label: "Delete this board",
- description:
- "Once you delete a board, there is no going back. Please be certain.",
+ description: "Once you delete a board, there is no going back. Please be certain.",
button: "Delete this board",
confirm: {
title: "Delete board",
diff --git a/packages/translation/src/server.ts b/packages/translation/src/server.ts
index 481ca59cb..c7b32793a 100644
--- a/packages/translation/src/server.ts
+++ b/packages/translation/src/server.ts
@@ -3,9 +3,6 @@ import { createI18nServer } from "next-international/server";
import { languageMapping } from "./lang";
import enTranslation from "./lang/en";
-export const { getI18n, getScopedI18n, getStaticParams } = createI18nServer(
- languageMapping(),
- {
- fallbackLocale: enTranslation,
- },
-);
+export const { getI18n, getScopedI18n, getStaticParams } = createI18nServer(languageMapping(), {
+ fallbackLocale: enTranslation,
+});
diff --git a/packages/ui/src/components/search-input.tsx b/packages/ui/src/components/search-input.tsx
index 1cf182741..4a783d50a 100644
--- a/packages/ui/src/components/search-input.tsx
+++ b/packages/ui/src/components/search-input.tsx
@@ -12,10 +12,7 @@ interface SearchInputProps {
placeholder: string;
}
-export const SearchInput = ({
- placeholder,
- defaultValue,
-}: SearchInputProps) => {
+export const SearchInput = ({ placeholder, defaultValue }: SearchInputProps) => {
// eslint-disable-next-line @typescript-eslint/unbound-method
const { replace } = useRouter();
const pathName = usePathname();
diff --git a/packages/ui/src/components/select-with-custom-items.tsx b/packages/ui/src/components/select-with-custom-items.tsx
index f8185e0f5..94b756a58 100644
--- a/packages/ui/src/components/select-with-custom-items.tsx
+++ b/packages/ui/src/components/select-with-custom-items.tsx
@@ -11,19 +11,15 @@ interface BaseSelectItem {
}
export interface SelectWithCustomItemsProps<TSelectItem extends BaseSelectItem>
- extends Pick<
- SelectProps,
- "label" | "error" | "defaultValue" | "value" | "onChange" | "placeholder"
- > {
+ extends Pick<SelectProps, "label" | "error" | "defaultValue" | "value" | "onChange" | "placeholder"> {
data: TSelectItem[];
onBlur?: (event: React.FocusEvent<HTMLButtonElement>) => void;
onFocus?: (event: React.FocusEvent<HTMLButtonElement>) => void;
}
-type Props<TSelectItem extends BaseSelectItem> =
- SelectWithCustomItemsProps<TSelectItem> & {
- SelectOption: React.ComponentType<TSelectItem>;
- };
+type Props<TSelectItem extends BaseSelectItem> = SelectWithCustomItemsProps<TSelectItem> & {
+ SelectOption: React.ComponentType<TSelectItem>;
+};
export const SelectWithCustomItems = <TSelectItem extends BaseSelectItem>({
data,
@@ -45,10 +41,7 @@ export const SelectWithCustomItems = <TSelectItem extends BaseSelectItem>({
onChange,
});
- const selectedOption = useMemo(
- () => data.find((item) => item.value === _value),
- [data, _value],
- );
+ const selectedOption = useMemo(() => data.find((item) => item.value === _value), [data, _value]);
const options = data.map((item) => (
<Combobox.Option value={item.value} key={item.value}>
@@ -69,11 +62,7 @@ export const SelectWithCustomItems = <TSelectItem extends BaseSelectItem>({
);
return (
- <Combobox
- store={combobox}
- withinPortal={false}
- onOptionSubmit={onOptionSubmit}
- >
+ <Combobox store={combobox} withinPortal={false} onOptionSubmit={onOptionSubmit}>
<Combobox.Target>
<InputBase
{...props}
@@ -85,11 +74,7 @@ export const SelectWithCustomItems = <TSelectItem extends BaseSelectItem>({
rightSectionPointerEvents="none"
multiline
>
- {selectedOption ? (
- <SelectOption {...selectedOption} />
- ) : (
- <Input.Placeholder>{placeholder}</Input.Placeholder>
- )}
+ {selectedOption ? <SelectOption {...selectedOption} /> : <Input.Placeholder>{placeholder}</Input.Placeholder>}
</InputBase>
</Combobox.Target>
diff --git a/packages/ui/src/components/select-with-description-and-badge.tsx b/packages/ui/src/components/select-with-description-and-badge.tsx
index 0293c1e83..5874da042 100644
--- a/packages/ui/src/components/select-with-description-and-badge.tsx
+++ b/packages/ui/src/components/select-with-description-and-badge.tsx
@@ -15,19 +15,10 @@ export interface SelectItemWithDescriptionBadge {
type Props = SelectWithCustomItemsProps<SelectItemWithDescriptionBadge>;
export const SelectWithDescriptionBadge = (props: Props) => {
- return (
- <SelectWithCustomItems<SelectItemWithDescriptionBadge>
- {...props}
- SelectOption={SelectOption}
- />
- );
+ return <SelectWithCustomItems<SelectItemWithDescriptionBadge> {...props} SelectOption={SelectOption} />;
};
-const SelectOption = ({
- label,
- description,
- badge,
-}: SelectItemWithDescriptionBadge) => {
+const SelectOption = ({ label, description, badge }: SelectItemWithDescriptionBadge) => {
return (
<Group justify="space-between">
<div>
diff --git a/packages/ui/src/components/select-with-description.tsx b/packages/ui/src/components/select-with-description.tsx
index c301effcc..bc5914216 100644
--- a/packages/ui/src/components/select-with-description.tsx
+++ b/packages/ui/src/components/select-with-description.tsx
@@ -13,12 +13,7 @@ export interface SelectItemWithDescription {
type Props = SelectWithCustomItemsProps<SelectItemWithDescription>;
export const SelectWithDescription = (props: Props) => {
- return (
- <SelectWithCustomItems<SelectItemWithDescription>
- {...props}
- SelectOption={SelectOption}
- />
- );
+ return <SelectWithCustomItems<SelectItemWithDescription> {...props} SelectOption={SelectOption} />;
};
const SelectOption = ({ label, description }: SelectItemWithDescription) => {
diff --git a/packages/ui/src/components/table-pagination.tsx b/packages/ui/src/components/table-pagination.tsx
index eefcc0168..83420ba54 100644
--- a/packages/ui/src/components/table-pagination.tsx
+++ b/packages/ui/src/components/table-pagination.tsx
@@ -47,23 +47,12 @@ export const TablePagination = ({ total }: TablePaginationProps) => {
);
return (
- <Pagination
- total={total}
- getItemProps={getItemProps}
- getControlProps={getControlProps}
- onChange={handleChange}
- />
+ <Pagination total={total} getItemProps={getItemProps} getControlProps={getControlProps} onChange={handleChange} />
);
};
-type ControlType = Parameters<
- Exclude<PaginationProps["getControlProps"], undefined>
->[0];
-const calculatePageFor = (
- type: ControlType,
- current: number,
- total: number,
-) => {
+type ControlType = Parameters<Exclude<PaginationProps["getControlProps"], undefined>>[0];
+const calculatePageFor = (type: ControlType, current: number, total: number) => {
switch (type) {
case "first":
return 1;
diff --git a/packages/ui/src/components/user-avatar-group.tsx b/packages/ui/src/components/user-avatar-group.tsx
index cb838c814..1aa2fbf6b 100644
--- a/packages/ui/src/components/user-avatar-group.tsx
+++ b/packages/ui/src/components/user-avatar-group.tsx
@@ -10,11 +10,7 @@ interface UserAvatarGroupProps {
users: UserProps[];
}
-export const UserAvatarGroup = ({
- size,
- limit,
- users,
-}: UserAvatarGroupProps) => {
+export const UserAvatarGroup = ({ size, limit, users }: UserAvatarGroupProps) => {
return (
<TooltipGroup openDelay={300} closeDelay={300}>
<AvatarGroup>
diff --git a/packages/ui/src/components/user-avatar.tsx b/packages/ui/src/components/user-avatar.tsx
index 41369225c..805be9c9b 100644
--- a/packages/ui/src/components/user-avatar.tsx
+++ b/packages/ui/src/components/user-avatar.tsx
@@ -22,7 +22,5 @@ export const UserAvatar = ({ user, size }: UserAvatarProps) => {
return <Avatar {...commonProps} src={user.image} alt={user.name} />;
}
- return (
- <Avatar {...commonProps}>{user.name.substring(0, 2).toUpperCase()}</Avatar>
- );
+ return <Avatar {...commonProps}>{user.name.substring(0, 2).toUpperCase()}</Avatar>;
};
diff --git a/packages/validation/src/enums.ts b/packages/validation/src/enums.ts
index d9644a776..f9e59ef89 100644
--- a/packages/validation/src/enums.ts
+++ b/packages/validation/src/enums.ts
@@ -2,10 +2,8 @@ import { z } from "zod";
type CouldBeReadonlyArray<T> = T[] | readonly T[];
-export const zodEnumFromArray = <T extends string>(
- array: CouldBeReadonlyArray<T>,
-) => z.enum([array[0]!, ...array.slice(1)]);
+export const zodEnumFromArray = <T extends string>(array: CouldBeReadonlyArray<T>) =>
+ z.enum([array[0]!, ...array.slice(1)]);
-export const zodUnionFromArray = <T extends z.ZodTypeAny>(
- array: CouldBeReadonlyArray<T>,
-) => z.union([array[0]!, array[1]!, ...array.slice(2)]);
+export const zodUnionFromArray = <T extends z.ZodTypeAny>(array: CouldBeReadonlyArray<T>) =>
+ z.union([array[0]!, array[1]!, ...array.slice(2)]);
diff --git a/packages/validation/src/form/i18n.ts b/packages/validation/src/form/i18n.ts
index 20deccdc5..08f97e988 100644
--- a/packages/validation/src/form/i18n.ts
+++ b/packages/validation/src/form/i18n.ts
@@ -16,10 +16,7 @@ export const zodErrorMap = <
message: error.message ?? ctx.defaultError,
};
return {
- message: t(
- error.key ? `common.zod.${error.key}` : "common.zod.errors.default",
- error.params ?? {},
- ),
+ message: t(error.key ? `common.zod.${error.key}` : "common.zod.errors.default", error.params ?? {}),
};
};
};
@@ -134,6 +131,5 @@ export interface CustomErrorParams {
};
}
-export const createCustomErrorParams = (
- i18n: CustomErrorParams["i18n"] | CustomErrorParams["i18n"]["key"],
-) => (typeof i18n === "string" ? { i18n: { key: i18n } } : { i18n });
+export const createCustomErrorParams = (i18n: CustomErrorParams["i18n"] | CustomErrorParams["i18n"]["key"]) =>
+ typeof i18n === "string" ? { i18n: { key: i18n } } : { i18n };
diff --git a/packages/validation/src/index.ts b/packages/validation/src/index.ts
index 9d3c503be..2d7f3701d 100644
--- a/packages/validation/src/index.ts
+++ b/packages/validation/src/index.ts
@@ -18,8 +18,4 @@ export const validation = {
icons: iconsSchemas,
};
-export {
- createSectionSchema,
- sharedItemSchema,
- type BoardItemIntegration,
-} from "./shared";
+export { createSectionSchema, sharedItemSchema, type BoardItemIntegration } from "./shared";
diff --git a/packages/validation/src/shared.ts b/packages/validation/src/shared.ts
index c5aa875a2..0aa6feaf1 100644
--- a/packages/validation/src/shared.ts
+++ b/packages/validation/src/shared.ts
@@ -29,9 +29,7 @@ export const commonItemSchema = z
})
.and(sharedItemSchema);
-const createCategorySchema = <TItemSchema extends z.ZodTypeAny>(
- itemSchema: TItemSchema,
-) =>
+const createCategorySchema = <TItemSchema extends z.ZodTypeAny>(itemSchema: TItemSchema) =>
z.object({
id: z.string(),
name: z.string(),
@@ -40,9 +38,7 @@ const createCategorySchema = <TItemSchema extends z.ZodTypeAny>(
items: z.array(itemSchema),
});
-const createEmptySchema = <TItemSchema extends z.ZodTypeAny>(
- itemSchema: TItemSchema,
-) =>
+const createEmptySchema = <TItemSchema extends z.ZodTypeAny>(itemSchema: TItemSchema) =>
z.object({
id: z.string(),
kind: z.literal("empty"),
@@ -50,6 +46,5 @@ const createEmptySchema = <TItemSchema extends z.ZodTypeAny>(
items: z.array(itemSchema),
});
-export const createSectionSchema = <TItemSchema extends z.ZodTypeAny>(
- itemSchema: TItemSchema,
-) => z.union([createCategorySchema(itemSchema), createEmptySchema(itemSchema)]);
+export const createSectionSchema = <TItemSchema extends z.ZodTypeAny>(itemSchema: TItemSchema) =>
+ z.union([createCategorySchema(itemSchema), createEmptySchema(itemSchema)]);
diff --git a/packages/validation/src/user.ts b/packages/validation/src/user.ts
index 28a8e44d2..9653b7991 100644
--- a/packages/validation/src/user.ts
+++ b/packages/validation/src/user.ts
@@ -6,8 +6,7 @@ const usernameSchema = z.string().min(3).max(255);
const passwordSchema = z.string().min(8).max(255);
const confirmPasswordRefine = [
- (data: { password: string; confirmPassword: string }) =>
- data.password === data.confirmPassword,
+ (data: { password: string; confirmPassword: string }) => data.password === data.confirmPassword,
{
path: ["confirmPassword"],
params: createCustomErrorParams("passwordsDoNotMatch"),
@@ -66,9 +65,7 @@ const changePasswordSchema = z
})
.refine(confirmPasswordRefine[0], confirmPasswordRefine[1]);
-const changePasswordApiSchema = changePasswordSchema.and(
- z.object({ userId: z.string() }),
-);
+const changePasswordApiSchema = changePasswordSchema.and(z.object({ userId: z.string() }));
export const userSchemas = {
signIn: signInSchema,
diff --git a/packages/widgets/src/_inputs/common.tsx b/packages/widgets/src/_inputs/common.tsx
index 486c4b650..17d03aecf 100644
--- a/packages/widgets/src/_inputs/common.tsx
+++ b/packages/widgets/src/_inputs/common.tsx
@@ -9,9 +9,7 @@ export interface CommonWidgetInputProps<TKey extends WidgetOptionType> {
options: Omit<WidgetOptionOfType<TKey>, "defaultValue" | "type">;
}
-type UseWidgetInputTranslationReturnType = (
- key: "label" | "description",
-) => string;
+type UseWidgetInputTranslationReturnType = (key: "label" | "description") => string;
/**
* Short description why as and unknown convertions are used below:
@@ -23,10 +21,7 @@ type UseWidgetInputTranslationReturnType = (
* - The label translation can be used for every input, especially considering that all options should have defined a label for themself. The description translation should only be used when withDescription
* is defined for the option. The method does sadly not reconize issues with those definitions. So it does not yell at you when you somewhere show the label without having it defined in the translations.
*/
-export const useWidgetInputTranslation = (
- kind: WidgetKind,
- property: string,
-): UseWidgetInputTranslationReturnType => {
+export const useWidgetInputTranslation = (kind: WidgetKind, property: string): UseWidgetInputTranslationReturnType => {
return useScopedI18n(
`widget.${kind}.option.${property}` as never, // Because the type is complex and not recognized by typescript, we need to cast it to never to make it work.
) as unknown as UseWidgetInputTranslationReturnType;
diff --git a/packages/widgets/src/_inputs/form.ts b/packages/widgets/src/_inputs/form.ts
index c90b4d402..a0199b55f 100644
--- a/packages/widgets/src/_inputs/form.ts
+++ b/packages/widgets/src/_inputs/form.ts
@@ -4,5 +4,4 @@ import { createFormContext } from "@homarr/form";
import type { WidgetEditModalState } from "../modals/widget-edit-modal";
-export const [FormProvider, useFormContext, useForm] =
- createFormContext<WidgetEditModalState>();
+export const [FormProvider, useFormContext, useForm] = createFormContext<WidgetEditModalState>();
diff --git a/packages/widgets/src/_inputs/index.ts b/packages/widgets/src/_inputs/index.ts
index 558872aee..c702d7238 100644
--- a/packages/widgets/src/_inputs/index.ts
+++ b/packages/widgets/src/_inputs/index.ts
@@ -20,8 +20,6 @@ const mapping = {
app: WidgetAppInput,
} satisfies Record<WidgetOptionType, unknown>;
-export const getInputForType = <TType extends WidgetOptionType>(
- type: TType,
-) => {
+export const getInputForType = <TType extends WidgetOptionType>(type: TType) => {
return mapping[type];
};
diff --git a/packages/widgets/src/_inputs/widget-app-input.tsx b/packages/widgets/src/_inputs/widget-app-input.tsx
index 2ff70eb28..04a85d468 100644
--- a/packages/widgets/src/_inputs/widget-app-input.tsx
+++ b/packages/widgets/src/_inputs/widget-app-input.tsx
@@ -12,11 +12,7 @@ import type { CommonWidgetInputProps } from "./common";
import { useWidgetInputTranslation } from "./common";
import { useFormContext } from "./form";
-export const WidgetAppInput = ({
- property,
- kind,
- options,
-}: CommonWidgetInputProps<"app">) => {
+export const WidgetAppInput = ({ property, kind, options }: CommonWidgetInputProps<"app">) => {
const t = useWidgetInputTranslation(kind, property);
const form = useFormContext();
const { data: apps, isPending } = clientApi.app.selectable.useQuery();
@@ -31,9 +27,7 @@ export const WidgetAppInput = ({
label={t("label")}
searchable
limit={10}
- leftSection={
- <MemoizedLeftSection isPending={isPending} currentApp={currentApp} />
- }
+ leftSection={<MemoizedLeftSection isPending={isPending} currentApp={currentApp} />}
renderOption={renderSelectOption}
data={
apps?.map((app) => ({
@@ -55,18 +49,13 @@ const iconProps = {
size: 18,
};
-const renderSelectOption: SelectProps["renderOption"] = ({
- option,
- checked,
-}) => (
+const renderSelectOption: SelectProps["renderOption"] = ({ option, checked }) => (
<Group flex="1" gap="xs">
{"iconUrl" in option && typeof option.iconUrl === "string" ? (
<img width={20} height={20} src={option.iconUrl} alt={option.label} />
) : null}
{option.label}
- {checked && (
- <IconCheck style={{ marginInlineStart: "auto" }} {...iconProps} />
- )}
+ {checked && <IconCheck style={{ marginInlineStart: "auto" }} {...iconProps} />}
</Group>
);
@@ -82,14 +71,7 @@ const LeftSection = ({ isPending, currentApp }: LeftSectionProps) => {
}
if (currentApp) {
- return (
- <img
- width={size}
- height={size}
- src={currentApp.iconUrl}
- alt={currentApp.name}
- />
- );
+ return <img width={size} height={size} src={currentApp.iconUrl} alt={currentApp.name} />;
}
return null;
diff --git a/packages/widgets/src/_inputs/widget-location-input.tsx b/packages/widgets/src/_inputs/widget-location-input.tsx
index 9b035c515..baa6aca42 100644
--- a/packages/widgets/src/_inputs/widget-location-input.tsx
+++ b/packages/widgets/src/_inputs/widget-location-input.tsx
@@ -28,10 +28,7 @@ import type { CommonWidgetInputProps } from "./common";
import { useWidgetInputTranslation } from "./common";
import { useFormContext } from "./form";
-export const WidgetLocationInput = ({
- property,
- kind,
-}: CommonWidgetInputProps<"location">) => {
+export const WidgetLocationInput = ({ property, kind }: CommonWidgetInputProps<"location">) => {
const t = useWidgetInputTranslation(kind, property);
const tLocation = useScopedI18n("widget.common.location");
const form = useFormContext();
@@ -39,8 +36,7 @@ export const WidgetLocationInput = ({
const value = form.values.options[property] as OptionLocation;
const selectionEnabled = value.name.length > 1;
- const handleChange = form.getInputProps(`options.${property}`)
- .onChange as LocationOnChange;
+ const handleChange = form.getInputProps(`options.${property}`).onChange as LocationOnChange;
const unknownLocation = tLocation("unknownLocation");
const onQueryChange = useCallback((event: ChangeEvent<HTMLInputElement>) => {
@@ -95,16 +91,8 @@ export const WidgetLocationInput = ({
<Fieldset legend={t("label")}>
<Stack gap="xs">
<Group wrap="nowrap" align="end">
- <TextInput
- w="100%"
- label={tLocation("query")}
- value={value.name}
- onChange={onQueryChange}
- />
- <Tooltip
- hidden={selectionEnabled}
- label={tLocation("disabledTooltip")}
- >
+ <TextInput w="100%" label={tLocation("query")} value={value.name} onChange={onQueryChange} />
+ <Tooltip hidden={selectionEnabled} label={tLocation("disabledTooltip")}>
<div>
<Button
disabled={!selectionEnabled}
@@ -151,61 +139,57 @@ interface LocationSearchInnerProps {
onLocationSelect: (location: OptionLocation) => void;
}
-const LocationSearchModal = createModal<LocationSearchInnerProps>(
- ({ actions, innerProps }) => {
- const t = useScopedI18n("widget.common.location.table");
- const tCommon = useScopedI18n("common");
- const { data, isPending, error } = clientApi.location.searchCity.useQuery({
- query: innerProps.query,
- });
+const LocationSearchModal = createModal<LocationSearchInnerProps>(({ actions, innerProps }) => {
+ const t = useScopedI18n("widget.common.location.table");
+ const tCommon = useScopedI18n("common");
+ const { data, isPending, error } = clientApi.location.searchCity.useQuery({
+ query: innerProps.query,
+ });
- if (error) {
- throw error;
- }
+ if (error) {
+ throw error;
+ }
- return (
- <Stack>
- <Table striped>
- <Table.Thead>
+ return (
+ <Stack>
+ <Table striped>
+ <Table.Thead>
+ <Table.Tr>
+ <Table.Th style={{ width: "70%" }}>{t("header.city")}</Table.Th>
+ <Table.Th style={{ width: "50%" }}>{t("header.country")}</Table.Th>
+ <Table.Th>{t("header.coordinates")}</Table.Th>
+ <Table.Th>{t("header.population")}</Table.Th>
+ <Table.Th style={{ width: 40 }} />
+ </Table.Tr>
+ </Table.Thead>
+ <Table.Tbody>
+ {isPending && (
<Table.Tr>
- <Table.Th style={{ width: "70%" }}>{t("header.city")}</Table.Th>
- <Table.Th style={{ width: "50%" }}>
- {t("header.country")}
- </Table.Th>
- <Table.Th>{t("header.coordinates")}</Table.Th>
- <Table.Th>{t("header.population")}</Table.Th>
- <Table.Th style={{ width: 40 }} />
+ <Table.Td colSpan={5}>
+ <Group justify="center">
+ <Loader />
+ </Group>
+ </Table.Td>
</Table.Tr>
- </Table.Thead>
- <Table.Tbody>
- {isPending && (
- <Table.Tr>
- <Table.Td colSpan={5}>
- <Group justify="center">
- <Loader />
- </Group>
- </Table.Td>
- </Table.Tr>
- )}
- {data?.results.map((city) => (
- <LocationSelectTableRow
- key={city.id}
- city={city}
- onLocationSelect={innerProps.onLocationSelect}
- closeModal={actions.closeModal}
- />
- ))}
- </Table.Tbody>
- </Table>
- <Group justify="right">
- <Button variant="light" onClick={actions.closeModal}>
- {tCommon("action.cancel")}
- </Button>
- </Group>
- </Stack>
- );
- },
-).withOptions({
+ )}
+ {data?.results.map((city) => (
+ <LocationSelectTableRow
+ key={city.id}
+ city={city}
+ onLocationSelect={innerProps.onLocationSelect}
+ closeModal={actions.closeModal}
+ />
+ ))}
+ </Table.Tbody>
+ </Table>
+ <Group justify="right">
+ <Button variant="light" onClick={actions.closeModal}>
+ {tCommon("action.cancel")}
+ </Button>
+ </Group>
+ </Stack>
+ );
+}).withOptions({
defaultTitle(t) {
return t("widget.common.location.search");
},
@@ -218,11 +202,7 @@ interface LocationSearchTableRowProps {
closeModal: () => void;
}
-const LocationSelectTableRow = ({
- city,
- onLocationSelect,
- closeModal,
-}: LocationSearchTableRowProps) => {
+const LocationSelectTableRow = ({ city, onLocationSelect, closeModal }: LocationSearchTableRowProps) => {
const t = useScopedI18n("widget.common.location.table");
const onSelect = useCallback(() => {
onLocationSelect({
@@ -244,10 +224,7 @@ const LocationSelectTableRow = ({
<Text style={{ whiteSpace: "nowrap" }}>{city.country}</Text>
</Table.Td>
<Table.Td>
- <Anchor
- target="_blank"
- href={`https://www.google.com/maps/place/${city.latitude},${city.longitude}`}
- >
+ <Anchor target="_blank" href={`https://www.google.com/maps/place/${city.latitude},${city.longitude}`}>
<Text style={{ whiteSpace: "nowrap" }}>
{city.latitude}, {city.longitude}
</Text>
@@ -255,9 +232,7 @@ const LocationSelectTableRow = ({
</Table.Td>
<Table.Td>
{city.population ? (
- <Text style={{ whiteSpace: "nowrap" }}>
- {formatter.format(city.population)}
- </Text>
+ <Text style={{ whiteSpace: "nowrap" }}>{formatter.format(city.population)}</Text>
) : (
<Text c="gray"> {t("population.fallback")}</Text>
)}
diff --git a/packages/widgets/src/_inputs/widget-multiselect-input.tsx b/packages/widgets/src/_inputs/widget-multiselect-input.tsx
index 584c44117..282ae5c2f 100644
--- a/packages/widgets/src/_inputs/widget-multiselect-input.tsx
+++ b/packages/widgets/src/_inputs/widget-multiselect-input.tsx
@@ -7,11 +7,7 @@ import { useWidgetInputTranslation } from "./common";
import { useFormContext } from "./form";
import type { SelectOption } from "./widget-select-input";
-export const WidgetMultiSelectInput = ({
- property,
- kind,
- options,
-}: CommonWidgetInputProps<"multiSelect">) => {
+export const WidgetMultiSelectInput = ({ property, kind, options }: CommonWidgetInputProps<"multiSelect">) => {
const t = useWidgetInputTranslation(kind, property);
const form = useFormContext();
diff --git a/packages/widgets/src/_inputs/widget-number-input.tsx b/packages/widgets/src/_inputs/widget-number-input.tsx
index 116a0cc6b..929aae1a5 100644
--- a/packages/widgets/src/_inputs/widget-number-input.tsx
+++ b/packages/widgets/src/_inputs/widget-number-input.tsx
@@ -6,11 +6,7 @@ import type { CommonWidgetInputProps } from "./common";
import { useWidgetInputTranslation } from "./common";
import { useFormContext } from "./form";
-export const WidgetNumberInput = ({
- property,
- kind,
- options,
-}: CommonWidgetInputProps<"number">) => {
+export const WidgetNumberInput = ({ property, kind, options }: CommonWidgetInputProps<"number">) => {
const t = useWidgetInputTranslation(kind, property);
const form = useFormContext();
diff --git a/packages/widgets/src/_inputs/widget-select-input.tsx b/packages/widgets/src/_inputs/widget-select-input.tsx
index 721c1ef98..aa855dbf8 100644
--- a/packages/widgets/src/_inputs/widget-select-input.tsx
+++ b/packages/widgets/src/_inputs/widget-select-input.tsx
@@ -13,18 +13,13 @@ export type SelectOption =
}
| string;
-export type inferSelectOptionValue<TOption extends SelectOption> =
- TOption extends {
- value: infer TValue;
- }
- ? TValue
- : TOption;
+export type inferSelectOptionValue<TOption extends SelectOption> = TOption extends {
+ value: infer TValue;
+}
+ ? TValue
+ : TOption;
-export const WidgetSelectInput = ({
- property,
- kind,
- options,
-}: CommonWidgetInputProps<"select">) => {
+export const WidgetSelectInput = ({ property, kind, options }: CommonWidgetInputProps<"select">) => {
const t = useWidgetInputTranslation(kind, property);
const form = useFormContext();
diff --git a/packages/widgets/src/_inputs/widget-slider-input.tsx b/packages/widgets/src/_inputs/widget-slider-input.tsx
index 654f9d782..8689b2f2c 100644
--- a/packages/widgets/src/_inputs/widget-slider-input.tsx
+++ b/packages/widgets/src/_inputs/widget-slider-input.tsx
@@ -6,11 +6,7 @@ import type { CommonWidgetInputProps } from "./common";
import { useWidgetInputTranslation } from "./common";
import { useFormContext } from "./form";
-export const WidgetSliderInput = ({
- property,
- kind,
- options,
-}: CommonWidgetInputProps<"slider">) => {
+export const WidgetSliderInput = ({ property, kind, options }: CommonWidgetInputProps<"slider">) => {
const t = useWidgetInputTranslation(kind, property);
const form = useFormContext();
diff --git a/packages/widgets/src/_inputs/widget-switch-input.tsx b/packages/widgets/src/_inputs/widget-switch-input.tsx
index 369fd161d..66cbc0c67 100644
--- a/packages/widgets/src/_inputs/widget-switch-input.tsx
+++ b/packages/widgets/src/_inputs/widget-switch-input.tsx
@@ -6,11 +6,7 @@ import type { CommonWidgetInputProps } from "./common";
import { useWidgetInputTranslation } from "./common";
import { useFormContext } from "./form";
-export const WidgetSwitchInput = ({
- property,
- kind,
- options,
-}: CommonWidgetInputProps<"switch">) => {
+export const WidgetSwitchInput = ({ property, kind, options }: CommonWidgetInputProps<"switch">) => {
const t = useWidgetInputTranslation(kind, property);
const form = useFormContext();
diff --git a/packages/widgets/src/_inputs/widget-text-input.tsx b/packages/widgets/src/_inputs/widget-text-input.tsx
index 67f368a6f..bd6b43fdb 100644
--- a/packages/widgets/src/_inputs/widget-text-input.tsx
+++ b/packages/widgets/src/_inputs/widget-text-input.tsx
@@ -6,11 +6,7 @@ import type { CommonWidgetInputProps } from "./common";
import { useWidgetInputTranslation } from "./common";
import { useFormContext } from "./form";
-export const WidgetTextInput = ({
- property,
- kind,
- options,
-}: CommonWidgetInputProps<"text">) => {
+export const WidgetTextInput = ({ property, kind, options }: CommonWidgetInputProps<"text">) => {
const t = useWidgetInputTranslation(kind, property);
const form = useFormContext();
diff --git a/packages/widgets/src/app/component.tsx b/packages/widgets/src/app/component.tsx
index 896b66d40..85754a0cf 100644
--- a/packages/widgets/src/app/component.tsx
+++ b/packages/widgets/src/app/component.tsx
@@ -1,15 +1,7 @@
"use client";
import type { PropsWithChildren } from "react";
-import {
- Center,
- Flex,
- Loader,
- Stack,
- Text,
- Tooltip,
- UnstyledButton,
-} from "@mantine/core";
+import { Center, Flex, Loader, Stack, Text, Tooltip, UnstyledButton } from "@mantine/core";
import { IconDeviceDesktopX } from "@tabler/icons-react";
import { clientApi } from "@homarr/api/client";
@@ -19,13 +11,7 @@ import { useScopedI18n } from "@homarr/translation/client";
import type { WidgetComponentProps } from "../definition";
import classes from "./app.module.css";
-export default function AppWidget({
- options,
- serverData,
- isEditMode,
- width,
- height,
-}: WidgetComponentProps<"app">) {
+export default function AppWidget({ options, serverData, isEditMode, width, height }: WidgetComponentProps<"app">) {
const t = useScopedI18n("widget.app");
const isQueryEnabled = Boolean(options.appId);
const {
@@ -90,11 +76,7 @@ export default function AppWidget({
}
return (
- <AppLink
- href={app?.href ?? ""}
- openInNewTab={options.openInNewTab}
- enabled={Boolean(app?.href) && !isEditMode}
- >
+ <AppLink href={app?.href ?? ""} openInNewTab={options.openInNewTab} enabled={Boolean(app?.href) && !isEditMode}>
<Flex align="center" justify="center" h="100%">
<Tooltip.Floating
label={app?.description}
@@ -118,11 +100,7 @@ export default function AppWidget({
{app?.name}
</Text>
)}
- <img
- src={app?.iconUrl}
- alt={app?.name}
- className={classes.appIcon}
- />
+ <img src={app?.iconUrl} alt={app?.name} className={classes.appIcon} />
</Flex>
</Tooltip.Floating>
</Flex>
@@ -136,20 +114,9 @@ interface AppLinkProps {
enabled: boolean;
}
-const AppLink = ({
- href,
- openInNewTab,
- enabled,
- children,
-}: PropsWithChildren<AppLinkProps>) =>
+const AppLink = ({ href, openInNewTab, enabled, children }: PropsWithChildren<AppLinkProps>) =>
enabled ? (
- <UnstyledButton
- component="a"
- href={href}
- target={openInNewTab ? "_blank" : undefined}
- h="100%"
- w="100%"
- >
+ <UnstyledButton component="a" href={href} target={openInNewTab ? "_blank" : undefined} h="100%" w="100%">
{children}
</UnstyledButton>
) : (
diff --git a/packages/widgets/src/app/index.ts b/packages/widgets/src/app/index.ts
index f6e2d7026..4eb1d5440 100644
--- a/packages/widgets/src/app/index.ts
+++ b/packages/widgets/src/app/index.ts
@@ -3,14 +3,13 @@ import { IconApps } from "@tabler/icons-react";
import { createWidgetDefinition } from "../definition";
import { optionsBuilder } from "../options";
-export const { definition, componentLoader, serverDataLoader } =
- createWidgetDefinition("app", {
- icon: IconApps,
- options: optionsBuilder.from((factory) => ({
- appId: factory.app(),
- openInNewTab: factory.switch({ defaultValue: true }),
- showDescriptionTooltip: factory.switch({ defaultValue: false }),
- })),
- })
- .withServerData(() => import("./serverData"))
- .withDynamicImport(() => import("./component"));
+export const { definition, componentLoader, serverDataLoader } = createWidgetDefinition("app", {
+ icon: IconApps,
+ options: optionsBuilder.from((factory) => ({
+ appId: factory.app(),
+ openInNewTab: factory.switch({ defaultValue: true }),
+ showDescriptionTooltip: factory.switch({ defaultValue: false }),
+ })),
+})
+ .withServerData(() => import("./serverData"))
+ .withDynamicImport(() => import("./component"));
diff --git a/packages/widgets/src/app/serverData.ts b/packages/widgets/src/app/serverData.ts
index 730d449a5..a6df69678 100644
--- a/packages/widgets/src/app/serverData.ts
+++ b/packages/widgets/src/app/serverData.ts
@@ -4,9 +4,7 @@ import { api } from "@homarr/api/server";
import type { WidgetProps } from "../definition";
-export default async function getServerDataAsync({
- options,
-}: WidgetProps<"app">) {
+export default async function getServerDataAsync({ options }: WidgetProps<"app">) {
try {
const app = await api.app.byId({ id: options.appId });
return { app };
diff --git a/packages/widgets/src/clock/component.tsx b/packages/widgets/src/clock/component.tsx
index 466a3fb9b..ce3969714 100644
--- a/packages/widgets/src/clock/component.tsx
+++ b/packages/widgets/src/clock/component.tsx
@@ -13,37 +13,19 @@ dayjs.extend(advancedFormat);
dayjs.extend(utc);
dayjs.extend(timezones);
-export default function ClockWidget({
- options,
-}: WidgetComponentProps<"clock">) {
+export default function ClockWidget({ options }: WidgetComponentProps<"clock">) {
const secondsFormat = options.showSeconds ? ":ss" : "";
- const timeFormat = options.is24HourFormat
- ? `HH:mm${secondsFormat}`
- : `h:mm${secondsFormat} A`;
+ const timeFormat = options.is24HourFormat ? `HH:mm${secondsFormat}` : `h:mm${secondsFormat} A`;
const dateFormat = options.dateFormat;
- const timezone = options.useCustomTimezone
- ? options.timezone
- : Intl.DateTimeFormat().resolvedOptions().timeZone;
+ const timezone = options.useCustomTimezone ? options.timezone : Intl.DateTimeFormat().resolvedOptions().timeZone;
const time = useCurrentTime(options);
return (
- <Flex
- classNames={{ root: "clock-wrapper" }}
- align="center"
- justify="center"
- h="100%"
- >
+ <Flex classNames={{ root: "clock-wrapper" }} align="center" justify="center" h="100%">
<Stack classNames={{ root: "clock-text-stack" }} align="center" gap="xs">
{options.customTitleToggle && (
- <Text classNames={{ root: "clock-customTitle-text" }}>
- {options.customTitle}
- </Text>
+ <Text classNames={{ root: "clock-customTitle-text" }}>{options.customTitle}</Text>
)}
- <Text
- classNames={{ root: "clock-time-text" }}
- fw={700}
- size="2.125rem"
- lh="1"
- >
+ <Text classNames={{ root: "clock-time-text" }} fw={700} size="2.125rem" lh="1">
{dayjs(time).tz(timezone).format(timeFormat)}
</Text>
{options.showDate && (
@@ -64,10 +46,7 @@ const useCurrentTime = ({ showSeconds }: UseCurrentTimeProps) => {
const [time, setTime] = useState(new Date());
const timeoutRef = useRef<NodeJS.Timeout>();
const intervalRef = useRef<NodeJS.Timeout>();
- const intervalMultiplier = useMemo(
- () => (showSeconds ? 1 : 60),
- [showSeconds],
- );
+ const intervalMultiplier = useMemo(() => (showSeconds ? 1 : 60), [showSeconds]);
useEffect(() => {
setTime(new Date());
@@ -79,8 +58,7 @@ const useCurrentTime = ({ showSeconds }: UseCurrentTimeProps) => {
setTime(new Date());
}, intervalMultiplier * 1000);
},
- intervalMultiplier * 1000 -
- (1000 * (showSeconds ? 0 : dayjs().second()) + dayjs().millisecond()),
+ intervalMultiplier * 1000 - (1000 * (showSeconds ? 0 : dayjs().second()) + dayjs().millisecond()),
);
return () => {
diff --git a/packages/widgets/src/definition.ts b/packages/widgets/src/definition.ts
index 88732a102..d134f185d 100644
--- a/packages/widgets/src/definition.ts
+++ b/packages/widgets/src/definition.ts
@@ -4,10 +4,7 @@ import type { IntegrationKind, WidgetKind } from "@homarr/definitions";
import type { TablerIcon } from "@homarr/ui";
import type { WidgetImports } from ".";
-import type {
- inferOptionsFromDefinition,
- WidgetOptionsRecord,
-} from "./options";
+import type { inferOptionsFromDefinition, WidgetOptionsRecord } from "./options";
import type { IntegrationSelectOption } from "./widget-integration-select";
type ServerDataLoader<TKind extends WidgetKind> = () => Promise<{
@@ -29,9 +26,7 @@ const createWithDynamicImport =
WidgetComponentProps<TKind> &
(TServerDataLoader extends ServerDataLoader<TKind>
? {
- serverData: Awaited<
- ReturnType<Awaited<ReturnType<TServerDataLoader>>["default"]>
- >;
+ serverData: Awaited<ReturnType<Awaited<ReturnType<TServerDataLoader>>["default"]>>;
}
: never)
>,
@@ -46,30 +41,18 @@ const createWithDynamicImport =
});
const createWithServerData =
- <TKind extends WidgetKind, TDefinition extends WidgetDefinition>(
- kind: TKind,
- definition: TDefinition,
- ) =>
- <TServerDataLoader extends ServerDataLoader<TKind>>(
- serverDataLoader: TServerDataLoader,
- ) => ({
+ <TKind extends WidgetKind, TDefinition extends WidgetDefinition>(kind: TKind, definition: TDefinition) =>
+ <TServerDataLoader extends ServerDataLoader<TKind>>(serverDataLoader: TServerDataLoader) => ({
definition: {
...definition,
kind,
},
kind,
serverDataLoader,
- withDynamicImport: createWithDynamicImport(
- kind,
- definition,
- serverDataLoader,
- ),
+ withDynamicImport: createWithDynamicImport(kind, definition, serverDataLoader),
});
-export const createWidgetDefinition = <
- TKind extends WidgetKind,
- TDefinition extends WidgetDefinition,
->(
+export const createWidgetDefinition = <TKind extends WidgetKind, TDefinition extends WidgetDefinition>(
kind: TKind,
definition: TDefinition,
) => ({
@@ -85,41 +68,32 @@ export interface WidgetDefinition {
export interface WidgetProps<TKind extends WidgetKind> {
options: inferOptionsFromDefinition<WidgetOptionsRecordOf<TKind>>;
- integrations: inferIntegrationsFromDefinition<
- WidgetImports[TKind]["definition"]
- >;
+ integrations: inferIntegrationsFromDefinition<WidgetImports[TKind]["definition"]>;
}
-type inferServerDataForKind<TKind extends WidgetKind> =
- WidgetImports[TKind] extends { serverDataLoader: ServerDataLoader<TKind> }
- ? Awaited<
- ReturnType<
- Awaited<
- ReturnType<WidgetImports[TKind]["serverDataLoader"]>
- >["default"]
- >
- >
- : undefined;
+type inferServerDataForKind<TKind extends WidgetKind> = WidgetImports[TKind] extends {
+ serverDataLoader: ServerDataLoader<TKind>;
+}
+ ? Awaited<ReturnType<Awaited<ReturnType<WidgetImports[TKind]["serverDataLoader"]>>["default"]>>
+ : undefined;
-export type WidgetComponentProps<TKind extends WidgetKind> =
- WidgetProps<TKind> & {
- serverData?: inferServerDataForKind<TKind>;
- } & {
- itemId: string | undefined; // undefined when in preview mode
- boardId: string | undefined; // undefined when in preview mode
- isEditMode: boolean;
- width: number;
- height: number;
- };
+export type WidgetComponentProps<TKind extends WidgetKind> = WidgetProps<TKind> & {
+ serverData?: inferServerDataForKind<TKind>;
+} & {
+ itemId: string | undefined; // undefined when in preview mode
+ boardId: string | undefined; // undefined when in preview mode
+ isEditMode: boolean;
+ width: number;
+ height: number;
+};
-type inferIntegrationsFromDefinition<TDefinition extends WidgetDefinition> =
- TDefinition extends {
- supportedIntegrations: infer TSupportedIntegrations;
- } // check if definition has supportedIntegrations
- ? TSupportedIntegrations extends IntegrationKind[] // check if supportedIntegrations is an array of IntegrationKind
- ? IntegrationSelectOptionFor<TSupportedIntegrations[number]>[] // if so, return an array of IntegrationSelectOptionFor
- : IntegrationSelectOption[] // otherwise, return an array of IntegrationSelectOption without specifying the kind
- : IntegrationSelectOption[];
+type inferIntegrationsFromDefinition<TDefinition extends WidgetDefinition> = TDefinition extends {
+ supportedIntegrations: infer TSupportedIntegrations;
+} // check if definition has supportedIntegrations
+ ? TSupportedIntegrations extends IntegrationKind[] // check if supportedIntegrations is an array of IntegrationKind
+ ? IntegrationSelectOptionFor<TSupportedIntegrations[number]>[] // if so, return an array of IntegrationSelectOptionFor
+ : IntegrationSelectOption[] // otherwise, return an array of IntegrationSelectOption without specifying the kind
+ : IntegrationSelectOption[];
interface IntegrationSelectOptionFor<TIntegration extends IntegrationKind> {
id: string;
@@ -128,5 +102,4 @@ interface IntegrationSelectOptionFor<TIntegration extends IntegrationKind> {
kind: TIntegration[number];
}
-export type WidgetOptionsRecordOf<TKind extends WidgetKind> =
- WidgetImports[TKind]["definition"]["options"];
+export type WidgetOptionsRecordOf<TKind extends WidgetKind> = WidgetImports[TKind]["definition"]["options"];
diff --git a/packages/widgets/src/iframe/component.tsx b/packages/widgets/src/iframe/component.tsx
index 31205fb8d..a4a2ffd55 100644
--- a/packages/widgets/src/iframe/component.tsx
+++ b/packages/widgets/src/iframe/component.tsx
@@ -7,9 +7,7 @@ import { useI18n } from "@homarr/translation/client";
import type { WidgetComponentProps } from "../definition";
import classes from "./component.module.css";
-export default function IFrameWidget({
- options,
-}: WidgetComponentProps<"iframe">) {
+export default function IFrameWidget({ options }: WidgetComponentProps<"iframe">) {
const t = useI18n();
const { embedUrl, ...permissions } = options;
const allowedPermissions = getAllowedPermissions(permissions);
@@ -18,12 +16,7 @@ export default function IFrameWidget({
return (
<Box h="100%" w="100%">
- <iframe
- className={classes.iframe}
- src={embedUrl}
- title="widget iframe"
- allow={allowedPermissions.join(" ")}
- >
+ <iframe className={classes.iframe} src={embedUrl} title="widget iframe" allow={allowedPermissions.join(" ")}>
<Text>{t("widget.iframe.error.noBrowerSupport")}</Text>
</iframe>
</Box>
@@ -41,9 +34,7 @@ const NoUrl = () => {
);
};
-const getAllowedPermissions = (
- permissions: Omit<WidgetComponentProps<"iframe">["options"], "embedUrl">,
-) => {
+const getAllowedPermissions = (permissions: Omit<WidgetComponentProps<"iframe">["options"], "embedUrl">) => {
return objectEntries(permissions)
.filter(([_key, value]) => value)
.map(([key]) => permissionMapping[key]);
@@ -58,7 +49,4 @@ const permissionMapping = {
allowPayment: "payment",
allowScrolling: "scrolling",
allowTransparency: "transparency",
-} satisfies Record<
- keyof Omit<WidgetComponentProps<"iframe">["options"], "embedUrl">,
- string
->;
+} satisfies Record<keyof Omit<WidgetComponentProps<"iframe">["options"], "embedUrl">, string>;
diff --git a/packages/widgets/src/iframe/index.ts b/packages/widgets/src/iframe/index.ts
index 5da19beeb..97b277ff8 100644
--- a/packages/widgets/src/iframe/index.ts
+++ b/packages/widgets/src/iframe/index.ts
@@ -3,22 +3,19 @@ import { IconBrowser } from "@tabler/icons-react";
import { createWidgetDefinition } from "../definition";
import { optionsBuilder } from "../options";
-export const { definition, componentLoader } = createWidgetDefinition(
- "iframe",
- {
- icon: IconBrowser,
- options: optionsBuilder.from((factory) => ({
- embedUrl: factory.text(),
- allowFullScreen: factory.switch(),
- allowScrolling: factory.switch({
- defaultValue: true,
- }),
- allowTransparency: factory.switch(),
- allowPayment: factory.switch(),
- allowAutoPlay: factory.switch(),
- allowMicrophone: factory.switch(),
- allowCamera: factory.switch(),
- allowGeolocation: factory.switch(),
- })),
- },
-).withDynamicImport(() => import("./component"));
+export const { definition, componentLoader } = createWidgetDefinition("iframe", {
+ icon: IconBrowser,
+ options: optionsBuilder.from((factory) => ({
+ embedUrl: factory.text(),
+ allowFullScreen: factory.switch(),
+ allowScrolling: factory.switch({
+ defaultValue: true,
+ }),
+ allowTransparency: factory.switch(),
+ allowPayment: factory.switch(),
+ allowAutoPlay: factory.switch(),
+ allowMicrophone: factory.switch(),
+ allowCamera: factory.switch(),
+ allowGeolocation: factory.switch(),
+ })),
+}).withDynamicImport(() => import("./component"));
diff --git a/packages/widgets/src/index.tsx b/packages/widgets/src/index.tsx
index 93d106117..7ea2d7e7a 100644
--- a/packages/widgets/src/index.tsx
+++ b/packages/widgets/src/index.tsx
@@ -32,10 +32,7 @@ export const widgetImports = {
export type WidgetImports = typeof widgetImports;
export type WidgetImportKey = keyof WidgetImports;
-const loadedComponents = new Map<
- WidgetKind,
- ComponentType<WidgetComponentProps<WidgetKind>>
->();
+const loadedComponents = new Map<WidgetKind, ComponentType<WidgetComponentProps<WidgetKind>>>();
export const loadWidgetDynamic = <TKind extends WidgetKind>(kind: TKind) => {
const existingComponent = loadedComponents.get(kind);
diff --git a/packages/widgets/src/modals/widget-edit-modal.tsx b/packages/widgets/src/modals/widget-edit-modal.tsx
index 06b72e20a..51531ccbd 100644
--- a/packages/widgets/src/modals/widget-edit-modal.tsx
+++ b/packages/widgets/src/modals/widget-edit-modal.tsx
@@ -27,69 +27,51 @@ interface ModalProps<TSort extends WidgetKind> {
integrationSupport: boolean;
}
-export const WidgetEditModal = createModal<ModalProps<WidgetKind>>(
- ({ actions, innerProps }) => {
- const t = useI18n();
- const form = useForm({
- initialValues: innerProps.value,
- });
+export const WidgetEditModal = createModal<ModalProps<WidgetKind>>(({ actions, innerProps }) => {
+ const t = useI18n();
+ const form = useForm({
+ initialValues: innerProps.value,
+ });
- const { definition } = widgetImports[innerProps.kind];
+ const { definition } = widgetImports[innerProps.kind];
- return (
- <form
- onSubmit={form.onSubmit((values) => {
- innerProps.onSuccessfulEdit(values);
- actions.closeModal();
- })}
- >
- <FormProvider form={form}>
- <Stack>
- {innerProps.integrationSupport && (
- <WidgetIntegrationSelect
- label={t("item.edit.field.integrations.label")}
- data={innerProps.integrationData}
- {...form.getInputProps("integrations")}
- />
- )}
- {Object.entries(definition.options).map(
- ([key, value]: [string, OptionsBuilderResult[string]]) => {
- const Input = getInputForType(value.type);
+ return (
+ <form
+ onSubmit={form.onSubmit((values) => {
+ innerProps.onSuccessfulEdit(values);
+ actions.closeModal();
+ })}
+ >
+ <FormProvider form={form}>
+ <Stack>
+ {innerProps.integrationSupport && (
+ <WidgetIntegrationSelect
+ label={t("item.edit.field.integrations.label")}
+ data={innerProps.integrationData}
+ {...form.getInputProps("integrations")}
+ />
+ )}
+ {Object.entries(definition.options).map(([key, value]: [string, OptionsBuilderResult[string]]) => {
+ const Input = getInputForType(value.type);
- if (
- !Input ||
- value.shouldHide?.(form.values.options as never)
- ) {
- return null;
- }
+ if (!Input || value.shouldHide?.(form.values.options as never)) {
+ return null;
+ }
- return (
- <Input
- key={key}
- kind={innerProps.kind}
- property={key}
- options={value as never}
- />
- );
- },
- )}
- <Group justify="right">
- <Button
- onClick={actions.closeModal}
- variant="subtle"
- color="gray"
- >
- {t("common.action.cancel")}
- </Button>
- <Button type="submit" color="teal">
- {t("common.action.saveChanges")}
- </Button>
- </Group>
- </Stack>
- </FormProvider>
- </form>
- );
- },
-).withOptions({
+ return <Input key={key} kind={innerProps.kind} property={key} options={value as never} />;
+ })}
+ <Group justify="right">
+ <Button onClick={actions.closeModal} variant="subtle" color="gray">
+ {t("common.action.cancel")}
+ </Button>
+ <Button type="submit" color="teal">
+ {t("common.action.saveChanges")}
+ </Button>
+ </Group>
+ </Stack>
+ </FormProvider>
+ </form>
+ );
+}).withOptions({
keepMounted: true,
});
diff --git a/packages/widgets/src/notebook/component.tsx b/packages/widgets/src/notebook/component.tsx
index 45c230a75..5231e1db9 100644
--- a/packages/widgets/src/notebook/component.tsx
+++ b/packages/widgets/src/notebook/component.tsx
@@ -4,15 +4,10 @@ import "@mantine/tiptap/styles.css";
import type { WidgetComponentProps } from "../definition";
-const Notebook = dynamic(
- () => import("./notebook").then((module) => module.Notebook),
- {
- ssr: false,
- },
-);
+const Notebook = dynamic(() => import("./notebook").then((module) => module.Notebook), {
+ ssr: false,
+});
-export default function NotebookWidget(
- props: WidgetComponentProps<"notebook">,
-) {
+export default function NotebookWidget(props: WidgetComponentProps<"notebook">) {
return <Notebook {...props} />;
}
diff --git a/packages/widgets/src/notebook/index.ts b/packages/widgets/src/notebook/index.ts
index 36ef69660..5258ee78d 100644
--- a/packages/widgets/src/notebook/index.ts
+++ b/packages/widgets/src/notebook/index.ts
@@ -4,27 +4,24 @@ import { createWidgetDefinition } from "../definition";
import { optionsBuilder } from "../options";
import { defaultContent } from "./default-content";
-export const { definition, componentLoader } = createWidgetDefinition(
- "notebook",
- {
- icon: IconNotes,
- options: optionsBuilder.from(
- (factory) => ({
- showToolbar: factory.switch({
- defaultValue: true,
- }),
- allowReadOnlyCheck: factory.switch({
- defaultValue: true,
- }),
- content: factory.text({
- defaultValue: defaultContent,
- }),
+export const { definition, componentLoader } = createWidgetDefinition("notebook", {
+ icon: IconNotes,
+ options: optionsBuilder.from(
+ (factory) => ({
+ showToolbar: factory.switch({
+ defaultValue: true,
}),
- {
- content: {
- shouldHide: () => true, // Hide the content option as it can be modified in the editor
- },
+ allowReadOnlyCheck: factory.switch({
+ defaultValue: true,
+ }),
+ content: factory.text({
+ defaultValue: defaultContent,
+ }),
+ }),
+ {
+ content: {
+ shouldHide: () => true, // Hide the content option as it can be modified in the editor
},
- ),
- },
-).withDynamicImport(() => import("./component"));
+ },
+ ),
+}).withDynamicImport(() => import("./component"));
diff --git a/packages/widgets/src/notebook/notebook.tsx b/packages/widgets/src/notebook/notebook.tsx
index 7e056e4aa..e7967d81f 100644
--- a/packages/widgets/src/notebook/notebook.tsx
+++ b/packages/widgets/src/notebook/notebook.tsx
@@ -16,11 +16,7 @@ import {
useMantineTheme,
} from "@mantine/core";
import { useDisclosure } from "@mantine/hooks";
-import {
- Link,
- RichTextEditor,
- useRichTextEditorContext,
-} from "@mantine/tiptap";
+import { Link, RichTextEditor, useRichTextEditorContext } from "@mantine/tiptap";
import {
IconCheck,
IconCircleOff,
@@ -78,12 +74,7 @@ const controlIconProps = {
stroke: 1.5,
};
-export function Notebook({
- options,
- isEditMode,
- boardId,
- itemId,
-}: WidgetComponentProps<"notebook">) {
+export function Notebook({ options, isEditMode, boardId, itemId }: WidgetComponentProps<"notebook">) {
const [content, setContent] = useState(options.content);
const [toSaveContent, setToSaveContent] = useState(content);
@@ -137,12 +128,9 @@ export function Notebook({
backgroundColor: {
default: undefined,
renderHTML: (attributes) => ({
- style: attributes.backgroundColor
- ? `background-color: ${attributes.backgroundColor}`
- : undefined,
+ style: attributes.backgroundColor ? `background-color: ${attributes.backgroundColor}` : undefined,
}),
- parseHTML: (element) =>
- element.style.backgroundColor || undefined,
+ parseHTML: (element) => element.style.backgroundColor || undefined,
},
};
},
@@ -178,9 +166,7 @@ export function Notebook({
[toSaveContent],
);
- const handleOnReadOnlyCheck = (
- event: CustomEventInit<{ node: Node; checked: boolean }>,
- ) => {
+ const handleOnReadOnlyCheck = (event: CustomEventInit<{ node: Node; checked: boolean }>) => {
if (!options.allowReadOnlyCheck) return;
if (!editor) return;
@@ -251,8 +237,7 @@ export function Notebook({
"& .ProseMirror": {
padding: "0 !important",
},
- backgroundColor:
- colorScheme === "dark" ? theme.colors.dark[6] : "white",
+ backgroundColor: colorScheme === "dark" ? theme.colors.dark[6] : "white",
border: "none",
borderRadius: "0.5rem",
display: "flex",
@@ -270,8 +255,7 @@ export function Notebook({
>
<RichTextEditor.Toolbar
style={{
- display:
- isEditing && options.showToolbar === true ? "flex" : "none",
+ display: isEditing && options.showToolbar === true ? "flex" : "none",
}}
>
<RichTextEditor.ControlsGroup>
@@ -319,9 +303,7 @@ export function Notebook({
<RichTextEditor.BulletList title={tControls("bulletList")} />
<RichTextEditor.OrderedList title={tControls("orderedList")} />
<TaskListToggle />
- {(editor?.isActive("taskList") ||
- editor?.isActive("bulletList") ||
- editor?.isActive("orderedList")) && (
+ {(editor?.isActive("taskList") || editor?.isActive("bulletList") || editor?.isActive("orderedList")) && (
<>
<ListIndentIncrease />
<ListIndentDecrease />
@@ -368,9 +350,7 @@ export function Notebook({
{enabled && (
<>
<ActionIcon
- title={
- isEditing ? t("common.action.save") : t("common.action.edit")
- }
+ title={isEditing ? t("common.action.save") : t("common.action.edit")}
style={{
zIndex: 1,
}}
@@ -383,11 +363,7 @@ export function Notebook({
radius={"md"}
onClick={handleEditToggle}
>
- {isEditing ? (
- <IconDeviceFloppy {...iconProps} />
- ) : (
- <IconEdit {...iconProps} />
- )}
+ {isEditing ? <IconDeviceFloppy {...iconProps} /> : <IconEdit {...iconProps} />}
</ActionIcon>
{isEditing && (
<ActionIcon
@@ -482,9 +458,7 @@ function ColorCellControl() {
const { editor } = useRichTextEditorContext();
const getCurrent = useCallback(() => {
- return editor?.getAttributes("tableCell").backgroundColor as
- | string
- | undefined;
+ return editor?.getAttributes("tableCell").backgroundColor as string | undefined;
}, [editor]);
const update = useCallback(
@@ -513,13 +487,7 @@ interface ColorControlProps {
ariaLabel: string;
}
-const ColorControl = ({
- defaultColor,
- getCurrent,
- update,
- icon: Icon,
- ariaLabel,
-}: ColorControlProps) => {
+const ColorControl = ({ defaultColor, getCurrent, update, icon: Icon, ariaLabel }: ColorControlProps) => {
const { editor } = useRichTextEditorContext();
const [color, setColor] = useState(defaultColor);
const { colors, white } = useMantineTheme();
@@ -591,33 +559,15 @@ const ColorControl = ({
</Popover.Target>
<Popover.Dropdown>
<Stack gap={8}>
- <ColorPicker
- value={color}
- onChange={setColor}
- format="hexa"
- swatches={palette}
- swatchesPerRow={6}
- />
+ <ColorPicker value={color} onChange={setColor} format="hexa" swatches={palette} swatchesPerRow={6} />
<Group justify="right" gap={8}>
- <ActionIcon
- title={t("common.action.cancel")}
- variant="default"
- onClick={close}
- >
+ <ActionIcon title={t("common.action.cancel")} variant="default" onClick={close}>
<IconX stroke={1.5} size="1rem" />
</ActionIcon>
- <ActionIcon
- title={t("common.action.apply")}
- variant="default"
- onClick={handleApplyColor}
- >
+ <ActionIcon title={t("common.action.apply")} variant="default" onClick={handleApplyColor}>
<IconCheck stroke={1.5} size="1rem" />
</ActionIcon>
- <ActionIcon
- title={t("widget.notebook.popover.clearColor")}
- variant="default"
- onClick={handleClearColor}
- >
+ <ActionIcon title={t("widget.notebook.popover.clearColor")} variant="default" onClick={handleClearColor}>
<IconCircleOff stroke={1.5} size="1rem" />
</ActionIcon>
</Group>
@@ -676,11 +626,7 @@ function EmbedImage() {
trapFocus
>
<Popover.Target>
- <RichTextEditor.Control
- onClick={toggle}
- title={tControls("image")}
- active={editor?.isActive("image")}
- >
+ <RichTextEditor.Control onClick={toggle} title={tControls("image")} active={editor?.isActive("image")}>
<IconPhoto stroke={1.5} size="1rem" />
</RichTextEditor.Control>
</Popover.Target>
@@ -777,11 +723,7 @@ const handleAddColumnBefore = (editor: Editor) => {
};
const TableAddColumnBefore = () => (
- <TableControl
- title="addColumnLeft"
- onClick={handleAddColumnBefore}
- icon={IconColumnInsertLeft}
- />
+ <TableControl title="addColumnLeft" onClick={handleAddColumnBefore} icon={IconColumnInsertLeft} />
);
const handleAddColumnAfter = (editor: Editor) => {
@@ -789,11 +731,7 @@ const handleAddColumnAfter = (editor: Editor) => {
};
const TableAddColumnAfter = () => (
- <TableControl
- title="addColumnRight"
- onClick={handleAddColumnAfter}
- icon={IconColumnInsertRight}
- />
+ <TableControl title="addColumnRight" onClick={handleAddColumnAfter} icon={IconColumnInsertRight} />
);
const handleRemoveColumn = (editor: Editor) => {
@@ -801,54 +739,31 @@ const handleRemoveColumn = (editor: Editor) => {
};
const TableRemoveColumn = () => (
- <TableControl
- title="deleteColumn"
- onClick={handleRemoveColumn}
- icon={IconColumnRemove}
- />
+ <TableControl title="deleteColumn" onClick={handleRemoveColumn} icon={IconColumnRemove} />
);
const handleAddRowBefore = (editor: Editor) => {
editor.commands.addRowBefore();
};
-const TableAddRowBefore = () => (
- <TableControl
- title="addRowTop"
- onClick={handleAddRowBefore}
- icon={IconRowInsertTop}
- />
-);
+const TableAddRowBefore = () => <TableControl title="addRowTop" onClick={handleAddRowBefore} icon={IconRowInsertTop} />;
const handleAddRowAfter = (editor: Editor) => {
editor.commands.addRowAfter();
};
const TableAddRowAfter = () => (
- <TableControl
- title="addRowBelow"
- onClick={handleAddRowAfter}
- icon={IconRowInsertBottom}
- />
+ <TableControl title="addRowBelow" onClick={handleAddRowAfter} icon={IconRowInsertBottom} />
);
const handleRemoveRow = (editor: Editor) => {
editor.commands.deleteRow();
};
-const TableRemoveRow = () => (
- <TableControl
- title="deleteRow"
- onClick={handleRemoveRow}
- icon={IconRowRemove}
- />
-);
+const TableRemoveRow = () => <TableControl title="deleteRow" onClick={handleRemoveRow} icon={IconRowRemove} />;
interface TableControlProps {
- title: Exclude<
- keyof TranslationObject["widget"]["notebook"]["controls"],
- "align" | "heading"
- >;
+ title: Exclude<keyof TranslationObject["widget"]["notebook"]["controls"], "align" | "heading">;
onClick: (editor: Editor) => void;
icon: TablerIcon;
}
@@ -862,10 +777,7 @@ const TableControl = ({ title, onClick, icon: Icon }: TableControlProps) => {
}, [editor, onClick]);
return (
- <RichTextEditor.Control
- title={tControls(title)}
- onClick={handleControlClick}
- >
+ <RichTextEditor.Control title={tControls(title)} onClick={handleControlClick}>
<Icon {...controlIconProps} />
</RichTextEditor.Control>
);
@@ -958,26 +870,14 @@ function TableToggle() {
active={isActive}
onClick={handleControlClick}
>
- {isActive ? (
- <IconTableOff stroke={1.5} size="1rem" />
- ) : (
- <IconTablePlus stroke={1.5} size="1rem" />
- )}
+ {isActive ? <IconTableOff stroke={1.5} size="1rem" /> : <IconTablePlus stroke={1.5} size="1rem" />}
</RichTextEditor.Control>
</Popover.Target>
<Popover.Dropdown>
<form onSubmit={form.onSubmit(handleSubmit)}>
<Stack gap={5}>
- <NumberInput
- label={t("widget.notebook.popover.columns")}
- min={1}
- {...form.getInputProps("cols")}
- />
- <NumberInput
- label={t("widget.notebook.popover.rows")}
- min={1}
- {...form.getInputProps("rows")}
- />
+ <NumberInput label={t("widget.notebook.popover.columns")} min={1} {...form.getInputProps("cols")} />
+ <NumberInput label={t("widget.notebook.popover.rows")} min={1} {...form.getInputProps("rows")} />
<Button type="submit" variant="default" mt={10} mb={5}>
{t("common.action.insert")}
</Button>
diff --git a/packages/widgets/src/options.ts b/packages/widgets/src/options.ts
index 4a3c89048..4d7fc15be 100644
--- a/packages/widgets/src/options.ts
+++ b/packages/widgets/src/options.ts
@@ -3,10 +3,7 @@ import type { WidgetKind } from "@homarr/definitions";
import type { z } from "@homarr/validation";
import { widgetImports } from ".";
-import type {
- inferSelectOptionValue,
- SelectOption,
-} from "./_inputs/widget-select-input";
+import type { inferSelectOptionValue, SelectOption } from "./_inputs/widget-select-input";
interface CommonInput<TType> {
defaultValue?: TType;
@@ -57,21 +54,16 @@ const optionsFactory = {
withDescription: input?.withDescription ?? false,
validate: input?.validate,
}),
- multiSelect: <const TOptions extends SelectOption[]>(
- input: MultiSelectInput<TOptions>,
- ) => ({
+ multiSelect: <const TOptions extends SelectOption[]>(input: MultiSelectInput<TOptions>) => ({
type: "multiSelect" as const,
defaultValue: input.defaultValue ?? [],
options: input.options,
searchable: input.searchable ?? false,
withDescription: input.withDescription ?? false,
}),
- select: <const TOptions extends SelectOption[]>(
- input: SelectInput<TOptions>,
- ) => ({
+ select: <const TOptions extends SelectOption[]>(input: SelectInput<TOptions>) => ({
type: "select" as const,
- defaultValue: (input.defaultValue ??
- input.options[0]) as inferSelectOptionValue<TOptions[number]>,
+ defaultValue: (input.defaultValue ?? input.options[0]) as inferSelectOptionValue<TOptions[number]>,
options: input.options,
searchable: input.searchable ?? false,
withDescription: input.withDescription ?? false,
@@ -112,18 +104,12 @@ const optionsFactory = {
};
type WidgetOptionFactory = typeof optionsFactory;
-export type WidgetOptionDefinition = ReturnType<
- WidgetOptionFactory[keyof WidgetOptionFactory]
->;
+export type WidgetOptionDefinition = ReturnType<WidgetOptionFactory[keyof WidgetOptionFactory]>;
export type WidgetOptionsRecord = Record<string, WidgetOptionDefinition>;
export type WidgetOptionType = WidgetOptionDefinition["type"];
-export type WidgetOptionOfType<TType extends WidgetOptionType> = Extract<
- WidgetOptionDefinition,
- { type: TType }
->;
+export type WidgetOptionOfType<TType extends WidgetOptionType> = Extract<WidgetOptionDefinition, { type: TType }>;
-type inferOptionFromDefinition<TDefinition extends WidgetOptionDefinition> =
- TDefinition["defaultValue"];
+type inferOptionFromDefinition<TDefinition extends WidgetOptionDefinition> = TDefinition["defaultValue"];
export type inferOptionsFromDefinition<TOptions extends WidgetOptionsRecord> = {
[key in keyof TOptions]: inferOptionFromDefinition<TOptions[key]>;
};
@@ -162,10 +148,7 @@ export const optionsBuilder = {
from: createOptions,
};
-export const reduceWidgetOptionsWithDefaultValues = (
- kind: WidgetKind,
- currentValue: Record<string, unknown> = {},
-) => {
+export const reduceWidgetOptionsWithDefaultValues = (kind: WidgetKind, currentValue: Record<string, unknown> = {}) => {
const definition = widgetImports[kind].definition;
const options = definition.options as Record<string, WidgetOptionDefinition>;
return objectEntries(options).reduce(
diff --git a/packages/widgets/src/server/provider.tsx b/packages/widgets/src/server/provider.tsx
index 4516559e9..f2e745be0 100644
--- a/packages/widgets/src/server/provider.tsx
+++ b/packages/widgets/src/server/provider.tsx
@@ -12,31 +12,21 @@ type Data = Record<
>;
interface GlobalItemServerDataContext {
- setItemServerData: (
- id: string,
- data: Record<string, unknown> | undefined,
- ) => void;
+ setItemServerData: (id: string, data: Record<string, unknown> | undefined) => void;
data: Data;
initalItemIds: string[];
}
-const GlobalItemServerDataContext =
- createContext<GlobalItemServerDataContext | null>(null);
+const GlobalItemServerDataContext = createContext<GlobalItemServerDataContext | null>(null);
interface Props {
initalItemIds: string[];
}
-export const GlobalItemServerDataProvider = ({
- children,
- initalItemIds,
-}: PropsWithChildren<Props>) => {
+export const GlobalItemServerDataProvider = ({ children, initalItemIds }: PropsWithChildren<Props>) => {
const [data, setData] = useState<Data>({});
- const setItemServerData = (
- id: string,
- itemData: Record<string, unknown> | undefined,
- ) => {
+ const setItemServerData = (id: string, itemData: Record<string, unknown> | undefined) => {
setData((prev) => ({
...prev,
[id]: {
@@ -47,9 +37,7 @@ export const GlobalItemServerDataProvider = ({
};
return (
- <GlobalItemServerDataContext.Provider
- value={{ setItemServerData, data, initalItemIds }}
- >
+ <GlobalItemServerDataContext.Provider value={{ setItemServerData, data, initalItemIds }}>
{children}
</GlobalItemServerDataContext.Provider>
);
@@ -73,10 +61,7 @@ export const useServerDataFor = (id: string) => {
return context.data[id];
};
-export const useServerDataInitializer = (
- id: string,
- serverData: Record<string, unknown> | undefined,
-) => {
+export const useServerDataInitializer = (id: string, serverData: Record<string, unknown> | undefined) => {
const context = useContext(GlobalItemServerDataContext);
if (!context) {
diff --git a/packages/widgets/src/server/runner.tsx b/packages/widgets/src/server/runner.tsx
index 6c123d05b..63d588e86 100644
--- a/packages/widgets/src/server/runner.tsx
+++ b/packages/widgets/src/server/runner.tsx
@@ -14,11 +14,7 @@ type Props = PropsWithChildren<{
board: Board;
}>;
-export const GlobalItemServerDataRunner = ({
- board,
- shouldRun,
- children,
-}: Props) => {
+export const GlobalItemServerDataRunner = ({ board, shouldRun, children }: Props) => {
if (!shouldRun) return children;
const allItems = board.sections.flatMap((section) => section.items);
@@ -45,10 +41,7 @@ const ItemDataLoader = async ({ item }: ItemDataLoaderProps) => {
return <ClientServerDataInitalizer id={item.id} serverData={undefined} />;
}
const loader = await widgetImport.serverDataLoader();
- const optionsWithDefault = reduceWidgetOptionsWithDefaultValues(
- item.kind,
- item.options,
- );
+ const optionsWithDefault = reduceWidgetOptionsWithDefaultValues(item.kind, item.options);
const data = await loader.default({
...item,
options: optionsWithDefault as never,
diff --git a/packages/widgets/src/video/component.tsx b/packages/widgets/src/video/component.tsx
index e9b373bf7..8832d2390 100644
--- a/packages/widgets/src/video/component.tsx
+++ b/packages/widgets/src/video/component.tsx
@@ -13,9 +13,7 @@ import classes from "./component.module.css";
import "video.js/dist/video-js.css";
-export default function VideoWidget({
- options,
-}: WidgetComponentProps<"video">) {
+export default function VideoWidget({ options }: WidgetComponentProps<"video">) {
if (options.feedUrl.trim() === "") {
return <NoUrl />;
}
@@ -48,9 +46,7 @@ const ForYoutubeUseIframe = () => {
<Stack align="center" gap="xs">
<IconBrandYoutube />
<Title order={4}>{t("widget.video.error.forYoutubeUseIframe")}</Title>
- <Anchor href="https://homarr.dev/docs/widgets/iframe/">
- {t("common.action.checkoutDocs")}
- </Anchor>
+ <Anchor href="https://homarr.dev/docs/widgets/iframe/">{t("common.action.checkoutDocs")}</Anchor>
</Stack>
</Center>
);
@@ -80,10 +76,7 @@ const Feed = ({ options }: Pick<WidgetComponentProps<"video">, "options">) => {
return (
<Group justify="center" w="100%" h="100%" pos="relative">
- <video
- className={combineClasses("video-js", classes.video)}
- ref={videoRef}
- >
+ <video className={combineClasses("video-js", classes.video)} ref={videoRef}>
<source src={options.feedUrl} />
</video>
</Group>
diff --git a/packages/widgets/src/weather/component.tsx b/packages/widgets/src/weather/component.tsx
index f6c41a7c6..cbe2ad5f4 100644
--- a/packages/widgets/src/weather/component.tsx
+++ b/packages/widgets/src/weather/component.tsx
@@ -1,9 +1,5 @@
import { Card, Flex, Group, Stack, Text, Title } from "@mantine/core";
-import {
- IconArrowDownRight,
- IconArrowUpRight,
- IconMapPin,
-} from "@tabler/icons-react";
+import { IconArrowDownRight, IconArrowUpRight, IconMapPin } from "@tabler/icons-react";
import type { RouterOutputs } from "@homarr/api";
import { clientApi } from "@homarr/api/client";
@@ -11,10 +7,7 @@ import { clientApi } from "@homarr/api/client";
import type { WidgetComponentProps } from "../definition";
import { WeatherIcon } from "./icon";
-export default function WeatherWidget({
- options,
- width,
-}: WidgetComponentProps<"weather">) {
+export default function WeatherWidget({ options, width }: WidgetComponentProps<"weather">) {
const [weather] = clientApi.widget.weather.atLocation.useSuspenseQuery(
{
latitude: options.location.latitude,
@@ -29,34 +22,18 @@ export default function WeatherWidget({
return (
<Stack w="100%" h="100%" justify="space-around" gap={0} align="center">
- <WeeklyForecast
- weather={weather}
- width={width}
- options={options}
- shouldHide={!options.hasForecast}
- />
- <DailyWeather
- weather={weather}
- width={width}
- options={options}
- shouldHide={options.hasForecast}
- />
+ <WeeklyForecast weather={weather} width={width} options={options} shouldHide={!options.hasForecast} />
+ <DailyWeather weather={weather} width={width} options={options} shouldHide={options.hasForecast} />
</Stack>
);
}
-interface DailyWeatherProps
- extends Pick<WidgetComponentProps<"weather">, "width" | "options"> {
+interface DailyWeatherProps extends Pick<WidgetComponentProps<"weather">, "width" | "options"> {
shouldHide: boolean;
weather: RouterOutputs["widget"]["weather"]["atLocation"];
}
-const DailyWeather = ({
- shouldHide,
- width,
- options,
- weather,
-}: DailyWeatherProps) => {
+const DailyWeather = ({ shouldHide, width, options, weather }: DailyWeatherProps) => {
if (shouldHide) {
return null;
}
@@ -69,30 +46,16 @@ const DailyWeather = ({
justify={"center"}
direction={width < 200 ? "column" : "row"}
>
- <WeatherIcon
- size={width < 300 ? 30 : 50}
- code={weather.current_weather.weathercode}
- />
- <Title order={2}>
- {getPreferredUnit(
- weather.current_weather.temperature,
- options.isFormatFahrenheit,
- )}
- </Title>
+ <WeatherIcon size={width < 300 ? 30 : 50} code={weather.current_weather.weathercode} />
+ <Title order={2}>{getPreferredUnit(weather.current_weather.temperature, options.isFormatFahrenheit)}</Title>
</Flex>
{width > 200 && (
<Group wrap="nowrap" gap="xs">
<IconArrowUpRight />
- {getPreferredUnit(
- weather.daily.temperature_2m_max[0]!,
- options.isFormatFahrenheit,
- )}
+ {getPreferredUnit(weather.daily.temperature_2m_max[0]!, options.isFormatFahrenheit)}
<IconArrowDownRight />
- {getPreferredUnit(
- weather.daily.temperature_2m_min[0]!,
- options.isFormatFahrenheit,
- )}
+ {getPreferredUnit(weather.daily.temperature_2m_min[0]!, options.isFormatFahrenheit)}
</Group>
)}
@@ -106,30 +69,19 @@ const DailyWeather = ({
);
};
-interface WeeklyForecastProps
- extends Pick<WidgetComponentProps<"weather">, "width" | "options"> {
+interface WeeklyForecastProps extends Pick<WidgetComponentProps<"weather">, "width" | "options"> {
shouldHide: boolean;
weather: RouterOutputs["widget"]["weather"]["atLocation"];
}
-const WeeklyForecast = ({
- shouldHide,
- width,
- options,
- weather,
-}: WeeklyForecastProps) => {
+const WeeklyForecast = ({ shouldHide, width, options, weather }: WeeklyForecastProps) => {
if (shouldHide) {
return null;
}
return (
<>
- <Flex
- align="center"
- gap={width < 120 ? "0.25rem" : "xs"}
- justify="center"
- direction="row"
- >
+ <Flex align="center" gap={width < 120 ? "0.25rem" : "xs"} justify="center" direction="row">
{options.showCity && (
<Group wrap="nowrap" gap="xs" align="center">
<IconMapPin color="blue" size={30} />
@@ -138,18 +90,9 @@ const WeeklyForecast = ({
</Text>
</Group>
)}
- <WeatherIcon
- size={width < 300 ? 30 : 50}
- code={weather.current_weather.weathercode}
- />
- <Title
- order={2}
- c={weather.current_weather.temperature > 20 ? "red" : "blue"}
- >
- {getPreferredUnit(
- weather.current_weather.temperature,
- options.isFormatFahrenheit,
- )}
+ <WeatherIcon size={width < 300 ? 30 : 50} code={weather.current_weather.weathercode} />
+ <Title order={2} c={weather.current_weather.temperature > 20 ? "red" : "blue"}>
+ {getPreferredUnit(weather.current_weather.temperature, options.isFormatFahrenheit)}
</Title>
</Flex>
<Forecast weather={weather} options={options} width={width} />
@@ -157,8 +100,7 @@ const WeeklyForecast = ({
);
};
-interface ForecastProps
- extends Pick<WidgetComponentProps<"weather">, "options" | "width"> {
+interface ForecastProps extends Pick<WidgetComponentProps<"weather">, "options" | "width"> {
weather: RouterOutputs["widget"]["weather"]["atLocation"];
}
@@ -166,31 +108,19 @@ function Forecast({ weather, options, width }: ForecastProps) {
return (
<Flex align="center" direction="row" justify="space-between" w="100%">
{weather.daily.time
- .slice(
- 0,
- Math.min(options.forecastDayCount, width / (width < 300 ? 64 : 92)),
- )
+ .slice(0, Math.min(options.forecastDayCount, width / (width < 300 ? 64 : 92)))
.map((time, index) => (
<Card key={time}>
<Flex direction="column" align="center">
<Text fw={700} lh="1.25rem">
{new Date(time).getDate().toString().padStart(2, "0")}
</Text>
- <WeatherIcon
- size={width < 300 ? 20 : 50}
- code={weather.daily.weathercode[index]!}
- />
+ <WeatherIcon size={width < 300 ? 20 : 50} code={weather.daily.weathercode[index]!} />
<Text fz={width < 300 ? "xs" : "sm"} lh="1rem">
- {getPreferredUnit(
- weather.daily.temperature_2m_max[index]!,
- options.isFormatFahrenheit,
- )}
+ {getPreferredUnit(weather.daily.temperature_2m_max[index]!, options.isFormatFahrenheit)}
</Text>
<Text fz={width < 300 ? "xs" : "sm"} lh="1rem" c="grey">
- {getPreferredUnit(
- weather.daily.temperature_2m_min[index]!,
- options.isFormatFahrenheit,
- )}
+ {getPreferredUnit(weather.daily.temperature_2m_min[index]!, options.isFormatFahrenheit)}
</Text>
</Flex>
</Card>
@@ -200,6 +130,4 @@ function Forecast({ weather, options, width }: ForecastProps) {
}
const getPreferredUnit = (value: number, isFahrenheit = false): string =>
- isFahrenheit
- ? `${(value * (9 / 5) + 32).toFixed(1)}°F`
- : `${value.toFixed(1)}°C`;
+ isFahrenheit ? `${(value * (9 / 5) + 32).toFixed(1)}°F` : `${value.toFixed(1)}°C`;
diff --git a/packages/widgets/src/weather/icon.tsx b/packages/widgets/src/weather/icon.tsx
index 5c2839b8c..71d9dc87b 100644
--- a/packages/widgets/src/weather/icon.tsx
+++ b/packages/widgets/src/weather/icon.tsx
@@ -28,8 +28,7 @@ export const WeatherIcon = ({ code, size = 50 }: WeatherIconProps) => {
const t = useScopedI18n("widget.weather");
const { icon: Icon, name } =
- weatherDefinitions.find((definition) => definition.codes.includes(code)) ??
- unknownWeather;
+ weatherDefinitions.find((definition) => definition.codes.includes(code)) ?? unknownWeather;
return (
<Tooltip withinPortal withArrow label={t(`kind.${name}`)}>
diff --git a/packages/widgets/src/weather/index.ts b/packages/widgets/src/weather/index.ts
index 28805cc1e..e0db620dc 100644
--- a/packages/widgets/src/weather/index.ts
+++ b/packages/widgets/src/weather/index.ts
@@ -5,36 +5,33 @@ import { z } from "@homarr/validation";
import { createWidgetDefinition } from "../definition";
import { optionsBuilder } from "../options";
-export const { definition, componentLoader } = createWidgetDefinition(
- "weather",
- {
- icon: IconCloud,
- options: optionsBuilder.from(
- (factory) => ({
- isFormatFahrenheit: factory.switch(),
- location: factory.location({
- defaultValue: {
- name: "Paris",
- latitude: 48.85341,
- longitude: 2.3488,
- },
- }),
- showCity: factory.switch(),
- hasForecast: factory.switch(),
- forecastDayCount: factory.slider({
- defaultValue: 5,
- validate: z.number().min(1).max(7),
- step: 1,
- withDescription: true,
- }),
+export const { definition, componentLoader } = createWidgetDefinition("weather", {
+ icon: IconCloud,
+ options: optionsBuilder.from(
+ (factory) => ({
+ isFormatFahrenheit: factory.switch(),
+ location: factory.location({
+ defaultValue: {
+ name: "Paris",
+ latitude: 48.85341,
+ longitude: 2.3488,
+ },
+ }),
+ showCity: factory.switch(),
+ hasForecast: factory.switch(),
+ forecastDayCount: factory.slider({
+ defaultValue: 5,
+ validate: z.number().min(1).max(7),
+ step: 1,
+ withDescription: true,
}),
- {
- forecastDayCount: {
- shouldHide({ hasForecast }) {
- return !hasForecast;
- },
+ }),
+ {
+ forecastDayCount: {
+ shouldHide({ hasForecast }) {
+ return !hasForecast;
},
},
- ),
- },
-).withDynamicImport(() => import("./component"));
+ },
+ ),
+}).withDynamicImport(() => import("./component"));
diff --git a/packages/widgets/src/widget-integration-select.module.css b/packages/widgets/src/widget-integration-select.module.css
index 7e1da6c97..c3a912789 100644
--- a/packages/widgets/src/widget-integration-select.module.css
+++ b/packages/widgets/src/widget-integration-select.module.css
@@ -1,11 +1,7 @@
.pill {
cursor: default;
- background-color: light-dark(
- var(--mantine-color-white),
- var(--mantine-color-dark-7)
- );
- border: rem(1px) solid
- light-dark(var(--mantine-color-gray-4), var(--mantine-color-dark-7));
+ background-color: light-dark(var(--mantine-color-white), var(--mantine-color-dark-7));
+ border: rem(1px) solid light-dark(var(--mantine-color-gray-4), var(--mantine-color-dark-7));
padding-left: var(--mantine-spacing-xs);
border-radius: var(--mantine-radius-xl);
}
diff --git a/packages/widgets/src/widget-integration-select.tsx b/packages/widgets/src/widget-integration-select.tsx
index f59a0c9db..bb8ce11ef 100644
--- a/packages/widgets/src/widget-integration-select.tsx
+++ b/packages/widgets/src/widget-integration-select.tsx
@@ -65,11 +65,7 @@ export const WidgetIntegrationSelect = ({
const options = data.map((item) => {
return (
- <Combobox.Option
- value={item.id}
- key={item.id}
- active={multiSelectValues.includes(item.id)}
- >
+ <Combobox.Option value={item.id} key={item.id} active={multiSelectValues.includes(item.id)}>
<Group gap="sm" align="center">
{multiSelectValues.includes(item.id) ? <CheckIcon size={12} /> : null}
<Group gap={7} align="center">
@@ -87,25 +83,11 @@ export const WidgetIntegrationSelect = ({
});
return (
- <Combobox
- store={combobox}
- onOptionSubmit={handleValueSelect}
- withinPortal={false}
- >
+ <Combobox store={combobox} onOptionSubmit={handleValueSelect} withinPortal={false}>
<Combobox.DropdownTarget>
- <PillsInput
- pointer
- onClick={() => combobox.toggleDropdown()}
- {...props}
- >
+ <PillsInput pointer onClick={() => combobox.toggleDropdown()} {...props}>
<Pill.Group>
- {values.length > 0 ? (
- values
- ) : (
- <Input.Placeholder>
- {t("common.multiSelect.placeholder")}
- </Input.Placeholder>
- )}
+ {values.length > 0 ? values : <Input.Placeholder>{t("common.multiSelect.placeholder")}</Input.Placeholder>}
<Combobox.EventsTarget>
<PillsInput.Field
@@ -115,9 +97,7 @@ export const WidgetIntegrationSelect = ({
if (event.key !== "Backspace") return;
event.preventDefault();
- handleValueRemove(
- multiSelectValues[multiSelectValues.length - 1]!,
- );
+ handleValueRemove(multiSelectValues[multiSelectValues.length - 1]!);
}}
/>
</Combobox.EventsTarget>
@@ -150,13 +130,6 @@ const IntegrationPill = ({ option, onRemove }: IntegrationPillProps) => (
<Text span size="xs" lh={1} fw={500}>
{option.name}
</Text>
- <CloseButton
- onMouseDown={onRemove}
- variant="transparent"
- color="gray"
- size={22}
- iconSize={14}
- tabIndex={-1}
- />
+ <CloseButton onMouseDown={onRemove} variant="transparent" color="gray" size={22} iconSize={14} tabIndex={-1} />
</Group>
);
diff --git a/tooling/eslint/base.js b/tooling/eslint/base.js
index fe08052ed..bb154044f 100644
--- a/tooling/eslint/base.js
+++ b/tooling/eslint/base.js
@@ -27,18 +27,12 @@ const config = {
],
"@typescript-eslint/prefer-nullish-coalescing": "off",
"turbo/no-undeclared-env-vars": "off",
- "@typescript-eslint/no-unused-vars": [
- "error",
- { argsIgnorePattern: "^_", varsIgnorePattern: "^_" },
- ],
+ "@typescript-eslint/no-unused-vars": ["error", { argsIgnorePattern: "^_", varsIgnorePattern: "^_" }],
"@typescript-eslint/consistent-type-imports": [
"warn",
{ prefer: "type-imports", fixStyle: "separate-type-imports" },
],
- "@typescript-eslint/no-misused-promises": [
- 2,
- { checksVoidReturn: { attributes: false } },
- ],
+ "@typescript-eslint/no-misused-promises": [2, { checksVoidReturn: { attributes: false } }],
"import/consistent-type-specifier-style": ["error", "prefer-top-level"],
"no-restricted-syntax": [
"error",
@@ -49,8 +43,7 @@ const config = {
{
selector:
"FunctionDeclaration[async=true][id.name=/^[a-z].*$/][id.name=/ ^(?!generateMetadata$)[a-z].*$/][id.name!=/Async$/]",
- message:
- "Async function name must end in 'Async' (function declaration)",
+ message: "Async function name must end in 'Async' (function declaration)",
},
{
selector: "MethodDefinition[value.async=false][key.name=/Async$/]",
@@ -61,8 +54,7 @@ const config = {
message: "Async method name must end in 'Async'",
},
{
- selector:
- "Property[value.type=/FunctionExpression$/][value.async=false][key.name=/Async$/]",
+ selector: "Property[value.type=/FunctionExpression$/][value.async=false][key.name=/Async$/]",
message: "Function ending in 'Async' must be declared async",
},
{
@@ -71,26 +63,17 @@ const config = {
message: "Async function name must end in 'Async' (property)",
},
{
- selector:
- "VariableDeclarator[init.type=/FunctionExpression$/][init.async=false][id.name=/Async$/]",
+ selector: "VariableDeclarator[init.type=/FunctionExpression$/][init.async=false][id.name=/Async$/]",
message: "Function ending in 'Async' must be declared async",
},
{
selector:
"VariableDeclarator[init.type=/FunctionExpression$/][init.async=true][id.name=/^[a-z].*$/][id.name!=/Async$/]",
- message:
- "Async function name must end in 'Async' (variable declarator)",
+ message: "Async function name must end in 'Async' (variable declarator)",
},
],
},
- ignorePatterns: [
- "**/.eslintrc.cjs",
- "**/*.config.js",
- "**/*.config.cjs",
- ".next",
- "dist",
- "pnpm-lock.yaml",
- ],
+ ignorePatterns: ["**/.eslintrc.cjs", "**/*.config.js", "**/*.config.cjs", ".next", "dist", "pnpm-lock.yaml"],
reportUnusedDisableDirectives: true,
};
diff --git a/tooling/eslint/react.js b/tooling/eslint/react.js
index 618e1816f..ee21a219f 100644
--- a/tooling/eslint/react.js
+++ b/tooling/eslint/react.js
@@ -1,10 +1,6 @@
/** @type {import('eslint').Linter.Config} */
const config = {
- extends: [
- "plugin:react/recommended",
- "plugin:react-hooks/recommended",
- "plugin:jsx-a11y/recommended",
- ],
+ extends: ["plugin:react/recommended", "plugin:react-hooks/recommended", "plugin:jsx-a11y/recommended"],
rules: {
"react/prop-types": "off",
},
diff --git a/tooling/prettier/index.mjs b/tooling/prettier/index.mjs
index 252af72ad..bbda4c6b8 100644
--- a/tooling/prettier/index.mjs
+++ b/tooling/prettier/index.mjs
@@ -16,6 +16,7 @@ const config = {
"^[./]",
],
importOrderParserPlugins: ["typescript", "jsx", "decorators-legacy"],
+ printWidth: 120,
importOrderTypeScriptVersion: "4.4.0",
};